diff --git a/src/core/display/DisplayObject.js b/src/core/display/DisplayObject.js index 66ebc3c..20e778c 100644 --- a/src/core/display/DisplayObject.js +++ b/src/core/display/DisplayObject.js @@ -7,7 +7,8 @@ * @class * @namespace PIXI */ -function DisplayObject() { +function DisplayObject() +{ /** * The coordinate of the object relative to the local coordinates of the parent. * @@ -152,10 +153,12 @@ * @memberof DisplayObject# */ x: { - get: function () { + get: function () + { return this.position.x; }, - set: function (value) { + set: function (value) + { this.position.x = value; } }, @@ -167,10 +170,12 @@ * @memberof DisplayObject# */ y: { - get: function () { + get: function () + { return this.position.y; }, - set: function (value) { + set: function (value) + { this.position.y = value; } }, @@ -183,11 +188,13 @@ * @readonly */ worldVisible: { - get: function () { + get: function () + { var item = this; do { - if (!item.visible) { + if (!item.visible) + { return false; } @@ -207,17 +214,21 @@ * @memberof DisplayObject# */ mask: { - get: function () { + get: function () + { return this._mask; }, - set: function (value) { - if (this._mask) { + set: function (value) + { + if (this._mask) + { this._mask.isMask = false; } this._mask = value; - if (this._mask) { + if (this._mask) + { this._mask.isMask = true; } } @@ -232,18 +243,23 @@ * @memberof DisplayObject# */ filters: { - get: function () { + get: function () + { return this._filters; }, - set: function (value) { - if (value) { + set: function (value) + { + if (value) + { // now put all the passes in one place.. var passes = []; - for (var i = 0; i < value.length; i++) { + for (var i = 0; i < value.length; i++) + { var filterPasses = value[i].passes; - for (var j = 0; j < filterPasses.length; j++) { + for (var j = 0; j < filterPasses.length; j++) + { passes.push(filterPasses[j]); } } @@ -264,8 +280,9 @@ * * @private */ -DisplayObject.prototype.updateTransform = function () { - +DisplayObject.prototype.updateTransform = function () +{ + // create some matrix refs for easy access var pt = this.parent.worldTransform; var wt = this.worldTransform; @@ -274,9 +291,11 @@ var a, b, c, d, tx, ty; // so if rotation is between 0 then we can simplify the multiplication process.. - if (this.rotation % math.PI_2) { + if (this.rotation % math.PI_2) + { // 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) { + if (this.rotation !== this.rotationCache) + { this.rotationCache = this.rotation; this._sr = Math.sin(this.rotation); this._cr = Math.cos(this.rotation); @@ -291,7 +310,8 @@ ty = this.position.y; // check for pivot.. not often used so geared towards that fact! - if (this.pivot.x || this.pivot.y) { + 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; } @@ -304,7 +324,8 @@ wt.tx = tx * pt.a + ty * pt.c + pt.tx; wt.ty = tx * pt.b + ty * pt.d + pt.ty; } - else { + else + { // lets do the fast version as we know there is no rotation.. a = this.scale.x; d = this.scale.y; @@ -333,7 +354,8 @@ * @param matrix {Matrix} * @return {Rectangle} the rectangular bounding area */ -DisplayObject.prototype.getBounds = function (/* matrix */) { +DisplayObject.prototype.getBounds = function (/* matrix */) +{ return math.Rectangle.EMPTY; }; @@ -342,7 +364,8 @@ * * @return {Rectangle} the rectangular bounding area */ -DisplayObject.prototype.getLocalBounds = function () { +DisplayObject.prototype.getLocalBounds = function () +{ return this.getBounds(math.Matrix.IDENTITY); }; @@ -352,7 +375,8 @@ * @param position {Point} The world origin to calculate from * @return {Point} A point object representing the position of this object */ -DisplayObject.prototype.toGlobal = function (position) { +DisplayObject.prototype.toGlobal = function (position) +{ // don't need to u[date the lot this.displayObjectUpdateTransform(); return this.worldTransform.apply(position); @@ -365,8 +389,10 @@ * @param [from] {DisplayObject} The DisplayObject to calculate the global position from * @return {Point} A point object representing the position of this object */ -DisplayObject.prototype.toLocal = function (position, from) { - if (from) { +DisplayObject.prototype.toLocal = function (position, from) +{ + if (from) + { position = from.toGlobal(position); } @@ -381,7 +407,8 @@ * @param renderer {WebGLRenderer} The renderer * @private */ -DisplayObject.prototype.renderWebGL = function (/* renderer */) { +DisplayObject.prototype.renderWebGL = function (/* renderer */) +{ // OVERWRITE; }; @@ -391,6 +418,7 @@ * @param renderer {CanvasRenderer} The renderer * @private */ -DisplayObject.prototype.renderCanvas = function (/* renderer */) { +DisplayObject.prototype.renderCanvas = function (/* renderer */) +{ // OVERWRITE; }; diff --git a/src/core/display/DisplayObject.js b/src/core/display/DisplayObject.js index 66ebc3c..20e778c 100644 --- a/src/core/display/DisplayObject.js +++ b/src/core/display/DisplayObject.js @@ -7,7 +7,8 @@ * @class * @namespace PIXI */ -function DisplayObject() { +function DisplayObject() +{ /** * The coordinate of the object relative to the local coordinates of the parent. * @@ -152,10 +153,12 @@ * @memberof DisplayObject# */ x: { - get: function () { + get: function () + { return this.position.x; }, - set: function (value) { + set: function (value) + { this.position.x = value; } }, @@ -167,10 +170,12 @@ * @memberof DisplayObject# */ y: { - get: function () { + get: function () + { return this.position.y; }, - set: function (value) { + set: function (value) + { this.position.y = value; } }, @@ -183,11 +188,13 @@ * @readonly */ worldVisible: { - get: function () { + get: function () + { var item = this; do { - if (!item.visible) { + if (!item.visible) + { return false; } @@ -207,17 +214,21 @@ * @memberof DisplayObject# */ mask: { - get: function () { + get: function () + { return this._mask; }, - set: function (value) { - if (this._mask) { + set: function (value) + { + if (this._mask) + { this._mask.isMask = false; } this._mask = value; - if (this._mask) { + if (this._mask) + { this._mask.isMask = true; } } @@ -232,18 +243,23 @@ * @memberof DisplayObject# */ filters: { - get: function () { + get: function () + { return this._filters; }, - set: function (value) { - if (value) { + set: function (value) + { + if (value) + { // now put all the passes in one place.. var passes = []; - for (var i = 0; i < value.length; i++) { + for (var i = 0; i < value.length; i++) + { var filterPasses = value[i].passes; - for (var j = 0; j < filterPasses.length; j++) { + for (var j = 0; j < filterPasses.length; j++) + { passes.push(filterPasses[j]); } } @@ -264,8 +280,9 @@ * * @private */ -DisplayObject.prototype.updateTransform = function () { - +DisplayObject.prototype.updateTransform = function () +{ + // create some matrix refs for easy access var pt = this.parent.worldTransform; var wt = this.worldTransform; @@ -274,9 +291,11 @@ var a, b, c, d, tx, ty; // so if rotation is between 0 then we can simplify the multiplication process.. - if (this.rotation % math.PI_2) { + if (this.rotation % math.PI_2) + { // 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) { + if (this.rotation !== this.rotationCache) + { this.rotationCache = this.rotation; this._sr = Math.sin(this.rotation); this._cr = Math.cos(this.rotation); @@ -291,7 +310,8 @@ ty = this.position.y; // check for pivot.. not often used so geared towards that fact! - if (this.pivot.x || this.pivot.y) { + 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; } @@ -304,7 +324,8 @@ wt.tx = tx * pt.a + ty * pt.c + pt.tx; wt.ty = tx * pt.b + ty * pt.d + pt.ty; } - else { + else + { // lets do the fast version as we know there is no rotation.. a = this.scale.x; d = this.scale.y; @@ -333,7 +354,8 @@ * @param matrix {Matrix} * @return {Rectangle} the rectangular bounding area */ -DisplayObject.prototype.getBounds = function (/* matrix */) { +DisplayObject.prototype.getBounds = function (/* matrix */) +{ return math.Rectangle.EMPTY; }; @@ -342,7 +364,8 @@ * * @return {Rectangle} the rectangular bounding area */ -DisplayObject.prototype.getLocalBounds = function () { +DisplayObject.prototype.getLocalBounds = function () +{ return this.getBounds(math.Matrix.IDENTITY); }; @@ -352,7 +375,8 @@ * @param position {Point} The world origin to calculate from * @return {Point} A point object representing the position of this object */ -DisplayObject.prototype.toGlobal = function (position) { +DisplayObject.prototype.toGlobal = function (position) +{ // don't need to u[date the lot this.displayObjectUpdateTransform(); return this.worldTransform.apply(position); @@ -365,8 +389,10 @@ * @param [from] {DisplayObject} The DisplayObject to calculate the global position from * @return {Point} A point object representing the position of this object */ -DisplayObject.prototype.toLocal = function (position, from) { - if (from) { +DisplayObject.prototype.toLocal = function (position, from) +{ + if (from) + { position = from.toGlobal(position); } @@ -381,7 +407,8 @@ * @param renderer {WebGLRenderer} The renderer * @private */ -DisplayObject.prototype.renderWebGL = function (/* renderer */) { +DisplayObject.prototype.renderWebGL = function (/* renderer */) +{ // OVERWRITE; }; @@ -391,6 +418,7 @@ * @param renderer {CanvasRenderer} The renderer * @private */ -DisplayObject.prototype.renderCanvas = function (/* renderer */) { +DisplayObject.prototype.renderCanvas = function (/* renderer */) +{ // OVERWRITE; }; diff --git a/src/core/display/DisplayObjectContainer.js b/src/core/display/DisplayObjectContainer.js index 689f40b..4625ee8 100644 --- a/src/core/display/DisplayObjectContainer.js +++ b/src/core/display/DisplayObjectContainer.js @@ -12,7 +12,8 @@ * @extends DisplayObject * @namespace PIXI */ -function DisplayObjectContainer() { +function DisplayObjectContainer() +{ DisplayObject.call(this); /** @@ -47,17 +48,21 @@ * @memberof DisplayObjectContainer# */ width: { - get: function () { + get: function () + { return this.scale.x * this.getLocalBounds().width; }, - set: function (value) { + set: function (value) + { var width = this.getLocalBounds().width; - if(width !== 0) { + if(width !== 0) + { this.scale.x = value / width; } - else { + else + { this.scale.x = 1; } @@ -73,17 +78,21 @@ * @memberof DisplayObjectContainer# */ height: { - get: function () { + get: function () + { return this.scale.y * this.getLocalBounds().height; }, - set: function (value) { + set: function (value) + { var height = this.getLocalBounds().height; - if (height !== 0) { + if (height !== 0) + { this.scale.y = value / height ; } - else { + else + { this.scale.y = 1; } @@ -100,18 +109,23 @@ * @memberof DisplayObject# */ cacheAsBitmap: { - get: function () { + get: function () + { return this._cacheAsBitmap; }, - set: function (value) { - if (this._cacheAsBitmap === value) { + set: function (value) + { + if (this._cacheAsBitmap === value) + { return; } - if (value) { + if (value) + { this._generateCachedSprite(); } - else { + else + { this._destroyCachedSprite(); } @@ -126,7 +140,8 @@ * @param child {DisplayObject} The DisplayObject to add to the container * @return {DisplayObject} The child that was added. */ -DisplayObjectContainer.prototype.addChild = function (child) { +DisplayObjectContainer.prototype.addChild = function (child) +{ return this.addChildAt(child, this.children.length); }; @@ -137,14 +152,18 @@ * @param index {Number} The index to place the child in * @return {DisplayObject} The child that was added. */ -DisplayObjectContainer.prototype.addChildAt = function (child, index) { +DisplayObjectContainer.prototype.addChildAt = function (child, index) +{ // prevent adding self as child - if (child === this) { + if (child === this) + { return; } - if (index >= 0 && index <= this.children.length) { - if (child.parent) { + if (index >= 0 && index <= this.children.length) + { + if (child.parent) + { child.parent.removeChild(child); } @@ -154,7 +173,8 @@ return child; } - else { + else + { throw new Error(child + 'addChildAt: The index '+ index +' supplied is out of bounds ' + this.children.length); } }; @@ -165,15 +185,18 @@ * @param child {DisplayObject} * @param child2 {DisplayObject} */ -DisplayObjectContainer.prototype.swapChildren = function (child, child2) { - if (child === child2) { +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) { + if (index1 < 0 || index2 < 0) + { throw new Error('swapChildren: Both the supplied DisplayObjects must be a child of the caller.'); } @@ -187,10 +210,12 @@ * @param child {DisplayObject} The DisplayObject instance to identify * @return {Number} The index position of the child display object to identify */ -DisplayObjectContainer.prototype.getChildIndex = function (child) { +DisplayObjectContainer.prototype.getChildIndex = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { throw new Error('The supplied DisplayObject must be a child of the caller'); } @@ -203,8 +228,10 @@ * @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 */ -DisplayObjectContainer.prototype.setChildIndex = function (child, index) { - if (index < 0 || index >= this.children.length) { +DisplayObjectContainer.prototype.setChildIndex = function (child, index) +{ + if (index < 0 || index >= this.children.length) + { throw new Error('The supplied index is out of bounds'); } @@ -220,8 +247,10 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child at the given index, if any. */ -DisplayObjectContainer.prototype.getChildAt = function (index) { - if (index < 0 || index >= this.children.length) { +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'); } @@ -234,10 +263,12 @@ * @param child {DisplayObject} The DisplayObject to remove * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChild = function (child) { +DisplayObjectContainer.prototype.removeChild = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { return; } @@ -250,7 +281,8 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChildAt = function (index) { +DisplayObjectContainer.prototype.removeChildAt = function (index) +{ var child = this.getChildAt(index); child.parent = null; @@ -265,24 +297,29 @@ * @param beginIndex {Number} The beginning position. Default value is 0. * @param endIndex {Number} The ending position. Default value is size of the container. */ -DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) { +DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) +{ var begin = beginIndex || 0; var end = typeof endIndex === 'number' ? endIndex : this.children.length; var range = end - begin; - if (range > 0 && range <= end) { + if (range > 0 && range <= end) + { var removed = this.children.splice(begin, range); - for (var i = 0; i < removed.length; ++i) { + for (var i = 0; i < removed.length; ++i) + { removed[i].parent = null; } return removed; } - else if (range === 0 && this.children.length === 0) { + else if (range === 0 && this.children.length === 0) + { return []; } - else { + else + { throw new RangeError('removeChildren: numeric values are outside the acceptable range.'); } }; @@ -291,7 +328,8 @@ * Generates and updates the cached sprite for this object. * */ -DisplayObjectContainer.prototype.updateCachedSprite = function () { +DisplayObjectContainer.prototype.updateCachedSprite = function () +{ this._generateCachedSprite(); }; @@ -304,7 +342,8 @@ * @param renderer {CanvasRenderer|WebGLRenderer} The renderer used to generate the texture. * @return {Texture} a texture of the graphics object */ -DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) { +DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) +{ var bounds = this.getLocalBounds(); var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0, renderer, scaleMode, resolution); @@ -322,18 +361,22 @@ * * @private */ -DisplayObjectContainer.prototype.updateTransform = function () { - if (!this.visible) { +DisplayObjectContainer.prototype.updateTransform = function () +{ + if (!this.visible) + { return; } this.displayObjectUpdateTransform(); - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { return; } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } }; @@ -346,8 +389,10 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getBounds = function () { - if (this.children.length === 0) { +DisplayObjectContainer.prototype.getBounds = function () +{ + if (this.children.length === 0) + { return math.Rectangle.EMPTY; } @@ -365,10 +410,12 @@ var childVisible = false; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -386,7 +433,8 @@ maxY = maxY > childMaxY ? maxY : childMaxY; } - if (!childVisible) { + if (!childVisible) + { return math.Rectangle.EMPTY; } @@ -407,12 +455,14 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getLocalBounds = function () { +DisplayObjectContainer.prototype.getLocalBounds = function () +{ var matrixCache = this.worldTransform; this.worldTransform = math.Matrix.IDENTITY; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } @@ -428,13 +478,16 @@ * * @param renderer {WebGLRenderer} The renderer */ -DisplayObjectContainer.prototype.renderWebGL = function (renderer) { +DisplayObjectContainer.prototype.renderWebGL = function (renderer) +{ // if the object is not visible or the alpha is 0 then no need to render this element - if (!this.visible || this.alpha <= 0) { + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } @@ -442,14 +495,17 @@ var i, j; // do a quick check to see if this element has a mask or a filter. - if (this._mask || this._filters) { + if (this._mask || this._filters) + { // push filter first as we need to ensure the stencil buffer is correct for any masking - if (this._filters) { + if (this._filters) + { renderer.spriteBatch.flush(); renderer.filterManager.pushFilter(this._filterBlock); } - if (this._mask) { + if (this._mask) + { renderer.spriteBatch.stop(); renderer.maskManager.pushMask(this.mask, renderer); renderer.spriteBatch.start(); @@ -459,36 +515,42 @@ this._renderWebGL(renderer); // now loop through the children and make sure they get rendered - for (i = 0, j = this.children.length; i < j; i++) { + for (i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderWebGL(renderer); } // time to stop the sprite batch as either a mask element or a filter draw will happen next renderer.spriteBatch.stop(); - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(this._mask, renderer); } - if (this._filters) { + if (this._filters) + { renderer.filterManager.popFilter(); } renderer.spriteBatch.start(); } - else { + else + { this._renderWebGL(renderer); // simple render children! - for (i = 0, j = this.children.length; i < j; ++i) { + for (i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderWebGL(renderer); } } }; -DisplayObjectContainer.prototype._renderWebGL = function (renderer) { +DisplayObjectContainer.prototype._renderWebGL = function (renderer) +{ // this is where content itself gets renderd.. @@ -499,25 +561,31 @@ * * @param renderer {CanvasRenderer} The renderer */ -DisplayObjectContainer.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0) { +DisplayObjectContainer.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -528,13 +596,16 @@ * @param renderer {WebGLRenderer|CanvasRenderer} The renderer * @private */ -DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) { +DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) +{ this._cachedSprite.worldAlpha = this.worldAlpha; - if (renderer.gl) { + if (renderer.gl) + { this._cachedSprite.renderWebGL(renderer); } - else { + else + { this._cachedSprite.renderCanvas(renderer); } }; @@ -544,10 +615,12 @@ * * @private */ -DisplayObjectContainer.prototype._generateCachedSprite = function () { +DisplayObjectContainer.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { // TODO - RenderTexture now *requires* a renderer instance, so this is like broken // because `renderer` isn't actually in scope here :P var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0); @@ -555,7 +628,8 @@ this._cachedSprite = new Sprite(renderTexture); this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.texture.resize(bounds.width | 0, bounds.height | 0); } @@ -580,8 +654,10 @@ * * @private */ -DisplayObjectContainer.prototype._destroyCachedSprite = function () { - if (!this._cachedSprite) { +DisplayObjectContainer.prototype._destroyCachedSprite = function () +{ + if (!this._cachedSprite) + { return; } diff --git a/src/core/display/DisplayObject.js b/src/core/display/DisplayObject.js index 66ebc3c..20e778c 100644 --- a/src/core/display/DisplayObject.js +++ b/src/core/display/DisplayObject.js @@ -7,7 +7,8 @@ * @class * @namespace PIXI */ -function DisplayObject() { +function DisplayObject() +{ /** * The coordinate of the object relative to the local coordinates of the parent. * @@ -152,10 +153,12 @@ * @memberof DisplayObject# */ x: { - get: function () { + get: function () + { return this.position.x; }, - set: function (value) { + set: function (value) + { this.position.x = value; } }, @@ -167,10 +170,12 @@ * @memberof DisplayObject# */ y: { - get: function () { + get: function () + { return this.position.y; }, - set: function (value) { + set: function (value) + { this.position.y = value; } }, @@ -183,11 +188,13 @@ * @readonly */ worldVisible: { - get: function () { + get: function () + { var item = this; do { - if (!item.visible) { + if (!item.visible) + { return false; } @@ -207,17 +214,21 @@ * @memberof DisplayObject# */ mask: { - get: function () { + get: function () + { return this._mask; }, - set: function (value) { - if (this._mask) { + set: function (value) + { + if (this._mask) + { this._mask.isMask = false; } this._mask = value; - if (this._mask) { + if (this._mask) + { this._mask.isMask = true; } } @@ -232,18 +243,23 @@ * @memberof DisplayObject# */ filters: { - get: function () { + get: function () + { return this._filters; }, - set: function (value) { - if (value) { + set: function (value) + { + if (value) + { // now put all the passes in one place.. var passes = []; - for (var i = 0; i < value.length; i++) { + for (var i = 0; i < value.length; i++) + { var filterPasses = value[i].passes; - for (var j = 0; j < filterPasses.length; j++) { + for (var j = 0; j < filterPasses.length; j++) + { passes.push(filterPasses[j]); } } @@ -264,8 +280,9 @@ * * @private */ -DisplayObject.prototype.updateTransform = function () { - +DisplayObject.prototype.updateTransform = function () +{ + // create some matrix refs for easy access var pt = this.parent.worldTransform; var wt = this.worldTransform; @@ -274,9 +291,11 @@ var a, b, c, d, tx, ty; // so if rotation is between 0 then we can simplify the multiplication process.. - if (this.rotation % math.PI_2) { + if (this.rotation % math.PI_2) + { // 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) { + if (this.rotation !== this.rotationCache) + { this.rotationCache = this.rotation; this._sr = Math.sin(this.rotation); this._cr = Math.cos(this.rotation); @@ -291,7 +310,8 @@ ty = this.position.y; // check for pivot.. not often used so geared towards that fact! - if (this.pivot.x || this.pivot.y) { + 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; } @@ -304,7 +324,8 @@ wt.tx = tx * pt.a + ty * pt.c + pt.tx; wt.ty = tx * pt.b + ty * pt.d + pt.ty; } - else { + else + { // lets do the fast version as we know there is no rotation.. a = this.scale.x; d = this.scale.y; @@ -333,7 +354,8 @@ * @param matrix {Matrix} * @return {Rectangle} the rectangular bounding area */ -DisplayObject.prototype.getBounds = function (/* matrix */) { +DisplayObject.prototype.getBounds = function (/* matrix */) +{ return math.Rectangle.EMPTY; }; @@ -342,7 +364,8 @@ * * @return {Rectangle} the rectangular bounding area */ -DisplayObject.prototype.getLocalBounds = function () { +DisplayObject.prototype.getLocalBounds = function () +{ return this.getBounds(math.Matrix.IDENTITY); }; @@ -352,7 +375,8 @@ * @param position {Point} The world origin to calculate from * @return {Point} A point object representing the position of this object */ -DisplayObject.prototype.toGlobal = function (position) { +DisplayObject.prototype.toGlobal = function (position) +{ // don't need to u[date the lot this.displayObjectUpdateTransform(); return this.worldTransform.apply(position); @@ -365,8 +389,10 @@ * @param [from] {DisplayObject} The DisplayObject to calculate the global position from * @return {Point} A point object representing the position of this object */ -DisplayObject.prototype.toLocal = function (position, from) { - if (from) { +DisplayObject.prototype.toLocal = function (position, from) +{ + if (from) + { position = from.toGlobal(position); } @@ -381,7 +407,8 @@ * @param renderer {WebGLRenderer} The renderer * @private */ -DisplayObject.prototype.renderWebGL = function (/* renderer */) { +DisplayObject.prototype.renderWebGL = function (/* renderer */) +{ // OVERWRITE; }; @@ -391,6 +418,7 @@ * @param renderer {CanvasRenderer} The renderer * @private */ -DisplayObject.prototype.renderCanvas = function (/* renderer */) { +DisplayObject.prototype.renderCanvas = function (/* renderer */) +{ // OVERWRITE; }; diff --git a/src/core/display/DisplayObjectContainer.js b/src/core/display/DisplayObjectContainer.js index 689f40b..4625ee8 100644 --- a/src/core/display/DisplayObjectContainer.js +++ b/src/core/display/DisplayObjectContainer.js @@ -12,7 +12,8 @@ * @extends DisplayObject * @namespace PIXI */ -function DisplayObjectContainer() { +function DisplayObjectContainer() +{ DisplayObject.call(this); /** @@ -47,17 +48,21 @@ * @memberof DisplayObjectContainer# */ width: { - get: function () { + get: function () + { return this.scale.x * this.getLocalBounds().width; }, - set: function (value) { + set: function (value) + { var width = this.getLocalBounds().width; - if(width !== 0) { + if(width !== 0) + { this.scale.x = value / width; } - else { + else + { this.scale.x = 1; } @@ -73,17 +78,21 @@ * @memberof DisplayObjectContainer# */ height: { - get: function () { + get: function () + { return this.scale.y * this.getLocalBounds().height; }, - set: function (value) { + set: function (value) + { var height = this.getLocalBounds().height; - if (height !== 0) { + if (height !== 0) + { this.scale.y = value / height ; } - else { + else + { this.scale.y = 1; } @@ -100,18 +109,23 @@ * @memberof DisplayObject# */ cacheAsBitmap: { - get: function () { + get: function () + { return this._cacheAsBitmap; }, - set: function (value) { - if (this._cacheAsBitmap === value) { + set: function (value) + { + if (this._cacheAsBitmap === value) + { return; } - if (value) { + if (value) + { this._generateCachedSprite(); } - else { + else + { this._destroyCachedSprite(); } @@ -126,7 +140,8 @@ * @param child {DisplayObject} The DisplayObject to add to the container * @return {DisplayObject} The child that was added. */ -DisplayObjectContainer.prototype.addChild = function (child) { +DisplayObjectContainer.prototype.addChild = function (child) +{ return this.addChildAt(child, this.children.length); }; @@ -137,14 +152,18 @@ * @param index {Number} The index to place the child in * @return {DisplayObject} The child that was added. */ -DisplayObjectContainer.prototype.addChildAt = function (child, index) { +DisplayObjectContainer.prototype.addChildAt = function (child, index) +{ // prevent adding self as child - if (child === this) { + if (child === this) + { return; } - if (index >= 0 && index <= this.children.length) { - if (child.parent) { + if (index >= 0 && index <= this.children.length) + { + if (child.parent) + { child.parent.removeChild(child); } @@ -154,7 +173,8 @@ return child; } - else { + else + { throw new Error(child + 'addChildAt: The index '+ index +' supplied is out of bounds ' + this.children.length); } }; @@ -165,15 +185,18 @@ * @param child {DisplayObject} * @param child2 {DisplayObject} */ -DisplayObjectContainer.prototype.swapChildren = function (child, child2) { - if (child === child2) { +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) { + if (index1 < 0 || index2 < 0) + { throw new Error('swapChildren: Both the supplied DisplayObjects must be a child of the caller.'); } @@ -187,10 +210,12 @@ * @param child {DisplayObject} The DisplayObject instance to identify * @return {Number} The index position of the child display object to identify */ -DisplayObjectContainer.prototype.getChildIndex = function (child) { +DisplayObjectContainer.prototype.getChildIndex = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { throw new Error('The supplied DisplayObject must be a child of the caller'); } @@ -203,8 +228,10 @@ * @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 */ -DisplayObjectContainer.prototype.setChildIndex = function (child, index) { - if (index < 0 || index >= this.children.length) { +DisplayObjectContainer.prototype.setChildIndex = function (child, index) +{ + if (index < 0 || index >= this.children.length) + { throw new Error('The supplied index is out of bounds'); } @@ -220,8 +247,10 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child at the given index, if any. */ -DisplayObjectContainer.prototype.getChildAt = function (index) { - if (index < 0 || index >= this.children.length) { +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'); } @@ -234,10 +263,12 @@ * @param child {DisplayObject} The DisplayObject to remove * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChild = function (child) { +DisplayObjectContainer.prototype.removeChild = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { return; } @@ -250,7 +281,8 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChildAt = function (index) { +DisplayObjectContainer.prototype.removeChildAt = function (index) +{ var child = this.getChildAt(index); child.parent = null; @@ -265,24 +297,29 @@ * @param beginIndex {Number} The beginning position. Default value is 0. * @param endIndex {Number} The ending position. Default value is size of the container. */ -DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) { +DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) +{ var begin = beginIndex || 0; var end = typeof endIndex === 'number' ? endIndex : this.children.length; var range = end - begin; - if (range > 0 && range <= end) { + if (range > 0 && range <= end) + { var removed = this.children.splice(begin, range); - for (var i = 0; i < removed.length; ++i) { + for (var i = 0; i < removed.length; ++i) + { removed[i].parent = null; } return removed; } - else if (range === 0 && this.children.length === 0) { + else if (range === 0 && this.children.length === 0) + { return []; } - else { + else + { throw new RangeError('removeChildren: numeric values are outside the acceptable range.'); } }; @@ -291,7 +328,8 @@ * Generates and updates the cached sprite for this object. * */ -DisplayObjectContainer.prototype.updateCachedSprite = function () { +DisplayObjectContainer.prototype.updateCachedSprite = function () +{ this._generateCachedSprite(); }; @@ -304,7 +342,8 @@ * @param renderer {CanvasRenderer|WebGLRenderer} The renderer used to generate the texture. * @return {Texture} a texture of the graphics object */ -DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) { +DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) +{ var bounds = this.getLocalBounds(); var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0, renderer, scaleMode, resolution); @@ -322,18 +361,22 @@ * * @private */ -DisplayObjectContainer.prototype.updateTransform = function () { - if (!this.visible) { +DisplayObjectContainer.prototype.updateTransform = function () +{ + if (!this.visible) + { return; } this.displayObjectUpdateTransform(); - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { return; } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } }; @@ -346,8 +389,10 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getBounds = function () { - if (this.children.length === 0) { +DisplayObjectContainer.prototype.getBounds = function () +{ + if (this.children.length === 0) + { return math.Rectangle.EMPTY; } @@ -365,10 +410,12 @@ var childVisible = false; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -386,7 +433,8 @@ maxY = maxY > childMaxY ? maxY : childMaxY; } - if (!childVisible) { + if (!childVisible) + { return math.Rectangle.EMPTY; } @@ -407,12 +455,14 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getLocalBounds = function () { +DisplayObjectContainer.prototype.getLocalBounds = function () +{ var matrixCache = this.worldTransform; this.worldTransform = math.Matrix.IDENTITY; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } @@ -428,13 +478,16 @@ * * @param renderer {WebGLRenderer} The renderer */ -DisplayObjectContainer.prototype.renderWebGL = function (renderer) { +DisplayObjectContainer.prototype.renderWebGL = function (renderer) +{ // if the object is not visible or the alpha is 0 then no need to render this element - if (!this.visible || this.alpha <= 0) { + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } @@ -442,14 +495,17 @@ var i, j; // do a quick check to see if this element has a mask or a filter. - if (this._mask || this._filters) { + if (this._mask || this._filters) + { // push filter first as we need to ensure the stencil buffer is correct for any masking - if (this._filters) { + if (this._filters) + { renderer.spriteBatch.flush(); renderer.filterManager.pushFilter(this._filterBlock); } - if (this._mask) { + if (this._mask) + { renderer.spriteBatch.stop(); renderer.maskManager.pushMask(this.mask, renderer); renderer.spriteBatch.start(); @@ -459,36 +515,42 @@ this._renderWebGL(renderer); // now loop through the children and make sure they get rendered - for (i = 0, j = this.children.length; i < j; i++) { + for (i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderWebGL(renderer); } // time to stop the sprite batch as either a mask element or a filter draw will happen next renderer.spriteBatch.stop(); - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(this._mask, renderer); } - if (this._filters) { + if (this._filters) + { renderer.filterManager.popFilter(); } renderer.spriteBatch.start(); } - else { + else + { this._renderWebGL(renderer); // simple render children! - for (i = 0, j = this.children.length; i < j; ++i) { + for (i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderWebGL(renderer); } } }; -DisplayObjectContainer.prototype._renderWebGL = function (renderer) { +DisplayObjectContainer.prototype._renderWebGL = function (renderer) +{ // this is where content itself gets renderd.. @@ -499,25 +561,31 @@ * * @param renderer {CanvasRenderer} The renderer */ -DisplayObjectContainer.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0) { +DisplayObjectContainer.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -528,13 +596,16 @@ * @param renderer {WebGLRenderer|CanvasRenderer} The renderer * @private */ -DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) { +DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) +{ this._cachedSprite.worldAlpha = this.worldAlpha; - if (renderer.gl) { + if (renderer.gl) + { this._cachedSprite.renderWebGL(renderer); } - else { + else + { this._cachedSprite.renderCanvas(renderer); } }; @@ -544,10 +615,12 @@ * * @private */ -DisplayObjectContainer.prototype._generateCachedSprite = function () { +DisplayObjectContainer.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { // TODO - RenderTexture now *requires* a renderer instance, so this is like broken // because `renderer` isn't actually in scope here :P var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0); @@ -555,7 +628,8 @@ this._cachedSprite = new Sprite(renderTexture); this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.texture.resize(bounds.width | 0, bounds.height | 0); } @@ -580,8 +654,10 @@ * * @private */ -DisplayObjectContainer.prototype._destroyCachedSprite = function () { - if (!this._cachedSprite) { +DisplayObjectContainer.prototype._destroyCachedSprite = function () +{ + if (!this._cachedSprite) + { return; } diff --git a/src/core/display/Sprite.js b/src/core/display/Sprite.js index 707da24..5862aef 100644 --- a/src/core/display/Sprite.js +++ b/src/core/display/Sprite.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param texture {Texture} The texture for this sprite */ -function Sprite(texture) { +function Sprite(texture) +{ DisplayObjectContainer.call(this); /** @@ -85,12 +86,14 @@ this.texture = texture || Texture.EMPTY; } -Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) { +Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) +{ DisplayObjectContainer.prototype.destroy.call(this); this.anchor = null; - if (destroyTexture) { + if (destroyTexture) + { this._texture.destroy(destroyBaseTexture); } @@ -111,10 +114,12 @@ * @memberof Sprite# */ width: { - get: function () { + get: function () + { return this.scale.x * this.texture.frame.width; }, - set: function (value) { + set: function (value) + { this.scale.x = value / this.texture.frame.width; this._width = value; } @@ -127,10 +132,12 @@ * @memberof Sprite# */ height: { - get: function () { + get: function () + { return this.scale.y * this.texture.frame.height; }, - set: function (value) { + set: function (value) + { this.scale.y = value / this.texture.frame.height; this._height = value; } @@ -143,23 +150,29 @@ * @memberof Sprite# */ texture: { - get: function () { + get: function () + { return this._texture; }, - set: function (value) { - if (this._texture === value) { + set: function (value) + { + if (this._texture === value) + { return; } this._texture = value; this.cachedTint = 0xFFFFFF; - if (value) { + if (value) + { // wait for the texture to load - if (value.baseTexture.hasLoaded) { + if (value.baseTexture.hasLoaded) + { this._onTextureUpdate(); } - else { + else + { value.once('update', this._onTextureUpdate.bind(this)); } } @@ -172,18 +185,22 @@ * * @private */ -Sprite.prototype._onTextureUpdate = function () { +Sprite.prototype._onTextureUpdate = function () +{ // so if _width is 0 then width was not set.. - if (this._width) { + if (this._width) + { this.scale.x = this._width / this.texture.frame.width; } - if (this._height) { + if (this._height) + { this.scale.y = this._height / this.texture.frame.height; } }; -Sprite.prototype._renderWebGL = function (renderer) { +Sprite.prototype._renderWebGL = function (renderer) +{ // this is where content gets renderd.. // watch this space for a little render state manager.. @@ -197,7 +214,8 @@ * @param matrix {Matrix} the transformation matrix of the sprite * @return {Rectangle} the framing rectangle */ -Sprite.prototype.getBounds = function (matrix) { +Sprite.prototype.getBounds = function (matrix) +{ var width = this.texture.frame.width; var height = this.texture.frame.height; @@ -224,11 +242,13 @@ if(b === 0 && c === 0) { // scale may be negative! - if (a < 0) { + if (a < 0) + { a *= -1; } - if (d < 0) { + if (d < 0) + { d *= -1; } @@ -293,28 +313,34 @@ * * @param renderer {CanvasRenderer} The renderer */ -Sprite.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) { +Sprite.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) + { return; } - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; renderer.context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } // Ignore null sources - if (this.texture.valid) { + if (this.texture.valid) + { var resolution = this.texture.baseTexture.resolution / renderer.resolution; renderer.context.globalAlpha = this.worldAlpha; // If smoothingEnabled is supported and we need to change the smoothing property for this texture - if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) { + if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) + { renderer.scaleMode = this.texture.baseTexture.scaleMode; renderer.context[renderer.smoothProperty] = (renderer.scaleMode === CONST.scaleModes.LINEAR); } @@ -324,7 +350,8 @@ var dy = (this.texture.trim ? this.texture.trim.y : 0) - (this.anchor.y * this.texture.trim.height); // Allow for pixel rounding - if (renderer.roundPixels) { + if (renderer.roundPixels) + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -337,7 +364,8 @@ dx = dx | 0; dy = dy | 0; } - else { + else + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -348,8 +376,10 @@ ); } - if (this.tint !== 0xFFFFFF) { - if (this.cachedTint !== this.tint) { + if (this.tint !== 0xFFFFFF) + { + if (this.cachedTint !== this.tint) + { this.cachedTint = this.tint; // TODO clean up caching - how to clean up the caches? @@ -368,7 +398,8 @@ this.texture.crop.height / resolution ); } - else { + else + { renderer.context.drawImage( this.texture.baseTexture.source, this.texture.crop.x, @@ -383,11 +414,13 @@ } } - for (var i = 0, j = this.children.length; i < j; i++) { + for (var i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -402,10 +435,12 @@ * @param frameId {String} The frame Id of the texture in the cache * @return {Sprite} A new Sprite using a texture from the texture cache matching the frameId */ -Sprite.fromFrame = function (frameId) { +Sprite.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache' + this); } @@ -420,6 +455,7 @@ * @param imageId {String} The image url of the texture * @return {Sprite} A new Sprite using a texture from the texture cache matching the image id */ -Sprite.fromImage = function (imageId, crossorigin, scaleMode) { +Sprite.fromImage = function (imageId, crossorigin, scaleMode) +{ return new Sprite(Texture.fromImage(imageId, crossorigin, scaleMode)); }; diff --git a/src/core/display/DisplayObject.js b/src/core/display/DisplayObject.js index 66ebc3c..20e778c 100644 --- a/src/core/display/DisplayObject.js +++ b/src/core/display/DisplayObject.js @@ -7,7 +7,8 @@ * @class * @namespace PIXI */ -function DisplayObject() { +function DisplayObject() +{ /** * The coordinate of the object relative to the local coordinates of the parent. * @@ -152,10 +153,12 @@ * @memberof DisplayObject# */ x: { - get: function () { + get: function () + { return this.position.x; }, - set: function (value) { + set: function (value) + { this.position.x = value; } }, @@ -167,10 +170,12 @@ * @memberof DisplayObject# */ y: { - get: function () { + get: function () + { return this.position.y; }, - set: function (value) { + set: function (value) + { this.position.y = value; } }, @@ -183,11 +188,13 @@ * @readonly */ worldVisible: { - get: function () { + get: function () + { var item = this; do { - if (!item.visible) { + if (!item.visible) + { return false; } @@ -207,17 +214,21 @@ * @memberof DisplayObject# */ mask: { - get: function () { + get: function () + { return this._mask; }, - set: function (value) { - if (this._mask) { + set: function (value) + { + if (this._mask) + { this._mask.isMask = false; } this._mask = value; - if (this._mask) { + if (this._mask) + { this._mask.isMask = true; } } @@ -232,18 +243,23 @@ * @memberof DisplayObject# */ filters: { - get: function () { + get: function () + { return this._filters; }, - set: function (value) { - if (value) { + set: function (value) + { + if (value) + { // now put all the passes in one place.. var passes = []; - for (var i = 0; i < value.length; i++) { + for (var i = 0; i < value.length; i++) + { var filterPasses = value[i].passes; - for (var j = 0; j < filterPasses.length; j++) { + for (var j = 0; j < filterPasses.length; j++) + { passes.push(filterPasses[j]); } } @@ -264,8 +280,9 @@ * * @private */ -DisplayObject.prototype.updateTransform = function () { - +DisplayObject.prototype.updateTransform = function () +{ + // create some matrix refs for easy access var pt = this.parent.worldTransform; var wt = this.worldTransform; @@ -274,9 +291,11 @@ var a, b, c, d, tx, ty; // so if rotation is between 0 then we can simplify the multiplication process.. - if (this.rotation % math.PI_2) { + if (this.rotation % math.PI_2) + { // 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) { + if (this.rotation !== this.rotationCache) + { this.rotationCache = this.rotation; this._sr = Math.sin(this.rotation); this._cr = Math.cos(this.rotation); @@ -291,7 +310,8 @@ ty = this.position.y; // check for pivot.. not often used so geared towards that fact! - if (this.pivot.x || this.pivot.y) { + 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; } @@ -304,7 +324,8 @@ wt.tx = tx * pt.a + ty * pt.c + pt.tx; wt.ty = tx * pt.b + ty * pt.d + pt.ty; } - else { + else + { // lets do the fast version as we know there is no rotation.. a = this.scale.x; d = this.scale.y; @@ -333,7 +354,8 @@ * @param matrix {Matrix} * @return {Rectangle} the rectangular bounding area */ -DisplayObject.prototype.getBounds = function (/* matrix */) { +DisplayObject.prototype.getBounds = function (/* matrix */) +{ return math.Rectangle.EMPTY; }; @@ -342,7 +364,8 @@ * * @return {Rectangle} the rectangular bounding area */ -DisplayObject.prototype.getLocalBounds = function () { +DisplayObject.prototype.getLocalBounds = function () +{ return this.getBounds(math.Matrix.IDENTITY); }; @@ -352,7 +375,8 @@ * @param position {Point} The world origin to calculate from * @return {Point} A point object representing the position of this object */ -DisplayObject.prototype.toGlobal = function (position) { +DisplayObject.prototype.toGlobal = function (position) +{ // don't need to u[date the lot this.displayObjectUpdateTransform(); return this.worldTransform.apply(position); @@ -365,8 +389,10 @@ * @param [from] {DisplayObject} The DisplayObject to calculate the global position from * @return {Point} A point object representing the position of this object */ -DisplayObject.prototype.toLocal = function (position, from) { - if (from) { +DisplayObject.prototype.toLocal = function (position, from) +{ + if (from) + { position = from.toGlobal(position); } @@ -381,7 +407,8 @@ * @param renderer {WebGLRenderer} The renderer * @private */ -DisplayObject.prototype.renderWebGL = function (/* renderer */) { +DisplayObject.prototype.renderWebGL = function (/* renderer */) +{ // OVERWRITE; }; @@ -391,6 +418,7 @@ * @param renderer {CanvasRenderer} The renderer * @private */ -DisplayObject.prototype.renderCanvas = function (/* renderer */) { +DisplayObject.prototype.renderCanvas = function (/* renderer */) +{ // OVERWRITE; }; diff --git a/src/core/display/DisplayObjectContainer.js b/src/core/display/DisplayObjectContainer.js index 689f40b..4625ee8 100644 --- a/src/core/display/DisplayObjectContainer.js +++ b/src/core/display/DisplayObjectContainer.js @@ -12,7 +12,8 @@ * @extends DisplayObject * @namespace PIXI */ -function DisplayObjectContainer() { +function DisplayObjectContainer() +{ DisplayObject.call(this); /** @@ -47,17 +48,21 @@ * @memberof DisplayObjectContainer# */ width: { - get: function () { + get: function () + { return this.scale.x * this.getLocalBounds().width; }, - set: function (value) { + set: function (value) + { var width = this.getLocalBounds().width; - if(width !== 0) { + if(width !== 0) + { this.scale.x = value / width; } - else { + else + { this.scale.x = 1; } @@ -73,17 +78,21 @@ * @memberof DisplayObjectContainer# */ height: { - get: function () { + get: function () + { return this.scale.y * this.getLocalBounds().height; }, - set: function (value) { + set: function (value) + { var height = this.getLocalBounds().height; - if (height !== 0) { + if (height !== 0) + { this.scale.y = value / height ; } - else { + else + { this.scale.y = 1; } @@ -100,18 +109,23 @@ * @memberof DisplayObject# */ cacheAsBitmap: { - get: function () { + get: function () + { return this._cacheAsBitmap; }, - set: function (value) { - if (this._cacheAsBitmap === value) { + set: function (value) + { + if (this._cacheAsBitmap === value) + { return; } - if (value) { + if (value) + { this._generateCachedSprite(); } - else { + else + { this._destroyCachedSprite(); } @@ -126,7 +140,8 @@ * @param child {DisplayObject} The DisplayObject to add to the container * @return {DisplayObject} The child that was added. */ -DisplayObjectContainer.prototype.addChild = function (child) { +DisplayObjectContainer.prototype.addChild = function (child) +{ return this.addChildAt(child, this.children.length); }; @@ -137,14 +152,18 @@ * @param index {Number} The index to place the child in * @return {DisplayObject} The child that was added. */ -DisplayObjectContainer.prototype.addChildAt = function (child, index) { +DisplayObjectContainer.prototype.addChildAt = function (child, index) +{ // prevent adding self as child - if (child === this) { + if (child === this) + { return; } - if (index >= 0 && index <= this.children.length) { - if (child.parent) { + if (index >= 0 && index <= this.children.length) + { + if (child.parent) + { child.parent.removeChild(child); } @@ -154,7 +173,8 @@ return child; } - else { + else + { throw new Error(child + 'addChildAt: The index '+ index +' supplied is out of bounds ' + this.children.length); } }; @@ -165,15 +185,18 @@ * @param child {DisplayObject} * @param child2 {DisplayObject} */ -DisplayObjectContainer.prototype.swapChildren = function (child, child2) { - if (child === child2) { +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) { + if (index1 < 0 || index2 < 0) + { throw new Error('swapChildren: Both the supplied DisplayObjects must be a child of the caller.'); } @@ -187,10 +210,12 @@ * @param child {DisplayObject} The DisplayObject instance to identify * @return {Number} The index position of the child display object to identify */ -DisplayObjectContainer.prototype.getChildIndex = function (child) { +DisplayObjectContainer.prototype.getChildIndex = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { throw new Error('The supplied DisplayObject must be a child of the caller'); } @@ -203,8 +228,10 @@ * @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 */ -DisplayObjectContainer.prototype.setChildIndex = function (child, index) { - if (index < 0 || index >= this.children.length) { +DisplayObjectContainer.prototype.setChildIndex = function (child, index) +{ + if (index < 0 || index >= this.children.length) + { throw new Error('The supplied index is out of bounds'); } @@ -220,8 +247,10 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child at the given index, if any. */ -DisplayObjectContainer.prototype.getChildAt = function (index) { - if (index < 0 || index >= this.children.length) { +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'); } @@ -234,10 +263,12 @@ * @param child {DisplayObject} The DisplayObject to remove * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChild = function (child) { +DisplayObjectContainer.prototype.removeChild = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { return; } @@ -250,7 +281,8 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChildAt = function (index) { +DisplayObjectContainer.prototype.removeChildAt = function (index) +{ var child = this.getChildAt(index); child.parent = null; @@ -265,24 +297,29 @@ * @param beginIndex {Number} The beginning position. Default value is 0. * @param endIndex {Number} The ending position. Default value is size of the container. */ -DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) { +DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) +{ var begin = beginIndex || 0; var end = typeof endIndex === 'number' ? endIndex : this.children.length; var range = end - begin; - if (range > 0 && range <= end) { + if (range > 0 && range <= end) + { var removed = this.children.splice(begin, range); - for (var i = 0; i < removed.length; ++i) { + for (var i = 0; i < removed.length; ++i) + { removed[i].parent = null; } return removed; } - else if (range === 0 && this.children.length === 0) { + else if (range === 0 && this.children.length === 0) + { return []; } - else { + else + { throw new RangeError('removeChildren: numeric values are outside the acceptable range.'); } }; @@ -291,7 +328,8 @@ * Generates and updates the cached sprite for this object. * */ -DisplayObjectContainer.prototype.updateCachedSprite = function () { +DisplayObjectContainer.prototype.updateCachedSprite = function () +{ this._generateCachedSprite(); }; @@ -304,7 +342,8 @@ * @param renderer {CanvasRenderer|WebGLRenderer} The renderer used to generate the texture. * @return {Texture} a texture of the graphics object */ -DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) { +DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) +{ var bounds = this.getLocalBounds(); var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0, renderer, scaleMode, resolution); @@ -322,18 +361,22 @@ * * @private */ -DisplayObjectContainer.prototype.updateTransform = function () { - if (!this.visible) { +DisplayObjectContainer.prototype.updateTransform = function () +{ + if (!this.visible) + { return; } this.displayObjectUpdateTransform(); - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { return; } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } }; @@ -346,8 +389,10 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getBounds = function () { - if (this.children.length === 0) { +DisplayObjectContainer.prototype.getBounds = function () +{ + if (this.children.length === 0) + { return math.Rectangle.EMPTY; } @@ -365,10 +410,12 @@ var childVisible = false; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -386,7 +433,8 @@ maxY = maxY > childMaxY ? maxY : childMaxY; } - if (!childVisible) { + if (!childVisible) + { return math.Rectangle.EMPTY; } @@ -407,12 +455,14 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getLocalBounds = function () { +DisplayObjectContainer.prototype.getLocalBounds = function () +{ var matrixCache = this.worldTransform; this.worldTransform = math.Matrix.IDENTITY; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } @@ -428,13 +478,16 @@ * * @param renderer {WebGLRenderer} The renderer */ -DisplayObjectContainer.prototype.renderWebGL = function (renderer) { +DisplayObjectContainer.prototype.renderWebGL = function (renderer) +{ // if the object is not visible or the alpha is 0 then no need to render this element - if (!this.visible || this.alpha <= 0) { + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } @@ -442,14 +495,17 @@ var i, j; // do a quick check to see if this element has a mask or a filter. - if (this._mask || this._filters) { + if (this._mask || this._filters) + { // push filter first as we need to ensure the stencil buffer is correct for any masking - if (this._filters) { + if (this._filters) + { renderer.spriteBatch.flush(); renderer.filterManager.pushFilter(this._filterBlock); } - if (this._mask) { + if (this._mask) + { renderer.spriteBatch.stop(); renderer.maskManager.pushMask(this.mask, renderer); renderer.spriteBatch.start(); @@ -459,36 +515,42 @@ this._renderWebGL(renderer); // now loop through the children and make sure they get rendered - for (i = 0, j = this.children.length; i < j; i++) { + for (i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderWebGL(renderer); } // time to stop the sprite batch as either a mask element or a filter draw will happen next renderer.spriteBatch.stop(); - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(this._mask, renderer); } - if (this._filters) { + if (this._filters) + { renderer.filterManager.popFilter(); } renderer.spriteBatch.start(); } - else { + else + { this._renderWebGL(renderer); // simple render children! - for (i = 0, j = this.children.length; i < j; ++i) { + for (i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderWebGL(renderer); } } }; -DisplayObjectContainer.prototype._renderWebGL = function (renderer) { +DisplayObjectContainer.prototype._renderWebGL = function (renderer) +{ // this is where content itself gets renderd.. @@ -499,25 +561,31 @@ * * @param renderer {CanvasRenderer} The renderer */ -DisplayObjectContainer.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0) { +DisplayObjectContainer.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -528,13 +596,16 @@ * @param renderer {WebGLRenderer|CanvasRenderer} The renderer * @private */ -DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) { +DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) +{ this._cachedSprite.worldAlpha = this.worldAlpha; - if (renderer.gl) { + if (renderer.gl) + { this._cachedSprite.renderWebGL(renderer); } - else { + else + { this._cachedSprite.renderCanvas(renderer); } }; @@ -544,10 +615,12 @@ * * @private */ -DisplayObjectContainer.prototype._generateCachedSprite = function () { +DisplayObjectContainer.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { // TODO - RenderTexture now *requires* a renderer instance, so this is like broken // because `renderer` isn't actually in scope here :P var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0); @@ -555,7 +628,8 @@ this._cachedSprite = new Sprite(renderTexture); this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.texture.resize(bounds.width | 0, bounds.height | 0); } @@ -580,8 +654,10 @@ * * @private */ -DisplayObjectContainer.prototype._destroyCachedSprite = function () { - if (!this._cachedSprite) { +DisplayObjectContainer.prototype._destroyCachedSprite = function () +{ + if (!this._cachedSprite) + { return; } diff --git a/src/core/display/Sprite.js b/src/core/display/Sprite.js index 707da24..5862aef 100644 --- a/src/core/display/Sprite.js +++ b/src/core/display/Sprite.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param texture {Texture} The texture for this sprite */ -function Sprite(texture) { +function Sprite(texture) +{ DisplayObjectContainer.call(this); /** @@ -85,12 +86,14 @@ this.texture = texture || Texture.EMPTY; } -Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) { +Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) +{ DisplayObjectContainer.prototype.destroy.call(this); this.anchor = null; - if (destroyTexture) { + if (destroyTexture) + { this._texture.destroy(destroyBaseTexture); } @@ -111,10 +114,12 @@ * @memberof Sprite# */ width: { - get: function () { + get: function () + { return this.scale.x * this.texture.frame.width; }, - set: function (value) { + set: function (value) + { this.scale.x = value / this.texture.frame.width; this._width = value; } @@ -127,10 +132,12 @@ * @memberof Sprite# */ height: { - get: function () { + get: function () + { return this.scale.y * this.texture.frame.height; }, - set: function (value) { + set: function (value) + { this.scale.y = value / this.texture.frame.height; this._height = value; } @@ -143,23 +150,29 @@ * @memberof Sprite# */ texture: { - get: function () { + get: function () + { return this._texture; }, - set: function (value) { - if (this._texture === value) { + set: function (value) + { + if (this._texture === value) + { return; } this._texture = value; this.cachedTint = 0xFFFFFF; - if (value) { + if (value) + { // wait for the texture to load - if (value.baseTexture.hasLoaded) { + if (value.baseTexture.hasLoaded) + { this._onTextureUpdate(); } - else { + else + { value.once('update', this._onTextureUpdate.bind(this)); } } @@ -172,18 +185,22 @@ * * @private */ -Sprite.prototype._onTextureUpdate = function () { +Sprite.prototype._onTextureUpdate = function () +{ // so if _width is 0 then width was not set.. - if (this._width) { + if (this._width) + { this.scale.x = this._width / this.texture.frame.width; } - if (this._height) { + if (this._height) + { this.scale.y = this._height / this.texture.frame.height; } }; -Sprite.prototype._renderWebGL = function (renderer) { +Sprite.prototype._renderWebGL = function (renderer) +{ // this is where content gets renderd.. // watch this space for a little render state manager.. @@ -197,7 +214,8 @@ * @param matrix {Matrix} the transformation matrix of the sprite * @return {Rectangle} the framing rectangle */ -Sprite.prototype.getBounds = function (matrix) { +Sprite.prototype.getBounds = function (matrix) +{ var width = this.texture.frame.width; var height = this.texture.frame.height; @@ -224,11 +242,13 @@ if(b === 0 && c === 0) { // scale may be negative! - if (a < 0) { + if (a < 0) + { a *= -1; } - if (d < 0) { + if (d < 0) + { d *= -1; } @@ -293,28 +313,34 @@ * * @param renderer {CanvasRenderer} The renderer */ -Sprite.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) { +Sprite.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) + { return; } - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; renderer.context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } // Ignore null sources - if (this.texture.valid) { + if (this.texture.valid) + { var resolution = this.texture.baseTexture.resolution / renderer.resolution; renderer.context.globalAlpha = this.worldAlpha; // If smoothingEnabled is supported and we need to change the smoothing property for this texture - if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) { + if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) + { renderer.scaleMode = this.texture.baseTexture.scaleMode; renderer.context[renderer.smoothProperty] = (renderer.scaleMode === CONST.scaleModes.LINEAR); } @@ -324,7 +350,8 @@ var dy = (this.texture.trim ? this.texture.trim.y : 0) - (this.anchor.y * this.texture.trim.height); // Allow for pixel rounding - if (renderer.roundPixels) { + if (renderer.roundPixels) + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -337,7 +364,8 @@ dx = dx | 0; dy = dy | 0; } - else { + else + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -348,8 +376,10 @@ ); } - if (this.tint !== 0xFFFFFF) { - if (this.cachedTint !== this.tint) { + if (this.tint !== 0xFFFFFF) + { + if (this.cachedTint !== this.tint) + { this.cachedTint = this.tint; // TODO clean up caching - how to clean up the caches? @@ -368,7 +398,8 @@ this.texture.crop.height / resolution ); } - else { + else + { renderer.context.drawImage( this.texture.baseTexture.source, this.texture.crop.x, @@ -383,11 +414,13 @@ } } - for (var i = 0, j = this.children.length; i < j; i++) { + for (var i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -402,10 +435,12 @@ * @param frameId {String} The frame Id of the texture in the cache * @return {Sprite} A new Sprite using a texture from the texture cache matching the frameId */ -Sprite.fromFrame = function (frameId) { +Sprite.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache' + this); } @@ -420,6 +455,7 @@ * @param imageId {String} The image url of the texture * @return {Sprite} A new Sprite using a texture from the texture cache matching the image id */ -Sprite.fromImage = function (imageId, crossorigin, scaleMode) { +Sprite.fromImage = function (imageId, crossorigin, scaleMode) +{ return new Sprite(Texture.fromImage(imageId, crossorigin, scaleMode)); }; diff --git a/src/core/display/SpriteBatch.js b/src/core/display/SpriteBatch.js index 3187777..c196fef 100644 --- a/src/core/display/SpriteBatch.js +++ b/src/core/display/SpriteBatch.js @@ -12,7 +12,8 @@ * ```js * var container = new SpriteBatch(); * - * for(var i = 0; i < 100; ++i) { + * for(var i = 0; i < 100; ++i) + * { * var sprite = new PIXI.Sprite.fromImage("myImage.png"); * container.addChild(sprite); * } @@ -25,7 +26,8 @@ */ //TODO RENAME to PARTICLE CONTAINER? -function SpriteBatch() { +function SpriteBatch() +{ DisplayObjectContainer.call(this); } @@ -38,7 +40,8 @@ * * @private */ -SpriteBatch.prototype.updateTransform = function () { +SpriteBatch.prototype.updateTransform = function () +{ // TODO don't need to! this.displayObjectUpdateTransform(); // PIXI.DisplayObjectContainer.prototype.updateTransform.call( this ); @@ -50,8 +53,10 @@ * @param renderer {WebGLRenderer} The webgl renderer * @private */ -SpriteBatch.prototype.renderWebGL = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderWebGL = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -71,8 +76,10 @@ * @param renderer {CanvasRenderer} The canvas renderer * @private */ -SpriteBatch.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -84,10 +91,12 @@ this.displayObjectUpdateTransform(); - for (var i = 0; i < this.children.length; ++i) { + for (var i = 0; i < this.children.length; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -95,9 +104,11 @@ context.globalAlpha = this.worldAlpha * child.alpha; - if (child.rotation % (Math.PI * 2) === 0) { + if (child.rotation % (Math.PI * 2) === 0) + { // this is the fastest way to optimise! - if rotation is 0 then we can avoid any kind of setTransform call - if (isRotated) { + if (isRotated) + { context.setTransform( transform.a, transform.b, @@ -122,8 +133,10 @@ frame.height * child.scale.y ); } - else { - if (!isRotated) { + else + { + if (!isRotated) + { isRotated = true; } @@ -131,7 +144,8 @@ var childTransform = child.worldTransform; - if (renderer.roundPixels) { + if (renderer.roundPixels) + { context.setTransform( childTransform.a, childTransform.b, @@ -141,7 +155,8 @@ childTransform.ty | 0 ); } - else { + else + { context.setTransform( childTransform.a, childTransform.b, diff --git a/src/core/display/DisplayObject.js b/src/core/display/DisplayObject.js index 66ebc3c..20e778c 100644 --- a/src/core/display/DisplayObject.js +++ b/src/core/display/DisplayObject.js @@ -7,7 +7,8 @@ * @class * @namespace PIXI */ -function DisplayObject() { +function DisplayObject() +{ /** * The coordinate of the object relative to the local coordinates of the parent. * @@ -152,10 +153,12 @@ * @memberof DisplayObject# */ x: { - get: function () { + get: function () + { return this.position.x; }, - set: function (value) { + set: function (value) + { this.position.x = value; } }, @@ -167,10 +170,12 @@ * @memberof DisplayObject# */ y: { - get: function () { + get: function () + { return this.position.y; }, - set: function (value) { + set: function (value) + { this.position.y = value; } }, @@ -183,11 +188,13 @@ * @readonly */ worldVisible: { - get: function () { + get: function () + { var item = this; do { - if (!item.visible) { + if (!item.visible) + { return false; } @@ -207,17 +214,21 @@ * @memberof DisplayObject# */ mask: { - get: function () { + get: function () + { return this._mask; }, - set: function (value) { - if (this._mask) { + set: function (value) + { + if (this._mask) + { this._mask.isMask = false; } this._mask = value; - if (this._mask) { + if (this._mask) + { this._mask.isMask = true; } } @@ -232,18 +243,23 @@ * @memberof DisplayObject# */ filters: { - get: function () { + get: function () + { return this._filters; }, - set: function (value) { - if (value) { + set: function (value) + { + if (value) + { // now put all the passes in one place.. var passes = []; - for (var i = 0; i < value.length; i++) { + for (var i = 0; i < value.length; i++) + { var filterPasses = value[i].passes; - for (var j = 0; j < filterPasses.length; j++) { + for (var j = 0; j < filterPasses.length; j++) + { passes.push(filterPasses[j]); } } @@ -264,8 +280,9 @@ * * @private */ -DisplayObject.prototype.updateTransform = function () { - +DisplayObject.prototype.updateTransform = function () +{ + // create some matrix refs for easy access var pt = this.parent.worldTransform; var wt = this.worldTransform; @@ -274,9 +291,11 @@ var a, b, c, d, tx, ty; // so if rotation is between 0 then we can simplify the multiplication process.. - if (this.rotation % math.PI_2) { + if (this.rotation % math.PI_2) + { // 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) { + if (this.rotation !== this.rotationCache) + { this.rotationCache = this.rotation; this._sr = Math.sin(this.rotation); this._cr = Math.cos(this.rotation); @@ -291,7 +310,8 @@ ty = this.position.y; // check for pivot.. not often used so geared towards that fact! - if (this.pivot.x || this.pivot.y) { + 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; } @@ -304,7 +324,8 @@ wt.tx = tx * pt.a + ty * pt.c + pt.tx; wt.ty = tx * pt.b + ty * pt.d + pt.ty; } - else { + else + { // lets do the fast version as we know there is no rotation.. a = this.scale.x; d = this.scale.y; @@ -333,7 +354,8 @@ * @param matrix {Matrix} * @return {Rectangle} the rectangular bounding area */ -DisplayObject.prototype.getBounds = function (/* matrix */) { +DisplayObject.prototype.getBounds = function (/* matrix */) +{ return math.Rectangle.EMPTY; }; @@ -342,7 +364,8 @@ * * @return {Rectangle} the rectangular bounding area */ -DisplayObject.prototype.getLocalBounds = function () { +DisplayObject.prototype.getLocalBounds = function () +{ return this.getBounds(math.Matrix.IDENTITY); }; @@ -352,7 +375,8 @@ * @param position {Point} The world origin to calculate from * @return {Point} A point object representing the position of this object */ -DisplayObject.prototype.toGlobal = function (position) { +DisplayObject.prototype.toGlobal = function (position) +{ // don't need to u[date the lot this.displayObjectUpdateTransform(); return this.worldTransform.apply(position); @@ -365,8 +389,10 @@ * @param [from] {DisplayObject} The DisplayObject to calculate the global position from * @return {Point} A point object representing the position of this object */ -DisplayObject.prototype.toLocal = function (position, from) { - if (from) { +DisplayObject.prototype.toLocal = function (position, from) +{ + if (from) + { position = from.toGlobal(position); } @@ -381,7 +407,8 @@ * @param renderer {WebGLRenderer} The renderer * @private */ -DisplayObject.prototype.renderWebGL = function (/* renderer */) { +DisplayObject.prototype.renderWebGL = function (/* renderer */) +{ // OVERWRITE; }; @@ -391,6 +418,7 @@ * @param renderer {CanvasRenderer} The renderer * @private */ -DisplayObject.prototype.renderCanvas = function (/* renderer */) { +DisplayObject.prototype.renderCanvas = function (/* renderer */) +{ // OVERWRITE; }; diff --git a/src/core/display/DisplayObjectContainer.js b/src/core/display/DisplayObjectContainer.js index 689f40b..4625ee8 100644 --- a/src/core/display/DisplayObjectContainer.js +++ b/src/core/display/DisplayObjectContainer.js @@ -12,7 +12,8 @@ * @extends DisplayObject * @namespace PIXI */ -function DisplayObjectContainer() { +function DisplayObjectContainer() +{ DisplayObject.call(this); /** @@ -47,17 +48,21 @@ * @memberof DisplayObjectContainer# */ width: { - get: function () { + get: function () + { return this.scale.x * this.getLocalBounds().width; }, - set: function (value) { + set: function (value) + { var width = this.getLocalBounds().width; - if(width !== 0) { + if(width !== 0) + { this.scale.x = value / width; } - else { + else + { this.scale.x = 1; } @@ -73,17 +78,21 @@ * @memberof DisplayObjectContainer# */ height: { - get: function () { + get: function () + { return this.scale.y * this.getLocalBounds().height; }, - set: function (value) { + set: function (value) + { var height = this.getLocalBounds().height; - if (height !== 0) { + if (height !== 0) + { this.scale.y = value / height ; } - else { + else + { this.scale.y = 1; } @@ -100,18 +109,23 @@ * @memberof DisplayObject# */ cacheAsBitmap: { - get: function () { + get: function () + { return this._cacheAsBitmap; }, - set: function (value) { - if (this._cacheAsBitmap === value) { + set: function (value) + { + if (this._cacheAsBitmap === value) + { return; } - if (value) { + if (value) + { this._generateCachedSprite(); } - else { + else + { this._destroyCachedSprite(); } @@ -126,7 +140,8 @@ * @param child {DisplayObject} The DisplayObject to add to the container * @return {DisplayObject} The child that was added. */ -DisplayObjectContainer.prototype.addChild = function (child) { +DisplayObjectContainer.prototype.addChild = function (child) +{ return this.addChildAt(child, this.children.length); }; @@ -137,14 +152,18 @@ * @param index {Number} The index to place the child in * @return {DisplayObject} The child that was added. */ -DisplayObjectContainer.prototype.addChildAt = function (child, index) { +DisplayObjectContainer.prototype.addChildAt = function (child, index) +{ // prevent adding self as child - if (child === this) { + if (child === this) + { return; } - if (index >= 0 && index <= this.children.length) { - if (child.parent) { + if (index >= 0 && index <= this.children.length) + { + if (child.parent) + { child.parent.removeChild(child); } @@ -154,7 +173,8 @@ return child; } - else { + else + { throw new Error(child + 'addChildAt: The index '+ index +' supplied is out of bounds ' + this.children.length); } }; @@ -165,15 +185,18 @@ * @param child {DisplayObject} * @param child2 {DisplayObject} */ -DisplayObjectContainer.prototype.swapChildren = function (child, child2) { - if (child === child2) { +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) { + if (index1 < 0 || index2 < 0) + { throw new Error('swapChildren: Both the supplied DisplayObjects must be a child of the caller.'); } @@ -187,10 +210,12 @@ * @param child {DisplayObject} The DisplayObject instance to identify * @return {Number} The index position of the child display object to identify */ -DisplayObjectContainer.prototype.getChildIndex = function (child) { +DisplayObjectContainer.prototype.getChildIndex = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { throw new Error('The supplied DisplayObject must be a child of the caller'); } @@ -203,8 +228,10 @@ * @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 */ -DisplayObjectContainer.prototype.setChildIndex = function (child, index) { - if (index < 0 || index >= this.children.length) { +DisplayObjectContainer.prototype.setChildIndex = function (child, index) +{ + if (index < 0 || index >= this.children.length) + { throw new Error('The supplied index is out of bounds'); } @@ -220,8 +247,10 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child at the given index, if any. */ -DisplayObjectContainer.prototype.getChildAt = function (index) { - if (index < 0 || index >= this.children.length) { +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'); } @@ -234,10 +263,12 @@ * @param child {DisplayObject} The DisplayObject to remove * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChild = function (child) { +DisplayObjectContainer.prototype.removeChild = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { return; } @@ -250,7 +281,8 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChildAt = function (index) { +DisplayObjectContainer.prototype.removeChildAt = function (index) +{ var child = this.getChildAt(index); child.parent = null; @@ -265,24 +297,29 @@ * @param beginIndex {Number} The beginning position. Default value is 0. * @param endIndex {Number} The ending position. Default value is size of the container. */ -DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) { +DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) +{ var begin = beginIndex || 0; var end = typeof endIndex === 'number' ? endIndex : this.children.length; var range = end - begin; - if (range > 0 && range <= end) { + if (range > 0 && range <= end) + { var removed = this.children.splice(begin, range); - for (var i = 0; i < removed.length; ++i) { + for (var i = 0; i < removed.length; ++i) + { removed[i].parent = null; } return removed; } - else if (range === 0 && this.children.length === 0) { + else if (range === 0 && this.children.length === 0) + { return []; } - else { + else + { throw new RangeError('removeChildren: numeric values are outside the acceptable range.'); } }; @@ -291,7 +328,8 @@ * Generates and updates the cached sprite for this object. * */ -DisplayObjectContainer.prototype.updateCachedSprite = function () { +DisplayObjectContainer.prototype.updateCachedSprite = function () +{ this._generateCachedSprite(); }; @@ -304,7 +342,8 @@ * @param renderer {CanvasRenderer|WebGLRenderer} The renderer used to generate the texture. * @return {Texture} a texture of the graphics object */ -DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) { +DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) +{ var bounds = this.getLocalBounds(); var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0, renderer, scaleMode, resolution); @@ -322,18 +361,22 @@ * * @private */ -DisplayObjectContainer.prototype.updateTransform = function () { - if (!this.visible) { +DisplayObjectContainer.prototype.updateTransform = function () +{ + if (!this.visible) + { return; } this.displayObjectUpdateTransform(); - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { return; } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } }; @@ -346,8 +389,10 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getBounds = function () { - if (this.children.length === 0) { +DisplayObjectContainer.prototype.getBounds = function () +{ + if (this.children.length === 0) + { return math.Rectangle.EMPTY; } @@ -365,10 +410,12 @@ var childVisible = false; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -386,7 +433,8 @@ maxY = maxY > childMaxY ? maxY : childMaxY; } - if (!childVisible) { + if (!childVisible) + { return math.Rectangle.EMPTY; } @@ -407,12 +455,14 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getLocalBounds = function () { +DisplayObjectContainer.prototype.getLocalBounds = function () +{ var matrixCache = this.worldTransform; this.worldTransform = math.Matrix.IDENTITY; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } @@ -428,13 +478,16 @@ * * @param renderer {WebGLRenderer} The renderer */ -DisplayObjectContainer.prototype.renderWebGL = function (renderer) { +DisplayObjectContainer.prototype.renderWebGL = function (renderer) +{ // if the object is not visible or the alpha is 0 then no need to render this element - if (!this.visible || this.alpha <= 0) { + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } @@ -442,14 +495,17 @@ var i, j; // do a quick check to see if this element has a mask or a filter. - if (this._mask || this._filters) { + if (this._mask || this._filters) + { // push filter first as we need to ensure the stencil buffer is correct for any masking - if (this._filters) { + if (this._filters) + { renderer.spriteBatch.flush(); renderer.filterManager.pushFilter(this._filterBlock); } - if (this._mask) { + if (this._mask) + { renderer.spriteBatch.stop(); renderer.maskManager.pushMask(this.mask, renderer); renderer.spriteBatch.start(); @@ -459,36 +515,42 @@ this._renderWebGL(renderer); // now loop through the children and make sure they get rendered - for (i = 0, j = this.children.length; i < j; i++) { + for (i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderWebGL(renderer); } // time to stop the sprite batch as either a mask element or a filter draw will happen next renderer.spriteBatch.stop(); - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(this._mask, renderer); } - if (this._filters) { + if (this._filters) + { renderer.filterManager.popFilter(); } renderer.spriteBatch.start(); } - else { + else + { this._renderWebGL(renderer); // simple render children! - for (i = 0, j = this.children.length; i < j; ++i) { + for (i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderWebGL(renderer); } } }; -DisplayObjectContainer.prototype._renderWebGL = function (renderer) { +DisplayObjectContainer.prototype._renderWebGL = function (renderer) +{ // this is where content itself gets renderd.. @@ -499,25 +561,31 @@ * * @param renderer {CanvasRenderer} The renderer */ -DisplayObjectContainer.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0) { +DisplayObjectContainer.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -528,13 +596,16 @@ * @param renderer {WebGLRenderer|CanvasRenderer} The renderer * @private */ -DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) { +DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) +{ this._cachedSprite.worldAlpha = this.worldAlpha; - if (renderer.gl) { + if (renderer.gl) + { this._cachedSprite.renderWebGL(renderer); } - else { + else + { this._cachedSprite.renderCanvas(renderer); } }; @@ -544,10 +615,12 @@ * * @private */ -DisplayObjectContainer.prototype._generateCachedSprite = function () { +DisplayObjectContainer.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { // TODO - RenderTexture now *requires* a renderer instance, so this is like broken // because `renderer` isn't actually in scope here :P var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0); @@ -555,7 +628,8 @@ this._cachedSprite = new Sprite(renderTexture); this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.texture.resize(bounds.width | 0, bounds.height | 0); } @@ -580,8 +654,10 @@ * * @private */ -DisplayObjectContainer.prototype._destroyCachedSprite = function () { - if (!this._cachedSprite) { +DisplayObjectContainer.prototype._destroyCachedSprite = function () +{ + if (!this._cachedSprite) + { return; } diff --git a/src/core/display/Sprite.js b/src/core/display/Sprite.js index 707da24..5862aef 100644 --- a/src/core/display/Sprite.js +++ b/src/core/display/Sprite.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param texture {Texture} The texture for this sprite */ -function Sprite(texture) { +function Sprite(texture) +{ DisplayObjectContainer.call(this); /** @@ -85,12 +86,14 @@ this.texture = texture || Texture.EMPTY; } -Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) { +Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) +{ DisplayObjectContainer.prototype.destroy.call(this); this.anchor = null; - if (destroyTexture) { + if (destroyTexture) + { this._texture.destroy(destroyBaseTexture); } @@ -111,10 +114,12 @@ * @memberof Sprite# */ width: { - get: function () { + get: function () + { return this.scale.x * this.texture.frame.width; }, - set: function (value) { + set: function (value) + { this.scale.x = value / this.texture.frame.width; this._width = value; } @@ -127,10 +132,12 @@ * @memberof Sprite# */ height: { - get: function () { + get: function () + { return this.scale.y * this.texture.frame.height; }, - set: function (value) { + set: function (value) + { this.scale.y = value / this.texture.frame.height; this._height = value; } @@ -143,23 +150,29 @@ * @memberof Sprite# */ texture: { - get: function () { + get: function () + { return this._texture; }, - set: function (value) { - if (this._texture === value) { + set: function (value) + { + if (this._texture === value) + { return; } this._texture = value; this.cachedTint = 0xFFFFFF; - if (value) { + if (value) + { // wait for the texture to load - if (value.baseTexture.hasLoaded) { + if (value.baseTexture.hasLoaded) + { this._onTextureUpdate(); } - else { + else + { value.once('update', this._onTextureUpdate.bind(this)); } } @@ -172,18 +185,22 @@ * * @private */ -Sprite.prototype._onTextureUpdate = function () { +Sprite.prototype._onTextureUpdate = function () +{ // so if _width is 0 then width was not set.. - if (this._width) { + if (this._width) + { this.scale.x = this._width / this.texture.frame.width; } - if (this._height) { + if (this._height) + { this.scale.y = this._height / this.texture.frame.height; } }; -Sprite.prototype._renderWebGL = function (renderer) { +Sprite.prototype._renderWebGL = function (renderer) +{ // this is where content gets renderd.. // watch this space for a little render state manager.. @@ -197,7 +214,8 @@ * @param matrix {Matrix} the transformation matrix of the sprite * @return {Rectangle} the framing rectangle */ -Sprite.prototype.getBounds = function (matrix) { +Sprite.prototype.getBounds = function (matrix) +{ var width = this.texture.frame.width; var height = this.texture.frame.height; @@ -224,11 +242,13 @@ if(b === 0 && c === 0) { // scale may be negative! - if (a < 0) { + if (a < 0) + { a *= -1; } - if (d < 0) { + if (d < 0) + { d *= -1; } @@ -293,28 +313,34 @@ * * @param renderer {CanvasRenderer} The renderer */ -Sprite.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) { +Sprite.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) + { return; } - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; renderer.context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } // Ignore null sources - if (this.texture.valid) { + if (this.texture.valid) + { var resolution = this.texture.baseTexture.resolution / renderer.resolution; renderer.context.globalAlpha = this.worldAlpha; // If smoothingEnabled is supported and we need to change the smoothing property for this texture - if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) { + if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) + { renderer.scaleMode = this.texture.baseTexture.scaleMode; renderer.context[renderer.smoothProperty] = (renderer.scaleMode === CONST.scaleModes.LINEAR); } @@ -324,7 +350,8 @@ var dy = (this.texture.trim ? this.texture.trim.y : 0) - (this.anchor.y * this.texture.trim.height); // Allow for pixel rounding - if (renderer.roundPixels) { + if (renderer.roundPixels) + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -337,7 +364,8 @@ dx = dx | 0; dy = dy | 0; } - else { + else + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -348,8 +376,10 @@ ); } - if (this.tint !== 0xFFFFFF) { - if (this.cachedTint !== this.tint) { + if (this.tint !== 0xFFFFFF) + { + if (this.cachedTint !== this.tint) + { this.cachedTint = this.tint; // TODO clean up caching - how to clean up the caches? @@ -368,7 +398,8 @@ this.texture.crop.height / resolution ); } - else { + else + { renderer.context.drawImage( this.texture.baseTexture.source, this.texture.crop.x, @@ -383,11 +414,13 @@ } } - for (var i = 0, j = this.children.length; i < j; i++) { + for (var i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -402,10 +435,12 @@ * @param frameId {String} The frame Id of the texture in the cache * @return {Sprite} A new Sprite using a texture from the texture cache matching the frameId */ -Sprite.fromFrame = function (frameId) { +Sprite.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache' + this); } @@ -420,6 +455,7 @@ * @param imageId {String} The image url of the texture * @return {Sprite} A new Sprite using a texture from the texture cache matching the image id */ -Sprite.fromImage = function (imageId, crossorigin, scaleMode) { +Sprite.fromImage = function (imageId, crossorigin, scaleMode) +{ return new Sprite(Texture.fromImage(imageId, crossorigin, scaleMode)); }; diff --git a/src/core/display/SpriteBatch.js b/src/core/display/SpriteBatch.js index 3187777..c196fef 100644 --- a/src/core/display/SpriteBatch.js +++ b/src/core/display/SpriteBatch.js @@ -12,7 +12,8 @@ * ```js * var container = new SpriteBatch(); * - * for(var i = 0; i < 100; ++i) { + * for(var i = 0; i < 100; ++i) + * { * var sprite = new PIXI.Sprite.fromImage("myImage.png"); * container.addChild(sprite); * } @@ -25,7 +26,8 @@ */ //TODO RENAME to PARTICLE CONTAINER? -function SpriteBatch() { +function SpriteBatch() +{ DisplayObjectContainer.call(this); } @@ -38,7 +40,8 @@ * * @private */ -SpriteBatch.prototype.updateTransform = function () { +SpriteBatch.prototype.updateTransform = function () +{ // TODO don't need to! this.displayObjectUpdateTransform(); // PIXI.DisplayObjectContainer.prototype.updateTransform.call( this ); @@ -50,8 +53,10 @@ * @param renderer {WebGLRenderer} The webgl renderer * @private */ -SpriteBatch.prototype.renderWebGL = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderWebGL = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -71,8 +76,10 @@ * @param renderer {CanvasRenderer} The canvas renderer * @private */ -SpriteBatch.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -84,10 +91,12 @@ this.displayObjectUpdateTransform(); - for (var i = 0; i < this.children.length; ++i) { + for (var i = 0; i < this.children.length; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -95,9 +104,11 @@ context.globalAlpha = this.worldAlpha * child.alpha; - if (child.rotation % (Math.PI * 2) === 0) { + if (child.rotation % (Math.PI * 2) === 0) + { // this is the fastest way to optimise! - if rotation is 0 then we can avoid any kind of setTransform call - if (isRotated) { + if (isRotated) + { context.setTransform( transform.a, transform.b, @@ -122,8 +133,10 @@ frame.height * child.scale.y ); } - else { - if (!isRotated) { + else + { + if (!isRotated) + { isRotated = true; } @@ -131,7 +144,8 @@ var childTransform = child.worldTransform; - if (renderer.roundPixels) { + if (renderer.roundPixels) + { context.setTransform( childTransform.a, childTransform.b, @@ -141,7 +155,8 @@ childTransform.ty | 0 ); } - else { + else + { context.setTransform( childTransform.a, childTransform.b, diff --git a/src/core/index.js b/src/core/index.js index 3954b6f..eb4a82b 100644 --- a/src/core/index.js +++ b/src/core/index.js @@ -58,11 +58,13 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRenderer: function (width, height, options, noWebGL) { + autoDetectRenderer: function (width, height, options, noWebGL) + { width = width || 800; height = height || 600; - if (!noWebGL && require('webgl-enabled')()) { + if (!noWebGL && require('webgl-enabled')()) + { return new core.WebGLRenderer(width, height, options); } @@ -87,7 +89,8 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRecommendedRenderer: function (width, height, options) { + autoDetectRecommendedRenderer: function (width, height, options) + { var isAndroid = /Android/i.test(navigator.userAgent); return core.autoDetectRenderer(width, height, options, isAndroid); diff --git a/src/core/display/DisplayObject.js b/src/core/display/DisplayObject.js index 66ebc3c..20e778c 100644 --- a/src/core/display/DisplayObject.js +++ b/src/core/display/DisplayObject.js @@ -7,7 +7,8 @@ * @class * @namespace PIXI */ -function DisplayObject() { +function DisplayObject() +{ /** * The coordinate of the object relative to the local coordinates of the parent. * @@ -152,10 +153,12 @@ * @memberof DisplayObject# */ x: { - get: function () { + get: function () + { return this.position.x; }, - set: function (value) { + set: function (value) + { this.position.x = value; } }, @@ -167,10 +170,12 @@ * @memberof DisplayObject# */ y: { - get: function () { + get: function () + { return this.position.y; }, - set: function (value) { + set: function (value) + { this.position.y = value; } }, @@ -183,11 +188,13 @@ * @readonly */ worldVisible: { - get: function () { + get: function () + { var item = this; do { - if (!item.visible) { + if (!item.visible) + { return false; } @@ -207,17 +214,21 @@ * @memberof DisplayObject# */ mask: { - get: function () { + get: function () + { return this._mask; }, - set: function (value) { - if (this._mask) { + set: function (value) + { + if (this._mask) + { this._mask.isMask = false; } this._mask = value; - if (this._mask) { + if (this._mask) + { this._mask.isMask = true; } } @@ -232,18 +243,23 @@ * @memberof DisplayObject# */ filters: { - get: function () { + get: function () + { return this._filters; }, - set: function (value) { - if (value) { + set: function (value) + { + if (value) + { // now put all the passes in one place.. var passes = []; - for (var i = 0; i < value.length; i++) { + for (var i = 0; i < value.length; i++) + { var filterPasses = value[i].passes; - for (var j = 0; j < filterPasses.length; j++) { + for (var j = 0; j < filterPasses.length; j++) + { passes.push(filterPasses[j]); } } @@ -264,8 +280,9 @@ * * @private */ -DisplayObject.prototype.updateTransform = function () { - +DisplayObject.prototype.updateTransform = function () +{ + // create some matrix refs for easy access var pt = this.parent.worldTransform; var wt = this.worldTransform; @@ -274,9 +291,11 @@ var a, b, c, d, tx, ty; // so if rotation is between 0 then we can simplify the multiplication process.. - if (this.rotation % math.PI_2) { + if (this.rotation % math.PI_2) + { // 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) { + if (this.rotation !== this.rotationCache) + { this.rotationCache = this.rotation; this._sr = Math.sin(this.rotation); this._cr = Math.cos(this.rotation); @@ -291,7 +310,8 @@ ty = this.position.y; // check for pivot.. not often used so geared towards that fact! - if (this.pivot.x || this.pivot.y) { + 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; } @@ -304,7 +324,8 @@ wt.tx = tx * pt.a + ty * pt.c + pt.tx; wt.ty = tx * pt.b + ty * pt.d + pt.ty; } - else { + else + { // lets do the fast version as we know there is no rotation.. a = this.scale.x; d = this.scale.y; @@ -333,7 +354,8 @@ * @param matrix {Matrix} * @return {Rectangle} the rectangular bounding area */ -DisplayObject.prototype.getBounds = function (/* matrix */) { +DisplayObject.prototype.getBounds = function (/* matrix */) +{ return math.Rectangle.EMPTY; }; @@ -342,7 +364,8 @@ * * @return {Rectangle} the rectangular bounding area */ -DisplayObject.prototype.getLocalBounds = function () { +DisplayObject.prototype.getLocalBounds = function () +{ return this.getBounds(math.Matrix.IDENTITY); }; @@ -352,7 +375,8 @@ * @param position {Point} The world origin to calculate from * @return {Point} A point object representing the position of this object */ -DisplayObject.prototype.toGlobal = function (position) { +DisplayObject.prototype.toGlobal = function (position) +{ // don't need to u[date the lot this.displayObjectUpdateTransform(); return this.worldTransform.apply(position); @@ -365,8 +389,10 @@ * @param [from] {DisplayObject} The DisplayObject to calculate the global position from * @return {Point} A point object representing the position of this object */ -DisplayObject.prototype.toLocal = function (position, from) { - if (from) { +DisplayObject.prototype.toLocal = function (position, from) +{ + if (from) + { position = from.toGlobal(position); } @@ -381,7 +407,8 @@ * @param renderer {WebGLRenderer} The renderer * @private */ -DisplayObject.prototype.renderWebGL = function (/* renderer */) { +DisplayObject.prototype.renderWebGL = function (/* renderer */) +{ // OVERWRITE; }; @@ -391,6 +418,7 @@ * @param renderer {CanvasRenderer} The renderer * @private */ -DisplayObject.prototype.renderCanvas = function (/* renderer */) { +DisplayObject.prototype.renderCanvas = function (/* renderer */) +{ // OVERWRITE; }; diff --git a/src/core/display/DisplayObjectContainer.js b/src/core/display/DisplayObjectContainer.js index 689f40b..4625ee8 100644 --- a/src/core/display/DisplayObjectContainer.js +++ b/src/core/display/DisplayObjectContainer.js @@ -12,7 +12,8 @@ * @extends DisplayObject * @namespace PIXI */ -function DisplayObjectContainer() { +function DisplayObjectContainer() +{ DisplayObject.call(this); /** @@ -47,17 +48,21 @@ * @memberof DisplayObjectContainer# */ width: { - get: function () { + get: function () + { return this.scale.x * this.getLocalBounds().width; }, - set: function (value) { + set: function (value) + { var width = this.getLocalBounds().width; - if(width !== 0) { + if(width !== 0) + { this.scale.x = value / width; } - else { + else + { this.scale.x = 1; } @@ -73,17 +78,21 @@ * @memberof DisplayObjectContainer# */ height: { - get: function () { + get: function () + { return this.scale.y * this.getLocalBounds().height; }, - set: function (value) { + set: function (value) + { var height = this.getLocalBounds().height; - if (height !== 0) { + if (height !== 0) + { this.scale.y = value / height ; } - else { + else + { this.scale.y = 1; } @@ -100,18 +109,23 @@ * @memberof DisplayObject# */ cacheAsBitmap: { - get: function () { + get: function () + { return this._cacheAsBitmap; }, - set: function (value) { - if (this._cacheAsBitmap === value) { + set: function (value) + { + if (this._cacheAsBitmap === value) + { return; } - if (value) { + if (value) + { this._generateCachedSprite(); } - else { + else + { this._destroyCachedSprite(); } @@ -126,7 +140,8 @@ * @param child {DisplayObject} The DisplayObject to add to the container * @return {DisplayObject} The child that was added. */ -DisplayObjectContainer.prototype.addChild = function (child) { +DisplayObjectContainer.prototype.addChild = function (child) +{ return this.addChildAt(child, this.children.length); }; @@ -137,14 +152,18 @@ * @param index {Number} The index to place the child in * @return {DisplayObject} The child that was added. */ -DisplayObjectContainer.prototype.addChildAt = function (child, index) { +DisplayObjectContainer.prototype.addChildAt = function (child, index) +{ // prevent adding self as child - if (child === this) { + if (child === this) + { return; } - if (index >= 0 && index <= this.children.length) { - if (child.parent) { + if (index >= 0 && index <= this.children.length) + { + if (child.parent) + { child.parent.removeChild(child); } @@ -154,7 +173,8 @@ return child; } - else { + else + { throw new Error(child + 'addChildAt: The index '+ index +' supplied is out of bounds ' + this.children.length); } }; @@ -165,15 +185,18 @@ * @param child {DisplayObject} * @param child2 {DisplayObject} */ -DisplayObjectContainer.prototype.swapChildren = function (child, child2) { - if (child === child2) { +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) { + if (index1 < 0 || index2 < 0) + { throw new Error('swapChildren: Both the supplied DisplayObjects must be a child of the caller.'); } @@ -187,10 +210,12 @@ * @param child {DisplayObject} The DisplayObject instance to identify * @return {Number} The index position of the child display object to identify */ -DisplayObjectContainer.prototype.getChildIndex = function (child) { +DisplayObjectContainer.prototype.getChildIndex = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { throw new Error('The supplied DisplayObject must be a child of the caller'); } @@ -203,8 +228,10 @@ * @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 */ -DisplayObjectContainer.prototype.setChildIndex = function (child, index) { - if (index < 0 || index >= this.children.length) { +DisplayObjectContainer.prototype.setChildIndex = function (child, index) +{ + if (index < 0 || index >= this.children.length) + { throw new Error('The supplied index is out of bounds'); } @@ -220,8 +247,10 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child at the given index, if any. */ -DisplayObjectContainer.prototype.getChildAt = function (index) { - if (index < 0 || index >= this.children.length) { +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'); } @@ -234,10 +263,12 @@ * @param child {DisplayObject} The DisplayObject to remove * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChild = function (child) { +DisplayObjectContainer.prototype.removeChild = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { return; } @@ -250,7 +281,8 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChildAt = function (index) { +DisplayObjectContainer.prototype.removeChildAt = function (index) +{ var child = this.getChildAt(index); child.parent = null; @@ -265,24 +297,29 @@ * @param beginIndex {Number} The beginning position. Default value is 0. * @param endIndex {Number} The ending position. Default value is size of the container. */ -DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) { +DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) +{ var begin = beginIndex || 0; var end = typeof endIndex === 'number' ? endIndex : this.children.length; var range = end - begin; - if (range > 0 && range <= end) { + if (range > 0 && range <= end) + { var removed = this.children.splice(begin, range); - for (var i = 0; i < removed.length; ++i) { + for (var i = 0; i < removed.length; ++i) + { removed[i].parent = null; } return removed; } - else if (range === 0 && this.children.length === 0) { + else if (range === 0 && this.children.length === 0) + { return []; } - else { + else + { throw new RangeError('removeChildren: numeric values are outside the acceptable range.'); } }; @@ -291,7 +328,8 @@ * Generates and updates the cached sprite for this object. * */ -DisplayObjectContainer.prototype.updateCachedSprite = function () { +DisplayObjectContainer.prototype.updateCachedSprite = function () +{ this._generateCachedSprite(); }; @@ -304,7 +342,8 @@ * @param renderer {CanvasRenderer|WebGLRenderer} The renderer used to generate the texture. * @return {Texture} a texture of the graphics object */ -DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) { +DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) +{ var bounds = this.getLocalBounds(); var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0, renderer, scaleMode, resolution); @@ -322,18 +361,22 @@ * * @private */ -DisplayObjectContainer.prototype.updateTransform = function () { - if (!this.visible) { +DisplayObjectContainer.prototype.updateTransform = function () +{ + if (!this.visible) + { return; } this.displayObjectUpdateTransform(); - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { return; } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } }; @@ -346,8 +389,10 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getBounds = function () { - if (this.children.length === 0) { +DisplayObjectContainer.prototype.getBounds = function () +{ + if (this.children.length === 0) + { return math.Rectangle.EMPTY; } @@ -365,10 +410,12 @@ var childVisible = false; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -386,7 +433,8 @@ maxY = maxY > childMaxY ? maxY : childMaxY; } - if (!childVisible) { + if (!childVisible) + { return math.Rectangle.EMPTY; } @@ -407,12 +455,14 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getLocalBounds = function () { +DisplayObjectContainer.prototype.getLocalBounds = function () +{ var matrixCache = this.worldTransform; this.worldTransform = math.Matrix.IDENTITY; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } @@ -428,13 +478,16 @@ * * @param renderer {WebGLRenderer} The renderer */ -DisplayObjectContainer.prototype.renderWebGL = function (renderer) { +DisplayObjectContainer.prototype.renderWebGL = function (renderer) +{ // if the object is not visible or the alpha is 0 then no need to render this element - if (!this.visible || this.alpha <= 0) { + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } @@ -442,14 +495,17 @@ var i, j; // do a quick check to see if this element has a mask or a filter. - if (this._mask || this._filters) { + if (this._mask || this._filters) + { // push filter first as we need to ensure the stencil buffer is correct for any masking - if (this._filters) { + if (this._filters) + { renderer.spriteBatch.flush(); renderer.filterManager.pushFilter(this._filterBlock); } - if (this._mask) { + if (this._mask) + { renderer.spriteBatch.stop(); renderer.maskManager.pushMask(this.mask, renderer); renderer.spriteBatch.start(); @@ -459,36 +515,42 @@ this._renderWebGL(renderer); // now loop through the children and make sure they get rendered - for (i = 0, j = this.children.length; i < j; i++) { + for (i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderWebGL(renderer); } // time to stop the sprite batch as either a mask element or a filter draw will happen next renderer.spriteBatch.stop(); - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(this._mask, renderer); } - if (this._filters) { + if (this._filters) + { renderer.filterManager.popFilter(); } renderer.spriteBatch.start(); } - else { + else + { this._renderWebGL(renderer); // simple render children! - for (i = 0, j = this.children.length; i < j; ++i) { + for (i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderWebGL(renderer); } } }; -DisplayObjectContainer.prototype._renderWebGL = function (renderer) { +DisplayObjectContainer.prototype._renderWebGL = function (renderer) +{ // this is where content itself gets renderd.. @@ -499,25 +561,31 @@ * * @param renderer {CanvasRenderer} The renderer */ -DisplayObjectContainer.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0) { +DisplayObjectContainer.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -528,13 +596,16 @@ * @param renderer {WebGLRenderer|CanvasRenderer} The renderer * @private */ -DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) { +DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) +{ this._cachedSprite.worldAlpha = this.worldAlpha; - if (renderer.gl) { + if (renderer.gl) + { this._cachedSprite.renderWebGL(renderer); } - else { + else + { this._cachedSprite.renderCanvas(renderer); } }; @@ -544,10 +615,12 @@ * * @private */ -DisplayObjectContainer.prototype._generateCachedSprite = function () { +DisplayObjectContainer.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { // TODO - RenderTexture now *requires* a renderer instance, so this is like broken // because `renderer` isn't actually in scope here :P var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0); @@ -555,7 +628,8 @@ this._cachedSprite = new Sprite(renderTexture); this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.texture.resize(bounds.width | 0, bounds.height | 0); } @@ -580,8 +654,10 @@ * * @private */ -DisplayObjectContainer.prototype._destroyCachedSprite = function () { - if (!this._cachedSprite) { +DisplayObjectContainer.prototype._destroyCachedSprite = function () +{ + if (!this._cachedSprite) + { return; } diff --git a/src/core/display/Sprite.js b/src/core/display/Sprite.js index 707da24..5862aef 100644 --- a/src/core/display/Sprite.js +++ b/src/core/display/Sprite.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param texture {Texture} The texture for this sprite */ -function Sprite(texture) { +function Sprite(texture) +{ DisplayObjectContainer.call(this); /** @@ -85,12 +86,14 @@ this.texture = texture || Texture.EMPTY; } -Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) { +Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) +{ DisplayObjectContainer.prototype.destroy.call(this); this.anchor = null; - if (destroyTexture) { + if (destroyTexture) + { this._texture.destroy(destroyBaseTexture); } @@ -111,10 +114,12 @@ * @memberof Sprite# */ width: { - get: function () { + get: function () + { return this.scale.x * this.texture.frame.width; }, - set: function (value) { + set: function (value) + { this.scale.x = value / this.texture.frame.width; this._width = value; } @@ -127,10 +132,12 @@ * @memberof Sprite# */ height: { - get: function () { + get: function () + { return this.scale.y * this.texture.frame.height; }, - set: function (value) { + set: function (value) + { this.scale.y = value / this.texture.frame.height; this._height = value; } @@ -143,23 +150,29 @@ * @memberof Sprite# */ texture: { - get: function () { + get: function () + { return this._texture; }, - set: function (value) { - if (this._texture === value) { + set: function (value) + { + if (this._texture === value) + { return; } this._texture = value; this.cachedTint = 0xFFFFFF; - if (value) { + if (value) + { // wait for the texture to load - if (value.baseTexture.hasLoaded) { + if (value.baseTexture.hasLoaded) + { this._onTextureUpdate(); } - else { + else + { value.once('update', this._onTextureUpdate.bind(this)); } } @@ -172,18 +185,22 @@ * * @private */ -Sprite.prototype._onTextureUpdate = function () { +Sprite.prototype._onTextureUpdate = function () +{ // so if _width is 0 then width was not set.. - if (this._width) { + if (this._width) + { this.scale.x = this._width / this.texture.frame.width; } - if (this._height) { + if (this._height) + { this.scale.y = this._height / this.texture.frame.height; } }; -Sprite.prototype._renderWebGL = function (renderer) { +Sprite.prototype._renderWebGL = function (renderer) +{ // this is where content gets renderd.. // watch this space for a little render state manager.. @@ -197,7 +214,8 @@ * @param matrix {Matrix} the transformation matrix of the sprite * @return {Rectangle} the framing rectangle */ -Sprite.prototype.getBounds = function (matrix) { +Sprite.prototype.getBounds = function (matrix) +{ var width = this.texture.frame.width; var height = this.texture.frame.height; @@ -224,11 +242,13 @@ if(b === 0 && c === 0) { // scale may be negative! - if (a < 0) { + if (a < 0) + { a *= -1; } - if (d < 0) { + if (d < 0) + { d *= -1; } @@ -293,28 +313,34 @@ * * @param renderer {CanvasRenderer} The renderer */ -Sprite.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) { +Sprite.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) + { return; } - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; renderer.context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } // Ignore null sources - if (this.texture.valid) { + if (this.texture.valid) + { var resolution = this.texture.baseTexture.resolution / renderer.resolution; renderer.context.globalAlpha = this.worldAlpha; // If smoothingEnabled is supported and we need to change the smoothing property for this texture - if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) { + if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) + { renderer.scaleMode = this.texture.baseTexture.scaleMode; renderer.context[renderer.smoothProperty] = (renderer.scaleMode === CONST.scaleModes.LINEAR); } @@ -324,7 +350,8 @@ var dy = (this.texture.trim ? this.texture.trim.y : 0) - (this.anchor.y * this.texture.trim.height); // Allow for pixel rounding - if (renderer.roundPixels) { + if (renderer.roundPixels) + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -337,7 +364,8 @@ dx = dx | 0; dy = dy | 0; } - else { + else + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -348,8 +376,10 @@ ); } - if (this.tint !== 0xFFFFFF) { - if (this.cachedTint !== this.tint) { + if (this.tint !== 0xFFFFFF) + { + if (this.cachedTint !== this.tint) + { this.cachedTint = this.tint; // TODO clean up caching - how to clean up the caches? @@ -368,7 +398,8 @@ this.texture.crop.height / resolution ); } - else { + else + { renderer.context.drawImage( this.texture.baseTexture.source, this.texture.crop.x, @@ -383,11 +414,13 @@ } } - for (var i = 0, j = this.children.length; i < j; i++) { + for (var i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -402,10 +435,12 @@ * @param frameId {String} The frame Id of the texture in the cache * @return {Sprite} A new Sprite using a texture from the texture cache matching the frameId */ -Sprite.fromFrame = function (frameId) { +Sprite.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache' + this); } @@ -420,6 +455,7 @@ * @param imageId {String} The image url of the texture * @return {Sprite} A new Sprite using a texture from the texture cache matching the image id */ -Sprite.fromImage = function (imageId, crossorigin, scaleMode) { +Sprite.fromImage = function (imageId, crossorigin, scaleMode) +{ return new Sprite(Texture.fromImage(imageId, crossorigin, scaleMode)); }; diff --git a/src/core/display/SpriteBatch.js b/src/core/display/SpriteBatch.js index 3187777..c196fef 100644 --- a/src/core/display/SpriteBatch.js +++ b/src/core/display/SpriteBatch.js @@ -12,7 +12,8 @@ * ```js * var container = new SpriteBatch(); * - * for(var i = 0; i < 100; ++i) { + * for(var i = 0; i < 100; ++i) + * { * var sprite = new PIXI.Sprite.fromImage("myImage.png"); * container.addChild(sprite); * } @@ -25,7 +26,8 @@ */ //TODO RENAME to PARTICLE CONTAINER? -function SpriteBatch() { +function SpriteBatch() +{ DisplayObjectContainer.call(this); } @@ -38,7 +40,8 @@ * * @private */ -SpriteBatch.prototype.updateTransform = function () { +SpriteBatch.prototype.updateTransform = function () +{ // TODO don't need to! this.displayObjectUpdateTransform(); // PIXI.DisplayObjectContainer.prototype.updateTransform.call( this ); @@ -50,8 +53,10 @@ * @param renderer {WebGLRenderer} The webgl renderer * @private */ -SpriteBatch.prototype.renderWebGL = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderWebGL = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -71,8 +76,10 @@ * @param renderer {CanvasRenderer} The canvas renderer * @private */ -SpriteBatch.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -84,10 +91,12 @@ this.displayObjectUpdateTransform(); - for (var i = 0; i < this.children.length; ++i) { + for (var i = 0; i < this.children.length; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -95,9 +104,11 @@ context.globalAlpha = this.worldAlpha * child.alpha; - if (child.rotation % (Math.PI * 2) === 0) { + if (child.rotation % (Math.PI * 2) === 0) + { // this is the fastest way to optimise! - if rotation is 0 then we can avoid any kind of setTransform call - if (isRotated) { + if (isRotated) + { context.setTransform( transform.a, transform.b, @@ -122,8 +133,10 @@ frame.height * child.scale.y ); } - else { - if (!isRotated) { + else + { + if (!isRotated) + { isRotated = true; } @@ -131,7 +144,8 @@ var childTransform = child.worldTransform; - if (renderer.roundPixels) { + if (renderer.roundPixels) + { context.setTransform( childTransform.a, childTransform.b, @@ -141,7 +155,8 @@ childTransform.ty | 0 ); } - else { + else + { context.setTransform( childTransform.a, childTransform.b, diff --git a/src/core/index.js b/src/core/index.js index 3954b6f..eb4a82b 100644 --- a/src/core/index.js +++ b/src/core/index.js @@ -58,11 +58,13 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRenderer: function (width, height, options, noWebGL) { + autoDetectRenderer: function (width, height, options, noWebGL) + { width = width || 800; height = height || 600; - if (!noWebGL && require('webgl-enabled')()) { + if (!noWebGL && require('webgl-enabled')()) + { return new core.WebGLRenderer(width, height, options); } @@ -87,7 +89,8 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRecommendedRenderer: function (width, height, options) { + autoDetectRecommendedRenderer: function (width, height, options) + { var isAndroid = /Android/i.test(navigator.userAgent); return core.autoDetectRenderer(width, height, options, isAndroid); diff --git a/src/core/math/Matrix.js b/src/core/math/Matrix.js index c2f87e2..2ff4848 100644 --- a/src/core/math/Matrix.js +++ b/src/core/math/Matrix.js @@ -10,7 +10,8 @@ * @class * @namespace PIXI */ -function Matrix() { +function Matrix() +{ /** * @member {number} * @default 1 @@ -63,7 +64,8 @@ * * @param array {number[]} The array that the matrix will be populated from. */ -Matrix.prototype.fromArray = function (array) { +Matrix.prototype.fromArray = function (array) +{ this.a = array[0]; this.b = array[1]; this.c = array[3]; @@ -78,14 +80,17 @@ * @param transpose {boolean} Whether we need to transpose the matrix or not * @return {number[]} the newly created array which contains the matrix */ -Matrix.prototype.toArray = function (transpose) { - if (!this.array) { +Matrix.prototype.toArray = function (transpose) +{ + if (!this.array) + { this.array = new Float32Array(9); } var array = this.array; - if (transpose) { + if (transpose) + { array[0] = this.a; array[1] = this.b; array[2] = 0; @@ -96,7 +101,8 @@ array[7] = this.ty; array[8] = 1; } - else { + else + { array[0] = this.a; array[1] = this.c; array[2] = this.tx; @@ -119,7 +125,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, transformed through this matrix */ -Matrix.prototype.apply = function (pos, newPos) { +Matrix.prototype.apply = function (pos, newPos) +{ newPos = newPos || new Point(); newPos.x = this.a * pos.x + this.c * pos.y + this.tx; @@ -136,7 +143,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, inverse-transformed through this matrix */ -Matrix.prototype.applyInverse = function (pos, newPos) { +Matrix.prototype.applyInverse = function (pos, newPos) +{ newPos = newPos || new Point(); var id = 1 / (this.a * this.d + this.c * -this.b); @@ -154,7 +162,8 @@ * @param {number} y * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.translate = function (x, y) { +Matrix.prototype.translate = function (x, y) +{ this.tx += x; this.ty += y; @@ -168,7 +177,8 @@ * @param {number} y The amount to scale vertically * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.scale = function (x, y) { +Matrix.prototype.scale = function (x, y) +{ this.a *= x; this.d *= y; this.c *= x; @@ -186,7 +196,8 @@ * @param {number} angle - The angle in radians. * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.rotate = function (angle) { +Matrix.prototype.rotate = function (angle) +{ var cos = Math.cos( angle ); var sin = Math.sin( angle ); @@ -210,7 +221,8 @@ * @param {Matrix} matrix * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.append = function (matrix) { +Matrix.prototype.append = function (matrix) +{ var a1 = this.a; var b1 = this.b; var c1 = this.c; @@ -232,7 +244,8 @@ * * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.identity = function () { +Matrix.prototype.identity = function () +{ this.a = 1; this.b = 0; this.c = 0; diff --git a/src/core/display/DisplayObject.js b/src/core/display/DisplayObject.js index 66ebc3c..20e778c 100644 --- a/src/core/display/DisplayObject.js +++ b/src/core/display/DisplayObject.js @@ -7,7 +7,8 @@ * @class * @namespace PIXI */ -function DisplayObject() { +function DisplayObject() +{ /** * The coordinate of the object relative to the local coordinates of the parent. * @@ -152,10 +153,12 @@ * @memberof DisplayObject# */ x: { - get: function () { + get: function () + { return this.position.x; }, - set: function (value) { + set: function (value) + { this.position.x = value; } }, @@ -167,10 +170,12 @@ * @memberof DisplayObject# */ y: { - get: function () { + get: function () + { return this.position.y; }, - set: function (value) { + set: function (value) + { this.position.y = value; } }, @@ -183,11 +188,13 @@ * @readonly */ worldVisible: { - get: function () { + get: function () + { var item = this; do { - if (!item.visible) { + if (!item.visible) + { return false; } @@ -207,17 +214,21 @@ * @memberof DisplayObject# */ mask: { - get: function () { + get: function () + { return this._mask; }, - set: function (value) { - if (this._mask) { + set: function (value) + { + if (this._mask) + { this._mask.isMask = false; } this._mask = value; - if (this._mask) { + if (this._mask) + { this._mask.isMask = true; } } @@ -232,18 +243,23 @@ * @memberof DisplayObject# */ filters: { - get: function () { + get: function () + { return this._filters; }, - set: function (value) { - if (value) { + set: function (value) + { + if (value) + { // now put all the passes in one place.. var passes = []; - for (var i = 0; i < value.length; i++) { + for (var i = 0; i < value.length; i++) + { var filterPasses = value[i].passes; - for (var j = 0; j < filterPasses.length; j++) { + for (var j = 0; j < filterPasses.length; j++) + { passes.push(filterPasses[j]); } } @@ -264,8 +280,9 @@ * * @private */ -DisplayObject.prototype.updateTransform = function () { - +DisplayObject.prototype.updateTransform = function () +{ + // create some matrix refs for easy access var pt = this.parent.worldTransform; var wt = this.worldTransform; @@ -274,9 +291,11 @@ var a, b, c, d, tx, ty; // so if rotation is between 0 then we can simplify the multiplication process.. - if (this.rotation % math.PI_2) { + if (this.rotation % math.PI_2) + { // 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) { + if (this.rotation !== this.rotationCache) + { this.rotationCache = this.rotation; this._sr = Math.sin(this.rotation); this._cr = Math.cos(this.rotation); @@ -291,7 +310,8 @@ ty = this.position.y; // check for pivot.. not often used so geared towards that fact! - if (this.pivot.x || this.pivot.y) { + 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; } @@ -304,7 +324,8 @@ wt.tx = tx * pt.a + ty * pt.c + pt.tx; wt.ty = tx * pt.b + ty * pt.d + pt.ty; } - else { + else + { // lets do the fast version as we know there is no rotation.. a = this.scale.x; d = this.scale.y; @@ -333,7 +354,8 @@ * @param matrix {Matrix} * @return {Rectangle} the rectangular bounding area */ -DisplayObject.prototype.getBounds = function (/* matrix */) { +DisplayObject.prototype.getBounds = function (/* matrix */) +{ return math.Rectangle.EMPTY; }; @@ -342,7 +364,8 @@ * * @return {Rectangle} the rectangular bounding area */ -DisplayObject.prototype.getLocalBounds = function () { +DisplayObject.prototype.getLocalBounds = function () +{ return this.getBounds(math.Matrix.IDENTITY); }; @@ -352,7 +375,8 @@ * @param position {Point} The world origin to calculate from * @return {Point} A point object representing the position of this object */ -DisplayObject.prototype.toGlobal = function (position) { +DisplayObject.prototype.toGlobal = function (position) +{ // don't need to u[date the lot this.displayObjectUpdateTransform(); return this.worldTransform.apply(position); @@ -365,8 +389,10 @@ * @param [from] {DisplayObject} The DisplayObject to calculate the global position from * @return {Point} A point object representing the position of this object */ -DisplayObject.prototype.toLocal = function (position, from) { - if (from) { +DisplayObject.prototype.toLocal = function (position, from) +{ + if (from) + { position = from.toGlobal(position); } @@ -381,7 +407,8 @@ * @param renderer {WebGLRenderer} The renderer * @private */ -DisplayObject.prototype.renderWebGL = function (/* renderer */) { +DisplayObject.prototype.renderWebGL = function (/* renderer */) +{ // OVERWRITE; }; @@ -391,6 +418,7 @@ * @param renderer {CanvasRenderer} The renderer * @private */ -DisplayObject.prototype.renderCanvas = function (/* renderer */) { +DisplayObject.prototype.renderCanvas = function (/* renderer */) +{ // OVERWRITE; }; diff --git a/src/core/display/DisplayObjectContainer.js b/src/core/display/DisplayObjectContainer.js index 689f40b..4625ee8 100644 --- a/src/core/display/DisplayObjectContainer.js +++ b/src/core/display/DisplayObjectContainer.js @@ -12,7 +12,8 @@ * @extends DisplayObject * @namespace PIXI */ -function DisplayObjectContainer() { +function DisplayObjectContainer() +{ DisplayObject.call(this); /** @@ -47,17 +48,21 @@ * @memberof DisplayObjectContainer# */ width: { - get: function () { + get: function () + { return this.scale.x * this.getLocalBounds().width; }, - set: function (value) { + set: function (value) + { var width = this.getLocalBounds().width; - if(width !== 0) { + if(width !== 0) + { this.scale.x = value / width; } - else { + else + { this.scale.x = 1; } @@ -73,17 +78,21 @@ * @memberof DisplayObjectContainer# */ height: { - get: function () { + get: function () + { return this.scale.y * this.getLocalBounds().height; }, - set: function (value) { + set: function (value) + { var height = this.getLocalBounds().height; - if (height !== 0) { + if (height !== 0) + { this.scale.y = value / height ; } - else { + else + { this.scale.y = 1; } @@ -100,18 +109,23 @@ * @memberof DisplayObject# */ cacheAsBitmap: { - get: function () { + get: function () + { return this._cacheAsBitmap; }, - set: function (value) { - if (this._cacheAsBitmap === value) { + set: function (value) + { + if (this._cacheAsBitmap === value) + { return; } - if (value) { + if (value) + { this._generateCachedSprite(); } - else { + else + { this._destroyCachedSprite(); } @@ -126,7 +140,8 @@ * @param child {DisplayObject} The DisplayObject to add to the container * @return {DisplayObject} The child that was added. */ -DisplayObjectContainer.prototype.addChild = function (child) { +DisplayObjectContainer.prototype.addChild = function (child) +{ return this.addChildAt(child, this.children.length); }; @@ -137,14 +152,18 @@ * @param index {Number} The index to place the child in * @return {DisplayObject} The child that was added. */ -DisplayObjectContainer.prototype.addChildAt = function (child, index) { +DisplayObjectContainer.prototype.addChildAt = function (child, index) +{ // prevent adding self as child - if (child === this) { + if (child === this) + { return; } - if (index >= 0 && index <= this.children.length) { - if (child.parent) { + if (index >= 0 && index <= this.children.length) + { + if (child.parent) + { child.parent.removeChild(child); } @@ -154,7 +173,8 @@ return child; } - else { + else + { throw new Error(child + 'addChildAt: The index '+ index +' supplied is out of bounds ' + this.children.length); } }; @@ -165,15 +185,18 @@ * @param child {DisplayObject} * @param child2 {DisplayObject} */ -DisplayObjectContainer.prototype.swapChildren = function (child, child2) { - if (child === child2) { +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) { + if (index1 < 0 || index2 < 0) + { throw new Error('swapChildren: Both the supplied DisplayObjects must be a child of the caller.'); } @@ -187,10 +210,12 @@ * @param child {DisplayObject} The DisplayObject instance to identify * @return {Number} The index position of the child display object to identify */ -DisplayObjectContainer.prototype.getChildIndex = function (child) { +DisplayObjectContainer.prototype.getChildIndex = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { throw new Error('The supplied DisplayObject must be a child of the caller'); } @@ -203,8 +228,10 @@ * @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 */ -DisplayObjectContainer.prototype.setChildIndex = function (child, index) { - if (index < 0 || index >= this.children.length) { +DisplayObjectContainer.prototype.setChildIndex = function (child, index) +{ + if (index < 0 || index >= this.children.length) + { throw new Error('The supplied index is out of bounds'); } @@ -220,8 +247,10 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child at the given index, if any. */ -DisplayObjectContainer.prototype.getChildAt = function (index) { - if (index < 0 || index >= this.children.length) { +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'); } @@ -234,10 +263,12 @@ * @param child {DisplayObject} The DisplayObject to remove * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChild = function (child) { +DisplayObjectContainer.prototype.removeChild = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { return; } @@ -250,7 +281,8 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChildAt = function (index) { +DisplayObjectContainer.prototype.removeChildAt = function (index) +{ var child = this.getChildAt(index); child.parent = null; @@ -265,24 +297,29 @@ * @param beginIndex {Number} The beginning position. Default value is 0. * @param endIndex {Number} The ending position. Default value is size of the container. */ -DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) { +DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) +{ var begin = beginIndex || 0; var end = typeof endIndex === 'number' ? endIndex : this.children.length; var range = end - begin; - if (range > 0 && range <= end) { + if (range > 0 && range <= end) + { var removed = this.children.splice(begin, range); - for (var i = 0; i < removed.length; ++i) { + for (var i = 0; i < removed.length; ++i) + { removed[i].parent = null; } return removed; } - else if (range === 0 && this.children.length === 0) { + else if (range === 0 && this.children.length === 0) + { return []; } - else { + else + { throw new RangeError('removeChildren: numeric values are outside the acceptable range.'); } }; @@ -291,7 +328,8 @@ * Generates and updates the cached sprite for this object. * */ -DisplayObjectContainer.prototype.updateCachedSprite = function () { +DisplayObjectContainer.prototype.updateCachedSprite = function () +{ this._generateCachedSprite(); }; @@ -304,7 +342,8 @@ * @param renderer {CanvasRenderer|WebGLRenderer} The renderer used to generate the texture. * @return {Texture} a texture of the graphics object */ -DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) { +DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) +{ var bounds = this.getLocalBounds(); var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0, renderer, scaleMode, resolution); @@ -322,18 +361,22 @@ * * @private */ -DisplayObjectContainer.prototype.updateTransform = function () { - if (!this.visible) { +DisplayObjectContainer.prototype.updateTransform = function () +{ + if (!this.visible) + { return; } this.displayObjectUpdateTransform(); - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { return; } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } }; @@ -346,8 +389,10 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getBounds = function () { - if (this.children.length === 0) { +DisplayObjectContainer.prototype.getBounds = function () +{ + if (this.children.length === 0) + { return math.Rectangle.EMPTY; } @@ -365,10 +410,12 @@ var childVisible = false; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -386,7 +433,8 @@ maxY = maxY > childMaxY ? maxY : childMaxY; } - if (!childVisible) { + if (!childVisible) + { return math.Rectangle.EMPTY; } @@ -407,12 +455,14 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getLocalBounds = function () { +DisplayObjectContainer.prototype.getLocalBounds = function () +{ var matrixCache = this.worldTransform; this.worldTransform = math.Matrix.IDENTITY; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } @@ -428,13 +478,16 @@ * * @param renderer {WebGLRenderer} The renderer */ -DisplayObjectContainer.prototype.renderWebGL = function (renderer) { +DisplayObjectContainer.prototype.renderWebGL = function (renderer) +{ // if the object is not visible or the alpha is 0 then no need to render this element - if (!this.visible || this.alpha <= 0) { + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } @@ -442,14 +495,17 @@ var i, j; // do a quick check to see if this element has a mask or a filter. - if (this._mask || this._filters) { + if (this._mask || this._filters) + { // push filter first as we need to ensure the stencil buffer is correct for any masking - if (this._filters) { + if (this._filters) + { renderer.spriteBatch.flush(); renderer.filterManager.pushFilter(this._filterBlock); } - if (this._mask) { + if (this._mask) + { renderer.spriteBatch.stop(); renderer.maskManager.pushMask(this.mask, renderer); renderer.spriteBatch.start(); @@ -459,36 +515,42 @@ this._renderWebGL(renderer); // now loop through the children and make sure they get rendered - for (i = 0, j = this.children.length; i < j; i++) { + for (i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderWebGL(renderer); } // time to stop the sprite batch as either a mask element or a filter draw will happen next renderer.spriteBatch.stop(); - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(this._mask, renderer); } - if (this._filters) { + if (this._filters) + { renderer.filterManager.popFilter(); } renderer.spriteBatch.start(); } - else { + else + { this._renderWebGL(renderer); // simple render children! - for (i = 0, j = this.children.length; i < j; ++i) { + for (i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderWebGL(renderer); } } }; -DisplayObjectContainer.prototype._renderWebGL = function (renderer) { +DisplayObjectContainer.prototype._renderWebGL = function (renderer) +{ // this is where content itself gets renderd.. @@ -499,25 +561,31 @@ * * @param renderer {CanvasRenderer} The renderer */ -DisplayObjectContainer.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0) { +DisplayObjectContainer.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -528,13 +596,16 @@ * @param renderer {WebGLRenderer|CanvasRenderer} The renderer * @private */ -DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) { +DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) +{ this._cachedSprite.worldAlpha = this.worldAlpha; - if (renderer.gl) { + if (renderer.gl) + { this._cachedSprite.renderWebGL(renderer); } - else { + else + { this._cachedSprite.renderCanvas(renderer); } }; @@ -544,10 +615,12 @@ * * @private */ -DisplayObjectContainer.prototype._generateCachedSprite = function () { +DisplayObjectContainer.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { // TODO - RenderTexture now *requires* a renderer instance, so this is like broken // because `renderer` isn't actually in scope here :P var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0); @@ -555,7 +628,8 @@ this._cachedSprite = new Sprite(renderTexture); this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.texture.resize(bounds.width | 0, bounds.height | 0); } @@ -580,8 +654,10 @@ * * @private */ -DisplayObjectContainer.prototype._destroyCachedSprite = function () { - if (!this._cachedSprite) { +DisplayObjectContainer.prototype._destroyCachedSprite = function () +{ + if (!this._cachedSprite) + { return; } diff --git a/src/core/display/Sprite.js b/src/core/display/Sprite.js index 707da24..5862aef 100644 --- a/src/core/display/Sprite.js +++ b/src/core/display/Sprite.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param texture {Texture} The texture for this sprite */ -function Sprite(texture) { +function Sprite(texture) +{ DisplayObjectContainer.call(this); /** @@ -85,12 +86,14 @@ this.texture = texture || Texture.EMPTY; } -Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) { +Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) +{ DisplayObjectContainer.prototype.destroy.call(this); this.anchor = null; - if (destroyTexture) { + if (destroyTexture) + { this._texture.destroy(destroyBaseTexture); } @@ -111,10 +114,12 @@ * @memberof Sprite# */ width: { - get: function () { + get: function () + { return this.scale.x * this.texture.frame.width; }, - set: function (value) { + set: function (value) + { this.scale.x = value / this.texture.frame.width; this._width = value; } @@ -127,10 +132,12 @@ * @memberof Sprite# */ height: { - get: function () { + get: function () + { return this.scale.y * this.texture.frame.height; }, - set: function (value) { + set: function (value) + { this.scale.y = value / this.texture.frame.height; this._height = value; } @@ -143,23 +150,29 @@ * @memberof Sprite# */ texture: { - get: function () { + get: function () + { return this._texture; }, - set: function (value) { - if (this._texture === value) { + set: function (value) + { + if (this._texture === value) + { return; } this._texture = value; this.cachedTint = 0xFFFFFF; - if (value) { + if (value) + { // wait for the texture to load - if (value.baseTexture.hasLoaded) { + if (value.baseTexture.hasLoaded) + { this._onTextureUpdate(); } - else { + else + { value.once('update', this._onTextureUpdate.bind(this)); } } @@ -172,18 +185,22 @@ * * @private */ -Sprite.prototype._onTextureUpdate = function () { +Sprite.prototype._onTextureUpdate = function () +{ // so if _width is 0 then width was not set.. - if (this._width) { + if (this._width) + { this.scale.x = this._width / this.texture.frame.width; } - if (this._height) { + if (this._height) + { this.scale.y = this._height / this.texture.frame.height; } }; -Sprite.prototype._renderWebGL = function (renderer) { +Sprite.prototype._renderWebGL = function (renderer) +{ // this is where content gets renderd.. // watch this space for a little render state manager.. @@ -197,7 +214,8 @@ * @param matrix {Matrix} the transformation matrix of the sprite * @return {Rectangle} the framing rectangle */ -Sprite.prototype.getBounds = function (matrix) { +Sprite.prototype.getBounds = function (matrix) +{ var width = this.texture.frame.width; var height = this.texture.frame.height; @@ -224,11 +242,13 @@ if(b === 0 && c === 0) { // scale may be negative! - if (a < 0) { + if (a < 0) + { a *= -1; } - if (d < 0) { + if (d < 0) + { d *= -1; } @@ -293,28 +313,34 @@ * * @param renderer {CanvasRenderer} The renderer */ -Sprite.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) { +Sprite.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) + { return; } - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; renderer.context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } // Ignore null sources - if (this.texture.valid) { + if (this.texture.valid) + { var resolution = this.texture.baseTexture.resolution / renderer.resolution; renderer.context.globalAlpha = this.worldAlpha; // If smoothingEnabled is supported and we need to change the smoothing property for this texture - if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) { + if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) + { renderer.scaleMode = this.texture.baseTexture.scaleMode; renderer.context[renderer.smoothProperty] = (renderer.scaleMode === CONST.scaleModes.LINEAR); } @@ -324,7 +350,8 @@ var dy = (this.texture.trim ? this.texture.trim.y : 0) - (this.anchor.y * this.texture.trim.height); // Allow for pixel rounding - if (renderer.roundPixels) { + if (renderer.roundPixels) + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -337,7 +364,8 @@ dx = dx | 0; dy = dy | 0; } - else { + else + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -348,8 +376,10 @@ ); } - if (this.tint !== 0xFFFFFF) { - if (this.cachedTint !== this.tint) { + if (this.tint !== 0xFFFFFF) + { + if (this.cachedTint !== this.tint) + { this.cachedTint = this.tint; // TODO clean up caching - how to clean up the caches? @@ -368,7 +398,8 @@ this.texture.crop.height / resolution ); } - else { + else + { renderer.context.drawImage( this.texture.baseTexture.source, this.texture.crop.x, @@ -383,11 +414,13 @@ } } - for (var i = 0, j = this.children.length; i < j; i++) { + for (var i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -402,10 +435,12 @@ * @param frameId {String} The frame Id of the texture in the cache * @return {Sprite} A new Sprite using a texture from the texture cache matching the frameId */ -Sprite.fromFrame = function (frameId) { +Sprite.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache' + this); } @@ -420,6 +455,7 @@ * @param imageId {String} The image url of the texture * @return {Sprite} A new Sprite using a texture from the texture cache matching the image id */ -Sprite.fromImage = function (imageId, crossorigin, scaleMode) { +Sprite.fromImage = function (imageId, crossorigin, scaleMode) +{ return new Sprite(Texture.fromImage(imageId, crossorigin, scaleMode)); }; diff --git a/src/core/display/SpriteBatch.js b/src/core/display/SpriteBatch.js index 3187777..c196fef 100644 --- a/src/core/display/SpriteBatch.js +++ b/src/core/display/SpriteBatch.js @@ -12,7 +12,8 @@ * ```js * var container = new SpriteBatch(); * - * for(var i = 0; i < 100; ++i) { + * for(var i = 0; i < 100; ++i) + * { * var sprite = new PIXI.Sprite.fromImage("myImage.png"); * container.addChild(sprite); * } @@ -25,7 +26,8 @@ */ //TODO RENAME to PARTICLE CONTAINER? -function SpriteBatch() { +function SpriteBatch() +{ DisplayObjectContainer.call(this); } @@ -38,7 +40,8 @@ * * @private */ -SpriteBatch.prototype.updateTransform = function () { +SpriteBatch.prototype.updateTransform = function () +{ // TODO don't need to! this.displayObjectUpdateTransform(); // PIXI.DisplayObjectContainer.prototype.updateTransform.call( this ); @@ -50,8 +53,10 @@ * @param renderer {WebGLRenderer} The webgl renderer * @private */ -SpriteBatch.prototype.renderWebGL = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderWebGL = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -71,8 +76,10 @@ * @param renderer {CanvasRenderer} The canvas renderer * @private */ -SpriteBatch.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -84,10 +91,12 @@ this.displayObjectUpdateTransform(); - for (var i = 0; i < this.children.length; ++i) { + for (var i = 0; i < this.children.length; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -95,9 +104,11 @@ context.globalAlpha = this.worldAlpha * child.alpha; - if (child.rotation % (Math.PI * 2) === 0) { + if (child.rotation % (Math.PI * 2) === 0) + { // this is the fastest way to optimise! - if rotation is 0 then we can avoid any kind of setTransform call - if (isRotated) { + if (isRotated) + { context.setTransform( transform.a, transform.b, @@ -122,8 +133,10 @@ frame.height * child.scale.y ); } - else { - if (!isRotated) { + else + { + if (!isRotated) + { isRotated = true; } @@ -131,7 +144,8 @@ var childTransform = child.worldTransform; - if (renderer.roundPixels) { + if (renderer.roundPixels) + { context.setTransform( childTransform.a, childTransform.b, @@ -141,7 +155,8 @@ childTransform.ty | 0 ); } - else { + else + { context.setTransform( childTransform.a, childTransform.b, diff --git a/src/core/index.js b/src/core/index.js index 3954b6f..eb4a82b 100644 --- a/src/core/index.js +++ b/src/core/index.js @@ -58,11 +58,13 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRenderer: function (width, height, options, noWebGL) { + autoDetectRenderer: function (width, height, options, noWebGL) + { width = width || 800; height = height || 600; - if (!noWebGL && require('webgl-enabled')()) { + if (!noWebGL && require('webgl-enabled')()) + { return new core.WebGLRenderer(width, height, options); } @@ -87,7 +89,8 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRecommendedRenderer: function (width, height, options) { + autoDetectRecommendedRenderer: function (width, height, options) + { var isAndroid = /Android/i.test(navigator.userAgent); return core.autoDetectRenderer(width, height, options, isAndroid); diff --git a/src/core/math/Matrix.js b/src/core/math/Matrix.js index c2f87e2..2ff4848 100644 --- a/src/core/math/Matrix.js +++ b/src/core/math/Matrix.js @@ -10,7 +10,8 @@ * @class * @namespace PIXI */ -function Matrix() { +function Matrix() +{ /** * @member {number} * @default 1 @@ -63,7 +64,8 @@ * * @param array {number[]} The array that the matrix will be populated from. */ -Matrix.prototype.fromArray = function (array) { +Matrix.prototype.fromArray = function (array) +{ this.a = array[0]; this.b = array[1]; this.c = array[3]; @@ -78,14 +80,17 @@ * @param transpose {boolean} Whether we need to transpose the matrix or not * @return {number[]} the newly created array which contains the matrix */ -Matrix.prototype.toArray = function (transpose) { - if (!this.array) { +Matrix.prototype.toArray = function (transpose) +{ + if (!this.array) + { this.array = new Float32Array(9); } var array = this.array; - if (transpose) { + if (transpose) + { array[0] = this.a; array[1] = this.b; array[2] = 0; @@ -96,7 +101,8 @@ array[7] = this.ty; array[8] = 1; } - else { + else + { array[0] = this.a; array[1] = this.c; array[2] = this.tx; @@ -119,7 +125,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, transformed through this matrix */ -Matrix.prototype.apply = function (pos, newPos) { +Matrix.prototype.apply = function (pos, newPos) +{ newPos = newPos || new Point(); newPos.x = this.a * pos.x + this.c * pos.y + this.tx; @@ -136,7 +143,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, inverse-transformed through this matrix */ -Matrix.prototype.applyInverse = function (pos, newPos) { +Matrix.prototype.applyInverse = function (pos, newPos) +{ newPos = newPos || new Point(); var id = 1 / (this.a * this.d + this.c * -this.b); @@ -154,7 +162,8 @@ * @param {number} y * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.translate = function (x, y) { +Matrix.prototype.translate = function (x, y) +{ this.tx += x; this.ty += y; @@ -168,7 +177,8 @@ * @param {number} y The amount to scale vertically * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.scale = function (x, y) { +Matrix.prototype.scale = function (x, y) +{ this.a *= x; this.d *= y; this.c *= x; @@ -186,7 +196,8 @@ * @param {number} angle - The angle in radians. * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.rotate = function (angle) { +Matrix.prototype.rotate = function (angle) +{ var cos = Math.cos( angle ); var sin = Math.sin( angle ); @@ -210,7 +221,8 @@ * @param {Matrix} matrix * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.append = function (matrix) { +Matrix.prototype.append = function (matrix) +{ var a1 = this.a; var b1 = this.b; var c1 = this.c; @@ -232,7 +244,8 @@ * * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.identity = function () { +Matrix.prototype.identity = function () +{ this.a = 1; this.b = 0; this.c = 0; diff --git a/src/core/math/Point.js b/src/core/math/Point.js index 7565b2d..632f346 100644 --- a/src/core/math/Point.js +++ b/src/core/math/Point.js @@ -7,7 +7,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -function Point(x, y) { +function Point(x, y) +{ /** * @member {number} * @default 0 @@ -29,7 +30,8 @@ * * @return {Point} a copy of the point */ -Point.prototype.clone = function () { +Point.prototype.clone = function () +{ return new Point(this.x, this.y); }; @@ -40,7 +42,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -Point.prototype.set = function (x, y) { +Point.prototype.set = function (x, y) +{ this.x = x || 0; this.y = y || ( (y !== 0) ? this.x : 0 ) ; }; diff --git a/src/core/display/DisplayObject.js b/src/core/display/DisplayObject.js index 66ebc3c..20e778c 100644 --- a/src/core/display/DisplayObject.js +++ b/src/core/display/DisplayObject.js @@ -7,7 +7,8 @@ * @class * @namespace PIXI */ -function DisplayObject() { +function DisplayObject() +{ /** * The coordinate of the object relative to the local coordinates of the parent. * @@ -152,10 +153,12 @@ * @memberof DisplayObject# */ x: { - get: function () { + get: function () + { return this.position.x; }, - set: function (value) { + set: function (value) + { this.position.x = value; } }, @@ -167,10 +170,12 @@ * @memberof DisplayObject# */ y: { - get: function () { + get: function () + { return this.position.y; }, - set: function (value) { + set: function (value) + { this.position.y = value; } }, @@ -183,11 +188,13 @@ * @readonly */ worldVisible: { - get: function () { + get: function () + { var item = this; do { - if (!item.visible) { + if (!item.visible) + { return false; } @@ -207,17 +214,21 @@ * @memberof DisplayObject# */ mask: { - get: function () { + get: function () + { return this._mask; }, - set: function (value) { - if (this._mask) { + set: function (value) + { + if (this._mask) + { this._mask.isMask = false; } this._mask = value; - if (this._mask) { + if (this._mask) + { this._mask.isMask = true; } } @@ -232,18 +243,23 @@ * @memberof DisplayObject# */ filters: { - get: function () { + get: function () + { return this._filters; }, - set: function (value) { - if (value) { + set: function (value) + { + if (value) + { // now put all the passes in one place.. var passes = []; - for (var i = 0; i < value.length; i++) { + for (var i = 0; i < value.length; i++) + { var filterPasses = value[i].passes; - for (var j = 0; j < filterPasses.length; j++) { + for (var j = 0; j < filterPasses.length; j++) + { passes.push(filterPasses[j]); } } @@ -264,8 +280,9 @@ * * @private */ -DisplayObject.prototype.updateTransform = function () { - +DisplayObject.prototype.updateTransform = function () +{ + // create some matrix refs for easy access var pt = this.parent.worldTransform; var wt = this.worldTransform; @@ -274,9 +291,11 @@ var a, b, c, d, tx, ty; // so if rotation is between 0 then we can simplify the multiplication process.. - if (this.rotation % math.PI_2) { + if (this.rotation % math.PI_2) + { // 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) { + if (this.rotation !== this.rotationCache) + { this.rotationCache = this.rotation; this._sr = Math.sin(this.rotation); this._cr = Math.cos(this.rotation); @@ -291,7 +310,8 @@ ty = this.position.y; // check for pivot.. not often used so geared towards that fact! - if (this.pivot.x || this.pivot.y) { + 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; } @@ -304,7 +324,8 @@ wt.tx = tx * pt.a + ty * pt.c + pt.tx; wt.ty = tx * pt.b + ty * pt.d + pt.ty; } - else { + else + { // lets do the fast version as we know there is no rotation.. a = this.scale.x; d = this.scale.y; @@ -333,7 +354,8 @@ * @param matrix {Matrix} * @return {Rectangle} the rectangular bounding area */ -DisplayObject.prototype.getBounds = function (/* matrix */) { +DisplayObject.prototype.getBounds = function (/* matrix */) +{ return math.Rectangle.EMPTY; }; @@ -342,7 +364,8 @@ * * @return {Rectangle} the rectangular bounding area */ -DisplayObject.prototype.getLocalBounds = function () { +DisplayObject.prototype.getLocalBounds = function () +{ return this.getBounds(math.Matrix.IDENTITY); }; @@ -352,7 +375,8 @@ * @param position {Point} The world origin to calculate from * @return {Point} A point object representing the position of this object */ -DisplayObject.prototype.toGlobal = function (position) { +DisplayObject.prototype.toGlobal = function (position) +{ // don't need to u[date the lot this.displayObjectUpdateTransform(); return this.worldTransform.apply(position); @@ -365,8 +389,10 @@ * @param [from] {DisplayObject} The DisplayObject to calculate the global position from * @return {Point} A point object representing the position of this object */ -DisplayObject.prototype.toLocal = function (position, from) { - if (from) { +DisplayObject.prototype.toLocal = function (position, from) +{ + if (from) + { position = from.toGlobal(position); } @@ -381,7 +407,8 @@ * @param renderer {WebGLRenderer} The renderer * @private */ -DisplayObject.prototype.renderWebGL = function (/* renderer */) { +DisplayObject.prototype.renderWebGL = function (/* renderer */) +{ // OVERWRITE; }; @@ -391,6 +418,7 @@ * @param renderer {CanvasRenderer} The renderer * @private */ -DisplayObject.prototype.renderCanvas = function (/* renderer */) { +DisplayObject.prototype.renderCanvas = function (/* renderer */) +{ // OVERWRITE; }; diff --git a/src/core/display/DisplayObjectContainer.js b/src/core/display/DisplayObjectContainer.js index 689f40b..4625ee8 100644 --- a/src/core/display/DisplayObjectContainer.js +++ b/src/core/display/DisplayObjectContainer.js @@ -12,7 +12,8 @@ * @extends DisplayObject * @namespace PIXI */ -function DisplayObjectContainer() { +function DisplayObjectContainer() +{ DisplayObject.call(this); /** @@ -47,17 +48,21 @@ * @memberof DisplayObjectContainer# */ width: { - get: function () { + get: function () + { return this.scale.x * this.getLocalBounds().width; }, - set: function (value) { + set: function (value) + { var width = this.getLocalBounds().width; - if(width !== 0) { + if(width !== 0) + { this.scale.x = value / width; } - else { + else + { this.scale.x = 1; } @@ -73,17 +78,21 @@ * @memberof DisplayObjectContainer# */ height: { - get: function () { + get: function () + { return this.scale.y * this.getLocalBounds().height; }, - set: function (value) { + set: function (value) + { var height = this.getLocalBounds().height; - if (height !== 0) { + if (height !== 0) + { this.scale.y = value / height ; } - else { + else + { this.scale.y = 1; } @@ -100,18 +109,23 @@ * @memberof DisplayObject# */ cacheAsBitmap: { - get: function () { + get: function () + { return this._cacheAsBitmap; }, - set: function (value) { - if (this._cacheAsBitmap === value) { + set: function (value) + { + if (this._cacheAsBitmap === value) + { return; } - if (value) { + if (value) + { this._generateCachedSprite(); } - else { + else + { this._destroyCachedSprite(); } @@ -126,7 +140,8 @@ * @param child {DisplayObject} The DisplayObject to add to the container * @return {DisplayObject} The child that was added. */ -DisplayObjectContainer.prototype.addChild = function (child) { +DisplayObjectContainer.prototype.addChild = function (child) +{ return this.addChildAt(child, this.children.length); }; @@ -137,14 +152,18 @@ * @param index {Number} The index to place the child in * @return {DisplayObject} The child that was added. */ -DisplayObjectContainer.prototype.addChildAt = function (child, index) { +DisplayObjectContainer.prototype.addChildAt = function (child, index) +{ // prevent adding self as child - if (child === this) { + if (child === this) + { return; } - if (index >= 0 && index <= this.children.length) { - if (child.parent) { + if (index >= 0 && index <= this.children.length) + { + if (child.parent) + { child.parent.removeChild(child); } @@ -154,7 +173,8 @@ return child; } - else { + else + { throw new Error(child + 'addChildAt: The index '+ index +' supplied is out of bounds ' + this.children.length); } }; @@ -165,15 +185,18 @@ * @param child {DisplayObject} * @param child2 {DisplayObject} */ -DisplayObjectContainer.prototype.swapChildren = function (child, child2) { - if (child === child2) { +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) { + if (index1 < 0 || index2 < 0) + { throw new Error('swapChildren: Both the supplied DisplayObjects must be a child of the caller.'); } @@ -187,10 +210,12 @@ * @param child {DisplayObject} The DisplayObject instance to identify * @return {Number} The index position of the child display object to identify */ -DisplayObjectContainer.prototype.getChildIndex = function (child) { +DisplayObjectContainer.prototype.getChildIndex = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { throw new Error('The supplied DisplayObject must be a child of the caller'); } @@ -203,8 +228,10 @@ * @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 */ -DisplayObjectContainer.prototype.setChildIndex = function (child, index) { - if (index < 0 || index >= this.children.length) { +DisplayObjectContainer.prototype.setChildIndex = function (child, index) +{ + if (index < 0 || index >= this.children.length) + { throw new Error('The supplied index is out of bounds'); } @@ -220,8 +247,10 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child at the given index, if any. */ -DisplayObjectContainer.prototype.getChildAt = function (index) { - if (index < 0 || index >= this.children.length) { +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'); } @@ -234,10 +263,12 @@ * @param child {DisplayObject} The DisplayObject to remove * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChild = function (child) { +DisplayObjectContainer.prototype.removeChild = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { return; } @@ -250,7 +281,8 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChildAt = function (index) { +DisplayObjectContainer.prototype.removeChildAt = function (index) +{ var child = this.getChildAt(index); child.parent = null; @@ -265,24 +297,29 @@ * @param beginIndex {Number} The beginning position. Default value is 0. * @param endIndex {Number} The ending position. Default value is size of the container. */ -DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) { +DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) +{ var begin = beginIndex || 0; var end = typeof endIndex === 'number' ? endIndex : this.children.length; var range = end - begin; - if (range > 0 && range <= end) { + if (range > 0 && range <= end) + { var removed = this.children.splice(begin, range); - for (var i = 0; i < removed.length; ++i) { + for (var i = 0; i < removed.length; ++i) + { removed[i].parent = null; } return removed; } - else if (range === 0 && this.children.length === 0) { + else if (range === 0 && this.children.length === 0) + { return []; } - else { + else + { throw new RangeError('removeChildren: numeric values are outside the acceptable range.'); } }; @@ -291,7 +328,8 @@ * Generates and updates the cached sprite for this object. * */ -DisplayObjectContainer.prototype.updateCachedSprite = function () { +DisplayObjectContainer.prototype.updateCachedSprite = function () +{ this._generateCachedSprite(); }; @@ -304,7 +342,8 @@ * @param renderer {CanvasRenderer|WebGLRenderer} The renderer used to generate the texture. * @return {Texture} a texture of the graphics object */ -DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) { +DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) +{ var bounds = this.getLocalBounds(); var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0, renderer, scaleMode, resolution); @@ -322,18 +361,22 @@ * * @private */ -DisplayObjectContainer.prototype.updateTransform = function () { - if (!this.visible) { +DisplayObjectContainer.prototype.updateTransform = function () +{ + if (!this.visible) + { return; } this.displayObjectUpdateTransform(); - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { return; } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } }; @@ -346,8 +389,10 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getBounds = function () { - if (this.children.length === 0) { +DisplayObjectContainer.prototype.getBounds = function () +{ + if (this.children.length === 0) + { return math.Rectangle.EMPTY; } @@ -365,10 +410,12 @@ var childVisible = false; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -386,7 +433,8 @@ maxY = maxY > childMaxY ? maxY : childMaxY; } - if (!childVisible) { + if (!childVisible) + { return math.Rectangle.EMPTY; } @@ -407,12 +455,14 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getLocalBounds = function () { +DisplayObjectContainer.prototype.getLocalBounds = function () +{ var matrixCache = this.worldTransform; this.worldTransform = math.Matrix.IDENTITY; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } @@ -428,13 +478,16 @@ * * @param renderer {WebGLRenderer} The renderer */ -DisplayObjectContainer.prototype.renderWebGL = function (renderer) { +DisplayObjectContainer.prototype.renderWebGL = function (renderer) +{ // if the object is not visible or the alpha is 0 then no need to render this element - if (!this.visible || this.alpha <= 0) { + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } @@ -442,14 +495,17 @@ var i, j; // do a quick check to see if this element has a mask or a filter. - if (this._mask || this._filters) { + if (this._mask || this._filters) + { // push filter first as we need to ensure the stencil buffer is correct for any masking - if (this._filters) { + if (this._filters) + { renderer.spriteBatch.flush(); renderer.filterManager.pushFilter(this._filterBlock); } - if (this._mask) { + if (this._mask) + { renderer.spriteBatch.stop(); renderer.maskManager.pushMask(this.mask, renderer); renderer.spriteBatch.start(); @@ -459,36 +515,42 @@ this._renderWebGL(renderer); // now loop through the children and make sure they get rendered - for (i = 0, j = this.children.length; i < j; i++) { + for (i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderWebGL(renderer); } // time to stop the sprite batch as either a mask element or a filter draw will happen next renderer.spriteBatch.stop(); - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(this._mask, renderer); } - if (this._filters) { + if (this._filters) + { renderer.filterManager.popFilter(); } renderer.spriteBatch.start(); } - else { + else + { this._renderWebGL(renderer); // simple render children! - for (i = 0, j = this.children.length; i < j; ++i) { + for (i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderWebGL(renderer); } } }; -DisplayObjectContainer.prototype._renderWebGL = function (renderer) { +DisplayObjectContainer.prototype._renderWebGL = function (renderer) +{ // this is where content itself gets renderd.. @@ -499,25 +561,31 @@ * * @param renderer {CanvasRenderer} The renderer */ -DisplayObjectContainer.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0) { +DisplayObjectContainer.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -528,13 +596,16 @@ * @param renderer {WebGLRenderer|CanvasRenderer} The renderer * @private */ -DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) { +DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) +{ this._cachedSprite.worldAlpha = this.worldAlpha; - if (renderer.gl) { + if (renderer.gl) + { this._cachedSprite.renderWebGL(renderer); } - else { + else + { this._cachedSprite.renderCanvas(renderer); } }; @@ -544,10 +615,12 @@ * * @private */ -DisplayObjectContainer.prototype._generateCachedSprite = function () { +DisplayObjectContainer.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { // TODO - RenderTexture now *requires* a renderer instance, so this is like broken // because `renderer` isn't actually in scope here :P var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0); @@ -555,7 +628,8 @@ this._cachedSprite = new Sprite(renderTexture); this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.texture.resize(bounds.width | 0, bounds.height | 0); } @@ -580,8 +654,10 @@ * * @private */ -DisplayObjectContainer.prototype._destroyCachedSprite = function () { - if (!this._cachedSprite) { +DisplayObjectContainer.prototype._destroyCachedSprite = function () +{ + if (!this._cachedSprite) + { return; } diff --git a/src/core/display/Sprite.js b/src/core/display/Sprite.js index 707da24..5862aef 100644 --- a/src/core/display/Sprite.js +++ b/src/core/display/Sprite.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param texture {Texture} The texture for this sprite */ -function Sprite(texture) { +function Sprite(texture) +{ DisplayObjectContainer.call(this); /** @@ -85,12 +86,14 @@ this.texture = texture || Texture.EMPTY; } -Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) { +Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) +{ DisplayObjectContainer.prototype.destroy.call(this); this.anchor = null; - if (destroyTexture) { + if (destroyTexture) + { this._texture.destroy(destroyBaseTexture); } @@ -111,10 +114,12 @@ * @memberof Sprite# */ width: { - get: function () { + get: function () + { return this.scale.x * this.texture.frame.width; }, - set: function (value) { + set: function (value) + { this.scale.x = value / this.texture.frame.width; this._width = value; } @@ -127,10 +132,12 @@ * @memberof Sprite# */ height: { - get: function () { + get: function () + { return this.scale.y * this.texture.frame.height; }, - set: function (value) { + set: function (value) + { this.scale.y = value / this.texture.frame.height; this._height = value; } @@ -143,23 +150,29 @@ * @memberof Sprite# */ texture: { - get: function () { + get: function () + { return this._texture; }, - set: function (value) { - if (this._texture === value) { + set: function (value) + { + if (this._texture === value) + { return; } this._texture = value; this.cachedTint = 0xFFFFFF; - if (value) { + if (value) + { // wait for the texture to load - if (value.baseTexture.hasLoaded) { + if (value.baseTexture.hasLoaded) + { this._onTextureUpdate(); } - else { + else + { value.once('update', this._onTextureUpdate.bind(this)); } } @@ -172,18 +185,22 @@ * * @private */ -Sprite.prototype._onTextureUpdate = function () { +Sprite.prototype._onTextureUpdate = function () +{ // so if _width is 0 then width was not set.. - if (this._width) { + if (this._width) + { this.scale.x = this._width / this.texture.frame.width; } - if (this._height) { + if (this._height) + { this.scale.y = this._height / this.texture.frame.height; } }; -Sprite.prototype._renderWebGL = function (renderer) { +Sprite.prototype._renderWebGL = function (renderer) +{ // this is where content gets renderd.. // watch this space for a little render state manager.. @@ -197,7 +214,8 @@ * @param matrix {Matrix} the transformation matrix of the sprite * @return {Rectangle} the framing rectangle */ -Sprite.prototype.getBounds = function (matrix) { +Sprite.prototype.getBounds = function (matrix) +{ var width = this.texture.frame.width; var height = this.texture.frame.height; @@ -224,11 +242,13 @@ if(b === 0 && c === 0) { // scale may be negative! - if (a < 0) { + if (a < 0) + { a *= -1; } - if (d < 0) { + if (d < 0) + { d *= -1; } @@ -293,28 +313,34 @@ * * @param renderer {CanvasRenderer} The renderer */ -Sprite.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) { +Sprite.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) + { return; } - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; renderer.context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } // Ignore null sources - if (this.texture.valid) { + if (this.texture.valid) + { var resolution = this.texture.baseTexture.resolution / renderer.resolution; renderer.context.globalAlpha = this.worldAlpha; // If smoothingEnabled is supported and we need to change the smoothing property for this texture - if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) { + if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) + { renderer.scaleMode = this.texture.baseTexture.scaleMode; renderer.context[renderer.smoothProperty] = (renderer.scaleMode === CONST.scaleModes.LINEAR); } @@ -324,7 +350,8 @@ var dy = (this.texture.trim ? this.texture.trim.y : 0) - (this.anchor.y * this.texture.trim.height); // Allow for pixel rounding - if (renderer.roundPixels) { + if (renderer.roundPixels) + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -337,7 +364,8 @@ dx = dx | 0; dy = dy | 0; } - else { + else + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -348,8 +376,10 @@ ); } - if (this.tint !== 0xFFFFFF) { - if (this.cachedTint !== this.tint) { + if (this.tint !== 0xFFFFFF) + { + if (this.cachedTint !== this.tint) + { this.cachedTint = this.tint; // TODO clean up caching - how to clean up the caches? @@ -368,7 +398,8 @@ this.texture.crop.height / resolution ); } - else { + else + { renderer.context.drawImage( this.texture.baseTexture.source, this.texture.crop.x, @@ -383,11 +414,13 @@ } } - for (var i = 0, j = this.children.length; i < j; i++) { + for (var i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -402,10 +435,12 @@ * @param frameId {String} The frame Id of the texture in the cache * @return {Sprite} A new Sprite using a texture from the texture cache matching the frameId */ -Sprite.fromFrame = function (frameId) { +Sprite.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache' + this); } @@ -420,6 +455,7 @@ * @param imageId {String} The image url of the texture * @return {Sprite} A new Sprite using a texture from the texture cache matching the image id */ -Sprite.fromImage = function (imageId, crossorigin, scaleMode) { +Sprite.fromImage = function (imageId, crossorigin, scaleMode) +{ return new Sprite(Texture.fromImage(imageId, crossorigin, scaleMode)); }; diff --git a/src/core/display/SpriteBatch.js b/src/core/display/SpriteBatch.js index 3187777..c196fef 100644 --- a/src/core/display/SpriteBatch.js +++ b/src/core/display/SpriteBatch.js @@ -12,7 +12,8 @@ * ```js * var container = new SpriteBatch(); * - * for(var i = 0; i < 100; ++i) { + * for(var i = 0; i < 100; ++i) + * { * var sprite = new PIXI.Sprite.fromImage("myImage.png"); * container.addChild(sprite); * } @@ -25,7 +26,8 @@ */ //TODO RENAME to PARTICLE CONTAINER? -function SpriteBatch() { +function SpriteBatch() +{ DisplayObjectContainer.call(this); } @@ -38,7 +40,8 @@ * * @private */ -SpriteBatch.prototype.updateTransform = function () { +SpriteBatch.prototype.updateTransform = function () +{ // TODO don't need to! this.displayObjectUpdateTransform(); // PIXI.DisplayObjectContainer.prototype.updateTransform.call( this ); @@ -50,8 +53,10 @@ * @param renderer {WebGLRenderer} The webgl renderer * @private */ -SpriteBatch.prototype.renderWebGL = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderWebGL = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -71,8 +76,10 @@ * @param renderer {CanvasRenderer} The canvas renderer * @private */ -SpriteBatch.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -84,10 +91,12 @@ this.displayObjectUpdateTransform(); - for (var i = 0; i < this.children.length; ++i) { + for (var i = 0; i < this.children.length; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -95,9 +104,11 @@ context.globalAlpha = this.worldAlpha * child.alpha; - if (child.rotation % (Math.PI * 2) === 0) { + if (child.rotation % (Math.PI * 2) === 0) + { // this is the fastest way to optimise! - if rotation is 0 then we can avoid any kind of setTransform call - if (isRotated) { + if (isRotated) + { context.setTransform( transform.a, transform.b, @@ -122,8 +133,10 @@ frame.height * child.scale.y ); } - else { - if (!isRotated) { + else + { + if (!isRotated) + { isRotated = true; } @@ -131,7 +144,8 @@ var childTransform = child.worldTransform; - if (renderer.roundPixels) { + if (renderer.roundPixels) + { context.setTransform( childTransform.a, childTransform.b, @@ -141,7 +155,8 @@ childTransform.ty | 0 ); } - else { + else + { context.setTransform( childTransform.a, childTransform.b, diff --git a/src/core/index.js b/src/core/index.js index 3954b6f..eb4a82b 100644 --- a/src/core/index.js +++ b/src/core/index.js @@ -58,11 +58,13 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRenderer: function (width, height, options, noWebGL) { + autoDetectRenderer: function (width, height, options, noWebGL) + { width = width || 800; height = height || 600; - if (!noWebGL && require('webgl-enabled')()) { + if (!noWebGL && require('webgl-enabled')()) + { return new core.WebGLRenderer(width, height, options); } @@ -87,7 +89,8 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRecommendedRenderer: function (width, height, options) { + autoDetectRecommendedRenderer: function (width, height, options) + { var isAndroid = /Android/i.test(navigator.userAgent); return core.autoDetectRenderer(width, height, options, isAndroid); diff --git a/src/core/math/Matrix.js b/src/core/math/Matrix.js index c2f87e2..2ff4848 100644 --- a/src/core/math/Matrix.js +++ b/src/core/math/Matrix.js @@ -10,7 +10,8 @@ * @class * @namespace PIXI */ -function Matrix() { +function Matrix() +{ /** * @member {number} * @default 1 @@ -63,7 +64,8 @@ * * @param array {number[]} The array that the matrix will be populated from. */ -Matrix.prototype.fromArray = function (array) { +Matrix.prototype.fromArray = function (array) +{ this.a = array[0]; this.b = array[1]; this.c = array[3]; @@ -78,14 +80,17 @@ * @param transpose {boolean} Whether we need to transpose the matrix or not * @return {number[]} the newly created array which contains the matrix */ -Matrix.prototype.toArray = function (transpose) { - if (!this.array) { +Matrix.prototype.toArray = function (transpose) +{ + if (!this.array) + { this.array = new Float32Array(9); } var array = this.array; - if (transpose) { + if (transpose) + { array[0] = this.a; array[1] = this.b; array[2] = 0; @@ -96,7 +101,8 @@ array[7] = this.ty; array[8] = 1; } - else { + else + { array[0] = this.a; array[1] = this.c; array[2] = this.tx; @@ -119,7 +125,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, transformed through this matrix */ -Matrix.prototype.apply = function (pos, newPos) { +Matrix.prototype.apply = function (pos, newPos) +{ newPos = newPos || new Point(); newPos.x = this.a * pos.x + this.c * pos.y + this.tx; @@ -136,7 +143,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, inverse-transformed through this matrix */ -Matrix.prototype.applyInverse = function (pos, newPos) { +Matrix.prototype.applyInverse = function (pos, newPos) +{ newPos = newPos || new Point(); var id = 1 / (this.a * this.d + this.c * -this.b); @@ -154,7 +162,8 @@ * @param {number} y * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.translate = function (x, y) { +Matrix.prototype.translate = function (x, y) +{ this.tx += x; this.ty += y; @@ -168,7 +177,8 @@ * @param {number} y The amount to scale vertically * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.scale = function (x, y) { +Matrix.prototype.scale = function (x, y) +{ this.a *= x; this.d *= y; this.c *= x; @@ -186,7 +196,8 @@ * @param {number} angle - The angle in radians. * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.rotate = function (angle) { +Matrix.prototype.rotate = function (angle) +{ var cos = Math.cos( angle ); var sin = Math.sin( angle ); @@ -210,7 +221,8 @@ * @param {Matrix} matrix * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.append = function (matrix) { +Matrix.prototype.append = function (matrix) +{ var a1 = this.a; var b1 = this.b; var c1 = this.c; @@ -232,7 +244,8 @@ * * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.identity = function () { +Matrix.prototype.identity = function () +{ this.a = 1; this.b = 0; this.c = 0; diff --git a/src/core/math/Point.js b/src/core/math/Point.js index 7565b2d..632f346 100644 --- a/src/core/math/Point.js +++ b/src/core/math/Point.js @@ -7,7 +7,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -function Point(x, y) { +function Point(x, y) +{ /** * @member {number} * @default 0 @@ -29,7 +30,8 @@ * * @return {Point} a copy of the point */ -Point.prototype.clone = function () { +Point.prototype.clone = function () +{ return new Point(this.x, this.y); }; @@ -40,7 +42,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -Point.prototype.set = function (x, y) { +Point.prototype.set = function (x, y) +{ this.x = x || 0; this.y = y || ( (y !== 0) ? this.x : 0 ) ; }; diff --git a/src/core/math/shapes/Circle.js b/src/core/math/shapes/Circle.js index 69cfdc9..4d76efc 100644 --- a/src/core/math/shapes/Circle.js +++ b/src/core/math/shapes/Circle.js @@ -10,7 +10,8 @@ * @param y {number} The Y coordinate of the center of this circle * @param radius {number} The radius of the circle */ -function Circle(x, y, radius) { +function Circle(x, y, radius) +{ /** * @member {number} * @default 0 @@ -46,7 +47,8 @@ * @method clone * @return {Circle} a copy of the Circle */ -Circle.prototype.clone = function () { +Circle.prototype.clone = function () +{ return new Circle(this.x, this.y, this.radius); }; @@ -58,8 +60,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Circle */ -Circle.prototype.contains = function (x, y) { - if (this.radius <= 0) { +Circle.prototype.contains = function (x, y) +{ + if (this.radius <= 0) + { return false; } @@ -79,6 +83,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Circle.prototype.getBounds = function () { +Circle.prototype.getBounds = function () +{ return new Rectangle(this.x - this.radius, this.y - this.radius, this.radius * 2, this.radius * 2); }; diff --git a/src/core/display/DisplayObject.js b/src/core/display/DisplayObject.js index 66ebc3c..20e778c 100644 --- a/src/core/display/DisplayObject.js +++ b/src/core/display/DisplayObject.js @@ -7,7 +7,8 @@ * @class * @namespace PIXI */ -function DisplayObject() { +function DisplayObject() +{ /** * The coordinate of the object relative to the local coordinates of the parent. * @@ -152,10 +153,12 @@ * @memberof DisplayObject# */ x: { - get: function () { + get: function () + { return this.position.x; }, - set: function (value) { + set: function (value) + { this.position.x = value; } }, @@ -167,10 +170,12 @@ * @memberof DisplayObject# */ y: { - get: function () { + get: function () + { return this.position.y; }, - set: function (value) { + set: function (value) + { this.position.y = value; } }, @@ -183,11 +188,13 @@ * @readonly */ worldVisible: { - get: function () { + get: function () + { var item = this; do { - if (!item.visible) { + if (!item.visible) + { return false; } @@ -207,17 +214,21 @@ * @memberof DisplayObject# */ mask: { - get: function () { + get: function () + { return this._mask; }, - set: function (value) { - if (this._mask) { + set: function (value) + { + if (this._mask) + { this._mask.isMask = false; } this._mask = value; - if (this._mask) { + if (this._mask) + { this._mask.isMask = true; } } @@ -232,18 +243,23 @@ * @memberof DisplayObject# */ filters: { - get: function () { + get: function () + { return this._filters; }, - set: function (value) { - if (value) { + set: function (value) + { + if (value) + { // now put all the passes in one place.. var passes = []; - for (var i = 0; i < value.length; i++) { + for (var i = 0; i < value.length; i++) + { var filterPasses = value[i].passes; - for (var j = 0; j < filterPasses.length; j++) { + for (var j = 0; j < filterPasses.length; j++) + { passes.push(filterPasses[j]); } } @@ -264,8 +280,9 @@ * * @private */ -DisplayObject.prototype.updateTransform = function () { - +DisplayObject.prototype.updateTransform = function () +{ + // create some matrix refs for easy access var pt = this.parent.worldTransform; var wt = this.worldTransform; @@ -274,9 +291,11 @@ var a, b, c, d, tx, ty; // so if rotation is between 0 then we can simplify the multiplication process.. - if (this.rotation % math.PI_2) { + if (this.rotation % math.PI_2) + { // 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) { + if (this.rotation !== this.rotationCache) + { this.rotationCache = this.rotation; this._sr = Math.sin(this.rotation); this._cr = Math.cos(this.rotation); @@ -291,7 +310,8 @@ ty = this.position.y; // check for pivot.. not often used so geared towards that fact! - if (this.pivot.x || this.pivot.y) { + 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; } @@ -304,7 +324,8 @@ wt.tx = tx * pt.a + ty * pt.c + pt.tx; wt.ty = tx * pt.b + ty * pt.d + pt.ty; } - else { + else + { // lets do the fast version as we know there is no rotation.. a = this.scale.x; d = this.scale.y; @@ -333,7 +354,8 @@ * @param matrix {Matrix} * @return {Rectangle} the rectangular bounding area */ -DisplayObject.prototype.getBounds = function (/* matrix */) { +DisplayObject.prototype.getBounds = function (/* matrix */) +{ return math.Rectangle.EMPTY; }; @@ -342,7 +364,8 @@ * * @return {Rectangle} the rectangular bounding area */ -DisplayObject.prototype.getLocalBounds = function () { +DisplayObject.prototype.getLocalBounds = function () +{ return this.getBounds(math.Matrix.IDENTITY); }; @@ -352,7 +375,8 @@ * @param position {Point} The world origin to calculate from * @return {Point} A point object representing the position of this object */ -DisplayObject.prototype.toGlobal = function (position) { +DisplayObject.prototype.toGlobal = function (position) +{ // don't need to u[date the lot this.displayObjectUpdateTransform(); return this.worldTransform.apply(position); @@ -365,8 +389,10 @@ * @param [from] {DisplayObject} The DisplayObject to calculate the global position from * @return {Point} A point object representing the position of this object */ -DisplayObject.prototype.toLocal = function (position, from) { - if (from) { +DisplayObject.prototype.toLocal = function (position, from) +{ + if (from) + { position = from.toGlobal(position); } @@ -381,7 +407,8 @@ * @param renderer {WebGLRenderer} The renderer * @private */ -DisplayObject.prototype.renderWebGL = function (/* renderer */) { +DisplayObject.prototype.renderWebGL = function (/* renderer */) +{ // OVERWRITE; }; @@ -391,6 +418,7 @@ * @param renderer {CanvasRenderer} The renderer * @private */ -DisplayObject.prototype.renderCanvas = function (/* renderer */) { +DisplayObject.prototype.renderCanvas = function (/* renderer */) +{ // OVERWRITE; }; diff --git a/src/core/display/DisplayObjectContainer.js b/src/core/display/DisplayObjectContainer.js index 689f40b..4625ee8 100644 --- a/src/core/display/DisplayObjectContainer.js +++ b/src/core/display/DisplayObjectContainer.js @@ -12,7 +12,8 @@ * @extends DisplayObject * @namespace PIXI */ -function DisplayObjectContainer() { +function DisplayObjectContainer() +{ DisplayObject.call(this); /** @@ -47,17 +48,21 @@ * @memberof DisplayObjectContainer# */ width: { - get: function () { + get: function () + { return this.scale.x * this.getLocalBounds().width; }, - set: function (value) { + set: function (value) + { var width = this.getLocalBounds().width; - if(width !== 0) { + if(width !== 0) + { this.scale.x = value / width; } - else { + else + { this.scale.x = 1; } @@ -73,17 +78,21 @@ * @memberof DisplayObjectContainer# */ height: { - get: function () { + get: function () + { return this.scale.y * this.getLocalBounds().height; }, - set: function (value) { + set: function (value) + { var height = this.getLocalBounds().height; - if (height !== 0) { + if (height !== 0) + { this.scale.y = value / height ; } - else { + else + { this.scale.y = 1; } @@ -100,18 +109,23 @@ * @memberof DisplayObject# */ cacheAsBitmap: { - get: function () { + get: function () + { return this._cacheAsBitmap; }, - set: function (value) { - if (this._cacheAsBitmap === value) { + set: function (value) + { + if (this._cacheAsBitmap === value) + { return; } - if (value) { + if (value) + { this._generateCachedSprite(); } - else { + else + { this._destroyCachedSprite(); } @@ -126,7 +140,8 @@ * @param child {DisplayObject} The DisplayObject to add to the container * @return {DisplayObject} The child that was added. */ -DisplayObjectContainer.prototype.addChild = function (child) { +DisplayObjectContainer.prototype.addChild = function (child) +{ return this.addChildAt(child, this.children.length); }; @@ -137,14 +152,18 @@ * @param index {Number} The index to place the child in * @return {DisplayObject} The child that was added. */ -DisplayObjectContainer.prototype.addChildAt = function (child, index) { +DisplayObjectContainer.prototype.addChildAt = function (child, index) +{ // prevent adding self as child - if (child === this) { + if (child === this) + { return; } - if (index >= 0 && index <= this.children.length) { - if (child.parent) { + if (index >= 0 && index <= this.children.length) + { + if (child.parent) + { child.parent.removeChild(child); } @@ -154,7 +173,8 @@ return child; } - else { + else + { throw new Error(child + 'addChildAt: The index '+ index +' supplied is out of bounds ' + this.children.length); } }; @@ -165,15 +185,18 @@ * @param child {DisplayObject} * @param child2 {DisplayObject} */ -DisplayObjectContainer.prototype.swapChildren = function (child, child2) { - if (child === child2) { +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) { + if (index1 < 0 || index2 < 0) + { throw new Error('swapChildren: Both the supplied DisplayObjects must be a child of the caller.'); } @@ -187,10 +210,12 @@ * @param child {DisplayObject} The DisplayObject instance to identify * @return {Number} The index position of the child display object to identify */ -DisplayObjectContainer.prototype.getChildIndex = function (child) { +DisplayObjectContainer.prototype.getChildIndex = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { throw new Error('The supplied DisplayObject must be a child of the caller'); } @@ -203,8 +228,10 @@ * @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 */ -DisplayObjectContainer.prototype.setChildIndex = function (child, index) { - if (index < 0 || index >= this.children.length) { +DisplayObjectContainer.prototype.setChildIndex = function (child, index) +{ + if (index < 0 || index >= this.children.length) + { throw new Error('The supplied index is out of bounds'); } @@ -220,8 +247,10 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child at the given index, if any. */ -DisplayObjectContainer.prototype.getChildAt = function (index) { - if (index < 0 || index >= this.children.length) { +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'); } @@ -234,10 +263,12 @@ * @param child {DisplayObject} The DisplayObject to remove * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChild = function (child) { +DisplayObjectContainer.prototype.removeChild = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { return; } @@ -250,7 +281,8 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChildAt = function (index) { +DisplayObjectContainer.prototype.removeChildAt = function (index) +{ var child = this.getChildAt(index); child.parent = null; @@ -265,24 +297,29 @@ * @param beginIndex {Number} The beginning position. Default value is 0. * @param endIndex {Number} The ending position. Default value is size of the container. */ -DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) { +DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) +{ var begin = beginIndex || 0; var end = typeof endIndex === 'number' ? endIndex : this.children.length; var range = end - begin; - if (range > 0 && range <= end) { + if (range > 0 && range <= end) + { var removed = this.children.splice(begin, range); - for (var i = 0; i < removed.length; ++i) { + for (var i = 0; i < removed.length; ++i) + { removed[i].parent = null; } return removed; } - else if (range === 0 && this.children.length === 0) { + else if (range === 0 && this.children.length === 0) + { return []; } - else { + else + { throw new RangeError('removeChildren: numeric values are outside the acceptable range.'); } }; @@ -291,7 +328,8 @@ * Generates and updates the cached sprite for this object. * */ -DisplayObjectContainer.prototype.updateCachedSprite = function () { +DisplayObjectContainer.prototype.updateCachedSprite = function () +{ this._generateCachedSprite(); }; @@ -304,7 +342,8 @@ * @param renderer {CanvasRenderer|WebGLRenderer} The renderer used to generate the texture. * @return {Texture} a texture of the graphics object */ -DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) { +DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) +{ var bounds = this.getLocalBounds(); var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0, renderer, scaleMode, resolution); @@ -322,18 +361,22 @@ * * @private */ -DisplayObjectContainer.prototype.updateTransform = function () { - if (!this.visible) { +DisplayObjectContainer.prototype.updateTransform = function () +{ + if (!this.visible) + { return; } this.displayObjectUpdateTransform(); - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { return; } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } }; @@ -346,8 +389,10 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getBounds = function () { - if (this.children.length === 0) { +DisplayObjectContainer.prototype.getBounds = function () +{ + if (this.children.length === 0) + { return math.Rectangle.EMPTY; } @@ -365,10 +410,12 @@ var childVisible = false; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -386,7 +433,8 @@ maxY = maxY > childMaxY ? maxY : childMaxY; } - if (!childVisible) { + if (!childVisible) + { return math.Rectangle.EMPTY; } @@ -407,12 +455,14 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getLocalBounds = function () { +DisplayObjectContainer.prototype.getLocalBounds = function () +{ var matrixCache = this.worldTransform; this.worldTransform = math.Matrix.IDENTITY; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } @@ -428,13 +478,16 @@ * * @param renderer {WebGLRenderer} The renderer */ -DisplayObjectContainer.prototype.renderWebGL = function (renderer) { +DisplayObjectContainer.prototype.renderWebGL = function (renderer) +{ // if the object is not visible or the alpha is 0 then no need to render this element - if (!this.visible || this.alpha <= 0) { + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } @@ -442,14 +495,17 @@ var i, j; // do a quick check to see if this element has a mask or a filter. - if (this._mask || this._filters) { + if (this._mask || this._filters) + { // push filter first as we need to ensure the stencil buffer is correct for any masking - if (this._filters) { + if (this._filters) + { renderer.spriteBatch.flush(); renderer.filterManager.pushFilter(this._filterBlock); } - if (this._mask) { + if (this._mask) + { renderer.spriteBatch.stop(); renderer.maskManager.pushMask(this.mask, renderer); renderer.spriteBatch.start(); @@ -459,36 +515,42 @@ this._renderWebGL(renderer); // now loop through the children and make sure they get rendered - for (i = 0, j = this.children.length; i < j; i++) { + for (i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderWebGL(renderer); } // time to stop the sprite batch as either a mask element or a filter draw will happen next renderer.spriteBatch.stop(); - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(this._mask, renderer); } - if (this._filters) { + if (this._filters) + { renderer.filterManager.popFilter(); } renderer.spriteBatch.start(); } - else { + else + { this._renderWebGL(renderer); // simple render children! - for (i = 0, j = this.children.length; i < j; ++i) { + for (i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderWebGL(renderer); } } }; -DisplayObjectContainer.prototype._renderWebGL = function (renderer) { +DisplayObjectContainer.prototype._renderWebGL = function (renderer) +{ // this is where content itself gets renderd.. @@ -499,25 +561,31 @@ * * @param renderer {CanvasRenderer} The renderer */ -DisplayObjectContainer.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0) { +DisplayObjectContainer.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -528,13 +596,16 @@ * @param renderer {WebGLRenderer|CanvasRenderer} The renderer * @private */ -DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) { +DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) +{ this._cachedSprite.worldAlpha = this.worldAlpha; - if (renderer.gl) { + if (renderer.gl) + { this._cachedSprite.renderWebGL(renderer); } - else { + else + { this._cachedSprite.renderCanvas(renderer); } }; @@ -544,10 +615,12 @@ * * @private */ -DisplayObjectContainer.prototype._generateCachedSprite = function () { +DisplayObjectContainer.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { // TODO - RenderTexture now *requires* a renderer instance, so this is like broken // because `renderer` isn't actually in scope here :P var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0); @@ -555,7 +628,8 @@ this._cachedSprite = new Sprite(renderTexture); this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.texture.resize(bounds.width | 0, bounds.height | 0); } @@ -580,8 +654,10 @@ * * @private */ -DisplayObjectContainer.prototype._destroyCachedSprite = function () { - if (!this._cachedSprite) { +DisplayObjectContainer.prototype._destroyCachedSprite = function () +{ + if (!this._cachedSprite) + { return; } diff --git a/src/core/display/Sprite.js b/src/core/display/Sprite.js index 707da24..5862aef 100644 --- a/src/core/display/Sprite.js +++ b/src/core/display/Sprite.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param texture {Texture} The texture for this sprite */ -function Sprite(texture) { +function Sprite(texture) +{ DisplayObjectContainer.call(this); /** @@ -85,12 +86,14 @@ this.texture = texture || Texture.EMPTY; } -Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) { +Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) +{ DisplayObjectContainer.prototype.destroy.call(this); this.anchor = null; - if (destroyTexture) { + if (destroyTexture) + { this._texture.destroy(destroyBaseTexture); } @@ -111,10 +114,12 @@ * @memberof Sprite# */ width: { - get: function () { + get: function () + { return this.scale.x * this.texture.frame.width; }, - set: function (value) { + set: function (value) + { this.scale.x = value / this.texture.frame.width; this._width = value; } @@ -127,10 +132,12 @@ * @memberof Sprite# */ height: { - get: function () { + get: function () + { return this.scale.y * this.texture.frame.height; }, - set: function (value) { + set: function (value) + { this.scale.y = value / this.texture.frame.height; this._height = value; } @@ -143,23 +150,29 @@ * @memberof Sprite# */ texture: { - get: function () { + get: function () + { return this._texture; }, - set: function (value) { - if (this._texture === value) { + set: function (value) + { + if (this._texture === value) + { return; } this._texture = value; this.cachedTint = 0xFFFFFF; - if (value) { + if (value) + { // wait for the texture to load - if (value.baseTexture.hasLoaded) { + if (value.baseTexture.hasLoaded) + { this._onTextureUpdate(); } - else { + else + { value.once('update', this._onTextureUpdate.bind(this)); } } @@ -172,18 +185,22 @@ * * @private */ -Sprite.prototype._onTextureUpdate = function () { +Sprite.prototype._onTextureUpdate = function () +{ // so if _width is 0 then width was not set.. - if (this._width) { + if (this._width) + { this.scale.x = this._width / this.texture.frame.width; } - if (this._height) { + if (this._height) + { this.scale.y = this._height / this.texture.frame.height; } }; -Sprite.prototype._renderWebGL = function (renderer) { +Sprite.prototype._renderWebGL = function (renderer) +{ // this is where content gets renderd.. // watch this space for a little render state manager.. @@ -197,7 +214,8 @@ * @param matrix {Matrix} the transformation matrix of the sprite * @return {Rectangle} the framing rectangle */ -Sprite.prototype.getBounds = function (matrix) { +Sprite.prototype.getBounds = function (matrix) +{ var width = this.texture.frame.width; var height = this.texture.frame.height; @@ -224,11 +242,13 @@ if(b === 0 && c === 0) { // scale may be negative! - if (a < 0) { + if (a < 0) + { a *= -1; } - if (d < 0) { + if (d < 0) + { d *= -1; } @@ -293,28 +313,34 @@ * * @param renderer {CanvasRenderer} The renderer */ -Sprite.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) { +Sprite.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) + { return; } - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; renderer.context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } // Ignore null sources - if (this.texture.valid) { + if (this.texture.valid) + { var resolution = this.texture.baseTexture.resolution / renderer.resolution; renderer.context.globalAlpha = this.worldAlpha; // If smoothingEnabled is supported and we need to change the smoothing property for this texture - if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) { + if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) + { renderer.scaleMode = this.texture.baseTexture.scaleMode; renderer.context[renderer.smoothProperty] = (renderer.scaleMode === CONST.scaleModes.LINEAR); } @@ -324,7 +350,8 @@ var dy = (this.texture.trim ? this.texture.trim.y : 0) - (this.anchor.y * this.texture.trim.height); // Allow for pixel rounding - if (renderer.roundPixels) { + if (renderer.roundPixels) + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -337,7 +364,8 @@ dx = dx | 0; dy = dy | 0; } - else { + else + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -348,8 +376,10 @@ ); } - if (this.tint !== 0xFFFFFF) { - if (this.cachedTint !== this.tint) { + if (this.tint !== 0xFFFFFF) + { + if (this.cachedTint !== this.tint) + { this.cachedTint = this.tint; // TODO clean up caching - how to clean up the caches? @@ -368,7 +398,8 @@ this.texture.crop.height / resolution ); } - else { + else + { renderer.context.drawImage( this.texture.baseTexture.source, this.texture.crop.x, @@ -383,11 +414,13 @@ } } - for (var i = 0, j = this.children.length; i < j; i++) { + for (var i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -402,10 +435,12 @@ * @param frameId {String} The frame Id of the texture in the cache * @return {Sprite} A new Sprite using a texture from the texture cache matching the frameId */ -Sprite.fromFrame = function (frameId) { +Sprite.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache' + this); } @@ -420,6 +455,7 @@ * @param imageId {String} The image url of the texture * @return {Sprite} A new Sprite using a texture from the texture cache matching the image id */ -Sprite.fromImage = function (imageId, crossorigin, scaleMode) { +Sprite.fromImage = function (imageId, crossorigin, scaleMode) +{ return new Sprite(Texture.fromImage(imageId, crossorigin, scaleMode)); }; diff --git a/src/core/display/SpriteBatch.js b/src/core/display/SpriteBatch.js index 3187777..c196fef 100644 --- a/src/core/display/SpriteBatch.js +++ b/src/core/display/SpriteBatch.js @@ -12,7 +12,8 @@ * ```js * var container = new SpriteBatch(); * - * for(var i = 0; i < 100; ++i) { + * for(var i = 0; i < 100; ++i) + * { * var sprite = new PIXI.Sprite.fromImage("myImage.png"); * container.addChild(sprite); * } @@ -25,7 +26,8 @@ */ //TODO RENAME to PARTICLE CONTAINER? -function SpriteBatch() { +function SpriteBatch() +{ DisplayObjectContainer.call(this); } @@ -38,7 +40,8 @@ * * @private */ -SpriteBatch.prototype.updateTransform = function () { +SpriteBatch.prototype.updateTransform = function () +{ // TODO don't need to! this.displayObjectUpdateTransform(); // PIXI.DisplayObjectContainer.prototype.updateTransform.call( this ); @@ -50,8 +53,10 @@ * @param renderer {WebGLRenderer} The webgl renderer * @private */ -SpriteBatch.prototype.renderWebGL = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderWebGL = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -71,8 +76,10 @@ * @param renderer {CanvasRenderer} The canvas renderer * @private */ -SpriteBatch.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -84,10 +91,12 @@ this.displayObjectUpdateTransform(); - for (var i = 0; i < this.children.length; ++i) { + for (var i = 0; i < this.children.length; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -95,9 +104,11 @@ context.globalAlpha = this.worldAlpha * child.alpha; - if (child.rotation % (Math.PI * 2) === 0) { + if (child.rotation % (Math.PI * 2) === 0) + { // this is the fastest way to optimise! - if rotation is 0 then we can avoid any kind of setTransform call - if (isRotated) { + if (isRotated) + { context.setTransform( transform.a, transform.b, @@ -122,8 +133,10 @@ frame.height * child.scale.y ); } - else { - if (!isRotated) { + else + { + if (!isRotated) + { isRotated = true; } @@ -131,7 +144,8 @@ var childTransform = child.worldTransform; - if (renderer.roundPixels) { + if (renderer.roundPixels) + { context.setTransform( childTransform.a, childTransform.b, @@ -141,7 +155,8 @@ childTransform.ty | 0 ); } - else { + else + { context.setTransform( childTransform.a, childTransform.b, diff --git a/src/core/index.js b/src/core/index.js index 3954b6f..eb4a82b 100644 --- a/src/core/index.js +++ b/src/core/index.js @@ -58,11 +58,13 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRenderer: function (width, height, options, noWebGL) { + autoDetectRenderer: function (width, height, options, noWebGL) + { width = width || 800; height = height || 600; - if (!noWebGL && require('webgl-enabled')()) { + if (!noWebGL && require('webgl-enabled')()) + { return new core.WebGLRenderer(width, height, options); } @@ -87,7 +89,8 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRecommendedRenderer: function (width, height, options) { + autoDetectRecommendedRenderer: function (width, height, options) + { var isAndroid = /Android/i.test(navigator.userAgent); return core.autoDetectRenderer(width, height, options, isAndroid); diff --git a/src/core/math/Matrix.js b/src/core/math/Matrix.js index c2f87e2..2ff4848 100644 --- a/src/core/math/Matrix.js +++ b/src/core/math/Matrix.js @@ -10,7 +10,8 @@ * @class * @namespace PIXI */ -function Matrix() { +function Matrix() +{ /** * @member {number} * @default 1 @@ -63,7 +64,8 @@ * * @param array {number[]} The array that the matrix will be populated from. */ -Matrix.prototype.fromArray = function (array) { +Matrix.prototype.fromArray = function (array) +{ this.a = array[0]; this.b = array[1]; this.c = array[3]; @@ -78,14 +80,17 @@ * @param transpose {boolean} Whether we need to transpose the matrix or not * @return {number[]} the newly created array which contains the matrix */ -Matrix.prototype.toArray = function (transpose) { - if (!this.array) { +Matrix.prototype.toArray = function (transpose) +{ + if (!this.array) + { this.array = new Float32Array(9); } var array = this.array; - if (transpose) { + if (transpose) + { array[0] = this.a; array[1] = this.b; array[2] = 0; @@ -96,7 +101,8 @@ array[7] = this.ty; array[8] = 1; } - else { + else + { array[0] = this.a; array[1] = this.c; array[2] = this.tx; @@ -119,7 +125,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, transformed through this matrix */ -Matrix.prototype.apply = function (pos, newPos) { +Matrix.prototype.apply = function (pos, newPos) +{ newPos = newPos || new Point(); newPos.x = this.a * pos.x + this.c * pos.y + this.tx; @@ -136,7 +143,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, inverse-transformed through this matrix */ -Matrix.prototype.applyInverse = function (pos, newPos) { +Matrix.prototype.applyInverse = function (pos, newPos) +{ newPos = newPos || new Point(); var id = 1 / (this.a * this.d + this.c * -this.b); @@ -154,7 +162,8 @@ * @param {number} y * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.translate = function (x, y) { +Matrix.prototype.translate = function (x, y) +{ this.tx += x; this.ty += y; @@ -168,7 +177,8 @@ * @param {number} y The amount to scale vertically * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.scale = function (x, y) { +Matrix.prototype.scale = function (x, y) +{ this.a *= x; this.d *= y; this.c *= x; @@ -186,7 +196,8 @@ * @param {number} angle - The angle in radians. * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.rotate = function (angle) { +Matrix.prototype.rotate = function (angle) +{ var cos = Math.cos( angle ); var sin = Math.sin( angle ); @@ -210,7 +221,8 @@ * @param {Matrix} matrix * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.append = function (matrix) { +Matrix.prototype.append = function (matrix) +{ var a1 = this.a; var b1 = this.b; var c1 = this.c; @@ -232,7 +244,8 @@ * * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.identity = function () { +Matrix.prototype.identity = function () +{ this.a = 1; this.b = 0; this.c = 0; diff --git a/src/core/math/Point.js b/src/core/math/Point.js index 7565b2d..632f346 100644 --- a/src/core/math/Point.js +++ b/src/core/math/Point.js @@ -7,7 +7,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -function Point(x, y) { +function Point(x, y) +{ /** * @member {number} * @default 0 @@ -29,7 +30,8 @@ * * @return {Point} a copy of the point */ -Point.prototype.clone = function () { +Point.prototype.clone = function () +{ return new Point(this.x, this.y); }; @@ -40,7 +42,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -Point.prototype.set = function (x, y) { +Point.prototype.set = function (x, y) +{ this.x = x || 0; this.y = y || ( (y !== 0) ? this.x : 0 ) ; }; diff --git a/src/core/math/shapes/Circle.js b/src/core/math/shapes/Circle.js index 69cfdc9..4d76efc 100644 --- a/src/core/math/shapes/Circle.js +++ b/src/core/math/shapes/Circle.js @@ -10,7 +10,8 @@ * @param y {number} The Y coordinate of the center of this circle * @param radius {number} The radius of the circle */ -function Circle(x, y, radius) { +function Circle(x, y, radius) +{ /** * @member {number} * @default 0 @@ -46,7 +47,8 @@ * @method clone * @return {Circle} a copy of the Circle */ -Circle.prototype.clone = function () { +Circle.prototype.clone = function () +{ return new Circle(this.x, this.y, this.radius); }; @@ -58,8 +60,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Circle */ -Circle.prototype.contains = function (x, y) { - if (this.radius <= 0) { +Circle.prototype.contains = function (x, y) +{ + if (this.radius <= 0) + { return false; } @@ -79,6 +83,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Circle.prototype.getBounds = function () { +Circle.prototype.getBounds = function () +{ return new Rectangle(this.x - this.radius, this.y - this.radius, this.radius * 2, this.radius * 2); }; diff --git a/src/core/math/shapes/Ellipse.js b/src/core/math/shapes/Ellipse.js index 4f2d066..fefd01a 100644 --- a/src/core/math/shapes/Ellipse.js +++ b/src/core/math/shapes/Ellipse.js @@ -11,7 +11,8 @@ * @param width {number} The half width of this ellipse * @param height {number} The half height of this ellipse */ -function Ellipse(x, y, width, height) { +function Ellipse(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -53,7 +54,8 @@ * @method clone * @return {Ellipse} a copy of the ellipse */ -Ellipse.prototype.clone = function () { +Ellipse.prototype.clone = function () +{ return new Ellipse(this.x, this.y, this.width, this.height); }; @@ -65,8 +67,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coords are within this ellipse */ -Ellipse.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Ellipse.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } @@ -86,6 +90,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Ellipse.prototype.getBounds = function () { +Ellipse.prototype.getBounds = function () +{ return new Rectangle(this.x - this.width, this.y - this.height, this.width, this.height); }; diff --git a/src/core/display/DisplayObject.js b/src/core/display/DisplayObject.js index 66ebc3c..20e778c 100644 --- a/src/core/display/DisplayObject.js +++ b/src/core/display/DisplayObject.js @@ -7,7 +7,8 @@ * @class * @namespace PIXI */ -function DisplayObject() { +function DisplayObject() +{ /** * The coordinate of the object relative to the local coordinates of the parent. * @@ -152,10 +153,12 @@ * @memberof DisplayObject# */ x: { - get: function () { + get: function () + { return this.position.x; }, - set: function (value) { + set: function (value) + { this.position.x = value; } }, @@ -167,10 +170,12 @@ * @memberof DisplayObject# */ y: { - get: function () { + get: function () + { return this.position.y; }, - set: function (value) { + set: function (value) + { this.position.y = value; } }, @@ -183,11 +188,13 @@ * @readonly */ worldVisible: { - get: function () { + get: function () + { var item = this; do { - if (!item.visible) { + if (!item.visible) + { return false; } @@ -207,17 +214,21 @@ * @memberof DisplayObject# */ mask: { - get: function () { + get: function () + { return this._mask; }, - set: function (value) { - if (this._mask) { + set: function (value) + { + if (this._mask) + { this._mask.isMask = false; } this._mask = value; - if (this._mask) { + if (this._mask) + { this._mask.isMask = true; } } @@ -232,18 +243,23 @@ * @memberof DisplayObject# */ filters: { - get: function () { + get: function () + { return this._filters; }, - set: function (value) { - if (value) { + set: function (value) + { + if (value) + { // now put all the passes in one place.. var passes = []; - for (var i = 0; i < value.length; i++) { + for (var i = 0; i < value.length; i++) + { var filterPasses = value[i].passes; - for (var j = 0; j < filterPasses.length; j++) { + for (var j = 0; j < filterPasses.length; j++) + { passes.push(filterPasses[j]); } } @@ -264,8 +280,9 @@ * * @private */ -DisplayObject.prototype.updateTransform = function () { - +DisplayObject.prototype.updateTransform = function () +{ + // create some matrix refs for easy access var pt = this.parent.worldTransform; var wt = this.worldTransform; @@ -274,9 +291,11 @@ var a, b, c, d, tx, ty; // so if rotation is between 0 then we can simplify the multiplication process.. - if (this.rotation % math.PI_2) { + if (this.rotation % math.PI_2) + { // 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) { + if (this.rotation !== this.rotationCache) + { this.rotationCache = this.rotation; this._sr = Math.sin(this.rotation); this._cr = Math.cos(this.rotation); @@ -291,7 +310,8 @@ ty = this.position.y; // check for pivot.. not often used so geared towards that fact! - if (this.pivot.x || this.pivot.y) { + 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; } @@ -304,7 +324,8 @@ wt.tx = tx * pt.a + ty * pt.c + pt.tx; wt.ty = tx * pt.b + ty * pt.d + pt.ty; } - else { + else + { // lets do the fast version as we know there is no rotation.. a = this.scale.x; d = this.scale.y; @@ -333,7 +354,8 @@ * @param matrix {Matrix} * @return {Rectangle} the rectangular bounding area */ -DisplayObject.prototype.getBounds = function (/* matrix */) { +DisplayObject.prototype.getBounds = function (/* matrix */) +{ return math.Rectangle.EMPTY; }; @@ -342,7 +364,8 @@ * * @return {Rectangle} the rectangular bounding area */ -DisplayObject.prototype.getLocalBounds = function () { +DisplayObject.prototype.getLocalBounds = function () +{ return this.getBounds(math.Matrix.IDENTITY); }; @@ -352,7 +375,8 @@ * @param position {Point} The world origin to calculate from * @return {Point} A point object representing the position of this object */ -DisplayObject.prototype.toGlobal = function (position) { +DisplayObject.prototype.toGlobal = function (position) +{ // don't need to u[date the lot this.displayObjectUpdateTransform(); return this.worldTransform.apply(position); @@ -365,8 +389,10 @@ * @param [from] {DisplayObject} The DisplayObject to calculate the global position from * @return {Point} A point object representing the position of this object */ -DisplayObject.prototype.toLocal = function (position, from) { - if (from) { +DisplayObject.prototype.toLocal = function (position, from) +{ + if (from) + { position = from.toGlobal(position); } @@ -381,7 +407,8 @@ * @param renderer {WebGLRenderer} The renderer * @private */ -DisplayObject.prototype.renderWebGL = function (/* renderer */) { +DisplayObject.prototype.renderWebGL = function (/* renderer */) +{ // OVERWRITE; }; @@ -391,6 +418,7 @@ * @param renderer {CanvasRenderer} The renderer * @private */ -DisplayObject.prototype.renderCanvas = function (/* renderer */) { +DisplayObject.prototype.renderCanvas = function (/* renderer */) +{ // OVERWRITE; }; diff --git a/src/core/display/DisplayObjectContainer.js b/src/core/display/DisplayObjectContainer.js index 689f40b..4625ee8 100644 --- a/src/core/display/DisplayObjectContainer.js +++ b/src/core/display/DisplayObjectContainer.js @@ -12,7 +12,8 @@ * @extends DisplayObject * @namespace PIXI */ -function DisplayObjectContainer() { +function DisplayObjectContainer() +{ DisplayObject.call(this); /** @@ -47,17 +48,21 @@ * @memberof DisplayObjectContainer# */ width: { - get: function () { + get: function () + { return this.scale.x * this.getLocalBounds().width; }, - set: function (value) { + set: function (value) + { var width = this.getLocalBounds().width; - if(width !== 0) { + if(width !== 0) + { this.scale.x = value / width; } - else { + else + { this.scale.x = 1; } @@ -73,17 +78,21 @@ * @memberof DisplayObjectContainer# */ height: { - get: function () { + get: function () + { return this.scale.y * this.getLocalBounds().height; }, - set: function (value) { + set: function (value) + { var height = this.getLocalBounds().height; - if (height !== 0) { + if (height !== 0) + { this.scale.y = value / height ; } - else { + else + { this.scale.y = 1; } @@ -100,18 +109,23 @@ * @memberof DisplayObject# */ cacheAsBitmap: { - get: function () { + get: function () + { return this._cacheAsBitmap; }, - set: function (value) { - if (this._cacheAsBitmap === value) { + set: function (value) + { + if (this._cacheAsBitmap === value) + { return; } - if (value) { + if (value) + { this._generateCachedSprite(); } - else { + else + { this._destroyCachedSprite(); } @@ -126,7 +140,8 @@ * @param child {DisplayObject} The DisplayObject to add to the container * @return {DisplayObject} The child that was added. */ -DisplayObjectContainer.prototype.addChild = function (child) { +DisplayObjectContainer.prototype.addChild = function (child) +{ return this.addChildAt(child, this.children.length); }; @@ -137,14 +152,18 @@ * @param index {Number} The index to place the child in * @return {DisplayObject} The child that was added. */ -DisplayObjectContainer.prototype.addChildAt = function (child, index) { +DisplayObjectContainer.prototype.addChildAt = function (child, index) +{ // prevent adding self as child - if (child === this) { + if (child === this) + { return; } - if (index >= 0 && index <= this.children.length) { - if (child.parent) { + if (index >= 0 && index <= this.children.length) + { + if (child.parent) + { child.parent.removeChild(child); } @@ -154,7 +173,8 @@ return child; } - else { + else + { throw new Error(child + 'addChildAt: The index '+ index +' supplied is out of bounds ' + this.children.length); } }; @@ -165,15 +185,18 @@ * @param child {DisplayObject} * @param child2 {DisplayObject} */ -DisplayObjectContainer.prototype.swapChildren = function (child, child2) { - if (child === child2) { +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) { + if (index1 < 0 || index2 < 0) + { throw new Error('swapChildren: Both the supplied DisplayObjects must be a child of the caller.'); } @@ -187,10 +210,12 @@ * @param child {DisplayObject} The DisplayObject instance to identify * @return {Number} The index position of the child display object to identify */ -DisplayObjectContainer.prototype.getChildIndex = function (child) { +DisplayObjectContainer.prototype.getChildIndex = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { throw new Error('The supplied DisplayObject must be a child of the caller'); } @@ -203,8 +228,10 @@ * @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 */ -DisplayObjectContainer.prototype.setChildIndex = function (child, index) { - if (index < 0 || index >= this.children.length) { +DisplayObjectContainer.prototype.setChildIndex = function (child, index) +{ + if (index < 0 || index >= this.children.length) + { throw new Error('The supplied index is out of bounds'); } @@ -220,8 +247,10 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child at the given index, if any. */ -DisplayObjectContainer.prototype.getChildAt = function (index) { - if (index < 0 || index >= this.children.length) { +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'); } @@ -234,10 +263,12 @@ * @param child {DisplayObject} The DisplayObject to remove * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChild = function (child) { +DisplayObjectContainer.prototype.removeChild = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { return; } @@ -250,7 +281,8 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChildAt = function (index) { +DisplayObjectContainer.prototype.removeChildAt = function (index) +{ var child = this.getChildAt(index); child.parent = null; @@ -265,24 +297,29 @@ * @param beginIndex {Number} The beginning position. Default value is 0. * @param endIndex {Number} The ending position. Default value is size of the container. */ -DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) { +DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) +{ var begin = beginIndex || 0; var end = typeof endIndex === 'number' ? endIndex : this.children.length; var range = end - begin; - if (range > 0 && range <= end) { + if (range > 0 && range <= end) + { var removed = this.children.splice(begin, range); - for (var i = 0; i < removed.length; ++i) { + for (var i = 0; i < removed.length; ++i) + { removed[i].parent = null; } return removed; } - else if (range === 0 && this.children.length === 0) { + else if (range === 0 && this.children.length === 0) + { return []; } - else { + else + { throw new RangeError('removeChildren: numeric values are outside the acceptable range.'); } }; @@ -291,7 +328,8 @@ * Generates and updates the cached sprite for this object. * */ -DisplayObjectContainer.prototype.updateCachedSprite = function () { +DisplayObjectContainer.prototype.updateCachedSprite = function () +{ this._generateCachedSprite(); }; @@ -304,7 +342,8 @@ * @param renderer {CanvasRenderer|WebGLRenderer} The renderer used to generate the texture. * @return {Texture} a texture of the graphics object */ -DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) { +DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) +{ var bounds = this.getLocalBounds(); var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0, renderer, scaleMode, resolution); @@ -322,18 +361,22 @@ * * @private */ -DisplayObjectContainer.prototype.updateTransform = function () { - if (!this.visible) { +DisplayObjectContainer.prototype.updateTransform = function () +{ + if (!this.visible) + { return; } this.displayObjectUpdateTransform(); - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { return; } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } }; @@ -346,8 +389,10 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getBounds = function () { - if (this.children.length === 0) { +DisplayObjectContainer.prototype.getBounds = function () +{ + if (this.children.length === 0) + { return math.Rectangle.EMPTY; } @@ -365,10 +410,12 @@ var childVisible = false; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -386,7 +433,8 @@ maxY = maxY > childMaxY ? maxY : childMaxY; } - if (!childVisible) { + if (!childVisible) + { return math.Rectangle.EMPTY; } @@ -407,12 +455,14 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getLocalBounds = function () { +DisplayObjectContainer.prototype.getLocalBounds = function () +{ var matrixCache = this.worldTransform; this.worldTransform = math.Matrix.IDENTITY; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } @@ -428,13 +478,16 @@ * * @param renderer {WebGLRenderer} The renderer */ -DisplayObjectContainer.prototype.renderWebGL = function (renderer) { +DisplayObjectContainer.prototype.renderWebGL = function (renderer) +{ // if the object is not visible or the alpha is 0 then no need to render this element - if (!this.visible || this.alpha <= 0) { + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } @@ -442,14 +495,17 @@ var i, j; // do a quick check to see if this element has a mask or a filter. - if (this._mask || this._filters) { + if (this._mask || this._filters) + { // push filter first as we need to ensure the stencil buffer is correct for any masking - if (this._filters) { + if (this._filters) + { renderer.spriteBatch.flush(); renderer.filterManager.pushFilter(this._filterBlock); } - if (this._mask) { + if (this._mask) + { renderer.spriteBatch.stop(); renderer.maskManager.pushMask(this.mask, renderer); renderer.spriteBatch.start(); @@ -459,36 +515,42 @@ this._renderWebGL(renderer); // now loop through the children and make sure they get rendered - for (i = 0, j = this.children.length; i < j; i++) { + for (i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderWebGL(renderer); } // time to stop the sprite batch as either a mask element or a filter draw will happen next renderer.spriteBatch.stop(); - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(this._mask, renderer); } - if (this._filters) { + if (this._filters) + { renderer.filterManager.popFilter(); } renderer.spriteBatch.start(); } - else { + else + { this._renderWebGL(renderer); // simple render children! - for (i = 0, j = this.children.length; i < j; ++i) { + for (i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderWebGL(renderer); } } }; -DisplayObjectContainer.prototype._renderWebGL = function (renderer) { +DisplayObjectContainer.prototype._renderWebGL = function (renderer) +{ // this is where content itself gets renderd.. @@ -499,25 +561,31 @@ * * @param renderer {CanvasRenderer} The renderer */ -DisplayObjectContainer.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0) { +DisplayObjectContainer.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -528,13 +596,16 @@ * @param renderer {WebGLRenderer|CanvasRenderer} The renderer * @private */ -DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) { +DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) +{ this._cachedSprite.worldAlpha = this.worldAlpha; - if (renderer.gl) { + if (renderer.gl) + { this._cachedSprite.renderWebGL(renderer); } - else { + else + { this._cachedSprite.renderCanvas(renderer); } }; @@ -544,10 +615,12 @@ * * @private */ -DisplayObjectContainer.prototype._generateCachedSprite = function () { +DisplayObjectContainer.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { // TODO - RenderTexture now *requires* a renderer instance, so this is like broken // because `renderer` isn't actually in scope here :P var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0); @@ -555,7 +628,8 @@ this._cachedSprite = new Sprite(renderTexture); this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.texture.resize(bounds.width | 0, bounds.height | 0); } @@ -580,8 +654,10 @@ * * @private */ -DisplayObjectContainer.prototype._destroyCachedSprite = function () { - if (!this._cachedSprite) { +DisplayObjectContainer.prototype._destroyCachedSprite = function () +{ + if (!this._cachedSprite) + { return; } diff --git a/src/core/display/Sprite.js b/src/core/display/Sprite.js index 707da24..5862aef 100644 --- a/src/core/display/Sprite.js +++ b/src/core/display/Sprite.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param texture {Texture} The texture for this sprite */ -function Sprite(texture) { +function Sprite(texture) +{ DisplayObjectContainer.call(this); /** @@ -85,12 +86,14 @@ this.texture = texture || Texture.EMPTY; } -Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) { +Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) +{ DisplayObjectContainer.prototype.destroy.call(this); this.anchor = null; - if (destroyTexture) { + if (destroyTexture) + { this._texture.destroy(destroyBaseTexture); } @@ -111,10 +114,12 @@ * @memberof Sprite# */ width: { - get: function () { + get: function () + { return this.scale.x * this.texture.frame.width; }, - set: function (value) { + set: function (value) + { this.scale.x = value / this.texture.frame.width; this._width = value; } @@ -127,10 +132,12 @@ * @memberof Sprite# */ height: { - get: function () { + get: function () + { return this.scale.y * this.texture.frame.height; }, - set: function (value) { + set: function (value) + { this.scale.y = value / this.texture.frame.height; this._height = value; } @@ -143,23 +150,29 @@ * @memberof Sprite# */ texture: { - get: function () { + get: function () + { return this._texture; }, - set: function (value) { - if (this._texture === value) { + set: function (value) + { + if (this._texture === value) + { return; } this._texture = value; this.cachedTint = 0xFFFFFF; - if (value) { + if (value) + { // wait for the texture to load - if (value.baseTexture.hasLoaded) { + if (value.baseTexture.hasLoaded) + { this._onTextureUpdate(); } - else { + else + { value.once('update', this._onTextureUpdate.bind(this)); } } @@ -172,18 +185,22 @@ * * @private */ -Sprite.prototype._onTextureUpdate = function () { +Sprite.prototype._onTextureUpdate = function () +{ // so if _width is 0 then width was not set.. - if (this._width) { + if (this._width) + { this.scale.x = this._width / this.texture.frame.width; } - if (this._height) { + if (this._height) + { this.scale.y = this._height / this.texture.frame.height; } }; -Sprite.prototype._renderWebGL = function (renderer) { +Sprite.prototype._renderWebGL = function (renderer) +{ // this is where content gets renderd.. // watch this space for a little render state manager.. @@ -197,7 +214,8 @@ * @param matrix {Matrix} the transformation matrix of the sprite * @return {Rectangle} the framing rectangle */ -Sprite.prototype.getBounds = function (matrix) { +Sprite.prototype.getBounds = function (matrix) +{ var width = this.texture.frame.width; var height = this.texture.frame.height; @@ -224,11 +242,13 @@ if(b === 0 && c === 0) { // scale may be negative! - if (a < 0) { + if (a < 0) + { a *= -1; } - if (d < 0) { + if (d < 0) + { d *= -1; } @@ -293,28 +313,34 @@ * * @param renderer {CanvasRenderer} The renderer */ -Sprite.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) { +Sprite.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) + { return; } - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; renderer.context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } // Ignore null sources - if (this.texture.valid) { + if (this.texture.valid) + { var resolution = this.texture.baseTexture.resolution / renderer.resolution; renderer.context.globalAlpha = this.worldAlpha; // If smoothingEnabled is supported and we need to change the smoothing property for this texture - if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) { + if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) + { renderer.scaleMode = this.texture.baseTexture.scaleMode; renderer.context[renderer.smoothProperty] = (renderer.scaleMode === CONST.scaleModes.LINEAR); } @@ -324,7 +350,8 @@ var dy = (this.texture.trim ? this.texture.trim.y : 0) - (this.anchor.y * this.texture.trim.height); // Allow for pixel rounding - if (renderer.roundPixels) { + if (renderer.roundPixels) + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -337,7 +364,8 @@ dx = dx | 0; dy = dy | 0; } - else { + else + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -348,8 +376,10 @@ ); } - if (this.tint !== 0xFFFFFF) { - if (this.cachedTint !== this.tint) { + if (this.tint !== 0xFFFFFF) + { + if (this.cachedTint !== this.tint) + { this.cachedTint = this.tint; // TODO clean up caching - how to clean up the caches? @@ -368,7 +398,8 @@ this.texture.crop.height / resolution ); } - else { + else + { renderer.context.drawImage( this.texture.baseTexture.source, this.texture.crop.x, @@ -383,11 +414,13 @@ } } - for (var i = 0, j = this.children.length; i < j; i++) { + for (var i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -402,10 +435,12 @@ * @param frameId {String} The frame Id of the texture in the cache * @return {Sprite} A new Sprite using a texture from the texture cache matching the frameId */ -Sprite.fromFrame = function (frameId) { +Sprite.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache' + this); } @@ -420,6 +455,7 @@ * @param imageId {String} The image url of the texture * @return {Sprite} A new Sprite using a texture from the texture cache matching the image id */ -Sprite.fromImage = function (imageId, crossorigin, scaleMode) { +Sprite.fromImage = function (imageId, crossorigin, scaleMode) +{ return new Sprite(Texture.fromImage(imageId, crossorigin, scaleMode)); }; diff --git a/src/core/display/SpriteBatch.js b/src/core/display/SpriteBatch.js index 3187777..c196fef 100644 --- a/src/core/display/SpriteBatch.js +++ b/src/core/display/SpriteBatch.js @@ -12,7 +12,8 @@ * ```js * var container = new SpriteBatch(); * - * for(var i = 0; i < 100; ++i) { + * for(var i = 0; i < 100; ++i) + * { * var sprite = new PIXI.Sprite.fromImage("myImage.png"); * container.addChild(sprite); * } @@ -25,7 +26,8 @@ */ //TODO RENAME to PARTICLE CONTAINER? -function SpriteBatch() { +function SpriteBatch() +{ DisplayObjectContainer.call(this); } @@ -38,7 +40,8 @@ * * @private */ -SpriteBatch.prototype.updateTransform = function () { +SpriteBatch.prototype.updateTransform = function () +{ // TODO don't need to! this.displayObjectUpdateTransform(); // PIXI.DisplayObjectContainer.prototype.updateTransform.call( this ); @@ -50,8 +53,10 @@ * @param renderer {WebGLRenderer} The webgl renderer * @private */ -SpriteBatch.prototype.renderWebGL = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderWebGL = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -71,8 +76,10 @@ * @param renderer {CanvasRenderer} The canvas renderer * @private */ -SpriteBatch.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -84,10 +91,12 @@ this.displayObjectUpdateTransform(); - for (var i = 0; i < this.children.length; ++i) { + for (var i = 0; i < this.children.length; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -95,9 +104,11 @@ context.globalAlpha = this.worldAlpha * child.alpha; - if (child.rotation % (Math.PI * 2) === 0) { + if (child.rotation % (Math.PI * 2) === 0) + { // this is the fastest way to optimise! - if rotation is 0 then we can avoid any kind of setTransform call - if (isRotated) { + if (isRotated) + { context.setTransform( transform.a, transform.b, @@ -122,8 +133,10 @@ frame.height * child.scale.y ); } - else { - if (!isRotated) { + else + { + if (!isRotated) + { isRotated = true; } @@ -131,7 +144,8 @@ var childTransform = child.worldTransform; - if (renderer.roundPixels) { + if (renderer.roundPixels) + { context.setTransform( childTransform.a, childTransform.b, @@ -141,7 +155,8 @@ childTransform.ty | 0 ); } - else { + else + { context.setTransform( childTransform.a, childTransform.b, diff --git a/src/core/index.js b/src/core/index.js index 3954b6f..eb4a82b 100644 --- a/src/core/index.js +++ b/src/core/index.js @@ -58,11 +58,13 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRenderer: function (width, height, options, noWebGL) { + autoDetectRenderer: function (width, height, options, noWebGL) + { width = width || 800; height = height || 600; - if (!noWebGL && require('webgl-enabled')()) { + if (!noWebGL && require('webgl-enabled')()) + { return new core.WebGLRenderer(width, height, options); } @@ -87,7 +89,8 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRecommendedRenderer: function (width, height, options) { + autoDetectRecommendedRenderer: function (width, height, options) + { var isAndroid = /Android/i.test(navigator.userAgent); return core.autoDetectRenderer(width, height, options, isAndroid); diff --git a/src/core/math/Matrix.js b/src/core/math/Matrix.js index c2f87e2..2ff4848 100644 --- a/src/core/math/Matrix.js +++ b/src/core/math/Matrix.js @@ -10,7 +10,8 @@ * @class * @namespace PIXI */ -function Matrix() { +function Matrix() +{ /** * @member {number} * @default 1 @@ -63,7 +64,8 @@ * * @param array {number[]} The array that the matrix will be populated from. */ -Matrix.prototype.fromArray = function (array) { +Matrix.prototype.fromArray = function (array) +{ this.a = array[0]; this.b = array[1]; this.c = array[3]; @@ -78,14 +80,17 @@ * @param transpose {boolean} Whether we need to transpose the matrix or not * @return {number[]} the newly created array which contains the matrix */ -Matrix.prototype.toArray = function (transpose) { - if (!this.array) { +Matrix.prototype.toArray = function (transpose) +{ + if (!this.array) + { this.array = new Float32Array(9); } var array = this.array; - if (transpose) { + if (transpose) + { array[0] = this.a; array[1] = this.b; array[2] = 0; @@ -96,7 +101,8 @@ array[7] = this.ty; array[8] = 1; } - else { + else + { array[0] = this.a; array[1] = this.c; array[2] = this.tx; @@ -119,7 +125,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, transformed through this matrix */ -Matrix.prototype.apply = function (pos, newPos) { +Matrix.prototype.apply = function (pos, newPos) +{ newPos = newPos || new Point(); newPos.x = this.a * pos.x + this.c * pos.y + this.tx; @@ -136,7 +143,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, inverse-transformed through this matrix */ -Matrix.prototype.applyInverse = function (pos, newPos) { +Matrix.prototype.applyInverse = function (pos, newPos) +{ newPos = newPos || new Point(); var id = 1 / (this.a * this.d + this.c * -this.b); @@ -154,7 +162,8 @@ * @param {number} y * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.translate = function (x, y) { +Matrix.prototype.translate = function (x, y) +{ this.tx += x; this.ty += y; @@ -168,7 +177,8 @@ * @param {number} y The amount to scale vertically * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.scale = function (x, y) { +Matrix.prototype.scale = function (x, y) +{ this.a *= x; this.d *= y; this.c *= x; @@ -186,7 +196,8 @@ * @param {number} angle - The angle in radians. * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.rotate = function (angle) { +Matrix.prototype.rotate = function (angle) +{ var cos = Math.cos( angle ); var sin = Math.sin( angle ); @@ -210,7 +221,8 @@ * @param {Matrix} matrix * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.append = function (matrix) { +Matrix.prototype.append = function (matrix) +{ var a1 = this.a; var b1 = this.b; var c1 = this.c; @@ -232,7 +244,8 @@ * * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.identity = function () { +Matrix.prototype.identity = function () +{ this.a = 1; this.b = 0; this.c = 0; diff --git a/src/core/math/Point.js b/src/core/math/Point.js index 7565b2d..632f346 100644 --- a/src/core/math/Point.js +++ b/src/core/math/Point.js @@ -7,7 +7,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -function Point(x, y) { +function Point(x, y) +{ /** * @member {number} * @default 0 @@ -29,7 +30,8 @@ * * @return {Point} a copy of the point */ -Point.prototype.clone = function () { +Point.prototype.clone = function () +{ return new Point(this.x, this.y); }; @@ -40,7 +42,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -Point.prototype.set = function (x, y) { +Point.prototype.set = function (x, y) +{ this.x = x || 0; this.y = y || ( (y !== 0) ? this.x : 0 ) ; }; diff --git a/src/core/math/shapes/Circle.js b/src/core/math/shapes/Circle.js index 69cfdc9..4d76efc 100644 --- a/src/core/math/shapes/Circle.js +++ b/src/core/math/shapes/Circle.js @@ -10,7 +10,8 @@ * @param y {number} The Y coordinate of the center of this circle * @param radius {number} The radius of the circle */ -function Circle(x, y, radius) { +function Circle(x, y, radius) +{ /** * @member {number} * @default 0 @@ -46,7 +47,8 @@ * @method clone * @return {Circle} a copy of the Circle */ -Circle.prototype.clone = function () { +Circle.prototype.clone = function () +{ return new Circle(this.x, this.y, this.radius); }; @@ -58,8 +60,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Circle */ -Circle.prototype.contains = function (x, y) { - if (this.radius <= 0) { +Circle.prototype.contains = function (x, y) +{ + if (this.radius <= 0) + { return false; } @@ -79,6 +83,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Circle.prototype.getBounds = function () { +Circle.prototype.getBounds = function () +{ return new Rectangle(this.x - this.radius, this.y - this.radius, this.radius * 2, this.radius * 2); }; diff --git a/src/core/math/shapes/Ellipse.js b/src/core/math/shapes/Ellipse.js index 4f2d066..fefd01a 100644 --- a/src/core/math/shapes/Ellipse.js +++ b/src/core/math/shapes/Ellipse.js @@ -11,7 +11,8 @@ * @param width {number} The half width of this ellipse * @param height {number} The half height of this ellipse */ -function Ellipse(x, y, width, height) { +function Ellipse(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -53,7 +54,8 @@ * @method clone * @return {Ellipse} a copy of the ellipse */ -Ellipse.prototype.clone = function () { +Ellipse.prototype.clone = function () +{ return new Ellipse(this.x, this.y, this.width, this.height); }; @@ -65,8 +67,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coords are within this ellipse */ -Ellipse.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Ellipse.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } @@ -86,6 +90,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Ellipse.prototype.getBounds = function () { +Ellipse.prototype.getBounds = function () +{ return new Rectangle(this.x - this.width, this.y - this.height, this.width, this.height); }; diff --git a/src/core/math/shapes/Polygon.js b/src/core/math/shapes/Polygon.js index ae89148..fea6d37 100644 --- a/src/core/math/shapes/Polygon.js +++ b/src/core/math/shapes/Polygon.js @@ -10,16 +10,20 @@ * arguments passed can be flat x,y values e.g. `new Polygon(x,y, x,y, x,y, ...)` where `x` and `y` are * Numbers. */ -function Polygon(points) { +function Polygon(points) +{ //if points isn't an array, use arguments as the array - if (!(points instanceof Array)) { + if (!(points instanceof Array)) + { points = Array.prototype.slice.call(arguments); } //if this is a flat array of numbers, convert it to points - if (points[0] instanceof Point) { + if (points[0] instanceof Point) + { var p = []; - for (var i = 0, il = points.length; i < il; i++) { + for (var i = 0, il = points.length; i < il; i++) + { p.push(points[i].x, points[i].y); } @@ -51,7 +55,8 @@ * * @return {Polygon} a copy of the polygon */ -Polygon.prototype.clone = function () { +Polygon.prototype.clone = function () +{ return new Polygon(this.points.slice()); }; @@ -62,19 +67,22 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this polygon */ -Polygon.prototype.contains = function (x, y) { +Polygon.prototype.contains = function (x, y) +{ var inside = false; // use some raycasting to test hits // https://github.com/substack/point-in-polygon/blob/master/index.js var length = this.points.length / 2; - for (var i = 0, j = length - 1; i < length; j = i++) { + for (var i = 0, j = length - 1; i < length; j = i++) + { var xi = this.points[i * 2], yi = this.points[i * 2 + 1], xj = this.points[j * 2], yj = this.points[j * 2 + 1], intersect = ((yi > y) !== (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi); - if (intersect) { + if (intersect) + { inside = !inside; } } diff --git a/src/core/display/DisplayObject.js b/src/core/display/DisplayObject.js index 66ebc3c..20e778c 100644 --- a/src/core/display/DisplayObject.js +++ b/src/core/display/DisplayObject.js @@ -7,7 +7,8 @@ * @class * @namespace PIXI */ -function DisplayObject() { +function DisplayObject() +{ /** * The coordinate of the object relative to the local coordinates of the parent. * @@ -152,10 +153,12 @@ * @memberof DisplayObject# */ x: { - get: function () { + get: function () + { return this.position.x; }, - set: function (value) { + set: function (value) + { this.position.x = value; } }, @@ -167,10 +170,12 @@ * @memberof DisplayObject# */ y: { - get: function () { + get: function () + { return this.position.y; }, - set: function (value) { + set: function (value) + { this.position.y = value; } }, @@ -183,11 +188,13 @@ * @readonly */ worldVisible: { - get: function () { + get: function () + { var item = this; do { - if (!item.visible) { + if (!item.visible) + { return false; } @@ -207,17 +214,21 @@ * @memberof DisplayObject# */ mask: { - get: function () { + get: function () + { return this._mask; }, - set: function (value) { - if (this._mask) { + set: function (value) + { + if (this._mask) + { this._mask.isMask = false; } this._mask = value; - if (this._mask) { + if (this._mask) + { this._mask.isMask = true; } } @@ -232,18 +243,23 @@ * @memberof DisplayObject# */ filters: { - get: function () { + get: function () + { return this._filters; }, - set: function (value) { - if (value) { + set: function (value) + { + if (value) + { // now put all the passes in one place.. var passes = []; - for (var i = 0; i < value.length; i++) { + for (var i = 0; i < value.length; i++) + { var filterPasses = value[i].passes; - for (var j = 0; j < filterPasses.length; j++) { + for (var j = 0; j < filterPasses.length; j++) + { passes.push(filterPasses[j]); } } @@ -264,8 +280,9 @@ * * @private */ -DisplayObject.prototype.updateTransform = function () { - +DisplayObject.prototype.updateTransform = function () +{ + // create some matrix refs for easy access var pt = this.parent.worldTransform; var wt = this.worldTransform; @@ -274,9 +291,11 @@ var a, b, c, d, tx, ty; // so if rotation is between 0 then we can simplify the multiplication process.. - if (this.rotation % math.PI_2) { + if (this.rotation % math.PI_2) + { // 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) { + if (this.rotation !== this.rotationCache) + { this.rotationCache = this.rotation; this._sr = Math.sin(this.rotation); this._cr = Math.cos(this.rotation); @@ -291,7 +310,8 @@ ty = this.position.y; // check for pivot.. not often used so geared towards that fact! - if (this.pivot.x || this.pivot.y) { + 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; } @@ -304,7 +324,8 @@ wt.tx = tx * pt.a + ty * pt.c + pt.tx; wt.ty = tx * pt.b + ty * pt.d + pt.ty; } - else { + else + { // lets do the fast version as we know there is no rotation.. a = this.scale.x; d = this.scale.y; @@ -333,7 +354,8 @@ * @param matrix {Matrix} * @return {Rectangle} the rectangular bounding area */ -DisplayObject.prototype.getBounds = function (/* matrix */) { +DisplayObject.prototype.getBounds = function (/* matrix */) +{ return math.Rectangle.EMPTY; }; @@ -342,7 +364,8 @@ * * @return {Rectangle} the rectangular bounding area */ -DisplayObject.prototype.getLocalBounds = function () { +DisplayObject.prototype.getLocalBounds = function () +{ return this.getBounds(math.Matrix.IDENTITY); }; @@ -352,7 +375,8 @@ * @param position {Point} The world origin to calculate from * @return {Point} A point object representing the position of this object */ -DisplayObject.prototype.toGlobal = function (position) { +DisplayObject.prototype.toGlobal = function (position) +{ // don't need to u[date the lot this.displayObjectUpdateTransform(); return this.worldTransform.apply(position); @@ -365,8 +389,10 @@ * @param [from] {DisplayObject} The DisplayObject to calculate the global position from * @return {Point} A point object representing the position of this object */ -DisplayObject.prototype.toLocal = function (position, from) { - if (from) { +DisplayObject.prototype.toLocal = function (position, from) +{ + if (from) + { position = from.toGlobal(position); } @@ -381,7 +407,8 @@ * @param renderer {WebGLRenderer} The renderer * @private */ -DisplayObject.prototype.renderWebGL = function (/* renderer */) { +DisplayObject.prototype.renderWebGL = function (/* renderer */) +{ // OVERWRITE; }; @@ -391,6 +418,7 @@ * @param renderer {CanvasRenderer} The renderer * @private */ -DisplayObject.prototype.renderCanvas = function (/* renderer */) { +DisplayObject.prototype.renderCanvas = function (/* renderer */) +{ // OVERWRITE; }; diff --git a/src/core/display/DisplayObjectContainer.js b/src/core/display/DisplayObjectContainer.js index 689f40b..4625ee8 100644 --- a/src/core/display/DisplayObjectContainer.js +++ b/src/core/display/DisplayObjectContainer.js @@ -12,7 +12,8 @@ * @extends DisplayObject * @namespace PIXI */ -function DisplayObjectContainer() { +function DisplayObjectContainer() +{ DisplayObject.call(this); /** @@ -47,17 +48,21 @@ * @memberof DisplayObjectContainer# */ width: { - get: function () { + get: function () + { return this.scale.x * this.getLocalBounds().width; }, - set: function (value) { + set: function (value) + { var width = this.getLocalBounds().width; - if(width !== 0) { + if(width !== 0) + { this.scale.x = value / width; } - else { + else + { this.scale.x = 1; } @@ -73,17 +78,21 @@ * @memberof DisplayObjectContainer# */ height: { - get: function () { + get: function () + { return this.scale.y * this.getLocalBounds().height; }, - set: function (value) { + set: function (value) + { var height = this.getLocalBounds().height; - if (height !== 0) { + if (height !== 0) + { this.scale.y = value / height ; } - else { + else + { this.scale.y = 1; } @@ -100,18 +109,23 @@ * @memberof DisplayObject# */ cacheAsBitmap: { - get: function () { + get: function () + { return this._cacheAsBitmap; }, - set: function (value) { - if (this._cacheAsBitmap === value) { + set: function (value) + { + if (this._cacheAsBitmap === value) + { return; } - if (value) { + if (value) + { this._generateCachedSprite(); } - else { + else + { this._destroyCachedSprite(); } @@ -126,7 +140,8 @@ * @param child {DisplayObject} The DisplayObject to add to the container * @return {DisplayObject} The child that was added. */ -DisplayObjectContainer.prototype.addChild = function (child) { +DisplayObjectContainer.prototype.addChild = function (child) +{ return this.addChildAt(child, this.children.length); }; @@ -137,14 +152,18 @@ * @param index {Number} The index to place the child in * @return {DisplayObject} The child that was added. */ -DisplayObjectContainer.prototype.addChildAt = function (child, index) { +DisplayObjectContainer.prototype.addChildAt = function (child, index) +{ // prevent adding self as child - if (child === this) { + if (child === this) + { return; } - if (index >= 0 && index <= this.children.length) { - if (child.parent) { + if (index >= 0 && index <= this.children.length) + { + if (child.parent) + { child.parent.removeChild(child); } @@ -154,7 +173,8 @@ return child; } - else { + else + { throw new Error(child + 'addChildAt: The index '+ index +' supplied is out of bounds ' + this.children.length); } }; @@ -165,15 +185,18 @@ * @param child {DisplayObject} * @param child2 {DisplayObject} */ -DisplayObjectContainer.prototype.swapChildren = function (child, child2) { - if (child === child2) { +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) { + if (index1 < 0 || index2 < 0) + { throw new Error('swapChildren: Both the supplied DisplayObjects must be a child of the caller.'); } @@ -187,10 +210,12 @@ * @param child {DisplayObject} The DisplayObject instance to identify * @return {Number} The index position of the child display object to identify */ -DisplayObjectContainer.prototype.getChildIndex = function (child) { +DisplayObjectContainer.prototype.getChildIndex = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { throw new Error('The supplied DisplayObject must be a child of the caller'); } @@ -203,8 +228,10 @@ * @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 */ -DisplayObjectContainer.prototype.setChildIndex = function (child, index) { - if (index < 0 || index >= this.children.length) { +DisplayObjectContainer.prototype.setChildIndex = function (child, index) +{ + if (index < 0 || index >= this.children.length) + { throw new Error('The supplied index is out of bounds'); } @@ -220,8 +247,10 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child at the given index, if any. */ -DisplayObjectContainer.prototype.getChildAt = function (index) { - if (index < 0 || index >= this.children.length) { +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'); } @@ -234,10 +263,12 @@ * @param child {DisplayObject} The DisplayObject to remove * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChild = function (child) { +DisplayObjectContainer.prototype.removeChild = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { return; } @@ -250,7 +281,8 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChildAt = function (index) { +DisplayObjectContainer.prototype.removeChildAt = function (index) +{ var child = this.getChildAt(index); child.parent = null; @@ -265,24 +297,29 @@ * @param beginIndex {Number} The beginning position. Default value is 0. * @param endIndex {Number} The ending position. Default value is size of the container. */ -DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) { +DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) +{ var begin = beginIndex || 0; var end = typeof endIndex === 'number' ? endIndex : this.children.length; var range = end - begin; - if (range > 0 && range <= end) { + if (range > 0 && range <= end) + { var removed = this.children.splice(begin, range); - for (var i = 0; i < removed.length; ++i) { + for (var i = 0; i < removed.length; ++i) + { removed[i].parent = null; } return removed; } - else if (range === 0 && this.children.length === 0) { + else if (range === 0 && this.children.length === 0) + { return []; } - else { + else + { throw new RangeError('removeChildren: numeric values are outside the acceptable range.'); } }; @@ -291,7 +328,8 @@ * Generates and updates the cached sprite for this object. * */ -DisplayObjectContainer.prototype.updateCachedSprite = function () { +DisplayObjectContainer.prototype.updateCachedSprite = function () +{ this._generateCachedSprite(); }; @@ -304,7 +342,8 @@ * @param renderer {CanvasRenderer|WebGLRenderer} The renderer used to generate the texture. * @return {Texture} a texture of the graphics object */ -DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) { +DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) +{ var bounds = this.getLocalBounds(); var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0, renderer, scaleMode, resolution); @@ -322,18 +361,22 @@ * * @private */ -DisplayObjectContainer.prototype.updateTransform = function () { - if (!this.visible) { +DisplayObjectContainer.prototype.updateTransform = function () +{ + if (!this.visible) + { return; } this.displayObjectUpdateTransform(); - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { return; } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } }; @@ -346,8 +389,10 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getBounds = function () { - if (this.children.length === 0) { +DisplayObjectContainer.prototype.getBounds = function () +{ + if (this.children.length === 0) + { return math.Rectangle.EMPTY; } @@ -365,10 +410,12 @@ var childVisible = false; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -386,7 +433,8 @@ maxY = maxY > childMaxY ? maxY : childMaxY; } - if (!childVisible) { + if (!childVisible) + { return math.Rectangle.EMPTY; } @@ -407,12 +455,14 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getLocalBounds = function () { +DisplayObjectContainer.prototype.getLocalBounds = function () +{ var matrixCache = this.worldTransform; this.worldTransform = math.Matrix.IDENTITY; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } @@ -428,13 +478,16 @@ * * @param renderer {WebGLRenderer} The renderer */ -DisplayObjectContainer.prototype.renderWebGL = function (renderer) { +DisplayObjectContainer.prototype.renderWebGL = function (renderer) +{ // if the object is not visible or the alpha is 0 then no need to render this element - if (!this.visible || this.alpha <= 0) { + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } @@ -442,14 +495,17 @@ var i, j; // do a quick check to see if this element has a mask or a filter. - if (this._mask || this._filters) { + if (this._mask || this._filters) + { // push filter first as we need to ensure the stencil buffer is correct for any masking - if (this._filters) { + if (this._filters) + { renderer.spriteBatch.flush(); renderer.filterManager.pushFilter(this._filterBlock); } - if (this._mask) { + if (this._mask) + { renderer.spriteBatch.stop(); renderer.maskManager.pushMask(this.mask, renderer); renderer.spriteBatch.start(); @@ -459,36 +515,42 @@ this._renderWebGL(renderer); // now loop through the children and make sure they get rendered - for (i = 0, j = this.children.length; i < j; i++) { + for (i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderWebGL(renderer); } // time to stop the sprite batch as either a mask element or a filter draw will happen next renderer.spriteBatch.stop(); - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(this._mask, renderer); } - if (this._filters) { + if (this._filters) + { renderer.filterManager.popFilter(); } renderer.spriteBatch.start(); } - else { + else + { this._renderWebGL(renderer); // simple render children! - for (i = 0, j = this.children.length; i < j; ++i) { + for (i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderWebGL(renderer); } } }; -DisplayObjectContainer.prototype._renderWebGL = function (renderer) { +DisplayObjectContainer.prototype._renderWebGL = function (renderer) +{ // this is where content itself gets renderd.. @@ -499,25 +561,31 @@ * * @param renderer {CanvasRenderer} The renderer */ -DisplayObjectContainer.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0) { +DisplayObjectContainer.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -528,13 +596,16 @@ * @param renderer {WebGLRenderer|CanvasRenderer} The renderer * @private */ -DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) { +DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) +{ this._cachedSprite.worldAlpha = this.worldAlpha; - if (renderer.gl) { + if (renderer.gl) + { this._cachedSprite.renderWebGL(renderer); } - else { + else + { this._cachedSprite.renderCanvas(renderer); } }; @@ -544,10 +615,12 @@ * * @private */ -DisplayObjectContainer.prototype._generateCachedSprite = function () { +DisplayObjectContainer.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { // TODO - RenderTexture now *requires* a renderer instance, so this is like broken // because `renderer` isn't actually in scope here :P var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0); @@ -555,7 +628,8 @@ this._cachedSprite = new Sprite(renderTexture); this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.texture.resize(bounds.width | 0, bounds.height | 0); } @@ -580,8 +654,10 @@ * * @private */ -DisplayObjectContainer.prototype._destroyCachedSprite = function () { - if (!this._cachedSprite) { +DisplayObjectContainer.prototype._destroyCachedSprite = function () +{ + if (!this._cachedSprite) + { return; } diff --git a/src/core/display/Sprite.js b/src/core/display/Sprite.js index 707da24..5862aef 100644 --- a/src/core/display/Sprite.js +++ b/src/core/display/Sprite.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param texture {Texture} The texture for this sprite */ -function Sprite(texture) { +function Sprite(texture) +{ DisplayObjectContainer.call(this); /** @@ -85,12 +86,14 @@ this.texture = texture || Texture.EMPTY; } -Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) { +Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) +{ DisplayObjectContainer.prototype.destroy.call(this); this.anchor = null; - if (destroyTexture) { + if (destroyTexture) + { this._texture.destroy(destroyBaseTexture); } @@ -111,10 +114,12 @@ * @memberof Sprite# */ width: { - get: function () { + get: function () + { return this.scale.x * this.texture.frame.width; }, - set: function (value) { + set: function (value) + { this.scale.x = value / this.texture.frame.width; this._width = value; } @@ -127,10 +132,12 @@ * @memberof Sprite# */ height: { - get: function () { + get: function () + { return this.scale.y * this.texture.frame.height; }, - set: function (value) { + set: function (value) + { this.scale.y = value / this.texture.frame.height; this._height = value; } @@ -143,23 +150,29 @@ * @memberof Sprite# */ texture: { - get: function () { + get: function () + { return this._texture; }, - set: function (value) { - if (this._texture === value) { + set: function (value) + { + if (this._texture === value) + { return; } this._texture = value; this.cachedTint = 0xFFFFFF; - if (value) { + if (value) + { // wait for the texture to load - if (value.baseTexture.hasLoaded) { + if (value.baseTexture.hasLoaded) + { this._onTextureUpdate(); } - else { + else + { value.once('update', this._onTextureUpdate.bind(this)); } } @@ -172,18 +185,22 @@ * * @private */ -Sprite.prototype._onTextureUpdate = function () { +Sprite.prototype._onTextureUpdate = function () +{ // so if _width is 0 then width was not set.. - if (this._width) { + if (this._width) + { this.scale.x = this._width / this.texture.frame.width; } - if (this._height) { + if (this._height) + { this.scale.y = this._height / this.texture.frame.height; } }; -Sprite.prototype._renderWebGL = function (renderer) { +Sprite.prototype._renderWebGL = function (renderer) +{ // this is where content gets renderd.. // watch this space for a little render state manager.. @@ -197,7 +214,8 @@ * @param matrix {Matrix} the transformation matrix of the sprite * @return {Rectangle} the framing rectangle */ -Sprite.prototype.getBounds = function (matrix) { +Sprite.prototype.getBounds = function (matrix) +{ var width = this.texture.frame.width; var height = this.texture.frame.height; @@ -224,11 +242,13 @@ if(b === 0 && c === 0) { // scale may be negative! - if (a < 0) { + if (a < 0) + { a *= -1; } - if (d < 0) { + if (d < 0) + { d *= -1; } @@ -293,28 +313,34 @@ * * @param renderer {CanvasRenderer} The renderer */ -Sprite.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) { +Sprite.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) + { return; } - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; renderer.context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } // Ignore null sources - if (this.texture.valid) { + if (this.texture.valid) + { var resolution = this.texture.baseTexture.resolution / renderer.resolution; renderer.context.globalAlpha = this.worldAlpha; // If smoothingEnabled is supported and we need to change the smoothing property for this texture - if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) { + if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) + { renderer.scaleMode = this.texture.baseTexture.scaleMode; renderer.context[renderer.smoothProperty] = (renderer.scaleMode === CONST.scaleModes.LINEAR); } @@ -324,7 +350,8 @@ var dy = (this.texture.trim ? this.texture.trim.y : 0) - (this.anchor.y * this.texture.trim.height); // Allow for pixel rounding - if (renderer.roundPixels) { + if (renderer.roundPixels) + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -337,7 +364,8 @@ dx = dx | 0; dy = dy | 0; } - else { + else + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -348,8 +376,10 @@ ); } - if (this.tint !== 0xFFFFFF) { - if (this.cachedTint !== this.tint) { + if (this.tint !== 0xFFFFFF) + { + if (this.cachedTint !== this.tint) + { this.cachedTint = this.tint; // TODO clean up caching - how to clean up the caches? @@ -368,7 +398,8 @@ this.texture.crop.height / resolution ); } - else { + else + { renderer.context.drawImage( this.texture.baseTexture.source, this.texture.crop.x, @@ -383,11 +414,13 @@ } } - for (var i = 0, j = this.children.length; i < j; i++) { + for (var i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -402,10 +435,12 @@ * @param frameId {String} The frame Id of the texture in the cache * @return {Sprite} A new Sprite using a texture from the texture cache matching the frameId */ -Sprite.fromFrame = function (frameId) { +Sprite.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache' + this); } @@ -420,6 +455,7 @@ * @param imageId {String} The image url of the texture * @return {Sprite} A new Sprite using a texture from the texture cache matching the image id */ -Sprite.fromImage = function (imageId, crossorigin, scaleMode) { +Sprite.fromImage = function (imageId, crossorigin, scaleMode) +{ return new Sprite(Texture.fromImage(imageId, crossorigin, scaleMode)); }; diff --git a/src/core/display/SpriteBatch.js b/src/core/display/SpriteBatch.js index 3187777..c196fef 100644 --- a/src/core/display/SpriteBatch.js +++ b/src/core/display/SpriteBatch.js @@ -12,7 +12,8 @@ * ```js * var container = new SpriteBatch(); * - * for(var i = 0; i < 100; ++i) { + * for(var i = 0; i < 100; ++i) + * { * var sprite = new PIXI.Sprite.fromImage("myImage.png"); * container.addChild(sprite); * } @@ -25,7 +26,8 @@ */ //TODO RENAME to PARTICLE CONTAINER? -function SpriteBatch() { +function SpriteBatch() +{ DisplayObjectContainer.call(this); } @@ -38,7 +40,8 @@ * * @private */ -SpriteBatch.prototype.updateTransform = function () { +SpriteBatch.prototype.updateTransform = function () +{ // TODO don't need to! this.displayObjectUpdateTransform(); // PIXI.DisplayObjectContainer.prototype.updateTransform.call( this ); @@ -50,8 +53,10 @@ * @param renderer {WebGLRenderer} The webgl renderer * @private */ -SpriteBatch.prototype.renderWebGL = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderWebGL = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -71,8 +76,10 @@ * @param renderer {CanvasRenderer} The canvas renderer * @private */ -SpriteBatch.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -84,10 +91,12 @@ this.displayObjectUpdateTransform(); - for (var i = 0; i < this.children.length; ++i) { + for (var i = 0; i < this.children.length; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -95,9 +104,11 @@ context.globalAlpha = this.worldAlpha * child.alpha; - if (child.rotation % (Math.PI * 2) === 0) { + if (child.rotation % (Math.PI * 2) === 0) + { // this is the fastest way to optimise! - if rotation is 0 then we can avoid any kind of setTransform call - if (isRotated) { + if (isRotated) + { context.setTransform( transform.a, transform.b, @@ -122,8 +133,10 @@ frame.height * child.scale.y ); } - else { - if (!isRotated) { + else + { + if (!isRotated) + { isRotated = true; } @@ -131,7 +144,8 @@ var childTransform = child.worldTransform; - if (renderer.roundPixels) { + if (renderer.roundPixels) + { context.setTransform( childTransform.a, childTransform.b, @@ -141,7 +155,8 @@ childTransform.ty | 0 ); } - else { + else + { context.setTransform( childTransform.a, childTransform.b, diff --git a/src/core/index.js b/src/core/index.js index 3954b6f..eb4a82b 100644 --- a/src/core/index.js +++ b/src/core/index.js @@ -58,11 +58,13 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRenderer: function (width, height, options, noWebGL) { + autoDetectRenderer: function (width, height, options, noWebGL) + { width = width || 800; height = height || 600; - if (!noWebGL && require('webgl-enabled')()) { + if (!noWebGL && require('webgl-enabled')()) + { return new core.WebGLRenderer(width, height, options); } @@ -87,7 +89,8 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRecommendedRenderer: function (width, height, options) { + autoDetectRecommendedRenderer: function (width, height, options) + { var isAndroid = /Android/i.test(navigator.userAgent); return core.autoDetectRenderer(width, height, options, isAndroid); diff --git a/src/core/math/Matrix.js b/src/core/math/Matrix.js index c2f87e2..2ff4848 100644 --- a/src/core/math/Matrix.js +++ b/src/core/math/Matrix.js @@ -10,7 +10,8 @@ * @class * @namespace PIXI */ -function Matrix() { +function Matrix() +{ /** * @member {number} * @default 1 @@ -63,7 +64,8 @@ * * @param array {number[]} The array that the matrix will be populated from. */ -Matrix.prototype.fromArray = function (array) { +Matrix.prototype.fromArray = function (array) +{ this.a = array[0]; this.b = array[1]; this.c = array[3]; @@ -78,14 +80,17 @@ * @param transpose {boolean} Whether we need to transpose the matrix or not * @return {number[]} the newly created array which contains the matrix */ -Matrix.prototype.toArray = function (transpose) { - if (!this.array) { +Matrix.prototype.toArray = function (transpose) +{ + if (!this.array) + { this.array = new Float32Array(9); } var array = this.array; - if (transpose) { + if (transpose) + { array[0] = this.a; array[1] = this.b; array[2] = 0; @@ -96,7 +101,8 @@ array[7] = this.ty; array[8] = 1; } - else { + else + { array[0] = this.a; array[1] = this.c; array[2] = this.tx; @@ -119,7 +125,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, transformed through this matrix */ -Matrix.prototype.apply = function (pos, newPos) { +Matrix.prototype.apply = function (pos, newPos) +{ newPos = newPos || new Point(); newPos.x = this.a * pos.x + this.c * pos.y + this.tx; @@ -136,7 +143,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, inverse-transformed through this matrix */ -Matrix.prototype.applyInverse = function (pos, newPos) { +Matrix.prototype.applyInverse = function (pos, newPos) +{ newPos = newPos || new Point(); var id = 1 / (this.a * this.d + this.c * -this.b); @@ -154,7 +162,8 @@ * @param {number} y * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.translate = function (x, y) { +Matrix.prototype.translate = function (x, y) +{ this.tx += x; this.ty += y; @@ -168,7 +177,8 @@ * @param {number} y The amount to scale vertically * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.scale = function (x, y) { +Matrix.prototype.scale = function (x, y) +{ this.a *= x; this.d *= y; this.c *= x; @@ -186,7 +196,8 @@ * @param {number} angle - The angle in radians. * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.rotate = function (angle) { +Matrix.prototype.rotate = function (angle) +{ var cos = Math.cos( angle ); var sin = Math.sin( angle ); @@ -210,7 +221,8 @@ * @param {Matrix} matrix * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.append = function (matrix) { +Matrix.prototype.append = function (matrix) +{ var a1 = this.a; var b1 = this.b; var c1 = this.c; @@ -232,7 +244,8 @@ * * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.identity = function () { +Matrix.prototype.identity = function () +{ this.a = 1; this.b = 0; this.c = 0; diff --git a/src/core/math/Point.js b/src/core/math/Point.js index 7565b2d..632f346 100644 --- a/src/core/math/Point.js +++ b/src/core/math/Point.js @@ -7,7 +7,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -function Point(x, y) { +function Point(x, y) +{ /** * @member {number} * @default 0 @@ -29,7 +30,8 @@ * * @return {Point} a copy of the point */ -Point.prototype.clone = function () { +Point.prototype.clone = function () +{ return new Point(this.x, this.y); }; @@ -40,7 +42,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -Point.prototype.set = function (x, y) { +Point.prototype.set = function (x, y) +{ this.x = x || 0; this.y = y || ( (y !== 0) ? this.x : 0 ) ; }; diff --git a/src/core/math/shapes/Circle.js b/src/core/math/shapes/Circle.js index 69cfdc9..4d76efc 100644 --- a/src/core/math/shapes/Circle.js +++ b/src/core/math/shapes/Circle.js @@ -10,7 +10,8 @@ * @param y {number} The Y coordinate of the center of this circle * @param radius {number} The radius of the circle */ -function Circle(x, y, radius) { +function Circle(x, y, radius) +{ /** * @member {number} * @default 0 @@ -46,7 +47,8 @@ * @method clone * @return {Circle} a copy of the Circle */ -Circle.prototype.clone = function () { +Circle.prototype.clone = function () +{ return new Circle(this.x, this.y, this.radius); }; @@ -58,8 +60,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Circle */ -Circle.prototype.contains = function (x, y) { - if (this.radius <= 0) { +Circle.prototype.contains = function (x, y) +{ + if (this.radius <= 0) + { return false; } @@ -79,6 +83,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Circle.prototype.getBounds = function () { +Circle.prototype.getBounds = function () +{ return new Rectangle(this.x - this.radius, this.y - this.radius, this.radius * 2, this.radius * 2); }; diff --git a/src/core/math/shapes/Ellipse.js b/src/core/math/shapes/Ellipse.js index 4f2d066..fefd01a 100644 --- a/src/core/math/shapes/Ellipse.js +++ b/src/core/math/shapes/Ellipse.js @@ -11,7 +11,8 @@ * @param width {number} The half width of this ellipse * @param height {number} The half height of this ellipse */ -function Ellipse(x, y, width, height) { +function Ellipse(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -53,7 +54,8 @@ * @method clone * @return {Ellipse} a copy of the ellipse */ -Ellipse.prototype.clone = function () { +Ellipse.prototype.clone = function () +{ return new Ellipse(this.x, this.y, this.width, this.height); }; @@ -65,8 +67,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coords are within this ellipse */ -Ellipse.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Ellipse.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } @@ -86,6 +90,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Ellipse.prototype.getBounds = function () { +Ellipse.prototype.getBounds = function () +{ return new Rectangle(this.x - this.width, this.y - this.height, this.width, this.height); }; diff --git a/src/core/math/shapes/Polygon.js b/src/core/math/shapes/Polygon.js index ae89148..fea6d37 100644 --- a/src/core/math/shapes/Polygon.js +++ b/src/core/math/shapes/Polygon.js @@ -10,16 +10,20 @@ * arguments passed can be flat x,y values e.g. `new Polygon(x,y, x,y, x,y, ...)` where `x` and `y` are * Numbers. */ -function Polygon(points) { +function Polygon(points) +{ //if points isn't an array, use arguments as the array - if (!(points instanceof Array)) { + if (!(points instanceof Array)) + { points = Array.prototype.slice.call(arguments); } //if this is a flat array of numbers, convert it to points - if (points[0] instanceof Point) { + if (points[0] instanceof Point) + { var p = []; - for (var i = 0, il = points.length; i < il; i++) { + for (var i = 0, il = points.length; i < il; i++) + { p.push(points[i].x, points[i].y); } @@ -51,7 +55,8 @@ * * @return {Polygon} a copy of the polygon */ -Polygon.prototype.clone = function () { +Polygon.prototype.clone = function () +{ return new Polygon(this.points.slice()); }; @@ -62,19 +67,22 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this polygon */ -Polygon.prototype.contains = function (x, y) { +Polygon.prototype.contains = function (x, y) +{ var inside = false; // use some raycasting to test hits // https://github.com/substack/point-in-polygon/blob/master/index.js var length = this.points.length / 2; - for (var i = 0, j = length - 1; i < length; j = i++) { + for (var i = 0, j = length - 1; i < length; j = i++) + { var xi = this.points[i * 2], yi = this.points[i * 2 + 1], xj = this.points[j * 2], yj = this.points[j * 2 + 1], intersect = ((yi > y) !== (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi); - if (intersect) { + if (intersect) + { inside = !inside; } } diff --git a/src/core/math/shapes/Rectangle.js b/src/core/math/shapes/Rectangle.js index 16ac62a..4008b68 100644 --- a/src/core/math/shapes/Rectangle.js +++ b/src/core/math/shapes/Rectangle.js @@ -10,7 +10,8 @@ * @param width {number} The overall width of this rectangle * @param height {number} The overall height of this rectangle */ -function Rectangle(x, y, width, height) { +function Rectangle(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -60,7 +61,8 @@ * * @return {Rectangle} a copy of the rectangle */ -Rectangle.prototype.clone = function () { +Rectangle.prototype.clone = function () +{ return new Rectangle(this.x, this.y, this.width, this.height); }; @@ -71,13 +73,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rectangle */ -Rectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Rectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/display/DisplayObject.js b/src/core/display/DisplayObject.js index 66ebc3c..20e778c 100644 --- a/src/core/display/DisplayObject.js +++ b/src/core/display/DisplayObject.js @@ -7,7 +7,8 @@ * @class * @namespace PIXI */ -function DisplayObject() { +function DisplayObject() +{ /** * The coordinate of the object relative to the local coordinates of the parent. * @@ -152,10 +153,12 @@ * @memberof DisplayObject# */ x: { - get: function () { + get: function () + { return this.position.x; }, - set: function (value) { + set: function (value) + { this.position.x = value; } }, @@ -167,10 +170,12 @@ * @memberof DisplayObject# */ y: { - get: function () { + get: function () + { return this.position.y; }, - set: function (value) { + set: function (value) + { this.position.y = value; } }, @@ -183,11 +188,13 @@ * @readonly */ worldVisible: { - get: function () { + get: function () + { var item = this; do { - if (!item.visible) { + if (!item.visible) + { return false; } @@ -207,17 +214,21 @@ * @memberof DisplayObject# */ mask: { - get: function () { + get: function () + { return this._mask; }, - set: function (value) { - if (this._mask) { + set: function (value) + { + if (this._mask) + { this._mask.isMask = false; } this._mask = value; - if (this._mask) { + if (this._mask) + { this._mask.isMask = true; } } @@ -232,18 +243,23 @@ * @memberof DisplayObject# */ filters: { - get: function () { + get: function () + { return this._filters; }, - set: function (value) { - if (value) { + set: function (value) + { + if (value) + { // now put all the passes in one place.. var passes = []; - for (var i = 0; i < value.length; i++) { + for (var i = 0; i < value.length; i++) + { var filterPasses = value[i].passes; - for (var j = 0; j < filterPasses.length; j++) { + for (var j = 0; j < filterPasses.length; j++) + { passes.push(filterPasses[j]); } } @@ -264,8 +280,9 @@ * * @private */ -DisplayObject.prototype.updateTransform = function () { - +DisplayObject.prototype.updateTransform = function () +{ + // create some matrix refs for easy access var pt = this.parent.worldTransform; var wt = this.worldTransform; @@ -274,9 +291,11 @@ var a, b, c, d, tx, ty; // so if rotation is between 0 then we can simplify the multiplication process.. - if (this.rotation % math.PI_2) { + if (this.rotation % math.PI_2) + { // 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) { + if (this.rotation !== this.rotationCache) + { this.rotationCache = this.rotation; this._sr = Math.sin(this.rotation); this._cr = Math.cos(this.rotation); @@ -291,7 +310,8 @@ ty = this.position.y; // check for pivot.. not often used so geared towards that fact! - if (this.pivot.x || this.pivot.y) { + 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; } @@ -304,7 +324,8 @@ wt.tx = tx * pt.a + ty * pt.c + pt.tx; wt.ty = tx * pt.b + ty * pt.d + pt.ty; } - else { + else + { // lets do the fast version as we know there is no rotation.. a = this.scale.x; d = this.scale.y; @@ -333,7 +354,8 @@ * @param matrix {Matrix} * @return {Rectangle} the rectangular bounding area */ -DisplayObject.prototype.getBounds = function (/* matrix */) { +DisplayObject.prototype.getBounds = function (/* matrix */) +{ return math.Rectangle.EMPTY; }; @@ -342,7 +364,8 @@ * * @return {Rectangle} the rectangular bounding area */ -DisplayObject.prototype.getLocalBounds = function () { +DisplayObject.prototype.getLocalBounds = function () +{ return this.getBounds(math.Matrix.IDENTITY); }; @@ -352,7 +375,8 @@ * @param position {Point} The world origin to calculate from * @return {Point} A point object representing the position of this object */ -DisplayObject.prototype.toGlobal = function (position) { +DisplayObject.prototype.toGlobal = function (position) +{ // don't need to u[date the lot this.displayObjectUpdateTransform(); return this.worldTransform.apply(position); @@ -365,8 +389,10 @@ * @param [from] {DisplayObject} The DisplayObject to calculate the global position from * @return {Point} A point object representing the position of this object */ -DisplayObject.prototype.toLocal = function (position, from) { - if (from) { +DisplayObject.prototype.toLocal = function (position, from) +{ + if (from) + { position = from.toGlobal(position); } @@ -381,7 +407,8 @@ * @param renderer {WebGLRenderer} The renderer * @private */ -DisplayObject.prototype.renderWebGL = function (/* renderer */) { +DisplayObject.prototype.renderWebGL = function (/* renderer */) +{ // OVERWRITE; }; @@ -391,6 +418,7 @@ * @param renderer {CanvasRenderer} The renderer * @private */ -DisplayObject.prototype.renderCanvas = function (/* renderer */) { +DisplayObject.prototype.renderCanvas = function (/* renderer */) +{ // OVERWRITE; }; diff --git a/src/core/display/DisplayObjectContainer.js b/src/core/display/DisplayObjectContainer.js index 689f40b..4625ee8 100644 --- a/src/core/display/DisplayObjectContainer.js +++ b/src/core/display/DisplayObjectContainer.js @@ -12,7 +12,8 @@ * @extends DisplayObject * @namespace PIXI */ -function DisplayObjectContainer() { +function DisplayObjectContainer() +{ DisplayObject.call(this); /** @@ -47,17 +48,21 @@ * @memberof DisplayObjectContainer# */ width: { - get: function () { + get: function () + { return this.scale.x * this.getLocalBounds().width; }, - set: function (value) { + set: function (value) + { var width = this.getLocalBounds().width; - if(width !== 0) { + if(width !== 0) + { this.scale.x = value / width; } - else { + else + { this.scale.x = 1; } @@ -73,17 +78,21 @@ * @memberof DisplayObjectContainer# */ height: { - get: function () { + get: function () + { return this.scale.y * this.getLocalBounds().height; }, - set: function (value) { + set: function (value) + { var height = this.getLocalBounds().height; - if (height !== 0) { + if (height !== 0) + { this.scale.y = value / height ; } - else { + else + { this.scale.y = 1; } @@ -100,18 +109,23 @@ * @memberof DisplayObject# */ cacheAsBitmap: { - get: function () { + get: function () + { return this._cacheAsBitmap; }, - set: function (value) { - if (this._cacheAsBitmap === value) { + set: function (value) + { + if (this._cacheAsBitmap === value) + { return; } - if (value) { + if (value) + { this._generateCachedSprite(); } - else { + else + { this._destroyCachedSprite(); } @@ -126,7 +140,8 @@ * @param child {DisplayObject} The DisplayObject to add to the container * @return {DisplayObject} The child that was added. */ -DisplayObjectContainer.prototype.addChild = function (child) { +DisplayObjectContainer.prototype.addChild = function (child) +{ return this.addChildAt(child, this.children.length); }; @@ -137,14 +152,18 @@ * @param index {Number} The index to place the child in * @return {DisplayObject} The child that was added. */ -DisplayObjectContainer.prototype.addChildAt = function (child, index) { +DisplayObjectContainer.prototype.addChildAt = function (child, index) +{ // prevent adding self as child - if (child === this) { + if (child === this) + { return; } - if (index >= 0 && index <= this.children.length) { - if (child.parent) { + if (index >= 0 && index <= this.children.length) + { + if (child.parent) + { child.parent.removeChild(child); } @@ -154,7 +173,8 @@ return child; } - else { + else + { throw new Error(child + 'addChildAt: The index '+ index +' supplied is out of bounds ' + this.children.length); } }; @@ -165,15 +185,18 @@ * @param child {DisplayObject} * @param child2 {DisplayObject} */ -DisplayObjectContainer.prototype.swapChildren = function (child, child2) { - if (child === child2) { +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) { + if (index1 < 0 || index2 < 0) + { throw new Error('swapChildren: Both the supplied DisplayObjects must be a child of the caller.'); } @@ -187,10 +210,12 @@ * @param child {DisplayObject} The DisplayObject instance to identify * @return {Number} The index position of the child display object to identify */ -DisplayObjectContainer.prototype.getChildIndex = function (child) { +DisplayObjectContainer.prototype.getChildIndex = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { throw new Error('The supplied DisplayObject must be a child of the caller'); } @@ -203,8 +228,10 @@ * @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 */ -DisplayObjectContainer.prototype.setChildIndex = function (child, index) { - if (index < 0 || index >= this.children.length) { +DisplayObjectContainer.prototype.setChildIndex = function (child, index) +{ + if (index < 0 || index >= this.children.length) + { throw new Error('The supplied index is out of bounds'); } @@ -220,8 +247,10 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child at the given index, if any. */ -DisplayObjectContainer.prototype.getChildAt = function (index) { - if (index < 0 || index >= this.children.length) { +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'); } @@ -234,10 +263,12 @@ * @param child {DisplayObject} The DisplayObject to remove * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChild = function (child) { +DisplayObjectContainer.prototype.removeChild = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { return; } @@ -250,7 +281,8 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChildAt = function (index) { +DisplayObjectContainer.prototype.removeChildAt = function (index) +{ var child = this.getChildAt(index); child.parent = null; @@ -265,24 +297,29 @@ * @param beginIndex {Number} The beginning position. Default value is 0. * @param endIndex {Number} The ending position. Default value is size of the container. */ -DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) { +DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) +{ var begin = beginIndex || 0; var end = typeof endIndex === 'number' ? endIndex : this.children.length; var range = end - begin; - if (range > 0 && range <= end) { + if (range > 0 && range <= end) + { var removed = this.children.splice(begin, range); - for (var i = 0; i < removed.length; ++i) { + for (var i = 0; i < removed.length; ++i) + { removed[i].parent = null; } return removed; } - else if (range === 0 && this.children.length === 0) { + else if (range === 0 && this.children.length === 0) + { return []; } - else { + else + { throw new RangeError('removeChildren: numeric values are outside the acceptable range.'); } }; @@ -291,7 +328,8 @@ * Generates and updates the cached sprite for this object. * */ -DisplayObjectContainer.prototype.updateCachedSprite = function () { +DisplayObjectContainer.prototype.updateCachedSprite = function () +{ this._generateCachedSprite(); }; @@ -304,7 +342,8 @@ * @param renderer {CanvasRenderer|WebGLRenderer} The renderer used to generate the texture. * @return {Texture} a texture of the graphics object */ -DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) { +DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) +{ var bounds = this.getLocalBounds(); var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0, renderer, scaleMode, resolution); @@ -322,18 +361,22 @@ * * @private */ -DisplayObjectContainer.prototype.updateTransform = function () { - if (!this.visible) { +DisplayObjectContainer.prototype.updateTransform = function () +{ + if (!this.visible) + { return; } this.displayObjectUpdateTransform(); - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { return; } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } }; @@ -346,8 +389,10 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getBounds = function () { - if (this.children.length === 0) { +DisplayObjectContainer.prototype.getBounds = function () +{ + if (this.children.length === 0) + { return math.Rectangle.EMPTY; } @@ -365,10 +410,12 @@ var childVisible = false; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -386,7 +433,8 @@ maxY = maxY > childMaxY ? maxY : childMaxY; } - if (!childVisible) { + if (!childVisible) + { return math.Rectangle.EMPTY; } @@ -407,12 +455,14 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getLocalBounds = function () { +DisplayObjectContainer.prototype.getLocalBounds = function () +{ var matrixCache = this.worldTransform; this.worldTransform = math.Matrix.IDENTITY; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } @@ -428,13 +478,16 @@ * * @param renderer {WebGLRenderer} The renderer */ -DisplayObjectContainer.prototype.renderWebGL = function (renderer) { +DisplayObjectContainer.prototype.renderWebGL = function (renderer) +{ // if the object is not visible or the alpha is 0 then no need to render this element - if (!this.visible || this.alpha <= 0) { + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } @@ -442,14 +495,17 @@ var i, j; // do a quick check to see if this element has a mask or a filter. - if (this._mask || this._filters) { + if (this._mask || this._filters) + { // push filter first as we need to ensure the stencil buffer is correct for any masking - if (this._filters) { + if (this._filters) + { renderer.spriteBatch.flush(); renderer.filterManager.pushFilter(this._filterBlock); } - if (this._mask) { + if (this._mask) + { renderer.spriteBatch.stop(); renderer.maskManager.pushMask(this.mask, renderer); renderer.spriteBatch.start(); @@ -459,36 +515,42 @@ this._renderWebGL(renderer); // now loop through the children and make sure they get rendered - for (i = 0, j = this.children.length; i < j; i++) { + for (i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderWebGL(renderer); } // time to stop the sprite batch as either a mask element or a filter draw will happen next renderer.spriteBatch.stop(); - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(this._mask, renderer); } - if (this._filters) { + if (this._filters) + { renderer.filterManager.popFilter(); } renderer.spriteBatch.start(); } - else { + else + { this._renderWebGL(renderer); // simple render children! - for (i = 0, j = this.children.length; i < j; ++i) { + for (i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderWebGL(renderer); } } }; -DisplayObjectContainer.prototype._renderWebGL = function (renderer) { +DisplayObjectContainer.prototype._renderWebGL = function (renderer) +{ // this is where content itself gets renderd.. @@ -499,25 +561,31 @@ * * @param renderer {CanvasRenderer} The renderer */ -DisplayObjectContainer.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0) { +DisplayObjectContainer.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -528,13 +596,16 @@ * @param renderer {WebGLRenderer|CanvasRenderer} The renderer * @private */ -DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) { +DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) +{ this._cachedSprite.worldAlpha = this.worldAlpha; - if (renderer.gl) { + if (renderer.gl) + { this._cachedSprite.renderWebGL(renderer); } - else { + else + { this._cachedSprite.renderCanvas(renderer); } }; @@ -544,10 +615,12 @@ * * @private */ -DisplayObjectContainer.prototype._generateCachedSprite = function () { +DisplayObjectContainer.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { // TODO - RenderTexture now *requires* a renderer instance, so this is like broken // because `renderer` isn't actually in scope here :P var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0); @@ -555,7 +628,8 @@ this._cachedSprite = new Sprite(renderTexture); this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.texture.resize(bounds.width | 0, bounds.height | 0); } @@ -580,8 +654,10 @@ * * @private */ -DisplayObjectContainer.prototype._destroyCachedSprite = function () { - if (!this._cachedSprite) { +DisplayObjectContainer.prototype._destroyCachedSprite = function () +{ + if (!this._cachedSprite) + { return; } diff --git a/src/core/display/Sprite.js b/src/core/display/Sprite.js index 707da24..5862aef 100644 --- a/src/core/display/Sprite.js +++ b/src/core/display/Sprite.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param texture {Texture} The texture for this sprite */ -function Sprite(texture) { +function Sprite(texture) +{ DisplayObjectContainer.call(this); /** @@ -85,12 +86,14 @@ this.texture = texture || Texture.EMPTY; } -Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) { +Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) +{ DisplayObjectContainer.prototype.destroy.call(this); this.anchor = null; - if (destroyTexture) { + if (destroyTexture) + { this._texture.destroy(destroyBaseTexture); } @@ -111,10 +114,12 @@ * @memberof Sprite# */ width: { - get: function () { + get: function () + { return this.scale.x * this.texture.frame.width; }, - set: function (value) { + set: function (value) + { this.scale.x = value / this.texture.frame.width; this._width = value; } @@ -127,10 +132,12 @@ * @memberof Sprite# */ height: { - get: function () { + get: function () + { return this.scale.y * this.texture.frame.height; }, - set: function (value) { + set: function (value) + { this.scale.y = value / this.texture.frame.height; this._height = value; } @@ -143,23 +150,29 @@ * @memberof Sprite# */ texture: { - get: function () { + get: function () + { return this._texture; }, - set: function (value) { - if (this._texture === value) { + set: function (value) + { + if (this._texture === value) + { return; } this._texture = value; this.cachedTint = 0xFFFFFF; - if (value) { + if (value) + { // wait for the texture to load - if (value.baseTexture.hasLoaded) { + if (value.baseTexture.hasLoaded) + { this._onTextureUpdate(); } - else { + else + { value.once('update', this._onTextureUpdate.bind(this)); } } @@ -172,18 +185,22 @@ * * @private */ -Sprite.prototype._onTextureUpdate = function () { +Sprite.prototype._onTextureUpdate = function () +{ // so if _width is 0 then width was not set.. - if (this._width) { + if (this._width) + { this.scale.x = this._width / this.texture.frame.width; } - if (this._height) { + if (this._height) + { this.scale.y = this._height / this.texture.frame.height; } }; -Sprite.prototype._renderWebGL = function (renderer) { +Sprite.prototype._renderWebGL = function (renderer) +{ // this is where content gets renderd.. // watch this space for a little render state manager.. @@ -197,7 +214,8 @@ * @param matrix {Matrix} the transformation matrix of the sprite * @return {Rectangle} the framing rectangle */ -Sprite.prototype.getBounds = function (matrix) { +Sprite.prototype.getBounds = function (matrix) +{ var width = this.texture.frame.width; var height = this.texture.frame.height; @@ -224,11 +242,13 @@ if(b === 0 && c === 0) { // scale may be negative! - if (a < 0) { + if (a < 0) + { a *= -1; } - if (d < 0) { + if (d < 0) + { d *= -1; } @@ -293,28 +313,34 @@ * * @param renderer {CanvasRenderer} The renderer */ -Sprite.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) { +Sprite.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) + { return; } - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; renderer.context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } // Ignore null sources - if (this.texture.valid) { + if (this.texture.valid) + { var resolution = this.texture.baseTexture.resolution / renderer.resolution; renderer.context.globalAlpha = this.worldAlpha; // If smoothingEnabled is supported and we need to change the smoothing property for this texture - if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) { + if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) + { renderer.scaleMode = this.texture.baseTexture.scaleMode; renderer.context[renderer.smoothProperty] = (renderer.scaleMode === CONST.scaleModes.LINEAR); } @@ -324,7 +350,8 @@ var dy = (this.texture.trim ? this.texture.trim.y : 0) - (this.anchor.y * this.texture.trim.height); // Allow for pixel rounding - if (renderer.roundPixels) { + if (renderer.roundPixels) + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -337,7 +364,8 @@ dx = dx | 0; dy = dy | 0; } - else { + else + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -348,8 +376,10 @@ ); } - if (this.tint !== 0xFFFFFF) { - if (this.cachedTint !== this.tint) { + if (this.tint !== 0xFFFFFF) + { + if (this.cachedTint !== this.tint) + { this.cachedTint = this.tint; // TODO clean up caching - how to clean up the caches? @@ -368,7 +398,8 @@ this.texture.crop.height / resolution ); } - else { + else + { renderer.context.drawImage( this.texture.baseTexture.source, this.texture.crop.x, @@ -383,11 +414,13 @@ } } - for (var i = 0, j = this.children.length; i < j; i++) { + for (var i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -402,10 +435,12 @@ * @param frameId {String} The frame Id of the texture in the cache * @return {Sprite} A new Sprite using a texture from the texture cache matching the frameId */ -Sprite.fromFrame = function (frameId) { +Sprite.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache' + this); } @@ -420,6 +455,7 @@ * @param imageId {String} The image url of the texture * @return {Sprite} A new Sprite using a texture from the texture cache matching the image id */ -Sprite.fromImage = function (imageId, crossorigin, scaleMode) { +Sprite.fromImage = function (imageId, crossorigin, scaleMode) +{ return new Sprite(Texture.fromImage(imageId, crossorigin, scaleMode)); }; diff --git a/src/core/display/SpriteBatch.js b/src/core/display/SpriteBatch.js index 3187777..c196fef 100644 --- a/src/core/display/SpriteBatch.js +++ b/src/core/display/SpriteBatch.js @@ -12,7 +12,8 @@ * ```js * var container = new SpriteBatch(); * - * for(var i = 0; i < 100; ++i) { + * for(var i = 0; i < 100; ++i) + * { * var sprite = new PIXI.Sprite.fromImage("myImage.png"); * container.addChild(sprite); * } @@ -25,7 +26,8 @@ */ //TODO RENAME to PARTICLE CONTAINER? -function SpriteBatch() { +function SpriteBatch() +{ DisplayObjectContainer.call(this); } @@ -38,7 +40,8 @@ * * @private */ -SpriteBatch.prototype.updateTransform = function () { +SpriteBatch.prototype.updateTransform = function () +{ // TODO don't need to! this.displayObjectUpdateTransform(); // PIXI.DisplayObjectContainer.prototype.updateTransform.call( this ); @@ -50,8 +53,10 @@ * @param renderer {WebGLRenderer} The webgl renderer * @private */ -SpriteBatch.prototype.renderWebGL = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderWebGL = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -71,8 +76,10 @@ * @param renderer {CanvasRenderer} The canvas renderer * @private */ -SpriteBatch.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -84,10 +91,12 @@ this.displayObjectUpdateTransform(); - for (var i = 0; i < this.children.length; ++i) { + for (var i = 0; i < this.children.length; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -95,9 +104,11 @@ context.globalAlpha = this.worldAlpha * child.alpha; - if (child.rotation % (Math.PI * 2) === 0) { + if (child.rotation % (Math.PI * 2) === 0) + { // this is the fastest way to optimise! - if rotation is 0 then we can avoid any kind of setTransform call - if (isRotated) { + if (isRotated) + { context.setTransform( transform.a, transform.b, @@ -122,8 +133,10 @@ frame.height * child.scale.y ); } - else { - if (!isRotated) { + else + { + if (!isRotated) + { isRotated = true; } @@ -131,7 +144,8 @@ var childTransform = child.worldTransform; - if (renderer.roundPixels) { + if (renderer.roundPixels) + { context.setTransform( childTransform.a, childTransform.b, @@ -141,7 +155,8 @@ childTransform.ty | 0 ); } - else { + else + { context.setTransform( childTransform.a, childTransform.b, diff --git a/src/core/index.js b/src/core/index.js index 3954b6f..eb4a82b 100644 --- a/src/core/index.js +++ b/src/core/index.js @@ -58,11 +58,13 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRenderer: function (width, height, options, noWebGL) { + autoDetectRenderer: function (width, height, options, noWebGL) + { width = width || 800; height = height || 600; - if (!noWebGL && require('webgl-enabled')()) { + if (!noWebGL && require('webgl-enabled')()) + { return new core.WebGLRenderer(width, height, options); } @@ -87,7 +89,8 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRecommendedRenderer: function (width, height, options) { + autoDetectRecommendedRenderer: function (width, height, options) + { var isAndroid = /Android/i.test(navigator.userAgent); return core.autoDetectRenderer(width, height, options, isAndroid); diff --git a/src/core/math/Matrix.js b/src/core/math/Matrix.js index c2f87e2..2ff4848 100644 --- a/src/core/math/Matrix.js +++ b/src/core/math/Matrix.js @@ -10,7 +10,8 @@ * @class * @namespace PIXI */ -function Matrix() { +function Matrix() +{ /** * @member {number} * @default 1 @@ -63,7 +64,8 @@ * * @param array {number[]} The array that the matrix will be populated from. */ -Matrix.prototype.fromArray = function (array) { +Matrix.prototype.fromArray = function (array) +{ this.a = array[0]; this.b = array[1]; this.c = array[3]; @@ -78,14 +80,17 @@ * @param transpose {boolean} Whether we need to transpose the matrix or not * @return {number[]} the newly created array which contains the matrix */ -Matrix.prototype.toArray = function (transpose) { - if (!this.array) { +Matrix.prototype.toArray = function (transpose) +{ + if (!this.array) + { this.array = new Float32Array(9); } var array = this.array; - if (transpose) { + if (transpose) + { array[0] = this.a; array[1] = this.b; array[2] = 0; @@ -96,7 +101,8 @@ array[7] = this.ty; array[8] = 1; } - else { + else + { array[0] = this.a; array[1] = this.c; array[2] = this.tx; @@ -119,7 +125,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, transformed through this matrix */ -Matrix.prototype.apply = function (pos, newPos) { +Matrix.prototype.apply = function (pos, newPos) +{ newPos = newPos || new Point(); newPos.x = this.a * pos.x + this.c * pos.y + this.tx; @@ -136,7 +143,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, inverse-transformed through this matrix */ -Matrix.prototype.applyInverse = function (pos, newPos) { +Matrix.prototype.applyInverse = function (pos, newPos) +{ newPos = newPos || new Point(); var id = 1 / (this.a * this.d + this.c * -this.b); @@ -154,7 +162,8 @@ * @param {number} y * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.translate = function (x, y) { +Matrix.prototype.translate = function (x, y) +{ this.tx += x; this.ty += y; @@ -168,7 +177,8 @@ * @param {number} y The amount to scale vertically * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.scale = function (x, y) { +Matrix.prototype.scale = function (x, y) +{ this.a *= x; this.d *= y; this.c *= x; @@ -186,7 +196,8 @@ * @param {number} angle - The angle in radians. * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.rotate = function (angle) { +Matrix.prototype.rotate = function (angle) +{ var cos = Math.cos( angle ); var sin = Math.sin( angle ); @@ -210,7 +221,8 @@ * @param {Matrix} matrix * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.append = function (matrix) { +Matrix.prototype.append = function (matrix) +{ var a1 = this.a; var b1 = this.b; var c1 = this.c; @@ -232,7 +244,8 @@ * * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.identity = function () { +Matrix.prototype.identity = function () +{ this.a = 1; this.b = 0; this.c = 0; diff --git a/src/core/math/Point.js b/src/core/math/Point.js index 7565b2d..632f346 100644 --- a/src/core/math/Point.js +++ b/src/core/math/Point.js @@ -7,7 +7,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -function Point(x, y) { +function Point(x, y) +{ /** * @member {number} * @default 0 @@ -29,7 +30,8 @@ * * @return {Point} a copy of the point */ -Point.prototype.clone = function () { +Point.prototype.clone = function () +{ return new Point(this.x, this.y); }; @@ -40,7 +42,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -Point.prototype.set = function (x, y) { +Point.prototype.set = function (x, y) +{ this.x = x || 0; this.y = y || ( (y !== 0) ? this.x : 0 ) ; }; diff --git a/src/core/math/shapes/Circle.js b/src/core/math/shapes/Circle.js index 69cfdc9..4d76efc 100644 --- a/src/core/math/shapes/Circle.js +++ b/src/core/math/shapes/Circle.js @@ -10,7 +10,8 @@ * @param y {number} The Y coordinate of the center of this circle * @param radius {number} The radius of the circle */ -function Circle(x, y, radius) { +function Circle(x, y, radius) +{ /** * @member {number} * @default 0 @@ -46,7 +47,8 @@ * @method clone * @return {Circle} a copy of the Circle */ -Circle.prototype.clone = function () { +Circle.prototype.clone = function () +{ return new Circle(this.x, this.y, this.radius); }; @@ -58,8 +60,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Circle */ -Circle.prototype.contains = function (x, y) { - if (this.radius <= 0) { +Circle.prototype.contains = function (x, y) +{ + if (this.radius <= 0) + { return false; } @@ -79,6 +83,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Circle.prototype.getBounds = function () { +Circle.prototype.getBounds = function () +{ return new Rectangle(this.x - this.radius, this.y - this.radius, this.radius * 2, this.radius * 2); }; diff --git a/src/core/math/shapes/Ellipse.js b/src/core/math/shapes/Ellipse.js index 4f2d066..fefd01a 100644 --- a/src/core/math/shapes/Ellipse.js +++ b/src/core/math/shapes/Ellipse.js @@ -11,7 +11,8 @@ * @param width {number} The half width of this ellipse * @param height {number} The half height of this ellipse */ -function Ellipse(x, y, width, height) { +function Ellipse(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -53,7 +54,8 @@ * @method clone * @return {Ellipse} a copy of the ellipse */ -Ellipse.prototype.clone = function () { +Ellipse.prototype.clone = function () +{ return new Ellipse(this.x, this.y, this.width, this.height); }; @@ -65,8 +67,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coords are within this ellipse */ -Ellipse.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Ellipse.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } @@ -86,6 +90,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Ellipse.prototype.getBounds = function () { +Ellipse.prototype.getBounds = function () +{ return new Rectangle(this.x - this.width, this.y - this.height, this.width, this.height); }; diff --git a/src/core/math/shapes/Polygon.js b/src/core/math/shapes/Polygon.js index ae89148..fea6d37 100644 --- a/src/core/math/shapes/Polygon.js +++ b/src/core/math/shapes/Polygon.js @@ -10,16 +10,20 @@ * arguments passed can be flat x,y values e.g. `new Polygon(x,y, x,y, x,y, ...)` where `x` and `y` are * Numbers. */ -function Polygon(points) { +function Polygon(points) +{ //if points isn't an array, use arguments as the array - if (!(points instanceof Array)) { + if (!(points instanceof Array)) + { points = Array.prototype.slice.call(arguments); } //if this is a flat array of numbers, convert it to points - if (points[0] instanceof Point) { + if (points[0] instanceof Point) + { var p = []; - for (var i = 0, il = points.length; i < il; i++) { + for (var i = 0, il = points.length; i < il; i++) + { p.push(points[i].x, points[i].y); } @@ -51,7 +55,8 @@ * * @return {Polygon} a copy of the polygon */ -Polygon.prototype.clone = function () { +Polygon.prototype.clone = function () +{ return new Polygon(this.points.slice()); }; @@ -62,19 +67,22 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this polygon */ -Polygon.prototype.contains = function (x, y) { +Polygon.prototype.contains = function (x, y) +{ var inside = false; // use some raycasting to test hits // https://github.com/substack/point-in-polygon/blob/master/index.js var length = this.points.length / 2; - for (var i = 0, j = length - 1; i < length; j = i++) { + for (var i = 0, j = length - 1; i < length; j = i++) + { var xi = this.points[i * 2], yi = this.points[i * 2 + 1], xj = this.points[j * 2], yj = this.points[j * 2 + 1], intersect = ((yi > y) !== (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi); - if (intersect) { + if (intersect) + { inside = !inside; } } diff --git a/src/core/math/shapes/Rectangle.js b/src/core/math/shapes/Rectangle.js index 16ac62a..4008b68 100644 --- a/src/core/math/shapes/Rectangle.js +++ b/src/core/math/shapes/Rectangle.js @@ -10,7 +10,8 @@ * @param width {number} The overall width of this rectangle * @param height {number} The overall height of this rectangle */ -function Rectangle(x, y, width, height) { +function Rectangle(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -60,7 +61,8 @@ * * @return {Rectangle} a copy of the rectangle */ -Rectangle.prototype.clone = function () { +Rectangle.prototype.clone = function () +{ return new Rectangle(this.x, this.y, this.width, this.height); }; @@ -71,13 +73,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rectangle */ -Rectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Rectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/math/shapes/RoundedRectangle.js b/src/core/math/shapes/RoundedRectangle.js index 27d286e..7bf6411 100644 --- a/src/core/math/shapes/RoundedRectangle.js +++ b/src/core/math/shapes/RoundedRectangle.js @@ -11,7 +11,8 @@ * @param height {number} The overall height of this rounded rectangle * @param radius {number} Controls the radius of the rounded corners */ -function RoundedRectangle(x, y, width, height, radius) { +function RoundedRectangle(x, y, width, height, radius) +{ /** * @member {number} * @default 0 @@ -58,7 +59,8 @@ * * @return {RoundedRectangle} a copy of the rounded rectangle */ -RoundedRectangle.prototype.clone = function () { +RoundedRectangle.prototype.clone = function () +{ return new RoundedRectangle(this.x, this.y, this.width, this.height, this.radius); }; @@ -69,13 +71,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rounded Rectangle */ -RoundedRectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +RoundedRectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/display/DisplayObject.js b/src/core/display/DisplayObject.js index 66ebc3c..20e778c 100644 --- a/src/core/display/DisplayObject.js +++ b/src/core/display/DisplayObject.js @@ -7,7 +7,8 @@ * @class * @namespace PIXI */ -function DisplayObject() { +function DisplayObject() +{ /** * The coordinate of the object relative to the local coordinates of the parent. * @@ -152,10 +153,12 @@ * @memberof DisplayObject# */ x: { - get: function () { + get: function () + { return this.position.x; }, - set: function (value) { + set: function (value) + { this.position.x = value; } }, @@ -167,10 +170,12 @@ * @memberof DisplayObject# */ y: { - get: function () { + get: function () + { return this.position.y; }, - set: function (value) { + set: function (value) + { this.position.y = value; } }, @@ -183,11 +188,13 @@ * @readonly */ worldVisible: { - get: function () { + get: function () + { var item = this; do { - if (!item.visible) { + if (!item.visible) + { return false; } @@ -207,17 +214,21 @@ * @memberof DisplayObject# */ mask: { - get: function () { + get: function () + { return this._mask; }, - set: function (value) { - if (this._mask) { + set: function (value) + { + if (this._mask) + { this._mask.isMask = false; } this._mask = value; - if (this._mask) { + if (this._mask) + { this._mask.isMask = true; } } @@ -232,18 +243,23 @@ * @memberof DisplayObject# */ filters: { - get: function () { + get: function () + { return this._filters; }, - set: function (value) { - if (value) { + set: function (value) + { + if (value) + { // now put all the passes in one place.. var passes = []; - for (var i = 0; i < value.length; i++) { + for (var i = 0; i < value.length; i++) + { var filterPasses = value[i].passes; - for (var j = 0; j < filterPasses.length; j++) { + for (var j = 0; j < filterPasses.length; j++) + { passes.push(filterPasses[j]); } } @@ -264,8 +280,9 @@ * * @private */ -DisplayObject.prototype.updateTransform = function () { - +DisplayObject.prototype.updateTransform = function () +{ + // create some matrix refs for easy access var pt = this.parent.worldTransform; var wt = this.worldTransform; @@ -274,9 +291,11 @@ var a, b, c, d, tx, ty; // so if rotation is between 0 then we can simplify the multiplication process.. - if (this.rotation % math.PI_2) { + if (this.rotation % math.PI_2) + { // 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) { + if (this.rotation !== this.rotationCache) + { this.rotationCache = this.rotation; this._sr = Math.sin(this.rotation); this._cr = Math.cos(this.rotation); @@ -291,7 +310,8 @@ ty = this.position.y; // check for pivot.. not often used so geared towards that fact! - if (this.pivot.x || this.pivot.y) { + 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; } @@ -304,7 +324,8 @@ wt.tx = tx * pt.a + ty * pt.c + pt.tx; wt.ty = tx * pt.b + ty * pt.d + pt.ty; } - else { + else + { // lets do the fast version as we know there is no rotation.. a = this.scale.x; d = this.scale.y; @@ -333,7 +354,8 @@ * @param matrix {Matrix} * @return {Rectangle} the rectangular bounding area */ -DisplayObject.prototype.getBounds = function (/* matrix */) { +DisplayObject.prototype.getBounds = function (/* matrix */) +{ return math.Rectangle.EMPTY; }; @@ -342,7 +364,8 @@ * * @return {Rectangle} the rectangular bounding area */ -DisplayObject.prototype.getLocalBounds = function () { +DisplayObject.prototype.getLocalBounds = function () +{ return this.getBounds(math.Matrix.IDENTITY); }; @@ -352,7 +375,8 @@ * @param position {Point} The world origin to calculate from * @return {Point} A point object representing the position of this object */ -DisplayObject.prototype.toGlobal = function (position) { +DisplayObject.prototype.toGlobal = function (position) +{ // don't need to u[date the lot this.displayObjectUpdateTransform(); return this.worldTransform.apply(position); @@ -365,8 +389,10 @@ * @param [from] {DisplayObject} The DisplayObject to calculate the global position from * @return {Point} A point object representing the position of this object */ -DisplayObject.prototype.toLocal = function (position, from) { - if (from) { +DisplayObject.prototype.toLocal = function (position, from) +{ + if (from) + { position = from.toGlobal(position); } @@ -381,7 +407,8 @@ * @param renderer {WebGLRenderer} The renderer * @private */ -DisplayObject.prototype.renderWebGL = function (/* renderer */) { +DisplayObject.prototype.renderWebGL = function (/* renderer */) +{ // OVERWRITE; }; @@ -391,6 +418,7 @@ * @param renderer {CanvasRenderer} The renderer * @private */ -DisplayObject.prototype.renderCanvas = function (/* renderer */) { +DisplayObject.prototype.renderCanvas = function (/* renderer */) +{ // OVERWRITE; }; diff --git a/src/core/display/DisplayObjectContainer.js b/src/core/display/DisplayObjectContainer.js index 689f40b..4625ee8 100644 --- a/src/core/display/DisplayObjectContainer.js +++ b/src/core/display/DisplayObjectContainer.js @@ -12,7 +12,8 @@ * @extends DisplayObject * @namespace PIXI */ -function DisplayObjectContainer() { +function DisplayObjectContainer() +{ DisplayObject.call(this); /** @@ -47,17 +48,21 @@ * @memberof DisplayObjectContainer# */ width: { - get: function () { + get: function () + { return this.scale.x * this.getLocalBounds().width; }, - set: function (value) { + set: function (value) + { var width = this.getLocalBounds().width; - if(width !== 0) { + if(width !== 0) + { this.scale.x = value / width; } - else { + else + { this.scale.x = 1; } @@ -73,17 +78,21 @@ * @memberof DisplayObjectContainer# */ height: { - get: function () { + get: function () + { return this.scale.y * this.getLocalBounds().height; }, - set: function (value) { + set: function (value) + { var height = this.getLocalBounds().height; - if (height !== 0) { + if (height !== 0) + { this.scale.y = value / height ; } - else { + else + { this.scale.y = 1; } @@ -100,18 +109,23 @@ * @memberof DisplayObject# */ cacheAsBitmap: { - get: function () { + get: function () + { return this._cacheAsBitmap; }, - set: function (value) { - if (this._cacheAsBitmap === value) { + set: function (value) + { + if (this._cacheAsBitmap === value) + { return; } - if (value) { + if (value) + { this._generateCachedSprite(); } - else { + else + { this._destroyCachedSprite(); } @@ -126,7 +140,8 @@ * @param child {DisplayObject} The DisplayObject to add to the container * @return {DisplayObject} The child that was added. */ -DisplayObjectContainer.prototype.addChild = function (child) { +DisplayObjectContainer.prototype.addChild = function (child) +{ return this.addChildAt(child, this.children.length); }; @@ -137,14 +152,18 @@ * @param index {Number} The index to place the child in * @return {DisplayObject} The child that was added. */ -DisplayObjectContainer.prototype.addChildAt = function (child, index) { +DisplayObjectContainer.prototype.addChildAt = function (child, index) +{ // prevent adding self as child - if (child === this) { + if (child === this) + { return; } - if (index >= 0 && index <= this.children.length) { - if (child.parent) { + if (index >= 0 && index <= this.children.length) + { + if (child.parent) + { child.parent.removeChild(child); } @@ -154,7 +173,8 @@ return child; } - else { + else + { throw new Error(child + 'addChildAt: The index '+ index +' supplied is out of bounds ' + this.children.length); } }; @@ -165,15 +185,18 @@ * @param child {DisplayObject} * @param child2 {DisplayObject} */ -DisplayObjectContainer.prototype.swapChildren = function (child, child2) { - if (child === child2) { +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) { + if (index1 < 0 || index2 < 0) + { throw new Error('swapChildren: Both the supplied DisplayObjects must be a child of the caller.'); } @@ -187,10 +210,12 @@ * @param child {DisplayObject} The DisplayObject instance to identify * @return {Number} The index position of the child display object to identify */ -DisplayObjectContainer.prototype.getChildIndex = function (child) { +DisplayObjectContainer.prototype.getChildIndex = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { throw new Error('The supplied DisplayObject must be a child of the caller'); } @@ -203,8 +228,10 @@ * @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 */ -DisplayObjectContainer.prototype.setChildIndex = function (child, index) { - if (index < 0 || index >= this.children.length) { +DisplayObjectContainer.prototype.setChildIndex = function (child, index) +{ + if (index < 0 || index >= this.children.length) + { throw new Error('The supplied index is out of bounds'); } @@ -220,8 +247,10 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child at the given index, if any. */ -DisplayObjectContainer.prototype.getChildAt = function (index) { - if (index < 0 || index >= this.children.length) { +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'); } @@ -234,10 +263,12 @@ * @param child {DisplayObject} The DisplayObject to remove * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChild = function (child) { +DisplayObjectContainer.prototype.removeChild = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { return; } @@ -250,7 +281,8 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChildAt = function (index) { +DisplayObjectContainer.prototype.removeChildAt = function (index) +{ var child = this.getChildAt(index); child.parent = null; @@ -265,24 +297,29 @@ * @param beginIndex {Number} The beginning position. Default value is 0. * @param endIndex {Number} The ending position. Default value is size of the container. */ -DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) { +DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) +{ var begin = beginIndex || 0; var end = typeof endIndex === 'number' ? endIndex : this.children.length; var range = end - begin; - if (range > 0 && range <= end) { + if (range > 0 && range <= end) + { var removed = this.children.splice(begin, range); - for (var i = 0; i < removed.length; ++i) { + for (var i = 0; i < removed.length; ++i) + { removed[i].parent = null; } return removed; } - else if (range === 0 && this.children.length === 0) { + else if (range === 0 && this.children.length === 0) + { return []; } - else { + else + { throw new RangeError('removeChildren: numeric values are outside the acceptable range.'); } }; @@ -291,7 +328,8 @@ * Generates and updates the cached sprite for this object. * */ -DisplayObjectContainer.prototype.updateCachedSprite = function () { +DisplayObjectContainer.prototype.updateCachedSprite = function () +{ this._generateCachedSprite(); }; @@ -304,7 +342,8 @@ * @param renderer {CanvasRenderer|WebGLRenderer} The renderer used to generate the texture. * @return {Texture} a texture of the graphics object */ -DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) { +DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) +{ var bounds = this.getLocalBounds(); var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0, renderer, scaleMode, resolution); @@ -322,18 +361,22 @@ * * @private */ -DisplayObjectContainer.prototype.updateTransform = function () { - if (!this.visible) { +DisplayObjectContainer.prototype.updateTransform = function () +{ + if (!this.visible) + { return; } this.displayObjectUpdateTransform(); - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { return; } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } }; @@ -346,8 +389,10 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getBounds = function () { - if (this.children.length === 0) { +DisplayObjectContainer.prototype.getBounds = function () +{ + if (this.children.length === 0) + { return math.Rectangle.EMPTY; } @@ -365,10 +410,12 @@ var childVisible = false; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -386,7 +433,8 @@ maxY = maxY > childMaxY ? maxY : childMaxY; } - if (!childVisible) { + if (!childVisible) + { return math.Rectangle.EMPTY; } @@ -407,12 +455,14 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getLocalBounds = function () { +DisplayObjectContainer.prototype.getLocalBounds = function () +{ var matrixCache = this.worldTransform; this.worldTransform = math.Matrix.IDENTITY; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } @@ -428,13 +478,16 @@ * * @param renderer {WebGLRenderer} The renderer */ -DisplayObjectContainer.prototype.renderWebGL = function (renderer) { +DisplayObjectContainer.prototype.renderWebGL = function (renderer) +{ // if the object is not visible or the alpha is 0 then no need to render this element - if (!this.visible || this.alpha <= 0) { + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } @@ -442,14 +495,17 @@ var i, j; // do a quick check to see if this element has a mask or a filter. - if (this._mask || this._filters) { + if (this._mask || this._filters) + { // push filter first as we need to ensure the stencil buffer is correct for any masking - if (this._filters) { + if (this._filters) + { renderer.spriteBatch.flush(); renderer.filterManager.pushFilter(this._filterBlock); } - if (this._mask) { + if (this._mask) + { renderer.spriteBatch.stop(); renderer.maskManager.pushMask(this.mask, renderer); renderer.spriteBatch.start(); @@ -459,36 +515,42 @@ this._renderWebGL(renderer); // now loop through the children and make sure they get rendered - for (i = 0, j = this.children.length; i < j; i++) { + for (i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderWebGL(renderer); } // time to stop the sprite batch as either a mask element or a filter draw will happen next renderer.spriteBatch.stop(); - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(this._mask, renderer); } - if (this._filters) { + if (this._filters) + { renderer.filterManager.popFilter(); } renderer.spriteBatch.start(); } - else { + else + { this._renderWebGL(renderer); // simple render children! - for (i = 0, j = this.children.length; i < j; ++i) { + for (i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderWebGL(renderer); } } }; -DisplayObjectContainer.prototype._renderWebGL = function (renderer) { +DisplayObjectContainer.prototype._renderWebGL = function (renderer) +{ // this is where content itself gets renderd.. @@ -499,25 +561,31 @@ * * @param renderer {CanvasRenderer} The renderer */ -DisplayObjectContainer.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0) { +DisplayObjectContainer.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -528,13 +596,16 @@ * @param renderer {WebGLRenderer|CanvasRenderer} The renderer * @private */ -DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) { +DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) +{ this._cachedSprite.worldAlpha = this.worldAlpha; - if (renderer.gl) { + if (renderer.gl) + { this._cachedSprite.renderWebGL(renderer); } - else { + else + { this._cachedSprite.renderCanvas(renderer); } }; @@ -544,10 +615,12 @@ * * @private */ -DisplayObjectContainer.prototype._generateCachedSprite = function () { +DisplayObjectContainer.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { // TODO - RenderTexture now *requires* a renderer instance, so this is like broken // because `renderer` isn't actually in scope here :P var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0); @@ -555,7 +628,8 @@ this._cachedSprite = new Sprite(renderTexture); this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.texture.resize(bounds.width | 0, bounds.height | 0); } @@ -580,8 +654,10 @@ * * @private */ -DisplayObjectContainer.prototype._destroyCachedSprite = function () { - if (!this._cachedSprite) { +DisplayObjectContainer.prototype._destroyCachedSprite = function () +{ + if (!this._cachedSprite) + { return; } diff --git a/src/core/display/Sprite.js b/src/core/display/Sprite.js index 707da24..5862aef 100644 --- a/src/core/display/Sprite.js +++ b/src/core/display/Sprite.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param texture {Texture} The texture for this sprite */ -function Sprite(texture) { +function Sprite(texture) +{ DisplayObjectContainer.call(this); /** @@ -85,12 +86,14 @@ this.texture = texture || Texture.EMPTY; } -Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) { +Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) +{ DisplayObjectContainer.prototype.destroy.call(this); this.anchor = null; - if (destroyTexture) { + if (destroyTexture) + { this._texture.destroy(destroyBaseTexture); } @@ -111,10 +114,12 @@ * @memberof Sprite# */ width: { - get: function () { + get: function () + { return this.scale.x * this.texture.frame.width; }, - set: function (value) { + set: function (value) + { this.scale.x = value / this.texture.frame.width; this._width = value; } @@ -127,10 +132,12 @@ * @memberof Sprite# */ height: { - get: function () { + get: function () + { return this.scale.y * this.texture.frame.height; }, - set: function (value) { + set: function (value) + { this.scale.y = value / this.texture.frame.height; this._height = value; } @@ -143,23 +150,29 @@ * @memberof Sprite# */ texture: { - get: function () { + get: function () + { return this._texture; }, - set: function (value) { - if (this._texture === value) { + set: function (value) + { + if (this._texture === value) + { return; } this._texture = value; this.cachedTint = 0xFFFFFF; - if (value) { + if (value) + { // wait for the texture to load - if (value.baseTexture.hasLoaded) { + if (value.baseTexture.hasLoaded) + { this._onTextureUpdate(); } - else { + else + { value.once('update', this._onTextureUpdate.bind(this)); } } @@ -172,18 +185,22 @@ * * @private */ -Sprite.prototype._onTextureUpdate = function () { +Sprite.prototype._onTextureUpdate = function () +{ // so if _width is 0 then width was not set.. - if (this._width) { + if (this._width) + { this.scale.x = this._width / this.texture.frame.width; } - if (this._height) { + if (this._height) + { this.scale.y = this._height / this.texture.frame.height; } }; -Sprite.prototype._renderWebGL = function (renderer) { +Sprite.prototype._renderWebGL = function (renderer) +{ // this is where content gets renderd.. // watch this space for a little render state manager.. @@ -197,7 +214,8 @@ * @param matrix {Matrix} the transformation matrix of the sprite * @return {Rectangle} the framing rectangle */ -Sprite.prototype.getBounds = function (matrix) { +Sprite.prototype.getBounds = function (matrix) +{ var width = this.texture.frame.width; var height = this.texture.frame.height; @@ -224,11 +242,13 @@ if(b === 0 && c === 0) { // scale may be negative! - if (a < 0) { + if (a < 0) + { a *= -1; } - if (d < 0) { + if (d < 0) + { d *= -1; } @@ -293,28 +313,34 @@ * * @param renderer {CanvasRenderer} The renderer */ -Sprite.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) { +Sprite.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) + { return; } - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; renderer.context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } // Ignore null sources - if (this.texture.valid) { + if (this.texture.valid) + { var resolution = this.texture.baseTexture.resolution / renderer.resolution; renderer.context.globalAlpha = this.worldAlpha; // If smoothingEnabled is supported and we need to change the smoothing property for this texture - if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) { + if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) + { renderer.scaleMode = this.texture.baseTexture.scaleMode; renderer.context[renderer.smoothProperty] = (renderer.scaleMode === CONST.scaleModes.LINEAR); } @@ -324,7 +350,8 @@ var dy = (this.texture.trim ? this.texture.trim.y : 0) - (this.anchor.y * this.texture.trim.height); // Allow for pixel rounding - if (renderer.roundPixels) { + if (renderer.roundPixels) + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -337,7 +364,8 @@ dx = dx | 0; dy = dy | 0; } - else { + else + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -348,8 +376,10 @@ ); } - if (this.tint !== 0xFFFFFF) { - if (this.cachedTint !== this.tint) { + if (this.tint !== 0xFFFFFF) + { + if (this.cachedTint !== this.tint) + { this.cachedTint = this.tint; // TODO clean up caching - how to clean up the caches? @@ -368,7 +398,8 @@ this.texture.crop.height / resolution ); } - else { + else + { renderer.context.drawImage( this.texture.baseTexture.source, this.texture.crop.x, @@ -383,11 +414,13 @@ } } - for (var i = 0, j = this.children.length; i < j; i++) { + for (var i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -402,10 +435,12 @@ * @param frameId {String} The frame Id of the texture in the cache * @return {Sprite} A new Sprite using a texture from the texture cache matching the frameId */ -Sprite.fromFrame = function (frameId) { +Sprite.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache' + this); } @@ -420,6 +455,7 @@ * @param imageId {String} The image url of the texture * @return {Sprite} A new Sprite using a texture from the texture cache matching the image id */ -Sprite.fromImage = function (imageId, crossorigin, scaleMode) { +Sprite.fromImage = function (imageId, crossorigin, scaleMode) +{ return new Sprite(Texture.fromImage(imageId, crossorigin, scaleMode)); }; diff --git a/src/core/display/SpriteBatch.js b/src/core/display/SpriteBatch.js index 3187777..c196fef 100644 --- a/src/core/display/SpriteBatch.js +++ b/src/core/display/SpriteBatch.js @@ -12,7 +12,8 @@ * ```js * var container = new SpriteBatch(); * - * for(var i = 0; i < 100; ++i) { + * for(var i = 0; i < 100; ++i) + * { * var sprite = new PIXI.Sprite.fromImage("myImage.png"); * container.addChild(sprite); * } @@ -25,7 +26,8 @@ */ //TODO RENAME to PARTICLE CONTAINER? -function SpriteBatch() { +function SpriteBatch() +{ DisplayObjectContainer.call(this); } @@ -38,7 +40,8 @@ * * @private */ -SpriteBatch.prototype.updateTransform = function () { +SpriteBatch.prototype.updateTransform = function () +{ // TODO don't need to! this.displayObjectUpdateTransform(); // PIXI.DisplayObjectContainer.prototype.updateTransform.call( this ); @@ -50,8 +53,10 @@ * @param renderer {WebGLRenderer} The webgl renderer * @private */ -SpriteBatch.prototype.renderWebGL = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderWebGL = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -71,8 +76,10 @@ * @param renderer {CanvasRenderer} The canvas renderer * @private */ -SpriteBatch.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -84,10 +91,12 @@ this.displayObjectUpdateTransform(); - for (var i = 0; i < this.children.length; ++i) { + for (var i = 0; i < this.children.length; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -95,9 +104,11 @@ context.globalAlpha = this.worldAlpha * child.alpha; - if (child.rotation % (Math.PI * 2) === 0) { + if (child.rotation % (Math.PI * 2) === 0) + { // this is the fastest way to optimise! - if rotation is 0 then we can avoid any kind of setTransform call - if (isRotated) { + if (isRotated) + { context.setTransform( transform.a, transform.b, @@ -122,8 +133,10 @@ frame.height * child.scale.y ); } - else { - if (!isRotated) { + else + { + if (!isRotated) + { isRotated = true; } @@ -131,7 +144,8 @@ var childTransform = child.worldTransform; - if (renderer.roundPixels) { + if (renderer.roundPixels) + { context.setTransform( childTransform.a, childTransform.b, @@ -141,7 +155,8 @@ childTransform.ty | 0 ); } - else { + else + { context.setTransform( childTransform.a, childTransform.b, diff --git a/src/core/index.js b/src/core/index.js index 3954b6f..eb4a82b 100644 --- a/src/core/index.js +++ b/src/core/index.js @@ -58,11 +58,13 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRenderer: function (width, height, options, noWebGL) { + autoDetectRenderer: function (width, height, options, noWebGL) + { width = width || 800; height = height || 600; - if (!noWebGL && require('webgl-enabled')()) { + if (!noWebGL && require('webgl-enabled')()) + { return new core.WebGLRenderer(width, height, options); } @@ -87,7 +89,8 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRecommendedRenderer: function (width, height, options) { + autoDetectRecommendedRenderer: function (width, height, options) + { var isAndroid = /Android/i.test(navigator.userAgent); return core.autoDetectRenderer(width, height, options, isAndroid); diff --git a/src/core/math/Matrix.js b/src/core/math/Matrix.js index c2f87e2..2ff4848 100644 --- a/src/core/math/Matrix.js +++ b/src/core/math/Matrix.js @@ -10,7 +10,8 @@ * @class * @namespace PIXI */ -function Matrix() { +function Matrix() +{ /** * @member {number} * @default 1 @@ -63,7 +64,8 @@ * * @param array {number[]} The array that the matrix will be populated from. */ -Matrix.prototype.fromArray = function (array) { +Matrix.prototype.fromArray = function (array) +{ this.a = array[0]; this.b = array[1]; this.c = array[3]; @@ -78,14 +80,17 @@ * @param transpose {boolean} Whether we need to transpose the matrix or not * @return {number[]} the newly created array which contains the matrix */ -Matrix.prototype.toArray = function (transpose) { - if (!this.array) { +Matrix.prototype.toArray = function (transpose) +{ + if (!this.array) + { this.array = new Float32Array(9); } var array = this.array; - if (transpose) { + if (transpose) + { array[0] = this.a; array[1] = this.b; array[2] = 0; @@ -96,7 +101,8 @@ array[7] = this.ty; array[8] = 1; } - else { + else + { array[0] = this.a; array[1] = this.c; array[2] = this.tx; @@ -119,7 +125,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, transformed through this matrix */ -Matrix.prototype.apply = function (pos, newPos) { +Matrix.prototype.apply = function (pos, newPos) +{ newPos = newPos || new Point(); newPos.x = this.a * pos.x + this.c * pos.y + this.tx; @@ -136,7 +143,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, inverse-transformed through this matrix */ -Matrix.prototype.applyInverse = function (pos, newPos) { +Matrix.prototype.applyInverse = function (pos, newPos) +{ newPos = newPos || new Point(); var id = 1 / (this.a * this.d + this.c * -this.b); @@ -154,7 +162,8 @@ * @param {number} y * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.translate = function (x, y) { +Matrix.prototype.translate = function (x, y) +{ this.tx += x; this.ty += y; @@ -168,7 +177,8 @@ * @param {number} y The amount to scale vertically * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.scale = function (x, y) { +Matrix.prototype.scale = function (x, y) +{ this.a *= x; this.d *= y; this.c *= x; @@ -186,7 +196,8 @@ * @param {number} angle - The angle in radians. * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.rotate = function (angle) { +Matrix.prototype.rotate = function (angle) +{ var cos = Math.cos( angle ); var sin = Math.sin( angle ); @@ -210,7 +221,8 @@ * @param {Matrix} matrix * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.append = function (matrix) { +Matrix.prototype.append = function (matrix) +{ var a1 = this.a; var b1 = this.b; var c1 = this.c; @@ -232,7 +244,8 @@ * * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.identity = function () { +Matrix.prototype.identity = function () +{ this.a = 1; this.b = 0; this.c = 0; diff --git a/src/core/math/Point.js b/src/core/math/Point.js index 7565b2d..632f346 100644 --- a/src/core/math/Point.js +++ b/src/core/math/Point.js @@ -7,7 +7,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -function Point(x, y) { +function Point(x, y) +{ /** * @member {number} * @default 0 @@ -29,7 +30,8 @@ * * @return {Point} a copy of the point */ -Point.prototype.clone = function () { +Point.prototype.clone = function () +{ return new Point(this.x, this.y); }; @@ -40,7 +42,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -Point.prototype.set = function (x, y) { +Point.prototype.set = function (x, y) +{ this.x = x || 0; this.y = y || ( (y !== 0) ? this.x : 0 ) ; }; diff --git a/src/core/math/shapes/Circle.js b/src/core/math/shapes/Circle.js index 69cfdc9..4d76efc 100644 --- a/src/core/math/shapes/Circle.js +++ b/src/core/math/shapes/Circle.js @@ -10,7 +10,8 @@ * @param y {number} The Y coordinate of the center of this circle * @param radius {number} The radius of the circle */ -function Circle(x, y, radius) { +function Circle(x, y, radius) +{ /** * @member {number} * @default 0 @@ -46,7 +47,8 @@ * @method clone * @return {Circle} a copy of the Circle */ -Circle.prototype.clone = function () { +Circle.prototype.clone = function () +{ return new Circle(this.x, this.y, this.radius); }; @@ -58,8 +60,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Circle */ -Circle.prototype.contains = function (x, y) { - if (this.radius <= 0) { +Circle.prototype.contains = function (x, y) +{ + if (this.radius <= 0) + { return false; } @@ -79,6 +83,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Circle.prototype.getBounds = function () { +Circle.prototype.getBounds = function () +{ return new Rectangle(this.x - this.radius, this.y - this.radius, this.radius * 2, this.radius * 2); }; diff --git a/src/core/math/shapes/Ellipse.js b/src/core/math/shapes/Ellipse.js index 4f2d066..fefd01a 100644 --- a/src/core/math/shapes/Ellipse.js +++ b/src/core/math/shapes/Ellipse.js @@ -11,7 +11,8 @@ * @param width {number} The half width of this ellipse * @param height {number} The half height of this ellipse */ -function Ellipse(x, y, width, height) { +function Ellipse(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -53,7 +54,8 @@ * @method clone * @return {Ellipse} a copy of the ellipse */ -Ellipse.prototype.clone = function () { +Ellipse.prototype.clone = function () +{ return new Ellipse(this.x, this.y, this.width, this.height); }; @@ -65,8 +67,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coords are within this ellipse */ -Ellipse.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Ellipse.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } @@ -86,6 +90,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Ellipse.prototype.getBounds = function () { +Ellipse.prototype.getBounds = function () +{ return new Rectangle(this.x - this.width, this.y - this.height, this.width, this.height); }; diff --git a/src/core/math/shapes/Polygon.js b/src/core/math/shapes/Polygon.js index ae89148..fea6d37 100644 --- a/src/core/math/shapes/Polygon.js +++ b/src/core/math/shapes/Polygon.js @@ -10,16 +10,20 @@ * arguments passed can be flat x,y values e.g. `new Polygon(x,y, x,y, x,y, ...)` where `x` and `y` are * Numbers. */ -function Polygon(points) { +function Polygon(points) +{ //if points isn't an array, use arguments as the array - if (!(points instanceof Array)) { + if (!(points instanceof Array)) + { points = Array.prototype.slice.call(arguments); } //if this is a flat array of numbers, convert it to points - if (points[0] instanceof Point) { + if (points[0] instanceof Point) + { var p = []; - for (var i = 0, il = points.length; i < il; i++) { + for (var i = 0, il = points.length; i < il; i++) + { p.push(points[i].x, points[i].y); } @@ -51,7 +55,8 @@ * * @return {Polygon} a copy of the polygon */ -Polygon.prototype.clone = function () { +Polygon.prototype.clone = function () +{ return new Polygon(this.points.slice()); }; @@ -62,19 +67,22 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this polygon */ -Polygon.prototype.contains = function (x, y) { +Polygon.prototype.contains = function (x, y) +{ var inside = false; // use some raycasting to test hits // https://github.com/substack/point-in-polygon/blob/master/index.js var length = this.points.length / 2; - for (var i = 0, j = length - 1; i < length; j = i++) { + for (var i = 0, j = length - 1; i < length; j = i++) + { var xi = this.points[i * 2], yi = this.points[i * 2 + 1], xj = this.points[j * 2], yj = this.points[j * 2 + 1], intersect = ((yi > y) !== (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi); - if (intersect) { + if (intersect) + { inside = !inside; } } diff --git a/src/core/math/shapes/Rectangle.js b/src/core/math/shapes/Rectangle.js index 16ac62a..4008b68 100644 --- a/src/core/math/shapes/Rectangle.js +++ b/src/core/math/shapes/Rectangle.js @@ -10,7 +10,8 @@ * @param width {number} The overall width of this rectangle * @param height {number} The overall height of this rectangle */ -function Rectangle(x, y, width, height) { +function Rectangle(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -60,7 +61,8 @@ * * @return {Rectangle} a copy of the rectangle */ -Rectangle.prototype.clone = function () { +Rectangle.prototype.clone = function () +{ return new Rectangle(this.x, this.y, this.width, this.height); }; @@ -71,13 +73,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rectangle */ -Rectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Rectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/math/shapes/RoundedRectangle.js b/src/core/math/shapes/RoundedRectangle.js index 27d286e..7bf6411 100644 --- a/src/core/math/shapes/RoundedRectangle.js +++ b/src/core/math/shapes/RoundedRectangle.js @@ -11,7 +11,8 @@ * @param height {number} The overall height of this rounded rectangle * @param radius {number} Controls the radius of the rounded corners */ -function RoundedRectangle(x, y, width, height, radius) { +function RoundedRectangle(x, y, width, height, radius) +{ /** * @member {number} * @default 0 @@ -58,7 +59,8 @@ * * @return {RoundedRectangle} a copy of the rounded rectangle */ -RoundedRectangle.prototype.clone = function () { +RoundedRectangle.prototype.clone = function () +{ return new RoundedRectangle(this.x, this.y, this.width, this.height, this.radius); }; @@ -69,13 +71,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rounded Rectangle */ -RoundedRectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +RoundedRectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/primitives/Graphics.js b/src/core/primitives/Graphics.js index 261c534..e902d2a 100644 --- a/src/core/primitives/Graphics.js +++ b/src/core/primitives/Graphics.js @@ -16,7 +16,8 @@ * @extends DisplayObjectContainer * @namespace PIXI */ -function Graphics() { +function Graphics() +{ DisplayObjectContainer.call(this); this.renderable = true; @@ -154,16 +155,20 @@ * @private */ cacheAsBitmap: { - get: function () { + get: function () + { return this._cacheAsBitmap; }, - set: function (value) { + set: function (value) + { this._cacheAsBitmap = value; - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._generateCachedSprite(); } - else { + else + { this.destroyCachedSprite(); this.dirty = true; } @@ -176,7 +181,8 @@ * * @return {Graphics} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ var clone = new Graphics(); clone.renderable = this.renderable; @@ -192,7 +198,8 @@ clone.cachedSpriteDirty = this.cachedSpriteDirty; // copy graphics data - for (var i = 0; i < this.graphicsData.length; ++i) { + for (var i = 0; i < this.graphicsData.length; ++i) + { clone.graphicsData.push(this.graphicsData.clone()); } @@ -211,17 +218,21 @@ * @param alpha {number} alpha of the line to draw, will update the objects stored style * @return {Graphics} */ -Graphics.prototype.lineStyle = function (lineWidth, color, alpha) { +Graphics.prototype.lineStyle = function (lineWidth, color, alpha) +{ this.lineWidth = lineWidth || 0; this.lineColor = color || 0; this.lineAlpha = (arguments.length < 3) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length) + { // halfway through a line? start a new one! this.drawShape( new math.Polygon( this.currentPath.shape.points.slice(-2) )); } - else { + else + { // otherwise its empty so lets just set the line properties this.currentPath.lineWidth = this.lineWidth; this.currentPath.lineColor = this.lineColor; @@ -239,7 +250,8 @@ * @param y {number} the Y coordinate to move to * @return {Graphics} */ -Graphics.prototype.moveTo = function (x, y) { +Graphics.prototype.moveTo = function (x, y) +{ this.drawShape(new math.Polygon([x,y])); return this; @@ -253,7 +265,8 @@ * @param y {number} the Y coordinate to draw to * @return {Graphics} */ -Graphics.prototype.lineTo = function (x, y) { +Graphics.prototype.lineTo = function (x, y) +{ this.currentPath.shape.points.push(x, y); this.dirty = true; @@ -270,13 +283,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -285,7 +302,8 @@ n = 20, points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { this.moveTo(0, 0); } @@ -293,7 +311,8 @@ var fromY = points[points.length-1]; var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; xa = fromX + ( (cpX - fromX) * j ); @@ -319,13 +338,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -342,7 +365,8 @@ var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; dt = (1 - j); @@ -373,13 +397,17 @@ * @param radius {number} The radius of the arc * @return {Graphics} */ -Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points.push(x1, y1); } } - else { + else + { this.moveTo(x1, y1); } @@ -392,12 +420,15 @@ b2 = x2 - x1, mm = Math.abs(a1 * b2 - b1 * a2); - if (mm < 1.0e-8 || radius === 0) { - if (points[points.length-2] !== x1 || points[points.length-1] !== y1) { + if (mm < 1.0e-8 || radius === 0) + { + if (points[points.length-2] !== x1 || points[points.length-1] !== y1) + { points.push(x1, y1); } } - else { + else + { var dd = a1 * a1 + b1 * b1, cc = a2 * a2 + b2 * b2, tt = a1 * a2 + b1 * b2, @@ -433,42 +464,51 @@ * @param anticlockwise {boolean} Optional. Specifies whether the drawing should be counterclockwise or clockwise. False is default, and indicates clockwise, while true indicates counter-clockwise. * @return {Graphics} */ -Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) { +Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) +{ var startX = cx + Math.cos(startAngle) * radius; var startY = cy + Math.sin(startAngle) * radius; var points; // TODO - This if-else makes no sense. It uses currentPath in the else where it doesn't exist... - if (this.currentPath) { + if (this.currentPath) + { points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { points.push(startX, startY); } - else if (points[points.length-2] !== startX || points[points.length-1] !== startY) { + else if (points[points.length-2] !== startX || points[points.length-1] !== startY) + { points.push(startX, startY); } } - else { + else + { this.moveTo(startX, startY); points = this.currentPath.shape.points; } - if (startAngle === endAngle) { + if (startAngle === endAngle) + { return this; } - if (!anticlockwise && endAngle <= startAngle) { + if (!anticlockwise && endAngle <= startAngle) + { endAngle += Math.PI * 2; } - else if (anticlockwise && startAngle <= endAngle) { + else if (anticlockwise && startAngle <= endAngle) + { startAngle += Math.PI * 2; } var sweep = anticlockwise ? (startAngle - endAngle) *-1 : (endAngle - startAngle); var segs = (Math.abs(sweep)/ (Math.PI * 2)) * 40; - if (sweep === 0) { + if (sweep === 0) + { return this; } @@ -482,7 +522,8 @@ var remainder = ( segMinus % 1 ) / segMinus; - for (var i = 0; i <= segMinus; ++i) { + for (var i = 0; i <= segMinus; ++i) + { var real = i + remainder * i; var angle = ((theta) + startAngle + (theta2 * real)); @@ -506,13 +547,16 @@ * @param alpha {number} the alpha of the fill * @return {Graphics} */ -Graphics.prototype.beginFill = function (color, alpha) { +Graphics.prototype.beginFill = function (color, alpha) +{ this.filling = true; this.fillColor = color || 0; this.fillAlpha = (alpha === undefined) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length <= 2) + { this.currentPath.fill = this.filling; this.currentPath.fillColor = this.fillColor; this.currentPath.fillAlpha = this.fillAlpha; @@ -526,7 +570,8 @@ * * @return {Graphics} */ -Graphics.prototype.endFill = function () { +Graphics.prototype.endFill = function () +{ this.filling = false; this.fillColor = null; this.fillAlpha = 1; @@ -542,7 +587,8 @@ * @param height {number} The height of the rectangle * @return {Graphics} */ -Graphics.prototype.drawRect = function ( x, y, width, height ) { +Graphics.prototype.drawRect = function ( x, y, width, height ) +{ this.drawShape(new math.Rectangle(x,y, width, height)); return this; @@ -556,7 +602,8 @@ * @param height {number} The height of the rectangle * @param radius {number} Radius of the rectangle corners */ -Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) { +Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) +{ this.drawShape(new math.RoundedRectangle(x, y, width, height, radius)); return this; @@ -570,7 +617,8 @@ * @param radius {number} The radius of the circle * @return {Graphics} */ -Graphics.prototype.drawCircle = function (x, y, radius) { +Graphics.prototype.drawCircle = function (x, y, radius) +{ this.drawShape(new math.Circle(x,y, radius)); return this; @@ -585,7 +633,8 @@ * @param height {number} The half height of the ellipse * @return {Graphics} */ -Graphics.prototype.drawEllipse = function (x, y, width, height) { +Graphics.prototype.drawEllipse = function (x, y, width, height) +{ this.drawShape(new math.Ellipse(x, y, width, height)); return this; @@ -597,8 +646,10 @@ * @param path {Array} The path data used to construct the polygon. * @return {Graphics} */ -Graphics.prototype.drawPolygon = function (path) { - if (!(path instanceof Array)) { +Graphics.prototype.drawPolygon = function (path) +{ + if (!(path instanceof Array)) + { path = Array.prototype.slice.call(arguments); } @@ -612,7 +663,8 @@ * * @return {Graphics} */ -Graphics.prototype.clear = function () { +Graphics.prototype.clear = function () +{ this.lineWidth = 0; this.filling = false; @@ -631,7 +683,8 @@ * @param scaleMode {number} Should be one of the scaleMode consts * @return {Texture} a texture of the graphics object */ -Graphics.prototype.generateTexture = function (resolution, scaleMode) { +Graphics.prototype.generateTexture = function (resolution, scaleMode) +{ resolution = resolution || 1; var bounds = this.getBounds(); @@ -655,17 +708,21 @@ * * @param renderer {WebGLRenderer} */ -Graphics.prototype._renderWebGL = function (renderer) { +Graphics.prototype._renderWebGL = function (renderer) +{ // if the sprite is not visible or the alpha is 0 then no need to render this element - if (this.isMask === true) { + if (this.isMask === true) + { return; } // this code may still be needed so leaving for now.. - // + // /* - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture on the gpu too! @@ -681,17 +738,24 @@ return; } - */ - - // check if the webgl graphic needs to be updated - if (this.glDirty) { - this.dirty = true; - this.glDirty = false; - } + else */ - renderer.setObjectRendererer(renderer.graphicsRenderer); - renderer.graphicsRenderer.render(this); + renderer.spriteBatch.stop(); + renderer.blendModeManager.setBlendMode(this.blendMode); + // check blend mode + renderer.blendModeManager.setBlendMode( this.blendMode ); + + // check if the webgl graphic needs to be updated + if (this.glDirty) + { + this.dirty = true; + this.glDirty = false; + } + + WebGLGraphics.renderGraphics(this, renderer); + + renderer.spriteBatch.start(); }; /** @@ -700,14 +764,18 @@ * @param renderer {CanvasRenderer} * @private */ -Graphics.prototype.renderCanvas = function (renderer) { +Graphics.prototype.renderCanvas = function (renderer) +{ // 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.isMask === true) { + if (!this.visible || this.alpha <= 0 || this.isMask === true) + { return; } - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture @@ -723,16 +791,19 @@ return; } - else { + else + { var context = renderer.context; var transform = this.worldTransform; - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } @@ -748,11 +819,13 @@ CanvasGraphics.renderGraphics(this, context); - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } } @@ -763,13 +836,16 @@ * * @return {Rectangle} the rectangular bounding area */ -Graphics.prototype.getBounds = function (matrix) { +Graphics.prototype.getBounds = function (matrix) +{ // return an empty object if the item is a mask! - if (this.isMask) { + if (this.isMask) + { return math.Rectangle.EMPTY; } - if (this.dirty) { + if (this.dirty) + { this.updateLocalBounds(); this.glDirty = true; @@ -841,23 +917,27 @@ * Update the bounds of the object * */ -Graphics.prototype.updateLocalBounds = function () { +Graphics.prototype.updateLocalBounds = function () +{ var minX = Infinity; var maxX = -Infinity; var minY = Infinity; var maxY = -Infinity; - if (this.graphicsData.length) { + if (this.graphicsData.length) + { var shape, points, x, y, w, h; - for (var i = 0; i < this.graphicsData.length; i++) { + for (var i = 0; i < this.graphicsData.length; i++) + { var data = this.graphicsData[i]; var type = data.type; var lineWidth = data.lineWidth; shape = data.shape; - if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) { + if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) + { x = shape.x - lineWidth/2; y = shape.y - lineWidth/2; w = shape.width + lineWidth; @@ -869,7 +949,8 @@ minY = y < minY ? y : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.CIRC) { + else if (type === CONST.SHAPES.CIRC) + { x = shape.x; y = shape.y; w = shape.radius + lineWidth/2; @@ -881,7 +962,8 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.ELIP) { + else if (type === CONST.SHAPES.ELIP) + { x = shape.x; y = shape.y; w = shape.width + lineWidth/2; @@ -893,11 +975,13 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else { + else + { // POLY points = shape.points; - for (var j = 0; j < points.length; j += 2) { + for (var j = 0; j < points.length; j += 2) + { x = points[j]; y = points[j+1]; @@ -910,7 +994,8 @@ } } } - else { + else + { minX = 0; maxX = 0; minY = 0; @@ -931,10 +1016,12 @@ * * @private */ -Graphics.prototype._generateCachedSprite = function () { +Graphics.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { var canvasBuffer = new CanvasBuffer(bounds.width, bounds.height); var texture = Texture.fromCanvas(canvasBuffer.canvas); @@ -943,7 +1030,8 @@ this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.buffer.resize(bounds.width, bounds.height); } @@ -968,7 +1056,8 @@ * * @private */ -Graphics.prototype.updateCachedSpriteTexture = function () { +Graphics.prototype.updateCachedSpriteTexture = function () +{ var cachedSprite = this._cachedSprite; var texture = cachedSprite.texture; var canvas = cachedSprite.buffer.canvas; @@ -989,7 +1078,8 @@ * Destroys a previous cached sprite. * */ -Graphics.prototype.destroyCachedSprite = function () { +Graphics.prototype.destroyCachedSprite = function () +{ this._cachedSprite.texture.destroy(true); // let the gc collect the unused sprite @@ -1003,10 +1093,13 @@ * @param {Circle|Rectangle|Ellipse|Line|Polygon} shape The Shape object to draw. * @return {GraphicsData} The generated GraphicsData object. */ -Graphics.prototype.drawShape = function (shape) { - if (this.currentPath) { +Graphics.prototype.drawShape = function (shape) +{ + if (this.currentPath) + { // check current path! - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath.shape.points.length <= 2) + { this.graphicsData.pop(); } } @@ -1017,7 +1110,8 @@ this.graphicsData.push(data); - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { data.shape.closed = this.filling; this.currentPath = data; } diff --git a/src/core/display/DisplayObject.js b/src/core/display/DisplayObject.js index 66ebc3c..20e778c 100644 --- a/src/core/display/DisplayObject.js +++ b/src/core/display/DisplayObject.js @@ -7,7 +7,8 @@ * @class * @namespace PIXI */ -function DisplayObject() { +function DisplayObject() +{ /** * The coordinate of the object relative to the local coordinates of the parent. * @@ -152,10 +153,12 @@ * @memberof DisplayObject# */ x: { - get: function () { + get: function () + { return this.position.x; }, - set: function (value) { + set: function (value) + { this.position.x = value; } }, @@ -167,10 +170,12 @@ * @memberof DisplayObject# */ y: { - get: function () { + get: function () + { return this.position.y; }, - set: function (value) { + set: function (value) + { this.position.y = value; } }, @@ -183,11 +188,13 @@ * @readonly */ worldVisible: { - get: function () { + get: function () + { var item = this; do { - if (!item.visible) { + if (!item.visible) + { return false; } @@ -207,17 +214,21 @@ * @memberof DisplayObject# */ mask: { - get: function () { + get: function () + { return this._mask; }, - set: function (value) { - if (this._mask) { + set: function (value) + { + if (this._mask) + { this._mask.isMask = false; } this._mask = value; - if (this._mask) { + if (this._mask) + { this._mask.isMask = true; } } @@ -232,18 +243,23 @@ * @memberof DisplayObject# */ filters: { - get: function () { + get: function () + { return this._filters; }, - set: function (value) { - if (value) { + set: function (value) + { + if (value) + { // now put all the passes in one place.. var passes = []; - for (var i = 0; i < value.length; i++) { + for (var i = 0; i < value.length; i++) + { var filterPasses = value[i].passes; - for (var j = 0; j < filterPasses.length; j++) { + for (var j = 0; j < filterPasses.length; j++) + { passes.push(filterPasses[j]); } } @@ -264,8 +280,9 @@ * * @private */ -DisplayObject.prototype.updateTransform = function () { - +DisplayObject.prototype.updateTransform = function () +{ + // create some matrix refs for easy access var pt = this.parent.worldTransform; var wt = this.worldTransform; @@ -274,9 +291,11 @@ var a, b, c, d, tx, ty; // so if rotation is between 0 then we can simplify the multiplication process.. - if (this.rotation % math.PI_2) { + if (this.rotation % math.PI_2) + { // 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) { + if (this.rotation !== this.rotationCache) + { this.rotationCache = this.rotation; this._sr = Math.sin(this.rotation); this._cr = Math.cos(this.rotation); @@ -291,7 +310,8 @@ ty = this.position.y; // check for pivot.. not often used so geared towards that fact! - if (this.pivot.x || this.pivot.y) { + 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; } @@ -304,7 +324,8 @@ wt.tx = tx * pt.a + ty * pt.c + pt.tx; wt.ty = tx * pt.b + ty * pt.d + pt.ty; } - else { + else + { // lets do the fast version as we know there is no rotation.. a = this.scale.x; d = this.scale.y; @@ -333,7 +354,8 @@ * @param matrix {Matrix} * @return {Rectangle} the rectangular bounding area */ -DisplayObject.prototype.getBounds = function (/* matrix */) { +DisplayObject.prototype.getBounds = function (/* matrix */) +{ return math.Rectangle.EMPTY; }; @@ -342,7 +364,8 @@ * * @return {Rectangle} the rectangular bounding area */ -DisplayObject.prototype.getLocalBounds = function () { +DisplayObject.prototype.getLocalBounds = function () +{ return this.getBounds(math.Matrix.IDENTITY); }; @@ -352,7 +375,8 @@ * @param position {Point} The world origin to calculate from * @return {Point} A point object representing the position of this object */ -DisplayObject.prototype.toGlobal = function (position) { +DisplayObject.prototype.toGlobal = function (position) +{ // don't need to u[date the lot this.displayObjectUpdateTransform(); return this.worldTransform.apply(position); @@ -365,8 +389,10 @@ * @param [from] {DisplayObject} The DisplayObject to calculate the global position from * @return {Point} A point object representing the position of this object */ -DisplayObject.prototype.toLocal = function (position, from) { - if (from) { +DisplayObject.prototype.toLocal = function (position, from) +{ + if (from) + { position = from.toGlobal(position); } @@ -381,7 +407,8 @@ * @param renderer {WebGLRenderer} The renderer * @private */ -DisplayObject.prototype.renderWebGL = function (/* renderer */) { +DisplayObject.prototype.renderWebGL = function (/* renderer */) +{ // OVERWRITE; }; @@ -391,6 +418,7 @@ * @param renderer {CanvasRenderer} The renderer * @private */ -DisplayObject.prototype.renderCanvas = function (/* renderer */) { +DisplayObject.prototype.renderCanvas = function (/* renderer */) +{ // OVERWRITE; }; diff --git a/src/core/display/DisplayObjectContainer.js b/src/core/display/DisplayObjectContainer.js index 689f40b..4625ee8 100644 --- a/src/core/display/DisplayObjectContainer.js +++ b/src/core/display/DisplayObjectContainer.js @@ -12,7 +12,8 @@ * @extends DisplayObject * @namespace PIXI */ -function DisplayObjectContainer() { +function DisplayObjectContainer() +{ DisplayObject.call(this); /** @@ -47,17 +48,21 @@ * @memberof DisplayObjectContainer# */ width: { - get: function () { + get: function () + { return this.scale.x * this.getLocalBounds().width; }, - set: function (value) { + set: function (value) + { var width = this.getLocalBounds().width; - if(width !== 0) { + if(width !== 0) + { this.scale.x = value / width; } - else { + else + { this.scale.x = 1; } @@ -73,17 +78,21 @@ * @memberof DisplayObjectContainer# */ height: { - get: function () { + get: function () + { return this.scale.y * this.getLocalBounds().height; }, - set: function (value) { + set: function (value) + { var height = this.getLocalBounds().height; - if (height !== 0) { + if (height !== 0) + { this.scale.y = value / height ; } - else { + else + { this.scale.y = 1; } @@ -100,18 +109,23 @@ * @memberof DisplayObject# */ cacheAsBitmap: { - get: function () { + get: function () + { return this._cacheAsBitmap; }, - set: function (value) { - if (this._cacheAsBitmap === value) { + set: function (value) + { + if (this._cacheAsBitmap === value) + { return; } - if (value) { + if (value) + { this._generateCachedSprite(); } - else { + else + { this._destroyCachedSprite(); } @@ -126,7 +140,8 @@ * @param child {DisplayObject} The DisplayObject to add to the container * @return {DisplayObject} The child that was added. */ -DisplayObjectContainer.prototype.addChild = function (child) { +DisplayObjectContainer.prototype.addChild = function (child) +{ return this.addChildAt(child, this.children.length); }; @@ -137,14 +152,18 @@ * @param index {Number} The index to place the child in * @return {DisplayObject} The child that was added. */ -DisplayObjectContainer.prototype.addChildAt = function (child, index) { +DisplayObjectContainer.prototype.addChildAt = function (child, index) +{ // prevent adding self as child - if (child === this) { + if (child === this) + { return; } - if (index >= 0 && index <= this.children.length) { - if (child.parent) { + if (index >= 0 && index <= this.children.length) + { + if (child.parent) + { child.parent.removeChild(child); } @@ -154,7 +173,8 @@ return child; } - else { + else + { throw new Error(child + 'addChildAt: The index '+ index +' supplied is out of bounds ' + this.children.length); } }; @@ -165,15 +185,18 @@ * @param child {DisplayObject} * @param child2 {DisplayObject} */ -DisplayObjectContainer.prototype.swapChildren = function (child, child2) { - if (child === child2) { +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) { + if (index1 < 0 || index2 < 0) + { throw new Error('swapChildren: Both the supplied DisplayObjects must be a child of the caller.'); } @@ -187,10 +210,12 @@ * @param child {DisplayObject} The DisplayObject instance to identify * @return {Number} The index position of the child display object to identify */ -DisplayObjectContainer.prototype.getChildIndex = function (child) { +DisplayObjectContainer.prototype.getChildIndex = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { throw new Error('The supplied DisplayObject must be a child of the caller'); } @@ -203,8 +228,10 @@ * @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 */ -DisplayObjectContainer.prototype.setChildIndex = function (child, index) { - if (index < 0 || index >= this.children.length) { +DisplayObjectContainer.prototype.setChildIndex = function (child, index) +{ + if (index < 0 || index >= this.children.length) + { throw new Error('The supplied index is out of bounds'); } @@ -220,8 +247,10 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child at the given index, if any. */ -DisplayObjectContainer.prototype.getChildAt = function (index) { - if (index < 0 || index >= this.children.length) { +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'); } @@ -234,10 +263,12 @@ * @param child {DisplayObject} The DisplayObject to remove * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChild = function (child) { +DisplayObjectContainer.prototype.removeChild = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { return; } @@ -250,7 +281,8 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChildAt = function (index) { +DisplayObjectContainer.prototype.removeChildAt = function (index) +{ var child = this.getChildAt(index); child.parent = null; @@ -265,24 +297,29 @@ * @param beginIndex {Number} The beginning position. Default value is 0. * @param endIndex {Number} The ending position. Default value is size of the container. */ -DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) { +DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) +{ var begin = beginIndex || 0; var end = typeof endIndex === 'number' ? endIndex : this.children.length; var range = end - begin; - if (range > 0 && range <= end) { + if (range > 0 && range <= end) + { var removed = this.children.splice(begin, range); - for (var i = 0; i < removed.length; ++i) { + for (var i = 0; i < removed.length; ++i) + { removed[i].parent = null; } return removed; } - else if (range === 0 && this.children.length === 0) { + else if (range === 0 && this.children.length === 0) + { return []; } - else { + else + { throw new RangeError('removeChildren: numeric values are outside the acceptable range.'); } }; @@ -291,7 +328,8 @@ * Generates and updates the cached sprite for this object. * */ -DisplayObjectContainer.prototype.updateCachedSprite = function () { +DisplayObjectContainer.prototype.updateCachedSprite = function () +{ this._generateCachedSprite(); }; @@ -304,7 +342,8 @@ * @param renderer {CanvasRenderer|WebGLRenderer} The renderer used to generate the texture. * @return {Texture} a texture of the graphics object */ -DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) { +DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) +{ var bounds = this.getLocalBounds(); var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0, renderer, scaleMode, resolution); @@ -322,18 +361,22 @@ * * @private */ -DisplayObjectContainer.prototype.updateTransform = function () { - if (!this.visible) { +DisplayObjectContainer.prototype.updateTransform = function () +{ + if (!this.visible) + { return; } this.displayObjectUpdateTransform(); - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { return; } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } }; @@ -346,8 +389,10 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getBounds = function () { - if (this.children.length === 0) { +DisplayObjectContainer.prototype.getBounds = function () +{ + if (this.children.length === 0) + { return math.Rectangle.EMPTY; } @@ -365,10 +410,12 @@ var childVisible = false; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -386,7 +433,8 @@ maxY = maxY > childMaxY ? maxY : childMaxY; } - if (!childVisible) { + if (!childVisible) + { return math.Rectangle.EMPTY; } @@ -407,12 +455,14 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getLocalBounds = function () { +DisplayObjectContainer.prototype.getLocalBounds = function () +{ var matrixCache = this.worldTransform; this.worldTransform = math.Matrix.IDENTITY; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } @@ -428,13 +478,16 @@ * * @param renderer {WebGLRenderer} The renderer */ -DisplayObjectContainer.prototype.renderWebGL = function (renderer) { +DisplayObjectContainer.prototype.renderWebGL = function (renderer) +{ // if the object is not visible or the alpha is 0 then no need to render this element - if (!this.visible || this.alpha <= 0) { + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } @@ -442,14 +495,17 @@ var i, j; // do a quick check to see if this element has a mask or a filter. - if (this._mask || this._filters) { + if (this._mask || this._filters) + { // push filter first as we need to ensure the stencil buffer is correct for any masking - if (this._filters) { + if (this._filters) + { renderer.spriteBatch.flush(); renderer.filterManager.pushFilter(this._filterBlock); } - if (this._mask) { + if (this._mask) + { renderer.spriteBatch.stop(); renderer.maskManager.pushMask(this.mask, renderer); renderer.spriteBatch.start(); @@ -459,36 +515,42 @@ this._renderWebGL(renderer); // now loop through the children and make sure they get rendered - for (i = 0, j = this.children.length; i < j; i++) { + for (i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderWebGL(renderer); } // time to stop the sprite batch as either a mask element or a filter draw will happen next renderer.spriteBatch.stop(); - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(this._mask, renderer); } - if (this._filters) { + if (this._filters) + { renderer.filterManager.popFilter(); } renderer.spriteBatch.start(); } - else { + else + { this._renderWebGL(renderer); // simple render children! - for (i = 0, j = this.children.length; i < j; ++i) { + for (i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderWebGL(renderer); } } }; -DisplayObjectContainer.prototype._renderWebGL = function (renderer) { +DisplayObjectContainer.prototype._renderWebGL = function (renderer) +{ // this is where content itself gets renderd.. @@ -499,25 +561,31 @@ * * @param renderer {CanvasRenderer} The renderer */ -DisplayObjectContainer.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0) { +DisplayObjectContainer.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -528,13 +596,16 @@ * @param renderer {WebGLRenderer|CanvasRenderer} The renderer * @private */ -DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) { +DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) +{ this._cachedSprite.worldAlpha = this.worldAlpha; - if (renderer.gl) { + if (renderer.gl) + { this._cachedSprite.renderWebGL(renderer); } - else { + else + { this._cachedSprite.renderCanvas(renderer); } }; @@ -544,10 +615,12 @@ * * @private */ -DisplayObjectContainer.prototype._generateCachedSprite = function () { +DisplayObjectContainer.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { // TODO - RenderTexture now *requires* a renderer instance, so this is like broken // because `renderer` isn't actually in scope here :P var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0); @@ -555,7 +628,8 @@ this._cachedSprite = new Sprite(renderTexture); this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.texture.resize(bounds.width | 0, bounds.height | 0); } @@ -580,8 +654,10 @@ * * @private */ -DisplayObjectContainer.prototype._destroyCachedSprite = function () { - if (!this._cachedSprite) { +DisplayObjectContainer.prototype._destroyCachedSprite = function () +{ + if (!this._cachedSprite) + { return; } diff --git a/src/core/display/Sprite.js b/src/core/display/Sprite.js index 707da24..5862aef 100644 --- a/src/core/display/Sprite.js +++ b/src/core/display/Sprite.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param texture {Texture} The texture for this sprite */ -function Sprite(texture) { +function Sprite(texture) +{ DisplayObjectContainer.call(this); /** @@ -85,12 +86,14 @@ this.texture = texture || Texture.EMPTY; } -Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) { +Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) +{ DisplayObjectContainer.prototype.destroy.call(this); this.anchor = null; - if (destroyTexture) { + if (destroyTexture) + { this._texture.destroy(destroyBaseTexture); } @@ -111,10 +114,12 @@ * @memberof Sprite# */ width: { - get: function () { + get: function () + { return this.scale.x * this.texture.frame.width; }, - set: function (value) { + set: function (value) + { this.scale.x = value / this.texture.frame.width; this._width = value; } @@ -127,10 +132,12 @@ * @memberof Sprite# */ height: { - get: function () { + get: function () + { return this.scale.y * this.texture.frame.height; }, - set: function (value) { + set: function (value) + { this.scale.y = value / this.texture.frame.height; this._height = value; } @@ -143,23 +150,29 @@ * @memberof Sprite# */ texture: { - get: function () { + get: function () + { return this._texture; }, - set: function (value) { - if (this._texture === value) { + set: function (value) + { + if (this._texture === value) + { return; } this._texture = value; this.cachedTint = 0xFFFFFF; - if (value) { + if (value) + { // wait for the texture to load - if (value.baseTexture.hasLoaded) { + if (value.baseTexture.hasLoaded) + { this._onTextureUpdate(); } - else { + else + { value.once('update', this._onTextureUpdate.bind(this)); } } @@ -172,18 +185,22 @@ * * @private */ -Sprite.prototype._onTextureUpdate = function () { +Sprite.prototype._onTextureUpdate = function () +{ // so if _width is 0 then width was not set.. - if (this._width) { + if (this._width) + { this.scale.x = this._width / this.texture.frame.width; } - if (this._height) { + if (this._height) + { this.scale.y = this._height / this.texture.frame.height; } }; -Sprite.prototype._renderWebGL = function (renderer) { +Sprite.prototype._renderWebGL = function (renderer) +{ // this is where content gets renderd.. // watch this space for a little render state manager.. @@ -197,7 +214,8 @@ * @param matrix {Matrix} the transformation matrix of the sprite * @return {Rectangle} the framing rectangle */ -Sprite.prototype.getBounds = function (matrix) { +Sprite.prototype.getBounds = function (matrix) +{ var width = this.texture.frame.width; var height = this.texture.frame.height; @@ -224,11 +242,13 @@ if(b === 0 && c === 0) { // scale may be negative! - if (a < 0) { + if (a < 0) + { a *= -1; } - if (d < 0) { + if (d < 0) + { d *= -1; } @@ -293,28 +313,34 @@ * * @param renderer {CanvasRenderer} The renderer */ -Sprite.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) { +Sprite.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) + { return; } - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; renderer.context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } // Ignore null sources - if (this.texture.valid) { + if (this.texture.valid) + { var resolution = this.texture.baseTexture.resolution / renderer.resolution; renderer.context.globalAlpha = this.worldAlpha; // If smoothingEnabled is supported and we need to change the smoothing property for this texture - if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) { + if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) + { renderer.scaleMode = this.texture.baseTexture.scaleMode; renderer.context[renderer.smoothProperty] = (renderer.scaleMode === CONST.scaleModes.LINEAR); } @@ -324,7 +350,8 @@ var dy = (this.texture.trim ? this.texture.trim.y : 0) - (this.anchor.y * this.texture.trim.height); // Allow for pixel rounding - if (renderer.roundPixels) { + if (renderer.roundPixels) + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -337,7 +364,8 @@ dx = dx | 0; dy = dy | 0; } - else { + else + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -348,8 +376,10 @@ ); } - if (this.tint !== 0xFFFFFF) { - if (this.cachedTint !== this.tint) { + if (this.tint !== 0xFFFFFF) + { + if (this.cachedTint !== this.tint) + { this.cachedTint = this.tint; // TODO clean up caching - how to clean up the caches? @@ -368,7 +398,8 @@ this.texture.crop.height / resolution ); } - else { + else + { renderer.context.drawImage( this.texture.baseTexture.source, this.texture.crop.x, @@ -383,11 +414,13 @@ } } - for (var i = 0, j = this.children.length; i < j; i++) { + for (var i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -402,10 +435,12 @@ * @param frameId {String} The frame Id of the texture in the cache * @return {Sprite} A new Sprite using a texture from the texture cache matching the frameId */ -Sprite.fromFrame = function (frameId) { +Sprite.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache' + this); } @@ -420,6 +455,7 @@ * @param imageId {String} The image url of the texture * @return {Sprite} A new Sprite using a texture from the texture cache matching the image id */ -Sprite.fromImage = function (imageId, crossorigin, scaleMode) { +Sprite.fromImage = function (imageId, crossorigin, scaleMode) +{ return new Sprite(Texture.fromImage(imageId, crossorigin, scaleMode)); }; diff --git a/src/core/display/SpriteBatch.js b/src/core/display/SpriteBatch.js index 3187777..c196fef 100644 --- a/src/core/display/SpriteBatch.js +++ b/src/core/display/SpriteBatch.js @@ -12,7 +12,8 @@ * ```js * var container = new SpriteBatch(); * - * for(var i = 0; i < 100; ++i) { + * for(var i = 0; i < 100; ++i) + * { * var sprite = new PIXI.Sprite.fromImage("myImage.png"); * container.addChild(sprite); * } @@ -25,7 +26,8 @@ */ //TODO RENAME to PARTICLE CONTAINER? -function SpriteBatch() { +function SpriteBatch() +{ DisplayObjectContainer.call(this); } @@ -38,7 +40,8 @@ * * @private */ -SpriteBatch.prototype.updateTransform = function () { +SpriteBatch.prototype.updateTransform = function () +{ // TODO don't need to! this.displayObjectUpdateTransform(); // PIXI.DisplayObjectContainer.prototype.updateTransform.call( this ); @@ -50,8 +53,10 @@ * @param renderer {WebGLRenderer} The webgl renderer * @private */ -SpriteBatch.prototype.renderWebGL = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderWebGL = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -71,8 +76,10 @@ * @param renderer {CanvasRenderer} The canvas renderer * @private */ -SpriteBatch.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -84,10 +91,12 @@ this.displayObjectUpdateTransform(); - for (var i = 0; i < this.children.length; ++i) { + for (var i = 0; i < this.children.length; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -95,9 +104,11 @@ context.globalAlpha = this.worldAlpha * child.alpha; - if (child.rotation % (Math.PI * 2) === 0) { + if (child.rotation % (Math.PI * 2) === 0) + { // this is the fastest way to optimise! - if rotation is 0 then we can avoid any kind of setTransform call - if (isRotated) { + if (isRotated) + { context.setTransform( transform.a, transform.b, @@ -122,8 +133,10 @@ frame.height * child.scale.y ); } - else { - if (!isRotated) { + else + { + if (!isRotated) + { isRotated = true; } @@ -131,7 +144,8 @@ var childTransform = child.worldTransform; - if (renderer.roundPixels) { + if (renderer.roundPixels) + { context.setTransform( childTransform.a, childTransform.b, @@ -141,7 +155,8 @@ childTransform.ty | 0 ); } - else { + else + { context.setTransform( childTransform.a, childTransform.b, diff --git a/src/core/index.js b/src/core/index.js index 3954b6f..eb4a82b 100644 --- a/src/core/index.js +++ b/src/core/index.js @@ -58,11 +58,13 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRenderer: function (width, height, options, noWebGL) { + autoDetectRenderer: function (width, height, options, noWebGL) + { width = width || 800; height = height || 600; - if (!noWebGL && require('webgl-enabled')()) { + if (!noWebGL && require('webgl-enabled')()) + { return new core.WebGLRenderer(width, height, options); } @@ -87,7 +89,8 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRecommendedRenderer: function (width, height, options) { + autoDetectRecommendedRenderer: function (width, height, options) + { var isAndroid = /Android/i.test(navigator.userAgent); return core.autoDetectRenderer(width, height, options, isAndroid); diff --git a/src/core/math/Matrix.js b/src/core/math/Matrix.js index c2f87e2..2ff4848 100644 --- a/src/core/math/Matrix.js +++ b/src/core/math/Matrix.js @@ -10,7 +10,8 @@ * @class * @namespace PIXI */ -function Matrix() { +function Matrix() +{ /** * @member {number} * @default 1 @@ -63,7 +64,8 @@ * * @param array {number[]} The array that the matrix will be populated from. */ -Matrix.prototype.fromArray = function (array) { +Matrix.prototype.fromArray = function (array) +{ this.a = array[0]; this.b = array[1]; this.c = array[3]; @@ -78,14 +80,17 @@ * @param transpose {boolean} Whether we need to transpose the matrix or not * @return {number[]} the newly created array which contains the matrix */ -Matrix.prototype.toArray = function (transpose) { - if (!this.array) { +Matrix.prototype.toArray = function (transpose) +{ + if (!this.array) + { this.array = new Float32Array(9); } var array = this.array; - if (transpose) { + if (transpose) + { array[0] = this.a; array[1] = this.b; array[2] = 0; @@ -96,7 +101,8 @@ array[7] = this.ty; array[8] = 1; } - else { + else + { array[0] = this.a; array[1] = this.c; array[2] = this.tx; @@ -119,7 +125,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, transformed through this matrix */ -Matrix.prototype.apply = function (pos, newPos) { +Matrix.prototype.apply = function (pos, newPos) +{ newPos = newPos || new Point(); newPos.x = this.a * pos.x + this.c * pos.y + this.tx; @@ -136,7 +143,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, inverse-transformed through this matrix */ -Matrix.prototype.applyInverse = function (pos, newPos) { +Matrix.prototype.applyInverse = function (pos, newPos) +{ newPos = newPos || new Point(); var id = 1 / (this.a * this.d + this.c * -this.b); @@ -154,7 +162,8 @@ * @param {number} y * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.translate = function (x, y) { +Matrix.prototype.translate = function (x, y) +{ this.tx += x; this.ty += y; @@ -168,7 +177,8 @@ * @param {number} y The amount to scale vertically * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.scale = function (x, y) { +Matrix.prototype.scale = function (x, y) +{ this.a *= x; this.d *= y; this.c *= x; @@ -186,7 +196,8 @@ * @param {number} angle - The angle in radians. * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.rotate = function (angle) { +Matrix.prototype.rotate = function (angle) +{ var cos = Math.cos( angle ); var sin = Math.sin( angle ); @@ -210,7 +221,8 @@ * @param {Matrix} matrix * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.append = function (matrix) { +Matrix.prototype.append = function (matrix) +{ var a1 = this.a; var b1 = this.b; var c1 = this.c; @@ -232,7 +244,8 @@ * * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.identity = function () { +Matrix.prototype.identity = function () +{ this.a = 1; this.b = 0; this.c = 0; diff --git a/src/core/math/Point.js b/src/core/math/Point.js index 7565b2d..632f346 100644 --- a/src/core/math/Point.js +++ b/src/core/math/Point.js @@ -7,7 +7,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -function Point(x, y) { +function Point(x, y) +{ /** * @member {number} * @default 0 @@ -29,7 +30,8 @@ * * @return {Point} a copy of the point */ -Point.prototype.clone = function () { +Point.prototype.clone = function () +{ return new Point(this.x, this.y); }; @@ -40,7 +42,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -Point.prototype.set = function (x, y) { +Point.prototype.set = function (x, y) +{ this.x = x || 0; this.y = y || ( (y !== 0) ? this.x : 0 ) ; }; diff --git a/src/core/math/shapes/Circle.js b/src/core/math/shapes/Circle.js index 69cfdc9..4d76efc 100644 --- a/src/core/math/shapes/Circle.js +++ b/src/core/math/shapes/Circle.js @@ -10,7 +10,8 @@ * @param y {number} The Y coordinate of the center of this circle * @param radius {number} The radius of the circle */ -function Circle(x, y, radius) { +function Circle(x, y, radius) +{ /** * @member {number} * @default 0 @@ -46,7 +47,8 @@ * @method clone * @return {Circle} a copy of the Circle */ -Circle.prototype.clone = function () { +Circle.prototype.clone = function () +{ return new Circle(this.x, this.y, this.radius); }; @@ -58,8 +60,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Circle */ -Circle.prototype.contains = function (x, y) { - if (this.radius <= 0) { +Circle.prototype.contains = function (x, y) +{ + if (this.radius <= 0) + { return false; } @@ -79,6 +83,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Circle.prototype.getBounds = function () { +Circle.prototype.getBounds = function () +{ return new Rectangle(this.x - this.radius, this.y - this.radius, this.radius * 2, this.radius * 2); }; diff --git a/src/core/math/shapes/Ellipse.js b/src/core/math/shapes/Ellipse.js index 4f2d066..fefd01a 100644 --- a/src/core/math/shapes/Ellipse.js +++ b/src/core/math/shapes/Ellipse.js @@ -11,7 +11,8 @@ * @param width {number} The half width of this ellipse * @param height {number} The half height of this ellipse */ -function Ellipse(x, y, width, height) { +function Ellipse(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -53,7 +54,8 @@ * @method clone * @return {Ellipse} a copy of the ellipse */ -Ellipse.prototype.clone = function () { +Ellipse.prototype.clone = function () +{ return new Ellipse(this.x, this.y, this.width, this.height); }; @@ -65,8 +67,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coords are within this ellipse */ -Ellipse.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Ellipse.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } @@ -86,6 +90,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Ellipse.prototype.getBounds = function () { +Ellipse.prototype.getBounds = function () +{ return new Rectangle(this.x - this.width, this.y - this.height, this.width, this.height); }; diff --git a/src/core/math/shapes/Polygon.js b/src/core/math/shapes/Polygon.js index ae89148..fea6d37 100644 --- a/src/core/math/shapes/Polygon.js +++ b/src/core/math/shapes/Polygon.js @@ -10,16 +10,20 @@ * arguments passed can be flat x,y values e.g. `new Polygon(x,y, x,y, x,y, ...)` where `x` and `y` are * Numbers. */ -function Polygon(points) { +function Polygon(points) +{ //if points isn't an array, use arguments as the array - if (!(points instanceof Array)) { + if (!(points instanceof Array)) + { points = Array.prototype.slice.call(arguments); } //if this is a flat array of numbers, convert it to points - if (points[0] instanceof Point) { + if (points[0] instanceof Point) + { var p = []; - for (var i = 0, il = points.length; i < il; i++) { + for (var i = 0, il = points.length; i < il; i++) + { p.push(points[i].x, points[i].y); } @@ -51,7 +55,8 @@ * * @return {Polygon} a copy of the polygon */ -Polygon.prototype.clone = function () { +Polygon.prototype.clone = function () +{ return new Polygon(this.points.slice()); }; @@ -62,19 +67,22 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this polygon */ -Polygon.prototype.contains = function (x, y) { +Polygon.prototype.contains = function (x, y) +{ var inside = false; // use some raycasting to test hits // https://github.com/substack/point-in-polygon/blob/master/index.js var length = this.points.length / 2; - for (var i = 0, j = length - 1; i < length; j = i++) { + for (var i = 0, j = length - 1; i < length; j = i++) + { var xi = this.points[i * 2], yi = this.points[i * 2 + 1], xj = this.points[j * 2], yj = this.points[j * 2 + 1], intersect = ((yi > y) !== (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi); - if (intersect) { + if (intersect) + { inside = !inside; } } diff --git a/src/core/math/shapes/Rectangle.js b/src/core/math/shapes/Rectangle.js index 16ac62a..4008b68 100644 --- a/src/core/math/shapes/Rectangle.js +++ b/src/core/math/shapes/Rectangle.js @@ -10,7 +10,8 @@ * @param width {number} The overall width of this rectangle * @param height {number} The overall height of this rectangle */ -function Rectangle(x, y, width, height) { +function Rectangle(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -60,7 +61,8 @@ * * @return {Rectangle} a copy of the rectangle */ -Rectangle.prototype.clone = function () { +Rectangle.prototype.clone = function () +{ return new Rectangle(this.x, this.y, this.width, this.height); }; @@ -71,13 +73,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rectangle */ -Rectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Rectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/math/shapes/RoundedRectangle.js b/src/core/math/shapes/RoundedRectangle.js index 27d286e..7bf6411 100644 --- a/src/core/math/shapes/RoundedRectangle.js +++ b/src/core/math/shapes/RoundedRectangle.js @@ -11,7 +11,8 @@ * @param height {number} The overall height of this rounded rectangle * @param radius {number} Controls the radius of the rounded corners */ -function RoundedRectangle(x, y, width, height, radius) { +function RoundedRectangle(x, y, width, height, radius) +{ /** * @member {number} * @default 0 @@ -58,7 +59,8 @@ * * @return {RoundedRectangle} a copy of the rounded rectangle */ -RoundedRectangle.prototype.clone = function () { +RoundedRectangle.prototype.clone = function () +{ return new RoundedRectangle(this.x, this.y, this.width, this.height, this.radius); }; @@ -69,13 +71,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rounded Rectangle */ -RoundedRectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +RoundedRectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/primitives/Graphics.js b/src/core/primitives/Graphics.js index 261c534..e902d2a 100644 --- a/src/core/primitives/Graphics.js +++ b/src/core/primitives/Graphics.js @@ -16,7 +16,8 @@ * @extends DisplayObjectContainer * @namespace PIXI */ -function Graphics() { +function Graphics() +{ DisplayObjectContainer.call(this); this.renderable = true; @@ -154,16 +155,20 @@ * @private */ cacheAsBitmap: { - get: function () { + get: function () + { return this._cacheAsBitmap; }, - set: function (value) { + set: function (value) + { this._cacheAsBitmap = value; - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._generateCachedSprite(); } - else { + else + { this.destroyCachedSprite(); this.dirty = true; } @@ -176,7 +181,8 @@ * * @return {Graphics} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ var clone = new Graphics(); clone.renderable = this.renderable; @@ -192,7 +198,8 @@ clone.cachedSpriteDirty = this.cachedSpriteDirty; // copy graphics data - for (var i = 0; i < this.graphicsData.length; ++i) { + for (var i = 0; i < this.graphicsData.length; ++i) + { clone.graphicsData.push(this.graphicsData.clone()); } @@ -211,17 +218,21 @@ * @param alpha {number} alpha of the line to draw, will update the objects stored style * @return {Graphics} */ -Graphics.prototype.lineStyle = function (lineWidth, color, alpha) { +Graphics.prototype.lineStyle = function (lineWidth, color, alpha) +{ this.lineWidth = lineWidth || 0; this.lineColor = color || 0; this.lineAlpha = (arguments.length < 3) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length) + { // halfway through a line? start a new one! this.drawShape( new math.Polygon( this.currentPath.shape.points.slice(-2) )); } - else { + else + { // otherwise its empty so lets just set the line properties this.currentPath.lineWidth = this.lineWidth; this.currentPath.lineColor = this.lineColor; @@ -239,7 +250,8 @@ * @param y {number} the Y coordinate to move to * @return {Graphics} */ -Graphics.prototype.moveTo = function (x, y) { +Graphics.prototype.moveTo = function (x, y) +{ this.drawShape(new math.Polygon([x,y])); return this; @@ -253,7 +265,8 @@ * @param y {number} the Y coordinate to draw to * @return {Graphics} */ -Graphics.prototype.lineTo = function (x, y) { +Graphics.prototype.lineTo = function (x, y) +{ this.currentPath.shape.points.push(x, y); this.dirty = true; @@ -270,13 +283,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -285,7 +302,8 @@ n = 20, points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { this.moveTo(0, 0); } @@ -293,7 +311,8 @@ var fromY = points[points.length-1]; var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; xa = fromX + ( (cpX - fromX) * j ); @@ -319,13 +338,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -342,7 +365,8 @@ var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; dt = (1 - j); @@ -373,13 +397,17 @@ * @param radius {number} The radius of the arc * @return {Graphics} */ -Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points.push(x1, y1); } } - else { + else + { this.moveTo(x1, y1); } @@ -392,12 +420,15 @@ b2 = x2 - x1, mm = Math.abs(a1 * b2 - b1 * a2); - if (mm < 1.0e-8 || radius === 0) { - if (points[points.length-2] !== x1 || points[points.length-1] !== y1) { + if (mm < 1.0e-8 || radius === 0) + { + if (points[points.length-2] !== x1 || points[points.length-1] !== y1) + { points.push(x1, y1); } } - else { + else + { var dd = a1 * a1 + b1 * b1, cc = a2 * a2 + b2 * b2, tt = a1 * a2 + b1 * b2, @@ -433,42 +464,51 @@ * @param anticlockwise {boolean} Optional. Specifies whether the drawing should be counterclockwise or clockwise. False is default, and indicates clockwise, while true indicates counter-clockwise. * @return {Graphics} */ -Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) { +Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) +{ var startX = cx + Math.cos(startAngle) * radius; var startY = cy + Math.sin(startAngle) * radius; var points; // TODO - This if-else makes no sense. It uses currentPath in the else where it doesn't exist... - if (this.currentPath) { + if (this.currentPath) + { points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { points.push(startX, startY); } - else if (points[points.length-2] !== startX || points[points.length-1] !== startY) { + else if (points[points.length-2] !== startX || points[points.length-1] !== startY) + { points.push(startX, startY); } } - else { + else + { this.moveTo(startX, startY); points = this.currentPath.shape.points; } - if (startAngle === endAngle) { + if (startAngle === endAngle) + { return this; } - if (!anticlockwise && endAngle <= startAngle) { + if (!anticlockwise && endAngle <= startAngle) + { endAngle += Math.PI * 2; } - else if (anticlockwise && startAngle <= endAngle) { + else if (anticlockwise && startAngle <= endAngle) + { startAngle += Math.PI * 2; } var sweep = anticlockwise ? (startAngle - endAngle) *-1 : (endAngle - startAngle); var segs = (Math.abs(sweep)/ (Math.PI * 2)) * 40; - if (sweep === 0) { + if (sweep === 0) + { return this; } @@ -482,7 +522,8 @@ var remainder = ( segMinus % 1 ) / segMinus; - for (var i = 0; i <= segMinus; ++i) { + for (var i = 0; i <= segMinus; ++i) + { var real = i + remainder * i; var angle = ((theta) + startAngle + (theta2 * real)); @@ -506,13 +547,16 @@ * @param alpha {number} the alpha of the fill * @return {Graphics} */ -Graphics.prototype.beginFill = function (color, alpha) { +Graphics.prototype.beginFill = function (color, alpha) +{ this.filling = true; this.fillColor = color || 0; this.fillAlpha = (alpha === undefined) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length <= 2) + { this.currentPath.fill = this.filling; this.currentPath.fillColor = this.fillColor; this.currentPath.fillAlpha = this.fillAlpha; @@ -526,7 +570,8 @@ * * @return {Graphics} */ -Graphics.prototype.endFill = function () { +Graphics.prototype.endFill = function () +{ this.filling = false; this.fillColor = null; this.fillAlpha = 1; @@ -542,7 +587,8 @@ * @param height {number} The height of the rectangle * @return {Graphics} */ -Graphics.prototype.drawRect = function ( x, y, width, height ) { +Graphics.prototype.drawRect = function ( x, y, width, height ) +{ this.drawShape(new math.Rectangle(x,y, width, height)); return this; @@ -556,7 +602,8 @@ * @param height {number} The height of the rectangle * @param radius {number} Radius of the rectangle corners */ -Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) { +Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) +{ this.drawShape(new math.RoundedRectangle(x, y, width, height, radius)); return this; @@ -570,7 +617,8 @@ * @param radius {number} The radius of the circle * @return {Graphics} */ -Graphics.prototype.drawCircle = function (x, y, radius) { +Graphics.prototype.drawCircle = function (x, y, radius) +{ this.drawShape(new math.Circle(x,y, radius)); return this; @@ -585,7 +633,8 @@ * @param height {number} The half height of the ellipse * @return {Graphics} */ -Graphics.prototype.drawEllipse = function (x, y, width, height) { +Graphics.prototype.drawEllipse = function (x, y, width, height) +{ this.drawShape(new math.Ellipse(x, y, width, height)); return this; @@ -597,8 +646,10 @@ * @param path {Array} The path data used to construct the polygon. * @return {Graphics} */ -Graphics.prototype.drawPolygon = function (path) { - if (!(path instanceof Array)) { +Graphics.prototype.drawPolygon = function (path) +{ + if (!(path instanceof Array)) + { path = Array.prototype.slice.call(arguments); } @@ -612,7 +663,8 @@ * * @return {Graphics} */ -Graphics.prototype.clear = function () { +Graphics.prototype.clear = function () +{ this.lineWidth = 0; this.filling = false; @@ -631,7 +683,8 @@ * @param scaleMode {number} Should be one of the scaleMode consts * @return {Texture} a texture of the graphics object */ -Graphics.prototype.generateTexture = function (resolution, scaleMode) { +Graphics.prototype.generateTexture = function (resolution, scaleMode) +{ resolution = resolution || 1; var bounds = this.getBounds(); @@ -655,17 +708,21 @@ * * @param renderer {WebGLRenderer} */ -Graphics.prototype._renderWebGL = function (renderer) { +Graphics.prototype._renderWebGL = function (renderer) +{ // if the sprite is not visible or the alpha is 0 then no need to render this element - if (this.isMask === true) { + if (this.isMask === true) + { return; } // this code may still be needed so leaving for now.. - // + // /* - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture on the gpu too! @@ -681,17 +738,24 @@ return; } - */ - - // check if the webgl graphic needs to be updated - if (this.glDirty) { - this.dirty = true; - this.glDirty = false; - } + else */ - renderer.setObjectRendererer(renderer.graphicsRenderer); - renderer.graphicsRenderer.render(this); + renderer.spriteBatch.stop(); + renderer.blendModeManager.setBlendMode(this.blendMode); + // check blend mode + renderer.blendModeManager.setBlendMode( this.blendMode ); + + // check if the webgl graphic needs to be updated + if (this.glDirty) + { + this.dirty = true; + this.glDirty = false; + } + + WebGLGraphics.renderGraphics(this, renderer); + + renderer.spriteBatch.start(); }; /** @@ -700,14 +764,18 @@ * @param renderer {CanvasRenderer} * @private */ -Graphics.prototype.renderCanvas = function (renderer) { +Graphics.prototype.renderCanvas = function (renderer) +{ // 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.isMask === true) { + if (!this.visible || this.alpha <= 0 || this.isMask === true) + { return; } - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture @@ -723,16 +791,19 @@ return; } - else { + else + { var context = renderer.context; var transform = this.worldTransform; - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } @@ -748,11 +819,13 @@ CanvasGraphics.renderGraphics(this, context); - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } } @@ -763,13 +836,16 @@ * * @return {Rectangle} the rectangular bounding area */ -Graphics.prototype.getBounds = function (matrix) { +Graphics.prototype.getBounds = function (matrix) +{ // return an empty object if the item is a mask! - if (this.isMask) { + if (this.isMask) + { return math.Rectangle.EMPTY; } - if (this.dirty) { + if (this.dirty) + { this.updateLocalBounds(); this.glDirty = true; @@ -841,23 +917,27 @@ * Update the bounds of the object * */ -Graphics.prototype.updateLocalBounds = function () { +Graphics.prototype.updateLocalBounds = function () +{ var minX = Infinity; var maxX = -Infinity; var minY = Infinity; var maxY = -Infinity; - if (this.graphicsData.length) { + if (this.graphicsData.length) + { var shape, points, x, y, w, h; - for (var i = 0; i < this.graphicsData.length; i++) { + for (var i = 0; i < this.graphicsData.length; i++) + { var data = this.graphicsData[i]; var type = data.type; var lineWidth = data.lineWidth; shape = data.shape; - if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) { + if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) + { x = shape.x - lineWidth/2; y = shape.y - lineWidth/2; w = shape.width + lineWidth; @@ -869,7 +949,8 @@ minY = y < minY ? y : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.CIRC) { + else if (type === CONST.SHAPES.CIRC) + { x = shape.x; y = shape.y; w = shape.radius + lineWidth/2; @@ -881,7 +962,8 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.ELIP) { + else if (type === CONST.SHAPES.ELIP) + { x = shape.x; y = shape.y; w = shape.width + lineWidth/2; @@ -893,11 +975,13 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else { + else + { // POLY points = shape.points; - for (var j = 0; j < points.length; j += 2) { + for (var j = 0; j < points.length; j += 2) + { x = points[j]; y = points[j+1]; @@ -910,7 +994,8 @@ } } } - else { + else + { minX = 0; maxX = 0; minY = 0; @@ -931,10 +1016,12 @@ * * @private */ -Graphics.prototype._generateCachedSprite = function () { +Graphics.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { var canvasBuffer = new CanvasBuffer(bounds.width, bounds.height); var texture = Texture.fromCanvas(canvasBuffer.canvas); @@ -943,7 +1030,8 @@ this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.buffer.resize(bounds.width, bounds.height); } @@ -968,7 +1056,8 @@ * * @private */ -Graphics.prototype.updateCachedSpriteTexture = function () { +Graphics.prototype.updateCachedSpriteTexture = function () +{ var cachedSprite = this._cachedSprite; var texture = cachedSprite.texture; var canvas = cachedSprite.buffer.canvas; @@ -989,7 +1078,8 @@ * Destroys a previous cached sprite. * */ -Graphics.prototype.destroyCachedSprite = function () { +Graphics.prototype.destroyCachedSprite = function () +{ this._cachedSprite.texture.destroy(true); // let the gc collect the unused sprite @@ -1003,10 +1093,13 @@ * @param {Circle|Rectangle|Ellipse|Line|Polygon} shape The Shape object to draw. * @return {GraphicsData} The generated GraphicsData object. */ -Graphics.prototype.drawShape = function (shape) { - if (this.currentPath) { +Graphics.prototype.drawShape = function (shape) +{ + if (this.currentPath) + { // check current path! - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath.shape.points.length <= 2) + { this.graphicsData.pop(); } } @@ -1017,7 +1110,8 @@ this.graphicsData.push(data); - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { data.shape.closed = this.filling; this.currentPath = data; } diff --git a/src/core/primitives/GraphicsData.js b/src/core/primitives/GraphicsData.js index 99decbe..788f6f2 100644 --- a/src/core/primitives/GraphicsData.js +++ b/src/core/primitives/GraphicsData.js @@ -4,7 +4,8 @@ * @class * @namespace PIXI */ -function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) { +function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) +{ this.lineWidth = lineWidth; this.lineColor = lineColor; this.lineAlpha = lineAlpha; @@ -27,7 +28,8 @@ * * @return {GraphicsData} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ return new GraphicsData( this.lineWidth, this.lineColor, diff --git a/src/core/display/DisplayObject.js b/src/core/display/DisplayObject.js index 66ebc3c..20e778c 100644 --- a/src/core/display/DisplayObject.js +++ b/src/core/display/DisplayObject.js @@ -7,7 +7,8 @@ * @class * @namespace PIXI */ -function DisplayObject() { +function DisplayObject() +{ /** * The coordinate of the object relative to the local coordinates of the parent. * @@ -152,10 +153,12 @@ * @memberof DisplayObject# */ x: { - get: function () { + get: function () + { return this.position.x; }, - set: function (value) { + set: function (value) + { this.position.x = value; } }, @@ -167,10 +170,12 @@ * @memberof DisplayObject# */ y: { - get: function () { + get: function () + { return this.position.y; }, - set: function (value) { + set: function (value) + { this.position.y = value; } }, @@ -183,11 +188,13 @@ * @readonly */ worldVisible: { - get: function () { + get: function () + { var item = this; do { - if (!item.visible) { + if (!item.visible) + { return false; } @@ -207,17 +214,21 @@ * @memberof DisplayObject# */ mask: { - get: function () { + get: function () + { return this._mask; }, - set: function (value) { - if (this._mask) { + set: function (value) + { + if (this._mask) + { this._mask.isMask = false; } this._mask = value; - if (this._mask) { + if (this._mask) + { this._mask.isMask = true; } } @@ -232,18 +243,23 @@ * @memberof DisplayObject# */ filters: { - get: function () { + get: function () + { return this._filters; }, - set: function (value) { - if (value) { + set: function (value) + { + if (value) + { // now put all the passes in one place.. var passes = []; - for (var i = 0; i < value.length; i++) { + for (var i = 0; i < value.length; i++) + { var filterPasses = value[i].passes; - for (var j = 0; j < filterPasses.length; j++) { + for (var j = 0; j < filterPasses.length; j++) + { passes.push(filterPasses[j]); } } @@ -264,8 +280,9 @@ * * @private */ -DisplayObject.prototype.updateTransform = function () { - +DisplayObject.prototype.updateTransform = function () +{ + // create some matrix refs for easy access var pt = this.parent.worldTransform; var wt = this.worldTransform; @@ -274,9 +291,11 @@ var a, b, c, d, tx, ty; // so if rotation is between 0 then we can simplify the multiplication process.. - if (this.rotation % math.PI_2) { + if (this.rotation % math.PI_2) + { // 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) { + if (this.rotation !== this.rotationCache) + { this.rotationCache = this.rotation; this._sr = Math.sin(this.rotation); this._cr = Math.cos(this.rotation); @@ -291,7 +310,8 @@ ty = this.position.y; // check for pivot.. not often used so geared towards that fact! - if (this.pivot.x || this.pivot.y) { + 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; } @@ -304,7 +324,8 @@ wt.tx = tx * pt.a + ty * pt.c + pt.tx; wt.ty = tx * pt.b + ty * pt.d + pt.ty; } - else { + else + { // lets do the fast version as we know there is no rotation.. a = this.scale.x; d = this.scale.y; @@ -333,7 +354,8 @@ * @param matrix {Matrix} * @return {Rectangle} the rectangular bounding area */ -DisplayObject.prototype.getBounds = function (/* matrix */) { +DisplayObject.prototype.getBounds = function (/* matrix */) +{ return math.Rectangle.EMPTY; }; @@ -342,7 +364,8 @@ * * @return {Rectangle} the rectangular bounding area */ -DisplayObject.prototype.getLocalBounds = function () { +DisplayObject.prototype.getLocalBounds = function () +{ return this.getBounds(math.Matrix.IDENTITY); }; @@ -352,7 +375,8 @@ * @param position {Point} The world origin to calculate from * @return {Point} A point object representing the position of this object */ -DisplayObject.prototype.toGlobal = function (position) { +DisplayObject.prototype.toGlobal = function (position) +{ // don't need to u[date the lot this.displayObjectUpdateTransform(); return this.worldTransform.apply(position); @@ -365,8 +389,10 @@ * @param [from] {DisplayObject} The DisplayObject to calculate the global position from * @return {Point} A point object representing the position of this object */ -DisplayObject.prototype.toLocal = function (position, from) { - if (from) { +DisplayObject.prototype.toLocal = function (position, from) +{ + if (from) + { position = from.toGlobal(position); } @@ -381,7 +407,8 @@ * @param renderer {WebGLRenderer} The renderer * @private */ -DisplayObject.prototype.renderWebGL = function (/* renderer */) { +DisplayObject.prototype.renderWebGL = function (/* renderer */) +{ // OVERWRITE; }; @@ -391,6 +418,7 @@ * @param renderer {CanvasRenderer} The renderer * @private */ -DisplayObject.prototype.renderCanvas = function (/* renderer */) { +DisplayObject.prototype.renderCanvas = function (/* renderer */) +{ // OVERWRITE; }; diff --git a/src/core/display/DisplayObjectContainer.js b/src/core/display/DisplayObjectContainer.js index 689f40b..4625ee8 100644 --- a/src/core/display/DisplayObjectContainer.js +++ b/src/core/display/DisplayObjectContainer.js @@ -12,7 +12,8 @@ * @extends DisplayObject * @namespace PIXI */ -function DisplayObjectContainer() { +function DisplayObjectContainer() +{ DisplayObject.call(this); /** @@ -47,17 +48,21 @@ * @memberof DisplayObjectContainer# */ width: { - get: function () { + get: function () + { return this.scale.x * this.getLocalBounds().width; }, - set: function (value) { + set: function (value) + { var width = this.getLocalBounds().width; - if(width !== 0) { + if(width !== 0) + { this.scale.x = value / width; } - else { + else + { this.scale.x = 1; } @@ -73,17 +78,21 @@ * @memberof DisplayObjectContainer# */ height: { - get: function () { + get: function () + { return this.scale.y * this.getLocalBounds().height; }, - set: function (value) { + set: function (value) + { var height = this.getLocalBounds().height; - if (height !== 0) { + if (height !== 0) + { this.scale.y = value / height ; } - else { + else + { this.scale.y = 1; } @@ -100,18 +109,23 @@ * @memberof DisplayObject# */ cacheAsBitmap: { - get: function () { + get: function () + { return this._cacheAsBitmap; }, - set: function (value) { - if (this._cacheAsBitmap === value) { + set: function (value) + { + if (this._cacheAsBitmap === value) + { return; } - if (value) { + if (value) + { this._generateCachedSprite(); } - else { + else + { this._destroyCachedSprite(); } @@ -126,7 +140,8 @@ * @param child {DisplayObject} The DisplayObject to add to the container * @return {DisplayObject} The child that was added. */ -DisplayObjectContainer.prototype.addChild = function (child) { +DisplayObjectContainer.prototype.addChild = function (child) +{ return this.addChildAt(child, this.children.length); }; @@ -137,14 +152,18 @@ * @param index {Number} The index to place the child in * @return {DisplayObject} The child that was added. */ -DisplayObjectContainer.prototype.addChildAt = function (child, index) { +DisplayObjectContainer.prototype.addChildAt = function (child, index) +{ // prevent adding self as child - if (child === this) { + if (child === this) + { return; } - if (index >= 0 && index <= this.children.length) { - if (child.parent) { + if (index >= 0 && index <= this.children.length) + { + if (child.parent) + { child.parent.removeChild(child); } @@ -154,7 +173,8 @@ return child; } - else { + else + { throw new Error(child + 'addChildAt: The index '+ index +' supplied is out of bounds ' + this.children.length); } }; @@ -165,15 +185,18 @@ * @param child {DisplayObject} * @param child2 {DisplayObject} */ -DisplayObjectContainer.prototype.swapChildren = function (child, child2) { - if (child === child2) { +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) { + if (index1 < 0 || index2 < 0) + { throw new Error('swapChildren: Both the supplied DisplayObjects must be a child of the caller.'); } @@ -187,10 +210,12 @@ * @param child {DisplayObject} The DisplayObject instance to identify * @return {Number} The index position of the child display object to identify */ -DisplayObjectContainer.prototype.getChildIndex = function (child) { +DisplayObjectContainer.prototype.getChildIndex = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { throw new Error('The supplied DisplayObject must be a child of the caller'); } @@ -203,8 +228,10 @@ * @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 */ -DisplayObjectContainer.prototype.setChildIndex = function (child, index) { - if (index < 0 || index >= this.children.length) { +DisplayObjectContainer.prototype.setChildIndex = function (child, index) +{ + if (index < 0 || index >= this.children.length) + { throw new Error('The supplied index is out of bounds'); } @@ -220,8 +247,10 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child at the given index, if any. */ -DisplayObjectContainer.prototype.getChildAt = function (index) { - if (index < 0 || index >= this.children.length) { +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'); } @@ -234,10 +263,12 @@ * @param child {DisplayObject} The DisplayObject to remove * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChild = function (child) { +DisplayObjectContainer.prototype.removeChild = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { return; } @@ -250,7 +281,8 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChildAt = function (index) { +DisplayObjectContainer.prototype.removeChildAt = function (index) +{ var child = this.getChildAt(index); child.parent = null; @@ -265,24 +297,29 @@ * @param beginIndex {Number} The beginning position. Default value is 0. * @param endIndex {Number} The ending position. Default value is size of the container. */ -DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) { +DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) +{ var begin = beginIndex || 0; var end = typeof endIndex === 'number' ? endIndex : this.children.length; var range = end - begin; - if (range > 0 && range <= end) { + if (range > 0 && range <= end) + { var removed = this.children.splice(begin, range); - for (var i = 0; i < removed.length; ++i) { + for (var i = 0; i < removed.length; ++i) + { removed[i].parent = null; } return removed; } - else if (range === 0 && this.children.length === 0) { + else if (range === 0 && this.children.length === 0) + { return []; } - else { + else + { throw new RangeError('removeChildren: numeric values are outside the acceptable range.'); } }; @@ -291,7 +328,8 @@ * Generates and updates the cached sprite for this object. * */ -DisplayObjectContainer.prototype.updateCachedSprite = function () { +DisplayObjectContainer.prototype.updateCachedSprite = function () +{ this._generateCachedSprite(); }; @@ -304,7 +342,8 @@ * @param renderer {CanvasRenderer|WebGLRenderer} The renderer used to generate the texture. * @return {Texture} a texture of the graphics object */ -DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) { +DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) +{ var bounds = this.getLocalBounds(); var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0, renderer, scaleMode, resolution); @@ -322,18 +361,22 @@ * * @private */ -DisplayObjectContainer.prototype.updateTransform = function () { - if (!this.visible) { +DisplayObjectContainer.prototype.updateTransform = function () +{ + if (!this.visible) + { return; } this.displayObjectUpdateTransform(); - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { return; } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } }; @@ -346,8 +389,10 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getBounds = function () { - if (this.children.length === 0) { +DisplayObjectContainer.prototype.getBounds = function () +{ + if (this.children.length === 0) + { return math.Rectangle.EMPTY; } @@ -365,10 +410,12 @@ var childVisible = false; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -386,7 +433,8 @@ maxY = maxY > childMaxY ? maxY : childMaxY; } - if (!childVisible) { + if (!childVisible) + { return math.Rectangle.EMPTY; } @@ -407,12 +455,14 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getLocalBounds = function () { +DisplayObjectContainer.prototype.getLocalBounds = function () +{ var matrixCache = this.worldTransform; this.worldTransform = math.Matrix.IDENTITY; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } @@ -428,13 +478,16 @@ * * @param renderer {WebGLRenderer} The renderer */ -DisplayObjectContainer.prototype.renderWebGL = function (renderer) { +DisplayObjectContainer.prototype.renderWebGL = function (renderer) +{ // if the object is not visible or the alpha is 0 then no need to render this element - if (!this.visible || this.alpha <= 0) { + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } @@ -442,14 +495,17 @@ var i, j; // do a quick check to see if this element has a mask or a filter. - if (this._mask || this._filters) { + if (this._mask || this._filters) + { // push filter first as we need to ensure the stencil buffer is correct for any masking - if (this._filters) { + if (this._filters) + { renderer.spriteBatch.flush(); renderer.filterManager.pushFilter(this._filterBlock); } - if (this._mask) { + if (this._mask) + { renderer.spriteBatch.stop(); renderer.maskManager.pushMask(this.mask, renderer); renderer.spriteBatch.start(); @@ -459,36 +515,42 @@ this._renderWebGL(renderer); // now loop through the children and make sure they get rendered - for (i = 0, j = this.children.length; i < j; i++) { + for (i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderWebGL(renderer); } // time to stop the sprite batch as either a mask element or a filter draw will happen next renderer.spriteBatch.stop(); - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(this._mask, renderer); } - if (this._filters) { + if (this._filters) + { renderer.filterManager.popFilter(); } renderer.spriteBatch.start(); } - else { + else + { this._renderWebGL(renderer); // simple render children! - for (i = 0, j = this.children.length; i < j; ++i) { + for (i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderWebGL(renderer); } } }; -DisplayObjectContainer.prototype._renderWebGL = function (renderer) { +DisplayObjectContainer.prototype._renderWebGL = function (renderer) +{ // this is where content itself gets renderd.. @@ -499,25 +561,31 @@ * * @param renderer {CanvasRenderer} The renderer */ -DisplayObjectContainer.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0) { +DisplayObjectContainer.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -528,13 +596,16 @@ * @param renderer {WebGLRenderer|CanvasRenderer} The renderer * @private */ -DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) { +DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) +{ this._cachedSprite.worldAlpha = this.worldAlpha; - if (renderer.gl) { + if (renderer.gl) + { this._cachedSprite.renderWebGL(renderer); } - else { + else + { this._cachedSprite.renderCanvas(renderer); } }; @@ -544,10 +615,12 @@ * * @private */ -DisplayObjectContainer.prototype._generateCachedSprite = function () { +DisplayObjectContainer.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { // TODO - RenderTexture now *requires* a renderer instance, so this is like broken // because `renderer` isn't actually in scope here :P var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0); @@ -555,7 +628,8 @@ this._cachedSprite = new Sprite(renderTexture); this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.texture.resize(bounds.width | 0, bounds.height | 0); } @@ -580,8 +654,10 @@ * * @private */ -DisplayObjectContainer.prototype._destroyCachedSprite = function () { - if (!this._cachedSprite) { +DisplayObjectContainer.prototype._destroyCachedSprite = function () +{ + if (!this._cachedSprite) + { return; } diff --git a/src/core/display/Sprite.js b/src/core/display/Sprite.js index 707da24..5862aef 100644 --- a/src/core/display/Sprite.js +++ b/src/core/display/Sprite.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param texture {Texture} The texture for this sprite */ -function Sprite(texture) { +function Sprite(texture) +{ DisplayObjectContainer.call(this); /** @@ -85,12 +86,14 @@ this.texture = texture || Texture.EMPTY; } -Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) { +Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) +{ DisplayObjectContainer.prototype.destroy.call(this); this.anchor = null; - if (destroyTexture) { + if (destroyTexture) + { this._texture.destroy(destroyBaseTexture); } @@ -111,10 +114,12 @@ * @memberof Sprite# */ width: { - get: function () { + get: function () + { return this.scale.x * this.texture.frame.width; }, - set: function (value) { + set: function (value) + { this.scale.x = value / this.texture.frame.width; this._width = value; } @@ -127,10 +132,12 @@ * @memberof Sprite# */ height: { - get: function () { + get: function () + { return this.scale.y * this.texture.frame.height; }, - set: function (value) { + set: function (value) + { this.scale.y = value / this.texture.frame.height; this._height = value; } @@ -143,23 +150,29 @@ * @memberof Sprite# */ texture: { - get: function () { + get: function () + { return this._texture; }, - set: function (value) { - if (this._texture === value) { + set: function (value) + { + if (this._texture === value) + { return; } this._texture = value; this.cachedTint = 0xFFFFFF; - if (value) { + if (value) + { // wait for the texture to load - if (value.baseTexture.hasLoaded) { + if (value.baseTexture.hasLoaded) + { this._onTextureUpdate(); } - else { + else + { value.once('update', this._onTextureUpdate.bind(this)); } } @@ -172,18 +185,22 @@ * * @private */ -Sprite.prototype._onTextureUpdate = function () { +Sprite.prototype._onTextureUpdate = function () +{ // so if _width is 0 then width was not set.. - if (this._width) { + if (this._width) + { this.scale.x = this._width / this.texture.frame.width; } - if (this._height) { + if (this._height) + { this.scale.y = this._height / this.texture.frame.height; } }; -Sprite.prototype._renderWebGL = function (renderer) { +Sprite.prototype._renderWebGL = function (renderer) +{ // this is where content gets renderd.. // watch this space for a little render state manager.. @@ -197,7 +214,8 @@ * @param matrix {Matrix} the transformation matrix of the sprite * @return {Rectangle} the framing rectangle */ -Sprite.prototype.getBounds = function (matrix) { +Sprite.prototype.getBounds = function (matrix) +{ var width = this.texture.frame.width; var height = this.texture.frame.height; @@ -224,11 +242,13 @@ if(b === 0 && c === 0) { // scale may be negative! - if (a < 0) { + if (a < 0) + { a *= -1; } - if (d < 0) { + if (d < 0) + { d *= -1; } @@ -293,28 +313,34 @@ * * @param renderer {CanvasRenderer} The renderer */ -Sprite.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) { +Sprite.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) + { return; } - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; renderer.context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } // Ignore null sources - if (this.texture.valid) { + if (this.texture.valid) + { var resolution = this.texture.baseTexture.resolution / renderer.resolution; renderer.context.globalAlpha = this.worldAlpha; // If smoothingEnabled is supported and we need to change the smoothing property for this texture - if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) { + if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) + { renderer.scaleMode = this.texture.baseTexture.scaleMode; renderer.context[renderer.smoothProperty] = (renderer.scaleMode === CONST.scaleModes.LINEAR); } @@ -324,7 +350,8 @@ var dy = (this.texture.trim ? this.texture.trim.y : 0) - (this.anchor.y * this.texture.trim.height); // Allow for pixel rounding - if (renderer.roundPixels) { + if (renderer.roundPixels) + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -337,7 +364,8 @@ dx = dx | 0; dy = dy | 0; } - else { + else + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -348,8 +376,10 @@ ); } - if (this.tint !== 0xFFFFFF) { - if (this.cachedTint !== this.tint) { + if (this.tint !== 0xFFFFFF) + { + if (this.cachedTint !== this.tint) + { this.cachedTint = this.tint; // TODO clean up caching - how to clean up the caches? @@ -368,7 +398,8 @@ this.texture.crop.height / resolution ); } - else { + else + { renderer.context.drawImage( this.texture.baseTexture.source, this.texture.crop.x, @@ -383,11 +414,13 @@ } } - for (var i = 0, j = this.children.length; i < j; i++) { + for (var i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -402,10 +435,12 @@ * @param frameId {String} The frame Id of the texture in the cache * @return {Sprite} A new Sprite using a texture from the texture cache matching the frameId */ -Sprite.fromFrame = function (frameId) { +Sprite.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache' + this); } @@ -420,6 +455,7 @@ * @param imageId {String} The image url of the texture * @return {Sprite} A new Sprite using a texture from the texture cache matching the image id */ -Sprite.fromImage = function (imageId, crossorigin, scaleMode) { +Sprite.fromImage = function (imageId, crossorigin, scaleMode) +{ return new Sprite(Texture.fromImage(imageId, crossorigin, scaleMode)); }; diff --git a/src/core/display/SpriteBatch.js b/src/core/display/SpriteBatch.js index 3187777..c196fef 100644 --- a/src/core/display/SpriteBatch.js +++ b/src/core/display/SpriteBatch.js @@ -12,7 +12,8 @@ * ```js * var container = new SpriteBatch(); * - * for(var i = 0; i < 100; ++i) { + * for(var i = 0; i < 100; ++i) + * { * var sprite = new PIXI.Sprite.fromImage("myImage.png"); * container.addChild(sprite); * } @@ -25,7 +26,8 @@ */ //TODO RENAME to PARTICLE CONTAINER? -function SpriteBatch() { +function SpriteBatch() +{ DisplayObjectContainer.call(this); } @@ -38,7 +40,8 @@ * * @private */ -SpriteBatch.prototype.updateTransform = function () { +SpriteBatch.prototype.updateTransform = function () +{ // TODO don't need to! this.displayObjectUpdateTransform(); // PIXI.DisplayObjectContainer.prototype.updateTransform.call( this ); @@ -50,8 +53,10 @@ * @param renderer {WebGLRenderer} The webgl renderer * @private */ -SpriteBatch.prototype.renderWebGL = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderWebGL = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -71,8 +76,10 @@ * @param renderer {CanvasRenderer} The canvas renderer * @private */ -SpriteBatch.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -84,10 +91,12 @@ this.displayObjectUpdateTransform(); - for (var i = 0; i < this.children.length; ++i) { + for (var i = 0; i < this.children.length; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -95,9 +104,11 @@ context.globalAlpha = this.worldAlpha * child.alpha; - if (child.rotation % (Math.PI * 2) === 0) { + if (child.rotation % (Math.PI * 2) === 0) + { // this is the fastest way to optimise! - if rotation is 0 then we can avoid any kind of setTransform call - if (isRotated) { + if (isRotated) + { context.setTransform( transform.a, transform.b, @@ -122,8 +133,10 @@ frame.height * child.scale.y ); } - else { - if (!isRotated) { + else + { + if (!isRotated) + { isRotated = true; } @@ -131,7 +144,8 @@ var childTransform = child.worldTransform; - if (renderer.roundPixels) { + if (renderer.roundPixels) + { context.setTransform( childTransform.a, childTransform.b, @@ -141,7 +155,8 @@ childTransform.ty | 0 ); } - else { + else + { context.setTransform( childTransform.a, childTransform.b, diff --git a/src/core/index.js b/src/core/index.js index 3954b6f..eb4a82b 100644 --- a/src/core/index.js +++ b/src/core/index.js @@ -58,11 +58,13 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRenderer: function (width, height, options, noWebGL) { + autoDetectRenderer: function (width, height, options, noWebGL) + { width = width || 800; height = height || 600; - if (!noWebGL && require('webgl-enabled')()) { + if (!noWebGL && require('webgl-enabled')()) + { return new core.WebGLRenderer(width, height, options); } @@ -87,7 +89,8 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRecommendedRenderer: function (width, height, options) { + autoDetectRecommendedRenderer: function (width, height, options) + { var isAndroid = /Android/i.test(navigator.userAgent); return core.autoDetectRenderer(width, height, options, isAndroid); diff --git a/src/core/math/Matrix.js b/src/core/math/Matrix.js index c2f87e2..2ff4848 100644 --- a/src/core/math/Matrix.js +++ b/src/core/math/Matrix.js @@ -10,7 +10,8 @@ * @class * @namespace PIXI */ -function Matrix() { +function Matrix() +{ /** * @member {number} * @default 1 @@ -63,7 +64,8 @@ * * @param array {number[]} The array that the matrix will be populated from. */ -Matrix.prototype.fromArray = function (array) { +Matrix.prototype.fromArray = function (array) +{ this.a = array[0]; this.b = array[1]; this.c = array[3]; @@ -78,14 +80,17 @@ * @param transpose {boolean} Whether we need to transpose the matrix or not * @return {number[]} the newly created array which contains the matrix */ -Matrix.prototype.toArray = function (transpose) { - if (!this.array) { +Matrix.prototype.toArray = function (transpose) +{ + if (!this.array) + { this.array = new Float32Array(9); } var array = this.array; - if (transpose) { + if (transpose) + { array[0] = this.a; array[1] = this.b; array[2] = 0; @@ -96,7 +101,8 @@ array[7] = this.ty; array[8] = 1; } - else { + else + { array[0] = this.a; array[1] = this.c; array[2] = this.tx; @@ -119,7 +125,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, transformed through this matrix */ -Matrix.prototype.apply = function (pos, newPos) { +Matrix.prototype.apply = function (pos, newPos) +{ newPos = newPos || new Point(); newPos.x = this.a * pos.x + this.c * pos.y + this.tx; @@ -136,7 +143,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, inverse-transformed through this matrix */ -Matrix.prototype.applyInverse = function (pos, newPos) { +Matrix.prototype.applyInverse = function (pos, newPos) +{ newPos = newPos || new Point(); var id = 1 / (this.a * this.d + this.c * -this.b); @@ -154,7 +162,8 @@ * @param {number} y * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.translate = function (x, y) { +Matrix.prototype.translate = function (x, y) +{ this.tx += x; this.ty += y; @@ -168,7 +177,8 @@ * @param {number} y The amount to scale vertically * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.scale = function (x, y) { +Matrix.prototype.scale = function (x, y) +{ this.a *= x; this.d *= y; this.c *= x; @@ -186,7 +196,8 @@ * @param {number} angle - The angle in radians. * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.rotate = function (angle) { +Matrix.prototype.rotate = function (angle) +{ var cos = Math.cos( angle ); var sin = Math.sin( angle ); @@ -210,7 +221,8 @@ * @param {Matrix} matrix * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.append = function (matrix) { +Matrix.prototype.append = function (matrix) +{ var a1 = this.a; var b1 = this.b; var c1 = this.c; @@ -232,7 +244,8 @@ * * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.identity = function () { +Matrix.prototype.identity = function () +{ this.a = 1; this.b = 0; this.c = 0; diff --git a/src/core/math/Point.js b/src/core/math/Point.js index 7565b2d..632f346 100644 --- a/src/core/math/Point.js +++ b/src/core/math/Point.js @@ -7,7 +7,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -function Point(x, y) { +function Point(x, y) +{ /** * @member {number} * @default 0 @@ -29,7 +30,8 @@ * * @return {Point} a copy of the point */ -Point.prototype.clone = function () { +Point.prototype.clone = function () +{ return new Point(this.x, this.y); }; @@ -40,7 +42,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -Point.prototype.set = function (x, y) { +Point.prototype.set = function (x, y) +{ this.x = x || 0; this.y = y || ( (y !== 0) ? this.x : 0 ) ; }; diff --git a/src/core/math/shapes/Circle.js b/src/core/math/shapes/Circle.js index 69cfdc9..4d76efc 100644 --- a/src/core/math/shapes/Circle.js +++ b/src/core/math/shapes/Circle.js @@ -10,7 +10,8 @@ * @param y {number} The Y coordinate of the center of this circle * @param radius {number} The radius of the circle */ -function Circle(x, y, radius) { +function Circle(x, y, radius) +{ /** * @member {number} * @default 0 @@ -46,7 +47,8 @@ * @method clone * @return {Circle} a copy of the Circle */ -Circle.prototype.clone = function () { +Circle.prototype.clone = function () +{ return new Circle(this.x, this.y, this.radius); }; @@ -58,8 +60,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Circle */ -Circle.prototype.contains = function (x, y) { - if (this.radius <= 0) { +Circle.prototype.contains = function (x, y) +{ + if (this.radius <= 0) + { return false; } @@ -79,6 +83,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Circle.prototype.getBounds = function () { +Circle.prototype.getBounds = function () +{ return new Rectangle(this.x - this.radius, this.y - this.radius, this.radius * 2, this.radius * 2); }; diff --git a/src/core/math/shapes/Ellipse.js b/src/core/math/shapes/Ellipse.js index 4f2d066..fefd01a 100644 --- a/src/core/math/shapes/Ellipse.js +++ b/src/core/math/shapes/Ellipse.js @@ -11,7 +11,8 @@ * @param width {number} The half width of this ellipse * @param height {number} The half height of this ellipse */ -function Ellipse(x, y, width, height) { +function Ellipse(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -53,7 +54,8 @@ * @method clone * @return {Ellipse} a copy of the ellipse */ -Ellipse.prototype.clone = function () { +Ellipse.prototype.clone = function () +{ return new Ellipse(this.x, this.y, this.width, this.height); }; @@ -65,8 +67,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coords are within this ellipse */ -Ellipse.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Ellipse.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } @@ -86,6 +90,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Ellipse.prototype.getBounds = function () { +Ellipse.prototype.getBounds = function () +{ return new Rectangle(this.x - this.width, this.y - this.height, this.width, this.height); }; diff --git a/src/core/math/shapes/Polygon.js b/src/core/math/shapes/Polygon.js index ae89148..fea6d37 100644 --- a/src/core/math/shapes/Polygon.js +++ b/src/core/math/shapes/Polygon.js @@ -10,16 +10,20 @@ * arguments passed can be flat x,y values e.g. `new Polygon(x,y, x,y, x,y, ...)` where `x` and `y` are * Numbers. */ -function Polygon(points) { +function Polygon(points) +{ //if points isn't an array, use arguments as the array - if (!(points instanceof Array)) { + if (!(points instanceof Array)) + { points = Array.prototype.slice.call(arguments); } //if this is a flat array of numbers, convert it to points - if (points[0] instanceof Point) { + if (points[0] instanceof Point) + { var p = []; - for (var i = 0, il = points.length; i < il; i++) { + for (var i = 0, il = points.length; i < il; i++) + { p.push(points[i].x, points[i].y); } @@ -51,7 +55,8 @@ * * @return {Polygon} a copy of the polygon */ -Polygon.prototype.clone = function () { +Polygon.prototype.clone = function () +{ return new Polygon(this.points.slice()); }; @@ -62,19 +67,22 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this polygon */ -Polygon.prototype.contains = function (x, y) { +Polygon.prototype.contains = function (x, y) +{ var inside = false; // use some raycasting to test hits // https://github.com/substack/point-in-polygon/blob/master/index.js var length = this.points.length / 2; - for (var i = 0, j = length - 1; i < length; j = i++) { + for (var i = 0, j = length - 1; i < length; j = i++) + { var xi = this.points[i * 2], yi = this.points[i * 2 + 1], xj = this.points[j * 2], yj = this.points[j * 2 + 1], intersect = ((yi > y) !== (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi); - if (intersect) { + if (intersect) + { inside = !inside; } } diff --git a/src/core/math/shapes/Rectangle.js b/src/core/math/shapes/Rectangle.js index 16ac62a..4008b68 100644 --- a/src/core/math/shapes/Rectangle.js +++ b/src/core/math/shapes/Rectangle.js @@ -10,7 +10,8 @@ * @param width {number} The overall width of this rectangle * @param height {number} The overall height of this rectangle */ -function Rectangle(x, y, width, height) { +function Rectangle(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -60,7 +61,8 @@ * * @return {Rectangle} a copy of the rectangle */ -Rectangle.prototype.clone = function () { +Rectangle.prototype.clone = function () +{ return new Rectangle(this.x, this.y, this.width, this.height); }; @@ -71,13 +73,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rectangle */ -Rectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Rectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/math/shapes/RoundedRectangle.js b/src/core/math/shapes/RoundedRectangle.js index 27d286e..7bf6411 100644 --- a/src/core/math/shapes/RoundedRectangle.js +++ b/src/core/math/shapes/RoundedRectangle.js @@ -11,7 +11,8 @@ * @param height {number} The overall height of this rounded rectangle * @param radius {number} Controls the radius of the rounded corners */ -function RoundedRectangle(x, y, width, height, radius) { +function RoundedRectangle(x, y, width, height, radius) +{ /** * @member {number} * @default 0 @@ -58,7 +59,8 @@ * * @return {RoundedRectangle} a copy of the rounded rectangle */ -RoundedRectangle.prototype.clone = function () { +RoundedRectangle.prototype.clone = function () +{ return new RoundedRectangle(this.x, this.y, this.width, this.height, this.radius); }; @@ -69,13 +71,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rounded Rectangle */ -RoundedRectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +RoundedRectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/primitives/Graphics.js b/src/core/primitives/Graphics.js index 261c534..e902d2a 100644 --- a/src/core/primitives/Graphics.js +++ b/src/core/primitives/Graphics.js @@ -16,7 +16,8 @@ * @extends DisplayObjectContainer * @namespace PIXI */ -function Graphics() { +function Graphics() +{ DisplayObjectContainer.call(this); this.renderable = true; @@ -154,16 +155,20 @@ * @private */ cacheAsBitmap: { - get: function () { + get: function () + { return this._cacheAsBitmap; }, - set: function (value) { + set: function (value) + { this._cacheAsBitmap = value; - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._generateCachedSprite(); } - else { + else + { this.destroyCachedSprite(); this.dirty = true; } @@ -176,7 +181,8 @@ * * @return {Graphics} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ var clone = new Graphics(); clone.renderable = this.renderable; @@ -192,7 +198,8 @@ clone.cachedSpriteDirty = this.cachedSpriteDirty; // copy graphics data - for (var i = 0; i < this.graphicsData.length; ++i) { + for (var i = 0; i < this.graphicsData.length; ++i) + { clone.graphicsData.push(this.graphicsData.clone()); } @@ -211,17 +218,21 @@ * @param alpha {number} alpha of the line to draw, will update the objects stored style * @return {Graphics} */ -Graphics.prototype.lineStyle = function (lineWidth, color, alpha) { +Graphics.prototype.lineStyle = function (lineWidth, color, alpha) +{ this.lineWidth = lineWidth || 0; this.lineColor = color || 0; this.lineAlpha = (arguments.length < 3) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length) + { // halfway through a line? start a new one! this.drawShape( new math.Polygon( this.currentPath.shape.points.slice(-2) )); } - else { + else + { // otherwise its empty so lets just set the line properties this.currentPath.lineWidth = this.lineWidth; this.currentPath.lineColor = this.lineColor; @@ -239,7 +250,8 @@ * @param y {number} the Y coordinate to move to * @return {Graphics} */ -Graphics.prototype.moveTo = function (x, y) { +Graphics.prototype.moveTo = function (x, y) +{ this.drawShape(new math.Polygon([x,y])); return this; @@ -253,7 +265,8 @@ * @param y {number} the Y coordinate to draw to * @return {Graphics} */ -Graphics.prototype.lineTo = function (x, y) { +Graphics.prototype.lineTo = function (x, y) +{ this.currentPath.shape.points.push(x, y); this.dirty = true; @@ -270,13 +283,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -285,7 +302,8 @@ n = 20, points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { this.moveTo(0, 0); } @@ -293,7 +311,8 @@ var fromY = points[points.length-1]; var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; xa = fromX + ( (cpX - fromX) * j ); @@ -319,13 +338,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -342,7 +365,8 @@ var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; dt = (1 - j); @@ -373,13 +397,17 @@ * @param radius {number} The radius of the arc * @return {Graphics} */ -Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points.push(x1, y1); } } - else { + else + { this.moveTo(x1, y1); } @@ -392,12 +420,15 @@ b2 = x2 - x1, mm = Math.abs(a1 * b2 - b1 * a2); - if (mm < 1.0e-8 || radius === 0) { - if (points[points.length-2] !== x1 || points[points.length-1] !== y1) { + if (mm < 1.0e-8 || radius === 0) + { + if (points[points.length-2] !== x1 || points[points.length-1] !== y1) + { points.push(x1, y1); } } - else { + else + { var dd = a1 * a1 + b1 * b1, cc = a2 * a2 + b2 * b2, tt = a1 * a2 + b1 * b2, @@ -433,42 +464,51 @@ * @param anticlockwise {boolean} Optional. Specifies whether the drawing should be counterclockwise or clockwise. False is default, and indicates clockwise, while true indicates counter-clockwise. * @return {Graphics} */ -Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) { +Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) +{ var startX = cx + Math.cos(startAngle) * radius; var startY = cy + Math.sin(startAngle) * radius; var points; // TODO - This if-else makes no sense. It uses currentPath in the else where it doesn't exist... - if (this.currentPath) { + if (this.currentPath) + { points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { points.push(startX, startY); } - else if (points[points.length-2] !== startX || points[points.length-1] !== startY) { + else if (points[points.length-2] !== startX || points[points.length-1] !== startY) + { points.push(startX, startY); } } - else { + else + { this.moveTo(startX, startY); points = this.currentPath.shape.points; } - if (startAngle === endAngle) { + if (startAngle === endAngle) + { return this; } - if (!anticlockwise && endAngle <= startAngle) { + if (!anticlockwise && endAngle <= startAngle) + { endAngle += Math.PI * 2; } - else if (anticlockwise && startAngle <= endAngle) { + else if (anticlockwise && startAngle <= endAngle) + { startAngle += Math.PI * 2; } var sweep = anticlockwise ? (startAngle - endAngle) *-1 : (endAngle - startAngle); var segs = (Math.abs(sweep)/ (Math.PI * 2)) * 40; - if (sweep === 0) { + if (sweep === 0) + { return this; } @@ -482,7 +522,8 @@ var remainder = ( segMinus % 1 ) / segMinus; - for (var i = 0; i <= segMinus; ++i) { + for (var i = 0; i <= segMinus; ++i) + { var real = i + remainder * i; var angle = ((theta) + startAngle + (theta2 * real)); @@ -506,13 +547,16 @@ * @param alpha {number} the alpha of the fill * @return {Graphics} */ -Graphics.prototype.beginFill = function (color, alpha) { +Graphics.prototype.beginFill = function (color, alpha) +{ this.filling = true; this.fillColor = color || 0; this.fillAlpha = (alpha === undefined) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length <= 2) + { this.currentPath.fill = this.filling; this.currentPath.fillColor = this.fillColor; this.currentPath.fillAlpha = this.fillAlpha; @@ -526,7 +570,8 @@ * * @return {Graphics} */ -Graphics.prototype.endFill = function () { +Graphics.prototype.endFill = function () +{ this.filling = false; this.fillColor = null; this.fillAlpha = 1; @@ -542,7 +587,8 @@ * @param height {number} The height of the rectangle * @return {Graphics} */ -Graphics.prototype.drawRect = function ( x, y, width, height ) { +Graphics.prototype.drawRect = function ( x, y, width, height ) +{ this.drawShape(new math.Rectangle(x,y, width, height)); return this; @@ -556,7 +602,8 @@ * @param height {number} The height of the rectangle * @param radius {number} Radius of the rectangle corners */ -Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) { +Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) +{ this.drawShape(new math.RoundedRectangle(x, y, width, height, radius)); return this; @@ -570,7 +617,8 @@ * @param radius {number} The radius of the circle * @return {Graphics} */ -Graphics.prototype.drawCircle = function (x, y, radius) { +Graphics.prototype.drawCircle = function (x, y, radius) +{ this.drawShape(new math.Circle(x,y, radius)); return this; @@ -585,7 +633,8 @@ * @param height {number} The half height of the ellipse * @return {Graphics} */ -Graphics.prototype.drawEllipse = function (x, y, width, height) { +Graphics.prototype.drawEllipse = function (x, y, width, height) +{ this.drawShape(new math.Ellipse(x, y, width, height)); return this; @@ -597,8 +646,10 @@ * @param path {Array} The path data used to construct the polygon. * @return {Graphics} */ -Graphics.prototype.drawPolygon = function (path) { - if (!(path instanceof Array)) { +Graphics.prototype.drawPolygon = function (path) +{ + if (!(path instanceof Array)) + { path = Array.prototype.slice.call(arguments); } @@ -612,7 +663,8 @@ * * @return {Graphics} */ -Graphics.prototype.clear = function () { +Graphics.prototype.clear = function () +{ this.lineWidth = 0; this.filling = false; @@ -631,7 +683,8 @@ * @param scaleMode {number} Should be one of the scaleMode consts * @return {Texture} a texture of the graphics object */ -Graphics.prototype.generateTexture = function (resolution, scaleMode) { +Graphics.prototype.generateTexture = function (resolution, scaleMode) +{ resolution = resolution || 1; var bounds = this.getBounds(); @@ -655,17 +708,21 @@ * * @param renderer {WebGLRenderer} */ -Graphics.prototype._renderWebGL = function (renderer) { +Graphics.prototype._renderWebGL = function (renderer) +{ // if the sprite is not visible or the alpha is 0 then no need to render this element - if (this.isMask === true) { + if (this.isMask === true) + { return; } // this code may still be needed so leaving for now.. - // + // /* - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture on the gpu too! @@ -681,17 +738,24 @@ return; } - */ - - // check if the webgl graphic needs to be updated - if (this.glDirty) { - this.dirty = true; - this.glDirty = false; - } + else */ - renderer.setObjectRendererer(renderer.graphicsRenderer); - renderer.graphicsRenderer.render(this); + renderer.spriteBatch.stop(); + renderer.blendModeManager.setBlendMode(this.blendMode); + // check blend mode + renderer.blendModeManager.setBlendMode( this.blendMode ); + + // check if the webgl graphic needs to be updated + if (this.glDirty) + { + this.dirty = true; + this.glDirty = false; + } + + WebGLGraphics.renderGraphics(this, renderer); + + renderer.spriteBatch.start(); }; /** @@ -700,14 +764,18 @@ * @param renderer {CanvasRenderer} * @private */ -Graphics.prototype.renderCanvas = function (renderer) { +Graphics.prototype.renderCanvas = function (renderer) +{ // 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.isMask === true) { + if (!this.visible || this.alpha <= 0 || this.isMask === true) + { return; } - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture @@ -723,16 +791,19 @@ return; } - else { + else + { var context = renderer.context; var transform = this.worldTransform; - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } @@ -748,11 +819,13 @@ CanvasGraphics.renderGraphics(this, context); - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } } @@ -763,13 +836,16 @@ * * @return {Rectangle} the rectangular bounding area */ -Graphics.prototype.getBounds = function (matrix) { +Graphics.prototype.getBounds = function (matrix) +{ // return an empty object if the item is a mask! - if (this.isMask) { + if (this.isMask) + { return math.Rectangle.EMPTY; } - if (this.dirty) { + if (this.dirty) + { this.updateLocalBounds(); this.glDirty = true; @@ -841,23 +917,27 @@ * Update the bounds of the object * */ -Graphics.prototype.updateLocalBounds = function () { +Graphics.prototype.updateLocalBounds = function () +{ var minX = Infinity; var maxX = -Infinity; var minY = Infinity; var maxY = -Infinity; - if (this.graphicsData.length) { + if (this.graphicsData.length) + { var shape, points, x, y, w, h; - for (var i = 0; i < this.graphicsData.length; i++) { + for (var i = 0; i < this.graphicsData.length; i++) + { var data = this.graphicsData[i]; var type = data.type; var lineWidth = data.lineWidth; shape = data.shape; - if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) { + if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) + { x = shape.x - lineWidth/2; y = shape.y - lineWidth/2; w = shape.width + lineWidth; @@ -869,7 +949,8 @@ minY = y < minY ? y : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.CIRC) { + else if (type === CONST.SHAPES.CIRC) + { x = shape.x; y = shape.y; w = shape.radius + lineWidth/2; @@ -881,7 +962,8 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.ELIP) { + else if (type === CONST.SHAPES.ELIP) + { x = shape.x; y = shape.y; w = shape.width + lineWidth/2; @@ -893,11 +975,13 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else { + else + { // POLY points = shape.points; - for (var j = 0; j < points.length; j += 2) { + for (var j = 0; j < points.length; j += 2) + { x = points[j]; y = points[j+1]; @@ -910,7 +994,8 @@ } } } - else { + else + { minX = 0; maxX = 0; minY = 0; @@ -931,10 +1016,12 @@ * * @private */ -Graphics.prototype._generateCachedSprite = function () { +Graphics.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { var canvasBuffer = new CanvasBuffer(bounds.width, bounds.height); var texture = Texture.fromCanvas(canvasBuffer.canvas); @@ -943,7 +1030,8 @@ this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.buffer.resize(bounds.width, bounds.height); } @@ -968,7 +1056,8 @@ * * @private */ -Graphics.prototype.updateCachedSpriteTexture = function () { +Graphics.prototype.updateCachedSpriteTexture = function () +{ var cachedSprite = this._cachedSprite; var texture = cachedSprite.texture; var canvas = cachedSprite.buffer.canvas; @@ -989,7 +1078,8 @@ * Destroys a previous cached sprite. * */ -Graphics.prototype.destroyCachedSprite = function () { +Graphics.prototype.destroyCachedSprite = function () +{ this._cachedSprite.texture.destroy(true); // let the gc collect the unused sprite @@ -1003,10 +1093,13 @@ * @param {Circle|Rectangle|Ellipse|Line|Polygon} shape The Shape object to draw. * @return {GraphicsData} The generated GraphicsData object. */ -Graphics.prototype.drawShape = function (shape) { - if (this.currentPath) { +Graphics.prototype.drawShape = function (shape) +{ + if (this.currentPath) + { // check current path! - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath.shape.points.length <= 2) + { this.graphicsData.pop(); } } @@ -1017,7 +1110,8 @@ this.graphicsData.push(data); - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { data.shape.closed = this.filling; this.currentPath = data; } diff --git a/src/core/primitives/GraphicsData.js b/src/core/primitives/GraphicsData.js index 99decbe..788f6f2 100644 --- a/src/core/primitives/GraphicsData.js +++ b/src/core/primitives/GraphicsData.js @@ -4,7 +4,8 @@ * @class * @namespace PIXI */ -function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) { +function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) +{ this.lineWidth = lineWidth; this.lineColor = lineColor; this.lineAlpha = lineAlpha; @@ -27,7 +28,8 @@ * * @return {GraphicsData} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ return new GraphicsData( this.lineWidth, this.lineColor, diff --git a/src/core/renderers/canvas/CanvasRenderer.js b/src/core/renderers/canvas/CanvasRenderer.js index 15a0978..7aebd44 100644 --- a/src/core/renderers/canvas/CanvasRenderer.js +++ b/src/core/renderers/canvas/CanvasRenderer.js @@ -17,17 +17,22 @@ * @param [options.resolution=1] {number} the resolution of the renderer retina would be 2 * @param [options.clearBeforeRender=true] {boolean} This sets if the CanvasRenderer will clear the canvas or not before the new render pass. */ -function CanvasRenderer(width, height, options) { +function CanvasRenderer(width, height, options) +{ utils.sayHello('Canvas'); - if (options) { - for (var i in CONST.defaultRenderOptions) { - if (typeof options[i] === 'undefined') { + if (options) + { + for (var i in CONST.defaultRenderOptions) + { + if (typeof options[i] === 'undefined') + { options[i] = CONST.defaultRenderOptions[i]; } } } - else { + else + { options = CONST.defaultRenderOptions; } @@ -156,19 +161,24 @@ this.smoothProperty = null; - if (this.context.imageSmoothingEnabled) { + if (this.context.imageSmoothingEnabled) + { this.smoothProperty = 'imageSmoothingEnabled'; } - else if (this.context.webkitImageSmoothingEnabled) { + else if (this.context.webkitImageSmoothingEnabled) + { this.smoothProperty = 'webkitImageSmoothingEnabled'; } - else if (this.context.mozImageSmoothingEnabled) { + else if (this.context.mozImageSmoothingEnabled) + { this.smoothProperty = 'mozImageSmoothingEnabled'; } - else if (this.context.oImageSmoothingEnabled) { + else if (this.context.oImageSmoothingEnabled) + { this.smoothProperty = 'oImageSmoothingEnabled'; } - else if (this.context.msImageSmoothingEnabled) { + else if (this.context.msImageSmoothingEnabled) + { this.smoothProperty = 'msImageSmoothingEnabled'; } @@ -193,10 +203,12 @@ * @memberof CanvasRenderer# */ backgroundColor: { - get: function () { + get: function () + { return this._backgroundColor; }, - set: function (val) { + set: function (val) + { this._backgroundColor = val; this._backgroundColorString = utils.hex2string(val); } @@ -208,7 +220,8 @@ * * @param object {DisplayObject} the object to be rendered */ -CanvasRenderer.prototype.render = function (object) { +CanvasRenderer.prototype.render = function (object) +{ object.updateTransform(); this.context.setTransform(1,0,0,1,0,0); @@ -218,16 +231,20 @@ this.currentBlendMode = CONST.blendModes.NORMAL; this.context.globalCompositeOperation = this.blendModes[CONST.blendModes.NORMAL]; - if (navigator.isCocoonJS && this.view.screencanvas) { + if (navigator.isCocoonJS && this.view.screencanvas) + { this.context.fillStyle = 'black'; this.context.clear(); } - if (this.clearBeforeRender) { - if (this.transparent) { + if (this.clearBeforeRender) + { + if (this.transparent) + { this.context.clearRect(0, 0, this.width, this.height); } - else { + else + { this.context.fillStyle = this._backgroundColorString; this.context.fillRect(0, 0, this.width , this.height); } @@ -241,8 +258,10 @@ * * @param [removeView=false] {boolean} Removes the Canvas element from the DOM. */ -CanvasRenderer.prototype.destroy = function (removeView) { - if (removeView && this.view.parent) { +CanvasRenderer.prototype.destroy = function (removeView) +{ + if (removeView && this.view.parent) + { this.view.parent.removeChild(this.view); } @@ -257,14 +276,16 @@ * @param width {number} the new width of the canvas view * @param height {number} the new height of the canvas view */ -CanvasRenderer.prototype.resize = function (width, height) { +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) { + if (this.autoResize) + { this.view.style.width = this.width / this.resolution + 'px'; this.view.style.height = this.height / this.resolution + 'px'; } @@ -276,7 +297,8 @@ * @param displayObject {DisplayObject} The displayObject to render * @private */ -CanvasRenderer.prototype.renderDisplayObject = function (displayObject) { +CanvasRenderer.prototype.renderDisplayObject = function (displayObject) +{ displayObject.renderCanvas(this); }; @@ -285,11 +307,14 @@ * * @private */ -CanvasRenderer.prototype._mapBlendModes = function () { - if (!this.blendModes) { +CanvasRenderer.prototype._mapBlendModes = function () +{ + if (!this.blendModes) + { this.blendModes = {}; - if (utils.canUseNewCanvasBlendModes()) { + if (utils.canUseNewCanvasBlendModes()) + { this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? this.blendModes[CONST.blendModes.MULTIPLY] = 'multiply'; @@ -308,7 +333,8 @@ this.blendModes[CONST.blendModes.COLOR] = 'color'; this.blendModes[CONST.blendModes.LUMINOSITY] = 'luminosity'; } - else { + else + { // this means that the browser does not support the cool new blend modes in canvas 'cough' ie 'cough' this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? diff --git a/src/core/display/DisplayObject.js b/src/core/display/DisplayObject.js index 66ebc3c..20e778c 100644 --- a/src/core/display/DisplayObject.js +++ b/src/core/display/DisplayObject.js @@ -7,7 +7,8 @@ * @class * @namespace PIXI */ -function DisplayObject() { +function DisplayObject() +{ /** * The coordinate of the object relative to the local coordinates of the parent. * @@ -152,10 +153,12 @@ * @memberof DisplayObject# */ x: { - get: function () { + get: function () + { return this.position.x; }, - set: function (value) { + set: function (value) + { this.position.x = value; } }, @@ -167,10 +170,12 @@ * @memberof DisplayObject# */ y: { - get: function () { + get: function () + { return this.position.y; }, - set: function (value) { + set: function (value) + { this.position.y = value; } }, @@ -183,11 +188,13 @@ * @readonly */ worldVisible: { - get: function () { + get: function () + { var item = this; do { - if (!item.visible) { + if (!item.visible) + { return false; } @@ -207,17 +214,21 @@ * @memberof DisplayObject# */ mask: { - get: function () { + get: function () + { return this._mask; }, - set: function (value) { - if (this._mask) { + set: function (value) + { + if (this._mask) + { this._mask.isMask = false; } this._mask = value; - if (this._mask) { + if (this._mask) + { this._mask.isMask = true; } } @@ -232,18 +243,23 @@ * @memberof DisplayObject# */ filters: { - get: function () { + get: function () + { return this._filters; }, - set: function (value) { - if (value) { + set: function (value) + { + if (value) + { // now put all the passes in one place.. var passes = []; - for (var i = 0; i < value.length; i++) { + for (var i = 0; i < value.length; i++) + { var filterPasses = value[i].passes; - for (var j = 0; j < filterPasses.length; j++) { + for (var j = 0; j < filterPasses.length; j++) + { passes.push(filterPasses[j]); } } @@ -264,8 +280,9 @@ * * @private */ -DisplayObject.prototype.updateTransform = function () { - +DisplayObject.prototype.updateTransform = function () +{ + // create some matrix refs for easy access var pt = this.parent.worldTransform; var wt = this.worldTransform; @@ -274,9 +291,11 @@ var a, b, c, d, tx, ty; // so if rotation is between 0 then we can simplify the multiplication process.. - if (this.rotation % math.PI_2) { + if (this.rotation % math.PI_2) + { // 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) { + if (this.rotation !== this.rotationCache) + { this.rotationCache = this.rotation; this._sr = Math.sin(this.rotation); this._cr = Math.cos(this.rotation); @@ -291,7 +310,8 @@ ty = this.position.y; // check for pivot.. not often used so geared towards that fact! - if (this.pivot.x || this.pivot.y) { + 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; } @@ -304,7 +324,8 @@ wt.tx = tx * pt.a + ty * pt.c + pt.tx; wt.ty = tx * pt.b + ty * pt.d + pt.ty; } - else { + else + { // lets do the fast version as we know there is no rotation.. a = this.scale.x; d = this.scale.y; @@ -333,7 +354,8 @@ * @param matrix {Matrix} * @return {Rectangle} the rectangular bounding area */ -DisplayObject.prototype.getBounds = function (/* matrix */) { +DisplayObject.prototype.getBounds = function (/* matrix */) +{ return math.Rectangle.EMPTY; }; @@ -342,7 +364,8 @@ * * @return {Rectangle} the rectangular bounding area */ -DisplayObject.prototype.getLocalBounds = function () { +DisplayObject.prototype.getLocalBounds = function () +{ return this.getBounds(math.Matrix.IDENTITY); }; @@ -352,7 +375,8 @@ * @param position {Point} The world origin to calculate from * @return {Point} A point object representing the position of this object */ -DisplayObject.prototype.toGlobal = function (position) { +DisplayObject.prototype.toGlobal = function (position) +{ // don't need to u[date the lot this.displayObjectUpdateTransform(); return this.worldTransform.apply(position); @@ -365,8 +389,10 @@ * @param [from] {DisplayObject} The DisplayObject to calculate the global position from * @return {Point} A point object representing the position of this object */ -DisplayObject.prototype.toLocal = function (position, from) { - if (from) { +DisplayObject.prototype.toLocal = function (position, from) +{ + if (from) + { position = from.toGlobal(position); } @@ -381,7 +407,8 @@ * @param renderer {WebGLRenderer} The renderer * @private */ -DisplayObject.prototype.renderWebGL = function (/* renderer */) { +DisplayObject.prototype.renderWebGL = function (/* renderer */) +{ // OVERWRITE; }; @@ -391,6 +418,7 @@ * @param renderer {CanvasRenderer} The renderer * @private */ -DisplayObject.prototype.renderCanvas = function (/* renderer */) { +DisplayObject.prototype.renderCanvas = function (/* renderer */) +{ // OVERWRITE; }; diff --git a/src/core/display/DisplayObjectContainer.js b/src/core/display/DisplayObjectContainer.js index 689f40b..4625ee8 100644 --- a/src/core/display/DisplayObjectContainer.js +++ b/src/core/display/DisplayObjectContainer.js @@ -12,7 +12,8 @@ * @extends DisplayObject * @namespace PIXI */ -function DisplayObjectContainer() { +function DisplayObjectContainer() +{ DisplayObject.call(this); /** @@ -47,17 +48,21 @@ * @memberof DisplayObjectContainer# */ width: { - get: function () { + get: function () + { return this.scale.x * this.getLocalBounds().width; }, - set: function (value) { + set: function (value) + { var width = this.getLocalBounds().width; - if(width !== 0) { + if(width !== 0) + { this.scale.x = value / width; } - else { + else + { this.scale.x = 1; } @@ -73,17 +78,21 @@ * @memberof DisplayObjectContainer# */ height: { - get: function () { + get: function () + { return this.scale.y * this.getLocalBounds().height; }, - set: function (value) { + set: function (value) + { var height = this.getLocalBounds().height; - if (height !== 0) { + if (height !== 0) + { this.scale.y = value / height ; } - else { + else + { this.scale.y = 1; } @@ -100,18 +109,23 @@ * @memberof DisplayObject# */ cacheAsBitmap: { - get: function () { + get: function () + { return this._cacheAsBitmap; }, - set: function (value) { - if (this._cacheAsBitmap === value) { + set: function (value) + { + if (this._cacheAsBitmap === value) + { return; } - if (value) { + if (value) + { this._generateCachedSprite(); } - else { + else + { this._destroyCachedSprite(); } @@ -126,7 +140,8 @@ * @param child {DisplayObject} The DisplayObject to add to the container * @return {DisplayObject} The child that was added. */ -DisplayObjectContainer.prototype.addChild = function (child) { +DisplayObjectContainer.prototype.addChild = function (child) +{ return this.addChildAt(child, this.children.length); }; @@ -137,14 +152,18 @@ * @param index {Number} The index to place the child in * @return {DisplayObject} The child that was added. */ -DisplayObjectContainer.prototype.addChildAt = function (child, index) { +DisplayObjectContainer.prototype.addChildAt = function (child, index) +{ // prevent adding self as child - if (child === this) { + if (child === this) + { return; } - if (index >= 0 && index <= this.children.length) { - if (child.parent) { + if (index >= 0 && index <= this.children.length) + { + if (child.parent) + { child.parent.removeChild(child); } @@ -154,7 +173,8 @@ return child; } - else { + else + { throw new Error(child + 'addChildAt: The index '+ index +' supplied is out of bounds ' + this.children.length); } }; @@ -165,15 +185,18 @@ * @param child {DisplayObject} * @param child2 {DisplayObject} */ -DisplayObjectContainer.prototype.swapChildren = function (child, child2) { - if (child === child2) { +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) { + if (index1 < 0 || index2 < 0) + { throw new Error('swapChildren: Both the supplied DisplayObjects must be a child of the caller.'); } @@ -187,10 +210,12 @@ * @param child {DisplayObject} The DisplayObject instance to identify * @return {Number} The index position of the child display object to identify */ -DisplayObjectContainer.prototype.getChildIndex = function (child) { +DisplayObjectContainer.prototype.getChildIndex = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { throw new Error('The supplied DisplayObject must be a child of the caller'); } @@ -203,8 +228,10 @@ * @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 */ -DisplayObjectContainer.prototype.setChildIndex = function (child, index) { - if (index < 0 || index >= this.children.length) { +DisplayObjectContainer.prototype.setChildIndex = function (child, index) +{ + if (index < 0 || index >= this.children.length) + { throw new Error('The supplied index is out of bounds'); } @@ -220,8 +247,10 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child at the given index, if any. */ -DisplayObjectContainer.prototype.getChildAt = function (index) { - if (index < 0 || index >= this.children.length) { +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'); } @@ -234,10 +263,12 @@ * @param child {DisplayObject} The DisplayObject to remove * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChild = function (child) { +DisplayObjectContainer.prototype.removeChild = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { return; } @@ -250,7 +281,8 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChildAt = function (index) { +DisplayObjectContainer.prototype.removeChildAt = function (index) +{ var child = this.getChildAt(index); child.parent = null; @@ -265,24 +297,29 @@ * @param beginIndex {Number} The beginning position. Default value is 0. * @param endIndex {Number} The ending position. Default value is size of the container. */ -DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) { +DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) +{ var begin = beginIndex || 0; var end = typeof endIndex === 'number' ? endIndex : this.children.length; var range = end - begin; - if (range > 0 && range <= end) { + if (range > 0 && range <= end) + { var removed = this.children.splice(begin, range); - for (var i = 0; i < removed.length; ++i) { + for (var i = 0; i < removed.length; ++i) + { removed[i].parent = null; } return removed; } - else if (range === 0 && this.children.length === 0) { + else if (range === 0 && this.children.length === 0) + { return []; } - else { + else + { throw new RangeError('removeChildren: numeric values are outside the acceptable range.'); } }; @@ -291,7 +328,8 @@ * Generates and updates the cached sprite for this object. * */ -DisplayObjectContainer.prototype.updateCachedSprite = function () { +DisplayObjectContainer.prototype.updateCachedSprite = function () +{ this._generateCachedSprite(); }; @@ -304,7 +342,8 @@ * @param renderer {CanvasRenderer|WebGLRenderer} The renderer used to generate the texture. * @return {Texture} a texture of the graphics object */ -DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) { +DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) +{ var bounds = this.getLocalBounds(); var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0, renderer, scaleMode, resolution); @@ -322,18 +361,22 @@ * * @private */ -DisplayObjectContainer.prototype.updateTransform = function () { - if (!this.visible) { +DisplayObjectContainer.prototype.updateTransform = function () +{ + if (!this.visible) + { return; } this.displayObjectUpdateTransform(); - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { return; } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } }; @@ -346,8 +389,10 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getBounds = function () { - if (this.children.length === 0) { +DisplayObjectContainer.prototype.getBounds = function () +{ + if (this.children.length === 0) + { return math.Rectangle.EMPTY; } @@ -365,10 +410,12 @@ var childVisible = false; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -386,7 +433,8 @@ maxY = maxY > childMaxY ? maxY : childMaxY; } - if (!childVisible) { + if (!childVisible) + { return math.Rectangle.EMPTY; } @@ -407,12 +455,14 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getLocalBounds = function () { +DisplayObjectContainer.prototype.getLocalBounds = function () +{ var matrixCache = this.worldTransform; this.worldTransform = math.Matrix.IDENTITY; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } @@ -428,13 +478,16 @@ * * @param renderer {WebGLRenderer} The renderer */ -DisplayObjectContainer.prototype.renderWebGL = function (renderer) { +DisplayObjectContainer.prototype.renderWebGL = function (renderer) +{ // if the object is not visible or the alpha is 0 then no need to render this element - if (!this.visible || this.alpha <= 0) { + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } @@ -442,14 +495,17 @@ var i, j; // do a quick check to see if this element has a mask or a filter. - if (this._mask || this._filters) { + if (this._mask || this._filters) + { // push filter first as we need to ensure the stencil buffer is correct for any masking - if (this._filters) { + if (this._filters) + { renderer.spriteBatch.flush(); renderer.filterManager.pushFilter(this._filterBlock); } - if (this._mask) { + if (this._mask) + { renderer.spriteBatch.stop(); renderer.maskManager.pushMask(this.mask, renderer); renderer.spriteBatch.start(); @@ -459,36 +515,42 @@ this._renderWebGL(renderer); // now loop through the children and make sure they get rendered - for (i = 0, j = this.children.length; i < j; i++) { + for (i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderWebGL(renderer); } // time to stop the sprite batch as either a mask element or a filter draw will happen next renderer.spriteBatch.stop(); - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(this._mask, renderer); } - if (this._filters) { + if (this._filters) + { renderer.filterManager.popFilter(); } renderer.spriteBatch.start(); } - else { + else + { this._renderWebGL(renderer); // simple render children! - for (i = 0, j = this.children.length; i < j; ++i) { + for (i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderWebGL(renderer); } } }; -DisplayObjectContainer.prototype._renderWebGL = function (renderer) { +DisplayObjectContainer.prototype._renderWebGL = function (renderer) +{ // this is where content itself gets renderd.. @@ -499,25 +561,31 @@ * * @param renderer {CanvasRenderer} The renderer */ -DisplayObjectContainer.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0) { +DisplayObjectContainer.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -528,13 +596,16 @@ * @param renderer {WebGLRenderer|CanvasRenderer} The renderer * @private */ -DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) { +DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) +{ this._cachedSprite.worldAlpha = this.worldAlpha; - if (renderer.gl) { + if (renderer.gl) + { this._cachedSprite.renderWebGL(renderer); } - else { + else + { this._cachedSprite.renderCanvas(renderer); } }; @@ -544,10 +615,12 @@ * * @private */ -DisplayObjectContainer.prototype._generateCachedSprite = function () { +DisplayObjectContainer.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { // TODO - RenderTexture now *requires* a renderer instance, so this is like broken // because `renderer` isn't actually in scope here :P var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0); @@ -555,7 +628,8 @@ this._cachedSprite = new Sprite(renderTexture); this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.texture.resize(bounds.width | 0, bounds.height | 0); } @@ -580,8 +654,10 @@ * * @private */ -DisplayObjectContainer.prototype._destroyCachedSprite = function () { - if (!this._cachedSprite) { +DisplayObjectContainer.prototype._destroyCachedSprite = function () +{ + if (!this._cachedSprite) + { return; } diff --git a/src/core/display/Sprite.js b/src/core/display/Sprite.js index 707da24..5862aef 100644 --- a/src/core/display/Sprite.js +++ b/src/core/display/Sprite.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param texture {Texture} The texture for this sprite */ -function Sprite(texture) { +function Sprite(texture) +{ DisplayObjectContainer.call(this); /** @@ -85,12 +86,14 @@ this.texture = texture || Texture.EMPTY; } -Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) { +Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) +{ DisplayObjectContainer.prototype.destroy.call(this); this.anchor = null; - if (destroyTexture) { + if (destroyTexture) + { this._texture.destroy(destroyBaseTexture); } @@ -111,10 +114,12 @@ * @memberof Sprite# */ width: { - get: function () { + get: function () + { return this.scale.x * this.texture.frame.width; }, - set: function (value) { + set: function (value) + { this.scale.x = value / this.texture.frame.width; this._width = value; } @@ -127,10 +132,12 @@ * @memberof Sprite# */ height: { - get: function () { + get: function () + { return this.scale.y * this.texture.frame.height; }, - set: function (value) { + set: function (value) + { this.scale.y = value / this.texture.frame.height; this._height = value; } @@ -143,23 +150,29 @@ * @memberof Sprite# */ texture: { - get: function () { + get: function () + { return this._texture; }, - set: function (value) { - if (this._texture === value) { + set: function (value) + { + if (this._texture === value) + { return; } this._texture = value; this.cachedTint = 0xFFFFFF; - if (value) { + if (value) + { // wait for the texture to load - if (value.baseTexture.hasLoaded) { + if (value.baseTexture.hasLoaded) + { this._onTextureUpdate(); } - else { + else + { value.once('update', this._onTextureUpdate.bind(this)); } } @@ -172,18 +185,22 @@ * * @private */ -Sprite.prototype._onTextureUpdate = function () { +Sprite.prototype._onTextureUpdate = function () +{ // so if _width is 0 then width was not set.. - if (this._width) { + if (this._width) + { this.scale.x = this._width / this.texture.frame.width; } - if (this._height) { + if (this._height) + { this.scale.y = this._height / this.texture.frame.height; } }; -Sprite.prototype._renderWebGL = function (renderer) { +Sprite.prototype._renderWebGL = function (renderer) +{ // this is where content gets renderd.. // watch this space for a little render state manager.. @@ -197,7 +214,8 @@ * @param matrix {Matrix} the transformation matrix of the sprite * @return {Rectangle} the framing rectangle */ -Sprite.prototype.getBounds = function (matrix) { +Sprite.prototype.getBounds = function (matrix) +{ var width = this.texture.frame.width; var height = this.texture.frame.height; @@ -224,11 +242,13 @@ if(b === 0 && c === 0) { // scale may be negative! - if (a < 0) { + if (a < 0) + { a *= -1; } - if (d < 0) { + if (d < 0) + { d *= -1; } @@ -293,28 +313,34 @@ * * @param renderer {CanvasRenderer} The renderer */ -Sprite.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) { +Sprite.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) + { return; } - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; renderer.context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } // Ignore null sources - if (this.texture.valid) { + if (this.texture.valid) + { var resolution = this.texture.baseTexture.resolution / renderer.resolution; renderer.context.globalAlpha = this.worldAlpha; // If smoothingEnabled is supported and we need to change the smoothing property for this texture - if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) { + if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) + { renderer.scaleMode = this.texture.baseTexture.scaleMode; renderer.context[renderer.smoothProperty] = (renderer.scaleMode === CONST.scaleModes.LINEAR); } @@ -324,7 +350,8 @@ var dy = (this.texture.trim ? this.texture.trim.y : 0) - (this.anchor.y * this.texture.trim.height); // Allow for pixel rounding - if (renderer.roundPixels) { + if (renderer.roundPixels) + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -337,7 +364,8 @@ dx = dx | 0; dy = dy | 0; } - else { + else + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -348,8 +376,10 @@ ); } - if (this.tint !== 0xFFFFFF) { - if (this.cachedTint !== this.tint) { + if (this.tint !== 0xFFFFFF) + { + if (this.cachedTint !== this.tint) + { this.cachedTint = this.tint; // TODO clean up caching - how to clean up the caches? @@ -368,7 +398,8 @@ this.texture.crop.height / resolution ); } - else { + else + { renderer.context.drawImage( this.texture.baseTexture.source, this.texture.crop.x, @@ -383,11 +414,13 @@ } } - for (var i = 0, j = this.children.length; i < j; i++) { + for (var i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -402,10 +435,12 @@ * @param frameId {String} The frame Id of the texture in the cache * @return {Sprite} A new Sprite using a texture from the texture cache matching the frameId */ -Sprite.fromFrame = function (frameId) { +Sprite.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache' + this); } @@ -420,6 +455,7 @@ * @param imageId {String} The image url of the texture * @return {Sprite} A new Sprite using a texture from the texture cache matching the image id */ -Sprite.fromImage = function (imageId, crossorigin, scaleMode) { +Sprite.fromImage = function (imageId, crossorigin, scaleMode) +{ return new Sprite(Texture.fromImage(imageId, crossorigin, scaleMode)); }; diff --git a/src/core/display/SpriteBatch.js b/src/core/display/SpriteBatch.js index 3187777..c196fef 100644 --- a/src/core/display/SpriteBatch.js +++ b/src/core/display/SpriteBatch.js @@ -12,7 +12,8 @@ * ```js * var container = new SpriteBatch(); * - * for(var i = 0; i < 100; ++i) { + * for(var i = 0; i < 100; ++i) + * { * var sprite = new PIXI.Sprite.fromImage("myImage.png"); * container.addChild(sprite); * } @@ -25,7 +26,8 @@ */ //TODO RENAME to PARTICLE CONTAINER? -function SpriteBatch() { +function SpriteBatch() +{ DisplayObjectContainer.call(this); } @@ -38,7 +40,8 @@ * * @private */ -SpriteBatch.prototype.updateTransform = function () { +SpriteBatch.prototype.updateTransform = function () +{ // TODO don't need to! this.displayObjectUpdateTransform(); // PIXI.DisplayObjectContainer.prototype.updateTransform.call( this ); @@ -50,8 +53,10 @@ * @param renderer {WebGLRenderer} The webgl renderer * @private */ -SpriteBatch.prototype.renderWebGL = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderWebGL = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -71,8 +76,10 @@ * @param renderer {CanvasRenderer} The canvas renderer * @private */ -SpriteBatch.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -84,10 +91,12 @@ this.displayObjectUpdateTransform(); - for (var i = 0; i < this.children.length; ++i) { + for (var i = 0; i < this.children.length; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -95,9 +104,11 @@ context.globalAlpha = this.worldAlpha * child.alpha; - if (child.rotation % (Math.PI * 2) === 0) { + if (child.rotation % (Math.PI * 2) === 0) + { // this is the fastest way to optimise! - if rotation is 0 then we can avoid any kind of setTransform call - if (isRotated) { + if (isRotated) + { context.setTransform( transform.a, transform.b, @@ -122,8 +133,10 @@ frame.height * child.scale.y ); } - else { - if (!isRotated) { + else + { + if (!isRotated) + { isRotated = true; } @@ -131,7 +144,8 @@ var childTransform = child.worldTransform; - if (renderer.roundPixels) { + if (renderer.roundPixels) + { context.setTransform( childTransform.a, childTransform.b, @@ -141,7 +155,8 @@ childTransform.ty | 0 ); } - else { + else + { context.setTransform( childTransform.a, childTransform.b, diff --git a/src/core/index.js b/src/core/index.js index 3954b6f..eb4a82b 100644 --- a/src/core/index.js +++ b/src/core/index.js @@ -58,11 +58,13 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRenderer: function (width, height, options, noWebGL) { + autoDetectRenderer: function (width, height, options, noWebGL) + { width = width || 800; height = height || 600; - if (!noWebGL && require('webgl-enabled')()) { + if (!noWebGL && require('webgl-enabled')()) + { return new core.WebGLRenderer(width, height, options); } @@ -87,7 +89,8 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRecommendedRenderer: function (width, height, options) { + autoDetectRecommendedRenderer: function (width, height, options) + { var isAndroid = /Android/i.test(navigator.userAgent); return core.autoDetectRenderer(width, height, options, isAndroid); diff --git a/src/core/math/Matrix.js b/src/core/math/Matrix.js index c2f87e2..2ff4848 100644 --- a/src/core/math/Matrix.js +++ b/src/core/math/Matrix.js @@ -10,7 +10,8 @@ * @class * @namespace PIXI */ -function Matrix() { +function Matrix() +{ /** * @member {number} * @default 1 @@ -63,7 +64,8 @@ * * @param array {number[]} The array that the matrix will be populated from. */ -Matrix.prototype.fromArray = function (array) { +Matrix.prototype.fromArray = function (array) +{ this.a = array[0]; this.b = array[1]; this.c = array[3]; @@ -78,14 +80,17 @@ * @param transpose {boolean} Whether we need to transpose the matrix or not * @return {number[]} the newly created array which contains the matrix */ -Matrix.prototype.toArray = function (transpose) { - if (!this.array) { +Matrix.prototype.toArray = function (transpose) +{ + if (!this.array) + { this.array = new Float32Array(9); } var array = this.array; - if (transpose) { + if (transpose) + { array[0] = this.a; array[1] = this.b; array[2] = 0; @@ -96,7 +101,8 @@ array[7] = this.ty; array[8] = 1; } - else { + else + { array[0] = this.a; array[1] = this.c; array[2] = this.tx; @@ -119,7 +125,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, transformed through this matrix */ -Matrix.prototype.apply = function (pos, newPos) { +Matrix.prototype.apply = function (pos, newPos) +{ newPos = newPos || new Point(); newPos.x = this.a * pos.x + this.c * pos.y + this.tx; @@ -136,7 +143,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, inverse-transformed through this matrix */ -Matrix.prototype.applyInverse = function (pos, newPos) { +Matrix.prototype.applyInverse = function (pos, newPos) +{ newPos = newPos || new Point(); var id = 1 / (this.a * this.d + this.c * -this.b); @@ -154,7 +162,8 @@ * @param {number} y * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.translate = function (x, y) { +Matrix.prototype.translate = function (x, y) +{ this.tx += x; this.ty += y; @@ -168,7 +177,8 @@ * @param {number} y The amount to scale vertically * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.scale = function (x, y) { +Matrix.prototype.scale = function (x, y) +{ this.a *= x; this.d *= y; this.c *= x; @@ -186,7 +196,8 @@ * @param {number} angle - The angle in radians. * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.rotate = function (angle) { +Matrix.prototype.rotate = function (angle) +{ var cos = Math.cos( angle ); var sin = Math.sin( angle ); @@ -210,7 +221,8 @@ * @param {Matrix} matrix * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.append = function (matrix) { +Matrix.prototype.append = function (matrix) +{ var a1 = this.a; var b1 = this.b; var c1 = this.c; @@ -232,7 +244,8 @@ * * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.identity = function () { +Matrix.prototype.identity = function () +{ this.a = 1; this.b = 0; this.c = 0; diff --git a/src/core/math/Point.js b/src/core/math/Point.js index 7565b2d..632f346 100644 --- a/src/core/math/Point.js +++ b/src/core/math/Point.js @@ -7,7 +7,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -function Point(x, y) { +function Point(x, y) +{ /** * @member {number} * @default 0 @@ -29,7 +30,8 @@ * * @return {Point} a copy of the point */ -Point.prototype.clone = function () { +Point.prototype.clone = function () +{ return new Point(this.x, this.y); }; @@ -40,7 +42,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -Point.prototype.set = function (x, y) { +Point.prototype.set = function (x, y) +{ this.x = x || 0; this.y = y || ( (y !== 0) ? this.x : 0 ) ; }; diff --git a/src/core/math/shapes/Circle.js b/src/core/math/shapes/Circle.js index 69cfdc9..4d76efc 100644 --- a/src/core/math/shapes/Circle.js +++ b/src/core/math/shapes/Circle.js @@ -10,7 +10,8 @@ * @param y {number} The Y coordinate of the center of this circle * @param radius {number} The radius of the circle */ -function Circle(x, y, radius) { +function Circle(x, y, radius) +{ /** * @member {number} * @default 0 @@ -46,7 +47,8 @@ * @method clone * @return {Circle} a copy of the Circle */ -Circle.prototype.clone = function () { +Circle.prototype.clone = function () +{ return new Circle(this.x, this.y, this.radius); }; @@ -58,8 +60,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Circle */ -Circle.prototype.contains = function (x, y) { - if (this.radius <= 0) { +Circle.prototype.contains = function (x, y) +{ + if (this.radius <= 0) + { return false; } @@ -79,6 +83,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Circle.prototype.getBounds = function () { +Circle.prototype.getBounds = function () +{ return new Rectangle(this.x - this.radius, this.y - this.radius, this.radius * 2, this.radius * 2); }; diff --git a/src/core/math/shapes/Ellipse.js b/src/core/math/shapes/Ellipse.js index 4f2d066..fefd01a 100644 --- a/src/core/math/shapes/Ellipse.js +++ b/src/core/math/shapes/Ellipse.js @@ -11,7 +11,8 @@ * @param width {number} The half width of this ellipse * @param height {number} The half height of this ellipse */ -function Ellipse(x, y, width, height) { +function Ellipse(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -53,7 +54,8 @@ * @method clone * @return {Ellipse} a copy of the ellipse */ -Ellipse.prototype.clone = function () { +Ellipse.prototype.clone = function () +{ return new Ellipse(this.x, this.y, this.width, this.height); }; @@ -65,8 +67,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coords are within this ellipse */ -Ellipse.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Ellipse.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } @@ -86,6 +90,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Ellipse.prototype.getBounds = function () { +Ellipse.prototype.getBounds = function () +{ return new Rectangle(this.x - this.width, this.y - this.height, this.width, this.height); }; diff --git a/src/core/math/shapes/Polygon.js b/src/core/math/shapes/Polygon.js index ae89148..fea6d37 100644 --- a/src/core/math/shapes/Polygon.js +++ b/src/core/math/shapes/Polygon.js @@ -10,16 +10,20 @@ * arguments passed can be flat x,y values e.g. `new Polygon(x,y, x,y, x,y, ...)` where `x` and `y` are * Numbers. */ -function Polygon(points) { +function Polygon(points) +{ //if points isn't an array, use arguments as the array - if (!(points instanceof Array)) { + if (!(points instanceof Array)) + { points = Array.prototype.slice.call(arguments); } //if this is a flat array of numbers, convert it to points - if (points[0] instanceof Point) { + if (points[0] instanceof Point) + { var p = []; - for (var i = 0, il = points.length; i < il; i++) { + for (var i = 0, il = points.length; i < il; i++) + { p.push(points[i].x, points[i].y); } @@ -51,7 +55,8 @@ * * @return {Polygon} a copy of the polygon */ -Polygon.prototype.clone = function () { +Polygon.prototype.clone = function () +{ return new Polygon(this.points.slice()); }; @@ -62,19 +67,22 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this polygon */ -Polygon.prototype.contains = function (x, y) { +Polygon.prototype.contains = function (x, y) +{ var inside = false; // use some raycasting to test hits // https://github.com/substack/point-in-polygon/blob/master/index.js var length = this.points.length / 2; - for (var i = 0, j = length - 1; i < length; j = i++) { + for (var i = 0, j = length - 1; i < length; j = i++) + { var xi = this.points[i * 2], yi = this.points[i * 2 + 1], xj = this.points[j * 2], yj = this.points[j * 2 + 1], intersect = ((yi > y) !== (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi); - if (intersect) { + if (intersect) + { inside = !inside; } } diff --git a/src/core/math/shapes/Rectangle.js b/src/core/math/shapes/Rectangle.js index 16ac62a..4008b68 100644 --- a/src/core/math/shapes/Rectangle.js +++ b/src/core/math/shapes/Rectangle.js @@ -10,7 +10,8 @@ * @param width {number} The overall width of this rectangle * @param height {number} The overall height of this rectangle */ -function Rectangle(x, y, width, height) { +function Rectangle(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -60,7 +61,8 @@ * * @return {Rectangle} a copy of the rectangle */ -Rectangle.prototype.clone = function () { +Rectangle.prototype.clone = function () +{ return new Rectangle(this.x, this.y, this.width, this.height); }; @@ -71,13 +73,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rectangle */ -Rectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Rectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/math/shapes/RoundedRectangle.js b/src/core/math/shapes/RoundedRectangle.js index 27d286e..7bf6411 100644 --- a/src/core/math/shapes/RoundedRectangle.js +++ b/src/core/math/shapes/RoundedRectangle.js @@ -11,7 +11,8 @@ * @param height {number} The overall height of this rounded rectangle * @param radius {number} Controls the radius of the rounded corners */ -function RoundedRectangle(x, y, width, height, radius) { +function RoundedRectangle(x, y, width, height, radius) +{ /** * @member {number} * @default 0 @@ -58,7 +59,8 @@ * * @return {RoundedRectangle} a copy of the rounded rectangle */ -RoundedRectangle.prototype.clone = function () { +RoundedRectangle.prototype.clone = function () +{ return new RoundedRectangle(this.x, this.y, this.width, this.height, this.radius); }; @@ -69,13 +71,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rounded Rectangle */ -RoundedRectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +RoundedRectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/primitives/Graphics.js b/src/core/primitives/Graphics.js index 261c534..e902d2a 100644 --- a/src/core/primitives/Graphics.js +++ b/src/core/primitives/Graphics.js @@ -16,7 +16,8 @@ * @extends DisplayObjectContainer * @namespace PIXI */ -function Graphics() { +function Graphics() +{ DisplayObjectContainer.call(this); this.renderable = true; @@ -154,16 +155,20 @@ * @private */ cacheAsBitmap: { - get: function () { + get: function () + { return this._cacheAsBitmap; }, - set: function (value) { + set: function (value) + { this._cacheAsBitmap = value; - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._generateCachedSprite(); } - else { + else + { this.destroyCachedSprite(); this.dirty = true; } @@ -176,7 +181,8 @@ * * @return {Graphics} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ var clone = new Graphics(); clone.renderable = this.renderable; @@ -192,7 +198,8 @@ clone.cachedSpriteDirty = this.cachedSpriteDirty; // copy graphics data - for (var i = 0; i < this.graphicsData.length; ++i) { + for (var i = 0; i < this.graphicsData.length; ++i) + { clone.graphicsData.push(this.graphicsData.clone()); } @@ -211,17 +218,21 @@ * @param alpha {number} alpha of the line to draw, will update the objects stored style * @return {Graphics} */ -Graphics.prototype.lineStyle = function (lineWidth, color, alpha) { +Graphics.prototype.lineStyle = function (lineWidth, color, alpha) +{ this.lineWidth = lineWidth || 0; this.lineColor = color || 0; this.lineAlpha = (arguments.length < 3) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length) + { // halfway through a line? start a new one! this.drawShape( new math.Polygon( this.currentPath.shape.points.slice(-2) )); } - else { + else + { // otherwise its empty so lets just set the line properties this.currentPath.lineWidth = this.lineWidth; this.currentPath.lineColor = this.lineColor; @@ -239,7 +250,8 @@ * @param y {number} the Y coordinate to move to * @return {Graphics} */ -Graphics.prototype.moveTo = function (x, y) { +Graphics.prototype.moveTo = function (x, y) +{ this.drawShape(new math.Polygon([x,y])); return this; @@ -253,7 +265,8 @@ * @param y {number} the Y coordinate to draw to * @return {Graphics} */ -Graphics.prototype.lineTo = function (x, y) { +Graphics.prototype.lineTo = function (x, y) +{ this.currentPath.shape.points.push(x, y); this.dirty = true; @@ -270,13 +283,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -285,7 +302,8 @@ n = 20, points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { this.moveTo(0, 0); } @@ -293,7 +311,8 @@ var fromY = points[points.length-1]; var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; xa = fromX + ( (cpX - fromX) * j ); @@ -319,13 +338,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -342,7 +365,8 @@ var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; dt = (1 - j); @@ -373,13 +397,17 @@ * @param radius {number} The radius of the arc * @return {Graphics} */ -Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points.push(x1, y1); } } - else { + else + { this.moveTo(x1, y1); } @@ -392,12 +420,15 @@ b2 = x2 - x1, mm = Math.abs(a1 * b2 - b1 * a2); - if (mm < 1.0e-8 || radius === 0) { - if (points[points.length-2] !== x1 || points[points.length-1] !== y1) { + if (mm < 1.0e-8 || radius === 0) + { + if (points[points.length-2] !== x1 || points[points.length-1] !== y1) + { points.push(x1, y1); } } - else { + else + { var dd = a1 * a1 + b1 * b1, cc = a2 * a2 + b2 * b2, tt = a1 * a2 + b1 * b2, @@ -433,42 +464,51 @@ * @param anticlockwise {boolean} Optional. Specifies whether the drawing should be counterclockwise or clockwise. False is default, and indicates clockwise, while true indicates counter-clockwise. * @return {Graphics} */ -Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) { +Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) +{ var startX = cx + Math.cos(startAngle) * radius; var startY = cy + Math.sin(startAngle) * radius; var points; // TODO - This if-else makes no sense. It uses currentPath in the else where it doesn't exist... - if (this.currentPath) { + if (this.currentPath) + { points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { points.push(startX, startY); } - else if (points[points.length-2] !== startX || points[points.length-1] !== startY) { + else if (points[points.length-2] !== startX || points[points.length-1] !== startY) + { points.push(startX, startY); } } - else { + else + { this.moveTo(startX, startY); points = this.currentPath.shape.points; } - if (startAngle === endAngle) { + if (startAngle === endAngle) + { return this; } - if (!anticlockwise && endAngle <= startAngle) { + if (!anticlockwise && endAngle <= startAngle) + { endAngle += Math.PI * 2; } - else if (anticlockwise && startAngle <= endAngle) { + else if (anticlockwise && startAngle <= endAngle) + { startAngle += Math.PI * 2; } var sweep = anticlockwise ? (startAngle - endAngle) *-1 : (endAngle - startAngle); var segs = (Math.abs(sweep)/ (Math.PI * 2)) * 40; - if (sweep === 0) { + if (sweep === 0) + { return this; } @@ -482,7 +522,8 @@ var remainder = ( segMinus % 1 ) / segMinus; - for (var i = 0; i <= segMinus; ++i) { + for (var i = 0; i <= segMinus; ++i) + { var real = i + remainder * i; var angle = ((theta) + startAngle + (theta2 * real)); @@ -506,13 +547,16 @@ * @param alpha {number} the alpha of the fill * @return {Graphics} */ -Graphics.prototype.beginFill = function (color, alpha) { +Graphics.prototype.beginFill = function (color, alpha) +{ this.filling = true; this.fillColor = color || 0; this.fillAlpha = (alpha === undefined) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length <= 2) + { this.currentPath.fill = this.filling; this.currentPath.fillColor = this.fillColor; this.currentPath.fillAlpha = this.fillAlpha; @@ -526,7 +570,8 @@ * * @return {Graphics} */ -Graphics.prototype.endFill = function () { +Graphics.prototype.endFill = function () +{ this.filling = false; this.fillColor = null; this.fillAlpha = 1; @@ -542,7 +587,8 @@ * @param height {number} The height of the rectangle * @return {Graphics} */ -Graphics.prototype.drawRect = function ( x, y, width, height ) { +Graphics.prototype.drawRect = function ( x, y, width, height ) +{ this.drawShape(new math.Rectangle(x,y, width, height)); return this; @@ -556,7 +602,8 @@ * @param height {number} The height of the rectangle * @param radius {number} Radius of the rectangle corners */ -Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) { +Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) +{ this.drawShape(new math.RoundedRectangle(x, y, width, height, radius)); return this; @@ -570,7 +617,8 @@ * @param radius {number} The radius of the circle * @return {Graphics} */ -Graphics.prototype.drawCircle = function (x, y, radius) { +Graphics.prototype.drawCircle = function (x, y, radius) +{ this.drawShape(new math.Circle(x,y, radius)); return this; @@ -585,7 +633,8 @@ * @param height {number} The half height of the ellipse * @return {Graphics} */ -Graphics.prototype.drawEllipse = function (x, y, width, height) { +Graphics.prototype.drawEllipse = function (x, y, width, height) +{ this.drawShape(new math.Ellipse(x, y, width, height)); return this; @@ -597,8 +646,10 @@ * @param path {Array} The path data used to construct the polygon. * @return {Graphics} */ -Graphics.prototype.drawPolygon = function (path) { - if (!(path instanceof Array)) { +Graphics.prototype.drawPolygon = function (path) +{ + if (!(path instanceof Array)) + { path = Array.prototype.slice.call(arguments); } @@ -612,7 +663,8 @@ * * @return {Graphics} */ -Graphics.prototype.clear = function () { +Graphics.prototype.clear = function () +{ this.lineWidth = 0; this.filling = false; @@ -631,7 +683,8 @@ * @param scaleMode {number} Should be one of the scaleMode consts * @return {Texture} a texture of the graphics object */ -Graphics.prototype.generateTexture = function (resolution, scaleMode) { +Graphics.prototype.generateTexture = function (resolution, scaleMode) +{ resolution = resolution || 1; var bounds = this.getBounds(); @@ -655,17 +708,21 @@ * * @param renderer {WebGLRenderer} */ -Graphics.prototype._renderWebGL = function (renderer) { +Graphics.prototype._renderWebGL = function (renderer) +{ // if the sprite is not visible or the alpha is 0 then no need to render this element - if (this.isMask === true) { + if (this.isMask === true) + { return; } // this code may still be needed so leaving for now.. - // + // /* - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture on the gpu too! @@ -681,17 +738,24 @@ return; } - */ - - // check if the webgl graphic needs to be updated - if (this.glDirty) { - this.dirty = true; - this.glDirty = false; - } + else */ - renderer.setObjectRendererer(renderer.graphicsRenderer); - renderer.graphicsRenderer.render(this); + renderer.spriteBatch.stop(); + renderer.blendModeManager.setBlendMode(this.blendMode); + // check blend mode + renderer.blendModeManager.setBlendMode( this.blendMode ); + + // check if the webgl graphic needs to be updated + if (this.glDirty) + { + this.dirty = true; + this.glDirty = false; + } + + WebGLGraphics.renderGraphics(this, renderer); + + renderer.spriteBatch.start(); }; /** @@ -700,14 +764,18 @@ * @param renderer {CanvasRenderer} * @private */ -Graphics.prototype.renderCanvas = function (renderer) { +Graphics.prototype.renderCanvas = function (renderer) +{ // 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.isMask === true) { + if (!this.visible || this.alpha <= 0 || this.isMask === true) + { return; } - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture @@ -723,16 +791,19 @@ return; } - else { + else + { var context = renderer.context; var transform = this.worldTransform; - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } @@ -748,11 +819,13 @@ CanvasGraphics.renderGraphics(this, context); - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } } @@ -763,13 +836,16 @@ * * @return {Rectangle} the rectangular bounding area */ -Graphics.prototype.getBounds = function (matrix) { +Graphics.prototype.getBounds = function (matrix) +{ // return an empty object if the item is a mask! - if (this.isMask) { + if (this.isMask) + { return math.Rectangle.EMPTY; } - if (this.dirty) { + if (this.dirty) + { this.updateLocalBounds(); this.glDirty = true; @@ -841,23 +917,27 @@ * Update the bounds of the object * */ -Graphics.prototype.updateLocalBounds = function () { +Graphics.prototype.updateLocalBounds = function () +{ var minX = Infinity; var maxX = -Infinity; var minY = Infinity; var maxY = -Infinity; - if (this.graphicsData.length) { + if (this.graphicsData.length) + { var shape, points, x, y, w, h; - for (var i = 0; i < this.graphicsData.length; i++) { + for (var i = 0; i < this.graphicsData.length; i++) + { var data = this.graphicsData[i]; var type = data.type; var lineWidth = data.lineWidth; shape = data.shape; - if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) { + if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) + { x = shape.x - lineWidth/2; y = shape.y - lineWidth/2; w = shape.width + lineWidth; @@ -869,7 +949,8 @@ minY = y < minY ? y : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.CIRC) { + else if (type === CONST.SHAPES.CIRC) + { x = shape.x; y = shape.y; w = shape.radius + lineWidth/2; @@ -881,7 +962,8 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.ELIP) { + else if (type === CONST.SHAPES.ELIP) + { x = shape.x; y = shape.y; w = shape.width + lineWidth/2; @@ -893,11 +975,13 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else { + else + { // POLY points = shape.points; - for (var j = 0; j < points.length; j += 2) { + for (var j = 0; j < points.length; j += 2) + { x = points[j]; y = points[j+1]; @@ -910,7 +994,8 @@ } } } - else { + else + { minX = 0; maxX = 0; minY = 0; @@ -931,10 +1016,12 @@ * * @private */ -Graphics.prototype._generateCachedSprite = function () { +Graphics.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { var canvasBuffer = new CanvasBuffer(bounds.width, bounds.height); var texture = Texture.fromCanvas(canvasBuffer.canvas); @@ -943,7 +1030,8 @@ this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.buffer.resize(bounds.width, bounds.height); } @@ -968,7 +1056,8 @@ * * @private */ -Graphics.prototype.updateCachedSpriteTexture = function () { +Graphics.prototype.updateCachedSpriteTexture = function () +{ var cachedSprite = this._cachedSprite; var texture = cachedSprite.texture; var canvas = cachedSprite.buffer.canvas; @@ -989,7 +1078,8 @@ * Destroys a previous cached sprite. * */ -Graphics.prototype.destroyCachedSprite = function () { +Graphics.prototype.destroyCachedSprite = function () +{ this._cachedSprite.texture.destroy(true); // let the gc collect the unused sprite @@ -1003,10 +1093,13 @@ * @param {Circle|Rectangle|Ellipse|Line|Polygon} shape The Shape object to draw. * @return {GraphicsData} The generated GraphicsData object. */ -Graphics.prototype.drawShape = function (shape) { - if (this.currentPath) { +Graphics.prototype.drawShape = function (shape) +{ + if (this.currentPath) + { // check current path! - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath.shape.points.length <= 2) + { this.graphicsData.pop(); } } @@ -1017,7 +1110,8 @@ this.graphicsData.push(data); - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { data.shape.closed = this.filling; this.currentPath = data; } diff --git a/src/core/primitives/GraphicsData.js b/src/core/primitives/GraphicsData.js index 99decbe..788f6f2 100644 --- a/src/core/primitives/GraphicsData.js +++ b/src/core/primitives/GraphicsData.js @@ -4,7 +4,8 @@ * @class * @namespace PIXI */ -function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) { +function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) +{ this.lineWidth = lineWidth; this.lineColor = lineColor; this.lineAlpha = lineAlpha; @@ -27,7 +28,8 @@ * * @return {GraphicsData} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ return new GraphicsData( this.lineWidth, this.lineColor, diff --git a/src/core/renderers/canvas/CanvasRenderer.js b/src/core/renderers/canvas/CanvasRenderer.js index 15a0978..7aebd44 100644 --- a/src/core/renderers/canvas/CanvasRenderer.js +++ b/src/core/renderers/canvas/CanvasRenderer.js @@ -17,17 +17,22 @@ * @param [options.resolution=1] {number} the resolution of the renderer retina would be 2 * @param [options.clearBeforeRender=true] {boolean} This sets if the CanvasRenderer will clear the canvas or not before the new render pass. */ -function CanvasRenderer(width, height, options) { +function CanvasRenderer(width, height, options) +{ utils.sayHello('Canvas'); - if (options) { - for (var i in CONST.defaultRenderOptions) { - if (typeof options[i] === 'undefined') { + if (options) + { + for (var i in CONST.defaultRenderOptions) + { + if (typeof options[i] === 'undefined') + { options[i] = CONST.defaultRenderOptions[i]; } } } - else { + else + { options = CONST.defaultRenderOptions; } @@ -156,19 +161,24 @@ this.smoothProperty = null; - if (this.context.imageSmoothingEnabled) { + if (this.context.imageSmoothingEnabled) + { this.smoothProperty = 'imageSmoothingEnabled'; } - else if (this.context.webkitImageSmoothingEnabled) { + else if (this.context.webkitImageSmoothingEnabled) + { this.smoothProperty = 'webkitImageSmoothingEnabled'; } - else if (this.context.mozImageSmoothingEnabled) { + else if (this.context.mozImageSmoothingEnabled) + { this.smoothProperty = 'mozImageSmoothingEnabled'; } - else if (this.context.oImageSmoothingEnabled) { + else if (this.context.oImageSmoothingEnabled) + { this.smoothProperty = 'oImageSmoothingEnabled'; } - else if (this.context.msImageSmoothingEnabled) { + else if (this.context.msImageSmoothingEnabled) + { this.smoothProperty = 'msImageSmoothingEnabled'; } @@ -193,10 +203,12 @@ * @memberof CanvasRenderer# */ backgroundColor: { - get: function () { + get: function () + { return this._backgroundColor; }, - set: function (val) { + set: function (val) + { this._backgroundColor = val; this._backgroundColorString = utils.hex2string(val); } @@ -208,7 +220,8 @@ * * @param object {DisplayObject} the object to be rendered */ -CanvasRenderer.prototype.render = function (object) { +CanvasRenderer.prototype.render = function (object) +{ object.updateTransform(); this.context.setTransform(1,0,0,1,0,0); @@ -218,16 +231,20 @@ this.currentBlendMode = CONST.blendModes.NORMAL; this.context.globalCompositeOperation = this.blendModes[CONST.blendModes.NORMAL]; - if (navigator.isCocoonJS && this.view.screencanvas) { + if (navigator.isCocoonJS && this.view.screencanvas) + { this.context.fillStyle = 'black'; this.context.clear(); } - if (this.clearBeforeRender) { - if (this.transparent) { + if (this.clearBeforeRender) + { + if (this.transparent) + { this.context.clearRect(0, 0, this.width, this.height); } - else { + else + { this.context.fillStyle = this._backgroundColorString; this.context.fillRect(0, 0, this.width , this.height); } @@ -241,8 +258,10 @@ * * @param [removeView=false] {boolean} Removes the Canvas element from the DOM. */ -CanvasRenderer.prototype.destroy = function (removeView) { - if (removeView && this.view.parent) { +CanvasRenderer.prototype.destroy = function (removeView) +{ + if (removeView && this.view.parent) + { this.view.parent.removeChild(this.view); } @@ -257,14 +276,16 @@ * @param width {number} the new width of the canvas view * @param height {number} the new height of the canvas view */ -CanvasRenderer.prototype.resize = function (width, height) { +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) { + if (this.autoResize) + { this.view.style.width = this.width / this.resolution + 'px'; this.view.style.height = this.height / this.resolution + 'px'; } @@ -276,7 +297,8 @@ * @param displayObject {DisplayObject} The displayObject to render * @private */ -CanvasRenderer.prototype.renderDisplayObject = function (displayObject) { +CanvasRenderer.prototype.renderDisplayObject = function (displayObject) +{ displayObject.renderCanvas(this); }; @@ -285,11 +307,14 @@ * * @private */ -CanvasRenderer.prototype._mapBlendModes = function () { - if (!this.blendModes) { +CanvasRenderer.prototype._mapBlendModes = function () +{ + if (!this.blendModes) + { this.blendModes = {}; - if (utils.canUseNewCanvasBlendModes()) { + if (utils.canUseNewCanvasBlendModes()) + { this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? this.blendModes[CONST.blendModes.MULTIPLY] = 'multiply'; @@ -308,7 +333,8 @@ this.blendModes[CONST.blendModes.COLOR] = 'color'; this.blendModes[CONST.blendModes.LUMINOSITY] = 'luminosity'; } - else { + else + { // this means that the browser does not support the cool new blend modes in canvas 'cough' ie 'cough' this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? diff --git a/src/core/renderers/canvas/utils/CanvasBuffer.js b/src/core/renderers/canvas/utils/CanvasBuffer.js index ebe5d47..b183a66 100644 --- a/src/core/renderers/canvas/utils/CanvasBuffer.js +++ b/src/core/renderers/canvas/utils/CanvasBuffer.js @@ -6,7 +6,8 @@ * @param width {number} the width for the newly created canvas * @param height {number} the height for the newly created canvas */ -function CanvasBuffer(width, height) { +function CanvasBuffer(width, height) +{ /** * The Canvas object that belongs to this CanvasBuffer. * @@ -36,10 +37,12 @@ * @memberof CanvasBuffer# */ width: { - get: function () { + get: function () + { return this.canvas.width; }, - set: function (val) { + set: function (val) + { this.canvas.width = val; } }, @@ -50,10 +53,12 @@ * @memberof CanvasBuffer# */ height: { - get: function () { + get: function () + { return this.canvas.height; }, - set: function (val) { + set: function (val) + { this.canvas.height = val; } } @@ -64,7 +69,8 @@ * * @private */ -CanvasBuffer.prototype.clear = function () { +CanvasBuffer.prototype.clear = function () +{ this.context.setTransform(1, 0, 0, 1, 0, 0); this.context.clearRect(0,0, this.canvas.width, this.canvas.height); }; @@ -75,7 +81,8 @@ * @param width {number} the new width of the canvas * @param height {number} the new height of the canvas */ -CanvasBuffer.prototype.resize = function (width, height) { +CanvasBuffer.prototype.resize = function (width, height) +{ this.canvas.width = width; this.canvas.height = height; }; diff --git a/src/core/display/DisplayObject.js b/src/core/display/DisplayObject.js index 66ebc3c..20e778c 100644 --- a/src/core/display/DisplayObject.js +++ b/src/core/display/DisplayObject.js @@ -7,7 +7,8 @@ * @class * @namespace PIXI */ -function DisplayObject() { +function DisplayObject() +{ /** * The coordinate of the object relative to the local coordinates of the parent. * @@ -152,10 +153,12 @@ * @memberof DisplayObject# */ x: { - get: function () { + get: function () + { return this.position.x; }, - set: function (value) { + set: function (value) + { this.position.x = value; } }, @@ -167,10 +170,12 @@ * @memberof DisplayObject# */ y: { - get: function () { + get: function () + { return this.position.y; }, - set: function (value) { + set: function (value) + { this.position.y = value; } }, @@ -183,11 +188,13 @@ * @readonly */ worldVisible: { - get: function () { + get: function () + { var item = this; do { - if (!item.visible) { + if (!item.visible) + { return false; } @@ -207,17 +214,21 @@ * @memberof DisplayObject# */ mask: { - get: function () { + get: function () + { return this._mask; }, - set: function (value) { - if (this._mask) { + set: function (value) + { + if (this._mask) + { this._mask.isMask = false; } this._mask = value; - if (this._mask) { + if (this._mask) + { this._mask.isMask = true; } } @@ -232,18 +243,23 @@ * @memberof DisplayObject# */ filters: { - get: function () { + get: function () + { return this._filters; }, - set: function (value) { - if (value) { + set: function (value) + { + if (value) + { // now put all the passes in one place.. var passes = []; - for (var i = 0; i < value.length; i++) { + for (var i = 0; i < value.length; i++) + { var filterPasses = value[i].passes; - for (var j = 0; j < filterPasses.length; j++) { + for (var j = 0; j < filterPasses.length; j++) + { passes.push(filterPasses[j]); } } @@ -264,8 +280,9 @@ * * @private */ -DisplayObject.prototype.updateTransform = function () { - +DisplayObject.prototype.updateTransform = function () +{ + // create some matrix refs for easy access var pt = this.parent.worldTransform; var wt = this.worldTransform; @@ -274,9 +291,11 @@ var a, b, c, d, tx, ty; // so if rotation is between 0 then we can simplify the multiplication process.. - if (this.rotation % math.PI_2) { + if (this.rotation % math.PI_2) + { // 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) { + if (this.rotation !== this.rotationCache) + { this.rotationCache = this.rotation; this._sr = Math.sin(this.rotation); this._cr = Math.cos(this.rotation); @@ -291,7 +310,8 @@ ty = this.position.y; // check for pivot.. not often used so geared towards that fact! - if (this.pivot.x || this.pivot.y) { + 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; } @@ -304,7 +324,8 @@ wt.tx = tx * pt.a + ty * pt.c + pt.tx; wt.ty = tx * pt.b + ty * pt.d + pt.ty; } - else { + else + { // lets do the fast version as we know there is no rotation.. a = this.scale.x; d = this.scale.y; @@ -333,7 +354,8 @@ * @param matrix {Matrix} * @return {Rectangle} the rectangular bounding area */ -DisplayObject.prototype.getBounds = function (/* matrix */) { +DisplayObject.prototype.getBounds = function (/* matrix */) +{ return math.Rectangle.EMPTY; }; @@ -342,7 +364,8 @@ * * @return {Rectangle} the rectangular bounding area */ -DisplayObject.prototype.getLocalBounds = function () { +DisplayObject.prototype.getLocalBounds = function () +{ return this.getBounds(math.Matrix.IDENTITY); }; @@ -352,7 +375,8 @@ * @param position {Point} The world origin to calculate from * @return {Point} A point object representing the position of this object */ -DisplayObject.prototype.toGlobal = function (position) { +DisplayObject.prototype.toGlobal = function (position) +{ // don't need to u[date the lot this.displayObjectUpdateTransform(); return this.worldTransform.apply(position); @@ -365,8 +389,10 @@ * @param [from] {DisplayObject} The DisplayObject to calculate the global position from * @return {Point} A point object representing the position of this object */ -DisplayObject.prototype.toLocal = function (position, from) { - if (from) { +DisplayObject.prototype.toLocal = function (position, from) +{ + if (from) + { position = from.toGlobal(position); } @@ -381,7 +407,8 @@ * @param renderer {WebGLRenderer} The renderer * @private */ -DisplayObject.prototype.renderWebGL = function (/* renderer */) { +DisplayObject.prototype.renderWebGL = function (/* renderer */) +{ // OVERWRITE; }; @@ -391,6 +418,7 @@ * @param renderer {CanvasRenderer} The renderer * @private */ -DisplayObject.prototype.renderCanvas = function (/* renderer */) { +DisplayObject.prototype.renderCanvas = function (/* renderer */) +{ // OVERWRITE; }; diff --git a/src/core/display/DisplayObjectContainer.js b/src/core/display/DisplayObjectContainer.js index 689f40b..4625ee8 100644 --- a/src/core/display/DisplayObjectContainer.js +++ b/src/core/display/DisplayObjectContainer.js @@ -12,7 +12,8 @@ * @extends DisplayObject * @namespace PIXI */ -function DisplayObjectContainer() { +function DisplayObjectContainer() +{ DisplayObject.call(this); /** @@ -47,17 +48,21 @@ * @memberof DisplayObjectContainer# */ width: { - get: function () { + get: function () + { return this.scale.x * this.getLocalBounds().width; }, - set: function (value) { + set: function (value) + { var width = this.getLocalBounds().width; - if(width !== 0) { + if(width !== 0) + { this.scale.x = value / width; } - else { + else + { this.scale.x = 1; } @@ -73,17 +78,21 @@ * @memberof DisplayObjectContainer# */ height: { - get: function () { + get: function () + { return this.scale.y * this.getLocalBounds().height; }, - set: function (value) { + set: function (value) + { var height = this.getLocalBounds().height; - if (height !== 0) { + if (height !== 0) + { this.scale.y = value / height ; } - else { + else + { this.scale.y = 1; } @@ -100,18 +109,23 @@ * @memberof DisplayObject# */ cacheAsBitmap: { - get: function () { + get: function () + { return this._cacheAsBitmap; }, - set: function (value) { - if (this._cacheAsBitmap === value) { + set: function (value) + { + if (this._cacheAsBitmap === value) + { return; } - if (value) { + if (value) + { this._generateCachedSprite(); } - else { + else + { this._destroyCachedSprite(); } @@ -126,7 +140,8 @@ * @param child {DisplayObject} The DisplayObject to add to the container * @return {DisplayObject} The child that was added. */ -DisplayObjectContainer.prototype.addChild = function (child) { +DisplayObjectContainer.prototype.addChild = function (child) +{ return this.addChildAt(child, this.children.length); }; @@ -137,14 +152,18 @@ * @param index {Number} The index to place the child in * @return {DisplayObject} The child that was added. */ -DisplayObjectContainer.prototype.addChildAt = function (child, index) { +DisplayObjectContainer.prototype.addChildAt = function (child, index) +{ // prevent adding self as child - if (child === this) { + if (child === this) + { return; } - if (index >= 0 && index <= this.children.length) { - if (child.parent) { + if (index >= 0 && index <= this.children.length) + { + if (child.parent) + { child.parent.removeChild(child); } @@ -154,7 +173,8 @@ return child; } - else { + else + { throw new Error(child + 'addChildAt: The index '+ index +' supplied is out of bounds ' + this.children.length); } }; @@ -165,15 +185,18 @@ * @param child {DisplayObject} * @param child2 {DisplayObject} */ -DisplayObjectContainer.prototype.swapChildren = function (child, child2) { - if (child === child2) { +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) { + if (index1 < 0 || index2 < 0) + { throw new Error('swapChildren: Both the supplied DisplayObjects must be a child of the caller.'); } @@ -187,10 +210,12 @@ * @param child {DisplayObject} The DisplayObject instance to identify * @return {Number} The index position of the child display object to identify */ -DisplayObjectContainer.prototype.getChildIndex = function (child) { +DisplayObjectContainer.prototype.getChildIndex = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { throw new Error('The supplied DisplayObject must be a child of the caller'); } @@ -203,8 +228,10 @@ * @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 */ -DisplayObjectContainer.prototype.setChildIndex = function (child, index) { - if (index < 0 || index >= this.children.length) { +DisplayObjectContainer.prototype.setChildIndex = function (child, index) +{ + if (index < 0 || index >= this.children.length) + { throw new Error('The supplied index is out of bounds'); } @@ -220,8 +247,10 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child at the given index, if any. */ -DisplayObjectContainer.prototype.getChildAt = function (index) { - if (index < 0 || index >= this.children.length) { +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'); } @@ -234,10 +263,12 @@ * @param child {DisplayObject} The DisplayObject to remove * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChild = function (child) { +DisplayObjectContainer.prototype.removeChild = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { return; } @@ -250,7 +281,8 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChildAt = function (index) { +DisplayObjectContainer.prototype.removeChildAt = function (index) +{ var child = this.getChildAt(index); child.parent = null; @@ -265,24 +297,29 @@ * @param beginIndex {Number} The beginning position. Default value is 0. * @param endIndex {Number} The ending position. Default value is size of the container. */ -DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) { +DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) +{ var begin = beginIndex || 0; var end = typeof endIndex === 'number' ? endIndex : this.children.length; var range = end - begin; - if (range > 0 && range <= end) { + if (range > 0 && range <= end) + { var removed = this.children.splice(begin, range); - for (var i = 0; i < removed.length; ++i) { + for (var i = 0; i < removed.length; ++i) + { removed[i].parent = null; } return removed; } - else if (range === 0 && this.children.length === 0) { + else if (range === 0 && this.children.length === 0) + { return []; } - else { + else + { throw new RangeError('removeChildren: numeric values are outside the acceptable range.'); } }; @@ -291,7 +328,8 @@ * Generates and updates the cached sprite for this object. * */ -DisplayObjectContainer.prototype.updateCachedSprite = function () { +DisplayObjectContainer.prototype.updateCachedSprite = function () +{ this._generateCachedSprite(); }; @@ -304,7 +342,8 @@ * @param renderer {CanvasRenderer|WebGLRenderer} The renderer used to generate the texture. * @return {Texture} a texture of the graphics object */ -DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) { +DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) +{ var bounds = this.getLocalBounds(); var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0, renderer, scaleMode, resolution); @@ -322,18 +361,22 @@ * * @private */ -DisplayObjectContainer.prototype.updateTransform = function () { - if (!this.visible) { +DisplayObjectContainer.prototype.updateTransform = function () +{ + if (!this.visible) + { return; } this.displayObjectUpdateTransform(); - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { return; } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } }; @@ -346,8 +389,10 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getBounds = function () { - if (this.children.length === 0) { +DisplayObjectContainer.prototype.getBounds = function () +{ + if (this.children.length === 0) + { return math.Rectangle.EMPTY; } @@ -365,10 +410,12 @@ var childVisible = false; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -386,7 +433,8 @@ maxY = maxY > childMaxY ? maxY : childMaxY; } - if (!childVisible) { + if (!childVisible) + { return math.Rectangle.EMPTY; } @@ -407,12 +455,14 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getLocalBounds = function () { +DisplayObjectContainer.prototype.getLocalBounds = function () +{ var matrixCache = this.worldTransform; this.worldTransform = math.Matrix.IDENTITY; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } @@ -428,13 +478,16 @@ * * @param renderer {WebGLRenderer} The renderer */ -DisplayObjectContainer.prototype.renderWebGL = function (renderer) { +DisplayObjectContainer.prototype.renderWebGL = function (renderer) +{ // if the object is not visible or the alpha is 0 then no need to render this element - if (!this.visible || this.alpha <= 0) { + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } @@ -442,14 +495,17 @@ var i, j; // do a quick check to see if this element has a mask or a filter. - if (this._mask || this._filters) { + if (this._mask || this._filters) + { // push filter first as we need to ensure the stencil buffer is correct for any masking - if (this._filters) { + if (this._filters) + { renderer.spriteBatch.flush(); renderer.filterManager.pushFilter(this._filterBlock); } - if (this._mask) { + if (this._mask) + { renderer.spriteBatch.stop(); renderer.maskManager.pushMask(this.mask, renderer); renderer.spriteBatch.start(); @@ -459,36 +515,42 @@ this._renderWebGL(renderer); // now loop through the children and make sure they get rendered - for (i = 0, j = this.children.length; i < j; i++) { + for (i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderWebGL(renderer); } // time to stop the sprite batch as either a mask element or a filter draw will happen next renderer.spriteBatch.stop(); - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(this._mask, renderer); } - if (this._filters) { + if (this._filters) + { renderer.filterManager.popFilter(); } renderer.spriteBatch.start(); } - else { + else + { this._renderWebGL(renderer); // simple render children! - for (i = 0, j = this.children.length; i < j; ++i) { + for (i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderWebGL(renderer); } } }; -DisplayObjectContainer.prototype._renderWebGL = function (renderer) { +DisplayObjectContainer.prototype._renderWebGL = function (renderer) +{ // this is where content itself gets renderd.. @@ -499,25 +561,31 @@ * * @param renderer {CanvasRenderer} The renderer */ -DisplayObjectContainer.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0) { +DisplayObjectContainer.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -528,13 +596,16 @@ * @param renderer {WebGLRenderer|CanvasRenderer} The renderer * @private */ -DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) { +DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) +{ this._cachedSprite.worldAlpha = this.worldAlpha; - if (renderer.gl) { + if (renderer.gl) + { this._cachedSprite.renderWebGL(renderer); } - else { + else + { this._cachedSprite.renderCanvas(renderer); } }; @@ -544,10 +615,12 @@ * * @private */ -DisplayObjectContainer.prototype._generateCachedSprite = function () { +DisplayObjectContainer.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { // TODO - RenderTexture now *requires* a renderer instance, so this is like broken // because `renderer` isn't actually in scope here :P var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0); @@ -555,7 +628,8 @@ this._cachedSprite = new Sprite(renderTexture); this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.texture.resize(bounds.width | 0, bounds.height | 0); } @@ -580,8 +654,10 @@ * * @private */ -DisplayObjectContainer.prototype._destroyCachedSprite = function () { - if (!this._cachedSprite) { +DisplayObjectContainer.prototype._destroyCachedSprite = function () +{ + if (!this._cachedSprite) + { return; } diff --git a/src/core/display/Sprite.js b/src/core/display/Sprite.js index 707da24..5862aef 100644 --- a/src/core/display/Sprite.js +++ b/src/core/display/Sprite.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param texture {Texture} The texture for this sprite */ -function Sprite(texture) { +function Sprite(texture) +{ DisplayObjectContainer.call(this); /** @@ -85,12 +86,14 @@ this.texture = texture || Texture.EMPTY; } -Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) { +Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) +{ DisplayObjectContainer.prototype.destroy.call(this); this.anchor = null; - if (destroyTexture) { + if (destroyTexture) + { this._texture.destroy(destroyBaseTexture); } @@ -111,10 +114,12 @@ * @memberof Sprite# */ width: { - get: function () { + get: function () + { return this.scale.x * this.texture.frame.width; }, - set: function (value) { + set: function (value) + { this.scale.x = value / this.texture.frame.width; this._width = value; } @@ -127,10 +132,12 @@ * @memberof Sprite# */ height: { - get: function () { + get: function () + { return this.scale.y * this.texture.frame.height; }, - set: function (value) { + set: function (value) + { this.scale.y = value / this.texture.frame.height; this._height = value; } @@ -143,23 +150,29 @@ * @memberof Sprite# */ texture: { - get: function () { + get: function () + { return this._texture; }, - set: function (value) { - if (this._texture === value) { + set: function (value) + { + if (this._texture === value) + { return; } this._texture = value; this.cachedTint = 0xFFFFFF; - if (value) { + if (value) + { // wait for the texture to load - if (value.baseTexture.hasLoaded) { + if (value.baseTexture.hasLoaded) + { this._onTextureUpdate(); } - else { + else + { value.once('update', this._onTextureUpdate.bind(this)); } } @@ -172,18 +185,22 @@ * * @private */ -Sprite.prototype._onTextureUpdate = function () { +Sprite.prototype._onTextureUpdate = function () +{ // so if _width is 0 then width was not set.. - if (this._width) { + if (this._width) + { this.scale.x = this._width / this.texture.frame.width; } - if (this._height) { + if (this._height) + { this.scale.y = this._height / this.texture.frame.height; } }; -Sprite.prototype._renderWebGL = function (renderer) { +Sprite.prototype._renderWebGL = function (renderer) +{ // this is where content gets renderd.. // watch this space for a little render state manager.. @@ -197,7 +214,8 @@ * @param matrix {Matrix} the transformation matrix of the sprite * @return {Rectangle} the framing rectangle */ -Sprite.prototype.getBounds = function (matrix) { +Sprite.prototype.getBounds = function (matrix) +{ var width = this.texture.frame.width; var height = this.texture.frame.height; @@ -224,11 +242,13 @@ if(b === 0 && c === 0) { // scale may be negative! - if (a < 0) { + if (a < 0) + { a *= -1; } - if (d < 0) { + if (d < 0) + { d *= -1; } @@ -293,28 +313,34 @@ * * @param renderer {CanvasRenderer} The renderer */ -Sprite.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) { +Sprite.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) + { return; } - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; renderer.context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } // Ignore null sources - if (this.texture.valid) { + if (this.texture.valid) + { var resolution = this.texture.baseTexture.resolution / renderer.resolution; renderer.context.globalAlpha = this.worldAlpha; // If smoothingEnabled is supported and we need to change the smoothing property for this texture - if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) { + if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) + { renderer.scaleMode = this.texture.baseTexture.scaleMode; renderer.context[renderer.smoothProperty] = (renderer.scaleMode === CONST.scaleModes.LINEAR); } @@ -324,7 +350,8 @@ var dy = (this.texture.trim ? this.texture.trim.y : 0) - (this.anchor.y * this.texture.trim.height); // Allow for pixel rounding - if (renderer.roundPixels) { + if (renderer.roundPixels) + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -337,7 +364,8 @@ dx = dx | 0; dy = dy | 0; } - else { + else + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -348,8 +376,10 @@ ); } - if (this.tint !== 0xFFFFFF) { - if (this.cachedTint !== this.tint) { + if (this.tint !== 0xFFFFFF) + { + if (this.cachedTint !== this.tint) + { this.cachedTint = this.tint; // TODO clean up caching - how to clean up the caches? @@ -368,7 +398,8 @@ this.texture.crop.height / resolution ); } - else { + else + { renderer.context.drawImage( this.texture.baseTexture.source, this.texture.crop.x, @@ -383,11 +414,13 @@ } } - for (var i = 0, j = this.children.length; i < j; i++) { + for (var i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -402,10 +435,12 @@ * @param frameId {String} The frame Id of the texture in the cache * @return {Sprite} A new Sprite using a texture from the texture cache matching the frameId */ -Sprite.fromFrame = function (frameId) { +Sprite.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache' + this); } @@ -420,6 +455,7 @@ * @param imageId {String} The image url of the texture * @return {Sprite} A new Sprite using a texture from the texture cache matching the image id */ -Sprite.fromImage = function (imageId, crossorigin, scaleMode) { +Sprite.fromImage = function (imageId, crossorigin, scaleMode) +{ return new Sprite(Texture.fromImage(imageId, crossorigin, scaleMode)); }; diff --git a/src/core/display/SpriteBatch.js b/src/core/display/SpriteBatch.js index 3187777..c196fef 100644 --- a/src/core/display/SpriteBatch.js +++ b/src/core/display/SpriteBatch.js @@ -12,7 +12,8 @@ * ```js * var container = new SpriteBatch(); * - * for(var i = 0; i < 100; ++i) { + * for(var i = 0; i < 100; ++i) + * { * var sprite = new PIXI.Sprite.fromImage("myImage.png"); * container.addChild(sprite); * } @@ -25,7 +26,8 @@ */ //TODO RENAME to PARTICLE CONTAINER? -function SpriteBatch() { +function SpriteBatch() +{ DisplayObjectContainer.call(this); } @@ -38,7 +40,8 @@ * * @private */ -SpriteBatch.prototype.updateTransform = function () { +SpriteBatch.prototype.updateTransform = function () +{ // TODO don't need to! this.displayObjectUpdateTransform(); // PIXI.DisplayObjectContainer.prototype.updateTransform.call( this ); @@ -50,8 +53,10 @@ * @param renderer {WebGLRenderer} The webgl renderer * @private */ -SpriteBatch.prototype.renderWebGL = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderWebGL = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -71,8 +76,10 @@ * @param renderer {CanvasRenderer} The canvas renderer * @private */ -SpriteBatch.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -84,10 +91,12 @@ this.displayObjectUpdateTransform(); - for (var i = 0; i < this.children.length; ++i) { + for (var i = 0; i < this.children.length; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -95,9 +104,11 @@ context.globalAlpha = this.worldAlpha * child.alpha; - if (child.rotation % (Math.PI * 2) === 0) { + if (child.rotation % (Math.PI * 2) === 0) + { // this is the fastest way to optimise! - if rotation is 0 then we can avoid any kind of setTransform call - if (isRotated) { + if (isRotated) + { context.setTransform( transform.a, transform.b, @@ -122,8 +133,10 @@ frame.height * child.scale.y ); } - else { - if (!isRotated) { + else + { + if (!isRotated) + { isRotated = true; } @@ -131,7 +144,8 @@ var childTransform = child.worldTransform; - if (renderer.roundPixels) { + if (renderer.roundPixels) + { context.setTransform( childTransform.a, childTransform.b, @@ -141,7 +155,8 @@ childTransform.ty | 0 ); } - else { + else + { context.setTransform( childTransform.a, childTransform.b, diff --git a/src/core/index.js b/src/core/index.js index 3954b6f..eb4a82b 100644 --- a/src/core/index.js +++ b/src/core/index.js @@ -58,11 +58,13 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRenderer: function (width, height, options, noWebGL) { + autoDetectRenderer: function (width, height, options, noWebGL) + { width = width || 800; height = height || 600; - if (!noWebGL && require('webgl-enabled')()) { + if (!noWebGL && require('webgl-enabled')()) + { return new core.WebGLRenderer(width, height, options); } @@ -87,7 +89,8 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRecommendedRenderer: function (width, height, options) { + autoDetectRecommendedRenderer: function (width, height, options) + { var isAndroid = /Android/i.test(navigator.userAgent); return core.autoDetectRenderer(width, height, options, isAndroid); diff --git a/src/core/math/Matrix.js b/src/core/math/Matrix.js index c2f87e2..2ff4848 100644 --- a/src/core/math/Matrix.js +++ b/src/core/math/Matrix.js @@ -10,7 +10,8 @@ * @class * @namespace PIXI */ -function Matrix() { +function Matrix() +{ /** * @member {number} * @default 1 @@ -63,7 +64,8 @@ * * @param array {number[]} The array that the matrix will be populated from. */ -Matrix.prototype.fromArray = function (array) { +Matrix.prototype.fromArray = function (array) +{ this.a = array[0]; this.b = array[1]; this.c = array[3]; @@ -78,14 +80,17 @@ * @param transpose {boolean} Whether we need to transpose the matrix or not * @return {number[]} the newly created array which contains the matrix */ -Matrix.prototype.toArray = function (transpose) { - if (!this.array) { +Matrix.prototype.toArray = function (transpose) +{ + if (!this.array) + { this.array = new Float32Array(9); } var array = this.array; - if (transpose) { + if (transpose) + { array[0] = this.a; array[1] = this.b; array[2] = 0; @@ -96,7 +101,8 @@ array[7] = this.ty; array[8] = 1; } - else { + else + { array[0] = this.a; array[1] = this.c; array[2] = this.tx; @@ -119,7 +125,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, transformed through this matrix */ -Matrix.prototype.apply = function (pos, newPos) { +Matrix.prototype.apply = function (pos, newPos) +{ newPos = newPos || new Point(); newPos.x = this.a * pos.x + this.c * pos.y + this.tx; @@ -136,7 +143,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, inverse-transformed through this matrix */ -Matrix.prototype.applyInverse = function (pos, newPos) { +Matrix.prototype.applyInverse = function (pos, newPos) +{ newPos = newPos || new Point(); var id = 1 / (this.a * this.d + this.c * -this.b); @@ -154,7 +162,8 @@ * @param {number} y * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.translate = function (x, y) { +Matrix.prototype.translate = function (x, y) +{ this.tx += x; this.ty += y; @@ -168,7 +177,8 @@ * @param {number} y The amount to scale vertically * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.scale = function (x, y) { +Matrix.prototype.scale = function (x, y) +{ this.a *= x; this.d *= y; this.c *= x; @@ -186,7 +196,8 @@ * @param {number} angle - The angle in radians. * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.rotate = function (angle) { +Matrix.prototype.rotate = function (angle) +{ var cos = Math.cos( angle ); var sin = Math.sin( angle ); @@ -210,7 +221,8 @@ * @param {Matrix} matrix * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.append = function (matrix) { +Matrix.prototype.append = function (matrix) +{ var a1 = this.a; var b1 = this.b; var c1 = this.c; @@ -232,7 +244,8 @@ * * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.identity = function () { +Matrix.prototype.identity = function () +{ this.a = 1; this.b = 0; this.c = 0; diff --git a/src/core/math/Point.js b/src/core/math/Point.js index 7565b2d..632f346 100644 --- a/src/core/math/Point.js +++ b/src/core/math/Point.js @@ -7,7 +7,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -function Point(x, y) { +function Point(x, y) +{ /** * @member {number} * @default 0 @@ -29,7 +30,8 @@ * * @return {Point} a copy of the point */ -Point.prototype.clone = function () { +Point.prototype.clone = function () +{ return new Point(this.x, this.y); }; @@ -40,7 +42,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -Point.prototype.set = function (x, y) { +Point.prototype.set = function (x, y) +{ this.x = x || 0; this.y = y || ( (y !== 0) ? this.x : 0 ) ; }; diff --git a/src/core/math/shapes/Circle.js b/src/core/math/shapes/Circle.js index 69cfdc9..4d76efc 100644 --- a/src/core/math/shapes/Circle.js +++ b/src/core/math/shapes/Circle.js @@ -10,7 +10,8 @@ * @param y {number} The Y coordinate of the center of this circle * @param radius {number} The radius of the circle */ -function Circle(x, y, radius) { +function Circle(x, y, radius) +{ /** * @member {number} * @default 0 @@ -46,7 +47,8 @@ * @method clone * @return {Circle} a copy of the Circle */ -Circle.prototype.clone = function () { +Circle.prototype.clone = function () +{ return new Circle(this.x, this.y, this.radius); }; @@ -58,8 +60,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Circle */ -Circle.prototype.contains = function (x, y) { - if (this.radius <= 0) { +Circle.prototype.contains = function (x, y) +{ + if (this.radius <= 0) + { return false; } @@ -79,6 +83,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Circle.prototype.getBounds = function () { +Circle.prototype.getBounds = function () +{ return new Rectangle(this.x - this.radius, this.y - this.radius, this.radius * 2, this.radius * 2); }; diff --git a/src/core/math/shapes/Ellipse.js b/src/core/math/shapes/Ellipse.js index 4f2d066..fefd01a 100644 --- a/src/core/math/shapes/Ellipse.js +++ b/src/core/math/shapes/Ellipse.js @@ -11,7 +11,8 @@ * @param width {number} The half width of this ellipse * @param height {number} The half height of this ellipse */ -function Ellipse(x, y, width, height) { +function Ellipse(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -53,7 +54,8 @@ * @method clone * @return {Ellipse} a copy of the ellipse */ -Ellipse.prototype.clone = function () { +Ellipse.prototype.clone = function () +{ return new Ellipse(this.x, this.y, this.width, this.height); }; @@ -65,8 +67,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coords are within this ellipse */ -Ellipse.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Ellipse.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } @@ -86,6 +90,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Ellipse.prototype.getBounds = function () { +Ellipse.prototype.getBounds = function () +{ return new Rectangle(this.x - this.width, this.y - this.height, this.width, this.height); }; diff --git a/src/core/math/shapes/Polygon.js b/src/core/math/shapes/Polygon.js index ae89148..fea6d37 100644 --- a/src/core/math/shapes/Polygon.js +++ b/src/core/math/shapes/Polygon.js @@ -10,16 +10,20 @@ * arguments passed can be flat x,y values e.g. `new Polygon(x,y, x,y, x,y, ...)` where `x` and `y` are * Numbers. */ -function Polygon(points) { +function Polygon(points) +{ //if points isn't an array, use arguments as the array - if (!(points instanceof Array)) { + if (!(points instanceof Array)) + { points = Array.prototype.slice.call(arguments); } //if this is a flat array of numbers, convert it to points - if (points[0] instanceof Point) { + if (points[0] instanceof Point) + { var p = []; - for (var i = 0, il = points.length; i < il; i++) { + for (var i = 0, il = points.length; i < il; i++) + { p.push(points[i].x, points[i].y); } @@ -51,7 +55,8 @@ * * @return {Polygon} a copy of the polygon */ -Polygon.prototype.clone = function () { +Polygon.prototype.clone = function () +{ return new Polygon(this.points.slice()); }; @@ -62,19 +67,22 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this polygon */ -Polygon.prototype.contains = function (x, y) { +Polygon.prototype.contains = function (x, y) +{ var inside = false; // use some raycasting to test hits // https://github.com/substack/point-in-polygon/blob/master/index.js var length = this.points.length / 2; - for (var i = 0, j = length - 1; i < length; j = i++) { + for (var i = 0, j = length - 1; i < length; j = i++) + { var xi = this.points[i * 2], yi = this.points[i * 2 + 1], xj = this.points[j * 2], yj = this.points[j * 2 + 1], intersect = ((yi > y) !== (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi); - if (intersect) { + if (intersect) + { inside = !inside; } } diff --git a/src/core/math/shapes/Rectangle.js b/src/core/math/shapes/Rectangle.js index 16ac62a..4008b68 100644 --- a/src/core/math/shapes/Rectangle.js +++ b/src/core/math/shapes/Rectangle.js @@ -10,7 +10,8 @@ * @param width {number} The overall width of this rectangle * @param height {number} The overall height of this rectangle */ -function Rectangle(x, y, width, height) { +function Rectangle(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -60,7 +61,8 @@ * * @return {Rectangle} a copy of the rectangle */ -Rectangle.prototype.clone = function () { +Rectangle.prototype.clone = function () +{ return new Rectangle(this.x, this.y, this.width, this.height); }; @@ -71,13 +73,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rectangle */ -Rectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Rectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/math/shapes/RoundedRectangle.js b/src/core/math/shapes/RoundedRectangle.js index 27d286e..7bf6411 100644 --- a/src/core/math/shapes/RoundedRectangle.js +++ b/src/core/math/shapes/RoundedRectangle.js @@ -11,7 +11,8 @@ * @param height {number} The overall height of this rounded rectangle * @param radius {number} Controls the radius of the rounded corners */ -function RoundedRectangle(x, y, width, height, radius) { +function RoundedRectangle(x, y, width, height, radius) +{ /** * @member {number} * @default 0 @@ -58,7 +59,8 @@ * * @return {RoundedRectangle} a copy of the rounded rectangle */ -RoundedRectangle.prototype.clone = function () { +RoundedRectangle.prototype.clone = function () +{ return new RoundedRectangle(this.x, this.y, this.width, this.height, this.radius); }; @@ -69,13 +71,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rounded Rectangle */ -RoundedRectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +RoundedRectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/primitives/Graphics.js b/src/core/primitives/Graphics.js index 261c534..e902d2a 100644 --- a/src/core/primitives/Graphics.js +++ b/src/core/primitives/Graphics.js @@ -16,7 +16,8 @@ * @extends DisplayObjectContainer * @namespace PIXI */ -function Graphics() { +function Graphics() +{ DisplayObjectContainer.call(this); this.renderable = true; @@ -154,16 +155,20 @@ * @private */ cacheAsBitmap: { - get: function () { + get: function () + { return this._cacheAsBitmap; }, - set: function (value) { + set: function (value) + { this._cacheAsBitmap = value; - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._generateCachedSprite(); } - else { + else + { this.destroyCachedSprite(); this.dirty = true; } @@ -176,7 +181,8 @@ * * @return {Graphics} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ var clone = new Graphics(); clone.renderable = this.renderable; @@ -192,7 +198,8 @@ clone.cachedSpriteDirty = this.cachedSpriteDirty; // copy graphics data - for (var i = 0; i < this.graphicsData.length; ++i) { + for (var i = 0; i < this.graphicsData.length; ++i) + { clone.graphicsData.push(this.graphicsData.clone()); } @@ -211,17 +218,21 @@ * @param alpha {number} alpha of the line to draw, will update the objects stored style * @return {Graphics} */ -Graphics.prototype.lineStyle = function (lineWidth, color, alpha) { +Graphics.prototype.lineStyle = function (lineWidth, color, alpha) +{ this.lineWidth = lineWidth || 0; this.lineColor = color || 0; this.lineAlpha = (arguments.length < 3) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length) + { // halfway through a line? start a new one! this.drawShape( new math.Polygon( this.currentPath.shape.points.slice(-2) )); } - else { + else + { // otherwise its empty so lets just set the line properties this.currentPath.lineWidth = this.lineWidth; this.currentPath.lineColor = this.lineColor; @@ -239,7 +250,8 @@ * @param y {number} the Y coordinate to move to * @return {Graphics} */ -Graphics.prototype.moveTo = function (x, y) { +Graphics.prototype.moveTo = function (x, y) +{ this.drawShape(new math.Polygon([x,y])); return this; @@ -253,7 +265,8 @@ * @param y {number} the Y coordinate to draw to * @return {Graphics} */ -Graphics.prototype.lineTo = function (x, y) { +Graphics.prototype.lineTo = function (x, y) +{ this.currentPath.shape.points.push(x, y); this.dirty = true; @@ -270,13 +283,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -285,7 +302,8 @@ n = 20, points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { this.moveTo(0, 0); } @@ -293,7 +311,8 @@ var fromY = points[points.length-1]; var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; xa = fromX + ( (cpX - fromX) * j ); @@ -319,13 +338,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -342,7 +365,8 @@ var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; dt = (1 - j); @@ -373,13 +397,17 @@ * @param radius {number} The radius of the arc * @return {Graphics} */ -Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points.push(x1, y1); } } - else { + else + { this.moveTo(x1, y1); } @@ -392,12 +420,15 @@ b2 = x2 - x1, mm = Math.abs(a1 * b2 - b1 * a2); - if (mm < 1.0e-8 || radius === 0) { - if (points[points.length-2] !== x1 || points[points.length-1] !== y1) { + if (mm < 1.0e-8 || radius === 0) + { + if (points[points.length-2] !== x1 || points[points.length-1] !== y1) + { points.push(x1, y1); } } - else { + else + { var dd = a1 * a1 + b1 * b1, cc = a2 * a2 + b2 * b2, tt = a1 * a2 + b1 * b2, @@ -433,42 +464,51 @@ * @param anticlockwise {boolean} Optional. Specifies whether the drawing should be counterclockwise or clockwise. False is default, and indicates clockwise, while true indicates counter-clockwise. * @return {Graphics} */ -Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) { +Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) +{ var startX = cx + Math.cos(startAngle) * radius; var startY = cy + Math.sin(startAngle) * radius; var points; // TODO - This if-else makes no sense. It uses currentPath in the else where it doesn't exist... - if (this.currentPath) { + if (this.currentPath) + { points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { points.push(startX, startY); } - else if (points[points.length-2] !== startX || points[points.length-1] !== startY) { + else if (points[points.length-2] !== startX || points[points.length-1] !== startY) + { points.push(startX, startY); } } - else { + else + { this.moveTo(startX, startY); points = this.currentPath.shape.points; } - if (startAngle === endAngle) { + if (startAngle === endAngle) + { return this; } - if (!anticlockwise && endAngle <= startAngle) { + if (!anticlockwise && endAngle <= startAngle) + { endAngle += Math.PI * 2; } - else if (anticlockwise && startAngle <= endAngle) { + else if (anticlockwise && startAngle <= endAngle) + { startAngle += Math.PI * 2; } var sweep = anticlockwise ? (startAngle - endAngle) *-1 : (endAngle - startAngle); var segs = (Math.abs(sweep)/ (Math.PI * 2)) * 40; - if (sweep === 0) { + if (sweep === 0) + { return this; } @@ -482,7 +522,8 @@ var remainder = ( segMinus % 1 ) / segMinus; - for (var i = 0; i <= segMinus; ++i) { + for (var i = 0; i <= segMinus; ++i) + { var real = i + remainder * i; var angle = ((theta) + startAngle + (theta2 * real)); @@ -506,13 +547,16 @@ * @param alpha {number} the alpha of the fill * @return {Graphics} */ -Graphics.prototype.beginFill = function (color, alpha) { +Graphics.prototype.beginFill = function (color, alpha) +{ this.filling = true; this.fillColor = color || 0; this.fillAlpha = (alpha === undefined) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length <= 2) + { this.currentPath.fill = this.filling; this.currentPath.fillColor = this.fillColor; this.currentPath.fillAlpha = this.fillAlpha; @@ -526,7 +570,8 @@ * * @return {Graphics} */ -Graphics.prototype.endFill = function () { +Graphics.prototype.endFill = function () +{ this.filling = false; this.fillColor = null; this.fillAlpha = 1; @@ -542,7 +587,8 @@ * @param height {number} The height of the rectangle * @return {Graphics} */ -Graphics.prototype.drawRect = function ( x, y, width, height ) { +Graphics.prototype.drawRect = function ( x, y, width, height ) +{ this.drawShape(new math.Rectangle(x,y, width, height)); return this; @@ -556,7 +602,8 @@ * @param height {number} The height of the rectangle * @param radius {number} Radius of the rectangle corners */ -Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) { +Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) +{ this.drawShape(new math.RoundedRectangle(x, y, width, height, radius)); return this; @@ -570,7 +617,8 @@ * @param radius {number} The radius of the circle * @return {Graphics} */ -Graphics.prototype.drawCircle = function (x, y, radius) { +Graphics.prototype.drawCircle = function (x, y, radius) +{ this.drawShape(new math.Circle(x,y, radius)); return this; @@ -585,7 +633,8 @@ * @param height {number} The half height of the ellipse * @return {Graphics} */ -Graphics.prototype.drawEllipse = function (x, y, width, height) { +Graphics.prototype.drawEllipse = function (x, y, width, height) +{ this.drawShape(new math.Ellipse(x, y, width, height)); return this; @@ -597,8 +646,10 @@ * @param path {Array} The path data used to construct the polygon. * @return {Graphics} */ -Graphics.prototype.drawPolygon = function (path) { - if (!(path instanceof Array)) { +Graphics.prototype.drawPolygon = function (path) +{ + if (!(path instanceof Array)) + { path = Array.prototype.slice.call(arguments); } @@ -612,7 +663,8 @@ * * @return {Graphics} */ -Graphics.prototype.clear = function () { +Graphics.prototype.clear = function () +{ this.lineWidth = 0; this.filling = false; @@ -631,7 +683,8 @@ * @param scaleMode {number} Should be one of the scaleMode consts * @return {Texture} a texture of the graphics object */ -Graphics.prototype.generateTexture = function (resolution, scaleMode) { +Graphics.prototype.generateTexture = function (resolution, scaleMode) +{ resolution = resolution || 1; var bounds = this.getBounds(); @@ -655,17 +708,21 @@ * * @param renderer {WebGLRenderer} */ -Graphics.prototype._renderWebGL = function (renderer) { +Graphics.prototype._renderWebGL = function (renderer) +{ // if the sprite is not visible or the alpha is 0 then no need to render this element - if (this.isMask === true) { + if (this.isMask === true) + { return; } // this code may still be needed so leaving for now.. - // + // /* - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture on the gpu too! @@ -681,17 +738,24 @@ return; } - */ - - // check if the webgl graphic needs to be updated - if (this.glDirty) { - this.dirty = true; - this.glDirty = false; - } + else */ - renderer.setObjectRendererer(renderer.graphicsRenderer); - renderer.graphicsRenderer.render(this); + renderer.spriteBatch.stop(); + renderer.blendModeManager.setBlendMode(this.blendMode); + // check blend mode + renderer.blendModeManager.setBlendMode( this.blendMode ); + + // check if the webgl graphic needs to be updated + if (this.glDirty) + { + this.dirty = true; + this.glDirty = false; + } + + WebGLGraphics.renderGraphics(this, renderer); + + renderer.spriteBatch.start(); }; /** @@ -700,14 +764,18 @@ * @param renderer {CanvasRenderer} * @private */ -Graphics.prototype.renderCanvas = function (renderer) { +Graphics.prototype.renderCanvas = function (renderer) +{ // 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.isMask === true) { + if (!this.visible || this.alpha <= 0 || this.isMask === true) + { return; } - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture @@ -723,16 +791,19 @@ return; } - else { + else + { var context = renderer.context; var transform = this.worldTransform; - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } @@ -748,11 +819,13 @@ CanvasGraphics.renderGraphics(this, context); - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } } @@ -763,13 +836,16 @@ * * @return {Rectangle} the rectangular bounding area */ -Graphics.prototype.getBounds = function (matrix) { +Graphics.prototype.getBounds = function (matrix) +{ // return an empty object if the item is a mask! - if (this.isMask) { + if (this.isMask) + { return math.Rectangle.EMPTY; } - if (this.dirty) { + if (this.dirty) + { this.updateLocalBounds(); this.glDirty = true; @@ -841,23 +917,27 @@ * Update the bounds of the object * */ -Graphics.prototype.updateLocalBounds = function () { +Graphics.prototype.updateLocalBounds = function () +{ var minX = Infinity; var maxX = -Infinity; var minY = Infinity; var maxY = -Infinity; - if (this.graphicsData.length) { + if (this.graphicsData.length) + { var shape, points, x, y, w, h; - for (var i = 0; i < this.graphicsData.length; i++) { + for (var i = 0; i < this.graphicsData.length; i++) + { var data = this.graphicsData[i]; var type = data.type; var lineWidth = data.lineWidth; shape = data.shape; - if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) { + if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) + { x = shape.x - lineWidth/2; y = shape.y - lineWidth/2; w = shape.width + lineWidth; @@ -869,7 +949,8 @@ minY = y < minY ? y : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.CIRC) { + else if (type === CONST.SHAPES.CIRC) + { x = shape.x; y = shape.y; w = shape.radius + lineWidth/2; @@ -881,7 +962,8 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.ELIP) { + else if (type === CONST.SHAPES.ELIP) + { x = shape.x; y = shape.y; w = shape.width + lineWidth/2; @@ -893,11 +975,13 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else { + else + { // POLY points = shape.points; - for (var j = 0; j < points.length; j += 2) { + for (var j = 0; j < points.length; j += 2) + { x = points[j]; y = points[j+1]; @@ -910,7 +994,8 @@ } } } - else { + else + { minX = 0; maxX = 0; minY = 0; @@ -931,10 +1016,12 @@ * * @private */ -Graphics.prototype._generateCachedSprite = function () { +Graphics.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { var canvasBuffer = new CanvasBuffer(bounds.width, bounds.height); var texture = Texture.fromCanvas(canvasBuffer.canvas); @@ -943,7 +1030,8 @@ this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.buffer.resize(bounds.width, bounds.height); } @@ -968,7 +1056,8 @@ * * @private */ -Graphics.prototype.updateCachedSpriteTexture = function () { +Graphics.prototype.updateCachedSpriteTexture = function () +{ var cachedSprite = this._cachedSprite; var texture = cachedSprite.texture; var canvas = cachedSprite.buffer.canvas; @@ -989,7 +1078,8 @@ * Destroys a previous cached sprite. * */ -Graphics.prototype.destroyCachedSprite = function () { +Graphics.prototype.destroyCachedSprite = function () +{ this._cachedSprite.texture.destroy(true); // let the gc collect the unused sprite @@ -1003,10 +1093,13 @@ * @param {Circle|Rectangle|Ellipse|Line|Polygon} shape The Shape object to draw. * @return {GraphicsData} The generated GraphicsData object. */ -Graphics.prototype.drawShape = function (shape) { - if (this.currentPath) { +Graphics.prototype.drawShape = function (shape) +{ + if (this.currentPath) + { // check current path! - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath.shape.points.length <= 2) + { this.graphicsData.pop(); } } @@ -1017,7 +1110,8 @@ this.graphicsData.push(data); - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { data.shape.closed = this.filling; this.currentPath = data; } diff --git a/src/core/primitives/GraphicsData.js b/src/core/primitives/GraphicsData.js index 99decbe..788f6f2 100644 --- a/src/core/primitives/GraphicsData.js +++ b/src/core/primitives/GraphicsData.js @@ -4,7 +4,8 @@ * @class * @namespace PIXI */ -function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) { +function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) +{ this.lineWidth = lineWidth; this.lineColor = lineColor; this.lineAlpha = lineAlpha; @@ -27,7 +28,8 @@ * * @return {GraphicsData} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ return new GraphicsData( this.lineWidth, this.lineColor, diff --git a/src/core/renderers/canvas/CanvasRenderer.js b/src/core/renderers/canvas/CanvasRenderer.js index 15a0978..7aebd44 100644 --- a/src/core/renderers/canvas/CanvasRenderer.js +++ b/src/core/renderers/canvas/CanvasRenderer.js @@ -17,17 +17,22 @@ * @param [options.resolution=1] {number} the resolution of the renderer retina would be 2 * @param [options.clearBeforeRender=true] {boolean} This sets if the CanvasRenderer will clear the canvas or not before the new render pass. */ -function CanvasRenderer(width, height, options) { +function CanvasRenderer(width, height, options) +{ utils.sayHello('Canvas'); - if (options) { - for (var i in CONST.defaultRenderOptions) { - if (typeof options[i] === 'undefined') { + if (options) + { + for (var i in CONST.defaultRenderOptions) + { + if (typeof options[i] === 'undefined') + { options[i] = CONST.defaultRenderOptions[i]; } } } - else { + else + { options = CONST.defaultRenderOptions; } @@ -156,19 +161,24 @@ this.smoothProperty = null; - if (this.context.imageSmoothingEnabled) { + if (this.context.imageSmoothingEnabled) + { this.smoothProperty = 'imageSmoothingEnabled'; } - else if (this.context.webkitImageSmoothingEnabled) { + else if (this.context.webkitImageSmoothingEnabled) + { this.smoothProperty = 'webkitImageSmoothingEnabled'; } - else if (this.context.mozImageSmoothingEnabled) { + else if (this.context.mozImageSmoothingEnabled) + { this.smoothProperty = 'mozImageSmoothingEnabled'; } - else if (this.context.oImageSmoothingEnabled) { + else if (this.context.oImageSmoothingEnabled) + { this.smoothProperty = 'oImageSmoothingEnabled'; } - else if (this.context.msImageSmoothingEnabled) { + else if (this.context.msImageSmoothingEnabled) + { this.smoothProperty = 'msImageSmoothingEnabled'; } @@ -193,10 +203,12 @@ * @memberof CanvasRenderer# */ backgroundColor: { - get: function () { + get: function () + { return this._backgroundColor; }, - set: function (val) { + set: function (val) + { this._backgroundColor = val; this._backgroundColorString = utils.hex2string(val); } @@ -208,7 +220,8 @@ * * @param object {DisplayObject} the object to be rendered */ -CanvasRenderer.prototype.render = function (object) { +CanvasRenderer.prototype.render = function (object) +{ object.updateTransform(); this.context.setTransform(1,0,0,1,0,0); @@ -218,16 +231,20 @@ this.currentBlendMode = CONST.blendModes.NORMAL; this.context.globalCompositeOperation = this.blendModes[CONST.blendModes.NORMAL]; - if (navigator.isCocoonJS && this.view.screencanvas) { + if (navigator.isCocoonJS && this.view.screencanvas) + { this.context.fillStyle = 'black'; this.context.clear(); } - if (this.clearBeforeRender) { - if (this.transparent) { + if (this.clearBeforeRender) + { + if (this.transparent) + { this.context.clearRect(0, 0, this.width, this.height); } - else { + else + { this.context.fillStyle = this._backgroundColorString; this.context.fillRect(0, 0, this.width , this.height); } @@ -241,8 +258,10 @@ * * @param [removeView=false] {boolean} Removes the Canvas element from the DOM. */ -CanvasRenderer.prototype.destroy = function (removeView) { - if (removeView && this.view.parent) { +CanvasRenderer.prototype.destroy = function (removeView) +{ + if (removeView && this.view.parent) + { this.view.parent.removeChild(this.view); } @@ -257,14 +276,16 @@ * @param width {number} the new width of the canvas view * @param height {number} the new height of the canvas view */ -CanvasRenderer.prototype.resize = function (width, height) { +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) { + if (this.autoResize) + { this.view.style.width = this.width / this.resolution + 'px'; this.view.style.height = this.height / this.resolution + 'px'; } @@ -276,7 +297,8 @@ * @param displayObject {DisplayObject} The displayObject to render * @private */ -CanvasRenderer.prototype.renderDisplayObject = function (displayObject) { +CanvasRenderer.prototype.renderDisplayObject = function (displayObject) +{ displayObject.renderCanvas(this); }; @@ -285,11 +307,14 @@ * * @private */ -CanvasRenderer.prototype._mapBlendModes = function () { - if (!this.blendModes) { +CanvasRenderer.prototype._mapBlendModes = function () +{ + if (!this.blendModes) + { this.blendModes = {}; - if (utils.canUseNewCanvasBlendModes()) { + if (utils.canUseNewCanvasBlendModes()) + { this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? this.blendModes[CONST.blendModes.MULTIPLY] = 'multiply'; @@ -308,7 +333,8 @@ this.blendModes[CONST.blendModes.COLOR] = 'color'; this.blendModes[CONST.blendModes.LUMINOSITY] = 'luminosity'; } - else { + else + { // this means that the browser does not support the cool new blend modes in canvas 'cough' ie 'cough' this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? diff --git a/src/core/renderers/canvas/utils/CanvasBuffer.js b/src/core/renderers/canvas/utils/CanvasBuffer.js index ebe5d47..b183a66 100644 --- a/src/core/renderers/canvas/utils/CanvasBuffer.js +++ b/src/core/renderers/canvas/utils/CanvasBuffer.js @@ -6,7 +6,8 @@ * @param width {number} the width for the newly created canvas * @param height {number} the height for the newly created canvas */ -function CanvasBuffer(width, height) { +function CanvasBuffer(width, height) +{ /** * The Canvas object that belongs to this CanvasBuffer. * @@ -36,10 +37,12 @@ * @memberof CanvasBuffer# */ width: { - get: function () { + get: function () + { return this.canvas.width; }, - set: function (val) { + set: function (val) + { this.canvas.width = val; } }, @@ -50,10 +53,12 @@ * @memberof CanvasBuffer# */ height: { - get: function () { + get: function () + { return this.canvas.height; }, - set: function (val) { + set: function (val) + { this.canvas.height = val; } } @@ -64,7 +69,8 @@ * * @private */ -CanvasBuffer.prototype.clear = function () { +CanvasBuffer.prototype.clear = function () +{ this.context.setTransform(1, 0, 0, 1, 0, 0); this.context.clearRect(0,0, this.canvas.width, this.canvas.height); }; @@ -75,7 +81,8 @@ * @param width {number} the new width of the canvas * @param height {number} the new height of the canvas */ -CanvasBuffer.prototype.resize = function (width, height) { +CanvasBuffer.prototype.resize = function (width, height) +{ this.canvas.width = width; this.canvas.height = height; }; diff --git a/src/core/renderers/canvas/utils/CanvasGraphics.js b/src/core/renderers/canvas/utils/CanvasGraphics.js index c7eaa2a..3f2a91f 100644 --- a/src/core/renderers/canvas/utils/CanvasGraphics.js +++ b/src/core/renderers/canvas/utils/CanvasGraphics.js @@ -13,15 +13,18 @@ * @param graphics {Graphics} the actual graphics object to render * @param context {CanvasRenderingContext2D} the 2d drawing method of the canvas */ -CanvasGraphics.renderGraphics = function (graphics, context) { +CanvasGraphics.renderGraphics = function (graphics, context) +{ var worldAlpha = graphics.worldAlpha; - if (graphics.dirty) { + if (graphics.dirty) + { this.updateGraphicsTint(graphics); graphics.dirty = false; } - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; @@ -30,69 +33,82 @@ context.lineWidth = data.lineWidth; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { context.beginPath(); var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } - if (shape.closed) { + if (shape.closed) + { context.lineTo(points[0], points[1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fillRect(shape.x, shape.y, shape.width, shape.height); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.strokeRect(shape.x, shape.y, shape.width, shape.height); } } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.beginPath(); context.arc(shape.x, shape.y, shape.radius,0,2*Math.PI); context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas var w = shape.width * 2; @@ -119,18 +135,21 @@ context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; var width = shape.width; @@ -152,13 +171,15 @@ context.quadraticCurveTo(rx, ry, rx, ry + radius); context.closePath(); - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); @@ -174,45 +195,54 @@ * @param graphics {Graphics} the graphics which will be used as a mask * @param context {CanvasRenderingContext2D} the context 2d method of the canvas */ -CanvasGraphics.renderGraphicsMask = function (graphics, context) { +CanvasGraphics.renderGraphicsMask = function (graphics, context) +{ var len = graphics.graphicsData.length; - if (len === 0) { + if (len === 0) + { return; } context.beginPath(); - for (var i = 0; i < len; i++) { + for (var i = 0; i < len; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { context.rect(shape.x, shape.y, shape.width, shape.height); context.closePath(); } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.arc(shape.x, shape.y, shape.radius, 0, 2 * Math.PI); context.closePath(); } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas @@ -237,7 +267,8 @@ context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); context.closePath(); } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; @@ -262,8 +293,10 @@ } }; -CanvasGraphics.updateGraphicsTint = function (graphics) { - if (graphics.tint === 0xFFFFFF) { +CanvasGraphics.updateGraphicsTint = function (graphics) +{ + if (graphics.tint === 0xFFFFFF) + { return; } @@ -271,7 +304,8 @@ var tintG = (graphics.tint >> 8 & 0xFF) / 255; var tintB = (graphics.tint & 0xFF)/ 255; - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var fillColor = data.fillColor | 0; diff --git a/src/core/display/DisplayObject.js b/src/core/display/DisplayObject.js index 66ebc3c..20e778c 100644 --- a/src/core/display/DisplayObject.js +++ b/src/core/display/DisplayObject.js @@ -7,7 +7,8 @@ * @class * @namespace PIXI */ -function DisplayObject() { +function DisplayObject() +{ /** * The coordinate of the object relative to the local coordinates of the parent. * @@ -152,10 +153,12 @@ * @memberof DisplayObject# */ x: { - get: function () { + get: function () + { return this.position.x; }, - set: function (value) { + set: function (value) + { this.position.x = value; } }, @@ -167,10 +170,12 @@ * @memberof DisplayObject# */ y: { - get: function () { + get: function () + { return this.position.y; }, - set: function (value) { + set: function (value) + { this.position.y = value; } }, @@ -183,11 +188,13 @@ * @readonly */ worldVisible: { - get: function () { + get: function () + { var item = this; do { - if (!item.visible) { + if (!item.visible) + { return false; } @@ -207,17 +214,21 @@ * @memberof DisplayObject# */ mask: { - get: function () { + get: function () + { return this._mask; }, - set: function (value) { - if (this._mask) { + set: function (value) + { + if (this._mask) + { this._mask.isMask = false; } this._mask = value; - if (this._mask) { + if (this._mask) + { this._mask.isMask = true; } } @@ -232,18 +243,23 @@ * @memberof DisplayObject# */ filters: { - get: function () { + get: function () + { return this._filters; }, - set: function (value) { - if (value) { + set: function (value) + { + if (value) + { // now put all the passes in one place.. var passes = []; - for (var i = 0; i < value.length; i++) { + for (var i = 0; i < value.length; i++) + { var filterPasses = value[i].passes; - for (var j = 0; j < filterPasses.length; j++) { + for (var j = 0; j < filterPasses.length; j++) + { passes.push(filterPasses[j]); } } @@ -264,8 +280,9 @@ * * @private */ -DisplayObject.prototype.updateTransform = function () { - +DisplayObject.prototype.updateTransform = function () +{ + // create some matrix refs for easy access var pt = this.parent.worldTransform; var wt = this.worldTransform; @@ -274,9 +291,11 @@ var a, b, c, d, tx, ty; // so if rotation is between 0 then we can simplify the multiplication process.. - if (this.rotation % math.PI_2) { + if (this.rotation % math.PI_2) + { // 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) { + if (this.rotation !== this.rotationCache) + { this.rotationCache = this.rotation; this._sr = Math.sin(this.rotation); this._cr = Math.cos(this.rotation); @@ -291,7 +310,8 @@ ty = this.position.y; // check for pivot.. not often used so geared towards that fact! - if (this.pivot.x || this.pivot.y) { + 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; } @@ -304,7 +324,8 @@ wt.tx = tx * pt.a + ty * pt.c + pt.tx; wt.ty = tx * pt.b + ty * pt.d + pt.ty; } - else { + else + { // lets do the fast version as we know there is no rotation.. a = this.scale.x; d = this.scale.y; @@ -333,7 +354,8 @@ * @param matrix {Matrix} * @return {Rectangle} the rectangular bounding area */ -DisplayObject.prototype.getBounds = function (/* matrix */) { +DisplayObject.prototype.getBounds = function (/* matrix */) +{ return math.Rectangle.EMPTY; }; @@ -342,7 +364,8 @@ * * @return {Rectangle} the rectangular bounding area */ -DisplayObject.prototype.getLocalBounds = function () { +DisplayObject.prototype.getLocalBounds = function () +{ return this.getBounds(math.Matrix.IDENTITY); }; @@ -352,7 +375,8 @@ * @param position {Point} The world origin to calculate from * @return {Point} A point object representing the position of this object */ -DisplayObject.prototype.toGlobal = function (position) { +DisplayObject.prototype.toGlobal = function (position) +{ // don't need to u[date the lot this.displayObjectUpdateTransform(); return this.worldTransform.apply(position); @@ -365,8 +389,10 @@ * @param [from] {DisplayObject} The DisplayObject to calculate the global position from * @return {Point} A point object representing the position of this object */ -DisplayObject.prototype.toLocal = function (position, from) { - if (from) { +DisplayObject.prototype.toLocal = function (position, from) +{ + if (from) + { position = from.toGlobal(position); } @@ -381,7 +407,8 @@ * @param renderer {WebGLRenderer} The renderer * @private */ -DisplayObject.prototype.renderWebGL = function (/* renderer */) { +DisplayObject.prototype.renderWebGL = function (/* renderer */) +{ // OVERWRITE; }; @@ -391,6 +418,7 @@ * @param renderer {CanvasRenderer} The renderer * @private */ -DisplayObject.prototype.renderCanvas = function (/* renderer */) { +DisplayObject.prototype.renderCanvas = function (/* renderer */) +{ // OVERWRITE; }; diff --git a/src/core/display/DisplayObjectContainer.js b/src/core/display/DisplayObjectContainer.js index 689f40b..4625ee8 100644 --- a/src/core/display/DisplayObjectContainer.js +++ b/src/core/display/DisplayObjectContainer.js @@ -12,7 +12,8 @@ * @extends DisplayObject * @namespace PIXI */ -function DisplayObjectContainer() { +function DisplayObjectContainer() +{ DisplayObject.call(this); /** @@ -47,17 +48,21 @@ * @memberof DisplayObjectContainer# */ width: { - get: function () { + get: function () + { return this.scale.x * this.getLocalBounds().width; }, - set: function (value) { + set: function (value) + { var width = this.getLocalBounds().width; - if(width !== 0) { + if(width !== 0) + { this.scale.x = value / width; } - else { + else + { this.scale.x = 1; } @@ -73,17 +78,21 @@ * @memberof DisplayObjectContainer# */ height: { - get: function () { + get: function () + { return this.scale.y * this.getLocalBounds().height; }, - set: function (value) { + set: function (value) + { var height = this.getLocalBounds().height; - if (height !== 0) { + if (height !== 0) + { this.scale.y = value / height ; } - else { + else + { this.scale.y = 1; } @@ -100,18 +109,23 @@ * @memberof DisplayObject# */ cacheAsBitmap: { - get: function () { + get: function () + { return this._cacheAsBitmap; }, - set: function (value) { - if (this._cacheAsBitmap === value) { + set: function (value) + { + if (this._cacheAsBitmap === value) + { return; } - if (value) { + if (value) + { this._generateCachedSprite(); } - else { + else + { this._destroyCachedSprite(); } @@ -126,7 +140,8 @@ * @param child {DisplayObject} The DisplayObject to add to the container * @return {DisplayObject} The child that was added. */ -DisplayObjectContainer.prototype.addChild = function (child) { +DisplayObjectContainer.prototype.addChild = function (child) +{ return this.addChildAt(child, this.children.length); }; @@ -137,14 +152,18 @@ * @param index {Number} The index to place the child in * @return {DisplayObject} The child that was added. */ -DisplayObjectContainer.prototype.addChildAt = function (child, index) { +DisplayObjectContainer.prototype.addChildAt = function (child, index) +{ // prevent adding self as child - if (child === this) { + if (child === this) + { return; } - if (index >= 0 && index <= this.children.length) { - if (child.parent) { + if (index >= 0 && index <= this.children.length) + { + if (child.parent) + { child.parent.removeChild(child); } @@ -154,7 +173,8 @@ return child; } - else { + else + { throw new Error(child + 'addChildAt: The index '+ index +' supplied is out of bounds ' + this.children.length); } }; @@ -165,15 +185,18 @@ * @param child {DisplayObject} * @param child2 {DisplayObject} */ -DisplayObjectContainer.prototype.swapChildren = function (child, child2) { - if (child === child2) { +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) { + if (index1 < 0 || index2 < 0) + { throw new Error('swapChildren: Both the supplied DisplayObjects must be a child of the caller.'); } @@ -187,10 +210,12 @@ * @param child {DisplayObject} The DisplayObject instance to identify * @return {Number} The index position of the child display object to identify */ -DisplayObjectContainer.prototype.getChildIndex = function (child) { +DisplayObjectContainer.prototype.getChildIndex = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { throw new Error('The supplied DisplayObject must be a child of the caller'); } @@ -203,8 +228,10 @@ * @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 */ -DisplayObjectContainer.prototype.setChildIndex = function (child, index) { - if (index < 0 || index >= this.children.length) { +DisplayObjectContainer.prototype.setChildIndex = function (child, index) +{ + if (index < 0 || index >= this.children.length) + { throw new Error('The supplied index is out of bounds'); } @@ -220,8 +247,10 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child at the given index, if any. */ -DisplayObjectContainer.prototype.getChildAt = function (index) { - if (index < 0 || index >= this.children.length) { +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'); } @@ -234,10 +263,12 @@ * @param child {DisplayObject} The DisplayObject to remove * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChild = function (child) { +DisplayObjectContainer.prototype.removeChild = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { return; } @@ -250,7 +281,8 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChildAt = function (index) { +DisplayObjectContainer.prototype.removeChildAt = function (index) +{ var child = this.getChildAt(index); child.parent = null; @@ -265,24 +297,29 @@ * @param beginIndex {Number} The beginning position. Default value is 0. * @param endIndex {Number} The ending position. Default value is size of the container. */ -DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) { +DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) +{ var begin = beginIndex || 0; var end = typeof endIndex === 'number' ? endIndex : this.children.length; var range = end - begin; - if (range > 0 && range <= end) { + if (range > 0 && range <= end) + { var removed = this.children.splice(begin, range); - for (var i = 0; i < removed.length; ++i) { + for (var i = 0; i < removed.length; ++i) + { removed[i].parent = null; } return removed; } - else if (range === 0 && this.children.length === 0) { + else if (range === 0 && this.children.length === 0) + { return []; } - else { + else + { throw new RangeError('removeChildren: numeric values are outside the acceptable range.'); } }; @@ -291,7 +328,8 @@ * Generates and updates the cached sprite for this object. * */ -DisplayObjectContainer.prototype.updateCachedSprite = function () { +DisplayObjectContainer.prototype.updateCachedSprite = function () +{ this._generateCachedSprite(); }; @@ -304,7 +342,8 @@ * @param renderer {CanvasRenderer|WebGLRenderer} The renderer used to generate the texture. * @return {Texture} a texture of the graphics object */ -DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) { +DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) +{ var bounds = this.getLocalBounds(); var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0, renderer, scaleMode, resolution); @@ -322,18 +361,22 @@ * * @private */ -DisplayObjectContainer.prototype.updateTransform = function () { - if (!this.visible) { +DisplayObjectContainer.prototype.updateTransform = function () +{ + if (!this.visible) + { return; } this.displayObjectUpdateTransform(); - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { return; } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } }; @@ -346,8 +389,10 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getBounds = function () { - if (this.children.length === 0) { +DisplayObjectContainer.prototype.getBounds = function () +{ + if (this.children.length === 0) + { return math.Rectangle.EMPTY; } @@ -365,10 +410,12 @@ var childVisible = false; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -386,7 +433,8 @@ maxY = maxY > childMaxY ? maxY : childMaxY; } - if (!childVisible) { + if (!childVisible) + { return math.Rectangle.EMPTY; } @@ -407,12 +455,14 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getLocalBounds = function () { +DisplayObjectContainer.prototype.getLocalBounds = function () +{ var matrixCache = this.worldTransform; this.worldTransform = math.Matrix.IDENTITY; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } @@ -428,13 +478,16 @@ * * @param renderer {WebGLRenderer} The renderer */ -DisplayObjectContainer.prototype.renderWebGL = function (renderer) { +DisplayObjectContainer.prototype.renderWebGL = function (renderer) +{ // if the object is not visible or the alpha is 0 then no need to render this element - if (!this.visible || this.alpha <= 0) { + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } @@ -442,14 +495,17 @@ var i, j; // do a quick check to see if this element has a mask or a filter. - if (this._mask || this._filters) { + if (this._mask || this._filters) + { // push filter first as we need to ensure the stencil buffer is correct for any masking - if (this._filters) { + if (this._filters) + { renderer.spriteBatch.flush(); renderer.filterManager.pushFilter(this._filterBlock); } - if (this._mask) { + if (this._mask) + { renderer.spriteBatch.stop(); renderer.maskManager.pushMask(this.mask, renderer); renderer.spriteBatch.start(); @@ -459,36 +515,42 @@ this._renderWebGL(renderer); // now loop through the children and make sure they get rendered - for (i = 0, j = this.children.length; i < j; i++) { + for (i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderWebGL(renderer); } // time to stop the sprite batch as either a mask element or a filter draw will happen next renderer.spriteBatch.stop(); - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(this._mask, renderer); } - if (this._filters) { + if (this._filters) + { renderer.filterManager.popFilter(); } renderer.spriteBatch.start(); } - else { + else + { this._renderWebGL(renderer); // simple render children! - for (i = 0, j = this.children.length; i < j; ++i) { + for (i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderWebGL(renderer); } } }; -DisplayObjectContainer.prototype._renderWebGL = function (renderer) { +DisplayObjectContainer.prototype._renderWebGL = function (renderer) +{ // this is where content itself gets renderd.. @@ -499,25 +561,31 @@ * * @param renderer {CanvasRenderer} The renderer */ -DisplayObjectContainer.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0) { +DisplayObjectContainer.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -528,13 +596,16 @@ * @param renderer {WebGLRenderer|CanvasRenderer} The renderer * @private */ -DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) { +DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) +{ this._cachedSprite.worldAlpha = this.worldAlpha; - if (renderer.gl) { + if (renderer.gl) + { this._cachedSprite.renderWebGL(renderer); } - else { + else + { this._cachedSprite.renderCanvas(renderer); } }; @@ -544,10 +615,12 @@ * * @private */ -DisplayObjectContainer.prototype._generateCachedSprite = function () { +DisplayObjectContainer.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { // TODO - RenderTexture now *requires* a renderer instance, so this is like broken // because `renderer` isn't actually in scope here :P var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0); @@ -555,7 +628,8 @@ this._cachedSprite = new Sprite(renderTexture); this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.texture.resize(bounds.width | 0, bounds.height | 0); } @@ -580,8 +654,10 @@ * * @private */ -DisplayObjectContainer.prototype._destroyCachedSprite = function () { - if (!this._cachedSprite) { +DisplayObjectContainer.prototype._destroyCachedSprite = function () +{ + if (!this._cachedSprite) + { return; } diff --git a/src/core/display/Sprite.js b/src/core/display/Sprite.js index 707da24..5862aef 100644 --- a/src/core/display/Sprite.js +++ b/src/core/display/Sprite.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param texture {Texture} The texture for this sprite */ -function Sprite(texture) { +function Sprite(texture) +{ DisplayObjectContainer.call(this); /** @@ -85,12 +86,14 @@ this.texture = texture || Texture.EMPTY; } -Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) { +Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) +{ DisplayObjectContainer.prototype.destroy.call(this); this.anchor = null; - if (destroyTexture) { + if (destroyTexture) + { this._texture.destroy(destroyBaseTexture); } @@ -111,10 +114,12 @@ * @memberof Sprite# */ width: { - get: function () { + get: function () + { return this.scale.x * this.texture.frame.width; }, - set: function (value) { + set: function (value) + { this.scale.x = value / this.texture.frame.width; this._width = value; } @@ -127,10 +132,12 @@ * @memberof Sprite# */ height: { - get: function () { + get: function () + { return this.scale.y * this.texture.frame.height; }, - set: function (value) { + set: function (value) + { this.scale.y = value / this.texture.frame.height; this._height = value; } @@ -143,23 +150,29 @@ * @memberof Sprite# */ texture: { - get: function () { + get: function () + { return this._texture; }, - set: function (value) { - if (this._texture === value) { + set: function (value) + { + if (this._texture === value) + { return; } this._texture = value; this.cachedTint = 0xFFFFFF; - if (value) { + if (value) + { // wait for the texture to load - if (value.baseTexture.hasLoaded) { + if (value.baseTexture.hasLoaded) + { this._onTextureUpdate(); } - else { + else + { value.once('update', this._onTextureUpdate.bind(this)); } } @@ -172,18 +185,22 @@ * * @private */ -Sprite.prototype._onTextureUpdate = function () { +Sprite.prototype._onTextureUpdate = function () +{ // so if _width is 0 then width was not set.. - if (this._width) { + if (this._width) + { this.scale.x = this._width / this.texture.frame.width; } - if (this._height) { + if (this._height) + { this.scale.y = this._height / this.texture.frame.height; } }; -Sprite.prototype._renderWebGL = function (renderer) { +Sprite.prototype._renderWebGL = function (renderer) +{ // this is where content gets renderd.. // watch this space for a little render state manager.. @@ -197,7 +214,8 @@ * @param matrix {Matrix} the transformation matrix of the sprite * @return {Rectangle} the framing rectangle */ -Sprite.prototype.getBounds = function (matrix) { +Sprite.prototype.getBounds = function (matrix) +{ var width = this.texture.frame.width; var height = this.texture.frame.height; @@ -224,11 +242,13 @@ if(b === 0 && c === 0) { // scale may be negative! - if (a < 0) { + if (a < 0) + { a *= -1; } - if (d < 0) { + if (d < 0) + { d *= -1; } @@ -293,28 +313,34 @@ * * @param renderer {CanvasRenderer} The renderer */ -Sprite.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) { +Sprite.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) + { return; } - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; renderer.context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } // Ignore null sources - if (this.texture.valid) { + if (this.texture.valid) + { var resolution = this.texture.baseTexture.resolution / renderer.resolution; renderer.context.globalAlpha = this.worldAlpha; // If smoothingEnabled is supported and we need to change the smoothing property for this texture - if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) { + if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) + { renderer.scaleMode = this.texture.baseTexture.scaleMode; renderer.context[renderer.smoothProperty] = (renderer.scaleMode === CONST.scaleModes.LINEAR); } @@ -324,7 +350,8 @@ var dy = (this.texture.trim ? this.texture.trim.y : 0) - (this.anchor.y * this.texture.trim.height); // Allow for pixel rounding - if (renderer.roundPixels) { + if (renderer.roundPixels) + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -337,7 +364,8 @@ dx = dx | 0; dy = dy | 0; } - else { + else + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -348,8 +376,10 @@ ); } - if (this.tint !== 0xFFFFFF) { - if (this.cachedTint !== this.tint) { + if (this.tint !== 0xFFFFFF) + { + if (this.cachedTint !== this.tint) + { this.cachedTint = this.tint; // TODO clean up caching - how to clean up the caches? @@ -368,7 +398,8 @@ this.texture.crop.height / resolution ); } - else { + else + { renderer.context.drawImage( this.texture.baseTexture.source, this.texture.crop.x, @@ -383,11 +414,13 @@ } } - for (var i = 0, j = this.children.length; i < j; i++) { + for (var i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -402,10 +435,12 @@ * @param frameId {String} The frame Id of the texture in the cache * @return {Sprite} A new Sprite using a texture from the texture cache matching the frameId */ -Sprite.fromFrame = function (frameId) { +Sprite.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache' + this); } @@ -420,6 +455,7 @@ * @param imageId {String} The image url of the texture * @return {Sprite} A new Sprite using a texture from the texture cache matching the image id */ -Sprite.fromImage = function (imageId, crossorigin, scaleMode) { +Sprite.fromImage = function (imageId, crossorigin, scaleMode) +{ return new Sprite(Texture.fromImage(imageId, crossorigin, scaleMode)); }; diff --git a/src/core/display/SpriteBatch.js b/src/core/display/SpriteBatch.js index 3187777..c196fef 100644 --- a/src/core/display/SpriteBatch.js +++ b/src/core/display/SpriteBatch.js @@ -12,7 +12,8 @@ * ```js * var container = new SpriteBatch(); * - * for(var i = 0; i < 100; ++i) { + * for(var i = 0; i < 100; ++i) + * { * var sprite = new PIXI.Sprite.fromImage("myImage.png"); * container.addChild(sprite); * } @@ -25,7 +26,8 @@ */ //TODO RENAME to PARTICLE CONTAINER? -function SpriteBatch() { +function SpriteBatch() +{ DisplayObjectContainer.call(this); } @@ -38,7 +40,8 @@ * * @private */ -SpriteBatch.prototype.updateTransform = function () { +SpriteBatch.prototype.updateTransform = function () +{ // TODO don't need to! this.displayObjectUpdateTransform(); // PIXI.DisplayObjectContainer.prototype.updateTransform.call( this ); @@ -50,8 +53,10 @@ * @param renderer {WebGLRenderer} The webgl renderer * @private */ -SpriteBatch.prototype.renderWebGL = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderWebGL = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -71,8 +76,10 @@ * @param renderer {CanvasRenderer} The canvas renderer * @private */ -SpriteBatch.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -84,10 +91,12 @@ this.displayObjectUpdateTransform(); - for (var i = 0; i < this.children.length; ++i) { + for (var i = 0; i < this.children.length; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -95,9 +104,11 @@ context.globalAlpha = this.worldAlpha * child.alpha; - if (child.rotation % (Math.PI * 2) === 0) { + if (child.rotation % (Math.PI * 2) === 0) + { // this is the fastest way to optimise! - if rotation is 0 then we can avoid any kind of setTransform call - if (isRotated) { + if (isRotated) + { context.setTransform( transform.a, transform.b, @@ -122,8 +133,10 @@ frame.height * child.scale.y ); } - else { - if (!isRotated) { + else + { + if (!isRotated) + { isRotated = true; } @@ -131,7 +144,8 @@ var childTransform = child.worldTransform; - if (renderer.roundPixels) { + if (renderer.roundPixels) + { context.setTransform( childTransform.a, childTransform.b, @@ -141,7 +155,8 @@ childTransform.ty | 0 ); } - else { + else + { context.setTransform( childTransform.a, childTransform.b, diff --git a/src/core/index.js b/src/core/index.js index 3954b6f..eb4a82b 100644 --- a/src/core/index.js +++ b/src/core/index.js @@ -58,11 +58,13 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRenderer: function (width, height, options, noWebGL) { + autoDetectRenderer: function (width, height, options, noWebGL) + { width = width || 800; height = height || 600; - if (!noWebGL && require('webgl-enabled')()) { + if (!noWebGL && require('webgl-enabled')()) + { return new core.WebGLRenderer(width, height, options); } @@ -87,7 +89,8 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRecommendedRenderer: function (width, height, options) { + autoDetectRecommendedRenderer: function (width, height, options) + { var isAndroid = /Android/i.test(navigator.userAgent); return core.autoDetectRenderer(width, height, options, isAndroid); diff --git a/src/core/math/Matrix.js b/src/core/math/Matrix.js index c2f87e2..2ff4848 100644 --- a/src/core/math/Matrix.js +++ b/src/core/math/Matrix.js @@ -10,7 +10,8 @@ * @class * @namespace PIXI */ -function Matrix() { +function Matrix() +{ /** * @member {number} * @default 1 @@ -63,7 +64,8 @@ * * @param array {number[]} The array that the matrix will be populated from. */ -Matrix.prototype.fromArray = function (array) { +Matrix.prototype.fromArray = function (array) +{ this.a = array[0]; this.b = array[1]; this.c = array[3]; @@ -78,14 +80,17 @@ * @param transpose {boolean} Whether we need to transpose the matrix or not * @return {number[]} the newly created array which contains the matrix */ -Matrix.prototype.toArray = function (transpose) { - if (!this.array) { +Matrix.prototype.toArray = function (transpose) +{ + if (!this.array) + { this.array = new Float32Array(9); } var array = this.array; - if (transpose) { + if (transpose) + { array[0] = this.a; array[1] = this.b; array[2] = 0; @@ -96,7 +101,8 @@ array[7] = this.ty; array[8] = 1; } - else { + else + { array[0] = this.a; array[1] = this.c; array[2] = this.tx; @@ -119,7 +125,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, transformed through this matrix */ -Matrix.prototype.apply = function (pos, newPos) { +Matrix.prototype.apply = function (pos, newPos) +{ newPos = newPos || new Point(); newPos.x = this.a * pos.x + this.c * pos.y + this.tx; @@ -136,7 +143,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, inverse-transformed through this matrix */ -Matrix.prototype.applyInverse = function (pos, newPos) { +Matrix.prototype.applyInverse = function (pos, newPos) +{ newPos = newPos || new Point(); var id = 1 / (this.a * this.d + this.c * -this.b); @@ -154,7 +162,8 @@ * @param {number} y * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.translate = function (x, y) { +Matrix.prototype.translate = function (x, y) +{ this.tx += x; this.ty += y; @@ -168,7 +177,8 @@ * @param {number} y The amount to scale vertically * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.scale = function (x, y) { +Matrix.prototype.scale = function (x, y) +{ this.a *= x; this.d *= y; this.c *= x; @@ -186,7 +196,8 @@ * @param {number} angle - The angle in radians. * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.rotate = function (angle) { +Matrix.prototype.rotate = function (angle) +{ var cos = Math.cos( angle ); var sin = Math.sin( angle ); @@ -210,7 +221,8 @@ * @param {Matrix} matrix * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.append = function (matrix) { +Matrix.prototype.append = function (matrix) +{ var a1 = this.a; var b1 = this.b; var c1 = this.c; @@ -232,7 +244,8 @@ * * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.identity = function () { +Matrix.prototype.identity = function () +{ this.a = 1; this.b = 0; this.c = 0; diff --git a/src/core/math/Point.js b/src/core/math/Point.js index 7565b2d..632f346 100644 --- a/src/core/math/Point.js +++ b/src/core/math/Point.js @@ -7,7 +7,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -function Point(x, y) { +function Point(x, y) +{ /** * @member {number} * @default 0 @@ -29,7 +30,8 @@ * * @return {Point} a copy of the point */ -Point.prototype.clone = function () { +Point.prototype.clone = function () +{ return new Point(this.x, this.y); }; @@ -40,7 +42,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -Point.prototype.set = function (x, y) { +Point.prototype.set = function (x, y) +{ this.x = x || 0; this.y = y || ( (y !== 0) ? this.x : 0 ) ; }; diff --git a/src/core/math/shapes/Circle.js b/src/core/math/shapes/Circle.js index 69cfdc9..4d76efc 100644 --- a/src/core/math/shapes/Circle.js +++ b/src/core/math/shapes/Circle.js @@ -10,7 +10,8 @@ * @param y {number} The Y coordinate of the center of this circle * @param radius {number} The radius of the circle */ -function Circle(x, y, radius) { +function Circle(x, y, radius) +{ /** * @member {number} * @default 0 @@ -46,7 +47,8 @@ * @method clone * @return {Circle} a copy of the Circle */ -Circle.prototype.clone = function () { +Circle.prototype.clone = function () +{ return new Circle(this.x, this.y, this.radius); }; @@ -58,8 +60,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Circle */ -Circle.prototype.contains = function (x, y) { - if (this.radius <= 0) { +Circle.prototype.contains = function (x, y) +{ + if (this.radius <= 0) + { return false; } @@ -79,6 +83,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Circle.prototype.getBounds = function () { +Circle.prototype.getBounds = function () +{ return new Rectangle(this.x - this.radius, this.y - this.radius, this.radius * 2, this.radius * 2); }; diff --git a/src/core/math/shapes/Ellipse.js b/src/core/math/shapes/Ellipse.js index 4f2d066..fefd01a 100644 --- a/src/core/math/shapes/Ellipse.js +++ b/src/core/math/shapes/Ellipse.js @@ -11,7 +11,8 @@ * @param width {number} The half width of this ellipse * @param height {number} The half height of this ellipse */ -function Ellipse(x, y, width, height) { +function Ellipse(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -53,7 +54,8 @@ * @method clone * @return {Ellipse} a copy of the ellipse */ -Ellipse.prototype.clone = function () { +Ellipse.prototype.clone = function () +{ return new Ellipse(this.x, this.y, this.width, this.height); }; @@ -65,8 +67,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coords are within this ellipse */ -Ellipse.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Ellipse.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } @@ -86,6 +90,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Ellipse.prototype.getBounds = function () { +Ellipse.prototype.getBounds = function () +{ return new Rectangle(this.x - this.width, this.y - this.height, this.width, this.height); }; diff --git a/src/core/math/shapes/Polygon.js b/src/core/math/shapes/Polygon.js index ae89148..fea6d37 100644 --- a/src/core/math/shapes/Polygon.js +++ b/src/core/math/shapes/Polygon.js @@ -10,16 +10,20 @@ * arguments passed can be flat x,y values e.g. `new Polygon(x,y, x,y, x,y, ...)` where `x` and `y` are * Numbers. */ -function Polygon(points) { +function Polygon(points) +{ //if points isn't an array, use arguments as the array - if (!(points instanceof Array)) { + if (!(points instanceof Array)) + { points = Array.prototype.slice.call(arguments); } //if this is a flat array of numbers, convert it to points - if (points[0] instanceof Point) { + if (points[0] instanceof Point) + { var p = []; - for (var i = 0, il = points.length; i < il; i++) { + for (var i = 0, il = points.length; i < il; i++) + { p.push(points[i].x, points[i].y); } @@ -51,7 +55,8 @@ * * @return {Polygon} a copy of the polygon */ -Polygon.prototype.clone = function () { +Polygon.prototype.clone = function () +{ return new Polygon(this.points.slice()); }; @@ -62,19 +67,22 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this polygon */ -Polygon.prototype.contains = function (x, y) { +Polygon.prototype.contains = function (x, y) +{ var inside = false; // use some raycasting to test hits // https://github.com/substack/point-in-polygon/blob/master/index.js var length = this.points.length / 2; - for (var i = 0, j = length - 1; i < length; j = i++) { + for (var i = 0, j = length - 1; i < length; j = i++) + { var xi = this.points[i * 2], yi = this.points[i * 2 + 1], xj = this.points[j * 2], yj = this.points[j * 2 + 1], intersect = ((yi > y) !== (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi); - if (intersect) { + if (intersect) + { inside = !inside; } } diff --git a/src/core/math/shapes/Rectangle.js b/src/core/math/shapes/Rectangle.js index 16ac62a..4008b68 100644 --- a/src/core/math/shapes/Rectangle.js +++ b/src/core/math/shapes/Rectangle.js @@ -10,7 +10,8 @@ * @param width {number} The overall width of this rectangle * @param height {number} The overall height of this rectangle */ -function Rectangle(x, y, width, height) { +function Rectangle(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -60,7 +61,8 @@ * * @return {Rectangle} a copy of the rectangle */ -Rectangle.prototype.clone = function () { +Rectangle.prototype.clone = function () +{ return new Rectangle(this.x, this.y, this.width, this.height); }; @@ -71,13 +73,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rectangle */ -Rectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Rectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/math/shapes/RoundedRectangle.js b/src/core/math/shapes/RoundedRectangle.js index 27d286e..7bf6411 100644 --- a/src/core/math/shapes/RoundedRectangle.js +++ b/src/core/math/shapes/RoundedRectangle.js @@ -11,7 +11,8 @@ * @param height {number} The overall height of this rounded rectangle * @param radius {number} Controls the radius of the rounded corners */ -function RoundedRectangle(x, y, width, height, radius) { +function RoundedRectangle(x, y, width, height, radius) +{ /** * @member {number} * @default 0 @@ -58,7 +59,8 @@ * * @return {RoundedRectangle} a copy of the rounded rectangle */ -RoundedRectangle.prototype.clone = function () { +RoundedRectangle.prototype.clone = function () +{ return new RoundedRectangle(this.x, this.y, this.width, this.height, this.radius); }; @@ -69,13 +71,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rounded Rectangle */ -RoundedRectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +RoundedRectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/primitives/Graphics.js b/src/core/primitives/Graphics.js index 261c534..e902d2a 100644 --- a/src/core/primitives/Graphics.js +++ b/src/core/primitives/Graphics.js @@ -16,7 +16,8 @@ * @extends DisplayObjectContainer * @namespace PIXI */ -function Graphics() { +function Graphics() +{ DisplayObjectContainer.call(this); this.renderable = true; @@ -154,16 +155,20 @@ * @private */ cacheAsBitmap: { - get: function () { + get: function () + { return this._cacheAsBitmap; }, - set: function (value) { + set: function (value) + { this._cacheAsBitmap = value; - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._generateCachedSprite(); } - else { + else + { this.destroyCachedSprite(); this.dirty = true; } @@ -176,7 +181,8 @@ * * @return {Graphics} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ var clone = new Graphics(); clone.renderable = this.renderable; @@ -192,7 +198,8 @@ clone.cachedSpriteDirty = this.cachedSpriteDirty; // copy graphics data - for (var i = 0; i < this.graphicsData.length; ++i) { + for (var i = 0; i < this.graphicsData.length; ++i) + { clone.graphicsData.push(this.graphicsData.clone()); } @@ -211,17 +218,21 @@ * @param alpha {number} alpha of the line to draw, will update the objects stored style * @return {Graphics} */ -Graphics.prototype.lineStyle = function (lineWidth, color, alpha) { +Graphics.prototype.lineStyle = function (lineWidth, color, alpha) +{ this.lineWidth = lineWidth || 0; this.lineColor = color || 0; this.lineAlpha = (arguments.length < 3) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length) + { // halfway through a line? start a new one! this.drawShape( new math.Polygon( this.currentPath.shape.points.slice(-2) )); } - else { + else + { // otherwise its empty so lets just set the line properties this.currentPath.lineWidth = this.lineWidth; this.currentPath.lineColor = this.lineColor; @@ -239,7 +250,8 @@ * @param y {number} the Y coordinate to move to * @return {Graphics} */ -Graphics.prototype.moveTo = function (x, y) { +Graphics.prototype.moveTo = function (x, y) +{ this.drawShape(new math.Polygon([x,y])); return this; @@ -253,7 +265,8 @@ * @param y {number} the Y coordinate to draw to * @return {Graphics} */ -Graphics.prototype.lineTo = function (x, y) { +Graphics.prototype.lineTo = function (x, y) +{ this.currentPath.shape.points.push(x, y); this.dirty = true; @@ -270,13 +283,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -285,7 +302,8 @@ n = 20, points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { this.moveTo(0, 0); } @@ -293,7 +311,8 @@ var fromY = points[points.length-1]; var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; xa = fromX + ( (cpX - fromX) * j ); @@ -319,13 +338,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -342,7 +365,8 @@ var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; dt = (1 - j); @@ -373,13 +397,17 @@ * @param radius {number} The radius of the arc * @return {Graphics} */ -Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points.push(x1, y1); } } - else { + else + { this.moveTo(x1, y1); } @@ -392,12 +420,15 @@ b2 = x2 - x1, mm = Math.abs(a1 * b2 - b1 * a2); - if (mm < 1.0e-8 || radius === 0) { - if (points[points.length-2] !== x1 || points[points.length-1] !== y1) { + if (mm < 1.0e-8 || radius === 0) + { + if (points[points.length-2] !== x1 || points[points.length-1] !== y1) + { points.push(x1, y1); } } - else { + else + { var dd = a1 * a1 + b1 * b1, cc = a2 * a2 + b2 * b2, tt = a1 * a2 + b1 * b2, @@ -433,42 +464,51 @@ * @param anticlockwise {boolean} Optional. Specifies whether the drawing should be counterclockwise or clockwise. False is default, and indicates clockwise, while true indicates counter-clockwise. * @return {Graphics} */ -Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) { +Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) +{ var startX = cx + Math.cos(startAngle) * radius; var startY = cy + Math.sin(startAngle) * radius; var points; // TODO - This if-else makes no sense. It uses currentPath in the else where it doesn't exist... - if (this.currentPath) { + if (this.currentPath) + { points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { points.push(startX, startY); } - else if (points[points.length-2] !== startX || points[points.length-1] !== startY) { + else if (points[points.length-2] !== startX || points[points.length-1] !== startY) + { points.push(startX, startY); } } - else { + else + { this.moveTo(startX, startY); points = this.currentPath.shape.points; } - if (startAngle === endAngle) { + if (startAngle === endAngle) + { return this; } - if (!anticlockwise && endAngle <= startAngle) { + if (!anticlockwise && endAngle <= startAngle) + { endAngle += Math.PI * 2; } - else if (anticlockwise && startAngle <= endAngle) { + else if (anticlockwise && startAngle <= endAngle) + { startAngle += Math.PI * 2; } var sweep = anticlockwise ? (startAngle - endAngle) *-1 : (endAngle - startAngle); var segs = (Math.abs(sweep)/ (Math.PI * 2)) * 40; - if (sweep === 0) { + if (sweep === 0) + { return this; } @@ -482,7 +522,8 @@ var remainder = ( segMinus % 1 ) / segMinus; - for (var i = 0; i <= segMinus; ++i) { + for (var i = 0; i <= segMinus; ++i) + { var real = i + remainder * i; var angle = ((theta) + startAngle + (theta2 * real)); @@ -506,13 +547,16 @@ * @param alpha {number} the alpha of the fill * @return {Graphics} */ -Graphics.prototype.beginFill = function (color, alpha) { +Graphics.prototype.beginFill = function (color, alpha) +{ this.filling = true; this.fillColor = color || 0; this.fillAlpha = (alpha === undefined) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length <= 2) + { this.currentPath.fill = this.filling; this.currentPath.fillColor = this.fillColor; this.currentPath.fillAlpha = this.fillAlpha; @@ -526,7 +570,8 @@ * * @return {Graphics} */ -Graphics.prototype.endFill = function () { +Graphics.prototype.endFill = function () +{ this.filling = false; this.fillColor = null; this.fillAlpha = 1; @@ -542,7 +587,8 @@ * @param height {number} The height of the rectangle * @return {Graphics} */ -Graphics.prototype.drawRect = function ( x, y, width, height ) { +Graphics.prototype.drawRect = function ( x, y, width, height ) +{ this.drawShape(new math.Rectangle(x,y, width, height)); return this; @@ -556,7 +602,8 @@ * @param height {number} The height of the rectangle * @param radius {number} Radius of the rectangle corners */ -Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) { +Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) +{ this.drawShape(new math.RoundedRectangle(x, y, width, height, radius)); return this; @@ -570,7 +617,8 @@ * @param radius {number} The radius of the circle * @return {Graphics} */ -Graphics.prototype.drawCircle = function (x, y, radius) { +Graphics.prototype.drawCircle = function (x, y, radius) +{ this.drawShape(new math.Circle(x,y, radius)); return this; @@ -585,7 +633,8 @@ * @param height {number} The half height of the ellipse * @return {Graphics} */ -Graphics.prototype.drawEllipse = function (x, y, width, height) { +Graphics.prototype.drawEllipse = function (x, y, width, height) +{ this.drawShape(new math.Ellipse(x, y, width, height)); return this; @@ -597,8 +646,10 @@ * @param path {Array} The path data used to construct the polygon. * @return {Graphics} */ -Graphics.prototype.drawPolygon = function (path) { - if (!(path instanceof Array)) { +Graphics.prototype.drawPolygon = function (path) +{ + if (!(path instanceof Array)) + { path = Array.prototype.slice.call(arguments); } @@ -612,7 +663,8 @@ * * @return {Graphics} */ -Graphics.prototype.clear = function () { +Graphics.prototype.clear = function () +{ this.lineWidth = 0; this.filling = false; @@ -631,7 +683,8 @@ * @param scaleMode {number} Should be one of the scaleMode consts * @return {Texture} a texture of the graphics object */ -Graphics.prototype.generateTexture = function (resolution, scaleMode) { +Graphics.prototype.generateTexture = function (resolution, scaleMode) +{ resolution = resolution || 1; var bounds = this.getBounds(); @@ -655,17 +708,21 @@ * * @param renderer {WebGLRenderer} */ -Graphics.prototype._renderWebGL = function (renderer) { +Graphics.prototype._renderWebGL = function (renderer) +{ // if the sprite is not visible or the alpha is 0 then no need to render this element - if (this.isMask === true) { + if (this.isMask === true) + { return; } // this code may still be needed so leaving for now.. - // + // /* - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture on the gpu too! @@ -681,17 +738,24 @@ return; } - */ - - // check if the webgl graphic needs to be updated - if (this.glDirty) { - this.dirty = true; - this.glDirty = false; - } + else */ - renderer.setObjectRendererer(renderer.graphicsRenderer); - renderer.graphicsRenderer.render(this); + renderer.spriteBatch.stop(); + renderer.blendModeManager.setBlendMode(this.blendMode); + // check blend mode + renderer.blendModeManager.setBlendMode( this.blendMode ); + + // check if the webgl graphic needs to be updated + if (this.glDirty) + { + this.dirty = true; + this.glDirty = false; + } + + WebGLGraphics.renderGraphics(this, renderer); + + renderer.spriteBatch.start(); }; /** @@ -700,14 +764,18 @@ * @param renderer {CanvasRenderer} * @private */ -Graphics.prototype.renderCanvas = function (renderer) { +Graphics.prototype.renderCanvas = function (renderer) +{ // 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.isMask === true) { + if (!this.visible || this.alpha <= 0 || this.isMask === true) + { return; } - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture @@ -723,16 +791,19 @@ return; } - else { + else + { var context = renderer.context; var transform = this.worldTransform; - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } @@ -748,11 +819,13 @@ CanvasGraphics.renderGraphics(this, context); - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } } @@ -763,13 +836,16 @@ * * @return {Rectangle} the rectangular bounding area */ -Graphics.prototype.getBounds = function (matrix) { +Graphics.prototype.getBounds = function (matrix) +{ // return an empty object if the item is a mask! - if (this.isMask) { + if (this.isMask) + { return math.Rectangle.EMPTY; } - if (this.dirty) { + if (this.dirty) + { this.updateLocalBounds(); this.glDirty = true; @@ -841,23 +917,27 @@ * Update the bounds of the object * */ -Graphics.prototype.updateLocalBounds = function () { +Graphics.prototype.updateLocalBounds = function () +{ var minX = Infinity; var maxX = -Infinity; var minY = Infinity; var maxY = -Infinity; - if (this.graphicsData.length) { + if (this.graphicsData.length) + { var shape, points, x, y, w, h; - for (var i = 0; i < this.graphicsData.length; i++) { + for (var i = 0; i < this.graphicsData.length; i++) + { var data = this.graphicsData[i]; var type = data.type; var lineWidth = data.lineWidth; shape = data.shape; - if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) { + if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) + { x = shape.x - lineWidth/2; y = shape.y - lineWidth/2; w = shape.width + lineWidth; @@ -869,7 +949,8 @@ minY = y < minY ? y : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.CIRC) { + else if (type === CONST.SHAPES.CIRC) + { x = shape.x; y = shape.y; w = shape.radius + lineWidth/2; @@ -881,7 +962,8 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.ELIP) { + else if (type === CONST.SHAPES.ELIP) + { x = shape.x; y = shape.y; w = shape.width + lineWidth/2; @@ -893,11 +975,13 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else { + else + { // POLY points = shape.points; - for (var j = 0; j < points.length; j += 2) { + for (var j = 0; j < points.length; j += 2) + { x = points[j]; y = points[j+1]; @@ -910,7 +994,8 @@ } } } - else { + else + { minX = 0; maxX = 0; minY = 0; @@ -931,10 +1016,12 @@ * * @private */ -Graphics.prototype._generateCachedSprite = function () { +Graphics.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { var canvasBuffer = new CanvasBuffer(bounds.width, bounds.height); var texture = Texture.fromCanvas(canvasBuffer.canvas); @@ -943,7 +1030,8 @@ this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.buffer.resize(bounds.width, bounds.height); } @@ -968,7 +1056,8 @@ * * @private */ -Graphics.prototype.updateCachedSpriteTexture = function () { +Graphics.prototype.updateCachedSpriteTexture = function () +{ var cachedSprite = this._cachedSprite; var texture = cachedSprite.texture; var canvas = cachedSprite.buffer.canvas; @@ -989,7 +1078,8 @@ * Destroys a previous cached sprite. * */ -Graphics.prototype.destroyCachedSprite = function () { +Graphics.prototype.destroyCachedSprite = function () +{ this._cachedSprite.texture.destroy(true); // let the gc collect the unused sprite @@ -1003,10 +1093,13 @@ * @param {Circle|Rectangle|Ellipse|Line|Polygon} shape The Shape object to draw. * @return {GraphicsData} The generated GraphicsData object. */ -Graphics.prototype.drawShape = function (shape) { - if (this.currentPath) { +Graphics.prototype.drawShape = function (shape) +{ + if (this.currentPath) + { // check current path! - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath.shape.points.length <= 2) + { this.graphicsData.pop(); } } @@ -1017,7 +1110,8 @@ this.graphicsData.push(data); - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { data.shape.closed = this.filling; this.currentPath = data; } diff --git a/src/core/primitives/GraphicsData.js b/src/core/primitives/GraphicsData.js index 99decbe..788f6f2 100644 --- a/src/core/primitives/GraphicsData.js +++ b/src/core/primitives/GraphicsData.js @@ -4,7 +4,8 @@ * @class * @namespace PIXI */ -function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) { +function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) +{ this.lineWidth = lineWidth; this.lineColor = lineColor; this.lineAlpha = lineAlpha; @@ -27,7 +28,8 @@ * * @return {GraphicsData} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ return new GraphicsData( this.lineWidth, this.lineColor, diff --git a/src/core/renderers/canvas/CanvasRenderer.js b/src/core/renderers/canvas/CanvasRenderer.js index 15a0978..7aebd44 100644 --- a/src/core/renderers/canvas/CanvasRenderer.js +++ b/src/core/renderers/canvas/CanvasRenderer.js @@ -17,17 +17,22 @@ * @param [options.resolution=1] {number} the resolution of the renderer retina would be 2 * @param [options.clearBeforeRender=true] {boolean} This sets if the CanvasRenderer will clear the canvas or not before the new render pass. */ -function CanvasRenderer(width, height, options) { +function CanvasRenderer(width, height, options) +{ utils.sayHello('Canvas'); - if (options) { - for (var i in CONST.defaultRenderOptions) { - if (typeof options[i] === 'undefined') { + if (options) + { + for (var i in CONST.defaultRenderOptions) + { + if (typeof options[i] === 'undefined') + { options[i] = CONST.defaultRenderOptions[i]; } } } - else { + else + { options = CONST.defaultRenderOptions; } @@ -156,19 +161,24 @@ this.smoothProperty = null; - if (this.context.imageSmoothingEnabled) { + if (this.context.imageSmoothingEnabled) + { this.smoothProperty = 'imageSmoothingEnabled'; } - else if (this.context.webkitImageSmoothingEnabled) { + else if (this.context.webkitImageSmoothingEnabled) + { this.smoothProperty = 'webkitImageSmoothingEnabled'; } - else if (this.context.mozImageSmoothingEnabled) { + else if (this.context.mozImageSmoothingEnabled) + { this.smoothProperty = 'mozImageSmoothingEnabled'; } - else if (this.context.oImageSmoothingEnabled) { + else if (this.context.oImageSmoothingEnabled) + { this.smoothProperty = 'oImageSmoothingEnabled'; } - else if (this.context.msImageSmoothingEnabled) { + else if (this.context.msImageSmoothingEnabled) + { this.smoothProperty = 'msImageSmoothingEnabled'; } @@ -193,10 +203,12 @@ * @memberof CanvasRenderer# */ backgroundColor: { - get: function () { + get: function () + { return this._backgroundColor; }, - set: function (val) { + set: function (val) + { this._backgroundColor = val; this._backgroundColorString = utils.hex2string(val); } @@ -208,7 +220,8 @@ * * @param object {DisplayObject} the object to be rendered */ -CanvasRenderer.prototype.render = function (object) { +CanvasRenderer.prototype.render = function (object) +{ object.updateTransform(); this.context.setTransform(1,0,0,1,0,0); @@ -218,16 +231,20 @@ this.currentBlendMode = CONST.blendModes.NORMAL; this.context.globalCompositeOperation = this.blendModes[CONST.blendModes.NORMAL]; - if (navigator.isCocoonJS && this.view.screencanvas) { + if (navigator.isCocoonJS && this.view.screencanvas) + { this.context.fillStyle = 'black'; this.context.clear(); } - if (this.clearBeforeRender) { - if (this.transparent) { + if (this.clearBeforeRender) + { + if (this.transparent) + { this.context.clearRect(0, 0, this.width, this.height); } - else { + else + { this.context.fillStyle = this._backgroundColorString; this.context.fillRect(0, 0, this.width , this.height); } @@ -241,8 +258,10 @@ * * @param [removeView=false] {boolean} Removes the Canvas element from the DOM. */ -CanvasRenderer.prototype.destroy = function (removeView) { - if (removeView && this.view.parent) { +CanvasRenderer.prototype.destroy = function (removeView) +{ + if (removeView && this.view.parent) + { this.view.parent.removeChild(this.view); } @@ -257,14 +276,16 @@ * @param width {number} the new width of the canvas view * @param height {number} the new height of the canvas view */ -CanvasRenderer.prototype.resize = function (width, height) { +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) { + if (this.autoResize) + { this.view.style.width = this.width / this.resolution + 'px'; this.view.style.height = this.height / this.resolution + 'px'; } @@ -276,7 +297,8 @@ * @param displayObject {DisplayObject} The displayObject to render * @private */ -CanvasRenderer.prototype.renderDisplayObject = function (displayObject) { +CanvasRenderer.prototype.renderDisplayObject = function (displayObject) +{ displayObject.renderCanvas(this); }; @@ -285,11 +307,14 @@ * * @private */ -CanvasRenderer.prototype._mapBlendModes = function () { - if (!this.blendModes) { +CanvasRenderer.prototype._mapBlendModes = function () +{ + if (!this.blendModes) + { this.blendModes = {}; - if (utils.canUseNewCanvasBlendModes()) { + if (utils.canUseNewCanvasBlendModes()) + { this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? this.blendModes[CONST.blendModes.MULTIPLY] = 'multiply'; @@ -308,7 +333,8 @@ this.blendModes[CONST.blendModes.COLOR] = 'color'; this.blendModes[CONST.blendModes.LUMINOSITY] = 'luminosity'; } - else { + else + { // this means that the browser does not support the cool new blend modes in canvas 'cough' ie 'cough' this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? diff --git a/src/core/renderers/canvas/utils/CanvasBuffer.js b/src/core/renderers/canvas/utils/CanvasBuffer.js index ebe5d47..b183a66 100644 --- a/src/core/renderers/canvas/utils/CanvasBuffer.js +++ b/src/core/renderers/canvas/utils/CanvasBuffer.js @@ -6,7 +6,8 @@ * @param width {number} the width for the newly created canvas * @param height {number} the height for the newly created canvas */ -function CanvasBuffer(width, height) { +function CanvasBuffer(width, height) +{ /** * The Canvas object that belongs to this CanvasBuffer. * @@ -36,10 +37,12 @@ * @memberof CanvasBuffer# */ width: { - get: function () { + get: function () + { return this.canvas.width; }, - set: function (val) { + set: function (val) + { this.canvas.width = val; } }, @@ -50,10 +53,12 @@ * @memberof CanvasBuffer# */ height: { - get: function () { + get: function () + { return this.canvas.height; }, - set: function (val) { + set: function (val) + { this.canvas.height = val; } } @@ -64,7 +69,8 @@ * * @private */ -CanvasBuffer.prototype.clear = function () { +CanvasBuffer.prototype.clear = function () +{ this.context.setTransform(1, 0, 0, 1, 0, 0); this.context.clearRect(0,0, this.canvas.width, this.canvas.height); }; @@ -75,7 +81,8 @@ * @param width {number} the new width of the canvas * @param height {number} the new height of the canvas */ -CanvasBuffer.prototype.resize = function (width, height) { +CanvasBuffer.prototype.resize = function (width, height) +{ this.canvas.width = width; this.canvas.height = height; }; diff --git a/src/core/renderers/canvas/utils/CanvasGraphics.js b/src/core/renderers/canvas/utils/CanvasGraphics.js index c7eaa2a..3f2a91f 100644 --- a/src/core/renderers/canvas/utils/CanvasGraphics.js +++ b/src/core/renderers/canvas/utils/CanvasGraphics.js @@ -13,15 +13,18 @@ * @param graphics {Graphics} the actual graphics object to render * @param context {CanvasRenderingContext2D} the 2d drawing method of the canvas */ -CanvasGraphics.renderGraphics = function (graphics, context) { +CanvasGraphics.renderGraphics = function (graphics, context) +{ var worldAlpha = graphics.worldAlpha; - if (graphics.dirty) { + if (graphics.dirty) + { this.updateGraphicsTint(graphics); graphics.dirty = false; } - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; @@ -30,69 +33,82 @@ context.lineWidth = data.lineWidth; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { context.beginPath(); var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } - if (shape.closed) { + if (shape.closed) + { context.lineTo(points[0], points[1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fillRect(shape.x, shape.y, shape.width, shape.height); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.strokeRect(shape.x, shape.y, shape.width, shape.height); } } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.beginPath(); context.arc(shape.x, shape.y, shape.radius,0,2*Math.PI); context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas var w = shape.width * 2; @@ -119,18 +135,21 @@ context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; var width = shape.width; @@ -152,13 +171,15 @@ context.quadraticCurveTo(rx, ry, rx, ry + radius); context.closePath(); - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); @@ -174,45 +195,54 @@ * @param graphics {Graphics} the graphics which will be used as a mask * @param context {CanvasRenderingContext2D} the context 2d method of the canvas */ -CanvasGraphics.renderGraphicsMask = function (graphics, context) { +CanvasGraphics.renderGraphicsMask = function (graphics, context) +{ var len = graphics.graphicsData.length; - if (len === 0) { + if (len === 0) + { return; } context.beginPath(); - for (var i = 0; i < len; i++) { + for (var i = 0; i < len; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { context.rect(shape.x, shape.y, shape.width, shape.height); context.closePath(); } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.arc(shape.x, shape.y, shape.radius, 0, 2 * Math.PI); context.closePath(); } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas @@ -237,7 +267,8 @@ context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); context.closePath(); } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; @@ -262,8 +293,10 @@ } }; -CanvasGraphics.updateGraphicsTint = function (graphics) { - if (graphics.tint === 0xFFFFFF) { +CanvasGraphics.updateGraphicsTint = function (graphics) +{ + if (graphics.tint === 0xFFFFFF) + { return; } @@ -271,7 +304,8 @@ var tintG = (graphics.tint >> 8 & 0xFF) / 255; var tintB = (graphics.tint & 0xFF)/ 255; - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var fillColor = data.fillColor | 0; diff --git a/src/core/renderers/canvas/utils/CanvasMaskManager.js b/src/core/renderers/canvas/utils/CanvasMaskManager.js index e04a733..9827d36 100644 --- a/src/core/renderers/canvas/utils/CanvasMaskManager.js +++ b/src/core/renderers/canvas/utils/CanvasMaskManager.js @@ -6,7 +6,8 @@ * @class * @namespace PIXI */ -function CanvasMaskManager() {} +function CanvasMaskManager() +{} CanvasMaskManager.prototype.constructor = CanvasMaskManager; module.exports = CanvasMaskManager; @@ -17,7 +18,8 @@ * @param maskData {object} the maskData that will be pushed * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.pushMask = function (maskData, renderer) { +CanvasMaskManager.prototype.pushMask = function (maskData, renderer) +{ renderer.context.save(); var cacheAlpha = maskData.alpha; @@ -45,6 +47,7 @@ * * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.popMask = function (renderer) { +CanvasMaskManager.prototype.popMask = function (renderer) +{ renderer.context.restore(); }; diff --git a/src/core/display/DisplayObject.js b/src/core/display/DisplayObject.js index 66ebc3c..20e778c 100644 --- a/src/core/display/DisplayObject.js +++ b/src/core/display/DisplayObject.js @@ -7,7 +7,8 @@ * @class * @namespace PIXI */ -function DisplayObject() { +function DisplayObject() +{ /** * The coordinate of the object relative to the local coordinates of the parent. * @@ -152,10 +153,12 @@ * @memberof DisplayObject# */ x: { - get: function () { + get: function () + { return this.position.x; }, - set: function (value) { + set: function (value) + { this.position.x = value; } }, @@ -167,10 +170,12 @@ * @memberof DisplayObject# */ y: { - get: function () { + get: function () + { return this.position.y; }, - set: function (value) { + set: function (value) + { this.position.y = value; } }, @@ -183,11 +188,13 @@ * @readonly */ worldVisible: { - get: function () { + get: function () + { var item = this; do { - if (!item.visible) { + if (!item.visible) + { return false; } @@ -207,17 +214,21 @@ * @memberof DisplayObject# */ mask: { - get: function () { + get: function () + { return this._mask; }, - set: function (value) { - if (this._mask) { + set: function (value) + { + if (this._mask) + { this._mask.isMask = false; } this._mask = value; - if (this._mask) { + if (this._mask) + { this._mask.isMask = true; } } @@ -232,18 +243,23 @@ * @memberof DisplayObject# */ filters: { - get: function () { + get: function () + { return this._filters; }, - set: function (value) { - if (value) { + set: function (value) + { + if (value) + { // now put all the passes in one place.. var passes = []; - for (var i = 0; i < value.length; i++) { + for (var i = 0; i < value.length; i++) + { var filterPasses = value[i].passes; - for (var j = 0; j < filterPasses.length; j++) { + for (var j = 0; j < filterPasses.length; j++) + { passes.push(filterPasses[j]); } } @@ -264,8 +280,9 @@ * * @private */ -DisplayObject.prototype.updateTransform = function () { - +DisplayObject.prototype.updateTransform = function () +{ + // create some matrix refs for easy access var pt = this.parent.worldTransform; var wt = this.worldTransform; @@ -274,9 +291,11 @@ var a, b, c, d, tx, ty; // so if rotation is between 0 then we can simplify the multiplication process.. - if (this.rotation % math.PI_2) { + if (this.rotation % math.PI_2) + { // 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) { + if (this.rotation !== this.rotationCache) + { this.rotationCache = this.rotation; this._sr = Math.sin(this.rotation); this._cr = Math.cos(this.rotation); @@ -291,7 +310,8 @@ ty = this.position.y; // check for pivot.. not often used so geared towards that fact! - if (this.pivot.x || this.pivot.y) { + 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; } @@ -304,7 +324,8 @@ wt.tx = tx * pt.a + ty * pt.c + pt.tx; wt.ty = tx * pt.b + ty * pt.d + pt.ty; } - else { + else + { // lets do the fast version as we know there is no rotation.. a = this.scale.x; d = this.scale.y; @@ -333,7 +354,8 @@ * @param matrix {Matrix} * @return {Rectangle} the rectangular bounding area */ -DisplayObject.prototype.getBounds = function (/* matrix */) { +DisplayObject.prototype.getBounds = function (/* matrix */) +{ return math.Rectangle.EMPTY; }; @@ -342,7 +364,8 @@ * * @return {Rectangle} the rectangular bounding area */ -DisplayObject.prototype.getLocalBounds = function () { +DisplayObject.prototype.getLocalBounds = function () +{ return this.getBounds(math.Matrix.IDENTITY); }; @@ -352,7 +375,8 @@ * @param position {Point} The world origin to calculate from * @return {Point} A point object representing the position of this object */ -DisplayObject.prototype.toGlobal = function (position) { +DisplayObject.prototype.toGlobal = function (position) +{ // don't need to u[date the lot this.displayObjectUpdateTransform(); return this.worldTransform.apply(position); @@ -365,8 +389,10 @@ * @param [from] {DisplayObject} The DisplayObject to calculate the global position from * @return {Point} A point object representing the position of this object */ -DisplayObject.prototype.toLocal = function (position, from) { - if (from) { +DisplayObject.prototype.toLocal = function (position, from) +{ + if (from) + { position = from.toGlobal(position); } @@ -381,7 +407,8 @@ * @param renderer {WebGLRenderer} The renderer * @private */ -DisplayObject.prototype.renderWebGL = function (/* renderer */) { +DisplayObject.prototype.renderWebGL = function (/* renderer */) +{ // OVERWRITE; }; @@ -391,6 +418,7 @@ * @param renderer {CanvasRenderer} The renderer * @private */ -DisplayObject.prototype.renderCanvas = function (/* renderer */) { +DisplayObject.prototype.renderCanvas = function (/* renderer */) +{ // OVERWRITE; }; diff --git a/src/core/display/DisplayObjectContainer.js b/src/core/display/DisplayObjectContainer.js index 689f40b..4625ee8 100644 --- a/src/core/display/DisplayObjectContainer.js +++ b/src/core/display/DisplayObjectContainer.js @@ -12,7 +12,8 @@ * @extends DisplayObject * @namespace PIXI */ -function DisplayObjectContainer() { +function DisplayObjectContainer() +{ DisplayObject.call(this); /** @@ -47,17 +48,21 @@ * @memberof DisplayObjectContainer# */ width: { - get: function () { + get: function () + { return this.scale.x * this.getLocalBounds().width; }, - set: function (value) { + set: function (value) + { var width = this.getLocalBounds().width; - if(width !== 0) { + if(width !== 0) + { this.scale.x = value / width; } - else { + else + { this.scale.x = 1; } @@ -73,17 +78,21 @@ * @memberof DisplayObjectContainer# */ height: { - get: function () { + get: function () + { return this.scale.y * this.getLocalBounds().height; }, - set: function (value) { + set: function (value) + { var height = this.getLocalBounds().height; - if (height !== 0) { + if (height !== 0) + { this.scale.y = value / height ; } - else { + else + { this.scale.y = 1; } @@ -100,18 +109,23 @@ * @memberof DisplayObject# */ cacheAsBitmap: { - get: function () { + get: function () + { return this._cacheAsBitmap; }, - set: function (value) { - if (this._cacheAsBitmap === value) { + set: function (value) + { + if (this._cacheAsBitmap === value) + { return; } - if (value) { + if (value) + { this._generateCachedSprite(); } - else { + else + { this._destroyCachedSprite(); } @@ -126,7 +140,8 @@ * @param child {DisplayObject} The DisplayObject to add to the container * @return {DisplayObject} The child that was added. */ -DisplayObjectContainer.prototype.addChild = function (child) { +DisplayObjectContainer.prototype.addChild = function (child) +{ return this.addChildAt(child, this.children.length); }; @@ -137,14 +152,18 @@ * @param index {Number} The index to place the child in * @return {DisplayObject} The child that was added. */ -DisplayObjectContainer.prototype.addChildAt = function (child, index) { +DisplayObjectContainer.prototype.addChildAt = function (child, index) +{ // prevent adding self as child - if (child === this) { + if (child === this) + { return; } - if (index >= 0 && index <= this.children.length) { - if (child.parent) { + if (index >= 0 && index <= this.children.length) + { + if (child.parent) + { child.parent.removeChild(child); } @@ -154,7 +173,8 @@ return child; } - else { + else + { throw new Error(child + 'addChildAt: The index '+ index +' supplied is out of bounds ' + this.children.length); } }; @@ -165,15 +185,18 @@ * @param child {DisplayObject} * @param child2 {DisplayObject} */ -DisplayObjectContainer.prototype.swapChildren = function (child, child2) { - if (child === child2) { +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) { + if (index1 < 0 || index2 < 0) + { throw new Error('swapChildren: Both the supplied DisplayObjects must be a child of the caller.'); } @@ -187,10 +210,12 @@ * @param child {DisplayObject} The DisplayObject instance to identify * @return {Number} The index position of the child display object to identify */ -DisplayObjectContainer.prototype.getChildIndex = function (child) { +DisplayObjectContainer.prototype.getChildIndex = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { throw new Error('The supplied DisplayObject must be a child of the caller'); } @@ -203,8 +228,10 @@ * @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 */ -DisplayObjectContainer.prototype.setChildIndex = function (child, index) { - if (index < 0 || index >= this.children.length) { +DisplayObjectContainer.prototype.setChildIndex = function (child, index) +{ + if (index < 0 || index >= this.children.length) + { throw new Error('The supplied index is out of bounds'); } @@ -220,8 +247,10 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child at the given index, if any. */ -DisplayObjectContainer.prototype.getChildAt = function (index) { - if (index < 0 || index >= this.children.length) { +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'); } @@ -234,10 +263,12 @@ * @param child {DisplayObject} The DisplayObject to remove * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChild = function (child) { +DisplayObjectContainer.prototype.removeChild = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { return; } @@ -250,7 +281,8 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChildAt = function (index) { +DisplayObjectContainer.prototype.removeChildAt = function (index) +{ var child = this.getChildAt(index); child.parent = null; @@ -265,24 +297,29 @@ * @param beginIndex {Number} The beginning position. Default value is 0. * @param endIndex {Number} The ending position. Default value is size of the container. */ -DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) { +DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) +{ var begin = beginIndex || 0; var end = typeof endIndex === 'number' ? endIndex : this.children.length; var range = end - begin; - if (range > 0 && range <= end) { + if (range > 0 && range <= end) + { var removed = this.children.splice(begin, range); - for (var i = 0; i < removed.length; ++i) { + for (var i = 0; i < removed.length; ++i) + { removed[i].parent = null; } return removed; } - else if (range === 0 && this.children.length === 0) { + else if (range === 0 && this.children.length === 0) + { return []; } - else { + else + { throw new RangeError('removeChildren: numeric values are outside the acceptable range.'); } }; @@ -291,7 +328,8 @@ * Generates and updates the cached sprite for this object. * */ -DisplayObjectContainer.prototype.updateCachedSprite = function () { +DisplayObjectContainer.prototype.updateCachedSprite = function () +{ this._generateCachedSprite(); }; @@ -304,7 +342,8 @@ * @param renderer {CanvasRenderer|WebGLRenderer} The renderer used to generate the texture. * @return {Texture} a texture of the graphics object */ -DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) { +DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) +{ var bounds = this.getLocalBounds(); var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0, renderer, scaleMode, resolution); @@ -322,18 +361,22 @@ * * @private */ -DisplayObjectContainer.prototype.updateTransform = function () { - if (!this.visible) { +DisplayObjectContainer.prototype.updateTransform = function () +{ + if (!this.visible) + { return; } this.displayObjectUpdateTransform(); - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { return; } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } }; @@ -346,8 +389,10 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getBounds = function () { - if (this.children.length === 0) { +DisplayObjectContainer.prototype.getBounds = function () +{ + if (this.children.length === 0) + { return math.Rectangle.EMPTY; } @@ -365,10 +410,12 @@ var childVisible = false; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -386,7 +433,8 @@ maxY = maxY > childMaxY ? maxY : childMaxY; } - if (!childVisible) { + if (!childVisible) + { return math.Rectangle.EMPTY; } @@ -407,12 +455,14 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getLocalBounds = function () { +DisplayObjectContainer.prototype.getLocalBounds = function () +{ var matrixCache = this.worldTransform; this.worldTransform = math.Matrix.IDENTITY; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } @@ -428,13 +478,16 @@ * * @param renderer {WebGLRenderer} The renderer */ -DisplayObjectContainer.prototype.renderWebGL = function (renderer) { +DisplayObjectContainer.prototype.renderWebGL = function (renderer) +{ // if the object is not visible or the alpha is 0 then no need to render this element - if (!this.visible || this.alpha <= 0) { + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } @@ -442,14 +495,17 @@ var i, j; // do a quick check to see if this element has a mask or a filter. - if (this._mask || this._filters) { + if (this._mask || this._filters) + { // push filter first as we need to ensure the stencil buffer is correct for any masking - if (this._filters) { + if (this._filters) + { renderer.spriteBatch.flush(); renderer.filterManager.pushFilter(this._filterBlock); } - if (this._mask) { + if (this._mask) + { renderer.spriteBatch.stop(); renderer.maskManager.pushMask(this.mask, renderer); renderer.spriteBatch.start(); @@ -459,36 +515,42 @@ this._renderWebGL(renderer); // now loop through the children and make sure they get rendered - for (i = 0, j = this.children.length; i < j; i++) { + for (i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderWebGL(renderer); } // time to stop the sprite batch as either a mask element or a filter draw will happen next renderer.spriteBatch.stop(); - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(this._mask, renderer); } - if (this._filters) { + if (this._filters) + { renderer.filterManager.popFilter(); } renderer.spriteBatch.start(); } - else { + else + { this._renderWebGL(renderer); // simple render children! - for (i = 0, j = this.children.length; i < j; ++i) { + for (i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderWebGL(renderer); } } }; -DisplayObjectContainer.prototype._renderWebGL = function (renderer) { +DisplayObjectContainer.prototype._renderWebGL = function (renderer) +{ // this is where content itself gets renderd.. @@ -499,25 +561,31 @@ * * @param renderer {CanvasRenderer} The renderer */ -DisplayObjectContainer.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0) { +DisplayObjectContainer.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -528,13 +596,16 @@ * @param renderer {WebGLRenderer|CanvasRenderer} The renderer * @private */ -DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) { +DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) +{ this._cachedSprite.worldAlpha = this.worldAlpha; - if (renderer.gl) { + if (renderer.gl) + { this._cachedSprite.renderWebGL(renderer); } - else { + else + { this._cachedSprite.renderCanvas(renderer); } }; @@ -544,10 +615,12 @@ * * @private */ -DisplayObjectContainer.prototype._generateCachedSprite = function () { +DisplayObjectContainer.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { // TODO - RenderTexture now *requires* a renderer instance, so this is like broken // because `renderer` isn't actually in scope here :P var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0); @@ -555,7 +628,8 @@ this._cachedSprite = new Sprite(renderTexture); this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.texture.resize(bounds.width | 0, bounds.height | 0); } @@ -580,8 +654,10 @@ * * @private */ -DisplayObjectContainer.prototype._destroyCachedSprite = function () { - if (!this._cachedSprite) { +DisplayObjectContainer.prototype._destroyCachedSprite = function () +{ + if (!this._cachedSprite) + { return; } diff --git a/src/core/display/Sprite.js b/src/core/display/Sprite.js index 707da24..5862aef 100644 --- a/src/core/display/Sprite.js +++ b/src/core/display/Sprite.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param texture {Texture} The texture for this sprite */ -function Sprite(texture) { +function Sprite(texture) +{ DisplayObjectContainer.call(this); /** @@ -85,12 +86,14 @@ this.texture = texture || Texture.EMPTY; } -Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) { +Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) +{ DisplayObjectContainer.prototype.destroy.call(this); this.anchor = null; - if (destroyTexture) { + if (destroyTexture) + { this._texture.destroy(destroyBaseTexture); } @@ -111,10 +114,12 @@ * @memberof Sprite# */ width: { - get: function () { + get: function () + { return this.scale.x * this.texture.frame.width; }, - set: function (value) { + set: function (value) + { this.scale.x = value / this.texture.frame.width; this._width = value; } @@ -127,10 +132,12 @@ * @memberof Sprite# */ height: { - get: function () { + get: function () + { return this.scale.y * this.texture.frame.height; }, - set: function (value) { + set: function (value) + { this.scale.y = value / this.texture.frame.height; this._height = value; } @@ -143,23 +150,29 @@ * @memberof Sprite# */ texture: { - get: function () { + get: function () + { return this._texture; }, - set: function (value) { - if (this._texture === value) { + set: function (value) + { + if (this._texture === value) + { return; } this._texture = value; this.cachedTint = 0xFFFFFF; - if (value) { + if (value) + { // wait for the texture to load - if (value.baseTexture.hasLoaded) { + if (value.baseTexture.hasLoaded) + { this._onTextureUpdate(); } - else { + else + { value.once('update', this._onTextureUpdate.bind(this)); } } @@ -172,18 +185,22 @@ * * @private */ -Sprite.prototype._onTextureUpdate = function () { +Sprite.prototype._onTextureUpdate = function () +{ // so if _width is 0 then width was not set.. - if (this._width) { + if (this._width) + { this.scale.x = this._width / this.texture.frame.width; } - if (this._height) { + if (this._height) + { this.scale.y = this._height / this.texture.frame.height; } }; -Sprite.prototype._renderWebGL = function (renderer) { +Sprite.prototype._renderWebGL = function (renderer) +{ // this is where content gets renderd.. // watch this space for a little render state manager.. @@ -197,7 +214,8 @@ * @param matrix {Matrix} the transformation matrix of the sprite * @return {Rectangle} the framing rectangle */ -Sprite.prototype.getBounds = function (matrix) { +Sprite.prototype.getBounds = function (matrix) +{ var width = this.texture.frame.width; var height = this.texture.frame.height; @@ -224,11 +242,13 @@ if(b === 0 && c === 0) { // scale may be negative! - if (a < 0) { + if (a < 0) + { a *= -1; } - if (d < 0) { + if (d < 0) + { d *= -1; } @@ -293,28 +313,34 @@ * * @param renderer {CanvasRenderer} The renderer */ -Sprite.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) { +Sprite.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) + { return; } - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; renderer.context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } // Ignore null sources - if (this.texture.valid) { + if (this.texture.valid) + { var resolution = this.texture.baseTexture.resolution / renderer.resolution; renderer.context.globalAlpha = this.worldAlpha; // If smoothingEnabled is supported and we need to change the smoothing property for this texture - if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) { + if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) + { renderer.scaleMode = this.texture.baseTexture.scaleMode; renderer.context[renderer.smoothProperty] = (renderer.scaleMode === CONST.scaleModes.LINEAR); } @@ -324,7 +350,8 @@ var dy = (this.texture.trim ? this.texture.trim.y : 0) - (this.anchor.y * this.texture.trim.height); // Allow for pixel rounding - if (renderer.roundPixels) { + if (renderer.roundPixels) + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -337,7 +364,8 @@ dx = dx | 0; dy = dy | 0; } - else { + else + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -348,8 +376,10 @@ ); } - if (this.tint !== 0xFFFFFF) { - if (this.cachedTint !== this.tint) { + if (this.tint !== 0xFFFFFF) + { + if (this.cachedTint !== this.tint) + { this.cachedTint = this.tint; // TODO clean up caching - how to clean up the caches? @@ -368,7 +398,8 @@ this.texture.crop.height / resolution ); } - else { + else + { renderer.context.drawImage( this.texture.baseTexture.source, this.texture.crop.x, @@ -383,11 +414,13 @@ } } - for (var i = 0, j = this.children.length; i < j; i++) { + for (var i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -402,10 +435,12 @@ * @param frameId {String} The frame Id of the texture in the cache * @return {Sprite} A new Sprite using a texture from the texture cache matching the frameId */ -Sprite.fromFrame = function (frameId) { +Sprite.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache' + this); } @@ -420,6 +455,7 @@ * @param imageId {String} The image url of the texture * @return {Sprite} A new Sprite using a texture from the texture cache matching the image id */ -Sprite.fromImage = function (imageId, crossorigin, scaleMode) { +Sprite.fromImage = function (imageId, crossorigin, scaleMode) +{ return new Sprite(Texture.fromImage(imageId, crossorigin, scaleMode)); }; diff --git a/src/core/display/SpriteBatch.js b/src/core/display/SpriteBatch.js index 3187777..c196fef 100644 --- a/src/core/display/SpriteBatch.js +++ b/src/core/display/SpriteBatch.js @@ -12,7 +12,8 @@ * ```js * var container = new SpriteBatch(); * - * for(var i = 0; i < 100; ++i) { + * for(var i = 0; i < 100; ++i) + * { * var sprite = new PIXI.Sprite.fromImage("myImage.png"); * container.addChild(sprite); * } @@ -25,7 +26,8 @@ */ //TODO RENAME to PARTICLE CONTAINER? -function SpriteBatch() { +function SpriteBatch() +{ DisplayObjectContainer.call(this); } @@ -38,7 +40,8 @@ * * @private */ -SpriteBatch.prototype.updateTransform = function () { +SpriteBatch.prototype.updateTransform = function () +{ // TODO don't need to! this.displayObjectUpdateTransform(); // PIXI.DisplayObjectContainer.prototype.updateTransform.call( this ); @@ -50,8 +53,10 @@ * @param renderer {WebGLRenderer} The webgl renderer * @private */ -SpriteBatch.prototype.renderWebGL = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderWebGL = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -71,8 +76,10 @@ * @param renderer {CanvasRenderer} The canvas renderer * @private */ -SpriteBatch.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -84,10 +91,12 @@ this.displayObjectUpdateTransform(); - for (var i = 0; i < this.children.length; ++i) { + for (var i = 0; i < this.children.length; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -95,9 +104,11 @@ context.globalAlpha = this.worldAlpha * child.alpha; - if (child.rotation % (Math.PI * 2) === 0) { + if (child.rotation % (Math.PI * 2) === 0) + { // this is the fastest way to optimise! - if rotation is 0 then we can avoid any kind of setTransform call - if (isRotated) { + if (isRotated) + { context.setTransform( transform.a, transform.b, @@ -122,8 +133,10 @@ frame.height * child.scale.y ); } - else { - if (!isRotated) { + else + { + if (!isRotated) + { isRotated = true; } @@ -131,7 +144,8 @@ var childTransform = child.worldTransform; - if (renderer.roundPixels) { + if (renderer.roundPixels) + { context.setTransform( childTransform.a, childTransform.b, @@ -141,7 +155,8 @@ childTransform.ty | 0 ); } - else { + else + { context.setTransform( childTransform.a, childTransform.b, diff --git a/src/core/index.js b/src/core/index.js index 3954b6f..eb4a82b 100644 --- a/src/core/index.js +++ b/src/core/index.js @@ -58,11 +58,13 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRenderer: function (width, height, options, noWebGL) { + autoDetectRenderer: function (width, height, options, noWebGL) + { width = width || 800; height = height || 600; - if (!noWebGL && require('webgl-enabled')()) { + if (!noWebGL && require('webgl-enabled')()) + { return new core.WebGLRenderer(width, height, options); } @@ -87,7 +89,8 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRecommendedRenderer: function (width, height, options) { + autoDetectRecommendedRenderer: function (width, height, options) + { var isAndroid = /Android/i.test(navigator.userAgent); return core.autoDetectRenderer(width, height, options, isAndroid); diff --git a/src/core/math/Matrix.js b/src/core/math/Matrix.js index c2f87e2..2ff4848 100644 --- a/src/core/math/Matrix.js +++ b/src/core/math/Matrix.js @@ -10,7 +10,8 @@ * @class * @namespace PIXI */ -function Matrix() { +function Matrix() +{ /** * @member {number} * @default 1 @@ -63,7 +64,8 @@ * * @param array {number[]} The array that the matrix will be populated from. */ -Matrix.prototype.fromArray = function (array) { +Matrix.prototype.fromArray = function (array) +{ this.a = array[0]; this.b = array[1]; this.c = array[3]; @@ -78,14 +80,17 @@ * @param transpose {boolean} Whether we need to transpose the matrix or not * @return {number[]} the newly created array which contains the matrix */ -Matrix.prototype.toArray = function (transpose) { - if (!this.array) { +Matrix.prototype.toArray = function (transpose) +{ + if (!this.array) + { this.array = new Float32Array(9); } var array = this.array; - if (transpose) { + if (transpose) + { array[0] = this.a; array[1] = this.b; array[2] = 0; @@ -96,7 +101,8 @@ array[7] = this.ty; array[8] = 1; } - else { + else + { array[0] = this.a; array[1] = this.c; array[2] = this.tx; @@ -119,7 +125,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, transformed through this matrix */ -Matrix.prototype.apply = function (pos, newPos) { +Matrix.prototype.apply = function (pos, newPos) +{ newPos = newPos || new Point(); newPos.x = this.a * pos.x + this.c * pos.y + this.tx; @@ -136,7 +143,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, inverse-transformed through this matrix */ -Matrix.prototype.applyInverse = function (pos, newPos) { +Matrix.prototype.applyInverse = function (pos, newPos) +{ newPos = newPos || new Point(); var id = 1 / (this.a * this.d + this.c * -this.b); @@ -154,7 +162,8 @@ * @param {number} y * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.translate = function (x, y) { +Matrix.prototype.translate = function (x, y) +{ this.tx += x; this.ty += y; @@ -168,7 +177,8 @@ * @param {number} y The amount to scale vertically * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.scale = function (x, y) { +Matrix.prototype.scale = function (x, y) +{ this.a *= x; this.d *= y; this.c *= x; @@ -186,7 +196,8 @@ * @param {number} angle - The angle in radians. * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.rotate = function (angle) { +Matrix.prototype.rotate = function (angle) +{ var cos = Math.cos( angle ); var sin = Math.sin( angle ); @@ -210,7 +221,8 @@ * @param {Matrix} matrix * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.append = function (matrix) { +Matrix.prototype.append = function (matrix) +{ var a1 = this.a; var b1 = this.b; var c1 = this.c; @@ -232,7 +244,8 @@ * * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.identity = function () { +Matrix.prototype.identity = function () +{ this.a = 1; this.b = 0; this.c = 0; diff --git a/src/core/math/Point.js b/src/core/math/Point.js index 7565b2d..632f346 100644 --- a/src/core/math/Point.js +++ b/src/core/math/Point.js @@ -7,7 +7,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -function Point(x, y) { +function Point(x, y) +{ /** * @member {number} * @default 0 @@ -29,7 +30,8 @@ * * @return {Point} a copy of the point */ -Point.prototype.clone = function () { +Point.prototype.clone = function () +{ return new Point(this.x, this.y); }; @@ -40,7 +42,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -Point.prototype.set = function (x, y) { +Point.prototype.set = function (x, y) +{ this.x = x || 0; this.y = y || ( (y !== 0) ? this.x : 0 ) ; }; diff --git a/src/core/math/shapes/Circle.js b/src/core/math/shapes/Circle.js index 69cfdc9..4d76efc 100644 --- a/src/core/math/shapes/Circle.js +++ b/src/core/math/shapes/Circle.js @@ -10,7 +10,8 @@ * @param y {number} The Y coordinate of the center of this circle * @param radius {number} The radius of the circle */ -function Circle(x, y, radius) { +function Circle(x, y, radius) +{ /** * @member {number} * @default 0 @@ -46,7 +47,8 @@ * @method clone * @return {Circle} a copy of the Circle */ -Circle.prototype.clone = function () { +Circle.prototype.clone = function () +{ return new Circle(this.x, this.y, this.radius); }; @@ -58,8 +60,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Circle */ -Circle.prototype.contains = function (x, y) { - if (this.radius <= 0) { +Circle.prototype.contains = function (x, y) +{ + if (this.radius <= 0) + { return false; } @@ -79,6 +83,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Circle.prototype.getBounds = function () { +Circle.prototype.getBounds = function () +{ return new Rectangle(this.x - this.radius, this.y - this.radius, this.radius * 2, this.radius * 2); }; diff --git a/src/core/math/shapes/Ellipse.js b/src/core/math/shapes/Ellipse.js index 4f2d066..fefd01a 100644 --- a/src/core/math/shapes/Ellipse.js +++ b/src/core/math/shapes/Ellipse.js @@ -11,7 +11,8 @@ * @param width {number} The half width of this ellipse * @param height {number} The half height of this ellipse */ -function Ellipse(x, y, width, height) { +function Ellipse(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -53,7 +54,8 @@ * @method clone * @return {Ellipse} a copy of the ellipse */ -Ellipse.prototype.clone = function () { +Ellipse.prototype.clone = function () +{ return new Ellipse(this.x, this.y, this.width, this.height); }; @@ -65,8 +67,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coords are within this ellipse */ -Ellipse.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Ellipse.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } @@ -86,6 +90,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Ellipse.prototype.getBounds = function () { +Ellipse.prototype.getBounds = function () +{ return new Rectangle(this.x - this.width, this.y - this.height, this.width, this.height); }; diff --git a/src/core/math/shapes/Polygon.js b/src/core/math/shapes/Polygon.js index ae89148..fea6d37 100644 --- a/src/core/math/shapes/Polygon.js +++ b/src/core/math/shapes/Polygon.js @@ -10,16 +10,20 @@ * arguments passed can be flat x,y values e.g. `new Polygon(x,y, x,y, x,y, ...)` where `x` and `y` are * Numbers. */ -function Polygon(points) { +function Polygon(points) +{ //if points isn't an array, use arguments as the array - if (!(points instanceof Array)) { + if (!(points instanceof Array)) + { points = Array.prototype.slice.call(arguments); } //if this is a flat array of numbers, convert it to points - if (points[0] instanceof Point) { + if (points[0] instanceof Point) + { var p = []; - for (var i = 0, il = points.length; i < il; i++) { + for (var i = 0, il = points.length; i < il; i++) + { p.push(points[i].x, points[i].y); } @@ -51,7 +55,8 @@ * * @return {Polygon} a copy of the polygon */ -Polygon.prototype.clone = function () { +Polygon.prototype.clone = function () +{ return new Polygon(this.points.slice()); }; @@ -62,19 +67,22 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this polygon */ -Polygon.prototype.contains = function (x, y) { +Polygon.prototype.contains = function (x, y) +{ var inside = false; // use some raycasting to test hits // https://github.com/substack/point-in-polygon/blob/master/index.js var length = this.points.length / 2; - for (var i = 0, j = length - 1; i < length; j = i++) { + for (var i = 0, j = length - 1; i < length; j = i++) + { var xi = this.points[i * 2], yi = this.points[i * 2 + 1], xj = this.points[j * 2], yj = this.points[j * 2 + 1], intersect = ((yi > y) !== (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi); - if (intersect) { + if (intersect) + { inside = !inside; } } diff --git a/src/core/math/shapes/Rectangle.js b/src/core/math/shapes/Rectangle.js index 16ac62a..4008b68 100644 --- a/src/core/math/shapes/Rectangle.js +++ b/src/core/math/shapes/Rectangle.js @@ -10,7 +10,8 @@ * @param width {number} The overall width of this rectangle * @param height {number} The overall height of this rectangle */ -function Rectangle(x, y, width, height) { +function Rectangle(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -60,7 +61,8 @@ * * @return {Rectangle} a copy of the rectangle */ -Rectangle.prototype.clone = function () { +Rectangle.prototype.clone = function () +{ return new Rectangle(this.x, this.y, this.width, this.height); }; @@ -71,13 +73,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rectangle */ -Rectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Rectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/math/shapes/RoundedRectangle.js b/src/core/math/shapes/RoundedRectangle.js index 27d286e..7bf6411 100644 --- a/src/core/math/shapes/RoundedRectangle.js +++ b/src/core/math/shapes/RoundedRectangle.js @@ -11,7 +11,8 @@ * @param height {number} The overall height of this rounded rectangle * @param radius {number} Controls the radius of the rounded corners */ -function RoundedRectangle(x, y, width, height, radius) { +function RoundedRectangle(x, y, width, height, radius) +{ /** * @member {number} * @default 0 @@ -58,7 +59,8 @@ * * @return {RoundedRectangle} a copy of the rounded rectangle */ -RoundedRectangle.prototype.clone = function () { +RoundedRectangle.prototype.clone = function () +{ return new RoundedRectangle(this.x, this.y, this.width, this.height, this.radius); }; @@ -69,13 +71,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rounded Rectangle */ -RoundedRectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +RoundedRectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/primitives/Graphics.js b/src/core/primitives/Graphics.js index 261c534..e902d2a 100644 --- a/src/core/primitives/Graphics.js +++ b/src/core/primitives/Graphics.js @@ -16,7 +16,8 @@ * @extends DisplayObjectContainer * @namespace PIXI */ -function Graphics() { +function Graphics() +{ DisplayObjectContainer.call(this); this.renderable = true; @@ -154,16 +155,20 @@ * @private */ cacheAsBitmap: { - get: function () { + get: function () + { return this._cacheAsBitmap; }, - set: function (value) { + set: function (value) + { this._cacheAsBitmap = value; - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._generateCachedSprite(); } - else { + else + { this.destroyCachedSprite(); this.dirty = true; } @@ -176,7 +181,8 @@ * * @return {Graphics} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ var clone = new Graphics(); clone.renderable = this.renderable; @@ -192,7 +198,8 @@ clone.cachedSpriteDirty = this.cachedSpriteDirty; // copy graphics data - for (var i = 0; i < this.graphicsData.length; ++i) { + for (var i = 0; i < this.graphicsData.length; ++i) + { clone.graphicsData.push(this.graphicsData.clone()); } @@ -211,17 +218,21 @@ * @param alpha {number} alpha of the line to draw, will update the objects stored style * @return {Graphics} */ -Graphics.prototype.lineStyle = function (lineWidth, color, alpha) { +Graphics.prototype.lineStyle = function (lineWidth, color, alpha) +{ this.lineWidth = lineWidth || 0; this.lineColor = color || 0; this.lineAlpha = (arguments.length < 3) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length) + { // halfway through a line? start a new one! this.drawShape( new math.Polygon( this.currentPath.shape.points.slice(-2) )); } - else { + else + { // otherwise its empty so lets just set the line properties this.currentPath.lineWidth = this.lineWidth; this.currentPath.lineColor = this.lineColor; @@ -239,7 +250,8 @@ * @param y {number} the Y coordinate to move to * @return {Graphics} */ -Graphics.prototype.moveTo = function (x, y) { +Graphics.prototype.moveTo = function (x, y) +{ this.drawShape(new math.Polygon([x,y])); return this; @@ -253,7 +265,8 @@ * @param y {number} the Y coordinate to draw to * @return {Graphics} */ -Graphics.prototype.lineTo = function (x, y) { +Graphics.prototype.lineTo = function (x, y) +{ this.currentPath.shape.points.push(x, y); this.dirty = true; @@ -270,13 +283,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -285,7 +302,8 @@ n = 20, points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { this.moveTo(0, 0); } @@ -293,7 +311,8 @@ var fromY = points[points.length-1]; var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; xa = fromX + ( (cpX - fromX) * j ); @@ -319,13 +338,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -342,7 +365,8 @@ var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; dt = (1 - j); @@ -373,13 +397,17 @@ * @param radius {number} The radius of the arc * @return {Graphics} */ -Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points.push(x1, y1); } } - else { + else + { this.moveTo(x1, y1); } @@ -392,12 +420,15 @@ b2 = x2 - x1, mm = Math.abs(a1 * b2 - b1 * a2); - if (mm < 1.0e-8 || radius === 0) { - if (points[points.length-2] !== x1 || points[points.length-1] !== y1) { + if (mm < 1.0e-8 || radius === 0) + { + if (points[points.length-2] !== x1 || points[points.length-1] !== y1) + { points.push(x1, y1); } } - else { + else + { var dd = a1 * a1 + b1 * b1, cc = a2 * a2 + b2 * b2, tt = a1 * a2 + b1 * b2, @@ -433,42 +464,51 @@ * @param anticlockwise {boolean} Optional. Specifies whether the drawing should be counterclockwise or clockwise. False is default, and indicates clockwise, while true indicates counter-clockwise. * @return {Graphics} */ -Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) { +Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) +{ var startX = cx + Math.cos(startAngle) * radius; var startY = cy + Math.sin(startAngle) * radius; var points; // TODO - This if-else makes no sense. It uses currentPath in the else where it doesn't exist... - if (this.currentPath) { + if (this.currentPath) + { points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { points.push(startX, startY); } - else if (points[points.length-2] !== startX || points[points.length-1] !== startY) { + else if (points[points.length-2] !== startX || points[points.length-1] !== startY) + { points.push(startX, startY); } } - else { + else + { this.moveTo(startX, startY); points = this.currentPath.shape.points; } - if (startAngle === endAngle) { + if (startAngle === endAngle) + { return this; } - if (!anticlockwise && endAngle <= startAngle) { + if (!anticlockwise && endAngle <= startAngle) + { endAngle += Math.PI * 2; } - else if (anticlockwise && startAngle <= endAngle) { + else if (anticlockwise && startAngle <= endAngle) + { startAngle += Math.PI * 2; } var sweep = anticlockwise ? (startAngle - endAngle) *-1 : (endAngle - startAngle); var segs = (Math.abs(sweep)/ (Math.PI * 2)) * 40; - if (sweep === 0) { + if (sweep === 0) + { return this; } @@ -482,7 +522,8 @@ var remainder = ( segMinus % 1 ) / segMinus; - for (var i = 0; i <= segMinus; ++i) { + for (var i = 0; i <= segMinus; ++i) + { var real = i + remainder * i; var angle = ((theta) + startAngle + (theta2 * real)); @@ -506,13 +547,16 @@ * @param alpha {number} the alpha of the fill * @return {Graphics} */ -Graphics.prototype.beginFill = function (color, alpha) { +Graphics.prototype.beginFill = function (color, alpha) +{ this.filling = true; this.fillColor = color || 0; this.fillAlpha = (alpha === undefined) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length <= 2) + { this.currentPath.fill = this.filling; this.currentPath.fillColor = this.fillColor; this.currentPath.fillAlpha = this.fillAlpha; @@ -526,7 +570,8 @@ * * @return {Graphics} */ -Graphics.prototype.endFill = function () { +Graphics.prototype.endFill = function () +{ this.filling = false; this.fillColor = null; this.fillAlpha = 1; @@ -542,7 +587,8 @@ * @param height {number} The height of the rectangle * @return {Graphics} */ -Graphics.prototype.drawRect = function ( x, y, width, height ) { +Graphics.prototype.drawRect = function ( x, y, width, height ) +{ this.drawShape(new math.Rectangle(x,y, width, height)); return this; @@ -556,7 +602,8 @@ * @param height {number} The height of the rectangle * @param radius {number} Radius of the rectangle corners */ -Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) { +Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) +{ this.drawShape(new math.RoundedRectangle(x, y, width, height, radius)); return this; @@ -570,7 +617,8 @@ * @param radius {number} The radius of the circle * @return {Graphics} */ -Graphics.prototype.drawCircle = function (x, y, radius) { +Graphics.prototype.drawCircle = function (x, y, radius) +{ this.drawShape(new math.Circle(x,y, radius)); return this; @@ -585,7 +633,8 @@ * @param height {number} The half height of the ellipse * @return {Graphics} */ -Graphics.prototype.drawEllipse = function (x, y, width, height) { +Graphics.prototype.drawEllipse = function (x, y, width, height) +{ this.drawShape(new math.Ellipse(x, y, width, height)); return this; @@ -597,8 +646,10 @@ * @param path {Array} The path data used to construct the polygon. * @return {Graphics} */ -Graphics.prototype.drawPolygon = function (path) { - if (!(path instanceof Array)) { +Graphics.prototype.drawPolygon = function (path) +{ + if (!(path instanceof Array)) + { path = Array.prototype.slice.call(arguments); } @@ -612,7 +663,8 @@ * * @return {Graphics} */ -Graphics.prototype.clear = function () { +Graphics.prototype.clear = function () +{ this.lineWidth = 0; this.filling = false; @@ -631,7 +683,8 @@ * @param scaleMode {number} Should be one of the scaleMode consts * @return {Texture} a texture of the graphics object */ -Graphics.prototype.generateTexture = function (resolution, scaleMode) { +Graphics.prototype.generateTexture = function (resolution, scaleMode) +{ resolution = resolution || 1; var bounds = this.getBounds(); @@ -655,17 +708,21 @@ * * @param renderer {WebGLRenderer} */ -Graphics.prototype._renderWebGL = function (renderer) { +Graphics.prototype._renderWebGL = function (renderer) +{ // if the sprite is not visible or the alpha is 0 then no need to render this element - if (this.isMask === true) { + if (this.isMask === true) + { return; } // this code may still be needed so leaving for now.. - // + // /* - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture on the gpu too! @@ -681,17 +738,24 @@ return; } - */ - - // check if the webgl graphic needs to be updated - if (this.glDirty) { - this.dirty = true; - this.glDirty = false; - } + else */ - renderer.setObjectRendererer(renderer.graphicsRenderer); - renderer.graphicsRenderer.render(this); + renderer.spriteBatch.stop(); + renderer.blendModeManager.setBlendMode(this.blendMode); + // check blend mode + renderer.blendModeManager.setBlendMode( this.blendMode ); + + // check if the webgl graphic needs to be updated + if (this.glDirty) + { + this.dirty = true; + this.glDirty = false; + } + + WebGLGraphics.renderGraphics(this, renderer); + + renderer.spriteBatch.start(); }; /** @@ -700,14 +764,18 @@ * @param renderer {CanvasRenderer} * @private */ -Graphics.prototype.renderCanvas = function (renderer) { +Graphics.prototype.renderCanvas = function (renderer) +{ // 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.isMask === true) { + if (!this.visible || this.alpha <= 0 || this.isMask === true) + { return; } - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture @@ -723,16 +791,19 @@ return; } - else { + else + { var context = renderer.context; var transform = this.worldTransform; - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } @@ -748,11 +819,13 @@ CanvasGraphics.renderGraphics(this, context); - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } } @@ -763,13 +836,16 @@ * * @return {Rectangle} the rectangular bounding area */ -Graphics.prototype.getBounds = function (matrix) { +Graphics.prototype.getBounds = function (matrix) +{ // return an empty object if the item is a mask! - if (this.isMask) { + if (this.isMask) + { return math.Rectangle.EMPTY; } - if (this.dirty) { + if (this.dirty) + { this.updateLocalBounds(); this.glDirty = true; @@ -841,23 +917,27 @@ * Update the bounds of the object * */ -Graphics.prototype.updateLocalBounds = function () { +Graphics.prototype.updateLocalBounds = function () +{ var minX = Infinity; var maxX = -Infinity; var minY = Infinity; var maxY = -Infinity; - if (this.graphicsData.length) { + if (this.graphicsData.length) + { var shape, points, x, y, w, h; - for (var i = 0; i < this.graphicsData.length; i++) { + for (var i = 0; i < this.graphicsData.length; i++) + { var data = this.graphicsData[i]; var type = data.type; var lineWidth = data.lineWidth; shape = data.shape; - if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) { + if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) + { x = shape.x - lineWidth/2; y = shape.y - lineWidth/2; w = shape.width + lineWidth; @@ -869,7 +949,8 @@ minY = y < minY ? y : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.CIRC) { + else if (type === CONST.SHAPES.CIRC) + { x = shape.x; y = shape.y; w = shape.radius + lineWidth/2; @@ -881,7 +962,8 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.ELIP) { + else if (type === CONST.SHAPES.ELIP) + { x = shape.x; y = shape.y; w = shape.width + lineWidth/2; @@ -893,11 +975,13 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else { + else + { // POLY points = shape.points; - for (var j = 0; j < points.length; j += 2) { + for (var j = 0; j < points.length; j += 2) + { x = points[j]; y = points[j+1]; @@ -910,7 +994,8 @@ } } } - else { + else + { minX = 0; maxX = 0; minY = 0; @@ -931,10 +1016,12 @@ * * @private */ -Graphics.prototype._generateCachedSprite = function () { +Graphics.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { var canvasBuffer = new CanvasBuffer(bounds.width, bounds.height); var texture = Texture.fromCanvas(canvasBuffer.canvas); @@ -943,7 +1030,8 @@ this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.buffer.resize(bounds.width, bounds.height); } @@ -968,7 +1056,8 @@ * * @private */ -Graphics.prototype.updateCachedSpriteTexture = function () { +Graphics.prototype.updateCachedSpriteTexture = function () +{ var cachedSprite = this._cachedSprite; var texture = cachedSprite.texture; var canvas = cachedSprite.buffer.canvas; @@ -989,7 +1078,8 @@ * Destroys a previous cached sprite. * */ -Graphics.prototype.destroyCachedSprite = function () { +Graphics.prototype.destroyCachedSprite = function () +{ this._cachedSprite.texture.destroy(true); // let the gc collect the unused sprite @@ -1003,10 +1093,13 @@ * @param {Circle|Rectangle|Ellipse|Line|Polygon} shape The Shape object to draw. * @return {GraphicsData} The generated GraphicsData object. */ -Graphics.prototype.drawShape = function (shape) { - if (this.currentPath) { +Graphics.prototype.drawShape = function (shape) +{ + if (this.currentPath) + { // check current path! - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath.shape.points.length <= 2) + { this.graphicsData.pop(); } } @@ -1017,7 +1110,8 @@ this.graphicsData.push(data); - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { data.shape.closed = this.filling; this.currentPath = data; } diff --git a/src/core/primitives/GraphicsData.js b/src/core/primitives/GraphicsData.js index 99decbe..788f6f2 100644 --- a/src/core/primitives/GraphicsData.js +++ b/src/core/primitives/GraphicsData.js @@ -4,7 +4,8 @@ * @class * @namespace PIXI */ -function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) { +function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) +{ this.lineWidth = lineWidth; this.lineColor = lineColor; this.lineAlpha = lineAlpha; @@ -27,7 +28,8 @@ * * @return {GraphicsData} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ return new GraphicsData( this.lineWidth, this.lineColor, diff --git a/src/core/renderers/canvas/CanvasRenderer.js b/src/core/renderers/canvas/CanvasRenderer.js index 15a0978..7aebd44 100644 --- a/src/core/renderers/canvas/CanvasRenderer.js +++ b/src/core/renderers/canvas/CanvasRenderer.js @@ -17,17 +17,22 @@ * @param [options.resolution=1] {number} the resolution of the renderer retina would be 2 * @param [options.clearBeforeRender=true] {boolean} This sets if the CanvasRenderer will clear the canvas or not before the new render pass. */ -function CanvasRenderer(width, height, options) { +function CanvasRenderer(width, height, options) +{ utils.sayHello('Canvas'); - if (options) { - for (var i in CONST.defaultRenderOptions) { - if (typeof options[i] === 'undefined') { + if (options) + { + for (var i in CONST.defaultRenderOptions) + { + if (typeof options[i] === 'undefined') + { options[i] = CONST.defaultRenderOptions[i]; } } } - else { + else + { options = CONST.defaultRenderOptions; } @@ -156,19 +161,24 @@ this.smoothProperty = null; - if (this.context.imageSmoothingEnabled) { + if (this.context.imageSmoothingEnabled) + { this.smoothProperty = 'imageSmoothingEnabled'; } - else if (this.context.webkitImageSmoothingEnabled) { + else if (this.context.webkitImageSmoothingEnabled) + { this.smoothProperty = 'webkitImageSmoothingEnabled'; } - else if (this.context.mozImageSmoothingEnabled) { + else if (this.context.mozImageSmoothingEnabled) + { this.smoothProperty = 'mozImageSmoothingEnabled'; } - else if (this.context.oImageSmoothingEnabled) { + else if (this.context.oImageSmoothingEnabled) + { this.smoothProperty = 'oImageSmoothingEnabled'; } - else if (this.context.msImageSmoothingEnabled) { + else if (this.context.msImageSmoothingEnabled) + { this.smoothProperty = 'msImageSmoothingEnabled'; } @@ -193,10 +203,12 @@ * @memberof CanvasRenderer# */ backgroundColor: { - get: function () { + get: function () + { return this._backgroundColor; }, - set: function (val) { + set: function (val) + { this._backgroundColor = val; this._backgroundColorString = utils.hex2string(val); } @@ -208,7 +220,8 @@ * * @param object {DisplayObject} the object to be rendered */ -CanvasRenderer.prototype.render = function (object) { +CanvasRenderer.prototype.render = function (object) +{ object.updateTransform(); this.context.setTransform(1,0,0,1,0,0); @@ -218,16 +231,20 @@ this.currentBlendMode = CONST.blendModes.NORMAL; this.context.globalCompositeOperation = this.blendModes[CONST.blendModes.NORMAL]; - if (navigator.isCocoonJS && this.view.screencanvas) { + if (navigator.isCocoonJS && this.view.screencanvas) + { this.context.fillStyle = 'black'; this.context.clear(); } - if (this.clearBeforeRender) { - if (this.transparent) { + if (this.clearBeforeRender) + { + if (this.transparent) + { this.context.clearRect(0, 0, this.width, this.height); } - else { + else + { this.context.fillStyle = this._backgroundColorString; this.context.fillRect(0, 0, this.width , this.height); } @@ -241,8 +258,10 @@ * * @param [removeView=false] {boolean} Removes the Canvas element from the DOM. */ -CanvasRenderer.prototype.destroy = function (removeView) { - if (removeView && this.view.parent) { +CanvasRenderer.prototype.destroy = function (removeView) +{ + if (removeView && this.view.parent) + { this.view.parent.removeChild(this.view); } @@ -257,14 +276,16 @@ * @param width {number} the new width of the canvas view * @param height {number} the new height of the canvas view */ -CanvasRenderer.prototype.resize = function (width, height) { +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) { + if (this.autoResize) + { this.view.style.width = this.width / this.resolution + 'px'; this.view.style.height = this.height / this.resolution + 'px'; } @@ -276,7 +297,8 @@ * @param displayObject {DisplayObject} The displayObject to render * @private */ -CanvasRenderer.prototype.renderDisplayObject = function (displayObject) { +CanvasRenderer.prototype.renderDisplayObject = function (displayObject) +{ displayObject.renderCanvas(this); }; @@ -285,11 +307,14 @@ * * @private */ -CanvasRenderer.prototype._mapBlendModes = function () { - if (!this.blendModes) { +CanvasRenderer.prototype._mapBlendModes = function () +{ + if (!this.blendModes) + { this.blendModes = {}; - if (utils.canUseNewCanvasBlendModes()) { + if (utils.canUseNewCanvasBlendModes()) + { this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? this.blendModes[CONST.blendModes.MULTIPLY] = 'multiply'; @@ -308,7 +333,8 @@ this.blendModes[CONST.blendModes.COLOR] = 'color'; this.blendModes[CONST.blendModes.LUMINOSITY] = 'luminosity'; } - else { + else + { // this means that the browser does not support the cool new blend modes in canvas 'cough' ie 'cough' this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? diff --git a/src/core/renderers/canvas/utils/CanvasBuffer.js b/src/core/renderers/canvas/utils/CanvasBuffer.js index ebe5d47..b183a66 100644 --- a/src/core/renderers/canvas/utils/CanvasBuffer.js +++ b/src/core/renderers/canvas/utils/CanvasBuffer.js @@ -6,7 +6,8 @@ * @param width {number} the width for the newly created canvas * @param height {number} the height for the newly created canvas */ -function CanvasBuffer(width, height) { +function CanvasBuffer(width, height) +{ /** * The Canvas object that belongs to this CanvasBuffer. * @@ -36,10 +37,12 @@ * @memberof CanvasBuffer# */ width: { - get: function () { + get: function () + { return this.canvas.width; }, - set: function (val) { + set: function (val) + { this.canvas.width = val; } }, @@ -50,10 +53,12 @@ * @memberof CanvasBuffer# */ height: { - get: function () { + get: function () + { return this.canvas.height; }, - set: function (val) { + set: function (val) + { this.canvas.height = val; } } @@ -64,7 +69,8 @@ * * @private */ -CanvasBuffer.prototype.clear = function () { +CanvasBuffer.prototype.clear = function () +{ this.context.setTransform(1, 0, 0, 1, 0, 0); this.context.clearRect(0,0, this.canvas.width, this.canvas.height); }; @@ -75,7 +81,8 @@ * @param width {number} the new width of the canvas * @param height {number} the new height of the canvas */ -CanvasBuffer.prototype.resize = function (width, height) { +CanvasBuffer.prototype.resize = function (width, height) +{ this.canvas.width = width; this.canvas.height = height; }; diff --git a/src/core/renderers/canvas/utils/CanvasGraphics.js b/src/core/renderers/canvas/utils/CanvasGraphics.js index c7eaa2a..3f2a91f 100644 --- a/src/core/renderers/canvas/utils/CanvasGraphics.js +++ b/src/core/renderers/canvas/utils/CanvasGraphics.js @@ -13,15 +13,18 @@ * @param graphics {Graphics} the actual graphics object to render * @param context {CanvasRenderingContext2D} the 2d drawing method of the canvas */ -CanvasGraphics.renderGraphics = function (graphics, context) { +CanvasGraphics.renderGraphics = function (graphics, context) +{ var worldAlpha = graphics.worldAlpha; - if (graphics.dirty) { + if (graphics.dirty) + { this.updateGraphicsTint(graphics); graphics.dirty = false; } - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; @@ -30,69 +33,82 @@ context.lineWidth = data.lineWidth; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { context.beginPath(); var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } - if (shape.closed) { + if (shape.closed) + { context.lineTo(points[0], points[1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fillRect(shape.x, shape.y, shape.width, shape.height); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.strokeRect(shape.x, shape.y, shape.width, shape.height); } } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.beginPath(); context.arc(shape.x, shape.y, shape.radius,0,2*Math.PI); context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas var w = shape.width * 2; @@ -119,18 +135,21 @@ context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; var width = shape.width; @@ -152,13 +171,15 @@ context.quadraticCurveTo(rx, ry, rx, ry + radius); context.closePath(); - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); @@ -174,45 +195,54 @@ * @param graphics {Graphics} the graphics which will be used as a mask * @param context {CanvasRenderingContext2D} the context 2d method of the canvas */ -CanvasGraphics.renderGraphicsMask = function (graphics, context) { +CanvasGraphics.renderGraphicsMask = function (graphics, context) +{ var len = graphics.graphicsData.length; - if (len === 0) { + if (len === 0) + { return; } context.beginPath(); - for (var i = 0; i < len; i++) { + for (var i = 0; i < len; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { context.rect(shape.x, shape.y, shape.width, shape.height); context.closePath(); } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.arc(shape.x, shape.y, shape.radius, 0, 2 * Math.PI); context.closePath(); } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas @@ -237,7 +267,8 @@ context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); context.closePath(); } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; @@ -262,8 +293,10 @@ } }; -CanvasGraphics.updateGraphicsTint = function (graphics) { - if (graphics.tint === 0xFFFFFF) { +CanvasGraphics.updateGraphicsTint = function (graphics) +{ + if (graphics.tint === 0xFFFFFF) + { return; } @@ -271,7 +304,8 @@ var tintG = (graphics.tint >> 8 & 0xFF) / 255; var tintB = (graphics.tint & 0xFF)/ 255; - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var fillColor = data.fillColor | 0; diff --git a/src/core/renderers/canvas/utils/CanvasMaskManager.js b/src/core/renderers/canvas/utils/CanvasMaskManager.js index e04a733..9827d36 100644 --- a/src/core/renderers/canvas/utils/CanvasMaskManager.js +++ b/src/core/renderers/canvas/utils/CanvasMaskManager.js @@ -6,7 +6,8 @@ * @class * @namespace PIXI */ -function CanvasMaskManager() {} +function CanvasMaskManager() +{} CanvasMaskManager.prototype.constructor = CanvasMaskManager; module.exports = CanvasMaskManager; @@ -17,7 +18,8 @@ * @param maskData {object} the maskData that will be pushed * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.pushMask = function (maskData, renderer) { +CanvasMaskManager.prototype.pushMask = function (maskData, renderer) +{ renderer.context.save(); var cacheAlpha = maskData.alpha; @@ -45,6 +47,7 @@ * * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.popMask = function (renderer) { +CanvasMaskManager.prototype.popMask = function (renderer) +{ renderer.context.restore(); }; diff --git a/src/core/renderers/canvas/utils/CanvasTinter.js b/src/core/renderers/canvas/utils/CanvasTinter.js index 17e0529..d2fb1bc 100644 --- a/src/core/renderers/canvas/utils/CanvasTinter.js +++ b/src/core/renderers/canvas/utils/CanvasTinter.js @@ -14,7 +14,8 @@ * @param color {number} the color to use to tint the sprite with * @return {HTMLCanvasElement} The tinted canvas */ -CanvasTinter.getTintedTexture = function (sprite, color) { +CanvasTinter.getTintedTexture = function (sprite, color) +{ var texture = sprite.texture; color = CanvasTinter.roundColor(color); @@ -23,7 +24,8 @@ texture.tintCache = texture.tintCache || {}; - if (texture.tintCache[stringColor]) { + if (texture.tintCache[stringColor]) + { return texture.tintCache[stringColor]; } @@ -33,14 +35,16 @@ //CanvasTinter.tintWithPerPixel(texture, stringColor, canvas); CanvasTinter.tintMethod(texture, color, canvas); - if (CanvasTinter.convertTintToImage) { + if (CanvasTinter.convertTintToImage) + { // is this better? var tintImage = new Image(); tintImage.src = canvas.toDataURL(); texture.tintCache[stringColor] = tintImage; } - else { + else + { texture.tintCache[stringColor] = canvas; // if we are not converting the texture to an image then we need to lose the reference to the canvas CanvasTinter.canvas = null; @@ -56,7 +60,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithMultiply = function (texture, color, canvas) { +CanvasTinter.tintWithMultiply = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -104,7 +109,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithOverlay = function (texture, color, canvas) { +CanvasTinter.tintWithOverlay = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -139,7 +145,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithPerPixel = function (texture, color, canvas) { +CanvasTinter.tintWithPerPixel = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -167,7 +174,8 @@ var pixels = pixelData.data; - for (var i = 0; i < pixels.length; i += 4) { + for (var i = 0; i < pixels.length; i += 4) + { pixels[i+0] *= r; pixels[i+1] *= g; pixels[i+2] *= b; @@ -181,7 +189,8 @@ * * @param color {number} the color to round, should be a hex color */ -CanvasTinter.roundColor = function (color) { +CanvasTinter.roundColor = function (color) +{ var step = CanvasTinter.cacheStepsPerColorChannel; var rgbValues = utils.hex2rgb(color); diff --git a/src/core/display/DisplayObject.js b/src/core/display/DisplayObject.js index 66ebc3c..20e778c 100644 --- a/src/core/display/DisplayObject.js +++ b/src/core/display/DisplayObject.js @@ -7,7 +7,8 @@ * @class * @namespace PIXI */ -function DisplayObject() { +function DisplayObject() +{ /** * The coordinate of the object relative to the local coordinates of the parent. * @@ -152,10 +153,12 @@ * @memberof DisplayObject# */ x: { - get: function () { + get: function () + { return this.position.x; }, - set: function (value) { + set: function (value) + { this.position.x = value; } }, @@ -167,10 +170,12 @@ * @memberof DisplayObject# */ y: { - get: function () { + get: function () + { return this.position.y; }, - set: function (value) { + set: function (value) + { this.position.y = value; } }, @@ -183,11 +188,13 @@ * @readonly */ worldVisible: { - get: function () { + get: function () + { var item = this; do { - if (!item.visible) { + if (!item.visible) + { return false; } @@ -207,17 +214,21 @@ * @memberof DisplayObject# */ mask: { - get: function () { + get: function () + { return this._mask; }, - set: function (value) { - if (this._mask) { + set: function (value) + { + if (this._mask) + { this._mask.isMask = false; } this._mask = value; - if (this._mask) { + if (this._mask) + { this._mask.isMask = true; } } @@ -232,18 +243,23 @@ * @memberof DisplayObject# */ filters: { - get: function () { + get: function () + { return this._filters; }, - set: function (value) { - if (value) { + set: function (value) + { + if (value) + { // now put all the passes in one place.. var passes = []; - for (var i = 0; i < value.length; i++) { + for (var i = 0; i < value.length; i++) + { var filterPasses = value[i].passes; - for (var j = 0; j < filterPasses.length; j++) { + for (var j = 0; j < filterPasses.length; j++) + { passes.push(filterPasses[j]); } } @@ -264,8 +280,9 @@ * * @private */ -DisplayObject.prototype.updateTransform = function () { - +DisplayObject.prototype.updateTransform = function () +{ + // create some matrix refs for easy access var pt = this.parent.worldTransform; var wt = this.worldTransform; @@ -274,9 +291,11 @@ var a, b, c, d, tx, ty; // so if rotation is between 0 then we can simplify the multiplication process.. - if (this.rotation % math.PI_2) { + if (this.rotation % math.PI_2) + { // 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) { + if (this.rotation !== this.rotationCache) + { this.rotationCache = this.rotation; this._sr = Math.sin(this.rotation); this._cr = Math.cos(this.rotation); @@ -291,7 +310,8 @@ ty = this.position.y; // check for pivot.. not often used so geared towards that fact! - if (this.pivot.x || this.pivot.y) { + 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; } @@ -304,7 +324,8 @@ wt.tx = tx * pt.a + ty * pt.c + pt.tx; wt.ty = tx * pt.b + ty * pt.d + pt.ty; } - else { + else + { // lets do the fast version as we know there is no rotation.. a = this.scale.x; d = this.scale.y; @@ -333,7 +354,8 @@ * @param matrix {Matrix} * @return {Rectangle} the rectangular bounding area */ -DisplayObject.prototype.getBounds = function (/* matrix */) { +DisplayObject.prototype.getBounds = function (/* matrix */) +{ return math.Rectangle.EMPTY; }; @@ -342,7 +364,8 @@ * * @return {Rectangle} the rectangular bounding area */ -DisplayObject.prototype.getLocalBounds = function () { +DisplayObject.prototype.getLocalBounds = function () +{ return this.getBounds(math.Matrix.IDENTITY); }; @@ -352,7 +375,8 @@ * @param position {Point} The world origin to calculate from * @return {Point} A point object representing the position of this object */ -DisplayObject.prototype.toGlobal = function (position) { +DisplayObject.prototype.toGlobal = function (position) +{ // don't need to u[date the lot this.displayObjectUpdateTransform(); return this.worldTransform.apply(position); @@ -365,8 +389,10 @@ * @param [from] {DisplayObject} The DisplayObject to calculate the global position from * @return {Point} A point object representing the position of this object */ -DisplayObject.prototype.toLocal = function (position, from) { - if (from) { +DisplayObject.prototype.toLocal = function (position, from) +{ + if (from) + { position = from.toGlobal(position); } @@ -381,7 +407,8 @@ * @param renderer {WebGLRenderer} The renderer * @private */ -DisplayObject.prototype.renderWebGL = function (/* renderer */) { +DisplayObject.prototype.renderWebGL = function (/* renderer */) +{ // OVERWRITE; }; @@ -391,6 +418,7 @@ * @param renderer {CanvasRenderer} The renderer * @private */ -DisplayObject.prototype.renderCanvas = function (/* renderer */) { +DisplayObject.prototype.renderCanvas = function (/* renderer */) +{ // OVERWRITE; }; diff --git a/src/core/display/DisplayObjectContainer.js b/src/core/display/DisplayObjectContainer.js index 689f40b..4625ee8 100644 --- a/src/core/display/DisplayObjectContainer.js +++ b/src/core/display/DisplayObjectContainer.js @@ -12,7 +12,8 @@ * @extends DisplayObject * @namespace PIXI */ -function DisplayObjectContainer() { +function DisplayObjectContainer() +{ DisplayObject.call(this); /** @@ -47,17 +48,21 @@ * @memberof DisplayObjectContainer# */ width: { - get: function () { + get: function () + { return this.scale.x * this.getLocalBounds().width; }, - set: function (value) { + set: function (value) + { var width = this.getLocalBounds().width; - if(width !== 0) { + if(width !== 0) + { this.scale.x = value / width; } - else { + else + { this.scale.x = 1; } @@ -73,17 +78,21 @@ * @memberof DisplayObjectContainer# */ height: { - get: function () { + get: function () + { return this.scale.y * this.getLocalBounds().height; }, - set: function (value) { + set: function (value) + { var height = this.getLocalBounds().height; - if (height !== 0) { + if (height !== 0) + { this.scale.y = value / height ; } - else { + else + { this.scale.y = 1; } @@ -100,18 +109,23 @@ * @memberof DisplayObject# */ cacheAsBitmap: { - get: function () { + get: function () + { return this._cacheAsBitmap; }, - set: function (value) { - if (this._cacheAsBitmap === value) { + set: function (value) + { + if (this._cacheAsBitmap === value) + { return; } - if (value) { + if (value) + { this._generateCachedSprite(); } - else { + else + { this._destroyCachedSprite(); } @@ -126,7 +140,8 @@ * @param child {DisplayObject} The DisplayObject to add to the container * @return {DisplayObject} The child that was added. */ -DisplayObjectContainer.prototype.addChild = function (child) { +DisplayObjectContainer.prototype.addChild = function (child) +{ return this.addChildAt(child, this.children.length); }; @@ -137,14 +152,18 @@ * @param index {Number} The index to place the child in * @return {DisplayObject} The child that was added. */ -DisplayObjectContainer.prototype.addChildAt = function (child, index) { +DisplayObjectContainer.prototype.addChildAt = function (child, index) +{ // prevent adding self as child - if (child === this) { + if (child === this) + { return; } - if (index >= 0 && index <= this.children.length) { - if (child.parent) { + if (index >= 0 && index <= this.children.length) + { + if (child.parent) + { child.parent.removeChild(child); } @@ -154,7 +173,8 @@ return child; } - else { + else + { throw new Error(child + 'addChildAt: The index '+ index +' supplied is out of bounds ' + this.children.length); } }; @@ -165,15 +185,18 @@ * @param child {DisplayObject} * @param child2 {DisplayObject} */ -DisplayObjectContainer.prototype.swapChildren = function (child, child2) { - if (child === child2) { +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) { + if (index1 < 0 || index2 < 0) + { throw new Error('swapChildren: Both the supplied DisplayObjects must be a child of the caller.'); } @@ -187,10 +210,12 @@ * @param child {DisplayObject} The DisplayObject instance to identify * @return {Number} The index position of the child display object to identify */ -DisplayObjectContainer.prototype.getChildIndex = function (child) { +DisplayObjectContainer.prototype.getChildIndex = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { throw new Error('The supplied DisplayObject must be a child of the caller'); } @@ -203,8 +228,10 @@ * @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 */ -DisplayObjectContainer.prototype.setChildIndex = function (child, index) { - if (index < 0 || index >= this.children.length) { +DisplayObjectContainer.prototype.setChildIndex = function (child, index) +{ + if (index < 0 || index >= this.children.length) + { throw new Error('The supplied index is out of bounds'); } @@ -220,8 +247,10 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child at the given index, if any. */ -DisplayObjectContainer.prototype.getChildAt = function (index) { - if (index < 0 || index >= this.children.length) { +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'); } @@ -234,10 +263,12 @@ * @param child {DisplayObject} The DisplayObject to remove * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChild = function (child) { +DisplayObjectContainer.prototype.removeChild = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { return; } @@ -250,7 +281,8 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChildAt = function (index) { +DisplayObjectContainer.prototype.removeChildAt = function (index) +{ var child = this.getChildAt(index); child.parent = null; @@ -265,24 +297,29 @@ * @param beginIndex {Number} The beginning position. Default value is 0. * @param endIndex {Number} The ending position. Default value is size of the container. */ -DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) { +DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) +{ var begin = beginIndex || 0; var end = typeof endIndex === 'number' ? endIndex : this.children.length; var range = end - begin; - if (range > 0 && range <= end) { + if (range > 0 && range <= end) + { var removed = this.children.splice(begin, range); - for (var i = 0; i < removed.length; ++i) { + for (var i = 0; i < removed.length; ++i) + { removed[i].parent = null; } return removed; } - else if (range === 0 && this.children.length === 0) { + else if (range === 0 && this.children.length === 0) + { return []; } - else { + else + { throw new RangeError('removeChildren: numeric values are outside the acceptable range.'); } }; @@ -291,7 +328,8 @@ * Generates and updates the cached sprite for this object. * */ -DisplayObjectContainer.prototype.updateCachedSprite = function () { +DisplayObjectContainer.prototype.updateCachedSprite = function () +{ this._generateCachedSprite(); }; @@ -304,7 +342,8 @@ * @param renderer {CanvasRenderer|WebGLRenderer} The renderer used to generate the texture. * @return {Texture} a texture of the graphics object */ -DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) { +DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) +{ var bounds = this.getLocalBounds(); var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0, renderer, scaleMode, resolution); @@ -322,18 +361,22 @@ * * @private */ -DisplayObjectContainer.prototype.updateTransform = function () { - if (!this.visible) { +DisplayObjectContainer.prototype.updateTransform = function () +{ + if (!this.visible) + { return; } this.displayObjectUpdateTransform(); - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { return; } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } }; @@ -346,8 +389,10 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getBounds = function () { - if (this.children.length === 0) { +DisplayObjectContainer.prototype.getBounds = function () +{ + if (this.children.length === 0) + { return math.Rectangle.EMPTY; } @@ -365,10 +410,12 @@ var childVisible = false; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -386,7 +433,8 @@ maxY = maxY > childMaxY ? maxY : childMaxY; } - if (!childVisible) { + if (!childVisible) + { return math.Rectangle.EMPTY; } @@ -407,12 +455,14 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getLocalBounds = function () { +DisplayObjectContainer.prototype.getLocalBounds = function () +{ var matrixCache = this.worldTransform; this.worldTransform = math.Matrix.IDENTITY; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } @@ -428,13 +478,16 @@ * * @param renderer {WebGLRenderer} The renderer */ -DisplayObjectContainer.prototype.renderWebGL = function (renderer) { +DisplayObjectContainer.prototype.renderWebGL = function (renderer) +{ // if the object is not visible or the alpha is 0 then no need to render this element - if (!this.visible || this.alpha <= 0) { + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } @@ -442,14 +495,17 @@ var i, j; // do a quick check to see if this element has a mask or a filter. - if (this._mask || this._filters) { + if (this._mask || this._filters) + { // push filter first as we need to ensure the stencil buffer is correct for any masking - if (this._filters) { + if (this._filters) + { renderer.spriteBatch.flush(); renderer.filterManager.pushFilter(this._filterBlock); } - if (this._mask) { + if (this._mask) + { renderer.spriteBatch.stop(); renderer.maskManager.pushMask(this.mask, renderer); renderer.spriteBatch.start(); @@ -459,36 +515,42 @@ this._renderWebGL(renderer); // now loop through the children and make sure they get rendered - for (i = 0, j = this.children.length; i < j; i++) { + for (i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderWebGL(renderer); } // time to stop the sprite batch as either a mask element or a filter draw will happen next renderer.spriteBatch.stop(); - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(this._mask, renderer); } - if (this._filters) { + if (this._filters) + { renderer.filterManager.popFilter(); } renderer.spriteBatch.start(); } - else { + else + { this._renderWebGL(renderer); // simple render children! - for (i = 0, j = this.children.length; i < j; ++i) { + for (i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderWebGL(renderer); } } }; -DisplayObjectContainer.prototype._renderWebGL = function (renderer) { +DisplayObjectContainer.prototype._renderWebGL = function (renderer) +{ // this is where content itself gets renderd.. @@ -499,25 +561,31 @@ * * @param renderer {CanvasRenderer} The renderer */ -DisplayObjectContainer.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0) { +DisplayObjectContainer.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -528,13 +596,16 @@ * @param renderer {WebGLRenderer|CanvasRenderer} The renderer * @private */ -DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) { +DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) +{ this._cachedSprite.worldAlpha = this.worldAlpha; - if (renderer.gl) { + if (renderer.gl) + { this._cachedSprite.renderWebGL(renderer); } - else { + else + { this._cachedSprite.renderCanvas(renderer); } }; @@ -544,10 +615,12 @@ * * @private */ -DisplayObjectContainer.prototype._generateCachedSprite = function () { +DisplayObjectContainer.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { // TODO - RenderTexture now *requires* a renderer instance, so this is like broken // because `renderer` isn't actually in scope here :P var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0); @@ -555,7 +628,8 @@ this._cachedSprite = new Sprite(renderTexture); this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.texture.resize(bounds.width | 0, bounds.height | 0); } @@ -580,8 +654,10 @@ * * @private */ -DisplayObjectContainer.prototype._destroyCachedSprite = function () { - if (!this._cachedSprite) { +DisplayObjectContainer.prototype._destroyCachedSprite = function () +{ + if (!this._cachedSprite) + { return; } diff --git a/src/core/display/Sprite.js b/src/core/display/Sprite.js index 707da24..5862aef 100644 --- a/src/core/display/Sprite.js +++ b/src/core/display/Sprite.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param texture {Texture} The texture for this sprite */ -function Sprite(texture) { +function Sprite(texture) +{ DisplayObjectContainer.call(this); /** @@ -85,12 +86,14 @@ this.texture = texture || Texture.EMPTY; } -Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) { +Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) +{ DisplayObjectContainer.prototype.destroy.call(this); this.anchor = null; - if (destroyTexture) { + if (destroyTexture) + { this._texture.destroy(destroyBaseTexture); } @@ -111,10 +114,12 @@ * @memberof Sprite# */ width: { - get: function () { + get: function () + { return this.scale.x * this.texture.frame.width; }, - set: function (value) { + set: function (value) + { this.scale.x = value / this.texture.frame.width; this._width = value; } @@ -127,10 +132,12 @@ * @memberof Sprite# */ height: { - get: function () { + get: function () + { return this.scale.y * this.texture.frame.height; }, - set: function (value) { + set: function (value) + { this.scale.y = value / this.texture.frame.height; this._height = value; } @@ -143,23 +150,29 @@ * @memberof Sprite# */ texture: { - get: function () { + get: function () + { return this._texture; }, - set: function (value) { - if (this._texture === value) { + set: function (value) + { + if (this._texture === value) + { return; } this._texture = value; this.cachedTint = 0xFFFFFF; - if (value) { + if (value) + { // wait for the texture to load - if (value.baseTexture.hasLoaded) { + if (value.baseTexture.hasLoaded) + { this._onTextureUpdate(); } - else { + else + { value.once('update', this._onTextureUpdate.bind(this)); } } @@ -172,18 +185,22 @@ * * @private */ -Sprite.prototype._onTextureUpdate = function () { +Sprite.prototype._onTextureUpdate = function () +{ // so if _width is 0 then width was not set.. - if (this._width) { + if (this._width) + { this.scale.x = this._width / this.texture.frame.width; } - if (this._height) { + if (this._height) + { this.scale.y = this._height / this.texture.frame.height; } }; -Sprite.prototype._renderWebGL = function (renderer) { +Sprite.prototype._renderWebGL = function (renderer) +{ // this is where content gets renderd.. // watch this space for a little render state manager.. @@ -197,7 +214,8 @@ * @param matrix {Matrix} the transformation matrix of the sprite * @return {Rectangle} the framing rectangle */ -Sprite.prototype.getBounds = function (matrix) { +Sprite.prototype.getBounds = function (matrix) +{ var width = this.texture.frame.width; var height = this.texture.frame.height; @@ -224,11 +242,13 @@ if(b === 0 && c === 0) { // scale may be negative! - if (a < 0) { + if (a < 0) + { a *= -1; } - if (d < 0) { + if (d < 0) + { d *= -1; } @@ -293,28 +313,34 @@ * * @param renderer {CanvasRenderer} The renderer */ -Sprite.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) { +Sprite.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) + { return; } - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; renderer.context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } // Ignore null sources - if (this.texture.valid) { + if (this.texture.valid) + { var resolution = this.texture.baseTexture.resolution / renderer.resolution; renderer.context.globalAlpha = this.worldAlpha; // If smoothingEnabled is supported and we need to change the smoothing property for this texture - if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) { + if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) + { renderer.scaleMode = this.texture.baseTexture.scaleMode; renderer.context[renderer.smoothProperty] = (renderer.scaleMode === CONST.scaleModes.LINEAR); } @@ -324,7 +350,8 @@ var dy = (this.texture.trim ? this.texture.trim.y : 0) - (this.anchor.y * this.texture.trim.height); // Allow for pixel rounding - if (renderer.roundPixels) { + if (renderer.roundPixels) + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -337,7 +364,8 @@ dx = dx | 0; dy = dy | 0; } - else { + else + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -348,8 +376,10 @@ ); } - if (this.tint !== 0xFFFFFF) { - if (this.cachedTint !== this.tint) { + if (this.tint !== 0xFFFFFF) + { + if (this.cachedTint !== this.tint) + { this.cachedTint = this.tint; // TODO clean up caching - how to clean up the caches? @@ -368,7 +398,8 @@ this.texture.crop.height / resolution ); } - else { + else + { renderer.context.drawImage( this.texture.baseTexture.source, this.texture.crop.x, @@ -383,11 +414,13 @@ } } - for (var i = 0, j = this.children.length; i < j; i++) { + for (var i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -402,10 +435,12 @@ * @param frameId {String} The frame Id of the texture in the cache * @return {Sprite} A new Sprite using a texture from the texture cache matching the frameId */ -Sprite.fromFrame = function (frameId) { +Sprite.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache' + this); } @@ -420,6 +455,7 @@ * @param imageId {String} The image url of the texture * @return {Sprite} A new Sprite using a texture from the texture cache matching the image id */ -Sprite.fromImage = function (imageId, crossorigin, scaleMode) { +Sprite.fromImage = function (imageId, crossorigin, scaleMode) +{ return new Sprite(Texture.fromImage(imageId, crossorigin, scaleMode)); }; diff --git a/src/core/display/SpriteBatch.js b/src/core/display/SpriteBatch.js index 3187777..c196fef 100644 --- a/src/core/display/SpriteBatch.js +++ b/src/core/display/SpriteBatch.js @@ -12,7 +12,8 @@ * ```js * var container = new SpriteBatch(); * - * for(var i = 0; i < 100; ++i) { + * for(var i = 0; i < 100; ++i) + * { * var sprite = new PIXI.Sprite.fromImage("myImage.png"); * container.addChild(sprite); * } @@ -25,7 +26,8 @@ */ //TODO RENAME to PARTICLE CONTAINER? -function SpriteBatch() { +function SpriteBatch() +{ DisplayObjectContainer.call(this); } @@ -38,7 +40,8 @@ * * @private */ -SpriteBatch.prototype.updateTransform = function () { +SpriteBatch.prototype.updateTransform = function () +{ // TODO don't need to! this.displayObjectUpdateTransform(); // PIXI.DisplayObjectContainer.prototype.updateTransform.call( this ); @@ -50,8 +53,10 @@ * @param renderer {WebGLRenderer} The webgl renderer * @private */ -SpriteBatch.prototype.renderWebGL = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderWebGL = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -71,8 +76,10 @@ * @param renderer {CanvasRenderer} The canvas renderer * @private */ -SpriteBatch.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -84,10 +91,12 @@ this.displayObjectUpdateTransform(); - for (var i = 0; i < this.children.length; ++i) { + for (var i = 0; i < this.children.length; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -95,9 +104,11 @@ context.globalAlpha = this.worldAlpha * child.alpha; - if (child.rotation % (Math.PI * 2) === 0) { + if (child.rotation % (Math.PI * 2) === 0) + { // this is the fastest way to optimise! - if rotation is 0 then we can avoid any kind of setTransform call - if (isRotated) { + if (isRotated) + { context.setTransform( transform.a, transform.b, @@ -122,8 +133,10 @@ frame.height * child.scale.y ); } - else { - if (!isRotated) { + else + { + if (!isRotated) + { isRotated = true; } @@ -131,7 +144,8 @@ var childTransform = child.worldTransform; - if (renderer.roundPixels) { + if (renderer.roundPixels) + { context.setTransform( childTransform.a, childTransform.b, @@ -141,7 +155,8 @@ childTransform.ty | 0 ); } - else { + else + { context.setTransform( childTransform.a, childTransform.b, diff --git a/src/core/index.js b/src/core/index.js index 3954b6f..eb4a82b 100644 --- a/src/core/index.js +++ b/src/core/index.js @@ -58,11 +58,13 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRenderer: function (width, height, options, noWebGL) { + autoDetectRenderer: function (width, height, options, noWebGL) + { width = width || 800; height = height || 600; - if (!noWebGL && require('webgl-enabled')()) { + if (!noWebGL && require('webgl-enabled')()) + { return new core.WebGLRenderer(width, height, options); } @@ -87,7 +89,8 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRecommendedRenderer: function (width, height, options) { + autoDetectRecommendedRenderer: function (width, height, options) + { var isAndroid = /Android/i.test(navigator.userAgent); return core.autoDetectRenderer(width, height, options, isAndroid); diff --git a/src/core/math/Matrix.js b/src/core/math/Matrix.js index c2f87e2..2ff4848 100644 --- a/src/core/math/Matrix.js +++ b/src/core/math/Matrix.js @@ -10,7 +10,8 @@ * @class * @namespace PIXI */ -function Matrix() { +function Matrix() +{ /** * @member {number} * @default 1 @@ -63,7 +64,8 @@ * * @param array {number[]} The array that the matrix will be populated from. */ -Matrix.prototype.fromArray = function (array) { +Matrix.prototype.fromArray = function (array) +{ this.a = array[0]; this.b = array[1]; this.c = array[3]; @@ -78,14 +80,17 @@ * @param transpose {boolean} Whether we need to transpose the matrix or not * @return {number[]} the newly created array which contains the matrix */ -Matrix.prototype.toArray = function (transpose) { - if (!this.array) { +Matrix.prototype.toArray = function (transpose) +{ + if (!this.array) + { this.array = new Float32Array(9); } var array = this.array; - if (transpose) { + if (transpose) + { array[0] = this.a; array[1] = this.b; array[2] = 0; @@ -96,7 +101,8 @@ array[7] = this.ty; array[8] = 1; } - else { + else + { array[0] = this.a; array[1] = this.c; array[2] = this.tx; @@ -119,7 +125,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, transformed through this matrix */ -Matrix.prototype.apply = function (pos, newPos) { +Matrix.prototype.apply = function (pos, newPos) +{ newPos = newPos || new Point(); newPos.x = this.a * pos.x + this.c * pos.y + this.tx; @@ -136,7 +143,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, inverse-transformed through this matrix */ -Matrix.prototype.applyInverse = function (pos, newPos) { +Matrix.prototype.applyInverse = function (pos, newPos) +{ newPos = newPos || new Point(); var id = 1 / (this.a * this.d + this.c * -this.b); @@ -154,7 +162,8 @@ * @param {number} y * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.translate = function (x, y) { +Matrix.prototype.translate = function (x, y) +{ this.tx += x; this.ty += y; @@ -168,7 +177,8 @@ * @param {number} y The amount to scale vertically * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.scale = function (x, y) { +Matrix.prototype.scale = function (x, y) +{ this.a *= x; this.d *= y; this.c *= x; @@ -186,7 +196,8 @@ * @param {number} angle - The angle in radians. * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.rotate = function (angle) { +Matrix.prototype.rotate = function (angle) +{ var cos = Math.cos( angle ); var sin = Math.sin( angle ); @@ -210,7 +221,8 @@ * @param {Matrix} matrix * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.append = function (matrix) { +Matrix.prototype.append = function (matrix) +{ var a1 = this.a; var b1 = this.b; var c1 = this.c; @@ -232,7 +244,8 @@ * * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.identity = function () { +Matrix.prototype.identity = function () +{ this.a = 1; this.b = 0; this.c = 0; diff --git a/src/core/math/Point.js b/src/core/math/Point.js index 7565b2d..632f346 100644 --- a/src/core/math/Point.js +++ b/src/core/math/Point.js @@ -7,7 +7,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -function Point(x, y) { +function Point(x, y) +{ /** * @member {number} * @default 0 @@ -29,7 +30,8 @@ * * @return {Point} a copy of the point */ -Point.prototype.clone = function () { +Point.prototype.clone = function () +{ return new Point(this.x, this.y); }; @@ -40,7 +42,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -Point.prototype.set = function (x, y) { +Point.prototype.set = function (x, y) +{ this.x = x || 0; this.y = y || ( (y !== 0) ? this.x : 0 ) ; }; diff --git a/src/core/math/shapes/Circle.js b/src/core/math/shapes/Circle.js index 69cfdc9..4d76efc 100644 --- a/src/core/math/shapes/Circle.js +++ b/src/core/math/shapes/Circle.js @@ -10,7 +10,8 @@ * @param y {number} The Y coordinate of the center of this circle * @param radius {number} The radius of the circle */ -function Circle(x, y, radius) { +function Circle(x, y, radius) +{ /** * @member {number} * @default 0 @@ -46,7 +47,8 @@ * @method clone * @return {Circle} a copy of the Circle */ -Circle.prototype.clone = function () { +Circle.prototype.clone = function () +{ return new Circle(this.x, this.y, this.radius); }; @@ -58,8 +60,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Circle */ -Circle.prototype.contains = function (x, y) { - if (this.radius <= 0) { +Circle.prototype.contains = function (x, y) +{ + if (this.radius <= 0) + { return false; } @@ -79,6 +83,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Circle.prototype.getBounds = function () { +Circle.prototype.getBounds = function () +{ return new Rectangle(this.x - this.radius, this.y - this.radius, this.radius * 2, this.radius * 2); }; diff --git a/src/core/math/shapes/Ellipse.js b/src/core/math/shapes/Ellipse.js index 4f2d066..fefd01a 100644 --- a/src/core/math/shapes/Ellipse.js +++ b/src/core/math/shapes/Ellipse.js @@ -11,7 +11,8 @@ * @param width {number} The half width of this ellipse * @param height {number} The half height of this ellipse */ -function Ellipse(x, y, width, height) { +function Ellipse(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -53,7 +54,8 @@ * @method clone * @return {Ellipse} a copy of the ellipse */ -Ellipse.prototype.clone = function () { +Ellipse.prototype.clone = function () +{ return new Ellipse(this.x, this.y, this.width, this.height); }; @@ -65,8 +67,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coords are within this ellipse */ -Ellipse.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Ellipse.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } @@ -86,6 +90,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Ellipse.prototype.getBounds = function () { +Ellipse.prototype.getBounds = function () +{ return new Rectangle(this.x - this.width, this.y - this.height, this.width, this.height); }; diff --git a/src/core/math/shapes/Polygon.js b/src/core/math/shapes/Polygon.js index ae89148..fea6d37 100644 --- a/src/core/math/shapes/Polygon.js +++ b/src/core/math/shapes/Polygon.js @@ -10,16 +10,20 @@ * arguments passed can be flat x,y values e.g. `new Polygon(x,y, x,y, x,y, ...)` where `x` and `y` are * Numbers. */ -function Polygon(points) { +function Polygon(points) +{ //if points isn't an array, use arguments as the array - if (!(points instanceof Array)) { + if (!(points instanceof Array)) + { points = Array.prototype.slice.call(arguments); } //if this is a flat array of numbers, convert it to points - if (points[0] instanceof Point) { + if (points[0] instanceof Point) + { var p = []; - for (var i = 0, il = points.length; i < il; i++) { + for (var i = 0, il = points.length; i < il; i++) + { p.push(points[i].x, points[i].y); } @@ -51,7 +55,8 @@ * * @return {Polygon} a copy of the polygon */ -Polygon.prototype.clone = function () { +Polygon.prototype.clone = function () +{ return new Polygon(this.points.slice()); }; @@ -62,19 +67,22 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this polygon */ -Polygon.prototype.contains = function (x, y) { +Polygon.prototype.contains = function (x, y) +{ var inside = false; // use some raycasting to test hits // https://github.com/substack/point-in-polygon/blob/master/index.js var length = this.points.length / 2; - for (var i = 0, j = length - 1; i < length; j = i++) { + for (var i = 0, j = length - 1; i < length; j = i++) + { var xi = this.points[i * 2], yi = this.points[i * 2 + 1], xj = this.points[j * 2], yj = this.points[j * 2 + 1], intersect = ((yi > y) !== (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi); - if (intersect) { + if (intersect) + { inside = !inside; } } diff --git a/src/core/math/shapes/Rectangle.js b/src/core/math/shapes/Rectangle.js index 16ac62a..4008b68 100644 --- a/src/core/math/shapes/Rectangle.js +++ b/src/core/math/shapes/Rectangle.js @@ -10,7 +10,8 @@ * @param width {number} The overall width of this rectangle * @param height {number} The overall height of this rectangle */ -function Rectangle(x, y, width, height) { +function Rectangle(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -60,7 +61,8 @@ * * @return {Rectangle} a copy of the rectangle */ -Rectangle.prototype.clone = function () { +Rectangle.prototype.clone = function () +{ return new Rectangle(this.x, this.y, this.width, this.height); }; @@ -71,13 +73,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rectangle */ -Rectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Rectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/math/shapes/RoundedRectangle.js b/src/core/math/shapes/RoundedRectangle.js index 27d286e..7bf6411 100644 --- a/src/core/math/shapes/RoundedRectangle.js +++ b/src/core/math/shapes/RoundedRectangle.js @@ -11,7 +11,8 @@ * @param height {number} The overall height of this rounded rectangle * @param radius {number} Controls the radius of the rounded corners */ -function RoundedRectangle(x, y, width, height, radius) { +function RoundedRectangle(x, y, width, height, radius) +{ /** * @member {number} * @default 0 @@ -58,7 +59,8 @@ * * @return {RoundedRectangle} a copy of the rounded rectangle */ -RoundedRectangle.prototype.clone = function () { +RoundedRectangle.prototype.clone = function () +{ return new RoundedRectangle(this.x, this.y, this.width, this.height, this.radius); }; @@ -69,13 +71,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rounded Rectangle */ -RoundedRectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +RoundedRectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/primitives/Graphics.js b/src/core/primitives/Graphics.js index 261c534..e902d2a 100644 --- a/src/core/primitives/Graphics.js +++ b/src/core/primitives/Graphics.js @@ -16,7 +16,8 @@ * @extends DisplayObjectContainer * @namespace PIXI */ -function Graphics() { +function Graphics() +{ DisplayObjectContainer.call(this); this.renderable = true; @@ -154,16 +155,20 @@ * @private */ cacheAsBitmap: { - get: function () { + get: function () + { return this._cacheAsBitmap; }, - set: function (value) { + set: function (value) + { this._cacheAsBitmap = value; - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._generateCachedSprite(); } - else { + else + { this.destroyCachedSprite(); this.dirty = true; } @@ -176,7 +181,8 @@ * * @return {Graphics} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ var clone = new Graphics(); clone.renderable = this.renderable; @@ -192,7 +198,8 @@ clone.cachedSpriteDirty = this.cachedSpriteDirty; // copy graphics data - for (var i = 0; i < this.graphicsData.length; ++i) { + for (var i = 0; i < this.graphicsData.length; ++i) + { clone.graphicsData.push(this.graphicsData.clone()); } @@ -211,17 +218,21 @@ * @param alpha {number} alpha of the line to draw, will update the objects stored style * @return {Graphics} */ -Graphics.prototype.lineStyle = function (lineWidth, color, alpha) { +Graphics.prototype.lineStyle = function (lineWidth, color, alpha) +{ this.lineWidth = lineWidth || 0; this.lineColor = color || 0; this.lineAlpha = (arguments.length < 3) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length) + { // halfway through a line? start a new one! this.drawShape( new math.Polygon( this.currentPath.shape.points.slice(-2) )); } - else { + else + { // otherwise its empty so lets just set the line properties this.currentPath.lineWidth = this.lineWidth; this.currentPath.lineColor = this.lineColor; @@ -239,7 +250,8 @@ * @param y {number} the Y coordinate to move to * @return {Graphics} */ -Graphics.prototype.moveTo = function (x, y) { +Graphics.prototype.moveTo = function (x, y) +{ this.drawShape(new math.Polygon([x,y])); return this; @@ -253,7 +265,8 @@ * @param y {number} the Y coordinate to draw to * @return {Graphics} */ -Graphics.prototype.lineTo = function (x, y) { +Graphics.prototype.lineTo = function (x, y) +{ this.currentPath.shape.points.push(x, y); this.dirty = true; @@ -270,13 +283,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -285,7 +302,8 @@ n = 20, points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { this.moveTo(0, 0); } @@ -293,7 +311,8 @@ var fromY = points[points.length-1]; var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; xa = fromX + ( (cpX - fromX) * j ); @@ -319,13 +338,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -342,7 +365,8 @@ var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; dt = (1 - j); @@ -373,13 +397,17 @@ * @param radius {number} The radius of the arc * @return {Graphics} */ -Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points.push(x1, y1); } } - else { + else + { this.moveTo(x1, y1); } @@ -392,12 +420,15 @@ b2 = x2 - x1, mm = Math.abs(a1 * b2 - b1 * a2); - if (mm < 1.0e-8 || radius === 0) { - if (points[points.length-2] !== x1 || points[points.length-1] !== y1) { + if (mm < 1.0e-8 || radius === 0) + { + if (points[points.length-2] !== x1 || points[points.length-1] !== y1) + { points.push(x1, y1); } } - else { + else + { var dd = a1 * a1 + b1 * b1, cc = a2 * a2 + b2 * b2, tt = a1 * a2 + b1 * b2, @@ -433,42 +464,51 @@ * @param anticlockwise {boolean} Optional. Specifies whether the drawing should be counterclockwise or clockwise. False is default, and indicates clockwise, while true indicates counter-clockwise. * @return {Graphics} */ -Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) { +Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) +{ var startX = cx + Math.cos(startAngle) * radius; var startY = cy + Math.sin(startAngle) * radius; var points; // TODO - This if-else makes no sense. It uses currentPath in the else where it doesn't exist... - if (this.currentPath) { + if (this.currentPath) + { points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { points.push(startX, startY); } - else if (points[points.length-2] !== startX || points[points.length-1] !== startY) { + else if (points[points.length-2] !== startX || points[points.length-1] !== startY) + { points.push(startX, startY); } } - else { + else + { this.moveTo(startX, startY); points = this.currentPath.shape.points; } - if (startAngle === endAngle) { + if (startAngle === endAngle) + { return this; } - if (!anticlockwise && endAngle <= startAngle) { + if (!anticlockwise && endAngle <= startAngle) + { endAngle += Math.PI * 2; } - else if (anticlockwise && startAngle <= endAngle) { + else if (anticlockwise && startAngle <= endAngle) + { startAngle += Math.PI * 2; } var sweep = anticlockwise ? (startAngle - endAngle) *-1 : (endAngle - startAngle); var segs = (Math.abs(sweep)/ (Math.PI * 2)) * 40; - if (sweep === 0) { + if (sweep === 0) + { return this; } @@ -482,7 +522,8 @@ var remainder = ( segMinus % 1 ) / segMinus; - for (var i = 0; i <= segMinus; ++i) { + for (var i = 0; i <= segMinus; ++i) + { var real = i + remainder * i; var angle = ((theta) + startAngle + (theta2 * real)); @@ -506,13 +547,16 @@ * @param alpha {number} the alpha of the fill * @return {Graphics} */ -Graphics.prototype.beginFill = function (color, alpha) { +Graphics.prototype.beginFill = function (color, alpha) +{ this.filling = true; this.fillColor = color || 0; this.fillAlpha = (alpha === undefined) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length <= 2) + { this.currentPath.fill = this.filling; this.currentPath.fillColor = this.fillColor; this.currentPath.fillAlpha = this.fillAlpha; @@ -526,7 +570,8 @@ * * @return {Graphics} */ -Graphics.prototype.endFill = function () { +Graphics.prototype.endFill = function () +{ this.filling = false; this.fillColor = null; this.fillAlpha = 1; @@ -542,7 +587,8 @@ * @param height {number} The height of the rectangle * @return {Graphics} */ -Graphics.prototype.drawRect = function ( x, y, width, height ) { +Graphics.prototype.drawRect = function ( x, y, width, height ) +{ this.drawShape(new math.Rectangle(x,y, width, height)); return this; @@ -556,7 +602,8 @@ * @param height {number} The height of the rectangle * @param radius {number} Radius of the rectangle corners */ -Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) { +Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) +{ this.drawShape(new math.RoundedRectangle(x, y, width, height, radius)); return this; @@ -570,7 +617,8 @@ * @param radius {number} The radius of the circle * @return {Graphics} */ -Graphics.prototype.drawCircle = function (x, y, radius) { +Graphics.prototype.drawCircle = function (x, y, radius) +{ this.drawShape(new math.Circle(x,y, radius)); return this; @@ -585,7 +633,8 @@ * @param height {number} The half height of the ellipse * @return {Graphics} */ -Graphics.prototype.drawEllipse = function (x, y, width, height) { +Graphics.prototype.drawEllipse = function (x, y, width, height) +{ this.drawShape(new math.Ellipse(x, y, width, height)); return this; @@ -597,8 +646,10 @@ * @param path {Array} The path data used to construct the polygon. * @return {Graphics} */ -Graphics.prototype.drawPolygon = function (path) { - if (!(path instanceof Array)) { +Graphics.prototype.drawPolygon = function (path) +{ + if (!(path instanceof Array)) + { path = Array.prototype.slice.call(arguments); } @@ -612,7 +663,8 @@ * * @return {Graphics} */ -Graphics.prototype.clear = function () { +Graphics.prototype.clear = function () +{ this.lineWidth = 0; this.filling = false; @@ -631,7 +683,8 @@ * @param scaleMode {number} Should be one of the scaleMode consts * @return {Texture} a texture of the graphics object */ -Graphics.prototype.generateTexture = function (resolution, scaleMode) { +Graphics.prototype.generateTexture = function (resolution, scaleMode) +{ resolution = resolution || 1; var bounds = this.getBounds(); @@ -655,17 +708,21 @@ * * @param renderer {WebGLRenderer} */ -Graphics.prototype._renderWebGL = function (renderer) { +Graphics.prototype._renderWebGL = function (renderer) +{ // if the sprite is not visible or the alpha is 0 then no need to render this element - if (this.isMask === true) { + if (this.isMask === true) + { return; } // this code may still be needed so leaving for now.. - // + // /* - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture on the gpu too! @@ -681,17 +738,24 @@ return; } - */ - - // check if the webgl graphic needs to be updated - if (this.glDirty) { - this.dirty = true; - this.glDirty = false; - } + else */ - renderer.setObjectRendererer(renderer.graphicsRenderer); - renderer.graphicsRenderer.render(this); + renderer.spriteBatch.stop(); + renderer.blendModeManager.setBlendMode(this.blendMode); + // check blend mode + renderer.blendModeManager.setBlendMode( this.blendMode ); + + // check if the webgl graphic needs to be updated + if (this.glDirty) + { + this.dirty = true; + this.glDirty = false; + } + + WebGLGraphics.renderGraphics(this, renderer); + + renderer.spriteBatch.start(); }; /** @@ -700,14 +764,18 @@ * @param renderer {CanvasRenderer} * @private */ -Graphics.prototype.renderCanvas = function (renderer) { +Graphics.prototype.renderCanvas = function (renderer) +{ // 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.isMask === true) { + if (!this.visible || this.alpha <= 0 || this.isMask === true) + { return; } - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture @@ -723,16 +791,19 @@ return; } - else { + else + { var context = renderer.context; var transform = this.worldTransform; - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } @@ -748,11 +819,13 @@ CanvasGraphics.renderGraphics(this, context); - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } } @@ -763,13 +836,16 @@ * * @return {Rectangle} the rectangular bounding area */ -Graphics.prototype.getBounds = function (matrix) { +Graphics.prototype.getBounds = function (matrix) +{ // return an empty object if the item is a mask! - if (this.isMask) { + if (this.isMask) + { return math.Rectangle.EMPTY; } - if (this.dirty) { + if (this.dirty) + { this.updateLocalBounds(); this.glDirty = true; @@ -841,23 +917,27 @@ * Update the bounds of the object * */ -Graphics.prototype.updateLocalBounds = function () { +Graphics.prototype.updateLocalBounds = function () +{ var minX = Infinity; var maxX = -Infinity; var minY = Infinity; var maxY = -Infinity; - if (this.graphicsData.length) { + if (this.graphicsData.length) + { var shape, points, x, y, w, h; - for (var i = 0; i < this.graphicsData.length; i++) { + for (var i = 0; i < this.graphicsData.length; i++) + { var data = this.graphicsData[i]; var type = data.type; var lineWidth = data.lineWidth; shape = data.shape; - if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) { + if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) + { x = shape.x - lineWidth/2; y = shape.y - lineWidth/2; w = shape.width + lineWidth; @@ -869,7 +949,8 @@ minY = y < minY ? y : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.CIRC) { + else if (type === CONST.SHAPES.CIRC) + { x = shape.x; y = shape.y; w = shape.radius + lineWidth/2; @@ -881,7 +962,8 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.ELIP) { + else if (type === CONST.SHAPES.ELIP) + { x = shape.x; y = shape.y; w = shape.width + lineWidth/2; @@ -893,11 +975,13 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else { + else + { // POLY points = shape.points; - for (var j = 0; j < points.length; j += 2) { + for (var j = 0; j < points.length; j += 2) + { x = points[j]; y = points[j+1]; @@ -910,7 +994,8 @@ } } } - else { + else + { minX = 0; maxX = 0; minY = 0; @@ -931,10 +1016,12 @@ * * @private */ -Graphics.prototype._generateCachedSprite = function () { +Graphics.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { var canvasBuffer = new CanvasBuffer(bounds.width, bounds.height); var texture = Texture.fromCanvas(canvasBuffer.canvas); @@ -943,7 +1030,8 @@ this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.buffer.resize(bounds.width, bounds.height); } @@ -968,7 +1056,8 @@ * * @private */ -Graphics.prototype.updateCachedSpriteTexture = function () { +Graphics.prototype.updateCachedSpriteTexture = function () +{ var cachedSprite = this._cachedSprite; var texture = cachedSprite.texture; var canvas = cachedSprite.buffer.canvas; @@ -989,7 +1078,8 @@ * Destroys a previous cached sprite. * */ -Graphics.prototype.destroyCachedSprite = function () { +Graphics.prototype.destroyCachedSprite = function () +{ this._cachedSprite.texture.destroy(true); // let the gc collect the unused sprite @@ -1003,10 +1093,13 @@ * @param {Circle|Rectangle|Ellipse|Line|Polygon} shape The Shape object to draw. * @return {GraphicsData} The generated GraphicsData object. */ -Graphics.prototype.drawShape = function (shape) { - if (this.currentPath) { +Graphics.prototype.drawShape = function (shape) +{ + if (this.currentPath) + { // check current path! - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath.shape.points.length <= 2) + { this.graphicsData.pop(); } } @@ -1017,7 +1110,8 @@ this.graphicsData.push(data); - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { data.shape.closed = this.filling; this.currentPath = data; } diff --git a/src/core/primitives/GraphicsData.js b/src/core/primitives/GraphicsData.js index 99decbe..788f6f2 100644 --- a/src/core/primitives/GraphicsData.js +++ b/src/core/primitives/GraphicsData.js @@ -4,7 +4,8 @@ * @class * @namespace PIXI */ -function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) { +function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) +{ this.lineWidth = lineWidth; this.lineColor = lineColor; this.lineAlpha = lineAlpha; @@ -27,7 +28,8 @@ * * @return {GraphicsData} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ return new GraphicsData( this.lineWidth, this.lineColor, diff --git a/src/core/renderers/canvas/CanvasRenderer.js b/src/core/renderers/canvas/CanvasRenderer.js index 15a0978..7aebd44 100644 --- a/src/core/renderers/canvas/CanvasRenderer.js +++ b/src/core/renderers/canvas/CanvasRenderer.js @@ -17,17 +17,22 @@ * @param [options.resolution=1] {number} the resolution of the renderer retina would be 2 * @param [options.clearBeforeRender=true] {boolean} This sets if the CanvasRenderer will clear the canvas or not before the new render pass. */ -function CanvasRenderer(width, height, options) { +function CanvasRenderer(width, height, options) +{ utils.sayHello('Canvas'); - if (options) { - for (var i in CONST.defaultRenderOptions) { - if (typeof options[i] === 'undefined') { + if (options) + { + for (var i in CONST.defaultRenderOptions) + { + if (typeof options[i] === 'undefined') + { options[i] = CONST.defaultRenderOptions[i]; } } } - else { + else + { options = CONST.defaultRenderOptions; } @@ -156,19 +161,24 @@ this.smoothProperty = null; - if (this.context.imageSmoothingEnabled) { + if (this.context.imageSmoothingEnabled) + { this.smoothProperty = 'imageSmoothingEnabled'; } - else if (this.context.webkitImageSmoothingEnabled) { + else if (this.context.webkitImageSmoothingEnabled) + { this.smoothProperty = 'webkitImageSmoothingEnabled'; } - else if (this.context.mozImageSmoothingEnabled) { + else if (this.context.mozImageSmoothingEnabled) + { this.smoothProperty = 'mozImageSmoothingEnabled'; } - else if (this.context.oImageSmoothingEnabled) { + else if (this.context.oImageSmoothingEnabled) + { this.smoothProperty = 'oImageSmoothingEnabled'; } - else if (this.context.msImageSmoothingEnabled) { + else if (this.context.msImageSmoothingEnabled) + { this.smoothProperty = 'msImageSmoothingEnabled'; } @@ -193,10 +203,12 @@ * @memberof CanvasRenderer# */ backgroundColor: { - get: function () { + get: function () + { return this._backgroundColor; }, - set: function (val) { + set: function (val) + { this._backgroundColor = val; this._backgroundColorString = utils.hex2string(val); } @@ -208,7 +220,8 @@ * * @param object {DisplayObject} the object to be rendered */ -CanvasRenderer.prototype.render = function (object) { +CanvasRenderer.prototype.render = function (object) +{ object.updateTransform(); this.context.setTransform(1,0,0,1,0,0); @@ -218,16 +231,20 @@ this.currentBlendMode = CONST.blendModes.NORMAL; this.context.globalCompositeOperation = this.blendModes[CONST.blendModes.NORMAL]; - if (navigator.isCocoonJS && this.view.screencanvas) { + if (navigator.isCocoonJS && this.view.screencanvas) + { this.context.fillStyle = 'black'; this.context.clear(); } - if (this.clearBeforeRender) { - if (this.transparent) { + if (this.clearBeforeRender) + { + if (this.transparent) + { this.context.clearRect(0, 0, this.width, this.height); } - else { + else + { this.context.fillStyle = this._backgroundColorString; this.context.fillRect(0, 0, this.width , this.height); } @@ -241,8 +258,10 @@ * * @param [removeView=false] {boolean} Removes the Canvas element from the DOM. */ -CanvasRenderer.prototype.destroy = function (removeView) { - if (removeView && this.view.parent) { +CanvasRenderer.prototype.destroy = function (removeView) +{ + if (removeView && this.view.parent) + { this.view.parent.removeChild(this.view); } @@ -257,14 +276,16 @@ * @param width {number} the new width of the canvas view * @param height {number} the new height of the canvas view */ -CanvasRenderer.prototype.resize = function (width, height) { +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) { + if (this.autoResize) + { this.view.style.width = this.width / this.resolution + 'px'; this.view.style.height = this.height / this.resolution + 'px'; } @@ -276,7 +297,8 @@ * @param displayObject {DisplayObject} The displayObject to render * @private */ -CanvasRenderer.prototype.renderDisplayObject = function (displayObject) { +CanvasRenderer.prototype.renderDisplayObject = function (displayObject) +{ displayObject.renderCanvas(this); }; @@ -285,11 +307,14 @@ * * @private */ -CanvasRenderer.prototype._mapBlendModes = function () { - if (!this.blendModes) { +CanvasRenderer.prototype._mapBlendModes = function () +{ + if (!this.blendModes) + { this.blendModes = {}; - if (utils.canUseNewCanvasBlendModes()) { + if (utils.canUseNewCanvasBlendModes()) + { this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? this.blendModes[CONST.blendModes.MULTIPLY] = 'multiply'; @@ -308,7 +333,8 @@ this.blendModes[CONST.blendModes.COLOR] = 'color'; this.blendModes[CONST.blendModes.LUMINOSITY] = 'luminosity'; } - else { + else + { // this means that the browser does not support the cool new blend modes in canvas 'cough' ie 'cough' this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? diff --git a/src/core/renderers/canvas/utils/CanvasBuffer.js b/src/core/renderers/canvas/utils/CanvasBuffer.js index ebe5d47..b183a66 100644 --- a/src/core/renderers/canvas/utils/CanvasBuffer.js +++ b/src/core/renderers/canvas/utils/CanvasBuffer.js @@ -6,7 +6,8 @@ * @param width {number} the width for the newly created canvas * @param height {number} the height for the newly created canvas */ -function CanvasBuffer(width, height) { +function CanvasBuffer(width, height) +{ /** * The Canvas object that belongs to this CanvasBuffer. * @@ -36,10 +37,12 @@ * @memberof CanvasBuffer# */ width: { - get: function () { + get: function () + { return this.canvas.width; }, - set: function (val) { + set: function (val) + { this.canvas.width = val; } }, @@ -50,10 +53,12 @@ * @memberof CanvasBuffer# */ height: { - get: function () { + get: function () + { return this.canvas.height; }, - set: function (val) { + set: function (val) + { this.canvas.height = val; } } @@ -64,7 +69,8 @@ * * @private */ -CanvasBuffer.prototype.clear = function () { +CanvasBuffer.prototype.clear = function () +{ this.context.setTransform(1, 0, 0, 1, 0, 0); this.context.clearRect(0,0, this.canvas.width, this.canvas.height); }; @@ -75,7 +81,8 @@ * @param width {number} the new width of the canvas * @param height {number} the new height of the canvas */ -CanvasBuffer.prototype.resize = function (width, height) { +CanvasBuffer.prototype.resize = function (width, height) +{ this.canvas.width = width; this.canvas.height = height; }; diff --git a/src/core/renderers/canvas/utils/CanvasGraphics.js b/src/core/renderers/canvas/utils/CanvasGraphics.js index c7eaa2a..3f2a91f 100644 --- a/src/core/renderers/canvas/utils/CanvasGraphics.js +++ b/src/core/renderers/canvas/utils/CanvasGraphics.js @@ -13,15 +13,18 @@ * @param graphics {Graphics} the actual graphics object to render * @param context {CanvasRenderingContext2D} the 2d drawing method of the canvas */ -CanvasGraphics.renderGraphics = function (graphics, context) { +CanvasGraphics.renderGraphics = function (graphics, context) +{ var worldAlpha = graphics.worldAlpha; - if (graphics.dirty) { + if (graphics.dirty) + { this.updateGraphicsTint(graphics); graphics.dirty = false; } - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; @@ -30,69 +33,82 @@ context.lineWidth = data.lineWidth; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { context.beginPath(); var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } - if (shape.closed) { + if (shape.closed) + { context.lineTo(points[0], points[1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fillRect(shape.x, shape.y, shape.width, shape.height); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.strokeRect(shape.x, shape.y, shape.width, shape.height); } } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.beginPath(); context.arc(shape.x, shape.y, shape.radius,0,2*Math.PI); context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas var w = shape.width * 2; @@ -119,18 +135,21 @@ context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; var width = shape.width; @@ -152,13 +171,15 @@ context.quadraticCurveTo(rx, ry, rx, ry + radius); context.closePath(); - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); @@ -174,45 +195,54 @@ * @param graphics {Graphics} the graphics which will be used as a mask * @param context {CanvasRenderingContext2D} the context 2d method of the canvas */ -CanvasGraphics.renderGraphicsMask = function (graphics, context) { +CanvasGraphics.renderGraphicsMask = function (graphics, context) +{ var len = graphics.graphicsData.length; - if (len === 0) { + if (len === 0) + { return; } context.beginPath(); - for (var i = 0; i < len; i++) { + for (var i = 0; i < len; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { context.rect(shape.x, shape.y, shape.width, shape.height); context.closePath(); } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.arc(shape.x, shape.y, shape.radius, 0, 2 * Math.PI); context.closePath(); } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas @@ -237,7 +267,8 @@ context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); context.closePath(); } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; @@ -262,8 +293,10 @@ } }; -CanvasGraphics.updateGraphicsTint = function (graphics) { - if (graphics.tint === 0xFFFFFF) { +CanvasGraphics.updateGraphicsTint = function (graphics) +{ + if (graphics.tint === 0xFFFFFF) + { return; } @@ -271,7 +304,8 @@ var tintG = (graphics.tint >> 8 & 0xFF) / 255; var tintB = (graphics.tint & 0xFF)/ 255; - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var fillColor = data.fillColor | 0; diff --git a/src/core/renderers/canvas/utils/CanvasMaskManager.js b/src/core/renderers/canvas/utils/CanvasMaskManager.js index e04a733..9827d36 100644 --- a/src/core/renderers/canvas/utils/CanvasMaskManager.js +++ b/src/core/renderers/canvas/utils/CanvasMaskManager.js @@ -6,7 +6,8 @@ * @class * @namespace PIXI */ -function CanvasMaskManager() {} +function CanvasMaskManager() +{} CanvasMaskManager.prototype.constructor = CanvasMaskManager; module.exports = CanvasMaskManager; @@ -17,7 +18,8 @@ * @param maskData {object} the maskData that will be pushed * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.pushMask = function (maskData, renderer) { +CanvasMaskManager.prototype.pushMask = function (maskData, renderer) +{ renderer.context.save(); var cacheAlpha = maskData.alpha; @@ -45,6 +47,7 @@ * * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.popMask = function (renderer) { +CanvasMaskManager.prototype.popMask = function (renderer) +{ renderer.context.restore(); }; diff --git a/src/core/renderers/canvas/utils/CanvasTinter.js b/src/core/renderers/canvas/utils/CanvasTinter.js index 17e0529..d2fb1bc 100644 --- a/src/core/renderers/canvas/utils/CanvasTinter.js +++ b/src/core/renderers/canvas/utils/CanvasTinter.js @@ -14,7 +14,8 @@ * @param color {number} the color to use to tint the sprite with * @return {HTMLCanvasElement} The tinted canvas */ -CanvasTinter.getTintedTexture = function (sprite, color) { +CanvasTinter.getTintedTexture = function (sprite, color) +{ var texture = sprite.texture; color = CanvasTinter.roundColor(color); @@ -23,7 +24,8 @@ texture.tintCache = texture.tintCache || {}; - if (texture.tintCache[stringColor]) { + if (texture.tintCache[stringColor]) + { return texture.tintCache[stringColor]; } @@ -33,14 +35,16 @@ //CanvasTinter.tintWithPerPixel(texture, stringColor, canvas); CanvasTinter.tintMethod(texture, color, canvas); - if (CanvasTinter.convertTintToImage) { + if (CanvasTinter.convertTintToImage) + { // is this better? var tintImage = new Image(); tintImage.src = canvas.toDataURL(); texture.tintCache[stringColor] = tintImage; } - else { + else + { texture.tintCache[stringColor] = canvas; // if we are not converting the texture to an image then we need to lose the reference to the canvas CanvasTinter.canvas = null; @@ -56,7 +60,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithMultiply = function (texture, color, canvas) { +CanvasTinter.tintWithMultiply = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -104,7 +109,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithOverlay = function (texture, color, canvas) { +CanvasTinter.tintWithOverlay = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -139,7 +145,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithPerPixel = function (texture, color, canvas) { +CanvasTinter.tintWithPerPixel = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -167,7 +174,8 @@ var pixels = pixelData.data; - for (var i = 0; i < pixels.length; i += 4) { + for (var i = 0; i < pixels.length; i += 4) + { pixels[i+0] *= r; pixels[i+1] *= g; pixels[i+2] *= b; @@ -181,7 +189,8 @@ * * @param color {number} the color to round, should be a hex color */ -CanvasTinter.roundColor = function (color) { +CanvasTinter.roundColor = function (color) +{ var step = CanvasTinter.cacheStepsPerColorChannel; var rgbValues = utils.hex2rgb(color); diff --git a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js index 9f2f89a..35edbaf 100644 --- a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js +++ b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLBlendModeManager(renderer) { +function WebGLBlendModeManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -23,8 +24,10 @@ * * @param blendMode {number} the blendMode, should be a Pixi const, such as BlendModes.ADD */ -WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) { - if (this.currentBlendMode === blendMode) { +WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) +{ + if (this.currentBlendMode === blendMode) + { return false; } diff --git a/src/core/display/DisplayObject.js b/src/core/display/DisplayObject.js index 66ebc3c..20e778c 100644 --- a/src/core/display/DisplayObject.js +++ b/src/core/display/DisplayObject.js @@ -7,7 +7,8 @@ * @class * @namespace PIXI */ -function DisplayObject() { +function DisplayObject() +{ /** * The coordinate of the object relative to the local coordinates of the parent. * @@ -152,10 +153,12 @@ * @memberof DisplayObject# */ x: { - get: function () { + get: function () + { return this.position.x; }, - set: function (value) { + set: function (value) + { this.position.x = value; } }, @@ -167,10 +170,12 @@ * @memberof DisplayObject# */ y: { - get: function () { + get: function () + { return this.position.y; }, - set: function (value) { + set: function (value) + { this.position.y = value; } }, @@ -183,11 +188,13 @@ * @readonly */ worldVisible: { - get: function () { + get: function () + { var item = this; do { - if (!item.visible) { + if (!item.visible) + { return false; } @@ -207,17 +214,21 @@ * @memberof DisplayObject# */ mask: { - get: function () { + get: function () + { return this._mask; }, - set: function (value) { - if (this._mask) { + set: function (value) + { + if (this._mask) + { this._mask.isMask = false; } this._mask = value; - if (this._mask) { + if (this._mask) + { this._mask.isMask = true; } } @@ -232,18 +243,23 @@ * @memberof DisplayObject# */ filters: { - get: function () { + get: function () + { return this._filters; }, - set: function (value) { - if (value) { + set: function (value) + { + if (value) + { // now put all the passes in one place.. var passes = []; - for (var i = 0; i < value.length; i++) { + for (var i = 0; i < value.length; i++) + { var filterPasses = value[i].passes; - for (var j = 0; j < filterPasses.length; j++) { + for (var j = 0; j < filterPasses.length; j++) + { passes.push(filterPasses[j]); } } @@ -264,8 +280,9 @@ * * @private */ -DisplayObject.prototype.updateTransform = function () { - +DisplayObject.prototype.updateTransform = function () +{ + // create some matrix refs for easy access var pt = this.parent.worldTransform; var wt = this.worldTransform; @@ -274,9 +291,11 @@ var a, b, c, d, tx, ty; // so if rotation is between 0 then we can simplify the multiplication process.. - if (this.rotation % math.PI_2) { + if (this.rotation % math.PI_2) + { // 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) { + if (this.rotation !== this.rotationCache) + { this.rotationCache = this.rotation; this._sr = Math.sin(this.rotation); this._cr = Math.cos(this.rotation); @@ -291,7 +310,8 @@ ty = this.position.y; // check for pivot.. not often used so geared towards that fact! - if (this.pivot.x || this.pivot.y) { + 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; } @@ -304,7 +324,8 @@ wt.tx = tx * pt.a + ty * pt.c + pt.tx; wt.ty = tx * pt.b + ty * pt.d + pt.ty; } - else { + else + { // lets do the fast version as we know there is no rotation.. a = this.scale.x; d = this.scale.y; @@ -333,7 +354,8 @@ * @param matrix {Matrix} * @return {Rectangle} the rectangular bounding area */ -DisplayObject.prototype.getBounds = function (/* matrix */) { +DisplayObject.prototype.getBounds = function (/* matrix */) +{ return math.Rectangle.EMPTY; }; @@ -342,7 +364,8 @@ * * @return {Rectangle} the rectangular bounding area */ -DisplayObject.prototype.getLocalBounds = function () { +DisplayObject.prototype.getLocalBounds = function () +{ return this.getBounds(math.Matrix.IDENTITY); }; @@ -352,7 +375,8 @@ * @param position {Point} The world origin to calculate from * @return {Point} A point object representing the position of this object */ -DisplayObject.prototype.toGlobal = function (position) { +DisplayObject.prototype.toGlobal = function (position) +{ // don't need to u[date the lot this.displayObjectUpdateTransform(); return this.worldTransform.apply(position); @@ -365,8 +389,10 @@ * @param [from] {DisplayObject} The DisplayObject to calculate the global position from * @return {Point} A point object representing the position of this object */ -DisplayObject.prototype.toLocal = function (position, from) { - if (from) { +DisplayObject.prototype.toLocal = function (position, from) +{ + if (from) + { position = from.toGlobal(position); } @@ -381,7 +407,8 @@ * @param renderer {WebGLRenderer} The renderer * @private */ -DisplayObject.prototype.renderWebGL = function (/* renderer */) { +DisplayObject.prototype.renderWebGL = function (/* renderer */) +{ // OVERWRITE; }; @@ -391,6 +418,7 @@ * @param renderer {CanvasRenderer} The renderer * @private */ -DisplayObject.prototype.renderCanvas = function (/* renderer */) { +DisplayObject.prototype.renderCanvas = function (/* renderer */) +{ // OVERWRITE; }; diff --git a/src/core/display/DisplayObjectContainer.js b/src/core/display/DisplayObjectContainer.js index 689f40b..4625ee8 100644 --- a/src/core/display/DisplayObjectContainer.js +++ b/src/core/display/DisplayObjectContainer.js @@ -12,7 +12,8 @@ * @extends DisplayObject * @namespace PIXI */ -function DisplayObjectContainer() { +function DisplayObjectContainer() +{ DisplayObject.call(this); /** @@ -47,17 +48,21 @@ * @memberof DisplayObjectContainer# */ width: { - get: function () { + get: function () + { return this.scale.x * this.getLocalBounds().width; }, - set: function (value) { + set: function (value) + { var width = this.getLocalBounds().width; - if(width !== 0) { + if(width !== 0) + { this.scale.x = value / width; } - else { + else + { this.scale.x = 1; } @@ -73,17 +78,21 @@ * @memberof DisplayObjectContainer# */ height: { - get: function () { + get: function () + { return this.scale.y * this.getLocalBounds().height; }, - set: function (value) { + set: function (value) + { var height = this.getLocalBounds().height; - if (height !== 0) { + if (height !== 0) + { this.scale.y = value / height ; } - else { + else + { this.scale.y = 1; } @@ -100,18 +109,23 @@ * @memberof DisplayObject# */ cacheAsBitmap: { - get: function () { + get: function () + { return this._cacheAsBitmap; }, - set: function (value) { - if (this._cacheAsBitmap === value) { + set: function (value) + { + if (this._cacheAsBitmap === value) + { return; } - if (value) { + if (value) + { this._generateCachedSprite(); } - else { + else + { this._destroyCachedSprite(); } @@ -126,7 +140,8 @@ * @param child {DisplayObject} The DisplayObject to add to the container * @return {DisplayObject} The child that was added. */ -DisplayObjectContainer.prototype.addChild = function (child) { +DisplayObjectContainer.prototype.addChild = function (child) +{ return this.addChildAt(child, this.children.length); }; @@ -137,14 +152,18 @@ * @param index {Number} The index to place the child in * @return {DisplayObject} The child that was added. */ -DisplayObjectContainer.prototype.addChildAt = function (child, index) { +DisplayObjectContainer.prototype.addChildAt = function (child, index) +{ // prevent adding self as child - if (child === this) { + if (child === this) + { return; } - if (index >= 0 && index <= this.children.length) { - if (child.parent) { + if (index >= 0 && index <= this.children.length) + { + if (child.parent) + { child.parent.removeChild(child); } @@ -154,7 +173,8 @@ return child; } - else { + else + { throw new Error(child + 'addChildAt: The index '+ index +' supplied is out of bounds ' + this.children.length); } }; @@ -165,15 +185,18 @@ * @param child {DisplayObject} * @param child2 {DisplayObject} */ -DisplayObjectContainer.prototype.swapChildren = function (child, child2) { - if (child === child2) { +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) { + if (index1 < 0 || index2 < 0) + { throw new Error('swapChildren: Both the supplied DisplayObjects must be a child of the caller.'); } @@ -187,10 +210,12 @@ * @param child {DisplayObject} The DisplayObject instance to identify * @return {Number} The index position of the child display object to identify */ -DisplayObjectContainer.prototype.getChildIndex = function (child) { +DisplayObjectContainer.prototype.getChildIndex = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { throw new Error('The supplied DisplayObject must be a child of the caller'); } @@ -203,8 +228,10 @@ * @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 */ -DisplayObjectContainer.prototype.setChildIndex = function (child, index) { - if (index < 0 || index >= this.children.length) { +DisplayObjectContainer.prototype.setChildIndex = function (child, index) +{ + if (index < 0 || index >= this.children.length) + { throw new Error('The supplied index is out of bounds'); } @@ -220,8 +247,10 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child at the given index, if any. */ -DisplayObjectContainer.prototype.getChildAt = function (index) { - if (index < 0 || index >= this.children.length) { +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'); } @@ -234,10 +263,12 @@ * @param child {DisplayObject} The DisplayObject to remove * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChild = function (child) { +DisplayObjectContainer.prototype.removeChild = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { return; } @@ -250,7 +281,8 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChildAt = function (index) { +DisplayObjectContainer.prototype.removeChildAt = function (index) +{ var child = this.getChildAt(index); child.parent = null; @@ -265,24 +297,29 @@ * @param beginIndex {Number} The beginning position. Default value is 0. * @param endIndex {Number} The ending position. Default value is size of the container. */ -DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) { +DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) +{ var begin = beginIndex || 0; var end = typeof endIndex === 'number' ? endIndex : this.children.length; var range = end - begin; - if (range > 0 && range <= end) { + if (range > 0 && range <= end) + { var removed = this.children.splice(begin, range); - for (var i = 0; i < removed.length; ++i) { + for (var i = 0; i < removed.length; ++i) + { removed[i].parent = null; } return removed; } - else if (range === 0 && this.children.length === 0) { + else if (range === 0 && this.children.length === 0) + { return []; } - else { + else + { throw new RangeError('removeChildren: numeric values are outside the acceptable range.'); } }; @@ -291,7 +328,8 @@ * Generates and updates the cached sprite for this object. * */ -DisplayObjectContainer.prototype.updateCachedSprite = function () { +DisplayObjectContainer.prototype.updateCachedSprite = function () +{ this._generateCachedSprite(); }; @@ -304,7 +342,8 @@ * @param renderer {CanvasRenderer|WebGLRenderer} The renderer used to generate the texture. * @return {Texture} a texture of the graphics object */ -DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) { +DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) +{ var bounds = this.getLocalBounds(); var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0, renderer, scaleMode, resolution); @@ -322,18 +361,22 @@ * * @private */ -DisplayObjectContainer.prototype.updateTransform = function () { - if (!this.visible) { +DisplayObjectContainer.prototype.updateTransform = function () +{ + if (!this.visible) + { return; } this.displayObjectUpdateTransform(); - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { return; } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } }; @@ -346,8 +389,10 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getBounds = function () { - if (this.children.length === 0) { +DisplayObjectContainer.prototype.getBounds = function () +{ + if (this.children.length === 0) + { return math.Rectangle.EMPTY; } @@ -365,10 +410,12 @@ var childVisible = false; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -386,7 +433,8 @@ maxY = maxY > childMaxY ? maxY : childMaxY; } - if (!childVisible) { + if (!childVisible) + { return math.Rectangle.EMPTY; } @@ -407,12 +455,14 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getLocalBounds = function () { +DisplayObjectContainer.prototype.getLocalBounds = function () +{ var matrixCache = this.worldTransform; this.worldTransform = math.Matrix.IDENTITY; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } @@ -428,13 +478,16 @@ * * @param renderer {WebGLRenderer} The renderer */ -DisplayObjectContainer.prototype.renderWebGL = function (renderer) { +DisplayObjectContainer.prototype.renderWebGL = function (renderer) +{ // if the object is not visible or the alpha is 0 then no need to render this element - if (!this.visible || this.alpha <= 0) { + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } @@ -442,14 +495,17 @@ var i, j; // do a quick check to see if this element has a mask or a filter. - if (this._mask || this._filters) { + if (this._mask || this._filters) + { // push filter first as we need to ensure the stencil buffer is correct for any masking - if (this._filters) { + if (this._filters) + { renderer.spriteBatch.flush(); renderer.filterManager.pushFilter(this._filterBlock); } - if (this._mask) { + if (this._mask) + { renderer.spriteBatch.stop(); renderer.maskManager.pushMask(this.mask, renderer); renderer.spriteBatch.start(); @@ -459,36 +515,42 @@ this._renderWebGL(renderer); // now loop through the children and make sure they get rendered - for (i = 0, j = this.children.length; i < j; i++) { + for (i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderWebGL(renderer); } // time to stop the sprite batch as either a mask element or a filter draw will happen next renderer.spriteBatch.stop(); - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(this._mask, renderer); } - if (this._filters) { + if (this._filters) + { renderer.filterManager.popFilter(); } renderer.spriteBatch.start(); } - else { + else + { this._renderWebGL(renderer); // simple render children! - for (i = 0, j = this.children.length; i < j; ++i) { + for (i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderWebGL(renderer); } } }; -DisplayObjectContainer.prototype._renderWebGL = function (renderer) { +DisplayObjectContainer.prototype._renderWebGL = function (renderer) +{ // this is where content itself gets renderd.. @@ -499,25 +561,31 @@ * * @param renderer {CanvasRenderer} The renderer */ -DisplayObjectContainer.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0) { +DisplayObjectContainer.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -528,13 +596,16 @@ * @param renderer {WebGLRenderer|CanvasRenderer} The renderer * @private */ -DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) { +DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) +{ this._cachedSprite.worldAlpha = this.worldAlpha; - if (renderer.gl) { + if (renderer.gl) + { this._cachedSprite.renderWebGL(renderer); } - else { + else + { this._cachedSprite.renderCanvas(renderer); } }; @@ -544,10 +615,12 @@ * * @private */ -DisplayObjectContainer.prototype._generateCachedSprite = function () { +DisplayObjectContainer.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { // TODO - RenderTexture now *requires* a renderer instance, so this is like broken // because `renderer` isn't actually in scope here :P var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0); @@ -555,7 +628,8 @@ this._cachedSprite = new Sprite(renderTexture); this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.texture.resize(bounds.width | 0, bounds.height | 0); } @@ -580,8 +654,10 @@ * * @private */ -DisplayObjectContainer.prototype._destroyCachedSprite = function () { - if (!this._cachedSprite) { +DisplayObjectContainer.prototype._destroyCachedSprite = function () +{ + if (!this._cachedSprite) + { return; } diff --git a/src/core/display/Sprite.js b/src/core/display/Sprite.js index 707da24..5862aef 100644 --- a/src/core/display/Sprite.js +++ b/src/core/display/Sprite.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param texture {Texture} The texture for this sprite */ -function Sprite(texture) { +function Sprite(texture) +{ DisplayObjectContainer.call(this); /** @@ -85,12 +86,14 @@ this.texture = texture || Texture.EMPTY; } -Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) { +Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) +{ DisplayObjectContainer.prototype.destroy.call(this); this.anchor = null; - if (destroyTexture) { + if (destroyTexture) + { this._texture.destroy(destroyBaseTexture); } @@ -111,10 +114,12 @@ * @memberof Sprite# */ width: { - get: function () { + get: function () + { return this.scale.x * this.texture.frame.width; }, - set: function (value) { + set: function (value) + { this.scale.x = value / this.texture.frame.width; this._width = value; } @@ -127,10 +132,12 @@ * @memberof Sprite# */ height: { - get: function () { + get: function () + { return this.scale.y * this.texture.frame.height; }, - set: function (value) { + set: function (value) + { this.scale.y = value / this.texture.frame.height; this._height = value; } @@ -143,23 +150,29 @@ * @memberof Sprite# */ texture: { - get: function () { + get: function () + { return this._texture; }, - set: function (value) { - if (this._texture === value) { + set: function (value) + { + if (this._texture === value) + { return; } this._texture = value; this.cachedTint = 0xFFFFFF; - if (value) { + if (value) + { // wait for the texture to load - if (value.baseTexture.hasLoaded) { + if (value.baseTexture.hasLoaded) + { this._onTextureUpdate(); } - else { + else + { value.once('update', this._onTextureUpdate.bind(this)); } } @@ -172,18 +185,22 @@ * * @private */ -Sprite.prototype._onTextureUpdate = function () { +Sprite.prototype._onTextureUpdate = function () +{ // so if _width is 0 then width was not set.. - if (this._width) { + if (this._width) + { this.scale.x = this._width / this.texture.frame.width; } - if (this._height) { + if (this._height) + { this.scale.y = this._height / this.texture.frame.height; } }; -Sprite.prototype._renderWebGL = function (renderer) { +Sprite.prototype._renderWebGL = function (renderer) +{ // this is where content gets renderd.. // watch this space for a little render state manager.. @@ -197,7 +214,8 @@ * @param matrix {Matrix} the transformation matrix of the sprite * @return {Rectangle} the framing rectangle */ -Sprite.prototype.getBounds = function (matrix) { +Sprite.prototype.getBounds = function (matrix) +{ var width = this.texture.frame.width; var height = this.texture.frame.height; @@ -224,11 +242,13 @@ if(b === 0 && c === 0) { // scale may be negative! - if (a < 0) { + if (a < 0) + { a *= -1; } - if (d < 0) { + if (d < 0) + { d *= -1; } @@ -293,28 +313,34 @@ * * @param renderer {CanvasRenderer} The renderer */ -Sprite.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) { +Sprite.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) + { return; } - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; renderer.context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } // Ignore null sources - if (this.texture.valid) { + if (this.texture.valid) + { var resolution = this.texture.baseTexture.resolution / renderer.resolution; renderer.context.globalAlpha = this.worldAlpha; // If smoothingEnabled is supported and we need to change the smoothing property for this texture - if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) { + if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) + { renderer.scaleMode = this.texture.baseTexture.scaleMode; renderer.context[renderer.smoothProperty] = (renderer.scaleMode === CONST.scaleModes.LINEAR); } @@ -324,7 +350,8 @@ var dy = (this.texture.trim ? this.texture.trim.y : 0) - (this.anchor.y * this.texture.trim.height); // Allow for pixel rounding - if (renderer.roundPixels) { + if (renderer.roundPixels) + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -337,7 +364,8 @@ dx = dx | 0; dy = dy | 0; } - else { + else + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -348,8 +376,10 @@ ); } - if (this.tint !== 0xFFFFFF) { - if (this.cachedTint !== this.tint) { + if (this.tint !== 0xFFFFFF) + { + if (this.cachedTint !== this.tint) + { this.cachedTint = this.tint; // TODO clean up caching - how to clean up the caches? @@ -368,7 +398,8 @@ this.texture.crop.height / resolution ); } - else { + else + { renderer.context.drawImage( this.texture.baseTexture.source, this.texture.crop.x, @@ -383,11 +414,13 @@ } } - for (var i = 0, j = this.children.length; i < j; i++) { + for (var i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -402,10 +435,12 @@ * @param frameId {String} The frame Id of the texture in the cache * @return {Sprite} A new Sprite using a texture from the texture cache matching the frameId */ -Sprite.fromFrame = function (frameId) { +Sprite.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache' + this); } @@ -420,6 +455,7 @@ * @param imageId {String} The image url of the texture * @return {Sprite} A new Sprite using a texture from the texture cache matching the image id */ -Sprite.fromImage = function (imageId, crossorigin, scaleMode) { +Sprite.fromImage = function (imageId, crossorigin, scaleMode) +{ return new Sprite(Texture.fromImage(imageId, crossorigin, scaleMode)); }; diff --git a/src/core/display/SpriteBatch.js b/src/core/display/SpriteBatch.js index 3187777..c196fef 100644 --- a/src/core/display/SpriteBatch.js +++ b/src/core/display/SpriteBatch.js @@ -12,7 +12,8 @@ * ```js * var container = new SpriteBatch(); * - * for(var i = 0; i < 100; ++i) { + * for(var i = 0; i < 100; ++i) + * { * var sprite = new PIXI.Sprite.fromImage("myImage.png"); * container.addChild(sprite); * } @@ -25,7 +26,8 @@ */ //TODO RENAME to PARTICLE CONTAINER? -function SpriteBatch() { +function SpriteBatch() +{ DisplayObjectContainer.call(this); } @@ -38,7 +40,8 @@ * * @private */ -SpriteBatch.prototype.updateTransform = function () { +SpriteBatch.prototype.updateTransform = function () +{ // TODO don't need to! this.displayObjectUpdateTransform(); // PIXI.DisplayObjectContainer.prototype.updateTransform.call( this ); @@ -50,8 +53,10 @@ * @param renderer {WebGLRenderer} The webgl renderer * @private */ -SpriteBatch.prototype.renderWebGL = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderWebGL = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -71,8 +76,10 @@ * @param renderer {CanvasRenderer} The canvas renderer * @private */ -SpriteBatch.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -84,10 +91,12 @@ this.displayObjectUpdateTransform(); - for (var i = 0; i < this.children.length; ++i) { + for (var i = 0; i < this.children.length; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -95,9 +104,11 @@ context.globalAlpha = this.worldAlpha * child.alpha; - if (child.rotation % (Math.PI * 2) === 0) { + if (child.rotation % (Math.PI * 2) === 0) + { // this is the fastest way to optimise! - if rotation is 0 then we can avoid any kind of setTransform call - if (isRotated) { + if (isRotated) + { context.setTransform( transform.a, transform.b, @@ -122,8 +133,10 @@ frame.height * child.scale.y ); } - else { - if (!isRotated) { + else + { + if (!isRotated) + { isRotated = true; } @@ -131,7 +144,8 @@ var childTransform = child.worldTransform; - if (renderer.roundPixels) { + if (renderer.roundPixels) + { context.setTransform( childTransform.a, childTransform.b, @@ -141,7 +155,8 @@ childTransform.ty | 0 ); } - else { + else + { context.setTransform( childTransform.a, childTransform.b, diff --git a/src/core/index.js b/src/core/index.js index 3954b6f..eb4a82b 100644 --- a/src/core/index.js +++ b/src/core/index.js @@ -58,11 +58,13 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRenderer: function (width, height, options, noWebGL) { + autoDetectRenderer: function (width, height, options, noWebGL) + { width = width || 800; height = height || 600; - if (!noWebGL && require('webgl-enabled')()) { + if (!noWebGL && require('webgl-enabled')()) + { return new core.WebGLRenderer(width, height, options); } @@ -87,7 +89,8 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRecommendedRenderer: function (width, height, options) { + autoDetectRecommendedRenderer: function (width, height, options) + { var isAndroid = /Android/i.test(navigator.userAgent); return core.autoDetectRenderer(width, height, options, isAndroid); diff --git a/src/core/math/Matrix.js b/src/core/math/Matrix.js index c2f87e2..2ff4848 100644 --- a/src/core/math/Matrix.js +++ b/src/core/math/Matrix.js @@ -10,7 +10,8 @@ * @class * @namespace PIXI */ -function Matrix() { +function Matrix() +{ /** * @member {number} * @default 1 @@ -63,7 +64,8 @@ * * @param array {number[]} The array that the matrix will be populated from. */ -Matrix.prototype.fromArray = function (array) { +Matrix.prototype.fromArray = function (array) +{ this.a = array[0]; this.b = array[1]; this.c = array[3]; @@ -78,14 +80,17 @@ * @param transpose {boolean} Whether we need to transpose the matrix or not * @return {number[]} the newly created array which contains the matrix */ -Matrix.prototype.toArray = function (transpose) { - if (!this.array) { +Matrix.prototype.toArray = function (transpose) +{ + if (!this.array) + { this.array = new Float32Array(9); } var array = this.array; - if (transpose) { + if (transpose) + { array[0] = this.a; array[1] = this.b; array[2] = 0; @@ -96,7 +101,8 @@ array[7] = this.ty; array[8] = 1; } - else { + else + { array[0] = this.a; array[1] = this.c; array[2] = this.tx; @@ -119,7 +125,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, transformed through this matrix */ -Matrix.prototype.apply = function (pos, newPos) { +Matrix.prototype.apply = function (pos, newPos) +{ newPos = newPos || new Point(); newPos.x = this.a * pos.x + this.c * pos.y + this.tx; @@ -136,7 +143,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, inverse-transformed through this matrix */ -Matrix.prototype.applyInverse = function (pos, newPos) { +Matrix.prototype.applyInverse = function (pos, newPos) +{ newPos = newPos || new Point(); var id = 1 / (this.a * this.d + this.c * -this.b); @@ -154,7 +162,8 @@ * @param {number} y * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.translate = function (x, y) { +Matrix.prototype.translate = function (x, y) +{ this.tx += x; this.ty += y; @@ -168,7 +177,8 @@ * @param {number} y The amount to scale vertically * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.scale = function (x, y) { +Matrix.prototype.scale = function (x, y) +{ this.a *= x; this.d *= y; this.c *= x; @@ -186,7 +196,8 @@ * @param {number} angle - The angle in radians. * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.rotate = function (angle) { +Matrix.prototype.rotate = function (angle) +{ var cos = Math.cos( angle ); var sin = Math.sin( angle ); @@ -210,7 +221,8 @@ * @param {Matrix} matrix * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.append = function (matrix) { +Matrix.prototype.append = function (matrix) +{ var a1 = this.a; var b1 = this.b; var c1 = this.c; @@ -232,7 +244,8 @@ * * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.identity = function () { +Matrix.prototype.identity = function () +{ this.a = 1; this.b = 0; this.c = 0; diff --git a/src/core/math/Point.js b/src/core/math/Point.js index 7565b2d..632f346 100644 --- a/src/core/math/Point.js +++ b/src/core/math/Point.js @@ -7,7 +7,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -function Point(x, y) { +function Point(x, y) +{ /** * @member {number} * @default 0 @@ -29,7 +30,8 @@ * * @return {Point} a copy of the point */ -Point.prototype.clone = function () { +Point.prototype.clone = function () +{ return new Point(this.x, this.y); }; @@ -40,7 +42,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -Point.prototype.set = function (x, y) { +Point.prototype.set = function (x, y) +{ this.x = x || 0; this.y = y || ( (y !== 0) ? this.x : 0 ) ; }; diff --git a/src/core/math/shapes/Circle.js b/src/core/math/shapes/Circle.js index 69cfdc9..4d76efc 100644 --- a/src/core/math/shapes/Circle.js +++ b/src/core/math/shapes/Circle.js @@ -10,7 +10,8 @@ * @param y {number} The Y coordinate of the center of this circle * @param radius {number} The radius of the circle */ -function Circle(x, y, radius) { +function Circle(x, y, radius) +{ /** * @member {number} * @default 0 @@ -46,7 +47,8 @@ * @method clone * @return {Circle} a copy of the Circle */ -Circle.prototype.clone = function () { +Circle.prototype.clone = function () +{ return new Circle(this.x, this.y, this.radius); }; @@ -58,8 +60,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Circle */ -Circle.prototype.contains = function (x, y) { - if (this.radius <= 0) { +Circle.prototype.contains = function (x, y) +{ + if (this.radius <= 0) + { return false; } @@ -79,6 +83,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Circle.prototype.getBounds = function () { +Circle.prototype.getBounds = function () +{ return new Rectangle(this.x - this.radius, this.y - this.radius, this.radius * 2, this.radius * 2); }; diff --git a/src/core/math/shapes/Ellipse.js b/src/core/math/shapes/Ellipse.js index 4f2d066..fefd01a 100644 --- a/src/core/math/shapes/Ellipse.js +++ b/src/core/math/shapes/Ellipse.js @@ -11,7 +11,8 @@ * @param width {number} The half width of this ellipse * @param height {number} The half height of this ellipse */ -function Ellipse(x, y, width, height) { +function Ellipse(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -53,7 +54,8 @@ * @method clone * @return {Ellipse} a copy of the ellipse */ -Ellipse.prototype.clone = function () { +Ellipse.prototype.clone = function () +{ return new Ellipse(this.x, this.y, this.width, this.height); }; @@ -65,8 +67,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coords are within this ellipse */ -Ellipse.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Ellipse.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } @@ -86,6 +90,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Ellipse.prototype.getBounds = function () { +Ellipse.prototype.getBounds = function () +{ return new Rectangle(this.x - this.width, this.y - this.height, this.width, this.height); }; diff --git a/src/core/math/shapes/Polygon.js b/src/core/math/shapes/Polygon.js index ae89148..fea6d37 100644 --- a/src/core/math/shapes/Polygon.js +++ b/src/core/math/shapes/Polygon.js @@ -10,16 +10,20 @@ * arguments passed can be flat x,y values e.g. `new Polygon(x,y, x,y, x,y, ...)` where `x` and `y` are * Numbers. */ -function Polygon(points) { +function Polygon(points) +{ //if points isn't an array, use arguments as the array - if (!(points instanceof Array)) { + if (!(points instanceof Array)) + { points = Array.prototype.slice.call(arguments); } //if this is a flat array of numbers, convert it to points - if (points[0] instanceof Point) { + if (points[0] instanceof Point) + { var p = []; - for (var i = 0, il = points.length; i < il; i++) { + for (var i = 0, il = points.length; i < il; i++) + { p.push(points[i].x, points[i].y); } @@ -51,7 +55,8 @@ * * @return {Polygon} a copy of the polygon */ -Polygon.prototype.clone = function () { +Polygon.prototype.clone = function () +{ return new Polygon(this.points.slice()); }; @@ -62,19 +67,22 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this polygon */ -Polygon.prototype.contains = function (x, y) { +Polygon.prototype.contains = function (x, y) +{ var inside = false; // use some raycasting to test hits // https://github.com/substack/point-in-polygon/blob/master/index.js var length = this.points.length / 2; - for (var i = 0, j = length - 1; i < length; j = i++) { + for (var i = 0, j = length - 1; i < length; j = i++) + { var xi = this.points[i * 2], yi = this.points[i * 2 + 1], xj = this.points[j * 2], yj = this.points[j * 2 + 1], intersect = ((yi > y) !== (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi); - if (intersect) { + if (intersect) + { inside = !inside; } } diff --git a/src/core/math/shapes/Rectangle.js b/src/core/math/shapes/Rectangle.js index 16ac62a..4008b68 100644 --- a/src/core/math/shapes/Rectangle.js +++ b/src/core/math/shapes/Rectangle.js @@ -10,7 +10,8 @@ * @param width {number} The overall width of this rectangle * @param height {number} The overall height of this rectangle */ -function Rectangle(x, y, width, height) { +function Rectangle(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -60,7 +61,8 @@ * * @return {Rectangle} a copy of the rectangle */ -Rectangle.prototype.clone = function () { +Rectangle.prototype.clone = function () +{ return new Rectangle(this.x, this.y, this.width, this.height); }; @@ -71,13 +73,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rectangle */ -Rectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Rectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/math/shapes/RoundedRectangle.js b/src/core/math/shapes/RoundedRectangle.js index 27d286e..7bf6411 100644 --- a/src/core/math/shapes/RoundedRectangle.js +++ b/src/core/math/shapes/RoundedRectangle.js @@ -11,7 +11,8 @@ * @param height {number} The overall height of this rounded rectangle * @param radius {number} Controls the radius of the rounded corners */ -function RoundedRectangle(x, y, width, height, radius) { +function RoundedRectangle(x, y, width, height, radius) +{ /** * @member {number} * @default 0 @@ -58,7 +59,8 @@ * * @return {RoundedRectangle} a copy of the rounded rectangle */ -RoundedRectangle.prototype.clone = function () { +RoundedRectangle.prototype.clone = function () +{ return new RoundedRectangle(this.x, this.y, this.width, this.height, this.radius); }; @@ -69,13 +71,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rounded Rectangle */ -RoundedRectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +RoundedRectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/primitives/Graphics.js b/src/core/primitives/Graphics.js index 261c534..e902d2a 100644 --- a/src/core/primitives/Graphics.js +++ b/src/core/primitives/Graphics.js @@ -16,7 +16,8 @@ * @extends DisplayObjectContainer * @namespace PIXI */ -function Graphics() { +function Graphics() +{ DisplayObjectContainer.call(this); this.renderable = true; @@ -154,16 +155,20 @@ * @private */ cacheAsBitmap: { - get: function () { + get: function () + { return this._cacheAsBitmap; }, - set: function (value) { + set: function (value) + { this._cacheAsBitmap = value; - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._generateCachedSprite(); } - else { + else + { this.destroyCachedSprite(); this.dirty = true; } @@ -176,7 +181,8 @@ * * @return {Graphics} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ var clone = new Graphics(); clone.renderable = this.renderable; @@ -192,7 +198,8 @@ clone.cachedSpriteDirty = this.cachedSpriteDirty; // copy graphics data - for (var i = 0; i < this.graphicsData.length; ++i) { + for (var i = 0; i < this.graphicsData.length; ++i) + { clone.graphicsData.push(this.graphicsData.clone()); } @@ -211,17 +218,21 @@ * @param alpha {number} alpha of the line to draw, will update the objects stored style * @return {Graphics} */ -Graphics.prototype.lineStyle = function (lineWidth, color, alpha) { +Graphics.prototype.lineStyle = function (lineWidth, color, alpha) +{ this.lineWidth = lineWidth || 0; this.lineColor = color || 0; this.lineAlpha = (arguments.length < 3) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length) + { // halfway through a line? start a new one! this.drawShape( new math.Polygon( this.currentPath.shape.points.slice(-2) )); } - else { + else + { // otherwise its empty so lets just set the line properties this.currentPath.lineWidth = this.lineWidth; this.currentPath.lineColor = this.lineColor; @@ -239,7 +250,8 @@ * @param y {number} the Y coordinate to move to * @return {Graphics} */ -Graphics.prototype.moveTo = function (x, y) { +Graphics.prototype.moveTo = function (x, y) +{ this.drawShape(new math.Polygon([x,y])); return this; @@ -253,7 +265,8 @@ * @param y {number} the Y coordinate to draw to * @return {Graphics} */ -Graphics.prototype.lineTo = function (x, y) { +Graphics.prototype.lineTo = function (x, y) +{ this.currentPath.shape.points.push(x, y); this.dirty = true; @@ -270,13 +283,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -285,7 +302,8 @@ n = 20, points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { this.moveTo(0, 0); } @@ -293,7 +311,8 @@ var fromY = points[points.length-1]; var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; xa = fromX + ( (cpX - fromX) * j ); @@ -319,13 +338,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -342,7 +365,8 @@ var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; dt = (1 - j); @@ -373,13 +397,17 @@ * @param radius {number} The radius of the arc * @return {Graphics} */ -Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points.push(x1, y1); } } - else { + else + { this.moveTo(x1, y1); } @@ -392,12 +420,15 @@ b2 = x2 - x1, mm = Math.abs(a1 * b2 - b1 * a2); - if (mm < 1.0e-8 || radius === 0) { - if (points[points.length-2] !== x1 || points[points.length-1] !== y1) { + if (mm < 1.0e-8 || radius === 0) + { + if (points[points.length-2] !== x1 || points[points.length-1] !== y1) + { points.push(x1, y1); } } - else { + else + { var dd = a1 * a1 + b1 * b1, cc = a2 * a2 + b2 * b2, tt = a1 * a2 + b1 * b2, @@ -433,42 +464,51 @@ * @param anticlockwise {boolean} Optional. Specifies whether the drawing should be counterclockwise or clockwise. False is default, and indicates clockwise, while true indicates counter-clockwise. * @return {Graphics} */ -Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) { +Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) +{ var startX = cx + Math.cos(startAngle) * radius; var startY = cy + Math.sin(startAngle) * radius; var points; // TODO - This if-else makes no sense. It uses currentPath in the else where it doesn't exist... - if (this.currentPath) { + if (this.currentPath) + { points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { points.push(startX, startY); } - else if (points[points.length-2] !== startX || points[points.length-1] !== startY) { + else if (points[points.length-2] !== startX || points[points.length-1] !== startY) + { points.push(startX, startY); } } - else { + else + { this.moveTo(startX, startY); points = this.currentPath.shape.points; } - if (startAngle === endAngle) { + if (startAngle === endAngle) + { return this; } - if (!anticlockwise && endAngle <= startAngle) { + if (!anticlockwise && endAngle <= startAngle) + { endAngle += Math.PI * 2; } - else if (anticlockwise && startAngle <= endAngle) { + else if (anticlockwise && startAngle <= endAngle) + { startAngle += Math.PI * 2; } var sweep = anticlockwise ? (startAngle - endAngle) *-1 : (endAngle - startAngle); var segs = (Math.abs(sweep)/ (Math.PI * 2)) * 40; - if (sweep === 0) { + if (sweep === 0) + { return this; } @@ -482,7 +522,8 @@ var remainder = ( segMinus % 1 ) / segMinus; - for (var i = 0; i <= segMinus; ++i) { + for (var i = 0; i <= segMinus; ++i) + { var real = i + remainder * i; var angle = ((theta) + startAngle + (theta2 * real)); @@ -506,13 +547,16 @@ * @param alpha {number} the alpha of the fill * @return {Graphics} */ -Graphics.prototype.beginFill = function (color, alpha) { +Graphics.prototype.beginFill = function (color, alpha) +{ this.filling = true; this.fillColor = color || 0; this.fillAlpha = (alpha === undefined) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length <= 2) + { this.currentPath.fill = this.filling; this.currentPath.fillColor = this.fillColor; this.currentPath.fillAlpha = this.fillAlpha; @@ -526,7 +570,8 @@ * * @return {Graphics} */ -Graphics.prototype.endFill = function () { +Graphics.prototype.endFill = function () +{ this.filling = false; this.fillColor = null; this.fillAlpha = 1; @@ -542,7 +587,8 @@ * @param height {number} The height of the rectangle * @return {Graphics} */ -Graphics.prototype.drawRect = function ( x, y, width, height ) { +Graphics.prototype.drawRect = function ( x, y, width, height ) +{ this.drawShape(new math.Rectangle(x,y, width, height)); return this; @@ -556,7 +602,8 @@ * @param height {number} The height of the rectangle * @param radius {number} Radius of the rectangle corners */ -Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) { +Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) +{ this.drawShape(new math.RoundedRectangle(x, y, width, height, radius)); return this; @@ -570,7 +617,8 @@ * @param radius {number} The radius of the circle * @return {Graphics} */ -Graphics.prototype.drawCircle = function (x, y, radius) { +Graphics.prototype.drawCircle = function (x, y, radius) +{ this.drawShape(new math.Circle(x,y, radius)); return this; @@ -585,7 +633,8 @@ * @param height {number} The half height of the ellipse * @return {Graphics} */ -Graphics.prototype.drawEllipse = function (x, y, width, height) { +Graphics.prototype.drawEllipse = function (x, y, width, height) +{ this.drawShape(new math.Ellipse(x, y, width, height)); return this; @@ -597,8 +646,10 @@ * @param path {Array} The path data used to construct the polygon. * @return {Graphics} */ -Graphics.prototype.drawPolygon = function (path) { - if (!(path instanceof Array)) { +Graphics.prototype.drawPolygon = function (path) +{ + if (!(path instanceof Array)) + { path = Array.prototype.slice.call(arguments); } @@ -612,7 +663,8 @@ * * @return {Graphics} */ -Graphics.prototype.clear = function () { +Graphics.prototype.clear = function () +{ this.lineWidth = 0; this.filling = false; @@ -631,7 +683,8 @@ * @param scaleMode {number} Should be one of the scaleMode consts * @return {Texture} a texture of the graphics object */ -Graphics.prototype.generateTexture = function (resolution, scaleMode) { +Graphics.prototype.generateTexture = function (resolution, scaleMode) +{ resolution = resolution || 1; var bounds = this.getBounds(); @@ -655,17 +708,21 @@ * * @param renderer {WebGLRenderer} */ -Graphics.prototype._renderWebGL = function (renderer) { +Graphics.prototype._renderWebGL = function (renderer) +{ // if the sprite is not visible or the alpha is 0 then no need to render this element - if (this.isMask === true) { + if (this.isMask === true) + { return; } // this code may still be needed so leaving for now.. - // + // /* - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture on the gpu too! @@ -681,17 +738,24 @@ return; } - */ - - // check if the webgl graphic needs to be updated - if (this.glDirty) { - this.dirty = true; - this.glDirty = false; - } + else */ - renderer.setObjectRendererer(renderer.graphicsRenderer); - renderer.graphicsRenderer.render(this); + renderer.spriteBatch.stop(); + renderer.blendModeManager.setBlendMode(this.blendMode); + // check blend mode + renderer.blendModeManager.setBlendMode( this.blendMode ); + + // check if the webgl graphic needs to be updated + if (this.glDirty) + { + this.dirty = true; + this.glDirty = false; + } + + WebGLGraphics.renderGraphics(this, renderer); + + renderer.spriteBatch.start(); }; /** @@ -700,14 +764,18 @@ * @param renderer {CanvasRenderer} * @private */ -Graphics.prototype.renderCanvas = function (renderer) { +Graphics.prototype.renderCanvas = function (renderer) +{ // 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.isMask === true) { + if (!this.visible || this.alpha <= 0 || this.isMask === true) + { return; } - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture @@ -723,16 +791,19 @@ return; } - else { + else + { var context = renderer.context; var transform = this.worldTransform; - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } @@ -748,11 +819,13 @@ CanvasGraphics.renderGraphics(this, context); - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } } @@ -763,13 +836,16 @@ * * @return {Rectangle} the rectangular bounding area */ -Graphics.prototype.getBounds = function (matrix) { +Graphics.prototype.getBounds = function (matrix) +{ // return an empty object if the item is a mask! - if (this.isMask) { + if (this.isMask) + { return math.Rectangle.EMPTY; } - if (this.dirty) { + if (this.dirty) + { this.updateLocalBounds(); this.glDirty = true; @@ -841,23 +917,27 @@ * Update the bounds of the object * */ -Graphics.prototype.updateLocalBounds = function () { +Graphics.prototype.updateLocalBounds = function () +{ var minX = Infinity; var maxX = -Infinity; var minY = Infinity; var maxY = -Infinity; - if (this.graphicsData.length) { + if (this.graphicsData.length) + { var shape, points, x, y, w, h; - for (var i = 0; i < this.graphicsData.length; i++) { + for (var i = 0; i < this.graphicsData.length; i++) + { var data = this.graphicsData[i]; var type = data.type; var lineWidth = data.lineWidth; shape = data.shape; - if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) { + if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) + { x = shape.x - lineWidth/2; y = shape.y - lineWidth/2; w = shape.width + lineWidth; @@ -869,7 +949,8 @@ minY = y < minY ? y : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.CIRC) { + else if (type === CONST.SHAPES.CIRC) + { x = shape.x; y = shape.y; w = shape.radius + lineWidth/2; @@ -881,7 +962,8 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.ELIP) { + else if (type === CONST.SHAPES.ELIP) + { x = shape.x; y = shape.y; w = shape.width + lineWidth/2; @@ -893,11 +975,13 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else { + else + { // POLY points = shape.points; - for (var j = 0; j < points.length; j += 2) { + for (var j = 0; j < points.length; j += 2) + { x = points[j]; y = points[j+1]; @@ -910,7 +994,8 @@ } } } - else { + else + { minX = 0; maxX = 0; minY = 0; @@ -931,10 +1016,12 @@ * * @private */ -Graphics.prototype._generateCachedSprite = function () { +Graphics.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { var canvasBuffer = new CanvasBuffer(bounds.width, bounds.height); var texture = Texture.fromCanvas(canvasBuffer.canvas); @@ -943,7 +1030,8 @@ this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.buffer.resize(bounds.width, bounds.height); } @@ -968,7 +1056,8 @@ * * @private */ -Graphics.prototype.updateCachedSpriteTexture = function () { +Graphics.prototype.updateCachedSpriteTexture = function () +{ var cachedSprite = this._cachedSprite; var texture = cachedSprite.texture; var canvas = cachedSprite.buffer.canvas; @@ -989,7 +1078,8 @@ * Destroys a previous cached sprite. * */ -Graphics.prototype.destroyCachedSprite = function () { +Graphics.prototype.destroyCachedSprite = function () +{ this._cachedSprite.texture.destroy(true); // let the gc collect the unused sprite @@ -1003,10 +1093,13 @@ * @param {Circle|Rectangle|Ellipse|Line|Polygon} shape The Shape object to draw. * @return {GraphicsData} The generated GraphicsData object. */ -Graphics.prototype.drawShape = function (shape) { - if (this.currentPath) { +Graphics.prototype.drawShape = function (shape) +{ + if (this.currentPath) + { // check current path! - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath.shape.points.length <= 2) + { this.graphicsData.pop(); } } @@ -1017,7 +1110,8 @@ this.graphicsData.push(data); - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { data.shape.closed = this.filling; this.currentPath = data; } diff --git a/src/core/primitives/GraphicsData.js b/src/core/primitives/GraphicsData.js index 99decbe..788f6f2 100644 --- a/src/core/primitives/GraphicsData.js +++ b/src/core/primitives/GraphicsData.js @@ -4,7 +4,8 @@ * @class * @namespace PIXI */ -function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) { +function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) +{ this.lineWidth = lineWidth; this.lineColor = lineColor; this.lineAlpha = lineAlpha; @@ -27,7 +28,8 @@ * * @return {GraphicsData} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ return new GraphicsData( this.lineWidth, this.lineColor, diff --git a/src/core/renderers/canvas/CanvasRenderer.js b/src/core/renderers/canvas/CanvasRenderer.js index 15a0978..7aebd44 100644 --- a/src/core/renderers/canvas/CanvasRenderer.js +++ b/src/core/renderers/canvas/CanvasRenderer.js @@ -17,17 +17,22 @@ * @param [options.resolution=1] {number} the resolution of the renderer retina would be 2 * @param [options.clearBeforeRender=true] {boolean} This sets if the CanvasRenderer will clear the canvas or not before the new render pass. */ -function CanvasRenderer(width, height, options) { +function CanvasRenderer(width, height, options) +{ utils.sayHello('Canvas'); - if (options) { - for (var i in CONST.defaultRenderOptions) { - if (typeof options[i] === 'undefined') { + if (options) + { + for (var i in CONST.defaultRenderOptions) + { + if (typeof options[i] === 'undefined') + { options[i] = CONST.defaultRenderOptions[i]; } } } - else { + else + { options = CONST.defaultRenderOptions; } @@ -156,19 +161,24 @@ this.smoothProperty = null; - if (this.context.imageSmoothingEnabled) { + if (this.context.imageSmoothingEnabled) + { this.smoothProperty = 'imageSmoothingEnabled'; } - else if (this.context.webkitImageSmoothingEnabled) { + else if (this.context.webkitImageSmoothingEnabled) + { this.smoothProperty = 'webkitImageSmoothingEnabled'; } - else if (this.context.mozImageSmoothingEnabled) { + else if (this.context.mozImageSmoothingEnabled) + { this.smoothProperty = 'mozImageSmoothingEnabled'; } - else if (this.context.oImageSmoothingEnabled) { + else if (this.context.oImageSmoothingEnabled) + { this.smoothProperty = 'oImageSmoothingEnabled'; } - else if (this.context.msImageSmoothingEnabled) { + else if (this.context.msImageSmoothingEnabled) + { this.smoothProperty = 'msImageSmoothingEnabled'; } @@ -193,10 +203,12 @@ * @memberof CanvasRenderer# */ backgroundColor: { - get: function () { + get: function () + { return this._backgroundColor; }, - set: function (val) { + set: function (val) + { this._backgroundColor = val; this._backgroundColorString = utils.hex2string(val); } @@ -208,7 +220,8 @@ * * @param object {DisplayObject} the object to be rendered */ -CanvasRenderer.prototype.render = function (object) { +CanvasRenderer.prototype.render = function (object) +{ object.updateTransform(); this.context.setTransform(1,0,0,1,0,0); @@ -218,16 +231,20 @@ this.currentBlendMode = CONST.blendModes.NORMAL; this.context.globalCompositeOperation = this.blendModes[CONST.blendModes.NORMAL]; - if (navigator.isCocoonJS && this.view.screencanvas) { + if (navigator.isCocoonJS && this.view.screencanvas) + { this.context.fillStyle = 'black'; this.context.clear(); } - if (this.clearBeforeRender) { - if (this.transparent) { + if (this.clearBeforeRender) + { + if (this.transparent) + { this.context.clearRect(0, 0, this.width, this.height); } - else { + else + { this.context.fillStyle = this._backgroundColorString; this.context.fillRect(0, 0, this.width , this.height); } @@ -241,8 +258,10 @@ * * @param [removeView=false] {boolean} Removes the Canvas element from the DOM. */ -CanvasRenderer.prototype.destroy = function (removeView) { - if (removeView && this.view.parent) { +CanvasRenderer.prototype.destroy = function (removeView) +{ + if (removeView && this.view.parent) + { this.view.parent.removeChild(this.view); } @@ -257,14 +276,16 @@ * @param width {number} the new width of the canvas view * @param height {number} the new height of the canvas view */ -CanvasRenderer.prototype.resize = function (width, height) { +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) { + if (this.autoResize) + { this.view.style.width = this.width / this.resolution + 'px'; this.view.style.height = this.height / this.resolution + 'px'; } @@ -276,7 +297,8 @@ * @param displayObject {DisplayObject} The displayObject to render * @private */ -CanvasRenderer.prototype.renderDisplayObject = function (displayObject) { +CanvasRenderer.prototype.renderDisplayObject = function (displayObject) +{ displayObject.renderCanvas(this); }; @@ -285,11 +307,14 @@ * * @private */ -CanvasRenderer.prototype._mapBlendModes = function () { - if (!this.blendModes) { +CanvasRenderer.prototype._mapBlendModes = function () +{ + if (!this.blendModes) + { this.blendModes = {}; - if (utils.canUseNewCanvasBlendModes()) { + if (utils.canUseNewCanvasBlendModes()) + { this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? this.blendModes[CONST.blendModes.MULTIPLY] = 'multiply'; @@ -308,7 +333,8 @@ this.blendModes[CONST.blendModes.COLOR] = 'color'; this.blendModes[CONST.blendModes.LUMINOSITY] = 'luminosity'; } - else { + else + { // this means that the browser does not support the cool new blend modes in canvas 'cough' ie 'cough' this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? diff --git a/src/core/renderers/canvas/utils/CanvasBuffer.js b/src/core/renderers/canvas/utils/CanvasBuffer.js index ebe5d47..b183a66 100644 --- a/src/core/renderers/canvas/utils/CanvasBuffer.js +++ b/src/core/renderers/canvas/utils/CanvasBuffer.js @@ -6,7 +6,8 @@ * @param width {number} the width for the newly created canvas * @param height {number} the height for the newly created canvas */ -function CanvasBuffer(width, height) { +function CanvasBuffer(width, height) +{ /** * The Canvas object that belongs to this CanvasBuffer. * @@ -36,10 +37,12 @@ * @memberof CanvasBuffer# */ width: { - get: function () { + get: function () + { return this.canvas.width; }, - set: function (val) { + set: function (val) + { this.canvas.width = val; } }, @@ -50,10 +53,12 @@ * @memberof CanvasBuffer# */ height: { - get: function () { + get: function () + { return this.canvas.height; }, - set: function (val) { + set: function (val) + { this.canvas.height = val; } } @@ -64,7 +69,8 @@ * * @private */ -CanvasBuffer.prototype.clear = function () { +CanvasBuffer.prototype.clear = function () +{ this.context.setTransform(1, 0, 0, 1, 0, 0); this.context.clearRect(0,0, this.canvas.width, this.canvas.height); }; @@ -75,7 +81,8 @@ * @param width {number} the new width of the canvas * @param height {number} the new height of the canvas */ -CanvasBuffer.prototype.resize = function (width, height) { +CanvasBuffer.prototype.resize = function (width, height) +{ this.canvas.width = width; this.canvas.height = height; }; diff --git a/src/core/renderers/canvas/utils/CanvasGraphics.js b/src/core/renderers/canvas/utils/CanvasGraphics.js index c7eaa2a..3f2a91f 100644 --- a/src/core/renderers/canvas/utils/CanvasGraphics.js +++ b/src/core/renderers/canvas/utils/CanvasGraphics.js @@ -13,15 +13,18 @@ * @param graphics {Graphics} the actual graphics object to render * @param context {CanvasRenderingContext2D} the 2d drawing method of the canvas */ -CanvasGraphics.renderGraphics = function (graphics, context) { +CanvasGraphics.renderGraphics = function (graphics, context) +{ var worldAlpha = graphics.worldAlpha; - if (graphics.dirty) { + if (graphics.dirty) + { this.updateGraphicsTint(graphics); graphics.dirty = false; } - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; @@ -30,69 +33,82 @@ context.lineWidth = data.lineWidth; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { context.beginPath(); var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } - if (shape.closed) { + if (shape.closed) + { context.lineTo(points[0], points[1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fillRect(shape.x, shape.y, shape.width, shape.height); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.strokeRect(shape.x, shape.y, shape.width, shape.height); } } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.beginPath(); context.arc(shape.x, shape.y, shape.radius,0,2*Math.PI); context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas var w = shape.width * 2; @@ -119,18 +135,21 @@ context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; var width = shape.width; @@ -152,13 +171,15 @@ context.quadraticCurveTo(rx, ry, rx, ry + radius); context.closePath(); - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); @@ -174,45 +195,54 @@ * @param graphics {Graphics} the graphics which will be used as a mask * @param context {CanvasRenderingContext2D} the context 2d method of the canvas */ -CanvasGraphics.renderGraphicsMask = function (graphics, context) { +CanvasGraphics.renderGraphicsMask = function (graphics, context) +{ var len = graphics.graphicsData.length; - if (len === 0) { + if (len === 0) + { return; } context.beginPath(); - for (var i = 0; i < len; i++) { + for (var i = 0; i < len; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { context.rect(shape.x, shape.y, shape.width, shape.height); context.closePath(); } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.arc(shape.x, shape.y, shape.radius, 0, 2 * Math.PI); context.closePath(); } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas @@ -237,7 +267,8 @@ context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); context.closePath(); } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; @@ -262,8 +293,10 @@ } }; -CanvasGraphics.updateGraphicsTint = function (graphics) { - if (graphics.tint === 0xFFFFFF) { +CanvasGraphics.updateGraphicsTint = function (graphics) +{ + if (graphics.tint === 0xFFFFFF) + { return; } @@ -271,7 +304,8 @@ var tintG = (graphics.tint >> 8 & 0xFF) / 255; var tintB = (graphics.tint & 0xFF)/ 255; - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var fillColor = data.fillColor | 0; diff --git a/src/core/renderers/canvas/utils/CanvasMaskManager.js b/src/core/renderers/canvas/utils/CanvasMaskManager.js index e04a733..9827d36 100644 --- a/src/core/renderers/canvas/utils/CanvasMaskManager.js +++ b/src/core/renderers/canvas/utils/CanvasMaskManager.js @@ -6,7 +6,8 @@ * @class * @namespace PIXI */ -function CanvasMaskManager() {} +function CanvasMaskManager() +{} CanvasMaskManager.prototype.constructor = CanvasMaskManager; module.exports = CanvasMaskManager; @@ -17,7 +18,8 @@ * @param maskData {object} the maskData that will be pushed * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.pushMask = function (maskData, renderer) { +CanvasMaskManager.prototype.pushMask = function (maskData, renderer) +{ renderer.context.save(); var cacheAlpha = maskData.alpha; @@ -45,6 +47,7 @@ * * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.popMask = function (renderer) { +CanvasMaskManager.prototype.popMask = function (renderer) +{ renderer.context.restore(); }; diff --git a/src/core/renderers/canvas/utils/CanvasTinter.js b/src/core/renderers/canvas/utils/CanvasTinter.js index 17e0529..d2fb1bc 100644 --- a/src/core/renderers/canvas/utils/CanvasTinter.js +++ b/src/core/renderers/canvas/utils/CanvasTinter.js @@ -14,7 +14,8 @@ * @param color {number} the color to use to tint the sprite with * @return {HTMLCanvasElement} The tinted canvas */ -CanvasTinter.getTintedTexture = function (sprite, color) { +CanvasTinter.getTintedTexture = function (sprite, color) +{ var texture = sprite.texture; color = CanvasTinter.roundColor(color); @@ -23,7 +24,8 @@ texture.tintCache = texture.tintCache || {}; - if (texture.tintCache[stringColor]) { + if (texture.tintCache[stringColor]) + { return texture.tintCache[stringColor]; } @@ -33,14 +35,16 @@ //CanvasTinter.tintWithPerPixel(texture, stringColor, canvas); CanvasTinter.tintMethod(texture, color, canvas); - if (CanvasTinter.convertTintToImage) { + if (CanvasTinter.convertTintToImage) + { // is this better? var tintImage = new Image(); tintImage.src = canvas.toDataURL(); texture.tintCache[stringColor] = tintImage; } - else { + else + { texture.tintCache[stringColor] = canvas; // if we are not converting the texture to an image then we need to lose the reference to the canvas CanvasTinter.canvas = null; @@ -56,7 +60,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithMultiply = function (texture, color, canvas) { +CanvasTinter.tintWithMultiply = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -104,7 +109,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithOverlay = function (texture, color, canvas) { +CanvasTinter.tintWithOverlay = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -139,7 +145,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithPerPixel = function (texture, color, canvas) { +CanvasTinter.tintWithPerPixel = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -167,7 +174,8 @@ var pixels = pixelData.data; - for (var i = 0; i < pixels.length; i += 4) { + for (var i = 0; i < pixels.length; i += 4) + { pixels[i+0] *= r; pixels[i+1] *= g; pixels[i+2] *= b; @@ -181,7 +189,8 @@ * * @param color {number} the color to round, should be a hex color */ -CanvasTinter.roundColor = function (color) { +CanvasTinter.roundColor = function (color) +{ var step = CanvasTinter.cacheStepsPerColorChannel; var rgbValues = utils.hex2rgb(color); diff --git a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js index 9f2f89a..35edbaf 100644 --- a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js +++ b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLBlendModeManager(renderer) { +function WebGLBlendModeManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -23,8 +24,10 @@ * * @param blendMode {number} the blendMode, should be a Pixi const, such as BlendModes.ADD */ -WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) { - if (this.currentBlendMode === blendMode) { +WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) +{ + if (this.currentBlendMode === blendMode) + { return false; } diff --git a/src/core/renderers/webgl/managers/WebGLFilterManager.js b/src/core/renderers/webgl/managers/WebGLFilterManager.js index 1179258..2dac048 100644 --- a/src/core/renderers/webgl/managers/WebGLFilterManager.js +++ b/src/core/renderers/webgl/managers/WebGLFilterManager.js @@ -7,7 +7,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLFilterManager(renderer) { +function WebGLFilterManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -32,7 +33,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.texturePool.length = 0; self.initShaderBuffers(); }); @@ -46,7 +48,8 @@ * @param renderer {WebGLRenderer} * @param buffer {ArrayBuffer} */ -WebGLFilterManager.prototype.begin = function (buffer) { +WebGLFilterManager.prototype.begin = function (buffer) +{ this.defaultShader = this.renderer.shaderManager.defaultShader; this.width = this.renderer.projection.x * 2; @@ -60,7 +63,8 @@ * * @param filterBlock {object} the filter that will be pushed to the current filter stack */ -WebGLFilterManager.prototype.pushFilter = function (filterBlock) { +WebGLFilterManager.prototype.pushFilter = function (filterBlock) +{ var gl = this.renderer.gl; var projection = this.renderer.projection; @@ -78,10 +82,12 @@ this.offsetY += filterBlock._filterArea.y; var texture = this.texturePool.pop(); - if (!texture) { + if (!texture) + { texture = new FilterTexture(this.renderer.gl, this.width, this.height); } - else { + else + { texture.resize(this.width, this.height); } @@ -98,29 +104,35 @@ var localX = filterArea.x, localY = filterArea.y; - if (filterArea.x < 0) { + if (filterArea.x < 0) + { filterArea.width += filterArea.x; filterArea.x = 0; } - if (filterArea.y < 0) { + if (filterArea.y < 0) + { filterArea.height += filterArea.y; filterArea.y = 0; } - if (localX + filterArea.width > this.width) { + if (localX + filterArea.width > this.width) + { filterArea.width = this.width - localX; } - if (localY + filterArea.height > this.height) { + if (localY + filterArea.height > this.height) + { filterArea.height = this.height - localY; } - if (filterArea.width < 0) { + if (filterArea.width < 0) + { filterArea.width = 0; } - if (filterArea.height < 0) { + if (filterArea.height < 0) + { filterArea.height = 0; } @@ -154,7 +166,8 @@ * Removes the last filter from the filter stack and doesn't return it. * */ -WebGLFilterManager.prototype.popFilter = function () { +WebGLFilterManager.prototype.popFilter = function () +{ var gl = this.renderer.gl; var filterBlock = this.filterStack.pop(); @@ -163,7 +176,8 @@ var projection = this.renderer.projection; var offset = this.renderer.offset; - if (filterBlock.filterPasses.length > 1) { + if (filterBlock.filterPasses.length > 1) + { gl.viewport(0, 0, filterArea.width, filterArea.height); gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); @@ -193,7 +207,8 @@ var inputTexture = texture; var outputTexture = this.texturePool.pop(); - if (!outputTexture) { + if (!outputTexture) + { outputTexture = new FilterTexture(this.renderer.gl, this.width, this.height); } outputTexture.resize(this.width, this.height); @@ -204,7 +219,8 @@ gl.disable(gl.BLEND); - for (var i = 0; i < filterBlock.filterPasses.length-1; i++) { + for (var i = 0; i < filterBlock.filterPasses.length-1; i++) + { var filterPass = filterBlock.filterPasses[i]; gl.bindFramebuffer(gl.FRAMEBUFFER, outputTexture.frameBuffer ); @@ -243,10 +259,12 @@ var buffer = this.buffer; // time to render the filters texture to the previous scene - if (this.filterStack.length === 0) { + if (this.filterStack.length === 0) + { gl.colorMask(true, true, true, true);//this.transparent); } - else { + else + { var currentFilter = this.filterStack[this.filterStack.length-1]; filterArea = currentFilter._filterArea; @@ -332,13 +350,15 @@ * @param width {number} the horizontal range of the filter * @param height {number} the vertical range of the filter */ -WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) { +WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) +{ // use program var gl = this.renderer.gl; var shader = filter.shaders[gl.id]; - if (!shader) { + if (!shader) + { shader = new Shader(gl); shader.fragmentSrc = filter.fragmentSrc; @@ -356,7 +376,8 @@ gl.uniform2f(shader.projectionVector, width/2, -height/2); gl.uniform2f(shader.offsetVector, 0,0); - if (filter.uniforms.dimensions) { + 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]; @@ -386,7 +407,8 @@ * Initialises the shader buffers. * */ -WebGLFilterManager.prototype.initShaderBuffers = function () { +WebGLFilterManager.prototype.initShaderBuffers = function () +{ var gl = this.renderer.gl; // create some buffers @@ -432,7 +454,8 @@ * Destroys the filter and removes it from the filter stack. * */ -WebGLFilterManager.prototype.destroy = function () { +WebGLFilterManager.prototype.destroy = function () +{ var gl = this.renderer.gl; this.filterStack = null; @@ -441,7 +464,8 @@ this.offsetY = 0; // destroy textures - for (var i = 0; i < this.texturePool.length; i++) { + for (var i = 0; i < this.texturePool.length; i++) + { this.texturePool[i].destroy(); } diff --git a/src/core/display/DisplayObject.js b/src/core/display/DisplayObject.js index 66ebc3c..20e778c 100644 --- a/src/core/display/DisplayObject.js +++ b/src/core/display/DisplayObject.js @@ -7,7 +7,8 @@ * @class * @namespace PIXI */ -function DisplayObject() { +function DisplayObject() +{ /** * The coordinate of the object relative to the local coordinates of the parent. * @@ -152,10 +153,12 @@ * @memberof DisplayObject# */ x: { - get: function () { + get: function () + { return this.position.x; }, - set: function (value) { + set: function (value) + { this.position.x = value; } }, @@ -167,10 +170,12 @@ * @memberof DisplayObject# */ y: { - get: function () { + get: function () + { return this.position.y; }, - set: function (value) { + set: function (value) + { this.position.y = value; } }, @@ -183,11 +188,13 @@ * @readonly */ worldVisible: { - get: function () { + get: function () + { var item = this; do { - if (!item.visible) { + if (!item.visible) + { return false; } @@ -207,17 +214,21 @@ * @memberof DisplayObject# */ mask: { - get: function () { + get: function () + { return this._mask; }, - set: function (value) { - if (this._mask) { + set: function (value) + { + if (this._mask) + { this._mask.isMask = false; } this._mask = value; - if (this._mask) { + if (this._mask) + { this._mask.isMask = true; } } @@ -232,18 +243,23 @@ * @memberof DisplayObject# */ filters: { - get: function () { + get: function () + { return this._filters; }, - set: function (value) { - if (value) { + set: function (value) + { + if (value) + { // now put all the passes in one place.. var passes = []; - for (var i = 0; i < value.length; i++) { + for (var i = 0; i < value.length; i++) + { var filterPasses = value[i].passes; - for (var j = 0; j < filterPasses.length; j++) { + for (var j = 0; j < filterPasses.length; j++) + { passes.push(filterPasses[j]); } } @@ -264,8 +280,9 @@ * * @private */ -DisplayObject.prototype.updateTransform = function () { - +DisplayObject.prototype.updateTransform = function () +{ + // create some matrix refs for easy access var pt = this.parent.worldTransform; var wt = this.worldTransform; @@ -274,9 +291,11 @@ var a, b, c, d, tx, ty; // so if rotation is between 0 then we can simplify the multiplication process.. - if (this.rotation % math.PI_2) { + if (this.rotation % math.PI_2) + { // 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) { + if (this.rotation !== this.rotationCache) + { this.rotationCache = this.rotation; this._sr = Math.sin(this.rotation); this._cr = Math.cos(this.rotation); @@ -291,7 +310,8 @@ ty = this.position.y; // check for pivot.. not often used so geared towards that fact! - if (this.pivot.x || this.pivot.y) { + 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; } @@ -304,7 +324,8 @@ wt.tx = tx * pt.a + ty * pt.c + pt.tx; wt.ty = tx * pt.b + ty * pt.d + pt.ty; } - else { + else + { // lets do the fast version as we know there is no rotation.. a = this.scale.x; d = this.scale.y; @@ -333,7 +354,8 @@ * @param matrix {Matrix} * @return {Rectangle} the rectangular bounding area */ -DisplayObject.prototype.getBounds = function (/* matrix */) { +DisplayObject.prototype.getBounds = function (/* matrix */) +{ return math.Rectangle.EMPTY; }; @@ -342,7 +364,8 @@ * * @return {Rectangle} the rectangular bounding area */ -DisplayObject.prototype.getLocalBounds = function () { +DisplayObject.prototype.getLocalBounds = function () +{ return this.getBounds(math.Matrix.IDENTITY); }; @@ -352,7 +375,8 @@ * @param position {Point} The world origin to calculate from * @return {Point} A point object representing the position of this object */ -DisplayObject.prototype.toGlobal = function (position) { +DisplayObject.prototype.toGlobal = function (position) +{ // don't need to u[date the lot this.displayObjectUpdateTransform(); return this.worldTransform.apply(position); @@ -365,8 +389,10 @@ * @param [from] {DisplayObject} The DisplayObject to calculate the global position from * @return {Point} A point object representing the position of this object */ -DisplayObject.prototype.toLocal = function (position, from) { - if (from) { +DisplayObject.prototype.toLocal = function (position, from) +{ + if (from) + { position = from.toGlobal(position); } @@ -381,7 +407,8 @@ * @param renderer {WebGLRenderer} The renderer * @private */ -DisplayObject.prototype.renderWebGL = function (/* renderer */) { +DisplayObject.prototype.renderWebGL = function (/* renderer */) +{ // OVERWRITE; }; @@ -391,6 +418,7 @@ * @param renderer {CanvasRenderer} The renderer * @private */ -DisplayObject.prototype.renderCanvas = function (/* renderer */) { +DisplayObject.prototype.renderCanvas = function (/* renderer */) +{ // OVERWRITE; }; diff --git a/src/core/display/DisplayObjectContainer.js b/src/core/display/DisplayObjectContainer.js index 689f40b..4625ee8 100644 --- a/src/core/display/DisplayObjectContainer.js +++ b/src/core/display/DisplayObjectContainer.js @@ -12,7 +12,8 @@ * @extends DisplayObject * @namespace PIXI */ -function DisplayObjectContainer() { +function DisplayObjectContainer() +{ DisplayObject.call(this); /** @@ -47,17 +48,21 @@ * @memberof DisplayObjectContainer# */ width: { - get: function () { + get: function () + { return this.scale.x * this.getLocalBounds().width; }, - set: function (value) { + set: function (value) + { var width = this.getLocalBounds().width; - if(width !== 0) { + if(width !== 0) + { this.scale.x = value / width; } - else { + else + { this.scale.x = 1; } @@ -73,17 +78,21 @@ * @memberof DisplayObjectContainer# */ height: { - get: function () { + get: function () + { return this.scale.y * this.getLocalBounds().height; }, - set: function (value) { + set: function (value) + { var height = this.getLocalBounds().height; - if (height !== 0) { + if (height !== 0) + { this.scale.y = value / height ; } - else { + else + { this.scale.y = 1; } @@ -100,18 +109,23 @@ * @memberof DisplayObject# */ cacheAsBitmap: { - get: function () { + get: function () + { return this._cacheAsBitmap; }, - set: function (value) { - if (this._cacheAsBitmap === value) { + set: function (value) + { + if (this._cacheAsBitmap === value) + { return; } - if (value) { + if (value) + { this._generateCachedSprite(); } - else { + else + { this._destroyCachedSprite(); } @@ -126,7 +140,8 @@ * @param child {DisplayObject} The DisplayObject to add to the container * @return {DisplayObject} The child that was added. */ -DisplayObjectContainer.prototype.addChild = function (child) { +DisplayObjectContainer.prototype.addChild = function (child) +{ return this.addChildAt(child, this.children.length); }; @@ -137,14 +152,18 @@ * @param index {Number} The index to place the child in * @return {DisplayObject} The child that was added. */ -DisplayObjectContainer.prototype.addChildAt = function (child, index) { +DisplayObjectContainer.prototype.addChildAt = function (child, index) +{ // prevent adding self as child - if (child === this) { + if (child === this) + { return; } - if (index >= 0 && index <= this.children.length) { - if (child.parent) { + if (index >= 0 && index <= this.children.length) + { + if (child.parent) + { child.parent.removeChild(child); } @@ -154,7 +173,8 @@ return child; } - else { + else + { throw new Error(child + 'addChildAt: The index '+ index +' supplied is out of bounds ' + this.children.length); } }; @@ -165,15 +185,18 @@ * @param child {DisplayObject} * @param child2 {DisplayObject} */ -DisplayObjectContainer.prototype.swapChildren = function (child, child2) { - if (child === child2) { +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) { + if (index1 < 0 || index2 < 0) + { throw new Error('swapChildren: Both the supplied DisplayObjects must be a child of the caller.'); } @@ -187,10 +210,12 @@ * @param child {DisplayObject} The DisplayObject instance to identify * @return {Number} The index position of the child display object to identify */ -DisplayObjectContainer.prototype.getChildIndex = function (child) { +DisplayObjectContainer.prototype.getChildIndex = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { throw new Error('The supplied DisplayObject must be a child of the caller'); } @@ -203,8 +228,10 @@ * @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 */ -DisplayObjectContainer.prototype.setChildIndex = function (child, index) { - if (index < 0 || index >= this.children.length) { +DisplayObjectContainer.prototype.setChildIndex = function (child, index) +{ + if (index < 0 || index >= this.children.length) + { throw new Error('The supplied index is out of bounds'); } @@ -220,8 +247,10 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child at the given index, if any. */ -DisplayObjectContainer.prototype.getChildAt = function (index) { - if (index < 0 || index >= this.children.length) { +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'); } @@ -234,10 +263,12 @@ * @param child {DisplayObject} The DisplayObject to remove * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChild = function (child) { +DisplayObjectContainer.prototype.removeChild = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { return; } @@ -250,7 +281,8 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChildAt = function (index) { +DisplayObjectContainer.prototype.removeChildAt = function (index) +{ var child = this.getChildAt(index); child.parent = null; @@ -265,24 +297,29 @@ * @param beginIndex {Number} The beginning position. Default value is 0. * @param endIndex {Number} The ending position. Default value is size of the container. */ -DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) { +DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) +{ var begin = beginIndex || 0; var end = typeof endIndex === 'number' ? endIndex : this.children.length; var range = end - begin; - if (range > 0 && range <= end) { + if (range > 0 && range <= end) + { var removed = this.children.splice(begin, range); - for (var i = 0; i < removed.length; ++i) { + for (var i = 0; i < removed.length; ++i) + { removed[i].parent = null; } return removed; } - else if (range === 0 && this.children.length === 0) { + else if (range === 0 && this.children.length === 0) + { return []; } - else { + else + { throw new RangeError('removeChildren: numeric values are outside the acceptable range.'); } }; @@ -291,7 +328,8 @@ * Generates and updates the cached sprite for this object. * */ -DisplayObjectContainer.prototype.updateCachedSprite = function () { +DisplayObjectContainer.prototype.updateCachedSprite = function () +{ this._generateCachedSprite(); }; @@ -304,7 +342,8 @@ * @param renderer {CanvasRenderer|WebGLRenderer} The renderer used to generate the texture. * @return {Texture} a texture of the graphics object */ -DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) { +DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) +{ var bounds = this.getLocalBounds(); var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0, renderer, scaleMode, resolution); @@ -322,18 +361,22 @@ * * @private */ -DisplayObjectContainer.prototype.updateTransform = function () { - if (!this.visible) { +DisplayObjectContainer.prototype.updateTransform = function () +{ + if (!this.visible) + { return; } this.displayObjectUpdateTransform(); - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { return; } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } }; @@ -346,8 +389,10 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getBounds = function () { - if (this.children.length === 0) { +DisplayObjectContainer.prototype.getBounds = function () +{ + if (this.children.length === 0) + { return math.Rectangle.EMPTY; } @@ -365,10 +410,12 @@ var childVisible = false; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -386,7 +433,8 @@ maxY = maxY > childMaxY ? maxY : childMaxY; } - if (!childVisible) { + if (!childVisible) + { return math.Rectangle.EMPTY; } @@ -407,12 +455,14 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getLocalBounds = function () { +DisplayObjectContainer.prototype.getLocalBounds = function () +{ var matrixCache = this.worldTransform; this.worldTransform = math.Matrix.IDENTITY; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } @@ -428,13 +478,16 @@ * * @param renderer {WebGLRenderer} The renderer */ -DisplayObjectContainer.prototype.renderWebGL = function (renderer) { +DisplayObjectContainer.prototype.renderWebGL = function (renderer) +{ // if the object is not visible or the alpha is 0 then no need to render this element - if (!this.visible || this.alpha <= 0) { + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } @@ -442,14 +495,17 @@ var i, j; // do a quick check to see if this element has a mask or a filter. - if (this._mask || this._filters) { + if (this._mask || this._filters) + { // push filter first as we need to ensure the stencil buffer is correct for any masking - if (this._filters) { + if (this._filters) + { renderer.spriteBatch.flush(); renderer.filterManager.pushFilter(this._filterBlock); } - if (this._mask) { + if (this._mask) + { renderer.spriteBatch.stop(); renderer.maskManager.pushMask(this.mask, renderer); renderer.spriteBatch.start(); @@ -459,36 +515,42 @@ this._renderWebGL(renderer); // now loop through the children and make sure they get rendered - for (i = 0, j = this.children.length; i < j; i++) { + for (i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderWebGL(renderer); } // time to stop the sprite batch as either a mask element or a filter draw will happen next renderer.spriteBatch.stop(); - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(this._mask, renderer); } - if (this._filters) { + if (this._filters) + { renderer.filterManager.popFilter(); } renderer.spriteBatch.start(); } - else { + else + { this._renderWebGL(renderer); // simple render children! - for (i = 0, j = this.children.length; i < j; ++i) { + for (i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderWebGL(renderer); } } }; -DisplayObjectContainer.prototype._renderWebGL = function (renderer) { +DisplayObjectContainer.prototype._renderWebGL = function (renderer) +{ // this is where content itself gets renderd.. @@ -499,25 +561,31 @@ * * @param renderer {CanvasRenderer} The renderer */ -DisplayObjectContainer.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0) { +DisplayObjectContainer.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -528,13 +596,16 @@ * @param renderer {WebGLRenderer|CanvasRenderer} The renderer * @private */ -DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) { +DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) +{ this._cachedSprite.worldAlpha = this.worldAlpha; - if (renderer.gl) { + if (renderer.gl) + { this._cachedSprite.renderWebGL(renderer); } - else { + else + { this._cachedSprite.renderCanvas(renderer); } }; @@ -544,10 +615,12 @@ * * @private */ -DisplayObjectContainer.prototype._generateCachedSprite = function () { +DisplayObjectContainer.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { // TODO - RenderTexture now *requires* a renderer instance, so this is like broken // because `renderer` isn't actually in scope here :P var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0); @@ -555,7 +628,8 @@ this._cachedSprite = new Sprite(renderTexture); this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.texture.resize(bounds.width | 0, bounds.height | 0); } @@ -580,8 +654,10 @@ * * @private */ -DisplayObjectContainer.prototype._destroyCachedSprite = function () { - if (!this._cachedSprite) { +DisplayObjectContainer.prototype._destroyCachedSprite = function () +{ + if (!this._cachedSprite) + { return; } diff --git a/src/core/display/Sprite.js b/src/core/display/Sprite.js index 707da24..5862aef 100644 --- a/src/core/display/Sprite.js +++ b/src/core/display/Sprite.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param texture {Texture} The texture for this sprite */ -function Sprite(texture) { +function Sprite(texture) +{ DisplayObjectContainer.call(this); /** @@ -85,12 +86,14 @@ this.texture = texture || Texture.EMPTY; } -Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) { +Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) +{ DisplayObjectContainer.prototype.destroy.call(this); this.anchor = null; - if (destroyTexture) { + if (destroyTexture) + { this._texture.destroy(destroyBaseTexture); } @@ -111,10 +114,12 @@ * @memberof Sprite# */ width: { - get: function () { + get: function () + { return this.scale.x * this.texture.frame.width; }, - set: function (value) { + set: function (value) + { this.scale.x = value / this.texture.frame.width; this._width = value; } @@ -127,10 +132,12 @@ * @memberof Sprite# */ height: { - get: function () { + get: function () + { return this.scale.y * this.texture.frame.height; }, - set: function (value) { + set: function (value) + { this.scale.y = value / this.texture.frame.height; this._height = value; } @@ -143,23 +150,29 @@ * @memberof Sprite# */ texture: { - get: function () { + get: function () + { return this._texture; }, - set: function (value) { - if (this._texture === value) { + set: function (value) + { + if (this._texture === value) + { return; } this._texture = value; this.cachedTint = 0xFFFFFF; - if (value) { + if (value) + { // wait for the texture to load - if (value.baseTexture.hasLoaded) { + if (value.baseTexture.hasLoaded) + { this._onTextureUpdate(); } - else { + else + { value.once('update', this._onTextureUpdate.bind(this)); } } @@ -172,18 +185,22 @@ * * @private */ -Sprite.prototype._onTextureUpdate = function () { +Sprite.prototype._onTextureUpdate = function () +{ // so if _width is 0 then width was not set.. - if (this._width) { + if (this._width) + { this.scale.x = this._width / this.texture.frame.width; } - if (this._height) { + if (this._height) + { this.scale.y = this._height / this.texture.frame.height; } }; -Sprite.prototype._renderWebGL = function (renderer) { +Sprite.prototype._renderWebGL = function (renderer) +{ // this is where content gets renderd.. // watch this space for a little render state manager.. @@ -197,7 +214,8 @@ * @param matrix {Matrix} the transformation matrix of the sprite * @return {Rectangle} the framing rectangle */ -Sprite.prototype.getBounds = function (matrix) { +Sprite.prototype.getBounds = function (matrix) +{ var width = this.texture.frame.width; var height = this.texture.frame.height; @@ -224,11 +242,13 @@ if(b === 0 && c === 0) { // scale may be negative! - if (a < 0) { + if (a < 0) + { a *= -1; } - if (d < 0) { + if (d < 0) + { d *= -1; } @@ -293,28 +313,34 @@ * * @param renderer {CanvasRenderer} The renderer */ -Sprite.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) { +Sprite.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) + { return; } - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; renderer.context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } // Ignore null sources - if (this.texture.valid) { + if (this.texture.valid) + { var resolution = this.texture.baseTexture.resolution / renderer.resolution; renderer.context.globalAlpha = this.worldAlpha; // If smoothingEnabled is supported and we need to change the smoothing property for this texture - if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) { + if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) + { renderer.scaleMode = this.texture.baseTexture.scaleMode; renderer.context[renderer.smoothProperty] = (renderer.scaleMode === CONST.scaleModes.LINEAR); } @@ -324,7 +350,8 @@ var dy = (this.texture.trim ? this.texture.trim.y : 0) - (this.anchor.y * this.texture.trim.height); // Allow for pixel rounding - if (renderer.roundPixels) { + if (renderer.roundPixels) + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -337,7 +364,8 @@ dx = dx | 0; dy = dy | 0; } - else { + else + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -348,8 +376,10 @@ ); } - if (this.tint !== 0xFFFFFF) { - if (this.cachedTint !== this.tint) { + if (this.tint !== 0xFFFFFF) + { + if (this.cachedTint !== this.tint) + { this.cachedTint = this.tint; // TODO clean up caching - how to clean up the caches? @@ -368,7 +398,8 @@ this.texture.crop.height / resolution ); } - else { + else + { renderer.context.drawImage( this.texture.baseTexture.source, this.texture.crop.x, @@ -383,11 +414,13 @@ } } - for (var i = 0, j = this.children.length; i < j; i++) { + for (var i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -402,10 +435,12 @@ * @param frameId {String} The frame Id of the texture in the cache * @return {Sprite} A new Sprite using a texture from the texture cache matching the frameId */ -Sprite.fromFrame = function (frameId) { +Sprite.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache' + this); } @@ -420,6 +455,7 @@ * @param imageId {String} The image url of the texture * @return {Sprite} A new Sprite using a texture from the texture cache matching the image id */ -Sprite.fromImage = function (imageId, crossorigin, scaleMode) { +Sprite.fromImage = function (imageId, crossorigin, scaleMode) +{ return new Sprite(Texture.fromImage(imageId, crossorigin, scaleMode)); }; diff --git a/src/core/display/SpriteBatch.js b/src/core/display/SpriteBatch.js index 3187777..c196fef 100644 --- a/src/core/display/SpriteBatch.js +++ b/src/core/display/SpriteBatch.js @@ -12,7 +12,8 @@ * ```js * var container = new SpriteBatch(); * - * for(var i = 0; i < 100; ++i) { + * for(var i = 0; i < 100; ++i) + * { * var sprite = new PIXI.Sprite.fromImage("myImage.png"); * container.addChild(sprite); * } @@ -25,7 +26,8 @@ */ //TODO RENAME to PARTICLE CONTAINER? -function SpriteBatch() { +function SpriteBatch() +{ DisplayObjectContainer.call(this); } @@ -38,7 +40,8 @@ * * @private */ -SpriteBatch.prototype.updateTransform = function () { +SpriteBatch.prototype.updateTransform = function () +{ // TODO don't need to! this.displayObjectUpdateTransform(); // PIXI.DisplayObjectContainer.prototype.updateTransform.call( this ); @@ -50,8 +53,10 @@ * @param renderer {WebGLRenderer} The webgl renderer * @private */ -SpriteBatch.prototype.renderWebGL = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderWebGL = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -71,8 +76,10 @@ * @param renderer {CanvasRenderer} The canvas renderer * @private */ -SpriteBatch.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -84,10 +91,12 @@ this.displayObjectUpdateTransform(); - for (var i = 0; i < this.children.length; ++i) { + for (var i = 0; i < this.children.length; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -95,9 +104,11 @@ context.globalAlpha = this.worldAlpha * child.alpha; - if (child.rotation % (Math.PI * 2) === 0) { + if (child.rotation % (Math.PI * 2) === 0) + { // this is the fastest way to optimise! - if rotation is 0 then we can avoid any kind of setTransform call - if (isRotated) { + if (isRotated) + { context.setTransform( transform.a, transform.b, @@ -122,8 +133,10 @@ frame.height * child.scale.y ); } - else { - if (!isRotated) { + else + { + if (!isRotated) + { isRotated = true; } @@ -131,7 +144,8 @@ var childTransform = child.worldTransform; - if (renderer.roundPixels) { + if (renderer.roundPixels) + { context.setTransform( childTransform.a, childTransform.b, @@ -141,7 +155,8 @@ childTransform.ty | 0 ); } - else { + else + { context.setTransform( childTransform.a, childTransform.b, diff --git a/src/core/index.js b/src/core/index.js index 3954b6f..eb4a82b 100644 --- a/src/core/index.js +++ b/src/core/index.js @@ -58,11 +58,13 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRenderer: function (width, height, options, noWebGL) { + autoDetectRenderer: function (width, height, options, noWebGL) + { width = width || 800; height = height || 600; - if (!noWebGL && require('webgl-enabled')()) { + if (!noWebGL && require('webgl-enabled')()) + { return new core.WebGLRenderer(width, height, options); } @@ -87,7 +89,8 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRecommendedRenderer: function (width, height, options) { + autoDetectRecommendedRenderer: function (width, height, options) + { var isAndroid = /Android/i.test(navigator.userAgent); return core.autoDetectRenderer(width, height, options, isAndroid); diff --git a/src/core/math/Matrix.js b/src/core/math/Matrix.js index c2f87e2..2ff4848 100644 --- a/src/core/math/Matrix.js +++ b/src/core/math/Matrix.js @@ -10,7 +10,8 @@ * @class * @namespace PIXI */ -function Matrix() { +function Matrix() +{ /** * @member {number} * @default 1 @@ -63,7 +64,8 @@ * * @param array {number[]} The array that the matrix will be populated from. */ -Matrix.prototype.fromArray = function (array) { +Matrix.prototype.fromArray = function (array) +{ this.a = array[0]; this.b = array[1]; this.c = array[3]; @@ -78,14 +80,17 @@ * @param transpose {boolean} Whether we need to transpose the matrix or not * @return {number[]} the newly created array which contains the matrix */ -Matrix.prototype.toArray = function (transpose) { - if (!this.array) { +Matrix.prototype.toArray = function (transpose) +{ + if (!this.array) + { this.array = new Float32Array(9); } var array = this.array; - if (transpose) { + if (transpose) + { array[0] = this.a; array[1] = this.b; array[2] = 0; @@ -96,7 +101,8 @@ array[7] = this.ty; array[8] = 1; } - else { + else + { array[0] = this.a; array[1] = this.c; array[2] = this.tx; @@ -119,7 +125,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, transformed through this matrix */ -Matrix.prototype.apply = function (pos, newPos) { +Matrix.prototype.apply = function (pos, newPos) +{ newPos = newPos || new Point(); newPos.x = this.a * pos.x + this.c * pos.y + this.tx; @@ -136,7 +143,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, inverse-transformed through this matrix */ -Matrix.prototype.applyInverse = function (pos, newPos) { +Matrix.prototype.applyInverse = function (pos, newPos) +{ newPos = newPos || new Point(); var id = 1 / (this.a * this.d + this.c * -this.b); @@ -154,7 +162,8 @@ * @param {number} y * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.translate = function (x, y) { +Matrix.prototype.translate = function (x, y) +{ this.tx += x; this.ty += y; @@ -168,7 +177,8 @@ * @param {number} y The amount to scale vertically * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.scale = function (x, y) { +Matrix.prototype.scale = function (x, y) +{ this.a *= x; this.d *= y; this.c *= x; @@ -186,7 +196,8 @@ * @param {number} angle - The angle in radians. * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.rotate = function (angle) { +Matrix.prototype.rotate = function (angle) +{ var cos = Math.cos( angle ); var sin = Math.sin( angle ); @@ -210,7 +221,8 @@ * @param {Matrix} matrix * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.append = function (matrix) { +Matrix.prototype.append = function (matrix) +{ var a1 = this.a; var b1 = this.b; var c1 = this.c; @@ -232,7 +244,8 @@ * * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.identity = function () { +Matrix.prototype.identity = function () +{ this.a = 1; this.b = 0; this.c = 0; diff --git a/src/core/math/Point.js b/src/core/math/Point.js index 7565b2d..632f346 100644 --- a/src/core/math/Point.js +++ b/src/core/math/Point.js @@ -7,7 +7,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -function Point(x, y) { +function Point(x, y) +{ /** * @member {number} * @default 0 @@ -29,7 +30,8 @@ * * @return {Point} a copy of the point */ -Point.prototype.clone = function () { +Point.prototype.clone = function () +{ return new Point(this.x, this.y); }; @@ -40,7 +42,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -Point.prototype.set = function (x, y) { +Point.prototype.set = function (x, y) +{ this.x = x || 0; this.y = y || ( (y !== 0) ? this.x : 0 ) ; }; diff --git a/src/core/math/shapes/Circle.js b/src/core/math/shapes/Circle.js index 69cfdc9..4d76efc 100644 --- a/src/core/math/shapes/Circle.js +++ b/src/core/math/shapes/Circle.js @@ -10,7 +10,8 @@ * @param y {number} The Y coordinate of the center of this circle * @param radius {number} The radius of the circle */ -function Circle(x, y, radius) { +function Circle(x, y, radius) +{ /** * @member {number} * @default 0 @@ -46,7 +47,8 @@ * @method clone * @return {Circle} a copy of the Circle */ -Circle.prototype.clone = function () { +Circle.prototype.clone = function () +{ return new Circle(this.x, this.y, this.radius); }; @@ -58,8 +60,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Circle */ -Circle.prototype.contains = function (x, y) { - if (this.radius <= 0) { +Circle.prototype.contains = function (x, y) +{ + if (this.radius <= 0) + { return false; } @@ -79,6 +83,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Circle.prototype.getBounds = function () { +Circle.prototype.getBounds = function () +{ return new Rectangle(this.x - this.radius, this.y - this.radius, this.radius * 2, this.radius * 2); }; diff --git a/src/core/math/shapes/Ellipse.js b/src/core/math/shapes/Ellipse.js index 4f2d066..fefd01a 100644 --- a/src/core/math/shapes/Ellipse.js +++ b/src/core/math/shapes/Ellipse.js @@ -11,7 +11,8 @@ * @param width {number} The half width of this ellipse * @param height {number} The half height of this ellipse */ -function Ellipse(x, y, width, height) { +function Ellipse(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -53,7 +54,8 @@ * @method clone * @return {Ellipse} a copy of the ellipse */ -Ellipse.prototype.clone = function () { +Ellipse.prototype.clone = function () +{ return new Ellipse(this.x, this.y, this.width, this.height); }; @@ -65,8 +67,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coords are within this ellipse */ -Ellipse.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Ellipse.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } @@ -86,6 +90,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Ellipse.prototype.getBounds = function () { +Ellipse.prototype.getBounds = function () +{ return new Rectangle(this.x - this.width, this.y - this.height, this.width, this.height); }; diff --git a/src/core/math/shapes/Polygon.js b/src/core/math/shapes/Polygon.js index ae89148..fea6d37 100644 --- a/src/core/math/shapes/Polygon.js +++ b/src/core/math/shapes/Polygon.js @@ -10,16 +10,20 @@ * arguments passed can be flat x,y values e.g. `new Polygon(x,y, x,y, x,y, ...)` where `x` and `y` are * Numbers. */ -function Polygon(points) { +function Polygon(points) +{ //if points isn't an array, use arguments as the array - if (!(points instanceof Array)) { + if (!(points instanceof Array)) + { points = Array.prototype.slice.call(arguments); } //if this is a flat array of numbers, convert it to points - if (points[0] instanceof Point) { + if (points[0] instanceof Point) + { var p = []; - for (var i = 0, il = points.length; i < il; i++) { + for (var i = 0, il = points.length; i < il; i++) + { p.push(points[i].x, points[i].y); } @@ -51,7 +55,8 @@ * * @return {Polygon} a copy of the polygon */ -Polygon.prototype.clone = function () { +Polygon.prototype.clone = function () +{ return new Polygon(this.points.slice()); }; @@ -62,19 +67,22 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this polygon */ -Polygon.prototype.contains = function (x, y) { +Polygon.prototype.contains = function (x, y) +{ var inside = false; // use some raycasting to test hits // https://github.com/substack/point-in-polygon/blob/master/index.js var length = this.points.length / 2; - for (var i = 0, j = length - 1; i < length; j = i++) { + for (var i = 0, j = length - 1; i < length; j = i++) + { var xi = this.points[i * 2], yi = this.points[i * 2 + 1], xj = this.points[j * 2], yj = this.points[j * 2 + 1], intersect = ((yi > y) !== (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi); - if (intersect) { + if (intersect) + { inside = !inside; } } diff --git a/src/core/math/shapes/Rectangle.js b/src/core/math/shapes/Rectangle.js index 16ac62a..4008b68 100644 --- a/src/core/math/shapes/Rectangle.js +++ b/src/core/math/shapes/Rectangle.js @@ -10,7 +10,8 @@ * @param width {number} The overall width of this rectangle * @param height {number} The overall height of this rectangle */ -function Rectangle(x, y, width, height) { +function Rectangle(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -60,7 +61,8 @@ * * @return {Rectangle} a copy of the rectangle */ -Rectangle.prototype.clone = function () { +Rectangle.prototype.clone = function () +{ return new Rectangle(this.x, this.y, this.width, this.height); }; @@ -71,13 +73,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rectangle */ -Rectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Rectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/math/shapes/RoundedRectangle.js b/src/core/math/shapes/RoundedRectangle.js index 27d286e..7bf6411 100644 --- a/src/core/math/shapes/RoundedRectangle.js +++ b/src/core/math/shapes/RoundedRectangle.js @@ -11,7 +11,8 @@ * @param height {number} The overall height of this rounded rectangle * @param radius {number} Controls the radius of the rounded corners */ -function RoundedRectangle(x, y, width, height, radius) { +function RoundedRectangle(x, y, width, height, radius) +{ /** * @member {number} * @default 0 @@ -58,7 +59,8 @@ * * @return {RoundedRectangle} a copy of the rounded rectangle */ -RoundedRectangle.prototype.clone = function () { +RoundedRectangle.prototype.clone = function () +{ return new RoundedRectangle(this.x, this.y, this.width, this.height, this.radius); }; @@ -69,13 +71,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rounded Rectangle */ -RoundedRectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +RoundedRectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/primitives/Graphics.js b/src/core/primitives/Graphics.js index 261c534..e902d2a 100644 --- a/src/core/primitives/Graphics.js +++ b/src/core/primitives/Graphics.js @@ -16,7 +16,8 @@ * @extends DisplayObjectContainer * @namespace PIXI */ -function Graphics() { +function Graphics() +{ DisplayObjectContainer.call(this); this.renderable = true; @@ -154,16 +155,20 @@ * @private */ cacheAsBitmap: { - get: function () { + get: function () + { return this._cacheAsBitmap; }, - set: function (value) { + set: function (value) + { this._cacheAsBitmap = value; - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._generateCachedSprite(); } - else { + else + { this.destroyCachedSprite(); this.dirty = true; } @@ -176,7 +181,8 @@ * * @return {Graphics} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ var clone = new Graphics(); clone.renderable = this.renderable; @@ -192,7 +198,8 @@ clone.cachedSpriteDirty = this.cachedSpriteDirty; // copy graphics data - for (var i = 0; i < this.graphicsData.length; ++i) { + for (var i = 0; i < this.graphicsData.length; ++i) + { clone.graphicsData.push(this.graphicsData.clone()); } @@ -211,17 +218,21 @@ * @param alpha {number} alpha of the line to draw, will update the objects stored style * @return {Graphics} */ -Graphics.prototype.lineStyle = function (lineWidth, color, alpha) { +Graphics.prototype.lineStyle = function (lineWidth, color, alpha) +{ this.lineWidth = lineWidth || 0; this.lineColor = color || 0; this.lineAlpha = (arguments.length < 3) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length) + { // halfway through a line? start a new one! this.drawShape( new math.Polygon( this.currentPath.shape.points.slice(-2) )); } - else { + else + { // otherwise its empty so lets just set the line properties this.currentPath.lineWidth = this.lineWidth; this.currentPath.lineColor = this.lineColor; @@ -239,7 +250,8 @@ * @param y {number} the Y coordinate to move to * @return {Graphics} */ -Graphics.prototype.moveTo = function (x, y) { +Graphics.prototype.moveTo = function (x, y) +{ this.drawShape(new math.Polygon([x,y])); return this; @@ -253,7 +265,8 @@ * @param y {number} the Y coordinate to draw to * @return {Graphics} */ -Graphics.prototype.lineTo = function (x, y) { +Graphics.prototype.lineTo = function (x, y) +{ this.currentPath.shape.points.push(x, y); this.dirty = true; @@ -270,13 +283,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -285,7 +302,8 @@ n = 20, points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { this.moveTo(0, 0); } @@ -293,7 +311,8 @@ var fromY = points[points.length-1]; var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; xa = fromX + ( (cpX - fromX) * j ); @@ -319,13 +338,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -342,7 +365,8 @@ var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; dt = (1 - j); @@ -373,13 +397,17 @@ * @param radius {number} The radius of the arc * @return {Graphics} */ -Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points.push(x1, y1); } } - else { + else + { this.moveTo(x1, y1); } @@ -392,12 +420,15 @@ b2 = x2 - x1, mm = Math.abs(a1 * b2 - b1 * a2); - if (mm < 1.0e-8 || radius === 0) { - if (points[points.length-2] !== x1 || points[points.length-1] !== y1) { + if (mm < 1.0e-8 || radius === 0) + { + if (points[points.length-2] !== x1 || points[points.length-1] !== y1) + { points.push(x1, y1); } } - else { + else + { var dd = a1 * a1 + b1 * b1, cc = a2 * a2 + b2 * b2, tt = a1 * a2 + b1 * b2, @@ -433,42 +464,51 @@ * @param anticlockwise {boolean} Optional. Specifies whether the drawing should be counterclockwise or clockwise. False is default, and indicates clockwise, while true indicates counter-clockwise. * @return {Graphics} */ -Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) { +Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) +{ var startX = cx + Math.cos(startAngle) * radius; var startY = cy + Math.sin(startAngle) * radius; var points; // TODO - This if-else makes no sense. It uses currentPath in the else where it doesn't exist... - if (this.currentPath) { + if (this.currentPath) + { points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { points.push(startX, startY); } - else if (points[points.length-2] !== startX || points[points.length-1] !== startY) { + else if (points[points.length-2] !== startX || points[points.length-1] !== startY) + { points.push(startX, startY); } } - else { + else + { this.moveTo(startX, startY); points = this.currentPath.shape.points; } - if (startAngle === endAngle) { + if (startAngle === endAngle) + { return this; } - if (!anticlockwise && endAngle <= startAngle) { + if (!anticlockwise && endAngle <= startAngle) + { endAngle += Math.PI * 2; } - else if (anticlockwise && startAngle <= endAngle) { + else if (anticlockwise && startAngle <= endAngle) + { startAngle += Math.PI * 2; } var sweep = anticlockwise ? (startAngle - endAngle) *-1 : (endAngle - startAngle); var segs = (Math.abs(sweep)/ (Math.PI * 2)) * 40; - if (sweep === 0) { + if (sweep === 0) + { return this; } @@ -482,7 +522,8 @@ var remainder = ( segMinus % 1 ) / segMinus; - for (var i = 0; i <= segMinus; ++i) { + for (var i = 0; i <= segMinus; ++i) + { var real = i + remainder * i; var angle = ((theta) + startAngle + (theta2 * real)); @@ -506,13 +547,16 @@ * @param alpha {number} the alpha of the fill * @return {Graphics} */ -Graphics.prototype.beginFill = function (color, alpha) { +Graphics.prototype.beginFill = function (color, alpha) +{ this.filling = true; this.fillColor = color || 0; this.fillAlpha = (alpha === undefined) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length <= 2) + { this.currentPath.fill = this.filling; this.currentPath.fillColor = this.fillColor; this.currentPath.fillAlpha = this.fillAlpha; @@ -526,7 +570,8 @@ * * @return {Graphics} */ -Graphics.prototype.endFill = function () { +Graphics.prototype.endFill = function () +{ this.filling = false; this.fillColor = null; this.fillAlpha = 1; @@ -542,7 +587,8 @@ * @param height {number} The height of the rectangle * @return {Graphics} */ -Graphics.prototype.drawRect = function ( x, y, width, height ) { +Graphics.prototype.drawRect = function ( x, y, width, height ) +{ this.drawShape(new math.Rectangle(x,y, width, height)); return this; @@ -556,7 +602,8 @@ * @param height {number} The height of the rectangle * @param radius {number} Radius of the rectangle corners */ -Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) { +Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) +{ this.drawShape(new math.RoundedRectangle(x, y, width, height, radius)); return this; @@ -570,7 +617,8 @@ * @param radius {number} The radius of the circle * @return {Graphics} */ -Graphics.prototype.drawCircle = function (x, y, radius) { +Graphics.prototype.drawCircle = function (x, y, radius) +{ this.drawShape(new math.Circle(x,y, radius)); return this; @@ -585,7 +633,8 @@ * @param height {number} The half height of the ellipse * @return {Graphics} */ -Graphics.prototype.drawEllipse = function (x, y, width, height) { +Graphics.prototype.drawEllipse = function (x, y, width, height) +{ this.drawShape(new math.Ellipse(x, y, width, height)); return this; @@ -597,8 +646,10 @@ * @param path {Array} The path data used to construct the polygon. * @return {Graphics} */ -Graphics.prototype.drawPolygon = function (path) { - if (!(path instanceof Array)) { +Graphics.prototype.drawPolygon = function (path) +{ + if (!(path instanceof Array)) + { path = Array.prototype.slice.call(arguments); } @@ -612,7 +663,8 @@ * * @return {Graphics} */ -Graphics.prototype.clear = function () { +Graphics.prototype.clear = function () +{ this.lineWidth = 0; this.filling = false; @@ -631,7 +683,8 @@ * @param scaleMode {number} Should be one of the scaleMode consts * @return {Texture} a texture of the graphics object */ -Graphics.prototype.generateTexture = function (resolution, scaleMode) { +Graphics.prototype.generateTexture = function (resolution, scaleMode) +{ resolution = resolution || 1; var bounds = this.getBounds(); @@ -655,17 +708,21 @@ * * @param renderer {WebGLRenderer} */ -Graphics.prototype._renderWebGL = function (renderer) { +Graphics.prototype._renderWebGL = function (renderer) +{ // if the sprite is not visible or the alpha is 0 then no need to render this element - if (this.isMask === true) { + if (this.isMask === true) + { return; } // this code may still be needed so leaving for now.. - // + // /* - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture on the gpu too! @@ -681,17 +738,24 @@ return; } - */ - - // check if the webgl graphic needs to be updated - if (this.glDirty) { - this.dirty = true; - this.glDirty = false; - } + else */ - renderer.setObjectRendererer(renderer.graphicsRenderer); - renderer.graphicsRenderer.render(this); + renderer.spriteBatch.stop(); + renderer.blendModeManager.setBlendMode(this.blendMode); + // check blend mode + renderer.blendModeManager.setBlendMode( this.blendMode ); + + // check if the webgl graphic needs to be updated + if (this.glDirty) + { + this.dirty = true; + this.glDirty = false; + } + + WebGLGraphics.renderGraphics(this, renderer); + + renderer.spriteBatch.start(); }; /** @@ -700,14 +764,18 @@ * @param renderer {CanvasRenderer} * @private */ -Graphics.prototype.renderCanvas = function (renderer) { +Graphics.prototype.renderCanvas = function (renderer) +{ // 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.isMask === true) { + if (!this.visible || this.alpha <= 0 || this.isMask === true) + { return; } - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture @@ -723,16 +791,19 @@ return; } - else { + else + { var context = renderer.context; var transform = this.worldTransform; - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } @@ -748,11 +819,13 @@ CanvasGraphics.renderGraphics(this, context); - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } } @@ -763,13 +836,16 @@ * * @return {Rectangle} the rectangular bounding area */ -Graphics.prototype.getBounds = function (matrix) { +Graphics.prototype.getBounds = function (matrix) +{ // return an empty object if the item is a mask! - if (this.isMask) { + if (this.isMask) + { return math.Rectangle.EMPTY; } - if (this.dirty) { + if (this.dirty) + { this.updateLocalBounds(); this.glDirty = true; @@ -841,23 +917,27 @@ * Update the bounds of the object * */ -Graphics.prototype.updateLocalBounds = function () { +Graphics.prototype.updateLocalBounds = function () +{ var minX = Infinity; var maxX = -Infinity; var minY = Infinity; var maxY = -Infinity; - if (this.graphicsData.length) { + if (this.graphicsData.length) + { var shape, points, x, y, w, h; - for (var i = 0; i < this.graphicsData.length; i++) { + for (var i = 0; i < this.graphicsData.length; i++) + { var data = this.graphicsData[i]; var type = data.type; var lineWidth = data.lineWidth; shape = data.shape; - if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) { + if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) + { x = shape.x - lineWidth/2; y = shape.y - lineWidth/2; w = shape.width + lineWidth; @@ -869,7 +949,8 @@ minY = y < minY ? y : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.CIRC) { + else if (type === CONST.SHAPES.CIRC) + { x = shape.x; y = shape.y; w = shape.radius + lineWidth/2; @@ -881,7 +962,8 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.ELIP) { + else if (type === CONST.SHAPES.ELIP) + { x = shape.x; y = shape.y; w = shape.width + lineWidth/2; @@ -893,11 +975,13 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else { + else + { // POLY points = shape.points; - for (var j = 0; j < points.length; j += 2) { + for (var j = 0; j < points.length; j += 2) + { x = points[j]; y = points[j+1]; @@ -910,7 +994,8 @@ } } } - else { + else + { minX = 0; maxX = 0; minY = 0; @@ -931,10 +1016,12 @@ * * @private */ -Graphics.prototype._generateCachedSprite = function () { +Graphics.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { var canvasBuffer = new CanvasBuffer(bounds.width, bounds.height); var texture = Texture.fromCanvas(canvasBuffer.canvas); @@ -943,7 +1030,8 @@ this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.buffer.resize(bounds.width, bounds.height); } @@ -968,7 +1056,8 @@ * * @private */ -Graphics.prototype.updateCachedSpriteTexture = function () { +Graphics.prototype.updateCachedSpriteTexture = function () +{ var cachedSprite = this._cachedSprite; var texture = cachedSprite.texture; var canvas = cachedSprite.buffer.canvas; @@ -989,7 +1078,8 @@ * Destroys a previous cached sprite. * */ -Graphics.prototype.destroyCachedSprite = function () { +Graphics.prototype.destroyCachedSprite = function () +{ this._cachedSprite.texture.destroy(true); // let the gc collect the unused sprite @@ -1003,10 +1093,13 @@ * @param {Circle|Rectangle|Ellipse|Line|Polygon} shape The Shape object to draw. * @return {GraphicsData} The generated GraphicsData object. */ -Graphics.prototype.drawShape = function (shape) { - if (this.currentPath) { +Graphics.prototype.drawShape = function (shape) +{ + if (this.currentPath) + { // check current path! - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath.shape.points.length <= 2) + { this.graphicsData.pop(); } } @@ -1017,7 +1110,8 @@ this.graphicsData.push(data); - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { data.shape.closed = this.filling; this.currentPath = data; } diff --git a/src/core/primitives/GraphicsData.js b/src/core/primitives/GraphicsData.js index 99decbe..788f6f2 100644 --- a/src/core/primitives/GraphicsData.js +++ b/src/core/primitives/GraphicsData.js @@ -4,7 +4,8 @@ * @class * @namespace PIXI */ -function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) { +function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) +{ this.lineWidth = lineWidth; this.lineColor = lineColor; this.lineAlpha = lineAlpha; @@ -27,7 +28,8 @@ * * @return {GraphicsData} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ return new GraphicsData( this.lineWidth, this.lineColor, diff --git a/src/core/renderers/canvas/CanvasRenderer.js b/src/core/renderers/canvas/CanvasRenderer.js index 15a0978..7aebd44 100644 --- a/src/core/renderers/canvas/CanvasRenderer.js +++ b/src/core/renderers/canvas/CanvasRenderer.js @@ -17,17 +17,22 @@ * @param [options.resolution=1] {number} the resolution of the renderer retina would be 2 * @param [options.clearBeforeRender=true] {boolean} This sets if the CanvasRenderer will clear the canvas or not before the new render pass. */ -function CanvasRenderer(width, height, options) { +function CanvasRenderer(width, height, options) +{ utils.sayHello('Canvas'); - if (options) { - for (var i in CONST.defaultRenderOptions) { - if (typeof options[i] === 'undefined') { + if (options) + { + for (var i in CONST.defaultRenderOptions) + { + if (typeof options[i] === 'undefined') + { options[i] = CONST.defaultRenderOptions[i]; } } } - else { + else + { options = CONST.defaultRenderOptions; } @@ -156,19 +161,24 @@ this.smoothProperty = null; - if (this.context.imageSmoothingEnabled) { + if (this.context.imageSmoothingEnabled) + { this.smoothProperty = 'imageSmoothingEnabled'; } - else if (this.context.webkitImageSmoothingEnabled) { + else if (this.context.webkitImageSmoothingEnabled) + { this.smoothProperty = 'webkitImageSmoothingEnabled'; } - else if (this.context.mozImageSmoothingEnabled) { + else if (this.context.mozImageSmoothingEnabled) + { this.smoothProperty = 'mozImageSmoothingEnabled'; } - else if (this.context.oImageSmoothingEnabled) { + else if (this.context.oImageSmoothingEnabled) + { this.smoothProperty = 'oImageSmoothingEnabled'; } - else if (this.context.msImageSmoothingEnabled) { + else if (this.context.msImageSmoothingEnabled) + { this.smoothProperty = 'msImageSmoothingEnabled'; } @@ -193,10 +203,12 @@ * @memberof CanvasRenderer# */ backgroundColor: { - get: function () { + get: function () + { return this._backgroundColor; }, - set: function (val) { + set: function (val) + { this._backgroundColor = val; this._backgroundColorString = utils.hex2string(val); } @@ -208,7 +220,8 @@ * * @param object {DisplayObject} the object to be rendered */ -CanvasRenderer.prototype.render = function (object) { +CanvasRenderer.prototype.render = function (object) +{ object.updateTransform(); this.context.setTransform(1,0,0,1,0,0); @@ -218,16 +231,20 @@ this.currentBlendMode = CONST.blendModes.NORMAL; this.context.globalCompositeOperation = this.blendModes[CONST.blendModes.NORMAL]; - if (navigator.isCocoonJS && this.view.screencanvas) { + if (navigator.isCocoonJS && this.view.screencanvas) + { this.context.fillStyle = 'black'; this.context.clear(); } - if (this.clearBeforeRender) { - if (this.transparent) { + if (this.clearBeforeRender) + { + if (this.transparent) + { this.context.clearRect(0, 0, this.width, this.height); } - else { + else + { this.context.fillStyle = this._backgroundColorString; this.context.fillRect(0, 0, this.width , this.height); } @@ -241,8 +258,10 @@ * * @param [removeView=false] {boolean} Removes the Canvas element from the DOM. */ -CanvasRenderer.prototype.destroy = function (removeView) { - if (removeView && this.view.parent) { +CanvasRenderer.prototype.destroy = function (removeView) +{ + if (removeView && this.view.parent) + { this.view.parent.removeChild(this.view); } @@ -257,14 +276,16 @@ * @param width {number} the new width of the canvas view * @param height {number} the new height of the canvas view */ -CanvasRenderer.prototype.resize = function (width, height) { +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) { + if (this.autoResize) + { this.view.style.width = this.width / this.resolution + 'px'; this.view.style.height = this.height / this.resolution + 'px'; } @@ -276,7 +297,8 @@ * @param displayObject {DisplayObject} The displayObject to render * @private */ -CanvasRenderer.prototype.renderDisplayObject = function (displayObject) { +CanvasRenderer.prototype.renderDisplayObject = function (displayObject) +{ displayObject.renderCanvas(this); }; @@ -285,11 +307,14 @@ * * @private */ -CanvasRenderer.prototype._mapBlendModes = function () { - if (!this.blendModes) { +CanvasRenderer.prototype._mapBlendModes = function () +{ + if (!this.blendModes) + { this.blendModes = {}; - if (utils.canUseNewCanvasBlendModes()) { + if (utils.canUseNewCanvasBlendModes()) + { this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? this.blendModes[CONST.blendModes.MULTIPLY] = 'multiply'; @@ -308,7 +333,8 @@ this.blendModes[CONST.blendModes.COLOR] = 'color'; this.blendModes[CONST.blendModes.LUMINOSITY] = 'luminosity'; } - else { + else + { // this means that the browser does not support the cool new blend modes in canvas 'cough' ie 'cough' this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? diff --git a/src/core/renderers/canvas/utils/CanvasBuffer.js b/src/core/renderers/canvas/utils/CanvasBuffer.js index ebe5d47..b183a66 100644 --- a/src/core/renderers/canvas/utils/CanvasBuffer.js +++ b/src/core/renderers/canvas/utils/CanvasBuffer.js @@ -6,7 +6,8 @@ * @param width {number} the width for the newly created canvas * @param height {number} the height for the newly created canvas */ -function CanvasBuffer(width, height) { +function CanvasBuffer(width, height) +{ /** * The Canvas object that belongs to this CanvasBuffer. * @@ -36,10 +37,12 @@ * @memberof CanvasBuffer# */ width: { - get: function () { + get: function () + { return this.canvas.width; }, - set: function (val) { + set: function (val) + { this.canvas.width = val; } }, @@ -50,10 +53,12 @@ * @memberof CanvasBuffer# */ height: { - get: function () { + get: function () + { return this.canvas.height; }, - set: function (val) { + set: function (val) + { this.canvas.height = val; } } @@ -64,7 +69,8 @@ * * @private */ -CanvasBuffer.prototype.clear = function () { +CanvasBuffer.prototype.clear = function () +{ this.context.setTransform(1, 0, 0, 1, 0, 0); this.context.clearRect(0,0, this.canvas.width, this.canvas.height); }; @@ -75,7 +81,8 @@ * @param width {number} the new width of the canvas * @param height {number} the new height of the canvas */ -CanvasBuffer.prototype.resize = function (width, height) { +CanvasBuffer.prototype.resize = function (width, height) +{ this.canvas.width = width; this.canvas.height = height; }; diff --git a/src/core/renderers/canvas/utils/CanvasGraphics.js b/src/core/renderers/canvas/utils/CanvasGraphics.js index c7eaa2a..3f2a91f 100644 --- a/src/core/renderers/canvas/utils/CanvasGraphics.js +++ b/src/core/renderers/canvas/utils/CanvasGraphics.js @@ -13,15 +13,18 @@ * @param graphics {Graphics} the actual graphics object to render * @param context {CanvasRenderingContext2D} the 2d drawing method of the canvas */ -CanvasGraphics.renderGraphics = function (graphics, context) { +CanvasGraphics.renderGraphics = function (graphics, context) +{ var worldAlpha = graphics.worldAlpha; - if (graphics.dirty) { + if (graphics.dirty) + { this.updateGraphicsTint(graphics); graphics.dirty = false; } - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; @@ -30,69 +33,82 @@ context.lineWidth = data.lineWidth; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { context.beginPath(); var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } - if (shape.closed) { + if (shape.closed) + { context.lineTo(points[0], points[1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fillRect(shape.x, shape.y, shape.width, shape.height); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.strokeRect(shape.x, shape.y, shape.width, shape.height); } } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.beginPath(); context.arc(shape.x, shape.y, shape.radius,0,2*Math.PI); context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas var w = shape.width * 2; @@ -119,18 +135,21 @@ context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; var width = shape.width; @@ -152,13 +171,15 @@ context.quadraticCurveTo(rx, ry, rx, ry + radius); context.closePath(); - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); @@ -174,45 +195,54 @@ * @param graphics {Graphics} the graphics which will be used as a mask * @param context {CanvasRenderingContext2D} the context 2d method of the canvas */ -CanvasGraphics.renderGraphicsMask = function (graphics, context) { +CanvasGraphics.renderGraphicsMask = function (graphics, context) +{ var len = graphics.graphicsData.length; - if (len === 0) { + if (len === 0) + { return; } context.beginPath(); - for (var i = 0; i < len; i++) { + for (var i = 0; i < len; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { context.rect(shape.x, shape.y, shape.width, shape.height); context.closePath(); } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.arc(shape.x, shape.y, shape.radius, 0, 2 * Math.PI); context.closePath(); } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas @@ -237,7 +267,8 @@ context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); context.closePath(); } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; @@ -262,8 +293,10 @@ } }; -CanvasGraphics.updateGraphicsTint = function (graphics) { - if (graphics.tint === 0xFFFFFF) { +CanvasGraphics.updateGraphicsTint = function (graphics) +{ + if (graphics.tint === 0xFFFFFF) + { return; } @@ -271,7 +304,8 @@ var tintG = (graphics.tint >> 8 & 0xFF) / 255; var tintB = (graphics.tint & 0xFF)/ 255; - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var fillColor = data.fillColor | 0; diff --git a/src/core/renderers/canvas/utils/CanvasMaskManager.js b/src/core/renderers/canvas/utils/CanvasMaskManager.js index e04a733..9827d36 100644 --- a/src/core/renderers/canvas/utils/CanvasMaskManager.js +++ b/src/core/renderers/canvas/utils/CanvasMaskManager.js @@ -6,7 +6,8 @@ * @class * @namespace PIXI */ -function CanvasMaskManager() {} +function CanvasMaskManager() +{} CanvasMaskManager.prototype.constructor = CanvasMaskManager; module.exports = CanvasMaskManager; @@ -17,7 +18,8 @@ * @param maskData {object} the maskData that will be pushed * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.pushMask = function (maskData, renderer) { +CanvasMaskManager.prototype.pushMask = function (maskData, renderer) +{ renderer.context.save(); var cacheAlpha = maskData.alpha; @@ -45,6 +47,7 @@ * * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.popMask = function (renderer) { +CanvasMaskManager.prototype.popMask = function (renderer) +{ renderer.context.restore(); }; diff --git a/src/core/renderers/canvas/utils/CanvasTinter.js b/src/core/renderers/canvas/utils/CanvasTinter.js index 17e0529..d2fb1bc 100644 --- a/src/core/renderers/canvas/utils/CanvasTinter.js +++ b/src/core/renderers/canvas/utils/CanvasTinter.js @@ -14,7 +14,8 @@ * @param color {number} the color to use to tint the sprite with * @return {HTMLCanvasElement} The tinted canvas */ -CanvasTinter.getTintedTexture = function (sprite, color) { +CanvasTinter.getTintedTexture = function (sprite, color) +{ var texture = sprite.texture; color = CanvasTinter.roundColor(color); @@ -23,7 +24,8 @@ texture.tintCache = texture.tintCache || {}; - if (texture.tintCache[stringColor]) { + if (texture.tintCache[stringColor]) + { return texture.tintCache[stringColor]; } @@ -33,14 +35,16 @@ //CanvasTinter.tintWithPerPixel(texture, stringColor, canvas); CanvasTinter.tintMethod(texture, color, canvas); - if (CanvasTinter.convertTintToImage) { + if (CanvasTinter.convertTintToImage) + { // is this better? var tintImage = new Image(); tintImage.src = canvas.toDataURL(); texture.tintCache[stringColor] = tintImage; } - else { + else + { texture.tintCache[stringColor] = canvas; // if we are not converting the texture to an image then we need to lose the reference to the canvas CanvasTinter.canvas = null; @@ -56,7 +60,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithMultiply = function (texture, color, canvas) { +CanvasTinter.tintWithMultiply = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -104,7 +109,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithOverlay = function (texture, color, canvas) { +CanvasTinter.tintWithOverlay = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -139,7 +145,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithPerPixel = function (texture, color, canvas) { +CanvasTinter.tintWithPerPixel = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -167,7 +174,8 @@ var pixels = pixelData.data; - for (var i = 0; i < pixels.length; i += 4) { + for (var i = 0; i < pixels.length; i += 4) + { pixels[i+0] *= r; pixels[i+1] *= g; pixels[i+2] *= b; @@ -181,7 +189,8 @@ * * @param color {number} the color to round, should be a hex color */ -CanvasTinter.roundColor = function (color) { +CanvasTinter.roundColor = function (color) +{ var step = CanvasTinter.cacheStepsPerColorChannel; var rgbValues = utils.hex2rgb(color); diff --git a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js index 9f2f89a..35edbaf 100644 --- a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js +++ b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLBlendModeManager(renderer) { +function WebGLBlendModeManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -23,8 +24,10 @@ * * @param blendMode {number} the blendMode, should be a Pixi const, such as BlendModes.ADD */ -WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) { - if (this.currentBlendMode === blendMode) { +WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) +{ + if (this.currentBlendMode === blendMode) + { return false; } diff --git a/src/core/renderers/webgl/managers/WebGLFilterManager.js b/src/core/renderers/webgl/managers/WebGLFilterManager.js index 1179258..2dac048 100644 --- a/src/core/renderers/webgl/managers/WebGLFilterManager.js +++ b/src/core/renderers/webgl/managers/WebGLFilterManager.js @@ -7,7 +7,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLFilterManager(renderer) { +function WebGLFilterManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -32,7 +33,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.texturePool.length = 0; self.initShaderBuffers(); }); @@ -46,7 +48,8 @@ * @param renderer {WebGLRenderer} * @param buffer {ArrayBuffer} */ -WebGLFilterManager.prototype.begin = function (buffer) { +WebGLFilterManager.prototype.begin = function (buffer) +{ this.defaultShader = this.renderer.shaderManager.defaultShader; this.width = this.renderer.projection.x * 2; @@ -60,7 +63,8 @@ * * @param filterBlock {object} the filter that will be pushed to the current filter stack */ -WebGLFilterManager.prototype.pushFilter = function (filterBlock) { +WebGLFilterManager.prototype.pushFilter = function (filterBlock) +{ var gl = this.renderer.gl; var projection = this.renderer.projection; @@ -78,10 +82,12 @@ this.offsetY += filterBlock._filterArea.y; var texture = this.texturePool.pop(); - if (!texture) { + if (!texture) + { texture = new FilterTexture(this.renderer.gl, this.width, this.height); } - else { + else + { texture.resize(this.width, this.height); } @@ -98,29 +104,35 @@ var localX = filterArea.x, localY = filterArea.y; - if (filterArea.x < 0) { + if (filterArea.x < 0) + { filterArea.width += filterArea.x; filterArea.x = 0; } - if (filterArea.y < 0) { + if (filterArea.y < 0) + { filterArea.height += filterArea.y; filterArea.y = 0; } - if (localX + filterArea.width > this.width) { + if (localX + filterArea.width > this.width) + { filterArea.width = this.width - localX; } - if (localY + filterArea.height > this.height) { + if (localY + filterArea.height > this.height) + { filterArea.height = this.height - localY; } - if (filterArea.width < 0) { + if (filterArea.width < 0) + { filterArea.width = 0; } - if (filterArea.height < 0) { + if (filterArea.height < 0) + { filterArea.height = 0; } @@ -154,7 +166,8 @@ * Removes the last filter from the filter stack and doesn't return it. * */ -WebGLFilterManager.prototype.popFilter = function () { +WebGLFilterManager.prototype.popFilter = function () +{ var gl = this.renderer.gl; var filterBlock = this.filterStack.pop(); @@ -163,7 +176,8 @@ var projection = this.renderer.projection; var offset = this.renderer.offset; - if (filterBlock.filterPasses.length > 1) { + if (filterBlock.filterPasses.length > 1) + { gl.viewport(0, 0, filterArea.width, filterArea.height); gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); @@ -193,7 +207,8 @@ var inputTexture = texture; var outputTexture = this.texturePool.pop(); - if (!outputTexture) { + if (!outputTexture) + { outputTexture = new FilterTexture(this.renderer.gl, this.width, this.height); } outputTexture.resize(this.width, this.height); @@ -204,7 +219,8 @@ gl.disable(gl.BLEND); - for (var i = 0; i < filterBlock.filterPasses.length-1; i++) { + for (var i = 0; i < filterBlock.filterPasses.length-1; i++) + { var filterPass = filterBlock.filterPasses[i]; gl.bindFramebuffer(gl.FRAMEBUFFER, outputTexture.frameBuffer ); @@ -243,10 +259,12 @@ var buffer = this.buffer; // time to render the filters texture to the previous scene - if (this.filterStack.length === 0) { + if (this.filterStack.length === 0) + { gl.colorMask(true, true, true, true);//this.transparent); } - else { + else + { var currentFilter = this.filterStack[this.filterStack.length-1]; filterArea = currentFilter._filterArea; @@ -332,13 +350,15 @@ * @param width {number} the horizontal range of the filter * @param height {number} the vertical range of the filter */ -WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) { +WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) +{ // use program var gl = this.renderer.gl; var shader = filter.shaders[gl.id]; - if (!shader) { + if (!shader) + { shader = new Shader(gl); shader.fragmentSrc = filter.fragmentSrc; @@ -356,7 +376,8 @@ gl.uniform2f(shader.projectionVector, width/2, -height/2); gl.uniform2f(shader.offsetVector, 0,0); - if (filter.uniforms.dimensions) { + 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]; @@ -386,7 +407,8 @@ * Initialises the shader buffers. * */ -WebGLFilterManager.prototype.initShaderBuffers = function () { +WebGLFilterManager.prototype.initShaderBuffers = function () +{ var gl = this.renderer.gl; // create some buffers @@ -432,7 +454,8 @@ * Destroys the filter and removes it from the filter stack. * */ -WebGLFilterManager.prototype.destroy = function () { +WebGLFilterManager.prototype.destroy = function () +{ var gl = this.renderer.gl; this.filterStack = null; @@ -441,7 +464,8 @@ this.offsetY = 0; // destroy textures - for (var i = 0; i < this.texturePool.length; i++) { + for (var i = 0; i < this.texturePool.length; i++) + { this.texturePool[i].destroy(); } diff --git a/src/core/renderers/webgl/managers/WebGLManager.js b/src/core/renderers/webgl/managers/WebGLManager.js index 9d47b5c..c30cd51 100644 --- a/src/core/renderers/webgl/managers/WebGLManager.js +++ b/src/core/renderers/webgl/managers/WebGLManager.js @@ -3,7 +3,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLManager(renderer) { +function WebGLManager(renderer) +{ /** * The renderer this manager works for. * @@ -15,6 +16,7 @@ WebGLManager.prototype.constructor = WebGLManager; module.exports = WebGLManager; -WebGLManager.prototype.destroy = function () { +WebGLManager.prototype.destroy = function () +{ this.renderer = null; }; diff --git a/src/core/display/DisplayObject.js b/src/core/display/DisplayObject.js index 66ebc3c..20e778c 100644 --- a/src/core/display/DisplayObject.js +++ b/src/core/display/DisplayObject.js @@ -7,7 +7,8 @@ * @class * @namespace PIXI */ -function DisplayObject() { +function DisplayObject() +{ /** * The coordinate of the object relative to the local coordinates of the parent. * @@ -152,10 +153,12 @@ * @memberof DisplayObject# */ x: { - get: function () { + get: function () + { return this.position.x; }, - set: function (value) { + set: function (value) + { this.position.x = value; } }, @@ -167,10 +170,12 @@ * @memberof DisplayObject# */ y: { - get: function () { + get: function () + { return this.position.y; }, - set: function (value) { + set: function (value) + { this.position.y = value; } }, @@ -183,11 +188,13 @@ * @readonly */ worldVisible: { - get: function () { + get: function () + { var item = this; do { - if (!item.visible) { + if (!item.visible) + { return false; } @@ -207,17 +214,21 @@ * @memberof DisplayObject# */ mask: { - get: function () { + get: function () + { return this._mask; }, - set: function (value) { - if (this._mask) { + set: function (value) + { + if (this._mask) + { this._mask.isMask = false; } this._mask = value; - if (this._mask) { + if (this._mask) + { this._mask.isMask = true; } } @@ -232,18 +243,23 @@ * @memberof DisplayObject# */ filters: { - get: function () { + get: function () + { return this._filters; }, - set: function (value) { - if (value) { + set: function (value) + { + if (value) + { // now put all the passes in one place.. var passes = []; - for (var i = 0; i < value.length; i++) { + for (var i = 0; i < value.length; i++) + { var filterPasses = value[i].passes; - for (var j = 0; j < filterPasses.length; j++) { + for (var j = 0; j < filterPasses.length; j++) + { passes.push(filterPasses[j]); } } @@ -264,8 +280,9 @@ * * @private */ -DisplayObject.prototype.updateTransform = function () { - +DisplayObject.prototype.updateTransform = function () +{ + // create some matrix refs for easy access var pt = this.parent.worldTransform; var wt = this.worldTransform; @@ -274,9 +291,11 @@ var a, b, c, d, tx, ty; // so if rotation is between 0 then we can simplify the multiplication process.. - if (this.rotation % math.PI_2) { + if (this.rotation % math.PI_2) + { // 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) { + if (this.rotation !== this.rotationCache) + { this.rotationCache = this.rotation; this._sr = Math.sin(this.rotation); this._cr = Math.cos(this.rotation); @@ -291,7 +310,8 @@ ty = this.position.y; // check for pivot.. not often used so geared towards that fact! - if (this.pivot.x || this.pivot.y) { + 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; } @@ -304,7 +324,8 @@ wt.tx = tx * pt.a + ty * pt.c + pt.tx; wt.ty = tx * pt.b + ty * pt.d + pt.ty; } - else { + else + { // lets do the fast version as we know there is no rotation.. a = this.scale.x; d = this.scale.y; @@ -333,7 +354,8 @@ * @param matrix {Matrix} * @return {Rectangle} the rectangular bounding area */ -DisplayObject.prototype.getBounds = function (/* matrix */) { +DisplayObject.prototype.getBounds = function (/* matrix */) +{ return math.Rectangle.EMPTY; }; @@ -342,7 +364,8 @@ * * @return {Rectangle} the rectangular bounding area */ -DisplayObject.prototype.getLocalBounds = function () { +DisplayObject.prototype.getLocalBounds = function () +{ return this.getBounds(math.Matrix.IDENTITY); }; @@ -352,7 +375,8 @@ * @param position {Point} The world origin to calculate from * @return {Point} A point object representing the position of this object */ -DisplayObject.prototype.toGlobal = function (position) { +DisplayObject.prototype.toGlobal = function (position) +{ // don't need to u[date the lot this.displayObjectUpdateTransform(); return this.worldTransform.apply(position); @@ -365,8 +389,10 @@ * @param [from] {DisplayObject} The DisplayObject to calculate the global position from * @return {Point} A point object representing the position of this object */ -DisplayObject.prototype.toLocal = function (position, from) { - if (from) { +DisplayObject.prototype.toLocal = function (position, from) +{ + if (from) + { position = from.toGlobal(position); } @@ -381,7 +407,8 @@ * @param renderer {WebGLRenderer} The renderer * @private */ -DisplayObject.prototype.renderWebGL = function (/* renderer */) { +DisplayObject.prototype.renderWebGL = function (/* renderer */) +{ // OVERWRITE; }; @@ -391,6 +418,7 @@ * @param renderer {CanvasRenderer} The renderer * @private */ -DisplayObject.prototype.renderCanvas = function (/* renderer */) { +DisplayObject.prototype.renderCanvas = function (/* renderer */) +{ // OVERWRITE; }; diff --git a/src/core/display/DisplayObjectContainer.js b/src/core/display/DisplayObjectContainer.js index 689f40b..4625ee8 100644 --- a/src/core/display/DisplayObjectContainer.js +++ b/src/core/display/DisplayObjectContainer.js @@ -12,7 +12,8 @@ * @extends DisplayObject * @namespace PIXI */ -function DisplayObjectContainer() { +function DisplayObjectContainer() +{ DisplayObject.call(this); /** @@ -47,17 +48,21 @@ * @memberof DisplayObjectContainer# */ width: { - get: function () { + get: function () + { return this.scale.x * this.getLocalBounds().width; }, - set: function (value) { + set: function (value) + { var width = this.getLocalBounds().width; - if(width !== 0) { + if(width !== 0) + { this.scale.x = value / width; } - else { + else + { this.scale.x = 1; } @@ -73,17 +78,21 @@ * @memberof DisplayObjectContainer# */ height: { - get: function () { + get: function () + { return this.scale.y * this.getLocalBounds().height; }, - set: function (value) { + set: function (value) + { var height = this.getLocalBounds().height; - if (height !== 0) { + if (height !== 0) + { this.scale.y = value / height ; } - else { + else + { this.scale.y = 1; } @@ -100,18 +109,23 @@ * @memberof DisplayObject# */ cacheAsBitmap: { - get: function () { + get: function () + { return this._cacheAsBitmap; }, - set: function (value) { - if (this._cacheAsBitmap === value) { + set: function (value) + { + if (this._cacheAsBitmap === value) + { return; } - if (value) { + if (value) + { this._generateCachedSprite(); } - else { + else + { this._destroyCachedSprite(); } @@ -126,7 +140,8 @@ * @param child {DisplayObject} The DisplayObject to add to the container * @return {DisplayObject} The child that was added. */ -DisplayObjectContainer.prototype.addChild = function (child) { +DisplayObjectContainer.prototype.addChild = function (child) +{ return this.addChildAt(child, this.children.length); }; @@ -137,14 +152,18 @@ * @param index {Number} The index to place the child in * @return {DisplayObject} The child that was added. */ -DisplayObjectContainer.prototype.addChildAt = function (child, index) { +DisplayObjectContainer.prototype.addChildAt = function (child, index) +{ // prevent adding self as child - if (child === this) { + if (child === this) + { return; } - if (index >= 0 && index <= this.children.length) { - if (child.parent) { + if (index >= 0 && index <= this.children.length) + { + if (child.parent) + { child.parent.removeChild(child); } @@ -154,7 +173,8 @@ return child; } - else { + else + { throw new Error(child + 'addChildAt: The index '+ index +' supplied is out of bounds ' + this.children.length); } }; @@ -165,15 +185,18 @@ * @param child {DisplayObject} * @param child2 {DisplayObject} */ -DisplayObjectContainer.prototype.swapChildren = function (child, child2) { - if (child === child2) { +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) { + if (index1 < 0 || index2 < 0) + { throw new Error('swapChildren: Both the supplied DisplayObjects must be a child of the caller.'); } @@ -187,10 +210,12 @@ * @param child {DisplayObject} The DisplayObject instance to identify * @return {Number} The index position of the child display object to identify */ -DisplayObjectContainer.prototype.getChildIndex = function (child) { +DisplayObjectContainer.prototype.getChildIndex = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { throw new Error('The supplied DisplayObject must be a child of the caller'); } @@ -203,8 +228,10 @@ * @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 */ -DisplayObjectContainer.prototype.setChildIndex = function (child, index) { - if (index < 0 || index >= this.children.length) { +DisplayObjectContainer.prototype.setChildIndex = function (child, index) +{ + if (index < 0 || index >= this.children.length) + { throw new Error('The supplied index is out of bounds'); } @@ -220,8 +247,10 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child at the given index, if any. */ -DisplayObjectContainer.prototype.getChildAt = function (index) { - if (index < 0 || index >= this.children.length) { +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'); } @@ -234,10 +263,12 @@ * @param child {DisplayObject} The DisplayObject to remove * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChild = function (child) { +DisplayObjectContainer.prototype.removeChild = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { return; } @@ -250,7 +281,8 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChildAt = function (index) { +DisplayObjectContainer.prototype.removeChildAt = function (index) +{ var child = this.getChildAt(index); child.parent = null; @@ -265,24 +297,29 @@ * @param beginIndex {Number} The beginning position. Default value is 0. * @param endIndex {Number} The ending position. Default value is size of the container. */ -DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) { +DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) +{ var begin = beginIndex || 0; var end = typeof endIndex === 'number' ? endIndex : this.children.length; var range = end - begin; - if (range > 0 && range <= end) { + if (range > 0 && range <= end) + { var removed = this.children.splice(begin, range); - for (var i = 0; i < removed.length; ++i) { + for (var i = 0; i < removed.length; ++i) + { removed[i].parent = null; } return removed; } - else if (range === 0 && this.children.length === 0) { + else if (range === 0 && this.children.length === 0) + { return []; } - else { + else + { throw new RangeError('removeChildren: numeric values are outside the acceptable range.'); } }; @@ -291,7 +328,8 @@ * Generates and updates the cached sprite for this object. * */ -DisplayObjectContainer.prototype.updateCachedSprite = function () { +DisplayObjectContainer.prototype.updateCachedSprite = function () +{ this._generateCachedSprite(); }; @@ -304,7 +342,8 @@ * @param renderer {CanvasRenderer|WebGLRenderer} The renderer used to generate the texture. * @return {Texture} a texture of the graphics object */ -DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) { +DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) +{ var bounds = this.getLocalBounds(); var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0, renderer, scaleMode, resolution); @@ -322,18 +361,22 @@ * * @private */ -DisplayObjectContainer.prototype.updateTransform = function () { - if (!this.visible) { +DisplayObjectContainer.prototype.updateTransform = function () +{ + if (!this.visible) + { return; } this.displayObjectUpdateTransform(); - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { return; } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } }; @@ -346,8 +389,10 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getBounds = function () { - if (this.children.length === 0) { +DisplayObjectContainer.prototype.getBounds = function () +{ + if (this.children.length === 0) + { return math.Rectangle.EMPTY; } @@ -365,10 +410,12 @@ var childVisible = false; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -386,7 +433,8 @@ maxY = maxY > childMaxY ? maxY : childMaxY; } - if (!childVisible) { + if (!childVisible) + { return math.Rectangle.EMPTY; } @@ -407,12 +455,14 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getLocalBounds = function () { +DisplayObjectContainer.prototype.getLocalBounds = function () +{ var matrixCache = this.worldTransform; this.worldTransform = math.Matrix.IDENTITY; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } @@ -428,13 +478,16 @@ * * @param renderer {WebGLRenderer} The renderer */ -DisplayObjectContainer.prototype.renderWebGL = function (renderer) { +DisplayObjectContainer.prototype.renderWebGL = function (renderer) +{ // if the object is not visible or the alpha is 0 then no need to render this element - if (!this.visible || this.alpha <= 0) { + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } @@ -442,14 +495,17 @@ var i, j; // do a quick check to see if this element has a mask or a filter. - if (this._mask || this._filters) { + if (this._mask || this._filters) + { // push filter first as we need to ensure the stencil buffer is correct for any masking - if (this._filters) { + if (this._filters) + { renderer.spriteBatch.flush(); renderer.filterManager.pushFilter(this._filterBlock); } - if (this._mask) { + if (this._mask) + { renderer.spriteBatch.stop(); renderer.maskManager.pushMask(this.mask, renderer); renderer.spriteBatch.start(); @@ -459,36 +515,42 @@ this._renderWebGL(renderer); // now loop through the children and make sure they get rendered - for (i = 0, j = this.children.length; i < j; i++) { + for (i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderWebGL(renderer); } // time to stop the sprite batch as either a mask element or a filter draw will happen next renderer.spriteBatch.stop(); - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(this._mask, renderer); } - if (this._filters) { + if (this._filters) + { renderer.filterManager.popFilter(); } renderer.spriteBatch.start(); } - else { + else + { this._renderWebGL(renderer); // simple render children! - for (i = 0, j = this.children.length; i < j; ++i) { + for (i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderWebGL(renderer); } } }; -DisplayObjectContainer.prototype._renderWebGL = function (renderer) { +DisplayObjectContainer.prototype._renderWebGL = function (renderer) +{ // this is where content itself gets renderd.. @@ -499,25 +561,31 @@ * * @param renderer {CanvasRenderer} The renderer */ -DisplayObjectContainer.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0) { +DisplayObjectContainer.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -528,13 +596,16 @@ * @param renderer {WebGLRenderer|CanvasRenderer} The renderer * @private */ -DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) { +DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) +{ this._cachedSprite.worldAlpha = this.worldAlpha; - if (renderer.gl) { + if (renderer.gl) + { this._cachedSprite.renderWebGL(renderer); } - else { + else + { this._cachedSprite.renderCanvas(renderer); } }; @@ -544,10 +615,12 @@ * * @private */ -DisplayObjectContainer.prototype._generateCachedSprite = function () { +DisplayObjectContainer.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { // TODO - RenderTexture now *requires* a renderer instance, so this is like broken // because `renderer` isn't actually in scope here :P var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0); @@ -555,7 +628,8 @@ this._cachedSprite = new Sprite(renderTexture); this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.texture.resize(bounds.width | 0, bounds.height | 0); } @@ -580,8 +654,10 @@ * * @private */ -DisplayObjectContainer.prototype._destroyCachedSprite = function () { - if (!this._cachedSprite) { +DisplayObjectContainer.prototype._destroyCachedSprite = function () +{ + if (!this._cachedSprite) + { return; } diff --git a/src/core/display/Sprite.js b/src/core/display/Sprite.js index 707da24..5862aef 100644 --- a/src/core/display/Sprite.js +++ b/src/core/display/Sprite.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param texture {Texture} The texture for this sprite */ -function Sprite(texture) { +function Sprite(texture) +{ DisplayObjectContainer.call(this); /** @@ -85,12 +86,14 @@ this.texture = texture || Texture.EMPTY; } -Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) { +Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) +{ DisplayObjectContainer.prototype.destroy.call(this); this.anchor = null; - if (destroyTexture) { + if (destroyTexture) + { this._texture.destroy(destroyBaseTexture); } @@ -111,10 +114,12 @@ * @memberof Sprite# */ width: { - get: function () { + get: function () + { return this.scale.x * this.texture.frame.width; }, - set: function (value) { + set: function (value) + { this.scale.x = value / this.texture.frame.width; this._width = value; } @@ -127,10 +132,12 @@ * @memberof Sprite# */ height: { - get: function () { + get: function () + { return this.scale.y * this.texture.frame.height; }, - set: function (value) { + set: function (value) + { this.scale.y = value / this.texture.frame.height; this._height = value; } @@ -143,23 +150,29 @@ * @memberof Sprite# */ texture: { - get: function () { + get: function () + { return this._texture; }, - set: function (value) { - if (this._texture === value) { + set: function (value) + { + if (this._texture === value) + { return; } this._texture = value; this.cachedTint = 0xFFFFFF; - if (value) { + if (value) + { // wait for the texture to load - if (value.baseTexture.hasLoaded) { + if (value.baseTexture.hasLoaded) + { this._onTextureUpdate(); } - else { + else + { value.once('update', this._onTextureUpdate.bind(this)); } } @@ -172,18 +185,22 @@ * * @private */ -Sprite.prototype._onTextureUpdate = function () { +Sprite.prototype._onTextureUpdate = function () +{ // so if _width is 0 then width was not set.. - if (this._width) { + if (this._width) + { this.scale.x = this._width / this.texture.frame.width; } - if (this._height) { + if (this._height) + { this.scale.y = this._height / this.texture.frame.height; } }; -Sprite.prototype._renderWebGL = function (renderer) { +Sprite.prototype._renderWebGL = function (renderer) +{ // this is where content gets renderd.. // watch this space for a little render state manager.. @@ -197,7 +214,8 @@ * @param matrix {Matrix} the transformation matrix of the sprite * @return {Rectangle} the framing rectangle */ -Sprite.prototype.getBounds = function (matrix) { +Sprite.prototype.getBounds = function (matrix) +{ var width = this.texture.frame.width; var height = this.texture.frame.height; @@ -224,11 +242,13 @@ if(b === 0 && c === 0) { // scale may be negative! - if (a < 0) { + if (a < 0) + { a *= -1; } - if (d < 0) { + if (d < 0) + { d *= -1; } @@ -293,28 +313,34 @@ * * @param renderer {CanvasRenderer} The renderer */ -Sprite.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) { +Sprite.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) + { return; } - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; renderer.context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } // Ignore null sources - if (this.texture.valid) { + if (this.texture.valid) + { var resolution = this.texture.baseTexture.resolution / renderer.resolution; renderer.context.globalAlpha = this.worldAlpha; // If smoothingEnabled is supported and we need to change the smoothing property for this texture - if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) { + if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) + { renderer.scaleMode = this.texture.baseTexture.scaleMode; renderer.context[renderer.smoothProperty] = (renderer.scaleMode === CONST.scaleModes.LINEAR); } @@ -324,7 +350,8 @@ var dy = (this.texture.trim ? this.texture.trim.y : 0) - (this.anchor.y * this.texture.trim.height); // Allow for pixel rounding - if (renderer.roundPixels) { + if (renderer.roundPixels) + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -337,7 +364,8 @@ dx = dx | 0; dy = dy | 0; } - else { + else + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -348,8 +376,10 @@ ); } - if (this.tint !== 0xFFFFFF) { - if (this.cachedTint !== this.tint) { + if (this.tint !== 0xFFFFFF) + { + if (this.cachedTint !== this.tint) + { this.cachedTint = this.tint; // TODO clean up caching - how to clean up the caches? @@ -368,7 +398,8 @@ this.texture.crop.height / resolution ); } - else { + else + { renderer.context.drawImage( this.texture.baseTexture.source, this.texture.crop.x, @@ -383,11 +414,13 @@ } } - for (var i = 0, j = this.children.length; i < j; i++) { + for (var i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -402,10 +435,12 @@ * @param frameId {String} The frame Id of the texture in the cache * @return {Sprite} A new Sprite using a texture from the texture cache matching the frameId */ -Sprite.fromFrame = function (frameId) { +Sprite.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache' + this); } @@ -420,6 +455,7 @@ * @param imageId {String} The image url of the texture * @return {Sprite} A new Sprite using a texture from the texture cache matching the image id */ -Sprite.fromImage = function (imageId, crossorigin, scaleMode) { +Sprite.fromImage = function (imageId, crossorigin, scaleMode) +{ return new Sprite(Texture.fromImage(imageId, crossorigin, scaleMode)); }; diff --git a/src/core/display/SpriteBatch.js b/src/core/display/SpriteBatch.js index 3187777..c196fef 100644 --- a/src/core/display/SpriteBatch.js +++ b/src/core/display/SpriteBatch.js @@ -12,7 +12,8 @@ * ```js * var container = new SpriteBatch(); * - * for(var i = 0; i < 100; ++i) { + * for(var i = 0; i < 100; ++i) + * { * var sprite = new PIXI.Sprite.fromImage("myImage.png"); * container.addChild(sprite); * } @@ -25,7 +26,8 @@ */ //TODO RENAME to PARTICLE CONTAINER? -function SpriteBatch() { +function SpriteBatch() +{ DisplayObjectContainer.call(this); } @@ -38,7 +40,8 @@ * * @private */ -SpriteBatch.prototype.updateTransform = function () { +SpriteBatch.prototype.updateTransform = function () +{ // TODO don't need to! this.displayObjectUpdateTransform(); // PIXI.DisplayObjectContainer.prototype.updateTransform.call( this ); @@ -50,8 +53,10 @@ * @param renderer {WebGLRenderer} The webgl renderer * @private */ -SpriteBatch.prototype.renderWebGL = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderWebGL = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -71,8 +76,10 @@ * @param renderer {CanvasRenderer} The canvas renderer * @private */ -SpriteBatch.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -84,10 +91,12 @@ this.displayObjectUpdateTransform(); - for (var i = 0; i < this.children.length; ++i) { + for (var i = 0; i < this.children.length; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -95,9 +104,11 @@ context.globalAlpha = this.worldAlpha * child.alpha; - if (child.rotation % (Math.PI * 2) === 0) { + if (child.rotation % (Math.PI * 2) === 0) + { // this is the fastest way to optimise! - if rotation is 0 then we can avoid any kind of setTransform call - if (isRotated) { + if (isRotated) + { context.setTransform( transform.a, transform.b, @@ -122,8 +133,10 @@ frame.height * child.scale.y ); } - else { - if (!isRotated) { + else + { + if (!isRotated) + { isRotated = true; } @@ -131,7 +144,8 @@ var childTransform = child.worldTransform; - if (renderer.roundPixels) { + if (renderer.roundPixels) + { context.setTransform( childTransform.a, childTransform.b, @@ -141,7 +155,8 @@ childTransform.ty | 0 ); } - else { + else + { context.setTransform( childTransform.a, childTransform.b, diff --git a/src/core/index.js b/src/core/index.js index 3954b6f..eb4a82b 100644 --- a/src/core/index.js +++ b/src/core/index.js @@ -58,11 +58,13 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRenderer: function (width, height, options, noWebGL) { + autoDetectRenderer: function (width, height, options, noWebGL) + { width = width || 800; height = height || 600; - if (!noWebGL && require('webgl-enabled')()) { + if (!noWebGL && require('webgl-enabled')()) + { return new core.WebGLRenderer(width, height, options); } @@ -87,7 +89,8 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRecommendedRenderer: function (width, height, options) { + autoDetectRecommendedRenderer: function (width, height, options) + { var isAndroid = /Android/i.test(navigator.userAgent); return core.autoDetectRenderer(width, height, options, isAndroid); diff --git a/src/core/math/Matrix.js b/src/core/math/Matrix.js index c2f87e2..2ff4848 100644 --- a/src/core/math/Matrix.js +++ b/src/core/math/Matrix.js @@ -10,7 +10,8 @@ * @class * @namespace PIXI */ -function Matrix() { +function Matrix() +{ /** * @member {number} * @default 1 @@ -63,7 +64,8 @@ * * @param array {number[]} The array that the matrix will be populated from. */ -Matrix.prototype.fromArray = function (array) { +Matrix.prototype.fromArray = function (array) +{ this.a = array[0]; this.b = array[1]; this.c = array[3]; @@ -78,14 +80,17 @@ * @param transpose {boolean} Whether we need to transpose the matrix or not * @return {number[]} the newly created array which contains the matrix */ -Matrix.prototype.toArray = function (transpose) { - if (!this.array) { +Matrix.prototype.toArray = function (transpose) +{ + if (!this.array) + { this.array = new Float32Array(9); } var array = this.array; - if (transpose) { + if (transpose) + { array[0] = this.a; array[1] = this.b; array[2] = 0; @@ -96,7 +101,8 @@ array[7] = this.ty; array[8] = 1; } - else { + else + { array[0] = this.a; array[1] = this.c; array[2] = this.tx; @@ -119,7 +125,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, transformed through this matrix */ -Matrix.prototype.apply = function (pos, newPos) { +Matrix.prototype.apply = function (pos, newPos) +{ newPos = newPos || new Point(); newPos.x = this.a * pos.x + this.c * pos.y + this.tx; @@ -136,7 +143,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, inverse-transformed through this matrix */ -Matrix.prototype.applyInverse = function (pos, newPos) { +Matrix.prototype.applyInverse = function (pos, newPos) +{ newPos = newPos || new Point(); var id = 1 / (this.a * this.d + this.c * -this.b); @@ -154,7 +162,8 @@ * @param {number} y * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.translate = function (x, y) { +Matrix.prototype.translate = function (x, y) +{ this.tx += x; this.ty += y; @@ -168,7 +177,8 @@ * @param {number} y The amount to scale vertically * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.scale = function (x, y) { +Matrix.prototype.scale = function (x, y) +{ this.a *= x; this.d *= y; this.c *= x; @@ -186,7 +196,8 @@ * @param {number} angle - The angle in radians. * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.rotate = function (angle) { +Matrix.prototype.rotate = function (angle) +{ var cos = Math.cos( angle ); var sin = Math.sin( angle ); @@ -210,7 +221,8 @@ * @param {Matrix} matrix * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.append = function (matrix) { +Matrix.prototype.append = function (matrix) +{ var a1 = this.a; var b1 = this.b; var c1 = this.c; @@ -232,7 +244,8 @@ * * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.identity = function () { +Matrix.prototype.identity = function () +{ this.a = 1; this.b = 0; this.c = 0; diff --git a/src/core/math/Point.js b/src/core/math/Point.js index 7565b2d..632f346 100644 --- a/src/core/math/Point.js +++ b/src/core/math/Point.js @@ -7,7 +7,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -function Point(x, y) { +function Point(x, y) +{ /** * @member {number} * @default 0 @@ -29,7 +30,8 @@ * * @return {Point} a copy of the point */ -Point.prototype.clone = function () { +Point.prototype.clone = function () +{ return new Point(this.x, this.y); }; @@ -40,7 +42,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -Point.prototype.set = function (x, y) { +Point.prototype.set = function (x, y) +{ this.x = x || 0; this.y = y || ( (y !== 0) ? this.x : 0 ) ; }; diff --git a/src/core/math/shapes/Circle.js b/src/core/math/shapes/Circle.js index 69cfdc9..4d76efc 100644 --- a/src/core/math/shapes/Circle.js +++ b/src/core/math/shapes/Circle.js @@ -10,7 +10,8 @@ * @param y {number} The Y coordinate of the center of this circle * @param radius {number} The radius of the circle */ -function Circle(x, y, radius) { +function Circle(x, y, radius) +{ /** * @member {number} * @default 0 @@ -46,7 +47,8 @@ * @method clone * @return {Circle} a copy of the Circle */ -Circle.prototype.clone = function () { +Circle.prototype.clone = function () +{ return new Circle(this.x, this.y, this.radius); }; @@ -58,8 +60,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Circle */ -Circle.prototype.contains = function (x, y) { - if (this.radius <= 0) { +Circle.prototype.contains = function (x, y) +{ + if (this.radius <= 0) + { return false; } @@ -79,6 +83,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Circle.prototype.getBounds = function () { +Circle.prototype.getBounds = function () +{ return new Rectangle(this.x - this.radius, this.y - this.radius, this.radius * 2, this.radius * 2); }; diff --git a/src/core/math/shapes/Ellipse.js b/src/core/math/shapes/Ellipse.js index 4f2d066..fefd01a 100644 --- a/src/core/math/shapes/Ellipse.js +++ b/src/core/math/shapes/Ellipse.js @@ -11,7 +11,8 @@ * @param width {number} The half width of this ellipse * @param height {number} The half height of this ellipse */ -function Ellipse(x, y, width, height) { +function Ellipse(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -53,7 +54,8 @@ * @method clone * @return {Ellipse} a copy of the ellipse */ -Ellipse.prototype.clone = function () { +Ellipse.prototype.clone = function () +{ return new Ellipse(this.x, this.y, this.width, this.height); }; @@ -65,8 +67,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coords are within this ellipse */ -Ellipse.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Ellipse.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } @@ -86,6 +90,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Ellipse.prototype.getBounds = function () { +Ellipse.prototype.getBounds = function () +{ return new Rectangle(this.x - this.width, this.y - this.height, this.width, this.height); }; diff --git a/src/core/math/shapes/Polygon.js b/src/core/math/shapes/Polygon.js index ae89148..fea6d37 100644 --- a/src/core/math/shapes/Polygon.js +++ b/src/core/math/shapes/Polygon.js @@ -10,16 +10,20 @@ * arguments passed can be flat x,y values e.g. `new Polygon(x,y, x,y, x,y, ...)` where `x` and `y` are * Numbers. */ -function Polygon(points) { +function Polygon(points) +{ //if points isn't an array, use arguments as the array - if (!(points instanceof Array)) { + if (!(points instanceof Array)) + { points = Array.prototype.slice.call(arguments); } //if this is a flat array of numbers, convert it to points - if (points[0] instanceof Point) { + if (points[0] instanceof Point) + { var p = []; - for (var i = 0, il = points.length; i < il; i++) { + for (var i = 0, il = points.length; i < il; i++) + { p.push(points[i].x, points[i].y); } @@ -51,7 +55,8 @@ * * @return {Polygon} a copy of the polygon */ -Polygon.prototype.clone = function () { +Polygon.prototype.clone = function () +{ return new Polygon(this.points.slice()); }; @@ -62,19 +67,22 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this polygon */ -Polygon.prototype.contains = function (x, y) { +Polygon.prototype.contains = function (x, y) +{ var inside = false; // use some raycasting to test hits // https://github.com/substack/point-in-polygon/blob/master/index.js var length = this.points.length / 2; - for (var i = 0, j = length - 1; i < length; j = i++) { + for (var i = 0, j = length - 1; i < length; j = i++) + { var xi = this.points[i * 2], yi = this.points[i * 2 + 1], xj = this.points[j * 2], yj = this.points[j * 2 + 1], intersect = ((yi > y) !== (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi); - if (intersect) { + if (intersect) + { inside = !inside; } } diff --git a/src/core/math/shapes/Rectangle.js b/src/core/math/shapes/Rectangle.js index 16ac62a..4008b68 100644 --- a/src/core/math/shapes/Rectangle.js +++ b/src/core/math/shapes/Rectangle.js @@ -10,7 +10,8 @@ * @param width {number} The overall width of this rectangle * @param height {number} The overall height of this rectangle */ -function Rectangle(x, y, width, height) { +function Rectangle(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -60,7 +61,8 @@ * * @return {Rectangle} a copy of the rectangle */ -Rectangle.prototype.clone = function () { +Rectangle.prototype.clone = function () +{ return new Rectangle(this.x, this.y, this.width, this.height); }; @@ -71,13 +73,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rectangle */ -Rectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Rectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/math/shapes/RoundedRectangle.js b/src/core/math/shapes/RoundedRectangle.js index 27d286e..7bf6411 100644 --- a/src/core/math/shapes/RoundedRectangle.js +++ b/src/core/math/shapes/RoundedRectangle.js @@ -11,7 +11,8 @@ * @param height {number} The overall height of this rounded rectangle * @param radius {number} Controls the radius of the rounded corners */ -function RoundedRectangle(x, y, width, height, radius) { +function RoundedRectangle(x, y, width, height, radius) +{ /** * @member {number} * @default 0 @@ -58,7 +59,8 @@ * * @return {RoundedRectangle} a copy of the rounded rectangle */ -RoundedRectangle.prototype.clone = function () { +RoundedRectangle.prototype.clone = function () +{ return new RoundedRectangle(this.x, this.y, this.width, this.height, this.radius); }; @@ -69,13 +71,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rounded Rectangle */ -RoundedRectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +RoundedRectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/primitives/Graphics.js b/src/core/primitives/Graphics.js index 261c534..e902d2a 100644 --- a/src/core/primitives/Graphics.js +++ b/src/core/primitives/Graphics.js @@ -16,7 +16,8 @@ * @extends DisplayObjectContainer * @namespace PIXI */ -function Graphics() { +function Graphics() +{ DisplayObjectContainer.call(this); this.renderable = true; @@ -154,16 +155,20 @@ * @private */ cacheAsBitmap: { - get: function () { + get: function () + { return this._cacheAsBitmap; }, - set: function (value) { + set: function (value) + { this._cacheAsBitmap = value; - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._generateCachedSprite(); } - else { + else + { this.destroyCachedSprite(); this.dirty = true; } @@ -176,7 +181,8 @@ * * @return {Graphics} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ var clone = new Graphics(); clone.renderable = this.renderable; @@ -192,7 +198,8 @@ clone.cachedSpriteDirty = this.cachedSpriteDirty; // copy graphics data - for (var i = 0; i < this.graphicsData.length; ++i) { + for (var i = 0; i < this.graphicsData.length; ++i) + { clone.graphicsData.push(this.graphicsData.clone()); } @@ -211,17 +218,21 @@ * @param alpha {number} alpha of the line to draw, will update the objects stored style * @return {Graphics} */ -Graphics.prototype.lineStyle = function (lineWidth, color, alpha) { +Graphics.prototype.lineStyle = function (lineWidth, color, alpha) +{ this.lineWidth = lineWidth || 0; this.lineColor = color || 0; this.lineAlpha = (arguments.length < 3) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length) + { // halfway through a line? start a new one! this.drawShape( new math.Polygon( this.currentPath.shape.points.slice(-2) )); } - else { + else + { // otherwise its empty so lets just set the line properties this.currentPath.lineWidth = this.lineWidth; this.currentPath.lineColor = this.lineColor; @@ -239,7 +250,8 @@ * @param y {number} the Y coordinate to move to * @return {Graphics} */ -Graphics.prototype.moveTo = function (x, y) { +Graphics.prototype.moveTo = function (x, y) +{ this.drawShape(new math.Polygon([x,y])); return this; @@ -253,7 +265,8 @@ * @param y {number} the Y coordinate to draw to * @return {Graphics} */ -Graphics.prototype.lineTo = function (x, y) { +Graphics.prototype.lineTo = function (x, y) +{ this.currentPath.shape.points.push(x, y); this.dirty = true; @@ -270,13 +283,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -285,7 +302,8 @@ n = 20, points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { this.moveTo(0, 0); } @@ -293,7 +311,8 @@ var fromY = points[points.length-1]; var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; xa = fromX + ( (cpX - fromX) * j ); @@ -319,13 +338,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -342,7 +365,8 @@ var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; dt = (1 - j); @@ -373,13 +397,17 @@ * @param radius {number} The radius of the arc * @return {Graphics} */ -Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points.push(x1, y1); } } - else { + else + { this.moveTo(x1, y1); } @@ -392,12 +420,15 @@ b2 = x2 - x1, mm = Math.abs(a1 * b2 - b1 * a2); - if (mm < 1.0e-8 || radius === 0) { - if (points[points.length-2] !== x1 || points[points.length-1] !== y1) { + if (mm < 1.0e-8 || radius === 0) + { + if (points[points.length-2] !== x1 || points[points.length-1] !== y1) + { points.push(x1, y1); } } - else { + else + { var dd = a1 * a1 + b1 * b1, cc = a2 * a2 + b2 * b2, tt = a1 * a2 + b1 * b2, @@ -433,42 +464,51 @@ * @param anticlockwise {boolean} Optional. Specifies whether the drawing should be counterclockwise or clockwise. False is default, and indicates clockwise, while true indicates counter-clockwise. * @return {Graphics} */ -Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) { +Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) +{ var startX = cx + Math.cos(startAngle) * radius; var startY = cy + Math.sin(startAngle) * radius; var points; // TODO - This if-else makes no sense. It uses currentPath in the else where it doesn't exist... - if (this.currentPath) { + if (this.currentPath) + { points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { points.push(startX, startY); } - else if (points[points.length-2] !== startX || points[points.length-1] !== startY) { + else if (points[points.length-2] !== startX || points[points.length-1] !== startY) + { points.push(startX, startY); } } - else { + else + { this.moveTo(startX, startY); points = this.currentPath.shape.points; } - if (startAngle === endAngle) { + if (startAngle === endAngle) + { return this; } - if (!anticlockwise && endAngle <= startAngle) { + if (!anticlockwise && endAngle <= startAngle) + { endAngle += Math.PI * 2; } - else if (anticlockwise && startAngle <= endAngle) { + else if (anticlockwise && startAngle <= endAngle) + { startAngle += Math.PI * 2; } var sweep = anticlockwise ? (startAngle - endAngle) *-1 : (endAngle - startAngle); var segs = (Math.abs(sweep)/ (Math.PI * 2)) * 40; - if (sweep === 0) { + if (sweep === 0) + { return this; } @@ -482,7 +522,8 @@ var remainder = ( segMinus % 1 ) / segMinus; - for (var i = 0; i <= segMinus; ++i) { + for (var i = 0; i <= segMinus; ++i) + { var real = i + remainder * i; var angle = ((theta) + startAngle + (theta2 * real)); @@ -506,13 +547,16 @@ * @param alpha {number} the alpha of the fill * @return {Graphics} */ -Graphics.prototype.beginFill = function (color, alpha) { +Graphics.prototype.beginFill = function (color, alpha) +{ this.filling = true; this.fillColor = color || 0; this.fillAlpha = (alpha === undefined) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length <= 2) + { this.currentPath.fill = this.filling; this.currentPath.fillColor = this.fillColor; this.currentPath.fillAlpha = this.fillAlpha; @@ -526,7 +570,8 @@ * * @return {Graphics} */ -Graphics.prototype.endFill = function () { +Graphics.prototype.endFill = function () +{ this.filling = false; this.fillColor = null; this.fillAlpha = 1; @@ -542,7 +587,8 @@ * @param height {number} The height of the rectangle * @return {Graphics} */ -Graphics.prototype.drawRect = function ( x, y, width, height ) { +Graphics.prototype.drawRect = function ( x, y, width, height ) +{ this.drawShape(new math.Rectangle(x,y, width, height)); return this; @@ -556,7 +602,8 @@ * @param height {number} The height of the rectangle * @param radius {number} Radius of the rectangle corners */ -Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) { +Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) +{ this.drawShape(new math.RoundedRectangle(x, y, width, height, radius)); return this; @@ -570,7 +617,8 @@ * @param radius {number} The radius of the circle * @return {Graphics} */ -Graphics.prototype.drawCircle = function (x, y, radius) { +Graphics.prototype.drawCircle = function (x, y, radius) +{ this.drawShape(new math.Circle(x,y, radius)); return this; @@ -585,7 +633,8 @@ * @param height {number} The half height of the ellipse * @return {Graphics} */ -Graphics.prototype.drawEllipse = function (x, y, width, height) { +Graphics.prototype.drawEllipse = function (x, y, width, height) +{ this.drawShape(new math.Ellipse(x, y, width, height)); return this; @@ -597,8 +646,10 @@ * @param path {Array} The path data used to construct the polygon. * @return {Graphics} */ -Graphics.prototype.drawPolygon = function (path) { - if (!(path instanceof Array)) { +Graphics.prototype.drawPolygon = function (path) +{ + if (!(path instanceof Array)) + { path = Array.prototype.slice.call(arguments); } @@ -612,7 +663,8 @@ * * @return {Graphics} */ -Graphics.prototype.clear = function () { +Graphics.prototype.clear = function () +{ this.lineWidth = 0; this.filling = false; @@ -631,7 +683,8 @@ * @param scaleMode {number} Should be one of the scaleMode consts * @return {Texture} a texture of the graphics object */ -Graphics.prototype.generateTexture = function (resolution, scaleMode) { +Graphics.prototype.generateTexture = function (resolution, scaleMode) +{ resolution = resolution || 1; var bounds = this.getBounds(); @@ -655,17 +708,21 @@ * * @param renderer {WebGLRenderer} */ -Graphics.prototype._renderWebGL = function (renderer) { +Graphics.prototype._renderWebGL = function (renderer) +{ // if the sprite is not visible or the alpha is 0 then no need to render this element - if (this.isMask === true) { + if (this.isMask === true) + { return; } // this code may still be needed so leaving for now.. - // + // /* - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture on the gpu too! @@ -681,17 +738,24 @@ return; } - */ - - // check if the webgl graphic needs to be updated - if (this.glDirty) { - this.dirty = true; - this.glDirty = false; - } + else */ - renderer.setObjectRendererer(renderer.graphicsRenderer); - renderer.graphicsRenderer.render(this); + renderer.spriteBatch.stop(); + renderer.blendModeManager.setBlendMode(this.blendMode); + // check blend mode + renderer.blendModeManager.setBlendMode( this.blendMode ); + + // check if the webgl graphic needs to be updated + if (this.glDirty) + { + this.dirty = true; + this.glDirty = false; + } + + WebGLGraphics.renderGraphics(this, renderer); + + renderer.spriteBatch.start(); }; /** @@ -700,14 +764,18 @@ * @param renderer {CanvasRenderer} * @private */ -Graphics.prototype.renderCanvas = function (renderer) { +Graphics.prototype.renderCanvas = function (renderer) +{ // 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.isMask === true) { + if (!this.visible || this.alpha <= 0 || this.isMask === true) + { return; } - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture @@ -723,16 +791,19 @@ return; } - else { + else + { var context = renderer.context; var transform = this.worldTransform; - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } @@ -748,11 +819,13 @@ CanvasGraphics.renderGraphics(this, context); - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } } @@ -763,13 +836,16 @@ * * @return {Rectangle} the rectangular bounding area */ -Graphics.prototype.getBounds = function (matrix) { +Graphics.prototype.getBounds = function (matrix) +{ // return an empty object if the item is a mask! - if (this.isMask) { + if (this.isMask) + { return math.Rectangle.EMPTY; } - if (this.dirty) { + if (this.dirty) + { this.updateLocalBounds(); this.glDirty = true; @@ -841,23 +917,27 @@ * Update the bounds of the object * */ -Graphics.prototype.updateLocalBounds = function () { +Graphics.prototype.updateLocalBounds = function () +{ var minX = Infinity; var maxX = -Infinity; var minY = Infinity; var maxY = -Infinity; - if (this.graphicsData.length) { + if (this.graphicsData.length) + { var shape, points, x, y, w, h; - for (var i = 0; i < this.graphicsData.length; i++) { + for (var i = 0; i < this.graphicsData.length; i++) + { var data = this.graphicsData[i]; var type = data.type; var lineWidth = data.lineWidth; shape = data.shape; - if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) { + if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) + { x = shape.x - lineWidth/2; y = shape.y - lineWidth/2; w = shape.width + lineWidth; @@ -869,7 +949,8 @@ minY = y < minY ? y : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.CIRC) { + else if (type === CONST.SHAPES.CIRC) + { x = shape.x; y = shape.y; w = shape.radius + lineWidth/2; @@ -881,7 +962,8 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.ELIP) { + else if (type === CONST.SHAPES.ELIP) + { x = shape.x; y = shape.y; w = shape.width + lineWidth/2; @@ -893,11 +975,13 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else { + else + { // POLY points = shape.points; - for (var j = 0; j < points.length; j += 2) { + for (var j = 0; j < points.length; j += 2) + { x = points[j]; y = points[j+1]; @@ -910,7 +994,8 @@ } } } - else { + else + { minX = 0; maxX = 0; minY = 0; @@ -931,10 +1016,12 @@ * * @private */ -Graphics.prototype._generateCachedSprite = function () { +Graphics.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { var canvasBuffer = new CanvasBuffer(bounds.width, bounds.height); var texture = Texture.fromCanvas(canvasBuffer.canvas); @@ -943,7 +1030,8 @@ this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.buffer.resize(bounds.width, bounds.height); } @@ -968,7 +1056,8 @@ * * @private */ -Graphics.prototype.updateCachedSpriteTexture = function () { +Graphics.prototype.updateCachedSpriteTexture = function () +{ var cachedSprite = this._cachedSprite; var texture = cachedSprite.texture; var canvas = cachedSprite.buffer.canvas; @@ -989,7 +1078,8 @@ * Destroys a previous cached sprite. * */ -Graphics.prototype.destroyCachedSprite = function () { +Graphics.prototype.destroyCachedSprite = function () +{ this._cachedSprite.texture.destroy(true); // let the gc collect the unused sprite @@ -1003,10 +1093,13 @@ * @param {Circle|Rectangle|Ellipse|Line|Polygon} shape The Shape object to draw. * @return {GraphicsData} The generated GraphicsData object. */ -Graphics.prototype.drawShape = function (shape) { - if (this.currentPath) { +Graphics.prototype.drawShape = function (shape) +{ + if (this.currentPath) + { // check current path! - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath.shape.points.length <= 2) + { this.graphicsData.pop(); } } @@ -1017,7 +1110,8 @@ this.graphicsData.push(data); - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { data.shape.closed = this.filling; this.currentPath = data; } diff --git a/src/core/primitives/GraphicsData.js b/src/core/primitives/GraphicsData.js index 99decbe..788f6f2 100644 --- a/src/core/primitives/GraphicsData.js +++ b/src/core/primitives/GraphicsData.js @@ -4,7 +4,8 @@ * @class * @namespace PIXI */ -function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) { +function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) +{ this.lineWidth = lineWidth; this.lineColor = lineColor; this.lineAlpha = lineAlpha; @@ -27,7 +28,8 @@ * * @return {GraphicsData} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ return new GraphicsData( this.lineWidth, this.lineColor, diff --git a/src/core/renderers/canvas/CanvasRenderer.js b/src/core/renderers/canvas/CanvasRenderer.js index 15a0978..7aebd44 100644 --- a/src/core/renderers/canvas/CanvasRenderer.js +++ b/src/core/renderers/canvas/CanvasRenderer.js @@ -17,17 +17,22 @@ * @param [options.resolution=1] {number} the resolution of the renderer retina would be 2 * @param [options.clearBeforeRender=true] {boolean} This sets if the CanvasRenderer will clear the canvas or not before the new render pass. */ -function CanvasRenderer(width, height, options) { +function CanvasRenderer(width, height, options) +{ utils.sayHello('Canvas'); - if (options) { - for (var i in CONST.defaultRenderOptions) { - if (typeof options[i] === 'undefined') { + if (options) + { + for (var i in CONST.defaultRenderOptions) + { + if (typeof options[i] === 'undefined') + { options[i] = CONST.defaultRenderOptions[i]; } } } - else { + else + { options = CONST.defaultRenderOptions; } @@ -156,19 +161,24 @@ this.smoothProperty = null; - if (this.context.imageSmoothingEnabled) { + if (this.context.imageSmoothingEnabled) + { this.smoothProperty = 'imageSmoothingEnabled'; } - else if (this.context.webkitImageSmoothingEnabled) { + else if (this.context.webkitImageSmoothingEnabled) + { this.smoothProperty = 'webkitImageSmoothingEnabled'; } - else if (this.context.mozImageSmoothingEnabled) { + else if (this.context.mozImageSmoothingEnabled) + { this.smoothProperty = 'mozImageSmoothingEnabled'; } - else if (this.context.oImageSmoothingEnabled) { + else if (this.context.oImageSmoothingEnabled) + { this.smoothProperty = 'oImageSmoothingEnabled'; } - else if (this.context.msImageSmoothingEnabled) { + else if (this.context.msImageSmoothingEnabled) + { this.smoothProperty = 'msImageSmoothingEnabled'; } @@ -193,10 +203,12 @@ * @memberof CanvasRenderer# */ backgroundColor: { - get: function () { + get: function () + { return this._backgroundColor; }, - set: function (val) { + set: function (val) + { this._backgroundColor = val; this._backgroundColorString = utils.hex2string(val); } @@ -208,7 +220,8 @@ * * @param object {DisplayObject} the object to be rendered */ -CanvasRenderer.prototype.render = function (object) { +CanvasRenderer.prototype.render = function (object) +{ object.updateTransform(); this.context.setTransform(1,0,0,1,0,0); @@ -218,16 +231,20 @@ this.currentBlendMode = CONST.blendModes.NORMAL; this.context.globalCompositeOperation = this.blendModes[CONST.blendModes.NORMAL]; - if (navigator.isCocoonJS && this.view.screencanvas) { + if (navigator.isCocoonJS && this.view.screencanvas) + { this.context.fillStyle = 'black'; this.context.clear(); } - if (this.clearBeforeRender) { - if (this.transparent) { + if (this.clearBeforeRender) + { + if (this.transparent) + { this.context.clearRect(0, 0, this.width, this.height); } - else { + else + { this.context.fillStyle = this._backgroundColorString; this.context.fillRect(0, 0, this.width , this.height); } @@ -241,8 +258,10 @@ * * @param [removeView=false] {boolean} Removes the Canvas element from the DOM. */ -CanvasRenderer.prototype.destroy = function (removeView) { - if (removeView && this.view.parent) { +CanvasRenderer.prototype.destroy = function (removeView) +{ + if (removeView && this.view.parent) + { this.view.parent.removeChild(this.view); } @@ -257,14 +276,16 @@ * @param width {number} the new width of the canvas view * @param height {number} the new height of the canvas view */ -CanvasRenderer.prototype.resize = function (width, height) { +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) { + if (this.autoResize) + { this.view.style.width = this.width / this.resolution + 'px'; this.view.style.height = this.height / this.resolution + 'px'; } @@ -276,7 +297,8 @@ * @param displayObject {DisplayObject} The displayObject to render * @private */ -CanvasRenderer.prototype.renderDisplayObject = function (displayObject) { +CanvasRenderer.prototype.renderDisplayObject = function (displayObject) +{ displayObject.renderCanvas(this); }; @@ -285,11 +307,14 @@ * * @private */ -CanvasRenderer.prototype._mapBlendModes = function () { - if (!this.blendModes) { +CanvasRenderer.prototype._mapBlendModes = function () +{ + if (!this.blendModes) + { this.blendModes = {}; - if (utils.canUseNewCanvasBlendModes()) { + if (utils.canUseNewCanvasBlendModes()) + { this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? this.blendModes[CONST.blendModes.MULTIPLY] = 'multiply'; @@ -308,7 +333,8 @@ this.blendModes[CONST.blendModes.COLOR] = 'color'; this.blendModes[CONST.blendModes.LUMINOSITY] = 'luminosity'; } - else { + else + { // this means that the browser does not support the cool new blend modes in canvas 'cough' ie 'cough' this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? diff --git a/src/core/renderers/canvas/utils/CanvasBuffer.js b/src/core/renderers/canvas/utils/CanvasBuffer.js index ebe5d47..b183a66 100644 --- a/src/core/renderers/canvas/utils/CanvasBuffer.js +++ b/src/core/renderers/canvas/utils/CanvasBuffer.js @@ -6,7 +6,8 @@ * @param width {number} the width for the newly created canvas * @param height {number} the height for the newly created canvas */ -function CanvasBuffer(width, height) { +function CanvasBuffer(width, height) +{ /** * The Canvas object that belongs to this CanvasBuffer. * @@ -36,10 +37,12 @@ * @memberof CanvasBuffer# */ width: { - get: function () { + get: function () + { return this.canvas.width; }, - set: function (val) { + set: function (val) + { this.canvas.width = val; } }, @@ -50,10 +53,12 @@ * @memberof CanvasBuffer# */ height: { - get: function () { + get: function () + { return this.canvas.height; }, - set: function (val) { + set: function (val) + { this.canvas.height = val; } } @@ -64,7 +69,8 @@ * * @private */ -CanvasBuffer.prototype.clear = function () { +CanvasBuffer.prototype.clear = function () +{ this.context.setTransform(1, 0, 0, 1, 0, 0); this.context.clearRect(0,0, this.canvas.width, this.canvas.height); }; @@ -75,7 +81,8 @@ * @param width {number} the new width of the canvas * @param height {number} the new height of the canvas */ -CanvasBuffer.prototype.resize = function (width, height) { +CanvasBuffer.prototype.resize = function (width, height) +{ this.canvas.width = width; this.canvas.height = height; }; diff --git a/src/core/renderers/canvas/utils/CanvasGraphics.js b/src/core/renderers/canvas/utils/CanvasGraphics.js index c7eaa2a..3f2a91f 100644 --- a/src/core/renderers/canvas/utils/CanvasGraphics.js +++ b/src/core/renderers/canvas/utils/CanvasGraphics.js @@ -13,15 +13,18 @@ * @param graphics {Graphics} the actual graphics object to render * @param context {CanvasRenderingContext2D} the 2d drawing method of the canvas */ -CanvasGraphics.renderGraphics = function (graphics, context) { +CanvasGraphics.renderGraphics = function (graphics, context) +{ var worldAlpha = graphics.worldAlpha; - if (graphics.dirty) { + if (graphics.dirty) + { this.updateGraphicsTint(graphics); graphics.dirty = false; } - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; @@ -30,69 +33,82 @@ context.lineWidth = data.lineWidth; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { context.beginPath(); var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } - if (shape.closed) { + if (shape.closed) + { context.lineTo(points[0], points[1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fillRect(shape.x, shape.y, shape.width, shape.height); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.strokeRect(shape.x, shape.y, shape.width, shape.height); } } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.beginPath(); context.arc(shape.x, shape.y, shape.radius,0,2*Math.PI); context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas var w = shape.width * 2; @@ -119,18 +135,21 @@ context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; var width = shape.width; @@ -152,13 +171,15 @@ context.quadraticCurveTo(rx, ry, rx, ry + radius); context.closePath(); - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); @@ -174,45 +195,54 @@ * @param graphics {Graphics} the graphics which will be used as a mask * @param context {CanvasRenderingContext2D} the context 2d method of the canvas */ -CanvasGraphics.renderGraphicsMask = function (graphics, context) { +CanvasGraphics.renderGraphicsMask = function (graphics, context) +{ var len = graphics.graphicsData.length; - if (len === 0) { + if (len === 0) + { return; } context.beginPath(); - for (var i = 0; i < len; i++) { + for (var i = 0; i < len; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { context.rect(shape.x, shape.y, shape.width, shape.height); context.closePath(); } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.arc(shape.x, shape.y, shape.radius, 0, 2 * Math.PI); context.closePath(); } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas @@ -237,7 +267,8 @@ context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); context.closePath(); } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; @@ -262,8 +293,10 @@ } }; -CanvasGraphics.updateGraphicsTint = function (graphics) { - if (graphics.tint === 0xFFFFFF) { +CanvasGraphics.updateGraphicsTint = function (graphics) +{ + if (graphics.tint === 0xFFFFFF) + { return; } @@ -271,7 +304,8 @@ var tintG = (graphics.tint >> 8 & 0xFF) / 255; var tintB = (graphics.tint & 0xFF)/ 255; - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var fillColor = data.fillColor | 0; diff --git a/src/core/renderers/canvas/utils/CanvasMaskManager.js b/src/core/renderers/canvas/utils/CanvasMaskManager.js index e04a733..9827d36 100644 --- a/src/core/renderers/canvas/utils/CanvasMaskManager.js +++ b/src/core/renderers/canvas/utils/CanvasMaskManager.js @@ -6,7 +6,8 @@ * @class * @namespace PIXI */ -function CanvasMaskManager() {} +function CanvasMaskManager() +{} CanvasMaskManager.prototype.constructor = CanvasMaskManager; module.exports = CanvasMaskManager; @@ -17,7 +18,8 @@ * @param maskData {object} the maskData that will be pushed * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.pushMask = function (maskData, renderer) { +CanvasMaskManager.prototype.pushMask = function (maskData, renderer) +{ renderer.context.save(); var cacheAlpha = maskData.alpha; @@ -45,6 +47,7 @@ * * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.popMask = function (renderer) { +CanvasMaskManager.prototype.popMask = function (renderer) +{ renderer.context.restore(); }; diff --git a/src/core/renderers/canvas/utils/CanvasTinter.js b/src/core/renderers/canvas/utils/CanvasTinter.js index 17e0529..d2fb1bc 100644 --- a/src/core/renderers/canvas/utils/CanvasTinter.js +++ b/src/core/renderers/canvas/utils/CanvasTinter.js @@ -14,7 +14,8 @@ * @param color {number} the color to use to tint the sprite with * @return {HTMLCanvasElement} The tinted canvas */ -CanvasTinter.getTintedTexture = function (sprite, color) { +CanvasTinter.getTintedTexture = function (sprite, color) +{ var texture = sprite.texture; color = CanvasTinter.roundColor(color); @@ -23,7 +24,8 @@ texture.tintCache = texture.tintCache || {}; - if (texture.tintCache[stringColor]) { + if (texture.tintCache[stringColor]) + { return texture.tintCache[stringColor]; } @@ -33,14 +35,16 @@ //CanvasTinter.tintWithPerPixel(texture, stringColor, canvas); CanvasTinter.tintMethod(texture, color, canvas); - if (CanvasTinter.convertTintToImage) { + if (CanvasTinter.convertTintToImage) + { // is this better? var tintImage = new Image(); tintImage.src = canvas.toDataURL(); texture.tintCache[stringColor] = tintImage; } - else { + else + { texture.tintCache[stringColor] = canvas; // if we are not converting the texture to an image then we need to lose the reference to the canvas CanvasTinter.canvas = null; @@ -56,7 +60,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithMultiply = function (texture, color, canvas) { +CanvasTinter.tintWithMultiply = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -104,7 +109,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithOverlay = function (texture, color, canvas) { +CanvasTinter.tintWithOverlay = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -139,7 +145,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithPerPixel = function (texture, color, canvas) { +CanvasTinter.tintWithPerPixel = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -167,7 +174,8 @@ var pixels = pixelData.data; - for (var i = 0; i < pixels.length; i += 4) { + for (var i = 0; i < pixels.length; i += 4) + { pixels[i+0] *= r; pixels[i+1] *= g; pixels[i+2] *= b; @@ -181,7 +189,8 @@ * * @param color {number} the color to round, should be a hex color */ -CanvasTinter.roundColor = function (color) { +CanvasTinter.roundColor = function (color) +{ var step = CanvasTinter.cacheStepsPerColorChannel; var rgbValues = utils.hex2rgb(color); diff --git a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js index 9f2f89a..35edbaf 100644 --- a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js +++ b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLBlendModeManager(renderer) { +function WebGLBlendModeManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -23,8 +24,10 @@ * * @param blendMode {number} the blendMode, should be a Pixi const, such as BlendModes.ADD */ -WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) { - if (this.currentBlendMode === blendMode) { +WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) +{ + if (this.currentBlendMode === blendMode) + { return false; } diff --git a/src/core/renderers/webgl/managers/WebGLFilterManager.js b/src/core/renderers/webgl/managers/WebGLFilterManager.js index 1179258..2dac048 100644 --- a/src/core/renderers/webgl/managers/WebGLFilterManager.js +++ b/src/core/renderers/webgl/managers/WebGLFilterManager.js @@ -7,7 +7,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLFilterManager(renderer) { +function WebGLFilterManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -32,7 +33,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.texturePool.length = 0; self.initShaderBuffers(); }); @@ -46,7 +48,8 @@ * @param renderer {WebGLRenderer} * @param buffer {ArrayBuffer} */ -WebGLFilterManager.prototype.begin = function (buffer) { +WebGLFilterManager.prototype.begin = function (buffer) +{ this.defaultShader = this.renderer.shaderManager.defaultShader; this.width = this.renderer.projection.x * 2; @@ -60,7 +63,8 @@ * * @param filterBlock {object} the filter that will be pushed to the current filter stack */ -WebGLFilterManager.prototype.pushFilter = function (filterBlock) { +WebGLFilterManager.prototype.pushFilter = function (filterBlock) +{ var gl = this.renderer.gl; var projection = this.renderer.projection; @@ -78,10 +82,12 @@ this.offsetY += filterBlock._filterArea.y; var texture = this.texturePool.pop(); - if (!texture) { + if (!texture) + { texture = new FilterTexture(this.renderer.gl, this.width, this.height); } - else { + else + { texture.resize(this.width, this.height); } @@ -98,29 +104,35 @@ var localX = filterArea.x, localY = filterArea.y; - if (filterArea.x < 0) { + if (filterArea.x < 0) + { filterArea.width += filterArea.x; filterArea.x = 0; } - if (filterArea.y < 0) { + if (filterArea.y < 0) + { filterArea.height += filterArea.y; filterArea.y = 0; } - if (localX + filterArea.width > this.width) { + if (localX + filterArea.width > this.width) + { filterArea.width = this.width - localX; } - if (localY + filterArea.height > this.height) { + if (localY + filterArea.height > this.height) + { filterArea.height = this.height - localY; } - if (filterArea.width < 0) { + if (filterArea.width < 0) + { filterArea.width = 0; } - if (filterArea.height < 0) { + if (filterArea.height < 0) + { filterArea.height = 0; } @@ -154,7 +166,8 @@ * Removes the last filter from the filter stack and doesn't return it. * */ -WebGLFilterManager.prototype.popFilter = function () { +WebGLFilterManager.prototype.popFilter = function () +{ var gl = this.renderer.gl; var filterBlock = this.filterStack.pop(); @@ -163,7 +176,8 @@ var projection = this.renderer.projection; var offset = this.renderer.offset; - if (filterBlock.filterPasses.length > 1) { + if (filterBlock.filterPasses.length > 1) + { gl.viewport(0, 0, filterArea.width, filterArea.height); gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); @@ -193,7 +207,8 @@ var inputTexture = texture; var outputTexture = this.texturePool.pop(); - if (!outputTexture) { + if (!outputTexture) + { outputTexture = new FilterTexture(this.renderer.gl, this.width, this.height); } outputTexture.resize(this.width, this.height); @@ -204,7 +219,8 @@ gl.disable(gl.BLEND); - for (var i = 0; i < filterBlock.filterPasses.length-1; i++) { + for (var i = 0; i < filterBlock.filterPasses.length-1; i++) + { var filterPass = filterBlock.filterPasses[i]; gl.bindFramebuffer(gl.FRAMEBUFFER, outputTexture.frameBuffer ); @@ -243,10 +259,12 @@ var buffer = this.buffer; // time to render the filters texture to the previous scene - if (this.filterStack.length === 0) { + if (this.filterStack.length === 0) + { gl.colorMask(true, true, true, true);//this.transparent); } - else { + else + { var currentFilter = this.filterStack[this.filterStack.length-1]; filterArea = currentFilter._filterArea; @@ -332,13 +350,15 @@ * @param width {number} the horizontal range of the filter * @param height {number} the vertical range of the filter */ -WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) { +WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) +{ // use program var gl = this.renderer.gl; var shader = filter.shaders[gl.id]; - if (!shader) { + if (!shader) + { shader = new Shader(gl); shader.fragmentSrc = filter.fragmentSrc; @@ -356,7 +376,8 @@ gl.uniform2f(shader.projectionVector, width/2, -height/2); gl.uniform2f(shader.offsetVector, 0,0); - if (filter.uniforms.dimensions) { + 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]; @@ -386,7 +407,8 @@ * Initialises the shader buffers. * */ -WebGLFilterManager.prototype.initShaderBuffers = function () { +WebGLFilterManager.prototype.initShaderBuffers = function () +{ var gl = this.renderer.gl; // create some buffers @@ -432,7 +454,8 @@ * Destroys the filter and removes it from the filter stack. * */ -WebGLFilterManager.prototype.destroy = function () { +WebGLFilterManager.prototype.destroy = function () +{ var gl = this.renderer.gl; this.filterStack = null; @@ -441,7 +464,8 @@ this.offsetY = 0; // destroy textures - for (var i = 0; i < this.texturePool.length; i++) { + for (var i = 0; i < this.texturePool.length; i++) + { this.texturePool[i].destroy(); } diff --git a/src/core/renderers/webgl/managers/WebGLManager.js b/src/core/renderers/webgl/managers/WebGLManager.js index 9d47b5c..c30cd51 100644 --- a/src/core/renderers/webgl/managers/WebGLManager.js +++ b/src/core/renderers/webgl/managers/WebGLManager.js @@ -3,7 +3,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLManager(renderer) { +function WebGLManager(renderer) +{ /** * The renderer this manager works for. * @@ -15,6 +16,7 @@ WebGLManager.prototype.constructor = WebGLManager; module.exports = WebGLManager; -WebGLManager.prototype.destroy = function () { +WebGLManager.prototype.destroy = function () +{ this.renderer = null; }; diff --git a/src/core/renderers/webgl/managers/WebGLMaskManager.js b/src/core/renderers/webgl/managers/WebGLMaskManager.js index 2f90b64..e568812 100644 --- a/src/core/renderers/webgl/managers/WebGLMaskManager.js +++ b/src/core/renderers/webgl/managers/WebGLMaskManager.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLMaskManager(renderer) { +function WebGLMaskManager(renderer) +{ WebGLManager.call(this, renderer); } @@ -19,12 +20,15 @@ * * @param maskData {any[]} */ -WebGLMaskManager.prototype.pushMask = function (maskData) { - if (maskData.dirty) { +WebGLMaskManager.prototype.pushMask = function (maskData) +{ + if (maskData.dirty) + { WebGLGraphics.updateGraphics(maskData, this.renderer.gl); } - if (!maskData._webGL[this.renderer.gl.id].data.length) { + if (!maskData._webGL[this.renderer.gl.id].data.length) + { return; } @@ -36,6 +40,7 @@ * * @param maskData {any[]} */ -WebGLMaskManager.prototype.popMask = function (maskData) { +WebGLMaskManager.prototype.popMask = function (maskData) +{ this.renderer.stencilManager.popStencil(maskData, maskData._webGL[this.renderer.gl.id].data[0], this.renderer); }; diff --git a/src/core/display/DisplayObject.js b/src/core/display/DisplayObject.js index 66ebc3c..20e778c 100644 --- a/src/core/display/DisplayObject.js +++ b/src/core/display/DisplayObject.js @@ -7,7 +7,8 @@ * @class * @namespace PIXI */ -function DisplayObject() { +function DisplayObject() +{ /** * The coordinate of the object relative to the local coordinates of the parent. * @@ -152,10 +153,12 @@ * @memberof DisplayObject# */ x: { - get: function () { + get: function () + { return this.position.x; }, - set: function (value) { + set: function (value) + { this.position.x = value; } }, @@ -167,10 +170,12 @@ * @memberof DisplayObject# */ y: { - get: function () { + get: function () + { return this.position.y; }, - set: function (value) { + set: function (value) + { this.position.y = value; } }, @@ -183,11 +188,13 @@ * @readonly */ worldVisible: { - get: function () { + get: function () + { var item = this; do { - if (!item.visible) { + if (!item.visible) + { return false; } @@ -207,17 +214,21 @@ * @memberof DisplayObject# */ mask: { - get: function () { + get: function () + { return this._mask; }, - set: function (value) { - if (this._mask) { + set: function (value) + { + if (this._mask) + { this._mask.isMask = false; } this._mask = value; - if (this._mask) { + if (this._mask) + { this._mask.isMask = true; } } @@ -232,18 +243,23 @@ * @memberof DisplayObject# */ filters: { - get: function () { + get: function () + { return this._filters; }, - set: function (value) { - if (value) { + set: function (value) + { + if (value) + { // now put all the passes in one place.. var passes = []; - for (var i = 0; i < value.length; i++) { + for (var i = 0; i < value.length; i++) + { var filterPasses = value[i].passes; - for (var j = 0; j < filterPasses.length; j++) { + for (var j = 0; j < filterPasses.length; j++) + { passes.push(filterPasses[j]); } } @@ -264,8 +280,9 @@ * * @private */ -DisplayObject.prototype.updateTransform = function () { - +DisplayObject.prototype.updateTransform = function () +{ + // create some matrix refs for easy access var pt = this.parent.worldTransform; var wt = this.worldTransform; @@ -274,9 +291,11 @@ var a, b, c, d, tx, ty; // so if rotation is between 0 then we can simplify the multiplication process.. - if (this.rotation % math.PI_2) { + if (this.rotation % math.PI_2) + { // 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) { + if (this.rotation !== this.rotationCache) + { this.rotationCache = this.rotation; this._sr = Math.sin(this.rotation); this._cr = Math.cos(this.rotation); @@ -291,7 +310,8 @@ ty = this.position.y; // check for pivot.. not often used so geared towards that fact! - if (this.pivot.x || this.pivot.y) { + 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; } @@ -304,7 +324,8 @@ wt.tx = tx * pt.a + ty * pt.c + pt.tx; wt.ty = tx * pt.b + ty * pt.d + pt.ty; } - else { + else + { // lets do the fast version as we know there is no rotation.. a = this.scale.x; d = this.scale.y; @@ -333,7 +354,8 @@ * @param matrix {Matrix} * @return {Rectangle} the rectangular bounding area */ -DisplayObject.prototype.getBounds = function (/* matrix */) { +DisplayObject.prototype.getBounds = function (/* matrix */) +{ return math.Rectangle.EMPTY; }; @@ -342,7 +364,8 @@ * * @return {Rectangle} the rectangular bounding area */ -DisplayObject.prototype.getLocalBounds = function () { +DisplayObject.prototype.getLocalBounds = function () +{ return this.getBounds(math.Matrix.IDENTITY); }; @@ -352,7 +375,8 @@ * @param position {Point} The world origin to calculate from * @return {Point} A point object representing the position of this object */ -DisplayObject.prototype.toGlobal = function (position) { +DisplayObject.prototype.toGlobal = function (position) +{ // don't need to u[date the lot this.displayObjectUpdateTransform(); return this.worldTransform.apply(position); @@ -365,8 +389,10 @@ * @param [from] {DisplayObject} The DisplayObject to calculate the global position from * @return {Point} A point object representing the position of this object */ -DisplayObject.prototype.toLocal = function (position, from) { - if (from) { +DisplayObject.prototype.toLocal = function (position, from) +{ + if (from) + { position = from.toGlobal(position); } @@ -381,7 +407,8 @@ * @param renderer {WebGLRenderer} The renderer * @private */ -DisplayObject.prototype.renderWebGL = function (/* renderer */) { +DisplayObject.prototype.renderWebGL = function (/* renderer */) +{ // OVERWRITE; }; @@ -391,6 +418,7 @@ * @param renderer {CanvasRenderer} The renderer * @private */ -DisplayObject.prototype.renderCanvas = function (/* renderer */) { +DisplayObject.prototype.renderCanvas = function (/* renderer */) +{ // OVERWRITE; }; diff --git a/src/core/display/DisplayObjectContainer.js b/src/core/display/DisplayObjectContainer.js index 689f40b..4625ee8 100644 --- a/src/core/display/DisplayObjectContainer.js +++ b/src/core/display/DisplayObjectContainer.js @@ -12,7 +12,8 @@ * @extends DisplayObject * @namespace PIXI */ -function DisplayObjectContainer() { +function DisplayObjectContainer() +{ DisplayObject.call(this); /** @@ -47,17 +48,21 @@ * @memberof DisplayObjectContainer# */ width: { - get: function () { + get: function () + { return this.scale.x * this.getLocalBounds().width; }, - set: function (value) { + set: function (value) + { var width = this.getLocalBounds().width; - if(width !== 0) { + if(width !== 0) + { this.scale.x = value / width; } - else { + else + { this.scale.x = 1; } @@ -73,17 +78,21 @@ * @memberof DisplayObjectContainer# */ height: { - get: function () { + get: function () + { return this.scale.y * this.getLocalBounds().height; }, - set: function (value) { + set: function (value) + { var height = this.getLocalBounds().height; - if (height !== 0) { + if (height !== 0) + { this.scale.y = value / height ; } - else { + else + { this.scale.y = 1; } @@ -100,18 +109,23 @@ * @memberof DisplayObject# */ cacheAsBitmap: { - get: function () { + get: function () + { return this._cacheAsBitmap; }, - set: function (value) { - if (this._cacheAsBitmap === value) { + set: function (value) + { + if (this._cacheAsBitmap === value) + { return; } - if (value) { + if (value) + { this._generateCachedSprite(); } - else { + else + { this._destroyCachedSprite(); } @@ -126,7 +140,8 @@ * @param child {DisplayObject} The DisplayObject to add to the container * @return {DisplayObject} The child that was added. */ -DisplayObjectContainer.prototype.addChild = function (child) { +DisplayObjectContainer.prototype.addChild = function (child) +{ return this.addChildAt(child, this.children.length); }; @@ -137,14 +152,18 @@ * @param index {Number} The index to place the child in * @return {DisplayObject} The child that was added. */ -DisplayObjectContainer.prototype.addChildAt = function (child, index) { +DisplayObjectContainer.prototype.addChildAt = function (child, index) +{ // prevent adding self as child - if (child === this) { + if (child === this) + { return; } - if (index >= 0 && index <= this.children.length) { - if (child.parent) { + if (index >= 0 && index <= this.children.length) + { + if (child.parent) + { child.parent.removeChild(child); } @@ -154,7 +173,8 @@ return child; } - else { + else + { throw new Error(child + 'addChildAt: The index '+ index +' supplied is out of bounds ' + this.children.length); } }; @@ -165,15 +185,18 @@ * @param child {DisplayObject} * @param child2 {DisplayObject} */ -DisplayObjectContainer.prototype.swapChildren = function (child, child2) { - if (child === child2) { +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) { + if (index1 < 0 || index2 < 0) + { throw new Error('swapChildren: Both the supplied DisplayObjects must be a child of the caller.'); } @@ -187,10 +210,12 @@ * @param child {DisplayObject} The DisplayObject instance to identify * @return {Number} The index position of the child display object to identify */ -DisplayObjectContainer.prototype.getChildIndex = function (child) { +DisplayObjectContainer.prototype.getChildIndex = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { throw new Error('The supplied DisplayObject must be a child of the caller'); } @@ -203,8 +228,10 @@ * @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 */ -DisplayObjectContainer.prototype.setChildIndex = function (child, index) { - if (index < 0 || index >= this.children.length) { +DisplayObjectContainer.prototype.setChildIndex = function (child, index) +{ + if (index < 0 || index >= this.children.length) + { throw new Error('The supplied index is out of bounds'); } @@ -220,8 +247,10 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child at the given index, if any. */ -DisplayObjectContainer.prototype.getChildAt = function (index) { - if (index < 0 || index >= this.children.length) { +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'); } @@ -234,10 +263,12 @@ * @param child {DisplayObject} The DisplayObject to remove * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChild = function (child) { +DisplayObjectContainer.prototype.removeChild = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { return; } @@ -250,7 +281,8 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChildAt = function (index) { +DisplayObjectContainer.prototype.removeChildAt = function (index) +{ var child = this.getChildAt(index); child.parent = null; @@ -265,24 +297,29 @@ * @param beginIndex {Number} The beginning position. Default value is 0. * @param endIndex {Number} The ending position. Default value is size of the container. */ -DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) { +DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) +{ var begin = beginIndex || 0; var end = typeof endIndex === 'number' ? endIndex : this.children.length; var range = end - begin; - if (range > 0 && range <= end) { + if (range > 0 && range <= end) + { var removed = this.children.splice(begin, range); - for (var i = 0; i < removed.length; ++i) { + for (var i = 0; i < removed.length; ++i) + { removed[i].parent = null; } return removed; } - else if (range === 0 && this.children.length === 0) { + else if (range === 0 && this.children.length === 0) + { return []; } - else { + else + { throw new RangeError('removeChildren: numeric values are outside the acceptable range.'); } }; @@ -291,7 +328,8 @@ * Generates and updates the cached sprite for this object. * */ -DisplayObjectContainer.prototype.updateCachedSprite = function () { +DisplayObjectContainer.prototype.updateCachedSprite = function () +{ this._generateCachedSprite(); }; @@ -304,7 +342,8 @@ * @param renderer {CanvasRenderer|WebGLRenderer} The renderer used to generate the texture. * @return {Texture} a texture of the graphics object */ -DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) { +DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) +{ var bounds = this.getLocalBounds(); var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0, renderer, scaleMode, resolution); @@ -322,18 +361,22 @@ * * @private */ -DisplayObjectContainer.prototype.updateTransform = function () { - if (!this.visible) { +DisplayObjectContainer.prototype.updateTransform = function () +{ + if (!this.visible) + { return; } this.displayObjectUpdateTransform(); - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { return; } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } }; @@ -346,8 +389,10 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getBounds = function () { - if (this.children.length === 0) { +DisplayObjectContainer.prototype.getBounds = function () +{ + if (this.children.length === 0) + { return math.Rectangle.EMPTY; } @@ -365,10 +410,12 @@ var childVisible = false; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -386,7 +433,8 @@ maxY = maxY > childMaxY ? maxY : childMaxY; } - if (!childVisible) { + if (!childVisible) + { return math.Rectangle.EMPTY; } @@ -407,12 +455,14 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getLocalBounds = function () { +DisplayObjectContainer.prototype.getLocalBounds = function () +{ var matrixCache = this.worldTransform; this.worldTransform = math.Matrix.IDENTITY; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } @@ -428,13 +478,16 @@ * * @param renderer {WebGLRenderer} The renderer */ -DisplayObjectContainer.prototype.renderWebGL = function (renderer) { +DisplayObjectContainer.prototype.renderWebGL = function (renderer) +{ // if the object is not visible or the alpha is 0 then no need to render this element - if (!this.visible || this.alpha <= 0) { + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } @@ -442,14 +495,17 @@ var i, j; // do a quick check to see if this element has a mask or a filter. - if (this._mask || this._filters) { + if (this._mask || this._filters) + { // push filter first as we need to ensure the stencil buffer is correct for any masking - if (this._filters) { + if (this._filters) + { renderer.spriteBatch.flush(); renderer.filterManager.pushFilter(this._filterBlock); } - if (this._mask) { + if (this._mask) + { renderer.spriteBatch.stop(); renderer.maskManager.pushMask(this.mask, renderer); renderer.spriteBatch.start(); @@ -459,36 +515,42 @@ this._renderWebGL(renderer); // now loop through the children and make sure they get rendered - for (i = 0, j = this.children.length; i < j; i++) { + for (i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderWebGL(renderer); } // time to stop the sprite batch as either a mask element or a filter draw will happen next renderer.spriteBatch.stop(); - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(this._mask, renderer); } - if (this._filters) { + if (this._filters) + { renderer.filterManager.popFilter(); } renderer.spriteBatch.start(); } - else { + else + { this._renderWebGL(renderer); // simple render children! - for (i = 0, j = this.children.length; i < j; ++i) { + for (i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderWebGL(renderer); } } }; -DisplayObjectContainer.prototype._renderWebGL = function (renderer) { +DisplayObjectContainer.prototype._renderWebGL = function (renderer) +{ // this is where content itself gets renderd.. @@ -499,25 +561,31 @@ * * @param renderer {CanvasRenderer} The renderer */ -DisplayObjectContainer.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0) { +DisplayObjectContainer.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -528,13 +596,16 @@ * @param renderer {WebGLRenderer|CanvasRenderer} The renderer * @private */ -DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) { +DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) +{ this._cachedSprite.worldAlpha = this.worldAlpha; - if (renderer.gl) { + if (renderer.gl) + { this._cachedSprite.renderWebGL(renderer); } - else { + else + { this._cachedSprite.renderCanvas(renderer); } }; @@ -544,10 +615,12 @@ * * @private */ -DisplayObjectContainer.prototype._generateCachedSprite = function () { +DisplayObjectContainer.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { // TODO - RenderTexture now *requires* a renderer instance, so this is like broken // because `renderer` isn't actually in scope here :P var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0); @@ -555,7 +628,8 @@ this._cachedSprite = new Sprite(renderTexture); this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.texture.resize(bounds.width | 0, bounds.height | 0); } @@ -580,8 +654,10 @@ * * @private */ -DisplayObjectContainer.prototype._destroyCachedSprite = function () { - if (!this._cachedSprite) { +DisplayObjectContainer.prototype._destroyCachedSprite = function () +{ + if (!this._cachedSprite) + { return; } diff --git a/src/core/display/Sprite.js b/src/core/display/Sprite.js index 707da24..5862aef 100644 --- a/src/core/display/Sprite.js +++ b/src/core/display/Sprite.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param texture {Texture} The texture for this sprite */ -function Sprite(texture) { +function Sprite(texture) +{ DisplayObjectContainer.call(this); /** @@ -85,12 +86,14 @@ this.texture = texture || Texture.EMPTY; } -Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) { +Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) +{ DisplayObjectContainer.prototype.destroy.call(this); this.anchor = null; - if (destroyTexture) { + if (destroyTexture) + { this._texture.destroy(destroyBaseTexture); } @@ -111,10 +114,12 @@ * @memberof Sprite# */ width: { - get: function () { + get: function () + { return this.scale.x * this.texture.frame.width; }, - set: function (value) { + set: function (value) + { this.scale.x = value / this.texture.frame.width; this._width = value; } @@ -127,10 +132,12 @@ * @memberof Sprite# */ height: { - get: function () { + get: function () + { return this.scale.y * this.texture.frame.height; }, - set: function (value) { + set: function (value) + { this.scale.y = value / this.texture.frame.height; this._height = value; } @@ -143,23 +150,29 @@ * @memberof Sprite# */ texture: { - get: function () { + get: function () + { return this._texture; }, - set: function (value) { - if (this._texture === value) { + set: function (value) + { + if (this._texture === value) + { return; } this._texture = value; this.cachedTint = 0xFFFFFF; - if (value) { + if (value) + { // wait for the texture to load - if (value.baseTexture.hasLoaded) { + if (value.baseTexture.hasLoaded) + { this._onTextureUpdate(); } - else { + else + { value.once('update', this._onTextureUpdate.bind(this)); } } @@ -172,18 +185,22 @@ * * @private */ -Sprite.prototype._onTextureUpdate = function () { +Sprite.prototype._onTextureUpdate = function () +{ // so if _width is 0 then width was not set.. - if (this._width) { + if (this._width) + { this.scale.x = this._width / this.texture.frame.width; } - if (this._height) { + if (this._height) + { this.scale.y = this._height / this.texture.frame.height; } }; -Sprite.prototype._renderWebGL = function (renderer) { +Sprite.prototype._renderWebGL = function (renderer) +{ // this is where content gets renderd.. // watch this space for a little render state manager.. @@ -197,7 +214,8 @@ * @param matrix {Matrix} the transformation matrix of the sprite * @return {Rectangle} the framing rectangle */ -Sprite.prototype.getBounds = function (matrix) { +Sprite.prototype.getBounds = function (matrix) +{ var width = this.texture.frame.width; var height = this.texture.frame.height; @@ -224,11 +242,13 @@ if(b === 0 && c === 0) { // scale may be negative! - if (a < 0) { + if (a < 0) + { a *= -1; } - if (d < 0) { + if (d < 0) + { d *= -1; } @@ -293,28 +313,34 @@ * * @param renderer {CanvasRenderer} The renderer */ -Sprite.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) { +Sprite.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) + { return; } - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; renderer.context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } // Ignore null sources - if (this.texture.valid) { + if (this.texture.valid) + { var resolution = this.texture.baseTexture.resolution / renderer.resolution; renderer.context.globalAlpha = this.worldAlpha; // If smoothingEnabled is supported and we need to change the smoothing property for this texture - if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) { + if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) + { renderer.scaleMode = this.texture.baseTexture.scaleMode; renderer.context[renderer.smoothProperty] = (renderer.scaleMode === CONST.scaleModes.LINEAR); } @@ -324,7 +350,8 @@ var dy = (this.texture.trim ? this.texture.trim.y : 0) - (this.anchor.y * this.texture.trim.height); // Allow for pixel rounding - if (renderer.roundPixels) { + if (renderer.roundPixels) + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -337,7 +364,8 @@ dx = dx | 0; dy = dy | 0; } - else { + else + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -348,8 +376,10 @@ ); } - if (this.tint !== 0xFFFFFF) { - if (this.cachedTint !== this.tint) { + if (this.tint !== 0xFFFFFF) + { + if (this.cachedTint !== this.tint) + { this.cachedTint = this.tint; // TODO clean up caching - how to clean up the caches? @@ -368,7 +398,8 @@ this.texture.crop.height / resolution ); } - else { + else + { renderer.context.drawImage( this.texture.baseTexture.source, this.texture.crop.x, @@ -383,11 +414,13 @@ } } - for (var i = 0, j = this.children.length; i < j; i++) { + for (var i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -402,10 +435,12 @@ * @param frameId {String} The frame Id of the texture in the cache * @return {Sprite} A new Sprite using a texture from the texture cache matching the frameId */ -Sprite.fromFrame = function (frameId) { +Sprite.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache' + this); } @@ -420,6 +455,7 @@ * @param imageId {String} The image url of the texture * @return {Sprite} A new Sprite using a texture from the texture cache matching the image id */ -Sprite.fromImage = function (imageId, crossorigin, scaleMode) { +Sprite.fromImage = function (imageId, crossorigin, scaleMode) +{ return new Sprite(Texture.fromImage(imageId, crossorigin, scaleMode)); }; diff --git a/src/core/display/SpriteBatch.js b/src/core/display/SpriteBatch.js index 3187777..c196fef 100644 --- a/src/core/display/SpriteBatch.js +++ b/src/core/display/SpriteBatch.js @@ -12,7 +12,8 @@ * ```js * var container = new SpriteBatch(); * - * for(var i = 0; i < 100; ++i) { + * for(var i = 0; i < 100; ++i) + * { * var sprite = new PIXI.Sprite.fromImage("myImage.png"); * container.addChild(sprite); * } @@ -25,7 +26,8 @@ */ //TODO RENAME to PARTICLE CONTAINER? -function SpriteBatch() { +function SpriteBatch() +{ DisplayObjectContainer.call(this); } @@ -38,7 +40,8 @@ * * @private */ -SpriteBatch.prototype.updateTransform = function () { +SpriteBatch.prototype.updateTransform = function () +{ // TODO don't need to! this.displayObjectUpdateTransform(); // PIXI.DisplayObjectContainer.prototype.updateTransform.call( this ); @@ -50,8 +53,10 @@ * @param renderer {WebGLRenderer} The webgl renderer * @private */ -SpriteBatch.prototype.renderWebGL = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderWebGL = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -71,8 +76,10 @@ * @param renderer {CanvasRenderer} The canvas renderer * @private */ -SpriteBatch.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -84,10 +91,12 @@ this.displayObjectUpdateTransform(); - for (var i = 0; i < this.children.length; ++i) { + for (var i = 0; i < this.children.length; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -95,9 +104,11 @@ context.globalAlpha = this.worldAlpha * child.alpha; - if (child.rotation % (Math.PI * 2) === 0) { + if (child.rotation % (Math.PI * 2) === 0) + { // this is the fastest way to optimise! - if rotation is 0 then we can avoid any kind of setTransform call - if (isRotated) { + if (isRotated) + { context.setTransform( transform.a, transform.b, @@ -122,8 +133,10 @@ frame.height * child.scale.y ); } - else { - if (!isRotated) { + else + { + if (!isRotated) + { isRotated = true; } @@ -131,7 +144,8 @@ var childTransform = child.worldTransform; - if (renderer.roundPixels) { + if (renderer.roundPixels) + { context.setTransform( childTransform.a, childTransform.b, @@ -141,7 +155,8 @@ childTransform.ty | 0 ); } - else { + else + { context.setTransform( childTransform.a, childTransform.b, diff --git a/src/core/index.js b/src/core/index.js index 3954b6f..eb4a82b 100644 --- a/src/core/index.js +++ b/src/core/index.js @@ -58,11 +58,13 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRenderer: function (width, height, options, noWebGL) { + autoDetectRenderer: function (width, height, options, noWebGL) + { width = width || 800; height = height || 600; - if (!noWebGL && require('webgl-enabled')()) { + if (!noWebGL && require('webgl-enabled')()) + { return new core.WebGLRenderer(width, height, options); } @@ -87,7 +89,8 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRecommendedRenderer: function (width, height, options) { + autoDetectRecommendedRenderer: function (width, height, options) + { var isAndroid = /Android/i.test(navigator.userAgent); return core.autoDetectRenderer(width, height, options, isAndroid); diff --git a/src/core/math/Matrix.js b/src/core/math/Matrix.js index c2f87e2..2ff4848 100644 --- a/src/core/math/Matrix.js +++ b/src/core/math/Matrix.js @@ -10,7 +10,8 @@ * @class * @namespace PIXI */ -function Matrix() { +function Matrix() +{ /** * @member {number} * @default 1 @@ -63,7 +64,8 @@ * * @param array {number[]} The array that the matrix will be populated from. */ -Matrix.prototype.fromArray = function (array) { +Matrix.prototype.fromArray = function (array) +{ this.a = array[0]; this.b = array[1]; this.c = array[3]; @@ -78,14 +80,17 @@ * @param transpose {boolean} Whether we need to transpose the matrix or not * @return {number[]} the newly created array which contains the matrix */ -Matrix.prototype.toArray = function (transpose) { - if (!this.array) { +Matrix.prototype.toArray = function (transpose) +{ + if (!this.array) + { this.array = new Float32Array(9); } var array = this.array; - if (transpose) { + if (transpose) + { array[0] = this.a; array[1] = this.b; array[2] = 0; @@ -96,7 +101,8 @@ array[7] = this.ty; array[8] = 1; } - else { + else + { array[0] = this.a; array[1] = this.c; array[2] = this.tx; @@ -119,7 +125,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, transformed through this matrix */ -Matrix.prototype.apply = function (pos, newPos) { +Matrix.prototype.apply = function (pos, newPos) +{ newPos = newPos || new Point(); newPos.x = this.a * pos.x + this.c * pos.y + this.tx; @@ -136,7 +143,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, inverse-transformed through this matrix */ -Matrix.prototype.applyInverse = function (pos, newPos) { +Matrix.prototype.applyInverse = function (pos, newPos) +{ newPos = newPos || new Point(); var id = 1 / (this.a * this.d + this.c * -this.b); @@ -154,7 +162,8 @@ * @param {number} y * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.translate = function (x, y) { +Matrix.prototype.translate = function (x, y) +{ this.tx += x; this.ty += y; @@ -168,7 +177,8 @@ * @param {number} y The amount to scale vertically * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.scale = function (x, y) { +Matrix.prototype.scale = function (x, y) +{ this.a *= x; this.d *= y; this.c *= x; @@ -186,7 +196,8 @@ * @param {number} angle - The angle in radians. * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.rotate = function (angle) { +Matrix.prototype.rotate = function (angle) +{ var cos = Math.cos( angle ); var sin = Math.sin( angle ); @@ -210,7 +221,8 @@ * @param {Matrix} matrix * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.append = function (matrix) { +Matrix.prototype.append = function (matrix) +{ var a1 = this.a; var b1 = this.b; var c1 = this.c; @@ -232,7 +244,8 @@ * * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.identity = function () { +Matrix.prototype.identity = function () +{ this.a = 1; this.b = 0; this.c = 0; diff --git a/src/core/math/Point.js b/src/core/math/Point.js index 7565b2d..632f346 100644 --- a/src/core/math/Point.js +++ b/src/core/math/Point.js @@ -7,7 +7,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -function Point(x, y) { +function Point(x, y) +{ /** * @member {number} * @default 0 @@ -29,7 +30,8 @@ * * @return {Point} a copy of the point */ -Point.prototype.clone = function () { +Point.prototype.clone = function () +{ return new Point(this.x, this.y); }; @@ -40,7 +42,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -Point.prototype.set = function (x, y) { +Point.prototype.set = function (x, y) +{ this.x = x || 0; this.y = y || ( (y !== 0) ? this.x : 0 ) ; }; diff --git a/src/core/math/shapes/Circle.js b/src/core/math/shapes/Circle.js index 69cfdc9..4d76efc 100644 --- a/src/core/math/shapes/Circle.js +++ b/src/core/math/shapes/Circle.js @@ -10,7 +10,8 @@ * @param y {number} The Y coordinate of the center of this circle * @param radius {number} The radius of the circle */ -function Circle(x, y, radius) { +function Circle(x, y, radius) +{ /** * @member {number} * @default 0 @@ -46,7 +47,8 @@ * @method clone * @return {Circle} a copy of the Circle */ -Circle.prototype.clone = function () { +Circle.prototype.clone = function () +{ return new Circle(this.x, this.y, this.radius); }; @@ -58,8 +60,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Circle */ -Circle.prototype.contains = function (x, y) { - if (this.radius <= 0) { +Circle.prototype.contains = function (x, y) +{ + if (this.radius <= 0) + { return false; } @@ -79,6 +83,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Circle.prototype.getBounds = function () { +Circle.prototype.getBounds = function () +{ return new Rectangle(this.x - this.radius, this.y - this.radius, this.radius * 2, this.radius * 2); }; diff --git a/src/core/math/shapes/Ellipse.js b/src/core/math/shapes/Ellipse.js index 4f2d066..fefd01a 100644 --- a/src/core/math/shapes/Ellipse.js +++ b/src/core/math/shapes/Ellipse.js @@ -11,7 +11,8 @@ * @param width {number} The half width of this ellipse * @param height {number} The half height of this ellipse */ -function Ellipse(x, y, width, height) { +function Ellipse(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -53,7 +54,8 @@ * @method clone * @return {Ellipse} a copy of the ellipse */ -Ellipse.prototype.clone = function () { +Ellipse.prototype.clone = function () +{ return new Ellipse(this.x, this.y, this.width, this.height); }; @@ -65,8 +67,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coords are within this ellipse */ -Ellipse.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Ellipse.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } @@ -86,6 +90,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Ellipse.prototype.getBounds = function () { +Ellipse.prototype.getBounds = function () +{ return new Rectangle(this.x - this.width, this.y - this.height, this.width, this.height); }; diff --git a/src/core/math/shapes/Polygon.js b/src/core/math/shapes/Polygon.js index ae89148..fea6d37 100644 --- a/src/core/math/shapes/Polygon.js +++ b/src/core/math/shapes/Polygon.js @@ -10,16 +10,20 @@ * arguments passed can be flat x,y values e.g. `new Polygon(x,y, x,y, x,y, ...)` where `x` and `y` are * Numbers. */ -function Polygon(points) { +function Polygon(points) +{ //if points isn't an array, use arguments as the array - if (!(points instanceof Array)) { + if (!(points instanceof Array)) + { points = Array.prototype.slice.call(arguments); } //if this is a flat array of numbers, convert it to points - if (points[0] instanceof Point) { + if (points[0] instanceof Point) + { var p = []; - for (var i = 0, il = points.length; i < il; i++) { + for (var i = 0, il = points.length; i < il; i++) + { p.push(points[i].x, points[i].y); } @@ -51,7 +55,8 @@ * * @return {Polygon} a copy of the polygon */ -Polygon.prototype.clone = function () { +Polygon.prototype.clone = function () +{ return new Polygon(this.points.slice()); }; @@ -62,19 +67,22 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this polygon */ -Polygon.prototype.contains = function (x, y) { +Polygon.prototype.contains = function (x, y) +{ var inside = false; // use some raycasting to test hits // https://github.com/substack/point-in-polygon/blob/master/index.js var length = this.points.length / 2; - for (var i = 0, j = length - 1; i < length; j = i++) { + for (var i = 0, j = length - 1; i < length; j = i++) + { var xi = this.points[i * 2], yi = this.points[i * 2 + 1], xj = this.points[j * 2], yj = this.points[j * 2 + 1], intersect = ((yi > y) !== (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi); - if (intersect) { + if (intersect) + { inside = !inside; } } diff --git a/src/core/math/shapes/Rectangle.js b/src/core/math/shapes/Rectangle.js index 16ac62a..4008b68 100644 --- a/src/core/math/shapes/Rectangle.js +++ b/src/core/math/shapes/Rectangle.js @@ -10,7 +10,8 @@ * @param width {number} The overall width of this rectangle * @param height {number} The overall height of this rectangle */ -function Rectangle(x, y, width, height) { +function Rectangle(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -60,7 +61,8 @@ * * @return {Rectangle} a copy of the rectangle */ -Rectangle.prototype.clone = function () { +Rectangle.prototype.clone = function () +{ return new Rectangle(this.x, this.y, this.width, this.height); }; @@ -71,13 +73,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rectangle */ -Rectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Rectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/math/shapes/RoundedRectangle.js b/src/core/math/shapes/RoundedRectangle.js index 27d286e..7bf6411 100644 --- a/src/core/math/shapes/RoundedRectangle.js +++ b/src/core/math/shapes/RoundedRectangle.js @@ -11,7 +11,8 @@ * @param height {number} The overall height of this rounded rectangle * @param radius {number} Controls the radius of the rounded corners */ -function RoundedRectangle(x, y, width, height, radius) { +function RoundedRectangle(x, y, width, height, radius) +{ /** * @member {number} * @default 0 @@ -58,7 +59,8 @@ * * @return {RoundedRectangle} a copy of the rounded rectangle */ -RoundedRectangle.prototype.clone = function () { +RoundedRectangle.prototype.clone = function () +{ return new RoundedRectangle(this.x, this.y, this.width, this.height, this.radius); }; @@ -69,13 +71,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rounded Rectangle */ -RoundedRectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +RoundedRectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/primitives/Graphics.js b/src/core/primitives/Graphics.js index 261c534..e902d2a 100644 --- a/src/core/primitives/Graphics.js +++ b/src/core/primitives/Graphics.js @@ -16,7 +16,8 @@ * @extends DisplayObjectContainer * @namespace PIXI */ -function Graphics() { +function Graphics() +{ DisplayObjectContainer.call(this); this.renderable = true; @@ -154,16 +155,20 @@ * @private */ cacheAsBitmap: { - get: function () { + get: function () + { return this._cacheAsBitmap; }, - set: function (value) { + set: function (value) + { this._cacheAsBitmap = value; - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._generateCachedSprite(); } - else { + else + { this.destroyCachedSprite(); this.dirty = true; } @@ -176,7 +181,8 @@ * * @return {Graphics} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ var clone = new Graphics(); clone.renderable = this.renderable; @@ -192,7 +198,8 @@ clone.cachedSpriteDirty = this.cachedSpriteDirty; // copy graphics data - for (var i = 0; i < this.graphicsData.length; ++i) { + for (var i = 0; i < this.graphicsData.length; ++i) + { clone.graphicsData.push(this.graphicsData.clone()); } @@ -211,17 +218,21 @@ * @param alpha {number} alpha of the line to draw, will update the objects stored style * @return {Graphics} */ -Graphics.prototype.lineStyle = function (lineWidth, color, alpha) { +Graphics.prototype.lineStyle = function (lineWidth, color, alpha) +{ this.lineWidth = lineWidth || 0; this.lineColor = color || 0; this.lineAlpha = (arguments.length < 3) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length) + { // halfway through a line? start a new one! this.drawShape( new math.Polygon( this.currentPath.shape.points.slice(-2) )); } - else { + else + { // otherwise its empty so lets just set the line properties this.currentPath.lineWidth = this.lineWidth; this.currentPath.lineColor = this.lineColor; @@ -239,7 +250,8 @@ * @param y {number} the Y coordinate to move to * @return {Graphics} */ -Graphics.prototype.moveTo = function (x, y) { +Graphics.prototype.moveTo = function (x, y) +{ this.drawShape(new math.Polygon([x,y])); return this; @@ -253,7 +265,8 @@ * @param y {number} the Y coordinate to draw to * @return {Graphics} */ -Graphics.prototype.lineTo = function (x, y) { +Graphics.prototype.lineTo = function (x, y) +{ this.currentPath.shape.points.push(x, y); this.dirty = true; @@ -270,13 +283,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -285,7 +302,8 @@ n = 20, points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { this.moveTo(0, 0); } @@ -293,7 +311,8 @@ var fromY = points[points.length-1]; var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; xa = fromX + ( (cpX - fromX) * j ); @@ -319,13 +338,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -342,7 +365,8 @@ var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; dt = (1 - j); @@ -373,13 +397,17 @@ * @param radius {number} The radius of the arc * @return {Graphics} */ -Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points.push(x1, y1); } } - else { + else + { this.moveTo(x1, y1); } @@ -392,12 +420,15 @@ b2 = x2 - x1, mm = Math.abs(a1 * b2 - b1 * a2); - if (mm < 1.0e-8 || radius === 0) { - if (points[points.length-2] !== x1 || points[points.length-1] !== y1) { + if (mm < 1.0e-8 || radius === 0) + { + if (points[points.length-2] !== x1 || points[points.length-1] !== y1) + { points.push(x1, y1); } } - else { + else + { var dd = a1 * a1 + b1 * b1, cc = a2 * a2 + b2 * b2, tt = a1 * a2 + b1 * b2, @@ -433,42 +464,51 @@ * @param anticlockwise {boolean} Optional. Specifies whether the drawing should be counterclockwise or clockwise. False is default, and indicates clockwise, while true indicates counter-clockwise. * @return {Graphics} */ -Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) { +Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) +{ var startX = cx + Math.cos(startAngle) * radius; var startY = cy + Math.sin(startAngle) * radius; var points; // TODO - This if-else makes no sense. It uses currentPath in the else where it doesn't exist... - if (this.currentPath) { + if (this.currentPath) + { points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { points.push(startX, startY); } - else if (points[points.length-2] !== startX || points[points.length-1] !== startY) { + else if (points[points.length-2] !== startX || points[points.length-1] !== startY) + { points.push(startX, startY); } } - else { + else + { this.moveTo(startX, startY); points = this.currentPath.shape.points; } - if (startAngle === endAngle) { + if (startAngle === endAngle) + { return this; } - if (!anticlockwise && endAngle <= startAngle) { + if (!anticlockwise && endAngle <= startAngle) + { endAngle += Math.PI * 2; } - else if (anticlockwise && startAngle <= endAngle) { + else if (anticlockwise && startAngle <= endAngle) + { startAngle += Math.PI * 2; } var sweep = anticlockwise ? (startAngle - endAngle) *-1 : (endAngle - startAngle); var segs = (Math.abs(sweep)/ (Math.PI * 2)) * 40; - if (sweep === 0) { + if (sweep === 0) + { return this; } @@ -482,7 +522,8 @@ var remainder = ( segMinus % 1 ) / segMinus; - for (var i = 0; i <= segMinus; ++i) { + for (var i = 0; i <= segMinus; ++i) + { var real = i + remainder * i; var angle = ((theta) + startAngle + (theta2 * real)); @@ -506,13 +547,16 @@ * @param alpha {number} the alpha of the fill * @return {Graphics} */ -Graphics.prototype.beginFill = function (color, alpha) { +Graphics.prototype.beginFill = function (color, alpha) +{ this.filling = true; this.fillColor = color || 0; this.fillAlpha = (alpha === undefined) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length <= 2) + { this.currentPath.fill = this.filling; this.currentPath.fillColor = this.fillColor; this.currentPath.fillAlpha = this.fillAlpha; @@ -526,7 +570,8 @@ * * @return {Graphics} */ -Graphics.prototype.endFill = function () { +Graphics.prototype.endFill = function () +{ this.filling = false; this.fillColor = null; this.fillAlpha = 1; @@ -542,7 +587,8 @@ * @param height {number} The height of the rectangle * @return {Graphics} */ -Graphics.prototype.drawRect = function ( x, y, width, height ) { +Graphics.prototype.drawRect = function ( x, y, width, height ) +{ this.drawShape(new math.Rectangle(x,y, width, height)); return this; @@ -556,7 +602,8 @@ * @param height {number} The height of the rectangle * @param radius {number} Radius of the rectangle corners */ -Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) { +Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) +{ this.drawShape(new math.RoundedRectangle(x, y, width, height, radius)); return this; @@ -570,7 +617,8 @@ * @param radius {number} The radius of the circle * @return {Graphics} */ -Graphics.prototype.drawCircle = function (x, y, radius) { +Graphics.prototype.drawCircle = function (x, y, radius) +{ this.drawShape(new math.Circle(x,y, radius)); return this; @@ -585,7 +633,8 @@ * @param height {number} The half height of the ellipse * @return {Graphics} */ -Graphics.prototype.drawEllipse = function (x, y, width, height) { +Graphics.prototype.drawEllipse = function (x, y, width, height) +{ this.drawShape(new math.Ellipse(x, y, width, height)); return this; @@ -597,8 +646,10 @@ * @param path {Array} The path data used to construct the polygon. * @return {Graphics} */ -Graphics.prototype.drawPolygon = function (path) { - if (!(path instanceof Array)) { +Graphics.prototype.drawPolygon = function (path) +{ + if (!(path instanceof Array)) + { path = Array.prototype.slice.call(arguments); } @@ -612,7 +663,8 @@ * * @return {Graphics} */ -Graphics.prototype.clear = function () { +Graphics.prototype.clear = function () +{ this.lineWidth = 0; this.filling = false; @@ -631,7 +683,8 @@ * @param scaleMode {number} Should be one of the scaleMode consts * @return {Texture} a texture of the graphics object */ -Graphics.prototype.generateTexture = function (resolution, scaleMode) { +Graphics.prototype.generateTexture = function (resolution, scaleMode) +{ resolution = resolution || 1; var bounds = this.getBounds(); @@ -655,17 +708,21 @@ * * @param renderer {WebGLRenderer} */ -Graphics.prototype._renderWebGL = function (renderer) { +Graphics.prototype._renderWebGL = function (renderer) +{ // if the sprite is not visible or the alpha is 0 then no need to render this element - if (this.isMask === true) { + if (this.isMask === true) + { return; } // this code may still be needed so leaving for now.. - // + // /* - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture on the gpu too! @@ -681,17 +738,24 @@ return; } - */ - - // check if the webgl graphic needs to be updated - if (this.glDirty) { - this.dirty = true; - this.glDirty = false; - } + else */ - renderer.setObjectRendererer(renderer.graphicsRenderer); - renderer.graphicsRenderer.render(this); + renderer.spriteBatch.stop(); + renderer.blendModeManager.setBlendMode(this.blendMode); + // check blend mode + renderer.blendModeManager.setBlendMode( this.blendMode ); + + // check if the webgl graphic needs to be updated + if (this.glDirty) + { + this.dirty = true; + this.glDirty = false; + } + + WebGLGraphics.renderGraphics(this, renderer); + + renderer.spriteBatch.start(); }; /** @@ -700,14 +764,18 @@ * @param renderer {CanvasRenderer} * @private */ -Graphics.prototype.renderCanvas = function (renderer) { +Graphics.prototype.renderCanvas = function (renderer) +{ // 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.isMask === true) { + if (!this.visible || this.alpha <= 0 || this.isMask === true) + { return; } - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture @@ -723,16 +791,19 @@ return; } - else { + else + { var context = renderer.context; var transform = this.worldTransform; - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } @@ -748,11 +819,13 @@ CanvasGraphics.renderGraphics(this, context); - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } } @@ -763,13 +836,16 @@ * * @return {Rectangle} the rectangular bounding area */ -Graphics.prototype.getBounds = function (matrix) { +Graphics.prototype.getBounds = function (matrix) +{ // return an empty object if the item is a mask! - if (this.isMask) { + if (this.isMask) + { return math.Rectangle.EMPTY; } - if (this.dirty) { + if (this.dirty) + { this.updateLocalBounds(); this.glDirty = true; @@ -841,23 +917,27 @@ * Update the bounds of the object * */ -Graphics.prototype.updateLocalBounds = function () { +Graphics.prototype.updateLocalBounds = function () +{ var minX = Infinity; var maxX = -Infinity; var minY = Infinity; var maxY = -Infinity; - if (this.graphicsData.length) { + if (this.graphicsData.length) + { var shape, points, x, y, w, h; - for (var i = 0; i < this.graphicsData.length; i++) { + for (var i = 0; i < this.graphicsData.length; i++) + { var data = this.graphicsData[i]; var type = data.type; var lineWidth = data.lineWidth; shape = data.shape; - if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) { + if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) + { x = shape.x - lineWidth/2; y = shape.y - lineWidth/2; w = shape.width + lineWidth; @@ -869,7 +949,8 @@ minY = y < minY ? y : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.CIRC) { + else if (type === CONST.SHAPES.CIRC) + { x = shape.x; y = shape.y; w = shape.radius + lineWidth/2; @@ -881,7 +962,8 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.ELIP) { + else if (type === CONST.SHAPES.ELIP) + { x = shape.x; y = shape.y; w = shape.width + lineWidth/2; @@ -893,11 +975,13 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else { + else + { // POLY points = shape.points; - for (var j = 0; j < points.length; j += 2) { + for (var j = 0; j < points.length; j += 2) + { x = points[j]; y = points[j+1]; @@ -910,7 +994,8 @@ } } } - else { + else + { minX = 0; maxX = 0; minY = 0; @@ -931,10 +1016,12 @@ * * @private */ -Graphics.prototype._generateCachedSprite = function () { +Graphics.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { var canvasBuffer = new CanvasBuffer(bounds.width, bounds.height); var texture = Texture.fromCanvas(canvasBuffer.canvas); @@ -943,7 +1030,8 @@ this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.buffer.resize(bounds.width, bounds.height); } @@ -968,7 +1056,8 @@ * * @private */ -Graphics.prototype.updateCachedSpriteTexture = function () { +Graphics.prototype.updateCachedSpriteTexture = function () +{ var cachedSprite = this._cachedSprite; var texture = cachedSprite.texture; var canvas = cachedSprite.buffer.canvas; @@ -989,7 +1078,8 @@ * Destroys a previous cached sprite. * */ -Graphics.prototype.destroyCachedSprite = function () { +Graphics.prototype.destroyCachedSprite = function () +{ this._cachedSprite.texture.destroy(true); // let the gc collect the unused sprite @@ -1003,10 +1093,13 @@ * @param {Circle|Rectangle|Ellipse|Line|Polygon} shape The Shape object to draw. * @return {GraphicsData} The generated GraphicsData object. */ -Graphics.prototype.drawShape = function (shape) { - if (this.currentPath) { +Graphics.prototype.drawShape = function (shape) +{ + if (this.currentPath) + { // check current path! - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath.shape.points.length <= 2) + { this.graphicsData.pop(); } } @@ -1017,7 +1110,8 @@ this.graphicsData.push(data); - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { data.shape.closed = this.filling; this.currentPath = data; } diff --git a/src/core/primitives/GraphicsData.js b/src/core/primitives/GraphicsData.js index 99decbe..788f6f2 100644 --- a/src/core/primitives/GraphicsData.js +++ b/src/core/primitives/GraphicsData.js @@ -4,7 +4,8 @@ * @class * @namespace PIXI */ -function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) { +function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) +{ this.lineWidth = lineWidth; this.lineColor = lineColor; this.lineAlpha = lineAlpha; @@ -27,7 +28,8 @@ * * @return {GraphicsData} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ return new GraphicsData( this.lineWidth, this.lineColor, diff --git a/src/core/renderers/canvas/CanvasRenderer.js b/src/core/renderers/canvas/CanvasRenderer.js index 15a0978..7aebd44 100644 --- a/src/core/renderers/canvas/CanvasRenderer.js +++ b/src/core/renderers/canvas/CanvasRenderer.js @@ -17,17 +17,22 @@ * @param [options.resolution=1] {number} the resolution of the renderer retina would be 2 * @param [options.clearBeforeRender=true] {boolean} This sets if the CanvasRenderer will clear the canvas or not before the new render pass. */ -function CanvasRenderer(width, height, options) { +function CanvasRenderer(width, height, options) +{ utils.sayHello('Canvas'); - if (options) { - for (var i in CONST.defaultRenderOptions) { - if (typeof options[i] === 'undefined') { + if (options) + { + for (var i in CONST.defaultRenderOptions) + { + if (typeof options[i] === 'undefined') + { options[i] = CONST.defaultRenderOptions[i]; } } } - else { + else + { options = CONST.defaultRenderOptions; } @@ -156,19 +161,24 @@ this.smoothProperty = null; - if (this.context.imageSmoothingEnabled) { + if (this.context.imageSmoothingEnabled) + { this.smoothProperty = 'imageSmoothingEnabled'; } - else if (this.context.webkitImageSmoothingEnabled) { + else if (this.context.webkitImageSmoothingEnabled) + { this.smoothProperty = 'webkitImageSmoothingEnabled'; } - else if (this.context.mozImageSmoothingEnabled) { + else if (this.context.mozImageSmoothingEnabled) + { this.smoothProperty = 'mozImageSmoothingEnabled'; } - else if (this.context.oImageSmoothingEnabled) { + else if (this.context.oImageSmoothingEnabled) + { this.smoothProperty = 'oImageSmoothingEnabled'; } - else if (this.context.msImageSmoothingEnabled) { + else if (this.context.msImageSmoothingEnabled) + { this.smoothProperty = 'msImageSmoothingEnabled'; } @@ -193,10 +203,12 @@ * @memberof CanvasRenderer# */ backgroundColor: { - get: function () { + get: function () + { return this._backgroundColor; }, - set: function (val) { + set: function (val) + { this._backgroundColor = val; this._backgroundColorString = utils.hex2string(val); } @@ -208,7 +220,8 @@ * * @param object {DisplayObject} the object to be rendered */ -CanvasRenderer.prototype.render = function (object) { +CanvasRenderer.prototype.render = function (object) +{ object.updateTransform(); this.context.setTransform(1,0,0,1,0,0); @@ -218,16 +231,20 @@ this.currentBlendMode = CONST.blendModes.NORMAL; this.context.globalCompositeOperation = this.blendModes[CONST.blendModes.NORMAL]; - if (navigator.isCocoonJS && this.view.screencanvas) { + if (navigator.isCocoonJS && this.view.screencanvas) + { this.context.fillStyle = 'black'; this.context.clear(); } - if (this.clearBeforeRender) { - if (this.transparent) { + if (this.clearBeforeRender) + { + if (this.transparent) + { this.context.clearRect(0, 0, this.width, this.height); } - else { + else + { this.context.fillStyle = this._backgroundColorString; this.context.fillRect(0, 0, this.width , this.height); } @@ -241,8 +258,10 @@ * * @param [removeView=false] {boolean} Removes the Canvas element from the DOM. */ -CanvasRenderer.prototype.destroy = function (removeView) { - if (removeView && this.view.parent) { +CanvasRenderer.prototype.destroy = function (removeView) +{ + if (removeView && this.view.parent) + { this.view.parent.removeChild(this.view); } @@ -257,14 +276,16 @@ * @param width {number} the new width of the canvas view * @param height {number} the new height of the canvas view */ -CanvasRenderer.prototype.resize = function (width, height) { +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) { + if (this.autoResize) + { this.view.style.width = this.width / this.resolution + 'px'; this.view.style.height = this.height / this.resolution + 'px'; } @@ -276,7 +297,8 @@ * @param displayObject {DisplayObject} The displayObject to render * @private */ -CanvasRenderer.prototype.renderDisplayObject = function (displayObject) { +CanvasRenderer.prototype.renderDisplayObject = function (displayObject) +{ displayObject.renderCanvas(this); }; @@ -285,11 +307,14 @@ * * @private */ -CanvasRenderer.prototype._mapBlendModes = function () { - if (!this.blendModes) { +CanvasRenderer.prototype._mapBlendModes = function () +{ + if (!this.blendModes) + { this.blendModes = {}; - if (utils.canUseNewCanvasBlendModes()) { + if (utils.canUseNewCanvasBlendModes()) + { this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? this.blendModes[CONST.blendModes.MULTIPLY] = 'multiply'; @@ -308,7 +333,8 @@ this.blendModes[CONST.blendModes.COLOR] = 'color'; this.blendModes[CONST.blendModes.LUMINOSITY] = 'luminosity'; } - else { + else + { // this means that the browser does not support the cool new blend modes in canvas 'cough' ie 'cough' this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? diff --git a/src/core/renderers/canvas/utils/CanvasBuffer.js b/src/core/renderers/canvas/utils/CanvasBuffer.js index ebe5d47..b183a66 100644 --- a/src/core/renderers/canvas/utils/CanvasBuffer.js +++ b/src/core/renderers/canvas/utils/CanvasBuffer.js @@ -6,7 +6,8 @@ * @param width {number} the width for the newly created canvas * @param height {number} the height for the newly created canvas */ -function CanvasBuffer(width, height) { +function CanvasBuffer(width, height) +{ /** * The Canvas object that belongs to this CanvasBuffer. * @@ -36,10 +37,12 @@ * @memberof CanvasBuffer# */ width: { - get: function () { + get: function () + { return this.canvas.width; }, - set: function (val) { + set: function (val) + { this.canvas.width = val; } }, @@ -50,10 +53,12 @@ * @memberof CanvasBuffer# */ height: { - get: function () { + get: function () + { return this.canvas.height; }, - set: function (val) { + set: function (val) + { this.canvas.height = val; } } @@ -64,7 +69,8 @@ * * @private */ -CanvasBuffer.prototype.clear = function () { +CanvasBuffer.prototype.clear = function () +{ this.context.setTransform(1, 0, 0, 1, 0, 0); this.context.clearRect(0,0, this.canvas.width, this.canvas.height); }; @@ -75,7 +81,8 @@ * @param width {number} the new width of the canvas * @param height {number} the new height of the canvas */ -CanvasBuffer.prototype.resize = function (width, height) { +CanvasBuffer.prototype.resize = function (width, height) +{ this.canvas.width = width; this.canvas.height = height; }; diff --git a/src/core/renderers/canvas/utils/CanvasGraphics.js b/src/core/renderers/canvas/utils/CanvasGraphics.js index c7eaa2a..3f2a91f 100644 --- a/src/core/renderers/canvas/utils/CanvasGraphics.js +++ b/src/core/renderers/canvas/utils/CanvasGraphics.js @@ -13,15 +13,18 @@ * @param graphics {Graphics} the actual graphics object to render * @param context {CanvasRenderingContext2D} the 2d drawing method of the canvas */ -CanvasGraphics.renderGraphics = function (graphics, context) { +CanvasGraphics.renderGraphics = function (graphics, context) +{ var worldAlpha = graphics.worldAlpha; - if (graphics.dirty) { + if (graphics.dirty) + { this.updateGraphicsTint(graphics); graphics.dirty = false; } - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; @@ -30,69 +33,82 @@ context.lineWidth = data.lineWidth; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { context.beginPath(); var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } - if (shape.closed) { + if (shape.closed) + { context.lineTo(points[0], points[1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fillRect(shape.x, shape.y, shape.width, shape.height); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.strokeRect(shape.x, shape.y, shape.width, shape.height); } } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.beginPath(); context.arc(shape.x, shape.y, shape.radius,0,2*Math.PI); context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas var w = shape.width * 2; @@ -119,18 +135,21 @@ context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; var width = shape.width; @@ -152,13 +171,15 @@ context.quadraticCurveTo(rx, ry, rx, ry + radius); context.closePath(); - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); @@ -174,45 +195,54 @@ * @param graphics {Graphics} the graphics which will be used as a mask * @param context {CanvasRenderingContext2D} the context 2d method of the canvas */ -CanvasGraphics.renderGraphicsMask = function (graphics, context) { +CanvasGraphics.renderGraphicsMask = function (graphics, context) +{ var len = graphics.graphicsData.length; - if (len === 0) { + if (len === 0) + { return; } context.beginPath(); - for (var i = 0; i < len; i++) { + for (var i = 0; i < len; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { context.rect(shape.x, shape.y, shape.width, shape.height); context.closePath(); } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.arc(shape.x, shape.y, shape.radius, 0, 2 * Math.PI); context.closePath(); } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas @@ -237,7 +267,8 @@ context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); context.closePath(); } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; @@ -262,8 +293,10 @@ } }; -CanvasGraphics.updateGraphicsTint = function (graphics) { - if (graphics.tint === 0xFFFFFF) { +CanvasGraphics.updateGraphicsTint = function (graphics) +{ + if (graphics.tint === 0xFFFFFF) + { return; } @@ -271,7 +304,8 @@ var tintG = (graphics.tint >> 8 & 0xFF) / 255; var tintB = (graphics.tint & 0xFF)/ 255; - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var fillColor = data.fillColor | 0; diff --git a/src/core/renderers/canvas/utils/CanvasMaskManager.js b/src/core/renderers/canvas/utils/CanvasMaskManager.js index e04a733..9827d36 100644 --- a/src/core/renderers/canvas/utils/CanvasMaskManager.js +++ b/src/core/renderers/canvas/utils/CanvasMaskManager.js @@ -6,7 +6,8 @@ * @class * @namespace PIXI */ -function CanvasMaskManager() {} +function CanvasMaskManager() +{} CanvasMaskManager.prototype.constructor = CanvasMaskManager; module.exports = CanvasMaskManager; @@ -17,7 +18,8 @@ * @param maskData {object} the maskData that will be pushed * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.pushMask = function (maskData, renderer) { +CanvasMaskManager.prototype.pushMask = function (maskData, renderer) +{ renderer.context.save(); var cacheAlpha = maskData.alpha; @@ -45,6 +47,7 @@ * * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.popMask = function (renderer) { +CanvasMaskManager.prototype.popMask = function (renderer) +{ renderer.context.restore(); }; diff --git a/src/core/renderers/canvas/utils/CanvasTinter.js b/src/core/renderers/canvas/utils/CanvasTinter.js index 17e0529..d2fb1bc 100644 --- a/src/core/renderers/canvas/utils/CanvasTinter.js +++ b/src/core/renderers/canvas/utils/CanvasTinter.js @@ -14,7 +14,8 @@ * @param color {number} the color to use to tint the sprite with * @return {HTMLCanvasElement} The tinted canvas */ -CanvasTinter.getTintedTexture = function (sprite, color) { +CanvasTinter.getTintedTexture = function (sprite, color) +{ var texture = sprite.texture; color = CanvasTinter.roundColor(color); @@ -23,7 +24,8 @@ texture.tintCache = texture.tintCache || {}; - if (texture.tintCache[stringColor]) { + if (texture.tintCache[stringColor]) + { return texture.tintCache[stringColor]; } @@ -33,14 +35,16 @@ //CanvasTinter.tintWithPerPixel(texture, stringColor, canvas); CanvasTinter.tintMethod(texture, color, canvas); - if (CanvasTinter.convertTintToImage) { + if (CanvasTinter.convertTintToImage) + { // is this better? var tintImage = new Image(); tintImage.src = canvas.toDataURL(); texture.tintCache[stringColor] = tintImage; } - else { + else + { texture.tintCache[stringColor] = canvas; // if we are not converting the texture to an image then we need to lose the reference to the canvas CanvasTinter.canvas = null; @@ -56,7 +60,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithMultiply = function (texture, color, canvas) { +CanvasTinter.tintWithMultiply = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -104,7 +109,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithOverlay = function (texture, color, canvas) { +CanvasTinter.tintWithOverlay = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -139,7 +145,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithPerPixel = function (texture, color, canvas) { +CanvasTinter.tintWithPerPixel = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -167,7 +174,8 @@ var pixels = pixelData.data; - for (var i = 0; i < pixels.length; i += 4) { + for (var i = 0; i < pixels.length; i += 4) + { pixels[i+0] *= r; pixels[i+1] *= g; pixels[i+2] *= b; @@ -181,7 +189,8 @@ * * @param color {number} the color to round, should be a hex color */ -CanvasTinter.roundColor = function (color) { +CanvasTinter.roundColor = function (color) +{ var step = CanvasTinter.cacheStepsPerColorChannel; var rgbValues = utils.hex2rgb(color); diff --git a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js index 9f2f89a..35edbaf 100644 --- a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js +++ b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLBlendModeManager(renderer) { +function WebGLBlendModeManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -23,8 +24,10 @@ * * @param blendMode {number} the blendMode, should be a Pixi const, such as BlendModes.ADD */ -WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) { - if (this.currentBlendMode === blendMode) { +WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) +{ + if (this.currentBlendMode === blendMode) + { return false; } diff --git a/src/core/renderers/webgl/managers/WebGLFilterManager.js b/src/core/renderers/webgl/managers/WebGLFilterManager.js index 1179258..2dac048 100644 --- a/src/core/renderers/webgl/managers/WebGLFilterManager.js +++ b/src/core/renderers/webgl/managers/WebGLFilterManager.js @@ -7,7 +7,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLFilterManager(renderer) { +function WebGLFilterManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -32,7 +33,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.texturePool.length = 0; self.initShaderBuffers(); }); @@ -46,7 +48,8 @@ * @param renderer {WebGLRenderer} * @param buffer {ArrayBuffer} */ -WebGLFilterManager.prototype.begin = function (buffer) { +WebGLFilterManager.prototype.begin = function (buffer) +{ this.defaultShader = this.renderer.shaderManager.defaultShader; this.width = this.renderer.projection.x * 2; @@ -60,7 +63,8 @@ * * @param filterBlock {object} the filter that will be pushed to the current filter stack */ -WebGLFilterManager.prototype.pushFilter = function (filterBlock) { +WebGLFilterManager.prototype.pushFilter = function (filterBlock) +{ var gl = this.renderer.gl; var projection = this.renderer.projection; @@ -78,10 +82,12 @@ this.offsetY += filterBlock._filterArea.y; var texture = this.texturePool.pop(); - if (!texture) { + if (!texture) + { texture = new FilterTexture(this.renderer.gl, this.width, this.height); } - else { + else + { texture.resize(this.width, this.height); } @@ -98,29 +104,35 @@ var localX = filterArea.x, localY = filterArea.y; - if (filterArea.x < 0) { + if (filterArea.x < 0) + { filterArea.width += filterArea.x; filterArea.x = 0; } - if (filterArea.y < 0) { + if (filterArea.y < 0) + { filterArea.height += filterArea.y; filterArea.y = 0; } - if (localX + filterArea.width > this.width) { + if (localX + filterArea.width > this.width) + { filterArea.width = this.width - localX; } - if (localY + filterArea.height > this.height) { + if (localY + filterArea.height > this.height) + { filterArea.height = this.height - localY; } - if (filterArea.width < 0) { + if (filterArea.width < 0) + { filterArea.width = 0; } - if (filterArea.height < 0) { + if (filterArea.height < 0) + { filterArea.height = 0; } @@ -154,7 +166,8 @@ * Removes the last filter from the filter stack and doesn't return it. * */ -WebGLFilterManager.prototype.popFilter = function () { +WebGLFilterManager.prototype.popFilter = function () +{ var gl = this.renderer.gl; var filterBlock = this.filterStack.pop(); @@ -163,7 +176,8 @@ var projection = this.renderer.projection; var offset = this.renderer.offset; - if (filterBlock.filterPasses.length > 1) { + if (filterBlock.filterPasses.length > 1) + { gl.viewport(0, 0, filterArea.width, filterArea.height); gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); @@ -193,7 +207,8 @@ var inputTexture = texture; var outputTexture = this.texturePool.pop(); - if (!outputTexture) { + if (!outputTexture) + { outputTexture = new FilterTexture(this.renderer.gl, this.width, this.height); } outputTexture.resize(this.width, this.height); @@ -204,7 +219,8 @@ gl.disable(gl.BLEND); - for (var i = 0; i < filterBlock.filterPasses.length-1; i++) { + for (var i = 0; i < filterBlock.filterPasses.length-1; i++) + { var filterPass = filterBlock.filterPasses[i]; gl.bindFramebuffer(gl.FRAMEBUFFER, outputTexture.frameBuffer ); @@ -243,10 +259,12 @@ var buffer = this.buffer; // time to render the filters texture to the previous scene - if (this.filterStack.length === 0) { + if (this.filterStack.length === 0) + { gl.colorMask(true, true, true, true);//this.transparent); } - else { + else + { var currentFilter = this.filterStack[this.filterStack.length-1]; filterArea = currentFilter._filterArea; @@ -332,13 +350,15 @@ * @param width {number} the horizontal range of the filter * @param height {number} the vertical range of the filter */ -WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) { +WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) +{ // use program var gl = this.renderer.gl; var shader = filter.shaders[gl.id]; - if (!shader) { + if (!shader) + { shader = new Shader(gl); shader.fragmentSrc = filter.fragmentSrc; @@ -356,7 +376,8 @@ gl.uniform2f(shader.projectionVector, width/2, -height/2); gl.uniform2f(shader.offsetVector, 0,0); - if (filter.uniforms.dimensions) { + 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]; @@ -386,7 +407,8 @@ * Initialises the shader buffers. * */ -WebGLFilterManager.prototype.initShaderBuffers = function () { +WebGLFilterManager.prototype.initShaderBuffers = function () +{ var gl = this.renderer.gl; // create some buffers @@ -432,7 +454,8 @@ * Destroys the filter and removes it from the filter stack. * */ -WebGLFilterManager.prototype.destroy = function () { +WebGLFilterManager.prototype.destroy = function () +{ var gl = this.renderer.gl; this.filterStack = null; @@ -441,7 +464,8 @@ this.offsetY = 0; // destroy textures - for (var i = 0; i < this.texturePool.length; i++) { + for (var i = 0; i < this.texturePool.length; i++) + { this.texturePool[i].destroy(); } diff --git a/src/core/renderers/webgl/managers/WebGLManager.js b/src/core/renderers/webgl/managers/WebGLManager.js index 9d47b5c..c30cd51 100644 --- a/src/core/renderers/webgl/managers/WebGLManager.js +++ b/src/core/renderers/webgl/managers/WebGLManager.js @@ -3,7 +3,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLManager(renderer) { +function WebGLManager(renderer) +{ /** * The renderer this manager works for. * @@ -15,6 +16,7 @@ WebGLManager.prototype.constructor = WebGLManager; module.exports = WebGLManager; -WebGLManager.prototype.destroy = function () { +WebGLManager.prototype.destroy = function () +{ this.renderer = null; }; diff --git a/src/core/renderers/webgl/managers/WebGLMaskManager.js b/src/core/renderers/webgl/managers/WebGLMaskManager.js index 2f90b64..e568812 100644 --- a/src/core/renderers/webgl/managers/WebGLMaskManager.js +++ b/src/core/renderers/webgl/managers/WebGLMaskManager.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLMaskManager(renderer) { +function WebGLMaskManager(renderer) +{ WebGLManager.call(this, renderer); } @@ -19,12 +20,15 @@ * * @param maskData {any[]} */ -WebGLMaskManager.prototype.pushMask = function (maskData) { - if (maskData.dirty) { +WebGLMaskManager.prototype.pushMask = function (maskData) +{ + if (maskData.dirty) + { WebGLGraphics.updateGraphics(maskData, this.renderer.gl); } - if (!maskData._webGL[this.renderer.gl.id].data.length) { + if (!maskData._webGL[this.renderer.gl.id].data.length) + { return; } @@ -36,6 +40,7 @@ * * @param maskData {any[]} */ -WebGLMaskManager.prototype.popMask = function (maskData) { +WebGLMaskManager.prototype.popMask = function (maskData) +{ this.renderer.stencilManager.popStencil(maskData, maskData._webGL[this.renderer.gl.id].data[0], this.renderer); }; diff --git a/src/core/renderers/webgl/managers/WebGLShaderManager.js b/src/core/renderers/webgl/managers/WebGLShaderManager.js index fef071c..90c6477 100644 --- a/src/core/renderers/webgl/managers/WebGLShaderManager.js +++ b/src/core/renderers/webgl/managers/WebGLShaderManager.js @@ -10,7 +10,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLShaderManager(renderer) { +function WebGLShaderManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -28,7 +29,8 @@ */ this.tempAttribState = []; - for (var i = 0; i < this.maxAttibs; i++) { + for (var i = 0; i < this.maxAttibs; i++) + { this.attribState[i] = false; } @@ -66,7 +68,8 @@ // listen for context and update necessary shaders var self = this; - this.renderer.on('context', function (event) { + this.renderer.on('context', function (event) + { var gl = event.data; // this shader is used for rendering primitives @@ -97,29 +100,36 @@ * * @param attribs {Array} attribs */ -WebGLShaderManager.prototype.setAttribs = function (attribs) { +WebGLShaderManager.prototype.setAttribs = function (attribs) +{ // reset temp state var i; - for (i = 0; i < this.tempAttribState.length; i++) { + for (i = 0; i < this.tempAttribState.length; i++) + { this.tempAttribState[i] = false; } // set the new attribs - for (var a in attribs) { + for (var a in attribs) + { this.tempAttribState[attribs[a]] = true; } var gl = this.renderer.gl; - for (i = 0; i < this.attribState.length; i++) { - if (this.attribState[i] !== this.tempAttribState[i]) { + for (i = 0; i < this.attribState.length; i++) + { + if (this.attribState[i] !== this.tempAttribState[i]) + { this.attribState[i] = this.tempAttribState[i]; - if (this.attribState[i]) { + if (this.attribState[i]) + { gl.enableVertexAttribArray(i); } - else { + else + { gl.disableVertexAttribArray(i); } } @@ -131,8 +141,10 @@ * * @param shader {Any} */ -WebGLShaderManager.prototype.setShader = function (shader) { - if (this._currentId === shader.uuid) { +WebGLShaderManager.prototype.setShader = function (shader) +{ + if (this._currentId === shader.uuid) + { return false; } @@ -150,7 +162,8 @@ * Destroys this object. * */ -WebGLShaderManager.prototype.destroy = function () { +WebGLShaderManager.prototype.destroy = function () +{ this.attribState = null; this.tempAttribState = null; diff --git a/src/core/display/DisplayObject.js b/src/core/display/DisplayObject.js index 66ebc3c..20e778c 100644 --- a/src/core/display/DisplayObject.js +++ b/src/core/display/DisplayObject.js @@ -7,7 +7,8 @@ * @class * @namespace PIXI */ -function DisplayObject() { +function DisplayObject() +{ /** * The coordinate of the object relative to the local coordinates of the parent. * @@ -152,10 +153,12 @@ * @memberof DisplayObject# */ x: { - get: function () { + get: function () + { return this.position.x; }, - set: function (value) { + set: function (value) + { this.position.x = value; } }, @@ -167,10 +170,12 @@ * @memberof DisplayObject# */ y: { - get: function () { + get: function () + { return this.position.y; }, - set: function (value) { + set: function (value) + { this.position.y = value; } }, @@ -183,11 +188,13 @@ * @readonly */ worldVisible: { - get: function () { + get: function () + { var item = this; do { - if (!item.visible) { + if (!item.visible) + { return false; } @@ -207,17 +214,21 @@ * @memberof DisplayObject# */ mask: { - get: function () { + get: function () + { return this._mask; }, - set: function (value) { - if (this._mask) { + set: function (value) + { + if (this._mask) + { this._mask.isMask = false; } this._mask = value; - if (this._mask) { + if (this._mask) + { this._mask.isMask = true; } } @@ -232,18 +243,23 @@ * @memberof DisplayObject# */ filters: { - get: function () { + get: function () + { return this._filters; }, - set: function (value) { - if (value) { + set: function (value) + { + if (value) + { // now put all the passes in one place.. var passes = []; - for (var i = 0; i < value.length; i++) { + for (var i = 0; i < value.length; i++) + { var filterPasses = value[i].passes; - for (var j = 0; j < filterPasses.length; j++) { + for (var j = 0; j < filterPasses.length; j++) + { passes.push(filterPasses[j]); } } @@ -264,8 +280,9 @@ * * @private */ -DisplayObject.prototype.updateTransform = function () { - +DisplayObject.prototype.updateTransform = function () +{ + // create some matrix refs for easy access var pt = this.parent.worldTransform; var wt = this.worldTransform; @@ -274,9 +291,11 @@ var a, b, c, d, tx, ty; // so if rotation is between 0 then we can simplify the multiplication process.. - if (this.rotation % math.PI_2) { + if (this.rotation % math.PI_2) + { // 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) { + if (this.rotation !== this.rotationCache) + { this.rotationCache = this.rotation; this._sr = Math.sin(this.rotation); this._cr = Math.cos(this.rotation); @@ -291,7 +310,8 @@ ty = this.position.y; // check for pivot.. not often used so geared towards that fact! - if (this.pivot.x || this.pivot.y) { + 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; } @@ -304,7 +324,8 @@ wt.tx = tx * pt.a + ty * pt.c + pt.tx; wt.ty = tx * pt.b + ty * pt.d + pt.ty; } - else { + else + { // lets do the fast version as we know there is no rotation.. a = this.scale.x; d = this.scale.y; @@ -333,7 +354,8 @@ * @param matrix {Matrix} * @return {Rectangle} the rectangular bounding area */ -DisplayObject.prototype.getBounds = function (/* matrix */) { +DisplayObject.prototype.getBounds = function (/* matrix */) +{ return math.Rectangle.EMPTY; }; @@ -342,7 +364,8 @@ * * @return {Rectangle} the rectangular bounding area */ -DisplayObject.prototype.getLocalBounds = function () { +DisplayObject.prototype.getLocalBounds = function () +{ return this.getBounds(math.Matrix.IDENTITY); }; @@ -352,7 +375,8 @@ * @param position {Point} The world origin to calculate from * @return {Point} A point object representing the position of this object */ -DisplayObject.prototype.toGlobal = function (position) { +DisplayObject.prototype.toGlobal = function (position) +{ // don't need to u[date the lot this.displayObjectUpdateTransform(); return this.worldTransform.apply(position); @@ -365,8 +389,10 @@ * @param [from] {DisplayObject} The DisplayObject to calculate the global position from * @return {Point} A point object representing the position of this object */ -DisplayObject.prototype.toLocal = function (position, from) { - if (from) { +DisplayObject.prototype.toLocal = function (position, from) +{ + if (from) + { position = from.toGlobal(position); } @@ -381,7 +407,8 @@ * @param renderer {WebGLRenderer} The renderer * @private */ -DisplayObject.prototype.renderWebGL = function (/* renderer */) { +DisplayObject.prototype.renderWebGL = function (/* renderer */) +{ // OVERWRITE; }; @@ -391,6 +418,7 @@ * @param renderer {CanvasRenderer} The renderer * @private */ -DisplayObject.prototype.renderCanvas = function (/* renderer */) { +DisplayObject.prototype.renderCanvas = function (/* renderer */) +{ // OVERWRITE; }; diff --git a/src/core/display/DisplayObjectContainer.js b/src/core/display/DisplayObjectContainer.js index 689f40b..4625ee8 100644 --- a/src/core/display/DisplayObjectContainer.js +++ b/src/core/display/DisplayObjectContainer.js @@ -12,7 +12,8 @@ * @extends DisplayObject * @namespace PIXI */ -function DisplayObjectContainer() { +function DisplayObjectContainer() +{ DisplayObject.call(this); /** @@ -47,17 +48,21 @@ * @memberof DisplayObjectContainer# */ width: { - get: function () { + get: function () + { return this.scale.x * this.getLocalBounds().width; }, - set: function (value) { + set: function (value) + { var width = this.getLocalBounds().width; - if(width !== 0) { + if(width !== 0) + { this.scale.x = value / width; } - else { + else + { this.scale.x = 1; } @@ -73,17 +78,21 @@ * @memberof DisplayObjectContainer# */ height: { - get: function () { + get: function () + { return this.scale.y * this.getLocalBounds().height; }, - set: function (value) { + set: function (value) + { var height = this.getLocalBounds().height; - if (height !== 0) { + if (height !== 0) + { this.scale.y = value / height ; } - else { + else + { this.scale.y = 1; } @@ -100,18 +109,23 @@ * @memberof DisplayObject# */ cacheAsBitmap: { - get: function () { + get: function () + { return this._cacheAsBitmap; }, - set: function (value) { - if (this._cacheAsBitmap === value) { + set: function (value) + { + if (this._cacheAsBitmap === value) + { return; } - if (value) { + if (value) + { this._generateCachedSprite(); } - else { + else + { this._destroyCachedSprite(); } @@ -126,7 +140,8 @@ * @param child {DisplayObject} The DisplayObject to add to the container * @return {DisplayObject} The child that was added. */ -DisplayObjectContainer.prototype.addChild = function (child) { +DisplayObjectContainer.prototype.addChild = function (child) +{ return this.addChildAt(child, this.children.length); }; @@ -137,14 +152,18 @@ * @param index {Number} The index to place the child in * @return {DisplayObject} The child that was added. */ -DisplayObjectContainer.prototype.addChildAt = function (child, index) { +DisplayObjectContainer.prototype.addChildAt = function (child, index) +{ // prevent adding self as child - if (child === this) { + if (child === this) + { return; } - if (index >= 0 && index <= this.children.length) { - if (child.parent) { + if (index >= 0 && index <= this.children.length) + { + if (child.parent) + { child.parent.removeChild(child); } @@ -154,7 +173,8 @@ return child; } - else { + else + { throw new Error(child + 'addChildAt: The index '+ index +' supplied is out of bounds ' + this.children.length); } }; @@ -165,15 +185,18 @@ * @param child {DisplayObject} * @param child2 {DisplayObject} */ -DisplayObjectContainer.prototype.swapChildren = function (child, child2) { - if (child === child2) { +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) { + if (index1 < 0 || index2 < 0) + { throw new Error('swapChildren: Both the supplied DisplayObjects must be a child of the caller.'); } @@ -187,10 +210,12 @@ * @param child {DisplayObject} The DisplayObject instance to identify * @return {Number} The index position of the child display object to identify */ -DisplayObjectContainer.prototype.getChildIndex = function (child) { +DisplayObjectContainer.prototype.getChildIndex = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { throw new Error('The supplied DisplayObject must be a child of the caller'); } @@ -203,8 +228,10 @@ * @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 */ -DisplayObjectContainer.prototype.setChildIndex = function (child, index) { - if (index < 0 || index >= this.children.length) { +DisplayObjectContainer.prototype.setChildIndex = function (child, index) +{ + if (index < 0 || index >= this.children.length) + { throw new Error('The supplied index is out of bounds'); } @@ -220,8 +247,10 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child at the given index, if any. */ -DisplayObjectContainer.prototype.getChildAt = function (index) { - if (index < 0 || index >= this.children.length) { +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'); } @@ -234,10 +263,12 @@ * @param child {DisplayObject} The DisplayObject to remove * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChild = function (child) { +DisplayObjectContainer.prototype.removeChild = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { return; } @@ -250,7 +281,8 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChildAt = function (index) { +DisplayObjectContainer.prototype.removeChildAt = function (index) +{ var child = this.getChildAt(index); child.parent = null; @@ -265,24 +297,29 @@ * @param beginIndex {Number} The beginning position. Default value is 0. * @param endIndex {Number} The ending position. Default value is size of the container. */ -DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) { +DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) +{ var begin = beginIndex || 0; var end = typeof endIndex === 'number' ? endIndex : this.children.length; var range = end - begin; - if (range > 0 && range <= end) { + if (range > 0 && range <= end) + { var removed = this.children.splice(begin, range); - for (var i = 0; i < removed.length; ++i) { + for (var i = 0; i < removed.length; ++i) + { removed[i].parent = null; } return removed; } - else if (range === 0 && this.children.length === 0) { + else if (range === 0 && this.children.length === 0) + { return []; } - else { + else + { throw new RangeError('removeChildren: numeric values are outside the acceptable range.'); } }; @@ -291,7 +328,8 @@ * Generates and updates the cached sprite for this object. * */ -DisplayObjectContainer.prototype.updateCachedSprite = function () { +DisplayObjectContainer.prototype.updateCachedSprite = function () +{ this._generateCachedSprite(); }; @@ -304,7 +342,8 @@ * @param renderer {CanvasRenderer|WebGLRenderer} The renderer used to generate the texture. * @return {Texture} a texture of the graphics object */ -DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) { +DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) +{ var bounds = this.getLocalBounds(); var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0, renderer, scaleMode, resolution); @@ -322,18 +361,22 @@ * * @private */ -DisplayObjectContainer.prototype.updateTransform = function () { - if (!this.visible) { +DisplayObjectContainer.prototype.updateTransform = function () +{ + if (!this.visible) + { return; } this.displayObjectUpdateTransform(); - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { return; } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } }; @@ -346,8 +389,10 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getBounds = function () { - if (this.children.length === 0) { +DisplayObjectContainer.prototype.getBounds = function () +{ + if (this.children.length === 0) + { return math.Rectangle.EMPTY; } @@ -365,10 +410,12 @@ var childVisible = false; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -386,7 +433,8 @@ maxY = maxY > childMaxY ? maxY : childMaxY; } - if (!childVisible) { + if (!childVisible) + { return math.Rectangle.EMPTY; } @@ -407,12 +455,14 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getLocalBounds = function () { +DisplayObjectContainer.prototype.getLocalBounds = function () +{ var matrixCache = this.worldTransform; this.worldTransform = math.Matrix.IDENTITY; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } @@ -428,13 +478,16 @@ * * @param renderer {WebGLRenderer} The renderer */ -DisplayObjectContainer.prototype.renderWebGL = function (renderer) { +DisplayObjectContainer.prototype.renderWebGL = function (renderer) +{ // if the object is not visible or the alpha is 0 then no need to render this element - if (!this.visible || this.alpha <= 0) { + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } @@ -442,14 +495,17 @@ var i, j; // do a quick check to see if this element has a mask or a filter. - if (this._mask || this._filters) { + if (this._mask || this._filters) + { // push filter first as we need to ensure the stencil buffer is correct for any masking - if (this._filters) { + if (this._filters) + { renderer.spriteBatch.flush(); renderer.filterManager.pushFilter(this._filterBlock); } - if (this._mask) { + if (this._mask) + { renderer.spriteBatch.stop(); renderer.maskManager.pushMask(this.mask, renderer); renderer.spriteBatch.start(); @@ -459,36 +515,42 @@ this._renderWebGL(renderer); // now loop through the children and make sure they get rendered - for (i = 0, j = this.children.length; i < j; i++) { + for (i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderWebGL(renderer); } // time to stop the sprite batch as either a mask element or a filter draw will happen next renderer.spriteBatch.stop(); - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(this._mask, renderer); } - if (this._filters) { + if (this._filters) + { renderer.filterManager.popFilter(); } renderer.spriteBatch.start(); } - else { + else + { this._renderWebGL(renderer); // simple render children! - for (i = 0, j = this.children.length; i < j; ++i) { + for (i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderWebGL(renderer); } } }; -DisplayObjectContainer.prototype._renderWebGL = function (renderer) { +DisplayObjectContainer.prototype._renderWebGL = function (renderer) +{ // this is where content itself gets renderd.. @@ -499,25 +561,31 @@ * * @param renderer {CanvasRenderer} The renderer */ -DisplayObjectContainer.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0) { +DisplayObjectContainer.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -528,13 +596,16 @@ * @param renderer {WebGLRenderer|CanvasRenderer} The renderer * @private */ -DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) { +DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) +{ this._cachedSprite.worldAlpha = this.worldAlpha; - if (renderer.gl) { + if (renderer.gl) + { this._cachedSprite.renderWebGL(renderer); } - else { + else + { this._cachedSprite.renderCanvas(renderer); } }; @@ -544,10 +615,12 @@ * * @private */ -DisplayObjectContainer.prototype._generateCachedSprite = function () { +DisplayObjectContainer.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { // TODO - RenderTexture now *requires* a renderer instance, so this is like broken // because `renderer` isn't actually in scope here :P var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0); @@ -555,7 +628,8 @@ this._cachedSprite = new Sprite(renderTexture); this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.texture.resize(bounds.width | 0, bounds.height | 0); } @@ -580,8 +654,10 @@ * * @private */ -DisplayObjectContainer.prototype._destroyCachedSprite = function () { - if (!this._cachedSprite) { +DisplayObjectContainer.prototype._destroyCachedSprite = function () +{ + if (!this._cachedSprite) + { return; } diff --git a/src/core/display/Sprite.js b/src/core/display/Sprite.js index 707da24..5862aef 100644 --- a/src/core/display/Sprite.js +++ b/src/core/display/Sprite.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param texture {Texture} The texture for this sprite */ -function Sprite(texture) { +function Sprite(texture) +{ DisplayObjectContainer.call(this); /** @@ -85,12 +86,14 @@ this.texture = texture || Texture.EMPTY; } -Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) { +Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) +{ DisplayObjectContainer.prototype.destroy.call(this); this.anchor = null; - if (destroyTexture) { + if (destroyTexture) + { this._texture.destroy(destroyBaseTexture); } @@ -111,10 +114,12 @@ * @memberof Sprite# */ width: { - get: function () { + get: function () + { return this.scale.x * this.texture.frame.width; }, - set: function (value) { + set: function (value) + { this.scale.x = value / this.texture.frame.width; this._width = value; } @@ -127,10 +132,12 @@ * @memberof Sprite# */ height: { - get: function () { + get: function () + { return this.scale.y * this.texture.frame.height; }, - set: function (value) { + set: function (value) + { this.scale.y = value / this.texture.frame.height; this._height = value; } @@ -143,23 +150,29 @@ * @memberof Sprite# */ texture: { - get: function () { + get: function () + { return this._texture; }, - set: function (value) { - if (this._texture === value) { + set: function (value) + { + if (this._texture === value) + { return; } this._texture = value; this.cachedTint = 0xFFFFFF; - if (value) { + if (value) + { // wait for the texture to load - if (value.baseTexture.hasLoaded) { + if (value.baseTexture.hasLoaded) + { this._onTextureUpdate(); } - else { + else + { value.once('update', this._onTextureUpdate.bind(this)); } } @@ -172,18 +185,22 @@ * * @private */ -Sprite.prototype._onTextureUpdate = function () { +Sprite.prototype._onTextureUpdate = function () +{ // so if _width is 0 then width was not set.. - if (this._width) { + if (this._width) + { this.scale.x = this._width / this.texture.frame.width; } - if (this._height) { + if (this._height) + { this.scale.y = this._height / this.texture.frame.height; } }; -Sprite.prototype._renderWebGL = function (renderer) { +Sprite.prototype._renderWebGL = function (renderer) +{ // this is where content gets renderd.. // watch this space for a little render state manager.. @@ -197,7 +214,8 @@ * @param matrix {Matrix} the transformation matrix of the sprite * @return {Rectangle} the framing rectangle */ -Sprite.prototype.getBounds = function (matrix) { +Sprite.prototype.getBounds = function (matrix) +{ var width = this.texture.frame.width; var height = this.texture.frame.height; @@ -224,11 +242,13 @@ if(b === 0 && c === 0) { // scale may be negative! - if (a < 0) { + if (a < 0) + { a *= -1; } - if (d < 0) { + if (d < 0) + { d *= -1; } @@ -293,28 +313,34 @@ * * @param renderer {CanvasRenderer} The renderer */ -Sprite.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) { +Sprite.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) + { return; } - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; renderer.context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } // Ignore null sources - if (this.texture.valid) { + if (this.texture.valid) + { var resolution = this.texture.baseTexture.resolution / renderer.resolution; renderer.context.globalAlpha = this.worldAlpha; // If smoothingEnabled is supported and we need to change the smoothing property for this texture - if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) { + if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) + { renderer.scaleMode = this.texture.baseTexture.scaleMode; renderer.context[renderer.smoothProperty] = (renderer.scaleMode === CONST.scaleModes.LINEAR); } @@ -324,7 +350,8 @@ var dy = (this.texture.trim ? this.texture.trim.y : 0) - (this.anchor.y * this.texture.trim.height); // Allow for pixel rounding - if (renderer.roundPixels) { + if (renderer.roundPixels) + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -337,7 +364,8 @@ dx = dx | 0; dy = dy | 0; } - else { + else + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -348,8 +376,10 @@ ); } - if (this.tint !== 0xFFFFFF) { - if (this.cachedTint !== this.tint) { + if (this.tint !== 0xFFFFFF) + { + if (this.cachedTint !== this.tint) + { this.cachedTint = this.tint; // TODO clean up caching - how to clean up the caches? @@ -368,7 +398,8 @@ this.texture.crop.height / resolution ); } - else { + else + { renderer.context.drawImage( this.texture.baseTexture.source, this.texture.crop.x, @@ -383,11 +414,13 @@ } } - for (var i = 0, j = this.children.length; i < j; i++) { + for (var i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -402,10 +435,12 @@ * @param frameId {String} The frame Id of the texture in the cache * @return {Sprite} A new Sprite using a texture from the texture cache matching the frameId */ -Sprite.fromFrame = function (frameId) { +Sprite.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache' + this); } @@ -420,6 +455,7 @@ * @param imageId {String} The image url of the texture * @return {Sprite} A new Sprite using a texture from the texture cache matching the image id */ -Sprite.fromImage = function (imageId, crossorigin, scaleMode) { +Sprite.fromImage = function (imageId, crossorigin, scaleMode) +{ return new Sprite(Texture.fromImage(imageId, crossorigin, scaleMode)); }; diff --git a/src/core/display/SpriteBatch.js b/src/core/display/SpriteBatch.js index 3187777..c196fef 100644 --- a/src/core/display/SpriteBatch.js +++ b/src/core/display/SpriteBatch.js @@ -12,7 +12,8 @@ * ```js * var container = new SpriteBatch(); * - * for(var i = 0; i < 100; ++i) { + * for(var i = 0; i < 100; ++i) + * { * var sprite = new PIXI.Sprite.fromImage("myImage.png"); * container.addChild(sprite); * } @@ -25,7 +26,8 @@ */ //TODO RENAME to PARTICLE CONTAINER? -function SpriteBatch() { +function SpriteBatch() +{ DisplayObjectContainer.call(this); } @@ -38,7 +40,8 @@ * * @private */ -SpriteBatch.prototype.updateTransform = function () { +SpriteBatch.prototype.updateTransform = function () +{ // TODO don't need to! this.displayObjectUpdateTransform(); // PIXI.DisplayObjectContainer.prototype.updateTransform.call( this ); @@ -50,8 +53,10 @@ * @param renderer {WebGLRenderer} The webgl renderer * @private */ -SpriteBatch.prototype.renderWebGL = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderWebGL = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -71,8 +76,10 @@ * @param renderer {CanvasRenderer} The canvas renderer * @private */ -SpriteBatch.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -84,10 +91,12 @@ this.displayObjectUpdateTransform(); - for (var i = 0; i < this.children.length; ++i) { + for (var i = 0; i < this.children.length; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -95,9 +104,11 @@ context.globalAlpha = this.worldAlpha * child.alpha; - if (child.rotation % (Math.PI * 2) === 0) { + if (child.rotation % (Math.PI * 2) === 0) + { // this is the fastest way to optimise! - if rotation is 0 then we can avoid any kind of setTransform call - if (isRotated) { + if (isRotated) + { context.setTransform( transform.a, transform.b, @@ -122,8 +133,10 @@ frame.height * child.scale.y ); } - else { - if (!isRotated) { + else + { + if (!isRotated) + { isRotated = true; } @@ -131,7 +144,8 @@ var childTransform = child.worldTransform; - if (renderer.roundPixels) { + if (renderer.roundPixels) + { context.setTransform( childTransform.a, childTransform.b, @@ -141,7 +155,8 @@ childTransform.ty | 0 ); } - else { + else + { context.setTransform( childTransform.a, childTransform.b, diff --git a/src/core/index.js b/src/core/index.js index 3954b6f..eb4a82b 100644 --- a/src/core/index.js +++ b/src/core/index.js @@ -58,11 +58,13 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRenderer: function (width, height, options, noWebGL) { + autoDetectRenderer: function (width, height, options, noWebGL) + { width = width || 800; height = height || 600; - if (!noWebGL && require('webgl-enabled')()) { + if (!noWebGL && require('webgl-enabled')()) + { return new core.WebGLRenderer(width, height, options); } @@ -87,7 +89,8 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRecommendedRenderer: function (width, height, options) { + autoDetectRecommendedRenderer: function (width, height, options) + { var isAndroid = /Android/i.test(navigator.userAgent); return core.autoDetectRenderer(width, height, options, isAndroid); diff --git a/src/core/math/Matrix.js b/src/core/math/Matrix.js index c2f87e2..2ff4848 100644 --- a/src/core/math/Matrix.js +++ b/src/core/math/Matrix.js @@ -10,7 +10,8 @@ * @class * @namespace PIXI */ -function Matrix() { +function Matrix() +{ /** * @member {number} * @default 1 @@ -63,7 +64,8 @@ * * @param array {number[]} The array that the matrix will be populated from. */ -Matrix.prototype.fromArray = function (array) { +Matrix.prototype.fromArray = function (array) +{ this.a = array[0]; this.b = array[1]; this.c = array[3]; @@ -78,14 +80,17 @@ * @param transpose {boolean} Whether we need to transpose the matrix or not * @return {number[]} the newly created array which contains the matrix */ -Matrix.prototype.toArray = function (transpose) { - if (!this.array) { +Matrix.prototype.toArray = function (transpose) +{ + if (!this.array) + { this.array = new Float32Array(9); } var array = this.array; - if (transpose) { + if (transpose) + { array[0] = this.a; array[1] = this.b; array[2] = 0; @@ -96,7 +101,8 @@ array[7] = this.ty; array[8] = 1; } - else { + else + { array[0] = this.a; array[1] = this.c; array[2] = this.tx; @@ -119,7 +125,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, transformed through this matrix */ -Matrix.prototype.apply = function (pos, newPos) { +Matrix.prototype.apply = function (pos, newPos) +{ newPos = newPos || new Point(); newPos.x = this.a * pos.x + this.c * pos.y + this.tx; @@ -136,7 +143,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, inverse-transformed through this matrix */ -Matrix.prototype.applyInverse = function (pos, newPos) { +Matrix.prototype.applyInverse = function (pos, newPos) +{ newPos = newPos || new Point(); var id = 1 / (this.a * this.d + this.c * -this.b); @@ -154,7 +162,8 @@ * @param {number} y * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.translate = function (x, y) { +Matrix.prototype.translate = function (x, y) +{ this.tx += x; this.ty += y; @@ -168,7 +177,8 @@ * @param {number} y The amount to scale vertically * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.scale = function (x, y) { +Matrix.prototype.scale = function (x, y) +{ this.a *= x; this.d *= y; this.c *= x; @@ -186,7 +196,8 @@ * @param {number} angle - The angle in radians. * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.rotate = function (angle) { +Matrix.prototype.rotate = function (angle) +{ var cos = Math.cos( angle ); var sin = Math.sin( angle ); @@ -210,7 +221,8 @@ * @param {Matrix} matrix * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.append = function (matrix) { +Matrix.prototype.append = function (matrix) +{ var a1 = this.a; var b1 = this.b; var c1 = this.c; @@ -232,7 +244,8 @@ * * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.identity = function () { +Matrix.prototype.identity = function () +{ this.a = 1; this.b = 0; this.c = 0; diff --git a/src/core/math/Point.js b/src/core/math/Point.js index 7565b2d..632f346 100644 --- a/src/core/math/Point.js +++ b/src/core/math/Point.js @@ -7,7 +7,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -function Point(x, y) { +function Point(x, y) +{ /** * @member {number} * @default 0 @@ -29,7 +30,8 @@ * * @return {Point} a copy of the point */ -Point.prototype.clone = function () { +Point.prototype.clone = function () +{ return new Point(this.x, this.y); }; @@ -40,7 +42,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -Point.prototype.set = function (x, y) { +Point.prototype.set = function (x, y) +{ this.x = x || 0; this.y = y || ( (y !== 0) ? this.x : 0 ) ; }; diff --git a/src/core/math/shapes/Circle.js b/src/core/math/shapes/Circle.js index 69cfdc9..4d76efc 100644 --- a/src/core/math/shapes/Circle.js +++ b/src/core/math/shapes/Circle.js @@ -10,7 +10,8 @@ * @param y {number} The Y coordinate of the center of this circle * @param radius {number} The radius of the circle */ -function Circle(x, y, radius) { +function Circle(x, y, radius) +{ /** * @member {number} * @default 0 @@ -46,7 +47,8 @@ * @method clone * @return {Circle} a copy of the Circle */ -Circle.prototype.clone = function () { +Circle.prototype.clone = function () +{ return new Circle(this.x, this.y, this.radius); }; @@ -58,8 +60,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Circle */ -Circle.prototype.contains = function (x, y) { - if (this.radius <= 0) { +Circle.prototype.contains = function (x, y) +{ + if (this.radius <= 0) + { return false; } @@ -79,6 +83,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Circle.prototype.getBounds = function () { +Circle.prototype.getBounds = function () +{ return new Rectangle(this.x - this.radius, this.y - this.radius, this.radius * 2, this.radius * 2); }; diff --git a/src/core/math/shapes/Ellipse.js b/src/core/math/shapes/Ellipse.js index 4f2d066..fefd01a 100644 --- a/src/core/math/shapes/Ellipse.js +++ b/src/core/math/shapes/Ellipse.js @@ -11,7 +11,8 @@ * @param width {number} The half width of this ellipse * @param height {number} The half height of this ellipse */ -function Ellipse(x, y, width, height) { +function Ellipse(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -53,7 +54,8 @@ * @method clone * @return {Ellipse} a copy of the ellipse */ -Ellipse.prototype.clone = function () { +Ellipse.prototype.clone = function () +{ return new Ellipse(this.x, this.y, this.width, this.height); }; @@ -65,8 +67,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coords are within this ellipse */ -Ellipse.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Ellipse.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } @@ -86,6 +90,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Ellipse.prototype.getBounds = function () { +Ellipse.prototype.getBounds = function () +{ return new Rectangle(this.x - this.width, this.y - this.height, this.width, this.height); }; diff --git a/src/core/math/shapes/Polygon.js b/src/core/math/shapes/Polygon.js index ae89148..fea6d37 100644 --- a/src/core/math/shapes/Polygon.js +++ b/src/core/math/shapes/Polygon.js @@ -10,16 +10,20 @@ * arguments passed can be flat x,y values e.g. `new Polygon(x,y, x,y, x,y, ...)` where `x` and `y` are * Numbers. */ -function Polygon(points) { +function Polygon(points) +{ //if points isn't an array, use arguments as the array - if (!(points instanceof Array)) { + if (!(points instanceof Array)) + { points = Array.prototype.slice.call(arguments); } //if this is a flat array of numbers, convert it to points - if (points[0] instanceof Point) { + if (points[0] instanceof Point) + { var p = []; - for (var i = 0, il = points.length; i < il; i++) { + for (var i = 0, il = points.length; i < il; i++) + { p.push(points[i].x, points[i].y); } @@ -51,7 +55,8 @@ * * @return {Polygon} a copy of the polygon */ -Polygon.prototype.clone = function () { +Polygon.prototype.clone = function () +{ return new Polygon(this.points.slice()); }; @@ -62,19 +67,22 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this polygon */ -Polygon.prototype.contains = function (x, y) { +Polygon.prototype.contains = function (x, y) +{ var inside = false; // use some raycasting to test hits // https://github.com/substack/point-in-polygon/blob/master/index.js var length = this.points.length / 2; - for (var i = 0, j = length - 1; i < length; j = i++) { + for (var i = 0, j = length - 1; i < length; j = i++) + { var xi = this.points[i * 2], yi = this.points[i * 2 + 1], xj = this.points[j * 2], yj = this.points[j * 2 + 1], intersect = ((yi > y) !== (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi); - if (intersect) { + if (intersect) + { inside = !inside; } } diff --git a/src/core/math/shapes/Rectangle.js b/src/core/math/shapes/Rectangle.js index 16ac62a..4008b68 100644 --- a/src/core/math/shapes/Rectangle.js +++ b/src/core/math/shapes/Rectangle.js @@ -10,7 +10,8 @@ * @param width {number} The overall width of this rectangle * @param height {number} The overall height of this rectangle */ -function Rectangle(x, y, width, height) { +function Rectangle(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -60,7 +61,8 @@ * * @return {Rectangle} a copy of the rectangle */ -Rectangle.prototype.clone = function () { +Rectangle.prototype.clone = function () +{ return new Rectangle(this.x, this.y, this.width, this.height); }; @@ -71,13 +73,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rectangle */ -Rectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Rectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/math/shapes/RoundedRectangle.js b/src/core/math/shapes/RoundedRectangle.js index 27d286e..7bf6411 100644 --- a/src/core/math/shapes/RoundedRectangle.js +++ b/src/core/math/shapes/RoundedRectangle.js @@ -11,7 +11,8 @@ * @param height {number} The overall height of this rounded rectangle * @param radius {number} Controls the radius of the rounded corners */ -function RoundedRectangle(x, y, width, height, radius) { +function RoundedRectangle(x, y, width, height, radius) +{ /** * @member {number} * @default 0 @@ -58,7 +59,8 @@ * * @return {RoundedRectangle} a copy of the rounded rectangle */ -RoundedRectangle.prototype.clone = function () { +RoundedRectangle.prototype.clone = function () +{ return new RoundedRectangle(this.x, this.y, this.width, this.height, this.radius); }; @@ -69,13 +71,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rounded Rectangle */ -RoundedRectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +RoundedRectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/primitives/Graphics.js b/src/core/primitives/Graphics.js index 261c534..e902d2a 100644 --- a/src/core/primitives/Graphics.js +++ b/src/core/primitives/Graphics.js @@ -16,7 +16,8 @@ * @extends DisplayObjectContainer * @namespace PIXI */ -function Graphics() { +function Graphics() +{ DisplayObjectContainer.call(this); this.renderable = true; @@ -154,16 +155,20 @@ * @private */ cacheAsBitmap: { - get: function () { + get: function () + { return this._cacheAsBitmap; }, - set: function (value) { + set: function (value) + { this._cacheAsBitmap = value; - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._generateCachedSprite(); } - else { + else + { this.destroyCachedSprite(); this.dirty = true; } @@ -176,7 +181,8 @@ * * @return {Graphics} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ var clone = new Graphics(); clone.renderable = this.renderable; @@ -192,7 +198,8 @@ clone.cachedSpriteDirty = this.cachedSpriteDirty; // copy graphics data - for (var i = 0; i < this.graphicsData.length; ++i) { + for (var i = 0; i < this.graphicsData.length; ++i) + { clone.graphicsData.push(this.graphicsData.clone()); } @@ -211,17 +218,21 @@ * @param alpha {number} alpha of the line to draw, will update the objects stored style * @return {Graphics} */ -Graphics.prototype.lineStyle = function (lineWidth, color, alpha) { +Graphics.prototype.lineStyle = function (lineWidth, color, alpha) +{ this.lineWidth = lineWidth || 0; this.lineColor = color || 0; this.lineAlpha = (arguments.length < 3) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length) + { // halfway through a line? start a new one! this.drawShape( new math.Polygon( this.currentPath.shape.points.slice(-2) )); } - else { + else + { // otherwise its empty so lets just set the line properties this.currentPath.lineWidth = this.lineWidth; this.currentPath.lineColor = this.lineColor; @@ -239,7 +250,8 @@ * @param y {number} the Y coordinate to move to * @return {Graphics} */ -Graphics.prototype.moveTo = function (x, y) { +Graphics.prototype.moveTo = function (x, y) +{ this.drawShape(new math.Polygon([x,y])); return this; @@ -253,7 +265,8 @@ * @param y {number} the Y coordinate to draw to * @return {Graphics} */ -Graphics.prototype.lineTo = function (x, y) { +Graphics.prototype.lineTo = function (x, y) +{ this.currentPath.shape.points.push(x, y); this.dirty = true; @@ -270,13 +283,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -285,7 +302,8 @@ n = 20, points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { this.moveTo(0, 0); } @@ -293,7 +311,8 @@ var fromY = points[points.length-1]; var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; xa = fromX + ( (cpX - fromX) * j ); @@ -319,13 +338,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -342,7 +365,8 @@ var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; dt = (1 - j); @@ -373,13 +397,17 @@ * @param radius {number} The radius of the arc * @return {Graphics} */ -Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points.push(x1, y1); } } - else { + else + { this.moveTo(x1, y1); } @@ -392,12 +420,15 @@ b2 = x2 - x1, mm = Math.abs(a1 * b2 - b1 * a2); - if (mm < 1.0e-8 || radius === 0) { - if (points[points.length-2] !== x1 || points[points.length-1] !== y1) { + if (mm < 1.0e-8 || radius === 0) + { + if (points[points.length-2] !== x1 || points[points.length-1] !== y1) + { points.push(x1, y1); } } - else { + else + { var dd = a1 * a1 + b1 * b1, cc = a2 * a2 + b2 * b2, tt = a1 * a2 + b1 * b2, @@ -433,42 +464,51 @@ * @param anticlockwise {boolean} Optional. Specifies whether the drawing should be counterclockwise or clockwise. False is default, and indicates clockwise, while true indicates counter-clockwise. * @return {Graphics} */ -Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) { +Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) +{ var startX = cx + Math.cos(startAngle) * radius; var startY = cy + Math.sin(startAngle) * radius; var points; // TODO - This if-else makes no sense. It uses currentPath in the else where it doesn't exist... - if (this.currentPath) { + if (this.currentPath) + { points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { points.push(startX, startY); } - else if (points[points.length-2] !== startX || points[points.length-1] !== startY) { + else if (points[points.length-2] !== startX || points[points.length-1] !== startY) + { points.push(startX, startY); } } - else { + else + { this.moveTo(startX, startY); points = this.currentPath.shape.points; } - if (startAngle === endAngle) { + if (startAngle === endAngle) + { return this; } - if (!anticlockwise && endAngle <= startAngle) { + if (!anticlockwise && endAngle <= startAngle) + { endAngle += Math.PI * 2; } - else if (anticlockwise && startAngle <= endAngle) { + else if (anticlockwise && startAngle <= endAngle) + { startAngle += Math.PI * 2; } var sweep = anticlockwise ? (startAngle - endAngle) *-1 : (endAngle - startAngle); var segs = (Math.abs(sweep)/ (Math.PI * 2)) * 40; - if (sweep === 0) { + if (sweep === 0) + { return this; } @@ -482,7 +522,8 @@ var remainder = ( segMinus % 1 ) / segMinus; - for (var i = 0; i <= segMinus; ++i) { + for (var i = 0; i <= segMinus; ++i) + { var real = i + remainder * i; var angle = ((theta) + startAngle + (theta2 * real)); @@ -506,13 +547,16 @@ * @param alpha {number} the alpha of the fill * @return {Graphics} */ -Graphics.prototype.beginFill = function (color, alpha) { +Graphics.prototype.beginFill = function (color, alpha) +{ this.filling = true; this.fillColor = color || 0; this.fillAlpha = (alpha === undefined) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length <= 2) + { this.currentPath.fill = this.filling; this.currentPath.fillColor = this.fillColor; this.currentPath.fillAlpha = this.fillAlpha; @@ -526,7 +570,8 @@ * * @return {Graphics} */ -Graphics.prototype.endFill = function () { +Graphics.prototype.endFill = function () +{ this.filling = false; this.fillColor = null; this.fillAlpha = 1; @@ -542,7 +587,8 @@ * @param height {number} The height of the rectangle * @return {Graphics} */ -Graphics.prototype.drawRect = function ( x, y, width, height ) { +Graphics.prototype.drawRect = function ( x, y, width, height ) +{ this.drawShape(new math.Rectangle(x,y, width, height)); return this; @@ -556,7 +602,8 @@ * @param height {number} The height of the rectangle * @param radius {number} Radius of the rectangle corners */ -Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) { +Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) +{ this.drawShape(new math.RoundedRectangle(x, y, width, height, radius)); return this; @@ -570,7 +617,8 @@ * @param radius {number} The radius of the circle * @return {Graphics} */ -Graphics.prototype.drawCircle = function (x, y, radius) { +Graphics.prototype.drawCircle = function (x, y, radius) +{ this.drawShape(new math.Circle(x,y, radius)); return this; @@ -585,7 +633,8 @@ * @param height {number} The half height of the ellipse * @return {Graphics} */ -Graphics.prototype.drawEllipse = function (x, y, width, height) { +Graphics.prototype.drawEllipse = function (x, y, width, height) +{ this.drawShape(new math.Ellipse(x, y, width, height)); return this; @@ -597,8 +646,10 @@ * @param path {Array} The path data used to construct the polygon. * @return {Graphics} */ -Graphics.prototype.drawPolygon = function (path) { - if (!(path instanceof Array)) { +Graphics.prototype.drawPolygon = function (path) +{ + if (!(path instanceof Array)) + { path = Array.prototype.slice.call(arguments); } @@ -612,7 +663,8 @@ * * @return {Graphics} */ -Graphics.prototype.clear = function () { +Graphics.prototype.clear = function () +{ this.lineWidth = 0; this.filling = false; @@ -631,7 +683,8 @@ * @param scaleMode {number} Should be one of the scaleMode consts * @return {Texture} a texture of the graphics object */ -Graphics.prototype.generateTexture = function (resolution, scaleMode) { +Graphics.prototype.generateTexture = function (resolution, scaleMode) +{ resolution = resolution || 1; var bounds = this.getBounds(); @@ -655,17 +708,21 @@ * * @param renderer {WebGLRenderer} */ -Graphics.prototype._renderWebGL = function (renderer) { +Graphics.prototype._renderWebGL = function (renderer) +{ // if the sprite is not visible or the alpha is 0 then no need to render this element - if (this.isMask === true) { + if (this.isMask === true) + { return; } // this code may still be needed so leaving for now.. - // + // /* - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture on the gpu too! @@ -681,17 +738,24 @@ return; } - */ - - // check if the webgl graphic needs to be updated - if (this.glDirty) { - this.dirty = true; - this.glDirty = false; - } + else */ - renderer.setObjectRendererer(renderer.graphicsRenderer); - renderer.graphicsRenderer.render(this); + renderer.spriteBatch.stop(); + renderer.blendModeManager.setBlendMode(this.blendMode); + // check blend mode + renderer.blendModeManager.setBlendMode( this.blendMode ); + + // check if the webgl graphic needs to be updated + if (this.glDirty) + { + this.dirty = true; + this.glDirty = false; + } + + WebGLGraphics.renderGraphics(this, renderer); + + renderer.spriteBatch.start(); }; /** @@ -700,14 +764,18 @@ * @param renderer {CanvasRenderer} * @private */ -Graphics.prototype.renderCanvas = function (renderer) { +Graphics.prototype.renderCanvas = function (renderer) +{ // 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.isMask === true) { + if (!this.visible || this.alpha <= 0 || this.isMask === true) + { return; } - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture @@ -723,16 +791,19 @@ return; } - else { + else + { var context = renderer.context; var transform = this.worldTransform; - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } @@ -748,11 +819,13 @@ CanvasGraphics.renderGraphics(this, context); - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } } @@ -763,13 +836,16 @@ * * @return {Rectangle} the rectangular bounding area */ -Graphics.prototype.getBounds = function (matrix) { +Graphics.prototype.getBounds = function (matrix) +{ // return an empty object if the item is a mask! - if (this.isMask) { + if (this.isMask) + { return math.Rectangle.EMPTY; } - if (this.dirty) { + if (this.dirty) + { this.updateLocalBounds(); this.glDirty = true; @@ -841,23 +917,27 @@ * Update the bounds of the object * */ -Graphics.prototype.updateLocalBounds = function () { +Graphics.prototype.updateLocalBounds = function () +{ var minX = Infinity; var maxX = -Infinity; var minY = Infinity; var maxY = -Infinity; - if (this.graphicsData.length) { + if (this.graphicsData.length) + { var shape, points, x, y, w, h; - for (var i = 0; i < this.graphicsData.length; i++) { + for (var i = 0; i < this.graphicsData.length; i++) + { var data = this.graphicsData[i]; var type = data.type; var lineWidth = data.lineWidth; shape = data.shape; - if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) { + if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) + { x = shape.x - lineWidth/2; y = shape.y - lineWidth/2; w = shape.width + lineWidth; @@ -869,7 +949,8 @@ minY = y < minY ? y : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.CIRC) { + else if (type === CONST.SHAPES.CIRC) + { x = shape.x; y = shape.y; w = shape.radius + lineWidth/2; @@ -881,7 +962,8 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.ELIP) { + else if (type === CONST.SHAPES.ELIP) + { x = shape.x; y = shape.y; w = shape.width + lineWidth/2; @@ -893,11 +975,13 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else { + else + { // POLY points = shape.points; - for (var j = 0; j < points.length; j += 2) { + for (var j = 0; j < points.length; j += 2) + { x = points[j]; y = points[j+1]; @@ -910,7 +994,8 @@ } } } - else { + else + { minX = 0; maxX = 0; minY = 0; @@ -931,10 +1016,12 @@ * * @private */ -Graphics.prototype._generateCachedSprite = function () { +Graphics.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { var canvasBuffer = new CanvasBuffer(bounds.width, bounds.height); var texture = Texture.fromCanvas(canvasBuffer.canvas); @@ -943,7 +1030,8 @@ this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.buffer.resize(bounds.width, bounds.height); } @@ -968,7 +1056,8 @@ * * @private */ -Graphics.prototype.updateCachedSpriteTexture = function () { +Graphics.prototype.updateCachedSpriteTexture = function () +{ var cachedSprite = this._cachedSprite; var texture = cachedSprite.texture; var canvas = cachedSprite.buffer.canvas; @@ -989,7 +1078,8 @@ * Destroys a previous cached sprite. * */ -Graphics.prototype.destroyCachedSprite = function () { +Graphics.prototype.destroyCachedSprite = function () +{ this._cachedSprite.texture.destroy(true); // let the gc collect the unused sprite @@ -1003,10 +1093,13 @@ * @param {Circle|Rectangle|Ellipse|Line|Polygon} shape The Shape object to draw. * @return {GraphicsData} The generated GraphicsData object. */ -Graphics.prototype.drawShape = function (shape) { - if (this.currentPath) { +Graphics.prototype.drawShape = function (shape) +{ + if (this.currentPath) + { // check current path! - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath.shape.points.length <= 2) + { this.graphicsData.pop(); } } @@ -1017,7 +1110,8 @@ this.graphicsData.push(data); - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { data.shape.closed = this.filling; this.currentPath = data; } diff --git a/src/core/primitives/GraphicsData.js b/src/core/primitives/GraphicsData.js index 99decbe..788f6f2 100644 --- a/src/core/primitives/GraphicsData.js +++ b/src/core/primitives/GraphicsData.js @@ -4,7 +4,8 @@ * @class * @namespace PIXI */ -function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) { +function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) +{ this.lineWidth = lineWidth; this.lineColor = lineColor; this.lineAlpha = lineAlpha; @@ -27,7 +28,8 @@ * * @return {GraphicsData} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ return new GraphicsData( this.lineWidth, this.lineColor, diff --git a/src/core/renderers/canvas/CanvasRenderer.js b/src/core/renderers/canvas/CanvasRenderer.js index 15a0978..7aebd44 100644 --- a/src/core/renderers/canvas/CanvasRenderer.js +++ b/src/core/renderers/canvas/CanvasRenderer.js @@ -17,17 +17,22 @@ * @param [options.resolution=1] {number} the resolution of the renderer retina would be 2 * @param [options.clearBeforeRender=true] {boolean} This sets if the CanvasRenderer will clear the canvas or not before the new render pass. */ -function CanvasRenderer(width, height, options) { +function CanvasRenderer(width, height, options) +{ utils.sayHello('Canvas'); - if (options) { - for (var i in CONST.defaultRenderOptions) { - if (typeof options[i] === 'undefined') { + if (options) + { + for (var i in CONST.defaultRenderOptions) + { + if (typeof options[i] === 'undefined') + { options[i] = CONST.defaultRenderOptions[i]; } } } - else { + else + { options = CONST.defaultRenderOptions; } @@ -156,19 +161,24 @@ this.smoothProperty = null; - if (this.context.imageSmoothingEnabled) { + if (this.context.imageSmoothingEnabled) + { this.smoothProperty = 'imageSmoothingEnabled'; } - else if (this.context.webkitImageSmoothingEnabled) { + else if (this.context.webkitImageSmoothingEnabled) + { this.smoothProperty = 'webkitImageSmoothingEnabled'; } - else if (this.context.mozImageSmoothingEnabled) { + else if (this.context.mozImageSmoothingEnabled) + { this.smoothProperty = 'mozImageSmoothingEnabled'; } - else if (this.context.oImageSmoothingEnabled) { + else if (this.context.oImageSmoothingEnabled) + { this.smoothProperty = 'oImageSmoothingEnabled'; } - else if (this.context.msImageSmoothingEnabled) { + else if (this.context.msImageSmoothingEnabled) + { this.smoothProperty = 'msImageSmoothingEnabled'; } @@ -193,10 +203,12 @@ * @memberof CanvasRenderer# */ backgroundColor: { - get: function () { + get: function () + { return this._backgroundColor; }, - set: function (val) { + set: function (val) + { this._backgroundColor = val; this._backgroundColorString = utils.hex2string(val); } @@ -208,7 +220,8 @@ * * @param object {DisplayObject} the object to be rendered */ -CanvasRenderer.prototype.render = function (object) { +CanvasRenderer.prototype.render = function (object) +{ object.updateTransform(); this.context.setTransform(1,0,0,1,0,0); @@ -218,16 +231,20 @@ this.currentBlendMode = CONST.blendModes.NORMAL; this.context.globalCompositeOperation = this.blendModes[CONST.blendModes.NORMAL]; - if (navigator.isCocoonJS && this.view.screencanvas) { + if (navigator.isCocoonJS && this.view.screencanvas) + { this.context.fillStyle = 'black'; this.context.clear(); } - if (this.clearBeforeRender) { - if (this.transparent) { + if (this.clearBeforeRender) + { + if (this.transparent) + { this.context.clearRect(0, 0, this.width, this.height); } - else { + else + { this.context.fillStyle = this._backgroundColorString; this.context.fillRect(0, 0, this.width , this.height); } @@ -241,8 +258,10 @@ * * @param [removeView=false] {boolean} Removes the Canvas element from the DOM. */ -CanvasRenderer.prototype.destroy = function (removeView) { - if (removeView && this.view.parent) { +CanvasRenderer.prototype.destroy = function (removeView) +{ + if (removeView && this.view.parent) + { this.view.parent.removeChild(this.view); } @@ -257,14 +276,16 @@ * @param width {number} the new width of the canvas view * @param height {number} the new height of the canvas view */ -CanvasRenderer.prototype.resize = function (width, height) { +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) { + if (this.autoResize) + { this.view.style.width = this.width / this.resolution + 'px'; this.view.style.height = this.height / this.resolution + 'px'; } @@ -276,7 +297,8 @@ * @param displayObject {DisplayObject} The displayObject to render * @private */ -CanvasRenderer.prototype.renderDisplayObject = function (displayObject) { +CanvasRenderer.prototype.renderDisplayObject = function (displayObject) +{ displayObject.renderCanvas(this); }; @@ -285,11 +307,14 @@ * * @private */ -CanvasRenderer.prototype._mapBlendModes = function () { - if (!this.blendModes) { +CanvasRenderer.prototype._mapBlendModes = function () +{ + if (!this.blendModes) + { this.blendModes = {}; - if (utils.canUseNewCanvasBlendModes()) { + if (utils.canUseNewCanvasBlendModes()) + { this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? this.blendModes[CONST.blendModes.MULTIPLY] = 'multiply'; @@ -308,7 +333,8 @@ this.blendModes[CONST.blendModes.COLOR] = 'color'; this.blendModes[CONST.blendModes.LUMINOSITY] = 'luminosity'; } - else { + else + { // this means that the browser does not support the cool new blend modes in canvas 'cough' ie 'cough' this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? diff --git a/src/core/renderers/canvas/utils/CanvasBuffer.js b/src/core/renderers/canvas/utils/CanvasBuffer.js index ebe5d47..b183a66 100644 --- a/src/core/renderers/canvas/utils/CanvasBuffer.js +++ b/src/core/renderers/canvas/utils/CanvasBuffer.js @@ -6,7 +6,8 @@ * @param width {number} the width for the newly created canvas * @param height {number} the height for the newly created canvas */ -function CanvasBuffer(width, height) { +function CanvasBuffer(width, height) +{ /** * The Canvas object that belongs to this CanvasBuffer. * @@ -36,10 +37,12 @@ * @memberof CanvasBuffer# */ width: { - get: function () { + get: function () + { return this.canvas.width; }, - set: function (val) { + set: function (val) + { this.canvas.width = val; } }, @@ -50,10 +53,12 @@ * @memberof CanvasBuffer# */ height: { - get: function () { + get: function () + { return this.canvas.height; }, - set: function (val) { + set: function (val) + { this.canvas.height = val; } } @@ -64,7 +69,8 @@ * * @private */ -CanvasBuffer.prototype.clear = function () { +CanvasBuffer.prototype.clear = function () +{ this.context.setTransform(1, 0, 0, 1, 0, 0); this.context.clearRect(0,0, this.canvas.width, this.canvas.height); }; @@ -75,7 +81,8 @@ * @param width {number} the new width of the canvas * @param height {number} the new height of the canvas */ -CanvasBuffer.prototype.resize = function (width, height) { +CanvasBuffer.prototype.resize = function (width, height) +{ this.canvas.width = width; this.canvas.height = height; }; diff --git a/src/core/renderers/canvas/utils/CanvasGraphics.js b/src/core/renderers/canvas/utils/CanvasGraphics.js index c7eaa2a..3f2a91f 100644 --- a/src/core/renderers/canvas/utils/CanvasGraphics.js +++ b/src/core/renderers/canvas/utils/CanvasGraphics.js @@ -13,15 +13,18 @@ * @param graphics {Graphics} the actual graphics object to render * @param context {CanvasRenderingContext2D} the 2d drawing method of the canvas */ -CanvasGraphics.renderGraphics = function (graphics, context) { +CanvasGraphics.renderGraphics = function (graphics, context) +{ var worldAlpha = graphics.worldAlpha; - if (graphics.dirty) { + if (graphics.dirty) + { this.updateGraphicsTint(graphics); graphics.dirty = false; } - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; @@ -30,69 +33,82 @@ context.lineWidth = data.lineWidth; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { context.beginPath(); var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } - if (shape.closed) { + if (shape.closed) + { context.lineTo(points[0], points[1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fillRect(shape.x, shape.y, shape.width, shape.height); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.strokeRect(shape.x, shape.y, shape.width, shape.height); } } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.beginPath(); context.arc(shape.x, shape.y, shape.radius,0,2*Math.PI); context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas var w = shape.width * 2; @@ -119,18 +135,21 @@ context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; var width = shape.width; @@ -152,13 +171,15 @@ context.quadraticCurveTo(rx, ry, rx, ry + radius); context.closePath(); - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); @@ -174,45 +195,54 @@ * @param graphics {Graphics} the graphics which will be used as a mask * @param context {CanvasRenderingContext2D} the context 2d method of the canvas */ -CanvasGraphics.renderGraphicsMask = function (graphics, context) { +CanvasGraphics.renderGraphicsMask = function (graphics, context) +{ var len = graphics.graphicsData.length; - if (len === 0) { + if (len === 0) + { return; } context.beginPath(); - for (var i = 0; i < len; i++) { + for (var i = 0; i < len; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { context.rect(shape.x, shape.y, shape.width, shape.height); context.closePath(); } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.arc(shape.x, shape.y, shape.radius, 0, 2 * Math.PI); context.closePath(); } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas @@ -237,7 +267,8 @@ context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); context.closePath(); } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; @@ -262,8 +293,10 @@ } }; -CanvasGraphics.updateGraphicsTint = function (graphics) { - if (graphics.tint === 0xFFFFFF) { +CanvasGraphics.updateGraphicsTint = function (graphics) +{ + if (graphics.tint === 0xFFFFFF) + { return; } @@ -271,7 +304,8 @@ var tintG = (graphics.tint >> 8 & 0xFF) / 255; var tintB = (graphics.tint & 0xFF)/ 255; - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var fillColor = data.fillColor | 0; diff --git a/src/core/renderers/canvas/utils/CanvasMaskManager.js b/src/core/renderers/canvas/utils/CanvasMaskManager.js index e04a733..9827d36 100644 --- a/src/core/renderers/canvas/utils/CanvasMaskManager.js +++ b/src/core/renderers/canvas/utils/CanvasMaskManager.js @@ -6,7 +6,8 @@ * @class * @namespace PIXI */ -function CanvasMaskManager() {} +function CanvasMaskManager() +{} CanvasMaskManager.prototype.constructor = CanvasMaskManager; module.exports = CanvasMaskManager; @@ -17,7 +18,8 @@ * @param maskData {object} the maskData that will be pushed * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.pushMask = function (maskData, renderer) { +CanvasMaskManager.prototype.pushMask = function (maskData, renderer) +{ renderer.context.save(); var cacheAlpha = maskData.alpha; @@ -45,6 +47,7 @@ * * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.popMask = function (renderer) { +CanvasMaskManager.prototype.popMask = function (renderer) +{ renderer.context.restore(); }; diff --git a/src/core/renderers/canvas/utils/CanvasTinter.js b/src/core/renderers/canvas/utils/CanvasTinter.js index 17e0529..d2fb1bc 100644 --- a/src/core/renderers/canvas/utils/CanvasTinter.js +++ b/src/core/renderers/canvas/utils/CanvasTinter.js @@ -14,7 +14,8 @@ * @param color {number} the color to use to tint the sprite with * @return {HTMLCanvasElement} The tinted canvas */ -CanvasTinter.getTintedTexture = function (sprite, color) { +CanvasTinter.getTintedTexture = function (sprite, color) +{ var texture = sprite.texture; color = CanvasTinter.roundColor(color); @@ -23,7 +24,8 @@ texture.tintCache = texture.tintCache || {}; - if (texture.tintCache[stringColor]) { + if (texture.tintCache[stringColor]) + { return texture.tintCache[stringColor]; } @@ -33,14 +35,16 @@ //CanvasTinter.tintWithPerPixel(texture, stringColor, canvas); CanvasTinter.tintMethod(texture, color, canvas); - if (CanvasTinter.convertTintToImage) { + if (CanvasTinter.convertTintToImage) + { // is this better? var tintImage = new Image(); tintImage.src = canvas.toDataURL(); texture.tintCache[stringColor] = tintImage; } - else { + else + { texture.tintCache[stringColor] = canvas; // if we are not converting the texture to an image then we need to lose the reference to the canvas CanvasTinter.canvas = null; @@ -56,7 +60,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithMultiply = function (texture, color, canvas) { +CanvasTinter.tintWithMultiply = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -104,7 +109,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithOverlay = function (texture, color, canvas) { +CanvasTinter.tintWithOverlay = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -139,7 +145,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithPerPixel = function (texture, color, canvas) { +CanvasTinter.tintWithPerPixel = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -167,7 +174,8 @@ var pixels = pixelData.data; - for (var i = 0; i < pixels.length; i += 4) { + for (var i = 0; i < pixels.length; i += 4) + { pixels[i+0] *= r; pixels[i+1] *= g; pixels[i+2] *= b; @@ -181,7 +189,8 @@ * * @param color {number} the color to round, should be a hex color */ -CanvasTinter.roundColor = function (color) { +CanvasTinter.roundColor = function (color) +{ var step = CanvasTinter.cacheStepsPerColorChannel; var rgbValues = utils.hex2rgb(color); diff --git a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js index 9f2f89a..35edbaf 100644 --- a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js +++ b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLBlendModeManager(renderer) { +function WebGLBlendModeManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -23,8 +24,10 @@ * * @param blendMode {number} the blendMode, should be a Pixi const, such as BlendModes.ADD */ -WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) { - if (this.currentBlendMode === blendMode) { +WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) +{ + if (this.currentBlendMode === blendMode) + { return false; } diff --git a/src/core/renderers/webgl/managers/WebGLFilterManager.js b/src/core/renderers/webgl/managers/WebGLFilterManager.js index 1179258..2dac048 100644 --- a/src/core/renderers/webgl/managers/WebGLFilterManager.js +++ b/src/core/renderers/webgl/managers/WebGLFilterManager.js @@ -7,7 +7,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLFilterManager(renderer) { +function WebGLFilterManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -32,7 +33,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.texturePool.length = 0; self.initShaderBuffers(); }); @@ -46,7 +48,8 @@ * @param renderer {WebGLRenderer} * @param buffer {ArrayBuffer} */ -WebGLFilterManager.prototype.begin = function (buffer) { +WebGLFilterManager.prototype.begin = function (buffer) +{ this.defaultShader = this.renderer.shaderManager.defaultShader; this.width = this.renderer.projection.x * 2; @@ -60,7 +63,8 @@ * * @param filterBlock {object} the filter that will be pushed to the current filter stack */ -WebGLFilterManager.prototype.pushFilter = function (filterBlock) { +WebGLFilterManager.prototype.pushFilter = function (filterBlock) +{ var gl = this.renderer.gl; var projection = this.renderer.projection; @@ -78,10 +82,12 @@ this.offsetY += filterBlock._filterArea.y; var texture = this.texturePool.pop(); - if (!texture) { + if (!texture) + { texture = new FilterTexture(this.renderer.gl, this.width, this.height); } - else { + else + { texture.resize(this.width, this.height); } @@ -98,29 +104,35 @@ var localX = filterArea.x, localY = filterArea.y; - if (filterArea.x < 0) { + if (filterArea.x < 0) + { filterArea.width += filterArea.x; filterArea.x = 0; } - if (filterArea.y < 0) { + if (filterArea.y < 0) + { filterArea.height += filterArea.y; filterArea.y = 0; } - if (localX + filterArea.width > this.width) { + if (localX + filterArea.width > this.width) + { filterArea.width = this.width - localX; } - if (localY + filterArea.height > this.height) { + if (localY + filterArea.height > this.height) + { filterArea.height = this.height - localY; } - if (filterArea.width < 0) { + if (filterArea.width < 0) + { filterArea.width = 0; } - if (filterArea.height < 0) { + if (filterArea.height < 0) + { filterArea.height = 0; } @@ -154,7 +166,8 @@ * Removes the last filter from the filter stack and doesn't return it. * */ -WebGLFilterManager.prototype.popFilter = function () { +WebGLFilterManager.prototype.popFilter = function () +{ var gl = this.renderer.gl; var filterBlock = this.filterStack.pop(); @@ -163,7 +176,8 @@ var projection = this.renderer.projection; var offset = this.renderer.offset; - if (filterBlock.filterPasses.length > 1) { + if (filterBlock.filterPasses.length > 1) + { gl.viewport(0, 0, filterArea.width, filterArea.height); gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); @@ -193,7 +207,8 @@ var inputTexture = texture; var outputTexture = this.texturePool.pop(); - if (!outputTexture) { + if (!outputTexture) + { outputTexture = new FilterTexture(this.renderer.gl, this.width, this.height); } outputTexture.resize(this.width, this.height); @@ -204,7 +219,8 @@ gl.disable(gl.BLEND); - for (var i = 0; i < filterBlock.filterPasses.length-1; i++) { + for (var i = 0; i < filterBlock.filterPasses.length-1; i++) + { var filterPass = filterBlock.filterPasses[i]; gl.bindFramebuffer(gl.FRAMEBUFFER, outputTexture.frameBuffer ); @@ -243,10 +259,12 @@ var buffer = this.buffer; // time to render the filters texture to the previous scene - if (this.filterStack.length === 0) { + if (this.filterStack.length === 0) + { gl.colorMask(true, true, true, true);//this.transparent); } - else { + else + { var currentFilter = this.filterStack[this.filterStack.length-1]; filterArea = currentFilter._filterArea; @@ -332,13 +350,15 @@ * @param width {number} the horizontal range of the filter * @param height {number} the vertical range of the filter */ -WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) { +WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) +{ // use program var gl = this.renderer.gl; var shader = filter.shaders[gl.id]; - if (!shader) { + if (!shader) + { shader = new Shader(gl); shader.fragmentSrc = filter.fragmentSrc; @@ -356,7 +376,8 @@ gl.uniform2f(shader.projectionVector, width/2, -height/2); gl.uniform2f(shader.offsetVector, 0,0); - if (filter.uniforms.dimensions) { + 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]; @@ -386,7 +407,8 @@ * Initialises the shader buffers. * */ -WebGLFilterManager.prototype.initShaderBuffers = function () { +WebGLFilterManager.prototype.initShaderBuffers = function () +{ var gl = this.renderer.gl; // create some buffers @@ -432,7 +454,8 @@ * Destroys the filter and removes it from the filter stack. * */ -WebGLFilterManager.prototype.destroy = function () { +WebGLFilterManager.prototype.destroy = function () +{ var gl = this.renderer.gl; this.filterStack = null; @@ -441,7 +464,8 @@ this.offsetY = 0; // destroy textures - for (var i = 0; i < this.texturePool.length; i++) { + for (var i = 0; i < this.texturePool.length; i++) + { this.texturePool[i].destroy(); } diff --git a/src/core/renderers/webgl/managers/WebGLManager.js b/src/core/renderers/webgl/managers/WebGLManager.js index 9d47b5c..c30cd51 100644 --- a/src/core/renderers/webgl/managers/WebGLManager.js +++ b/src/core/renderers/webgl/managers/WebGLManager.js @@ -3,7 +3,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLManager(renderer) { +function WebGLManager(renderer) +{ /** * The renderer this manager works for. * @@ -15,6 +16,7 @@ WebGLManager.prototype.constructor = WebGLManager; module.exports = WebGLManager; -WebGLManager.prototype.destroy = function () { +WebGLManager.prototype.destroy = function () +{ this.renderer = null; }; diff --git a/src/core/renderers/webgl/managers/WebGLMaskManager.js b/src/core/renderers/webgl/managers/WebGLMaskManager.js index 2f90b64..e568812 100644 --- a/src/core/renderers/webgl/managers/WebGLMaskManager.js +++ b/src/core/renderers/webgl/managers/WebGLMaskManager.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLMaskManager(renderer) { +function WebGLMaskManager(renderer) +{ WebGLManager.call(this, renderer); } @@ -19,12 +20,15 @@ * * @param maskData {any[]} */ -WebGLMaskManager.prototype.pushMask = function (maskData) { - if (maskData.dirty) { +WebGLMaskManager.prototype.pushMask = function (maskData) +{ + if (maskData.dirty) + { WebGLGraphics.updateGraphics(maskData, this.renderer.gl); } - if (!maskData._webGL[this.renderer.gl.id].data.length) { + if (!maskData._webGL[this.renderer.gl.id].data.length) + { return; } @@ -36,6 +40,7 @@ * * @param maskData {any[]} */ -WebGLMaskManager.prototype.popMask = function (maskData) { +WebGLMaskManager.prototype.popMask = function (maskData) +{ this.renderer.stencilManager.popStencil(maskData, maskData._webGL[this.renderer.gl.id].data[0], this.renderer); }; diff --git a/src/core/renderers/webgl/managers/WebGLShaderManager.js b/src/core/renderers/webgl/managers/WebGLShaderManager.js index fef071c..90c6477 100644 --- a/src/core/renderers/webgl/managers/WebGLShaderManager.js +++ b/src/core/renderers/webgl/managers/WebGLShaderManager.js @@ -10,7 +10,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLShaderManager(renderer) { +function WebGLShaderManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -28,7 +29,8 @@ */ this.tempAttribState = []; - for (var i = 0; i < this.maxAttibs; i++) { + for (var i = 0; i < this.maxAttibs; i++) + { this.attribState[i] = false; } @@ -66,7 +68,8 @@ // listen for context and update necessary shaders var self = this; - this.renderer.on('context', function (event) { + this.renderer.on('context', function (event) + { var gl = event.data; // this shader is used for rendering primitives @@ -97,29 +100,36 @@ * * @param attribs {Array} attribs */ -WebGLShaderManager.prototype.setAttribs = function (attribs) { +WebGLShaderManager.prototype.setAttribs = function (attribs) +{ // reset temp state var i; - for (i = 0; i < this.tempAttribState.length; i++) { + for (i = 0; i < this.tempAttribState.length; i++) + { this.tempAttribState[i] = false; } // set the new attribs - for (var a in attribs) { + for (var a in attribs) + { this.tempAttribState[attribs[a]] = true; } var gl = this.renderer.gl; - for (i = 0; i < this.attribState.length; i++) { - if (this.attribState[i] !== this.tempAttribState[i]) { + for (i = 0; i < this.attribState.length; i++) + { + if (this.attribState[i] !== this.tempAttribState[i]) + { this.attribState[i] = this.tempAttribState[i]; - if (this.attribState[i]) { + if (this.attribState[i]) + { gl.enableVertexAttribArray(i); } - else { + else + { gl.disableVertexAttribArray(i); } } @@ -131,8 +141,10 @@ * * @param shader {Any} */ -WebGLShaderManager.prototype.setShader = function (shader) { - if (this._currentId === shader.uuid) { +WebGLShaderManager.prototype.setShader = function (shader) +{ + if (this._currentId === shader.uuid) + { return false; } @@ -150,7 +162,8 @@ * Destroys this object. * */ -WebGLShaderManager.prototype.destroy = function () { +WebGLShaderManager.prototype.destroy = function () +{ this.attribState = null; this.tempAttribState = null; diff --git a/src/core/renderers/webgl/managers/WebGLStencilManager.js b/src/core/renderers/webgl/managers/WebGLStencilManager.js index 9ec6398..4cb0134 100644 --- a/src/core/renderers/webgl/managers/WebGLStencilManager.js +++ b/src/core/renderers/webgl/managers/WebGLStencilManager.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLStencilManager(renderer) { +function WebGLStencilManager(renderer) +{ WebGLManager.call(this, renderer); this.stencilStack = []; @@ -24,12 +25,14 @@ * @param graphics {Graphics} * @param webGLData {any[]} */ -WebGLStencilManager.prototype.pushStencil = function (graphics, webGLData) { +WebGLStencilManager.prototype.pushStencil = function (graphics, webGLData) +{ var gl = this.renderer.gl; this.bindGraphics(graphics, webGLData, this.renderer); - if (this.stencilStack.length === 0) { + if (this.stencilStack.length === 0) + { gl.enable(gl.STENCIL_TEST); gl.clear(gl.STENCIL_BUFFER_BIT); this.reverse = true; @@ -47,14 +50,17 @@ // draw the triangle strip! - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } @@ -62,31 +68,38 @@ // draw a quad to increment.. gl.drawElements(gl.TRIANGLE_FAN, 4, gl.UNSIGNED_SHORT, ( webGLData.indices.length - 4 ) * 2 ); - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); } this.reverse = !this.reverse; } - else { - if (!this.reverse) { + else + { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } - else { + 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) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); } } @@ -103,7 +116,8 @@ * @param graphics {Graphics} * @param webGLData {Array} */ -WebGLStencilManager.prototype.bindGraphics = function (graphics, webGLData) { +WebGLStencilManager.prototype.bindGraphics = function (graphics, webGLData) +{ //if (this._currentGraphics === graphics)return; this._currentGraphics = graphics; @@ -114,7 +128,8 @@ offset = this.renderer.offset, shader;// = this.renderer.shaderManager.primitiveShader; - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { shader = this.renderer.shaderManager.complexPrimitiveShader; this.renderer.shaderManager.setShader(shader); @@ -141,7 +156,8 @@ // set the index buffer! gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, webGLData.indexBuffer); } - else { + else + { //this.renderer.shaderManager.activatePrimitiveShader(); shader = this.renderer.shaderManager.primitiveShader; this.renderer.shaderManager.setShader( shader ); @@ -154,7 +170,7 @@ gl.uniform2f(shader.uniforms.offsetVector._location, -offset.x, -offset.y); gl.uniform3fv(shader.uniforms.tint._location, utils.hex2rgb(graphics.tint)); - + gl.uniform1f(shader.uniforms.alpha._location, graphics.worldAlpha); @@ -172,19 +188,22 @@ * @param graphics {Graphics} * @param webGLData {Array} */ -WebGLStencilManager.prototype.popStencil = function (graphics, webGLData) { +WebGLStencilManager.prototype.popStencil = function (graphics, webGLData) +{ var gl = this.renderer.gl; this.stencilStack.pop(); this.count--; - if (this.stencilStack.length === 0) { + if (this.stencilStack.length === 0) + { // the stack is empty! gl.disable(gl.STENCIL_TEST); } - else { + else + { var level = this.count; @@ -192,14 +211,17 @@ gl.colorMask(false, false, false, false); - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { this.reverse = !this.reverse; - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } @@ -213,31 +235,38 @@ // draw the triangle strip! gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); - if (!this.reverse) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); } } - else { + else + { // console.log("<<>>") - if (!this.reverse) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } - else { + 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) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); } } @@ -253,7 +282,8 @@ * Destroys the mask stack. * */ -WebGLStencilManager.prototype.destroy = function () { +WebGLStencilManager.prototype.destroy = function () +{ this.renderer = null; this.stencilStack = null; }; diff --git a/src/core/display/DisplayObject.js b/src/core/display/DisplayObject.js index 66ebc3c..20e778c 100644 --- a/src/core/display/DisplayObject.js +++ b/src/core/display/DisplayObject.js @@ -7,7 +7,8 @@ * @class * @namespace PIXI */ -function DisplayObject() { +function DisplayObject() +{ /** * The coordinate of the object relative to the local coordinates of the parent. * @@ -152,10 +153,12 @@ * @memberof DisplayObject# */ x: { - get: function () { + get: function () + { return this.position.x; }, - set: function (value) { + set: function (value) + { this.position.x = value; } }, @@ -167,10 +170,12 @@ * @memberof DisplayObject# */ y: { - get: function () { + get: function () + { return this.position.y; }, - set: function (value) { + set: function (value) + { this.position.y = value; } }, @@ -183,11 +188,13 @@ * @readonly */ worldVisible: { - get: function () { + get: function () + { var item = this; do { - if (!item.visible) { + if (!item.visible) + { return false; } @@ -207,17 +214,21 @@ * @memberof DisplayObject# */ mask: { - get: function () { + get: function () + { return this._mask; }, - set: function (value) { - if (this._mask) { + set: function (value) + { + if (this._mask) + { this._mask.isMask = false; } this._mask = value; - if (this._mask) { + if (this._mask) + { this._mask.isMask = true; } } @@ -232,18 +243,23 @@ * @memberof DisplayObject# */ filters: { - get: function () { + get: function () + { return this._filters; }, - set: function (value) { - if (value) { + set: function (value) + { + if (value) + { // now put all the passes in one place.. var passes = []; - for (var i = 0; i < value.length; i++) { + for (var i = 0; i < value.length; i++) + { var filterPasses = value[i].passes; - for (var j = 0; j < filterPasses.length; j++) { + for (var j = 0; j < filterPasses.length; j++) + { passes.push(filterPasses[j]); } } @@ -264,8 +280,9 @@ * * @private */ -DisplayObject.prototype.updateTransform = function () { - +DisplayObject.prototype.updateTransform = function () +{ + // create some matrix refs for easy access var pt = this.parent.worldTransform; var wt = this.worldTransform; @@ -274,9 +291,11 @@ var a, b, c, d, tx, ty; // so if rotation is between 0 then we can simplify the multiplication process.. - if (this.rotation % math.PI_2) { + if (this.rotation % math.PI_2) + { // 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) { + if (this.rotation !== this.rotationCache) + { this.rotationCache = this.rotation; this._sr = Math.sin(this.rotation); this._cr = Math.cos(this.rotation); @@ -291,7 +310,8 @@ ty = this.position.y; // check for pivot.. not often used so geared towards that fact! - if (this.pivot.x || this.pivot.y) { + 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; } @@ -304,7 +324,8 @@ wt.tx = tx * pt.a + ty * pt.c + pt.tx; wt.ty = tx * pt.b + ty * pt.d + pt.ty; } - else { + else + { // lets do the fast version as we know there is no rotation.. a = this.scale.x; d = this.scale.y; @@ -333,7 +354,8 @@ * @param matrix {Matrix} * @return {Rectangle} the rectangular bounding area */ -DisplayObject.prototype.getBounds = function (/* matrix */) { +DisplayObject.prototype.getBounds = function (/* matrix */) +{ return math.Rectangle.EMPTY; }; @@ -342,7 +364,8 @@ * * @return {Rectangle} the rectangular bounding area */ -DisplayObject.prototype.getLocalBounds = function () { +DisplayObject.prototype.getLocalBounds = function () +{ return this.getBounds(math.Matrix.IDENTITY); }; @@ -352,7 +375,8 @@ * @param position {Point} The world origin to calculate from * @return {Point} A point object representing the position of this object */ -DisplayObject.prototype.toGlobal = function (position) { +DisplayObject.prototype.toGlobal = function (position) +{ // don't need to u[date the lot this.displayObjectUpdateTransform(); return this.worldTransform.apply(position); @@ -365,8 +389,10 @@ * @param [from] {DisplayObject} The DisplayObject to calculate the global position from * @return {Point} A point object representing the position of this object */ -DisplayObject.prototype.toLocal = function (position, from) { - if (from) { +DisplayObject.prototype.toLocal = function (position, from) +{ + if (from) + { position = from.toGlobal(position); } @@ -381,7 +407,8 @@ * @param renderer {WebGLRenderer} The renderer * @private */ -DisplayObject.prototype.renderWebGL = function (/* renderer */) { +DisplayObject.prototype.renderWebGL = function (/* renderer */) +{ // OVERWRITE; }; @@ -391,6 +418,7 @@ * @param renderer {CanvasRenderer} The renderer * @private */ -DisplayObject.prototype.renderCanvas = function (/* renderer */) { +DisplayObject.prototype.renderCanvas = function (/* renderer */) +{ // OVERWRITE; }; diff --git a/src/core/display/DisplayObjectContainer.js b/src/core/display/DisplayObjectContainer.js index 689f40b..4625ee8 100644 --- a/src/core/display/DisplayObjectContainer.js +++ b/src/core/display/DisplayObjectContainer.js @@ -12,7 +12,8 @@ * @extends DisplayObject * @namespace PIXI */ -function DisplayObjectContainer() { +function DisplayObjectContainer() +{ DisplayObject.call(this); /** @@ -47,17 +48,21 @@ * @memberof DisplayObjectContainer# */ width: { - get: function () { + get: function () + { return this.scale.x * this.getLocalBounds().width; }, - set: function (value) { + set: function (value) + { var width = this.getLocalBounds().width; - if(width !== 0) { + if(width !== 0) + { this.scale.x = value / width; } - else { + else + { this.scale.x = 1; } @@ -73,17 +78,21 @@ * @memberof DisplayObjectContainer# */ height: { - get: function () { + get: function () + { return this.scale.y * this.getLocalBounds().height; }, - set: function (value) { + set: function (value) + { var height = this.getLocalBounds().height; - if (height !== 0) { + if (height !== 0) + { this.scale.y = value / height ; } - else { + else + { this.scale.y = 1; } @@ -100,18 +109,23 @@ * @memberof DisplayObject# */ cacheAsBitmap: { - get: function () { + get: function () + { return this._cacheAsBitmap; }, - set: function (value) { - if (this._cacheAsBitmap === value) { + set: function (value) + { + if (this._cacheAsBitmap === value) + { return; } - if (value) { + if (value) + { this._generateCachedSprite(); } - else { + else + { this._destroyCachedSprite(); } @@ -126,7 +140,8 @@ * @param child {DisplayObject} The DisplayObject to add to the container * @return {DisplayObject} The child that was added. */ -DisplayObjectContainer.prototype.addChild = function (child) { +DisplayObjectContainer.prototype.addChild = function (child) +{ return this.addChildAt(child, this.children.length); }; @@ -137,14 +152,18 @@ * @param index {Number} The index to place the child in * @return {DisplayObject} The child that was added. */ -DisplayObjectContainer.prototype.addChildAt = function (child, index) { +DisplayObjectContainer.prototype.addChildAt = function (child, index) +{ // prevent adding self as child - if (child === this) { + if (child === this) + { return; } - if (index >= 0 && index <= this.children.length) { - if (child.parent) { + if (index >= 0 && index <= this.children.length) + { + if (child.parent) + { child.parent.removeChild(child); } @@ -154,7 +173,8 @@ return child; } - else { + else + { throw new Error(child + 'addChildAt: The index '+ index +' supplied is out of bounds ' + this.children.length); } }; @@ -165,15 +185,18 @@ * @param child {DisplayObject} * @param child2 {DisplayObject} */ -DisplayObjectContainer.prototype.swapChildren = function (child, child2) { - if (child === child2) { +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) { + if (index1 < 0 || index2 < 0) + { throw new Error('swapChildren: Both the supplied DisplayObjects must be a child of the caller.'); } @@ -187,10 +210,12 @@ * @param child {DisplayObject} The DisplayObject instance to identify * @return {Number} The index position of the child display object to identify */ -DisplayObjectContainer.prototype.getChildIndex = function (child) { +DisplayObjectContainer.prototype.getChildIndex = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { throw new Error('The supplied DisplayObject must be a child of the caller'); } @@ -203,8 +228,10 @@ * @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 */ -DisplayObjectContainer.prototype.setChildIndex = function (child, index) { - if (index < 0 || index >= this.children.length) { +DisplayObjectContainer.prototype.setChildIndex = function (child, index) +{ + if (index < 0 || index >= this.children.length) + { throw new Error('The supplied index is out of bounds'); } @@ -220,8 +247,10 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child at the given index, if any. */ -DisplayObjectContainer.prototype.getChildAt = function (index) { - if (index < 0 || index >= this.children.length) { +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'); } @@ -234,10 +263,12 @@ * @param child {DisplayObject} The DisplayObject to remove * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChild = function (child) { +DisplayObjectContainer.prototype.removeChild = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { return; } @@ -250,7 +281,8 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChildAt = function (index) { +DisplayObjectContainer.prototype.removeChildAt = function (index) +{ var child = this.getChildAt(index); child.parent = null; @@ -265,24 +297,29 @@ * @param beginIndex {Number} The beginning position. Default value is 0. * @param endIndex {Number} The ending position. Default value is size of the container. */ -DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) { +DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) +{ var begin = beginIndex || 0; var end = typeof endIndex === 'number' ? endIndex : this.children.length; var range = end - begin; - if (range > 0 && range <= end) { + if (range > 0 && range <= end) + { var removed = this.children.splice(begin, range); - for (var i = 0; i < removed.length; ++i) { + for (var i = 0; i < removed.length; ++i) + { removed[i].parent = null; } return removed; } - else if (range === 0 && this.children.length === 0) { + else if (range === 0 && this.children.length === 0) + { return []; } - else { + else + { throw new RangeError('removeChildren: numeric values are outside the acceptable range.'); } }; @@ -291,7 +328,8 @@ * Generates and updates the cached sprite for this object. * */ -DisplayObjectContainer.prototype.updateCachedSprite = function () { +DisplayObjectContainer.prototype.updateCachedSprite = function () +{ this._generateCachedSprite(); }; @@ -304,7 +342,8 @@ * @param renderer {CanvasRenderer|WebGLRenderer} The renderer used to generate the texture. * @return {Texture} a texture of the graphics object */ -DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) { +DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) +{ var bounds = this.getLocalBounds(); var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0, renderer, scaleMode, resolution); @@ -322,18 +361,22 @@ * * @private */ -DisplayObjectContainer.prototype.updateTransform = function () { - if (!this.visible) { +DisplayObjectContainer.prototype.updateTransform = function () +{ + if (!this.visible) + { return; } this.displayObjectUpdateTransform(); - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { return; } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } }; @@ -346,8 +389,10 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getBounds = function () { - if (this.children.length === 0) { +DisplayObjectContainer.prototype.getBounds = function () +{ + if (this.children.length === 0) + { return math.Rectangle.EMPTY; } @@ -365,10 +410,12 @@ var childVisible = false; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -386,7 +433,8 @@ maxY = maxY > childMaxY ? maxY : childMaxY; } - if (!childVisible) { + if (!childVisible) + { return math.Rectangle.EMPTY; } @@ -407,12 +455,14 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getLocalBounds = function () { +DisplayObjectContainer.prototype.getLocalBounds = function () +{ var matrixCache = this.worldTransform; this.worldTransform = math.Matrix.IDENTITY; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } @@ -428,13 +478,16 @@ * * @param renderer {WebGLRenderer} The renderer */ -DisplayObjectContainer.prototype.renderWebGL = function (renderer) { +DisplayObjectContainer.prototype.renderWebGL = function (renderer) +{ // if the object is not visible or the alpha is 0 then no need to render this element - if (!this.visible || this.alpha <= 0) { + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } @@ -442,14 +495,17 @@ var i, j; // do a quick check to see if this element has a mask or a filter. - if (this._mask || this._filters) { + if (this._mask || this._filters) + { // push filter first as we need to ensure the stencil buffer is correct for any masking - if (this._filters) { + if (this._filters) + { renderer.spriteBatch.flush(); renderer.filterManager.pushFilter(this._filterBlock); } - if (this._mask) { + if (this._mask) + { renderer.spriteBatch.stop(); renderer.maskManager.pushMask(this.mask, renderer); renderer.spriteBatch.start(); @@ -459,36 +515,42 @@ this._renderWebGL(renderer); // now loop through the children and make sure they get rendered - for (i = 0, j = this.children.length; i < j; i++) { + for (i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderWebGL(renderer); } // time to stop the sprite batch as either a mask element or a filter draw will happen next renderer.spriteBatch.stop(); - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(this._mask, renderer); } - if (this._filters) { + if (this._filters) + { renderer.filterManager.popFilter(); } renderer.spriteBatch.start(); } - else { + else + { this._renderWebGL(renderer); // simple render children! - for (i = 0, j = this.children.length; i < j; ++i) { + for (i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderWebGL(renderer); } } }; -DisplayObjectContainer.prototype._renderWebGL = function (renderer) { +DisplayObjectContainer.prototype._renderWebGL = function (renderer) +{ // this is where content itself gets renderd.. @@ -499,25 +561,31 @@ * * @param renderer {CanvasRenderer} The renderer */ -DisplayObjectContainer.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0) { +DisplayObjectContainer.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -528,13 +596,16 @@ * @param renderer {WebGLRenderer|CanvasRenderer} The renderer * @private */ -DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) { +DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) +{ this._cachedSprite.worldAlpha = this.worldAlpha; - if (renderer.gl) { + if (renderer.gl) + { this._cachedSprite.renderWebGL(renderer); } - else { + else + { this._cachedSprite.renderCanvas(renderer); } }; @@ -544,10 +615,12 @@ * * @private */ -DisplayObjectContainer.prototype._generateCachedSprite = function () { +DisplayObjectContainer.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { // TODO - RenderTexture now *requires* a renderer instance, so this is like broken // because `renderer` isn't actually in scope here :P var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0); @@ -555,7 +628,8 @@ this._cachedSprite = new Sprite(renderTexture); this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.texture.resize(bounds.width | 0, bounds.height | 0); } @@ -580,8 +654,10 @@ * * @private */ -DisplayObjectContainer.prototype._destroyCachedSprite = function () { - if (!this._cachedSprite) { +DisplayObjectContainer.prototype._destroyCachedSprite = function () +{ + if (!this._cachedSprite) + { return; } diff --git a/src/core/display/Sprite.js b/src/core/display/Sprite.js index 707da24..5862aef 100644 --- a/src/core/display/Sprite.js +++ b/src/core/display/Sprite.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param texture {Texture} The texture for this sprite */ -function Sprite(texture) { +function Sprite(texture) +{ DisplayObjectContainer.call(this); /** @@ -85,12 +86,14 @@ this.texture = texture || Texture.EMPTY; } -Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) { +Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) +{ DisplayObjectContainer.prototype.destroy.call(this); this.anchor = null; - if (destroyTexture) { + if (destroyTexture) + { this._texture.destroy(destroyBaseTexture); } @@ -111,10 +114,12 @@ * @memberof Sprite# */ width: { - get: function () { + get: function () + { return this.scale.x * this.texture.frame.width; }, - set: function (value) { + set: function (value) + { this.scale.x = value / this.texture.frame.width; this._width = value; } @@ -127,10 +132,12 @@ * @memberof Sprite# */ height: { - get: function () { + get: function () + { return this.scale.y * this.texture.frame.height; }, - set: function (value) { + set: function (value) + { this.scale.y = value / this.texture.frame.height; this._height = value; } @@ -143,23 +150,29 @@ * @memberof Sprite# */ texture: { - get: function () { + get: function () + { return this._texture; }, - set: function (value) { - if (this._texture === value) { + set: function (value) + { + if (this._texture === value) + { return; } this._texture = value; this.cachedTint = 0xFFFFFF; - if (value) { + if (value) + { // wait for the texture to load - if (value.baseTexture.hasLoaded) { + if (value.baseTexture.hasLoaded) + { this._onTextureUpdate(); } - else { + else + { value.once('update', this._onTextureUpdate.bind(this)); } } @@ -172,18 +185,22 @@ * * @private */ -Sprite.prototype._onTextureUpdate = function () { +Sprite.prototype._onTextureUpdate = function () +{ // so if _width is 0 then width was not set.. - if (this._width) { + if (this._width) + { this.scale.x = this._width / this.texture.frame.width; } - if (this._height) { + if (this._height) + { this.scale.y = this._height / this.texture.frame.height; } }; -Sprite.prototype._renderWebGL = function (renderer) { +Sprite.prototype._renderWebGL = function (renderer) +{ // this is where content gets renderd.. // watch this space for a little render state manager.. @@ -197,7 +214,8 @@ * @param matrix {Matrix} the transformation matrix of the sprite * @return {Rectangle} the framing rectangle */ -Sprite.prototype.getBounds = function (matrix) { +Sprite.prototype.getBounds = function (matrix) +{ var width = this.texture.frame.width; var height = this.texture.frame.height; @@ -224,11 +242,13 @@ if(b === 0 && c === 0) { // scale may be negative! - if (a < 0) { + if (a < 0) + { a *= -1; } - if (d < 0) { + if (d < 0) + { d *= -1; } @@ -293,28 +313,34 @@ * * @param renderer {CanvasRenderer} The renderer */ -Sprite.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) { +Sprite.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) + { return; } - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; renderer.context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } // Ignore null sources - if (this.texture.valid) { + if (this.texture.valid) + { var resolution = this.texture.baseTexture.resolution / renderer.resolution; renderer.context.globalAlpha = this.worldAlpha; // If smoothingEnabled is supported and we need to change the smoothing property for this texture - if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) { + if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) + { renderer.scaleMode = this.texture.baseTexture.scaleMode; renderer.context[renderer.smoothProperty] = (renderer.scaleMode === CONST.scaleModes.LINEAR); } @@ -324,7 +350,8 @@ var dy = (this.texture.trim ? this.texture.trim.y : 0) - (this.anchor.y * this.texture.trim.height); // Allow for pixel rounding - if (renderer.roundPixels) { + if (renderer.roundPixels) + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -337,7 +364,8 @@ dx = dx | 0; dy = dy | 0; } - else { + else + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -348,8 +376,10 @@ ); } - if (this.tint !== 0xFFFFFF) { - if (this.cachedTint !== this.tint) { + if (this.tint !== 0xFFFFFF) + { + if (this.cachedTint !== this.tint) + { this.cachedTint = this.tint; // TODO clean up caching - how to clean up the caches? @@ -368,7 +398,8 @@ this.texture.crop.height / resolution ); } - else { + else + { renderer.context.drawImage( this.texture.baseTexture.source, this.texture.crop.x, @@ -383,11 +414,13 @@ } } - for (var i = 0, j = this.children.length; i < j; i++) { + for (var i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -402,10 +435,12 @@ * @param frameId {String} The frame Id of the texture in the cache * @return {Sprite} A new Sprite using a texture from the texture cache matching the frameId */ -Sprite.fromFrame = function (frameId) { +Sprite.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache' + this); } @@ -420,6 +455,7 @@ * @param imageId {String} The image url of the texture * @return {Sprite} A new Sprite using a texture from the texture cache matching the image id */ -Sprite.fromImage = function (imageId, crossorigin, scaleMode) { +Sprite.fromImage = function (imageId, crossorigin, scaleMode) +{ return new Sprite(Texture.fromImage(imageId, crossorigin, scaleMode)); }; diff --git a/src/core/display/SpriteBatch.js b/src/core/display/SpriteBatch.js index 3187777..c196fef 100644 --- a/src/core/display/SpriteBatch.js +++ b/src/core/display/SpriteBatch.js @@ -12,7 +12,8 @@ * ```js * var container = new SpriteBatch(); * - * for(var i = 0; i < 100; ++i) { + * for(var i = 0; i < 100; ++i) + * { * var sprite = new PIXI.Sprite.fromImage("myImage.png"); * container.addChild(sprite); * } @@ -25,7 +26,8 @@ */ //TODO RENAME to PARTICLE CONTAINER? -function SpriteBatch() { +function SpriteBatch() +{ DisplayObjectContainer.call(this); } @@ -38,7 +40,8 @@ * * @private */ -SpriteBatch.prototype.updateTransform = function () { +SpriteBatch.prototype.updateTransform = function () +{ // TODO don't need to! this.displayObjectUpdateTransform(); // PIXI.DisplayObjectContainer.prototype.updateTransform.call( this ); @@ -50,8 +53,10 @@ * @param renderer {WebGLRenderer} The webgl renderer * @private */ -SpriteBatch.prototype.renderWebGL = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderWebGL = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -71,8 +76,10 @@ * @param renderer {CanvasRenderer} The canvas renderer * @private */ -SpriteBatch.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -84,10 +91,12 @@ this.displayObjectUpdateTransform(); - for (var i = 0; i < this.children.length; ++i) { + for (var i = 0; i < this.children.length; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -95,9 +104,11 @@ context.globalAlpha = this.worldAlpha * child.alpha; - if (child.rotation % (Math.PI * 2) === 0) { + if (child.rotation % (Math.PI * 2) === 0) + { // this is the fastest way to optimise! - if rotation is 0 then we can avoid any kind of setTransform call - if (isRotated) { + if (isRotated) + { context.setTransform( transform.a, transform.b, @@ -122,8 +133,10 @@ frame.height * child.scale.y ); } - else { - if (!isRotated) { + else + { + if (!isRotated) + { isRotated = true; } @@ -131,7 +144,8 @@ var childTransform = child.worldTransform; - if (renderer.roundPixels) { + if (renderer.roundPixels) + { context.setTransform( childTransform.a, childTransform.b, @@ -141,7 +155,8 @@ childTransform.ty | 0 ); } - else { + else + { context.setTransform( childTransform.a, childTransform.b, diff --git a/src/core/index.js b/src/core/index.js index 3954b6f..eb4a82b 100644 --- a/src/core/index.js +++ b/src/core/index.js @@ -58,11 +58,13 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRenderer: function (width, height, options, noWebGL) { + autoDetectRenderer: function (width, height, options, noWebGL) + { width = width || 800; height = height || 600; - if (!noWebGL && require('webgl-enabled')()) { + if (!noWebGL && require('webgl-enabled')()) + { return new core.WebGLRenderer(width, height, options); } @@ -87,7 +89,8 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRecommendedRenderer: function (width, height, options) { + autoDetectRecommendedRenderer: function (width, height, options) + { var isAndroid = /Android/i.test(navigator.userAgent); return core.autoDetectRenderer(width, height, options, isAndroid); diff --git a/src/core/math/Matrix.js b/src/core/math/Matrix.js index c2f87e2..2ff4848 100644 --- a/src/core/math/Matrix.js +++ b/src/core/math/Matrix.js @@ -10,7 +10,8 @@ * @class * @namespace PIXI */ -function Matrix() { +function Matrix() +{ /** * @member {number} * @default 1 @@ -63,7 +64,8 @@ * * @param array {number[]} The array that the matrix will be populated from. */ -Matrix.prototype.fromArray = function (array) { +Matrix.prototype.fromArray = function (array) +{ this.a = array[0]; this.b = array[1]; this.c = array[3]; @@ -78,14 +80,17 @@ * @param transpose {boolean} Whether we need to transpose the matrix or not * @return {number[]} the newly created array which contains the matrix */ -Matrix.prototype.toArray = function (transpose) { - if (!this.array) { +Matrix.prototype.toArray = function (transpose) +{ + if (!this.array) + { this.array = new Float32Array(9); } var array = this.array; - if (transpose) { + if (transpose) + { array[0] = this.a; array[1] = this.b; array[2] = 0; @@ -96,7 +101,8 @@ array[7] = this.ty; array[8] = 1; } - else { + else + { array[0] = this.a; array[1] = this.c; array[2] = this.tx; @@ -119,7 +125,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, transformed through this matrix */ -Matrix.prototype.apply = function (pos, newPos) { +Matrix.prototype.apply = function (pos, newPos) +{ newPos = newPos || new Point(); newPos.x = this.a * pos.x + this.c * pos.y + this.tx; @@ -136,7 +143,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, inverse-transformed through this matrix */ -Matrix.prototype.applyInverse = function (pos, newPos) { +Matrix.prototype.applyInverse = function (pos, newPos) +{ newPos = newPos || new Point(); var id = 1 / (this.a * this.d + this.c * -this.b); @@ -154,7 +162,8 @@ * @param {number} y * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.translate = function (x, y) { +Matrix.prototype.translate = function (x, y) +{ this.tx += x; this.ty += y; @@ -168,7 +177,8 @@ * @param {number} y The amount to scale vertically * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.scale = function (x, y) { +Matrix.prototype.scale = function (x, y) +{ this.a *= x; this.d *= y; this.c *= x; @@ -186,7 +196,8 @@ * @param {number} angle - The angle in radians. * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.rotate = function (angle) { +Matrix.prototype.rotate = function (angle) +{ var cos = Math.cos( angle ); var sin = Math.sin( angle ); @@ -210,7 +221,8 @@ * @param {Matrix} matrix * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.append = function (matrix) { +Matrix.prototype.append = function (matrix) +{ var a1 = this.a; var b1 = this.b; var c1 = this.c; @@ -232,7 +244,8 @@ * * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.identity = function () { +Matrix.prototype.identity = function () +{ this.a = 1; this.b = 0; this.c = 0; diff --git a/src/core/math/Point.js b/src/core/math/Point.js index 7565b2d..632f346 100644 --- a/src/core/math/Point.js +++ b/src/core/math/Point.js @@ -7,7 +7,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -function Point(x, y) { +function Point(x, y) +{ /** * @member {number} * @default 0 @@ -29,7 +30,8 @@ * * @return {Point} a copy of the point */ -Point.prototype.clone = function () { +Point.prototype.clone = function () +{ return new Point(this.x, this.y); }; @@ -40,7 +42,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -Point.prototype.set = function (x, y) { +Point.prototype.set = function (x, y) +{ this.x = x || 0; this.y = y || ( (y !== 0) ? this.x : 0 ) ; }; diff --git a/src/core/math/shapes/Circle.js b/src/core/math/shapes/Circle.js index 69cfdc9..4d76efc 100644 --- a/src/core/math/shapes/Circle.js +++ b/src/core/math/shapes/Circle.js @@ -10,7 +10,8 @@ * @param y {number} The Y coordinate of the center of this circle * @param radius {number} The radius of the circle */ -function Circle(x, y, radius) { +function Circle(x, y, radius) +{ /** * @member {number} * @default 0 @@ -46,7 +47,8 @@ * @method clone * @return {Circle} a copy of the Circle */ -Circle.prototype.clone = function () { +Circle.prototype.clone = function () +{ return new Circle(this.x, this.y, this.radius); }; @@ -58,8 +60,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Circle */ -Circle.prototype.contains = function (x, y) { - if (this.radius <= 0) { +Circle.prototype.contains = function (x, y) +{ + if (this.radius <= 0) + { return false; } @@ -79,6 +83,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Circle.prototype.getBounds = function () { +Circle.prototype.getBounds = function () +{ return new Rectangle(this.x - this.radius, this.y - this.radius, this.radius * 2, this.radius * 2); }; diff --git a/src/core/math/shapes/Ellipse.js b/src/core/math/shapes/Ellipse.js index 4f2d066..fefd01a 100644 --- a/src/core/math/shapes/Ellipse.js +++ b/src/core/math/shapes/Ellipse.js @@ -11,7 +11,8 @@ * @param width {number} The half width of this ellipse * @param height {number} The half height of this ellipse */ -function Ellipse(x, y, width, height) { +function Ellipse(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -53,7 +54,8 @@ * @method clone * @return {Ellipse} a copy of the ellipse */ -Ellipse.prototype.clone = function () { +Ellipse.prototype.clone = function () +{ return new Ellipse(this.x, this.y, this.width, this.height); }; @@ -65,8 +67,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coords are within this ellipse */ -Ellipse.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Ellipse.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } @@ -86,6 +90,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Ellipse.prototype.getBounds = function () { +Ellipse.prototype.getBounds = function () +{ return new Rectangle(this.x - this.width, this.y - this.height, this.width, this.height); }; diff --git a/src/core/math/shapes/Polygon.js b/src/core/math/shapes/Polygon.js index ae89148..fea6d37 100644 --- a/src/core/math/shapes/Polygon.js +++ b/src/core/math/shapes/Polygon.js @@ -10,16 +10,20 @@ * arguments passed can be flat x,y values e.g. `new Polygon(x,y, x,y, x,y, ...)` where `x` and `y` are * Numbers. */ -function Polygon(points) { +function Polygon(points) +{ //if points isn't an array, use arguments as the array - if (!(points instanceof Array)) { + if (!(points instanceof Array)) + { points = Array.prototype.slice.call(arguments); } //if this is a flat array of numbers, convert it to points - if (points[0] instanceof Point) { + if (points[0] instanceof Point) + { var p = []; - for (var i = 0, il = points.length; i < il; i++) { + for (var i = 0, il = points.length; i < il; i++) + { p.push(points[i].x, points[i].y); } @@ -51,7 +55,8 @@ * * @return {Polygon} a copy of the polygon */ -Polygon.prototype.clone = function () { +Polygon.prototype.clone = function () +{ return new Polygon(this.points.slice()); }; @@ -62,19 +67,22 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this polygon */ -Polygon.prototype.contains = function (x, y) { +Polygon.prototype.contains = function (x, y) +{ var inside = false; // use some raycasting to test hits // https://github.com/substack/point-in-polygon/blob/master/index.js var length = this.points.length / 2; - for (var i = 0, j = length - 1; i < length; j = i++) { + for (var i = 0, j = length - 1; i < length; j = i++) + { var xi = this.points[i * 2], yi = this.points[i * 2 + 1], xj = this.points[j * 2], yj = this.points[j * 2 + 1], intersect = ((yi > y) !== (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi); - if (intersect) { + if (intersect) + { inside = !inside; } } diff --git a/src/core/math/shapes/Rectangle.js b/src/core/math/shapes/Rectangle.js index 16ac62a..4008b68 100644 --- a/src/core/math/shapes/Rectangle.js +++ b/src/core/math/shapes/Rectangle.js @@ -10,7 +10,8 @@ * @param width {number} The overall width of this rectangle * @param height {number} The overall height of this rectangle */ -function Rectangle(x, y, width, height) { +function Rectangle(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -60,7 +61,8 @@ * * @return {Rectangle} a copy of the rectangle */ -Rectangle.prototype.clone = function () { +Rectangle.prototype.clone = function () +{ return new Rectangle(this.x, this.y, this.width, this.height); }; @@ -71,13 +73,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rectangle */ -Rectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Rectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/math/shapes/RoundedRectangle.js b/src/core/math/shapes/RoundedRectangle.js index 27d286e..7bf6411 100644 --- a/src/core/math/shapes/RoundedRectangle.js +++ b/src/core/math/shapes/RoundedRectangle.js @@ -11,7 +11,8 @@ * @param height {number} The overall height of this rounded rectangle * @param radius {number} Controls the radius of the rounded corners */ -function RoundedRectangle(x, y, width, height, radius) { +function RoundedRectangle(x, y, width, height, radius) +{ /** * @member {number} * @default 0 @@ -58,7 +59,8 @@ * * @return {RoundedRectangle} a copy of the rounded rectangle */ -RoundedRectangle.prototype.clone = function () { +RoundedRectangle.prototype.clone = function () +{ return new RoundedRectangle(this.x, this.y, this.width, this.height, this.radius); }; @@ -69,13 +71,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rounded Rectangle */ -RoundedRectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +RoundedRectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/primitives/Graphics.js b/src/core/primitives/Graphics.js index 261c534..e902d2a 100644 --- a/src/core/primitives/Graphics.js +++ b/src/core/primitives/Graphics.js @@ -16,7 +16,8 @@ * @extends DisplayObjectContainer * @namespace PIXI */ -function Graphics() { +function Graphics() +{ DisplayObjectContainer.call(this); this.renderable = true; @@ -154,16 +155,20 @@ * @private */ cacheAsBitmap: { - get: function () { + get: function () + { return this._cacheAsBitmap; }, - set: function (value) { + set: function (value) + { this._cacheAsBitmap = value; - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._generateCachedSprite(); } - else { + else + { this.destroyCachedSprite(); this.dirty = true; } @@ -176,7 +181,8 @@ * * @return {Graphics} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ var clone = new Graphics(); clone.renderable = this.renderable; @@ -192,7 +198,8 @@ clone.cachedSpriteDirty = this.cachedSpriteDirty; // copy graphics data - for (var i = 0; i < this.graphicsData.length; ++i) { + for (var i = 0; i < this.graphicsData.length; ++i) + { clone.graphicsData.push(this.graphicsData.clone()); } @@ -211,17 +218,21 @@ * @param alpha {number} alpha of the line to draw, will update the objects stored style * @return {Graphics} */ -Graphics.prototype.lineStyle = function (lineWidth, color, alpha) { +Graphics.prototype.lineStyle = function (lineWidth, color, alpha) +{ this.lineWidth = lineWidth || 0; this.lineColor = color || 0; this.lineAlpha = (arguments.length < 3) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length) + { // halfway through a line? start a new one! this.drawShape( new math.Polygon( this.currentPath.shape.points.slice(-2) )); } - else { + else + { // otherwise its empty so lets just set the line properties this.currentPath.lineWidth = this.lineWidth; this.currentPath.lineColor = this.lineColor; @@ -239,7 +250,8 @@ * @param y {number} the Y coordinate to move to * @return {Graphics} */ -Graphics.prototype.moveTo = function (x, y) { +Graphics.prototype.moveTo = function (x, y) +{ this.drawShape(new math.Polygon([x,y])); return this; @@ -253,7 +265,8 @@ * @param y {number} the Y coordinate to draw to * @return {Graphics} */ -Graphics.prototype.lineTo = function (x, y) { +Graphics.prototype.lineTo = function (x, y) +{ this.currentPath.shape.points.push(x, y); this.dirty = true; @@ -270,13 +283,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -285,7 +302,8 @@ n = 20, points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { this.moveTo(0, 0); } @@ -293,7 +311,8 @@ var fromY = points[points.length-1]; var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; xa = fromX + ( (cpX - fromX) * j ); @@ -319,13 +338,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -342,7 +365,8 @@ var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; dt = (1 - j); @@ -373,13 +397,17 @@ * @param radius {number} The radius of the arc * @return {Graphics} */ -Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points.push(x1, y1); } } - else { + else + { this.moveTo(x1, y1); } @@ -392,12 +420,15 @@ b2 = x2 - x1, mm = Math.abs(a1 * b2 - b1 * a2); - if (mm < 1.0e-8 || radius === 0) { - if (points[points.length-2] !== x1 || points[points.length-1] !== y1) { + if (mm < 1.0e-8 || radius === 0) + { + if (points[points.length-2] !== x1 || points[points.length-1] !== y1) + { points.push(x1, y1); } } - else { + else + { var dd = a1 * a1 + b1 * b1, cc = a2 * a2 + b2 * b2, tt = a1 * a2 + b1 * b2, @@ -433,42 +464,51 @@ * @param anticlockwise {boolean} Optional. Specifies whether the drawing should be counterclockwise or clockwise. False is default, and indicates clockwise, while true indicates counter-clockwise. * @return {Graphics} */ -Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) { +Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) +{ var startX = cx + Math.cos(startAngle) * radius; var startY = cy + Math.sin(startAngle) * radius; var points; // TODO - This if-else makes no sense. It uses currentPath in the else where it doesn't exist... - if (this.currentPath) { + if (this.currentPath) + { points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { points.push(startX, startY); } - else if (points[points.length-2] !== startX || points[points.length-1] !== startY) { + else if (points[points.length-2] !== startX || points[points.length-1] !== startY) + { points.push(startX, startY); } } - else { + else + { this.moveTo(startX, startY); points = this.currentPath.shape.points; } - if (startAngle === endAngle) { + if (startAngle === endAngle) + { return this; } - if (!anticlockwise && endAngle <= startAngle) { + if (!anticlockwise && endAngle <= startAngle) + { endAngle += Math.PI * 2; } - else if (anticlockwise && startAngle <= endAngle) { + else if (anticlockwise && startAngle <= endAngle) + { startAngle += Math.PI * 2; } var sweep = anticlockwise ? (startAngle - endAngle) *-1 : (endAngle - startAngle); var segs = (Math.abs(sweep)/ (Math.PI * 2)) * 40; - if (sweep === 0) { + if (sweep === 0) + { return this; } @@ -482,7 +522,8 @@ var remainder = ( segMinus % 1 ) / segMinus; - for (var i = 0; i <= segMinus; ++i) { + for (var i = 0; i <= segMinus; ++i) + { var real = i + remainder * i; var angle = ((theta) + startAngle + (theta2 * real)); @@ -506,13 +547,16 @@ * @param alpha {number} the alpha of the fill * @return {Graphics} */ -Graphics.prototype.beginFill = function (color, alpha) { +Graphics.prototype.beginFill = function (color, alpha) +{ this.filling = true; this.fillColor = color || 0; this.fillAlpha = (alpha === undefined) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length <= 2) + { this.currentPath.fill = this.filling; this.currentPath.fillColor = this.fillColor; this.currentPath.fillAlpha = this.fillAlpha; @@ -526,7 +570,8 @@ * * @return {Graphics} */ -Graphics.prototype.endFill = function () { +Graphics.prototype.endFill = function () +{ this.filling = false; this.fillColor = null; this.fillAlpha = 1; @@ -542,7 +587,8 @@ * @param height {number} The height of the rectangle * @return {Graphics} */ -Graphics.prototype.drawRect = function ( x, y, width, height ) { +Graphics.prototype.drawRect = function ( x, y, width, height ) +{ this.drawShape(new math.Rectangle(x,y, width, height)); return this; @@ -556,7 +602,8 @@ * @param height {number} The height of the rectangle * @param radius {number} Radius of the rectangle corners */ -Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) { +Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) +{ this.drawShape(new math.RoundedRectangle(x, y, width, height, radius)); return this; @@ -570,7 +617,8 @@ * @param radius {number} The radius of the circle * @return {Graphics} */ -Graphics.prototype.drawCircle = function (x, y, radius) { +Graphics.prototype.drawCircle = function (x, y, radius) +{ this.drawShape(new math.Circle(x,y, radius)); return this; @@ -585,7 +633,8 @@ * @param height {number} The half height of the ellipse * @return {Graphics} */ -Graphics.prototype.drawEllipse = function (x, y, width, height) { +Graphics.prototype.drawEllipse = function (x, y, width, height) +{ this.drawShape(new math.Ellipse(x, y, width, height)); return this; @@ -597,8 +646,10 @@ * @param path {Array} The path data used to construct the polygon. * @return {Graphics} */ -Graphics.prototype.drawPolygon = function (path) { - if (!(path instanceof Array)) { +Graphics.prototype.drawPolygon = function (path) +{ + if (!(path instanceof Array)) + { path = Array.prototype.slice.call(arguments); } @@ -612,7 +663,8 @@ * * @return {Graphics} */ -Graphics.prototype.clear = function () { +Graphics.prototype.clear = function () +{ this.lineWidth = 0; this.filling = false; @@ -631,7 +683,8 @@ * @param scaleMode {number} Should be one of the scaleMode consts * @return {Texture} a texture of the graphics object */ -Graphics.prototype.generateTexture = function (resolution, scaleMode) { +Graphics.prototype.generateTexture = function (resolution, scaleMode) +{ resolution = resolution || 1; var bounds = this.getBounds(); @@ -655,17 +708,21 @@ * * @param renderer {WebGLRenderer} */ -Graphics.prototype._renderWebGL = function (renderer) { +Graphics.prototype._renderWebGL = function (renderer) +{ // if the sprite is not visible or the alpha is 0 then no need to render this element - if (this.isMask === true) { + if (this.isMask === true) + { return; } // this code may still be needed so leaving for now.. - // + // /* - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture on the gpu too! @@ -681,17 +738,24 @@ return; } - */ - - // check if the webgl graphic needs to be updated - if (this.glDirty) { - this.dirty = true; - this.glDirty = false; - } + else */ - renderer.setObjectRendererer(renderer.graphicsRenderer); - renderer.graphicsRenderer.render(this); + renderer.spriteBatch.stop(); + renderer.blendModeManager.setBlendMode(this.blendMode); + // check blend mode + renderer.blendModeManager.setBlendMode( this.blendMode ); + + // check if the webgl graphic needs to be updated + if (this.glDirty) + { + this.dirty = true; + this.glDirty = false; + } + + WebGLGraphics.renderGraphics(this, renderer); + + renderer.spriteBatch.start(); }; /** @@ -700,14 +764,18 @@ * @param renderer {CanvasRenderer} * @private */ -Graphics.prototype.renderCanvas = function (renderer) { +Graphics.prototype.renderCanvas = function (renderer) +{ // 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.isMask === true) { + if (!this.visible || this.alpha <= 0 || this.isMask === true) + { return; } - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture @@ -723,16 +791,19 @@ return; } - else { + else + { var context = renderer.context; var transform = this.worldTransform; - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } @@ -748,11 +819,13 @@ CanvasGraphics.renderGraphics(this, context); - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } } @@ -763,13 +836,16 @@ * * @return {Rectangle} the rectangular bounding area */ -Graphics.prototype.getBounds = function (matrix) { +Graphics.prototype.getBounds = function (matrix) +{ // return an empty object if the item is a mask! - if (this.isMask) { + if (this.isMask) + { return math.Rectangle.EMPTY; } - if (this.dirty) { + if (this.dirty) + { this.updateLocalBounds(); this.glDirty = true; @@ -841,23 +917,27 @@ * Update the bounds of the object * */ -Graphics.prototype.updateLocalBounds = function () { +Graphics.prototype.updateLocalBounds = function () +{ var minX = Infinity; var maxX = -Infinity; var minY = Infinity; var maxY = -Infinity; - if (this.graphicsData.length) { + if (this.graphicsData.length) + { var shape, points, x, y, w, h; - for (var i = 0; i < this.graphicsData.length; i++) { + for (var i = 0; i < this.graphicsData.length; i++) + { var data = this.graphicsData[i]; var type = data.type; var lineWidth = data.lineWidth; shape = data.shape; - if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) { + if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) + { x = shape.x - lineWidth/2; y = shape.y - lineWidth/2; w = shape.width + lineWidth; @@ -869,7 +949,8 @@ minY = y < minY ? y : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.CIRC) { + else if (type === CONST.SHAPES.CIRC) + { x = shape.x; y = shape.y; w = shape.radius + lineWidth/2; @@ -881,7 +962,8 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.ELIP) { + else if (type === CONST.SHAPES.ELIP) + { x = shape.x; y = shape.y; w = shape.width + lineWidth/2; @@ -893,11 +975,13 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else { + else + { // POLY points = shape.points; - for (var j = 0; j < points.length; j += 2) { + for (var j = 0; j < points.length; j += 2) + { x = points[j]; y = points[j+1]; @@ -910,7 +994,8 @@ } } } - else { + else + { minX = 0; maxX = 0; minY = 0; @@ -931,10 +1016,12 @@ * * @private */ -Graphics.prototype._generateCachedSprite = function () { +Graphics.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { var canvasBuffer = new CanvasBuffer(bounds.width, bounds.height); var texture = Texture.fromCanvas(canvasBuffer.canvas); @@ -943,7 +1030,8 @@ this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.buffer.resize(bounds.width, bounds.height); } @@ -968,7 +1056,8 @@ * * @private */ -Graphics.prototype.updateCachedSpriteTexture = function () { +Graphics.prototype.updateCachedSpriteTexture = function () +{ var cachedSprite = this._cachedSprite; var texture = cachedSprite.texture; var canvas = cachedSprite.buffer.canvas; @@ -989,7 +1078,8 @@ * Destroys a previous cached sprite. * */ -Graphics.prototype.destroyCachedSprite = function () { +Graphics.prototype.destroyCachedSprite = function () +{ this._cachedSprite.texture.destroy(true); // let the gc collect the unused sprite @@ -1003,10 +1093,13 @@ * @param {Circle|Rectangle|Ellipse|Line|Polygon} shape The Shape object to draw. * @return {GraphicsData} The generated GraphicsData object. */ -Graphics.prototype.drawShape = function (shape) { - if (this.currentPath) { +Graphics.prototype.drawShape = function (shape) +{ + if (this.currentPath) + { // check current path! - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath.shape.points.length <= 2) + { this.graphicsData.pop(); } } @@ -1017,7 +1110,8 @@ this.graphicsData.push(data); - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { data.shape.closed = this.filling; this.currentPath = data; } diff --git a/src/core/primitives/GraphicsData.js b/src/core/primitives/GraphicsData.js index 99decbe..788f6f2 100644 --- a/src/core/primitives/GraphicsData.js +++ b/src/core/primitives/GraphicsData.js @@ -4,7 +4,8 @@ * @class * @namespace PIXI */ -function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) { +function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) +{ this.lineWidth = lineWidth; this.lineColor = lineColor; this.lineAlpha = lineAlpha; @@ -27,7 +28,8 @@ * * @return {GraphicsData} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ return new GraphicsData( this.lineWidth, this.lineColor, diff --git a/src/core/renderers/canvas/CanvasRenderer.js b/src/core/renderers/canvas/CanvasRenderer.js index 15a0978..7aebd44 100644 --- a/src/core/renderers/canvas/CanvasRenderer.js +++ b/src/core/renderers/canvas/CanvasRenderer.js @@ -17,17 +17,22 @@ * @param [options.resolution=1] {number} the resolution of the renderer retina would be 2 * @param [options.clearBeforeRender=true] {boolean} This sets if the CanvasRenderer will clear the canvas or not before the new render pass. */ -function CanvasRenderer(width, height, options) { +function CanvasRenderer(width, height, options) +{ utils.sayHello('Canvas'); - if (options) { - for (var i in CONST.defaultRenderOptions) { - if (typeof options[i] === 'undefined') { + if (options) + { + for (var i in CONST.defaultRenderOptions) + { + if (typeof options[i] === 'undefined') + { options[i] = CONST.defaultRenderOptions[i]; } } } - else { + else + { options = CONST.defaultRenderOptions; } @@ -156,19 +161,24 @@ this.smoothProperty = null; - if (this.context.imageSmoothingEnabled) { + if (this.context.imageSmoothingEnabled) + { this.smoothProperty = 'imageSmoothingEnabled'; } - else if (this.context.webkitImageSmoothingEnabled) { + else if (this.context.webkitImageSmoothingEnabled) + { this.smoothProperty = 'webkitImageSmoothingEnabled'; } - else if (this.context.mozImageSmoothingEnabled) { + else if (this.context.mozImageSmoothingEnabled) + { this.smoothProperty = 'mozImageSmoothingEnabled'; } - else if (this.context.oImageSmoothingEnabled) { + else if (this.context.oImageSmoothingEnabled) + { this.smoothProperty = 'oImageSmoothingEnabled'; } - else if (this.context.msImageSmoothingEnabled) { + else if (this.context.msImageSmoothingEnabled) + { this.smoothProperty = 'msImageSmoothingEnabled'; } @@ -193,10 +203,12 @@ * @memberof CanvasRenderer# */ backgroundColor: { - get: function () { + get: function () + { return this._backgroundColor; }, - set: function (val) { + set: function (val) + { this._backgroundColor = val; this._backgroundColorString = utils.hex2string(val); } @@ -208,7 +220,8 @@ * * @param object {DisplayObject} the object to be rendered */ -CanvasRenderer.prototype.render = function (object) { +CanvasRenderer.prototype.render = function (object) +{ object.updateTransform(); this.context.setTransform(1,0,0,1,0,0); @@ -218,16 +231,20 @@ this.currentBlendMode = CONST.blendModes.NORMAL; this.context.globalCompositeOperation = this.blendModes[CONST.blendModes.NORMAL]; - if (navigator.isCocoonJS && this.view.screencanvas) { + if (navigator.isCocoonJS && this.view.screencanvas) + { this.context.fillStyle = 'black'; this.context.clear(); } - if (this.clearBeforeRender) { - if (this.transparent) { + if (this.clearBeforeRender) + { + if (this.transparent) + { this.context.clearRect(0, 0, this.width, this.height); } - else { + else + { this.context.fillStyle = this._backgroundColorString; this.context.fillRect(0, 0, this.width , this.height); } @@ -241,8 +258,10 @@ * * @param [removeView=false] {boolean} Removes the Canvas element from the DOM. */ -CanvasRenderer.prototype.destroy = function (removeView) { - if (removeView && this.view.parent) { +CanvasRenderer.prototype.destroy = function (removeView) +{ + if (removeView && this.view.parent) + { this.view.parent.removeChild(this.view); } @@ -257,14 +276,16 @@ * @param width {number} the new width of the canvas view * @param height {number} the new height of the canvas view */ -CanvasRenderer.prototype.resize = function (width, height) { +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) { + if (this.autoResize) + { this.view.style.width = this.width / this.resolution + 'px'; this.view.style.height = this.height / this.resolution + 'px'; } @@ -276,7 +297,8 @@ * @param displayObject {DisplayObject} The displayObject to render * @private */ -CanvasRenderer.prototype.renderDisplayObject = function (displayObject) { +CanvasRenderer.prototype.renderDisplayObject = function (displayObject) +{ displayObject.renderCanvas(this); }; @@ -285,11 +307,14 @@ * * @private */ -CanvasRenderer.prototype._mapBlendModes = function () { - if (!this.blendModes) { +CanvasRenderer.prototype._mapBlendModes = function () +{ + if (!this.blendModes) + { this.blendModes = {}; - if (utils.canUseNewCanvasBlendModes()) { + if (utils.canUseNewCanvasBlendModes()) + { this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? this.blendModes[CONST.blendModes.MULTIPLY] = 'multiply'; @@ -308,7 +333,8 @@ this.blendModes[CONST.blendModes.COLOR] = 'color'; this.blendModes[CONST.blendModes.LUMINOSITY] = 'luminosity'; } - else { + else + { // this means that the browser does not support the cool new blend modes in canvas 'cough' ie 'cough' this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? diff --git a/src/core/renderers/canvas/utils/CanvasBuffer.js b/src/core/renderers/canvas/utils/CanvasBuffer.js index ebe5d47..b183a66 100644 --- a/src/core/renderers/canvas/utils/CanvasBuffer.js +++ b/src/core/renderers/canvas/utils/CanvasBuffer.js @@ -6,7 +6,8 @@ * @param width {number} the width for the newly created canvas * @param height {number} the height for the newly created canvas */ -function CanvasBuffer(width, height) { +function CanvasBuffer(width, height) +{ /** * The Canvas object that belongs to this CanvasBuffer. * @@ -36,10 +37,12 @@ * @memberof CanvasBuffer# */ width: { - get: function () { + get: function () + { return this.canvas.width; }, - set: function (val) { + set: function (val) + { this.canvas.width = val; } }, @@ -50,10 +53,12 @@ * @memberof CanvasBuffer# */ height: { - get: function () { + get: function () + { return this.canvas.height; }, - set: function (val) { + set: function (val) + { this.canvas.height = val; } } @@ -64,7 +69,8 @@ * * @private */ -CanvasBuffer.prototype.clear = function () { +CanvasBuffer.prototype.clear = function () +{ this.context.setTransform(1, 0, 0, 1, 0, 0); this.context.clearRect(0,0, this.canvas.width, this.canvas.height); }; @@ -75,7 +81,8 @@ * @param width {number} the new width of the canvas * @param height {number} the new height of the canvas */ -CanvasBuffer.prototype.resize = function (width, height) { +CanvasBuffer.prototype.resize = function (width, height) +{ this.canvas.width = width; this.canvas.height = height; }; diff --git a/src/core/renderers/canvas/utils/CanvasGraphics.js b/src/core/renderers/canvas/utils/CanvasGraphics.js index c7eaa2a..3f2a91f 100644 --- a/src/core/renderers/canvas/utils/CanvasGraphics.js +++ b/src/core/renderers/canvas/utils/CanvasGraphics.js @@ -13,15 +13,18 @@ * @param graphics {Graphics} the actual graphics object to render * @param context {CanvasRenderingContext2D} the 2d drawing method of the canvas */ -CanvasGraphics.renderGraphics = function (graphics, context) { +CanvasGraphics.renderGraphics = function (graphics, context) +{ var worldAlpha = graphics.worldAlpha; - if (graphics.dirty) { + if (graphics.dirty) + { this.updateGraphicsTint(graphics); graphics.dirty = false; } - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; @@ -30,69 +33,82 @@ context.lineWidth = data.lineWidth; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { context.beginPath(); var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } - if (shape.closed) { + if (shape.closed) + { context.lineTo(points[0], points[1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fillRect(shape.x, shape.y, shape.width, shape.height); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.strokeRect(shape.x, shape.y, shape.width, shape.height); } } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.beginPath(); context.arc(shape.x, shape.y, shape.radius,0,2*Math.PI); context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas var w = shape.width * 2; @@ -119,18 +135,21 @@ context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; var width = shape.width; @@ -152,13 +171,15 @@ context.quadraticCurveTo(rx, ry, rx, ry + radius); context.closePath(); - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); @@ -174,45 +195,54 @@ * @param graphics {Graphics} the graphics which will be used as a mask * @param context {CanvasRenderingContext2D} the context 2d method of the canvas */ -CanvasGraphics.renderGraphicsMask = function (graphics, context) { +CanvasGraphics.renderGraphicsMask = function (graphics, context) +{ var len = graphics.graphicsData.length; - if (len === 0) { + if (len === 0) + { return; } context.beginPath(); - for (var i = 0; i < len; i++) { + for (var i = 0; i < len; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { context.rect(shape.x, shape.y, shape.width, shape.height); context.closePath(); } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.arc(shape.x, shape.y, shape.radius, 0, 2 * Math.PI); context.closePath(); } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas @@ -237,7 +267,8 @@ context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); context.closePath(); } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; @@ -262,8 +293,10 @@ } }; -CanvasGraphics.updateGraphicsTint = function (graphics) { - if (graphics.tint === 0xFFFFFF) { +CanvasGraphics.updateGraphicsTint = function (graphics) +{ + if (graphics.tint === 0xFFFFFF) + { return; } @@ -271,7 +304,8 @@ var tintG = (graphics.tint >> 8 & 0xFF) / 255; var tintB = (graphics.tint & 0xFF)/ 255; - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var fillColor = data.fillColor | 0; diff --git a/src/core/renderers/canvas/utils/CanvasMaskManager.js b/src/core/renderers/canvas/utils/CanvasMaskManager.js index e04a733..9827d36 100644 --- a/src/core/renderers/canvas/utils/CanvasMaskManager.js +++ b/src/core/renderers/canvas/utils/CanvasMaskManager.js @@ -6,7 +6,8 @@ * @class * @namespace PIXI */ -function CanvasMaskManager() {} +function CanvasMaskManager() +{} CanvasMaskManager.prototype.constructor = CanvasMaskManager; module.exports = CanvasMaskManager; @@ -17,7 +18,8 @@ * @param maskData {object} the maskData that will be pushed * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.pushMask = function (maskData, renderer) { +CanvasMaskManager.prototype.pushMask = function (maskData, renderer) +{ renderer.context.save(); var cacheAlpha = maskData.alpha; @@ -45,6 +47,7 @@ * * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.popMask = function (renderer) { +CanvasMaskManager.prototype.popMask = function (renderer) +{ renderer.context.restore(); }; diff --git a/src/core/renderers/canvas/utils/CanvasTinter.js b/src/core/renderers/canvas/utils/CanvasTinter.js index 17e0529..d2fb1bc 100644 --- a/src/core/renderers/canvas/utils/CanvasTinter.js +++ b/src/core/renderers/canvas/utils/CanvasTinter.js @@ -14,7 +14,8 @@ * @param color {number} the color to use to tint the sprite with * @return {HTMLCanvasElement} The tinted canvas */ -CanvasTinter.getTintedTexture = function (sprite, color) { +CanvasTinter.getTintedTexture = function (sprite, color) +{ var texture = sprite.texture; color = CanvasTinter.roundColor(color); @@ -23,7 +24,8 @@ texture.tintCache = texture.tintCache || {}; - if (texture.tintCache[stringColor]) { + if (texture.tintCache[stringColor]) + { return texture.tintCache[stringColor]; } @@ -33,14 +35,16 @@ //CanvasTinter.tintWithPerPixel(texture, stringColor, canvas); CanvasTinter.tintMethod(texture, color, canvas); - if (CanvasTinter.convertTintToImage) { + if (CanvasTinter.convertTintToImage) + { // is this better? var tintImage = new Image(); tintImage.src = canvas.toDataURL(); texture.tintCache[stringColor] = tintImage; } - else { + else + { texture.tintCache[stringColor] = canvas; // if we are not converting the texture to an image then we need to lose the reference to the canvas CanvasTinter.canvas = null; @@ -56,7 +60,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithMultiply = function (texture, color, canvas) { +CanvasTinter.tintWithMultiply = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -104,7 +109,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithOverlay = function (texture, color, canvas) { +CanvasTinter.tintWithOverlay = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -139,7 +145,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithPerPixel = function (texture, color, canvas) { +CanvasTinter.tintWithPerPixel = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -167,7 +174,8 @@ var pixels = pixelData.data; - for (var i = 0; i < pixels.length; i += 4) { + for (var i = 0; i < pixels.length; i += 4) + { pixels[i+0] *= r; pixels[i+1] *= g; pixels[i+2] *= b; @@ -181,7 +189,8 @@ * * @param color {number} the color to round, should be a hex color */ -CanvasTinter.roundColor = function (color) { +CanvasTinter.roundColor = function (color) +{ var step = CanvasTinter.cacheStepsPerColorChannel; var rgbValues = utils.hex2rgb(color); diff --git a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js index 9f2f89a..35edbaf 100644 --- a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js +++ b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLBlendModeManager(renderer) { +function WebGLBlendModeManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -23,8 +24,10 @@ * * @param blendMode {number} the blendMode, should be a Pixi const, such as BlendModes.ADD */ -WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) { - if (this.currentBlendMode === blendMode) { +WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) +{ + if (this.currentBlendMode === blendMode) + { return false; } diff --git a/src/core/renderers/webgl/managers/WebGLFilterManager.js b/src/core/renderers/webgl/managers/WebGLFilterManager.js index 1179258..2dac048 100644 --- a/src/core/renderers/webgl/managers/WebGLFilterManager.js +++ b/src/core/renderers/webgl/managers/WebGLFilterManager.js @@ -7,7 +7,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLFilterManager(renderer) { +function WebGLFilterManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -32,7 +33,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.texturePool.length = 0; self.initShaderBuffers(); }); @@ -46,7 +48,8 @@ * @param renderer {WebGLRenderer} * @param buffer {ArrayBuffer} */ -WebGLFilterManager.prototype.begin = function (buffer) { +WebGLFilterManager.prototype.begin = function (buffer) +{ this.defaultShader = this.renderer.shaderManager.defaultShader; this.width = this.renderer.projection.x * 2; @@ -60,7 +63,8 @@ * * @param filterBlock {object} the filter that will be pushed to the current filter stack */ -WebGLFilterManager.prototype.pushFilter = function (filterBlock) { +WebGLFilterManager.prototype.pushFilter = function (filterBlock) +{ var gl = this.renderer.gl; var projection = this.renderer.projection; @@ -78,10 +82,12 @@ this.offsetY += filterBlock._filterArea.y; var texture = this.texturePool.pop(); - if (!texture) { + if (!texture) + { texture = new FilterTexture(this.renderer.gl, this.width, this.height); } - else { + else + { texture.resize(this.width, this.height); } @@ -98,29 +104,35 @@ var localX = filterArea.x, localY = filterArea.y; - if (filterArea.x < 0) { + if (filterArea.x < 0) + { filterArea.width += filterArea.x; filterArea.x = 0; } - if (filterArea.y < 0) { + if (filterArea.y < 0) + { filterArea.height += filterArea.y; filterArea.y = 0; } - if (localX + filterArea.width > this.width) { + if (localX + filterArea.width > this.width) + { filterArea.width = this.width - localX; } - if (localY + filterArea.height > this.height) { + if (localY + filterArea.height > this.height) + { filterArea.height = this.height - localY; } - if (filterArea.width < 0) { + if (filterArea.width < 0) + { filterArea.width = 0; } - if (filterArea.height < 0) { + if (filterArea.height < 0) + { filterArea.height = 0; } @@ -154,7 +166,8 @@ * Removes the last filter from the filter stack and doesn't return it. * */ -WebGLFilterManager.prototype.popFilter = function () { +WebGLFilterManager.prototype.popFilter = function () +{ var gl = this.renderer.gl; var filterBlock = this.filterStack.pop(); @@ -163,7 +176,8 @@ var projection = this.renderer.projection; var offset = this.renderer.offset; - if (filterBlock.filterPasses.length > 1) { + if (filterBlock.filterPasses.length > 1) + { gl.viewport(0, 0, filterArea.width, filterArea.height); gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); @@ -193,7 +207,8 @@ var inputTexture = texture; var outputTexture = this.texturePool.pop(); - if (!outputTexture) { + if (!outputTexture) + { outputTexture = new FilterTexture(this.renderer.gl, this.width, this.height); } outputTexture.resize(this.width, this.height); @@ -204,7 +219,8 @@ gl.disable(gl.BLEND); - for (var i = 0; i < filterBlock.filterPasses.length-1; i++) { + for (var i = 0; i < filterBlock.filterPasses.length-1; i++) + { var filterPass = filterBlock.filterPasses[i]; gl.bindFramebuffer(gl.FRAMEBUFFER, outputTexture.frameBuffer ); @@ -243,10 +259,12 @@ var buffer = this.buffer; // time to render the filters texture to the previous scene - if (this.filterStack.length === 0) { + if (this.filterStack.length === 0) + { gl.colorMask(true, true, true, true);//this.transparent); } - else { + else + { var currentFilter = this.filterStack[this.filterStack.length-1]; filterArea = currentFilter._filterArea; @@ -332,13 +350,15 @@ * @param width {number} the horizontal range of the filter * @param height {number} the vertical range of the filter */ -WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) { +WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) +{ // use program var gl = this.renderer.gl; var shader = filter.shaders[gl.id]; - if (!shader) { + if (!shader) + { shader = new Shader(gl); shader.fragmentSrc = filter.fragmentSrc; @@ -356,7 +376,8 @@ gl.uniform2f(shader.projectionVector, width/2, -height/2); gl.uniform2f(shader.offsetVector, 0,0); - if (filter.uniforms.dimensions) { + 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]; @@ -386,7 +407,8 @@ * Initialises the shader buffers. * */ -WebGLFilterManager.prototype.initShaderBuffers = function () { +WebGLFilterManager.prototype.initShaderBuffers = function () +{ var gl = this.renderer.gl; // create some buffers @@ -432,7 +454,8 @@ * Destroys the filter and removes it from the filter stack. * */ -WebGLFilterManager.prototype.destroy = function () { +WebGLFilterManager.prototype.destroy = function () +{ var gl = this.renderer.gl; this.filterStack = null; @@ -441,7 +464,8 @@ this.offsetY = 0; // destroy textures - for (var i = 0; i < this.texturePool.length; i++) { + for (var i = 0; i < this.texturePool.length; i++) + { this.texturePool[i].destroy(); } diff --git a/src/core/renderers/webgl/managers/WebGLManager.js b/src/core/renderers/webgl/managers/WebGLManager.js index 9d47b5c..c30cd51 100644 --- a/src/core/renderers/webgl/managers/WebGLManager.js +++ b/src/core/renderers/webgl/managers/WebGLManager.js @@ -3,7 +3,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLManager(renderer) { +function WebGLManager(renderer) +{ /** * The renderer this manager works for. * @@ -15,6 +16,7 @@ WebGLManager.prototype.constructor = WebGLManager; module.exports = WebGLManager; -WebGLManager.prototype.destroy = function () { +WebGLManager.prototype.destroy = function () +{ this.renderer = null; }; diff --git a/src/core/renderers/webgl/managers/WebGLMaskManager.js b/src/core/renderers/webgl/managers/WebGLMaskManager.js index 2f90b64..e568812 100644 --- a/src/core/renderers/webgl/managers/WebGLMaskManager.js +++ b/src/core/renderers/webgl/managers/WebGLMaskManager.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLMaskManager(renderer) { +function WebGLMaskManager(renderer) +{ WebGLManager.call(this, renderer); } @@ -19,12 +20,15 @@ * * @param maskData {any[]} */ -WebGLMaskManager.prototype.pushMask = function (maskData) { - if (maskData.dirty) { +WebGLMaskManager.prototype.pushMask = function (maskData) +{ + if (maskData.dirty) + { WebGLGraphics.updateGraphics(maskData, this.renderer.gl); } - if (!maskData._webGL[this.renderer.gl.id].data.length) { + if (!maskData._webGL[this.renderer.gl.id].data.length) + { return; } @@ -36,6 +40,7 @@ * * @param maskData {any[]} */ -WebGLMaskManager.prototype.popMask = function (maskData) { +WebGLMaskManager.prototype.popMask = function (maskData) +{ this.renderer.stencilManager.popStencil(maskData, maskData._webGL[this.renderer.gl.id].data[0], this.renderer); }; diff --git a/src/core/renderers/webgl/managers/WebGLShaderManager.js b/src/core/renderers/webgl/managers/WebGLShaderManager.js index fef071c..90c6477 100644 --- a/src/core/renderers/webgl/managers/WebGLShaderManager.js +++ b/src/core/renderers/webgl/managers/WebGLShaderManager.js @@ -10,7 +10,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLShaderManager(renderer) { +function WebGLShaderManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -28,7 +29,8 @@ */ this.tempAttribState = []; - for (var i = 0; i < this.maxAttibs; i++) { + for (var i = 0; i < this.maxAttibs; i++) + { this.attribState[i] = false; } @@ -66,7 +68,8 @@ // listen for context and update necessary shaders var self = this; - this.renderer.on('context', function (event) { + this.renderer.on('context', function (event) + { var gl = event.data; // this shader is used for rendering primitives @@ -97,29 +100,36 @@ * * @param attribs {Array} attribs */ -WebGLShaderManager.prototype.setAttribs = function (attribs) { +WebGLShaderManager.prototype.setAttribs = function (attribs) +{ // reset temp state var i; - for (i = 0; i < this.tempAttribState.length; i++) { + for (i = 0; i < this.tempAttribState.length; i++) + { this.tempAttribState[i] = false; } // set the new attribs - for (var a in attribs) { + for (var a in attribs) + { this.tempAttribState[attribs[a]] = true; } var gl = this.renderer.gl; - for (i = 0; i < this.attribState.length; i++) { - if (this.attribState[i] !== this.tempAttribState[i]) { + for (i = 0; i < this.attribState.length; i++) + { + if (this.attribState[i] !== this.tempAttribState[i]) + { this.attribState[i] = this.tempAttribState[i]; - if (this.attribState[i]) { + if (this.attribState[i]) + { gl.enableVertexAttribArray(i); } - else { + else + { gl.disableVertexAttribArray(i); } } @@ -131,8 +141,10 @@ * * @param shader {Any} */ -WebGLShaderManager.prototype.setShader = function (shader) { - if (this._currentId === shader.uuid) { +WebGLShaderManager.prototype.setShader = function (shader) +{ + if (this._currentId === shader.uuid) + { return false; } @@ -150,7 +162,8 @@ * Destroys this object. * */ -WebGLShaderManager.prototype.destroy = function () { +WebGLShaderManager.prototype.destroy = function () +{ this.attribState = null; this.tempAttribState = null; diff --git a/src/core/renderers/webgl/managers/WebGLStencilManager.js b/src/core/renderers/webgl/managers/WebGLStencilManager.js index 9ec6398..4cb0134 100644 --- a/src/core/renderers/webgl/managers/WebGLStencilManager.js +++ b/src/core/renderers/webgl/managers/WebGLStencilManager.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLStencilManager(renderer) { +function WebGLStencilManager(renderer) +{ WebGLManager.call(this, renderer); this.stencilStack = []; @@ -24,12 +25,14 @@ * @param graphics {Graphics} * @param webGLData {any[]} */ -WebGLStencilManager.prototype.pushStencil = function (graphics, webGLData) { +WebGLStencilManager.prototype.pushStencil = function (graphics, webGLData) +{ var gl = this.renderer.gl; this.bindGraphics(graphics, webGLData, this.renderer); - if (this.stencilStack.length === 0) { + if (this.stencilStack.length === 0) + { gl.enable(gl.STENCIL_TEST); gl.clear(gl.STENCIL_BUFFER_BIT); this.reverse = true; @@ -47,14 +50,17 @@ // draw the triangle strip! - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } @@ -62,31 +68,38 @@ // draw a quad to increment.. gl.drawElements(gl.TRIANGLE_FAN, 4, gl.UNSIGNED_SHORT, ( webGLData.indices.length - 4 ) * 2 ); - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); } this.reverse = !this.reverse; } - else { - if (!this.reverse) { + else + { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } - else { + 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) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); } } @@ -103,7 +116,8 @@ * @param graphics {Graphics} * @param webGLData {Array} */ -WebGLStencilManager.prototype.bindGraphics = function (graphics, webGLData) { +WebGLStencilManager.prototype.bindGraphics = function (graphics, webGLData) +{ //if (this._currentGraphics === graphics)return; this._currentGraphics = graphics; @@ -114,7 +128,8 @@ offset = this.renderer.offset, shader;// = this.renderer.shaderManager.primitiveShader; - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { shader = this.renderer.shaderManager.complexPrimitiveShader; this.renderer.shaderManager.setShader(shader); @@ -141,7 +156,8 @@ // set the index buffer! gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, webGLData.indexBuffer); } - else { + else + { //this.renderer.shaderManager.activatePrimitiveShader(); shader = this.renderer.shaderManager.primitiveShader; this.renderer.shaderManager.setShader( shader ); @@ -154,7 +170,7 @@ gl.uniform2f(shader.uniforms.offsetVector._location, -offset.x, -offset.y); gl.uniform3fv(shader.uniforms.tint._location, utils.hex2rgb(graphics.tint)); - + gl.uniform1f(shader.uniforms.alpha._location, graphics.worldAlpha); @@ -172,19 +188,22 @@ * @param graphics {Graphics} * @param webGLData {Array} */ -WebGLStencilManager.prototype.popStencil = function (graphics, webGLData) { +WebGLStencilManager.prototype.popStencil = function (graphics, webGLData) +{ var gl = this.renderer.gl; this.stencilStack.pop(); this.count--; - if (this.stencilStack.length === 0) { + if (this.stencilStack.length === 0) + { // the stack is empty! gl.disable(gl.STENCIL_TEST); } - else { + else + { var level = this.count; @@ -192,14 +211,17 @@ gl.colorMask(false, false, false, false); - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { this.reverse = !this.reverse; - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } @@ -213,31 +235,38 @@ // draw the triangle strip! gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); - if (!this.reverse) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); } } - else { + else + { // console.log("<<>>") - if (!this.reverse) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } - else { + 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) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); } } @@ -253,7 +282,8 @@ * Destroys the mask stack. * */ -WebGLStencilManager.prototype.destroy = function () { +WebGLStencilManager.prototype.destroy = function () +{ this.renderer = null; this.stencilStack = null; }; diff --git a/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js b/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js index 913ba5e..1ea7d19 100644 --- a/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js +++ b/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function ComplexPrimitiveShader(gl) { +function ComplexPrimitiveShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -24,7 +25,8 @@ 'uniform float flipY;', 'varying vec4 vColor;', - 'void main(void) {', + '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);', @@ -37,7 +39,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = vColor;', '}' ].join('\n'), diff --git a/src/core/display/DisplayObject.js b/src/core/display/DisplayObject.js index 66ebc3c..20e778c 100644 --- a/src/core/display/DisplayObject.js +++ b/src/core/display/DisplayObject.js @@ -7,7 +7,8 @@ * @class * @namespace PIXI */ -function DisplayObject() { +function DisplayObject() +{ /** * The coordinate of the object relative to the local coordinates of the parent. * @@ -152,10 +153,12 @@ * @memberof DisplayObject# */ x: { - get: function () { + get: function () + { return this.position.x; }, - set: function (value) { + set: function (value) + { this.position.x = value; } }, @@ -167,10 +170,12 @@ * @memberof DisplayObject# */ y: { - get: function () { + get: function () + { return this.position.y; }, - set: function (value) { + set: function (value) + { this.position.y = value; } }, @@ -183,11 +188,13 @@ * @readonly */ worldVisible: { - get: function () { + get: function () + { var item = this; do { - if (!item.visible) { + if (!item.visible) + { return false; } @@ -207,17 +214,21 @@ * @memberof DisplayObject# */ mask: { - get: function () { + get: function () + { return this._mask; }, - set: function (value) { - if (this._mask) { + set: function (value) + { + if (this._mask) + { this._mask.isMask = false; } this._mask = value; - if (this._mask) { + if (this._mask) + { this._mask.isMask = true; } } @@ -232,18 +243,23 @@ * @memberof DisplayObject# */ filters: { - get: function () { + get: function () + { return this._filters; }, - set: function (value) { - if (value) { + set: function (value) + { + if (value) + { // now put all the passes in one place.. var passes = []; - for (var i = 0; i < value.length; i++) { + for (var i = 0; i < value.length; i++) + { var filterPasses = value[i].passes; - for (var j = 0; j < filterPasses.length; j++) { + for (var j = 0; j < filterPasses.length; j++) + { passes.push(filterPasses[j]); } } @@ -264,8 +280,9 @@ * * @private */ -DisplayObject.prototype.updateTransform = function () { - +DisplayObject.prototype.updateTransform = function () +{ + // create some matrix refs for easy access var pt = this.parent.worldTransform; var wt = this.worldTransform; @@ -274,9 +291,11 @@ var a, b, c, d, tx, ty; // so if rotation is between 0 then we can simplify the multiplication process.. - if (this.rotation % math.PI_2) { + if (this.rotation % math.PI_2) + { // 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) { + if (this.rotation !== this.rotationCache) + { this.rotationCache = this.rotation; this._sr = Math.sin(this.rotation); this._cr = Math.cos(this.rotation); @@ -291,7 +310,8 @@ ty = this.position.y; // check for pivot.. not often used so geared towards that fact! - if (this.pivot.x || this.pivot.y) { + 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; } @@ -304,7 +324,8 @@ wt.tx = tx * pt.a + ty * pt.c + pt.tx; wt.ty = tx * pt.b + ty * pt.d + pt.ty; } - else { + else + { // lets do the fast version as we know there is no rotation.. a = this.scale.x; d = this.scale.y; @@ -333,7 +354,8 @@ * @param matrix {Matrix} * @return {Rectangle} the rectangular bounding area */ -DisplayObject.prototype.getBounds = function (/* matrix */) { +DisplayObject.prototype.getBounds = function (/* matrix */) +{ return math.Rectangle.EMPTY; }; @@ -342,7 +364,8 @@ * * @return {Rectangle} the rectangular bounding area */ -DisplayObject.prototype.getLocalBounds = function () { +DisplayObject.prototype.getLocalBounds = function () +{ return this.getBounds(math.Matrix.IDENTITY); }; @@ -352,7 +375,8 @@ * @param position {Point} The world origin to calculate from * @return {Point} A point object representing the position of this object */ -DisplayObject.prototype.toGlobal = function (position) { +DisplayObject.prototype.toGlobal = function (position) +{ // don't need to u[date the lot this.displayObjectUpdateTransform(); return this.worldTransform.apply(position); @@ -365,8 +389,10 @@ * @param [from] {DisplayObject} The DisplayObject to calculate the global position from * @return {Point} A point object representing the position of this object */ -DisplayObject.prototype.toLocal = function (position, from) { - if (from) { +DisplayObject.prototype.toLocal = function (position, from) +{ + if (from) + { position = from.toGlobal(position); } @@ -381,7 +407,8 @@ * @param renderer {WebGLRenderer} The renderer * @private */ -DisplayObject.prototype.renderWebGL = function (/* renderer */) { +DisplayObject.prototype.renderWebGL = function (/* renderer */) +{ // OVERWRITE; }; @@ -391,6 +418,7 @@ * @param renderer {CanvasRenderer} The renderer * @private */ -DisplayObject.prototype.renderCanvas = function (/* renderer */) { +DisplayObject.prototype.renderCanvas = function (/* renderer */) +{ // OVERWRITE; }; diff --git a/src/core/display/DisplayObjectContainer.js b/src/core/display/DisplayObjectContainer.js index 689f40b..4625ee8 100644 --- a/src/core/display/DisplayObjectContainer.js +++ b/src/core/display/DisplayObjectContainer.js @@ -12,7 +12,8 @@ * @extends DisplayObject * @namespace PIXI */ -function DisplayObjectContainer() { +function DisplayObjectContainer() +{ DisplayObject.call(this); /** @@ -47,17 +48,21 @@ * @memberof DisplayObjectContainer# */ width: { - get: function () { + get: function () + { return this.scale.x * this.getLocalBounds().width; }, - set: function (value) { + set: function (value) + { var width = this.getLocalBounds().width; - if(width !== 0) { + if(width !== 0) + { this.scale.x = value / width; } - else { + else + { this.scale.x = 1; } @@ -73,17 +78,21 @@ * @memberof DisplayObjectContainer# */ height: { - get: function () { + get: function () + { return this.scale.y * this.getLocalBounds().height; }, - set: function (value) { + set: function (value) + { var height = this.getLocalBounds().height; - if (height !== 0) { + if (height !== 0) + { this.scale.y = value / height ; } - else { + else + { this.scale.y = 1; } @@ -100,18 +109,23 @@ * @memberof DisplayObject# */ cacheAsBitmap: { - get: function () { + get: function () + { return this._cacheAsBitmap; }, - set: function (value) { - if (this._cacheAsBitmap === value) { + set: function (value) + { + if (this._cacheAsBitmap === value) + { return; } - if (value) { + if (value) + { this._generateCachedSprite(); } - else { + else + { this._destroyCachedSprite(); } @@ -126,7 +140,8 @@ * @param child {DisplayObject} The DisplayObject to add to the container * @return {DisplayObject} The child that was added. */ -DisplayObjectContainer.prototype.addChild = function (child) { +DisplayObjectContainer.prototype.addChild = function (child) +{ return this.addChildAt(child, this.children.length); }; @@ -137,14 +152,18 @@ * @param index {Number} The index to place the child in * @return {DisplayObject} The child that was added. */ -DisplayObjectContainer.prototype.addChildAt = function (child, index) { +DisplayObjectContainer.prototype.addChildAt = function (child, index) +{ // prevent adding self as child - if (child === this) { + if (child === this) + { return; } - if (index >= 0 && index <= this.children.length) { - if (child.parent) { + if (index >= 0 && index <= this.children.length) + { + if (child.parent) + { child.parent.removeChild(child); } @@ -154,7 +173,8 @@ return child; } - else { + else + { throw new Error(child + 'addChildAt: The index '+ index +' supplied is out of bounds ' + this.children.length); } }; @@ -165,15 +185,18 @@ * @param child {DisplayObject} * @param child2 {DisplayObject} */ -DisplayObjectContainer.prototype.swapChildren = function (child, child2) { - if (child === child2) { +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) { + if (index1 < 0 || index2 < 0) + { throw new Error('swapChildren: Both the supplied DisplayObjects must be a child of the caller.'); } @@ -187,10 +210,12 @@ * @param child {DisplayObject} The DisplayObject instance to identify * @return {Number} The index position of the child display object to identify */ -DisplayObjectContainer.prototype.getChildIndex = function (child) { +DisplayObjectContainer.prototype.getChildIndex = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { throw new Error('The supplied DisplayObject must be a child of the caller'); } @@ -203,8 +228,10 @@ * @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 */ -DisplayObjectContainer.prototype.setChildIndex = function (child, index) { - if (index < 0 || index >= this.children.length) { +DisplayObjectContainer.prototype.setChildIndex = function (child, index) +{ + if (index < 0 || index >= this.children.length) + { throw new Error('The supplied index is out of bounds'); } @@ -220,8 +247,10 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child at the given index, if any. */ -DisplayObjectContainer.prototype.getChildAt = function (index) { - if (index < 0 || index >= this.children.length) { +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'); } @@ -234,10 +263,12 @@ * @param child {DisplayObject} The DisplayObject to remove * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChild = function (child) { +DisplayObjectContainer.prototype.removeChild = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { return; } @@ -250,7 +281,8 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChildAt = function (index) { +DisplayObjectContainer.prototype.removeChildAt = function (index) +{ var child = this.getChildAt(index); child.parent = null; @@ -265,24 +297,29 @@ * @param beginIndex {Number} The beginning position. Default value is 0. * @param endIndex {Number} The ending position. Default value is size of the container. */ -DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) { +DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) +{ var begin = beginIndex || 0; var end = typeof endIndex === 'number' ? endIndex : this.children.length; var range = end - begin; - if (range > 0 && range <= end) { + if (range > 0 && range <= end) + { var removed = this.children.splice(begin, range); - for (var i = 0; i < removed.length; ++i) { + for (var i = 0; i < removed.length; ++i) + { removed[i].parent = null; } return removed; } - else if (range === 0 && this.children.length === 0) { + else if (range === 0 && this.children.length === 0) + { return []; } - else { + else + { throw new RangeError('removeChildren: numeric values are outside the acceptable range.'); } }; @@ -291,7 +328,8 @@ * Generates and updates the cached sprite for this object. * */ -DisplayObjectContainer.prototype.updateCachedSprite = function () { +DisplayObjectContainer.prototype.updateCachedSprite = function () +{ this._generateCachedSprite(); }; @@ -304,7 +342,8 @@ * @param renderer {CanvasRenderer|WebGLRenderer} The renderer used to generate the texture. * @return {Texture} a texture of the graphics object */ -DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) { +DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) +{ var bounds = this.getLocalBounds(); var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0, renderer, scaleMode, resolution); @@ -322,18 +361,22 @@ * * @private */ -DisplayObjectContainer.prototype.updateTransform = function () { - if (!this.visible) { +DisplayObjectContainer.prototype.updateTransform = function () +{ + if (!this.visible) + { return; } this.displayObjectUpdateTransform(); - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { return; } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } }; @@ -346,8 +389,10 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getBounds = function () { - if (this.children.length === 0) { +DisplayObjectContainer.prototype.getBounds = function () +{ + if (this.children.length === 0) + { return math.Rectangle.EMPTY; } @@ -365,10 +410,12 @@ var childVisible = false; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -386,7 +433,8 @@ maxY = maxY > childMaxY ? maxY : childMaxY; } - if (!childVisible) { + if (!childVisible) + { return math.Rectangle.EMPTY; } @@ -407,12 +455,14 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getLocalBounds = function () { +DisplayObjectContainer.prototype.getLocalBounds = function () +{ var matrixCache = this.worldTransform; this.worldTransform = math.Matrix.IDENTITY; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } @@ -428,13 +478,16 @@ * * @param renderer {WebGLRenderer} The renderer */ -DisplayObjectContainer.prototype.renderWebGL = function (renderer) { +DisplayObjectContainer.prototype.renderWebGL = function (renderer) +{ // if the object is not visible or the alpha is 0 then no need to render this element - if (!this.visible || this.alpha <= 0) { + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } @@ -442,14 +495,17 @@ var i, j; // do a quick check to see if this element has a mask or a filter. - if (this._mask || this._filters) { + if (this._mask || this._filters) + { // push filter first as we need to ensure the stencil buffer is correct for any masking - if (this._filters) { + if (this._filters) + { renderer.spriteBatch.flush(); renderer.filterManager.pushFilter(this._filterBlock); } - if (this._mask) { + if (this._mask) + { renderer.spriteBatch.stop(); renderer.maskManager.pushMask(this.mask, renderer); renderer.spriteBatch.start(); @@ -459,36 +515,42 @@ this._renderWebGL(renderer); // now loop through the children and make sure they get rendered - for (i = 0, j = this.children.length; i < j; i++) { + for (i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderWebGL(renderer); } // time to stop the sprite batch as either a mask element or a filter draw will happen next renderer.spriteBatch.stop(); - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(this._mask, renderer); } - if (this._filters) { + if (this._filters) + { renderer.filterManager.popFilter(); } renderer.spriteBatch.start(); } - else { + else + { this._renderWebGL(renderer); // simple render children! - for (i = 0, j = this.children.length; i < j; ++i) { + for (i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderWebGL(renderer); } } }; -DisplayObjectContainer.prototype._renderWebGL = function (renderer) { +DisplayObjectContainer.prototype._renderWebGL = function (renderer) +{ // this is where content itself gets renderd.. @@ -499,25 +561,31 @@ * * @param renderer {CanvasRenderer} The renderer */ -DisplayObjectContainer.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0) { +DisplayObjectContainer.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -528,13 +596,16 @@ * @param renderer {WebGLRenderer|CanvasRenderer} The renderer * @private */ -DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) { +DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) +{ this._cachedSprite.worldAlpha = this.worldAlpha; - if (renderer.gl) { + if (renderer.gl) + { this._cachedSprite.renderWebGL(renderer); } - else { + else + { this._cachedSprite.renderCanvas(renderer); } }; @@ -544,10 +615,12 @@ * * @private */ -DisplayObjectContainer.prototype._generateCachedSprite = function () { +DisplayObjectContainer.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { // TODO - RenderTexture now *requires* a renderer instance, so this is like broken // because `renderer` isn't actually in scope here :P var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0); @@ -555,7 +628,8 @@ this._cachedSprite = new Sprite(renderTexture); this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.texture.resize(bounds.width | 0, bounds.height | 0); } @@ -580,8 +654,10 @@ * * @private */ -DisplayObjectContainer.prototype._destroyCachedSprite = function () { - if (!this._cachedSprite) { +DisplayObjectContainer.prototype._destroyCachedSprite = function () +{ + if (!this._cachedSprite) + { return; } diff --git a/src/core/display/Sprite.js b/src/core/display/Sprite.js index 707da24..5862aef 100644 --- a/src/core/display/Sprite.js +++ b/src/core/display/Sprite.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param texture {Texture} The texture for this sprite */ -function Sprite(texture) { +function Sprite(texture) +{ DisplayObjectContainer.call(this); /** @@ -85,12 +86,14 @@ this.texture = texture || Texture.EMPTY; } -Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) { +Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) +{ DisplayObjectContainer.prototype.destroy.call(this); this.anchor = null; - if (destroyTexture) { + if (destroyTexture) + { this._texture.destroy(destroyBaseTexture); } @@ -111,10 +114,12 @@ * @memberof Sprite# */ width: { - get: function () { + get: function () + { return this.scale.x * this.texture.frame.width; }, - set: function (value) { + set: function (value) + { this.scale.x = value / this.texture.frame.width; this._width = value; } @@ -127,10 +132,12 @@ * @memberof Sprite# */ height: { - get: function () { + get: function () + { return this.scale.y * this.texture.frame.height; }, - set: function (value) { + set: function (value) + { this.scale.y = value / this.texture.frame.height; this._height = value; } @@ -143,23 +150,29 @@ * @memberof Sprite# */ texture: { - get: function () { + get: function () + { return this._texture; }, - set: function (value) { - if (this._texture === value) { + set: function (value) + { + if (this._texture === value) + { return; } this._texture = value; this.cachedTint = 0xFFFFFF; - if (value) { + if (value) + { // wait for the texture to load - if (value.baseTexture.hasLoaded) { + if (value.baseTexture.hasLoaded) + { this._onTextureUpdate(); } - else { + else + { value.once('update', this._onTextureUpdate.bind(this)); } } @@ -172,18 +185,22 @@ * * @private */ -Sprite.prototype._onTextureUpdate = function () { +Sprite.prototype._onTextureUpdate = function () +{ // so if _width is 0 then width was not set.. - if (this._width) { + if (this._width) + { this.scale.x = this._width / this.texture.frame.width; } - if (this._height) { + if (this._height) + { this.scale.y = this._height / this.texture.frame.height; } }; -Sprite.prototype._renderWebGL = function (renderer) { +Sprite.prototype._renderWebGL = function (renderer) +{ // this is where content gets renderd.. // watch this space for a little render state manager.. @@ -197,7 +214,8 @@ * @param matrix {Matrix} the transformation matrix of the sprite * @return {Rectangle} the framing rectangle */ -Sprite.prototype.getBounds = function (matrix) { +Sprite.prototype.getBounds = function (matrix) +{ var width = this.texture.frame.width; var height = this.texture.frame.height; @@ -224,11 +242,13 @@ if(b === 0 && c === 0) { // scale may be negative! - if (a < 0) { + if (a < 0) + { a *= -1; } - if (d < 0) { + if (d < 0) + { d *= -1; } @@ -293,28 +313,34 @@ * * @param renderer {CanvasRenderer} The renderer */ -Sprite.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) { +Sprite.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) + { return; } - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; renderer.context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } // Ignore null sources - if (this.texture.valid) { + if (this.texture.valid) + { var resolution = this.texture.baseTexture.resolution / renderer.resolution; renderer.context.globalAlpha = this.worldAlpha; // If smoothingEnabled is supported and we need to change the smoothing property for this texture - if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) { + if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) + { renderer.scaleMode = this.texture.baseTexture.scaleMode; renderer.context[renderer.smoothProperty] = (renderer.scaleMode === CONST.scaleModes.LINEAR); } @@ -324,7 +350,8 @@ var dy = (this.texture.trim ? this.texture.trim.y : 0) - (this.anchor.y * this.texture.trim.height); // Allow for pixel rounding - if (renderer.roundPixels) { + if (renderer.roundPixels) + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -337,7 +364,8 @@ dx = dx | 0; dy = dy | 0; } - else { + else + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -348,8 +376,10 @@ ); } - if (this.tint !== 0xFFFFFF) { - if (this.cachedTint !== this.tint) { + if (this.tint !== 0xFFFFFF) + { + if (this.cachedTint !== this.tint) + { this.cachedTint = this.tint; // TODO clean up caching - how to clean up the caches? @@ -368,7 +398,8 @@ this.texture.crop.height / resolution ); } - else { + else + { renderer.context.drawImage( this.texture.baseTexture.source, this.texture.crop.x, @@ -383,11 +414,13 @@ } } - for (var i = 0, j = this.children.length; i < j; i++) { + for (var i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -402,10 +435,12 @@ * @param frameId {String} The frame Id of the texture in the cache * @return {Sprite} A new Sprite using a texture from the texture cache matching the frameId */ -Sprite.fromFrame = function (frameId) { +Sprite.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache' + this); } @@ -420,6 +455,7 @@ * @param imageId {String} The image url of the texture * @return {Sprite} A new Sprite using a texture from the texture cache matching the image id */ -Sprite.fromImage = function (imageId, crossorigin, scaleMode) { +Sprite.fromImage = function (imageId, crossorigin, scaleMode) +{ return new Sprite(Texture.fromImage(imageId, crossorigin, scaleMode)); }; diff --git a/src/core/display/SpriteBatch.js b/src/core/display/SpriteBatch.js index 3187777..c196fef 100644 --- a/src/core/display/SpriteBatch.js +++ b/src/core/display/SpriteBatch.js @@ -12,7 +12,8 @@ * ```js * var container = new SpriteBatch(); * - * for(var i = 0; i < 100; ++i) { + * for(var i = 0; i < 100; ++i) + * { * var sprite = new PIXI.Sprite.fromImage("myImage.png"); * container.addChild(sprite); * } @@ -25,7 +26,8 @@ */ //TODO RENAME to PARTICLE CONTAINER? -function SpriteBatch() { +function SpriteBatch() +{ DisplayObjectContainer.call(this); } @@ -38,7 +40,8 @@ * * @private */ -SpriteBatch.prototype.updateTransform = function () { +SpriteBatch.prototype.updateTransform = function () +{ // TODO don't need to! this.displayObjectUpdateTransform(); // PIXI.DisplayObjectContainer.prototype.updateTransform.call( this ); @@ -50,8 +53,10 @@ * @param renderer {WebGLRenderer} The webgl renderer * @private */ -SpriteBatch.prototype.renderWebGL = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderWebGL = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -71,8 +76,10 @@ * @param renderer {CanvasRenderer} The canvas renderer * @private */ -SpriteBatch.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -84,10 +91,12 @@ this.displayObjectUpdateTransform(); - for (var i = 0; i < this.children.length; ++i) { + for (var i = 0; i < this.children.length; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -95,9 +104,11 @@ context.globalAlpha = this.worldAlpha * child.alpha; - if (child.rotation % (Math.PI * 2) === 0) { + if (child.rotation % (Math.PI * 2) === 0) + { // this is the fastest way to optimise! - if rotation is 0 then we can avoid any kind of setTransform call - if (isRotated) { + if (isRotated) + { context.setTransform( transform.a, transform.b, @@ -122,8 +133,10 @@ frame.height * child.scale.y ); } - else { - if (!isRotated) { + else + { + if (!isRotated) + { isRotated = true; } @@ -131,7 +144,8 @@ var childTransform = child.worldTransform; - if (renderer.roundPixels) { + if (renderer.roundPixels) + { context.setTransform( childTransform.a, childTransform.b, @@ -141,7 +155,8 @@ childTransform.ty | 0 ); } - else { + else + { context.setTransform( childTransform.a, childTransform.b, diff --git a/src/core/index.js b/src/core/index.js index 3954b6f..eb4a82b 100644 --- a/src/core/index.js +++ b/src/core/index.js @@ -58,11 +58,13 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRenderer: function (width, height, options, noWebGL) { + autoDetectRenderer: function (width, height, options, noWebGL) + { width = width || 800; height = height || 600; - if (!noWebGL && require('webgl-enabled')()) { + if (!noWebGL && require('webgl-enabled')()) + { return new core.WebGLRenderer(width, height, options); } @@ -87,7 +89,8 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRecommendedRenderer: function (width, height, options) { + autoDetectRecommendedRenderer: function (width, height, options) + { var isAndroid = /Android/i.test(navigator.userAgent); return core.autoDetectRenderer(width, height, options, isAndroid); diff --git a/src/core/math/Matrix.js b/src/core/math/Matrix.js index c2f87e2..2ff4848 100644 --- a/src/core/math/Matrix.js +++ b/src/core/math/Matrix.js @@ -10,7 +10,8 @@ * @class * @namespace PIXI */ -function Matrix() { +function Matrix() +{ /** * @member {number} * @default 1 @@ -63,7 +64,8 @@ * * @param array {number[]} The array that the matrix will be populated from. */ -Matrix.prototype.fromArray = function (array) { +Matrix.prototype.fromArray = function (array) +{ this.a = array[0]; this.b = array[1]; this.c = array[3]; @@ -78,14 +80,17 @@ * @param transpose {boolean} Whether we need to transpose the matrix or not * @return {number[]} the newly created array which contains the matrix */ -Matrix.prototype.toArray = function (transpose) { - if (!this.array) { +Matrix.prototype.toArray = function (transpose) +{ + if (!this.array) + { this.array = new Float32Array(9); } var array = this.array; - if (transpose) { + if (transpose) + { array[0] = this.a; array[1] = this.b; array[2] = 0; @@ -96,7 +101,8 @@ array[7] = this.ty; array[8] = 1; } - else { + else + { array[0] = this.a; array[1] = this.c; array[2] = this.tx; @@ -119,7 +125,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, transformed through this matrix */ -Matrix.prototype.apply = function (pos, newPos) { +Matrix.prototype.apply = function (pos, newPos) +{ newPos = newPos || new Point(); newPos.x = this.a * pos.x + this.c * pos.y + this.tx; @@ -136,7 +143,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, inverse-transformed through this matrix */ -Matrix.prototype.applyInverse = function (pos, newPos) { +Matrix.prototype.applyInverse = function (pos, newPos) +{ newPos = newPos || new Point(); var id = 1 / (this.a * this.d + this.c * -this.b); @@ -154,7 +162,8 @@ * @param {number} y * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.translate = function (x, y) { +Matrix.prototype.translate = function (x, y) +{ this.tx += x; this.ty += y; @@ -168,7 +177,8 @@ * @param {number} y The amount to scale vertically * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.scale = function (x, y) { +Matrix.prototype.scale = function (x, y) +{ this.a *= x; this.d *= y; this.c *= x; @@ -186,7 +196,8 @@ * @param {number} angle - The angle in radians. * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.rotate = function (angle) { +Matrix.prototype.rotate = function (angle) +{ var cos = Math.cos( angle ); var sin = Math.sin( angle ); @@ -210,7 +221,8 @@ * @param {Matrix} matrix * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.append = function (matrix) { +Matrix.prototype.append = function (matrix) +{ var a1 = this.a; var b1 = this.b; var c1 = this.c; @@ -232,7 +244,8 @@ * * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.identity = function () { +Matrix.prototype.identity = function () +{ this.a = 1; this.b = 0; this.c = 0; diff --git a/src/core/math/Point.js b/src/core/math/Point.js index 7565b2d..632f346 100644 --- a/src/core/math/Point.js +++ b/src/core/math/Point.js @@ -7,7 +7,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -function Point(x, y) { +function Point(x, y) +{ /** * @member {number} * @default 0 @@ -29,7 +30,8 @@ * * @return {Point} a copy of the point */ -Point.prototype.clone = function () { +Point.prototype.clone = function () +{ return new Point(this.x, this.y); }; @@ -40,7 +42,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -Point.prototype.set = function (x, y) { +Point.prototype.set = function (x, y) +{ this.x = x || 0; this.y = y || ( (y !== 0) ? this.x : 0 ) ; }; diff --git a/src/core/math/shapes/Circle.js b/src/core/math/shapes/Circle.js index 69cfdc9..4d76efc 100644 --- a/src/core/math/shapes/Circle.js +++ b/src/core/math/shapes/Circle.js @@ -10,7 +10,8 @@ * @param y {number} The Y coordinate of the center of this circle * @param radius {number} The radius of the circle */ -function Circle(x, y, radius) { +function Circle(x, y, radius) +{ /** * @member {number} * @default 0 @@ -46,7 +47,8 @@ * @method clone * @return {Circle} a copy of the Circle */ -Circle.prototype.clone = function () { +Circle.prototype.clone = function () +{ return new Circle(this.x, this.y, this.radius); }; @@ -58,8 +60,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Circle */ -Circle.prototype.contains = function (x, y) { - if (this.radius <= 0) { +Circle.prototype.contains = function (x, y) +{ + if (this.radius <= 0) + { return false; } @@ -79,6 +83,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Circle.prototype.getBounds = function () { +Circle.prototype.getBounds = function () +{ return new Rectangle(this.x - this.radius, this.y - this.radius, this.radius * 2, this.radius * 2); }; diff --git a/src/core/math/shapes/Ellipse.js b/src/core/math/shapes/Ellipse.js index 4f2d066..fefd01a 100644 --- a/src/core/math/shapes/Ellipse.js +++ b/src/core/math/shapes/Ellipse.js @@ -11,7 +11,8 @@ * @param width {number} The half width of this ellipse * @param height {number} The half height of this ellipse */ -function Ellipse(x, y, width, height) { +function Ellipse(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -53,7 +54,8 @@ * @method clone * @return {Ellipse} a copy of the ellipse */ -Ellipse.prototype.clone = function () { +Ellipse.prototype.clone = function () +{ return new Ellipse(this.x, this.y, this.width, this.height); }; @@ -65,8 +67,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coords are within this ellipse */ -Ellipse.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Ellipse.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } @@ -86,6 +90,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Ellipse.prototype.getBounds = function () { +Ellipse.prototype.getBounds = function () +{ return new Rectangle(this.x - this.width, this.y - this.height, this.width, this.height); }; diff --git a/src/core/math/shapes/Polygon.js b/src/core/math/shapes/Polygon.js index ae89148..fea6d37 100644 --- a/src/core/math/shapes/Polygon.js +++ b/src/core/math/shapes/Polygon.js @@ -10,16 +10,20 @@ * arguments passed can be flat x,y values e.g. `new Polygon(x,y, x,y, x,y, ...)` where `x` and `y` are * Numbers. */ -function Polygon(points) { +function Polygon(points) +{ //if points isn't an array, use arguments as the array - if (!(points instanceof Array)) { + if (!(points instanceof Array)) + { points = Array.prototype.slice.call(arguments); } //if this is a flat array of numbers, convert it to points - if (points[0] instanceof Point) { + if (points[0] instanceof Point) + { var p = []; - for (var i = 0, il = points.length; i < il; i++) { + for (var i = 0, il = points.length; i < il; i++) + { p.push(points[i].x, points[i].y); } @@ -51,7 +55,8 @@ * * @return {Polygon} a copy of the polygon */ -Polygon.prototype.clone = function () { +Polygon.prototype.clone = function () +{ return new Polygon(this.points.slice()); }; @@ -62,19 +67,22 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this polygon */ -Polygon.prototype.contains = function (x, y) { +Polygon.prototype.contains = function (x, y) +{ var inside = false; // use some raycasting to test hits // https://github.com/substack/point-in-polygon/blob/master/index.js var length = this.points.length / 2; - for (var i = 0, j = length - 1; i < length; j = i++) { + for (var i = 0, j = length - 1; i < length; j = i++) + { var xi = this.points[i * 2], yi = this.points[i * 2 + 1], xj = this.points[j * 2], yj = this.points[j * 2 + 1], intersect = ((yi > y) !== (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi); - if (intersect) { + if (intersect) + { inside = !inside; } } diff --git a/src/core/math/shapes/Rectangle.js b/src/core/math/shapes/Rectangle.js index 16ac62a..4008b68 100644 --- a/src/core/math/shapes/Rectangle.js +++ b/src/core/math/shapes/Rectangle.js @@ -10,7 +10,8 @@ * @param width {number} The overall width of this rectangle * @param height {number} The overall height of this rectangle */ -function Rectangle(x, y, width, height) { +function Rectangle(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -60,7 +61,8 @@ * * @return {Rectangle} a copy of the rectangle */ -Rectangle.prototype.clone = function () { +Rectangle.prototype.clone = function () +{ return new Rectangle(this.x, this.y, this.width, this.height); }; @@ -71,13 +73,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rectangle */ -Rectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Rectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/math/shapes/RoundedRectangle.js b/src/core/math/shapes/RoundedRectangle.js index 27d286e..7bf6411 100644 --- a/src/core/math/shapes/RoundedRectangle.js +++ b/src/core/math/shapes/RoundedRectangle.js @@ -11,7 +11,8 @@ * @param height {number} The overall height of this rounded rectangle * @param radius {number} Controls the radius of the rounded corners */ -function RoundedRectangle(x, y, width, height, radius) { +function RoundedRectangle(x, y, width, height, radius) +{ /** * @member {number} * @default 0 @@ -58,7 +59,8 @@ * * @return {RoundedRectangle} a copy of the rounded rectangle */ -RoundedRectangle.prototype.clone = function () { +RoundedRectangle.prototype.clone = function () +{ return new RoundedRectangle(this.x, this.y, this.width, this.height, this.radius); }; @@ -69,13 +71,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rounded Rectangle */ -RoundedRectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +RoundedRectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/primitives/Graphics.js b/src/core/primitives/Graphics.js index 261c534..e902d2a 100644 --- a/src/core/primitives/Graphics.js +++ b/src/core/primitives/Graphics.js @@ -16,7 +16,8 @@ * @extends DisplayObjectContainer * @namespace PIXI */ -function Graphics() { +function Graphics() +{ DisplayObjectContainer.call(this); this.renderable = true; @@ -154,16 +155,20 @@ * @private */ cacheAsBitmap: { - get: function () { + get: function () + { return this._cacheAsBitmap; }, - set: function (value) { + set: function (value) + { this._cacheAsBitmap = value; - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._generateCachedSprite(); } - else { + else + { this.destroyCachedSprite(); this.dirty = true; } @@ -176,7 +181,8 @@ * * @return {Graphics} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ var clone = new Graphics(); clone.renderable = this.renderable; @@ -192,7 +198,8 @@ clone.cachedSpriteDirty = this.cachedSpriteDirty; // copy graphics data - for (var i = 0; i < this.graphicsData.length; ++i) { + for (var i = 0; i < this.graphicsData.length; ++i) + { clone.graphicsData.push(this.graphicsData.clone()); } @@ -211,17 +218,21 @@ * @param alpha {number} alpha of the line to draw, will update the objects stored style * @return {Graphics} */ -Graphics.prototype.lineStyle = function (lineWidth, color, alpha) { +Graphics.prototype.lineStyle = function (lineWidth, color, alpha) +{ this.lineWidth = lineWidth || 0; this.lineColor = color || 0; this.lineAlpha = (arguments.length < 3) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length) + { // halfway through a line? start a new one! this.drawShape( new math.Polygon( this.currentPath.shape.points.slice(-2) )); } - else { + else + { // otherwise its empty so lets just set the line properties this.currentPath.lineWidth = this.lineWidth; this.currentPath.lineColor = this.lineColor; @@ -239,7 +250,8 @@ * @param y {number} the Y coordinate to move to * @return {Graphics} */ -Graphics.prototype.moveTo = function (x, y) { +Graphics.prototype.moveTo = function (x, y) +{ this.drawShape(new math.Polygon([x,y])); return this; @@ -253,7 +265,8 @@ * @param y {number} the Y coordinate to draw to * @return {Graphics} */ -Graphics.prototype.lineTo = function (x, y) { +Graphics.prototype.lineTo = function (x, y) +{ this.currentPath.shape.points.push(x, y); this.dirty = true; @@ -270,13 +283,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -285,7 +302,8 @@ n = 20, points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { this.moveTo(0, 0); } @@ -293,7 +311,8 @@ var fromY = points[points.length-1]; var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; xa = fromX + ( (cpX - fromX) * j ); @@ -319,13 +338,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -342,7 +365,8 @@ var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; dt = (1 - j); @@ -373,13 +397,17 @@ * @param radius {number} The radius of the arc * @return {Graphics} */ -Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points.push(x1, y1); } } - else { + else + { this.moveTo(x1, y1); } @@ -392,12 +420,15 @@ b2 = x2 - x1, mm = Math.abs(a1 * b2 - b1 * a2); - if (mm < 1.0e-8 || radius === 0) { - if (points[points.length-2] !== x1 || points[points.length-1] !== y1) { + if (mm < 1.0e-8 || radius === 0) + { + if (points[points.length-2] !== x1 || points[points.length-1] !== y1) + { points.push(x1, y1); } } - else { + else + { var dd = a1 * a1 + b1 * b1, cc = a2 * a2 + b2 * b2, tt = a1 * a2 + b1 * b2, @@ -433,42 +464,51 @@ * @param anticlockwise {boolean} Optional. Specifies whether the drawing should be counterclockwise or clockwise. False is default, and indicates clockwise, while true indicates counter-clockwise. * @return {Graphics} */ -Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) { +Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) +{ var startX = cx + Math.cos(startAngle) * radius; var startY = cy + Math.sin(startAngle) * radius; var points; // TODO - This if-else makes no sense. It uses currentPath in the else where it doesn't exist... - if (this.currentPath) { + if (this.currentPath) + { points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { points.push(startX, startY); } - else if (points[points.length-2] !== startX || points[points.length-1] !== startY) { + else if (points[points.length-2] !== startX || points[points.length-1] !== startY) + { points.push(startX, startY); } } - else { + else + { this.moveTo(startX, startY); points = this.currentPath.shape.points; } - if (startAngle === endAngle) { + if (startAngle === endAngle) + { return this; } - if (!anticlockwise && endAngle <= startAngle) { + if (!anticlockwise && endAngle <= startAngle) + { endAngle += Math.PI * 2; } - else if (anticlockwise && startAngle <= endAngle) { + else if (anticlockwise && startAngle <= endAngle) + { startAngle += Math.PI * 2; } var sweep = anticlockwise ? (startAngle - endAngle) *-1 : (endAngle - startAngle); var segs = (Math.abs(sweep)/ (Math.PI * 2)) * 40; - if (sweep === 0) { + if (sweep === 0) + { return this; } @@ -482,7 +522,8 @@ var remainder = ( segMinus % 1 ) / segMinus; - for (var i = 0; i <= segMinus; ++i) { + for (var i = 0; i <= segMinus; ++i) + { var real = i + remainder * i; var angle = ((theta) + startAngle + (theta2 * real)); @@ -506,13 +547,16 @@ * @param alpha {number} the alpha of the fill * @return {Graphics} */ -Graphics.prototype.beginFill = function (color, alpha) { +Graphics.prototype.beginFill = function (color, alpha) +{ this.filling = true; this.fillColor = color || 0; this.fillAlpha = (alpha === undefined) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length <= 2) + { this.currentPath.fill = this.filling; this.currentPath.fillColor = this.fillColor; this.currentPath.fillAlpha = this.fillAlpha; @@ -526,7 +570,8 @@ * * @return {Graphics} */ -Graphics.prototype.endFill = function () { +Graphics.prototype.endFill = function () +{ this.filling = false; this.fillColor = null; this.fillAlpha = 1; @@ -542,7 +587,8 @@ * @param height {number} The height of the rectangle * @return {Graphics} */ -Graphics.prototype.drawRect = function ( x, y, width, height ) { +Graphics.prototype.drawRect = function ( x, y, width, height ) +{ this.drawShape(new math.Rectangle(x,y, width, height)); return this; @@ -556,7 +602,8 @@ * @param height {number} The height of the rectangle * @param radius {number} Radius of the rectangle corners */ -Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) { +Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) +{ this.drawShape(new math.RoundedRectangle(x, y, width, height, radius)); return this; @@ -570,7 +617,8 @@ * @param radius {number} The radius of the circle * @return {Graphics} */ -Graphics.prototype.drawCircle = function (x, y, radius) { +Graphics.prototype.drawCircle = function (x, y, radius) +{ this.drawShape(new math.Circle(x,y, radius)); return this; @@ -585,7 +633,8 @@ * @param height {number} The half height of the ellipse * @return {Graphics} */ -Graphics.prototype.drawEllipse = function (x, y, width, height) { +Graphics.prototype.drawEllipse = function (x, y, width, height) +{ this.drawShape(new math.Ellipse(x, y, width, height)); return this; @@ -597,8 +646,10 @@ * @param path {Array} The path data used to construct the polygon. * @return {Graphics} */ -Graphics.prototype.drawPolygon = function (path) { - if (!(path instanceof Array)) { +Graphics.prototype.drawPolygon = function (path) +{ + if (!(path instanceof Array)) + { path = Array.prototype.slice.call(arguments); } @@ -612,7 +663,8 @@ * * @return {Graphics} */ -Graphics.prototype.clear = function () { +Graphics.prototype.clear = function () +{ this.lineWidth = 0; this.filling = false; @@ -631,7 +683,8 @@ * @param scaleMode {number} Should be one of the scaleMode consts * @return {Texture} a texture of the graphics object */ -Graphics.prototype.generateTexture = function (resolution, scaleMode) { +Graphics.prototype.generateTexture = function (resolution, scaleMode) +{ resolution = resolution || 1; var bounds = this.getBounds(); @@ -655,17 +708,21 @@ * * @param renderer {WebGLRenderer} */ -Graphics.prototype._renderWebGL = function (renderer) { +Graphics.prototype._renderWebGL = function (renderer) +{ // if the sprite is not visible or the alpha is 0 then no need to render this element - if (this.isMask === true) { + if (this.isMask === true) + { return; } // this code may still be needed so leaving for now.. - // + // /* - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture on the gpu too! @@ -681,17 +738,24 @@ return; } - */ - - // check if the webgl graphic needs to be updated - if (this.glDirty) { - this.dirty = true; - this.glDirty = false; - } + else */ - renderer.setObjectRendererer(renderer.graphicsRenderer); - renderer.graphicsRenderer.render(this); + renderer.spriteBatch.stop(); + renderer.blendModeManager.setBlendMode(this.blendMode); + // check blend mode + renderer.blendModeManager.setBlendMode( this.blendMode ); + + // check if the webgl graphic needs to be updated + if (this.glDirty) + { + this.dirty = true; + this.glDirty = false; + } + + WebGLGraphics.renderGraphics(this, renderer); + + renderer.spriteBatch.start(); }; /** @@ -700,14 +764,18 @@ * @param renderer {CanvasRenderer} * @private */ -Graphics.prototype.renderCanvas = function (renderer) { +Graphics.prototype.renderCanvas = function (renderer) +{ // 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.isMask === true) { + if (!this.visible || this.alpha <= 0 || this.isMask === true) + { return; } - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture @@ -723,16 +791,19 @@ return; } - else { + else + { var context = renderer.context; var transform = this.worldTransform; - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } @@ -748,11 +819,13 @@ CanvasGraphics.renderGraphics(this, context); - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } } @@ -763,13 +836,16 @@ * * @return {Rectangle} the rectangular bounding area */ -Graphics.prototype.getBounds = function (matrix) { +Graphics.prototype.getBounds = function (matrix) +{ // return an empty object if the item is a mask! - if (this.isMask) { + if (this.isMask) + { return math.Rectangle.EMPTY; } - if (this.dirty) { + if (this.dirty) + { this.updateLocalBounds(); this.glDirty = true; @@ -841,23 +917,27 @@ * Update the bounds of the object * */ -Graphics.prototype.updateLocalBounds = function () { +Graphics.prototype.updateLocalBounds = function () +{ var minX = Infinity; var maxX = -Infinity; var minY = Infinity; var maxY = -Infinity; - if (this.graphicsData.length) { + if (this.graphicsData.length) + { var shape, points, x, y, w, h; - for (var i = 0; i < this.graphicsData.length; i++) { + for (var i = 0; i < this.graphicsData.length; i++) + { var data = this.graphicsData[i]; var type = data.type; var lineWidth = data.lineWidth; shape = data.shape; - if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) { + if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) + { x = shape.x - lineWidth/2; y = shape.y - lineWidth/2; w = shape.width + lineWidth; @@ -869,7 +949,8 @@ minY = y < minY ? y : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.CIRC) { + else if (type === CONST.SHAPES.CIRC) + { x = shape.x; y = shape.y; w = shape.radius + lineWidth/2; @@ -881,7 +962,8 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.ELIP) { + else if (type === CONST.SHAPES.ELIP) + { x = shape.x; y = shape.y; w = shape.width + lineWidth/2; @@ -893,11 +975,13 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else { + else + { // POLY points = shape.points; - for (var j = 0; j < points.length; j += 2) { + for (var j = 0; j < points.length; j += 2) + { x = points[j]; y = points[j+1]; @@ -910,7 +994,8 @@ } } } - else { + else + { minX = 0; maxX = 0; minY = 0; @@ -931,10 +1016,12 @@ * * @private */ -Graphics.prototype._generateCachedSprite = function () { +Graphics.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { var canvasBuffer = new CanvasBuffer(bounds.width, bounds.height); var texture = Texture.fromCanvas(canvasBuffer.canvas); @@ -943,7 +1030,8 @@ this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.buffer.resize(bounds.width, bounds.height); } @@ -968,7 +1056,8 @@ * * @private */ -Graphics.prototype.updateCachedSpriteTexture = function () { +Graphics.prototype.updateCachedSpriteTexture = function () +{ var cachedSprite = this._cachedSprite; var texture = cachedSprite.texture; var canvas = cachedSprite.buffer.canvas; @@ -989,7 +1078,8 @@ * Destroys a previous cached sprite. * */ -Graphics.prototype.destroyCachedSprite = function () { +Graphics.prototype.destroyCachedSprite = function () +{ this._cachedSprite.texture.destroy(true); // let the gc collect the unused sprite @@ -1003,10 +1093,13 @@ * @param {Circle|Rectangle|Ellipse|Line|Polygon} shape The Shape object to draw. * @return {GraphicsData} The generated GraphicsData object. */ -Graphics.prototype.drawShape = function (shape) { - if (this.currentPath) { +Graphics.prototype.drawShape = function (shape) +{ + if (this.currentPath) + { // check current path! - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath.shape.points.length <= 2) + { this.graphicsData.pop(); } } @@ -1017,7 +1110,8 @@ this.graphicsData.push(data); - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { data.shape.closed = this.filling; this.currentPath = data; } diff --git a/src/core/primitives/GraphicsData.js b/src/core/primitives/GraphicsData.js index 99decbe..788f6f2 100644 --- a/src/core/primitives/GraphicsData.js +++ b/src/core/primitives/GraphicsData.js @@ -4,7 +4,8 @@ * @class * @namespace PIXI */ -function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) { +function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) +{ this.lineWidth = lineWidth; this.lineColor = lineColor; this.lineAlpha = lineAlpha; @@ -27,7 +28,8 @@ * * @return {GraphicsData} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ return new GraphicsData( this.lineWidth, this.lineColor, diff --git a/src/core/renderers/canvas/CanvasRenderer.js b/src/core/renderers/canvas/CanvasRenderer.js index 15a0978..7aebd44 100644 --- a/src/core/renderers/canvas/CanvasRenderer.js +++ b/src/core/renderers/canvas/CanvasRenderer.js @@ -17,17 +17,22 @@ * @param [options.resolution=1] {number} the resolution of the renderer retina would be 2 * @param [options.clearBeforeRender=true] {boolean} This sets if the CanvasRenderer will clear the canvas or not before the new render pass. */ -function CanvasRenderer(width, height, options) { +function CanvasRenderer(width, height, options) +{ utils.sayHello('Canvas'); - if (options) { - for (var i in CONST.defaultRenderOptions) { - if (typeof options[i] === 'undefined') { + if (options) + { + for (var i in CONST.defaultRenderOptions) + { + if (typeof options[i] === 'undefined') + { options[i] = CONST.defaultRenderOptions[i]; } } } - else { + else + { options = CONST.defaultRenderOptions; } @@ -156,19 +161,24 @@ this.smoothProperty = null; - if (this.context.imageSmoothingEnabled) { + if (this.context.imageSmoothingEnabled) + { this.smoothProperty = 'imageSmoothingEnabled'; } - else if (this.context.webkitImageSmoothingEnabled) { + else if (this.context.webkitImageSmoothingEnabled) + { this.smoothProperty = 'webkitImageSmoothingEnabled'; } - else if (this.context.mozImageSmoothingEnabled) { + else if (this.context.mozImageSmoothingEnabled) + { this.smoothProperty = 'mozImageSmoothingEnabled'; } - else if (this.context.oImageSmoothingEnabled) { + else if (this.context.oImageSmoothingEnabled) + { this.smoothProperty = 'oImageSmoothingEnabled'; } - else if (this.context.msImageSmoothingEnabled) { + else if (this.context.msImageSmoothingEnabled) + { this.smoothProperty = 'msImageSmoothingEnabled'; } @@ -193,10 +203,12 @@ * @memberof CanvasRenderer# */ backgroundColor: { - get: function () { + get: function () + { return this._backgroundColor; }, - set: function (val) { + set: function (val) + { this._backgroundColor = val; this._backgroundColorString = utils.hex2string(val); } @@ -208,7 +220,8 @@ * * @param object {DisplayObject} the object to be rendered */ -CanvasRenderer.prototype.render = function (object) { +CanvasRenderer.prototype.render = function (object) +{ object.updateTransform(); this.context.setTransform(1,0,0,1,0,0); @@ -218,16 +231,20 @@ this.currentBlendMode = CONST.blendModes.NORMAL; this.context.globalCompositeOperation = this.blendModes[CONST.blendModes.NORMAL]; - if (navigator.isCocoonJS && this.view.screencanvas) { + if (navigator.isCocoonJS && this.view.screencanvas) + { this.context.fillStyle = 'black'; this.context.clear(); } - if (this.clearBeforeRender) { - if (this.transparent) { + if (this.clearBeforeRender) + { + if (this.transparent) + { this.context.clearRect(0, 0, this.width, this.height); } - else { + else + { this.context.fillStyle = this._backgroundColorString; this.context.fillRect(0, 0, this.width , this.height); } @@ -241,8 +258,10 @@ * * @param [removeView=false] {boolean} Removes the Canvas element from the DOM. */ -CanvasRenderer.prototype.destroy = function (removeView) { - if (removeView && this.view.parent) { +CanvasRenderer.prototype.destroy = function (removeView) +{ + if (removeView && this.view.parent) + { this.view.parent.removeChild(this.view); } @@ -257,14 +276,16 @@ * @param width {number} the new width of the canvas view * @param height {number} the new height of the canvas view */ -CanvasRenderer.prototype.resize = function (width, height) { +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) { + if (this.autoResize) + { this.view.style.width = this.width / this.resolution + 'px'; this.view.style.height = this.height / this.resolution + 'px'; } @@ -276,7 +297,8 @@ * @param displayObject {DisplayObject} The displayObject to render * @private */ -CanvasRenderer.prototype.renderDisplayObject = function (displayObject) { +CanvasRenderer.prototype.renderDisplayObject = function (displayObject) +{ displayObject.renderCanvas(this); }; @@ -285,11 +307,14 @@ * * @private */ -CanvasRenderer.prototype._mapBlendModes = function () { - if (!this.blendModes) { +CanvasRenderer.prototype._mapBlendModes = function () +{ + if (!this.blendModes) + { this.blendModes = {}; - if (utils.canUseNewCanvasBlendModes()) { + if (utils.canUseNewCanvasBlendModes()) + { this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? this.blendModes[CONST.blendModes.MULTIPLY] = 'multiply'; @@ -308,7 +333,8 @@ this.blendModes[CONST.blendModes.COLOR] = 'color'; this.blendModes[CONST.blendModes.LUMINOSITY] = 'luminosity'; } - else { + else + { // this means that the browser does not support the cool new blend modes in canvas 'cough' ie 'cough' this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? diff --git a/src/core/renderers/canvas/utils/CanvasBuffer.js b/src/core/renderers/canvas/utils/CanvasBuffer.js index ebe5d47..b183a66 100644 --- a/src/core/renderers/canvas/utils/CanvasBuffer.js +++ b/src/core/renderers/canvas/utils/CanvasBuffer.js @@ -6,7 +6,8 @@ * @param width {number} the width for the newly created canvas * @param height {number} the height for the newly created canvas */ -function CanvasBuffer(width, height) { +function CanvasBuffer(width, height) +{ /** * The Canvas object that belongs to this CanvasBuffer. * @@ -36,10 +37,12 @@ * @memberof CanvasBuffer# */ width: { - get: function () { + get: function () + { return this.canvas.width; }, - set: function (val) { + set: function (val) + { this.canvas.width = val; } }, @@ -50,10 +53,12 @@ * @memberof CanvasBuffer# */ height: { - get: function () { + get: function () + { return this.canvas.height; }, - set: function (val) { + set: function (val) + { this.canvas.height = val; } } @@ -64,7 +69,8 @@ * * @private */ -CanvasBuffer.prototype.clear = function () { +CanvasBuffer.prototype.clear = function () +{ this.context.setTransform(1, 0, 0, 1, 0, 0); this.context.clearRect(0,0, this.canvas.width, this.canvas.height); }; @@ -75,7 +81,8 @@ * @param width {number} the new width of the canvas * @param height {number} the new height of the canvas */ -CanvasBuffer.prototype.resize = function (width, height) { +CanvasBuffer.prototype.resize = function (width, height) +{ this.canvas.width = width; this.canvas.height = height; }; diff --git a/src/core/renderers/canvas/utils/CanvasGraphics.js b/src/core/renderers/canvas/utils/CanvasGraphics.js index c7eaa2a..3f2a91f 100644 --- a/src/core/renderers/canvas/utils/CanvasGraphics.js +++ b/src/core/renderers/canvas/utils/CanvasGraphics.js @@ -13,15 +13,18 @@ * @param graphics {Graphics} the actual graphics object to render * @param context {CanvasRenderingContext2D} the 2d drawing method of the canvas */ -CanvasGraphics.renderGraphics = function (graphics, context) { +CanvasGraphics.renderGraphics = function (graphics, context) +{ var worldAlpha = graphics.worldAlpha; - if (graphics.dirty) { + if (graphics.dirty) + { this.updateGraphicsTint(graphics); graphics.dirty = false; } - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; @@ -30,69 +33,82 @@ context.lineWidth = data.lineWidth; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { context.beginPath(); var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } - if (shape.closed) { + if (shape.closed) + { context.lineTo(points[0], points[1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fillRect(shape.x, shape.y, shape.width, shape.height); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.strokeRect(shape.x, shape.y, shape.width, shape.height); } } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.beginPath(); context.arc(shape.x, shape.y, shape.radius,0,2*Math.PI); context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas var w = shape.width * 2; @@ -119,18 +135,21 @@ context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; var width = shape.width; @@ -152,13 +171,15 @@ context.quadraticCurveTo(rx, ry, rx, ry + radius); context.closePath(); - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); @@ -174,45 +195,54 @@ * @param graphics {Graphics} the graphics which will be used as a mask * @param context {CanvasRenderingContext2D} the context 2d method of the canvas */ -CanvasGraphics.renderGraphicsMask = function (graphics, context) { +CanvasGraphics.renderGraphicsMask = function (graphics, context) +{ var len = graphics.graphicsData.length; - if (len === 0) { + if (len === 0) + { return; } context.beginPath(); - for (var i = 0; i < len; i++) { + for (var i = 0; i < len; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { context.rect(shape.x, shape.y, shape.width, shape.height); context.closePath(); } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.arc(shape.x, shape.y, shape.radius, 0, 2 * Math.PI); context.closePath(); } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas @@ -237,7 +267,8 @@ context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); context.closePath(); } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; @@ -262,8 +293,10 @@ } }; -CanvasGraphics.updateGraphicsTint = function (graphics) { - if (graphics.tint === 0xFFFFFF) { +CanvasGraphics.updateGraphicsTint = function (graphics) +{ + if (graphics.tint === 0xFFFFFF) + { return; } @@ -271,7 +304,8 @@ var tintG = (graphics.tint >> 8 & 0xFF) / 255; var tintB = (graphics.tint & 0xFF)/ 255; - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var fillColor = data.fillColor | 0; diff --git a/src/core/renderers/canvas/utils/CanvasMaskManager.js b/src/core/renderers/canvas/utils/CanvasMaskManager.js index e04a733..9827d36 100644 --- a/src/core/renderers/canvas/utils/CanvasMaskManager.js +++ b/src/core/renderers/canvas/utils/CanvasMaskManager.js @@ -6,7 +6,8 @@ * @class * @namespace PIXI */ -function CanvasMaskManager() {} +function CanvasMaskManager() +{} CanvasMaskManager.prototype.constructor = CanvasMaskManager; module.exports = CanvasMaskManager; @@ -17,7 +18,8 @@ * @param maskData {object} the maskData that will be pushed * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.pushMask = function (maskData, renderer) { +CanvasMaskManager.prototype.pushMask = function (maskData, renderer) +{ renderer.context.save(); var cacheAlpha = maskData.alpha; @@ -45,6 +47,7 @@ * * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.popMask = function (renderer) { +CanvasMaskManager.prototype.popMask = function (renderer) +{ renderer.context.restore(); }; diff --git a/src/core/renderers/canvas/utils/CanvasTinter.js b/src/core/renderers/canvas/utils/CanvasTinter.js index 17e0529..d2fb1bc 100644 --- a/src/core/renderers/canvas/utils/CanvasTinter.js +++ b/src/core/renderers/canvas/utils/CanvasTinter.js @@ -14,7 +14,8 @@ * @param color {number} the color to use to tint the sprite with * @return {HTMLCanvasElement} The tinted canvas */ -CanvasTinter.getTintedTexture = function (sprite, color) { +CanvasTinter.getTintedTexture = function (sprite, color) +{ var texture = sprite.texture; color = CanvasTinter.roundColor(color); @@ -23,7 +24,8 @@ texture.tintCache = texture.tintCache || {}; - if (texture.tintCache[stringColor]) { + if (texture.tintCache[stringColor]) + { return texture.tintCache[stringColor]; } @@ -33,14 +35,16 @@ //CanvasTinter.tintWithPerPixel(texture, stringColor, canvas); CanvasTinter.tintMethod(texture, color, canvas); - if (CanvasTinter.convertTintToImage) { + if (CanvasTinter.convertTintToImage) + { // is this better? var tintImage = new Image(); tintImage.src = canvas.toDataURL(); texture.tintCache[stringColor] = tintImage; } - else { + else + { texture.tintCache[stringColor] = canvas; // if we are not converting the texture to an image then we need to lose the reference to the canvas CanvasTinter.canvas = null; @@ -56,7 +60,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithMultiply = function (texture, color, canvas) { +CanvasTinter.tintWithMultiply = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -104,7 +109,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithOverlay = function (texture, color, canvas) { +CanvasTinter.tintWithOverlay = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -139,7 +145,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithPerPixel = function (texture, color, canvas) { +CanvasTinter.tintWithPerPixel = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -167,7 +174,8 @@ var pixels = pixelData.data; - for (var i = 0; i < pixels.length; i += 4) { + for (var i = 0; i < pixels.length; i += 4) + { pixels[i+0] *= r; pixels[i+1] *= g; pixels[i+2] *= b; @@ -181,7 +189,8 @@ * * @param color {number} the color to round, should be a hex color */ -CanvasTinter.roundColor = function (color) { +CanvasTinter.roundColor = function (color) +{ var step = CanvasTinter.cacheStepsPerColorChannel; var rgbValues = utils.hex2rgb(color); diff --git a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js index 9f2f89a..35edbaf 100644 --- a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js +++ b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLBlendModeManager(renderer) { +function WebGLBlendModeManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -23,8 +24,10 @@ * * @param blendMode {number} the blendMode, should be a Pixi const, such as BlendModes.ADD */ -WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) { - if (this.currentBlendMode === blendMode) { +WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) +{ + if (this.currentBlendMode === blendMode) + { return false; } diff --git a/src/core/renderers/webgl/managers/WebGLFilterManager.js b/src/core/renderers/webgl/managers/WebGLFilterManager.js index 1179258..2dac048 100644 --- a/src/core/renderers/webgl/managers/WebGLFilterManager.js +++ b/src/core/renderers/webgl/managers/WebGLFilterManager.js @@ -7,7 +7,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLFilterManager(renderer) { +function WebGLFilterManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -32,7 +33,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.texturePool.length = 0; self.initShaderBuffers(); }); @@ -46,7 +48,8 @@ * @param renderer {WebGLRenderer} * @param buffer {ArrayBuffer} */ -WebGLFilterManager.prototype.begin = function (buffer) { +WebGLFilterManager.prototype.begin = function (buffer) +{ this.defaultShader = this.renderer.shaderManager.defaultShader; this.width = this.renderer.projection.x * 2; @@ -60,7 +63,8 @@ * * @param filterBlock {object} the filter that will be pushed to the current filter stack */ -WebGLFilterManager.prototype.pushFilter = function (filterBlock) { +WebGLFilterManager.prototype.pushFilter = function (filterBlock) +{ var gl = this.renderer.gl; var projection = this.renderer.projection; @@ -78,10 +82,12 @@ this.offsetY += filterBlock._filterArea.y; var texture = this.texturePool.pop(); - if (!texture) { + if (!texture) + { texture = new FilterTexture(this.renderer.gl, this.width, this.height); } - else { + else + { texture.resize(this.width, this.height); } @@ -98,29 +104,35 @@ var localX = filterArea.x, localY = filterArea.y; - if (filterArea.x < 0) { + if (filterArea.x < 0) + { filterArea.width += filterArea.x; filterArea.x = 0; } - if (filterArea.y < 0) { + if (filterArea.y < 0) + { filterArea.height += filterArea.y; filterArea.y = 0; } - if (localX + filterArea.width > this.width) { + if (localX + filterArea.width > this.width) + { filterArea.width = this.width - localX; } - if (localY + filterArea.height > this.height) { + if (localY + filterArea.height > this.height) + { filterArea.height = this.height - localY; } - if (filterArea.width < 0) { + if (filterArea.width < 0) + { filterArea.width = 0; } - if (filterArea.height < 0) { + if (filterArea.height < 0) + { filterArea.height = 0; } @@ -154,7 +166,8 @@ * Removes the last filter from the filter stack and doesn't return it. * */ -WebGLFilterManager.prototype.popFilter = function () { +WebGLFilterManager.prototype.popFilter = function () +{ var gl = this.renderer.gl; var filterBlock = this.filterStack.pop(); @@ -163,7 +176,8 @@ var projection = this.renderer.projection; var offset = this.renderer.offset; - if (filterBlock.filterPasses.length > 1) { + if (filterBlock.filterPasses.length > 1) + { gl.viewport(0, 0, filterArea.width, filterArea.height); gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); @@ -193,7 +207,8 @@ var inputTexture = texture; var outputTexture = this.texturePool.pop(); - if (!outputTexture) { + if (!outputTexture) + { outputTexture = new FilterTexture(this.renderer.gl, this.width, this.height); } outputTexture.resize(this.width, this.height); @@ -204,7 +219,8 @@ gl.disable(gl.BLEND); - for (var i = 0; i < filterBlock.filterPasses.length-1; i++) { + for (var i = 0; i < filterBlock.filterPasses.length-1; i++) + { var filterPass = filterBlock.filterPasses[i]; gl.bindFramebuffer(gl.FRAMEBUFFER, outputTexture.frameBuffer ); @@ -243,10 +259,12 @@ var buffer = this.buffer; // time to render the filters texture to the previous scene - if (this.filterStack.length === 0) { + if (this.filterStack.length === 0) + { gl.colorMask(true, true, true, true);//this.transparent); } - else { + else + { var currentFilter = this.filterStack[this.filterStack.length-1]; filterArea = currentFilter._filterArea; @@ -332,13 +350,15 @@ * @param width {number} the horizontal range of the filter * @param height {number} the vertical range of the filter */ -WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) { +WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) +{ // use program var gl = this.renderer.gl; var shader = filter.shaders[gl.id]; - if (!shader) { + if (!shader) + { shader = new Shader(gl); shader.fragmentSrc = filter.fragmentSrc; @@ -356,7 +376,8 @@ gl.uniform2f(shader.projectionVector, width/2, -height/2); gl.uniform2f(shader.offsetVector, 0,0); - if (filter.uniforms.dimensions) { + 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]; @@ -386,7 +407,8 @@ * Initialises the shader buffers. * */ -WebGLFilterManager.prototype.initShaderBuffers = function () { +WebGLFilterManager.prototype.initShaderBuffers = function () +{ var gl = this.renderer.gl; // create some buffers @@ -432,7 +454,8 @@ * Destroys the filter and removes it from the filter stack. * */ -WebGLFilterManager.prototype.destroy = function () { +WebGLFilterManager.prototype.destroy = function () +{ var gl = this.renderer.gl; this.filterStack = null; @@ -441,7 +464,8 @@ this.offsetY = 0; // destroy textures - for (var i = 0; i < this.texturePool.length; i++) { + for (var i = 0; i < this.texturePool.length; i++) + { this.texturePool[i].destroy(); } diff --git a/src/core/renderers/webgl/managers/WebGLManager.js b/src/core/renderers/webgl/managers/WebGLManager.js index 9d47b5c..c30cd51 100644 --- a/src/core/renderers/webgl/managers/WebGLManager.js +++ b/src/core/renderers/webgl/managers/WebGLManager.js @@ -3,7 +3,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLManager(renderer) { +function WebGLManager(renderer) +{ /** * The renderer this manager works for. * @@ -15,6 +16,7 @@ WebGLManager.prototype.constructor = WebGLManager; module.exports = WebGLManager; -WebGLManager.prototype.destroy = function () { +WebGLManager.prototype.destroy = function () +{ this.renderer = null; }; diff --git a/src/core/renderers/webgl/managers/WebGLMaskManager.js b/src/core/renderers/webgl/managers/WebGLMaskManager.js index 2f90b64..e568812 100644 --- a/src/core/renderers/webgl/managers/WebGLMaskManager.js +++ b/src/core/renderers/webgl/managers/WebGLMaskManager.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLMaskManager(renderer) { +function WebGLMaskManager(renderer) +{ WebGLManager.call(this, renderer); } @@ -19,12 +20,15 @@ * * @param maskData {any[]} */ -WebGLMaskManager.prototype.pushMask = function (maskData) { - if (maskData.dirty) { +WebGLMaskManager.prototype.pushMask = function (maskData) +{ + if (maskData.dirty) + { WebGLGraphics.updateGraphics(maskData, this.renderer.gl); } - if (!maskData._webGL[this.renderer.gl.id].data.length) { + if (!maskData._webGL[this.renderer.gl.id].data.length) + { return; } @@ -36,6 +40,7 @@ * * @param maskData {any[]} */ -WebGLMaskManager.prototype.popMask = function (maskData) { +WebGLMaskManager.prototype.popMask = function (maskData) +{ this.renderer.stencilManager.popStencil(maskData, maskData._webGL[this.renderer.gl.id].data[0], this.renderer); }; diff --git a/src/core/renderers/webgl/managers/WebGLShaderManager.js b/src/core/renderers/webgl/managers/WebGLShaderManager.js index fef071c..90c6477 100644 --- a/src/core/renderers/webgl/managers/WebGLShaderManager.js +++ b/src/core/renderers/webgl/managers/WebGLShaderManager.js @@ -10,7 +10,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLShaderManager(renderer) { +function WebGLShaderManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -28,7 +29,8 @@ */ this.tempAttribState = []; - for (var i = 0; i < this.maxAttibs; i++) { + for (var i = 0; i < this.maxAttibs; i++) + { this.attribState[i] = false; } @@ -66,7 +68,8 @@ // listen for context and update necessary shaders var self = this; - this.renderer.on('context', function (event) { + this.renderer.on('context', function (event) + { var gl = event.data; // this shader is used for rendering primitives @@ -97,29 +100,36 @@ * * @param attribs {Array} attribs */ -WebGLShaderManager.prototype.setAttribs = function (attribs) { +WebGLShaderManager.prototype.setAttribs = function (attribs) +{ // reset temp state var i; - for (i = 0; i < this.tempAttribState.length; i++) { + for (i = 0; i < this.tempAttribState.length; i++) + { this.tempAttribState[i] = false; } // set the new attribs - for (var a in attribs) { + for (var a in attribs) + { this.tempAttribState[attribs[a]] = true; } var gl = this.renderer.gl; - for (i = 0; i < this.attribState.length; i++) { - if (this.attribState[i] !== this.tempAttribState[i]) { + for (i = 0; i < this.attribState.length; i++) + { + if (this.attribState[i] !== this.tempAttribState[i]) + { this.attribState[i] = this.tempAttribState[i]; - if (this.attribState[i]) { + if (this.attribState[i]) + { gl.enableVertexAttribArray(i); } - else { + else + { gl.disableVertexAttribArray(i); } } @@ -131,8 +141,10 @@ * * @param shader {Any} */ -WebGLShaderManager.prototype.setShader = function (shader) { - if (this._currentId === shader.uuid) { +WebGLShaderManager.prototype.setShader = function (shader) +{ + if (this._currentId === shader.uuid) + { return false; } @@ -150,7 +162,8 @@ * Destroys this object. * */ -WebGLShaderManager.prototype.destroy = function () { +WebGLShaderManager.prototype.destroy = function () +{ this.attribState = null; this.tempAttribState = null; diff --git a/src/core/renderers/webgl/managers/WebGLStencilManager.js b/src/core/renderers/webgl/managers/WebGLStencilManager.js index 9ec6398..4cb0134 100644 --- a/src/core/renderers/webgl/managers/WebGLStencilManager.js +++ b/src/core/renderers/webgl/managers/WebGLStencilManager.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLStencilManager(renderer) { +function WebGLStencilManager(renderer) +{ WebGLManager.call(this, renderer); this.stencilStack = []; @@ -24,12 +25,14 @@ * @param graphics {Graphics} * @param webGLData {any[]} */ -WebGLStencilManager.prototype.pushStencil = function (graphics, webGLData) { +WebGLStencilManager.prototype.pushStencil = function (graphics, webGLData) +{ var gl = this.renderer.gl; this.bindGraphics(graphics, webGLData, this.renderer); - if (this.stencilStack.length === 0) { + if (this.stencilStack.length === 0) + { gl.enable(gl.STENCIL_TEST); gl.clear(gl.STENCIL_BUFFER_BIT); this.reverse = true; @@ -47,14 +50,17 @@ // draw the triangle strip! - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } @@ -62,31 +68,38 @@ // draw a quad to increment.. gl.drawElements(gl.TRIANGLE_FAN, 4, gl.UNSIGNED_SHORT, ( webGLData.indices.length - 4 ) * 2 ); - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); } this.reverse = !this.reverse; } - else { - if (!this.reverse) { + else + { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } - else { + 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) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); } } @@ -103,7 +116,8 @@ * @param graphics {Graphics} * @param webGLData {Array} */ -WebGLStencilManager.prototype.bindGraphics = function (graphics, webGLData) { +WebGLStencilManager.prototype.bindGraphics = function (graphics, webGLData) +{ //if (this._currentGraphics === graphics)return; this._currentGraphics = graphics; @@ -114,7 +128,8 @@ offset = this.renderer.offset, shader;// = this.renderer.shaderManager.primitiveShader; - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { shader = this.renderer.shaderManager.complexPrimitiveShader; this.renderer.shaderManager.setShader(shader); @@ -141,7 +156,8 @@ // set the index buffer! gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, webGLData.indexBuffer); } - else { + else + { //this.renderer.shaderManager.activatePrimitiveShader(); shader = this.renderer.shaderManager.primitiveShader; this.renderer.shaderManager.setShader( shader ); @@ -154,7 +170,7 @@ gl.uniform2f(shader.uniforms.offsetVector._location, -offset.x, -offset.y); gl.uniform3fv(shader.uniforms.tint._location, utils.hex2rgb(graphics.tint)); - + gl.uniform1f(shader.uniforms.alpha._location, graphics.worldAlpha); @@ -172,19 +188,22 @@ * @param graphics {Graphics} * @param webGLData {Array} */ -WebGLStencilManager.prototype.popStencil = function (graphics, webGLData) { +WebGLStencilManager.prototype.popStencil = function (graphics, webGLData) +{ var gl = this.renderer.gl; this.stencilStack.pop(); this.count--; - if (this.stencilStack.length === 0) { + if (this.stencilStack.length === 0) + { // the stack is empty! gl.disable(gl.STENCIL_TEST); } - else { + else + { var level = this.count; @@ -192,14 +211,17 @@ gl.colorMask(false, false, false, false); - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { this.reverse = !this.reverse; - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } @@ -213,31 +235,38 @@ // draw the triangle strip! gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); - if (!this.reverse) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); } } - else { + else + { // console.log("<<>>") - if (!this.reverse) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } - else { + 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) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); } } @@ -253,7 +282,8 @@ * Destroys the mask stack. * */ -WebGLStencilManager.prototype.destroy = function () { +WebGLStencilManager.prototype.destroy = function () +{ this.renderer = null; this.stencilStack = null; }; diff --git a/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js b/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js index 913ba5e..1ea7d19 100644 --- a/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js +++ b/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function ComplexPrimitiveShader(gl) { +function ComplexPrimitiveShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -24,7 +25,8 @@ 'uniform float flipY;', 'varying vec4 vColor;', - 'void main(void) {', + '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);', @@ -37,7 +39,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = vColor;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/FastShader.js b/src/core/renderers/webgl/shaders/FastShader.js index bd2e29a..2e5e060 100644 --- a/src/core/renderers/webgl/shaders/FastShader.js +++ b/src/core/renderers/webgl/shaders/FastShader.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function FastShader(gl) { +function FastShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -28,7 +29,8 @@ 'const vec2 center = vec2(-1.0, 1.0);', - 'void main(void) {', + 'void main(void) + {', ' vec2 v;', ' vec2 sv = aVertexPosition * aScale;', ' v.x = (sv.x) * cos(aRotation) - (sv.y) * sin(aRotation);', @@ -49,7 +51,8 @@ 'uniform sampler2D uSampler;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;', '}' ].join('\n'), diff --git a/src/core/display/DisplayObject.js b/src/core/display/DisplayObject.js index 66ebc3c..20e778c 100644 --- a/src/core/display/DisplayObject.js +++ b/src/core/display/DisplayObject.js @@ -7,7 +7,8 @@ * @class * @namespace PIXI */ -function DisplayObject() { +function DisplayObject() +{ /** * The coordinate of the object relative to the local coordinates of the parent. * @@ -152,10 +153,12 @@ * @memberof DisplayObject# */ x: { - get: function () { + get: function () + { return this.position.x; }, - set: function (value) { + set: function (value) + { this.position.x = value; } }, @@ -167,10 +170,12 @@ * @memberof DisplayObject# */ y: { - get: function () { + get: function () + { return this.position.y; }, - set: function (value) { + set: function (value) + { this.position.y = value; } }, @@ -183,11 +188,13 @@ * @readonly */ worldVisible: { - get: function () { + get: function () + { var item = this; do { - if (!item.visible) { + if (!item.visible) + { return false; } @@ -207,17 +214,21 @@ * @memberof DisplayObject# */ mask: { - get: function () { + get: function () + { return this._mask; }, - set: function (value) { - if (this._mask) { + set: function (value) + { + if (this._mask) + { this._mask.isMask = false; } this._mask = value; - if (this._mask) { + if (this._mask) + { this._mask.isMask = true; } } @@ -232,18 +243,23 @@ * @memberof DisplayObject# */ filters: { - get: function () { + get: function () + { return this._filters; }, - set: function (value) { - if (value) { + set: function (value) + { + if (value) + { // now put all the passes in one place.. var passes = []; - for (var i = 0; i < value.length; i++) { + for (var i = 0; i < value.length; i++) + { var filterPasses = value[i].passes; - for (var j = 0; j < filterPasses.length; j++) { + for (var j = 0; j < filterPasses.length; j++) + { passes.push(filterPasses[j]); } } @@ -264,8 +280,9 @@ * * @private */ -DisplayObject.prototype.updateTransform = function () { - +DisplayObject.prototype.updateTransform = function () +{ + // create some matrix refs for easy access var pt = this.parent.worldTransform; var wt = this.worldTransform; @@ -274,9 +291,11 @@ var a, b, c, d, tx, ty; // so if rotation is between 0 then we can simplify the multiplication process.. - if (this.rotation % math.PI_2) { + if (this.rotation % math.PI_2) + { // 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) { + if (this.rotation !== this.rotationCache) + { this.rotationCache = this.rotation; this._sr = Math.sin(this.rotation); this._cr = Math.cos(this.rotation); @@ -291,7 +310,8 @@ ty = this.position.y; // check for pivot.. not often used so geared towards that fact! - if (this.pivot.x || this.pivot.y) { + 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; } @@ -304,7 +324,8 @@ wt.tx = tx * pt.a + ty * pt.c + pt.tx; wt.ty = tx * pt.b + ty * pt.d + pt.ty; } - else { + else + { // lets do the fast version as we know there is no rotation.. a = this.scale.x; d = this.scale.y; @@ -333,7 +354,8 @@ * @param matrix {Matrix} * @return {Rectangle} the rectangular bounding area */ -DisplayObject.prototype.getBounds = function (/* matrix */) { +DisplayObject.prototype.getBounds = function (/* matrix */) +{ return math.Rectangle.EMPTY; }; @@ -342,7 +364,8 @@ * * @return {Rectangle} the rectangular bounding area */ -DisplayObject.prototype.getLocalBounds = function () { +DisplayObject.prototype.getLocalBounds = function () +{ return this.getBounds(math.Matrix.IDENTITY); }; @@ -352,7 +375,8 @@ * @param position {Point} The world origin to calculate from * @return {Point} A point object representing the position of this object */ -DisplayObject.prototype.toGlobal = function (position) { +DisplayObject.prototype.toGlobal = function (position) +{ // don't need to u[date the lot this.displayObjectUpdateTransform(); return this.worldTransform.apply(position); @@ -365,8 +389,10 @@ * @param [from] {DisplayObject} The DisplayObject to calculate the global position from * @return {Point} A point object representing the position of this object */ -DisplayObject.prototype.toLocal = function (position, from) { - if (from) { +DisplayObject.prototype.toLocal = function (position, from) +{ + if (from) + { position = from.toGlobal(position); } @@ -381,7 +407,8 @@ * @param renderer {WebGLRenderer} The renderer * @private */ -DisplayObject.prototype.renderWebGL = function (/* renderer */) { +DisplayObject.prototype.renderWebGL = function (/* renderer */) +{ // OVERWRITE; }; @@ -391,6 +418,7 @@ * @param renderer {CanvasRenderer} The renderer * @private */ -DisplayObject.prototype.renderCanvas = function (/* renderer */) { +DisplayObject.prototype.renderCanvas = function (/* renderer */) +{ // OVERWRITE; }; diff --git a/src/core/display/DisplayObjectContainer.js b/src/core/display/DisplayObjectContainer.js index 689f40b..4625ee8 100644 --- a/src/core/display/DisplayObjectContainer.js +++ b/src/core/display/DisplayObjectContainer.js @@ -12,7 +12,8 @@ * @extends DisplayObject * @namespace PIXI */ -function DisplayObjectContainer() { +function DisplayObjectContainer() +{ DisplayObject.call(this); /** @@ -47,17 +48,21 @@ * @memberof DisplayObjectContainer# */ width: { - get: function () { + get: function () + { return this.scale.x * this.getLocalBounds().width; }, - set: function (value) { + set: function (value) + { var width = this.getLocalBounds().width; - if(width !== 0) { + if(width !== 0) + { this.scale.x = value / width; } - else { + else + { this.scale.x = 1; } @@ -73,17 +78,21 @@ * @memberof DisplayObjectContainer# */ height: { - get: function () { + get: function () + { return this.scale.y * this.getLocalBounds().height; }, - set: function (value) { + set: function (value) + { var height = this.getLocalBounds().height; - if (height !== 0) { + if (height !== 0) + { this.scale.y = value / height ; } - else { + else + { this.scale.y = 1; } @@ -100,18 +109,23 @@ * @memberof DisplayObject# */ cacheAsBitmap: { - get: function () { + get: function () + { return this._cacheAsBitmap; }, - set: function (value) { - if (this._cacheAsBitmap === value) { + set: function (value) + { + if (this._cacheAsBitmap === value) + { return; } - if (value) { + if (value) + { this._generateCachedSprite(); } - else { + else + { this._destroyCachedSprite(); } @@ -126,7 +140,8 @@ * @param child {DisplayObject} The DisplayObject to add to the container * @return {DisplayObject} The child that was added. */ -DisplayObjectContainer.prototype.addChild = function (child) { +DisplayObjectContainer.prototype.addChild = function (child) +{ return this.addChildAt(child, this.children.length); }; @@ -137,14 +152,18 @@ * @param index {Number} The index to place the child in * @return {DisplayObject} The child that was added. */ -DisplayObjectContainer.prototype.addChildAt = function (child, index) { +DisplayObjectContainer.prototype.addChildAt = function (child, index) +{ // prevent adding self as child - if (child === this) { + if (child === this) + { return; } - if (index >= 0 && index <= this.children.length) { - if (child.parent) { + if (index >= 0 && index <= this.children.length) + { + if (child.parent) + { child.parent.removeChild(child); } @@ -154,7 +173,8 @@ return child; } - else { + else + { throw new Error(child + 'addChildAt: The index '+ index +' supplied is out of bounds ' + this.children.length); } }; @@ -165,15 +185,18 @@ * @param child {DisplayObject} * @param child2 {DisplayObject} */ -DisplayObjectContainer.prototype.swapChildren = function (child, child2) { - if (child === child2) { +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) { + if (index1 < 0 || index2 < 0) + { throw new Error('swapChildren: Both the supplied DisplayObjects must be a child of the caller.'); } @@ -187,10 +210,12 @@ * @param child {DisplayObject} The DisplayObject instance to identify * @return {Number} The index position of the child display object to identify */ -DisplayObjectContainer.prototype.getChildIndex = function (child) { +DisplayObjectContainer.prototype.getChildIndex = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { throw new Error('The supplied DisplayObject must be a child of the caller'); } @@ -203,8 +228,10 @@ * @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 */ -DisplayObjectContainer.prototype.setChildIndex = function (child, index) { - if (index < 0 || index >= this.children.length) { +DisplayObjectContainer.prototype.setChildIndex = function (child, index) +{ + if (index < 0 || index >= this.children.length) + { throw new Error('The supplied index is out of bounds'); } @@ -220,8 +247,10 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child at the given index, if any. */ -DisplayObjectContainer.prototype.getChildAt = function (index) { - if (index < 0 || index >= this.children.length) { +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'); } @@ -234,10 +263,12 @@ * @param child {DisplayObject} The DisplayObject to remove * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChild = function (child) { +DisplayObjectContainer.prototype.removeChild = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { return; } @@ -250,7 +281,8 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChildAt = function (index) { +DisplayObjectContainer.prototype.removeChildAt = function (index) +{ var child = this.getChildAt(index); child.parent = null; @@ -265,24 +297,29 @@ * @param beginIndex {Number} The beginning position. Default value is 0. * @param endIndex {Number} The ending position. Default value is size of the container. */ -DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) { +DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) +{ var begin = beginIndex || 0; var end = typeof endIndex === 'number' ? endIndex : this.children.length; var range = end - begin; - if (range > 0 && range <= end) { + if (range > 0 && range <= end) + { var removed = this.children.splice(begin, range); - for (var i = 0; i < removed.length; ++i) { + for (var i = 0; i < removed.length; ++i) + { removed[i].parent = null; } return removed; } - else if (range === 0 && this.children.length === 0) { + else if (range === 0 && this.children.length === 0) + { return []; } - else { + else + { throw new RangeError('removeChildren: numeric values are outside the acceptable range.'); } }; @@ -291,7 +328,8 @@ * Generates and updates the cached sprite for this object. * */ -DisplayObjectContainer.prototype.updateCachedSprite = function () { +DisplayObjectContainer.prototype.updateCachedSprite = function () +{ this._generateCachedSprite(); }; @@ -304,7 +342,8 @@ * @param renderer {CanvasRenderer|WebGLRenderer} The renderer used to generate the texture. * @return {Texture} a texture of the graphics object */ -DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) { +DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) +{ var bounds = this.getLocalBounds(); var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0, renderer, scaleMode, resolution); @@ -322,18 +361,22 @@ * * @private */ -DisplayObjectContainer.prototype.updateTransform = function () { - if (!this.visible) { +DisplayObjectContainer.prototype.updateTransform = function () +{ + if (!this.visible) + { return; } this.displayObjectUpdateTransform(); - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { return; } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } }; @@ -346,8 +389,10 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getBounds = function () { - if (this.children.length === 0) { +DisplayObjectContainer.prototype.getBounds = function () +{ + if (this.children.length === 0) + { return math.Rectangle.EMPTY; } @@ -365,10 +410,12 @@ var childVisible = false; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -386,7 +433,8 @@ maxY = maxY > childMaxY ? maxY : childMaxY; } - if (!childVisible) { + if (!childVisible) + { return math.Rectangle.EMPTY; } @@ -407,12 +455,14 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getLocalBounds = function () { +DisplayObjectContainer.prototype.getLocalBounds = function () +{ var matrixCache = this.worldTransform; this.worldTransform = math.Matrix.IDENTITY; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } @@ -428,13 +478,16 @@ * * @param renderer {WebGLRenderer} The renderer */ -DisplayObjectContainer.prototype.renderWebGL = function (renderer) { +DisplayObjectContainer.prototype.renderWebGL = function (renderer) +{ // if the object is not visible or the alpha is 0 then no need to render this element - if (!this.visible || this.alpha <= 0) { + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } @@ -442,14 +495,17 @@ var i, j; // do a quick check to see if this element has a mask or a filter. - if (this._mask || this._filters) { + if (this._mask || this._filters) + { // push filter first as we need to ensure the stencil buffer is correct for any masking - if (this._filters) { + if (this._filters) + { renderer.spriteBatch.flush(); renderer.filterManager.pushFilter(this._filterBlock); } - if (this._mask) { + if (this._mask) + { renderer.spriteBatch.stop(); renderer.maskManager.pushMask(this.mask, renderer); renderer.spriteBatch.start(); @@ -459,36 +515,42 @@ this._renderWebGL(renderer); // now loop through the children and make sure they get rendered - for (i = 0, j = this.children.length; i < j; i++) { + for (i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderWebGL(renderer); } // time to stop the sprite batch as either a mask element or a filter draw will happen next renderer.spriteBatch.stop(); - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(this._mask, renderer); } - if (this._filters) { + if (this._filters) + { renderer.filterManager.popFilter(); } renderer.spriteBatch.start(); } - else { + else + { this._renderWebGL(renderer); // simple render children! - for (i = 0, j = this.children.length; i < j; ++i) { + for (i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderWebGL(renderer); } } }; -DisplayObjectContainer.prototype._renderWebGL = function (renderer) { +DisplayObjectContainer.prototype._renderWebGL = function (renderer) +{ // this is where content itself gets renderd.. @@ -499,25 +561,31 @@ * * @param renderer {CanvasRenderer} The renderer */ -DisplayObjectContainer.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0) { +DisplayObjectContainer.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -528,13 +596,16 @@ * @param renderer {WebGLRenderer|CanvasRenderer} The renderer * @private */ -DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) { +DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) +{ this._cachedSprite.worldAlpha = this.worldAlpha; - if (renderer.gl) { + if (renderer.gl) + { this._cachedSprite.renderWebGL(renderer); } - else { + else + { this._cachedSprite.renderCanvas(renderer); } }; @@ -544,10 +615,12 @@ * * @private */ -DisplayObjectContainer.prototype._generateCachedSprite = function () { +DisplayObjectContainer.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { // TODO - RenderTexture now *requires* a renderer instance, so this is like broken // because `renderer` isn't actually in scope here :P var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0); @@ -555,7 +628,8 @@ this._cachedSprite = new Sprite(renderTexture); this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.texture.resize(bounds.width | 0, bounds.height | 0); } @@ -580,8 +654,10 @@ * * @private */ -DisplayObjectContainer.prototype._destroyCachedSprite = function () { - if (!this._cachedSprite) { +DisplayObjectContainer.prototype._destroyCachedSprite = function () +{ + if (!this._cachedSprite) + { return; } diff --git a/src/core/display/Sprite.js b/src/core/display/Sprite.js index 707da24..5862aef 100644 --- a/src/core/display/Sprite.js +++ b/src/core/display/Sprite.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param texture {Texture} The texture for this sprite */ -function Sprite(texture) { +function Sprite(texture) +{ DisplayObjectContainer.call(this); /** @@ -85,12 +86,14 @@ this.texture = texture || Texture.EMPTY; } -Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) { +Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) +{ DisplayObjectContainer.prototype.destroy.call(this); this.anchor = null; - if (destroyTexture) { + if (destroyTexture) + { this._texture.destroy(destroyBaseTexture); } @@ -111,10 +114,12 @@ * @memberof Sprite# */ width: { - get: function () { + get: function () + { return this.scale.x * this.texture.frame.width; }, - set: function (value) { + set: function (value) + { this.scale.x = value / this.texture.frame.width; this._width = value; } @@ -127,10 +132,12 @@ * @memberof Sprite# */ height: { - get: function () { + get: function () + { return this.scale.y * this.texture.frame.height; }, - set: function (value) { + set: function (value) + { this.scale.y = value / this.texture.frame.height; this._height = value; } @@ -143,23 +150,29 @@ * @memberof Sprite# */ texture: { - get: function () { + get: function () + { return this._texture; }, - set: function (value) { - if (this._texture === value) { + set: function (value) + { + if (this._texture === value) + { return; } this._texture = value; this.cachedTint = 0xFFFFFF; - if (value) { + if (value) + { // wait for the texture to load - if (value.baseTexture.hasLoaded) { + if (value.baseTexture.hasLoaded) + { this._onTextureUpdate(); } - else { + else + { value.once('update', this._onTextureUpdate.bind(this)); } } @@ -172,18 +185,22 @@ * * @private */ -Sprite.prototype._onTextureUpdate = function () { +Sprite.prototype._onTextureUpdate = function () +{ // so if _width is 0 then width was not set.. - if (this._width) { + if (this._width) + { this.scale.x = this._width / this.texture.frame.width; } - if (this._height) { + if (this._height) + { this.scale.y = this._height / this.texture.frame.height; } }; -Sprite.prototype._renderWebGL = function (renderer) { +Sprite.prototype._renderWebGL = function (renderer) +{ // this is where content gets renderd.. // watch this space for a little render state manager.. @@ -197,7 +214,8 @@ * @param matrix {Matrix} the transformation matrix of the sprite * @return {Rectangle} the framing rectangle */ -Sprite.prototype.getBounds = function (matrix) { +Sprite.prototype.getBounds = function (matrix) +{ var width = this.texture.frame.width; var height = this.texture.frame.height; @@ -224,11 +242,13 @@ if(b === 0 && c === 0) { // scale may be negative! - if (a < 0) { + if (a < 0) + { a *= -1; } - if (d < 0) { + if (d < 0) + { d *= -1; } @@ -293,28 +313,34 @@ * * @param renderer {CanvasRenderer} The renderer */ -Sprite.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) { +Sprite.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) + { return; } - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; renderer.context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } // Ignore null sources - if (this.texture.valid) { + if (this.texture.valid) + { var resolution = this.texture.baseTexture.resolution / renderer.resolution; renderer.context.globalAlpha = this.worldAlpha; // If smoothingEnabled is supported and we need to change the smoothing property for this texture - if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) { + if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) + { renderer.scaleMode = this.texture.baseTexture.scaleMode; renderer.context[renderer.smoothProperty] = (renderer.scaleMode === CONST.scaleModes.LINEAR); } @@ -324,7 +350,8 @@ var dy = (this.texture.trim ? this.texture.trim.y : 0) - (this.anchor.y * this.texture.trim.height); // Allow for pixel rounding - if (renderer.roundPixels) { + if (renderer.roundPixels) + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -337,7 +364,8 @@ dx = dx | 0; dy = dy | 0; } - else { + else + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -348,8 +376,10 @@ ); } - if (this.tint !== 0xFFFFFF) { - if (this.cachedTint !== this.tint) { + if (this.tint !== 0xFFFFFF) + { + if (this.cachedTint !== this.tint) + { this.cachedTint = this.tint; // TODO clean up caching - how to clean up the caches? @@ -368,7 +398,8 @@ this.texture.crop.height / resolution ); } - else { + else + { renderer.context.drawImage( this.texture.baseTexture.source, this.texture.crop.x, @@ -383,11 +414,13 @@ } } - for (var i = 0, j = this.children.length; i < j; i++) { + for (var i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -402,10 +435,12 @@ * @param frameId {String} The frame Id of the texture in the cache * @return {Sprite} A new Sprite using a texture from the texture cache matching the frameId */ -Sprite.fromFrame = function (frameId) { +Sprite.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache' + this); } @@ -420,6 +455,7 @@ * @param imageId {String} The image url of the texture * @return {Sprite} A new Sprite using a texture from the texture cache matching the image id */ -Sprite.fromImage = function (imageId, crossorigin, scaleMode) { +Sprite.fromImage = function (imageId, crossorigin, scaleMode) +{ return new Sprite(Texture.fromImage(imageId, crossorigin, scaleMode)); }; diff --git a/src/core/display/SpriteBatch.js b/src/core/display/SpriteBatch.js index 3187777..c196fef 100644 --- a/src/core/display/SpriteBatch.js +++ b/src/core/display/SpriteBatch.js @@ -12,7 +12,8 @@ * ```js * var container = new SpriteBatch(); * - * for(var i = 0; i < 100; ++i) { + * for(var i = 0; i < 100; ++i) + * { * var sprite = new PIXI.Sprite.fromImage("myImage.png"); * container.addChild(sprite); * } @@ -25,7 +26,8 @@ */ //TODO RENAME to PARTICLE CONTAINER? -function SpriteBatch() { +function SpriteBatch() +{ DisplayObjectContainer.call(this); } @@ -38,7 +40,8 @@ * * @private */ -SpriteBatch.prototype.updateTransform = function () { +SpriteBatch.prototype.updateTransform = function () +{ // TODO don't need to! this.displayObjectUpdateTransform(); // PIXI.DisplayObjectContainer.prototype.updateTransform.call( this ); @@ -50,8 +53,10 @@ * @param renderer {WebGLRenderer} The webgl renderer * @private */ -SpriteBatch.prototype.renderWebGL = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderWebGL = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -71,8 +76,10 @@ * @param renderer {CanvasRenderer} The canvas renderer * @private */ -SpriteBatch.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -84,10 +91,12 @@ this.displayObjectUpdateTransform(); - for (var i = 0; i < this.children.length; ++i) { + for (var i = 0; i < this.children.length; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -95,9 +104,11 @@ context.globalAlpha = this.worldAlpha * child.alpha; - if (child.rotation % (Math.PI * 2) === 0) { + if (child.rotation % (Math.PI * 2) === 0) + { // this is the fastest way to optimise! - if rotation is 0 then we can avoid any kind of setTransform call - if (isRotated) { + if (isRotated) + { context.setTransform( transform.a, transform.b, @@ -122,8 +133,10 @@ frame.height * child.scale.y ); } - else { - if (!isRotated) { + else + { + if (!isRotated) + { isRotated = true; } @@ -131,7 +144,8 @@ var childTransform = child.worldTransform; - if (renderer.roundPixels) { + if (renderer.roundPixels) + { context.setTransform( childTransform.a, childTransform.b, @@ -141,7 +155,8 @@ childTransform.ty | 0 ); } - else { + else + { context.setTransform( childTransform.a, childTransform.b, diff --git a/src/core/index.js b/src/core/index.js index 3954b6f..eb4a82b 100644 --- a/src/core/index.js +++ b/src/core/index.js @@ -58,11 +58,13 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRenderer: function (width, height, options, noWebGL) { + autoDetectRenderer: function (width, height, options, noWebGL) + { width = width || 800; height = height || 600; - if (!noWebGL && require('webgl-enabled')()) { + if (!noWebGL && require('webgl-enabled')()) + { return new core.WebGLRenderer(width, height, options); } @@ -87,7 +89,8 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRecommendedRenderer: function (width, height, options) { + autoDetectRecommendedRenderer: function (width, height, options) + { var isAndroid = /Android/i.test(navigator.userAgent); return core.autoDetectRenderer(width, height, options, isAndroid); diff --git a/src/core/math/Matrix.js b/src/core/math/Matrix.js index c2f87e2..2ff4848 100644 --- a/src/core/math/Matrix.js +++ b/src/core/math/Matrix.js @@ -10,7 +10,8 @@ * @class * @namespace PIXI */ -function Matrix() { +function Matrix() +{ /** * @member {number} * @default 1 @@ -63,7 +64,8 @@ * * @param array {number[]} The array that the matrix will be populated from. */ -Matrix.prototype.fromArray = function (array) { +Matrix.prototype.fromArray = function (array) +{ this.a = array[0]; this.b = array[1]; this.c = array[3]; @@ -78,14 +80,17 @@ * @param transpose {boolean} Whether we need to transpose the matrix or not * @return {number[]} the newly created array which contains the matrix */ -Matrix.prototype.toArray = function (transpose) { - if (!this.array) { +Matrix.prototype.toArray = function (transpose) +{ + if (!this.array) + { this.array = new Float32Array(9); } var array = this.array; - if (transpose) { + if (transpose) + { array[0] = this.a; array[1] = this.b; array[2] = 0; @@ -96,7 +101,8 @@ array[7] = this.ty; array[8] = 1; } - else { + else + { array[0] = this.a; array[1] = this.c; array[2] = this.tx; @@ -119,7 +125,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, transformed through this matrix */ -Matrix.prototype.apply = function (pos, newPos) { +Matrix.prototype.apply = function (pos, newPos) +{ newPos = newPos || new Point(); newPos.x = this.a * pos.x + this.c * pos.y + this.tx; @@ -136,7 +143,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, inverse-transformed through this matrix */ -Matrix.prototype.applyInverse = function (pos, newPos) { +Matrix.prototype.applyInverse = function (pos, newPos) +{ newPos = newPos || new Point(); var id = 1 / (this.a * this.d + this.c * -this.b); @@ -154,7 +162,8 @@ * @param {number} y * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.translate = function (x, y) { +Matrix.prototype.translate = function (x, y) +{ this.tx += x; this.ty += y; @@ -168,7 +177,8 @@ * @param {number} y The amount to scale vertically * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.scale = function (x, y) { +Matrix.prototype.scale = function (x, y) +{ this.a *= x; this.d *= y; this.c *= x; @@ -186,7 +196,8 @@ * @param {number} angle - The angle in radians. * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.rotate = function (angle) { +Matrix.prototype.rotate = function (angle) +{ var cos = Math.cos( angle ); var sin = Math.sin( angle ); @@ -210,7 +221,8 @@ * @param {Matrix} matrix * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.append = function (matrix) { +Matrix.prototype.append = function (matrix) +{ var a1 = this.a; var b1 = this.b; var c1 = this.c; @@ -232,7 +244,8 @@ * * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.identity = function () { +Matrix.prototype.identity = function () +{ this.a = 1; this.b = 0; this.c = 0; diff --git a/src/core/math/Point.js b/src/core/math/Point.js index 7565b2d..632f346 100644 --- a/src/core/math/Point.js +++ b/src/core/math/Point.js @@ -7,7 +7,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -function Point(x, y) { +function Point(x, y) +{ /** * @member {number} * @default 0 @@ -29,7 +30,8 @@ * * @return {Point} a copy of the point */ -Point.prototype.clone = function () { +Point.prototype.clone = function () +{ return new Point(this.x, this.y); }; @@ -40,7 +42,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -Point.prototype.set = function (x, y) { +Point.prototype.set = function (x, y) +{ this.x = x || 0; this.y = y || ( (y !== 0) ? this.x : 0 ) ; }; diff --git a/src/core/math/shapes/Circle.js b/src/core/math/shapes/Circle.js index 69cfdc9..4d76efc 100644 --- a/src/core/math/shapes/Circle.js +++ b/src/core/math/shapes/Circle.js @@ -10,7 +10,8 @@ * @param y {number} The Y coordinate of the center of this circle * @param radius {number} The radius of the circle */ -function Circle(x, y, radius) { +function Circle(x, y, radius) +{ /** * @member {number} * @default 0 @@ -46,7 +47,8 @@ * @method clone * @return {Circle} a copy of the Circle */ -Circle.prototype.clone = function () { +Circle.prototype.clone = function () +{ return new Circle(this.x, this.y, this.radius); }; @@ -58,8 +60,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Circle */ -Circle.prototype.contains = function (x, y) { - if (this.radius <= 0) { +Circle.prototype.contains = function (x, y) +{ + if (this.radius <= 0) + { return false; } @@ -79,6 +83,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Circle.prototype.getBounds = function () { +Circle.prototype.getBounds = function () +{ return new Rectangle(this.x - this.radius, this.y - this.radius, this.radius * 2, this.radius * 2); }; diff --git a/src/core/math/shapes/Ellipse.js b/src/core/math/shapes/Ellipse.js index 4f2d066..fefd01a 100644 --- a/src/core/math/shapes/Ellipse.js +++ b/src/core/math/shapes/Ellipse.js @@ -11,7 +11,8 @@ * @param width {number} The half width of this ellipse * @param height {number} The half height of this ellipse */ -function Ellipse(x, y, width, height) { +function Ellipse(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -53,7 +54,8 @@ * @method clone * @return {Ellipse} a copy of the ellipse */ -Ellipse.prototype.clone = function () { +Ellipse.prototype.clone = function () +{ return new Ellipse(this.x, this.y, this.width, this.height); }; @@ -65,8 +67,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coords are within this ellipse */ -Ellipse.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Ellipse.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } @@ -86,6 +90,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Ellipse.prototype.getBounds = function () { +Ellipse.prototype.getBounds = function () +{ return new Rectangle(this.x - this.width, this.y - this.height, this.width, this.height); }; diff --git a/src/core/math/shapes/Polygon.js b/src/core/math/shapes/Polygon.js index ae89148..fea6d37 100644 --- a/src/core/math/shapes/Polygon.js +++ b/src/core/math/shapes/Polygon.js @@ -10,16 +10,20 @@ * arguments passed can be flat x,y values e.g. `new Polygon(x,y, x,y, x,y, ...)` where `x` and `y` are * Numbers. */ -function Polygon(points) { +function Polygon(points) +{ //if points isn't an array, use arguments as the array - if (!(points instanceof Array)) { + if (!(points instanceof Array)) + { points = Array.prototype.slice.call(arguments); } //if this is a flat array of numbers, convert it to points - if (points[0] instanceof Point) { + if (points[0] instanceof Point) + { var p = []; - for (var i = 0, il = points.length; i < il; i++) { + for (var i = 0, il = points.length; i < il; i++) + { p.push(points[i].x, points[i].y); } @@ -51,7 +55,8 @@ * * @return {Polygon} a copy of the polygon */ -Polygon.prototype.clone = function () { +Polygon.prototype.clone = function () +{ return new Polygon(this.points.slice()); }; @@ -62,19 +67,22 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this polygon */ -Polygon.prototype.contains = function (x, y) { +Polygon.prototype.contains = function (x, y) +{ var inside = false; // use some raycasting to test hits // https://github.com/substack/point-in-polygon/blob/master/index.js var length = this.points.length / 2; - for (var i = 0, j = length - 1; i < length; j = i++) { + for (var i = 0, j = length - 1; i < length; j = i++) + { var xi = this.points[i * 2], yi = this.points[i * 2 + 1], xj = this.points[j * 2], yj = this.points[j * 2 + 1], intersect = ((yi > y) !== (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi); - if (intersect) { + if (intersect) + { inside = !inside; } } diff --git a/src/core/math/shapes/Rectangle.js b/src/core/math/shapes/Rectangle.js index 16ac62a..4008b68 100644 --- a/src/core/math/shapes/Rectangle.js +++ b/src/core/math/shapes/Rectangle.js @@ -10,7 +10,8 @@ * @param width {number} The overall width of this rectangle * @param height {number} The overall height of this rectangle */ -function Rectangle(x, y, width, height) { +function Rectangle(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -60,7 +61,8 @@ * * @return {Rectangle} a copy of the rectangle */ -Rectangle.prototype.clone = function () { +Rectangle.prototype.clone = function () +{ return new Rectangle(this.x, this.y, this.width, this.height); }; @@ -71,13 +73,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rectangle */ -Rectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Rectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/math/shapes/RoundedRectangle.js b/src/core/math/shapes/RoundedRectangle.js index 27d286e..7bf6411 100644 --- a/src/core/math/shapes/RoundedRectangle.js +++ b/src/core/math/shapes/RoundedRectangle.js @@ -11,7 +11,8 @@ * @param height {number} The overall height of this rounded rectangle * @param radius {number} Controls the radius of the rounded corners */ -function RoundedRectangle(x, y, width, height, radius) { +function RoundedRectangle(x, y, width, height, radius) +{ /** * @member {number} * @default 0 @@ -58,7 +59,8 @@ * * @return {RoundedRectangle} a copy of the rounded rectangle */ -RoundedRectangle.prototype.clone = function () { +RoundedRectangle.prototype.clone = function () +{ return new RoundedRectangle(this.x, this.y, this.width, this.height, this.radius); }; @@ -69,13 +71,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rounded Rectangle */ -RoundedRectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +RoundedRectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/primitives/Graphics.js b/src/core/primitives/Graphics.js index 261c534..e902d2a 100644 --- a/src/core/primitives/Graphics.js +++ b/src/core/primitives/Graphics.js @@ -16,7 +16,8 @@ * @extends DisplayObjectContainer * @namespace PIXI */ -function Graphics() { +function Graphics() +{ DisplayObjectContainer.call(this); this.renderable = true; @@ -154,16 +155,20 @@ * @private */ cacheAsBitmap: { - get: function () { + get: function () + { return this._cacheAsBitmap; }, - set: function (value) { + set: function (value) + { this._cacheAsBitmap = value; - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._generateCachedSprite(); } - else { + else + { this.destroyCachedSprite(); this.dirty = true; } @@ -176,7 +181,8 @@ * * @return {Graphics} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ var clone = new Graphics(); clone.renderable = this.renderable; @@ -192,7 +198,8 @@ clone.cachedSpriteDirty = this.cachedSpriteDirty; // copy graphics data - for (var i = 0; i < this.graphicsData.length; ++i) { + for (var i = 0; i < this.graphicsData.length; ++i) + { clone.graphicsData.push(this.graphicsData.clone()); } @@ -211,17 +218,21 @@ * @param alpha {number} alpha of the line to draw, will update the objects stored style * @return {Graphics} */ -Graphics.prototype.lineStyle = function (lineWidth, color, alpha) { +Graphics.prototype.lineStyle = function (lineWidth, color, alpha) +{ this.lineWidth = lineWidth || 0; this.lineColor = color || 0; this.lineAlpha = (arguments.length < 3) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length) + { // halfway through a line? start a new one! this.drawShape( new math.Polygon( this.currentPath.shape.points.slice(-2) )); } - else { + else + { // otherwise its empty so lets just set the line properties this.currentPath.lineWidth = this.lineWidth; this.currentPath.lineColor = this.lineColor; @@ -239,7 +250,8 @@ * @param y {number} the Y coordinate to move to * @return {Graphics} */ -Graphics.prototype.moveTo = function (x, y) { +Graphics.prototype.moveTo = function (x, y) +{ this.drawShape(new math.Polygon([x,y])); return this; @@ -253,7 +265,8 @@ * @param y {number} the Y coordinate to draw to * @return {Graphics} */ -Graphics.prototype.lineTo = function (x, y) { +Graphics.prototype.lineTo = function (x, y) +{ this.currentPath.shape.points.push(x, y); this.dirty = true; @@ -270,13 +283,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -285,7 +302,8 @@ n = 20, points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { this.moveTo(0, 0); } @@ -293,7 +311,8 @@ var fromY = points[points.length-1]; var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; xa = fromX + ( (cpX - fromX) * j ); @@ -319,13 +338,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -342,7 +365,8 @@ var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; dt = (1 - j); @@ -373,13 +397,17 @@ * @param radius {number} The radius of the arc * @return {Graphics} */ -Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points.push(x1, y1); } } - else { + else + { this.moveTo(x1, y1); } @@ -392,12 +420,15 @@ b2 = x2 - x1, mm = Math.abs(a1 * b2 - b1 * a2); - if (mm < 1.0e-8 || radius === 0) { - if (points[points.length-2] !== x1 || points[points.length-1] !== y1) { + if (mm < 1.0e-8 || radius === 0) + { + if (points[points.length-2] !== x1 || points[points.length-1] !== y1) + { points.push(x1, y1); } } - else { + else + { var dd = a1 * a1 + b1 * b1, cc = a2 * a2 + b2 * b2, tt = a1 * a2 + b1 * b2, @@ -433,42 +464,51 @@ * @param anticlockwise {boolean} Optional. Specifies whether the drawing should be counterclockwise or clockwise. False is default, and indicates clockwise, while true indicates counter-clockwise. * @return {Graphics} */ -Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) { +Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) +{ var startX = cx + Math.cos(startAngle) * radius; var startY = cy + Math.sin(startAngle) * radius; var points; // TODO - This if-else makes no sense. It uses currentPath in the else where it doesn't exist... - if (this.currentPath) { + if (this.currentPath) + { points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { points.push(startX, startY); } - else if (points[points.length-2] !== startX || points[points.length-1] !== startY) { + else if (points[points.length-2] !== startX || points[points.length-1] !== startY) + { points.push(startX, startY); } } - else { + else + { this.moveTo(startX, startY); points = this.currentPath.shape.points; } - if (startAngle === endAngle) { + if (startAngle === endAngle) + { return this; } - if (!anticlockwise && endAngle <= startAngle) { + if (!anticlockwise && endAngle <= startAngle) + { endAngle += Math.PI * 2; } - else if (anticlockwise && startAngle <= endAngle) { + else if (anticlockwise && startAngle <= endAngle) + { startAngle += Math.PI * 2; } var sweep = anticlockwise ? (startAngle - endAngle) *-1 : (endAngle - startAngle); var segs = (Math.abs(sweep)/ (Math.PI * 2)) * 40; - if (sweep === 0) { + if (sweep === 0) + { return this; } @@ -482,7 +522,8 @@ var remainder = ( segMinus % 1 ) / segMinus; - for (var i = 0; i <= segMinus; ++i) { + for (var i = 0; i <= segMinus; ++i) + { var real = i + remainder * i; var angle = ((theta) + startAngle + (theta2 * real)); @@ -506,13 +547,16 @@ * @param alpha {number} the alpha of the fill * @return {Graphics} */ -Graphics.prototype.beginFill = function (color, alpha) { +Graphics.prototype.beginFill = function (color, alpha) +{ this.filling = true; this.fillColor = color || 0; this.fillAlpha = (alpha === undefined) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length <= 2) + { this.currentPath.fill = this.filling; this.currentPath.fillColor = this.fillColor; this.currentPath.fillAlpha = this.fillAlpha; @@ -526,7 +570,8 @@ * * @return {Graphics} */ -Graphics.prototype.endFill = function () { +Graphics.prototype.endFill = function () +{ this.filling = false; this.fillColor = null; this.fillAlpha = 1; @@ -542,7 +587,8 @@ * @param height {number} The height of the rectangle * @return {Graphics} */ -Graphics.prototype.drawRect = function ( x, y, width, height ) { +Graphics.prototype.drawRect = function ( x, y, width, height ) +{ this.drawShape(new math.Rectangle(x,y, width, height)); return this; @@ -556,7 +602,8 @@ * @param height {number} The height of the rectangle * @param radius {number} Radius of the rectangle corners */ -Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) { +Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) +{ this.drawShape(new math.RoundedRectangle(x, y, width, height, radius)); return this; @@ -570,7 +617,8 @@ * @param radius {number} The radius of the circle * @return {Graphics} */ -Graphics.prototype.drawCircle = function (x, y, radius) { +Graphics.prototype.drawCircle = function (x, y, radius) +{ this.drawShape(new math.Circle(x,y, radius)); return this; @@ -585,7 +633,8 @@ * @param height {number} The half height of the ellipse * @return {Graphics} */ -Graphics.prototype.drawEllipse = function (x, y, width, height) { +Graphics.prototype.drawEllipse = function (x, y, width, height) +{ this.drawShape(new math.Ellipse(x, y, width, height)); return this; @@ -597,8 +646,10 @@ * @param path {Array} The path data used to construct the polygon. * @return {Graphics} */ -Graphics.prototype.drawPolygon = function (path) { - if (!(path instanceof Array)) { +Graphics.prototype.drawPolygon = function (path) +{ + if (!(path instanceof Array)) + { path = Array.prototype.slice.call(arguments); } @@ -612,7 +663,8 @@ * * @return {Graphics} */ -Graphics.prototype.clear = function () { +Graphics.prototype.clear = function () +{ this.lineWidth = 0; this.filling = false; @@ -631,7 +683,8 @@ * @param scaleMode {number} Should be one of the scaleMode consts * @return {Texture} a texture of the graphics object */ -Graphics.prototype.generateTexture = function (resolution, scaleMode) { +Graphics.prototype.generateTexture = function (resolution, scaleMode) +{ resolution = resolution || 1; var bounds = this.getBounds(); @@ -655,17 +708,21 @@ * * @param renderer {WebGLRenderer} */ -Graphics.prototype._renderWebGL = function (renderer) { +Graphics.prototype._renderWebGL = function (renderer) +{ // if the sprite is not visible or the alpha is 0 then no need to render this element - if (this.isMask === true) { + if (this.isMask === true) + { return; } // this code may still be needed so leaving for now.. - // + // /* - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture on the gpu too! @@ -681,17 +738,24 @@ return; } - */ - - // check if the webgl graphic needs to be updated - if (this.glDirty) { - this.dirty = true; - this.glDirty = false; - } + else */ - renderer.setObjectRendererer(renderer.graphicsRenderer); - renderer.graphicsRenderer.render(this); + renderer.spriteBatch.stop(); + renderer.blendModeManager.setBlendMode(this.blendMode); + // check blend mode + renderer.blendModeManager.setBlendMode( this.blendMode ); + + // check if the webgl graphic needs to be updated + if (this.glDirty) + { + this.dirty = true; + this.glDirty = false; + } + + WebGLGraphics.renderGraphics(this, renderer); + + renderer.spriteBatch.start(); }; /** @@ -700,14 +764,18 @@ * @param renderer {CanvasRenderer} * @private */ -Graphics.prototype.renderCanvas = function (renderer) { +Graphics.prototype.renderCanvas = function (renderer) +{ // 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.isMask === true) { + if (!this.visible || this.alpha <= 0 || this.isMask === true) + { return; } - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture @@ -723,16 +791,19 @@ return; } - else { + else + { var context = renderer.context; var transform = this.worldTransform; - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } @@ -748,11 +819,13 @@ CanvasGraphics.renderGraphics(this, context); - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } } @@ -763,13 +836,16 @@ * * @return {Rectangle} the rectangular bounding area */ -Graphics.prototype.getBounds = function (matrix) { +Graphics.prototype.getBounds = function (matrix) +{ // return an empty object if the item is a mask! - if (this.isMask) { + if (this.isMask) + { return math.Rectangle.EMPTY; } - if (this.dirty) { + if (this.dirty) + { this.updateLocalBounds(); this.glDirty = true; @@ -841,23 +917,27 @@ * Update the bounds of the object * */ -Graphics.prototype.updateLocalBounds = function () { +Graphics.prototype.updateLocalBounds = function () +{ var minX = Infinity; var maxX = -Infinity; var minY = Infinity; var maxY = -Infinity; - if (this.graphicsData.length) { + if (this.graphicsData.length) + { var shape, points, x, y, w, h; - for (var i = 0; i < this.graphicsData.length; i++) { + for (var i = 0; i < this.graphicsData.length; i++) + { var data = this.graphicsData[i]; var type = data.type; var lineWidth = data.lineWidth; shape = data.shape; - if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) { + if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) + { x = shape.x - lineWidth/2; y = shape.y - lineWidth/2; w = shape.width + lineWidth; @@ -869,7 +949,8 @@ minY = y < minY ? y : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.CIRC) { + else if (type === CONST.SHAPES.CIRC) + { x = shape.x; y = shape.y; w = shape.radius + lineWidth/2; @@ -881,7 +962,8 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.ELIP) { + else if (type === CONST.SHAPES.ELIP) + { x = shape.x; y = shape.y; w = shape.width + lineWidth/2; @@ -893,11 +975,13 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else { + else + { // POLY points = shape.points; - for (var j = 0; j < points.length; j += 2) { + for (var j = 0; j < points.length; j += 2) + { x = points[j]; y = points[j+1]; @@ -910,7 +994,8 @@ } } } - else { + else + { minX = 0; maxX = 0; minY = 0; @@ -931,10 +1016,12 @@ * * @private */ -Graphics.prototype._generateCachedSprite = function () { +Graphics.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { var canvasBuffer = new CanvasBuffer(bounds.width, bounds.height); var texture = Texture.fromCanvas(canvasBuffer.canvas); @@ -943,7 +1030,8 @@ this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.buffer.resize(bounds.width, bounds.height); } @@ -968,7 +1056,8 @@ * * @private */ -Graphics.prototype.updateCachedSpriteTexture = function () { +Graphics.prototype.updateCachedSpriteTexture = function () +{ var cachedSprite = this._cachedSprite; var texture = cachedSprite.texture; var canvas = cachedSprite.buffer.canvas; @@ -989,7 +1078,8 @@ * Destroys a previous cached sprite. * */ -Graphics.prototype.destroyCachedSprite = function () { +Graphics.prototype.destroyCachedSprite = function () +{ this._cachedSprite.texture.destroy(true); // let the gc collect the unused sprite @@ -1003,10 +1093,13 @@ * @param {Circle|Rectangle|Ellipse|Line|Polygon} shape The Shape object to draw. * @return {GraphicsData} The generated GraphicsData object. */ -Graphics.prototype.drawShape = function (shape) { - if (this.currentPath) { +Graphics.prototype.drawShape = function (shape) +{ + if (this.currentPath) + { // check current path! - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath.shape.points.length <= 2) + { this.graphicsData.pop(); } } @@ -1017,7 +1110,8 @@ this.graphicsData.push(data); - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { data.shape.closed = this.filling; this.currentPath = data; } diff --git a/src/core/primitives/GraphicsData.js b/src/core/primitives/GraphicsData.js index 99decbe..788f6f2 100644 --- a/src/core/primitives/GraphicsData.js +++ b/src/core/primitives/GraphicsData.js @@ -4,7 +4,8 @@ * @class * @namespace PIXI */ -function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) { +function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) +{ this.lineWidth = lineWidth; this.lineColor = lineColor; this.lineAlpha = lineAlpha; @@ -27,7 +28,8 @@ * * @return {GraphicsData} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ return new GraphicsData( this.lineWidth, this.lineColor, diff --git a/src/core/renderers/canvas/CanvasRenderer.js b/src/core/renderers/canvas/CanvasRenderer.js index 15a0978..7aebd44 100644 --- a/src/core/renderers/canvas/CanvasRenderer.js +++ b/src/core/renderers/canvas/CanvasRenderer.js @@ -17,17 +17,22 @@ * @param [options.resolution=1] {number} the resolution of the renderer retina would be 2 * @param [options.clearBeforeRender=true] {boolean} This sets if the CanvasRenderer will clear the canvas or not before the new render pass. */ -function CanvasRenderer(width, height, options) { +function CanvasRenderer(width, height, options) +{ utils.sayHello('Canvas'); - if (options) { - for (var i in CONST.defaultRenderOptions) { - if (typeof options[i] === 'undefined') { + if (options) + { + for (var i in CONST.defaultRenderOptions) + { + if (typeof options[i] === 'undefined') + { options[i] = CONST.defaultRenderOptions[i]; } } } - else { + else + { options = CONST.defaultRenderOptions; } @@ -156,19 +161,24 @@ this.smoothProperty = null; - if (this.context.imageSmoothingEnabled) { + if (this.context.imageSmoothingEnabled) + { this.smoothProperty = 'imageSmoothingEnabled'; } - else if (this.context.webkitImageSmoothingEnabled) { + else if (this.context.webkitImageSmoothingEnabled) + { this.smoothProperty = 'webkitImageSmoothingEnabled'; } - else if (this.context.mozImageSmoothingEnabled) { + else if (this.context.mozImageSmoothingEnabled) + { this.smoothProperty = 'mozImageSmoothingEnabled'; } - else if (this.context.oImageSmoothingEnabled) { + else if (this.context.oImageSmoothingEnabled) + { this.smoothProperty = 'oImageSmoothingEnabled'; } - else if (this.context.msImageSmoothingEnabled) { + else if (this.context.msImageSmoothingEnabled) + { this.smoothProperty = 'msImageSmoothingEnabled'; } @@ -193,10 +203,12 @@ * @memberof CanvasRenderer# */ backgroundColor: { - get: function () { + get: function () + { return this._backgroundColor; }, - set: function (val) { + set: function (val) + { this._backgroundColor = val; this._backgroundColorString = utils.hex2string(val); } @@ -208,7 +220,8 @@ * * @param object {DisplayObject} the object to be rendered */ -CanvasRenderer.prototype.render = function (object) { +CanvasRenderer.prototype.render = function (object) +{ object.updateTransform(); this.context.setTransform(1,0,0,1,0,0); @@ -218,16 +231,20 @@ this.currentBlendMode = CONST.blendModes.NORMAL; this.context.globalCompositeOperation = this.blendModes[CONST.blendModes.NORMAL]; - if (navigator.isCocoonJS && this.view.screencanvas) { + if (navigator.isCocoonJS && this.view.screencanvas) + { this.context.fillStyle = 'black'; this.context.clear(); } - if (this.clearBeforeRender) { - if (this.transparent) { + if (this.clearBeforeRender) + { + if (this.transparent) + { this.context.clearRect(0, 0, this.width, this.height); } - else { + else + { this.context.fillStyle = this._backgroundColorString; this.context.fillRect(0, 0, this.width , this.height); } @@ -241,8 +258,10 @@ * * @param [removeView=false] {boolean} Removes the Canvas element from the DOM. */ -CanvasRenderer.prototype.destroy = function (removeView) { - if (removeView && this.view.parent) { +CanvasRenderer.prototype.destroy = function (removeView) +{ + if (removeView && this.view.parent) + { this.view.parent.removeChild(this.view); } @@ -257,14 +276,16 @@ * @param width {number} the new width of the canvas view * @param height {number} the new height of the canvas view */ -CanvasRenderer.prototype.resize = function (width, height) { +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) { + if (this.autoResize) + { this.view.style.width = this.width / this.resolution + 'px'; this.view.style.height = this.height / this.resolution + 'px'; } @@ -276,7 +297,8 @@ * @param displayObject {DisplayObject} The displayObject to render * @private */ -CanvasRenderer.prototype.renderDisplayObject = function (displayObject) { +CanvasRenderer.prototype.renderDisplayObject = function (displayObject) +{ displayObject.renderCanvas(this); }; @@ -285,11 +307,14 @@ * * @private */ -CanvasRenderer.prototype._mapBlendModes = function () { - if (!this.blendModes) { +CanvasRenderer.prototype._mapBlendModes = function () +{ + if (!this.blendModes) + { this.blendModes = {}; - if (utils.canUseNewCanvasBlendModes()) { + if (utils.canUseNewCanvasBlendModes()) + { this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? this.blendModes[CONST.blendModes.MULTIPLY] = 'multiply'; @@ -308,7 +333,8 @@ this.blendModes[CONST.blendModes.COLOR] = 'color'; this.blendModes[CONST.blendModes.LUMINOSITY] = 'luminosity'; } - else { + else + { // this means that the browser does not support the cool new blend modes in canvas 'cough' ie 'cough' this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? diff --git a/src/core/renderers/canvas/utils/CanvasBuffer.js b/src/core/renderers/canvas/utils/CanvasBuffer.js index ebe5d47..b183a66 100644 --- a/src/core/renderers/canvas/utils/CanvasBuffer.js +++ b/src/core/renderers/canvas/utils/CanvasBuffer.js @@ -6,7 +6,8 @@ * @param width {number} the width for the newly created canvas * @param height {number} the height for the newly created canvas */ -function CanvasBuffer(width, height) { +function CanvasBuffer(width, height) +{ /** * The Canvas object that belongs to this CanvasBuffer. * @@ -36,10 +37,12 @@ * @memberof CanvasBuffer# */ width: { - get: function () { + get: function () + { return this.canvas.width; }, - set: function (val) { + set: function (val) + { this.canvas.width = val; } }, @@ -50,10 +53,12 @@ * @memberof CanvasBuffer# */ height: { - get: function () { + get: function () + { return this.canvas.height; }, - set: function (val) { + set: function (val) + { this.canvas.height = val; } } @@ -64,7 +69,8 @@ * * @private */ -CanvasBuffer.prototype.clear = function () { +CanvasBuffer.prototype.clear = function () +{ this.context.setTransform(1, 0, 0, 1, 0, 0); this.context.clearRect(0,0, this.canvas.width, this.canvas.height); }; @@ -75,7 +81,8 @@ * @param width {number} the new width of the canvas * @param height {number} the new height of the canvas */ -CanvasBuffer.prototype.resize = function (width, height) { +CanvasBuffer.prototype.resize = function (width, height) +{ this.canvas.width = width; this.canvas.height = height; }; diff --git a/src/core/renderers/canvas/utils/CanvasGraphics.js b/src/core/renderers/canvas/utils/CanvasGraphics.js index c7eaa2a..3f2a91f 100644 --- a/src/core/renderers/canvas/utils/CanvasGraphics.js +++ b/src/core/renderers/canvas/utils/CanvasGraphics.js @@ -13,15 +13,18 @@ * @param graphics {Graphics} the actual graphics object to render * @param context {CanvasRenderingContext2D} the 2d drawing method of the canvas */ -CanvasGraphics.renderGraphics = function (graphics, context) { +CanvasGraphics.renderGraphics = function (graphics, context) +{ var worldAlpha = graphics.worldAlpha; - if (graphics.dirty) { + if (graphics.dirty) + { this.updateGraphicsTint(graphics); graphics.dirty = false; } - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; @@ -30,69 +33,82 @@ context.lineWidth = data.lineWidth; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { context.beginPath(); var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } - if (shape.closed) { + if (shape.closed) + { context.lineTo(points[0], points[1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fillRect(shape.x, shape.y, shape.width, shape.height); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.strokeRect(shape.x, shape.y, shape.width, shape.height); } } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.beginPath(); context.arc(shape.x, shape.y, shape.radius,0,2*Math.PI); context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas var w = shape.width * 2; @@ -119,18 +135,21 @@ context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; var width = shape.width; @@ -152,13 +171,15 @@ context.quadraticCurveTo(rx, ry, rx, ry + radius); context.closePath(); - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); @@ -174,45 +195,54 @@ * @param graphics {Graphics} the graphics which will be used as a mask * @param context {CanvasRenderingContext2D} the context 2d method of the canvas */ -CanvasGraphics.renderGraphicsMask = function (graphics, context) { +CanvasGraphics.renderGraphicsMask = function (graphics, context) +{ var len = graphics.graphicsData.length; - if (len === 0) { + if (len === 0) + { return; } context.beginPath(); - for (var i = 0; i < len; i++) { + for (var i = 0; i < len; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { context.rect(shape.x, shape.y, shape.width, shape.height); context.closePath(); } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.arc(shape.x, shape.y, shape.radius, 0, 2 * Math.PI); context.closePath(); } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas @@ -237,7 +267,8 @@ context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); context.closePath(); } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; @@ -262,8 +293,10 @@ } }; -CanvasGraphics.updateGraphicsTint = function (graphics) { - if (graphics.tint === 0xFFFFFF) { +CanvasGraphics.updateGraphicsTint = function (graphics) +{ + if (graphics.tint === 0xFFFFFF) + { return; } @@ -271,7 +304,8 @@ var tintG = (graphics.tint >> 8 & 0xFF) / 255; var tintB = (graphics.tint & 0xFF)/ 255; - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var fillColor = data.fillColor | 0; diff --git a/src/core/renderers/canvas/utils/CanvasMaskManager.js b/src/core/renderers/canvas/utils/CanvasMaskManager.js index e04a733..9827d36 100644 --- a/src/core/renderers/canvas/utils/CanvasMaskManager.js +++ b/src/core/renderers/canvas/utils/CanvasMaskManager.js @@ -6,7 +6,8 @@ * @class * @namespace PIXI */ -function CanvasMaskManager() {} +function CanvasMaskManager() +{} CanvasMaskManager.prototype.constructor = CanvasMaskManager; module.exports = CanvasMaskManager; @@ -17,7 +18,8 @@ * @param maskData {object} the maskData that will be pushed * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.pushMask = function (maskData, renderer) { +CanvasMaskManager.prototype.pushMask = function (maskData, renderer) +{ renderer.context.save(); var cacheAlpha = maskData.alpha; @@ -45,6 +47,7 @@ * * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.popMask = function (renderer) { +CanvasMaskManager.prototype.popMask = function (renderer) +{ renderer.context.restore(); }; diff --git a/src/core/renderers/canvas/utils/CanvasTinter.js b/src/core/renderers/canvas/utils/CanvasTinter.js index 17e0529..d2fb1bc 100644 --- a/src/core/renderers/canvas/utils/CanvasTinter.js +++ b/src/core/renderers/canvas/utils/CanvasTinter.js @@ -14,7 +14,8 @@ * @param color {number} the color to use to tint the sprite with * @return {HTMLCanvasElement} The tinted canvas */ -CanvasTinter.getTintedTexture = function (sprite, color) { +CanvasTinter.getTintedTexture = function (sprite, color) +{ var texture = sprite.texture; color = CanvasTinter.roundColor(color); @@ -23,7 +24,8 @@ texture.tintCache = texture.tintCache || {}; - if (texture.tintCache[stringColor]) { + if (texture.tintCache[stringColor]) + { return texture.tintCache[stringColor]; } @@ -33,14 +35,16 @@ //CanvasTinter.tintWithPerPixel(texture, stringColor, canvas); CanvasTinter.tintMethod(texture, color, canvas); - if (CanvasTinter.convertTintToImage) { + if (CanvasTinter.convertTintToImage) + { // is this better? var tintImage = new Image(); tintImage.src = canvas.toDataURL(); texture.tintCache[stringColor] = tintImage; } - else { + else + { texture.tintCache[stringColor] = canvas; // if we are not converting the texture to an image then we need to lose the reference to the canvas CanvasTinter.canvas = null; @@ -56,7 +60,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithMultiply = function (texture, color, canvas) { +CanvasTinter.tintWithMultiply = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -104,7 +109,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithOverlay = function (texture, color, canvas) { +CanvasTinter.tintWithOverlay = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -139,7 +145,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithPerPixel = function (texture, color, canvas) { +CanvasTinter.tintWithPerPixel = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -167,7 +174,8 @@ var pixels = pixelData.data; - for (var i = 0; i < pixels.length; i += 4) { + for (var i = 0; i < pixels.length; i += 4) + { pixels[i+0] *= r; pixels[i+1] *= g; pixels[i+2] *= b; @@ -181,7 +189,8 @@ * * @param color {number} the color to round, should be a hex color */ -CanvasTinter.roundColor = function (color) { +CanvasTinter.roundColor = function (color) +{ var step = CanvasTinter.cacheStepsPerColorChannel; var rgbValues = utils.hex2rgb(color); diff --git a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js index 9f2f89a..35edbaf 100644 --- a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js +++ b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLBlendModeManager(renderer) { +function WebGLBlendModeManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -23,8 +24,10 @@ * * @param blendMode {number} the blendMode, should be a Pixi const, such as BlendModes.ADD */ -WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) { - if (this.currentBlendMode === blendMode) { +WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) +{ + if (this.currentBlendMode === blendMode) + { return false; } diff --git a/src/core/renderers/webgl/managers/WebGLFilterManager.js b/src/core/renderers/webgl/managers/WebGLFilterManager.js index 1179258..2dac048 100644 --- a/src/core/renderers/webgl/managers/WebGLFilterManager.js +++ b/src/core/renderers/webgl/managers/WebGLFilterManager.js @@ -7,7 +7,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLFilterManager(renderer) { +function WebGLFilterManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -32,7 +33,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.texturePool.length = 0; self.initShaderBuffers(); }); @@ -46,7 +48,8 @@ * @param renderer {WebGLRenderer} * @param buffer {ArrayBuffer} */ -WebGLFilterManager.prototype.begin = function (buffer) { +WebGLFilterManager.prototype.begin = function (buffer) +{ this.defaultShader = this.renderer.shaderManager.defaultShader; this.width = this.renderer.projection.x * 2; @@ -60,7 +63,8 @@ * * @param filterBlock {object} the filter that will be pushed to the current filter stack */ -WebGLFilterManager.prototype.pushFilter = function (filterBlock) { +WebGLFilterManager.prototype.pushFilter = function (filterBlock) +{ var gl = this.renderer.gl; var projection = this.renderer.projection; @@ -78,10 +82,12 @@ this.offsetY += filterBlock._filterArea.y; var texture = this.texturePool.pop(); - if (!texture) { + if (!texture) + { texture = new FilterTexture(this.renderer.gl, this.width, this.height); } - else { + else + { texture.resize(this.width, this.height); } @@ -98,29 +104,35 @@ var localX = filterArea.x, localY = filterArea.y; - if (filterArea.x < 0) { + if (filterArea.x < 0) + { filterArea.width += filterArea.x; filterArea.x = 0; } - if (filterArea.y < 0) { + if (filterArea.y < 0) + { filterArea.height += filterArea.y; filterArea.y = 0; } - if (localX + filterArea.width > this.width) { + if (localX + filterArea.width > this.width) + { filterArea.width = this.width - localX; } - if (localY + filterArea.height > this.height) { + if (localY + filterArea.height > this.height) + { filterArea.height = this.height - localY; } - if (filterArea.width < 0) { + if (filterArea.width < 0) + { filterArea.width = 0; } - if (filterArea.height < 0) { + if (filterArea.height < 0) + { filterArea.height = 0; } @@ -154,7 +166,8 @@ * Removes the last filter from the filter stack and doesn't return it. * */ -WebGLFilterManager.prototype.popFilter = function () { +WebGLFilterManager.prototype.popFilter = function () +{ var gl = this.renderer.gl; var filterBlock = this.filterStack.pop(); @@ -163,7 +176,8 @@ var projection = this.renderer.projection; var offset = this.renderer.offset; - if (filterBlock.filterPasses.length > 1) { + if (filterBlock.filterPasses.length > 1) + { gl.viewport(0, 0, filterArea.width, filterArea.height); gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); @@ -193,7 +207,8 @@ var inputTexture = texture; var outputTexture = this.texturePool.pop(); - if (!outputTexture) { + if (!outputTexture) + { outputTexture = new FilterTexture(this.renderer.gl, this.width, this.height); } outputTexture.resize(this.width, this.height); @@ -204,7 +219,8 @@ gl.disable(gl.BLEND); - for (var i = 0; i < filterBlock.filterPasses.length-1; i++) { + for (var i = 0; i < filterBlock.filterPasses.length-1; i++) + { var filterPass = filterBlock.filterPasses[i]; gl.bindFramebuffer(gl.FRAMEBUFFER, outputTexture.frameBuffer ); @@ -243,10 +259,12 @@ var buffer = this.buffer; // time to render the filters texture to the previous scene - if (this.filterStack.length === 0) { + if (this.filterStack.length === 0) + { gl.colorMask(true, true, true, true);//this.transparent); } - else { + else + { var currentFilter = this.filterStack[this.filterStack.length-1]; filterArea = currentFilter._filterArea; @@ -332,13 +350,15 @@ * @param width {number} the horizontal range of the filter * @param height {number} the vertical range of the filter */ -WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) { +WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) +{ // use program var gl = this.renderer.gl; var shader = filter.shaders[gl.id]; - if (!shader) { + if (!shader) + { shader = new Shader(gl); shader.fragmentSrc = filter.fragmentSrc; @@ -356,7 +376,8 @@ gl.uniform2f(shader.projectionVector, width/2, -height/2); gl.uniform2f(shader.offsetVector, 0,0); - if (filter.uniforms.dimensions) { + 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]; @@ -386,7 +407,8 @@ * Initialises the shader buffers. * */ -WebGLFilterManager.prototype.initShaderBuffers = function () { +WebGLFilterManager.prototype.initShaderBuffers = function () +{ var gl = this.renderer.gl; // create some buffers @@ -432,7 +454,8 @@ * Destroys the filter and removes it from the filter stack. * */ -WebGLFilterManager.prototype.destroy = function () { +WebGLFilterManager.prototype.destroy = function () +{ var gl = this.renderer.gl; this.filterStack = null; @@ -441,7 +464,8 @@ this.offsetY = 0; // destroy textures - for (var i = 0; i < this.texturePool.length; i++) { + for (var i = 0; i < this.texturePool.length; i++) + { this.texturePool[i].destroy(); } diff --git a/src/core/renderers/webgl/managers/WebGLManager.js b/src/core/renderers/webgl/managers/WebGLManager.js index 9d47b5c..c30cd51 100644 --- a/src/core/renderers/webgl/managers/WebGLManager.js +++ b/src/core/renderers/webgl/managers/WebGLManager.js @@ -3,7 +3,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLManager(renderer) { +function WebGLManager(renderer) +{ /** * The renderer this manager works for. * @@ -15,6 +16,7 @@ WebGLManager.prototype.constructor = WebGLManager; module.exports = WebGLManager; -WebGLManager.prototype.destroy = function () { +WebGLManager.prototype.destroy = function () +{ this.renderer = null; }; diff --git a/src/core/renderers/webgl/managers/WebGLMaskManager.js b/src/core/renderers/webgl/managers/WebGLMaskManager.js index 2f90b64..e568812 100644 --- a/src/core/renderers/webgl/managers/WebGLMaskManager.js +++ b/src/core/renderers/webgl/managers/WebGLMaskManager.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLMaskManager(renderer) { +function WebGLMaskManager(renderer) +{ WebGLManager.call(this, renderer); } @@ -19,12 +20,15 @@ * * @param maskData {any[]} */ -WebGLMaskManager.prototype.pushMask = function (maskData) { - if (maskData.dirty) { +WebGLMaskManager.prototype.pushMask = function (maskData) +{ + if (maskData.dirty) + { WebGLGraphics.updateGraphics(maskData, this.renderer.gl); } - if (!maskData._webGL[this.renderer.gl.id].data.length) { + if (!maskData._webGL[this.renderer.gl.id].data.length) + { return; } @@ -36,6 +40,7 @@ * * @param maskData {any[]} */ -WebGLMaskManager.prototype.popMask = function (maskData) { +WebGLMaskManager.prototype.popMask = function (maskData) +{ this.renderer.stencilManager.popStencil(maskData, maskData._webGL[this.renderer.gl.id].data[0], this.renderer); }; diff --git a/src/core/renderers/webgl/managers/WebGLShaderManager.js b/src/core/renderers/webgl/managers/WebGLShaderManager.js index fef071c..90c6477 100644 --- a/src/core/renderers/webgl/managers/WebGLShaderManager.js +++ b/src/core/renderers/webgl/managers/WebGLShaderManager.js @@ -10,7 +10,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLShaderManager(renderer) { +function WebGLShaderManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -28,7 +29,8 @@ */ this.tempAttribState = []; - for (var i = 0; i < this.maxAttibs; i++) { + for (var i = 0; i < this.maxAttibs; i++) + { this.attribState[i] = false; } @@ -66,7 +68,8 @@ // listen for context and update necessary shaders var self = this; - this.renderer.on('context', function (event) { + this.renderer.on('context', function (event) + { var gl = event.data; // this shader is used for rendering primitives @@ -97,29 +100,36 @@ * * @param attribs {Array} attribs */ -WebGLShaderManager.prototype.setAttribs = function (attribs) { +WebGLShaderManager.prototype.setAttribs = function (attribs) +{ // reset temp state var i; - for (i = 0; i < this.tempAttribState.length; i++) { + for (i = 0; i < this.tempAttribState.length; i++) + { this.tempAttribState[i] = false; } // set the new attribs - for (var a in attribs) { + for (var a in attribs) + { this.tempAttribState[attribs[a]] = true; } var gl = this.renderer.gl; - for (i = 0; i < this.attribState.length; i++) { - if (this.attribState[i] !== this.tempAttribState[i]) { + for (i = 0; i < this.attribState.length; i++) + { + if (this.attribState[i] !== this.tempAttribState[i]) + { this.attribState[i] = this.tempAttribState[i]; - if (this.attribState[i]) { + if (this.attribState[i]) + { gl.enableVertexAttribArray(i); } - else { + else + { gl.disableVertexAttribArray(i); } } @@ -131,8 +141,10 @@ * * @param shader {Any} */ -WebGLShaderManager.prototype.setShader = function (shader) { - if (this._currentId === shader.uuid) { +WebGLShaderManager.prototype.setShader = function (shader) +{ + if (this._currentId === shader.uuid) + { return false; } @@ -150,7 +162,8 @@ * Destroys this object. * */ -WebGLShaderManager.prototype.destroy = function () { +WebGLShaderManager.prototype.destroy = function () +{ this.attribState = null; this.tempAttribState = null; diff --git a/src/core/renderers/webgl/managers/WebGLStencilManager.js b/src/core/renderers/webgl/managers/WebGLStencilManager.js index 9ec6398..4cb0134 100644 --- a/src/core/renderers/webgl/managers/WebGLStencilManager.js +++ b/src/core/renderers/webgl/managers/WebGLStencilManager.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLStencilManager(renderer) { +function WebGLStencilManager(renderer) +{ WebGLManager.call(this, renderer); this.stencilStack = []; @@ -24,12 +25,14 @@ * @param graphics {Graphics} * @param webGLData {any[]} */ -WebGLStencilManager.prototype.pushStencil = function (graphics, webGLData) { +WebGLStencilManager.prototype.pushStencil = function (graphics, webGLData) +{ var gl = this.renderer.gl; this.bindGraphics(graphics, webGLData, this.renderer); - if (this.stencilStack.length === 0) { + if (this.stencilStack.length === 0) + { gl.enable(gl.STENCIL_TEST); gl.clear(gl.STENCIL_BUFFER_BIT); this.reverse = true; @@ -47,14 +50,17 @@ // draw the triangle strip! - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } @@ -62,31 +68,38 @@ // draw a quad to increment.. gl.drawElements(gl.TRIANGLE_FAN, 4, gl.UNSIGNED_SHORT, ( webGLData.indices.length - 4 ) * 2 ); - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); } this.reverse = !this.reverse; } - else { - if (!this.reverse) { + else + { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } - else { + 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) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); } } @@ -103,7 +116,8 @@ * @param graphics {Graphics} * @param webGLData {Array} */ -WebGLStencilManager.prototype.bindGraphics = function (graphics, webGLData) { +WebGLStencilManager.prototype.bindGraphics = function (graphics, webGLData) +{ //if (this._currentGraphics === graphics)return; this._currentGraphics = graphics; @@ -114,7 +128,8 @@ offset = this.renderer.offset, shader;// = this.renderer.shaderManager.primitiveShader; - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { shader = this.renderer.shaderManager.complexPrimitiveShader; this.renderer.shaderManager.setShader(shader); @@ -141,7 +156,8 @@ // set the index buffer! gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, webGLData.indexBuffer); } - else { + else + { //this.renderer.shaderManager.activatePrimitiveShader(); shader = this.renderer.shaderManager.primitiveShader; this.renderer.shaderManager.setShader( shader ); @@ -154,7 +170,7 @@ gl.uniform2f(shader.uniforms.offsetVector._location, -offset.x, -offset.y); gl.uniform3fv(shader.uniforms.tint._location, utils.hex2rgb(graphics.tint)); - + gl.uniform1f(shader.uniforms.alpha._location, graphics.worldAlpha); @@ -172,19 +188,22 @@ * @param graphics {Graphics} * @param webGLData {Array} */ -WebGLStencilManager.prototype.popStencil = function (graphics, webGLData) { +WebGLStencilManager.prototype.popStencil = function (graphics, webGLData) +{ var gl = this.renderer.gl; this.stencilStack.pop(); this.count--; - if (this.stencilStack.length === 0) { + if (this.stencilStack.length === 0) + { // the stack is empty! gl.disable(gl.STENCIL_TEST); } - else { + else + { var level = this.count; @@ -192,14 +211,17 @@ gl.colorMask(false, false, false, false); - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { this.reverse = !this.reverse; - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } @@ -213,31 +235,38 @@ // draw the triangle strip! gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); - if (!this.reverse) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); } } - else { + else + { // console.log("<<>>") - if (!this.reverse) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } - else { + 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) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); } } @@ -253,7 +282,8 @@ * Destroys the mask stack. * */ -WebGLStencilManager.prototype.destroy = function () { +WebGLStencilManager.prototype.destroy = function () +{ this.renderer = null; this.stencilStack = null; }; diff --git a/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js b/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js index 913ba5e..1ea7d19 100644 --- a/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js +++ b/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function ComplexPrimitiveShader(gl) { +function ComplexPrimitiveShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -24,7 +25,8 @@ 'uniform float flipY;', 'varying vec4 vColor;', - 'void main(void) {', + '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);', @@ -37,7 +39,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = vColor;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/FastShader.js b/src/core/renderers/webgl/shaders/FastShader.js index bd2e29a..2e5e060 100644 --- a/src/core/renderers/webgl/shaders/FastShader.js +++ b/src/core/renderers/webgl/shaders/FastShader.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function FastShader(gl) { +function FastShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -28,7 +29,8 @@ 'const vec2 center = vec2(-1.0, 1.0);', - 'void main(void) {', + 'void main(void) + {', ' vec2 v;', ' vec2 sv = aVertexPosition * aScale;', ' v.x = (sv.x) * cos(aRotation) - (sv.y) * sin(aRotation);', @@ -49,7 +51,8 @@ 'uniform sampler2D uSampler;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/PrimitiveShader.js b/src/core/renderers/webgl/shaders/PrimitiveShader.js index 6f25409..a25f54f 100644 --- a/src/core/renderers/webgl/shaders/PrimitiveShader.js +++ b/src/core/renderers/webgl/shaders/PrimitiveShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function PrimitiveShader(gl) { +function PrimitiveShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -23,7 +24,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + '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);', @@ -36,7 +38,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = vColor;', '}' ].join('\n'), diff --git a/src/core/display/DisplayObject.js b/src/core/display/DisplayObject.js index 66ebc3c..20e778c 100644 --- a/src/core/display/DisplayObject.js +++ b/src/core/display/DisplayObject.js @@ -7,7 +7,8 @@ * @class * @namespace PIXI */ -function DisplayObject() { +function DisplayObject() +{ /** * The coordinate of the object relative to the local coordinates of the parent. * @@ -152,10 +153,12 @@ * @memberof DisplayObject# */ x: { - get: function () { + get: function () + { return this.position.x; }, - set: function (value) { + set: function (value) + { this.position.x = value; } }, @@ -167,10 +170,12 @@ * @memberof DisplayObject# */ y: { - get: function () { + get: function () + { return this.position.y; }, - set: function (value) { + set: function (value) + { this.position.y = value; } }, @@ -183,11 +188,13 @@ * @readonly */ worldVisible: { - get: function () { + get: function () + { var item = this; do { - if (!item.visible) { + if (!item.visible) + { return false; } @@ -207,17 +214,21 @@ * @memberof DisplayObject# */ mask: { - get: function () { + get: function () + { return this._mask; }, - set: function (value) { - if (this._mask) { + set: function (value) + { + if (this._mask) + { this._mask.isMask = false; } this._mask = value; - if (this._mask) { + if (this._mask) + { this._mask.isMask = true; } } @@ -232,18 +243,23 @@ * @memberof DisplayObject# */ filters: { - get: function () { + get: function () + { return this._filters; }, - set: function (value) { - if (value) { + set: function (value) + { + if (value) + { // now put all the passes in one place.. var passes = []; - for (var i = 0; i < value.length; i++) { + for (var i = 0; i < value.length; i++) + { var filterPasses = value[i].passes; - for (var j = 0; j < filterPasses.length; j++) { + for (var j = 0; j < filterPasses.length; j++) + { passes.push(filterPasses[j]); } } @@ -264,8 +280,9 @@ * * @private */ -DisplayObject.prototype.updateTransform = function () { - +DisplayObject.prototype.updateTransform = function () +{ + // create some matrix refs for easy access var pt = this.parent.worldTransform; var wt = this.worldTransform; @@ -274,9 +291,11 @@ var a, b, c, d, tx, ty; // so if rotation is between 0 then we can simplify the multiplication process.. - if (this.rotation % math.PI_2) { + if (this.rotation % math.PI_2) + { // 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) { + if (this.rotation !== this.rotationCache) + { this.rotationCache = this.rotation; this._sr = Math.sin(this.rotation); this._cr = Math.cos(this.rotation); @@ -291,7 +310,8 @@ ty = this.position.y; // check for pivot.. not often used so geared towards that fact! - if (this.pivot.x || this.pivot.y) { + 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; } @@ -304,7 +324,8 @@ wt.tx = tx * pt.a + ty * pt.c + pt.tx; wt.ty = tx * pt.b + ty * pt.d + pt.ty; } - else { + else + { // lets do the fast version as we know there is no rotation.. a = this.scale.x; d = this.scale.y; @@ -333,7 +354,8 @@ * @param matrix {Matrix} * @return {Rectangle} the rectangular bounding area */ -DisplayObject.prototype.getBounds = function (/* matrix */) { +DisplayObject.prototype.getBounds = function (/* matrix */) +{ return math.Rectangle.EMPTY; }; @@ -342,7 +364,8 @@ * * @return {Rectangle} the rectangular bounding area */ -DisplayObject.prototype.getLocalBounds = function () { +DisplayObject.prototype.getLocalBounds = function () +{ return this.getBounds(math.Matrix.IDENTITY); }; @@ -352,7 +375,8 @@ * @param position {Point} The world origin to calculate from * @return {Point} A point object representing the position of this object */ -DisplayObject.prototype.toGlobal = function (position) { +DisplayObject.prototype.toGlobal = function (position) +{ // don't need to u[date the lot this.displayObjectUpdateTransform(); return this.worldTransform.apply(position); @@ -365,8 +389,10 @@ * @param [from] {DisplayObject} The DisplayObject to calculate the global position from * @return {Point} A point object representing the position of this object */ -DisplayObject.prototype.toLocal = function (position, from) { - if (from) { +DisplayObject.prototype.toLocal = function (position, from) +{ + if (from) + { position = from.toGlobal(position); } @@ -381,7 +407,8 @@ * @param renderer {WebGLRenderer} The renderer * @private */ -DisplayObject.prototype.renderWebGL = function (/* renderer */) { +DisplayObject.prototype.renderWebGL = function (/* renderer */) +{ // OVERWRITE; }; @@ -391,6 +418,7 @@ * @param renderer {CanvasRenderer} The renderer * @private */ -DisplayObject.prototype.renderCanvas = function (/* renderer */) { +DisplayObject.prototype.renderCanvas = function (/* renderer */) +{ // OVERWRITE; }; diff --git a/src/core/display/DisplayObjectContainer.js b/src/core/display/DisplayObjectContainer.js index 689f40b..4625ee8 100644 --- a/src/core/display/DisplayObjectContainer.js +++ b/src/core/display/DisplayObjectContainer.js @@ -12,7 +12,8 @@ * @extends DisplayObject * @namespace PIXI */ -function DisplayObjectContainer() { +function DisplayObjectContainer() +{ DisplayObject.call(this); /** @@ -47,17 +48,21 @@ * @memberof DisplayObjectContainer# */ width: { - get: function () { + get: function () + { return this.scale.x * this.getLocalBounds().width; }, - set: function (value) { + set: function (value) + { var width = this.getLocalBounds().width; - if(width !== 0) { + if(width !== 0) + { this.scale.x = value / width; } - else { + else + { this.scale.x = 1; } @@ -73,17 +78,21 @@ * @memberof DisplayObjectContainer# */ height: { - get: function () { + get: function () + { return this.scale.y * this.getLocalBounds().height; }, - set: function (value) { + set: function (value) + { var height = this.getLocalBounds().height; - if (height !== 0) { + if (height !== 0) + { this.scale.y = value / height ; } - else { + else + { this.scale.y = 1; } @@ -100,18 +109,23 @@ * @memberof DisplayObject# */ cacheAsBitmap: { - get: function () { + get: function () + { return this._cacheAsBitmap; }, - set: function (value) { - if (this._cacheAsBitmap === value) { + set: function (value) + { + if (this._cacheAsBitmap === value) + { return; } - if (value) { + if (value) + { this._generateCachedSprite(); } - else { + else + { this._destroyCachedSprite(); } @@ -126,7 +140,8 @@ * @param child {DisplayObject} The DisplayObject to add to the container * @return {DisplayObject} The child that was added. */ -DisplayObjectContainer.prototype.addChild = function (child) { +DisplayObjectContainer.prototype.addChild = function (child) +{ return this.addChildAt(child, this.children.length); }; @@ -137,14 +152,18 @@ * @param index {Number} The index to place the child in * @return {DisplayObject} The child that was added. */ -DisplayObjectContainer.prototype.addChildAt = function (child, index) { +DisplayObjectContainer.prototype.addChildAt = function (child, index) +{ // prevent adding self as child - if (child === this) { + if (child === this) + { return; } - if (index >= 0 && index <= this.children.length) { - if (child.parent) { + if (index >= 0 && index <= this.children.length) + { + if (child.parent) + { child.parent.removeChild(child); } @@ -154,7 +173,8 @@ return child; } - else { + else + { throw new Error(child + 'addChildAt: The index '+ index +' supplied is out of bounds ' + this.children.length); } }; @@ -165,15 +185,18 @@ * @param child {DisplayObject} * @param child2 {DisplayObject} */ -DisplayObjectContainer.prototype.swapChildren = function (child, child2) { - if (child === child2) { +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) { + if (index1 < 0 || index2 < 0) + { throw new Error('swapChildren: Both the supplied DisplayObjects must be a child of the caller.'); } @@ -187,10 +210,12 @@ * @param child {DisplayObject} The DisplayObject instance to identify * @return {Number} The index position of the child display object to identify */ -DisplayObjectContainer.prototype.getChildIndex = function (child) { +DisplayObjectContainer.prototype.getChildIndex = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { throw new Error('The supplied DisplayObject must be a child of the caller'); } @@ -203,8 +228,10 @@ * @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 */ -DisplayObjectContainer.prototype.setChildIndex = function (child, index) { - if (index < 0 || index >= this.children.length) { +DisplayObjectContainer.prototype.setChildIndex = function (child, index) +{ + if (index < 0 || index >= this.children.length) + { throw new Error('The supplied index is out of bounds'); } @@ -220,8 +247,10 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child at the given index, if any. */ -DisplayObjectContainer.prototype.getChildAt = function (index) { - if (index < 0 || index >= this.children.length) { +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'); } @@ -234,10 +263,12 @@ * @param child {DisplayObject} The DisplayObject to remove * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChild = function (child) { +DisplayObjectContainer.prototype.removeChild = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { return; } @@ -250,7 +281,8 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChildAt = function (index) { +DisplayObjectContainer.prototype.removeChildAt = function (index) +{ var child = this.getChildAt(index); child.parent = null; @@ -265,24 +297,29 @@ * @param beginIndex {Number} The beginning position. Default value is 0. * @param endIndex {Number} The ending position. Default value is size of the container. */ -DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) { +DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) +{ var begin = beginIndex || 0; var end = typeof endIndex === 'number' ? endIndex : this.children.length; var range = end - begin; - if (range > 0 && range <= end) { + if (range > 0 && range <= end) + { var removed = this.children.splice(begin, range); - for (var i = 0; i < removed.length; ++i) { + for (var i = 0; i < removed.length; ++i) + { removed[i].parent = null; } return removed; } - else if (range === 0 && this.children.length === 0) { + else if (range === 0 && this.children.length === 0) + { return []; } - else { + else + { throw new RangeError('removeChildren: numeric values are outside the acceptable range.'); } }; @@ -291,7 +328,8 @@ * Generates and updates the cached sprite for this object. * */ -DisplayObjectContainer.prototype.updateCachedSprite = function () { +DisplayObjectContainer.prototype.updateCachedSprite = function () +{ this._generateCachedSprite(); }; @@ -304,7 +342,8 @@ * @param renderer {CanvasRenderer|WebGLRenderer} The renderer used to generate the texture. * @return {Texture} a texture of the graphics object */ -DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) { +DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) +{ var bounds = this.getLocalBounds(); var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0, renderer, scaleMode, resolution); @@ -322,18 +361,22 @@ * * @private */ -DisplayObjectContainer.prototype.updateTransform = function () { - if (!this.visible) { +DisplayObjectContainer.prototype.updateTransform = function () +{ + if (!this.visible) + { return; } this.displayObjectUpdateTransform(); - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { return; } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } }; @@ -346,8 +389,10 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getBounds = function () { - if (this.children.length === 0) { +DisplayObjectContainer.prototype.getBounds = function () +{ + if (this.children.length === 0) + { return math.Rectangle.EMPTY; } @@ -365,10 +410,12 @@ var childVisible = false; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -386,7 +433,8 @@ maxY = maxY > childMaxY ? maxY : childMaxY; } - if (!childVisible) { + if (!childVisible) + { return math.Rectangle.EMPTY; } @@ -407,12 +455,14 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getLocalBounds = function () { +DisplayObjectContainer.prototype.getLocalBounds = function () +{ var matrixCache = this.worldTransform; this.worldTransform = math.Matrix.IDENTITY; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } @@ -428,13 +478,16 @@ * * @param renderer {WebGLRenderer} The renderer */ -DisplayObjectContainer.prototype.renderWebGL = function (renderer) { +DisplayObjectContainer.prototype.renderWebGL = function (renderer) +{ // if the object is not visible or the alpha is 0 then no need to render this element - if (!this.visible || this.alpha <= 0) { + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } @@ -442,14 +495,17 @@ var i, j; // do a quick check to see if this element has a mask or a filter. - if (this._mask || this._filters) { + if (this._mask || this._filters) + { // push filter first as we need to ensure the stencil buffer is correct for any masking - if (this._filters) { + if (this._filters) + { renderer.spriteBatch.flush(); renderer.filterManager.pushFilter(this._filterBlock); } - if (this._mask) { + if (this._mask) + { renderer.spriteBatch.stop(); renderer.maskManager.pushMask(this.mask, renderer); renderer.spriteBatch.start(); @@ -459,36 +515,42 @@ this._renderWebGL(renderer); // now loop through the children and make sure they get rendered - for (i = 0, j = this.children.length; i < j; i++) { + for (i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderWebGL(renderer); } // time to stop the sprite batch as either a mask element or a filter draw will happen next renderer.spriteBatch.stop(); - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(this._mask, renderer); } - if (this._filters) { + if (this._filters) + { renderer.filterManager.popFilter(); } renderer.spriteBatch.start(); } - else { + else + { this._renderWebGL(renderer); // simple render children! - for (i = 0, j = this.children.length; i < j; ++i) { + for (i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderWebGL(renderer); } } }; -DisplayObjectContainer.prototype._renderWebGL = function (renderer) { +DisplayObjectContainer.prototype._renderWebGL = function (renderer) +{ // this is where content itself gets renderd.. @@ -499,25 +561,31 @@ * * @param renderer {CanvasRenderer} The renderer */ -DisplayObjectContainer.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0) { +DisplayObjectContainer.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -528,13 +596,16 @@ * @param renderer {WebGLRenderer|CanvasRenderer} The renderer * @private */ -DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) { +DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) +{ this._cachedSprite.worldAlpha = this.worldAlpha; - if (renderer.gl) { + if (renderer.gl) + { this._cachedSprite.renderWebGL(renderer); } - else { + else + { this._cachedSprite.renderCanvas(renderer); } }; @@ -544,10 +615,12 @@ * * @private */ -DisplayObjectContainer.prototype._generateCachedSprite = function () { +DisplayObjectContainer.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { // TODO - RenderTexture now *requires* a renderer instance, so this is like broken // because `renderer` isn't actually in scope here :P var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0); @@ -555,7 +628,8 @@ this._cachedSprite = new Sprite(renderTexture); this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.texture.resize(bounds.width | 0, bounds.height | 0); } @@ -580,8 +654,10 @@ * * @private */ -DisplayObjectContainer.prototype._destroyCachedSprite = function () { - if (!this._cachedSprite) { +DisplayObjectContainer.prototype._destroyCachedSprite = function () +{ + if (!this._cachedSprite) + { return; } diff --git a/src/core/display/Sprite.js b/src/core/display/Sprite.js index 707da24..5862aef 100644 --- a/src/core/display/Sprite.js +++ b/src/core/display/Sprite.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param texture {Texture} The texture for this sprite */ -function Sprite(texture) { +function Sprite(texture) +{ DisplayObjectContainer.call(this); /** @@ -85,12 +86,14 @@ this.texture = texture || Texture.EMPTY; } -Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) { +Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) +{ DisplayObjectContainer.prototype.destroy.call(this); this.anchor = null; - if (destroyTexture) { + if (destroyTexture) + { this._texture.destroy(destroyBaseTexture); } @@ -111,10 +114,12 @@ * @memberof Sprite# */ width: { - get: function () { + get: function () + { return this.scale.x * this.texture.frame.width; }, - set: function (value) { + set: function (value) + { this.scale.x = value / this.texture.frame.width; this._width = value; } @@ -127,10 +132,12 @@ * @memberof Sprite# */ height: { - get: function () { + get: function () + { return this.scale.y * this.texture.frame.height; }, - set: function (value) { + set: function (value) + { this.scale.y = value / this.texture.frame.height; this._height = value; } @@ -143,23 +150,29 @@ * @memberof Sprite# */ texture: { - get: function () { + get: function () + { return this._texture; }, - set: function (value) { - if (this._texture === value) { + set: function (value) + { + if (this._texture === value) + { return; } this._texture = value; this.cachedTint = 0xFFFFFF; - if (value) { + if (value) + { // wait for the texture to load - if (value.baseTexture.hasLoaded) { + if (value.baseTexture.hasLoaded) + { this._onTextureUpdate(); } - else { + else + { value.once('update', this._onTextureUpdate.bind(this)); } } @@ -172,18 +185,22 @@ * * @private */ -Sprite.prototype._onTextureUpdate = function () { +Sprite.prototype._onTextureUpdate = function () +{ // so if _width is 0 then width was not set.. - if (this._width) { + if (this._width) + { this.scale.x = this._width / this.texture.frame.width; } - if (this._height) { + if (this._height) + { this.scale.y = this._height / this.texture.frame.height; } }; -Sprite.prototype._renderWebGL = function (renderer) { +Sprite.prototype._renderWebGL = function (renderer) +{ // this is where content gets renderd.. // watch this space for a little render state manager.. @@ -197,7 +214,8 @@ * @param matrix {Matrix} the transformation matrix of the sprite * @return {Rectangle} the framing rectangle */ -Sprite.prototype.getBounds = function (matrix) { +Sprite.prototype.getBounds = function (matrix) +{ var width = this.texture.frame.width; var height = this.texture.frame.height; @@ -224,11 +242,13 @@ if(b === 0 && c === 0) { // scale may be negative! - if (a < 0) { + if (a < 0) + { a *= -1; } - if (d < 0) { + if (d < 0) + { d *= -1; } @@ -293,28 +313,34 @@ * * @param renderer {CanvasRenderer} The renderer */ -Sprite.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) { +Sprite.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) + { return; } - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; renderer.context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } // Ignore null sources - if (this.texture.valid) { + if (this.texture.valid) + { var resolution = this.texture.baseTexture.resolution / renderer.resolution; renderer.context.globalAlpha = this.worldAlpha; // If smoothingEnabled is supported and we need to change the smoothing property for this texture - if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) { + if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) + { renderer.scaleMode = this.texture.baseTexture.scaleMode; renderer.context[renderer.smoothProperty] = (renderer.scaleMode === CONST.scaleModes.LINEAR); } @@ -324,7 +350,8 @@ var dy = (this.texture.trim ? this.texture.trim.y : 0) - (this.anchor.y * this.texture.trim.height); // Allow for pixel rounding - if (renderer.roundPixels) { + if (renderer.roundPixels) + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -337,7 +364,8 @@ dx = dx | 0; dy = dy | 0; } - else { + else + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -348,8 +376,10 @@ ); } - if (this.tint !== 0xFFFFFF) { - if (this.cachedTint !== this.tint) { + if (this.tint !== 0xFFFFFF) + { + if (this.cachedTint !== this.tint) + { this.cachedTint = this.tint; // TODO clean up caching - how to clean up the caches? @@ -368,7 +398,8 @@ this.texture.crop.height / resolution ); } - else { + else + { renderer.context.drawImage( this.texture.baseTexture.source, this.texture.crop.x, @@ -383,11 +414,13 @@ } } - for (var i = 0, j = this.children.length; i < j; i++) { + for (var i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -402,10 +435,12 @@ * @param frameId {String} The frame Id of the texture in the cache * @return {Sprite} A new Sprite using a texture from the texture cache matching the frameId */ -Sprite.fromFrame = function (frameId) { +Sprite.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache' + this); } @@ -420,6 +455,7 @@ * @param imageId {String} The image url of the texture * @return {Sprite} A new Sprite using a texture from the texture cache matching the image id */ -Sprite.fromImage = function (imageId, crossorigin, scaleMode) { +Sprite.fromImage = function (imageId, crossorigin, scaleMode) +{ return new Sprite(Texture.fromImage(imageId, crossorigin, scaleMode)); }; diff --git a/src/core/display/SpriteBatch.js b/src/core/display/SpriteBatch.js index 3187777..c196fef 100644 --- a/src/core/display/SpriteBatch.js +++ b/src/core/display/SpriteBatch.js @@ -12,7 +12,8 @@ * ```js * var container = new SpriteBatch(); * - * for(var i = 0; i < 100; ++i) { + * for(var i = 0; i < 100; ++i) + * { * var sprite = new PIXI.Sprite.fromImage("myImage.png"); * container.addChild(sprite); * } @@ -25,7 +26,8 @@ */ //TODO RENAME to PARTICLE CONTAINER? -function SpriteBatch() { +function SpriteBatch() +{ DisplayObjectContainer.call(this); } @@ -38,7 +40,8 @@ * * @private */ -SpriteBatch.prototype.updateTransform = function () { +SpriteBatch.prototype.updateTransform = function () +{ // TODO don't need to! this.displayObjectUpdateTransform(); // PIXI.DisplayObjectContainer.prototype.updateTransform.call( this ); @@ -50,8 +53,10 @@ * @param renderer {WebGLRenderer} The webgl renderer * @private */ -SpriteBatch.prototype.renderWebGL = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderWebGL = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -71,8 +76,10 @@ * @param renderer {CanvasRenderer} The canvas renderer * @private */ -SpriteBatch.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -84,10 +91,12 @@ this.displayObjectUpdateTransform(); - for (var i = 0; i < this.children.length; ++i) { + for (var i = 0; i < this.children.length; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -95,9 +104,11 @@ context.globalAlpha = this.worldAlpha * child.alpha; - if (child.rotation % (Math.PI * 2) === 0) { + if (child.rotation % (Math.PI * 2) === 0) + { // this is the fastest way to optimise! - if rotation is 0 then we can avoid any kind of setTransform call - if (isRotated) { + if (isRotated) + { context.setTransform( transform.a, transform.b, @@ -122,8 +133,10 @@ frame.height * child.scale.y ); } - else { - if (!isRotated) { + else + { + if (!isRotated) + { isRotated = true; } @@ -131,7 +144,8 @@ var childTransform = child.worldTransform; - if (renderer.roundPixels) { + if (renderer.roundPixels) + { context.setTransform( childTransform.a, childTransform.b, @@ -141,7 +155,8 @@ childTransform.ty | 0 ); } - else { + else + { context.setTransform( childTransform.a, childTransform.b, diff --git a/src/core/index.js b/src/core/index.js index 3954b6f..eb4a82b 100644 --- a/src/core/index.js +++ b/src/core/index.js @@ -58,11 +58,13 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRenderer: function (width, height, options, noWebGL) { + autoDetectRenderer: function (width, height, options, noWebGL) + { width = width || 800; height = height || 600; - if (!noWebGL && require('webgl-enabled')()) { + if (!noWebGL && require('webgl-enabled')()) + { return new core.WebGLRenderer(width, height, options); } @@ -87,7 +89,8 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRecommendedRenderer: function (width, height, options) { + autoDetectRecommendedRenderer: function (width, height, options) + { var isAndroid = /Android/i.test(navigator.userAgent); return core.autoDetectRenderer(width, height, options, isAndroid); diff --git a/src/core/math/Matrix.js b/src/core/math/Matrix.js index c2f87e2..2ff4848 100644 --- a/src/core/math/Matrix.js +++ b/src/core/math/Matrix.js @@ -10,7 +10,8 @@ * @class * @namespace PIXI */ -function Matrix() { +function Matrix() +{ /** * @member {number} * @default 1 @@ -63,7 +64,8 @@ * * @param array {number[]} The array that the matrix will be populated from. */ -Matrix.prototype.fromArray = function (array) { +Matrix.prototype.fromArray = function (array) +{ this.a = array[0]; this.b = array[1]; this.c = array[3]; @@ -78,14 +80,17 @@ * @param transpose {boolean} Whether we need to transpose the matrix or not * @return {number[]} the newly created array which contains the matrix */ -Matrix.prototype.toArray = function (transpose) { - if (!this.array) { +Matrix.prototype.toArray = function (transpose) +{ + if (!this.array) + { this.array = new Float32Array(9); } var array = this.array; - if (transpose) { + if (transpose) + { array[0] = this.a; array[1] = this.b; array[2] = 0; @@ -96,7 +101,8 @@ array[7] = this.ty; array[8] = 1; } - else { + else + { array[0] = this.a; array[1] = this.c; array[2] = this.tx; @@ -119,7 +125,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, transformed through this matrix */ -Matrix.prototype.apply = function (pos, newPos) { +Matrix.prototype.apply = function (pos, newPos) +{ newPos = newPos || new Point(); newPos.x = this.a * pos.x + this.c * pos.y + this.tx; @@ -136,7 +143,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, inverse-transformed through this matrix */ -Matrix.prototype.applyInverse = function (pos, newPos) { +Matrix.prototype.applyInverse = function (pos, newPos) +{ newPos = newPos || new Point(); var id = 1 / (this.a * this.d + this.c * -this.b); @@ -154,7 +162,8 @@ * @param {number} y * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.translate = function (x, y) { +Matrix.prototype.translate = function (x, y) +{ this.tx += x; this.ty += y; @@ -168,7 +177,8 @@ * @param {number} y The amount to scale vertically * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.scale = function (x, y) { +Matrix.prototype.scale = function (x, y) +{ this.a *= x; this.d *= y; this.c *= x; @@ -186,7 +196,8 @@ * @param {number} angle - The angle in radians. * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.rotate = function (angle) { +Matrix.prototype.rotate = function (angle) +{ var cos = Math.cos( angle ); var sin = Math.sin( angle ); @@ -210,7 +221,8 @@ * @param {Matrix} matrix * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.append = function (matrix) { +Matrix.prototype.append = function (matrix) +{ var a1 = this.a; var b1 = this.b; var c1 = this.c; @@ -232,7 +244,8 @@ * * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.identity = function () { +Matrix.prototype.identity = function () +{ this.a = 1; this.b = 0; this.c = 0; diff --git a/src/core/math/Point.js b/src/core/math/Point.js index 7565b2d..632f346 100644 --- a/src/core/math/Point.js +++ b/src/core/math/Point.js @@ -7,7 +7,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -function Point(x, y) { +function Point(x, y) +{ /** * @member {number} * @default 0 @@ -29,7 +30,8 @@ * * @return {Point} a copy of the point */ -Point.prototype.clone = function () { +Point.prototype.clone = function () +{ return new Point(this.x, this.y); }; @@ -40,7 +42,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -Point.prototype.set = function (x, y) { +Point.prototype.set = function (x, y) +{ this.x = x || 0; this.y = y || ( (y !== 0) ? this.x : 0 ) ; }; diff --git a/src/core/math/shapes/Circle.js b/src/core/math/shapes/Circle.js index 69cfdc9..4d76efc 100644 --- a/src/core/math/shapes/Circle.js +++ b/src/core/math/shapes/Circle.js @@ -10,7 +10,8 @@ * @param y {number} The Y coordinate of the center of this circle * @param radius {number} The radius of the circle */ -function Circle(x, y, radius) { +function Circle(x, y, radius) +{ /** * @member {number} * @default 0 @@ -46,7 +47,8 @@ * @method clone * @return {Circle} a copy of the Circle */ -Circle.prototype.clone = function () { +Circle.prototype.clone = function () +{ return new Circle(this.x, this.y, this.radius); }; @@ -58,8 +60,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Circle */ -Circle.prototype.contains = function (x, y) { - if (this.radius <= 0) { +Circle.prototype.contains = function (x, y) +{ + if (this.radius <= 0) + { return false; } @@ -79,6 +83,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Circle.prototype.getBounds = function () { +Circle.prototype.getBounds = function () +{ return new Rectangle(this.x - this.radius, this.y - this.radius, this.radius * 2, this.radius * 2); }; diff --git a/src/core/math/shapes/Ellipse.js b/src/core/math/shapes/Ellipse.js index 4f2d066..fefd01a 100644 --- a/src/core/math/shapes/Ellipse.js +++ b/src/core/math/shapes/Ellipse.js @@ -11,7 +11,8 @@ * @param width {number} The half width of this ellipse * @param height {number} The half height of this ellipse */ -function Ellipse(x, y, width, height) { +function Ellipse(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -53,7 +54,8 @@ * @method clone * @return {Ellipse} a copy of the ellipse */ -Ellipse.prototype.clone = function () { +Ellipse.prototype.clone = function () +{ return new Ellipse(this.x, this.y, this.width, this.height); }; @@ -65,8 +67,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coords are within this ellipse */ -Ellipse.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Ellipse.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } @@ -86,6 +90,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Ellipse.prototype.getBounds = function () { +Ellipse.prototype.getBounds = function () +{ return new Rectangle(this.x - this.width, this.y - this.height, this.width, this.height); }; diff --git a/src/core/math/shapes/Polygon.js b/src/core/math/shapes/Polygon.js index ae89148..fea6d37 100644 --- a/src/core/math/shapes/Polygon.js +++ b/src/core/math/shapes/Polygon.js @@ -10,16 +10,20 @@ * arguments passed can be flat x,y values e.g. `new Polygon(x,y, x,y, x,y, ...)` where `x` and `y` are * Numbers. */ -function Polygon(points) { +function Polygon(points) +{ //if points isn't an array, use arguments as the array - if (!(points instanceof Array)) { + if (!(points instanceof Array)) + { points = Array.prototype.slice.call(arguments); } //if this is a flat array of numbers, convert it to points - if (points[0] instanceof Point) { + if (points[0] instanceof Point) + { var p = []; - for (var i = 0, il = points.length; i < il; i++) { + for (var i = 0, il = points.length; i < il; i++) + { p.push(points[i].x, points[i].y); } @@ -51,7 +55,8 @@ * * @return {Polygon} a copy of the polygon */ -Polygon.prototype.clone = function () { +Polygon.prototype.clone = function () +{ return new Polygon(this.points.slice()); }; @@ -62,19 +67,22 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this polygon */ -Polygon.prototype.contains = function (x, y) { +Polygon.prototype.contains = function (x, y) +{ var inside = false; // use some raycasting to test hits // https://github.com/substack/point-in-polygon/blob/master/index.js var length = this.points.length / 2; - for (var i = 0, j = length - 1; i < length; j = i++) { + for (var i = 0, j = length - 1; i < length; j = i++) + { var xi = this.points[i * 2], yi = this.points[i * 2 + 1], xj = this.points[j * 2], yj = this.points[j * 2 + 1], intersect = ((yi > y) !== (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi); - if (intersect) { + if (intersect) + { inside = !inside; } } diff --git a/src/core/math/shapes/Rectangle.js b/src/core/math/shapes/Rectangle.js index 16ac62a..4008b68 100644 --- a/src/core/math/shapes/Rectangle.js +++ b/src/core/math/shapes/Rectangle.js @@ -10,7 +10,8 @@ * @param width {number} The overall width of this rectangle * @param height {number} The overall height of this rectangle */ -function Rectangle(x, y, width, height) { +function Rectangle(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -60,7 +61,8 @@ * * @return {Rectangle} a copy of the rectangle */ -Rectangle.prototype.clone = function () { +Rectangle.prototype.clone = function () +{ return new Rectangle(this.x, this.y, this.width, this.height); }; @@ -71,13 +73,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rectangle */ -Rectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Rectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/math/shapes/RoundedRectangle.js b/src/core/math/shapes/RoundedRectangle.js index 27d286e..7bf6411 100644 --- a/src/core/math/shapes/RoundedRectangle.js +++ b/src/core/math/shapes/RoundedRectangle.js @@ -11,7 +11,8 @@ * @param height {number} The overall height of this rounded rectangle * @param radius {number} Controls the radius of the rounded corners */ -function RoundedRectangle(x, y, width, height, radius) { +function RoundedRectangle(x, y, width, height, radius) +{ /** * @member {number} * @default 0 @@ -58,7 +59,8 @@ * * @return {RoundedRectangle} a copy of the rounded rectangle */ -RoundedRectangle.prototype.clone = function () { +RoundedRectangle.prototype.clone = function () +{ return new RoundedRectangle(this.x, this.y, this.width, this.height, this.radius); }; @@ -69,13 +71,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rounded Rectangle */ -RoundedRectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +RoundedRectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/primitives/Graphics.js b/src/core/primitives/Graphics.js index 261c534..e902d2a 100644 --- a/src/core/primitives/Graphics.js +++ b/src/core/primitives/Graphics.js @@ -16,7 +16,8 @@ * @extends DisplayObjectContainer * @namespace PIXI */ -function Graphics() { +function Graphics() +{ DisplayObjectContainer.call(this); this.renderable = true; @@ -154,16 +155,20 @@ * @private */ cacheAsBitmap: { - get: function () { + get: function () + { return this._cacheAsBitmap; }, - set: function (value) { + set: function (value) + { this._cacheAsBitmap = value; - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._generateCachedSprite(); } - else { + else + { this.destroyCachedSprite(); this.dirty = true; } @@ -176,7 +181,8 @@ * * @return {Graphics} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ var clone = new Graphics(); clone.renderable = this.renderable; @@ -192,7 +198,8 @@ clone.cachedSpriteDirty = this.cachedSpriteDirty; // copy graphics data - for (var i = 0; i < this.graphicsData.length; ++i) { + for (var i = 0; i < this.graphicsData.length; ++i) + { clone.graphicsData.push(this.graphicsData.clone()); } @@ -211,17 +218,21 @@ * @param alpha {number} alpha of the line to draw, will update the objects stored style * @return {Graphics} */ -Graphics.prototype.lineStyle = function (lineWidth, color, alpha) { +Graphics.prototype.lineStyle = function (lineWidth, color, alpha) +{ this.lineWidth = lineWidth || 0; this.lineColor = color || 0; this.lineAlpha = (arguments.length < 3) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length) + { // halfway through a line? start a new one! this.drawShape( new math.Polygon( this.currentPath.shape.points.slice(-2) )); } - else { + else + { // otherwise its empty so lets just set the line properties this.currentPath.lineWidth = this.lineWidth; this.currentPath.lineColor = this.lineColor; @@ -239,7 +250,8 @@ * @param y {number} the Y coordinate to move to * @return {Graphics} */ -Graphics.prototype.moveTo = function (x, y) { +Graphics.prototype.moveTo = function (x, y) +{ this.drawShape(new math.Polygon([x,y])); return this; @@ -253,7 +265,8 @@ * @param y {number} the Y coordinate to draw to * @return {Graphics} */ -Graphics.prototype.lineTo = function (x, y) { +Graphics.prototype.lineTo = function (x, y) +{ this.currentPath.shape.points.push(x, y); this.dirty = true; @@ -270,13 +283,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -285,7 +302,8 @@ n = 20, points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { this.moveTo(0, 0); } @@ -293,7 +311,8 @@ var fromY = points[points.length-1]; var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; xa = fromX + ( (cpX - fromX) * j ); @@ -319,13 +338,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -342,7 +365,8 @@ var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; dt = (1 - j); @@ -373,13 +397,17 @@ * @param radius {number} The radius of the arc * @return {Graphics} */ -Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points.push(x1, y1); } } - else { + else + { this.moveTo(x1, y1); } @@ -392,12 +420,15 @@ b2 = x2 - x1, mm = Math.abs(a1 * b2 - b1 * a2); - if (mm < 1.0e-8 || radius === 0) { - if (points[points.length-2] !== x1 || points[points.length-1] !== y1) { + if (mm < 1.0e-8 || radius === 0) + { + if (points[points.length-2] !== x1 || points[points.length-1] !== y1) + { points.push(x1, y1); } } - else { + else + { var dd = a1 * a1 + b1 * b1, cc = a2 * a2 + b2 * b2, tt = a1 * a2 + b1 * b2, @@ -433,42 +464,51 @@ * @param anticlockwise {boolean} Optional. Specifies whether the drawing should be counterclockwise or clockwise. False is default, and indicates clockwise, while true indicates counter-clockwise. * @return {Graphics} */ -Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) { +Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) +{ var startX = cx + Math.cos(startAngle) * radius; var startY = cy + Math.sin(startAngle) * radius; var points; // TODO - This if-else makes no sense. It uses currentPath in the else where it doesn't exist... - if (this.currentPath) { + if (this.currentPath) + { points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { points.push(startX, startY); } - else if (points[points.length-2] !== startX || points[points.length-1] !== startY) { + else if (points[points.length-2] !== startX || points[points.length-1] !== startY) + { points.push(startX, startY); } } - else { + else + { this.moveTo(startX, startY); points = this.currentPath.shape.points; } - if (startAngle === endAngle) { + if (startAngle === endAngle) + { return this; } - if (!anticlockwise && endAngle <= startAngle) { + if (!anticlockwise && endAngle <= startAngle) + { endAngle += Math.PI * 2; } - else if (anticlockwise && startAngle <= endAngle) { + else if (anticlockwise && startAngle <= endAngle) + { startAngle += Math.PI * 2; } var sweep = anticlockwise ? (startAngle - endAngle) *-1 : (endAngle - startAngle); var segs = (Math.abs(sweep)/ (Math.PI * 2)) * 40; - if (sweep === 0) { + if (sweep === 0) + { return this; } @@ -482,7 +522,8 @@ var remainder = ( segMinus % 1 ) / segMinus; - for (var i = 0; i <= segMinus; ++i) { + for (var i = 0; i <= segMinus; ++i) + { var real = i + remainder * i; var angle = ((theta) + startAngle + (theta2 * real)); @@ -506,13 +547,16 @@ * @param alpha {number} the alpha of the fill * @return {Graphics} */ -Graphics.prototype.beginFill = function (color, alpha) { +Graphics.prototype.beginFill = function (color, alpha) +{ this.filling = true; this.fillColor = color || 0; this.fillAlpha = (alpha === undefined) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length <= 2) + { this.currentPath.fill = this.filling; this.currentPath.fillColor = this.fillColor; this.currentPath.fillAlpha = this.fillAlpha; @@ -526,7 +570,8 @@ * * @return {Graphics} */ -Graphics.prototype.endFill = function () { +Graphics.prototype.endFill = function () +{ this.filling = false; this.fillColor = null; this.fillAlpha = 1; @@ -542,7 +587,8 @@ * @param height {number} The height of the rectangle * @return {Graphics} */ -Graphics.prototype.drawRect = function ( x, y, width, height ) { +Graphics.prototype.drawRect = function ( x, y, width, height ) +{ this.drawShape(new math.Rectangle(x,y, width, height)); return this; @@ -556,7 +602,8 @@ * @param height {number} The height of the rectangle * @param radius {number} Radius of the rectangle corners */ -Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) { +Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) +{ this.drawShape(new math.RoundedRectangle(x, y, width, height, radius)); return this; @@ -570,7 +617,8 @@ * @param radius {number} The radius of the circle * @return {Graphics} */ -Graphics.prototype.drawCircle = function (x, y, radius) { +Graphics.prototype.drawCircle = function (x, y, radius) +{ this.drawShape(new math.Circle(x,y, radius)); return this; @@ -585,7 +633,8 @@ * @param height {number} The half height of the ellipse * @return {Graphics} */ -Graphics.prototype.drawEllipse = function (x, y, width, height) { +Graphics.prototype.drawEllipse = function (x, y, width, height) +{ this.drawShape(new math.Ellipse(x, y, width, height)); return this; @@ -597,8 +646,10 @@ * @param path {Array} The path data used to construct the polygon. * @return {Graphics} */ -Graphics.prototype.drawPolygon = function (path) { - if (!(path instanceof Array)) { +Graphics.prototype.drawPolygon = function (path) +{ + if (!(path instanceof Array)) + { path = Array.prototype.slice.call(arguments); } @@ -612,7 +663,8 @@ * * @return {Graphics} */ -Graphics.prototype.clear = function () { +Graphics.prototype.clear = function () +{ this.lineWidth = 0; this.filling = false; @@ -631,7 +683,8 @@ * @param scaleMode {number} Should be one of the scaleMode consts * @return {Texture} a texture of the graphics object */ -Graphics.prototype.generateTexture = function (resolution, scaleMode) { +Graphics.prototype.generateTexture = function (resolution, scaleMode) +{ resolution = resolution || 1; var bounds = this.getBounds(); @@ -655,17 +708,21 @@ * * @param renderer {WebGLRenderer} */ -Graphics.prototype._renderWebGL = function (renderer) { +Graphics.prototype._renderWebGL = function (renderer) +{ // if the sprite is not visible or the alpha is 0 then no need to render this element - if (this.isMask === true) { + if (this.isMask === true) + { return; } // this code may still be needed so leaving for now.. - // + // /* - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture on the gpu too! @@ -681,17 +738,24 @@ return; } - */ - - // check if the webgl graphic needs to be updated - if (this.glDirty) { - this.dirty = true; - this.glDirty = false; - } + else */ - renderer.setObjectRendererer(renderer.graphicsRenderer); - renderer.graphicsRenderer.render(this); + renderer.spriteBatch.stop(); + renderer.blendModeManager.setBlendMode(this.blendMode); + // check blend mode + renderer.blendModeManager.setBlendMode( this.blendMode ); + + // check if the webgl graphic needs to be updated + if (this.glDirty) + { + this.dirty = true; + this.glDirty = false; + } + + WebGLGraphics.renderGraphics(this, renderer); + + renderer.spriteBatch.start(); }; /** @@ -700,14 +764,18 @@ * @param renderer {CanvasRenderer} * @private */ -Graphics.prototype.renderCanvas = function (renderer) { +Graphics.prototype.renderCanvas = function (renderer) +{ // 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.isMask === true) { + if (!this.visible || this.alpha <= 0 || this.isMask === true) + { return; } - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture @@ -723,16 +791,19 @@ return; } - else { + else + { var context = renderer.context; var transform = this.worldTransform; - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } @@ -748,11 +819,13 @@ CanvasGraphics.renderGraphics(this, context); - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } } @@ -763,13 +836,16 @@ * * @return {Rectangle} the rectangular bounding area */ -Graphics.prototype.getBounds = function (matrix) { +Graphics.prototype.getBounds = function (matrix) +{ // return an empty object if the item is a mask! - if (this.isMask) { + if (this.isMask) + { return math.Rectangle.EMPTY; } - if (this.dirty) { + if (this.dirty) + { this.updateLocalBounds(); this.glDirty = true; @@ -841,23 +917,27 @@ * Update the bounds of the object * */ -Graphics.prototype.updateLocalBounds = function () { +Graphics.prototype.updateLocalBounds = function () +{ var minX = Infinity; var maxX = -Infinity; var minY = Infinity; var maxY = -Infinity; - if (this.graphicsData.length) { + if (this.graphicsData.length) + { var shape, points, x, y, w, h; - for (var i = 0; i < this.graphicsData.length; i++) { + for (var i = 0; i < this.graphicsData.length; i++) + { var data = this.graphicsData[i]; var type = data.type; var lineWidth = data.lineWidth; shape = data.shape; - if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) { + if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) + { x = shape.x - lineWidth/2; y = shape.y - lineWidth/2; w = shape.width + lineWidth; @@ -869,7 +949,8 @@ minY = y < minY ? y : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.CIRC) { + else if (type === CONST.SHAPES.CIRC) + { x = shape.x; y = shape.y; w = shape.radius + lineWidth/2; @@ -881,7 +962,8 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.ELIP) { + else if (type === CONST.SHAPES.ELIP) + { x = shape.x; y = shape.y; w = shape.width + lineWidth/2; @@ -893,11 +975,13 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else { + else + { // POLY points = shape.points; - for (var j = 0; j < points.length; j += 2) { + for (var j = 0; j < points.length; j += 2) + { x = points[j]; y = points[j+1]; @@ -910,7 +994,8 @@ } } } - else { + else + { minX = 0; maxX = 0; minY = 0; @@ -931,10 +1016,12 @@ * * @private */ -Graphics.prototype._generateCachedSprite = function () { +Graphics.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { var canvasBuffer = new CanvasBuffer(bounds.width, bounds.height); var texture = Texture.fromCanvas(canvasBuffer.canvas); @@ -943,7 +1030,8 @@ this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.buffer.resize(bounds.width, bounds.height); } @@ -968,7 +1056,8 @@ * * @private */ -Graphics.prototype.updateCachedSpriteTexture = function () { +Graphics.prototype.updateCachedSpriteTexture = function () +{ var cachedSprite = this._cachedSprite; var texture = cachedSprite.texture; var canvas = cachedSprite.buffer.canvas; @@ -989,7 +1078,8 @@ * Destroys a previous cached sprite. * */ -Graphics.prototype.destroyCachedSprite = function () { +Graphics.prototype.destroyCachedSprite = function () +{ this._cachedSprite.texture.destroy(true); // let the gc collect the unused sprite @@ -1003,10 +1093,13 @@ * @param {Circle|Rectangle|Ellipse|Line|Polygon} shape The Shape object to draw. * @return {GraphicsData} The generated GraphicsData object. */ -Graphics.prototype.drawShape = function (shape) { - if (this.currentPath) { +Graphics.prototype.drawShape = function (shape) +{ + if (this.currentPath) + { // check current path! - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath.shape.points.length <= 2) + { this.graphicsData.pop(); } } @@ -1017,7 +1110,8 @@ this.graphicsData.push(data); - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { data.shape.closed = this.filling; this.currentPath = data; } diff --git a/src/core/primitives/GraphicsData.js b/src/core/primitives/GraphicsData.js index 99decbe..788f6f2 100644 --- a/src/core/primitives/GraphicsData.js +++ b/src/core/primitives/GraphicsData.js @@ -4,7 +4,8 @@ * @class * @namespace PIXI */ -function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) { +function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) +{ this.lineWidth = lineWidth; this.lineColor = lineColor; this.lineAlpha = lineAlpha; @@ -27,7 +28,8 @@ * * @return {GraphicsData} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ return new GraphicsData( this.lineWidth, this.lineColor, diff --git a/src/core/renderers/canvas/CanvasRenderer.js b/src/core/renderers/canvas/CanvasRenderer.js index 15a0978..7aebd44 100644 --- a/src/core/renderers/canvas/CanvasRenderer.js +++ b/src/core/renderers/canvas/CanvasRenderer.js @@ -17,17 +17,22 @@ * @param [options.resolution=1] {number} the resolution of the renderer retina would be 2 * @param [options.clearBeforeRender=true] {boolean} This sets if the CanvasRenderer will clear the canvas or not before the new render pass. */ -function CanvasRenderer(width, height, options) { +function CanvasRenderer(width, height, options) +{ utils.sayHello('Canvas'); - if (options) { - for (var i in CONST.defaultRenderOptions) { - if (typeof options[i] === 'undefined') { + if (options) + { + for (var i in CONST.defaultRenderOptions) + { + if (typeof options[i] === 'undefined') + { options[i] = CONST.defaultRenderOptions[i]; } } } - else { + else + { options = CONST.defaultRenderOptions; } @@ -156,19 +161,24 @@ this.smoothProperty = null; - if (this.context.imageSmoothingEnabled) { + if (this.context.imageSmoothingEnabled) + { this.smoothProperty = 'imageSmoothingEnabled'; } - else if (this.context.webkitImageSmoothingEnabled) { + else if (this.context.webkitImageSmoothingEnabled) + { this.smoothProperty = 'webkitImageSmoothingEnabled'; } - else if (this.context.mozImageSmoothingEnabled) { + else if (this.context.mozImageSmoothingEnabled) + { this.smoothProperty = 'mozImageSmoothingEnabled'; } - else if (this.context.oImageSmoothingEnabled) { + else if (this.context.oImageSmoothingEnabled) + { this.smoothProperty = 'oImageSmoothingEnabled'; } - else if (this.context.msImageSmoothingEnabled) { + else if (this.context.msImageSmoothingEnabled) + { this.smoothProperty = 'msImageSmoothingEnabled'; } @@ -193,10 +203,12 @@ * @memberof CanvasRenderer# */ backgroundColor: { - get: function () { + get: function () + { return this._backgroundColor; }, - set: function (val) { + set: function (val) + { this._backgroundColor = val; this._backgroundColorString = utils.hex2string(val); } @@ -208,7 +220,8 @@ * * @param object {DisplayObject} the object to be rendered */ -CanvasRenderer.prototype.render = function (object) { +CanvasRenderer.prototype.render = function (object) +{ object.updateTransform(); this.context.setTransform(1,0,0,1,0,0); @@ -218,16 +231,20 @@ this.currentBlendMode = CONST.blendModes.NORMAL; this.context.globalCompositeOperation = this.blendModes[CONST.blendModes.NORMAL]; - if (navigator.isCocoonJS && this.view.screencanvas) { + if (navigator.isCocoonJS && this.view.screencanvas) + { this.context.fillStyle = 'black'; this.context.clear(); } - if (this.clearBeforeRender) { - if (this.transparent) { + if (this.clearBeforeRender) + { + if (this.transparent) + { this.context.clearRect(0, 0, this.width, this.height); } - else { + else + { this.context.fillStyle = this._backgroundColorString; this.context.fillRect(0, 0, this.width , this.height); } @@ -241,8 +258,10 @@ * * @param [removeView=false] {boolean} Removes the Canvas element from the DOM. */ -CanvasRenderer.prototype.destroy = function (removeView) { - if (removeView && this.view.parent) { +CanvasRenderer.prototype.destroy = function (removeView) +{ + if (removeView && this.view.parent) + { this.view.parent.removeChild(this.view); } @@ -257,14 +276,16 @@ * @param width {number} the new width of the canvas view * @param height {number} the new height of the canvas view */ -CanvasRenderer.prototype.resize = function (width, height) { +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) { + if (this.autoResize) + { this.view.style.width = this.width / this.resolution + 'px'; this.view.style.height = this.height / this.resolution + 'px'; } @@ -276,7 +297,8 @@ * @param displayObject {DisplayObject} The displayObject to render * @private */ -CanvasRenderer.prototype.renderDisplayObject = function (displayObject) { +CanvasRenderer.prototype.renderDisplayObject = function (displayObject) +{ displayObject.renderCanvas(this); }; @@ -285,11 +307,14 @@ * * @private */ -CanvasRenderer.prototype._mapBlendModes = function () { - if (!this.blendModes) { +CanvasRenderer.prototype._mapBlendModes = function () +{ + if (!this.blendModes) + { this.blendModes = {}; - if (utils.canUseNewCanvasBlendModes()) { + if (utils.canUseNewCanvasBlendModes()) + { this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? this.blendModes[CONST.blendModes.MULTIPLY] = 'multiply'; @@ -308,7 +333,8 @@ this.blendModes[CONST.blendModes.COLOR] = 'color'; this.blendModes[CONST.blendModes.LUMINOSITY] = 'luminosity'; } - else { + else + { // this means that the browser does not support the cool new blend modes in canvas 'cough' ie 'cough' this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? diff --git a/src/core/renderers/canvas/utils/CanvasBuffer.js b/src/core/renderers/canvas/utils/CanvasBuffer.js index ebe5d47..b183a66 100644 --- a/src/core/renderers/canvas/utils/CanvasBuffer.js +++ b/src/core/renderers/canvas/utils/CanvasBuffer.js @@ -6,7 +6,8 @@ * @param width {number} the width for the newly created canvas * @param height {number} the height for the newly created canvas */ -function CanvasBuffer(width, height) { +function CanvasBuffer(width, height) +{ /** * The Canvas object that belongs to this CanvasBuffer. * @@ -36,10 +37,12 @@ * @memberof CanvasBuffer# */ width: { - get: function () { + get: function () + { return this.canvas.width; }, - set: function (val) { + set: function (val) + { this.canvas.width = val; } }, @@ -50,10 +53,12 @@ * @memberof CanvasBuffer# */ height: { - get: function () { + get: function () + { return this.canvas.height; }, - set: function (val) { + set: function (val) + { this.canvas.height = val; } } @@ -64,7 +69,8 @@ * * @private */ -CanvasBuffer.prototype.clear = function () { +CanvasBuffer.prototype.clear = function () +{ this.context.setTransform(1, 0, 0, 1, 0, 0); this.context.clearRect(0,0, this.canvas.width, this.canvas.height); }; @@ -75,7 +81,8 @@ * @param width {number} the new width of the canvas * @param height {number} the new height of the canvas */ -CanvasBuffer.prototype.resize = function (width, height) { +CanvasBuffer.prototype.resize = function (width, height) +{ this.canvas.width = width; this.canvas.height = height; }; diff --git a/src/core/renderers/canvas/utils/CanvasGraphics.js b/src/core/renderers/canvas/utils/CanvasGraphics.js index c7eaa2a..3f2a91f 100644 --- a/src/core/renderers/canvas/utils/CanvasGraphics.js +++ b/src/core/renderers/canvas/utils/CanvasGraphics.js @@ -13,15 +13,18 @@ * @param graphics {Graphics} the actual graphics object to render * @param context {CanvasRenderingContext2D} the 2d drawing method of the canvas */ -CanvasGraphics.renderGraphics = function (graphics, context) { +CanvasGraphics.renderGraphics = function (graphics, context) +{ var worldAlpha = graphics.worldAlpha; - if (graphics.dirty) { + if (graphics.dirty) + { this.updateGraphicsTint(graphics); graphics.dirty = false; } - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; @@ -30,69 +33,82 @@ context.lineWidth = data.lineWidth; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { context.beginPath(); var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } - if (shape.closed) { + if (shape.closed) + { context.lineTo(points[0], points[1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fillRect(shape.x, shape.y, shape.width, shape.height); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.strokeRect(shape.x, shape.y, shape.width, shape.height); } } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.beginPath(); context.arc(shape.x, shape.y, shape.radius,0,2*Math.PI); context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas var w = shape.width * 2; @@ -119,18 +135,21 @@ context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; var width = shape.width; @@ -152,13 +171,15 @@ context.quadraticCurveTo(rx, ry, rx, ry + radius); context.closePath(); - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); @@ -174,45 +195,54 @@ * @param graphics {Graphics} the graphics which will be used as a mask * @param context {CanvasRenderingContext2D} the context 2d method of the canvas */ -CanvasGraphics.renderGraphicsMask = function (graphics, context) { +CanvasGraphics.renderGraphicsMask = function (graphics, context) +{ var len = graphics.graphicsData.length; - if (len === 0) { + if (len === 0) + { return; } context.beginPath(); - for (var i = 0; i < len; i++) { + for (var i = 0; i < len; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { context.rect(shape.x, shape.y, shape.width, shape.height); context.closePath(); } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.arc(shape.x, shape.y, shape.radius, 0, 2 * Math.PI); context.closePath(); } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas @@ -237,7 +267,8 @@ context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); context.closePath(); } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; @@ -262,8 +293,10 @@ } }; -CanvasGraphics.updateGraphicsTint = function (graphics) { - if (graphics.tint === 0xFFFFFF) { +CanvasGraphics.updateGraphicsTint = function (graphics) +{ + if (graphics.tint === 0xFFFFFF) + { return; } @@ -271,7 +304,8 @@ var tintG = (graphics.tint >> 8 & 0xFF) / 255; var tintB = (graphics.tint & 0xFF)/ 255; - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var fillColor = data.fillColor | 0; diff --git a/src/core/renderers/canvas/utils/CanvasMaskManager.js b/src/core/renderers/canvas/utils/CanvasMaskManager.js index e04a733..9827d36 100644 --- a/src/core/renderers/canvas/utils/CanvasMaskManager.js +++ b/src/core/renderers/canvas/utils/CanvasMaskManager.js @@ -6,7 +6,8 @@ * @class * @namespace PIXI */ -function CanvasMaskManager() {} +function CanvasMaskManager() +{} CanvasMaskManager.prototype.constructor = CanvasMaskManager; module.exports = CanvasMaskManager; @@ -17,7 +18,8 @@ * @param maskData {object} the maskData that will be pushed * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.pushMask = function (maskData, renderer) { +CanvasMaskManager.prototype.pushMask = function (maskData, renderer) +{ renderer.context.save(); var cacheAlpha = maskData.alpha; @@ -45,6 +47,7 @@ * * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.popMask = function (renderer) { +CanvasMaskManager.prototype.popMask = function (renderer) +{ renderer.context.restore(); }; diff --git a/src/core/renderers/canvas/utils/CanvasTinter.js b/src/core/renderers/canvas/utils/CanvasTinter.js index 17e0529..d2fb1bc 100644 --- a/src/core/renderers/canvas/utils/CanvasTinter.js +++ b/src/core/renderers/canvas/utils/CanvasTinter.js @@ -14,7 +14,8 @@ * @param color {number} the color to use to tint the sprite with * @return {HTMLCanvasElement} The tinted canvas */ -CanvasTinter.getTintedTexture = function (sprite, color) { +CanvasTinter.getTintedTexture = function (sprite, color) +{ var texture = sprite.texture; color = CanvasTinter.roundColor(color); @@ -23,7 +24,8 @@ texture.tintCache = texture.tintCache || {}; - if (texture.tintCache[stringColor]) { + if (texture.tintCache[stringColor]) + { return texture.tintCache[stringColor]; } @@ -33,14 +35,16 @@ //CanvasTinter.tintWithPerPixel(texture, stringColor, canvas); CanvasTinter.tintMethod(texture, color, canvas); - if (CanvasTinter.convertTintToImage) { + if (CanvasTinter.convertTintToImage) + { // is this better? var tintImage = new Image(); tintImage.src = canvas.toDataURL(); texture.tintCache[stringColor] = tintImage; } - else { + else + { texture.tintCache[stringColor] = canvas; // if we are not converting the texture to an image then we need to lose the reference to the canvas CanvasTinter.canvas = null; @@ -56,7 +60,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithMultiply = function (texture, color, canvas) { +CanvasTinter.tintWithMultiply = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -104,7 +109,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithOverlay = function (texture, color, canvas) { +CanvasTinter.tintWithOverlay = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -139,7 +145,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithPerPixel = function (texture, color, canvas) { +CanvasTinter.tintWithPerPixel = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -167,7 +174,8 @@ var pixels = pixelData.data; - for (var i = 0; i < pixels.length; i += 4) { + for (var i = 0; i < pixels.length; i += 4) + { pixels[i+0] *= r; pixels[i+1] *= g; pixels[i+2] *= b; @@ -181,7 +189,8 @@ * * @param color {number} the color to round, should be a hex color */ -CanvasTinter.roundColor = function (color) { +CanvasTinter.roundColor = function (color) +{ var step = CanvasTinter.cacheStepsPerColorChannel; var rgbValues = utils.hex2rgb(color); diff --git a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js index 9f2f89a..35edbaf 100644 --- a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js +++ b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLBlendModeManager(renderer) { +function WebGLBlendModeManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -23,8 +24,10 @@ * * @param blendMode {number} the blendMode, should be a Pixi const, such as BlendModes.ADD */ -WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) { - if (this.currentBlendMode === blendMode) { +WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) +{ + if (this.currentBlendMode === blendMode) + { return false; } diff --git a/src/core/renderers/webgl/managers/WebGLFilterManager.js b/src/core/renderers/webgl/managers/WebGLFilterManager.js index 1179258..2dac048 100644 --- a/src/core/renderers/webgl/managers/WebGLFilterManager.js +++ b/src/core/renderers/webgl/managers/WebGLFilterManager.js @@ -7,7 +7,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLFilterManager(renderer) { +function WebGLFilterManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -32,7 +33,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.texturePool.length = 0; self.initShaderBuffers(); }); @@ -46,7 +48,8 @@ * @param renderer {WebGLRenderer} * @param buffer {ArrayBuffer} */ -WebGLFilterManager.prototype.begin = function (buffer) { +WebGLFilterManager.prototype.begin = function (buffer) +{ this.defaultShader = this.renderer.shaderManager.defaultShader; this.width = this.renderer.projection.x * 2; @@ -60,7 +63,8 @@ * * @param filterBlock {object} the filter that will be pushed to the current filter stack */ -WebGLFilterManager.prototype.pushFilter = function (filterBlock) { +WebGLFilterManager.prototype.pushFilter = function (filterBlock) +{ var gl = this.renderer.gl; var projection = this.renderer.projection; @@ -78,10 +82,12 @@ this.offsetY += filterBlock._filterArea.y; var texture = this.texturePool.pop(); - if (!texture) { + if (!texture) + { texture = new FilterTexture(this.renderer.gl, this.width, this.height); } - else { + else + { texture.resize(this.width, this.height); } @@ -98,29 +104,35 @@ var localX = filterArea.x, localY = filterArea.y; - if (filterArea.x < 0) { + if (filterArea.x < 0) + { filterArea.width += filterArea.x; filterArea.x = 0; } - if (filterArea.y < 0) { + if (filterArea.y < 0) + { filterArea.height += filterArea.y; filterArea.y = 0; } - if (localX + filterArea.width > this.width) { + if (localX + filterArea.width > this.width) + { filterArea.width = this.width - localX; } - if (localY + filterArea.height > this.height) { + if (localY + filterArea.height > this.height) + { filterArea.height = this.height - localY; } - if (filterArea.width < 0) { + if (filterArea.width < 0) + { filterArea.width = 0; } - if (filterArea.height < 0) { + if (filterArea.height < 0) + { filterArea.height = 0; } @@ -154,7 +166,8 @@ * Removes the last filter from the filter stack and doesn't return it. * */ -WebGLFilterManager.prototype.popFilter = function () { +WebGLFilterManager.prototype.popFilter = function () +{ var gl = this.renderer.gl; var filterBlock = this.filterStack.pop(); @@ -163,7 +176,8 @@ var projection = this.renderer.projection; var offset = this.renderer.offset; - if (filterBlock.filterPasses.length > 1) { + if (filterBlock.filterPasses.length > 1) + { gl.viewport(0, 0, filterArea.width, filterArea.height); gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); @@ -193,7 +207,8 @@ var inputTexture = texture; var outputTexture = this.texturePool.pop(); - if (!outputTexture) { + if (!outputTexture) + { outputTexture = new FilterTexture(this.renderer.gl, this.width, this.height); } outputTexture.resize(this.width, this.height); @@ -204,7 +219,8 @@ gl.disable(gl.BLEND); - for (var i = 0; i < filterBlock.filterPasses.length-1; i++) { + for (var i = 0; i < filterBlock.filterPasses.length-1; i++) + { var filterPass = filterBlock.filterPasses[i]; gl.bindFramebuffer(gl.FRAMEBUFFER, outputTexture.frameBuffer ); @@ -243,10 +259,12 @@ var buffer = this.buffer; // time to render the filters texture to the previous scene - if (this.filterStack.length === 0) { + if (this.filterStack.length === 0) + { gl.colorMask(true, true, true, true);//this.transparent); } - else { + else + { var currentFilter = this.filterStack[this.filterStack.length-1]; filterArea = currentFilter._filterArea; @@ -332,13 +350,15 @@ * @param width {number} the horizontal range of the filter * @param height {number} the vertical range of the filter */ -WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) { +WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) +{ // use program var gl = this.renderer.gl; var shader = filter.shaders[gl.id]; - if (!shader) { + if (!shader) + { shader = new Shader(gl); shader.fragmentSrc = filter.fragmentSrc; @@ -356,7 +376,8 @@ gl.uniform2f(shader.projectionVector, width/2, -height/2); gl.uniform2f(shader.offsetVector, 0,0); - if (filter.uniforms.dimensions) { + 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]; @@ -386,7 +407,8 @@ * Initialises the shader buffers. * */ -WebGLFilterManager.prototype.initShaderBuffers = function () { +WebGLFilterManager.prototype.initShaderBuffers = function () +{ var gl = this.renderer.gl; // create some buffers @@ -432,7 +454,8 @@ * Destroys the filter and removes it from the filter stack. * */ -WebGLFilterManager.prototype.destroy = function () { +WebGLFilterManager.prototype.destroy = function () +{ var gl = this.renderer.gl; this.filterStack = null; @@ -441,7 +464,8 @@ this.offsetY = 0; // destroy textures - for (var i = 0; i < this.texturePool.length; i++) { + for (var i = 0; i < this.texturePool.length; i++) + { this.texturePool[i].destroy(); } diff --git a/src/core/renderers/webgl/managers/WebGLManager.js b/src/core/renderers/webgl/managers/WebGLManager.js index 9d47b5c..c30cd51 100644 --- a/src/core/renderers/webgl/managers/WebGLManager.js +++ b/src/core/renderers/webgl/managers/WebGLManager.js @@ -3,7 +3,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLManager(renderer) { +function WebGLManager(renderer) +{ /** * The renderer this manager works for. * @@ -15,6 +16,7 @@ WebGLManager.prototype.constructor = WebGLManager; module.exports = WebGLManager; -WebGLManager.prototype.destroy = function () { +WebGLManager.prototype.destroy = function () +{ this.renderer = null; }; diff --git a/src/core/renderers/webgl/managers/WebGLMaskManager.js b/src/core/renderers/webgl/managers/WebGLMaskManager.js index 2f90b64..e568812 100644 --- a/src/core/renderers/webgl/managers/WebGLMaskManager.js +++ b/src/core/renderers/webgl/managers/WebGLMaskManager.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLMaskManager(renderer) { +function WebGLMaskManager(renderer) +{ WebGLManager.call(this, renderer); } @@ -19,12 +20,15 @@ * * @param maskData {any[]} */ -WebGLMaskManager.prototype.pushMask = function (maskData) { - if (maskData.dirty) { +WebGLMaskManager.prototype.pushMask = function (maskData) +{ + if (maskData.dirty) + { WebGLGraphics.updateGraphics(maskData, this.renderer.gl); } - if (!maskData._webGL[this.renderer.gl.id].data.length) { + if (!maskData._webGL[this.renderer.gl.id].data.length) + { return; } @@ -36,6 +40,7 @@ * * @param maskData {any[]} */ -WebGLMaskManager.prototype.popMask = function (maskData) { +WebGLMaskManager.prototype.popMask = function (maskData) +{ this.renderer.stencilManager.popStencil(maskData, maskData._webGL[this.renderer.gl.id].data[0], this.renderer); }; diff --git a/src/core/renderers/webgl/managers/WebGLShaderManager.js b/src/core/renderers/webgl/managers/WebGLShaderManager.js index fef071c..90c6477 100644 --- a/src/core/renderers/webgl/managers/WebGLShaderManager.js +++ b/src/core/renderers/webgl/managers/WebGLShaderManager.js @@ -10,7 +10,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLShaderManager(renderer) { +function WebGLShaderManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -28,7 +29,8 @@ */ this.tempAttribState = []; - for (var i = 0; i < this.maxAttibs; i++) { + for (var i = 0; i < this.maxAttibs; i++) + { this.attribState[i] = false; } @@ -66,7 +68,8 @@ // listen for context and update necessary shaders var self = this; - this.renderer.on('context', function (event) { + this.renderer.on('context', function (event) + { var gl = event.data; // this shader is used for rendering primitives @@ -97,29 +100,36 @@ * * @param attribs {Array} attribs */ -WebGLShaderManager.prototype.setAttribs = function (attribs) { +WebGLShaderManager.prototype.setAttribs = function (attribs) +{ // reset temp state var i; - for (i = 0; i < this.tempAttribState.length; i++) { + for (i = 0; i < this.tempAttribState.length; i++) + { this.tempAttribState[i] = false; } // set the new attribs - for (var a in attribs) { + for (var a in attribs) + { this.tempAttribState[attribs[a]] = true; } var gl = this.renderer.gl; - for (i = 0; i < this.attribState.length; i++) { - if (this.attribState[i] !== this.tempAttribState[i]) { + for (i = 0; i < this.attribState.length; i++) + { + if (this.attribState[i] !== this.tempAttribState[i]) + { this.attribState[i] = this.tempAttribState[i]; - if (this.attribState[i]) { + if (this.attribState[i]) + { gl.enableVertexAttribArray(i); } - else { + else + { gl.disableVertexAttribArray(i); } } @@ -131,8 +141,10 @@ * * @param shader {Any} */ -WebGLShaderManager.prototype.setShader = function (shader) { - if (this._currentId === shader.uuid) { +WebGLShaderManager.prototype.setShader = function (shader) +{ + if (this._currentId === shader.uuid) + { return false; } @@ -150,7 +162,8 @@ * Destroys this object. * */ -WebGLShaderManager.prototype.destroy = function () { +WebGLShaderManager.prototype.destroy = function () +{ this.attribState = null; this.tempAttribState = null; diff --git a/src/core/renderers/webgl/managers/WebGLStencilManager.js b/src/core/renderers/webgl/managers/WebGLStencilManager.js index 9ec6398..4cb0134 100644 --- a/src/core/renderers/webgl/managers/WebGLStencilManager.js +++ b/src/core/renderers/webgl/managers/WebGLStencilManager.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLStencilManager(renderer) { +function WebGLStencilManager(renderer) +{ WebGLManager.call(this, renderer); this.stencilStack = []; @@ -24,12 +25,14 @@ * @param graphics {Graphics} * @param webGLData {any[]} */ -WebGLStencilManager.prototype.pushStencil = function (graphics, webGLData) { +WebGLStencilManager.prototype.pushStencil = function (graphics, webGLData) +{ var gl = this.renderer.gl; this.bindGraphics(graphics, webGLData, this.renderer); - if (this.stencilStack.length === 0) { + if (this.stencilStack.length === 0) + { gl.enable(gl.STENCIL_TEST); gl.clear(gl.STENCIL_BUFFER_BIT); this.reverse = true; @@ -47,14 +50,17 @@ // draw the triangle strip! - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } @@ -62,31 +68,38 @@ // draw a quad to increment.. gl.drawElements(gl.TRIANGLE_FAN, 4, gl.UNSIGNED_SHORT, ( webGLData.indices.length - 4 ) * 2 ); - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); } this.reverse = !this.reverse; } - else { - if (!this.reverse) { + else + { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } - else { + 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) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); } } @@ -103,7 +116,8 @@ * @param graphics {Graphics} * @param webGLData {Array} */ -WebGLStencilManager.prototype.bindGraphics = function (graphics, webGLData) { +WebGLStencilManager.prototype.bindGraphics = function (graphics, webGLData) +{ //if (this._currentGraphics === graphics)return; this._currentGraphics = graphics; @@ -114,7 +128,8 @@ offset = this.renderer.offset, shader;// = this.renderer.shaderManager.primitiveShader; - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { shader = this.renderer.shaderManager.complexPrimitiveShader; this.renderer.shaderManager.setShader(shader); @@ -141,7 +156,8 @@ // set the index buffer! gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, webGLData.indexBuffer); } - else { + else + { //this.renderer.shaderManager.activatePrimitiveShader(); shader = this.renderer.shaderManager.primitiveShader; this.renderer.shaderManager.setShader( shader ); @@ -154,7 +170,7 @@ gl.uniform2f(shader.uniforms.offsetVector._location, -offset.x, -offset.y); gl.uniform3fv(shader.uniforms.tint._location, utils.hex2rgb(graphics.tint)); - + gl.uniform1f(shader.uniforms.alpha._location, graphics.worldAlpha); @@ -172,19 +188,22 @@ * @param graphics {Graphics} * @param webGLData {Array} */ -WebGLStencilManager.prototype.popStencil = function (graphics, webGLData) { +WebGLStencilManager.prototype.popStencil = function (graphics, webGLData) +{ var gl = this.renderer.gl; this.stencilStack.pop(); this.count--; - if (this.stencilStack.length === 0) { + if (this.stencilStack.length === 0) + { // the stack is empty! gl.disable(gl.STENCIL_TEST); } - else { + else + { var level = this.count; @@ -192,14 +211,17 @@ gl.colorMask(false, false, false, false); - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { this.reverse = !this.reverse; - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } @@ -213,31 +235,38 @@ // draw the triangle strip! gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); - if (!this.reverse) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); } } - else { + else + { // console.log("<<>>") - if (!this.reverse) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } - else { + 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) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); } } @@ -253,7 +282,8 @@ * Destroys the mask stack. * */ -WebGLStencilManager.prototype.destroy = function () { +WebGLStencilManager.prototype.destroy = function () +{ this.renderer = null; this.stencilStack = null; }; diff --git a/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js b/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js index 913ba5e..1ea7d19 100644 --- a/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js +++ b/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function ComplexPrimitiveShader(gl) { +function ComplexPrimitiveShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -24,7 +25,8 @@ 'uniform float flipY;', 'varying vec4 vColor;', - 'void main(void) {', + '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);', @@ -37,7 +39,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = vColor;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/FastShader.js b/src/core/renderers/webgl/shaders/FastShader.js index bd2e29a..2e5e060 100644 --- a/src/core/renderers/webgl/shaders/FastShader.js +++ b/src/core/renderers/webgl/shaders/FastShader.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function FastShader(gl) { +function FastShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -28,7 +29,8 @@ 'const vec2 center = vec2(-1.0, 1.0);', - 'void main(void) {', + 'void main(void) + {', ' vec2 v;', ' vec2 sv = aVertexPosition * aScale;', ' v.x = (sv.x) * cos(aRotation) - (sv.y) * sin(aRotation);', @@ -49,7 +51,8 @@ 'uniform sampler2D uSampler;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/PrimitiveShader.js b/src/core/renderers/webgl/shaders/PrimitiveShader.js index 6f25409..a25f54f 100644 --- a/src/core/renderers/webgl/shaders/PrimitiveShader.js +++ b/src/core/renderers/webgl/shaders/PrimitiveShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function PrimitiveShader(gl) { +function PrimitiveShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -23,7 +24,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + '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);', @@ -36,7 +38,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = vColor;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/Shader.js b/src/core/renderers/webgl/shaders/Shader.js index f8964f5..fd75ef5 100644 --- a/src/core/renderers/webgl/shaders/Shader.js +++ b/src/core/renderers/webgl/shaders/Shader.js @@ -6,7 +6,8 @@ * @param [fragmentSrc] {string} The source of the fragment shader. * @param [vertexSrc] {string} The source of the vertex shader. */ -function Shader(gl, vertexSrc, fragmentSrc, customUniforms, customAttributes) { +function Shader(gl, vertexSrc, fragmentSrc, customUniforms, customAttributes) +{ /** * @member {number} * @readonly @@ -33,7 +34,8 @@ dimensions: { type: '4f', value: new Float32Array(4) } }; - for (var u in customUniforms) { + for (var u in customUniforms) + { this.uniforms[u] = customUniforms[u]; } @@ -43,7 +45,8 @@ aColor: 0 }; - for (var a in customAttributes) { + for (var a in customAttributes) + { this.attributes[a] = customAttributes[a]; } @@ -66,7 +69,8 @@ 'const vec2 center = vec2(-1.0, 1.0);', - 'void main(void) {', + 'void main(void) + {', ' gl_Position = vec4( ((aVertexPosition + offsetVector) / projectionVector) + center , 0.0, 1.0);', ' vTextureCoord = aTextureCoord;', ' vColor = vec4(aColor.rgb * aColor.a, aColor.a);', @@ -85,7 +89,8 @@ 'uniform sampler2D uSampler;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;', '}' ].join('\n'); @@ -96,7 +101,8 @@ Shader.prototype.constructor = Shader; module.exports = Shader; -Shader.prototype.init = function () { +Shader.prototype.init = function () +{ this.compile(); this.gl.useProgram(this.program); @@ -105,14 +111,18 @@ this.cacheAttributeLocations(Object.keys(this.attributes)); }; -Shader.prototype.cacheUniformLocations = function (keys) { - for (var i = 0; i < keys.length; ++i) { +Shader.prototype.cacheUniformLocations = function (keys) +{ + for (var i = 0; i < keys.length; ++i) + { this.uniforms[keys[i]]._location = this.gl.getUniformLocation(this.program, keys[i]); } }; -Shader.prototype.cacheAttributeLocations = function (keys) { - for (var i = 0; i < keys.length; ++i) { +Shader.prototype.cacheAttributeLocations = function (keys) +{ + for (var i = 0; i < keys.length; ++i) + { this.attributes[keys[i]] = this.gl.getAttribLocation(this.program, keys[i]); } @@ -124,14 +134,16 @@ // 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.attributes.aColor === -1) { + // if (this.attributes.aColor === -1) + { // this.attributes.aColor = 2; // } // End worst hack eva // }; -Shader.prototype.compile = function () { +Shader.prototype.compile = function () +{ var gl = this.gl; var glVertShader = this._glCompile(gl.VERTEX_SHADER, this.vertexSrc); @@ -144,13 +156,15 @@ gl.linkProgram(program); // if linking fails, then log and cleanup - if (!gl.getProgramParameter(program, gl.LINK_STATUS)) { + if (!gl.getProgramParameter(program, gl.LINK_STATUS)) + { window.console.error('Pixi.js Error: Could not initialize shader.'); window.console.error('gl.VALIDATE_STATUS', gl.getProgramParameter(program, gl.VALIDATE_STATUS)); window.console.error('gl.getError()', gl.getError()); // if there is a program info log, log it - if (gl.getProgramInfoLog(program) !== '') { + if (gl.getProgramInfoLog(program) !== '') + { window.console.warn('Pixi.js Warning: gl.getProgramInfoLog()', gl.getProgramInfoLog(program)); } @@ -165,18 +179,21 @@ return (this.program = program); }; -Shader.prototype.syncUniforms = function () { +Shader.prototype.syncUniforms = function () +{ var gl = this.gl; this.textureCount = 1; - for (var key in this.uniforms) { + for (var key in this.uniforms) + { var uniform = this.uniforms[key], location = uniform._location, value = uniform.value, i, il; - switch (uniform.type) { + switch (uniform.type) + { // single int value case 'i': case '1i': @@ -282,7 +299,8 @@ // a Color Value case 'c': - if (typeof value === 'number') { + if (typeof value === 'number') + { value = utils.hex2rgb(value); } @@ -311,11 +329,13 @@ // array of 2D Point objects case 'v2v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(2 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 2] = value[i].x; uniform._array[i * 2 + 1] = value[i].y; } @@ -325,11 +345,13 @@ // array of 3D Point objects case 'v3v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(3 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 3] = value[i].x; uniform._array[i * 3 + 1] = value[i].y; uniform._array[i * 3 + 2] = value[i].z; @@ -341,11 +363,13 @@ // array of 4D Point objects case 'v4v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(4 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 4] = value[i].x; uniform._array[i * 4 + 1] = value[i].y; uniform._array[i * 4 + 2] = value[i].z; @@ -359,7 +383,8 @@ // PIXI.Texture case 't': case 'sampler2D': - if (!uniform.value || !uniform.value.baseTexture || !uniform.value.baseTexture.hasLoaded) { + if (!uniform.value || !uniform.value.baseTexture || !uniform.value.baseTexture.hasLoaded) + { break; } @@ -376,7 +401,8 @@ this.textureCount++; // initialize the texture if we haven't yet - if (!uniform._init) { + if (!uniform._init) + { this.initSampler2D(uniform); uniform._init = true; @@ -394,11 +420,13 @@ * Initialises a Sampler2D uniform (which may only be available later on after initUniforms once the texture has loaded) * */ -Shader.prototype.initSampler2D = function (uniform) { +Shader.prototype.initSampler2D = function (uniform) +{ var gl = this.gl; // Extended texture data - if (uniform.textureData) { + if (uniform.textureData) + { var data = uniform.textureData; // GLTexture = mag linear, min linear_mipmap_linear, wrap repeat + gl.generateMipmap(gl.TEXTURE_2D); @@ -417,14 +445,16 @@ var wrapT = (data.wrapT) ? data.wrapT : gl.CLAMP_TO_EDGE; var format = (data.luminance) ? gl.LUMINANCE : gl.RGBA; - if (data.repeat) { + if (data.repeat) + { wrapS = gl.REPEAT; wrapT = gl.REPEAT; } gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, !!data.flipY); - if (data.width) { + if (data.width) + { var width = (data.width) ? data.width : 512; var height = (data.height) ? data.height : 2; var border = (data.border) ? data.border : 0; @@ -432,7 +462,8 @@ // 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 { + 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); } @@ -448,7 +479,8 @@ * Destroys the shader. * */ -Shader.prototype.destroy = function () { +Shader.prototype.destroy = function () +{ this.gl.deleteProgram(this.program); this.gl = null; @@ -459,13 +491,15 @@ this.fragmentSrc = null; }; -Shader.prototype._glCompile = function (type, src) { +Shader.prototype._glCompile = function (type, src) +{ var shader = this.gl.createShader(type); this.gl.shaderSource(shader, src); this.gl.compileShader(shader); - if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) { + if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) + { window.console.log(this.gl.getShaderInfoLog(shader)); return null; } diff --git a/src/core/display/DisplayObject.js b/src/core/display/DisplayObject.js index 66ebc3c..20e778c 100644 --- a/src/core/display/DisplayObject.js +++ b/src/core/display/DisplayObject.js @@ -7,7 +7,8 @@ * @class * @namespace PIXI */ -function DisplayObject() { +function DisplayObject() +{ /** * The coordinate of the object relative to the local coordinates of the parent. * @@ -152,10 +153,12 @@ * @memberof DisplayObject# */ x: { - get: function () { + get: function () + { return this.position.x; }, - set: function (value) { + set: function (value) + { this.position.x = value; } }, @@ -167,10 +170,12 @@ * @memberof DisplayObject# */ y: { - get: function () { + get: function () + { return this.position.y; }, - set: function (value) { + set: function (value) + { this.position.y = value; } }, @@ -183,11 +188,13 @@ * @readonly */ worldVisible: { - get: function () { + get: function () + { var item = this; do { - if (!item.visible) { + if (!item.visible) + { return false; } @@ -207,17 +214,21 @@ * @memberof DisplayObject# */ mask: { - get: function () { + get: function () + { return this._mask; }, - set: function (value) { - if (this._mask) { + set: function (value) + { + if (this._mask) + { this._mask.isMask = false; } this._mask = value; - if (this._mask) { + if (this._mask) + { this._mask.isMask = true; } } @@ -232,18 +243,23 @@ * @memberof DisplayObject# */ filters: { - get: function () { + get: function () + { return this._filters; }, - set: function (value) { - if (value) { + set: function (value) + { + if (value) + { // now put all the passes in one place.. var passes = []; - for (var i = 0; i < value.length; i++) { + for (var i = 0; i < value.length; i++) + { var filterPasses = value[i].passes; - for (var j = 0; j < filterPasses.length; j++) { + for (var j = 0; j < filterPasses.length; j++) + { passes.push(filterPasses[j]); } } @@ -264,8 +280,9 @@ * * @private */ -DisplayObject.prototype.updateTransform = function () { - +DisplayObject.prototype.updateTransform = function () +{ + // create some matrix refs for easy access var pt = this.parent.worldTransform; var wt = this.worldTransform; @@ -274,9 +291,11 @@ var a, b, c, d, tx, ty; // so if rotation is between 0 then we can simplify the multiplication process.. - if (this.rotation % math.PI_2) { + if (this.rotation % math.PI_2) + { // 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) { + if (this.rotation !== this.rotationCache) + { this.rotationCache = this.rotation; this._sr = Math.sin(this.rotation); this._cr = Math.cos(this.rotation); @@ -291,7 +310,8 @@ ty = this.position.y; // check for pivot.. not often used so geared towards that fact! - if (this.pivot.x || this.pivot.y) { + 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; } @@ -304,7 +324,8 @@ wt.tx = tx * pt.a + ty * pt.c + pt.tx; wt.ty = tx * pt.b + ty * pt.d + pt.ty; } - else { + else + { // lets do the fast version as we know there is no rotation.. a = this.scale.x; d = this.scale.y; @@ -333,7 +354,8 @@ * @param matrix {Matrix} * @return {Rectangle} the rectangular bounding area */ -DisplayObject.prototype.getBounds = function (/* matrix */) { +DisplayObject.prototype.getBounds = function (/* matrix */) +{ return math.Rectangle.EMPTY; }; @@ -342,7 +364,8 @@ * * @return {Rectangle} the rectangular bounding area */ -DisplayObject.prototype.getLocalBounds = function () { +DisplayObject.prototype.getLocalBounds = function () +{ return this.getBounds(math.Matrix.IDENTITY); }; @@ -352,7 +375,8 @@ * @param position {Point} The world origin to calculate from * @return {Point} A point object representing the position of this object */ -DisplayObject.prototype.toGlobal = function (position) { +DisplayObject.prototype.toGlobal = function (position) +{ // don't need to u[date the lot this.displayObjectUpdateTransform(); return this.worldTransform.apply(position); @@ -365,8 +389,10 @@ * @param [from] {DisplayObject} The DisplayObject to calculate the global position from * @return {Point} A point object representing the position of this object */ -DisplayObject.prototype.toLocal = function (position, from) { - if (from) { +DisplayObject.prototype.toLocal = function (position, from) +{ + if (from) + { position = from.toGlobal(position); } @@ -381,7 +407,8 @@ * @param renderer {WebGLRenderer} The renderer * @private */ -DisplayObject.prototype.renderWebGL = function (/* renderer */) { +DisplayObject.prototype.renderWebGL = function (/* renderer */) +{ // OVERWRITE; }; @@ -391,6 +418,7 @@ * @param renderer {CanvasRenderer} The renderer * @private */ -DisplayObject.prototype.renderCanvas = function (/* renderer */) { +DisplayObject.prototype.renderCanvas = function (/* renderer */) +{ // OVERWRITE; }; diff --git a/src/core/display/DisplayObjectContainer.js b/src/core/display/DisplayObjectContainer.js index 689f40b..4625ee8 100644 --- a/src/core/display/DisplayObjectContainer.js +++ b/src/core/display/DisplayObjectContainer.js @@ -12,7 +12,8 @@ * @extends DisplayObject * @namespace PIXI */ -function DisplayObjectContainer() { +function DisplayObjectContainer() +{ DisplayObject.call(this); /** @@ -47,17 +48,21 @@ * @memberof DisplayObjectContainer# */ width: { - get: function () { + get: function () + { return this.scale.x * this.getLocalBounds().width; }, - set: function (value) { + set: function (value) + { var width = this.getLocalBounds().width; - if(width !== 0) { + if(width !== 0) + { this.scale.x = value / width; } - else { + else + { this.scale.x = 1; } @@ -73,17 +78,21 @@ * @memberof DisplayObjectContainer# */ height: { - get: function () { + get: function () + { return this.scale.y * this.getLocalBounds().height; }, - set: function (value) { + set: function (value) + { var height = this.getLocalBounds().height; - if (height !== 0) { + if (height !== 0) + { this.scale.y = value / height ; } - else { + else + { this.scale.y = 1; } @@ -100,18 +109,23 @@ * @memberof DisplayObject# */ cacheAsBitmap: { - get: function () { + get: function () + { return this._cacheAsBitmap; }, - set: function (value) { - if (this._cacheAsBitmap === value) { + set: function (value) + { + if (this._cacheAsBitmap === value) + { return; } - if (value) { + if (value) + { this._generateCachedSprite(); } - else { + else + { this._destroyCachedSprite(); } @@ -126,7 +140,8 @@ * @param child {DisplayObject} The DisplayObject to add to the container * @return {DisplayObject} The child that was added. */ -DisplayObjectContainer.prototype.addChild = function (child) { +DisplayObjectContainer.prototype.addChild = function (child) +{ return this.addChildAt(child, this.children.length); }; @@ -137,14 +152,18 @@ * @param index {Number} The index to place the child in * @return {DisplayObject} The child that was added. */ -DisplayObjectContainer.prototype.addChildAt = function (child, index) { +DisplayObjectContainer.prototype.addChildAt = function (child, index) +{ // prevent adding self as child - if (child === this) { + if (child === this) + { return; } - if (index >= 0 && index <= this.children.length) { - if (child.parent) { + if (index >= 0 && index <= this.children.length) + { + if (child.parent) + { child.parent.removeChild(child); } @@ -154,7 +173,8 @@ return child; } - else { + else + { throw new Error(child + 'addChildAt: The index '+ index +' supplied is out of bounds ' + this.children.length); } }; @@ -165,15 +185,18 @@ * @param child {DisplayObject} * @param child2 {DisplayObject} */ -DisplayObjectContainer.prototype.swapChildren = function (child, child2) { - if (child === child2) { +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) { + if (index1 < 0 || index2 < 0) + { throw new Error('swapChildren: Both the supplied DisplayObjects must be a child of the caller.'); } @@ -187,10 +210,12 @@ * @param child {DisplayObject} The DisplayObject instance to identify * @return {Number} The index position of the child display object to identify */ -DisplayObjectContainer.prototype.getChildIndex = function (child) { +DisplayObjectContainer.prototype.getChildIndex = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { throw new Error('The supplied DisplayObject must be a child of the caller'); } @@ -203,8 +228,10 @@ * @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 */ -DisplayObjectContainer.prototype.setChildIndex = function (child, index) { - if (index < 0 || index >= this.children.length) { +DisplayObjectContainer.prototype.setChildIndex = function (child, index) +{ + if (index < 0 || index >= this.children.length) + { throw new Error('The supplied index is out of bounds'); } @@ -220,8 +247,10 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child at the given index, if any. */ -DisplayObjectContainer.prototype.getChildAt = function (index) { - if (index < 0 || index >= this.children.length) { +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'); } @@ -234,10 +263,12 @@ * @param child {DisplayObject} The DisplayObject to remove * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChild = function (child) { +DisplayObjectContainer.prototype.removeChild = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { return; } @@ -250,7 +281,8 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChildAt = function (index) { +DisplayObjectContainer.prototype.removeChildAt = function (index) +{ var child = this.getChildAt(index); child.parent = null; @@ -265,24 +297,29 @@ * @param beginIndex {Number} The beginning position. Default value is 0. * @param endIndex {Number} The ending position. Default value is size of the container. */ -DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) { +DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) +{ var begin = beginIndex || 0; var end = typeof endIndex === 'number' ? endIndex : this.children.length; var range = end - begin; - if (range > 0 && range <= end) { + if (range > 0 && range <= end) + { var removed = this.children.splice(begin, range); - for (var i = 0; i < removed.length; ++i) { + for (var i = 0; i < removed.length; ++i) + { removed[i].parent = null; } return removed; } - else if (range === 0 && this.children.length === 0) { + else if (range === 0 && this.children.length === 0) + { return []; } - else { + else + { throw new RangeError('removeChildren: numeric values are outside the acceptable range.'); } }; @@ -291,7 +328,8 @@ * Generates and updates the cached sprite for this object. * */ -DisplayObjectContainer.prototype.updateCachedSprite = function () { +DisplayObjectContainer.prototype.updateCachedSprite = function () +{ this._generateCachedSprite(); }; @@ -304,7 +342,8 @@ * @param renderer {CanvasRenderer|WebGLRenderer} The renderer used to generate the texture. * @return {Texture} a texture of the graphics object */ -DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) { +DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) +{ var bounds = this.getLocalBounds(); var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0, renderer, scaleMode, resolution); @@ -322,18 +361,22 @@ * * @private */ -DisplayObjectContainer.prototype.updateTransform = function () { - if (!this.visible) { +DisplayObjectContainer.prototype.updateTransform = function () +{ + if (!this.visible) + { return; } this.displayObjectUpdateTransform(); - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { return; } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } }; @@ -346,8 +389,10 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getBounds = function () { - if (this.children.length === 0) { +DisplayObjectContainer.prototype.getBounds = function () +{ + if (this.children.length === 0) + { return math.Rectangle.EMPTY; } @@ -365,10 +410,12 @@ var childVisible = false; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -386,7 +433,8 @@ maxY = maxY > childMaxY ? maxY : childMaxY; } - if (!childVisible) { + if (!childVisible) + { return math.Rectangle.EMPTY; } @@ -407,12 +455,14 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getLocalBounds = function () { +DisplayObjectContainer.prototype.getLocalBounds = function () +{ var matrixCache = this.worldTransform; this.worldTransform = math.Matrix.IDENTITY; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } @@ -428,13 +478,16 @@ * * @param renderer {WebGLRenderer} The renderer */ -DisplayObjectContainer.prototype.renderWebGL = function (renderer) { +DisplayObjectContainer.prototype.renderWebGL = function (renderer) +{ // if the object is not visible or the alpha is 0 then no need to render this element - if (!this.visible || this.alpha <= 0) { + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } @@ -442,14 +495,17 @@ var i, j; // do a quick check to see if this element has a mask or a filter. - if (this._mask || this._filters) { + if (this._mask || this._filters) + { // push filter first as we need to ensure the stencil buffer is correct for any masking - if (this._filters) { + if (this._filters) + { renderer.spriteBatch.flush(); renderer.filterManager.pushFilter(this._filterBlock); } - if (this._mask) { + if (this._mask) + { renderer.spriteBatch.stop(); renderer.maskManager.pushMask(this.mask, renderer); renderer.spriteBatch.start(); @@ -459,36 +515,42 @@ this._renderWebGL(renderer); // now loop through the children and make sure they get rendered - for (i = 0, j = this.children.length; i < j; i++) { + for (i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderWebGL(renderer); } // time to stop the sprite batch as either a mask element or a filter draw will happen next renderer.spriteBatch.stop(); - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(this._mask, renderer); } - if (this._filters) { + if (this._filters) + { renderer.filterManager.popFilter(); } renderer.spriteBatch.start(); } - else { + else + { this._renderWebGL(renderer); // simple render children! - for (i = 0, j = this.children.length; i < j; ++i) { + for (i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderWebGL(renderer); } } }; -DisplayObjectContainer.prototype._renderWebGL = function (renderer) { +DisplayObjectContainer.prototype._renderWebGL = function (renderer) +{ // this is where content itself gets renderd.. @@ -499,25 +561,31 @@ * * @param renderer {CanvasRenderer} The renderer */ -DisplayObjectContainer.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0) { +DisplayObjectContainer.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -528,13 +596,16 @@ * @param renderer {WebGLRenderer|CanvasRenderer} The renderer * @private */ -DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) { +DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) +{ this._cachedSprite.worldAlpha = this.worldAlpha; - if (renderer.gl) { + if (renderer.gl) + { this._cachedSprite.renderWebGL(renderer); } - else { + else + { this._cachedSprite.renderCanvas(renderer); } }; @@ -544,10 +615,12 @@ * * @private */ -DisplayObjectContainer.prototype._generateCachedSprite = function () { +DisplayObjectContainer.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { // TODO - RenderTexture now *requires* a renderer instance, so this is like broken // because `renderer` isn't actually in scope here :P var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0); @@ -555,7 +628,8 @@ this._cachedSprite = new Sprite(renderTexture); this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.texture.resize(bounds.width | 0, bounds.height | 0); } @@ -580,8 +654,10 @@ * * @private */ -DisplayObjectContainer.prototype._destroyCachedSprite = function () { - if (!this._cachedSprite) { +DisplayObjectContainer.prototype._destroyCachedSprite = function () +{ + if (!this._cachedSprite) + { return; } diff --git a/src/core/display/Sprite.js b/src/core/display/Sprite.js index 707da24..5862aef 100644 --- a/src/core/display/Sprite.js +++ b/src/core/display/Sprite.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param texture {Texture} The texture for this sprite */ -function Sprite(texture) { +function Sprite(texture) +{ DisplayObjectContainer.call(this); /** @@ -85,12 +86,14 @@ this.texture = texture || Texture.EMPTY; } -Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) { +Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) +{ DisplayObjectContainer.prototype.destroy.call(this); this.anchor = null; - if (destroyTexture) { + if (destroyTexture) + { this._texture.destroy(destroyBaseTexture); } @@ -111,10 +114,12 @@ * @memberof Sprite# */ width: { - get: function () { + get: function () + { return this.scale.x * this.texture.frame.width; }, - set: function (value) { + set: function (value) + { this.scale.x = value / this.texture.frame.width; this._width = value; } @@ -127,10 +132,12 @@ * @memberof Sprite# */ height: { - get: function () { + get: function () + { return this.scale.y * this.texture.frame.height; }, - set: function (value) { + set: function (value) + { this.scale.y = value / this.texture.frame.height; this._height = value; } @@ -143,23 +150,29 @@ * @memberof Sprite# */ texture: { - get: function () { + get: function () + { return this._texture; }, - set: function (value) { - if (this._texture === value) { + set: function (value) + { + if (this._texture === value) + { return; } this._texture = value; this.cachedTint = 0xFFFFFF; - if (value) { + if (value) + { // wait for the texture to load - if (value.baseTexture.hasLoaded) { + if (value.baseTexture.hasLoaded) + { this._onTextureUpdate(); } - else { + else + { value.once('update', this._onTextureUpdate.bind(this)); } } @@ -172,18 +185,22 @@ * * @private */ -Sprite.prototype._onTextureUpdate = function () { +Sprite.prototype._onTextureUpdate = function () +{ // so if _width is 0 then width was not set.. - if (this._width) { + if (this._width) + { this.scale.x = this._width / this.texture.frame.width; } - if (this._height) { + if (this._height) + { this.scale.y = this._height / this.texture.frame.height; } }; -Sprite.prototype._renderWebGL = function (renderer) { +Sprite.prototype._renderWebGL = function (renderer) +{ // this is where content gets renderd.. // watch this space for a little render state manager.. @@ -197,7 +214,8 @@ * @param matrix {Matrix} the transformation matrix of the sprite * @return {Rectangle} the framing rectangle */ -Sprite.prototype.getBounds = function (matrix) { +Sprite.prototype.getBounds = function (matrix) +{ var width = this.texture.frame.width; var height = this.texture.frame.height; @@ -224,11 +242,13 @@ if(b === 0 && c === 0) { // scale may be negative! - if (a < 0) { + if (a < 0) + { a *= -1; } - if (d < 0) { + if (d < 0) + { d *= -1; } @@ -293,28 +313,34 @@ * * @param renderer {CanvasRenderer} The renderer */ -Sprite.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) { +Sprite.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) + { return; } - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; renderer.context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } // Ignore null sources - if (this.texture.valid) { + if (this.texture.valid) + { var resolution = this.texture.baseTexture.resolution / renderer.resolution; renderer.context.globalAlpha = this.worldAlpha; // If smoothingEnabled is supported and we need to change the smoothing property for this texture - if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) { + if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) + { renderer.scaleMode = this.texture.baseTexture.scaleMode; renderer.context[renderer.smoothProperty] = (renderer.scaleMode === CONST.scaleModes.LINEAR); } @@ -324,7 +350,8 @@ var dy = (this.texture.trim ? this.texture.trim.y : 0) - (this.anchor.y * this.texture.trim.height); // Allow for pixel rounding - if (renderer.roundPixels) { + if (renderer.roundPixels) + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -337,7 +364,8 @@ dx = dx | 0; dy = dy | 0; } - else { + else + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -348,8 +376,10 @@ ); } - if (this.tint !== 0xFFFFFF) { - if (this.cachedTint !== this.tint) { + if (this.tint !== 0xFFFFFF) + { + if (this.cachedTint !== this.tint) + { this.cachedTint = this.tint; // TODO clean up caching - how to clean up the caches? @@ -368,7 +398,8 @@ this.texture.crop.height / resolution ); } - else { + else + { renderer.context.drawImage( this.texture.baseTexture.source, this.texture.crop.x, @@ -383,11 +414,13 @@ } } - for (var i = 0, j = this.children.length; i < j; i++) { + for (var i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -402,10 +435,12 @@ * @param frameId {String} The frame Id of the texture in the cache * @return {Sprite} A new Sprite using a texture from the texture cache matching the frameId */ -Sprite.fromFrame = function (frameId) { +Sprite.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache' + this); } @@ -420,6 +455,7 @@ * @param imageId {String} The image url of the texture * @return {Sprite} A new Sprite using a texture from the texture cache matching the image id */ -Sprite.fromImage = function (imageId, crossorigin, scaleMode) { +Sprite.fromImage = function (imageId, crossorigin, scaleMode) +{ return new Sprite(Texture.fromImage(imageId, crossorigin, scaleMode)); }; diff --git a/src/core/display/SpriteBatch.js b/src/core/display/SpriteBatch.js index 3187777..c196fef 100644 --- a/src/core/display/SpriteBatch.js +++ b/src/core/display/SpriteBatch.js @@ -12,7 +12,8 @@ * ```js * var container = new SpriteBatch(); * - * for(var i = 0; i < 100; ++i) { + * for(var i = 0; i < 100; ++i) + * { * var sprite = new PIXI.Sprite.fromImage("myImage.png"); * container.addChild(sprite); * } @@ -25,7 +26,8 @@ */ //TODO RENAME to PARTICLE CONTAINER? -function SpriteBatch() { +function SpriteBatch() +{ DisplayObjectContainer.call(this); } @@ -38,7 +40,8 @@ * * @private */ -SpriteBatch.prototype.updateTransform = function () { +SpriteBatch.prototype.updateTransform = function () +{ // TODO don't need to! this.displayObjectUpdateTransform(); // PIXI.DisplayObjectContainer.prototype.updateTransform.call( this ); @@ -50,8 +53,10 @@ * @param renderer {WebGLRenderer} The webgl renderer * @private */ -SpriteBatch.prototype.renderWebGL = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderWebGL = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -71,8 +76,10 @@ * @param renderer {CanvasRenderer} The canvas renderer * @private */ -SpriteBatch.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -84,10 +91,12 @@ this.displayObjectUpdateTransform(); - for (var i = 0; i < this.children.length; ++i) { + for (var i = 0; i < this.children.length; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -95,9 +104,11 @@ context.globalAlpha = this.worldAlpha * child.alpha; - if (child.rotation % (Math.PI * 2) === 0) { + if (child.rotation % (Math.PI * 2) === 0) + { // this is the fastest way to optimise! - if rotation is 0 then we can avoid any kind of setTransform call - if (isRotated) { + if (isRotated) + { context.setTransform( transform.a, transform.b, @@ -122,8 +133,10 @@ frame.height * child.scale.y ); } - else { - if (!isRotated) { + else + { + if (!isRotated) + { isRotated = true; } @@ -131,7 +144,8 @@ var childTransform = child.worldTransform; - if (renderer.roundPixels) { + if (renderer.roundPixels) + { context.setTransform( childTransform.a, childTransform.b, @@ -141,7 +155,8 @@ childTransform.ty | 0 ); } - else { + else + { context.setTransform( childTransform.a, childTransform.b, diff --git a/src/core/index.js b/src/core/index.js index 3954b6f..eb4a82b 100644 --- a/src/core/index.js +++ b/src/core/index.js @@ -58,11 +58,13 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRenderer: function (width, height, options, noWebGL) { + autoDetectRenderer: function (width, height, options, noWebGL) + { width = width || 800; height = height || 600; - if (!noWebGL && require('webgl-enabled')()) { + if (!noWebGL && require('webgl-enabled')()) + { return new core.WebGLRenderer(width, height, options); } @@ -87,7 +89,8 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRecommendedRenderer: function (width, height, options) { + autoDetectRecommendedRenderer: function (width, height, options) + { var isAndroid = /Android/i.test(navigator.userAgent); return core.autoDetectRenderer(width, height, options, isAndroid); diff --git a/src/core/math/Matrix.js b/src/core/math/Matrix.js index c2f87e2..2ff4848 100644 --- a/src/core/math/Matrix.js +++ b/src/core/math/Matrix.js @@ -10,7 +10,8 @@ * @class * @namespace PIXI */ -function Matrix() { +function Matrix() +{ /** * @member {number} * @default 1 @@ -63,7 +64,8 @@ * * @param array {number[]} The array that the matrix will be populated from. */ -Matrix.prototype.fromArray = function (array) { +Matrix.prototype.fromArray = function (array) +{ this.a = array[0]; this.b = array[1]; this.c = array[3]; @@ -78,14 +80,17 @@ * @param transpose {boolean} Whether we need to transpose the matrix or not * @return {number[]} the newly created array which contains the matrix */ -Matrix.prototype.toArray = function (transpose) { - if (!this.array) { +Matrix.prototype.toArray = function (transpose) +{ + if (!this.array) + { this.array = new Float32Array(9); } var array = this.array; - if (transpose) { + if (transpose) + { array[0] = this.a; array[1] = this.b; array[2] = 0; @@ -96,7 +101,8 @@ array[7] = this.ty; array[8] = 1; } - else { + else + { array[0] = this.a; array[1] = this.c; array[2] = this.tx; @@ -119,7 +125,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, transformed through this matrix */ -Matrix.prototype.apply = function (pos, newPos) { +Matrix.prototype.apply = function (pos, newPos) +{ newPos = newPos || new Point(); newPos.x = this.a * pos.x + this.c * pos.y + this.tx; @@ -136,7 +143,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, inverse-transformed through this matrix */ -Matrix.prototype.applyInverse = function (pos, newPos) { +Matrix.prototype.applyInverse = function (pos, newPos) +{ newPos = newPos || new Point(); var id = 1 / (this.a * this.d + this.c * -this.b); @@ -154,7 +162,8 @@ * @param {number} y * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.translate = function (x, y) { +Matrix.prototype.translate = function (x, y) +{ this.tx += x; this.ty += y; @@ -168,7 +177,8 @@ * @param {number} y The amount to scale vertically * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.scale = function (x, y) { +Matrix.prototype.scale = function (x, y) +{ this.a *= x; this.d *= y; this.c *= x; @@ -186,7 +196,8 @@ * @param {number} angle - The angle in radians. * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.rotate = function (angle) { +Matrix.prototype.rotate = function (angle) +{ var cos = Math.cos( angle ); var sin = Math.sin( angle ); @@ -210,7 +221,8 @@ * @param {Matrix} matrix * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.append = function (matrix) { +Matrix.prototype.append = function (matrix) +{ var a1 = this.a; var b1 = this.b; var c1 = this.c; @@ -232,7 +244,8 @@ * * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.identity = function () { +Matrix.prototype.identity = function () +{ this.a = 1; this.b = 0; this.c = 0; diff --git a/src/core/math/Point.js b/src/core/math/Point.js index 7565b2d..632f346 100644 --- a/src/core/math/Point.js +++ b/src/core/math/Point.js @@ -7,7 +7,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -function Point(x, y) { +function Point(x, y) +{ /** * @member {number} * @default 0 @@ -29,7 +30,8 @@ * * @return {Point} a copy of the point */ -Point.prototype.clone = function () { +Point.prototype.clone = function () +{ return new Point(this.x, this.y); }; @@ -40,7 +42,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -Point.prototype.set = function (x, y) { +Point.prototype.set = function (x, y) +{ this.x = x || 0; this.y = y || ( (y !== 0) ? this.x : 0 ) ; }; diff --git a/src/core/math/shapes/Circle.js b/src/core/math/shapes/Circle.js index 69cfdc9..4d76efc 100644 --- a/src/core/math/shapes/Circle.js +++ b/src/core/math/shapes/Circle.js @@ -10,7 +10,8 @@ * @param y {number} The Y coordinate of the center of this circle * @param radius {number} The radius of the circle */ -function Circle(x, y, radius) { +function Circle(x, y, radius) +{ /** * @member {number} * @default 0 @@ -46,7 +47,8 @@ * @method clone * @return {Circle} a copy of the Circle */ -Circle.prototype.clone = function () { +Circle.prototype.clone = function () +{ return new Circle(this.x, this.y, this.radius); }; @@ -58,8 +60,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Circle */ -Circle.prototype.contains = function (x, y) { - if (this.radius <= 0) { +Circle.prototype.contains = function (x, y) +{ + if (this.radius <= 0) + { return false; } @@ -79,6 +83,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Circle.prototype.getBounds = function () { +Circle.prototype.getBounds = function () +{ return new Rectangle(this.x - this.radius, this.y - this.radius, this.radius * 2, this.radius * 2); }; diff --git a/src/core/math/shapes/Ellipse.js b/src/core/math/shapes/Ellipse.js index 4f2d066..fefd01a 100644 --- a/src/core/math/shapes/Ellipse.js +++ b/src/core/math/shapes/Ellipse.js @@ -11,7 +11,8 @@ * @param width {number} The half width of this ellipse * @param height {number} The half height of this ellipse */ -function Ellipse(x, y, width, height) { +function Ellipse(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -53,7 +54,8 @@ * @method clone * @return {Ellipse} a copy of the ellipse */ -Ellipse.prototype.clone = function () { +Ellipse.prototype.clone = function () +{ return new Ellipse(this.x, this.y, this.width, this.height); }; @@ -65,8 +67,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coords are within this ellipse */ -Ellipse.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Ellipse.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } @@ -86,6 +90,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Ellipse.prototype.getBounds = function () { +Ellipse.prototype.getBounds = function () +{ return new Rectangle(this.x - this.width, this.y - this.height, this.width, this.height); }; diff --git a/src/core/math/shapes/Polygon.js b/src/core/math/shapes/Polygon.js index ae89148..fea6d37 100644 --- a/src/core/math/shapes/Polygon.js +++ b/src/core/math/shapes/Polygon.js @@ -10,16 +10,20 @@ * arguments passed can be flat x,y values e.g. `new Polygon(x,y, x,y, x,y, ...)` where `x` and `y` are * Numbers. */ -function Polygon(points) { +function Polygon(points) +{ //if points isn't an array, use arguments as the array - if (!(points instanceof Array)) { + if (!(points instanceof Array)) + { points = Array.prototype.slice.call(arguments); } //if this is a flat array of numbers, convert it to points - if (points[0] instanceof Point) { + if (points[0] instanceof Point) + { var p = []; - for (var i = 0, il = points.length; i < il; i++) { + for (var i = 0, il = points.length; i < il; i++) + { p.push(points[i].x, points[i].y); } @@ -51,7 +55,8 @@ * * @return {Polygon} a copy of the polygon */ -Polygon.prototype.clone = function () { +Polygon.prototype.clone = function () +{ return new Polygon(this.points.slice()); }; @@ -62,19 +67,22 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this polygon */ -Polygon.prototype.contains = function (x, y) { +Polygon.prototype.contains = function (x, y) +{ var inside = false; // use some raycasting to test hits // https://github.com/substack/point-in-polygon/blob/master/index.js var length = this.points.length / 2; - for (var i = 0, j = length - 1; i < length; j = i++) { + for (var i = 0, j = length - 1; i < length; j = i++) + { var xi = this.points[i * 2], yi = this.points[i * 2 + 1], xj = this.points[j * 2], yj = this.points[j * 2 + 1], intersect = ((yi > y) !== (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi); - if (intersect) { + if (intersect) + { inside = !inside; } } diff --git a/src/core/math/shapes/Rectangle.js b/src/core/math/shapes/Rectangle.js index 16ac62a..4008b68 100644 --- a/src/core/math/shapes/Rectangle.js +++ b/src/core/math/shapes/Rectangle.js @@ -10,7 +10,8 @@ * @param width {number} The overall width of this rectangle * @param height {number} The overall height of this rectangle */ -function Rectangle(x, y, width, height) { +function Rectangle(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -60,7 +61,8 @@ * * @return {Rectangle} a copy of the rectangle */ -Rectangle.prototype.clone = function () { +Rectangle.prototype.clone = function () +{ return new Rectangle(this.x, this.y, this.width, this.height); }; @@ -71,13 +73,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rectangle */ -Rectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Rectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/math/shapes/RoundedRectangle.js b/src/core/math/shapes/RoundedRectangle.js index 27d286e..7bf6411 100644 --- a/src/core/math/shapes/RoundedRectangle.js +++ b/src/core/math/shapes/RoundedRectangle.js @@ -11,7 +11,8 @@ * @param height {number} The overall height of this rounded rectangle * @param radius {number} Controls the radius of the rounded corners */ -function RoundedRectangle(x, y, width, height, radius) { +function RoundedRectangle(x, y, width, height, radius) +{ /** * @member {number} * @default 0 @@ -58,7 +59,8 @@ * * @return {RoundedRectangle} a copy of the rounded rectangle */ -RoundedRectangle.prototype.clone = function () { +RoundedRectangle.prototype.clone = function () +{ return new RoundedRectangle(this.x, this.y, this.width, this.height, this.radius); }; @@ -69,13 +71,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rounded Rectangle */ -RoundedRectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +RoundedRectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/primitives/Graphics.js b/src/core/primitives/Graphics.js index 261c534..e902d2a 100644 --- a/src/core/primitives/Graphics.js +++ b/src/core/primitives/Graphics.js @@ -16,7 +16,8 @@ * @extends DisplayObjectContainer * @namespace PIXI */ -function Graphics() { +function Graphics() +{ DisplayObjectContainer.call(this); this.renderable = true; @@ -154,16 +155,20 @@ * @private */ cacheAsBitmap: { - get: function () { + get: function () + { return this._cacheAsBitmap; }, - set: function (value) { + set: function (value) + { this._cacheAsBitmap = value; - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._generateCachedSprite(); } - else { + else + { this.destroyCachedSprite(); this.dirty = true; } @@ -176,7 +181,8 @@ * * @return {Graphics} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ var clone = new Graphics(); clone.renderable = this.renderable; @@ -192,7 +198,8 @@ clone.cachedSpriteDirty = this.cachedSpriteDirty; // copy graphics data - for (var i = 0; i < this.graphicsData.length; ++i) { + for (var i = 0; i < this.graphicsData.length; ++i) + { clone.graphicsData.push(this.graphicsData.clone()); } @@ -211,17 +218,21 @@ * @param alpha {number} alpha of the line to draw, will update the objects stored style * @return {Graphics} */ -Graphics.prototype.lineStyle = function (lineWidth, color, alpha) { +Graphics.prototype.lineStyle = function (lineWidth, color, alpha) +{ this.lineWidth = lineWidth || 0; this.lineColor = color || 0; this.lineAlpha = (arguments.length < 3) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length) + { // halfway through a line? start a new one! this.drawShape( new math.Polygon( this.currentPath.shape.points.slice(-2) )); } - else { + else + { // otherwise its empty so lets just set the line properties this.currentPath.lineWidth = this.lineWidth; this.currentPath.lineColor = this.lineColor; @@ -239,7 +250,8 @@ * @param y {number} the Y coordinate to move to * @return {Graphics} */ -Graphics.prototype.moveTo = function (x, y) { +Graphics.prototype.moveTo = function (x, y) +{ this.drawShape(new math.Polygon([x,y])); return this; @@ -253,7 +265,8 @@ * @param y {number} the Y coordinate to draw to * @return {Graphics} */ -Graphics.prototype.lineTo = function (x, y) { +Graphics.prototype.lineTo = function (x, y) +{ this.currentPath.shape.points.push(x, y); this.dirty = true; @@ -270,13 +283,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -285,7 +302,8 @@ n = 20, points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { this.moveTo(0, 0); } @@ -293,7 +311,8 @@ var fromY = points[points.length-1]; var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; xa = fromX + ( (cpX - fromX) * j ); @@ -319,13 +338,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -342,7 +365,8 @@ var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; dt = (1 - j); @@ -373,13 +397,17 @@ * @param radius {number} The radius of the arc * @return {Graphics} */ -Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points.push(x1, y1); } } - else { + else + { this.moveTo(x1, y1); } @@ -392,12 +420,15 @@ b2 = x2 - x1, mm = Math.abs(a1 * b2 - b1 * a2); - if (mm < 1.0e-8 || radius === 0) { - if (points[points.length-2] !== x1 || points[points.length-1] !== y1) { + if (mm < 1.0e-8 || radius === 0) + { + if (points[points.length-2] !== x1 || points[points.length-1] !== y1) + { points.push(x1, y1); } } - else { + else + { var dd = a1 * a1 + b1 * b1, cc = a2 * a2 + b2 * b2, tt = a1 * a2 + b1 * b2, @@ -433,42 +464,51 @@ * @param anticlockwise {boolean} Optional. Specifies whether the drawing should be counterclockwise or clockwise. False is default, and indicates clockwise, while true indicates counter-clockwise. * @return {Graphics} */ -Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) { +Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) +{ var startX = cx + Math.cos(startAngle) * radius; var startY = cy + Math.sin(startAngle) * radius; var points; // TODO - This if-else makes no sense. It uses currentPath in the else where it doesn't exist... - if (this.currentPath) { + if (this.currentPath) + { points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { points.push(startX, startY); } - else if (points[points.length-2] !== startX || points[points.length-1] !== startY) { + else if (points[points.length-2] !== startX || points[points.length-1] !== startY) + { points.push(startX, startY); } } - else { + else + { this.moveTo(startX, startY); points = this.currentPath.shape.points; } - if (startAngle === endAngle) { + if (startAngle === endAngle) + { return this; } - if (!anticlockwise && endAngle <= startAngle) { + if (!anticlockwise && endAngle <= startAngle) + { endAngle += Math.PI * 2; } - else if (anticlockwise && startAngle <= endAngle) { + else if (anticlockwise && startAngle <= endAngle) + { startAngle += Math.PI * 2; } var sweep = anticlockwise ? (startAngle - endAngle) *-1 : (endAngle - startAngle); var segs = (Math.abs(sweep)/ (Math.PI * 2)) * 40; - if (sweep === 0) { + if (sweep === 0) + { return this; } @@ -482,7 +522,8 @@ var remainder = ( segMinus % 1 ) / segMinus; - for (var i = 0; i <= segMinus; ++i) { + for (var i = 0; i <= segMinus; ++i) + { var real = i + remainder * i; var angle = ((theta) + startAngle + (theta2 * real)); @@ -506,13 +547,16 @@ * @param alpha {number} the alpha of the fill * @return {Graphics} */ -Graphics.prototype.beginFill = function (color, alpha) { +Graphics.prototype.beginFill = function (color, alpha) +{ this.filling = true; this.fillColor = color || 0; this.fillAlpha = (alpha === undefined) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length <= 2) + { this.currentPath.fill = this.filling; this.currentPath.fillColor = this.fillColor; this.currentPath.fillAlpha = this.fillAlpha; @@ -526,7 +570,8 @@ * * @return {Graphics} */ -Graphics.prototype.endFill = function () { +Graphics.prototype.endFill = function () +{ this.filling = false; this.fillColor = null; this.fillAlpha = 1; @@ -542,7 +587,8 @@ * @param height {number} The height of the rectangle * @return {Graphics} */ -Graphics.prototype.drawRect = function ( x, y, width, height ) { +Graphics.prototype.drawRect = function ( x, y, width, height ) +{ this.drawShape(new math.Rectangle(x,y, width, height)); return this; @@ -556,7 +602,8 @@ * @param height {number} The height of the rectangle * @param radius {number} Radius of the rectangle corners */ -Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) { +Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) +{ this.drawShape(new math.RoundedRectangle(x, y, width, height, radius)); return this; @@ -570,7 +617,8 @@ * @param radius {number} The radius of the circle * @return {Graphics} */ -Graphics.prototype.drawCircle = function (x, y, radius) { +Graphics.prototype.drawCircle = function (x, y, radius) +{ this.drawShape(new math.Circle(x,y, radius)); return this; @@ -585,7 +633,8 @@ * @param height {number} The half height of the ellipse * @return {Graphics} */ -Graphics.prototype.drawEllipse = function (x, y, width, height) { +Graphics.prototype.drawEllipse = function (x, y, width, height) +{ this.drawShape(new math.Ellipse(x, y, width, height)); return this; @@ -597,8 +646,10 @@ * @param path {Array} The path data used to construct the polygon. * @return {Graphics} */ -Graphics.prototype.drawPolygon = function (path) { - if (!(path instanceof Array)) { +Graphics.prototype.drawPolygon = function (path) +{ + if (!(path instanceof Array)) + { path = Array.prototype.slice.call(arguments); } @@ -612,7 +663,8 @@ * * @return {Graphics} */ -Graphics.prototype.clear = function () { +Graphics.prototype.clear = function () +{ this.lineWidth = 0; this.filling = false; @@ -631,7 +683,8 @@ * @param scaleMode {number} Should be one of the scaleMode consts * @return {Texture} a texture of the graphics object */ -Graphics.prototype.generateTexture = function (resolution, scaleMode) { +Graphics.prototype.generateTexture = function (resolution, scaleMode) +{ resolution = resolution || 1; var bounds = this.getBounds(); @@ -655,17 +708,21 @@ * * @param renderer {WebGLRenderer} */ -Graphics.prototype._renderWebGL = function (renderer) { +Graphics.prototype._renderWebGL = function (renderer) +{ // if the sprite is not visible or the alpha is 0 then no need to render this element - if (this.isMask === true) { + if (this.isMask === true) + { return; } // this code may still be needed so leaving for now.. - // + // /* - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture on the gpu too! @@ -681,17 +738,24 @@ return; } - */ - - // check if the webgl graphic needs to be updated - if (this.glDirty) { - this.dirty = true; - this.glDirty = false; - } + else */ - renderer.setObjectRendererer(renderer.graphicsRenderer); - renderer.graphicsRenderer.render(this); + renderer.spriteBatch.stop(); + renderer.blendModeManager.setBlendMode(this.blendMode); + // check blend mode + renderer.blendModeManager.setBlendMode( this.blendMode ); + + // check if the webgl graphic needs to be updated + if (this.glDirty) + { + this.dirty = true; + this.glDirty = false; + } + + WebGLGraphics.renderGraphics(this, renderer); + + renderer.spriteBatch.start(); }; /** @@ -700,14 +764,18 @@ * @param renderer {CanvasRenderer} * @private */ -Graphics.prototype.renderCanvas = function (renderer) { +Graphics.prototype.renderCanvas = function (renderer) +{ // 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.isMask === true) { + if (!this.visible || this.alpha <= 0 || this.isMask === true) + { return; } - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture @@ -723,16 +791,19 @@ return; } - else { + else + { var context = renderer.context; var transform = this.worldTransform; - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } @@ -748,11 +819,13 @@ CanvasGraphics.renderGraphics(this, context); - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } } @@ -763,13 +836,16 @@ * * @return {Rectangle} the rectangular bounding area */ -Graphics.prototype.getBounds = function (matrix) { +Graphics.prototype.getBounds = function (matrix) +{ // return an empty object if the item is a mask! - if (this.isMask) { + if (this.isMask) + { return math.Rectangle.EMPTY; } - if (this.dirty) { + if (this.dirty) + { this.updateLocalBounds(); this.glDirty = true; @@ -841,23 +917,27 @@ * Update the bounds of the object * */ -Graphics.prototype.updateLocalBounds = function () { +Graphics.prototype.updateLocalBounds = function () +{ var minX = Infinity; var maxX = -Infinity; var minY = Infinity; var maxY = -Infinity; - if (this.graphicsData.length) { + if (this.graphicsData.length) + { var shape, points, x, y, w, h; - for (var i = 0; i < this.graphicsData.length; i++) { + for (var i = 0; i < this.graphicsData.length; i++) + { var data = this.graphicsData[i]; var type = data.type; var lineWidth = data.lineWidth; shape = data.shape; - if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) { + if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) + { x = shape.x - lineWidth/2; y = shape.y - lineWidth/2; w = shape.width + lineWidth; @@ -869,7 +949,8 @@ minY = y < minY ? y : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.CIRC) { + else if (type === CONST.SHAPES.CIRC) + { x = shape.x; y = shape.y; w = shape.radius + lineWidth/2; @@ -881,7 +962,8 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.ELIP) { + else if (type === CONST.SHAPES.ELIP) + { x = shape.x; y = shape.y; w = shape.width + lineWidth/2; @@ -893,11 +975,13 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else { + else + { // POLY points = shape.points; - for (var j = 0; j < points.length; j += 2) { + for (var j = 0; j < points.length; j += 2) + { x = points[j]; y = points[j+1]; @@ -910,7 +994,8 @@ } } } - else { + else + { minX = 0; maxX = 0; minY = 0; @@ -931,10 +1016,12 @@ * * @private */ -Graphics.prototype._generateCachedSprite = function () { +Graphics.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { var canvasBuffer = new CanvasBuffer(bounds.width, bounds.height); var texture = Texture.fromCanvas(canvasBuffer.canvas); @@ -943,7 +1030,8 @@ this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.buffer.resize(bounds.width, bounds.height); } @@ -968,7 +1056,8 @@ * * @private */ -Graphics.prototype.updateCachedSpriteTexture = function () { +Graphics.prototype.updateCachedSpriteTexture = function () +{ var cachedSprite = this._cachedSprite; var texture = cachedSprite.texture; var canvas = cachedSprite.buffer.canvas; @@ -989,7 +1078,8 @@ * Destroys a previous cached sprite. * */ -Graphics.prototype.destroyCachedSprite = function () { +Graphics.prototype.destroyCachedSprite = function () +{ this._cachedSprite.texture.destroy(true); // let the gc collect the unused sprite @@ -1003,10 +1093,13 @@ * @param {Circle|Rectangle|Ellipse|Line|Polygon} shape The Shape object to draw. * @return {GraphicsData} The generated GraphicsData object. */ -Graphics.prototype.drawShape = function (shape) { - if (this.currentPath) { +Graphics.prototype.drawShape = function (shape) +{ + if (this.currentPath) + { // check current path! - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath.shape.points.length <= 2) + { this.graphicsData.pop(); } } @@ -1017,7 +1110,8 @@ this.graphicsData.push(data); - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { data.shape.closed = this.filling; this.currentPath = data; } diff --git a/src/core/primitives/GraphicsData.js b/src/core/primitives/GraphicsData.js index 99decbe..788f6f2 100644 --- a/src/core/primitives/GraphicsData.js +++ b/src/core/primitives/GraphicsData.js @@ -4,7 +4,8 @@ * @class * @namespace PIXI */ -function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) { +function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) +{ this.lineWidth = lineWidth; this.lineColor = lineColor; this.lineAlpha = lineAlpha; @@ -27,7 +28,8 @@ * * @return {GraphicsData} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ return new GraphicsData( this.lineWidth, this.lineColor, diff --git a/src/core/renderers/canvas/CanvasRenderer.js b/src/core/renderers/canvas/CanvasRenderer.js index 15a0978..7aebd44 100644 --- a/src/core/renderers/canvas/CanvasRenderer.js +++ b/src/core/renderers/canvas/CanvasRenderer.js @@ -17,17 +17,22 @@ * @param [options.resolution=1] {number} the resolution of the renderer retina would be 2 * @param [options.clearBeforeRender=true] {boolean} This sets if the CanvasRenderer will clear the canvas or not before the new render pass. */ -function CanvasRenderer(width, height, options) { +function CanvasRenderer(width, height, options) +{ utils.sayHello('Canvas'); - if (options) { - for (var i in CONST.defaultRenderOptions) { - if (typeof options[i] === 'undefined') { + if (options) + { + for (var i in CONST.defaultRenderOptions) + { + if (typeof options[i] === 'undefined') + { options[i] = CONST.defaultRenderOptions[i]; } } } - else { + else + { options = CONST.defaultRenderOptions; } @@ -156,19 +161,24 @@ this.smoothProperty = null; - if (this.context.imageSmoothingEnabled) { + if (this.context.imageSmoothingEnabled) + { this.smoothProperty = 'imageSmoothingEnabled'; } - else if (this.context.webkitImageSmoothingEnabled) { + else if (this.context.webkitImageSmoothingEnabled) + { this.smoothProperty = 'webkitImageSmoothingEnabled'; } - else if (this.context.mozImageSmoothingEnabled) { + else if (this.context.mozImageSmoothingEnabled) + { this.smoothProperty = 'mozImageSmoothingEnabled'; } - else if (this.context.oImageSmoothingEnabled) { + else if (this.context.oImageSmoothingEnabled) + { this.smoothProperty = 'oImageSmoothingEnabled'; } - else if (this.context.msImageSmoothingEnabled) { + else if (this.context.msImageSmoothingEnabled) + { this.smoothProperty = 'msImageSmoothingEnabled'; } @@ -193,10 +203,12 @@ * @memberof CanvasRenderer# */ backgroundColor: { - get: function () { + get: function () + { return this._backgroundColor; }, - set: function (val) { + set: function (val) + { this._backgroundColor = val; this._backgroundColorString = utils.hex2string(val); } @@ -208,7 +220,8 @@ * * @param object {DisplayObject} the object to be rendered */ -CanvasRenderer.prototype.render = function (object) { +CanvasRenderer.prototype.render = function (object) +{ object.updateTransform(); this.context.setTransform(1,0,0,1,0,0); @@ -218,16 +231,20 @@ this.currentBlendMode = CONST.blendModes.NORMAL; this.context.globalCompositeOperation = this.blendModes[CONST.blendModes.NORMAL]; - if (navigator.isCocoonJS && this.view.screencanvas) { + if (navigator.isCocoonJS && this.view.screencanvas) + { this.context.fillStyle = 'black'; this.context.clear(); } - if (this.clearBeforeRender) { - if (this.transparent) { + if (this.clearBeforeRender) + { + if (this.transparent) + { this.context.clearRect(0, 0, this.width, this.height); } - else { + else + { this.context.fillStyle = this._backgroundColorString; this.context.fillRect(0, 0, this.width , this.height); } @@ -241,8 +258,10 @@ * * @param [removeView=false] {boolean} Removes the Canvas element from the DOM. */ -CanvasRenderer.prototype.destroy = function (removeView) { - if (removeView && this.view.parent) { +CanvasRenderer.prototype.destroy = function (removeView) +{ + if (removeView && this.view.parent) + { this.view.parent.removeChild(this.view); } @@ -257,14 +276,16 @@ * @param width {number} the new width of the canvas view * @param height {number} the new height of the canvas view */ -CanvasRenderer.prototype.resize = function (width, height) { +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) { + if (this.autoResize) + { this.view.style.width = this.width / this.resolution + 'px'; this.view.style.height = this.height / this.resolution + 'px'; } @@ -276,7 +297,8 @@ * @param displayObject {DisplayObject} The displayObject to render * @private */ -CanvasRenderer.prototype.renderDisplayObject = function (displayObject) { +CanvasRenderer.prototype.renderDisplayObject = function (displayObject) +{ displayObject.renderCanvas(this); }; @@ -285,11 +307,14 @@ * * @private */ -CanvasRenderer.prototype._mapBlendModes = function () { - if (!this.blendModes) { +CanvasRenderer.prototype._mapBlendModes = function () +{ + if (!this.blendModes) + { this.blendModes = {}; - if (utils.canUseNewCanvasBlendModes()) { + if (utils.canUseNewCanvasBlendModes()) + { this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? this.blendModes[CONST.blendModes.MULTIPLY] = 'multiply'; @@ -308,7 +333,8 @@ this.blendModes[CONST.blendModes.COLOR] = 'color'; this.blendModes[CONST.blendModes.LUMINOSITY] = 'luminosity'; } - else { + else + { // this means that the browser does not support the cool new blend modes in canvas 'cough' ie 'cough' this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? diff --git a/src/core/renderers/canvas/utils/CanvasBuffer.js b/src/core/renderers/canvas/utils/CanvasBuffer.js index ebe5d47..b183a66 100644 --- a/src/core/renderers/canvas/utils/CanvasBuffer.js +++ b/src/core/renderers/canvas/utils/CanvasBuffer.js @@ -6,7 +6,8 @@ * @param width {number} the width for the newly created canvas * @param height {number} the height for the newly created canvas */ -function CanvasBuffer(width, height) { +function CanvasBuffer(width, height) +{ /** * The Canvas object that belongs to this CanvasBuffer. * @@ -36,10 +37,12 @@ * @memberof CanvasBuffer# */ width: { - get: function () { + get: function () + { return this.canvas.width; }, - set: function (val) { + set: function (val) + { this.canvas.width = val; } }, @@ -50,10 +53,12 @@ * @memberof CanvasBuffer# */ height: { - get: function () { + get: function () + { return this.canvas.height; }, - set: function (val) { + set: function (val) + { this.canvas.height = val; } } @@ -64,7 +69,8 @@ * * @private */ -CanvasBuffer.prototype.clear = function () { +CanvasBuffer.prototype.clear = function () +{ this.context.setTransform(1, 0, 0, 1, 0, 0); this.context.clearRect(0,0, this.canvas.width, this.canvas.height); }; @@ -75,7 +81,8 @@ * @param width {number} the new width of the canvas * @param height {number} the new height of the canvas */ -CanvasBuffer.prototype.resize = function (width, height) { +CanvasBuffer.prototype.resize = function (width, height) +{ this.canvas.width = width; this.canvas.height = height; }; diff --git a/src/core/renderers/canvas/utils/CanvasGraphics.js b/src/core/renderers/canvas/utils/CanvasGraphics.js index c7eaa2a..3f2a91f 100644 --- a/src/core/renderers/canvas/utils/CanvasGraphics.js +++ b/src/core/renderers/canvas/utils/CanvasGraphics.js @@ -13,15 +13,18 @@ * @param graphics {Graphics} the actual graphics object to render * @param context {CanvasRenderingContext2D} the 2d drawing method of the canvas */ -CanvasGraphics.renderGraphics = function (graphics, context) { +CanvasGraphics.renderGraphics = function (graphics, context) +{ var worldAlpha = graphics.worldAlpha; - if (graphics.dirty) { + if (graphics.dirty) + { this.updateGraphicsTint(graphics); graphics.dirty = false; } - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; @@ -30,69 +33,82 @@ context.lineWidth = data.lineWidth; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { context.beginPath(); var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } - if (shape.closed) { + if (shape.closed) + { context.lineTo(points[0], points[1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fillRect(shape.x, shape.y, shape.width, shape.height); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.strokeRect(shape.x, shape.y, shape.width, shape.height); } } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.beginPath(); context.arc(shape.x, shape.y, shape.radius,0,2*Math.PI); context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas var w = shape.width * 2; @@ -119,18 +135,21 @@ context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; var width = shape.width; @@ -152,13 +171,15 @@ context.quadraticCurveTo(rx, ry, rx, ry + radius); context.closePath(); - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); @@ -174,45 +195,54 @@ * @param graphics {Graphics} the graphics which will be used as a mask * @param context {CanvasRenderingContext2D} the context 2d method of the canvas */ -CanvasGraphics.renderGraphicsMask = function (graphics, context) { +CanvasGraphics.renderGraphicsMask = function (graphics, context) +{ var len = graphics.graphicsData.length; - if (len === 0) { + if (len === 0) + { return; } context.beginPath(); - for (var i = 0; i < len; i++) { + for (var i = 0; i < len; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { context.rect(shape.x, shape.y, shape.width, shape.height); context.closePath(); } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.arc(shape.x, shape.y, shape.radius, 0, 2 * Math.PI); context.closePath(); } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas @@ -237,7 +267,8 @@ context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); context.closePath(); } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; @@ -262,8 +293,10 @@ } }; -CanvasGraphics.updateGraphicsTint = function (graphics) { - if (graphics.tint === 0xFFFFFF) { +CanvasGraphics.updateGraphicsTint = function (graphics) +{ + if (graphics.tint === 0xFFFFFF) + { return; } @@ -271,7 +304,8 @@ var tintG = (graphics.tint >> 8 & 0xFF) / 255; var tintB = (graphics.tint & 0xFF)/ 255; - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var fillColor = data.fillColor | 0; diff --git a/src/core/renderers/canvas/utils/CanvasMaskManager.js b/src/core/renderers/canvas/utils/CanvasMaskManager.js index e04a733..9827d36 100644 --- a/src/core/renderers/canvas/utils/CanvasMaskManager.js +++ b/src/core/renderers/canvas/utils/CanvasMaskManager.js @@ -6,7 +6,8 @@ * @class * @namespace PIXI */ -function CanvasMaskManager() {} +function CanvasMaskManager() +{} CanvasMaskManager.prototype.constructor = CanvasMaskManager; module.exports = CanvasMaskManager; @@ -17,7 +18,8 @@ * @param maskData {object} the maskData that will be pushed * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.pushMask = function (maskData, renderer) { +CanvasMaskManager.prototype.pushMask = function (maskData, renderer) +{ renderer.context.save(); var cacheAlpha = maskData.alpha; @@ -45,6 +47,7 @@ * * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.popMask = function (renderer) { +CanvasMaskManager.prototype.popMask = function (renderer) +{ renderer.context.restore(); }; diff --git a/src/core/renderers/canvas/utils/CanvasTinter.js b/src/core/renderers/canvas/utils/CanvasTinter.js index 17e0529..d2fb1bc 100644 --- a/src/core/renderers/canvas/utils/CanvasTinter.js +++ b/src/core/renderers/canvas/utils/CanvasTinter.js @@ -14,7 +14,8 @@ * @param color {number} the color to use to tint the sprite with * @return {HTMLCanvasElement} The tinted canvas */ -CanvasTinter.getTintedTexture = function (sprite, color) { +CanvasTinter.getTintedTexture = function (sprite, color) +{ var texture = sprite.texture; color = CanvasTinter.roundColor(color); @@ -23,7 +24,8 @@ texture.tintCache = texture.tintCache || {}; - if (texture.tintCache[stringColor]) { + if (texture.tintCache[stringColor]) + { return texture.tintCache[stringColor]; } @@ -33,14 +35,16 @@ //CanvasTinter.tintWithPerPixel(texture, stringColor, canvas); CanvasTinter.tintMethod(texture, color, canvas); - if (CanvasTinter.convertTintToImage) { + if (CanvasTinter.convertTintToImage) + { // is this better? var tintImage = new Image(); tintImage.src = canvas.toDataURL(); texture.tintCache[stringColor] = tintImage; } - else { + else + { texture.tintCache[stringColor] = canvas; // if we are not converting the texture to an image then we need to lose the reference to the canvas CanvasTinter.canvas = null; @@ -56,7 +60,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithMultiply = function (texture, color, canvas) { +CanvasTinter.tintWithMultiply = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -104,7 +109,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithOverlay = function (texture, color, canvas) { +CanvasTinter.tintWithOverlay = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -139,7 +145,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithPerPixel = function (texture, color, canvas) { +CanvasTinter.tintWithPerPixel = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -167,7 +174,8 @@ var pixels = pixelData.data; - for (var i = 0; i < pixels.length; i += 4) { + for (var i = 0; i < pixels.length; i += 4) + { pixels[i+0] *= r; pixels[i+1] *= g; pixels[i+2] *= b; @@ -181,7 +189,8 @@ * * @param color {number} the color to round, should be a hex color */ -CanvasTinter.roundColor = function (color) { +CanvasTinter.roundColor = function (color) +{ var step = CanvasTinter.cacheStepsPerColorChannel; var rgbValues = utils.hex2rgb(color); diff --git a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js index 9f2f89a..35edbaf 100644 --- a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js +++ b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLBlendModeManager(renderer) { +function WebGLBlendModeManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -23,8 +24,10 @@ * * @param blendMode {number} the blendMode, should be a Pixi const, such as BlendModes.ADD */ -WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) { - if (this.currentBlendMode === blendMode) { +WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) +{ + if (this.currentBlendMode === blendMode) + { return false; } diff --git a/src/core/renderers/webgl/managers/WebGLFilterManager.js b/src/core/renderers/webgl/managers/WebGLFilterManager.js index 1179258..2dac048 100644 --- a/src/core/renderers/webgl/managers/WebGLFilterManager.js +++ b/src/core/renderers/webgl/managers/WebGLFilterManager.js @@ -7,7 +7,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLFilterManager(renderer) { +function WebGLFilterManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -32,7 +33,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.texturePool.length = 0; self.initShaderBuffers(); }); @@ -46,7 +48,8 @@ * @param renderer {WebGLRenderer} * @param buffer {ArrayBuffer} */ -WebGLFilterManager.prototype.begin = function (buffer) { +WebGLFilterManager.prototype.begin = function (buffer) +{ this.defaultShader = this.renderer.shaderManager.defaultShader; this.width = this.renderer.projection.x * 2; @@ -60,7 +63,8 @@ * * @param filterBlock {object} the filter that will be pushed to the current filter stack */ -WebGLFilterManager.prototype.pushFilter = function (filterBlock) { +WebGLFilterManager.prototype.pushFilter = function (filterBlock) +{ var gl = this.renderer.gl; var projection = this.renderer.projection; @@ -78,10 +82,12 @@ this.offsetY += filterBlock._filterArea.y; var texture = this.texturePool.pop(); - if (!texture) { + if (!texture) + { texture = new FilterTexture(this.renderer.gl, this.width, this.height); } - else { + else + { texture.resize(this.width, this.height); } @@ -98,29 +104,35 @@ var localX = filterArea.x, localY = filterArea.y; - if (filterArea.x < 0) { + if (filterArea.x < 0) + { filterArea.width += filterArea.x; filterArea.x = 0; } - if (filterArea.y < 0) { + if (filterArea.y < 0) + { filterArea.height += filterArea.y; filterArea.y = 0; } - if (localX + filterArea.width > this.width) { + if (localX + filterArea.width > this.width) + { filterArea.width = this.width - localX; } - if (localY + filterArea.height > this.height) { + if (localY + filterArea.height > this.height) + { filterArea.height = this.height - localY; } - if (filterArea.width < 0) { + if (filterArea.width < 0) + { filterArea.width = 0; } - if (filterArea.height < 0) { + if (filterArea.height < 0) + { filterArea.height = 0; } @@ -154,7 +166,8 @@ * Removes the last filter from the filter stack and doesn't return it. * */ -WebGLFilterManager.prototype.popFilter = function () { +WebGLFilterManager.prototype.popFilter = function () +{ var gl = this.renderer.gl; var filterBlock = this.filterStack.pop(); @@ -163,7 +176,8 @@ var projection = this.renderer.projection; var offset = this.renderer.offset; - if (filterBlock.filterPasses.length > 1) { + if (filterBlock.filterPasses.length > 1) + { gl.viewport(0, 0, filterArea.width, filterArea.height); gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); @@ -193,7 +207,8 @@ var inputTexture = texture; var outputTexture = this.texturePool.pop(); - if (!outputTexture) { + if (!outputTexture) + { outputTexture = new FilterTexture(this.renderer.gl, this.width, this.height); } outputTexture.resize(this.width, this.height); @@ -204,7 +219,8 @@ gl.disable(gl.BLEND); - for (var i = 0; i < filterBlock.filterPasses.length-1; i++) { + for (var i = 0; i < filterBlock.filterPasses.length-1; i++) + { var filterPass = filterBlock.filterPasses[i]; gl.bindFramebuffer(gl.FRAMEBUFFER, outputTexture.frameBuffer ); @@ -243,10 +259,12 @@ var buffer = this.buffer; // time to render the filters texture to the previous scene - if (this.filterStack.length === 0) { + if (this.filterStack.length === 0) + { gl.colorMask(true, true, true, true);//this.transparent); } - else { + else + { var currentFilter = this.filterStack[this.filterStack.length-1]; filterArea = currentFilter._filterArea; @@ -332,13 +350,15 @@ * @param width {number} the horizontal range of the filter * @param height {number} the vertical range of the filter */ -WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) { +WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) +{ // use program var gl = this.renderer.gl; var shader = filter.shaders[gl.id]; - if (!shader) { + if (!shader) + { shader = new Shader(gl); shader.fragmentSrc = filter.fragmentSrc; @@ -356,7 +376,8 @@ gl.uniform2f(shader.projectionVector, width/2, -height/2); gl.uniform2f(shader.offsetVector, 0,0); - if (filter.uniforms.dimensions) { + 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]; @@ -386,7 +407,8 @@ * Initialises the shader buffers. * */ -WebGLFilterManager.prototype.initShaderBuffers = function () { +WebGLFilterManager.prototype.initShaderBuffers = function () +{ var gl = this.renderer.gl; // create some buffers @@ -432,7 +454,8 @@ * Destroys the filter and removes it from the filter stack. * */ -WebGLFilterManager.prototype.destroy = function () { +WebGLFilterManager.prototype.destroy = function () +{ var gl = this.renderer.gl; this.filterStack = null; @@ -441,7 +464,8 @@ this.offsetY = 0; // destroy textures - for (var i = 0; i < this.texturePool.length; i++) { + for (var i = 0; i < this.texturePool.length; i++) + { this.texturePool[i].destroy(); } diff --git a/src/core/renderers/webgl/managers/WebGLManager.js b/src/core/renderers/webgl/managers/WebGLManager.js index 9d47b5c..c30cd51 100644 --- a/src/core/renderers/webgl/managers/WebGLManager.js +++ b/src/core/renderers/webgl/managers/WebGLManager.js @@ -3,7 +3,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLManager(renderer) { +function WebGLManager(renderer) +{ /** * The renderer this manager works for. * @@ -15,6 +16,7 @@ WebGLManager.prototype.constructor = WebGLManager; module.exports = WebGLManager; -WebGLManager.prototype.destroy = function () { +WebGLManager.prototype.destroy = function () +{ this.renderer = null; }; diff --git a/src/core/renderers/webgl/managers/WebGLMaskManager.js b/src/core/renderers/webgl/managers/WebGLMaskManager.js index 2f90b64..e568812 100644 --- a/src/core/renderers/webgl/managers/WebGLMaskManager.js +++ b/src/core/renderers/webgl/managers/WebGLMaskManager.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLMaskManager(renderer) { +function WebGLMaskManager(renderer) +{ WebGLManager.call(this, renderer); } @@ -19,12 +20,15 @@ * * @param maskData {any[]} */ -WebGLMaskManager.prototype.pushMask = function (maskData) { - if (maskData.dirty) { +WebGLMaskManager.prototype.pushMask = function (maskData) +{ + if (maskData.dirty) + { WebGLGraphics.updateGraphics(maskData, this.renderer.gl); } - if (!maskData._webGL[this.renderer.gl.id].data.length) { + if (!maskData._webGL[this.renderer.gl.id].data.length) + { return; } @@ -36,6 +40,7 @@ * * @param maskData {any[]} */ -WebGLMaskManager.prototype.popMask = function (maskData) { +WebGLMaskManager.prototype.popMask = function (maskData) +{ this.renderer.stencilManager.popStencil(maskData, maskData._webGL[this.renderer.gl.id].data[0], this.renderer); }; diff --git a/src/core/renderers/webgl/managers/WebGLShaderManager.js b/src/core/renderers/webgl/managers/WebGLShaderManager.js index fef071c..90c6477 100644 --- a/src/core/renderers/webgl/managers/WebGLShaderManager.js +++ b/src/core/renderers/webgl/managers/WebGLShaderManager.js @@ -10,7 +10,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLShaderManager(renderer) { +function WebGLShaderManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -28,7 +29,8 @@ */ this.tempAttribState = []; - for (var i = 0; i < this.maxAttibs; i++) { + for (var i = 0; i < this.maxAttibs; i++) + { this.attribState[i] = false; } @@ -66,7 +68,8 @@ // listen for context and update necessary shaders var self = this; - this.renderer.on('context', function (event) { + this.renderer.on('context', function (event) + { var gl = event.data; // this shader is used for rendering primitives @@ -97,29 +100,36 @@ * * @param attribs {Array} attribs */ -WebGLShaderManager.prototype.setAttribs = function (attribs) { +WebGLShaderManager.prototype.setAttribs = function (attribs) +{ // reset temp state var i; - for (i = 0; i < this.tempAttribState.length; i++) { + for (i = 0; i < this.tempAttribState.length; i++) + { this.tempAttribState[i] = false; } // set the new attribs - for (var a in attribs) { + for (var a in attribs) + { this.tempAttribState[attribs[a]] = true; } var gl = this.renderer.gl; - for (i = 0; i < this.attribState.length; i++) { - if (this.attribState[i] !== this.tempAttribState[i]) { + for (i = 0; i < this.attribState.length; i++) + { + if (this.attribState[i] !== this.tempAttribState[i]) + { this.attribState[i] = this.tempAttribState[i]; - if (this.attribState[i]) { + if (this.attribState[i]) + { gl.enableVertexAttribArray(i); } - else { + else + { gl.disableVertexAttribArray(i); } } @@ -131,8 +141,10 @@ * * @param shader {Any} */ -WebGLShaderManager.prototype.setShader = function (shader) { - if (this._currentId === shader.uuid) { +WebGLShaderManager.prototype.setShader = function (shader) +{ + if (this._currentId === shader.uuid) + { return false; } @@ -150,7 +162,8 @@ * Destroys this object. * */ -WebGLShaderManager.prototype.destroy = function () { +WebGLShaderManager.prototype.destroy = function () +{ this.attribState = null; this.tempAttribState = null; diff --git a/src/core/renderers/webgl/managers/WebGLStencilManager.js b/src/core/renderers/webgl/managers/WebGLStencilManager.js index 9ec6398..4cb0134 100644 --- a/src/core/renderers/webgl/managers/WebGLStencilManager.js +++ b/src/core/renderers/webgl/managers/WebGLStencilManager.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLStencilManager(renderer) { +function WebGLStencilManager(renderer) +{ WebGLManager.call(this, renderer); this.stencilStack = []; @@ -24,12 +25,14 @@ * @param graphics {Graphics} * @param webGLData {any[]} */ -WebGLStencilManager.prototype.pushStencil = function (graphics, webGLData) { +WebGLStencilManager.prototype.pushStencil = function (graphics, webGLData) +{ var gl = this.renderer.gl; this.bindGraphics(graphics, webGLData, this.renderer); - if (this.stencilStack.length === 0) { + if (this.stencilStack.length === 0) + { gl.enable(gl.STENCIL_TEST); gl.clear(gl.STENCIL_BUFFER_BIT); this.reverse = true; @@ -47,14 +50,17 @@ // draw the triangle strip! - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } @@ -62,31 +68,38 @@ // draw a quad to increment.. gl.drawElements(gl.TRIANGLE_FAN, 4, gl.UNSIGNED_SHORT, ( webGLData.indices.length - 4 ) * 2 ); - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); } this.reverse = !this.reverse; } - else { - if (!this.reverse) { + else + { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } - else { + 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) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); } } @@ -103,7 +116,8 @@ * @param graphics {Graphics} * @param webGLData {Array} */ -WebGLStencilManager.prototype.bindGraphics = function (graphics, webGLData) { +WebGLStencilManager.prototype.bindGraphics = function (graphics, webGLData) +{ //if (this._currentGraphics === graphics)return; this._currentGraphics = graphics; @@ -114,7 +128,8 @@ offset = this.renderer.offset, shader;// = this.renderer.shaderManager.primitiveShader; - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { shader = this.renderer.shaderManager.complexPrimitiveShader; this.renderer.shaderManager.setShader(shader); @@ -141,7 +156,8 @@ // set the index buffer! gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, webGLData.indexBuffer); } - else { + else + { //this.renderer.shaderManager.activatePrimitiveShader(); shader = this.renderer.shaderManager.primitiveShader; this.renderer.shaderManager.setShader( shader ); @@ -154,7 +170,7 @@ gl.uniform2f(shader.uniforms.offsetVector._location, -offset.x, -offset.y); gl.uniform3fv(shader.uniforms.tint._location, utils.hex2rgb(graphics.tint)); - + gl.uniform1f(shader.uniforms.alpha._location, graphics.worldAlpha); @@ -172,19 +188,22 @@ * @param graphics {Graphics} * @param webGLData {Array} */ -WebGLStencilManager.prototype.popStencil = function (graphics, webGLData) { +WebGLStencilManager.prototype.popStencil = function (graphics, webGLData) +{ var gl = this.renderer.gl; this.stencilStack.pop(); this.count--; - if (this.stencilStack.length === 0) { + if (this.stencilStack.length === 0) + { // the stack is empty! gl.disable(gl.STENCIL_TEST); } - else { + else + { var level = this.count; @@ -192,14 +211,17 @@ gl.colorMask(false, false, false, false); - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { this.reverse = !this.reverse; - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } @@ -213,31 +235,38 @@ // draw the triangle strip! gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); - if (!this.reverse) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); } } - else { + else + { // console.log("<<>>") - if (!this.reverse) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } - else { + 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) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); } } @@ -253,7 +282,8 @@ * Destroys the mask stack. * */ -WebGLStencilManager.prototype.destroy = function () { +WebGLStencilManager.prototype.destroy = function () +{ this.renderer = null; this.stencilStack = null; }; diff --git a/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js b/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js index 913ba5e..1ea7d19 100644 --- a/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js +++ b/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function ComplexPrimitiveShader(gl) { +function ComplexPrimitiveShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -24,7 +25,8 @@ 'uniform float flipY;', 'varying vec4 vColor;', - 'void main(void) {', + '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);', @@ -37,7 +39,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = vColor;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/FastShader.js b/src/core/renderers/webgl/shaders/FastShader.js index bd2e29a..2e5e060 100644 --- a/src/core/renderers/webgl/shaders/FastShader.js +++ b/src/core/renderers/webgl/shaders/FastShader.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function FastShader(gl) { +function FastShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -28,7 +29,8 @@ 'const vec2 center = vec2(-1.0, 1.0);', - 'void main(void) {', + 'void main(void) + {', ' vec2 v;', ' vec2 sv = aVertexPosition * aScale;', ' v.x = (sv.x) * cos(aRotation) - (sv.y) * sin(aRotation);', @@ -49,7 +51,8 @@ 'uniform sampler2D uSampler;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/PrimitiveShader.js b/src/core/renderers/webgl/shaders/PrimitiveShader.js index 6f25409..a25f54f 100644 --- a/src/core/renderers/webgl/shaders/PrimitiveShader.js +++ b/src/core/renderers/webgl/shaders/PrimitiveShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function PrimitiveShader(gl) { +function PrimitiveShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -23,7 +24,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + '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);', @@ -36,7 +38,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = vColor;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/Shader.js b/src/core/renderers/webgl/shaders/Shader.js index f8964f5..fd75ef5 100644 --- a/src/core/renderers/webgl/shaders/Shader.js +++ b/src/core/renderers/webgl/shaders/Shader.js @@ -6,7 +6,8 @@ * @param [fragmentSrc] {string} The source of the fragment shader. * @param [vertexSrc] {string} The source of the vertex shader. */ -function Shader(gl, vertexSrc, fragmentSrc, customUniforms, customAttributes) { +function Shader(gl, vertexSrc, fragmentSrc, customUniforms, customAttributes) +{ /** * @member {number} * @readonly @@ -33,7 +34,8 @@ dimensions: { type: '4f', value: new Float32Array(4) } }; - for (var u in customUniforms) { + for (var u in customUniforms) + { this.uniforms[u] = customUniforms[u]; } @@ -43,7 +45,8 @@ aColor: 0 }; - for (var a in customAttributes) { + for (var a in customAttributes) + { this.attributes[a] = customAttributes[a]; } @@ -66,7 +69,8 @@ 'const vec2 center = vec2(-1.0, 1.0);', - 'void main(void) {', + 'void main(void) + {', ' gl_Position = vec4( ((aVertexPosition + offsetVector) / projectionVector) + center , 0.0, 1.0);', ' vTextureCoord = aTextureCoord;', ' vColor = vec4(aColor.rgb * aColor.a, aColor.a);', @@ -85,7 +89,8 @@ 'uniform sampler2D uSampler;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;', '}' ].join('\n'); @@ -96,7 +101,8 @@ Shader.prototype.constructor = Shader; module.exports = Shader; -Shader.prototype.init = function () { +Shader.prototype.init = function () +{ this.compile(); this.gl.useProgram(this.program); @@ -105,14 +111,18 @@ this.cacheAttributeLocations(Object.keys(this.attributes)); }; -Shader.prototype.cacheUniformLocations = function (keys) { - for (var i = 0; i < keys.length; ++i) { +Shader.prototype.cacheUniformLocations = function (keys) +{ + for (var i = 0; i < keys.length; ++i) + { this.uniforms[keys[i]]._location = this.gl.getUniformLocation(this.program, keys[i]); } }; -Shader.prototype.cacheAttributeLocations = function (keys) { - for (var i = 0; i < keys.length; ++i) { +Shader.prototype.cacheAttributeLocations = function (keys) +{ + for (var i = 0; i < keys.length; ++i) + { this.attributes[keys[i]] = this.gl.getAttribLocation(this.program, keys[i]); } @@ -124,14 +134,16 @@ // 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.attributes.aColor === -1) { + // if (this.attributes.aColor === -1) + { // this.attributes.aColor = 2; // } // End worst hack eva // }; -Shader.prototype.compile = function () { +Shader.prototype.compile = function () +{ var gl = this.gl; var glVertShader = this._glCompile(gl.VERTEX_SHADER, this.vertexSrc); @@ -144,13 +156,15 @@ gl.linkProgram(program); // if linking fails, then log and cleanup - if (!gl.getProgramParameter(program, gl.LINK_STATUS)) { + if (!gl.getProgramParameter(program, gl.LINK_STATUS)) + { window.console.error('Pixi.js Error: Could not initialize shader.'); window.console.error('gl.VALIDATE_STATUS', gl.getProgramParameter(program, gl.VALIDATE_STATUS)); window.console.error('gl.getError()', gl.getError()); // if there is a program info log, log it - if (gl.getProgramInfoLog(program) !== '') { + if (gl.getProgramInfoLog(program) !== '') + { window.console.warn('Pixi.js Warning: gl.getProgramInfoLog()', gl.getProgramInfoLog(program)); } @@ -165,18 +179,21 @@ return (this.program = program); }; -Shader.prototype.syncUniforms = function () { +Shader.prototype.syncUniforms = function () +{ var gl = this.gl; this.textureCount = 1; - for (var key in this.uniforms) { + for (var key in this.uniforms) + { var uniform = this.uniforms[key], location = uniform._location, value = uniform.value, i, il; - switch (uniform.type) { + switch (uniform.type) + { // single int value case 'i': case '1i': @@ -282,7 +299,8 @@ // a Color Value case 'c': - if (typeof value === 'number') { + if (typeof value === 'number') + { value = utils.hex2rgb(value); } @@ -311,11 +329,13 @@ // array of 2D Point objects case 'v2v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(2 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 2] = value[i].x; uniform._array[i * 2 + 1] = value[i].y; } @@ -325,11 +345,13 @@ // array of 3D Point objects case 'v3v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(3 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 3] = value[i].x; uniform._array[i * 3 + 1] = value[i].y; uniform._array[i * 3 + 2] = value[i].z; @@ -341,11 +363,13 @@ // array of 4D Point objects case 'v4v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(4 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 4] = value[i].x; uniform._array[i * 4 + 1] = value[i].y; uniform._array[i * 4 + 2] = value[i].z; @@ -359,7 +383,8 @@ // PIXI.Texture case 't': case 'sampler2D': - if (!uniform.value || !uniform.value.baseTexture || !uniform.value.baseTexture.hasLoaded) { + if (!uniform.value || !uniform.value.baseTexture || !uniform.value.baseTexture.hasLoaded) + { break; } @@ -376,7 +401,8 @@ this.textureCount++; // initialize the texture if we haven't yet - if (!uniform._init) { + if (!uniform._init) + { this.initSampler2D(uniform); uniform._init = true; @@ -394,11 +420,13 @@ * Initialises a Sampler2D uniform (which may only be available later on after initUniforms once the texture has loaded) * */ -Shader.prototype.initSampler2D = function (uniform) { +Shader.prototype.initSampler2D = function (uniform) +{ var gl = this.gl; // Extended texture data - if (uniform.textureData) { + if (uniform.textureData) + { var data = uniform.textureData; // GLTexture = mag linear, min linear_mipmap_linear, wrap repeat + gl.generateMipmap(gl.TEXTURE_2D); @@ -417,14 +445,16 @@ var wrapT = (data.wrapT) ? data.wrapT : gl.CLAMP_TO_EDGE; var format = (data.luminance) ? gl.LUMINANCE : gl.RGBA; - if (data.repeat) { + if (data.repeat) + { wrapS = gl.REPEAT; wrapT = gl.REPEAT; } gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, !!data.flipY); - if (data.width) { + if (data.width) + { var width = (data.width) ? data.width : 512; var height = (data.height) ? data.height : 2; var border = (data.border) ? data.border : 0; @@ -432,7 +462,8 @@ // 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 { + 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); } @@ -448,7 +479,8 @@ * Destroys the shader. * */ -Shader.prototype.destroy = function () { +Shader.prototype.destroy = function () +{ this.gl.deleteProgram(this.program); this.gl = null; @@ -459,13 +491,15 @@ this.fragmentSrc = null; }; -Shader.prototype._glCompile = function (type, src) { +Shader.prototype._glCompile = function (type, src) +{ var shader = this.gl.createShader(type); this.gl.shaderSource(shader, src); this.gl.compileShader(shader); - if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) { + if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) + { window.console.log(this.gl.getShaderInfoLog(shader)); return null; } diff --git a/src/core/renderers/webgl/shaders/StripShader.js b/src/core/renderers/webgl/shaders/StripShader.js index 193f6e1..a7abcc6 100644 --- a/src/core/renderers/webgl/shaders/StripShader.js +++ b/src/core/renderers/webgl/shaders/StripShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function StripShader(gl) { +function StripShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -20,7 +21,8 @@ 'varying vec2 vTextureCoord;', - 'void main(void) {', + '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);', @@ -36,7 +38,8 @@ 'varying vec2 vTextureCoord;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vec2(vTextureCoord.x, vTextureCoord.y)) * alpha;', '}' ].join('\n'), diff --git a/src/core/display/DisplayObject.js b/src/core/display/DisplayObject.js index 66ebc3c..20e778c 100644 --- a/src/core/display/DisplayObject.js +++ b/src/core/display/DisplayObject.js @@ -7,7 +7,8 @@ * @class * @namespace PIXI */ -function DisplayObject() { +function DisplayObject() +{ /** * The coordinate of the object relative to the local coordinates of the parent. * @@ -152,10 +153,12 @@ * @memberof DisplayObject# */ x: { - get: function () { + get: function () + { return this.position.x; }, - set: function (value) { + set: function (value) + { this.position.x = value; } }, @@ -167,10 +170,12 @@ * @memberof DisplayObject# */ y: { - get: function () { + get: function () + { return this.position.y; }, - set: function (value) { + set: function (value) + { this.position.y = value; } }, @@ -183,11 +188,13 @@ * @readonly */ worldVisible: { - get: function () { + get: function () + { var item = this; do { - if (!item.visible) { + if (!item.visible) + { return false; } @@ -207,17 +214,21 @@ * @memberof DisplayObject# */ mask: { - get: function () { + get: function () + { return this._mask; }, - set: function (value) { - if (this._mask) { + set: function (value) + { + if (this._mask) + { this._mask.isMask = false; } this._mask = value; - if (this._mask) { + if (this._mask) + { this._mask.isMask = true; } } @@ -232,18 +243,23 @@ * @memberof DisplayObject# */ filters: { - get: function () { + get: function () + { return this._filters; }, - set: function (value) { - if (value) { + set: function (value) + { + if (value) + { // now put all the passes in one place.. var passes = []; - for (var i = 0; i < value.length; i++) { + for (var i = 0; i < value.length; i++) + { var filterPasses = value[i].passes; - for (var j = 0; j < filterPasses.length; j++) { + for (var j = 0; j < filterPasses.length; j++) + { passes.push(filterPasses[j]); } } @@ -264,8 +280,9 @@ * * @private */ -DisplayObject.prototype.updateTransform = function () { - +DisplayObject.prototype.updateTransform = function () +{ + // create some matrix refs for easy access var pt = this.parent.worldTransform; var wt = this.worldTransform; @@ -274,9 +291,11 @@ var a, b, c, d, tx, ty; // so if rotation is between 0 then we can simplify the multiplication process.. - if (this.rotation % math.PI_2) { + if (this.rotation % math.PI_2) + { // 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) { + if (this.rotation !== this.rotationCache) + { this.rotationCache = this.rotation; this._sr = Math.sin(this.rotation); this._cr = Math.cos(this.rotation); @@ -291,7 +310,8 @@ ty = this.position.y; // check for pivot.. not often used so geared towards that fact! - if (this.pivot.x || this.pivot.y) { + 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; } @@ -304,7 +324,8 @@ wt.tx = tx * pt.a + ty * pt.c + pt.tx; wt.ty = tx * pt.b + ty * pt.d + pt.ty; } - else { + else + { // lets do the fast version as we know there is no rotation.. a = this.scale.x; d = this.scale.y; @@ -333,7 +354,8 @@ * @param matrix {Matrix} * @return {Rectangle} the rectangular bounding area */ -DisplayObject.prototype.getBounds = function (/* matrix */) { +DisplayObject.prototype.getBounds = function (/* matrix */) +{ return math.Rectangle.EMPTY; }; @@ -342,7 +364,8 @@ * * @return {Rectangle} the rectangular bounding area */ -DisplayObject.prototype.getLocalBounds = function () { +DisplayObject.prototype.getLocalBounds = function () +{ return this.getBounds(math.Matrix.IDENTITY); }; @@ -352,7 +375,8 @@ * @param position {Point} The world origin to calculate from * @return {Point} A point object representing the position of this object */ -DisplayObject.prototype.toGlobal = function (position) { +DisplayObject.prototype.toGlobal = function (position) +{ // don't need to u[date the lot this.displayObjectUpdateTransform(); return this.worldTransform.apply(position); @@ -365,8 +389,10 @@ * @param [from] {DisplayObject} The DisplayObject to calculate the global position from * @return {Point} A point object representing the position of this object */ -DisplayObject.prototype.toLocal = function (position, from) { - if (from) { +DisplayObject.prototype.toLocal = function (position, from) +{ + if (from) + { position = from.toGlobal(position); } @@ -381,7 +407,8 @@ * @param renderer {WebGLRenderer} The renderer * @private */ -DisplayObject.prototype.renderWebGL = function (/* renderer */) { +DisplayObject.prototype.renderWebGL = function (/* renderer */) +{ // OVERWRITE; }; @@ -391,6 +418,7 @@ * @param renderer {CanvasRenderer} The renderer * @private */ -DisplayObject.prototype.renderCanvas = function (/* renderer */) { +DisplayObject.prototype.renderCanvas = function (/* renderer */) +{ // OVERWRITE; }; diff --git a/src/core/display/DisplayObjectContainer.js b/src/core/display/DisplayObjectContainer.js index 689f40b..4625ee8 100644 --- a/src/core/display/DisplayObjectContainer.js +++ b/src/core/display/DisplayObjectContainer.js @@ -12,7 +12,8 @@ * @extends DisplayObject * @namespace PIXI */ -function DisplayObjectContainer() { +function DisplayObjectContainer() +{ DisplayObject.call(this); /** @@ -47,17 +48,21 @@ * @memberof DisplayObjectContainer# */ width: { - get: function () { + get: function () + { return this.scale.x * this.getLocalBounds().width; }, - set: function (value) { + set: function (value) + { var width = this.getLocalBounds().width; - if(width !== 0) { + if(width !== 0) + { this.scale.x = value / width; } - else { + else + { this.scale.x = 1; } @@ -73,17 +78,21 @@ * @memberof DisplayObjectContainer# */ height: { - get: function () { + get: function () + { return this.scale.y * this.getLocalBounds().height; }, - set: function (value) { + set: function (value) + { var height = this.getLocalBounds().height; - if (height !== 0) { + if (height !== 0) + { this.scale.y = value / height ; } - else { + else + { this.scale.y = 1; } @@ -100,18 +109,23 @@ * @memberof DisplayObject# */ cacheAsBitmap: { - get: function () { + get: function () + { return this._cacheAsBitmap; }, - set: function (value) { - if (this._cacheAsBitmap === value) { + set: function (value) + { + if (this._cacheAsBitmap === value) + { return; } - if (value) { + if (value) + { this._generateCachedSprite(); } - else { + else + { this._destroyCachedSprite(); } @@ -126,7 +140,8 @@ * @param child {DisplayObject} The DisplayObject to add to the container * @return {DisplayObject} The child that was added. */ -DisplayObjectContainer.prototype.addChild = function (child) { +DisplayObjectContainer.prototype.addChild = function (child) +{ return this.addChildAt(child, this.children.length); }; @@ -137,14 +152,18 @@ * @param index {Number} The index to place the child in * @return {DisplayObject} The child that was added. */ -DisplayObjectContainer.prototype.addChildAt = function (child, index) { +DisplayObjectContainer.prototype.addChildAt = function (child, index) +{ // prevent adding self as child - if (child === this) { + if (child === this) + { return; } - if (index >= 0 && index <= this.children.length) { - if (child.parent) { + if (index >= 0 && index <= this.children.length) + { + if (child.parent) + { child.parent.removeChild(child); } @@ -154,7 +173,8 @@ return child; } - else { + else + { throw new Error(child + 'addChildAt: The index '+ index +' supplied is out of bounds ' + this.children.length); } }; @@ -165,15 +185,18 @@ * @param child {DisplayObject} * @param child2 {DisplayObject} */ -DisplayObjectContainer.prototype.swapChildren = function (child, child2) { - if (child === child2) { +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) { + if (index1 < 0 || index2 < 0) + { throw new Error('swapChildren: Both the supplied DisplayObjects must be a child of the caller.'); } @@ -187,10 +210,12 @@ * @param child {DisplayObject} The DisplayObject instance to identify * @return {Number} The index position of the child display object to identify */ -DisplayObjectContainer.prototype.getChildIndex = function (child) { +DisplayObjectContainer.prototype.getChildIndex = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { throw new Error('The supplied DisplayObject must be a child of the caller'); } @@ -203,8 +228,10 @@ * @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 */ -DisplayObjectContainer.prototype.setChildIndex = function (child, index) { - if (index < 0 || index >= this.children.length) { +DisplayObjectContainer.prototype.setChildIndex = function (child, index) +{ + if (index < 0 || index >= this.children.length) + { throw new Error('The supplied index is out of bounds'); } @@ -220,8 +247,10 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child at the given index, if any. */ -DisplayObjectContainer.prototype.getChildAt = function (index) { - if (index < 0 || index >= this.children.length) { +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'); } @@ -234,10 +263,12 @@ * @param child {DisplayObject} The DisplayObject to remove * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChild = function (child) { +DisplayObjectContainer.prototype.removeChild = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { return; } @@ -250,7 +281,8 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChildAt = function (index) { +DisplayObjectContainer.prototype.removeChildAt = function (index) +{ var child = this.getChildAt(index); child.parent = null; @@ -265,24 +297,29 @@ * @param beginIndex {Number} The beginning position. Default value is 0. * @param endIndex {Number} The ending position. Default value is size of the container. */ -DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) { +DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) +{ var begin = beginIndex || 0; var end = typeof endIndex === 'number' ? endIndex : this.children.length; var range = end - begin; - if (range > 0 && range <= end) { + if (range > 0 && range <= end) + { var removed = this.children.splice(begin, range); - for (var i = 0; i < removed.length; ++i) { + for (var i = 0; i < removed.length; ++i) + { removed[i].parent = null; } return removed; } - else if (range === 0 && this.children.length === 0) { + else if (range === 0 && this.children.length === 0) + { return []; } - else { + else + { throw new RangeError('removeChildren: numeric values are outside the acceptable range.'); } }; @@ -291,7 +328,8 @@ * Generates and updates the cached sprite for this object. * */ -DisplayObjectContainer.prototype.updateCachedSprite = function () { +DisplayObjectContainer.prototype.updateCachedSprite = function () +{ this._generateCachedSprite(); }; @@ -304,7 +342,8 @@ * @param renderer {CanvasRenderer|WebGLRenderer} The renderer used to generate the texture. * @return {Texture} a texture of the graphics object */ -DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) { +DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) +{ var bounds = this.getLocalBounds(); var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0, renderer, scaleMode, resolution); @@ -322,18 +361,22 @@ * * @private */ -DisplayObjectContainer.prototype.updateTransform = function () { - if (!this.visible) { +DisplayObjectContainer.prototype.updateTransform = function () +{ + if (!this.visible) + { return; } this.displayObjectUpdateTransform(); - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { return; } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } }; @@ -346,8 +389,10 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getBounds = function () { - if (this.children.length === 0) { +DisplayObjectContainer.prototype.getBounds = function () +{ + if (this.children.length === 0) + { return math.Rectangle.EMPTY; } @@ -365,10 +410,12 @@ var childVisible = false; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -386,7 +433,8 @@ maxY = maxY > childMaxY ? maxY : childMaxY; } - if (!childVisible) { + if (!childVisible) + { return math.Rectangle.EMPTY; } @@ -407,12 +455,14 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getLocalBounds = function () { +DisplayObjectContainer.prototype.getLocalBounds = function () +{ var matrixCache = this.worldTransform; this.worldTransform = math.Matrix.IDENTITY; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } @@ -428,13 +478,16 @@ * * @param renderer {WebGLRenderer} The renderer */ -DisplayObjectContainer.prototype.renderWebGL = function (renderer) { +DisplayObjectContainer.prototype.renderWebGL = function (renderer) +{ // if the object is not visible or the alpha is 0 then no need to render this element - if (!this.visible || this.alpha <= 0) { + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } @@ -442,14 +495,17 @@ var i, j; // do a quick check to see if this element has a mask or a filter. - if (this._mask || this._filters) { + if (this._mask || this._filters) + { // push filter first as we need to ensure the stencil buffer is correct for any masking - if (this._filters) { + if (this._filters) + { renderer.spriteBatch.flush(); renderer.filterManager.pushFilter(this._filterBlock); } - if (this._mask) { + if (this._mask) + { renderer.spriteBatch.stop(); renderer.maskManager.pushMask(this.mask, renderer); renderer.spriteBatch.start(); @@ -459,36 +515,42 @@ this._renderWebGL(renderer); // now loop through the children and make sure they get rendered - for (i = 0, j = this.children.length; i < j; i++) { + for (i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderWebGL(renderer); } // time to stop the sprite batch as either a mask element or a filter draw will happen next renderer.spriteBatch.stop(); - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(this._mask, renderer); } - if (this._filters) { + if (this._filters) + { renderer.filterManager.popFilter(); } renderer.spriteBatch.start(); } - else { + else + { this._renderWebGL(renderer); // simple render children! - for (i = 0, j = this.children.length; i < j; ++i) { + for (i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderWebGL(renderer); } } }; -DisplayObjectContainer.prototype._renderWebGL = function (renderer) { +DisplayObjectContainer.prototype._renderWebGL = function (renderer) +{ // this is where content itself gets renderd.. @@ -499,25 +561,31 @@ * * @param renderer {CanvasRenderer} The renderer */ -DisplayObjectContainer.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0) { +DisplayObjectContainer.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -528,13 +596,16 @@ * @param renderer {WebGLRenderer|CanvasRenderer} The renderer * @private */ -DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) { +DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) +{ this._cachedSprite.worldAlpha = this.worldAlpha; - if (renderer.gl) { + if (renderer.gl) + { this._cachedSprite.renderWebGL(renderer); } - else { + else + { this._cachedSprite.renderCanvas(renderer); } }; @@ -544,10 +615,12 @@ * * @private */ -DisplayObjectContainer.prototype._generateCachedSprite = function () { +DisplayObjectContainer.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { // TODO - RenderTexture now *requires* a renderer instance, so this is like broken // because `renderer` isn't actually in scope here :P var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0); @@ -555,7 +628,8 @@ this._cachedSprite = new Sprite(renderTexture); this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.texture.resize(bounds.width | 0, bounds.height | 0); } @@ -580,8 +654,10 @@ * * @private */ -DisplayObjectContainer.prototype._destroyCachedSprite = function () { - if (!this._cachedSprite) { +DisplayObjectContainer.prototype._destroyCachedSprite = function () +{ + if (!this._cachedSprite) + { return; } diff --git a/src/core/display/Sprite.js b/src/core/display/Sprite.js index 707da24..5862aef 100644 --- a/src/core/display/Sprite.js +++ b/src/core/display/Sprite.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param texture {Texture} The texture for this sprite */ -function Sprite(texture) { +function Sprite(texture) +{ DisplayObjectContainer.call(this); /** @@ -85,12 +86,14 @@ this.texture = texture || Texture.EMPTY; } -Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) { +Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) +{ DisplayObjectContainer.prototype.destroy.call(this); this.anchor = null; - if (destroyTexture) { + if (destroyTexture) + { this._texture.destroy(destroyBaseTexture); } @@ -111,10 +114,12 @@ * @memberof Sprite# */ width: { - get: function () { + get: function () + { return this.scale.x * this.texture.frame.width; }, - set: function (value) { + set: function (value) + { this.scale.x = value / this.texture.frame.width; this._width = value; } @@ -127,10 +132,12 @@ * @memberof Sprite# */ height: { - get: function () { + get: function () + { return this.scale.y * this.texture.frame.height; }, - set: function (value) { + set: function (value) + { this.scale.y = value / this.texture.frame.height; this._height = value; } @@ -143,23 +150,29 @@ * @memberof Sprite# */ texture: { - get: function () { + get: function () + { return this._texture; }, - set: function (value) { - if (this._texture === value) { + set: function (value) + { + if (this._texture === value) + { return; } this._texture = value; this.cachedTint = 0xFFFFFF; - if (value) { + if (value) + { // wait for the texture to load - if (value.baseTexture.hasLoaded) { + if (value.baseTexture.hasLoaded) + { this._onTextureUpdate(); } - else { + else + { value.once('update', this._onTextureUpdate.bind(this)); } } @@ -172,18 +185,22 @@ * * @private */ -Sprite.prototype._onTextureUpdate = function () { +Sprite.prototype._onTextureUpdate = function () +{ // so if _width is 0 then width was not set.. - if (this._width) { + if (this._width) + { this.scale.x = this._width / this.texture.frame.width; } - if (this._height) { + if (this._height) + { this.scale.y = this._height / this.texture.frame.height; } }; -Sprite.prototype._renderWebGL = function (renderer) { +Sprite.prototype._renderWebGL = function (renderer) +{ // this is where content gets renderd.. // watch this space for a little render state manager.. @@ -197,7 +214,8 @@ * @param matrix {Matrix} the transformation matrix of the sprite * @return {Rectangle} the framing rectangle */ -Sprite.prototype.getBounds = function (matrix) { +Sprite.prototype.getBounds = function (matrix) +{ var width = this.texture.frame.width; var height = this.texture.frame.height; @@ -224,11 +242,13 @@ if(b === 0 && c === 0) { // scale may be negative! - if (a < 0) { + if (a < 0) + { a *= -1; } - if (d < 0) { + if (d < 0) + { d *= -1; } @@ -293,28 +313,34 @@ * * @param renderer {CanvasRenderer} The renderer */ -Sprite.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) { +Sprite.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) + { return; } - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; renderer.context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } // Ignore null sources - if (this.texture.valid) { + if (this.texture.valid) + { var resolution = this.texture.baseTexture.resolution / renderer.resolution; renderer.context.globalAlpha = this.worldAlpha; // If smoothingEnabled is supported and we need to change the smoothing property for this texture - if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) { + if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) + { renderer.scaleMode = this.texture.baseTexture.scaleMode; renderer.context[renderer.smoothProperty] = (renderer.scaleMode === CONST.scaleModes.LINEAR); } @@ -324,7 +350,8 @@ var dy = (this.texture.trim ? this.texture.trim.y : 0) - (this.anchor.y * this.texture.trim.height); // Allow for pixel rounding - if (renderer.roundPixels) { + if (renderer.roundPixels) + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -337,7 +364,8 @@ dx = dx | 0; dy = dy | 0; } - else { + else + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -348,8 +376,10 @@ ); } - if (this.tint !== 0xFFFFFF) { - if (this.cachedTint !== this.tint) { + if (this.tint !== 0xFFFFFF) + { + if (this.cachedTint !== this.tint) + { this.cachedTint = this.tint; // TODO clean up caching - how to clean up the caches? @@ -368,7 +398,8 @@ this.texture.crop.height / resolution ); } - else { + else + { renderer.context.drawImage( this.texture.baseTexture.source, this.texture.crop.x, @@ -383,11 +414,13 @@ } } - for (var i = 0, j = this.children.length; i < j; i++) { + for (var i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -402,10 +435,12 @@ * @param frameId {String} The frame Id of the texture in the cache * @return {Sprite} A new Sprite using a texture from the texture cache matching the frameId */ -Sprite.fromFrame = function (frameId) { +Sprite.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache' + this); } @@ -420,6 +455,7 @@ * @param imageId {String} The image url of the texture * @return {Sprite} A new Sprite using a texture from the texture cache matching the image id */ -Sprite.fromImage = function (imageId, crossorigin, scaleMode) { +Sprite.fromImage = function (imageId, crossorigin, scaleMode) +{ return new Sprite(Texture.fromImage(imageId, crossorigin, scaleMode)); }; diff --git a/src/core/display/SpriteBatch.js b/src/core/display/SpriteBatch.js index 3187777..c196fef 100644 --- a/src/core/display/SpriteBatch.js +++ b/src/core/display/SpriteBatch.js @@ -12,7 +12,8 @@ * ```js * var container = new SpriteBatch(); * - * for(var i = 0; i < 100; ++i) { + * for(var i = 0; i < 100; ++i) + * { * var sprite = new PIXI.Sprite.fromImage("myImage.png"); * container.addChild(sprite); * } @@ -25,7 +26,8 @@ */ //TODO RENAME to PARTICLE CONTAINER? -function SpriteBatch() { +function SpriteBatch() +{ DisplayObjectContainer.call(this); } @@ -38,7 +40,8 @@ * * @private */ -SpriteBatch.prototype.updateTransform = function () { +SpriteBatch.prototype.updateTransform = function () +{ // TODO don't need to! this.displayObjectUpdateTransform(); // PIXI.DisplayObjectContainer.prototype.updateTransform.call( this ); @@ -50,8 +53,10 @@ * @param renderer {WebGLRenderer} The webgl renderer * @private */ -SpriteBatch.prototype.renderWebGL = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderWebGL = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -71,8 +76,10 @@ * @param renderer {CanvasRenderer} The canvas renderer * @private */ -SpriteBatch.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -84,10 +91,12 @@ this.displayObjectUpdateTransform(); - for (var i = 0; i < this.children.length; ++i) { + for (var i = 0; i < this.children.length; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -95,9 +104,11 @@ context.globalAlpha = this.worldAlpha * child.alpha; - if (child.rotation % (Math.PI * 2) === 0) { + if (child.rotation % (Math.PI * 2) === 0) + { // this is the fastest way to optimise! - if rotation is 0 then we can avoid any kind of setTransform call - if (isRotated) { + if (isRotated) + { context.setTransform( transform.a, transform.b, @@ -122,8 +133,10 @@ frame.height * child.scale.y ); } - else { - if (!isRotated) { + else + { + if (!isRotated) + { isRotated = true; } @@ -131,7 +144,8 @@ var childTransform = child.worldTransform; - if (renderer.roundPixels) { + if (renderer.roundPixels) + { context.setTransform( childTransform.a, childTransform.b, @@ -141,7 +155,8 @@ childTransform.ty | 0 ); } - else { + else + { context.setTransform( childTransform.a, childTransform.b, diff --git a/src/core/index.js b/src/core/index.js index 3954b6f..eb4a82b 100644 --- a/src/core/index.js +++ b/src/core/index.js @@ -58,11 +58,13 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRenderer: function (width, height, options, noWebGL) { + autoDetectRenderer: function (width, height, options, noWebGL) + { width = width || 800; height = height || 600; - if (!noWebGL && require('webgl-enabled')()) { + if (!noWebGL && require('webgl-enabled')()) + { return new core.WebGLRenderer(width, height, options); } @@ -87,7 +89,8 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRecommendedRenderer: function (width, height, options) { + autoDetectRecommendedRenderer: function (width, height, options) + { var isAndroid = /Android/i.test(navigator.userAgent); return core.autoDetectRenderer(width, height, options, isAndroid); diff --git a/src/core/math/Matrix.js b/src/core/math/Matrix.js index c2f87e2..2ff4848 100644 --- a/src/core/math/Matrix.js +++ b/src/core/math/Matrix.js @@ -10,7 +10,8 @@ * @class * @namespace PIXI */ -function Matrix() { +function Matrix() +{ /** * @member {number} * @default 1 @@ -63,7 +64,8 @@ * * @param array {number[]} The array that the matrix will be populated from. */ -Matrix.prototype.fromArray = function (array) { +Matrix.prototype.fromArray = function (array) +{ this.a = array[0]; this.b = array[1]; this.c = array[3]; @@ -78,14 +80,17 @@ * @param transpose {boolean} Whether we need to transpose the matrix or not * @return {number[]} the newly created array which contains the matrix */ -Matrix.prototype.toArray = function (transpose) { - if (!this.array) { +Matrix.prototype.toArray = function (transpose) +{ + if (!this.array) + { this.array = new Float32Array(9); } var array = this.array; - if (transpose) { + if (transpose) + { array[0] = this.a; array[1] = this.b; array[2] = 0; @@ -96,7 +101,8 @@ array[7] = this.ty; array[8] = 1; } - else { + else + { array[0] = this.a; array[1] = this.c; array[2] = this.tx; @@ -119,7 +125,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, transformed through this matrix */ -Matrix.prototype.apply = function (pos, newPos) { +Matrix.prototype.apply = function (pos, newPos) +{ newPos = newPos || new Point(); newPos.x = this.a * pos.x + this.c * pos.y + this.tx; @@ -136,7 +143,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, inverse-transformed through this matrix */ -Matrix.prototype.applyInverse = function (pos, newPos) { +Matrix.prototype.applyInverse = function (pos, newPos) +{ newPos = newPos || new Point(); var id = 1 / (this.a * this.d + this.c * -this.b); @@ -154,7 +162,8 @@ * @param {number} y * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.translate = function (x, y) { +Matrix.prototype.translate = function (x, y) +{ this.tx += x; this.ty += y; @@ -168,7 +177,8 @@ * @param {number} y The amount to scale vertically * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.scale = function (x, y) { +Matrix.prototype.scale = function (x, y) +{ this.a *= x; this.d *= y; this.c *= x; @@ -186,7 +196,8 @@ * @param {number} angle - The angle in radians. * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.rotate = function (angle) { +Matrix.prototype.rotate = function (angle) +{ var cos = Math.cos( angle ); var sin = Math.sin( angle ); @@ -210,7 +221,8 @@ * @param {Matrix} matrix * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.append = function (matrix) { +Matrix.prototype.append = function (matrix) +{ var a1 = this.a; var b1 = this.b; var c1 = this.c; @@ -232,7 +244,8 @@ * * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.identity = function () { +Matrix.prototype.identity = function () +{ this.a = 1; this.b = 0; this.c = 0; diff --git a/src/core/math/Point.js b/src/core/math/Point.js index 7565b2d..632f346 100644 --- a/src/core/math/Point.js +++ b/src/core/math/Point.js @@ -7,7 +7,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -function Point(x, y) { +function Point(x, y) +{ /** * @member {number} * @default 0 @@ -29,7 +30,8 @@ * * @return {Point} a copy of the point */ -Point.prototype.clone = function () { +Point.prototype.clone = function () +{ return new Point(this.x, this.y); }; @@ -40,7 +42,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -Point.prototype.set = function (x, y) { +Point.prototype.set = function (x, y) +{ this.x = x || 0; this.y = y || ( (y !== 0) ? this.x : 0 ) ; }; diff --git a/src/core/math/shapes/Circle.js b/src/core/math/shapes/Circle.js index 69cfdc9..4d76efc 100644 --- a/src/core/math/shapes/Circle.js +++ b/src/core/math/shapes/Circle.js @@ -10,7 +10,8 @@ * @param y {number} The Y coordinate of the center of this circle * @param radius {number} The radius of the circle */ -function Circle(x, y, radius) { +function Circle(x, y, radius) +{ /** * @member {number} * @default 0 @@ -46,7 +47,8 @@ * @method clone * @return {Circle} a copy of the Circle */ -Circle.prototype.clone = function () { +Circle.prototype.clone = function () +{ return new Circle(this.x, this.y, this.radius); }; @@ -58,8 +60,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Circle */ -Circle.prototype.contains = function (x, y) { - if (this.radius <= 0) { +Circle.prototype.contains = function (x, y) +{ + if (this.radius <= 0) + { return false; } @@ -79,6 +83,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Circle.prototype.getBounds = function () { +Circle.prototype.getBounds = function () +{ return new Rectangle(this.x - this.radius, this.y - this.radius, this.radius * 2, this.radius * 2); }; diff --git a/src/core/math/shapes/Ellipse.js b/src/core/math/shapes/Ellipse.js index 4f2d066..fefd01a 100644 --- a/src/core/math/shapes/Ellipse.js +++ b/src/core/math/shapes/Ellipse.js @@ -11,7 +11,8 @@ * @param width {number} The half width of this ellipse * @param height {number} The half height of this ellipse */ -function Ellipse(x, y, width, height) { +function Ellipse(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -53,7 +54,8 @@ * @method clone * @return {Ellipse} a copy of the ellipse */ -Ellipse.prototype.clone = function () { +Ellipse.prototype.clone = function () +{ return new Ellipse(this.x, this.y, this.width, this.height); }; @@ -65,8 +67,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coords are within this ellipse */ -Ellipse.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Ellipse.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } @@ -86,6 +90,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Ellipse.prototype.getBounds = function () { +Ellipse.prototype.getBounds = function () +{ return new Rectangle(this.x - this.width, this.y - this.height, this.width, this.height); }; diff --git a/src/core/math/shapes/Polygon.js b/src/core/math/shapes/Polygon.js index ae89148..fea6d37 100644 --- a/src/core/math/shapes/Polygon.js +++ b/src/core/math/shapes/Polygon.js @@ -10,16 +10,20 @@ * arguments passed can be flat x,y values e.g. `new Polygon(x,y, x,y, x,y, ...)` where `x` and `y` are * Numbers. */ -function Polygon(points) { +function Polygon(points) +{ //if points isn't an array, use arguments as the array - if (!(points instanceof Array)) { + if (!(points instanceof Array)) + { points = Array.prototype.slice.call(arguments); } //if this is a flat array of numbers, convert it to points - if (points[0] instanceof Point) { + if (points[0] instanceof Point) + { var p = []; - for (var i = 0, il = points.length; i < il; i++) { + for (var i = 0, il = points.length; i < il; i++) + { p.push(points[i].x, points[i].y); } @@ -51,7 +55,8 @@ * * @return {Polygon} a copy of the polygon */ -Polygon.prototype.clone = function () { +Polygon.prototype.clone = function () +{ return new Polygon(this.points.slice()); }; @@ -62,19 +67,22 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this polygon */ -Polygon.prototype.contains = function (x, y) { +Polygon.prototype.contains = function (x, y) +{ var inside = false; // use some raycasting to test hits // https://github.com/substack/point-in-polygon/blob/master/index.js var length = this.points.length / 2; - for (var i = 0, j = length - 1; i < length; j = i++) { + for (var i = 0, j = length - 1; i < length; j = i++) + { var xi = this.points[i * 2], yi = this.points[i * 2 + 1], xj = this.points[j * 2], yj = this.points[j * 2 + 1], intersect = ((yi > y) !== (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi); - if (intersect) { + if (intersect) + { inside = !inside; } } diff --git a/src/core/math/shapes/Rectangle.js b/src/core/math/shapes/Rectangle.js index 16ac62a..4008b68 100644 --- a/src/core/math/shapes/Rectangle.js +++ b/src/core/math/shapes/Rectangle.js @@ -10,7 +10,8 @@ * @param width {number} The overall width of this rectangle * @param height {number} The overall height of this rectangle */ -function Rectangle(x, y, width, height) { +function Rectangle(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -60,7 +61,8 @@ * * @return {Rectangle} a copy of the rectangle */ -Rectangle.prototype.clone = function () { +Rectangle.prototype.clone = function () +{ return new Rectangle(this.x, this.y, this.width, this.height); }; @@ -71,13 +73,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rectangle */ -Rectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Rectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/math/shapes/RoundedRectangle.js b/src/core/math/shapes/RoundedRectangle.js index 27d286e..7bf6411 100644 --- a/src/core/math/shapes/RoundedRectangle.js +++ b/src/core/math/shapes/RoundedRectangle.js @@ -11,7 +11,8 @@ * @param height {number} The overall height of this rounded rectangle * @param radius {number} Controls the radius of the rounded corners */ -function RoundedRectangle(x, y, width, height, radius) { +function RoundedRectangle(x, y, width, height, radius) +{ /** * @member {number} * @default 0 @@ -58,7 +59,8 @@ * * @return {RoundedRectangle} a copy of the rounded rectangle */ -RoundedRectangle.prototype.clone = function () { +RoundedRectangle.prototype.clone = function () +{ return new RoundedRectangle(this.x, this.y, this.width, this.height, this.radius); }; @@ -69,13 +71,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rounded Rectangle */ -RoundedRectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +RoundedRectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/primitives/Graphics.js b/src/core/primitives/Graphics.js index 261c534..e902d2a 100644 --- a/src/core/primitives/Graphics.js +++ b/src/core/primitives/Graphics.js @@ -16,7 +16,8 @@ * @extends DisplayObjectContainer * @namespace PIXI */ -function Graphics() { +function Graphics() +{ DisplayObjectContainer.call(this); this.renderable = true; @@ -154,16 +155,20 @@ * @private */ cacheAsBitmap: { - get: function () { + get: function () + { return this._cacheAsBitmap; }, - set: function (value) { + set: function (value) + { this._cacheAsBitmap = value; - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._generateCachedSprite(); } - else { + else + { this.destroyCachedSprite(); this.dirty = true; } @@ -176,7 +181,8 @@ * * @return {Graphics} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ var clone = new Graphics(); clone.renderable = this.renderable; @@ -192,7 +198,8 @@ clone.cachedSpriteDirty = this.cachedSpriteDirty; // copy graphics data - for (var i = 0; i < this.graphicsData.length; ++i) { + for (var i = 0; i < this.graphicsData.length; ++i) + { clone.graphicsData.push(this.graphicsData.clone()); } @@ -211,17 +218,21 @@ * @param alpha {number} alpha of the line to draw, will update the objects stored style * @return {Graphics} */ -Graphics.prototype.lineStyle = function (lineWidth, color, alpha) { +Graphics.prototype.lineStyle = function (lineWidth, color, alpha) +{ this.lineWidth = lineWidth || 0; this.lineColor = color || 0; this.lineAlpha = (arguments.length < 3) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length) + { // halfway through a line? start a new one! this.drawShape( new math.Polygon( this.currentPath.shape.points.slice(-2) )); } - else { + else + { // otherwise its empty so lets just set the line properties this.currentPath.lineWidth = this.lineWidth; this.currentPath.lineColor = this.lineColor; @@ -239,7 +250,8 @@ * @param y {number} the Y coordinate to move to * @return {Graphics} */ -Graphics.prototype.moveTo = function (x, y) { +Graphics.prototype.moveTo = function (x, y) +{ this.drawShape(new math.Polygon([x,y])); return this; @@ -253,7 +265,8 @@ * @param y {number} the Y coordinate to draw to * @return {Graphics} */ -Graphics.prototype.lineTo = function (x, y) { +Graphics.prototype.lineTo = function (x, y) +{ this.currentPath.shape.points.push(x, y); this.dirty = true; @@ -270,13 +283,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -285,7 +302,8 @@ n = 20, points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { this.moveTo(0, 0); } @@ -293,7 +311,8 @@ var fromY = points[points.length-1]; var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; xa = fromX + ( (cpX - fromX) * j ); @@ -319,13 +338,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -342,7 +365,8 @@ var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; dt = (1 - j); @@ -373,13 +397,17 @@ * @param radius {number} The radius of the arc * @return {Graphics} */ -Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points.push(x1, y1); } } - else { + else + { this.moveTo(x1, y1); } @@ -392,12 +420,15 @@ b2 = x2 - x1, mm = Math.abs(a1 * b2 - b1 * a2); - if (mm < 1.0e-8 || radius === 0) { - if (points[points.length-2] !== x1 || points[points.length-1] !== y1) { + if (mm < 1.0e-8 || radius === 0) + { + if (points[points.length-2] !== x1 || points[points.length-1] !== y1) + { points.push(x1, y1); } } - else { + else + { var dd = a1 * a1 + b1 * b1, cc = a2 * a2 + b2 * b2, tt = a1 * a2 + b1 * b2, @@ -433,42 +464,51 @@ * @param anticlockwise {boolean} Optional. Specifies whether the drawing should be counterclockwise or clockwise. False is default, and indicates clockwise, while true indicates counter-clockwise. * @return {Graphics} */ -Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) { +Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) +{ var startX = cx + Math.cos(startAngle) * radius; var startY = cy + Math.sin(startAngle) * radius; var points; // TODO - This if-else makes no sense. It uses currentPath in the else where it doesn't exist... - if (this.currentPath) { + if (this.currentPath) + { points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { points.push(startX, startY); } - else if (points[points.length-2] !== startX || points[points.length-1] !== startY) { + else if (points[points.length-2] !== startX || points[points.length-1] !== startY) + { points.push(startX, startY); } } - else { + else + { this.moveTo(startX, startY); points = this.currentPath.shape.points; } - if (startAngle === endAngle) { + if (startAngle === endAngle) + { return this; } - if (!anticlockwise && endAngle <= startAngle) { + if (!anticlockwise && endAngle <= startAngle) + { endAngle += Math.PI * 2; } - else if (anticlockwise && startAngle <= endAngle) { + else if (anticlockwise && startAngle <= endAngle) + { startAngle += Math.PI * 2; } var sweep = anticlockwise ? (startAngle - endAngle) *-1 : (endAngle - startAngle); var segs = (Math.abs(sweep)/ (Math.PI * 2)) * 40; - if (sweep === 0) { + if (sweep === 0) + { return this; } @@ -482,7 +522,8 @@ var remainder = ( segMinus % 1 ) / segMinus; - for (var i = 0; i <= segMinus; ++i) { + for (var i = 0; i <= segMinus; ++i) + { var real = i + remainder * i; var angle = ((theta) + startAngle + (theta2 * real)); @@ -506,13 +547,16 @@ * @param alpha {number} the alpha of the fill * @return {Graphics} */ -Graphics.prototype.beginFill = function (color, alpha) { +Graphics.prototype.beginFill = function (color, alpha) +{ this.filling = true; this.fillColor = color || 0; this.fillAlpha = (alpha === undefined) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length <= 2) + { this.currentPath.fill = this.filling; this.currentPath.fillColor = this.fillColor; this.currentPath.fillAlpha = this.fillAlpha; @@ -526,7 +570,8 @@ * * @return {Graphics} */ -Graphics.prototype.endFill = function () { +Graphics.prototype.endFill = function () +{ this.filling = false; this.fillColor = null; this.fillAlpha = 1; @@ -542,7 +587,8 @@ * @param height {number} The height of the rectangle * @return {Graphics} */ -Graphics.prototype.drawRect = function ( x, y, width, height ) { +Graphics.prototype.drawRect = function ( x, y, width, height ) +{ this.drawShape(new math.Rectangle(x,y, width, height)); return this; @@ -556,7 +602,8 @@ * @param height {number} The height of the rectangle * @param radius {number} Radius of the rectangle corners */ -Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) { +Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) +{ this.drawShape(new math.RoundedRectangle(x, y, width, height, radius)); return this; @@ -570,7 +617,8 @@ * @param radius {number} The radius of the circle * @return {Graphics} */ -Graphics.prototype.drawCircle = function (x, y, radius) { +Graphics.prototype.drawCircle = function (x, y, radius) +{ this.drawShape(new math.Circle(x,y, radius)); return this; @@ -585,7 +633,8 @@ * @param height {number} The half height of the ellipse * @return {Graphics} */ -Graphics.prototype.drawEllipse = function (x, y, width, height) { +Graphics.prototype.drawEllipse = function (x, y, width, height) +{ this.drawShape(new math.Ellipse(x, y, width, height)); return this; @@ -597,8 +646,10 @@ * @param path {Array} The path data used to construct the polygon. * @return {Graphics} */ -Graphics.prototype.drawPolygon = function (path) { - if (!(path instanceof Array)) { +Graphics.prototype.drawPolygon = function (path) +{ + if (!(path instanceof Array)) + { path = Array.prototype.slice.call(arguments); } @@ -612,7 +663,8 @@ * * @return {Graphics} */ -Graphics.prototype.clear = function () { +Graphics.prototype.clear = function () +{ this.lineWidth = 0; this.filling = false; @@ -631,7 +683,8 @@ * @param scaleMode {number} Should be one of the scaleMode consts * @return {Texture} a texture of the graphics object */ -Graphics.prototype.generateTexture = function (resolution, scaleMode) { +Graphics.prototype.generateTexture = function (resolution, scaleMode) +{ resolution = resolution || 1; var bounds = this.getBounds(); @@ -655,17 +708,21 @@ * * @param renderer {WebGLRenderer} */ -Graphics.prototype._renderWebGL = function (renderer) { +Graphics.prototype._renderWebGL = function (renderer) +{ // if the sprite is not visible or the alpha is 0 then no need to render this element - if (this.isMask === true) { + if (this.isMask === true) + { return; } // this code may still be needed so leaving for now.. - // + // /* - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture on the gpu too! @@ -681,17 +738,24 @@ return; } - */ - - // check if the webgl graphic needs to be updated - if (this.glDirty) { - this.dirty = true; - this.glDirty = false; - } + else */ - renderer.setObjectRendererer(renderer.graphicsRenderer); - renderer.graphicsRenderer.render(this); + renderer.spriteBatch.stop(); + renderer.blendModeManager.setBlendMode(this.blendMode); + // check blend mode + renderer.blendModeManager.setBlendMode( this.blendMode ); + + // check if the webgl graphic needs to be updated + if (this.glDirty) + { + this.dirty = true; + this.glDirty = false; + } + + WebGLGraphics.renderGraphics(this, renderer); + + renderer.spriteBatch.start(); }; /** @@ -700,14 +764,18 @@ * @param renderer {CanvasRenderer} * @private */ -Graphics.prototype.renderCanvas = function (renderer) { +Graphics.prototype.renderCanvas = function (renderer) +{ // 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.isMask === true) { + if (!this.visible || this.alpha <= 0 || this.isMask === true) + { return; } - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture @@ -723,16 +791,19 @@ return; } - else { + else + { var context = renderer.context; var transform = this.worldTransform; - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } @@ -748,11 +819,13 @@ CanvasGraphics.renderGraphics(this, context); - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } } @@ -763,13 +836,16 @@ * * @return {Rectangle} the rectangular bounding area */ -Graphics.prototype.getBounds = function (matrix) { +Graphics.prototype.getBounds = function (matrix) +{ // return an empty object if the item is a mask! - if (this.isMask) { + if (this.isMask) + { return math.Rectangle.EMPTY; } - if (this.dirty) { + if (this.dirty) + { this.updateLocalBounds(); this.glDirty = true; @@ -841,23 +917,27 @@ * Update the bounds of the object * */ -Graphics.prototype.updateLocalBounds = function () { +Graphics.prototype.updateLocalBounds = function () +{ var minX = Infinity; var maxX = -Infinity; var minY = Infinity; var maxY = -Infinity; - if (this.graphicsData.length) { + if (this.graphicsData.length) + { var shape, points, x, y, w, h; - for (var i = 0; i < this.graphicsData.length; i++) { + for (var i = 0; i < this.graphicsData.length; i++) + { var data = this.graphicsData[i]; var type = data.type; var lineWidth = data.lineWidth; shape = data.shape; - if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) { + if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) + { x = shape.x - lineWidth/2; y = shape.y - lineWidth/2; w = shape.width + lineWidth; @@ -869,7 +949,8 @@ minY = y < minY ? y : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.CIRC) { + else if (type === CONST.SHAPES.CIRC) + { x = shape.x; y = shape.y; w = shape.radius + lineWidth/2; @@ -881,7 +962,8 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.ELIP) { + else if (type === CONST.SHAPES.ELIP) + { x = shape.x; y = shape.y; w = shape.width + lineWidth/2; @@ -893,11 +975,13 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else { + else + { // POLY points = shape.points; - for (var j = 0; j < points.length; j += 2) { + for (var j = 0; j < points.length; j += 2) + { x = points[j]; y = points[j+1]; @@ -910,7 +994,8 @@ } } } - else { + else + { minX = 0; maxX = 0; minY = 0; @@ -931,10 +1016,12 @@ * * @private */ -Graphics.prototype._generateCachedSprite = function () { +Graphics.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { var canvasBuffer = new CanvasBuffer(bounds.width, bounds.height); var texture = Texture.fromCanvas(canvasBuffer.canvas); @@ -943,7 +1030,8 @@ this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.buffer.resize(bounds.width, bounds.height); } @@ -968,7 +1056,8 @@ * * @private */ -Graphics.prototype.updateCachedSpriteTexture = function () { +Graphics.prototype.updateCachedSpriteTexture = function () +{ var cachedSprite = this._cachedSprite; var texture = cachedSprite.texture; var canvas = cachedSprite.buffer.canvas; @@ -989,7 +1078,8 @@ * Destroys a previous cached sprite. * */ -Graphics.prototype.destroyCachedSprite = function () { +Graphics.prototype.destroyCachedSprite = function () +{ this._cachedSprite.texture.destroy(true); // let the gc collect the unused sprite @@ -1003,10 +1093,13 @@ * @param {Circle|Rectangle|Ellipse|Line|Polygon} shape The Shape object to draw. * @return {GraphicsData} The generated GraphicsData object. */ -Graphics.prototype.drawShape = function (shape) { - if (this.currentPath) { +Graphics.prototype.drawShape = function (shape) +{ + if (this.currentPath) + { // check current path! - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath.shape.points.length <= 2) + { this.graphicsData.pop(); } } @@ -1017,7 +1110,8 @@ this.graphicsData.push(data); - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { data.shape.closed = this.filling; this.currentPath = data; } diff --git a/src/core/primitives/GraphicsData.js b/src/core/primitives/GraphicsData.js index 99decbe..788f6f2 100644 --- a/src/core/primitives/GraphicsData.js +++ b/src/core/primitives/GraphicsData.js @@ -4,7 +4,8 @@ * @class * @namespace PIXI */ -function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) { +function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) +{ this.lineWidth = lineWidth; this.lineColor = lineColor; this.lineAlpha = lineAlpha; @@ -27,7 +28,8 @@ * * @return {GraphicsData} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ return new GraphicsData( this.lineWidth, this.lineColor, diff --git a/src/core/renderers/canvas/CanvasRenderer.js b/src/core/renderers/canvas/CanvasRenderer.js index 15a0978..7aebd44 100644 --- a/src/core/renderers/canvas/CanvasRenderer.js +++ b/src/core/renderers/canvas/CanvasRenderer.js @@ -17,17 +17,22 @@ * @param [options.resolution=1] {number} the resolution of the renderer retina would be 2 * @param [options.clearBeforeRender=true] {boolean} This sets if the CanvasRenderer will clear the canvas or not before the new render pass. */ -function CanvasRenderer(width, height, options) { +function CanvasRenderer(width, height, options) +{ utils.sayHello('Canvas'); - if (options) { - for (var i in CONST.defaultRenderOptions) { - if (typeof options[i] === 'undefined') { + if (options) + { + for (var i in CONST.defaultRenderOptions) + { + if (typeof options[i] === 'undefined') + { options[i] = CONST.defaultRenderOptions[i]; } } } - else { + else + { options = CONST.defaultRenderOptions; } @@ -156,19 +161,24 @@ this.smoothProperty = null; - if (this.context.imageSmoothingEnabled) { + if (this.context.imageSmoothingEnabled) + { this.smoothProperty = 'imageSmoothingEnabled'; } - else if (this.context.webkitImageSmoothingEnabled) { + else if (this.context.webkitImageSmoothingEnabled) + { this.smoothProperty = 'webkitImageSmoothingEnabled'; } - else if (this.context.mozImageSmoothingEnabled) { + else if (this.context.mozImageSmoothingEnabled) + { this.smoothProperty = 'mozImageSmoothingEnabled'; } - else if (this.context.oImageSmoothingEnabled) { + else if (this.context.oImageSmoothingEnabled) + { this.smoothProperty = 'oImageSmoothingEnabled'; } - else if (this.context.msImageSmoothingEnabled) { + else if (this.context.msImageSmoothingEnabled) + { this.smoothProperty = 'msImageSmoothingEnabled'; } @@ -193,10 +203,12 @@ * @memberof CanvasRenderer# */ backgroundColor: { - get: function () { + get: function () + { return this._backgroundColor; }, - set: function (val) { + set: function (val) + { this._backgroundColor = val; this._backgroundColorString = utils.hex2string(val); } @@ -208,7 +220,8 @@ * * @param object {DisplayObject} the object to be rendered */ -CanvasRenderer.prototype.render = function (object) { +CanvasRenderer.prototype.render = function (object) +{ object.updateTransform(); this.context.setTransform(1,0,0,1,0,0); @@ -218,16 +231,20 @@ this.currentBlendMode = CONST.blendModes.NORMAL; this.context.globalCompositeOperation = this.blendModes[CONST.blendModes.NORMAL]; - if (navigator.isCocoonJS && this.view.screencanvas) { + if (navigator.isCocoonJS && this.view.screencanvas) + { this.context.fillStyle = 'black'; this.context.clear(); } - if (this.clearBeforeRender) { - if (this.transparent) { + if (this.clearBeforeRender) + { + if (this.transparent) + { this.context.clearRect(0, 0, this.width, this.height); } - else { + else + { this.context.fillStyle = this._backgroundColorString; this.context.fillRect(0, 0, this.width , this.height); } @@ -241,8 +258,10 @@ * * @param [removeView=false] {boolean} Removes the Canvas element from the DOM. */ -CanvasRenderer.prototype.destroy = function (removeView) { - if (removeView && this.view.parent) { +CanvasRenderer.prototype.destroy = function (removeView) +{ + if (removeView && this.view.parent) + { this.view.parent.removeChild(this.view); } @@ -257,14 +276,16 @@ * @param width {number} the new width of the canvas view * @param height {number} the new height of the canvas view */ -CanvasRenderer.prototype.resize = function (width, height) { +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) { + if (this.autoResize) + { this.view.style.width = this.width / this.resolution + 'px'; this.view.style.height = this.height / this.resolution + 'px'; } @@ -276,7 +297,8 @@ * @param displayObject {DisplayObject} The displayObject to render * @private */ -CanvasRenderer.prototype.renderDisplayObject = function (displayObject) { +CanvasRenderer.prototype.renderDisplayObject = function (displayObject) +{ displayObject.renderCanvas(this); }; @@ -285,11 +307,14 @@ * * @private */ -CanvasRenderer.prototype._mapBlendModes = function () { - if (!this.blendModes) { +CanvasRenderer.prototype._mapBlendModes = function () +{ + if (!this.blendModes) + { this.blendModes = {}; - if (utils.canUseNewCanvasBlendModes()) { + if (utils.canUseNewCanvasBlendModes()) + { this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? this.blendModes[CONST.blendModes.MULTIPLY] = 'multiply'; @@ -308,7 +333,8 @@ this.blendModes[CONST.blendModes.COLOR] = 'color'; this.blendModes[CONST.blendModes.LUMINOSITY] = 'luminosity'; } - else { + else + { // this means that the browser does not support the cool new blend modes in canvas 'cough' ie 'cough' this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? diff --git a/src/core/renderers/canvas/utils/CanvasBuffer.js b/src/core/renderers/canvas/utils/CanvasBuffer.js index ebe5d47..b183a66 100644 --- a/src/core/renderers/canvas/utils/CanvasBuffer.js +++ b/src/core/renderers/canvas/utils/CanvasBuffer.js @@ -6,7 +6,8 @@ * @param width {number} the width for the newly created canvas * @param height {number} the height for the newly created canvas */ -function CanvasBuffer(width, height) { +function CanvasBuffer(width, height) +{ /** * The Canvas object that belongs to this CanvasBuffer. * @@ -36,10 +37,12 @@ * @memberof CanvasBuffer# */ width: { - get: function () { + get: function () + { return this.canvas.width; }, - set: function (val) { + set: function (val) + { this.canvas.width = val; } }, @@ -50,10 +53,12 @@ * @memberof CanvasBuffer# */ height: { - get: function () { + get: function () + { return this.canvas.height; }, - set: function (val) { + set: function (val) + { this.canvas.height = val; } } @@ -64,7 +69,8 @@ * * @private */ -CanvasBuffer.prototype.clear = function () { +CanvasBuffer.prototype.clear = function () +{ this.context.setTransform(1, 0, 0, 1, 0, 0); this.context.clearRect(0,0, this.canvas.width, this.canvas.height); }; @@ -75,7 +81,8 @@ * @param width {number} the new width of the canvas * @param height {number} the new height of the canvas */ -CanvasBuffer.prototype.resize = function (width, height) { +CanvasBuffer.prototype.resize = function (width, height) +{ this.canvas.width = width; this.canvas.height = height; }; diff --git a/src/core/renderers/canvas/utils/CanvasGraphics.js b/src/core/renderers/canvas/utils/CanvasGraphics.js index c7eaa2a..3f2a91f 100644 --- a/src/core/renderers/canvas/utils/CanvasGraphics.js +++ b/src/core/renderers/canvas/utils/CanvasGraphics.js @@ -13,15 +13,18 @@ * @param graphics {Graphics} the actual graphics object to render * @param context {CanvasRenderingContext2D} the 2d drawing method of the canvas */ -CanvasGraphics.renderGraphics = function (graphics, context) { +CanvasGraphics.renderGraphics = function (graphics, context) +{ var worldAlpha = graphics.worldAlpha; - if (graphics.dirty) { + if (graphics.dirty) + { this.updateGraphicsTint(graphics); graphics.dirty = false; } - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; @@ -30,69 +33,82 @@ context.lineWidth = data.lineWidth; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { context.beginPath(); var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } - if (shape.closed) { + if (shape.closed) + { context.lineTo(points[0], points[1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fillRect(shape.x, shape.y, shape.width, shape.height); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.strokeRect(shape.x, shape.y, shape.width, shape.height); } } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.beginPath(); context.arc(shape.x, shape.y, shape.radius,0,2*Math.PI); context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas var w = shape.width * 2; @@ -119,18 +135,21 @@ context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; var width = shape.width; @@ -152,13 +171,15 @@ context.quadraticCurveTo(rx, ry, rx, ry + radius); context.closePath(); - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); @@ -174,45 +195,54 @@ * @param graphics {Graphics} the graphics which will be used as a mask * @param context {CanvasRenderingContext2D} the context 2d method of the canvas */ -CanvasGraphics.renderGraphicsMask = function (graphics, context) { +CanvasGraphics.renderGraphicsMask = function (graphics, context) +{ var len = graphics.graphicsData.length; - if (len === 0) { + if (len === 0) + { return; } context.beginPath(); - for (var i = 0; i < len; i++) { + for (var i = 0; i < len; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { context.rect(shape.x, shape.y, shape.width, shape.height); context.closePath(); } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.arc(shape.x, shape.y, shape.radius, 0, 2 * Math.PI); context.closePath(); } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas @@ -237,7 +267,8 @@ context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); context.closePath(); } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; @@ -262,8 +293,10 @@ } }; -CanvasGraphics.updateGraphicsTint = function (graphics) { - if (graphics.tint === 0xFFFFFF) { +CanvasGraphics.updateGraphicsTint = function (graphics) +{ + if (graphics.tint === 0xFFFFFF) + { return; } @@ -271,7 +304,8 @@ var tintG = (graphics.tint >> 8 & 0xFF) / 255; var tintB = (graphics.tint & 0xFF)/ 255; - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var fillColor = data.fillColor | 0; diff --git a/src/core/renderers/canvas/utils/CanvasMaskManager.js b/src/core/renderers/canvas/utils/CanvasMaskManager.js index e04a733..9827d36 100644 --- a/src/core/renderers/canvas/utils/CanvasMaskManager.js +++ b/src/core/renderers/canvas/utils/CanvasMaskManager.js @@ -6,7 +6,8 @@ * @class * @namespace PIXI */ -function CanvasMaskManager() {} +function CanvasMaskManager() +{} CanvasMaskManager.prototype.constructor = CanvasMaskManager; module.exports = CanvasMaskManager; @@ -17,7 +18,8 @@ * @param maskData {object} the maskData that will be pushed * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.pushMask = function (maskData, renderer) { +CanvasMaskManager.prototype.pushMask = function (maskData, renderer) +{ renderer.context.save(); var cacheAlpha = maskData.alpha; @@ -45,6 +47,7 @@ * * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.popMask = function (renderer) { +CanvasMaskManager.prototype.popMask = function (renderer) +{ renderer.context.restore(); }; diff --git a/src/core/renderers/canvas/utils/CanvasTinter.js b/src/core/renderers/canvas/utils/CanvasTinter.js index 17e0529..d2fb1bc 100644 --- a/src/core/renderers/canvas/utils/CanvasTinter.js +++ b/src/core/renderers/canvas/utils/CanvasTinter.js @@ -14,7 +14,8 @@ * @param color {number} the color to use to tint the sprite with * @return {HTMLCanvasElement} The tinted canvas */ -CanvasTinter.getTintedTexture = function (sprite, color) { +CanvasTinter.getTintedTexture = function (sprite, color) +{ var texture = sprite.texture; color = CanvasTinter.roundColor(color); @@ -23,7 +24,8 @@ texture.tintCache = texture.tintCache || {}; - if (texture.tintCache[stringColor]) { + if (texture.tintCache[stringColor]) + { return texture.tintCache[stringColor]; } @@ -33,14 +35,16 @@ //CanvasTinter.tintWithPerPixel(texture, stringColor, canvas); CanvasTinter.tintMethod(texture, color, canvas); - if (CanvasTinter.convertTintToImage) { + if (CanvasTinter.convertTintToImage) + { // is this better? var tintImage = new Image(); tintImage.src = canvas.toDataURL(); texture.tintCache[stringColor] = tintImage; } - else { + else + { texture.tintCache[stringColor] = canvas; // if we are not converting the texture to an image then we need to lose the reference to the canvas CanvasTinter.canvas = null; @@ -56,7 +60,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithMultiply = function (texture, color, canvas) { +CanvasTinter.tintWithMultiply = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -104,7 +109,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithOverlay = function (texture, color, canvas) { +CanvasTinter.tintWithOverlay = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -139,7 +145,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithPerPixel = function (texture, color, canvas) { +CanvasTinter.tintWithPerPixel = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -167,7 +174,8 @@ var pixels = pixelData.data; - for (var i = 0; i < pixels.length; i += 4) { + for (var i = 0; i < pixels.length; i += 4) + { pixels[i+0] *= r; pixels[i+1] *= g; pixels[i+2] *= b; @@ -181,7 +189,8 @@ * * @param color {number} the color to round, should be a hex color */ -CanvasTinter.roundColor = function (color) { +CanvasTinter.roundColor = function (color) +{ var step = CanvasTinter.cacheStepsPerColorChannel; var rgbValues = utils.hex2rgb(color); diff --git a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js index 9f2f89a..35edbaf 100644 --- a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js +++ b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLBlendModeManager(renderer) { +function WebGLBlendModeManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -23,8 +24,10 @@ * * @param blendMode {number} the blendMode, should be a Pixi const, such as BlendModes.ADD */ -WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) { - if (this.currentBlendMode === blendMode) { +WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) +{ + if (this.currentBlendMode === blendMode) + { return false; } diff --git a/src/core/renderers/webgl/managers/WebGLFilterManager.js b/src/core/renderers/webgl/managers/WebGLFilterManager.js index 1179258..2dac048 100644 --- a/src/core/renderers/webgl/managers/WebGLFilterManager.js +++ b/src/core/renderers/webgl/managers/WebGLFilterManager.js @@ -7,7 +7,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLFilterManager(renderer) { +function WebGLFilterManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -32,7 +33,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.texturePool.length = 0; self.initShaderBuffers(); }); @@ -46,7 +48,8 @@ * @param renderer {WebGLRenderer} * @param buffer {ArrayBuffer} */ -WebGLFilterManager.prototype.begin = function (buffer) { +WebGLFilterManager.prototype.begin = function (buffer) +{ this.defaultShader = this.renderer.shaderManager.defaultShader; this.width = this.renderer.projection.x * 2; @@ -60,7 +63,8 @@ * * @param filterBlock {object} the filter that will be pushed to the current filter stack */ -WebGLFilterManager.prototype.pushFilter = function (filterBlock) { +WebGLFilterManager.prototype.pushFilter = function (filterBlock) +{ var gl = this.renderer.gl; var projection = this.renderer.projection; @@ -78,10 +82,12 @@ this.offsetY += filterBlock._filterArea.y; var texture = this.texturePool.pop(); - if (!texture) { + if (!texture) + { texture = new FilterTexture(this.renderer.gl, this.width, this.height); } - else { + else + { texture.resize(this.width, this.height); } @@ -98,29 +104,35 @@ var localX = filterArea.x, localY = filterArea.y; - if (filterArea.x < 0) { + if (filterArea.x < 0) + { filterArea.width += filterArea.x; filterArea.x = 0; } - if (filterArea.y < 0) { + if (filterArea.y < 0) + { filterArea.height += filterArea.y; filterArea.y = 0; } - if (localX + filterArea.width > this.width) { + if (localX + filterArea.width > this.width) + { filterArea.width = this.width - localX; } - if (localY + filterArea.height > this.height) { + if (localY + filterArea.height > this.height) + { filterArea.height = this.height - localY; } - if (filterArea.width < 0) { + if (filterArea.width < 0) + { filterArea.width = 0; } - if (filterArea.height < 0) { + if (filterArea.height < 0) + { filterArea.height = 0; } @@ -154,7 +166,8 @@ * Removes the last filter from the filter stack and doesn't return it. * */ -WebGLFilterManager.prototype.popFilter = function () { +WebGLFilterManager.prototype.popFilter = function () +{ var gl = this.renderer.gl; var filterBlock = this.filterStack.pop(); @@ -163,7 +176,8 @@ var projection = this.renderer.projection; var offset = this.renderer.offset; - if (filterBlock.filterPasses.length > 1) { + if (filterBlock.filterPasses.length > 1) + { gl.viewport(0, 0, filterArea.width, filterArea.height); gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); @@ -193,7 +207,8 @@ var inputTexture = texture; var outputTexture = this.texturePool.pop(); - if (!outputTexture) { + if (!outputTexture) + { outputTexture = new FilterTexture(this.renderer.gl, this.width, this.height); } outputTexture.resize(this.width, this.height); @@ -204,7 +219,8 @@ gl.disable(gl.BLEND); - for (var i = 0; i < filterBlock.filterPasses.length-1; i++) { + for (var i = 0; i < filterBlock.filterPasses.length-1; i++) + { var filterPass = filterBlock.filterPasses[i]; gl.bindFramebuffer(gl.FRAMEBUFFER, outputTexture.frameBuffer ); @@ -243,10 +259,12 @@ var buffer = this.buffer; // time to render the filters texture to the previous scene - if (this.filterStack.length === 0) { + if (this.filterStack.length === 0) + { gl.colorMask(true, true, true, true);//this.transparent); } - else { + else + { var currentFilter = this.filterStack[this.filterStack.length-1]; filterArea = currentFilter._filterArea; @@ -332,13 +350,15 @@ * @param width {number} the horizontal range of the filter * @param height {number} the vertical range of the filter */ -WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) { +WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) +{ // use program var gl = this.renderer.gl; var shader = filter.shaders[gl.id]; - if (!shader) { + if (!shader) + { shader = new Shader(gl); shader.fragmentSrc = filter.fragmentSrc; @@ -356,7 +376,8 @@ gl.uniform2f(shader.projectionVector, width/2, -height/2); gl.uniform2f(shader.offsetVector, 0,0); - if (filter.uniforms.dimensions) { + 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]; @@ -386,7 +407,8 @@ * Initialises the shader buffers. * */ -WebGLFilterManager.prototype.initShaderBuffers = function () { +WebGLFilterManager.prototype.initShaderBuffers = function () +{ var gl = this.renderer.gl; // create some buffers @@ -432,7 +454,8 @@ * Destroys the filter and removes it from the filter stack. * */ -WebGLFilterManager.prototype.destroy = function () { +WebGLFilterManager.prototype.destroy = function () +{ var gl = this.renderer.gl; this.filterStack = null; @@ -441,7 +464,8 @@ this.offsetY = 0; // destroy textures - for (var i = 0; i < this.texturePool.length; i++) { + for (var i = 0; i < this.texturePool.length; i++) + { this.texturePool[i].destroy(); } diff --git a/src/core/renderers/webgl/managers/WebGLManager.js b/src/core/renderers/webgl/managers/WebGLManager.js index 9d47b5c..c30cd51 100644 --- a/src/core/renderers/webgl/managers/WebGLManager.js +++ b/src/core/renderers/webgl/managers/WebGLManager.js @@ -3,7 +3,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLManager(renderer) { +function WebGLManager(renderer) +{ /** * The renderer this manager works for. * @@ -15,6 +16,7 @@ WebGLManager.prototype.constructor = WebGLManager; module.exports = WebGLManager; -WebGLManager.prototype.destroy = function () { +WebGLManager.prototype.destroy = function () +{ this.renderer = null; }; diff --git a/src/core/renderers/webgl/managers/WebGLMaskManager.js b/src/core/renderers/webgl/managers/WebGLMaskManager.js index 2f90b64..e568812 100644 --- a/src/core/renderers/webgl/managers/WebGLMaskManager.js +++ b/src/core/renderers/webgl/managers/WebGLMaskManager.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLMaskManager(renderer) { +function WebGLMaskManager(renderer) +{ WebGLManager.call(this, renderer); } @@ -19,12 +20,15 @@ * * @param maskData {any[]} */ -WebGLMaskManager.prototype.pushMask = function (maskData) { - if (maskData.dirty) { +WebGLMaskManager.prototype.pushMask = function (maskData) +{ + if (maskData.dirty) + { WebGLGraphics.updateGraphics(maskData, this.renderer.gl); } - if (!maskData._webGL[this.renderer.gl.id].data.length) { + if (!maskData._webGL[this.renderer.gl.id].data.length) + { return; } @@ -36,6 +40,7 @@ * * @param maskData {any[]} */ -WebGLMaskManager.prototype.popMask = function (maskData) { +WebGLMaskManager.prototype.popMask = function (maskData) +{ this.renderer.stencilManager.popStencil(maskData, maskData._webGL[this.renderer.gl.id].data[0], this.renderer); }; diff --git a/src/core/renderers/webgl/managers/WebGLShaderManager.js b/src/core/renderers/webgl/managers/WebGLShaderManager.js index fef071c..90c6477 100644 --- a/src/core/renderers/webgl/managers/WebGLShaderManager.js +++ b/src/core/renderers/webgl/managers/WebGLShaderManager.js @@ -10,7 +10,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLShaderManager(renderer) { +function WebGLShaderManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -28,7 +29,8 @@ */ this.tempAttribState = []; - for (var i = 0; i < this.maxAttibs; i++) { + for (var i = 0; i < this.maxAttibs; i++) + { this.attribState[i] = false; } @@ -66,7 +68,8 @@ // listen for context and update necessary shaders var self = this; - this.renderer.on('context', function (event) { + this.renderer.on('context', function (event) + { var gl = event.data; // this shader is used for rendering primitives @@ -97,29 +100,36 @@ * * @param attribs {Array} attribs */ -WebGLShaderManager.prototype.setAttribs = function (attribs) { +WebGLShaderManager.prototype.setAttribs = function (attribs) +{ // reset temp state var i; - for (i = 0; i < this.tempAttribState.length; i++) { + for (i = 0; i < this.tempAttribState.length; i++) + { this.tempAttribState[i] = false; } // set the new attribs - for (var a in attribs) { + for (var a in attribs) + { this.tempAttribState[attribs[a]] = true; } var gl = this.renderer.gl; - for (i = 0; i < this.attribState.length; i++) { - if (this.attribState[i] !== this.tempAttribState[i]) { + for (i = 0; i < this.attribState.length; i++) + { + if (this.attribState[i] !== this.tempAttribState[i]) + { this.attribState[i] = this.tempAttribState[i]; - if (this.attribState[i]) { + if (this.attribState[i]) + { gl.enableVertexAttribArray(i); } - else { + else + { gl.disableVertexAttribArray(i); } } @@ -131,8 +141,10 @@ * * @param shader {Any} */ -WebGLShaderManager.prototype.setShader = function (shader) { - if (this._currentId === shader.uuid) { +WebGLShaderManager.prototype.setShader = function (shader) +{ + if (this._currentId === shader.uuid) + { return false; } @@ -150,7 +162,8 @@ * Destroys this object. * */ -WebGLShaderManager.prototype.destroy = function () { +WebGLShaderManager.prototype.destroy = function () +{ this.attribState = null; this.tempAttribState = null; diff --git a/src/core/renderers/webgl/managers/WebGLStencilManager.js b/src/core/renderers/webgl/managers/WebGLStencilManager.js index 9ec6398..4cb0134 100644 --- a/src/core/renderers/webgl/managers/WebGLStencilManager.js +++ b/src/core/renderers/webgl/managers/WebGLStencilManager.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLStencilManager(renderer) { +function WebGLStencilManager(renderer) +{ WebGLManager.call(this, renderer); this.stencilStack = []; @@ -24,12 +25,14 @@ * @param graphics {Graphics} * @param webGLData {any[]} */ -WebGLStencilManager.prototype.pushStencil = function (graphics, webGLData) { +WebGLStencilManager.prototype.pushStencil = function (graphics, webGLData) +{ var gl = this.renderer.gl; this.bindGraphics(graphics, webGLData, this.renderer); - if (this.stencilStack.length === 0) { + if (this.stencilStack.length === 0) + { gl.enable(gl.STENCIL_TEST); gl.clear(gl.STENCIL_BUFFER_BIT); this.reverse = true; @@ -47,14 +50,17 @@ // draw the triangle strip! - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } @@ -62,31 +68,38 @@ // draw a quad to increment.. gl.drawElements(gl.TRIANGLE_FAN, 4, gl.UNSIGNED_SHORT, ( webGLData.indices.length - 4 ) * 2 ); - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); } this.reverse = !this.reverse; } - else { - if (!this.reverse) { + else + { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } - else { + 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) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); } } @@ -103,7 +116,8 @@ * @param graphics {Graphics} * @param webGLData {Array} */ -WebGLStencilManager.prototype.bindGraphics = function (graphics, webGLData) { +WebGLStencilManager.prototype.bindGraphics = function (graphics, webGLData) +{ //if (this._currentGraphics === graphics)return; this._currentGraphics = graphics; @@ -114,7 +128,8 @@ offset = this.renderer.offset, shader;// = this.renderer.shaderManager.primitiveShader; - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { shader = this.renderer.shaderManager.complexPrimitiveShader; this.renderer.shaderManager.setShader(shader); @@ -141,7 +156,8 @@ // set the index buffer! gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, webGLData.indexBuffer); } - else { + else + { //this.renderer.shaderManager.activatePrimitiveShader(); shader = this.renderer.shaderManager.primitiveShader; this.renderer.shaderManager.setShader( shader ); @@ -154,7 +170,7 @@ gl.uniform2f(shader.uniforms.offsetVector._location, -offset.x, -offset.y); gl.uniform3fv(shader.uniforms.tint._location, utils.hex2rgb(graphics.tint)); - + gl.uniform1f(shader.uniforms.alpha._location, graphics.worldAlpha); @@ -172,19 +188,22 @@ * @param graphics {Graphics} * @param webGLData {Array} */ -WebGLStencilManager.prototype.popStencil = function (graphics, webGLData) { +WebGLStencilManager.prototype.popStencil = function (graphics, webGLData) +{ var gl = this.renderer.gl; this.stencilStack.pop(); this.count--; - if (this.stencilStack.length === 0) { + if (this.stencilStack.length === 0) + { // the stack is empty! gl.disable(gl.STENCIL_TEST); } - else { + else + { var level = this.count; @@ -192,14 +211,17 @@ gl.colorMask(false, false, false, false); - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { this.reverse = !this.reverse; - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } @@ -213,31 +235,38 @@ // draw the triangle strip! gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); - if (!this.reverse) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); } } - else { + else + { // console.log("<<>>") - if (!this.reverse) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } - else { + 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) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); } } @@ -253,7 +282,8 @@ * Destroys the mask stack. * */ -WebGLStencilManager.prototype.destroy = function () { +WebGLStencilManager.prototype.destroy = function () +{ this.renderer = null; this.stencilStack = null; }; diff --git a/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js b/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js index 913ba5e..1ea7d19 100644 --- a/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js +++ b/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function ComplexPrimitiveShader(gl) { +function ComplexPrimitiveShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -24,7 +25,8 @@ 'uniform float flipY;', 'varying vec4 vColor;', - 'void main(void) {', + '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);', @@ -37,7 +39,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = vColor;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/FastShader.js b/src/core/renderers/webgl/shaders/FastShader.js index bd2e29a..2e5e060 100644 --- a/src/core/renderers/webgl/shaders/FastShader.js +++ b/src/core/renderers/webgl/shaders/FastShader.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function FastShader(gl) { +function FastShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -28,7 +29,8 @@ 'const vec2 center = vec2(-1.0, 1.0);', - 'void main(void) {', + 'void main(void) + {', ' vec2 v;', ' vec2 sv = aVertexPosition * aScale;', ' v.x = (sv.x) * cos(aRotation) - (sv.y) * sin(aRotation);', @@ -49,7 +51,8 @@ 'uniform sampler2D uSampler;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/PrimitiveShader.js b/src/core/renderers/webgl/shaders/PrimitiveShader.js index 6f25409..a25f54f 100644 --- a/src/core/renderers/webgl/shaders/PrimitiveShader.js +++ b/src/core/renderers/webgl/shaders/PrimitiveShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function PrimitiveShader(gl) { +function PrimitiveShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -23,7 +24,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + '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);', @@ -36,7 +38,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = vColor;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/Shader.js b/src/core/renderers/webgl/shaders/Shader.js index f8964f5..fd75ef5 100644 --- a/src/core/renderers/webgl/shaders/Shader.js +++ b/src/core/renderers/webgl/shaders/Shader.js @@ -6,7 +6,8 @@ * @param [fragmentSrc] {string} The source of the fragment shader. * @param [vertexSrc] {string} The source of the vertex shader. */ -function Shader(gl, vertexSrc, fragmentSrc, customUniforms, customAttributes) { +function Shader(gl, vertexSrc, fragmentSrc, customUniforms, customAttributes) +{ /** * @member {number} * @readonly @@ -33,7 +34,8 @@ dimensions: { type: '4f', value: new Float32Array(4) } }; - for (var u in customUniforms) { + for (var u in customUniforms) + { this.uniforms[u] = customUniforms[u]; } @@ -43,7 +45,8 @@ aColor: 0 }; - for (var a in customAttributes) { + for (var a in customAttributes) + { this.attributes[a] = customAttributes[a]; } @@ -66,7 +69,8 @@ 'const vec2 center = vec2(-1.0, 1.0);', - 'void main(void) {', + 'void main(void) + {', ' gl_Position = vec4( ((aVertexPosition + offsetVector) / projectionVector) + center , 0.0, 1.0);', ' vTextureCoord = aTextureCoord;', ' vColor = vec4(aColor.rgb * aColor.a, aColor.a);', @@ -85,7 +89,8 @@ 'uniform sampler2D uSampler;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;', '}' ].join('\n'); @@ -96,7 +101,8 @@ Shader.prototype.constructor = Shader; module.exports = Shader; -Shader.prototype.init = function () { +Shader.prototype.init = function () +{ this.compile(); this.gl.useProgram(this.program); @@ -105,14 +111,18 @@ this.cacheAttributeLocations(Object.keys(this.attributes)); }; -Shader.prototype.cacheUniformLocations = function (keys) { - for (var i = 0; i < keys.length; ++i) { +Shader.prototype.cacheUniformLocations = function (keys) +{ + for (var i = 0; i < keys.length; ++i) + { this.uniforms[keys[i]]._location = this.gl.getUniformLocation(this.program, keys[i]); } }; -Shader.prototype.cacheAttributeLocations = function (keys) { - for (var i = 0; i < keys.length; ++i) { +Shader.prototype.cacheAttributeLocations = function (keys) +{ + for (var i = 0; i < keys.length; ++i) + { this.attributes[keys[i]] = this.gl.getAttribLocation(this.program, keys[i]); } @@ -124,14 +134,16 @@ // 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.attributes.aColor === -1) { + // if (this.attributes.aColor === -1) + { // this.attributes.aColor = 2; // } // End worst hack eva // }; -Shader.prototype.compile = function () { +Shader.prototype.compile = function () +{ var gl = this.gl; var glVertShader = this._glCompile(gl.VERTEX_SHADER, this.vertexSrc); @@ -144,13 +156,15 @@ gl.linkProgram(program); // if linking fails, then log and cleanup - if (!gl.getProgramParameter(program, gl.LINK_STATUS)) { + if (!gl.getProgramParameter(program, gl.LINK_STATUS)) + { window.console.error('Pixi.js Error: Could not initialize shader.'); window.console.error('gl.VALIDATE_STATUS', gl.getProgramParameter(program, gl.VALIDATE_STATUS)); window.console.error('gl.getError()', gl.getError()); // if there is a program info log, log it - if (gl.getProgramInfoLog(program) !== '') { + if (gl.getProgramInfoLog(program) !== '') + { window.console.warn('Pixi.js Warning: gl.getProgramInfoLog()', gl.getProgramInfoLog(program)); } @@ -165,18 +179,21 @@ return (this.program = program); }; -Shader.prototype.syncUniforms = function () { +Shader.prototype.syncUniforms = function () +{ var gl = this.gl; this.textureCount = 1; - for (var key in this.uniforms) { + for (var key in this.uniforms) + { var uniform = this.uniforms[key], location = uniform._location, value = uniform.value, i, il; - switch (uniform.type) { + switch (uniform.type) + { // single int value case 'i': case '1i': @@ -282,7 +299,8 @@ // a Color Value case 'c': - if (typeof value === 'number') { + if (typeof value === 'number') + { value = utils.hex2rgb(value); } @@ -311,11 +329,13 @@ // array of 2D Point objects case 'v2v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(2 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 2] = value[i].x; uniform._array[i * 2 + 1] = value[i].y; } @@ -325,11 +345,13 @@ // array of 3D Point objects case 'v3v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(3 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 3] = value[i].x; uniform._array[i * 3 + 1] = value[i].y; uniform._array[i * 3 + 2] = value[i].z; @@ -341,11 +363,13 @@ // array of 4D Point objects case 'v4v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(4 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 4] = value[i].x; uniform._array[i * 4 + 1] = value[i].y; uniform._array[i * 4 + 2] = value[i].z; @@ -359,7 +383,8 @@ // PIXI.Texture case 't': case 'sampler2D': - if (!uniform.value || !uniform.value.baseTexture || !uniform.value.baseTexture.hasLoaded) { + if (!uniform.value || !uniform.value.baseTexture || !uniform.value.baseTexture.hasLoaded) + { break; } @@ -376,7 +401,8 @@ this.textureCount++; // initialize the texture if we haven't yet - if (!uniform._init) { + if (!uniform._init) + { this.initSampler2D(uniform); uniform._init = true; @@ -394,11 +420,13 @@ * Initialises a Sampler2D uniform (which may only be available later on after initUniforms once the texture has loaded) * */ -Shader.prototype.initSampler2D = function (uniform) { +Shader.prototype.initSampler2D = function (uniform) +{ var gl = this.gl; // Extended texture data - if (uniform.textureData) { + if (uniform.textureData) + { var data = uniform.textureData; // GLTexture = mag linear, min linear_mipmap_linear, wrap repeat + gl.generateMipmap(gl.TEXTURE_2D); @@ -417,14 +445,16 @@ var wrapT = (data.wrapT) ? data.wrapT : gl.CLAMP_TO_EDGE; var format = (data.luminance) ? gl.LUMINANCE : gl.RGBA; - if (data.repeat) { + if (data.repeat) + { wrapS = gl.REPEAT; wrapT = gl.REPEAT; } gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, !!data.flipY); - if (data.width) { + if (data.width) + { var width = (data.width) ? data.width : 512; var height = (data.height) ? data.height : 2; var border = (data.border) ? data.border : 0; @@ -432,7 +462,8 @@ // 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 { + 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); } @@ -448,7 +479,8 @@ * Destroys the shader. * */ -Shader.prototype.destroy = function () { +Shader.prototype.destroy = function () +{ this.gl.deleteProgram(this.program); this.gl = null; @@ -459,13 +491,15 @@ this.fragmentSrc = null; }; -Shader.prototype._glCompile = function (type, src) { +Shader.prototype._glCompile = function (type, src) +{ var shader = this.gl.createShader(type); this.gl.shaderSource(shader, src); this.gl.compileShader(shader); - if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) { + if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) + { window.console.log(this.gl.getShaderInfoLog(shader)); return null; } diff --git a/src/core/renderers/webgl/shaders/StripShader.js b/src/core/renderers/webgl/shaders/StripShader.js index 193f6e1..a7abcc6 100644 --- a/src/core/renderers/webgl/shaders/StripShader.js +++ b/src/core/renderers/webgl/shaders/StripShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function StripShader(gl) { +function StripShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -20,7 +21,8 @@ 'varying vec2 vTextureCoord;', - 'void main(void) {', + '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);', @@ -36,7 +38,8 @@ 'varying vec2 vTextureCoord;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vec2(vTextureCoord.x, vTextureCoord.y)) * alpha;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/utils/FilterTexture.js b/src/core/renderers/webgl/utils/FilterTexture.js index d2c8423..4433d44 100644 --- a/src/core/renderers/webgl/utils/FilterTexture.js +++ b/src/core/renderers/webgl/utils/FilterTexture.js @@ -8,7 +8,8 @@ * @param height {number} the vertical range of the filter * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values */ -function FilterTexture(gl, width, height, scaleMode) { +function FilterTexture(gl, width, height, scaleMode) +{ /** * @member {WebGLContext} */ @@ -59,7 +60,8 @@ * Clears the filter texture. * */ -FilterTexture.prototype.clear = function () { +FilterTexture.prototype.clear = function () +{ var gl = this.gl; gl.clearColor(0,0,0, 0); @@ -72,8 +74,10 @@ * @param width {number} the new width of the texture * @param height {number} the new height of the texture */ -FilterTexture.prototype.resize = function (width, height) { - if (this.width === width && this.height === height) { +FilterTexture.prototype.resize = function (width, height) +{ + if (this.width === width && this.height === height) + { return; } @@ -96,7 +100,8 @@ * Destroys the filter texture. * */ -FilterTexture.prototype.destroy = function () { +FilterTexture.prototype.destroy = function () +{ var gl = this.gl; gl.deleteFramebuffer( this.frameBuffer ); gl.deleteTexture( this.texture ); diff --git a/src/core/display/DisplayObject.js b/src/core/display/DisplayObject.js index 66ebc3c..20e778c 100644 --- a/src/core/display/DisplayObject.js +++ b/src/core/display/DisplayObject.js @@ -7,7 +7,8 @@ * @class * @namespace PIXI */ -function DisplayObject() { +function DisplayObject() +{ /** * The coordinate of the object relative to the local coordinates of the parent. * @@ -152,10 +153,12 @@ * @memberof DisplayObject# */ x: { - get: function () { + get: function () + { return this.position.x; }, - set: function (value) { + set: function (value) + { this.position.x = value; } }, @@ -167,10 +170,12 @@ * @memberof DisplayObject# */ y: { - get: function () { + get: function () + { return this.position.y; }, - set: function (value) { + set: function (value) + { this.position.y = value; } }, @@ -183,11 +188,13 @@ * @readonly */ worldVisible: { - get: function () { + get: function () + { var item = this; do { - if (!item.visible) { + if (!item.visible) + { return false; } @@ -207,17 +214,21 @@ * @memberof DisplayObject# */ mask: { - get: function () { + get: function () + { return this._mask; }, - set: function (value) { - if (this._mask) { + set: function (value) + { + if (this._mask) + { this._mask.isMask = false; } this._mask = value; - if (this._mask) { + if (this._mask) + { this._mask.isMask = true; } } @@ -232,18 +243,23 @@ * @memberof DisplayObject# */ filters: { - get: function () { + get: function () + { return this._filters; }, - set: function (value) { - if (value) { + set: function (value) + { + if (value) + { // now put all the passes in one place.. var passes = []; - for (var i = 0; i < value.length; i++) { + for (var i = 0; i < value.length; i++) + { var filterPasses = value[i].passes; - for (var j = 0; j < filterPasses.length; j++) { + for (var j = 0; j < filterPasses.length; j++) + { passes.push(filterPasses[j]); } } @@ -264,8 +280,9 @@ * * @private */ -DisplayObject.prototype.updateTransform = function () { - +DisplayObject.prototype.updateTransform = function () +{ + // create some matrix refs for easy access var pt = this.parent.worldTransform; var wt = this.worldTransform; @@ -274,9 +291,11 @@ var a, b, c, d, tx, ty; // so if rotation is between 0 then we can simplify the multiplication process.. - if (this.rotation % math.PI_2) { + if (this.rotation % math.PI_2) + { // 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) { + if (this.rotation !== this.rotationCache) + { this.rotationCache = this.rotation; this._sr = Math.sin(this.rotation); this._cr = Math.cos(this.rotation); @@ -291,7 +310,8 @@ ty = this.position.y; // check for pivot.. not often used so geared towards that fact! - if (this.pivot.x || this.pivot.y) { + 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; } @@ -304,7 +324,8 @@ wt.tx = tx * pt.a + ty * pt.c + pt.tx; wt.ty = tx * pt.b + ty * pt.d + pt.ty; } - else { + else + { // lets do the fast version as we know there is no rotation.. a = this.scale.x; d = this.scale.y; @@ -333,7 +354,8 @@ * @param matrix {Matrix} * @return {Rectangle} the rectangular bounding area */ -DisplayObject.prototype.getBounds = function (/* matrix */) { +DisplayObject.prototype.getBounds = function (/* matrix */) +{ return math.Rectangle.EMPTY; }; @@ -342,7 +364,8 @@ * * @return {Rectangle} the rectangular bounding area */ -DisplayObject.prototype.getLocalBounds = function () { +DisplayObject.prototype.getLocalBounds = function () +{ return this.getBounds(math.Matrix.IDENTITY); }; @@ -352,7 +375,8 @@ * @param position {Point} The world origin to calculate from * @return {Point} A point object representing the position of this object */ -DisplayObject.prototype.toGlobal = function (position) { +DisplayObject.prototype.toGlobal = function (position) +{ // don't need to u[date the lot this.displayObjectUpdateTransform(); return this.worldTransform.apply(position); @@ -365,8 +389,10 @@ * @param [from] {DisplayObject} The DisplayObject to calculate the global position from * @return {Point} A point object representing the position of this object */ -DisplayObject.prototype.toLocal = function (position, from) { - if (from) { +DisplayObject.prototype.toLocal = function (position, from) +{ + if (from) + { position = from.toGlobal(position); } @@ -381,7 +407,8 @@ * @param renderer {WebGLRenderer} The renderer * @private */ -DisplayObject.prototype.renderWebGL = function (/* renderer */) { +DisplayObject.prototype.renderWebGL = function (/* renderer */) +{ // OVERWRITE; }; @@ -391,6 +418,7 @@ * @param renderer {CanvasRenderer} The renderer * @private */ -DisplayObject.prototype.renderCanvas = function (/* renderer */) { +DisplayObject.prototype.renderCanvas = function (/* renderer */) +{ // OVERWRITE; }; diff --git a/src/core/display/DisplayObjectContainer.js b/src/core/display/DisplayObjectContainer.js index 689f40b..4625ee8 100644 --- a/src/core/display/DisplayObjectContainer.js +++ b/src/core/display/DisplayObjectContainer.js @@ -12,7 +12,8 @@ * @extends DisplayObject * @namespace PIXI */ -function DisplayObjectContainer() { +function DisplayObjectContainer() +{ DisplayObject.call(this); /** @@ -47,17 +48,21 @@ * @memberof DisplayObjectContainer# */ width: { - get: function () { + get: function () + { return this.scale.x * this.getLocalBounds().width; }, - set: function (value) { + set: function (value) + { var width = this.getLocalBounds().width; - if(width !== 0) { + if(width !== 0) + { this.scale.x = value / width; } - else { + else + { this.scale.x = 1; } @@ -73,17 +78,21 @@ * @memberof DisplayObjectContainer# */ height: { - get: function () { + get: function () + { return this.scale.y * this.getLocalBounds().height; }, - set: function (value) { + set: function (value) + { var height = this.getLocalBounds().height; - if (height !== 0) { + if (height !== 0) + { this.scale.y = value / height ; } - else { + else + { this.scale.y = 1; } @@ -100,18 +109,23 @@ * @memberof DisplayObject# */ cacheAsBitmap: { - get: function () { + get: function () + { return this._cacheAsBitmap; }, - set: function (value) { - if (this._cacheAsBitmap === value) { + set: function (value) + { + if (this._cacheAsBitmap === value) + { return; } - if (value) { + if (value) + { this._generateCachedSprite(); } - else { + else + { this._destroyCachedSprite(); } @@ -126,7 +140,8 @@ * @param child {DisplayObject} The DisplayObject to add to the container * @return {DisplayObject} The child that was added. */ -DisplayObjectContainer.prototype.addChild = function (child) { +DisplayObjectContainer.prototype.addChild = function (child) +{ return this.addChildAt(child, this.children.length); }; @@ -137,14 +152,18 @@ * @param index {Number} The index to place the child in * @return {DisplayObject} The child that was added. */ -DisplayObjectContainer.prototype.addChildAt = function (child, index) { +DisplayObjectContainer.prototype.addChildAt = function (child, index) +{ // prevent adding self as child - if (child === this) { + if (child === this) + { return; } - if (index >= 0 && index <= this.children.length) { - if (child.parent) { + if (index >= 0 && index <= this.children.length) + { + if (child.parent) + { child.parent.removeChild(child); } @@ -154,7 +173,8 @@ return child; } - else { + else + { throw new Error(child + 'addChildAt: The index '+ index +' supplied is out of bounds ' + this.children.length); } }; @@ -165,15 +185,18 @@ * @param child {DisplayObject} * @param child2 {DisplayObject} */ -DisplayObjectContainer.prototype.swapChildren = function (child, child2) { - if (child === child2) { +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) { + if (index1 < 0 || index2 < 0) + { throw new Error('swapChildren: Both the supplied DisplayObjects must be a child of the caller.'); } @@ -187,10 +210,12 @@ * @param child {DisplayObject} The DisplayObject instance to identify * @return {Number} The index position of the child display object to identify */ -DisplayObjectContainer.prototype.getChildIndex = function (child) { +DisplayObjectContainer.prototype.getChildIndex = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { throw new Error('The supplied DisplayObject must be a child of the caller'); } @@ -203,8 +228,10 @@ * @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 */ -DisplayObjectContainer.prototype.setChildIndex = function (child, index) { - if (index < 0 || index >= this.children.length) { +DisplayObjectContainer.prototype.setChildIndex = function (child, index) +{ + if (index < 0 || index >= this.children.length) + { throw new Error('The supplied index is out of bounds'); } @@ -220,8 +247,10 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child at the given index, if any. */ -DisplayObjectContainer.prototype.getChildAt = function (index) { - if (index < 0 || index >= this.children.length) { +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'); } @@ -234,10 +263,12 @@ * @param child {DisplayObject} The DisplayObject to remove * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChild = function (child) { +DisplayObjectContainer.prototype.removeChild = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { return; } @@ -250,7 +281,8 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChildAt = function (index) { +DisplayObjectContainer.prototype.removeChildAt = function (index) +{ var child = this.getChildAt(index); child.parent = null; @@ -265,24 +297,29 @@ * @param beginIndex {Number} The beginning position. Default value is 0. * @param endIndex {Number} The ending position. Default value is size of the container. */ -DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) { +DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) +{ var begin = beginIndex || 0; var end = typeof endIndex === 'number' ? endIndex : this.children.length; var range = end - begin; - if (range > 0 && range <= end) { + if (range > 0 && range <= end) + { var removed = this.children.splice(begin, range); - for (var i = 0; i < removed.length; ++i) { + for (var i = 0; i < removed.length; ++i) + { removed[i].parent = null; } return removed; } - else if (range === 0 && this.children.length === 0) { + else if (range === 0 && this.children.length === 0) + { return []; } - else { + else + { throw new RangeError('removeChildren: numeric values are outside the acceptable range.'); } }; @@ -291,7 +328,8 @@ * Generates and updates the cached sprite for this object. * */ -DisplayObjectContainer.prototype.updateCachedSprite = function () { +DisplayObjectContainer.prototype.updateCachedSprite = function () +{ this._generateCachedSprite(); }; @@ -304,7 +342,8 @@ * @param renderer {CanvasRenderer|WebGLRenderer} The renderer used to generate the texture. * @return {Texture} a texture of the graphics object */ -DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) { +DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) +{ var bounds = this.getLocalBounds(); var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0, renderer, scaleMode, resolution); @@ -322,18 +361,22 @@ * * @private */ -DisplayObjectContainer.prototype.updateTransform = function () { - if (!this.visible) { +DisplayObjectContainer.prototype.updateTransform = function () +{ + if (!this.visible) + { return; } this.displayObjectUpdateTransform(); - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { return; } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } }; @@ -346,8 +389,10 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getBounds = function () { - if (this.children.length === 0) { +DisplayObjectContainer.prototype.getBounds = function () +{ + if (this.children.length === 0) + { return math.Rectangle.EMPTY; } @@ -365,10 +410,12 @@ var childVisible = false; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -386,7 +433,8 @@ maxY = maxY > childMaxY ? maxY : childMaxY; } - if (!childVisible) { + if (!childVisible) + { return math.Rectangle.EMPTY; } @@ -407,12 +455,14 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getLocalBounds = function () { +DisplayObjectContainer.prototype.getLocalBounds = function () +{ var matrixCache = this.worldTransform; this.worldTransform = math.Matrix.IDENTITY; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } @@ -428,13 +478,16 @@ * * @param renderer {WebGLRenderer} The renderer */ -DisplayObjectContainer.prototype.renderWebGL = function (renderer) { +DisplayObjectContainer.prototype.renderWebGL = function (renderer) +{ // if the object is not visible or the alpha is 0 then no need to render this element - if (!this.visible || this.alpha <= 0) { + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } @@ -442,14 +495,17 @@ var i, j; // do a quick check to see if this element has a mask or a filter. - if (this._mask || this._filters) { + if (this._mask || this._filters) + { // push filter first as we need to ensure the stencil buffer is correct for any masking - if (this._filters) { + if (this._filters) + { renderer.spriteBatch.flush(); renderer.filterManager.pushFilter(this._filterBlock); } - if (this._mask) { + if (this._mask) + { renderer.spriteBatch.stop(); renderer.maskManager.pushMask(this.mask, renderer); renderer.spriteBatch.start(); @@ -459,36 +515,42 @@ this._renderWebGL(renderer); // now loop through the children and make sure they get rendered - for (i = 0, j = this.children.length; i < j; i++) { + for (i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderWebGL(renderer); } // time to stop the sprite batch as either a mask element or a filter draw will happen next renderer.spriteBatch.stop(); - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(this._mask, renderer); } - if (this._filters) { + if (this._filters) + { renderer.filterManager.popFilter(); } renderer.spriteBatch.start(); } - else { + else + { this._renderWebGL(renderer); // simple render children! - for (i = 0, j = this.children.length; i < j; ++i) { + for (i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderWebGL(renderer); } } }; -DisplayObjectContainer.prototype._renderWebGL = function (renderer) { +DisplayObjectContainer.prototype._renderWebGL = function (renderer) +{ // this is where content itself gets renderd.. @@ -499,25 +561,31 @@ * * @param renderer {CanvasRenderer} The renderer */ -DisplayObjectContainer.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0) { +DisplayObjectContainer.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -528,13 +596,16 @@ * @param renderer {WebGLRenderer|CanvasRenderer} The renderer * @private */ -DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) { +DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) +{ this._cachedSprite.worldAlpha = this.worldAlpha; - if (renderer.gl) { + if (renderer.gl) + { this._cachedSprite.renderWebGL(renderer); } - else { + else + { this._cachedSprite.renderCanvas(renderer); } }; @@ -544,10 +615,12 @@ * * @private */ -DisplayObjectContainer.prototype._generateCachedSprite = function () { +DisplayObjectContainer.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { // TODO - RenderTexture now *requires* a renderer instance, so this is like broken // because `renderer` isn't actually in scope here :P var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0); @@ -555,7 +628,8 @@ this._cachedSprite = new Sprite(renderTexture); this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.texture.resize(bounds.width | 0, bounds.height | 0); } @@ -580,8 +654,10 @@ * * @private */ -DisplayObjectContainer.prototype._destroyCachedSprite = function () { - if (!this._cachedSprite) { +DisplayObjectContainer.prototype._destroyCachedSprite = function () +{ + if (!this._cachedSprite) + { return; } diff --git a/src/core/display/Sprite.js b/src/core/display/Sprite.js index 707da24..5862aef 100644 --- a/src/core/display/Sprite.js +++ b/src/core/display/Sprite.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param texture {Texture} The texture for this sprite */ -function Sprite(texture) { +function Sprite(texture) +{ DisplayObjectContainer.call(this); /** @@ -85,12 +86,14 @@ this.texture = texture || Texture.EMPTY; } -Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) { +Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) +{ DisplayObjectContainer.prototype.destroy.call(this); this.anchor = null; - if (destroyTexture) { + if (destroyTexture) + { this._texture.destroy(destroyBaseTexture); } @@ -111,10 +114,12 @@ * @memberof Sprite# */ width: { - get: function () { + get: function () + { return this.scale.x * this.texture.frame.width; }, - set: function (value) { + set: function (value) + { this.scale.x = value / this.texture.frame.width; this._width = value; } @@ -127,10 +132,12 @@ * @memberof Sprite# */ height: { - get: function () { + get: function () + { return this.scale.y * this.texture.frame.height; }, - set: function (value) { + set: function (value) + { this.scale.y = value / this.texture.frame.height; this._height = value; } @@ -143,23 +150,29 @@ * @memberof Sprite# */ texture: { - get: function () { + get: function () + { return this._texture; }, - set: function (value) { - if (this._texture === value) { + set: function (value) + { + if (this._texture === value) + { return; } this._texture = value; this.cachedTint = 0xFFFFFF; - if (value) { + if (value) + { // wait for the texture to load - if (value.baseTexture.hasLoaded) { + if (value.baseTexture.hasLoaded) + { this._onTextureUpdate(); } - else { + else + { value.once('update', this._onTextureUpdate.bind(this)); } } @@ -172,18 +185,22 @@ * * @private */ -Sprite.prototype._onTextureUpdate = function () { +Sprite.prototype._onTextureUpdate = function () +{ // so if _width is 0 then width was not set.. - if (this._width) { + if (this._width) + { this.scale.x = this._width / this.texture.frame.width; } - if (this._height) { + if (this._height) + { this.scale.y = this._height / this.texture.frame.height; } }; -Sprite.prototype._renderWebGL = function (renderer) { +Sprite.prototype._renderWebGL = function (renderer) +{ // this is where content gets renderd.. // watch this space for a little render state manager.. @@ -197,7 +214,8 @@ * @param matrix {Matrix} the transformation matrix of the sprite * @return {Rectangle} the framing rectangle */ -Sprite.prototype.getBounds = function (matrix) { +Sprite.prototype.getBounds = function (matrix) +{ var width = this.texture.frame.width; var height = this.texture.frame.height; @@ -224,11 +242,13 @@ if(b === 0 && c === 0) { // scale may be negative! - if (a < 0) { + if (a < 0) + { a *= -1; } - if (d < 0) { + if (d < 0) + { d *= -1; } @@ -293,28 +313,34 @@ * * @param renderer {CanvasRenderer} The renderer */ -Sprite.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) { +Sprite.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) + { return; } - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; renderer.context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } // Ignore null sources - if (this.texture.valid) { + if (this.texture.valid) + { var resolution = this.texture.baseTexture.resolution / renderer.resolution; renderer.context.globalAlpha = this.worldAlpha; // If smoothingEnabled is supported and we need to change the smoothing property for this texture - if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) { + if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) + { renderer.scaleMode = this.texture.baseTexture.scaleMode; renderer.context[renderer.smoothProperty] = (renderer.scaleMode === CONST.scaleModes.LINEAR); } @@ -324,7 +350,8 @@ var dy = (this.texture.trim ? this.texture.trim.y : 0) - (this.anchor.y * this.texture.trim.height); // Allow for pixel rounding - if (renderer.roundPixels) { + if (renderer.roundPixels) + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -337,7 +364,8 @@ dx = dx | 0; dy = dy | 0; } - else { + else + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -348,8 +376,10 @@ ); } - if (this.tint !== 0xFFFFFF) { - if (this.cachedTint !== this.tint) { + if (this.tint !== 0xFFFFFF) + { + if (this.cachedTint !== this.tint) + { this.cachedTint = this.tint; // TODO clean up caching - how to clean up the caches? @@ -368,7 +398,8 @@ this.texture.crop.height / resolution ); } - else { + else + { renderer.context.drawImage( this.texture.baseTexture.source, this.texture.crop.x, @@ -383,11 +414,13 @@ } } - for (var i = 0, j = this.children.length; i < j; i++) { + for (var i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -402,10 +435,12 @@ * @param frameId {String} The frame Id of the texture in the cache * @return {Sprite} A new Sprite using a texture from the texture cache matching the frameId */ -Sprite.fromFrame = function (frameId) { +Sprite.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache' + this); } @@ -420,6 +455,7 @@ * @param imageId {String} The image url of the texture * @return {Sprite} A new Sprite using a texture from the texture cache matching the image id */ -Sprite.fromImage = function (imageId, crossorigin, scaleMode) { +Sprite.fromImage = function (imageId, crossorigin, scaleMode) +{ return new Sprite(Texture.fromImage(imageId, crossorigin, scaleMode)); }; diff --git a/src/core/display/SpriteBatch.js b/src/core/display/SpriteBatch.js index 3187777..c196fef 100644 --- a/src/core/display/SpriteBatch.js +++ b/src/core/display/SpriteBatch.js @@ -12,7 +12,8 @@ * ```js * var container = new SpriteBatch(); * - * for(var i = 0; i < 100; ++i) { + * for(var i = 0; i < 100; ++i) + * { * var sprite = new PIXI.Sprite.fromImage("myImage.png"); * container.addChild(sprite); * } @@ -25,7 +26,8 @@ */ //TODO RENAME to PARTICLE CONTAINER? -function SpriteBatch() { +function SpriteBatch() +{ DisplayObjectContainer.call(this); } @@ -38,7 +40,8 @@ * * @private */ -SpriteBatch.prototype.updateTransform = function () { +SpriteBatch.prototype.updateTransform = function () +{ // TODO don't need to! this.displayObjectUpdateTransform(); // PIXI.DisplayObjectContainer.prototype.updateTransform.call( this ); @@ -50,8 +53,10 @@ * @param renderer {WebGLRenderer} The webgl renderer * @private */ -SpriteBatch.prototype.renderWebGL = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderWebGL = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -71,8 +76,10 @@ * @param renderer {CanvasRenderer} The canvas renderer * @private */ -SpriteBatch.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -84,10 +91,12 @@ this.displayObjectUpdateTransform(); - for (var i = 0; i < this.children.length; ++i) { + for (var i = 0; i < this.children.length; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -95,9 +104,11 @@ context.globalAlpha = this.worldAlpha * child.alpha; - if (child.rotation % (Math.PI * 2) === 0) { + if (child.rotation % (Math.PI * 2) === 0) + { // this is the fastest way to optimise! - if rotation is 0 then we can avoid any kind of setTransform call - if (isRotated) { + if (isRotated) + { context.setTransform( transform.a, transform.b, @@ -122,8 +133,10 @@ frame.height * child.scale.y ); } - else { - if (!isRotated) { + else + { + if (!isRotated) + { isRotated = true; } @@ -131,7 +144,8 @@ var childTransform = child.worldTransform; - if (renderer.roundPixels) { + if (renderer.roundPixels) + { context.setTransform( childTransform.a, childTransform.b, @@ -141,7 +155,8 @@ childTransform.ty | 0 ); } - else { + else + { context.setTransform( childTransform.a, childTransform.b, diff --git a/src/core/index.js b/src/core/index.js index 3954b6f..eb4a82b 100644 --- a/src/core/index.js +++ b/src/core/index.js @@ -58,11 +58,13 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRenderer: function (width, height, options, noWebGL) { + autoDetectRenderer: function (width, height, options, noWebGL) + { width = width || 800; height = height || 600; - if (!noWebGL && require('webgl-enabled')()) { + if (!noWebGL && require('webgl-enabled')()) + { return new core.WebGLRenderer(width, height, options); } @@ -87,7 +89,8 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRecommendedRenderer: function (width, height, options) { + autoDetectRecommendedRenderer: function (width, height, options) + { var isAndroid = /Android/i.test(navigator.userAgent); return core.autoDetectRenderer(width, height, options, isAndroid); diff --git a/src/core/math/Matrix.js b/src/core/math/Matrix.js index c2f87e2..2ff4848 100644 --- a/src/core/math/Matrix.js +++ b/src/core/math/Matrix.js @@ -10,7 +10,8 @@ * @class * @namespace PIXI */ -function Matrix() { +function Matrix() +{ /** * @member {number} * @default 1 @@ -63,7 +64,8 @@ * * @param array {number[]} The array that the matrix will be populated from. */ -Matrix.prototype.fromArray = function (array) { +Matrix.prototype.fromArray = function (array) +{ this.a = array[0]; this.b = array[1]; this.c = array[3]; @@ -78,14 +80,17 @@ * @param transpose {boolean} Whether we need to transpose the matrix or not * @return {number[]} the newly created array which contains the matrix */ -Matrix.prototype.toArray = function (transpose) { - if (!this.array) { +Matrix.prototype.toArray = function (transpose) +{ + if (!this.array) + { this.array = new Float32Array(9); } var array = this.array; - if (transpose) { + if (transpose) + { array[0] = this.a; array[1] = this.b; array[2] = 0; @@ -96,7 +101,8 @@ array[7] = this.ty; array[8] = 1; } - else { + else + { array[0] = this.a; array[1] = this.c; array[2] = this.tx; @@ -119,7 +125,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, transformed through this matrix */ -Matrix.prototype.apply = function (pos, newPos) { +Matrix.prototype.apply = function (pos, newPos) +{ newPos = newPos || new Point(); newPos.x = this.a * pos.x + this.c * pos.y + this.tx; @@ -136,7 +143,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, inverse-transformed through this matrix */ -Matrix.prototype.applyInverse = function (pos, newPos) { +Matrix.prototype.applyInverse = function (pos, newPos) +{ newPos = newPos || new Point(); var id = 1 / (this.a * this.d + this.c * -this.b); @@ -154,7 +162,8 @@ * @param {number} y * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.translate = function (x, y) { +Matrix.prototype.translate = function (x, y) +{ this.tx += x; this.ty += y; @@ -168,7 +177,8 @@ * @param {number} y The amount to scale vertically * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.scale = function (x, y) { +Matrix.prototype.scale = function (x, y) +{ this.a *= x; this.d *= y; this.c *= x; @@ -186,7 +196,8 @@ * @param {number} angle - The angle in radians. * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.rotate = function (angle) { +Matrix.prototype.rotate = function (angle) +{ var cos = Math.cos( angle ); var sin = Math.sin( angle ); @@ -210,7 +221,8 @@ * @param {Matrix} matrix * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.append = function (matrix) { +Matrix.prototype.append = function (matrix) +{ var a1 = this.a; var b1 = this.b; var c1 = this.c; @@ -232,7 +244,8 @@ * * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.identity = function () { +Matrix.prototype.identity = function () +{ this.a = 1; this.b = 0; this.c = 0; diff --git a/src/core/math/Point.js b/src/core/math/Point.js index 7565b2d..632f346 100644 --- a/src/core/math/Point.js +++ b/src/core/math/Point.js @@ -7,7 +7,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -function Point(x, y) { +function Point(x, y) +{ /** * @member {number} * @default 0 @@ -29,7 +30,8 @@ * * @return {Point} a copy of the point */ -Point.prototype.clone = function () { +Point.prototype.clone = function () +{ return new Point(this.x, this.y); }; @@ -40,7 +42,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -Point.prototype.set = function (x, y) { +Point.prototype.set = function (x, y) +{ this.x = x || 0; this.y = y || ( (y !== 0) ? this.x : 0 ) ; }; diff --git a/src/core/math/shapes/Circle.js b/src/core/math/shapes/Circle.js index 69cfdc9..4d76efc 100644 --- a/src/core/math/shapes/Circle.js +++ b/src/core/math/shapes/Circle.js @@ -10,7 +10,8 @@ * @param y {number} The Y coordinate of the center of this circle * @param radius {number} The radius of the circle */ -function Circle(x, y, radius) { +function Circle(x, y, radius) +{ /** * @member {number} * @default 0 @@ -46,7 +47,8 @@ * @method clone * @return {Circle} a copy of the Circle */ -Circle.prototype.clone = function () { +Circle.prototype.clone = function () +{ return new Circle(this.x, this.y, this.radius); }; @@ -58,8 +60,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Circle */ -Circle.prototype.contains = function (x, y) { - if (this.radius <= 0) { +Circle.prototype.contains = function (x, y) +{ + if (this.radius <= 0) + { return false; } @@ -79,6 +83,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Circle.prototype.getBounds = function () { +Circle.prototype.getBounds = function () +{ return new Rectangle(this.x - this.radius, this.y - this.radius, this.radius * 2, this.radius * 2); }; diff --git a/src/core/math/shapes/Ellipse.js b/src/core/math/shapes/Ellipse.js index 4f2d066..fefd01a 100644 --- a/src/core/math/shapes/Ellipse.js +++ b/src/core/math/shapes/Ellipse.js @@ -11,7 +11,8 @@ * @param width {number} The half width of this ellipse * @param height {number} The half height of this ellipse */ -function Ellipse(x, y, width, height) { +function Ellipse(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -53,7 +54,8 @@ * @method clone * @return {Ellipse} a copy of the ellipse */ -Ellipse.prototype.clone = function () { +Ellipse.prototype.clone = function () +{ return new Ellipse(this.x, this.y, this.width, this.height); }; @@ -65,8 +67,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coords are within this ellipse */ -Ellipse.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Ellipse.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } @@ -86,6 +90,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Ellipse.prototype.getBounds = function () { +Ellipse.prototype.getBounds = function () +{ return new Rectangle(this.x - this.width, this.y - this.height, this.width, this.height); }; diff --git a/src/core/math/shapes/Polygon.js b/src/core/math/shapes/Polygon.js index ae89148..fea6d37 100644 --- a/src/core/math/shapes/Polygon.js +++ b/src/core/math/shapes/Polygon.js @@ -10,16 +10,20 @@ * arguments passed can be flat x,y values e.g. `new Polygon(x,y, x,y, x,y, ...)` where `x` and `y` are * Numbers. */ -function Polygon(points) { +function Polygon(points) +{ //if points isn't an array, use arguments as the array - if (!(points instanceof Array)) { + if (!(points instanceof Array)) + { points = Array.prototype.slice.call(arguments); } //if this is a flat array of numbers, convert it to points - if (points[0] instanceof Point) { + if (points[0] instanceof Point) + { var p = []; - for (var i = 0, il = points.length; i < il; i++) { + for (var i = 0, il = points.length; i < il; i++) + { p.push(points[i].x, points[i].y); } @@ -51,7 +55,8 @@ * * @return {Polygon} a copy of the polygon */ -Polygon.prototype.clone = function () { +Polygon.prototype.clone = function () +{ return new Polygon(this.points.slice()); }; @@ -62,19 +67,22 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this polygon */ -Polygon.prototype.contains = function (x, y) { +Polygon.prototype.contains = function (x, y) +{ var inside = false; // use some raycasting to test hits // https://github.com/substack/point-in-polygon/blob/master/index.js var length = this.points.length / 2; - for (var i = 0, j = length - 1; i < length; j = i++) { + for (var i = 0, j = length - 1; i < length; j = i++) + { var xi = this.points[i * 2], yi = this.points[i * 2 + 1], xj = this.points[j * 2], yj = this.points[j * 2 + 1], intersect = ((yi > y) !== (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi); - if (intersect) { + if (intersect) + { inside = !inside; } } diff --git a/src/core/math/shapes/Rectangle.js b/src/core/math/shapes/Rectangle.js index 16ac62a..4008b68 100644 --- a/src/core/math/shapes/Rectangle.js +++ b/src/core/math/shapes/Rectangle.js @@ -10,7 +10,8 @@ * @param width {number} The overall width of this rectangle * @param height {number} The overall height of this rectangle */ -function Rectangle(x, y, width, height) { +function Rectangle(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -60,7 +61,8 @@ * * @return {Rectangle} a copy of the rectangle */ -Rectangle.prototype.clone = function () { +Rectangle.prototype.clone = function () +{ return new Rectangle(this.x, this.y, this.width, this.height); }; @@ -71,13 +73,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rectangle */ -Rectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Rectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/math/shapes/RoundedRectangle.js b/src/core/math/shapes/RoundedRectangle.js index 27d286e..7bf6411 100644 --- a/src/core/math/shapes/RoundedRectangle.js +++ b/src/core/math/shapes/RoundedRectangle.js @@ -11,7 +11,8 @@ * @param height {number} The overall height of this rounded rectangle * @param radius {number} Controls the radius of the rounded corners */ -function RoundedRectangle(x, y, width, height, radius) { +function RoundedRectangle(x, y, width, height, radius) +{ /** * @member {number} * @default 0 @@ -58,7 +59,8 @@ * * @return {RoundedRectangle} a copy of the rounded rectangle */ -RoundedRectangle.prototype.clone = function () { +RoundedRectangle.prototype.clone = function () +{ return new RoundedRectangle(this.x, this.y, this.width, this.height, this.radius); }; @@ -69,13 +71,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rounded Rectangle */ -RoundedRectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +RoundedRectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/primitives/Graphics.js b/src/core/primitives/Graphics.js index 261c534..e902d2a 100644 --- a/src/core/primitives/Graphics.js +++ b/src/core/primitives/Graphics.js @@ -16,7 +16,8 @@ * @extends DisplayObjectContainer * @namespace PIXI */ -function Graphics() { +function Graphics() +{ DisplayObjectContainer.call(this); this.renderable = true; @@ -154,16 +155,20 @@ * @private */ cacheAsBitmap: { - get: function () { + get: function () + { return this._cacheAsBitmap; }, - set: function (value) { + set: function (value) + { this._cacheAsBitmap = value; - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._generateCachedSprite(); } - else { + else + { this.destroyCachedSprite(); this.dirty = true; } @@ -176,7 +181,8 @@ * * @return {Graphics} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ var clone = new Graphics(); clone.renderable = this.renderable; @@ -192,7 +198,8 @@ clone.cachedSpriteDirty = this.cachedSpriteDirty; // copy graphics data - for (var i = 0; i < this.graphicsData.length; ++i) { + for (var i = 0; i < this.graphicsData.length; ++i) + { clone.graphicsData.push(this.graphicsData.clone()); } @@ -211,17 +218,21 @@ * @param alpha {number} alpha of the line to draw, will update the objects stored style * @return {Graphics} */ -Graphics.prototype.lineStyle = function (lineWidth, color, alpha) { +Graphics.prototype.lineStyle = function (lineWidth, color, alpha) +{ this.lineWidth = lineWidth || 0; this.lineColor = color || 0; this.lineAlpha = (arguments.length < 3) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length) + { // halfway through a line? start a new one! this.drawShape( new math.Polygon( this.currentPath.shape.points.slice(-2) )); } - else { + else + { // otherwise its empty so lets just set the line properties this.currentPath.lineWidth = this.lineWidth; this.currentPath.lineColor = this.lineColor; @@ -239,7 +250,8 @@ * @param y {number} the Y coordinate to move to * @return {Graphics} */ -Graphics.prototype.moveTo = function (x, y) { +Graphics.prototype.moveTo = function (x, y) +{ this.drawShape(new math.Polygon([x,y])); return this; @@ -253,7 +265,8 @@ * @param y {number} the Y coordinate to draw to * @return {Graphics} */ -Graphics.prototype.lineTo = function (x, y) { +Graphics.prototype.lineTo = function (x, y) +{ this.currentPath.shape.points.push(x, y); this.dirty = true; @@ -270,13 +283,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -285,7 +302,8 @@ n = 20, points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { this.moveTo(0, 0); } @@ -293,7 +311,8 @@ var fromY = points[points.length-1]; var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; xa = fromX + ( (cpX - fromX) * j ); @@ -319,13 +338,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -342,7 +365,8 @@ var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; dt = (1 - j); @@ -373,13 +397,17 @@ * @param radius {number} The radius of the arc * @return {Graphics} */ -Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points.push(x1, y1); } } - else { + else + { this.moveTo(x1, y1); } @@ -392,12 +420,15 @@ b2 = x2 - x1, mm = Math.abs(a1 * b2 - b1 * a2); - if (mm < 1.0e-8 || radius === 0) { - if (points[points.length-2] !== x1 || points[points.length-1] !== y1) { + if (mm < 1.0e-8 || radius === 0) + { + if (points[points.length-2] !== x1 || points[points.length-1] !== y1) + { points.push(x1, y1); } } - else { + else + { var dd = a1 * a1 + b1 * b1, cc = a2 * a2 + b2 * b2, tt = a1 * a2 + b1 * b2, @@ -433,42 +464,51 @@ * @param anticlockwise {boolean} Optional. Specifies whether the drawing should be counterclockwise or clockwise. False is default, and indicates clockwise, while true indicates counter-clockwise. * @return {Graphics} */ -Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) { +Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) +{ var startX = cx + Math.cos(startAngle) * radius; var startY = cy + Math.sin(startAngle) * radius; var points; // TODO - This if-else makes no sense. It uses currentPath in the else where it doesn't exist... - if (this.currentPath) { + if (this.currentPath) + { points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { points.push(startX, startY); } - else if (points[points.length-2] !== startX || points[points.length-1] !== startY) { + else if (points[points.length-2] !== startX || points[points.length-1] !== startY) + { points.push(startX, startY); } } - else { + else + { this.moveTo(startX, startY); points = this.currentPath.shape.points; } - if (startAngle === endAngle) { + if (startAngle === endAngle) + { return this; } - if (!anticlockwise && endAngle <= startAngle) { + if (!anticlockwise && endAngle <= startAngle) + { endAngle += Math.PI * 2; } - else if (anticlockwise && startAngle <= endAngle) { + else if (anticlockwise && startAngle <= endAngle) + { startAngle += Math.PI * 2; } var sweep = anticlockwise ? (startAngle - endAngle) *-1 : (endAngle - startAngle); var segs = (Math.abs(sweep)/ (Math.PI * 2)) * 40; - if (sweep === 0) { + if (sweep === 0) + { return this; } @@ -482,7 +522,8 @@ var remainder = ( segMinus % 1 ) / segMinus; - for (var i = 0; i <= segMinus; ++i) { + for (var i = 0; i <= segMinus; ++i) + { var real = i + remainder * i; var angle = ((theta) + startAngle + (theta2 * real)); @@ -506,13 +547,16 @@ * @param alpha {number} the alpha of the fill * @return {Graphics} */ -Graphics.prototype.beginFill = function (color, alpha) { +Graphics.prototype.beginFill = function (color, alpha) +{ this.filling = true; this.fillColor = color || 0; this.fillAlpha = (alpha === undefined) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length <= 2) + { this.currentPath.fill = this.filling; this.currentPath.fillColor = this.fillColor; this.currentPath.fillAlpha = this.fillAlpha; @@ -526,7 +570,8 @@ * * @return {Graphics} */ -Graphics.prototype.endFill = function () { +Graphics.prototype.endFill = function () +{ this.filling = false; this.fillColor = null; this.fillAlpha = 1; @@ -542,7 +587,8 @@ * @param height {number} The height of the rectangle * @return {Graphics} */ -Graphics.prototype.drawRect = function ( x, y, width, height ) { +Graphics.prototype.drawRect = function ( x, y, width, height ) +{ this.drawShape(new math.Rectangle(x,y, width, height)); return this; @@ -556,7 +602,8 @@ * @param height {number} The height of the rectangle * @param radius {number} Radius of the rectangle corners */ -Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) { +Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) +{ this.drawShape(new math.RoundedRectangle(x, y, width, height, radius)); return this; @@ -570,7 +617,8 @@ * @param radius {number} The radius of the circle * @return {Graphics} */ -Graphics.prototype.drawCircle = function (x, y, radius) { +Graphics.prototype.drawCircle = function (x, y, radius) +{ this.drawShape(new math.Circle(x,y, radius)); return this; @@ -585,7 +633,8 @@ * @param height {number} The half height of the ellipse * @return {Graphics} */ -Graphics.prototype.drawEllipse = function (x, y, width, height) { +Graphics.prototype.drawEllipse = function (x, y, width, height) +{ this.drawShape(new math.Ellipse(x, y, width, height)); return this; @@ -597,8 +646,10 @@ * @param path {Array} The path data used to construct the polygon. * @return {Graphics} */ -Graphics.prototype.drawPolygon = function (path) { - if (!(path instanceof Array)) { +Graphics.prototype.drawPolygon = function (path) +{ + if (!(path instanceof Array)) + { path = Array.prototype.slice.call(arguments); } @@ -612,7 +663,8 @@ * * @return {Graphics} */ -Graphics.prototype.clear = function () { +Graphics.prototype.clear = function () +{ this.lineWidth = 0; this.filling = false; @@ -631,7 +683,8 @@ * @param scaleMode {number} Should be one of the scaleMode consts * @return {Texture} a texture of the graphics object */ -Graphics.prototype.generateTexture = function (resolution, scaleMode) { +Graphics.prototype.generateTexture = function (resolution, scaleMode) +{ resolution = resolution || 1; var bounds = this.getBounds(); @@ -655,17 +708,21 @@ * * @param renderer {WebGLRenderer} */ -Graphics.prototype._renderWebGL = function (renderer) { +Graphics.prototype._renderWebGL = function (renderer) +{ // if the sprite is not visible or the alpha is 0 then no need to render this element - if (this.isMask === true) { + if (this.isMask === true) + { return; } // this code may still be needed so leaving for now.. - // + // /* - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture on the gpu too! @@ -681,17 +738,24 @@ return; } - */ - - // check if the webgl graphic needs to be updated - if (this.glDirty) { - this.dirty = true; - this.glDirty = false; - } + else */ - renderer.setObjectRendererer(renderer.graphicsRenderer); - renderer.graphicsRenderer.render(this); + renderer.spriteBatch.stop(); + renderer.blendModeManager.setBlendMode(this.blendMode); + // check blend mode + renderer.blendModeManager.setBlendMode( this.blendMode ); + + // check if the webgl graphic needs to be updated + if (this.glDirty) + { + this.dirty = true; + this.glDirty = false; + } + + WebGLGraphics.renderGraphics(this, renderer); + + renderer.spriteBatch.start(); }; /** @@ -700,14 +764,18 @@ * @param renderer {CanvasRenderer} * @private */ -Graphics.prototype.renderCanvas = function (renderer) { +Graphics.prototype.renderCanvas = function (renderer) +{ // 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.isMask === true) { + if (!this.visible || this.alpha <= 0 || this.isMask === true) + { return; } - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture @@ -723,16 +791,19 @@ return; } - else { + else + { var context = renderer.context; var transform = this.worldTransform; - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } @@ -748,11 +819,13 @@ CanvasGraphics.renderGraphics(this, context); - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } } @@ -763,13 +836,16 @@ * * @return {Rectangle} the rectangular bounding area */ -Graphics.prototype.getBounds = function (matrix) { +Graphics.prototype.getBounds = function (matrix) +{ // return an empty object if the item is a mask! - if (this.isMask) { + if (this.isMask) + { return math.Rectangle.EMPTY; } - if (this.dirty) { + if (this.dirty) + { this.updateLocalBounds(); this.glDirty = true; @@ -841,23 +917,27 @@ * Update the bounds of the object * */ -Graphics.prototype.updateLocalBounds = function () { +Graphics.prototype.updateLocalBounds = function () +{ var minX = Infinity; var maxX = -Infinity; var minY = Infinity; var maxY = -Infinity; - if (this.graphicsData.length) { + if (this.graphicsData.length) + { var shape, points, x, y, w, h; - for (var i = 0; i < this.graphicsData.length; i++) { + for (var i = 0; i < this.graphicsData.length; i++) + { var data = this.graphicsData[i]; var type = data.type; var lineWidth = data.lineWidth; shape = data.shape; - if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) { + if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) + { x = shape.x - lineWidth/2; y = shape.y - lineWidth/2; w = shape.width + lineWidth; @@ -869,7 +949,8 @@ minY = y < minY ? y : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.CIRC) { + else if (type === CONST.SHAPES.CIRC) + { x = shape.x; y = shape.y; w = shape.radius + lineWidth/2; @@ -881,7 +962,8 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.ELIP) { + else if (type === CONST.SHAPES.ELIP) + { x = shape.x; y = shape.y; w = shape.width + lineWidth/2; @@ -893,11 +975,13 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else { + else + { // POLY points = shape.points; - for (var j = 0; j < points.length; j += 2) { + for (var j = 0; j < points.length; j += 2) + { x = points[j]; y = points[j+1]; @@ -910,7 +994,8 @@ } } } - else { + else + { minX = 0; maxX = 0; minY = 0; @@ -931,10 +1016,12 @@ * * @private */ -Graphics.prototype._generateCachedSprite = function () { +Graphics.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { var canvasBuffer = new CanvasBuffer(bounds.width, bounds.height); var texture = Texture.fromCanvas(canvasBuffer.canvas); @@ -943,7 +1030,8 @@ this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.buffer.resize(bounds.width, bounds.height); } @@ -968,7 +1056,8 @@ * * @private */ -Graphics.prototype.updateCachedSpriteTexture = function () { +Graphics.prototype.updateCachedSpriteTexture = function () +{ var cachedSprite = this._cachedSprite; var texture = cachedSprite.texture; var canvas = cachedSprite.buffer.canvas; @@ -989,7 +1078,8 @@ * Destroys a previous cached sprite. * */ -Graphics.prototype.destroyCachedSprite = function () { +Graphics.prototype.destroyCachedSprite = function () +{ this._cachedSprite.texture.destroy(true); // let the gc collect the unused sprite @@ -1003,10 +1093,13 @@ * @param {Circle|Rectangle|Ellipse|Line|Polygon} shape The Shape object to draw. * @return {GraphicsData} The generated GraphicsData object. */ -Graphics.prototype.drawShape = function (shape) { - if (this.currentPath) { +Graphics.prototype.drawShape = function (shape) +{ + if (this.currentPath) + { // check current path! - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath.shape.points.length <= 2) + { this.graphicsData.pop(); } } @@ -1017,7 +1110,8 @@ this.graphicsData.push(data); - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { data.shape.closed = this.filling; this.currentPath = data; } diff --git a/src/core/primitives/GraphicsData.js b/src/core/primitives/GraphicsData.js index 99decbe..788f6f2 100644 --- a/src/core/primitives/GraphicsData.js +++ b/src/core/primitives/GraphicsData.js @@ -4,7 +4,8 @@ * @class * @namespace PIXI */ -function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) { +function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) +{ this.lineWidth = lineWidth; this.lineColor = lineColor; this.lineAlpha = lineAlpha; @@ -27,7 +28,8 @@ * * @return {GraphicsData} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ return new GraphicsData( this.lineWidth, this.lineColor, diff --git a/src/core/renderers/canvas/CanvasRenderer.js b/src/core/renderers/canvas/CanvasRenderer.js index 15a0978..7aebd44 100644 --- a/src/core/renderers/canvas/CanvasRenderer.js +++ b/src/core/renderers/canvas/CanvasRenderer.js @@ -17,17 +17,22 @@ * @param [options.resolution=1] {number} the resolution of the renderer retina would be 2 * @param [options.clearBeforeRender=true] {boolean} This sets if the CanvasRenderer will clear the canvas or not before the new render pass. */ -function CanvasRenderer(width, height, options) { +function CanvasRenderer(width, height, options) +{ utils.sayHello('Canvas'); - if (options) { - for (var i in CONST.defaultRenderOptions) { - if (typeof options[i] === 'undefined') { + if (options) + { + for (var i in CONST.defaultRenderOptions) + { + if (typeof options[i] === 'undefined') + { options[i] = CONST.defaultRenderOptions[i]; } } } - else { + else + { options = CONST.defaultRenderOptions; } @@ -156,19 +161,24 @@ this.smoothProperty = null; - if (this.context.imageSmoothingEnabled) { + if (this.context.imageSmoothingEnabled) + { this.smoothProperty = 'imageSmoothingEnabled'; } - else if (this.context.webkitImageSmoothingEnabled) { + else if (this.context.webkitImageSmoothingEnabled) + { this.smoothProperty = 'webkitImageSmoothingEnabled'; } - else if (this.context.mozImageSmoothingEnabled) { + else if (this.context.mozImageSmoothingEnabled) + { this.smoothProperty = 'mozImageSmoothingEnabled'; } - else if (this.context.oImageSmoothingEnabled) { + else if (this.context.oImageSmoothingEnabled) + { this.smoothProperty = 'oImageSmoothingEnabled'; } - else if (this.context.msImageSmoothingEnabled) { + else if (this.context.msImageSmoothingEnabled) + { this.smoothProperty = 'msImageSmoothingEnabled'; } @@ -193,10 +203,12 @@ * @memberof CanvasRenderer# */ backgroundColor: { - get: function () { + get: function () + { return this._backgroundColor; }, - set: function (val) { + set: function (val) + { this._backgroundColor = val; this._backgroundColorString = utils.hex2string(val); } @@ -208,7 +220,8 @@ * * @param object {DisplayObject} the object to be rendered */ -CanvasRenderer.prototype.render = function (object) { +CanvasRenderer.prototype.render = function (object) +{ object.updateTransform(); this.context.setTransform(1,0,0,1,0,0); @@ -218,16 +231,20 @@ this.currentBlendMode = CONST.blendModes.NORMAL; this.context.globalCompositeOperation = this.blendModes[CONST.blendModes.NORMAL]; - if (navigator.isCocoonJS && this.view.screencanvas) { + if (navigator.isCocoonJS && this.view.screencanvas) + { this.context.fillStyle = 'black'; this.context.clear(); } - if (this.clearBeforeRender) { - if (this.transparent) { + if (this.clearBeforeRender) + { + if (this.transparent) + { this.context.clearRect(0, 0, this.width, this.height); } - else { + else + { this.context.fillStyle = this._backgroundColorString; this.context.fillRect(0, 0, this.width , this.height); } @@ -241,8 +258,10 @@ * * @param [removeView=false] {boolean} Removes the Canvas element from the DOM. */ -CanvasRenderer.prototype.destroy = function (removeView) { - if (removeView && this.view.parent) { +CanvasRenderer.prototype.destroy = function (removeView) +{ + if (removeView && this.view.parent) + { this.view.parent.removeChild(this.view); } @@ -257,14 +276,16 @@ * @param width {number} the new width of the canvas view * @param height {number} the new height of the canvas view */ -CanvasRenderer.prototype.resize = function (width, height) { +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) { + if (this.autoResize) + { this.view.style.width = this.width / this.resolution + 'px'; this.view.style.height = this.height / this.resolution + 'px'; } @@ -276,7 +297,8 @@ * @param displayObject {DisplayObject} The displayObject to render * @private */ -CanvasRenderer.prototype.renderDisplayObject = function (displayObject) { +CanvasRenderer.prototype.renderDisplayObject = function (displayObject) +{ displayObject.renderCanvas(this); }; @@ -285,11 +307,14 @@ * * @private */ -CanvasRenderer.prototype._mapBlendModes = function () { - if (!this.blendModes) { +CanvasRenderer.prototype._mapBlendModes = function () +{ + if (!this.blendModes) + { this.blendModes = {}; - if (utils.canUseNewCanvasBlendModes()) { + if (utils.canUseNewCanvasBlendModes()) + { this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? this.blendModes[CONST.blendModes.MULTIPLY] = 'multiply'; @@ -308,7 +333,8 @@ this.blendModes[CONST.blendModes.COLOR] = 'color'; this.blendModes[CONST.blendModes.LUMINOSITY] = 'luminosity'; } - else { + else + { // this means that the browser does not support the cool new blend modes in canvas 'cough' ie 'cough' this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? diff --git a/src/core/renderers/canvas/utils/CanvasBuffer.js b/src/core/renderers/canvas/utils/CanvasBuffer.js index ebe5d47..b183a66 100644 --- a/src/core/renderers/canvas/utils/CanvasBuffer.js +++ b/src/core/renderers/canvas/utils/CanvasBuffer.js @@ -6,7 +6,8 @@ * @param width {number} the width for the newly created canvas * @param height {number} the height for the newly created canvas */ -function CanvasBuffer(width, height) { +function CanvasBuffer(width, height) +{ /** * The Canvas object that belongs to this CanvasBuffer. * @@ -36,10 +37,12 @@ * @memberof CanvasBuffer# */ width: { - get: function () { + get: function () + { return this.canvas.width; }, - set: function (val) { + set: function (val) + { this.canvas.width = val; } }, @@ -50,10 +53,12 @@ * @memberof CanvasBuffer# */ height: { - get: function () { + get: function () + { return this.canvas.height; }, - set: function (val) { + set: function (val) + { this.canvas.height = val; } } @@ -64,7 +69,8 @@ * * @private */ -CanvasBuffer.prototype.clear = function () { +CanvasBuffer.prototype.clear = function () +{ this.context.setTransform(1, 0, 0, 1, 0, 0); this.context.clearRect(0,0, this.canvas.width, this.canvas.height); }; @@ -75,7 +81,8 @@ * @param width {number} the new width of the canvas * @param height {number} the new height of the canvas */ -CanvasBuffer.prototype.resize = function (width, height) { +CanvasBuffer.prototype.resize = function (width, height) +{ this.canvas.width = width; this.canvas.height = height; }; diff --git a/src/core/renderers/canvas/utils/CanvasGraphics.js b/src/core/renderers/canvas/utils/CanvasGraphics.js index c7eaa2a..3f2a91f 100644 --- a/src/core/renderers/canvas/utils/CanvasGraphics.js +++ b/src/core/renderers/canvas/utils/CanvasGraphics.js @@ -13,15 +13,18 @@ * @param graphics {Graphics} the actual graphics object to render * @param context {CanvasRenderingContext2D} the 2d drawing method of the canvas */ -CanvasGraphics.renderGraphics = function (graphics, context) { +CanvasGraphics.renderGraphics = function (graphics, context) +{ var worldAlpha = graphics.worldAlpha; - if (graphics.dirty) { + if (graphics.dirty) + { this.updateGraphicsTint(graphics); graphics.dirty = false; } - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; @@ -30,69 +33,82 @@ context.lineWidth = data.lineWidth; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { context.beginPath(); var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } - if (shape.closed) { + if (shape.closed) + { context.lineTo(points[0], points[1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fillRect(shape.x, shape.y, shape.width, shape.height); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.strokeRect(shape.x, shape.y, shape.width, shape.height); } } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.beginPath(); context.arc(shape.x, shape.y, shape.radius,0,2*Math.PI); context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas var w = shape.width * 2; @@ -119,18 +135,21 @@ context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; var width = shape.width; @@ -152,13 +171,15 @@ context.quadraticCurveTo(rx, ry, rx, ry + radius); context.closePath(); - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); @@ -174,45 +195,54 @@ * @param graphics {Graphics} the graphics which will be used as a mask * @param context {CanvasRenderingContext2D} the context 2d method of the canvas */ -CanvasGraphics.renderGraphicsMask = function (graphics, context) { +CanvasGraphics.renderGraphicsMask = function (graphics, context) +{ var len = graphics.graphicsData.length; - if (len === 0) { + if (len === 0) + { return; } context.beginPath(); - for (var i = 0; i < len; i++) { + for (var i = 0; i < len; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { context.rect(shape.x, shape.y, shape.width, shape.height); context.closePath(); } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.arc(shape.x, shape.y, shape.radius, 0, 2 * Math.PI); context.closePath(); } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas @@ -237,7 +267,8 @@ context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); context.closePath(); } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; @@ -262,8 +293,10 @@ } }; -CanvasGraphics.updateGraphicsTint = function (graphics) { - if (graphics.tint === 0xFFFFFF) { +CanvasGraphics.updateGraphicsTint = function (graphics) +{ + if (graphics.tint === 0xFFFFFF) + { return; } @@ -271,7 +304,8 @@ var tintG = (graphics.tint >> 8 & 0xFF) / 255; var tintB = (graphics.tint & 0xFF)/ 255; - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var fillColor = data.fillColor | 0; diff --git a/src/core/renderers/canvas/utils/CanvasMaskManager.js b/src/core/renderers/canvas/utils/CanvasMaskManager.js index e04a733..9827d36 100644 --- a/src/core/renderers/canvas/utils/CanvasMaskManager.js +++ b/src/core/renderers/canvas/utils/CanvasMaskManager.js @@ -6,7 +6,8 @@ * @class * @namespace PIXI */ -function CanvasMaskManager() {} +function CanvasMaskManager() +{} CanvasMaskManager.prototype.constructor = CanvasMaskManager; module.exports = CanvasMaskManager; @@ -17,7 +18,8 @@ * @param maskData {object} the maskData that will be pushed * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.pushMask = function (maskData, renderer) { +CanvasMaskManager.prototype.pushMask = function (maskData, renderer) +{ renderer.context.save(); var cacheAlpha = maskData.alpha; @@ -45,6 +47,7 @@ * * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.popMask = function (renderer) { +CanvasMaskManager.prototype.popMask = function (renderer) +{ renderer.context.restore(); }; diff --git a/src/core/renderers/canvas/utils/CanvasTinter.js b/src/core/renderers/canvas/utils/CanvasTinter.js index 17e0529..d2fb1bc 100644 --- a/src/core/renderers/canvas/utils/CanvasTinter.js +++ b/src/core/renderers/canvas/utils/CanvasTinter.js @@ -14,7 +14,8 @@ * @param color {number} the color to use to tint the sprite with * @return {HTMLCanvasElement} The tinted canvas */ -CanvasTinter.getTintedTexture = function (sprite, color) { +CanvasTinter.getTintedTexture = function (sprite, color) +{ var texture = sprite.texture; color = CanvasTinter.roundColor(color); @@ -23,7 +24,8 @@ texture.tintCache = texture.tintCache || {}; - if (texture.tintCache[stringColor]) { + if (texture.tintCache[stringColor]) + { return texture.tintCache[stringColor]; } @@ -33,14 +35,16 @@ //CanvasTinter.tintWithPerPixel(texture, stringColor, canvas); CanvasTinter.tintMethod(texture, color, canvas); - if (CanvasTinter.convertTintToImage) { + if (CanvasTinter.convertTintToImage) + { // is this better? var tintImage = new Image(); tintImage.src = canvas.toDataURL(); texture.tintCache[stringColor] = tintImage; } - else { + else + { texture.tintCache[stringColor] = canvas; // if we are not converting the texture to an image then we need to lose the reference to the canvas CanvasTinter.canvas = null; @@ -56,7 +60,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithMultiply = function (texture, color, canvas) { +CanvasTinter.tintWithMultiply = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -104,7 +109,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithOverlay = function (texture, color, canvas) { +CanvasTinter.tintWithOverlay = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -139,7 +145,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithPerPixel = function (texture, color, canvas) { +CanvasTinter.tintWithPerPixel = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -167,7 +174,8 @@ var pixels = pixelData.data; - for (var i = 0; i < pixels.length; i += 4) { + for (var i = 0; i < pixels.length; i += 4) + { pixels[i+0] *= r; pixels[i+1] *= g; pixels[i+2] *= b; @@ -181,7 +189,8 @@ * * @param color {number} the color to round, should be a hex color */ -CanvasTinter.roundColor = function (color) { +CanvasTinter.roundColor = function (color) +{ var step = CanvasTinter.cacheStepsPerColorChannel; var rgbValues = utils.hex2rgb(color); diff --git a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js index 9f2f89a..35edbaf 100644 --- a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js +++ b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLBlendModeManager(renderer) { +function WebGLBlendModeManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -23,8 +24,10 @@ * * @param blendMode {number} the blendMode, should be a Pixi const, such as BlendModes.ADD */ -WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) { - if (this.currentBlendMode === blendMode) { +WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) +{ + if (this.currentBlendMode === blendMode) + { return false; } diff --git a/src/core/renderers/webgl/managers/WebGLFilterManager.js b/src/core/renderers/webgl/managers/WebGLFilterManager.js index 1179258..2dac048 100644 --- a/src/core/renderers/webgl/managers/WebGLFilterManager.js +++ b/src/core/renderers/webgl/managers/WebGLFilterManager.js @@ -7,7 +7,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLFilterManager(renderer) { +function WebGLFilterManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -32,7 +33,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.texturePool.length = 0; self.initShaderBuffers(); }); @@ -46,7 +48,8 @@ * @param renderer {WebGLRenderer} * @param buffer {ArrayBuffer} */ -WebGLFilterManager.prototype.begin = function (buffer) { +WebGLFilterManager.prototype.begin = function (buffer) +{ this.defaultShader = this.renderer.shaderManager.defaultShader; this.width = this.renderer.projection.x * 2; @@ -60,7 +63,8 @@ * * @param filterBlock {object} the filter that will be pushed to the current filter stack */ -WebGLFilterManager.prototype.pushFilter = function (filterBlock) { +WebGLFilterManager.prototype.pushFilter = function (filterBlock) +{ var gl = this.renderer.gl; var projection = this.renderer.projection; @@ -78,10 +82,12 @@ this.offsetY += filterBlock._filterArea.y; var texture = this.texturePool.pop(); - if (!texture) { + if (!texture) + { texture = new FilterTexture(this.renderer.gl, this.width, this.height); } - else { + else + { texture.resize(this.width, this.height); } @@ -98,29 +104,35 @@ var localX = filterArea.x, localY = filterArea.y; - if (filterArea.x < 0) { + if (filterArea.x < 0) + { filterArea.width += filterArea.x; filterArea.x = 0; } - if (filterArea.y < 0) { + if (filterArea.y < 0) + { filterArea.height += filterArea.y; filterArea.y = 0; } - if (localX + filterArea.width > this.width) { + if (localX + filterArea.width > this.width) + { filterArea.width = this.width - localX; } - if (localY + filterArea.height > this.height) { + if (localY + filterArea.height > this.height) + { filterArea.height = this.height - localY; } - if (filterArea.width < 0) { + if (filterArea.width < 0) + { filterArea.width = 0; } - if (filterArea.height < 0) { + if (filterArea.height < 0) + { filterArea.height = 0; } @@ -154,7 +166,8 @@ * Removes the last filter from the filter stack and doesn't return it. * */ -WebGLFilterManager.prototype.popFilter = function () { +WebGLFilterManager.prototype.popFilter = function () +{ var gl = this.renderer.gl; var filterBlock = this.filterStack.pop(); @@ -163,7 +176,8 @@ var projection = this.renderer.projection; var offset = this.renderer.offset; - if (filterBlock.filterPasses.length > 1) { + if (filterBlock.filterPasses.length > 1) + { gl.viewport(0, 0, filterArea.width, filterArea.height); gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); @@ -193,7 +207,8 @@ var inputTexture = texture; var outputTexture = this.texturePool.pop(); - if (!outputTexture) { + if (!outputTexture) + { outputTexture = new FilterTexture(this.renderer.gl, this.width, this.height); } outputTexture.resize(this.width, this.height); @@ -204,7 +219,8 @@ gl.disable(gl.BLEND); - for (var i = 0; i < filterBlock.filterPasses.length-1; i++) { + for (var i = 0; i < filterBlock.filterPasses.length-1; i++) + { var filterPass = filterBlock.filterPasses[i]; gl.bindFramebuffer(gl.FRAMEBUFFER, outputTexture.frameBuffer ); @@ -243,10 +259,12 @@ var buffer = this.buffer; // time to render the filters texture to the previous scene - if (this.filterStack.length === 0) { + if (this.filterStack.length === 0) + { gl.colorMask(true, true, true, true);//this.transparent); } - else { + else + { var currentFilter = this.filterStack[this.filterStack.length-1]; filterArea = currentFilter._filterArea; @@ -332,13 +350,15 @@ * @param width {number} the horizontal range of the filter * @param height {number} the vertical range of the filter */ -WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) { +WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) +{ // use program var gl = this.renderer.gl; var shader = filter.shaders[gl.id]; - if (!shader) { + if (!shader) + { shader = new Shader(gl); shader.fragmentSrc = filter.fragmentSrc; @@ -356,7 +376,8 @@ gl.uniform2f(shader.projectionVector, width/2, -height/2); gl.uniform2f(shader.offsetVector, 0,0); - if (filter.uniforms.dimensions) { + 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]; @@ -386,7 +407,8 @@ * Initialises the shader buffers. * */ -WebGLFilterManager.prototype.initShaderBuffers = function () { +WebGLFilterManager.prototype.initShaderBuffers = function () +{ var gl = this.renderer.gl; // create some buffers @@ -432,7 +454,8 @@ * Destroys the filter and removes it from the filter stack. * */ -WebGLFilterManager.prototype.destroy = function () { +WebGLFilterManager.prototype.destroy = function () +{ var gl = this.renderer.gl; this.filterStack = null; @@ -441,7 +464,8 @@ this.offsetY = 0; // destroy textures - for (var i = 0; i < this.texturePool.length; i++) { + for (var i = 0; i < this.texturePool.length; i++) + { this.texturePool[i].destroy(); } diff --git a/src/core/renderers/webgl/managers/WebGLManager.js b/src/core/renderers/webgl/managers/WebGLManager.js index 9d47b5c..c30cd51 100644 --- a/src/core/renderers/webgl/managers/WebGLManager.js +++ b/src/core/renderers/webgl/managers/WebGLManager.js @@ -3,7 +3,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLManager(renderer) { +function WebGLManager(renderer) +{ /** * The renderer this manager works for. * @@ -15,6 +16,7 @@ WebGLManager.prototype.constructor = WebGLManager; module.exports = WebGLManager; -WebGLManager.prototype.destroy = function () { +WebGLManager.prototype.destroy = function () +{ this.renderer = null; }; diff --git a/src/core/renderers/webgl/managers/WebGLMaskManager.js b/src/core/renderers/webgl/managers/WebGLMaskManager.js index 2f90b64..e568812 100644 --- a/src/core/renderers/webgl/managers/WebGLMaskManager.js +++ b/src/core/renderers/webgl/managers/WebGLMaskManager.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLMaskManager(renderer) { +function WebGLMaskManager(renderer) +{ WebGLManager.call(this, renderer); } @@ -19,12 +20,15 @@ * * @param maskData {any[]} */ -WebGLMaskManager.prototype.pushMask = function (maskData) { - if (maskData.dirty) { +WebGLMaskManager.prototype.pushMask = function (maskData) +{ + if (maskData.dirty) + { WebGLGraphics.updateGraphics(maskData, this.renderer.gl); } - if (!maskData._webGL[this.renderer.gl.id].data.length) { + if (!maskData._webGL[this.renderer.gl.id].data.length) + { return; } @@ -36,6 +40,7 @@ * * @param maskData {any[]} */ -WebGLMaskManager.prototype.popMask = function (maskData) { +WebGLMaskManager.prototype.popMask = function (maskData) +{ this.renderer.stencilManager.popStencil(maskData, maskData._webGL[this.renderer.gl.id].data[0], this.renderer); }; diff --git a/src/core/renderers/webgl/managers/WebGLShaderManager.js b/src/core/renderers/webgl/managers/WebGLShaderManager.js index fef071c..90c6477 100644 --- a/src/core/renderers/webgl/managers/WebGLShaderManager.js +++ b/src/core/renderers/webgl/managers/WebGLShaderManager.js @@ -10,7 +10,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLShaderManager(renderer) { +function WebGLShaderManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -28,7 +29,8 @@ */ this.tempAttribState = []; - for (var i = 0; i < this.maxAttibs; i++) { + for (var i = 0; i < this.maxAttibs; i++) + { this.attribState[i] = false; } @@ -66,7 +68,8 @@ // listen for context and update necessary shaders var self = this; - this.renderer.on('context', function (event) { + this.renderer.on('context', function (event) + { var gl = event.data; // this shader is used for rendering primitives @@ -97,29 +100,36 @@ * * @param attribs {Array} attribs */ -WebGLShaderManager.prototype.setAttribs = function (attribs) { +WebGLShaderManager.prototype.setAttribs = function (attribs) +{ // reset temp state var i; - for (i = 0; i < this.tempAttribState.length; i++) { + for (i = 0; i < this.tempAttribState.length; i++) + { this.tempAttribState[i] = false; } // set the new attribs - for (var a in attribs) { + for (var a in attribs) + { this.tempAttribState[attribs[a]] = true; } var gl = this.renderer.gl; - for (i = 0; i < this.attribState.length; i++) { - if (this.attribState[i] !== this.tempAttribState[i]) { + for (i = 0; i < this.attribState.length; i++) + { + if (this.attribState[i] !== this.tempAttribState[i]) + { this.attribState[i] = this.tempAttribState[i]; - if (this.attribState[i]) { + if (this.attribState[i]) + { gl.enableVertexAttribArray(i); } - else { + else + { gl.disableVertexAttribArray(i); } } @@ -131,8 +141,10 @@ * * @param shader {Any} */ -WebGLShaderManager.prototype.setShader = function (shader) { - if (this._currentId === shader.uuid) { +WebGLShaderManager.prototype.setShader = function (shader) +{ + if (this._currentId === shader.uuid) + { return false; } @@ -150,7 +162,8 @@ * Destroys this object. * */ -WebGLShaderManager.prototype.destroy = function () { +WebGLShaderManager.prototype.destroy = function () +{ this.attribState = null; this.tempAttribState = null; diff --git a/src/core/renderers/webgl/managers/WebGLStencilManager.js b/src/core/renderers/webgl/managers/WebGLStencilManager.js index 9ec6398..4cb0134 100644 --- a/src/core/renderers/webgl/managers/WebGLStencilManager.js +++ b/src/core/renderers/webgl/managers/WebGLStencilManager.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLStencilManager(renderer) { +function WebGLStencilManager(renderer) +{ WebGLManager.call(this, renderer); this.stencilStack = []; @@ -24,12 +25,14 @@ * @param graphics {Graphics} * @param webGLData {any[]} */ -WebGLStencilManager.prototype.pushStencil = function (graphics, webGLData) { +WebGLStencilManager.prototype.pushStencil = function (graphics, webGLData) +{ var gl = this.renderer.gl; this.bindGraphics(graphics, webGLData, this.renderer); - if (this.stencilStack.length === 0) { + if (this.stencilStack.length === 0) + { gl.enable(gl.STENCIL_TEST); gl.clear(gl.STENCIL_BUFFER_BIT); this.reverse = true; @@ -47,14 +50,17 @@ // draw the triangle strip! - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } @@ -62,31 +68,38 @@ // draw a quad to increment.. gl.drawElements(gl.TRIANGLE_FAN, 4, gl.UNSIGNED_SHORT, ( webGLData.indices.length - 4 ) * 2 ); - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); } this.reverse = !this.reverse; } - else { - if (!this.reverse) { + else + { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } - else { + 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) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); } } @@ -103,7 +116,8 @@ * @param graphics {Graphics} * @param webGLData {Array} */ -WebGLStencilManager.prototype.bindGraphics = function (graphics, webGLData) { +WebGLStencilManager.prototype.bindGraphics = function (graphics, webGLData) +{ //if (this._currentGraphics === graphics)return; this._currentGraphics = graphics; @@ -114,7 +128,8 @@ offset = this.renderer.offset, shader;// = this.renderer.shaderManager.primitiveShader; - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { shader = this.renderer.shaderManager.complexPrimitiveShader; this.renderer.shaderManager.setShader(shader); @@ -141,7 +156,8 @@ // set the index buffer! gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, webGLData.indexBuffer); } - else { + else + { //this.renderer.shaderManager.activatePrimitiveShader(); shader = this.renderer.shaderManager.primitiveShader; this.renderer.shaderManager.setShader( shader ); @@ -154,7 +170,7 @@ gl.uniform2f(shader.uniforms.offsetVector._location, -offset.x, -offset.y); gl.uniform3fv(shader.uniforms.tint._location, utils.hex2rgb(graphics.tint)); - + gl.uniform1f(shader.uniforms.alpha._location, graphics.worldAlpha); @@ -172,19 +188,22 @@ * @param graphics {Graphics} * @param webGLData {Array} */ -WebGLStencilManager.prototype.popStencil = function (graphics, webGLData) { +WebGLStencilManager.prototype.popStencil = function (graphics, webGLData) +{ var gl = this.renderer.gl; this.stencilStack.pop(); this.count--; - if (this.stencilStack.length === 0) { + if (this.stencilStack.length === 0) + { // the stack is empty! gl.disable(gl.STENCIL_TEST); } - else { + else + { var level = this.count; @@ -192,14 +211,17 @@ gl.colorMask(false, false, false, false); - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { this.reverse = !this.reverse; - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } @@ -213,31 +235,38 @@ // draw the triangle strip! gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); - if (!this.reverse) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); } } - else { + else + { // console.log("<<>>") - if (!this.reverse) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } - else { + 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) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); } } @@ -253,7 +282,8 @@ * Destroys the mask stack. * */ -WebGLStencilManager.prototype.destroy = function () { +WebGLStencilManager.prototype.destroy = function () +{ this.renderer = null; this.stencilStack = null; }; diff --git a/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js b/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js index 913ba5e..1ea7d19 100644 --- a/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js +++ b/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function ComplexPrimitiveShader(gl) { +function ComplexPrimitiveShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -24,7 +25,8 @@ 'uniform float flipY;', 'varying vec4 vColor;', - 'void main(void) {', + '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);', @@ -37,7 +39,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = vColor;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/FastShader.js b/src/core/renderers/webgl/shaders/FastShader.js index bd2e29a..2e5e060 100644 --- a/src/core/renderers/webgl/shaders/FastShader.js +++ b/src/core/renderers/webgl/shaders/FastShader.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function FastShader(gl) { +function FastShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -28,7 +29,8 @@ 'const vec2 center = vec2(-1.0, 1.0);', - 'void main(void) {', + 'void main(void) + {', ' vec2 v;', ' vec2 sv = aVertexPosition * aScale;', ' v.x = (sv.x) * cos(aRotation) - (sv.y) * sin(aRotation);', @@ -49,7 +51,8 @@ 'uniform sampler2D uSampler;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/PrimitiveShader.js b/src/core/renderers/webgl/shaders/PrimitiveShader.js index 6f25409..a25f54f 100644 --- a/src/core/renderers/webgl/shaders/PrimitiveShader.js +++ b/src/core/renderers/webgl/shaders/PrimitiveShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function PrimitiveShader(gl) { +function PrimitiveShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -23,7 +24,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + '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);', @@ -36,7 +38,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = vColor;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/Shader.js b/src/core/renderers/webgl/shaders/Shader.js index f8964f5..fd75ef5 100644 --- a/src/core/renderers/webgl/shaders/Shader.js +++ b/src/core/renderers/webgl/shaders/Shader.js @@ -6,7 +6,8 @@ * @param [fragmentSrc] {string} The source of the fragment shader. * @param [vertexSrc] {string} The source of the vertex shader. */ -function Shader(gl, vertexSrc, fragmentSrc, customUniforms, customAttributes) { +function Shader(gl, vertexSrc, fragmentSrc, customUniforms, customAttributes) +{ /** * @member {number} * @readonly @@ -33,7 +34,8 @@ dimensions: { type: '4f', value: new Float32Array(4) } }; - for (var u in customUniforms) { + for (var u in customUniforms) + { this.uniforms[u] = customUniforms[u]; } @@ -43,7 +45,8 @@ aColor: 0 }; - for (var a in customAttributes) { + for (var a in customAttributes) + { this.attributes[a] = customAttributes[a]; } @@ -66,7 +69,8 @@ 'const vec2 center = vec2(-1.0, 1.0);', - 'void main(void) {', + 'void main(void) + {', ' gl_Position = vec4( ((aVertexPosition + offsetVector) / projectionVector) + center , 0.0, 1.0);', ' vTextureCoord = aTextureCoord;', ' vColor = vec4(aColor.rgb * aColor.a, aColor.a);', @@ -85,7 +89,8 @@ 'uniform sampler2D uSampler;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;', '}' ].join('\n'); @@ -96,7 +101,8 @@ Shader.prototype.constructor = Shader; module.exports = Shader; -Shader.prototype.init = function () { +Shader.prototype.init = function () +{ this.compile(); this.gl.useProgram(this.program); @@ -105,14 +111,18 @@ this.cacheAttributeLocations(Object.keys(this.attributes)); }; -Shader.prototype.cacheUniformLocations = function (keys) { - for (var i = 0; i < keys.length; ++i) { +Shader.prototype.cacheUniformLocations = function (keys) +{ + for (var i = 0; i < keys.length; ++i) + { this.uniforms[keys[i]]._location = this.gl.getUniformLocation(this.program, keys[i]); } }; -Shader.prototype.cacheAttributeLocations = function (keys) { - for (var i = 0; i < keys.length; ++i) { +Shader.prototype.cacheAttributeLocations = function (keys) +{ + for (var i = 0; i < keys.length; ++i) + { this.attributes[keys[i]] = this.gl.getAttribLocation(this.program, keys[i]); } @@ -124,14 +134,16 @@ // 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.attributes.aColor === -1) { + // if (this.attributes.aColor === -1) + { // this.attributes.aColor = 2; // } // End worst hack eva // }; -Shader.prototype.compile = function () { +Shader.prototype.compile = function () +{ var gl = this.gl; var glVertShader = this._glCompile(gl.VERTEX_SHADER, this.vertexSrc); @@ -144,13 +156,15 @@ gl.linkProgram(program); // if linking fails, then log and cleanup - if (!gl.getProgramParameter(program, gl.LINK_STATUS)) { + if (!gl.getProgramParameter(program, gl.LINK_STATUS)) + { window.console.error('Pixi.js Error: Could not initialize shader.'); window.console.error('gl.VALIDATE_STATUS', gl.getProgramParameter(program, gl.VALIDATE_STATUS)); window.console.error('gl.getError()', gl.getError()); // if there is a program info log, log it - if (gl.getProgramInfoLog(program) !== '') { + if (gl.getProgramInfoLog(program) !== '') + { window.console.warn('Pixi.js Warning: gl.getProgramInfoLog()', gl.getProgramInfoLog(program)); } @@ -165,18 +179,21 @@ return (this.program = program); }; -Shader.prototype.syncUniforms = function () { +Shader.prototype.syncUniforms = function () +{ var gl = this.gl; this.textureCount = 1; - for (var key in this.uniforms) { + for (var key in this.uniforms) + { var uniform = this.uniforms[key], location = uniform._location, value = uniform.value, i, il; - switch (uniform.type) { + switch (uniform.type) + { // single int value case 'i': case '1i': @@ -282,7 +299,8 @@ // a Color Value case 'c': - if (typeof value === 'number') { + if (typeof value === 'number') + { value = utils.hex2rgb(value); } @@ -311,11 +329,13 @@ // array of 2D Point objects case 'v2v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(2 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 2] = value[i].x; uniform._array[i * 2 + 1] = value[i].y; } @@ -325,11 +345,13 @@ // array of 3D Point objects case 'v3v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(3 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 3] = value[i].x; uniform._array[i * 3 + 1] = value[i].y; uniform._array[i * 3 + 2] = value[i].z; @@ -341,11 +363,13 @@ // array of 4D Point objects case 'v4v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(4 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 4] = value[i].x; uniform._array[i * 4 + 1] = value[i].y; uniform._array[i * 4 + 2] = value[i].z; @@ -359,7 +383,8 @@ // PIXI.Texture case 't': case 'sampler2D': - if (!uniform.value || !uniform.value.baseTexture || !uniform.value.baseTexture.hasLoaded) { + if (!uniform.value || !uniform.value.baseTexture || !uniform.value.baseTexture.hasLoaded) + { break; } @@ -376,7 +401,8 @@ this.textureCount++; // initialize the texture if we haven't yet - if (!uniform._init) { + if (!uniform._init) + { this.initSampler2D(uniform); uniform._init = true; @@ -394,11 +420,13 @@ * Initialises a Sampler2D uniform (which may only be available later on after initUniforms once the texture has loaded) * */ -Shader.prototype.initSampler2D = function (uniform) { +Shader.prototype.initSampler2D = function (uniform) +{ var gl = this.gl; // Extended texture data - if (uniform.textureData) { + if (uniform.textureData) + { var data = uniform.textureData; // GLTexture = mag linear, min linear_mipmap_linear, wrap repeat + gl.generateMipmap(gl.TEXTURE_2D); @@ -417,14 +445,16 @@ var wrapT = (data.wrapT) ? data.wrapT : gl.CLAMP_TO_EDGE; var format = (data.luminance) ? gl.LUMINANCE : gl.RGBA; - if (data.repeat) { + if (data.repeat) + { wrapS = gl.REPEAT; wrapT = gl.REPEAT; } gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, !!data.flipY); - if (data.width) { + if (data.width) + { var width = (data.width) ? data.width : 512; var height = (data.height) ? data.height : 2; var border = (data.border) ? data.border : 0; @@ -432,7 +462,8 @@ // 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 { + 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); } @@ -448,7 +479,8 @@ * Destroys the shader. * */ -Shader.prototype.destroy = function () { +Shader.prototype.destroy = function () +{ this.gl.deleteProgram(this.program); this.gl = null; @@ -459,13 +491,15 @@ this.fragmentSrc = null; }; -Shader.prototype._glCompile = function (type, src) { +Shader.prototype._glCompile = function (type, src) +{ var shader = this.gl.createShader(type); this.gl.shaderSource(shader, src); this.gl.compileShader(shader); - if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) { + if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) + { window.console.log(this.gl.getShaderInfoLog(shader)); return null; } diff --git a/src/core/renderers/webgl/shaders/StripShader.js b/src/core/renderers/webgl/shaders/StripShader.js index 193f6e1..a7abcc6 100644 --- a/src/core/renderers/webgl/shaders/StripShader.js +++ b/src/core/renderers/webgl/shaders/StripShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function StripShader(gl) { +function StripShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -20,7 +21,8 @@ 'varying vec2 vTextureCoord;', - 'void main(void) {', + '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);', @@ -36,7 +38,8 @@ 'varying vec2 vTextureCoord;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vec2(vTextureCoord.x, vTextureCoord.y)) * alpha;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/utils/FilterTexture.js b/src/core/renderers/webgl/utils/FilterTexture.js index d2c8423..4433d44 100644 --- a/src/core/renderers/webgl/utils/FilterTexture.js +++ b/src/core/renderers/webgl/utils/FilterTexture.js @@ -8,7 +8,8 @@ * @param height {number} the vertical range of the filter * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values */ -function FilterTexture(gl, width, height, scaleMode) { +function FilterTexture(gl, width, height, scaleMode) +{ /** * @member {WebGLContext} */ @@ -59,7 +60,8 @@ * Clears the filter texture. * */ -FilterTexture.prototype.clear = function () { +FilterTexture.prototype.clear = function () +{ var gl = this.gl; gl.clearColor(0,0,0, 0); @@ -72,8 +74,10 @@ * @param width {number} the new width of the texture * @param height {number} the new height of the texture */ -FilterTexture.prototype.resize = function (width, height) { - if (this.width === width && this.height === height) { +FilterTexture.prototype.resize = function (width, height) +{ + if (this.width === width && this.height === height) + { return; } @@ -96,7 +100,8 @@ * Destroys the filter texture. * */ -FilterTexture.prototype.destroy = function () { +FilterTexture.prototype.destroy = function () +{ var gl = this.gl; gl.deleteFramebuffer( this.frameBuffer ); gl.deleteTexture( this.texture ); diff --git a/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js b/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js index c4721e9..a63f4d7 100644 --- a/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js +++ b/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js @@ -14,7 +14,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this sprite batch works for. */ -function WebGLFastSpriteBatch(renderer) { +function WebGLFastSpriteBatch(renderer) +{ /** * The renderer instance this sprite batch operates on. * @@ -91,7 +92,8 @@ */ this.lastIndexCount = 0; - for (var i=0, j=0; i < numIndices; i += 6, j += 4) { + 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; @@ -144,7 +146,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.setupContext(); }); } @@ -157,7 +160,8 @@ * * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLFastSpriteBatch.prototype.setupContext = function () { +WebGLFastSpriteBatch.prototype.setupContext = function () +{ var gl = this.renderer.gl; // create a couple of buffers @@ -177,7 +181,8 @@ /** * @param spriteBatch {SpriteBatch} The SpriteBatch container to prepare for. */ -WebGLFastSpriteBatch.prototype.begin = function (spriteBatch) { +WebGLFastSpriteBatch.prototype.begin = function (spriteBatch) +{ this.shader = this.renderer.shaderManager.fastShader; this.matrix = spriteBatch.worldTransform.toArray(true); @@ -187,33 +192,38 @@ /** */ -WebGLFastSpriteBatch.prototype.end = function () { +WebGLFastSpriteBatch.prototype.end = function () +{ this.flush(); }; /** * @param spriteBatch {SpriteBatch} The SpriteBatch container to render. */ -WebGLFastSpriteBatch.prototype.render = function (spriteBatch) { +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) { + if (!sprite.texture._uvs) + { return; } this.currentBaseTexture = sprite.texture.baseTexture; // check blend mode - if (sprite.blendMode !== this.renderer.blendModeManager.currentBlendMode) { + if (sprite.blendMode !== this.renderer.blendModeManager.currentBlendMode) + { this.flush(); this.renderer.blendModeManager.setBlendMode(sprite.blendMode); } - for (var i=0,j= children.length; i= this.size) { + if (this.currentBatchSize >= this.size) + { this.flush(); } }; @@ -362,29 +379,35 @@ /** * */ -WebGLFastSpriteBatch.prototype.flush = function () { +WebGLFastSpriteBatch.prototype.flush = function () +{ // If the batch is length 0 then return as there is nothing to draw - if (this.currentBatchSize === 0) { + if (this.currentBatchSize === 0) + { return; } var gl = this.renderer.gl; // bind the current texture - if (!this.currentBaseTexture._glTextures[gl.id]) { + if (!this.currentBaseTexture._glTextures[gl.id]) + { this.renderer.updateTexture(this.currentBaseTexture, gl); } //TODO-SHOUD THIS BE ELSE??!?!?! - else { + else + { gl.bindTexture(gl.TEXTURE_2D, this.currentBaseTexture._glTextures[gl.id]); } // upload the verts to the buffer - if (this.currentBatchSize > ( this.size * 0.5 ) ) { + if (this.currentBatchSize > ( this.size * 0.5 ) ) + { gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); } - else { + else + { var view = this.vertices.subarray(0, this.currentBatchSize * this.vertByteSize); gl.bufferSubData(gl.ARRAY_BUFFER, 0, view); @@ -405,14 +428,16 @@ * Ends the batch and flushes * */ -WebGLFastSpriteBatch.prototype.stop = function () { +WebGLFastSpriteBatch.prototype.stop = function () +{ this.flush(); }; /** * */ -WebGLFastSpriteBatch.prototype.start = function () { +WebGLFastSpriteBatch.prototype.start = function () +{ var gl = this.renderer.gl; // bind the main texture diff --git a/src/core/display/DisplayObject.js b/src/core/display/DisplayObject.js index 66ebc3c..20e778c 100644 --- a/src/core/display/DisplayObject.js +++ b/src/core/display/DisplayObject.js @@ -7,7 +7,8 @@ * @class * @namespace PIXI */ -function DisplayObject() { +function DisplayObject() +{ /** * The coordinate of the object relative to the local coordinates of the parent. * @@ -152,10 +153,12 @@ * @memberof DisplayObject# */ x: { - get: function () { + get: function () + { return this.position.x; }, - set: function (value) { + set: function (value) + { this.position.x = value; } }, @@ -167,10 +170,12 @@ * @memberof DisplayObject# */ y: { - get: function () { + get: function () + { return this.position.y; }, - set: function (value) { + set: function (value) + { this.position.y = value; } }, @@ -183,11 +188,13 @@ * @readonly */ worldVisible: { - get: function () { + get: function () + { var item = this; do { - if (!item.visible) { + if (!item.visible) + { return false; } @@ -207,17 +214,21 @@ * @memberof DisplayObject# */ mask: { - get: function () { + get: function () + { return this._mask; }, - set: function (value) { - if (this._mask) { + set: function (value) + { + if (this._mask) + { this._mask.isMask = false; } this._mask = value; - if (this._mask) { + if (this._mask) + { this._mask.isMask = true; } } @@ -232,18 +243,23 @@ * @memberof DisplayObject# */ filters: { - get: function () { + get: function () + { return this._filters; }, - set: function (value) { - if (value) { + set: function (value) + { + if (value) + { // now put all the passes in one place.. var passes = []; - for (var i = 0; i < value.length; i++) { + for (var i = 0; i < value.length; i++) + { var filterPasses = value[i].passes; - for (var j = 0; j < filterPasses.length; j++) { + for (var j = 0; j < filterPasses.length; j++) + { passes.push(filterPasses[j]); } } @@ -264,8 +280,9 @@ * * @private */ -DisplayObject.prototype.updateTransform = function () { - +DisplayObject.prototype.updateTransform = function () +{ + // create some matrix refs for easy access var pt = this.parent.worldTransform; var wt = this.worldTransform; @@ -274,9 +291,11 @@ var a, b, c, d, tx, ty; // so if rotation is between 0 then we can simplify the multiplication process.. - if (this.rotation % math.PI_2) { + if (this.rotation % math.PI_2) + { // 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) { + if (this.rotation !== this.rotationCache) + { this.rotationCache = this.rotation; this._sr = Math.sin(this.rotation); this._cr = Math.cos(this.rotation); @@ -291,7 +310,8 @@ ty = this.position.y; // check for pivot.. not often used so geared towards that fact! - if (this.pivot.x || this.pivot.y) { + 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; } @@ -304,7 +324,8 @@ wt.tx = tx * pt.a + ty * pt.c + pt.tx; wt.ty = tx * pt.b + ty * pt.d + pt.ty; } - else { + else + { // lets do the fast version as we know there is no rotation.. a = this.scale.x; d = this.scale.y; @@ -333,7 +354,8 @@ * @param matrix {Matrix} * @return {Rectangle} the rectangular bounding area */ -DisplayObject.prototype.getBounds = function (/* matrix */) { +DisplayObject.prototype.getBounds = function (/* matrix */) +{ return math.Rectangle.EMPTY; }; @@ -342,7 +364,8 @@ * * @return {Rectangle} the rectangular bounding area */ -DisplayObject.prototype.getLocalBounds = function () { +DisplayObject.prototype.getLocalBounds = function () +{ return this.getBounds(math.Matrix.IDENTITY); }; @@ -352,7 +375,8 @@ * @param position {Point} The world origin to calculate from * @return {Point} A point object representing the position of this object */ -DisplayObject.prototype.toGlobal = function (position) { +DisplayObject.prototype.toGlobal = function (position) +{ // don't need to u[date the lot this.displayObjectUpdateTransform(); return this.worldTransform.apply(position); @@ -365,8 +389,10 @@ * @param [from] {DisplayObject} The DisplayObject to calculate the global position from * @return {Point} A point object representing the position of this object */ -DisplayObject.prototype.toLocal = function (position, from) { - if (from) { +DisplayObject.prototype.toLocal = function (position, from) +{ + if (from) + { position = from.toGlobal(position); } @@ -381,7 +407,8 @@ * @param renderer {WebGLRenderer} The renderer * @private */ -DisplayObject.prototype.renderWebGL = function (/* renderer */) { +DisplayObject.prototype.renderWebGL = function (/* renderer */) +{ // OVERWRITE; }; @@ -391,6 +418,7 @@ * @param renderer {CanvasRenderer} The renderer * @private */ -DisplayObject.prototype.renderCanvas = function (/* renderer */) { +DisplayObject.prototype.renderCanvas = function (/* renderer */) +{ // OVERWRITE; }; diff --git a/src/core/display/DisplayObjectContainer.js b/src/core/display/DisplayObjectContainer.js index 689f40b..4625ee8 100644 --- a/src/core/display/DisplayObjectContainer.js +++ b/src/core/display/DisplayObjectContainer.js @@ -12,7 +12,8 @@ * @extends DisplayObject * @namespace PIXI */ -function DisplayObjectContainer() { +function DisplayObjectContainer() +{ DisplayObject.call(this); /** @@ -47,17 +48,21 @@ * @memberof DisplayObjectContainer# */ width: { - get: function () { + get: function () + { return this.scale.x * this.getLocalBounds().width; }, - set: function (value) { + set: function (value) + { var width = this.getLocalBounds().width; - if(width !== 0) { + if(width !== 0) + { this.scale.x = value / width; } - else { + else + { this.scale.x = 1; } @@ -73,17 +78,21 @@ * @memberof DisplayObjectContainer# */ height: { - get: function () { + get: function () + { return this.scale.y * this.getLocalBounds().height; }, - set: function (value) { + set: function (value) + { var height = this.getLocalBounds().height; - if (height !== 0) { + if (height !== 0) + { this.scale.y = value / height ; } - else { + else + { this.scale.y = 1; } @@ -100,18 +109,23 @@ * @memberof DisplayObject# */ cacheAsBitmap: { - get: function () { + get: function () + { return this._cacheAsBitmap; }, - set: function (value) { - if (this._cacheAsBitmap === value) { + set: function (value) + { + if (this._cacheAsBitmap === value) + { return; } - if (value) { + if (value) + { this._generateCachedSprite(); } - else { + else + { this._destroyCachedSprite(); } @@ -126,7 +140,8 @@ * @param child {DisplayObject} The DisplayObject to add to the container * @return {DisplayObject} The child that was added. */ -DisplayObjectContainer.prototype.addChild = function (child) { +DisplayObjectContainer.prototype.addChild = function (child) +{ return this.addChildAt(child, this.children.length); }; @@ -137,14 +152,18 @@ * @param index {Number} The index to place the child in * @return {DisplayObject} The child that was added. */ -DisplayObjectContainer.prototype.addChildAt = function (child, index) { +DisplayObjectContainer.prototype.addChildAt = function (child, index) +{ // prevent adding self as child - if (child === this) { + if (child === this) + { return; } - if (index >= 0 && index <= this.children.length) { - if (child.parent) { + if (index >= 0 && index <= this.children.length) + { + if (child.parent) + { child.parent.removeChild(child); } @@ -154,7 +173,8 @@ return child; } - else { + else + { throw new Error(child + 'addChildAt: The index '+ index +' supplied is out of bounds ' + this.children.length); } }; @@ -165,15 +185,18 @@ * @param child {DisplayObject} * @param child2 {DisplayObject} */ -DisplayObjectContainer.prototype.swapChildren = function (child, child2) { - if (child === child2) { +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) { + if (index1 < 0 || index2 < 0) + { throw new Error('swapChildren: Both the supplied DisplayObjects must be a child of the caller.'); } @@ -187,10 +210,12 @@ * @param child {DisplayObject} The DisplayObject instance to identify * @return {Number} The index position of the child display object to identify */ -DisplayObjectContainer.prototype.getChildIndex = function (child) { +DisplayObjectContainer.prototype.getChildIndex = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { throw new Error('The supplied DisplayObject must be a child of the caller'); } @@ -203,8 +228,10 @@ * @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 */ -DisplayObjectContainer.prototype.setChildIndex = function (child, index) { - if (index < 0 || index >= this.children.length) { +DisplayObjectContainer.prototype.setChildIndex = function (child, index) +{ + if (index < 0 || index >= this.children.length) + { throw new Error('The supplied index is out of bounds'); } @@ -220,8 +247,10 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child at the given index, if any. */ -DisplayObjectContainer.prototype.getChildAt = function (index) { - if (index < 0 || index >= this.children.length) { +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'); } @@ -234,10 +263,12 @@ * @param child {DisplayObject} The DisplayObject to remove * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChild = function (child) { +DisplayObjectContainer.prototype.removeChild = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { return; } @@ -250,7 +281,8 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChildAt = function (index) { +DisplayObjectContainer.prototype.removeChildAt = function (index) +{ var child = this.getChildAt(index); child.parent = null; @@ -265,24 +297,29 @@ * @param beginIndex {Number} The beginning position. Default value is 0. * @param endIndex {Number} The ending position. Default value is size of the container. */ -DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) { +DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) +{ var begin = beginIndex || 0; var end = typeof endIndex === 'number' ? endIndex : this.children.length; var range = end - begin; - if (range > 0 && range <= end) { + if (range > 0 && range <= end) + { var removed = this.children.splice(begin, range); - for (var i = 0; i < removed.length; ++i) { + for (var i = 0; i < removed.length; ++i) + { removed[i].parent = null; } return removed; } - else if (range === 0 && this.children.length === 0) { + else if (range === 0 && this.children.length === 0) + { return []; } - else { + else + { throw new RangeError('removeChildren: numeric values are outside the acceptable range.'); } }; @@ -291,7 +328,8 @@ * Generates and updates the cached sprite for this object. * */ -DisplayObjectContainer.prototype.updateCachedSprite = function () { +DisplayObjectContainer.prototype.updateCachedSprite = function () +{ this._generateCachedSprite(); }; @@ -304,7 +342,8 @@ * @param renderer {CanvasRenderer|WebGLRenderer} The renderer used to generate the texture. * @return {Texture} a texture of the graphics object */ -DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) { +DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) +{ var bounds = this.getLocalBounds(); var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0, renderer, scaleMode, resolution); @@ -322,18 +361,22 @@ * * @private */ -DisplayObjectContainer.prototype.updateTransform = function () { - if (!this.visible) { +DisplayObjectContainer.prototype.updateTransform = function () +{ + if (!this.visible) + { return; } this.displayObjectUpdateTransform(); - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { return; } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } }; @@ -346,8 +389,10 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getBounds = function () { - if (this.children.length === 0) { +DisplayObjectContainer.prototype.getBounds = function () +{ + if (this.children.length === 0) + { return math.Rectangle.EMPTY; } @@ -365,10 +410,12 @@ var childVisible = false; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -386,7 +433,8 @@ maxY = maxY > childMaxY ? maxY : childMaxY; } - if (!childVisible) { + if (!childVisible) + { return math.Rectangle.EMPTY; } @@ -407,12 +455,14 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getLocalBounds = function () { +DisplayObjectContainer.prototype.getLocalBounds = function () +{ var matrixCache = this.worldTransform; this.worldTransform = math.Matrix.IDENTITY; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } @@ -428,13 +478,16 @@ * * @param renderer {WebGLRenderer} The renderer */ -DisplayObjectContainer.prototype.renderWebGL = function (renderer) { +DisplayObjectContainer.prototype.renderWebGL = function (renderer) +{ // if the object is not visible or the alpha is 0 then no need to render this element - if (!this.visible || this.alpha <= 0) { + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } @@ -442,14 +495,17 @@ var i, j; // do a quick check to see if this element has a mask or a filter. - if (this._mask || this._filters) { + if (this._mask || this._filters) + { // push filter first as we need to ensure the stencil buffer is correct for any masking - if (this._filters) { + if (this._filters) + { renderer.spriteBatch.flush(); renderer.filterManager.pushFilter(this._filterBlock); } - if (this._mask) { + if (this._mask) + { renderer.spriteBatch.stop(); renderer.maskManager.pushMask(this.mask, renderer); renderer.spriteBatch.start(); @@ -459,36 +515,42 @@ this._renderWebGL(renderer); // now loop through the children and make sure they get rendered - for (i = 0, j = this.children.length; i < j; i++) { + for (i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderWebGL(renderer); } // time to stop the sprite batch as either a mask element or a filter draw will happen next renderer.spriteBatch.stop(); - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(this._mask, renderer); } - if (this._filters) { + if (this._filters) + { renderer.filterManager.popFilter(); } renderer.spriteBatch.start(); } - else { + else + { this._renderWebGL(renderer); // simple render children! - for (i = 0, j = this.children.length; i < j; ++i) { + for (i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderWebGL(renderer); } } }; -DisplayObjectContainer.prototype._renderWebGL = function (renderer) { +DisplayObjectContainer.prototype._renderWebGL = function (renderer) +{ // this is where content itself gets renderd.. @@ -499,25 +561,31 @@ * * @param renderer {CanvasRenderer} The renderer */ -DisplayObjectContainer.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0) { +DisplayObjectContainer.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -528,13 +596,16 @@ * @param renderer {WebGLRenderer|CanvasRenderer} The renderer * @private */ -DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) { +DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) +{ this._cachedSprite.worldAlpha = this.worldAlpha; - if (renderer.gl) { + if (renderer.gl) + { this._cachedSprite.renderWebGL(renderer); } - else { + else + { this._cachedSprite.renderCanvas(renderer); } }; @@ -544,10 +615,12 @@ * * @private */ -DisplayObjectContainer.prototype._generateCachedSprite = function () { +DisplayObjectContainer.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { // TODO - RenderTexture now *requires* a renderer instance, so this is like broken // because `renderer` isn't actually in scope here :P var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0); @@ -555,7 +628,8 @@ this._cachedSprite = new Sprite(renderTexture); this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.texture.resize(bounds.width | 0, bounds.height | 0); } @@ -580,8 +654,10 @@ * * @private */ -DisplayObjectContainer.prototype._destroyCachedSprite = function () { - if (!this._cachedSprite) { +DisplayObjectContainer.prototype._destroyCachedSprite = function () +{ + if (!this._cachedSprite) + { return; } diff --git a/src/core/display/Sprite.js b/src/core/display/Sprite.js index 707da24..5862aef 100644 --- a/src/core/display/Sprite.js +++ b/src/core/display/Sprite.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param texture {Texture} The texture for this sprite */ -function Sprite(texture) { +function Sprite(texture) +{ DisplayObjectContainer.call(this); /** @@ -85,12 +86,14 @@ this.texture = texture || Texture.EMPTY; } -Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) { +Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) +{ DisplayObjectContainer.prototype.destroy.call(this); this.anchor = null; - if (destroyTexture) { + if (destroyTexture) + { this._texture.destroy(destroyBaseTexture); } @@ -111,10 +114,12 @@ * @memberof Sprite# */ width: { - get: function () { + get: function () + { return this.scale.x * this.texture.frame.width; }, - set: function (value) { + set: function (value) + { this.scale.x = value / this.texture.frame.width; this._width = value; } @@ -127,10 +132,12 @@ * @memberof Sprite# */ height: { - get: function () { + get: function () + { return this.scale.y * this.texture.frame.height; }, - set: function (value) { + set: function (value) + { this.scale.y = value / this.texture.frame.height; this._height = value; } @@ -143,23 +150,29 @@ * @memberof Sprite# */ texture: { - get: function () { + get: function () + { return this._texture; }, - set: function (value) { - if (this._texture === value) { + set: function (value) + { + if (this._texture === value) + { return; } this._texture = value; this.cachedTint = 0xFFFFFF; - if (value) { + if (value) + { // wait for the texture to load - if (value.baseTexture.hasLoaded) { + if (value.baseTexture.hasLoaded) + { this._onTextureUpdate(); } - else { + else + { value.once('update', this._onTextureUpdate.bind(this)); } } @@ -172,18 +185,22 @@ * * @private */ -Sprite.prototype._onTextureUpdate = function () { +Sprite.prototype._onTextureUpdate = function () +{ // so if _width is 0 then width was not set.. - if (this._width) { + if (this._width) + { this.scale.x = this._width / this.texture.frame.width; } - if (this._height) { + if (this._height) + { this.scale.y = this._height / this.texture.frame.height; } }; -Sprite.prototype._renderWebGL = function (renderer) { +Sprite.prototype._renderWebGL = function (renderer) +{ // this is where content gets renderd.. // watch this space for a little render state manager.. @@ -197,7 +214,8 @@ * @param matrix {Matrix} the transformation matrix of the sprite * @return {Rectangle} the framing rectangle */ -Sprite.prototype.getBounds = function (matrix) { +Sprite.prototype.getBounds = function (matrix) +{ var width = this.texture.frame.width; var height = this.texture.frame.height; @@ -224,11 +242,13 @@ if(b === 0 && c === 0) { // scale may be negative! - if (a < 0) { + if (a < 0) + { a *= -1; } - if (d < 0) { + if (d < 0) + { d *= -1; } @@ -293,28 +313,34 @@ * * @param renderer {CanvasRenderer} The renderer */ -Sprite.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) { +Sprite.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) + { return; } - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; renderer.context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } // Ignore null sources - if (this.texture.valid) { + if (this.texture.valid) + { var resolution = this.texture.baseTexture.resolution / renderer.resolution; renderer.context.globalAlpha = this.worldAlpha; // If smoothingEnabled is supported and we need to change the smoothing property for this texture - if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) { + if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) + { renderer.scaleMode = this.texture.baseTexture.scaleMode; renderer.context[renderer.smoothProperty] = (renderer.scaleMode === CONST.scaleModes.LINEAR); } @@ -324,7 +350,8 @@ var dy = (this.texture.trim ? this.texture.trim.y : 0) - (this.anchor.y * this.texture.trim.height); // Allow for pixel rounding - if (renderer.roundPixels) { + if (renderer.roundPixels) + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -337,7 +364,8 @@ dx = dx | 0; dy = dy | 0; } - else { + else + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -348,8 +376,10 @@ ); } - if (this.tint !== 0xFFFFFF) { - if (this.cachedTint !== this.tint) { + if (this.tint !== 0xFFFFFF) + { + if (this.cachedTint !== this.tint) + { this.cachedTint = this.tint; // TODO clean up caching - how to clean up the caches? @@ -368,7 +398,8 @@ this.texture.crop.height / resolution ); } - else { + else + { renderer.context.drawImage( this.texture.baseTexture.source, this.texture.crop.x, @@ -383,11 +414,13 @@ } } - for (var i = 0, j = this.children.length; i < j; i++) { + for (var i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -402,10 +435,12 @@ * @param frameId {String} The frame Id of the texture in the cache * @return {Sprite} A new Sprite using a texture from the texture cache matching the frameId */ -Sprite.fromFrame = function (frameId) { +Sprite.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache' + this); } @@ -420,6 +455,7 @@ * @param imageId {String} The image url of the texture * @return {Sprite} A new Sprite using a texture from the texture cache matching the image id */ -Sprite.fromImage = function (imageId, crossorigin, scaleMode) { +Sprite.fromImage = function (imageId, crossorigin, scaleMode) +{ return new Sprite(Texture.fromImage(imageId, crossorigin, scaleMode)); }; diff --git a/src/core/display/SpriteBatch.js b/src/core/display/SpriteBatch.js index 3187777..c196fef 100644 --- a/src/core/display/SpriteBatch.js +++ b/src/core/display/SpriteBatch.js @@ -12,7 +12,8 @@ * ```js * var container = new SpriteBatch(); * - * for(var i = 0; i < 100; ++i) { + * for(var i = 0; i < 100; ++i) + * { * var sprite = new PIXI.Sprite.fromImage("myImage.png"); * container.addChild(sprite); * } @@ -25,7 +26,8 @@ */ //TODO RENAME to PARTICLE CONTAINER? -function SpriteBatch() { +function SpriteBatch() +{ DisplayObjectContainer.call(this); } @@ -38,7 +40,8 @@ * * @private */ -SpriteBatch.prototype.updateTransform = function () { +SpriteBatch.prototype.updateTransform = function () +{ // TODO don't need to! this.displayObjectUpdateTransform(); // PIXI.DisplayObjectContainer.prototype.updateTransform.call( this ); @@ -50,8 +53,10 @@ * @param renderer {WebGLRenderer} The webgl renderer * @private */ -SpriteBatch.prototype.renderWebGL = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderWebGL = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -71,8 +76,10 @@ * @param renderer {CanvasRenderer} The canvas renderer * @private */ -SpriteBatch.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -84,10 +91,12 @@ this.displayObjectUpdateTransform(); - for (var i = 0; i < this.children.length; ++i) { + for (var i = 0; i < this.children.length; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -95,9 +104,11 @@ context.globalAlpha = this.worldAlpha * child.alpha; - if (child.rotation % (Math.PI * 2) === 0) { + if (child.rotation % (Math.PI * 2) === 0) + { // this is the fastest way to optimise! - if rotation is 0 then we can avoid any kind of setTransform call - if (isRotated) { + if (isRotated) + { context.setTransform( transform.a, transform.b, @@ -122,8 +133,10 @@ frame.height * child.scale.y ); } - else { - if (!isRotated) { + else + { + if (!isRotated) + { isRotated = true; } @@ -131,7 +144,8 @@ var childTransform = child.worldTransform; - if (renderer.roundPixels) { + if (renderer.roundPixels) + { context.setTransform( childTransform.a, childTransform.b, @@ -141,7 +155,8 @@ childTransform.ty | 0 ); } - else { + else + { context.setTransform( childTransform.a, childTransform.b, diff --git a/src/core/index.js b/src/core/index.js index 3954b6f..eb4a82b 100644 --- a/src/core/index.js +++ b/src/core/index.js @@ -58,11 +58,13 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRenderer: function (width, height, options, noWebGL) { + autoDetectRenderer: function (width, height, options, noWebGL) + { width = width || 800; height = height || 600; - if (!noWebGL && require('webgl-enabled')()) { + if (!noWebGL && require('webgl-enabled')()) + { return new core.WebGLRenderer(width, height, options); } @@ -87,7 +89,8 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRecommendedRenderer: function (width, height, options) { + autoDetectRecommendedRenderer: function (width, height, options) + { var isAndroid = /Android/i.test(navigator.userAgent); return core.autoDetectRenderer(width, height, options, isAndroid); diff --git a/src/core/math/Matrix.js b/src/core/math/Matrix.js index c2f87e2..2ff4848 100644 --- a/src/core/math/Matrix.js +++ b/src/core/math/Matrix.js @@ -10,7 +10,8 @@ * @class * @namespace PIXI */ -function Matrix() { +function Matrix() +{ /** * @member {number} * @default 1 @@ -63,7 +64,8 @@ * * @param array {number[]} The array that the matrix will be populated from. */ -Matrix.prototype.fromArray = function (array) { +Matrix.prototype.fromArray = function (array) +{ this.a = array[0]; this.b = array[1]; this.c = array[3]; @@ -78,14 +80,17 @@ * @param transpose {boolean} Whether we need to transpose the matrix or not * @return {number[]} the newly created array which contains the matrix */ -Matrix.prototype.toArray = function (transpose) { - if (!this.array) { +Matrix.prototype.toArray = function (transpose) +{ + if (!this.array) + { this.array = new Float32Array(9); } var array = this.array; - if (transpose) { + if (transpose) + { array[0] = this.a; array[1] = this.b; array[2] = 0; @@ -96,7 +101,8 @@ array[7] = this.ty; array[8] = 1; } - else { + else + { array[0] = this.a; array[1] = this.c; array[2] = this.tx; @@ -119,7 +125,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, transformed through this matrix */ -Matrix.prototype.apply = function (pos, newPos) { +Matrix.prototype.apply = function (pos, newPos) +{ newPos = newPos || new Point(); newPos.x = this.a * pos.x + this.c * pos.y + this.tx; @@ -136,7 +143,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, inverse-transformed through this matrix */ -Matrix.prototype.applyInverse = function (pos, newPos) { +Matrix.prototype.applyInverse = function (pos, newPos) +{ newPos = newPos || new Point(); var id = 1 / (this.a * this.d + this.c * -this.b); @@ -154,7 +162,8 @@ * @param {number} y * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.translate = function (x, y) { +Matrix.prototype.translate = function (x, y) +{ this.tx += x; this.ty += y; @@ -168,7 +177,8 @@ * @param {number} y The amount to scale vertically * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.scale = function (x, y) { +Matrix.prototype.scale = function (x, y) +{ this.a *= x; this.d *= y; this.c *= x; @@ -186,7 +196,8 @@ * @param {number} angle - The angle in radians. * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.rotate = function (angle) { +Matrix.prototype.rotate = function (angle) +{ var cos = Math.cos( angle ); var sin = Math.sin( angle ); @@ -210,7 +221,8 @@ * @param {Matrix} matrix * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.append = function (matrix) { +Matrix.prototype.append = function (matrix) +{ var a1 = this.a; var b1 = this.b; var c1 = this.c; @@ -232,7 +244,8 @@ * * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.identity = function () { +Matrix.prototype.identity = function () +{ this.a = 1; this.b = 0; this.c = 0; diff --git a/src/core/math/Point.js b/src/core/math/Point.js index 7565b2d..632f346 100644 --- a/src/core/math/Point.js +++ b/src/core/math/Point.js @@ -7,7 +7,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -function Point(x, y) { +function Point(x, y) +{ /** * @member {number} * @default 0 @@ -29,7 +30,8 @@ * * @return {Point} a copy of the point */ -Point.prototype.clone = function () { +Point.prototype.clone = function () +{ return new Point(this.x, this.y); }; @@ -40,7 +42,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -Point.prototype.set = function (x, y) { +Point.prototype.set = function (x, y) +{ this.x = x || 0; this.y = y || ( (y !== 0) ? this.x : 0 ) ; }; diff --git a/src/core/math/shapes/Circle.js b/src/core/math/shapes/Circle.js index 69cfdc9..4d76efc 100644 --- a/src/core/math/shapes/Circle.js +++ b/src/core/math/shapes/Circle.js @@ -10,7 +10,8 @@ * @param y {number} The Y coordinate of the center of this circle * @param radius {number} The radius of the circle */ -function Circle(x, y, radius) { +function Circle(x, y, radius) +{ /** * @member {number} * @default 0 @@ -46,7 +47,8 @@ * @method clone * @return {Circle} a copy of the Circle */ -Circle.prototype.clone = function () { +Circle.prototype.clone = function () +{ return new Circle(this.x, this.y, this.radius); }; @@ -58,8 +60,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Circle */ -Circle.prototype.contains = function (x, y) { - if (this.radius <= 0) { +Circle.prototype.contains = function (x, y) +{ + if (this.radius <= 0) + { return false; } @@ -79,6 +83,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Circle.prototype.getBounds = function () { +Circle.prototype.getBounds = function () +{ return new Rectangle(this.x - this.radius, this.y - this.radius, this.radius * 2, this.radius * 2); }; diff --git a/src/core/math/shapes/Ellipse.js b/src/core/math/shapes/Ellipse.js index 4f2d066..fefd01a 100644 --- a/src/core/math/shapes/Ellipse.js +++ b/src/core/math/shapes/Ellipse.js @@ -11,7 +11,8 @@ * @param width {number} The half width of this ellipse * @param height {number} The half height of this ellipse */ -function Ellipse(x, y, width, height) { +function Ellipse(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -53,7 +54,8 @@ * @method clone * @return {Ellipse} a copy of the ellipse */ -Ellipse.prototype.clone = function () { +Ellipse.prototype.clone = function () +{ return new Ellipse(this.x, this.y, this.width, this.height); }; @@ -65,8 +67,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coords are within this ellipse */ -Ellipse.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Ellipse.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } @@ -86,6 +90,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Ellipse.prototype.getBounds = function () { +Ellipse.prototype.getBounds = function () +{ return new Rectangle(this.x - this.width, this.y - this.height, this.width, this.height); }; diff --git a/src/core/math/shapes/Polygon.js b/src/core/math/shapes/Polygon.js index ae89148..fea6d37 100644 --- a/src/core/math/shapes/Polygon.js +++ b/src/core/math/shapes/Polygon.js @@ -10,16 +10,20 @@ * arguments passed can be flat x,y values e.g. `new Polygon(x,y, x,y, x,y, ...)` where `x` and `y` are * Numbers. */ -function Polygon(points) { +function Polygon(points) +{ //if points isn't an array, use arguments as the array - if (!(points instanceof Array)) { + if (!(points instanceof Array)) + { points = Array.prototype.slice.call(arguments); } //if this is a flat array of numbers, convert it to points - if (points[0] instanceof Point) { + if (points[0] instanceof Point) + { var p = []; - for (var i = 0, il = points.length; i < il; i++) { + for (var i = 0, il = points.length; i < il; i++) + { p.push(points[i].x, points[i].y); } @@ -51,7 +55,8 @@ * * @return {Polygon} a copy of the polygon */ -Polygon.prototype.clone = function () { +Polygon.prototype.clone = function () +{ return new Polygon(this.points.slice()); }; @@ -62,19 +67,22 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this polygon */ -Polygon.prototype.contains = function (x, y) { +Polygon.prototype.contains = function (x, y) +{ var inside = false; // use some raycasting to test hits // https://github.com/substack/point-in-polygon/blob/master/index.js var length = this.points.length / 2; - for (var i = 0, j = length - 1; i < length; j = i++) { + for (var i = 0, j = length - 1; i < length; j = i++) + { var xi = this.points[i * 2], yi = this.points[i * 2 + 1], xj = this.points[j * 2], yj = this.points[j * 2 + 1], intersect = ((yi > y) !== (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi); - if (intersect) { + if (intersect) + { inside = !inside; } } diff --git a/src/core/math/shapes/Rectangle.js b/src/core/math/shapes/Rectangle.js index 16ac62a..4008b68 100644 --- a/src/core/math/shapes/Rectangle.js +++ b/src/core/math/shapes/Rectangle.js @@ -10,7 +10,8 @@ * @param width {number} The overall width of this rectangle * @param height {number} The overall height of this rectangle */ -function Rectangle(x, y, width, height) { +function Rectangle(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -60,7 +61,8 @@ * * @return {Rectangle} a copy of the rectangle */ -Rectangle.prototype.clone = function () { +Rectangle.prototype.clone = function () +{ return new Rectangle(this.x, this.y, this.width, this.height); }; @@ -71,13 +73,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rectangle */ -Rectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Rectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/math/shapes/RoundedRectangle.js b/src/core/math/shapes/RoundedRectangle.js index 27d286e..7bf6411 100644 --- a/src/core/math/shapes/RoundedRectangle.js +++ b/src/core/math/shapes/RoundedRectangle.js @@ -11,7 +11,8 @@ * @param height {number} The overall height of this rounded rectangle * @param radius {number} Controls the radius of the rounded corners */ -function RoundedRectangle(x, y, width, height, radius) { +function RoundedRectangle(x, y, width, height, radius) +{ /** * @member {number} * @default 0 @@ -58,7 +59,8 @@ * * @return {RoundedRectangle} a copy of the rounded rectangle */ -RoundedRectangle.prototype.clone = function () { +RoundedRectangle.prototype.clone = function () +{ return new RoundedRectangle(this.x, this.y, this.width, this.height, this.radius); }; @@ -69,13 +71,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rounded Rectangle */ -RoundedRectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +RoundedRectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/primitives/Graphics.js b/src/core/primitives/Graphics.js index 261c534..e902d2a 100644 --- a/src/core/primitives/Graphics.js +++ b/src/core/primitives/Graphics.js @@ -16,7 +16,8 @@ * @extends DisplayObjectContainer * @namespace PIXI */ -function Graphics() { +function Graphics() +{ DisplayObjectContainer.call(this); this.renderable = true; @@ -154,16 +155,20 @@ * @private */ cacheAsBitmap: { - get: function () { + get: function () + { return this._cacheAsBitmap; }, - set: function (value) { + set: function (value) + { this._cacheAsBitmap = value; - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._generateCachedSprite(); } - else { + else + { this.destroyCachedSprite(); this.dirty = true; } @@ -176,7 +181,8 @@ * * @return {Graphics} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ var clone = new Graphics(); clone.renderable = this.renderable; @@ -192,7 +198,8 @@ clone.cachedSpriteDirty = this.cachedSpriteDirty; // copy graphics data - for (var i = 0; i < this.graphicsData.length; ++i) { + for (var i = 0; i < this.graphicsData.length; ++i) + { clone.graphicsData.push(this.graphicsData.clone()); } @@ -211,17 +218,21 @@ * @param alpha {number} alpha of the line to draw, will update the objects stored style * @return {Graphics} */ -Graphics.prototype.lineStyle = function (lineWidth, color, alpha) { +Graphics.prototype.lineStyle = function (lineWidth, color, alpha) +{ this.lineWidth = lineWidth || 0; this.lineColor = color || 0; this.lineAlpha = (arguments.length < 3) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length) + { // halfway through a line? start a new one! this.drawShape( new math.Polygon( this.currentPath.shape.points.slice(-2) )); } - else { + else + { // otherwise its empty so lets just set the line properties this.currentPath.lineWidth = this.lineWidth; this.currentPath.lineColor = this.lineColor; @@ -239,7 +250,8 @@ * @param y {number} the Y coordinate to move to * @return {Graphics} */ -Graphics.prototype.moveTo = function (x, y) { +Graphics.prototype.moveTo = function (x, y) +{ this.drawShape(new math.Polygon([x,y])); return this; @@ -253,7 +265,8 @@ * @param y {number} the Y coordinate to draw to * @return {Graphics} */ -Graphics.prototype.lineTo = function (x, y) { +Graphics.prototype.lineTo = function (x, y) +{ this.currentPath.shape.points.push(x, y); this.dirty = true; @@ -270,13 +283,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -285,7 +302,8 @@ n = 20, points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { this.moveTo(0, 0); } @@ -293,7 +311,8 @@ var fromY = points[points.length-1]; var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; xa = fromX + ( (cpX - fromX) * j ); @@ -319,13 +338,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -342,7 +365,8 @@ var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; dt = (1 - j); @@ -373,13 +397,17 @@ * @param radius {number} The radius of the arc * @return {Graphics} */ -Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points.push(x1, y1); } } - else { + else + { this.moveTo(x1, y1); } @@ -392,12 +420,15 @@ b2 = x2 - x1, mm = Math.abs(a1 * b2 - b1 * a2); - if (mm < 1.0e-8 || radius === 0) { - if (points[points.length-2] !== x1 || points[points.length-1] !== y1) { + if (mm < 1.0e-8 || radius === 0) + { + if (points[points.length-2] !== x1 || points[points.length-1] !== y1) + { points.push(x1, y1); } } - else { + else + { var dd = a1 * a1 + b1 * b1, cc = a2 * a2 + b2 * b2, tt = a1 * a2 + b1 * b2, @@ -433,42 +464,51 @@ * @param anticlockwise {boolean} Optional. Specifies whether the drawing should be counterclockwise or clockwise. False is default, and indicates clockwise, while true indicates counter-clockwise. * @return {Graphics} */ -Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) { +Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) +{ var startX = cx + Math.cos(startAngle) * radius; var startY = cy + Math.sin(startAngle) * radius; var points; // TODO - This if-else makes no sense. It uses currentPath in the else where it doesn't exist... - if (this.currentPath) { + if (this.currentPath) + { points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { points.push(startX, startY); } - else if (points[points.length-2] !== startX || points[points.length-1] !== startY) { + else if (points[points.length-2] !== startX || points[points.length-1] !== startY) + { points.push(startX, startY); } } - else { + else + { this.moveTo(startX, startY); points = this.currentPath.shape.points; } - if (startAngle === endAngle) { + if (startAngle === endAngle) + { return this; } - if (!anticlockwise && endAngle <= startAngle) { + if (!anticlockwise && endAngle <= startAngle) + { endAngle += Math.PI * 2; } - else if (anticlockwise && startAngle <= endAngle) { + else if (anticlockwise && startAngle <= endAngle) + { startAngle += Math.PI * 2; } var sweep = anticlockwise ? (startAngle - endAngle) *-1 : (endAngle - startAngle); var segs = (Math.abs(sweep)/ (Math.PI * 2)) * 40; - if (sweep === 0) { + if (sweep === 0) + { return this; } @@ -482,7 +522,8 @@ var remainder = ( segMinus % 1 ) / segMinus; - for (var i = 0; i <= segMinus; ++i) { + for (var i = 0; i <= segMinus; ++i) + { var real = i + remainder * i; var angle = ((theta) + startAngle + (theta2 * real)); @@ -506,13 +547,16 @@ * @param alpha {number} the alpha of the fill * @return {Graphics} */ -Graphics.prototype.beginFill = function (color, alpha) { +Graphics.prototype.beginFill = function (color, alpha) +{ this.filling = true; this.fillColor = color || 0; this.fillAlpha = (alpha === undefined) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length <= 2) + { this.currentPath.fill = this.filling; this.currentPath.fillColor = this.fillColor; this.currentPath.fillAlpha = this.fillAlpha; @@ -526,7 +570,8 @@ * * @return {Graphics} */ -Graphics.prototype.endFill = function () { +Graphics.prototype.endFill = function () +{ this.filling = false; this.fillColor = null; this.fillAlpha = 1; @@ -542,7 +587,8 @@ * @param height {number} The height of the rectangle * @return {Graphics} */ -Graphics.prototype.drawRect = function ( x, y, width, height ) { +Graphics.prototype.drawRect = function ( x, y, width, height ) +{ this.drawShape(new math.Rectangle(x,y, width, height)); return this; @@ -556,7 +602,8 @@ * @param height {number} The height of the rectangle * @param radius {number} Radius of the rectangle corners */ -Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) { +Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) +{ this.drawShape(new math.RoundedRectangle(x, y, width, height, radius)); return this; @@ -570,7 +617,8 @@ * @param radius {number} The radius of the circle * @return {Graphics} */ -Graphics.prototype.drawCircle = function (x, y, radius) { +Graphics.prototype.drawCircle = function (x, y, radius) +{ this.drawShape(new math.Circle(x,y, radius)); return this; @@ -585,7 +633,8 @@ * @param height {number} The half height of the ellipse * @return {Graphics} */ -Graphics.prototype.drawEllipse = function (x, y, width, height) { +Graphics.prototype.drawEllipse = function (x, y, width, height) +{ this.drawShape(new math.Ellipse(x, y, width, height)); return this; @@ -597,8 +646,10 @@ * @param path {Array} The path data used to construct the polygon. * @return {Graphics} */ -Graphics.prototype.drawPolygon = function (path) { - if (!(path instanceof Array)) { +Graphics.prototype.drawPolygon = function (path) +{ + if (!(path instanceof Array)) + { path = Array.prototype.slice.call(arguments); } @@ -612,7 +663,8 @@ * * @return {Graphics} */ -Graphics.prototype.clear = function () { +Graphics.prototype.clear = function () +{ this.lineWidth = 0; this.filling = false; @@ -631,7 +683,8 @@ * @param scaleMode {number} Should be one of the scaleMode consts * @return {Texture} a texture of the graphics object */ -Graphics.prototype.generateTexture = function (resolution, scaleMode) { +Graphics.prototype.generateTexture = function (resolution, scaleMode) +{ resolution = resolution || 1; var bounds = this.getBounds(); @@ -655,17 +708,21 @@ * * @param renderer {WebGLRenderer} */ -Graphics.prototype._renderWebGL = function (renderer) { +Graphics.prototype._renderWebGL = function (renderer) +{ // if the sprite is not visible or the alpha is 0 then no need to render this element - if (this.isMask === true) { + if (this.isMask === true) + { return; } // this code may still be needed so leaving for now.. - // + // /* - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture on the gpu too! @@ -681,17 +738,24 @@ return; } - */ - - // check if the webgl graphic needs to be updated - if (this.glDirty) { - this.dirty = true; - this.glDirty = false; - } + else */ - renderer.setObjectRendererer(renderer.graphicsRenderer); - renderer.graphicsRenderer.render(this); + renderer.spriteBatch.stop(); + renderer.blendModeManager.setBlendMode(this.blendMode); + // check blend mode + renderer.blendModeManager.setBlendMode( this.blendMode ); + + // check if the webgl graphic needs to be updated + if (this.glDirty) + { + this.dirty = true; + this.glDirty = false; + } + + WebGLGraphics.renderGraphics(this, renderer); + + renderer.spriteBatch.start(); }; /** @@ -700,14 +764,18 @@ * @param renderer {CanvasRenderer} * @private */ -Graphics.prototype.renderCanvas = function (renderer) { +Graphics.prototype.renderCanvas = function (renderer) +{ // 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.isMask === true) { + if (!this.visible || this.alpha <= 0 || this.isMask === true) + { return; } - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture @@ -723,16 +791,19 @@ return; } - else { + else + { var context = renderer.context; var transform = this.worldTransform; - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } @@ -748,11 +819,13 @@ CanvasGraphics.renderGraphics(this, context); - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } } @@ -763,13 +836,16 @@ * * @return {Rectangle} the rectangular bounding area */ -Graphics.prototype.getBounds = function (matrix) { +Graphics.prototype.getBounds = function (matrix) +{ // return an empty object if the item is a mask! - if (this.isMask) { + if (this.isMask) + { return math.Rectangle.EMPTY; } - if (this.dirty) { + if (this.dirty) + { this.updateLocalBounds(); this.glDirty = true; @@ -841,23 +917,27 @@ * Update the bounds of the object * */ -Graphics.prototype.updateLocalBounds = function () { +Graphics.prototype.updateLocalBounds = function () +{ var minX = Infinity; var maxX = -Infinity; var minY = Infinity; var maxY = -Infinity; - if (this.graphicsData.length) { + if (this.graphicsData.length) + { var shape, points, x, y, w, h; - for (var i = 0; i < this.graphicsData.length; i++) { + for (var i = 0; i < this.graphicsData.length; i++) + { var data = this.graphicsData[i]; var type = data.type; var lineWidth = data.lineWidth; shape = data.shape; - if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) { + if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) + { x = shape.x - lineWidth/2; y = shape.y - lineWidth/2; w = shape.width + lineWidth; @@ -869,7 +949,8 @@ minY = y < minY ? y : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.CIRC) { + else if (type === CONST.SHAPES.CIRC) + { x = shape.x; y = shape.y; w = shape.radius + lineWidth/2; @@ -881,7 +962,8 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.ELIP) { + else if (type === CONST.SHAPES.ELIP) + { x = shape.x; y = shape.y; w = shape.width + lineWidth/2; @@ -893,11 +975,13 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else { + else + { // POLY points = shape.points; - for (var j = 0; j < points.length; j += 2) { + for (var j = 0; j < points.length; j += 2) + { x = points[j]; y = points[j+1]; @@ -910,7 +994,8 @@ } } } - else { + else + { minX = 0; maxX = 0; minY = 0; @@ -931,10 +1016,12 @@ * * @private */ -Graphics.prototype._generateCachedSprite = function () { +Graphics.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { var canvasBuffer = new CanvasBuffer(bounds.width, bounds.height); var texture = Texture.fromCanvas(canvasBuffer.canvas); @@ -943,7 +1030,8 @@ this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.buffer.resize(bounds.width, bounds.height); } @@ -968,7 +1056,8 @@ * * @private */ -Graphics.prototype.updateCachedSpriteTexture = function () { +Graphics.prototype.updateCachedSpriteTexture = function () +{ var cachedSprite = this._cachedSprite; var texture = cachedSprite.texture; var canvas = cachedSprite.buffer.canvas; @@ -989,7 +1078,8 @@ * Destroys a previous cached sprite. * */ -Graphics.prototype.destroyCachedSprite = function () { +Graphics.prototype.destroyCachedSprite = function () +{ this._cachedSprite.texture.destroy(true); // let the gc collect the unused sprite @@ -1003,10 +1093,13 @@ * @param {Circle|Rectangle|Ellipse|Line|Polygon} shape The Shape object to draw. * @return {GraphicsData} The generated GraphicsData object. */ -Graphics.prototype.drawShape = function (shape) { - if (this.currentPath) { +Graphics.prototype.drawShape = function (shape) +{ + if (this.currentPath) + { // check current path! - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath.shape.points.length <= 2) + { this.graphicsData.pop(); } } @@ -1017,7 +1110,8 @@ this.graphicsData.push(data); - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { data.shape.closed = this.filling; this.currentPath = data; } diff --git a/src/core/primitives/GraphicsData.js b/src/core/primitives/GraphicsData.js index 99decbe..788f6f2 100644 --- a/src/core/primitives/GraphicsData.js +++ b/src/core/primitives/GraphicsData.js @@ -4,7 +4,8 @@ * @class * @namespace PIXI */ -function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) { +function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) +{ this.lineWidth = lineWidth; this.lineColor = lineColor; this.lineAlpha = lineAlpha; @@ -27,7 +28,8 @@ * * @return {GraphicsData} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ return new GraphicsData( this.lineWidth, this.lineColor, diff --git a/src/core/renderers/canvas/CanvasRenderer.js b/src/core/renderers/canvas/CanvasRenderer.js index 15a0978..7aebd44 100644 --- a/src/core/renderers/canvas/CanvasRenderer.js +++ b/src/core/renderers/canvas/CanvasRenderer.js @@ -17,17 +17,22 @@ * @param [options.resolution=1] {number} the resolution of the renderer retina would be 2 * @param [options.clearBeforeRender=true] {boolean} This sets if the CanvasRenderer will clear the canvas or not before the new render pass. */ -function CanvasRenderer(width, height, options) { +function CanvasRenderer(width, height, options) +{ utils.sayHello('Canvas'); - if (options) { - for (var i in CONST.defaultRenderOptions) { - if (typeof options[i] === 'undefined') { + if (options) + { + for (var i in CONST.defaultRenderOptions) + { + if (typeof options[i] === 'undefined') + { options[i] = CONST.defaultRenderOptions[i]; } } } - else { + else + { options = CONST.defaultRenderOptions; } @@ -156,19 +161,24 @@ this.smoothProperty = null; - if (this.context.imageSmoothingEnabled) { + if (this.context.imageSmoothingEnabled) + { this.smoothProperty = 'imageSmoothingEnabled'; } - else if (this.context.webkitImageSmoothingEnabled) { + else if (this.context.webkitImageSmoothingEnabled) + { this.smoothProperty = 'webkitImageSmoothingEnabled'; } - else if (this.context.mozImageSmoothingEnabled) { + else if (this.context.mozImageSmoothingEnabled) + { this.smoothProperty = 'mozImageSmoothingEnabled'; } - else if (this.context.oImageSmoothingEnabled) { + else if (this.context.oImageSmoothingEnabled) + { this.smoothProperty = 'oImageSmoothingEnabled'; } - else if (this.context.msImageSmoothingEnabled) { + else if (this.context.msImageSmoothingEnabled) + { this.smoothProperty = 'msImageSmoothingEnabled'; } @@ -193,10 +203,12 @@ * @memberof CanvasRenderer# */ backgroundColor: { - get: function () { + get: function () + { return this._backgroundColor; }, - set: function (val) { + set: function (val) + { this._backgroundColor = val; this._backgroundColorString = utils.hex2string(val); } @@ -208,7 +220,8 @@ * * @param object {DisplayObject} the object to be rendered */ -CanvasRenderer.prototype.render = function (object) { +CanvasRenderer.prototype.render = function (object) +{ object.updateTransform(); this.context.setTransform(1,0,0,1,0,0); @@ -218,16 +231,20 @@ this.currentBlendMode = CONST.blendModes.NORMAL; this.context.globalCompositeOperation = this.blendModes[CONST.blendModes.NORMAL]; - if (navigator.isCocoonJS && this.view.screencanvas) { + if (navigator.isCocoonJS && this.view.screencanvas) + { this.context.fillStyle = 'black'; this.context.clear(); } - if (this.clearBeforeRender) { - if (this.transparent) { + if (this.clearBeforeRender) + { + if (this.transparent) + { this.context.clearRect(0, 0, this.width, this.height); } - else { + else + { this.context.fillStyle = this._backgroundColorString; this.context.fillRect(0, 0, this.width , this.height); } @@ -241,8 +258,10 @@ * * @param [removeView=false] {boolean} Removes the Canvas element from the DOM. */ -CanvasRenderer.prototype.destroy = function (removeView) { - if (removeView && this.view.parent) { +CanvasRenderer.prototype.destroy = function (removeView) +{ + if (removeView && this.view.parent) + { this.view.parent.removeChild(this.view); } @@ -257,14 +276,16 @@ * @param width {number} the new width of the canvas view * @param height {number} the new height of the canvas view */ -CanvasRenderer.prototype.resize = function (width, height) { +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) { + if (this.autoResize) + { this.view.style.width = this.width / this.resolution + 'px'; this.view.style.height = this.height / this.resolution + 'px'; } @@ -276,7 +297,8 @@ * @param displayObject {DisplayObject} The displayObject to render * @private */ -CanvasRenderer.prototype.renderDisplayObject = function (displayObject) { +CanvasRenderer.prototype.renderDisplayObject = function (displayObject) +{ displayObject.renderCanvas(this); }; @@ -285,11 +307,14 @@ * * @private */ -CanvasRenderer.prototype._mapBlendModes = function () { - if (!this.blendModes) { +CanvasRenderer.prototype._mapBlendModes = function () +{ + if (!this.blendModes) + { this.blendModes = {}; - if (utils.canUseNewCanvasBlendModes()) { + if (utils.canUseNewCanvasBlendModes()) + { this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? this.blendModes[CONST.blendModes.MULTIPLY] = 'multiply'; @@ -308,7 +333,8 @@ this.blendModes[CONST.blendModes.COLOR] = 'color'; this.blendModes[CONST.blendModes.LUMINOSITY] = 'luminosity'; } - else { + else + { // this means that the browser does not support the cool new blend modes in canvas 'cough' ie 'cough' this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? diff --git a/src/core/renderers/canvas/utils/CanvasBuffer.js b/src/core/renderers/canvas/utils/CanvasBuffer.js index ebe5d47..b183a66 100644 --- a/src/core/renderers/canvas/utils/CanvasBuffer.js +++ b/src/core/renderers/canvas/utils/CanvasBuffer.js @@ -6,7 +6,8 @@ * @param width {number} the width for the newly created canvas * @param height {number} the height for the newly created canvas */ -function CanvasBuffer(width, height) { +function CanvasBuffer(width, height) +{ /** * The Canvas object that belongs to this CanvasBuffer. * @@ -36,10 +37,12 @@ * @memberof CanvasBuffer# */ width: { - get: function () { + get: function () + { return this.canvas.width; }, - set: function (val) { + set: function (val) + { this.canvas.width = val; } }, @@ -50,10 +53,12 @@ * @memberof CanvasBuffer# */ height: { - get: function () { + get: function () + { return this.canvas.height; }, - set: function (val) { + set: function (val) + { this.canvas.height = val; } } @@ -64,7 +69,8 @@ * * @private */ -CanvasBuffer.prototype.clear = function () { +CanvasBuffer.prototype.clear = function () +{ this.context.setTransform(1, 0, 0, 1, 0, 0); this.context.clearRect(0,0, this.canvas.width, this.canvas.height); }; @@ -75,7 +81,8 @@ * @param width {number} the new width of the canvas * @param height {number} the new height of the canvas */ -CanvasBuffer.prototype.resize = function (width, height) { +CanvasBuffer.prototype.resize = function (width, height) +{ this.canvas.width = width; this.canvas.height = height; }; diff --git a/src/core/renderers/canvas/utils/CanvasGraphics.js b/src/core/renderers/canvas/utils/CanvasGraphics.js index c7eaa2a..3f2a91f 100644 --- a/src/core/renderers/canvas/utils/CanvasGraphics.js +++ b/src/core/renderers/canvas/utils/CanvasGraphics.js @@ -13,15 +13,18 @@ * @param graphics {Graphics} the actual graphics object to render * @param context {CanvasRenderingContext2D} the 2d drawing method of the canvas */ -CanvasGraphics.renderGraphics = function (graphics, context) { +CanvasGraphics.renderGraphics = function (graphics, context) +{ var worldAlpha = graphics.worldAlpha; - if (graphics.dirty) { + if (graphics.dirty) + { this.updateGraphicsTint(graphics); graphics.dirty = false; } - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; @@ -30,69 +33,82 @@ context.lineWidth = data.lineWidth; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { context.beginPath(); var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } - if (shape.closed) { + if (shape.closed) + { context.lineTo(points[0], points[1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fillRect(shape.x, shape.y, shape.width, shape.height); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.strokeRect(shape.x, shape.y, shape.width, shape.height); } } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.beginPath(); context.arc(shape.x, shape.y, shape.radius,0,2*Math.PI); context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas var w = shape.width * 2; @@ -119,18 +135,21 @@ context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; var width = shape.width; @@ -152,13 +171,15 @@ context.quadraticCurveTo(rx, ry, rx, ry + radius); context.closePath(); - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); @@ -174,45 +195,54 @@ * @param graphics {Graphics} the graphics which will be used as a mask * @param context {CanvasRenderingContext2D} the context 2d method of the canvas */ -CanvasGraphics.renderGraphicsMask = function (graphics, context) { +CanvasGraphics.renderGraphicsMask = function (graphics, context) +{ var len = graphics.graphicsData.length; - if (len === 0) { + if (len === 0) + { return; } context.beginPath(); - for (var i = 0; i < len; i++) { + for (var i = 0; i < len; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { context.rect(shape.x, shape.y, shape.width, shape.height); context.closePath(); } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.arc(shape.x, shape.y, shape.radius, 0, 2 * Math.PI); context.closePath(); } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas @@ -237,7 +267,8 @@ context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); context.closePath(); } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; @@ -262,8 +293,10 @@ } }; -CanvasGraphics.updateGraphicsTint = function (graphics) { - if (graphics.tint === 0xFFFFFF) { +CanvasGraphics.updateGraphicsTint = function (graphics) +{ + if (graphics.tint === 0xFFFFFF) + { return; } @@ -271,7 +304,8 @@ var tintG = (graphics.tint >> 8 & 0xFF) / 255; var tintB = (graphics.tint & 0xFF)/ 255; - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var fillColor = data.fillColor | 0; diff --git a/src/core/renderers/canvas/utils/CanvasMaskManager.js b/src/core/renderers/canvas/utils/CanvasMaskManager.js index e04a733..9827d36 100644 --- a/src/core/renderers/canvas/utils/CanvasMaskManager.js +++ b/src/core/renderers/canvas/utils/CanvasMaskManager.js @@ -6,7 +6,8 @@ * @class * @namespace PIXI */ -function CanvasMaskManager() {} +function CanvasMaskManager() +{} CanvasMaskManager.prototype.constructor = CanvasMaskManager; module.exports = CanvasMaskManager; @@ -17,7 +18,8 @@ * @param maskData {object} the maskData that will be pushed * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.pushMask = function (maskData, renderer) { +CanvasMaskManager.prototype.pushMask = function (maskData, renderer) +{ renderer.context.save(); var cacheAlpha = maskData.alpha; @@ -45,6 +47,7 @@ * * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.popMask = function (renderer) { +CanvasMaskManager.prototype.popMask = function (renderer) +{ renderer.context.restore(); }; diff --git a/src/core/renderers/canvas/utils/CanvasTinter.js b/src/core/renderers/canvas/utils/CanvasTinter.js index 17e0529..d2fb1bc 100644 --- a/src/core/renderers/canvas/utils/CanvasTinter.js +++ b/src/core/renderers/canvas/utils/CanvasTinter.js @@ -14,7 +14,8 @@ * @param color {number} the color to use to tint the sprite with * @return {HTMLCanvasElement} The tinted canvas */ -CanvasTinter.getTintedTexture = function (sprite, color) { +CanvasTinter.getTintedTexture = function (sprite, color) +{ var texture = sprite.texture; color = CanvasTinter.roundColor(color); @@ -23,7 +24,8 @@ texture.tintCache = texture.tintCache || {}; - if (texture.tintCache[stringColor]) { + if (texture.tintCache[stringColor]) + { return texture.tintCache[stringColor]; } @@ -33,14 +35,16 @@ //CanvasTinter.tintWithPerPixel(texture, stringColor, canvas); CanvasTinter.tintMethod(texture, color, canvas); - if (CanvasTinter.convertTintToImage) { + if (CanvasTinter.convertTintToImage) + { // is this better? var tintImage = new Image(); tintImage.src = canvas.toDataURL(); texture.tintCache[stringColor] = tintImage; } - else { + else + { texture.tintCache[stringColor] = canvas; // if we are not converting the texture to an image then we need to lose the reference to the canvas CanvasTinter.canvas = null; @@ -56,7 +60,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithMultiply = function (texture, color, canvas) { +CanvasTinter.tintWithMultiply = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -104,7 +109,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithOverlay = function (texture, color, canvas) { +CanvasTinter.tintWithOverlay = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -139,7 +145,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithPerPixel = function (texture, color, canvas) { +CanvasTinter.tintWithPerPixel = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -167,7 +174,8 @@ var pixels = pixelData.data; - for (var i = 0; i < pixels.length; i += 4) { + for (var i = 0; i < pixels.length; i += 4) + { pixels[i+0] *= r; pixels[i+1] *= g; pixels[i+2] *= b; @@ -181,7 +189,8 @@ * * @param color {number} the color to round, should be a hex color */ -CanvasTinter.roundColor = function (color) { +CanvasTinter.roundColor = function (color) +{ var step = CanvasTinter.cacheStepsPerColorChannel; var rgbValues = utils.hex2rgb(color); diff --git a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js index 9f2f89a..35edbaf 100644 --- a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js +++ b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLBlendModeManager(renderer) { +function WebGLBlendModeManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -23,8 +24,10 @@ * * @param blendMode {number} the blendMode, should be a Pixi const, such as BlendModes.ADD */ -WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) { - if (this.currentBlendMode === blendMode) { +WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) +{ + if (this.currentBlendMode === blendMode) + { return false; } diff --git a/src/core/renderers/webgl/managers/WebGLFilterManager.js b/src/core/renderers/webgl/managers/WebGLFilterManager.js index 1179258..2dac048 100644 --- a/src/core/renderers/webgl/managers/WebGLFilterManager.js +++ b/src/core/renderers/webgl/managers/WebGLFilterManager.js @@ -7,7 +7,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLFilterManager(renderer) { +function WebGLFilterManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -32,7 +33,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.texturePool.length = 0; self.initShaderBuffers(); }); @@ -46,7 +48,8 @@ * @param renderer {WebGLRenderer} * @param buffer {ArrayBuffer} */ -WebGLFilterManager.prototype.begin = function (buffer) { +WebGLFilterManager.prototype.begin = function (buffer) +{ this.defaultShader = this.renderer.shaderManager.defaultShader; this.width = this.renderer.projection.x * 2; @@ -60,7 +63,8 @@ * * @param filterBlock {object} the filter that will be pushed to the current filter stack */ -WebGLFilterManager.prototype.pushFilter = function (filterBlock) { +WebGLFilterManager.prototype.pushFilter = function (filterBlock) +{ var gl = this.renderer.gl; var projection = this.renderer.projection; @@ -78,10 +82,12 @@ this.offsetY += filterBlock._filterArea.y; var texture = this.texturePool.pop(); - if (!texture) { + if (!texture) + { texture = new FilterTexture(this.renderer.gl, this.width, this.height); } - else { + else + { texture.resize(this.width, this.height); } @@ -98,29 +104,35 @@ var localX = filterArea.x, localY = filterArea.y; - if (filterArea.x < 0) { + if (filterArea.x < 0) + { filterArea.width += filterArea.x; filterArea.x = 0; } - if (filterArea.y < 0) { + if (filterArea.y < 0) + { filterArea.height += filterArea.y; filterArea.y = 0; } - if (localX + filterArea.width > this.width) { + if (localX + filterArea.width > this.width) + { filterArea.width = this.width - localX; } - if (localY + filterArea.height > this.height) { + if (localY + filterArea.height > this.height) + { filterArea.height = this.height - localY; } - if (filterArea.width < 0) { + if (filterArea.width < 0) + { filterArea.width = 0; } - if (filterArea.height < 0) { + if (filterArea.height < 0) + { filterArea.height = 0; } @@ -154,7 +166,8 @@ * Removes the last filter from the filter stack and doesn't return it. * */ -WebGLFilterManager.prototype.popFilter = function () { +WebGLFilterManager.prototype.popFilter = function () +{ var gl = this.renderer.gl; var filterBlock = this.filterStack.pop(); @@ -163,7 +176,8 @@ var projection = this.renderer.projection; var offset = this.renderer.offset; - if (filterBlock.filterPasses.length > 1) { + if (filterBlock.filterPasses.length > 1) + { gl.viewport(0, 0, filterArea.width, filterArea.height); gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); @@ -193,7 +207,8 @@ var inputTexture = texture; var outputTexture = this.texturePool.pop(); - if (!outputTexture) { + if (!outputTexture) + { outputTexture = new FilterTexture(this.renderer.gl, this.width, this.height); } outputTexture.resize(this.width, this.height); @@ -204,7 +219,8 @@ gl.disable(gl.BLEND); - for (var i = 0; i < filterBlock.filterPasses.length-1; i++) { + for (var i = 0; i < filterBlock.filterPasses.length-1; i++) + { var filterPass = filterBlock.filterPasses[i]; gl.bindFramebuffer(gl.FRAMEBUFFER, outputTexture.frameBuffer ); @@ -243,10 +259,12 @@ var buffer = this.buffer; // time to render the filters texture to the previous scene - if (this.filterStack.length === 0) { + if (this.filterStack.length === 0) + { gl.colorMask(true, true, true, true);//this.transparent); } - else { + else + { var currentFilter = this.filterStack[this.filterStack.length-1]; filterArea = currentFilter._filterArea; @@ -332,13 +350,15 @@ * @param width {number} the horizontal range of the filter * @param height {number} the vertical range of the filter */ -WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) { +WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) +{ // use program var gl = this.renderer.gl; var shader = filter.shaders[gl.id]; - if (!shader) { + if (!shader) + { shader = new Shader(gl); shader.fragmentSrc = filter.fragmentSrc; @@ -356,7 +376,8 @@ gl.uniform2f(shader.projectionVector, width/2, -height/2); gl.uniform2f(shader.offsetVector, 0,0); - if (filter.uniforms.dimensions) { + 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]; @@ -386,7 +407,8 @@ * Initialises the shader buffers. * */ -WebGLFilterManager.prototype.initShaderBuffers = function () { +WebGLFilterManager.prototype.initShaderBuffers = function () +{ var gl = this.renderer.gl; // create some buffers @@ -432,7 +454,8 @@ * Destroys the filter and removes it from the filter stack. * */ -WebGLFilterManager.prototype.destroy = function () { +WebGLFilterManager.prototype.destroy = function () +{ var gl = this.renderer.gl; this.filterStack = null; @@ -441,7 +464,8 @@ this.offsetY = 0; // destroy textures - for (var i = 0; i < this.texturePool.length; i++) { + for (var i = 0; i < this.texturePool.length; i++) + { this.texturePool[i].destroy(); } diff --git a/src/core/renderers/webgl/managers/WebGLManager.js b/src/core/renderers/webgl/managers/WebGLManager.js index 9d47b5c..c30cd51 100644 --- a/src/core/renderers/webgl/managers/WebGLManager.js +++ b/src/core/renderers/webgl/managers/WebGLManager.js @@ -3,7 +3,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLManager(renderer) { +function WebGLManager(renderer) +{ /** * The renderer this manager works for. * @@ -15,6 +16,7 @@ WebGLManager.prototype.constructor = WebGLManager; module.exports = WebGLManager; -WebGLManager.prototype.destroy = function () { +WebGLManager.prototype.destroy = function () +{ this.renderer = null; }; diff --git a/src/core/renderers/webgl/managers/WebGLMaskManager.js b/src/core/renderers/webgl/managers/WebGLMaskManager.js index 2f90b64..e568812 100644 --- a/src/core/renderers/webgl/managers/WebGLMaskManager.js +++ b/src/core/renderers/webgl/managers/WebGLMaskManager.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLMaskManager(renderer) { +function WebGLMaskManager(renderer) +{ WebGLManager.call(this, renderer); } @@ -19,12 +20,15 @@ * * @param maskData {any[]} */ -WebGLMaskManager.prototype.pushMask = function (maskData) { - if (maskData.dirty) { +WebGLMaskManager.prototype.pushMask = function (maskData) +{ + if (maskData.dirty) + { WebGLGraphics.updateGraphics(maskData, this.renderer.gl); } - if (!maskData._webGL[this.renderer.gl.id].data.length) { + if (!maskData._webGL[this.renderer.gl.id].data.length) + { return; } @@ -36,6 +40,7 @@ * * @param maskData {any[]} */ -WebGLMaskManager.prototype.popMask = function (maskData) { +WebGLMaskManager.prototype.popMask = function (maskData) +{ this.renderer.stencilManager.popStencil(maskData, maskData._webGL[this.renderer.gl.id].data[0], this.renderer); }; diff --git a/src/core/renderers/webgl/managers/WebGLShaderManager.js b/src/core/renderers/webgl/managers/WebGLShaderManager.js index fef071c..90c6477 100644 --- a/src/core/renderers/webgl/managers/WebGLShaderManager.js +++ b/src/core/renderers/webgl/managers/WebGLShaderManager.js @@ -10,7 +10,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLShaderManager(renderer) { +function WebGLShaderManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -28,7 +29,8 @@ */ this.tempAttribState = []; - for (var i = 0; i < this.maxAttibs; i++) { + for (var i = 0; i < this.maxAttibs; i++) + { this.attribState[i] = false; } @@ -66,7 +68,8 @@ // listen for context and update necessary shaders var self = this; - this.renderer.on('context', function (event) { + this.renderer.on('context', function (event) + { var gl = event.data; // this shader is used for rendering primitives @@ -97,29 +100,36 @@ * * @param attribs {Array} attribs */ -WebGLShaderManager.prototype.setAttribs = function (attribs) { +WebGLShaderManager.prototype.setAttribs = function (attribs) +{ // reset temp state var i; - for (i = 0; i < this.tempAttribState.length; i++) { + for (i = 0; i < this.tempAttribState.length; i++) + { this.tempAttribState[i] = false; } // set the new attribs - for (var a in attribs) { + for (var a in attribs) + { this.tempAttribState[attribs[a]] = true; } var gl = this.renderer.gl; - for (i = 0; i < this.attribState.length; i++) { - if (this.attribState[i] !== this.tempAttribState[i]) { + for (i = 0; i < this.attribState.length; i++) + { + if (this.attribState[i] !== this.tempAttribState[i]) + { this.attribState[i] = this.tempAttribState[i]; - if (this.attribState[i]) { + if (this.attribState[i]) + { gl.enableVertexAttribArray(i); } - else { + else + { gl.disableVertexAttribArray(i); } } @@ -131,8 +141,10 @@ * * @param shader {Any} */ -WebGLShaderManager.prototype.setShader = function (shader) { - if (this._currentId === shader.uuid) { +WebGLShaderManager.prototype.setShader = function (shader) +{ + if (this._currentId === shader.uuid) + { return false; } @@ -150,7 +162,8 @@ * Destroys this object. * */ -WebGLShaderManager.prototype.destroy = function () { +WebGLShaderManager.prototype.destroy = function () +{ this.attribState = null; this.tempAttribState = null; diff --git a/src/core/renderers/webgl/managers/WebGLStencilManager.js b/src/core/renderers/webgl/managers/WebGLStencilManager.js index 9ec6398..4cb0134 100644 --- a/src/core/renderers/webgl/managers/WebGLStencilManager.js +++ b/src/core/renderers/webgl/managers/WebGLStencilManager.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLStencilManager(renderer) { +function WebGLStencilManager(renderer) +{ WebGLManager.call(this, renderer); this.stencilStack = []; @@ -24,12 +25,14 @@ * @param graphics {Graphics} * @param webGLData {any[]} */ -WebGLStencilManager.prototype.pushStencil = function (graphics, webGLData) { +WebGLStencilManager.prototype.pushStencil = function (graphics, webGLData) +{ var gl = this.renderer.gl; this.bindGraphics(graphics, webGLData, this.renderer); - if (this.stencilStack.length === 0) { + if (this.stencilStack.length === 0) + { gl.enable(gl.STENCIL_TEST); gl.clear(gl.STENCIL_BUFFER_BIT); this.reverse = true; @@ -47,14 +50,17 @@ // draw the triangle strip! - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } @@ -62,31 +68,38 @@ // draw a quad to increment.. gl.drawElements(gl.TRIANGLE_FAN, 4, gl.UNSIGNED_SHORT, ( webGLData.indices.length - 4 ) * 2 ); - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); } this.reverse = !this.reverse; } - else { - if (!this.reverse) { + else + { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } - else { + 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) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); } } @@ -103,7 +116,8 @@ * @param graphics {Graphics} * @param webGLData {Array} */ -WebGLStencilManager.prototype.bindGraphics = function (graphics, webGLData) { +WebGLStencilManager.prototype.bindGraphics = function (graphics, webGLData) +{ //if (this._currentGraphics === graphics)return; this._currentGraphics = graphics; @@ -114,7 +128,8 @@ offset = this.renderer.offset, shader;// = this.renderer.shaderManager.primitiveShader; - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { shader = this.renderer.shaderManager.complexPrimitiveShader; this.renderer.shaderManager.setShader(shader); @@ -141,7 +156,8 @@ // set the index buffer! gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, webGLData.indexBuffer); } - else { + else + { //this.renderer.shaderManager.activatePrimitiveShader(); shader = this.renderer.shaderManager.primitiveShader; this.renderer.shaderManager.setShader( shader ); @@ -154,7 +170,7 @@ gl.uniform2f(shader.uniforms.offsetVector._location, -offset.x, -offset.y); gl.uniform3fv(shader.uniforms.tint._location, utils.hex2rgb(graphics.tint)); - + gl.uniform1f(shader.uniforms.alpha._location, graphics.worldAlpha); @@ -172,19 +188,22 @@ * @param graphics {Graphics} * @param webGLData {Array} */ -WebGLStencilManager.prototype.popStencil = function (graphics, webGLData) { +WebGLStencilManager.prototype.popStencil = function (graphics, webGLData) +{ var gl = this.renderer.gl; this.stencilStack.pop(); this.count--; - if (this.stencilStack.length === 0) { + if (this.stencilStack.length === 0) + { // the stack is empty! gl.disable(gl.STENCIL_TEST); } - else { + else + { var level = this.count; @@ -192,14 +211,17 @@ gl.colorMask(false, false, false, false); - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { this.reverse = !this.reverse; - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } @@ -213,31 +235,38 @@ // draw the triangle strip! gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); - if (!this.reverse) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); } } - else { + else + { // console.log("<<>>") - if (!this.reverse) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } - else { + 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) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); } } @@ -253,7 +282,8 @@ * Destroys the mask stack. * */ -WebGLStencilManager.prototype.destroy = function () { +WebGLStencilManager.prototype.destroy = function () +{ this.renderer = null; this.stencilStack = null; }; diff --git a/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js b/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js index 913ba5e..1ea7d19 100644 --- a/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js +++ b/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function ComplexPrimitiveShader(gl) { +function ComplexPrimitiveShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -24,7 +25,8 @@ 'uniform float flipY;', 'varying vec4 vColor;', - 'void main(void) {', + '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);', @@ -37,7 +39,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = vColor;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/FastShader.js b/src/core/renderers/webgl/shaders/FastShader.js index bd2e29a..2e5e060 100644 --- a/src/core/renderers/webgl/shaders/FastShader.js +++ b/src/core/renderers/webgl/shaders/FastShader.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function FastShader(gl) { +function FastShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -28,7 +29,8 @@ 'const vec2 center = vec2(-1.0, 1.0);', - 'void main(void) {', + 'void main(void) + {', ' vec2 v;', ' vec2 sv = aVertexPosition * aScale;', ' v.x = (sv.x) * cos(aRotation) - (sv.y) * sin(aRotation);', @@ -49,7 +51,8 @@ 'uniform sampler2D uSampler;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/PrimitiveShader.js b/src/core/renderers/webgl/shaders/PrimitiveShader.js index 6f25409..a25f54f 100644 --- a/src/core/renderers/webgl/shaders/PrimitiveShader.js +++ b/src/core/renderers/webgl/shaders/PrimitiveShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function PrimitiveShader(gl) { +function PrimitiveShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -23,7 +24,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + '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);', @@ -36,7 +38,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = vColor;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/Shader.js b/src/core/renderers/webgl/shaders/Shader.js index f8964f5..fd75ef5 100644 --- a/src/core/renderers/webgl/shaders/Shader.js +++ b/src/core/renderers/webgl/shaders/Shader.js @@ -6,7 +6,8 @@ * @param [fragmentSrc] {string} The source of the fragment shader. * @param [vertexSrc] {string} The source of the vertex shader. */ -function Shader(gl, vertexSrc, fragmentSrc, customUniforms, customAttributes) { +function Shader(gl, vertexSrc, fragmentSrc, customUniforms, customAttributes) +{ /** * @member {number} * @readonly @@ -33,7 +34,8 @@ dimensions: { type: '4f', value: new Float32Array(4) } }; - for (var u in customUniforms) { + for (var u in customUniforms) + { this.uniforms[u] = customUniforms[u]; } @@ -43,7 +45,8 @@ aColor: 0 }; - for (var a in customAttributes) { + for (var a in customAttributes) + { this.attributes[a] = customAttributes[a]; } @@ -66,7 +69,8 @@ 'const vec2 center = vec2(-1.0, 1.0);', - 'void main(void) {', + 'void main(void) + {', ' gl_Position = vec4( ((aVertexPosition + offsetVector) / projectionVector) + center , 0.0, 1.0);', ' vTextureCoord = aTextureCoord;', ' vColor = vec4(aColor.rgb * aColor.a, aColor.a);', @@ -85,7 +89,8 @@ 'uniform sampler2D uSampler;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;', '}' ].join('\n'); @@ -96,7 +101,8 @@ Shader.prototype.constructor = Shader; module.exports = Shader; -Shader.prototype.init = function () { +Shader.prototype.init = function () +{ this.compile(); this.gl.useProgram(this.program); @@ -105,14 +111,18 @@ this.cacheAttributeLocations(Object.keys(this.attributes)); }; -Shader.prototype.cacheUniformLocations = function (keys) { - for (var i = 0; i < keys.length; ++i) { +Shader.prototype.cacheUniformLocations = function (keys) +{ + for (var i = 0; i < keys.length; ++i) + { this.uniforms[keys[i]]._location = this.gl.getUniformLocation(this.program, keys[i]); } }; -Shader.prototype.cacheAttributeLocations = function (keys) { - for (var i = 0; i < keys.length; ++i) { +Shader.prototype.cacheAttributeLocations = function (keys) +{ + for (var i = 0; i < keys.length; ++i) + { this.attributes[keys[i]] = this.gl.getAttribLocation(this.program, keys[i]); } @@ -124,14 +134,16 @@ // 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.attributes.aColor === -1) { + // if (this.attributes.aColor === -1) + { // this.attributes.aColor = 2; // } // End worst hack eva // }; -Shader.prototype.compile = function () { +Shader.prototype.compile = function () +{ var gl = this.gl; var glVertShader = this._glCompile(gl.VERTEX_SHADER, this.vertexSrc); @@ -144,13 +156,15 @@ gl.linkProgram(program); // if linking fails, then log and cleanup - if (!gl.getProgramParameter(program, gl.LINK_STATUS)) { + if (!gl.getProgramParameter(program, gl.LINK_STATUS)) + { window.console.error('Pixi.js Error: Could not initialize shader.'); window.console.error('gl.VALIDATE_STATUS', gl.getProgramParameter(program, gl.VALIDATE_STATUS)); window.console.error('gl.getError()', gl.getError()); // if there is a program info log, log it - if (gl.getProgramInfoLog(program) !== '') { + if (gl.getProgramInfoLog(program) !== '') + { window.console.warn('Pixi.js Warning: gl.getProgramInfoLog()', gl.getProgramInfoLog(program)); } @@ -165,18 +179,21 @@ return (this.program = program); }; -Shader.prototype.syncUniforms = function () { +Shader.prototype.syncUniforms = function () +{ var gl = this.gl; this.textureCount = 1; - for (var key in this.uniforms) { + for (var key in this.uniforms) + { var uniform = this.uniforms[key], location = uniform._location, value = uniform.value, i, il; - switch (uniform.type) { + switch (uniform.type) + { // single int value case 'i': case '1i': @@ -282,7 +299,8 @@ // a Color Value case 'c': - if (typeof value === 'number') { + if (typeof value === 'number') + { value = utils.hex2rgb(value); } @@ -311,11 +329,13 @@ // array of 2D Point objects case 'v2v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(2 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 2] = value[i].x; uniform._array[i * 2 + 1] = value[i].y; } @@ -325,11 +345,13 @@ // array of 3D Point objects case 'v3v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(3 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 3] = value[i].x; uniform._array[i * 3 + 1] = value[i].y; uniform._array[i * 3 + 2] = value[i].z; @@ -341,11 +363,13 @@ // array of 4D Point objects case 'v4v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(4 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 4] = value[i].x; uniform._array[i * 4 + 1] = value[i].y; uniform._array[i * 4 + 2] = value[i].z; @@ -359,7 +383,8 @@ // PIXI.Texture case 't': case 'sampler2D': - if (!uniform.value || !uniform.value.baseTexture || !uniform.value.baseTexture.hasLoaded) { + if (!uniform.value || !uniform.value.baseTexture || !uniform.value.baseTexture.hasLoaded) + { break; } @@ -376,7 +401,8 @@ this.textureCount++; // initialize the texture if we haven't yet - if (!uniform._init) { + if (!uniform._init) + { this.initSampler2D(uniform); uniform._init = true; @@ -394,11 +420,13 @@ * Initialises a Sampler2D uniform (which may only be available later on after initUniforms once the texture has loaded) * */ -Shader.prototype.initSampler2D = function (uniform) { +Shader.prototype.initSampler2D = function (uniform) +{ var gl = this.gl; // Extended texture data - if (uniform.textureData) { + if (uniform.textureData) + { var data = uniform.textureData; // GLTexture = mag linear, min linear_mipmap_linear, wrap repeat + gl.generateMipmap(gl.TEXTURE_2D); @@ -417,14 +445,16 @@ var wrapT = (data.wrapT) ? data.wrapT : gl.CLAMP_TO_EDGE; var format = (data.luminance) ? gl.LUMINANCE : gl.RGBA; - if (data.repeat) { + if (data.repeat) + { wrapS = gl.REPEAT; wrapT = gl.REPEAT; } gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, !!data.flipY); - if (data.width) { + if (data.width) + { var width = (data.width) ? data.width : 512; var height = (data.height) ? data.height : 2; var border = (data.border) ? data.border : 0; @@ -432,7 +462,8 @@ // 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 { + 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); } @@ -448,7 +479,8 @@ * Destroys the shader. * */ -Shader.prototype.destroy = function () { +Shader.prototype.destroy = function () +{ this.gl.deleteProgram(this.program); this.gl = null; @@ -459,13 +491,15 @@ this.fragmentSrc = null; }; -Shader.prototype._glCompile = function (type, src) { +Shader.prototype._glCompile = function (type, src) +{ var shader = this.gl.createShader(type); this.gl.shaderSource(shader, src); this.gl.compileShader(shader); - if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) { + if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) + { window.console.log(this.gl.getShaderInfoLog(shader)); return null; } diff --git a/src/core/renderers/webgl/shaders/StripShader.js b/src/core/renderers/webgl/shaders/StripShader.js index 193f6e1..a7abcc6 100644 --- a/src/core/renderers/webgl/shaders/StripShader.js +++ b/src/core/renderers/webgl/shaders/StripShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function StripShader(gl) { +function StripShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -20,7 +21,8 @@ 'varying vec2 vTextureCoord;', - 'void main(void) {', + '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);', @@ -36,7 +38,8 @@ 'varying vec2 vTextureCoord;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vec2(vTextureCoord.x, vTextureCoord.y)) * alpha;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/utils/FilterTexture.js b/src/core/renderers/webgl/utils/FilterTexture.js index d2c8423..4433d44 100644 --- a/src/core/renderers/webgl/utils/FilterTexture.js +++ b/src/core/renderers/webgl/utils/FilterTexture.js @@ -8,7 +8,8 @@ * @param height {number} the vertical range of the filter * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values */ -function FilterTexture(gl, width, height, scaleMode) { +function FilterTexture(gl, width, height, scaleMode) +{ /** * @member {WebGLContext} */ @@ -59,7 +60,8 @@ * Clears the filter texture. * */ -FilterTexture.prototype.clear = function () { +FilterTexture.prototype.clear = function () +{ var gl = this.gl; gl.clearColor(0,0,0, 0); @@ -72,8 +74,10 @@ * @param width {number} the new width of the texture * @param height {number} the new height of the texture */ -FilterTexture.prototype.resize = function (width, height) { - if (this.width === width && this.height === height) { +FilterTexture.prototype.resize = function (width, height) +{ + if (this.width === width && this.height === height) + { return; } @@ -96,7 +100,8 @@ * Destroys the filter texture. * */ -FilterTexture.prototype.destroy = function () { +FilterTexture.prototype.destroy = function () +{ var gl = this.gl; gl.deleteFramebuffer( this.frameBuffer ); gl.deleteTexture( this.texture ); diff --git a/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js b/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js index c4721e9..a63f4d7 100644 --- a/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js +++ b/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js @@ -14,7 +14,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this sprite batch works for. */ -function WebGLFastSpriteBatch(renderer) { +function WebGLFastSpriteBatch(renderer) +{ /** * The renderer instance this sprite batch operates on. * @@ -91,7 +92,8 @@ */ this.lastIndexCount = 0; - for (var i=0, j=0; i < numIndices; i += 6, j += 4) { + 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; @@ -144,7 +146,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.setupContext(); }); } @@ -157,7 +160,8 @@ * * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLFastSpriteBatch.prototype.setupContext = function () { +WebGLFastSpriteBatch.prototype.setupContext = function () +{ var gl = this.renderer.gl; // create a couple of buffers @@ -177,7 +181,8 @@ /** * @param spriteBatch {SpriteBatch} The SpriteBatch container to prepare for. */ -WebGLFastSpriteBatch.prototype.begin = function (spriteBatch) { +WebGLFastSpriteBatch.prototype.begin = function (spriteBatch) +{ this.shader = this.renderer.shaderManager.fastShader; this.matrix = spriteBatch.worldTransform.toArray(true); @@ -187,33 +192,38 @@ /** */ -WebGLFastSpriteBatch.prototype.end = function () { +WebGLFastSpriteBatch.prototype.end = function () +{ this.flush(); }; /** * @param spriteBatch {SpriteBatch} The SpriteBatch container to render. */ -WebGLFastSpriteBatch.prototype.render = function (spriteBatch) { +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) { + if (!sprite.texture._uvs) + { return; } this.currentBaseTexture = sprite.texture.baseTexture; // check blend mode - if (sprite.blendMode !== this.renderer.blendModeManager.currentBlendMode) { + if (sprite.blendMode !== this.renderer.blendModeManager.currentBlendMode) + { this.flush(); this.renderer.blendModeManager.setBlendMode(sprite.blendMode); } - for (var i=0,j= children.length; i= this.size) { + if (this.currentBatchSize >= this.size) + { this.flush(); } }; @@ -362,29 +379,35 @@ /** * */ -WebGLFastSpriteBatch.prototype.flush = function () { +WebGLFastSpriteBatch.prototype.flush = function () +{ // If the batch is length 0 then return as there is nothing to draw - if (this.currentBatchSize === 0) { + if (this.currentBatchSize === 0) + { return; } var gl = this.renderer.gl; // bind the current texture - if (!this.currentBaseTexture._glTextures[gl.id]) { + if (!this.currentBaseTexture._glTextures[gl.id]) + { this.renderer.updateTexture(this.currentBaseTexture, gl); } //TODO-SHOUD THIS BE ELSE??!?!?! - else { + else + { gl.bindTexture(gl.TEXTURE_2D, this.currentBaseTexture._glTextures[gl.id]); } // upload the verts to the buffer - if (this.currentBatchSize > ( this.size * 0.5 ) ) { + if (this.currentBatchSize > ( this.size * 0.5 ) ) + { gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); } - else { + else + { var view = this.vertices.subarray(0, this.currentBatchSize * this.vertByteSize); gl.bufferSubData(gl.ARRAY_BUFFER, 0, view); @@ -405,14 +428,16 @@ * Ends the batch and flushes * */ -WebGLFastSpriteBatch.prototype.stop = function () { +WebGLFastSpriteBatch.prototype.stop = function () +{ this.flush(); }; /** * */ -WebGLFastSpriteBatch.prototype.start = function () { +WebGLFastSpriteBatch.prototype.start = function () +{ var gl = this.renderer.gl; // bind the main texture diff --git a/src/core/renderers/webgl/utils/WebGLGraphics.js b/src/core/renderers/webgl/utils/WebGLGraphics.js index 55f4911..ab8f46e 100644 --- a/src/core/renderers/webgl/utils/WebGLGraphics.js +++ b/src/core/renderers/webgl/utils/WebGLGraphics.js @@ -19,7 +19,8 @@ * @param graphics {Graphics} * @param renderer {WebGLRenderer} */ -WebGLGraphics.renderGraphics = function (graphics, renderer) {//projection, offset) { +WebGLGraphics.renderGraphics = function (graphics, renderer) {//projection, offset) +{ var gl = renderer.gl; var projection = renderer.projection, @@ -27,7 +28,8 @@ shader = renderer.shaderManager.primitiveShader, webGLData; - if (graphics.dirty) { + if (graphics.dirty) + { WebGLGraphics.updateGraphics(graphics, gl); } @@ -35,8 +37,10 @@ // This could be speeded up for sure! - for (var i = 0; i < webGL.data.length; i++) { - if (webGL.data[i].mode === 1) { + for (var i = 0; i < webGL.data.length; i++) + { + if (webGL.data[i].mode === 1) + { webGLData = webGL.data[i]; renderer.stencilManager.pushStencil(graphics, webGLData, renderer); @@ -46,7 +50,8 @@ renderer.stencilManager.popStencil(graphics, webGLData, renderer); } - else { + else + { webGLData = webGL.data[i]; @@ -84,12 +89,14 @@ * @param graphicsData {Graphics} The graphics object to update * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLGraphics.updateGraphics = function (graphics, gl) { +WebGLGraphics.updateGraphics = function (graphics, gl) +{ // get the contexts graphics object var webGL = graphics._webGL[gl.id]; // if the graphics object does not exist in the webGL context time to create it! - if (!webGL) { + if (!webGL) + { webGL = graphics._webGL[gl.id] = {lastIndex:0, data:[], gl:gl}; } @@ -99,11 +106,13 @@ var i; // if the user cleared the graphics object we will need to clear every object - if (graphics.clearDirty) { + if (graphics.clearDirty) + { graphics.clearDirty = false; // lop through and return all the webGLDatas to the object pool so than can be reused later on - for (i = 0; i < webGL.data.length; i++) { + for (i = 0; i < webGL.data.length; i++) + { var graphicsData = webGL.data[i]; graphicsData.reset(); WebGLGraphics.graphicsDataPool.push( graphicsData ); @@ -119,58 +128,72 @@ // loop through the graphics datas and construct each one.. // if the object is a complex fill then the new stencil buffer technique will be used // other wise graphics objects will be pushed into a batch.. - for (i = webGL.lastIndex; i < graphics.graphicsData.length; i++) { + for (i = webGL.lastIndex; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { // need to add the points the the graphics object.. data.points = data.shape.points.slice(); - if (data.shape.closed) { + if (data.shape.closed) + { // close the poly if the value is true! - if (data.points[0] !== data.points[data.points.length-2] || data.points[1] !== data.points[data.points.length-1]) { + if (data.points[0] !== data.points[data.points.length-2] || data.points[1] !== data.points[data.points.length-1]) + { data.points.push(data.points[0], data.points[1]); } } // MAKE SURE WE HAVE THE CORRECT TYPE.. - if (data.fill) { - if (data.points.length >= 6) { - if (data.points.length < 6 * 2) { + if (data.fill) + { + if (data.points.length >= 6) + { + if (data.points.length < 6 * 2) + { webGLData = WebGLGraphics.switchMode(webGL, 0); var canDrawUsingSimple = WebGLGraphics.buildPoly(data, webGLData); // console.log(canDrawUsingSimple); - if (!canDrawUsingSimple) { + if (!canDrawUsingSimple) + { // console.log("<>>>") webGLData = WebGLGraphics.switchMode(webGL, 1); WebGLGraphics.buildComplexPoly(data, webGLData); } } - else { + else + { webGLData = WebGLGraphics.switchMode(webGL, 1); WebGLGraphics.buildComplexPoly(data, webGLData); } } } - if (data.lineWidth > 0) { + if (data.lineWidth > 0) + { webGLData = WebGLGraphics.switchMode(webGL, 0); WebGLGraphics.buildLine(data, webGLData); } } - else { + else + { webGLData = WebGLGraphics.switchMode(webGL, 0); - if (data.type === CONST.SHAPES.RECT) { + if (data.type === CONST.SHAPES.RECT) + { WebGLGraphics.buildRectangle(data, webGLData); } - else if (data.type === CONST.SHAPES.CIRC || data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.CIRC || data.type === CONST.SHAPES.ELIP) + { WebGLGraphics.buildCircle(data, webGLData); } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { WebGLGraphics.buildRoundedRectangle(data, webGLData); } } @@ -179,10 +202,12 @@ } // upload all the dirty data... - for (i = 0; i < webGL.data.length; i++) { + for (i = 0; i < webGL.data.length; i++) + { webGLData = webGL.data[i]; - if (webGLData.dirty) { + if (webGLData.dirty) + { webGLData.upload(); } } @@ -194,18 +219,22 @@ * @param webGL {WebGLContext} * @param type {number} */ -WebGLGraphics.switchMode = function (webGL, type) { +WebGLGraphics.switchMode = function (webGL, type) +{ var webGLData; - if (!webGL.data.length) { + if (!webGL.data.length) + { webGLData = WebGLGraphics.graphicsDataPool.pop() || new WebGLGraphicsData(webGL.gl); webGLData.mode = type; webGL.data.push(webGLData); } - else { + else + { webGLData = webGL.data[webGL.data.length-1]; - if (webGLData.mode !== type || type === 1) { + if (webGLData.mode !== type || type === 1) + { webGLData = WebGLGraphics.graphicsDataPool.pop() || new WebGLGraphicsData(webGL.gl); webGLData.mode = type; webGL.data.push(webGLData); @@ -225,7 +254,8 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildRectangle = function (graphicsData, webGLData) { +WebGLGraphics.buildRectangle = function (graphicsData, webGLData) +{ // --- // // need to convert points to a nice regular data // @@ -235,7 +265,8 @@ var width = rectData.width; var height = rectData.height; - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -265,7 +296,8 @@ indices.push(vertPos, vertPos, vertPos+1, vertPos+2, vertPos+3, vertPos+3); } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = [x, y, @@ -289,7 +321,8 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildRoundedRectangle = function (graphicsData, webGLData) { +WebGLGraphics.buildRoundedRectangle = function (graphicsData, webGLData) +{ var rrectData = graphicsData.shape; var x = rrectData.x; var y = rrectData.y; @@ -305,7 +338,8 @@ recPoints = recPoints.concat(WebGLGraphics.quadraticBezierCurve(x + width, y + radius, x + width, y, x + width - radius, y)); recPoints = recPoints.concat(WebGLGraphics.quadraticBezierCurve(x + radius, y, x, y, x, y + radius)); - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -323,7 +357,8 @@ // var i = 0; - for (i = 0; i < triangles.length; i+=3) { + for (i = 0; i < triangles.length; i+=3) + { indices.push(triangles[i] + vecPos); indices.push(triangles[i] + vecPos); indices.push(triangles[i+1] + vecPos); @@ -332,12 +367,14 @@ } - for (i = 0; i < recPoints.length; i++) { + for (i = 0; i < recPoints.length; i++) + { verts.push(recPoints[i], recPoints[++i], r, g, b, alpha); } } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = recPoints; @@ -362,7 +399,8 @@ * @param toY {number} Destination point y * @return {number[]} */ -WebGLGraphics.quadraticBezierCurve = function (fromX, fromY, cpX, cpY, toX, toY) { +WebGLGraphics.quadraticBezierCurve = function (fromX, fromY, cpX, cpY, toX, toY) +{ var xa, ya, @@ -373,14 +411,16 @@ n = 20, points = []; - function getPt(n1 , n2, perc) { + function getPt(n1 , n2, perc) + { var diff = n2 - n1; return n1 + ( diff * perc ); } var j = 0; - for (var i = 0; i <= n; i++ ) { + for (var i = 0; i <= n; i++ ) + { j = i / n; // The Green Line @@ -406,7 +446,8 @@ * @param graphicsData {Graphics} The graphics object to draw * @param webGLData {object} */ -WebGLGraphics.buildCircle = function (graphicsData, webGLData) { +WebGLGraphics.buildCircle = function (graphicsData, webGLData) +{ // need to convert points to a nice regular data var circleData = graphicsData.shape; var x = circleData.x; @@ -415,11 +456,13 @@ var height; // TODO - bit hacky?? - if (graphicsData.type === CONST.SHAPES.CIRC) { + if (graphicsData.type === CONST.SHAPES.CIRC) + { width = circleData.radius; height = circleData.radius; } - else { + else + { width = circleData.width; height = circleData.height; } @@ -429,7 +472,8 @@ var i = 0; - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -444,7 +488,8 @@ indices.push(vecPos); - for (i = 0; i < totalSegs + 1 ; i++) { + for (i = 0; i < totalSegs + 1 ; i++) + { verts.push(x,y, r, g, b, alpha); verts.push(x + Math.sin(seg * i) * width, @@ -457,12 +502,14 @@ indices.push(vecPos-1); } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = []; - for (i = 0; i < totalSegs + 1; i++) { + for (i = 0; i < totalSegs + 1; i++) + { graphicsData.points.push(x + Math.sin(seg * i) * width, y + Math.cos(seg * i) * height); } @@ -481,18 +528,22 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildLine = function (graphicsData, webGLData) { +WebGLGraphics.buildLine = function (graphicsData, webGLData) +{ // TODO OPTIMISE! var i = 0; var points = graphicsData.points; - if (points.length === 0) { + if (points.length === 0) + { return; } // if the line width is an odd number add 0.5 to align to a whole pixel - if (graphicsData.lineWidth%2) { - for (i = 0; i < points.length; i++) { + if (graphicsData.lineWidth%2) + { + for (i = 0; i < points.length; i++) + { points[i] += 0.5; } } @@ -502,7 +553,8 @@ var lastPoint = new math.Point(points[points.length - 2], points[points.length - 1]); // if the first point is the last point - gonna have issues :) - if (firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) { + if (firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) + { // need to clone as we are going to slightly modify the shape.. points = points.slice(); @@ -562,7 +614,8 @@ verts.push(p1x + perpx , p1y + perpy, r, g, b, alpha); - for (i = 1; i < length-1; i++) { + for (i = 1; i < length-1; i++) + { p1x = points[(i-1)*2]; p1y = points[(i-1)*2 + 1]; @@ -599,7 +652,8 @@ denom = a1*b2 - a2*b1; - if (Math.abs(denom) < 0.1 ) { + if (Math.abs(denom) < 0.1 ) + { denom+=10.1; verts.push(p2x - perpx , p2y - perpy, @@ -618,7 +672,8 @@ pdist = (px -p2x) * (px -p2x) + (py -p2y) + (py -p2y); - if (pdist > 140 * 140) { + if (pdist > 140 * 140) + { perp3x = perpx - perp2x; perp3y = perpy - perp2y; @@ -639,7 +694,8 @@ indexCount++; } - else { + else + { verts.push(px , py); verts.push(r, g, b, alpha); @@ -672,7 +728,8 @@ indices.push(indexStart); - for (i = 0; i < indexCount; i++) { + for (i = 0; i < indexCount; i++) + { indices.push(indexStart++); } @@ -687,11 +744,13 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildComplexPoly = function (graphicsData, webGLData) { +WebGLGraphics.buildComplexPoly = function (graphicsData, webGLData) +{ //TODO - no need to copy this as it gets turned into a FLoat32Array anyways.. var points = graphicsData.points.slice(); - if (points.length < 6) { + if (points.length < 6) + { return; } @@ -711,7 +770,8 @@ var x,y; // get size.. - for (var i = 0; i < points.length; i+=2) { + for (var i = 0; i < points.length; i+=2) + { x = points[i]; y = points[i+1]; @@ -732,7 +792,8 @@ //TODO - this aint needed! var length = points.length / 2; - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { indices.push( i ); } @@ -746,10 +807,12 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildPoly = function (graphicsData, webGLData) { +WebGLGraphics.buildPoly = function (graphicsData, webGLData) +{ var points = graphicsData.points; - if (points.length < 6) { + if (points.length < 6) + { return; } // get first and last point.. figure out the middle! @@ -767,7 +830,8 @@ var triangles = utils.PolyK.Triangulate(points); - if (!triangles) { + if (!triangles) + { return false; } @@ -775,7 +839,8 @@ var i = 0; - for (i = 0; i < triangles.length; i+=3) { + for (i = 0; i < triangles.length; i+=3) + { indices.push(triangles[i] + vertPos); indices.push(triangles[i] + vertPos); indices.push(triangles[i+1] + vertPos); @@ -783,7 +848,8 @@ indices.push(triangles[i+2] + vertPos); } - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { verts.push(points[i * 2], points[i * 2 + 1], r, g, b, alpha); } diff --git a/src/core/display/DisplayObject.js b/src/core/display/DisplayObject.js index 66ebc3c..20e778c 100644 --- a/src/core/display/DisplayObject.js +++ b/src/core/display/DisplayObject.js @@ -7,7 +7,8 @@ * @class * @namespace PIXI */ -function DisplayObject() { +function DisplayObject() +{ /** * The coordinate of the object relative to the local coordinates of the parent. * @@ -152,10 +153,12 @@ * @memberof DisplayObject# */ x: { - get: function () { + get: function () + { return this.position.x; }, - set: function (value) { + set: function (value) + { this.position.x = value; } }, @@ -167,10 +170,12 @@ * @memberof DisplayObject# */ y: { - get: function () { + get: function () + { return this.position.y; }, - set: function (value) { + set: function (value) + { this.position.y = value; } }, @@ -183,11 +188,13 @@ * @readonly */ worldVisible: { - get: function () { + get: function () + { var item = this; do { - if (!item.visible) { + if (!item.visible) + { return false; } @@ -207,17 +214,21 @@ * @memberof DisplayObject# */ mask: { - get: function () { + get: function () + { return this._mask; }, - set: function (value) { - if (this._mask) { + set: function (value) + { + if (this._mask) + { this._mask.isMask = false; } this._mask = value; - if (this._mask) { + if (this._mask) + { this._mask.isMask = true; } } @@ -232,18 +243,23 @@ * @memberof DisplayObject# */ filters: { - get: function () { + get: function () + { return this._filters; }, - set: function (value) { - if (value) { + set: function (value) + { + if (value) + { // now put all the passes in one place.. var passes = []; - for (var i = 0; i < value.length; i++) { + for (var i = 0; i < value.length; i++) + { var filterPasses = value[i].passes; - for (var j = 0; j < filterPasses.length; j++) { + for (var j = 0; j < filterPasses.length; j++) + { passes.push(filterPasses[j]); } } @@ -264,8 +280,9 @@ * * @private */ -DisplayObject.prototype.updateTransform = function () { - +DisplayObject.prototype.updateTransform = function () +{ + // create some matrix refs for easy access var pt = this.parent.worldTransform; var wt = this.worldTransform; @@ -274,9 +291,11 @@ var a, b, c, d, tx, ty; // so if rotation is between 0 then we can simplify the multiplication process.. - if (this.rotation % math.PI_2) { + if (this.rotation % math.PI_2) + { // 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) { + if (this.rotation !== this.rotationCache) + { this.rotationCache = this.rotation; this._sr = Math.sin(this.rotation); this._cr = Math.cos(this.rotation); @@ -291,7 +310,8 @@ ty = this.position.y; // check for pivot.. not often used so geared towards that fact! - if (this.pivot.x || this.pivot.y) { + 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; } @@ -304,7 +324,8 @@ wt.tx = tx * pt.a + ty * pt.c + pt.tx; wt.ty = tx * pt.b + ty * pt.d + pt.ty; } - else { + else + { // lets do the fast version as we know there is no rotation.. a = this.scale.x; d = this.scale.y; @@ -333,7 +354,8 @@ * @param matrix {Matrix} * @return {Rectangle} the rectangular bounding area */ -DisplayObject.prototype.getBounds = function (/* matrix */) { +DisplayObject.prototype.getBounds = function (/* matrix */) +{ return math.Rectangle.EMPTY; }; @@ -342,7 +364,8 @@ * * @return {Rectangle} the rectangular bounding area */ -DisplayObject.prototype.getLocalBounds = function () { +DisplayObject.prototype.getLocalBounds = function () +{ return this.getBounds(math.Matrix.IDENTITY); }; @@ -352,7 +375,8 @@ * @param position {Point} The world origin to calculate from * @return {Point} A point object representing the position of this object */ -DisplayObject.prototype.toGlobal = function (position) { +DisplayObject.prototype.toGlobal = function (position) +{ // don't need to u[date the lot this.displayObjectUpdateTransform(); return this.worldTransform.apply(position); @@ -365,8 +389,10 @@ * @param [from] {DisplayObject} The DisplayObject to calculate the global position from * @return {Point} A point object representing the position of this object */ -DisplayObject.prototype.toLocal = function (position, from) { - if (from) { +DisplayObject.prototype.toLocal = function (position, from) +{ + if (from) + { position = from.toGlobal(position); } @@ -381,7 +407,8 @@ * @param renderer {WebGLRenderer} The renderer * @private */ -DisplayObject.prototype.renderWebGL = function (/* renderer */) { +DisplayObject.prototype.renderWebGL = function (/* renderer */) +{ // OVERWRITE; }; @@ -391,6 +418,7 @@ * @param renderer {CanvasRenderer} The renderer * @private */ -DisplayObject.prototype.renderCanvas = function (/* renderer */) { +DisplayObject.prototype.renderCanvas = function (/* renderer */) +{ // OVERWRITE; }; diff --git a/src/core/display/DisplayObjectContainer.js b/src/core/display/DisplayObjectContainer.js index 689f40b..4625ee8 100644 --- a/src/core/display/DisplayObjectContainer.js +++ b/src/core/display/DisplayObjectContainer.js @@ -12,7 +12,8 @@ * @extends DisplayObject * @namespace PIXI */ -function DisplayObjectContainer() { +function DisplayObjectContainer() +{ DisplayObject.call(this); /** @@ -47,17 +48,21 @@ * @memberof DisplayObjectContainer# */ width: { - get: function () { + get: function () + { return this.scale.x * this.getLocalBounds().width; }, - set: function (value) { + set: function (value) + { var width = this.getLocalBounds().width; - if(width !== 0) { + if(width !== 0) + { this.scale.x = value / width; } - else { + else + { this.scale.x = 1; } @@ -73,17 +78,21 @@ * @memberof DisplayObjectContainer# */ height: { - get: function () { + get: function () + { return this.scale.y * this.getLocalBounds().height; }, - set: function (value) { + set: function (value) + { var height = this.getLocalBounds().height; - if (height !== 0) { + if (height !== 0) + { this.scale.y = value / height ; } - else { + else + { this.scale.y = 1; } @@ -100,18 +109,23 @@ * @memberof DisplayObject# */ cacheAsBitmap: { - get: function () { + get: function () + { return this._cacheAsBitmap; }, - set: function (value) { - if (this._cacheAsBitmap === value) { + set: function (value) + { + if (this._cacheAsBitmap === value) + { return; } - if (value) { + if (value) + { this._generateCachedSprite(); } - else { + else + { this._destroyCachedSprite(); } @@ -126,7 +140,8 @@ * @param child {DisplayObject} The DisplayObject to add to the container * @return {DisplayObject} The child that was added. */ -DisplayObjectContainer.prototype.addChild = function (child) { +DisplayObjectContainer.prototype.addChild = function (child) +{ return this.addChildAt(child, this.children.length); }; @@ -137,14 +152,18 @@ * @param index {Number} The index to place the child in * @return {DisplayObject} The child that was added. */ -DisplayObjectContainer.prototype.addChildAt = function (child, index) { +DisplayObjectContainer.prototype.addChildAt = function (child, index) +{ // prevent adding self as child - if (child === this) { + if (child === this) + { return; } - if (index >= 0 && index <= this.children.length) { - if (child.parent) { + if (index >= 0 && index <= this.children.length) + { + if (child.parent) + { child.parent.removeChild(child); } @@ -154,7 +173,8 @@ return child; } - else { + else + { throw new Error(child + 'addChildAt: The index '+ index +' supplied is out of bounds ' + this.children.length); } }; @@ -165,15 +185,18 @@ * @param child {DisplayObject} * @param child2 {DisplayObject} */ -DisplayObjectContainer.prototype.swapChildren = function (child, child2) { - if (child === child2) { +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) { + if (index1 < 0 || index2 < 0) + { throw new Error('swapChildren: Both the supplied DisplayObjects must be a child of the caller.'); } @@ -187,10 +210,12 @@ * @param child {DisplayObject} The DisplayObject instance to identify * @return {Number} The index position of the child display object to identify */ -DisplayObjectContainer.prototype.getChildIndex = function (child) { +DisplayObjectContainer.prototype.getChildIndex = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { throw new Error('The supplied DisplayObject must be a child of the caller'); } @@ -203,8 +228,10 @@ * @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 */ -DisplayObjectContainer.prototype.setChildIndex = function (child, index) { - if (index < 0 || index >= this.children.length) { +DisplayObjectContainer.prototype.setChildIndex = function (child, index) +{ + if (index < 0 || index >= this.children.length) + { throw new Error('The supplied index is out of bounds'); } @@ -220,8 +247,10 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child at the given index, if any. */ -DisplayObjectContainer.prototype.getChildAt = function (index) { - if (index < 0 || index >= this.children.length) { +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'); } @@ -234,10 +263,12 @@ * @param child {DisplayObject} The DisplayObject to remove * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChild = function (child) { +DisplayObjectContainer.prototype.removeChild = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { return; } @@ -250,7 +281,8 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChildAt = function (index) { +DisplayObjectContainer.prototype.removeChildAt = function (index) +{ var child = this.getChildAt(index); child.parent = null; @@ -265,24 +297,29 @@ * @param beginIndex {Number} The beginning position. Default value is 0. * @param endIndex {Number} The ending position. Default value is size of the container. */ -DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) { +DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) +{ var begin = beginIndex || 0; var end = typeof endIndex === 'number' ? endIndex : this.children.length; var range = end - begin; - if (range > 0 && range <= end) { + if (range > 0 && range <= end) + { var removed = this.children.splice(begin, range); - for (var i = 0; i < removed.length; ++i) { + for (var i = 0; i < removed.length; ++i) + { removed[i].parent = null; } return removed; } - else if (range === 0 && this.children.length === 0) { + else if (range === 0 && this.children.length === 0) + { return []; } - else { + else + { throw new RangeError('removeChildren: numeric values are outside the acceptable range.'); } }; @@ -291,7 +328,8 @@ * Generates and updates the cached sprite for this object. * */ -DisplayObjectContainer.prototype.updateCachedSprite = function () { +DisplayObjectContainer.prototype.updateCachedSprite = function () +{ this._generateCachedSprite(); }; @@ -304,7 +342,8 @@ * @param renderer {CanvasRenderer|WebGLRenderer} The renderer used to generate the texture. * @return {Texture} a texture of the graphics object */ -DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) { +DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) +{ var bounds = this.getLocalBounds(); var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0, renderer, scaleMode, resolution); @@ -322,18 +361,22 @@ * * @private */ -DisplayObjectContainer.prototype.updateTransform = function () { - if (!this.visible) { +DisplayObjectContainer.prototype.updateTransform = function () +{ + if (!this.visible) + { return; } this.displayObjectUpdateTransform(); - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { return; } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } }; @@ -346,8 +389,10 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getBounds = function () { - if (this.children.length === 0) { +DisplayObjectContainer.prototype.getBounds = function () +{ + if (this.children.length === 0) + { return math.Rectangle.EMPTY; } @@ -365,10 +410,12 @@ var childVisible = false; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -386,7 +433,8 @@ maxY = maxY > childMaxY ? maxY : childMaxY; } - if (!childVisible) { + if (!childVisible) + { return math.Rectangle.EMPTY; } @@ -407,12 +455,14 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getLocalBounds = function () { +DisplayObjectContainer.prototype.getLocalBounds = function () +{ var matrixCache = this.worldTransform; this.worldTransform = math.Matrix.IDENTITY; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } @@ -428,13 +478,16 @@ * * @param renderer {WebGLRenderer} The renderer */ -DisplayObjectContainer.prototype.renderWebGL = function (renderer) { +DisplayObjectContainer.prototype.renderWebGL = function (renderer) +{ // if the object is not visible or the alpha is 0 then no need to render this element - if (!this.visible || this.alpha <= 0) { + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } @@ -442,14 +495,17 @@ var i, j; // do a quick check to see if this element has a mask or a filter. - if (this._mask || this._filters) { + if (this._mask || this._filters) + { // push filter first as we need to ensure the stencil buffer is correct for any masking - if (this._filters) { + if (this._filters) + { renderer.spriteBatch.flush(); renderer.filterManager.pushFilter(this._filterBlock); } - if (this._mask) { + if (this._mask) + { renderer.spriteBatch.stop(); renderer.maskManager.pushMask(this.mask, renderer); renderer.spriteBatch.start(); @@ -459,36 +515,42 @@ this._renderWebGL(renderer); // now loop through the children and make sure they get rendered - for (i = 0, j = this.children.length; i < j; i++) { + for (i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderWebGL(renderer); } // time to stop the sprite batch as either a mask element or a filter draw will happen next renderer.spriteBatch.stop(); - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(this._mask, renderer); } - if (this._filters) { + if (this._filters) + { renderer.filterManager.popFilter(); } renderer.spriteBatch.start(); } - else { + else + { this._renderWebGL(renderer); // simple render children! - for (i = 0, j = this.children.length; i < j; ++i) { + for (i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderWebGL(renderer); } } }; -DisplayObjectContainer.prototype._renderWebGL = function (renderer) { +DisplayObjectContainer.prototype._renderWebGL = function (renderer) +{ // this is where content itself gets renderd.. @@ -499,25 +561,31 @@ * * @param renderer {CanvasRenderer} The renderer */ -DisplayObjectContainer.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0) { +DisplayObjectContainer.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -528,13 +596,16 @@ * @param renderer {WebGLRenderer|CanvasRenderer} The renderer * @private */ -DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) { +DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) +{ this._cachedSprite.worldAlpha = this.worldAlpha; - if (renderer.gl) { + if (renderer.gl) + { this._cachedSprite.renderWebGL(renderer); } - else { + else + { this._cachedSprite.renderCanvas(renderer); } }; @@ -544,10 +615,12 @@ * * @private */ -DisplayObjectContainer.prototype._generateCachedSprite = function () { +DisplayObjectContainer.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { // TODO - RenderTexture now *requires* a renderer instance, so this is like broken // because `renderer` isn't actually in scope here :P var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0); @@ -555,7 +628,8 @@ this._cachedSprite = new Sprite(renderTexture); this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.texture.resize(bounds.width | 0, bounds.height | 0); } @@ -580,8 +654,10 @@ * * @private */ -DisplayObjectContainer.prototype._destroyCachedSprite = function () { - if (!this._cachedSprite) { +DisplayObjectContainer.prototype._destroyCachedSprite = function () +{ + if (!this._cachedSprite) + { return; } diff --git a/src/core/display/Sprite.js b/src/core/display/Sprite.js index 707da24..5862aef 100644 --- a/src/core/display/Sprite.js +++ b/src/core/display/Sprite.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param texture {Texture} The texture for this sprite */ -function Sprite(texture) { +function Sprite(texture) +{ DisplayObjectContainer.call(this); /** @@ -85,12 +86,14 @@ this.texture = texture || Texture.EMPTY; } -Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) { +Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) +{ DisplayObjectContainer.prototype.destroy.call(this); this.anchor = null; - if (destroyTexture) { + if (destroyTexture) + { this._texture.destroy(destroyBaseTexture); } @@ -111,10 +114,12 @@ * @memberof Sprite# */ width: { - get: function () { + get: function () + { return this.scale.x * this.texture.frame.width; }, - set: function (value) { + set: function (value) + { this.scale.x = value / this.texture.frame.width; this._width = value; } @@ -127,10 +132,12 @@ * @memberof Sprite# */ height: { - get: function () { + get: function () + { return this.scale.y * this.texture.frame.height; }, - set: function (value) { + set: function (value) + { this.scale.y = value / this.texture.frame.height; this._height = value; } @@ -143,23 +150,29 @@ * @memberof Sprite# */ texture: { - get: function () { + get: function () + { return this._texture; }, - set: function (value) { - if (this._texture === value) { + set: function (value) + { + if (this._texture === value) + { return; } this._texture = value; this.cachedTint = 0xFFFFFF; - if (value) { + if (value) + { // wait for the texture to load - if (value.baseTexture.hasLoaded) { + if (value.baseTexture.hasLoaded) + { this._onTextureUpdate(); } - else { + else + { value.once('update', this._onTextureUpdate.bind(this)); } } @@ -172,18 +185,22 @@ * * @private */ -Sprite.prototype._onTextureUpdate = function () { +Sprite.prototype._onTextureUpdate = function () +{ // so if _width is 0 then width was not set.. - if (this._width) { + if (this._width) + { this.scale.x = this._width / this.texture.frame.width; } - if (this._height) { + if (this._height) + { this.scale.y = this._height / this.texture.frame.height; } }; -Sprite.prototype._renderWebGL = function (renderer) { +Sprite.prototype._renderWebGL = function (renderer) +{ // this is where content gets renderd.. // watch this space for a little render state manager.. @@ -197,7 +214,8 @@ * @param matrix {Matrix} the transformation matrix of the sprite * @return {Rectangle} the framing rectangle */ -Sprite.prototype.getBounds = function (matrix) { +Sprite.prototype.getBounds = function (matrix) +{ var width = this.texture.frame.width; var height = this.texture.frame.height; @@ -224,11 +242,13 @@ if(b === 0 && c === 0) { // scale may be negative! - if (a < 0) { + if (a < 0) + { a *= -1; } - if (d < 0) { + if (d < 0) + { d *= -1; } @@ -293,28 +313,34 @@ * * @param renderer {CanvasRenderer} The renderer */ -Sprite.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) { +Sprite.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) + { return; } - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; renderer.context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } // Ignore null sources - if (this.texture.valid) { + if (this.texture.valid) + { var resolution = this.texture.baseTexture.resolution / renderer.resolution; renderer.context.globalAlpha = this.worldAlpha; // If smoothingEnabled is supported and we need to change the smoothing property for this texture - if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) { + if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) + { renderer.scaleMode = this.texture.baseTexture.scaleMode; renderer.context[renderer.smoothProperty] = (renderer.scaleMode === CONST.scaleModes.LINEAR); } @@ -324,7 +350,8 @@ var dy = (this.texture.trim ? this.texture.trim.y : 0) - (this.anchor.y * this.texture.trim.height); // Allow for pixel rounding - if (renderer.roundPixels) { + if (renderer.roundPixels) + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -337,7 +364,8 @@ dx = dx | 0; dy = dy | 0; } - else { + else + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -348,8 +376,10 @@ ); } - if (this.tint !== 0xFFFFFF) { - if (this.cachedTint !== this.tint) { + if (this.tint !== 0xFFFFFF) + { + if (this.cachedTint !== this.tint) + { this.cachedTint = this.tint; // TODO clean up caching - how to clean up the caches? @@ -368,7 +398,8 @@ this.texture.crop.height / resolution ); } - else { + else + { renderer.context.drawImage( this.texture.baseTexture.source, this.texture.crop.x, @@ -383,11 +414,13 @@ } } - for (var i = 0, j = this.children.length; i < j; i++) { + for (var i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -402,10 +435,12 @@ * @param frameId {String} The frame Id of the texture in the cache * @return {Sprite} A new Sprite using a texture from the texture cache matching the frameId */ -Sprite.fromFrame = function (frameId) { +Sprite.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache' + this); } @@ -420,6 +455,7 @@ * @param imageId {String} The image url of the texture * @return {Sprite} A new Sprite using a texture from the texture cache matching the image id */ -Sprite.fromImage = function (imageId, crossorigin, scaleMode) { +Sprite.fromImage = function (imageId, crossorigin, scaleMode) +{ return new Sprite(Texture.fromImage(imageId, crossorigin, scaleMode)); }; diff --git a/src/core/display/SpriteBatch.js b/src/core/display/SpriteBatch.js index 3187777..c196fef 100644 --- a/src/core/display/SpriteBatch.js +++ b/src/core/display/SpriteBatch.js @@ -12,7 +12,8 @@ * ```js * var container = new SpriteBatch(); * - * for(var i = 0; i < 100; ++i) { + * for(var i = 0; i < 100; ++i) + * { * var sprite = new PIXI.Sprite.fromImage("myImage.png"); * container.addChild(sprite); * } @@ -25,7 +26,8 @@ */ //TODO RENAME to PARTICLE CONTAINER? -function SpriteBatch() { +function SpriteBatch() +{ DisplayObjectContainer.call(this); } @@ -38,7 +40,8 @@ * * @private */ -SpriteBatch.prototype.updateTransform = function () { +SpriteBatch.prototype.updateTransform = function () +{ // TODO don't need to! this.displayObjectUpdateTransform(); // PIXI.DisplayObjectContainer.prototype.updateTransform.call( this ); @@ -50,8 +53,10 @@ * @param renderer {WebGLRenderer} The webgl renderer * @private */ -SpriteBatch.prototype.renderWebGL = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderWebGL = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -71,8 +76,10 @@ * @param renderer {CanvasRenderer} The canvas renderer * @private */ -SpriteBatch.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -84,10 +91,12 @@ this.displayObjectUpdateTransform(); - for (var i = 0; i < this.children.length; ++i) { + for (var i = 0; i < this.children.length; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -95,9 +104,11 @@ context.globalAlpha = this.worldAlpha * child.alpha; - if (child.rotation % (Math.PI * 2) === 0) { + if (child.rotation % (Math.PI * 2) === 0) + { // this is the fastest way to optimise! - if rotation is 0 then we can avoid any kind of setTransform call - if (isRotated) { + if (isRotated) + { context.setTransform( transform.a, transform.b, @@ -122,8 +133,10 @@ frame.height * child.scale.y ); } - else { - if (!isRotated) { + else + { + if (!isRotated) + { isRotated = true; } @@ -131,7 +144,8 @@ var childTransform = child.worldTransform; - if (renderer.roundPixels) { + if (renderer.roundPixels) + { context.setTransform( childTransform.a, childTransform.b, @@ -141,7 +155,8 @@ childTransform.ty | 0 ); } - else { + else + { context.setTransform( childTransform.a, childTransform.b, diff --git a/src/core/index.js b/src/core/index.js index 3954b6f..eb4a82b 100644 --- a/src/core/index.js +++ b/src/core/index.js @@ -58,11 +58,13 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRenderer: function (width, height, options, noWebGL) { + autoDetectRenderer: function (width, height, options, noWebGL) + { width = width || 800; height = height || 600; - if (!noWebGL && require('webgl-enabled')()) { + if (!noWebGL && require('webgl-enabled')()) + { return new core.WebGLRenderer(width, height, options); } @@ -87,7 +89,8 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRecommendedRenderer: function (width, height, options) { + autoDetectRecommendedRenderer: function (width, height, options) + { var isAndroid = /Android/i.test(navigator.userAgent); return core.autoDetectRenderer(width, height, options, isAndroid); diff --git a/src/core/math/Matrix.js b/src/core/math/Matrix.js index c2f87e2..2ff4848 100644 --- a/src/core/math/Matrix.js +++ b/src/core/math/Matrix.js @@ -10,7 +10,8 @@ * @class * @namespace PIXI */ -function Matrix() { +function Matrix() +{ /** * @member {number} * @default 1 @@ -63,7 +64,8 @@ * * @param array {number[]} The array that the matrix will be populated from. */ -Matrix.prototype.fromArray = function (array) { +Matrix.prototype.fromArray = function (array) +{ this.a = array[0]; this.b = array[1]; this.c = array[3]; @@ -78,14 +80,17 @@ * @param transpose {boolean} Whether we need to transpose the matrix or not * @return {number[]} the newly created array which contains the matrix */ -Matrix.prototype.toArray = function (transpose) { - if (!this.array) { +Matrix.prototype.toArray = function (transpose) +{ + if (!this.array) + { this.array = new Float32Array(9); } var array = this.array; - if (transpose) { + if (transpose) + { array[0] = this.a; array[1] = this.b; array[2] = 0; @@ -96,7 +101,8 @@ array[7] = this.ty; array[8] = 1; } - else { + else + { array[0] = this.a; array[1] = this.c; array[2] = this.tx; @@ -119,7 +125,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, transformed through this matrix */ -Matrix.prototype.apply = function (pos, newPos) { +Matrix.prototype.apply = function (pos, newPos) +{ newPos = newPos || new Point(); newPos.x = this.a * pos.x + this.c * pos.y + this.tx; @@ -136,7 +143,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, inverse-transformed through this matrix */ -Matrix.prototype.applyInverse = function (pos, newPos) { +Matrix.prototype.applyInverse = function (pos, newPos) +{ newPos = newPos || new Point(); var id = 1 / (this.a * this.d + this.c * -this.b); @@ -154,7 +162,8 @@ * @param {number} y * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.translate = function (x, y) { +Matrix.prototype.translate = function (x, y) +{ this.tx += x; this.ty += y; @@ -168,7 +177,8 @@ * @param {number} y The amount to scale vertically * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.scale = function (x, y) { +Matrix.prototype.scale = function (x, y) +{ this.a *= x; this.d *= y; this.c *= x; @@ -186,7 +196,8 @@ * @param {number} angle - The angle in radians. * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.rotate = function (angle) { +Matrix.prototype.rotate = function (angle) +{ var cos = Math.cos( angle ); var sin = Math.sin( angle ); @@ -210,7 +221,8 @@ * @param {Matrix} matrix * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.append = function (matrix) { +Matrix.prototype.append = function (matrix) +{ var a1 = this.a; var b1 = this.b; var c1 = this.c; @@ -232,7 +244,8 @@ * * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.identity = function () { +Matrix.prototype.identity = function () +{ this.a = 1; this.b = 0; this.c = 0; diff --git a/src/core/math/Point.js b/src/core/math/Point.js index 7565b2d..632f346 100644 --- a/src/core/math/Point.js +++ b/src/core/math/Point.js @@ -7,7 +7,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -function Point(x, y) { +function Point(x, y) +{ /** * @member {number} * @default 0 @@ -29,7 +30,8 @@ * * @return {Point} a copy of the point */ -Point.prototype.clone = function () { +Point.prototype.clone = function () +{ return new Point(this.x, this.y); }; @@ -40,7 +42,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -Point.prototype.set = function (x, y) { +Point.prototype.set = function (x, y) +{ this.x = x || 0; this.y = y || ( (y !== 0) ? this.x : 0 ) ; }; diff --git a/src/core/math/shapes/Circle.js b/src/core/math/shapes/Circle.js index 69cfdc9..4d76efc 100644 --- a/src/core/math/shapes/Circle.js +++ b/src/core/math/shapes/Circle.js @@ -10,7 +10,8 @@ * @param y {number} The Y coordinate of the center of this circle * @param radius {number} The radius of the circle */ -function Circle(x, y, radius) { +function Circle(x, y, radius) +{ /** * @member {number} * @default 0 @@ -46,7 +47,8 @@ * @method clone * @return {Circle} a copy of the Circle */ -Circle.prototype.clone = function () { +Circle.prototype.clone = function () +{ return new Circle(this.x, this.y, this.radius); }; @@ -58,8 +60,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Circle */ -Circle.prototype.contains = function (x, y) { - if (this.radius <= 0) { +Circle.prototype.contains = function (x, y) +{ + if (this.radius <= 0) + { return false; } @@ -79,6 +83,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Circle.prototype.getBounds = function () { +Circle.prototype.getBounds = function () +{ return new Rectangle(this.x - this.radius, this.y - this.radius, this.radius * 2, this.radius * 2); }; diff --git a/src/core/math/shapes/Ellipse.js b/src/core/math/shapes/Ellipse.js index 4f2d066..fefd01a 100644 --- a/src/core/math/shapes/Ellipse.js +++ b/src/core/math/shapes/Ellipse.js @@ -11,7 +11,8 @@ * @param width {number} The half width of this ellipse * @param height {number} The half height of this ellipse */ -function Ellipse(x, y, width, height) { +function Ellipse(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -53,7 +54,8 @@ * @method clone * @return {Ellipse} a copy of the ellipse */ -Ellipse.prototype.clone = function () { +Ellipse.prototype.clone = function () +{ return new Ellipse(this.x, this.y, this.width, this.height); }; @@ -65,8 +67,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coords are within this ellipse */ -Ellipse.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Ellipse.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } @@ -86,6 +90,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Ellipse.prototype.getBounds = function () { +Ellipse.prototype.getBounds = function () +{ return new Rectangle(this.x - this.width, this.y - this.height, this.width, this.height); }; diff --git a/src/core/math/shapes/Polygon.js b/src/core/math/shapes/Polygon.js index ae89148..fea6d37 100644 --- a/src/core/math/shapes/Polygon.js +++ b/src/core/math/shapes/Polygon.js @@ -10,16 +10,20 @@ * arguments passed can be flat x,y values e.g. `new Polygon(x,y, x,y, x,y, ...)` where `x` and `y` are * Numbers. */ -function Polygon(points) { +function Polygon(points) +{ //if points isn't an array, use arguments as the array - if (!(points instanceof Array)) { + if (!(points instanceof Array)) + { points = Array.prototype.slice.call(arguments); } //if this is a flat array of numbers, convert it to points - if (points[0] instanceof Point) { + if (points[0] instanceof Point) + { var p = []; - for (var i = 0, il = points.length; i < il; i++) { + for (var i = 0, il = points.length; i < il; i++) + { p.push(points[i].x, points[i].y); } @@ -51,7 +55,8 @@ * * @return {Polygon} a copy of the polygon */ -Polygon.prototype.clone = function () { +Polygon.prototype.clone = function () +{ return new Polygon(this.points.slice()); }; @@ -62,19 +67,22 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this polygon */ -Polygon.prototype.contains = function (x, y) { +Polygon.prototype.contains = function (x, y) +{ var inside = false; // use some raycasting to test hits // https://github.com/substack/point-in-polygon/blob/master/index.js var length = this.points.length / 2; - for (var i = 0, j = length - 1; i < length; j = i++) { + for (var i = 0, j = length - 1; i < length; j = i++) + { var xi = this.points[i * 2], yi = this.points[i * 2 + 1], xj = this.points[j * 2], yj = this.points[j * 2 + 1], intersect = ((yi > y) !== (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi); - if (intersect) { + if (intersect) + { inside = !inside; } } diff --git a/src/core/math/shapes/Rectangle.js b/src/core/math/shapes/Rectangle.js index 16ac62a..4008b68 100644 --- a/src/core/math/shapes/Rectangle.js +++ b/src/core/math/shapes/Rectangle.js @@ -10,7 +10,8 @@ * @param width {number} The overall width of this rectangle * @param height {number} The overall height of this rectangle */ -function Rectangle(x, y, width, height) { +function Rectangle(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -60,7 +61,8 @@ * * @return {Rectangle} a copy of the rectangle */ -Rectangle.prototype.clone = function () { +Rectangle.prototype.clone = function () +{ return new Rectangle(this.x, this.y, this.width, this.height); }; @@ -71,13 +73,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rectangle */ -Rectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Rectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/math/shapes/RoundedRectangle.js b/src/core/math/shapes/RoundedRectangle.js index 27d286e..7bf6411 100644 --- a/src/core/math/shapes/RoundedRectangle.js +++ b/src/core/math/shapes/RoundedRectangle.js @@ -11,7 +11,8 @@ * @param height {number} The overall height of this rounded rectangle * @param radius {number} Controls the radius of the rounded corners */ -function RoundedRectangle(x, y, width, height, radius) { +function RoundedRectangle(x, y, width, height, radius) +{ /** * @member {number} * @default 0 @@ -58,7 +59,8 @@ * * @return {RoundedRectangle} a copy of the rounded rectangle */ -RoundedRectangle.prototype.clone = function () { +RoundedRectangle.prototype.clone = function () +{ return new RoundedRectangle(this.x, this.y, this.width, this.height, this.radius); }; @@ -69,13 +71,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rounded Rectangle */ -RoundedRectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +RoundedRectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/primitives/Graphics.js b/src/core/primitives/Graphics.js index 261c534..e902d2a 100644 --- a/src/core/primitives/Graphics.js +++ b/src/core/primitives/Graphics.js @@ -16,7 +16,8 @@ * @extends DisplayObjectContainer * @namespace PIXI */ -function Graphics() { +function Graphics() +{ DisplayObjectContainer.call(this); this.renderable = true; @@ -154,16 +155,20 @@ * @private */ cacheAsBitmap: { - get: function () { + get: function () + { return this._cacheAsBitmap; }, - set: function (value) { + set: function (value) + { this._cacheAsBitmap = value; - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._generateCachedSprite(); } - else { + else + { this.destroyCachedSprite(); this.dirty = true; } @@ -176,7 +181,8 @@ * * @return {Graphics} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ var clone = new Graphics(); clone.renderable = this.renderable; @@ -192,7 +198,8 @@ clone.cachedSpriteDirty = this.cachedSpriteDirty; // copy graphics data - for (var i = 0; i < this.graphicsData.length; ++i) { + for (var i = 0; i < this.graphicsData.length; ++i) + { clone.graphicsData.push(this.graphicsData.clone()); } @@ -211,17 +218,21 @@ * @param alpha {number} alpha of the line to draw, will update the objects stored style * @return {Graphics} */ -Graphics.prototype.lineStyle = function (lineWidth, color, alpha) { +Graphics.prototype.lineStyle = function (lineWidth, color, alpha) +{ this.lineWidth = lineWidth || 0; this.lineColor = color || 0; this.lineAlpha = (arguments.length < 3) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length) + { // halfway through a line? start a new one! this.drawShape( new math.Polygon( this.currentPath.shape.points.slice(-2) )); } - else { + else + { // otherwise its empty so lets just set the line properties this.currentPath.lineWidth = this.lineWidth; this.currentPath.lineColor = this.lineColor; @@ -239,7 +250,8 @@ * @param y {number} the Y coordinate to move to * @return {Graphics} */ -Graphics.prototype.moveTo = function (x, y) { +Graphics.prototype.moveTo = function (x, y) +{ this.drawShape(new math.Polygon([x,y])); return this; @@ -253,7 +265,8 @@ * @param y {number} the Y coordinate to draw to * @return {Graphics} */ -Graphics.prototype.lineTo = function (x, y) { +Graphics.prototype.lineTo = function (x, y) +{ this.currentPath.shape.points.push(x, y); this.dirty = true; @@ -270,13 +283,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -285,7 +302,8 @@ n = 20, points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { this.moveTo(0, 0); } @@ -293,7 +311,8 @@ var fromY = points[points.length-1]; var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; xa = fromX + ( (cpX - fromX) * j ); @@ -319,13 +338,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -342,7 +365,8 @@ var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; dt = (1 - j); @@ -373,13 +397,17 @@ * @param radius {number} The radius of the arc * @return {Graphics} */ -Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points.push(x1, y1); } } - else { + else + { this.moveTo(x1, y1); } @@ -392,12 +420,15 @@ b2 = x2 - x1, mm = Math.abs(a1 * b2 - b1 * a2); - if (mm < 1.0e-8 || radius === 0) { - if (points[points.length-2] !== x1 || points[points.length-1] !== y1) { + if (mm < 1.0e-8 || radius === 0) + { + if (points[points.length-2] !== x1 || points[points.length-1] !== y1) + { points.push(x1, y1); } } - else { + else + { var dd = a1 * a1 + b1 * b1, cc = a2 * a2 + b2 * b2, tt = a1 * a2 + b1 * b2, @@ -433,42 +464,51 @@ * @param anticlockwise {boolean} Optional. Specifies whether the drawing should be counterclockwise or clockwise. False is default, and indicates clockwise, while true indicates counter-clockwise. * @return {Graphics} */ -Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) { +Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) +{ var startX = cx + Math.cos(startAngle) * radius; var startY = cy + Math.sin(startAngle) * radius; var points; // TODO - This if-else makes no sense. It uses currentPath in the else where it doesn't exist... - if (this.currentPath) { + if (this.currentPath) + { points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { points.push(startX, startY); } - else if (points[points.length-2] !== startX || points[points.length-1] !== startY) { + else if (points[points.length-2] !== startX || points[points.length-1] !== startY) + { points.push(startX, startY); } } - else { + else + { this.moveTo(startX, startY); points = this.currentPath.shape.points; } - if (startAngle === endAngle) { + if (startAngle === endAngle) + { return this; } - if (!anticlockwise && endAngle <= startAngle) { + if (!anticlockwise && endAngle <= startAngle) + { endAngle += Math.PI * 2; } - else if (anticlockwise && startAngle <= endAngle) { + else if (anticlockwise && startAngle <= endAngle) + { startAngle += Math.PI * 2; } var sweep = anticlockwise ? (startAngle - endAngle) *-1 : (endAngle - startAngle); var segs = (Math.abs(sweep)/ (Math.PI * 2)) * 40; - if (sweep === 0) { + if (sweep === 0) + { return this; } @@ -482,7 +522,8 @@ var remainder = ( segMinus % 1 ) / segMinus; - for (var i = 0; i <= segMinus; ++i) { + for (var i = 0; i <= segMinus; ++i) + { var real = i + remainder * i; var angle = ((theta) + startAngle + (theta2 * real)); @@ -506,13 +547,16 @@ * @param alpha {number} the alpha of the fill * @return {Graphics} */ -Graphics.prototype.beginFill = function (color, alpha) { +Graphics.prototype.beginFill = function (color, alpha) +{ this.filling = true; this.fillColor = color || 0; this.fillAlpha = (alpha === undefined) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length <= 2) + { this.currentPath.fill = this.filling; this.currentPath.fillColor = this.fillColor; this.currentPath.fillAlpha = this.fillAlpha; @@ -526,7 +570,8 @@ * * @return {Graphics} */ -Graphics.prototype.endFill = function () { +Graphics.prototype.endFill = function () +{ this.filling = false; this.fillColor = null; this.fillAlpha = 1; @@ -542,7 +587,8 @@ * @param height {number} The height of the rectangle * @return {Graphics} */ -Graphics.prototype.drawRect = function ( x, y, width, height ) { +Graphics.prototype.drawRect = function ( x, y, width, height ) +{ this.drawShape(new math.Rectangle(x,y, width, height)); return this; @@ -556,7 +602,8 @@ * @param height {number} The height of the rectangle * @param radius {number} Radius of the rectangle corners */ -Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) { +Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) +{ this.drawShape(new math.RoundedRectangle(x, y, width, height, radius)); return this; @@ -570,7 +617,8 @@ * @param radius {number} The radius of the circle * @return {Graphics} */ -Graphics.prototype.drawCircle = function (x, y, radius) { +Graphics.prototype.drawCircle = function (x, y, radius) +{ this.drawShape(new math.Circle(x,y, radius)); return this; @@ -585,7 +633,8 @@ * @param height {number} The half height of the ellipse * @return {Graphics} */ -Graphics.prototype.drawEllipse = function (x, y, width, height) { +Graphics.prototype.drawEllipse = function (x, y, width, height) +{ this.drawShape(new math.Ellipse(x, y, width, height)); return this; @@ -597,8 +646,10 @@ * @param path {Array} The path data used to construct the polygon. * @return {Graphics} */ -Graphics.prototype.drawPolygon = function (path) { - if (!(path instanceof Array)) { +Graphics.prototype.drawPolygon = function (path) +{ + if (!(path instanceof Array)) + { path = Array.prototype.slice.call(arguments); } @@ -612,7 +663,8 @@ * * @return {Graphics} */ -Graphics.prototype.clear = function () { +Graphics.prototype.clear = function () +{ this.lineWidth = 0; this.filling = false; @@ -631,7 +683,8 @@ * @param scaleMode {number} Should be one of the scaleMode consts * @return {Texture} a texture of the graphics object */ -Graphics.prototype.generateTexture = function (resolution, scaleMode) { +Graphics.prototype.generateTexture = function (resolution, scaleMode) +{ resolution = resolution || 1; var bounds = this.getBounds(); @@ -655,17 +708,21 @@ * * @param renderer {WebGLRenderer} */ -Graphics.prototype._renderWebGL = function (renderer) { +Graphics.prototype._renderWebGL = function (renderer) +{ // if the sprite is not visible or the alpha is 0 then no need to render this element - if (this.isMask === true) { + if (this.isMask === true) + { return; } // this code may still be needed so leaving for now.. - // + // /* - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture on the gpu too! @@ -681,17 +738,24 @@ return; } - */ - - // check if the webgl graphic needs to be updated - if (this.glDirty) { - this.dirty = true; - this.glDirty = false; - } + else */ - renderer.setObjectRendererer(renderer.graphicsRenderer); - renderer.graphicsRenderer.render(this); + renderer.spriteBatch.stop(); + renderer.blendModeManager.setBlendMode(this.blendMode); + // check blend mode + renderer.blendModeManager.setBlendMode( this.blendMode ); + + // check if the webgl graphic needs to be updated + if (this.glDirty) + { + this.dirty = true; + this.glDirty = false; + } + + WebGLGraphics.renderGraphics(this, renderer); + + renderer.spriteBatch.start(); }; /** @@ -700,14 +764,18 @@ * @param renderer {CanvasRenderer} * @private */ -Graphics.prototype.renderCanvas = function (renderer) { +Graphics.prototype.renderCanvas = function (renderer) +{ // 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.isMask === true) { + if (!this.visible || this.alpha <= 0 || this.isMask === true) + { return; } - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture @@ -723,16 +791,19 @@ return; } - else { + else + { var context = renderer.context; var transform = this.worldTransform; - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } @@ -748,11 +819,13 @@ CanvasGraphics.renderGraphics(this, context); - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } } @@ -763,13 +836,16 @@ * * @return {Rectangle} the rectangular bounding area */ -Graphics.prototype.getBounds = function (matrix) { +Graphics.prototype.getBounds = function (matrix) +{ // return an empty object if the item is a mask! - if (this.isMask) { + if (this.isMask) + { return math.Rectangle.EMPTY; } - if (this.dirty) { + if (this.dirty) + { this.updateLocalBounds(); this.glDirty = true; @@ -841,23 +917,27 @@ * Update the bounds of the object * */ -Graphics.prototype.updateLocalBounds = function () { +Graphics.prototype.updateLocalBounds = function () +{ var minX = Infinity; var maxX = -Infinity; var minY = Infinity; var maxY = -Infinity; - if (this.graphicsData.length) { + if (this.graphicsData.length) + { var shape, points, x, y, w, h; - for (var i = 0; i < this.graphicsData.length; i++) { + for (var i = 0; i < this.graphicsData.length; i++) + { var data = this.graphicsData[i]; var type = data.type; var lineWidth = data.lineWidth; shape = data.shape; - if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) { + if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) + { x = shape.x - lineWidth/2; y = shape.y - lineWidth/2; w = shape.width + lineWidth; @@ -869,7 +949,8 @@ minY = y < minY ? y : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.CIRC) { + else if (type === CONST.SHAPES.CIRC) + { x = shape.x; y = shape.y; w = shape.radius + lineWidth/2; @@ -881,7 +962,8 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.ELIP) { + else if (type === CONST.SHAPES.ELIP) + { x = shape.x; y = shape.y; w = shape.width + lineWidth/2; @@ -893,11 +975,13 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else { + else + { // POLY points = shape.points; - for (var j = 0; j < points.length; j += 2) { + for (var j = 0; j < points.length; j += 2) + { x = points[j]; y = points[j+1]; @@ -910,7 +994,8 @@ } } } - else { + else + { minX = 0; maxX = 0; minY = 0; @@ -931,10 +1016,12 @@ * * @private */ -Graphics.prototype._generateCachedSprite = function () { +Graphics.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { var canvasBuffer = new CanvasBuffer(bounds.width, bounds.height); var texture = Texture.fromCanvas(canvasBuffer.canvas); @@ -943,7 +1030,8 @@ this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.buffer.resize(bounds.width, bounds.height); } @@ -968,7 +1056,8 @@ * * @private */ -Graphics.prototype.updateCachedSpriteTexture = function () { +Graphics.prototype.updateCachedSpriteTexture = function () +{ var cachedSprite = this._cachedSprite; var texture = cachedSprite.texture; var canvas = cachedSprite.buffer.canvas; @@ -989,7 +1078,8 @@ * Destroys a previous cached sprite. * */ -Graphics.prototype.destroyCachedSprite = function () { +Graphics.prototype.destroyCachedSprite = function () +{ this._cachedSprite.texture.destroy(true); // let the gc collect the unused sprite @@ -1003,10 +1093,13 @@ * @param {Circle|Rectangle|Ellipse|Line|Polygon} shape The Shape object to draw. * @return {GraphicsData} The generated GraphicsData object. */ -Graphics.prototype.drawShape = function (shape) { - if (this.currentPath) { +Graphics.prototype.drawShape = function (shape) +{ + if (this.currentPath) + { // check current path! - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath.shape.points.length <= 2) + { this.graphicsData.pop(); } } @@ -1017,7 +1110,8 @@ this.graphicsData.push(data); - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { data.shape.closed = this.filling; this.currentPath = data; } diff --git a/src/core/primitives/GraphicsData.js b/src/core/primitives/GraphicsData.js index 99decbe..788f6f2 100644 --- a/src/core/primitives/GraphicsData.js +++ b/src/core/primitives/GraphicsData.js @@ -4,7 +4,8 @@ * @class * @namespace PIXI */ -function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) { +function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) +{ this.lineWidth = lineWidth; this.lineColor = lineColor; this.lineAlpha = lineAlpha; @@ -27,7 +28,8 @@ * * @return {GraphicsData} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ return new GraphicsData( this.lineWidth, this.lineColor, diff --git a/src/core/renderers/canvas/CanvasRenderer.js b/src/core/renderers/canvas/CanvasRenderer.js index 15a0978..7aebd44 100644 --- a/src/core/renderers/canvas/CanvasRenderer.js +++ b/src/core/renderers/canvas/CanvasRenderer.js @@ -17,17 +17,22 @@ * @param [options.resolution=1] {number} the resolution of the renderer retina would be 2 * @param [options.clearBeforeRender=true] {boolean} This sets if the CanvasRenderer will clear the canvas or not before the new render pass. */ -function CanvasRenderer(width, height, options) { +function CanvasRenderer(width, height, options) +{ utils.sayHello('Canvas'); - if (options) { - for (var i in CONST.defaultRenderOptions) { - if (typeof options[i] === 'undefined') { + if (options) + { + for (var i in CONST.defaultRenderOptions) + { + if (typeof options[i] === 'undefined') + { options[i] = CONST.defaultRenderOptions[i]; } } } - else { + else + { options = CONST.defaultRenderOptions; } @@ -156,19 +161,24 @@ this.smoothProperty = null; - if (this.context.imageSmoothingEnabled) { + if (this.context.imageSmoothingEnabled) + { this.smoothProperty = 'imageSmoothingEnabled'; } - else if (this.context.webkitImageSmoothingEnabled) { + else if (this.context.webkitImageSmoothingEnabled) + { this.smoothProperty = 'webkitImageSmoothingEnabled'; } - else if (this.context.mozImageSmoothingEnabled) { + else if (this.context.mozImageSmoothingEnabled) + { this.smoothProperty = 'mozImageSmoothingEnabled'; } - else if (this.context.oImageSmoothingEnabled) { + else if (this.context.oImageSmoothingEnabled) + { this.smoothProperty = 'oImageSmoothingEnabled'; } - else if (this.context.msImageSmoothingEnabled) { + else if (this.context.msImageSmoothingEnabled) + { this.smoothProperty = 'msImageSmoothingEnabled'; } @@ -193,10 +203,12 @@ * @memberof CanvasRenderer# */ backgroundColor: { - get: function () { + get: function () + { return this._backgroundColor; }, - set: function (val) { + set: function (val) + { this._backgroundColor = val; this._backgroundColorString = utils.hex2string(val); } @@ -208,7 +220,8 @@ * * @param object {DisplayObject} the object to be rendered */ -CanvasRenderer.prototype.render = function (object) { +CanvasRenderer.prototype.render = function (object) +{ object.updateTransform(); this.context.setTransform(1,0,0,1,0,0); @@ -218,16 +231,20 @@ this.currentBlendMode = CONST.blendModes.NORMAL; this.context.globalCompositeOperation = this.blendModes[CONST.blendModes.NORMAL]; - if (navigator.isCocoonJS && this.view.screencanvas) { + if (navigator.isCocoonJS && this.view.screencanvas) + { this.context.fillStyle = 'black'; this.context.clear(); } - if (this.clearBeforeRender) { - if (this.transparent) { + if (this.clearBeforeRender) + { + if (this.transparent) + { this.context.clearRect(0, 0, this.width, this.height); } - else { + else + { this.context.fillStyle = this._backgroundColorString; this.context.fillRect(0, 0, this.width , this.height); } @@ -241,8 +258,10 @@ * * @param [removeView=false] {boolean} Removes the Canvas element from the DOM. */ -CanvasRenderer.prototype.destroy = function (removeView) { - if (removeView && this.view.parent) { +CanvasRenderer.prototype.destroy = function (removeView) +{ + if (removeView && this.view.parent) + { this.view.parent.removeChild(this.view); } @@ -257,14 +276,16 @@ * @param width {number} the new width of the canvas view * @param height {number} the new height of the canvas view */ -CanvasRenderer.prototype.resize = function (width, height) { +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) { + if (this.autoResize) + { this.view.style.width = this.width / this.resolution + 'px'; this.view.style.height = this.height / this.resolution + 'px'; } @@ -276,7 +297,8 @@ * @param displayObject {DisplayObject} The displayObject to render * @private */ -CanvasRenderer.prototype.renderDisplayObject = function (displayObject) { +CanvasRenderer.prototype.renderDisplayObject = function (displayObject) +{ displayObject.renderCanvas(this); }; @@ -285,11 +307,14 @@ * * @private */ -CanvasRenderer.prototype._mapBlendModes = function () { - if (!this.blendModes) { +CanvasRenderer.prototype._mapBlendModes = function () +{ + if (!this.blendModes) + { this.blendModes = {}; - if (utils.canUseNewCanvasBlendModes()) { + if (utils.canUseNewCanvasBlendModes()) + { this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? this.blendModes[CONST.blendModes.MULTIPLY] = 'multiply'; @@ -308,7 +333,8 @@ this.blendModes[CONST.blendModes.COLOR] = 'color'; this.blendModes[CONST.blendModes.LUMINOSITY] = 'luminosity'; } - else { + else + { // this means that the browser does not support the cool new blend modes in canvas 'cough' ie 'cough' this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? diff --git a/src/core/renderers/canvas/utils/CanvasBuffer.js b/src/core/renderers/canvas/utils/CanvasBuffer.js index ebe5d47..b183a66 100644 --- a/src/core/renderers/canvas/utils/CanvasBuffer.js +++ b/src/core/renderers/canvas/utils/CanvasBuffer.js @@ -6,7 +6,8 @@ * @param width {number} the width for the newly created canvas * @param height {number} the height for the newly created canvas */ -function CanvasBuffer(width, height) { +function CanvasBuffer(width, height) +{ /** * The Canvas object that belongs to this CanvasBuffer. * @@ -36,10 +37,12 @@ * @memberof CanvasBuffer# */ width: { - get: function () { + get: function () + { return this.canvas.width; }, - set: function (val) { + set: function (val) + { this.canvas.width = val; } }, @@ -50,10 +53,12 @@ * @memberof CanvasBuffer# */ height: { - get: function () { + get: function () + { return this.canvas.height; }, - set: function (val) { + set: function (val) + { this.canvas.height = val; } } @@ -64,7 +69,8 @@ * * @private */ -CanvasBuffer.prototype.clear = function () { +CanvasBuffer.prototype.clear = function () +{ this.context.setTransform(1, 0, 0, 1, 0, 0); this.context.clearRect(0,0, this.canvas.width, this.canvas.height); }; @@ -75,7 +81,8 @@ * @param width {number} the new width of the canvas * @param height {number} the new height of the canvas */ -CanvasBuffer.prototype.resize = function (width, height) { +CanvasBuffer.prototype.resize = function (width, height) +{ this.canvas.width = width; this.canvas.height = height; }; diff --git a/src/core/renderers/canvas/utils/CanvasGraphics.js b/src/core/renderers/canvas/utils/CanvasGraphics.js index c7eaa2a..3f2a91f 100644 --- a/src/core/renderers/canvas/utils/CanvasGraphics.js +++ b/src/core/renderers/canvas/utils/CanvasGraphics.js @@ -13,15 +13,18 @@ * @param graphics {Graphics} the actual graphics object to render * @param context {CanvasRenderingContext2D} the 2d drawing method of the canvas */ -CanvasGraphics.renderGraphics = function (graphics, context) { +CanvasGraphics.renderGraphics = function (graphics, context) +{ var worldAlpha = graphics.worldAlpha; - if (graphics.dirty) { + if (graphics.dirty) + { this.updateGraphicsTint(graphics); graphics.dirty = false; } - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; @@ -30,69 +33,82 @@ context.lineWidth = data.lineWidth; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { context.beginPath(); var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } - if (shape.closed) { + if (shape.closed) + { context.lineTo(points[0], points[1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fillRect(shape.x, shape.y, shape.width, shape.height); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.strokeRect(shape.x, shape.y, shape.width, shape.height); } } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.beginPath(); context.arc(shape.x, shape.y, shape.radius,0,2*Math.PI); context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas var w = shape.width * 2; @@ -119,18 +135,21 @@ context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; var width = shape.width; @@ -152,13 +171,15 @@ context.quadraticCurveTo(rx, ry, rx, ry + radius); context.closePath(); - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); @@ -174,45 +195,54 @@ * @param graphics {Graphics} the graphics which will be used as a mask * @param context {CanvasRenderingContext2D} the context 2d method of the canvas */ -CanvasGraphics.renderGraphicsMask = function (graphics, context) { +CanvasGraphics.renderGraphicsMask = function (graphics, context) +{ var len = graphics.graphicsData.length; - if (len === 0) { + if (len === 0) + { return; } context.beginPath(); - for (var i = 0; i < len; i++) { + for (var i = 0; i < len; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { context.rect(shape.x, shape.y, shape.width, shape.height); context.closePath(); } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.arc(shape.x, shape.y, shape.radius, 0, 2 * Math.PI); context.closePath(); } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas @@ -237,7 +267,8 @@ context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); context.closePath(); } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; @@ -262,8 +293,10 @@ } }; -CanvasGraphics.updateGraphicsTint = function (graphics) { - if (graphics.tint === 0xFFFFFF) { +CanvasGraphics.updateGraphicsTint = function (graphics) +{ + if (graphics.tint === 0xFFFFFF) + { return; } @@ -271,7 +304,8 @@ var tintG = (graphics.tint >> 8 & 0xFF) / 255; var tintB = (graphics.tint & 0xFF)/ 255; - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var fillColor = data.fillColor | 0; diff --git a/src/core/renderers/canvas/utils/CanvasMaskManager.js b/src/core/renderers/canvas/utils/CanvasMaskManager.js index e04a733..9827d36 100644 --- a/src/core/renderers/canvas/utils/CanvasMaskManager.js +++ b/src/core/renderers/canvas/utils/CanvasMaskManager.js @@ -6,7 +6,8 @@ * @class * @namespace PIXI */ -function CanvasMaskManager() {} +function CanvasMaskManager() +{} CanvasMaskManager.prototype.constructor = CanvasMaskManager; module.exports = CanvasMaskManager; @@ -17,7 +18,8 @@ * @param maskData {object} the maskData that will be pushed * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.pushMask = function (maskData, renderer) { +CanvasMaskManager.prototype.pushMask = function (maskData, renderer) +{ renderer.context.save(); var cacheAlpha = maskData.alpha; @@ -45,6 +47,7 @@ * * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.popMask = function (renderer) { +CanvasMaskManager.prototype.popMask = function (renderer) +{ renderer.context.restore(); }; diff --git a/src/core/renderers/canvas/utils/CanvasTinter.js b/src/core/renderers/canvas/utils/CanvasTinter.js index 17e0529..d2fb1bc 100644 --- a/src/core/renderers/canvas/utils/CanvasTinter.js +++ b/src/core/renderers/canvas/utils/CanvasTinter.js @@ -14,7 +14,8 @@ * @param color {number} the color to use to tint the sprite with * @return {HTMLCanvasElement} The tinted canvas */ -CanvasTinter.getTintedTexture = function (sprite, color) { +CanvasTinter.getTintedTexture = function (sprite, color) +{ var texture = sprite.texture; color = CanvasTinter.roundColor(color); @@ -23,7 +24,8 @@ texture.tintCache = texture.tintCache || {}; - if (texture.tintCache[stringColor]) { + if (texture.tintCache[stringColor]) + { return texture.tintCache[stringColor]; } @@ -33,14 +35,16 @@ //CanvasTinter.tintWithPerPixel(texture, stringColor, canvas); CanvasTinter.tintMethod(texture, color, canvas); - if (CanvasTinter.convertTintToImage) { + if (CanvasTinter.convertTintToImage) + { // is this better? var tintImage = new Image(); tintImage.src = canvas.toDataURL(); texture.tintCache[stringColor] = tintImage; } - else { + else + { texture.tintCache[stringColor] = canvas; // if we are not converting the texture to an image then we need to lose the reference to the canvas CanvasTinter.canvas = null; @@ -56,7 +60,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithMultiply = function (texture, color, canvas) { +CanvasTinter.tintWithMultiply = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -104,7 +109,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithOverlay = function (texture, color, canvas) { +CanvasTinter.tintWithOverlay = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -139,7 +145,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithPerPixel = function (texture, color, canvas) { +CanvasTinter.tintWithPerPixel = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -167,7 +174,8 @@ var pixels = pixelData.data; - for (var i = 0; i < pixels.length; i += 4) { + for (var i = 0; i < pixels.length; i += 4) + { pixels[i+0] *= r; pixels[i+1] *= g; pixels[i+2] *= b; @@ -181,7 +189,8 @@ * * @param color {number} the color to round, should be a hex color */ -CanvasTinter.roundColor = function (color) { +CanvasTinter.roundColor = function (color) +{ var step = CanvasTinter.cacheStepsPerColorChannel; var rgbValues = utils.hex2rgb(color); diff --git a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js index 9f2f89a..35edbaf 100644 --- a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js +++ b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLBlendModeManager(renderer) { +function WebGLBlendModeManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -23,8 +24,10 @@ * * @param blendMode {number} the blendMode, should be a Pixi const, such as BlendModes.ADD */ -WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) { - if (this.currentBlendMode === blendMode) { +WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) +{ + if (this.currentBlendMode === blendMode) + { return false; } diff --git a/src/core/renderers/webgl/managers/WebGLFilterManager.js b/src/core/renderers/webgl/managers/WebGLFilterManager.js index 1179258..2dac048 100644 --- a/src/core/renderers/webgl/managers/WebGLFilterManager.js +++ b/src/core/renderers/webgl/managers/WebGLFilterManager.js @@ -7,7 +7,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLFilterManager(renderer) { +function WebGLFilterManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -32,7 +33,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.texturePool.length = 0; self.initShaderBuffers(); }); @@ -46,7 +48,8 @@ * @param renderer {WebGLRenderer} * @param buffer {ArrayBuffer} */ -WebGLFilterManager.prototype.begin = function (buffer) { +WebGLFilterManager.prototype.begin = function (buffer) +{ this.defaultShader = this.renderer.shaderManager.defaultShader; this.width = this.renderer.projection.x * 2; @@ -60,7 +63,8 @@ * * @param filterBlock {object} the filter that will be pushed to the current filter stack */ -WebGLFilterManager.prototype.pushFilter = function (filterBlock) { +WebGLFilterManager.prototype.pushFilter = function (filterBlock) +{ var gl = this.renderer.gl; var projection = this.renderer.projection; @@ -78,10 +82,12 @@ this.offsetY += filterBlock._filterArea.y; var texture = this.texturePool.pop(); - if (!texture) { + if (!texture) + { texture = new FilterTexture(this.renderer.gl, this.width, this.height); } - else { + else + { texture.resize(this.width, this.height); } @@ -98,29 +104,35 @@ var localX = filterArea.x, localY = filterArea.y; - if (filterArea.x < 0) { + if (filterArea.x < 0) + { filterArea.width += filterArea.x; filterArea.x = 0; } - if (filterArea.y < 0) { + if (filterArea.y < 0) + { filterArea.height += filterArea.y; filterArea.y = 0; } - if (localX + filterArea.width > this.width) { + if (localX + filterArea.width > this.width) + { filterArea.width = this.width - localX; } - if (localY + filterArea.height > this.height) { + if (localY + filterArea.height > this.height) + { filterArea.height = this.height - localY; } - if (filterArea.width < 0) { + if (filterArea.width < 0) + { filterArea.width = 0; } - if (filterArea.height < 0) { + if (filterArea.height < 0) + { filterArea.height = 0; } @@ -154,7 +166,8 @@ * Removes the last filter from the filter stack and doesn't return it. * */ -WebGLFilterManager.prototype.popFilter = function () { +WebGLFilterManager.prototype.popFilter = function () +{ var gl = this.renderer.gl; var filterBlock = this.filterStack.pop(); @@ -163,7 +176,8 @@ var projection = this.renderer.projection; var offset = this.renderer.offset; - if (filterBlock.filterPasses.length > 1) { + if (filterBlock.filterPasses.length > 1) + { gl.viewport(0, 0, filterArea.width, filterArea.height); gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); @@ -193,7 +207,8 @@ var inputTexture = texture; var outputTexture = this.texturePool.pop(); - if (!outputTexture) { + if (!outputTexture) + { outputTexture = new FilterTexture(this.renderer.gl, this.width, this.height); } outputTexture.resize(this.width, this.height); @@ -204,7 +219,8 @@ gl.disable(gl.BLEND); - for (var i = 0; i < filterBlock.filterPasses.length-1; i++) { + for (var i = 0; i < filterBlock.filterPasses.length-1; i++) + { var filterPass = filterBlock.filterPasses[i]; gl.bindFramebuffer(gl.FRAMEBUFFER, outputTexture.frameBuffer ); @@ -243,10 +259,12 @@ var buffer = this.buffer; // time to render the filters texture to the previous scene - if (this.filterStack.length === 0) { + if (this.filterStack.length === 0) + { gl.colorMask(true, true, true, true);//this.transparent); } - else { + else + { var currentFilter = this.filterStack[this.filterStack.length-1]; filterArea = currentFilter._filterArea; @@ -332,13 +350,15 @@ * @param width {number} the horizontal range of the filter * @param height {number} the vertical range of the filter */ -WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) { +WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) +{ // use program var gl = this.renderer.gl; var shader = filter.shaders[gl.id]; - if (!shader) { + if (!shader) + { shader = new Shader(gl); shader.fragmentSrc = filter.fragmentSrc; @@ -356,7 +376,8 @@ gl.uniform2f(shader.projectionVector, width/2, -height/2); gl.uniform2f(shader.offsetVector, 0,0); - if (filter.uniforms.dimensions) { + 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]; @@ -386,7 +407,8 @@ * Initialises the shader buffers. * */ -WebGLFilterManager.prototype.initShaderBuffers = function () { +WebGLFilterManager.prototype.initShaderBuffers = function () +{ var gl = this.renderer.gl; // create some buffers @@ -432,7 +454,8 @@ * Destroys the filter and removes it from the filter stack. * */ -WebGLFilterManager.prototype.destroy = function () { +WebGLFilterManager.prototype.destroy = function () +{ var gl = this.renderer.gl; this.filterStack = null; @@ -441,7 +464,8 @@ this.offsetY = 0; // destroy textures - for (var i = 0; i < this.texturePool.length; i++) { + for (var i = 0; i < this.texturePool.length; i++) + { this.texturePool[i].destroy(); } diff --git a/src/core/renderers/webgl/managers/WebGLManager.js b/src/core/renderers/webgl/managers/WebGLManager.js index 9d47b5c..c30cd51 100644 --- a/src/core/renderers/webgl/managers/WebGLManager.js +++ b/src/core/renderers/webgl/managers/WebGLManager.js @@ -3,7 +3,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLManager(renderer) { +function WebGLManager(renderer) +{ /** * The renderer this manager works for. * @@ -15,6 +16,7 @@ WebGLManager.prototype.constructor = WebGLManager; module.exports = WebGLManager; -WebGLManager.prototype.destroy = function () { +WebGLManager.prototype.destroy = function () +{ this.renderer = null; }; diff --git a/src/core/renderers/webgl/managers/WebGLMaskManager.js b/src/core/renderers/webgl/managers/WebGLMaskManager.js index 2f90b64..e568812 100644 --- a/src/core/renderers/webgl/managers/WebGLMaskManager.js +++ b/src/core/renderers/webgl/managers/WebGLMaskManager.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLMaskManager(renderer) { +function WebGLMaskManager(renderer) +{ WebGLManager.call(this, renderer); } @@ -19,12 +20,15 @@ * * @param maskData {any[]} */ -WebGLMaskManager.prototype.pushMask = function (maskData) { - if (maskData.dirty) { +WebGLMaskManager.prototype.pushMask = function (maskData) +{ + if (maskData.dirty) + { WebGLGraphics.updateGraphics(maskData, this.renderer.gl); } - if (!maskData._webGL[this.renderer.gl.id].data.length) { + if (!maskData._webGL[this.renderer.gl.id].data.length) + { return; } @@ -36,6 +40,7 @@ * * @param maskData {any[]} */ -WebGLMaskManager.prototype.popMask = function (maskData) { +WebGLMaskManager.prototype.popMask = function (maskData) +{ this.renderer.stencilManager.popStencil(maskData, maskData._webGL[this.renderer.gl.id].data[0], this.renderer); }; diff --git a/src/core/renderers/webgl/managers/WebGLShaderManager.js b/src/core/renderers/webgl/managers/WebGLShaderManager.js index fef071c..90c6477 100644 --- a/src/core/renderers/webgl/managers/WebGLShaderManager.js +++ b/src/core/renderers/webgl/managers/WebGLShaderManager.js @@ -10,7 +10,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLShaderManager(renderer) { +function WebGLShaderManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -28,7 +29,8 @@ */ this.tempAttribState = []; - for (var i = 0; i < this.maxAttibs; i++) { + for (var i = 0; i < this.maxAttibs; i++) + { this.attribState[i] = false; } @@ -66,7 +68,8 @@ // listen for context and update necessary shaders var self = this; - this.renderer.on('context', function (event) { + this.renderer.on('context', function (event) + { var gl = event.data; // this shader is used for rendering primitives @@ -97,29 +100,36 @@ * * @param attribs {Array} attribs */ -WebGLShaderManager.prototype.setAttribs = function (attribs) { +WebGLShaderManager.prototype.setAttribs = function (attribs) +{ // reset temp state var i; - for (i = 0; i < this.tempAttribState.length; i++) { + for (i = 0; i < this.tempAttribState.length; i++) + { this.tempAttribState[i] = false; } // set the new attribs - for (var a in attribs) { + for (var a in attribs) + { this.tempAttribState[attribs[a]] = true; } var gl = this.renderer.gl; - for (i = 0; i < this.attribState.length; i++) { - if (this.attribState[i] !== this.tempAttribState[i]) { + for (i = 0; i < this.attribState.length; i++) + { + if (this.attribState[i] !== this.tempAttribState[i]) + { this.attribState[i] = this.tempAttribState[i]; - if (this.attribState[i]) { + if (this.attribState[i]) + { gl.enableVertexAttribArray(i); } - else { + else + { gl.disableVertexAttribArray(i); } } @@ -131,8 +141,10 @@ * * @param shader {Any} */ -WebGLShaderManager.prototype.setShader = function (shader) { - if (this._currentId === shader.uuid) { +WebGLShaderManager.prototype.setShader = function (shader) +{ + if (this._currentId === shader.uuid) + { return false; } @@ -150,7 +162,8 @@ * Destroys this object. * */ -WebGLShaderManager.prototype.destroy = function () { +WebGLShaderManager.prototype.destroy = function () +{ this.attribState = null; this.tempAttribState = null; diff --git a/src/core/renderers/webgl/managers/WebGLStencilManager.js b/src/core/renderers/webgl/managers/WebGLStencilManager.js index 9ec6398..4cb0134 100644 --- a/src/core/renderers/webgl/managers/WebGLStencilManager.js +++ b/src/core/renderers/webgl/managers/WebGLStencilManager.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLStencilManager(renderer) { +function WebGLStencilManager(renderer) +{ WebGLManager.call(this, renderer); this.stencilStack = []; @@ -24,12 +25,14 @@ * @param graphics {Graphics} * @param webGLData {any[]} */ -WebGLStencilManager.prototype.pushStencil = function (graphics, webGLData) { +WebGLStencilManager.prototype.pushStencil = function (graphics, webGLData) +{ var gl = this.renderer.gl; this.bindGraphics(graphics, webGLData, this.renderer); - if (this.stencilStack.length === 0) { + if (this.stencilStack.length === 0) + { gl.enable(gl.STENCIL_TEST); gl.clear(gl.STENCIL_BUFFER_BIT); this.reverse = true; @@ -47,14 +50,17 @@ // draw the triangle strip! - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } @@ -62,31 +68,38 @@ // draw a quad to increment.. gl.drawElements(gl.TRIANGLE_FAN, 4, gl.UNSIGNED_SHORT, ( webGLData.indices.length - 4 ) * 2 ); - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); } this.reverse = !this.reverse; } - else { - if (!this.reverse) { + else + { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } - else { + 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) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); } } @@ -103,7 +116,8 @@ * @param graphics {Graphics} * @param webGLData {Array} */ -WebGLStencilManager.prototype.bindGraphics = function (graphics, webGLData) { +WebGLStencilManager.prototype.bindGraphics = function (graphics, webGLData) +{ //if (this._currentGraphics === graphics)return; this._currentGraphics = graphics; @@ -114,7 +128,8 @@ offset = this.renderer.offset, shader;// = this.renderer.shaderManager.primitiveShader; - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { shader = this.renderer.shaderManager.complexPrimitiveShader; this.renderer.shaderManager.setShader(shader); @@ -141,7 +156,8 @@ // set the index buffer! gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, webGLData.indexBuffer); } - else { + else + { //this.renderer.shaderManager.activatePrimitiveShader(); shader = this.renderer.shaderManager.primitiveShader; this.renderer.shaderManager.setShader( shader ); @@ -154,7 +170,7 @@ gl.uniform2f(shader.uniforms.offsetVector._location, -offset.x, -offset.y); gl.uniform3fv(shader.uniforms.tint._location, utils.hex2rgb(graphics.tint)); - + gl.uniform1f(shader.uniforms.alpha._location, graphics.worldAlpha); @@ -172,19 +188,22 @@ * @param graphics {Graphics} * @param webGLData {Array} */ -WebGLStencilManager.prototype.popStencil = function (graphics, webGLData) { +WebGLStencilManager.prototype.popStencil = function (graphics, webGLData) +{ var gl = this.renderer.gl; this.stencilStack.pop(); this.count--; - if (this.stencilStack.length === 0) { + if (this.stencilStack.length === 0) + { // the stack is empty! gl.disable(gl.STENCIL_TEST); } - else { + else + { var level = this.count; @@ -192,14 +211,17 @@ gl.colorMask(false, false, false, false); - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { this.reverse = !this.reverse; - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } @@ -213,31 +235,38 @@ // draw the triangle strip! gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); - if (!this.reverse) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); } } - else { + else + { // console.log("<<>>") - if (!this.reverse) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } - else { + 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) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); } } @@ -253,7 +282,8 @@ * Destroys the mask stack. * */ -WebGLStencilManager.prototype.destroy = function () { +WebGLStencilManager.prototype.destroy = function () +{ this.renderer = null; this.stencilStack = null; }; diff --git a/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js b/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js index 913ba5e..1ea7d19 100644 --- a/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js +++ b/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function ComplexPrimitiveShader(gl) { +function ComplexPrimitiveShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -24,7 +25,8 @@ 'uniform float flipY;', 'varying vec4 vColor;', - 'void main(void) {', + '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);', @@ -37,7 +39,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = vColor;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/FastShader.js b/src/core/renderers/webgl/shaders/FastShader.js index bd2e29a..2e5e060 100644 --- a/src/core/renderers/webgl/shaders/FastShader.js +++ b/src/core/renderers/webgl/shaders/FastShader.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function FastShader(gl) { +function FastShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -28,7 +29,8 @@ 'const vec2 center = vec2(-1.0, 1.0);', - 'void main(void) {', + 'void main(void) + {', ' vec2 v;', ' vec2 sv = aVertexPosition * aScale;', ' v.x = (sv.x) * cos(aRotation) - (sv.y) * sin(aRotation);', @@ -49,7 +51,8 @@ 'uniform sampler2D uSampler;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/PrimitiveShader.js b/src/core/renderers/webgl/shaders/PrimitiveShader.js index 6f25409..a25f54f 100644 --- a/src/core/renderers/webgl/shaders/PrimitiveShader.js +++ b/src/core/renderers/webgl/shaders/PrimitiveShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function PrimitiveShader(gl) { +function PrimitiveShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -23,7 +24,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + '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);', @@ -36,7 +38,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = vColor;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/Shader.js b/src/core/renderers/webgl/shaders/Shader.js index f8964f5..fd75ef5 100644 --- a/src/core/renderers/webgl/shaders/Shader.js +++ b/src/core/renderers/webgl/shaders/Shader.js @@ -6,7 +6,8 @@ * @param [fragmentSrc] {string} The source of the fragment shader. * @param [vertexSrc] {string} The source of the vertex shader. */ -function Shader(gl, vertexSrc, fragmentSrc, customUniforms, customAttributes) { +function Shader(gl, vertexSrc, fragmentSrc, customUniforms, customAttributes) +{ /** * @member {number} * @readonly @@ -33,7 +34,8 @@ dimensions: { type: '4f', value: new Float32Array(4) } }; - for (var u in customUniforms) { + for (var u in customUniforms) + { this.uniforms[u] = customUniforms[u]; } @@ -43,7 +45,8 @@ aColor: 0 }; - for (var a in customAttributes) { + for (var a in customAttributes) + { this.attributes[a] = customAttributes[a]; } @@ -66,7 +69,8 @@ 'const vec2 center = vec2(-1.0, 1.0);', - 'void main(void) {', + 'void main(void) + {', ' gl_Position = vec4( ((aVertexPosition + offsetVector) / projectionVector) + center , 0.0, 1.0);', ' vTextureCoord = aTextureCoord;', ' vColor = vec4(aColor.rgb * aColor.a, aColor.a);', @@ -85,7 +89,8 @@ 'uniform sampler2D uSampler;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;', '}' ].join('\n'); @@ -96,7 +101,8 @@ Shader.prototype.constructor = Shader; module.exports = Shader; -Shader.prototype.init = function () { +Shader.prototype.init = function () +{ this.compile(); this.gl.useProgram(this.program); @@ -105,14 +111,18 @@ this.cacheAttributeLocations(Object.keys(this.attributes)); }; -Shader.prototype.cacheUniformLocations = function (keys) { - for (var i = 0; i < keys.length; ++i) { +Shader.prototype.cacheUniformLocations = function (keys) +{ + for (var i = 0; i < keys.length; ++i) + { this.uniforms[keys[i]]._location = this.gl.getUniformLocation(this.program, keys[i]); } }; -Shader.prototype.cacheAttributeLocations = function (keys) { - for (var i = 0; i < keys.length; ++i) { +Shader.prototype.cacheAttributeLocations = function (keys) +{ + for (var i = 0; i < keys.length; ++i) + { this.attributes[keys[i]] = this.gl.getAttribLocation(this.program, keys[i]); } @@ -124,14 +134,16 @@ // 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.attributes.aColor === -1) { + // if (this.attributes.aColor === -1) + { // this.attributes.aColor = 2; // } // End worst hack eva // }; -Shader.prototype.compile = function () { +Shader.prototype.compile = function () +{ var gl = this.gl; var glVertShader = this._glCompile(gl.VERTEX_SHADER, this.vertexSrc); @@ -144,13 +156,15 @@ gl.linkProgram(program); // if linking fails, then log and cleanup - if (!gl.getProgramParameter(program, gl.LINK_STATUS)) { + if (!gl.getProgramParameter(program, gl.LINK_STATUS)) + { window.console.error('Pixi.js Error: Could not initialize shader.'); window.console.error('gl.VALIDATE_STATUS', gl.getProgramParameter(program, gl.VALIDATE_STATUS)); window.console.error('gl.getError()', gl.getError()); // if there is a program info log, log it - if (gl.getProgramInfoLog(program) !== '') { + if (gl.getProgramInfoLog(program) !== '') + { window.console.warn('Pixi.js Warning: gl.getProgramInfoLog()', gl.getProgramInfoLog(program)); } @@ -165,18 +179,21 @@ return (this.program = program); }; -Shader.prototype.syncUniforms = function () { +Shader.prototype.syncUniforms = function () +{ var gl = this.gl; this.textureCount = 1; - for (var key in this.uniforms) { + for (var key in this.uniforms) + { var uniform = this.uniforms[key], location = uniform._location, value = uniform.value, i, il; - switch (uniform.type) { + switch (uniform.type) + { // single int value case 'i': case '1i': @@ -282,7 +299,8 @@ // a Color Value case 'c': - if (typeof value === 'number') { + if (typeof value === 'number') + { value = utils.hex2rgb(value); } @@ -311,11 +329,13 @@ // array of 2D Point objects case 'v2v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(2 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 2] = value[i].x; uniform._array[i * 2 + 1] = value[i].y; } @@ -325,11 +345,13 @@ // array of 3D Point objects case 'v3v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(3 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 3] = value[i].x; uniform._array[i * 3 + 1] = value[i].y; uniform._array[i * 3 + 2] = value[i].z; @@ -341,11 +363,13 @@ // array of 4D Point objects case 'v4v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(4 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 4] = value[i].x; uniform._array[i * 4 + 1] = value[i].y; uniform._array[i * 4 + 2] = value[i].z; @@ -359,7 +383,8 @@ // PIXI.Texture case 't': case 'sampler2D': - if (!uniform.value || !uniform.value.baseTexture || !uniform.value.baseTexture.hasLoaded) { + if (!uniform.value || !uniform.value.baseTexture || !uniform.value.baseTexture.hasLoaded) + { break; } @@ -376,7 +401,8 @@ this.textureCount++; // initialize the texture if we haven't yet - if (!uniform._init) { + if (!uniform._init) + { this.initSampler2D(uniform); uniform._init = true; @@ -394,11 +420,13 @@ * Initialises a Sampler2D uniform (which may only be available later on after initUniforms once the texture has loaded) * */ -Shader.prototype.initSampler2D = function (uniform) { +Shader.prototype.initSampler2D = function (uniform) +{ var gl = this.gl; // Extended texture data - if (uniform.textureData) { + if (uniform.textureData) + { var data = uniform.textureData; // GLTexture = mag linear, min linear_mipmap_linear, wrap repeat + gl.generateMipmap(gl.TEXTURE_2D); @@ -417,14 +445,16 @@ var wrapT = (data.wrapT) ? data.wrapT : gl.CLAMP_TO_EDGE; var format = (data.luminance) ? gl.LUMINANCE : gl.RGBA; - if (data.repeat) { + if (data.repeat) + { wrapS = gl.REPEAT; wrapT = gl.REPEAT; } gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, !!data.flipY); - if (data.width) { + if (data.width) + { var width = (data.width) ? data.width : 512; var height = (data.height) ? data.height : 2; var border = (data.border) ? data.border : 0; @@ -432,7 +462,8 @@ // 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 { + 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); } @@ -448,7 +479,8 @@ * Destroys the shader. * */ -Shader.prototype.destroy = function () { +Shader.prototype.destroy = function () +{ this.gl.deleteProgram(this.program); this.gl = null; @@ -459,13 +491,15 @@ this.fragmentSrc = null; }; -Shader.prototype._glCompile = function (type, src) { +Shader.prototype._glCompile = function (type, src) +{ var shader = this.gl.createShader(type); this.gl.shaderSource(shader, src); this.gl.compileShader(shader); - if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) { + if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) + { window.console.log(this.gl.getShaderInfoLog(shader)); return null; } diff --git a/src/core/renderers/webgl/shaders/StripShader.js b/src/core/renderers/webgl/shaders/StripShader.js index 193f6e1..a7abcc6 100644 --- a/src/core/renderers/webgl/shaders/StripShader.js +++ b/src/core/renderers/webgl/shaders/StripShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function StripShader(gl) { +function StripShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -20,7 +21,8 @@ 'varying vec2 vTextureCoord;', - 'void main(void) {', + '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);', @@ -36,7 +38,8 @@ 'varying vec2 vTextureCoord;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vec2(vTextureCoord.x, vTextureCoord.y)) * alpha;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/utils/FilterTexture.js b/src/core/renderers/webgl/utils/FilterTexture.js index d2c8423..4433d44 100644 --- a/src/core/renderers/webgl/utils/FilterTexture.js +++ b/src/core/renderers/webgl/utils/FilterTexture.js @@ -8,7 +8,8 @@ * @param height {number} the vertical range of the filter * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values */ -function FilterTexture(gl, width, height, scaleMode) { +function FilterTexture(gl, width, height, scaleMode) +{ /** * @member {WebGLContext} */ @@ -59,7 +60,8 @@ * Clears the filter texture. * */ -FilterTexture.prototype.clear = function () { +FilterTexture.prototype.clear = function () +{ var gl = this.gl; gl.clearColor(0,0,0, 0); @@ -72,8 +74,10 @@ * @param width {number} the new width of the texture * @param height {number} the new height of the texture */ -FilterTexture.prototype.resize = function (width, height) { - if (this.width === width && this.height === height) { +FilterTexture.prototype.resize = function (width, height) +{ + if (this.width === width && this.height === height) + { return; } @@ -96,7 +100,8 @@ * Destroys the filter texture. * */ -FilterTexture.prototype.destroy = function () { +FilterTexture.prototype.destroy = function () +{ var gl = this.gl; gl.deleteFramebuffer( this.frameBuffer ); gl.deleteTexture( this.texture ); diff --git a/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js b/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js index c4721e9..a63f4d7 100644 --- a/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js +++ b/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js @@ -14,7 +14,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this sprite batch works for. */ -function WebGLFastSpriteBatch(renderer) { +function WebGLFastSpriteBatch(renderer) +{ /** * The renderer instance this sprite batch operates on. * @@ -91,7 +92,8 @@ */ this.lastIndexCount = 0; - for (var i=0, j=0; i < numIndices; i += 6, j += 4) { + 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; @@ -144,7 +146,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.setupContext(); }); } @@ -157,7 +160,8 @@ * * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLFastSpriteBatch.prototype.setupContext = function () { +WebGLFastSpriteBatch.prototype.setupContext = function () +{ var gl = this.renderer.gl; // create a couple of buffers @@ -177,7 +181,8 @@ /** * @param spriteBatch {SpriteBatch} The SpriteBatch container to prepare for. */ -WebGLFastSpriteBatch.prototype.begin = function (spriteBatch) { +WebGLFastSpriteBatch.prototype.begin = function (spriteBatch) +{ this.shader = this.renderer.shaderManager.fastShader; this.matrix = spriteBatch.worldTransform.toArray(true); @@ -187,33 +192,38 @@ /** */ -WebGLFastSpriteBatch.prototype.end = function () { +WebGLFastSpriteBatch.prototype.end = function () +{ this.flush(); }; /** * @param spriteBatch {SpriteBatch} The SpriteBatch container to render. */ -WebGLFastSpriteBatch.prototype.render = function (spriteBatch) { +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) { + if (!sprite.texture._uvs) + { return; } this.currentBaseTexture = sprite.texture.baseTexture; // check blend mode - if (sprite.blendMode !== this.renderer.blendModeManager.currentBlendMode) { + if (sprite.blendMode !== this.renderer.blendModeManager.currentBlendMode) + { this.flush(); this.renderer.blendModeManager.setBlendMode(sprite.blendMode); } - for (var i=0,j= children.length; i= this.size) { + if (this.currentBatchSize >= this.size) + { this.flush(); } }; @@ -362,29 +379,35 @@ /** * */ -WebGLFastSpriteBatch.prototype.flush = function () { +WebGLFastSpriteBatch.prototype.flush = function () +{ // If the batch is length 0 then return as there is nothing to draw - if (this.currentBatchSize === 0) { + if (this.currentBatchSize === 0) + { return; } var gl = this.renderer.gl; // bind the current texture - if (!this.currentBaseTexture._glTextures[gl.id]) { + if (!this.currentBaseTexture._glTextures[gl.id]) + { this.renderer.updateTexture(this.currentBaseTexture, gl); } //TODO-SHOUD THIS BE ELSE??!?!?! - else { + else + { gl.bindTexture(gl.TEXTURE_2D, this.currentBaseTexture._glTextures[gl.id]); } // upload the verts to the buffer - if (this.currentBatchSize > ( this.size * 0.5 ) ) { + if (this.currentBatchSize > ( this.size * 0.5 ) ) + { gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); } - else { + else + { var view = this.vertices.subarray(0, this.currentBatchSize * this.vertByteSize); gl.bufferSubData(gl.ARRAY_BUFFER, 0, view); @@ -405,14 +428,16 @@ * Ends the batch and flushes * */ -WebGLFastSpriteBatch.prototype.stop = function () { +WebGLFastSpriteBatch.prototype.stop = function () +{ this.flush(); }; /** * */ -WebGLFastSpriteBatch.prototype.start = function () { +WebGLFastSpriteBatch.prototype.start = function () +{ var gl = this.renderer.gl; // bind the main texture diff --git a/src/core/renderers/webgl/utils/WebGLGraphics.js b/src/core/renderers/webgl/utils/WebGLGraphics.js index 55f4911..ab8f46e 100644 --- a/src/core/renderers/webgl/utils/WebGLGraphics.js +++ b/src/core/renderers/webgl/utils/WebGLGraphics.js @@ -19,7 +19,8 @@ * @param graphics {Graphics} * @param renderer {WebGLRenderer} */ -WebGLGraphics.renderGraphics = function (graphics, renderer) {//projection, offset) { +WebGLGraphics.renderGraphics = function (graphics, renderer) {//projection, offset) +{ var gl = renderer.gl; var projection = renderer.projection, @@ -27,7 +28,8 @@ shader = renderer.shaderManager.primitiveShader, webGLData; - if (graphics.dirty) { + if (graphics.dirty) + { WebGLGraphics.updateGraphics(graphics, gl); } @@ -35,8 +37,10 @@ // This could be speeded up for sure! - for (var i = 0; i < webGL.data.length; i++) { - if (webGL.data[i].mode === 1) { + for (var i = 0; i < webGL.data.length; i++) + { + if (webGL.data[i].mode === 1) + { webGLData = webGL.data[i]; renderer.stencilManager.pushStencil(graphics, webGLData, renderer); @@ -46,7 +50,8 @@ renderer.stencilManager.popStencil(graphics, webGLData, renderer); } - else { + else + { webGLData = webGL.data[i]; @@ -84,12 +89,14 @@ * @param graphicsData {Graphics} The graphics object to update * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLGraphics.updateGraphics = function (graphics, gl) { +WebGLGraphics.updateGraphics = function (graphics, gl) +{ // get the contexts graphics object var webGL = graphics._webGL[gl.id]; // if the graphics object does not exist in the webGL context time to create it! - if (!webGL) { + if (!webGL) + { webGL = graphics._webGL[gl.id] = {lastIndex:0, data:[], gl:gl}; } @@ -99,11 +106,13 @@ var i; // if the user cleared the graphics object we will need to clear every object - if (graphics.clearDirty) { + if (graphics.clearDirty) + { graphics.clearDirty = false; // lop through and return all the webGLDatas to the object pool so than can be reused later on - for (i = 0; i < webGL.data.length; i++) { + for (i = 0; i < webGL.data.length; i++) + { var graphicsData = webGL.data[i]; graphicsData.reset(); WebGLGraphics.graphicsDataPool.push( graphicsData ); @@ -119,58 +128,72 @@ // loop through the graphics datas and construct each one.. // if the object is a complex fill then the new stencil buffer technique will be used // other wise graphics objects will be pushed into a batch.. - for (i = webGL.lastIndex; i < graphics.graphicsData.length; i++) { + for (i = webGL.lastIndex; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { // need to add the points the the graphics object.. data.points = data.shape.points.slice(); - if (data.shape.closed) { + if (data.shape.closed) + { // close the poly if the value is true! - if (data.points[0] !== data.points[data.points.length-2] || data.points[1] !== data.points[data.points.length-1]) { + if (data.points[0] !== data.points[data.points.length-2] || data.points[1] !== data.points[data.points.length-1]) + { data.points.push(data.points[0], data.points[1]); } } // MAKE SURE WE HAVE THE CORRECT TYPE.. - if (data.fill) { - if (data.points.length >= 6) { - if (data.points.length < 6 * 2) { + if (data.fill) + { + if (data.points.length >= 6) + { + if (data.points.length < 6 * 2) + { webGLData = WebGLGraphics.switchMode(webGL, 0); var canDrawUsingSimple = WebGLGraphics.buildPoly(data, webGLData); // console.log(canDrawUsingSimple); - if (!canDrawUsingSimple) { + if (!canDrawUsingSimple) + { // console.log("<>>>") webGLData = WebGLGraphics.switchMode(webGL, 1); WebGLGraphics.buildComplexPoly(data, webGLData); } } - else { + else + { webGLData = WebGLGraphics.switchMode(webGL, 1); WebGLGraphics.buildComplexPoly(data, webGLData); } } } - if (data.lineWidth > 0) { + if (data.lineWidth > 0) + { webGLData = WebGLGraphics.switchMode(webGL, 0); WebGLGraphics.buildLine(data, webGLData); } } - else { + else + { webGLData = WebGLGraphics.switchMode(webGL, 0); - if (data.type === CONST.SHAPES.RECT) { + if (data.type === CONST.SHAPES.RECT) + { WebGLGraphics.buildRectangle(data, webGLData); } - else if (data.type === CONST.SHAPES.CIRC || data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.CIRC || data.type === CONST.SHAPES.ELIP) + { WebGLGraphics.buildCircle(data, webGLData); } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { WebGLGraphics.buildRoundedRectangle(data, webGLData); } } @@ -179,10 +202,12 @@ } // upload all the dirty data... - for (i = 0; i < webGL.data.length; i++) { + for (i = 0; i < webGL.data.length; i++) + { webGLData = webGL.data[i]; - if (webGLData.dirty) { + if (webGLData.dirty) + { webGLData.upload(); } } @@ -194,18 +219,22 @@ * @param webGL {WebGLContext} * @param type {number} */ -WebGLGraphics.switchMode = function (webGL, type) { +WebGLGraphics.switchMode = function (webGL, type) +{ var webGLData; - if (!webGL.data.length) { + if (!webGL.data.length) + { webGLData = WebGLGraphics.graphicsDataPool.pop() || new WebGLGraphicsData(webGL.gl); webGLData.mode = type; webGL.data.push(webGLData); } - else { + else + { webGLData = webGL.data[webGL.data.length-1]; - if (webGLData.mode !== type || type === 1) { + if (webGLData.mode !== type || type === 1) + { webGLData = WebGLGraphics.graphicsDataPool.pop() || new WebGLGraphicsData(webGL.gl); webGLData.mode = type; webGL.data.push(webGLData); @@ -225,7 +254,8 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildRectangle = function (graphicsData, webGLData) { +WebGLGraphics.buildRectangle = function (graphicsData, webGLData) +{ // --- // // need to convert points to a nice regular data // @@ -235,7 +265,8 @@ var width = rectData.width; var height = rectData.height; - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -265,7 +296,8 @@ indices.push(vertPos, vertPos, vertPos+1, vertPos+2, vertPos+3, vertPos+3); } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = [x, y, @@ -289,7 +321,8 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildRoundedRectangle = function (graphicsData, webGLData) { +WebGLGraphics.buildRoundedRectangle = function (graphicsData, webGLData) +{ var rrectData = graphicsData.shape; var x = rrectData.x; var y = rrectData.y; @@ -305,7 +338,8 @@ recPoints = recPoints.concat(WebGLGraphics.quadraticBezierCurve(x + width, y + radius, x + width, y, x + width - radius, y)); recPoints = recPoints.concat(WebGLGraphics.quadraticBezierCurve(x + radius, y, x, y, x, y + radius)); - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -323,7 +357,8 @@ // var i = 0; - for (i = 0; i < triangles.length; i+=3) { + for (i = 0; i < triangles.length; i+=3) + { indices.push(triangles[i] + vecPos); indices.push(triangles[i] + vecPos); indices.push(triangles[i+1] + vecPos); @@ -332,12 +367,14 @@ } - for (i = 0; i < recPoints.length; i++) { + for (i = 0; i < recPoints.length; i++) + { verts.push(recPoints[i], recPoints[++i], r, g, b, alpha); } } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = recPoints; @@ -362,7 +399,8 @@ * @param toY {number} Destination point y * @return {number[]} */ -WebGLGraphics.quadraticBezierCurve = function (fromX, fromY, cpX, cpY, toX, toY) { +WebGLGraphics.quadraticBezierCurve = function (fromX, fromY, cpX, cpY, toX, toY) +{ var xa, ya, @@ -373,14 +411,16 @@ n = 20, points = []; - function getPt(n1 , n2, perc) { + function getPt(n1 , n2, perc) + { var diff = n2 - n1; return n1 + ( diff * perc ); } var j = 0; - for (var i = 0; i <= n; i++ ) { + for (var i = 0; i <= n; i++ ) + { j = i / n; // The Green Line @@ -406,7 +446,8 @@ * @param graphicsData {Graphics} The graphics object to draw * @param webGLData {object} */ -WebGLGraphics.buildCircle = function (graphicsData, webGLData) { +WebGLGraphics.buildCircle = function (graphicsData, webGLData) +{ // need to convert points to a nice regular data var circleData = graphicsData.shape; var x = circleData.x; @@ -415,11 +456,13 @@ var height; // TODO - bit hacky?? - if (graphicsData.type === CONST.SHAPES.CIRC) { + if (graphicsData.type === CONST.SHAPES.CIRC) + { width = circleData.radius; height = circleData.radius; } - else { + else + { width = circleData.width; height = circleData.height; } @@ -429,7 +472,8 @@ var i = 0; - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -444,7 +488,8 @@ indices.push(vecPos); - for (i = 0; i < totalSegs + 1 ; i++) { + for (i = 0; i < totalSegs + 1 ; i++) + { verts.push(x,y, r, g, b, alpha); verts.push(x + Math.sin(seg * i) * width, @@ -457,12 +502,14 @@ indices.push(vecPos-1); } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = []; - for (i = 0; i < totalSegs + 1; i++) { + for (i = 0; i < totalSegs + 1; i++) + { graphicsData.points.push(x + Math.sin(seg * i) * width, y + Math.cos(seg * i) * height); } @@ -481,18 +528,22 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildLine = function (graphicsData, webGLData) { +WebGLGraphics.buildLine = function (graphicsData, webGLData) +{ // TODO OPTIMISE! var i = 0; var points = graphicsData.points; - if (points.length === 0) { + if (points.length === 0) + { return; } // if the line width is an odd number add 0.5 to align to a whole pixel - if (graphicsData.lineWidth%2) { - for (i = 0; i < points.length; i++) { + if (graphicsData.lineWidth%2) + { + for (i = 0; i < points.length; i++) + { points[i] += 0.5; } } @@ -502,7 +553,8 @@ var lastPoint = new math.Point(points[points.length - 2], points[points.length - 1]); // if the first point is the last point - gonna have issues :) - if (firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) { + if (firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) + { // need to clone as we are going to slightly modify the shape.. points = points.slice(); @@ -562,7 +614,8 @@ verts.push(p1x + perpx , p1y + perpy, r, g, b, alpha); - for (i = 1; i < length-1; i++) { + for (i = 1; i < length-1; i++) + { p1x = points[(i-1)*2]; p1y = points[(i-1)*2 + 1]; @@ -599,7 +652,8 @@ denom = a1*b2 - a2*b1; - if (Math.abs(denom) < 0.1 ) { + if (Math.abs(denom) < 0.1 ) + { denom+=10.1; verts.push(p2x - perpx , p2y - perpy, @@ -618,7 +672,8 @@ pdist = (px -p2x) * (px -p2x) + (py -p2y) + (py -p2y); - if (pdist > 140 * 140) { + if (pdist > 140 * 140) + { perp3x = perpx - perp2x; perp3y = perpy - perp2y; @@ -639,7 +694,8 @@ indexCount++; } - else { + else + { verts.push(px , py); verts.push(r, g, b, alpha); @@ -672,7 +728,8 @@ indices.push(indexStart); - for (i = 0; i < indexCount; i++) { + for (i = 0; i < indexCount; i++) + { indices.push(indexStart++); } @@ -687,11 +744,13 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildComplexPoly = function (graphicsData, webGLData) { +WebGLGraphics.buildComplexPoly = function (graphicsData, webGLData) +{ //TODO - no need to copy this as it gets turned into a FLoat32Array anyways.. var points = graphicsData.points.slice(); - if (points.length < 6) { + if (points.length < 6) + { return; } @@ -711,7 +770,8 @@ var x,y; // get size.. - for (var i = 0; i < points.length; i+=2) { + for (var i = 0; i < points.length; i+=2) + { x = points[i]; y = points[i+1]; @@ -732,7 +792,8 @@ //TODO - this aint needed! var length = points.length / 2; - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { indices.push( i ); } @@ -746,10 +807,12 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildPoly = function (graphicsData, webGLData) { +WebGLGraphics.buildPoly = function (graphicsData, webGLData) +{ var points = graphicsData.points; - if (points.length < 6) { + if (points.length < 6) + { return; } // get first and last point.. figure out the middle! @@ -767,7 +830,8 @@ var triangles = utils.PolyK.Triangulate(points); - if (!triangles) { + if (!triangles) + { return false; } @@ -775,7 +839,8 @@ var i = 0; - for (i = 0; i < triangles.length; i+=3) { + for (i = 0; i < triangles.length; i+=3) + { indices.push(triangles[i] + vertPos); indices.push(triangles[i] + vertPos); indices.push(triangles[i+1] + vertPos); @@ -783,7 +848,8 @@ indices.push(triangles[i+2] + vertPos); } - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { verts.push(points[i * 2], points[i * 2 + 1], r, g, b, alpha); } diff --git a/src/core/renderers/webgl/utils/WebGLGraphicsData.js b/src/core/renderers/webgl/utils/WebGLGraphicsData.js index c56d05e..c739ba7 100644 --- a/src/core/renderers/webgl/utils/WebGLGraphicsData.js +++ b/src/core/renderers/webgl/utils/WebGLGraphicsData.js @@ -2,7 +2,8 @@ * @class * @private */ -function WebGLGraphicsData(gl) { +function WebGLGraphicsData(gl) +{ this.gl = gl; //TODO does this need to be split before uploding?? @@ -22,7 +23,8 @@ /** * */ -WebGLGraphicsData.prototype.reset = function () { +WebGLGraphicsData.prototype.reset = function () +{ this.points.length = 0; this.indices.length = 0; }; @@ -30,7 +32,8 @@ /** * */ -WebGLGraphicsData.prototype.upload = function () { +WebGLGraphicsData.prototype.upload = function () +{ var gl = this.gl; // this.lastIndex = graphics.graphicsData.length; diff --git a/src/core/display/DisplayObject.js b/src/core/display/DisplayObject.js index 66ebc3c..20e778c 100644 --- a/src/core/display/DisplayObject.js +++ b/src/core/display/DisplayObject.js @@ -7,7 +7,8 @@ * @class * @namespace PIXI */ -function DisplayObject() { +function DisplayObject() +{ /** * The coordinate of the object relative to the local coordinates of the parent. * @@ -152,10 +153,12 @@ * @memberof DisplayObject# */ x: { - get: function () { + get: function () + { return this.position.x; }, - set: function (value) { + set: function (value) + { this.position.x = value; } }, @@ -167,10 +170,12 @@ * @memberof DisplayObject# */ y: { - get: function () { + get: function () + { return this.position.y; }, - set: function (value) { + set: function (value) + { this.position.y = value; } }, @@ -183,11 +188,13 @@ * @readonly */ worldVisible: { - get: function () { + get: function () + { var item = this; do { - if (!item.visible) { + if (!item.visible) + { return false; } @@ -207,17 +214,21 @@ * @memberof DisplayObject# */ mask: { - get: function () { + get: function () + { return this._mask; }, - set: function (value) { - if (this._mask) { + set: function (value) + { + if (this._mask) + { this._mask.isMask = false; } this._mask = value; - if (this._mask) { + if (this._mask) + { this._mask.isMask = true; } } @@ -232,18 +243,23 @@ * @memberof DisplayObject# */ filters: { - get: function () { + get: function () + { return this._filters; }, - set: function (value) { - if (value) { + set: function (value) + { + if (value) + { // now put all the passes in one place.. var passes = []; - for (var i = 0; i < value.length; i++) { + for (var i = 0; i < value.length; i++) + { var filterPasses = value[i].passes; - for (var j = 0; j < filterPasses.length; j++) { + for (var j = 0; j < filterPasses.length; j++) + { passes.push(filterPasses[j]); } } @@ -264,8 +280,9 @@ * * @private */ -DisplayObject.prototype.updateTransform = function () { - +DisplayObject.prototype.updateTransform = function () +{ + // create some matrix refs for easy access var pt = this.parent.worldTransform; var wt = this.worldTransform; @@ -274,9 +291,11 @@ var a, b, c, d, tx, ty; // so if rotation is between 0 then we can simplify the multiplication process.. - if (this.rotation % math.PI_2) { + if (this.rotation % math.PI_2) + { // 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) { + if (this.rotation !== this.rotationCache) + { this.rotationCache = this.rotation; this._sr = Math.sin(this.rotation); this._cr = Math.cos(this.rotation); @@ -291,7 +310,8 @@ ty = this.position.y; // check for pivot.. not often used so geared towards that fact! - if (this.pivot.x || this.pivot.y) { + 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; } @@ -304,7 +324,8 @@ wt.tx = tx * pt.a + ty * pt.c + pt.tx; wt.ty = tx * pt.b + ty * pt.d + pt.ty; } - else { + else + { // lets do the fast version as we know there is no rotation.. a = this.scale.x; d = this.scale.y; @@ -333,7 +354,8 @@ * @param matrix {Matrix} * @return {Rectangle} the rectangular bounding area */ -DisplayObject.prototype.getBounds = function (/* matrix */) { +DisplayObject.prototype.getBounds = function (/* matrix */) +{ return math.Rectangle.EMPTY; }; @@ -342,7 +364,8 @@ * * @return {Rectangle} the rectangular bounding area */ -DisplayObject.prototype.getLocalBounds = function () { +DisplayObject.prototype.getLocalBounds = function () +{ return this.getBounds(math.Matrix.IDENTITY); }; @@ -352,7 +375,8 @@ * @param position {Point} The world origin to calculate from * @return {Point} A point object representing the position of this object */ -DisplayObject.prototype.toGlobal = function (position) { +DisplayObject.prototype.toGlobal = function (position) +{ // don't need to u[date the lot this.displayObjectUpdateTransform(); return this.worldTransform.apply(position); @@ -365,8 +389,10 @@ * @param [from] {DisplayObject} The DisplayObject to calculate the global position from * @return {Point} A point object representing the position of this object */ -DisplayObject.prototype.toLocal = function (position, from) { - if (from) { +DisplayObject.prototype.toLocal = function (position, from) +{ + if (from) + { position = from.toGlobal(position); } @@ -381,7 +407,8 @@ * @param renderer {WebGLRenderer} The renderer * @private */ -DisplayObject.prototype.renderWebGL = function (/* renderer */) { +DisplayObject.prototype.renderWebGL = function (/* renderer */) +{ // OVERWRITE; }; @@ -391,6 +418,7 @@ * @param renderer {CanvasRenderer} The renderer * @private */ -DisplayObject.prototype.renderCanvas = function (/* renderer */) { +DisplayObject.prototype.renderCanvas = function (/* renderer */) +{ // OVERWRITE; }; diff --git a/src/core/display/DisplayObjectContainer.js b/src/core/display/DisplayObjectContainer.js index 689f40b..4625ee8 100644 --- a/src/core/display/DisplayObjectContainer.js +++ b/src/core/display/DisplayObjectContainer.js @@ -12,7 +12,8 @@ * @extends DisplayObject * @namespace PIXI */ -function DisplayObjectContainer() { +function DisplayObjectContainer() +{ DisplayObject.call(this); /** @@ -47,17 +48,21 @@ * @memberof DisplayObjectContainer# */ width: { - get: function () { + get: function () + { return this.scale.x * this.getLocalBounds().width; }, - set: function (value) { + set: function (value) + { var width = this.getLocalBounds().width; - if(width !== 0) { + if(width !== 0) + { this.scale.x = value / width; } - else { + else + { this.scale.x = 1; } @@ -73,17 +78,21 @@ * @memberof DisplayObjectContainer# */ height: { - get: function () { + get: function () + { return this.scale.y * this.getLocalBounds().height; }, - set: function (value) { + set: function (value) + { var height = this.getLocalBounds().height; - if (height !== 0) { + if (height !== 0) + { this.scale.y = value / height ; } - else { + else + { this.scale.y = 1; } @@ -100,18 +109,23 @@ * @memberof DisplayObject# */ cacheAsBitmap: { - get: function () { + get: function () + { return this._cacheAsBitmap; }, - set: function (value) { - if (this._cacheAsBitmap === value) { + set: function (value) + { + if (this._cacheAsBitmap === value) + { return; } - if (value) { + if (value) + { this._generateCachedSprite(); } - else { + else + { this._destroyCachedSprite(); } @@ -126,7 +140,8 @@ * @param child {DisplayObject} The DisplayObject to add to the container * @return {DisplayObject} The child that was added. */ -DisplayObjectContainer.prototype.addChild = function (child) { +DisplayObjectContainer.prototype.addChild = function (child) +{ return this.addChildAt(child, this.children.length); }; @@ -137,14 +152,18 @@ * @param index {Number} The index to place the child in * @return {DisplayObject} The child that was added. */ -DisplayObjectContainer.prototype.addChildAt = function (child, index) { +DisplayObjectContainer.prototype.addChildAt = function (child, index) +{ // prevent adding self as child - if (child === this) { + if (child === this) + { return; } - if (index >= 0 && index <= this.children.length) { - if (child.parent) { + if (index >= 0 && index <= this.children.length) + { + if (child.parent) + { child.parent.removeChild(child); } @@ -154,7 +173,8 @@ return child; } - else { + else + { throw new Error(child + 'addChildAt: The index '+ index +' supplied is out of bounds ' + this.children.length); } }; @@ -165,15 +185,18 @@ * @param child {DisplayObject} * @param child2 {DisplayObject} */ -DisplayObjectContainer.prototype.swapChildren = function (child, child2) { - if (child === child2) { +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) { + if (index1 < 0 || index2 < 0) + { throw new Error('swapChildren: Both the supplied DisplayObjects must be a child of the caller.'); } @@ -187,10 +210,12 @@ * @param child {DisplayObject} The DisplayObject instance to identify * @return {Number} The index position of the child display object to identify */ -DisplayObjectContainer.prototype.getChildIndex = function (child) { +DisplayObjectContainer.prototype.getChildIndex = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { throw new Error('The supplied DisplayObject must be a child of the caller'); } @@ -203,8 +228,10 @@ * @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 */ -DisplayObjectContainer.prototype.setChildIndex = function (child, index) { - if (index < 0 || index >= this.children.length) { +DisplayObjectContainer.prototype.setChildIndex = function (child, index) +{ + if (index < 0 || index >= this.children.length) + { throw new Error('The supplied index is out of bounds'); } @@ -220,8 +247,10 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child at the given index, if any. */ -DisplayObjectContainer.prototype.getChildAt = function (index) { - if (index < 0 || index >= this.children.length) { +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'); } @@ -234,10 +263,12 @@ * @param child {DisplayObject} The DisplayObject to remove * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChild = function (child) { +DisplayObjectContainer.prototype.removeChild = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { return; } @@ -250,7 +281,8 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChildAt = function (index) { +DisplayObjectContainer.prototype.removeChildAt = function (index) +{ var child = this.getChildAt(index); child.parent = null; @@ -265,24 +297,29 @@ * @param beginIndex {Number} The beginning position. Default value is 0. * @param endIndex {Number} The ending position. Default value is size of the container. */ -DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) { +DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) +{ var begin = beginIndex || 0; var end = typeof endIndex === 'number' ? endIndex : this.children.length; var range = end - begin; - if (range > 0 && range <= end) { + if (range > 0 && range <= end) + { var removed = this.children.splice(begin, range); - for (var i = 0; i < removed.length; ++i) { + for (var i = 0; i < removed.length; ++i) + { removed[i].parent = null; } return removed; } - else if (range === 0 && this.children.length === 0) { + else if (range === 0 && this.children.length === 0) + { return []; } - else { + else + { throw new RangeError('removeChildren: numeric values are outside the acceptable range.'); } }; @@ -291,7 +328,8 @@ * Generates and updates the cached sprite for this object. * */ -DisplayObjectContainer.prototype.updateCachedSprite = function () { +DisplayObjectContainer.prototype.updateCachedSprite = function () +{ this._generateCachedSprite(); }; @@ -304,7 +342,8 @@ * @param renderer {CanvasRenderer|WebGLRenderer} The renderer used to generate the texture. * @return {Texture} a texture of the graphics object */ -DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) { +DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) +{ var bounds = this.getLocalBounds(); var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0, renderer, scaleMode, resolution); @@ -322,18 +361,22 @@ * * @private */ -DisplayObjectContainer.prototype.updateTransform = function () { - if (!this.visible) { +DisplayObjectContainer.prototype.updateTransform = function () +{ + if (!this.visible) + { return; } this.displayObjectUpdateTransform(); - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { return; } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } }; @@ -346,8 +389,10 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getBounds = function () { - if (this.children.length === 0) { +DisplayObjectContainer.prototype.getBounds = function () +{ + if (this.children.length === 0) + { return math.Rectangle.EMPTY; } @@ -365,10 +410,12 @@ var childVisible = false; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -386,7 +433,8 @@ maxY = maxY > childMaxY ? maxY : childMaxY; } - if (!childVisible) { + if (!childVisible) + { return math.Rectangle.EMPTY; } @@ -407,12 +455,14 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getLocalBounds = function () { +DisplayObjectContainer.prototype.getLocalBounds = function () +{ var matrixCache = this.worldTransform; this.worldTransform = math.Matrix.IDENTITY; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } @@ -428,13 +478,16 @@ * * @param renderer {WebGLRenderer} The renderer */ -DisplayObjectContainer.prototype.renderWebGL = function (renderer) { +DisplayObjectContainer.prototype.renderWebGL = function (renderer) +{ // if the object is not visible or the alpha is 0 then no need to render this element - if (!this.visible || this.alpha <= 0) { + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } @@ -442,14 +495,17 @@ var i, j; // do a quick check to see if this element has a mask or a filter. - if (this._mask || this._filters) { + if (this._mask || this._filters) + { // push filter first as we need to ensure the stencil buffer is correct for any masking - if (this._filters) { + if (this._filters) + { renderer.spriteBatch.flush(); renderer.filterManager.pushFilter(this._filterBlock); } - if (this._mask) { + if (this._mask) + { renderer.spriteBatch.stop(); renderer.maskManager.pushMask(this.mask, renderer); renderer.spriteBatch.start(); @@ -459,36 +515,42 @@ this._renderWebGL(renderer); // now loop through the children and make sure they get rendered - for (i = 0, j = this.children.length; i < j; i++) { + for (i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderWebGL(renderer); } // time to stop the sprite batch as either a mask element or a filter draw will happen next renderer.spriteBatch.stop(); - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(this._mask, renderer); } - if (this._filters) { + if (this._filters) + { renderer.filterManager.popFilter(); } renderer.spriteBatch.start(); } - else { + else + { this._renderWebGL(renderer); // simple render children! - for (i = 0, j = this.children.length; i < j; ++i) { + for (i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderWebGL(renderer); } } }; -DisplayObjectContainer.prototype._renderWebGL = function (renderer) { +DisplayObjectContainer.prototype._renderWebGL = function (renderer) +{ // this is where content itself gets renderd.. @@ -499,25 +561,31 @@ * * @param renderer {CanvasRenderer} The renderer */ -DisplayObjectContainer.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0) { +DisplayObjectContainer.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -528,13 +596,16 @@ * @param renderer {WebGLRenderer|CanvasRenderer} The renderer * @private */ -DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) { +DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) +{ this._cachedSprite.worldAlpha = this.worldAlpha; - if (renderer.gl) { + if (renderer.gl) + { this._cachedSprite.renderWebGL(renderer); } - else { + else + { this._cachedSprite.renderCanvas(renderer); } }; @@ -544,10 +615,12 @@ * * @private */ -DisplayObjectContainer.prototype._generateCachedSprite = function () { +DisplayObjectContainer.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { // TODO - RenderTexture now *requires* a renderer instance, so this is like broken // because `renderer` isn't actually in scope here :P var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0); @@ -555,7 +628,8 @@ this._cachedSprite = new Sprite(renderTexture); this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.texture.resize(bounds.width | 0, bounds.height | 0); } @@ -580,8 +654,10 @@ * * @private */ -DisplayObjectContainer.prototype._destroyCachedSprite = function () { - if (!this._cachedSprite) { +DisplayObjectContainer.prototype._destroyCachedSprite = function () +{ + if (!this._cachedSprite) + { return; } diff --git a/src/core/display/Sprite.js b/src/core/display/Sprite.js index 707da24..5862aef 100644 --- a/src/core/display/Sprite.js +++ b/src/core/display/Sprite.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param texture {Texture} The texture for this sprite */ -function Sprite(texture) { +function Sprite(texture) +{ DisplayObjectContainer.call(this); /** @@ -85,12 +86,14 @@ this.texture = texture || Texture.EMPTY; } -Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) { +Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) +{ DisplayObjectContainer.prototype.destroy.call(this); this.anchor = null; - if (destroyTexture) { + if (destroyTexture) + { this._texture.destroy(destroyBaseTexture); } @@ -111,10 +114,12 @@ * @memberof Sprite# */ width: { - get: function () { + get: function () + { return this.scale.x * this.texture.frame.width; }, - set: function (value) { + set: function (value) + { this.scale.x = value / this.texture.frame.width; this._width = value; } @@ -127,10 +132,12 @@ * @memberof Sprite# */ height: { - get: function () { + get: function () + { return this.scale.y * this.texture.frame.height; }, - set: function (value) { + set: function (value) + { this.scale.y = value / this.texture.frame.height; this._height = value; } @@ -143,23 +150,29 @@ * @memberof Sprite# */ texture: { - get: function () { + get: function () + { return this._texture; }, - set: function (value) { - if (this._texture === value) { + set: function (value) + { + if (this._texture === value) + { return; } this._texture = value; this.cachedTint = 0xFFFFFF; - if (value) { + if (value) + { // wait for the texture to load - if (value.baseTexture.hasLoaded) { + if (value.baseTexture.hasLoaded) + { this._onTextureUpdate(); } - else { + else + { value.once('update', this._onTextureUpdate.bind(this)); } } @@ -172,18 +185,22 @@ * * @private */ -Sprite.prototype._onTextureUpdate = function () { +Sprite.prototype._onTextureUpdate = function () +{ // so if _width is 0 then width was not set.. - if (this._width) { + if (this._width) + { this.scale.x = this._width / this.texture.frame.width; } - if (this._height) { + if (this._height) + { this.scale.y = this._height / this.texture.frame.height; } }; -Sprite.prototype._renderWebGL = function (renderer) { +Sprite.prototype._renderWebGL = function (renderer) +{ // this is where content gets renderd.. // watch this space for a little render state manager.. @@ -197,7 +214,8 @@ * @param matrix {Matrix} the transformation matrix of the sprite * @return {Rectangle} the framing rectangle */ -Sprite.prototype.getBounds = function (matrix) { +Sprite.prototype.getBounds = function (matrix) +{ var width = this.texture.frame.width; var height = this.texture.frame.height; @@ -224,11 +242,13 @@ if(b === 0 && c === 0) { // scale may be negative! - if (a < 0) { + if (a < 0) + { a *= -1; } - if (d < 0) { + if (d < 0) + { d *= -1; } @@ -293,28 +313,34 @@ * * @param renderer {CanvasRenderer} The renderer */ -Sprite.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) { +Sprite.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) + { return; } - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; renderer.context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } // Ignore null sources - if (this.texture.valid) { + if (this.texture.valid) + { var resolution = this.texture.baseTexture.resolution / renderer.resolution; renderer.context.globalAlpha = this.worldAlpha; // If smoothingEnabled is supported and we need to change the smoothing property for this texture - if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) { + if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) + { renderer.scaleMode = this.texture.baseTexture.scaleMode; renderer.context[renderer.smoothProperty] = (renderer.scaleMode === CONST.scaleModes.LINEAR); } @@ -324,7 +350,8 @@ var dy = (this.texture.trim ? this.texture.trim.y : 0) - (this.anchor.y * this.texture.trim.height); // Allow for pixel rounding - if (renderer.roundPixels) { + if (renderer.roundPixels) + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -337,7 +364,8 @@ dx = dx | 0; dy = dy | 0; } - else { + else + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -348,8 +376,10 @@ ); } - if (this.tint !== 0xFFFFFF) { - if (this.cachedTint !== this.tint) { + if (this.tint !== 0xFFFFFF) + { + if (this.cachedTint !== this.tint) + { this.cachedTint = this.tint; // TODO clean up caching - how to clean up the caches? @@ -368,7 +398,8 @@ this.texture.crop.height / resolution ); } - else { + else + { renderer.context.drawImage( this.texture.baseTexture.source, this.texture.crop.x, @@ -383,11 +414,13 @@ } } - for (var i = 0, j = this.children.length; i < j; i++) { + for (var i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -402,10 +435,12 @@ * @param frameId {String} The frame Id of the texture in the cache * @return {Sprite} A new Sprite using a texture from the texture cache matching the frameId */ -Sprite.fromFrame = function (frameId) { +Sprite.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache' + this); } @@ -420,6 +455,7 @@ * @param imageId {String} The image url of the texture * @return {Sprite} A new Sprite using a texture from the texture cache matching the image id */ -Sprite.fromImage = function (imageId, crossorigin, scaleMode) { +Sprite.fromImage = function (imageId, crossorigin, scaleMode) +{ return new Sprite(Texture.fromImage(imageId, crossorigin, scaleMode)); }; diff --git a/src/core/display/SpriteBatch.js b/src/core/display/SpriteBatch.js index 3187777..c196fef 100644 --- a/src/core/display/SpriteBatch.js +++ b/src/core/display/SpriteBatch.js @@ -12,7 +12,8 @@ * ```js * var container = new SpriteBatch(); * - * for(var i = 0; i < 100; ++i) { + * for(var i = 0; i < 100; ++i) + * { * var sprite = new PIXI.Sprite.fromImage("myImage.png"); * container.addChild(sprite); * } @@ -25,7 +26,8 @@ */ //TODO RENAME to PARTICLE CONTAINER? -function SpriteBatch() { +function SpriteBatch() +{ DisplayObjectContainer.call(this); } @@ -38,7 +40,8 @@ * * @private */ -SpriteBatch.prototype.updateTransform = function () { +SpriteBatch.prototype.updateTransform = function () +{ // TODO don't need to! this.displayObjectUpdateTransform(); // PIXI.DisplayObjectContainer.prototype.updateTransform.call( this ); @@ -50,8 +53,10 @@ * @param renderer {WebGLRenderer} The webgl renderer * @private */ -SpriteBatch.prototype.renderWebGL = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderWebGL = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -71,8 +76,10 @@ * @param renderer {CanvasRenderer} The canvas renderer * @private */ -SpriteBatch.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -84,10 +91,12 @@ this.displayObjectUpdateTransform(); - for (var i = 0; i < this.children.length; ++i) { + for (var i = 0; i < this.children.length; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -95,9 +104,11 @@ context.globalAlpha = this.worldAlpha * child.alpha; - if (child.rotation % (Math.PI * 2) === 0) { + if (child.rotation % (Math.PI * 2) === 0) + { // this is the fastest way to optimise! - if rotation is 0 then we can avoid any kind of setTransform call - if (isRotated) { + if (isRotated) + { context.setTransform( transform.a, transform.b, @@ -122,8 +133,10 @@ frame.height * child.scale.y ); } - else { - if (!isRotated) { + else + { + if (!isRotated) + { isRotated = true; } @@ -131,7 +144,8 @@ var childTransform = child.worldTransform; - if (renderer.roundPixels) { + if (renderer.roundPixels) + { context.setTransform( childTransform.a, childTransform.b, @@ -141,7 +155,8 @@ childTransform.ty | 0 ); } - else { + else + { context.setTransform( childTransform.a, childTransform.b, diff --git a/src/core/index.js b/src/core/index.js index 3954b6f..eb4a82b 100644 --- a/src/core/index.js +++ b/src/core/index.js @@ -58,11 +58,13 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRenderer: function (width, height, options, noWebGL) { + autoDetectRenderer: function (width, height, options, noWebGL) + { width = width || 800; height = height || 600; - if (!noWebGL && require('webgl-enabled')()) { + if (!noWebGL && require('webgl-enabled')()) + { return new core.WebGLRenderer(width, height, options); } @@ -87,7 +89,8 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRecommendedRenderer: function (width, height, options) { + autoDetectRecommendedRenderer: function (width, height, options) + { var isAndroid = /Android/i.test(navigator.userAgent); return core.autoDetectRenderer(width, height, options, isAndroid); diff --git a/src/core/math/Matrix.js b/src/core/math/Matrix.js index c2f87e2..2ff4848 100644 --- a/src/core/math/Matrix.js +++ b/src/core/math/Matrix.js @@ -10,7 +10,8 @@ * @class * @namespace PIXI */ -function Matrix() { +function Matrix() +{ /** * @member {number} * @default 1 @@ -63,7 +64,8 @@ * * @param array {number[]} The array that the matrix will be populated from. */ -Matrix.prototype.fromArray = function (array) { +Matrix.prototype.fromArray = function (array) +{ this.a = array[0]; this.b = array[1]; this.c = array[3]; @@ -78,14 +80,17 @@ * @param transpose {boolean} Whether we need to transpose the matrix or not * @return {number[]} the newly created array which contains the matrix */ -Matrix.prototype.toArray = function (transpose) { - if (!this.array) { +Matrix.prototype.toArray = function (transpose) +{ + if (!this.array) + { this.array = new Float32Array(9); } var array = this.array; - if (transpose) { + if (transpose) + { array[0] = this.a; array[1] = this.b; array[2] = 0; @@ -96,7 +101,8 @@ array[7] = this.ty; array[8] = 1; } - else { + else + { array[0] = this.a; array[1] = this.c; array[2] = this.tx; @@ -119,7 +125,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, transformed through this matrix */ -Matrix.prototype.apply = function (pos, newPos) { +Matrix.prototype.apply = function (pos, newPos) +{ newPos = newPos || new Point(); newPos.x = this.a * pos.x + this.c * pos.y + this.tx; @@ -136,7 +143,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, inverse-transformed through this matrix */ -Matrix.prototype.applyInverse = function (pos, newPos) { +Matrix.prototype.applyInverse = function (pos, newPos) +{ newPos = newPos || new Point(); var id = 1 / (this.a * this.d + this.c * -this.b); @@ -154,7 +162,8 @@ * @param {number} y * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.translate = function (x, y) { +Matrix.prototype.translate = function (x, y) +{ this.tx += x; this.ty += y; @@ -168,7 +177,8 @@ * @param {number} y The amount to scale vertically * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.scale = function (x, y) { +Matrix.prototype.scale = function (x, y) +{ this.a *= x; this.d *= y; this.c *= x; @@ -186,7 +196,8 @@ * @param {number} angle - The angle in radians. * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.rotate = function (angle) { +Matrix.prototype.rotate = function (angle) +{ var cos = Math.cos( angle ); var sin = Math.sin( angle ); @@ -210,7 +221,8 @@ * @param {Matrix} matrix * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.append = function (matrix) { +Matrix.prototype.append = function (matrix) +{ var a1 = this.a; var b1 = this.b; var c1 = this.c; @@ -232,7 +244,8 @@ * * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.identity = function () { +Matrix.prototype.identity = function () +{ this.a = 1; this.b = 0; this.c = 0; diff --git a/src/core/math/Point.js b/src/core/math/Point.js index 7565b2d..632f346 100644 --- a/src/core/math/Point.js +++ b/src/core/math/Point.js @@ -7,7 +7,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -function Point(x, y) { +function Point(x, y) +{ /** * @member {number} * @default 0 @@ -29,7 +30,8 @@ * * @return {Point} a copy of the point */ -Point.prototype.clone = function () { +Point.prototype.clone = function () +{ return new Point(this.x, this.y); }; @@ -40,7 +42,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -Point.prototype.set = function (x, y) { +Point.prototype.set = function (x, y) +{ this.x = x || 0; this.y = y || ( (y !== 0) ? this.x : 0 ) ; }; diff --git a/src/core/math/shapes/Circle.js b/src/core/math/shapes/Circle.js index 69cfdc9..4d76efc 100644 --- a/src/core/math/shapes/Circle.js +++ b/src/core/math/shapes/Circle.js @@ -10,7 +10,8 @@ * @param y {number} The Y coordinate of the center of this circle * @param radius {number} The radius of the circle */ -function Circle(x, y, radius) { +function Circle(x, y, radius) +{ /** * @member {number} * @default 0 @@ -46,7 +47,8 @@ * @method clone * @return {Circle} a copy of the Circle */ -Circle.prototype.clone = function () { +Circle.prototype.clone = function () +{ return new Circle(this.x, this.y, this.radius); }; @@ -58,8 +60,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Circle */ -Circle.prototype.contains = function (x, y) { - if (this.radius <= 0) { +Circle.prototype.contains = function (x, y) +{ + if (this.radius <= 0) + { return false; } @@ -79,6 +83,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Circle.prototype.getBounds = function () { +Circle.prototype.getBounds = function () +{ return new Rectangle(this.x - this.radius, this.y - this.radius, this.radius * 2, this.radius * 2); }; diff --git a/src/core/math/shapes/Ellipse.js b/src/core/math/shapes/Ellipse.js index 4f2d066..fefd01a 100644 --- a/src/core/math/shapes/Ellipse.js +++ b/src/core/math/shapes/Ellipse.js @@ -11,7 +11,8 @@ * @param width {number} The half width of this ellipse * @param height {number} The half height of this ellipse */ -function Ellipse(x, y, width, height) { +function Ellipse(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -53,7 +54,8 @@ * @method clone * @return {Ellipse} a copy of the ellipse */ -Ellipse.prototype.clone = function () { +Ellipse.prototype.clone = function () +{ return new Ellipse(this.x, this.y, this.width, this.height); }; @@ -65,8 +67,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coords are within this ellipse */ -Ellipse.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Ellipse.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } @@ -86,6 +90,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Ellipse.prototype.getBounds = function () { +Ellipse.prototype.getBounds = function () +{ return new Rectangle(this.x - this.width, this.y - this.height, this.width, this.height); }; diff --git a/src/core/math/shapes/Polygon.js b/src/core/math/shapes/Polygon.js index ae89148..fea6d37 100644 --- a/src/core/math/shapes/Polygon.js +++ b/src/core/math/shapes/Polygon.js @@ -10,16 +10,20 @@ * arguments passed can be flat x,y values e.g. `new Polygon(x,y, x,y, x,y, ...)` where `x` and `y` are * Numbers. */ -function Polygon(points) { +function Polygon(points) +{ //if points isn't an array, use arguments as the array - if (!(points instanceof Array)) { + if (!(points instanceof Array)) + { points = Array.prototype.slice.call(arguments); } //if this is a flat array of numbers, convert it to points - if (points[0] instanceof Point) { + if (points[0] instanceof Point) + { var p = []; - for (var i = 0, il = points.length; i < il; i++) { + for (var i = 0, il = points.length; i < il; i++) + { p.push(points[i].x, points[i].y); } @@ -51,7 +55,8 @@ * * @return {Polygon} a copy of the polygon */ -Polygon.prototype.clone = function () { +Polygon.prototype.clone = function () +{ return new Polygon(this.points.slice()); }; @@ -62,19 +67,22 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this polygon */ -Polygon.prototype.contains = function (x, y) { +Polygon.prototype.contains = function (x, y) +{ var inside = false; // use some raycasting to test hits // https://github.com/substack/point-in-polygon/blob/master/index.js var length = this.points.length / 2; - for (var i = 0, j = length - 1; i < length; j = i++) { + for (var i = 0, j = length - 1; i < length; j = i++) + { var xi = this.points[i * 2], yi = this.points[i * 2 + 1], xj = this.points[j * 2], yj = this.points[j * 2 + 1], intersect = ((yi > y) !== (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi); - if (intersect) { + if (intersect) + { inside = !inside; } } diff --git a/src/core/math/shapes/Rectangle.js b/src/core/math/shapes/Rectangle.js index 16ac62a..4008b68 100644 --- a/src/core/math/shapes/Rectangle.js +++ b/src/core/math/shapes/Rectangle.js @@ -10,7 +10,8 @@ * @param width {number} The overall width of this rectangle * @param height {number} The overall height of this rectangle */ -function Rectangle(x, y, width, height) { +function Rectangle(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -60,7 +61,8 @@ * * @return {Rectangle} a copy of the rectangle */ -Rectangle.prototype.clone = function () { +Rectangle.prototype.clone = function () +{ return new Rectangle(this.x, this.y, this.width, this.height); }; @@ -71,13 +73,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rectangle */ -Rectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Rectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/math/shapes/RoundedRectangle.js b/src/core/math/shapes/RoundedRectangle.js index 27d286e..7bf6411 100644 --- a/src/core/math/shapes/RoundedRectangle.js +++ b/src/core/math/shapes/RoundedRectangle.js @@ -11,7 +11,8 @@ * @param height {number} The overall height of this rounded rectangle * @param radius {number} Controls the radius of the rounded corners */ -function RoundedRectangle(x, y, width, height, radius) { +function RoundedRectangle(x, y, width, height, radius) +{ /** * @member {number} * @default 0 @@ -58,7 +59,8 @@ * * @return {RoundedRectangle} a copy of the rounded rectangle */ -RoundedRectangle.prototype.clone = function () { +RoundedRectangle.prototype.clone = function () +{ return new RoundedRectangle(this.x, this.y, this.width, this.height, this.radius); }; @@ -69,13 +71,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rounded Rectangle */ -RoundedRectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +RoundedRectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/primitives/Graphics.js b/src/core/primitives/Graphics.js index 261c534..e902d2a 100644 --- a/src/core/primitives/Graphics.js +++ b/src/core/primitives/Graphics.js @@ -16,7 +16,8 @@ * @extends DisplayObjectContainer * @namespace PIXI */ -function Graphics() { +function Graphics() +{ DisplayObjectContainer.call(this); this.renderable = true; @@ -154,16 +155,20 @@ * @private */ cacheAsBitmap: { - get: function () { + get: function () + { return this._cacheAsBitmap; }, - set: function (value) { + set: function (value) + { this._cacheAsBitmap = value; - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._generateCachedSprite(); } - else { + else + { this.destroyCachedSprite(); this.dirty = true; } @@ -176,7 +181,8 @@ * * @return {Graphics} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ var clone = new Graphics(); clone.renderable = this.renderable; @@ -192,7 +198,8 @@ clone.cachedSpriteDirty = this.cachedSpriteDirty; // copy graphics data - for (var i = 0; i < this.graphicsData.length; ++i) { + for (var i = 0; i < this.graphicsData.length; ++i) + { clone.graphicsData.push(this.graphicsData.clone()); } @@ -211,17 +218,21 @@ * @param alpha {number} alpha of the line to draw, will update the objects stored style * @return {Graphics} */ -Graphics.prototype.lineStyle = function (lineWidth, color, alpha) { +Graphics.prototype.lineStyle = function (lineWidth, color, alpha) +{ this.lineWidth = lineWidth || 0; this.lineColor = color || 0; this.lineAlpha = (arguments.length < 3) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length) + { // halfway through a line? start a new one! this.drawShape( new math.Polygon( this.currentPath.shape.points.slice(-2) )); } - else { + else + { // otherwise its empty so lets just set the line properties this.currentPath.lineWidth = this.lineWidth; this.currentPath.lineColor = this.lineColor; @@ -239,7 +250,8 @@ * @param y {number} the Y coordinate to move to * @return {Graphics} */ -Graphics.prototype.moveTo = function (x, y) { +Graphics.prototype.moveTo = function (x, y) +{ this.drawShape(new math.Polygon([x,y])); return this; @@ -253,7 +265,8 @@ * @param y {number} the Y coordinate to draw to * @return {Graphics} */ -Graphics.prototype.lineTo = function (x, y) { +Graphics.prototype.lineTo = function (x, y) +{ this.currentPath.shape.points.push(x, y); this.dirty = true; @@ -270,13 +283,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -285,7 +302,8 @@ n = 20, points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { this.moveTo(0, 0); } @@ -293,7 +311,8 @@ var fromY = points[points.length-1]; var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; xa = fromX + ( (cpX - fromX) * j ); @@ -319,13 +338,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -342,7 +365,8 @@ var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; dt = (1 - j); @@ -373,13 +397,17 @@ * @param radius {number} The radius of the arc * @return {Graphics} */ -Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points.push(x1, y1); } } - else { + else + { this.moveTo(x1, y1); } @@ -392,12 +420,15 @@ b2 = x2 - x1, mm = Math.abs(a1 * b2 - b1 * a2); - if (mm < 1.0e-8 || radius === 0) { - if (points[points.length-2] !== x1 || points[points.length-1] !== y1) { + if (mm < 1.0e-8 || radius === 0) + { + if (points[points.length-2] !== x1 || points[points.length-1] !== y1) + { points.push(x1, y1); } } - else { + else + { var dd = a1 * a1 + b1 * b1, cc = a2 * a2 + b2 * b2, tt = a1 * a2 + b1 * b2, @@ -433,42 +464,51 @@ * @param anticlockwise {boolean} Optional. Specifies whether the drawing should be counterclockwise or clockwise. False is default, and indicates clockwise, while true indicates counter-clockwise. * @return {Graphics} */ -Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) { +Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) +{ var startX = cx + Math.cos(startAngle) * radius; var startY = cy + Math.sin(startAngle) * radius; var points; // TODO - This if-else makes no sense. It uses currentPath in the else where it doesn't exist... - if (this.currentPath) { + if (this.currentPath) + { points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { points.push(startX, startY); } - else if (points[points.length-2] !== startX || points[points.length-1] !== startY) { + else if (points[points.length-2] !== startX || points[points.length-1] !== startY) + { points.push(startX, startY); } } - else { + else + { this.moveTo(startX, startY); points = this.currentPath.shape.points; } - if (startAngle === endAngle) { + if (startAngle === endAngle) + { return this; } - if (!anticlockwise && endAngle <= startAngle) { + if (!anticlockwise && endAngle <= startAngle) + { endAngle += Math.PI * 2; } - else if (anticlockwise && startAngle <= endAngle) { + else if (anticlockwise && startAngle <= endAngle) + { startAngle += Math.PI * 2; } var sweep = anticlockwise ? (startAngle - endAngle) *-1 : (endAngle - startAngle); var segs = (Math.abs(sweep)/ (Math.PI * 2)) * 40; - if (sweep === 0) { + if (sweep === 0) + { return this; } @@ -482,7 +522,8 @@ var remainder = ( segMinus % 1 ) / segMinus; - for (var i = 0; i <= segMinus; ++i) { + for (var i = 0; i <= segMinus; ++i) + { var real = i + remainder * i; var angle = ((theta) + startAngle + (theta2 * real)); @@ -506,13 +547,16 @@ * @param alpha {number} the alpha of the fill * @return {Graphics} */ -Graphics.prototype.beginFill = function (color, alpha) { +Graphics.prototype.beginFill = function (color, alpha) +{ this.filling = true; this.fillColor = color || 0; this.fillAlpha = (alpha === undefined) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length <= 2) + { this.currentPath.fill = this.filling; this.currentPath.fillColor = this.fillColor; this.currentPath.fillAlpha = this.fillAlpha; @@ -526,7 +570,8 @@ * * @return {Graphics} */ -Graphics.prototype.endFill = function () { +Graphics.prototype.endFill = function () +{ this.filling = false; this.fillColor = null; this.fillAlpha = 1; @@ -542,7 +587,8 @@ * @param height {number} The height of the rectangle * @return {Graphics} */ -Graphics.prototype.drawRect = function ( x, y, width, height ) { +Graphics.prototype.drawRect = function ( x, y, width, height ) +{ this.drawShape(new math.Rectangle(x,y, width, height)); return this; @@ -556,7 +602,8 @@ * @param height {number} The height of the rectangle * @param radius {number} Radius of the rectangle corners */ -Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) { +Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) +{ this.drawShape(new math.RoundedRectangle(x, y, width, height, radius)); return this; @@ -570,7 +617,8 @@ * @param radius {number} The radius of the circle * @return {Graphics} */ -Graphics.prototype.drawCircle = function (x, y, radius) { +Graphics.prototype.drawCircle = function (x, y, radius) +{ this.drawShape(new math.Circle(x,y, radius)); return this; @@ -585,7 +633,8 @@ * @param height {number} The half height of the ellipse * @return {Graphics} */ -Graphics.prototype.drawEllipse = function (x, y, width, height) { +Graphics.prototype.drawEllipse = function (x, y, width, height) +{ this.drawShape(new math.Ellipse(x, y, width, height)); return this; @@ -597,8 +646,10 @@ * @param path {Array} The path data used to construct the polygon. * @return {Graphics} */ -Graphics.prototype.drawPolygon = function (path) { - if (!(path instanceof Array)) { +Graphics.prototype.drawPolygon = function (path) +{ + if (!(path instanceof Array)) + { path = Array.prototype.slice.call(arguments); } @@ -612,7 +663,8 @@ * * @return {Graphics} */ -Graphics.prototype.clear = function () { +Graphics.prototype.clear = function () +{ this.lineWidth = 0; this.filling = false; @@ -631,7 +683,8 @@ * @param scaleMode {number} Should be one of the scaleMode consts * @return {Texture} a texture of the graphics object */ -Graphics.prototype.generateTexture = function (resolution, scaleMode) { +Graphics.prototype.generateTexture = function (resolution, scaleMode) +{ resolution = resolution || 1; var bounds = this.getBounds(); @@ -655,17 +708,21 @@ * * @param renderer {WebGLRenderer} */ -Graphics.prototype._renderWebGL = function (renderer) { +Graphics.prototype._renderWebGL = function (renderer) +{ // if the sprite is not visible or the alpha is 0 then no need to render this element - if (this.isMask === true) { + if (this.isMask === true) + { return; } // this code may still be needed so leaving for now.. - // + // /* - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture on the gpu too! @@ -681,17 +738,24 @@ return; } - */ - - // check if the webgl graphic needs to be updated - if (this.glDirty) { - this.dirty = true; - this.glDirty = false; - } + else */ - renderer.setObjectRendererer(renderer.graphicsRenderer); - renderer.graphicsRenderer.render(this); + renderer.spriteBatch.stop(); + renderer.blendModeManager.setBlendMode(this.blendMode); + // check blend mode + renderer.blendModeManager.setBlendMode( this.blendMode ); + + // check if the webgl graphic needs to be updated + if (this.glDirty) + { + this.dirty = true; + this.glDirty = false; + } + + WebGLGraphics.renderGraphics(this, renderer); + + renderer.spriteBatch.start(); }; /** @@ -700,14 +764,18 @@ * @param renderer {CanvasRenderer} * @private */ -Graphics.prototype.renderCanvas = function (renderer) { +Graphics.prototype.renderCanvas = function (renderer) +{ // 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.isMask === true) { + if (!this.visible || this.alpha <= 0 || this.isMask === true) + { return; } - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture @@ -723,16 +791,19 @@ return; } - else { + else + { var context = renderer.context; var transform = this.worldTransform; - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } @@ -748,11 +819,13 @@ CanvasGraphics.renderGraphics(this, context); - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } } @@ -763,13 +836,16 @@ * * @return {Rectangle} the rectangular bounding area */ -Graphics.prototype.getBounds = function (matrix) { +Graphics.prototype.getBounds = function (matrix) +{ // return an empty object if the item is a mask! - if (this.isMask) { + if (this.isMask) + { return math.Rectangle.EMPTY; } - if (this.dirty) { + if (this.dirty) + { this.updateLocalBounds(); this.glDirty = true; @@ -841,23 +917,27 @@ * Update the bounds of the object * */ -Graphics.prototype.updateLocalBounds = function () { +Graphics.prototype.updateLocalBounds = function () +{ var minX = Infinity; var maxX = -Infinity; var minY = Infinity; var maxY = -Infinity; - if (this.graphicsData.length) { + if (this.graphicsData.length) + { var shape, points, x, y, w, h; - for (var i = 0; i < this.graphicsData.length; i++) { + for (var i = 0; i < this.graphicsData.length; i++) + { var data = this.graphicsData[i]; var type = data.type; var lineWidth = data.lineWidth; shape = data.shape; - if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) { + if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) + { x = shape.x - lineWidth/2; y = shape.y - lineWidth/2; w = shape.width + lineWidth; @@ -869,7 +949,8 @@ minY = y < minY ? y : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.CIRC) { + else if (type === CONST.SHAPES.CIRC) + { x = shape.x; y = shape.y; w = shape.radius + lineWidth/2; @@ -881,7 +962,8 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.ELIP) { + else if (type === CONST.SHAPES.ELIP) + { x = shape.x; y = shape.y; w = shape.width + lineWidth/2; @@ -893,11 +975,13 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else { + else + { // POLY points = shape.points; - for (var j = 0; j < points.length; j += 2) { + for (var j = 0; j < points.length; j += 2) + { x = points[j]; y = points[j+1]; @@ -910,7 +994,8 @@ } } } - else { + else + { minX = 0; maxX = 0; minY = 0; @@ -931,10 +1016,12 @@ * * @private */ -Graphics.prototype._generateCachedSprite = function () { +Graphics.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { var canvasBuffer = new CanvasBuffer(bounds.width, bounds.height); var texture = Texture.fromCanvas(canvasBuffer.canvas); @@ -943,7 +1030,8 @@ this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.buffer.resize(bounds.width, bounds.height); } @@ -968,7 +1056,8 @@ * * @private */ -Graphics.prototype.updateCachedSpriteTexture = function () { +Graphics.prototype.updateCachedSpriteTexture = function () +{ var cachedSprite = this._cachedSprite; var texture = cachedSprite.texture; var canvas = cachedSprite.buffer.canvas; @@ -989,7 +1078,8 @@ * Destroys a previous cached sprite. * */ -Graphics.prototype.destroyCachedSprite = function () { +Graphics.prototype.destroyCachedSprite = function () +{ this._cachedSprite.texture.destroy(true); // let the gc collect the unused sprite @@ -1003,10 +1093,13 @@ * @param {Circle|Rectangle|Ellipse|Line|Polygon} shape The Shape object to draw. * @return {GraphicsData} The generated GraphicsData object. */ -Graphics.prototype.drawShape = function (shape) { - if (this.currentPath) { +Graphics.prototype.drawShape = function (shape) +{ + if (this.currentPath) + { // check current path! - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath.shape.points.length <= 2) + { this.graphicsData.pop(); } } @@ -1017,7 +1110,8 @@ this.graphicsData.push(data); - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { data.shape.closed = this.filling; this.currentPath = data; } diff --git a/src/core/primitives/GraphicsData.js b/src/core/primitives/GraphicsData.js index 99decbe..788f6f2 100644 --- a/src/core/primitives/GraphicsData.js +++ b/src/core/primitives/GraphicsData.js @@ -4,7 +4,8 @@ * @class * @namespace PIXI */ -function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) { +function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) +{ this.lineWidth = lineWidth; this.lineColor = lineColor; this.lineAlpha = lineAlpha; @@ -27,7 +28,8 @@ * * @return {GraphicsData} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ return new GraphicsData( this.lineWidth, this.lineColor, diff --git a/src/core/renderers/canvas/CanvasRenderer.js b/src/core/renderers/canvas/CanvasRenderer.js index 15a0978..7aebd44 100644 --- a/src/core/renderers/canvas/CanvasRenderer.js +++ b/src/core/renderers/canvas/CanvasRenderer.js @@ -17,17 +17,22 @@ * @param [options.resolution=1] {number} the resolution of the renderer retina would be 2 * @param [options.clearBeforeRender=true] {boolean} This sets if the CanvasRenderer will clear the canvas or not before the new render pass. */ -function CanvasRenderer(width, height, options) { +function CanvasRenderer(width, height, options) +{ utils.sayHello('Canvas'); - if (options) { - for (var i in CONST.defaultRenderOptions) { - if (typeof options[i] === 'undefined') { + if (options) + { + for (var i in CONST.defaultRenderOptions) + { + if (typeof options[i] === 'undefined') + { options[i] = CONST.defaultRenderOptions[i]; } } } - else { + else + { options = CONST.defaultRenderOptions; } @@ -156,19 +161,24 @@ this.smoothProperty = null; - if (this.context.imageSmoothingEnabled) { + if (this.context.imageSmoothingEnabled) + { this.smoothProperty = 'imageSmoothingEnabled'; } - else if (this.context.webkitImageSmoothingEnabled) { + else if (this.context.webkitImageSmoothingEnabled) + { this.smoothProperty = 'webkitImageSmoothingEnabled'; } - else if (this.context.mozImageSmoothingEnabled) { + else if (this.context.mozImageSmoothingEnabled) + { this.smoothProperty = 'mozImageSmoothingEnabled'; } - else if (this.context.oImageSmoothingEnabled) { + else if (this.context.oImageSmoothingEnabled) + { this.smoothProperty = 'oImageSmoothingEnabled'; } - else if (this.context.msImageSmoothingEnabled) { + else if (this.context.msImageSmoothingEnabled) + { this.smoothProperty = 'msImageSmoothingEnabled'; } @@ -193,10 +203,12 @@ * @memberof CanvasRenderer# */ backgroundColor: { - get: function () { + get: function () + { return this._backgroundColor; }, - set: function (val) { + set: function (val) + { this._backgroundColor = val; this._backgroundColorString = utils.hex2string(val); } @@ -208,7 +220,8 @@ * * @param object {DisplayObject} the object to be rendered */ -CanvasRenderer.prototype.render = function (object) { +CanvasRenderer.prototype.render = function (object) +{ object.updateTransform(); this.context.setTransform(1,0,0,1,0,0); @@ -218,16 +231,20 @@ this.currentBlendMode = CONST.blendModes.NORMAL; this.context.globalCompositeOperation = this.blendModes[CONST.blendModes.NORMAL]; - if (navigator.isCocoonJS && this.view.screencanvas) { + if (navigator.isCocoonJS && this.view.screencanvas) + { this.context.fillStyle = 'black'; this.context.clear(); } - if (this.clearBeforeRender) { - if (this.transparent) { + if (this.clearBeforeRender) + { + if (this.transparent) + { this.context.clearRect(0, 0, this.width, this.height); } - else { + else + { this.context.fillStyle = this._backgroundColorString; this.context.fillRect(0, 0, this.width , this.height); } @@ -241,8 +258,10 @@ * * @param [removeView=false] {boolean} Removes the Canvas element from the DOM. */ -CanvasRenderer.prototype.destroy = function (removeView) { - if (removeView && this.view.parent) { +CanvasRenderer.prototype.destroy = function (removeView) +{ + if (removeView && this.view.parent) + { this.view.parent.removeChild(this.view); } @@ -257,14 +276,16 @@ * @param width {number} the new width of the canvas view * @param height {number} the new height of the canvas view */ -CanvasRenderer.prototype.resize = function (width, height) { +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) { + if (this.autoResize) + { this.view.style.width = this.width / this.resolution + 'px'; this.view.style.height = this.height / this.resolution + 'px'; } @@ -276,7 +297,8 @@ * @param displayObject {DisplayObject} The displayObject to render * @private */ -CanvasRenderer.prototype.renderDisplayObject = function (displayObject) { +CanvasRenderer.prototype.renderDisplayObject = function (displayObject) +{ displayObject.renderCanvas(this); }; @@ -285,11 +307,14 @@ * * @private */ -CanvasRenderer.prototype._mapBlendModes = function () { - if (!this.blendModes) { +CanvasRenderer.prototype._mapBlendModes = function () +{ + if (!this.blendModes) + { this.blendModes = {}; - if (utils.canUseNewCanvasBlendModes()) { + if (utils.canUseNewCanvasBlendModes()) + { this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? this.blendModes[CONST.blendModes.MULTIPLY] = 'multiply'; @@ -308,7 +333,8 @@ this.blendModes[CONST.blendModes.COLOR] = 'color'; this.blendModes[CONST.blendModes.LUMINOSITY] = 'luminosity'; } - else { + else + { // this means that the browser does not support the cool new blend modes in canvas 'cough' ie 'cough' this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? diff --git a/src/core/renderers/canvas/utils/CanvasBuffer.js b/src/core/renderers/canvas/utils/CanvasBuffer.js index ebe5d47..b183a66 100644 --- a/src/core/renderers/canvas/utils/CanvasBuffer.js +++ b/src/core/renderers/canvas/utils/CanvasBuffer.js @@ -6,7 +6,8 @@ * @param width {number} the width for the newly created canvas * @param height {number} the height for the newly created canvas */ -function CanvasBuffer(width, height) { +function CanvasBuffer(width, height) +{ /** * The Canvas object that belongs to this CanvasBuffer. * @@ -36,10 +37,12 @@ * @memberof CanvasBuffer# */ width: { - get: function () { + get: function () + { return this.canvas.width; }, - set: function (val) { + set: function (val) + { this.canvas.width = val; } }, @@ -50,10 +53,12 @@ * @memberof CanvasBuffer# */ height: { - get: function () { + get: function () + { return this.canvas.height; }, - set: function (val) { + set: function (val) + { this.canvas.height = val; } } @@ -64,7 +69,8 @@ * * @private */ -CanvasBuffer.prototype.clear = function () { +CanvasBuffer.prototype.clear = function () +{ this.context.setTransform(1, 0, 0, 1, 0, 0); this.context.clearRect(0,0, this.canvas.width, this.canvas.height); }; @@ -75,7 +81,8 @@ * @param width {number} the new width of the canvas * @param height {number} the new height of the canvas */ -CanvasBuffer.prototype.resize = function (width, height) { +CanvasBuffer.prototype.resize = function (width, height) +{ this.canvas.width = width; this.canvas.height = height; }; diff --git a/src/core/renderers/canvas/utils/CanvasGraphics.js b/src/core/renderers/canvas/utils/CanvasGraphics.js index c7eaa2a..3f2a91f 100644 --- a/src/core/renderers/canvas/utils/CanvasGraphics.js +++ b/src/core/renderers/canvas/utils/CanvasGraphics.js @@ -13,15 +13,18 @@ * @param graphics {Graphics} the actual graphics object to render * @param context {CanvasRenderingContext2D} the 2d drawing method of the canvas */ -CanvasGraphics.renderGraphics = function (graphics, context) { +CanvasGraphics.renderGraphics = function (graphics, context) +{ var worldAlpha = graphics.worldAlpha; - if (graphics.dirty) { + if (graphics.dirty) + { this.updateGraphicsTint(graphics); graphics.dirty = false; } - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; @@ -30,69 +33,82 @@ context.lineWidth = data.lineWidth; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { context.beginPath(); var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } - if (shape.closed) { + if (shape.closed) + { context.lineTo(points[0], points[1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fillRect(shape.x, shape.y, shape.width, shape.height); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.strokeRect(shape.x, shape.y, shape.width, shape.height); } } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.beginPath(); context.arc(shape.x, shape.y, shape.radius,0,2*Math.PI); context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas var w = shape.width * 2; @@ -119,18 +135,21 @@ context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; var width = shape.width; @@ -152,13 +171,15 @@ context.quadraticCurveTo(rx, ry, rx, ry + radius); context.closePath(); - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); @@ -174,45 +195,54 @@ * @param graphics {Graphics} the graphics which will be used as a mask * @param context {CanvasRenderingContext2D} the context 2d method of the canvas */ -CanvasGraphics.renderGraphicsMask = function (graphics, context) { +CanvasGraphics.renderGraphicsMask = function (graphics, context) +{ var len = graphics.graphicsData.length; - if (len === 0) { + if (len === 0) + { return; } context.beginPath(); - for (var i = 0; i < len; i++) { + for (var i = 0; i < len; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { context.rect(shape.x, shape.y, shape.width, shape.height); context.closePath(); } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.arc(shape.x, shape.y, shape.radius, 0, 2 * Math.PI); context.closePath(); } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas @@ -237,7 +267,8 @@ context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); context.closePath(); } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; @@ -262,8 +293,10 @@ } }; -CanvasGraphics.updateGraphicsTint = function (graphics) { - if (graphics.tint === 0xFFFFFF) { +CanvasGraphics.updateGraphicsTint = function (graphics) +{ + if (graphics.tint === 0xFFFFFF) + { return; } @@ -271,7 +304,8 @@ var tintG = (graphics.tint >> 8 & 0xFF) / 255; var tintB = (graphics.tint & 0xFF)/ 255; - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var fillColor = data.fillColor | 0; diff --git a/src/core/renderers/canvas/utils/CanvasMaskManager.js b/src/core/renderers/canvas/utils/CanvasMaskManager.js index e04a733..9827d36 100644 --- a/src/core/renderers/canvas/utils/CanvasMaskManager.js +++ b/src/core/renderers/canvas/utils/CanvasMaskManager.js @@ -6,7 +6,8 @@ * @class * @namespace PIXI */ -function CanvasMaskManager() {} +function CanvasMaskManager() +{} CanvasMaskManager.prototype.constructor = CanvasMaskManager; module.exports = CanvasMaskManager; @@ -17,7 +18,8 @@ * @param maskData {object} the maskData that will be pushed * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.pushMask = function (maskData, renderer) { +CanvasMaskManager.prototype.pushMask = function (maskData, renderer) +{ renderer.context.save(); var cacheAlpha = maskData.alpha; @@ -45,6 +47,7 @@ * * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.popMask = function (renderer) { +CanvasMaskManager.prototype.popMask = function (renderer) +{ renderer.context.restore(); }; diff --git a/src/core/renderers/canvas/utils/CanvasTinter.js b/src/core/renderers/canvas/utils/CanvasTinter.js index 17e0529..d2fb1bc 100644 --- a/src/core/renderers/canvas/utils/CanvasTinter.js +++ b/src/core/renderers/canvas/utils/CanvasTinter.js @@ -14,7 +14,8 @@ * @param color {number} the color to use to tint the sprite with * @return {HTMLCanvasElement} The tinted canvas */ -CanvasTinter.getTintedTexture = function (sprite, color) { +CanvasTinter.getTintedTexture = function (sprite, color) +{ var texture = sprite.texture; color = CanvasTinter.roundColor(color); @@ -23,7 +24,8 @@ texture.tintCache = texture.tintCache || {}; - if (texture.tintCache[stringColor]) { + if (texture.tintCache[stringColor]) + { return texture.tintCache[stringColor]; } @@ -33,14 +35,16 @@ //CanvasTinter.tintWithPerPixel(texture, stringColor, canvas); CanvasTinter.tintMethod(texture, color, canvas); - if (CanvasTinter.convertTintToImage) { + if (CanvasTinter.convertTintToImage) + { // is this better? var tintImage = new Image(); tintImage.src = canvas.toDataURL(); texture.tintCache[stringColor] = tintImage; } - else { + else + { texture.tintCache[stringColor] = canvas; // if we are not converting the texture to an image then we need to lose the reference to the canvas CanvasTinter.canvas = null; @@ -56,7 +60,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithMultiply = function (texture, color, canvas) { +CanvasTinter.tintWithMultiply = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -104,7 +109,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithOverlay = function (texture, color, canvas) { +CanvasTinter.tintWithOverlay = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -139,7 +145,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithPerPixel = function (texture, color, canvas) { +CanvasTinter.tintWithPerPixel = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -167,7 +174,8 @@ var pixels = pixelData.data; - for (var i = 0; i < pixels.length; i += 4) { + for (var i = 0; i < pixels.length; i += 4) + { pixels[i+0] *= r; pixels[i+1] *= g; pixels[i+2] *= b; @@ -181,7 +189,8 @@ * * @param color {number} the color to round, should be a hex color */ -CanvasTinter.roundColor = function (color) { +CanvasTinter.roundColor = function (color) +{ var step = CanvasTinter.cacheStepsPerColorChannel; var rgbValues = utils.hex2rgb(color); diff --git a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js index 9f2f89a..35edbaf 100644 --- a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js +++ b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLBlendModeManager(renderer) { +function WebGLBlendModeManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -23,8 +24,10 @@ * * @param blendMode {number} the blendMode, should be a Pixi const, such as BlendModes.ADD */ -WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) { - if (this.currentBlendMode === blendMode) { +WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) +{ + if (this.currentBlendMode === blendMode) + { return false; } diff --git a/src/core/renderers/webgl/managers/WebGLFilterManager.js b/src/core/renderers/webgl/managers/WebGLFilterManager.js index 1179258..2dac048 100644 --- a/src/core/renderers/webgl/managers/WebGLFilterManager.js +++ b/src/core/renderers/webgl/managers/WebGLFilterManager.js @@ -7,7 +7,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLFilterManager(renderer) { +function WebGLFilterManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -32,7 +33,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.texturePool.length = 0; self.initShaderBuffers(); }); @@ -46,7 +48,8 @@ * @param renderer {WebGLRenderer} * @param buffer {ArrayBuffer} */ -WebGLFilterManager.prototype.begin = function (buffer) { +WebGLFilterManager.prototype.begin = function (buffer) +{ this.defaultShader = this.renderer.shaderManager.defaultShader; this.width = this.renderer.projection.x * 2; @@ -60,7 +63,8 @@ * * @param filterBlock {object} the filter that will be pushed to the current filter stack */ -WebGLFilterManager.prototype.pushFilter = function (filterBlock) { +WebGLFilterManager.prototype.pushFilter = function (filterBlock) +{ var gl = this.renderer.gl; var projection = this.renderer.projection; @@ -78,10 +82,12 @@ this.offsetY += filterBlock._filterArea.y; var texture = this.texturePool.pop(); - if (!texture) { + if (!texture) + { texture = new FilterTexture(this.renderer.gl, this.width, this.height); } - else { + else + { texture.resize(this.width, this.height); } @@ -98,29 +104,35 @@ var localX = filterArea.x, localY = filterArea.y; - if (filterArea.x < 0) { + if (filterArea.x < 0) + { filterArea.width += filterArea.x; filterArea.x = 0; } - if (filterArea.y < 0) { + if (filterArea.y < 0) + { filterArea.height += filterArea.y; filterArea.y = 0; } - if (localX + filterArea.width > this.width) { + if (localX + filterArea.width > this.width) + { filterArea.width = this.width - localX; } - if (localY + filterArea.height > this.height) { + if (localY + filterArea.height > this.height) + { filterArea.height = this.height - localY; } - if (filterArea.width < 0) { + if (filterArea.width < 0) + { filterArea.width = 0; } - if (filterArea.height < 0) { + if (filterArea.height < 0) + { filterArea.height = 0; } @@ -154,7 +166,8 @@ * Removes the last filter from the filter stack and doesn't return it. * */ -WebGLFilterManager.prototype.popFilter = function () { +WebGLFilterManager.prototype.popFilter = function () +{ var gl = this.renderer.gl; var filterBlock = this.filterStack.pop(); @@ -163,7 +176,8 @@ var projection = this.renderer.projection; var offset = this.renderer.offset; - if (filterBlock.filterPasses.length > 1) { + if (filterBlock.filterPasses.length > 1) + { gl.viewport(0, 0, filterArea.width, filterArea.height); gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); @@ -193,7 +207,8 @@ var inputTexture = texture; var outputTexture = this.texturePool.pop(); - if (!outputTexture) { + if (!outputTexture) + { outputTexture = new FilterTexture(this.renderer.gl, this.width, this.height); } outputTexture.resize(this.width, this.height); @@ -204,7 +219,8 @@ gl.disable(gl.BLEND); - for (var i = 0; i < filterBlock.filterPasses.length-1; i++) { + for (var i = 0; i < filterBlock.filterPasses.length-1; i++) + { var filterPass = filterBlock.filterPasses[i]; gl.bindFramebuffer(gl.FRAMEBUFFER, outputTexture.frameBuffer ); @@ -243,10 +259,12 @@ var buffer = this.buffer; // time to render the filters texture to the previous scene - if (this.filterStack.length === 0) { + if (this.filterStack.length === 0) + { gl.colorMask(true, true, true, true);//this.transparent); } - else { + else + { var currentFilter = this.filterStack[this.filterStack.length-1]; filterArea = currentFilter._filterArea; @@ -332,13 +350,15 @@ * @param width {number} the horizontal range of the filter * @param height {number} the vertical range of the filter */ -WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) { +WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) +{ // use program var gl = this.renderer.gl; var shader = filter.shaders[gl.id]; - if (!shader) { + if (!shader) + { shader = new Shader(gl); shader.fragmentSrc = filter.fragmentSrc; @@ -356,7 +376,8 @@ gl.uniform2f(shader.projectionVector, width/2, -height/2); gl.uniform2f(shader.offsetVector, 0,0); - if (filter.uniforms.dimensions) { + 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]; @@ -386,7 +407,8 @@ * Initialises the shader buffers. * */ -WebGLFilterManager.prototype.initShaderBuffers = function () { +WebGLFilterManager.prototype.initShaderBuffers = function () +{ var gl = this.renderer.gl; // create some buffers @@ -432,7 +454,8 @@ * Destroys the filter and removes it from the filter stack. * */ -WebGLFilterManager.prototype.destroy = function () { +WebGLFilterManager.prototype.destroy = function () +{ var gl = this.renderer.gl; this.filterStack = null; @@ -441,7 +464,8 @@ this.offsetY = 0; // destroy textures - for (var i = 0; i < this.texturePool.length; i++) { + for (var i = 0; i < this.texturePool.length; i++) + { this.texturePool[i].destroy(); } diff --git a/src/core/renderers/webgl/managers/WebGLManager.js b/src/core/renderers/webgl/managers/WebGLManager.js index 9d47b5c..c30cd51 100644 --- a/src/core/renderers/webgl/managers/WebGLManager.js +++ b/src/core/renderers/webgl/managers/WebGLManager.js @@ -3,7 +3,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLManager(renderer) { +function WebGLManager(renderer) +{ /** * The renderer this manager works for. * @@ -15,6 +16,7 @@ WebGLManager.prototype.constructor = WebGLManager; module.exports = WebGLManager; -WebGLManager.prototype.destroy = function () { +WebGLManager.prototype.destroy = function () +{ this.renderer = null; }; diff --git a/src/core/renderers/webgl/managers/WebGLMaskManager.js b/src/core/renderers/webgl/managers/WebGLMaskManager.js index 2f90b64..e568812 100644 --- a/src/core/renderers/webgl/managers/WebGLMaskManager.js +++ b/src/core/renderers/webgl/managers/WebGLMaskManager.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLMaskManager(renderer) { +function WebGLMaskManager(renderer) +{ WebGLManager.call(this, renderer); } @@ -19,12 +20,15 @@ * * @param maskData {any[]} */ -WebGLMaskManager.prototype.pushMask = function (maskData) { - if (maskData.dirty) { +WebGLMaskManager.prototype.pushMask = function (maskData) +{ + if (maskData.dirty) + { WebGLGraphics.updateGraphics(maskData, this.renderer.gl); } - if (!maskData._webGL[this.renderer.gl.id].data.length) { + if (!maskData._webGL[this.renderer.gl.id].data.length) + { return; } @@ -36,6 +40,7 @@ * * @param maskData {any[]} */ -WebGLMaskManager.prototype.popMask = function (maskData) { +WebGLMaskManager.prototype.popMask = function (maskData) +{ this.renderer.stencilManager.popStencil(maskData, maskData._webGL[this.renderer.gl.id].data[0], this.renderer); }; diff --git a/src/core/renderers/webgl/managers/WebGLShaderManager.js b/src/core/renderers/webgl/managers/WebGLShaderManager.js index fef071c..90c6477 100644 --- a/src/core/renderers/webgl/managers/WebGLShaderManager.js +++ b/src/core/renderers/webgl/managers/WebGLShaderManager.js @@ -10,7 +10,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLShaderManager(renderer) { +function WebGLShaderManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -28,7 +29,8 @@ */ this.tempAttribState = []; - for (var i = 0; i < this.maxAttibs; i++) { + for (var i = 0; i < this.maxAttibs; i++) + { this.attribState[i] = false; } @@ -66,7 +68,8 @@ // listen for context and update necessary shaders var self = this; - this.renderer.on('context', function (event) { + this.renderer.on('context', function (event) + { var gl = event.data; // this shader is used for rendering primitives @@ -97,29 +100,36 @@ * * @param attribs {Array} attribs */ -WebGLShaderManager.prototype.setAttribs = function (attribs) { +WebGLShaderManager.prototype.setAttribs = function (attribs) +{ // reset temp state var i; - for (i = 0; i < this.tempAttribState.length; i++) { + for (i = 0; i < this.tempAttribState.length; i++) + { this.tempAttribState[i] = false; } // set the new attribs - for (var a in attribs) { + for (var a in attribs) + { this.tempAttribState[attribs[a]] = true; } var gl = this.renderer.gl; - for (i = 0; i < this.attribState.length; i++) { - if (this.attribState[i] !== this.tempAttribState[i]) { + for (i = 0; i < this.attribState.length; i++) + { + if (this.attribState[i] !== this.tempAttribState[i]) + { this.attribState[i] = this.tempAttribState[i]; - if (this.attribState[i]) { + if (this.attribState[i]) + { gl.enableVertexAttribArray(i); } - else { + else + { gl.disableVertexAttribArray(i); } } @@ -131,8 +141,10 @@ * * @param shader {Any} */ -WebGLShaderManager.prototype.setShader = function (shader) { - if (this._currentId === shader.uuid) { +WebGLShaderManager.prototype.setShader = function (shader) +{ + if (this._currentId === shader.uuid) + { return false; } @@ -150,7 +162,8 @@ * Destroys this object. * */ -WebGLShaderManager.prototype.destroy = function () { +WebGLShaderManager.prototype.destroy = function () +{ this.attribState = null; this.tempAttribState = null; diff --git a/src/core/renderers/webgl/managers/WebGLStencilManager.js b/src/core/renderers/webgl/managers/WebGLStencilManager.js index 9ec6398..4cb0134 100644 --- a/src/core/renderers/webgl/managers/WebGLStencilManager.js +++ b/src/core/renderers/webgl/managers/WebGLStencilManager.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLStencilManager(renderer) { +function WebGLStencilManager(renderer) +{ WebGLManager.call(this, renderer); this.stencilStack = []; @@ -24,12 +25,14 @@ * @param graphics {Graphics} * @param webGLData {any[]} */ -WebGLStencilManager.prototype.pushStencil = function (graphics, webGLData) { +WebGLStencilManager.prototype.pushStencil = function (graphics, webGLData) +{ var gl = this.renderer.gl; this.bindGraphics(graphics, webGLData, this.renderer); - if (this.stencilStack.length === 0) { + if (this.stencilStack.length === 0) + { gl.enable(gl.STENCIL_TEST); gl.clear(gl.STENCIL_BUFFER_BIT); this.reverse = true; @@ -47,14 +50,17 @@ // draw the triangle strip! - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } @@ -62,31 +68,38 @@ // draw a quad to increment.. gl.drawElements(gl.TRIANGLE_FAN, 4, gl.UNSIGNED_SHORT, ( webGLData.indices.length - 4 ) * 2 ); - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); } this.reverse = !this.reverse; } - else { - if (!this.reverse) { + else + { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } - else { + 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) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); } } @@ -103,7 +116,8 @@ * @param graphics {Graphics} * @param webGLData {Array} */ -WebGLStencilManager.prototype.bindGraphics = function (graphics, webGLData) { +WebGLStencilManager.prototype.bindGraphics = function (graphics, webGLData) +{ //if (this._currentGraphics === graphics)return; this._currentGraphics = graphics; @@ -114,7 +128,8 @@ offset = this.renderer.offset, shader;// = this.renderer.shaderManager.primitiveShader; - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { shader = this.renderer.shaderManager.complexPrimitiveShader; this.renderer.shaderManager.setShader(shader); @@ -141,7 +156,8 @@ // set the index buffer! gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, webGLData.indexBuffer); } - else { + else + { //this.renderer.shaderManager.activatePrimitiveShader(); shader = this.renderer.shaderManager.primitiveShader; this.renderer.shaderManager.setShader( shader ); @@ -154,7 +170,7 @@ gl.uniform2f(shader.uniforms.offsetVector._location, -offset.x, -offset.y); gl.uniform3fv(shader.uniforms.tint._location, utils.hex2rgb(graphics.tint)); - + gl.uniform1f(shader.uniforms.alpha._location, graphics.worldAlpha); @@ -172,19 +188,22 @@ * @param graphics {Graphics} * @param webGLData {Array} */ -WebGLStencilManager.prototype.popStencil = function (graphics, webGLData) { +WebGLStencilManager.prototype.popStencil = function (graphics, webGLData) +{ var gl = this.renderer.gl; this.stencilStack.pop(); this.count--; - if (this.stencilStack.length === 0) { + if (this.stencilStack.length === 0) + { // the stack is empty! gl.disable(gl.STENCIL_TEST); } - else { + else + { var level = this.count; @@ -192,14 +211,17 @@ gl.colorMask(false, false, false, false); - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { this.reverse = !this.reverse; - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } @@ -213,31 +235,38 @@ // draw the triangle strip! gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); - if (!this.reverse) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); } } - else { + else + { // console.log("<<>>") - if (!this.reverse) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } - else { + 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) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); } } @@ -253,7 +282,8 @@ * Destroys the mask stack. * */ -WebGLStencilManager.prototype.destroy = function () { +WebGLStencilManager.prototype.destroy = function () +{ this.renderer = null; this.stencilStack = null; }; diff --git a/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js b/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js index 913ba5e..1ea7d19 100644 --- a/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js +++ b/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function ComplexPrimitiveShader(gl) { +function ComplexPrimitiveShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -24,7 +25,8 @@ 'uniform float flipY;', 'varying vec4 vColor;', - 'void main(void) {', + '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);', @@ -37,7 +39,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = vColor;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/FastShader.js b/src/core/renderers/webgl/shaders/FastShader.js index bd2e29a..2e5e060 100644 --- a/src/core/renderers/webgl/shaders/FastShader.js +++ b/src/core/renderers/webgl/shaders/FastShader.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function FastShader(gl) { +function FastShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -28,7 +29,8 @@ 'const vec2 center = vec2(-1.0, 1.0);', - 'void main(void) {', + 'void main(void) + {', ' vec2 v;', ' vec2 sv = aVertexPosition * aScale;', ' v.x = (sv.x) * cos(aRotation) - (sv.y) * sin(aRotation);', @@ -49,7 +51,8 @@ 'uniform sampler2D uSampler;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/PrimitiveShader.js b/src/core/renderers/webgl/shaders/PrimitiveShader.js index 6f25409..a25f54f 100644 --- a/src/core/renderers/webgl/shaders/PrimitiveShader.js +++ b/src/core/renderers/webgl/shaders/PrimitiveShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function PrimitiveShader(gl) { +function PrimitiveShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -23,7 +24,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + '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);', @@ -36,7 +38,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = vColor;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/Shader.js b/src/core/renderers/webgl/shaders/Shader.js index f8964f5..fd75ef5 100644 --- a/src/core/renderers/webgl/shaders/Shader.js +++ b/src/core/renderers/webgl/shaders/Shader.js @@ -6,7 +6,8 @@ * @param [fragmentSrc] {string} The source of the fragment shader. * @param [vertexSrc] {string} The source of the vertex shader. */ -function Shader(gl, vertexSrc, fragmentSrc, customUniforms, customAttributes) { +function Shader(gl, vertexSrc, fragmentSrc, customUniforms, customAttributes) +{ /** * @member {number} * @readonly @@ -33,7 +34,8 @@ dimensions: { type: '4f', value: new Float32Array(4) } }; - for (var u in customUniforms) { + for (var u in customUniforms) + { this.uniforms[u] = customUniforms[u]; } @@ -43,7 +45,8 @@ aColor: 0 }; - for (var a in customAttributes) { + for (var a in customAttributes) + { this.attributes[a] = customAttributes[a]; } @@ -66,7 +69,8 @@ 'const vec2 center = vec2(-1.0, 1.0);', - 'void main(void) {', + 'void main(void) + {', ' gl_Position = vec4( ((aVertexPosition + offsetVector) / projectionVector) + center , 0.0, 1.0);', ' vTextureCoord = aTextureCoord;', ' vColor = vec4(aColor.rgb * aColor.a, aColor.a);', @@ -85,7 +89,8 @@ 'uniform sampler2D uSampler;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;', '}' ].join('\n'); @@ -96,7 +101,8 @@ Shader.prototype.constructor = Shader; module.exports = Shader; -Shader.prototype.init = function () { +Shader.prototype.init = function () +{ this.compile(); this.gl.useProgram(this.program); @@ -105,14 +111,18 @@ this.cacheAttributeLocations(Object.keys(this.attributes)); }; -Shader.prototype.cacheUniformLocations = function (keys) { - for (var i = 0; i < keys.length; ++i) { +Shader.prototype.cacheUniformLocations = function (keys) +{ + for (var i = 0; i < keys.length; ++i) + { this.uniforms[keys[i]]._location = this.gl.getUniformLocation(this.program, keys[i]); } }; -Shader.prototype.cacheAttributeLocations = function (keys) { - for (var i = 0; i < keys.length; ++i) { +Shader.prototype.cacheAttributeLocations = function (keys) +{ + for (var i = 0; i < keys.length; ++i) + { this.attributes[keys[i]] = this.gl.getAttribLocation(this.program, keys[i]); } @@ -124,14 +134,16 @@ // 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.attributes.aColor === -1) { + // if (this.attributes.aColor === -1) + { // this.attributes.aColor = 2; // } // End worst hack eva // }; -Shader.prototype.compile = function () { +Shader.prototype.compile = function () +{ var gl = this.gl; var glVertShader = this._glCompile(gl.VERTEX_SHADER, this.vertexSrc); @@ -144,13 +156,15 @@ gl.linkProgram(program); // if linking fails, then log and cleanup - if (!gl.getProgramParameter(program, gl.LINK_STATUS)) { + if (!gl.getProgramParameter(program, gl.LINK_STATUS)) + { window.console.error('Pixi.js Error: Could not initialize shader.'); window.console.error('gl.VALIDATE_STATUS', gl.getProgramParameter(program, gl.VALIDATE_STATUS)); window.console.error('gl.getError()', gl.getError()); // if there is a program info log, log it - if (gl.getProgramInfoLog(program) !== '') { + if (gl.getProgramInfoLog(program) !== '') + { window.console.warn('Pixi.js Warning: gl.getProgramInfoLog()', gl.getProgramInfoLog(program)); } @@ -165,18 +179,21 @@ return (this.program = program); }; -Shader.prototype.syncUniforms = function () { +Shader.prototype.syncUniforms = function () +{ var gl = this.gl; this.textureCount = 1; - for (var key in this.uniforms) { + for (var key in this.uniforms) + { var uniform = this.uniforms[key], location = uniform._location, value = uniform.value, i, il; - switch (uniform.type) { + switch (uniform.type) + { // single int value case 'i': case '1i': @@ -282,7 +299,8 @@ // a Color Value case 'c': - if (typeof value === 'number') { + if (typeof value === 'number') + { value = utils.hex2rgb(value); } @@ -311,11 +329,13 @@ // array of 2D Point objects case 'v2v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(2 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 2] = value[i].x; uniform._array[i * 2 + 1] = value[i].y; } @@ -325,11 +345,13 @@ // array of 3D Point objects case 'v3v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(3 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 3] = value[i].x; uniform._array[i * 3 + 1] = value[i].y; uniform._array[i * 3 + 2] = value[i].z; @@ -341,11 +363,13 @@ // array of 4D Point objects case 'v4v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(4 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 4] = value[i].x; uniform._array[i * 4 + 1] = value[i].y; uniform._array[i * 4 + 2] = value[i].z; @@ -359,7 +383,8 @@ // PIXI.Texture case 't': case 'sampler2D': - if (!uniform.value || !uniform.value.baseTexture || !uniform.value.baseTexture.hasLoaded) { + if (!uniform.value || !uniform.value.baseTexture || !uniform.value.baseTexture.hasLoaded) + { break; } @@ -376,7 +401,8 @@ this.textureCount++; // initialize the texture if we haven't yet - if (!uniform._init) { + if (!uniform._init) + { this.initSampler2D(uniform); uniform._init = true; @@ -394,11 +420,13 @@ * Initialises a Sampler2D uniform (which may only be available later on after initUniforms once the texture has loaded) * */ -Shader.prototype.initSampler2D = function (uniform) { +Shader.prototype.initSampler2D = function (uniform) +{ var gl = this.gl; // Extended texture data - if (uniform.textureData) { + if (uniform.textureData) + { var data = uniform.textureData; // GLTexture = mag linear, min linear_mipmap_linear, wrap repeat + gl.generateMipmap(gl.TEXTURE_2D); @@ -417,14 +445,16 @@ var wrapT = (data.wrapT) ? data.wrapT : gl.CLAMP_TO_EDGE; var format = (data.luminance) ? gl.LUMINANCE : gl.RGBA; - if (data.repeat) { + if (data.repeat) + { wrapS = gl.REPEAT; wrapT = gl.REPEAT; } gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, !!data.flipY); - if (data.width) { + if (data.width) + { var width = (data.width) ? data.width : 512; var height = (data.height) ? data.height : 2; var border = (data.border) ? data.border : 0; @@ -432,7 +462,8 @@ // 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 { + 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); } @@ -448,7 +479,8 @@ * Destroys the shader. * */ -Shader.prototype.destroy = function () { +Shader.prototype.destroy = function () +{ this.gl.deleteProgram(this.program); this.gl = null; @@ -459,13 +491,15 @@ this.fragmentSrc = null; }; -Shader.prototype._glCompile = function (type, src) { +Shader.prototype._glCompile = function (type, src) +{ var shader = this.gl.createShader(type); this.gl.shaderSource(shader, src); this.gl.compileShader(shader); - if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) { + if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) + { window.console.log(this.gl.getShaderInfoLog(shader)); return null; } diff --git a/src/core/renderers/webgl/shaders/StripShader.js b/src/core/renderers/webgl/shaders/StripShader.js index 193f6e1..a7abcc6 100644 --- a/src/core/renderers/webgl/shaders/StripShader.js +++ b/src/core/renderers/webgl/shaders/StripShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function StripShader(gl) { +function StripShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -20,7 +21,8 @@ 'varying vec2 vTextureCoord;', - 'void main(void) {', + '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);', @@ -36,7 +38,8 @@ 'varying vec2 vTextureCoord;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vec2(vTextureCoord.x, vTextureCoord.y)) * alpha;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/utils/FilterTexture.js b/src/core/renderers/webgl/utils/FilterTexture.js index d2c8423..4433d44 100644 --- a/src/core/renderers/webgl/utils/FilterTexture.js +++ b/src/core/renderers/webgl/utils/FilterTexture.js @@ -8,7 +8,8 @@ * @param height {number} the vertical range of the filter * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values */ -function FilterTexture(gl, width, height, scaleMode) { +function FilterTexture(gl, width, height, scaleMode) +{ /** * @member {WebGLContext} */ @@ -59,7 +60,8 @@ * Clears the filter texture. * */ -FilterTexture.prototype.clear = function () { +FilterTexture.prototype.clear = function () +{ var gl = this.gl; gl.clearColor(0,0,0, 0); @@ -72,8 +74,10 @@ * @param width {number} the new width of the texture * @param height {number} the new height of the texture */ -FilterTexture.prototype.resize = function (width, height) { - if (this.width === width && this.height === height) { +FilterTexture.prototype.resize = function (width, height) +{ + if (this.width === width && this.height === height) + { return; } @@ -96,7 +100,8 @@ * Destroys the filter texture. * */ -FilterTexture.prototype.destroy = function () { +FilterTexture.prototype.destroy = function () +{ var gl = this.gl; gl.deleteFramebuffer( this.frameBuffer ); gl.deleteTexture( this.texture ); diff --git a/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js b/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js index c4721e9..a63f4d7 100644 --- a/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js +++ b/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js @@ -14,7 +14,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this sprite batch works for. */ -function WebGLFastSpriteBatch(renderer) { +function WebGLFastSpriteBatch(renderer) +{ /** * The renderer instance this sprite batch operates on. * @@ -91,7 +92,8 @@ */ this.lastIndexCount = 0; - for (var i=0, j=0; i < numIndices; i += 6, j += 4) { + 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; @@ -144,7 +146,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.setupContext(); }); } @@ -157,7 +160,8 @@ * * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLFastSpriteBatch.prototype.setupContext = function () { +WebGLFastSpriteBatch.prototype.setupContext = function () +{ var gl = this.renderer.gl; // create a couple of buffers @@ -177,7 +181,8 @@ /** * @param spriteBatch {SpriteBatch} The SpriteBatch container to prepare for. */ -WebGLFastSpriteBatch.prototype.begin = function (spriteBatch) { +WebGLFastSpriteBatch.prototype.begin = function (spriteBatch) +{ this.shader = this.renderer.shaderManager.fastShader; this.matrix = spriteBatch.worldTransform.toArray(true); @@ -187,33 +192,38 @@ /** */ -WebGLFastSpriteBatch.prototype.end = function () { +WebGLFastSpriteBatch.prototype.end = function () +{ this.flush(); }; /** * @param spriteBatch {SpriteBatch} The SpriteBatch container to render. */ -WebGLFastSpriteBatch.prototype.render = function (spriteBatch) { +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) { + if (!sprite.texture._uvs) + { return; } this.currentBaseTexture = sprite.texture.baseTexture; // check blend mode - if (sprite.blendMode !== this.renderer.blendModeManager.currentBlendMode) { + if (sprite.blendMode !== this.renderer.blendModeManager.currentBlendMode) + { this.flush(); this.renderer.blendModeManager.setBlendMode(sprite.blendMode); } - for (var i=0,j= children.length; i= this.size) { + if (this.currentBatchSize >= this.size) + { this.flush(); } }; @@ -362,29 +379,35 @@ /** * */ -WebGLFastSpriteBatch.prototype.flush = function () { +WebGLFastSpriteBatch.prototype.flush = function () +{ // If the batch is length 0 then return as there is nothing to draw - if (this.currentBatchSize === 0) { + if (this.currentBatchSize === 0) + { return; } var gl = this.renderer.gl; // bind the current texture - if (!this.currentBaseTexture._glTextures[gl.id]) { + if (!this.currentBaseTexture._glTextures[gl.id]) + { this.renderer.updateTexture(this.currentBaseTexture, gl); } //TODO-SHOUD THIS BE ELSE??!?!?! - else { + else + { gl.bindTexture(gl.TEXTURE_2D, this.currentBaseTexture._glTextures[gl.id]); } // upload the verts to the buffer - if (this.currentBatchSize > ( this.size * 0.5 ) ) { + if (this.currentBatchSize > ( this.size * 0.5 ) ) + { gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); } - else { + else + { var view = this.vertices.subarray(0, this.currentBatchSize * this.vertByteSize); gl.bufferSubData(gl.ARRAY_BUFFER, 0, view); @@ -405,14 +428,16 @@ * Ends the batch and flushes * */ -WebGLFastSpriteBatch.prototype.stop = function () { +WebGLFastSpriteBatch.prototype.stop = function () +{ this.flush(); }; /** * */ -WebGLFastSpriteBatch.prototype.start = function () { +WebGLFastSpriteBatch.prototype.start = function () +{ var gl = this.renderer.gl; // bind the main texture diff --git a/src/core/renderers/webgl/utils/WebGLGraphics.js b/src/core/renderers/webgl/utils/WebGLGraphics.js index 55f4911..ab8f46e 100644 --- a/src/core/renderers/webgl/utils/WebGLGraphics.js +++ b/src/core/renderers/webgl/utils/WebGLGraphics.js @@ -19,7 +19,8 @@ * @param graphics {Graphics} * @param renderer {WebGLRenderer} */ -WebGLGraphics.renderGraphics = function (graphics, renderer) {//projection, offset) { +WebGLGraphics.renderGraphics = function (graphics, renderer) {//projection, offset) +{ var gl = renderer.gl; var projection = renderer.projection, @@ -27,7 +28,8 @@ shader = renderer.shaderManager.primitiveShader, webGLData; - if (graphics.dirty) { + if (graphics.dirty) + { WebGLGraphics.updateGraphics(graphics, gl); } @@ -35,8 +37,10 @@ // This could be speeded up for sure! - for (var i = 0; i < webGL.data.length; i++) { - if (webGL.data[i].mode === 1) { + for (var i = 0; i < webGL.data.length; i++) + { + if (webGL.data[i].mode === 1) + { webGLData = webGL.data[i]; renderer.stencilManager.pushStencil(graphics, webGLData, renderer); @@ -46,7 +50,8 @@ renderer.stencilManager.popStencil(graphics, webGLData, renderer); } - else { + else + { webGLData = webGL.data[i]; @@ -84,12 +89,14 @@ * @param graphicsData {Graphics} The graphics object to update * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLGraphics.updateGraphics = function (graphics, gl) { +WebGLGraphics.updateGraphics = function (graphics, gl) +{ // get the contexts graphics object var webGL = graphics._webGL[gl.id]; // if the graphics object does not exist in the webGL context time to create it! - if (!webGL) { + if (!webGL) + { webGL = graphics._webGL[gl.id] = {lastIndex:0, data:[], gl:gl}; } @@ -99,11 +106,13 @@ var i; // if the user cleared the graphics object we will need to clear every object - if (graphics.clearDirty) { + if (graphics.clearDirty) + { graphics.clearDirty = false; // lop through and return all the webGLDatas to the object pool so than can be reused later on - for (i = 0; i < webGL.data.length; i++) { + for (i = 0; i < webGL.data.length; i++) + { var graphicsData = webGL.data[i]; graphicsData.reset(); WebGLGraphics.graphicsDataPool.push( graphicsData ); @@ -119,58 +128,72 @@ // loop through the graphics datas and construct each one.. // if the object is a complex fill then the new stencil buffer technique will be used // other wise graphics objects will be pushed into a batch.. - for (i = webGL.lastIndex; i < graphics.graphicsData.length; i++) { + for (i = webGL.lastIndex; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { // need to add the points the the graphics object.. data.points = data.shape.points.slice(); - if (data.shape.closed) { + if (data.shape.closed) + { // close the poly if the value is true! - if (data.points[0] !== data.points[data.points.length-2] || data.points[1] !== data.points[data.points.length-1]) { + if (data.points[0] !== data.points[data.points.length-2] || data.points[1] !== data.points[data.points.length-1]) + { data.points.push(data.points[0], data.points[1]); } } // MAKE SURE WE HAVE THE CORRECT TYPE.. - if (data.fill) { - if (data.points.length >= 6) { - if (data.points.length < 6 * 2) { + if (data.fill) + { + if (data.points.length >= 6) + { + if (data.points.length < 6 * 2) + { webGLData = WebGLGraphics.switchMode(webGL, 0); var canDrawUsingSimple = WebGLGraphics.buildPoly(data, webGLData); // console.log(canDrawUsingSimple); - if (!canDrawUsingSimple) { + if (!canDrawUsingSimple) + { // console.log("<>>>") webGLData = WebGLGraphics.switchMode(webGL, 1); WebGLGraphics.buildComplexPoly(data, webGLData); } } - else { + else + { webGLData = WebGLGraphics.switchMode(webGL, 1); WebGLGraphics.buildComplexPoly(data, webGLData); } } } - if (data.lineWidth > 0) { + if (data.lineWidth > 0) + { webGLData = WebGLGraphics.switchMode(webGL, 0); WebGLGraphics.buildLine(data, webGLData); } } - else { + else + { webGLData = WebGLGraphics.switchMode(webGL, 0); - if (data.type === CONST.SHAPES.RECT) { + if (data.type === CONST.SHAPES.RECT) + { WebGLGraphics.buildRectangle(data, webGLData); } - else if (data.type === CONST.SHAPES.CIRC || data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.CIRC || data.type === CONST.SHAPES.ELIP) + { WebGLGraphics.buildCircle(data, webGLData); } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { WebGLGraphics.buildRoundedRectangle(data, webGLData); } } @@ -179,10 +202,12 @@ } // upload all the dirty data... - for (i = 0; i < webGL.data.length; i++) { + for (i = 0; i < webGL.data.length; i++) + { webGLData = webGL.data[i]; - if (webGLData.dirty) { + if (webGLData.dirty) + { webGLData.upload(); } } @@ -194,18 +219,22 @@ * @param webGL {WebGLContext} * @param type {number} */ -WebGLGraphics.switchMode = function (webGL, type) { +WebGLGraphics.switchMode = function (webGL, type) +{ var webGLData; - if (!webGL.data.length) { + if (!webGL.data.length) + { webGLData = WebGLGraphics.graphicsDataPool.pop() || new WebGLGraphicsData(webGL.gl); webGLData.mode = type; webGL.data.push(webGLData); } - else { + else + { webGLData = webGL.data[webGL.data.length-1]; - if (webGLData.mode !== type || type === 1) { + if (webGLData.mode !== type || type === 1) + { webGLData = WebGLGraphics.graphicsDataPool.pop() || new WebGLGraphicsData(webGL.gl); webGLData.mode = type; webGL.data.push(webGLData); @@ -225,7 +254,8 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildRectangle = function (graphicsData, webGLData) { +WebGLGraphics.buildRectangle = function (graphicsData, webGLData) +{ // --- // // need to convert points to a nice regular data // @@ -235,7 +265,8 @@ var width = rectData.width; var height = rectData.height; - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -265,7 +296,8 @@ indices.push(vertPos, vertPos, vertPos+1, vertPos+2, vertPos+3, vertPos+3); } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = [x, y, @@ -289,7 +321,8 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildRoundedRectangle = function (graphicsData, webGLData) { +WebGLGraphics.buildRoundedRectangle = function (graphicsData, webGLData) +{ var rrectData = graphicsData.shape; var x = rrectData.x; var y = rrectData.y; @@ -305,7 +338,8 @@ recPoints = recPoints.concat(WebGLGraphics.quadraticBezierCurve(x + width, y + radius, x + width, y, x + width - radius, y)); recPoints = recPoints.concat(WebGLGraphics.quadraticBezierCurve(x + radius, y, x, y, x, y + radius)); - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -323,7 +357,8 @@ // var i = 0; - for (i = 0; i < triangles.length; i+=3) { + for (i = 0; i < triangles.length; i+=3) + { indices.push(triangles[i] + vecPos); indices.push(triangles[i] + vecPos); indices.push(triangles[i+1] + vecPos); @@ -332,12 +367,14 @@ } - for (i = 0; i < recPoints.length; i++) { + for (i = 0; i < recPoints.length; i++) + { verts.push(recPoints[i], recPoints[++i], r, g, b, alpha); } } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = recPoints; @@ -362,7 +399,8 @@ * @param toY {number} Destination point y * @return {number[]} */ -WebGLGraphics.quadraticBezierCurve = function (fromX, fromY, cpX, cpY, toX, toY) { +WebGLGraphics.quadraticBezierCurve = function (fromX, fromY, cpX, cpY, toX, toY) +{ var xa, ya, @@ -373,14 +411,16 @@ n = 20, points = []; - function getPt(n1 , n2, perc) { + function getPt(n1 , n2, perc) + { var diff = n2 - n1; return n1 + ( diff * perc ); } var j = 0; - for (var i = 0; i <= n; i++ ) { + for (var i = 0; i <= n; i++ ) + { j = i / n; // The Green Line @@ -406,7 +446,8 @@ * @param graphicsData {Graphics} The graphics object to draw * @param webGLData {object} */ -WebGLGraphics.buildCircle = function (graphicsData, webGLData) { +WebGLGraphics.buildCircle = function (graphicsData, webGLData) +{ // need to convert points to a nice regular data var circleData = graphicsData.shape; var x = circleData.x; @@ -415,11 +456,13 @@ var height; // TODO - bit hacky?? - if (graphicsData.type === CONST.SHAPES.CIRC) { + if (graphicsData.type === CONST.SHAPES.CIRC) + { width = circleData.radius; height = circleData.radius; } - else { + else + { width = circleData.width; height = circleData.height; } @@ -429,7 +472,8 @@ var i = 0; - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -444,7 +488,8 @@ indices.push(vecPos); - for (i = 0; i < totalSegs + 1 ; i++) { + for (i = 0; i < totalSegs + 1 ; i++) + { verts.push(x,y, r, g, b, alpha); verts.push(x + Math.sin(seg * i) * width, @@ -457,12 +502,14 @@ indices.push(vecPos-1); } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = []; - for (i = 0; i < totalSegs + 1; i++) { + for (i = 0; i < totalSegs + 1; i++) + { graphicsData.points.push(x + Math.sin(seg * i) * width, y + Math.cos(seg * i) * height); } @@ -481,18 +528,22 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildLine = function (graphicsData, webGLData) { +WebGLGraphics.buildLine = function (graphicsData, webGLData) +{ // TODO OPTIMISE! var i = 0; var points = graphicsData.points; - if (points.length === 0) { + if (points.length === 0) + { return; } // if the line width is an odd number add 0.5 to align to a whole pixel - if (graphicsData.lineWidth%2) { - for (i = 0; i < points.length; i++) { + if (graphicsData.lineWidth%2) + { + for (i = 0; i < points.length; i++) + { points[i] += 0.5; } } @@ -502,7 +553,8 @@ var lastPoint = new math.Point(points[points.length - 2], points[points.length - 1]); // if the first point is the last point - gonna have issues :) - if (firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) { + if (firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) + { // need to clone as we are going to slightly modify the shape.. points = points.slice(); @@ -562,7 +614,8 @@ verts.push(p1x + perpx , p1y + perpy, r, g, b, alpha); - for (i = 1; i < length-1; i++) { + for (i = 1; i < length-1; i++) + { p1x = points[(i-1)*2]; p1y = points[(i-1)*2 + 1]; @@ -599,7 +652,8 @@ denom = a1*b2 - a2*b1; - if (Math.abs(denom) < 0.1 ) { + if (Math.abs(denom) < 0.1 ) + { denom+=10.1; verts.push(p2x - perpx , p2y - perpy, @@ -618,7 +672,8 @@ pdist = (px -p2x) * (px -p2x) + (py -p2y) + (py -p2y); - if (pdist > 140 * 140) { + if (pdist > 140 * 140) + { perp3x = perpx - perp2x; perp3y = perpy - perp2y; @@ -639,7 +694,8 @@ indexCount++; } - else { + else + { verts.push(px , py); verts.push(r, g, b, alpha); @@ -672,7 +728,8 @@ indices.push(indexStart); - for (i = 0; i < indexCount; i++) { + for (i = 0; i < indexCount; i++) + { indices.push(indexStart++); } @@ -687,11 +744,13 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildComplexPoly = function (graphicsData, webGLData) { +WebGLGraphics.buildComplexPoly = function (graphicsData, webGLData) +{ //TODO - no need to copy this as it gets turned into a FLoat32Array anyways.. var points = graphicsData.points.slice(); - if (points.length < 6) { + if (points.length < 6) + { return; } @@ -711,7 +770,8 @@ var x,y; // get size.. - for (var i = 0; i < points.length; i+=2) { + for (var i = 0; i < points.length; i+=2) + { x = points[i]; y = points[i+1]; @@ -732,7 +792,8 @@ //TODO - this aint needed! var length = points.length / 2; - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { indices.push( i ); } @@ -746,10 +807,12 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildPoly = function (graphicsData, webGLData) { +WebGLGraphics.buildPoly = function (graphicsData, webGLData) +{ var points = graphicsData.points; - if (points.length < 6) { + if (points.length < 6) + { return; } // get first and last point.. figure out the middle! @@ -767,7 +830,8 @@ var triangles = utils.PolyK.Triangulate(points); - if (!triangles) { + if (!triangles) + { return false; } @@ -775,7 +839,8 @@ var i = 0; - for (i = 0; i < triangles.length; i+=3) { + for (i = 0; i < triangles.length; i+=3) + { indices.push(triangles[i] + vertPos); indices.push(triangles[i] + vertPos); indices.push(triangles[i+1] + vertPos); @@ -783,7 +848,8 @@ indices.push(triangles[i+2] + vertPos); } - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { verts.push(points[i * 2], points[i * 2 + 1], r, g, b, alpha); } diff --git a/src/core/renderers/webgl/utils/WebGLGraphicsData.js b/src/core/renderers/webgl/utils/WebGLGraphicsData.js index c56d05e..c739ba7 100644 --- a/src/core/renderers/webgl/utils/WebGLGraphicsData.js +++ b/src/core/renderers/webgl/utils/WebGLGraphicsData.js @@ -2,7 +2,8 @@ * @class * @private */ -function WebGLGraphicsData(gl) { +function WebGLGraphicsData(gl) +{ this.gl = gl; //TODO does this need to be split before uploding?? @@ -22,7 +23,8 @@ /** * */ -WebGLGraphicsData.prototype.reset = function () { +WebGLGraphicsData.prototype.reset = function () +{ this.points.length = 0; this.indices.length = 0; }; @@ -30,7 +32,8 @@ /** * */ -WebGLGraphicsData.prototype.upload = function () { +WebGLGraphicsData.prototype.upload = function () +{ var gl = this.gl; // this.lastIndex = graphics.graphicsData.length; diff --git a/src/core/renderers/webgl/utils/WebGLSpriteBatch.js b/src/core/renderers/webgl/utils/WebGLSpriteBatch.js index 96eaa52..55befbb 100644 --- a/src/core/renderers/webgl/utils/WebGLSpriteBatch.js +++ b/src/core/renderers/webgl/utils/WebGLSpriteBatch.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this sprite batch works for. */ -function WebGLSpriteBatch(renderer) { +function WebGLSpriteBatch(renderer) +{ /** * * @@ -88,7 +89,8 @@ */ this.lastIndexCount = 0; - for (var i=0, j=0; i < numIndices; i += 6, j += 4) { + 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; @@ -162,7 +164,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.setupContext(); }); } @@ -173,7 +176,8 @@ /** * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLSpriteBatch.prototype.setupContext = function () { +WebGLSpriteBatch.prototype.setupContext = function () +{ var gl = this.renderer.gl; // setup default shader @@ -198,7 +202,8 @@ /** * */ -WebGLSpriteBatch.prototype.begin = function () { +WebGLSpriteBatch.prototype.begin = function () +{ // this.shader = this.renderer.shaderManager.defaultShader; this.start(); @@ -206,19 +211,22 @@ /** */ -WebGLSpriteBatch.prototype.end = function () { +WebGLSpriteBatch.prototype.end = function () +{ this.flush(); }; /** * @param sprite {Sprite} the sprite to render when using this spritebatch */ -WebGLSpriteBatch.prototype.render = function (sprite) { +WebGLSpriteBatch.prototype.render = function (sprite) +{ var texture = sprite.texture; //TODO set blend modes.. // check texture.. - if (this.currentBatchSize >= this.size) { + if (this.currentBatchSize >= this.size) + { this.flush(); this.currentBaseTexture = texture.baseTexture; } @@ -227,7 +235,8 @@ var uvs = texture._uvs; // if the uvs have not updated then no point rendering just yet! - if (!uvs) { + if (!uvs) + { return; } @@ -237,7 +246,8 @@ var w0, w1, h0, h1; - if (texture.trim) { + 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; @@ -248,7 +258,8 @@ h0 = h1 + texture.crop.height; } - else { + else + { w0 = (texture.frame.width ) * (1-aX); w1 = (texture.frame.width ) * -aX; @@ -272,7 +283,8 @@ var colors = this.colors; var positions = this.positions; - if (this.renderer.roundPixels) { + if (this.renderer.roundPixels) + { // xy positions[index] = a * w1 + c * h1 + tx | 0; positions[index+1] = d * h1 + b * w1 + ty | 0; @@ -289,7 +301,8 @@ positions[index+15] = a * w1 + c * h0 + tx | 0; positions[index+16] = d * h0 + b * w1 + ty | 0; } - else { + else + { // xy positions[index] = a * w1 + c * h1 + tx; positions[index+1] = d * h1 + b * w1 + ty; @@ -338,11 +351,13 @@ * * @param sprite {TilingSprite} the tilingSprite to render */ -WebGLSpriteBatch.prototype.renderTilingSprite = function (tilingSprite) { +WebGLSpriteBatch.prototype.renderTilingSprite = function (tilingSprite) +{ var texture = tilingSprite.tilingTexture; // check texture.. - if (this.currentBatchSize >= this.size) { + if (this.currentBatchSize >= this.size) + { //return; this.flush(); this.currentBaseTexture = texture.baseTexture; @@ -351,7 +366,8 @@ // set the textures uvs temporarily // TODO create a separate texture so that we can tile part of a texture - if (!tilingSprite._uvs) { + if (!tilingSprite._uvs) + { tilingSprite._uvs = new TextureUvs(); } @@ -454,16 +470,19 @@ * Renders the content and empties the current batch. * */ -WebGLSpriteBatch.prototype.flush = function () { +WebGLSpriteBatch.prototype.flush = function () +{ // If the batch is length 0 then return as there is nothing to draw - if (this.currentBatchSize === 0) { + if (this.currentBatchSize === 0) + { return; } var gl = this.renderer.gl; var shader; - if (this.dirty) { + if (this.dirty) + { this.dirty = false; // bind the main texture gl.activeTexture(gl.TEXTURE0); @@ -482,10 +501,12 @@ } // upload the verts to the buffer - if (this.currentBatchSize > ( this.size * 0.5 ) ) { + if (this.currentBatchSize > ( this.size * 0.5 ) ) + { gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); } - else { + else + { var view = this.positions.subarray(0, this.currentBatchSize * this.vertByteSize); gl.bufferSubData(gl.ARRAY_BUFFER, 0, view); } @@ -502,7 +523,8 @@ var shaderSwap = false; var sprite; - for (var i = 0, j = this.currentBatchSize; i < j; i++) { + for (var i = 0, j = this.currentBatchSize; i < j; i++) + { sprite = this.sprites[i]; @@ -513,24 +535,28 @@ blendSwap = currentBlendMode !== nextBlendMode; shaderSwap = currentShader !== nextShader; // should I use uuidS??? - if (currentBaseTexture !== nextTexture || blendSwap || shaderSwap) { + if (currentBaseTexture !== nextTexture || blendSwap || shaderSwap) + { this.renderBatch(currentBaseTexture, batchSize, start); start = i; batchSize = 0; currentBaseTexture = nextTexture; - if (blendSwap) { + if (blendSwap) + { currentBlendMode = nextBlendMode; this.renderer.blendModeManager.setBlendMode( currentBlendMode ); } - if (shaderSwap) { + if (shaderSwap) + { currentShader = nextShader; shader = currentShader.shaders ? currentShader.shaders[gl.id] : currentShader; - if (!shader) { + if (!shader) + { shader = new Shader(gl, null, currentShader.fragmentSrc, currentShader.uniforms); currentShader.shaders[gl.id] = shader; } @@ -538,7 +564,8 @@ // set shader function??? this.renderer.shaderManager.setShader(shader); - if (shader.dirty) { + if (shader.dirty) + { shader.syncUniforms(); } @@ -569,17 +596,21 @@ * @param size {number} * @param startIndex {number} */ -WebGLSpriteBatch.prototype.renderBatch = function (texture, size, startIndex) { - if (size === 0) { +WebGLSpriteBatch.prototype.renderBatch = function (texture, size, startIndex) +{ + if (size === 0) + { return; } var gl = this.renderer.gl; - if (!texture._glTextures[gl.id]) { + if (!texture._glTextures[gl.id]) + { this.renderer.updateTexture(texture); } - else { + else + { // bind the current texture gl.bindTexture(gl.TEXTURE_2D, texture._glTextures[gl.id]); } @@ -594,7 +625,8 @@ /** * */ -WebGLSpriteBatch.prototype.stop = function () { +WebGLSpriteBatch.prototype.stop = function () +{ this.flush(); this.dirty = true; }; @@ -602,7 +634,8 @@ /** * */ -WebGLSpriteBatch.prototype.start = function () { +WebGLSpriteBatch.prototype.start = function () +{ this.dirty = true; }; @@ -610,7 +643,8 @@ * Destroys the SpriteBatch. * */ -WebGLSpriteBatch.prototype.destroy = function () { +WebGLSpriteBatch.prototype.destroy = function () +{ this.renderer.gl.deleteBuffer(this.vertexBuffer); this.renderer.gl.deleteBuffer(this.indexBuffer); diff --git a/src/core/display/DisplayObject.js b/src/core/display/DisplayObject.js index 66ebc3c..20e778c 100644 --- a/src/core/display/DisplayObject.js +++ b/src/core/display/DisplayObject.js @@ -7,7 +7,8 @@ * @class * @namespace PIXI */ -function DisplayObject() { +function DisplayObject() +{ /** * The coordinate of the object relative to the local coordinates of the parent. * @@ -152,10 +153,12 @@ * @memberof DisplayObject# */ x: { - get: function () { + get: function () + { return this.position.x; }, - set: function (value) { + set: function (value) + { this.position.x = value; } }, @@ -167,10 +170,12 @@ * @memberof DisplayObject# */ y: { - get: function () { + get: function () + { return this.position.y; }, - set: function (value) { + set: function (value) + { this.position.y = value; } }, @@ -183,11 +188,13 @@ * @readonly */ worldVisible: { - get: function () { + get: function () + { var item = this; do { - if (!item.visible) { + if (!item.visible) + { return false; } @@ -207,17 +214,21 @@ * @memberof DisplayObject# */ mask: { - get: function () { + get: function () + { return this._mask; }, - set: function (value) { - if (this._mask) { + set: function (value) + { + if (this._mask) + { this._mask.isMask = false; } this._mask = value; - if (this._mask) { + if (this._mask) + { this._mask.isMask = true; } } @@ -232,18 +243,23 @@ * @memberof DisplayObject# */ filters: { - get: function () { + get: function () + { return this._filters; }, - set: function (value) { - if (value) { + set: function (value) + { + if (value) + { // now put all the passes in one place.. var passes = []; - for (var i = 0; i < value.length; i++) { + for (var i = 0; i < value.length; i++) + { var filterPasses = value[i].passes; - for (var j = 0; j < filterPasses.length; j++) { + for (var j = 0; j < filterPasses.length; j++) + { passes.push(filterPasses[j]); } } @@ -264,8 +280,9 @@ * * @private */ -DisplayObject.prototype.updateTransform = function () { - +DisplayObject.prototype.updateTransform = function () +{ + // create some matrix refs for easy access var pt = this.parent.worldTransform; var wt = this.worldTransform; @@ -274,9 +291,11 @@ var a, b, c, d, tx, ty; // so if rotation is between 0 then we can simplify the multiplication process.. - if (this.rotation % math.PI_2) { + if (this.rotation % math.PI_2) + { // 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) { + if (this.rotation !== this.rotationCache) + { this.rotationCache = this.rotation; this._sr = Math.sin(this.rotation); this._cr = Math.cos(this.rotation); @@ -291,7 +310,8 @@ ty = this.position.y; // check for pivot.. not often used so geared towards that fact! - if (this.pivot.x || this.pivot.y) { + 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; } @@ -304,7 +324,8 @@ wt.tx = tx * pt.a + ty * pt.c + pt.tx; wt.ty = tx * pt.b + ty * pt.d + pt.ty; } - else { + else + { // lets do the fast version as we know there is no rotation.. a = this.scale.x; d = this.scale.y; @@ -333,7 +354,8 @@ * @param matrix {Matrix} * @return {Rectangle} the rectangular bounding area */ -DisplayObject.prototype.getBounds = function (/* matrix */) { +DisplayObject.prototype.getBounds = function (/* matrix */) +{ return math.Rectangle.EMPTY; }; @@ -342,7 +364,8 @@ * * @return {Rectangle} the rectangular bounding area */ -DisplayObject.prototype.getLocalBounds = function () { +DisplayObject.prototype.getLocalBounds = function () +{ return this.getBounds(math.Matrix.IDENTITY); }; @@ -352,7 +375,8 @@ * @param position {Point} The world origin to calculate from * @return {Point} A point object representing the position of this object */ -DisplayObject.prototype.toGlobal = function (position) { +DisplayObject.prototype.toGlobal = function (position) +{ // don't need to u[date the lot this.displayObjectUpdateTransform(); return this.worldTransform.apply(position); @@ -365,8 +389,10 @@ * @param [from] {DisplayObject} The DisplayObject to calculate the global position from * @return {Point} A point object representing the position of this object */ -DisplayObject.prototype.toLocal = function (position, from) { - if (from) { +DisplayObject.prototype.toLocal = function (position, from) +{ + if (from) + { position = from.toGlobal(position); } @@ -381,7 +407,8 @@ * @param renderer {WebGLRenderer} The renderer * @private */ -DisplayObject.prototype.renderWebGL = function (/* renderer */) { +DisplayObject.prototype.renderWebGL = function (/* renderer */) +{ // OVERWRITE; }; @@ -391,6 +418,7 @@ * @param renderer {CanvasRenderer} The renderer * @private */ -DisplayObject.prototype.renderCanvas = function (/* renderer */) { +DisplayObject.prototype.renderCanvas = function (/* renderer */) +{ // OVERWRITE; }; diff --git a/src/core/display/DisplayObjectContainer.js b/src/core/display/DisplayObjectContainer.js index 689f40b..4625ee8 100644 --- a/src/core/display/DisplayObjectContainer.js +++ b/src/core/display/DisplayObjectContainer.js @@ -12,7 +12,8 @@ * @extends DisplayObject * @namespace PIXI */ -function DisplayObjectContainer() { +function DisplayObjectContainer() +{ DisplayObject.call(this); /** @@ -47,17 +48,21 @@ * @memberof DisplayObjectContainer# */ width: { - get: function () { + get: function () + { return this.scale.x * this.getLocalBounds().width; }, - set: function (value) { + set: function (value) + { var width = this.getLocalBounds().width; - if(width !== 0) { + if(width !== 0) + { this.scale.x = value / width; } - else { + else + { this.scale.x = 1; } @@ -73,17 +78,21 @@ * @memberof DisplayObjectContainer# */ height: { - get: function () { + get: function () + { return this.scale.y * this.getLocalBounds().height; }, - set: function (value) { + set: function (value) + { var height = this.getLocalBounds().height; - if (height !== 0) { + if (height !== 0) + { this.scale.y = value / height ; } - else { + else + { this.scale.y = 1; } @@ -100,18 +109,23 @@ * @memberof DisplayObject# */ cacheAsBitmap: { - get: function () { + get: function () + { return this._cacheAsBitmap; }, - set: function (value) { - if (this._cacheAsBitmap === value) { + set: function (value) + { + if (this._cacheAsBitmap === value) + { return; } - if (value) { + if (value) + { this._generateCachedSprite(); } - else { + else + { this._destroyCachedSprite(); } @@ -126,7 +140,8 @@ * @param child {DisplayObject} The DisplayObject to add to the container * @return {DisplayObject} The child that was added. */ -DisplayObjectContainer.prototype.addChild = function (child) { +DisplayObjectContainer.prototype.addChild = function (child) +{ return this.addChildAt(child, this.children.length); }; @@ -137,14 +152,18 @@ * @param index {Number} The index to place the child in * @return {DisplayObject} The child that was added. */ -DisplayObjectContainer.prototype.addChildAt = function (child, index) { +DisplayObjectContainer.prototype.addChildAt = function (child, index) +{ // prevent adding self as child - if (child === this) { + if (child === this) + { return; } - if (index >= 0 && index <= this.children.length) { - if (child.parent) { + if (index >= 0 && index <= this.children.length) + { + if (child.parent) + { child.parent.removeChild(child); } @@ -154,7 +173,8 @@ return child; } - else { + else + { throw new Error(child + 'addChildAt: The index '+ index +' supplied is out of bounds ' + this.children.length); } }; @@ -165,15 +185,18 @@ * @param child {DisplayObject} * @param child2 {DisplayObject} */ -DisplayObjectContainer.prototype.swapChildren = function (child, child2) { - if (child === child2) { +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) { + if (index1 < 0 || index2 < 0) + { throw new Error('swapChildren: Both the supplied DisplayObjects must be a child of the caller.'); } @@ -187,10 +210,12 @@ * @param child {DisplayObject} The DisplayObject instance to identify * @return {Number} The index position of the child display object to identify */ -DisplayObjectContainer.prototype.getChildIndex = function (child) { +DisplayObjectContainer.prototype.getChildIndex = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { throw new Error('The supplied DisplayObject must be a child of the caller'); } @@ -203,8 +228,10 @@ * @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 */ -DisplayObjectContainer.prototype.setChildIndex = function (child, index) { - if (index < 0 || index >= this.children.length) { +DisplayObjectContainer.prototype.setChildIndex = function (child, index) +{ + if (index < 0 || index >= this.children.length) + { throw new Error('The supplied index is out of bounds'); } @@ -220,8 +247,10 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child at the given index, if any. */ -DisplayObjectContainer.prototype.getChildAt = function (index) { - if (index < 0 || index >= this.children.length) { +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'); } @@ -234,10 +263,12 @@ * @param child {DisplayObject} The DisplayObject to remove * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChild = function (child) { +DisplayObjectContainer.prototype.removeChild = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { return; } @@ -250,7 +281,8 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChildAt = function (index) { +DisplayObjectContainer.prototype.removeChildAt = function (index) +{ var child = this.getChildAt(index); child.parent = null; @@ -265,24 +297,29 @@ * @param beginIndex {Number} The beginning position. Default value is 0. * @param endIndex {Number} The ending position. Default value is size of the container. */ -DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) { +DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) +{ var begin = beginIndex || 0; var end = typeof endIndex === 'number' ? endIndex : this.children.length; var range = end - begin; - if (range > 0 && range <= end) { + if (range > 0 && range <= end) + { var removed = this.children.splice(begin, range); - for (var i = 0; i < removed.length; ++i) { + for (var i = 0; i < removed.length; ++i) + { removed[i].parent = null; } return removed; } - else if (range === 0 && this.children.length === 0) { + else if (range === 0 && this.children.length === 0) + { return []; } - else { + else + { throw new RangeError('removeChildren: numeric values are outside the acceptable range.'); } }; @@ -291,7 +328,8 @@ * Generates and updates the cached sprite for this object. * */ -DisplayObjectContainer.prototype.updateCachedSprite = function () { +DisplayObjectContainer.prototype.updateCachedSprite = function () +{ this._generateCachedSprite(); }; @@ -304,7 +342,8 @@ * @param renderer {CanvasRenderer|WebGLRenderer} The renderer used to generate the texture. * @return {Texture} a texture of the graphics object */ -DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) { +DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) +{ var bounds = this.getLocalBounds(); var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0, renderer, scaleMode, resolution); @@ -322,18 +361,22 @@ * * @private */ -DisplayObjectContainer.prototype.updateTransform = function () { - if (!this.visible) { +DisplayObjectContainer.prototype.updateTransform = function () +{ + if (!this.visible) + { return; } this.displayObjectUpdateTransform(); - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { return; } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } }; @@ -346,8 +389,10 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getBounds = function () { - if (this.children.length === 0) { +DisplayObjectContainer.prototype.getBounds = function () +{ + if (this.children.length === 0) + { return math.Rectangle.EMPTY; } @@ -365,10 +410,12 @@ var childVisible = false; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -386,7 +433,8 @@ maxY = maxY > childMaxY ? maxY : childMaxY; } - if (!childVisible) { + if (!childVisible) + { return math.Rectangle.EMPTY; } @@ -407,12 +455,14 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getLocalBounds = function () { +DisplayObjectContainer.prototype.getLocalBounds = function () +{ var matrixCache = this.worldTransform; this.worldTransform = math.Matrix.IDENTITY; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } @@ -428,13 +478,16 @@ * * @param renderer {WebGLRenderer} The renderer */ -DisplayObjectContainer.prototype.renderWebGL = function (renderer) { +DisplayObjectContainer.prototype.renderWebGL = function (renderer) +{ // if the object is not visible or the alpha is 0 then no need to render this element - if (!this.visible || this.alpha <= 0) { + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } @@ -442,14 +495,17 @@ var i, j; // do a quick check to see if this element has a mask or a filter. - if (this._mask || this._filters) { + if (this._mask || this._filters) + { // push filter first as we need to ensure the stencil buffer is correct for any masking - if (this._filters) { + if (this._filters) + { renderer.spriteBatch.flush(); renderer.filterManager.pushFilter(this._filterBlock); } - if (this._mask) { + if (this._mask) + { renderer.spriteBatch.stop(); renderer.maskManager.pushMask(this.mask, renderer); renderer.spriteBatch.start(); @@ -459,36 +515,42 @@ this._renderWebGL(renderer); // now loop through the children and make sure they get rendered - for (i = 0, j = this.children.length; i < j; i++) { + for (i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderWebGL(renderer); } // time to stop the sprite batch as either a mask element or a filter draw will happen next renderer.spriteBatch.stop(); - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(this._mask, renderer); } - if (this._filters) { + if (this._filters) + { renderer.filterManager.popFilter(); } renderer.spriteBatch.start(); } - else { + else + { this._renderWebGL(renderer); // simple render children! - for (i = 0, j = this.children.length; i < j; ++i) { + for (i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderWebGL(renderer); } } }; -DisplayObjectContainer.prototype._renderWebGL = function (renderer) { +DisplayObjectContainer.prototype._renderWebGL = function (renderer) +{ // this is where content itself gets renderd.. @@ -499,25 +561,31 @@ * * @param renderer {CanvasRenderer} The renderer */ -DisplayObjectContainer.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0) { +DisplayObjectContainer.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -528,13 +596,16 @@ * @param renderer {WebGLRenderer|CanvasRenderer} The renderer * @private */ -DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) { +DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) +{ this._cachedSprite.worldAlpha = this.worldAlpha; - if (renderer.gl) { + if (renderer.gl) + { this._cachedSprite.renderWebGL(renderer); } - else { + else + { this._cachedSprite.renderCanvas(renderer); } }; @@ -544,10 +615,12 @@ * * @private */ -DisplayObjectContainer.prototype._generateCachedSprite = function () { +DisplayObjectContainer.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { // TODO - RenderTexture now *requires* a renderer instance, so this is like broken // because `renderer` isn't actually in scope here :P var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0); @@ -555,7 +628,8 @@ this._cachedSprite = new Sprite(renderTexture); this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.texture.resize(bounds.width | 0, bounds.height | 0); } @@ -580,8 +654,10 @@ * * @private */ -DisplayObjectContainer.prototype._destroyCachedSprite = function () { - if (!this._cachedSprite) { +DisplayObjectContainer.prototype._destroyCachedSprite = function () +{ + if (!this._cachedSprite) + { return; } diff --git a/src/core/display/Sprite.js b/src/core/display/Sprite.js index 707da24..5862aef 100644 --- a/src/core/display/Sprite.js +++ b/src/core/display/Sprite.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param texture {Texture} The texture for this sprite */ -function Sprite(texture) { +function Sprite(texture) +{ DisplayObjectContainer.call(this); /** @@ -85,12 +86,14 @@ this.texture = texture || Texture.EMPTY; } -Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) { +Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) +{ DisplayObjectContainer.prototype.destroy.call(this); this.anchor = null; - if (destroyTexture) { + if (destroyTexture) + { this._texture.destroy(destroyBaseTexture); } @@ -111,10 +114,12 @@ * @memberof Sprite# */ width: { - get: function () { + get: function () + { return this.scale.x * this.texture.frame.width; }, - set: function (value) { + set: function (value) + { this.scale.x = value / this.texture.frame.width; this._width = value; } @@ -127,10 +132,12 @@ * @memberof Sprite# */ height: { - get: function () { + get: function () + { return this.scale.y * this.texture.frame.height; }, - set: function (value) { + set: function (value) + { this.scale.y = value / this.texture.frame.height; this._height = value; } @@ -143,23 +150,29 @@ * @memberof Sprite# */ texture: { - get: function () { + get: function () + { return this._texture; }, - set: function (value) { - if (this._texture === value) { + set: function (value) + { + if (this._texture === value) + { return; } this._texture = value; this.cachedTint = 0xFFFFFF; - if (value) { + if (value) + { // wait for the texture to load - if (value.baseTexture.hasLoaded) { + if (value.baseTexture.hasLoaded) + { this._onTextureUpdate(); } - else { + else + { value.once('update', this._onTextureUpdate.bind(this)); } } @@ -172,18 +185,22 @@ * * @private */ -Sprite.prototype._onTextureUpdate = function () { +Sprite.prototype._onTextureUpdate = function () +{ // so if _width is 0 then width was not set.. - if (this._width) { + if (this._width) + { this.scale.x = this._width / this.texture.frame.width; } - if (this._height) { + if (this._height) + { this.scale.y = this._height / this.texture.frame.height; } }; -Sprite.prototype._renderWebGL = function (renderer) { +Sprite.prototype._renderWebGL = function (renderer) +{ // this is where content gets renderd.. // watch this space for a little render state manager.. @@ -197,7 +214,8 @@ * @param matrix {Matrix} the transformation matrix of the sprite * @return {Rectangle} the framing rectangle */ -Sprite.prototype.getBounds = function (matrix) { +Sprite.prototype.getBounds = function (matrix) +{ var width = this.texture.frame.width; var height = this.texture.frame.height; @@ -224,11 +242,13 @@ if(b === 0 && c === 0) { // scale may be negative! - if (a < 0) { + if (a < 0) + { a *= -1; } - if (d < 0) { + if (d < 0) + { d *= -1; } @@ -293,28 +313,34 @@ * * @param renderer {CanvasRenderer} The renderer */ -Sprite.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) { +Sprite.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) + { return; } - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; renderer.context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } // Ignore null sources - if (this.texture.valid) { + if (this.texture.valid) + { var resolution = this.texture.baseTexture.resolution / renderer.resolution; renderer.context.globalAlpha = this.worldAlpha; // If smoothingEnabled is supported and we need to change the smoothing property for this texture - if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) { + if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) + { renderer.scaleMode = this.texture.baseTexture.scaleMode; renderer.context[renderer.smoothProperty] = (renderer.scaleMode === CONST.scaleModes.LINEAR); } @@ -324,7 +350,8 @@ var dy = (this.texture.trim ? this.texture.trim.y : 0) - (this.anchor.y * this.texture.trim.height); // Allow for pixel rounding - if (renderer.roundPixels) { + if (renderer.roundPixels) + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -337,7 +364,8 @@ dx = dx | 0; dy = dy | 0; } - else { + else + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -348,8 +376,10 @@ ); } - if (this.tint !== 0xFFFFFF) { - if (this.cachedTint !== this.tint) { + if (this.tint !== 0xFFFFFF) + { + if (this.cachedTint !== this.tint) + { this.cachedTint = this.tint; // TODO clean up caching - how to clean up the caches? @@ -368,7 +398,8 @@ this.texture.crop.height / resolution ); } - else { + else + { renderer.context.drawImage( this.texture.baseTexture.source, this.texture.crop.x, @@ -383,11 +414,13 @@ } } - for (var i = 0, j = this.children.length; i < j; i++) { + for (var i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -402,10 +435,12 @@ * @param frameId {String} The frame Id of the texture in the cache * @return {Sprite} A new Sprite using a texture from the texture cache matching the frameId */ -Sprite.fromFrame = function (frameId) { +Sprite.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache' + this); } @@ -420,6 +455,7 @@ * @param imageId {String} The image url of the texture * @return {Sprite} A new Sprite using a texture from the texture cache matching the image id */ -Sprite.fromImage = function (imageId, crossorigin, scaleMode) { +Sprite.fromImage = function (imageId, crossorigin, scaleMode) +{ return new Sprite(Texture.fromImage(imageId, crossorigin, scaleMode)); }; diff --git a/src/core/display/SpriteBatch.js b/src/core/display/SpriteBatch.js index 3187777..c196fef 100644 --- a/src/core/display/SpriteBatch.js +++ b/src/core/display/SpriteBatch.js @@ -12,7 +12,8 @@ * ```js * var container = new SpriteBatch(); * - * for(var i = 0; i < 100; ++i) { + * for(var i = 0; i < 100; ++i) + * { * var sprite = new PIXI.Sprite.fromImage("myImage.png"); * container.addChild(sprite); * } @@ -25,7 +26,8 @@ */ //TODO RENAME to PARTICLE CONTAINER? -function SpriteBatch() { +function SpriteBatch() +{ DisplayObjectContainer.call(this); } @@ -38,7 +40,8 @@ * * @private */ -SpriteBatch.prototype.updateTransform = function () { +SpriteBatch.prototype.updateTransform = function () +{ // TODO don't need to! this.displayObjectUpdateTransform(); // PIXI.DisplayObjectContainer.prototype.updateTransform.call( this ); @@ -50,8 +53,10 @@ * @param renderer {WebGLRenderer} The webgl renderer * @private */ -SpriteBatch.prototype.renderWebGL = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderWebGL = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -71,8 +76,10 @@ * @param renderer {CanvasRenderer} The canvas renderer * @private */ -SpriteBatch.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -84,10 +91,12 @@ this.displayObjectUpdateTransform(); - for (var i = 0; i < this.children.length; ++i) { + for (var i = 0; i < this.children.length; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -95,9 +104,11 @@ context.globalAlpha = this.worldAlpha * child.alpha; - if (child.rotation % (Math.PI * 2) === 0) { + if (child.rotation % (Math.PI * 2) === 0) + { // this is the fastest way to optimise! - if rotation is 0 then we can avoid any kind of setTransform call - if (isRotated) { + if (isRotated) + { context.setTransform( transform.a, transform.b, @@ -122,8 +133,10 @@ frame.height * child.scale.y ); } - else { - if (!isRotated) { + else + { + if (!isRotated) + { isRotated = true; } @@ -131,7 +144,8 @@ var childTransform = child.worldTransform; - if (renderer.roundPixels) { + if (renderer.roundPixels) + { context.setTransform( childTransform.a, childTransform.b, @@ -141,7 +155,8 @@ childTransform.ty | 0 ); } - else { + else + { context.setTransform( childTransform.a, childTransform.b, diff --git a/src/core/index.js b/src/core/index.js index 3954b6f..eb4a82b 100644 --- a/src/core/index.js +++ b/src/core/index.js @@ -58,11 +58,13 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRenderer: function (width, height, options, noWebGL) { + autoDetectRenderer: function (width, height, options, noWebGL) + { width = width || 800; height = height || 600; - if (!noWebGL && require('webgl-enabled')()) { + if (!noWebGL && require('webgl-enabled')()) + { return new core.WebGLRenderer(width, height, options); } @@ -87,7 +89,8 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRecommendedRenderer: function (width, height, options) { + autoDetectRecommendedRenderer: function (width, height, options) + { var isAndroid = /Android/i.test(navigator.userAgent); return core.autoDetectRenderer(width, height, options, isAndroid); diff --git a/src/core/math/Matrix.js b/src/core/math/Matrix.js index c2f87e2..2ff4848 100644 --- a/src/core/math/Matrix.js +++ b/src/core/math/Matrix.js @@ -10,7 +10,8 @@ * @class * @namespace PIXI */ -function Matrix() { +function Matrix() +{ /** * @member {number} * @default 1 @@ -63,7 +64,8 @@ * * @param array {number[]} The array that the matrix will be populated from. */ -Matrix.prototype.fromArray = function (array) { +Matrix.prototype.fromArray = function (array) +{ this.a = array[0]; this.b = array[1]; this.c = array[3]; @@ -78,14 +80,17 @@ * @param transpose {boolean} Whether we need to transpose the matrix or not * @return {number[]} the newly created array which contains the matrix */ -Matrix.prototype.toArray = function (transpose) { - if (!this.array) { +Matrix.prototype.toArray = function (transpose) +{ + if (!this.array) + { this.array = new Float32Array(9); } var array = this.array; - if (transpose) { + if (transpose) + { array[0] = this.a; array[1] = this.b; array[2] = 0; @@ -96,7 +101,8 @@ array[7] = this.ty; array[8] = 1; } - else { + else + { array[0] = this.a; array[1] = this.c; array[2] = this.tx; @@ -119,7 +125,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, transformed through this matrix */ -Matrix.prototype.apply = function (pos, newPos) { +Matrix.prototype.apply = function (pos, newPos) +{ newPos = newPos || new Point(); newPos.x = this.a * pos.x + this.c * pos.y + this.tx; @@ -136,7 +143,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, inverse-transformed through this matrix */ -Matrix.prototype.applyInverse = function (pos, newPos) { +Matrix.prototype.applyInverse = function (pos, newPos) +{ newPos = newPos || new Point(); var id = 1 / (this.a * this.d + this.c * -this.b); @@ -154,7 +162,8 @@ * @param {number} y * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.translate = function (x, y) { +Matrix.prototype.translate = function (x, y) +{ this.tx += x; this.ty += y; @@ -168,7 +177,8 @@ * @param {number} y The amount to scale vertically * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.scale = function (x, y) { +Matrix.prototype.scale = function (x, y) +{ this.a *= x; this.d *= y; this.c *= x; @@ -186,7 +196,8 @@ * @param {number} angle - The angle in radians. * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.rotate = function (angle) { +Matrix.prototype.rotate = function (angle) +{ var cos = Math.cos( angle ); var sin = Math.sin( angle ); @@ -210,7 +221,8 @@ * @param {Matrix} matrix * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.append = function (matrix) { +Matrix.prototype.append = function (matrix) +{ var a1 = this.a; var b1 = this.b; var c1 = this.c; @@ -232,7 +244,8 @@ * * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.identity = function () { +Matrix.prototype.identity = function () +{ this.a = 1; this.b = 0; this.c = 0; diff --git a/src/core/math/Point.js b/src/core/math/Point.js index 7565b2d..632f346 100644 --- a/src/core/math/Point.js +++ b/src/core/math/Point.js @@ -7,7 +7,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -function Point(x, y) { +function Point(x, y) +{ /** * @member {number} * @default 0 @@ -29,7 +30,8 @@ * * @return {Point} a copy of the point */ -Point.prototype.clone = function () { +Point.prototype.clone = function () +{ return new Point(this.x, this.y); }; @@ -40,7 +42,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -Point.prototype.set = function (x, y) { +Point.prototype.set = function (x, y) +{ this.x = x || 0; this.y = y || ( (y !== 0) ? this.x : 0 ) ; }; diff --git a/src/core/math/shapes/Circle.js b/src/core/math/shapes/Circle.js index 69cfdc9..4d76efc 100644 --- a/src/core/math/shapes/Circle.js +++ b/src/core/math/shapes/Circle.js @@ -10,7 +10,8 @@ * @param y {number} The Y coordinate of the center of this circle * @param radius {number} The radius of the circle */ -function Circle(x, y, radius) { +function Circle(x, y, radius) +{ /** * @member {number} * @default 0 @@ -46,7 +47,8 @@ * @method clone * @return {Circle} a copy of the Circle */ -Circle.prototype.clone = function () { +Circle.prototype.clone = function () +{ return new Circle(this.x, this.y, this.radius); }; @@ -58,8 +60,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Circle */ -Circle.prototype.contains = function (x, y) { - if (this.radius <= 0) { +Circle.prototype.contains = function (x, y) +{ + if (this.radius <= 0) + { return false; } @@ -79,6 +83,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Circle.prototype.getBounds = function () { +Circle.prototype.getBounds = function () +{ return new Rectangle(this.x - this.radius, this.y - this.radius, this.radius * 2, this.radius * 2); }; diff --git a/src/core/math/shapes/Ellipse.js b/src/core/math/shapes/Ellipse.js index 4f2d066..fefd01a 100644 --- a/src/core/math/shapes/Ellipse.js +++ b/src/core/math/shapes/Ellipse.js @@ -11,7 +11,8 @@ * @param width {number} The half width of this ellipse * @param height {number} The half height of this ellipse */ -function Ellipse(x, y, width, height) { +function Ellipse(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -53,7 +54,8 @@ * @method clone * @return {Ellipse} a copy of the ellipse */ -Ellipse.prototype.clone = function () { +Ellipse.prototype.clone = function () +{ return new Ellipse(this.x, this.y, this.width, this.height); }; @@ -65,8 +67,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coords are within this ellipse */ -Ellipse.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Ellipse.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } @@ -86,6 +90,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Ellipse.prototype.getBounds = function () { +Ellipse.prototype.getBounds = function () +{ return new Rectangle(this.x - this.width, this.y - this.height, this.width, this.height); }; diff --git a/src/core/math/shapes/Polygon.js b/src/core/math/shapes/Polygon.js index ae89148..fea6d37 100644 --- a/src/core/math/shapes/Polygon.js +++ b/src/core/math/shapes/Polygon.js @@ -10,16 +10,20 @@ * arguments passed can be flat x,y values e.g. `new Polygon(x,y, x,y, x,y, ...)` where `x` and `y` are * Numbers. */ -function Polygon(points) { +function Polygon(points) +{ //if points isn't an array, use arguments as the array - if (!(points instanceof Array)) { + if (!(points instanceof Array)) + { points = Array.prototype.slice.call(arguments); } //if this is a flat array of numbers, convert it to points - if (points[0] instanceof Point) { + if (points[0] instanceof Point) + { var p = []; - for (var i = 0, il = points.length; i < il; i++) { + for (var i = 0, il = points.length; i < il; i++) + { p.push(points[i].x, points[i].y); } @@ -51,7 +55,8 @@ * * @return {Polygon} a copy of the polygon */ -Polygon.prototype.clone = function () { +Polygon.prototype.clone = function () +{ return new Polygon(this.points.slice()); }; @@ -62,19 +67,22 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this polygon */ -Polygon.prototype.contains = function (x, y) { +Polygon.prototype.contains = function (x, y) +{ var inside = false; // use some raycasting to test hits // https://github.com/substack/point-in-polygon/blob/master/index.js var length = this.points.length / 2; - for (var i = 0, j = length - 1; i < length; j = i++) { + for (var i = 0, j = length - 1; i < length; j = i++) + { var xi = this.points[i * 2], yi = this.points[i * 2 + 1], xj = this.points[j * 2], yj = this.points[j * 2 + 1], intersect = ((yi > y) !== (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi); - if (intersect) { + if (intersect) + { inside = !inside; } } diff --git a/src/core/math/shapes/Rectangle.js b/src/core/math/shapes/Rectangle.js index 16ac62a..4008b68 100644 --- a/src/core/math/shapes/Rectangle.js +++ b/src/core/math/shapes/Rectangle.js @@ -10,7 +10,8 @@ * @param width {number} The overall width of this rectangle * @param height {number} The overall height of this rectangle */ -function Rectangle(x, y, width, height) { +function Rectangle(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -60,7 +61,8 @@ * * @return {Rectangle} a copy of the rectangle */ -Rectangle.prototype.clone = function () { +Rectangle.prototype.clone = function () +{ return new Rectangle(this.x, this.y, this.width, this.height); }; @@ -71,13 +73,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rectangle */ -Rectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Rectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/math/shapes/RoundedRectangle.js b/src/core/math/shapes/RoundedRectangle.js index 27d286e..7bf6411 100644 --- a/src/core/math/shapes/RoundedRectangle.js +++ b/src/core/math/shapes/RoundedRectangle.js @@ -11,7 +11,8 @@ * @param height {number} The overall height of this rounded rectangle * @param radius {number} Controls the radius of the rounded corners */ -function RoundedRectangle(x, y, width, height, radius) { +function RoundedRectangle(x, y, width, height, radius) +{ /** * @member {number} * @default 0 @@ -58,7 +59,8 @@ * * @return {RoundedRectangle} a copy of the rounded rectangle */ -RoundedRectangle.prototype.clone = function () { +RoundedRectangle.prototype.clone = function () +{ return new RoundedRectangle(this.x, this.y, this.width, this.height, this.radius); }; @@ -69,13 +71,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rounded Rectangle */ -RoundedRectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +RoundedRectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/primitives/Graphics.js b/src/core/primitives/Graphics.js index 261c534..e902d2a 100644 --- a/src/core/primitives/Graphics.js +++ b/src/core/primitives/Graphics.js @@ -16,7 +16,8 @@ * @extends DisplayObjectContainer * @namespace PIXI */ -function Graphics() { +function Graphics() +{ DisplayObjectContainer.call(this); this.renderable = true; @@ -154,16 +155,20 @@ * @private */ cacheAsBitmap: { - get: function () { + get: function () + { return this._cacheAsBitmap; }, - set: function (value) { + set: function (value) + { this._cacheAsBitmap = value; - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._generateCachedSprite(); } - else { + else + { this.destroyCachedSprite(); this.dirty = true; } @@ -176,7 +181,8 @@ * * @return {Graphics} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ var clone = new Graphics(); clone.renderable = this.renderable; @@ -192,7 +198,8 @@ clone.cachedSpriteDirty = this.cachedSpriteDirty; // copy graphics data - for (var i = 0; i < this.graphicsData.length; ++i) { + for (var i = 0; i < this.graphicsData.length; ++i) + { clone.graphicsData.push(this.graphicsData.clone()); } @@ -211,17 +218,21 @@ * @param alpha {number} alpha of the line to draw, will update the objects stored style * @return {Graphics} */ -Graphics.prototype.lineStyle = function (lineWidth, color, alpha) { +Graphics.prototype.lineStyle = function (lineWidth, color, alpha) +{ this.lineWidth = lineWidth || 0; this.lineColor = color || 0; this.lineAlpha = (arguments.length < 3) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length) + { // halfway through a line? start a new one! this.drawShape( new math.Polygon( this.currentPath.shape.points.slice(-2) )); } - else { + else + { // otherwise its empty so lets just set the line properties this.currentPath.lineWidth = this.lineWidth; this.currentPath.lineColor = this.lineColor; @@ -239,7 +250,8 @@ * @param y {number} the Y coordinate to move to * @return {Graphics} */ -Graphics.prototype.moveTo = function (x, y) { +Graphics.prototype.moveTo = function (x, y) +{ this.drawShape(new math.Polygon([x,y])); return this; @@ -253,7 +265,8 @@ * @param y {number} the Y coordinate to draw to * @return {Graphics} */ -Graphics.prototype.lineTo = function (x, y) { +Graphics.prototype.lineTo = function (x, y) +{ this.currentPath.shape.points.push(x, y); this.dirty = true; @@ -270,13 +283,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -285,7 +302,8 @@ n = 20, points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { this.moveTo(0, 0); } @@ -293,7 +311,8 @@ var fromY = points[points.length-1]; var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; xa = fromX + ( (cpX - fromX) * j ); @@ -319,13 +338,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -342,7 +365,8 @@ var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; dt = (1 - j); @@ -373,13 +397,17 @@ * @param radius {number} The radius of the arc * @return {Graphics} */ -Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points.push(x1, y1); } } - else { + else + { this.moveTo(x1, y1); } @@ -392,12 +420,15 @@ b2 = x2 - x1, mm = Math.abs(a1 * b2 - b1 * a2); - if (mm < 1.0e-8 || radius === 0) { - if (points[points.length-2] !== x1 || points[points.length-1] !== y1) { + if (mm < 1.0e-8 || radius === 0) + { + if (points[points.length-2] !== x1 || points[points.length-1] !== y1) + { points.push(x1, y1); } } - else { + else + { var dd = a1 * a1 + b1 * b1, cc = a2 * a2 + b2 * b2, tt = a1 * a2 + b1 * b2, @@ -433,42 +464,51 @@ * @param anticlockwise {boolean} Optional. Specifies whether the drawing should be counterclockwise or clockwise. False is default, and indicates clockwise, while true indicates counter-clockwise. * @return {Graphics} */ -Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) { +Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) +{ var startX = cx + Math.cos(startAngle) * radius; var startY = cy + Math.sin(startAngle) * radius; var points; // TODO - This if-else makes no sense. It uses currentPath in the else where it doesn't exist... - if (this.currentPath) { + if (this.currentPath) + { points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { points.push(startX, startY); } - else if (points[points.length-2] !== startX || points[points.length-1] !== startY) { + else if (points[points.length-2] !== startX || points[points.length-1] !== startY) + { points.push(startX, startY); } } - else { + else + { this.moveTo(startX, startY); points = this.currentPath.shape.points; } - if (startAngle === endAngle) { + if (startAngle === endAngle) + { return this; } - if (!anticlockwise && endAngle <= startAngle) { + if (!anticlockwise && endAngle <= startAngle) + { endAngle += Math.PI * 2; } - else if (anticlockwise && startAngle <= endAngle) { + else if (anticlockwise && startAngle <= endAngle) + { startAngle += Math.PI * 2; } var sweep = anticlockwise ? (startAngle - endAngle) *-1 : (endAngle - startAngle); var segs = (Math.abs(sweep)/ (Math.PI * 2)) * 40; - if (sweep === 0) { + if (sweep === 0) + { return this; } @@ -482,7 +522,8 @@ var remainder = ( segMinus % 1 ) / segMinus; - for (var i = 0; i <= segMinus; ++i) { + for (var i = 0; i <= segMinus; ++i) + { var real = i + remainder * i; var angle = ((theta) + startAngle + (theta2 * real)); @@ -506,13 +547,16 @@ * @param alpha {number} the alpha of the fill * @return {Graphics} */ -Graphics.prototype.beginFill = function (color, alpha) { +Graphics.prototype.beginFill = function (color, alpha) +{ this.filling = true; this.fillColor = color || 0; this.fillAlpha = (alpha === undefined) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length <= 2) + { this.currentPath.fill = this.filling; this.currentPath.fillColor = this.fillColor; this.currentPath.fillAlpha = this.fillAlpha; @@ -526,7 +570,8 @@ * * @return {Graphics} */ -Graphics.prototype.endFill = function () { +Graphics.prototype.endFill = function () +{ this.filling = false; this.fillColor = null; this.fillAlpha = 1; @@ -542,7 +587,8 @@ * @param height {number} The height of the rectangle * @return {Graphics} */ -Graphics.prototype.drawRect = function ( x, y, width, height ) { +Graphics.prototype.drawRect = function ( x, y, width, height ) +{ this.drawShape(new math.Rectangle(x,y, width, height)); return this; @@ -556,7 +602,8 @@ * @param height {number} The height of the rectangle * @param radius {number} Radius of the rectangle corners */ -Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) { +Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) +{ this.drawShape(new math.RoundedRectangle(x, y, width, height, radius)); return this; @@ -570,7 +617,8 @@ * @param radius {number} The radius of the circle * @return {Graphics} */ -Graphics.prototype.drawCircle = function (x, y, radius) { +Graphics.prototype.drawCircle = function (x, y, radius) +{ this.drawShape(new math.Circle(x,y, radius)); return this; @@ -585,7 +633,8 @@ * @param height {number} The half height of the ellipse * @return {Graphics} */ -Graphics.prototype.drawEllipse = function (x, y, width, height) { +Graphics.prototype.drawEllipse = function (x, y, width, height) +{ this.drawShape(new math.Ellipse(x, y, width, height)); return this; @@ -597,8 +646,10 @@ * @param path {Array} The path data used to construct the polygon. * @return {Graphics} */ -Graphics.prototype.drawPolygon = function (path) { - if (!(path instanceof Array)) { +Graphics.prototype.drawPolygon = function (path) +{ + if (!(path instanceof Array)) + { path = Array.prototype.slice.call(arguments); } @@ -612,7 +663,8 @@ * * @return {Graphics} */ -Graphics.prototype.clear = function () { +Graphics.prototype.clear = function () +{ this.lineWidth = 0; this.filling = false; @@ -631,7 +683,8 @@ * @param scaleMode {number} Should be one of the scaleMode consts * @return {Texture} a texture of the graphics object */ -Graphics.prototype.generateTexture = function (resolution, scaleMode) { +Graphics.prototype.generateTexture = function (resolution, scaleMode) +{ resolution = resolution || 1; var bounds = this.getBounds(); @@ -655,17 +708,21 @@ * * @param renderer {WebGLRenderer} */ -Graphics.prototype._renderWebGL = function (renderer) { +Graphics.prototype._renderWebGL = function (renderer) +{ // if the sprite is not visible or the alpha is 0 then no need to render this element - if (this.isMask === true) { + if (this.isMask === true) + { return; } // this code may still be needed so leaving for now.. - // + // /* - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture on the gpu too! @@ -681,17 +738,24 @@ return; } - */ - - // check if the webgl graphic needs to be updated - if (this.glDirty) { - this.dirty = true; - this.glDirty = false; - } + else */ - renderer.setObjectRendererer(renderer.graphicsRenderer); - renderer.graphicsRenderer.render(this); + renderer.spriteBatch.stop(); + renderer.blendModeManager.setBlendMode(this.blendMode); + // check blend mode + renderer.blendModeManager.setBlendMode( this.blendMode ); + + // check if the webgl graphic needs to be updated + if (this.glDirty) + { + this.dirty = true; + this.glDirty = false; + } + + WebGLGraphics.renderGraphics(this, renderer); + + renderer.spriteBatch.start(); }; /** @@ -700,14 +764,18 @@ * @param renderer {CanvasRenderer} * @private */ -Graphics.prototype.renderCanvas = function (renderer) { +Graphics.prototype.renderCanvas = function (renderer) +{ // 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.isMask === true) { + if (!this.visible || this.alpha <= 0 || this.isMask === true) + { return; } - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture @@ -723,16 +791,19 @@ return; } - else { + else + { var context = renderer.context; var transform = this.worldTransform; - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } @@ -748,11 +819,13 @@ CanvasGraphics.renderGraphics(this, context); - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } } @@ -763,13 +836,16 @@ * * @return {Rectangle} the rectangular bounding area */ -Graphics.prototype.getBounds = function (matrix) { +Graphics.prototype.getBounds = function (matrix) +{ // return an empty object if the item is a mask! - if (this.isMask) { + if (this.isMask) + { return math.Rectangle.EMPTY; } - if (this.dirty) { + if (this.dirty) + { this.updateLocalBounds(); this.glDirty = true; @@ -841,23 +917,27 @@ * Update the bounds of the object * */ -Graphics.prototype.updateLocalBounds = function () { +Graphics.prototype.updateLocalBounds = function () +{ var minX = Infinity; var maxX = -Infinity; var minY = Infinity; var maxY = -Infinity; - if (this.graphicsData.length) { + if (this.graphicsData.length) + { var shape, points, x, y, w, h; - for (var i = 0; i < this.graphicsData.length; i++) { + for (var i = 0; i < this.graphicsData.length; i++) + { var data = this.graphicsData[i]; var type = data.type; var lineWidth = data.lineWidth; shape = data.shape; - if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) { + if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) + { x = shape.x - lineWidth/2; y = shape.y - lineWidth/2; w = shape.width + lineWidth; @@ -869,7 +949,8 @@ minY = y < minY ? y : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.CIRC) { + else if (type === CONST.SHAPES.CIRC) + { x = shape.x; y = shape.y; w = shape.radius + lineWidth/2; @@ -881,7 +962,8 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.ELIP) { + else if (type === CONST.SHAPES.ELIP) + { x = shape.x; y = shape.y; w = shape.width + lineWidth/2; @@ -893,11 +975,13 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else { + else + { // POLY points = shape.points; - for (var j = 0; j < points.length; j += 2) { + for (var j = 0; j < points.length; j += 2) + { x = points[j]; y = points[j+1]; @@ -910,7 +994,8 @@ } } } - else { + else + { minX = 0; maxX = 0; minY = 0; @@ -931,10 +1016,12 @@ * * @private */ -Graphics.prototype._generateCachedSprite = function () { +Graphics.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { var canvasBuffer = new CanvasBuffer(bounds.width, bounds.height); var texture = Texture.fromCanvas(canvasBuffer.canvas); @@ -943,7 +1030,8 @@ this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.buffer.resize(bounds.width, bounds.height); } @@ -968,7 +1056,8 @@ * * @private */ -Graphics.prototype.updateCachedSpriteTexture = function () { +Graphics.prototype.updateCachedSpriteTexture = function () +{ var cachedSprite = this._cachedSprite; var texture = cachedSprite.texture; var canvas = cachedSprite.buffer.canvas; @@ -989,7 +1078,8 @@ * Destroys a previous cached sprite. * */ -Graphics.prototype.destroyCachedSprite = function () { +Graphics.prototype.destroyCachedSprite = function () +{ this._cachedSprite.texture.destroy(true); // let the gc collect the unused sprite @@ -1003,10 +1093,13 @@ * @param {Circle|Rectangle|Ellipse|Line|Polygon} shape The Shape object to draw. * @return {GraphicsData} The generated GraphicsData object. */ -Graphics.prototype.drawShape = function (shape) { - if (this.currentPath) { +Graphics.prototype.drawShape = function (shape) +{ + if (this.currentPath) + { // check current path! - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath.shape.points.length <= 2) + { this.graphicsData.pop(); } } @@ -1017,7 +1110,8 @@ this.graphicsData.push(data); - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { data.shape.closed = this.filling; this.currentPath = data; } diff --git a/src/core/primitives/GraphicsData.js b/src/core/primitives/GraphicsData.js index 99decbe..788f6f2 100644 --- a/src/core/primitives/GraphicsData.js +++ b/src/core/primitives/GraphicsData.js @@ -4,7 +4,8 @@ * @class * @namespace PIXI */ -function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) { +function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) +{ this.lineWidth = lineWidth; this.lineColor = lineColor; this.lineAlpha = lineAlpha; @@ -27,7 +28,8 @@ * * @return {GraphicsData} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ return new GraphicsData( this.lineWidth, this.lineColor, diff --git a/src/core/renderers/canvas/CanvasRenderer.js b/src/core/renderers/canvas/CanvasRenderer.js index 15a0978..7aebd44 100644 --- a/src/core/renderers/canvas/CanvasRenderer.js +++ b/src/core/renderers/canvas/CanvasRenderer.js @@ -17,17 +17,22 @@ * @param [options.resolution=1] {number} the resolution of the renderer retina would be 2 * @param [options.clearBeforeRender=true] {boolean} This sets if the CanvasRenderer will clear the canvas or not before the new render pass. */ -function CanvasRenderer(width, height, options) { +function CanvasRenderer(width, height, options) +{ utils.sayHello('Canvas'); - if (options) { - for (var i in CONST.defaultRenderOptions) { - if (typeof options[i] === 'undefined') { + if (options) + { + for (var i in CONST.defaultRenderOptions) + { + if (typeof options[i] === 'undefined') + { options[i] = CONST.defaultRenderOptions[i]; } } } - else { + else + { options = CONST.defaultRenderOptions; } @@ -156,19 +161,24 @@ this.smoothProperty = null; - if (this.context.imageSmoothingEnabled) { + if (this.context.imageSmoothingEnabled) + { this.smoothProperty = 'imageSmoothingEnabled'; } - else if (this.context.webkitImageSmoothingEnabled) { + else if (this.context.webkitImageSmoothingEnabled) + { this.smoothProperty = 'webkitImageSmoothingEnabled'; } - else if (this.context.mozImageSmoothingEnabled) { + else if (this.context.mozImageSmoothingEnabled) + { this.smoothProperty = 'mozImageSmoothingEnabled'; } - else if (this.context.oImageSmoothingEnabled) { + else if (this.context.oImageSmoothingEnabled) + { this.smoothProperty = 'oImageSmoothingEnabled'; } - else if (this.context.msImageSmoothingEnabled) { + else if (this.context.msImageSmoothingEnabled) + { this.smoothProperty = 'msImageSmoothingEnabled'; } @@ -193,10 +203,12 @@ * @memberof CanvasRenderer# */ backgroundColor: { - get: function () { + get: function () + { return this._backgroundColor; }, - set: function (val) { + set: function (val) + { this._backgroundColor = val; this._backgroundColorString = utils.hex2string(val); } @@ -208,7 +220,8 @@ * * @param object {DisplayObject} the object to be rendered */ -CanvasRenderer.prototype.render = function (object) { +CanvasRenderer.prototype.render = function (object) +{ object.updateTransform(); this.context.setTransform(1,0,0,1,0,0); @@ -218,16 +231,20 @@ this.currentBlendMode = CONST.blendModes.NORMAL; this.context.globalCompositeOperation = this.blendModes[CONST.blendModes.NORMAL]; - if (navigator.isCocoonJS && this.view.screencanvas) { + if (navigator.isCocoonJS && this.view.screencanvas) + { this.context.fillStyle = 'black'; this.context.clear(); } - if (this.clearBeforeRender) { - if (this.transparent) { + if (this.clearBeforeRender) + { + if (this.transparent) + { this.context.clearRect(0, 0, this.width, this.height); } - else { + else + { this.context.fillStyle = this._backgroundColorString; this.context.fillRect(0, 0, this.width , this.height); } @@ -241,8 +258,10 @@ * * @param [removeView=false] {boolean} Removes the Canvas element from the DOM. */ -CanvasRenderer.prototype.destroy = function (removeView) { - if (removeView && this.view.parent) { +CanvasRenderer.prototype.destroy = function (removeView) +{ + if (removeView && this.view.parent) + { this.view.parent.removeChild(this.view); } @@ -257,14 +276,16 @@ * @param width {number} the new width of the canvas view * @param height {number} the new height of the canvas view */ -CanvasRenderer.prototype.resize = function (width, height) { +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) { + if (this.autoResize) + { this.view.style.width = this.width / this.resolution + 'px'; this.view.style.height = this.height / this.resolution + 'px'; } @@ -276,7 +297,8 @@ * @param displayObject {DisplayObject} The displayObject to render * @private */ -CanvasRenderer.prototype.renderDisplayObject = function (displayObject) { +CanvasRenderer.prototype.renderDisplayObject = function (displayObject) +{ displayObject.renderCanvas(this); }; @@ -285,11 +307,14 @@ * * @private */ -CanvasRenderer.prototype._mapBlendModes = function () { - if (!this.blendModes) { +CanvasRenderer.prototype._mapBlendModes = function () +{ + if (!this.blendModes) + { this.blendModes = {}; - if (utils.canUseNewCanvasBlendModes()) { + if (utils.canUseNewCanvasBlendModes()) + { this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? this.blendModes[CONST.blendModes.MULTIPLY] = 'multiply'; @@ -308,7 +333,8 @@ this.blendModes[CONST.blendModes.COLOR] = 'color'; this.blendModes[CONST.blendModes.LUMINOSITY] = 'luminosity'; } - else { + else + { // this means that the browser does not support the cool new blend modes in canvas 'cough' ie 'cough' this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? diff --git a/src/core/renderers/canvas/utils/CanvasBuffer.js b/src/core/renderers/canvas/utils/CanvasBuffer.js index ebe5d47..b183a66 100644 --- a/src/core/renderers/canvas/utils/CanvasBuffer.js +++ b/src/core/renderers/canvas/utils/CanvasBuffer.js @@ -6,7 +6,8 @@ * @param width {number} the width for the newly created canvas * @param height {number} the height for the newly created canvas */ -function CanvasBuffer(width, height) { +function CanvasBuffer(width, height) +{ /** * The Canvas object that belongs to this CanvasBuffer. * @@ -36,10 +37,12 @@ * @memberof CanvasBuffer# */ width: { - get: function () { + get: function () + { return this.canvas.width; }, - set: function (val) { + set: function (val) + { this.canvas.width = val; } }, @@ -50,10 +53,12 @@ * @memberof CanvasBuffer# */ height: { - get: function () { + get: function () + { return this.canvas.height; }, - set: function (val) { + set: function (val) + { this.canvas.height = val; } } @@ -64,7 +69,8 @@ * * @private */ -CanvasBuffer.prototype.clear = function () { +CanvasBuffer.prototype.clear = function () +{ this.context.setTransform(1, 0, 0, 1, 0, 0); this.context.clearRect(0,0, this.canvas.width, this.canvas.height); }; @@ -75,7 +81,8 @@ * @param width {number} the new width of the canvas * @param height {number} the new height of the canvas */ -CanvasBuffer.prototype.resize = function (width, height) { +CanvasBuffer.prototype.resize = function (width, height) +{ this.canvas.width = width; this.canvas.height = height; }; diff --git a/src/core/renderers/canvas/utils/CanvasGraphics.js b/src/core/renderers/canvas/utils/CanvasGraphics.js index c7eaa2a..3f2a91f 100644 --- a/src/core/renderers/canvas/utils/CanvasGraphics.js +++ b/src/core/renderers/canvas/utils/CanvasGraphics.js @@ -13,15 +13,18 @@ * @param graphics {Graphics} the actual graphics object to render * @param context {CanvasRenderingContext2D} the 2d drawing method of the canvas */ -CanvasGraphics.renderGraphics = function (graphics, context) { +CanvasGraphics.renderGraphics = function (graphics, context) +{ var worldAlpha = graphics.worldAlpha; - if (graphics.dirty) { + if (graphics.dirty) + { this.updateGraphicsTint(graphics); graphics.dirty = false; } - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; @@ -30,69 +33,82 @@ context.lineWidth = data.lineWidth; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { context.beginPath(); var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } - if (shape.closed) { + if (shape.closed) + { context.lineTo(points[0], points[1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fillRect(shape.x, shape.y, shape.width, shape.height); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.strokeRect(shape.x, shape.y, shape.width, shape.height); } } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.beginPath(); context.arc(shape.x, shape.y, shape.radius,0,2*Math.PI); context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas var w = shape.width * 2; @@ -119,18 +135,21 @@ context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; var width = shape.width; @@ -152,13 +171,15 @@ context.quadraticCurveTo(rx, ry, rx, ry + radius); context.closePath(); - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); @@ -174,45 +195,54 @@ * @param graphics {Graphics} the graphics which will be used as a mask * @param context {CanvasRenderingContext2D} the context 2d method of the canvas */ -CanvasGraphics.renderGraphicsMask = function (graphics, context) { +CanvasGraphics.renderGraphicsMask = function (graphics, context) +{ var len = graphics.graphicsData.length; - if (len === 0) { + if (len === 0) + { return; } context.beginPath(); - for (var i = 0; i < len; i++) { + for (var i = 0; i < len; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { context.rect(shape.x, shape.y, shape.width, shape.height); context.closePath(); } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.arc(shape.x, shape.y, shape.radius, 0, 2 * Math.PI); context.closePath(); } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas @@ -237,7 +267,8 @@ context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); context.closePath(); } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; @@ -262,8 +293,10 @@ } }; -CanvasGraphics.updateGraphicsTint = function (graphics) { - if (graphics.tint === 0xFFFFFF) { +CanvasGraphics.updateGraphicsTint = function (graphics) +{ + if (graphics.tint === 0xFFFFFF) + { return; } @@ -271,7 +304,8 @@ var tintG = (graphics.tint >> 8 & 0xFF) / 255; var tintB = (graphics.tint & 0xFF)/ 255; - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var fillColor = data.fillColor | 0; diff --git a/src/core/renderers/canvas/utils/CanvasMaskManager.js b/src/core/renderers/canvas/utils/CanvasMaskManager.js index e04a733..9827d36 100644 --- a/src/core/renderers/canvas/utils/CanvasMaskManager.js +++ b/src/core/renderers/canvas/utils/CanvasMaskManager.js @@ -6,7 +6,8 @@ * @class * @namespace PIXI */ -function CanvasMaskManager() {} +function CanvasMaskManager() +{} CanvasMaskManager.prototype.constructor = CanvasMaskManager; module.exports = CanvasMaskManager; @@ -17,7 +18,8 @@ * @param maskData {object} the maskData that will be pushed * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.pushMask = function (maskData, renderer) { +CanvasMaskManager.prototype.pushMask = function (maskData, renderer) +{ renderer.context.save(); var cacheAlpha = maskData.alpha; @@ -45,6 +47,7 @@ * * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.popMask = function (renderer) { +CanvasMaskManager.prototype.popMask = function (renderer) +{ renderer.context.restore(); }; diff --git a/src/core/renderers/canvas/utils/CanvasTinter.js b/src/core/renderers/canvas/utils/CanvasTinter.js index 17e0529..d2fb1bc 100644 --- a/src/core/renderers/canvas/utils/CanvasTinter.js +++ b/src/core/renderers/canvas/utils/CanvasTinter.js @@ -14,7 +14,8 @@ * @param color {number} the color to use to tint the sprite with * @return {HTMLCanvasElement} The tinted canvas */ -CanvasTinter.getTintedTexture = function (sprite, color) { +CanvasTinter.getTintedTexture = function (sprite, color) +{ var texture = sprite.texture; color = CanvasTinter.roundColor(color); @@ -23,7 +24,8 @@ texture.tintCache = texture.tintCache || {}; - if (texture.tintCache[stringColor]) { + if (texture.tintCache[stringColor]) + { return texture.tintCache[stringColor]; } @@ -33,14 +35,16 @@ //CanvasTinter.tintWithPerPixel(texture, stringColor, canvas); CanvasTinter.tintMethod(texture, color, canvas); - if (CanvasTinter.convertTintToImage) { + if (CanvasTinter.convertTintToImage) + { // is this better? var tintImage = new Image(); tintImage.src = canvas.toDataURL(); texture.tintCache[stringColor] = tintImage; } - else { + else + { texture.tintCache[stringColor] = canvas; // if we are not converting the texture to an image then we need to lose the reference to the canvas CanvasTinter.canvas = null; @@ -56,7 +60,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithMultiply = function (texture, color, canvas) { +CanvasTinter.tintWithMultiply = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -104,7 +109,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithOverlay = function (texture, color, canvas) { +CanvasTinter.tintWithOverlay = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -139,7 +145,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithPerPixel = function (texture, color, canvas) { +CanvasTinter.tintWithPerPixel = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -167,7 +174,8 @@ var pixels = pixelData.data; - for (var i = 0; i < pixels.length; i += 4) { + for (var i = 0; i < pixels.length; i += 4) + { pixels[i+0] *= r; pixels[i+1] *= g; pixels[i+2] *= b; @@ -181,7 +189,8 @@ * * @param color {number} the color to round, should be a hex color */ -CanvasTinter.roundColor = function (color) { +CanvasTinter.roundColor = function (color) +{ var step = CanvasTinter.cacheStepsPerColorChannel; var rgbValues = utils.hex2rgb(color); diff --git a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js index 9f2f89a..35edbaf 100644 --- a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js +++ b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLBlendModeManager(renderer) { +function WebGLBlendModeManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -23,8 +24,10 @@ * * @param blendMode {number} the blendMode, should be a Pixi const, such as BlendModes.ADD */ -WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) { - if (this.currentBlendMode === blendMode) { +WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) +{ + if (this.currentBlendMode === blendMode) + { return false; } diff --git a/src/core/renderers/webgl/managers/WebGLFilterManager.js b/src/core/renderers/webgl/managers/WebGLFilterManager.js index 1179258..2dac048 100644 --- a/src/core/renderers/webgl/managers/WebGLFilterManager.js +++ b/src/core/renderers/webgl/managers/WebGLFilterManager.js @@ -7,7 +7,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLFilterManager(renderer) { +function WebGLFilterManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -32,7 +33,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.texturePool.length = 0; self.initShaderBuffers(); }); @@ -46,7 +48,8 @@ * @param renderer {WebGLRenderer} * @param buffer {ArrayBuffer} */ -WebGLFilterManager.prototype.begin = function (buffer) { +WebGLFilterManager.prototype.begin = function (buffer) +{ this.defaultShader = this.renderer.shaderManager.defaultShader; this.width = this.renderer.projection.x * 2; @@ -60,7 +63,8 @@ * * @param filterBlock {object} the filter that will be pushed to the current filter stack */ -WebGLFilterManager.prototype.pushFilter = function (filterBlock) { +WebGLFilterManager.prototype.pushFilter = function (filterBlock) +{ var gl = this.renderer.gl; var projection = this.renderer.projection; @@ -78,10 +82,12 @@ this.offsetY += filterBlock._filterArea.y; var texture = this.texturePool.pop(); - if (!texture) { + if (!texture) + { texture = new FilterTexture(this.renderer.gl, this.width, this.height); } - else { + else + { texture.resize(this.width, this.height); } @@ -98,29 +104,35 @@ var localX = filterArea.x, localY = filterArea.y; - if (filterArea.x < 0) { + if (filterArea.x < 0) + { filterArea.width += filterArea.x; filterArea.x = 0; } - if (filterArea.y < 0) { + if (filterArea.y < 0) + { filterArea.height += filterArea.y; filterArea.y = 0; } - if (localX + filterArea.width > this.width) { + if (localX + filterArea.width > this.width) + { filterArea.width = this.width - localX; } - if (localY + filterArea.height > this.height) { + if (localY + filterArea.height > this.height) + { filterArea.height = this.height - localY; } - if (filterArea.width < 0) { + if (filterArea.width < 0) + { filterArea.width = 0; } - if (filterArea.height < 0) { + if (filterArea.height < 0) + { filterArea.height = 0; } @@ -154,7 +166,8 @@ * Removes the last filter from the filter stack and doesn't return it. * */ -WebGLFilterManager.prototype.popFilter = function () { +WebGLFilterManager.prototype.popFilter = function () +{ var gl = this.renderer.gl; var filterBlock = this.filterStack.pop(); @@ -163,7 +176,8 @@ var projection = this.renderer.projection; var offset = this.renderer.offset; - if (filterBlock.filterPasses.length > 1) { + if (filterBlock.filterPasses.length > 1) + { gl.viewport(0, 0, filterArea.width, filterArea.height); gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); @@ -193,7 +207,8 @@ var inputTexture = texture; var outputTexture = this.texturePool.pop(); - if (!outputTexture) { + if (!outputTexture) + { outputTexture = new FilterTexture(this.renderer.gl, this.width, this.height); } outputTexture.resize(this.width, this.height); @@ -204,7 +219,8 @@ gl.disable(gl.BLEND); - for (var i = 0; i < filterBlock.filterPasses.length-1; i++) { + for (var i = 0; i < filterBlock.filterPasses.length-1; i++) + { var filterPass = filterBlock.filterPasses[i]; gl.bindFramebuffer(gl.FRAMEBUFFER, outputTexture.frameBuffer ); @@ -243,10 +259,12 @@ var buffer = this.buffer; // time to render the filters texture to the previous scene - if (this.filterStack.length === 0) { + if (this.filterStack.length === 0) + { gl.colorMask(true, true, true, true);//this.transparent); } - else { + else + { var currentFilter = this.filterStack[this.filterStack.length-1]; filterArea = currentFilter._filterArea; @@ -332,13 +350,15 @@ * @param width {number} the horizontal range of the filter * @param height {number} the vertical range of the filter */ -WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) { +WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) +{ // use program var gl = this.renderer.gl; var shader = filter.shaders[gl.id]; - if (!shader) { + if (!shader) + { shader = new Shader(gl); shader.fragmentSrc = filter.fragmentSrc; @@ -356,7 +376,8 @@ gl.uniform2f(shader.projectionVector, width/2, -height/2); gl.uniform2f(shader.offsetVector, 0,0); - if (filter.uniforms.dimensions) { + 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]; @@ -386,7 +407,8 @@ * Initialises the shader buffers. * */ -WebGLFilterManager.prototype.initShaderBuffers = function () { +WebGLFilterManager.prototype.initShaderBuffers = function () +{ var gl = this.renderer.gl; // create some buffers @@ -432,7 +454,8 @@ * Destroys the filter and removes it from the filter stack. * */ -WebGLFilterManager.prototype.destroy = function () { +WebGLFilterManager.prototype.destroy = function () +{ var gl = this.renderer.gl; this.filterStack = null; @@ -441,7 +464,8 @@ this.offsetY = 0; // destroy textures - for (var i = 0; i < this.texturePool.length; i++) { + for (var i = 0; i < this.texturePool.length; i++) + { this.texturePool[i].destroy(); } diff --git a/src/core/renderers/webgl/managers/WebGLManager.js b/src/core/renderers/webgl/managers/WebGLManager.js index 9d47b5c..c30cd51 100644 --- a/src/core/renderers/webgl/managers/WebGLManager.js +++ b/src/core/renderers/webgl/managers/WebGLManager.js @@ -3,7 +3,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLManager(renderer) { +function WebGLManager(renderer) +{ /** * The renderer this manager works for. * @@ -15,6 +16,7 @@ WebGLManager.prototype.constructor = WebGLManager; module.exports = WebGLManager; -WebGLManager.prototype.destroy = function () { +WebGLManager.prototype.destroy = function () +{ this.renderer = null; }; diff --git a/src/core/renderers/webgl/managers/WebGLMaskManager.js b/src/core/renderers/webgl/managers/WebGLMaskManager.js index 2f90b64..e568812 100644 --- a/src/core/renderers/webgl/managers/WebGLMaskManager.js +++ b/src/core/renderers/webgl/managers/WebGLMaskManager.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLMaskManager(renderer) { +function WebGLMaskManager(renderer) +{ WebGLManager.call(this, renderer); } @@ -19,12 +20,15 @@ * * @param maskData {any[]} */ -WebGLMaskManager.prototype.pushMask = function (maskData) { - if (maskData.dirty) { +WebGLMaskManager.prototype.pushMask = function (maskData) +{ + if (maskData.dirty) + { WebGLGraphics.updateGraphics(maskData, this.renderer.gl); } - if (!maskData._webGL[this.renderer.gl.id].data.length) { + if (!maskData._webGL[this.renderer.gl.id].data.length) + { return; } @@ -36,6 +40,7 @@ * * @param maskData {any[]} */ -WebGLMaskManager.prototype.popMask = function (maskData) { +WebGLMaskManager.prototype.popMask = function (maskData) +{ this.renderer.stencilManager.popStencil(maskData, maskData._webGL[this.renderer.gl.id].data[0], this.renderer); }; diff --git a/src/core/renderers/webgl/managers/WebGLShaderManager.js b/src/core/renderers/webgl/managers/WebGLShaderManager.js index fef071c..90c6477 100644 --- a/src/core/renderers/webgl/managers/WebGLShaderManager.js +++ b/src/core/renderers/webgl/managers/WebGLShaderManager.js @@ -10,7 +10,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLShaderManager(renderer) { +function WebGLShaderManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -28,7 +29,8 @@ */ this.tempAttribState = []; - for (var i = 0; i < this.maxAttibs; i++) { + for (var i = 0; i < this.maxAttibs; i++) + { this.attribState[i] = false; } @@ -66,7 +68,8 @@ // listen for context and update necessary shaders var self = this; - this.renderer.on('context', function (event) { + this.renderer.on('context', function (event) + { var gl = event.data; // this shader is used for rendering primitives @@ -97,29 +100,36 @@ * * @param attribs {Array} attribs */ -WebGLShaderManager.prototype.setAttribs = function (attribs) { +WebGLShaderManager.prototype.setAttribs = function (attribs) +{ // reset temp state var i; - for (i = 0; i < this.tempAttribState.length; i++) { + for (i = 0; i < this.tempAttribState.length; i++) + { this.tempAttribState[i] = false; } // set the new attribs - for (var a in attribs) { + for (var a in attribs) + { this.tempAttribState[attribs[a]] = true; } var gl = this.renderer.gl; - for (i = 0; i < this.attribState.length; i++) { - if (this.attribState[i] !== this.tempAttribState[i]) { + for (i = 0; i < this.attribState.length; i++) + { + if (this.attribState[i] !== this.tempAttribState[i]) + { this.attribState[i] = this.tempAttribState[i]; - if (this.attribState[i]) { + if (this.attribState[i]) + { gl.enableVertexAttribArray(i); } - else { + else + { gl.disableVertexAttribArray(i); } } @@ -131,8 +141,10 @@ * * @param shader {Any} */ -WebGLShaderManager.prototype.setShader = function (shader) { - if (this._currentId === shader.uuid) { +WebGLShaderManager.prototype.setShader = function (shader) +{ + if (this._currentId === shader.uuid) + { return false; } @@ -150,7 +162,8 @@ * Destroys this object. * */ -WebGLShaderManager.prototype.destroy = function () { +WebGLShaderManager.prototype.destroy = function () +{ this.attribState = null; this.tempAttribState = null; diff --git a/src/core/renderers/webgl/managers/WebGLStencilManager.js b/src/core/renderers/webgl/managers/WebGLStencilManager.js index 9ec6398..4cb0134 100644 --- a/src/core/renderers/webgl/managers/WebGLStencilManager.js +++ b/src/core/renderers/webgl/managers/WebGLStencilManager.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLStencilManager(renderer) { +function WebGLStencilManager(renderer) +{ WebGLManager.call(this, renderer); this.stencilStack = []; @@ -24,12 +25,14 @@ * @param graphics {Graphics} * @param webGLData {any[]} */ -WebGLStencilManager.prototype.pushStencil = function (graphics, webGLData) { +WebGLStencilManager.prototype.pushStencil = function (graphics, webGLData) +{ var gl = this.renderer.gl; this.bindGraphics(graphics, webGLData, this.renderer); - if (this.stencilStack.length === 0) { + if (this.stencilStack.length === 0) + { gl.enable(gl.STENCIL_TEST); gl.clear(gl.STENCIL_BUFFER_BIT); this.reverse = true; @@ -47,14 +50,17 @@ // draw the triangle strip! - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } @@ -62,31 +68,38 @@ // draw a quad to increment.. gl.drawElements(gl.TRIANGLE_FAN, 4, gl.UNSIGNED_SHORT, ( webGLData.indices.length - 4 ) * 2 ); - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); } this.reverse = !this.reverse; } - else { - if (!this.reverse) { + else + { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } - else { + 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) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); } } @@ -103,7 +116,8 @@ * @param graphics {Graphics} * @param webGLData {Array} */ -WebGLStencilManager.prototype.bindGraphics = function (graphics, webGLData) { +WebGLStencilManager.prototype.bindGraphics = function (graphics, webGLData) +{ //if (this._currentGraphics === graphics)return; this._currentGraphics = graphics; @@ -114,7 +128,8 @@ offset = this.renderer.offset, shader;// = this.renderer.shaderManager.primitiveShader; - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { shader = this.renderer.shaderManager.complexPrimitiveShader; this.renderer.shaderManager.setShader(shader); @@ -141,7 +156,8 @@ // set the index buffer! gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, webGLData.indexBuffer); } - else { + else + { //this.renderer.shaderManager.activatePrimitiveShader(); shader = this.renderer.shaderManager.primitiveShader; this.renderer.shaderManager.setShader( shader ); @@ -154,7 +170,7 @@ gl.uniform2f(shader.uniforms.offsetVector._location, -offset.x, -offset.y); gl.uniform3fv(shader.uniforms.tint._location, utils.hex2rgb(graphics.tint)); - + gl.uniform1f(shader.uniforms.alpha._location, graphics.worldAlpha); @@ -172,19 +188,22 @@ * @param graphics {Graphics} * @param webGLData {Array} */ -WebGLStencilManager.prototype.popStencil = function (graphics, webGLData) { +WebGLStencilManager.prototype.popStencil = function (graphics, webGLData) +{ var gl = this.renderer.gl; this.stencilStack.pop(); this.count--; - if (this.stencilStack.length === 0) { + if (this.stencilStack.length === 0) + { // the stack is empty! gl.disable(gl.STENCIL_TEST); } - else { + else + { var level = this.count; @@ -192,14 +211,17 @@ gl.colorMask(false, false, false, false); - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { this.reverse = !this.reverse; - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } @@ -213,31 +235,38 @@ // draw the triangle strip! gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); - if (!this.reverse) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); } } - else { + else + { // console.log("<<>>") - if (!this.reverse) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } - else { + 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) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); } } @@ -253,7 +282,8 @@ * Destroys the mask stack. * */ -WebGLStencilManager.prototype.destroy = function () { +WebGLStencilManager.prototype.destroy = function () +{ this.renderer = null; this.stencilStack = null; }; diff --git a/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js b/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js index 913ba5e..1ea7d19 100644 --- a/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js +++ b/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function ComplexPrimitiveShader(gl) { +function ComplexPrimitiveShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -24,7 +25,8 @@ 'uniform float flipY;', 'varying vec4 vColor;', - 'void main(void) {', + '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);', @@ -37,7 +39,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = vColor;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/FastShader.js b/src/core/renderers/webgl/shaders/FastShader.js index bd2e29a..2e5e060 100644 --- a/src/core/renderers/webgl/shaders/FastShader.js +++ b/src/core/renderers/webgl/shaders/FastShader.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function FastShader(gl) { +function FastShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -28,7 +29,8 @@ 'const vec2 center = vec2(-1.0, 1.0);', - 'void main(void) {', + 'void main(void) + {', ' vec2 v;', ' vec2 sv = aVertexPosition * aScale;', ' v.x = (sv.x) * cos(aRotation) - (sv.y) * sin(aRotation);', @@ -49,7 +51,8 @@ 'uniform sampler2D uSampler;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/PrimitiveShader.js b/src/core/renderers/webgl/shaders/PrimitiveShader.js index 6f25409..a25f54f 100644 --- a/src/core/renderers/webgl/shaders/PrimitiveShader.js +++ b/src/core/renderers/webgl/shaders/PrimitiveShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function PrimitiveShader(gl) { +function PrimitiveShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -23,7 +24,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + '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);', @@ -36,7 +38,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = vColor;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/Shader.js b/src/core/renderers/webgl/shaders/Shader.js index f8964f5..fd75ef5 100644 --- a/src/core/renderers/webgl/shaders/Shader.js +++ b/src/core/renderers/webgl/shaders/Shader.js @@ -6,7 +6,8 @@ * @param [fragmentSrc] {string} The source of the fragment shader. * @param [vertexSrc] {string} The source of the vertex shader. */ -function Shader(gl, vertexSrc, fragmentSrc, customUniforms, customAttributes) { +function Shader(gl, vertexSrc, fragmentSrc, customUniforms, customAttributes) +{ /** * @member {number} * @readonly @@ -33,7 +34,8 @@ dimensions: { type: '4f', value: new Float32Array(4) } }; - for (var u in customUniforms) { + for (var u in customUniforms) + { this.uniforms[u] = customUniforms[u]; } @@ -43,7 +45,8 @@ aColor: 0 }; - for (var a in customAttributes) { + for (var a in customAttributes) + { this.attributes[a] = customAttributes[a]; } @@ -66,7 +69,8 @@ 'const vec2 center = vec2(-1.0, 1.0);', - 'void main(void) {', + 'void main(void) + {', ' gl_Position = vec4( ((aVertexPosition + offsetVector) / projectionVector) + center , 0.0, 1.0);', ' vTextureCoord = aTextureCoord;', ' vColor = vec4(aColor.rgb * aColor.a, aColor.a);', @@ -85,7 +89,8 @@ 'uniform sampler2D uSampler;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;', '}' ].join('\n'); @@ -96,7 +101,8 @@ Shader.prototype.constructor = Shader; module.exports = Shader; -Shader.prototype.init = function () { +Shader.prototype.init = function () +{ this.compile(); this.gl.useProgram(this.program); @@ -105,14 +111,18 @@ this.cacheAttributeLocations(Object.keys(this.attributes)); }; -Shader.prototype.cacheUniformLocations = function (keys) { - for (var i = 0; i < keys.length; ++i) { +Shader.prototype.cacheUniformLocations = function (keys) +{ + for (var i = 0; i < keys.length; ++i) + { this.uniforms[keys[i]]._location = this.gl.getUniformLocation(this.program, keys[i]); } }; -Shader.prototype.cacheAttributeLocations = function (keys) { - for (var i = 0; i < keys.length; ++i) { +Shader.prototype.cacheAttributeLocations = function (keys) +{ + for (var i = 0; i < keys.length; ++i) + { this.attributes[keys[i]] = this.gl.getAttribLocation(this.program, keys[i]); } @@ -124,14 +134,16 @@ // 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.attributes.aColor === -1) { + // if (this.attributes.aColor === -1) + { // this.attributes.aColor = 2; // } // End worst hack eva // }; -Shader.prototype.compile = function () { +Shader.prototype.compile = function () +{ var gl = this.gl; var glVertShader = this._glCompile(gl.VERTEX_SHADER, this.vertexSrc); @@ -144,13 +156,15 @@ gl.linkProgram(program); // if linking fails, then log and cleanup - if (!gl.getProgramParameter(program, gl.LINK_STATUS)) { + if (!gl.getProgramParameter(program, gl.LINK_STATUS)) + { window.console.error('Pixi.js Error: Could not initialize shader.'); window.console.error('gl.VALIDATE_STATUS', gl.getProgramParameter(program, gl.VALIDATE_STATUS)); window.console.error('gl.getError()', gl.getError()); // if there is a program info log, log it - if (gl.getProgramInfoLog(program) !== '') { + if (gl.getProgramInfoLog(program) !== '') + { window.console.warn('Pixi.js Warning: gl.getProgramInfoLog()', gl.getProgramInfoLog(program)); } @@ -165,18 +179,21 @@ return (this.program = program); }; -Shader.prototype.syncUniforms = function () { +Shader.prototype.syncUniforms = function () +{ var gl = this.gl; this.textureCount = 1; - for (var key in this.uniforms) { + for (var key in this.uniforms) + { var uniform = this.uniforms[key], location = uniform._location, value = uniform.value, i, il; - switch (uniform.type) { + switch (uniform.type) + { // single int value case 'i': case '1i': @@ -282,7 +299,8 @@ // a Color Value case 'c': - if (typeof value === 'number') { + if (typeof value === 'number') + { value = utils.hex2rgb(value); } @@ -311,11 +329,13 @@ // array of 2D Point objects case 'v2v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(2 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 2] = value[i].x; uniform._array[i * 2 + 1] = value[i].y; } @@ -325,11 +345,13 @@ // array of 3D Point objects case 'v3v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(3 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 3] = value[i].x; uniform._array[i * 3 + 1] = value[i].y; uniform._array[i * 3 + 2] = value[i].z; @@ -341,11 +363,13 @@ // array of 4D Point objects case 'v4v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(4 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 4] = value[i].x; uniform._array[i * 4 + 1] = value[i].y; uniform._array[i * 4 + 2] = value[i].z; @@ -359,7 +383,8 @@ // PIXI.Texture case 't': case 'sampler2D': - if (!uniform.value || !uniform.value.baseTexture || !uniform.value.baseTexture.hasLoaded) { + if (!uniform.value || !uniform.value.baseTexture || !uniform.value.baseTexture.hasLoaded) + { break; } @@ -376,7 +401,8 @@ this.textureCount++; // initialize the texture if we haven't yet - if (!uniform._init) { + if (!uniform._init) + { this.initSampler2D(uniform); uniform._init = true; @@ -394,11 +420,13 @@ * Initialises a Sampler2D uniform (which may only be available later on after initUniforms once the texture has loaded) * */ -Shader.prototype.initSampler2D = function (uniform) { +Shader.prototype.initSampler2D = function (uniform) +{ var gl = this.gl; // Extended texture data - if (uniform.textureData) { + if (uniform.textureData) + { var data = uniform.textureData; // GLTexture = mag linear, min linear_mipmap_linear, wrap repeat + gl.generateMipmap(gl.TEXTURE_2D); @@ -417,14 +445,16 @@ var wrapT = (data.wrapT) ? data.wrapT : gl.CLAMP_TO_EDGE; var format = (data.luminance) ? gl.LUMINANCE : gl.RGBA; - if (data.repeat) { + if (data.repeat) + { wrapS = gl.REPEAT; wrapT = gl.REPEAT; } gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, !!data.flipY); - if (data.width) { + if (data.width) + { var width = (data.width) ? data.width : 512; var height = (data.height) ? data.height : 2; var border = (data.border) ? data.border : 0; @@ -432,7 +462,8 @@ // 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 { + 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); } @@ -448,7 +479,8 @@ * Destroys the shader. * */ -Shader.prototype.destroy = function () { +Shader.prototype.destroy = function () +{ this.gl.deleteProgram(this.program); this.gl = null; @@ -459,13 +491,15 @@ this.fragmentSrc = null; }; -Shader.prototype._glCompile = function (type, src) { +Shader.prototype._glCompile = function (type, src) +{ var shader = this.gl.createShader(type); this.gl.shaderSource(shader, src); this.gl.compileShader(shader); - if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) { + if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) + { window.console.log(this.gl.getShaderInfoLog(shader)); return null; } diff --git a/src/core/renderers/webgl/shaders/StripShader.js b/src/core/renderers/webgl/shaders/StripShader.js index 193f6e1..a7abcc6 100644 --- a/src/core/renderers/webgl/shaders/StripShader.js +++ b/src/core/renderers/webgl/shaders/StripShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function StripShader(gl) { +function StripShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -20,7 +21,8 @@ 'varying vec2 vTextureCoord;', - 'void main(void) {', + '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);', @@ -36,7 +38,8 @@ 'varying vec2 vTextureCoord;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vec2(vTextureCoord.x, vTextureCoord.y)) * alpha;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/utils/FilterTexture.js b/src/core/renderers/webgl/utils/FilterTexture.js index d2c8423..4433d44 100644 --- a/src/core/renderers/webgl/utils/FilterTexture.js +++ b/src/core/renderers/webgl/utils/FilterTexture.js @@ -8,7 +8,8 @@ * @param height {number} the vertical range of the filter * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values */ -function FilterTexture(gl, width, height, scaleMode) { +function FilterTexture(gl, width, height, scaleMode) +{ /** * @member {WebGLContext} */ @@ -59,7 +60,8 @@ * Clears the filter texture. * */ -FilterTexture.prototype.clear = function () { +FilterTexture.prototype.clear = function () +{ var gl = this.gl; gl.clearColor(0,0,0, 0); @@ -72,8 +74,10 @@ * @param width {number} the new width of the texture * @param height {number} the new height of the texture */ -FilterTexture.prototype.resize = function (width, height) { - if (this.width === width && this.height === height) { +FilterTexture.prototype.resize = function (width, height) +{ + if (this.width === width && this.height === height) + { return; } @@ -96,7 +100,8 @@ * Destroys the filter texture. * */ -FilterTexture.prototype.destroy = function () { +FilterTexture.prototype.destroy = function () +{ var gl = this.gl; gl.deleteFramebuffer( this.frameBuffer ); gl.deleteTexture( this.texture ); diff --git a/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js b/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js index c4721e9..a63f4d7 100644 --- a/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js +++ b/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js @@ -14,7 +14,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this sprite batch works for. */ -function WebGLFastSpriteBatch(renderer) { +function WebGLFastSpriteBatch(renderer) +{ /** * The renderer instance this sprite batch operates on. * @@ -91,7 +92,8 @@ */ this.lastIndexCount = 0; - for (var i=0, j=0; i < numIndices; i += 6, j += 4) { + 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; @@ -144,7 +146,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.setupContext(); }); } @@ -157,7 +160,8 @@ * * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLFastSpriteBatch.prototype.setupContext = function () { +WebGLFastSpriteBatch.prototype.setupContext = function () +{ var gl = this.renderer.gl; // create a couple of buffers @@ -177,7 +181,8 @@ /** * @param spriteBatch {SpriteBatch} The SpriteBatch container to prepare for. */ -WebGLFastSpriteBatch.prototype.begin = function (spriteBatch) { +WebGLFastSpriteBatch.prototype.begin = function (spriteBatch) +{ this.shader = this.renderer.shaderManager.fastShader; this.matrix = spriteBatch.worldTransform.toArray(true); @@ -187,33 +192,38 @@ /** */ -WebGLFastSpriteBatch.prototype.end = function () { +WebGLFastSpriteBatch.prototype.end = function () +{ this.flush(); }; /** * @param spriteBatch {SpriteBatch} The SpriteBatch container to render. */ -WebGLFastSpriteBatch.prototype.render = function (spriteBatch) { +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) { + if (!sprite.texture._uvs) + { return; } this.currentBaseTexture = sprite.texture.baseTexture; // check blend mode - if (sprite.blendMode !== this.renderer.blendModeManager.currentBlendMode) { + if (sprite.blendMode !== this.renderer.blendModeManager.currentBlendMode) + { this.flush(); this.renderer.blendModeManager.setBlendMode(sprite.blendMode); } - for (var i=0,j= children.length; i= this.size) { + if (this.currentBatchSize >= this.size) + { this.flush(); } }; @@ -362,29 +379,35 @@ /** * */ -WebGLFastSpriteBatch.prototype.flush = function () { +WebGLFastSpriteBatch.prototype.flush = function () +{ // If the batch is length 0 then return as there is nothing to draw - if (this.currentBatchSize === 0) { + if (this.currentBatchSize === 0) + { return; } var gl = this.renderer.gl; // bind the current texture - if (!this.currentBaseTexture._glTextures[gl.id]) { + if (!this.currentBaseTexture._glTextures[gl.id]) + { this.renderer.updateTexture(this.currentBaseTexture, gl); } //TODO-SHOUD THIS BE ELSE??!?!?! - else { + else + { gl.bindTexture(gl.TEXTURE_2D, this.currentBaseTexture._glTextures[gl.id]); } // upload the verts to the buffer - if (this.currentBatchSize > ( this.size * 0.5 ) ) { + if (this.currentBatchSize > ( this.size * 0.5 ) ) + { gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); } - else { + else + { var view = this.vertices.subarray(0, this.currentBatchSize * this.vertByteSize); gl.bufferSubData(gl.ARRAY_BUFFER, 0, view); @@ -405,14 +428,16 @@ * Ends the batch and flushes * */ -WebGLFastSpriteBatch.prototype.stop = function () { +WebGLFastSpriteBatch.prototype.stop = function () +{ this.flush(); }; /** * */ -WebGLFastSpriteBatch.prototype.start = function () { +WebGLFastSpriteBatch.prototype.start = function () +{ var gl = this.renderer.gl; // bind the main texture diff --git a/src/core/renderers/webgl/utils/WebGLGraphics.js b/src/core/renderers/webgl/utils/WebGLGraphics.js index 55f4911..ab8f46e 100644 --- a/src/core/renderers/webgl/utils/WebGLGraphics.js +++ b/src/core/renderers/webgl/utils/WebGLGraphics.js @@ -19,7 +19,8 @@ * @param graphics {Graphics} * @param renderer {WebGLRenderer} */ -WebGLGraphics.renderGraphics = function (graphics, renderer) {//projection, offset) { +WebGLGraphics.renderGraphics = function (graphics, renderer) {//projection, offset) +{ var gl = renderer.gl; var projection = renderer.projection, @@ -27,7 +28,8 @@ shader = renderer.shaderManager.primitiveShader, webGLData; - if (graphics.dirty) { + if (graphics.dirty) + { WebGLGraphics.updateGraphics(graphics, gl); } @@ -35,8 +37,10 @@ // This could be speeded up for sure! - for (var i = 0; i < webGL.data.length; i++) { - if (webGL.data[i].mode === 1) { + for (var i = 0; i < webGL.data.length; i++) + { + if (webGL.data[i].mode === 1) + { webGLData = webGL.data[i]; renderer.stencilManager.pushStencil(graphics, webGLData, renderer); @@ -46,7 +50,8 @@ renderer.stencilManager.popStencil(graphics, webGLData, renderer); } - else { + else + { webGLData = webGL.data[i]; @@ -84,12 +89,14 @@ * @param graphicsData {Graphics} The graphics object to update * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLGraphics.updateGraphics = function (graphics, gl) { +WebGLGraphics.updateGraphics = function (graphics, gl) +{ // get the contexts graphics object var webGL = graphics._webGL[gl.id]; // if the graphics object does not exist in the webGL context time to create it! - if (!webGL) { + if (!webGL) + { webGL = graphics._webGL[gl.id] = {lastIndex:0, data:[], gl:gl}; } @@ -99,11 +106,13 @@ var i; // if the user cleared the graphics object we will need to clear every object - if (graphics.clearDirty) { + if (graphics.clearDirty) + { graphics.clearDirty = false; // lop through and return all the webGLDatas to the object pool so than can be reused later on - for (i = 0; i < webGL.data.length; i++) { + for (i = 0; i < webGL.data.length; i++) + { var graphicsData = webGL.data[i]; graphicsData.reset(); WebGLGraphics.graphicsDataPool.push( graphicsData ); @@ -119,58 +128,72 @@ // loop through the graphics datas and construct each one.. // if the object is a complex fill then the new stencil buffer technique will be used // other wise graphics objects will be pushed into a batch.. - for (i = webGL.lastIndex; i < graphics.graphicsData.length; i++) { + for (i = webGL.lastIndex; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { // need to add the points the the graphics object.. data.points = data.shape.points.slice(); - if (data.shape.closed) { + if (data.shape.closed) + { // close the poly if the value is true! - if (data.points[0] !== data.points[data.points.length-2] || data.points[1] !== data.points[data.points.length-1]) { + if (data.points[0] !== data.points[data.points.length-2] || data.points[1] !== data.points[data.points.length-1]) + { data.points.push(data.points[0], data.points[1]); } } // MAKE SURE WE HAVE THE CORRECT TYPE.. - if (data.fill) { - if (data.points.length >= 6) { - if (data.points.length < 6 * 2) { + if (data.fill) + { + if (data.points.length >= 6) + { + if (data.points.length < 6 * 2) + { webGLData = WebGLGraphics.switchMode(webGL, 0); var canDrawUsingSimple = WebGLGraphics.buildPoly(data, webGLData); // console.log(canDrawUsingSimple); - if (!canDrawUsingSimple) { + if (!canDrawUsingSimple) + { // console.log("<>>>") webGLData = WebGLGraphics.switchMode(webGL, 1); WebGLGraphics.buildComplexPoly(data, webGLData); } } - else { + else + { webGLData = WebGLGraphics.switchMode(webGL, 1); WebGLGraphics.buildComplexPoly(data, webGLData); } } } - if (data.lineWidth > 0) { + if (data.lineWidth > 0) + { webGLData = WebGLGraphics.switchMode(webGL, 0); WebGLGraphics.buildLine(data, webGLData); } } - else { + else + { webGLData = WebGLGraphics.switchMode(webGL, 0); - if (data.type === CONST.SHAPES.RECT) { + if (data.type === CONST.SHAPES.RECT) + { WebGLGraphics.buildRectangle(data, webGLData); } - else if (data.type === CONST.SHAPES.CIRC || data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.CIRC || data.type === CONST.SHAPES.ELIP) + { WebGLGraphics.buildCircle(data, webGLData); } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { WebGLGraphics.buildRoundedRectangle(data, webGLData); } } @@ -179,10 +202,12 @@ } // upload all the dirty data... - for (i = 0; i < webGL.data.length; i++) { + for (i = 0; i < webGL.data.length; i++) + { webGLData = webGL.data[i]; - if (webGLData.dirty) { + if (webGLData.dirty) + { webGLData.upload(); } } @@ -194,18 +219,22 @@ * @param webGL {WebGLContext} * @param type {number} */ -WebGLGraphics.switchMode = function (webGL, type) { +WebGLGraphics.switchMode = function (webGL, type) +{ var webGLData; - if (!webGL.data.length) { + if (!webGL.data.length) + { webGLData = WebGLGraphics.graphicsDataPool.pop() || new WebGLGraphicsData(webGL.gl); webGLData.mode = type; webGL.data.push(webGLData); } - else { + else + { webGLData = webGL.data[webGL.data.length-1]; - if (webGLData.mode !== type || type === 1) { + if (webGLData.mode !== type || type === 1) + { webGLData = WebGLGraphics.graphicsDataPool.pop() || new WebGLGraphicsData(webGL.gl); webGLData.mode = type; webGL.data.push(webGLData); @@ -225,7 +254,8 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildRectangle = function (graphicsData, webGLData) { +WebGLGraphics.buildRectangle = function (graphicsData, webGLData) +{ // --- // // need to convert points to a nice regular data // @@ -235,7 +265,8 @@ var width = rectData.width; var height = rectData.height; - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -265,7 +296,8 @@ indices.push(vertPos, vertPos, vertPos+1, vertPos+2, vertPos+3, vertPos+3); } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = [x, y, @@ -289,7 +321,8 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildRoundedRectangle = function (graphicsData, webGLData) { +WebGLGraphics.buildRoundedRectangle = function (graphicsData, webGLData) +{ var rrectData = graphicsData.shape; var x = rrectData.x; var y = rrectData.y; @@ -305,7 +338,8 @@ recPoints = recPoints.concat(WebGLGraphics.quadraticBezierCurve(x + width, y + radius, x + width, y, x + width - radius, y)); recPoints = recPoints.concat(WebGLGraphics.quadraticBezierCurve(x + radius, y, x, y, x, y + radius)); - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -323,7 +357,8 @@ // var i = 0; - for (i = 0; i < triangles.length; i+=3) { + for (i = 0; i < triangles.length; i+=3) + { indices.push(triangles[i] + vecPos); indices.push(triangles[i] + vecPos); indices.push(triangles[i+1] + vecPos); @@ -332,12 +367,14 @@ } - for (i = 0; i < recPoints.length; i++) { + for (i = 0; i < recPoints.length; i++) + { verts.push(recPoints[i], recPoints[++i], r, g, b, alpha); } } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = recPoints; @@ -362,7 +399,8 @@ * @param toY {number} Destination point y * @return {number[]} */ -WebGLGraphics.quadraticBezierCurve = function (fromX, fromY, cpX, cpY, toX, toY) { +WebGLGraphics.quadraticBezierCurve = function (fromX, fromY, cpX, cpY, toX, toY) +{ var xa, ya, @@ -373,14 +411,16 @@ n = 20, points = []; - function getPt(n1 , n2, perc) { + function getPt(n1 , n2, perc) + { var diff = n2 - n1; return n1 + ( diff * perc ); } var j = 0; - for (var i = 0; i <= n; i++ ) { + for (var i = 0; i <= n; i++ ) + { j = i / n; // The Green Line @@ -406,7 +446,8 @@ * @param graphicsData {Graphics} The graphics object to draw * @param webGLData {object} */ -WebGLGraphics.buildCircle = function (graphicsData, webGLData) { +WebGLGraphics.buildCircle = function (graphicsData, webGLData) +{ // need to convert points to a nice regular data var circleData = graphicsData.shape; var x = circleData.x; @@ -415,11 +456,13 @@ var height; // TODO - bit hacky?? - if (graphicsData.type === CONST.SHAPES.CIRC) { + if (graphicsData.type === CONST.SHAPES.CIRC) + { width = circleData.radius; height = circleData.radius; } - else { + else + { width = circleData.width; height = circleData.height; } @@ -429,7 +472,8 @@ var i = 0; - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -444,7 +488,8 @@ indices.push(vecPos); - for (i = 0; i < totalSegs + 1 ; i++) { + for (i = 0; i < totalSegs + 1 ; i++) + { verts.push(x,y, r, g, b, alpha); verts.push(x + Math.sin(seg * i) * width, @@ -457,12 +502,14 @@ indices.push(vecPos-1); } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = []; - for (i = 0; i < totalSegs + 1; i++) { + for (i = 0; i < totalSegs + 1; i++) + { graphicsData.points.push(x + Math.sin(seg * i) * width, y + Math.cos(seg * i) * height); } @@ -481,18 +528,22 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildLine = function (graphicsData, webGLData) { +WebGLGraphics.buildLine = function (graphicsData, webGLData) +{ // TODO OPTIMISE! var i = 0; var points = graphicsData.points; - if (points.length === 0) { + if (points.length === 0) + { return; } // if the line width is an odd number add 0.5 to align to a whole pixel - if (graphicsData.lineWidth%2) { - for (i = 0; i < points.length; i++) { + if (graphicsData.lineWidth%2) + { + for (i = 0; i < points.length; i++) + { points[i] += 0.5; } } @@ -502,7 +553,8 @@ var lastPoint = new math.Point(points[points.length - 2], points[points.length - 1]); // if the first point is the last point - gonna have issues :) - if (firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) { + if (firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) + { // need to clone as we are going to slightly modify the shape.. points = points.slice(); @@ -562,7 +614,8 @@ verts.push(p1x + perpx , p1y + perpy, r, g, b, alpha); - for (i = 1; i < length-1; i++) { + for (i = 1; i < length-1; i++) + { p1x = points[(i-1)*2]; p1y = points[(i-1)*2 + 1]; @@ -599,7 +652,8 @@ denom = a1*b2 - a2*b1; - if (Math.abs(denom) < 0.1 ) { + if (Math.abs(denom) < 0.1 ) + { denom+=10.1; verts.push(p2x - perpx , p2y - perpy, @@ -618,7 +672,8 @@ pdist = (px -p2x) * (px -p2x) + (py -p2y) + (py -p2y); - if (pdist > 140 * 140) { + if (pdist > 140 * 140) + { perp3x = perpx - perp2x; perp3y = perpy - perp2y; @@ -639,7 +694,8 @@ indexCount++; } - else { + else + { verts.push(px , py); verts.push(r, g, b, alpha); @@ -672,7 +728,8 @@ indices.push(indexStart); - for (i = 0; i < indexCount; i++) { + for (i = 0; i < indexCount; i++) + { indices.push(indexStart++); } @@ -687,11 +744,13 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildComplexPoly = function (graphicsData, webGLData) { +WebGLGraphics.buildComplexPoly = function (graphicsData, webGLData) +{ //TODO - no need to copy this as it gets turned into a FLoat32Array anyways.. var points = graphicsData.points.slice(); - if (points.length < 6) { + if (points.length < 6) + { return; } @@ -711,7 +770,8 @@ var x,y; // get size.. - for (var i = 0; i < points.length; i+=2) { + for (var i = 0; i < points.length; i+=2) + { x = points[i]; y = points[i+1]; @@ -732,7 +792,8 @@ //TODO - this aint needed! var length = points.length / 2; - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { indices.push( i ); } @@ -746,10 +807,12 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildPoly = function (graphicsData, webGLData) { +WebGLGraphics.buildPoly = function (graphicsData, webGLData) +{ var points = graphicsData.points; - if (points.length < 6) { + if (points.length < 6) + { return; } // get first and last point.. figure out the middle! @@ -767,7 +830,8 @@ var triangles = utils.PolyK.Triangulate(points); - if (!triangles) { + if (!triangles) + { return false; } @@ -775,7 +839,8 @@ var i = 0; - for (i = 0; i < triangles.length; i+=3) { + for (i = 0; i < triangles.length; i+=3) + { indices.push(triangles[i] + vertPos); indices.push(triangles[i] + vertPos); indices.push(triangles[i+1] + vertPos); @@ -783,7 +848,8 @@ indices.push(triangles[i+2] + vertPos); } - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { verts.push(points[i * 2], points[i * 2 + 1], r, g, b, alpha); } diff --git a/src/core/renderers/webgl/utils/WebGLGraphicsData.js b/src/core/renderers/webgl/utils/WebGLGraphicsData.js index c56d05e..c739ba7 100644 --- a/src/core/renderers/webgl/utils/WebGLGraphicsData.js +++ b/src/core/renderers/webgl/utils/WebGLGraphicsData.js @@ -2,7 +2,8 @@ * @class * @private */ -function WebGLGraphicsData(gl) { +function WebGLGraphicsData(gl) +{ this.gl = gl; //TODO does this need to be split before uploding?? @@ -22,7 +23,8 @@ /** * */ -WebGLGraphicsData.prototype.reset = function () { +WebGLGraphicsData.prototype.reset = function () +{ this.points.length = 0; this.indices.length = 0; }; @@ -30,7 +32,8 @@ /** * */ -WebGLGraphicsData.prototype.upload = function () { +WebGLGraphicsData.prototype.upload = function () +{ var gl = this.gl; // this.lastIndex = graphics.graphicsData.length; diff --git a/src/core/renderers/webgl/utils/WebGLSpriteBatch.js b/src/core/renderers/webgl/utils/WebGLSpriteBatch.js index 96eaa52..55befbb 100644 --- a/src/core/renderers/webgl/utils/WebGLSpriteBatch.js +++ b/src/core/renderers/webgl/utils/WebGLSpriteBatch.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this sprite batch works for. */ -function WebGLSpriteBatch(renderer) { +function WebGLSpriteBatch(renderer) +{ /** * * @@ -88,7 +89,8 @@ */ this.lastIndexCount = 0; - for (var i=0, j=0; i < numIndices; i += 6, j += 4) { + 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; @@ -162,7 +164,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.setupContext(); }); } @@ -173,7 +176,8 @@ /** * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLSpriteBatch.prototype.setupContext = function () { +WebGLSpriteBatch.prototype.setupContext = function () +{ var gl = this.renderer.gl; // setup default shader @@ -198,7 +202,8 @@ /** * */ -WebGLSpriteBatch.prototype.begin = function () { +WebGLSpriteBatch.prototype.begin = function () +{ // this.shader = this.renderer.shaderManager.defaultShader; this.start(); @@ -206,19 +211,22 @@ /** */ -WebGLSpriteBatch.prototype.end = function () { +WebGLSpriteBatch.prototype.end = function () +{ this.flush(); }; /** * @param sprite {Sprite} the sprite to render when using this spritebatch */ -WebGLSpriteBatch.prototype.render = function (sprite) { +WebGLSpriteBatch.prototype.render = function (sprite) +{ var texture = sprite.texture; //TODO set blend modes.. // check texture.. - if (this.currentBatchSize >= this.size) { + if (this.currentBatchSize >= this.size) + { this.flush(); this.currentBaseTexture = texture.baseTexture; } @@ -227,7 +235,8 @@ var uvs = texture._uvs; // if the uvs have not updated then no point rendering just yet! - if (!uvs) { + if (!uvs) + { return; } @@ -237,7 +246,8 @@ var w0, w1, h0, h1; - if (texture.trim) { + 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; @@ -248,7 +258,8 @@ h0 = h1 + texture.crop.height; } - else { + else + { w0 = (texture.frame.width ) * (1-aX); w1 = (texture.frame.width ) * -aX; @@ -272,7 +283,8 @@ var colors = this.colors; var positions = this.positions; - if (this.renderer.roundPixels) { + if (this.renderer.roundPixels) + { // xy positions[index] = a * w1 + c * h1 + tx | 0; positions[index+1] = d * h1 + b * w1 + ty | 0; @@ -289,7 +301,8 @@ positions[index+15] = a * w1 + c * h0 + tx | 0; positions[index+16] = d * h0 + b * w1 + ty | 0; } - else { + else + { // xy positions[index] = a * w1 + c * h1 + tx; positions[index+1] = d * h1 + b * w1 + ty; @@ -338,11 +351,13 @@ * * @param sprite {TilingSprite} the tilingSprite to render */ -WebGLSpriteBatch.prototype.renderTilingSprite = function (tilingSprite) { +WebGLSpriteBatch.prototype.renderTilingSprite = function (tilingSprite) +{ var texture = tilingSprite.tilingTexture; // check texture.. - if (this.currentBatchSize >= this.size) { + if (this.currentBatchSize >= this.size) + { //return; this.flush(); this.currentBaseTexture = texture.baseTexture; @@ -351,7 +366,8 @@ // set the textures uvs temporarily // TODO create a separate texture so that we can tile part of a texture - if (!tilingSprite._uvs) { + if (!tilingSprite._uvs) + { tilingSprite._uvs = new TextureUvs(); } @@ -454,16 +470,19 @@ * Renders the content and empties the current batch. * */ -WebGLSpriteBatch.prototype.flush = function () { +WebGLSpriteBatch.prototype.flush = function () +{ // If the batch is length 0 then return as there is nothing to draw - if (this.currentBatchSize === 0) { + if (this.currentBatchSize === 0) + { return; } var gl = this.renderer.gl; var shader; - if (this.dirty) { + if (this.dirty) + { this.dirty = false; // bind the main texture gl.activeTexture(gl.TEXTURE0); @@ -482,10 +501,12 @@ } // upload the verts to the buffer - if (this.currentBatchSize > ( this.size * 0.5 ) ) { + if (this.currentBatchSize > ( this.size * 0.5 ) ) + { gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); } - else { + else + { var view = this.positions.subarray(0, this.currentBatchSize * this.vertByteSize); gl.bufferSubData(gl.ARRAY_BUFFER, 0, view); } @@ -502,7 +523,8 @@ var shaderSwap = false; var sprite; - for (var i = 0, j = this.currentBatchSize; i < j; i++) { + for (var i = 0, j = this.currentBatchSize; i < j; i++) + { sprite = this.sprites[i]; @@ -513,24 +535,28 @@ blendSwap = currentBlendMode !== nextBlendMode; shaderSwap = currentShader !== nextShader; // should I use uuidS??? - if (currentBaseTexture !== nextTexture || blendSwap || shaderSwap) { + if (currentBaseTexture !== nextTexture || blendSwap || shaderSwap) + { this.renderBatch(currentBaseTexture, batchSize, start); start = i; batchSize = 0; currentBaseTexture = nextTexture; - if (blendSwap) { + if (blendSwap) + { currentBlendMode = nextBlendMode; this.renderer.blendModeManager.setBlendMode( currentBlendMode ); } - if (shaderSwap) { + if (shaderSwap) + { currentShader = nextShader; shader = currentShader.shaders ? currentShader.shaders[gl.id] : currentShader; - if (!shader) { + if (!shader) + { shader = new Shader(gl, null, currentShader.fragmentSrc, currentShader.uniforms); currentShader.shaders[gl.id] = shader; } @@ -538,7 +564,8 @@ // set shader function??? this.renderer.shaderManager.setShader(shader); - if (shader.dirty) { + if (shader.dirty) + { shader.syncUniforms(); } @@ -569,17 +596,21 @@ * @param size {number} * @param startIndex {number} */ -WebGLSpriteBatch.prototype.renderBatch = function (texture, size, startIndex) { - if (size === 0) { +WebGLSpriteBatch.prototype.renderBatch = function (texture, size, startIndex) +{ + if (size === 0) + { return; } var gl = this.renderer.gl; - if (!texture._glTextures[gl.id]) { + if (!texture._glTextures[gl.id]) + { this.renderer.updateTexture(texture); } - else { + else + { // bind the current texture gl.bindTexture(gl.TEXTURE_2D, texture._glTextures[gl.id]); } @@ -594,7 +625,8 @@ /** * */ -WebGLSpriteBatch.prototype.stop = function () { +WebGLSpriteBatch.prototype.stop = function () +{ this.flush(); this.dirty = true; }; @@ -602,7 +634,8 @@ /** * */ -WebGLSpriteBatch.prototype.start = function () { +WebGLSpriteBatch.prototype.start = function () +{ this.dirty = true; }; @@ -610,7 +643,8 @@ * Destroys the SpriteBatch. * */ -WebGLSpriteBatch.prototype.destroy = function () { +WebGLSpriteBatch.prototype.destroy = function () +{ this.renderer.gl.deleteBuffer(this.vertexBuffer); this.renderer.gl.deleteBuffer(this.indexBuffer); diff --git a/src/core/textures/BaseTexture.js b/src/core/textures/BaseTexture.js index 2bf77d4..513d358 100644 --- a/src/core/textures/BaseTexture.js +++ b/src/core/textures/BaseTexture.js @@ -10,7 +10,8 @@ * @param source {Image|Canvas} the source object of the texture. * @param [scaleMode=scaleModes.DEFAULT] {number} See {@link scaleModes} for possible values */ -function BaseTexture(source, scaleMode) { +function BaseTexture(source, scaleMode) +{ this.uuid = utils.uuid(); /** @@ -123,7 +124,8 @@ this._needsUpdate = false; // if no source passed don't try to load - if (source) { + if (source) + { this.loadSource(source); } @@ -149,13 +151,16 @@ Object.defineProperties(BaseTexture.prototype, { needsUpdate: { - get: function () { + get: function () + { return this._needsUpdate; }, - set: function (val) { + set: function (val) + { this._needsUpdate = val; - if (val) { + if (val) + { this.emit('update', this); } } @@ -171,9 +176,11 @@ * * The logic state after calling `loadSource` directly or indirectly (eg. `fromImage`, `new BaseTexture`) is: * - * if (texture.hasLoaded) { + * if (texture.hasLoaded) + { * // texture ready for use - * } else if (texture.isLoading) { + * } else if (texture.isLoading) + { * // listen to 'loaded' and/or 'error' events on texture * } else { * // not loading, not going to load UNLESS the source is reloaded @@ -183,12 +190,14 @@ * @protected * @param source {Image|Canvas} the source object of the texture. */ -BaseTexture.prototype.loadSource = function (source) { +BaseTexture.prototype.loadSource = function (source) +{ var wasLoading = this.isLoading; this.hasLoaded = false; this.isLoading = false; - if (wasLoading && this.source) { + if (wasLoading && this.source) + { this.source.onload = null; this.source.onerror = null; } @@ -196,20 +205,24 @@ this.source = source; // Apply source if loaded. Otherwise setup appropriate loading monitors. - if ((this.source.complete || this.source.getContext) && this.source.width && this.source.height) { + if ((this.source.complete || this.source.getContext) && this.source.width && this.source.height) + { this._sourceLoaded(); } - else if(!source.getContext) { + else if(!source.getContext) + { // Image fail / not ready this.isLoading = true; var scope = this; - source.onload = function () { + source.onload = function () + { source.onload = null; source.onerror = null; - if(!scope.isLoading) { + if(!scope.isLoading) + { return; } @@ -219,11 +232,13 @@ scope.emit('loaded', scope); }; - source.onerror = function () { + source.onerror = function () + { source.onload = null; source.onerror = null; - if(!scope.isLoading) { + if(!scope.isLoading) + { return; } @@ -234,24 +249,29 @@ // Per http://www.w3.org/TR/html5/embedded-content-0.html#the-img-element // "The value of `complete` can thus change while a script is executing." // So complete needs to be re-checked after the callbacks have been added.. - if (source.complete) { + if (source.complete) + { this.isLoading = false; // ..and if we're complete now, no need for callbacks source.onload = null; source.onerror = null; - if (source.width && source.height) { + if (source.width && source.height) + { this._sourceLoaded(); // If any previous subscribers possible - if (wasLoading) { + if (wasLoading) + { this.emit('loaded', this); } } - else { + else + { // If any previous subscribers possible - if (wasLoading) { + if (wasLoading) + { this.emit('error', this); } } @@ -265,7 +285,8 @@ * * @private */ -BaseTexture.prototype._sourceLoaded = function () { +BaseTexture.prototype._sourceLoaded = function () +{ this.hasLoaded = true; this.width = this.source.naturalWidth || this.source.width; @@ -278,16 +299,20 @@ * Destroys this base texture * */ -BaseTexture.prototype.destroy = function () { - if (this.imageUrl) { +BaseTexture.prototype.destroy = function () +{ + if (this.imageUrl) + { delete utils.BaseTextureCache[this.imageUrl]; delete utils.TextureCache[this.imageUrl]; this.imageUrl = null; - if (!navigator.isCocoonJS) { + if (!navigator.isCocoonJS) + { this.source.src = ''; } } - else if (this.source && this.source._pixiId) { + else if (this.source && this.source._pixiId) + { delete utils.BaseTextureCache[this.source._pixiId]; } this.source = null; @@ -301,7 +326,8 @@ * memory again. * */ -BaseTexture.prototype.dispose = function () { +BaseTexture.prototype.dispose = function () +{ this.emit('dispose', this); }; @@ -311,7 +337,8 @@ * * @param newSrc {string} the path of the image */ -BaseTexture.prototype.updateSourceImage = function (newSrc) { +BaseTexture.prototype.updateSourceImage = function (newSrc) +{ this.source.src = newSrc; this.loadSource(this.source); }; @@ -326,18 +353,22 @@ * @param [scaleMode=scaleModes.DEFAULT] {number} See {@link scaleModes} for possible values * @return BaseTexture */ -BaseTexture.fromImage = function (imageUrl, crossorigin, scaleMode) { +BaseTexture.fromImage = function (imageUrl, crossorigin, scaleMode) +{ var baseTexture = utils.BaseTextureCache[imageUrl]; - if (crossorigin === undefined && imageUrl.indexOf('data:') !== 0) { + if (crossorigin === undefined && imageUrl.indexOf('data:') !== 0) + { crossorigin = true; } - if (!baseTexture) { + if (!baseTexture) + { // new Image() breaks tex loading in some versions of Chrome. // See https://code.google.com/p/chromium/issues/detail?id=238071 var image = new Image();//document.createElement('img'); - if (crossorigin) { + if (crossorigin) + { image.crossOrigin = ''; } @@ -347,7 +378,8 @@ utils.BaseTextureCache[imageUrl] = baseTexture; // if there is an @2x at the end of the url we are going to assume its a highres image - if ( imageUrl.indexOf(CONST.RETINA_PREFIX + '.') !== -1) { + if ( imageUrl.indexOf(CONST.RETINA_PREFIX + '.') !== -1) + { baseTexture.resolution = 2; } } @@ -363,14 +395,17 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return BaseTexture */ -BaseTexture.fromCanvas = function (canvas, scaleMode) { - if (!canvas._pixiId) { +BaseTexture.fromCanvas = function (canvas, scaleMode) +{ + if (!canvas._pixiId) + { canvas._pixiId = 'canvas_' + utils.uuid(); } var baseTexture = utils.BaseTextureCache[canvas._pixiId]; - if (!baseTexture) { + if (!baseTexture) + { baseTexture = new BaseTexture(canvas, scaleMode); utils.BaseTextureCache[canvas._pixiId] = baseTexture; } diff --git a/src/core/display/DisplayObject.js b/src/core/display/DisplayObject.js index 66ebc3c..20e778c 100644 --- a/src/core/display/DisplayObject.js +++ b/src/core/display/DisplayObject.js @@ -7,7 +7,8 @@ * @class * @namespace PIXI */ -function DisplayObject() { +function DisplayObject() +{ /** * The coordinate of the object relative to the local coordinates of the parent. * @@ -152,10 +153,12 @@ * @memberof DisplayObject# */ x: { - get: function () { + get: function () + { return this.position.x; }, - set: function (value) { + set: function (value) + { this.position.x = value; } }, @@ -167,10 +170,12 @@ * @memberof DisplayObject# */ y: { - get: function () { + get: function () + { return this.position.y; }, - set: function (value) { + set: function (value) + { this.position.y = value; } }, @@ -183,11 +188,13 @@ * @readonly */ worldVisible: { - get: function () { + get: function () + { var item = this; do { - if (!item.visible) { + if (!item.visible) + { return false; } @@ -207,17 +214,21 @@ * @memberof DisplayObject# */ mask: { - get: function () { + get: function () + { return this._mask; }, - set: function (value) { - if (this._mask) { + set: function (value) + { + if (this._mask) + { this._mask.isMask = false; } this._mask = value; - if (this._mask) { + if (this._mask) + { this._mask.isMask = true; } } @@ -232,18 +243,23 @@ * @memberof DisplayObject# */ filters: { - get: function () { + get: function () + { return this._filters; }, - set: function (value) { - if (value) { + set: function (value) + { + if (value) + { // now put all the passes in one place.. var passes = []; - for (var i = 0; i < value.length; i++) { + for (var i = 0; i < value.length; i++) + { var filterPasses = value[i].passes; - for (var j = 0; j < filterPasses.length; j++) { + for (var j = 0; j < filterPasses.length; j++) + { passes.push(filterPasses[j]); } } @@ -264,8 +280,9 @@ * * @private */ -DisplayObject.prototype.updateTransform = function () { - +DisplayObject.prototype.updateTransform = function () +{ + // create some matrix refs for easy access var pt = this.parent.worldTransform; var wt = this.worldTransform; @@ -274,9 +291,11 @@ var a, b, c, d, tx, ty; // so if rotation is between 0 then we can simplify the multiplication process.. - if (this.rotation % math.PI_2) { + if (this.rotation % math.PI_2) + { // 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) { + if (this.rotation !== this.rotationCache) + { this.rotationCache = this.rotation; this._sr = Math.sin(this.rotation); this._cr = Math.cos(this.rotation); @@ -291,7 +310,8 @@ ty = this.position.y; // check for pivot.. not often used so geared towards that fact! - if (this.pivot.x || this.pivot.y) { + 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; } @@ -304,7 +324,8 @@ wt.tx = tx * pt.a + ty * pt.c + pt.tx; wt.ty = tx * pt.b + ty * pt.d + pt.ty; } - else { + else + { // lets do the fast version as we know there is no rotation.. a = this.scale.x; d = this.scale.y; @@ -333,7 +354,8 @@ * @param matrix {Matrix} * @return {Rectangle} the rectangular bounding area */ -DisplayObject.prototype.getBounds = function (/* matrix */) { +DisplayObject.prototype.getBounds = function (/* matrix */) +{ return math.Rectangle.EMPTY; }; @@ -342,7 +364,8 @@ * * @return {Rectangle} the rectangular bounding area */ -DisplayObject.prototype.getLocalBounds = function () { +DisplayObject.prototype.getLocalBounds = function () +{ return this.getBounds(math.Matrix.IDENTITY); }; @@ -352,7 +375,8 @@ * @param position {Point} The world origin to calculate from * @return {Point} A point object representing the position of this object */ -DisplayObject.prototype.toGlobal = function (position) { +DisplayObject.prototype.toGlobal = function (position) +{ // don't need to u[date the lot this.displayObjectUpdateTransform(); return this.worldTransform.apply(position); @@ -365,8 +389,10 @@ * @param [from] {DisplayObject} The DisplayObject to calculate the global position from * @return {Point} A point object representing the position of this object */ -DisplayObject.prototype.toLocal = function (position, from) { - if (from) { +DisplayObject.prototype.toLocal = function (position, from) +{ + if (from) + { position = from.toGlobal(position); } @@ -381,7 +407,8 @@ * @param renderer {WebGLRenderer} The renderer * @private */ -DisplayObject.prototype.renderWebGL = function (/* renderer */) { +DisplayObject.prototype.renderWebGL = function (/* renderer */) +{ // OVERWRITE; }; @@ -391,6 +418,7 @@ * @param renderer {CanvasRenderer} The renderer * @private */ -DisplayObject.prototype.renderCanvas = function (/* renderer */) { +DisplayObject.prototype.renderCanvas = function (/* renderer */) +{ // OVERWRITE; }; diff --git a/src/core/display/DisplayObjectContainer.js b/src/core/display/DisplayObjectContainer.js index 689f40b..4625ee8 100644 --- a/src/core/display/DisplayObjectContainer.js +++ b/src/core/display/DisplayObjectContainer.js @@ -12,7 +12,8 @@ * @extends DisplayObject * @namespace PIXI */ -function DisplayObjectContainer() { +function DisplayObjectContainer() +{ DisplayObject.call(this); /** @@ -47,17 +48,21 @@ * @memberof DisplayObjectContainer# */ width: { - get: function () { + get: function () + { return this.scale.x * this.getLocalBounds().width; }, - set: function (value) { + set: function (value) + { var width = this.getLocalBounds().width; - if(width !== 0) { + if(width !== 0) + { this.scale.x = value / width; } - else { + else + { this.scale.x = 1; } @@ -73,17 +78,21 @@ * @memberof DisplayObjectContainer# */ height: { - get: function () { + get: function () + { return this.scale.y * this.getLocalBounds().height; }, - set: function (value) { + set: function (value) + { var height = this.getLocalBounds().height; - if (height !== 0) { + if (height !== 0) + { this.scale.y = value / height ; } - else { + else + { this.scale.y = 1; } @@ -100,18 +109,23 @@ * @memberof DisplayObject# */ cacheAsBitmap: { - get: function () { + get: function () + { return this._cacheAsBitmap; }, - set: function (value) { - if (this._cacheAsBitmap === value) { + set: function (value) + { + if (this._cacheAsBitmap === value) + { return; } - if (value) { + if (value) + { this._generateCachedSprite(); } - else { + else + { this._destroyCachedSprite(); } @@ -126,7 +140,8 @@ * @param child {DisplayObject} The DisplayObject to add to the container * @return {DisplayObject} The child that was added. */ -DisplayObjectContainer.prototype.addChild = function (child) { +DisplayObjectContainer.prototype.addChild = function (child) +{ return this.addChildAt(child, this.children.length); }; @@ -137,14 +152,18 @@ * @param index {Number} The index to place the child in * @return {DisplayObject} The child that was added. */ -DisplayObjectContainer.prototype.addChildAt = function (child, index) { +DisplayObjectContainer.prototype.addChildAt = function (child, index) +{ // prevent adding self as child - if (child === this) { + if (child === this) + { return; } - if (index >= 0 && index <= this.children.length) { - if (child.parent) { + if (index >= 0 && index <= this.children.length) + { + if (child.parent) + { child.parent.removeChild(child); } @@ -154,7 +173,8 @@ return child; } - else { + else + { throw new Error(child + 'addChildAt: The index '+ index +' supplied is out of bounds ' + this.children.length); } }; @@ -165,15 +185,18 @@ * @param child {DisplayObject} * @param child2 {DisplayObject} */ -DisplayObjectContainer.prototype.swapChildren = function (child, child2) { - if (child === child2) { +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) { + if (index1 < 0 || index2 < 0) + { throw new Error('swapChildren: Both the supplied DisplayObjects must be a child of the caller.'); } @@ -187,10 +210,12 @@ * @param child {DisplayObject} The DisplayObject instance to identify * @return {Number} The index position of the child display object to identify */ -DisplayObjectContainer.prototype.getChildIndex = function (child) { +DisplayObjectContainer.prototype.getChildIndex = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { throw new Error('The supplied DisplayObject must be a child of the caller'); } @@ -203,8 +228,10 @@ * @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 */ -DisplayObjectContainer.prototype.setChildIndex = function (child, index) { - if (index < 0 || index >= this.children.length) { +DisplayObjectContainer.prototype.setChildIndex = function (child, index) +{ + if (index < 0 || index >= this.children.length) + { throw new Error('The supplied index is out of bounds'); } @@ -220,8 +247,10 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child at the given index, if any. */ -DisplayObjectContainer.prototype.getChildAt = function (index) { - if (index < 0 || index >= this.children.length) { +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'); } @@ -234,10 +263,12 @@ * @param child {DisplayObject} The DisplayObject to remove * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChild = function (child) { +DisplayObjectContainer.prototype.removeChild = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { return; } @@ -250,7 +281,8 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChildAt = function (index) { +DisplayObjectContainer.prototype.removeChildAt = function (index) +{ var child = this.getChildAt(index); child.parent = null; @@ -265,24 +297,29 @@ * @param beginIndex {Number} The beginning position. Default value is 0. * @param endIndex {Number} The ending position. Default value is size of the container. */ -DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) { +DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) +{ var begin = beginIndex || 0; var end = typeof endIndex === 'number' ? endIndex : this.children.length; var range = end - begin; - if (range > 0 && range <= end) { + if (range > 0 && range <= end) + { var removed = this.children.splice(begin, range); - for (var i = 0; i < removed.length; ++i) { + for (var i = 0; i < removed.length; ++i) + { removed[i].parent = null; } return removed; } - else if (range === 0 && this.children.length === 0) { + else if (range === 0 && this.children.length === 0) + { return []; } - else { + else + { throw new RangeError('removeChildren: numeric values are outside the acceptable range.'); } }; @@ -291,7 +328,8 @@ * Generates and updates the cached sprite for this object. * */ -DisplayObjectContainer.prototype.updateCachedSprite = function () { +DisplayObjectContainer.prototype.updateCachedSprite = function () +{ this._generateCachedSprite(); }; @@ -304,7 +342,8 @@ * @param renderer {CanvasRenderer|WebGLRenderer} The renderer used to generate the texture. * @return {Texture} a texture of the graphics object */ -DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) { +DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) +{ var bounds = this.getLocalBounds(); var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0, renderer, scaleMode, resolution); @@ -322,18 +361,22 @@ * * @private */ -DisplayObjectContainer.prototype.updateTransform = function () { - if (!this.visible) { +DisplayObjectContainer.prototype.updateTransform = function () +{ + if (!this.visible) + { return; } this.displayObjectUpdateTransform(); - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { return; } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } }; @@ -346,8 +389,10 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getBounds = function () { - if (this.children.length === 0) { +DisplayObjectContainer.prototype.getBounds = function () +{ + if (this.children.length === 0) + { return math.Rectangle.EMPTY; } @@ -365,10 +410,12 @@ var childVisible = false; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -386,7 +433,8 @@ maxY = maxY > childMaxY ? maxY : childMaxY; } - if (!childVisible) { + if (!childVisible) + { return math.Rectangle.EMPTY; } @@ -407,12 +455,14 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getLocalBounds = function () { +DisplayObjectContainer.prototype.getLocalBounds = function () +{ var matrixCache = this.worldTransform; this.worldTransform = math.Matrix.IDENTITY; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } @@ -428,13 +478,16 @@ * * @param renderer {WebGLRenderer} The renderer */ -DisplayObjectContainer.prototype.renderWebGL = function (renderer) { +DisplayObjectContainer.prototype.renderWebGL = function (renderer) +{ // if the object is not visible or the alpha is 0 then no need to render this element - if (!this.visible || this.alpha <= 0) { + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } @@ -442,14 +495,17 @@ var i, j; // do a quick check to see if this element has a mask or a filter. - if (this._mask || this._filters) { + if (this._mask || this._filters) + { // push filter first as we need to ensure the stencil buffer is correct for any masking - if (this._filters) { + if (this._filters) + { renderer.spriteBatch.flush(); renderer.filterManager.pushFilter(this._filterBlock); } - if (this._mask) { + if (this._mask) + { renderer.spriteBatch.stop(); renderer.maskManager.pushMask(this.mask, renderer); renderer.spriteBatch.start(); @@ -459,36 +515,42 @@ this._renderWebGL(renderer); // now loop through the children and make sure they get rendered - for (i = 0, j = this.children.length; i < j; i++) { + for (i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderWebGL(renderer); } // time to stop the sprite batch as either a mask element or a filter draw will happen next renderer.spriteBatch.stop(); - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(this._mask, renderer); } - if (this._filters) { + if (this._filters) + { renderer.filterManager.popFilter(); } renderer.spriteBatch.start(); } - else { + else + { this._renderWebGL(renderer); // simple render children! - for (i = 0, j = this.children.length; i < j; ++i) { + for (i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderWebGL(renderer); } } }; -DisplayObjectContainer.prototype._renderWebGL = function (renderer) { +DisplayObjectContainer.prototype._renderWebGL = function (renderer) +{ // this is where content itself gets renderd.. @@ -499,25 +561,31 @@ * * @param renderer {CanvasRenderer} The renderer */ -DisplayObjectContainer.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0) { +DisplayObjectContainer.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -528,13 +596,16 @@ * @param renderer {WebGLRenderer|CanvasRenderer} The renderer * @private */ -DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) { +DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) +{ this._cachedSprite.worldAlpha = this.worldAlpha; - if (renderer.gl) { + if (renderer.gl) + { this._cachedSprite.renderWebGL(renderer); } - else { + else + { this._cachedSprite.renderCanvas(renderer); } }; @@ -544,10 +615,12 @@ * * @private */ -DisplayObjectContainer.prototype._generateCachedSprite = function () { +DisplayObjectContainer.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { // TODO - RenderTexture now *requires* a renderer instance, so this is like broken // because `renderer` isn't actually in scope here :P var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0); @@ -555,7 +628,8 @@ this._cachedSprite = new Sprite(renderTexture); this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.texture.resize(bounds.width | 0, bounds.height | 0); } @@ -580,8 +654,10 @@ * * @private */ -DisplayObjectContainer.prototype._destroyCachedSprite = function () { - if (!this._cachedSprite) { +DisplayObjectContainer.prototype._destroyCachedSprite = function () +{ + if (!this._cachedSprite) + { return; } diff --git a/src/core/display/Sprite.js b/src/core/display/Sprite.js index 707da24..5862aef 100644 --- a/src/core/display/Sprite.js +++ b/src/core/display/Sprite.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param texture {Texture} The texture for this sprite */ -function Sprite(texture) { +function Sprite(texture) +{ DisplayObjectContainer.call(this); /** @@ -85,12 +86,14 @@ this.texture = texture || Texture.EMPTY; } -Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) { +Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) +{ DisplayObjectContainer.prototype.destroy.call(this); this.anchor = null; - if (destroyTexture) { + if (destroyTexture) + { this._texture.destroy(destroyBaseTexture); } @@ -111,10 +114,12 @@ * @memberof Sprite# */ width: { - get: function () { + get: function () + { return this.scale.x * this.texture.frame.width; }, - set: function (value) { + set: function (value) + { this.scale.x = value / this.texture.frame.width; this._width = value; } @@ -127,10 +132,12 @@ * @memberof Sprite# */ height: { - get: function () { + get: function () + { return this.scale.y * this.texture.frame.height; }, - set: function (value) { + set: function (value) + { this.scale.y = value / this.texture.frame.height; this._height = value; } @@ -143,23 +150,29 @@ * @memberof Sprite# */ texture: { - get: function () { + get: function () + { return this._texture; }, - set: function (value) { - if (this._texture === value) { + set: function (value) + { + if (this._texture === value) + { return; } this._texture = value; this.cachedTint = 0xFFFFFF; - if (value) { + if (value) + { // wait for the texture to load - if (value.baseTexture.hasLoaded) { + if (value.baseTexture.hasLoaded) + { this._onTextureUpdate(); } - else { + else + { value.once('update', this._onTextureUpdate.bind(this)); } } @@ -172,18 +185,22 @@ * * @private */ -Sprite.prototype._onTextureUpdate = function () { +Sprite.prototype._onTextureUpdate = function () +{ // so if _width is 0 then width was not set.. - if (this._width) { + if (this._width) + { this.scale.x = this._width / this.texture.frame.width; } - if (this._height) { + if (this._height) + { this.scale.y = this._height / this.texture.frame.height; } }; -Sprite.prototype._renderWebGL = function (renderer) { +Sprite.prototype._renderWebGL = function (renderer) +{ // this is where content gets renderd.. // watch this space for a little render state manager.. @@ -197,7 +214,8 @@ * @param matrix {Matrix} the transformation matrix of the sprite * @return {Rectangle} the framing rectangle */ -Sprite.prototype.getBounds = function (matrix) { +Sprite.prototype.getBounds = function (matrix) +{ var width = this.texture.frame.width; var height = this.texture.frame.height; @@ -224,11 +242,13 @@ if(b === 0 && c === 0) { // scale may be negative! - if (a < 0) { + if (a < 0) + { a *= -1; } - if (d < 0) { + if (d < 0) + { d *= -1; } @@ -293,28 +313,34 @@ * * @param renderer {CanvasRenderer} The renderer */ -Sprite.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) { +Sprite.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) + { return; } - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; renderer.context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } // Ignore null sources - if (this.texture.valid) { + if (this.texture.valid) + { var resolution = this.texture.baseTexture.resolution / renderer.resolution; renderer.context.globalAlpha = this.worldAlpha; // If smoothingEnabled is supported and we need to change the smoothing property for this texture - if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) { + if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) + { renderer.scaleMode = this.texture.baseTexture.scaleMode; renderer.context[renderer.smoothProperty] = (renderer.scaleMode === CONST.scaleModes.LINEAR); } @@ -324,7 +350,8 @@ var dy = (this.texture.trim ? this.texture.trim.y : 0) - (this.anchor.y * this.texture.trim.height); // Allow for pixel rounding - if (renderer.roundPixels) { + if (renderer.roundPixels) + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -337,7 +364,8 @@ dx = dx | 0; dy = dy | 0; } - else { + else + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -348,8 +376,10 @@ ); } - if (this.tint !== 0xFFFFFF) { - if (this.cachedTint !== this.tint) { + if (this.tint !== 0xFFFFFF) + { + if (this.cachedTint !== this.tint) + { this.cachedTint = this.tint; // TODO clean up caching - how to clean up the caches? @@ -368,7 +398,8 @@ this.texture.crop.height / resolution ); } - else { + else + { renderer.context.drawImage( this.texture.baseTexture.source, this.texture.crop.x, @@ -383,11 +414,13 @@ } } - for (var i = 0, j = this.children.length; i < j; i++) { + for (var i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -402,10 +435,12 @@ * @param frameId {String} The frame Id of the texture in the cache * @return {Sprite} A new Sprite using a texture from the texture cache matching the frameId */ -Sprite.fromFrame = function (frameId) { +Sprite.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache' + this); } @@ -420,6 +455,7 @@ * @param imageId {String} The image url of the texture * @return {Sprite} A new Sprite using a texture from the texture cache matching the image id */ -Sprite.fromImage = function (imageId, crossorigin, scaleMode) { +Sprite.fromImage = function (imageId, crossorigin, scaleMode) +{ return new Sprite(Texture.fromImage(imageId, crossorigin, scaleMode)); }; diff --git a/src/core/display/SpriteBatch.js b/src/core/display/SpriteBatch.js index 3187777..c196fef 100644 --- a/src/core/display/SpriteBatch.js +++ b/src/core/display/SpriteBatch.js @@ -12,7 +12,8 @@ * ```js * var container = new SpriteBatch(); * - * for(var i = 0; i < 100; ++i) { + * for(var i = 0; i < 100; ++i) + * { * var sprite = new PIXI.Sprite.fromImage("myImage.png"); * container.addChild(sprite); * } @@ -25,7 +26,8 @@ */ //TODO RENAME to PARTICLE CONTAINER? -function SpriteBatch() { +function SpriteBatch() +{ DisplayObjectContainer.call(this); } @@ -38,7 +40,8 @@ * * @private */ -SpriteBatch.prototype.updateTransform = function () { +SpriteBatch.prototype.updateTransform = function () +{ // TODO don't need to! this.displayObjectUpdateTransform(); // PIXI.DisplayObjectContainer.prototype.updateTransform.call( this ); @@ -50,8 +53,10 @@ * @param renderer {WebGLRenderer} The webgl renderer * @private */ -SpriteBatch.prototype.renderWebGL = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderWebGL = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -71,8 +76,10 @@ * @param renderer {CanvasRenderer} The canvas renderer * @private */ -SpriteBatch.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -84,10 +91,12 @@ this.displayObjectUpdateTransform(); - for (var i = 0; i < this.children.length; ++i) { + for (var i = 0; i < this.children.length; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -95,9 +104,11 @@ context.globalAlpha = this.worldAlpha * child.alpha; - if (child.rotation % (Math.PI * 2) === 0) { + if (child.rotation % (Math.PI * 2) === 0) + { // this is the fastest way to optimise! - if rotation is 0 then we can avoid any kind of setTransform call - if (isRotated) { + if (isRotated) + { context.setTransform( transform.a, transform.b, @@ -122,8 +133,10 @@ frame.height * child.scale.y ); } - else { - if (!isRotated) { + else + { + if (!isRotated) + { isRotated = true; } @@ -131,7 +144,8 @@ var childTransform = child.worldTransform; - if (renderer.roundPixels) { + if (renderer.roundPixels) + { context.setTransform( childTransform.a, childTransform.b, @@ -141,7 +155,8 @@ childTransform.ty | 0 ); } - else { + else + { context.setTransform( childTransform.a, childTransform.b, diff --git a/src/core/index.js b/src/core/index.js index 3954b6f..eb4a82b 100644 --- a/src/core/index.js +++ b/src/core/index.js @@ -58,11 +58,13 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRenderer: function (width, height, options, noWebGL) { + autoDetectRenderer: function (width, height, options, noWebGL) + { width = width || 800; height = height || 600; - if (!noWebGL && require('webgl-enabled')()) { + if (!noWebGL && require('webgl-enabled')()) + { return new core.WebGLRenderer(width, height, options); } @@ -87,7 +89,8 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRecommendedRenderer: function (width, height, options) { + autoDetectRecommendedRenderer: function (width, height, options) + { var isAndroid = /Android/i.test(navigator.userAgent); return core.autoDetectRenderer(width, height, options, isAndroid); diff --git a/src/core/math/Matrix.js b/src/core/math/Matrix.js index c2f87e2..2ff4848 100644 --- a/src/core/math/Matrix.js +++ b/src/core/math/Matrix.js @@ -10,7 +10,8 @@ * @class * @namespace PIXI */ -function Matrix() { +function Matrix() +{ /** * @member {number} * @default 1 @@ -63,7 +64,8 @@ * * @param array {number[]} The array that the matrix will be populated from. */ -Matrix.prototype.fromArray = function (array) { +Matrix.prototype.fromArray = function (array) +{ this.a = array[0]; this.b = array[1]; this.c = array[3]; @@ -78,14 +80,17 @@ * @param transpose {boolean} Whether we need to transpose the matrix or not * @return {number[]} the newly created array which contains the matrix */ -Matrix.prototype.toArray = function (transpose) { - if (!this.array) { +Matrix.prototype.toArray = function (transpose) +{ + if (!this.array) + { this.array = new Float32Array(9); } var array = this.array; - if (transpose) { + if (transpose) + { array[0] = this.a; array[1] = this.b; array[2] = 0; @@ -96,7 +101,8 @@ array[7] = this.ty; array[8] = 1; } - else { + else + { array[0] = this.a; array[1] = this.c; array[2] = this.tx; @@ -119,7 +125,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, transformed through this matrix */ -Matrix.prototype.apply = function (pos, newPos) { +Matrix.prototype.apply = function (pos, newPos) +{ newPos = newPos || new Point(); newPos.x = this.a * pos.x + this.c * pos.y + this.tx; @@ -136,7 +143,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, inverse-transformed through this matrix */ -Matrix.prototype.applyInverse = function (pos, newPos) { +Matrix.prototype.applyInverse = function (pos, newPos) +{ newPos = newPos || new Point(); var id = 1 / (this.a * this.d + this.c * -this.b); @@ -154,7 +162,8 @@ * @param {number} y * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.translate = function (x, y) { +Matrix.prototype.translate = function (x, y) +{ this.tx += x; this.ty += y; @@ -168,7 +177,8 @@ * @param {number} y The amount to scale vertically * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.scale = function (x, y) { +Matrix.prototype.scale = function (x, y) +{ this.a *= x; this.d *= y; this.c *= x; @@ -186,7 +196,8 @@ * @param {number} angle - The angle in radians. * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.rotate = function (angle) { +Matrix.prototype.rotate = function (angle) +{ var cos = Math.cos( angle ); var sin = Math.sin( angle ); @@ -210,7 +221,8 @@ * @param {Matrix} matrix * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.append = function (matrix) { +Matrix.prototype.append = function (matrix) +{ var a1 = this.a; var b1 = this.b; var c1 = this.c; @@ -232,7 +244,8 @@ * * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.identity = function () { +Matrix.prototype.identity = function () +{ this.a = 1; this.b = 0; this.c = 0; diff --git a/src/core/math/Point.js b/src/core/math/Point.js index 7565b2d..632f346 100644 --- a/src/core/math/Point.js +++ b/src/core/math/Point.js @@ -7,7 +7,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -function Point(x, y) { +function Point(x, y) +{ /** * @member {number} * @default 0 @@ -29,7 +30,8 @@ * * @return {Point} a copy of the point */ -Point.prototype.clone = function () { +Point.prototype.clone = function () +{ return new Point(this.x, this.y); }; @@ -40,7 +42,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -Point.prototype.set = function (x, y) { +Point.prototype.set = function (x, y) +{ this.x = x || 0; this.y = y || ( (y !== 0) ? this.x : 0 ) ; }; diff --git a/src/core/math/shapes/Circle.js b/src/core/math/shapes/Circle.js index 69cfdc9..4d76efc 100644 --- a/src/core/math/shapes/Circle.js +++ b/src/core/math/shapes/Circle.js @@ -10,7 +10,8 @@ * @param y {number} The Y coordinate of the center of this circle * @param radius {number} The radius of the circle */ -function Circle(x, y, radius) { +function Circle(x, y, radius) +{ /** * @member {number} * @default 0 @@ -46,7 +47,8 @@ * @method clone * @return {Circle} a copy of the Circle */ -Circle.prototype.clone = function () { +Circle.prototype.clone = function () +{ return new Circle(this.x, this.y, this.radius); }; @@ -58,8 +60,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Circle */ -Circle.prototype.contains = function (x, y) { - if (this.radius <= 0) { +Circle.prototype.contains = function (x, y) +{ + if (this.radius <= 0) + { return false; } @@ -79,6 +83,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Circle.prototype.getBounds = function () { +Circle.prototype.getBounds = function () +{ return new Rectangle(this.x - this.radius, this.y - this.radius, this.radius * 2, this.radius * 2); }; diff --git a/src/core/math/shapes/Ellipse.js b/src/core/math/shapes/Ellipse.js index 4f2d066..fefd01a 100644 --- a/src/core/math/shapes/Ellipse.js +++ b/src/core/math/shapes/Ellipse.js @@ -11,7 +11,8 @@ * @param width {number} The half width of this ellipse * @param height {number} The half height of this ellipse */ -function Ellipse(x, y, width, height) { +function Ellipse(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -53,7 +54,8 @@ * @method clone * @return {Ellipse} a copy of the ellipse */ -Ellipse.prototype.clone = function () { +Ellipse.prototype.clone = function () +{ return new Ellipse(this.x, this.y, this.width, this.height); }; @@ -65,8 +67,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coords are within this ellipse */ -Ellipse.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Ellipse.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } @@ -86,6 +90,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Ellipse.prototype.getBounds = function () { +Ellipse.prototype.getBounds = function () +{ return new Rectangle(this.x - this.width, this.y - this.height, this.width, this.height); }; diff --git a/src/core/math/shapes/Polygon.js b/src/core/math/shapes/Polygon.js index ae89148..fea6d37 100644 --- a/src/core/math/shapes/Polygon.js +++ b/src/core/math/shapes/Polygon.js @@ -10,16 +10,20 @@ * arguments passed can be flat x,y values e.g. `new Polygon(x,y, x,y, x,y, ...)` where `x` and `y` are * Numbers. */ -function Polygon(points) { +function Polygon(points) +{ //if points isn't an array, use arguments as the array - if (!(points instanceof Array)) { + if (!(points instanceof Array)) + { points = Array.prototype.slice.call(arguments); } //if this is a flat array of numbers, convert it to points - if (points[0] instanceof Point) { + if (points[0] instanceof Point) + { var p = []; - for (var i = 0, il = points.length; i < il; i++) { + for (var i = 0, il = points.length; i < il; i++) + { p.push(points[i].x, points[i].y); } @@ -51,7 +55,8 @@ * * @return {Polygon} a copy of the polygon */ -Polygon.prototype.clone = function () { +Polygon.prototype.clone = function () +{ return new Polygon(this.points.slice()); }; @@ -62,19 +67,22 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this polygon */ -Polygon.prototype.contains = function (x, y) { +Polygon.prototype.contains = function (x, y) +{ var inside = false; // use some raycasting to test hits // https://github.com/substack/point-in-polygon/blob/master/index.js var length = this.points.length / 2; - for (var i = 0, j = length - 1; i < length; j = i++) { + for (var i = 0, j = length - 1; i < length; j = i++) + { var xi = this.points[i * 2], yi = this.points[i * 2 + 1], xj = this.points[j * 2], yj = this.points[j * 2 + 1], intersect = ((yi > y) !== (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi); - if (intersect) { + if (intersect) + { inside = !inside; } } diff --git a/src/core/math/shapes/Rectangle.js b/src/core/math/shapes/Rectangle.js index 16ac62a..4008b68 100644 --- a/src/core/math/shapes/Rectangle.js +++ b/src/core/math/shapes/Rectangle.js @@ -10,7 +10,8 @@ * @param width {number} The overall width of this rectangle * @param height {number} The overall height of this rectangle */ -function Rectangle(x, y, width, height) { +function Rectangle(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -60,7 +61,8 @@ * * @return {Rectangle} a copy of the rectangle */ -Rectangle.prototype.clone = function () { +Rectangle.prototype.clone = function () +{ return new Rectangle(this.x, this.y, this.width, this.height); }; @@ -71,13 +73,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rectangle */ -Rectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Rectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/math/shapes/RoundedRectangle.js b/src/core/math/shapes/RoundedRectangle.js index 27d286e..7bf6411 100644 --- a/src/core/math/shapes/RoundedRectangle.js +++ b/src/core/math/shapes/RoundedRectangle.js @@ -11,7 +11,8 @@ * @param height {number} The overall height of this rounded rectangle * @param radius {number} Controls the radius of the rounded corners */ -function RoundedRectangle(x, y, width, height, radius) { +function RoundedRectangle(x, y, width, height, radius) +{ /** * @member {number} * @default 0 @@ -58,7 +59,8 @@ * * @return {RoundedRectangle} a copy of the rounded rectangle */ -RoundedRectangle.prototype.clone = function () { +RoundedRectangle.prototype.clone = function () +{ return new RoundedRectangle(this.x, this.y, this.width, this.height, this.radius); }; @@ -69,13 +71,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rounded Rectangle */ -RoundedRectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +RoundedRectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/primitives/Graphics.js b/src/core/primitives/Graphics.js index 261c534..e902d2a 100644 --- a/src/core/primitives/Graphics.js +++ b/src/core/primitives/Graphics.js @@ -16,7 +16,8 @@ * @extends DisplayObjectContainer * @namespace PIXI */ -function Graphics() { +function Graphics() +{ DisplayObjectContainer.call(this); this.renderable = true; @@ -154,16 +155,20 @@ * @private */ cacheAsBitmap: { - get: function () { + get: function () + { return this._cacheAsBitmap; }, - set: function (value) { + set: function (value) + { this._cacheAsBitmap = value; - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._generateCachedSprite(); } - else { + else + { this.destroyCachedSprite(); this.dirty = true; } @@ -176,7 +181,8 @@ * * @return {Graphics} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ var clone = new Graphics(); clone.renderable = this.renderable; @@ -192,7 +198,8 @@ clone.cachedSpriteDirty = this.cachedSpriteDirty; // copy graphics data - for (var i = 0; i < this.graphicsData.length; ++i) { + for (var i = 0; i < this.graphicsData.length; ++i) + { clone.graphicsData.push(this.graphicsData.clone()); } @@ -211,17 +218,21 @@ * @param alpha {number} alpha of the line to draw, will update the objects stored style * @return {Graphics} */ -Graphics.prototype.lineStyle = function (lineWidth, color, alpha) { +Graphics.prototype.lineStyle = function (lineWidth, color, alpha) +{ this.lineWidth = lineWidth || 0; this.lineColor = color || 0; this.lineAlpha = (arguments.length < 3) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length) + { // halfway through a line? start a new one! this.drawShape( new math.Polygon( this.currentPath.shape.points.slice(-2) )); } - else { + else + { // otherwise its empty so lets just set the line properties this.currentPath.lineWidth = this.lineWidth; this.currentPath.lineColor = this.lineColor; @@ -239,7 +250,8 @@ * @param y {number} the Y coordinate to move to * @return {Graphics} */ -Graphics.prototype.moveTo = function (x, y) { +Graphics.prototype.moveTo = function (x, y) +{ this.drawShape(new math.Polygon([x,y])); return this; @@ -253,7 +265,8 @@ * @param y {number} the Y coordinate to draw to * @return {Graphics} */ -Graphics.prototype.lineTo = function (x, y) { +Graphics.prototype.lineTo = function (x, y) +{ this.currentPath.shape.points.push(x, y); this.dirty = true; @@ -270,13 +283,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -285,7 +302,8 @@ n = 20, points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { this.moveTo(0, 0); } @@ -293,7 +311,8 @@ var fromY = points[points.length-1]; var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; xa = fromX + ( (cpX - fromX) * j ); @@ -319,13 +338,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -342,7 +365,8 @@ var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; dt = (1 - j); @@ -373,13 +397,17 @@ * @param radius {number} The radius of the arc * @return {Graphics} */ -Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points.push(x1, y1); } } - else { + else + { this.moveTo(x1, y1); } @@ -392,12 +420,15 @@ b2 = x2 - x1, mm = Math.abs(a1 * b2 - b1 * a2); - if (mm < 1.0e-8 || radius === 0) { - if (points[points.length-2] !== x1 || points[points.length-1] !== y1) { + if (mm < 1.0e-8 || radius === 0) + { + if (points[points.length-2] !== x1 || points[points.length-1] !== y1) + { points.push(x1, y1); } } - else { + else + { var dd = a1 * a1 + b1 * b1, cc = a2 * a2 + b2 * b2, tt = a1 * a2 + b1 * b2, @@ -433,42 +464,51 @@ * @param anticlockwise {boolean} Optional. Specifies whether the drawing should be counterclockwise or clockwise. False is default, and indicates clockwise, while true indicates counter-clockwise. * @return {Graphics} */ -Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) { +Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) +{ var startX = cx + Math.cos(startAngle) * radius; var startY = cy + Math.sin(startAngle) * radius; var points; // TODO - This if-else makes no sense. It uses currentPath in the else where it doesn't exist... - if (this.currentPath) { + if (this.currentPath) + { points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { points.push(startX, startY); } - else if (points[points.length-2] !== startX || points[points.length-1] !== startY) { + else if (points[points.length-2] !== startX || points[points.length-1] !== startY) + { points.push(startX, startY); } } - else { + else + { this.moveTo(startX, startY); points = this.currentPath.shape.points; } - if (startAngle === endAngle) { + if (startAngle === endAngle) + { return this; } - if (!anticlockwise && endAngle <= startAngle) { + if (!anticlockwise && endAngle <= startAngle) + { endAngle += Math.PI * 2; } - else if (anticlockwise && startAngle <= endAngle) { + else if (anticlockwise && startAngle <= endAngle) + { startAngle += Math.PI * 2; } var sweep = anticlockwise ? (startAngle - endAngle) *-1 : (endAngle - startAngle); var segs = (Math.abs(sweep)/ (Math.PI * 2)) * 40; - if (sweep === 0) { + if (sweep === 0) + { return this; } @@ -482,7 +522,8 @@ var remainder = ( segMinus % 1 ) / segMinus; - for (var i = 0; i <= segMinus; ++i) { + for (var i = 0; i <= segMinus; ++i) + { var real = i + remainder * i; var angle = ((theta) + startAngle + (theta2 * real)); @@ -506,13 +547,16 @@ * @param alpha {number} the alpha of the fill * @return {Graphics} */ -Graphics.prototype.beginFill = function (color, alpha) { +Graphics.prototype.beginFill = function (color, alpha) +{ this.filling = true; this.fillColor = color || 0; this.fillAlpha = (alpha === undefined) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length <= 2) + { this.currentPath.fill = this.filling; this.currentPath.fillColor = this.fillColor; this.currentPath.fillAlpha = this.fillAlpha; @@ -526,7 +570,8 @@ * * @return {Graphics} */ -Graphics.prototype.endFill = function () { +Graphics.prototype.endFill = function () +{ this.filling = false; this.fillColor = null; this.fillAlpha = 1; @@ -542,7 +587,8 @@ * @param height {number} The height of the rectangle * @return {Graphics} */ -Graphics.prototype.drawRect = function ( x, y, width, height ) { +Graphics.prototype.drawRect = function ( x, y, width, height ) +{ this.drawShape(new math.Rectangle(x,y, width, height)); return this; @@ -556,7 +602,8 @@ * @param height {number} The height of the rectangle * @param radius {number} Radius of the rectangle corners */ -Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) { +Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) +{ this.drawShape(new math.RoundedRectangle(x, y, width, height, radius)); return this; @@ -570,7 +617,8 @@ * @param radius {number} The radius of the circle * @return {Graphics} */ -Graphics.prototype.drawCircle = function (x, y, radius) { +Graphics.prototype.drawCircle = function (x, y, radius) +{ this.drawShape(new math.Circle(x,y, radius)); return this; @@ -585,7 +633,8 @@ * @param height {number} The half height of the ellipse * @return {Graphics} */ -Graphics.prototype.drawEllipse = function (x, y, width, height) { +Graphics.prototype.drawEllipse = function (x, y, width, height) +{ this.drawShape(new math.Ellipse(x, y, width, height)); return this; @@ -597,8 +646,10 @@ * @param path {Array} The path data used to construct the polygon. * @return {Graphics} */ -Graphics.prototype.drawPolygon = function (path) { - if (!(path instanceof Array)) { +Graphics.prototype.drawPolygon = function (path) +{ + if (!(path instanceof Array)) + { path = Array.prototype.slice.call(arguments); } @@ -612,7 +663,8 @@ * * @return {Graphics} */ -Graphics.prototype.clear = function () { +Graphics.prototype.clear = function () +{ this.lineWidth = 0; this.filling = false; @@ -631,7 +683,8 @@ * @param scaleMode {number} Should be one of the scaleMode consts * @return {Texture} a texture of the graphics object */ -Graphics.prototype.generateTexture = function (resolution, scaleMode) { +Graphics.prototype.generateTexture = function (resolution, scaleMode) +{ resolution = resolution || 1; var bounds = this.getBounds(); @@ -655,17 +708,21 @@ * * @param renderer {WebGLRenderer} */ -Graphics.prototype._renderWebGL = function (renderer) { +Graphics.prototype._renderWebGL = function (renderer) +{ // if the sprite is not visible or the alpha is 0 then no need to render this element - if (this.isMask === true) { + if (this.isMask === true) + { return; } // this code may still be needed so leaving for now.. - // + // /* - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture on the gpu too! @@ -681,17 +738,24 @@ return; } - */ - - // check if the webgl graphic needs to be updated - if (this.glDirty) { - this.dirty = true; - this.glDirty = false; - } + else */ - renderer.setObjectRendererer(renderer.graphicsRenderer); - renderer.graphicsRenderer.render(this); + renderer.spriteBatch.stop(); + renderer.blendModeManager.setBlendMode(this.blendMode); + // check blend mode + renderer.blendModeManager.setBlendMode( this.blendMode ); + + // check if the webgl graphic needs to be updated + if (this.glDirty) + { + this.dirty = true; + this.glDirty = false; + } + + WebGLGraphics.renderGraphics(this, renderer); + + renderer.spriteBatch.start(); }; /** @@ -700,14 +764,18 @@ * @param renderer {CanvasRenderer} * @private */ -Graphics.prototype.renderCanvas = function (renderer) { +Graphics.prototype.renderCanvas = function (renderer) +{ // 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.isMask === true) { + if (!this.visible || this.alpha <= 0 || this.isMask === true) + { return; } - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture @@ -723,16 +791,19 @@ return; } - else { + else + { var context = renderer.context; var transform = this.worldTransform; - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } @@ -748,11 +819,13 @@ CanvasGraphics.renderGraphics(this, context); - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } } @@ -763,13 +836,16 @@ * * @return {Rectangle} the rectangular bounding area */ -Graphics.prototype.getBounds = function (matrix) { +Graphics.prototype.getBounds = function (matrix) +{ // return an empty object if the item is a mask! - if (this.isMask) { + if (this.isMask) + { return math.Rectangle.EMPTY; } - if (this.dirty) { + if (this.dirty) + { this.updateLocalBounds(); this.glDirty = true; @@ -841,23 +917,27 @@ * Update the bounds of the object * */ -Graphics.prototype.updateLocalBounds = function () { +Graphics.prototype.updateLocalBounds = function () +{ var minX = Infinity; var maxX = -Infinity; var minY = Infinity; var maxY = -Infinity; - if (this.graphicsData.length) { + if (this.graphicsData.length) + { var shape, points, x, y, w, h; - for (var i = 0; i < this.graphicsData.length; i++) { + for (var i = 0; i < this.graphicsData.length; i++) + { var data = this.graphicsData[i]; var type = data.type; var lineWidth = data.lineWidth; shape = data.shape; - if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) { + if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) + { x = shape.x - lineWidth/2; y = shape.y - lineWidth/2; w = shape.width + lineWidth; @@ -869,7 +949,8 @@ minY = y < minY ? y : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.CIRC) { + else if (type === CONST.SHAPES.CIRC) + { x = shape.x; y = shape.y; w = shape.radius + lineWidth/2; @@ -881,7 +962,8 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.ELIP) { + else if (type === CONST.SHAPES.ELIP) + { x = shape.x; y = shape.y; w = shape.width + lineWidth/2; @@ -893,11 +975,13 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else { + else + { // POLY points = shape.points; - for (var j = 0; j < points.length; j += 2) { + for (var j = 0; j < points.length; j += 2) + { x = points[j]; y = points[j+1]; @@ -910,7 +994,8 @@ } } } - else { + else + { minX = 0; maxX = 0; minY = 0; @@ -931,10 +1016,12 @@ * * @private */ -Graphics.prototype._generateCachedSprite = function () { +Graphics.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { var canvasBuffer = new CanvasBuffer(bounds.width, bounds.height); var texture = Texture.fromCanvas(canvasBuffer.canvas); @@ -943,7 +1030,8 @@ this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.buffer.resize(bounds.width, bounds.height); } @@ -968,7 +1056,8 @@ * * @private */ -Graphics.prototype.updateCachedSpriteTexture = function () { +Graphics.prototype.updateCachedSpriteTexture = function () +{ var cachedSprite = this._cachedSprite; var texture = cachedSprite.texture; var canvas = cachedSprite.buffer.canvas; @@ -989,7 +1078,8 @@ * Destroys a previous cached sprite. * */ -Graphics.prototype.destroyCachedSprite = function () { +Graphics.prototype.destroyCachedSprite = function () +{ this._cachedSprite.texture.destroy(true); // let the gc collect the unused sprite @@ -1003,10 +1093,13 @@ * @param {Circle|Rectangle|Ellipse|Line|Polygon} shape The Shape object to draw. * @return {GraphicsData} The generated GraphicsData object. */ -Graphics.prototype.drawShape = function (shape) { - if (this.currentPath) { +Graphics.prototype.drawShape = function (shape) +{ + if (this.currentPath) + { // check current path! - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath.shape.points.length <= 2) + { this.graphicsData.pop(); } } @@ -1017,7 +1110,8 @@ this.graphicsData.push(data); - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { data.shape.closed = this.filling; this.currentPath = data; } diff --git a/src/core/primitives/GraphicsData.js b/src/core/primitives/GraphicsData.js index 99decbe..788f6f2 100644 --- a/src/core/primitives/GraphicsData.js +++ b/src/core/primitives/GraphicsData.js @@ -4,7 +4,8 @@ * @class * @namespace PIXI */ -function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) { +function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) +{ this.lineWidth = lineWidth; this.lineColor = lineColor; this.lineAlpha = lineAlpha; @@ -27,7 +28,8 @@ * * @return {GraphicsData} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ return new GraphicsData( this.lineWidth, this.lineColor, diff --git a/src/core/renderers/canvas/CanvasRenderer.js b/src/core/renderers/canvas/CanvasRenderer.js index 15a0978..7aebd44 100644 --- a/src/core/renderers/canvas/CanvasRenderer.js +++ b/src/core/renderers/canvas/CanvasRenderer.js @@ -17,17 +17,22 @@ * @param [options.resolution=1] {number} the resolution of the renderer retina would be 2 * @param [options.clearBeforeRender=true] {boolean} This sets if the CanvasRenderer will clear the canvas or not before the new render pass. */ -function CanvasRenderer(width, height, options) { +function CanvasRenderer(width, height, options) +{ utils.sayHello('Canvas'); - if (options) { - for (var i in CONST.defaultRenderOptions) { - if (typeof options[i] === 'undefined') { + if (options) + { + for (var i in CONST.defaultRenderOptions) + { + if (typeof options[i] === 'undefined') + { options[i] = CONST.defaultRenderOptions[i]; } } } - else { + else + { options = CONST.defaultRenderOptions; } @@ -156,19 +161,24 @@ this.smoothProperty = null; - if (this.context.imageSmoothingEnabled) { + if (this.context.imageSmoothingEnabled) + { this.smoothProperty = 'imageSmoothingEnabled'; } - else if (this.context.webkitImageSmoothingEnabled) { + else if (this.context.webkitImageSmoothingEnabled) + { this.smoothProperty = 'webkitImageSmoothingEnabled'; } - else if (this.context.mozImageSmoothingEnabled) { + else if (this.context.mozImageSmoothingEnabled) + { this.smoothProperty = 'mozImageSmoothingEnabled'; } - else if (this.context.oImageSmoothingEnabled) { + else if (this.context.oImageSmoothingEnabled) + { this.smoothProperty = 'oImageSmoothingEnabled'; } - else if (this.context.msImageSmoothingEnabled) { + else if (this.context.msImageSmoothingEnabled) + { this.smoothProperty = 'msImageSmoothingEnabled'; } @@ -193,10 +203,12 @@ * @memberof CanvasRenderer# */ backgroundColor: { - get: function () { + get: function () + { return this._backgroundColor; }, - set: function (val) { + set: function (val) + { this._backgroundColor = val; this._backgroundColorString = utils.hex2string(val); } @@ -208,7 +220,8 @@ * * @param object {DisplayObject} the object to be rendered */ -CanvasRenderer.prototype.render = function (object) { +CanvasRenderer.prototype.render = function (object) +{ object.updateTransform(); this.context.setTransform(1,0,0,1,0,0); @@ -218,16 +231,20 @@ this.currentBlendMode = CONST.blendModes.NORMAL; this.context.globalCompositeOperation = this.blendModes[CONST.blendModes.NORMAL]; - if (navigator.isCocoonJS && this.view.screencanvas) { + if (navigator.isCocoonJS && this.view.screencanvas) + { this.context.fillStyle = 'black'; this.context.clear(); } - if (this.clearBeforeRender) { - if (this.transparent) { + if (this.clearBeforeRender) + { + if (this.transparent) + { this.context.clearRect(0, 0, this.width, this.height); } - else { + else + { this.context.fillStyle = this._backgroundColorString; this.context.fillRect(0, 0, this.width , this.height); } @@ -241,8 +258,10 @@ * * @param [removeView=false] {boolean} Removes the Canvas element from the DOM. */ -CanvasRenderer.prototype.destroy = function (removeView) { - if (removeView && this.view.parent) { +CanvasRenderer.prototype.destroy = function (removeView) +{ + if (removeView && this.view.parent) + { this.view.parent.removeChild(this.view); } @@ -257,14 +276,16 @@ * @param width {number} the new width of the canvas view * @param height {number} the new height of the canvas view */ -CanvasRenderer.prototype.resize = function (width, height) { +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) { + if (this.autoResize) + { this.view.style.width = this.width / this.resolution + 'px'; this.view.style.height = this.height / this.resolution + 'px'; } @@ -276,7 +297,8 @@ * @param displayObject {DisplayObject} The displayObject to render * @private */ -CanvasRenderer.prototype.renderDisplayObject = function (displayObject) { +CanvasRenderer.prototype.renderDisplayObject = function (displayObject) +{ displayObject.renderCanvas(this); }; @@ -285,11 +307,14 @@ * * @private */ -CanvasRenderer.prototype._mapBlendModes = function () { - if (!this.blendModes) { +CanvasRenderer.prototype._mapBlendModes = function () +{ + if (!this.blendModes) + { this.blendModes = {}; - if (utils.canUseNewCanvasBlendModes()) { + if (utils.canUseNewCanvasBlendModes()) + { this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? this.blendModes[CONST.blendModes.MULTIPLY] = 'multiply'; @@ -308,7 +333,8 @@ this.blendModes[CONST.blendModes.COLOR] = 'color'; this.blendModes[CONST.blendModes.LUMINOSITY] = 'luminosity'; } - else { + else + { // this means that the browser does not support the cool new blend modes in canvas 'cough' ie 'cough' this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? diff --git a/src/core/renderers/canvas/utils/CanvasBuffer.js b/src/core/renderers/canvas/utils/CanvasBuffer.js index ebe5d47..b183a66 100644 --- a/src/core/renderers/canvas/utils/CanvasBuffer.js +++ b/src/core/renderers/canvas/utils/CanvasBuffer.js @@ -6,7 +6,8 @@ * @param width {number} the width for the newly created canvas * @param height {number} the height for the newly created canvas */ -function CanvasBuffer(width, height) { +function CanvasBuffer(width, height) +{ /** * The Canvas object that belongs to this CanvasBuffer. * @@ -36,10 +37,12 @@ * @memberof CanvasBuffer# */ width: { - get: function () { + get: function () + { return this.canvas.width; }, - set: function (val) { + set: function (val) + { this.canvas.width = val; } }, @@ -50,10 +53,12 @@ * @memberof CanvasBuffer# */ height: { - get: function () { + get: function () + { return this.canvas.height; }, - set: function (val) { + set: function (val) + { this.canvas.height = val; } } @@ -64,7 +69,8 @@ * * @private */ -CanvasBuffer.prototype.clear = function () { +CanvasBuffer.prototype.clear = function () +{ this.context.setTransform(1, 0, 0, 1, 0, 0); this.context.clearRect(0,0, this.canvas.width, this.canvas.height); }; @@ -75,7 +81,8 @@ * @param width {number} the new width of the canvas * @param height {number} the new height of the canvas */ -CanvasBuffer.prototype.resize = function (width, height) { +CanvasBuffer.prototype.resize = function (width, height) +{ this.canvas.width = width; this.canvas.height = height; }; diff --git a/src/core/renderers/canvas/utils/CanvasGraphics.js b/src/core/renderers/canvas/utils/CanvasGraphics.js index c7eaa2a..3f2a91f 100644 --- a/src/core/renderers/canvas/utils/CanvasGraphics.js +++ b/src/core/renderers/canvas/utils/CanvasGraphics.js @@ -13,15 +13,18 @@ * @param graphics {Graphics} the actual graphics object to render * @param context {CanvasRenderingContext2D} the 2d drawing method of the canvas */ -CanvasGraphics.renderGraphics = function (graphics, context) { +CanvasGraphics.renderGraphics = function (graphics, context) +{ var worldAlpha = graphics.worldAlpha; - if (graphics.dirty) { + if (graphics.dirty) + { this.updateGraphicsTint(graphics); graphics.dirty = false; } - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; @@ -30,69 +33,82 @@ context.lineWidth = data.lineWidth; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { context.beginPath(); var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } - if (shape.closed) { + if (shape.closed) + { context.lineTo(points[0], points[1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fillRect(shape.x, shape.y, shape.width, shape.height); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.strokeRect(shape.x, shape.y, shape.width, shape.height); } } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.beginPath(); context.arc(shape.x, shape.y, shape.radius,0,2*Math.PI); context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas var w = shape.width * 2; @@ -119,18 +135,21 @@ context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; var width = shape.width; @@ -152,13 +171,15 @@ context.quadraticCurveTo(rx, ry, rx, ry + radius); context.closePath(); - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); @@ -174,45 +195,54 @@ * @param graphics {Graphics} the graphics which will be used as a mask * @param context {CanvasRenderingContext2D} the context 2d method of the canvas */ -CanvasGraphics.renderGraphicsMask = function (graphics, context) { +CanvasGraphics.renderGraphicsMask = function (graphics, context) +{ var len = graphics.graphicsData.length; - if (len === 0) { + if (len === 0) + { return; } context.beginPath(); - for (var i = 0; i < len; i++) { + for (var i = 0; i < len; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { context.rect(shape.x, shape.y, shape.width, shape.height); context.closePath(); } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.arc(shape.x, shape.y, shape.radius, 0, 2 * Math.PI); context.closePath(); } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas @@ -237,7 +267,8 @@ context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); context.closePath(); } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; @@ -262,8 +293,10 @@ } }; -CanvasGraphics.updateGraphicsTint = function (graphics) { - if (graphics.tint === 0xFFFFFF) { +CanvasGraphics.updateGraphicsTint = function (graphics) +{ + if (graphics.tint === 0xFFFFFF) + { return; } @@ -271,7 +304,8 @@ var tintG = (graphics.tint >> 8 & 0xFF) / 255; var tintB = (graphics.tint & 0xFF)/ 255; - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var fillColor = data.fillColor | 0; diff --git a/src/core/renderers/canvas/utils/CanvasMaskManager.js b/src/core/renderers/canvas/utils/CanvasMaskManager.js index e04a733..9827d36 100644 --- a/src/core/renderers/canvas/utils/CanvasMaskManager.js +++ b/src/core/renderers/canvas/utils/CanvasMaskManager.js @@ -6,7 +6,8 @@ * @class * @namespace PIXI */ -function CanvasMaskManager() {} +function CanvasMaskManager() +{} CanvasMaskManager.prototype.constructor = CanvasMaskManager; module.exports = CanvasMaskManager; @@ -17,7 +18,8 @@ * @param maskData {object} the maskData that will be pushed * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.pushMask = function (maskData, renderer) { +CanvasMaskManager.prototype.pushMask = function (maskData, renderer) +{ renderer.context.save(); var cacheAlpha = maskData.alpha; @@ -45,6 +47,7 @@ * * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.popMask = function (renderer) { +CanvasMaskManager.prototype.popMask = function (renderer) +{ renderer.context.restore(); }; diff --git a/src/core/renderers/canvas/utils/CanvasTinter.js b/src/core/renderers/canvas/utils/CanvasTinter.js index 17e0529..d2fb1bc 100644 --- a/src/core/renderers/canvas/utils/CanvasTinter.js +++ b/src/core/renderers/canvas/utils/CanvasTinter.js @@ -14,7 +14,8 @@ * @param color {number} the color to use to tint the sprite with * @return {HTMLCanvasElement} The tinted canvas */ -CanvasTinter.getTintedTexture = function (sprite, color) { +CanvasTinter.getTintedTexture = function (sprite, color) +{ var texture = sprite.texture; color = CanvasTinter.roundColor(color); @@ -23,7 +24,8 @@ texture.tintCache = texture.tintCache || {}; - if (texture.tintCache[stringColor]) { + if (texture.tintCache[stringColor]) + { return texture.tintCache[stringColor]; } @@ -33,14 +35,16 @@ //CanvasTinter.tintWithPerPixel(texture, stringColor, canvas); CanvasTinter.tintMethod(texture, color, canvas); - if (CanvasTinter.convertTintToImage) { + if (CanvasTinter.convertTintToImage) + { // is this better? var tintImage = new Image(); tintImage.src = canvas.toDataURL(); texture.tintCache[stringColor] = tintImage; } - else { + else + { texture.tintCache[stringColor] = canvas; // if we are not converting the texture to an image then we need to lose the reference to the canvas CanvasTinter.canvas = null; @@ -56,7 +60,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithMultiply = function (texture, color, canvas) { +CanvasTinter.tintWithMultiply = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -104,7 +109,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithOverlay = function (texture, color, canvas) { +CanvasTinter.tintWithOverlay = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -139,7 +145,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithPerPixel = function (texture, color, canvas) { +CanvasTinter.tintWithPerPixel = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -167,7 +174,8 @@ var pixels = pixelData.data; - for (var i = 0; i < pixels.length; i += 4) { + for (var i = 0; i < pixels.length; i += 4) + { pixels[i+0] *= r; pixels[i+1] *= g; pixels[i+2] *= b; @@ -181,7 +189,8 @@ * * @param color {number} the color to round, should be a hex color */ -CanvasTinter.roundColor = function (color) { +CanvasTinter.roundColor = function (color) +{ var step = CanvasTinter.cacheStepsPerColorChannel; var rgbValues = utils.hex2rgb(color); diff --git a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js index 9f2f89a..35edbaf 100644 --- a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js +++ b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLBlendModeManager(renderer) { +function WebGLBlendModeManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -23,8 +24,10 @@ * * @param blendMode {number} the blendMode, should be a Pixi const, such as BlendModes.ADD */ -WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) { - if (this.currentBlendMode === blendMode) { +WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) +{ + if (this.currentBlendMode === blendMode) + { return false; } diff --git a/src/core/renderers/webgl/managers/WebGLFilterManager.js b/src/core/renderers/webgl/managers/WebGLFilterManager.js index 1179258..2dac048 100644 --- a/src/core/renderers/webgl/managers/WebGLFilterManager.js +++ b/src/core/renderers/webgl/managers/WebGLFilterManager.js @@ -7,7 +7,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLFilterManager(renderer) { +function WebGLFilterManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -32,7 +33,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.texturePool.length = 0; self.initShaderBuffers(); }); @@ -46,7 +48,8 @@ * @param renderer {WebGLRenderer} * @param buffer {ArrayBuffer} */ -WebGLFilterManager.prototype.begin = function (buffer) { +WebGLFilterManager.prototype.begin = function (buffer) +{ this.defaultShader = this.renderer.shaderManager.defaultShader; this.width = this.renderer.projection.x * 2; @@ -60,7 +63,8 @@ * * @param filterBlock {object} the filter that will be pushed to the current filter stack */ -WebGLFilterManager.prototype.pushFilter = function (filterBlock) { +WebGLFilterManager.prototype.pushFilter = function (filterBlock) +{ var gl = this.renderer.gl; var projection = this.renderer.projection; @@ -78,10 +82,12 @@ this.offsetY += filterBlock._filterArea.y; var texture = this.texturePool.pop(); - if (!texture) { + if (!texture) + { texture = new FilterTexture(this.renderer.gl, this.width, this.height); } - else { + else + { texture.resize(this.width, this.height); } @@ -98,29 +104,35 @@ var localX = filterArea.x, localY = filterArea.y; - if (filterArea.x < 0) { + if (filterArea.x < 0) + { filterArea.width += filterArea.x; filterArea.x = 0; } - if (filterArea.y < 0) { + if (filterArea.y < 0) + { filterArea.height += filterArea.y; filterArea.y = 0; } - if (localX + filterArea.width > this.width) { + if (localX + filterArea.width > this.width) + { filterArea.width = this.width - localX; } - if (localY + filterArea.height > this.height) { + if (localY + filterArea.height > this.height) + { filterArea.height = this.height - localY; } - if (filterArea.width < 0) { + if (filterArea.width < 0) + { filterArea.width = 0; } - if (filterArea.height < 0) { + if (filterArea.height < 0) + { filterArea.height = 0; } @@ -154,7 +166,8 @@ * Removes the last filter from the filter stack and doesn't return it. * */ -WebGLFilterManager.prototype.popFilter = function () { +WebGLFilterManager.prototype.popFilter = function () +{ var gl = this.renderer.gl; var filterBlock = this.filterStack.pop(); @@ -163,7 +176,8 @@ var projection = this.renderer.projection; var offset = this.renderer.offset; - if (filterBlock.filterPasses.length > 1) { + if (filterBlock.filterPasses.length > 1) + { gl.viewport(0, 0, filterArea.width, filterArea.height); gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); @@ -193,7 +207,8 @@ var inputTexture = texture; var outputTexture = this.texturePool.pop(); - if (!outputTexture) { + if (!outputTexture) + { outputTexture = new FilterTexture(this.renderer.gl, this.width, this.height); } outputTexture.resize(this.width, this.height); @@ -204,7 +219,8 @@ gl.disable(gl.BLEND); - for (var i = 0; i < filterBlock.filterPasses.length-1; i++) { + for (var i = 0; i < filterBlock.filterPasses.length-1; i++) + { var filterPass = filterBlock.filterPasses[i]; gl.bindFramebuffer(gl.FRAMEBUFFER, outputTexture.frameBuffer ); @@ -243,10 +259,12 @@ var buffer = this.buffer; // time to render the filters texture to the previous scene - if (this.filterStack.length === 0) { + if (this.filterStack.length === 0) + { gl.colorMask(true, true, true, true);//this.transparent); } - else { + else + { var currentFilter = this.filterStack[this.filterStack.length-1]; filterArea = currentFilter._filterArea; @@ -332,13 +350,15 @@ * @param width {number} the horizontal range of the filter * @param height {number} the vertical range of the filter */ -WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) { +WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) +{ // use program var gl = this.renderer.gl; var shader = filter.shaders[gl.id]; - if (!shader) { + if (!shader) + { shader = new Shader(gl); shader.fragmentSrc = filter.fragmentSrc; @@ -356,7 +376,8 @@ gl.uniform2f(shader.projectionVector, width/2, -height/2); gl.uniform2f(shader.offsetVector, 0,0); - if (filter.uniforms.dimensions) { + 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]; @@ -386,7 +407,8 @@ * Initialises the shader buffers. * */ -WebGLFilterManager.prototype.initShaderBuffers = function () { +WebGLFilterManager.prototype.initShaderBuffers = function () +{ var gl = this.renderer.gl; // create some buffers @@ -432,7 +454,8 @@ * Destroys the filter and removes it from the filter stack. * */ -WebGLFilterManager.prototype.destroy = function () { +WebGLFilterManager.prototype.destroy = function () +{ var gl = this.renderer.gl; this.filterStack = null; @@ -441,7 +464,8 @@ this.offsetY = 0; // destroy textures - for (var i = 0; i < this.texturePool.length; i++) { + for (var i = 0; i < this.texturePool.length; i++) + { this.texturePool[i].destroy(); } diff --git a/src/core/renderers/webgl/managers/WebGLManager.js b/src/core/renderers/webgl/managers/WebGLManager.js index 9d47b5c..c30cd51 100644 --- a/src/core/renderers/webgl/managers/WebGLManager.js +++ b/src/core/renderers/webgl/managers/WebGLManager.js @@ -3,7 +3,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLManager(renderer) { +function WebGLManager(renderer) +{ /** * The renderer this manager works for. * @@ -15,6 +16,7 @@ WebGLManager.prototype.constructor = WebGLManager; module.exports = WebGLManager; -WebGLManager.prototype.destroy = function () { +WebGLManager.prototype.destroy = function () +{ this.renderer = null; }; diff --git a/src/core/renderers/webgl/managers/WebGLMaskManager.js b/src/core/renderers/webgl/managers/WebGLMaskManager.js index 2f90b64..e568812 100644 --- a/src/core/renderers/webgl/managers/WebGLMaskManager.js +++ b/src/core/renderers/webgl/managers/WebGLMaskManager.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLMaskManager(renderer) { +function WebGLMaskManager(renderer) +{ WebGLManager.call(this, renderer); } @@ -19,12 +20,15 @@ * * @param maskData {any[]} */ -WebGLMaskManager.prototype.pushMask = function (maskData) { - if (maskData.dirty) { +WebGLMaskManager.prototype.pushMask = function (maskData) +{ + if (maskData.dirty) + { WebGLGraphics.updateGraphics(maskData, this.renderer.gl); } - if (!maskData._webGL[this.renderer.gl.id].data.length) { + if (!maskData._webGL[this.renderer.gl.id].data.length) + { return; } @@ -36,6 +40,7 @@ * * @param maskData {any[]} */ -WebGLMaskManager.prototype.popMask = function (maskData) { +WebGLMaskManager.prototype.popMask = function (maskData) +{ this.renderer.stencilManager.popStencil(maskData, maskData._webGL[this.renderer.gl.id].data[0], this.renderer); }; diff --git a/src/core/renderers/webgl/managers/WebGLShaderManager.js b/src/core/renderers/webgl/managers/WebGLShaderManager.js index fef071c..90c6477 100644 --- a/src/core/renderers/webgl/managers/WebGLShaderManager.js +++ b/src/core/renderers/webgl/managers/WebGLShaderManager.js @@ -10,7 +10,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLShaderManager(renderer) { +function WebGLShaderManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -28,7 +29,8 @@ */ this.tempAttribState = []; - for (var i = 0; i < this.maxAttibs; i++) { + for (var i = 0; i < this.maxAttibs; i++) + { this.attribState[i] = false; } @@ -66,7 +68,8 @@ // listen for context and update necessary shaders var self = this; - this.renderer.on('context', function (event) { + this.renderer.on('context', function (event) + { var gl = event.data; // this shader is used for rendering primitives @@ -97,29 +100,36 @@ * * @param attribs {Array} attribs */ -WebGLShaderManager.prototype.setAttribs = function (attribs) { +WebGLShaderManager.prototype.setAttribs = function (attribs) +{ // reset temp state var i; - for (i = 0; i < this.tempAttribState.length; i++) { + for (i = 0; i < this.tempAttribState.length; i++) + { this.tempAttribState[i] = false; } // set the new attribs - for (var a in attribs) { + for (var a in attribs) + { this.tempAttribState[attribs[a]] = true; } var gl = this.renderer.gl; - for (i = 0; i < this.attribState.length; i++) { - if (this.attribState[i] !== this.tempAttribState[i]) { + for (i = 0; i < this.attribState.length; i++) + { + if (this.attribState[i] !== this.tempAttribState[i]) + { this.attribState[i] = this.tempAttribState[i]; - if (this.attribState[i]) { + if (this.attribState[i]) + { gl.enableVertexAttribArray(i); } - else { + else + { gl.disableVertexAttribArray(i); } } @@ -131,8 +141,10 @@ * * @param shader {Any} */ -WebGLShaderManager.prototype.setShader = function (shader) { - if (this._currentId === shader.uuid) { +WebGLShaderManager.prototype.setShader = function (shader) +{ + if (this._currentId === shader.uuid) + { return false; } @@ -150,7 +162,8 @@ * Destroys this object. * */ -WebGLShaderManager.prototype.destroy = function () { +WebGLShaderManager.prototype.destroy = function () +{ this.attribState = null; this.tempAttribState = null; diff --git a/src/core/renderers/webgl/managers/WebGLStencilManager.js b/src/core/renderers/webgl/managers/WebGLStencilManager.js index 9ec6398..4cb0134 100644 --- a/src/core/renderers/webgl/managers/WebGLStencilManager.js +++ b/src/core/renderers/webgl/managers/WebGLStencilManager.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLStencilManager(renderer) { +function WebGLStencilManager(renderer) +{ WebGLManager.call(this, renderer); this.stencilStack = []; @@ -24,12 +25,14 @@ * @param graphics {Graphics} * @param webGLData {any[]} */ -WebGLStencilManager.prototype.pushStencil = function (graphics, webGLData) { +WebGLStencilManager.prototype.pushStencil = function (graphics, webGLData) +{ var gl = this.renderer.gl; this.bindGraphics(graphics, webGLData, this.renderer); - if (this.stencilStack.length === 0) { + if (this.stencilStack.length === 0) + { gl.enable(gl.STENCIL_TEST); gl.clear(gl.STENCIL_BUFFER_BIT); this.reverse = true; @@ -47,14 +50,17 @@ // draw the triangle strip! - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } @@ -62,31 +68,38 @@ // draw a quad to increment.. gl.drawElements(gl.TRIANGLE_FAN, 4, gl.UNSIGNED_SHORT, ( webGLData.indices.length - 4 ) * 2 ); - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); } this.reverse = !this.reverse; } - else { - if (!this.reverse) { + else + { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } - else { + 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) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); } } @@ -103,7 +116,8 @@ * @param graphics {Graphics} * @param webGLData {Array} */ -WebGLStencilManager.prototype.bindGraphics = function (graphics, webGLData) { +WebGLStencilManager.prototype.bindGraphics = function (graphics, webGLData) +{ //if (this._currentGraphics === graphics)return; this._currentGraphics = graphics; @@ -114,7 +128,8 @@ offset = this.renderer.offset, shader;// = this.renderer.shaderManager.primitiveShader; - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { shader = this.renderer.shaderManager.complexPrimitiveShader; this.renderer.shaderManager.setShader(shader); @@ -141,7 +156,8 @@ // set the index buffer! gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, webGLData.indexBuffer); } - else { + else + { //this.renderer.shaderManager.activatePrimitiveShader(); shader = this.renderer.shaderManager.primitiveShader; this.renderer.shaderManager.setShader( shader ); @@ -154,7 +170,7 @@ gl.uniform2f(shader.uniforms.offsetVector._location, -offset.x, -offset.y); gl.uniform3fv(shader.uniforms.tint._location, utils.hex2rgb(graphics.tint)); - + gl.uniform1f(shader.uniforms.alpha._location, graphics.worldAlpha); @@ -172,19 +188,22 @@ * @param graphics {Graphics} * @param webGLData {Array} */ -WebGLStencilManager.prototype.popStencil = function (graphics, webGLData) { +WebGLStencilManager.prototype.popStencil = function (graphics, webGLData) +{ var gl = this.renderer.gl; this.stencilStack.pop(); this.count--; - if (this.stencilStack.length === 0) { + if (this.stencilStack.length === 0) + { // the stack is empty! gl.disable(gl.STENCIL_TEST); } - else { + else + { var level = this.count; @@ -192,14 +211,17 @@ gl.colorMask(false, false, false, false); - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { this.reverse = !this.reverse; - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } @@ -213,31 +235,38 @@ // draw the triangle strip! gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); - if (!this.reverse) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); } } - else { + else + { // console.log("<<>>") - if (!this.reverse) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } - else { + 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) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); } } @@ -253,7 +282,8 @@ * Destroys the mask stack. * */ -WebGLStencilManager.prototype.destroy = function () { +WebGLStencilManager.prototype.destroy = function () +{ this.renderer = null; this.stencilStack = null; }; diff --git a/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js b/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js index 913ba5e..1ea7d19 100644 --- a/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js +++ b/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function ComplexPrimitiveShader(gl) { +function ComplexPrimitiveShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -24,7 +25,8 @@ 'uniform float flipY;', 'varying vec4 vColor;', - 'void main(void) {', + '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);', @@ -37,7 +39,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = vColor;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/FastShader.js b/src/core/renderers/webgl/shaders/FastShader.js index bd2e29a..2e5e060 100644 --- a/src/core/renderers/webgl/shaders/FastShader.js +++ b/src/core/renderers/webgl/shaders/FastShader.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function FastShader(gl) { +function FastShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -28,7 +29,8 @@ 'const vec2 center = vec2(-1.0, 1.0);', - 'void main(void) {', + 'void main(void) + {', ' vec2 v;', ' vec2 sv = aVertexPosition * aScale;', ' v.x = (sv.x) * cos(aRotation) - (sv.y) * sin(aRotation);', @@ -49,7 +51,8 @@ 'uniform sampler2D uSampler;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/PrimitiveShader.js b/src/core/renderers/webgl/shaders/PrimitiveShader.js index 6f25409..a25f54f 100644 --- a/src/core/renderers/webgl/shaders/PrimitiveShader.js +++ b/src/core/renderers/webgl/shaders/PrimitiveShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function PrimitiveShader(gl) { +function PrimitiveShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -23,7 +24,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + '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);', @@ -36,7 +38,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = vColor;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/Shader.js b/src/core/renderers/webgl/shaders/Shader.js index f8964f5..fd75ef5 100644 --- a/src/core/renderers/webgl/shaders/Shader.js +++ b/src/core/renderers/webgl/shaders/Shader.js @@ -6,7 +6,8 @@ * @param [fragmentSrc] {string} The source of the fragment shader. * @param [vertexSrc] {string} The source of the vertex shader. */ -function Shader(gl, vertexSrc, fragmentSrc, customUniforms, customAttributes) { +function Shader(gl, vertexSrc, fragmentSrc, customUniforms, customAttributes) +{ /** * @member {number} * @readonly @@ -33,7 +34,8 @@ dimensions: { type: '4f', value: new Float32Array(4) } }; - for (var u in customUniforms) { + for (var u in customUniforms) + { this.uniforms[u] = customUniforms[u]; } @@ -43,7 +45,8 @@ aColor: 0 }; - for (var a in customAttributes) { + for (var a in customAttributes) + { this.attributes[a] = customAttributes[a]; } @@ -66,7 +69,8 @@ 'const vec2 center = vec2(-1.0, 1.0);', - 'void main(void) {', + 'void main(void) + {', ' gl_Position = vec4( ((aVertexPosition + offsetVector) / projectionVector) + center , 0.0, 1.0);', ' vTextureCoord = aTextureCoord;', ' vColor = vec4(aColor.rgb * aColor.a, aColor.a);', @@ -85,7 +89,8 @@ 'uniform sampler2D uSampler;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;', '}' ].join('\n'); @@ -96,7 +101,8 @@ Shader.prototype.constructor = Shader; module.exports = Shader; -Shader.prototype.init = function () { +Shader.prototype.init = function () +{ this.compile(); this.gl.useProgram(this.program); @@ -105,14 +111,18 @@ this.cacheAttributeLocations(Object.keys(this.attributes)); }; -Shader.prototype.cacheUniformLocations = function (keys) { - for (var i = 0; i < keys.length; ++i) { +Shader.prototype.cacheUniformLocations = function (keys) +{ + for (var i = 0; i < keys.length; ++i) + { this.uniforms[keys[i]]._location = this.gl.getUniformLocation(this.program, keys[i]); } }; -Shader.prototype.cacheAttributeLocations = function (keys) { - for (var i = 0; i < keys.length; ++i) { +Shader.prototype.cacheAttributeLocations = function (keys) +{ + for (var i = 0; i < keys.length; ++i) + { this.attributes[keys[i]] = this.gl.getAttribLocation(this.program, keys[i]); } @@ -124,14 +134,16 @@ // 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.attributes.aColor === -1) { + // if (this.attributes.aColor === -1) + { // this.attributes.aColor = 2; // } // End worst hack eva // }; -Shader.prototype.compile = function () { +Shader.prototype.compile = function () +{ var gl = this.gl; var glVertShader = this._glCompile(gl.VERTEX_SHADER, this.vertexSrc); @@ -144,13 +156,15 @@ gl.linkProgram(program); // if linking fails, then log and cleanup - if (!gl.getProgramParameter(program, gl.LINK_STATUS)) { + if (!gl.getProgramParameter(program, gl.LINK_STATUS)) + { window.console.error('Pixi.js Error: Could not initialize shader.'); window.console.error('gl.VALIDATE_STATUS', gl.getProgramParameter(program, gl.VALIDATE_STATUS)); window.console.error('gl.getError()', gl.getError()); // if there is a program info log, log it - if (gl.getProgramInfoLog(program) !== '') { + if (gl.getProgramInfoLog(program) !== '') + { window.console.warn('Pixi.js Warning: gl.getProgramInfoLog()', gl.getProgramInfoLog(program)); } @@ -165,18 +179,21 @@ return (this.program = program); }; -Shader.prototype.syncUniforms = function () { +Shader.prototype.syncUniforms = function () +{ var gl = this.gl; this.textureCount = 1; - for (var key in this.uniforms) { + for (var key in this.uniforms) + { var uniform = this.uniforms[key], location = uniform._location, value = uniform.value, i, il; - switch (uniform.type) { + switch (uniform.type) + { // single int value case 'i': case '1i': @@ -282,7 +299,8 @@ // a Color Value case 'c': - if (typeof value === 'number') { + if (typeof value === 'number') + { value = utils.hex2rgb(value); } @@ -311,11 +329,13 @@ // array of 2D Point objects case 'v2v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(2 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 2] = value[i].x; uniform._array[i * 2 + 1] = value[i].y; } @@ -325,11 +345,13 @@ // array of 3D Point objects case 'v3v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(3 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 3] = value[i].x; uniform._array[i * 3 + 1] = value[i].y; uniform._array[i * 3 + 2] = value[i].z; @@ -341,11 +363,13 @@ // array of 4D Point objects case 'v4v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(4 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 4] = value[i].x; uniform._array[i * 4 + 1] = value[i].y; uniform._array[i * 4 + 2] = value[i].z; @@ -359,7 +383,8 @@ // PIXI.Texture case 't': case 'sampler2D': - if (!uniform.value || !uniform.value.baseTexture || !uniform.value.baseTexture.hasLoaded) { + if (!uniform.value || !uniform.value.baseTexture || !uniform.value.baseTexture.hasLoaded) + { break; } @@ -376,7 +401,8 @@ this.textureCount++; // initialize the texture if we haven't yet - if (!uniform._init) { + if (!uniform._init) + { this.initSampler2D(uniform); uniform._init = true; @@ -394,11 +420,13 @@ * Initialises a Sampler2D uniform (which may only be available later on after initUniforms once the texture has loaded) * */ -Shader.prototype.initSampler2D = function (uniform) { +Shader.prototype.initSampler2D = function (uniform) +{ var gl = this.gl; // Extended texture data - if (uniform.textureData) { + if (uniform.textureData) + { var data = uniform.textureData; // GLTexture = mag linear, min linear_mipmap_linear, wrap repeat + gl.generateMipmap(gl.TEXTURE_2D); @@ -417,14 +445,16 @@ var wrapT = (data.wrapT) ? data.wrapT : gl.CLAMP_TO_EDGE; var format = (data.luminance) ? gl.LUMINANCE : gl.RGBA; - if (data.repeat) { + if (data.repeat) + { wrapS = gl.REPEAT; wrapT = gl.REPEAT; } gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, !!data.flipY); - if (data.width) { + if (data.width) + { var width = (data.width) ? data.width : 512; var height = (data.height) ? data.height : 2; var border = (data.border) ? data.border : 0; @@ -432,7 +462,8 @@ // 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 { + 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); } @@ -448,7 +479,8 @@ * Destroys the shader. * */ -Shader.prototype.destroy = function () { +Shader.prototype.destroy = function () +{ this.gl.deleteProgram(this.program); this.gl = null; @@ -459,13 +491,15 @@ this.fragmentSrc = null; }; -Shader.prototype._glCompile = function (type, src) { +Shader.prototype._glCompile = function (type, src) +{ var shader = this.gl.createShader(type); this.gl.shaderSource(shader, src); this.gl.compileShader(shader); - if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) { + if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) + { window.console.log(this.gl.getShaderInfoLog(shader)); return null; } diff --git a/src/core/renderers/webgl/shaders/StripShader.js b/src/core/renderers/webgl/shaders/StripShader.js index 193f6e1..a7abcc6 100644 --- a/src/core/renderers/webgl/shaders/StripShader.js +++ b/src/core/renderers/webgl/shaders/StripShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function StripShader(gl) { +function StripShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -20,7 +21,8 @@ 'varying vec2 vTextureCoord;', - 'void main(void) {', + '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);', @@ -36,7 +38,8 @@ 'varying vec2 vTextureCoord;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vec2(vTextureCoord.x, vTextureCoord.y)) * alpha;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/utils/FilterTexture.js b/src/core/renderers/webgl/utils/FilterTexture.js index d2c8423..4433d44 100644 --- a/src/core/renderers/webgl/utils/FilterTexture.js +++ b/src/core/renderers/webgl/utils/FilterTexture.js @@ -8,7 +8,8 @@ * @param height {number} the vertical range of the filter * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values */ -function FilterTexture(gl, width, height, scaleMode) { +function FilterTexture(gl, width, height, scaleMode) +{ /** * @member {WebGLContext} */ @@ -59,7 +60,8 @@ * Clears the filter texture. * */ -FilterTexture.prototype.clear = function () { +FilterTexture.prototype.clear = function () +{ var gl = this.gl; gl.clearColor(0,0,0, 0); @@ -72,8 +74,10 @@ * @param width {number} the new width of the texture * @param height {number} the new height of the texture */ -FilterTexture.prototype.resize = function (width, height) { - if (this.width === width && this.height === height) { +FilterTexture.prototype.resize = function (width, height) +{ + if (this.width === width && this.height === height) + { return; } @@ -96,7 +100,8 @@ * Destroys the filter texture. * */ -FilterTexture.prototype.destroy = function () { +FilterTexture.prototype.destroy = function () +{ var gl = this.gl; gl.deleteFramebuffer( this.frameBuffer ); gl.deleteTexture( this.texture ); diff --git a/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js b/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js index c4721e9..a63f4d7 100644 --- a/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js +++ b/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js @@ -14,7 +14,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this sprite batch works for. */ -function WebGLFastSpriteBatch(renderer) { +function WebGLFastSpriteBatch(renderer) +{ /** * The renderer instance this sprite batch operates on. * @@ -91,7 +92,8 @@ */ this.lastIndexCount = 0; - for (var i=0, j=0; i < numIndices; i += 6, j += 4) { + 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; @@ -144,7 +146,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.setupContext(); }); } @@ -157,7 +160,8 @@ * * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLFastSpriteBatch.prototype.setupContext = function () { +WebGLFastSpriteBatch.prototype.setupContext = function () +{ var gl = this.renderer.gl; // create a couple of buffers @@ -177,7 +181,8 @@ /** * @param spriteBatch {SpriteBatch} The SpriteBatch container to prepare for. */ -WebGLFastSpriteBatch.prototype.begin = function (spriteBatch) { +WebGLFastSpriteBatch.prototype.begin = function (spriteBatch) +{ this.shader = this.renderer.shaderManager.fastShader; this.matrix = spriteBatch.worldTransform.toArray(true); @@ -187,33 +192,38 @@ /** */ -WebGLFastSpriteBatch.prototype.end = function () { +WebGLFastSpriteBatch.prototype.end = function () +{ this.flush(); }; /** * @param spriteBatch {SpriteBatch} The SpriteBatch container to render. */ -WebGLFastSpriteBatch.prototype.render = function (spriteBatch) { +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) { + if (!sprite.texture._uvs) + { return; } this.currentBaseTexture = sprite.texture.baseTexture; // check blend mode - if (sprite.blendMode !== this.renderer.blendModeManager.currentBlendMode) { + if (sprite.blendMode !== this.renderer.blendModeManager.currentBlendMode) + { this.flush(); this.renderer.blendModeManager.setBlendMode(sprite.blendMode); } - for (var i=0,j= children.length; i= this.size) { + if (this.currentBatchSize >= this.size) + { this.flush(); } }; @@ -362,29 +379,35 @@ /** * */ -WebGLFastSpriteBatch.prototype.flush = function () { +WebGLFastSpriteBatch.prototype.flush = function () +{ // If the batch is length 0 then return as there is nothing to draw - if (this.currentBatchSize === 0) { + if (this.currentBatchSize === 0) + { return; } var gl = this.renderer.gl; // bind the current texture - if (!this.currentBaseTexture._glTextures[gl.id]) { + if (!this.currentBaseTexture._glTextures[gl.id]) + { this.renderer.updateTexture(this.currentBaseTexture, gl); } //TODO-SHOUD THIS BE ELSE??!?!?! - else { + else + { gl.bindTexture(gl.TEXTURE_2D, this.currentBaseTexture._glTextures[gl.id]); } // upload the verts to the buffer - if (this.currentBatchSize > ( this.size * 0.5 ) ) { + if (this.currentBatchSize > ( this.size * 0.5 ) ) + { gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); } - else { + else + { var view = this.vertices.subarray(0, this.currentBatchSize * this.vertByteSize); gl.bufferSubData(gl.ARRAY_BUFFER, 0, view); @@ -405,14 +428,16 @@ * Ends the batch and flushes * */ -WebGLFastSpriteBatch.prototype.stop = function () { +WebGLFastSpriteBatch.prototype.stop = function () +{ this.flush(); }; /** * */ -WebGLFastSpriteBatch.prototype.start = function () { +WebGLFastSpriteBatch.prototype.start = function () +{ var gl = this.renderer.gl; // bind the main texture diff --git a/src/core/renderers/webgl/utils/WebGLGraphics.js b/src/core/renderers/webgl/utils/WebGLGraphics.js index 55f4911..ab8f46e 100644 --- a/src/core/renderers/webgl/utils/WebGLGraphics.js +++ b/src/core/renderers/webgl/utils/WebGLGraphics.js @@ -19,7 +19,8 @@ * @param graphics {Graphics} * @param renderer {WebGLRenderer} */ -WebGLGraphics.renderGraphics = function (graphics, renderer) {//projection, offset) { +WebGLGraphics.renderGraphics = function (graphics, renderer) {//projection, offset) +{ var gl = renderer.gl; var projection = renderer.projection, @@ -27,7 +28,8 @@ shader = renderer.shaderManager.primitiveShader, webGLData; - if (graphics.dirty) { + if (graphics.dirty) + { WebGLGraphics.updateGraphics(graphics, gl); } @@ -35,8 +37,10 @@ // This could be speeded up for sure! - for (var i = 0; i < webGL.data.length; i++) { - if (webGL.data[i].mode === 1) { + for (var i = 0; i < webGL.data.length; i++) + { + if (webGL.data[i].mode === 1) + { webGLData = webGL.data[i]; renderer.stencilManager.pushStencil(graphics, webGLData, renderer); @@ -46,7 +50,8 @@ renderer.stencilManager.popStencil(graphics, webGLData, renderer); } - else { + else + { webGLData = webGL.data[i]; @@ -84,12 +89,14 @@ * @param graphicsData {Graphics} The graphics object to update * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLGraphics.updateGraphics = function (graphics, gl) { +WebGLGraphics.updateGraphics = function (graphics, gl) +{ // get the contexts graphics object var webGL = graphics._webGL[gl.id]; // if the graphics object does not exist in the webGL context time to create it! - if (!webGL) { + if (!webGL) + { webGL = graphics._webGL[gl.id] = {lastIndex:0, data:[], gl:gl}; } @@ -99,11 +106,13 @@ var i; // if the user cleared the graphics object we will need to clear every object - if (graphics.clearDirty) { + if (graphics.clearDirty) + { graphics.clearDirty = false; // lop through and return all the webGLDatas to the object pool so than can be reused later on - for (i = 0; i < webGL.data.length; i++) { + for (i = 0; i < webGL.data.length; i++) + { var graphicsData = webGL.data[i]; graphicsData.reset(); WebGLGraphics.graphicsDataPool.push( graphicsData ); @@ -119,58 +128,72 @@ // loop through the graphics datas and construct each one.. // if the object is a complex fill then the new stencil buffer technique will be used // other wise graphics objects will be pushed into a batch.. - for (i = webGL.lastIndex; i < graphics.graphicsData.length; i++) { + for (i = webGL.lastIndex; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { // need to add the points the the graphics object.. data.points = data.shape.points.slice(); - if (data.shape.closed) { + if (data.shape.closed) + { // close the poly if the value is true! - if (data.points[0] !== data.points[data.points.length-2] || data.points[1] !== data.points[data.points.length-1]) { + if (data.points[0] !== data.points[data.points.length-2] || data.points[1] !== data.points[data.points.length-1]) + { data.points.push(data.points[0], data.points[1]); } } // MAKE SURE WE HAVE THE CORRECT TYPE.. - if (data.fill) { - if (data.points.length >= 6) { - if (data.points.length < 6 * 2) { + if (data.fill) + { + if (data.points.length >= 6) + { + if (data.points.length < 6 * 2) + { webGLData = WebGLGraphics.switchMode(webGL, 0); var canDrawUsingSimple = WebGLGraphics.buildPoly(data, webGLData); // console.log(canDrawUsingSimple); - if (!canDrawUsingSimple) { + if (!canDrawUsingSimple) + { // console.log("<>>>") webGLData = WebGLGraphics.switchMode(webGL, 1); WebGLGraphics.buildComplexPoly(data, webGLData); } } - else { + else + { webGLData = WebGLGraphics.switchMode(webGL, 1); WebGLGraphics.buildComplexPoly(data, webGLData); } } } - if (data.lineWidth > 0) { + if (data.lineWidth > 0) + { webGLData = WebGLGraphics.switchMode(webGL, 0); WebGLGraphics.buildLine(data, webGLData); } } - else { + else + { webGLData = WebGLGraphics.switchMode(webGL, 0); - if (data.type === CONST.SHAPES.RECT) { + if (data.type === CONST.SHAPES.RECT) + { WebGLGraphics.buildRectangle(data, webGLData); } - else if (data.type === CONST.SHAPES.CIRC || data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.CIRC || data.type === CONST.SHAPES.ELIP) + { WebGLGraphics.buildCircle(data, webGLData); } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { WebGLGraphics.buildRoundedRectangle(data, webGLData); } } @@ -179,10 +202,12 @@ } // upload all the dirty data... - for (i = 0; i < webGL.data.length; i++) { + for (i = 0; i < webGL.data.length; i++) + { webGLData = webGL.data[i]; - if (webGLData.dirty) { + if (webGLData.dirty) + { webGLData.upload(); } } @@ -194,18 +219,22 @@ * @param webGL {WebGLContext} * @param type {number} */ -WebGLGraphics.switchMode = function (webGL, type) { +WebGLGraphics.switchMode = function (webGL, type) +{ var webGLData; - if (!webGL.data.length) { + if (!webGL.data.length) + { webGLData = WebGLGraphics.graphicsDataPool.pop() || new WebGLGraphicsData(webGL.gl); webGLData.mode = type; webGL.data.push(webGLData); } - else { + else + { webGLData = webGL.data[webGL.data.length-1]; - if (webGLData.mode !== type || type === 1) { + if (webGLData.mode !== type || type === 1) + { webGLData = WebGLGraphics.graphicsDataPool.pop() || new WebGLGraphicsData(webGL.gl); webGLData.mode = type; webGL.data.push(webGLData); @@ -225,7 +254,8 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildRectangle = function (graphicsData, webGLData) { +WebGLGraphics.buildRectangle = function (graphicsData, webGLData) +{ // --- // // need to convert points to a nice regular data // @@ -235,7 +265,8 @@ var width = rectData.width; var height = rectData.height; - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -265,7 +296,8 @@ indices.push(vertPos, vertPos, vertPos+1, vertPos+2, vertPos+3, vertPos+3); } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = [x, y, @@ -289,7 +321,8 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildRoundedRectangle = function (graphicsData, webGLData) { +WebGLGraphics.buildRoundedRectangle = function (graphicsData, webGLData) +{ var rrectData = graphicsData.shape; var x = rrectData.x; var y = rrectData.y; @@ -305,7 +338,8 @@ recPoints = recPoints.concat(WebGLGraphics.quadraticBezierCurve(x + width, y + radius, x + width, y, x + width - radius, y)); recPoints = recPoints.concat(WebGLGraphics.quadraticBezierCurve(x + radius, y, x, y, x, y + radius)); - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -323,7 +357,8 @@ // var i = 0; - for (i = 0; i < triangles.length; i+=3) { + for (i = 0; i < triangles.length; i+=3) + { indices.push(triangles[i] + vecPos); indices.push(triangles[i] + vecPos); indices.push(triangles[i+1] + vecPos); @@ -332,12 +367,14 @@ } - for (i = 0; i < recPoints.length; i++) { + for (i = 0; i < recPoints.length; i++) + { verts.push(recPoints[i], recPoints[++i], r, g, b, alpha); } } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = recPoints; @@ -362,7 +399,8 @@ * @param toY {number} Destination point y * @return {number[]} */ -WebGLGraphics.quadraticBezierCurve = function (fromX, fromY, cpX, cpY, toX, toY) { +WebGLGraphics.quadraticBezierCurve = function (fromX, fromY, cpX, cpY, toX, toY) +{ var xa, ya, @@ -373,14 +411,16 @@ n = 20, points = []; - function getPt(n1 , n2, perc) { + function getPt(n1 , n2, perc) + { var diff = n2 - n1; return n1 + ( diff * perc ); } var j = 0; - for (var i = 0; i <= n; i++ ) { + for (var i = 0; i <= n; i++ ) + { j = i / n; // The Green Line @@ -406,7 +446,8 @@ * @param graphicsData {Graphics} The graphics object to draw * @param webGLData {object} */ -WebGLGraphics.buildCircle = function (graphicsData, webGLData) { +WebGLGraphics.buildCircle = function (graphicsData, webGLData) +{ // need to convert points to a nice regular data var circleData = graphicsData.shape; var x = circleData.x; @@ -415,11 +456,13 @@ var height; // TODO - bit hacky?? - if (graphicsData.type === CONST.SHAPES.CIRC) { + if (graphicsData.type === CONST.SHAPES.CIRC) + { width = circleData.radius; height = circleData.radius; } - else { + else + { width = circleData.width; height = circleData.height; } @@ -429,7 +472,8 @@ var i = 0; - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -444,7 +488,8 @@ indices.push(vecPos); - for (i = 0; i < totalSegs + 1 ; i++) { + for (i = 0; i < totalSegs + 1 ; i++) + { verts.push(x,y, r, g, b, alpha); verts.push(x + Math.sin(seg * i) * width, @@ -457,12 +502,14 @@ indices.push(vecPos-1); } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = []; - for (i = 0; i < totalSegs + 1; i++) { + for (i = 0; i < totalSegs + 1; i++) + { graphicsData.points.push(x + Math.sin(seg * i) * width, y + Math.cos(seg * i) * height); } @@ -481,18 +528,22 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildLine = function (graphicsData, webGLData) { +WebGLGraphics.buildLine = function (graphicsData, webGLData) +{ // TODO OPTIMISE! var i = 0; var points = graphicsData.points; - if (points.length === 0) { + if (points.length === 0) + { return; } // if the line width is an odd number add 0.5 to align to a whole pixel - if (graphicsData.lineWidth%2) { - for (i = 0; i < points.length; i++) { + if (graphicsData.lineWidth%2) + { + for (i = 0; i < points.length; i++) + { points[i] += 0.5; } } @@ -502,7 +553,8 @@ var lastPoint = new math.Point(points[points.length - 2], points[points.length - 1]); // if the first point is the last point - gonna have issues :) - if (firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) { + if (firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) + { // need to clone as we are going to slightly modify the shape.. points = points.slice(); @@ -562,7 +614,8 @@ verts.push(p1x + perpx , p1y + perpy, r, g, b, alpha); - for (i = 1; i < length-1; i++) { + for (i = 1; i < length-1; i++) + { p1x = points[(i-1)*2]; p1y = points[(i-1)*2 + 1]; @@ -599,7 +652,8 @@ denom = a1*b2 - a2*b1; - if (Math.abs(denom) < 0.1 ) { + if (Math.abs(denom) < 0.1 ) + { denom+=10.1; verts.push(p2x - perpx , p2y - perpy, @@ -618,7 +672,8 @@ pdist = (px -p2x) * (px -p2x) + (py -p2y) + (py -p2y); - if (pdist > 140 * 140) { + if (pdist > 140 * 140) + { perp3x = perpx - perp2x; perp3y = perpy - perp2y; @@ -639,7 +694,8 @@ indexCount++; } - else { + else + { verts.push(px , py); verts.push(r, g, b, alpha); @@ -672,7 +728,8 @@ indices.push(indexStart); - for (i = 0; i < indexCount; i++) { + for (i = 0; i < indexCount; i++) + { indices.push(indexStart++); } @@ -687,11 +744,13 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildComplexPoly = function (graphicsData, webGLData) { +WebGLGraphics.buildComplexPoly = function (graphicsData, webGLData) +{ //TODO - no need to copy this as it gets turned into a FLoat32Array anyways.. var points = graphicsData.points.slice(); - if (points.length < 6) { + if (points.length < 6) + { return; } @@ -711,7 +770,8 @@ var x,y; // get size.. - for (var i = 0; i < points.length; i+=2) { + for (var i = 0; i < points.length; i+=2) + { x = points[i]; y = points[i+1]; @@ -732,7 +792,8 @@ //TODO - this aint needed! var length = points.length / 2; - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { indices.push( i ); } @@ -746,10 +807,12 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildPoly = function (graphicsData, webGLData) { +WebGLGraphics.buildPoly = function (graphicsData, webGLData) +{ var points = graphicsData.points; - if (points.length < 6) { + if (points.length < 6) + { return; } // get first and last point.. figure out the middle! @@ -767,7 +830,8 @@ var triangles = utils.PolyK.Triangulate(points); - if (!triangles) { + if (!triangles) + { return false; } @@ -775,7 +839,8 @@ var i = 0; - for (i = 0; i < triangles.length; i+=3) { + for (i = 0; i < triangles.length; i+=3) + { indices.push(triangles[i] + vertPos); indices.push(triangles[i] + vertPos); indices.push(triangles[i+1] + vertPos); @@ -783,7 +848,8 @@ indices.push(triangles[i+2] + vertPos); } - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { verts.push(points[i * 2], points[i * 2 + 1], r, g, b, alpha); } diff --git a/src/core/renderers/webgl/utils/WebGLGraphicsData.js b/src/core/renderers/webgl/utils/WebGLGraphicsData.js index c56d05e..c739ba7 100644 --- a/src/core/renderers/webgl/utils/WebGLGraphicsData.js +++ b/src/core/renderers/webgl/utils/WebGLGraphicsData.js @@ -2,7 +2,8 @@ * @class * @private */ -function WebGLGraphicsData(gl) { +function WebGLGraphicsData(gl) +{ this.gl = gl; //TODO does this need to be split before uploding?? @@ -22,7 +23,8 @@ /** * */ -WebGLGraphicsData.prototype.reset = function () { +WebGLGraphicsData.prototype.reset = function () +{ this.points.length = 0; this.indices.length = 0; }; @@ -30,7 +32,8 @@ /** * */ -WebGLGraphicsData.prototype.upload = function () { +WebGLGraphicsData.prototype.upload = function () +{ var gl = this.gl; // this.lastIndex = graphics.graphicsData.length; diff --git a/src/core/renderers/webgl/utils/WebGLSpriteBatch.js b/src/core/renderers/webgl/utils/WebGLSpriteBatch.js index 96eaa52..55befbb 100644 --- a/src/core/renderers/webgl/utils/WebGLSpriteBatch.js +++ b/src/core/renderers/webgl/utils/WebGLSpriteBatch.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this sprite batch works for. */ -function WebGLSpriteBatch(renderer) { +function WebGLSpriteBatch(renderer) +{ /** * * @@ -88,7 +89,8 @@ */ this.lastIndexCount = 0; - for (var i=0, j=0; i < numIndices; i += 6, j += 4) { + 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; @@ -162,7 +164,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.setupContext(); }); } @@ -173,7 +176,8 @@ /** * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLSpriteBatch.prototype.setupContext = function () { +WebGLSpriteBatch.prototype.setupContext = function () +{ var gl = this.renderer.gl; // setup default shader @@ -198,7 +202,8 @@ /** * */ -WebGLSpriteBatch.prototype.begin = function () { +WebGLSpriteBatch.prototype.begin = function () +{ // this.shader = this.renderer.shaderManager.defaultShader; this.start(); @@ -206,19 +211,22 @@ /** */ -WebGLSpriteBatch.prototype.end = function () { +WebGLSpriteBatch.prototype.end = function () +{ this.flush(); }; /** * @param sprite {Sprite} the sprite to render when using this spritebatch */ -WebGLSpriteBatch.prototype.render = function (sprite) { +WebGLSpriteBatch.prototype.render = function (sprite) +{ var texture = sprite.texture; //TODO set blend modes.. // check texture.. - if (this.currentBatchSize >= this.size) { + if (this.currentBatchSize >= this.size) + { this.flush(); this.currentBaseTexture = texture.baseTexture; } @@ -227,7 +235,8 @@ var uvs = texture._uvs; // if the uvs have not updated then no point rendering just yet! - if (!uvs) { + if (!uvs) + { return; } @@ -237,7 +246,8 @@ var w0, w1, h0, h1; - if (texture.trim) { + 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; @@ -248,7 +258,8 @@ h0 = h1 + texture.crop.height; } - else { + else + { w0 = (texture.frame.width ) * (1-aX); w1 = (texture.frame.width ) * -aX; @@ -272,7 +283,8 @@ var colors = this.colors; var positions = this.positions; - if (this.renderer.roundPixels) { + if (this.renderer.roundPixels) + { // xy positions[index] = a * w1 + c * h1 + tx | 0; positions[index+1] = d * h1 + b * w1 + ty | 0; @@ -289,7 +301,8 @@ positions[index+15] = a * w1 + c * h0 + tx | 0; positions[index+16] = d * h0 + b * w1 + ty | 0; } - else { + else + { // xy positions[index] = a * w1 + c * h1 + tx; positions[index+1] = d * h1 + b * w1 + ty; @@ -338,11 +351,13 @@ * * @param sprite {TilingSprite} the tilingSprite to render */ -WebGLSpriteBatch.prototype.renderTilingSprite = function (tilingSprite) { +WebGLSpriteBatch.prototype.renderTilingSprite = function (tilingSprite) +{ var texture = tilingSprite.tilingTexture; // check texture.. - if (this.currentBatchSize >= this.size) { + if (this.currentBatchSize >= this.size) + { //return; this.flush(); this.currentBaseTexture = texture.baseTexture; @@ -351,7 +366,8 @@ // set the textures uvs temporarily // TODO create a separate texture so that we can tile part of a texture - if (!tilingSprite._uvs) { + if (!tilingSprite._uvs) + { tilingSprite._uvs = new TextureUvs(); } @@ -454,16 +470,19 @@ * Renders the content and empties the current batch. * */ -WebGLSpriteBatch.prototype.flush = function () { +WebGLSpriteBatch.prototype.flush = function () +{ // If the batch is length 0 then return as there is nothing to draw - if (this.currentBatchSize === 0) { + if (this.currentBatchSize === 0) + { return; } var gl = this.renderer.gl; var shader; - if (this.dirty) { + if (this.dirty) + { this.dirty = false; // bind the main texture gl.activeTexture(gl.TEXTURE0); @@ -482,10 +501,12 @@ } // upload the verts to the buffer - if (this.currentBatchSize > ( this.size * 0.5 ) ) { + if (this.currentBatchSize > ( this.size * 0.5 ) ) + { gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); } - else { + else + { var view = this.positions.subarray(0, this.currentBatchSize * this.vertByteSize); gl.bufferSubData(gl.ARRAY_BUFFER, 0, view); } @@ -502,7 +523,8 @@ var shaderSwap = false; var sprite; - for (var i = 0, j = this.currentBatchSize; i < j; i++) { + for (var i = 0, j = this.currentBatchSize; i < j; i++) + { sprite = this.sprites[i]; @@ -513,24 +535,28 @@ blendSwap = currentBlendMode !== nextBlendMode; shaderSwap = currentShader !== nextShader; // should I use uuidS??? - if (currentBaseTexture !== nextTexture || blendSwap || shaderSwap) { + if (currentBaseTexture !== nextTexture || blendSwap || shaderSwap) + { this.renderBatch(currentBaseTexture, batchSize, start); start = i; batchSize = 0; currentBaseTexture = nextTexture; - if (blendSwap) { + if (blendSwap) + { currentBlendMode = nextBlendMode; this.renderer.blendModeManager.setBlendMode( currentBlendMode ); } - if (shaderSwap) { + if (shaderSwap) + { currentShader = nextShader; shader = currentShader.shaders ? currentShader.shaders[gl.id] : currentShader; - if (!shader) { + if (!shader) + { shader = new Shader(gl, null, currentShader.fragmentSrc, currentShader.uniforms); currentShader.shaders[gl.id] = shader; } @@ -538,7 +564,8 @@ // set shader function??? this.renderer.shaderManager.setShader(shader); - if (shader.dirty) { + if (shader.dirty) + { shader.syncUniforms(); } @@ -569,17 +596,21 @@ * @param size {number} * @param startIndex {number} */ -WebGLSpriteBatch.prototype.renderBatch = function (texture, size, startIndex) { - if (size === 0) { +WebGLSpriteBatch.prototype.renderBatch = function (texture, size, startIndex) +{ + if (size === 0) + { return; } var gl = this.renderer.gl; - if (!texture._glTextures[gl.id]) { + if (!texture._glTextures[gl.id]) + { this.renderer.updateTexture(texture); } - else { + else + { // bind the current texture gl.bindTexture(gl.TEXTURE_2D, texture._glTextures[gl.id]); } @@ -594,7 +625,8 @@ /** * */ -WebGLSpriteBatch.prototype.stop = function () { +WebGLSpriteBatch.prototype.stop = function () +{ this.flush(); this.dirty = true; }; @@ -602,7 +634,8 @@ /** * */ -WebGLSpriteBatch.prototype.start = function () { +WebGLSpriteBatch.prototype.start = function () +{ this.dirty = true; }; @@ -610,7 +643,8 @@ * Destroys the SpriteBatch. * */ -WebGLSpriteBatch.prototype.destroy = function () { +WebGLSpriteBatch.prototype.destroy = function () +{ this.renderer.gl.deleteBuffer(this.vertexBuffer); this.renderer.gl.deleteBuffer(this.indexBuffer); diff --git a/src/core/textures/BaseTexture.js b/src/core/textures/BaseTexture.js index 2bf77d4..513d358 100644 --- a/src/core/textures/BaseTexture.js +++ b/src/core/textures/BaseTexture.js @@ -10,7 +10,8 @@ * @param source {Image|Canvas} the source object of the texture. * @param [scaleMode=scaleModes.DEFAULT] {number} See {@link scaleModes} for possible values */ -function BaseTexture(source, scaleMode) { +function BaseTexture(source, scaleMode) +{ this.uuid = utils.uuid(); /** @@ -123,7 +124,8 @@ this._needsUpdate = false; // if no source passed don't try to load - if (source) { + if (source) + { this.loadSource(source); } @@ -149,13 +151,16 @@ Object.defineProperties(BaseTexture.prototype, { needsUpdate: { - get: function () { + get: function () + { return this._needsUpdate; }, - set: function (val) { + set: function (val) + { this._needsUpdate = val; - if (val) { + if (val) + { this.emit('update', this); } } @@ -171,9 +176,11 @@ * * The logic state after calling `loadSource` directly or indirectly (eg. `fromImage`, `new BaseTexture`) is: * - * if (texture.hasLoaded) { + * if (texture.hasLoaded) + { * // texture ready for use - * } else if (texture.isLoading) { + * } else if (texture.isLoading) + { * // listen to 'loaded' and/or 'error' events on texture * } else { * // not loading, not going to load UNLESS the source is reloaded @@ -183,12 +190,14 @@ * @protected * @param source {Image|Canvas} the source object of the texture. */ -BaseTexture.prototype.loadSource = function (source) { +BaseTexture.prototype.loadSource = function (source) +{ var wasLoading = this.isLoading; this.hasLoaded = false; this.isLoading = false; - if (wasLoading && this.source) { + if (wasLoading && this.source) + { this.source.onload = null; this.source.onerror = null; } @@ -196,20 +205,24 @@ this.source = source; // Apply source if loaded. Otherwise setup appropriate loading monitors. - if ((this.source.complete || this.source.getContext) && this.source.width && this.source.height) { + if ((this.source.complete || this.source.getContext) && this.source.width && this.source.height) + { this._sourceLoaded(); } - else if(!source.getContext) { + else if(!source.getContext) + { // Image fail / not ready this.isLoading = true; var scope = this; - source.onload = function () { + source.onload = function () + { source.onload = null; source.onerror = null; - if(!scope.isLoading) { + if(!scope.isLoading) + { return; } @@ -219,11 +232,13 @@ scope.emit('loaded', scope); }; - source.onerror = function () { + source.onerror = function () + { source.onload = null; source.onerror = null; - if(!scope.isLoading) { + if(!scope.isLoading) + { return; } @@ -234,24 +249,29 @@ // Per http://www.w3.org/TR/html5/embedded-content-0.html#the-img-element // "The value of `complete` can thus change while a script is executing." // So complete needs to be re-checked after the callbacks have been added.. - if (source.complete) { + if (source.complete) + { this.isLoading = false; // ..and if we're complete now, no need for callbacks source.onload = null; source.onerror = null; - if (source.width && source.height) { + if (source.width && source.height) + { this._sourceLoaded(); // If any previous subscribers possible - if (wasLoading) { + if (wasLoading) + { this.emit('loaded', this); } } - else { + else + { // If any previous subscribers possible - if (wasLoading) { + if (wasLoading) + { this.emit('error', this); } } @@ -265,7 +285,8 @@ * * @private */ -BaseTexture.prototype._sourceLoaded = function () { +BaseTexture.prototype._sourceLoaded = function () +{ this.hasLoaded = true; this.width = this.source.naturalWidth || this.source.width; @@ -278,16 +299,20 @@ * Destroys this base texture * */ -BaseTexture.prototype.destroy = function () { - if (this.imageUrl) { +BaseTexture.prototype.destroy = function () +{ + if (this.imageUrl) + { delete utils.BaseTextureCache[this.imageUrl]; delete utils.TextureCache[this.imageUrl]; this.imageUrl = null; - if (!navigator.isCocoonJS) { + if (!navigator.isCocoonJS) + { this.source.src = ''; } } - else if (this.source && this.source._pixiId) { + else if (this.source && this.source._pixiId) + { delete utils.BaseTextureCache[this.source._pixiId]; } this.source = null; @@ -301,7 +326,8 @@ * memory again. * */ -BaseTexture.prototype.dispose = function () { +BaseTexture.prototype.dispose = function () +{ this.emit('dispose', this); }; @@ -311,7 +337,8 @@ * * @param newSrc {string} the path of the image */ -BaseTexture.prototype.updateSourceImage = function (newSrc) { +BaseTexture.prototype.updateSourceImage = function (newSrc) +{ this.source.src = newSrc; this.loadSource(this.source); }; @@ -326,18 +353,22 @@ * @param [scaleMode=scaleModes.DEFAULT] {number} See {@link scaleModes} for possible values * @return BaseTexture */ -BaseTexture.fromImage = function (imageUrl, crossorigin, scaleMode) { +BaseTexture.fromImage = function (imageUrl, crossorigin, scaleMode) +{ var baseTexture = utils.BaseTextureCache[imageUrl]; - if (crossorigin === undefined && imageUrl.indexOf('data:') !== 0) { + if (crossorigin === undefined && imageUrl.indexOf('data:') !== 0) + { crossorigin = true; } - if (!baseTexture) { + if (!baseTexture) + { // new Image() breaks tex loading in some versions of Chrome. // See https://code.google.com/p/chromium/issues/detail?id=238071 var image = new Image();//document.createElement('img'); - if (crossorigin) { + if (crossorigin) + { image.crossOrigin = ''; } @@ -347,7 +378,8 @@ utils.BaseTextureCache[imageUrl] = baseTexture; // if there is an @2x at the end of the url we are going to assume its a highres image - if ( imageUrl.indexOf(CONST.RETINA_PREFIX + '.') !== -1) { + if ( imageUrl.indexOf(CONST.RETINA_PREFIX + '.') !== -1) + { baseTexture.resolution = 2; } } @@ -363,14 +395,17 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return BaseTexture */ -BaseTexture.fromCanvas = function (canvas, scaleMode) { - if (!canvas._pixiId) { +BaseTexture.fromCanvas = function (canvas, scaleMode) +{ + if (!canvas._pixiId) + { canvas._pixiId = 'canvas_' + utils.uuid(); } var baseTexture = utils.BaseTextureCache[canvas._pixiId]; - if (!baseTexture) { + if (!baseTexture) + { baseTexture = new BaseTexture(canvas, scaleMode); utils.BaseTextureCache[canvas._pixiId] = baseTexture; } diff --git a/src/core/textures/RenderTexture.js b/src/core/textures/RenderTexture.js index 6dad20f..53ae796 100644 --- a/src/core/textures/RenderTexture.js +++ b/src/core/textures/RenderTexture.js @@ -46,8 +46,10 @@ * @param [scaleMode] {number} See {@link scaleModes} for possible values * @param [resolution=1] {number} The resolution of the texture being generated */ -function RenderTexture(renderer, width, height, scaleMode, resolution) { - if (!renderer) { +function RenderTexture(renderer, width, height, scaleMode, resolution) +{ + if (!renderer) + { throw new Error('Unable to create RenderTexture, you must pass a renderer into the constructor.'); } @@ -133,7 +135,8 @@ */ this.renderer = renderer; - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { var gl = this.renderer.gl; this.textureBuffer = new FilterTexture(gl, this.width * this.resolution, this.height * this.resolution, this.baseTexture.scaleMode); @@ -142,7 +145,8 @@ this.render = this.renderWebGL; this.projection = new math.Point(this.width*0.5, -this.height*0.5); } - else { + else + { this.render = this.renderCanvas; this.textureBuffer = new CanvasBuffer(this.width* this.resolution, this.height* this.resolution); this.baseTexture.source = this.textureBuffer.canvas; @@ -167,8 +171,10 @@ * @param height {number} The height to resize to. * @param updateBase {boolean} Should the baseTexture.width and height values be resized as well? */ -RenderTexture.prototype.resize = function (width, height, updateBase) { - if (width === this.width && height === this.height) { +RenderTexture.prototype.resize = function (width, height, updateBase) +{ + if (width === this.width && height === this.height) + { return; } @@ -177,17 +183,20 @@ this.width = this.frame.width = this.crop.width = width; this.height = this.frame.height = this.crop.height = height; - if (updateBase) { + if (updateBase) + { this.baseTexture.width = this.width; this.baseTexture.height = this.height; } - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { this.projection.x = this.width / 2; this.projection.y = -this.height / 2; } - if (!this.valid) { + if (!this.valid) + { return; } @@ -198,12 +207,15 @@ * Clears the RenderTexture. * */ -RenderTexture.prototype.clear = function () { - if (!this.valid) { +RenderTexture.prototype.clear = function () +{ + if (!this.valid) + { return; } - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { this.renderer.gl.bindFramebuffer(this.renderer.gl.FRAMEBUFFER, this.textureBuffer.frameBuffer); } @@ -220,19 +232,23 @@ * @param [restoreWorldTransform=true] {boolean} If true the displayObject's worldTransform/worldAlpha and all children * transformations will be restored. Not restoring this information will be a little faster. */ -RenderTexture.prototype.renderWebGL = function (displayObject, matrix, clear, restoreWorldTransform) { - if (!this.valid) { +RenderTexture.prototype.renderWebGL = function (displayObject, matrix, clear, restoreWorldTransform) +{ + if (!this.valid) + { return; } - if (typeof restoreWorldTransform === 'undefined') { + if (typeof restoreWorldTransform === 'undefined') + { restoreWorldTransform = true; } var tempAlpha, tempTransform; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { tempAlpha = displayObject.worldAlpha; tempTransform = displayObject.worldTransform.toArray(); } @@ -245,7 +261,8 @@ wt.identity(); wt.translate(0, this.projection.y * 2); - if (matrix) { + if (matrix) + { wt.append(matrix); } @@ -258,7 +275,8 @@ var children = displayObject.children; var i, j; - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } @@ -269,7 +287,8 @@ gl.bindFramebuffer(gl.FRAMEBUFFER, this.textureBuffer.frameBuffer ); - if (clear) { + if (clear) + { this.textureBuffer.clear(); } @@ -279,11 +298,13 @@ this.renderer.spriteBatch.dirty = true; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { displayObject.worldAlpha = tempAlpha; displayObject.worldTransform.fromArray(tempTransform); - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } } @@ -300,26 +321,31 @@ * @param [restoreWorldTransform=true] {boolean} If true the displayObject's worldTransform/worldAlpha and all children * transformations will be restored. Not restoring this information will be a little faster. */ -RenderTexture.prototype.renderCanvas = function (displayObject, matrix, clear, restoreWorldTransform) { - if (!this.valid) { +RenderTexture.prototype.renderCanvas = function (displayObject, matrix, clear, restoreWorldTransform) +{ + if (!this.valid) + { return; } - if (typeof restoreWorldTransform === 'undefined') { + if (typeof restoreWorldTransform === 'undefined') + { restoreWorldTransform = true; } var tempAlpha, tempTransform; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { tempAlpha = displayObject.worldAlpha; tempTransform = displayObject.worldTransform.toArray(); } var wt = displayObject.worldTransform; wt.identity(); - if (matrix) { + if (matrix) + { wt.append(matrix); } @@ -330,11 +356,13 @@ var children = displayObject.children; var i, j; - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } - if (clear) { + if (clear) + { this.textureBuffer.clear(); } @@ -348,11 +376,13 @@ this.renderer.resolution = realResolution; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { displayObject.worldAlpha = tempAlpha; displayObject.worldTransform.fromArray(tempTransform); - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } } @@ -363,7 +393,8 @@ * * @return {Image} */ -RenderTexture.prototype.getImage = function () { +RenderTexture.prototype.getImage = function () +{ var image = new Image(); image.src = this.getBase64(); return image; @@ -374,7 +405,8 @@ * * @return {string} A base64 encoded string of the texture. */ -RenderTexture.prototype.getBase64 = function () { +RenderTexture.prototype.getBase64 = function () +{ return this.getCanvas().toDataURL(); }; @@ -383,8 +415,10 @@ * * @return {HTMLCanvasElement} A Canvas element with the texture rendered on. */ -RenderTexture.prototype.getCanvas = function () { - if (this.renderer.type === CONST.WEBGL_RENDERER) { +RenderTexture.prototype.getCanvas = function () +{ + if (this.renderer.type === CONST.WEBGL_RENDERER) + { var gl = this.renderer.gl; var width = this.textureBuffer.width; var height = this.textureBuffer.height; @@ -403,7 +437,8 @@ return tempCanvas.canvas; } - else { + else + { return this.textureBuffer.canvas; } }; diff --git a/src/core/display/DisplayObject.js b/src/core/display/DisplayObject.js index 66ebc3c..20e778c 100644 --- a/src/core/display/DisplayObject.js +++ b/src/core/display/DisplayObject.js @@ -7,7 +7,8 @@ * @class * @namespace PIXI */ -function DisplayObject() { +function DisplayObject() +{ /** * The coordinate of the object relative to the local coordinates of the parent. * @@ -152,10 +153,12 @@ * @memberof DisplayObject# */ x: { - get: function () { + get: function () + { return this.position.x; }, - set: function (value) { + set: function (value) + { this.position.x = value; } }, @@ -167,10 +170,12 @@ * @memberof DisplayObject# */ y: { - get: function () { + get: function () + { return this.position.y; }, - set: function (value) { + set: function (value) + { this.position.y = value; } }, @@ -183,11 +188,13 @@ * @readonly */ worldVisible: { - get: function () { + get: function () + { var item = this; do { - if (!item.visible) { + if (!item.visible) + { return false; } @@ -207,17 +214,21 @@ * @memberof DisplayObject# */ mask: { - get: function () { + get: function () + { return this._mask; }, - set: function (value) { - if (this._mask) { + set: function (value) + { + if (this._mask) + { this._mask.isMask = false; } this._mask = value; - if (this._mask) { + if (this._mask) + { this._mask.isMask = true; } } @@ -232,18 +243,23 @@ * @memberof DisplayObject# */ filters: { - get: function () { + get: function () + { return this._filters; }, - set: function (value) { - if (value) { + set: function (value) + { + if (value) + { // now put all the passes in one place.. var passes = []; - for (var i = 0; i < value.length; i++) { + for (var i = 0; i < value.length; i++) + { var filterPasses = value[i].passes; - for (var j = 0; j < filterPasses.length; j++) { + for (var j = 0; j < filterPasses.length; j++) + { passes.push(filterPasses[j]); } } @@ -264,8 +280,9 @@ * * @private */ -DisplayObject.prototype.updateTransform = function () { - +DisplayObject.prototype.updateTransform = function () +{ + // create some matrix refs for easy access var pt = this.parent.worldTransform; var wt = this.worldTransform; @@ -274,9 +291,11 @@ var a, b, c, d, tx, ty; // so if rotation is between 0 then we can simplify the multiplication process.. - if (this.rotation % math.PI_2) { + if (this.rotation % math.PI_2) + { // 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) { + if (this.rotation !== this.rotationCache) + { this.rotationCache = this.rotation; this._sr = Math.sin(this.rotation); this._cr = Math.cos(this.rotation); @@ -291,7 +310,8 @@ ty = this.position.y; // check for pivot.. not often used so geared towards that fact! - if (this.pivot.x || this.pivot.y) { + 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; } @@ -304,7 +324,8 @@ wt.tx = tx * pt.a + ty * pt.c + pt.tx; wt.ty = tx * pt.b + ty * pt.d + pt.ty; } - else { + else + { // lets do the fast version as we know there is no rotation.. a = this.scale.x; d = this.scale.y; @@ -333,7 +354,8 @@ * @param matrix {Matrix} * @return {Rectangle} the rectangular bounding area */ -DisplayObject.prototype.getBounds = function (/* matrix */) { +DisplayObject.prototype.getBounds = function (/* matrix */) +{ return math.Rectangle.EMPTY; }; @@ -342,7 +364,8 @@ * * @return {Rectangle} the rectangular bounding area */ -DisplayObject.prototype.getLocalBounds = function () { +DisplayObject.prototype.getLocalBounds = function () +{ return this.getBounds(math.Matrix.IDENTITY); }; @@ -352,7 +375,8 @@ * @param position {Point} The world origin to calculate from * @return {Point} A point object representing the position of this object */ -DisplayObject.prototype.toGlobal = function (position) { +DisplayObject.prototype.toGlobal = function (position) +{ // don't need to u[date the lot this.displayObjectUpdateTransform(); return this.worldTransform.apply(position); @@ -365,8 +389,10 @@ * @param [from] {DisplayObject} The DisplayObject to calculate the global position from * @return {Point} A point object representing the position of this object */ -DisplayObject.prototype.toLocal = function (position, from) { - if (from) { +DisplayObject.prototype.toLocal = function (position, from) +{ + if (from) + { position = from.toGlobal(position); } @@ -381,7 +407,8 @@ * @param renderer {WebGLRenderer} The renderer * @private */ -DisplayObject.prototype.renderWebGL = function (/* renderer */) { +DisplayObject.prototype.renderWebGL = function (/* renderer */) +{ // OVERWRITE; }; @@ -391,6 +418,7 @@ * @param renderer {CanvasRenderer} The renderer * @private */ -DisplayObject.prototype.renderCanvas = function (/* renderer */) { +DisplayObject.prototype.renderCanvas = function (/* renderer */) +{ // OVERWRITE; }; diff --git a/src/core/display/DisplayObjectContainer.js b/src/core/display/DisplayObjectContainer.js index 689f40b..4625ee8 100644 --- a/src/core/display/DisplayObjectContainer.js +++ b/src/core/display/DisplayObjectContainer.js @@ -12,7 +12,8 @@ * @extends DisplayObject * @namespace PIXI */ -function DisplayObjectContainer() { +function DisplayObjectContainer() +{ DisplayObject.call(this); /** @@ -47,17 +48,21 @@ * @memberof DisplayObjectContainer# */ width: { - get: function () { + get: function () + { return this.scale.x * this.getLocalBounds().width; }, - set: function (value) { + set: function (value) + { var width = this.getLocalBounds().width; - if(width !== 0) { + if(width !== 0) + { this.scale.x = value / width; } - else { + else + { this.scale.x = 1; } @@ -73,17 +78,21 @@ * @memberof DisplayObjectContainer# */ height: { - get: function () { + get: function () + { return this.scale.y * this.getLocalBounds().height; }, - set: function (value) { + set: function (value) + { var height = this.getLocalBounds().height; - if (height !== 0) { + if (height !== 0) + { this.scale.y = value / height ; } - else { + else + { this.scale.y = 1; } @@ -100,18 +109,23 @@ * @memberof DisplayObject# */ cacheAsBitmap: { - get: function () { + get: function () + { return this._cacheAsBitmap; }, - set: function (value) { - if (this._cacheAsBitmap === value) { + set: function (value) + { + if (this._cacheAsBitmap === value) + { return; } - if (value) { + if (value) + { this._generateCachedSprite(); } - else { + else + { this._destroyCachedSprite(); } @@ -126,7 +140,8 @@ * @param child {DisplayObject} The DisplayObject to add to the container * @return {DisplayObject} The child that was added. */ -DisplayObjectContainer.prototype.addChild = function (child) { +DisplayObjectContainer.prototype.addChild = function (child) +{ return this.addChildAt(child, this.children.length); }; @@ -137,14 +152,18 @@ * @param index {Number} The index to place the child in * @return {DisplayObject} The child that was added. */ -DisplayObjectContainer.prototype.addChildAt = function (child, index) { +DisplayObjectContainer.prototype.addChildAt = function (child, index) +{ // prevent adding self as child - if (child === this) { + if (child === this) + { return; } - if (index >= 0 && index <= this.children.length) { - if (child.parent) { + if (index >= 0 && index <= this.children.length) + { + if (child.parent) + { child.parent.removeChild(child); } @@ -154,7 +173,8 @@ return child; } - else { + else + { throw new Error(child + 'addChildAt: The index '+ index +' supplied is out of bounds ' + this.children.length); } }; @@ -165,15 +185,18 @@ * @param child {DisplayObject} * @param child2 {DisplayObject} */ -DisplayObjectContainer.prototype.swapChildren = function (child, child2) { - if (child === child2) { +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) { + if (index1 < 0 || index2 < 0) + { throw new Error('swapChildren: Both the supplied DisplayObjects must be a child of the caller.'); } @@ -187,10 +210,12 @@ * @param child {DisplayObject} The DisplayObject instance to identify * @return {Number} The index position of the child display object to identify */ -DisplayObjectContainer.prototype.getChildIndex = function (child) { +DisplayObjectContainer.prototype.getChildIndex = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { throw new Error('The supplied DisplayObject must be a child of the caller'); } @@ -203,8 +228,10 @@ * @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 */ -DisplayObjectContainer.prototype.setChildIndex = function (child, index) { - if (index < 0 || index >= this.children.length) { +DisplayObjectContainer.prototype.setChildIndex = function (child, index) +{ + if (index < 0 || index >= this.children.length) + { throw new Error('The supplied index is out of bounds'); } @@ -220,8 +247,10 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child at the given index, if any. */ -DisplayObjectContainer.prototype.getChildAt = function (index) { - if (index < 0 || index >= this.children.length) { +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'); } @@ -234,10 +263,12 @@ * @param child {DisplayObject} The DisplayObject to remove * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChild = function (child) { +DisplayObjectContainer.prototype.removeChild = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { return; } @@ -250,7 +281,8 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChildAt = function (index) { +DisplayObjectContainer.prototype.removeChildAt = function (index) +{ var child = this.getChildAt(index); child.parent = null; @@ -265,24 +297,29 @@ * @param beginIndex {Number} The beginning position. Default value is 0. * @param endIndex {Number} The ending position. Default value is size of the container. */ -DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) { +DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) +{ var begin = beginIndex || 0; var end = typeof endIndex === 'number' ? endIndex : this.children.length; var range = end - begin; - if (range > 0 && range <= end) { + if (range > 0 && range <= end) + { var removed = this.children.splice(begin, range); - for (var i = 0; i < removed.length; ++i) { + for (var i = 0; i < removed.length; ++i) + { removed[i].parent = null; } return removed; } - else if (range === 0 && this.children.length === 0) { + else if (range === 0 && this.children.length === 0) + { return []; } - else { + else + { throw new RangeError('removeChildren: numeric values are outside the acceptable range.'); } }; @@ -291,7 +328,8 @@ * Generates and updates the cached sprite for this object. * */ -DisplayObjectContainer.prototype.updateCachedSprite = function () { +DisplayObjectContainer.prototype.updateCachedSprite = function () +{ this._generateCachedSprite(); }; @@ -304,7 +342,8 @@ * @param renderer {CanvasRenderer|WebGLRenderer} The renderer used to generate the texture. * @return {Texture} a texture of the graphics object */ -DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) { +DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) +{ var bounds = this.getLocalBounds(); var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0, renderer, scaleMode, resolution); @@ -322,18 +361,22 @@ * * @private */ -DisplayObjectContainer.prototype.updateTransform = function () { - if (!this.visible) { +DisplayObjectContainer.prototype.updateTransform = function () +{ + if (!this.visible) + { return; } this.displayObjectUpdateTransform(); - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { return; } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } }; @@ -346,8 +389,10 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getBounds = function () { - if (this.children.length === 0) { +DisplayObjectContainer.prototype.getBounds = function () +{ + if (this.children.length === 0) + { return math.Rectangle.EMPTY; } @@ -365,10 +410,12 @@ var childVisible = false; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -386,7 +433,8 @@ maxY = maxY > childMaxY ? maxY : childMaxY; } - if (!childVisible) { + if (!childVisible) + { return math.Rectangle.EMPTY; } @@ -407,12 +455,14 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getLocalBounds = function () { +DisplayObjectContainer.prototype.getLocalBounds = function () +{ var matrixCache = this.worldTransform; this.worldTransform = math.Matrix.IDENTITY; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } @@ -428,13 +478,16 @@ * * @param renderer {WebGLRenderer} The renderer */ -DisplayObjectContainer.prototype.renderWebGL = function (renderer) { +DisplayObjectContainer.prototype.renderWebGL = function (renderer) +{ // if the object is not visible or the alpha is 0 then no need to render this element - if (!this.visible || this.alpha <= 0) { + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } @@ -442,14 +495,17 @@ var i, j; // do a quick check to see if this element has a mask or a filter. - if (this._mask || this._filters) { + if (this._mask || this._filters) + { // push filter first as we need to ensure the stencil buffer is correct for any masking - if (this._filters) { + if (this._filters) + { renderer.spriteBatch.flush(); renderer.filterManager.pushFilter(this._filterBlock); } - if (this._mask) { + if (this._mask) + { renderer.spriteBatch.stop(); renderer.maskManager.pushMask(this.mask, renderer); renderer.spriteBatch.start(); @@ -459,36 +515,42 @@ this._renderWebGL(renderer); // now loop through the children and make sure they get rendered - for (i = 0, j = this.children.length; i < j; i++) { + for (i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderWebGL(renderer); } // time to stop the sprite batch as either a mask element or a filter draw will happen next renderer.spriteBatch.stop(); - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(this._mask, renderer); } - if (this._filters) { + if (this._filters) + { renderer.filterManager.popFilter(); } renderer.spriteBatch.start(); } - else { + else + { this._renderWebGL(renderer); // simple render children! - for (i = 0, j = this.children.length; i < j; ++i) { + for (i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderWebGL(renderer); } } }; -DisplayObjectContainer.prototype._renderWebGL = function (renderer) { +DisplayObjectContainer.prototype._renderWebGL = function (renderer) +{ // this is where content itself gets renderd.. @@ -499,25 +561,31 @@ * * @param renderer {CanvasRenderer} The renderer */ -DisplayObjectContainer.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0) { +DisplayObjectContainer.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -528,13 +596,16 @@ * @param renderer {WebGLRenderer|CanvasRenderer} The renderer * @private */ -DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) { +DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) +{ this._cachedSprite.worldAlpha = this.worldAlpha; - if (renderer.gl) { + if (renderer.gl) + { this._cachedSprite.renderWebGL(renderer); } - else { + else + { this._cachedSprite.renderCanvas(renderer); } }; @@ -544,10 +615,12 @@ * * @private */ -DisplayObjectContainer.prototype._generateCachedSprite = function () { +DisplayObjectContainer.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { // TODO - RenderTexture now *requires* a renderer instance, so this is like broken // because `renderer` isn't actually in scope here :P var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0); @@ -555,7 +628,8 @@ this._cachedSprite = new Sprite(renderTexture); this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.texture.resize(bounds.width | 0, bounds.height | 0); } @@ -580,8 +654,10 @@ * * @private */ -DisplayObjectContainer.prototype._destroyCachedSprite = function () { - if (!this._cachedSprite) { +DisplayObjectContainer.prototype._destroyCachedSprite = function () +{ + if (!this._cachedSprite) + { return; } diff --git a/src/core/display/Sprite.js b/src/core/display/Sprite.js index 707da24..5862aef 100644 --- a/src/core/display/Sprite.js +++ b/src/core/display/Sprite.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param texture {Texture} The texture for this sprite */ -function Sprite(texture) { +function Sprite(texture) +{ DisplayObjectContainer.call(this); /** @@ -85,12 +86,14 @@ this.texture = texture || Texture.EMPTY; } -Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) { +Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) +{ DisplayObjectContainer.prototype.destroy.call(this); this.anchor = null; - if (destroyTexture) { + if (destroyTexture) + { this._texture.destroy(destroyBaseTexture); } @@ -111,10 +114,12 @@ * @memberof Sprite# */ width: { - get: function () { + get: function () + { return this.scale.x * this.texture.frame.width; }, - set: function (value) { + set: function (value) + { this.scale.x = value / this.texture.frame.width; this._width = value; } @@ -127,10 +132,12 @@ * @memberof Sprite# */ height: { - get: function () { + get: function () + { return this.scale.y * this.texture.frame.height; }, - set: function (value) { + set: function (value) + { this.scale.y = value / this.texture.frame.height; this._height = value; } @@ -143,23 +150,29 @@ * @memberof Sprite# */ texture: { - get: function () { + get: function () + { return this._texture; }, - set: function (value) { - if (this._texture === value) { + set: function (value) + { + if (this._texture === value) + { return; } this._texture = value; this.cachedTint = 0xFFFFFF; - if (value) { + if (value) + { // wait for the texture to load - if (value.baseTexture.hasLoaded) { + if (value.baseTexture.hasLoaded) + { this._onTextureUpdate(); } - else { + else + { value.once('update', this._onTextureUpdate.bind(this)); } } @@ -172,18 +185,22 @@ * * @private */ -Sprite.prototype._onTextureUpdate = function () { +Sprite.prototype._onTextureUpdate = function () +{ // so if _width is 0 then width was not set.. - if (this._width) { + if (this._width) + { this.scale.x = this._width / this.texture.frame.width; } - if (this._height) { + if (this._height) + { this.scale.y = this._height / this.texture.frame.height; } }; -Sprite.prototype._renderWebGL = function (renderer) { +Sprite.prototype._renderWebGL = function (renderer) +{ // this is where content gets renderd.. // watch this space for a little render state manager.. @@ -197,7 +214,8 @@ * @param matrix {Matrix} the transformation matrix of the sprite * @return {Rectangle} the framing rectangle */ -Sprite.prototype.getBounds = function (matrix) { +Sprite.prototype.getBounds = function (matrix) +{ var width = this.texture.frame.width; var height = this.texture.frame.height; @@ -224,11 +242,13 @@ if(b === 0 && c === 0) { // scale may be negative! - if (a < 0) { + if (a < 0) + { a *= -1; } - if (d < 0) { + if (d < 0) + { d *= -1; } @@ -293,28 +313,34 @@ * * @param renderer {CanvasRenderer} The renderer */ -Sprite.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) { +Sprite.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) + { return; } - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; renderer.context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } // Ignore null sources - if (this.texture.valid) { + if (this.texture.valid) + { var resolution = this.texture.baseTexture.resolution / renderer.resolution; renderer.context.globalAlpha = this.worldAlpha; // If smoothingEnabled is supported and we need to change the smoothing property for this texture - if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) { + if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) + { renderer.scaleMode = this.texture.baseTexture.scaleMode; renderer.context[renderer.smoothProperty] = (renderer.scaleMode === CONST.scaleModes.LINEAR); } @@ -324,7 +350,8 @@ var dy = (this.texture.trim ? this.texture.trim.y : 0) - (this.anchor.y * this.texture.trim.height); // Allow for pixel rounding - if (renderer.roundPixels) { + if (renderer.roundPixels) + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -337,7 +364,8 @@ dx = dx | 0; dy = dy | 0; } - else { + else + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -348,8 +376,10 @@ ); } - if (this.tint !== 0xFFFFFF) { - if (this.cachedTint !== this.tint) { + if (this.tint !== 0xFFFFFF) + { + if (this.cachedTint !== this.tint) + { this.cachedTint = this.tint; // TODO clean up caching - how to clean up the caches? @@ -368,7 +398,8 @@ this.texture.crop.height / resolution ); } - else { + else + { renderer.context.drawImage( this.texture.baseTexture.source, this.texture.crop.x, @@ -383,11 +414,13 @@ } } - for (var i = 0, j = this.children.length; i < j; i++) { + for (var i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -402,10 +435,12 @@ * @param frameId {String} The frame Id of the texture in the cache * @return {Sprite} A new Sprite using a texture from the texture cache matching the frameId */ -Sprite.fromFrame = function (frameId) { +Sprite.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache' + this); } @@ -420,6 +455,7 @@ * @param imageId {String} The image url of the texture * @return {Sprite} A new Sprite using a texture from the texture cache matching the image id */ -Sprite.fromImage = function (imageId, crossorigin, scaleMode) { +Sprite.fromImage = function (imageId, crossorigin, scaleMode) +{ return new Sprite(Texture.fromImage(imageId, crossorigin, scaleMode)); }; diff --git a/src/core/display/SpriteBatch.js b/src/core/display/SpriteBatch.js index 3187777..c196fef 100644 --- a/src/core/display/SpriteBatch.js +++ b/src/core/display/SpriteBatch.js @@ -12,7 +12,8 @@ * ```js * var container = new SpriteBatch(); * - * for(var i = 0; i < 100; ++i) { + * for(var i = 0; i < 100; ++i) + * { * var sprite = new PIXI.Sprite.fromImage("myImage.png"); * container.addChild(sprite); * } @@ -25,7 +26,8 @@ */ //TODO RENAME to PARTICLE CONTAINER? -function SpriteBatch() { +function SpriteBatch() +{ DisplayObjectContainer.call(this); } @@ -38,7 +40,8 @@ * * @private */ -SpriteBatch.prototype.updateTransform = function () { +SpriteBatch.prototype.updateTransform = function () +{ // TODO don't need to! this.displayObjectUpdateTransform(); // PIXI.DisplayObjectContainer.prototype.updateTransform.call( this ); @@ -50,8 +53,10 @@ * @param renderer {WebGLRenderer} The webgl renderer * @private */ -SpriteBatch.prototype.renderWebGL = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderWebGL = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -71,8 +76,10 @@ * @param renderer {CanvasRenderer} The canvas renderer * @private */ -SpriteBatch.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -84,10 +91,12 @@ this.displayObjectUpdateTransform(); - for (var i = 0; i < this.children.length; ++i) { + for (var i = 0; i < this.children.length; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -95,9 +104,11 @@ context.globalAlpha = this.worldAlpha * child.alpha; - if (child.rotation % (Math.PI * 2) === 0) { + if (child.rotation % (Math.PI * 2) === 0) + { // this is the fastest way to optimise! - if rotation is 0 then we can avoid any kind of setTransform call - if (isRotated) { + if (isRotated) + { context.setTransform( transform.a, transform.b, @@ -122,8 +133,10 @@ frame.height * child.scale.y ); } - else { - if (!isRotated) { + else + { + if (!isRotated) + { isRotated = true; } @@ -131,7 +144,8 @@ var childTransform = child.worldTransform; - if (renderer.roundPixels) { + if (renderer.roundPixels) + { context.setTransform( childTransform.a, childTransform.b, @@ -141,7 +155,8 @@ childTransform.ty | 0 ); } - else { + else + { context.setTransform( childTransform.a, childTransform.b, diff --git a/src/core/index.js b/src/core/index.js index 3954b6f..eb4a82b 100644 --- a/src/core/index.js +++ b/src/core/index.js @@ -58,11 +58,13 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRenderer: function (width, height, options, noWebGL) { + autoDetectRenderer: function (width, height, options, noWebGL) + { width = width || 800; height = height || 600; - if (!noWebGL && require('webgl-enabled')()) { + if (!noWebGL && require('webgl-enabled')()) + { return new core.WebGLRenderer(width, height, options); } @@ -87,7 +89,8 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRecommendedRenderer: function (width, height, options) { + autoDetectRecommendedRenderer: function (width, height, options) + { var isAndroid = /Android/i.test(navigator.userAgent); return core.autoDetectRenderer(width, height, options, isAndroid); diff --git a/src/core/math/Matrix.js b/src/core/math/Matrix.js index c2f87e2..2ff4848 100644 --- a/src/core/math/Matrix.js +++ b/src/core/math/Matrix.js @@ -10,7 +10,8 @@ * @class * @namespace PIXI */ -function Matrix() { +function Matrix() +{ /** * @member {number} * @default 1 @@ -63,7 +64,8 @@ * * @param array {number[]} The array that the matrix will be populated from. */ -Matrix.prototype.fromArray = function (array) { +Matrix.prototype.fromArray = function (array) +{ this.a = array[0]; this.b = array[1]; this.c = array[3]; @@ -78,14 +80,17 @@ * @param transpose {boolean} Whether we need to transpose the matrix or not * @return {number[]} the newly created array which contains the matrix */ -Matrix.prototype.toArray = function (transpose) { - if (!this.array) { +Matrix.prototype.toArray = function (transpose) +{ + if (!this.array) + { this.array = new Float32Array(9); } var array = this.array; - if (transpose) { + if (transpose) + { array[0] = this.a; array[1] = this.b; array[2] = 0; @@ -96,7 +101,8 @@ array[7] = this.ty; array[8] = 1; } - else { + else + { array[0] = this.a; array[1] = this.c; array[2] = this.tx; @@ -119,7 +125,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, transformed through this matrix */ -Matrix.prototype.apply = function (pos, newPos) { +Matrix.prototype.apply = function (pos, newPos) +{ newPos = newPos || new Point(); newPos.x = this.a * pos.x + this.c * pos.y + this.tx; @@ -136,7 +143,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, inverse-transformed through this matrix */ -Matrix.prototype.applyInverse = function (pos, newPos) { +Matrix.prototype.applyInverse = function (pos, newPos) +{ newPos = newPos || new Point(); var id = 1 / (this.a * this.d + this.c * -this.b); @@ -154,7 +162,8 @@ * @param {number} y * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.translate = function (x, y) { +Matrix.prototype.translate = function (x, y) +{ this.tx += x; this.ty += y; @@ -168,7 +177,8 @@ * @param {number} y The amount to scale vertically * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.scale = function (x, y) { +Matrix.prototype.scale = function (x, y) +{ this.a *= x; this.d *= y; this.c *= x; @@ -186,7 +196,8 @@ * @param {number} angle - The angle in radians. * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.rotate = function (angle) { +Matrix.prototype.rotate = function (angle) +{ var cos = Math.cos( angle ); var sin = Math.sin( angle ); @@ -210,7 +221,8 @@ * @param {Matrix} matrix * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.append = function (matrix) { +Matrix.prototype.append = function (matrix) +{ var a1 = this.a; var b1 = this.b; var c1 = this.c; @@ -232,7 +244,8 @@ * * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.identity = function () { +Matrix.prototype.identity = function () +{ this.a = 1; this.b = 0; this.c = 0; diff --git a/src/core/math/Point.js b/src/core/math/Point.js index 7565b2d..632f346 100644 --- a/src/core/math/Point.js +++ b/src/core/math/Point.js @@ -7,7 +7,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -function Point(x, y) { +function Point(x, y) +{ /** * @member {number} * @default 0 @@ -29,7 +30,8 @@ * * @return {Point} a copy of the point */ -Point.prototype.clone = function () { +Point.prototype.clone = function () +{ return new Point(this.x, this.y); }; @@ -40,7 +42,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -Point.prototype.set = function (x, y) { +Point.prototype.set = function (x, y) +{ this.x = x || 0; this.y = y || ( (y !== 0) ? this.x : 0 ) ; }; diff --git a/src/core/math/shapes/Circle.js b/src/core/math/shapes/Circle.js index 69cfdc9..4d76efc 100644 --- a/src/core/math/shapes/Circle.js +++ b/src/core/math/shapes/Circle.js @@ -10,7 +10,8 @@ * @param y {number} The Y coordinate of the center of this circle * @param radius {number} The radius of the circle */ -function Circle(x, y, radius) { +function Circle(x, y, radius) +{ /** * @member {number} * @default 0 @@ -46,7 +47,8 @@ * @method clone * @return {Circle} a copy of the Circle */ -Circle.prototype.clone = function () { +Circle.prototype.clone = function () +{ return new Circle(this.x, this.y, this.radius); }; @@ -58,8 +60,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Circle */ -Circle.prototype.contains = function (x, y) { - if (this.radius <= 0) { +Circle.prototype.contains = function (x, y) +{ + if (this.radius <= 0) + { return false; } @@ -79,6 +83,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Circle.prototype.getBounds = function () { +Circle.prototype.getBounds = function () +{ return new Rectangle(this.x - this.radius, this.y - this.radius, this.radius * 2, this.radius * 2); }; diff --git a/src/core/math/shapes/Ellipse.js b/src/core/math/shapes/Ellipse.js index 4f2d066..fefd01a 100644 --- a/src/core/math/shapes/Ellipse.js +++ b/src/core/math/shapes/Ellipse.js @@ -11,7 +11,8 @@ * @param width {number} The half width of this ellipse * @param height {number} The half height of this ellipse */ -function Ellipse(x, y, width, height) { +function Ellipse(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -53,7 +54,8 @@ * @method clone * @return {Ellipse} a copy of the ellipse */ -Ellipse.prototype.clone = function () { +Ellipse.prototype.clone = function () +{ return new Ellipse(this.x, this.y, this.width, this.height); }; @@ -65,8 +67,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coords are within this ellipse */ -Ellipse.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Ellipse.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } @@ -86,6 +90,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Ellipse.prototype.getBounds = function () { +Ellipse.prototype.getBounds = function () +{ return new Rectangle(this.x - this.width, this.y - this.height, this.width, this.height); }; diff --git a/src/core/math/shapes/Polygon.js b/src/core/math/shapes/Polygon.js index ae89148..fea6d37 100644 --- a/src/core/math/shapes/Polygon.js +++ b/src/core/math/shapes/Polygon.js @@ -10,16 +10,20 @@ * arguments passed can be flat x,y values e.g. `new Polygon(x,y, x,y, x,y, ...)` where `x` and `y` are * Numbers. */ -function Polygon(points) { +function Polygon(points) +{ //if points isn't an array, use arguments as the array - if (!(points instanceof Array)) { + if (!(points instanceof Array)) + { points = Array.prototype.slice.call(arguments); } //if this is a flat array of numbers, convert it to points - if (points[0] instanceof Point) { + if (points[0] instanceof Point) + { var p = []; - for (var i = 0, il = points.length; i < il; i++) { + for (var i = 0, il = points.length; i < il; i++) + { p.push(points[i].x, points[i].y); } @@ -51,7 +55,8 @@ * * @return {Polygon} a copy of the polygon */ -Polygon.prototype.clone = function () { +Polygon.prototype.clone = function () +{ return new Polygon(this.points.slice()); }; @@ -62,19 +67,22 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this polygon */ -Polygon.prototype.contains = function (x, y) { +Polygon.prototype.contains = function (x, y) +{ var inside = false; // use some raycasting to test hits // https://github.com/substack/point-in-polygon/blob/master/index.js var length = this.points.length / 2; - for (var i = 0, j = length - 1; i < length; j = i++) { + for (var i = 0, j = length - 1; i < length; j = i++) + { var xi = this.points[i * 2], yi = this.points[i * 2 + 1], xj = this.points[j * 2], yj = this.points[j * 2 + 1], intersect = ((yi > y) !== (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi); - if (intersect) { + if (intersect) + { inside = !inside; } } diff --git a/src/core/math/shapes/Rectangle.js b/src/core/math/shapes/Rectangle.js index 16ac62a..4008b68 100644 --- a/src/core/math/shapes/Rectangle.js +++ b/src/core/math/shapes/Rectangle.js @@ -10,7 +10,8 @@ * @param width {number} The overall width of this rectangle * @param height {number} The overall height of this rectangle */ -function Rectangle(x, y, width, height) { +function Rectangle(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -60,7 +61,8 @@ * * @return {Rectangle} a copy of the rectangle */ -Rectangle.prototype.clone = function () { +Rectangle.prototype.clone = function () +{ return new Rectangle(this.x, this.y, this.width, this.height); }; @@ -71,13 +73,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rectangle */ -Rectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Rectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/math/shapes/RoundedRectangle.js b/src/core/math/shapes/RoundedRectangle.js index 27d286e..7bf6411 100644 --- a/src/core/math/shapes/RoundedRectangle.js +++ b/src/core/math/shapes/RoundedRectangle.js @@ -11,7 +11,8 @@ * @param height {number} The overall height of this rounded rectangle * @param radius {number} Controls the radius of the rounded corners */ -function RoundedRectangle(x, y, width, height, radius) { +function RoundedRectangle(x, y, width, height, radius) +{ /** * @member {number} * @default 0 @@ -58,7 +59,8 @@ * * @return {RoundedRectangle} a copy of the rounded rectangle */ -RoundedRectangle.prototype.clone = function () { +RoundedRectangle.prototype.clone = function () +{ return new RoundedRectangle(this.x, this.y, this.width, this.height, this.radius); }; @@ -69,13 +71,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rounded Rectangle */ -RoundedRectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +RoundedRectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/primitives/Graphics.js b/src/core/primitives/Graphics.js index 261c534..e902d2a 100644 --- a/src/core/primitives/Graphics.js +++ b/src/core/primitives/Graphics.js @@ -16,7 +16,8 @@ * @extends DisplayObjectContainer * @namespace PIXI */ -function Graphics() { +function Graphics() +{ DisplayObjectContainer.call(this); this.renderable = true; @@ -154,16 +155,20 @@ * @private */ cacheAsBitmap: { - get: function () { + get: function () + { return this._cacheAsBitmap; }, - set: function (value) { + set: function (value) + { this._cacheAsBitmap = value; - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._generateCachedSprite(); } - else { + else + { this.destroyCachedSprite(); this.dirty = true; } @@ -176,7 +181,8 @@ * * @return {Graphics} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ var clone = new Graphics(); clone.renderable = this.renderable; @@ -192,7 +198,8 @@ clone.cachedSpriteDirty = this.cachedSpriteDirty; // copy graphics data - for (var i = 0; i < this.graphicsData.length; ++i) { + for (var i = 0; i < this.graphicsData.length; ++i) + { clone.graphicsData.push(this.graphicsData.clone()); } @@ -211,17 +218,21 @@ * @param alpha {number} alpha of the line to draw, will update the objects stored style * @return {Graphics} */ -Graphics.prototype.lineStyle = function (lineWidth, color, alpha) { +Graphics.prototype.lineStyle = function (lineWidth, color, alpha) +{ this.lineWidth = lineWidth || 0; this.lineColor = color || 0; this.lineAlpha = (arguments.length < 3) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length) + { // halfway through a line? start a new one! this.drawShape( new math.Polygon( this.currentPath.shape.points.slice(-2) )); } - else { + else + { // otherwise its empty so lets just set the line properties this.currentPath.lineWidth = this.lineWidth; this.currentPath.lineColor = this.lineColor; @@ -239,7 +250,8 @@ * @param y {number} the Y coordinate to move to * @return {Graphics} */ -Graphics.prototype.moveTo = function (x, y) { +Graphics.prototype.moveTo = function (x, y) +{ this.drawShape(new math.Polygon([x,y])); return this; @@ -253,7 +265,8 @@ * @param y {number} the Y coordinate to draw to * @return {Graphics} */ -Graphics.prototype.lineTo = function (x, y) { +Graphics.prototype.lineTo = function (x, y) +{ this.currentPath.shape.points.push(x, y); this.dirty = true; @@ -270,13 +283,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -285,7 +302,8 @@ n = 20, points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { this.moveTo(0, 0); } @@ -293,7 +311,8 @@ var fromY = points[points.length-1]; var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; xa = fromX + ( (cpX - fromX) * j ); @@ -319,13 +338,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -342,7 +365,8 @@ var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; dt = (1 - j); @@ -373,13 +397,17 @@ * @param radius {number} The radius of the arc * @return {Graphics} */ -Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points.push(x1, y1); } } - else { + else + { this.moveTo(x1, y1); } @@ -392,12 +420,15 @@ b2 = x2 - x1, mm = Math.abs(a1 * b2 - b1 * a2); - if (mm < 1.0e-8 || radius === 0) { - if (points[points.length-2] !== x1 || points[points.length-1] !== y1) { + if (mm < 1.0e-8 || radius === 0) + { + if (points[points.length-2] !== x1 || points[points.length-1] !== y1) + { points.push(x1, y1); } } - else { + else + { var dd = a1 * a1 + b1 * b1, cc = a2 * a2 + b2 * b2, tt = a1 * a2 + b1 * b2, @@ -433,42 +464,51 @@ * @param anticlockwise {boolean} Optional. Specifies whether the drawing should be counterclockwise or clockwise. False is default, and indicates clockwise, while true indicates counter-clockwise. * @return {Graphics} */ -Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) { +Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) +{ var startX = cx + Math.cos(startAngle) * radius; var startY = cy + Math.sin(startAngle) * radius; var points; // TODO - This if-else makes no sense. It uses currentPath in the else where it doesn't exist... - if (this.currentPath) { + if (this.currentPath) + { points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { points.push(startX, startY); } - else if (points[points.length-2] !== startX || points[points.length-1] !== startY) { + else if (points[points.length-2] !== startX || points[points.length-1] !== startY) + { points.push(startX, startY); } } - else { + else + { this.moveTo(startX, startY); points = this.currentPath.shape.points; } - if (startAngle === endAngle) { + if (startAngle === endAngle) + { return this; } - if (!anticlockwise && endAngle <= startAngle) { + if (!anticlockwise && endAngle <= startAngle) + { endAngle += Math.PI * 2; } - else if (anticlockwise && startAngle <= endAngle) { + else if (anticlockwise && startAngle <= endAngle) + { startAngle += Math.PI * 2; } var sweep = anticlockwise ? (startAngle - endAngle) *-1 : (endAngle - startAngle); var segs = (Math.abs(sweep)/ (Math.PI * 2)) * 40; - if (sweep === 0) { + if (sweep === 0) + { return this; } @@ -482,7 +522,8 @@ var remainder = ( segMinus % 1 ) / segMinus; - for (var i = 0; i <= segMinus; ++i) { + for (var i = 0; i <= segMinus; ++i) + { var real = i + remainder * i; var angle = ((theta) + startAngle + (theta2 * real)); @@ -506,13 +547,16 @@ * @param alpha {number} the alpha of the fill * @return {Graphics} */ -Graphics.prototype.beginFill = function (color, alpha) { +Graphics.prototype.beginFill = function (color, alpha) +{ this.filling = true; this.fillColor = color || 0; this.fillAlpha = (alpha === undefined) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length <= 2) + { this.currentPath.fill = this.filling; this.currentPath.fillColor = this.fillColor; this.currentPath.fillAlpha = this.fillAlpha; @@ -526,7 +570,8 @@ * * @return {Graphics} */ -Graphics.prototype.endFill = function () { +Graphics.prototype.endFill = function () +{ this.filling = false; this.fillColor = null; this.fillAlpha = 1; @@ -542,7 +587,8 @@ * @param height {number} The height of the rectangle * @return {Graphics} */ -Graphics.prototype.drawRect = function ( x, y, width, height ) { +Graphics.prototype.drawRect = function ( x, y, width, height ) +{ this.drawShape(new math.Rectangle(x,y, width, height)); return this; @@ -556,7 +602,8 @@ * @param height {number} The height of the rectangle * @param radius {number} Radius of the rectangle corners */ -Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) { +Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) +{ this.drawShape(new math.RoundedRectangle(x, y, width, height, radius)); return this; @@ -570,7 +617,8 @@ * @param radius {number} The radius of the circle * @return {Graphics} */ -Graphics.prototype.drawCircle = function (x, y, radius) { +Graphics.prototype.drawCircle = function (x, y, radius) +{ this.drawShape(new math.Circle(x,y, radius)); return this; @@ -585,7 +633,8 @@ * @param height {number} The half height of the ellipse * @return {Graphics} */ -Graphics.prototype.drawEllipse = function (x, y, width, height) { +Graphics.prototype.drawEllipse = function (x, y, width, height) +{ this.drawShape(new math.Ellipse(x, y, width, height)); return this; @@ -597,8 +646,10 @@ * @param path {Array} The path data used to construct the polygon. * @return {Graphics} */ -Graphics.prototype.drawPolygon = function (path) { - if (!(path instanceof Array)) { +Graphics.prototype.drawPolygon = function (path) +{ + if (!(path instanceof Array)) + { path = Array.prototype.slice.call(arguments); } @@ -612,7 +663,8 @@ * * @return {Graphics} */ -Graphics.prototype.clear = function () { +Graphics.prototype.clear = function () +{ this.lineWidth = 0; this.filling = false; @@ -631,7 +683,8 @@ * @param scaleMode {number} Should be one of the scaleMode consts * @return {Texture} a texture of the graphics object */ -Graphics.prototype.generateTexture = function (resolution, scaleMode) { +Graphics.prototype.generateTexture = function (resolution, scaleMode) +{ resolution = resolution || 1; var bounds = this.getBounds(); @@ -655,17 +708,21 @@ * * @param renderer {WebGLRenderer} */ -Graphics.prototype._renderWebGL = function (renderer) { +Graphics.prototype._renderWebGL = function (renderer) +{ // if the sprite is not visible or the alpha is 0 then no need to render this element - if (this.isMask === true) { + if (this.isMask === true) + { return; } // this code may still be needed so leaving for now.. - // + // /* - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture on the gpu too! @@ -681,17 +738,24 @@ return; } - */ - - // check if the webgl graphic needs to be updated - if (this.glDirty) { - this.dirty = true; - this.glDirty = false; - } + else */ - renderer.setObjectRendererer(renderer.graphicsRenderer); - renderer.graphicsRenderer.render(this); + renderer.spriteBatch.stop(); + renderer.blendModeManager.setBlendMode(this.blendMode); + // check blend mode + renderer.blendModeManager.setBlendMode( this.blendMode ); + + // check if the webgl graphic needs to be updated + if (this.glDirty) + { + this.dirty = true; + this.glDirty = false; + } + + WebGLGraphics.renderGraphics(this, renderer); + + renderer.spriteBatch.start(); }; /** @@ -700,14 +764,18 @@ * @param renderer {CanvasRenderer} * @private */ -Graphics.prototype.renderCanvas = function (renderer) { +Graphics.prototype.renderCanvas = function (renderer) +{ // 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.isMask === true) { + if (!this.visible || this.alpha <= 0 || this.isMask === true) + { return; } - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture @@ -723,16 +791,19 @@ return; } - else { + else + { var context = renderer.context; var transform = this.worldTransform; - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } @@ -748,11 +819,13 @@ CanvasGraphics.renderGraphics(this, context); - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } } @@ -763,13 +836,16 @@ * * @return {Rectangle} the rectangular bounding area */ -Graphics.prototype.getBounds = function (matrix) { +Graphics.prototype.getBounds = function (matrix) +{ // return an empty object if the item is a mask! - if (this.isMask) { + if (this.isMask) + { return math.Rectangle.EMPTY; } - if (this.dirty) { + if (this.dirty) + { this.updateLocalBounds(); this.glDirty = true; @@ -841,23 +917,27 @@ * Update the bounds of the object * */ -Graphics.prototype.updateLocalBounds = function () { +Graphics.prototype.updateLocalBounds = function () +{ var minX = Infinity; var maxX = -Infinity; var minY = Infinity; var maxY = -Infinity; - if (this.graphicsData.length) { + if (this.graphicsData.length) + { var shape, points, x, y, w, h; - for (var i = 0; i < this.graphicsData.length; i++) { + for (var i = 0; i < this.graphicsData.length; i++) + { var data = this.graphicsData[i]; var type = data.type; var lineWidth = data.lineWidth; shape = data.shape; - if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) { + if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) + { x = shape.x - lineWidth/2; y = shape.y - lineWidth/2; w = shape.width + lineWidth; @@ -869,7 +949,8 @@ minY = y < minY ? y : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.CIRC) { + else if (type === CONST.SHAPES.CIRC) + { x = shape.x; y = shape.y; w = shape.radius + lineWidth/2; @@ -881,7 +962,8 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.ELIP) { + else if (type === CONST.SHAPES.ELIP) + { x = shape.x; y = shape.y; w = shape.width + lineWidth/2; @@ -893,11 +975,13 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else { + else + { // POLY points = shape.points; - for (var j = 0; j < points.length; j += 2) { + for (var j = 0; j < points.length; j += 2) + { x = points[j]; y = points[j+1]; @@ -910,7 +994,8 @@ } } } - else { + else + { minX = 0; maxX = 0; minY = 0; @@ -931,10 +1016,12 @@ * * @private */ -Graphics.prototype._generateCachedSprite = function () { +Graphics.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { var canvasBuffer = new CanvasBuffer(bounds.width, bounds.height); var texture = Texture.fromCanvas(canvasBuffer.canvas); @@ -943,7 +1030,8 @@ this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.buffer.resize(bounds.width, bounds.height); } @@ -968,7 +1056,8 @@ * * @private */ -Graphics.prototype.updateCachedSpriteTexture = function () { +Graphics.prototype.updateCachedSpriteTexture = function () +{ var cachedSprite = this._cachedSprite; var texture = cachedSprite.texture; var canvas = cachedSprite.buffer.canvas; @@ -989,7 +1078,8 @@ * Destroys a previous cached sprite. * */ -Graphics.prototype.destroyCachedSprite = function () { +Graphics.prototype.destroyCachedSprite = function () +{ this._cachedSprite.texture.destroy(true); // let the gc collect the unused sprite @@ -1003,10 +1093,13 @@ * @param {Circle|Rectangle|Ellipse|Line|Polygon} shape The Shape object to draw. * @return {GraphicsData} The generated GraphicsData object. */ -Graphics.prototype.drawShape = function (shape) { - if (this.currentPath) { +Graphics.prototype.drawShape = function (shape) +{ + if (this.currentPath) + { // check current path! - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath.shape.points.length <= 2) + { this.graphicsData.pop(); } } @@ -1017,7 +1110,8 @@ this.graphicsData.push(data); - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { data.shape.closed = this.filling; this.currentPath = data; } diff --git a/src/core/primitives/GraphicsData.js b/src/core/primitives/GraphicsData.js index 99decbe..788f6f2 100644 --- a/src/core/primitives/GraphicsData.js +++ b/src/core/primitives/GraphicsData.js @@ -4,7 +4,8 @@ * @class * @namespace PIXI */ -function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) { +function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) +{ this.lineWidth = lineWidth; this.lineColor = lineColor; this.lineAlpha = lineAlpha; @@ -27,7 +28,8 @@ * * @return {GraphicsData} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ return new GraphicsData( this.lineWidth, this.lineColor, diff --git a/src/core/renderers/canvas/CanvasRenderer.js b/src/core/renderers/canvas/CanvasRenderer.js index 15a0978..7aebd44 100644 --- a/src/core/renderers/canvas/CanvasRenderer.js +++ b/src/core/renderers/canvas/CanvasRenderer.js @@ -17,17 +17,22 @@ * @param [options.resolution=1] {number} the resolution of the renderer retina would be 2 * @param [options.clearBeforeRender=true] {boolean} This sets if the CanvasRenderer will clear the canvas or not before the new render pass. */ -function CanvasRenderer(width, height, options) { +function CanvasRenderer(width, height, options) +{ utils.sayHello('Canvas'); - if (options) { - for (var i in CONST.defaultRenderOptions) { - if (typeof options[i] === 'undefined') { + if (options) + { + for (var i in CONST.defaultRenderOptions) + { + if (typeof options[i] === 'undefined') + { options[i] = CONST.defaultRenderOptions[i]; } } } - else { + else + { options = CONST.defaultRenderOptions; } @@ -156,19 +161,24 @@ this.smoothProperty = null; - if (this.context.imageSmoothingEnabled) { + if (this.context.imageSmoothingEnabled) + { this.smoothProperty = 'imageSmoothingEnabled'; } - else if (this.context.webkitImageSmoothingEnabled) { + else if (this.context.webkitImageSmoothingEnabled) + { this.smoothProperty = 'webkitImageSmoothingEnabled'; } - else if (this.context.mozImageSmoothingEnabled) { + else if (this.context.mozImageSmoothingEnabled) + { this.smoothProperty = 'mozImageSmoothingEnabled'; } - else if (this.context.oImageSmoothingEnabled) { + else if (this.context.oImageSmoothingEnabled) + { this.smoothProperty = 'oImageSmoothingEnabled'; } - else if (this.context.msImageSmoothingEnabled) { + else if (this.context.msImageSmoothingEnabled) + { this.smoothProperty = 'msImageSmoothingEnabled'; } @@ -193,10 +203,12 @@ * @memberof CanvasRenderer# */ backgroundColor: { - get: function () { + get: function () + { return this._backgroundColor; }, - set: function (val) { + set: function (val) + { this._backgroundColor = val; this._backgroundColorString = utils.hex2string(val); } @@ -208,7 +220,8 @@ * * @param object {DisplayObject} the object to be rendered */ -CanvasRenderer.prototype.render = function (object) { +CanvasRenderer.prototype.render = function (object) +{ object.updateTransform(); this.context.setTransform(1,0,0,1,0,0); @@ -218,16 +231,20 @@ this.currentBlendMode = CONST.blendModes.NORMAL; this.context.globalCompositeOperation = this.blendModes[CONST.blendModes.NORMAL]; - if (navigator.isCocoonJS && this.view.screencanvas) { + if (navigator.isCocoonJS && this.view.screencanvas) + { this.context.fillStyle = 'black'; this.context.clear(); } - if (this.clearBeforeRender) { - if (this.transparent) { + if (this.clearBeforeRender) + { + if (this.transparent) + { this.context.clearRect(0, 0, this.width, this.height); } - else { + else + { this.context.fillStyle = this._backgroundColorString; this.context.fillRect(0, 0, this.width , this.height); } @@ -241,8 +258,10 @@ * * @param [removeView=false] {boolean} Removes the Canvas element from the DOM. */ -CanvasRenderer.prototype.destroy = function (removeView) { - if (removeView && this.view.parent) { +CanvasRenderer.prototype.destroy = function (removeView) +{ + if (removeView && this.view.parent) + { this.view.parent.removeChild(this.view); } @@ -257,14 +276,16 @@ * @param width {number} the new width of the canvas view * @param height {number} the new height of the canvas view */ -CanvasRenderer.prototype.resize = function (width, height) { +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) { + if (this.autoResize) + { this.view.style.width = this.width / this.resolution + 'px'; this.view.style.height = this.height / this.resolution + 'px'; } @@ -276,7 +297,8 @@ * @param displayObject {DisplayObject} The displayObject to render * @private */ -CanvasRenderer.prototype.renderDisplayObject = function (displayObject) { +CanvasRenderer.prototype.renderDisplayObject = function (displayObject) +{ displayObject.renderCanvas(this); }; @@ -285,11 +307,14 @@ * * @private */ -CanvasRenderer.prototype._mapBlendModes = function () { - if (!this.blendModes) { +CanvasRenderer.prototype._mapBlendModes = function () +{ + if (!this.blendModes) + { this.blendModes = {}; - if (utils.canUseNewCanvasBlendModes()) { + if (utils.canUseNewCanvasBlendModes()) + { this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? this.blendModes[CONST.blendModes.MULTIPLY] = 'multiply'; @@ -308,7 +333,8 @@ this.blendModes[CONST.blendModes.COLOR] = 'color'; this.blendModes[CONST.blendModes.LUMINOSITY] = 'luminosity'; } - else { + else + { // this means that the browser does not support the cool new blend modes in canvas 'cough' ie 'cough' this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? diff --git a/src/core/renderers/canvas/utils/CanvasBuffer.js b/src/core/renderers/canvas/utils/CanvasBuffer.js index ebe5d47..b183a66 100644 --- a/src/core/renderers/canvas/utils/CanvasBuffer.js +++ b/src/core/renderers/canvas/utils/CanvasBuffer.js @@ -6,7 +6,8 @@ * @param width {number} the width for the newly created canvas * @param height {number} the height for the newly created canvas */ -function CanvasBuffer(width, height) { +function CanvasBuffer(width, height) +{ /** * The Canvas object that belongs to this CanvasBuffer. * @@ -36,10 +37,12 @@ * @memberof CanvasBuffer# */ width: { - get: function () { + get: function () + { return this.canvas.width; }, - set: function (val) { + set: function (val) + { this.canvas.width = val; } }, @@ -50,10 +53,12 @@ * @memberof CanvasBuffer# */ height: { - get: function () { + get: function () + { return this.canvas.height; }, - set: function (val) { + set: function (val) + { this.canvas.height = val; } } @@ -64,7 +69,8 @@ * * @private */ -CanvasBuffer.prototype.clear = function () { +CanvasBuffer.prototype.clear = function () +{ this.context.setTransform(1, 0, 0, 1, 0, 0); this.context.clearRect(0,0, this.canvas.width, this.canvas.height); }; @@ -75,7 +81,8 @@ * @param width {number} the new width of the canvas * @param height {number} the new height of the canvas */ -CanvasBuffer.prototype.resize = function (width, height) { +CanvasBuffer.prototype.resize = function (width, height) +{ this.canvas.width = width; this.canvas.height = height; }; diff --git a/src/core/renderers/canvas/utils/CanvasGraphics.js b/src/core/renderers/canvas/utils/CanvasGraphics.js index c7eaa2a..3f2a91f 100644 --- a/src/core/renderers/canvas/utils/CanvasGraphics.js +++ b/src/core/renderers/canvas/utils/CanvasGraphics.js @@ -13,15 +13,18 @@ * @param graphics {Graphics} the actual graphics object to render * @param context {CanvasRenderingContext2D} the 2d drawing method of the canvas */ -CanvasGraphics.renderGraphics = function (graphics, context) { +CanvasGraphics.renderGraphics = function (graphics, context) +{ var worldAlpha = graphics.worldAlpha; - if (graphics.dirty) { + if (graphics.dirty) + { this.updateGraphicsTint(graphics); graphics.dirty = false; } - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; @@ -30,69 +33,82 @@ context.lineWidth = data.lineWidth; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { context.beginPath(); var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } - if (shape.closed) { + if (shape.closed) + { context.lineTo(points[0], points[1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fillRect(shape.x, shape.y, shape.width, shape.height); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.strokeRect(shape.x, shape.y, shape.width, shape.height); } } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.beginPath(); context.arc(shape.x, shape.y, shape.radius,0,2*Math.PI); context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas var w = shape.width * 2; @@ -119,18 +135,21 @@ context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; var width = shape.width; @@ -152,13 +171,15 @@ context.quadraticCurveTo(rx, ry, rx, ry + radius); context.closePath(); - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); @@ -174,45 +195,54 @@ * @param graphics {Graphics} the graphics which will be used as a mask * @param context {CanvasRenderingContext2D} the context 2d method of the canvas */ -CanvasGraphics.renderGraphicsMask = function (graphics, context) { +CanvasGraphics.renderGraphicsMask = function (graphics, context) +{ var len = graphics.graphicsData.length; - if (len === 0) { + if (len === 0) + { return; } context.beginPath(); - for (var i = 0; i < len; i++) { + for (var i = 0; i < len; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { context.rect(shape.x, shape.y, shape.width, shape.height); context.closePath(); } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.arc(shape.x, shape.y, shape.radius, 0, 2 * Math.PI); context.closePath(); } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas @@ -237,7 +267,8 @@ context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); context.closePath(); } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; @@ -262,8 +293,10 @@ } }; -CanvasGraphics.updateGraphicsTint = function (graphics) { - if (graphics.tint === 0xFFFFFF) { +CanvasGraphics.updateGraphicsTint = function (graphics) +{ + if (graphics.tint === 0xFFFFFF) + { return; } @@ -271,7 +304,8 @@ var tintG = (graphics.tint >> 8 & 0xFF) / 255; var tintB = (graphics.tint & 0xFF)/ 255; - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var fillColor = data.fillColor | 0; diff --git a/src/core/renderers/canvas/utils/CanvasMaskManager.js b/src/core/renderers/canvas/utils/CanvasMaskManager.js index e04a733..9827d36 100644 --- a/src/core/renderers/canvas/utils/CanvasMaskManager.js +++ b/src/core/renderers/canvas/utils/CanvasMaskManager.js @@ -6,7 +6,8 @@ * @class * @namespace PIXI */ -function CanvasMaskManager() {} +function CanvasMaskManager() +{} CanvasMaskManager.prototype.constructor = CanvasMaskManager; module.exports = CanvasMaskManager; @@ -17,7 +18,8 @@ * @param maskData {object} the maskData that will be pushed * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.pushMask = function (maskData, renderer) { +CanvasMaskManager.prototype.pushMask = function (maskData, renderer) +{ renderer.context.save(); var cacheAlpha = maskData.alpha; @@ -45,6 +47,7 @@ * * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.popMask = function (renderer) { +CanvasMaskManager.prototype.popMask = function (renderer) +{ renderer.context.restore(); }; diff --git a/src/core/renderers/canvas/utils/CanvasTinter.js b/src/core/renderers/canvas/utils/CanvasTinter.js index 17e0529..d2fb1bc 100644 --- a/src/core/renderers/canvas/utils/CanvasTinter.js +++ b/src/core/renderers/canvas/utils/CanvasTinter.js @@ -14,7 +14,8 @@ * @param color {number} the color to use to tint the sprite with * @return {HTMLCanvasElement} The tinted canvas */ -CanvasTinter.getTintedTexture = function (sprite, color) { +CanvasTinter.getTintedTexture = function (sprite, color) +{ var texture = sprite.texture; color = CanvasTinter.roundColor(color); @@ -23,7 +24,8 @@ texture.tintCache = texture.tintCache || {}; - if (texture.tintCache[stringColor]) { + if (texture.tintCache[stringColor]) + { return texture.tintCache[stringColor]; } @@ -33,14 +35,16 @@ //CanvasTinter.tintWithPerPixel(texture, stringColor, canvas); CanvasTinter.tintMethod(texture, color, canvas); - if (CanvasTinter.convertTintToImage) { + if (CanvasTinter.convertTintToImage) + { // is this better? var tintImage = new Image(); tintImage.src = canvas.toDataURL(); texture.tintCache[stringColor] = tintImage; } - else { + else + { texture.tintCache[stringColor] = canvas; // if we are not converting the texture to an image then we need to lose the reference to the canvas CanvasTinter.canvas = null; @@ -56,7 +60,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithMultiply = function (texture, color, canvas) { +CanvasTinter.tintWithMultiply = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -104,7 +109,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithOverlay = function (texture, color, canvas) { +CanvasTinter.tintWithOverlay = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -139,7 +145,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithPerPixel = function (texture, color, canvas) { +CanvasTinter.tintWithPerPixel = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -167,7 +174,8 @@ var pixels = pixelData.data; - for (var i = 0; i < pixels.length; i += 4) { + for (var i = 0; i < pixels.length; i += 4) + { pixels[i+0] *= r; pixels[i+1] *= g; pixels[i+2] *= b; @@ -181,7 +189,8 @@ * * @param color {number} the color to round, should be a hex color */ -CanvasTinter.roundColor = function (color) { +CanvasTinter.roundColor = function (color) +{ var step = CanvasTinter.cacheStepsPerColorChannel; var rgbValues = utils.hex2rgb(color); diff --git a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js index 9f2f89a..35edbaf 100644 --- a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js +++ b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLBlendModeManager(renderer) { +function WebGLBlendModeManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -23,8 +24,10 @@ * * @param blendMode {number} the blendMode, should be a Pixi const, such as BlendModes.ADD */ -WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) { - if (this.currentBlendMode === blendMode) { +WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) +{ + if (this.currentBlendMode === blendMode) + { return false; } diff --git a/src/core/renderers/webgl/managers/WebGLFilterManager.js b/src/core/renderers/webgl/managers/WebGLFilterManager.js index 1179258..2dac048 100644 --- a/src/core/renderers/webgl/managers/WebGLFilterManager.js +++ b/src/core/renderers/webgl/managers/WebGLFilterManager.js @@ -7,7 +7,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLFilterManager(renderer) { +function WebGLFilterManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -32,7 +33,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.texturePool.length = 0; self.initShaderBuffers(); }); @@ -46,7 +48,8 @@ * @param renderer {WebGLRenderer} * @param buffer {ArrayBuffer} */ -WebGLFilterManager.prototype.begin = function (buffer) { +WebGLFilterManager.prototype.begin = function (buffer) +{ this.defaultShader = this.renderer.shaderManager.defaultShader; this.width = this.renderer.projection.x * 2; @@ -60,7 +63,8 @@ * * @param filterBlock {object} the filter that will be pushed to the current filter stack */ -WebGLFilterManager.prototype.pushFilter = function (filterBlock) { +WebGLFilterManager.prototype.pushFilter = function (filterBlock) +{ var gl = this.renderer.gl; var projection = this.renderer.projection; @@ -78,10 +82,12 @@ this.offsetY += filterBlock._filterArea.y; var texture = this.texturePool.pop(); - if (!texture) { + if (!texture) + { texture = new FilterTexture(this.renderer.gl, this.width, this.height); } - else { + else + { texture.resize(this.width, this.height); } @@ -98,29 +104,35 @@ var localX = filterArea.x, localY = filterArea.y; - if (filterArea.x < 0) { + if (filterArea.x < 0) + { filterArea.width += filterArea.x; filterArea.x = 0; } - if (filterArea.y < 0) { + if (filterArea.y < 0) + { filterArea.height += filterArea.y; filterArea.y = 0; } - if (localX + filterArea.width > this.width) { + if (localX + filterArea.width > this.width) + { filterArea.width = this.width - localX; } - if (localY + filterArea.height > this.height) { + if (localY + filterArea.height > this.height) + { filterArea.height = this.height - localY; } - if (filterArea.width < 0) { + if (filterArea.width < 0) + { filterArea.width = 0; } - if (filterArea.height < 0) { + if (filterArea.height < 0) + { filterArea.height = 0; } @@ -154,7 +166,8 @@ * Removes the last filter from the filter stack and doesn't return it. * */ -WebGLFilterManager.prototype.popFilter = function () { +WebGLFilterManager.prototype.popFilter = function () +{ var gl = this.renderer.gl; var filterBlock = this.filterStack.pop(); @@ -163,7 +176,8 @@ var projection = this.renderer.projection; var offset = this.renderer.offset; - if (filterBlock.filterPasses.length > 1) { + if (filterBlock.filterPasses.length > 1) + { gl.viewport(0, 0, filterArea.width, filterArea.height); gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); @@ -193,7 +207,8 @@ var inputTexture = texture; var outputTexture = this.texturePool.pop(); - if (!outputTexture) { + if (!outputTexture) + { outputTexture = new FilterTexture(this.renderer.gl, this.width, this.height); } outputTexture.resize(this.width, this.height); @@ -204,7 +219,8 @@ gl.disable(gl.BLEND); - for (var i = 0; i < filterBlock.filterPasses.length-1; i++) { + for (var i = 0; i < filterBlock.filterPasses.length-1; i++) + { var filterPass = filterBlock.filterPasses[i]; gl.bindFramebuffer(gl.FRAMEBUFFER, outputTexture.frameBuffer ); @@ -243,10 +259,12 @@ var buffer = this.buffer; // time to render the filters texture to the previous scene - if (this.filterStack.length === 0) { + if (this.filterStack.length === 0) + { gl.colorMask(true, true, true, true);//this.transparent); } - else { + else + { var currentFilter = this.filterStack[this.filterStack.length-1]; filterArea = currentFilter._filterArea; @@ -332,13 +350,15 @@ * @param width {number} the horizontal range of the filter * @param height {number} the vertical range of the filter */ -WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) { +WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) +{ // use program var gl = this.renderer.gl; var shader = filter.shaders[gl.id]; - if (!shader) { + if (!shader) + { shader = new Shader(gl); shader.fragmentSrc = filter.fragmentSrc; @@ -356,7 +376,8 @@ gl.uniform2f(shader.projectionVector, width/2, -height/2); gl.uniform2f(shader.offsetVector, 0,0); - if (filter.uniforms.dimensions) { + 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]; @@ -386,7 +407,8 @@ * Initialises the shader buffers. * */ -WebGLFilterManager.prototype.initShaderBuffers = function () { +WebGLFilterManager.prototype.initShaderBuffers = function () +{ var gl = this.renderer.gl; // create some buffers @@ -432,7 +454,8 @@ * Destroys the filter and removes it from the filter stack. * */ -WebGLFilterManager.prototype.destroy = function () { +WebGLFilterManager.prototype.destroy = function () +{ var gl = this.renderer.gl; this.filterStack = null; @@ -441,7 +464,8 @@ this.offsetY = 0; // destroy textures - for (var i = 0; i < this.texturePool.length; i++) { + for (var i = 0; i < this.texturePool.length; i++) + { this.texturePool[i].destroy(); } diff --git a/src/core/renderers/webgl/managers/WebGLManager.js b/src/core/renderers/webgl/managers/WebGLManager.js index 9d47b5c..c30cd51 100644 --- a/src/core/renderers/webgl/managers/WebGLManager.js +++ b/src/core/renderers/webgl/managers/WebGLManager.js @@ -3,7 +3,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLManager(renderer) { +function WebGLManager(renderer) +{ /** * The renderer this manager works for. * @@ -15,6 +16,7 @@ WebGLManager.prototype.constructor = WebGLManager; module.exports = WebGLManager; -WebGLManager.prototype.destroy = function () { +WebGLManager.prototype.destroy = function () +{ this.renderer = null; }; diff --git a/src/core/renderers/webgl/managers/WebGLMaskManager.js b/src/core/renderers/webgl/managers/WebGLMaskManager.js index 2f90b64..e568812 100644 --- a/src/core/renderers/webgl/managers/WebGLMaskManager.js +++ b/src/core/renderers/webgl/managers/WebGLMaskManager.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLMaskManager(renderer) { +function WebGLMaskManager(renderer) +{ WebGLManager.call(this, renderer); } @@ -19,12 +20,15 @@ * * @param maskData {any[]} */ -WebGLMaskManager.prototype.pushMask = function (maskData) { - if (maskData.dirty) { +WebGLMaskManager.prototype.pushMask = function (maskData) +{ + if (maskData.dirty) + { WebGLGraphics.updateGraphics(maskData, this.renderer.gl); } - if (!maskData._webGL[this.renderer.gl.id].data.length) { + if (!maskData._webGL[this.renderer.gl.id].data.length) + { return; } @@ -36,6 +40,7 @@ * * @param maskData {any[]} */ -WebGLMaskManager.prototype.popMask = function (maskData) { +WebGLMaskManager.prototype.popMask = function (maskData) +{ this.renderer.stencilManager.popStencil(maskData, maskData._webGL[this.renderer.gl.id].data[0], this.renderer); }; diff --git a/src/core/renderers/webgl/managers/WebGLShaderManager.js b/src/core/renderers/webgl/managers/WebGLShaderManager.js index fef071c..90c6477 100644 --- a/src/core/renderers/webgl/managers/WebGLShaderManager.js +++ b/src/core/renderers/webgl/managers/WebGLShaderManager.js @@ -10,7 +10,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLShaderManager(renderer) { +function WebGLShaderManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -28,7 +29,8 @@ */ this.tempAttribState = []; - for (var i = 0; i < this.maxAttibs; i++) { + for (var i = 0; i < this.maxAttibs; i++) + { this.attribState[i] = false; } @@ -66,7 +68,8 @@ // listen for context and update necessary shaders var self = this; - this.renderer.on('context', function (event) { + this.renderer.on('context', function (event) + { var gl = event.data; // this shader is used for rendering primitives @@ -97,29 +100,36 @@ * * @param attribs {Array} attribs */ -WebGLShaderManager.prototype.setAttribs = function (attribs) { +WebGLShaderManager.prototype.setAttribs = function (attribs) +{ // reset temp state var i; - for (i = 0; i < this.tempAttribState.length; i++) { + for (i = 0; i < this.tempAttribState.length; i++) + { this.tempAttribState[i] = false; } // set the new attribs - for (var a in attribs) { + for (var a in attribs) + { this.tempAttribState[attribs[a]] = true; } var gl = this.renderer.gl; - for (i = 0; i < this.attribState.length; i++) { - if (this.attribState[i] !== this.tempAttribState[i]) { + for (i = 0; i < this.attribState.length; i++) + { + if (this.attribState[i] !== this.tempAttribState[i]) + { this.attribState[i] = this.tempAttribState[i]; - if (this.attribState[i]) { + if (this.attribState[i]) + { gl.enableVertexAttribArray(i); } - else { + else + { gl.disableVertexAttribArray(i); } } @@ -131,8 +141,10 @@ * * @param shader {Any} */ -WebGLShaderManager.prototype.setShader = function (shader) { - if (this._currentId === shader.uuid) { +WebGLShaderManager.prototype.setShader = function (shader) +{ + if (this._currentId === shader.uuid) + { return false; } @@ -150,7 +162,8 @@ * Destroys this object. * */ -WebGLShaderManager.prototype.destroy = function () { +WebGLShaderManager.prototype.destroy = function () +{ this.attribState = null; this.tempAttribState = null; diff --git a/src/core/renderers/webgl/managers/WebGLStencilManager.js b/src/core/renderers/webgl/managers/WebGLStencilManager.js index 9ec6398..4cb0134 100644 --- a/src/core/renderers/webgl/managers/WebGLStencilManager.js +++ b/src/core/renderers/webgl/managers/WebGLStencilManager.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLStencilManager(renderer) { +function WebGLStencilManager(renderer) +{ WebGLManager.call(this, renderer); this.stencilStack = []; @@ -24,12 +25,14 @@ * @param graphics {Graphics} * @param webGLData {any[]} */ -WebGLStencilManager.prototype.pushStencil = function (graphics, webGLData) { +WebGLStencilManager.prototype.pushStencil = function (graphics, webGLData) +{ var gl = this.renderer.gl; this.bindGraphics(graphics, webGLData, this.renderer); - if (this.stencilStack.length === 0) { + if (this.stencilStack.length === 0) + { gl.enable(gl.STENCIL_TEST); gl.clear(gl.STENCIL_BUFFER_BIT); this.reverse = true; @@ -47,14 +50,17 @@ // draw the triangle strip! - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } @@ -62,31 +68,38 @@ // draw a quad to increment.. gl.drawElements(gl.TRIANGLE_FAN, 4, gl.UNSIGNED_SHORT, ( webGLData.indices.length - 4 ) * 2 ); - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); } this.reverse = !this.reverse; } - else { - if (!this.reverse) { + else + { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } - else { + 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) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); } } @@ -103,7 +116,8 @@ * @param graphics {Graphics} * @param webGLData {Array} */ -WebGLStencilManager.prototype.bindGraphics = function (graphics, webGLData) { +WebGLStencilManager.prototype.bindGraphics = function (graphics, webGLData) +{ //if (this._currentGraphics === graphics)return; this._currentGraphics = graphics; @@ -114,7 +128,8 @@ offset = this.renderer.offset, shader;// = this.renderer.shaderManager.primitiveShader; - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { shader = this.renderer.shaderManager.complexPrimitiveShader; this.renderer.shaderManager.setShader(shader); @@ -141,7 +156,8 @@ // set the index buffer! gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, webGLData.indexBuffer); } - else { + else + { //this.renderer.shaderManager.activatePrimitiveShader(); shader = this.renderer.shaderManager.primitiveShader; this.renderer.shaderManager.setShader( shader ); @@ -154,7 +170,7 @@ gl.uniform2f(shader.uniforms.offsetVector._location, -offset.x, -offset.y); gl.uniform3fv(shader.uniforms.tint._location, utils.hex2rgb(graphics.tint)); - + gl.uniform1f(shader.uniforms.alpha._location, graphics.worldAlpha); @@ -172,19 +188,22 @@ * @param graphics {Graphics} * @param webGLData {Array} */ -WebGLStencilManager.prototype.popStencil = function (graphics, webGLData) { +WebGLStencilManager.prototype.popStencil = function (graphics, webGLData) +{ var gl = this.renderer.gl; this.stencilStack.pop(); this.count--; - if (this.stencilStack.length === 0) { + if (this.stencilStack.length === 0) + { // the stack is empty! gl.disable(gl.STENCIL_TEST); } - else { + else + { var level = this.count; @@ -192,14 +211,17 @@ gl.colorMask(false, false, false, false); - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { this.reverse = !this.reverse; - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } @@ -213,31 +235,38 @@ // draw the triangle strip! gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); - if (!this.reverse) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); } } - else { + else + { // console.log("<<>>") - if (!this.reverse) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } - else { + 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) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); } } @@ -253,7 +282,8 @@ * Destroys the mask stack. * */ -WebGLStencilManager.prototype.destroy = function () { +WebGLStencilManager.prototype.destroy = function () +{ this.renderer = null; this.stencilStack = null; }; diff --git a/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js b/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js index 913ba5e..1ea7d19 100644 --- a/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js +++ b/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function ComplexPrimitiveShader(gl) { +function ComplexPrimitiveShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -24,7 +25,8 @@ 'uniform float flipY;', 'varying vec4 vColor;', - 'void main(void) {', + '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);', @@ -37,7 +39,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = vColor;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/FastShader.js b/src/core/renderers/webgl/shaders/FastShader.js index bd2e29a..2e5e060 100644 --- a/src/core/renderers/webgl/shaders/FastShader.js +++ b/src/core/renderers/webgl/shaders/FastShader.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function FastShader(gl) { +function FastShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -28,7 +29,8 @@ 'const vec2 center = vec2(-1.0, 1.0);', - 'void main(void) {', + 'void main(void) + {', ' vec2 v;', ' vec2 sv = aVertexPosition * aScale;', ' v.x = (sv.x) * cos(aRotation) - (sv.y) * sin(aRotation);', @@ -49,7 +51,8 @@ 'uniform sampler2D uSampler;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/PrimitiveShader.js b/src/core/renderers/webgl/shaders/PrimitiveShader.js index 6f25409..a25f54f 100644 --- a/src/core/renderers/webgl/shaders/PrimitiveShader.js +++ b/src/core/renderers/webgl/shaders/PrimitiveShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function PrimitiveShader(gl) { +function PrimitiveShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -23,7 +24,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + '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);', @@ -36,7 +38,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = vColor;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/Shader.js b/src/core/renderers/webgl/shaders/Shader.js index f8964f5..fd75ef5 100644 --- a/src/core/renderers/webgl/shaders/Shader.js +++ b/src/core/renderers/webgl/shaders/Shader.js @@ -6,7 +6,8 @@ * @param [fragmentSrc] {string} The source of the fragment shader. * @param [vertexSrc] {string} The source of the vertex shader. */ -function Shader(gl, vertexSrc, fragmentSrc, customUniforms, customAttributes) { +function Shader(gl, vertexSrc, fragmentSrc, customUniforms, customAttributes) +{ /** * @member {number} * @readonly @@ -33,7 +34,8 @@ dimensions: { type: '4f', value: new Float32Array(4) } }; - for (var u in customUniforms) { + for (var u in customUniforms) + { this.uniforms[u] = customUniforms[u]; } @@ -43,7 +45,8 @@ aColor: 0 }; - for (var a in customAttributes) { + for (var a in customAttributes) + { this.attributes[a] = customAttributes[a]; } @@ -66,7 +69,8 @@ 'const vec2 center = vec2(-1.0, 1.0);', - 'void main(void) {', + 'void main(void) + {', ' gl_Position = vec4( ((aVertexPosition + offsetVector) / projectionVector) + center , 0.0, 1.0);', ' vTextureCoord = aTextureCoord;', ' vColor = vec4(aColor.rgb * aColor.a, aColor.a);', @@ -85,7 +89,8 @@ 'uniform sampler2D uSampler;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;', '}' ].join('\n'); @@ -96,7 +101,8 @@ Shader.prototype.constructor = Shader; module.exports = Shader; -Shader.prototype.init = function () { +Shader.prototype.init = function () +{ this.compile(); this.gl.useProgram(this.program); @@ -105,14 +111,18 @@ this.cacheAttributeLocations(Object.keys(this.attributes)); }; -Shader.prototype.cacheUniformLocations = function (keys) { - for (var i = 0; i < keys.length; ++i) { +Shader.prototype.cacheUniformLocations = function (keys) +{ + for (var i = 0; i < keys.length; ++i) + { this.uniforms[keys[i]]._location = this.gl.getUniformLocation(this.program, keys[i]); } }; -Shader.prototype.cacheAttributeLocations = function (keys) { - for (var i = 0; i < keys.length; ++i) { +Shader.prototype.cacheAttributeLocations = function (keys) +{ + for (var i = 0; i < keys.length; ++i) + { this.attributes[keys[i]] = this.gl.getAttribLocation(this.program, keys[i]); } @@ -124,14 +134,16 @@ // 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.attributes.aColor === -1) { + // if (this.attributes.aColor === -1) + { // this.attributes.aColor = 2; // } // End worst hack eva // }; -Shader.prototype.compile = function () { +Shader.prototype.compile = function () +{ var gl = this.gl; var glVertShader = this._glCompile(gl.VERTEX_SHADER, this.vertexSrc); @@ -144,13 +156,15 @@ gl.linkProgram(program); // if linking fails, then log and cleanup - if (!gl.getProgramParameter(program, gl.LINK_STATUS)) { + if (!gl.getProgramParameter(program, gl.LINK_STATUS)) + { window.console.error('Pixi.js Error: Could not initialize shader.'); window.console.error('gl.VALIDATE_STATUS', gl.getProgramParameter(program, gl.VALIDATE_STATUS)); window.console.error('gl.getError()', gl.getError()); // if there is a program info log, log it - if (gl.getProgramInfoLog(program) !== '') { + if (gl.getProgramInfoLog(program) !== '') + { window.console.warn('Pixi.js Warning: gl.getProgramInfoLog()', gl.getProgramInfoLog(program)); } @@ -165,18 +179,21 @@ return (this.program = program); }; -Shader.prototype.syncUniforms = function () { +Shader.prototype.syncUniforms = function () +{ var gl = this.gl; this.textureCount = 1; - for (var key in this.uniforms) { + for (var key in this.uniforms) + { var uniform = this.uniforms[key], location = uniform._location, value = uniform.value, i, il; - switch (uniform.type) { + switch (uniform.type) + { // single int value case 'i': case '1i': @@ -282,7 +299,8 @@ // a Color Value case 'c': - if (typeof value === 'number') { + if (typeof value === 'number') + { value = utils.hex2rgb(value); } @@ -311,11 +329,13 @@ // array of 2D Point objects case 'v2v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(2 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 2] = value[i].x; uniform._array[i * 2 + 1] = value[i].y; } @@ -325,11 +345,13 @@ // array of 3D Point objects case 'v3v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(3 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 3] = value[i].x; uniform._array[i * 3 + 1] = value[i].y; uniform._array[i * 3 + 2] = value[i].z; @@ -341,11 +363,13 @@ // array of 4D Point objects case 'v4v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(4 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 4] = value[i].x; uniform._array[i * 4 + 1] = value[i].y; uniform._array[i * 4 + 2] = value[i].z; @@ -359,7 +383,8 @@ // PIXI.Texture case 't': case 'sampler2D': - if (!uniform.value || !uniform.value.baseTexture || !uniform.value.baseTexture.hasLoaded) { + if (!uniform.value || !uniform.value.baseTexture || !uniform.value.baseTexture.hasLoaded) + { break; } @@ -376,7 +401,8 @@ this.textureCount++; // initialize the texture if we haven't yet - if (!uniform._init) { + if (!uniform._init) + { this.initSampler2D(uniform); uniform._init = true; @@ -394,11 +420,13 @@ * Initialises a Sampler2D uniform (which may only be available later on after initUniforms once the texture has loaded) * */ -Shader.prototype.initSampler2D = function (uniform) { +Shader.prototype.initSampler2D = function (uniform) +{ var gl = this.gl; // Extended texture data - if (uniform.textureData) { + if (uniform.textureData) + { var data = uniform.textureData; // GLTexture = mag linear, min linear_mipmap_linear, wrap repeat + gl.generateMipmap(gl.TEXTURE_2D); @@ -417,14 +445,16 @@ var wrapT = (data.wrapT) ? data.wrapT : gl.CLAMP_TO_EDGE; var format = (data.luminance) ? gl.LUMINANCE : gl.RGBA; - if (data.repeat) { + if (data.repeat) + { wrapS = gl.REPEAT; wrapT = gl.REPEAT; } gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, !!data.flipY); - if (data.width) { + if (data.width) + { var width = (data.width) ? data.width : 512; var height = (data.height) ? data.height : 2; var border = (data.border) ? data.border : 0; @@ -432,7 +462,8 @@ // 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 { + 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); } @@ -448,7 +479,8 @@ * Destroys the shader. * */ -Shader.prototype.destroy = function () { +Shader.prototype.destroy = function () +{ this.gl.deleteProgram(this.program); this.gl = null; @@ -459,13 +491,15 @@ this.fragmentSrc = null; }; -Shader.prototype._glCompile = function (type, src) { +Shader.prototype._glCompile = function (type, src) +{ var shader = this.gl.createShader(type); this.gl.shaderSource(shader, src); this.gl.compileShader(shader); - if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) { + if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) + { window.console.log(this.gl.getShaderInfoLog(shader)); return null; } diff --git a/src/core/renderers/webgl/shaders/StripShader.js b/src/core/renderers/webgl/shaders/StripShader.js index 193f6e1..a7abcc6 100644 --- a/src/core/renderers/webgl/shaders/StripShader.js +++ b/src/core/renderers/webgl/shaders/StripShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function StripShader(gl) { +function StripShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -20,7 +21,8 @@ 'varying vec2 vTextureCoord;', - 'void main(void) {', + '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);', @@ -36,7 +38,8 @@ 'varying vec2 vTextureCoord;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vec2(vTextureCoord.x, vTextureCoord.y)) * alpha;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/utils/FilterTexture.js b/src/core/renderers/webgl/utils/FilterTexture.js index d2c8423..4433d44 100644 --- a/src/core/renderers/webgl/utils/FilterTexture.js +++ b/src/core/renderers/webgl/utils/FilterTexture.js @@ -8,7 +8,8 @@ * @param height {number} the vertical range of the filter * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values */ -function FilterTexture(gl, width, height, scaleMode) { +function FilterTexture(gl, width, height, scaleMode) +{ /** * @member {WebGLContext} */ @@ -59,7 +60,8 @@ * Clears the filter texture. * */ -FilterTexture.prototype.clear = function () { +FilterTexture.prototype.clear = function () +{ var gl = this.gl; gl.clearColor(0,0,0, 0); @@ -72,8 +74,10 @@ * @param width {number} the new width of the texture * @param height {number} the new height of the texture */ -FilterTexture.prototype.resize = function (width, height) { - if (this.width === width && this.height === height) { +FilterTexture.prototype.resize = function (width, height) +{ + if (this.width === width && this.height === height) + { return; } @@ -96,7 +100,8 @@ * Destroys the filter texture. * */ -FilterTexture.prototype.destroy = function () { +FilterTexture.prototype.destroy = function () +{ var gl = this.gl; gl.deleteFramebuffer( this.frameBuffer ); gl.deleteTexture( this.texture ); diff --git a/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js b/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js index c4721e9..a63f4d7 100644 --- a/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js +++ b/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js @@ -14,7 +14,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this sprite batch works for. */ -function WebGLFastSpriteBatch(renderer) { +function WebGLFastSpriteBatch(renderer) +{ /** * The renderer instance this sprite batch operates on. * @@ -91,7 +92,8 @@ */ this.lastIndexCount = 0; - for (var i=0, j=0; i < numIndices; i += 6, j += 4) { + 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; @@ -144,7 +146,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.setupContext(); }); } @@ -157,7 +160,8 @@ * * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLFastSpriteBatch.prototype.setupContext = function () { +WebGLFastSpriteBatch.prototype.setupContext = function () +{ var gl = this.renderer.gl; // create a couple of buffers @@ -177,7 +181,8 @@ /** * @param spriteBatch {SpriteBatch} The SpriteBatch container to prepare for. */ -WebGLFastSpriteBatch.prototype.begin = function (spriteBatch) { +WebGLFastSpriteBatch.prototype.begin = function (spriteBatch) +{ this.shader = this.renderer.shaderManager.fastShader; this.matrix = spriteBatch.worldTransform.toArray(true); @@ -187,33 +192,38 @@ /** */ -WebGLFastSpriteBatch.prototype.end = function () { +WebGLFastSpriteBatch.prototype.end = function () +{ this.flush(); }; /** * @param spriteBatch {SpriteBatch} The SpriteBatch container to render. */ -WebGLFastSpriteBatch.prototype.render = function (spriteBatch) { +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) { + if (!sprite.texture._uvs) + { return; } this.currentBaseTexture = sprite.texture.baseTexture; // check blend mode - if (sprite.blendMode !== this.renderer.blendModeManager.currentBlendMode) { + if (sprite.blendMode !== this.renderer.blendModeManager.currentBlendMode) + { this.flush(); this.renderer.blendModeManager.setBlendMode(sprite.blendMode); } - for (var i=0,j= children.length; i= this.size) { + if (this.currentBatchSize >= this.size) + { this.flush(); } }; @@ -362,29 +379,35 @@ /** * */ -WebGLFastSpriteBatch.prototype.flush = function () { +WebGLFastSpriteBatch.prototype.flush = function () +{ // If the batch is length 0 then return as there is nothing to draw - if (this.currentBatchSize === 0) { + if (this.currentBatchSize === 0) + { return; } var gl = this.renderer.gl; // bind the current texture - if (!this.currentBaseTexture._glTextures[gl.id]) { + if (!this.currentBaseTexture._glTextures[gl.id]) + { this.renderer.updateTexture(this.currentBaseTexture, gl); } //TODO-SHOUD THIS BE ELSE??!?!?! - else { + else + { gl.bindTexture(gl.TEXTURE_2D, this.currentBaseTexture._glTextures[gl.id]); } // upload the verts to the buffer - if (this.currentBatchSize > ( this.size * 0.5 ) ) { + if (this.currentBatchSize > ( this.size * 0.5 ) ) + { gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); } - else { + else + { var view = this.vertices.subarray(0, this.currentBatchSize * this.vertByteSize); gl.bufferSubData(gl.ARRAY_BUFFER, 0, view); @@ -405,14 +428,16 @@ * Ends the batch and flushes * */ -WebGLFastSpriteBatch.prototype.stop = function () { +WebGLFastSpriteBatch.prototype.stop = function () +{ this.flush(); }; /** * */ -WebGLFastSpriteBatch.prototype.start = function () { +WebGLFastSpriteBatch.prototype.start = function () +{ var gl = this.renderer.gl; // bind the main texture diff --git a/src/core/renderers/webgl/utils/WebGLGraphics.js b/src/core/renderers/webgl/utils/WebGLGraphics.js index 55f4911..ab8f46e 100644 --- a/src/core/renderers/webgl/utils/WebGLGraphics.js +++ b/src/core/renderers/webgl/utils/WebGLGraphics.js @@ -19,7 +19,8 @@ * @param graphics {Graphics} * @param renderer {WebGLRenderer} */ -WebGLGraphics.renderGraphics = function (graphics, renderer) {//projection, offset) { +WebGLGraphics.renderGraphics = function (graphics, renderer) {//projection, offset) +{ var gl = renderer.gl; var projection = renderer.projection, @@ -27,7 +28,8 @@ shader = renderer.shaderManager.primitiveShader, webGLData; - if (graphics.dirty) { + if (graphics.dirty) + { WebGLGraphics.updateGraphics(graphics, gl); } @@ -35,8 +37,10 @@ // This could be speeded up for sure! - for (var i = 0; i < webGL.data.length; i++) { - if (webGL.data[i].mode === 1) { + for (var i = 0; i < webGL.data.length; i++) + { + if (webGL.data[i].mode === 1) + { webGLData = webGL.data[i]; renderer.stencilManager.pushStencil(graphics, webGLData, renderer); @@ -46,7 +50,8 @@ renderer.stencilManager.popStencil(graphics, webGLData, renderer); } - else { + else + { webGLData = webGL.data[i]; @@ -84,12 +89,14 @@ * @param graphicsData {Graphics} The graphics object to update * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLGraphics.updateGraphics = function (graphics, gl) { +WebGLGraphics.updateGraphics = function (graphics, gl) +{ // get the contexts graphics object var webGL = graphics._webGL[gl.id]; // if the graphics object does not exist in the webGL context time to create it! - if (!webGL) { + if (!webGL) + { webGL = graphics._webGL[gl.id] = {lastIndex:0, data:[], gl:gl}; } @@ -99,11 +106,13 @@ var i; // if the user cleared the graphics object we will need to clear every object - if (graphics.clearDirty) { + if (graphics.clearDirty) + { graphics.clearDirty = false; // lop through and return all the webGLDatas to the object pool so than can be reused later on - for (i = 0; i < webGL.data.length; i++) { + for (i = 0; i < webGL.data.length; i++) + { var graphicsData = webGL.data[i]; graphicsData.reset(); WebGLGraphics.graphicsDataPool.push( graphicsData ); @@ -119,58 +128,72 @@ // loop through the graphics datas and construct each one.. // if the object is a complex fill then the new stencil buffer technique will be used // other wise graphics objects will be pushed into a batch.. - for (i = webGL.lastIndex; i < graphics.graphicsData.length; i++) { + for (i = webGL.lastIndex; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { // need to add the points the the graphics object.. data.points = data.shape.points.slice(); - if (data.shape.closed) { + if (data.shape.closed) + { // close the poly if the value is true! - if (data.points[0] !== data.points[data.points.length-2] || data.points[1] !== data.points[data.points.length-1]) { + if (data.points[0] !== data.points[data.points.length-2] || data.points[1] !== data.points[data.points.length-1]) + { data.points.push(data.points[0], data.points[1]); } } // MAKE SURE WE HAVE THE CORRECT TYPE.. - if (data.fill) { - if (data.points.length >= 6) { - if (data.points.length < 6 * 2) { + if (data.fill) + { + if (data.points.length >= 6) + { + if (data.points.length < 6 * 2) + { webGLData = WebGLGraphics.switchMode(webGL, 0); var canDrawUsingSimple = WebGLGraphics.buildPoly(data, webGLData); // console.log(canDrawUsingSimple); - if (!canDrawUsingSimple) { + if (!canDrawUsingSimple) + { // console.log("<>>>") webGLData = WebGLGraphics.switchMode(webGL, 1); WebGLGraphics.buildComplexPoly(data, webGLData); } } - else { + else + { webGLData = WebGLGraphics.switchMode(webGL, 1); WebGLGraphics.buildComplexPoly(data, webGLData); } } } - if (data.lineWidth > 0) { + if (data.lineWidth > 0) + { webGLData = WebGLGraphics.switchMode(webGL, 0); WebGLGraphics.buildLine(data, webGLData); } } - else { + else + { webGLData = WebGLGraphics.switchMode(webGL, 0); - if (data.type === CONST.SHAPES.RECT) { + if (data.type === CONST.SHAPES.RECT) + { WebGLGraphics.buildRectangle(data, webGLData); } - else if (data.type === CONST.SHAPES.CIRC || data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.CIRC || data.type === CONST.SHAPES.ELIP) + { WebGLGraphics.buildCircle(data, webGLData); } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { WebGLGraphics.buildRoundedRectangle(data, webGLData); } } @@ -179,10 +202,12 @@ } // upload all the dirty data... - for (i = 0; i < webGL.data.length; i++) { + for (i = 0; i < webGL.data.length; i++) + { webGLData = webGL.data[i]; - if (webGLData.dirty) { + if (webGLData.dirty) + { webGLData.upload(); } } @@ -194,18 +219,22 @@ * @param webGL {WebGLContext} * @param type {number} */ -WebGLGraphics.switchMode = function (webGL, type) { +WebGLGraphics.switchMode = function (webGL, type) +{ var webGLData; - if (!webGL.data.length) { + if (!webGL.data.length) + { webGLData = WebGLGraphics.graphicsDataPool.pop() || new WebGLGraphicsData(webGL.gl); webGLData.mode = type; webGL.data.push(webGLData); } - else { + else + { webGLData = webGL.data[webGL.data.length-1]; - if (webGLData.mode !== type || type === 1) { + if (webGLData.mode !== type || type === 1) + { webGLData = WebGLGraphics.graphicsDataPool.pop() || new WebGLGraphicsData(webGL.gl); webGLData.mode = type; webGL.data.push(webGLData); @@ -225,7 +254,8 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildRectangle = function (graphicsData, webGLData) { +WebGLGraphics.buildRectangle = function (graphicsData, webGLData) +{ // --- // // need to convert points to a nice regular data // @@ -235,7 +265,8 @@ var width = rectData.width; var height = rectData.height; - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -265,7 +296,8 @@ indices.push(vertPos, vertPos, vertPos+1, vertPos+2, vertPos+3, vertPos+3); } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = [x, y, @@ -289,7 +321,8 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildRoundedRectangle = function (graphicsData, webGLData) { +WebGLGraphics.buildRoundedRectangle = function (graphicsData, webGLData) +{ var rrectData = graphicsData.shape; var x = rrectData.x; var y = rrectData.y; @@ -305,7 +338,8 @@ recPoints = recPoints.concat(WebGLGraphics.quadraticBezierCurve(x + width, y + radius, x + width, y, x + width - radius, y)); recPoints = recPoints.concat(WebGLGraphics.quadraticBezierCurve(x + radius, y, x, y, x, y + radius)); - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -323,7 +357,8 @@ // var i = 0; - for (i = 0; i < triangles.length; i+=3) { + for (i = 0; i < triangles.length; i+=3) + { indices.push(triangles[i] + vecPos); indices.push(triangles[i] + vecPos); indices.push(triangles[i+1] + vecPos); @@ -332,12 +367,14 @@ } - for (i = 0; i < recPoints.length; i++) { + for (i = 0; i < recPoints.length; i++) + { verts.push(recPoints[i], recPoints[++i], r, g, b, alpha); } } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = recPoints; @@ -362,7 +399,8 @@ * @param toY {number} Destination point y * @return {number[]} */ -WebGLGraphics.quadraticBezierCurve = function (fromX, fromY, cpX, cpY, toX, toY) { +WebGLGraphics.quadraticBezierCurve = function (fromX, fromY, cpX, cpY, toX, toY) +{ var xa, ya, @@ -373,14 +411,16 @@ n = 20, points = []; - function getPt(n1 , n2, perc) { + function getPt(n1 , n2, perc) + { var diff = n2 - n1; return n1 + ( diff * perc ); } var j = 0; - for (var i = 0; i <= n; i++ ) { + for (var i = 0; i <= n; i++ ) + { j = i / n; // The Green Line @@ -406,7 +446,8 @@ * @param graphicsData {Graphics} The graphics object to draw * @param webGLData {object} */ -WebGLGraphics.buildCircle = function (graphicsData, webGLData) { +WebGLGraphics.buildCircle = function (graphicsData, webGLData) +{ // need to convert points to a nice regular data var circleData = graphicsData.shape; var x = circleData.x; @@ -415,11 +456,13 @@ var height; // TODO - bit hacky?? - if (graphicsData.type === CONST.SHAPES.CIRC) { + if (graphicsData.type === CONST.SHAPES.CIRC) + { width = circleData.radius; height = circleData.radius; } - else { + else + { width = circleData.width; height = circleData.height; } @@ -429,7 +472,8 @@ var i = 0; - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -444,7 +488,8 @@ indices.push(vecPos); - for (i = 0; i < totalSegs + 1 ; i++) { + for (i = 0; i < totalSegs + 1 ; i++) + { verts.push(x,y, r, g, b, alpha); verts.push(x + Math.sin(seg * i) * width, @@ -457,12 +502,14 @@ indices.push(vecPos-1); } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = []; - for (i = 0; i < totalSegs + 1; i++) { + for (i = 0; i < totalSegs + 1; i++) + { graphicsData.points.push(x + Math.sin(seg * i) * width, y + Math.cos(seg * i) * height); } @@ -481,18 +528,22 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildLine = function (graphicsData, webGLData) { +WebGLGraphics.buildLine = function (graphicsData, webGLData) +{ // TODO OPTIMISE! var i = 0; var points = graphicsData.points; - if (points.length === 0) { + if (points.length === 0) + { return; } // if the line width is an odd number add 0.5 to align to a whole pixel - if (graphicsData.lineWidth%2) { - for (i = 0; i < points.length; i++) { + if (graphicsData.lineWidth%2) + { + for (i = 0; i < points.length; i++) + { points[i] += 0.5; } } @@ -502,7 +553,8 @@ var lastPoint = new math.Point(points[points.length - 2], points[points.length - 1]); // if the first point is the last point - gonna have issues :) - if (firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) { + if (firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) + { // need to clone as we are going to slightly modify the shape.. points = points.slice(); @@ -562,7 +614,8 @@ verts.push(p1x + perpx , p1y + perpy, r, g, b, alpha); - for (i = 1; i < length-1; i++) { + for (i = 1; i < length-1; i++) + { p1x = points[(i-1)*2]; p1y = points[(i-1)*2 + 1]; @@ -599,7 +652,8 @@ denom = a1*b2 - a2*b1; - if (Math.abs(denom) < 0.1 ) { + if (Math.abs(denom) < 0.1 ) + { denom+=10.1; verts.push(p2x - perpx , p2y - perpy, @@ -618,7 +672,8 @@ pdist = (px -p2x) * (px -p2x) + (py -p2y) + (py -p2y); - if (pdist > 140 * 140) { + if (pdist > 140 * 140) + { perp3x = perpx - perp2x; perp3y = perpy - perp2y; @@ -639,7 +694,8 @@ indexCount++; } - else { + else + { verts.push(px , py); verts.push(r, g, b, alpha); @@ -672,7 +728,8 @@ indices.push(indexStart); - for (i = 0; i < indexCount; i++) { + for (i = 0; i < indexCount; i++) + { indices.push(indexStart++); } @@ -687,11 +744,13 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildComplexPoly = function (graphicsData, webGLData) { +WebGLGraphics.buildComplexPoly = function (graphicsData, webGLData) +{ //TODO - no need to copy this as it gets turned into a FLoat32Array anyways.. var points = graphicsData.points.slice(); - if (points.length < 6) { + if (points.length < 6) + { return; } @@ -711,7 +770,8 @@ var x,y; // get size.. - for (var i = 0; i < points.length; i+=2) { + for (var i = 0; i < points.length; i+=2) + { x = points[i]; y = points[i+1]; @@ -732,7 +792,8 @@ //TODO - this aint needed! var length = points.length / 2; - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { indices.push( i ); } @@ -746,10 +807,12 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildPoly = function (graphicsData, webGLData) { +WebGLGraphics.buildPoly = function (graphicsData, webGLData) +{ var points = graphicsData.points; - if (points.length < 6) { + if (points.length < 6) + { return; } // get first and last point.. figure out the middle! @@ -767,7 +830,8 @@ var triangles = utils.PolyK.Triangulate(points); - if (!triangles) { + if (!triangles) + { return false; } @@ -775,7 +839,8 @@ var i = 0; - for (i = 0; i < triangles.length; i+=3) { + for (i = 0; i < triangles.length; i+=3) + { indices.push(triangles[i] + vertPos); indices.push(triangles[i] + vertPos); indices.push(triangles[i+1] + vertPos); @@ -783,7 +848,8 @@ indices.push(triangles[i+2] + vertPos); } - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { verts.push(points[i * 2], points[i * 2 + 1], r, g, b, alpha); } diff --git a/src/core/renderers/webgl/utils/WebGLGraphicsData.js b/src/core/renderers/webgl/utils/WebGLGraphicsData.js index c56d05e..c739ba7 100644 --- a/src/core/renderers/webgl/utils/WebGLGraphicsData.js +++ b/src/core/renderers/webgl/utils/WebGLGraphicsData.js @@ -2,7 +2,8 @@ * @class * @private */ -function WebGLGraphicsData(gl) { +function WebGLGraphicsData(gl) +{ this.gl = gl; //TODO does this need to be split before uploding?? @@ -22,7 +23,8 @@ /** * */ -WebGLGraphicsData.prototype.reset = function () { +WebGLGraphicsData.prototype.reset = function () +{ this.points.length = 0; this.indices.length = 0; }; @@ -30,7 +32,8 @@ /** * */ -WebGLGraphicsData.prototype.upload = function () { +WebGLGraphicsData.prototype.upload = function () +{ var gl = this.gl; // this.lastIndex = graphics.graphicsData.length; diff --git a/src/core/renderers/webgl/utils/WebGLSpriteBatch.js b/src/core/renderers/webgl/utils/WebGLSpriteBatch.js index 96eaa52..55befbb 100644 --- a/src/core/renderers/webgl/utils/WebGLSpriteBatch.js +++ b/src/core/renderers/webgl/utils/WebGLSpriteBatch.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this sprite batch works for. */ -function WebGLSpriteBatch(renderer) { +function WebGLSpriteBatch(renderer) +{ /** * * @@ -88,7 +89,8 @@ */ this.lastIndexCount = 0; - for (var i=0, j=0; i < numIndices; i += 6, j += 4) { + 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; @@ -162,7 +164,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.setupContext(); }); } @@ -173,7 +176,8 @@ /** * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLSpriteBatch.prototype.setupContext = function () { +WebGLSpriteBatch.prototype.setupContext = function () +{ var gl = this.renderer.gl; // setup default shader @@ -198,7 +202,8 @@ /** * */ -WebGLSpriteBatch.prototype.begin = function () { +WebGLSpriteBatch.prototype.begin = function () +{ // this.shader = this.renderer.shaderManager.defaultShader; this.start(); @@ -206,19 +211,22 @@ /** */ -WebGLSpriteBatch.prototype.end = function () { +WebGLSpriteBatch.prototype.end = function () +{ this.flush(); }; /** * @param sprite {Sprite} the sprite to render when using this spritebatch */ -WebGLSpriteBatch.prototype.render = function (sprite) { +WebGLSpriteBatch.prototype.render = function (sprite) +{ var texture = sprite.texture; //TODO set blend modes.. // check texture.. - if (this.currentBatchSize >= this.size) { + if (this.currentBatchSize >= this.size) + { this.flush(); this.currentBaseTexture = texture.baseTexture; } @@ -227,7 +235,8 @@ var uvs = texture._uvs; // if the uvs have not updated then no point rendering just yet! - if (!uvs) { + if (!uvs) + { return; } @@ -237,7 +246,8 @@ var w0, w1, h0, h1; - if (texture.trim) { + 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; @@ -248,7 +258,8 @@ h0 = h1 + texture.crop.height; } - else { + else + { w0 = (texture.frame.width ) * (1-aX); w1 = (texture.frame.width ) * -aX; @@ -272,7 +283,8 @@ var colors = this.colors; var positions = this.positions; - if (this.renderer.roundPixels) { + if (this.renderer.roundPixels) + { // xy positions[index] = a * w1 + c * h1 + tx | 0; positions[index+1] = d * h1 + b * w1 + ty | 0; @@ -289,7 +301,8 @@ positions[index+15] = a * w1 + c * h0 + tx | 0; positions[index+16] = d * h0 + b * w1 + ty | 0; } - else { + else + { // xy positions[index] = a * w1 + c * h1 + tx; positions[index+1] = d * h1 + b * w1 + ty; @@ -338,11 +351,13 @@ * * @param sprite {TilingSprite} the tilingSprite to render */ -WebGLSpriteBatch.prototype.renderTilingSprite = function (tilingSprite) { +WebGLSpriteBatch.prototype.renderTilingSprite = function (tilingSprite) +{ var texture = tilingSprite.tilingTexture; // check texture.. - if (this.currentBatchSize >= this.size) { + if (this.currentBatchSize >= this.size) + { //return; this.flush(); this.currentBaseTexture = texture.baseTexture; @@ -351,7 +366,8 @@ // set the textures uvs temporarily // TODO create a separate texture so that we can tile part of a texture - if (!tilingSprite._uvs) { + if (!tilingSprite._uvs) + { tilingSprite._uvs = new TextureUvs(); } @@ -454,16 +470,19 @@ * Renders the content and empties the current batch. * */ -WebGLSpriteBatch.prototype.flush = function () { +WebGLSpriteBatch.prototype.flush = function () +{ // If the batch is length 0 then return as there is nothing to draw - if (this.currentBatchSize === 0) { + if (this.currentBatchSize === 0) + { return; } var gl = this.renderer.gl; var shader; - if (this.dirty) { + if (this.dirty) + { this.dirty = false; // bind the main texture gl.activeTexture(gl.TEXTURE0); @@ -482,10 +501,12 @@ } // upload the verts to the buffer - if (this.currentBatchSize > ( this.size * 0.5 ) ) { + if (this.currentBatchSize > ( this.size * 0.5 ) ) + { gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); } - else { + else + { var view = this.positions.subarray(0, this.currentBatchSize * this.vertByteSize); gl.bufferSubData(gl.ARRAY_BUFFER, 0, view); } @@ -502,7 +523,8 @@ var shaderSwap = false; var sprite; - for (var i = 0, j = this.currentBatchSize; i < j; i++) { + for (var i = 0, j = this.currentBatchSize; i < j; i++) + { sprite = this.sprites[i]; @@ -513,24 +535,28 @@ blendSwap = currentBlendMode !== nextBlendMode; shaderSwap = currentShader !== nextShader; // should I use uuidS??? - if (currentBaseTexture !== nextTexture || blendSwap || shaderSwap) { + if (currentBaseTexture !== nextTexture || blendSwap || shaderSwap) + { this.renderBatch(currentBaseTexture, batchSize, start); start = i; batchSize = 0; currentBaseTexture = nextTexture; - if (blendSwap) { + if (blendSwap) + { currentBlendMode = nextBlendMode; this.renderer.blendModeManager.setBlendMode( currentBlendMode ); } - if (shaderSwap) { + if (shaderSwap) + { currentShader = nextShader; shader = currentShader.shaders ? currentShader.shaders[gl.id] : currentShader; - if (!shader) { + if (!shader) + { shader = new Shader(gl, null, currentShader.fragmentSrc, currentShader.uniforms); currentShader.shaders[gl.id] = shader; } @@ -538,7 +564,8 @@ // set shader function??? this.renderer.shaderManager.setShader(shader); - if (shader.dirty) { + if (shader.dirty) + { shader.syncUniforms(); } @@ -569,17 +596,21 @@ * @param size {number} * @param startIndex {number} */ -WebGLSpriteBatch.prototype.renderBatch = function (texture, size, startIndex) { - if (size === 0) { +WebGLSpriteBatch.prototype.renderBatch = function (texture, size, startIndex) +{ + if (size === 0) + { return; } var gl = this.renderer.gl; - if (!texture._glTextures[gl.id]) { + if (!texture._glTextures[gl.id]) + { this.renderer.updateTexture(texture); } - else { + else + { // bind the current texture gl.bindTexture(gl.TEXTURE_2D, texture._glTextures[gl.id]); } @@ -594,7 +625,8 @@ /** * */ -WebGLSpriteBatch.prototype.stop = function () { +WebGLSpriteBatch.prototype.stop = function () +{ this.flush(); this.dirty = true; }; @@ -602,7 +634,8 @@ /** * */ -WebGLSpriteBatch.prototype.start = function () { +WebGLSpriteBatch.prototype.start = function () +{ this.dirty = true; }; @@ -610,7 +643,8 @@ * Destroys the SpriteBatch. * */ -WebGLSpriteBatch.prototype.destroy = function () { +WebGLSpriteBatch.prototype.destroy = function () +{ this.renderer.gl.deleteBuffer(this.vertexBuffer); this.renderer.gl.deleteBuffer(this.indexBuffer); diff --git a/src/core/textures/BaseTexture.js b/src/core/textures/BaseTexture.js index 2bf77d4..513d358 100644 --- a/src/core/textures/BaseTexture.js +++ b/src/core/textures/BaseTexture.js @@ -10,7 +10,8 @@ * @param source {Image|Canvas} the source object of the texture. * @param [scaleMode=scaleModes.DEFAULT] {number} See {@link scaleModes} for possible values */ -function BaseTexture(source, scaleMode) { +function BaseTexture(source, scaleMode) +{ this.uuid = utils.uuid(); /** @@ -123,7 +124,8 @@ this._needsUpdate = false; // if no source passed don't try to load - if (source) { + if (source) + { this.loadSource(source); } @@ -149,13 +151,16 @@ Object.defineProperties(BaseTexture.prototype, { needsUpdate: { - get: function () { + get: function () + { return this._needsUpdate; }, - set: function (val) { + set: function (val) + { this._needsUpdate = val; - if (val) { + if (val) + { this.emit('update', this); } } @@ -171,9 +176,11 @@ * * The logic state after calling `loadSource` directly or indirectly (eg. `fromImage`, `new BaseTexture`) is: * - * if (texture.hasLoaded) { + * if (texture.hasLoaded) + { * // texture ready for use - * } else if (texture.isLoading) { + * } else if (texture.isLoading) + { * // listen to 'loaded' and/or 'error' events on texture * } else { * // not loading, not going to load UNLESS the source is reloaded @@ -183,12 +190,14 @@ * @protected * @param source {Image|Canvas} the source object of the texture. */ -BaseTexture.prototype.loadSource = function (source) { +BaseTexture.prototype.loadSource = function (source) +{ var wasLoading = this.isLoading; this.hasLoaded = false; this.isLoading = false; - if (wasLoading && this.source) { + if (wasLoading && this.source) + { this.source.onload = null; this.source.onerror = null; } @@ -196,20 +205,24 @@ this.source = source; // Apply source if loaded. Otherwise setup appropriate loading monitors. - if ((this.source.complete || this.source.getContext) && this.source.width && this.source.height) { + if ((this.source.complete || this.source.getContext) && this.source.width && this.source.height) + { this._sourceLoaded(); } - else if(!source.getContext) { + else if(!source.getContext) + { // Image fail / not ready this.isLoading = true; var scope = this; - source.onload = function () { + source.onload = function () + { source.onload = null; source.onerror = null; - if(!scope.isLoading) { + if(!scope.isLoading) + { return; } @@ -219,11 +232,13 @@ scope.emit('loaded', scope); }; - source.onerror = function () { + source.onerror = function () + { source.onload = null; source.onerror = null; - if(!scope.isLoading) { + if(!scope.isLoading) + { return; } @@ -234,24 +249,29 @@ // Per http://www.w3.org/TR/html5/embedded-content-0.html#the-img-element // "The value of `complete` can thus change while a script is executing." // So complete needs to be re-checked after the callbacks have been added.. - if (source.complete) { + if (source.complete) + { this.isLoading = false; // ..and if we're complete now, no need for callbacks source.onload = null; source.onerror = null; - if (source.width && source.height) { + if (source.width && source.height) + { this._sourceLoaded(); // If any previous subscribers possible - if (wasLoading) { + if (wasLoading) + { this.emit('loaded', this); } } - else { + else + { // If any previous subscribers possible - if (wasLoading) { + if (wasLoading) + { this.emit('error', this); } } @@ -265,7 +285,8 @@ * * @private */ -BaseTexture.prototype._sourceLoaded = function () { +BaseTexture.prototype._sourceLoaded = function () +{ this.hasLoaded = true; this.width = this.source.naturalWidth || this.source.width; @@ -278,16 +299,20 @@ * Destroys this base texture * */ -BaseTexture.prototype.destroy = function () { - if (this.imageUrl) { +BaseTexture.prototype.destroy = function () +{ + if (this.imageUrl) + { delete utils.BaseTextureCache[this.imageUrl]; delete utils.TextureCache[this.imageUrl]; this.imageUrl = null; - if (!navigator.isCocoonJS) { + if (!navigator.isCocoonJS) + { this.source.src = ''; } } - else if (this.source && this.source._pixiId) { + else if (this.source && this.source._pixiId) + { delete utils.BaseTextureCache[this.source._pixiId]; } this.source = null; @@ -301,7 +326,8 @@ * memory again. * */ -BaseTexture.prototype.dispose = function () { +BaseTexture.prototype.dispose = function () +{ this.emit('dispose', this); }; @@ -311,7 +337,8 @@ * * @param newSrc {string} the path of the image */ -BaseTexture.prototype.updateSourceImage = function (newSrc) { +BaseTexture.prototype.updateSourceImage = function (newSrc) +{ this.source.src = newSrc; this.loadSource(this.source); }; @@ -326,18 +353,22 @@ * @param [scaleMode=scaleModes.DEFAULT] {number} See {@link scaleModes} for possible values * @return BaseTexture */ -BaseTexture.fromImage = function (imageUrl, crossorigin, scaleMode) { +BaseTexture.fromImage = function (imageUrl, crossorigin, scaleMode) +{ var baseTexture = utils.BaseTextureCache[imageUrl]; - if (crossorigin === undefined && imageUrl.indexOf('data:') !== 0) { + if (crossorigin === undefined && imageUrl.indexOf('data:') !== 0) + { crossorigin = true; } - if (!baseTexture) { + if (!baseTexture) + { // new Image() breaks tex loading in some versions of Chrome. // See https://code.google.com/p/chromium/issues/detail?id=238071 var image = new Image();//document.createElement('img'); - if (crossorigin) { + if (crossorigin) + { image.crossOrigin = ''; } @@ -347,7 +378,8 @@ utils.BaseTextureCache[imageUrl] = baseTexture; // if there is an @2x at the end of the url we are going to assume its a highres image - if ( imageUrl.indexOf(CONST.RETINA_PREFIX + '.') !== -1) { + if ( imageUrl.indexOf(CONST.RETINA_PREFIX + '.') !== -1) + { baseTexture.resolution = 2; } } @@ -363,14 +395,17 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return BaseTexture */ -BaseTexture.fromCanvas = function (canvas, scaleMode) { - if (!canvas._pixiId) { +BaseTexture.fromCanvas = function (canvas, scaleMode) +{ + if (!canvas._pixiId) + { canvas._pixiId = 'canvas_' + utils.uuid(); } var baseTexture = utils.BaseTextureCache[canvas._pixiId]; - if (!baseTexture) { + if (!baseTexture) + { baseTexture = new BaseTexture(canvas, scaleMode); utils.BaseTextureCache[canvas._pixiId] = baseTexture; } diff --git a/src/core/textures/RenderTexture.js b/src/core/textures/RenderTexture.js index 6dad20f..53ae796 100644 --- a/src/core/textures/RenderTexture.js +++ b/src/core/textures/RenderTexture.js @@ -46,8 +46,10 @@ * @param [scaleMode] {number} See {@link scaleModes} for possible values * @param [resolution=1] {number} The resolution of the texture being generated */ -function RenderTexture(renderer, width, height, scaleMode, resolution) { - if (!renderer) { +function RenderTexture(renderer, width, height, scaleMode, resolution) +{ + if (!renderer) + { throw new Error('Unable to create RenderTexture, you must pass a renderer into the constructor.'); } @@ -133,7 +135,8 @@ */ this.renderer = renderer; - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { var gl = this.renderer.gl; this.textureBuffer = new FilterTexture(gl, this.width * this.resolution, this.height * this.resolution, this.baseTexture.scaleMode); @@ -142,7 +145,8 @@ this.render = this.renderWebGL; this.projection = new math.Point(this.width*0.5, -this.height*0.5); } - else { + else + { this.render = this.renderCanvas; this.textureBuffer = new CanvasBuffer(this.width* this.resolution, this.height* this.resolution); this.baseTexture.source = this.textureBuffer.canvas; @@ -167,8 +171,10 @@ * @param height {number} The height to resize to. * @param updateBase {boolean} Should the baseTexture.width and height values be resized as well? */ -RenderTexture.prototype.resize = function (width, height, updateBase) { - if (width === this.width && height === this.height) { +RenderTexture.prototype.resize = function (width, height, updateBase) +{ + if (width === this.width && height === this.height) + { return; } @@ -177,17 +183,20 @@ this.width = this.frame.width = this.crop.width = width; this.height = this.frame.height = this.crop.height = height; - if (updateBase) { + if (updateBase) + { this.baseTexture.width = this.width; this.baseTexture.height = this.height; } - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { this.projection.x = this.width / 2; this.projection.y = -this.height / 2; } - if (!this.valid) { + if (!this.valid) + { return; } @@ -198,12 +207,15 @@ * Clears the RenderTexture. * */ -RenderTexture.prototype.clear = function () { - if (!this.valid) { +RenderTexture.prototype.clear = function () +{ + if (!this.valid) + { return; } - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { this.renderer.gl.bindFramebuffer(this.renderer.gl.FRAMEBUFFER, this.textureBuffer.frameBuffer); } @@ -220,19 +232,23 @@ * @param [restoreWorldTransform=true] {boolean} If true the displayObject's worldTransform/worldAlpha and all children * transformations will be restored. Not restoring this information will be a little faster. */ -RenderTexture.prototype.renderWebGL = function (displayObject, matrix, clear, restoreWorldTransform) { - if (!this.valid) { +RenderTexture.prototype.renderWebGL = function (displayObject, matrix, clear, restoreWorldTransform) +{ + if (!this.valid) + { return; } - if (typeof restoreWorldTransform === 'undefined') { + if (typeof restoreWorldTransform === 'undefined') + { restoreWorldTransform = true; } var tempAlpha, tempTransform; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { tempAlpha = displayObject.worldAlpha; tempTransform = displayObject.worldTransform.toArray(); } @@ -245,7 +261,8 @@ wt.identity(); wt.translate(0, this.projection.y * 2); - if (matrix) { + if (matrix) + { wt.append(matrix); } @@ -258,7 +275,8 @@ var children = displayObject.children; var i, j; - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } @@ -269,7 +287,8 @@ gl.bindFramebuffer(gl.FRAMEBUFFER, this.textureBuffer.frameBuffer ); - if (clear) { + if (clear) + { this.textureBuffer.clear(); } @@ -279,11 +298,13 @@ this.renderer.spriteBatch.dirty = true; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { displayObject.worldAlpha = tempAlpha; displayObject.worldTransform.fromArray(tempTransform); - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } } @@ -300,26 +321,31 @@ * @param [restoreWorldTransform=true] {boolean} If true the displayObject's worldTransform/worldAlpha and all children * transformations will be restored. Not restoring this information will be a little faster. */ -RenderTexture.prototype.renderCanvas = function (displayObject, matrix, clear, restoreWorldTransform) { - if (!this.valid) { +RenderTexture.prototype.renderCanvas = function (displayObject, matrix, clear, restoreWorldTransform) +{ + if (!this.valid) + { return; } - if (typeof restoreWorldTransform === 'undefined') { + if (typeof restoreWorldTransform === 'undefined') + { restoreWorldTransform = true; } var tempAlpha, tempTransform; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { tempAlpha = displayObject.worldAlpha; tempTransform = displayObject.worldTransform.toArray(); } var wt = displayObject.worldTransform; wt.identity(); - if (matrix) { + if (matrix) + { wt.append(matrix); } @@ -330,11 +356,13 @@ var children = displayObject.children; var i, j; - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } - if (clear) { + if (clear) + { this.textureBuffer.clear(); } @@ -348,11 +376,13 @@ this.renderer.resolution = realResolution; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { displayObject.worldAlpha = tempAlpha; displayObject.worldTransform.fromArray(tempTransform); - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } } @@ -363,7 +393,8 @@ * * @return {Image} */ -RenderTexture.prototype.getImage = function () { +RenderTexture.prototype.getImage = function () +{ var image = new Image(); image.src = this.getBase64(); return image; @@ -374,7 +405,8 @@ * * @return {string} A base64 encoded string of the texture. */ -RenderTexture.prototype.getBase64 = function () { +RenderTexture.prototype.getBase64 = function () +{ return this.getCanvas().toDataURL(); }; @@ -383,8 +415,10 @@ * * @return {HTMLCanvasElement} A Canvas element with the texture rendered on. */ -RenderTexture.prototype.getCanvas = function () { - if (this.renderer.type === CONST.WEBGL_RENDERER) { +RenderTexture.prototype.getCanvas = function () +{ + if (this.renderer.type === CONST.WEBGL_RENDERER) + { var gl = this.renderer.gl; var width = this.textureBuffer.width; var height = this.textureBuffer.height; @@ -403,7 +437,8 @@ return tempCanvas.canvas; } - else { + else + { return this.textureBuffer.canvas; } }; diff --git a/src/core/textures/Texture.js b/src/core/textures/Texture.js index 3c65909..e97f0aa 100644 --- a/src/core/textures/Texture.js +++ b/src/core/textures/Texture.js @@ -17,7 +17,8 @@ * @param [crop] {Rectangle} The area of original texture * @param [trim] {Rectangle} Trimmed texture rectangle */ -function Texture(baseTexture, frame, crop, trim) { +function Texture(baseTexture, frame, crop, trim) +{ /** * Does this Texture have any frame data assigned to it? * @@ -25,12 +26,14 @@ */ this.noFrame = false; - if (!frame) { + if (!frame) + { this.noFrame = true; frame = new math.Rectangle(0, 0, 1, 1); } - if (baseTexture instanceof Texture) { + if (baseTexture instanceof Texture) + { baseTexture = baseTexture.baseTexture; } @@ -100,13 +103,16 @@ */ this.crop = crop || new math.Rectangle(0, 0, 1, 1); - if (baseTexture.hasLoaded) { - if (this.noFrame) { + if (baseTexture.hasLoaded) + { + if (this.noFrame) + { frame = new math.Rectangle(0, 0, baseTexture.width, baseTexture.height); } this.frame = frame; } - else { + else + { baseTexture.addEventListener('loaded', this.onBaseTextureLoaded.bind(this)); } } @@ -118,19 +124,23 @@ Object.defineProperties(Texture.prototype, { needsUpdate: { - get: function () { + get: function () + { return this.baseTexture.needsUpdate; }, - set: function (val) { + set: function (val) + { this.baseTexture.needsUpdate = val; } }, frame: { - get: function () { + get: function () + { return this._frame; }, - set: function (frame) { + set: function (frame) + { this._frame = frame; this.noFrame = false; @@ -143,20 +153,23 @@ 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 (!this.trim && (frame.x + frame.width > this.baseTexture.width || frame.y + frame.height > this.baseTexture.height)) + { throw new Error('Texture Error: frame does not fit inside the base Texture dimensions ' + this); } this.valid = frame && frame.width && frame.height && this.baseTexture.source && this.baseTexture.hasLoaded; - if (this.trim) { + 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) { + if (this.valid) + { this._updateUvs(); } } @@ -168,11 +181,13 @@ * * @private */ -Texture.prototype.onBaseTextureLoaded = function () { +Texture.prototype.onBaseTextureLoaded = function () +{ var baseTexture = this.baseTexture; baseTexture.removeEventListener('loaded', this.onLoaded); - if (this.noFrame) { + if (this.noFrame) + { this.frame = new math.Rectangle(0, 0, baseTexture.width, baseTexture.height); } @@ -184,8 +199,10 @@ * * @param destroyBase {boolean} Whether to destroy the base texture as well */ -Texture.prototype.destroy = function (destroyBase) { - if (destroyBase) { +Texture.prototype.destroy = function (destroyBase) +{ + if (destroyBase) + { this.baseTexture.destroy(); } @@ -197,8 +214,10 @@ * * @private */ -Texture.prototype._updateUvs = function () { - if (!this._uvs) { +Texture.prototype._updateUvs = function () +{ + if (!this._uvs) + { this._uvs = new TextureUvs(); } @@ -229,10 +248,12 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return Texture */ -Texture.fromImage = function (imageUrl, crossorigin, scaleMode) { +Texture.fromImage = function (imageUrl, crossorigin, scaleMode) +{ var texture = utils.TextureCache[imageUrl]; - if (!texture) { + if (!texture) + { texture = new Texture(BaseTexture.fromImage(imageUrl, crossorigin, scaleMode)); utils.TextureCache[imageUrl] = texture; } @@ -248,9 +269,11 @@ * @param frameId {string} The frame id of the texture * @return Texture */ -Texture.fromFrame = function (frameId) { +Texture.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache '); } return texture; @@ -264,7 +287,8 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return {Texture} */ -Texture.fromCanvas = function (canvas, scaleMode) { +Texture.fromCanvas = function (canvas, scaleMode) +{ return new Texture(BaseTexture.fromCanvas(canvas, scaleMode)); }; @@ -276,7 +300,8 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return {Texture} A Texture */ -Texture.fromVideo = function (video, scaleMode) { +Texture.fromVideo = function (video, scaleMode) +{ return new Texture(VideoBaseTexture.baseTextureFromVideo(video, scaleMode)); }; @@ -287,7 +312,8 @@ * @param texture {Texture} The Texture to add to the cache. * @param id {string} The id that the texture will be stored against. */ -Texture.addTextureToCache = function (texture, id) { +Texture.addTextureToCache = function (texture, id) +{ utils.TextureCache[id] = texture; }; @@ -298,7 +324,8 @@ * @param id {string} The id of the texture to be removed * @return {Texture} The texture that was removed */ -Texture.removeTextureFromCache = function (id) { +Texture.removeTextureFromCache = function (id) +{ var texture = utils.TextureCache[id]; delete utils.TextureCache[id]; diff --git a/src/core/display/DisplayObject.js b/src/core/display/DisplayObject.js index 66ebc3c..20e778c 100644 --- a/src/core/display/DisplayObject.js +++ b/src/core/display/DisplayObject.js @@ -7,7 +7,8 @@ * @class * @namespace PIXI */ -function DisplayObject() { +function DisplayObject() +{ /** * The coordinate of the object relative to the local coordinates of the parent. * @@ -152,10 +153,12 @@ * @memberof DisplayObject# */ x: { - get: function () { + get: function () + { return this.position.x; }, - set: function (value) { + set: function (value) + { this.position.x = value; } }, @@ -167,10 +170,12 @@ * @memberof DisplayObject# */ y: { - get: function () { + get: function () + { return this.position.y; }, - set: function (value) { + set: function (value) + { this.position.y = value; } }, @@ -183,11 +188,13 @@ * @readonly */ worldVisible: { - get: function () { + get: function () + { var item = this; do { - if (!item.visible) { + if (!item.visible) + { return false; } @@ -207,17 +214,21 @@ * @memberof DisplayObject# */ mask: { - get: function () { + get: function () + { return this._mask; }, - set: function (value) { - if (this._mask) { + set: function (value) + { + if (this._mask) + { this._mask.isMask = false; } this._mask = value; - if (this._mask) { + if (this._mask) + { this._mask.isMask = true; } } @@ -232,18 +243,23 @@ * @memberof DisplayObject# */ filters: { - get: function () { + get: function () + { return this._filters; }, - set: function (value) { - if (value) { + set: function (value) + { + if (value) + { // now put all the passes in one place.. var passes = []; - for (var i = 0; i < value.length; i++) { + for (var i = 0; i < value.length; i++) + { var filterPasses = value[i].passes; - for (var j = 0; j < filterPasses.length; j++) { + for (var j = 0; j < filterPasses.length; j++) + { passes.push(filterPasses[j]); } } @@ -264,8 +280,9 @@ * * @private */ -DisplayObject.prototype.updateTransform = function () { - +DisplayObject.prototype.updateTransform = function () +{ + // create some matrix refs for easy access var pt = this.parent.worldTransform; var wt = this.worldTransform; @@ -274,9 +291,11 @@ var a, b, c, d, tx, ty; // so if rotation is between 0 then we can simplify the multiplication process.. - if (this.rotation % math.PI_2) { + if (this.rotation % math.PI_2) + { // 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) { + if (this.rotation !== this.rotationCache) + { this.rotationCache = this.rotation; this._sr = Math.sin(this.rotation); this._cr = Math.cos(this.rotation); @@ -291,7 +310,8 @@ ty = this.position.y; // check for pivot.. not often used so geared towards that fact! - if (this.pivot.x || this.pivot.y) { + 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; } @@ -304,7 +324,8 @@ wt.tx = tx * pt.a + ty * pt.c + pt.tx; wt.ty = tx * pt.b + ty * pt.d + pt.ty; } - else { + else + { // lets do the fast version as we know there is no rotation.. a = this.scale.x; d = this.scale.y; @@ -333,7 +354,8 @@ * @param matrix {Matrix} * @return {Rectangle} the rectangular bounding area */ -DisplayObject.prototype.getBounds = function (/* matrix */) { +DisplayObject.prototype.getBounds = function (/* matrix */) +{ return math.Rectangle.EMPTY; }; @@ -342,7 +364,8 @@ * * @return {Rectangle} the rectangular bounding area */ -DisplayObject.prototype.getLocalBounds = function () { +DisplayObject.prototype.getLocalBounds = function () +{ return this.getBounds(math.Matrix.IDENTITY); }; @@ -352,7 +375,8 @@ * @param position {Point} The world origin to calculate from * @return {Point} A point object representing the position of this object */ -DisplayObject.prototype.toGlobal = function (position) { +DisplayObject.prototype.toGlobal = function (position) +{ // don't need to u[date the lot this.displayObjectUpdateTransform(); return this.worldTransform.apply(position); @@ -365,8 +389,10 @@ * @param [from] {DisplayObject} The DisplayObject to calculate the global position from * @return {Point} A point object representing the position of this object */ -DisplayObject.prototype.toLocal = function (position, from) { - if (from) { +DisplayObject.prototype.toLocal = function (position, from) +{ + if (from) + { position = from.toGlobal(position); } @@ -381,7 +407,8 @@ * @param renderer {WebGLRenderer} The renderer * @private */ -DisplayObject.prototype.renderWebGL = function (/* renderer */) { +DisplayObject.prototype.renderWebGL = function (/* renderer */) +{ // OVERWRITE; }; @@ -391,6 +418,7 @@ * @param renderer {CanvasRenderer} The renderer * @private */ -DisplayObject.prototype.renderCanvas = function (/* renderer */) { +DisplayObject.prototype.renderCanvas = function (/* renderer */) +{ // OVERWRITE; }; diff --git a/src/core/display/DisplayObjectContainer.js b/src/core/display/DisplayObjectContainer.js index 689f40b..4625ee8 100644 --- a/src/core/display/DisplayObjectContainer.js +++ b/src/core/display/DisplayObjectContainer.js @@ -12,7 +12,8 @@ * @extends DisplayObject * @namespace PIXI */ -function DisplayObjectContainer() { +function DisplayObjectContainer() +{ DisplayObject.call(this); /** @@ -47,17 +48,21 @@ * @memberof DisplayObjectContainer# */ width: { - get: function () { + get: function () + { return this.scale.x * this.getLocalBounds().width; }, - set: function (value) { + set: function (value) + { var width = this.getLocalBounds().width; - if(width !== 0) { + if(width !== 0) + { this.scale.x = value / width; } - else { + else + { this.scale.x = 1; } @@ -73,17 +78,21 @@ * @memberof DisplayObjectContainer# */ height: { - get: function () { + get: function () + { return this.scale.y * this.getLocalBounds().height; }, - set: function (value) { + set: function (value) + { var height = this.getLocalBounds().height; - if (height !== 0) { + if (height !== 0) + { this.scale.y = value / height ; } - else { + else + { this.scale.y = 1; } @@ -100,18 +109,23 @@ * @memberof DisplayObject# */ cacheAsBitmap: { - get: function () { + get: function () + { return this._cacheAsBitmap; }, - set: function (value) { - if (this._cacheAsBitmap === value) { + set: function (value) + { + if (this._cacheAsBitmap === value) + { return; } - if (value) { + if (value) + { this._generateCachedSprite(); } - else { + else + { this._destroyCachedSprite(); } @@ -126,7 +140,8 @@ * @param child {DisplayObject} The DisplayObject to add to the container * @return {DisplayObject} The child that was added. */ -DisplayObjectContainer.prototype.addChild = function (child) { +DisplayObjectContainer.prototype.addChild = function (child) +{ return this.addChildAt(child, this.children.length); }; @@ -137,14 +152,18 @@ * @param index {Number} The index to place the child in * @return {DisplayObject} The child that was added. */ -DisplayObjectContainer.prototype.addChildAt = function (child, index) { +DisplayObjectContainer.prototype.addChildAt = function (child, index) +{ // prevent adding self as child - if (child === this) { + if (child === this) + { return; } - if (index >= 0 && index <= this.children.length) { - if (child.parent) { + if (index >= 0 && index <= this.children.length) + { + if (child.parent) + { child.parent.removeChild(child); } @@ -154,7 +173,8 @@ return child; } - else { + else + { throw new Error(child + 'addChildAt: The index '+ index +' supplied is out of bounds ' + this.children.length); } }; @@ -165,15 +185,18 @@ * @param child {DisplayObject} * @param child2 {DisplayObject} */ -DisplayObjectContainer.prototype.swapChildren = function (child, child2) { - if (child === child2) { +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) { + if (index1 < 0 || index2 < 0) + { throw new Error('swapChildren: Both the supplied DisplayObjects must be a child of the caller.'); } @@ -187,10 +210,12 @@ * @param child {DisplayObject} The DisplayObject instance to identify * @return {Number} The index position of the child display object to identify */ -DisplayObjectContainer.prototype.getChildIndex = function (child) { +DisplayObjectContainer.prototype.getChildIndex = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { throw new Error('The supplied DisplayObject must be a child of the caller'); } @@ -203,8 +228,10 @@ * @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 */ -DisplayObjectContainer.prototype.setChildIndex = function (child, index) { - if (index < 0 || index >= this.children.length) { +DisplayObjectContainer.prototype.setChildIndex = function (child, index) +{ + if (index < 0 || index >= this.children.length) + { throw new Error('The supplied index is out of bounds'); } @@ -220,8 +247,10 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child at the given index, if any. */ -DisplayObjectContainer.prototype.getChildAt = function (index) { - if (index < 0 || index >= this.children.length) { +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'); } @@ -234,10 +263,12 @@ * @param child {DisplayObject} The DisplayObject to remove * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChild = function (child) { +DisplayObjectContainer.prototype.removeChild = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { return; } @@ -250,7 +281,8 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChildAt = function (index) { +DisplayObjectContainer.prototype.removeChildAt = function (index) +{ var child = this.getChildAt(index); child.parent = null; @@ -265,24 +297,29 @@ * @param beginIndex {Number} The beginning position. Default value is 0. * @param endIndex {Number} The ending position. Default value is size of the container. */ -DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) { +DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) +{ var begin = beginIndex || 0; var end = typeof endIndex === 'number' ? endIndex : this.children.length; var range = end - begin; - if (range > 0 && range <= end) { + if (range > 0 && range <= end) + { var removed = this.children.splice(begin, range); - for (var i = 0; i < removed.length; ++i) { + for (var i = 0; i < removed.length; ++i) + { removed[i].parent = null; } return removed; } - else if (range === 0 && this.children.length === 0) { + else if (range === 0 && this.children.length === 0) + { return []; } - else { + else + { throw new RangeError('removeChildren: numeric values are outside the acceptable range.'); } }; @@ -291,7 +328,8 @@ * Generates and updates the cached sprite for this object. * */ -DisplayObjectContainer.prototype.updateCachedSprite = function () { +DisplayObjectContainer.prototype.updateCachedSprite = function () +{ this._generateCachedSprite(); }; @@ -304,7 +342,8 @@ * @param renderer {CanvasRenderer|WebGLRenderer} The renderer used to generate the texture. * @return {Texture} a texture of the graphics object */ -DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) { +DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) +{ var bounds = this.getLocalBounds(); var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0, renderer, scaleMode, resolution); @@ -322,18 +361,22 @@ * * @private */ -DisplayObjectContainer.prototype.updateTransform = function () { - if (!this.visible) { +DisplayObjectContainer.prototype.updateTransform = function () +{ + if (!this.visible) + { return; } this.displayObjectUpdateTransform(); - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { return; } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } }; @@ -346,8 +389,10 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getBounds = function () { - if (this.children.length === 0) { +DisplayObjectContainer.prototype.getBounds = function () +{ + if (this.children.length === 0) + { return math.Rectangle.EMPTY; } @@ -365,10 +410,12 @@ var childVisible = false; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -386,7 +433,8 @@ maxY = maxY > childMaxY ? maxY : childMaxY; } - if (!childVisible) { + if (!childVisible) + { return math.Rectangle.EMPTY; } @@ -407,12 +455,14 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getLocalBounds = function () { +DisplayObjectContainer.prototype.getLocalBounds = function () +{ var matrixCache = this.worldTransform; this.worldTransform = math.Matrix.IDENTITY; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } @@ -428,13 +478,16 @@ * * @param renderer {WebGLRenderer} The renderer */ -DisplayObjectContainer.prototype.renderWebGL = function (renderer) { +DisplayObjectContainer.prototype.renderWebGL = function (renderer) +{ // if the object is not visible or the alpha is 0 then no need to render this element - if (!this.visible || this.alpha <= 0) { + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } @@ -442,14 +495,17 @@ var i, j; // do a quick check to see if this element has a mask or a filter. - if (this._mask || this._filters) { + if (this._mask || this._filters) + { // push filter first as we need to ensure the stencil buffer is correct for any masking - if (this._filters) { + if (this._filters) + { renderer.spriteBatch.flush(); renderer.filterManager.pushFilter(this._filterBlock); } - if (this._mask) { + if (this._mask) + { renderer.spriteBatch.stop(); renderer.maskManager.pushMask(this.mask, renderer); renderer.spriteBatch.start(); @@ -459,36 +515,42 @@ this._renderWebGL(renderer); // now loop through the children and make sure they get rendered - for (i = 0, j = this.children.length; i < j; i++) { + for (i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderWebGL(renderer); } // time to stop the sprite batch as either a mask element or a filter draw will happen next renderer.spriteBatch.stop(); - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(this._mask, renderer); } - if (this._filters) { + if (this._filters) + { renderer.filterManager.popFilter(); } renderer.spriteBatch.start(); } - else { + else + { this._renderWebGL(renderer); // simple render children! - for (i = 0, j = this.children.length; i < j; ++i) { + for (i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderWebGL(renderer); } } }; -DisplayObjectContainer.prototype._renderWebGL = function (renderer) { +DisplayObjectContainer.prototype._renderWebGL = function (renderer) +{ // this is where content itself gets renderd.. @@ -499,25 +561,31 @@ * * @param renderer {CanvasRenderer} The renderer */ -DisplayObjectContainer.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0) { +DisplayObjectContainer.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -528,13 +596,16 @@ * @param renderer {WebGLRenderer|CanvasRenderer} The renderer * @private */ -DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) { +DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) +{ this._cachedSprite.worldAlpha = this.worldAlpha; - if (renderer.gl) { + if (renderer.gl) + { this._cachedSprite.renderWebGL(renderer); } - else { + else + { this._cachedSprite.renderCanvas(renderer); } }; @@ -544,10 +615,12 @@ * * @private */ -DisplayObjectContainer.prototype._generateCachedSprite = function () { +DisplayObjectContainer.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { // TODO - RenderTexture now *requires* a renderer instance, so this is like broken // because `renderer` isn't actually in scope here :P var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0); @@ -555,7 +628,8 @@ this._cachedSprite = new Sprite(renderTexture); this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.texture.resize(bounds.width | 0, bounds.height | 0); } @@ -580,8 +654,10 @@ * * @private */ -DisplayObjectContainer.prototype._destroyCachedSprite = function () { - if (!this._cachedSprite) { +DisplayObjectContainer.prototype._destroyCachedSprite = function () +{ + if (!this._cachedSprite) + { return; } diff --git a/src/core/display/Sprite.js b/src/core/display/Sprite.js index 707da24..5862aef 100644 --- a/src/core/display/Sprite.js +++ b/src/core/display/Sprite.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param texture {Texture} The texture for this sprite */ -function Sprite(texture) { +function Sprite(texture) +{ DisplayObjectContainer.call(this); /** @@ -85,12 +86,14 @@ this.texture = texture || Texture.EMPTY; } -Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) { +Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) +{ DisplayObjectContainer.prototype.destroy.call(this); this.anchor = null; - if (destroyTexture) { + if (destroyTexture) + { this._texture.destroy(destroyBaseTexture); } @@ -111,10 +114,12 @@ * @memberof Sprite# */ width: { - get: function () { + get: function () + { return this.scale.x * this.texture.frame.width; }, - set: function (value) { + set: function (value) + { this.scale.x = value / this.texture.frame.width; this._width = value; } @@ -127,10 +132,12 @@ * @memberof Sprite# */ height: { - get: function () { + get: function () + { return this.scale.y * this.texture.frame.height; }, - set: function (value) { + set: function (value) + { this.scale.y = value / this.texture.frame.height; this._height = value; } @@ -143,23 +150,29 @@ * @memberof Sprite# */ texture: { - get: function () { + get: function () + { return this._texture; }, - set: function (value) { - if (this._texture === value) { + set: function (value) + { + if (this._texture === value) + { return; } this._texture = value; this.cachedTint = 0xFFFFFF; - if (value) { + if (value) + { // wait for the texture to load - if (value.baseTexture.hasLoaded) { + if (value.baseTexture.hasLoaded) + { this._onTextureUpdate(); } - else { + else + { value.once('update', this._onTextureUpdate.bind(this)); } } @@ -172,18 +185,22 @@ * * @private */ -Sprite.prototype._onTextureUpdate = function () { +Sprite.prototype._onTextureUpdate = function () +{ // so if _width is 0 then width was not set.. - if (this._width) { + if (this._width) + { this.scale.x = this._width / this.texture.frame.width; } - if (this._height) { + if (this._height) + { this.scale.y = this._height / this.texture.frame.height; } }; -Sprite.prototype._renderWebGL = function (renderer) { +Sprite.prototype._renderWebGL = function (renderer) +{ // this is where content gets renderd.. // watch this space for a little render state manager.. @@ -197,7 +214,8 @@ * @param matrix {Matrix} the transformation matrix of the sprite * @return {Rectangle} the framing rectangle */ -Sprite.prototype.getBounds = function (matrix) { +Sprite.prototype.getBounds = function (matrix) +{ var width = this.texture.frame.width; var height = this.texture.frame.height; @@ -224,11 +242,13 @@ if(b === 0 && c === 0) { // scale may be negative! - if (a < 0) { + if (a < 0) + { a *= -1; } - if (d < 0) { + if (d < 0) + { d *= -1; } @@ -293,28 +313,34 @@ * * @param renderer {CanvasRenderer} The renderer */ -Sprite.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) { +Sprite.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) + { return; } - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; renderer.context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } // Ignore null sources - if (this.texture.valid) { + if (this.texture.valid) + { var resolution = this.texture.baseTexture.resolution / renderer.resolution; renderer.context.globalAlpha = this.worldAlpha; // If smoothingEnabled is supported and we need to change the smoothing property for this texture - if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) { + if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) + { renderer.scaleMode = this.texture.baseTexture.scaleMode; renderer.context[renderer.smoothProperty] = (renderer.scaleMode === CONST.scaleModes.LINEAR); } @@ -324,7 +350,8 @@ var dy = (this.texture.trim ? this.texture.trim.y : 0) - (this.anchor.y * this.texture.trim.height); // Allow for pixel rounding - if (renderer.roundPixels) { + if (renderer.roundPixels) + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -337,7 +364,8 @@ dx = dx | 0; dy = dy | 0; } - else { + else + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -348,8 +376,10 @@ ); } - if (this.tint !== 0xFFFFFF) { - if (this.cachedTint !== this.tint) { + if (this.tint !== 0xFFFFFF) + { + if (this.cachedTint !== this.tint) + { this.cachedTint = this.tint; // TODO clean up caching - how to clean up the caches? @@ -368,7 +398,8 @@ this.texture.crop.height / resolution ); } - else { + else + { renderer.context.drawImage( this.texture.baseTexture.source, this.texture.crop.x, @@ -383,11 +414,13 @@ } } - for (var i = 0, j = this.children.length; i < j; i++) { + for (var i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -402,10 +435,12 @@ * @param frameId {String} The frame Id of the texture in the cache * @return {Sprite} A new Sprite using a texture from the texture cache matching the frameId */ -Sprite.fromFrame = function (frameId) { +Sprite.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache' + this); } @@ -420,6 +455,7 @@ * @param imageId {String} The image url of the texture * @return {Sprite} A new Sprite using a texture from the texture cache matching the image id */ -Sprite.fromImage = function (imageId, crossorigin, scaleMode) { +Sprite.fromImage = function (imageId, crossorigin, scaleMode) +{ return new Sprite(Texture.fromImage(imageId, crossorigin, scaleMode)); }; diff --git a/src/core/display/SpriteBatch.js b/src/core/display/SpriteBatch.js index 3187777..c196fef 100644 --- a/src/core/display/SpriteBatch.js +++ b/src/core/display/SpriteBatch.js @@ -12,7 +12,8 @@ * ```js * var container = new SpriteBatch(); * - * for(var i = 0; i < 100; ++i) { + * for(var i = 0; i < 100; ++i) + * { * var sprite = new PIXI.Sprite.fromImage("myImage.png"); * container.addChild(sprite); * } @@ -25,7 +26,8 @@ */ //TODO RENAME to PARTICLE CONTAINER? -function SpriteBatch() { +function SpriteBatch() +{ DisplayObjectContainer.call(this); } @@ -38,7 +40,8 @@ * * @private */ -SpriteBatch.prototype.updateTransform = function () { +SpriteBatch.prototype.updateTransform = function () +{ // TODO don't need to! this.displayObjectUpdateTransform(); // PIXI.DisplayObjectContainer.prototype.updateTransform.call( this ); @@ -50,8 +53,10 @@ * @param renderer {WebGLRenderer} The webgl renderer * @private */ -SpriteBatch.prototype.renderWebGL = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderWebGL = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -71,8 +76,10 @@ * @param renderer {CanvasRenderer} The canvas renderer * @private */ -SpriteBatch.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -84,10 +91,12 @@ this.displayObjectUpdateTransform(); - for (var i = 0; i < this.children.length; ++i) { + for (var i = 0; i < this.children.length; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -95,9 +104,11 @@ context.globalAlpha = this.worldAlpha * child.alpha; - if (child.rotation % (Math.PI * 2) === 0) { + if (child.rotation % (Math.PI * 2) === 0) + { // this is the fastest way to optimise! - if rotation is 0 then we can avoid any kind of setTransform call - if (isRotated) { + if (isRotated) + { context.setTransform( transform.a, transform.b, @@ -122,8 +133,10 @@ frame.height * child.scale.y ); } - else { - if (!isRotated) { + else + { + if (!isRotated) + { isRotated = true; } @@ -131,7 +144,8 @@ var childTransform = child.worldTransform; - if (renderer.roundPixels) { + if (renderer.roundPixels) + { context.setTransform( childTransform.a, childTransform.b, @@ -141,7 +155,8 @@ childTransform.ty | 0 ); } - else { + else + { context.setTransform( childTransform.a, childTransform.b, diff --git a/src/core/index.js b/src/core/index.js index 3954b6f..eb4a82b 100644 --- a/src/core/index.js +++ b/src/core/index.js @@ -58,11 +58,13 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRenderer: function (width, height, options, noWebGL) { + autoDetectRenderer: function (width, height, options, noWebGL) + { width = width || 800; height = height || 600; - if (!noWebGL && require('webgl-enabled')()) { + if (!noWebGL && require('webgl-enabled')()) + { return new core.WebGLRenderer(width, height, options); } @@ -87,7 +89,8 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRecommendedRenderer: function (width, height, options) { + autoDetectRecommendedRenderer: function (width, height, options) + { var isAndroid = /Android/i.test(navigator.userAgent); return core.autoDetectRenderer(width, height, options, isAndroid); diff --git a/src/core/math/Matrix.js b/src/core/math/Matrix.js index c2f87e2..2ff4848 100644 --- a/src/core/math/Matrix.js +++ b/src/core/math/Matrix.js @@ -10,7 +10,8 @@ * @class * @namespace PIXI */ -function Matrix() { +function Matrix() +{ /** * @member {number} * @default 1 @@ -63,7 +64,8 @@ * * @param array {number[]} The array that the matrix will be populated from. */ -Matrix.prototype.fromArray = function (array) { +Matrix.prototype.fromArray = function (array) +{ this.a = array[0]; this.b = array[1]; this.c = array[3]; @@ -78,14 +80,17 @@ * @param transpose {boolean} Whether we need to transpose the matrix or not * @return {number[]} the newly created array which contains the matrix */ -Matrix.prototype.toArray = function (transpose) { - if (!this.array) { +Matrix.prototype.toArray = function (transpose) +{ + if (!this.array) + { this.array = new Float32Array(9); } var array = this.array; - if (transpose) { + if (transpose) + { array[0] = this.a; array[1] = this.b; array[2] = 0; @@ -96,7 +101,8 @@ array[7] = this.ty; array[8] = 1; } - else { + else + { array[0] = this.a; array[1] = this.c; array[2] = this.tx; @@ -119,7 +125,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, transformed through this matrix */ -Matrix.prototype.apply = function (pos, newPos) { +Matrix.prototype.apply = function (pos, newPos) +{ newPos = newPos || new Point(); newPos.x = this.a * pos.x + this.c * pos.y + this.tx; @@ -136,7 +143,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, inverse-transformed through this matrix */ -Matrix.prototype.applyInverse = function (pos, newPos) { +Matrix.prototype.applyInverse = function (pos, newPos) +{ newPos = newPos || new Point(); var id = 1 / (this.a * this.d + this.c * -this.b); @@ -154,7 +162,8 @@ * @param {number} y * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.translate = function (x, y) { +Matrix.prototype.translate = function (x, y) +{ this.tx += x; this.ty += y; @@ -168,7 +177,8 @@ * @param {number} y The amount to scale vertically * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.scale = function (x, y) { +Matrix.prototype.scale = function (x, y) +{ this.a *= x; this.d *= y; this.c *= x; @@ -186,7 +196,8 @@ * @param {number} angle - The angle in radians. * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.rotate = function (angle) { +Matrix.prototype.rotate = function (angle) +{ var cos = Math.cos( angle ); var sin = Math.sin( angle ); @@ -210,7 +221,8 @@ * @param {Matrix} matrix * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.append = function (matrix) { +Matrix.prototype.append = function (matrix) +{ var a1 = this.a; var b1 = this.b; var c1 = this.c; @@ -232,7 +244,8 @@ * * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.identity = function () { +Matrix.prototype.identity = function () +{ this.a = 1; this.b = 0; this.c = 0; diff --git a/src/core/math/Point.js b/src/core/math/Point.js index 7565b2d..632f346 100644 --- a/src/core/math/Point.js +++ b/src/core/math/Point.js @@ -7,7 +7,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -function Point(x, y) { +function Point(x, y) +{ /** * @member {number} * @default 0 @@ -29,7 +30,8 @@ * * @return {Point} a copy of the point */ -Point.prototype.clone = function () { +Point.prototype.clone = function () +{ return new Point(this.x, this.y); }; @@ -40,7 +42,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -Point.prototype.set = function (x, y) { +Point.prototype.set = function (x, y) +{ this.x = x || 0; this.y = y || ( (y !== 0) ? this.x : 0 ) ; }; diff --git a/src/core/math/shapes/Circle.js b/src/core/math/shapes/Circle.js index 69cfdc9..4d76efc 100644 --- a/src/core/math/shapes/Circle.js +++ b/src/core/math/shapes/Circle.js @@ -10,7 +10,8 @@ * @param y {number} The Y coordinate of the center of this circle * @param radius {number} The radius of the circle */ -function Circle(x, y, radius) { +function Circle(x, y, radius) +{ /** * @member {number} * @default 0 @@ -46,7 +47,8 @@ * @method clone * @return {Circle} a copy of the Circle */ -Circle.prototype.clone = function () { +Circle.prototype.clone = function () +{ return new Circle(this.x, this.y, this.radius); }; @@ -58,8 +60,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Circle */ -Circle.prototype.contains = function (x, y) { - if (this.radius <= 0) { +Circle.prototype.contains = function (x, y) +{ + if (this.radius <= 0) + { return false; } @@ -79,6 +83,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Circle.prototype.getBounds = function () { +Circle.prototype.getBounds = function () +{ return new Rectangle(this.x - this.radius, this.y - this.radius, this.radius * 2, this.radius * 2); }; diff --git a/src/core/math/shapes/Ellipse.js b/src/core/math/shapes/Ellipse.js index 4f2d066..fefd01a 100644 --- a/src/core/math/shapes/Ellipse.js +++ b/src/core/math/shapes/Ellipse.js @@ -11,7 +11,8 @@ * @param width {number} The half width of this ellipse * @param height {number} The half height of this ellipse */ -function Ellipse(x, y, width, height) { +function Ellipse(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -53,7 +54,8 @@ * @method clone * @return {Ellipse} a copy of the ellipse */ -Ellipse.prototype.clone = function () { +Ellipse.prototype.clone = function () +{ return new Ellipse(this.x, this.y, this.width, this.height); }; @@ -65,8 +67,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coords are within this ellipse */ -Ellipse.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Ellipse.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } @@ -86,6 +90,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Ellipse.prototype.getBounds = function () { +Ellipse.prototype.getBounds = function () +{ return new Rectangle(this.x - this.width, this.y - this.height, this.width, this.height); }; diff --git a/src/core/math/shapes/Polygon.js b/src/core/math/shapes/Polygon.js index ae89148..fea6d37 100644 --- a/src/core/math/shapes/Polygon.js +++ b/src/core/math/shapes/Polygon.js @@ -10,16 +10,20 @@ * arguments passed can be flat x,y values e.g. `new Polygon(x,y, x,y, x,y, ...)` where `x` and `y` are * Numbers. */ -function Polygon(points) { +function Polygon(points) +{ //if points isn't an array, use arguments as the array - if (!(points instanceof Array)) { + if (!(points instanceof Array)) + { points = Array.prototype.slice.call(arguments); } //if this is a flat array of numbers, convert it to points - if (points[0] instanceof Point) { + if (points[0] instanceof Point) + { var p = []; - for (var i = 0, il = points.length; i < il; i++) { + for (var i = 0, il = points.length; i < il; i++) + { p.push(points[i].x, points[i].y); } @@ -51,7 +55,8 @@ * * @return {Polygon} a copy of the polygon */ -Polygon.prototype.clone = function () { +Polygon.prototype.clone = function () +{ return new Polygon(this.points.slice()); }; @@ -62,19 +67,22 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this polygon */ -Polygon.prototype.contains = function (x, y) { +Polygon.prototype.contains = function (x, y) +{ var inside = false; // use some raycasting to test hits // https://github.com/substack/point-in-polygon/blob/master/index.js var length = this.points.length / 2; - for (var i = 0, j = length - 1; i < length; j = i++) { + for (var i = 0, j = length - 1; i < length; j = i++) + { var xi = this.points[i * 2], yi = this.points[i * 2 + 1], xj = this.points[j * 2], yj = this.points[j * 2 + 1], intersect = ((yi > y) !== (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi); - if (intersect) { + if (intersect) + { inside = !inside; } } diff --git a/src/core/math/shapes/Rectangle.js b/src/core/math/shapes/Rectangle.js index 16ac62a..4008b68 100644 --- a/src/core/math/shapes/Rectangle.js +++ b/src/core/math/shapes/Rectangle.js @@ -10,7 +10,8 @@ * @param width {number} The overall width of this rectangle * @param height {number} The overall height of this rectangle */ -function Rectangle(x, y, width, height) { +function Rectangle(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -60,7 +61,8 @@ * * @return {Rectangle} a copy of the rectangle */ -Rectangle.prototype.clone = function () { +Rectangle.prototype.clone = function () +{ return new Rectangle(this.x, this.y, this.width, this.height); }; @@ -71,13 +73,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rectangle */ -Rectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Rectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/math/shapes/RoundedRectangle.js b/src/core/math/shapes/RoundedRectangle.js index 27d286e..7bf6411 100644 --- a/src/core/math/shapes/RoundedRectangle.js +++ b/src/core/math/shapes/RoundedRectangle.js @@ -11,7 +11,8 @@ * @param height {number} The overall height of this rounded rectangle * @param radius {number} Controls the radius of the rounded corners */ -function RoundedRectangle(x, y, width, height, radius) { +function RoundedRectangle(x, y, width, height, radius) +{ /** * @member {number} * @default 0 @@ -58,7 +59,8 @@ * * @return {RoundedRectangle} a copy of the rounded rectangle */ -RoundedRectangle.prototype.clone = function () { +RoundedRectangle.prototype.clone = function () +{ return new RoundedRectangle(this.x, this.y, this.width, this.height, this.radius); }; @@ -69,13 +71,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rounded Rectangle */ -RoundedRectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +RoundedRectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/primitives/Graphics.js b/src/core/primitives/Graphics.js index 261c534..e902d2a 100644 --- a/src/core/primitives/Graphics.js +++ b/src/core/primitives/Graphics.js @@ -16,7 +16,8 @@ * @extends DisplayObjectContainer * @namespace PIXI */ -function Graphics() { +function Graphics() +{ DisplayObjectContainer.call(this); this.renderable = true; @@ -154,16 +155,20 @@ * @private */ cacheAsBitmap: { - get: function () { + get: function () + { return this._cacheAsBitmap; }, - set: function (value) { + set: function (value) + { this._cacheAsBitmap = value; - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._generateCachedSprite(); } - else { + else + { this.destroyCachedSprite(); this.dirty = true; } @@ -176,7 +181,8 @@ * * @return {Graphics} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ var clone = new Graphics(); clone.renderable = this.renderable; @@ -192,7 +198,8 @@ clone.cachedSpriteDirty = this.cachedSpriteDirty; // copy graphics data - for (var i = 0; i < this.graphicsData.length; ++i) { + for (var i = 0; i < this.graphicsData.length; ++i) + { clone.graphicsData.push(this.graphicsData.clone()); } @@ -211,17 +218,21 @@ * @param alpha {number} alpha of the line to draw, will update the objects stored style * @return {Graphics} */ -Graphics.prototype.lineStyle = function (lineWidth, color, alpha) { +Graphics.prototype.lineStyle = function (lineWidth, color, alpha) +{ this.lineWidth = lineWidth || 0; this.lineColor = color || 0; this.lineAlpha = (arguments.length < 3) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length) + { // halfway through a line? start a new one! this.drawShape( new math.Polygon( this.currentPath.shape.points.slice(-2) )); } - else { + else + { // otherwise its empty so lets just set the line properties this.currentPath.lineWidth = this.lineWidth; this.currentPath.lineColor = this.lineColor; @@ -239,7 +250,8 @@ * @param y {number} the Y coordinate to move to * @return {Graphics} */ -Graphics.prototype.moveTo = function (x, y) { +Graphics.prototype.moveTo = function (x, y) +{ this.drawShape(new math.Polygon([x,y])); return this; @@ -253,7 +265,8 @@ * @param y {number} the Y coordinate to draw to * @return {Graphics} */ -Graphics.prototype.lineTo = function (x, y) { +Graphics.prototype.lineTo = function (x, y) +{ this.currentPath.shape.points.push(x, y); this.dirty = true; @@ -270,13 +283,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -285,7 +302,8 @@ n = 20, points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { this.moveTo(0, 0); } @@ -293,7 +311,8 @@ var fromY = points[points.length-1]; var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; xa = fromX + ( (cpX - fromX) * j ); @@ -319,13 +338,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -342,7 +365,8 @@ var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; dt = (1 - j); @@ -373,13 +397,17 @@ * @param radius {number} The radius of the arc * @return {Graphics} */ -Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points.push(x1, y1); } } - else { + else + { this.moveTo(x1, y1); } @@ -392,12 +420,15 @@ b2 = x2 - x1, mm = Math.abs(a1 * b2 - b1 * a2); - if (mm < 1.0e-8 || radius === 0) { - if (points[points.length-2] !== x1 || points[points.length-1] !== y1) { + if (mm < 1.0e-8 || radius === 0) + { + if (points[points.length-2] !== x1 || points[points.length-1] !== y1) + { points.push(x1, y1); } } - else { + else + { var dd = a1 * a1 + b1 * b1, cc = a2 * a2 + b2 * b2, tt = a1 * a2 + b1 * b2, @@ -433,42 +464,51 @@ * @param anticlockwise {boolean} Optional. Specifies whether the drawing should be counterclockwise or clockwise. False is default, and indicates clockwise, while true indicates counter-clockwise. * @return {Graphics} */ -Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) { +Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) +{ var startX = cx + Math.cos(startAngle) * radius; var startY = cy + Math.sin(startAngle) * radius; var points; // TODO - This if-else makes no sense. It uses currentPath in the else where it doesn't exist... - if (this.currentPath) { + if (this.currentPath) + { points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { points.push(startX, startY); } - else if (points[points.length-2] !== startX || points[points.length-1] !== startY) { + else if (points[points.length-2] !== startX || points[points.length-1] !== startY) + { points.push(startX, startY); } } - else { + else + { this.moveTo(startX, startY); points = this.currentPath.shape.points; } - if (startAngle === endAngle) { + if (startAngle === endAngle) + { return this; } - if (!anticlockwise && endAngle <= startAngle) { + if (!anticlockwise && endAngle <= startAngle) + { endAngle += Math.PI * 2; } - else if (anticlockwise && startAngle <= endAngle) { + else if (anticlockwise && startAngle <= endAngle) + { startAngle += Math.PI * 2; } var sweep = anticlockwise ? (startAngle - endAngle) *-1 : (endAngle - startAngle); var segs = (Math.abs(sweep)/ (Math.PI * 2)) * 40; - if (sweep === 0) { + if (sweep === 0) + { return this; } @@ -482,7 +522,8 @@ var remainder = ( segMinus % 1 ) / segMinus; - for (var i = 0; i <= segMinus; ++i) { + for (var i = 0; i <= segMinus; ++i) + { var real = i + remainder * i; var angle = ((theta) + startAngle + (theta2 * real)); @@ -506,13 +547,16 @@ * @param alpha {number} the alpha of the fill * @return {Graphics} */ -Graphics.prototype.beginFill = function (color, alpha) { +Graphics.prototype.beginFill = function (color, alpha) +{ this.filling = true; this.fillColor = color || 0; this.fillAlpha = (alpha === undefined) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length <= 2) + { this.currentPath.fill = this.filling; this.currentPath.fillColor = this.fillColor; this.currentPath.fillAlpha = this.fillAlpha; @@ -526,7 +570,8 @@ * * @return {Graphics} */ -Graphics.prototype.endFill = function () { +Graphics.prototype.endFill = function () +{ this.filling = false; this.fillColor = null; this.fillAlpha = 1; @@ -542,7 +587,8 @@ * @param height {number} The height of the rectangle * @return {Graphics} */ -Graphics.prototype.drawRect = function ( x, y, width, height ) { +Graphics.prototype.drawRect = function ( x, y, width, height ) +{ this.drawShape(new math.Rectangle(x,y, width, height)); return this; @@ -556,7 +602,8 @@ * @param height {number} The height of the rectangle * @param radius {number} Radius of the rectangle corners */ -Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) { +Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) +{ this.drawShape(new math.RoundedRectangle(x, y, width, height, radius)); return this; @@ -570,7 +617,8 @@ * @param radius {number} The radius of the circle * @return {Graphics} */ -Graphics.prototype.drawCircle = function (x, y, radius) { +Graphics.prototype.drawCircle = function (x, y, radius) +{ this.drawShape(new math.Circle(x,y, radius)); return this; @@ -585,7 +633,8 @@ * @param height {number} The half height of the ellipse * @return {Graphics} */ -Graphics.prototype.drawEllipse = function (x, y, width, height) { +Graphics.prototype.drawEllipse = function (x, y, width, height) +{ this.drawShape(new math.Ellipse(x, y, width, height)); return this; @@ -597,8 +646,10 @@ * @param path {Array} The path data used to construct the polygon. * @return {Graphics} */ -Graphics.prototype.drawPolygon = function (path) { - if (!(path instanceof Array)) { +Graphics.prototype.drawPolygon = function (path) +{ + if (!(path instanceof Array)) + { path = Array.prototype.slice.call(arguments); } @@ -612,7 +663,8 @@ * * @return {Graphics} */ -Graphics.prototype.clear = function () { +Graphics.prototype.clear = function () +{ this.lineWidth = 0; this.filling = false; @@ -631,7 +683,8 @@ * @param scaleMode {number} Should be one of the scaleMode consts * @return {Texture} a texture of the graphics object */ -Graphics.prototype.generateTexture = function (resolution, scaleMode) { +Graphics.prototype.generateTexture = function (resolution, scaleMode) +{ resolution = resolution || 1; var bounds = this.getBounds(); @@ -655,17 +708,21 @@ * * @param renderer {WebGLRenderer} */ -Graphics.prototype._renderWebGL = function (renderer) { +Graphics.prototype._renderWebGL = function (renderer) +{ // if the sprite is not visible or the alpha is 0 then no need to render this element - if (this.isMask === true) { + if (this.isMask === true) + { return; } // this code may still be needed so leaving for now.. - // + // /* - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture on the gpu too! @@ -681,17 +738,24 @@ return; } - */ - - // check if the webgl graphic needs to be updated - if (this.glDirty) { - this.dirty = true; - this.glDirty = false; - } + else */ - renderer.setObjectRendererer(renderer.graphicsRenderer); - renderer.graphicsRenderer.render(this); + renderer.spriteBatch.stop(); + renderer.blendModeManager.setBlendMode(this.blendMode); + // check blend mode + renderer.blendModeManager.setBlendMode( this.blendMode ); + + // check if the webgl graphic needs to be updated + if (this.glDirty) + { + this.dirty = true; + this.glDirty = false; + } + + WebGLGraphics.renderGraphics(this, renderer); + + renderer.spriteBatch.start(); }; /** @@ -700,14 +764,18 @@ * @param renderer {CanvasRenderer} * @private */ -Graphics.prototype.renderCanvas = function (renderer) { +Graphics.prototype.renderCanvas = function (renderer) +{ // 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.isMask === true) { + if (!this.visible || this.alpha <= 0 || this.isMask === true) + { return; } - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture @@ -723,16 +791,19 @@ return; } - else { + else + { var context = renderer.context; var transform = this.worldTransform; - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } @@ -748,11 +819,13 @@ CanvasGraphics.renderGraphics(this, context); - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } } @@ -763,13 +836,16 @@ * * @return {Rectangle} the rectangular bounding area */ -Graphics.prototype.getBounds = function (matrix) { +Graphics.prototype.getBounds = function (matrix) +{ // return an empty object if the item is a mask! - if (this.isMask) { + if (this.isMask) + { return math.Rectangle.EMPTY; } - if (this.dirty) { + if (this.dirty) + { this.updateLocalBounds(); this.glDirty = true; @@ -841,23 +917,27 @@ * Update the bounds of the object * */ -Graphics.prototype.updateLocalBounds = function () { +Graphics.prototype.updateLocalBounds = function () +{ var minX = Infinity; var maxX = -Infinity; var minY = Infinity; var maxY = -Infinity; - if (this.graphicsData.length) { + if (this.graphicsData.length) + { var shape, points, x, y, w, h; - for (var i = 0; i < this.graphicsData.length; i++) { + for (var i = 0; i < this.graphicsData.length; i++) + { var data = this.graphicsData[i]; var type = data.type; var lineWidth = data.lineWidth; shape = data.shape; - if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) { + if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) + { x = shape.x - lineWidth/2; y = shape.y - lineWidth/2; w = shape.width + lineWidth; @@ -869,7 +949,8 @@ minY = y < minY ? y : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.CIRC) { + else if (type === CONST.SHAPES.CIRC) + { x = shape.x; y = shape.y; w = shape.radius + lineWidth/2; @@ -881,7 +962,8 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.ELIP) { + else if (type === CONST.SHAPES.ELIP) + { x = shape.x; y = shape.y; w = shape.width + lineWidth/2; @@ -893,11 +975,13 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else { + else + { // POLY points = shape.points; - for (var j = 0; j < points.length; j += 2) { + for (var j = 0; j < points.length; j += 2) + { x = points[j]; y = points[j+1]; @@ -910,7 +994,8 @@ } } } - else { + else + { minX = 0; maxX = 0; minY = 0; @@ -931,10 +1016,12 @@ * * @private */ -Graphics.prototype._generateCachedSprite = function () { +Graphics.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { var canvasBuffer = new CanvasBuffer(bounds.width, bounds.height); var texture = Texture.fromCanvas(canvasBuffer.canvas); @@ -943,7 +1030,8 @@ this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.buffer.resize(bounds.width, bounds.height); } @@ -968,7 +1056,8 @@ * * @private */ -Graphics.prototype.updateCachedSpriteTexture = function () { +Graphics.prototype.updateCachedSpriteTexture = function () +{ var cachedSprite = this._cachedSprite; var texture = cachedSprite.texture; var canvas = cachedSprite.buffer.canvas; @@ -989,7 +1078,8 @@ * Destroys a previous cached sprite. * */ -Graphics.prototype.destroyCachedSprite = function () { +Graphics.prototype.destroyCachedSprite = function () +{ this._cachedSprite.texture.destroy(true); // let the gc collect the unused sprite @@ -1003,10 +1093,13 @@ * @param {Circle|Rectangle|Ellipse|Line|Polygon} shape The Shape object to draw. * @return {GraphicsData} The generated GraphicsData object. */ -Graphics.prototype.drawShape = function (shape) { - if (this.currentPath) { +Graphics.prototype.drawShape = function (shape) +{ + if (this.currentPath) + { // check current path! - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath.shape.points.length <= 2) + { this.graphicsData.pop(); } } @@ -1017,7 +1110,8 @@ this.graphicsData.push(data); - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { data.shape.closed = this.filling; this.currentPath = data; } diff --git a/src/core/primitives/GraphicsData.js b/src/core/primitives/GraphicsData.js index 99decbe..788f6f2 100644 --- a/src/core/primitives/GraphicsData.js +++ b/src/core/primitives/GraphicsData.js @@ -4,7 +4,8 @@ * @class * @namespace PIXI */ -function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) { +function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) +{ this.lineWidth = lineWidth; this.lineColor = lineColor; this.lineAlpha = lineAlpha; @@ -27,7 +28,8 @@ * * @return {GraphicsData} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ return new GraphicsData( this.lineWidth, this.lineColor, diff --git a/src/core/renderers/canvas/CanvasRenderer.js b/src/core/renderers/canvas/CanvasRenderer.js index 15a0978..7aebd44 100644 --- a/src/core/renderers/canvas/CanvasRenderer.js +++ b/src/core/renderers/canvas/CanvasRenderer.js @@ -17,17 +17,22 @@ * @param [options.resolution=1] {number} the resolution of the renderer retina would be 2 * @param [options.clearBeforeRender=true] {boolean} This sets if the CanvasRenderer will clear the canvas or not before the new render pass. */ -function CanvasRenderer(width, height, options) { +function CanvasRenderer(width, height, options) +{ utils.sayHello('Canvas'); - if (options) { - for (var i in CONST.defaultRenderOptions) { - if (typeof options[i] === 'undefined') { + if (options) + { + for (var i in CONST.defaultRenderOptions) + { + if (typeof options[i] === 'undefined') + { options[i] = CONST.defaultRenderOptions[i]; } } } - else { + else + { options = CONST.defaultRenderOptions; } @@ -156,19 +161,24 @@ this.smoothProperty = null; - if (this.context.imageSmoothingEnabled) { + if (this.context.imageSmoothingEnabled) + { this.smoothProperty = 'imageSmoothingEnabled'; } - else if (this.context.webkitImageSmoothingEnabled) { + else if (this.context.webkitImageSmoothingEnabled) + { this.smoothProperty = 'webkitImageSmoothingEnabled'; } - else if (this.context.mozImageSmoothingEnabled) { + else if (this.context.mozImageSmoothingEnabled) + { this.smoothProperty = 'mozImageSmoothingEnabled'; } - else if (this.context.oImageSmoothingEnabled) { + else if (this.context.oImageSmoothingEnabled) + { this.smoothProperty = 'oImageSmoothingEnabled'; } - else if (this.context.msImageSmoothingEnabled) { + else if (this.context.msImageSmoothingEnabled) + { this.smoothProperty = 'msImageSmoothingEnabled'; } @@ -193,10 +203,12 @@ * @memberof CanvasRenderer# */ backgroundColor: { - get: function () { + get: function () + { return this._backgroundColor; }, - set: function (val) { + set: function (val) + { this._backgroundColor = val; this._backgroundColorString = utils.hex2string(val); } @@ -208,7 +220,8 @@ * * @param object {DisplayObject} the object to be rendered */ -CanvasRenderer.prototype.render = function (object) { +CanvasRenderer.prototype.render = function (object) +{ object.updateTransform(); this.context.setTransform(1,0,0,1,0,0); @@ -218,16 +231,20 @@ this.currentBlendMode = CONST.blendModes.NORMAL; this.context.globalCompositeOperation = this.blendModes[CONST.blendModes.NORMAL]; - if (navigator.isCocoonJS && this.view.screencanvas) { + if (navigator.isCocoonJS && this.view.screencanvas) + { this.context.fillStyle = 'black'; this.context.clear(); } - if (this.clearBeforeRender) { - if (this.transparent) { + if (this.clearBeforeRender) + { + if (this.transparent) + { this.context.clearRect(0, 0, this.width, this.height); } - else { + else + { this.context.fillStyle = this._backgroundColorString; this.context.fillRect(0, 0, this.width , this.height); } @@ -241,8 +258,10 @@ * * @param [removeView=false] {boolean} Removes the Canvas element from the DOM. */ -CanvasRenderer.prototype.destroy = function (removeView) { - if (removeView && this.view.parent) { +CanvasRenderer.prototype.destroy = function (removeView) +{ + if (removeView && this.view.parent) + { this.view.parent.removeChild(this.view); } @@ -257,14 +276,16 @@ * @param width {number} the new width of the canvas view * @param height {number} the new height of the canvas view */ -CanvasRenderer.prototype.resize = function (width, height) { +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) { + if (this.autoResize) + { this.view.style.width = this.width / this.resolution + 'px'; this.view.style.height = this.height / this.resolution + 'px'; } @@ -276,7 +297,8 @@ * @param displayObject {DisplayObject} The displayObject to render * @private */ -CanvasRenderer.prototype.renderDisplayObject = function (displayObject) { +CanvasRenderer.prototype.renderDisplayObject = function (displayObject) +{ displayObject.renderCanvas(this); }; @@ -285,11 +307,14 @@ * * @private */ -CanvasRenderer.prototype._mapBlendModes = function () { - if (!this.blendModes) { +CanvasRenderer.prototype._mapBlendModes = function () +{ + if (!this.blendModes) + { this.blendModes = {}; - if (utils.canUseNewCanvasBlendModes()) { + if (utils.canUseNewCanvasBlendModes()) + { this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? this.blendModes[CONST.blendModes.MULTIPLY] = 'multiply'; @@ -308,7 +333,8 @@ this.blendModes[CONST.blendModes.COLOR] = 'color'; this.blendModes[CONST.blendModes.LUMINOSITY] = 'luminosity'; } - else { + else + { // this means that the browser does not support the cool new blend modes in canvas 'cough' ie 'cough' this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? diff --git a/src/core/renderers/canvas/utils/CanvasBuffer.js b/src/core/renderers/canvas/utils/CanvasBuffer.js index ebe5d47..b183a66 100644 --- a/src/core/renderers/canvas/utils/CanvasBuffer.js +++ b/src/core/renderers/canvas/utils/CanvasBuffer.js @@ -6,7 +6,8 @@ * @param width {number} the width for the newly created canvas * @param height {number} the height for the newly created canvas */ -function CanvasBuffer(width, height) { +function CanvasBuffer(width, height) +{ /** * The Canvas object that belongs to this CanvasBuffer. * @@ -36,10 +37,12 @@ * @memberof CanvasBuffer# */ width: { - get: function () { + get: function () + { return this.canvas.width; }, - set: function (val) { + set: function (val) + { this.canvas.width = val; } }, @@ -50,10 +53,12 @@ * @memberof CanvasBuffer# */ height: { - get: function () { + get: function () + { return this.canvas.height; }, - set: function (val) { + set: function (val) + { this.canvas.height = val; } } @@ -64,7 +69,8 @@ * * @private */ -CanvasBuffer.prototype.clear = function () { +CanvasBuffer.prototype.clear = function () +{ this.context.setTransform(1, 0, 0, 1, 0, 0); this.context.clearRect(0,0, this.canvas.width, this.canvas.height); }; @@ -75,7 +81,8 @@ * @param width {number} the new width of the canvas * @param height {number} the new height of the canvas */ -CanvasBuffer.prototype.resize = function (width, height) { +CanvasBuffer.prototype.resize = function (width, height) +{ this.canvas.width = width; this.canvas.height = height; }; diff --git a/src/core/renderers/canvas/utils/CanvasGraphics.js b/src/core/renderers/canvas/utils/CanvasGraphics.js index c7eaa2a..3f2a91f 100644 --- a/src/core/renderers/canvas/utils/CanvasGraphics.js +++ b/src/core/renderers/canvas/utils/CanvasGraphics.js @@ -13,15 +13,18 @@ * @param graphics {Graphics} the actual graphics object to render * @param context {CanvasRenderingContext2D} the 2d drawing method of the canvas */ -CanvasGraphics.renderGraphics = function (graphics, context) { +CanvasGraphics.renderGraphics = function (graphics, context) +{ var worldAlpha = graphics.worldAlpha; - if (graphics.dirty) { + if (graphics.dirty) + { this.updateGraphicsTint(graphics); graphics.dirty = false; } - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; @@ -30,69 +33,82 @@ context.lineWidth = data.lineWidth; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { context.beginPath(); var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } - if (shape.closed) { + if (shape.closed) + { context.lineTo(points[0], points[1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fillRect(shape.x, shape.y, shape.width, shape.height); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.strokeRect(shape.x, shape.y, shape.width, shape.height); } } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.beginPath(); context.arc(shape.x, shape.y, shape.radius,0,2*Math.PI); context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas var w = shape.width * 2; @@ -119,18 +135,21 @@ context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; var width = shape.width; @@ -152,13 +171,15 @@ context.quadraticCurveTo(rx, ry, rx, ry + radius); context.closePath(); - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); @@ -174,45 +195,54 @@ * @param graphics {Graphics} the graphics which will be used as a mask * @param context {CanvasRenderingContext2D} the context 2d method of the canvas */ -CanvasGraphics.renderGraphicsMask = function (graphics, context) { +CanvasGraphics.renderGraphicsMask = function (graphics, context) +{ var len = graphics.graphicsData.length; - if (len === 0) { + if (len === 0) + { return; } context.beginPath(); - for (var i = 0; i < len; i++) { + for (var i = 0; i < len; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { context.rect(shape.x, shape.y, shape.width, shape.height); context.closePath(); } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.arc(shape.x, shape.y, shape.radius, 0, 2 * Math.PI); context.closePath(); } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas @@ -237,7 +267,8 @@ context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); context.closePath(); } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; @@ -262,8 +293,10 @@ } }; -CanvasGraphics.updateGraphicsTint = function (graphics) { - if (graphics.tint === 0xFFFFFF) { +CanvasGraphics.updateGraphicsTint = function (graphics) +{ + if (graphics.tint === 0xFFFFFF) + { return; } @@ -271,7 +304,8 @@ var tintG = (graphics.tint >> 8 & 0xFF) / 255; var tintB = (graphics.tint & 0xFF)/ 255; - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var fillColor = data.fillColor | 0; diff --git a/src/core/renderers/canvas/utils/CanvasMaskManager.js b/src/core/renderers/canvas/utils/CanvasMaskManager.js index e04a733..9827d36 100644 --- a/src/core/renderers/canvas/utils/CanvasMaskManager.js +++ b/src/core/renderers/canvas/utils/CanvasMaskManager.js @@ -6,7 +6,8 @@ * @class * @namespace PIXI */ -function CanvasMaskManager() {} +function CanvasMaskManager() +{} CanvasMaskManager.prototype.constructor = CanvasMaskManager; module.exports = CanvasMaskManager; @@ -17,7 +18,8 @@ * @param maskData {object} the maskData that will be pushed * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.pushMask = function (maskData, renderer) { +CanvasMaskManager.prototype.pushMask = function (maskData, renderer) +{ renderer.context.save(); var cacheAlpha = maskData.alpha; @@ -45,6 +47,7 @@ * * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.popMask = function (renderer) { +CanvasMaskManager.prototype.popMask = function (renderer) +{ renderer.context.restore(); }; diff --git a/src/core/renderers/canvas/utils/CanvasTinter.js b/src/core/renderers/canvas/utils/CanvasTinter.js index 17e0529..d2fb1bc 100644 --- a/src/core/renderers/canvas/utils/CanvasTinter.js +++ b/src/core/renderers/canvas/utils/CanvasTinter.js @@ -14,7 +14,8 @@ * @param color {number} the color to use to tint the sprite with * @return {HTMLCanvasElement} The tinted canvas */ -CanvasTinter.getTintedTexture = function (sprite, color) { +CanvasTinter.getTintedTexture = function (sprite, color) +{ var texture = sprite.texture; color = CanvasTinter.roundColor(color); @@ -23,7 +24,8 @@ texture.tintCache = texture.tintCache || {}; - if (texture.tintCache[stringColor]) { + if (texture.tintCache[stringColor]) + { return texture.tintCache[stringColor]; } @@ -33,14 +35,16 @@ //CanvasTinter.tintWithPerPixel(texture, stringColor, canvas); CanvasTinter.tintMethod(texture, color, canvas); - if (CanvasTinter.convertTintToImage) { + if (CanvasTinter.convertTintToImage) + { // is this better? var tintImage = new Image(); tintImage.src = canvas.toDataURL(); texture.tintCache[stringColor] = tintImage; } - else { + else + { texture.tintCache[stringColor] = canvas; // if we are not converting the texture to an image then we need to lose the reference to the canvas CanvasTinter.canvas = null; @@ -56,7 +60,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithMultiply = function (texture, color, canvas) { +CanvasTinter.tintWithMultiply = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -104,7 +109,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithOverlay = function (texture, color, canvas) { +CanvasTinter.tintWithOverlay = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -139,7 +145,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithPerPixel = function (texture, color, canvas) { +CanvasTinter.tintWithPerPixel = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -167,7 +174,8 @@ var pixels = pixelData.data; - for (var i = 0; i < pixels.length; i += 4) { + for (var i = 0; i < pixels.length; i += 4) + { pixels[i+0] *= r; pixels[i+1] *= g; pixels[i+2] *= b; @@ -181,7 +189,8 @@ * * @param color {number} the color to round, should be a hex color */ -CanvasTinter.roundColor = function (color) { +CanvasTinter.roundColor = function (color) +{ var step = CanvasTinter.cacheStepsPerColorChannel; var rgbValues = utils.hex2rgb(color); diff --git a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js index 9f2f89a..35edbaf 100644 --- a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js +++ b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLBlendModeManager(renderer) { +function WebGLBlendModeManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -23,8 +24,10 @@ * * @param blendMode {number} the blendMode, should be a Pixi const, such as BlendModes.ADD */ -WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) { - if (this.currentBlendMode === blendMode) { +WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) +{ + if (this.currentBlendMode === blendMode) + { return false; } diff --git a/src/core/renderers/webgl/managers/WebGLFilterManager.js b/src/core/renderers/webgl/managers/WebGLFilterManager.js index 1179258..2dac048 100644 --- a/src/core/renderers/webgl/managers/WebGLFilterManager.js +++ b/src/core/renderers/webgl/managers/WebGLFilterManager.js @@ -7,7 +7,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLFilterManager(renderer) { +function WebGLFilterManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -32,7 +33,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.texturePool.length = 0; self.initShaderBuffers(); }); @@ -46,7 +48,8 @@ * @param renderer {WebGLRenderer} * @param buffer {ArrayBuffer} */ -WebGLFilterManager.prototype.begin = function (buffer) { +WebGLFilterManager.prototype.begin = function (buffer) +{ this.defaultShader = this.renderer.shaderManager.defaultShader; this.width = this.renderer.projection.x * 2; @@ -60,7 +63,8 @@ * * @param filterBlock {object} the filter that will be pushed to the current filter stack */ -WebGLFilterManager.prototype.pushFilter = function (filterBlock) { +WebGLFilterManager.prototype.pushFilter = function (filterBlock) +{ var gl = this.renderer.gl; var projection = this.renderer.projection; @@ -78,10 +82,12 @@ this.offsetY += filterBlock._filterArea.y; var texture = this.texturePool.pop(); - if (!texture) { + if (!texture) + { texture = new FilterTexture(this.renderer.gl, this.width, this.height); } - else { + else + { texture.resize(this.width, this.height); } @@ -98,29 +104,35 @@ var localX = filterArea.x, localY = filterArea.y; - if (filterArea.x < 0) { + if (filterArea.x < 0) + { filterArea.width += filterArea.x; filterArea.x = 0; } - if (filterArea.y < 0) { + if (filterArea.y < 0) + { filterArea.height += filterArea.y; filterArea.y = 0; } - if (localX + filterArea.width > this.width) { + if (localX + filterArea.width > this.width) + { filterArea.width = this.width - localX; } - if (localY + filterArea.height > this.height) { + if (localY + filterArea.height > this.height) + { filterArea.height = this.height - localY; } - if (filterArea.width < 0) { + if (filterArea.width < 0) + { filterArea.width = 0; } - if (filterArea.height < 0) { + if (filterArea.height < 0) + { filterArea.height = 0; } @@ -154,7 +166,8 @@ * Removes the last filter from the filter stack and doesn't return it. * */ -WebGLFilterManager.prototype.popFilter = function () { +WebGLFilterManager.prototype.popFilter = function () +{ var gl = this.renderer.gl; var filterBlock = this.filterStack.pop(); @@ -163,7 +176,8 @@ var projection = this.renderer.projection; var offset = this.renderer.offset; - if (filterBlock.filterPasses.length > 1) { + if (filterBlock.filterPasses.length > 1) + { gl.viewport(0, 0, filterArea.width, filterArea.height); gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); @@ -193,7 +207,8 @@ var inputTexture = texture; var outputTexture = this.texturePool.pop(); - if (!outputTexture) { + if (!outputTexture) + { outputTexture = new FilterTexture(this.renderer.gl, this.width, this.height); } outputTexture.resize(this.width, this.height); @@ -204,7 +219,8 @@ gl.disable(gl.BLEND); - for (var i = 0; i < filterBlock.filterPasses.length-1; i++) { + for (var i = 0; i < filterBlock.filterPasses.length-1; i++) + { var filterPass = filterBlock.filterPasses[i]; gl.bindFramebuffer(gl.FRAMEBUFFER, outputTexture.frameBuffer ); @@ -243,10 +259,12 @@ var buffer = this.buffer; // time to render the filters texture to the previous scene - if (this.filterStack.length === 0) { + if (this.filterStack.length === 0) + { gl.colorMask(true, true, true, true);//this.transparent); } - else { + else + { var currentFilter = this.filterStack[this.filterStack.length-1]; filterArea = currentFilter._filterArea; @@ -332,13 +350,15 @@ * @param width {number} the horizontal range of the filter * @param height {number} the vertical range of the filter */ -WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) { +WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) +{ // use program var gl = this.renderer.gl; var shader = filter.shaders[gl.id]; - if (!shader) { + if (!shader) + { shader = new Shader(gl); shader.fragmentSrc = filter.fragmentSrc; @@ -356,7 +376,8 @@ gl.uniform2f(shader.projectionVector, width/2, -height/2); gl.uniform2f(shader.offsetVector, 0,0); - if (filter.uniforms.dimensions) { + 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]; @@ -386,7 +407,8 @@ * Initialises the shader buffers. * */ -WebGLFilterManager.prototype.initShaderBuffers = function () { +WebGLFilterManager.prototype.initShaderBuffers = function () +{ var gl = this.renderer.gl; // create some buffers @@ -432,7 +454,8 @@ * Destroys the filter and removes it from the filter stack. * */ -WebGLFilterManager.prototype.destroy = function () { +WebGLFilterManager.prototype.destroy = function () +{ var gl = this.renderer.gl; this.filterStack = null; @@ -441,7 +464,8 @@ this.offsetY = 0; // destroy textures - for (var i = 0; i < this.texturePool.length; i++) { + for (var i = 0; i < this.texturePool.length; i++) + { this.texturePool[i].destroy(); } diff --git a/src/core/renderers/webgl/managers/WebGLManager.js b/src/core/renderers/webgl/managers/WebGLManager.js index 9d47b5c..c30cd51 100644 --- a/src/core/renderers/webgl/managers/WebGLManager.js +++ b/src/core/renderers/webgl/managers/WebGLManager.js @@ -3,7 +3,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLManager(renderer) { +function WebGLManager(renderer) +{ /** * The renderer this manager works for. * @@ -15,6 +16,7 @@ WebGLManager.prototype.constructor = WebGLManager; module.exports = WebGLManager; -WebGLManager.prototype.destroy = function () { +WebGLManager.prototype.destroy = function () +{ this.renderer = null; }; diff --git a/src/core/renderers/webgl/managers/WebGLMaskManager.js b/src/core/renderers/webgl/managers/WebGLMaskManager.js index 2f90b64..e568812 100644 --- a/src/core/renderers/webgl/managers/WebGLMaskManager.js +++ b/src/core/renderers/webgl/managers/WebGLMaskManager.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLMaskManager(renderer) { +function WebGLMaskManager(renderer) +{ WebGLManager.call(this, renderer); } @@ -19,12 +20,15 @@ * * @param maskData {any[]} */ -WebGLMaskManager.prototype.pushMask = function (maskData) { - if (maskData.dirty) { +WebGLMaskManager.prototype.pushMask = function (maskData) +{ + if (maskData.dirty) + { WebGLGraphics.updateGraphics(maskData, this.renderer.gl); } - if (!maskData._webGL[this.renderer.gl.id].data.length) { + if (!maskData._webGL[this.renderer.gl.id].data.length) + { return; } @@ -36,6 +40,7 @@ * * @param maskData {any[]} */ -WebGLMaskManager.prototype.popMask = function (maskData) { +WebGLMaskManager.prototype.popMask = function (maskData) +{ this.renderer.stencilManager.popStencil(maskData, maskData._webGL[this.renderer.gl.id].data[0], this.renderer); }; diff --git a/src/core/renderers/webgl/managers/WebGLShaderManager.js b/src/core/renderers/webgl/managers/WebGLShaderManager.js index fef071c..90c6477 100644 --- a/src/core/renderers/webgl/managers/WebGLShaderManager.js +++ b/src/core/renderers/webgl/managers/WebGLShaderManager.js @@ -10,7 +10,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLShaderManager(renderer) { +function WebGLShaderManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -28,7 +29,8 @@ */ this.tempAttribState = []; - for (var i = 0; i < this.maxAttibs; i++) { + for (var i = 0; i < this.maxAttibs; i++) + { this.attribState[i] = false; } @@ -66,7 +68,8 @@ // listen for context and update necessary shaders var self = this; - this.renderer.on('context', function (event) { + this.renderer.on('context', function (event) + { var gl = event.data; // this shader is used for rendering primitives @@ -97,29 +100,36 @@ * * @param attribs {Array} attribs */ -WebGLShaderManager.prototype.setAttribs = function (attribs) { +WebGLShaderManager.prototype.setAttribs = function (attribs) +{ // reset temp state var i; - for (i = 0; i < this.tempAttribState.length; i++) { + for (i = 0; i < this.tempAttribState.length; i++) + { this.tempAttribState[i] = false; } // set the new attribs - for (var a in attribs) { + for (var a in attribs) + { this.tempAttribState[attribs[a]] = true; } var gl = this.renderer.gl; - for (i = 0; i < this.attribState.length; i++) { - if (this.attribState[i] !== this.tempAttribState[i]) { + for (i = 0; i < this.attribState.length; i++) + { + if (this.attribState[i] !== this.tempAttribState[i]) + { this.attribState[i] = this.tempAttribState[i]; - if (this.attribState[i]) { + if (this.attribState[i]) + { gl.enableVertexAttribArray(i); } - else { + else + { gl.disableVertexAttribArray(i); } } @@ -131,8 +141,10 @@ * * @param shader {Any} */ -WebGLShaderManager.prototype.setShader = function (shader) { - if (this._currentId === shader.uuid) { +WebGLShaderManager.prototype.setShader = function (shader) +{ + if (this._currentId === shader.uuid) + { return false; } @@ -150,7 +162,8 @@ * Destroys this object. * */ -WebGLShaderManager.prototype.destroy = function () { +WebGLShaderManager.prototype.destroy = function () +{ this.attribState = null; this.tempAttribState = null; diff --git a/src/core/renderers/webgl/managers/WebGLStencilManager.js b/src/core/renderers/webgl/managers/WebGLStencilManager.js index 9ec6398..4cb0134 100644 --- a/src/core/renderers/webgl/managers/WebGLStencilManager.js +++ b/src/core/renderers/webgl/managers/WebGLStencilManager.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLStencilManager(renderer) { +function WebGLStencilManager(renderer) +{ WebGLManager.call(this, renderer); this.stencilStack = []; @@ -24,12 +25,14 @@ * @param graphics {Graphics} * @param webGLData {any[]} */ -WebGLStencilManager.prototype.pushStencil = function (graphics, webGLData) { +WebGLStencilManager.prototype.pushStencil = function (graphics, webGLData) +{ var gl = this.renderer.gl; this.bindGraphics(graphics, webGLData, this.renderer); - if (this.stencilStack.length === 0) { + if (this.stencilStack.length === 0) + { gl.enable(gl.STENCIL_TEST); gl.clear(gl.STENCIL_BUFFER_BIT); this.reverse = true; @@ -47,14 +50,17 @@ // draw the triangle strip! - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } @@ -62,31 +68,38 @@ // draw a quad to increment.. gl.drawElements(gl.TRIANGLE_FAN, 4, gl.UNSIGNED_SHORT, ( webGLData.indices.length - 4 ) * 2 ); - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); } this.reverse = !this.reverse; } - else { - if (!this.reverse) { + else + { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } - else { + 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) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); } } @@ -103,7 +116,8 @@ * @param graphics {Graphics} * @param webGLData {Array} */ -WebGLStencilManager.prototype.bindGraphics = function (graphics, webGLData) { +WebGLStencilManager.prototype.bindGraphics = function (graphics, webGLData) +{ //if (this._currentGraphics === graphics)return; this._currentGraphics = graphics; @@ -114,7 +128,8 @@ offset = this.renderer.offset, shader;// = this.renderer.shaderManager.primitiveShader; - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { shader = this.renderer.shaderManager.complexPrimitiveShader; this.renderer.shaderManager.setShader(shader); @@ -141,7 +156,8 @@ // set the index buffer! gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, webGLData.indexBuffer); } - else { + else + { //this.renderer.shaderManager.activatePrimitiveShader(); shader = this.renderer.shaderManager.primitiveShader; this.renderer.shaderManager.setShader( shader ); @@ -154,7 +170,7 @@ gl.uniform2f(shader.uniforms.offsetVector._location, -offset.x, -offset.y); gl.uniform3fv(shader.uniforms.tint._location, utils.hex2rgb(graphics.tint)); - + gl.uniform1f(shader.uniforms.alpha._location, graphics.worldAlpha); @@ -172,19 +188,22 @@ * @param graphics {Graphics} * @param webGLData {Array} */ -WebGLStencilManager.prototype.popStencil = function (graphics, webGLData) { +WebGLStencilManager.prototype.popStencil = function (graphics, webGLData) +{ var gl = this.renderer.gl; this.stencilStack.pop(); this.count--; - if (this.stencilStack.length === 0) { + if (this.stencilStack.length === 0) + { // the stack is empty! gl.disable(gl.STENCIL_TEST); } - else { + else + { var level = this.count; @@ -192,14 +211,17 @@ gl.colorMask(false, false, false, false); - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { this.reverse = !this.reverse; - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } @@ -213,31 +235,38 @@ // draw the triangle strip! gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); - if (!this.reverse) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); } } - else { + else + { // console.log("<<>>") - if (!this.reverse) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } - else { + 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) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); } } @@ -253,7 +282,8 @@ * Destroys the mask stack. * */ -WebGLStencilManager.prototype.destroy = function () { +WebGLStencilManager.prototype.destroy = function () +{ this.renderer = null; this.stencilStack = null; }; diff --git a/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js b/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js index 913ba5e..1ea7d19 100644 --- a/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js +++ b/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function ComplexPrimitiveShader(gl) { +function ComplexPrimitiveShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -24,7 +25,8 @@ 'uniform float flipY;', 'varying vec4 vColor;', - 'void main(void) {', + '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);', @@ -37,7 +39,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = vColor;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/FastShader.js b/src/core/renderers/webgl/shaders/FastShader.js index bd2e29a..2e5e060 100644 --- a/src/core/renderers/webgl/shaders/FastShader.js +++ b/src/core/renderers/webgl/shaders/FastShader.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function FastShader(gl) { +function FastShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -28,7 +29,8 @@ 'const vec2 center = vec2(-1.0, 1.0);', - 'void main(void) {', + 'void main(void) + {', ' vec2 v;', ' vec2 sv = aVertexPosition * aScale;', ' v.x = (sv.x) * cos(aRotation) - (sv.y) * sin(aRotation);', @@ -49,7 +51,8 @@ 'uniform sampler2D uSampler;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/PrimitiveShader.js b/src/core/renderers/webgl/shaders/PrimitiveShader.js index 6f25409..a25f54f 100644 --- a/src/core/renderers/webgl/shaders/PrimitiveShader.js +++ b/src/core/renderers/webgl/shaders/PrimitiveShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function PrimitiveShader(gl) { +function PrimitiveShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -23,7 +24,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + '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);', @@ -36,7 +38,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = vColor;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/Shader.js b/src/core/renderers/webgl/shaders/Shader.js index f8964f5..fd75ef5 100644 --- a/src/core/renderers/webgl/shaders/Shader.js +++ b/src/core/renderers/webgl/shaders/Shader.js @@ -6,7 +6,8 @@ * @param [fragmentSrc] {string} The source of the fragment shader. * @param [vertexSrc] {string} The source of the vertex shader. */ -function Shader(gl, vertexSrc, fragmentSrc, customUniforms, customAttributes) { +function Shader(gl, vertexSrc, fragmentSrc, customUniforms, customAttributes) +{ /** * @member {number} * @readonly @@ -33,7 +34,8 @@ dimensions: { type: '4f', value: new Float32Array(4) } }; - for (var u in customUniforms) { + for (var u in customUniforms) + { this.uniforms[u] = customUniforms[u]; } @@ -43,7 +45,8 @@ aColor: 0 }; - for (var a in customAttributes) { + for (var a in customAttributes) + { this.attributes[a] = customAttributes[a]; } @@ -66,7 +69,8 @@ 'const vec2 center = vec2(-1.0, 1.0);', - 'void main(void) {', + 'void main(void) + {', ' gl_Position = vec4( ((aVertexPosition + offsetVector) / projectionVector) + center , 0.0, 1.0);', ' vTextureCoord = aTextureCoord;', ' vColor = vec4(aColor.rgb * aColor.a, aColor.a);', @@ -85,7 +89,8 @@ 'uniform sampler2D uSampler;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;', '}' ].join('\n'); @@ -96,7 +101,8 @@ Shader.prototype.constructor = Shader; module.exports = Shader; -Shader.prototype.init = function () { +Shader.prototype.init = function () +{ this.compile(); this.gl.useProgram(this.program); @@ -105,14 +111,18 @@ this.cacheAttributeLocations(Object.keys(this.attributes)); }; -Shader.prototype.cacheUniformLocations = function (keys) { - for (var i = 0; i < keys.length; ++i) { +Shader.prototype.cacheUniformLocations = function (keys) +{ + for (var i = 0; i < keys.length; ++i) + { this.uniforms[keys[i]]._location = this.gl.getUniformLocation(this.program, keys[i]); } }; -Shader.prototype.cacheAttributeLocations = function (keys) { - for (var i = 0; i < keys.length; ++i) { +Shader.prototype.cacheAttributeLocations = function (keys) +{ + for (var i = 0; i < keys.length; ++i) + { this.attributes[keys[i]] = this.gl.getAttribLocation(this.program, keys[i]); } @@ -124,14 +134,16 @@ // 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.attributes.aColor === -1) { + // if (this.attributes.aColor === -1) + { // this.attributes.aColor = 2; // } // End worst hack eva // }; -Shader.prototype.compile = function () { +Shader.prototype.compile = function () +{ var gl = this.gl; var glVertShader = this._glCompile(gl.VERTEX_SHADER, this.vertexSrc); @@ -144,13 +156,15 @@ gl.linkProgram(program); // if linking fails, then log and cleanup - if (!gl.getProgramParameter(program, gl.LINK_STATUS)) { + if (!gl.getProgramParameter(program, gl.LINK_STATUS)) + { window.console.error('Pixi.js Error: Could not initialize shader.'); window.console.error('gl.VALIDATE_STATUS', gl.getProgramParameter(program, gl.VALIDATE_STATUS)); window.console.error('gl.getError()', gl.getError()); // if there is a program info log, log it - if (gl.getProgramInfoLog(program) !== '') { + if (gl.getProgramInfoLog(program) !== '') + { window.console.warn('Pixi.js Warning: gl.getProgramInfoLog()', gl.getProgramInfoLog(program)); } @@ -165,18 +179,21 @@ return (this.program = program); }; -Shader.prototype.syncUniforms = function () { +Shader.prototype.syncUniforms = function () +{ var gl = this.gl; this.textureCount = 1; - for (var key in this.uniforms) { + for (var key in this.uniforms) + { var uniform = this.uniforms[key], location = uniform._location, value = uniform.value, i, il; - switch (uniform.type) { + switch (uniform.type) + { // single int value case 'i': case '1i': @@ -282,7 +299,8 @@ // a Color Value case 'c': - if (typeof value === 'number') { + if (typeof value === 'number') + { value = utils.hex2rgb(value); } @@ -311,11 +329,13 @@ // array of 2D Point objects case 'v2v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(2 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 2] = value[i].x; uniform._array[i * 2 + 1] = value[i].y; } @@ -325,11 +345,13 @@ // array of 3D Point objects case 'v3v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(3 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 3] = value[i].x; uniform._array[i * 3 + 1] = value[i].y; uniform._array[i * 3 + 2] = value[i].z; @@ -341,11 +363,13 @@ // array of 4D Point objects case 'v4v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(4 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 4] = value[i].x; uniform._array[i * 4 + 1] = value[i].y; uniform._array[i * 4 + 2] = value[i].z; @@ -359,7 +383,8 @@ // PIXI.Texture case 't': case 'sampler2D': - if (!uniform.value || !uniform.value.baseTexture || !uniform.value.baseTexture.hasLoaded) { + if (!uniform.value || !uniform.value.baseTexture || !uniform.value.baseTexture.hasLoaded) + { break; } @@ -376,7 +401,8 @@ this.textureCount++; // initialize the texture if we haven't yet - if (!uniform._init) { + if (!uniform._init) + { this.initSampler2D(uniform); uniform._init = true; @@ -394,11 +420,13 @@ * Initialises a Sampler2D uniform (which may only be available later on after initUniforms once the texture has loaded) * */ -Shader.prototype.initSampler2D = function (uniform) { +Shader.prototype.initSampler2D = function (uniform) +{ var gl = this.gl; // Extended texture data - if (uniform.textureData) { + if (uniform.textureData) + { var data = uniform.textureData; // GLTexture = mag linear, min linear_mipmap_linear, wrap repeat + gl.generateMipmap(gl.TEXTURE_2D); @@ -417,14 +445,16 @@ var wrapT = (data.wrapT) ? data.wrapT : gl.CLAMP_TO_EDGE; var format = (data.luminance) ? gl.LUMINANCE : gl.RGBA; - if (data.repeat) { + if (data.repeat) + { wrapS = gl.REPEAT; wrapT = gl.REPEAT; } gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, !!data.flipY); - if (data.width) { + if (data.width) + { var width = (data.width) ? data.width : 512; var height = (data.height) ? data.height : 2; var border = (data.border) ? data.border : 0; @@ -432,7 +462,8 @@ // 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 { + 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); } @@ -448,7 +479,8 @@ * Destroys the shader. * */ -Shader.prototype.destroy = function () { +Shader.prototype.destroy = function () +{ this.gl.deleteProgram(this.program); this.gl = null; @@ -459,13 +491,15 @@ this.fragmentSrc = null; }; -Shader.prototype._glCompile = function (type, src) { +Shader.prototype._glCompile = function (type, src) +{ var shader = this.gl.createShader(type); this.gl.shaderSource(shader, src); this.gl.compileShader(shader); - if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) { + if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) + { window.console.log(this.gl.getShaderInfoLog(shader)); return null; } diff --git a/src/core/renderers/webgl/shaders/StripShader.js b/src/core/renderers/webgl/shaders/StripShader.js index 193f6e1..a7abcc6 100644 --- a/src/core/renderers/webgl/shaders/StripShader.js +++ b/src/core/renderers/webgl/shaders/StripShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function StripShader(gl) { +function StripShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -20,7 +21,8 @@ 'varying vec2 vTextureCoord;', - 'void main(void) {', + '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);', @@ -36,7 +38,8 @@ 'varying vec2 vTextureCoord;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vec2(vTextureCoord.x, vTextureCoord.y)) * alpha;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/utils/FilterTexture.js b/src/core/renderers/webgl/utils/FilterTexture.js index d2c8423..4433d44 100644 --- a/src/core/renderers/webgl/utils/FilterTexture.js +++ b/src/core/renderers/webgl/utils/FilterTexture.js @@ -8,7 +8,8 @@ * @param height {number} the vertical range of the filter * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values */ -function FilterTexture(gl, width, height, scaleMode) { +function FilterTexture(gl, width, height, scaleMode) +{ /** * @member {WebGLContext} */ @@ -59,7 +60,8 @@ * Clears the filter texture. * */ -FilterTexture.prototype.clear = function () { +FilterTexture.prototype.clear = function () +{ var gl = this.gl; gl.clearColor(0,0,0, 0); @@ -72,8 +74,10 @@ * @param width {number} the new width of the texture * @param height {number} the new height of the texture */ -FilterTexture.prototype.resize = function (width, height) { - if (this.width === width && this.height === height) { +FilterTexture.prototype.resize = function (width, height) +{ + if (this.width === width && this.height === height) + { return; } @@ -96,7 +100,8 @@ * Destroys the filter texture. * */ -FilterTexture.prototype.destroy = function () { +FilterTexture.prototype.destroy = function () +{ var gl = this.gl; gl.deleteFramebuffer( this.frameBuffer ); gl.deleteTexture( this.texture ); diff --git a/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js b/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js index c4721e9..a63f4d7 100644 --- a/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js +++ b/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js @@ -14,7 +14,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this sprite batch works for. */ -function WebGLFastSpriteBatch(renderer) { +function WebGLFastSpriteBatch(renderer) +{ /** * The renderer instance this sprite batch operates on. * @@ -91,7 +92,8 @@ */ this.lastIndexCount = 0; - for (var i=0, j=0; i < numIndices; i += 6, j += 4) { + 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; @@ -144,7 +146,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.setupContext(); }); } @@ -157,7 +160,8 @@ * * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLFastSpriteBatch.prototype.setupContext = function () { +WebGLFastSpriteBatch.prototype.setupContext = function () +{ var gl = this.renderer.gl; // create a couple of buffers @@ -177,7 +181,8 @@ /** * @param spriteBatch {SpriteBatch} The SpriteBatch container to prepare for. */ -WebGLFastSpriteBatch.prototype.begin = function (spriteBatch) { +WebGLFastSpriteBatch.prototype.begin = function (spriteBatch) +{ this.shader = this.renderer.shaderManager.fastShader; this.matrix = spriteBatch.worldTransform.toArray(true); @@ -187,33 +192,38 @@ /** */ -WebGLFastSpriteBatch.prototype.end = function () { +WebGLFastSpriteBatch.prototype.end = function () +{ this.flush(); }; /** * @param spriteBatch {SpriteBatch} The SpriteBatch container to render. */ -WebGLFastSpriteBatch.prototype.render = function (spriteBatch) { +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) { + if (!sprite.texture._uvs) + { return; } this.currentBaseTexture = sprite.texture.baseTexture; // check blend mode - if (sprite.blendMode !== this.renderer.blendModeManager.currentBlendMode) { + if (sprite.blendMode !== this.renderer.blendModeManager.currentBlendMode) + { this.flush(); this.renderer.blendModeManager.setBlendMode(sprite.blendMode); } - for (var i=0,j= children.length; i= this.size) { + if (this.currentBatchSize >= this.size) + { this.flush(); } }; @@ -362,29 +379,35 @@ /** * */ -WebGLFastSpriteBatch.prototype.flush = function () { +WebGLFastSpriteBatch.prototype.flush = function () +{ // If the batch is length 0 then return as there is nothing to draw - if (this.currentBatchSize === 0) { + if (this.currentBatchSize === 0) + { return; } var gl = this.renderer.gl; // bind the current texture - if (!this.currentBaseTexture._glTextures[gl.id]) { + if (!this.currentBaseTexture._glTextures[gl.id]) + { this.renderer.updateTexture(this.currentBaseTexture, gl); } //TODO-SHOUD THIS BE ELSE??!?!?! - else { + else + { gl.bindTexture(gl.TEXTURE_2D, this.currentBaseTexture._glTextures[gl.id]); } // upload the verts to the buffer - if (this.currentBatchSize > ( this.size * 0.5 ) ) { + if (this.currentBatchSize > ( this.size * 0.5 ) ) + { gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); } - else { + else + { var view = this.vertices.subarray(0, this.currentBatchSize * this.vertByteSize); gl.bufferSubData(gl.ARRAY_BUFFER, 0, view); @@ -405,14 +428,16 @@ * Ends the batch and flushes * */ -WebGLFastSpriteBatch.prototype.stop = function () { +WebGLFastSpriteBatch.prototype.stop = function () +{ this.flush(); }; /** * */ -WebGLFastSpriteBatch.prototype.start = function () { +WebGLFastSpriteBatch.prototype.start = function () +{ var gl = this.renderer.gl; // bind the main texture diff --git a/src/core/renderers/webgl/utils/WebGLGraphics.js b/src/core/renderers/webgl/utils/WebGLGraphics.js index 55f4911..ab8f46e 100644 --- a/src/core/renderers/webgl/utils/WebGLGraphics.js +++ b/src/core/renderers/webgl/utils/WebGLGraphics.js @@ -19,7 +19,8 @@ * @param graphics {Graphics} * @param renderer {WebGLRenderer} */ -WebGLGraphics.renderGraphics = function (graphics, renderer) {//projection, offset) { +WebGLGraphics.renderGraphics = function (graphics, renderer) {//projection, offset) +{ var gl = renderer.gl; var projection = renderer.projection, @@ -27,7 +28,8 @@ shader = renderer.shaderManager.primitiveShader, webGLData; - if (graphics.dirty) { + if (graphics.dirty) + { WebGLGraphics.updateGraphics(graphics, gl); } @@ -35,8 +37,10 @@ // This could be speeded up for sure! - for (var i = 0; i < webGL.data.length; i++) { - if (webGL.data[i].mode === 1) { + for (var i = 0; i < webGL.data.length; i++) + { + if (webGL.data[i].mode === 1) + { webGLData = webGL.data[i]; renderer.stencilManager.pushStencil(graphics, webGLData, renderer); @@ -46,7 +50,8 @@ renderer.stencilManager.popStencil(graphics, webGLData, renderer); } - else { + else + { webGLData = webGL.data[i]; @@ -84,12 +89,14 @@ * @param graphicsData {Graphics} The graphics object to update * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLGraphics.updateGraphics = function (graphics, gl) { +WebGLGraphics.updateGraphics = function (graphics, gl) +{ // get the contexts graphics object var webGL = graphics._webGL[gl.id]; // if the graphics object does not exist in the webGL context time to create it! - if (!webGL) { + if (!webGL) + { webGL = graphics._webGL[gl.id] = {lastIndex:0, data:[], gl:gl}; } @@ -99,11 +106,13 @@ var i; // if the user cleared the graphics object we will need to clear every object - if (graphics.clearDirty) { + if (graphics.clearDirty) + { graphics.clearDirty = false; // lop through and return all the webGLDatas to the object pool so than can be reused later on - for (i = 0; i < webGL.data.length; i++) { + for (i = 0; i < webGL.data.length; i++) + { var graphicsData = webGL.data[i]; graphicsData.reset(); WebGLGraphics.graphicsDataPool.push( graphicsData ); @@ -119,58 +128,72 @@ // loop through the graphics datas and construct each one.. // if the object is a complex fill then the new stencil buffer technique will be used // other wise graphics objects will be pushed into a batch.. - for (i = webGL.lastIndex; i < graphics.graphicsData.length; i++) { + for (i = webGL.lastIndex; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { // need to add the points the the graphics object.. data.points = data.shape.points.slice(); - if (data.shape.closed) { + if (data.shape.closed) + { // close the poly if the value is true! - if (data.points[0] !== data.points[data.points.length-2] || data.points[1] !== data.points[data.points.length-1]) { + if (data.points[0] !== data.points[data.points.length-2] || data.points[1] !== data.points[data.points.length-1]) + { data.points.push(data.points[0], data.points[1]); } } // MAKE SURE WE HAVE THE CORRECT TYPE.. - if (data.fill) { - if (data.points.length >= 6) { - if (data.points.length < 6 * 2) { + if (data.fill) + { + if (data.points.length >= 6) + { + if (data.points.length < 6 * 2) + { webGLData = WebGLGraphics.switchMode(webGL, 0); var canDrawUsingSimple = WebGLGraphics.buildPoly(data, webGLData); // console.log(canDrawUsingSimple); - if (!canDrawUsingSimple) { + if (!canDrawUsingSimple) + { // console.log("<>>>") webGLData = WebGLGraphics.switchMode(webGL, 1); WebGLGraphics.buildComplexPoly(data, webGLData); } } - else { + else + { webGLData = WebGLGraphics.switchMode(webGL, 1); WebGLGraphics.buildComplexPoly(data, webGLData); } } } - if (data.lineWidth > 0) { + if (data.lineWidth > 0) + { webGLData = WebGLGraphics.switchMode(webGL, 0); WebGLGraphics.buildLine(data, webGLData); } } - else { + else + { webGLData = WebGLGraphics.switchMode(webGL, 0); - if (data.type === CONST.SHAPES.RECT) { + if (data.type === CONST.SHAPES.RECT) + { WebGLGraphics.buildRectangle(data, webGLData); } - else if (data.type === CONST.SHAPES.CIRC || data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.CIRC || data.type === CONST.SHAPES.ELIP) + { WebGLGraphics.buildCircle(data, webGLData); } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { WebGLGraphics.buildRoundedRectangle(data, webGLData); } } @@ -179,10 +202,12 @@ } // upload all the dirty data... - for (i = 0; i < webGL.data.length; i++) { + for (i = 0; i < webGL.data.length; i++) + { webGLData = webGL.data[i]; - if (webGLData.dirty) { + if (webGLData.dirty) + { webGLData.upload(); } } @@ -194,18 +219,22 @@ * @param webGL {WebGLContext} * @param type {number} */ -WebGLGraphics.switchMode = function (webGL, type) { +WebGLGraphics.switchMode = function (webGL, type) +{ var webGLData; - if (!webGL.data.length) { + if (!webGL.data.length) + { webGLData = WebGLGraphics.graphicsDataPool.pop() || new WebGLGraphicsData(webGL.gl); webGLData.mode = type; webGL.data.push(webGLData); } - else { + else + { webGLData = webGL.data[webGL.data.length-1]; - if (webGLData.mode !== type || type === 1) { + if (webGLData.mode !== type || type === 1) + { webGLData = WebGLGraphics.graphicsDataPool.pop() || new WebGLGraphicsData(webGL.gl); webGLData.mode = type; webGL.data.push(webGLData); @@ -225,7 +254,8 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildRectangle = function (graphicsData, webGLData) { +WebGLGraphics.buildRectangle = function (graphicsData, webGLData) +{ // --- // // need to convert points to a nice regular data // @@ -235,7 +265,8 @@ var width = rectData.width; var height = rectData.height; - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -265,7 +296,8 @@ indices.push(vertPos, vertPos, vertPos+1, vertPos+2, vertPos+3, vertPos+3); } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = [x, y, @@ -289,7 +321,8 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildRoundedRectangle = function (graphicsData, webGLData) { +WebGLGraphics.buildRoundedRectangle = function (graphicsData, webGLData) +{ var rrectData = graphicsData.shape; var x = rrectData.x; var y = rrectData.y; @@ -305,7 +338,8 @@ recPoints = recPoints.concat(WebGLGraphics.quadraticBezierCurve(x + width, y + radius, x + width, y, x + width - radius, y)); recPoints = recPoints.concat(WebGLGraphics.quadraticBezierCurve(x + radius, y, x, y, x, y + radius)); - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -323,7 +357,8 @@ // var i = 0; - for (i = 0; i < triangles.length; i+=3) { + for (i = 0; i < triangles.length; i+=3) + { indices.push(triangles[i] + vecPos); indices.push(triangles[i] + vecPos); indices.push(triangles[i+1] + vecPos); @@ -332,12 +367,14 @@ } - for (i = 0; i < recPoints.length; i++) { + for (i = 0; i < recPoints.length; i++) + { verts.push(recPoints[i], recPoints[++i], r, g, b, alpha); } } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = recPoints; @@ -362,7 +399,8 @@ * @param toY {number} Destination point y * @return {number[]} */ -WebGLGraphics.quadraticBezierCurve = function (fromX, fromY, cpX, cpY, toX, toY) { +WebGLGraphics.quadraticBezierCurve = function (fromX, fromY, cpX, cpY, toX, toY) +{ var xa, ya, @@ -373,14 +411,16 @@ n = 20, points = []; - function getPt(n1 , n2, perc) { + function getPt(n1 , n2, perc) + { var diff = n2 - n1; return n1 + ( diff * perc ); } var j = 0; - for (var i = 0; i <= n; i++ ) { + for (var i = 0; i <= n; i++ ) + { j = i / n; // The Green Line @@ -406,7 +446,8 @@ * @param graphicsData {Graphics} The graphics object to draw * @param webGLData {object} */ -WebGLGraphics.buildCircle = function (graphicsData, webGLData) { +WebGLGraphics.buildCircle = function (graphicsData, webGLData) +{ // need to convert points to a nice regular data var circleData = graphicsData.shape; var x = circleData.x; @@ -415,11 +456,13 @@ var height; // TODO - bit hacky?? - if (graphicsData.type === CONST.SHAPES.CIRC) { + if (graphicsData.type === CONST.SHAPES.CIRC) + { width = circleData.radius; height = circleData.radius; } - else { + else + { width = circleData.width; height = circleData.height; } @@ -429,7 +472,8 @@ var i = 0; - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -444,7 +488,8 @@ indices.push(vecPos); - for (i = 0; i < totalSegs + 1 ; i++) { + for (i = 0; i < totalSegs + 1 ; i++) + { verts.push(x,y, r, g, b, alpha); verts.push(x + Math.sin(seg * i) * width, @@ -457,12 +502,14 @@ indices.push(vecPos-1); } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = []; - for (i = 0; i < totalSegs + 1; i++) { + for (i = 0; i < totalSegs + 1; i++) + { graphicsData.points.push(x + Math.sin(seg * i) * width, y + Math.cos(seg * i) * height); } @@ -481,18 +528,22 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildLine = function (graphicsData, webGLData) { +WebGLGraphics.buildLine = function (graphicsData, webGLData) +{ // TODO OPTIMISE! var i = 0; var points = graphicsData.points; - if (points.length === 0) { + if (points.length === 0) + { return; } // if the line width is an odd number add 0.5 to align to a whole pixel - if (graphicsData.lineWidth%2) { - for (i = 0; i < points.length; i++) { + if (graphicsData.lineWidth%2) + { + for (i = 0; i < points.length; i++) + { points[i] += 0.5; } } @@ -502,7 +553,8 @@ var lastPoint = new math.Point(points[points.length - 2], points[points.length - 1]); // if the first point is the last point - gonna have issues :) - if (firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) { + if (firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) + { // need to clone as we are going to slightly modify the shape.. points = points.slice(); @@ -562,7 +614,8 @@ verts.push(p1x + perpx , p1y + perpy, r, g, b, alpha); - for (i = 1; i < length-1; i++) { + for (i = 1; i < length-1; i++) + { p1x = points[(i-1)*2]; p1y = points[(i-1)*2 + 1]; @@ -599,7 +652,8 @@ denom = a1*b2 - a2*b1; - if (Math.abs(denom) < 0.1 ) { + if (Math.abs(denom) < 0.1 ) + { denom+=10.1; verts.push(p2x - perpx , p2y - perpy, @@ -618,7 +672,8 @@ pdist = (px -p2x) * (px -p2x) + (py -p2y) + (py -p2y); - if (pdist > 140 * 140) { + if (pdist > 140 * 140) + { perp3x = perpx - perp2x; perp3y = perpy - perp2y; @@ -639,7 +694,8 @@ indexCount++; } - else { + else + { verts.push(px , py); verts.push(r, g, b, alpha); @@ -672,7 +728,8 @@ indices.push(indexStart); - for (i = 0; i < indexCount; i++) { + for (i = 0; i < indexCount; i++) + { indices.push(indexStart++); } @@ -687,11 +744,13 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildComplexPoly = function (graphicsData, webGLData) { +WebGLGraphics.buildComplexPoly = function (graphicsData, webGLData) +{ //TODO - no need to copy this as it gets turned into a FLoat32Array anyways.. var points = graphicsData.points.slice(); - if (points.length < 6) { + if (points.length < 6) + { return; } @@ -711,7 +770,8 @@ var x,y; // get size.. - for (var i = 0; i < points.length; i+=2) { + for (var i = 0; i < points.length; i+=2) + { x = points[i]; y = points[i+1]; @@ -732,7 +792,8 @@ //TODO - this aint needed! var length = points.length / 2; - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { indices.push( i ); } @@ -746,10 +807,12 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildPoly = function (graphicsData, webGLData) { +WebGLGraphics.buildPoly = function (graphicsData, webGLData) +{ var points = graphicsData.points; - if (points.length < 6) { + if (points.length < 6) + { return; } // get first and last point.. figure out the middle! @@ -767,7 +830,8 @@ var triangles = utils.PolyK.Triangulate(points); - if (!triangles) { + if (!triangles) + { return false; } @@ -775,7 +839,8 @@ var i = 0; - for (i = 0; i < triangles.length; i+=3) { + for (i = 0; i < triangles.length; i+=3) + { indices.push(triangles[i] + vertPos); indices.push(triangles[i] + vertPos); indices.push(triangles[i+1] + vertPos); @@ -783,7 +848,8 @@ indices.push(triangles[i+2] + vertPos); } - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { verts.push(points[i * 2], points[i * 2 + 1], r, g, b, alpha); } diff --git a/src/core/renderers/webgl/utils/WebGLGraphicsData.js b/src/core/renderers/webgl/utils/WebGLGraphicsData.js index c56d05e..c739ba7 100644 --- a/src/core/renderers/webgl/utils/WebGLGraphicsData.js +++ b/src/core/renderers/webgl/utils/WebGLGraphicsData.js @@ -2,7 +2,8 @@ * @class * @private */ -function WebGLGraphicsData(gl) { +function WebGLGraphicsData(gl) +{ this.gl = gl; //TODO does this need to be split before uploding?? @@ -22,7 +23,8 @@ /** * */ -WebGLGraphicsData.prototype.reset = function () { +WebGLGraphicsData.prototype.reset = function () +{ this.points.length = 0; this.indices.length = 0; }; @@ -30,7 +32,8 @@ /** * */ -WebGLGraphicsData.prototype.upload = function () { +WebGLGraphicsData.prototype.upload = function () +{ var gl = this.gl; // this.lastIndex = graphics.graphicsData.length; diff --git a/src/core/renderers/webgl/utils/WebGLSpriteBatch.js b/src/core/renderers/webgl/utils/WebGLSpriteBatch.js index 96eaa52..55befbb 100644 --- a/src/core/renderers/webgl/utils/WebGLSpriteBatch.js +++ b/src/core/renderers/webgl/utils/WebGLSpriteBatch.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this sprite batch works for. */ -function WebGLSpriteBatch(renderer) { +function WebGLSpriteBatch(renderer) +{ /** * * @@ -88,7 +89,8 @@ */ this.lastIndexCount = 0; - for (var i=0, j=0; i < numIndices; i += 6, j += 4) { + 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; @@ -162,7 +164,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.setupContext(); }); } @@ -173,7 +176,8 @@ /** * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLSpriteBatch.prototype.setupContext = function () { +WebGLSpriteBatch.prototype.setupContext = function () +{ var gl = this.renderer.gl; // setup default shader @@ -198,7 +202,8 @@ /** * */ -WebGLSpriteBatch.prototype.begin = function () { +WebGLSpriteBatch.prototype.begin = function () +{ // this.shader = this.renderer.shaderManager.defaultShader; this.start(); @@ -206,19 +211,22 @@ /** */ -WebGLSpriteBatch.prototype.end = function () { +WebGLSpriteBatch.prototype.end = function () +{ this.flush(); }; /** * @param sprite {Sprite} the sprite to render when using this spritebatch */ -WebGLSpriteBatch.prototype.render = function (sprite) { +WebGLSpriteBatch.prototype.render = function (sprite) +{ var texture = sprite.texture; //TODO set blend modes.. // check texture.. - if (this.currentBatchSize >= this.size) { + if (this.currentBatchSize >= this.size) + { this.flush(); this.currentBaseTexture = texture.baseTexture; } @@ -227,7 +235,8 @@ var uvs = texture._uvs; // if the uvs have not updated then no point rendering just yet! - if (!uvs) { + if (!uvs) + { return; } @@ -237,7 +246,8 @@ var w0, w1, h0, h1; - if (texture.trim) { + 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; @@ -248,7 +258,8 @@ h0 = h1 + texture.crop.height; } - else { + else + { w0 = (texture.frame.width ) * (1-aX); w1 = (texture.frame.width ) * -aX; @@ -272,7 +283,8 @@ var colors = this.colors; var positions = this.positions; - if (this.renderer.roundPixels) { + if (this.renderer.roundPixels) + { // xy positions[index] = a * w1 + c * h1 + tx | 0; positions[index+1] = d * h1 + b * w1 + ty | 0; @@ -289,7 +301,8 @@ positions[index+15] = a * w1 + c * h0 + tx | 0; positions[index+16] = d * h0 + b * w1 + ty | 0; } - else { + else + { // xy positions[index] = a * w1 + c * h1 + tx; positions[index+1] = d * h1 + b * w1 + ty; @@ -338,11 +351,13 @@ * * @param sprite {TilingSprite} the tilingSprite to render */ -WebGLSpriteBatch.prototype.renderTilingSprite = function (tilingSprite) { +WebGLSpriteBatch.prototype.renderTilingSprite = function (tilingSprite) +{ var texture = tilingSprite.tilingTexture; // check texture.. - if (this.currentBatchSize >= this.size) { + if (this.currentBatchSize >= this.size) + { //return; this.flush(); this.currentBaseTexture = texture.baseTexture; @@ -351,7 +366,8 @@ // set the textures uvs temporarily // TODO create a separate texture so that we can tile part of a texture - if (!tilingSprite._uvs) { + if (!tilingSprite._uvs) + { tilingSprite._uvs = new TextureUvs(); } @@ -454,16 +470,19 @@ * Renders the content and empties the current batch. * */ -WebGLSpriteBatch.prototype.flush = function () { +WebGLSpriteBatch.prototype.flush = function () +{ // If the batch is length 0 then return as there is nothing to draw - if (this.currentBatchSize === 0) { + if (this.currentBatchSize === 0) + { return; } var gl = this.renderer.gl; var shader; - if (this.dirty) { + if (this.dirty) + { this.dirty = false; // bind the main texture gl.activeTexture(gl.TEXTURE0); @@ -482,10 +501,12 @@ } // upload the verts to the buffer - if (this.currentBatchSize > ( this.size * 0.5 ) ) { + if (this.currentBatchSize > ( this.size * 0.5 ) ) + { gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); } - else { + else + { var view = this.positions.subarray(0, this.currentBatchSize * this.vertByteSize); gl.bufferSubData(gl.ARRAY_BUFFER, 0, view); } @@ -502,7 +523,8 @@ var shaderSwap = false; var sprite; - for (var i = 0, j = this.currentBatchSize; i < j; i++) { + for (var i = 0, j = this.currentBatchSize; i < j; i++) + { sprite = this.sprites[i]; @@ -513,24 +535,28 @@ blendSwap = currentBlendMode !== nextBlendMode; shaderSwap = currentShader !== nextShader; // should I use uuidS??? - if (currentBaseTexture !== nextTexture || blendSwap || shaderSwap) { + if (currentBaseTexture !== nextTexture || blendSwap || shaderSwap) + { this.renderBatch(currentBaseTexture, batchSize, start); start = i; batchSize = 0; currentBaseTexture = nextTexture; - if (blendSwap) { + if (blendSwap) + { currentBlendMode = nextBlendMode; this.renderer.blendModeManager.setBlendMode( currentBlendMode ); } - if (shaderSwap) { + if (shaderSwap) + { currentShader = nextShader; shader = currentShader.shaders ? currentShader.shaders[gl.id] : currentShader; - if (!shader) { + if (!shader) + { shader = new Shader(gl, null, currentShader.fragmentSrc, currentShader.uniforms); currentShader.shaders[gl.id] = shader; } @@ -538,7 +564,8 @@ // set shader function??? this.renderer.shaderManager.setShader(shader); - if (shader.dirty) { + if (shader.dirty) + { shader.syncUniforms(); } @@ -569,17 +596,21 @@ * @param size {number} * @param startIndex {number} */ -WebGLSpriteBatch.prototype.renderBatch = function (texture, size, startIndex) { - if (size === 0) { +WebGLSpriteBatch.prototype.renderBatch = function (texture, size, startIndex) +{ + if (size === 0) + { return; } var gl = this.renderer.gl; - if (!texture._glTextures[gl.id]) { + if (!texture._glTextures[gl.id]) + { this.renderer.updateTexture(texture); } - else { + else + { // bind the current texture gl.bindTexture(gl.TEXTURE_2D, texture._glTextures[gl.id]); } @@ -594,7 +625,8 @@ /** * */ -WebGLSpriteBatch.prototype.stop = function () { +WebGLSpriteBatch.prototype.stop = function () +{ this.flush(); this.dirty = true; }; @@ -602,7 +634,8 @@ /** * */ -WebGLSpriteBatch.prototype.start = function () { +WebGLSpriteBatch.prototype.start = function () +{ this.dirty = true; }; @@ -610,7 +643,8 @@ * Destroys the SpriteBatch. * */ -WebGLSpriteBatch.prototype.destroy = function () { +WebGLSpriteBatch.prototype.destroy = function () +{ this.renderer.gl.deleteBuffer(this.vertexBuffer); this.renderer.gl.deleteBuffer(this.indexBuffer); diff --git a/src/core/textures/BaseTexture.js b/src/core/textures/BaseTexture.js index 2bf77d4..513d358 100644 --- a/src/core/textures/BaseTexture.js +++ b/src/core/textures/BaseTexture.js @@ -10,7 +10,8 @@ * @param source {Image|Canvas} the source object of the texture. * @param [scaleMode=scaleModes.DEFAULT] {number} See {@link scaleModes} for possible values */ -function BaseTexture(source, scaleMode) { +function BaseTexture(source, scaleMode) +{ this.uuid = utils.uuid(); /** @@ -123,7 +124,8 @@ this._needsUpdate = false; // if no source passed don't try to load - if (source) { + if (source) + { this.loadSource(source); } @@ -149,13 +151,16 @@ Object.defineProperties(BaseTexture.prototype, { needsUpdate: { - get: function () { + get: function () + { return this._needsUpdate; }, - set: function (val) { + set: function (val) + { this._needsUpdate = val; - if (val) { + if (val) + { this.emit('update', this); } } @@ -171,9 +176,11 @@ * * The logic state after calling `loadSource` directly or indirectly (eg. `fromImage`, `new BaseTexture`) is: * - * if (texture.hasLoaded) { + * if (texture.hasLoaded) + { * // texture ready for use - * } else if (texture.isLoading) { + * } else if (texture.isLoading) + { * // listen to 'loaded' and/or 'error' events on texture * } else { * // not loading, not going to load UNLESS the source is reloaded @@ -183,12 +190,14 @@ * @protected * @param source {Image|Canvas} the source object of the texture. */ -BaseTexture.prototype.loadSource = function (source) { +BaseTexture.prototype.loadSource = function (source) +{ var wasLoading = this.isLoading; this.hasLoaded = false; this.isLoading = false; - if (wasLoading && this.source) { + if (wasLoading && this.source) + { this.source.onload = null; this.source.onerror = null; } @@ -196,20 +205,24 @@ this.source = source; // Apply source if loaded. Otherwise setup appropriate loading monitors. - if ((this.source.complete || this.source.getContext) && this.source.width && this.source.height) { + if ((this.source.complete || this.source.getContext) && this.source.width && this.source.height) + { this._sourceLoaded(); } - else if(!source.getContext) { + else if(!source.getContext) + { // Image fail / not ready this.isLoading = true; var scope = this; - source.onload = function () { + source.onload = function () + { source.onload = null; source.onerror = null; - if(!scope.isLoading) { + if(!scope.isLoading) + { return; } @@ -219,11 +232,13 @@ scope.emit('loaded', scope); }; - source.onerror = function () { + source.onerror = function () + { source.onload = null; source.onerror = null; - if(!scope.isLoading) { + if(!scope.isLoading) + { return; } @@ -234,24 +249,29 @@ // Per http://www.w3.org/TR/html5/embedded-content-0.html#the-img-element // "The value of `complete` can thus change while a script is executing." // So complete needs to be re-checked after the callbacks have been added.. - if (source.complete) { + if (source.complete) + { this.isLoading = false; // ..and if we're complete now, no need for callbacks source.onload = null; source.onerror = null; - if (source.width && source.height) { + if (source.width && source.height) + { this._sourceLoaded(); // If any previous subscribers possible - if (wasLoading) { + if (wasLoading) + { this.emit('loaded', this); } } - else { + else + { // If any previous subscribers possible - if (wasLoading) { + if (wasLoading) + { this.emit('error', this); } } @@ -265,7 +285,8 @@ * * @private */ -BaseTexture.prototype._sourceLoaded = function () { +BaseTexture.prototype._sourceLoaded = function () +{ this.hasLoaded = true; this.width = this.source.naturalWidth || this.source.width; @@ -278,16 +299,20 @@ * Destroys this base texture * */ -BaseTexture.prototype.destroy = function () { - if (this.imageUrl) { +BaseTexture.prototype.destroy = function () +{ + if (this.imageUrl) + { delete utils.BaseTextureCache[this.imageUrl]; delete utils.TextureCache[this.imageUrl]; this.imageUrl = null; - if (!navigator.isCocoonJS) { + if (!navigator.isCocoonJS) + { this.source.src = ''; } } - else if (this.source && this.source._pixiId) { + else if (this.source && this.source._pixiId) + { delete utils.BaseTextureCache[this.source._pixiId]; } this.source = null; @@ -301,7 +326,8 @@ * memory again. * */ -BaseTexture.prototype.dispose = function () { +BaseTexture.prototype.dispose = function () +{ this.emit('dispose', this); }; @@ -311,7 +337,8 @@ * * @param newSrc {string} the path of the image */ -BaseTexture.prototype.updateSourceImage = function (newSrc) { +BaseTexture.prototype.updateSourceImage = function (newSrc) +{ this.source.src = newSrc; this.loadSource(this.source); }; @@ -326,18 +353,22 @@ * @param [scaleMode=scaleModes.DEFAULT] {number} See {@link scaleModes} for possible values * @return BaseTexture */ -BaseTexture.fromImage = function (imageUrl, crossorigin, scaleMode) { +BaseTexture.fromImage = function (imageUrl, crossorigin, scaleMode) +{ var baseTexture = utils.BaseTextureCache[imageUrl]; - if (crossorigin === undefined && imageUrl.indexOf('data:') !== 0) { + if (crossorigin === undefined && imageUrl.indexOf('data:') !== 0) + { crossorigin = true; } - if (!baseTexture) { + if (!baseTexture) + { // new Image() breaks tex loading in some versions of Chrome. // See https://code.google.com/p/chromium/issues/detail?id=238071 var image = new Image();//document.createElement('img'); - if (crossorigin) { + if (crossorigin) + { image.crossOrigin = ''; } @@ -347,7 +378,8 @@ utils.BaseTextureCache[imageUrl] = baseTexture; // if there is an @2x at the end of the url we are going to assume its a highres image - if ( imageUrl.indexOf(CONST.RETINA_PREFIX + '.') !== -1) { + if ( imageUrl.indexOf(CONST.RETINA_PREFIX + '.') !== -1) + { baseTexture.resolution = 2; } } @@ -363,14 +395,17 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return BaseTexture */ -BaseTexture.fromCanvas = function (canvas, scaleMode) { - if (!canvas._pixiId) { +BaseTexture.fromCanvas = function (canvas, scaleMode) +{ + if (!canvas._pixiId) + { canvas._pixiId = 'canvas_' + utils.uuid(); } var baseTexture = utils.BaseTextureCache[canvas._pixiId]; - if (!baseTexture) { + if (!baseTexture) + { baseTexture = new BaseTexture(canvas, scaleMode); utils.BaseTextureCache[canvas._pixiId] = baseTexture; } diff --git a/src/core/textures/RenderTexture.js b/src/core/textures/RenderTexture.js index 6dad20f..53ae796 100644 --- a/src/core/textures/RenderTexture.js +++ b/src/core/textures/RenderTexture.js @@ -46,8 +46,10 @@ * @param [scaleMode] {number} See {@link scaleModes} for possible values * @param [resolution=1] {number} The resolution of the texture being generated */ -function RenderTexture(renderer, width, height, scaleMode, resolution) { - if (!renderer) { +function RenderTexture(renderer, width, height, scaleMode, resolution) +{ + if (!renderer) + { throw new Error('Unable to create RenderTexture, you must pass a renderer into the constructor.'); } @@ -133,7 +135,8 @@ */ this.renderer = renderer; - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { var gl = this.renderer.gl; this.textureBuffer = new FilterTexture(gl, this.width * this.resolution, this.height * this.resolution, this.baseTexture.scaleMode); @@ -142,7 +145,8 @@ this.render = this.renderWebGL; this.projection = new math.Point(this.width*0.5, -this.height*0.5); } - else { + else + { this.render = this.renderCanvas; this.textureBuffer = new CanvasBuffer(this.width* this.resolution, this.height* this.resolution); this.baseTexture.source = this.textureBuffer.canvas; @@ -167,8 +171,10 @@ * @param height {number} The height to resize to. * @param updateBase {boolean} Should the baseTexture.width and height values be resized as well? */ -RenderTexture.prototype.resize = function (width, height, updateBase) { - if (width === this.width && height === this.height) { +RenderTexture.prototype.resize = function (width, height, updateBase) +{ + if (width === this.width && height === this.height) + { return; } @@ -177,17 +183,20 @@ this.width = this.frame.width = this.crop.width = width; this.height = this.frame.height = this.crop.height = height; - if (updateBase) { + if (updateBase) + { this.baseTexture.width = this.width; this.baseTexture.height = this.height; } - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { this.projection.x = this.width / 2; this.projection.y = -this.height / 2; } - if (!this.valid) { + if (!this.valid) + { return; } @@ -198,12 +207,15 @@ * Clears the RenderTexture. * */ -RenderTexture.prototype.clear = function () { - if (!this.valid) { +RenderTexture.prototype.clear = function () +{ + if (!this.valid) + { return; } - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { this.renderer.gl.bindFramebuffer(this.renderer.gl.FRAMEBUFFER, this.textureBuffer.frameBuffer); } @@ -220,19 +232,23 @@ * @param [restoreWorldTransform=true] {boolean} If true the displayObject's worldTransform/worldAlpha and all children * transformations will be restored. Not restoring this information will be a little faster. */ -RenderTexture.prototype.renderWebGL = function (displayObject, matrix, clear, restoreWorldTransform) { - if (!this.valid) { +RenderTexture.prototype.renderWebGL = function (displayObject, matrix, clear, restoreWorldTransform) +{ + if (!this.valid) + { return; } - if (typeof restoreWorldTransform === 'undefined') { + if (typeof restoreWorldTransform === 'undefined') + { restoreWorldTransform = true; } var tempAlpha, tempTransform; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { tempAlpha = displayObject.worldAlpha; tempTransform = displayObject.worldTransform.toArray(); } @@ -245,7 +261,8 @@ wt.identity(); wt.translate(0, this.projection.y * 2); - if (matrix) { + if (matrix) + { wt.append(matrix); } @@ -258,7 +275,8 @@ var children = displayObject.children; var i, j; - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } @@ -269,7 +287,8 @@ gl.bindFramebuffer(gl.FRAMEBUFFER, this.textureBuffer.frameBuffer ); - if (clear) { + if (clear) + { this.textureBuffer.clear(); } @@ -279,11 +298,13 @@ this.renderer.spriteBatch.dirty = true; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { displayObject.worldAlpha = tempAlpha; displayObject.worldTransform.fromArray(tempTransform); - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } } @@ -300,26 +321,31 @@ * @param [restoreWorldTransform=true] {boolean} If true the displayObject's worldTransform/worldAlpha and all children * transformations will be restored. Not restoring this information will be a little faster. */ -RenderTexture.prototype.renderCanvas = function (displayObject, matrix, clear, restoreWorldTransform) { - if (!this.valid) { +RenderTexture.prototype.renderCanvas = function (displayObject, matrix, clear, restoreWorldTransform) +{ + if (!this.valid) + { return; } - if (typeof restoreWorldTransform === 'undefined') { + if (typeof restoreWorldTransform === 'undefined') + { restoreWorldTransform = true; } var tempAlpha, tempTransform; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { tempAlpha = displayObject.worldAlpha; tempTransform = displayObject.worldTransform.toArray(); } var wt = displayObject.worldTransform; wt.identity(); - if (matrix) { + if (matrix) + { wt.append(matrix); } @@ -330,11 +356,13 @@ var children = displayObject.children; var i, j; - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } - if (clear) { + if (clear) + { this.textureBuffer.clear(); } @@ -348,11 +376,13 @@ this.renderer.resolution = realResolution; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { displayObject.worldAlpha = tempAlpha; displayObject.worldTransform.fromArray(tempTransform); - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } } @@ -363,7 +393,8 @@ * * @return {Image} */ -RenderTexture.prototype.getImage = function () { +RenderTexture.prototype.getImage = function () +{ var image = new Image(); image.src = this.getBase64(); return image; @@ -374,7 +405,8 @@ * * @return {string} A base64 encoded string of the texture. */ -RenderTexture.prototype.getBase64 = function () { +RenderTexture.prototype.getBase64 = function () +{ return this.getCanvas().toDataURL(); }; @@ -383,8 +415,10 @@ * * @return {HTMLCanvasElement} A Canvas element with the texture rendered on. */ -RenderTexture.prototype.getCanvas = function () { - if (this.renderer.type === CONST.WEBGL_RENDERER) { +RenderTexture.prototype.getCanvas = function () +{ + if (this.renderer.type === CONST.WEBGL_RENDERER) + { var gl = this.renderer.gl; var width = this.textureBuffer.width; var height = this.textureBuffer.height; @@ -403,7 +437,8 @@ return tempCanvas.canvas; } - else { + else + { return this.textureBuffer.canvas; } }; diff --git a/src/core/textures/Texture.js b/src/core/textures/Texture.js index 3c65909..e97f0aa 100644 --- a/src/core/textures/Texture.js +++ b/src/core/textures/Texture.js @@ -17,7 +17,8 @@ * @param [crop] {Rectangle} The area of original texture * @param [trim] {Rectangle} Trimmed texture rectangle */ -function Texture(baseTexture, frame, crop, trim) { +function Texture(baseTexture, frame, crop, trim) +{ /** * Does this Texture have any frame data assigned to it? * @@ -25,12 +26,14 @@ */ this.noFrame = false; - if (!frame) { + if (!frame) + { this.noFrame = true; frame = new math.Rectangle(0, 0, 1, 1); } - if (baseTexture instanceof Texture) { + if (baseTexture instanceof Texture) + { baseTexture = baseTexture.baseTexture; } @@ -100,13 +103,16 @@ */ this.crop = crop || new math.Rectangle(0, 0, 1, 1); - if (baseTexture.hasLoaded) { - if (this.noFrame) { + if (baseTexture.hasLoaded) + { + if (this.noFrame) + { frame = new math.Rectangle(0, 0, baseTexture.width, baseTexture.height); } this.frame = frame; } - else { + else + { baseTexture.addEventListener('loaded', this.onBaseTextureLoaded.bind(this)); } } @@ -118,19 +124,23 @@ Object.defineProperties(Texture.prototype, { needsUpdate: { - get: function () { + get: function () + { return this.baseTexture.needsUpdate; }, - set: function (val) { + set: function (val) + { this.baseTexture.needsUpdate = val; } }, frame: { - get: function () { + get: function () + { return this._frame; }, - set: function (frame) { + set: function (frame) + { this._frame = frame; this.noFrame = false; @@ -143,20 +153,23 @@ 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 (!this.trim && (frame.x + frame.width > this.baseTexture.width || frame.y + frame.height > this.baseTexture.height)) + { throw new Error('Texture Error: frame does not fit inside the base Texture dimensions ' + this); } this.valid = frame && frame.width && frame.height && this.baseTexture.source && this.baseTexture.hasLoaded; - if (this.trim) { + 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) { + if (this.valid) + { this._updateUvs(); } } @@ -168,11 +181,13 @@ * * @private */ -Texture.prototype.onBaseTextureLoaded = function () { +Texture.prototype.onBaseTextureLoaded = function () +{ var baseTexture = this.baseTexture; baseTexture.removeEventListener('loaded', this.onLoaded); - if (this.noFrame) { + if (this.noFrame) + { this.frame = new math.Rectangle(0, 0, baseTexture.width, baseTexture.height); } @@ -184,8 +199,10 @@ * * @param destroyBase {boolean} Whether to destroy the base texture as well */ -Texture.prototype.destroy = function (destroyBase) { - if (destroyBase) { +Texture.prototype.destroy = function (destroyBase) +{ + if (destroyBase) + { this.baseTexture.destroy(); } @@ -197,8 +214,10 @@ * * @private */ -Texture.prototype._updateUvs = function () { - if (!this._uvs) { +Texture.prototype._updateUvs = function () +{ + if (!this._uvs) + { this._uvs = new TextureUvs(); } @@ -229,10 +248,12 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return Texture */ -Texture.fromImage = function (imageUrl, crossorigin, scaleMode) { +Texture.fromImage = function (imageUrl, crossorigin, scaleMode) +{ var texture = utils.TextureCache[imageUrl]; - if (!texture) { + if (!texture) + { texture = new Texture(BaseTexture.fromImage(imageUrl, crossorigin, scaleMode)); utils.TextureCache[imageUrl] = texture; } @@ -248,9 +269,11 @@ * @param frameId {string} The frame id of the texture * @return Texture */ -Texture.fromFrame = function (frameId) { +Texture.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache '); } return texture; @@ -264,7 +287,8 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return {Texture} */ -Texture.fromCanvas = function (canvas, scaleMode) { +Texture.fromCanvas = function (canvas, scaleMode) +{ return new Texture(BaseTexture.fromCanvas(canvas, scaleMode)); }; @@ -276,7 +300,8 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return {Texture} A Texture */ -Texture.fromVideo = function (video, scaleMode) { +Texture.fromVideo = function (video, scaleMode) +{ return new Texture(VideoBaseTexture.baseTextureFromVideo(video, scaleMode)); }; @@ -287,7 +312,8 @@ * @param texture {Texture} The Texture to add to the cache. * @param id {string} The id that the texture will be stored against. */ -Texture.addTextureToCache = function (texture, id) { +Texture.addTextureToCache = function (texture, id) +{ utils.TextureCache[id] = texture; }; @@ -298,7 +324,8 @@ * @param id {string} The id of the texture to be removed * @return {Texture} The texture that was removed */ -Texture.removeTextureFromCache = function (id) { +Texture.removeTextureFromCache = function (id) +{ var texture = utils.TextureCache[id]; delete utils.TextureCache[id]; diff --git a/src/core/textures/TextureUvs.js b/src/core/textures/TextureUvs.js index b9bbb58..5424d52 100644 --- a/src/core/textures/TextureUvs.js +++ b/src/core/textures/TextureUvs.js @@ -1,4 +1,5 @@ -function TextureUvs() { +function TextureUvs() +{ this.x0 = 0; this.y0 = 0; diff --git a/src/core/display/DisplayObject.js b/src/core/display/DisplayObject.js index 66ebc3c..20e778c 100644 --- a/src/core/display/DisplayObject.js +++ b/src/core/display/DisplayObject.js @@ -7,7 +7,8 @@ * @class * @namespace PIXI */ -function DisplayObject() { +function DisplayObject() +{ /** * The coordinate of the object relative to the local coordinates of the parent. * @@ -152,10 +153,12 @@ * @memberof DisplayObject# */ x: { - get: function () { + get: function () + { return this.position.x; }, - set: function (value) { + set: function (value) + { this.position.x = value; } }, @@ -167,10 +170,12 @@ * @memberof DisplayObject# */ y: { - get: function () { + get: function () + { return this.position.y; }, - set: function (value) { + set: function (value) + { this.position.y = value; } }, @@ -183,11 +188,13 @@ * @readonly */ worldVisible: { - get: function () { + get: function () + { var item = this; do { - if (!item.visible) { + if (!item.visible) + { return false; } @@ -207,17 +214,21 @@ * @memberof DisplayObject# */ mask: { - get: function () { + get: function () + { return this._mask; }, - set: function (value) { - if (this._mask) { + set: function (value) + { + if (this._mask) + { this._mask.isMask = false; } this._mask = value; - if (this._mask) { + if (this._mask) + { this._mask.isMask = true; } } @@ -232,18 +243,23 @@ * @memberof DisplayObject# */ filters: { - get: function () { + get: function () + { return this._filters; }, - set: function (value) { - if (value) { + set: function (value) + { + if (value) + { // now put all the passes in one place.. var passes = []; - for (var i = 0; i < value.length; i++) { + for (var i = 0; i < value.length; i++) + { var filterPasses = value[i].passes; - for (var j = 0; j < filterPasses.length; j++) { + for (var j = 0; j < filterPasses.length; j++) + { passes.push(filterPasses[j]); } } @@ -264,8 +280,9 @@ * * @private */ -DisplayObject.prototype.updateTransform = function () { - +DisplayObject.prototype.updateTransform = function () +{ + // create some matrix refs for easy access var pt = this.parent.worldTransform; var wt = this.worldTransform; @@ -274,9 +291,11 @@ var a, b, c, d, tx, ty; // so if rotation is between 0 then we can simplify the multiplication process.. - if (this.rotation % math.PI_2) { + if (this.rotation % math.PI_2) + { // 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) { + if (this.rotation !== this.rotationCache) + { this.rotationCache = this.rotation; this._sr = Math.sin(this.rotation); this._cr = Math.cos(this.rotation); @@ -291,7 +310,8 @@ ty = this.position.y; // check for pivot.. not often used so geared towards that fact! - if (this.pivot.x || this.pivot.y) { + 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; } @@ -304,7 +324,8 @@ wt.tx = tx * pt.a + ty * pt.c + pt.tx; wt.ty = tx * pt.b + ty * pt.d + pt.ty; } - else { + else + { // lets do the fast version as we know there is no rotation.. a = this.scale.x; d = this.scale.y; @@ -333,7 +354,8 @@ * @param matrix {Matrix} * @return {Rectangle} the rectangular bounding area */ -DisplayObject.prototype.getBounds = function (/* matrix */) { +DisplayObject.prototype.getBounds = function (/* matrix */) +{ return math.Rectangle.EMPTY; }; @@ -342,7 +364,8 @@ * * @return {Rectangle} the rectangular bounding area */ -DisplayObject.prototype.getLocalBounds = function () { +DisplayObject.prototype.getLocalBounds = function () +{ return this.getBounds(math.Matrix.IDENTITY); }; @@ -352,7 +375,8 @@ * @param position {Point} The world origin to calculate from * @return {Point} A point object representing the position of this object */ -DisplayObject.prototype.toGlobal = function (position) { +DisplayObject.prototype.toGlobal = function (position) +{ // don't need to u[date the lot this.displayObjectUpdateTransform(); return this.worldTransform.apply(position); @@ -365,8 +389,10 @@ * @param [from] {DisplayObject} The DisplayObject to calculate the global position from * @return {Point} A point object representing the position of this object */ -DisplayObject.prototype.toLocal = function (position, from) { - if (from) { +DisplayObject.prototype.toLocal = function (position, from) +{ + if (from) + { position = from.toGlobal(position); } @@ -381,7 +407,8 @@ * @param renderer {WebGLRenderer} The renderer * @private */ -DisplayObject.prototype.renderWebGL = function (/* renderer */) { +DisplayObject.prototype.renderWebGL = function (/* renderer */) +{ // OVERWRITE; }; @@ -391,6 +418,7 @@ * @param renderer {CanvasRenderer} The renderer * @private */ -DisplayObject.prototype.renderCanvas = function (/* renderer */) { +DisplayObject.prototype.renderCanvas = function (/* renderer */) +{ // OVERWRITE; }; diff --git a/src/core/display/DisplayObjectContainer.js b/src/core/display/DisplayObjectContainer.js index 689f40b..4625ee8 100644 --- a/src/core/display/DisplayObjectContainer.js +++ b/src/core/display/DisplayObjectContainer.js @@ -12,7 +12,8 @@ * @extends DisplayObject * @namespace PIXI */ -function DisplayObjectContainer() { +function DisplayObjectContainer() +{ DisplayObject.call(this); /** @@ -47,17 +48,21 @@ * @memberof DisplayObjectContainer# */ width: { - get: function () { + get: function () + { return this.scale.x * this.getLocalBounds().width; }, - set: function (value) { + set: function (value) + { var width = this.getLocalBounds().width; - if(width !== 0) { + if(width !== 0) + { this.scale.x = value / width; } - else { + else + { this.scale.x = 1; } @@ -73,17 +78,21 @@ * @memberof DisplayObjectContainer# */ height: { - get: function () { + get: function () + { return this.scale.y * this.getLocalBounds().height; }, - set: function (value) { + set: function (value) + { var height = this.getLocalBounds().height; - if (height !== 0) { + if (height !== 0) + { this.scale.y = value / height ; } - else { + else + { this.scale.y = 1; } @@ -100,18 +109,23 @@ * @memberof DisplayObject# */ cacheAsBitmap: { - get: function () { + get: function () + { return this._cacheAsBitmap; }, - set: function (value) { - if (this._cacheAsBitmap === value) { + set: function (value) + { + if (this._cacheAsBitmap === value) + { return; } - if (value) { + if (value) + { this._generateCachedSprite(); } - else { + else + { this._destroyCachedSprite(); } @@ -126,7 +140,8 @@ * @param child {DisplayObject} The DisplayObject to add to the container * @return {DisplayObject} The child that was added. */ -DisplayObjectContainer.prototype.addChild = function (child) { +DisplayObjectContainer.prototype.addChild = function (child) +{ return this.addChildAt(child, this.children.length); }; @@ -137,14 +152,18 @@ * @param index {Number} The index to place the child in * @return {DisplayObject} The child that was added. */ -DisplayObjectContainer.prototype.addChildAt = function (child, index) { +DisplayObjectContainer.prototype.addChildAt = function (child, index) +{ // prevent adding self as child - if (child === this) { + if (child === this) + { return; } - if (index >= 0 && index <= this.children.length) { - if (child.parent) { + if (index >= 0 && index <= this.children.length) + { + if (child.parent) + { child.parent.removeChild(child); } @@ -154,7 +173,8 @@ return child; } - else { + else + { throw new Error(child + 'addChildAt: The index '+ index +' supplied is out of bounds ' + this.children.length); } }; @@ -165,15 +185,18 @@ * @param child {DisplayObject} * @param child2 {DisplayObject} */ -DisplayObjectContainer.prototype.swapChildren = function (child, child2) { - if (child === child2) { +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) { + if (index1 < 0 || index2 < 0) + { throw new Error('swapChildren: Both the supplied DisplayObjects must be a child of the caller.'); } @@ -187,10 +210,12 @@ * @param child {DisplayObject} The DisplayObject instance to identify * @return {Number} The index position of the child display object to identify */ -DisplayObjectContainer.prototype.getChildIndex = function (child) { +DisplayObjectContainer.prototype.getChildIndex = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { throw new Error('The supplied DisplayObject must be a child of the caller'); } @@ -203,8 +228,10 @@ * @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 */ -DisplayObjectContainer.prototype.setChildIndex = function (child, index) { - if (index < 0 || index >= this.children.length) { +DisplayObjectContainer.prototype.setChildIndex = function (child, index) +{ + if (index < 0 || index >= this.children.length) + { throw new Error('The supplied index is out of bounds'); } @@ -220,8 +247,10 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child at the given index, if any. */ -DisplayObjectContainer.prototype.getChildAt = function (index) { - if (index < 0 || index >= this.children.length) { +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'); } @@ -234,10 +263,12 @@ * @param child {DisplayObject} The DisplayObject to remove * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChild = function (child) { +DisplayObjectContainer.prototype.removeChild = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { return; } @@ -250,7 +281,8 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChildAt = function (index) { +DisplayObjectContainer.prototype.removeChildAt = function (index) +{ var child = this.getChildAt(index); child.parent = null; @@ -265,24 +297,29 @@ * @param beginIndex {Number} The beginning position. Default value is 0. * @param endIndex {Number} The ending position. Default value is size of the container. */ -DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) { +DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) +{ var begin = beginIndex || 0; var end = typeof endIndex === 'number' ? endIndex : this.children.length; var range = end - begin; - if (range > 0 && range <= end) { + if (range > 0 && range <= end) + { var removed = this.children.splice(begin, range); - for (var i = 0; i < removed.length; ++i) { + for (var i = 0; i < removed.length; ++i) + { removed[i].parent = null; } return removed; } - else if (range === 0 && this.children.length === 0) { + else if (range === 0 && this.children.length === 0) + { return []; } - else { + else + { throw new RangeError('removeChildren: numeric values are outside the acceptable range.'); } }; @@ -291,7 +328,8 @@ * Generates and updates the cached sprite for this object. * */ -DisplayObjectContainer.prototype.updateCachedSprite = function () { +DisplayObjectContainer.prototype.updateCachedSprite = function () +{ this._generateCachedSprite(); }; @@ -304,7 +342,8 @@ * @param renderer {CanvasRenderer|WebGLRenderer} The renderer used to generate the texture. * @return {Texture} a texture of the graphics object */ -DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) { +DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) +{ var bounds = this.getLocalBounds(); var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0, renderer, scaleMode, resolution); @@ -322,18 +361,22 @@ * * @private */ -DisplayObjectContainer.prototype.updateTransform = function () { - if (!this.visible) { +DisplayObjectContainer.prototype.updateTransform = function () +{ + if (!this.visible) + { return; } this.displayObjectUpdateTransform(); - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { return; } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } }; @@ -346,8 +389,10 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getBounds = function () { - if (this.children.length === 0) { +DisplayObjectContainer.prototype.getBounds = function () +{ + if (this.children.length === 0) + { return math.Rectangle.EMPTY; } @@ -365,10 +410,12 @@ var childVisible = false; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -386,7 +433,8 @@ maxY = maxY > childMaxY ? maxY : childMaxY; } - if (!childVisible) { + if (!childVisible) + { return math.Rectangle.EMPTY; } @@ -407,12 +455,14 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getLocalBounds = function () { +DisplayObjectContainer.prototype.getLocalBounds = function () +{ var matrixCache = this.worldTransform; this.worldTransform = math.Matrix.IDENTITY; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } @@ -428,13 +478,16 @@ * * @param renderer {WebGLRenderer} The renderer */ -DisplayObjectContainer.prototype.renderWebGL = function (renderer) { +DisplayObjectContainer.prototype.renderWebGL = function (renderer) +{ // if the object is not visible or the alpha is 0 then no need to render this element - if (!this.visible || this.alpha <= 0) { + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } @@ -442,14 +495,17 @@ var i, j; // do a quick check to see if this element has a mask or a filter. - if (this._mask || this._filters) { + if (this._mask || this._filters) + { // push filter first as we need to ensure the stencil buffer is correct for any masking - if (this._filters) { + if (this._filters) + { renderer.spriteBatch.flush(); renderer.filterManager.pushFilter(this._filterBlock); } - if (this._mask) { + if (this._mask) + { renderer.spriteBatch.stop(); renderer.maskManager.pushMask(this.mask, renderer); renderer.spriteBatch.start(); @@ -459,36 +515,42 @@ this._renderWebGL(renderer); // now loop through the children and make sure they get rendered - for (i = 0, j = this.children.length; i < j; i++) { + for (i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderWebGL(renderer); } // time to stop the sprite batch as either a mask element or a filter draw will happen next renderer.spriteBatch.stop(); - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(this._mask, renderer); } - if (this._filters) { + if (this._filters) + { renderer.filterManager.popFilter(); } renderer.spriteBatch.start(); } - else { + else + { this._renderWebGL(renderer); // simple render children! - for (i = 0, j = this.children.length; i < j; ++i) { + for (i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderWebGL(renderer); } } }; -DisplayObjectContainer.prototype._renderWebGL = function (renderer) { +DisplayObjectContainer.prototype._renderWebGL = function (renderer) +{ // this is where content itself gets renderd.. @@ -499,25 +561,31 @@ * * @param renderer {CanvasRenderer} The renderer */ -DisplayObjectContainer.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0) { +DisplayObjectContainer.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -528,13 +596,16 @@ * @param renderer {WebGLRenderer|CanvasRenderer} The renderer * @private */ -DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) { +DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) +{ this._cachedSprite.worldAlpha = this.worldAlpha; - if (renderer.gl) { + if (renderer.gl) + { this._cachedSprite.renderWebGL(renderer); } - else { + else + { this._cachedSprite.renderCanvas(renderer); } }; @@ -544,10 +615,12 @@ * * @private */ -DisplayObjectContainer.prototype._generateCachedSprite = function () { +DisplayObjectContainer.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { // TODO - RenderTexture now *requires* a renderer instance, so this is like broken // because `renderer` isn't actually in scope here :P var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0); @@ -555,7 +628,8 @@ this._cachedSprite = new Sprite(renderTexture); this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.texture.resize(bounds.width | 0, bounds.height | 0); } @@ -580,8 +654,10 @@ * * @private */ -DisplayObjectContainer.prototype._destroyCachedSprite = function () { - if (!this._cachedSprite) { +DisplayObjectContainer.prototype._destroyCachedSprite = function () +{ + if (!this._cachedSprite) + { return; } diff --git a/src/core/display/Sprite.js b/src/core/display/Sprite.js index 707da24..5862aef 100644 --- a/src/core/display/Sprite.js +++ b/src/core/display/Sprite.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param texture {Texture} The texture for this sprite */ -function Sprite(texture) { +function Sprite(texture) +{ DisplayObjectContainer.call(this); /** @@ -85,12 +86,14 @@ this.texture = texture || Texture.EMPTY; } -Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) { +Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) +{ DisplayObjectContainer.prototype.destroy.call(this); this.anchor = null; - if (destroyTexture) { + if (destroyTexture) + { this._texture.destroy(destroyBaseTexture); } @@ -111,10 +114,12 @@ * @memberof Sprite# */ width: { - get: function () { + get: function () + { return this.scale.x * this.texture.frame.width; }, - set: function (value) { + set: function (value) + { this.scale.x = value / this.texture.frame.width; this._width = value; } @@ -127,10 +132,12 @@ * @memberof Sprite# */ height: { - get: function () { + get: function () + { return this.scale.y * this.texture.frame.height; }, - set: function (value) { + set: function (value) + { this.scale.y = value / this.texture.frame.height; this._height = value; } @@ -143,23 +150,29 @@ * @memberof Sprite# */ texture: { - get: function () { + get: function () + { return this._texture; }, - set: function (value) { - if (this._texture === value) { + set: function (value) + { + if (this._texture === value) + { return; } this._texture = value; this.cachedTint = 0xFFFFFF; - if (value) { + if (value) + { // wait for the texture to load - if (value.baseTexture.hasLoaded) { + if (value.baseTexture.hasLoaded) + { this._onTextureUpdate(); } - else { + else + { value.once('update', this._onTextureUpdate.bind(this)); } } @@ -172,18 +185,22 @@ * * @private */ -Sprite.prototype._onTextureUpdate = function () { +Sprite.prototype._onTextureUpdate = function () +{ // so if _width is 0 then width was not set.. - if (this._width) { + if (this._width) + { this.scale.x = this._width / this.texture.frame.width; } - if (this._height) { + if (this._height) + { this.scale.y = this._height / this.texture.frame.height; } }; -Sprite.prototype._renderWebGL = function (renderer) { +Sprite.prototype._renderWebGL = function (renderer) +{ // this is where content gets renderd.. // watch this space for a little render state manager.. @@ -197,7 +214,8 @@ * @param matrix {Matrix} the transformation matrix of the sprite * @return {Rectangle} the framing rectangle */ -Sprite.prototype.getBounds = function (matrix) { +Sprite.prototype.getBounds = function (matrix) +{ var width = this.texture.frame.width; var height = this.texture.frame.height; @@ -224,11 +242,13 @@ if(b === 0 && c === 0) { // scale may be negative! - if (a < 0) { + if (a < 0) + { a *= -1; } - if (d < 0) { + if (d < 0) + { d *= -1; } @@ -293,28 +313,34 @@ * * @param renderer {CanvasRenderer} The renderer */ -Sprite.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) { +Sprite.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) + { return; } - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; renderer.context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } // Ignore null sources - if (this.texture.valid) { + if (this.texture.valid) + { var resolution = this.texture.baseTexture.resolution / renderer.resolution; renderer.context.globalAlpha = this.worldAlpha; // If smoothingEnabled is supported and we need to change the smoothing property for this texture - if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) { + if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) + { renderer.scaleMode = this.texture.baseTexture.scaleMode; renderer.context[renderer.smoothProperty] = (renderer.scaleMode === CONST.scaleModes.LINEAR); } @@ -324,7 +350,8 @@ var dy = (this.texture.trim ? this.texture.trim.y : 0) - (this.anchor.y * this.texture.trim.height); // Allow for pixel rounding - if (renderer.roundPixels) { + if (renderer.roundPixels) + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -337,7 +364,8 @@ dx = dx | 0; dy = dy | 0; } - else { + else + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -348,8 +376,10 @@ ); } - if (this.tint !== 0xFFFFFF) { - if (this.cachedTint !== this.tint) { + if (this.tint !== 0xFFFFFF) + { + if (this.cachedTint !== this.tint) + { this.cachedTint = this.tint; // TODO clean up caching - how to clean up the caches? @@ -368,7 +398,8 @@ this.texture.crop.height / resolution ); } - else { + else + { renderer.context.drawImage( this.texture.baseTexture.source, this.texture.crop.x, @@ -383,11 +414,13 @@ } } - for (var i = 0, j = this.children.length; i < j; i++) { + for (var i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -402,10 +435,12 @@ * @param frameId {String} The frame Id of the texture in the cache * @return {Sprite} A new Sprite using a texture from the texture cache matching the frameId */ -Sprite.fromFrame = function (frameId) { +Sprite.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache' + this); } @@ -420,6 +455,7 @@ * @param imageId {String} The image url of the texture * @return {Sprite} A new Sprite using a texture from the texture cache matching the image id */ -Sprite.fromImage = function (imageId, crossorigin, scaleMode) { +Sprite.fromImage = function (imageId, crossorigin, scaleMode) +{ return new Sprite(Texture.fromImage(imageId, crossorigin, scaleMode)); }; diff --git a/src/core/display/SpriteBatch.js b/src/core/display/SpriteBatch.js index 3187777..c196fef 100644 --- a/src/core/display/SpriteBatch.js +++ b/src/core/display/SpriteBatch.js @@ -12,7 +12,8 @@ * ```js * var container = new SpriteBatch(); * - * for(var i = 0; i < 100; ++i) { + * for(var i = 0; i < 100; ++i) + * { * var sprite = new PIXI.Sprite.fromImage("myImage.png"); * container.addChild(sprite); * } @@ -25,7 +26,8 @@ */ //TODO RENAME to PARTICLE CONTAINER? -function SpriteBatch() { +function SpriteBatch() +{ DisplayObjectContainer.call(this); } @@ -38,7 +40,8 @@ * * @private */ -SpriteBatch.prototype.updateTransform = function () { +SpriteBatch.prototype.updateTransform = function () +{ // TODO don't need to! this.displayObjectUpdateTransform(); // PIXI.DisplayObjectContainer.prototype.updateTransform.call( this ); @@ -50,8 +53,10 @@ * @param renderer {WebGLRenderer} The webgl renderer * @private */ -SpriteBatch.prototype.renderWebGL = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderWebGL = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -71,8 +76,10 @@ * @param renderer {CanvasRenderer} The canvas renderer * @private */ -SpriteBatch.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -84,10 +91,12 @@ this.displayObjectUpdateTransform(); - for (var i = 0; i < this.children.length; ++i) { + for (var i = 0; i < this.children.length; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -95,9 +104,11 @@ context.globalAlpha = this.worldAlpha * child.alpha; - if (child.rotation % (Math.PI * 2) === 0) { + if (child.rotation % (Math.PI * 2) === 0) + { // this is the fastest way to optimise! - if rotation is 0 then we can avoid any kind of setTransform call - if (isRotated) { + if (isRotated) + { context.setTransform( transform.a, transform.b, @@ -122,8 +133,10 @@ frame.height * child.scale.y ); } - else { - if (!isRotated) { + else + { + if (!isRotated) + { isRotated = true; } @@ -131,7 +144,8 @@ var childTransform = child.worldTransform; - if (renderer.roundPixels) { + if (renderer.roundPixels) + { context.setTransform( childTransform.a, childTransform.b, @@ -141,7 +155,8 @@ childTransform.ty | 0 ); } - else { + else + { context.setTransform( childTransform.a, childTransform.b, diff --git a/src/core/index.js b/src/core/index.js index 3954b6f..eb4a82b 100644 --- a/src/core/index.js +++ b/src/core/index.js @@ -58,11 +58,13 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRenderer: function (width, height, options, noWebGL) { + autoDetectRenderer: function (width, height, options, noWebGL) + { width = width || 800; height = height || 600; - if (!noWebGL && require('webgl-enabled')()) { + if (!noWebGL && require('webgl-enabled')()) + { return new core.WebGLRenderer(width, height, options); } @@ -87,7 +89,8 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRecommendedRenderer: function (width, height, options) { + autoDetectRecommendedRenderer: function (width, height, options) + { var isAndroid = /Android/i.test(navigator.userAgent); return core.autoDetectRenderer(width, height, options, isAndroid); diff --git a/src/core/math/Matrix.js b/src/core/math/Matrix.js index c2f87e2..2ff4848 100644 --- a/src/core/math/Matrix.js +++ b/src/core/math/Matrix.js @@ -10,7 +10,8 @@ * @class * @namespace PIXI */ -function Matrix() { +function Matrix() +{ /** * @member {number} * @default 1 @@ -63,7 +64,8 @@ * * @param array {number[]} The array that the matrix will be populated from. */ -Matrix.prototype.fromArray = function (array) { +Matrix.prototype.fromArray = function (array) +{ this.a = array[0]; this.b = array[1]; this.c = array[3]; @@ -78,14 +80,17 @@ * @param transpose {boolean} Whether we need to transpose the matrix or not * @return {number[]} the newly created array which contains the matrix */ -Matrix.prototype.toArray = function (transpose) { - if (!this.array) { +Matrix.prototype.toArray = function (transpose) +{ + if (!this.array) + { this.array = new Float32Array(9); } var array = this.array; - if (transpose) { + if (transpose) + { array[0] = this.a; array[1] = this.b; array[2] = 0; @@ -96,7 +101,8 @@ array[7] = this.ty; array[8] = 1; } - else { + else + { array[0] = this.a; array[1] = this.c; array[2] = this.tx; @@ -119,7 +125,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, transformed through this matrix */ -Matrix.prototype.apply = function (pos, newPos) { +Matrix.prototype.apply = function (pos, newPos) +{ newPos = newPos || new Point(); newPos.x = this.a * pos.x + this.c * pos.y + this.tx; @@ -136,7 +143,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, inverse-transformed through this matrix */ -Matrix.prototype.applyInverse = function (pos, newPos) { +Matrix.prototype.applyInverse = function (pos, newPos) +{ newPos = newPos || new Point(); var id = 1 / (this.a * this.d + this.c * -this.b); @@ -154,7 +162,8 @@ * @param {number} y * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.translate = function (x, y) { +Matrix.prototype.translate = function (x, y) +{ this.tx += x; this.ty += y; @@ -168,7 +177,8 @@ * @param {number} y The amount to scale vertically * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.scale = function (x, y) { +Matrix.prototype.scale = function (x, y) +{ this.a *= x; this.d *= y; this.c *= x; @@ -186,7 +196,8 @@ * @param {number} angle - The angle in radians. * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.rotate = function (angle) { +Matrix.prototype.rotate = function (angle) +{ var cos = Math.cos( angle ); var sin = Math.sin( angle ); @@ -210,7 +221,8 @@ * @param {Matrix} matrix * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.append = function (matrix) { +Matrix.prototype.append = function (matrix) +{ var a1 = this.a; var b1 = this.b; var c1 = this.c; @@ -232,7 +244,8 @@ * * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.identity = function () { +Matrix.prototype.identity = function () +{ this.a = 1; this.b = 0; this.c = 0; diff --git a/src/core/math/Point.js b/src/core/math/Point.js index 7565b2d..632f346 100644 --- a/src/core/math/Point.js +++ b/src/core/math/Point.js @@ -7,7 +7,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -function Point(x, y) { +function Point(x, y) +{ /** * @member {number} * @default 0 @@ -29,7 +30,8 @@ * * @return {Point} a copy of the point */ -Point.prototype.clone = function () { +Point.prototype.clone = function () +{ return new Point(this.x, this.y); }; @@ -40,7 +42,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -Point.prototype.set = function (x, y) { +Point.prototype.set = function (x, y) +{ this.x = x || 0; this.y = y || ( (y !== 0) ? this.x : 0 ) ; }; diff --git a/src/core/math/shapes/Circle.js b/src/core/math/shapes/Circle.js index 69cfdc9..4d76efc 100644 --- a/src/core/math/shapes/Circle.js +++ b/src/core/math/shapes/Circle.js @@ -10,7 +10,8 @@ * @param y {number} The Y coordinate of the center of this circle * @param radius {number} The radius of the circle */ -function Circle(x, y, radius) { +function Circle(x, y, radius) +{ /** * @member {number} * @default 0 @@ -46,7 +47,8 @@ * @method clone * @return {Circle} a copy of the Circle */ -Circle.prototype.clone = function () { +Circle.prototype.clone = function () +{ return new Circle(this.x, this.y, this.radius); }; @@ -58,8 +60,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Circle */ -Circle.prototype.contains = function (x, y) { - if (this.radius <= 0) { +Circle.prototype.contains = function (x, y) +{ + if (this.radius <= 0) + { return false; } @@ -79,6 +83,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Circle.prototype.getBounds = function () { +Circle.prototype.getBounds = function () +{ return new Rectangle(this.x - this.radius, this.y - this.radius, this.radius * 2, this.radius * 2); }; diff --git a/src/core/math/shapes/Ellipse.js b/src/core/math/shapes/Ellipse.js index 4f2d066..fefd01a 100644 --- a/src/core/math/shapes/Ellipse.js +++ b/src/core/math/shapes/Ellipse.js @@ -11,7 +11,8 @@ * @param width {number} The half width of this ellipse * @param height {number} The half height of this ellipse */ -function Ellipse(x, y, width, height) { +function Ellipse(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -53,7 +54,8 @@ * @method clone * @return {Ellipse} a copy of the ellipse */ -Ellipse.prototype.clone = function () { +Ellipse.prototype.clone = function () +{ return new Ellipse(this.x, this.y, this.width, this.height); }; @@ -65,8 +67,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coords are within this ellipse */ -Ellipse.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Ellipse.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } @@ -86,6 +90,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Ellipse.prototype.getBounds = function () { +Ellipse.prototype.getBounds = function () +{ return new Rectangle(this.x - this.width, this.y - this.height, this.width, this.height); }; diff --git a/src/core/math/shapes/Polygon.js b/src/core/math/shapes/Polygon.js index ae89148..fea6d37 100644 --- a/src/core/math/shapes/Polygon.js +++ b/src/core/math/shapes/Polygon.js @@ -10,16 +10,20 @@ * arguments passed can be flat x,y values e.g. `new Polygon(x,y, x,y, x,y, ...)` where `x` and `y` are * Numbers. */ -function Polygon(points) { +function Polygon(points) +{ //if points isn't an array, use arguments as the array - if (!(points instanceof Array)) { + if (!(points instanceof Array)) + { points = Array.prototype.slice.call(arguments); } //if this is a flat array of numbers, convert it to points - if (points[0] instanceof Point) { + if (points[0] instanceof Point) + { var p = []; - for (var i = 0, il = points.length; i < il; i++) { + for (var i = 0, il = points.length; i < il; i++) + { p.push(points[i].x, points[i].y); } @@ -51,7 +55,8 @@ * * @return {Polygon} a copy of the polygon */ -Polygon.prototype.clone = function () { +Polygon.prototype.clone = function () +{ return new Polygon(this.points.slice()); }; @@ -62,19 +67,22 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this polygon */ -Polygon.prototype.contains = function (x, y) { +Polygon.prototype.contains = function (x, y) +{ var inside = false; // use some raycasting to test hits // https://github.com/substack/point-in-polygon/blob/master/index.js var length = this.points.length / 2; - for (var i = 0, j = length - 1; i < length; j = i++) { + for (var i = 0, j = length - 1; i < length; j = i++) + { var xi = this.points[i * 2], yi = this.points[i * 2 + 1], xj = this.points[j * 2], yj = this.points[j * 2 + 1], intersect = ((yi > y) !== (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi); - if (intersect) { + if (intersect) + { inside = !inside; } } diff --git a/src/core/math/shapes/Rectangle.js b/src/core/math/shapes/Rectangle.js index 16ac62a..4008b68 100644 --- a/src/core/math/shapes/Rectangle.js +++ b/src/core/math/shapes/Rectangle.js @@ -10,7 +10,8 @@ * @param width {number} The overall width of this rectangle * @param height {number} The overall height of this rectangle */ -function Rectangle(x, y, width, height) { +function Rectangle(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -60,7 +61,8 @@ * * @return {Rectangle} a copy of the rectangle */ -Rectangle.prototype.clone = function () { +Rectangle.prototype.clone = function () +{ return new Rectangle(this.x, this.y, this.width, this.height); }; @@ -71,13 +73,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rectangle */ -Rectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Rectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/math/shapes/RoundedRectangle.js b/src/core/math/shapes/RoundedRectangle.js index 27d286e..7bf6411 100644 --- a/src/core/math/shapes/RoundedRectangle.js +++ b/src/core/math/shapes/RoundedRectangle.js @@ -11,7 +11,8 @@ * @param height {number} The overall height of this rounded rectangle * @param radius {number} Controls the radius of the rounded corners */ -function RoundedRectangle(x, y, width, height, radius) { +function RoundedRectangle(x, y, width, height, radius) +{ /** * @member {number} * @default 0 @@ -58,7 +59,8 @@ * * @return {RoundedRectangle} a copy of the rounded rectangle */ -RoundedRectangle.prototype.clone = function () { +RoundedRectangle.prototype.clone = function () +{ return new RoundedRectangle(this.x, this.y, this.width, this.height, this.radius); }; @@ -69,13 +71,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rounded Rectangle */ -RoundedRectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +RoundedRectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/primitives/Graphics.js b/src/core/primitives/Graphics.js index 261c534..e902d2a 100644 --- a/src/core/primitives/Graphics.js +++ b/src/core/primitives/Graphics.js @@ -16,7 +16,8 @@ * @extends DisplayObjectContainer * @namespace PIXI */ -function Graphics() { +function Graphics() +{ DisplayObjectContainer.call(this); this.renderable = true; @@ -154,16 +155,20 @@ * @private */ cacheAsBitmap: { - get: function () { + get: function () + { return this._cacheAsBitmap; }, - set: function (value) { + set: function (value) + { this._cacheAsBitmap = value; - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._generateCachedSprite(); } - else { + else + { this.destroyCachedSprite(); this.dirty = true; } @@ -176,7 +181,8 @@ * * @return {Graphics} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ var clone = new Graphics(); clone.renderable = this.renderable; @@ -192,7 +198,8 @@ clone.cachedSpriteDirty = this.cachedSpriteDirty; // copy graphics data - for (var i = 0; i < this.graphicsData.length; ++i) { + for (var i = 0; i < this.graphicsData.length; ++i) + { clone.graphicsData.push(this.graphicsData.clone()); } @@ -211,17 +218,21 @@ * @param alpha {number} alpha of the line to draw, will update the objects stored style * @return {Graphics} */ -Graphics.prototype.lineStyle = function (lineWidth, color, alpha) { +Graphics.prototype.lineStyle = function (lineWidth, color, alpha) +{ this.lineWidth = lineWidth || 0; this.lineColor = color || 0; this.lineAlpha = (arguments.length < 3) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length) + { // halfway through a line? start a new one! this.drawShape( new math.Polygon( this.currentPath.shape.points.slice(-2) )); } - else { + else + { // otherwise its empty so lets just set the line properties this.currentPath.lineWidth = this.lineWidth; this.currentPath.lineColor = this.lineColor; @@ -239,7 +250,8 @@ * @param y {number} the Y coordinate to move to * @return {Graphics} */ -Graphics.prototype.moveTo = function (x, y) { +Graphics.prototype.moveTo = function (x, y) +{ this.drawShape(new math.Polygon([x,y])); return this; @@ -253,7 +265,8 @@ * @param y {number} the Y coordinate to draw to * @return {Graphics} */ -Graphics.prototype.lineTo = function (x, y) { +Graphics.prototype.lineTo = function (x, y) +{ this.currentPath.shape.points.push(x, y); this.dirty = true; @@ -270,13 +283,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -285,7 +302,8 @@ n = 20, points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { this.moveTo(0, 0); } @@ -293,7 +311,8 @@ var fromY = points[points.length-1]; var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; xa = fromX + ( (cpX - fromX) * j ); @@ -319,13 +338,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -342,7 +365,8 @@ var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; dt = (1 - j); @@ -373,13 +397,17 @@ * @param radius {number} The radius of the arc * @return {Graphics} */ -Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points.push(x1, y1); } } - else { + else + { this.moveTo(x1, y1); } @@ -392,12 +420,15 @@ b2 = x2 - x1, mm = Math.abs(a1 * b2 - b1 * a2); - if (mm < 1.0e-8 || radius === 0) { - if (points[points.length-2] !== x1 || points[points.length-1] !== y1) { + if (mm < 1.0e-8 || radius === 0) + { + if (points[points.length-2] !== x1 || points[points.length-1] !== y1) + { points.push(x1, y1); } } - else { + else + { var dd = a1 * a1 + b1 * b1, cc = a2 * a2 + b2 * b2, tt = a1 * a2 + b1 * b2, @@ -433,42 +464,51 @@ * @param anticlockwise {boolean} Optional. Specifies whether the drawing should be counterclockwise or clockwise. False is default, and indicates clockwise, while true indicates counter-clockwise. * @return {Graphics} */ -Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) { +Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) +{ var startX = cx + Math.cos(startAngle) * radius; var startY = cy + Math.sin(startAngle) * radius; var points; // TODO - This if-else makes no sense. It uses currentPath in the else where it doesn't exist... - if (this.currentPath) { + if (this.currentPath) + { points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { points.push(startX, startY); } - else if (points[points.length-2] !== startX || points[points.length-1] !== startY) { + else if (points[points.length-2] !== startX || points[points.length-1] !== startY) + { points.push(startX, startY); } } - else { + else + { this.moveTo(startX, startY); points = this.currentPath.shape.points; } - if (startAngle === endAngle) { + if (startAngle === endAngle) + { return this; } - if (!anticlockwise && endAngle <= startAngle) { + if (!anticlockwise && endAngle <= startAngle) + { endAngle += Math.PI * 2; } - else if (anticlockwise && startAngle <= endAngle) { + else if (anticlockwise && startAngle <= endAngle) + { startAngle += Math.PI * 2; } var sweep = anticlockwise ? (startAngle - endAngle) *-1 : (endAngle - startAngle); var segs = (Math.abs(sweep)/ (Math.PI * 2)) * 40; - if (sweep === 0) { + if (sweep === 0) + { return this; } @@ -482,7 +522,8 @@ var remainder = ( segMinus % 1 ) / segMinus; - for (var i = 0; i <= segMinus; ++i) { + for (var i = 0; i <= segMinus; ++i) + { var real = i + remainder * i; var angle = ((theta) + startAngle + (theta2 * real)); @@ -506,13 +547,16 @@ * @param alpha {number} the alpha of the fill * @return {Graphics} */ -Graphics.prototype.beginFill = function (color, alpha) { +Graphics.prototype.beginFill = function (color, alpha) +{ this.filling = true; this.fillColor = color || 0; this.fillAlpha = (alpha === undefined) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length <= 2) + { this.currentPath.fill = this.filling; this.currentPath.fillColor = this.fillColor; this.currentPath.fillAlpha = this.fillAlpha; @@ -526,7 +570,8 @@ * * @return {Graphics} */ -Graphics.prototype.endFill = function () { +Graphics.prototype.endFill = function () +{ this.filling = false; this.fillColor = null; this.fillAlpha = 1; @@ -542,7 +587,8 @@ * @param height {number} The height of the rectangle * @return {Graphics} */ -Graphics.prototype.drawRect = function ( x, y, width, height ) { +Graphics.prototype.drawRect = function ( x, y, width, height ) +{ this.drawShape(new math.Rectangle(x,y, width, height)); return this; @@ -556,7 +602,8 @@ * @param height {number} The height of the rectangle * @param radius {number} Radius of the rectangle corners */ -Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) { +Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) +{ this.drawShape(new math.RoundedRectangle(x, y, width, height, radius)); return this; @@ -570,7 +617,8 @@ * @param radius {number} The radius of the circle * @return {Graphics} */ -Graphics.prototype.drawCircle = function (x, y, radius) { +Graphics.prototype.drawCircle = function (x, y, radius) +{ this.drawShape(new math.Circle(x,y, radius)); return this; @@ -585,7 +633,8 @@ * @param height {number} The half height of the ellipse * @return {Graphics} */ -Graphics.prototype.drawEllipse = function (x, y, width, height) { +Graphics.prototype.drawEllipse = function (x, y, width, height) +{ this.drawShape(new math.Ellipse(x, y, width, height)); return this; @@ -597,8 +646,10 @@ * @param path {Array} The path data used to construct the polygon. * @return {Graphics} */ -Graphics.prototype.drawPolygon = function (path) { - if (!(path instanceof Array)) { +Graphics.prototype.drawPolygon = function (path) +{ + if (!(path instanceof Array)) + { path = Array.prototype.slice.call(arguments); } @@ -612,7 +663,8 @@ * * @return {Graphics} */ -Graphics.prototype.clear = function () { +Graphics.prototype.clear = function () +{ this.lineWidth = 0; this.filling = false; @@ -631,7 +683,8 @@ * @param scaleMode {number} Should be one of the scaleMode consts * @return {Texture} a texture of the graphics object */ -Graphics.prototype.generateTexture = function (resolution, scaleMode) { +Graphics.prototype.generateTexture = function (resolution, scaleMode) +{ resolution = resolution || 1; var bounds = this.getBounds(); @@ -655,17 +708,21 @@ * * @param renderer {WebGLRenderer} */ -Graphics.prototype._renderWebGL = function (renderer) { +Graphics.prototype._renderWebGL = function (renderer) +{ // if the sprite is not visible or the alpha is 0 then no need to render this element - if (this.isMask === true) { + if (this.isMask === true) + { return; } // this code may still be needed so leaving for now.. - // + // /* - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture on the gpu too! @@ -681,17 +738,24 @@ return; } - */ - - // check if the webgl graphic needs to be updated - if (this.glDirty) { - this.dirty = true; - this.glDirty = false; - } + else */ - renderer.setObjectRendererer(renderer.graphicsRenderer); - renderer.graphicsRenderer.render(this); + renderer.spriteBatch.stop(); + renderer.blendModeManager.setBlendMode(this.blendMode); + // check blend mode + renderer.blendModeManager.setBlendMode( this.blendMode ); + + // check if the webgl graphic needs to be updated + if (this.glDirty) + { + this.dirty = true; + this.glDirty = false; + } + + WebGLGraphics.renderGraphics(this, renderer); + + renderer.spriteBatch.start(); }; /** @@ -700,14 +764,18 @@ * @param renderer {CanvasRenderer} * @private */ -Graphics.prototype.renderCanvas = function (renderer) { +Graphics.prototype.renderCanvas = function (renderer) +{ // 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.isMask === true) { + if (!this.visible || this.alpha <= 0 || this.isMask === true) + { return; } - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture @@ -723,16 +791,19 @@ return; } - else { + else + { var context = renderer.context; var transform = this.worldTransform; - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } @@ -748,11 +819,13 @@ CanvasGraphics.renderGraphics(this, context); - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } } @@ -763,13 +836,16 @@ * * @return {Rectangle} the rectangular bounding area */ -Graphics.prototype.getBounds = function (matrix) { +Graphics.prototype.getBounds = function (matrix) +{ // return an empty object if the item is a mask! - if (this.isMask) { + if (this.isMask) + { return math.Rectangle.EMPTY; } - if (this.dirty) { + if (this.dirty) + { this.updateLocalBounds(); this.glDirty = true; @@ -841,23 +917,27 @@ * Update the bounds of the object * */ -Graphics.prototype.updateLocalBounds = function () { +Graphics.prototype.updateLocalBounds = function () +{ var minX = Infinity; var maxX = -Infinity; var minY = Infinity; var maxY = -Infinity; - if (this.graphicsData.length) { + if (this.graphicsData.length) + { var shape, points, x, y, w, h; - for (var i = 0; i < this.graphicsData.length; i++) { + for (var i = 0; i < this.graphicsData.length; i++) + { var data = this.graphicsData[i]; var type = data.type; var lineWidth = data.lineWidth; shape = data.shape; - if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) { + if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) + { x = shape.x - lineWidth/2; y = shape.y - lineWidth/2; w = shape.width + lineWidth; @@ -869,7 +949,8 @@ minY = y < minY ? y : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.CIRC) { + else if (type === CONST.SHAPES.CIRC) + { x = shape.x; y = shape.y; w = shape.radius + lineWidth/2; @@ -881,7 +962,8 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.ELIP) { + else if (type === CONST.SHAPES.ELIP) + { x = shape.x; y = shape.y; w = shape.width + lineWidth/2; @@ -893,11 +975,13 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else { + else + { // POLY points = shape.points; - for (var j = 0; j < points.length; j += 2) { + for (var j = 0; j < points.length; j += 2) + { x = points[j]; y = points[j+1]; @@ -910,7 +994,8 @@ } } } - else { + else + { minX = 0; maxX = 0; minY = 0; @@ -931,10 +1016,12 @@ * * @private */ -Graphics.prototype._generateCachedSprite = function () { +Graphics.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { var canvasBuffer = new CanvasBuffer(bounds.width, bounds.height); var texture = Texture.fromCanvas(canvasBuffer.canvas); @@ -943,7 +1030,8 @@ this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.buffer.resize(bounds.width, bounds.height); } @@ -968,7 +1056,8 @@ * * @private */ -Graphics.prototype.updateCachedSpriteTexture = function () { +Graphics.prototype.updateCachedSpriteTexture = function () +{ var cachedSprite = this._cachedSprite; var texture = cachedSprite.texture; var canvas = cachedSprite.buffer.canvas; @@ -989,7 +1078,8 @@ * Destroys a previous cached sprite. * */ -Graphics.prototype.destroyCachedSprite = function () { +Graphics.prototype.destroyCachedSprite = function () +{ this._cachedSprite.texture.destroy(true); // let the gc collect the unused sprite @@ -1003,10 +1093,13 @@ * @param {Circle|Rectangle|Ellipse|Line|Polygon} shape The Shape object to draw. * @return {GraphicsData} The generated GraphicsData object. */ -Graphics.prototype.drawShape = function (shape) { - if (this.currentPath) { +Graphics.prototype.drawShape = function (shape) +{ + if (this.currentPath) + { // check current path! - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath.shape.points.length <= 2) + { this.graphicsData.pop(); } } @@ -1017,7 +1110,8 @@ this.graphicsData.push(data); - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { data.shape.closed = this.filling; this.currentPath = data; } diff --git a/src/core/primitives/GraphicsData.js b/src/core/primitives/GraphicsData.js index 99decbe..788f6f2 100644 --- a/src/core/primitives/GraphicsData.js +++ b/src/core/primitives/GraphicsData.js @@ -4,7 +4,8 @@ * @class * @namespace PIXI */ -function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) { +function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) +{ this.lineWidth = lineWidth; this.lineColor = lineColor; this.lineAlpha = lineAlpha; @@ -27,7 +28,8 @@ * * @return {GraphicsData} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ return new GraphicsData( this.lineWidth, this.lineColor, diff --git a/src/core/renderers/canvas/CanvasRenderer.js b/src/core/renderers/canvas/CanvasRenderer.js index 15a0978..7aebd44 100644 --- a/src/core/renderers/canvas/CanvasRenderer.js +++ b/src/core/renderers/canvas/CanvasRenderer.js @@ -17,17 +17,22 @@ * @param [options.resolution=1] {number} the resolution of the renderer retina would be 2 * @param [options.clearBeforeRender=true] {boolean} This sets if the CanvasRenderer will clear the canvas or not before the new render pass. */ -function CanvasRenderer(width, height, options) { +function CanvasRenderer(width, height, options) +{ utils.sayHello('Canvas'); - if (options) { - for (var i in CONST.defaultRenderOptions) { - if (typeof options[i] === 'undefined') { + if (options) + { + for (var i in CONST.defaultRenderOptions) + { + if (typeof options[i] === 'undefined') + { options[i] = CONST.defaultRenderOptions[i]; } } } - else { + else + { options = CONST.defaultRenderOptions; } @@ -156,19 +161,24 @@ this.smoothProperty = null; - if (this.context.imageSmoothingEnabled) { + if (this.context.imageSmoothingEnabled) + { this.smoothProperty = 'imageSmoothingEnabled'; } - else if (this.context.webkitImageSmoothingEnabled) { + else if (this.context.webkitImageSmoothingEnabled) + { this.smoothProperty = 'webkitImageSmoothingEnabled'; } - else if (this.context.mozImageSmoothingEnabled) { + else if (this.context.mozImageSmoothingEnabled) + { this.smoothProperty = 'mozImageSmoothingEnabled'; } - else if (this.context.oImageSmoothingEnabled) { + else if (this.context.oImageSmoothingEnabled) + { this.smoothProperty = 'oImageSmoothingEnabled'; } - else if (this.context.msImageSmoothingEnabled) { + else if (this.context.msImageSmoothingEnabled) + { this.smoothProperty = 'msImageSmoothingEnabled'; } @@ -193,10 +203,12 @@ * @memberof CanvasRenderer# */ backgroundColor: { - get: function () { + get: function () + { return this._backgroundColor; }, - set: function (val) { + set: function (val) + { this._backgroundColor = val; this._backgroundColorString = utils.hex2string(val); } @@ -208,7 +220,8 @@ * * @param object {DisplayObject} the object to be rendered */ -CanvasRenderer.prototype.render = function (object) { +CanvasRenderer.prototype.render = function (object) +{ object.updateTransform(); this.context.setTransform(1,0,0,1,0,0); @@ -218,16 +231,20 @@ this.currentBlendMode = CONST.blendModes.NORMAL; this.context.globalCompositeOperation = this.blendModes[CONST.blendModes.NORMAL]; - if (navigator.isCocoonJS && this.view.screencanvas) { + if (navigator.isCocoonJS && this.view.screencanvas) + { this.context.fillStyle = 'black'; this.context.clear(); } - if (this.clearBeforeRender) { - if (this.transparent) { + if (this.clearBeforeRender) + { + if (this.transparent) + { this.context.clearRect(0, 0, this.width, this.height); } - else { + else + { this.context.fillStyle = this._backgroundColorString; this.context.fillRect(0, 0, this.width , this.height); } @@ -241,8 +258,10 @@ * * @param [removeView=false] {boolean} Removes the Canvas element from the DOM. */ -CanvasRenderer.prototype.destroy = function (removeView) { - if (removeView && this.view.parent) { +CanvasRenderer.prototype.destroy = function (removeView) +{ + if (removeView && this.view.parent) + { this.view.parent.removeChild(this.view); } @@ -257,14 +276,16 @@ * @param width {number} the new width of the canvas view * @param height {number} the new height of the canvas view */ -CanvasRenderer.prototype.resize = function (width, height) { +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) { + if (this.autoResize) + { this.view.style.width = this.width / this.resolution + 'px'; this.view.style.height = this.height / this.resolution + 'px'; } @@ -276,7 +297,8 @@ * @param displayObject {DisplayObject} The displayObject to render * @private */ -CanvasRenderer.prototype.renderDisplayObject = function (displayObject) { +CanvasRenderer.prototype.renderDisplayObject = function (displayObject) +{ displayObject.renderCanvas(this); }; @@ -285,11 +307,14 @@ * * @private */ -CanvasRenderer.prototype._mapBlendModes = function () { - if (!this.blendModes) { +CanvasRenderer.prototype._mapBlendModes = function () +{ + if (!this.blendModes) + { this.blendModes = {}; - if (utils.canUseNewCanvasBlendModes()) { + if (utils.canUseNewCanvasBlendModes()) + { this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? this.blendModes[CONST.blendModes.MULTIPLY] = 'multiply'; @@ -308,7 +333,8 @@ this.blendModes[CONST.blendModes.COLOR] = 'color'; this.blendModes[CONST.blendModes.LUMINOSITY] = 'luminosity'; } - else { + else + { // this means that the browser does not support the cool new blend modes in canvas 'cough' ie 'cough' this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? diff --git a/src/core/renderers/canvas/utils/CanvasBuffer.js b/src/core/renderers/canvas/utils/CanvasBuffer.js index ebe5d47..b183a66 100644 --- a/src/core/renderers/canvas/utils/CanvasBuffer.js +++ b/src/core/renderers/canvas/utils/CanvasBuffer.js @@ -6,7 +6,8 @@ * @param width {number} the width for the newly created canvas * @param height {number} the height for the newly created canvas */ -function CanvasBuffer(width, height) { +function CanvasBuffer(width, height) +{ /** * The Canvas object that belongs to this CanvasBuffer. * @@ -36,10 +37,12 @@ * @memberof CanvasBuffer# */ width: { - get: function () { + get: function () + { return this.canvas.width; }, - set: function (val) { + set: function (val) + { this.canvas.width = val; } }, @@ -50,10 +53,12 @@ * @memberof CanvasBuffer# */ height: { - get: function () { + get: function () + { return this.canvas.height; }, - set: function (val) { + set: function (val) + { this.canvas.height = val; } } @@ -64,7 +69,8 @@ * * @private */ -CanvasBuffer.prototype.clear = function () { +CanvasBuffer.prototype.clear = function () +{ this.context.setTransform(1, 0, 0, 1, 0, 0); this.context.clearRect(0,0, this.canvas.width, this.canvas.height); }; @@ -75,7 +81,8 @@ * @param width {number} the new width of the canvas * @param height {number} the new height of the canvas */ -CanvasBuffer.prototype.resize = function (width, height) { +CanvasBuffer.prototype.resize = function (width, height) +{ this.canvas.width = width; this.canvas.height = height; }; diff --git a/src/core/renderers/canvas/utils/CanvasGraphics.js b/src/core/renderers/canvas/utils/CanvasGraphics.js index c7eaa2a..3f2a91f 100644 --- a/src/core/renderers/canvas/utils/CanvasGraphics.js +++ b/src/core/renderers/canvas/utils/CanvasGraphics.js @@ -13,15 +13,18 @@ * @param graphics {Graphics} the actual graphics object to render * @param context {CanvasRenderingContext2D} the 2d drawing method of the canvas */ -CanvasGraphics.renderGraphics = function (graphics, context) { +CanvasGraphics.renderGraphics = function (graphics, context) +{ var worldAlpha = graphics.worldAlpha; - if (graphics.dirty) { + if (graphics.dirty) + { this.updateGraphicsTint(graphics); graphics.dirty = false; } - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; @@ -30,69 +33,82 @@ context.lineWidth = data.lineWidth; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { context.beginPath(); var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } - if (shape.closed) { + if (shape.closed) + { context.lineTo(points[0], points[1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fillRect(shape.x, shape.y, shape.width, shape.height); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.strokeRect(shape.x, shape.y, shape.width, shape.height); } } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.beginPath(); context.arc(shape.x, shape.y, shape.radius,0,2*Math.PI); context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas var w = shape.width * 2; @@ -119,18 +135,21 @@ context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; var width = shape.width; @@ -152,13 +171,15 @@ context.quadraticCurveTo(rx, ry, rx, ry + radius); context.closePath(); - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); @@ -174,45 +195,54 @@ * @param graphics {Graphics} the graphics which will be used as a mask * @param context {CanvasRenderingContext2D} the context 2d method of the canvas */ -CanvasGraphics.renderGraphicsMask = function (graphics, context) { +CanvasGraphics.renderGraphicsMask = function (graphics, context) +{ var len = graphics.graphicsData.length; - if (len === 0) { + if (len === 0) + { return; } context.beginPath(); - for (var i = 0; i < len; i++) { + for (var i = 0; i < len; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { context.rect(shape.x, shape.y, shape.width, shape.height); context.closePath(); } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.arc(shape.x, shape.y, shape.radius, 0, 2 * Math.PI); context.closePath(); } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas @@ -237,7 +267,8 @@ context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); context.closePath(); } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; @@ -262,8 +293,10 @@ } }; -CanvasGraphics.updateGraphicsTint = function (graphics) { - if (graphics.tint === 0xFFFFFF) { +CanvasGraphics.updateGraphicsTint = function (graphics) +{ + if (graphics.tint === 0xFFFFFF) + { return; } @@ -271,7 +304,8 @@ var tintG = (graphics.tint >> 8 & 0xFF) / 255; var tintB = (graphics.tint & 0xFF)/ 255; - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var fillColor = data.fillColor | 0; diff --git a/src/core/renderers/canvas/utils/CanvasMaskManager.js b/src/core/renderers/canvas/utils/CanvasMaskManager.js index e04a733..9827d36 100644 --- a/src/core/renderers/canvas/utils/CanvasMaskManager.js +++ b/src/core/renderers/canvas/utils/CanvasMaskManager.js @@ -6,7 +6,8 @@ * @class * @namespace PIXI */ -function CanvasMaskManager() {} +function CanvasMaskManager() +{} CanvasMaskManager.prototype.constructor = CanvasMaskManager; module.exports = CanvasMaskManager; @@ -17,7 +18,8 @@ * @param maskData {object} the maskData that will be pushed * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.pushMask = function (maskData, renderer) { +CanvasMaskManager.prototype.pushMask = function (maskData, renderer) +{ renderer.context.save(); var cacheAlpha = maskData.alpha; @@ -45,6 +47,7 @@ * * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.popMask = function (renderer) { +CanvasMaskManager.prototype.popMask = function (renderer) +{ renderer.context.restore(); }; diff --git a/src/core/renderers/canvas/utils/CanvasTinter.js b/src/core/renderers/canvas/utils/CanvasTinter.js index 17e0529..d2fb1bc 100644 --- a/src/core/renderers/canvas/utils/CanvasTinter.js +++ b/src/core/renderers/canvas/utils/CanvasTinter.js @@ -14,7 +14,8 @@ * @param color {number} the color to use to tint the sprite with * @return {HTMLCanvasElement} The tinted canvas */ -CanvasTinter.getTintedTexture = function (sprite, color) { +CanvasTinter.getTintedTexture = function (sprite, color) +{ var texture = sprite.texture; color = CanvasTinter.roundColor(color); @@ -23,7 +24,8 @@ texture.tintCache = texture.tintCache || {}; - if (texture.tintCache[stringColor]) { + if (texture.tintCache[stringColor]) + { return texture.tintCache[stringColor]; } @@ -33,14 +35,16 @@ //CanvasTinter.tintWithPerPixel(texture, stringColor, canvas); CanvasTinter.tintMethod(texture, color, canvas); - if (CanvasTinter.convertTintToImage) { + if (CanvasTinter.convertTintToImage) + { // is this better? var tintImage = new Image(); tintImage.src = canvas.toDataURL(); texture.tintCache[stringColor] = tintImage; } - else { + else + { texture.tintCache[stringColor] = canvas; // if we are not converting the texture to an image then we need to lose the reference to the canvas CanvasTinter.canvas = null; @@ -56,7 +60,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithMultiply = function (texture, color, canvas) { +CanvasTinter.tintWithMultiply = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -104,7 +109,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithOverlay = function (texture, color, canvas) { +CanvasTinter.tintWithOverlay = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -139,7 +145,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithPerPixel = function (texture, color, canvas) { +CanvasTinter.tintWithPerPixel = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -167,7 +174,8 @@ var pixels = pixelData.data; - for (var i = 0; i < pixels.length; i += 4) { + for (var i = 0; i < pixels.length; i += 4) + { pixels[i+0] *= r; pixels[i+1] *= g; pixels[i+2] *= b; @@ -181,7 +189,8 @@ * * @param color {number} the color to round, should be a hex color */ -CanvasTinter.roundColor = function (color) { +CanvasTinter.roundColor = function (color) +{ var step = CanvasTinter.cacheStepsPerColorChannel; var rgbValues = utils.hex2rgb(color); diff --git a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js index 9f2f89a..35edbaf 100644 --- a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js +++ b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLBlendModeManager(renderer) { +function WebGLBlendModeManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -23,8 +24,10 @@ * * @param blendMode {number} the blendMode, should be a Pixi const, such as BlendModes.ADD */ -WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) { - if (this.currentBlendMode === blendMode) { +WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) +{ + if (this.currentBlendMode === blendMode) + { return false; } diff --git a/src/core/renderers/webgl/managers/WebGLFilterManager.js b/src/core/renderers/webgl/managers/WebGLFilterManager.js index 1179258..2dac048 100644 --- a/src/core/renderers/webgl/managers/WebGLFilterManager.js +++ b/src/core/renderers/webgl/managers/WebGLFilterManager.js @@ -7,7 +7,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLFilterManager(renderer) { +function WebGLFilterManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -32,7 +33,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.texturePool.length = 0; self.initShaderBuffers(); }); @@ -46,7 +48,8 @@ * @param renderer {WebGLRenderer} * @param buffer {ArrayBuffer} */ -WebGLFilterManager.prototype.begin = function (buffer) { +WebGLFilterManager.prototype.begin = function (buffer) +{ this.defaultShader = this.renderer.shaderManager.defaultShader; this.width = this.renderer.projection.x * 2; @@ -60,7 +63,8 @@ * * @param filterBlock {object} the filter that will be pushed to the current filter stack */ -WebGLFilterManager.prototype.pushFilter = function (filterBlock) { +WebGLFilterManager.prototype.pushFilter = function (filterBlock) +{ var gl = this.renderer.gl; var projection = this.renderer.projection; @@ -78,10 +82,12 @@ this.offsetY += filterBlock._filterArea.y; var texture = this.texturePool.pop(); - if (!texture) { + if (!texture) + { texture = new FilterTexture(this.renderer.gl, this.width, this.height); } - else { + else + { texture.resize(this.width, this.height); } @@ -98,29 +104,35 @@ var localX = filterArea.x, localY = filterArea.y; - if (filterArea.x < 0) { + if (filterArea.x < 0) + { filterArea.width += filterArea.x; filterArea.x = 0; } - if (filterArea.y < 0) { + if (filterArea.y < 0) + { filterArea.height += filterArea.y; filterArea.y = 0; } - if (localX + filterArea.width > this.width) { + if (localX + filterArea.width > this.width) + { filterArea.width = this.width - localX; } - if (localY + filterArea.height > this.height) { + if (localY + filterArea.height > this.height) + { filterArea.height = this.height - localY; } - if (filterArea.width < 0) { + if (filterArea.width < 0) + { filterArea.width = 0; } - if (filterArea.height < 0) { + if (filterArea.height < 0) + { filterArea.height = 0; } @@ -154,7 +166,8 @@ * Removes the last filter from the filter stack and doesn't return it. * */ -WebGLFilterManager.prototype.popFilter = function () { +WebGLFilterManager.prototype.popFilter = function () +{ var gl = this.renderer.gl; var filterBlock = this.filterStack.pop(); @@ -163,7 +176,8 @@ var projection = this.renderer.projection; var offset = this.renderer.offset; - if (filterBlock.filterPasses.length > 1) { + if (filterBlock.filterPasses.length > 1) + { gl.viewport(0, 0, filterArea.width, filterArea.height); gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); @@ -193,7 +207,8 @@ var inputTexture = texture; var outputTexture = this.texturePool.pop(); - if (!outputTexture) { + if (!outputTexture) + { outputTexture = new FilterTexture(this.renderer.gl, this.width, this.height); } outputTexture.resize(this.width, this.height); @@ -204,7 +219,8 @@ gl.disable(gl.BLEND); - for (var i = 0; i < filterBlock.filterPasses.length-1; i++) { + for (var i = 0; i < filterBlock.filterPasses.length-1; i++) + { var filterPass = filterBlock.filterPasses[i]; gl.bindFramebuffer(gl.FRAMEBUFFER, outputTexture.frameBuffer ); @@ -243,10 +259,12 @@ var buffer = this.buffer; // time to render the filters texture to the previous scene - if (this.filterStack.length === 0) { + if (this.filterStack.length === 0) + { gl.colorMask(true, true, true, true);//this.transparent); } - else { + else + { var currentFilter = this.filterStack[this.filterStack.length-1]; filterArea = currentFilter._filterArea; @@ -332,13 +350,15 @@ * @param width {number} the horizontal range of the filter * @param height {number} the vertical range of the filter */ -WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) { +WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) +{ // use program var gl = this.renderer.gl; var shader = filter.shaders[gl.id]; - if (!shader) { + if (!shader) + { shader = new Shader(gl); shader.fragmentSrc = filter.fragmentSrc; @@ -356,7 +376,8 @@ gl.uniform2f(shader.projectionVector, width/2, -height/2); gl.uniform2f(shader.offsetVector, 0,0); - if (filter.uniforms.dimensions) { + 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]; @@ -386,7 +407,8 @@ * Initialises the shader buffers. * */ -WebGLFilterManager.prototype.initShaderBuffers = function () { +WebGLFilterManager.prototype.initShaderBuffers = function () +{ var gl = this.renderer.gl; // create some buffers @@ -432,7 +454,8 @@ * Destroys the filter and removes it from the filter stack. * */ -WebGLFilterManager.prototype.destroy = function () { +WebGLFilterManager.prototype.destroy = function () +{ var gl = this.renderer.gl; this.filterStack = null; @@ -441,7 +464,8 @@ this.offsetY = 0; // destroy textures - for (var i = 0; i < this.texturePool.length; i++) { + for (var i = 0; i < this.texturePool.length; i++) + { this.texturePool[i].destroy(); } diff --git a/src/core/renderers/webgl/managers/WebGLManager.js b/src/core/renderers/webgl/managers/WebGLManager.js index 9d47b5c..c30cd51 100644 --- a/src/core/renderers/webgl/managers/WebGLManager.js +++ b/src/core/renderers/webgl/managers/WebGLManager.js @@ -3,7 +3,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLManager(renderer) { +function WebGLManager(renderer) +{ /** * The renderer this manager works for. * @@ -15,6 +16,7 @@ WebGLManager.prototype.constructor = WebGLManager; module.exports = WebGLManager; -WebGLManager.prototype.destroy = function () { +WebGLManager.prototype.destroy = function () +{ this.renderer = null; }; diff --git a/src/core/renderers/webgl/managers/WebGLMaskManager.js b/src/core/renderers/webgl/managers/WebGLMaskManager.js index 2f90b64..e568812 100644 --- a/src/core/renderers/webgl/managers/WebGLMaskManager.js +++ b/src/core/renderers/webgl/managers/WebGLMaskManager.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLMaskManager(renderer) { +function WebGLMaskManager(renderer) +{ WebGLManager.call(this, renderer); } @@ -19,12 +20,15 @@ * * @param maskData {any[]} */ -WebGLMaskManager.prototype.pushMask = function (maskData) { - if (maskData.dirty) { +WebGLMaskManager.prototype.pushMask = function (maskData) +{ + if (maskData.dirty) + { WebGLGraphics.updateGraphics(maskData, this.renderer.gl); } - if (!maskData._webGL[this.renderer.gl.id].data.length) { + if (!maskData._webGL[this.renderer.gl.id].data.length) + { return; } @@ -36,6 +40,7 @@ * * @param maskData {any[]} */ -WebGLMaskManager.prototype.popMask = function (maskData) { +WebGLMaskManager.prototype.popMask = function (maskData) +{ this.renderer.stencilManager.popStencil(maskData, maskData._webGL[this.renderer.gl.id].data[0], this.renderer); }; diff --git a/src/core/renderers/webgl/managers/WebGLShaderManager.js b/src/core/renderers/webgl/managers/WebGLShaderManager.js index fef071c..90c6477 100644 --- a/src/core/renderers/webgl/managers/WebGLShaderManager.js +++ b/src/core/renderers/webgl/managers/WebGLShaderManager.js @@ -10,7 +10,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLShaderManager(renderer) { +function WebGLShaderManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -28,7 +29,8 @@ */ this.tempAttribState = []; - for (var i = 0; i < this.maxAttibs; i++) { + for (var i = 0; i < this.maxAttibs; i++) + { this.attribState[i] = false; } @@ -66,7 +68,8 @@ // listen for context and update necessary shaders var self = this; - this.renderer.on('context', function (event) { + this.renderer.on('context', function (event) + { var gl = event.data; // this shader is used for rendering primitives @@ -97,29 +100,36 @@ * * @param attribs {Array} attribs */ -WebGLShaderManager.prototype.setAttribs = function (attribs) { +WebGLShaderManager.prototype.setAttribs = function (attribs) +{ // reset temp state var i; - for (i = 0; i < this.tempAttribState.length; i++) { + for (i = 0; i < this.tempAttribState.length; i++) + { this.tempAttribState[i] = false; } // set the new attribs - for (var a in attribs) { + for (var a in attribs) + { this.tempAttribState[attribs[a]] = true; } var gl = this.renderer.gl; - for (i = 0; i < this.attribState.length; i++) { - if (this.attribState[i] !== this.tempAttribState[i]) { + for (i = 0; i < this.attribState.length; i++) + { + if (this.attribState[i] !== this.tempAttribState[i]) + { this.attribState[i] = this.tempAttribState[i]; - if (this.attribState[i]) { + if (this.attribState[i]) + { gl.enableVertexAttribArray(i); } - else { + else + { gl.disableVertexAttribArray(i); } } @@ -131,8 +141,10 @@ * * @param shader {Any} */ -WebGLShaderManager.prototype.setShader = function (shader) { - if (this._currentId === shader.uuid) { +WebGLShaderManager.prototype.setShader = function (shader) +{ + if (this._currentId === shader.uuid) + { return false; } @@ -150,7 +162,8 @@ * Destroys this object. * */ -WebGLShaderManager.prototype.destroy = function () { +WebGLShaderManager.prototype.destroy = function () +{ this.attribState = null; this.tempAttribState = null; diff --git a/src/core/renderers/webgl/managers/WebGLStencilManager.js b/src/core/renderers/webgl/managers/WebGLStencilManager.js index 9ec6398..4cb0134 100644 --- a/src/core/renderers/webgl/managers/WebGLStencilManager.js +++ b/src/core/renderers/webgl/managers/WebGLStencilManager.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLStencilManager(renderer) { +function WebGLStencilManager(renderer) +{ WebGLManager.call(this, renderer); this.stencilStack = []; @@ -24,12 +25,14 @@ * @param graphics {Graphics} * @param webGLData {any[]} */ -WebGLStencilManager.prototype.pushStencil = function (graphics, webGLData) { +WebGLStencilManager.prototype.pushStencil = function (graphics, webGLData) +{ var gl = this.renderer.gl; this.bindGraphics(graphics, webGLData, this.renderer); - if (this.stencilStack.length === 0) { + if (this.stencilStack.length === 0) + { gl.enable(gl.STENCIL_TEST); gl.clear(gl.STENCIL_BUFFER_BIT); this.reverse = true; @@ -47,14 +50,17 @@ // draw the triangle strip! - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } @@ -62,31 +68,38 @@ // draw a quad to increment.. gl.drawElements(gl.TRIANGLE_FAN, 4, gl.UNSIGNED_SHORT, ( webGLData.indices.length - 4 ) * 2 ); - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); } this.reverse = !this.reverse; } - else { - if (!this.reverse) { + else + { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } - else { + 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) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); } } @@ -103,7 +116,8 @@ * @param graphics {Graphics} * @param webGLData {Array} */ -WebGLStencilManager.prototype.bindGraphics = function (graphics, webGLData) { +WebGLStencilManager.prototype.bindGraphics = function (graphics, webGLData) +{ //if (this._currentGraphics === graphics)return; this._currentGraphics = graphics; @@ -114,7 +128,8 @@ offset = this.renderer.offset, shader;// = this.renderer.shaderManager.primitiveShader; - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { shader = this.renderer.shaderManager.complexPrimitiveShader; this.renderer.shaderManager.setShader(shader); @@ -141,7 +156,8 @@ // set the index buffer! gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, webGLData.indexBuffer); } - else { + else + { //this.renderer.shaderManager.activatePrimitiveShader(); shader = this.renderer.shaderManager.primitiveShader; this.renderer.shaderManager.setShader( shader ); @@ -154,7 +170,7 @@ gl.uniform2f(shader.uniforms.offsetVector._location, -offset.x, -offset.y); gl.uniform3fv(shader.uniforms.tint._location, utils.hex2rgb(graphics.tint)); - + gl.uniform1f(shader.uniforms.alpha._location, graphics.worldAlpha); @@ -172,19 +188,22 @@ * @param graphics {Graphics} * @param webGLData {Array} */ -WebGLStencilManager.prototype.popStencil = function (graphics, webGLData) { +WebGLStencilManager.prototype.popStencil = function (graphics, webGLData) +{ var gl = this.renderer.gl; this.stencilStack.pop(); this.count--; - if (this.stencilStack.length === 0) { + if (this.stencilStack.length === 0) + { // the stack is empty! gl.disable(gl.STENCIL_TEST); } - else { + else + { var level = this.count; @@ -192,14 +211,17 @@ gl.colorMask(false, false, false, false); - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { this.reverse = !this.reverse; - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } @@ -213,31 +235,38 @@ // draw the triangle strip! gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); - if (!this.reverse) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); } } - else { + else + { // console.log("<<>>") - if (!this.reverse) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } - else { + 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) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); } } @@ -253,7 +282,8 @@ * Destroys the mask stack. * */ -WebGLStencilManager.prototype.destroy = function () { +WebGLStencilManager.prototype.destroy = function () +{ this.renderer = null; this.stencilStack = null; }; diff --git a/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js b/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js index 913ba5e..1ea7d19 100644 --- a/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js +++ b/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function ComplexPrimitiveShader(gl) { +function ComplexPrimitiveShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -24,7 +25,8 @@ 'uniform float flipY;', 'varying vec4 vColor;', - 'void main(void) {', + '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);', @@ -37,7 +39,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = vColor;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/FastShader.js b/src/core/renderers/webgl/shaders/FastShader.js index bd2e29a..2e5e060 100644 --- a/src/core/renderers/webgl/shaders/FastShader.js +++ b/src/core/renderers/webgl/shaders/FastShader.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function FastShader(gl) { +function FastShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -28,7 +29,8 @@ 'const vec2 center = vec2(-1.0, 1.0);', - 'void main(void) {', + 'void main(void) + {', ' vec2 v;', ' vec2 sv = aVertexPosition * aScale;', ' v.x = (sv.x) * cos(aRotation) - (sv.y) * sin(aRotation);', @@ -49,7 +51,8 @@ 'uniform sampler2D uSampler;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/PrimitiveShader.js b/src/core/renderers/webgl/shaders/PrimitiveShader.js index 6f25409..a25f54f 100644 --- a/src/core/renderers/webgl/shaders/PrimitiveShader.js +++ b/src/core/renderers/webgl/shaders/PrimitiveShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function PrimitiveShader(gl) { +function PrimitiveShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -23,7 +24,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + '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);', @@ -36,7 +38,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = vColor;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/Shader.js b/src/core/renderers/webgl/shaders/Shader.js index f8964f5..fd75ef5 100644 --- a/src/core/renderers/webgl/shaders/Shader.js +++ b/src/core/renderers/webgl/shaders/Shader.js @@ -6,7 +6,8 @@ * @param [fragmentSrc] {string} The source of the fragment shader. * @param [vertexSrc] {string} The source of the vertex shader. */ -function Shader(gl, vertexSrc, fragmentSrc, customUniforms, customAttributes) { +function Shader(gl, vertexSrc, fragmentSrc, customUniforms, customAttributes) +{ /** * @member {number} * @readonly @@ -33,7 +34,8 @@ dimensions: { type: '4f', value: new Float32Array(4) } }; - for (var u in customUniforms) { + for (var u in customUniforms) + { this.uniforms[u] = customUniforms[u]; } @@ -43,7 +45,8 @@ aColor: 0 }; - for (var a in customAttributes) { + for (var a in customAttributes) + { this.attributes[a] = customAttributes[a]; } @@ -66,7 +69,8 @@ 'const vec2 center = vec2(-1.0, 1.0);', - 'void main(void) {', + 'void main(void) + {', ' gl_Position = vec4( ((aVertexPosition + offsetVector) / projectionVector) + center , 0.0, 1.0);', ' vTextureCoord = aTextureCoord;', ' vColor = vec4(aColor.rgb * aColor.a, aColor.a);', @@ -85,7 +89,8 @@ 'uniform sampler2D uSampler;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;', '}' ].join('\n'); @@ -96,7 +101,8 @@ Shader.prototype.constructor = Shader; module.exports = Shader; -Shader.prototype.init = function () { +Shader.prototype.init = function () +{ this.compile(); this.gl.useProgram(this.program); @@ -105,14 +111,18 @@ this.cacheAttributeLocations(Object.keys(this.attributes)); }; -Shader.prototype.cacheUniformLocations = function (keys) { - for (var i = 0; i < keys.length; ++i) { +Shader.prototype.cacheUniformLocations = function (keys) +{ + for (var i = 0; i < keys.length; ++i) + { this.uniforms[keys[i]]._location = this.gl.getUniformLocation(this.program, keys[i]); } }; -Shader.prototype.cacheAttributeLocations = function (keys) { - for (var i = 0; i < keys.length; ++i) { +Shader.prototype.cacheAttributeLocations = function (keys) +{ + for (var i = 0; i < keys.length; ++i) + { this.attributes[keys[i]] = this.gl.getAttribLocation(this.program, keys[i]); } @@ -124,14 +134,16 @@ // 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.attributes.aColor === -1) { + // if (this.attributes.aColor === -1) + { // this.attributes.aColor = 2; // } // End worst hack eva // }; -Shader.prototype.compile = function () { +Shader.prototype.compile = function () +{ var gl = this.gl; var glVertShader = this._glCompile(gl.VERTEX_SHADER, this.vertexSrc); @@ -144,13 +156,15 @@ gl.linkProgram(program); // if linking fails, then log and cleanup - if (!gl.getProgramParameter(program, gl.LINK_STATUS)) { + if (!gl.getProgramParameter(program, gl.LINK_STATUS)) + { window.console.error('Pixi.js Error: Could not initialize shader.'); window.console.error('gl.VALIDATE_STATUS', gl.getProgramParameter(program, gl.VALIDATE_STATUS)); window.console.error('gl.getError()', gl.getError()); // if there is a program info log, log it - if (gl.getProgramInfoLog(program) !== '') { + if (gl.getProgramInfoLog(program) !== '') + { window.console.warn('Pixi.js Warning: gl.getProgramInfoLog()', gl.getProgramInfoLog(program)); } @@ -165,18 +179,21 @@ return (this.program = program); }; -Shader.prototype.syncUniforms = function () { +Shader.prototype.syncUniforms = function () +{ var gl = this.gl; this.textureCount = 1; - for (var key in this.uniforms) { + for (var key in this.uniforms) + { var uniform = this.uniforms[key], location = uniform._location, value = uniform.value, i, il; - switch (uniform.type) { + switch (uniform.type) + { // single int value case 'i': case '1i': @@ -282,7 +299,8 @@ // a Color Value case 'c': - if (typeof value === 'number') { + if (typeof value === 'number') + { value = utils.hex2rgb(value); } @@ -311,11 +329,13 @@ // array of 2D Point objects case 'v2v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(2 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 2] = value[i].x; uniform._array[i * 2 + 1] = value[i].y; } @@ -325,11 +345,13 @@ // array of 3D Point objects case 'v3v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(3 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 3] = value[i].x; uniform._array[i * 3 + 1] = value[i].y; uniform._array[i * 3 + 2] = value[i].z; @@ -341,11 +363,13 @@ // array of 4D Point objects case 'v4v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(4 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 4] = value[i].x; uniform._array[i * 4 + 1] = value[i].y; uniform._array[i * 4 + 2] = value[i].z; @@ -359,7 +383,8 @@ // PIXI.Texture case 't': case 'sampler2D': - if (!uniform.value || !uniform.value.baseTexture || !uniform.value.baseTexture.hasLoaded) { + if (!uniform.value || !uniform.value.baseTexture || !uniform.value.baseTexture.hasLoaded) + { break; } @@ -376,7 +401,8 @@ this.textureCount++; // initialize the texture if we haven't yet - if (!uniform._init) { + if (!uniform._init) + { this.initSampler2D(uniform); uniform._init = true; @@ -394,11 +420,13 @@ * Initialises a Sampler2D uniform (which may only be available later on after initUniforms once the texture has loaded) * */ -Shader.prototype.initSampler2D = function (uniform) { +Shader.prototype.initSampler2D = function (uniform) +{ var gl = this.gl; // Extended texture data - if (uniform.textureData) { + if (uniform.textureData) + { var data = uniform.textureData; // GLTexture = mag linear, min linear_mipmap_linear, wrap repeat + gl.generateMipmap(gl.TEXTURE_2D); @@ -417,14 +445,16 @@ var wrapT = (data.wrapT) ? data.wrapT : gl.CLAMP_TO_EDGE; var format = (data.luminance) ? gl.LUMINANCE : gl.RGBA; - if (data.repeat) { + if (data.repeat) + { wrapS = gl.REPEAT; wrapT = gl.REPEAT; } gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, !!data.flipY); - if (data.width) { + if (data.width) + { var width = (data.width) ? data.width : 512; var height = (data.height) ? data.height : 2; var border = (data.border) ? data.border : 0; @@ -432,7 +462,8 @@ // 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 { + 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); } @@ -448,7 +479,8 @@ * Destroys the shader. * */ -Shader.prototype.destroy = function () { +Shader.prototype.destroy = function () +{ this.gl.deleteProgram(this.program); this.gl = null; @@ -459,13 +491,15 @@ this.fragmentSrc = null; }; -Shader.prototype._glCompile = function (type, src) { +Shader.prototype._glCompile = function (type, src) +{ var shader = this.gl.createShader(type); this.gl.shaderSource(shader, src); this.gl.compileShader(shader); - if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) { + if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) + { window.console.log(this.gl.getShaderInfoLog(shader)); return null; } diff --git a/src/core/renderers/webgl/shaders/StripShader.js b/src/core/renderers/webgl/shaders/StripShader.js index 193f6e1..a7abcc6 100644 --- a/src/core/renderers/webgl/shaders/StripShader.js +++ b/src/core/renderers/webgl/shaders/StripShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function StripShader(gl) { +function StripShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -20,7 +21,8 @@ 'varying vec2 vTextureCoord;', - 'void main(void) {', + '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);', @@ -36,7 +38,8 @@ 'varying vec2 vTextureCoord;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vec2(vTextureCoord.x, vTextureCoord.y)) * alpha;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/utils/FilterTexture.js b/src/core/renderers/webgl/utils/FilterTexture.js index d2c8423..4433d44 100644 --- a/src/core/renderers/webgl/utils/FilterTexture.js +++ b/src/core/renderers/webgl/utils/FilterTexture.js @@ -8,7 +8,8 @@ * @param height {number} the vertical range of the filter * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values */ -function FilterTexture(gl, width, height, scaleMode) { +function FilterTexture(gl, width, height, scaleMode) +{ /** * @member {WebGLContext} */ @@ -59,7 +60,8 @@ * Clears the filter texture. * */ -FilterTexture.prototype.clear = function () { +FilterTexture.prototype.clear = function () +{ var gl = this.gl; gl.clearColor(0,0,0, 0); @@ -72,8 +74,10 @@ * @param width {number} the new width of the texture * @param height {number} the new height of the texture */ -FilterTexture.prototype.resize = function (width, height) { - if (this.width === width && this.height === height) { +FilterTexture.prototype.resize = function (width, height) +{ + if (this.width === width && this.height === height) + { return; } @@ -96,7 +100,8 @@ * Destroys the filter texture. * */ -FilterTexture.prototype.destroy = function () { +FilterTexture.prototype.destroy = function () +{ var gl = this.gl; gl.deleteFramebuffer( this.frameBuffer ); gl.deleteTexture( this.texture ); diff --git a/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js b/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js index c4721e9..a63f4d7 100644 --- a/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js +++ b/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js @@ -14,7 +14,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this sprite batch works for. */ -function WebGLFastSpriteBatch(renderer) { +function WebGLFastSpriteBatch(renderer) +{ /** * The renderer instance this sprite batch operates on. * @@ -91,7 +92,8 @@ */ this.lastIndexCount = 0; - for (var i=0, j=0; i < numIndices; i += 6, j += 4) { + 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; @@ -144,7 +146,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.setupContext(); }); } @@ -157,7 +160,8 @@ * * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLFastSpriteBatch.prototype.setupContext = function () { +WebGLFastSpriteBatch.prototype.setupContext = function () +{ var gl = this.renderer.gl; // create a couple of buffers @@ -177,7 +181,8 @@ /** * @param spriteBatch {SpriteBatch} The SpriteBatch container to prepare for. */ -WebGLFastSpriteBatch.prototype.begin = function (spriteBatch) { +WebGLFastSpriteBatch.prototype.begin = function (spriteBatch) +{ this.shader = this.renderer.shaderManager.fastShader; this.matrix = spriteBatch.worldTransform.toArray(true); @@ -187,33 +192,38 @@ /** */ -WebGLFastSpriteBatch.prototype.end = function () { +WebGLFastSpriteBatch.prototype.end = function () +{ this.flush(); }; /** * @param spriteBatch {SpriteBatch} The SpriteBatch container to render. */ -WebGLFastSpriteBatch.prototype.render = function (spriteBatch) { +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) { + if (!sprite.texture._uvs) + { return; } this.currentBaseTexture = sprite.texture.baseTexture; // check blend mode - if (sprite.blendMode !== this.renderer.blendModeManager.currentBlendMode) { + if (sprite.blendMode !== this.renderer.blendModeManager.currentBlendMode) + { this.flush(); this.renderer.blendModeManager.setBlendMode(sprite.blendMode); } - for (var i=0,j= children.length; i= this.size) { + if (this.currentBatchSize >= this.size) + { this.flush(); } }; @@ -362,29 +379,35 @@ /** * */ -WebGLFastSpriteBatch.prototype.flush = function () { +WebGLFastSpriteBatch.prototype.flush = function () +{ // If the batch is length 0 then return as there is nothing to draw - if (this.currentBatchSize === 0) { + if (this.currentBatchSize === 0) + { return; } var gl = this.renderer.gl; // bind the current texture - if (!this.currentBaseTexture._glTextures[gl.id]) { + if (!this.currentBaseTexture._glTextures[gl.id]) + { this.renderer.updateTexture(this.currentBaseTexture, gl); } //TODO-SHOUD THIS BE ELSE??!?!?! - else { + else + { gl.bindTexture(gl.TEXTURE_2D, this.currentBaseTexture._glTextures[gl.id]); } // upload the verts to the buffer - if (this.currentBatchSize > ( this.size * 0.5 ) ) { + if (this.currentBatchSize > ( this.size * 0.5 ) ) + { gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); } - else { + else + { var view = this.vertices.subarray(0, this.currentBatchSize * this.vertByteSize); gl.bufferSubData(gl.ARRAY_BUFFER, 0, view); @@ -405,14 +428,16 @@ * Ends the batch and flushes * */ -WebGLFastSpriteBatch.prototype.stop = function () { +WebGLFastSpriteBatch.prototype.stop = function () +{ this.flush(); }; /** * */ -WebGLFastSpriteBatch.prototype.start = function () { +WebGLFastSpriteBatch.prototype.start = function () +{ var gl = this.renderer.gl; // bind the main texture diff --git a/src/core/renderers/webgl/utils/WebGLGraphics.js b/src/core/renderers/webgl/utils/WebGLGraphics.js index 55f4911..ab8f46e 100644 --- a/src/core/renderers/webgl/utils/WebGLGraphics.js +++ b/src/core/renderers/webgl/utils/WebGLGraphics.js @@ -19,7 +19,8 @@ * @param graphics {Graphics} * @param renderer {WebGLRenderer} */ -WebGLGraphics.renderGraphics = function (graphics, renderer) {//projection, offset) { +WebGLGraphics.renderGraphics = function (graphics, renderer) {//projection, offset) +{ var gl = renderer.gl; var projection = renderer.projection, @@ -27,7 +28,8 @@ shader = renderer.shaderManager.primitiveShader, webGLData; - if (graphics.dirty) { + if (graphics.dirty) + { WebGLGraphics.updateGraphics(graphics, gl); } @@ -35,8 +37,10 @@ // This could be speeded up for sure! - for (var i = 0; i < webGL.data.length; i++) { - if (webGL.data[i].mode === 1) { + for (var i = 0; i < webGL.data.length; i++) + { + if (webGL.data[i].mode === 1) + { webGLData = webGL.data[i]; renderer.stencilManager.pushStencil(graphics, webGLData, renderer); @@ -46,7 +50,8 @@ renderer.stencilManager.popStencil(graphics, webGLData, renderer); } - else { + else + { webGLData = webGL.data[i]; @@ -84,12 +89,14 @@ * @param graphicsData {Graphics} The graphics object to update * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLGraphics.updateGraphics = function (graphics, gl) { +WebGLGraphics.updateGraphics = function (graphics, gl) +{ // get the contexts graphics object var webGL = graphics._webGL[gl.id]; // if the graphics object does not exist in the webGL context time to create it! - if (!webGL) { + if (!webGL) + { webGL = graphics._webGL[gl.id] = {lastIndex:0, data:[], gl:gl}; } @@ -99,11 +106,13 @@ var i; // if the user cleared the graphics object we will need to clear every object - if (graphics.clearDirty) { + if (graphics.clearDirty) + { graphics.clearDirty = false; // lop through and return all the webGLDatas to the object pool so than can be reused later on - for (i = 0; i < webGL.data.length; i++) { + for (i = 0; i < webGL.data.length; i++) + { var graphicsData = webGL.data[i]; graphicsData.reset(); WebGLGraphics.graphicsDataPool.push( graphicsData ); @@ -119,58 +128,72 @@ // loop through the graphics datas and construct each one.. // if the object is a complex fill then the new stencil buffer technique will be used // other wise graphics objects will be pushed into a batch.. - for (i = webGL.lastIndex; i < graphics.graphicsData.length; i++) { + for (i = webGL.lastIndex; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { // need to add the points the the graphics object.. data.points = data.shape.points.slice(); - if (data.shape.closed) { + if (data.shape.closed) + { // close the poly if the value is true! - if (data.points[0] !== data.points[data.points.length-2] || data.points[1] !== data.points[data.points.length-1]) { + if (data.points[0] !== data.points[data.points.length-2] || data.points[1] !== data.points[data.points.length-1]) + { data.points.push(data.points[0], data.points[1]); } } // MAKE SURE WE HAVE THE CORRECT TYPE.. - if (data.fill) { - if (data.points.length >= 6) { - if (data.points.length < 6 * 2) { + if (data.fill) + { + if (data.points.length >= 6) + { + if (data.points.length < 6 * 2) + { webGLData = WebGLGraphics.switchMode(webGL, 0); var canDrawUsingSimple = WebGLGraphics.buildPoly(data, webGLData); // console.log(canDrawUsingSimple); - if (!canDrawUsingSimple) { + if (!canDrawUsingSimple) + { // console.log("<>>>") webGLData = WebGLGraphics.switchMode(webGL, 1); WebGLGraphics.buildComplexPoly(data, webGLData); } } - else { + else + { webGLData = WebGLGraphics.switchMode(webGL, 1); WebGLGraphics.buildComplexPoly(data, webGLData); } } } - if (data.lineWidth > 0) { + if (data.lineWidth > 0) + { webGLData = WebGLGraphics.switchMode(webGL, 0); WebGLGraphics.buildLine(data, webGLData); } } - else { + else + { webGLData = WebGLGraphics.switchMode(webGL, 0); - if (data.type === CONST.SHAPES.RECT) { + if (data.type === CONST.SHAPES.RECT) + { WebGLGraphics.buildRectangle(data, webGLData); } - else if (data.type === CONST.SHAPES.CIRC || data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.CIRC || data.type === CONST.SHAPES.ELIP) + { WebGLGraphics.buildCircle(data, webGLData); } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { WebGLGraphics.buildRoundedRectangle(data, webGLData); } } @@ -179,10 +202,12 @@ } // upload all the dirty data... - for (i = 0; i < webGL.data.length; i++) { + for (i = 0; i < webGL.data.length; i++) + { webGLData = webGL.data[i]; - if (webGLData.dirty) { + if (webGLData.dirty) + { webGLData.upload(); } } @@ -194,18 +219,22 @@ * @param webGL {WebGLContext} * @param type {number} */ -WebGLGraphics.switchMode = function (webGL, type) { +WebGLGraphics.switchMode = function (webGL, type) +{ var webGLData; - if (!webGL.data.length) { + if (!webGL.data.length) + { webGLData = WebGLGraphics.graphicsDataPool.pop() || new WebGLGraphicsData(webGL.gl); webGLData.mode = type; webGL.data.push(webGLData); } - else { + else + { webGLData = webGL.data[webGL.data.length-1]; - if (webGLData.mode !== type || type === 1) { + if (webGLData.mode !== type || type === 1) + { webGLData = WebGLGraphics.graphicsDataPool.pop() || new WebGLGraphicsData(webGL.gl); webGLData.mode = type; webGL.data.push(webGLData); @@ -225,7 +254,8 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildRectangle = function (graphicsData, webGLData) { +WebGLGraphics.buildRectangle = function (graphicsData, webGLData) +{ // --- // // need to convert points to a nice regular data // @@ -235,7 +265,8 @@ var width = rectData.width; var height = rectData.height; - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -265,7 +296,8 @@ indices.push(vertPos, vertPos, vertPos+1, vertPos+2, vertPos+3, vertPos+3); } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = [x, y, @@ -289,7 +321,8 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildRoundedRectangle = function (graphicsData, webGLData) { +WebGLGraphics.buildRoundedRectangle = function (graphicsData, webGLData) +{ var rrectData = graphicsData.shape; var x = rrectData.x; var y = rrectData.y; @@ -305,7 +338,8 @@ recPoints = recPoints.concat(WebGLGraphics.quadraticBezierCurve(x + width, y + radius, x + width, y, x + width - radius, y)); recPoints = recPoints.concat(WebGLGraphics.quadraticBezierCurve(x + radius, y, x, y, x, y + radius)); - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -323,7 +357,8 @@ // var i = 0; - for (i = 0; i < triangles.length; i+=3) { + for (i = 0; i < triangles.length; i+=3) + { indices.push(triangles[i] + vecPos); indices.push(triangles[i] + vecPos); indices.push(triangles[i+1] + vecPos); @@ -332,12 +367,14 @@ } - for (i = 0; i < recPoints.length; i++) { + for (i = 0; i < recPoints.length; i++) + { verts.push(recPoints[i], recPoints[++i], r, g, b, alpha); } } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = recPoints; @@ -362,7 +399,8 @@ * @param toY {number} Destination point y * @return {number[]} */ -WebGLGraphics.quadraticBezierCurve = function (fromX, fromY, cpX, cpY, toX, toY) { +WebGLGraphics.quadraticBezierCurve = function (fromX, fromY, cpX, cpY, toX, toY) +{ var xa, ya, @@ -373,14 +411,16 @@ n = 20, points = []; - function getPt(n1 , n2, perc) { + function getPt(n1 , n2, perc) + { var diff = n2 - n1; return n1 + ( diff * perc ); } var j = 0; - for (var i = 0; i <= n; i++ ) { + for (var i = 0; i <= n; i++ ) + { j = i / n; // The Green Line @@ -406,7 +446,8 @@ * @param graphicsData {Graphics} The graphics object to draw * @param webGLData {object} */ -WebGLGraphics.buildCircle = function (graphicsData, webGLData) { +WebGLGraphics.buildCircle = function (graphicsData, webGLData) +{ // need to convert points to a nice regular data var circleData = graphicsData.shape; var x = circleData.x; @@ -415,11 +456,13 @@ var height; // TODO - bit hacky?? - if (graphicsData.type === CONST.SHAPES.CIRC) { + if (graphicsData.type === CONST.SHAPES.CIRC) + { width = circleData.radius; height = circleData.radius; } - else { + else + { width = circleData.width; height = circleData.height; } @@ -429,7 +472,8 @@ var i = 0; - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -444,7 +488,8 @@ indices.push(vecPos); - for (i = 0; i < totalSegs + 1 ; i++) { + for (i = 0; i < totalSegs + 1 ; i++) + { verts.push(x,y, r, g, b, alpha); verts.push(x + Math.sin(seg * i) * width, @@ -457,12 +502,14 @@ indices.push(vecPos-1); } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = []; - for (i = 0; i < totalSegs + 1; i++) { + for (i = 0; i < totalSegs + 1; i++) + { graphicsData.points.push(x + Math.sin(seg * i) * width, y + Math.cos(seg * i) * height); } @@ -481,18 +528,22 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildLine = function (graphicsData, webGLData) { +WebGLGraphics.buildLine = function (graphicsData, webGLData) +{ // TODO OPTIMISE! var i = 0; var points = graphicsData.points; - if (points.length === 0) { + if (points.length === 0) + { return; } // if the line width is an odd number add 0.5 to align to a whole pixel - if (graphicsData.lineWidth%2) { - for (i = 0; i < points.length; i++) { + if (graphicsData.lineWidth%2) + { + for (i = 0; i < points.length; i++) + { points[i] += 0.5; } } @@ -502,7 +553,8 @@ var lastPoint = new math.Point(points[points.length - 2], points[points.length - 1]); // if the first point is the last point - gonna have issues :) - if (firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) { + if (firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) + { // need to clone as we are going to slightly modify the shape.. points = points.slice(); @@ -562,7 +614,8 @@ verts.push(p1x + perpx , p1y + perpy, r, g, b, alpha); - for (i = 1; i < length-1; i++) { + for (i = 1; i < length-1; i++) + { p1x = points[(i-1)*2]; p1y = points[(i-1)*2 + 1]; @@ -599,7 +652,8 @@ denom = a1*b2 - a2*b1; - if (Math.abs(denom) < 0.1 ) { + if (Math.abs(denom) < 0.1 ) + { denom+=10.1; verts.push(p2x - perpx , p2y - perpy, @@ -618,7 +672,8 @@ pdist = (px -p2x) * (px -p2x) + (py -p2y) + (py -p2y); - if (pdist > 140 * 140) { + if (pdist > 140 * 140) + { perp3x = perpx - perp2x; perp3y = perpy - perp2y; @@ -639,7 +694,8 @@ indexCount++; } - else { + else + { verts.push(px , py); verts.push(r, g, b, alpha); @@ -672,7 +728,8 @@ indices.push(indexStart); - for (i = 0; i < indexCount; i++) { + for (i = 0; i < indexCount; i++) + { indices.push(indexStart++); } @@ -687,11 +744,13 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildComplexPoly = function (graphicsData, webGLData) { +WebGLGraphics.buildComplexPoly = function (graphicsData, webGLData) +{ //TODO - no need to copy this as it gets turned into a FLoat32Array anyways.. var points = graphicsData.points.slice(); - if (points.length < 6) { + if (points.length < 6) + { return; } @@ -711,7 +770,8 @@ var x,y; // get size.. - for (var i = 0; i < points.length; i+=2) { + for (var i = 0; i < points.length; i+=2) + { x = points[i]; y = points[i+1]; @@ -732,7 +792,8 @@ //TODO - this aint needed! var length = points.length / 2; - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { indices.push( i ); } @@ -746,10 +807,12 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildPoly = function (graphicsData, webGLData) { +WebGLGraphics.buildPoly = function (graphicsData, webGLData) +{ var points = graphicsData.points; - if (points.length < 6) { + if (points.length < 6) + { return; } // get first and last point.. figure out the middle! @@ -767,7 +830,8 @@ var triangles = utils.PolyK.Triangulate(points); - if (!triangles) { + if (!triangles) + { return false; } @@ -775,7 +839,8 @@ var i = 0; - for (i = 0; i < triangles.length; i+=3) { + for (i = 0; i < triangles.length; i+=3) + { indices.push(triangles[i] + vertPos); indices.push(triangles[i] + vertPos); indices.push(triangles[i+1] + vertPos); @@ -783,7 +848,8 @@ indices.push(triangles[i+2] + vertPos); } - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { verts.push(points[i * 2], points[i * 2 + 1], r, g, b, alpha); } diff --git a/src/core/renderers/webgl/utils/WebGLGraphicsData.js b/src/core/renderers/webgl/utils/WebGLGraphicsData.js index c56d05e..c739ba7 100644 --- a/src/core/renderers/webgl/utils/WebGLGraphicsData.js +++ b/src/core/renderers/webgl/utils/WebGLGraphicsData.js @@ -2,7 +2,8 @@ * @class * @private */ -function WebGLGraphicsData(gl) { +function WebGLGraphicsData(gl) +{ this.gl = gl; //TODO does this need to be split before uploding?? @@ -22,7 +23,8 @@ /** * */ -WebGLGraphicsData.prototype.reset = function () { +WebGLGraphicsData.prototype.reset = function () +{ this.points.length = 0; this.indices.length = 0; }; @@ -30,7 +32,8 @@ /** * */ -WebGLGraphicsData.prototype.upload = function () { +WebGLGraphicsData.prototype.upload = function () +{ var gl = this.gl; // this.lastIndex = graphics.graphicsData.length; diff --git a/src/core/renderers/webgl/utils/WebGLSpriteBatch.js b/src/core/renderers/webgl/utils/WebGLSpriteBatch.js index 96eaa52..55befbb 100644 --- a/src/core/renderers/webgl/utils/WebGLSpriteBatch.js +++ b/src/core/renderers/webgl/utils/WebGLSpriteBatch.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this sprite batch works for. */ -function WebGLSpriteBatch(renderer) { +function WebGLSpriteBatch(renderer) +{ /** * * @@ -88,7 +89,8 @@ */ this.lastIndexCount = 0; - for (var i=0, j=0; i < numIndices; i += 6, j += 4) { + 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; @@ -162,7 +164,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.setupContext(); }); } @@ -173,7 +176,8 @@ /** * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLSpriteBatch.prototype.setupContext = function () { +WebGLSpriteBatch.prototype.setupContext = function () +{ var gl = this.renderer.gl; // setup default shader @@ -198,7 +202,8 @@ /** * */ -WebGLSpriteBatch.prototype.begin = function () { +WebGLSpriteBatch.prototype.begin = function () +{ // this.shader = this.renderer.shaderManager.defaultShader; this.start(); @@ -206,19 +211,22 @@ /** */ -WebGLSpriteBatch.prototype.end = function () { +WebGLSpriteBatch.prototype.end = function () +{ this.flush(); }; /** * @param sprite {Sprite} the sprite to render when using this spritebatch */ -WebGLSpriteBatch.prototype.render = function (sprite) { +WebGLSpriteBatch.prototype.render = function (sprite) +{ var texture = sprite.texture; //TODO set blend modes.. // check texture.. - if (this.currentBatchSize >= this.size) { + if (this.currentBatchSize >= this.size) + { this.flush(); this.currentBaseTexture = texture.baseTexture; } @@ -227,7 +235,8 @@ var uvs = texture._uvs; // if the uvs have not updated then no point rendering just yet! - if (!uvs) { + if (!uvs) + { return; } @@ -237,7 +246,8 @@ var w0, w1, h0, h1; - if (texture.trim) { + 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; @@ -248,7 +258,8 @@ h0 = h1 + texture.crop.height; } - else { + else + { w0 = (texture.frame.width ) * (1-aX); w1 = (texture.frame.width ) * -aX; @@ -272,7 +283,8 @@ var colors = this.colors; var positions = this.positions; - if (this.renderer.roundPixels) { + if (this.renderer.roundPixels) + { // xy positions[index] = a * w1 + c * h1 + tx | 0; positions[index+1] = d * h1 + b * w1 + ty | 0; @@ -289,7 +301,8 @@ positions[index+15] = a * w1 + c * h0 + tx | 0; positions[index+16] = d * h0 + b * w1 + ty | 0; } - else { + else + { // xy positions[index] = a * w1 + c * h1 + tx; positions[index+1] = d * h1 + b * w1 + ty; @@ -338,11 +351,13 @@ * * @param sprite {TilingSprite} the tilingSprite to render */ -WebGLSpriteBatch.prototype.renderTilingSprite = function (tilingSprite) { +WebGLSpriteBatch.prototype.renderTilingSprite = function (tilingSprite) +{ var texture = tilingSprite.tilingTexture; // check texture.. - if (this.currentBatchSize >= this.size) { + if (this.currentBatchSize >= this.size) + { //return; this.flush(); this.currentBaseTexture = texture.baseTexture; @@ -351,7 +366,8 @@ // set the textures uvs temporarily // TODO create a separate texture so that we can tile part of a texture - if (!tilingSprite._uvs) { + if (!tilingSprite._uvs) + { tilingSprite._uvs = new TextureUvs(); } @@ -454,16 +470,19 @@ * Renders the content and empties the current batch. * */ -WebGLSpriteBatch.prototype.flush = function () { +WebGLSpriteBatch.prototype.flush = function () +{ // If the batch is length 0 then return as there is nothing to draw - if (this.currentBatchSize === 0) { + if (this.currentBatchSize === 0) + { return; } var gl = this.renderer.gl; var shader; - if (this.dirty) { + if (this.dirty) + { this.dirty = false; // bind the main texture gl.activeTexture(gl.TEXTURE0); @@ -482,10 +501,12 @@ } // upload the verts to the buffer - if (this.currentBatchSize > ( this.size * 0.5 ) ) { + if (this.currentBatchSize > ( this.size * 0.5 ) ) + { gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); } - else { + else + { var view = this.positions.subarray(0, this.currentBatchSize * this.vertByteSize); gl.bufferSubData(gl.ARRAY_BUFFER, 0, view); } @@ -502,7 +523,8 @@ var shaderSwap = false; var sprite; - for (var i = 0, j = this.currentBatchSize; i < j; i++) { + for (var i = 0, j = this.currentBatchSize; i < j; i++) + { sprite = this.sprites[i]; @@ -513,24 +535,28 @@ blendSwap = currentBlendMode !== nextBlendMode; shaderSwap = currentShader !== nextShader; // should I use uuidS??? - if (currentBaseTexture !== nextTexture || blendSwap || shaderSwap) { + if (currentBaseTexture !== nextTexture || blendSwap || shaderSwap) + { this.renderBatch(currentBaseTexture, batchSize, start); start = i; batchSize = 0; currentBaseTexture = nextTexture; - if (blendSwap) { + if (blendSwap) + { currentBlendMode = nextBlendMode; this.renderer.blendModeManager.setBlendMode( currentBlendMode ); } - if (shaderSwap) { + if (shaderSwap) + { currentShader = nextShader; shader = currentShader.shaders ? currentShader.shaders[gl.id] : currentShader; - if (!shader) { + if (!shader) + { shader = new Shader(gl, null, currentShader.fragmentSrc, currentShader.uniforms); currentShader.shaders[gl.id] = shader; } @@ -538,7 +564,8 @@ // set shader function??? this.renderer.shaderManager.setShader(shader); - if (shader.dirty) { + if (shader.dirty) + { shader.syncUniforms(); } @@ -569,17 +596,21 @@ * @param size {number} * @param startIndex {number} */ -WebGLSpriteBatch.prototype.renderBatch = function (texture, size, startIndex) { - if (size === 0) { +WebGLSpriteBatch.prototype.renderBatch = function (texture, size, startIndex) +{ + if (size === 0) + { return; } var gl = this.renderer.gl; - if (!texture._glTextures[gl.id]) { + if (!texture._glTextures[gl.id]) + { this.renderer.updateTexture(texture); } - else { + else + { // bind the current texture gl.bindTexture(gl.TEXTURE_2D, texture._glTextures[gl.id]); } @@ -594,7 +625,8 @@ /** * */ -WebGLSpriteBatch.prototype.stop = function () { +WebGLSpriteBatch.prototype.stop = function () +{ this.flush(); this.dirty = true; }; @@ -602,7 +634,8 @@ /** * */ -WebGLSpriteBatch.prototype.start = function () { +WebGLSpriteBatch.prototype.start = function () +{ this.dirty = true; }; @@ -610,7 +643,8 @@ * Destroys the SpriteBatch. * */ -WebGLSpriteBatch.prototype.destroy = function () { +WebGLSpriteBatch.prototype.destroy = function () +{ this.renderer.gl.deleteBuffer(this.vertexBuffer); this.renderer.gl.deleteBuffer(this.indexBuffer); diff --git a/src/core/textures/BaseTexture.js b/src/core/textures/BaseTexture.js index 2bf77d4..513d358 100644 --- a/src/core/textures/BaseTexture.js +++ b/src/core/textures/BaseTexture.js @@ -10,7 +10,8 @@ * @param source {Image|Canvas} the source object of the texture. * @param [scaleMode=scaleModes.DEFAULT] {number} See {@link scaleModes} for possible values */ -function BaseTexture(source, scaleMode) { +function BaseTexture(source, scaleMode) +{ this.uuid = utils.uuid(); /** @@ -123,7 +124,8 @@ this._needsUpdate = false; // if no source passed don't try to load - if (source) { + if (source) + { this.loadSource(source); } @@ -149,13 +151,16 @@ Object.defineProperties(BaseTexture.prototype, { needsUpdate: { - get: function () { + get: function () + { return this._needsUpdate; }, - set: function (val) { + set: function (val) + { this._needsUpdate = val; - if (val) { + if (val) + { this.emit('update', this); } } @@ -171,9 +176,11 @@ * * The logic state after calling `loadSource` directly or indirectly (eg. `fromImage`, `new BaseTexture`) is: * - * if (texture.hasLoaded) { + * if (texture.hasLoaded) + { * // texture ready for use - * } else if (texture.isLoading) { + * } else if (texture.isLoading) + { * // listen to 'loaded' and/or 'error' events on texture * } else { * // not loading, not going to load UNLESS the source is reloaded @@ -183,12 +190,14 @@ * @protected * @param source {Image|Canvas} the source object of the texture. */ -BaseTexture.prototype.loadSource = function (source) { +BaseTexture.prototype.loadSource = function (source) +{ var wasLoading = this.isLoading; this.hasLoaded = false; this.isLoading = false; - if (wasLoading && this.source) { + if (wasLoading && this.source) + { this.source.onload = null; this.source.onerror = null; } @@ -196,20 +205,24 @@ this.source = source; // Apply source if loaded. Otherwise setup appropriate loading monitors. - if ((this.source.complete || this.source.getContext) && this.source.width && this.source.height) { + if ((this.source.complete || this.source.getContext) && this.source.width && this.source.height) + { this._sourceLoaded(); } - else if(!source.getContext) { + else if(!source.getContext) + { // Image fail / not ready this.isLoading = true; var scope = this; - source.onload = function () { + source.onload = function () + { source.onload = null; source.onerror = null; - if(!scope.isLoading) { + if(!scope.isLoading) + { return; } @@ -219,11 +232,13 @@ scope.emit('loaded', scope); }; - source.onerror = function () { + source.onerror = function () + { source.onload = null; source.onerror = null; - if(!scope.isLoading) { + if(!scope.isLoading) + { return; } @@ -234,24 +249,29 @@ // Per http://www.w3.org/TR/html5/embedded-content-0.html#the-img-element // "The value of `complete` can thus change while a script is executing." // So complete needs to be re-checked after the callbacks have been added.. - if (source.complete) { + if (source.complete) + { this.isLoading = false; // ..and if we're complete now, no need for callbacks source.onload = null; source.onerror = null; - if (source.width && source.height) { + if (source.width && source.height) + { this._sourceLoaded(); // If any previous subscribers possible - if (wasLoading) { + if (wasLoading) + { this.emit('loaded', this); } } - else { + else + { // If any previous subscribers possible - if (wasLoading) { + if (wasLoading) + { this.emit('error', this); } } @@ -265,7 +285,8 @@ * * @private */ -BaseTexture.prototype._sourceLoaded = function () { +BaseTexture.prototype._sourceLoaded = function () +{ this.hasLoaded = true; this.width = this.source.naturalWidth || this.source.width; @@ -278,16 +299,20 @@ * Destroys this base texture * */ -BaseTexture.prototype.destroy = function () { - if (this.imageUrl) { +BaseTexture.prototype.destroy = function () +{ + if (this.imageUrl) + { delete utils.BaseTextureCache[this.imageUrl]; delete utils.TextureCache[this.imageUrl]; this.imageUrl = null; - if (!navigator.isCocoonJS) { + if (!navigator.isCocoonJS) + { this.source.src = ''; } } - else if (this.source && this.source._pixiId) { + else if (this.source && this.source._pixiId) + { delete utils.BaseTextureCache[this.source._pixiId]; } this.source = null; @@ -301,7 +326,8 @@ * memory again. * */ -BaseTexture.prototype.dispose = function () { +BaseTexture.prototype.dispose = function () +{ this.emit('dispose', this); }; @@ -311,7 +337,8 @@ * * @param newSrc {string} the path of the image */ -BaseTexture.prototype.updateSourceImage = function (newSrc) { +BaseTexture.prototype.updateSourceImage = function (newSrc) +{ this.source.src = newSrc; this.loadSource(this.source); }; @@ -326,18 +353,22 @@ * @param [scaleMode=scaleModes.DEFAULT] {number} See {@link scaleModes} for possible values * @return BaseTexture */ -BaseTexture.fromImage = function (imageUrl, crossorigin, scaleMode) { +BaseTexture.fromImage = function (imageUrl, crossorigin, scaleMode) +{ var baseTexture = utils.BaseTextureCache[imageUrl]; - if (crossorigin === undefined && imageUrl.indexOf('data:') !== 0) { + if (crossorigin === undefined && imageUrl.indexOf('data:') !== 0) + { crossorigin = true; } - if (!baseTexture) { + if (!baseTexture) + { // new Image() breaks tex loading in some versions of Chrome. // See https://code.google.com/p/chromium/issues/detail?id=238071 var image = new Image();//document.createElement('img'); - if (crossorigin) { + if (crossorigin) + { image.crossOrigin = ''; } @@ -347,7 +378,8 @@ utils.BaseTextureCache[imageUrl] = baseTexture; // if there is an @2x at the end of the url we are going to assume its a highres image - if ( imageUrl.indexOf(CONST.RETINA_PREFIX + '.') !== -1) { + if ( imageUrl.indexOf(CONST.RETINA_PREFIX + '.') !== -1) + { baseTexture.resolution = 2; } } @@ -363,14 +395,17 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return BaseTexture */ -BaseTexture.fromCanvas = function (canvas, scaleMode) { - if (!canvas._pixiId) { +BaseTexture.fromCanvas = function (canvas, scaleMode) +{ + if (!canvas._pixiId) + { canvas._pixiId = 'canvas_' + utils.uuid(); } var baseTexture = utils.BaseTextureCache[canvas._pixiId]; - if (!baseTexture) { + if (!baseTexture) + { baseTexture = new BaseTexture(canvas, scaleMode); utils.BaseTextureCache[canvas._pixiId] = baseTexture; } diff --git a/src/core/textures/RenderTexture.js b/src/core/textures/RenderTexture.js index 6dad20f..53ae796 100644 --- a/src/core/textures/RenderTexture.js +++ b/src/core/textures/RenderTexture.js @@ -46,8 +46,10 @@ * @param [scaleMode] {number} See {@link scaleModes} for possible values * @param [resolution=1] {number} The resolution of the texture being generated */ -function RenderTexture(renderer, width, height, scaleMode, resolution) { - if (!renderer) { +function RenderTexture(renderer, width, height, scaleMode, resolution) +{ + if (!renderer) + { throw new Error('Unable to create RenderTexture, you must pass a renderer into the constructor.'); } @@ -133,7 +135,8 @@ */ this.renderer = renderer; - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { var gl = this.renderer.gl; this.textureBuffer = new FilterTexture(gl, this.width * this.resolution, this.height * this.resolution, this.baseTexture.scaleMode); @@ -142,7 +145,8 @@ this.render = this.renderWebGL; this.projection = new math.Point(this.width*0.5, -this.height*0.5); } - else { + else + { this.render = this.renderCanvas; this.textureBuffer = new CanvasBuffer(this.width* this.resolution, this.height* this.resolution); this.baseTexture.source = this.textureBuffer.canvas; @@ -167,8 +171,10 @@ * @param height {number} The height to resize to. * @param updateBase {boolean} Should the baseTexture.width and height values be resized as well? */ -RenderTexture.prototype.resize = function (width, height, updateBase) { - if (width === this.width && height === this.height) { +RenderTexture.prototype.resize = function (width, height, updateBase) +{ + if (width === this.width && height === this.height) + { return; } @@ -177,17 +183,20 @@ this.width = this.frame.width = this.crop.width = width; this.height = this.frame.height = this.crop.height = height; - if (updateBase) { + if (updateBase) + { this.baseTexture.width = this.width; this.baseTexture.height = this.height; } - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { this.projection.x = this.width / 2; this.projection.y = -this.height / 2; } - if (!this.valid) { + if (!this.valid) + { return; } @@ -198,12 +207,15 @@ * Clears the RenderTexture. * */ -RenderTexture.prototype.clear = function () { - if (!this.valid) { +RenderTexture.prototype.clear = function () +{ + if (!this.valid) + { return; } - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { this.renderer.gl.bindFramebuffer(this.renderer.gl.FRAMEBUFFER, this.textureBuffer.frameBuffer); } @@ -220,19 +232,23 @@ * @param [restoreWorldTransform=true] {boolean} If true the displayObject's worldTransform/worldAlpha and all children * transformations will be restored. Not restoring this information will be a little faster. */ -RenderTexture.prototype.renderWebGL = function (displayObject, matrix, clear, restoreWorldTransform) { - if (!this.valid) { +RenderTexture.prototype.renderWebGL = function (displayObject, matrix, clear, restoreWorldTransform) +{ + if (!this.valid) + { return; } - if (typeof restoreWorldTransform === 'undefined') { + if (typeof restoreWorldTransform === 'undefined') + { restoreWorldTransform = true; } var tempAlpha, tempTransform; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { tempAlpha = displayObject.worldAlpha; tempTransform = displayObject.worldTransform.toArray(); } @@ -245,7 +261,8 @@ wt.identity(); wt.translate(0, this.projection.y * 2); - if (matrix) { + if (matrix) + { wt.append(matrix); } @@ -258,7 +275,8 @@ var children = displayObject.children; var i, j; - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } @@ -269,7 +287,8 @@ gl.bindFramebuffer(gl.FRAMEBUFFER, this.textureBuffer.frameBuffer ); - if (clear) { + if (clear) + { this.textureBuffer.clear(); } @@ -279,11 +298,13 @@ this.renderer.spriteBatch.dirty = true; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { displayObject.worldAlpha = tempAlpha; displayObject.worldTransform.fromArray(tempTransform); - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } } @@ -300,26 +321,31 @@ * @param [restoreWorldTransform=true] {boolean} If true the displayObject's worldTransform/worldAlpha and all children * transformations will be restored. Not restoring this information will be a little faster. */ -RenderTexture.prototype.renderCanvas = function (displayObject, matrix, clear, restoreWorldTransform) { - if (!this.valid) { +RenderTexture.prototype.renderCanvas = function (displayObject, matrix, clear, restoreWorldTransform) +{ + if (!this.valid) + { return; } - if (typeof restoreWorldTransform === 'undefined') { + if (typeof restoreWorldTransform === 'undefined') + { restoreWorldTransform = true; } var tempAlpha, tempTransform; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { tempAlpha = displayObject.worldAlpha; tempTransform = displayObject.worldTransform.toArray(); } var wt = displayObject.worldTransform; wt.identity(); - if (matrix) { + if (matrix) + { wt.append(matrix); } @@ -330,11 +356,13 @@ var children = displayObject.children; var i, j; - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } - if (clear) { + if (clear) + { this.textureBuffer.clear(); } @@ -348,11 +376,13 @@ this.renderer.resolution = realResolution; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { displayObject.worldAlpha = tempAlpha; displayObject.worldTransform.fromArray(tempTransform); - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } } @@ -363,7 +393,8 @@ * * @return {Image} */ -RenderTexture.prototype.getImage = function () { +RenderTexture.prototype.getImage = function () +{ var image = new Image(); image.src = this.getBase64(); return image; @@ -374,7 +405,8 @@ * * @return {string} A base64 encoded string of the texture. */ -RenderTexture.prototype.getBase64 = function () { +RenderTexture.prototype.getBase64 = function () +{ return this.getCanvas().toDataURL(); }; @@ -383,8 +415,10 @@ * * @return {HTMLCanvasElement} A Canvas element with the texture rendered on. */ -RenderTexture.prototype.getCanvas = function () { - if (this.renderer.type === CONST.WEBGL_RENDERER) { +RenderTexture.prototype.getCanvas = function () +{ + if (this.renderer.type === CONST.WEBGL_RENDERER) + { var gl = this.renderer.gl; var width = this.textureBuffer.width; var height = this.textureBuffer.height; @@ -403,7 +437,8 @@ return tempCanvas.canvas; } - else { + else + { return this.textureBuffer.canvas; } }; diff --git a/src/core/textures/Texture.js b/src/core/textures/Texture.js index 3c65909..e97f0aa 100644 --- a/src/core/textures/Texture.js +++ b/src/core/textures/Texture.js @@ -17,7 +17,8 @@ * @param [crop] {Rectangle} The area of original texture * @param [trim] {Rectangle} Trimmed texture rectangle */ -function Texture(baseTexture, frame, crop, trim) { +function Texture(baseTexture, frame, crop, trim) +{ /** * Does this Texture have any frame data assigned to it? * @@ -25,12 +26,14 @@ */ this.noFrame = false; - if (!frame) { + if (!frame) + { this.noFrame = true; frame = new math.Rectangle(0, 0, 1, 1); } - if (baseTexture instanceof Texture) { + if (baseTexture instanceof Texture) + { baseTexture = baseTexture.baseTexture; } @@ -100,13 +103,16 @@ */ this.crop = crop || new math.Rectangle(0, 0, 1, 1); - if (baseTexture.hasLoaded) { - if (this.noFrame) { + if (baseTexture.hasLoaded) + { + if (this.noFrame) + { frame = new math.Rectangle(0, 0, baseTexture.width, baseTexture.height); } this.frame = frame; } - else { + else + { baseTexture.addEventListener('loaded', this.onBaseTextureLoaded.bind(this)); } } @@ -118,19 +124,23 @@ Object.defineProperties(Texture.prototype, { needsUpdate: { - get: function () { + get: function () + { return this.baseTexture.needsUpdate; }, - set: function (val) { + set: function (val) + { this.baseTexture.needsUpdate = val; } }, frame: { - get: function () { + get: function () + { return this._frame; }, - set: function (frame) { + set: function (frame) + { this._frame = frame; this.noFrame = false; @@ -143,20 +153,23 @@ 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 (!this.trim && (frame.x + frame.width > this.baseTexture.width || frame.y + frame.height > this.baseTexture.height)) + { throw new Error('Texture Error: frame does not fit inside the base Texture dimensions ' + this); } this.valid = frame && frame.width && frame.height && this.baseTexture.source && this.baseTexture.hasLoaded; - if (this.trim) { + 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) { + if (this.valid) + { this._updateUvs(); } } @@ -168,11 +181,13 @@ * * @private */ -Texture.prototype.onBaseTextureLoaded = function () { +Texture.prototype.onBaseTextureLoaded = function () +{ var baseTexture = this.baseTexture; baseTexture.removeEventListener('loaded', this.onLoaded); - if (this.noFrame) { + if (this.noFrame) + { this.frame = new math.Rectangle(0, 0, baseTexture.width, baseTexture.height); } @@ -184,8 +199,10 @@ * * @param destroyBase {boolean} Whether to destroy the base texture as well */ -Texture.prototype.destroy = function (destroyBase) { - if (destroyBase) { +Texture.prototype.destroy = function (destroyBase) +{ + if (destroyBase) + { this.baseTexture.destroy(); } @@ -197,8 +214,10 @@ * * @private */ -Texture.prototype._updateUvs = function () { - if (!this._uvs) { +Texture.prototype._updateUvs = function () +{ + if (!this._uvs) + { this._uvs = new TextureUvs(); } @@ -229,10 +248,12 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return Texture */ -Texture.fromImage = function (imageUrl, crossorigin, scaleMode) { +Texture.fromImage = function (imageUrl, crossorigin, scaleMode) +{ var texture = utils.TextureCache[imageUrl]; - if (!texture) { + if (!texture) + { texture = new Texture(BaseTexture.fromImage(imageUrl, crossorigin, scaleMode)); utils.TextureCache[imageUrl] = texture; } @@ -248,9 +269,11 @@ * @param frameId {string} The frame id of the texture * @return Texture */ -Texture.fromFrame = function (frameId) { +Texture.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache '); } return texture; @@ -264,7 +287,8 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return {Texture} */ -Texture.fromCanvas = function (canvas, scaleMode) { +Texture.fromCanvas = function (canvas, scaleMode) +{ return new Texture(BaseTexture.fromCanvas(canvas, scaleMode)); }; @@ -276,7 +300,8 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return {Texture} A Texture */ -Texture.fromVideo = function (video, scaleMode) { +Texture.fromVideo = function (video, scaleMode) +{ return new Texture(VideoBaseTexture.baseTextureFromVideo(video, scaleMode)); }; @@ -287,7 +312,8 @@ * @param texture {Texture} The Texture to add to the cache. * @param id {string} The id that the texture will be stored against. */ -Texture.addTextureToCache = function (texture, id) { +Texture.addTextureToCache = function (texture, id) +{ utils.TextureCache[id] = texture; }; @@ -298,7 +324,8 @@ * @param id {string} The id of the texture to be removed * @return {Texture} The texture that was removed */ -Texture.removeTextureFromCache = function (id) { +Texture.removeTextureFromCache = function (id) +{ var texture = utils.TextureCache[id]; delete utils.TextureCache[id]; diff --git a/src/core/textures/TextureUvs.js b/src/core/textures/TextureUvs.js index b9bbb58..5424d52 100644 --- a/src/core/textures/TextureUvs.js +++ b/src/core/textures/TextureUvs.js @@ -1,4 +1,5 @@ -function TextureUvs() { +function TextureUvs() +{ this.x0 = 0; this.y0 = 0; diff --git a/src/core/textures/VideoBaseTexture.js b/src/core/textures/VideoBaseTexture.js index e3e0c5a..1a826a9 100644 --- a/src/core/textures/VideoBaseTexture.js +++ b/src/core/textures/VideoBaseTexture.js @@ -12,15 +12,18 @@ * @param source {HTMLVideoElement} * @param [scaleMode] {number} See {@link scaleModes} for possible values */ -function VideoBaseTexture(source, scaleMode) { - if (!source){ +function VideoBaseTexture(source, scaleMode) +{ + if (!source) + { throw new Error('No video source element specified.'); } // hook in here to check if video is already available. // BaseTexture looks for a source.complete boolean, plus width & height. - if ((source.readyState === source.HAVE_ENOUGH_DATA || source.readyState === source.HAVE_FUTURE_DATA) && source.width && source.height) { + if ((source.readyState === source.HAVE_ENOUGH_DATA || source.readyState === source.HAVE_FUTURE_DATA) && source.width && source.height) + { source.complete = true; } @@ -31,7 +34,8 @@ this._boundOnUpdate = this._onUpdate.bind(this); this._boundOnCanPlay = this._onCanPlay.bind(this); - if (!source.complete) { + if (!source.complete) + { source.addEventListener('canplay', this._boundOnCanPlay); source.addEventListener('canplaythrough', this._boundOnCanPlay); @@ -47,28 +51,35 @@ VideoBaseTexture.prototype.constructor = VideoBaseTexture; module.exports = VideoBaseTexture; -VideoBaseTexture.prototype._onUpdate = function () { - if (this.autoUpdate) { +VideoBaseTexture.prototype._onUpdate = function () +{ + if (this.autoUpdate) + { window.requestAnimationFrame(this._boundOnUpdate); this.needsUpdate = true; } }; -VideoBaseTexture.prototype._onPlayStart = function () { - if (!this.autoUpdate) { +VideoBaseTexture.prototype._onPlayStart = function () +{ + if (!this.autoUpdate) + { window.requestAnimationFrame(this._boundOnUpdate); this.autoUpdate = true; } }; -VideoBaseTexture.prototype._onPlayStop = function () { +VideoBaseTexture.prototype._onPlayStop = function () +{ this.autoUpdate = false; }; -VideoBaseTexture.prototype._onCanPlay = function () { +VideoBaseTexture.prototype._onCanPlay = function () +{ this.hasLoaded = true; - if (this.source) { + if (this.source) + { this.source.removeEventListener('canplay', this._boundOnCanPlay); this.source.removeEventListener('canplaythrough', this._boundOnCanPlay); @@ -78,15 +89,18 @@ this.source.play(); // prevent multiple loaded dispatches.. - if(!this.__loaded){ + if(!this.__loaded) + { this.__loaded = true; this.emit('loaded', this); } } }; -VideoBaseTexture.prototype.destroy = function () { - if (this.source && this.source._pixiId) { +VideoBaseTexture.prototype.destroy = function () +{ + if (this.source && this.source._pixiId) + { utils.BaseTextureCache[ this.source._pixiId ] = null; delete utils.BaseTextureCache[ this.source._pixiId ]; @@ -105,14 +119,17 @@ * @param scaleMode {number} See {@link scaleModes} for possible values * @return {VideoBaseTexture} */ -VideoBaseTexture.fromVideo = function (video, scaleMode) { - if (!video._pixiId) { +VideoBaseTexture.fromVideo = function (video, scaleMode) +{ + if (!video._pixiId) + { video._pixiId = 'video_' + utils.uuid(); } var baseTexture = utils.BaseTextureCache[video._pixiId]; - if (!baseTexture) { + if (!baseTexture) + { baseTexture = new VideoBaseTexture(video, scaleMode); utils.BaseTextureCache[ video._pixiId ] = baseTexture; } @@ -147,17 +164,21 @@ * @param scaleMode {number} See {@link scaleModes} for possible values * @return {VideoBaseTexture} */ -VideoBaseTexture.fromUrl = function (videoSrc, scaleMode) { +VideoBaseTexture.fromUrl = function (videoSrc, scaleMode) +{ var video = document.createElement('video'); // array of objects or strings - if (Array.isArray(videoSrc)) { - for (var i = 0; i < videoSrc.length; ++i) { + if (Array.isArray(videoSrc)) + { + for (var i = 0; i < videoSrc.length; ++i) + { video.appendChild(createSource(videoSrc.src || videoSrc, videoSrc.mime)); } } // single object or string - else { + else + { video.appendChild(createSource(videoSrc.src || videoSrc, videoSrc.mime)); } @@ -169,8 +190,10 @@ VideoBaseTexture.fromUrls = VideoBaseTexture.fromUrl; -function createSource(path, type) { - if (!type) { +function createSource(path, type) +{ + if (!type) + { type = 'video/' + path.substr(path.lastIndexOf('.') + 1); } diff --git a/src/core/display/DisplayObject.js b/src/core/display/DisplayObject.js index 66ebc3c..20e778c 100644 --- a/src/core/display/DisplayObject.js +++ b/src/core/display/DisplayObject.js @@ -7,7 +7,8 @@ * @class * @namespace PIXI */ -function DisplayObject() { +function DisplayObject() +{ /** * The coordinate of the object relative to the local coordinates of the parent. * @@ -152,10 +153,12 @@ * @memberof DisplayObject# */ x: { - get: function () { + get: function () + { return this.position.x; }, - set: function (value) { + set: function (value) + { this.position.x = value; } }, @@ -167,10 +170,12 @@ * @memberof DisplayObject# */ y: { - get: function () { + get: function () + { return this.position.y; }, - set: function (value) { + set: function (value) + { this.position.y = value; } }, @@ -183,11 +188,13 @@ * @readonly */ worldVisible: { - get: function () { + get: function () + { var item = this; do { - if (!item.visible) { + if (!item.visible) + { return false; } @@ -207,17 +214,21 @@ * @memberof DisplayObject# */ mask: { - get: function () { + get: function () + { return this._mask; }, - set: function (value) { - if (this._mask) { + set: function (value) + { + if (this._mask) + { this._mask.isMask = false; } this._mask = value; - if (this._mask) { + if (this._mask) + { this._mask.isMask = true; } } @@ -232,18 +243,23 @@ * @memberof DisplayObject# */ filters: { - get: function () { + get: function () + { return this._filters; }, - set: function (value) { - if (value) { + set: function (value) + { + if (value) + { // now put all the passes in one place.. var passes = []; - for (var i = 0; i < value.length; i++) { + for (var i = 0; i < value.length; i++) + { var filterPasses = value[i].passes; - for (var j = 0; j < filterPasses.length; j++) { + for (var j = 0; j < filterPasses.length; j++) + { passes.push(filterPasses[j]); } } @@ -264,8 +280,9 @@ * * @private */ -DisplayObject.prototype.updateTransform = function () { - +DisplayObject.prototype.updateTransform = function () +{ + // create some matrix refs for easy access var pt = this.parent.worldTransform; var wt = this.worldTransform; @@ -274,9 +291,11 @@ var a, b, c, d, tx, ty; // so if rotation is between 0 then we can simplify the multiplication process.. - if (this.rotation % math.PI_2) { + if (this.rotation % math.PI_2) + { // 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) { + if (this.rotation !== this.rotationCache) + { this.rotationCache = this.rotation; this._sr = Math.sin(this.rotation); this._cr = Math.cos(this.rotation); @@ -291,7 +310,8 @@ ty = this.position.y; // check for pivot.. not often used so geared towards that fact! - if (this.pivot.x || this.pivot.y) { + 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; } @@ -304,7 +324,8 @@ wt.tx = tx * pt.a + ty * pt.c + pt.tx; wt.ty = tx * pt.b + ty * pt.d + pt.ty; } - else { + else + { // lets do the fast version as we know there is no rotation.. a = this.scale.x; d = this.scale.y; @@ -333,7 +354,8 @@ * @param matrix {Matrix} * @return {Rectangle} the rectangular bounding area */ -DisplayObject.prototype.getBounds = function (/* matrix */) { +DisplayObject.prototype.getBounds = function (/* matrix */) +{ return math.Rectangle.EMPTY; }; @@ -342,7 +364,8 @@ * * @return {Rectangle} the rectangular bounding area */ -DisplayObject.prototype.getLocalBounds = function () { +DisplayObject.prototype.getLocalBounds = function () +{ return this.getBounds(math.Matrix.IDENTITY); }; @@ -352,7 +375,8 @@ * @param position {Point} The world origin to calculate from * @return {Point} A point object representing the position of this object */ -DisplayObject.prototype.toGlobal = function (position) { +DisplayObject.prototype.toGlobal = function (position) +{ // don't need to u[date the lot this.displayObjectUpdateTransform(); return this.worldTransform.apply(position); @@ -365,8 +389,10 @@ * @param [from] {DisplayObject} The DisplayObject to calculate the global position from * @return {Point} A point object representing the position of this object */ -DisplayObject.prototype.toLocal = function (position, from) { - if (from) { +DisplayObject.prototype.toLocal = function (position, from) +{ + if (from) + { position = from.toGlobal(position); } @@ -381,7 +407,8 @@ * @param renderer {WebGLRenderer} The renderer * @private */ -DisplayObject.prototype.renderWebGL = function (/* renderer */) { +DisplayObject.prototype.renderWebGL = function (/* renderer */) +{ // OVERWRITE; }; @@ -391,6 +418,7 @@ * @param renderer {CanvasRenderer} The renderer * @private */ -DisplayObject.prototype.renderCanvas = function (/* renderer */) { +DisplayObject.prototype.renderCanvas = function (/* renderer */) +{ // OVERWRITE; }; diff --git a/src/core/display/DisplayObjectContainer.js b/src/core/display/DisplayObjectContainer.js index 689f40b..4625ee8 100644 --- a/src/core/display/DisplayObjectContainer.js +++ b/src/core/display/DisplayObjectContainer.js @@ -12,7 +12,8 @@ * @extends DisplayObject * @namespace PIXI */ -function DisplayObjectContainer() { +function DisplayObjectContainer() +{ DisplayObject.call(this); /** @@ -47,17 +48,21 @@ * @memberof DisplayObjectContainer# */ width: { - get: function () { + get: function () + { return this.scale.x * this.getLocalBounds().width; }, - set: function (value) { + set: function (value) + { var width = this.getLocalBounds().width; - if(width !== 0) { + if(width !== 0) + { this.scale.x = value / width; } - else { + else + { this.scale.x = 1; } @@ -73,17 +78,21 @@ * @memberof DisplayObjectContainer# */ height: { - get: function () { + get: function () + { return this.scale.y * this.getLocalBounds().height; }, - set: function (value) { + set: function (value) + { var height = this.getLocalBounds().height; - if (height !== 0) { + if (height !== 0) + { this.scale.y = value / height ; } - else { + else + { this.scale.y = 1; } @@ -100,18 +109,23 @@ * @memberof DisplayObject# */ cacheAsBitmap: { - get: function () { + get: function () + { return this._cacheAsBitmap; }, - set: function (value) { - if (this._cacheAsBitmap === value) { + set: function (value) + { + if (this._cacheAsBitmap === value) + { return; } - if (value) { + if (value) + { this._generateCachedSprite(); } - else { + else + { this._destroyCachedSprite(); } @@ -126,7 +140,8 @@ * @param child {DisplayObject} The DisplayObject to add to the container * @return {DisplayObject} The child that was added. */ -DisplayObjectContainer.prototype.addChild = function (child) { +DisplayObjectContainer.prototype.addChild = function (child) +{ return this.addChildAt(child, this.children.length); }; @@ -137,14 +152,18 @@ * @param index {Number} The index to place the child in * @return {DisplayObject} The child that was added. */ -DisplayObjectContainer.prototype.addChildAt = function (child, index) { +DisplayObjectContainer.prototype.addChildAt = function (child, index) +{ // prevent adding self as child - if (child === this) { + if (child === this) + { return; } - if (index >= 0 && index <= this.children.length) { - if (child.parent) { + if (index >= 0 && index <= this.children.length) + { + if (child.parent) + { child.parent.removeChild(child); } @@ -154,7 +173,8 @@ return child; } - else { + else + { throw new Error(child + 'addChildAt: The index '+ index +' supplied is out of bounds ' + this.children.length); } }; @@ -165,15 +185,18 @@ * @param child {DisplayObject} * @param child2 {DisplayObject} */ -DisplayObjectContainer.prototype.swapChildren = function (child, child2) { - if (child === child2) { +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) { + if (index1 < 0 || index2 < 0) + { throw new Error('swapChildren: Both the supplied DisplayObjects must be a child of the caller.'); } @@ -187,10 +210,12 @@ * @param child {DisplayObject} The DisplayObject instance to identify * @return {Number} The index position of the child display object to identify */ -DisplayObjectContainer.prototype.getChildIndex = function (child) { +DisplayObjectContainer.prototype.getChildIndex = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { throw new Error('The supplied DisplayObject must be a child of the caller'); } @@ -203,8 +228,10 @@ * @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 */ -DisplayObjectContainer.prototype.setChildIndex = function (child, index) { - if (index < 0 || index >= this.children.length) { +DisplayObjectContainer.prototype.setChildIndex = function (child, index) +{ + if (index < 0 || index >= this.children.length) + { throw new Error('The supplied index is out of bounds'); } @@ -220,8 +247,10 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child at the given index, if any. */ -DisplayObjectContainer.prototype.getChildAt = function (index) { - if (index < 0 || index >= this.children.length) { +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'); } @@ -234,10 +263,12 @@ * @param child {DisplayObject} The DisplayObject to remove * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChild = function (child) { +DisplayObjectContainer.prototype.removeChild = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { return; } @@ -250,7 +281,8 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChildAt = function (index) { +DisplayObjectContainer.prototype.removeChildAt = function (index) +{ var child = this.getChildAt(index); child.parent = null; @@ -265,24 +297,29 @@ * @param beginIndex {Number} The beginning position. Default value is 0. * @param endIndex {Number} The ending position. Default value is size of the container. */ -DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) { +DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) +{ var begin = beginIndex || 0; var end = typeof endIndex === 'number' ? endIndex : this.children.length; var range = end - begin; - if (range > 0 && range <= end) { + if (range > 0 && range <= end) + { var removed = this.children.splice(begin, range); - for (var i = 0; i < removed.length; ++i) { + for (var i = 0; i < removed.length; ++i) + { removed[i].parent = null; } return removed; } - else if (range === 0 && this.children.length === 0) { + else if (range === 0 && this.children.length === 0) + { return []; } - else { + else + { throw new RangeError('removeChildren: numeric values are outside the acceptable range.'); } }; @@ -291,7 +328,8 @@ * Generates and updates the cached sprite for this object. * */ -DisplayObjectContainer.prototype.updateCachedSprite = function () { +DisplayObjectContainer.prototype.updateCachedSprite = function () +{ this._generateCachedSprite(); }; @@ -304,7 +342,8 @@ * @param renderer {CanvasRenderer|WebGLRenderer} The renderer used to generate the texture. * @return {Texture} a texture of the graphics object */ -DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) { +DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) +{ var bounds = this.getLocalBounds(); var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0, renderer, scaleMode, resolution); @@ -322,18 +361,22 @@ * * @private */ -DisplayObjectContainer.prototype.updateTransform = function () { - if (!this.visible) { +DisplayObjectContainer.prototype.updateTransform = function () +{ + if (!this.visible) + { return; } this.displayObjectUpdateTransform(); - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { return; } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } }; @@ -346,8 +389,10 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getBounds = function () { - if (this.children.length === 0) { +DisplayObjectContainer.prototype.getBounds = function () +{ + if (this.children.length === 0) + { return math.Rectangle.EMPTY; } @@ -365,10 +410,12 @@ var childVisible = false; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -386,7 +433,8 @@ maxY = maxY > childMaxY ? maxY : childMaxY; } - if (!childVisible) { + if (!childVisible) + { return math.Rectangle.EMPTY; } @@ -407,12 +455,14 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getLocalBounds = function () { +DisplayObjectContainer.prototype.getLocalBounds = function () +{ var matrixCache = this.worldTransform; this.worldTransform = math.Matrix.IDENTITY; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } @@ -428,13 +478,16 @@ * * @param renderer {WebGLRenderer} The renderer */ -DisplayObjectContainer.prototype.renderWebGL = function (renderer) { +DisplayObjectContainer.prototype.renderWebGL = function (renderer) +{ // if the object is not visible or the alpha is 0 then no need to render this element - if (!this.visible || this.alpha <= 0) { + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } @@ -442,14 +495,17 @@ var i, j; // do a quick check to see if this element has a mask or a filter. - if (this._mask || this._filters) { + if (this._mask || this._filters) + { // push filter first as we need to ensure the stencil buffer is correct for any masking - if (this._filters) { + if (this._filters) + { renderer.spriteBatch.flush(); renderer.filterManager.pushFilter(this._filterBlock); } - if (this._mask) { + if (this._mask) + { renderer.spriteBatch.stop(); renderer.maskManager.pushMask(this.mask, renderer); renderer.spriteBatch.start(); @@ -459,36 +515,42 @@ this._renderWebGL(renderer); // now loop through the children and make sure they get rendered - for (i = 0, j = this.children.length; i < j; i++) { + for (i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderWebGL(renderer); } // time to stop the sprite batch as either a mask element or a filter draw will happen next renderer.spriteBatch.stop(); - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(this._mask, renderer); } - if (this._filters) { + if (this._filters) + { renderer.filterManager.popFilter(); } renderer.spriteBatch.start(); } - else { + else + { this._renderWebGL(renderer); // simple render children! - for (i = 0, j = this.children.length; i < j; ++i) { + for (i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderWebGL(renderer); } } }; -DisplayObjectContainer.prototype._renderWebGL = function (renderer) { +DisplayObjectContainer.prototype._renderWebGL = function (renderer) +{ // this is where content itself gets renderd.. @@ -499,25 +561,31 @@ * * @param renderer {CanvasRenderer} The renderer */ -DisplayObjectContainer.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0) { +DisplayObjectContainer.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -528,13 +596,16 @@ * @param renderer {WebGLRenderer|CanvasRenderer} The renderer * @private */ -DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) { +DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) +{ this._cachedSprite.worldAlpha = this.worldAlpha; - if (renderer.gl) { + if (renderer.gl) + { this._cachedSprite.renderWebGL(renderer); } - else { + else + { this._cachedSprite.renderCanvas(renderer); } }; @@ -544,10 +615,12 @@ * * @private */ -DisplayObjectContainer.prototype._generateCachedSprite = function () { +DisplayObjectContainer.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { // TODO - RenderTexture now *requires* a renderer instance, so this is like broken // because `renderer` isn't actually in scope here :P var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0); @@ -555,7 +628,8 @@ this._cachedSprite = new Sprite(renderTexture); this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.texture.resize(bounds.width | 0, bounds.height | 0); } @@ -580,8 +654,10 @@ * * @private */ -DisplayObjectContainer.prototype._destroyCachedSprite = function () { - if (!this._cachedSprite) { +DisplayObjectContainer.prototype._destroyCachedSprite = function () +{ + if (!this._cachedSprite) + { return; } diff --git a/src/core/display/Sprite.js b/src/core/display/Sprite.js index 707da24..5862aef 100644 --- a/src/core/display/Sprite.js +++ b/src/core/display/Sprite.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param texture {Texture} The texture for this sprite */ -function Sprite(texture) { +function Sprite(texture) +{ DisplayObjectContainer.call(this); /** @@ -85,12 +86,14 @@ this.texture = texture || Texture.EMPTY; } -Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) { +Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) +{ DisplayObjectContainer.prototype.destroy.call(this); this.anchor = null; - if (destroyTexture) { + if (destroyTexture) + { this._texture.destroy(destroyBaseTexture); } @@ -111,10 +114,12 @@ * @memberof Sprite# */ width: { - get: function () { + get: function () + { return this.scale.x * this.texture.frame.width; }, - set: function (value) { + set: function (value) + { this.scale.x = value / this.texture.frame.width; this._width = value; } @@ -127,10 +132,12 @@ * @memberof Sprite# */ height: { - get: function () { + get: function () + { return this.scale.y * this.texture.frame.height; }, - set: function (value) { + set: function (value) + { this.scale.y = value / this.texture.frame.height; this._height = value; } @@ -143,23 +150,29 @@ * @memberof Sprite# */ texture: { - get: function () { + get: function () + { return this._texture; }, - set: function (value) { - if (this._texture === value) { + set: function (value) + { + if (this._texture === value) + { return; } this._texture = value; this.cachedTint = 0xFFFFFF; - if (value) { + if (value) + { // wait for the texture to load - if (value.baseTexture.hasLoaded) { + if (value.baseTexture.hasLoaded) + { this._onTextureUpdate(); } - else { + else + { value.once('update', this._onTextureUpdate.bind(this)); } } @@ -172,18 +185,22 @@ * * @private */ -Sprite.prototype._onTextureUpdate = function () { +Sprite.prototype._onTextureUpdate = function () +{ // so if _width is 0 then width was not set.. - if (this._width) { + if (this._width) + { this.scale.x = this._width / this.texture.frame.width; } - if (this._height) { + if (this._height) + { this.scale.y = this._height / this.texture.frame.height; } }; -Sprite.prototype._renderWebGL = function (renderer) { +Sprite.prototype._renderWebGL = function (renderer) +{ // this is where content gets renderd.. // watch this space for a little render state manager.. @@ -197,7 +214,8 @@ * @param matrix {Matrix} the transformation matrix of the sprite * @return {Rectangle} the framing rectangle */ -Sprite.prototype.getBounds = function (matrix) { +Sprite.prototype.getBounds = function (matrix) +{ var width = this.texture.frame.width; var height = this.texture.frame.height; @@ -224,11 +242,13 @@ if(b === 0 && c === 0) { // scale may be negative! - if (a < 0) { + if (a < 0) + { a *= -1; } - if (d < 0) { + if (d < 0) + { d *= -1; } @@ -293,28 +313,34 @@ * * @param renderer {CanvasRenderer} The renderer */ -Sprite.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) { +Sprite.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) + { return; } - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; renderer.context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } // Ignore null sources - if (this.texture.valid) { + if (this.texture.valid) + { var resolution = this.texture.baseTexture.resolution / renderer.resolution; renderer.context.globalAlpha = this.worldAlpha; // If smoothingEnabled is supported and we need to change the smoothing property for this texture - if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) { + if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) + { renderer.scaleMode = this.texture.baseTexture.scaleMode; renderer.context[renderer.smoothProperty] = (renderer.scaleMode === CONST.scaleModes.LINEAR); } @@ -324,7 +350,8 @@ var dy = (this.texture.trim ? this.texture.trim.y : 0) - (this.anchor.y * this.texture.trim.height); // Allow for pixel rounding - if (renderer.roundPixels) { + if (renderer.roundPixels) + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -337,7 +364,8 @@ dx = dx | 0; dy = dy | 0; } - else { + else + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -348,8 +376,10 @@ ); } - if (this.tint !== 0xFFFFFF) { - if (this.cachedTint !== this.tint) { + if (this.tint !== 0xFFFFFF) + { + if (this.cachedTint !== this.tint) + { this.cachedTint = this.tint; // TODO clean up caching - how to clean up the caches? @@ -368,7 +398,8 @@ this.texture.crop.height / resolution ); } - else { + else + { renderer.context.drawImage( this.texture.baseTexture.source, this.texture.crop.x, @@ -383,11 +414,13 @@ } } - for (var i = 0, j = this.children.length; i < j; i++) { + for (var i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -402,10 +435,12 @@ * @param frameId {String} The frame Id of the texture in the cache * @return {Sprite} A new Sprite using a texture from the texture cache matching the frameId */ -Sprite.fromFrame = function (frameId) { +Sprite.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache' + this); } @@ -420,6 +455,7 @@ * @param imageId {String} The image url of the texture * @return {Sprite} A new Sprite using a texture from the texture cache matching the image id */ -Sprite.fromImage = function (imageId, crossorigin, scaleMode) { +Sprite.fromImage = function (imageId, crossorigin, scaleMode) +{ return new Sprite(Texture.fromImage(imageId, crossorigin, scaleMode)); }; diff --git a/src/core/display/SpriteBatch.js b/src/core/display/SpriteBatch.js index 3187777..c196fef 100644 --- a/src/core/display/SpriteBatch.js +++ b/src/core/display/SpriteBatch.js @@ -12,7 +12,8 @@ * ```js * var container = new SpriteBatch(); * - * for(var i = 0; i < 100; ++i) { + * for(var i = 0; i < 100; ++i) + * { * var sprite = new PIXI.Sprite.fromImage("myImage.png"); * container.addChild(sprite); * } @@ -25,7 +26,8 @@ */ //TODO RENAME to PARTICLE CONTAINER? -function SpriteBatch() { +function SpriteBatch() +{ DisplayObjectContainer.call(this); } @@ -38,7 +40,8 @@ * * @private */ -SpriteBatch.prototype.updateTransform = function () { +SpriteBatch.prototype.updateTransform = function () +{ // TODO don't need to! this.displayObjectUpdateTransform(); // PIXI.DisplayObjectContainer.prototype.updateTransform.call( this ); @@ -50,8 +53,10 @@ * @param renderer {WebGLRenderer} The webgl renderer * @private */ -SpriteBatch.prototype.renderWebGL = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderWebGL = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -71,8 +76,10 @@ * @param renderer {CanvasRenderer} The canvas renderer * @private */ -SpriteBatch.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -84,10 +91,12 @@ this.displayObjectUpdateTransform(); - for (var i = 0; i < this.children.length; ++i) { + for (var i = 0; i < this.children.length; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -95,9 +104,11 @@ context.globalAlpha = this.worldAlpha * child.alpha; - if (child.rotation % (Math.PI * 2) === 0) { + if (child.rotation % (Math.PI * 2) === 0) + { // this is the fastest way to optimise! - if rotation is 0 then we can avoid any kind of setTransform call - if (isRotated) { + if (isRotated) + { context.setTransform( transform.a, transform.b, @@ -122,8 +133,10 @@ frame.height * child.scale.y ); } - else { - if (!isRotated) { + else + { + if (!isRotated) + { isRotated = true; } @@ -131,7 +144,8 @@ var childTransform = child.worldTransform; - if (renderer.roundPixels) { + if (renderer.roundPixels) + { context.setTransform( childTransform.a, childTransform.b, @@ -141,7 +155,8 @@ childTransform.ty | 0 ); } - else { + else + { context.setTransform( childTransform.a, childTransform.b, diff --git a/src/core/index.js b/src/core/index.js index 3954b6f..eb4a82b 100644 --- a/src/core/index.js +++ b/src/core/index.js @@ -58,11 +58,13 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRenderer: function (width, height, options, noWebGL) { + autoDetectRenderer: function (width, height, options, noWebGL) + { width = width || 800; height = height || 600; - if (!noWebGL && require('webgl-enabled')()) { + if (!noWebGL && require('webgl-enabled')()) + { return new core.WebGLRenderer(width, height, options); } @@ -87,7 +89,8 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRecommendedRenderer: function (width, height, options) { + autoDetectRecommendedRenderer: function (width, height, options) + { var isAndroid = /Android/i.test(navigator.userAgent); return core.autoDetectRenderer(width, height, options, isAndroid); diff --git a/src/core/math/Matrix.js b/src/core/math/Matrix.js index c2f87e2..2ff4848 100644 --- a/src/core/math/Matrix.js +++ b/src/core/math/Matrix.js @@ -10,7 +10,8 @@ * @class * @namespace PIXI */ -function Matrix() { +function Matrix() +{ /** * @member {number} * @default 1 @@ -63,7 +64,8 @@ * * @param array {number[]} The array that the matrix will be populated from. */ -Matrix.prototype.fromArray = function (array) { +Matrix.prototype.fromArray = function (array) +{ this.a = array[0]; this.b = array[1]; this.c = array[3]; @@ -78,14 +80,17 @@ * @param transpose {boolean} Whether we need to transpose the matrix or not * @return {number[]} the newly created array which contains the matrix */ -Matrix.prototype.toArray = function (transpose) { - if (!this.array) { +Matrix.prototype.toArray = function (transpose) +{ + if (!this.array) + { this.array = new Float32Array(9); } var array = this.array; - if (transpose) { + if (transpose) + { array[0] = this.a; array[1] = this.b; array[2] = 0; @@ -96,7 +101,8 @@ array[7] = this.ty; array[8] = 1; } - else { + else + { array[0] = this.a; array[1] = this.c; array[2] = this.tx; @@ -119,7 +125,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, transformed through this matrix */ -Matrix.prototype.apply = function (pos, newPos) { +Matrix.prototype.apply = function (pos, newPos) +{ newPos = newPos || new Point(); newPos.x = this.a * pos.x + this.c * pos.y + this.tx; @@ -136,7 +143,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, inverse-transformed through this matrix */ -Matrix.prototype.applyInverse = function (pos, newPos) { +Matrix.prototype.applyInverse = function (pos, newPos) +{ newPos = newPos || new Point(); var id = 1 / (this.a * this.d + this.c * -this.b); @@ -154,7 +162,8 @@ * @param {number} y * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.translate = function (x, y) { +Matrix.prototype.translate = function (x, y) +{ this.tx += x; this.ty += y; @@ -168,7 +177,8 @@ * @param {number} y The amount to scale vertically * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.scale = function (x, y) { +Matrix.prototype.scale = function (x, y) +{ this.a *= x; this.d *= y; this.c *= x; @@ -186,7 +196,8 @@ * @param {number} angle - The angle in radians. * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.rotate = function (angle) { +Matrix.prototype.rotate = function (angle) +{ var cos = Math.cos( angle ); var sin = Math.sin( angle ); @@ -210,7 +221,8 @@ * @param {Matrix} matrix * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.append = function (matrix) { +Matrix.prototype.append = function (matrix) +{ var a1 = this.a; var b1 = this.b; var c1 = this.c; @@ -232,7 +244,8 @@ * * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.identity = function () { +Matrix.prototype.identity = function () +{ this.a = 1; this.b = 0; this.c = 0; diff --git a/src/core/math/Point.js b/src/core/math/Point.js index 7565b2d..632f346 100644 --- a/src/core/math/Point.js +++ b/src/core/math/Point.js @@ -7,7 +7,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -function Point(x, y) { +function Point(x, y) +{ /** * @member {number} * @default 0 @@ -29,7 +30,8 @@ * * @return {Point} a copy of the point */ -Point.prototype.clone = function () { +Point.prototype.clone = function () +{ return new Point(this.x, this.y); }; @@ -40,7 +42,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -Point.prototype.set = function (x, y) { +Point.prototype.set = function (x, y) +{ this.x = x || 0; this.y = y || ( (y !== 0) ? this.x : 0 ) ; }; diff --git a/src/core/math/shapes/Circle.js b/src/core/math/shapes/Circle.js index 69cfdc9..4d76efc 100644 --- a/src/core/math/shapes/Circle.js +++ b/src/core/math/shapes/Circle.js @@ -10,7 +10,8 @@ * @param y {number} The Y coordinate of the center of this circle * @param radius {number} The radius of the circle */ -function Circle(x, y, radius) { +function Circle(x, y, radius) +{ /** * @member {number} * @default 0 @@ -46,7 +47,8 @@ * @method clone * @return {Circle} a copy of the Circle */ -Circle.prototype.clone = function () { +Circle.prototype.clone = function () +{ return new Circle(this.x, this.y, this.radius); }; @@ -58,8 +60,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Circle */ -Circle.prototype.contains = function (x, y) { - if (this.radius <= 0) { +Circle.prototype.contains = function (x, y) +{ + if (this.radius <= 0) + { return false; } @@ -79,6 +83,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Circle.prototype.getBounds = function () { +Circle.prototype.getBounds = function () +{ return new Rectangle(this.x - this.radius, this.y - this.radius, this.radius * 2, this.radius * 2); }; diff --git a/src/core/math/shapes/Ellipse.js b/src/core/math/shapes/Ellipse.js index 4f2d066..fefd01a 100644 --- a/src/core/math/shapes/Ellipse.js +++ b/src/core/math/shapes/Ellipse.js @@ -11,7 +11,8 @@ * @param width {number} The half width of this ellipse * @param height {number} The half height of this ellipse */ -function Ellipse(x, y, width, height) { +function Ellipse(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -53,7 +54,8 @@ * @method clone * @return {Ellipse} a copy of the ellipse */ -Ellipse.prototype.clone = function () { +Ellipse.prototype.clone = function () +{ return new Ellipse(this.x, this.y, this.width, this.height); }; @@ -65,8 +67,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coords are within this ellipse */ -Ellipse.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Ellipse.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } @@ -86,6 +90,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Ellipse.prototype.getBounds = function () { +Ellipse.prototype.getBounds = function () +{ return new Rectangle(this.x - this.width, this.y - this.height, this.width, this.height); }; diff --git a/src/core/math/shapes/Polygon.js b/src/core/math/shapes/Polygon.js index ae89148..fea6d37 100644 --- a/src/core/math/shapes/Polygon.js +++ b/src/core/math/shapes/Polygon.js @@ -10,16 +10,20 @@ * arguments passed can be flat x,y values e.g. `new Polygon(x,y, x,y, x,y, ...)` where `x` and `y` are * Numbers. */ -function Polygon(points) { +function Polygon(points) +{ //if points isn't an array, use arguments as the array - if (!(points instanceof Array)) { + if (!(points instanceof Array)) + { points = Array.prototype.slice.call(arguments); } //if this is a flat array of numbers, convert it to points - if (points[0] instanceof Point) { + if (points[0] instanceof Point) + { var p = []; - for (var i = 0, il = points.length; i < il; i++) { + for (var i = 0, il = points.length; i < il; i++) + { p.push(points[i].x, points[i].y); } @@ -51,7 +55,8 @@ * * @return {Polygon} a copy of the polygon */ -Polygon.prototype.clone = function () { +Polygon.prototype.clone = function () +{ return new Polygon(this.points.slice()); }; @@ -62,19 +67,22 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this polygon */ -Polygon.prototype.contains = function (x, y) { +Polygon.prototype.contains = function (x, y) +{ var inside = false; // use some raycasting to test hits // https://github.com/substack/point-in-polygon/blob/master/index.js var length = this.points.length / 2; - for (var i = 0, j = length - 1; i < length; j = i++) { + for (var i = 0, j = length - 1; i < length; j = i++) + { var xi = this.points[i * 2], yi = this.points[i * 2 + 1], xj = this.points[j * 2], yj = this.points[j * 2 + 1], intersect = ((yi > y) !== (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi); - if (intersect) { + if (intersect) + { inside = !inside; } } diff --git a/src/core/math/shapes/Rectangle.js b/src/core/math/shapes/Rectangle.js index 16ac62a..4008b68 100644 --- a/src/core/math/shapes/Rectangle.js +++ b/src/core/math/shapes/Rectangle.js @@ -10,7 +10,8 @@ * @param width {number} The overall width of this rectangle * @param height {number} The overall height of this rectangle */ -function Rectangle(x, y, width, height) { +function Rectangle(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -60,7 +61,8 @@ * * @return {Rectangle} a copy of the rectangle */ -Rectangle.prototype.clone = function () { +Rectangle.prototype.clone = function () +{ return new Rectangle(this.x, this.y, this.width, this.height); }; @@ -71,13 +73,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rectangle */ -Rectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Rectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/math/shapes/RoundedRectangle.js b/src/core/math/shapes/RoundedRectangle.js index 27d286e..7bf6411 100644 --- a/src/core/math/shapes/RoundedRectangle.js +++ b/src/core/math/shapes/RoundedRectangle.js @@ -11,7 +11,8 @@ * @param height {number} The overall height of this rounded rectangle * @param radius {number} Controls the radius of the rounded corners */ -function RoundedRectangle(x, y, width, height, radius) { +function RoundedRectangle(x, y, width, height, radius) +{ /** * @member {number} * @default 0 @@ -58,7 +59,8 @@ * * @return {RoundedRectangle} a copy of the rounded rectangle */ -RoundedRectangle.prototype.clone = function () { +RoundedRectangle.prototype.clone = function () +{ return new RoundedRectangle(this.x, this.y, this.width, this.height, this.radius); }; @@ -69,13 +71,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rounded Rectangle */ -RoundedRectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +RoundedRectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/primitives/Graphics.js b/src/core/primitives/Graphics.js index 261c534..e902d2a 100644 --- a/src/core/primitives/Graphics.js +++ b/src/core/primitives/Graphics.js @@ -16,7 +16,8 @@ * @extends DisplayObjectContainer * @namespace PIXI */ -function Graphics() { +function Graphics() +{ DisplayObjectContainer.call(this); this.renderable = true; @@ -154,16 +155,20 @@ * @private */ cacheAsBitmap: { - get: function () { + get: function () + { return this._cacheAsBitmap; }, - set: function (value) { + set: function (value) + { this._cacheAsBitmap = value; - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._generateCachedSprite(); } - else { + else + { this.destroyCachedSprite(); this.dirty = true; } @@ -176,7 +181,8 @@ * * @return {Graphics} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ var clone = new Graphics(); clone.renderable = this.renderable; @@ -192,7 +198,8 @@ clone.cachedSpriteDirty = this.cachedSpriteDirty; // copy graphics data - for (var i = 0; i < this.graphicsData.length; ++i) { + for (var i = 0; i < this.graphicsData.length; ++i) + { clone.graphicsData.push(this.graphicsData.clone()); } @@ -211,17 +218,21 @@ * @param alpha {number} alpha of the line to draw, will update the objects stored style * @return {Graphics} */ -Graphics.prototype.lineStyle = function (lineWidth, color, alpha) { +Graphics.prototype.lineStyle = function (lineWidth, color, alpha) +{ this.lineWidth = lineWidth || 0; this.lineColor = color || 0; this.lineAlpha = (arguments.length < 3) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length) + { // halfway through a line? start a new one! this.drawShape( new math.Polygon( this.currentPath.shape.points.slice(-2) )); } - else { + else + { // otherwise its empty so lets just set the line properties this.currentPath.lineWidth = this.lineWidth; this.currentPath.lineColor = this.lineColor; @@ -239,7 +250,8 @@ * @param y {number} the Y coordinate to move to * @return {Graphics} */ -Graphics.prototype.moveTo = function (x, y) { +Graphics.prototype.moveTo = function (x, y) +{ this.drawShape(new math.Polygon([x,y])); return this; @@ -253,7 +265,8 @@ * @param y {number} the Y coordinate to draw to * @return {Graphics} */ -Graphics.prototype.lineTo = function (x, y) { +Graphics.prototype.lineTo = function (x, y) +{ this.currentPath.shape.points.push(x, y); this.dirty = true; @@ -270,13 +283,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -285,7 +302,8 @@ n = 20, points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { this.moveTo(0, 0); } @@ -293,7 +311,8 @@ var fromY = points[points.length-1]; var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; xa = fromX + ( (cpX - fromX) * j ); @@ -319,13 +338,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -342,7 +365,8 @@ var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; dt = (1 - j); @@ -373,13 +397,17 @@ * @param radius {number} The radius of the arc * @return {Graphics} */ -Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points.push(x1, y1); } } - else { + else + { this.moveTo(x1, y1); } @@ -392,12 +420,15 @@ b2 = x2 - x1, mm = Math.abs(a1 * b2 - b1 * a2); - if (mm < 1.0e-8 || radius === 0) { - if (points[points.length-2] !== x1 || points[points.length-1] !== y1) { + if (mm < 1.0e-8 || radius === 0) + { + if (points[points.length-2] !== x1 || points[points.length-1] !== y1) + { points.push(x1, y1); } } - else { + else + { var dd = a1 * a1 + b1 * b1, cc = a2 * a2 + b2 * b2, tt = a1 * a2 + b1 * b2, @@ -433,42 +464,51 @@ * @param anticlockwise {boolean} Optional. Specifies whether the drawing should be counterclockwise or clockwise. False is default, and indicates clockwise, while true indicates counter-clockwise. * @return {Graphics} */ -Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) { +Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) +{ var startX = cx + Math.cos(startAngle) * radius; var startY = cy + Math.sin(startAngle) * radius; var points; // TODO - This if-else makes no sense. It uses currentPath in the else where it doesn't exist... - if (this.currentPath) { + if (this.currentPath) + { points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { points.push(startX, startY); } - else if (points[points.length-2] !== startX || points[points.length-1] !== startY) { + else if (points[points.length-2] !== startX || points[points.length-1] !== startY) + { points.push(startX, startY); } } - else { + else + { this.moveTo(startX, startY); points = this.currentPath.shape.points; } - if (startAngle === endAngle) { + if (startAngle === endAngle) + { return this; } - if (!anticlockwise && endAngle <= startAngle) { + if (!anticlockwise && endAngle <= startAngle) + { endAngle += Math.PI * 2; } - else if (anticlockwise && startAngle <= endAngle) { + else if (anticlockwise && startAngle <= endAngle) + { startAngle += Math.PI * 2; } var sweep = anticlockwise ? (startAngle - endAngle) *-1 : (endAngle - startAngle); var segs = (Math.abs(sweep)/ (Math.PI * 2)) * 40; - if (sweep === 0) { + if (sweep === 0) + { return this; } @@ -482,7 +522,8 @@ var remainder = ( segMinus % 1 ) / segMinus; - for (var i = 0; i <= segMinus; ++i) { + for (var i = 0; i <= segMinus; ++i) + { var real = i + remainder * i; var angle = ((theta) + startAngle + (theta2 * real)); @@ -506,13 +547,16 @@ * @param alpha {number} the alpha of the fill * @return {Graphics} */ -Graphics.prototype.beginFill = function (color, alpha) { +Graphics.prototype.beginFill = function (color, alpha) +{ this.filling = true; this.fillColor = color || 0; this.fillAlpha = (alpha === undefined) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length <= 2) + { this.currentPath.fill = this.filling; this.currentPath.fillColor = this.fillColor; this.currentPath.fillAlpha = this.fillAlpha; @@ -526,7 +570,8 @@ * * @return {Graphics} */ -Graphics.prototype.endFill = function () { +Graphics.prototype.endFill = function () +{ this.filling = false; this.fillColor = null; this.fillAlpha = 1; @@ -542,7 +587,8 @@ * @param height {number} The height of the rectangle * @return {Graphics} */ -Graphics.prototype.drawRect = function ( x, y, width, height ) { +Graphics.prototype.drawRect = function ( x, y, width, height ) +{ this.drawShape(new math.Rectangle(x,y, width, height)); return this; @@ -556,7 +602,8 @@ * @param height {number} The height of the rectangle * @param radius {number} Radius of the rectangle corners */ -Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) { +Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) +{ this.drawShape(new math.RoundedRectangle(x, y, width, height, radius)); return this; @@ -570,7 +617,8 @@ * @param radius {number} The radius of the circle * @return {Graphics} */ -Graphics.prototype.drawCircle = function (x, y, radius) { +Graphics.prototype.drawCircle = function (x, y, radius) +{ this.drawShape(new math.Circle(x,y, radius)); return this; @@ -585,7 +633,8 @@ * @param height {number} The half height of the ellipse * @return {Graphics} */ -Graphics.prototype.drawEllipse = function (x, y, width, height) { +Graphics.prototype.drawEllipse = function (x, y, width, height) +{ this.drawShape(new math.Ellipse(x, y, width, height)); return this; @@ -597,8 +646,10 @@ * @param path {Array} The path data used to construct the polygon. * @return {Graphics} */ -Graphics.prototype.drawPolygon = function (path) { - if (!(path instanceof Array)) { +Graphics.prototype.drawPolygon = function (path) +{ + if (!(path instanceof Array)) + { path = Array.prototype.slice.call(arguments); } @@ -612,7 +663,8 @@ * * @return {Graphics} */ -Graphics.prototype.clear = function () { +Graphics.prototype.clear = function () +{ this.lineWidth = 0; this.filling = false; @@ -631,7 +683,8 @@ * @param scaleMode {number} Should be one of the scaleMode consts * @return {Texture} a texture of the graphics object */ -Graphics.prototype.generateTexture = function (resolution, scaleMode) { +Graphics.prototype.generateTexture = function (resolution, scaleMode) +{ resolution = resolution || 1; var bounds = this.getBounds(); @@ -655,17 +708,21 @@ * * @param renderer {WebGLRenderer} */ -Graphics.prototype._renderWebGL = function (renderer) { +Graphics.prototype._renderWebGL = function (renderer) +{ // if the sprite is not visible or the alpha is 0 then no need to render this element - if (this.isMask === true) { + if (this.isMask === true) + { return; } // this code may still be needed so leaving for now.. - // + // /* - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture on the gpu too! @@ -681,17 +738,24 @@ return; } - */ - - // check if the webgl graphic needs to be updated - if (this.glDirty) { - this.dirty = true; - this.glDirty = false; - } + else */ - renderer.setObjectRendererer(renderer.graphicsRenderer); - renderer.graphicsRenderer.render(this); + renderer.spriteBatch.stop(); + renderer.blendModeManager.setBlendMode(this.blendMode); + // check blend mode + renderer.blendModeManager.setBlendMode( this.blendMode ); + + // check if the webgl graphic needs to be updated + if (this.glDirty) + { + this.dirty = true; + this.glDirty = false; + } + + WebGLGraphics.renderGraphics(this, renderer); + + renderer.spriteBatch.start(); }; /** @@ -700,14 +764,18 @@ * @param renderer {CanvasRenderer} * @private */ -Graphics.prototype.renderCanvas = function (renderer) { +Graphics.prototype.renderCanvas = function (renderer) +{ // 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.isMask === true) { + if (!this.visible || this.alpha <= 0 || this.isMask === true) + { return; } - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture @@ -723,16 +791,19 @@ return; } - else { + else + { var context = renderer.context; var transform = this.worldTransform; - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } @@ -748,11 +819,13 @@ CanvasGraphics.renderGraphics(this, context); - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } } @@ -763,13 +836,16 @@ * * @return {Rectangle} the rectangular bounding area */ -Graphics.prototype.getBounds = function (matrix) { +Graphics.prototype.getBounds = function (matrix) +{ // return an empty object if the item is a mask! - if (this.isMask) { + if (this.isMask) + { return math.Rectangle.EMPTY; } - if (this.dirty) { + if (this.dirty) + { this.updateLocalBounds(); this.glDirty = true; @@ -841,23 +917,27 @@ * Update the bounds of the object * */ -Graphics.prototype.updateLocalBounds = function () { +Graphics.prototype.updateLocalBounds = function () +{ var minX = Infinity; var maxX = -Infinity; var minY = Infinity; var maxY = -Infinity; - if (this.graphicsData.length) { + if (this.graphicsData.length) + { var shape, points, x, y, w, h; - for (var i = 0; i < this.graphicsData.length; i++) { + for (var i = 0; i < this.graphicsData.length; i++) + { var data = this.graphicsData[i]; var type = data.type; var lineWidth = data.lineWidth; shape = data.shape; - if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) { + if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) + { x = shape.x - lineWidth/2; y = shape.y - lineWidth/2; w = shape.width + lineWidth; @@ -869,7 +949,8 @@ minY = y < minY ? y : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.CIRC) { + else if (type === CONST.SHAPES.CIRC) + { x = shape.x; y = shape.y; w = shape.radius + lineWidth/2; @@ -881,7 +962,8 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.ELIP) { + else if (type === CONST.SHAPES.ELIP) + { x = shape.x; y = shape.y; w = shape.width + lineWidth/2; @@ -893,11 +975,13 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else { + else + { // POLY points = shape.points; - for (var j = 0; j < points.length; j += 2) { + for (var j = 0; j < points.length; j += 2) + { x = points[j]; y = points[j+1]; @@ -910,7 +994,8 @@ } } } - else { + else + { minX = 0; maxX = 0; minY = 0; @@ -931,10 +1016,12 @@ * * @private */ -Graphics.prototype._generateCachedSprite = function () { +Graphics.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { var canvasBuffer = new CanvasBuffer(bounds.width, bounds.height); var texture = Texture.fromCanvas(canvasBuffer.canvas); @@ -943,7 +1030,8 @@ this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.buffer.resize(bounds.width, bounds.height); } @@ -968,7 +1056,8 @@ * * @private */ -Graphics.prototype.updateCachedSpriteTexture = function () { +Graphics.prototype.updateCachedSpriteTexture = function () +{ var cachedSprite = this._cachedSprite; var texture = cachedSprite.texture; var canvas = cachedSprite.buffer.canvas; @@ -989,7 +1078,8 @@ * Destroys a previous cached sprite. * */ -Graphics.prototype.destroyCachedSprite = function () { +Graphics.prototype.destroyCachedSprite = function () +{ this._cachedSprite.texture.destroy(true); // let the gc collect the unused sprite @@ -1003,10 +1093,13 @@ * @param {Circle|Rectangle|Ellipse|Line|Polygon} shape The Shape object to draw. * @return {GraphicsData} The generated GraphicsData object. */ -Graphics.prototype.drawShape = function (shape) { - if (this.currentPath) { +Graphics.prototype.drawShape = function (shape) +{ + if (this.currentPath) + { // check current path! - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath.shape.points.length <= 2) + { this.graphicsData.pop(); } } @@ -1017,7 +1110,8 @@ this.graphicsData.push(data); - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { data.shape.closed = this.filling; this.currentPath = data; } diff --git a/src/core/primitives/GraphicsData.js b/src/core/primitives/GraphicsData.js index 99decbe..788f6f2 100644 --- a/src/core/primitives/GraphicsData.js +++ b/src/core/primitives/GraphicsData.js @@ -4,7 +4,8 @@ * @class * @namespace PIXI */ -function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) { +function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) +{ this.lineWidth = lineWidth; this.lineColor = lineColor; this.lineAlpha = lineAlpha; @@ -27,7 +28,8 @@ * * @return {GraphicsData} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ return new GraphicsData( this.lineWidth, this.lineColor, diff --git a/src/core/renderers/canvas/CanvasRenderer.js b/src/core/renderers/canvas/CanvasRenderer.js index 15a0978..7aebd44 100644 --- a/src/core/renderers/canvas/CanvasRenderer.js +++ b/src/core/renderers/canvas/CanvasRenderer.js @@ -17,17 +17,22 @@ * @param [options.resolution=1] {number} the resolution of the renderer retina would be 2 * @param [options.clearBeforeRender=true] {boolean} This sets if the CanvasRenderer will clear the canvas or not before the new render pass. */ -function CanvasRenderer(width, height, options) { +function CanvasRenderer(width, height, options) +{ utils.sayHello('Canvas'); - if (options) { - for (var i in CONST.defaultRenderOptions) { - if (typeof options[i] === 'undefined') { + if (options) + { + for (var i in CONST.defaultRenderOptions) + { + if (typeof options[i] === 'undefined') + { options[i] = CONST.defaultRenderOptions[i]; } } } - else { + else + { options = CONST.defaultRenderOptions; } @@ -156,19 +161,24 @@ this.smoothProperty = null; - if (this.context.imageSmoothingEnabled) { + if (this.context.imageSmoothingEnabled) + { this.smoothProperty = 'imageSmoothingEnabled'; } - else if (this.context.webkitImageSmoothingEnabled) { + else if (this.context.webkitImageSmoothingEnabled) + { this.smoothProperty = 'webkitImageSmoothingEnabled'; } - else if (this.context.mozImageSmoothingEnabled) { + else if (this.context.mozImageSmoothingEnabled) + { this.smoothProperty = 'mozImageSmoothingEnabled'; } - else if (this.context.oImageSmoothingEnabled) { + else if (this.context.oImageSmoothingEnabled) + { this.smoothProperty = 'oImageSmoothingEnabled'; } - else if (this.context.msImageSmoothingEnabled) { + else if (this.context.msImageSmoothingEnabled) + { this.smoothProperty = 'msImageSmoothingEnabled'; } @@ -193,10 +203,12 @@ * @memberof CanvasRenderer# */ backgroundColor: { - get: function () { + get: function () + { return this._backgroundColor; }, - set: function (val) { + set: function (val) + { this._backgroundColor = val; this._backgroundColorString = utils.hex2string(val); } @@ -208,7 +220,8 @@ * * @param object {DisplayObject} the object to be rendered */ -CanvasRenderer.prototype.render = function (object) { +CanvasRenderer.prototype.render = function (object) +{ object.updateTransform(); this.context.setTransform(1,0,0,1,0,0); @@ -218,16 +231,20 @@ this.currentBlendMode = CONST.blendModes.NORMAL; this.context.globalCompositeOperation = this.blendModes[CONST.blendModes.NORMAL]; - if (navigator.isCocoonJS && this.view.screencanvas) { + if (navigator.isCocoonJS && this.view.screencanvas) + { this.context.fillStyle = 'black'; this.context.clear(); } - if (this.clearBeforeRender) { - if (this.transparent) { + if (this.clearBeforeRender) + { + if (this.transparent) + { this.context.clearRect(0, 0, this.width, this.height); } - else { + else + { this.context.fillStyle = this._backgroundColorString; this.context.fillRect(0, 0, this.width , this.height); } @@ -241,8 +258,10 @@ * * @param [removeView=false] {boolean} Removes the Canvas element from the DOM. */ -CanvasRenderer.prototype.destroy = function (removeView) { - if (removeView && this.view.parent) { +CanvasRenderer.prototype.destroy = function (removeView) +{ + if (removeView && this.view.parent) + { this.view.parent.removeChild(this.view); } @@ -257,14 +276,16 @@ * @param width {number} the new width of the canvas view * @param height {number} the new height of the canvas view */ -CanvasRenderer.prototype.resize = function (width, height) { +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) { + if (this.autoResize) + { this.view.style.width = this.width / this.resolution + 'px'; this.view.style.height = this.height / this.resolution + 'px'; } @@ -276,7 +297,8 @@ * @param displayObject {DisplayObject} The displayObject to render * @private */ -CanvasRenderer.prototype.renderDisplayObject = function (displayObject) { +CanvasRenderer.prototype.renderDisplayObject = function (displayObject) +{ displayObject.renderCanvas(this); }; @@ -285,11 +307,14 @@ * * @private */ -CanvasRenderer.prototype._mapBlendModes = function () { - if (!this.blendModes) { +CanvasRenderer.prototype._mapBlendModes = function () +{ + if (!this.blendModes) + { this.blendModes = {}; - if (utils.canUseNewCanvasBlendModes()) { + if (utils.canUseNewCanvasBlendModes()) + { this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? this.blendModes[CONST.blendModes.MULTIPLY] = 'multiply'; @@ -308,7 +333,8 @@ this.blendModes[CONST.blendModes.COLOR] = 'color'; this.blendModes[CONST.blendModes.LUMINOSITY] = 'luminosity'; } - else { + else + { // this means that the browser does not support the cool new blend modes in canvas 'cough' ie 'cough' this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? diff --git a/src/core/renderers/canvas/utils/CanvasBuffer.js b/src/core/renderers/canvas/utils/CanvasBuffer.js index ebe5d47..b183a66 100644 --- a/src/core/renderers/canvas/utils/CanvasBuffer.js +++ b/src/core/renderers/canvas/utils/CanvasBuffer.js @@ -6,7 +6,8 @@ * @param width {number} the width for the newly created canvas * @param height {number} the height for the newly created canvas */ -function CanvasBuffer(width, height) { +function CanvasBuffer(width, height) +{ /** * The Canvas object that belongs to this CanvasBuffer. * @@ -36,10 +37,12 @@ * @memberof CanvasBuffer# */ width: { - get: function () { + get: function () + { return this.canvas.width; }, - set: function (val) { + set: function (val) + { this.canvas.width = val; } }, @@ -50,10 +53,12 @@ * @memberof CanvasBuffer# */ height: { - get: function () { + get: function () + { return this.canvas.height; }, - set: function (val) { + set: function (val) + { this.canvas.height = val; } } @@ -64,7 +69,8 @@ * * @private */ -CanvasBuffer.prototype.clear = function () { +CanvasBuffer.prototype.clear = function () +{ this.context.setTransform(1, 0, 0, 1, 0, 0); this.context.clearRect(0,0, this.canvas.width, this.canvas.height); }; @@ -75,7 +81,8 @@ * @param width {number} the new width of the canvas * @param height {number} the new height of the canvas */ -CanvasBuffer.prototype.resize = function (width, height) { +CanvasBuffer.prototype.resize = function (width, height) +{ this.canvas.width = width; this.canvas.height = height; }; diff --git a/src/core/renderers/canvas/utils/CanvasGraphics.js b/src/core/renderers/canvas/utils/CanvasGraphics.js index c7eaa2a..3f2a91f 100644 --- a/src/core/renderers/canvas/utils/CanvasGraphics.js +++ b/src/core/renderers/canvas/utils/CanvasGraphics.js @@ -13,15 +13,18 @@ * @param graphics {Graphics} the actual graphics object to render * @param context {CanvasRenderingContext2D} the 2d drawing method of the canvas */ -CanvasGraphics.renderGraphics = function (graphics, context) { +CanvasGraphics.renderGraphics = function (graphics, context) +{ var worldAlpha = graphics.worldAlpha; - if (graphics.dirty) { + if (graphics.dirty) + { this.updateGraphicsTint(graphics); graphics.dirty = false; } - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; @@ -30,69 +33,82 @@ context.lineWidth = data.lineWidth; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { context.beginPath(); var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } - if (shape.closed) { + if (shape.closed) + { context.lineTo(points[0], points[1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fillRect(shape.x, shape.y, shape.width, shape.height); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.strokeRect(shape.x, shape.y, shape.width, shape.height); } } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.beginPath(); context.arc(shape.x, shape.y, shape.radius,0,2*Math.PI); context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas var w = shape.width * 2; @@ -119,18 +135,21 @@ context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; var width = shape.width; @@ -152,13 +171,15 @@ context.quadraticCurveTo(rx, ry, rx, ry + radius); context.closePath(); - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); @@ -174,45 +195,54 @@ * @param graphics {Graphics} the graphics which will be used as a mask * @param context {CanvasRenderingContext2D} the context 2d method of the canvas */ -CanvasGraphics.renderGraphicsMask = function (graphics, context) { +CanvasGraphics.renderGraphicsMask = function (graphics, context) +{ var len = graphics.graphicsData.length; - if (len === 0) { + if (len === 0) + { return; } context.beginPath(); - for (var i = 0; i < len; i++) { + for (var i = 0; i < len; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { context.rect(shape.x, shape.y, shape.width, shape.height); context.closePath(); } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.arc(shape.x, shape.y, shape.radius, 0, 2 * Math.PI); context.closePath(); } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas @@ -237,7 +267,8 @@ context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); context.closePath(); } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; @@ -262,8 +293,10 @@ } }; -CanvasGraphics.updateGraphicsTint = function (graphics) { - if (graphics.tint === 0xFFFFFF) { +CanvasGraphics.updateGraphicsTint = function (graphics) +{ + if (graphics.tint === 0xFFFFFF) + { return; } @@ -271,7 +304,8 @@ var tintG = (graphics.tint >> 8 & 0xFF) / 255; var tintB = (graphics.tint & 0xFF)/ 255; - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var fillColor = data.fillColor | 0; diff --git a/src/core/renderers/canvas/utils/CanvasMaskManager.js b/src/core/renderers/canvas/utils/CanvasMaskManager.js index e04a733..9827d36 100644 --- a/src/core/renderers/canvas/utils/CanvasMaskManager.js +++ b/src/core/renderers/canvas/utils/CanvasMaskManager.js @@ -6,7 +6,8 @@ * @class * @namespace PIXI */ -function CanvasMaskManager() {} +function CanvasMaskManager() +{} CanvasMaskManager.prototype.constructor = CanvasMaskManager; module.exports = CanvasMaskManager; @@ -17,7 +18,8 @@ * @param maskData {object} the maskData that will be pushed * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.pushMask = function (maskData, renderer) { +CanvasMaskManager.prototype.pushMask = function (maskData, renderer) +{ renderer.context.save(); var cacheAlpha = maskData.alpha; @@ -45,6 +47,7 @@ * * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.popMask = function (renderer) { +CanvasMaskManager.prototype.popMask = function (renderer) +{ renderer.context.restore(); }; diff --git a/src/core/renderers/canvas/utils/CanvasTinter.js b/src/core/renderers/canvas/utils/CanvasTinter.js index 17e0529..d2fb1bc 100644 --- a/src/core/renderers/canvas/utils/CanvasTinter.js +++ b/src/core/renderers/canvas/utils/CanvasTinter.js @@ -14,7 +14,8 @@ * @param color {number} the color to use to tint the sprite with * @return {HTMLCanvasElement} The tinted canvas */ -CanvasTinter.getTintedTexture = function (sprite, color) { +CanvasTinter.getTintedTexture = function (sprite, color) +{ var texture = sprite.texture; color = CanvasTinter.roundColor(color); @@ -23,7 +24,8 @@ texture.tintCache = texture.tintCache || {}; - if (texture.tintCache[stringColor]) { + if (texture.tintCache[stringColor]) + { return texture.tintCache[stringColor]; } @@ -33,14 +35,16 @@ //CanvasTinter.tintWithPerPixel(texture, stringColor, canvas); CanvasTinter.tintMethod(texture, color, canvas); - if (CanvasTinter.convertTintToImage) { + if (CanvasTinter.convertTintToImage) + { // is this better? var tintImage = new Image(); tintImage.src = canvas.toDataURL(); texture.tintCache[stringColor] = tintImage; } - else { + else + { texture.tintCache[stringColor] = canvas; // if we are not converting the texture to an image then we need to lose the reference to the canvas CanvasTinter.canvas = null; @@ -56,7 +60,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithMultiply = function (texture, color, canvas) { +CanvasTinter.tintWithMultiply = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -104,7 +109,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithOverlay = function (texture, color, canvas) { +CanvasTinter.tintWithOverlay = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -139,7 +145,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithPerPixel = function (texture, color, canvas) { +CanvasTinter.tintWithPerPixel = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -167,7 +174,8 @@ var pixels = pixelData.data; - for (var i = 0; i < pixels.length; i += 4) { + for (var i = 0; i < pixels.length; i += 4) + { pixels[i+0] *= r; pixels[i+1] *= g; pixels[i+2] *= b; @@ -181,7 +189,8 @@ * * @param color {number} the color to round, should be a hex color */ -CanvasTinter.roundColor = function (color) { +CanvasTinter.roundColor = function (color) +{ var step = CanvasTinter.cacheStepsPerColorChannel; var rgbValues = utils.hex2rgb(color); diff --git a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js index 9f2f89a..35edbaf 100644 --- a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js +++ b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLBlendModeManager(renderer) { +function WebGLBlendModeManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -23,8 +24,10 @@ * * @param blendMode {number} the blendMode, should be a Pixi const, such as BlendModes.ADD */ -WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) { - if (this.currentBlendMode === blendMode) { +WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) +{ + if (this.currentBlendMode === blendMode) + { return false; } diff --git a/src/core/renderers/webgl/managers/WebGLFilterManager.js b/src/core/renderers/webgl/managers/WebGLFilterManager.js index 1179258..2dac048 100644 --- a/src/core/renderers/webgl/managers/WebGLFilterManager.js +++ b/src/core/renderers/webgl/managers/WebGLFilterManager.js @@ -7,7 +7,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLFilterManager(renderer) { +function WebGLFilterManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -32,7 +33,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.texturePool.length = 0; self.initShaderBuffers(); }); @@ -46,7 +48,8 @@ * @param renderer {WebGLRenderer} * @param buffer {ArrayBuffer} */ -WebGLFilterManager.prototype.begin = function (buffer) { +WebGLFilterManager.prototype.begin = function (buffer) +{ this.defaultShader = this.renderer.shaderManager.defaultShader; this.width = this.renderer.projection.x * 2; @@ -60,7 +63,8 @@ * * @param filterBlock {object} the filter that will be pushed to the current filter stack */ -WebGLFilterManager.prototype.pushFilter = function (filterBlock) { +WebGLFilterManager.prototype.pushFilter = function (filterBlock) +{ var gl = this.renderer.gl; var projection = this.renderer.projection; @@ -78,10 +82,12 @@ this.offsetY += filterBlock._filterArea.y; var texture = this.texturePool.pop(); - if (!texture) { + if (!texture) + { texture = new FilterTexture(this.renderer.gl, this.width, this.height); } - else { + else + { texture.resize(this.width, this.height); } @@ -98,29 +104,35 @@ var localX = filterArea.x, localY = filterArea.y; - if (filterArea.x < 0) { + if (filterArea.x < 0) + { filterArea.width += filterArea.x; filterArea.x = 0; } - if (filterArea.y < 0) { + if (filterArea.y < 0) + { filterArea.height += filterArea.y; filterArea.y = 0; } - if (localX + filterArea.width > this.width) { + if (localX + filterArea.width > this.width) + { filterArea.width = this.width - localX; } - if (localY + filterArea.height > this.height) { + if (localY + filterArea.height > this.height) + { filterArea.height = this.height - localY; } - if (filterArea.width < 0) { + if (filterArea.width < 0) + { filterArea.width = 0; } - if (filterArea.height < 0) { + if (filterArea.height < 0) + { filterArea.height = 0; } @@ -154,7 +166,8 @@ * Removes the last filter from the filter stack and doesn't return it. * */ -WebGLFilterManager.prototype.popFilter = function () { +WebGLFilterManager.prototype.popFilter = function () +{ var gl = this.renderer.gl; var filterBlock = this.filterStack.pop(); @@ -163,7 +176,8 @@ var projection = this.renderer.projection; var offset = this.renderer.offset; - if (filterBlock.filterPasses.length > 1) { + if (filterBlock.filterPasses.length > 1) + { gl.viewport(0, 0, filterArea.width, filterArea.height); gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); @@ -193,7 +207,8 @@ var inputTexture = texture; var outputTexture = this.texturePool.pop(); - if (!outputTexture) { + if (!outputTexture) + { outputTexture = new FilterTexture(this.renderer.gl, this.width, this.height); } outputTexture.resize(this.width, this.height); @@ -204,7 +219,8 @@ gl.disable(gl.BLEND); - for (var i = 0; i < filterBlock.filterPasses.length-1; i++) { + for (var i = 0; i < filterBlock.filterPasses.length-1; i++) + { var filterPass = filterBlock.filterPasses[i]; gl.bindFramebuffer(gl.FRAMEBUFFER, outputTexture.frameBuffer ); @@ -243,10 +259,12 @@ var buffer = this.buffer; // time to render the filters texture to the previous scene - if (this.filterStack.length === 0) { + if (this.filterStack.length === 0) + { gl.colorMask(true, true, true, true);//this.transparent); } - else { + else + { var currentFilter = this.filterStack[this.filterStack.length-1]; filterArea = currentFilter._filterArea; @@ -332,13 +350,15 @@ * @param width {number} the horizontal range of the filter * @param height {number} the vertical range of the filter */ -WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) { +WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) +{ // use program var gl = this.renderer.gl; var shader = filter.shaders[gl.id]; - if (!shader) { + if (!shader) + { shader = new Shader(gl); shader.fragmentSrc = filter.fragmentSrc; @@ -356,7 +376,8 @@ gl.uniform2f(shader.projectionVector, width/2, -height/2); gl.uniform2f(shader.offsetVector, 0,0); - if (filter.uniforms.dimensions) { + 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]; @@ -386,7 +407,8 @@ * Initialises the shader buffers. * */ -WebGLFilterManager.prototype.initShaderBuffers = function () { +WebGLFilterManager.prototype.initShaderBuffers = function () +{ var gl = this.renderer.gl; // create some buffers @@ -432,7 +454,8 @@ * Destroys the filter and removes it from the filter stack. * */ -WebGLFilterManager.prototype.destroy = function () { +WebGLFilterManager.prototype.destroy = function () +{ var gl = this.renderer.gl; this.filterStack = null; @@ -441,7 +464,8 @@ this.offsetY = 0; // destroy textures - for (var i = 0; i < this.texturePool.length; i++) { + for (var i = 0; i < this.texturePool.length; i++) + { this.texturePool[i].destroy(); } diff --git a/src/core/renderers/webgl/managers/WebGLManager.js b/src/core/renderers/webgl/managers/WebGLManager.js index 9d47b5c..c30cd51 100644 --- a/src/core/renderers/webgl/managers/WebGLManager.js +++ b/src/core/renderers/webgl/managers/WebGLManager.js @@ -3,7 +3,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLManager(renderer) { +function WebGLManager(renderer) +{ /** * The renderer this manager works for. * @@ -15,6 +16,7 @@ WebGLManager.prototype.constructor = WebGLManager; module.exports = WebGLManager; -WebGLManager.prototype.destroy = function () { +WebGLManager.prototype.destroy = function () +{ this.renderer = null; }; diff --git a/src/core/renderers/webgl/managers/WebGLMaskManager.js b/src/core/renderers/webgl/managers/WebGLMaskManager.js index 2f90b64..e568812 100644 --- a/src/core/renderers/webgl/managers/WebGLMaskManager.js +++ b/src/core/renderers/webgl/managers/WebGLMaskManager.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLMaskManager(renderer) { +function WebGLMaskManager(renderer) +{ WebGLManager.call(this, renderer); } @@ -19,12 +20,15 @@ * * @param maskData {any[]} */ -WebGLMaskManager.prototype.pushMask = function (maskData) { - if (maskData.dirty) { +WebGLMaskManager.prototype.pushMask = function (maskData) +{ + if (maskData.dirty) + { WebGLGraphics.updateGraphics(maskData, this.renderer.gl); } - if (!maskData._webGL[this.renderer.gl.id].data.length) { + if (!maskData._webGL[this.renderer.gl.id].data.length) + { return; } @@ -36,6 +40,7 @@ * * @param maskData {any[]} */ -WebGLMaskManager.prototype.popMask = function (maskData) { +WebGLMaskManager.prototype.popMask = function (maskData) +{ this.renderer.stencilManager.popStencil(maskData, maskData._webGL[this.renderer.gl.id].data[0], this.renderer); }; diff --git a/src/core/renderers/webgl/managers/WebGLShaderManager.js b/src/core/renderers/webgl/managers/WebGLShaderManager.js index fef071c..90c6477 100644 --- a/src/core/renderers/webgl/managers/WebGLShaderManager.js +++ b/src/core/renderers/webgl/managers/WebGLShaderManager.js @@ -10,7 +10,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLShaderManager(renderer) { +function WebGLShaderManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -28,7 +29,8 @@ */ this.tempAttribState = []; - for (var i = 0; i < this.maxAttibs; i++) { + for (var i = 0; i < this.maxAttibs; i++) + { this.attribState[i] = false; } @@ -66,7 +68,8 @@ // listen for context and update necessary shaders var self = this; - this.renderer.on('context', function (event) { + this.renderer.on('context', function (event) + { var gl = event.data; // this shader is used for rendering primitives @@ -97,29 +100,36 @@ * * @param attribs {Array} attribs */ -WebGLShaderManager.prototype.setAttribs = function (attribs) { +WebGLShaderManager.prototype.setAttribs = function (attribs) +{ // reset temp state var i; - for (i = 0; i < this.tempAttribState.length; i++) { + for (i = 0; i < this.tempAttribState.length; i++) + { this.tempAttribState[i] = false; } // set the new attribs - for (var a in attribs) { + for (var a in attribs) + { this.tempAttribState[attribs[a]] = true; } var gl = this.renderer.gl; - for (i = 0; i < this.attribState.length; i++) { - if (this.attribState[i] !== this.tempAttribState[i]) { + for (i = 0; i < this.attribState.length; i++) + { + if (this.attribState[i] !== this.tempAttribState[i]) + { this.attribState[i] = this.tempAttribState[i]; - if (this.attribState[i]) { + if (this.attribState[i]) + { gl.enableVertexAttribArray(i); } - else { + else + { gl.disableVertexAttribArray(i); } } @@ -131,8 +141,10 @@ * * @param shader {Any} */ -WebGLShaderManager.prototype.setShader = function (shader) { - if (this._currentId === shader.uuid) { +WebGLShaderManager.prototype.setShader = function (shader) +{ + if (this._currentId === shader.uuid) + { return false; } @@ -150,7 +162,8 @@ * Destroys this object. * */ -WebGLShaderManager.prototype.destroy = function () { +WebGLShaderManager.prototype.destroy = function () +{ this.attribState = null; this.tempAttribState = null; diff --git a/src/core/renderers/webgl/managers/WebGLStencilManager.js b/src/core/renderers/webgl/managers/WebGLStencilManager.js index 9ec6398..4cb0134 100644 --- a/src/core/renderers/webgl/managers/WebGLStencilManager.js +++ b/src/core/renderers/webgl/managers/WebGLStencilManager.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLStencilManager(renderer) { +function WebGLStencilManager(renderer) +{ WebGLManager.call(this, renderer); this.stencilStack = []; @@ -24,12 +25,14 @@ * @param graphics {Graphics} * @param webGLData {any[]} */ -WebGLStencilManager.prototype.pushStencil = function (graphics, webGLData) { +WebGLStencilManager.prototype.pushStencil = function (graphics, webGLData) +{ var gl = this.renderer.gl; this.bindGraphics(graphics, webGLData, this.renderer); - if (this.stencilStack.length === 0) { + if (this.stencilStack.length === 0) + { gl.enable(gl.STENCIL_TEST); gl.clear(gl.STENCIL_BUFFER_BIT); this.reverse = true; @@ -47,14 +50,17 @@ // draw the triangle strip! - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } @@ -62,31 +68,38 @@ // draw a quad to increment.. gl.drawElements(gl.TRIANGLE_FAN, 4, gl.UNSIGNED_SHORT, ( webGLData.indices.length - 4 ) * 2 ); - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); } this.reverse = !this.reverse; } - else { - if (!this.reverse) { + else + { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } - else { + 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) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); } } @@ -103,7 +116,8 @@ * @param graphics {Graphics} * @param webGLData {Array} */ -WebGLStencilManager.prototype.bindGraphics = function (graphics, webGLData) { +WebGLStencilManager.prototype.bindGraphics = function (graphics, webGLData) +{ //if (this._currentGraphics === graphics)return; this._currentGraphics = graphics; @@ -114,7 +128,8 @@ offset = this.renderer.offset, shader;// = this.renderer.shaderManager.primitiveShader; - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { shader = this.renderer.shaderManager.complexPrimitiveShader; this.renderer.shaderManager.setShader(shader); @@ -141,7 +156,8 @@ // set the index buffer! gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, webGLData.indexBuffer); } - else { + else + { //this.renderer.shaderManager.activatePrimitiveShader(); shader = this.renderer.shaderManager.primitiveShader; this.renderer.shaderManager.setShader( shader ); @@ -154,7 +170,7 @@ gl.uniform2f(shader.uniforms.offsetVector._location, -offset.x, -offset.y); gl.uniform3fv(shader.uniforms.tint._location, utils.hex2rgb(graphics.tint)); - + gl.uniform1f(shader.uniforms.alpha._location, graphics.worldAlpha); @@ -172,19 +188,22 @@ * @param graphics {Graphics} * @param webGLData {Array} */ -WebGLStencilManager.prototype.popStencil = function (graphics, webGLData) { +WebGLStencilManager.prototype.popStencil = function (graphics, webGLData) +{ var gl = this.renderer.gl; this.stencilStack.pop(); this.count--; - if (this.stencilStack.length === 0) { + if (this.stencilStack.length === 0) + { // the stack is empty! gl.disable(gl.STENCIL_TEST); } - else { + else + { var level = this.count; @@ -192,14 +211,17 @@ gl.colorMask(false, false, false, false); - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { this.reverse = !this.reverse; - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } @@ -213,31 +235,38 @@ // draw the triangle strip! gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); - if (!this.reverse) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); } } - else { + else + { // console.log("<<>>") - if (!this.reverse) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } - else { + 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) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); } } @@ -253,7 +282,8 @@ * Destroys the mask stack. * */ -WebGLStencilManager.prototype.destroy = function () { +WebGLStencilManager.prototype.destroy = function () +{ this.renderer = null; this.stencilStack = null; }; diff --git a/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js b/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js index 913ba5e..1ea7d19 100644 --- a/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js +++ b/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function ComplexPrimitiveShader(gl) { +function ComplexPrimitiveShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -24,7 +25,8 @@ 'uniform float flipY;', 'varying vec4 vColor;', - 'void main(void) {', + '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);', @@ -37,7 +39,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = vColor;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/FastShader.js b/src/core/renderers/webgl/shaders/FastShader.js index bd2e29a..2e5e060 100644 --- a/src/core/renderers/webgl/shaders/FastShader.js +++ b/src/core/renderers/webgl/shaders/FastShader.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function FastShader(gl) { +function FastShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -28,7 +29,8 @@ 'const vec2 center = vec2(-1.0, 1.0);', - 'void main(void) {', + 'void main(void) + {', ' vec2 v;', ' vec2 sv = aVertexPosition * aScale;', ' v.x = (sv.x) * cos(aRotation) - (sv.y) * sin(aRotation);', @@ -49,7 +51,8 @@ 'uniform sampler2D uSampler;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/PrimitiveShader.js b/src/core/renderers/webgl/shaders/PrimitiveShader.js index 6f25409..a25f54f 100644 --- a/src/core/renderers/webgl/shaders/PrimitiveShader.js +++ b/src/core/renderers/webgl/shaders/PrimitiveShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function PrimitiveShader(gl) { +function PrimitiveShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -23,7 +24,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + '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);', @@ -36,7 +38,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = vColor;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/Shader.js b/src/core/renderers/webgl/shaders/Shader.js index f8964f5..fd75ef5 100644 --- a/src/core/renderers/webgl/shaders/Shader.js +++ b/src/core/renderers/webgl/shaders/Shader.js @@ -6,7 +6,8 @@ * @param [fragmentSrc] {string} The source of the fragment shader. * @param [vertexSrc] {string} The source of the vertex shader. */ -function Shader(gl, vertexSrc, fragmentSrc, customUniforms, customAttributes) { +function Shader(gl, vertexSrc, fragmentSrc, customUniforms, customAttributes) +{ /** * @member {number} * @readonly @@ -33,7 +34,8 @@ dimensions: { type: '4f', value: new Float32Array(4) } }; - for (var u in customUniforms) { + for (var u in customUniforms) + { this.uniforms[u] = customUniforms[u]; } @@ -43,7 +45,8 @@ aColor: 0 }; - for (var a in customAttributes) { + for (var a in customAttributes) + { this.attributes[a] = customAttributes[a]; } @@ -66,7 +69,8 @@ 'const vec2 center = vec2(-1.0, 1.0);', - 'void main(void) {', + 'void main(void) + {', ' gl_Position = vec4( ((aVertexPosition + offsetVector) / projectionVector) + center , 0.0, 1.0);', ' vTextureCoord = aTextureCoord;', ' vColor = vec4(aColor.rgb * aColor.a, aColor.a);', @@ -85,7 +89,8 @@ 'uniform sampler2D uSampler;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;', '}' ].join('\n'); @@ -96,7 +101,8 @@ Shader.prototype.constructor = Shader; module.exports = Shader; -Shader.prototype.init = function () { +Shader.prototype.init = function () +{ this.compile(); this.gl.useProgram(this.program); @@ -105,14 +111,18 @@ this.cacheAttributeLocations(Object.keys(this.attributes)); }; -Shader.prototype.cacheUniformLocations = function (keys) { - for (var i = 0; i < keys.length; ++i) { +Shader.prototype.cacheUniformLocations = function (keys) +{ + for (var i = 0; i < keys.length; ++i) + { this.uniforms[keys[i]]._location = this.gl.getUniformLocation(this.program, keys[i]); } }; -Shader.prototype.cacheAttributeLocations = function (keys) { - for (var i = 0; i < keys.length; ++i) { +Shader.prototype.cacheAttributeLocations = function (keys) +{ + for (var i = 0; i < keys.length; ++i) + { this.attributes[keys[i]] = this.gl.getAttribLocation(this.program, keys[i]); } @@ -124,14 +134,16 @@ // 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.attributes.aColor === -1) { + // if (this.attributes.aColor === -1) + { // this.attributes.aColor = 2; // } // End worst hack eva // }; -Shader.prototype.compile = function () { +Shader.prototype.compile = function () +{ var gl = this.gl; var glVertShader = this._glCompile(gl.VERTEX_SHADER, this.vertexSrc); @@ -144,13 +156,15 @@ gl.linkProgram(program); // if linking fails, then log and cleanup - if (!gl.getProgramParameter(program, gl.LINK_STATUS)) { + if (!gl.getProgramParameter(program, gl.LINK_STATUS)) + { window.console.error('Pixi.js Error: Could not initialize shader.'); window.console.error('gl.VALIDATE_STATUS', gl.getProgramParameter(program, gl.VALIDATE_STATUS)); window.console.error('gl.getError()', gl.getError()); // if there is a program info log, log it - if (gl.getProgramInfoLog(program) !== '') { + if (gl.getProgramInfoLog(program) !== '') + { window.console.warn('Pixi.js Warning: gl.getProgramInfoLog()', gl.getProgramInfoLog(program)); } @@ -165,18 +179,21 @@ return (this.program = program); }; -Shader.prototype.syncUniforms = function () { +Shader.prototype.syncUniforms = function () +{ var gl = this.gl; this.textureCount = 1; - for (var key in this.uniforms) { + for (var key in this.uniforms) + { var uniform = this.uniforms[key], location = uniform._location, value = uniform.value, i, il; - switch (uniform.type) { + switch (uniform.type) + { // single int value case 'i': case '1i': @@ -282,7 +299,8 @@ // a Color Value case 'c': - if (typeof value === 'number') { + if (typeof value === 'number') + { value = utils.hex2rgb(value); } @@ -311,11 +329,13 @@ // array of 2D Point objects case 'v2v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(2 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 2] = value[i].x; uniform._array[i * 2 + 1] = value[i].y; } @@ -325,11 +345,13 @@ // array of 3D Point objects case 'v3v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(3 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 3] = value[i].x; uniform._array[i * 3 + 1] = value[i].y; uniform._array[i * 3 + 2] = value[i].z; @@ -341,11 +363,13 @@ // array of 4D Point objects case 'v4v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(4 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 4] = value[i].x; uniform._array[i * 4 + 1] = value[i].y; uniform._array[i * 4 + 2] = value[i].z; @@ -359,7 +383,8 @@ // PIXI.Texture case 't': case 'sampler2D': - if (!uniform.value || !uniform.value.baseTexture || !uniform.value.baseTexture.hasLoaded) { + if (!uniform.value || !uniform.value.baseTexture || !uniform.value.baseTexture.hasLoaded) + { break; } @@ -376,7 +401,8 @@ this.textureCount++; // initialize the texture if we haven't yet - if (!uniform._init) { + if (!uniform._init) + { this.initSampler2D(uniform); uniform._init = true; @@ -394,11 +420,13 @@ * Initialises a Sampler2D uniform (which may only be available later on after initUniforms once the texture has loaded) * */ -Shader.prototype.initSampler2D = function (uniform) { +Shader.prototype.initSampler2D = function (uniform) +{ var gl = this.gl; // Extended texture data - if (uniform.textureData) { + if (uniform.textureData) + { var data = uniform.textureData; // GLTexture = mag linear, min linear_mipmap_linear, wrap repeat + gl.generateMipmap(gl.TEXTURE_2D); @@ -417,14 +445,16 @@ var wrapT = (data.wrapT) ? data.wrapT : gl.CLAMP_TO_EDGE; var format = (data.luminance) ? gl.LUMINANCE : gl.RGBA; - if (data.repeat) { + if (data.repeat) + { wrapS = gl.REPEAT; wrapT = gl.REPEAT; } gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, !!data.flipY); - if (data.width) { + if (data.width) + { var width = (data.width) ? data.width : 512; var height = (data.height) ? data.height : 2; var border = (data.border) ? data.border : 0; @@ -432,7 +462,8 @@ // 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 { + 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); } @@ -448,7 +479,8 @@ * Destroys the shader. * */ -Shader.prototype.destroy = function () { +Shader.prototype.destroy = function () +{ this.gl.deleteProgram(this.program); this.gl = null; @@ -459,13 +491,15 @@ this.fragmentSrc = null; }; -Shader.prototype._glCompile = function (type, src) { +Shader.prototype._glCompile = function (type, src) +{ var shader = this.gl.createShader(type); this.gl.shaderSource(shader, src); this.gl.compileShader(shader); - if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) { + if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) + { window.console.log(this.gl.getShaderInfoLog(shader)); return null; } diff --git a/src/core/renderers/webgl/shaders/StripShader.js b/src/core/renderers/webgl/shaders/StripShader.js index 193f6e1..a7abcc6 100644 --- a/src/core/renderers/webgl/shaders/StripShader.js +++ b/src/core/renderers/webgl/shaders/StripShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function StripShader(gl) { +function StripShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -20,7 +21,8 @@ 'varying vec2 vTextureCoord;', - 'void main(void) {', + '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);', @@ -36,7 +38,8 @@ 'varying vec2 vTextureCoord;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vec2(vTextureCoord.x, vTextureCoord.y)) * alpha;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/utils/FilterTexture.js b/src/core/renderers/webgl/utils/FilterTexture.js index d2c8423..4433d44 100644 --- a/src/core/renderers/webgl/utils/FilterTexture.js +++ b/src/core/renderers/webgl/utils/FilterTexture.js @@ -8,7 +8,8 @@ * @param height {number} the vertical range of the filter * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values */ -function FilterTexture(gl, width, height, scaleMode) { +function FilterTexture(gl, width, height, scaleMode) +{ /** * @member {WebGLContext} */ @@ -59,7 +60,8 @@ * Clears the filter texture. * */ -FilterTexture.prototype.clear = function () { +FilterTexture.prototype.clear = function () +{ var gl = this.gl; gl.clearColor(0,0,0, 0); @@ -72,8 +74,10 @@ * @param width {number} the new width of the texture * @param height {number} the new height of the texture */ -FilterTexture.prototype.resize = function (width, height) { - if (this.width === width && this.height === height) { +FilterTexture.prototype.resize = function (width, height) +{ + if (this.width === width && this.height === height) + { return; } @@ -96,7 +100,8 @@ * Destroys the filter texture. * */ -FilterTexture.prototype.destroy = function () { +FilterTexture.prototype.destroy = function () +{ var gl = this.gl; gl.deleteFramebuffer( this.frameBuffer ); gl.deleteTexture( this.texture ); diff --git a/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js b/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js index c4721e9..a63f4d7 100644 --- a/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js +++ b/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js @@ -14,7 +14,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this sprite batch works for. */ -function WebGLFastSpriteBatch(renderer) { +function WebGLFastSpriteBatch(renderer) +{ /** * The renderer instance this sprite batch operates on. * @@ -91,7 +92,8 @@ */ this.lastIndexCount = 0; - for (var i=0, j=0; i < numIndices; i += 6, j += 4) { + 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; @@ -144,7 +146,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.setupContext(); }); } @@ -157,7 +160,8 @@ * * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLFastSpriteBatch.prototype.setupContext = function () { +WebGLFastSpriteBatch.prototype.setupContext = function () +{ var gl = this.renderer.gl; // create a couple of buffers @@ -177,7 +181,8 @@ /** * @param spriteBatch {SpriteBatch} The SpriteBatch container to prepare for. */ -WebGLFastSpriteBatch.prototype.begin = function (spriteBatch) { +WebGLFastSpriteBatch.prototype.begin = function (spriteBatch) +{ this.shader = this.renderer.shaderManager.fastShader; this.matrix = spriteBatch.worldTransform.toArray(true); @@ -187,33 +192,38 @@ /** */ -WebGLFastSpriteBatch.prototype.end = function () { +WebGLFastSpriteBatch.prototype.end = function () +{ this.flush(); }; /** * @param spriteBatch {SpriteBatch} The SpriteBatch container to render. */ -WebGLFastSpriteBatch.prototype.render = function (spriteBatch) { +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) { + if (!sprite.texture._uvs) + { return; } this.currentBaseTexture = sprite.texture.baseTexture; // check blend mode - if (sprite.blendMode !== this.renderer.blendModeManager.currentBlendMode) { + if (sprite.blendMode !== this.renderer.blendModeManager.currentBlendMode) + { this.flush(); this.renderer.blendModeManager.setBlendMode(sprite.blendMode); } - for (var i=0,j= children.length; i= this.size) { + if (this.currentBatchSize >= this.size) + { this.flush(); } }; @@ -362,29 +379,35 @@ /** * */ -WebGLFastSpriteBatch.prototype.flush = function () { +WebGLFastSpriteBatch.prototype.flush = function () +{ // If the batch is length 0 then return as there is nothing to draw - if (this.currentBatchSize === 0) { + if (this.currentBatchSize === 0) + { return; } var gl = this.renderer.gl; // bind the current texture - if (!this.currentBaseTexture._glTextures[gl.id]) { + if (!this.currentBaseTexture._glTextures[gl.id]) + { this.renderer.updateTexture(this.currentBaseTexture, gl); } //TODO-SHOUD THIS BE ELSE??!?!?! - else { + else + { gl.bindTexture(gl.TEXTURE_2D, this.currentBaseTexture._glTextures[gl.id]); } // upload the verts to the buffer - if (this.currentBatchSize > ( this.size * 0.5 ) ) { + if (this.currentBatchSize > ( this.size * 0.5 ) ) + { gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); } - else { + else + { var view = this.vertices.subarray(0, this.currentBatchSize * this.vertByteSize); gl.bufferSubData(gl.ARRAY_BUFFER, 0, view); @@ -405,14 +428,16 @@ * Ends the batch and flushes * */ -WebGLFastSpriteBatch.prototype.stop = function () { +WebGLFastSpriteBatch.prototype.stop = function () +{ this.flush(); }; /** * */ -WebGLFastSpriteBatch.prototype.start = function () { +WebGLFastSpriteBatch.prototype.start = function () +{ var gl = this.renderer.gl; // bind the main texture diff --git a/src/core/renderers/webgl/utils/WebGLGraphics.js b/src/core/renderers/webgl/utils/WebGLGraphics.js index 55f4911..ab8f46e 100644 --- a/src/core/renderers/webgl/utils/WebGLGraphics.js +++ b/src/core/renderers/webgl/utils/WebGLGraphics.js @@ -19,7 +19,8 @@ * @param graphics {Graphics} * @param renderer {WebGLRenderer} */ -WebGLGraphics.renderGraphics = function (graphics, renderer) {//projection, offset) { +WebGLGraphics.renderGraphics = function (graphics, renderer) {//projection, offset) +{ var gl = renderer.gl; var projection = renderer.projection, @@ -27,7 +28,8 @@ shader = renderer.shaderManager.primitiveShader, webGLData; - if (graphics.dirty) { + if (graphics.dirty) + { WebGLGraphics.updateGraphics(graphics, gl); } @@ -35,8 +37,10 @@ // This could be speeded up for sure! - for (var i = 0; i < webGL.data.length; i++) { - if (webGL.data[i].mode === 1) { + for (var i = 0; i < webGL.data.length; i++) + { + if (webGL.data[i].mode === 1) + { webGLData = webGL.data[i]; renderer.stencilManager.pushStencil(graphics, webGLData, renderer); @@ -46,7 +50,8 @@ renderer.stencilManager.popStencil(graphics, webGLData, renderer); } - else { + else + { webGLData = webGL.data[i]; @@ -84,12 +89,14 @@ * @param graphicsData {Graphics} The graphics object to update * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLGraphics.updateGraphics = function (graphics, gl) { +WebGLGraphics.updateGraphics = function (graphics, gl) +{ // get the contexts graphics object var webGL = graphics._webGL[gl.id]; // if the graphics object does not exist in the webGL context time to create it! - if (!webGL) { + if (!webGL) + { webGL = graphics._webGL[gl.id] = {lastIndex:0, data:[], gl:gl}; } @@ -99,11 +106,13 @@ var i; // if the user cleared the graphics object we will need to clear every object - if (graphics.clearDirty) { + if (graphics.clearDirty) + { graphics.clearDirty = false; // lop through and return all the webGLDatas to the object pool so than can be reused later on - for (i = 0; i < webGL.data.length; i++) { + for (i = 0; i < webGL.data.length; i++) + { var graphicsData = webGL.data[i]; graphicsData.reset(); WebGLGraphics.graphicsDataPool.push( graphicsData ); @@ -119,58 +128,72 @@ // loop through the graphics datas and construct each one.. // if the object is a complex fill then the new stencil buffer technique will be used // other wise graphics objects will be pushed into a batch.. - for (i = webGL.lastIndex; i < graphics.graphicsData.length; i++) { + for (i = webGL.lastIndex; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { // need to add the points the the graphics object.. data.points = data.shape.points.slice(); - if (data.shape.closed) { + if (data.shape.closed) + { // close the poly if the value is true! - if (data.points[0] !== data.points[data.points.length-2] || data.points[1] !== data.points[data.points.length-1]) { + if (data.points[0] !== data.points[data.points.length-2] || data.points[1] !== data.points[data.points.length-1]) + { data.points.push(data.points[0], data.points[1]); } } // MAKE SURE WE HAVE THE CORRECT TYPE.. - if (data.fill) { - if (data.points.length >= 6) { - if (data.points.length < 6 * 2) { + if (data.fill) + { + if (data.points.length >= 6) + { + if (data.points.length < 6 * 2) + { webGLData = WebGLGraphics.switchMode(webGL, 0); var canDrawUsingSimple = WebGLGraphics.buildPoly(data, webGLData); // console.log(canDrawUsingSimple); - if (!canDrawUsingSimple) { + if (!canDrawUsingSimple) + { // console.log("<>>>") webGLData = WebGLGraphics.switchMode(webGL, 1); WebGLGraphics.buildComplexPoly(data, webGLData); } } - else { + else + { webGLData = WebGLGraphics.switchMode(webGL, 1); WebGLGraphics.buildComplexPoly(data, webGLData); } } } - if (data.lineWidth > 0) { + if (data.lineWidth > 0) + { webGLData = WebGLGraphics.switchMode(webGL, 0); WebGLGraphics.buildLine(data, webGLData); } } - else { + else + { webGLData = WebGLGraphics.switchMode(webGL, 0); - if (data.type === CONST.SHAPES.RECT) { + if (data.type === CONST.SHAPES.RECT) + { WebGLGraphics.buildRectangle(data, webGLData); } - else if (data.type === CONST.SHAPES.CIRC || data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.CIRC || data.type === CONST.SHAPES.ELIP) + { WebGLGraphics.buildCircle(data, webGLData); } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { WebGLGraphics.buildRoundedRectangle(data, webGLData); } } @@ -179,10 +202,12 @@ } // upload all the dirty data... - for (i = 0; i < webGL.data.length; i++) { + for (i = 0; i < webGL.data.length; i++) + { webGLData = webGL.data[i]; - if (webGLData.dirty) { + if (webGLData.dirty) + { webGLData.upload(); } } @@ -194,18 +219,22 @@ * @param webGL {WebGLContext} * @param type {number} */ -WebGLGraphics.switchMode = function (webGL, type) { +WebGLGraphics.switchMode = function (webGL, type) +{ var webGLData; - if (!webGL.data.length) { + if (!webGL.data.length) + { webGLData = WebGLGraphics.graphicsDataPool.pop() || new WebGLGraphicsData(webGL.gl); webGLData.mode = type; webGL.data.push(webGLData); } - else { + else + { webGLData = webGL.data[webGL.data.length-1]; - if (webGLData.mode !== type || type === 1) { + if (webGLData.mode !== type || type === 1) + { webGLData = WebGLGraphics.graphicsDataPool.pop() || new WebGLGraphicsData(webGL.gl); webGLData.mode = type; webGL.data.push(webGLData); @@ -225,7 +254,8 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildRectangle = function (graphicsData, webGLData) { +WebGLGraphics.buildRectangle = function (graphicsData, webGLData) +{ // --- // // need to convert points to a nice regular data // @@ -235,7 +265,8 @@ var width = rectData.width; var height = rectData.height; - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -265,7 +296,8 @@ indices.push(vertPos, vertPos, vertPos+1, vertPos+2, vertPos+3, vertPos+3); } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = [x, y, @@ -289,7 +321,8 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildRoundedRectangle = function (graphicsData, webGLData) { +WebGLGraphics.buildRoundedRectangle = function (graphicsData, webGLData) +{ var rrectData = graphicsData.shape; var x = rrectData.x; var y = rrectData.y; @@ -305,7 +338,8 @@ recPoints = recPoints.concat(WebGLGraphics.quadraticBezierCurve(x + width, y + radius, x + width, y, x + width - radius, y)); recPoints = recPoints.concat(WebGLGraphics.quadraticBezierCurve(x + radius, y, x, y, x, y + radius)); - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -323,7 +357,8 @@ // var i = 0; - for (i = 0; i < triangles.length; i+=3) { + for (i = 0; i < triangles.length; i+=3) + { indices.push(triangles[i] + vecPos); indices.push(triangles[i] + vecPos); indices.push(triangles[i+1] + vecPos); @@ -332,12 +367,14 @@ } - for (i = 0; i < recPoints.length; i++) { + for (i = 0; i < recPoints.length; i++) + { verts.push(recPoints[i], recPoints[++i], r, g, b, alpha); } } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = recPoints; @@ -362,7 +399,8 @@ * @param toY {number} Destination point y * @return {number[]} */ -WebGLGraphics.quadraticBezierCurve = function (fromX, fromY, cpX, cpY, toX, toY) { +WebGLGraphics.quadraticBezierCurve = function (fromX, fromY, cpX, cpY, toX, toY) +{ var xa, ya, @@ -373,14 +411,16 @@ n = 20, points = []; - function getPt(n1 , n2, perc) { + function getPt(n1 , n2, perc) + { var diff = n2 - n1; return n1 + ( diff * perc ); } var j = 0; - for (var i = 0; i <= n; i++ ) { + for (var i = 0; i <= n; i++ ) + { j = i / n; // The Green Line @@ -406,7 +446,8 @@ * @param graphicsData {Graphics} The graphics object to draw * @param webGLData {object} */ -WebGLGraphics.buildCircle = function (graphicsData, webGLData) { +WebGLGraphics.buildCircle = function (graphicsData, webGLData) +{ // need to convert points to a nice regular data var circleData = graphicsData.shape; var x = circleData.x; @@ -415,11 +456,13 @@ var height; // TODO - bit hacky?? - if (graphicsData.type === CONST.SHAPES.CIRC) { + if (graphicsData.type === CONST.SHAPES.CIRC) + { width = circleData.radius; height = circleData.radius; } - else { + else + { width = circleData.width; height = circleData.height; } @@ -429,7 +472,8 @@ var i = 0; - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -444,7 +488,8 @@ indices.push(vecPos); - for (i = 0; i < totalSegs + 1 ; i++) { + for (i = 0; i < totalSegs + 1 ; i++) + { verts.push(x,y, r, g, b, alpha); verts.push(x + Math.sin(seg * i) * width, @@ -457,12 +502,14 @@ indices.push(vecPos-1); } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = []; - for (i = 0; i < totalSegs + 1; i++) { + for (i = 0; i < totalSegs + 1; i++) + { graphicsData.points.push(x + Math.sin(seg * i) * width, y + Math.cos(seg * i) * height); } @@ -481,18 +528,22 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildLine = function (graphicsData, webGLData) { +WebGLGraphics.buildLine = function (graphicsData, webGLData) +{ // TODO OPTIMISE! var i = 0; var points = graphicsData.points; - if (points.length === 0) { + if (points.length === 0) + { return; } // if the line width is an odd number add 0.5 to align to a whole pixel - if (graphicsData.lineWidth%2) { - for (i = 0; i < points.length; i++) { + if (graphicsData.lineWidth%2) + { + for (i = 0; i < points.length; i++) + { points[i] += 0.5; } } @@ -502,7 +553,8 @@ var lastPoint = new math.Point(points[points.length - 2], points[points.length - 1]); // if the first point is the last point - gonna have issues :) - if (firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) { + if (firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) + { // need to clone as we are going to slightly modify the shape.. points = points.slice(); @@ -562,7 +614,8 @@ verts.push(p1x + perpx , p1y + perpy, r, g, b, alpha); - for (i = 1; i < length-1; i++) { + for (i = 1; i < length-1; i++) + { p1x = points[(i-1)*2]; p1y = points[(i-1)*2 + 1]; @@ -599,7 +652,8 @@ denom = a1*b2 - a2*b1; - if (Math.abs(denom) < 0.1 ) { + if (Math.abs(denom) < 0.1 ) + { denom+=10.1; verts.push(p2x - perpx , p2y - perpy, @@ -618,7 +672,8 @@ pdist = (px -p2x) * (px -p2x) + (py -p2y) + (py -p2y); - if (pdist > 140 * 140) { + if (pdist > 140 * 140) + { perp3x = perpx - perp2x; perp3y = perpy - perp2y; @@ -639,7 +694,8 @@ indexCount++; } - else { + else + { verts.push(px , py); verts.push(r, g, b, alpha); @@ -672,7 +728,8 @@ indices.push(indexStart); - for (i = 0; i < indexCount; i++) { + for (i = 0; i < indexCount; i++) + { indices.push(indexStart++); } @@ -687,11 +744,13 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildComplexPoly = function (graphicsData, webGLData) { +WebGLGraphics.buildComplexPoly = function (graphicsData, webGLData) +{ //TODO - no need to copy this as it gets turned into a FLoat32Array anyways.. var points = graphicsData.points.slice(); - if (points.length < 6) { + if (points.length < 6) + { return; } @@ -711,7 +770,8 @@ var x,y; // get size.. - for (var i = 0; i < points.length; i+=2) { + for (var i = 0; i < points.length; i+=2) + { x = points[i]; y = points[i+1]; @@ -732,7 +792,8 @@ //TODO - this aint needed! var length = points.length / 2; - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { indices.push( i ); } @@ -746,10 +807,12 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildPoly = function (graphicsData, webGLData) { +WebGLGraphics.buildPoly = function (graphicsData, webGLData) +{ var points = graphicsData.points; - if (points.length < 6) { + if (points.length < 6) + { return; } // get first and last point.. figure out the middle! @@ -767,7 +830,8 @@ var triangles = utils.PolyK.Triangulate(points); - if (!triangles) { + if (!triangles) + { return false; } @@ -775,7 +839,8 @@ var i = 0; - for (i = 0; i < triangles.length; i+=3) { + for (i = 0; i < triangles.length; i+=3) + { indices.push(triangles[i] + vertPos); indices.push(triangles[i] + vertPos); indices.push(triangles[i+1] + vertPos); @@ -783,7 +848,8 @@ indices.push(triangles[i+2] + vertPos); } - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { verts.push(points[i * 2], points[i * 2 + 1], r, g, b, alpha); } diff --git a/src/core/renderers/webgl/utils/WebGLGraphicsData.js b/src/core/renderers/webgl/utils/WebGLGraphicsData.js index c56d05e..c739ba7 100644 --- a/src/core/renderers/webgl/utils/WebGLGraphicsData.js +++ b/src/core/renderers/webgl/utils/WebGLGraphicsData.js @@ -2,7 +2,8 @@ * @class * @private */ -function WebGLGraphicsData(gl) { +function WebGLGraphicsData(gl) +{ this.gl = gl; //TODO does this need to be split before uploding?? @@ -22,7 +23,8 @@ /** * */ -WebGLGraphicsData.prototype.reset = function () { +WebGLGraphicsData.prototype.reset = function () +{ this.points.length = 0; this.indices.length = 0; }; @@ -30,7 +32,8 @@ /** * */ -WebGLGraphicsData.prototype.upload = function () { +WebGLGraphicsData.prototype.upload = function () +{ var gl = this.gl; // this.lastIndex = graphics.graphicsData.length; diff --git a/src/core/renderers/webgl/utils/WebGLSpriteBatch.js b/src/core/renderers/webgl/utils/WebGLSpriteBatch.js index 96eaa52..55befbb 100644 --- a/src/core/renderers/webgl/utils/WebGLSpriteBatch.js +++ b/src/core/renderers/webgl/utils/WebGLSpriteBatch.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this sprite batch works for. */ -function WebGLSpriteBatch(renderer) { +function WebGLSpriteBatch(renderer) +{ /** * * @@ -88,7 +89,8 @@ */ this.lastIndexCount = 0; - for (var i=0, j=0; i < numIndices; i += 6, j += 4) { + 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; @@ -162,7 +164,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.setupContext(); }); } @@ -173,7 +176,8 @@ /** * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLSpriteBatch.prototype.setupContext = function () { +WebGLSpriteBatch.prototype.setupContext = function () +{ var gl = this.renderer.gl; // setup default shader @@ -198,7 +202,8 @@ /** * */ -WebGLSpriteBatch.prototype.begin = function () { +WebGLSpriteBatch.prototype.begin = function () +{ // this.shader = this.renderer.shaderManager.defaultShader; this.start(); @@ -206,19 +211,22 @@ /** */ -WebGLSpriteBatch.prototype.end = function () { +WebGLSpriteBatch.prototype.end = function () +{ this.flush(); }; /** * @param sprite {Sprite} the sprite to render when using this spritebatch */ -WebGLSpriteBatch.prototype.render = function (sprite) { +WebGLSpriteBatch.prototype.render = function (sprite) +{ var texture = sprite.texture; //TODO set blend modes.. // check texture.. - if (this.currentBatchSize >= this.size) { + if (this.currentBatchSize >= this.size) + { this.flush(); this.currentBaseTexture = texture.baseTexture; } @@ -227,7 +235,8 @@ var uvs = texture._uvs; // if the uvs have not updated then no point rendering just yet! - if (!uvs) { + if (!uvs) + { return; } @@ -237,7 +246,8 @@ var w0, w1, h0, h1; - if (texture.trim) { + 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; @@ -248,7 +258,8 @@ h0 = h1 + texture.crop.height; } - else { + else + { w0 = (texture.frame.width ) * (1-aX); w1 = (texture.frame.width ) * -aX; @@ -272,7 +283,8 @@ var colors = this.colors; var positions = this.positions; - if (this.renderer.roundPixels) { + if (this.renderer.roundPixels) + { // xy positions[index] = a * w1 + c * h1 + tx | 0; positions[index+1] = d * h1 + b * w1 + ty | 0; @@ -289,7 +301,8 @@ positions[index+15] = a * w1 + c * h0 + tx | 0; positions[index+16] = d * h0 + b * w1 + ty | 0; } - else { + else + { // xy positions[index] = a * w1 + c * h1 + tx; positions[index+1] = d * h1 + b * w1 + ty; @@ -338,11 +351,13 @@ * * @param sprite {TilingSprite} the tilingSprite to render */ -WebGLSpriteBatch.prototype.renderTilingSprite = function (tilingSprite) { +WebGLSpriteBatch.prototype.renderTilingSprite = function (tilingSprite) +{ var texture = tilingSprite.tilingTexture; // check texture.. - if (this.currentBatchSize >= this.size) { + if (this.currentBatchSize >= this.size) + { //return; this.flush(); this.currentBaseTexture = texture.baseTexture; @@ -351,7 +366,8 @@ // set the textures uvs temporarily // TODO create a separate texture so that we can tile part of a texture - if (!tilingSprite._uvs) { + if (!tilingSprite._uvs) + { tilingSprite._uvs = new TextureUvs(); } @@ -454,16 +470,19 @@ * Renders the content and empties the current batch. * */ -WebGLSpriteBatch.prototype.flush = function () { +WebGLSpriteBatch.prototype.flush = function () +{ // If the batch is length 0 then return as there is nothing to draw - if (this.currentBatchSize === 0) { + if (this.currentBatchSize === 0) + { return; } var gl = this.renderer.gl; var shader; - if (this.dirty) { + if (this.dirty) + { this.dirty = false; // bind the main texture gl.activeTexture(gl.TEXTURE0); @@ -482,10 +501,12 @@ } // upload the verts to the buffer - if (this.currentBatchSize > ( this.size * 0.5 ) ) { + if (this.currentBatchSize > ( this.size * 0.5 ) ) + { gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); } - else { + else + { var view = this.positions.subarray(0, this.currentBatchSize * this.vertByteSize); gl.bufferSubData(gl.ARRAY_BUFFER, 0, view); } @@ -502,7 +523,8 @@ var shaderSwap = false; var sprite; - for (var i = 0, j = this.currentBatchSize; i < j; i++) { + for (var i = 0, j = this.currentBatchSize; i < j; i++) + { sprite = this.sprites[i]; @@ -513,24 +535,28 @@ blendSwap = currentBlendMode !== nextBlendMode; shaderSwap = currentShader !== nextShader; // should I use uuidS??? - if (currentBaseTexture !== nextTexture || blendSwap || shaderSwap) { + if (currentBaseTexture !== nextTexture || blendSwap || shaderSwap) + { this.renderBatch(currentBaseTexture, batchSize, start); start = i; batchSize = 0; currentBaseTexture = nextTexture; - if (blendSwap) { + if (blendSwap) + { currentBlendMode = nextBlendMode; this.renderer.blendModeManager.setBlendMode( currentBlendMode ); } - if (shaderSwap) { + if (shaderSwap) + { currentShader = nextShader; shader = currentShader.shaders ? currentShader.shaders[gl.id] : currentShader; - if (!shader) { + if (!shader) + { shader = new Shader(gl, null, currentShader.fragmentSrc, currentShader.uniforms); currentShader.shaders[gl.id] = shader; } @@ -538,7 +564,8 @@ // set shader function??? this.renderer.shaderManager.setShader(shader); - if (shader.dirty) { + if (shader.dirty) + { shader.syncUniforms(); } @@ -569,17 +596,21 @@ * @param size {number} * @param startIndex {number} */ -WebGLSpriteBatch.prototype.renderBatch = function (texture, size, startIndex) { - if (size === 0) { +WebGLSpriteBatch.prototype.renderBatch = function (texture, size, startIndex) +{ + if (size === 0) + { return; } var gl = this.renderer.gl; - if (!texture._glTextures[gl.id]) { + if (!texture._glTextures[gl.id]) + { this.renderer.updateTexture(texture); } - else { + else + { // bind the current texture gl.bindTexture(gl.TEXTURE_2D, texture._glTextures[gl.id]); } @@ -594,7 +625,8 @@ /** * */ -WebGLSpriteBatch.prototype.stop = function () { +WebGLSpriteBatch.prototype.stop = function () +{ this.flush(); this.dirty = true; }; @@ -602,7 +634,8 @@ /** * */ -WebGLSpriteBatch.prototype.start = function () { +WebGLSpriteBatch.prototype.start = function () +{ this.dirty = true; }; @@ -610,7 +643,8 @@ * Destroys the SpriteBatch. * */ -WebGLSpriteBatch.prototype.destroy = function () { +WebGLSpriteBatch.prototype.destroy = function () +{ this.renderer.gl.deleteBuffer(this.vertexBuffer); this.renderer.gl.deleteBuffer(this.indexBuffer); diff --git a/src/core/textures/BaseTexture.js b/src/core/textures/BaseTexture.js index 2bf77d4..513d358 100644 --- a/src/core/textures/BaseTexture.js +++ b/src/core/textures/BaseTexture.js @@ -10,7 +10,8 @@ * @param source {Image|Canvas} the source object of the texture. * @param [scaleMode=scaleModes.DEFAULT] {number} See {@link scaleModes} for possible values */ -function BaseTexture(source, scaleMode) { +function BaseTexture(source, scaleMode) +{ this.uuid = utils.uuid(); /** @@ -123,7 +124,8 @@ this._needsUpdate = false; // if no source passed don't try to load - if (source) { + if (source) + { this.loadSource(source); } @@ -149,13 +151,16 @@ Object.defineProperties(BaseTexture.prototype, { needsUpdate: { - get: function () { + get: function () + { return this._needsUpdate; }, - set: function (val) { + set: function (val) + { this._needsUpdate = val; - if (val) { + if (val) + { this.emit('update', this); } } @@ -171,9 +176,11 @@ * * The logic state after calling `loadSource` directly or indirectly (eg. `fromImage`, `new BaseTexture`) is: * - * if (texture.hasLoaded) { + * if (texture.hasLoaded) + { * // texture ready for use - * } else if (texture.isLoading) { + * } else if (texture.isLoading) + { * // listen to 'loaded' and/or 'error' events on texture * } else { * // not loading, not going to load UNLESS the source is reloaded @@ -183,12 +190,14 @@ * @protected * @param source {Image|Canvas} the source object of the texture. */ -BaseTexture.prototype.loadSource = function (source) { +BaseTexture.prototype.loadSource = function (source) +{ var wasLoading = this.isLoading; this.hasLoaded = false; this.isLoading = false; - if (wasLoading && this.source) { + if (wasLoading && this.source) + { this.source.onload = null; this.source.onerror = null; } @@ -196,20 +205,24 @@ this.source = source; // Apply source if loaded. Otherwise setup appropriate loading monitors. - if ((this.source.complete || this.source.getContext) && this.source.width && this.source.height) { + if ((this.source.complete || this.source.getContext) && this.source.width && this.source.height) + { this._sourceLoaded(); } - else if(!source.getContext) { + else if(!source.getContext) + { // Image fail / not ready this.isLoading = true; var scope = this; - source.onload = function () { + source.onload = function () + { source.onload = null; source.onerror = null; - if(!scope.isLoading) { + if(!scope.isLoading) + { return; } @@ -219,11 +232,13 @@ scope.emit('loaded', scope); }; - source.onerror = function () { + source.onerror = function () + { source.onload = null; source.onerror = null; - if(!scope.isLoading) { + if(!scope.isLoading) + { return; } @@ -234,24 +249,29 @@ // Per http://www.w3.org/TR/html5/embedded-content-0.html#the-img-element // "The value of `complete` can thus change while a script is executing." // So complete needs to be re-checked after the callbacks have been added.. - if (source.complete) { + if (source.complete) + { this.isLoading = false; // ..and if we're complete now, no need for callbacks source.onload = null; source.onerror = null; - if (source.width && source.height) { + if (source.width && source.height) + { this._sourceLoaded(); // If any previous subscribers possible - if (wasLoading) { + if (wasLoading) + { this.emit('loaded', this); } } - else { + else + { // If any previous subscribers possible - if (wasLoading) { + if (wasLoading) + { this.emit('error', this); } } @@ -265,7 +285,8 @@ * * @private */ -BaseTexture.prototype._sourceLoaded = function () { +BaseTexture.prototype._sourceLoaded = function () +{ this.hasLoaded = true; this.width = this.source.naturalWidth || this.source.width; @@ -278,16 +299,20 @@ * Destroys this base texture * */ -BaseTexture.prototype.destroy = function () { - if (this.imageUrl) { +BaseTexture.prototype.destroy = function () +{ + if (this.imageUrl) + { delete utils.BaseTextureCache[this.imageUrl]; delete utils.TextureCache[this.imageUrl]; this.imageUrl = null; - if (!navigator.isCocoonJS) { + if (!navigator.isCocoonJS) + { this.source.src = ''; } } - else if (this.source && this.source._pixiId) { + else if (this.source && this.source._pixiId) + { delete utils.BaseTextureCache[this.source._pixiId]; } this.source = null; @@ -301,7 +326,8 @@ * memory again. * */ -BaseTexture.prototype.dispose = function () { +BaseTexture.prototype.dispose = function () +{ this.emit('dispose', this); }; @@ -311,7 +337,8 @@ * * @param newSrc {string} the path of the image */ -BaseTexture.prototype.updateSourceImage = function (newSrc) { +BaseTexture.prototype.updateSourceImage = function (newSrc) +{ this.source.src = newSrc; this.loadSource(this.source); }; @@ -326,18 +353,22 @@ * @param [scaleMode=scaleModes.DEFAULT] {number} See {@link scaleModes} for possible values * @return BaseTexture */ -BaseTexture.fromImage = function (imageUrl, crossorigin, scaleMode) { +BaseTexture.fromImage = function (imageUrl, crossorigin, scaleMode) +{ var baseTexture = utils.BaseTextureCache[imageUrl]; - if (crossorigin === undefined && imageUrl.indexOf('data:') !== 0) { + if (crossorigin === undefined && imageUrl.indexOf('data:') !== 0) + { crossorigin = true; } - if (!baseTexture) { + if (!baseTexture) + { // new Image() breaks tex loading in some versions of Chrome. // See https://code.google.com/p/chromium/issues/detail?id=238071 var image = new Image();//document.createElement('img'); - if (crossorigin) { + if (crossorigin) + { image.crossOrigin = ''; } @@ -347,7 +378,8 @@ utils.BaseTextureCache[imageUrl] = baseTexture; // if there is an @2x at the end of the url we are going to assume its a highres image - if ( imageUrl.indexOf(CONST.RETINA_PREFIX + '.') !== -1) { + if ( imageUrl.indexOf(CONST.RETINA_PREFIX + '.') !== -1) + { baseTexture.resolution = 2; } } @@ -363,14 +395,17 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return BaseTexture */ -BaseTexture.fromCanvas = function (canvas, scaleMode) { - if (!canvas._pixiId) { +BaseTexture.fromCanvas = function (canvas, scaleMode) +{ + if (!canvas._pixiId) + { canvas._pixiId = 'canvas_' + utils.uuid(); } var baseTexture = utils.BaseTextureCache[canvas._pixiId]; - if (!baseTexture) { + if (!baseTexture) + { baseTexture = new BaseTexture(canvas, scaleMode); utils.BaseTextureCache[canvas._pixiId] = baseTexture; } diff --git a/src/core/textures/RenderTexture.js b/src/core/textures/RenderTexture.js index 6dad20f..53ae796 100644 --- a/src/core/textures/RenderTexture.js +++ b/src/core/textures/RenderTexture.js @@ -46,8 +46,10 @@ * @param [scaleMode] {number} See {@link scaleModes} for possible values * @param [resolution=1] {number} The resolution of the texture being generated */ -function RenderTexture(renderer, width, height, scaleMode, resolution) { - if (!renderer) { +function RenderTexture(renderer, width, height, scaleMode, resolution) +{ + if (!renderer) + { throw new Error('Unable to create RenderTexture, you must pass a renderer into the constructor.'); } @@ -133,7 +135,8 @@ */ this.renderer = renderer; - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { var gl = this.renderer.gl; this.textureBuffer = new FilterTexture(gl, this.width * this.resolution, this.height * this.resolution, this.baseTexture.scaleMode); @@ -142,7 +145,8 @@ this.render = this.renderWebGL; this.projection = new math.Point(this.width*0.5, -this.height*0.5); } - else { + else + { this.render = this.renderCanvas; this.textureBuffer = new CanvasBuffer(this.width* this.resolution, this.height* this.resolution); this.baseTexture.source = this.textureBuffer.canvas; @@ -167,8 +171,10 @@ * @param height {number} The height to resize to. * @param updateBase {boolean} Should the baseTexture.width and height values be resized as well? */ -RenderTexture.prototype.resize = function (width, height, updateBase) { - if (width === this.width && height === this.height) { +RenderTexture.prototype.resize = function (width, height, updateBase) +{ + if (width === this.width && height === this.height) + { return; } @@ -177,17 +183,20 @@ this.width = this.frame.width = this.crop.width = width; this.height = this.frame.height = this.crop.height = height; - if (updateBase) { + if (updateBase) + { this.baseTexture.width = this.width; this.baseTexture.height = this.height; } - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { this.projection.x = this.width / 2; this.projection.y = -this.height / 2; } - if (!this.valid) { + if (!this.valid) + { return; } @@ -198,12 +207,15 @@ * Clears the RenderTexture. * */ -RenderTexture.prototype.clear = function () { - if (!this.valid) { +RenderTexture.prototype.clear = function () +{ + if (!this.valid) + { return; } - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { this.renderer.gl.bindFramebuffer(this.renderer.gl.FRAMEBUFFER, this.textureBuffer.frameBuffer); } @@ -220,19 +232,23 @@ * @param [restoreWorldTransform=true] {boolean} If true the displayObject's worldTransform/worldAlpha and all children * transformations will be restored. Not restoring this information will be a little faster. */ -RenderTexture.prototype.renderWebGL = function (displayObject, matrix, clear, restoreWorldTransform) { - if (!this.valid) { +RenderTexture.prototype.renderWebGL = function (displayObject, matrix, clear, restoreWorldTransform) +{ + if (!this.valid) + { return; } - if (typeof restoreWorldTransform === 'undefined') { + if (typeof restoreWorldTransform === 'undefined') + { restoreWorldTransform = true; } var tempAlpha, tempTransform; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { tempAlpha = displayObject.worldAlpha; tempTransform = displayObject.worldTransform.toArray(); } @@ -245,7 +261,8 @@ wt.identity(); wt.translate(0, this.projection.y * 2); - if (matrix) { + if (matrix) + { wt.append(matrix); } @@ -258,7 +275,8 @@ var children = displayObject.children; var i, j; - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } @@ -269,7 +287,8 @@ gl.bindFramebuffer(gl.FRAMEBUFFER, this.textureBuffer.frameBuffer ); - if (clear) { + if (clear) + { this.textureBuffer.clear(); } @@ -279,11 +298,13 @@ this.renderer.spriteBatch.dirty = true; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { displayObject.worldAlpha = tempAlpha; displayObject.worldTransform.fromArray(tempTransform); - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } } @@ -300,26 +321,31 @@ * @param [restoreWorldTransform=true] {boolean} If true the displayObject's worldTransform/worldAlpha and all children * transformations will be restored. Not restoring this information will be a little faster. */ -RenderTexture.prototype.renderCanvas = function (displayObject, matrix, clear, restoreWorldTransform) { - if (!this.valid) { +RenderTexture.prototype.renderCanvas = function (displayObject, matrix, clear, restoreWorldTransform) +{ + if (!this.valid) + { return; } - if (typeof restoreWorldTransform === 'undefined') { + if (typeof restoreWorldTransform === 'undefined') + { restoreWorldTransform = true; } var tempAlpha, tempTransform; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { tempAlpha = displayObject.worldAlpha; tempTransform = displayObject.worldTransform.toArray(); } var wt = displayObject.worldTransform; wt.identity(); - if (matrix) { + if (matrix) + { wt.append(matrix); } @@ -330,11 +356,13 @@ var children = displayObject.children; var i, j; - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } - if (clear) { + if (clear) + { this.textureBuffer.clear(); } @@ -348,11 +376,13 @@ this.renderer.resolution = realResolution; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { displayObject.worldAlpha = tempAlpha; displayObject.worldTransform.fromArray(tempTransform); - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } } @@ -363,7 +393,8 @@ * * @return {Image} */ -RenderTexture.prototype.getImage = function () { +RenderTexture.prototype.getImage = function () +{ var image = new Image(); image.src = this.getBase64(); return image; @@ -374,7 +405,8 @@ * * @return {string} A base64 encoded string of the texture. */ -RenderTexture.prototype.getBase64 = function () { +RenderTexture.prototype.getBase64 = function () +{ return this.getCanvas().toDataURL(); }; @@ -383,8 +415,10 @@ * * @return {HTMLCanvasElement} A Canvas element with the texture rendered on. */ -RenderTexture.prototype.getCanvas = function () { - if (this.renderer.type === CONST.WEBGL_RENDERER) { +RenderTexture.prototype.getCanvas = function () +{ + if (this.renderer.type === CONST.WEBGL_RENDERER) + { var gl = this.renderer.gl; var width = this.textureBuffer.width; var height = this.textureBuffer.height; @@ -403,7 +437,8 @@ return tempCanvas.canvas; } - else { + else + { return this.textureBuffer.canvas; } }; diff --git a/src/core/textures/Texture.js b/src/core/textures/Texture.js index 3c65909..e97f0aa 100644 --- a/src/core/textures/Texture.js +++ b/src/core/textures/Texture.js @@ -17,7 +17,8 @@ * @param [crop] {Rectangle} The area of original texture * @param [trim] {Rectangle} Trimmed texture rectangle */ -function Texture(baseTexture, frame, crop, trim) { +function Texture(baseTexture, frame, crop, trim) +{ /** * Does this Texture have any frame data assigned to it? * @@ -25,12 +26,14 @@ */ this.noFrame = false; - if (!frame) { + if (!frame) + { this.noFrame = true; frame = new math.Rectangle(0, 0, 1, 1); } - if (baseTexture instanceof Texture) { + if (baseTexture instanceof Texture) + { baseTexture = baseTexture.baseTexture; } @@ -100,13 +103,16 @@ */ this.crop = crop || new math.Rectangle(0, 0, 1, 1); - if (baseTexture.hasLoaded) { - if (this.noFrame) { + if (baseTexture.hasLoaded) + { + if (this.noFrame) + { frame = new math.Rectangle(0, 0, baseTexture.width, baseTexture.height); } this.frame = frame; } - else { + else + { baseTexture.addEventListener('loaded', this.onBaseTextureLoaded.bind(this)); } } @@ -118,19 +124,23 @@ Object.defineProperties(Texture.prototype, { needsUpdate: { - get: function () { + get: function () + { return this.baseTexture.needsUpdate; }, - set: function (val) { + set: function (val) + { this.baseTexture.needsUpdate = val; } }, frame: { - get: function () { + get: function () + { return this._frame; }, - set: function (frame) { + set: function (frame) + { this._frame = frame; this.noFrame = false; @@ -143,20 +153,23 @@ 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 (!this.trim && (frame.x + frame.width > this.baseTexture.width || frame.y + frame.height > this.baseTexture.height)) + { throw new Error('Texture Error: frame does not fit inside the base Texture dimensions ' + this); } this.valid = frame && frame.width && frame.height && this.baseTexture.source && this.baseTexture.hasLoaded; - if (this.trim) { + 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) { + if (this.valid) + { this._updateUvs(); } } @@ -168,11 +181,13 @@ * * @private */ -Texture.prototype.onBaseTextureLoaded = function () { +Texture.prototype.onBaseTextureLoaded = function () +{ var baseTexture = this.baseTexture; baseTexture.removeEventListener('loaded', this.onLoaded); - if (this.noFrame) { + if (this.noFrame) + { this.frame = new math.Rectangle(0, 0, baseTexture.width, baseTexture.height); } @@ -184,8 +199,10 @@ * * @param destroyBase {boolean} Whether to destroy the base texture as well */ -Texture.prototype.destroy = function (destroyBase) { - if (destroyBase) { +Texture.prototype.destroy = function (destroyBase) +{ + if (destroyBase) + { this.baseTexture.destroy(); } @@ -197,8 +214,10 @@ * * @private */ -Texture.prototype._updateUvs = function () { - if (!this._uvs) { +Texture.prototype._updateUvs = function () +{ + if (!this._uvs) + { this._uvs = new TextureUvs(); } @@ -229,10 +248,12 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return Texture */ -Texture.fromImage = function (imageUrl, crossorigin, scaleMode) { +Texture.fromImage = function (imageUrl, crossorigin, scaleMode) +{ var texture = utils.TextureCache[imageUrl]; - if (!texture) { + if (!texture) + { texture = new Texture(BaseTexture.fromImage(imageUrl, crossorigin, scaleMode)); utils.TextureCache[imageUrl] = texture; } @@ -248,9 +269,11 @@ * @param frameId {string} The frame id of the texture * @return Texture */ -Texture.fromFrame = function (frameId) { +Texture.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache '); } return texture; @@ -264,7 +287,8 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return {Texture} */ -Texture.fromCanvas = function (canvas, scaleMode) { +Texture.fromCanvas = function (canvas, scaleMode) +{ return new Texture(BaseTexture.fromCanvas(canvas, scaleMode)); }; @@ -276,7 +300,8 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return {Texture} A Texture */ -Texture.fromVideo = function (video, scaleMode) { +Texture.fromVideo = function (video, scaleMode) +{ return new Texture(VideoBaseTexture.baseTextureFromVideo(video, scaleMode)); }; @@ -287,7 +312,8 @@ * @param texture {Texture} The Texture to add to the cache. * @param id {string} The id that the texture will be stored against. */ -Texture.addTextureToCache = function (texture, id) { +Texture.addTextureToCache = function (texture, id) +{ utils.TextureCache[id] = texture; }; @@ -298,7 +324,8 @@ * @param id {string} The id of the texture to be removed * @return {Texture} The texture that was removed */ -Texture.removeTextureFromCache = function (id) { +Texture.removeTextureFromCache = function (id) +{ var texture = utils.TextureCache[id]; delete utils.TextureCache[id]; diff --git a/src/core/textures/TextureUvs.js b/src/core/textures/TextureUvs.js index b9bbb58..5424d52 100644 --- a/src/core/textures/TextureUvs.js +++ b/src/core/textures/TextureUvs.js @@ -1,4 +1,5 @@ -function TextureUvs() { +function TextureUvs() +{ this.x0 = 0; this.y0 = 0; diff --git a/src/core/textures/VideoBaseTexture.js b/src/core/textures/VideoBaseTexture.js index e3e0c5a..1a826a9 100644 --- a/src/core/textures/VideoBaseTexture.js +++ b/src/core/textures/VideoBaseTexture.js @@ -12,15 +12,18 @@ * @param source {HTMLVideoElement} * @param [scaleMode] {number} See {@link scaleModes} for possible values */ -function VideoBaseTexture(source, scaleMode) { - if (!source){ +function VideoBaseTexture(source, scaleMode) +{ + if (!source) + { throw new Error('No video source element specified.'); } // hook in here to check if video is already available. // BaseTexture looks for a source.complete boolean, plus width & height. - if ((source.readyState === source.HAVE_ENOUGH_DATA || source.readyState === source.HAVE_FUTURE_DATA) && source.width && source.height) { + if ((source.readyState === source.HAVE_ENOUGH_DATA || source.readyState === source.HAVE_FUTURE_DATA) && source.width && source.height) + { source.complete = true; } @@ -31,7 +34,8 @@ this._boundOnUpdate = this._onUpdate.bind(this); this._boundOnCanPlay = this._onCanPlay.bind(this); - if (!source.complete) { + if (!source.complete) + { source.addEventListener('canplay', this._boundOnCanPlay); source.addEventListener('canplaythrough', this._boundOnCanPlay); @@ -47,28 +51,35 @@ VideoBaseTexture.prototype.constructor = VideoBaseTexture; module.exports = VideoBaseTexture; -VideoBaseTexture.prototype._onUpdate = function () { - if (this.autoUpdate) { +VideoBaseTexture.prototype._onUpdate = function () +{ + if (this.autoUpdate) + { window.requestAnimationFrame(this._boundOnUpdate); this.needsUpdate = true; } }; -VideoBaseTexture.prototype._onPlayStart = function () { - if (!this.autoUpdate) { +VideoBaseTexture.prototype._onPlayStart = function () +{ + if (!this.autoUpdate) + { window.requestAnimationFrame(this._boundOnUpdate); this.autoUpdate = true; } }; -VideoBaseTexture.prototype._onPlayStop = function () { +VideoBaseTexture.prototype._onPlayStop = function () +{ this.autoUpdate = false; }; -VideoBaseTexture.prototype._onCanPlay = function () { +VideoBaseTexture.prototype._onCanPlay = function () +{ this.hasLoaded = true; - if (this.source) { + if (this.source) + { this.source.removeEventListener('canplay', this._boundOnCanPlay); this.source.removeEventListener('canplaythrough', this._boundOnCanPlay); @@ -78,15 +89,18 @@ this.source.play(); // prevent multiple loaded dispatches.. - if(!this.__loaded){ + if(!this.__loaded) + { this.__loaded = true; this.emit('loaded', this); } } }; -VideoBaseTexture.prototype.destroy = function () { - if (this.source && this.source._pixiId) { +VideoBaseTexture.prototype.destroy = function () +{ + if (this.source && this.source._pixiId) + { utils.BaseTextureCache[ this.source._pixiId ] = null; delete utils.BaseTextureCache[ this.source._pixiId ]; @@ -105,14 +119,17 @@ * @param scaleMode {number} See {@link scaleModes} for possible values * @return {VideoBaseTexture} */ -VideoBaseTexture.fromVideo = function (video, scaleMode) { - if (!video._pixiId) { +VideoBaseTexture.fromVideo = function (video, scaleMode) +{ + if (!video._pixiId) + { video._pixiId = 'video_' + utils.uuid(); } var baseTexture = utils.BaseTextureCache[video._pixiId]; - if (!baseTexture) { + if (!baseTexture) + { baseTexture = new VideoBaseTexture(video, scaleMode); utils.BaseTextureCache[ video._pixiId ] = baseTexture; } @@ -147,17 +164,21 @@ * @param scaleMode {number} See {@link scaleModes} for possible values * @return {VideoBaseTexture} */ -VideoBaseTexture.fromUrl = function (videoSrc, scaleMode) { +VideoBaseTexture.fromUrl = function (videoSrc, scaleMode) +{ var video = document.createElement('video'); // array of objects or strings - if (Array.isArray(videoSrc)) { - for (var i = 0; i < videoSrc.length; ++i) { + if (Array.isArray(videoSrc)) + { + for (var i = 0; i < videoSrc.length; ++i) + { video.appendChild(createSource(videoSrc.src || videoSrc, videoSrc.mime)); } } // single object or string - else { + else + { video.appendChild(createSource(videoSrc.src || videoSrc, videoSrc.mime)); } @@ -169,8 +190,10 @@ VideoBaseTexture.fromUrls = VideoBaseTexture.fromUrl; -function createSource(path, type) { - if (!type) { +function createSource(path, type) +{ + if (!type) + { type = 'video/' + path.substr(path.lastIndexOf('.') + 1); } diff --git a/src/core/utils/EventData.js b/src/core/utils/EventData.js index 5d55a22..8cdf701 100644 --- a/src/core/utils/EventData.js +++ b/src/core/utils/EventData.js @@ -7,7 +7,8 @@ * @param name {string} The string name of the event that was triggered * @param data {object} Arbitrary event data to pass along */ -function EventData(target, name, data) { +function EventData(target, name, data) +{ // for duck typing in the ".on()" function this.__isEventObject = true; @@ -71,7 +72,8 @@ * Stops the propagation of events up the scene graph (prevents bubbling). * */ -EventData.prototype.stopPropagation = function stopPropagation() { +EventData.prototype.stopPropagation = function stopPropagation() +{ this.stopped = true; }; @@ -79,6 +81,7 @@ * Stops the propagation of events to sibling listeners (no longer calls any listeners). * */ -EventData.prototype.stopImmediatePropagation = function stopImmediatePropagation() { +EventData.prototype.stopImmediatePropagation = function stopImmediatePropagation() +{ this.stoppedImmediate = true; }; diff --git a/src/core/display/DisplayObject.js b/src/core/display/DisplayObject.js index 66ebc3c..20e778c 100644 --- a/src/core/display/DisplayObject.js +++ b/src/core/display/DisplayObject.js @@ -7,7 +7,8 @@ * @class * @namespace PIXI */ -function DisplayObject() { +function DisplayObject() +{ /** * The coordinate of the object relative to the local coordinates of the parent. * @@ -152,10 +153,12 @@ * @memberof DisplayObject# */ x: { - get: function () { + get: function () + { return this.position.x; }, - set: function (value) { + set: function (value) + { this.position.x = value; } }, @@ -167,10 +170,12 @@ * @memberof DisplayObject# */ y: { - get: function () { + get: function () + { return this.position.y; }, - set: function (value) { + set: function (value) + { this.position.y = value; } }, @@ -183,11 +188,13 @@ * @readonly */ worldVisible: { - get: function () { + get: function () + { var item = this; do { - if (!item.visible) { + if (!item.visible) + { return false; } @@ -207,17 +214,21 @@ * @memberof DisplayObject# */ mask: { - get: function () { + get: function () + { return this._mask; }, - set: function (value) { - if (this._mask) { + set: function (value) + { + if (this._mask) + { this._mask.isMask = false; } this._mask = value; - if (this._mask) { + if (this._mask) + { this._mask.isMask = true; } } @@ -232,18 +243,23 @@ * @memberof DisplayObject# */ filters: { - get: function () { + get: function () + { return this._filters; }, - set: function (value) { - if (value) { + set: function (value) + { + if (value) + { // now put all the passes in one place.. var passes = []; - for (var i = 0; i < value.length; i++) { + for (var i = 0; i < value.length; i++) + { var filterPasses = value[i].passes; - for (var j = 0; j < filterPasses.length; j++) { + for (var j = 0; j < filterPasses.length; j++) + { passes.push(filterPasses[j]); } } @@ -264,8 +280,9 @@ * * @private */ -DisplayObject.prototype.updateTransform = function () { - +DisplayObject.prototype.updateTransform = function () +{ + // create some matrix refs for easy access var pt = this.parent.worldTransform; var wt = this.worldTransform; @@ -274,9 +291,11 @@ var a, b, c, d, tx, ty; // so if rotation is between 0 then we can simplify the multiplication process.. - if (this.rotation % math.PI_2) { + if (this.rotation % math.PI_2) + { // 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) { + if (this.rotation !== this.rotationCache) + { this.rotationCache = this.rotation; this._sr = Math.sin(this.rotation); this._cr = Math.cos(this.rotation); @@ -291,7 +310,8 @@ ty = this.position.y; // check for pivot.. not often used so geared towards that fact! - if (this.pivot.x || this.pivot.y) { + 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; } @@ -304,7 +324,8 @@ wt.tx = tx * pt.a + ty * pt.c + pt.tx; wt.ty = tx * pt.b + ty * pt.d + pt.ty; } - else { + else + { // lets do the fast version as we know there is no rotation.. a = this.scale.x; d = this.scale.y; @@ -333,7 +354,8 @@ * @param matrix {Matrix} * @return {Rectangle} the rectangular bounding area */ -DisplayObject.prototype.getBounds = function (/* matrix */) { +DisplayObject.prototype.getBounds = function (/* matrix */) +{ return math.Rectangle.EMPTY; }; @@ -342,7 +364,8 @@ * * @return {Rectangle} the rectangular bounding area */ -DisplayObject.prototype.getLocalBounds = function () { +DisplayObject.prototype.getLocalBounds = function () +{ return this.getBounds(math.Matrix.IDENTITY); }; @@ -352,7 +375,8 @@ * @param position {Point} The world origin to calculate from * @return {Point} A point object representing the position of this object */ -DisplayObject.prototype.toGlobal = function (position) { +DisplayObject.prototype.toGlobal = function (position) +{ // don't need to u[date the lot this.displayObjectUpdateTransform(); return this.worldTransform.apply(position); @@ -365,8 +389,10 @@ * @param [from] {DisplayObject} The DisplayObject to calculate the global position from * @return {Point} A point object representing the position of this object */ -DisplayObject.prototype.toLocal = function (position, from) { - if (from) { +DisplayObject.prototype.toLocal = function (position, from) +{ + if (from) + { position = from.toGlobal(position); } @@ -381,7 +407,8 @@ * @param renderer {WebGLRenderer} The renderer * @private */ -DisplayObject.prototype.renderWebGL = function (/* renderer */) { +DisplayObject.prototype.renderWebGL = function (/* renderer */) +{ // OVERWRITE; }; @@ -391,6 +418,7 @@ * @param renderer {CanvasRenderer} The renderer * @private */ -DisplayObject.prototype.renderCanvas = function (/* renderer */) { +DisplayObject.prototype.renderCanvas = function (/* renderer */) +{ // OVERWRITE; }; diff --git a/src/core/display/DisplayObjectContainer.js b/src/core/display/DisplayObjectContainer.js index 689f40b..4625ee8 100644 --- a/src/core/display/DisplayObjectContainer.js +++ b/src/core/display/DisplayObjectContainer.js @@ -12,7 +12,8 @@ * @extends DisplayObject * @namespace PIXI */ -function DisplayObjectContainer() { +function DisplayObjectContainer() +{ DisplayObject.call(this); /** @@ -47,17 +48,21 @@ * @memberof DisplayObjectContainer# */ width: { - get: function () { + get: function () + { return this.scale.x * this.getLocalBounds().width; }, - set: function (value) { + set: function (value) + { var width = this.getLocalBounds().width; - if(width !== 0) { + if(width !== 0) + { this.scale.x = value / width; } - else { + else + { this.scale.x = 1; } @@ -73,17 +78,21 @@ * @memberof DisplayObjectContainer# */ height: { - get: function () { + get: function () + { return this.scale.y * this.getLocalBounds().height; }, - set: function (value) { + set: function (value) + { var height = this.getLocalBounds().height; - if (height !== 0) { + if (height !== 0) + { this.scale.y = value / height ; } - else { + else + { this.scale.y = 1; } @@ -100,18 +109,23 @@ * @memberof DisplayObject# */ cacheAsBitmap: { - get: function () { + get: function () + { return this._cacheAsBitmap; }, - set: function (value) { - if (this._cacheAsBitmap === value) { + set: function (value) + { + if (this._cacheAsBitmap === value) + { return; } - if (value) { + if (value) + { this._generateCachedSprite(); } - else { + else + { this._destroyCachedSprite(); } @@ -126,7 +140,8 @@ * @param child {DisplayObject} The DisplayObject to add to the container * @return {DisplayObject} The child that was added. */ -DisplayObjectContainer.prototype.addChild = function (child) { +DisplayObjectContainer.prototype.addChild = function (child) +{ return this.addChildAt(child, this.children.length); }; @@ -137,14 +152,18 @@ * @param index {Number} The index to place the child in * @return {DisplayObject} The child that was added. */ -DisplayObjectContainer.prototype.addChildAt = function (child, index) { +DisplayObjectContainer.prototype.addChildAt = function (child, index) +{ // prevent adding self as child - if (child === this) { + if (child === this) + { return; } - if (index >= 0 && index <= this.children.length) { - if (child.parent) { + if (index >= 0 && index <= this.children.length) + { + if (child.parent) + { child.parent.removeChild(child); } @@ -154,7 +173,8 @@ return child; } - else { + else + { throw new Error(child + 'addChildAt: The index '+ index +' supplied is out of bounds ' + this.children.length); } }; @@ -165,15 +185,18 @@ * @param child {DisplayObject} * @param child2 {DisplayObject} */ -DisplayObjectContainer.prototype.swapChildren = function (child, child2) { - if (child === child2) { +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) { + if (index1 < 0 || index2 < 0) + { throw new Error('swapChildren: Both the supplied DisplayObjects must be a child of the caller.'); } @@ -187,10 +210,12 @@ * @param child {DisplayObject} The DisplayObject instance to identify * @return {Number} The index position of the child display object to identify */ -DisplayObjectContainer.prototype.getChildIndex = function (child) { +DisplayObjectContainer.prototype.getChildIndex = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { throw new Error('The supplied DisplayObject must be a child of the caller'); } @@ -203,8 +228,10 @@ * @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 */ -DisplayObjectContainer.prototype.setChildIndex = function (child, index) { - if (index < 0 || index >= this.children.length) { +DisplayObjectContainer.prototype.setChildIndex = function (child, index) +{ + if (index < 0 || index >= this.children.length) + { throw new Error('The supplied index is out of bounds'); } @@ -220,8 +247,10 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child at the given index, if any. */ -DisplayObjectContainer.prototype.getChildAt = function (index) { - if (index < 0 || index >= this.children.length) { +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'); } @@ -234,10 +263,12 @@ * @param child {DisplayObject} The DisplayObject to remove * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChild = function (child) { +DisplayObjectContainer.prototype.removeChild = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { return; } @@ -250,7 +281,8 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChildAt = function (index) { +DisplayObjectContainer.prototype.removeChildAt = function (index) +{ var child = this.getChildAt(index); child.parent = null; @@ -265,24 +297,29 @@ * @param beginIndex {Number} The beginning position. Default value is 0. * @param endIndex {Number} The ending position. Default value is size of the container. */ -DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) { +DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) +{ var begin = beginIndex || 0; var end = typeof endIndex === 'number' ? endIndex : this.children.length; var range = end - begin; - if (range > 0 && range <= end) { + if (range > 0 && range <= end) + { var removed = this.children.splice(begin, range); - for (var i = 0; i < removed.length; ++i) { + for (var i = 0; i < removed.length; ++i) + { removed[i].parent = null; } return removed; } - else if (range === 0 && this.children.length === 0) { + else if (range === 0 && this.children.length === 0) + { return []; } - else { + else + { throw new RangeError('removeChildren: numeric values are outside the acceptable range.'); } }; @@ -291,7 +328,8 @@ * Generates and updates the cached sprite for this object. * */ -DisplayObjectContainer.prototype.updateCachedSprite = function () { +DisplayObjectContainer.prototype.updateCachedSprite = function () +{ this._generateCachedSprite(); }; @@ -304,7 +342,8 @@ * @param renderer {CanvasRenderer|WebGLRenderer} The renderer used to generate the texture. * @return {Texture} a texture of the graphics object */ -DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) { +DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) +{ var bounds = this.getLocalBounds(); var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0, renderer, scaleMode, resolution); @@ -322,18 +361,22 @@ * * @private */ -DisplayObjectContainer.prototype.updateTransform = function () { - if (!this.visible) { +DisplayObjectContainer.prototype.updateTransform = function () +{ + if (!this.visible) + { return; } this.displayObjectUpdateTransform(); - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { return; } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } }; @@ -346,8 +389,10 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getBounds = function () { - if (this.children.length === 0) { +DisplayObjectContainer.prototype.getBounds = function () +{ + if (this.children.length === 0) + { return math.Rectangle.EMPTY; } @@ -365,10 +410,12 @@ var childVisible = false; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -386,7 +433,8 @@ maxY = maxY > childMaxY ? maxY : childMaxY; } - if (!childVisible) { + if (!childVisible) + { return math.Rectangle.EMPTY; } @@ -407,12 +455,14 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getLocalBounds = function () { +DisplayObjectContainer.prototype.getLocalBounds = function () +{ var matrixCache = this.worldTransform; this.worldTransform = math.Matrix.IDENTITY; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } @@ -428,13 +478,16 @@ * * @param renderer {WebGLRenderer} The renderer */ -DisplayObjectContainer.prototype.renderWebGL = function (renderer) { +DisplayObjectContainer.prototype.renderWebGL = function (renderer) +{ // if the object is not visible or the alpha is 0 then no need to render this element - if (!this.visible || this.alpha <= 0) { + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } @@ -442,14 +495,17 @@ var i, j; // do a quick check to see if this element has a mask or a filter. - if (this._mask || this._filters) { + if (this._mask || this._filters) + { // push filter first as we need to ensure the stencil buffer is correct for any masking - if (this._filters) { + if (this._filters) + { renderer.spriteBatch.flush(); renderer.filterManager.pushFilter(this._filterBlock); } - if (this._mask) { + if (this._mask) + { renderer.spriteBatch.stop(); renderer.maskManager.pushMask(this.mask, renderer); renderer.spriteBatch.start(); @@ -459,36 +515,42 @@ this._renderWebGL(renderer); // now loop through the children and make sure they get rendered - for (i = 0, j = this.children.length; i < j; i++) { + for (i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderWebGL(renderer); } // time to stop the sprite batch as either a mask element or a filter draw will happen next renderer.spriteBatch.stop(); - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(this._mask, renderer); } - if (this._filters) { + if (this._filters) + { renderer.filterManager.popFilter(); } renderer.spriteBatch.start(); } - else { + else + { this._renderWebGL(renderer); // simple render children! - for (i = 0, j = this.children.length; i < j; ++i) { + for (i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderWebGL(renderer); } } }; -DisplayObjectContainer.prototype._renderWebGL = function (renderer) { +DisplayObjectContainer.prototype._renderWebGL = function (renderer) +{ // this is where content itself gets renderd.. @@ -499,25 +561,31 @@ * * @param renderer {CanvasRenderer} The renderer */ -DisplayObjectContainer.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0) { +DisplayObjectContainer.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -528,13 +596,16 @@ * @param renderer {WebGLRenderer|CanvasRenderer} The renderer * @private */ -DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) { +DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) +{ this._cachedSprite.worldAlpha = this.worldAlpha; - if (renderer.gl) { + if (renderer.gl) + { this._cachedSprite.renderWebGL(renderer); } - else { + else + { this._cachedSprite.renderCanvas(renderer); } }; @@ -544,10 +615,12 @@ * * @private */ -DisplayObjectContainer.prototype._generateCachedSprite = function () { +DisplayObjectContainer.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { // TODO - RenderTexture now *requires* a renderer instance, so this is like broken // because `renderer` isn't actually in scope here :P var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0); @@ -555,7 +628,8 @@ this._cachedSprite = new Sprite(renderTexture); this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.texture.resize(bounds.width | 0, bounds.height | 0); } @@ -580,8 +654,10 @@ * * @private */ -DisplayObjectContainer.prototype._destroyCachedSprite = function () { - if (!this._cachedSprite) { +DisplayObjectContainer.prototype._destroyCachedSprite = function () +{ + if (!this._cachedSprite) + { return; } diff --git a/src/core/display/Sprite.js b/src/core/display/Sprite.js index 707da24..5862aef 100644 --- a/src/core/display/Sprite.js +++ b/src/core/display/Sprite.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param texture {Texture} The texture for this sprite */ -function Sprite(texture) { +function Sprite(texture) +{ DisplayObjectContainer.call(this); /** @@ -85,12 +86,14 @@ this.texture = texture || Texture.EMPTY; } -Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) { +Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) +{ DisplayObjectContainer.prototype.destroy.call(this); this.anchor = null; - if (destroyTexture) { + if (destroyTexture) + { this._texture.destroy(destroyBaseTexture); } @@ -111,10 +114,12 @@ * @memberof Sprite# */ width: { - get: function () { + get: function () + { return this.scale.x * this.texture.frame.width; }, - set: function (value) { + set: function (value) + { this.scale.x = value / this.texture.frame.width; this._width = value; } @@ -127,10 +132,12 @@ * @memberof Sprite# */ height: { - get: function () { + get: function () + { return this.scale.y * this.texture.frame.height; }, - set: function (value) { + set: function (value) + { this.scale.y = value / this.texture.frame.height; this._height = value; } @@ -143,23 +150,29 @@ * @memberof Sprite# */ texture: { - get: function () { + get: function () + { return this._texture; }, - set: function (value) { - if (this._texture === value) { + set: function (value) + { + if (this._texture === value) + { return; } this._texture = value; this.cachedTint = 0xFFFFFF; - if (value) { + if (value) + { // wait for the texture to load - if (value.baseTexture.hasLoaded) { + if (value.baseTexture.hasLoaded) + { this._onTextureUpdate(); } - else { + else + { value.once('update', this._onTextureUpdate.bind(this)); } } @@ -172,18 +185,22 @@ * * @private */ -Sprite.prototype._onTextureUpdate = function () { +Sprite.prototype._onTextureUpdate = function () +{ // so if _width is 0 then width was not set.. - if (this._width) { + if (this._width) + { this.scale.x = this._width / this.texture.frame.width; } - if (this._height) { + if (this._height) + { this.scale.y = this._height / this.texture.frame.height; } }; -Sprite.prototype._renderWebGL = function (renderer) { +Sprite.prototype._renderWebGL = function (renderer) +{ // this is where content gets renderd.. // watch this space for a little render state manager.. @@ -197,7 +214,8 @@ * @param matrix {Matrix} the transformation matrix of the sprite * @return {Rectangle} the framing rectangle */ -Sprite.prototype.getBounds = function (matrix) { +Sprite.prototype.getBounds = function (matrix) +{ var width = this.texture.frame.width; var height = this.texture.frame.height; @@ -224,11 +242,13 @@ if(b === 0 && c === 0) { // scale may be negative! - if (a < 0) { + if (a < 0) + { a *= -1; } - if (d < 0) { + if (d < 0) + { d *= -1; } @@ -293,28 +313,34 @@ * * @param renderer {CanvasRenderer} The renderer */ -Sprite.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) { +Sprite.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) + { return; } - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; renderer.context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } // Ignore null sources - if (this.texture.valid) { + if (this.texture.valid) + { var resolution = this.texture.baseTexture.resolution / renderer.resolution; renderer.context.globalAlpha = this.worldAlpha; // If smoothingEnabled is supported and we need to change the smoothing property for this texture - if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) { + if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) + { renderer.scaleMode = this.texture.baseTexture.scaleMode; renderer.context[renderer.smoothProperty] = (renderer.scaleMode === CONST.scaleModes.LINEAR); } @@ -324,7 +350,8 @@ var dy = (this.texture.trim ? this.texture.trim.y : 0) - (this.anchor.y * this.texture.trim.height); // Allow for pixel rounding - if (renderer.roundPixels) { + if (renderer.roundPixels) + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -337,7 +364,8 @@ dx = dx | 0; dy = dy | 0; } - else { + else + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -348,8 +376,10 @@ ); } - if (this.tint !== 0xFFFFFF) { - if (this.cachedTint !== this.tint) { + if (this.tint !== 0xFFFFFF) + { + if (this.cachedTint !== this.tint) + { this.cachedTint = this.tint; // TODO clean up caching - how to clean up the caches? @@ -368,7 +398,8 @@ this.texture.crop.height / resolution ); } - else { + else + { renderer.context.drawImage( this.texture.baseTexture.source, this.texture.crop.x, @@ -383,11 +414,13 @@ } } - for (var i = 0, j = this.children.length; i < j; i++) { + for (var i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -402,10 +435,12 @@ * @param frameId {String} The frame Id of the texture in the cache * @return {Sprite} A new Sprite using a texture from the texture cache matching the frameId */ -Sprite.fromFrame = function (frameId) { +Sprite.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache' + this); } @@ -420,6 +455,7 @@ * @param imageId {String} The image url of the texture * @return {Sprite} A new Sprite using a texture from the texture cache matching the image id */ -Sprite.fromImage = function (imageId, crossorigin, scaleMode) { +Sprite.fromImage = function (imageId, crossorigin, scaleMode) +{ return new Sprite(Texture.fromImage(imageId, crossorigin, scaleMode)); }; diff --git a/src/core/display/SpriteBatch.js b/src/core/display/SpriteBatch.js index 3187777..c196fef 100644 --- a/src/core/display/SpriteBatch.js +++ b/src/core/display/SpriteBatch.js @@ -12,7 +12,8 @@ * ```js * var container = new SpriteBatch(); * - * for(var i = 0; i < 100; ++i) { + * for(var i = 0; i < 100; ++i) + * { * var sprite = new PIXI.Sprite.fromImage("myImage.png"); * container.addChild(sprite); * } @@ -25,7 +26,8 @@ */ //TODO RENAME to PARTICLE CONTAINER? -function SpriteBatch() { +function SpriteBatch() +{ DisplayObjectContainer.call(this); } @@ -38,7 +40,8 @@ * * @private */ -SpriteBatch.prototype.updateTransform = function () { +SpriteBatch.prototype.updateTransform = function () +{ // TODO don't need to! this.displayObjectUpdateTransform(); // PIXI.DisplayObjectContainer.prototype.updateTransform.call( this ); @@ -50,8 +53,10 @@ * @param renderer {WebGLRenderer} The webgl renderer * @private */ -SpriteBatch.prototype.renderWebGL = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderWebGL = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -71,8 +76,10 @@ * @param renderer {CanvasRenderer} The canvas renderer * @private */ -SpriteBatch.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -84,10 +91,12 @@ this.displayObjectUpdateTransform(); - for (var i = 0; i < this.children.length; ++i) { + for (var i = 0; i < this.children.length; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -95,9 +104,11 @@ context.globalAlpha = this.worldAlpha * child.alpha; - if (child.rotation % (Math.PI * 2) === 0) { + if (child.rotation % (Math.PI * 2) === 0) + { // this is the fastest way to optimise! - if rotation is 0 then we can avoid any kind of setTransform call - if (isRotated) { + if (isRotated) + { context.setTransform( transform.a, transform.b, @@ -122,8 +133,10 @@ frame.height * child.scale.y ); } - else { - if (!isRotated) { + else + { + if (!isRotated) + { isRotated = true; } @@ -131,7 +144,8 @@ var childTransform = child.worldTransform; - if (renderer.roundPixels) { + if (renderer.roundPixels) + { context.setTransform( childTransform.a, childTransform.b, @@ -141,7 +155,8 @@ childTransform.ty | 0 ); } - else { + else + { context.setTransform( childTransform.a, childTransform.b, diff --git a/src/core/index.js b/src/core/index.js index 3954b6f..eb4a82b 100644 --- a/src/core/index.js +++ b/src/core/index.js @@ -58,11 +58,13 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRenderer: function (width, height, options, noWebGL) { + autoDetectRenderer: function (width, height, options, noWebGL) + { width = width || 800; height = height || 600; - if (!noWebGL && require('webgl-enabled')()) { + if (!noWebGL && require('webgl-enabled')()) + { return new core.WebGLRenderer(width, height, options); } @@ -87,7 +89,8 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRecommendedRenderer: function (width, height, options) { + autoDetectRecommendedRenderer: function (width, height, options) + { var isAndroid = /Android/i.test(navigator.userAgent); return core.autoDetectRenderer(width, height, options, isAndroid); diff --git a/src/core/math/Matrix.js b/src/core/math/Matrix.js index c2f87e2..2ff4848 100644 --- a/src/core/math/Matrix.js +++ b/src/core/math/Matrix.js @@ -10,7 +10,8 @@ * @class * @namespace PIXI */ -function Matrix() { +function Matrix() +{ /** * @member {number} * @default 1 @@ -63,7 +64,8 @@ * * @param array {number[]} The array that the matrix will be populated from. */ -Matrix.prototype.fromArray = function (array) { +Matrix.prototype.fromArray = function (array) +{ this.a = array[0]; this.b = array[1]; this.c = array[3]; @@ -78,14 +80,17 @@ * @param transpose {boolean} Whether we need to transpose the matrix or not * @return {number[]} the newly created array which contains the matrix */ -Matrix.prototype.toArray = function (transpose) { - if (!this.array) { +Matrix.prototype.toArray = function (transpose) +{ + if (!this.array) + { this.array = new Float32Array(9); } var array = this.array; - if (transpose) { + if (transpose) + { array[0] = this.a; array[1] = this.b; array[2] = 0; @@ -96,7 +101,8 @@ array[7] = this.ty; array[8] = 1; } - else { + else + { array[0] = this.a; array[1] = this.c; array[2] = this.tx; @@ -119,7 +125,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, transformed through this matrix */ -Matrix.prototype.apply = function (pos, newPos) { +Matrix.prototype.apply = function (pos, newPos) +{ newPos = newPos || new Point(); newPos.x = this.a * pos.x + this.c * pos.y + this.tx; @@ -136,7 +143,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, inverse-transformed through this matrix */ -Matrix.prototype.applyInverse = function (pos, newPos) { +Matrix.prototype.applyInverse = function (pos, newPos) +{ newPos = newPos || new Point(); var id = 1 / (this.a * this.d + this.c * -this.b); @@ -154,7 +162,8 @@ * @param {number} y * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.translate = function (x, y) { +Matrix.prototype.translate = function (x, y) +{ this.tx += x; this.ty += y; @@ -168,7 +177,8 @@ * @param {number} y The amount to scale vertically * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.scale = function (x, y) { +Matrix.prototype.scale = function (x, y) +{ this.a *= x; this.d *= y; this.c *= x; @@ -186,7 +196,8 @@ * @param {number} angle - The angle in radians. * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.rotate = function (angle) { +Matrix.prototype.rotate = function (angle) +{ var cos = Math.cos( angle ); var sin = Math.sin( angle ); @@ -210,7 +221,8 @@ * @param {Matrix} matrix * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.append = function (matrix) { +Matrix.prototype.append = function (matrix) +{ var a1 = this.a; var b1 = this.b; var c1 = this.c; @@ -232,7 +244,8 @@ * * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.identity = function () { +Matrix.prototype.identity = function () +{ this.a = 1; this.b = 0; this.c = 0; diff --git a/src/core/math/Point.js b/src/core/math/Point.js index 7565b2d..632f346 100644 --- a/src/core/math/Point.js +++ b/src/core/math/Point.js @@ -7,7 +7,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -function Point(x, y) { +function Point(x, y) +{ /** * @member {number} * @default 0 @@ -29,7 +30,8 @@ * * @return {Point} a copy of the point */ -Point.prototype.clone = function () { +Point.prototype.clone = function () +{ return new Point(this.x, this.y); }; @@ -40,7 +42,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -Point.prototype.set = function (x, y) { +Point.prototype.set = function (x, y) +{ this.x = x || 0; this.y = y || ( (y !== 0) ? this.x : 0 ) ; }; diff --git a/src/core/math/shapes/Circle.js b/src/core/math/shapes/Circle.js index 69cfdc9..4d76efc 100644 --- a/src/core/math/shapes/Circle.js +++ b/src/core/math/shapes/Circle.js @@ -10,7 +10,8 @@ * @param y {number} The Y coordinate of the center of this circle * @param radius {number} The radius of the circle */ -function Circle(x, y, radius) { +function Circle(x, y, radius) +{ /** * @member {number} * @default 0 @@ -46,7 +47,8 @@ * @method clone * @return {Circle} a copy of the Circle */ -Circle.prototype.clone = function () { +Circle.prototype.clone = function () +{ return new Circle(this.x, this.y, this.radius); }; @@ -58,8 +60,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Circle */ -Circle.prototype.contains = function (x, y) { - if (this.radius <= 0) { +Circle.prototype.contains = function (x, y) +{ + if (this.radius <= 0) + { return false; } @@ -79,6 +83,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Circle.prototype.getBounds = function () { +Circle.prototype.getBounds = function () +{ return new Rectangle(this.x - this.radius, this.y - this.radius, this.radius * 2, this.radius * 2); }; diff --git a/src/core/math/shapes/Ellipse.js b/src/core/math/shapes/Ellipse.js index 4f2d066..fefd01a 100644 --- a/src/core/math/shapes/Ellipse.js +++ b/src/core/math/shapes/Ellipse.js @@ -11,7 +11,8 @@ * @param width {number} The half width of this ellipse * @param height {number} The half height of this ellipse */ -function Ellipse(x, y, width, height) { +function Ellipse(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -53,7 +54,8 @@ * @method clone * @return {Ellipse} a copy of the ellipse */ -Ellipse.prototype.clone = function () { +Ellipse.prototype.clone = function () +{ return new Ellipse(this.x, this.y, this.width, this.height); }; @@ -65,8 +67,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coords are within this ellipse */ -Ellipse.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Ellipse.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } @@ -86,6 +90,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Ellipse.prototype.getBounds = function () { +Ellipse.prototype.getBounds = function () +{ return new Rectangle(this.x - this.width, this.y - this.height, this.width, this.height); }; diff --git a/src/core/math/shapes/Polygon.js b/src/core/math/shapes/Polygon.js index ae89148..fea6d37 100644 --- a/src/core/math/shapes/Polygon.js +++ b/src/core/math/shapes/Polygon.js @@ -10,16 +10,20 @@ * arguments passed can be flat x,y values e.g. `new Polygon(x,y, x,y, x,y, ...)` where `x` and `y` are * Numbers. */ -function Polygon(points) { +function Polygon(points) +{ //if points isn't an array, use arguments as the array - if (!(points instanceof Array)) { + if (!(points instanceof Array)) + { points = Array.prototype.slice.call(arguments); } //if this is a flat array of numbers, convert it to points - if (points[0] instanceof Point) { + if (points[0] instanceof Point) + { var p = []; - for (var i = 0, il = points.length; i < il; i++) { + for (var i = 0, il = points.length; i < il; i++) + { p.push(points[i].x, points[i].y); } @@ -51,7 +55,8 @@ * * @return {Polygon} a copy of the polygon */ -Polygon.prototype.clone = function () { +Polygon.prototype.clone = function () +{ return new Polygon(this.points.slice()); }; @@ -62,19 +67,22 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this polygon */ -Polygon.prototype.contains = function (x, y) { +Polygon.prototype.contains = function (x, y) +{ var inside = false; // use some raycasting to test hits // https://github.com/substack/point-in-polygon/blob/master/index.js var length = this.points.length / 2; - for (var i = 0, j = length - 1; i < length; j = i++) { + for (var i = 0, j = length - 1; i < length; j = i++) + { var xi = this.points[i * 2], yi = this.points[i * 2 + 1], xj = this.points[j * 2], yj = this.points[j * 2 + 1], intersect = ((yi > y) !== (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi); - if (intersect) { + if (intersect) + { inside = !inside; } } diff --git a/src/core/math/shapes/Rectangle.js b/src/core/math/shapes/Rectangle.js index 16ac62a..4008b68 100644 --- a/src/core/math/shapes/Rectangle.js +++ b/src/core/math/shapes/Rectangle.js @@ -10,7 +10,8 @@ * @param width {number} The overall width of this rectangle * @param height {number} The overall height of this rectangle */ -function Rectangle(x, y, width, height) { +function Rectangle(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -60,7 +61,8 @@ * * @return {Rectangle} a copy of the rectangle */ -Rectangle.prototype.clone = function () { +Rectangle.prototype.clone = function () +{ return new Rectangle(this.x, this.y, this.width, this.height); }; @@ -71,13 +73,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rectangle */ -Rectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Rectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/math/shapes/RoundedRectangle.js b/src/core/math/shapes/RoundedRectangle.js index 27d286e..7bf6411 100644 --- a/src/core/math/shapes/RoundedRectangle.js +++ b/src/core/math/shapes/RoundedRectangle.js @@ -11,7 +11,8 @@ * @param height {number} The overall height of this rounded rectangle * @param radius {number} Controls the radius of the rounded corners */ -function RoundedRectangle(x, y, width, height, radius) { +function RoundedRectangle(x, y, width, height, radius) +{ /** * @member {number} * @default 0 @@ -58,7 +59,8 @@ * * @return {RoundedRectangle} a copy of the rounded rectangle */ -RoundedRectangle.prototype.clone = function () { +RoundedRectangle.prototype.clone = function () +{ return new RoundedRectangle(this.x, this.y, this.width, this.height, this.radius); }; @@ -69,13 +71,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rounded Rectangle */ -RoundedRectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +RoundedRectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/primitives/Graphics.js b/src/core/primitives/Graphics.js index 261c534..e902d2a 100644 --- a/src/core/primitives/Graphics.js +++ b/src/core/primitives/Graphics.js @@ -16,7 +16,8 @@ * @extends DisplayObjectContainer * @namespace PIXI */ -function Graphics() { +function Graphics() +{ DisplayObjectContainer.call(this); this.renderable = true; @@ -154,16 +155,20 @@ * @private */ cacheAsBitmap: { - get: function () { + get: function () + { return this._cacheAsBitmap; }, - set: function (value) { + set: function (value) + { this._cacheAsBitmap = value; - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._generateCachedSprite(); } - else { + else + { this.destroyCachedSprite(); this.dirty = true; } @@ -176,7 +181,8 @@ * * @return {Graphics} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ var clone = new Graphics(); clone.renderable = this.renderable; @@ -192,7 +198,8 @@ clone.cachedSpriteDirty = this.cachedSpriteDirty; // copy graphics data - for (var i = 0; i < this.graphicsData.length; ++i) { + for (var i = 0; i < this.graphicsData.length; ++i) + { clone.graphicsData.push(this.graphicsData.clone()); } @@ -211,17 +218,21 @@ * @param alpha {number} alpha of the line to draw, will update the objects stored style * @return {Graphics} */ -Graphics.prototype.lineStyle = function (lineWidth, color, alpha) { +Graphics.prototype.lineStyle = function (lineWidth, color, alpha) +{ this.lineWidth = lineWidth || 0; this.lineColor = color || 0; this.lineAlpha = (arguments.length < 3) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length) + { // halfway through a line? start a new one! this.drawShape( new math.Polygon( this.currentPath.shape.points.slice(-2) )); } - else { + else + { // otherwise its empty so lets just set the line properties this.currentPath.lineWidth = this.lineWidth; this.currentPath.lineColor = this.lineColor; @@ -239,7 +250,8 @@ * @param y {number} the Y coordinate to move to * @return {Graphics} */ -Graphics.prototype.moveTo = function (x, y) { +Graphics.prototype.moveTo = function (x, y) +{ this.drawShape(new math.Polygon([x,y])); return this; @@ -253,7 +265,8 @@ * @param y {number} the Y coordinate to draw to * @return {Graphics} */ -Graphics.prototype.lineTo = function (x, y) { +Graphics.prototype.lineTo = function (x, y) +{ this.currentPath.shape.points.push(x, y); this.dirty = true; @@ -270,13 +283,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -285,7 +302,8 @@ n = 20, points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { this.moveTo(0, 0); } @@ -293,7 +311,8 @@ var fromY = points[points.length-1]; var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; xa = fromX + ( (cpX - fromX) * j ); @@ -319,13 +338,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -342,7 +365,8 @@ var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; dt = (1 - j); @@ -373,13 +397,17 @@ * @param radius {number} The radius of the arc * @return {Graphics} */ -Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points.push(x1, y1); } } - else { + else + { this.moveTo(x1, y1); } @@ -392,12 +420,15 @@ b2 = x2 - x1, mm = Math.abs(a1 * b2 - b1 * a2); - if (mm < 1.0e-8 || radius === 0) { - if (points[points.length-2] !== x1 || points[points.length-1] !== y1) { + if (mm < 1.0e-8 || radius === 0) + { + if (points[points.length-2] !== x1 || points[points.length-1] !== y1) + { points.push(x1, y1); } } - else { + else + { var dd = a1 * a1 + b1 * b1, cc = a2 * a2 + b2 * b2, tt = a1 * a2 + b1 * b2, @@ -433,42 +464,51 @@ * @param anticlockwise {boolean} Optional. Specifies whether the drawing should be counterclockwise or clockwise. False is default, and indicates clockwise, while true indicates counter-clockwise. * @return {Graphics} */ -Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) { +Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) +{ var startX = cx + Math.cos(startAngle) * radius; var startY = cy + Math.sin(startAngle) * radius; var points; // TODO - This if-else makes no sense. It uses currentPath in the else where it doesn't exist... - if (this.currentPath) { + if (this.currentPath) + { points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { points.push(startX, startY); } - else if (points[points.length-2] !== startX || points[points.length-1] !== startY) { + else if (points[points.length-2] !== startX || points[points.length-1] !== startY) + { points.push(startX, startY); } } - else { + else + { this.moveTo(startX, startY); points = this.currentPath.shape.points; } - if (startAngle === endAngle) { + if (startAngle === endAngle) + { return this; } - if (!anticlockwise && endAngle <= startAngle) { + if (!anticlockwise && endAngle <= startAngle) + { endAngle += Math.PI * 2; } - else if (anticlockwise && startAngle <= endAngle) { + else if (anticlockwise && startAngle <= endAngle) + { startAngle += Math.PI * 2; } var sweep = anticlockwise ? (startAngle - endAngle) *-1 : (endAngle - startAngle); var segs = (Math.abs(sweep)/ (Math.PI * 2)) * 40; - if (sweep === 0) { + if (sweep === 0) + { return this; } @@ -482,7 +522,8 @@ var remainder = ( segMinus % 1 ) / segMinus; - for (var i = 0; i <= segMinus; ++i) { + for (var i = 0; i <= segMinus; ++i) + { var real = i + remainder * i; var angle = ((theta) + startAngle + (theta2 * real)); @@ -506,13 +547,16 @@ * @param alpha {number} the alpha of the fill * @return {Graphics} */ -Graphics.prototype.beginFill = function (color, alpha) { +Graphics.prototype.beginFill = function (color, alpha) +{ this.filling = true; this.fillColor = color || 0; this.fillAlpha = (alpha === undefined) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length <= 2) + { this.currentPath.fill = this.filling; this.currentPath.fillColor = this.fillColor; this.currentPath.fillAlpha = this.fillAlpha; @@ -526,7 +570,8 @@ * * @return {Graphics} */ -Graphics.prototype.endFill = function () { +Graphics.prototype.endFill = function () +{ this.filling = false; this.fillColor = null; this.fillAlpha = 1; @@ -542,7 +587,8 @@ * @param height {number} The height of the rectangle * @return {Graphics} */ -Graphics.prototype.drawRect = function ( x, y, width, height ) { +Graphics.prototype.drawRect = function ( x, y, width, height ) +{ this.drawShape(new math.Rectangle(x,y, width, height)); return this; @@ -556,7 +602,8 @@ * @param height {number} The height of the rectangle * @param radius {number} Radius of the rectangle corners */ -Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) { +Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) +{ this.drawShape(new math.RoundedRectangle(x, y, width, height, radius)); return this; @@ -570,7 +617,8 @@ * @param radius {number} The radius of the circle * @return {Graphics} */ -Graphics.prototype.drawCircle = function (x, y, radius) { +Graphics.prototype.drawCircle = function (x, y, radius) +{ this.drawShape(new math.Circle(x,y, radius)); return this; @@ -585,7 +633,8 @@ * @param height {number} The half height of the ellipse * @return {Graphics} */ -Graphics.prototype.drawEllipse = function (x, y, width, height) { +Graphics.prototype.drawEllipse = function (x, y, width, height) +{ this.drawShape(new math.Ellipse(x, y, width, height)); return this; @@ -597,8 +646,10 @@ * @param path {Array} The path data used to construct the polygon. * @return {Graphics} */ -Graphics.prototype.drawPolygon = function (path) { - if (!(path instanceof Array)) { +Graphics.prototype.drawPolygon = function (path) +{ + if (!(path instanceof Array)) + { path = Array.prototype.slice.call(arguments); } @@ -612,7 +663,8 @@ * * @return {Graphics} */ -Graphics.prototype.clear = function () { +Graphics.prototype.clear = function () +{ this.lineWidth = 0; this.filling = false; @@ -631,7 +683,8 @@ * @param scaleMode {number} Should be one of the scaleMode consts * @return {Texture} a texture of the graphics object */ -Graphics.prototype.generateTexture = function (resolution, scaleMode) { +Graphics.prototype.generateTexture = function (resolution, scaleMode) +{ resolution = resolution || 1; var bounds = this.getBounds(); @@ -655,17 +708,21 @@ * * @param renderer {WebGLRenderer} */ -Graphics.prototype._renderWebGL = function (renderer) { +Graphics.prototype._renderWebGL = function (renderer) +{ // if the sprite is not visible or the alpha is 0 then no need to render this element - if (this.isMask === true) { + if (this.isMask === true) + { return; } // this code may still be needed so leaving for now.. - // + // /* - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture on the gpu too! @@ -681,17 +738,24 @@ return; } - */ - - // check if the webgl graphic needs to be updated - if (this.glDirty) { - this.dirty = true; - this.glDirty = false; - } + else */ - renderer.setObjectRendererer(renderer.graphicsRenderer); - renderer.graphicsRenderer.render(this); + renderer.spriteBatch.stop(); + renderer.blendModeManager.setBlendMode(this.blendMode); + // check blend mode + renderer.blendModeManager.setBlendMode( this.blendMode ); + + // check if the webgl graphic needs to be updated + if (this.glDirty) + { + this.dirty = true; + this.glDirty = false; + } + + WebGLGraphics.renderGraphics(this, renderer); + + renderer.spriteBatch.start(); }; /** @@ -700,14 +764,18 @@ * @param renderer {CanvasRenderer} * @private */ -Graphics.prototype.renderCanvas = function (renderer) { +Graphics.prototype.renderCanvas = function (renderer) +{ // 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.isMask === true) { + if (!this.visible || this.alpha <= 0 || this.isMask === true) + { return; } - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture @@ -723,16 +791,19 @@ return; } - else { + else + { var context = renderer.context; var transform = this.worldTransform; - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } @@ -748,11 +819,13 @@ CanvasGraphics.renderGraphics(this, context); - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } } @@ -763,13 +836,16 @@ * * @return {Rectangle} the rectangular bounding area */ -Graphics.prototype.getBounds = function (matrix) { +Graphics.prototype.getBounds = function (matrix) +{ // return an empty object if the item is a mask! - if (this.isMask) { + if (this.isMask) + { return math.Rectangle.EMPTY; } - if (this.dirty) { + if (this.dirty) + { this.updateLocalBounds(); this.glDirty = true; @@ -841,23 +917,27 @@ * Update the bounds of the object * */ -Graphics.prototype.updateLocalBounds = function () { +Graphics.prototype.updateLocalBounds = function () +{ var minX = Infinity; var maxX = -Infinity; var minY = Infinity; var maxY = -Infinity; - if (this.graphicsData.length) { + if (this.graphicsData.length) + { var shape, points, x, y, w, h; - for (var i = 0; i < this.graphicsData.length; i++) { + for (var i = 0; i < this.graphicsData.length; i++) + { var data = this.graphicsData[i]; var type = data.type; var lineWidth = data.lineWidth; shape = data.shape; - if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) { + if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) + { x = shape.x - lineWidth/2; y = shape.y - lineWidth/2; w = shape.width + lineWidth; @@ -869,7 +949,8 @@ minY = y < minY ? y : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.CIRC) { + else if (type === CONST.SHAPES.CIRC) + { x = shape.x; y = shape.y; w = shape.radius + lineWidth/2; @@ -881,7 +962,8 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.ELIP) { + else if (type === CONST.SHAPES.ELIP) + { x = shape.x; y = shape.y; w = shape.width + lineWidth/2; @@ -893,11 +975,13 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else { + else + { // POLY points = shape.points; - for (var j = 0; j < points.length; j += 2) { + for (var j = 0; j < points.length; j += 2) + { x = points[j]; y = points[j+1]; @@ -910,7 +994,8 @@ } } } - else { + else + { minX = 0; maxX = 0; minY = 0; @@ -931,10 +1016,12 @@ * * @private */ -Graphics.prototype._generateCachedSprite = function () { +Graphics.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { var canvasBuffer = new CanvasBuffer(bounds.width, bounds.height); var texture = Texture.fromCanvas(canvasBuffer.canvas); @@ -943,7 +1030,8 @@ this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.buffer.resize(bounds.width, bounds.height); } @@ -968,7 +1056,8 @@ * * @private */ -Graphics.prototype.updateCachedSpriteTexture = function () { +Graphics.prototype.updateCachedSpriteTexture = function () +{ var cachedSprite = this._cachedSprite; var texture = cachedSprite.texture; var canvas = cachedSprite.buffer.canvas; @@ -989,7 +1078,8 @@ * Destroys a previous cached sprite. * */ -Graphics.prototype.destroyCachedSprite = function () { +Graphics.prototype.destroyCachedSprite = function () +{ this._cachedSprite.texture.destroy(true); // let the gc collect the unused sprite @@ -1003,10 +1093,13 @@ * @param {Circle|Rectangle|Ellipse|Line|Polygon} shape The Shape object to draw. * @return {GraphicsData} The generated GraphicsData object. */ -Graphics.prototype.drawShape = function (shape) { - if (this.currentPath) { +Graphics.prototype.drawShape = function (shape) +{ + if (this.currentPath) + { // check current path! - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath.shape.points.length <= 2) + { this.graphicsData.pop(); } } @@ -1017,7 +1110,8 @@ this.graphicsData.push(data); - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { data.shape.closed = this.filling; this.currentPath = data; } diff --git a/src/core/primitives/GraphicsData.js b/src/core/primitives/GraphicsData.js index 99decbe..788f6f2 100644 --- a/src/core/primitives/GraphicsData.js +++ b/src/core/primitives/GraphicsData.js @@ -4,7 +4,8 @@ * @class * @namespace PIXI */ -function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) { +function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) +{ this.lineWidth = lineWidth; this.lineColor = lineColor; this.lineAlpha = lineAlpha; @@ -27,7 +28,8 @@ * * @return {GraphicsData} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ return new GraphicsData( this.lineWidth, this.lineColor, diff --git a/src/core/renderers/canvas/CanvasRenderer.js b/src/core/renderers/canvas/CanvasRenderer.js index 15a0978..7aebd44 100644 --- a/src/core/renderers/canvas/CanvasRenderer.js +++ b/src/core/renderers/canvas/CanvasRenderer.js @@ -17,17 +17,22 @@ * @param [options.resolution=1] {number} the resolution of the renderer retina would be 2 * @param [options.clearBeforeRender=true] {boolean} This sets if the CanvasRenderer will clear the canvas or not before the new render pass. */ -function CanvasRenderer(width, height, options) { +function CanvasRenderer(width, height, options) +{ utils.sayHello('Canvas'); - if (options) { - for (var i in CONST.defaultRenderOptions) { - if (typeof options[i] === 'undefined') { + if (options) + { + for (var i in CONST.defaultRenderOptions) + { + if (typeof options[i] === 'undefined') + { options[i] = CONST.defaultRenderOptions[i]; } } } - else { + else + { options = CONST.defaultRenderOptions; } @@ -156,19 +161,24 @@ this.smoothProperty = null; - if (this.context.imageSmoothingEnabled) { + if (this.context.imageSmoothingEnabled) + { this.smoothProperty = 'imageSmoothingEnabled'; } - else if (this.context.webkitImageSmoothingEnabled) { + else if (this.context.webkitImageSmoothingEnabled) + { this.smoothProperty = 'webkitImageSmoothingEnabled'; } - else if (this.context.mozImageSmoothingEnabled) { + else if (this.context.mozImageSmoothingEnabled) + { this.smoothProperty = 'mozImageSmoothingEnabled'; } - else if (this.context.oImageSmoothingEnabled) { + else if (this.context.oImageSmoothingEnabled) + { this.smoothProperty = 'oImageSmoothingEnabled'; } - else if (this.context.msImageSmoothingEnabled) { + else if (this.context.msImageSmoothingEnabled) + { this.smoothProperty = 'msImageSmoothingEnabled'; } @@ -193,10 +203,12 @@ * @memberof CanvasRenderer# */ backgroundColor: { - get: function () { + get: function () + { return this._backgroundColor; }, - set: function (val) { + set: function (val) + { this._backgroundColor = val; this._backgroundColorString = utils.hex2string(val); } @@ -208,7 +220,8 @@ * * @param object {DisplayObject} the object to be rendered */ -CanvasRenderer.prototype.render = function (object) { +CanvasRenderer.prototype.render = function (object) +{ object.updateTransform(); this.context.setTransform(1,0,0,1,0,0); @@ -218,16 +231,20 @@ this.currentBlendMode = CONST.blendModes.NORMAL; this.context.globalCompositeOperation = this.blendModes[CONST.blendModes.NORMAL]; - if (navigator.isCocoonJS && this.view.screencanvas) { + if (navigator.isCocoonJS && this.view.screencanvas) + { this.context.fillStyle = 'black'; this.context.clear(); } - if (this.clearBeforeRender) { - if (this.transparent) { + if (this.clearBeforeRender) + { + if (this.transparent) + { this.context.clearRect(0, 0, this.width, this.height); } - else { + else + { this.context.fillStyle = this._backgroundColorString; this.context.fillRect(0, 0, this.width , this.height); } @@ -241,8 +258,10 @@ * * @param [removeView=false] {boolean} Removes the Canvas element from the DOM. */ -CanvasRenderer.prototype.destroy = function (removeView) { - if (removeView && this.view.parent) { +CanvasRenderer.prototype.destroy = function (removeView) +{ + if (removeView && this.view.parent) + { this.view.parent.removeChild(this.view); } @@ -257,14 +276,16 @@ * @param width {number} the new width of the canvas view * @param height {number} the new height of the canvas view */ -CanvasRenderer.prototype.resize = function (width, height) { +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) { + if (this.autoResize) + { this.view.style.width = this.width / this.resolution + 'px'; this.view.style.height = this.height / this.resolution + 'px'; } @@ -276,7 +297,8 @@ * @param displayObject {DisplayObject} The displayObject to render * @private */ -CanvasRenderer.prototype.renderDisplayObject = function (displayObject) { +CanvasRenderer.prototype.renderDisplayObject = function (displayObject) +{ displayObject.renderCanvas(this); }; @@ -285,11 +307,14 @@ * * @private */ -CanvasRenderer.prototype._mapBlendModes = function () { - if (!this.blendModes) { +CanvasRenderer.prototype._mapBlendModes = function () +{ + if (!this.blendModes) + { this.blendModes = {}; - if (utils.canUseNewCanvasBlendModes()) { + if (utils.canUseNewCanvasBlendModes()) + { this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? this.blendModes[CONST.blendModes.MULTIPLY] = 'multiply'; @@ -308,7 +333,8 @@ this.blendModes[CONST.blendModes.COLOR] = 'color'; this.blendModes[CONST.blendModes.LUMINOSITY] = 'luminosity'; } - else { + else + { // this means that the browser does not support the cool new blend modes in canvas 'cough' ie 'cough' this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? diff --git a/src/core/renderers/canvas/utils/CanvasBuffer.js b/src/core/renderers/canvas/utils/CanvasBuffer.js index ebe5d47..b183a66 100644 --- a/src/core/renderers/canvas/utils/CanvasBuffer.js +++ b/src/core/renderers/canvas/utils/CanvasBuffer.js @@ -6,7 +6,8 @@ * @param width {number} the width for the newly created canvas * @param height {number} the height for the newly created canvas */ -function CanvasBuffer(width, height) { +function CanvasBuffer(width, height) +{ /** * The Canvas object that belongs to this CanvasBuffer. * @@ -36,10 +37,12 @@ * @memberof CanvasBuffer# */ width: { - get: function () { + get: function () + { return this.canvas.width; }, - set: function (val) { + set: function (val) + { this.canvas.width = val; } }, @@ -50,10 +53,12 @@ * @memberof CanvasBuffer# */ height: { - get: function () { + get: function () + { return this.canvas.height; }, - set: function (val) { + set: function (val) + { this.canvas.height = val; } } @@ -64,7 +69,8 @@ * * @private */ -CanvasBuffer.prototype.clear = function () { +CanvasBuffer.prototype.clear = function () +{ this.context.setTransform(1, 0, 0, 1, 0, 0); this.context.clearRect(0,0, this.canvas.width, this.canvas.height); }; @@ -75,7 +81,8 @@ * @param width {number} the new width of the canvas * @param height {number} the new height of the canvas */ -CanvasBuffer.prototype.resize = function (width, height) { +CanvasBuffer.prototype.resize = function (width, height) +{ this.canvas.width = width; this.canvas.height = height; }; diff --git a/src/core/renderers/canvas/utils/CanvasGraphics.js b/src/core/renderers/canvas/utils/CanvasGraphics.js index c7eaa2a..3f2a91f 100644 --- a/src/core/renderers/canvas/utils/CanvasGraphics.js +++ b/src/core/renderers/canvas/utils/CanvasGraphics.js @@ -13,15 +13,18 @@ * @param graphics {Graphics} the actual graphics object to render * @param context {CanvasRenderingContext2D} the 2d drawing method of the canvas */ -CanvasGraphics.renderGraphics = function (graphics, context) { +CanvasGraphics.renderGraphics = function (graphics, context) +{ var worldAlpha = graphics.worldAlpha; - if (graphics.dirty) { + if (graphics.dirty) + { this.updateGraphicsTint(graphics); graphics.dirty = false; } - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; @@ -30,69 +33,82 @@ context.lineWidth = data.lineWidth; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { context.beginPath(); var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } - if (shape.closed) { + if (shape.closed) + { context.lineTo(points[0], points[1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fillRect(shape.x, shape.y, shape.width, shape.height); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.strokeRect(shape.x, shape.y, shape.width, shape.height); } } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.beginPath(); context.arc(shape.x, shape.y, shape.radius,0,2*Math.PI); context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas var w = shape.width * 2; @@ -119,18 +135,21 @@ context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; var width = shape.width; @@ -152,13 +171,15 @@ context.quadraticCurveTo(rx, ry, rx, ry + radius); context.closePath(); - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); @@ -174,45 +195,54 @@ * @param graphics {Graphics} the graphics which will be used as a mask * @param context {CanvasRenderingContext2D} the context 2d method of the canvas */ -CanvasGraphics.renderGraphicsMask = function (graphics, context) { +CanvasGraphics.renderGraphicsMask = function (graphics, context) +{ var len = graphics.graphicsData.length; - if (len === 0) { + if (len === 0) + { return; } context.beginPath(); - for (var i = 0; i < len; i++) { + for (var i = 0; i < len; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { context.rect(shape.x, shape.y, shape.width, shape.height); context.closePath(); } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.arc(shape.x, shape.y, shape.radius, 0, 2 * Math.PI); context.closePath(); } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas @@ -237,7 +267,8 @@ context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); context.closePath(); } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; @@ -262,8 +293,10 @@ } }; -CanvasGraphics.updateGraphicsTint = function (graphics) { - if (graphics.tint === 0xFFFFFF) { +CanvasGraphics.updateGraphicsTint = function (graphics) +{ + if (graphics.tint === 0xFFFFFF) + { return; } @@ -271,7 +304,8 @@ var tintG = (graphics.tint >> 8 & 0xFF) / 255; var tintB = (graphics.tint & 0xFF)/ 255; - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var fillColor = data.fillColor | 0; diff --git a/src/core/renderers/canvas/utils/CanvasMaskManager.js b/src/core/renderers/canvas/utils/CanvasMaskManager.js index e04a733..9827d36 100644 --- a/src/core/renderers/canvas/utils/CanvasMaskManager.js +++ b/src/core/renderers/canvas/utils/CanvasMaskManager.js @@ -6,7 +6,8 @@ * @class * @namespace PIXI */ -function CanvasMaskManager() {} +function CanvasMaskManager() +{} CanvasMaskManager.prototype.constructor = CanvasMaskManager; module.exports = CanvasMaskManager; @@ -17,7 +18,8 @@ * @param maskData {object} the maskData that will be pushed * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.pushMask = function (maskData, renderer) { +CanvasMaskManager.prototype.pushMask = function (maskData, renderer) +{ renderer.context.save(); var cacheAlpha = maskData.alpha; @@ -45,6 +47,7 @@ * * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.popMask = function (renderer) { +CanvasMaskManager.prototype.popMask = function (renderer) +{ renderer.context.restore(); }; diff --git a/src/core/renderers/canvas/utils/CanvasTinter.js b/src/core/renderers/canvas/utils/CanvasTinter.js index 17e0529..d2fb1bc 100644 --- a/src/core/renderers/canvas/utils/CanvasTinter.js +++ b/src/core/renderers/canvas/utils/CanvasTinter.js @@ -14,7 +14,8 @@ * @param color {number} the color to use to tint the sprite with * @return {HTMLCanvasElement} The tinted canvas */ -CanvasTinter.getTintedTexture = function (sprite, color) { +CanvasTinter.getTintedTexture = function (sprite, color) +{ var texture = sprite.texture; color = CanvasTinter.roundColor(color); @@ -23,7 +24,8 @@ texture.tintCache = texture.tintCache || {}; - if (texture.tintCache[stringColor]) { + if (texture.tintCache[stringColor]) + { return texture.tintCache[stringColor]; } @@ -33,14 +35,16 @@ //CanvasTinter.tintWithPerPixel(texture, stringColor, canvas); CanvasTinter.tintMethod(texture, color, canvas); - if (CanvasTinter.convertTintToImage) { + if (CanvasTinter.convertTintToImage) + { // is this better? var tintImage = new Image(); tintImage.src = canvas.toDataURL(); texture.tintCache[stringColor] = tintImage; } - else { + else + { texture.tintCache[stringColor] = canvas; // if we are not converting the texture to an image then we need to lose the reference to the canvas CanvasTinter.canvas = null; @@ -56,7 +60,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithMultiply = function (texture, color, canvas) { +CanvasTinter.tintWithMultiply = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -104,7 +109,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithOverlay = function (texture, color, canvas) { +CanvasTinter.tintWithOverlay = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -139,7 +145,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithPerPixel = function (texture, color, canvas) { +CanvasTinter.tintWithPerPixel = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -167,7 +174,8 @@ var pixels = pixelData.data; - for (var i = 0; i < pixels.length; i += 4) { + for (var i = 0; i < pixels.length; i += 4) + { pixels[i+0] *= r; pixels[i+1] *= g; pixels[i+2] *= b; @@ -181,7 +189,8 @@ * * @param color {number} the color to round, should be a hex color */ -CanvasTinter.roundColor = function (color) { +CanvasTinter.roundColor = function (color) +{ var step = CanvasTinter.cacheStepsPerColorChannel; var rgbValues = utils.hex2rgb(color); diff --git a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js index 9f2f89a..35edbaf 100644 --- a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js +++ b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLBlendModeManager(renderer) { +function WebGLBlendModeManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -23,8 +24,10 @@ * * @param blendMode {number} the blendMode, should be a Pixi const, such as BlendModes.ADD */ -WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) { - if (this.currentBlendMode === blendMode) { +WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) +{ + if (this.currentBlendMode === blendMode) + { return false; } diff --git a/src/core/renderers/webgl/managers/WebGLFilterManager.js b/src/core/renderers/webgl/managers/WebGLFilterManager.js index 1179258..2dac048 100644 --- a/src/core/renderers/webgl/managers/WebGLFilterManager.js +++ b/src/core/renderers/webgl/managers/WebGLFilterManager.js @@ -7,7 +7,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLFilterManager(renderer) { +function WebGLFilterManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -32,7 +33,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.texturePool.length = 0; self.initShaderBuffers(); }); @@ -46,7 +48,8 @@ * @param renderer {WebGLRenderer} * @param buffer {ArrayBuffer} */ -WebGLFilterManager.prototype.begin = function (buffer) { +WebGLFilterManager.prototype.begin = function (buffer) +{ this.defaultShader = this.renderer.shaderManager.defaultShader; this.width = this.renderer.projection.x * 2; @@ -60,7 +63,8 @@ * * @param filterBlock {object} the filter that will be pushed to the current filter stack */ -WebGLFilterManager.prototype.pushFilter = function (filterBlock) { +WebGLFilterManager.prototype.pushFilter = function (filterBlock) +{ var gl = this.renderer.gl; var projection = this.renderer.projection; @@ -78,10 +82,12 @@ this.offsetY += filterBlock._filterArea.y; var texture = this.texturePool.pop(); - if (!texture) { + if (!texture) + { texture = new FilterTexture(this.renderer.gl, this.width, this.height); } - else { + else + { texture.resize(this.width, this.height); } @@ -98,29 +104,35 @@ var localX = filterArea.x, localY = filterArea.y; - if (filterArea.x < 0) { + if (filterArea.x < 0) + { filterArea.width += filterArea.x; filterArea.x = 0; } - if (filterArea.y < 0) { + if (filterArea.y < 0) + { filterArea.height += filterArea.y; filterArea.y = 0; } - if (localX + filterArea.width > this.width) { + if (localX + filterArea.width > this.width) + { filterArea.width = this.width - localX; } - if (localY + filterArea.height > this.height) { + if (localY + filterArea.height > this.height) + { filterArea.height = this.height - localY; } - if (filterArea.width < 0) { + if (filterArea.width < 0) + { filterArea.width = 0; } - if (filterArea.height < 0) { + if (filterArea.height < 0) + { filterArea.height = 0; } @@ -154,7 +166,8 @@ * Removes the last filter from the filter stack and doesn't return it. * */ -WebGLFilterManager.prototype.popFilter = function () { +WebGLFilterManager.prototype.popFilter = function () +{ var gl = this.renderer.gl; var filterBlock = this.filterStack.pop(); @@ -163,7 +176,8 @@ var projection = this.renderer.projection; var offset = this.renderer.offset; - if (filterBlock.filterPasses.length > 1) { + if (filterBlock.filterPasses.length > 1) + { gl.viewport(0, 0, filterArea.width, filterArea.height); gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); @@ -193,7 +207,8 @@ var inputTexture = texture; var outputTexture = this.texturePool.pop(); - if (!outputTexture) { + if (!outputTexture) + { outputTexture = new FilterTexture(this.renderer.gl, this.width, this.height); } outputTexture.resize(this.width, this.height); @@ -204,7 +219,8 @@ gl.disable(gl.BLEND); - for (var i = 0; i < filterBlock.filterPasses.length-1; i++) { + for (var i = 0; i < filterBlock.filterPasses.length-1; i++) + { var filterPass = filterBlock.filterPasses[i]; gl.bindFramebuffer(gl.FRAMEBUFFER, outputTexture.frameBuffer ); @@ -243,10 +259,12 @@ var buffer = this.buffer; // time to render the filters texture to the previous scene - if (this.filterStack.length === 0) { + if (this.filterStack.length === 0) + { gl.colorMask(true, true, true, true);//this.transparent); } - else { + else + { var currentFilter = this.filterStack[this.filterStack.length-1]; filterArea = currentFilter._filterArea; @@ -332,13 +350,15 @@ * @param width {number} the horizontal range of the filter * @param height {number} the vertical range of the filter */ -WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) { +WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) +{ // use program var gl = this.renderer.gl; var shader = filter.shaders[gl.id]; - if (!shader) { + if (!shader) + { shader = new Shader(gl); shader.fragmentSrc = filter.fragmentSrc; @@ -356,7 +376,8 @@ gl.uniform2f(shader.projectionVector, width/2, -height/2); gl.uniform2f(shader.offsetVector, 0,0); - if (filter.uniforms.dimensions) { + 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]; @@ -386,7 +407,8 @@ * Initialises the shader buffers. * */ -WebGLFilterManager.prototype.initShaderBuffers = function () { +WebGLFilterManager.prototype.initShaderBuffers = function () +{ var gl = this.renderer.gl; // create some buffers @@ -432,7 +454,8 @@ * Destroys the filter and removes it from the filter stack. * */ -WebGLFilterManager.prototype.destroy = function () { +WebGLFilterManager.prototype.destroy = function () +{ var gl = this.renderer.gl; this.filterStack = null; @@ -441,7 +464,8 @@ this.offsetY = 0; // destroy textures - for (var i = 0; i < this.texturePool.length; i++) { + for (var i = 0; i < this.texturePool.length; i++) + { this.texturePool[i].destroy(); } diff --git a/src/core/renderers/webgl/managers/WebGLManager.js b/src/core/renderers/webgl/managers/WebGLManager.js index 9d47b5c..c30cd51 100644 --- a/src/core/renderers/webgl/managers/WebGLManager.js +++ b/src/core/renderers/webgl/managers/WebGLManager.js @@ -3,7 +3,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLManager(renderer) { +function WebGLManager(renderer) +{ /** * The renderer this manager works for. * @@ -15,6 +16,7 @@ WebGLManager.prototype.constructor = WebGLManager; module.exports = WebGLManager; -WebGLManager.prototype.destroy = function () { +WebGLManager.prototype.destroy = function () +{ this.renderer = null; }; diff --git a/src/core/renderers/webgl/managers/WebGLMaskManager.js b/src/core/renderers/webgl/managers/WebGLMaskManager.js index 2f90b64..e568812 100644 --- a/src/core/renderers/webgl/managers/WebGLMaskManager.js +++ b/src/core/renderers/webgl/managers/WebGLMaskManager.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLMaskManager(renderer) { +function WebGLMaskManager(renderer) +{ WebGLManager.call(this, renderer); } @@ -19,12 +20,15 @@ * * @param maskData {any[]} */ -WebGLMaskManager.prototype.pushMask = function (maskData) { - if (maskData.dirty) { +WebGLMaskManager.prototype.pushMask = function (maskData) +{ + if (maskData.dirty) + { WebGLGraphics.updateGraphics(maskData, this.renderer.gl); } - if (!maskData._webGL[this.renderer.gl.id].data.length) { + if (!maskData._webGL[this.renderer.gl.id].data.length) + { return; } @@ -36,6 +40,7 @@ * * @param maskData {any[]} */ -WebGLMaskManager.prototype.popMask = function (maskData) { +WebGLMaskManager.prototype.popMask = function (maskData) +{ this.renderer.stencilManager.popStencil(maskData, maskData._webGL[this.renderer.gl.id].data[0], this.renderer); }; diff --git a/src/core/renderers/webgl/managers/WebGLShaderManager.js b/src/core/renderers/webgl/managers/WebGLShaderManager.js index fef071c..90c6477 100644 --- a/src/core/renderers/webgl/managers/WebGLShaderManager.js +++ b/src/core/renderers/webgl/managers/WebGLShaderManager.js @@ -10,7 +10,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLShaderManager(renderer) { +function WebGLShaderManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -28,7 +29,8 @@ */ this.tempAttribState = []; - for (var i = 0; i < this.maxAttibs; i++) { + for (var i = 0; i < this.maxAttibs; i++) + { this.attribState[i] = false; } @@ -66,7 +68,8 @@ // listen for context and update necessary shaders var self = this; - this.renderer.on('context', function (event) { + this.renderer.on('context', function (event) + { var gl = event.data; // this shader is used for rendering primitives @@ -97,29 +100,36 @@ * * @param attribs {Array} attribs */ -WebGLShaderManager.prototype.setAttribs = function (attribs) { +WebGLShaderManager.prototype.setAttribs = function (attribs) +{ // reset temp state var i; - for (i = 0; i < this.tempAttribState.length; i++) { + for (i = 0; i < this.tempAttribState.length; i++) + { this.tempAttribState[i] = false; } // set the new attribs - for (var a in attribs) { + for (var a in attribs) + { this.tempAttribState[attribs[a]] = true; } var gl = this.renderer.gl; - for (i = 0; i < this.attribState.length; i++) { - if (this.attribState[i] !== this.tempAttribState[i]) { + for (i = 0; i < this.attribState.length; i++) + { + if (this.attribState[i] !== this.tempAttribState[i]) + { this.attribState[i] = this.tempAttribState[i]; - if (this.attribState[i]) { + if (this.attribState[i]) + { gl.enableVertexAttribArray(i); } - else { + else + { gl.disableVertexAttribArray(i); } } @@ -131,8 +141,10 @@ * * @param shader {Any} */ -WebGLShaderManager.prototype.setShader = function (shader) { - if (this._currentId === shader.uuid) { +WebGLShaderManager.prototype.setShader = function (shader) +{ + if (this._currentId === shader.uuid) + { return false; } @@ -150,7 +162,8 @@ * Destroys this object. * */ -WebGLShaderManager.prototype.destroy = function () { +WebGLShaderManager.prototype.destroy = function () +{ this.attribState = null; this.tempAttribState = null; diff --git a/src/core/renderers/webgl/managers/WebGLStencilManager.js b/src/core/renderers/webgl/managers/WebGLStencilManager.js index 9ec6398..4cb0134 100644 --- a/src/core/renderers/webgl/managers/WebGLStencilManager.js +++ b/src/core/renderers/webgl/managers/WebGLStencilManager.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLStencilManager(renderer) { +function WebGLStencilManager(renderer) +{ WebGLManager.call(this, renderer); this.stencilStack = []; @@ -24,12 +25,14 @@ * @param graphics {Graphics} * @param webGLData {any[]} */ -WebGLStencilManager.prototype.pushStencil = function (graphics, webGLData) { +WebGLStencilManager.prototype.pushStencil = function (graphics, webGLData) +{ var gl = this.renderer.gl; this.bindGraphics(graphics, webGLData, this.renderer); - if (this.stencilStack.length === 0) { + if (this.stencilStack.length === 0) + { gl.enable(gl.STENCIL_TEST); gl.clear(gl.STENCIL_BUFFER_BIT); this.reverse = true; @@ -47,14 +50,17 @@ // draw the triangle strip! - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } @@ -62,31 +68,38 @@ // draw a quad to increment.. gl.drawElements(gl.TRIANGLE_FAN, 4, gl.UNSIGNED_SHORT, ( webGLData.indices.length - 4 ) * 2 ); - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); } this.reverse = !this.reverse; } - else { - if (!this.reverse) { + else + { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } - else { + 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) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); } } @@ -103,7 +116,8 @@ * @param graphics {Graphics} * @param webGLData {Array} */ -WebGLStencilManager.prototype.bindGraphics = function (graphics, webGLData) { +WebGLStencilManager.prototype.bindGraphics = function (graphics, webGLData) +{ //if (this._currentGraphics === graphics)return; this._currentGraphics = graphics; @@ -114,7 +128,8 @@ offset = this.renderer.offset, shader;// = this.renderer.shaderManager.primitiveShader; - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { shader = this.renderer.shaderManager.complexPrimitiveShader; this.renderer.shaderManager.setShader(shader); @@ -141,7 +156,8 @@ // set the index buffer! gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, webGLData.indexBuffer); } - else { + else + { //this.renderer.shaderManager.activatePrimitiveShader(); shader = this.renderer.shaderManager.primitiveShader; this.renderer.shaderManager.setShader( shader ); @@ -154,7 +170,7 @@ gl.uniform2f(shader.uniforms.offsetVector._location, -offset.x, -offset.y); gl.uniform3fv(shader.uniforms.tint._location, utils.hex2rgb(graphics.tint)); - + gl.uniform1f(shader.uniforms.alpha._location, graphics.worldAlpha); @@ -172,19 +188,22 @@ * @param graphics {Graphics} * @param webGLData {Array} */ -WebGLStencilManager.prototype.popStencil = function (graphics, webGLData) { +WebGLStencilManager.prototype.popStencil = function (graphics, webGLData) +{ var gl = this.renderer.gl; this.stencilStack.pop(); this.count--; - if (this.stencilStack.length === 0) { + if (this.stencilStack.length === 0) + { // the stack is empty! gl.disable(gl.STENCIL_TEST); } - else { + else + { var level = this.count; @@ -192,14 +211,17 @@ gl.colorMask(false, false, false, false); - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { this.reverse = !this.reverse; - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } @@ -213,31 +235,38 @@ // draw the triangle strip! gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); - if (!this.reverse) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); } } - else { + else + { // console.log("<<>>") - if (!this.reverse) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } - else { + 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) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); } } @@ -253,7 +282,8 @@ * Destroys the mask stack. * */ -WebGLStencilManager.prototype.destroy = function () { +WebGLStencilManager.prototype.destroy = function () +{ this.renderer = null; this.stencilStack = null; }; diff --git a/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js b/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js index 913ba5e..1ea7d19 100644 --- a/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js +++ b/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function ComplexPrimitiveShader(gl) { +function ComplexPrimitiveShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -24,7 +25,8 @@ 'uniform float flipY;', 'varying vec4 vColor;', - 'void main(void) {', + '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);', @@ -37,7 +39,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = vColor;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/FastShader.js b/src/core/renderers/webgl/shaders/FastShader.js index bd2e29a..2e5e060 100644 --- a/src/core/renderers/webgl/shaders/FastShader.js +++ b/src/core/renderers/webgl/shaders/FastShader.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function FastShader(gl) { +function FastShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -28,7 +29,8 @@ 'const vec2 center = vec2(-1.0, 1.0);', - 'void main(void) {', + 'void main(void) + {', ' vec2 v;', ' vec2 sv = aVertexPosition * aScale;', ' v.x = (sv.x) * cos(aRotation) - (sv.y) * sin(aRotation);', @@ -49,7 +51,8 @@ 'uniform sampler2D uSampler;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/PrimitiveShader.js b/src/core/renderers/webgl/shaders/PrimitiveShader.js index 6f25409..a25f54f 100644 --- a/src/core/renderers/webgl/shaders/PrimitiveShader.js +++ b/src/core/renderers/webgl/shaders/PrimitiveShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function PrimitiveShader(gl) { +function PrimitiveShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -23,7 +24,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + '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);', @@ -36,7 +38,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = vColor;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/Shader.js b/src/core/renderers/webgl/shaders/Shader.js index f8964f5..fd75ef5 100644 --- a/src/core/renderers/webgl/shaders/Shader.js +++ b/src/core/renderers/webgl/shaders/Shader.js @@ -6,7 +6,8 @@ * @param [fragmentSrc] {string} The source of the fragment shader. * @param [vertexSrc] {string} The source of the vertex shader. */ -function Shader(gl, vertexSrc, fragmentSrc, customUniforms, customAttributes) { +function Shader(gl, vertexSrc, fragmentSrc, customUniforms, customAttributes) +{ /** * @member {number} * @readonly @@ -33,7 +34,8 @@ dimensions: { type: '4f', value: new Float32Array(4) } }; - for (var u in customUniforms) { + for (var u in customUniforms) + { this.uniforms[u] = customUniforms[u]; } @@ -43,7 +45,8 @@ aColor: 0 }; - for (var a in customAttributes) { + for (var a in customAttributes) + { this.attributes[a] = customAttributes[a]; } @@ -66,7 +69,8 @@ 'const vec2 center = vec2(-1.0, 1.0);', - 'void main(void) {', + 'void main(void) + {', ' gl_Position = vec4( ((aVertexPosition + offsetVector) / projectionVector) + center , 0.0, 1.0);', ' vTextureCoord = aTextureCoord;', ' vColor = vec4(aColor.rgb * aColor.a, aColor.a);', @@ -85,7 +89,8 @@ 'uniform sampler2D uSampler;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;', '}' ].join('\n'); @@ -96,7 +101,8 @@ Shader.prototype.constructor = Shader; module.exports = Shader; -Shader.prototype.init = function () { +Shader.prototype.init = function () +{ this.compile(); this.gl.useProgram(this.program); @@ -105,14 +111,18 @@ this.cacheAttributeLocations(Object.keys(this.attributes)); }; -Shader.prototype.cacheUniformLocations = function (keys) { - for (var i = 0; i < keys.length; ++i) { +Shader.prototype.cacheUniformLocations = function (keys) +{ + for (var i = 0; i < keys.length; ++i) + { this.uniforms[keys[i]]._location = this.gl.getUniformLocation(this.program, keys[i]); } }; -Shader.prototype.cacheAttributeLocations = function (keys) { - for (var i = 0; i < keys.length; ++i) { +Shader.prototype.cacheAttributeLocations = function (keys) +{ + for (var i = 0; i < keys.length; ++i) + { this.attributes[keys[i]] = this.gl.getAttribLocation(this.program, keys[i]); } @@ -124,14 +134,16 @@ // 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.attributes.aColor === -1) { + // if (this.attributes.aColor === -1) + { // this.attributes.aColor = 2; // } // End worst hack eva // }; -Shader.prototype.compile = function () { +Shader.prototype.compile = function () +{ var gl = this.gl; var glVertShader = this._glCompile(gl.VERTEX_SHADER, this.vertexSrc); @@ -144,13 +156,15 @@ gl.linkProgram(program); // if linking fails, then log and cleanup - if (!gl.getProgramParameter(program, gl.LINK_STATUS)) { + if (!gl.getProgramParameter(program, gl.LINK_STATUS)) + { window.console.error('Pixi.js Error: Could not initialize shader.'); window.console.error('gl.VALIDATE_STATUS', gl.getProgramParameter(program, gl.VALIDATE_STATUS)); window.console.error('gl.getError()', gl.getError()); // if there is a program info log, log it - if (gl.getProgramInfoLog(program) !== '') { + if (gl.getProgramInfoLog(program) !== '') + { window.console.warn('Pixi.js Warning: gl.getProgramInfoLog()', gl.getProgramInfoLog(program)); } @@ -165,18 +179,21 @@ return (this.program = program); }; -Shader.prototype.syncUniforms = function () { +Shader.prototype.syncUniforms = function () +{ var gl = this.gl; this.textureCount = 1; - for (var key in this.uniforms) { + for (var key in this.uniforms) + { var uniform = this.uniforms[key], location = uniform._location, value = uniform.value, i, il; - switch (uniform.type) { + switch (uniform.type) + { // single int value case 'i': case '1i': @@ -282,7 +299,8 @@ // a Color Value case 'c': - if (typeof value === 'number') { + if (typeof value === 'number') + { value = utils.hex2rgb(value); } @@ -311,11 +329,13 @@ // array of 2D Point objects case 'v2v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(2 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 2] = value[i].x; uniform._array[i * 2 + 1] = value[i].y; } @@ -325,11 +345,13 @@ // array of 3D Point objects case 'v3v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(3 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 3] = value[i].x; uniform._array[i * 3 + 1] = value[i].y; uniform._array[i * 3 + 2] = value[i].z; @@ -341,11 +363,13 @@ // array of 4D Point objects case 'v4v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(4 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 4] = value[i].x; uniform._array[i * 4 + 1] = value[i].y; uniform._array[i * 4 + 2] = value[i].z; @@ -359,7 +383,8 @@ // PIXI.Texture case 't': case 'sampler2D': - if (!uniform.value || !uniform.value.baseTexture || !uniform.value.baseTexture.hasLoaded) { + if (!uniform.value || !uniform.value.baseTexture || !uniform.value.baseTexture.hasLoaded) + { break; } @@ -376,7 +401,8 @@ this.textureCount++; // initialize the texture if we haven't yet - if (!uniform._init) { + if (!uniform._init) + { this.initSampler2D(uniform); uniform._init = true; @@ -394,11 +420,13 @@ * Initialises a Sampler2D uniform (which may only be available later on after initUniforms once the texture has loaded) * */ -Shader.prototype.initSampler2D = function (uniform) { +Shader.prototype.initSampler2D = function (uniform) +{ var gl = this.gl; // Extended texture data - if (uniform.textureData) { + if (uniform.textureData) + { var data = uniform.textureData; // GLTexture = mag linear, min linear_mipmap_linear, wrap repeat + gl.generateMipmap(gl.TEXTURE_2D); @@ -417,14 +445,16 @@ var wrapT = (data.wrapT) ? data.wrapT : gl.CLAMP_TO_EDGE; var format = (data.luminance) ? gl.LUMINANCE : gl.RGBA; - if (data.repeat) { + if (data.repeat) + { wrapS = gl.REPEAT; wrapT = gl.REPEAT; } gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, !!data.flipY); - if (data.width) { + if (data.width) + { var width = (data.width) ? data.width : 512; var height = (data.height) ? data.height : 2; var border = (data.border) ? data.border : 0; @@ -432,7 +462,8 @@ // 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 { + 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); } @@ -448,7 +479,8 @@ * Destroys the shader. * */ -Shader.prototype.destroy = function () { +Shader.prototype.destroy = function () +{ this.gl.deleteProgram(this.program); this.gl = null; @@ -459,13 +491,15 @@ this.fragmentSrc = null; }; -Shader.prototype._glCompile = function (type, src) { +Shader.prototype._glCompile = function (type, src) +{ var shader = this.gl.createShader(type); this.gl.shaderSource(shader, src); this.gl.compileShader(shader); - if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) { + if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) + { window.console.log(this.gl.getShaderInfoLog(shader)); return null; } diff --git a/src/core/renderers/webgl/shaders/StripShader.js b/src/core/renderers/webgl/shaders/StripShader.js index 193f6e1..a7abcc6 100644 --- a/src/core/renderers/webgl/shaders/StripShader.js +++ b/src/core/renderers/webgl/shaders/StripShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function StripShader(gl) { +function StripShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -20,7 +21,8 @@ 'varying vec2 vTextureCoord;', - 'void main(void) {', + '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);', @@ -36,7 +38,8 @@ 'varying vec2 vTextureCoord;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vec2(vTextureCoord.x, vTextureCoord.y)) * alpha;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/utils/FilterTexture.js b/src/core/renderers/webgl/utils/FilterTexture.js index d2c8423..4433d44 100644 --- a/src/core/renderers/webgl/utils/FilterTexture.js +++ b/src/core/renderers/webgl/utils/FilterTexture.js @@ -8,7 +8,8 @@ * @param height {number} the vertical range of the filter * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values */ -function FilterTexture(gl, width, height, scaleMode) { +function FilterTexture(gl, width, height, scaleMode) +{ /** * @member {WebGLContext} */ @@ -59,7 +60,8 @@ * Clears the filter texture. * */ -FilterTexture.prototype.clear = function () { +FilterTexture.prototype.clear = function () +{ var gl = this.gl; gl.clearColor(0,0,0, 0); @@ -72,8 +74,10 @@ * @param width {number} the new width of the texture * @param height {number} the new height of the texture */ -FilterTexture.prototype.resize = function (width, height) { - if (this.width === width && this.height === height) { +FilterTexture.prototype.resize = function (width, height) +{ + if (this.width === width && this.height === height) + { return; } @@ -96,7 +100,8 @@ * Destroys the filter texture. * */ -FilterTexture.prototype.destroy = function () { +FilterTexture.prototype.destroy = function () +{ var gl = this.gl; gl.deleteFramebuffer( this.frameBuffer ); gl.deleteTexture( this.texture ); diff --git a/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js b/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js index c4721e9..a63f4d7 100644 --- a/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js +++ b/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js @@ -14,7 +14,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this sprite batch works for. */ -function WebGLFastSpriteBatch(renderer) { +function WebGLFastSpriteBatch(renderer) +{ /** * The renderer instance this sprite batch operates on. * @@ -91,7 +92,8 @@ */ this.lastIndexCount = 0; - for (var i=0, j=0; i < numIndices; i += 6, j += 4) { + 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; @@ -144,7 +146,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.setupContext(); }); } @@ -157,7 +160,8 @@ * * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLFastSpriteBatch.prototype.setupContext = function () { +WebGLFastSpriteBatch.prototype.setupContext = function () +{ var gl = this.renderer.gl; // create a couple of buffers @@ -177,7 +181,8 @@ /** * @param spriteBatch {SpriteBatch} The SpriteBatch container to prepare for. */ -WebGLFastSpriteBatch.prototype.begin = function (spriteBatch) { +WebGLFastSpriteBatch.prototype.begin = function (spriteBatch) +{ this.shader = this.renderer.shaderManager.fastShader; this.matrix = spriteBatch.worldTransform.toArray(true); @@ -187,33 +192,38 @@ /** */ -WebGLFastSpriteBatch.prototype.end = function () { +WebGLFastSpriteBatch.prototype.end = function () +{ this.flush(); }; /** * @param spriteBatch {SpriteBatch} The SpriteBatch container to render. */ -WebGLFastSpriteBatch.prototype.render = function (spriteBatch) { +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) { + if (!sprite.texture._uvs) + { return; } this.currentBaseTexture = sprite.texture.baseTexture; // check blend mode - if (sprite.blendMode !== this.renderer.blendModeManager.currentBlendMode) { + if (sprite.blendMode !== this.renderer.blendModeManager.currentBlendMode) + { this.flush(); this.renderer.blendModeManager.setBlendMode(sprite.blendMode); } - for (var i=0,j= children.length; i= this.size) { + if (this.currentBatchSize >= this.size) + { this.flush(); } }; @@ -362,29 +379,35 @@ /** * */ -WebGLFastSpriteBatch.prototype.flush = function () { +WebGLFastSpriteBatch.prototype.flush = function () +{ // If the batch is length 0 then return as there is nothing to draw - if (this.currentBatchSize === 0) { + if (this.currentBatchSize === 0) + { return; } var gl = this.renderer.gl; // bind the current texture - if (!this.currentBaseTexture._glTextures[gl.id]) { + if (!this.currentBaseTexture._glTextures[gl.id]) + { this.renderer.updateTexture(this.currentBaseTexture, gl); } //TODO-SHOUD THIS BE ELSE??!?!?! - else { + else + { gl.bindTexture(gl.TEXTURE_2D, this.currentBaseTexture._glTextures[gl.id]); } // upload the verts to the buffer - if (this.currentBatchSize > ( this.size * 0.5 ) ) { + if (this.currentBatchSize > ( this.size * 0.5 ) ) + { gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); } - else { + else + { var view = this.vertices.subarray(0, this.currentBatchSize * this.vertByteSize); gl.bufferSubData(gl.ARRAY_BUFFER, 0, view); @@ -405,14 +428,16 @@ * Ends the batch and flushes * */ -WebGLFastSpriteBatch.prototype.stop = function () { +WebGLFastSpriteBatch.prototype.stop = function () +{ this.flush(); }; /** * */ -WebGLFastSpriteBatch.prototype.start = function () { +WebGLFastSpriteBatch.prototype.start = function () +{ var gl = this.renderer.gl; // bind the main texture diff --git a/src/core/renderers/webgl/utils/WebGLGraphics.js b/src/core/renderers/webgl/utils/WebGLGraphics.js index 55f4911..ab8f46e 100644 --- a/src/core/renderers/webgl/utils/WebGLGraphics.js +++ b/src/core/renderers/webgl/utils/WebGLGraphics.js @@ -19,7 +19,8 @@ * @param graphics {Graphics} * @param renderer {WebGLRenderer} */ -WebGLGraphics.renderGraphics = function (graphics, renderer) {//projection, offset) { +WebGLGraphics.renderGraphics = function (graphics, renderer) {//projection, offset) +{ var gl = renderer.gl; var projection = renderer.projection, @@ -27,7 +28,8 @@ shader = renderer.shaderManager.primitiveShader, webGLData; - if (graphics.dirty) { + if (graphics.dirty) + { WebGLGraphics.updateGraphics(graphics, gl); } @@ -35,8 +37,10 @@ // This could be speeded up for sure! - for (var i = 0; i < webGL.data.length; i++) { - if (webGL.data[i].mode === 1) { + for (var i = 0; i < webGL.data.length; i++) + { + if (webGL.data[i].mode === 1) + { webGLData = webGL.data[i]; renderer.stencilManager.pushStencil(graphics, webGLData, renderer); @@ -46,7 +50,8 @@ renderer.stencilManager.popStencil(graphics, webGLData, renderer); } - else { + else + { webGLData = webGL.data[i]; @@ -84,12 +89,14 @@ * @param graphicsData {Graphics} The graphics object to update * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLGraphics.updateGraphics = function (graphics, gl) { +WebGLGraphics.updateGraphics = function (graphics, gl) +{ // get the contexts graphics object var webGL = graphics._webGL[gl.id]; // if the graphics object does not exist in the webGL context time to create it! - if (!webGL) { + if (!webGL) + { webGL = graphics._webGL[gl.id] = {lastIndex:0, data:[], gl:gl}; } @@ -99,11 +106,13 @@ var i; // if the user cleared the graphics object we will need to clear every object - if (graphics.clearDirty) { + if (graphics.clearDirty) + { graphics.clearDirty = false; // lop through and return all the webGLDatas to the object pool so than can be reused later on - for (i = 0; i < webGL.data.length; i++) { + for (i = 0; i < webGL.data.length; i++) + { var graphicsData = webGL.data[i]; graphicsData.reset(); WebGLGraphics.graphicsDataPool.push( graphicsData ); @@ -119,58 +128,72 @@ // loop through the graphics datas and construct each one.. // if the object is a complex fill then the new stencil buffer technique will be used // other wise graphics objects will be pushed into a batch.. - for (i = webGL.lastIndex; i < graphics.graphicsData.length; i++) { + for (i = webGL.lastIndex; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { // need to add the points the the graphics object.. data.points = data.shape.points.slice(); - if (data.shape.closed) { + if (data.shape.closed) + { // close the poly if the value is true! - if (data.points[0] !== data.points[data.points.length-2] || data.points[1] !== data.points[data.points.length-1]) { + if (data.points[0] !== data.points[data.points.length-2] || data.points[1] !== data.points[data.points.length-1]) + { data.points.push(data.points[0], data.points[1]); } } // MAKE SURE WE HAVE THE CORRECT TYPE.. - if (data.fill) { - if (data.points.length >= 6) { - if (data.points.length < 6 * 2) { + if (data.fill) + { + if (data.points.length >= 6) + { + if (data.points.length < 6 * 2) + { webGLData = WebGLGraphics.switchMode(webGL, 0); var canDrawUsingSimple = WebGLGraphics.buildPoly(data, webGLData); // console.log(canDrawUsingSimple); - if (!canDrawUsingSimple) { + if (!canDrawUsingSimple) + { // console.log("<>>>") webGLData = WebGLGraphics.switchMode(webGL, 1); WebGLGraphics.buildComplexPoly(data, webGLData); } } - else { + else + { webGLData = WebGLGraphics.switchMode(webGL, 1); WebGLGraphics.buildComplexPoly(data, webGLData); } } } - if (data.lineWidth > 0) { + if (data.lineWidth > 0) + { webGLData = WebGLGraphics.switchMode(webGL, 0); WebGLGraphics.buildLine(data, webGLData); } } - else { + else + { webGLData = WebGLGraphics.switchMode(webGL, 0); - if (data.type === CONST.SHAPES.RECT) { + if (data.type === CONST.SHAPES.RECT) + { WebGLGraphics.buildRectangle(data, webGLData); } - else if (data.type === CONST.SHAPES.CIRC || data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.CIRC || data.type === CONST.SHAPES.ELIP) + { WebGLGraphics.buildCircle(data, webGLData); } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { WebGLGraphics.buildRoundedRectangle(data, webGLData); } } @@ -179,10 +202,12 @@ } // upload all the dirty data... - for (i = 0; i < webGL.data.length; i++) { + for (i = 0; i < webGL.data.length; i++) + { webGLData = webGL.data[i]; - if (webGLData.dirty) { + if (webGLData.dirty) + { webGLData.upload(); } } @@ -194,18 +219,22 @@ * @param webGL {WebGLContext} * @param type {number} */ -WebGLGraphics.switchMode = function (webGL, type) { +WebGLGraphics.switchMode = function (webGL, type) +{ var webGLData; - if (!webGL.data.length) { + if (!webGL.data.length) + { webGLData = WebGLGraphics.graphicsDataPool.pop() || new WebGLGraphicsData(webGL.gl); webGLData.mode = type; webGL.data.push(webGLData); } - else { + else + { webGLData = webGL.data[webGL.data.length-1]; - if (webGLData.mode !== type || type === 1) { + if (webGLData.mode !== type || type === 1) + { webGLData = WebGLGraphics.graphicsDataPool.pop() || new WebGLGraphicsData(webGL.gl); webGLData.mode = type; webGL.data.push(webGLData); @@ -225,7 +254,8 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildRectangle = function (graphicsData, webGLData) { +WebGLGraphics.buildRectangle = function (graphicsData, webGLData) +{ // --- // // need to convert points to a nice regular data // @@ -235,7 +265,8 @@ var width = rectData.width; var height = rectData.height; - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -265,7 +296,8 @@ indices.push(vertPos, vertPos, vertPos+1, vertPos+2, vertPos+3, vertPos+3); } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = [x, y, @@ -289,7 +321,8 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildRoundedRectangle = function (graphicsData, webGLData) { +WebGLGraphics.buildRoundedRectangle = function (graphicsData, webGLData) +{ var rrectData = graphicsData.shape; var x = rrectData.x; var y = rrectData.y; @@ -305,7 +338,8 @@ recPoints = recPoints.concat(WebGLGraphics.quadraticBezierCurve(x + width, y + radius, x + width, y, x + width - radius, y)); recPoints = recPoints.concat(WebGLGraphics.quadraticBezierCurve(x + radius, y, x, y, x, y + radius)); - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -323,7 +357,8 @@ // var i = 0; - for (i = 0; i < triangles.length; i+=3) { + for (i = 0; i < triangles.length; i+=3) + { indices.push(triangles[i] + vecPos); indices.push(triangles[i] + vecPos); indices.push(triangles[i+1] + vecPos); @@ -332,12 +367,14 @@ } - for (i = 0; i < recPoints.length; i++) { + for (i = 0; i < recPoints.length; i++) + { verts.push(recPoints[i], recPoints[++i], r, g, b, alpha); } } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = recPoints; @@ -362,7 +399,8 @@ * @param toY {number} Destination point y * @return {number[]} */ -WebGLGraphics.quadraticBezierCurve = function (fromX, fromY, cpX, cpY, toX, toY) { +WebGLGraphics.quadraticBezierCurve = function (fromX, fromY, cpX, cpY, toX, toY) +{ var xa, ya, @@ -373,14 +411,16 @@ n = 20, points = []; - function getPt(n1 , n2, perc) { + function getPt(n1 , n2, perc) + { var diff = n2 - n1; return n1 + ( diff * perc ); } var j = 0; - for (var i = 0; i <= n; i++ ) { + for (var i = 0; i <= n; i++ ) + { j = i / n; // The Green Line @@ -406,7 +446,8 @@ * @param graphicsData {Graphics} The graphics object to draw * @param webGLData {object} */ -WebGLGraphics.buildCircle = function (graphicsData, webGLData) { +WebGLGraphics.buildCircle = function (graphicsData, webGLData) +{ // need to convert points to a nice regular data var circleData = graphicsData.shape; var x = circleData.x; @@ -415,11 +456,13 @@ var height; // TODO - bit hacky?? - if (graphicsData.type === CONST.SHAPES.CIRC) { + if (graphicsData.type === CONST.SHAPES.CIRC) + { width = circleData.radius; height = circleData.radius; } - else { + else + { width = circleData.width; height = circleData.height; } @@ -429,7 +472,8 @@ var i = 0; - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -444,7 +488,8 @@ indices.push(vecPos); - for (i = 0; i < totalSegs + 1 ; i++) { + for (i = 0; i < totalSegs + 1 ; i++) + { verts.push(x,y, r, g, b, alpha); verts.push(x + Math.sin(seg * i) * width, @@ -457,12 +502,14 @@ indices.push(vecPos-1); } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = []; - for (i = 0; i < totalSegs + 1; i++) { + for (i = 0; i < totalSegs + 1; i++) + { graphicsData.points.push(x + Math.sin(seg * i) * width, y + Math.cos(seg * i) * height); } @@ -481,18 +528,22 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildLine = function (graphicsData, webGLData) { +WebGLGraphics.buildLine = function (graphicsData, webGLData) +{ // TODO OPTIMISE! var i = 0; var points = graphicsData.points; - if (points.length === 0) { + if (points.length === 0) + { return; } // if the line width is an odd number add 0.5 to align to a whole pixel - if (graphicsData.lineWidth%2) { - for (i = 0; i < points.length; i++) { + if (graphicsData.lineWidth%2) + { + for (i = 0; i < points.length; i++) + { points[i] += 0.5; } } @@ -502,7 +553,8 @@ var lastPoint = new math.Point(points[points.length - 2], points[points.length - 1]); // if the first point is the last point - gonna have issues :) - if (firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) { + if (firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) + { // need to clone as we are going to slightly modify the shape.. points = points.slice(); @@ -562,7 +614,8 @@ verts.push(p1x + perpx , p1y + perpy, r, g, b, alpha); - for (i = 1; i < length-1; i++) { + for (i = 1; i < length-1; i++) + { p1x = points[(i-1)*2]; p1y = points[(i-1)*2 + 1]; @@ -599,7 +652,8 @@ denom = a1*b2 - a2*b1; - if (Math.abs(denom) < 0.1 ) { + if (Math.abs(denom) < 0.1 ) + { denom+=10.1; verts.push(p2x - perpx , p2y - perpy, @@ -618,7 +672,8 @@ pdist = (px -p2x) * (px -p2x) + (py -p2y) + (py -p2y); - if (pdist > 140 * 140) { + if (pdist > 140 * 140) + { perp3x = perpx - perp2x; perp3y = perpy - perp2y; @@ -639,7 +694,8 @@ indexCount++; } - else { + else + { verts.push(px , py); verts.push(r, g, b, alpha); @@ -672,7 +728,8 @@ indices.push(indexStart); - for (i = 0; i < indexCount; i++) { + for (i = 0; i < indexCount; i++) + { indices.push(indexStart++); } @@ -687,11 +744,13 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildComplexPoly = function (graphicsData, webGLData) { +WebGLGraphics.buildComplexPoly = function (graphicsData, webGLData) +{ //TODO - no need to copy this as it gets turned into a FLoat32Array anyways.. var points = graphicsData.points.slice(); - if (points.length < 6) { + if (points.length < 6) + { return; } @@ -711,7 +770,8 @@ var x,y; // get size.. - for (var i = 0; i < points.length; i+=2) { + for (var i = 0; i < points.length; i+=2) + { x = points[i]; y = points[i+1]; @@ -732,7 +792,8 @@ //TODO - this aint needed! var length = points.length / 2; - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { indices.push( i ); } @@ -746,10 +807,12 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildPoly = function (graphicsData, webGLData) { +WebGLGraphics.buildPoly = function (graphicsData, webGLData) +{ var points = graphicsData.points; - if (points.length < 6) { + if (points.length < 6) + { return; } // get first and last point.. figure out the middle! @@ -767,7 +830,8 @@ var triangles = utils.PolyK.Triangulate(points); - if (!triangles) { + if (!triangles) + { return false; } @@ -775,7 +839,8 @@ var i = 0; - for (i = 0; i < triangles.length; i+=3) { + for (i = 0; i < triangles.length; i+=3) + { indices.push(triangles[i] + vertPos); indices.push(triangles[i] + vertPos); indices.push(triangles[i+1] + vertPos); @@ -783,7 +848,8 @@ indices.push(triangles[i+2] + vertPos); } - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { verts.push(points[i * 2], points[i * 2 + 1], r, g, b, alpha); } diff --git a/src/core/renderers/webgl/utils/WebGLGraphicsData.js b/src/core/renderers/webgl/utils/WebGLGraphicsData.js index c56d05e..c739ba7 100644 --- a/src/core/renderers/webgl/utils/WebGLGraphicsData.js +++ b/src/core/renderers/webgl/utils/WebGLGraphicsData.js @@ -2,7 +2,8 @@ * @class * @private */ -function WebGLGraphicsData(gl) { +function WebGLGraphicsData(gl) +{ this.gl = gl; //TODO does this need to be split before uploding?? @@ -22,7 +23,8 @@ /** * */ -WebGLGraphicsData.prototype.reset = function () { +WebGLGraphicsData.prototype.reset = function () +{ this.points.length = 0; this.indices.length = 0; }; @@ -30,7 +32,8 @@ /** * */ -WebGLGraphicsData.prototype.upload = function () { +WebGLGraphicsData.prototype.upload = function () +{ var gl = this.gl; // this.lastIndex = graphics.graphicsData.length; diff --git a/src/core/renderers/webgl/utils/WebGLSpriteBatch.js b/src/core/renderers/webgl/utils/WebGLSpriteBatch.js index 96eaa52..55befbb 100644 --- a/src/core/renderers/webgl/utils/WebGLSpriteBatch.js +++ b/src/core/renderers/webgl/utils/WebGLSpriteBatch.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this sprite batch works for. */ -function WebGLSpriteBatch(renderer) { +function WebGLSpriteBatch(renderer) +{ /** * * @@ -88,7 +89,8 @@ */ this.lastIndexCount = 0; - for (var i=0, j=0; i < numIndices; i += 6, j += 4) { + 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; @@ -162,7 +164,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.setupContext(); }); } @@ -173,7 +176,8 @@ /** * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLSpriteBatch.prototype.setupContext = function () { +WebGLSpriteBatch.prototype.setupContext = function () +{ var gl = this.renderer.gl; // setup default shader @@ -198,7 +202,8 @@ /** * */ -WebGLSpriteBatch.prototype.begin = function () { +WebGLSpriteBatch.prototype.begin = function () +{ // this.shader = this.renderer.shaderManager.defaultShader; this.start(); @@ -206,19 +211,22 @@ /** */ -WebGLSpriteBatch.prototype.end = function () { +WebGLSpriteBatch.prototype.end = function () +{ this.flush(); }; /** * @param sprite {Sprite} the sprite to render when using this spritebatch */ -WebGLSpriteBatch.prototype.render = function (sprite) { +WebGLSpriteBatch.prototype.render = function (sprite) +{ var texture = sprite.texture; //TODO set blend modes.. // check texture.. - if (this.currentBatchSize >= this.size) { + if (this.currentBatchSize >= this.size) + { this.flush(); this.currentBaseTexture = texture.baseTexture; } @@ -227,7 +235,8 @@ var uvs = texture._uvs; // if the uvs have not updated then no point rendering just yet! - if (!uvs) { + if (!uvs) + { return; } @@ -237,7 +246,8 @@ var w0, w1, h0, h1; - if (texture.trim) { + 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; @@ -248,7 +258,8 @@ h0 = h1 + texture.crop.height; } - else { + else + { w0 = (texture.frame.width ) * (1-aX); w1 = (texture.frame.width ) * -aX; @@ -272,7 +283,8 @@ var colors = this.colors; var positions = this.positions; - if (this.renderer.roundPixels) { + if (this.renderer.roundPixels) + { // xy positions[index] = a * w1 + c * h1 + tx | 0; positions[index+1] = d * h1 + b * w1 + ty | 0; @@ -289,7 +301,8 @@ positions[index+15] = a * w1 + c * h0 + tx | 0; positions[index+16] = d * h0 + b * w1 + ty | 0; } - else { + else + { // xy positions[index] = a * w1 + c * h1 + tx; positions[index+1] = d * h1 + b * w1 + ty; @@ -338,11 +351,13 @@ * * @param sprite {TilingSprite} the tilingSprite to render */ -WebGLSpriteBatch.prototype.renderTilingSprite = function (tilingSprite) { +WebGLSpriteBatch.prototype.renderTilingSprite = function (tilingSprite) +{ var texture = tilingSprite.tilingTexture; // check texture.. - if (this.currentBatchSize >= this.size) { + if (this.currentBatchSize >= this.size) + { //return; this.flush(); this.currentBaseTexture = texture.baseTexture; @@ -351,7 +366,8 @@ // set the textures uvs temporarily // TODO create a separate texture so that we can tile part of a texture - if (!tilingSprite._uvs) { + if (!tilingSprite._uvs) + { tilingSprite._uvs = new TextureUvs(); } @@ -454,16 +470,19 @@ * Renders the content and empties the current batch. * */ -WebGLSpriteBatch.prototype.flush = function () { +WebGLSpriteBatch.prototype.flush = function () +{ // If the batch is length 0 then return as there is nothing to draw - if (this.currentBatchSize === 0) { + if (this.currentBatchSize === 0) + { return; } var gl = this.renderer.gl; var shader; - if (this.dirty) { + if (this.dirty) + { this.dirty = false; // bind the main texture gl.activeTexture(gl.TEXTURE0); @@ -482,10 +501,12 @@ } // upload the verts to the buffer - if (this.currentBatchSize > ( this.size * 0.5 ) ) { + if (this.currentBatchSize > ( this.size * 0.5 ) ) + { gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); } - else { + else + { var view = this.positions.subarray(0, this.currentBatchSize * this.vertByteSize); gl.bufferSubData(gl.ARRAY_BUFFER, 0, view); } @@ -502,7 +523,8 @@ var shaderSwap = false; var sprite; - for (var i = 0, j = this.currentBatchSize; i < j; i++) { + for (var i = 0, j = this.currentBatchSize; i < j; i++) + { sprite = this.sprites[i]; @@ -513,24 +535,28 @@ blendSwap = currentBlendMode !== nextBlendMode; shaderSwap = currentShader !== nextShader; // should I use uuidS??? - if (currentBaseTexture !== nextTexture || blendSwap || shaderSwap) { + if (currentBaseTexture !== nextTexture || blendSwap || shaderSwap) + { this.renderBatch(currentBaseTexture, batchSize, start); start = i; batchSize = 0; currentBaseTexture = nextTexture; - if (blendSwap) { + if (blendSwap) + { currentBlendMode = nextBlendMode; this.renderer.blendModeManager.setBlendMode( currentBlendMode ); } - if (shaderSwap) { + if (shaderSwap) + { currentShader = nextShader; shader = currentShader.shaders ? currentShader.shaders[gl.id] : currentShader; - if (!shader) { + if (!shader) + { shader = new Shader(gl, null, currentShader.fragmentSrc, currentShader.uniforms); currentShader.shaders[gl.id] = shader; } @@ -538,7 +564,8 @@ // set shader function??? this.renderer.shaderManager.setShader(shader); - if (shader.dirty) { + if (shader.dirty) + { shader.syncUniforms(); } @@ -569,17 +596,21 @@ * @param size {number} * @param startIndex {number} */ -WebGLSpriteBatch.prototype.renderBatch = function (texture, size, startIndex) { - if (size === 0) { +WebGLSpriteBatch.prototype.renderBatch = function (texture, size, startIndex) +{ + if (size === 0) + { return; } var gl = this.renderer.gl; - if (!texture._glTextures[gl.id]) { + if (!texture._glTextures[gl.id]) + { this.renderer.updateTexture(texture); } - else { + else + { // bind the current texture gl.bindTexture(gl.TEXTURE_2D, texture._glTextures[gl.id]); } @@ -594,7 +625,8 @@ /** * */ -WebGLSpriteBatch.prototype.stop = function () { +WebGLSpriteBatch.prototype.stop = function () +{ this.flush(); this.dirty = true; }; @@ -602,7 +634,8 @@ /** * */ -WebGLSpriteBatch.prototype.start = function () { +WebGLSpriteBatch.prototype.start = function () +{ this.dirty = true; }; @@ -610,7 +643,8 @@ * Destroys the SpriteBatch. * */ -WebGLSpriteBatch.prototype.destroy = function () { +WebGLSpriteBatch.prototype.destroy = function () +{ this.renderer.gl.deleteBuffer(this.vertexBuffer); this.renderer.gl.deleteBuffer(this.indexBuffer); diff --git a/src/core/textures/BaseTexture.js b/src/core/textures/BaseTexture.js index 2bf77d4..513d358 100644 --- a/src/core/textures/BaseTexture.js +++ b/src/core/textures/BaseTexture.js @@ -10,7 +10,8 @@ * @param source {Image|Canvas} the source object of the texture. * @param [scaleMode=scaleModes.DEFAULT] {number} See {@link scaleModes} for possible values */ -function BaseTexture(source, scaleMode) { +function BaseTexture(source, scaleMode) +{ this.uuid = utils.uuid(); /** @@ -123,7 +124,8 @@ this._needsUpdate = false; // if no source passed don't try to load - if (source) { + if (source) + { this.loadSource(source); } @@ -149,13 +151,16 @@ Object.defineProperties(BaseTexture.prototype, { needsUpdate: { - get: function () { + get: function () + { return this._needsUpdate; }, - set: function (val) { + set: function (val) + { this._needsUpdate = val; - if (val) { + if (val) + { this.emit('update', this); } } @@ -171,9 +176,11 @@ * * The logic state after calling `loadSource` directly or indirectly (eg. `fromImage`, `new BaseTexture`) is: * - * if (texture.hasLoaded) { + * if (texture.hasLoaded) + { * // texture ready for use - * } else if (texture.isLoading) { + * } else if (texture.isLoading) + { * // listen to 'loaded' and/or 'error' events on texture * } else { * // not loading, not going to load UNLESS the source is reloaded @@ -183,12 +190,14 @@ * @protected * @param source {Image|Canvas} the source object of the texture. */ -BaseTexture.prototype.loadSource = function (source) { +BaseTexture.prototype.loadSource = function (source) +{ var wasLoading = this.isLoading; this.hasLoaded = false; this.isLoading = false; - if (wasLoading && this.source) { + if (wasLoading && this.source) + { this.source.onload = null; this.source.onerror = null; } @@ -196,20 +205,24 @@ this.source = source; // Apply source if loaded. Otherwise setup appropriate loading monitors. - if ((this.source.complete || this.source.getContext) && this.source.width && this.source.height) { + if ((this.source.complete || this.source.getContext) && this.source.width && this.source.height) + { this._sourceLoaded(); } - else if(!source.getContext) { + else if(!source.getContext) + { // Image fail / not ready this.isLoading = true; var scope = this; - source.onload = function () { + source.onload = function () + { source.onload = null; source.onerror = null; - if(!scope.isLoading) { + if(!scope.isLoading) + { return; } @@ -219,11 +232,13 @@ scope.emit('loaded', scope); }; - source.onerror = function () { + source.onerror = function () + { source.onload = null; source.onerror = null; - if(!scope.isLoading) { + if(!scope.isLoading) + { return; } @@ -234,24 +249,29 @@ // Per http://www.w3.org/TR/html5/embedded-content-0.html#the-img-element // "The value of `complete` can thus change while a script is executing." // So complete needs to be re-checked after the callbacks have been added.. - if (source.complete) { + if (source.complete) + { this.isLoading = false; // ..and if we're complete now, no need for callbacks source.onload = null; source.onerror = null; - if (source.width && source.height) { + if (source.width && source.height) + { this._sourceLoaded(); // If any previous subscribers possible - if (wasLoading) { + if (wasLoading) + { this.emit('loaded', this); } } - else { + else + { // If any previous subscribers possible - if (wasLoading) { + if (wasLoading) + { this.emit('error', this); } } @@ -265,7 +285,8 @@ * * @private */ -BaseTexture.prototype._sourceLoaded = function () { +BaseTexture.prototype._sourceLoaded = function () +{ this.hasLoaded = true; this.width = this.source.naturalWidth || this.source.width; @@ -278,16 +299,20 @@ * Destroys this base texture * */ -BaseTexture.prototype.destroy = function () { - if (this.imageUrl) { +BaseTexture.prototype.destroy = function () +{ + if (this.imageUrl) + { delete utils.BaseTextureCache[this.imageUrl]; delete utils.TextureCache[this.imageUrl]; this.imageUrl = null; - if (!navigator.isCocoonJS) { + if (!navigator.isCocoonJS) + { this.source.src = ''; } } - else if (this.source && this.source._pixiId) { + else if (this.source && this.source._pixiId) + { delete utils.BaseTextureCache[this.source._pixiId]; } this.source = null; @@ -301,7 +326,8 @@ * memory again. * */ -BaseTexture.prototype.dispose = function () { +BaseTexture.prototype.dispose = function () +{ this.emit('dispose', this); }; @@ -311,7 +337,8 @@ * * @param newSrc {string} the path of the image */ -BaseTexture.prototype.updateSourceImage = function (newSrc) { +BaseTexture.prototype.updateSourceImage = function (newSrc) +{ this.source.src = newSrc; this.loadSource(this.source); }; @@ -326,18 +353,22 @@ * @param [scaleMode=scaleModes.DEFAULT] {number} See {@link scaleModes} for possible values * @return BaseTexture */ -BaseTexture.fromImage = function (imageUrl, crossorigin, scaleMode) { +BaseTexture.fromImage = function (imageUrl, crossorigin, scaleMode) +{ var baseTexture = utils.BaseTextureCache[imageUrl]; - if (crossorigin === undefined && imageUrl.indexOf('data:') !== 0) { + if (crossorigin === undefined && imageUrl.indexOf('data:') !== 0) + { crossorigin = true; } - if (!baseTexture) { + if (!baseTexture) + { // new Image() breaks tex loading in some versions of Chrome. // See https://code.google.com/p/chromium/issues/detail?id=238071 var image = new Image();//document.createElement('img'); - if (crossorigin) { + if (crossorigin) + { image.crossOrigin = ''; } @@ -347,7 +378,8 @@ utils.BaseTextureCache[imageUrl] = baseTexture; // if there is an @2x at the end of the url we are going to assume its a highres image - if ( imageUrl.indexOf(CONST.RETINA_PREFIX + '.') !== -1) { + if ( imageUrl.indexOf(CONST.RETINA_PREFIX + '.') !== -1) + { baseTexture.resolution = 2; } } @@ -363,14 +395,17 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return BaseTexture */ -BaseTexture.fromCanvas = function (canvas, scaleMode) { - if (!canvas._pixiId) { +BaseTexture.fromCanvas = function (canvas, scaleMode) +{ + if (!canvas._pixiId) + { canvas._pixiId = 'canvas_' + utils.uuid(); } var baseTexture = utils.BaseTextureCache[canvas._pixiId]; - if (!baseTexture) { + if (!baseTexture) + { baseTexture = new BaseTexture(canvas, scaleMode); utils.BaseTextureCache[canvas._pixiId] = baseTexture; } diff --git a/src/core/textures/RenderTexture.js b/src/core/textures/RenderTexture.js index 6dad20f..53ae796 100644 --- a/src/core/textures/RenderTexture.js +++ b/src/core/textures/RenderTexture.js @@ -46,8 +46,10 @@ * @param [scaleMode] {number} See {@link scaleModes} for possible values * @param [resolution=1] {number} The resolution of the texture being generated */ -function RenderTexture(renderer, width, height, scaleMode, resolution) { - if (!renderer) { +function RenderTexture(renderer, width, height, scaleMode, resolution) +{ + if (!renderer) + { throw new Error('Unable to create RenderTexture, you must pass a renderer into the constructor.'); } @@ -133,7 +135,8 @@ */ this.renderer = renderer; - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { var gl = this.renderer.gl; this.textureBuffer = new FilterTexture(gl, this.width * this.resolution, this.height * this.resolution, this.baseTexture.scaleMode); @@ -142,7 +145,8 @@ this.render = this.renderWebGL; this.projection = new math.Point(this.width*0.5, -this.height*0.5); } - else { + else + { this.render = this.renderCanvas; this.textureBuffer = new CanvasBuffer(this.width* this.resolution, this.height* this.resolution); this.baseTexture.source = this.textureBuffer.canvas; @@ -167,8 +171,10 @@ * @param height {number} The height to resize to. * @param updateBase {boolean} Should the baseTexture.width and height values be resized as well? */ -RenderTexture.prototype.resize = function (width, height, updateBase) { - if (width === this.width && height === this.height) { +RenderTexture.prototype.resize = function (width, height, updateBase) +{ + if (width === this.width && height === this.height) + { return; } @@ -177,17 +183,20 @@ this.width = this.frame.width = this.crop.width = width; this.height = this.frame.height = this.crop.height = height; - if (updateBase) { + if (updateBase) + { this.baseTexture.width = this.width; this.baseTexture.height = this.height; } - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { this.projection.x = this.width / 2; this.projection.y = -this.height / 2; } - if (!this.valid) { + if (!this.valid) + { return; } @@ -198,12 +207,15 @@ * Clears the RenderTexture. * */ -RenderTexture.prototype.clear = function () { - if (!this.valid) { +RenderTexture.prototype.clear = function () +{ + if (!this.valid) + { return; } - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { this.renderer.gl.bindFramebuffer(this.renderer.gl.FRAMEBUFFER, this.textureBuffer.frameBuffer); } @@ -220,19 +232,23 @@ * @param [restoreWorldTransform=true] {boolean} If true the displayObject's worldTransform/worldAlpha and all children * transformations will be restored. Not restoring this information will be a little faster. */ -RenderTexture.prototype.renderWebGL = function (displayObject, matrix, clear, restoreWorldTransform) { - if (!this.valid) { +RenderTexture.prototype.renderWebGL = function (displayObject, matrix, clear, restoreWorldTransform) +{ + if (!this.valid) + { return; } - if (typeof restoreWorldTransform === 'undefined') { + if (typeof restoreWorldTransform === 'undefined') + { restoreWorldTransform = true; } var tempAlpha, tempTransform; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { tempAlpha = displayObject.worldAlpha; tempTransform = displayObject.worldTransform.toArray(); } @@ -245,7 +261,8 @@ wt.identity(); wt.translate(0, this.projection.y * 2); - if (matrix) { + if (matrix) + { wt.append(matrix); } @@ -258,7 +275,8 @@ var children = displayObject.children; var i, j; - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } @@ -269,7 +287,8 @@ gl.bindFramebuffer(gl.FRAMEBUFFER, this.textureBuffer.frameBuffer ); - if (clear) { + if (clear) + { this.textureBuffer.clear(); } @@ -279,11 +298,13 @@ this.renderer.spriteBatch.dirty = true; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { displayObject.worldAlpha = tempAlpha; displayObject.worldTransform.fromArray(tempTransform); - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } } @@ -300,26 +321,31 @@ * @param [restoreWorldTransform=true] {boolean} If true the displayObject's worldTransform/worldAlpha and all children * transformations will be restored. Not restoring this information will be a little faster. */ -RenderTexture.prototype.renderCanvas = function (displayObject, matrix, clear, restoreWorldTransform) { - if (!this.valid) { +RenderTexture.prototype.renderCanvas = function (displayObject, matrix, clear, restoreWorldTransform) +{ + if (!this.valid) + { return; } - if (typeof restoreWorldTransform === 'undefined') { + if (typeof restoreWorldTransform === 'undefined') + { restoreWorldTransform = true; } var tempAlpha, tempTransform; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { tempAlpha = displayObject.worldAlpha; tempTransform = displayObject.worldTransform.toArray(); } var wt = displayObject.worldTransform; wt.identity(); - if (matrix) { + if (matrix) + { wt.append(matrix); } @@ -330,11 +356,13 @@ var children = displayObject.children; var i, j; - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } - if (clear) { + if (clear) + { this.textureBuffer.clear(); } @@ -348,11 +376,13 @@ this.renderer.resolution = realResolution; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { displayObject.worldAlpha = tempAlpha; displayObject.worldTransform.fromArray(tempTransform); - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } } @@ -363,7 +393,8 @@ * * @return {Image} */ -RenderTexture.prototype.getImage = function () { +RenderTexture.prototype.getImage = function () +{ var image = new Image(); image.src = this.getBase64(); return image; @@ -374,7 +405,8 @@ * * @return {string} A base64 encoded string of the texture. */ -RenderTexture.prototype.getBase64 = function () { +RenderTexture.prototype.getBase64 = function () +{ return this.getCanvas().toDataURL(); }; @@ -383,8 +415,10 @@ * * @return {HTMLCanvasElement} A Canvas element with the texture rendered on. */ -RenderTexture.prototype.getCanvas = function () { - if (this.renderer.type === CONST.WEBGL_RENDERER) { +RenderTexture.prototype.getCanvas = function () +{ + if (this.renderer.type === CONST.WEBGL_RENDERER) + { var gl = this.renderer.gl; var width = this.textureBuffer.width; var height = this.textureBuffer.height; @@ -403,7 +437,8 @@ return tempCanvas.canvas; } - else { + else + { return this.textureBuffer.canvas; } }; diff --git a/src/core/textures/Texture.js b/src/core/textures/Texture.js index 3c65909..e97f0aa 100644 --- a/src/core/textures/Texture.js +++ b/src/core/textures/Texture.js @@ -17,7 +17,8 @@ * @param [crop] {Rectangle} The area of original texture * @param [trim] {Rectangle} Trimmed texture rectangle */ -function Texture(baseTexture, frame, crop, trim) { +function Texture(baseTexture, frame, crop, trim) +{ /** * Does this Texture have any frame data assigned to it? * @@ -25,12 +26,14 @@ */ this.noFrame = false; - if (!frame) { + if (!frame) + { this.noFrame = true; frame = new math.Rectangle(0, 0, 1, 1); } - if (baseTexture instanceof Texture) { + if (baseTexture instanceof Texture) + { baseTexture = baseTexture.baseTexture; } @@ -100,13 +103,16 @@ */ this.crop = crop || new math.Rectangle(0, 0, 1, 1); - if (baseTexture.hasLoaded) { - if (this.noFrame) { + if (baseTexture.hasLoaded) + { + if (this.noFrame) + { frame = new math.Rectangle(0, 0, baseTexture.width, baseTexture.height); } this.frame = frame; } - else { + else + { baseTexture.addEventListener('loaded', this.onBaseTextureLoaded.bind(this)); } } @@ -118,19 +124,23 @@ Object.defineProperties(Texture.prototype, { needsUpdate: { - get: function () { + get: function () + { return this.baseTexture.needsUpdate; }, - set: function (val) { + set: function (val) + { this.baseTexture.needsUpdate = val; } }, frame: { - get: function () { + get: function () + { return this._frame; }, - set: function (frame) { + set: function (frame) + { this._frame = frame; this.noFrame = false; @@ -143,20 +153,23 @@ 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 (!this.trim && (frame.x + frame.width > this.baseTexture.width || frame.y + frame.height > this.baseTexture.height)) + { throw new Error('Texture Error: frame does not fit inside the base Texture dimensions ' + this); } this.valid = frame && frame.width && frame.height && this.baseTexture.source && this.baseTexture.hasLoaded; - if (this.trim) { + 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) { + if (this.valid) + { this._updateUvs(); } } @@ -168,11 +181,13 @@ * * @private */ -Texture.prototype.onBaseTextureLoaded = function () { +Texture.prototype.onBaseTextureLoaded = function () +{ var baseTexture = this.baseTexture; baseTexture.removeEventListener('loaded', this.onLoaded); - if (this.noFrame) { + if (this.noFrame) + { this.frame = new math.Rectangle(0, 0, baseTexture.width, baseTexture.height); } @@ -184,8 +199,10 @@ * * @param destroyBase {boolean} Whether to destroy the base texture as well */ -Texture.prototype.destroy = function (destroyBase) { - if (destroyBase) { +Texture.prototype.destroy = function (destroyBase) +{ + if (destroyBase) + { this.baseTexture.destroy(); } @@ -197,8 +214,10 @@ * * @private */ -Texture.prototype._updateUvs = function () { - if (!this._uvs) { +Texture.prototype._updateUvs = function () +{ + if (!this._uvs) + { this._uvs = new TextureUvs(); } @@ -229,10 +248,12 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return Texture */ -Texture.fromImage = function (imageUrl, crossorigin, scaleMode) { +Texture.fromImage = function (imageUrl, crossorigin, scaleMode) +{ var texture = utils.TextureCache[imageUrl]; - if (!texture) { + if (!texture) + { texture = new Texture(BaseTexture.fromImage(imageUrl, crossorigin, scaleMode)); utils.TextureCache[imageUrl] = texture; } @@ -248,9 +269,11 @@ * @param frameId {string} The frame id of the texture * @return Texture */ -Texture.fromFrame = function (frameId) { +Texture.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache '); } return texture; @@ -264,7 +287,8 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return {Texture} */ -Texture.fromCanvas = function (canvas, scaleMode) { +Texture.fromCanvas = function (canvas, scaleMode) +{ return new Texture(BaseTexture.fromCanvas(canvas, scaleMode)); }; @@ -276,7 +300,8 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return {Texture} A Texture */ -Texture.fromVideo = function (video, scaleMode) { +Texture.fromVideo = function (video, scaleMode) +{ return new Texture(VideoBaseTexture.baseTextureFromVideo(video, scaleMode)); }; @@ -287,7 +312,8 @@ * @param texture {Texture} The Texture to add to the cache. * @param id {string} The id that the texture will be stored against. */ -Texture.addTextureToCache = function (texture, id) { +Texture.addTextureToCache = function (texture, id) +{ utils.TextureCache[id] = texture; }; @@ -298,7 +324,8 @@ * @param id {string} The id of the texture to be removed * @return {Texture} The texture that was removed */ -Texture.removeTextureFromCache = function (id) { +Texture.removeTextureFromCache = function (id) +{ var texture = utils.TextureCache[id]; delete utils.TextureCache[id]; diff --git a/src/core/textures/TextureUvs.js b/src/core/textures/TextureUvs.js index b9bbb58..5424d52 100644 --- a/src/core/textures/TextureUvs.js +++ b/src/core/textures/TextureUvs.js @@ -1,4 +1,5 @@ -function TextureUvs() { +function TextureUvs() +{ this.x0 = 0; this.y0 = 0; diff --git a/src/core/textures/VideoBaseTexture.js b/src/core/textures/VideoBaseTexture.js index e3e0c5a..1a826a9 100644 --- a/src/core/textures/VideoBaseTexture.js +++ b/src/core/textures/VideoBaseTexture.js @@ -12,15 +12,18 @@ * @param source {HTMLVideoElement} * @param [scaleMode] {number} See {@link scaleModes} for possible values */ -function VideoBaseTexture(source, scaleMode) { - if (!source){ +function VideoBaseTexture(source, scaleMode) +{ + if (!source) + { throw new Error('No video source element specified.'); } // hook in here to check if video is already available. // BaseTexture looks for a source.complete boolean, plus width & height. - if ((source.readyState === source.HAVE_ENOUGH_DATA || source.readyState === source.HAVE_FUTURE_DATA) && source.width && source.height) { + if ((source.readyState === source.HAVE_ENOUGH_DATA || source.readyState === source.HAVE_FUTURE_DATA) && source.width && source.height) + { source.complete = true; } @@ -31,7 +34,8 @@ this._boundOnUpdate = this._onUpdate.bind(this); this._boundOnCanPlay = this._onCanPlay.bind(this); - if (!source.complete) { + if (!source.complete) + { source.addEventListener('canplay', this._boundOnCanPlay); source.addEventListener('canplaythrough', this._boundOnCanPlay); @@ -47,28 +51,35 @@ VideoBaseTexture.prototype.constructor = VideoBaseTexture; module.exports = VideoBaseTexture; -VideoBaseTexture.prototype._onUpdate = function () { - if (this.autoUpdate) { +VideoBaseTexture.prototype._onUpdate = function () +{ + if (this.autoUpdate) + { window.requestAnimationFrame(this._boundOnUpdate); this.needsUpdate = true; } }; -VideoBaseTexture.prototype._onPlayStart = function () { - if (!this.autoUpdate) { +VideoBaseTexture.prototype._onPlayStart = function () +{ + if (!this.autoUpdate) + { window.requestAnimationFrame(this._boundOnUpdate); this.autoUpdate = true; } }; -VideoBaseTexture.prototype._onPlayStop = function () { +VideoBaseTexture.prototype._onPlayStop = function () +{ this.autoUpdate = false; }; -VideoBaseTexture.prototype._onCanPlay = function () { +VideoBaseTexture.prototype._onCanPlay = function () +{ this.hasLoaded = true; - if (this.source) { + if (this.source) + { this.source.removeEventListener('canplay', this._boundOnCanPlay); this.source.removeEventListener('canplaythrough', this._boundOnCanPlay); @@ -78,15 +89,18 @@ this.source.play(); // prevent multiple loaded dispatches.. - if(!this.__loaded){ + if(!this.__loaded) + { this.__loaded = true; this.emit('loaded', this); } } }; -VideoBaseTexture.prototype.destroy = function () { - if (this.source && this.source._pixiId) { +VideoBaseTexture.prototype.destroy = function () +{ + if (this.source && this.source._pixiId) + { utils.BaseTextureCache[ this.source._pixiId ] = null; delete utils.BaseTextureCache[ this.source._pixiId ]; @@ -105,14 +119,17 @@ * @param scaleMode {number} See {@link scaleModes} for possible values * @return {VideoBaseTexture} */ -VideoBaseTexture.fromVideo = function (video, scaleMode) { - if (!video._pixiId) { +VideoBaseTexture.fromVideo = function (video, scaleMode) +{ + if (!video._pixiId) + { video._pixiId = 'video_' + utils.uuid(); } var baseTexture = utils.BaseTextureCache[video._pixiId]; - if (!baseTexture) { + if (!baseTexture) + { baseTexture = new VideoBaseTexture(video, scaleMode); utils.BaseTextureCache[ video._pixiId ] = baseTexture; } @@ -147,17 +164,21 @@ * @param scaleMode {number} See {@link scaleModes} for possible values * @return {VideoBaseTexture} */ -VideoBaseTexture.fromUrl = function (videoSrc, scaleMode) { +VideoBaseTexture.fromUrl = function (videoSrc, scaleMode) +{ var video = document.createElement('video'); // array of objects or strings - if (Array.isArray(videoSrc)) { - for (var i = 0; i < videoSrc.length; ++i) { + if (Array.isArray(videoSrc)) + { + for (var i = 0; i < videoSrc.length; ++i) + { video.appendChild(createSource(videoSrc.src || videoSrc, videoSrc.mime)); } } // single object or string - else { + else + { video.appendChild(createSource(videoSrc.src || videoSrc, videoSrc.mime)); } @@ -169,8 +190,10 @@ VideoBaseTexture.fromUrls = VideoBaseTexture.fromUrl; -function createSource(path, type) { - if (!type) { +function createSource(path, type) +{ + if (!type) + { type = 'video/' + path.substr(path.lastIndexOf('.') + 1); } diff --git a/src/core/utils/EventData.js b/src/core/utils/EventData.js index 5d55a22..8cdf701 100644 --- a/src/core/utils/EventData.js +++ b/src/core/utils/EventData.js @@ -7,7 +7,8 @@ * @param name {string} The string name of the event that was triggered * @param data {object} Arbitrary event data to pass along */ -function EventData(target, name, data) { +function EventData(target, name, data) +{ // for duck typing in the ".on()" function this.__isEventObject = true; @@ -71,7 +72,8 @@ * Stops the propagation of events up the scene graph (prevents bubbling). * */ -EventData.prototype.stopPropagation = function stopPropagation() { +EventData.prototype.stopPropagation = function stopPropagation() +{ this.stopped = true; }; @@ -79,6 +81,7 @@ * Stops the propagation of events to sibling listeners (no longer calls any listeners). * */ -EventData.prototype.stopImmediatePropagation = function stopImmediatePropagation() { +EventData.prototype.stopImmediatePropagation = function stopImmediatePropagation() +{ this.stoppedImmediate = true; }; diff --git a/src/core/utils/EventTarget.js b/src/core/utils/EventTarget.js index 7ae8820..671a151 100644 --- a/src/core/utils/EventTarget.js +++ b/src/core/utils/EventTarget.js @@ -13,14 +13,16 @@ * var em = new MyEmitter(); * em.emit('eventName', 'some data', 'some more data', {}, null, ...); */ -function eventTarget(obj) { +function eventTarget(obj) +{ /** * Return a list of assigned event listeners. * * @param eventName {string} The events that should be listed. * @return {Array} An array of listener functions */ - obj.listeners = function listeners(eventName) { + obj.listeners = function listeners(eventName) + { this._listeners = this._listeners || {}; return this._listeners[eventName] ? this._listeners[eventName].slice() : []; @@ -33,22 +35,26 @@ * @param eventName {string} The name of the event. * @return {boolean} Indication if we've emitted an event. */ - obj.emit = obj.dispatchEvent = function emit(eventName, data) { + obj.emit = obj.dispatchEvent = function emit(eventName, data) + { this._listeners = this._listeners || {}; // fast return when there are no listeners - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return; } //backwards compat with old method ".emit({ type: 'something' })" - if (typeof eventName === 'object') { + if (typeof eventName === 'object') + { data = eventName; eventName = eventName.type; } //ensure we are using a real pixi event - if (!data || data.__isEventObject !== true) { + if (!data || data.__isEventObject !== true) + { data = new EventData(this, eventName, data); } @@ -58,23 +64,27 @@ fn = listeners[0], i; - for (i = 0; i < length; fn = listeners[++i]) { + for (i = 0; i < length; fn = listeners[++i]) + { //call the event listener fn.call(this, data); //if "stopImmediatePropagation" is called, stop calling sibling events - if (data.stoppedImmediate) { + if (data.stoppedImmediate) + { return this; } } //if "stopPropagation" is called then don't bubble the event - if (data.stopped) { + if (data.stopped) + { return this; } //bubble this event up the scene graph - if (this.parent && this.parent.emit) { + if (this.parent && this.parent.emit) + { this.parent.emit.call(this.parent, eventName, data); } @@ -88,7 +98,8 @@ * @param eventName {string} Name of the event. * @param callback {Functon} fn Callback function. */ - obj.on = obj.addEventListener = function on(eventName, fn) { + obj.on = obj.addEventListener = function on(eventName, fn) + { this._listeners = this._listeners || {}; (this._listeners[eventName] = this._listeners[eventName] || []) @@ -103,11 +114,13 @@ * @param eventName {string} Name of the event. * @param callback {Function} Callback function. */ - obj.once = function once(eventName, fn) { + obj.once = function once(eventName, fn) + { this._listeners = this._listeners || {}; var self = this; - function onceHandlerWrapper() { + function onceHandlerWrapper() + { fn.apply(self.off(eventName, onceHandlerWrapper), arguments); } onceHandlerWrapper._originalHandler = fn; @@ -122,23 +135,28 @@ * @param eventName {string} The event we want to remove. * @param callback {Function} The listener that we need to find. */ - obj.off = obj.removeEventListener = function off(eventName, fn) { + obj.off = obj.removeEventListener = function off(eventName, fn) + { this._listeners = this._listeners || {}; - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return this; } var list = this._listeners[eventName], i = fn ? list.length : 0; - while(i-- > 0) { - if (list[i] === fn || list[i]._originalHandler === fn) { + while(i-- > 0) + { + if (list[i] === fn || list[i]._originalHandler === fn) + { list.splice(i, 1); } } - if (list.length === 0) { + if (list.length === 0) + { delete this._listeners[eventName]; } @@ -150,10 +168,12 @@ * * @param eventName {string} The event you want to remove all listeners for. */ - obj.removeAllListeners = function removeAllListeners(eventName) { + obj.removeAllListeners = function removeAllListeners(eventName) + { this._listeners = this._listeners || {}; - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return this; } @@ -169,7 +189,8 @@ * * @param object {object} The obj to mix into */ - mixin: function mixin(obj) { + mixin: function mixin(obj) + { eventTarget(obj); } }; diff --git a/src/core/display/DisplayObject.js b/src/core/display/DisplayObject.js index 66ebc3c..20e778c 100644 --- a/src/core/display/DisplayObject.js +++ b/src/core/display/DisplayObject.js @@ -7,7 +7,8 @@ * @class * @namespace PIXI */ -function DisplayObject() { +function DisplayObject() +{ /** * The coordinate of the object relative to the local coordinates of the parent. * @@ -152,10 +153,12 @@ * @memberof DisplayObject# */ x: { - get: function () { + get: function () + { return this.position.x; }, - set: function (value) { + set: function (value) + { this.position.x = value; } }, @@ -167,10 +170,12 @@ * @memberof DisplayObject# */ y: { - get: function () { + get: function () + { return this.position.y; }, - set: function (value) { + set: function (value) + { this.position.y = value; } }, @@ -183,11 +188,13 @@ * @readonly */ worldVisible: { - get: function () { + get: function () + { var item = this; do { - if (!item.visible) { + if (!item.visible) + { return false; } @@ -207,17 +214,21 @@ * @memberof DisplayObject# */ mask: { - get: function () { + get: function () + { return this._mask; }, - set: function (value) { - if (this._mask) { + set: function (value) + { + if (this._mask) + { this._mask.isMask = false; } this._mask = value; - if (this._mask) { + if (this._mask) + { this._mask.isMask = true; } } @@ -232,18 +243,23 @@ * @memberof DisplayObject# */ filters: { - get: function () { + get: function () + { return this._filters; }, - set: function (value) { - if (value) { + set: function (value) + { + if (value) + { // now put all the passes in one place.. var passes = []; - for (var i = 0; i < value.length; i++) { + for (var i = 0; i < value.length; i++) + { var filterPasses = value[i].passes; - for (var j = 0; j < filterPasses.length; j++) { + for (var j = 0; j < filterPasses.length; j++) + { passes.push(filterPasses[j]); } } @@ -264,8 +280,9 @@ * * @private */ -DisplayObject.prototype.updateTransform = function () { - +DisplayObject.prototype.updateTransform = function () +{ + // create some matrix refs for easy access var pt = this.parent.worldTransform; var wt = this.worldTransform; @@ -274,9 +291,11 @@ var a, b, c, d, tx, ty; // so if rotation is between 0 then we can simplify the multiplication process.. - if (this.rotation % math.PI_2) { + if (this.rotation % math.PI_2) + { // 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) { + if (this.rotation !== this.rotationCache) + { this.rotationCache = this.rotation; this._sr = Math.sin(this.rotation); this._cr = Math.cos(this.rotation); @@ -291,7 +310,8 @@ ty = this.position.y; // check for pivot.. not often used so geared towards that fact! - if (this.pivot.x || this.pivot.y) { + 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; } @@ -304,7 +324,8 @@ wt.tx = tx * pt.a + ty * pt.c + pt.tx; wt.ty = tx * pt.b + ty * pt.d + pt.ty; } - else { + else + { // lets do the fast version as we know there is no rotation.. a = this.scale.x; d = this.scale.y; @@ -333,7 +354,8 @@ * @param matrix {Matrix} * @return {Rectangle} the rectangular bounding area */ -DisplayObject.prototype.getBounds = function (/* matrix */) { +DisplayObject.prototype.getBounds = function (/* matrix */) +{ return math.Rectangle.EMPTY; }; @@ -342,7 +364,8 @@ * * @return {Rectangle} the rectangular bounding area */ -DisplayObject.prototype.getLocalBounds = function () { +DisplayObject.prototype.getLocalBounds = function () +{ return this.getBounds(math.Matrix.IDENTITY); }; @@ -352,7 +375,8 @@ * @param position {Point} The world origin to calculate from * @return {Point} A point object representing the position of this object */ -DisplayObject.prototype.toGlobal = function (position) { +DisplayObject.prototype.toGlobal = function (position) +{ // don't need to u[date the lot this.displayObjectUpdateTransform(); return this.worldTransform.apply(position); @@ -365,8 +389,10 @@ * @param [from] {DisplayObject} The DisplayObject to calculate the global position from * @return {Point} A point object representing the position of this object */ -DisplayObject.prototype.toLocal = function (position, from) { - if (from) { +DisplayObject.prototype.toLocal = function (position, from) +{ + if (from) + { position = from.toGlobal(position); } @@ -381,7 +407,8 @@ * @param renderer {WebGLRenderer} The renderer * @private */ -DisplayObject.prototype.renderWebGL = function (/* renderer */) { +DisplayObject.prototype.renderWebGL = function (/* renderer */) +{ // OVERWRITE; }; @@ -391,6 +418,7 @@ * @param renderer {CanvasRenderer} The renderer * @private */ -DisplayObject.prototype.renderCanvas = function (/* renderer */) { +DisplayObject.prototype.renderCanvas = function (/* renderer */) +{ // OVERWRITE; }; diff --git a/src/core/display/DisplayObjectContainer.js b/src/core/display/DisplayObjectContainer.js index 689f40b..4625ee8 100644 --- a/src/core/display/DisplayObjectContainer.js +++ b/src/core/display/DisplayObjectContainer.js @@ -12,7 +12,8 @@ * @extends DisplayObject * @namespace PIXI */ -function DisplayObjectContainer() { +function DisplayObjectContainer() +{ DisplayObject.call(this); /** @@ -47,17 +48,21 @@ * @memberof DisplayObjectContainer# */ width: { - get: function () { + get: function () + { return this.scale.x * this.getLocalBounds().width; }, - set: function (value) { + set: function (value) + { var width = this.getLocalBounds().width; - if(width !== 0) { + if(width !== 0) + { this.scale.x = value / width; } - else { + else + { this.scale.x = 1; } @@ -73,17 +78,21 @@ * @memberof DisplayObjectContainer# */ height: { - get: function () { + get: function () + { return this.scale.y * this.getLocalBounds().height; }, - set: function (value) { + set: function (value) + { var height = this.getLocalBounds().height; - if (height !== 0) { + if (height !== 0) + { this.scale.y = value / height ; } - else { + else + { this.scale.y = 1; } @@ -100,18 +109,23 @@ * @memberof DisplayObject# */ cacheAsBitmap: { - get: function () { + get: function () + { return this._cacheAsBitmap; }, - set: function (value) { - if (this._cacheAsBitmap === value) { + set: function (value) + { + if (this._cacheAsBitmap === value) + { return; } - if (value) { + if (value) + { this._generateCachedSprite(); } - else { + else + { this._destroyCachedSprite(); } @@ -126,7 +140,8 @@ * @param child {DisplayObject} The DisplayObject to add to the container * @return {DisplayObject} The child that was added. */ -DisplayObjectContainer.prototype.addChild = function (child) { +DisplayObjectContainer.prototype.addChild = function (child) +{ return this.addChildAt(child, this.children.length); }; @@ -137,14 +152,18 @@ * @param index {Number} The index to place the child in * @return {DisplayObject} The child that was added. */ -DisplayObjectContainer.prototype.addChildAt = function (child, index) { +DisplayObjectContainer.prototype.addChildAt = function (child, index) +{ // prevent adding self as child - if (child === this) { + if (child === this) + { return; } - if (index >= 0 && index <= this.children.length) { - if (child.parent) { + if (index >= 0 && index <= this.children.length) + { + if (child.parent) + { child.parent.removeChild(child); } @@ -154,7 +173,8 @@ return child; } - else { + else + { throw new Error(child + 'addChildAt: The index '+ index +' supplied is out of bounds ' + this.children.length); } }; @@ -165,15 +185,18 @@ * @param child {DisplayObject} * @param child2 {DisplayObject} */ -DisplayObjectContainer.prototype.swapChildren = function (child, child2) { - if (child === child2) { +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) { + if (index1 < 0 || index2 < 0) + { throw new Error('swapChildren: Both the supplied DisplayObjects must be a child of the caller.'); } @@ -187,10 +210,12 @@ * @param child {DisplayObject} The DisplayObject instance to identify * @return {Number} The index position of the child display object to identify */ -DisplayObjectContainer.prototype.getChildIndex = function (child) { +DisplayObjectContainer.prototype.getChildIndex = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { throw new Error('The supplied DisplayObject must be a child of the caller'); } @@ -203,8 +228,10 @@ * @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 */ -DisplayObjectContainer.prototype.setChildIndex = function (child, index) { - if (index < 0 || index >= this.children.length) { +DisplayObjectContainer.prototype.setChildIndex = function (child, index) +{ + if (index < 0 || index >= this.children.length) + { throw new Error('The supplied index is out of bounds'); } @@ -220,8 +247,10 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child at the given index, if any. */ -DisplayObjectContainer.prototype.getChildAt = function (index) { - if (index < 0 || index >= this.children.length) { +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'); } @@ -234,10 +263,12 @@ * @param child {DisplayObject} The DisplayObject to remove * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChild = function (child) { +DisplayObjectContainer.prototype.removeChild = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { return; } @@ -250,7 +281,8 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChildAt = function (index) { +DisplayObjectContainer.prototype.removeChildAt = function (index) +{ var child = this.getChildAt(index); child.parent = null; @@ -265,24 +297,29 @@ * @param beginIndex {Number} The beginning position. Default value is 0. * @param endIndex {Number} The ending position. Default value is size of the container. */ -DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) { +DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) +{ var begin = beginIndex || 0; var end = typeof endIndex === 'number' ? endIndex : this.children.length; var range = end - begin; - if (range > 0 && range <= end) { + if (range > 0 && range <= end) + { var removed = this.children.splice(begin, range); - for (var i = 0; i < removed.length; ++i) { + for (var i = 0; i < removed.length; ++i) + { removed[i].parent = null; } return removed; } - else if (range === 0 && this.children.length === 0) { + else if (range === 0 && this.children.length === 0) + { return []; } - else { + else + { throw new RangeError('removeChildren: numeric values are outside the acceptable range.'); } }; @@ -291,7 +328,8 @@ * Generates and updates the cached sprite for this object. * */ -DisplayObjectContainer.prototype.updateCachedSprite = function () { +DisplayObjectContainer.prototype.updateCachedSprite = function () +{ this._generateCachedSprite(); }; @@ -304,7 +342,8 @@ * @param renderer {CanvasRenderer|WebGLRenderer} The renderer used to generate the texture. * @return {Texture} a texture of the graphics object */ -DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) { +DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) +{ var bounds = this.getLocalBounds(); var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0, renderer, scaleMode, resolution); @@ -322,18 +361,22 @@ * * @private */ -DisplayObjectContainer.prototype.updateTransform = function () { - if (!this.visible) { +DisplayObjectContainer.prototype.updateTransform = function () +{ + if (!this.visible) + { return; } this.displayObjectUpdateTransform(); - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { return; } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } }; @@ -346,8 +389,10 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getBounds = function () { - if (this.children.length === 0) { +DisplayObjectContainer.prototype.getBounds = function () +{ + if (this.children.length === 0) + { return math.Rectangle.EMPTY; } @@ -365,10 +410,12 @@ var childVisible = false; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -386,7 +433,8 @@ maxY = maxY > childMaxY ? maxY : childMaxY; } - if (!childVisible) { + if (!childVisible) + { return math.Rectangle.EMPTY; } @@ -407,12 +455,14 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getLocalBounds = function () { +DisplayObjectContainer.prototype.getLocalBounds = function () +{ var matrixCache = this.worldTransform; this.worldTransform = math.Matrix.IDENTITY; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } @@ -428,13 +478,16 @@ * * @param renderer {WebGLRenderer} The renderer */ -DisplayObjectContainer.prototype.renderWebGL = function (renderer) { +DisplayObjectContainer.prototype.renderWebGL = function (renderer) +{ // if the object is not visible or the alpha is 0 then no need to render this element - if (!this.visible || this.alpha <= 0) { + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } @@ -442,14 +495,17 @@ var i, j; // do a quick check to see if this element has a mask or a filter. - if (this._mask || this._filters) { + if (this._mask || this._filters) + { // push filter first as we need to ensure the stencil buffer is correct for any masking - if (this._filters) { + if (this._filters) + { renderer.spriteBatch.flush(); renderer.filterManager.pushFilter(this._filterBlock); } - if (this._mask) { + if (this._mask) + { renderer.spriteBatch.stop(); renderer.maskManager.pushMask(this.mask, renderer); renderer.spriteBatch.start(); @@ -459,36 +515,42 @@ this._renderWebGL(renderer); // now loop through the children and make sure they get rendered - for (i = 0, j = this.children.length; i < j; i++) { + for (i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderWebGL(renderer); } // time to stop the sprite batch as either a mask element or a filter draw will happen next renderer.spriteBatch.stop(); - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(this._mask, renderer); } - if (this._filters) { + if (this._filters) + { renderer.filterManager.popFilter(); } renderer.spriteBatch.start(); } - else { + else + { this._renderWebGL(renderer); // simple render children! - for (i = 0, j = this.children.length; i < j; ++i) { + for (i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderWebGL(renderer); } } }; -DisplayObjectContainer.prototype._renderWebGL = function (renderer) { +DisplayObjectContainer.prototype._renderWebGL = function (renderer) +{ // this is where content itself gets renderd.. @@ -499,25 +561,31 @@ * * @param renderer {CanvasRenderer} The renderer */ -DisplayObjectContainer.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0) { +DisplayObjectContainer.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -528,13 +596,16 @@ * @param renderer {WebGLRenderer|CanvasRenderer} The renderer * @private */ -DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) { +DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) +{ this._cachedSprite.worldAlpha = this.worldAlpha; - if (renderer.gl) { + if (renderer.gl) + { this._cachedSprite.renderWebGL(renderer); } - else { + else + { this._cachedSprite.renderCanvas(renderer); } }; @@ -544,10 +615,12 @@ * * @private */ -DisplayObjectContainer.prototype._generateCachedSprite = function () { +DisplayObjectContainer.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { // TODO - RenderTexture now *requires* a renderer instance, so this is like broken // because `renderer` isn't actually in scope here :P var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0); @@ -555,7 +628,8 @@ this._cachedSprite = new Sprite(renderTexture); this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.texture.resize(bounds.width | 0, bounds.height | 0); } @@ -580,8 +654,10 @@ * * @private */ -DisplayObjectContainer.prototype._destroyCachedSprite = function () { - if (!this._cachedSprite) { +DisplayObjectContainer.prototype._destroyCachedSprite = function () +{ + if (!this._cachedSprite) + { return; } diff --git a/src/core/display/Sprite.js b/src/core/display/Sprite.js index 707da24..5862aef 100644 --- a/src/core/display/Sprite.js +++ b/src/core/display/Sprite.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param texture {Texture} The texture for this sprite */ -function Sprite(texture) { +function Sprite(texture) +{ DisplayObjectContainer.call(this); /** @@ -85,12 +86,14 @@ this.texture = texture || Texture.EMPTY; } -Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) { +Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) +{ DisplayObjectContainer.prototype.destroy.call(this); this.anchor = null; - if (destroyTexture) { + if (destroyTexture) + { this._texture.destroy(destroyBaseTexture); } @@ -111,10 +114,12 @@ * @memberof Sprite# */ width: { - get: function () { + get: function () + { return this.scale.x * this.texture.frame.width; }, - set: function (value) { + set: function (value) + { this.scale.x = value / this.texture.frame.width; this._width = value; } @@ -127,10 +132,12 @@ * @memberof Sprite# */ height: { - get: function () { + get: function () + { return this.scale.y * this.texture.frame.height; }, - set: function (value) { + set: function (value) + { this.scale.y = value / this.texture.frame.height; this._height = value; } @@ -143,23 +150,29 @@ * @memberof Sprite# */ texture: { - get: function () { + get: function () + { return this._texture; }, - set: function (value) { - if (this._texture === value) { + set: function (value) + { + if (this._texture === value) + { return; } this._texture = value; this.cachedTint = 0xFFFFFF; - if (value) { + if (value) + { // wait for the texture to load - if (value.baseTexture.hasLoaded) { + if (value.baseTexture.hasLoaded) + { this._onTextureUpdate(); } - else { + else + { value.once('update', this._onTextureUpdate.bind(this)); } } @@ -172,18 +185,22 @@ * * @private */ -Sprite.prototype._onTextureUpdate = function () { +Sprite.prototype._onTextureUpdate = function () +{ // so if _width is 0 then width was not set.. - if (this._width) { + if (this._width) + { this.scale.x = this._width / this.texture.frame.width; } - if (this._height) { + if (this._height) + { this.scale.y = this._height / this.texture.frame.height; } }; -Sprite.prototype._renderWebGL = function (renderer) { +Sprite.prototype._renderWebGL = function (renderer) +{ // this is where content gets renderd.. // watch this space for a little render state manager.. @@ -197,7 +214,8 @@ * @param matrix {Matrix} the transformation matrix of the sprite * @return {Rectangle} the framing rectangle */ -Sprite.prototype.getBounds = function (matrix) { +Sprite.prototype.getBounds = function (matrix) +{ var width = this.texture.frame.width; var height = this.texture.frame.height; @@ -224,11 +242,13 @@ if(b === 0 && c === 0) { // scale may be negative! - if (a < 0) { + if (a < 0) + { a *= -1; } - if (d < 0) { + if (d < 0) + { d *= -1; } @@ -293,28 +313,34 @@ * * @param renderer {CanvasRenderer} The renderer */ -Sprite.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) { +Sprite.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) + { return; } - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; renderer.context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } // Ignore null sources - if (this.texture.valid) { + if (this.texture.valid) + { var resolution = this.texture.baseTexture.resolution / renderer.resolution; renderer.context.globalAlpha = this.worldAlpha; // If smoothingEnabled is supported and we need to change the smoothing property for this texture - if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) { + if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) + { renderer.scaleMode = this.texture.baseTexture.scaleMode; renderer.context[renderer.smoothProperty] = (renderer.scaleMode === CONST.scaleModes.LINEAR); } @@ -324,7 +350,8 @@ var dy = (this.texture.trim ? this.texture.trim.y : 0) - (this.anchor.y * this.texture.trim.height); // Allow for pixel rounding - if (renderer.roundPixels) { + if (renderer.roundPixels) + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -337,7 +364,8 @@ dx = dx | 0; dy = dy | 0; } - else { + else + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -348,8 +376,10 @@ ); } - if (this.tint !== 0xFFFFFF) { - if (this.cachedTint !== this.tint) { + if (this.tint !== 0xFFFFFF) + { + if (this.cachedTint !== this.tint) + { this.cachedTint = this.tint; // TODO clean up caching - how to clean up the caches? @@ -368,7 +398,8 @@ this.texture.crop.height / resolution ); } - else { + else + { renderer.context.drawImage( this.texture.baseTexture.source, this.texture.crop.x, @@ -383,11 +414,13 @@ } } - for (var i = 0, j = this.children.length; i < j; i++) { + for (var i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -402,10 +435,12 @@ * @param frameId {String} The frame Id of the texture in the cache * @return {Sprite} A new Sprite using a texture from the texture cache matching the frameId */ -Sprite.fromFrame = function (frameId) { +Sprite.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache' + this); } @@ -420,6 +455,7 @@ * @param imageId {String} The image url of the texture * @return {Sprite} A new Sprite using a texture from the texture cache matching the image id */ -Sprite.fromImage = function (imageId, crossorigin, scaleMode) { +Sprite.fromImage = function (imageId, crossorigin, scaleMode) +{ return new Sprite(Texture.fromImage(imageId, crossorigin, scaleMode)); }; diff --git a/src/core/display/SpriteBatch.js b/src/core/display/SpriteBatch.js index 3187777..c196fef 100644 --- a/src/core/display/SpriteBatch.js +++ b/src/core/display/SpriteBatch.js @@ -12,7 +12,8 @@ * ```js * var container = new SpriteBatch(); * - * for(var i = 0; i < 100; ++i) { + * for(var i = 0; i < 100; ++i) + * { * var sprite = new PIXI.Sprite.fromImage("myImage.png"); * container.addChild(sprite); * } @@ -25,7 +26,8 @@ */ //TODO RENAME to PARTICLE CONTAINER? -function SpriteBatch() { +function SpriteBatch() +{ DisplayObjectContainer.call(this); } @@ -38,7 +40,8 @@ * * @private */ -SpriteBatch.prototype.updateTransform = function () { +SpriteBatch.prototype.updateTransform = function () +{ // TODO don't need to! this.displayObjectUpdateTransform(); // PIXI.DisplayObjectContainer.prototype.updateTransform.call( this ); @@ -50,8 +53,10 @@ * @param renderer {WebGLRenderer} The webgl renderer * @private */ -SpriteBatch.prototype.renderWebGL = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderWebGL = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -71,8 +76,10 @@ * @param renderer {CanvasRenderer} The canvas renderer * @private */ -SpriteBatch.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -84,10 +91,12 @@ this.displayObjectUpdateTransform(); - for (var i = 0; i < this.children.length; ++i) { + for (var i = 0; i < this.children.length; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -95,9 +104,11 @@ context.globalAlpha = this.worldAlpha * child.alpha; - if (child.rotation % (Math.PI * 2) === 0) { + if (child.rotation % (Math.PI * 2) === 0) + { // this is the fastest way to optimise! - if rotation is 0 then we can avoid any kind of setTransform call - if (isRotated) { + if (isRotated) + { context.setTransform( transform.a, transform.b, @@ -122,8 +133,10 @@ frame.height * child.scale.y ); } - else { - if (!isRotated) { + else + { + if (!isRotated) + { isRotated = true; } @@ -131,7 +144,8 @@ var childTransform = child.worldTransform; - if (renderer.roundPixels) { + if (renderer.roundPixels) + { context.setTransform( childTransform.a, childTransform.b, @@ -141,7 +155,8 @@ childTransform.ty | 0 ); } - else { + else + { context.setTransform( childTransform.a, childTransform.b, diff --git a/src/core/index.js b/src/core/index.js index 3954b6f..eb4a82b 100644 --- a/src/core/index.js +++ b/src/core/index.js @@ -58,11 +58,13 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRenderer: function (width, height, options, noWebGL) { + autoDetectRenderer: function (width, height, options, noWebGL) + { width = width || 800; height = height || 600; - if (!noWebGL && require('webgl-enabled')()) { + if (!noWebGL && require('webgl-enabled')()) + { return new core.WebGLRenderer(width, height, options); } @@ -87,7 +89,8 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRecommendedRenderer: function (width, height, options) { + autoDetectRecommendedRenderer: function (width, height, options) + { var isAndroid = /Android/i.test(navigator.userAgent); return core.autoDetectRenderer(width, height, options, isAndroid); diff --git a/src/core/math/Matrix.js b/src/core/math/Matrix.js index c2f87e2..2ff4848 100644 --- a/src/core/math/Matrix.js +++ b/src/core/math/Matrix.js @@ -10,7 +10,8 @@ * @class * @namespace PIXI */ -function Matrix() { +function Matrix() +{ /** * @member {number} * @default 1 @@ -63,7 +64,8 @@ * * @param array {number[]} The array that the matrix will be populated from. */ -Matrix.prototype.fromArray = function (array) { +Matrix.prototype.fromArray = function (array) +{ this.a = array[0]; this.b = array[1]; this.c = array[3]; @@ -78,14 +80,17 @@ * @param transpose {boolean} Whether we need to transpose the matrix or not * @return {number[]} the newly created array which contains the matrix */ -Matrix.prototype.toArray = function (transpose) { - if (!this.array) { +Matrix.prototype.toArray = function (transpose) +{ + if (!this.array) + { this.array = new Float32Array(9); } var array = this.array; - if (transpose) { + if (transpose) + { array[0] = this.a; array[1] = this.b; array[2] = 0; @@ -96,7 +101,8 @@ array[7] = this.ty; array[8] = 1; } - else { + else + { array[0] = this.a; array[1] = this.c; array[2] = this.tx; @@ -119,7 +125,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, transformed through this matrix */ -Matrix.prototype.apply = function (pos, newPos) { +Matrix.prototype.apply = function (pos, newPos) +{ newPos = newPos || new Point(); newPos.x = this.a * pos.x + this.c * pos.y + this.tx; @@ -136,7 +143,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, inverse-transformed through this matrix */ -Matrix.prototype.applyInverse = function (pos, newPos) { +Matrix.prototype.applyInverse = function (pos, newPos) +{ newPos = newPos || new Point(); var id = 1 / (this.a * this.d + this.c * -this.b); @@ -154,7 +162,8 @@ * @param {number} y * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.translate = function (x, y) { +Matrix.prototype.translate = function (x, y) +{ this.tx += x; this.ty += y; @@ -168,7 +177,8 @@ * @param {number} y The amount to scale vertically * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.scale = function (x, y) { +Matrix.prototype.scale = function (x, y) +{ this.a *= x; this.d *= y; this.c *= x; @@ -186,7 +196,8 @@ * @param {number} angle - The angle in radians. * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.rotate = function (angle) { +Matrix.prototype.rotate = function (angle) +{ var cos = Math.cos( angle ); var sin = Math.sin( angle ); @@ -210,7 +221,8 @@ * @param {Matrix} matrix * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.append = function (matrix) { +Matrix.prototype.append = function (matrix) +{ var a1 = this.a; var b1 = this.b; var c1 = this.c; @@ -232,7 +244,8 @@ * * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.identity = function () { +Matrix.prototype.identity = function () +{ this.a = 1; this.b = 0; this.c = 0; diff --git a/src/core/math/Point.js b/src/core/math/Point.js index 7565b2d..632f346 100644 --- a/src/core/math/Point.js +++ b/src/core/math/Point.js @@ -7,7 +7,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -function Point(x, y) { +function Point(x, y) +{ /** * @member {number} * @default 0 @@ -29,7 +30,8 @@ * * @return {Point} a copy of the point */ -Point.prototype.clone = function () { +Point.prototype.clone = function () +{ return new Point(this.x, this.y); }; @@ -40,7 +42,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -Point.prototype.set = function (x, y) { +Point.prototype.set = function (x, y) +{ this.x = x || 0; this.y = y || ( (y !== 0) ? this.x : 0 ) ; }; diff --git a/src/core/math/shapes/Circle.js b/src/core/math/shapes/Circle.js index 69cfdc9..4d76efc 100644 --- a/src/core/math/shapes/Circle.js +++ b/src/core/math/shapes/Circle.js @@ -10,7 +10,8 @@ * @param y {number} The Y coordinate of the center of this circle * @param radius {number} The radius of the circle */ -function Circle(x, y, radius) { +function Circle(x, y, radius) +{ /** * @member {number} * @default 0 @@ -46,7 +47,8 @@ * @method clone * @return {Circle} a copy of the Circle */ -Circle.prototype.clone = function () { +Circle.prototype.clone = function () +{ return new Circle(this.x, this.y, this.radius); }; @@ -58,8 +60,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Circle */ -Circle.prototype.contains = function (x, y) { - if (this.radius <= 0) { +Circle.prototype.contains = function (x, y) +{ + if (this.radius <= 0) + { return false; } @@ -79,6 +83,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Circle.prototype.getBounds = function () { +Circle.prototype.getBounds = function () +{ return new Rectangle(this.x - this.radius, this.y - this.radius, this.radius * 2, this.radius * 2); }; diff --git a/src/core/math/shapes/Ellipse.js b/src/core/math/shapes/Ellipse.js index 4f2d066..fefd01a 100644 --- a/src/core/math/shapes/Ellipse.js +++ b/src/core/math/shapes/Ellipse.js @@ -11,7 +11,8 @@ * @param width {number} The half width of this ellipse * @param height {number} The half height of this ellipse */ -function Ellipse(x, y, width, height) { +function Ellipse(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -53,7 +54,8 @@ * @method clone * @return {Ellipse} a copy of the ellipse */ -Ellipse.prototype.clone = function () { +Ellipse.prototype.clone = function () +{ return new Ellipse(this.x, this.y, this.width, this.height); }; @@ -65,8 +67,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coords are within this ellipse */ -Ellipse.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Ellipse.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } @@ -86,6 +90,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Ellipse.prototype.getBounds = function () { +Ellipse.prototype.getBounds = function () +{ return new Rectangle(this.x - this.width, this.y - this.height, this.width, this.height); }; diff --git a/src/core/math/shapes/Polygon.js b/src/core/math/shapes/Polygon.js index ae89148..fea6d37 100644 --- a/src/core/math/shapes/Polygon.js +++ b/src/core/math/shapes/Polygon.js @@ -10,16 +10,20 @@ * arguments passed can be flat x,y values e.g. `new Polygon(x,y, x,y, x,y, ...)` where `x` and `y` are * Numbers. */ -function Polygon(points) { +function Polygon(points) +{ //if points isn't an array, use arguments as the array - if (!(points instanceof Array)) { + if (!(points instanceof Array)) + { points = Array.prototype.slice.call(arguments); } //if this is a flat array of numbers, convert it to points - if (points[0] instanceof Point) { + if (points[0] instanceof Point) + { var p = []; - for (var i = 0, il = points.length; i < il; i++) { + for (var i = 0, il = points.length; i < il; i++) + { p.push(points[i].x, points[i].y); } @@ -51,7 +55,8 @@ * * @return {Polygon} a copy of the polygon */ -Polygon.prototype.clone = function () { +Polygon.prototype.clone = function () +{ return new Polygon(this.points.slice()); }; @@ -62,19 +67,22 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this polygon */ -Polygon.prototype.contains = function (x, y) { +Polygon.prototype.contains = function (x, y) +{ var inside = false; // use some raycasting to test hits // https://github.com/substack/point-in-polygon/blob/master/index.js var length = this.points.length / 2; - for (var i = 0, j = length - 1; i < length; j = i++) { + for (var i = 0, j = length - 1; i < length; j = i++) + { var xi = this.points[i * 2], yi = this.points[i * 2 + 1], xj = this.points[j * 2], yj = this.points[j * 2 + 1], intersect = ((yi > y) !== (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi); - if (intersect) { + if (intersect) + { inside = !inside; } } diff --git a/src/core/math/shapes/Rectangle.js b/src/core/math/shapes/Rectangle.js index 16ac62a..4008b68 100644 --- a/src/core/math/shapes/Rectangle.js +++ b/src/core/math/shapes/Rectangle.js @@ -10,7 +10,8 @@ * @param width {number} The overall width of this rectangle * @param height {number} The overall height of this rectangle */ -function Rectangle(x, y, width, height) { +function Rectangle(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -60,7 +61,8 @@ * * @return {Rectangle} a copy of the rectangle */ -Rectangle.prototype.clone = function () { +Rectangle.prototype.clone = function () +{ return new Rectangle(this.x, this.y, this.width, this.height); }; @@ -71,13 +73,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rectangle */ -Rectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Rectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/math/shapes/RoundedRectangle.js b/src/core/math/shapes/RoundedRectangle.js index 27d286e..7bf6411 100644 --- a/src/core/math/shapes/RoundedRectangle.js +++ b/src/core/math/shapes/RoundedRectangle.js @@ -11,7 +11,8 @@ * @param height {number} The overall height of this rounded rectangle * @param radius {number} Controls the radius of the rounded corners */ -function RoundedRectangle(x, y, width, height, radius) { +function RoundedRectangle(x, y, width, height, radius) +{ /** * @member {number} * @default 0 @@ -58,7 +59,8 @@ * * @return {RoundedRectangle} a copy of the rounded rectangle */ -RoundedRectangle.prototype.clone = function () { +RoundedRectangle.prototype.clone = function () +{ return new RoundedRectangle(this.x, this.y, this.width, this.height, this.radius); }; @@ -69,13 +71,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rounded Rectangle */ -RoundedRectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +RoundedRectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/primitives/Graphics.js b/src/core/primitives/Graphics.js index 261c534..e902d2a 100644 --- a/src/core/primitives/Graphics.js +++ b/src/core/primitives/Graphics.js @@ -16,7 +16,8 @@ * @extends DisplayObjectContainer * @namespace PIXI */ -function Graphics() { +function Graphics() +{ DisplayObjectContainer.call(this); this.renderable = true; @@ -154,16 +155,20 @@ * @private */ cacheAsBitmap: { - get: function () { + get: function () + { return this._cacheAsBitmap; }, - set: function (value) { + set: function (value) + { this._cacheAsBitmap = value; - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._generateCachedSprite(); } - else { + else + { this.destroyCachedSprite(); this.dirty = true; } @@ -176,7 +181,8 @@ * * @return {Graphics} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ var clone = new Graphics(); clone.renderable = this.renderable; @@ -192,7 +198,8 @@ clone.cachedSpriteDirty = this.cachedSpriteDirty; // copy graphics data - for (var i = 0; i < this.graphicsData.length; ++i) { + for (var i = 0; i < this.graphicsData.length; ++i) + { clone.graphicsData.push(this.graphicsData.clone()); } @@ -211,17 +218,21 @@ * @param alpha {number} alpha of the line to draw, will update the objects stored style * @return {Graphics} */ -Graphics.prototype.lineStyle = function (lineWidth, color, alpha) { +Graphics.prototype.lineStyle = function (lineWidth, color, alpha) +{ this.lineWidth = lineWidth || 0; this.lineColor = color || 0; this.lineAlpha = (arguments.length < 3) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length) + { // halfway through a line? start a new one! this.drawShape( new math.Polygon( this.currentPath.shape.points.slice(-2) )); } - else { + else + { // otherwise its empty so lets just set the line properties this.currentPath.lineWidth = this.lineWidth; this.currentPath.lineColor = this.lineColor; @@ -239,7 +250,8 @@ * @param y {number} the Y coordinate to move to * @return {Graphics} */ -Graphics.prototype.moveTo = function (x, y) { +Graphics.prototype.moveTo = function (x, y) +{ this.drawShape(new math.Polygon([x,y])); return this; @@ -253,7 +265,8 @@ * @param y {number} the Y coordinate to draw to * @return {Graphics} */ -Graphics.prototype.lineTo = function (x, y) { +Graphics.prototype.lineTo = function (x, y) +{ this.currentPath.shape.points.push(x, y); this.dirty = true; @@ -270,13 +283,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -285,7 +302,8 @@ n = 20, points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { this.moveTo(0, 0); } @@ -293,7 +311,8 @@ var fromY = points[points.length-1]; var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; xa = fromX + ( (cpX - fromX) * j ); @@ -319,13 +338,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -342,7 +365,8 @@ var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; dt = (1 - j); @@ -373,13 +397,17 @@ * @param radius {number} The radius of the arc * @return {Graphics} */ -Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points.push(x1, y1); } } - else { + else + { this.moveTo(x1, y1); } @@ -392,12 +420,15 @@ b2 = x2 - x1, mm = Math.abs(a1 * b2 - b1 * a2); - if (mm < 1.0e-8 || radius === 0) { - if (points[points.length-2] !== x1 || points[points.length-1] !== y1) { + if (mm < 1.0e-8 || radius === 0) + { + if (points[points.length-2] !== x1 || points[points.length-1] !== y1) + { points.push(x1, y1); } } - else { + else + { var dd = a1 * a1 + b1 * b1, cc = a2 * a2 + b2 * b2, tt = a1 * a2 + b1 * b2, @@ -433,42 +464,51 @@ * @param anticlockwise {boolean} Optional. Specifies whether the drawing should be counterclockwise or clockwise. False is default, and indicates clockwise, while true indicates counter-clockwise. * @return {Graphics} */ -Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) { +Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) +{ var startX = cx + Math.cos(startAngle) * radius; var startY = cy + Math.sin(startAngle) * radius; var points; // TODO - This if-else makes no sense. It uses currentPath in the else where it doesn't exist... - if (this.currentPath) { + if (this.currentPath) + { points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { points.push(startX, startY); } - else if (points[points.length-2] !== startX || points[points.length-1] !== startY) { + else if (points[points.length-2] !== startX || points[points.length-1] !== startY) + { points.push(startX, startY); } } - else { + else + { this.moveTo(startX, startY); points = this.currentPath.shape.points; } - if (startAngle === endAngle) { + if (startAngle === endAngle) + { return this; } - if (!anticlockwise && endAngle <= startAngle) { + if (!anticlockwise && endAngle <= startAngle) + { endAngle += Math.PI * 2; } - else if (anticlockwise && startAngle <= endAngle) { + else if (anticlockwise && startAngle <= endAngle) + { startAngle += Math.PI * 2; } var sweep = anticlockwise ? (startAngle - endAngle) *-1 : (endAngle - startAngle); var segs = (Math.abs(sweep)/ (Math.PI * 2)) * 40; - if (sweep === 0) { + if (sweep === 0) + { return this; } @@ -482,7 +522,8 @@ var remainder = ( segMinus % 1 ) / segMinus; - for (var i = 0; i <= segMinus; ++i) { + for (var i = 0; i <= segMinus; ++i) + { var real = i + remainder * i; var angle = ((theta) + startAngle + (theta2 * real)); @@ -506,13 +547,16 @@ * @param alpha {number} the alpha of the fill * @return {Graphics} */ -Graphics.prototype.beginFill = function (color, alpha) { +Graphics.prototype.beginFill = function (color, alpha) +{ this.filling = true; this.fillColor = color || 0; this.fillAlpha = (alpha === undefined) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length <= 2) + { this.currentPath.fill = this.filling; this.currentPath.fillColor = this.fillColor; this.currentPath.fillAlpha = this.fillAlpha; @@ -526,7 +570,8 @@ * * @return {Graphics} */ -Graphics.prototype.endFill = function () { +Graphics.prototype.endFill = function () +{ this.filling = false; this.fillColor = null; this.fillAlpha = 1; @@ -542,7 +587,8 @@ * @param height {number} The height of the rectangle * @return {Graphics} */ -Graphics.prototype.drawRect = function ( x, y, width, height ) { +Graphics.prototype.drawRect = function ( x, y, width, height ) +{ this.drawShape(new math.Rectangle(x,y, width, height)); return this; @@ -556,7 +602,8 @@ * @param height {number} The height of the rectangle * @param radius {number} Radius of the rectangle corners */ -Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) { +Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) +{ this.drawShape(new math.RoundedRectangle(x, y, width, height, radius)); return this; @@ -570,7 +617,8 @@ * @param radius {number} The radius of the circle * @return {Graphics} */ -Graphics.prototype.drawCircle = function (x, y, radius) { +Graphics.prototype.drawCircle = function (x, y, radius) +{ this.drawShape(new math.Circle(x,y, radius)); return this; @@ -585,7 +633,8 @@ * @param height {number} The half height of the ellipse * @return {Graphics} */ -Graphics.prototype.drawEllipse = function (x, y, width, height) { +Graphics.prototype.drawEllipse = function (x, y, width, height) +{ this.drawShape(new math.Ellipse(x, y, width, height)); return this; @@ -597,8 +646,10 @@ * @param path {Array} The path data used to construct the polygon. * @return {Graphics} */ -Graphics.prototype.drawPolygon = function (path) { - if (!(path instanceof Array)) { +Graphics.prototype.drawPolygon = function (path) +{ + if (!(path instanceof Array)) + { path = Array.prototype.slice.call(arguments); } @@ -612,7 +663,8 @@ * * @return {Graphics} */ -Graphics.prototype.clear = function () { +Graphics.prototype.clear = function () +{ this.lineWidth = 0; this.filling = false; @@ -631,7 +683,8 @@ * @param scaleMode {number} Should be one of the scaleMode consts * @return {Texture} a texture of the graphics object */ -Graphics.prototype.generateTexture = function (resolution, scaleMode) { +Graphics.prototype.generateTexture = function (resolution, scaleMode) +{ resolution = resolution || 1; var bounds = this.getBounds(); @@ -655,17 +708,21 @@ * * @param renderer {WebGLRenderer} */ -Graphics.prototype._renderWebGL = function (renderer) { +Graphics.prototype._renderWebGL = function (renderer) +{ // if the sprite is not visible or the alpha is 0 then no need to render this element - if (this.isMask === true) { + if (this.isMask === true) + { return; } // this code may still be needed so leaving for now.. - // + // /* - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture on the gpu too! @@ -681,17 +738,24 @@ return; } - */ - - // check if the webgl graphic needs to be updated - if (this.glDirty) { - this.dirty = true; - this.glDirty = false; - } + else */ - renderer.setObjectRendererer(renderer.graphicsRenderer); - renderer.graphicsRenderer.render(this); + renderer.spriteBatch.stop(); + renderer.blendModeManager.setBlendMode(this.blendMode); + // check blend mode + renderer.blendModeManager.setBlendMode( this.blendMode ); + + // check if the webgl graphic needs to be updated + if (this.glDirty) + { + this.dirty = true; + this.glDirty = false; + } + + WebGLGraphics.renderGraphics(this, renderer); + + renderer.spriteBatch.start(); }; /** @@ -700,14 +764,18 @@ * @param renderer {CanvasRenderer} * @private */ -Graphics.prototype.renderCanvas = function (renderer) { +Graphics.prototype.renderCanvas = function (renderer) +{ // 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.isMask === true) { + if (!this.visible || this.alpha <= 0 || this.isMask === true) + { return; } - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture @@ -723,16 +791,19 @@ return; } - else { + else + { var context = renderer.context; var transform = this.worldTransform; - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } @@ -748,11 +819,13 @@ CanvasGraphics.renderGraphics(this, context); - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } } @@ -763,13 +836,16 @@ * * @return {Rectangle} the rectangular bounding area */ -Graphics.prototype.getBounds = function (matrix) { +Graphics.prototype.getBounds = function (matrix) +{ // return an empty object if the item is a mask! - if (this.isMask) { + if (this.isMask) + { return math.Rectangle.EMPTY; } - if (this.dirty) { + if (this.dirty) + { this.updateLocalBounds(); this.glDirty = true; @@ -841,23 +917,27 @@ * Update the bounds of the object * */ -Graphics.prototype.updateLocalBounds = function () { +Graphics.prototype.updateLocalBounds = function () +{ var minX = Infinity; var maxX = -Infinity; var minY = Infinity; var maxY = -Infinity; - if (this.graphicsData.length) { + if (this.graphicsData.length) + { var shape, points, x, y, w, h; - for (var i = 0; i < this.graphicsData.length; i++) { + for (var i = 0; i < this.graphicsData.length; i++) + { var data = this.graphicsData[i]; var type = data.type; var lineWidth = data.lineWidth; shape = data.shape; - if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) { + if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) + { x = shape.x - lineWidth/2; y = shape.y - lineWidth/2; w = shape.width + lineWidth; @@ -869,7 +949,8 @@ minY = y < minY ? y : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.CIRC) { + else if (type === CONST.SHAPES.CIRC) + { x = shape.x; y = shape.y; w = shape.radius + lineWidth/2; @@ -881,7 +962,8 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.ELIP) { + else if (type === CONST.SHAPES.ELIP) + { x = shape.x; y = shape.y; w = shape.width + lineWidth/2; @@ -893,11 +975,13 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else { + else + { // POLY points = shape.points; - for (var j = 0; j < points.length; j += 2) { + for (var j = 0; j < points.length; j += 2) + { x = points[j]; y = points[j+1]; @@ -910,7 +994,8 @@ } } } - else { + else + { minX = 0; maxX = 0; minY = 0; @@ -931,10 +1016,12 @@ * * @private */ -Graphics.prototype._generateCachedSprite = function () { +Graphics.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { var canvasBuffer = new CanvasBuffer(bounds.width, bounds.height); var texture = Texture.fromCanvas(canvasBuffer.canvas); @@ -943,7 +1030,8 @@ this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.buffer.resize(bounds.width, bounds.height); } @@ -968,7 +1056,8 @@ * * @private */ -Graphics.prototype.updateCachedSpriteTexture = function () { +Graphics.prototype.updateCachedSpriteTexture = function () +{ var cachedSprite = this._cachedSprite; var texture = cachedSprite.texture; var canvas = cachedSprite.buffer.canvas; @@ -989,7 +1078,8 @@ * Destroys a previous cached sprite. * */ -Graphics.prototype.destroyCachedSprite = function () { +Graphics.prototype.destroyCachedSprite = function () +{ this._cachedSprite.texture.destroy(true); // let the gc collect the unused sprite @@ -1003,10 +1093,13 @@ * @param {Circle|Rectangle|Ellipse|Line|Polygon} shape The Shape object to draw. * @return {GraphicsData} The generated GraphicsData object. */ -Graphics.prototype.drawShape = function (shape) { - if (this.currentPath) { +Graphics.prototype.drawShape = function (shape) +{ + if (this.currentPath) + { // check current path! - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath.shape.points.length <= 2) + { this.graphicsData.pop(); } } @@ -1017,7 +1110,8 @@ this.graphicsData.push(data); - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { data.shape.closed = this.filling; this.currentPath = data; } diff --git a/src/core/primitives/GraphicsData.js b/src/core/primitives/GraphicsData.js index 99decbe..788f6f2 100644 --- a/src/core/primitives/GraphicsData.js +++ b/src/core/primitives/GraphicsData.js @@ -4,7 +4,8 @@ * @class * @namespace PIXI */ -function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) { +function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) +{ this.lineWidth = lineWidth; this.lineColor = lineColor; this.lineAlpha = lineAlpha; @@ -27,7 +28,8 @@ * * @return {GraphicsData} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ return new GraphicsData( this.lineWidth, this.lineColor, diff --git a/src/core/renderers/canvas/CanvasRenderer.js b/src/core/renderers/canvas/CanvasRenderer.js index 15a0978..7aebd44 100644 --- a/src/core/renderers/canvas/CanvasRenderer.js +++ b/src/core/renderers/canvas/CanvasRenderer.js @@ -17,17 +17,22 @@ * @param [options.resolution=1] {number} the resolution of the renderer retina would be 2 * @param [options.clearBeforeRender=true] {boolean} This sets if the CanvasRenderer will clear the canvas or not before the new render pass. */ -function CanvasRenderer(width, height, options) { +function CanvasRenderer(width, height, options) +{ utils.sayHello('Canvas'); - if (options) { - for (var i in CONST.defaultRenderOptions) { - if (typeof options[i] === 'undefined') { + if (options) + { + for (var i in CONST.defaultRenderOptions) + { + if (typeof options[i] === 'undefined') + { options[i] = CONST.defaultRenderOptions[i]; } } } - else { + else + { options = CONST.defaultRenderOptions; } @@ -156,19 +161,24 @@ this.smoothProperty = null; - if (this.context.imageSmoothingEnabled) { + if (this.context.imageSmoothingEnabled) + { this.smoothProperty = 'imageSmoothingEnabled'; } - else if (this.context.webkitImageSmoothingEnabled) { + else if (this.context.webkitImageSmoothingEnabled) + { this.smoothProperty = 'webkitImageSmoothingEnabled'; } - else if (this.context.mozImageSmoothingEnabled) { + else if (this.context.mozImageSmoothingEnabled) + { this.smoothProperty = 'mozImageSmoothingEnabled'; } - else if (this.context.oImageSmoothingEnabled) { + else if (this.context.oImageSmoothingEnabled) + { this.smoothProperty = 'oImageSmoothingEnabled'; } - else if (this.context.msImageSmoothingEnabled) { + else if (this.context.msImageSmoothingEnabled) + { this.smoothProperty = 'msImageSmoothingEnabled'; } @@ -193,10 +203,12 @@ * @memberof CanvasRenderer# */ backgroundColor: { - get: function () { + get: function () + { return this._backgroundColor; }, - set: function (val) { + set: function (val) + { this._backgroundColor = val; this._backgroundColorString = utils.hex2string(val); } @@ -208,7 +220,8 @@ * * @param object {DisplayObject} the object to be rendered */ -CanvasRenderer.prototype.render = function (object) { +CanvasRenderer.prototype.render = function (object) +{ object.updateTransform(); this.context.setTransform(1,0,0,1,0,0); @@ -218,16 +231,20 @@ this.currentBlendMode = CONST.blendModes.NORMAL; this.context.globalCompositeOperation = this.blendModes[CONST.blendModes.NORMAL]; - if (navigator.isCocoonJS && this.view.screencanvas) { + if (navigator.isCocoonJS && this.view.screencanvas) + { this.context.fillStyle = 'black'; this.context.clear(); } - if (this.clearBeforeRender) { - if (this.transparent) { + if (this.clearBeforeRender) + { + if (this.transparent) + { this.context.clearRect(0, 0, this.width, this.height); } - else { + else + { this.context.fillStyle = this._backgroundColorString; this.context.fillRect(0, 0, this.width , this.height); } @@ -241,8 +258,10 @@ * * @param [removeView=false] {boolean} Removes the Canvas element from the DOM. */ -CanvasRenderer.prototype.destroy = function (removeView) { - if (removeView && this.view.parent) { +CanvasRenderer.prototype.destroy = function (removeView) +{ + if (removeView && this.view.parent) + { this.view.parent.removeChild(this.view); } @@ -257,14 +276,16 @@ * @param width {number} the new width of the canvas view * @param height {number} the new height of the canvas view */ -CanvasRenderer.prototype.resize = function (width, height) { +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) { + if (this.autoResize) + { this.view.style.width = this.width / this.resolution + 'px'; this.view.style.height = this.height / this.resolution + 'px'; } @@ -276,7 +297,8 @@ * @param displayObject {DisplayObject} The displayObject to render * @private */ -CanvasRenderer.prototype.renderDisplayObject = function (displayObject) { +CanvasRenderer.prototype.renderDisplayObject = function (displayObject) +{ displayObject.renderCanvas(this); }; @@ -285,11 +307,14 @@ * * @private */ -CanvasRenderer.prototype._mapBlendModes = function () { - if (!this.blendModes) { +CanvasRenderer.prototype._mapBlendModes = function () +{ + if (!this.blendModes) + { this.blendModes = {}; - if (utils.canUseNewCanvasBlendModes()) { + if (utils.canUseNewCanvasBlendModes()) + { this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? this.blendModes[CONST.blendModes.MULTIPLY] = 'multiply'; @@ -308,7 +333,8 @@ this.blendModes[CONST.blendModes.COLOR] = 'color'; this.blendModes[CONST.blendModes.LUMINOSITY] = 'luminosity'; } - else { + else + { // this means that the browser does not support the cool new blend modes in canvas 'cough' ie 'cough' this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? diff --git a/src/core/renderers/canvas/utils/CanvasBuffer.js b/src/core/renderers/canvas/utils/CanvasBuffer.js index ebe5d47..b183a66 100644 --- a/src/core/renderers/canvas/utils/CanvasBuffer.js +++ b/src/core/renderers/canvas/utils/CanvasBuffer.js @@ -6,7 +6,8 @@ * @param width {number} the width for the newly created canvas * @param height {number} the height for the newly created canvas */ -function CanvasBuffer(width, height) { +function CanvasBuffer(width, height) +{ /** * The Canvas object that belongs to this CanvasBuffer. * @@ -36,10 +37,12 @@ * @memberof CanvasBuffer# */ width: { - get: function () { + get: function () + { return this.canvas.width; }, - set: function (val) { + set: function (val) + { this.canvas.width = val; } }, @@ -50,10 +53,12 @@ * @memberof CanvasBuffer# */ height: { - get: function () { + get: function () + { return this.canvas.height; }, - set: function (val) { + set: function (val) + { this.canvas.height = val; } } @@ -64,7 +69,8 @@ * * @private */ -CanvasBuffer.prototype.clear = function () { +CanvasBuffer.prototype.clear = function () +{ this.context.setTransform(1, 0, 0, 1, 0, 0); this.context.clearRect(0,0, this.canvas.width, this.canvas.height); }; @@ -75,7 +81,8 @@ * @param width {number} the new width of the canvas * @param height {number} the new height of the canvas */ -CanvasBuffer.prototype.resize = function (width, height) { +CanvasBuffer.prototype.resize = function (width, height) +{ this.canvas.width = width; this.canvas.height = height; }; diff --git a/src/core/renderers/canvas/utils/CanvasGraphics.js b/src/core/renderers/canvas/utils/CanvasGraphics.js index c7eaa2a..3f2a91f 100644 --- a/src/core/renderers/canvas/utils/CanvasGraphics.js +++ b/src/core/renderers/canvas/utils/CanvasGraphics.js @@ -13,15 +13,18 @@ * @param graphics {Graphics} the actual graphics object to render * @param context {CanvasRenderingContext2D} the 2d drawing method of the canvas */ -CanvasGraphics.renderGraphics = function (graphics, context) { +CanvasGraphics.renderGraphics = function (graphics, context) +{ var worldAlpha = graphics.worldAlpha; - if (graphics.dirty) { + if (graphics.dirty) + { this.updateGraphicsTint(graphics); graphics.dirty = false; } - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; @@ -30,69 +33,82 @@ context.lineWidth = data.lineWidth; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { context.beginPath(); var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } - if (shape.closed) { + if (shape.closed) + { context.lineTo(points[0], points[1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fillRect(shape.x, shape.y, shape.width, shape.height); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.strokeRect(shape.x, shape.y, shape.width, shape.height); } } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.beginPath(); context.arc(shape.x, shape.y, shape.radius,0,2*Math.PI); context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas var w = shape.width * 2; @@ -119,18 +135,21 @@ context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; var width = shape.width; @@ -152,13 +171,15 @@ context.quadraticCurveTo(rx, ry, rx, ry + radius); context.closePath(); - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); @@ -174,45 +195,54 @@ * @param graphics {Graphics} the graphics which will be used as a mask * @param context {CanvasRenderingContext2D} the context 2d method of the canvas */ -CanvasGraphics.renderGraphicsMask = function (graphics, context) { +CanvasGraphics.renderGraphicsMask = function (graphics, context) +{ var len = graphics.graphicsData.length; - if (len === 0) { + if (len === 0) + { return; } context.beginPath(); - for (var i = 0; i < len; i++) { + for (var i = 0; i < len; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { context.rect(shape.x, shape.y, shape.width, shape.height); context.closePath(); } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.arc(shape.x, shape.y, shape.radius, 0, 2 * Math.PI); context.closePath(); } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas @@ -237,7 +267,8 @@ context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); context.closePath(); } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; @@ -262,8 +293,10 @@ } }; -CanvasGraphics.updateGraphicsTint = function (graphics) { - if (graphics.tint === 0xFFFFFF) { +CanvasGraphics.updateGraphicsTint = function (graphics) +{ + if (graphics.tint === 0xFFFFFF) + { return; } @@ -271,7 +304,8 @@ var tintG = (graphics.tint >> 8 & 0xFF) / 255; var tintB = (graphics.tint & 0xFF)/ 255; - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var fillColor = data.fillColor | 0; diff --git a/src/core/renderers/canvas/utils/CanvasMaskManager.js b/src/core/renderers/canvas/utils/CanvasMaskManager.js index e04a733..9827d36 100644 --- a/src/core/renderers/canvas/utils/CanvasMaskManager.js +++ b/src/core/renderers/canvas/utils/CanvasMaskManager.js @@ -6,7 +6,8 @@ * @class * @namespace PIXI */ -function CanvasMaskManager() {} +function CanvasMaskManager() +{} CanvasMaskManager.prototype.constructor = CanvasMaskManager; module.exports = CanvasMaskManager; @@ -17,7 +18,8 @@ * @param maskData {object} the maskData that will be pushed * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.pushMask = function (maskData, renderer) { +CanvasMaskManager.prototype.pushMask = function (maskData, renderer) +{ renderer.context.save(); var cacheAlpha = maskData.alpha; @@ -45,6 +47,7 @@ * * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.popMask = function (renderer) { +CanvasMaskManager.prototype.popMask = function (renderer) +{ renderer.context.restore(); }; diff --git a/src/core/renderers/canvas/utils/CanvasTinter.js b/src/core/renderers/canvas/utils/CanvasTinter.js index 17e0529..d2fb1bc 100644 --- a/src/core/renderers/canvas/utils/CanvasTinter.js +++ b/src/core/renderers/canvas/utils/CanvasTinter.js @@ -14,7 +14,8 @@ * @param color {number} the color to use to tint the sprite with * @return {HTMLCanvasElement} The tinted canvas */ -CanvasTinter.getTintedTexture = function (sprite, color) { +CanvasTinter.getTintedTexture = function (sprite, color) +{ var texture = sprite.texture; color = CanvasTinter.roundColor(color); @@ -23,7 +24,8 @@ texture.tintCache = texture.tintCache || {}; - if (texture.tintCache[stringColor]) { + if (texture.tintCache[stringColor]) + { return texture.tintCache[stringColor]; } @@ -33,14 +35,16 @@ //CanvasTinter.tintWithPerPixel(texture, stringColor, canvas); CanvasTinter.tintMethod(texture, color, canvas); - if (CanvasTinter.convertTintToImage) { + if (CanvasTinter.convertTintToImage) + { // is this better? var tintImage = new Image(); tintImage.src = canvas.toDataURL(); texture.tintCache[stringColor] = tintImage; } - else { + else + { texture.tintCache[stringColor] = canvas; // if we are not converting the texture to an image then we need to lose the reference to the canvas CanvasTinter.canvas = null; @@ -56,7 +60,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithMultiply = function (texture, color, canvas) { +CanvasTinter.tintWithMultiply = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -104,7 +109,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithOverlay = function (texture, color, canvas) { +CanvasTinter.tintWithOverlay = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -139,7 +145,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithPerPixel = function (texture, color, canvas) { +CanvasTinter.tintWithPerPixel = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -167,7 +174,8 @@ var pixels = pixelData.data; - for (var i = 0; i < pixels.length; i += 4) { + for (var i = 0; i < pixels.length; i += 4) + { pixels[i+0] *= r; pixels[i+1] *= g; pixels[i+2] *= b; @@ -181,7 +189,8 @@ * * @param color {number} the color to round, should be a hex color */ -CanvasTinter.roundColor = function (color) { +CanvasTinter.roundColor = function (color) +{ var step = CanvasTinter.cacheStepsPerColorChannel; var rgbValues = utils.hex2rgb(color); diff --git a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js index 9f2f89a..35edbaf 100644 --- a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js +++ b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLBlendModeManager(renderer) { +function WebGLBlendModeManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -23,8 +24,10 @@ * * @param blendMode {number} the blendMode, should be a Pixi const, such as BlendModes.ADD */ -WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) { - if (this.currentBlendMode === blendMode) { +WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) +{ + if (this.currentBlendMode === blendMode) + { return false; } diff --git a/src/core/renderers/webgl/managers/WebGLFilterManager.js b/src/core/renderers/webgl/managers/WebGLFilterManager.js index 1179258..2dac048 100644 --- a/src/core/renderers/webgl/managers/WebGLFilterManager.js +++ b/src/core/renderers/webgl/managers/WebGLFilterManager.js @@ -7,7 +7,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLFilterManager(renderer) { +function WebGLFilterManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -32,7 +33,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.texturePool.length = 0; self.initShaderBuffers(); }); @@ -46,7 +48,8 @@ * @param renderer {WebGLRenderer} * @param buffer {ArrayBuffer} */ -WebGLFilterManager.prototype.begin = function (buffer) { +WebGLFilterManager.prototype.begin = function (buffer) +{ this.defaultShader = this.renderer.shaderManager.defaultShader; this.width = this.renderer.projection.x * 2; @@ -60,7 +63,8 @@ * * @param filterBlock {object} the filter that will be pushed to the current filter stack */ -WebGLFilterManager.prototype.pushFilter = function (filterBlock) { +WebGLFilterManager.prototype.pushFilter = function (filterBlock) +{ var gl = this.renderer.gl; var projection = this.renderer.projection; @@ -78,10 +82,12 @@ this.offsetY += filterBlock._filterArea.y; var texture = this.texturePool.pop(); - if (!texture) { + if (!texture) + { texture = new FilterTexture(this.renderer.gl, this.width, this.height); } - else { + else + { texture.resize(this.width, this.height); } @@ -98,29 +104,35 @@ var localX = filterArea.x, localY = filterArea.y; - if (filterArea.x < 0) { + if (filterArea.x < 0) + { filterArea.width += filterArea.x; filterArea.x = 0; } - if (filterArea.y < 0) { + if (filterArea.y < 0) + { filterArea.height += filterArea.y; filterArea.y = 0; } - if (localX + filterArea.width > this.width) { + if (localX + filterArea.width > this.width) + { filterArea.width = this.width - localX; } - if (localY + filterArea.height > this.height) { + if (localY + filterArea.height > this.height) + { filterArea.height = this.height - localY; } - if (filterArea.width < 0) { + if (filterArea.width < 0) + { filterArea.width = 0; } - if (filterArea.height < 0) { + if (filterArea.height < 0) + { filterArea.height = 0; } @@ -154,7 +166,8 @@ * Removes the last filter from the filter stack and doesn't return it. * */ -WebGLFilterManager.prototype.popFilter = function () { +WebGLFilterManager.prototype.popFilter = function () +{ var gl = this.renderer.gl; var filterBlock = this.filterStack.pop(); @@ -163,7 +176,8 @@ var projection = this.renderer.projection; var offset = this.renderer.offset; - if (filterBlock.filterPasses.length > 1) { + if (filterBlock.filterPasses.length > 1) + { gl.viewport(0, 0, filterArea.width, filterArea.height); gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); @@ -193,7 +207,8 @@ var inputTexture = texture; var outputTexture = this.texturePool.pop(); - if (!outputTexture) { + if (!outputTexture) + { outputTexture = new FilterTexture(this.renderer.gl, this.width, this.height); } outputTexture.resize(this.width, this.height); @@ -204,7 +219,8 @@ gl.disable(gl.BLEND); - for (var i = 0; i < filterBlock.filterPasses.length-1; i++) { + for (var i = 0; i < filterBlock.filterPasses.length-1; i++) + { var filterPass = filterBlock.filterPasses[i]; gl.bindFramebuffer(gl.FRAMEBUFFER, outputTexture.frameBuffer ); @@ -243,10 +259,12 @@ var buffer = this.buffer; // time to render the filters texture to the previous scene - if (this.filterStack.length === 0) { + if (this.filterStack.length === 0) + { gl.colorMask(true, true, true, true);//this.transparent); } - else { + else + { var currentFilter = this.filterStack[this.filterStack.length-1]; filterArea = currentFilter._filterArea; @@ -332,13 +350,15 @@ * @param width {number} the horizontal range of the filter * @param height {number} the vertical range of the filter */ -WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) { +WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) +{ // use program var gl = this.renderer.gl; var shader = filter.shaders[gl.id]; - if (!shader) { + if (!shader) + { shader = new Shader(gl); shader.fragmentSrc = filter.fragmentSrc; @@ -356,7 +376,8 @@ gl.uniform2f(shader.projectionVector, width/2, -height/2); gl.uniform2f(shader.offsetVector, 0,0); - if (filter.uniforms.dimensions) { + 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]; @@ -386,7 +407,8 @@ * Initialises the shader buffers. * */ -WebGLFilterManager.prototype.initShaderBuffers = function () { +WebGLFilterManager.prototype.initShaderBuffers = function () +{ var gl = this.renderer.gl; // create some buffers @@ -432,7 +454,8 @@ * Destroys the filter and removes it from the filter stack. * */ -WebGLFilterManager.prototype.destroy = function () { +WebGLFilterManager.prototype.destroy = function () +{ var gl = this.renderer.gl; this.filterStack = null; @@ -441,7 +464,8 @@ this.offsetY = 0; // destroy textures - for (var i = 0; i < this.texturePool.length; i++) { + for (var i = 0; i < this.texturePool.length; i++) + { this.texturePool[i].destroy(); } diff --git a/src/core/renderers/webgl/managers/WebGLManager.js b/src/core/renderers/webgl/managers/WebGLManager.js index 9d47b5c..c30cd51 100644 --- a/src/core/renderers/webgl/managers/WebGLManager.js +++ b/src/core/renderers/webgl/managers/WebGLManager.js @@ -3,7 +3,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLManager(renderer) { +function WebGLManager(renderer) +{ /** * The renderer this manager works for. * @@ -15,6 +16,7 @@ WebGLManager.prototype.constructor = WebGLManager; module.exports = WebGLManager; -WebGLManager.prototype.destroy = function () { +WebGLManager.prototype.destroy = function () +{ this.renderer = null; }; diff --git a/src/core/renderers/webgl/managers/WebGLMaskManager.js b/src/core/renderers/webgl/managers/WebGLMaskManager.js index 2f90b64..e568812 100644 --- a/src/core/renderers/webgl/managers/WebGLMaskManager.js +++ b/src/core/renderers/webgl/managers/WebGLMaskManager.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLMaskManager(renderer) { +function WebGLMaskManager(renderer) +{ WebGLManager.call(this, renderer); } @@ -19,12 +20,15 @@ * * @param maskData {any[]} */ -WebGLMaskManager.prototype.pushMask = function (maskData) { - if (maskData.dirty) { +WebGLMaskManager.prototype.pushMask = function (maskData) +{ + if (maskData.dirty) + { WebGLGraphics.updateGraphics(maskData, this.renderer.gl); } - if (!maskData._webGL[this.renderer.gl.id].data.length) { + if (!maskData._webGL[this.renderer.gl.id].data.length) + { return; } @@ -36,6 +40,7 @@ * * @param maskData {any[]} */ -WebGLMaskManager.prototype.popMask = function (maskData) { +WebGLMaskManager.prototype.popMask = function (maskData) +{ this.renderer.stencilManager.popStencil(maskData, maskData._webGL[this.renderer.gl.id].data[0], this.renderer); }; diff --git a/src/core/renderers/webgl/managers/WebGLShaderManager.js b/src/core/renderers/webgl/managers/WebGLShaderManager.js index fef071c..90c6477 100644 --- a/src/core/renderers/webgl/managers/WebGLShaderManager.js +++ b/src/core/renderers/webgl/managers/WebGLShaderManager.js @@ -10,7 +10,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLShaderManager(renderer) { +function WebGLShaderManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -28,7 +29,8 @@ */ this.tempAttribState = []; - for (var i = 0; i < this.maxAttibs; i++) { + for (var i = 0; i < this.maxAttibs; i++) + { this.attribState[i] = false; } @@ -66,7 +68,8 @@ // listen for context and update necessary shaders var self = this; - this.renderer.on('context', function (event) { + this.renderer.on('context', function (event) + { var gl = event.data; // this shader is used for rendering primitives @@ -97,29 +100,36 @@ * * @param attribs {Array} attribs */ -WebGLShaderManager.prototype.setAttribs = function (attribs) { +WebGLShaderManager.prototype.setAttribs = function (attribs) +{ // reset temp state var i; - for (i = 0; i < this.tempAttribState.length; i++) { + for (i = 0; i < this.tempAttribState.length; i++) + { this.tempAttribState[i] = false; } // set the new attribs - for (var a in attribs) { + for (var a in attribs) + { this.tempAttribState[attribs[a]] = true; } var gl = this.renderer.gl; - for (i = 0; i < this.attribState.length; i++) { - if (this.attribState[i] !== this.tempAttribState[i]) { + for (i = 0; i < this.attribState.length; i++) + { + if (this.attribState[i] !== this.tempAttribState[i]) + { this.attribState[i] = this.tempAttribState[i]; - if (this.attribState[i]) { + if (this.attribState[i]) + { gl.enableVertexAttribArray(i); } - else { + else + { gl.disableVertexAttribArray(i); } } @@ -131,8 +141,10 @@ * * @param shader {Any} */ -WebGLShaderManager.prototype.setShader = function (shader) { - if (this._currentId === shader.uuid) { +WebGLShaderManager.prototype.setShader = function (shader) +{ + if (this._currentId === shader.uuid) + { return false; } @@ -150,7 +162,8 @@ * Destroys this object. * */ -WebGLShaderManager.prototype.destroy = function () { +WebGLShaderManager.prototype.destroy = function () +{ this.attribState = null; this.tempAttribState = null; diff --git a/src/core/renderers/webgl/managers/WebGLStencilManager.js b/src/core/renderers/webgl/managers/WebGLStencilManager.js index 9ec6398..4cb0134 100644 --- a/src/core/renderers/webgl/managers/WebGLStencilManager.js +++ b/src/core/renderers/webgl/managers/WebGLStencilManager.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLStencilManager(renderer) { +function WebGLStencilManager(renderer) +{ WebGLManager.call(this, renderer); this.stencilStack = []; @@ -24,12 +25,14 @@ * @param graphics {Graphics} * @param webGLData {any[]} */ -WebGLStencilManager.prototype.pushStencil = function (graphics, webGLData) { +WebGLStencilManager.prototype.pushStencil = function (graphics, webGLData) +{ var gl = this.renderer.gl; this.bindGraphics(graphics, webGLData, this.renderer); - if (this.stencilStack.length === 0) { + if (this.stencilStack.length === 0) + { gl.enable(gl.STENCIL_TEST); gl.clear(gl.STENCIL_BUFFER_BIT); this.reverse = true; @@ -47,14 +50,17 @@ // draw the triangle strip! - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } @@ -62,31 +68,38 @@ // draw a quad to increment.. gl.drawElements(gl.TRIANGLE_FAN, 4, gl.UNSIGNED_SHORT, ( webGLData.indices.length - 4 ) * 2 ); - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); } this.reverse = !this.reverse; } - else { - if (!this.reverse) { + else + { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } - else { + 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) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); } } @@ -103,7 +116,8 @@ * @param graphics {Graphics} * @param webGLData {Array} */ -WebGLStencilManager.prototype.bindGraphics = function (graphics, webGLData) { +WebGLStencilManager.prototype.bindGraphics = function (graphics, webGLData) +{ //if (this._currentGraphics === graphics)return; this._currentGraphics = graphics; @@ -114,7 +128,8 @@ offset = this.renderer.offset, shader;// = this.renderer.shaderManager.primitiveShader; - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { shader = this.renderer.shaderManager.complexPrimitiveShader; this.renderer.shaderManager.setShader(shader); @@ -141,7 +156,8 @@ // set the index buffer! gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, webGLData.indexBuffer); } - else { + else + { //this.renderer.shaderManager.activatePrimitiveShader(); shader = this.renderer.shaderManager.primitiveShader; this.renderer.shaderManager.setShader( shader ); @@ -154,7 +170,7 @@ gl.uniform2f(shader.uniforms.offsetVector._location, -offset.x, -offset.y); gl.uniform3fv(shader.uniforms.tint._location, utils.hex2rgb(graphics.tint)); - + gl.uniform1f(shader.uniforms.alpha._location, graphics.worldAlpha); @@ -172,19 +188,22 @@ * @param graphics {Graphics} * @param webGLData {Array} */ -WebGLStencilManager.prototype.popStencil = function (graphics, webGLData) { +WebGLStencilManager.prototype.popStencil = function (graphics, webGLData) +{ var gl = this.renderer.gl; this.stencilStack.pop(); this.count--; - if (this.stencilStack.length === 0) { + if (this.stencilStack.length === 0) + { // the stack is empty! gl.disable(gl.STENCIL_TEST); } - else { + else + { var level = this.count; @@ -192,14 +211,17 @@ gl.colorMask(false, false, false, false); - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { this.reverse = !this.reverse; - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } @@ -213,31 +235,38 @@ // draw the triangle strip! gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); - if (!this.reverse) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); } } - else { + else + { // console.log("<<>>") - if (!this.reverse) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } - else { + 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) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); } } @@ -253,7 +282,8 @@ * Destroys the mask stack. * */ -WebGLStencilManager.prototype.destroy = function () { +WebGLStencilManager.prototype.destroy = function () +{ this.renderer = null; this.stencilStack = null; }; diff --git a/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js b/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js index 913ba5e..1ea7d19 100644 --- a/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js +++ b/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function ComplexPrimitiveShader(gl) { +function ComplexPrimitiveShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -24,7 +25,8 @@ 'uniform float flipY;', 'varying vec4 vColor;', - 'void main(void) {', + '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);', @@ -37,7 +39,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = vColor;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/FastShader.js b/src/core/renderers/webgl/shaders/FastShader.js index bd2e29a..2e5e060 100644 --- a/src/core/renderers/webgl/shaders/FastShader.js +++ b/src/core/renderers/webgl/shaders/FastShader.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function FastShader(gl) { +function FastShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -28,7 +29,8 @@ 'const vec2 center = vec2(-1.0, 1.0);', - 'void main(void) {', + 'void main(void) + {', ' vec2 v;', ' vec2 sv = aVertexPosition * aScale;', ' v.x = (sv.x) * cos(aRotation) - (sv.y) * sin(aRotation);', @@ -49,7 +51,8 @@ 'uniform sampler2D uSampler;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/PrimitiveShader.js b/src/core/renderers/webgl/shaders/PrimitiveShader.js index 6f25409..a25f54f 100644 --- a/src/core/renderers/webgl/shaders/PrimitiveShader.js +++ b/src/core/renderers/webgl/shaders/PrimitiveShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function PrimitiveShader(gl) { +function PrimitiveShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -23,7 +24,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + '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);', @@ -36,7 +38,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = vColor;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/Shader.js b/src/core/renderers/webgl/shaders/Shader.js index f8964f5..fd75ef5 100644 --- a/src/core/renderers/webgl/shaders/Shader.js +++ b/src/core/renderers/webgl/shaders/Shader.js @@ -6,7 +6,8 @@ * @param [fragmentSrc] {string} The source of the fragment shader. * @param [vertexSrc] {string} The source of the vertex shader. */ -function Shader(gl, vertexSrc, fragmentSrc, customUniforms, customAttributes) { +function Shader(gl, vertexSrc, fragmentSrc, customUniforms, customAttributes) +{ /** * @member {number} * @readonly @@ -33,7 +34,8 @@ dimensions: { type: '4f', value: new Float32Array(4) } }; - for (var u in customUniforms) { + for (var u in customUniforms) + { this.uniforms[u] = customUniforms[u]; } @@ -43,7 +45,8 @@ aColor: 0 }; - for (var a in customAttributes) { + for (var a in customAttributes) + { this.attributes[a] = customAttributes[a]; } @@ -66,7 +69,8 @@ 'const vec2 center = vec2(-1.0, 1.0);', - 'void main(void) {', + 'void main(void) + {', ' gl_Position = vec4( ((aVertexPosition + offsetVector) / projectionVector) + center , 0.0, 1.0);', ' vTextureCoord = aTextureCoord;', ' vColor = vec4(aColor.rgb * aColor.a, aColor.a);', @@ -85,7 +89,8 @@ 'uniform sampler2D uSampler;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;', '}' ].join('\n'); @@ -96,7 +101,8 @@ Shader.prototype.constructor = Shader; module.exports = Shader; -Shader.prototype.init = function () { +Shader.prototype.init = function () +{ this.compile(); this.gl.useProgram(this.program); @@ -105,14 +111,18 @@ this.cacheAttributeLocations(Object.keys(this.attributes)); }; -Shader.prototype.cacheUniformLocations = function (keys) { - for (var i = 0; i < keys.length; ++i) { +Shader.prototype.cacheUniformLocations = function (keys) +{ + for (var i = 0; i < keys.length; ++i) + { this.uniforms[keys[i]]._location = this.gl.getUniformLocation(this.program, keys[i]); } }; -Shader.prototype.cacheAttributeLocations = function (keys) { - for (var i = 0; i < keys.length; ++i) { +Shader.prototype.cacheAttributeLocations = function (keys) +{ + for (var i = 0; i < keys.length; ++i) + { this.attributes[keys[i]] = this.gl.getAttribLocation(this.program, keys[i]); } @@ -124,14 +134,16 @@ // 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.attributes.aColor === -1) { + // if (this.attributes.aColor === -1) + { // this.attributes.aColor = 2; // } // End worst hack eva // }; -Shader.prototype.compile = function () { +Shader.prototype.compile = function () +{ var gl = this.gl; var glVertShader = this._glCompile(gl.VERTEX_SHADER, this.vertexSrc); @@ -144,13 +156,15 @@ gl.linkProgram(program); // if linking fails, then log and cleanup - if (!gl.getProgramParameter(program, gl.LINK_STATUS)) { + if (!gl.getProgramParameter(program, gl.LINK_STATUS)) + { window.console.error('Pixi.js Error: Could not initialize shader.'); window.console.error('gl.VALIDATE_STATUS', gl.getProgramParameter(program, gl.VALIDATE_STATUS)); window.console.error('gl.getError()', gl.getError()); // if there is a program info log, log it - if (gl.getProgramInfoLog(program) !== '') { + if (gl.getProgramInfoLog(program) !== '') + { window.console.warn('Pixi.js Warning: gl.getProgramInfoLog()', gl.getProgramInfoLog(program)); } @@ -165,18 +179,21 @@ return (this.program = program); }; -Shader.prototype.syncUniforms = function () { +Shader.prototype.syncUniforms = function () +{ var gl = this.gl; this.textureCount = 1; - for (var key in this.uniforms) { + for (var key in this.uniforms) + { var uniform = this.uniforms[key], location = uniform._location, value = uniform.value, i, il; - switch (uniform.type) { + switch (uniform.type) + { // single int value case 'i': case '1i': @@ -282,7 +299,8 @@ // a Color Value case 'c': - if (typeof value === 'number') { + if (typeof value === 'number') + { value = utils.hex2rgb(value); } @@ -311,11 +329,13 @@ // array of 2D Point objects case 'v2v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(2 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 2] = value[i].x; uniform._array[i * 2 + 1] = value[i].y; } @@ -325,11 +345,13 @@ // array of 3D Point objects case 'v3v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(3 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 3] = value[i].x; uniform._array[i * 3 + 1] = value[i].y; uniform._array[i * 3 + 2] = value[i].z; @@ -341,11 +363,13 @@ // array of 4D Point objects case 'v4v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(4 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 4] = value[i].x; uniform._array[i * 4 + 1] = value[i].y; uniform._array[i * 4 + 2] = value[i].z; @@ -359,7 +383,8 @@ // PIXI.Texture case 't': case 'sampler2D': - if (!uniform.value || !uniform.value.baseTexture || !uniform.value.baseTexture.hasLoaded) { + if (!uniform.value || !uniform.value.baseTexture || !uniform.value.baseTexture.hasLoaded) + { break; } @@ -376,7 +401,8 @@ this.textureCount++; // initialize the texture if we haven't yet - if (!uniform._init) { + if (!uniform._init) + { this.initSampler2D(uniform); uniform._init = true; @@ -394,11 +420,13 @@ * Initialises a Sampler2D uniform (which may only be available later on after initUniforms once the texture has loaded) * */ -Shader.prototype.initSampler2D = function (uniform) { +Shader.prototype.initSampler2D = function (uniform) +{ var gl = this.gl; // Extended texture data - if (uniform.textureData) { + if (uniform.textureData) + { var data = uniform.textureData; // GLTexture = mag linear, min linear_mipmap_linear, wrap repeat + gl.generateMipmap(gl.TEXTURE_2D); @@ -417,14 +445,16 @@ var wrapT = (data.wrapT) ? data.wrapT : gl.CLAMP_TO_EDGE; var format = (data.luminance) ? gl.LUMINANCE : gl.RGBA; - if (data.repeat) { + if (data.repeat) + { wrapS = gl.REPEAT; wrapT = gl.REPEAT; } gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, !!data.flipY); - if (data.width) { + if (data.width) + { var width = (data.width) ? data.width : 512; var height = (data.height) ? data.height : 2; var border = (data.border) ? data.border : 0; @@ -432,7 +462,8 @@ // 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 { + 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); } @@ -448,7 +479,8 @@ * Destroys the shader. * */ -Shader.prototype.destroy = function () { +Shader.prototype.destroy = function () +{ this.gl.deleteProgram(this.program); this.gl = null; @@ -459,13 +491,15 @@ this.fragmentSrc = null; }; -Shader.prototype._glCompile = function (type, src) { +Shader.prototype._glCompile = function (type, src) +{ var shader = this.gl.createShader(type); this.gl.shaderSource(shader, src); this.gl.compileShader(shader); - if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) { + if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) + { window.console.log(this.gl.getShaderInfoLog(shader)); return null; } diff --git a/src/core/renderers/webgl/shaders/StripShader.js b/src/core/renderers/webgl/shaders/StripShader.js index 193f6e1..a7abcc6 100644 --- a/src/core/renderers/webgl/shaders/StripShader.js +++ b/src/core/renderers/webgl/shaders/StripShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function StripShader(gl) { +function StripShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -20,7 +21,8 @@ 'varying vec2 vTextureCoord;', - 'void main(void) {', + '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);', @@ -36,7 +38,8 @@ 'varying vec2 vTextureCoord;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vec2(vTextureCoord.x, vTextureCoord.y)) * alpha;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/utils/FilterTexture.js b/src/core/renderers/webgl/utils/FilterTexture.js index d2c8423..4433d44 100644 --- a/src/core/renderers/webgl/utils/FilterTexture.js +++ b/src/core/renderers/webgl/utils/FilterTexture.js @@ -8,7 +8,8 @@ * @param height {number} the vertical range of the filter * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values */ -function FilterTexture(gl, width, height, scaleMode) { +function FilterTexture(gl, width, height, scaleMode) +{ /** * @member {WebGLContext} */ @@ -59,7 +60,8 @@ * Clears the filter texture. * */ -FilterTexture.prototype.clear = function () { +FilterTexture.prototype.clear = function () +{ var gl = this.gl; gl.clearColor(0,0,0, 0); @@ -72,8 +74,10 @@ * @param width {number} the new width of the texture * @param height {number} the new height of the texture */ -FilterTexture.prototype.resize = function (width, height) { - if (this.width === width && this.height === height) { +FilterTexture.prototype.resize = function (width, height) +{ + if (this.width === width && this.height === height) + { return; } @@ -96,7 +100,8 @@ * Destroys the filter texture. * */ -FilterTexture.prototype.destroy = function () { +FilterTexture.prototype.destroy = function () +{ var gl = this.gl; gl.deleteFramebuffer( this.frameBuffer ); gl.deleteTexture( this.texture ); diff --git a/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js b/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js index c4721e9..a63f4d7 100644 --- a/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js +++ b/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js @@ -14,7 +14,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this sprite batch works for. */ -function WebGLFastSpriteBatch(renderer) { +function WebGLFastSpriteBatch(renderer) +{ /** * The renderer instance this sprite batch operates on. * @@ -91,7 +92,8 @@ */ this.lastIndexCount = 0; - for (var i=0, j=0; i < numIndices; i += 6, j += 4) { + 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; @@ -144,7 +146,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.setupContext(); }); } @@ -157,7 +160,8 @@ * * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLFastSpriteBatch.prototype.setupContext = function () { +WebGLFastSpriteBatch.prototype.setupContext = function () +{ var gl = this.renderer.gl; // create a couple of buffers @@ -177,7 +181,8 @@ /** * @param spriteBatch {SpriteBatch} The SpriteBatch container to prepare for. */ -WebGLFastSpriteBatch.prototype.begin = function (spriteBatch) { +WebGLFastSpriteBatch.prototype.begin = function (spriteBatch) +{ this.shader = this.renderer.shaderManager.fastShader; this.matrix = spriteBatch.worldTransform.toArray(true); @@ -187,33 +192,38 @@ /** */ -WebGLFastSpriteBatch.prototype.end = function () { +WebGLFastSpriteBatch.prototype.end = function () +{ this.flush(); }; /** * @param spriteBatch {SpriteBatch} The SpriteBatch container to render. */ -WebGLFastSpriteBatch.prototype.render = function (spriteBatch) { +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) { + if (!sprite.texture._uvs) + { return; } this.currentBaseTexture = sprite.texture.baseTexture; // check blend mode - if (sprite.blendMode !== this.renderer.blendModeManager.currentBlendMode) { + if (sprite.blendMode !== this.renderer.blendModeManager.currentBlendMode) + { this.flush(); this.renderer.blendModeManager.setBlendMode(sprite.blendMode); } - for (var i=0,j= children.length; i= this.size) { + if (this.currentBatchSize >= this.size) + { this.flush(); } }; @@ -362,29 +379,35 @@ /** * */ -WebGLFastSpriteBatch.prototype.flush = function () { +WebGLFastSpriteBatch.prototype.flush = function () +{ // If the batch is length 0 then return as there is nothing to draw - if (this.currentBatchSize === 0) { + if (this.currentBatchSize === 0) + { return; } var gl = this.renderer.gl; // bind the current texture - if (!this.currentBaseTexture._glTextures[gl.id]) { + if (!this.currentBaseTexture._glTextures[gl.id]) + { this.renderer.updateTexture(this.currentBaseTexture, gl); } //TODO-SHOUD THIS BE ELSE??!?!?! - else { + else + { gl.bindTexture(gl.TEXTURE_2D, this.currentBaseTexture._glTextures[gl.id]); } // upload the verts to the buffer - if (this.currentBatchSize > ( this.size * 0.5 ) ) { + if (this.currentBatchSize > ( this.size * 0.5 ) ) + { gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); } - else { + else + { var view = this.vertices.subarray(0, this.currentBatchSize * this.vertByteSize); gl.bufferSubData(gl.ARRAY_BUFFER, 0, view); @@ -405,14 +428,16 @@ * Ends the batch and flushes * */ -WebGLFastSpriteBatch.prototype.stop = function () { +WebGLFastSpriteBatch.prototype.stop = function () +{ this.flush(); }; /** * */ -WebGLFastSpriteBatch.prototype.start = function () { +WebGLFastSpriteBatch.prototype.start = function () +{ var gl = this.renderer.gl; // bind the main texture diff --git a/src/core/renderers/webgl/utils/WebGLGraphics.js b/src/core/renderers/webgl/utils/WebGLGraphics.js index 55f4911..ab8f46e 100644 --- a/src/core/renderers/webgl/utils/WebGLGraphics.js +++ b/src/core/renderers/webgl/utils/WebGLGraphics.js @@ -19,7 +19,8 @@ * @param graphics {Graphics} * @param renderer {WebGLRenderer} */ -WebGLGraphics.renderGraphics = function (graphics, renderer) {//projection, offset) { +WebGLGraphics.renderGraphics = function (graphics, renderer) {//projection, offset) +{ var gl = renderer.gl; var projection = renderer.projection, @@ -27,7 +28,8 @@ shader = renderer.shaderManager.primitiveShader, webGLData; - if (graphics.dirty) { + if (graphics.dirty) + { WebGLGraphics.updateGraphics(graphics, gl); } @@ -35,8 +37,10 @@ // This could be speeded up for sure! - for (var i = 0; i < webGL.data.length; i++) { - if (webGL.data[i].mode === 1) { + for (var i = 0; i < webGL.data.length; i++) + { + if (webGL.data[i].mode === 1) + { webGLData = webGL.data[i]; renderer.stencilManager.pushStencil(graphics, webGLData, renderer); @@ -46,7 +50,8 @@ renderer.stencilManager.popStencil(graphics, webGLData, renderer); } - else { + else + { webGLData = webGL.data[i]; @@ -84,12 +89,14 @@ * @param graphicsData {Graphics} The graphics object to update * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLGraphics.updateGraphics = function (graphics, gl) { +WebGLGraphics.updateGraphics = function (graphics, gl) +{ // get the contexts graphics object var webGL = graphics._webGL[gl.id]; // if the graphics object does not exist in the webGL context time to create it! - if (!webGL) { + if (!webGL) + { webGL = graphics._webGL[gl.id] = {lastIndex:0, data:[], gl:gl}; } @@ -99,11 +106,13 @@ var i; // if the user cleared the graphics object we will need to clear every object - if (graphics.clearDirty) { + if (graphics.clearDirty) + { graphics.clearDirty = false; // lop through and return all the webGLDatas to the object pool so than can be reused later on - for (i = 0; i < webGL.data.length; i++) { + for (i = 0; i < webGL.data.length; i++) + { var graphicsData = webGL.data[i]; graphicsData.reset(); WebGLGraphics.graphicsDataPool.push( graphicsData ); @@ -119,58 +128,72 @@ // loop through the graphics datas and construct each one.. // if the object is a complex fill then the new stencil buffer technique will be used // other wise graphics objects will be pushed into a batch.. - for (i = webGL.lastIndex; i < graphics.graphicsData.length; i++) { + for (i = webGL.lastIndex; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { // need to add the points the the graphics object.. data.points = data.shape.points.slice(); - if (data.shape.closed) { + if (data.shape.closed) + { // close the poly if the value is true! - if (data.points[0] !== data.points[data.points.length-2] || data.points[1] !== data.points[data.points.length-1]) { + if (data.points[0] !== data.points[data.points.length-2] || data.points[1] !== data.points[data.points.length-1]) + { data.points.push(data.points[0], data.points[1]); } } // MAKE SURE WE HAVE THE CORRECT TYPE.. - if (data.fill) { - if (data.points.length >= 6) { - if (data.points.length < 6 * 2) { + if (data.fill) + { + if (data.points.length >= 6) + { + if (data.points.length < 6 * 2) + { webGLData = WebGLGraphics.switchMode(webGL, 0); var canDrawUsingSimple = WebGLGraphics.buildPoly(data, webGLData); // console.log(canDrawUsingSimple); - if (!canDrawUsingSimple) { + if (!canDrawUsingSimple) + { // console.log("<>>>") webGLData = WebGLGraphics.switchMode(webGL, 1); WebGLGraphics.buildComplexPoly(data, webGLData); } } - else { + else + { webGLData = WebGLGraphics.switchMode(webGL, 1); WebGLGraphics.buildComplexPoly(data, webGLData); } } } - if (data.lineWidth > 0) { + if (data.lineWidth > 0) + { webGLData = WebGLGraphics.switchMode(webGL, 0); WebGLGraphics.buildLine(data, webGLData); } } - else { + else + { webGLData = WebGLGraphics.switchMode(webGL, 0); - if (data.type === CONST.SHAPES.RECT) { + if (data.type === CONST.SHAPES.RECT) + { WebGLGraphics.buildRectangle(data, webGLData); } - else if (data.type === CONST.SHAPES.CIRC || data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.CIRC || data.type === CONST.SHAPES.ELIP) + { WebGLGraphics.buildCircle(data, webGLData); } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { WebGLGraphics.buildRoundedRectangle(data, webGLData); } } @@ -179,10 +202,12 @@ } // upload all the dirty data... - for (i = 0; i < webGL.data.length; i++) { + for (i = 0; i < webGL.data.length; i++) + { webGLData = webGL.data[i]; - if (webGLData.dirty) { + if (webGLData.dirty) + { webGLData.upload(); } } @@ -194,18 +219,22 @@ * @param webGL {WebGLContext} * @param type {number} */ -WebGLGraphics.switchMode = function (webGL, type) { +WebGLGraphics.switchMode = function (webGL, type) +{ var webGLData; - if (!webGL.data.length) { + if (!webGL.data.length) + { webGLData = WebGLGraphics.graphicsDataPool.pop() || new WebGLGraphicsData(webGL.gl); webGLData.mode = type; webGL.data.push(webGLData); } - else { + else + { webGLData = webGL.data[webGL.data.length-1]; - if (webGLData.mode !== type || type === 1) { + if (webGLData.mode !== type || type === 1) + { webGLData = WebGLGraphics.graphicsDataPool.pop() || new WebGLGraphicsData(webGL.gl); webGLData.mode = type; webGL.data.push(webGLData); @@ -225,7 +254,8 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildRectangle = function (graphicsData, webGLData) { +WebGLGraphics.buildRectangle = function (graphicsData, webGLData) +{ // --- // // need to convert points to a nice regular data // @@ -235,7 +265,8 @@ var width = rectData.width; var height = rectData.height; - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -265,7 +296,8 @@ indices.push(vertPos, vertPos, vertPos+1, vertPos+2, vertPos+3, vertPos+3); } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = [x, y, @@ -289,7 +321,8 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildRoundedRectangle = function (graphicsData, webGLData) { +WebGLGraphics.buildRoundedRectangle = function (graphicsData, webGLData) +{ var rrectData = graphicsData.shape; var x = rrectData.x; var y = rrectData.y; @@ -305,7 +338,8 @@ recPoints = recPoints.concat(WebGLGraphics.quadraticBezierCurve(x + width, y + radius, x + width, y, x + width - radius, y)); recPoints = recPoints.concat(WebGLGraphics.quadraticBezierCurve(x + radius, y, x, y, x, y + radius)); - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -323,7 +357,8 @@ // var i = 0; - for (i = 0; i < triangles.length; i+=3) { + for (i = 0; i < triangles.length; i+=3) + { indices.push(triangles[i] + vecPos); indices.push(triangles[i] + vecPos); indices.push(triangles[i+1] + vecPos); @@ -332,12 +367,14 @@ } - for (i = 0; i < recPoints.length; i++) { + for (i = 0; i < recPoints.length; i++) + { verts.push(recPoints[i], recPoints[++i], r, g, b, alpha); } } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = recPoints; @@ -362,7 +399,8 @@ * @param toY {number} Destination point y * @return {number[]} */ -WebGLGraphics.quadraticBezierCurve = function (fromX, fromY, cpX, cpY, toX, toY) { +WebGLGraphics.quadraticBezierCurve = function (fromX, fromY, cpX, cpY, toX, toY) +{ var xa, ya, @@ -373,14 +411,16 @@ n = 20, points = []; - function getPt(n1 , n2, perc) { + function getPt(n1 , n2, perc) + { var diff = n2 - n1; return n1 + ( diff * perc ); } var j = 0; - for (var i = 0; i <= n; i++ ) { + for (var i = 0; i <= n; i++ ) + { j = i / n; // The Green Line @@ -406,7 +446,8 @@ * @param graphicsData {Graphics} The graphics object to draw * @param webGLData {object} */ -WebGLGraphics.buildCircle = function (graphicsData, webGLData) { +WebGLGraphics.buildCircle = function (graphicsData, webGLData) +{ // need to convert points to a nice regular data var circleData = graphicsData.shape; var x = circleData.x; @@ -415,11 +456,13 @@ var height; // TODO - bit hacky?? - if (graphicsData.type === CONST.SHAPES.CIRC) { + if (graphicsData.type === CONST.SHAPES.CIRC) + { width = circleData.radius; height = circleData.radius; } - else { + else + { width = circleData.width; height = circleData.height; } @@ -429,7 +472,8 @@ var i = 0; - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -444,7 +488,8 @@ indices.push(vecPos); - for (i = 0; i < totalSegs + 1 ; i++) { + for (i = 0; i < totalSegs + 1 ; i++) + { verts.push(x,y, r, g, b, alpha); verts.push(x + Math.sin(seg * i) * width, @@ -457,12 +502,14 @@ indices.push(vecPos-1); } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = []; - for (i = 0; i < totalSegs + 1; i++) { + for (i = 0; i < totalSegs + 1; i++) + { graphicsData.points.push(x + Math.sin(seg * i) * width, y + Math.cos(seg * i) * height); } @@ -481,18 +528,22 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildLine = function (graphicsData, webGLData) { +WebGLGraphics.buildLine = function (graphicsData, webGLData) +{ // TODO OPTIMISE! var i = 0; var points = graphicsData.points; - if (points.length === 0) { + if (points.length === 0) + { return; } // if the line width is an odd number add 0.5 to align to a whole pixel - if (graphicsData.lineWidth%2) { - for (i = 0; i < points.length; i++) { + if (graphicsData.lineWidth%2) + { + for (i = 0; i < points.length; i++) + { points[i] += 0.5; } } @@ -502,7 +553,8 @@ var lastPoint = new math.Point(points[points.length - 2], points[points.length - 1]); // if the first point is the last point - gonna have issues :) - if (firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) { + if (firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) + { // need to clone as we are going to slightly modify the shape.. points = points.slice(); @@ -562,7 +614,8 @@ verts.push(p1x + perpx , p1y + perpy, r, g, b, alpha); - for (i = 1; i < length-1; i++) { + for (i = 1; i < length-1; i++) + { p1x = points[(i-1)*2]; p1y = points[(i-1)*2 + 1]; @@ -599,7 +652,8 @@ denom = a1*b2 - a2*b1; - if (Math.abs(denom) < 0.1 ) { + if (Math.abs(denom) < 0.1 ) + { denom+=10.1; verts.push(p2x - perpx , p2y - perpy, @@ -618,7 +672,8 @@ pdist = (px -p2x) * (px -p2x) + (py -p2y) + (py -p2y); - if (pdist > 140 * 140) { + if (pdist > 140 * 140) + { perp3x = perpx - perp2x; perp3y = perpy - perp2y; @@ -639,7 +694,8 @@ indexCount++; } - else { + else + { verts.push(px , py); verts.push(r, g, b, alpha); @@ -672,7 +728,8 @@ indices.push(indexStart); - for (i = 0; i < indexCount; i++) { + for (i = 0; i < indexCount; i++) + { indices.push(indexStart++); } @@ -687,11 +744,13 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildComplexPoly = function (graphicsData, webGLData) { +WebGLGraphics.buildComplexPoly = function (graphicsData, webGLData) +{ //TODO - no need to copy this as it gets turned into a FLoat32Array anyways.. var points = graphicsData.points.slice(); - if (points.length < 6) { + if (points.length < 6) + { return; } @@ -711,7 +770,8 @@ var x,y; // get size.. - for (var i = 0; i < points.length; i+=2) { + for (var i = 0; i < points.length; i+=2) + { x = points[i]; y = points[i+1]; @@ -732,7 +792,8 @@ //TODO - this aint needed! var length = points.length / 2; - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { indices.push( i ); } @@ -746,10 +807,12 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildPoly = function (graphicsData, webGLData) { +WebGLGraphics.buildPoly = function (graphicsData, webGLData) +{ var points = graphicsData.points; - if (points.length < 6) { + if (points.length < 6) + { return; } // get first and last point.. figure out the middle! @@ -767,7 +830,8 @@ var triangles = utils.PolyK.Triangulate(points); - if (!triangles) { + if (!triangles) + { return false; } @@ -775,7 +839,8 @@ var i = 0; - for (i = 0; i < triangles.length; i+=3) { + for (i = 0; i < triangles.length; i+=3) + { indices.push(triangles[i] + vertPos); indices.push(triangles[i] + vertPos); indices.push(triangles[i+1] + vertPos); @@ -783,7 +848,8 @@ indices.push(triangles[i+2] + vertPos); } - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { verts.push(points[i * 2], points[i * 2 + 1], r, g, b, alpha); } diff --git a/src/core/renderers/webgl/utils/WebGLGraphicsData.js b/src/core/renderers/webgl/utils/WebGLGraphicsData.js index c56d05e..c739ba7 100644 --- a/src/core/renderers/webgl/utils/WebGLGraphicsData.js +++ b/src/core/renderers/webgl/utils/WebGLGraphicsData.js @@ -2,7 +2,8 @@ * @class * @private */ -function WebGLGraphicsData(gl) { +function WebGLGraphicsData(gl) +{ this.gl = gl; //TODO does this need to be split before uploding?? @@ -22,7 +23,8 @@ /** * */ -WebGLGraphicsData.prototype.reset = function () { +WebGLGraphicsData.prototype.reset = function () +{ this.points.length = 0; this.indices.length = 0; }; @@ -30,7 +32,8 @@ /** * */ -WebGLGraphicsData.prototype.upload = function () { +WebGLGraphicsData.prototype.upload = function () +{ var gl = this.gl; // this.lastIndex = graphics.graphicsData.length; diff --git a/src/core/renderers/webgl/utils/WebGLSpriteBatch.js b/src/core/renderers/webgl/utils/WebGLSpriteBatch.js index 96eaa52..55befbb 100644 --- a/src/core/renderers/webgl/utils/WebGLSpriteBatch.js +++ b/src/core/renderers/webgl/utils/WebGLSpriteBatch.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this sprite batch works for. */ -function WebGLSpriteBatch(renderer) { +function WebGLSpriteBatch(renderer) +{ /** * * @@ -88,7 +89,8 @@ */ this.lastIndexCount = 0; - for (var i=0, j=0; i < numIndices; i += 6, j += 4) { + 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; @@ -162,7 +164,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.setupContext(); }); } @@ -173,7 +176,8 @@ /** * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLSpriteBatch.prototype.setupContext = function () { +WebGLSpriteBatch.prototype.setupContext = function () +{ var gl = this.renderer.gl; // setup default shader @@ -198,7 +202,8 @@ /** * */ -WebGLSpriteBatch.prototype.begin = function () { +WebGLSpriteBatch.prototype.begin = function () +{ // this.shader = this.renderer.shaderManager.defaultShader; this.start(); @@ -206,19 +211,22 @@ /** */ -WebGLSpriteBatch.prototype.end = function () { +WebGLSpriteBatch.prototype.end = function () +{ this.flush(); }; /** * @param sprite {Sprite} the sprite to render when using this spritebatch */ -WebGLSpriteBatch.prototype.render = function (sprite) { +WebGLSpriteBatch.prototype.render = function (sprite) +{ var texture = sprite.texture; //TODO set blend modes.. // check texture.. - if (this.currentBatchSize >= this.size) { + if (this.currentBatchSize >= this.size) + { this.flush(); this.currentBaseTexture = texture.baseTexture; } @@ -227,7 +235,8 @@ var uvs = texture._uvs; // if the uvs have not updated then no point rendering just yet! - if (!uvs) { + if (!uvs) + { return; } @@ -237,7 +246,8 @@ var w0, w1, h0, h1; - if (texture.trim) { + 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; @@ -248,7 +258,8 @@ h0 = h1 + texture.crop.height; } - else { + else + { w0 = (texture.frame.width ) * (1-aX); w1 = (texture.frame.width ) * -aX; @@ -272,7 +283,8 @@ var colors = this.colors; var positions = this.positions; - if (this.renderer.roundPixels) { + if (this.renderer.roundPixels) + { // xy positions[index] = a * w1 + c * h1 + tx | 0; positions[index+1] = d * h1 + b * w1 + ty | 0; @@ -289,7 +301,8 @@ positions[index+15] = a * w1 + c * h0 + tx | 0; positions[index+16] = d * h0 + b * w1 + ty | 0; } - else { + else + { // xy positions[index] = a * w1 + c * h1 + tx; positions[index+1] = d * h1 + b * w1 + ty; @@ -338,11 +351,13 @@ * * @param sprite {TilingSprite} the tilingSprite to render */ -WebGLSpriteBatch.prototype.renderTilingSprite = function (tilingSprite) { +WebGLSpriteBatch.prototype.renderTilingSprite = function (tilingSprite) +{ var texture = tilingSprite.tilingTexture; // check texture.. - if (this.currentBatchSize >= this.size) { + if (this.currentBatchSize >= this.size) + { //return; this.flush(); this.currentBaseTexture = texture.baseTexture; @@ -351,7 +366,8 @@ // set the textures uvs temporarily // TODO create a separate texture so that we can tile part of a texture - if (!tilingSprite._uvs) { + if (!tilingSprite._uvs) + { tilingSprite._uvs = new TextureUvs(); } @@ -454,16 +470,19 @@ * Renders the content and empties the current batch. * */ -WebGLSpriteBatch.prototype.flush = function () { +WebGLSpriteBatch.prototype.flush = function () +{ // If the batch is length 0 then return as there is nothing to draw - if (this.currentBatchSize === 0) { + if (this.currentBatchSize === 0) + { return; } var gl = this.renderer.gl; var shader; - if (this.dirty) { + if (this.dirty) + { this.dirty = false; // bind the main texture gl.activeTexture(gl.TEXTURE0); @@ -482,10 +501,12 @@ } // upload the verts to the buffer - if (this.currentBatchSize > ( this.size * 0.5 ) ) { + if (this.currentBatchSize > ( this.size * 0.5 ) ) + { gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); } - else { + else + { var view = this.positions.subarray(0, this.currentBatchSize * this.vertByteSize); gl.bufferSubData(gl.ARRAY_BUFFER, 0, view); } @@ -502,7 +523,8 @@ var shaderSwap = false; var sprite; - for (var i = 0, j = this.currentBatchSize; i < j; i++) { + for (var i = 0, j = this.currentBatchSize; i < j; i++) + { sprite = this.sprites[i]; @@ -513,24 +535,28 @@ blendSwap = currentBlendMode !== nextBlendMode; shaderSwap = currentShader !== nextShader; // should I use uuidS??? - if (currentBaseTexture !== nextTexture || blendSwap || shaderSwap) { + if (currentBaseTexture !== nextTexture || blendSwap || shaderSwap) + { this.renderBatch(currentBaseTexture, batchSize, start); start = i; batchSize = 0; currentBaseTexture = nextTexture; - if (blendSwap) { + if (blendSwap) + { currentBlendMode = nextBlendMode; this.renderer.blendModeManager.setBlendMode( currentBlendMode ); } - if (shaderSwap) { + if (shaderSwap) + { currentShader = nextShader; shader = currentShader.shaders ? currentShader.shaders[gl.id] : currentShader; - if (!shader) { + if (!shader) + { shader = new Shader(gl, null, currentShader.fragmentSrc, currentShader.uniforms); currentShader.shaders[gl.id] = shader; } @@ -538,7 +564,8 @@ // set shader function??? this.renderer.shaderManager.setShader(shader); - if (shader.dirty) { + if (shader.dirty) + { shader.syncUniforms(); } @@ -569,17 +596,21 @@ * @param size {number} * @param startIndex {number} */ -WebGLSpriteBatch.prototype.renderBatch = function (texture, size, startIndex) { - if (size === 0) { +WebGLSpriteBatch.prototype.renderBatch = function (texture, size, startIndex) +{ + if (size === 0) + { return; } var gl = this.renderer.gl; - if (!texture._glTextures[gl.id]) { + if (!texture._glTextures[gl.id]) + { this.renderer.updateTexture(texture); } - else { + else + { // bind the current texture gl.bindTexture(gl.TEXTURE_2D, texture._glTextures[gl.id]); } @@ -594,7 +625,8 @@ /** * */ -WebGLSpriteBatch.prototype.stop = function () { +WebGLSpriteBatch.prototype.stop = function () +{ this.flush(); this.dirty = true; }; @@ -602,7 +634,8 @@ /** * */ -WebGLSpriteBatch.prototype.start = function () { +WebGLSpriteBatch.prototype.start = function () +{ this.dirty = true; }; @@ -610,7 +643,8 @@ * Destroys the SpriteBatch. * */ -WebGLSpriteBatch.prototype.destroy = function () { +WebGLSpriteBatch.prototype.destroy = function () +{ this.renderer.gl.deleteBuffer(this.vertexBuffer); this.renderer.gl.deleteBuffer(this.indexBuffer); diff --git a/src/core/textures/BaseTexture.js b/src/core/textures/BaseTexture.js index 2bf77d4..513d358 100644 --- a/src/core/textures/BaseTexture.js +++ b/src/core/textures/BaseTexture.js @@ -10,7 +10,8 @@ * @param source {Image|Canvas} the source object of the texture. * @param [scaleMode=scaleModes.DEFAULT] {number} See {@link scaleModes} for possible values */ -function BaseTexture(source, scaleMode) { +function BaseTexture(source, scaleMode) +{ this.uuid = utils.uuid(); /** @@ -123,7 +124,8 @@ this._needsUpdate = false; // if no source passed don't try to load - if (source) { + if (source) + { this.loadSource(source); } @@ -149,13 +151,16 @@ Object.defineProperties(BaseTexture.prototype, { needsUpdate: { - get: function () { + get: function () + { return this._needsUpdate; }, - set: function (val) { + set: function (val) + { this._needsUpdate = val; - if (val) { + if (val) + { this.emit('update', this); } } @@ -171,9 +176,11 @@ * * The logic state after calling `loadSource` directly or indirectly (eg. `fromImage`, `new BaseTexture`) is: * - * if (texture.hasLoaded) { + * if (texture.hasLoaded) + { * // texture ready for use - * } else if (texture.isLoading) { + * } else if (texture.isLoading) + { * // listen to 'loaded' and/or 'error' events on texture * } else { * // not loading, not going to load UNLESS the source is reloaded @@ -183,12 +190,14 @@ * @protected * @param source {Image|Canvas} the source object of the texture. */ -BaseTexture.prototype.loadSource = function (source) { +BaseTexture.prototype.loadSource = function (source) +{ var wasLoading = this.isLoading; this.hasLoaded = false; this.isLoading = false; - if (wasLoading && this.source) { + if (wasLoading && this.source) + { this.source.onload = null; this.source.onerror = null; } @@ -196,20 +205,24 @@ this.source = source; // Apply source if loaded. Otherwise setup appropriate loading monitors. - if ((this.source.complete || this.source.getContext) && this.source.width && this.source.height) { + if ((this.source.complete || this.source.getContext) && this.source.width && this.source.height) + { this._sourceLoaded(); } - else if(!source.getContext) { + else if(!source.getContext) + { // Image fail / not ready this.isLoading = true; var scope = this; - source.onload = function () { + source.onload = function () + { source.onload = null; source.onerror = null; - if(!scope.isLoading) { + if(!scope.isLoading) + { return; } @@ -219,11 +232,13 @@ scope.emit('loaded', scope); }; - source.onerror = function () { + source.onerror = function () + { source.onload = null; source.onerror = null; - if(!scope.isLoading) { + if(!scope.isLoading) + { return; } @@ -234,24 +249,29 @@ // Per http://www.w3.org/TR/html5/embedded-content-0.html#the-img-element // "The value of `complete` can thus change while a script is executing." // So complete needs to be re-checked after the callbacks have been added.. - if (source.complete) { + if (source.complete) + { this.isLoading = false; // ..and if we're complete now, no need for callbacks source.onload = null; source.onerror = null; - if (source.width && source.height) { + if (source.width && source.height) + { this._sourceLoaded(); // If any previous subscribers possible - if (wasLoading) { + if (wasLoading) + { this.emit('loaded', this); } } - else { + else + { // If any previous subscribers possible - if (wasLoading) { + if (wasLoading) + { this.emit('error', this); } } @@ -265,7 +285,8 @@ * * @private */ -BaseTexture.prototype._sourceLoaded = function () { +BaseTexture.prototype._sourceLoaded = function () +{ this.hasLoaded = true; this.width = this.source.naturalWidth || this.source.width; @@ -278,16 +299,20 @@ * Destroys this base texture * */ -BaseTexture.prototype.destroy = function () { - if (this.imageUrl) { +BaseTexture.prototype.destroy = function () +{ + if (this.imageUrl) + { delete utils.BaseTextureCache[this.imageUrl]; delete utils.TextureCache[this.imageUrl]; this.imageUrl = null; - if (!navigator.isCocoonJS) { + if (!navigator.isCocoonJS) + { this.source.src = ''; } } - else if (this.source && this.source._pixiId) { + else if (this.source && this.source._pixiId) + { delete utils.BaseTextureCache[this.source._pixiId]; } this.source = null; @@ -301,7 +326,8 @@ * memory again. * */ -BaseTexture.prototype.dispose = function () { +BaseTexture.prototype.dispose = function () +{ this.emit('dispose', this); }; @@ -311,7 +337,8 @@ * * @param newSrc {string} the path of the image */ -BaseTexture.prototype.updateSourceImage = function (newSrc) { +BaseTexture.prototype.updateSourceImage = function (newSrc) +{ this.source.src = newSrc; this.loadSource(this.source); }; @@ -326,18 +353,22 @@ * @param [scaleMode=scaleModes.DEFAULT] {number} See {@link scaleModes} for possible values * @return BaseTexture */ -BaseTexture.fromImage = function (imageUrl, crossorigin, scaleMode) { +BaseTexture.fromImage = function (imageUrl, crossorigin, scaleMode) +{ var baseTexture = utils.BaseTextureCache[imageUrl]; - if (crossorigin === undefined && imageUrl.indexOf('data:') !== 0) { + if (crossorigin === undefined && imageUrl.indexOf('data:') !== 0) + { crossorigin = true; } - if (!baseTexture) { + if (!baseTexture) + { // new Image() breaks tex loading in some versions of Chrome. // See https://code.google.com/p/chromium/issues/detail?id=238071 var image = new Image();//document.createElement('img'); - if (crossorigin) { + if (crossorigin) + { image.crossOrigin = ''; } @@ -347,7 +378,8 @@ utils.BaseTextureCache[imageUrl] = baseTexture; // if there is an @2x at the end of the url we are going to assume its a highres image - if ( imageUrl.indexOf(CONST.RETINA_PREFIX + '.') !== -1) { + if ( imageUrl.indexOf(CONST.RETINA_PREFIX + '.') !== -1) + { baseTexture.resolution = 2; } } @@ -363,14 +395,17 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return BaseTexture */ -BaseTexture.fromCanvas = function (canvas, scaleMode) { - if (!canvas._pixiId) { +BaseTexture.fromCanvas = function (canvas, scaleMode) +{ + if (!canvas._pixiId) + { canvas._pixiId = 'canvas_' + utils.uuid(); } var baseTexture = utils.BaseTextureCache[canvas._pixiId]; - if (!baseTexture) { + if (!baseTexture) + { baseTexture = new BaseTexture(canvas, scaleMode); utils.BaseTextureCache[canvas._pixiId] = baseTexture; } diff --git a/src/core/textures/RenderTexture.js b/src/core/textures/RenderTexture.js index 6dad20f..53ae796 100644 --- a/src/core/textures/RenderTexture.js +++ b/src/core/textures/RenderTexture.js @@ -46,8 +46,10 @@ * @param [scaleMode] {number} See {@link scaleModes} for possible values * @param [resolution=1] {number} The resolution of the texture being generated */ -function RenderTexture(renderer, width, height, scaleMode, resolution) { - if (!renderer) { +function RenderTexture(renderer, width, height, scaleMode, resolution) +{ + if (!renderer) + { throw new Error('Unable to create RenderTexture, you must pass a renderer into the constructor.'); } @@ -133,7 +135,8 @@ */ this.renderer = renderer; - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { var gl = this.renderer.gl; this.textureBuffer = new FilterTexture(gl, this.width * this.resolution, this.height * this.resolution, this.baseTexture.scaleMode); @@ -142,7 +145,8 @@ this.render = this.renderWebGL; this.projection = new math.Point(this.width*0.5, -this.height*0.5); } - else { + else + { this.render = this.renderCanvas; this.textureBuffer = new CanvasBuffer(this.width* this.resolution, this.height* this.resolution); this.baseTexture.source = this.textureBuffer.canvas; @@ -167,8 +171,10 @@ * @param height {number} The height to resize to. * @param updateBase {boolean} Should the baseTexture.width and height values be resized as well? */ -RenderTexture.prototype.resize = function (width, height, updateBase) { - if (width === this.width && height === this.height) { +RenderTexture.prototype.resize = function (width, height, updateBase) +{ + if (width === this.width && height === this.height) + { return; } @@ -177,17 +183,20 @@ this.width = this.frame.width = this.crop.width = width; this.height = this.frame.height = this.crop.height = height; - if (updateBase) { + if (updateBase) + { this.baseTexture.width = this.width; this.baseTexture.height = this.height; } - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { this.projection.x = this.width / 2; this.projection.y = -this.height / 2; } - if (!this.valid) { + if (!this.valid) + { return; } @@ -198,12 +207,15 @@ * Clears the RenderTexture. * */ -RenderTexture.prototype.clear = function () { - if (!this.valid) { +RenderTexture.prototype.clear = function () +{ + if (!this.valid) + { return; } - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { this.renderer.gl.bindFramebuffer(this.renderer.gl.FRAMEBUFFER, this.textureBuffer.frameBuffer); } @@ -220,19 +232,23 @@ * @param [restoreWorldTransform=true] {boolean} If true the displayObject's worldTransform/worldAlpha and all children * transformations will be restored. Not restoring this information will be a little faster. */ -RenderTexture.prototype.renderWebGL = function (displayObject, matrix, clear, restoreWorldTransform) { - if (!this.valid) { +RenderTexture.prototype.renderWebGL = function (displayObject, matrix, clear, restoreWorldTransform) +{ + if (!this.valid) + { return; } - if (typeof restoreWorldTransform === 'undefined') { + if (typeof restoreWorldTransform === 'undefined') + { restoreWorldTransform = true; } var tempAlpha, tempTransform; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { tempAlpha = displayObject.worldAlpha; tempTransform = displayObject.worldTransform.toArray(); } @@ -245,7 +261,8 @@ wt.identity(); wt.translate(0, this.projection.y * 2); - if (matrix) { + if (matrix) + { wt.append(matrix); } @@ -258,7 +275,8 @@ var children = displayObject.children; var i, j; - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } @@ -269,7 +287,8 @@ gl.bindFramebuffer(gl.FRAMEBUFFER, this.textureBuffer.frameBuffer ); - if (clear) { + if (clear) + { this.textureBuffer.clear(); } @@ -279,11 +298,13 @@ this.renderer.spriteBatch.dirty = true; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { displayObject.worldAlpha = tempAlpha; displayObject.worldTransform.fromArray(tempTransform); - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } } @@ -300,26 +321,31 @@ * @param [restoreWorldTransform=true] {boolean} If true the displayObject's worldTransform/worldAlpha and all children * transformations will be restored. Not restoring this information will be a little faster. */ -RenderTexture.prototype.renderCanvas = function (displayObject, matrix, clear, restoreWorldTransform) { - if (!this.valid) { +RenderTexture.prototype.renderCanvas = function (displayObject, matrix, clear, restoreWorldTransform) +{ + if (!this.valid) + { return; } - if (typeof restoreWorldTransform === 'undefined') { + if (typeof restoreWorldTransform === 'undefined') + { restoreWorldTransform = true; } var tempAlpha, tempTransform; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { tempAlpha = displayObject.worldAlpha; tempTransform = displayObject.worldTransform.toArray(); } var wt = displayObject.worldTransform; wt.identity(); - if (matrix) { + if (matrix) + { wt.append(matrix); } @@ -330,11 +356,13 @@ var children = displayObject.children; var i, j; - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } - if (clear) { + if (clear) + { this.textureBuffer.clear(); } @@ -348,11 +376,13 @@ this.renderer.resolution = realResolution; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { displayObject.worldAlpha = tempAlpha; displayObject.worldTransform.fromArray(tempTransform); - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } } @@ -363,7 +393,8 @@ * * @return {Image} */ -RenderTexture.prototype.getImage = function () { +RenderTexture.prototype.getImage = function () +{ var image = new Image(); image.src = this.getBase64(); return image; @@ -374,7 +405,8 @@ * * @return {string} A base64 encoded string of the texture. */ -RenderTexture.prototype.getBase64 = function () { +RenderTexture.prototype.getBase64 = function () +{ return this.getCanvas().toDataURL(); }; @@ -383,8 +415,10 @@ * * @return {HTMLCanvasElement} A Canvas element with the texture rendered on. */ -RenderTexture.prototype.getCanvas = function () { - if (this.renderer.type === CONST.WEBGL_RENDERER) { +RenderTexture.prototype.getCanvas = function () +{ + if (this.renderer.type === CONST.WEBGL_RENDERER) + { var gl = this.renderer.gl; var width = this.textureBuffer.width; var height = this.textureBuffer.height; @@ -403,7 +437,8 @@ return tempCanvas.canvas; } - else { + else + { return this.textureBuffer.canvas; } }; diff --git a/src/core/textures/Texture.js b/src/core/textures/Texture.js index 3c65909..e97f0aa 100644 --- a/src/core/textures/Texture.js +++ b/src/core/textures/Texture.js @@ -17,7 +17,8 @@ * @param [crop] {Rectangle} The area of original texture * @param [trim] {Rectangle} Trimmed texture rectangle */ -function Texture(baseTexture, frame, crop, trim) { +function Texture(baseTexture, frame, crop, trim) +{ /** * Does this Texture have any frame data assigned to it? * @@ -25,12 +26,14 @@ */ this.noFrame = false; - if (!frame) { + if (!frame) + { this.noFrame = true; frame = new math.Rectangle(0, 0, 1, 1); } - if (baseTexture instanceof Texture) { + if (baseTexture instanceof Texture) + { baseTexture = baseTexture.baseTexture; } @@ -100,13 +103,16 @@ */ this.crop = crop || new math.Rectangle(0, 0, 1, 1); - if (baseTexture.hasLoaded) { - if (this.noFrame) { + if (baseTexture.hasLoaded) + { + if (this.noFrame) + { frame = new math.Rectangle(0, 0, baseTexture.width, baseTexture.height); } this.frame = frame; } - else { + else + { baseTexture.addEventListener('loaded', this.onBaseTextureLoaded.bind(this)); } } @@ -118,19 +124,23 @@ Object.defineProperties(Texture.prototype, { needsUpdate: { - get: function () { + get: function () + { return this.baseTexture.needsUpdate; }, - set: function (val) { + set: function (val) + { this.baseTexture.needsUpdate = val; } }, frame: { - get: function () { + get: function () + { return this._frame; }, - set: function (frame) { + set: function (frame) + { this._frame = frame; this.noFrame = false; @@ -143,20 +153,23 @@ 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 (!this.trim && (frame.x + frame.width > this.baseTexture.width || frame.y + frame.height > this.baseTexture.height)) + { throw new Error('Texture Error: frame does not fit inside the base Texture dimensions ' + this); } this.valid = frame && frame.width && frame.height && this.baseTexture.source && this.baseTexture.hasLoaded; - if (this.trim) { + 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) { + if (this.valid) + { this._updateUvs(); } } @@ -168,11 +181,13 @@ * * @private */ -Texture.prototype.onBaseTextureLoaded = function () { +Texture.prototype.onBaseTextureLoaded = function () +{ var baseTexture = this.baseTexture; baseTexture.removeEventListener('loaded', this.onLoaded); - if (this.noFrame) { + if (this.noFrame) + { this.frame = new math.Rectangle(0, 0, baseTexture.width, baseTexture.height); } @@ -184,8 +199,10 @@ * * @param destroyBase {boolean} Whether to destroy the base texture as well */ -Texture.prototype.destroy = function (destroyBase) { - if (destroyBase) { +Texture.prototype.destroy = function (destroyBase) +{ + if (destroyBase) + { this.baseTexture.destroy(); } @@ -197,8 +214,10 @@ * * @private */ -Texture.prototype._updateUvs = function () { - if (!this._uvs) { +Texture.prototype._updateUvs = function () +{ + if (!this._uvs) + { this._uvs = new TextureUvs(); } @@ -229,10 +248,12 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return Texture */ -Texture.fromImage = function (imageUrl, crossorigin, scaleMode) { +Texture.fromImage = function (imageUrl, crossorigin, scaleMode) +{ var texture = utils.TextureCache[imageUrl]; - if (!texture) { + if (!texture) + { texture = new Texture(BaseTexture.fromImage(imageUrl, crossorigin, scaleMode)); utils.TextureCache[imageUrl] = texture; } @@ -248,9 +269,11 @@ * @param frameId {string} The frame id of the texture * @return Texture */ -Texture.fromFrame = function (frameId) { +Texture.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache '); } return texture; @@ -264,7 +287,8 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return {Texture} */ -Texture.fromCanvas = function (canvas, scaleMode) { +Texture.fromCanvas = function (canvas, scaleMode) +{ return new Texture(BaseTexture.fromCanvas(canvas, scaleMode)); }; @@ -276,7 +300,8 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return {Texture} A Texture */ -Texture.fromVideo = function (video, scaleMode) { +Texture.fromVideo = function (video, scaleMode) +{ return new Texture(VideoBaseTexture.baseTextureFromVideo(video, scaleMode)); }; @@ -287,7 +312,8 @@ * @param texture {Texture} The Texture to add to the cache. * @param id {string} The id that the texture will be stored against. */ -Texture.addTextureToCache = function (texture, id) { +Texture.addTextureToCache = function (texture, id) +{ utils.TextureCache[id] = texture; }; @@ -298,7 +324,8 @@ * @param id {string} The id of the texture to be removed * @return {Texture} The texture that was removed */ -Texture.removeTextureFromCache = function (id) { +Texture.removeTextureFromCache = function (id) +{ var texture = utils.TextureCache[id]; delete utils.TextureCache[id]; diff --git a/src/core/textures/TextureUvs.js b/src/core/textures/TextureUvs.js index b9bbb58..5424d52 100644 --- a/src/core/textures/TextureUvs.js +++ b/src/core/textures/TextureUvs.js @@ -1,4 +1,5 @@ -function TextureUvs() { +function TextureUvs() +{ this.x0 = 0; this.y0 = 0; diff --git a/src/core/textures/VideoBaseTexture.js b/src/core/textures/VideoBaseTexture.js index e3e0c5a..1a826a9 100644 --- a/src/core/textures/VideoBaseTexture.js +++ b/src/core/textures/VideoBaseTexture.js @@ -12,15 +12,18 @@ * @param source {HTMLVideoElement} * @param [scaleMode] {number} See {@link scaleModes} for possible values */ -function VideoBaseTexture(source, scaleMode) { - if (!source){ +function VideoBaseTexture(source, scaleMode) +{ + if (!source) + { throw new Error('No video source element specified.'); } // hook in here to check if video is already available. // BaseTexture looks for a source.complete boolean, plus width & height. - if ((source.readyState === source.HAVE_ENOUGH_DATA || source.readyState === source.HAVE_FUTURE_DATA) && source.width && source.height) { + if ((source.readyState === source.HAVE_ENOUGH_DATA || source.readyState === source.HAVE_FUTURE_DATA) && source.width && source.height) + { source.complete = true; } @@ -31,7 +34,8 @@ this._boundOnUpdate = this._onUpdate.bind(this); this._boundOnCanPlay = this._onCanPlay.bind(this); - if (!source.complete) { + if (!source.complete) + { source.addEventListener('canplay', this._boundOnCanPlay); source.addEventListener('canplaythrough', this._boundOnCanPlay); @@ -47,28 +51,35 @@ VideoBaseTexture.prototype.constructor = VideoBaseTexture; module.exports = VideoBaseTexture; -VideoBaseTexture.prototype._onUpdate = function () { - if (this.autoUpdate) { +VideoBaseTexture.prototype._onUpdate = function () +{ + if (this.autoUpdate) + { window.requestAnimationFrame(this._boundOnUpdate); this.needsUpdate = true; } }; -VideoBaseTexture.prototype._onPlayStart = function () { - if (!this.autoUpdate) { +VideoBaseTexture.prototype._onPlayStart = function () +{ + if (!this.autoUpdate) + { window.requestAnimationFrame(this._boundOnUpdate); this.autoUpdate = true; } }; -VideoBaseTexture.prototype._onPlayStop = function () { +VideoBaseTexture.prototype._onPlayStop = function () +{ this.autoUpdate = false; }; -VideoBaseTexture.prototype._onCanPlay = function () { +VideoBaseTexture.prototype._onCanPlay = function () +{ this.hasLoaded = true; - if (this.source) { + if (this.source) + { this.source.removeEventListener('canplay', this._boundOnCanPlay); this.source.removeEventListener('canplaythrough', this._boundOnCanPlay); @@ -78,15 +89,18 @@ this.source.play(); // prevent multiple loaded dispatches.. - if(!this.__loaded){ + if(!this.__loaded) + { this.__loaded = true; this.emit('loaded', this); } } }; -VideoBaseTexture.prototype.destroy = function () { - if (this.source && this.source._pixiId) { +VideoBaseTexture.prototype.destroy = function () +{ + if (this.source && this.source._pixiId) + { utils.BaseTextureCache[ this.source._pixiId ] = null; delete utils.BaseTextureCache[ this.source._pixiId ]; @@ -105,14 +119,17 @@ * @param scaleMode {number} See {@link scaleModes} for possible values * @return {VideoBaseTexture} */ -VideoBaseTexture.fromVideo = function (video, scaleMode) { - if (!video._pixiId) { +VideoBaseTexture.fromVideo = function (video, scaleMode) +{ + if (!video._pixiId) + { video._pixiId = 'video_' + utils.uuid(); } var baseTexture = utils.BaseTextureCache[video._pixiId]; - if (!baseTexture) { + if (!baseTexture) + { baseTexture = new VideoBaseTexture(video, scaleMode); utils.BaseTextureCache[ video._pixiId ] = baseTexture; } @@ -147,17 +164,21 @@ * @param scaleMode {number} See {@link scaleModes} for possible values * @return {VideoBaseTexture} */ -VideoBaseTexture.fromUrl = function (videoSrc, scaleMode) { +VideoBaseTexture.fromUrl = function (videoSrc, scaleMode) +{ var video = document.createElement('video'); // array of objects or strings - if (Array.isArray(videoSrc)) { - for (var i = 0; i < videoSrc.length; ++i) { + if (Array.isArray(videoSrc)) + { + for (var i = 0; i < videoSrc.length; ++i) + { video.appendChild(createSource(videoSrc.src || videoSrc, videoSrc.mime)); } } // single object or string - else { + else + { video.appendChild(createSource(videoSrc.src || videoSrc, videoSrc.mime)); } @@ -169,8 +190,10 @@ VideoBaseTexture.fromUrls = VideoBaseTexture.fromUrl; -function createSource(path, type) { - if (!type) { +function createSource(path, type) +{ + if (!type) + { type = 'video/' + path.substr(path.lastIndexOf('.') + 1); } diff --git a/src/core/utils/EventData.js b/src/core/utils/EventData.js index 5d55a22..8cdf701 100644 --- a/src/core/utils/EventData.js +++ b/src/core/utils/EventData.js @@ -7,7 +7,8 @@ * @param name {string} The string name of the event that was triggered * @param data {object} Arbitrary event data to pass along */ -function EventData(target, name, data) { +function EventData(target, name, data) +{ // for duck typing in the ".on()" function this.__isEventObject = true; @@ -71,7 +72,8 @@ * Stops the propagation of events up the scene graph (prevents bubbling). * */ -EventData.prototype.stopPropagation = function stopPropagation() { +EventData.prototype.stopPropagation = function stopPropagation() +{ this.stopped = true; }; @@ -79,6 +81,7 @@ * Stops the propagation of events to sibling listeners (no longer calls any listeners). * */ -EventData.prototype.stopImmediatePropagation = function stopImmediatePropagation() { +EventData.prototype.stopImmediatePropagation = function stopImmediatePropagation() +{ this.stoppedImmediate = true; }; diff --git a/src/core/utils/EventTarget.js b/src/core/utils/EventTarget.js index 7ae8820..671a151 100644 --- a/src/core/utils/EventTarget.js +++ b/src/core/utils/EventTarget.js @@ -13,14 +13,16 @@ * var em = new MyEmitter(); * em.emit('eventName', 'some data', 'some more data', {}, null, ...); */ -function eventTarget(obj) { +function eventTarget(obj) +{ /** * Return a list of assigned event listeners. * * @param eventName {string} The events that should be listed. * @return {Array} An array of listener functions */ - obj.listeners = function listeners(eventName) { + obj.listeners = function listeners(eventName) + { this._listeners = this._listeners || {}; return this._listeners[eventName] ? this._listeners[eventName].slice() : []; @@ -33,22 +35,26 @@ * @param eventName {string} The name of the event. * @return {boolean} Indication if we've emitted an event. */ - obj.emit = obj.dispatchEvent = function emit(eventName, data) { + obj.emit = obj.dispatchEvent = function emit(eventName, data) + { this._listeners = this._listeners || {}; // fast return when there are no listeners - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return; } //backwards compat with old method ".emit({ type: 'something' })" - if (typeof eventName === 'object') { + if (typeof eventName === 'object') + { data = eventName; eventName = eventName.type; } //ensure we are using a real pixi event - if (!data || data.__isEventObject !== true) { + if (!data || data.__isEventObject !== true) + { data = new EventData(this, eventName, data); } @@ -58,23 +64,27 @@ fn = listeners[0], i; - for (i = 0; i < length; fn = listeners[++i]) { + for (i = 0; i < length; fn = listeners[++i]) + { //call the event listener fn.call(this, data); //if "stopImmediatePropagation" is called, stop calling sibling events - if (data.stoppedImmediate) { + if (data.stoppedImmediate) + { return this; } } //if "stopPropagation" is called then don't bubble the event - if (data.stopped) { + if (data.stopped) + { return this; } //bubble this event up the scene graph - if (this.parent && this.parent.emit) { + if (this.parent && this.parent.emit) + { this.parent.emit.call(this.parent, eventName, data); } @@ -88,7 +98,8 @@ * @param eventName {string} Name of the event. * @param callback {Functon} fn Callback function. */ - obj.on = obj.addEventListener = function on(eventName, fn) { + obj.on = obj.addEventListener = function on(eventName, fn) + { this._listeners = this._listeners || {}; (this._listeners[eventName] = this._listeners[eventName] || []) @@ -103,11 +114,13 @@ * @param eventName {string} Name of the event. * @param callback {Function} Callback function. */ - obj.once = function once(eventName, fn) { + obj.once = function once(eventName, fn) + { this._listeners = this._listeners || {}; var self = this; - function onceHandlerWrapper() { + function onceHandlerWrapper() + { fn.apply(self.off(eventName, onceHandlerWrapper), arguments); } onceHandlerWrapper._originalHandler = fn; @@ -122,23 +135,28 @@ * @param eventName {string} The event we want to remove. * @param callback {Function} The listener that we need to find. */ - obj.off = obj.removeEventListener = function off(eventName, fn) { + obj.off = obj.removeEventListener = function off(eventName, fn) + { this._listeners = this._listeners || {}; - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return this; } var list = this._listeners[eventName], i = fn ? list.length : 0; - while(i-- > 0) { - if (list[i] === fn || list[i]._originalHandler === fn) { + while(i-- > 0) + { + if (list[i] === fn || list[i]._originalHandler === fn) + { list.splice(i, 1); } } - if (list.length === 0) { + if (list.length === 0) + { delete this._listeners[eventName]; } @@ -150,10 +168,12 @@ * * @param eventName {string} The event you want to remove all listeners for. */ - obj.removeAllListeners = function removeAllListeners(eventName) { + obj.removeAllListeners = function removeAllListeners(eventName) + { this._listeners = this._listeners || {}; - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return this; } @@ -169,7 +189,8 @@ * * @param object {object} The obj to mix into */ - mixin: function mixin(obj) { + mixin: function mixin(obj) + { eventTarget(obj); } }; diff --git a/src/core/utils/PolyK.js b/src/core/utils/PolyK.js index 7325141..5e20c2b 100644 --- a/src/core/utils/PolyK.js +++ b/src/core/utils/PolyK.js @@ -47,7 +47,8 @@ * Triangulates shapes for webGL graphic fills. * */ -PolyK.Triangulate = function (p) { +PolyK.Triangulate = function (p) +{ var sign = true; var n = p.length >> 1; @@ -59,7 +60,8 @@ i = 0; var al = n; - while(al > 3) { + while(al > 3) + { var i0 = avl[(i+0)%al]; var i1 = avl[(i+1)%al]; var i2 = avl[(i+2)%al]; @@ -69,29 +71,35 @@ var cx = p[2*i2], cy = p[2*i2+1]; var earFound = false; - if (PolyK._convex(ax, ay, bx, by, cx, cy, sign)) { + if (PolyK._convex(ax, ay, bx, by, cx, cy, sign)) + { earFound = true; - for (var j = 0; j < al; j++) { + for (var j = 0; j < al; j++) + { var vi = avl[j]; if (vi === i0 || vi === i1 || vi === i2) continue; - if (PolyK._PointInTriangle(p[2*vi], p[2*vi+1], ax, ay, bx, by, cx, cy)) { + if (PolyK._PointInTriangle(p[2*vi], p[2*vi+1], ax, ay, bx, by, cx, cy)) + { earFound = false; break; } } } - if (earFound) { + if (earFound) + { tgs.push(i0, i1, i2); avl.splice((i+1)%al, 1); al--; i = 0; } - else if (i++ > 3*al) { + else if (i++ > 3*al) + { // need to flip flip reverse it! // reset! - if (sign) { + if (sign) + { tgs = []; avl = []; for (i = 0; i < n; i++) avl.push(i); @@ -101,7 +109,8 @@ sign = false; } - else { + else + { // window.console.log("PIXI Warning: shape too complex to fill"); return null; } @@ -126,7 +135,8 @@ * @private * @return {boolean} */ -PolyK._PointInTriangle = function (px, py, ax, ay, bx, by, cx, cy) { +PolyK._PointInTriangle = function (px, py, ax, ay, bx, by, cx, cy) +{ var v0x = cx-ax; var v0y = cy-ay; var v1x = bx-ax; @@ -154,6 +164,7 @@ * @private * @return {boolean} */ -PolyK._convex = function (ax, ay, bx, by, cx, cy, sign) { +PolyK._convex = function (ax, ay, bx, by, cx, cy, sign) +{ return ((ay-by)*(cx-bx) + (bx-ax)*(cy-by) >= 0) === sign; }; diff --git a/src/core/display/DisplayObject.js b/src/core/display/DisplayObject.js index 66ebc3c..20e778c 100644 --- a/src/core/display/DisplayObject.js +++ b/src/core/display/DisplayObject.js @@ -7,7 +7,8 @@ * @class * @namespace PIXI */ -function DisplayObject() { +function DisplayObject() +{ /** * The coordinate of the object relative to the local coordinates of the parent. * @@ -152,10 +153,12 @@ * @memberof DisplayObject# */ x: { - get: function () { + get: function () + { return this.position.x; }, - set: function (value) { + set: function (value) + { this.position.x = value; } }, @@ -167,10 +170,12 @@ * @memberof DisplayObject# */ y: { - get: function () { + get: function () + { return this.position.y; }, - set: function (value) { + set: function (value) + { this.position.y = value; } }, @@ -183,11 +188,13 @@ * @readonly */ worldVisible: { - get: function () { + get: function () + { var item = this; do { - if (!item.visible) { + if (!item.visible) + { return false; } @@ -207,17 +214,21 @@ * @memberof DisplayObject# */ mask: { - get: function () { + get: function () + { return this._mask; }, - set: function (value) { - if (this._mask) { + set: function (value) + { + if (this._mask) + { this._mask.isMask = false; } this._mask = value; - if (this._mask) { + if (this._mask) + { this._mask.isMask = true; } } @@ -232,18 +243,23 @@ * @memberof DisplayObject# */ filters: { - get: function () { + get: function () + { return this._filters; }, - set: function (value) { - if (value) { + set: function (value) + { + if (value) + { // now put all the passes in one place.. var passes = []; - for (var i = 0; i < value.length; i++) { + for (var i = 0; i < value.length; i++) + { var filterPasses = value[i].passes; - for (var j = 0; j < filterPasses.length; j++) { + for (var j = 0; j < filterPasses.length; j++) + { passes.push(filterPasses[j]); } } @@ -264,8 +280,9 @@ * * @private */ -DisplayObject.prototype.updateTransform = function () { - +DisplayObject.prototype.updateTransform = function () +{ + // create some matrix refs for easy access var pt = this.parent.worldTransform; var wt = this.worldTransform; @@ -274,9 +291,11 @@ var a, b, c, d, tx, ty; // so if rotation is between 0 then we can simplify the multiplication process.. - if (this.rotation % math.PI_2) { + if (this.rotation % math.PI_2) + { // 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) { + if (this.rotation !== this.rotationCache) + { this.rotationCache = this.rotation; this._sr = Math.sin(this.rotation); this._cr = Math.cos(this.rotation); @@ -291,7 +310,8 @@ ty = this.position.y; // check for pivot.. not often used so geared towards that fact! - if (this.pivot.x || this.pivot.y) { + 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; } @@ -304,7 +324,8 @@ wt.tx = tx * pt.a + ty * pt.c + pt.tx; wt.ty = tx * pt.b + ty * pt.d + pt.ty; } - else { + else + { // lets do the fast version as we know there is no rotation.. a = this.scale.x; d = this.scale.y; @@ -333,7 +354,8 @@ * @param matrix {Matrix} * @return {Rectangle} the rectangular bounding area */ -DisplayObject.prototype.getBounds = function (/* matrix */) { +DisplayObject.prototype.getBounds = function (/* matrix */) +{ return math.Rectangle.EMPTY; }; @@ -342,7 +364,8 @@ * * @return {Rectangle} the rectangular bounding area */ -DisplayObject.prototype.getLocalBounds = function () { +DisplayObject.prototype.getLocalBounds = function () +{ return this.getBounds(math.Matrix.IDENTITY); }; @@ -352,7 +375,8 @@ * @param position {Point} The world origin to calculate from * @return {Point} A point object representing the position of this object */ -DisplayObject.prototype.toGlobal = function (position) { +DisplayObject.prototype.toGlobal = function (position) +{ // don't need to u[date the lot this.displayObjectUpdateTransform(); return this.worldTransform.apply(position); @@ -365,8 +389,10 @@ * @param [from] {DisplayObject} The DisplayObject to calculate the global position from * @return {Point} A point object representing the position of this object */ -DisplayObject.prototype.toLocal = function (position, from) { - if (from) { +DisplayObject.prototype.toLocal = function (position, from) +{ + if (from) + { position = from.toGlobal(position); } @@ -381,7 +407,8 @@ * @param renderer {WebGLRenderer} The renderer * @private */ -DisplayObject.prototype.renderWebGL = function (/* renderer */) { +DisplayObject.prototype.renderWebGL = function (/* renderer */) +{ // OVERWRITE; }; @@ -391,6 +418,7 @@ * @param renderer {CanvasRenderer} The renderer * @private */ -DisplayObject.prototype.renderCanvas = function (/* renderer */) { +DisplayObject.prototype.renderCanvas = function (/* renderer */) +{ // OVERWRITE; }; diff --git a/src/core/display/DisplayObjectContainer.js b/src/core/display/DisplayObjectContainer.js index 689f40b..4625ee8 100644 --- a/src/core/display/DisplayObjectContainer.js +++ b/src/core/display/DisplayObjectContainer.js @@ -12,7 +12,8 @@ * @extends DisplayObject * @namespace PIXI */ -function DisplayObjectContainer() { +function DisplayObjectContainer() +{ DisplayObject.call(this); /** @@ -47,17 +48,21 @@ * @memberof DisplayObjectContainer# */ width: { - get: function () { + get: function () + { return this.scale.x * this.getLocalBounds().width; }, - set: function (value) { + set: function (value) + { var width = this.getLocalBounds().width; - if(width !== 0) { + if(width !== 0) + { this.scale.x = value / width; } - else { + else + { this.scale.x = 1; } @@ -73,17 +78,21 @@ * @memberof DisplayObjectContainer# */ height: { - get: function () { + get: function () + { return this.scale.y * this.getLocalBounds().height; }, - set: function (value) { + set: function (value) + { var height = this.getLocalBounds().height; - if (height !== 0) { + if (height !== 0) + { this.scale.y = value / height ; } - else { + else + { this.scale.y = 1; } @@ -100,18 +109,23 @@ * @memberof DisplayObject# */ cacheAsBitmap: { - get: function () { + get: function () + { return this._cacheAsBitmap; }, - set: function (value) { - if (this._cacheAsBitmap === value) { + set: function (value) + { + if (this._cacheAsBitmap === value) + { return; } - if (value) { + if (value) + { this._generateCachedSprite(); } - else { + else + { this._destroyCachedSprite(); } @@ -126,7 +140,8 @@ * @param child {DisplayObject} The DisplayObject to add to the container * @return {DisplayObject} The child that was added. */ -DisplayObjectContainer.prototype.addChild = function (child) { +DisplayObjectContainer.prototype.addChild = function (child) +{ return this.addChildAt(child, this.children.length); }; @@ -137,14 +152,18 @@ * @param index {Number} The index to place the child in * @return {DisplayObject} The child that was added. */ -DisplayObjectContainer.prototype.addChildAt = function (child, index) { +DisplayObjectContainer.prototype.addChildAt = function (child, index) +{ // prevent adding self as child - if (child === this) { + if (child === this) + { return; } - if (index >= 0 && index <= this.children.length) { - if (child.parent) { + if (index >= 0 && index <= this.children.length) + { + if (child.parent) + { child.parent.removeChild(child); } @@ -154,7 +173,8 @@ return child; } - else { + else + { throw new Error(child + 'addChildAt: The index '+ index +' supplied is out of bounds ' + this.children.length); } }; @@ -165,15 +185,18 @@ * @param child {DisplayObject} * @param child2 {DisplayObject} */ -DisplayObjectContainer.prototype.swapChildren = function (child, child2) { - if (child === child2) { +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) { + if (index1 < 0 || index2 < 0) + { throw new Error('swapChildren: Both the supplied DisplayObjects must be a child of the caller.'); } @@ -187,10 +210,12 @@ * @param child {DisplayObject} The DisplayObject instance to identify * @return {Number} The index position of the child display object to identify */ -DisplayObjectContainer.prototype.getChildIndex = function (child) { +DisplayObjectContainer.prototype.getChildIndex = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { throw new Error('The supplied DisplayObject must be a child of the caller'); } @@ -203,8 +228,10 @@ * @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 */ -DisplayObjectContainer.prototype.setChildIndex = function (child, index) { - if (index < 0 || index >= this.children.length) { +DisplayObjectContainer.prototype.setChildIndex = function (child, index) +{ + if (index < 0 || index >= this.children.length) + { throw new Error('The supplied index is out of bounds'); } @@ -220,8 +247,10 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child at the given index, if any. */ -DisplayObjectContainer.prototype.getChildAt = function (index) { - if (index < 0 || index >= this.children.length) { +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'); } @@ -234,10 +263,12 @@ * @param child {DisplayObject} The DisplayObject to remove * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChild = function (child) { +DisplayObjectContainer.prototype.removeChild = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { return; } @@ -250,7 +281,8 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChildAt = function (index) { +DisplayObjectContainer.prototype.removeChildAt = function (index) +{ var child = this.getChildAt(index); child.parent = null; @@ -265,24 +297,29 @@ * @param beginIndex {Number} The beginning position. Default value is 0. * @param endIndex {Number} The ending position. Default value is size of the container. */ -DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) { +DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) +{ var begin = beginIndex || 0; var end = typeof endIndex === 'number' ? endIndex : this.children.length; var range = end - begin; - if (range > 0 && range <= end) { + if (range > 0 && range <= end) + { var removed = this.children.splice(begin, range); - for (var i = 0; i < removed.length; ++i) { + for (var i = 0; i < removed.length; ++i) + { removed[i].parent = null; } return removed; } - else if (range === 0 && this.children.length === 0) { + else if (range === 0 && this.children.length === 0) + { return []; } - else { + else + { throw new RangeError('removeChildren: numeric values are outside the acceptable range.'); } }; @@ -291,7 +328,8 @@ * Generates and updates the cached sprite for this object. * */ -DisplayObjectContainer.prototype.updateCachedSprite = function () { +DisplayObjectContainer.prototype.updateCachedSprite = function () +{ this._generateCachedSprite(); }; @@ -304,7 +342,8 @@ * @param renderer {CanvasRenderer|WebGLRenderer} The renderer used to generate the texture. * @return {Texture} a texture of the graphics object */ -DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) { +DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) +{ var bounds = this.getLocalBounds(); var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0, renderer, scaleMode, resolution); @@ -322,18 +361,22 @@ * * @private */ -DisplayObjectContainer.prototype.updateTransform = function () { - if (!this.visible) { +DisplayObjectContainer.prototype.updateTransform = function () +{ + if (!this.visible) + { return; } this.displayObjectUpdateTransform(); - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { return; } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } }; @@ -346,8 +389,10 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getBounds = function () { - if (this.children.length === 0) { +DisplayObjectContainer.prototype.getBounds = function () +{ + if (this.children.length === 0) + { return math.Rectangle.EMPTY; } @@ -365,10 +410,12 @@ var childVisible = false; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -386,7 +433,8 @@ maxY = maxY > childMaxY ? maxY : childMaxY; } - if (!childVisible) { + if (!childVisible) + { return math.Rectangle.EMPTY; } @@ -407,12 +455,14 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getLocalBounds = function () { +DisplayObjectContainer.prototype.getLocalBounds = function () +{ var matrixCache = this.worldTransform; this.worldTransform = math.Matrix.IDENTITY; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } @@ -428,13 +478,16 @@ * * @param renderer {WebGLRenderer} The renderer */ -DisplayObjectContainer.prototype.renderWebGL = function (renderer) { +DisplayObjectContainer.prototype.renderWebGL = function (renderer) +{ // if the object is not visible or the alpha is 0 then no need to render this element - if (!this.visible || this.alpha <= 0) { + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } @@ -442,14 +495,17 @@ var i, j; // do a quick check to see if this element has a mask or a filter. - if (this._mask || this._filters) { + if (this._mask || this._filters) + { // push filter first as we need to ensure the stencil buffer is correct for any masking - if (this._filters) { + if (this._filters) + { renderer.spriteBatch.flush(); renderer.filterManager.pushFilter(this._filterBlock); } - if (this._mask) { + if (this._mask) + { renderer.spriteBatch.stop(); renderer.maskManager.pushMask(this.mask, renderer); renderer.spriteBatch.start(); @@ -459,36 +515,42 @@ this._renderWebGL(renderer); // now loop through the children and make sure they get rendered - for (i = 0, j = this.children.length; i < j; i++) { + for (i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderWebGL(renderer); } // time to stop the sprite batch as either a mask element or a filter draw will happen next renderer.spriteBatch.stop(); - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(this._mask, renderer); } - if (this._filters) { + if (this._filters) + { renderer.filterManager.popFilter(); } renderer.spriteBatch.start(); } - else { + else + { this._renderWebGL(renderer); // simple render children! - for (i = 0, j = this.children.length; i < j; ++i) { + for (i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderWebGL(renderer); } } }; -DisplayObjectContainer.prototype._renderWebGL = function (renderer) { +DisplayObjectContainer.prototype._renderWebGL = function (renderer) +{ // this is where content itself gets renderd.. @@ -499,25 +561,31 @@ * * @param renderer {CanvasRenderer} The renderer */ -DisplayObjectContainer.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0) { +DisplayObjectContainer.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -528,13 +596,16 @@ * @param renderer {WebGLRenderer|CanvasRenderer} The renderer * @private */ -DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) { +DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) +{ this._cachedSprite.worldAlpha = this.worldAlpha; - if (renderer.gl) { + if (renderer.gl) + { this._cachedSprite.renderWebGL(renderer); } - else { + else + { this._cachedSprite.renderCanvas(renderer); } }; @@ -544,10 +615,12 @@ * * @private */ -DisplayObjectContainer.prototype._generateCachedSprite = function () { +DisplayObjectContainer.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { // TODO - RenderTexture now *requires* a renderer instance, so this is like broken // because `renderer` isn't actually in scope here :P var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0); @@ -555,7 +628,8 @@ this._cachedSprite = new Sprite(renderTexture); this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.texture.resize(bounds.width | 0, bounds.height | 0); } @@ -580,8 +654,10 @@ * * @private */ -DisplayObjectContainer.prototype._destroyCachedSprite = function () { - if (!this._cachedSprite) { +DisplayObjectContainer.prototype._destroyCachedSprite = function () +{ + if (!this._cachedSprite) + { return; } diff --git a/src/core/display/Sprite.js b/src/core/display/Sprite.js index 707da24..5862aef 100644 --- a/src/core/display/Sprite.js +++ b/src/core/display/Sprite.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param texture {Texture} The texture for this sprite */ -function Sprite(texture) { +function Sprite(texture) +{ DisplayObjectContainer.call(this); /** @@ -85,12 +86,14 @@ this.texture = texture || Texture.EMPTY; } -Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) { +Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) +{ DisplayObjectContainer.prototype.destroy.call(this); this.anchor = null; - if (destroyTexture) { + if (destroyTexture) + { this._texture.destroy(destroyBaseTexture); } @@ -111,10 +114,12 @@ * @memberof Sprite# */ width: { - get: function () { + get: function () + { return this.scale.x * this.texture.frame.width; }, - set: function (value) { + set: function (value) + { this.scale.x = value / this.texture.frame.width; this._width = value; } @@ -127,10 +132,12 @@ * @memberof Sprite# */ height: { - get: function () { + get: function () + { return this.scale.y * this.texture.frame.height; }, - set: function (value) { + set: function (value) + { this.scale.y = value / this.texture.frame.height; this._height = value; } @@ -143,23 +150,29 @@ * @memberof Sprite# */ texture: { - get: function () { + get: function () + { return this._texture; }, - set: function (value) { - if (this._texture === value) { + set: function (value) + { + if (this._texture === value) + { return; } this._texture = value; this.cachedTint = 0xFFFFFF; - if (value) { + if (value) + { // wait for the texture to load - if (value.baseTexture.hasLoaded) { + if (value.baseTexture.hasLoaded) + { this._onTextureUpdate(); } - else { + else + { value.once('update', this._onTextureUpdate.bind(this)); } } @@ -172,18 +185,22 @@ * * @private */ -Sprite.prototype._onTextureUpdate = function () { +Sprite.prototype._onTextureUpdate = function () +{ // so if _width is 0 then width was not set.. - if (this._width) { + if (this._width) + { this.scale.x = this._width / this.texture.frame.width; } - if (this._height) { + if (this._height) + { this.scale.y = this._height / this.texture.frame.height; } }; -Sprite.prototype._renderWebGL = function (renderer) { +Sprite.prototype._renderWebGL = function (renderer) +{ // this is where content gets renderd.. // watch this space for a little render state manager.. @@ -197,7 +214,8 @@ * @param matrix {Matrix} the transformation matrix of the sprite * @return {Rectangle} the framing rectangle */ -Sprite.prototype.getBounds = function (matrix) { +Sprite.prototype.getBounds = function (matrix) +{ var width = this.texture.frame.width; var height = this.texture.frame.height; @@ -224,11 +242,13 @@ if(b === 0 && c === 0) { // scale may be negative! - if (a < 0) { + if (a < 0) + { a *= -1; } - if (d < 0) { + if (d < 0) + { d *= -1; } @@ -293,28 +313,34 @@ * * @param renderer {CanvasRenderer} The renderer */ -Sprite.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) { +Sprite.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) + { return; } - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; renderer.context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } // Ignore null sources - if (this.texture.valid) { + if (this.texture.valid) + { var resolution = this.texture.baseTexture.resolution / renderer.resolution; renderer.context.globalAlpha = this.worldAlpha; // If smoothingEnabled is supported and we need to change the smoothing property for this texture - if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) { + if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) + { renderer.scaleMode = this.texture.baseTexture.scaleMode; renderer.context[renderer.smoothProperty] = (renderer.scaleMode === CONST.scaleModes.LINEAR); } @@ -324,7 +350,8 @@ var dy = (this.texture.trim ? this.texture.trim.y : 0) - (this.anchor.y * this.texture.trim.height); // Allow for pixel rounding - if (renderer.roundPixels) { + if (renderer.roundPixels) + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -337,7 +364,8 @@ dx = dx | 0; dy = dy | 0; } - else { + else + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -348,8 +376,10 @@ ); } - if (this.tint !== 0xFFFFFF) { - if (this.cachedTint !== this.tint) { + if (this.tint !== 0xFFFFFF) + { + if (this.cachedTint !== this.tint) + { this.cachedTint = this.tint; // TODO clean up caching - how to clean up the caches? @@ -368,7 +398,8 @@ this.texture.crop.height / resolution ); } - else { + else + { renderer.context.drawImage( this.texture.baseTexture.source, this.texture.crop.x, @@ -383,11 +414,13 @@ } } - for (var i = 0, j = this.children.length; i < j; i++) { + for (var i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -402,10 +435,12 @@ * @param frameId {String} The frame Id of the texture in the cache * @return {Sprite} A new Sprite using a texture from the texture cache matching the frameId */ -Sprite.fromFrame = function (frameId) { +Sprite.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache' + this); } @@ -420,6 +455,7 @@ * @param imageId {String} The image url of the texture * @return {Sprite} A new Sprite using a texture from the texture cache matching the image id */ -Sprite.fromImage = function (imageId, crossorigin, scaleMode) { +Sprite.fromImage = function (imageId, crossorigin, scaleMode) +{ return new Sprite(Texture.fromImage(imageId, crossorigin, scaleMode)); }; diff --git a/src/core/display/SpriteBatch.js b/src/core/display/SpriteBatch.js index 3187777..c196fef 100644 --- a/src/core/display/SpriteBatch.js +++ b/src/core/display/SpriteBatch.js @@ -12,7 +12,8 @@ * ```js * var container = new SpriteBatch(); * - * for(var i = 0; i < 100; ++i) { + * for(var i = 0; i < 100; ++i) + * { * var sprite = new PIXI.Sprite.fromImage("myImage.png"); * container.addChild(sprite); * } @@ -25,7 +26,8 @@ */ //TODO RENAME to PARTICLE CONTAINER? -function SpriteBatch() { +function SpriteBatch() +{ DisplayObjectContainer.call(this); } @@ -38,7 +40,8 @@ * * @private */ -SpriteBatch.prototype.updateTransform = function () { +SpriteBatch.prototype.updateTransform = function () +{ // TODO don't need to! this.displayObjectUpdateTransform(); // PIXI.DisplayObjectContainer.prototype.updateTransform.call( this ); @@ -50,8 +53,10 @@ * @param renderer {WebGLRenderer} The webgl renderer * @private */ -SpriteBatch.prototype.renderWebGL = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderWebGL = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -71,8 +76,10 @@ * @param renderer {CanvasRenderer} The canvas renderer * @private */ -SpriteBatch.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -84,10 +91,12 @@ this.displayObjectUpdateTransform(); - for (var i = 0; i < this.children.length; ++i) { + for (var i = 0; i < this.children.length; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -95,9 +104,11 @@ context.globalAlpha = this.worldAlpha * child.alpha; - if (child.rotation % (Math.PI * 2) === 0) { + if (child.rotation % (Math.PI * 2) === 0) + { // this is the fastest way to optimise! - if rotation is 0 then we can avoid any kind of setTransform call - if (isRotated) { + if (isRotated) + { context.setTransform( transform.a, transform.b, @@ -122,8 +133,10 @@ frame.height * child.scale.y ); } - else { - if (!isRotated) { + else + { + if (!isRotated) + { isRotated = true; } @@ -131,7 +144,8 @@ var childTransform = child.worldTransform; - if (renderer.roundPixels) { + if (renderer.roundPixels) + { context.setTransform( childTransform.a, childTransform.b, @@ -141,7 +155,8 @@ childTransform.ty | 0 ); } - else { + else + { context.setTransform( childTransform.a, childTransform.b, diff --git a/src/core/index.js b/src/core/index.js index 3954b6f..eb4a82b 100644 --- a/src/core/index.js +++ b/src/core/index.js @@ -58,11 +58,13 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRenderer: function (width, height, options, noWebGL) { + autoDetectRenderer: function (width, height, options, noWebGL) + { width = width || 800; height = height || 600; - if (!noWebGL && require('webgl-enabled')()) { + if (!noWebGL && require('webgl-enabled')()) + { return new core.WebGLRenderer(width, height, options); } @@ -87,7 +89,8 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRecommendedRenderer: function (width, height, options) { + autoDetectRecommendedRenderer: function (width, height, options) + { var isAndroid = /Android/i.test(navigator.userAgent); return core.autoDetectRenderer(width, height, options, isAndroid); diff --git a/src/core/math/Matrix.js b/src/core/math/Matrix.js index c2f87e2..2ff4848 100644 --- a/src/core/math/Matrix.js +++ b/src/core/math/Matrix.js @@ -10,7 +10,8 @@ * @class * @namespace PIXI */ -function Matrix() { +function Matrix() +{ /** * @member {number} * @default 1 @@ -63,7 +64,8 @@ * * @param array {number[]} The array that the matrix will be populated from. */ -Matrix.prototype.fromArray = function (array) { +Matrix.prototype.fromArray = function (array) +{ this.a = array[0]; this.b = array[1]; this.c = array[3]; @@ -78,14 +80,17 @@ * @param transpose {boolean} Whether we need to transpose the matrix or not * @return {number[]} the newly created array which contains the matrix */ -Matrix.prototype.toArray = function (transpose) { - if (!this.array) { +Matrix.prototype.toArray = function (transpose) +{ + if (!this.array) + { this.array = new Float32Array(9); } var array = this.array; - if (transpose) { + if (transpose) + { array[0] = this.a; array[1] = this.b; array[2] = 0; @@ -96,7 +101,8 @@ array[7] = this.ty; array[8] = 1; } - else { + else + { array[0] = this.a; array[1] = this.c; array[2] = this.tx; @@ -119,7 +125,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, transformed through this matrix */ -Matrix.prototype.apply = function (pos, newPos) { +Matrix.prototype.apply = function (pos, newPos) +{ newPos = newPos || new Point(); newPos.x = this.a * pos.x + this.c * pos.y + this.tx; @@ -136,7 +143,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, inverse-transformed through this matrix */ -Matrix.prototype.applyInverse = function (pos, newPos) { +Matrix.prototype.applyInverse = function (pos, newPos) +{ newPos = newPos || new Point(); var id = 1 / (this.a * this.d + this.c * -this.b); @@ -154,7 +162,8 @@ * @param {number} y * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.translate = function (x, y) { +Matrix.prototype.translate = function (x, y) +{ this.tx += x; this.ty += y; @@ -168,7 +177,8 @@ * @param {number} y The amount to scale vertically * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.scale = function (x, y) { +Matrix.prototype.scale = function (x, y) +{ this.a *= x; this.d *= y; this.c *= x; @@ -186,7 +196,8 @@ * @param {number} angle - The angle in radians. * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.rotate = function (angle) { +Matrix.prototype.rotate = function (angle) +{ var cos = Math.cos( angle ); var sin = Math.sin( angle ); @@ -210,7 +221,8 @@ * @param {Matrix} matrix * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.append = function (matrix) { +Matrix.prototype.append = function (matrix) +{ var a1 = this.a; var b1 = this.b; var c1 = this.c; @@ -232,7 +244,8 @@ * * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.identity = function () { +Matrix.prototype.identity = function () +{ this.a = 1; this.b = 0; this.c = 0; diff --git a/src/core/math/Point.js b/src/core/math/Point.js index 7565b2d..632f346 100644 --- a/src/core/math/Point.js +++ b/src/core/math/Point.js @@ -7,7 +7,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -function Point(x, y) { +function Point(x, y) +{ /** * @member {number} * @default 0 @@ -29,7 +30,8 @@ * * @return {Point} a copy of the point */ -Point.prototype.clone = function () { +Point.prototype.clone = function () +{ return new Point(this.x, this.y); }; @@ -40,7 +42,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -Point.prototype.set = function (x, y) { +Point.prototype.set = function (x, y) +{ this.x = x || 0; this.y = y || ( (y !== 0) ? this.x : 0 ) ; }; diff --git a/src/core/math/shapes/Circle.js b/src/core/math/shapes/Circle.js index 69cfdc9..4d76efc 100644 --- a/src/core/math/shapes/Circle.js +++ b/src/core/math/shapes/Circle.js @@ -10,7 +10,8 @@ * @param y {number} The Y coordinate of the center of this circle * @param radius {number} The radius of the circle */ -function Circle(x, y, radius) { +function Circle(x, y, radius) +{ /** * @member {number} * @default 0 @@ -46,7 +47,8 @@ * @method clone * @return {Circle} a copy of the Circle */ -Circle.prototype.clone = function () { +Circle.prototype.clone = function () +{ return new Circle(this.x, this.y, this.radius); }; @@ -58,8 +60,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Circle */ -Circle.prototype.contains = function (x, y) { - if (this.radius <= 0) { +Circle.prototype.contains = function (x, y) +{ + if (this.radius <= 0) + { return false; } @@ -79,6 +83,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Circle.prototype.getBounds = function () { +Circle.prototype.getBounds = function () +{ return new Rectangle(this.x - this.radius, this.y - this.radius, this.radius * 2, this.radius * 2); }; diff --git a/src/core/math/shapes/Ellipse.js b/src/core/math/shapes/Ellipse.js index 4f2d066..fefd01a 100644 --- a/src/core/math/shapes/Ellipse.js +++ b/src/core/math/shapes/Ellipse.js @@ -11,7 +11,8 @@ * @param width {number} The half width of this ellipse * @param height {number} The half height of this ellipse */ -function Ellipse(x, y, width, height) { +function Ellipse(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -53,7 +54,8 @@ * @method clone * @return {Ellipse} a copy of the ellipse */ -Ellipse.prototype.clone = function () { +Ellipse.prototype.clone = function () +{ return new Ellipse(this.x, this.y, this.width, this.height); }; @@ -65,8 +67,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coords are within this ellipse */ -Ellipse.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Ellipse.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } @@ -86,6 +90,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Ellipse.prototype.getBounds = function () { +Ellipse.prototype.getBounds = function () +{ return new Rectangle(this.x - this.width, this.y - this.height, this.width, this.height); }; diff --git a/src/core/math/shapes/Polygon.js b/src/core/math/shapes/Polygon.js index ae89148..fea6d37 100644 --- a/src/core/math/shapes/Polygon.js +++ b/src/core/math/shapes/Polygon.js @@ -10,16 +10,20 @@ * arguments passed can be flat x,y values e.g. `new Polygon(x,y, x,y, x,y, ...)` where `x` and `y` are * Numbers. */ -function Polygon(points) { +function Polygon(points) +{ //if points isn't an array, use arguments as the array - if (!(points instanceof Array)) { + if (!(points instanceof Array)) + { points = Array.prototype.slice.call(arguments); } //if this is a flat array of numbers, convert it to points - if (points[0] instanceof Point) { + if (points[0] instanceof Point) + { var p = []; - for (var i = 0, il = points.length; i < il; i++) { + for (var i = 0, il = points.length; i < il; i++) + { p.push(points[i].x, points[i].y); } @@ -51,7 +55,8 @@ * * @return {Polygon} a copy of the polygon */ -Polygon.prototype.clone = function () { +Polygon.prototype.clone = function () +{ return new Polygon(this.points.slice()); }; @@ -62,19 +67,22 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this polygon */ -Polygon.prototype.contains = function (x, y) { +Polygon.prototype.contains = function (x, y) +{ var inside = false; // use some raycasting to test hits // https://github.com/substack/point-in-polygon/blob/master/index.js var length = this.points.length / 2; - for (var i = 0, j = length - 1; i < length; j = i++) { + for (var i = 0, j = length - 1; i < length; j = i++) + { var xi = this.points[i * 2], yi = this.points[i * 2 + 1], xj = this.points[j * 2], yj = this.points[j * 2 + 1], intersect = ((yi > y) !== (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi); - if (intersect) { + if (intersect) + { inside = !inside; } } diff --git a/src/core/math/shapes/Rectangle.js b/src/core/math/shapes/Rectangle.js index 16ac62a..4008b68 100644 --- a/src/core/math/shapes/Rectangle.js +++ b/src/core/math/shapes/Rectangle.js @@ -10,7 +10,8 @@ * @param width {number} The overall width of this rectangle * @param height {number} The overall height of this rectangle */ -function Rectangle(x, y, width, height) { +function Rectangle(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -60,7 +61,8 @@ * * @return {Rectangle} a copy of the rectangle */ -Rectangle.prototype.clone = function () { +Rectangle.prototype.clone = function () +{ return new Rectangle(this.x, this.y, this.width, this.height); }; @@ -71,13 +73,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rectangle */ -Rectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Rectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/math/shapes/RoundedRectangle.js b/src/core/math/shapes/RoundedRectangle.js index 27d286e..7bf6411 100644 --- a/src/core/math/shapes/RoundedRectangle.js +++ b/src/core/math/shapes/RoundedRectangle.js @@ -11,7 +11,8 @@ * @param height {number} The overall height of this rounded rectangle * @param radius {number} Controls the radius of the rounded corners */ -function RoundedRectangle(x, y, width, height, radius) { +function RoundedRectangle(x, y, width, height, radius) +{ /** * @member {number} * @default 0 @@ -58,7 +59,8 @@ * * @return {RoundedRectangle} a copy of the rounded rectangle */ -RoundedRectangle.prototype.clone = function () { +RoundedRectangle.prototype.clone = function () +{ return new RoundedRectangle(this.x, this.y, this.width, this.height, this.radius); }; @@ -69,13 +71,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rounded Rectangle */ -RoundedRectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +RoundedRectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/primitives/Graphics.js b/src/core/primitives/Graphics.js index 261c534..e902d2a 100644 --- a/src/core/primitives/Graphics.js +++ b/src/core/primitives/Graphics.js @@ -16,7 +16,8 @@ * @extends DisplayObjectContainer * @namespace PIXI */ -function Graphics() { +function Graphics() +{ DisplayObjectContainer.call(this); this.renderable = true; @@ -154,16 +155,20 @@ * @private */ cacheAsBitmap: { - get: function () { + get: function () + { return this._cacheAsBitmap; }, - set: function (value) { + set: function (value) + { this._cacheAsBitmap = value; - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._generateCachedSprite(); } - else { + else + { this.destroyCachedSprite(); this.dirty = true; } @@ -176,7 +181,8 @@ * * @return {Graphics} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ var clone = new Graphics(); clone.renderable = this.renderable; @@ -192,7 +198,8 @@ clone.cachedSpriteDirty = this.cachedSpriteDirty; // copy graphics data - for (var i = 0; i < this.graphicsData.length; ++i) { + for (var i = 0; i < this.graphicsData.length; ++i) + { clone.graphicsData.push(this.graphicsData.clone()); } @@ -211,17 +218,21 @@ * @param alpha {number} alpha of the line to draw, will update the objects stored style * @return {Graphics} */ -Graphics.prototype.lineStyle = function (lineWidth, color, alpha) { +Graphics.prototype.lineStyle = function (lineWidth, color, alpha) +{ this.lineWidth = lineWidth || 0; this.lineColor = color || 0; this.lineAlpha = (arguments.length < 3) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length) + { // halfway through a line? start a new one! this.drawShape( new math.Polygon( this.currentPath.shape.points.slice(-2) )); } - else { + else + { // otherwise its empty so lets just set the line properties this.currentPath.lineWidth = this.lineWidth; this.currentPath.lineColor = this.lineColor; @@ -239,7 +250,8 @@ * @param y {number} the Y coordinate to move to * @return {Graphics} */ -Graphics.prototype.moveTo = function (x, y) { +Graphics.prototype.moveTo = function (x, y) +{ this.drawShape(new math.Polygon([x,y])); return this; @@ -253,7 +265,8 @@ * @param y {number} the Y coordinate to draw to * @return {Graphics} */ -Graphics.prototype.lineTo = function (x, y) { +Graphics.prototype.lineTo = function (x, y) +{ this.currentPath.shape.points.push(x, y); this.dirty = true; @@ -270,13 +283,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -285,7 +302,8 @@ n = 20, points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { this.moveTo(0, 0); } @@ -293,7 +311,8 @@ var fromY = points[points.length-1]; var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; xa = fromX + ( (cpX - fromX) * j ); @@ -319,13 +338,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -342,7 +365,8 @@ var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; dt = (1 - j); @@ -373,13 +397,17 @@ * @param radius {number} The radius of the arc * @return {Graphics} */ -Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points.push(x1, y1); } } - else { + else + { this.moveTo(x1, y1); } @@ -392,12 +420,15 @@ b2 = x2 - x1, mm = Math.abs(a1 * b2 - b1 * a2); - if (mm < 1.0e-8 || radius === 0) { - if (points[points.length-2] !== x1 || points[points.length-1] !== y1) { + if (mm < 1.0e-8 || radius === 0) + { + if (points[points.length-2] !== x1 || points[points.length-1] !== y1) + { points.push(x1, y1); } } - else { + else + { var dd = a1 * a1 + b1 * b1, cc = a2 * a2 + b2 * b2, tt = a1 * a2 + b1 * b2, @@ -433,42 +464,51 @@ * @param anticlockwise {boolean} Optional. Specifies whether the drawing should be counterclockwise or clockwise. False is default, and indicates clockwise, while true indicates counter-clockwise. * @return {Graphics} */ -Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) { +Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) +{ var startX = cx + Math.cos(startAngle) * radius; var startY = cy + Math.sin(startAngle) * radius; var points; // TODO - This if-else makes no sense. It uses currentPath in the else where it doesn't exist... - if (this.currentPath) { + if (this.currentPath) + { points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { points.push(startX, startY); } - else if (points[points.length-2] !== startX || points[points.length-1] !== startY) { + else if (points[points.length-2] !== startX || points[points.length-1] !== startY) + { points.push(startX, startY); } } - else { + else + { this.moveTo(startX, startY); points = this.currentPath.shape.points; } - if (startAngle === endAngle) { + if (startAngle === endAngle) + { return this; } - if (!anticlockwise && endAngle <= startAngle) { + if (!anticlockwise && endAngle <= startAngle) + { endAngle += Math.PI * 2; } - else if (anticlockwise && startAngle <= endAngle) { + else if (anticlockwise && startAngle <= endAngle) + { startAngle += Math.PI * 2; } var sweep = anticlockwise ? (startAngle - endAngle) *-1 : (endAngle - startAngle); var segs = (Math.abs(sweep)/ (Math.PI * 2)) * 40; - if (sweep === 0) { + if (sweep === 0) + { return this; } @@ -482,7 +522,8 @@ var remainder = ( segMinus % 1 ) / segMinus; - for (var i = 0; i <= segMinus; ++i) { + for (var i = 0; i <= segMinus; ++i) + { var real = i + remainder * i; var angle = ((theta) + startAngle + (theta2 * real)); @@ -506,13 +547,16 @@ * @param alpha {number} the alpha of the fill * @return {Graphics} */ -Graphics.prototype.beginFill = function (color, alpha) { +Graphics.prototype.beginFill = function (color, alpha) +{ this.filling = true; this.fillColor = color || 0; this.fillAlpha = (alpha === undefined) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length <= 2) + { this.currentPath.fill = this.filling; this.currentPath.fillColor = this.fillColor; this.currentPath.fillAlpha = this.fillAlpha; @@ -526,7 +570,8 @@ * * @return {Graphics} */ -Graphics.prototype.endFill = function () { +Graphics.prototype.endFill = function () +{ this.filling = false; this.fillColor = null; this.fillAlpha = 1; @@ -542,7 +587,8 @@ * @param height {number} The height of the rectangle * @return {Graphics} */ -Graphics.prototype.drawRect = function ( x, y, width, height ) { +Graphics.prototype.drawRect = function ( x, y, width, height ) +{ this.drawShape(new math.Rectangle(x,y, width, height)); return this; @@ -556,7 +602,8 @@ * @param height {number} The height of the rectangle * @param radius {number} Radius of the rectangle corners */ -Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) { +Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) +{ this.drawShape(new math.RoundedRectangle(x, y, width, height, radius)); return this; @@ -570,7 +617,8 @@ * @param radius {number} The radius of the circle * @return {Graphics} */ -Graphics.prototype.drawCircle = function (x, y, radius) { +Graphics.prototype.drawCircle = function (x, y, radius) +{ this.drawShape(new math.Circle(x,y, radius)); return this; @@ -585,7 +633,8 @@ * @param height {number} The half height of the ellipse * @return {Graphics} */ -Graphics.prototype.drawEllipse = function (x, y, width, height) { +Graphics.prototype.drawEllipse = function (x, y, width, height) +{ this.drawShape(new math.Ellipse(x, y, width, height)); return this; @@ -597,8 +646,10 @@ * @param path {Array} The path data used to construct the polygon. * @return {Graphics} */ -Graphics.prototype.drawPolygon = function (path) { - if (!(path instanceof Array)) { +Graphics.prototype.drawPolygon = function (path) +{ + if (!(path instanceof Array)) + { path = Array.prototype.slice.call(arguments); } @@ -612,7 +663,8 @@ * * @return {Graphics} */ -Graphics.prototype.clear = function () { +Graphics.prototype.clear = function () +{ this.lineWidth = 0; this.filling = false; @@ -631,7 +683,8 @@ * @param scaleMode {number} Should be one of the scaleMode consts * @return {Texture} a texture of the graphics object */ -Graphics.prototype.generateTexture = function (resolution, scaleMode) { +Graphics.prototype.generateTexture = function (resolution, scaleMode) +{ resolution = resolution || 1; var bounds = this.getBounds(); @@ -655,17 +708,21 @@ * * @param renderer {WebGLRenderer} */ -Graphics.prototype._renderWebGL = function (renderer) { +Graphics.prototype._renderWebGL = function (renderer) +{ // if the sprite is not visible or the alpha is 0 then no need to render this element - if (this.isMask === true) { + if (this.isMask === true) + { return; } // this code may still be needed so leaving for now.. - // + // /* - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture on the gpu too! @@ -681,17 +738,24 @@ return; } - */ - - // check if the webgl graphic needs to be updated - if (this.glDirty) { - this.dirty = true; - this.glDirty = false; - } + else */ - renderer.setObjectRendererer(renderer.graphicsRenderer); - renderer.graphicsRenderer.render(this); + renderer.spriteBatch.stop(); + renderer.blendModeManager.setBlendMode(this.blendMode); + // check blend mode + renderer.blendModeManager.setBlendMode( this.blendMode ); + + // check if the webgl graphic needs to be updated + if (this.glDirty) + { + this.dirty = true; + this.glDirty = false; + } + + WebGLGraphics.renderGraphics(this, renderer); + + renderer.spriteBatch.start(); }; /** @@ -700,14 +764,18 @@ * @param renderer {CanvasRenderer} * @private */ -Graphics.prototype.renderCanvas = function (renderer) { +Graphics.prototype.renderCanvas = function (renderer) +{ // 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.isMask === true) { + if (!this.visible || this.alpha <= 0 || this.isMask === true) + { return; } - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture @@ -723,16 +791,19 @@ return; } - else { + else + { var context = renderer.context; var transform = this.worldTransform; - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } @@ -748,11 +819,13 @@ CanvasGraphics.renderGraphics(this, context); - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } } @@ -763,13 +836,16 @@ * * @return {Rectangle} the rectangular bounding area */ -Graphics.prototype.getBounds = function (matrix) { +Graphics.prototype.getBounds = function (matrix) +{ // return an empty object if the item is a mask! - if (this.isMask) { + if (this.isMask) + { return math.Rectangle.EMPTY; } - if (this.dirty) { + if (this.dirty) + { this.updateLocalBounds(); this.glDirty = true; @@ -841,23 +917,27 @@ * Update the bounds of the object * */ -Graphics.prototype.updateLocalBounds = function () { +Graphics.prototype.updateLocalBounds = function () +{ var minX = Infinity; var maxX = -Infinity; var minY = Infinity; var maxY = -Infinity; - if (this.graphicsData.length) { + if (this.graphicsData.length) + { var shape, points, x, y, w, h; - for (var i = 0; i < this.graphicsData.length; i++) { + for (var i = 0; i < this.graphicsData.length; i++) + { var data = this.graphicsData[i]; var type = data.type; var lineWidth = data.lineWidth; shape = data.shape; - if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) { + if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) + { x = shape.x - lineWidth/2; y = shape.y - lineWidth/2; w = shape.width + lineWidth; @@ -869,7 +949,8 @@ minY = y < minY ? y : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.CIRC) { + else if (type === CONST.SHAPES.CIRC) + { x = shape.x; y = shape.y; w = shape.radius + lineWidth/2; @@ -881,7 +962,8 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.ELIP) { + else if (type === CONST.SHAPES.ELIP) + { x = shape.x; y = shape.y; w = shape.width + lineWidth/2; @@ -893,11 +975,13 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else { + else + { // POLY points = shape.points; - for (var j = 0; j < points.length; j += 2) { + for (var j = 0; j < points.length; j += 2) + { x = points[j]; y = points[j+1]; @@ -910,7 +994,8 @@ } } } - else { + else + { minX = 0; maxX = 0; minY = 0; @@ -931,10 +1016,12 @@ * * @private */ -Graphics.prototype._generateCachedSprite = function () { +Graphics.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { var canvasBuffer = new CanvasBuffer(bounds.width, bounds.height); var texture = Texture.fromCanvas(canvasBuffer.canvas); @@ -943,7 +1030,8 @@ this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.buffer.resize(bounds.width, bounds.height); } @@ -968,7 +1056,8 @@ * * @private */ -Graphics.prototype.updateCachedSpriteTexture = function () { +Graphics.prototype.updateCachedSpriteTexture = function () +{ var cachedSprite = this._cachedSprite; var texture = cachedSprite.texture; var canvas = cachedSprite.buffer.canvas; @@ -989,7 +1078,8 @@ * Destroys a previous cached sprite. * */ -Graphics.prototype.destroyCachedSprite = function () { +Graphics.prototype.destroyCachedSprite = function () +{ this._cachedSprite.texture.destroy(true); // let the gc collect the unused sprite @@ -1003,10 +1093,13 @@ * @param {Circle|Rectangle|Ellipse|Line|Polygon} shape The Shape object to draw. * @return {GraphicsData} The generated GraphicsData object. */ -Graphics.prototype.drawShape = function (shape) { - if (this.currentPath) { +Graphics.prototype.drawShape = function (shape) +{ + if (this.currentPath) + { // check current path! - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath.shape.points.length <= 2) + { this.graphicsData.pop(); } } @@ -1017,7 +1110,8 @@ this.graphicsData.push(data); - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { data.shape.closed = this.filling; this.currentPath = data; } diff --git a/src/core/primitives/GraphicsData.js b/src/core/primitives/GraphicsData.js index 99decbe..788f6f2 100644 --- a/src/core/primitives/GraphicsData.js +++ b/src/core/primitives/GraphicsData.js @@ -4,7 +4,8 @@ * @class * @namespace PIXI */ -function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) { +function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) +{ this.lineWidth = lineWidth; this.lineColor = lineColor; this.lineAlpha = lineAlpha; @@ -27,7 +28,8 @@ * * @return {GraphicsData} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ return new GraphicsData( this.lineWidth, this.lineColor, diff --git a/src/core/renderers/canvas/CanvasRenderer.js b/src/core/renderers/canvas/CanvasRenderer.js index 15a0978..7aebd44 100644 --- a/src/core/renderers/canvas/CanvasRenderer.js +++ b/src/core/renderers/canvas/CanvasRenderer.js @@ -17,17 +17,22 @@ * @param [options.resolution=1] {number} the resolution of the renderer retina would be 2 * @param [options.clearBeforeRender=true] {boolean} This sets if the CanvasRenderer will clear the canvas or not before the new render pass. */ -function CanvasRenderer(width, height, options) { +function CanvasRenderer(width, height, options) +{ utils.sayHello('Canvas'); - if (options) { - for (var i in CONST.defaultRenderOptions) { - if (typeof options[i] === 'undefined') { + if (options) + { + for (var i in CONST.defaultRenderOptions) + { + if (typeof options[i] === 'undefined') + { options[i] = CONST.defaultRenderOptions[i]; } } } - else { + else + { options = CONST.defaultRenderOptions; } @@ -156,19 +161,24 @@ this.smoothProperty = null; - if (this.context.imageSmoothingEnabled) { + if (this.context.imageSmoothingEnabled) + { this.smoothProperty = 'imageSmoothingEnabled'; } - else if (this.context.webkitImageSmoothingEnabled) { + else if (this.context.webkitImageSmoothingEnabled) + { this.smoothProperty = 'webkitImageSmoothingEnabled'; } - else if (this.context.mozImageSmoothingEnabled) { + else if (this.context.mozImageSmoothingEnabled) + { this.smoothProperty = 'mozImageSmoothingEnabled'; } - else if (this.context.oImageSmoothingEnabled) { + else if (this.context.oImageSmoothingEnabled) + { this.smoothProperty = 'oImageSmoothingEnabled'; } - else if (this.context.msImageSmoothingEnabled) { + else if (this.context.msImageSmoothingEnabled) + { this.smoothProperty = 'msImageSmoothingEnabled'; } @@ -193,10 +203,12 @@ * @memberof CanvasRenderer# */ backgroundColor: { - get: function () { + get: function () + { return this._backgroundColor; }, - set: function (val) { + set: function (val) + { this._backgroundColor = val; this._backgroundColorString = utils.hex2string(val); } @@ -208,7 +220,8 @@ * * @param object {DisplayObject} the object to be rendered */ -CanvasRenderer.prototype.render = function (object) { +CanvasRenderer.prototype.render = function (object) +{ object.updateTransform(); this.context.setTransform(1,0,0,1,0,0); @@ -218,16 +231,20 @@ this.currentBlendMode = CONST.blendModes.NORMAL; this.context.globalCompositeOperation = this.blendModes[CONST.blendModes.NORMAL]; - if (navigator.isCocoonJS && this.view.screencanvas) { + if (navigator.isCocoonJS && this.view.screencanvas) + { this.context.fillStyle = 'black'; this.context.clear(); } - if (this.clearBeforeRender) { - if (this.transparent) { + if (this.clearBeforeRender) + { + if (this.transparent) + { this.context.clearRect(0, 0, this.width, this.height); } - else { + else + { this.context.fillStyle = this._backgroundColorString; this.context.fillRect(0, 0, this.width , this.height); } @@ -241,8 +258,10 @@ * * @param [removeView=false] {boolean} Removes the Canvas element from the DOM. */ -CanvasRenderer.prototype.destroy = function (removeView) { - if (removeView && this.view.parent) { +CanvasRenderer.prototype.destroy = function (removeView) +{ + if (removeView && this.view.parent) + { this.view.parent.removeChild(this.view); } @@ -257,14 +276,16 @@ * @param width {number} the new width of the canvas view * @param height {number} the new height of the canvas view */ -CanvasRenderer.prototype.resize = function (width, height) { +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) { + if (this.autoResize) + { this.view.style.width = this.width / this.resolution + 'px'; this.view.style.height = this.height / this.resolution + 'px'; } @@ -276,7 +297,8 @@ * @param displayObject {DisplayObject} The displayObject to render * @private */ -CanvasRenderer.prototype.renderDisplayObject = function (displayObject) { +CanvasRenderer.prototype.renderDisplayObject = function (displayObject) +{ displayObject.renderCanvas(this); }; @@ -285,11 +307,14 @@ * * @private */ -CanvasRenderer.prototype._mapBlendModes = function () { - if (!this.blendModes) { +CanvasRenderer.prototype._mapBlendModes = function () +{ + if (!this.blendModes) + { this.blendModes = {}; - if (utils.canUseNewCanvasBlendModes()) { + if (utils.canUseNewCanvasBlendModes()) + { this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? this.blendModes[CONST.blendModes.MULTIPLY] = 'multiply'; @@ -308,7 +333,8 @@ this.blendModes[CONST.blendModes.COLOR] = 'color'; this.blendModes[CONST.blendModes.LUMINOSITY] = 'luminosity'; } - else { + else + { // this means that the browser does not support the cool new blend modes in canvas 'cough' ie 'cough' this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? diff --git a/src/core/renderers/canvas/utils/CanvasBuffer.js b/src/core/renderers/canvas/utils/CanvasBuffer.js index ebe5d47..b183a66 100644 --- a/src/core/renderers/canvas/utils/CanvasBuffer.js +++ b/src/core/renderers/canvas/utils/CanvasBuffer.js @@ -6,7 +6,8 @@ * @param width {number} the width for the newly created canvas * @param height {number} the height for the newly created canvas */ -function CanvasBuffer(width, height) { +function CanvasBuffer(width, height) +{ /** * The Canvas object that belongs to this CanvasBuffer. * @@ -36,10 +37,12 @@ * @memberof CanvasBuffer# */ width: { - get: function () { + get: function () + { return this.canvas.width; }, - set: function (val) { + set: function (val) + { this.canvas.width = val; } }, @@ -50,10 +53,12 @@ * @memberof CanvasBuffer# */ height: { - get: function () { + get: function () + { return this.canvas.height; }, - set: function (val) { + set: function (val) + { this.canvas.height = val; } } @@ -64,7 +69,8 @@ * * @private */ -CanvasBuffer.prototype.clear = function () { +CanvasBuffer.prototype.clear = function () +{ this.context.setTransform(1, 0, 0, 1, 0, 0); this.context.clearRect(0,0, this.canvas.width, this.canvas.height); }; @@ -75,7 +81,8 @@ * @param width {number} the new width of the canvas * @param height {number} the new height of the canvas */ -CanvasBuffer.prototype.resize = function (width, height) { +CanvasBuffer.prototype.resize = function (width, height) +{ this.canvas.width = width; this.canvas.height = height; }; diff --git a/src/core/renderers/canvas/utils/CanvasGraphics.js b/src/core/renderers/canvas/utils/CanvasGraphics.js index c7eaa2a..3f2a91f 100644 --- a/src/core/renderers/canvas/utils/CanvasGraphics.js +++ b/src/core/renderers/canvas/utils/CanvasGraphics.js @@ -13,15 +13,18 @@ * @param graphics {Graphics} the actual graphics object to render * @param context {CanvasRenderingContext2D} the 2d drawing method of the canvas */ -CanvasGraphics.renderGraphics = function (graphics, context) { +CanvasGraphics.renderGraphics = function (graphics, context) +{ var worldAlpha = graphics.worldAlpha; - if (graphics.dirty) { + if (graphics.dirty) + { this.updateGraphicsTint(graphics); graphics.dirty = false; } - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; @@ -30,69 +33,82 @@ context.lineWidth = data.lineWidth; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { context.beginPath(); var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } - if (shape.closed) { + if (shape.closed) + { context.lineTo(points[0], points[1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fillRect(shape.x, shape.y, shape.width, shape.height); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.strokeRect(shape.x, shape.y, shape.width, shape.height); } } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.beginPath(); context.arc(shape.x, shape.y, shape.radius,0,2*Math.PI); context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas var w = shape.width * 2; @@ -119,18 +135,21 @@ context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; var width = shape.width; @@ -152,13 +171,15 @@ context.quadraticCurveTo(rx, ry, rx, ry + radius); context.closePath(); - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); @@ -174,45 +195,54 @@ * @param graphics {Graphics} the graphics which will be used as a mask * @param context {CanvasRenderingContext2D} the context 2d method of the canvas */ -CanvasGraphics.renderGraphicsMask = function (graphics, context) { +CanvasGraphics.renderGraphicsMask = function (graphics, context) +{ var len = graphics.graphicsData.length; - if (len === 0) { + if (len === 0) + { return; } context.beginPath(); - for (var i = 0; i < len; i++) { + for (var i = 0; i < len; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { context.rect(shape.x, shape.y, shape.width, shape.height); context.closePath(); } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.arc(shape.x, shape.y, shape.radius, 0, 2 * Math.PI); context.closePath(); } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas @@ -237,7 +267,8 @@ context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); context.closePath(); } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; @@ -262,8 +293,10 @@ } }; -CanvasGraphics.updateGraphicsTint = function (graphics) { - if (graphics.tint === 0xFFFFFF) { +CanvasGraphics.updateGraphicsTint = function (graphics) +{ + if (graphics.tint === 0xFFFFFF) + { return; } @@ -271,7 +304,8 @@ var tintG = (graphics.tint >> 8 & 0xFF) / 255; var tintB = (graphics.tint & 0xFF)/ 255; - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var fillColor = data.fillColor | 0; diff --git a/src/core/renderers/canvas/utils/CanvasMaskManager.js b/src/core/renderers/canvas/utils/CanvasMaskManager.js index e04a733..9827d36 100644 --- a/src/core/renderers/canvas/utils/CanvasMaskManager.js +++ b/src/core/renderers/canvas/utils/CanvasMaskManager.js @@ -6,7 +6,8 @@ * @class * @namespace PIXI */ -function CanvasMaskManager() {} +function CanvasMaskManager() +{} CanvasMaskManager.prototype.constructor = CanvasMaskManager; module.exports = CanvasMaskManager; @@ -17,7 +18,8 @@ * @param maskData {object} the maskData that will be pushed * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.pushMask = function (maskData, renderer) { +CanvasMaskManager.prototype.pushMask = function (maskData, renderer) +{ renderer.context.save(); var cacheAlpha = maskData.alpha; @@ -45,6 +47,7 @@ * * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.popMask = function (renderer) { +CanvasMaskManager.prototype.popMask = function (renderer) +{ renderer.context.restore(); }; diff --git a/src/core/renderers/canvas/utils/CanvasTinter.js b/src/core/renderers/canvas/utils/CanvasTinter.js index 17e0529..d2fb1bc 100644 --- a/src/core/renderers/canvas/utils/CanvasTinter.js +++ b/src/core/renderers/canvas/utils/CanvasTinter.js @@ -14,7 +14,8 @@ * @param color {number} the color to use to tint the sprite with * @return {HTMLCanvasElement} The tinted canvas */ -CanvasTinter.getTintedTexture = function (sprite, color) { +CanvasTinter.getTintedTexture = function (sprite, color) +{ var texture = sprite.texture; color = CanvasTinter.roundColor(color); @@ -23,7 +24,8 @@ texture.tintCache = texture.tintCache || {}; - if (texture.tintCache[stringColor]) { + if (texture.tintCache[stringColor]) + { return texture.tintCache[stringColor]; } @@ -33,14 +35,16 @@ //CanvasTinter.tintWithPerPixel(texture, stringColor, canvas); CanvasTinter.tintMethod(texture, color, canvas); - if (CanvasTinter.convertTintToImage) { + if (CanvasTinter.convertTintToImage) + { // is this better? var tintImage = new Image(); tintImage.src = canvas.toDataURL(); texture.tintCache[stringColor] = tintImage; } - else { + else + { texture.tintCache[stringColor] = canvas; // if we are not converting the texture to an image then we need to lose the reference to the canvas CanvasTinter.canvas = null; @@ -56,7 +60,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithMultiply = function (texture, color, canvas) { +CanvasTinter.tintWithMultiply = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -104,7 +109,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithOverlay = function (texture, color, canvas) { +CanvasTinter.tintWithOverlay = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -139,7 +145,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithPerPixel = function (texture, color, canvas) { +CanvasTinter.tintWithPerPixel = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -167,7 +174,8 @@ var pixels = pixelData.data; - for (var i = 0; i < pixels.length; i += 4) { + for (var i = 0; i < pixels.length; i += 4) + { pixels[i+0] *= r; pixels[i+1] *= g; pixels[i+2] *= b; @@ -181,7 +189,8 @@ * * @param color {number} the color to round, should be a hex color */ -CanvasTinter.roundColor = function (color) { +CanvasTinter.roundColor = function (color) +{ var step = CanvasTinter.cacheStepsPerColorChannel; var rgbValues = utils.hex2rgb(color); diff --git a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js index 9f2f89a..35edbaf 100644 --- a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js +++ b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLBlendModeManager(renderer) { +function WebGLBlendModeManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -23,8 +24,10 @@ * * @param blendMode {number} the blendMode, should be a Pixi const, such as BlendModes.ADD */ -WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) { - if (this.currentBlendMode === blendMode) { +WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) +{ + if (this.currentBlendMode === blendMode) + { return false; } diff --git a/src/core/renderers/webgl/managers/WebGLFilterManager.js b/src/core/renderers/webgl/managers/WebGLFilterManager.js index 1179258..2dac048 100644 --- a/src/core/renderers/webgl/managers/WebGLFilterManager.js +++ b/src/core/renderers/webgl/managers/WebGLFilterManager.js @@ -7,7 +7,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLFilterManager(renderer) { +function WebGLFilterManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -32,7 +33,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.texturePool.length = 0; self.initShaderBuffers(); }); @@ -46,7 +48,8 @@ * @param renderer {WebGLRenderer} * @param buffer {ArrayBuffer} */ -WebGLFilterManager.prototype.begin = function (buffer) { +WebGLFilterManager.prototype.begin = function (buffer) +{ this.defaultShader = this.renderer.shaderManager.defaultShader; this.width = this.renderer.projection.x * 2; @@ -60,7 +63,8 @@ * * @param filterBlock {object} the filter that will be pushed to the current filter stack */ -WebGLFilterManager.prototype.pushFilter = function (filterBlock) { +WebGLFilterManager.prototype.pushFilter = function (filterBlock) +{ var gl = this.renderer.gl; var projection = this.renderer.projection; @@ -78,10 +82,12 @@ this.offsetY += filterBlock._filterArea.y; var texture = this.texturePool.pop(); - if (!texture) { + if (!texture) + { texture = new FilterTexture(this.renderer.gl, this.width, this.height); } - else { + else + { texture.resize(this.width, this.height); } @@ -98,29 +104,35 @@ var localX = filterArea.x, localY = filterArea.y; - if (filterArea.x < 0) { + if (filterArea.x < 0) + { filterArea.width += filterArea.x; filterArea.x = 0; } - if (filterArea.y < 0) { + if (filterArea.y < 0) + { filterArea.height += filterArea.y; filterArea.y = 0; } - if (localX + filterArea.width > this.width) { + if (localX + filterArea.width > this.width) + { filterArea.width = this.width - localX; } - if (localY + filterArea.height > this.height) { + if (localY + filterArea.height > this.height) + { filterArea.height = this.height - localY; } - if (filterArea.width < 0) { + if (filterArea.width < 0) + { filterArea.width = 0; } - if (filterArea.height < 0) { + if (filterArea.height < 0) + { filterArea.height = 0; } @@ -154,7 +166,8 @@ * Removes the last filter from the filter stack and doesn't return it. * */ -WebGLFilterManager.prototype.popFilter = function () { +WebGLFilterManager.prototype.popFilter = function () +{ var gl = this.renderer.gl; var filterBlock = this.filterStack.pop(); @@ -163,7 +176,8 @@ var projection = this.renderer.projection; var offset = this.renderer.offset; - if (filterBlock.filterPasses.length > 1) { + if (filterBlock.filterPasses.length > 1) + { gl.viewport(0, 0, filterArea.width, filterArea.height); gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); @@ -193,7 +207,8 @@ var inputTexture = texture; var outputTexture = this.texturePool.pop(); - if (!outputTexture) { + if (!outputTexture) + { outputTexture = new FilterTexture(this.renderer.gl, this.width, this.height); } outputTexture.resize(this.width, this.height); @@ -204,7 +219,8 @@ gl.disable(gl.BLEND); - for (var i = 0; i < filterBlock.filterPasses.length-1; i++) { + for (var i = 0; i < filterBlock.filterPasses.length-1; i++) + { var filterPass = filterBlock.filterPasses[i]; gl.bindFramebuffer(gl.FRAMEBUFFER, outputTexture.frameBuffer ); @@ -243,10 +259,12 @@ var buffer = this.buffer; // time to render the filters texture to the previous scene - if (this.filterStack.length === 0) { + if (this.filterStack.length === 0) + { gl.colorMask(true, true, true, true);//this.transparent); } - else { + else + { var currentFilter = this.filterStack[this.filterStack.length-1]; filterArea = currentFilter._filterArea; @@ -332,13 +350,15 @@ * @param width {number} the horizontal range of the filter * @param height {number} the vertical range of the filter */ -WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) { +WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) +{ // use program var gl = this.renderer.gl; var shader = filter.shaders[gl.id]; - if (!shader) { + if (!shader) + { shader = new Shader(gl); shader.fragmentSrc = filter.fragmentSrc; @@ -356,7 +376,8 @@ gl.uniform2f(shader.projectionVector, width/2, -height/2); gl.uniform2f(shader.offsetVector, 0,0); - if (filter.uniforms.dimensions) { + 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]; @@ -386,7 +407,8 @@ * Initialises the shader buffers. * */ -WebGLFilterManager.prototype.initShaderBuffers = function () { +WebGLFilterManager.prototype.initShaderBuffers = function () +{ var gl = this.renderer.gl; // create some buffers @@ -432,7 +454,8 @@ * Destroys the filter and removes it from the filter stack. * */ -WebGLFilterManager.prototype.destroy = function () { +WebGLFilterManager.prototype.destroy = function () +{ var gl = this.renderer.gl; this.filterStack = null; @@ -441,7 +464,8 @@ this.offsetY = 0; // destroy textures - for (var i = 0; i < this.texturePool.length; i++) { + for (var i = 0; i < this.texturePool.length; i++) + { this.texturePool[i].destroy(); } diff --git a/src/core/renderers/webgl/managers/WebGLManager.js b/src/core/renderers/webgl/managers/WebGLManager.js index 9d47b5c..c30cd51 100644 --- a/src/core/renderers/webgl/managers/WebGLManager.js +++ b/src/core/renderers/webgl/managers/WebGLManager.js @@ -3,7 +3,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLManager(renderer) { +function WebGLManager(renderer) +{ /** * The renderer this manager works for. * @@ -15,6 +16,7 @@ WebGLManager.prototype.constructor = WebGLManager; module.exports = WebGLManager; -WebGLManager.prototype.destroy = function () { +WebGLManager.prototype.destroy = function () +{ this.renderer = null; }; diff --git a/src/core/renderers/webgl/managers/WebGLMaskManager.js b/src/core/renderers/webgl/managers/WebGLMaskManager.js index 2f90b64..e568812 100644 --- a/src/core/renderers/webgl/managers/WebGLMaskManager.js +++ b/src/core/renderers/webgl/managers/WebGLMaskManager.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLMaskManager(renderer) { +function WebGLMaskManager(renderer) +{ WebGLManager.call(this, renderer); } @@ -19,12 +20,15 @@ * * @param maskData {any[]} */ -WebGLMaskManager.prototype.pushMask = function (maskData) { - if (maskData.dirty) { +WebGLMaskManager.prototype.pushMask = function (maskData) +{ + if (maskData.dirty) + { WebGLGraphics.updateGraphics(maskData, this.renderer.gl); } - if (!maskData._webGL[this.renderer.gl.id].data.length) { + if (!maskData._webGL[this.renderer.gl.id].data.length) + { return; } @@ -36,6 +40,7 @@ * * @param maskData {any[]} */ -WebGLMaskManager.prototype.popMask = function (maskData) { +WebGLMaskManager.prototype.popMask = function (maskData) +{ this.renderer.stencilManager.popStencil(maskData, maskData._webGL[this.renderer.gl.id].data[0], this.renderer); }; diff --git a/src/core/renderers/webgl/managers/WebGLShaderManager.js b/src/core/renderers/webgl/managers/WebGLShaderManager.js index fef071c..90c6477 100644 --- a/src/core/renderers/webgl/managers/WebGLShaderManager.js +++ b/src/core/renderers/webgl/managers/WebGLShaderManager.js @@ -10,7 +10,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLShaderManager(renderer) { +function WebGLShaderManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -28,7 +29,8 @@ */ this.tempAttribState = []; - for (var i = 0; i < this.maxAttibs; i++) { + for (var i = 0; i < this.maxAttibs; i++) + { this.attribState[i] = false; } @@ -66,7 +68,8 @@ // listen for context and update necessary shaders var self = this; - this.renderer.on('context', function (event) { + this.renderer.on('context', function (event) + { var gl = event.data; // this shader is used for rendering primitives @@ -97,29 +100,36 @@ * * @param attribs {Array} attribs */ -WebGLShaderManager.prototype.setAttribs = function (attribs) { +WebGLShaderManager.prototype.setAttribs = function (attribs) +{ // reset temp state var i; - for (i = 0; i < this.tempAttribState.length; i++) { + for (i = 0; i < this.tempAttribState.length; i++) + { this.tempAttribState[i] = false; } // set the new attribs - for (var a in attribs) { + for (var a in attribs) + { this.tempAttribState[attribs[a]] = true; } var gl = this.renderer.gl; - for (i = 0; i < this.attribState.length; i++) { - if (this.attribState[i] !== this.tempAttribState[i]) { + for (i = 0; i < this.attribState.length; i++) + { + if (this.attribState[i] !== this.tempAttribState[i]) + { this.attribState[i] = this.tempAttribState[i]; - if (this.attribState[i]) { + if (this.attribState[i]) + { gl.enableVertexAttribArray(i); } - else { + else + { gl.disableVertexAttribArray(i); } } @@ -131,8 +141,10 @@ * * @param shader {Any} */ -WebGLShaderManager.prototype.setShader = function (shader) { - if (this._currentId === shader.uuid) { +WebGLShaderManager.prototype.setShader = function (shader) +{ + if (this._currentId === shader.uuid) + { return false; } @@ -150,7 +162,8 @@ * Destroys this object. * */ -WebGLShaderManager.prototype.destroy = function () { +WebGLShaderManager.prototype.destroy = function () +{ this.attribState = null; this.tempAttribState = null; diff --git a/src/core/renderers/webgl/managers/WebGLStencilManager.js b/src/core/renderers/webgl/managers/WebGLStencilManager.js index 9ec6398..4cb0134 100644 --- a/src/core/renderers/webgl/managers/WebGLStencilManager.js +++ b/src/core/renderers/webgl/managers/WebGLStencilManager.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLStencilManager(renderer) { +function WebGLStencilManager(renderer) +{ WebGLManager.call(this, renderer); this.stencilStack = []; @@ -24,12 +25,14 @@ * @param graphics {Graphics} * @param webGLData {any[]} */ -WebGLStencilManager.prototype.pushStencil = function (graphics, webGLData) { +WebGLStencilManager.prototype.pushStencil = function (graphics, webGLData) +{ var gl = this.renderer.gl; this.bindGraphics(graphics, webGLData, this.renderer); - if (this.stencilStack.length === 0) { + if (this.stencilStack.length === 0) + { gl.enable(gl.STENCIL_TEST); gl.clear(gl.STENCIL_BUFFER_BIT); this.reverse = true; @@ -47,14 +50,17 @@ // draw the triangle strip! - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } @@ -62,31 +68,38 @@ // draw a quad to increment.. gl.drawElements(gl.TRIANGLE_FAN, 4, gl.UNSIGNED_SHORT, ( webGLData.indices.length - 4 ) * 2 ); - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); } this.reverse = !this.reverse; } - else { - if (!this.reverse) { + else + { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } - else { + 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) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); } } @@ -103,7 +116,8 @@ * @param graphics {Graphics} * @param webGLData {Array} */ -WebGLStencilManager.prototype.bindGraphics = function (graphics, webGLData) { +WebGLStencilManager.prototype.bindGraphics = function (graphics, webGLData) +{ //if (this._currentGraphics === graphics)return; this._currentGraphics = graphics; @@ -114,7 +128,8 @@ offset = this.renderer.offset, shader;// = this.renderer.shaderManager.primitiveShader; - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { shader = this.renderer.shaderManager.complexPrimitiveShader; this.renderer.shaderManager.setShader(shader); @@ -141,7 +156,8 @@ // set the index buffer! gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, webGLData.indexBuffer); } - else { + else + { //this.renderer.shaderManager.activatePrimitiveShader(); shader = this.renderer.shaderManager.primitiveShader; this.renderer.shaderManager.setShader( shader ); @@ -154,7 +170,7 @@ gl.uniform2f(shader.uniforms.offsetVector._location, -offset.x, -offset.y); gl.uniform3fv(shader.uniforms.tint._location, utils.hex2rgb(graphics.tint)); - + gl.uniform1f(shader.uniforms.alpha._location, graphics.worldAlpha); @@ -172,19 +188,22 @@ * @param graphics {Graphics} * @param webGLData {Array} */ -WebGLStencilManager.prototype.popStencil = function (graphics, webGLData) { +WebGLStencilManager.prototype.popStencil = function (graphics, webGLData) +{ var gl = this.renderer.gl; this.stencilStack.pop(); this.count--; - if (this.stencilStack.length === 0) { + if (this.stencilStack.length === 0) + { // the stack is empty! gl.disable(gl.STENCIL_TEST); } - else { + else + { var level = this.count; @@ -192,14 +211,17 @@ gl.colorMask(false, false, false, false); - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { this.reverse = !this.reverse; - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } @@ -213,31 +235,38 @@ // draw the triangle strip! gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); - if (!this.reverse) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); } } - else { + else + { // console.log("<<>>") - if (!this.reverse) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } - else { + 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) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); } } @@ -253,7 +282,8 @@ * Destroys the mask stack. * */ -WebGLStencilManager.prototype.destroy = function () { +WebGLStencilManager.prototype.destroy = function () +{ this.renderer = null; this.stencilStack = null; }; diff --git a/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js b/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js index 913ba5e..1ea7d19 100644 --- a/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js +++ b/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function ComplexPrimitiveShader(gl) { +function ComplexPrimitiveShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -24,7 +25,8 @@ 'uniform float flipY;', 'varying vec4 vColor;', - 'void main(void) {', + '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);', @@ -37,7 +39,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = vColor;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/FastShader.js b/src/core/renderers/webgl/shaders/FastShader.js index bd2e29a..2e5e060 100644 --- a/src/core/renderers/webgl/shaders/FastShader.js +++ b/src/core/renderers/webgl/shaders/FastShader.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function FastShader(gl) { +function FastShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -28,7 +29,8 @@ 'const vec2 center = vec2(-1.0, 1.0);', - 'void main(void) {', + 'void main(void) + {', ' vec2 v;', ' vec2 sv = aVertexPosition * aScale;', ' v.x = (sv.x) * cos(aRotation) - (sv.y) * sin(aRotation);', @@ -49,7 +51,8 @@ 'uniform sampler2D uSampler;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/PrimitiveShader.js b/src/core/renderers/webgl/shaders/PrimitiveShader.js index 6f25409..a25f54f 100644 --- a/src/core/renderers/webgl/shaders/PrimitiveShader.js +++ b/src/core/renderers/webgl/shaders/PrimitiveShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function PrimitiveShader(gl) { +function PrimitiveShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -23,7 +24,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + '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);', @@ -36,7 +38,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = vColor;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/Shader.js b/src/core/renderers/webgl/shaders/Shader.js index f8964f5..fd75ef5 100644 --- a/src/core/renderers/webgl/shaders/Shader.js +++ b/src/core/renderers/webgl/shaders/Shader.js @@ -6,7 +6,8 @@ * @param [fragmentSrc] {string} The source of the fragment shader. * @param [vertexSrc] {string} The source of the vertex shader. */ -function Shader(gl, vertexSrc, fragmentSrc, customUniforms, customAttributes) { +function Shader(gl, vertexSrc, fragmentSrc, customUniforms, customAttributes) +{ /** * @member {number} * @readonly @@ -33,7 +34,8 @@ dimensions: { type: '4f', value: new Float32Array(4) } }; - for (var u in customUniforms) { + for (var u in customUniforms) + { this.uniforms[u] = customUniforms[u]; } @@ -43,7 +45,8 @@ aColor: 0 }; - for (var a in customAttributes) { + for (var a in customAttributes) + { this.attributes[a] = customAttributes[a]; } @@ -66,7 +69,8 @@ 'const vec2 center = vec2(-1.0, 1.0);', - 'void main(void) {', + 'void main(void) + {', ' gl_Position = vec4( ((aVertexPosition + offsetVector) / projectionVector) + center , 0.0, 1.0);', ' vTextureCoord = aTextureCoord;', ' vColor = vec4(aColor.rgb * aColor.a, aColor.a);', @@ -85,7 +89,8 @@ 'uniform sampler2D uSampler;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;', '}' ].join('\n'); @@ -96,7 +101,8 @@ Shader.prototype.constructor = Shader; module.exports = Shader; -Shader.prototype.init = function () { +Shader.prototype.init = function () +{ this.compile(); this.gl.useProgram(this.program); @@ -105,14 +111,18 @@ this.cacheAttributeLocations(Object.keys(this.attributes)); }; -Shader.prototype.cacheUniformLocations = function (keys) { - for (var i = 0; i < keys.length; ++i) { +Shader.prototype.cacheUniformLocations = function (keys) +{ + for (var i = 0; i < keys.length; ++i) + { this.uniforms[keys[i]]._location = this.gl.getUniformLocation(this.program, keys[i]); } }; -Shader.prototype.cacheAttributeLocations = function (keys) { - for (var i = 0; i < keys.length; ++i) { +Shader.prototype.cacheAttributeLocations = function (keys) +{ + for (var i = 0; i < keys.length; ++i) + { this.attributes[keys[i]] = this.gl.getAttribLocation(this.program, keys[i]); } @@ -124,14 +134,16 @@ // 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.attributes.aColor === -1) { + // if (this.attributes.aColor === -1) + { // this.attributes.aColor = 2; // } // End worst hack eva // }; -Shader.prototype.compile = function () { +Shader.prototype.compile = function () +{ var gl = this.gl; var glVertShader = this._glCompile(gl.VERTEX_SHADER, this.vertexSrc); @@ -144,13 +156,15 @@ gl.linkProgram(program); // if linking fails, then log and cleanup - if (!gl.getProgramParameter(program, gl.LINK_STATUS)) { + if (!gl.getProgramParameter(program, gl.LINK_STATUS)) + { window.console.error('Pixi.js Error: Could not initialize shader.'); window.console.error('gl.VALIDATE_STATUS', gl.getProgramParameter(program, gl.VALIDATE_STATUS)); window.console.error('gl.getError()', gl.getError()); // if there is a program info log, log it - if (gl.getProgramInfoLog(program) !== '') { + if (gl.getProgramInfoLog(program) !== '') + { window.console.warn('Pixi.js Warning: gl.getProgramInfoLog()', gl.getProgramInfoLog(program)); } @@ -165,18 +179,21 @@ return (this.program = program); }; -Shader.prototype.syncUniforms = function () { +Shader.prototype.syncUniforms = function () +{ var gl = this.gl; this.textureCount = 1; - for (var key in this.uniforms) { + for (var key in this.uniforms) + { var uniform = this.uniforms[key], location = uniform._location, value = uniform.value, i, il; - switch (uniform.type) { + switch (uniform.type) + { // single int value case 'i': case '1i': @@ -282,7 +299,8 @@ // a Color Value case 'c': - if (typeof value === 'number') { + if (typeof value === 'number') + { value = utils.hex2rgb(value); } @@ -311,11 +329,13 @@ // array of 2D Point objects case 'v2v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(2 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 2] = value[i].x; uniform._array[i * 2 + 1] = value[i].y; } @@ -325,11 +345,13 @@ // array of 3D Point objects case 'v3v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(3 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 3] = value[i].x; uniform._array[i * 3 + 1] = value[i].y; uniform._array[i * 3 + 2] = value[i].z; @@ -341,11 +363,13 @@ // array of 4D Point objects case 'v4v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(4 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 4] = value[i].x; uniform._array[i * 4 + 1] = value[i].y; uniform._array[i * 4 + 2] = value[i].z; @@ -359,7 +383,8 @@ // PIXI.Texture case 't': case 'sampler2D': - if (!uniform.value || !uniform.value.baseTexture || !uniform.value.baseTexture.hasLoaded) { + if (!uniform.value || !uniform.value.baseTexture || !uniform.value.baseTexture.hasLoaded) + { break; } @@ -376,7 +401,8 @@ this.textureCount++; // initialize the texture if we haven't yet - if (!uniform._init) { + if (!uniform._init) + { this.initSampler2D(uniform); uniform._init = true; @@ -394,11 +420,13 @@ * Initialises a Sampler2D uniform (which may only be available later on after initUniforms once the texture has loaded) * */ -Shader.prototype.initSampler2D = function (uniform) { +Shader.prototype.initSampler2D = function (uniform) +{ var gl = this.gl; // Extended texture data - if (uniform.textureData) { + if (uniform.textureData) + { var data = uniform.textureData; // GLTexture = mag linear, min linear_mipmap_linear, wrap repeat + gl.generateMipmap(gl.TEXTURE_2D); @@ -417,14 +445,16 @@ var wrapT = (data.wrapT) ? data.wrapT : gl.CLAMP_TO_EDGE; var format = (data.luminance) ? gl.LUMINANCE : gl.RGBA; - if (data.repeat) { + if (data.repeat) + { wrapS = gl.REPEAT; wrapT = gl.REPEAT; } gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, !!data.flipY); - if (data.width) { + if (data.width) + { var width = (data.width) ? data.width : 512; var height = (data.height) ? data.height : 2; var border = (data.border) ? data.border : 0; @@ -432,7 +462,8 @@ // 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 { + 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); } @@ -448,7 +479,8 @@ * Destroys the shader. * */ -Shader.prototype.destroy = function () { +Shader.prototype.destroy = function () +{ this.gl.deleteProgram(this.program); this.gl = null; @@ -459,13 +491,15 @@ this.fragmentSrc = null; }; -Shader.prototype._glCompile = function (type, src) { +Shader.prototype._glCompile = function (type, src) +{ var shader = this.gl.createShader(type); this.gl.shaderSource(shader, src); this.gl.compileShader(shader); - if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) { + if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) + { window.console.log(this.gl.getShaderInfoLog(shader)); return null; } diff --git a/src/core/renderers/webgl/shaders/StripShader.js b/src/core/renderers/webgl/shaders/StripShader.js index 193f6e1..a7abcc6 100644 --- a/src/core/renderers/webgl/shaders/StripShader.js +++ b/src/core/renderers/webgl/shaders/StripShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function StripShader(gl) { +function StripShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -20,7 +21,8 @@ 'varying vec2 vTextureCoord;', - 'void main(void) {', + '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);', @@ -36,7 +38,8 @@ 'varying vec2 vTextureCoord;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vec2(vTextureCoord.x, vTextureCoord.y)) * alpha;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/utils/FilterTexture.js b/src/core/renderers/webgl/utils/FilterTexture.js index d2c8423..4433d44 100644 --- a/src/core/renderers/webgl/utils/FilterTexture.js +++ b/src/core/renderers/webgl/utils/FilterTexture.js @@ -8,7 +8,8 @@ * @param height {number} the vertical range of the filter * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values */ -function FilterTexture(gl, width, height, scaleMode) { +function FilterTexture(gl, width, height, scaleMode) +{ /** * @member {WebGLContext} */ @@ -59,7 +60,8 @@ * Clears the filter texture. * */ -FilterTexture.prototype.clear = function () { +FilterTexture.prototype.clear = function () +{ var gl = this.gl; gl.clearColor(0,0,0, 0); @@ -72,8 +74,10 @@ * @param width {number} the new width of the texture * @param height {number} the new height of the texture */ -FilterTexture.prototype.resize = function (width, height) { - if (this.width === width && this.height === height) { +FilterTexture.prototype.resize = function (width, height) +{ + if (this.width === width && this.height === height) + { return; } @@ -96,7 +100,8 @@ * Destroys the filter texture. * */ -FilterTexture.prototype.destroy = function () { +FilterTexture.prototype.destroy = function () +{ var gl = this.gl; gl.deleteFramebuffer( this.frameBuffer ); gl.deleteTexture( this.texture ); diff --git a/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js b/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js index c4721e9..a63f4d7 100644 --- a/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js +++ b/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js @@ -14,7 +14,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this sprite batch works for. */ -function WebGLFastSpriteBatch(renderer) { +function WebGLFastSpriteBatch(renderer) +{ /** * The renderer instance this sprite batch operates on. * @@ -91,7 +92,8 @@ */ this.lastIndexCount = 0; - for (var i=0, j=0; i < numIndices; i += 6, j += 4) { + 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; @@ -144,7 +146,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.setupContext(); }); } @@ -157,7 +160,8 @@ * * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLFastSpriteBatch.prototype.setupContext = function () { +WebGLFastSpriteBatch.prototype.setupContext = function () +{ var gl = this.renderer.gl; // create a couple of buffers @@ -177,7 +181,8 @@ /** * @param spriteBatch {SpriteBatch} The SpriteBatch container to prepare for. */ -WebGLFastSpriteBatch.prototype.begin = function (spriteBatch) { +WebGLFastSpriteBatch.prototype.begin = function (spriteBatch) +{ this.shader = this.renderer.shaderManager.fastShader; this.matrix = spriteBatch.worldTransform.toArray(true); @@ -187,33 +192,38 @@ /** */ -WebGLFastSpriteBatch.prototype.end = function () { +WebGLFastSpriteBatch.prototype.end = function () +{ this.flush(); }; /** * @param spriteBatch {SpriteBatch} The SpriteBatch container to render. */ -WebGLFastSpriteBatch.prototype.render = function (spriteBatch) { +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) { + if (!sprite.texture._uvs) + { return; } this.currentBaseTexture = sprite.texture.baseTexture; // check blend mode - if (sprite.blendMode !== this.renderer.blendModeManager.currentBlendMode) { + if (sprite.blendMode !== this.renderer.blendModeManager.currentBlendMode) + { this.flush(); this.renderer.blendModeManager.setBlendMode(sprite.blendMode); } - for (var i=0,j= children.length; i= this.size) { + if (this.currentBatchSize >= this.size) + { this.flush(); } }; @@ -362,29 +379,35 @@ /** * */ -WebGLFastSpriteBatch.prototype.flush = function () { +WebGLFastSpriteBatch.prototype.flush = function () +{ // If the batch is length 0 then return as there is nothing to draw - if (this.currentBatchSize === 0) { + if (this.currentBatchSize === 0) + { return; } var gl = this.renderer.gl; // bind the current texture - if (!this.currentBaseTexture._glTextures[gl.id]) { + if (!this.currentBaseTexture._glTextures[gl.id]) + { this.renderer.updateTexture(this.currentBaseTexture, gl); } //TODO-SHOUD THIS BE ELSE??!?!?! - else { + else + { gl.bindTexture(gl.TEXTURE_2D, this.currentBaseTexture._glTextures[gl.id]); } // upload the verts to the buffer - if (this.currentBatchSize > ( this.size * 0.5 ) ) { + if (this.currentBatchSize > ( this.size * 0.5 ) ) + { gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); } - else { + else + { var view = this.vertices.subarray(0, this.currentBatchSize * this.vertByteSize); gl.bufferSubData(gl.ARRAY_BUFFER, 0, view); @@ -405,14 +428,16 @@ * Ends the batch and flushes * */ -WebGLFastSpriteBatch.prototype.stop = function () { +WebGLFastSpriteBatch.prototype.stop = function () +{ this.flush(); }; /** * */ -WebGLFastSpriteBatch.prototype.start = function () { +WebGLFastSpriteBatch.prototype.start = function () +{ var gl = this.renderer.gl; // bind the main texture diff --git a/src/core/renderers/webgl/utils/WebGLGraphics.js b/src/core/renderers/webgl/utils/WebGLGraphics.js index 55f4911..ab8f46e 100644 --- a/src/core/renderers/webgl/utils/WebGLGraphics.js +++ b/src/core/renderers/webgl/utils/WebGLGraphics.js @@ -19,7 +19,8 @@ * @param graphics {Graphics} * @param renderer {WebGLRenderer} */ -WebGLGraphics.renderGraphics = function (graphics, renderer) {//projection, offset) { +WebGLGraphics.renderGraphics = function (graphics, renderer) {//projection, offset) +{ var gl = renderer.gl; var projection = renderer.projection, @@ -27,7 +28,8 @@ shader = renderer.shaderManager.primitiveShader, webGLData; - if (graphics.dirty) { + if (graphics.dirty) + { WebGLGraphics.updateGraphics(graphics, gl); } @@ -35,8 +37,10 @@ // This could be speeded up for sure! - for (var i = 0; i < webGL.data.length; i++) { - if (webGL.data[i].mode === 1) { + for (var i = 0; i < webGL.data.length; i++) + { + if (webGL.data[i].mode === 1) + { webGLData = webGL.data[i]; renderer.stencilManager.pushStencil(graphics, webGLData, renderer); @@ -46,7 +50,8 @@ renderer.stencilManager.popStencil(graphics, webGLData, renderer); } - else { + else + { webGLData = webGL.data[i]; @@ -84,12 +89,14 @@ * @param graphicsData {Graphics} The graphics object to update * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLGraphics.updateGraphics = function (graphics, gl) { +WebGLGraphics.updateGraphics = function (graphics, gl) +{ // get the contexts graphics object var webGL = graphics._webGL[gl.id]; // if the graphics object does not exist in the webGL context time to create it! - if (!webGL) { + if (!webGL) + { webGL = graphics._webGL[gl.id] = {lastIndex:0, data:[], gl:gl}; } @@ -99,11 +106,13 @@ var i; // if the user cleared the graphics object we will need to clear every object - if (graphics.clearDirty) { + if (graphics.clearDirty) + { graphics.clearDirty = false; // lop through and return all the webGLDatas to the object pool so than can be reused later on - for (i = 0; i < webGL.data.length; i++) { + for (i = 0; i < webGL.data.length; i++) + { var graphicsData = webGL.data[i]; graphicsData.reset(); WebGLGraphics.graphicsDataPool.push( graphicsData ); @@ -119,58 +128,72 @@ // loop through the graphics datas and construct each one.. // if the object is a complex fill then the new stencil buffer technique will be used // other wise graphics objects will be pushed into a batch.. - for (i = webGL.lastIndex; i < graphics.graphicsData.length; i++) { + for (i = webGL.lastIndex; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { // need to add the points the the graphics object.. data.points = data.shape.points.slice(); - if (data.shape.closed) { + if (data.shape.closed) + { // close the poly if the value is true! - if (data.points[0] !== data.points[data.points.length-2] || data.points[1] !== data.points[data.points.length-1]) { + if (data.points[0] !== data.points[data.points.length-2] || data.points[1] !== data.points[data.points.length-1]) + { data.points.push(data.points[0], data.points[1]); } } // MAKE SURE WE HAVE THE CORRECT TYPE.. - if (data.fill) { - if (data.points.length >= 6) { - if (data.points.length < 6 * 2) { + if (data.fill) + { + if (data.points.length >= 6) + { + if (data.points.length < 6 * 2) + { webGLData = WebGLGraphics.switchMode(webGL, 0); var canDrawUsingSimple = WebGLGraphics.buildPoly(data, webGLData); // console.log(canDrawUsingSimple); - if (!canDrawUsingSimple) { + if (!canDrawUsingSimple) + { // console.log("<>>>") webGLData = WebGLGraphics.switchMode(webGL, 1); WebGLGraphics.buildComplexPoly(data, webGLData); } } - else { + else + { webGLData = WebGLGraphics.switchMode(webGL, 1); WebGLGraphics.buildComplexPoly(data, webGLData); } } } - if (data.lineWidth > 0) { + if (data.lineWidth > 0) + { webGLData = WebGLGraphics.switchMode(webGL, 0); WebGLGraphics.buildLine(data, webGLData); } } - else { + else + { webGLData = WebGLGraphics.switchMode(webGL, 0); - if (data.type === CONST.SHAPES.RECT) { + if (data.type === CONST.SHAPES.RECT) + { WebGLGraphics.buildRectangle(data, webGLData); } - else if (data.type === CONST.SHAPES.CIRC || data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.CIRC || data.type === CONST.SHAPES.ELIP) + { WebGLGraphics.buildCircle(data, webGLData); } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { WebGLGraphics.buildRoundedRectangle(data, webGLData); } } @@ -179,10 +202,12 @@ } // upload all the dirty data... - for (i = 0; i < webGL.data.length; i++) { + for (i = 0; i < webGL.data.length; i++) + { webGLData = webGL.data[i]; - if (webGLData.dirty) { + if (webGLData.dirty) + { webGLData.upload(); } } @@ -194,18 +219,22 @@ * @param webGL {WebGLContext} * @param type {number} */ -WebGLGraphics.switchMode = function (webGL, type) { +WebGLGraphics.switchMode = function (webGL, type) +{ var webGLData; - if (!webGL.data.length) { + if (!webGL.data.length) + { webGLData = WebGLGraphics.graphicsDataPool.pop() || new WebGLGraphicsData(webGL.gl); webGLData.mode = type; webGL.data.push(webGLData); } - else { + else + { webGLData = webGL.data[webGL.data.length-1]; - if (webGLData.mode !== type || type === 1) { + if (webGLData.mode !== type || type === 1) + { webGLData = WebGLGraphics.graphicsDataPool.pop() || new WebGLGraphicsData(webGL.gl); webGLData.mode = type; webGL.data.push(webGLData); @@ -225,7 +254,8 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildRectangle = function (graphicsData, webGLData) { +WebGLGraphics.buildRectangle = function (graphicsData, webGLData) +{ // --- // // need to convert points to a nice regular data // @@ -235,7 +265,8 @@ var width = rectData.width; var height = rectData.height; - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -265,7 +296,8 @@ indices.push(vertPos, vertPos, vertPos+1, vertPos+2, vertPos+3, vertPos+3); } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = [x, y, @@ -289,7 +321,8 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildRoundedRectangle = function (graphicsData, webGLData) { +WebGLGraphics.buildRoundedRectangle = function (graphicsData, webGLData) +{ var rrectData = graphicsData.shape; var x = rrectData.x; var y = rrectData.y; @@ -305,7 +338,8 @@ recPoints = recPoints.concat(WebGLGraphics.quadraticBezierCurve(x + width, y + radius, x + width, y, x + width - radius, y)); recPoints = recPoints.concat(WebGLGraphics.quadraticBezierCurve(x + radius, y, x, y, x, y + radius)); - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -323,7 +357,8 @@ // var i = 0; - for (i = 0; i < triangles.length; i+=3) { + for (i = 0; i < triangles.length; i+=3) + { indices.push(triangles[i] + vecPos); indices.push(triangles[i] + vecPos); indices.push(triangles[i+1] + vecPos); @@ -332,12 +367,14 @@ } - for (i = 0; i < recPoints.length; i++) { + for (i = 0; i < recPoints.length; i++) + { verts.push(recPoints[i], recPoints[++i], r, g, b, alpha); } } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = recPoints; @@ -362,7 +399,8 @@ * @param toY {number} Destination point y * @return {number[]} */ -WebGLGraphics.quadraticBezierCurve = function (fromX, fromY, cpX, cpY, toX, toY) { +WebGLGraphics.quadraticBezierCurve = function (fromX, fromY, cpX, cpY, toX, toY) +{ var xa, ya, @@ -373,14 +411,16 @@ n = 20, points = []; - function getPt(n1 , n2, perc) { + function getPt(n1 , n2, perc) + { var diff = n2 - n1; return n1 + ( diff * perc ); } var j = 0; - for (var i = 0; i <= n; i++ ) { + for (var i = 0; i <= n; i++ ) + { j = i / n; // The Green Line @@ -406,7 +446,8 @@ * @param graphicsData {Graphics} The graphics object to draw * @param webGLData {object} */ -WebGLGraphics.buildCircle = function (graphicsData, webGLData) { +WebGLGraphics.buildCircle = function (graphicsData, webGLData) +{ // need to convert points to a nice regular data var circleData = graphicsData.shape; var x = circleData.x; @@ -415,11 +456,13 @@ var height; // TODO - bit hacky?? - if (graphicsData.type === CONST.SHAPES.CIRC) { + if (graphicsData.type === CONST.SHAPES.CIRC) + { width = circleData.radius; height = circleData.radius; } - else { + else + { width = circleData.width; height = circleData.height; } @@ -429,7 +472,8 @@ var i = 0; - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -444,7 +488,8 @@ indices.push(vecPos); - for (i = 0; i < totalSegs + 1 ; i++) { + for (i = 0; i < totalSegs + 1 ; i++) + { verts.push(x,y, r, g, b, alpha); verts.push(x + Math.sin(seg * i) * width, @@ -457,12 +502,14 @@ indices.push(vecPos-1); } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = []; - for (i = 0; i < totalSegs + 1; i++) { + for (i = 0; i < totalSegs + 1; i++) + { graphicsData.points.push(x + Math.sin(seg * i) * width, y + Math.cos(seg * i) * height); } @@ -481,18 +528,22 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildLine = function (graphicsData, webGLData) { +WebGLGraphics.buildLine = function (graphicsData, webGLData) +{ // TODO OPTIMISE! var i = 0; var points = graphicsData.points; - if (points.length === 0) { + if (points.length === 0) + { return; } // if the line width is an odd number add 0.5 to align to a whole pixel - if (graphicsData.lineWidth%2) { - for (i = 0; i < points.length; i++) { + if (graphicsData.lineWidth%2) + { + for (i = 0; i < points.length; i++) + { points[i] += 0.5; } } @@ -502,7 +553,8 @@ var lastPoint = new math.Point(points[points.length - 2], points[points.length - 1]); // if the first point is the last point - gonna have issues :) - if (firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) { + if (firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) + { // need to clone as we are going to slightly modify the shape.. points = points.slice(); @@ -562,7 +614,8 @@ verts.push(p1x + perpx , p1y + perpy, r, g, b, alpha); - for (i = 1; i < length-1; i++) { + for (i = 1; i < length-1; i++) + { p1x = points[(i-1)*2]; p1y = points[(i-1)*2 + 1]; @@ -599,7 +652,8 @@ denom = a1*b2 - a2*b1; - if (Math.abs(denom) < 0.1 ) { + if (Math.abs(denom) < 0.1 ) + { denom+=10.1; verts.push(p2x - perpx , p2y - perpy, @@ -618,7 +672,8 @@ pdist = (px -p2x) * (px -p2x) + (py -p2y) + (py -p2y); - if (pdist > 140 * 140) { + if (pdist > 140 * 140) + { perp3x = perpx - perp2x; perp3y = perpy - perp2y; @@ -639,7 +694,8 @@ indexCount++; } - else { + else + { verts.push(px , py); verts.push(r, g, b, alpha); @@ -672,7 +728,8 @@ indices.push(indexStart); - for (i = 0; i < indexCount; i++) { + for (i = 0; i < indexCount; i++) + { indices.push(indexStart++); } @@ -687,11 +744,13 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildComplexPoly = function (graphicsData, webGLData) { +WebGLGraphics.buildComplexPoly = function (graphicsData, webGLData) +{ //TODO - no need to copy this as it gets turned into a FLoat32Array anyways.. var points = graphicsData.points.slice(); - if (points.length < 6) { + if (points.length < 6) + { return; } @@ -711,7 +770,8 @@ var x,y; // get size.. - for (var i = 0; i < points.length; i+=2) { + for (var i = 0; i < points.length; i+=2) + { x = points[i]; y = points[i+1]; @@ -732,7 +792,8 @@ //TODO - this aint needed! var length = points.length / 2; - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { indices.push( i ); } @@ -746,10 +807,12 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildPoly = function (graphicsData, webGLData) { +WebGLGraphics.buildPoly = function (graphicsData, webGLData) +{ var points = graphicsData.points; - if (points.length < 6) { + if (points.length < 6) + { return; } // get first and last point.. figure out the middle! @@ -767,7 +830,8 @@ var triangles = utils.PolyK.Triangulate(points); - if (!triangles) { + if (!triangles) + { return false; } @@ -775,7 +839,8 @@ var i = 0; - for (i = 0; i < triangles.length; i+=3) { + for (i = 0; i < triangles.length; i+=3) + { indices.push(triangles[i] + vertPos); indices.push(triangles[i] + vertPos); indices.push(triangles[i+1] + vertPos); @@ -783,7 +848,8 @@ indices.push(triangles[i+2] + vertPos); } - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { verts.push(points[i * 2], points[i * 2 + 1], r, g, b, alpha); } diff --git a/src/core/renderers/webgl/utils/WebGLGraphicsData.js b/src/core/renderers/webgl/utils/WebGLGraphicsData.js index c56d05e..c739ba7 100644 --- a/src/core/renderers/webgl/utils/WebGLGraphicsData.js +++ b/src/core/renderers/webgl/utils/WebGLGraphicsData.js @@ -2,7 +2,8 @@ * @class * @private */ -function WebGLGraphicsData(gl) { +function WebGLGraphicsData(gl) +{ this.gl = gl; //TODO does this need to be split before uploding?? @@ -22,7 +23,8 @@ /** * */ -WebGLGraphicsData.prototype.reset = function () { +WebGLGraphicsData.prototype.reset = function () +{ this.points.length = 0; this.indices.length = 0; }; @@ -30,7 +32,8 @@ /** * */ -WebGLGraphicsData.prototype.upload = function () { +WebGLGraphicsData.prototype.upload = function () +{ var gl = this.gl; // this.lastIndex = graphics.graphicsData.length; diff --git a/src/core/renderers/webgl/utils/WebGLSpriteBatch.js b/src/core/renderers/webgl/utils/WebGLSpriteBatch.js index 96eaa52..55befbb 100644 --- a/src/core/renderers/webgl/utils/WebGLSpriteBatch.js +++ b/src/core/renderers/webgl/utils/WebGLSpriteBatch.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this sprite batch works for. */ -function WebGLSpriteBatch(renderer) { +function WebGLSpriteBatch(renderer) +{ /** * * @@ -88,7 +89,8 @@ */ this.lastIndexCount = 0; - for (var i=0, j=0; i < numIndices; i += 6, j += 4) { + 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; @@ -162,7 +164,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.setupContext(); }); } @@ -173,7 +176,8 @@ /** * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLSpriteBatch.prototype.setupContext = function () { +WebGLSpriteBatch.prototype.setupContext = function () +{ var gl = this.renderer.gl; // setup default shader @@ -198,7 +202,8 @@ /** * */ -WebGLSpriteBatch.prototype.begin = function () { +WebGLSpriteBatch.prototype.begin = function () +{ // this.shader = this.renderer.shaderManager.defaultShader; this.start(); @@ -206,19 +211,22 @@ /** */ -WebGLSpriteBatch.prototype.end = function () { +WebGLSpriteBatch.prototype.end = function () +{ this.flush(); }; /** * @param sprite {Sprite} the sprite to render when using this spritebatch */ -WebGLSpriteBatch.prototype.render = function (sprite) { +WebGLSpriteBatch.prototype.render = function (sprite) +{ var texture = sprite.texture; //TODO set blend modes.. // check texture.. - if (this.currentBatchSize >= this.size) { + if (this.currentBatchSize >= this.size) + { this.flush(); this.currentBaseTexture = texture.baseTexture; } @@ -227,7 +235,8 @@ var uvs = texture._uvs; // if the uvs have not updated then no point rendering just yet! - if (!uvs) { + if (!uvs) + { return; } @@ -237,7 +246,8 @@ var w0, w1, h0, h1; - if (texture.trim) { + 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; @@ -248,7 +258,8 @@ h0 = h1 + texture.crop.height; } - else { + else + { w0 = (texture.frame.width ) * (1-aX); w1 = (texture.frame.width ) * -aX; @@ -272,7 +283,8 @@ var colors = this.colors; var positions = this.positions; - if (this.renderer.roundPixels) { + if (this.renderer.roundPixels) + { // xy positions[index] = a * w1 + c * h1 + tx | 0; positions[index+1] = d * h1 + b * w1 + ty | 0; @@ -289,7 +301,8 @@ positions[index+15] = a * w1 + c * h0 + tx | 0; positions[index+16] = d * h0 + b * w1 + ty | 0; } - else { + else + { // xy positions[index] = a * w1 + c * h1 + tx; positions[index+1] = d * h1 + b * w1 + ty; @@ -338,11 +351,13 @@ * * @param sprite {TilingSprite} the tilingSprite to render */ -WebGLSpriteBatch.prototype.renderTilingSprite = function (tilingSprite) { +WebGLSpriteBatch.prototype.renderTilingSprite = function (tilingSprite) +{ var texture = tilingSprite.tilingTexture; // check texture.. - if (this.currentBatchSize >= this.size) { + if (this.currentBatchSize >= this.size) + { //return; this.flush(); this.currentBaseTexture = texture.baseTexture; @@ -351,7 +366,8 @@ // set the textures uvs temporarily // TODO create a separate texture so that we can tile part of a texture - if (!tilingSprite._uvs) { + if (!tilingSprite._uvs) + { tilingSprite._uvs = new TextureUvs(); } @@ -454,16 +470,19 @@ * Renders the content and empties the current batch. * */ -WebGLSpriteBatch.prototype.flush = function () { +WebGLSpriteBatch.prototype.flush = function () +{ // If the batch is length 0 then return as there is nothing to draw - if (this.currentBatchSize === 0) { + if (this.currentBatchSize === 0) + { return; } var gl = this.renderer.gl; var shader; - if (this.dirty) { + if (this.dirty) + { this.dirty = false; // bind the main texture gl.activeTexture(gl.TEXTURE0); @@ -482,10 +501,12 @@ } // upload the verts to the buffer - if (this.currentBatchSize > ( this.size * 0.5 ) ) { + if (this.currentBatchSize > ( this.size * 0.5 ) ) + { gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); } - else { + else + { var view = this.positions.subarray(0, this.currentBatchSize * this.vertByteSize); gl.bufferSubData(gl.ARRAY_BUFFER, 0, view); } @@ -502,7 +523,8 @@ var shaderSwap = false; var sprite; - for (var i = 0, j = this.currentBatchSize; i < j; i++) { + for (var i = 0, j = this.currentBatchSize; i < j; i++) + { sprite = this.sprites[i]; @@ -513,24 +535,28 @@ blendSwap = currentBlendMode !== nextBlendMode; shaderSwap = currentShader !== nextShader; // should I use uuidS??? - if (currentBaseTexture !== nextTexture || blendSwap || shaderSwap) { + if (currentBaseTexture !== nextTexture || blendSwap || shaderSwap) + { this.renderBatch(currentBaseTexture, batchSize, start); start = i; batchSize = 0; currentBaseTexture = nextTexture; - if (blendSwap) { + if (blendSwap) + { currentBlendMode = nextBlendMode; this.renderer.blendModeManager.setBlendMode( currentBlendMode ); } - if (shaderSwap) { + if (shaderSwap) + { currentShader = nextShader; shader = currentShader.shaders ? currentShader.shaders[gl.id] : currentShader; - if (!shader) { + if (!shader) + { shader = new Shader(gl, null, currentShader.fragmentSrc, currentShader.uniforms); currentShader.shaders[gl.id] = shader; } @@ -538,7 +564,8 @@ // set shader function??? this.renderer.shaderManager.setShader(shader); - if (shader.dirty) { + if (shader.dirty) + { shader.syncUniforms(); } @@ -569,17 +596,21 @@ * @param size {number} * @param startIndex {number} */ -WebGLSpriteBatch.prototype.renderBatch = function (texture, size, startIndex) { - if (size === 0) { +WebGLSpriteBatch.prototype.renderBatch = function (texture, size, startIndex) +{ + if (size === 0) + { return; } var gl = this.renderer.gl; - if (!texture._glTextures[gl.id]) { + if (!texture._glTextures[gl.id]) + { this.renderer.updateTexture(texture); } - else { + else + { // bind the current texture gl.bindTexture(gl.TEXTURE_2D, texture._glTextures[gl.id]); } @@ -594,7 +625,8 @@ /** * */ -WebGLSpriteBatch.prototype.stop = function () { +WebGLSpriteBatch.prototype.stop = function () +{ this.flush(); this.dirty = true; }; @@ -602,7 +634,8 @@ /** * */ -WebGLSpriteBatch.prototype.start = function () { +WebGLSpriteBatch.prototype.start = function () +{ this.dirty = true; }; @@ -610,7 +643,8 @@ * Destroys the SpriteBatch. * */ -WebGLSpriteBatch.prototype.destroy = function () { +WebGLSpriteBatch.prototype.destroy = function () +{ this.renderer.gl.deleteBuffer(this.vertexBuffer); this.renderer.gl.deleteBuffer(this.indexBuffer); diff --git a/src/core/textures/BaseTexture.js b/src/core/textures/BaseTexture.js index 2bf77d4..513d358 100644 --- a/src/core/textures/BaseTexture.js +++ b/src/core/textures/BaseTexture.js @@ -10,7 +10,8 @@ * @param source {Image|Canvas} the source object of the texture. * @param [scaleMode=scaleModes.DEFAULT] {number} See {@link scaleModes} for possible values */ -function BaseTexture(source, scaleMode) { +function BaseTexture(source, scaleMode) +{ this.uuid = utils.uuid(); /** @@ -123,7 +124,8 @@ this._needsUpdate = false; // if no source passed don't try to load - if (source) { + if (source) + { this.loadSource(source); } @@ -149,13 +151,16 @@ Object.defineProperties(BaseTexture.prototype, { needsUpdate: { - get: function () { + get: function () + { return this._needsUpdate; }, - set: function (val) { + set: function (val) + { this._needsUpdate = val; - if (val) { + if (val) + { this.emit('update', this); } } @@ -171,9 +176,11 @@ * * The logic state after calling `loadSource` directly or indirectly (eg. `fromImage`, `new BaseTexture`) is: * - * if (texture.hasLoaded) { + * if (texture.hasLoaded) + { * // texture ready for use - * } else if (texture.isLoading) { + * } else if (texture.isLoading) + { * // listen to 'loaded' and/or 'error' events on texture * } else { * // not loading, not going to load UNLESS the source is reloaded @@ -183,12 +190,14 @@ * @protected * @param source {Image|Canvas} the source object of the texture. */ -BaseTexture.prototype.loadSource = function (source) { +BaseTexture.prototype.loadSource = function (source) +{ var wasLoading = this.isLoading; this.hasLoaded = false; this.isLoading = false; - if (wasLoading && this.source) { + if (wasLoading && this.source) + { this.source.onload = null; this.source.onerror = null; } @@ -196,20 +205,24 @@ this.source = source; // Apply source if loaded. Otherwise setup appropriate loading monitors. - if ((this.source.complete || this.source.getContext) && this.source.width && this.source.height) { + if ((this.source.complete || this.source.getContext) && this.source.width && this.source.height) + { this._sourceLoaded(); } - else if(!source.getContext) { + else if(!source.getContext) + { // Image fail / not ready this.isLoading = true; var scope = this; - source.onload = function () { + source.onload = function () + { source.onload = null; source.onerror = null; - if(!scope.isLoading) { + if(!scope.isLoading) + { return; } @@ -219,11 +232,13 @@ scope.emit('loaded', scope); }; - source.onerror = function () { + source.onerror = function () + { source.onload = null; source.onerror = null; - if(!scope.isLoading) { + if(!scope.isLoading) + { return; } @@ -234,24 +249,29 @@ // Per http://www.w3.org/TR/html5/embedded-content-0.html#the-img-element // "The value of `complete` can thus change while a script is executing." // So complete needs to be re-checked after the callbacks have been added.. - if (source.complete) { + if (source.complete) + { this.isLoading = false; // ..and if we're complete now, no need for callbacks source.onload = null; source.onerror = null; - if (source.width && source.height) { + if (source.width && source.height) + { this._sourceLoaded(); // If any previous subscribers possible - if (wasLoading) { + if (wasLoading) + { this.emit('loaded', this); } } - else { + else + { // If any previous subscribers possible - if (wasLoading) { + if (wasLoading) + { this.emit('error', this); } } @@ -265,7 +285,8 @@ * * @private */ -BaseTexture.prototype._sourceLoaded = function () { +BaseTexture.prototype._sourceLoaded = function () +{ this.hasLoaded = true; this.width = this.source.naturalWidth || this.source.width; @@ -278,16 +299,20 @@ * Destroys this base texture * */ -BaseTexture.prototype.destroy = function () { - if (this.imageUrl) { +BaseTexture.prototype.destroy = function () +{ + if (this.imageUrl) + { delete utils.BaseTextureCache[this.imageUrl]; delete utils.TextureCache[this.imageUrl]; this.imageUrl = null; - if (!navigator.isCocoonJS) { + if (!navigator.isCocoonJS) + { this.source.src = ''; } } - else if (this.source && this.source._pixiId) { + else if (this.source && this.source._pixiId) + { delete utils.BaseTextureCache[this.source._pixiId]; } this.source = null; @@ -301,7 +326,8 @@ * memory again. * */ -BaseTexture.prototype.dispose = function () { +BaseTexture.prototype.dispose = function () +{ this.emit('dispose', this); }; @@ -311,7 +337,8 @@ * * @param newSrc {string} the path of the image */ -BaseTexture.prototype.updateSourceImage = function (newSrc) { +BaseTexture.prototype.updateSourceImage = function (newSrc) +{ this.source.src = newSrc; this.loadSource(this.source); }; @@ -326,18 +353,22 @@ * @param [scaleMode=scaleModes.DEFAULT] {number} See {@link scaleModes} for possible values * @return BaseTexture */ -BaseTexture.fromImage = function (imageUrl, crossorigin, scaleMode) { +BaseTexture.fromImage = function (imageUrl, crossorigin, scaleMode) +{ var baseTexture = utils.BaseTextureCache[imageUrl]; - if (crossorigin === undefined && imageUrl.indexOf('data:') !== 0) { + if (crossorigin === undefined && imageUrl.indexOf('data:') !== 0) + { crossorigin = true; } - if (!baseTexture) { + if (!baseTexture) + { // new Image() breaks tex loading in some versions of Chrome. // See https://code.google.com/p/chromium/issues/detail?id=238071 var image = new Image();//document.createElement('img'); - if (crossorigin) { + if (crossorigin) + { image.crossOrigin = ''; } @@ -347,7 +378,8 @@ utils.BaseTextureCache[imageUrl] = baseTexture; // if there is an @2x at the end of the url we are going to assume its a highres image - if ( imageUrl.indexOf(CONST.RETINA_PREFIX + '.') !== -1) { + if ( imageUrl.indexOf(CONST.RETINA_PREFIX + '.') !== -1) + { baseTexture.resolution = 2; } } @@ -363,14 +395,17 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return BaseTexture */ -BaseTexture.fromCanvas = function (canvas, scaleMode) { - if (!canvas._pixiId) { +BaseTexture.fromCanvas = function (canvas, scaleMode) +{ + if (!canvas._pixiId) + { canvas._pixiId = 'canvas_' + utils.uuid(); } var baseTexture = utils.BaseTextureCache[canvas._pixiId]; - if (!baseTexture) { + if (!baseTexture) + { baseTexture = new BaseTexture(canvas, scaleMode); utils.BaseTextureCache[canvas._pixiId] = baseTexture; } diff --git a/src/core/textures/RenderTexture.js b/src/core/textures/RenderTexture.js index 6dad20f..53ae796 100644 --- a/src/core/textures/RenderTexture.js +++ b/src/core/textures/RenderTexture.js @@ -46,8 +46,10 @@ * @param [scaleMode] {number} See {@link scaleModes} for possible values * @param [resolution=1] {number} The resolution of the texture being generated */ -function RenderTexture(renderer, width, height, scaleMode, resolution) { - if (!renderer) { +function RenderTexture(renderer, width, height, scaleMode, resolution) +{ + if (!renderer) + { throw new Error('Unable to create RenderTexture, you must pass a renderer into the constructor.'); } @@ -133,7 +135,8 @@ */ this.renderer = renderer; - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { var gl = this.renderer.gl; this.textureBuffer = new FilterTexture(gl, this.width * this.resolution, this.height * this.resolution, this.baseTexture.scaleMode); @@ -142,7 +145,8 @@ this.render = this.renderWebGL; this.projection = new math.Point(this.width*0.5, -this.height*0.5); } - else { + else + { this.render = this.renderCanvas; this.textureBuffer = new CanvasBuffer(this.width* this.resolution, this.height* this.resolution); this.baseTexture.source = this.textureBuffer.canvas; @@ -167,8 +171,10 @@ * @param height {number} The height to resize to. * @param updateBase {boolean} Should the baseTexture.width and height values be resized as well? */ -RenderTexture.prototype.resize = function (width, height, updateBase) { - if (width === this.width && height === this.height) { +RenderTexture.prototype.resize = function (width, height, updateBase) +{ + if (width === this.width && height === this.height) + { return; } @@ -177,17 +183,20 @@ this.width = this.frame.width = this.crop.width = width; this.height = this.frame.height = this.crop.height = height; - if (updateBase) { + if (updateBase) + { this.baseTexture.width = this.width; this.baseTexture.height = this.height; } - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { this.projection.x = this.width / 2; this.projection.y = -this.height / 2; } - if (!this.valid) { + if (!this.valid) + { return; } @@ -198,12 +207,15 @@ * Clears the RenderTexture. * */ -RenderTexture.prototype.clear = function () { - if (!this.valid) { +RenderTexture.prototype.clear = function () +{ + if (!this.valid) + { return; } - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { this.renderer.gl.bindFramebuffer(this.renderer.gl.FRAMEBUFFER, this.textureBuffer.frameBuffer); } @@ -220,19 +232,23 @@ * @param [restoreWorldTransform=true] {boolean} If true the displayObject's worldTransform/worldAlpha and all children * transformations will be restored. Not restoring this information will be a little faster. */ -RenderTexture.prototype.renderWebGL = function (displayObject, matrix, clear, restoreWorldTransform) { - if (!this.valid) { +RenderTexture.prototype.renderWebGL = function (displayObject, matrix, clear, restoreWorldTransform) +{ + if (!this.valid) + { return; } - if (typeof restoreWorldTransform === 'undefined') { + if (typeof restoreWorldTransform === 'undefined') + { restoreWorldTransform = true; } var tempAlpha, tempTransform; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { tempAlpha = displayObject.worldAlpha; tempTransform = displayObject.worldTransform.toArray(); } @@ -245,7 +261,8 @@ wt.identity(); wt.translate(0, this.projection.y * 2); - if (matrix) { + if (matrix) + { wt.append(matrix); } @@ -258,7 +275,8 @@ var children = displayObject.children; var i, j; - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } @@ -269,7 +287,8 @@ gl.bindFramebuffer(gl.FRAMEBUFFER, this.textureBuffer.frameBuffer ); - if (clear) { + if (clear) + { this.textureBuffer.clear(); } @@ -279,11 +298,13 @@ this.renderer.spriteBatch.dirty = true; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { displayObject.worldAlpha = tempAlpha; displayObject.worldTransform.fromArray(tempTransform); - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } } @@ -300,26 +321,31 @@ * @param [restoreWorldTransform=true] {boolean} If true the displayObject's worldTransform/worldAlpha and all children * transformations will be restored. Not restoring this information will be a little faster. */ -RenderTexture.prototype.renderCanvas = function (displayObject, matrix, clear, restoreWorldTransform) { - if (!this.valid) { +RenderTexture.prototype.renderCanvas = function (displayObject, matrix, clear, restoreWorldTransform) +{ + if (!this.valid) + { return; } - if (typeof restoreWorldTransform === 'undefined') { + if (typeof restoreWorldTransform === 'undefined') + { restoreWorldTransform = true; } var tempAlpha, tempTransform; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { tempAlpha = displayObject.worldAlpha; tempTransform = displayObject.worldTransform.toArray(); } var wt = displayObject.worldTransform; wt.identity(); - if (matrix) { + if (matrix) + { wt.append(matrix); } @@ -330,11 +356,13 @@ var children = displayObject.children; var i, j; - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } - if (clear) { + if (clear) + { this.textureBuffer.clear(); } @@ -348,11 +376,13 @@ this.renderer.resolution = realResolution; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { displayObject.worldAlpha = tempAlpha; displayObject.worldTransform.fromArray(tempTransform); - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } } @@ -363,7 +393,8 @@ * * @return {Image} */ -RenderTexture.prototype.getImage = function () { +RenderTexture.prototype.getImage = function () +{ var image = new Image(); image.src = this.getBase64(); return image; @@ -374,7 +405,8 @@ * * @return {string} A base64 encoded string of the texture. */ -RenderTexture.prototype.getBase64 = function () { +RenderTexture.prototype.getBase64 = function () +{ return this.getCanvas().toDataURL(); }; @@ -383,8 +415,10 @@ * * @return {HTMLCanvasElement} A Canvas element with the texture rendered on. */ -RenderTexture.prototype.getCanvas = function () { - if (this.renderer.type === CONST.WEBGL_RENDERER) { +RenderTexture.prototype.getCanvas = function () +{ + if (this.renderer.type === CONST.WEBGL_RENDERER) + { var gl = this.renderer.gl; var width = this.textureBuffer.width; var height = this.textureBuffer.height; @@ -403,7 +437,8 @@ return tempCanvas.canvas; } - else { + else + { return this.textureBuffer.canvas; } }; diff --git a/src/core/textures/Texture.js b/src/core/textures/Texture.js index 3c65909..e97f0aa 100644 --- a/src/core/textures/Texture.js +++ b/src/core/textures/Texture.js @@ -17,7 +17,8 @@ * @param [crop] {Rectangle} The area of original texture * @param [trim] {Rectangle} Trimmed texture rectangle */ -function Texture(baseTexture, frame, crop, trim) { +function Texture(baseTexture, frame, crop, trim) +{ /** * Does this Texture have any frame data assigned to it? * @@ -25,12 +26,14 @@ */ this.noFrame = false; - if (!frame) { + if (!frame) + { this.noFrame = true; frame = new math.Rectangle(0, 0, 1, 1); } - if (baseTexture instanceof Texture) { + if (baseTexture instanceof Texture) + { baseTexture = baseTexture.baseTexture; } @@ -100,13 +103,16 @@ */ this.crop = crop || new math.Rectangle(0, 0, 1, 1); - if (baseTexture.hasLoaded) { - if (this.noFrame) { + if (baseTexture.hasLoaded) + { + if (this.noFrame) + { frame = new math.Rectangle(0, 0, baseTexture.width, baseTexture.height); } this.frame = frame; } - else { + else + { baseTexture.addEventListener('loaded', this.onBaseTextureLoaded.bind(this)); } } @@ -118,19 +124,23 @@ Object.defineProperties(Texture.prototype, { needsUpdate: { - get: function () { + get: function () + { return this.baseTexture.needsUpdate; }, - set: function (val) { + set: function (val) + { this.baseTexture.needsUpdate = val; } }, frame: { - get: function () { + get: function () + { return this._frame; }, - set: function (frame) { + set: function (frame) + { this._frame = frame; this.noFrame = false; @@ -143,20 +153,23 @@ 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 (!this.trim && (frame.x + frame.width > this.baseTexture.width || frame.y + frame.height > this.baseTexture.height)) + { throw new Error('Texture Error: frame does not fit inside the base Texture dimensions ' + this); } this.valid = frame && frame.width && frame.height && this.baseTexture.source && this.baseTexture.hasLoaded; - if (this.trim) { + 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) { + if (this.valid) + { this._updateUvs(); } } @@ -168,11 +181,13 @@ * * @private */ -Texture.prototype.onBaseTextureLoaded = function () { +Texture.prototype.onBaseTextureLoaded = function () +{ var baseTexture = this.baseTexture; baseTexture.removeEventListener('loaded', this.onLoaded); - if (this.noFrame) { + if (this.noFrame) + { this.frame = new math.Rectangle(0, 0, baseTexture.width, baseTexture.height); } @@ -184,8 +199,10 @@ * * @param destroyBase {boolean} Whether to destroy the base texture as well */ -Texture.prototype.destroy = function (destroyBase) { - if (destroyBase) { +Texture.prototype.destroy = function (destroyBase) +{ + if (destroyBase) + { this.baseTexture.destroy(); } @@ -197,8 +214,10 @@ * * @private */ -Texture.prototype._updateUvs = function () { - if (!this._uvs) { +Texture.prototype._updateUvs = function () +{ + if (!this._uvs) + { this._uvs = new TextureUvs(); } @@ -229,10 +248,12 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return Texture */ -Texture.fromImage = function (imageUrl, crossorigin, scaleMode) { +Texture.fromImage = function (imageUrl, crossorigin, scaleMode) +{ var texture = utils.TextureCache[imageUrl]; - if (!texture) { + if (!texture) + { texture = new Texture(BaseTexture.fromImage(imageUrl, crossorigin, scaleMode)); utils.TextureCache[imageUrl] = texture; } @@ -248,9 +269,11 @@ * @param frameId {string} The frame id of the texture * @return Texture */ -Texture.fromFrame = function (frameId) { +Texture.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache '); } return texture; @@ -264,7 +287,8 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return {Texture} */ -Texture.fromCanvas = function (canvas, scaleMode) { +Texture.fromCanvas = function (canvas, scaleMode) +{ return new Texture(BaseTexture.fromCanvas(canvas, scaleMode)); }; @@ -276,7 +300,8 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return {Texture} A Texture */ -Texture.fromVideo = function (video, scaleMode) { +Texture.fromVideo = function (video, scaleMode) +{ return new Texture(VideoBaseTexture.baseTextureFromVideo(video, scaleMode)); }; @@ -287,7 +312,8 @@ * @param texture {Texture} The Texture to add to the cache. * @param id {string} The id that the texture will be stored against. */ -Texture.addTextureToCache = function (texture, id) { +Texture.addTextureToCache = function (texture, id) +{ utils.TextureCache[id] = texture; }; @@ -298,7 +324,8 @@ * @param id {string} The id of the texture to be removed * @return {Texture} The texture that was removed */ -Texture.removeTextureFromCache = function (id) { +Texture.removeTextureFromCache = function (id) +{ var texture = utils.TextureCache[id]; delete utils.TextureCache[id]; diff --git a/src/core/textures/TextureUvs.js b/src/core/textures/TextureUvs.js index b9bbb58..5424d52 100644 --- a/src/core/textures/TextureUvs.js +++ b/src/core/textures/TextureUvs.js @@ -1,4 +1,5 @@ -function TextureUvs() { +function TextureUvs() +{ this.x0 = 0; this.y0 = 0; diff --git a/src/core/textures/VideoBaseTexture.js b/src/core/textures/VideoBaseTexture.js index e3e0c5a..1a826a9 100644 --- a/src/core/textures/VideoBaseTexture.js +++ b/src/core/textures/VideoBaseTexture.js @@ -12,15 +12,18 @@ * @param source {HTMLVideoElement} * @param [scaleMode] {number} See {@link scaleModes} for possible values */ -function VideoBaseTexture(source, scaleMode) { - if (!source){ +function VideoBaseTexture(source, scaleMode) +{ + if (!source) + { throw new Error('No video source element specified.'); } // hook in here to check if video is already available. // BaseTexture looks for a source.complete boolean, plus width & height. - if ((source.readyState === source.HAVE_ENOUGH_DATA || source.readyState === source.HAVE_FUTURE_DATA) && source.width && source.height) { + if ((source.readyState === source.HAVE_ENOUGH_DATA || source.readyState === source.HAVE_FUTURE_DATA) && source.width && source.height) + { source.complete = true; } @@ -31,7 +34,8 @@ this._boundOnUpdate = this._onUpdate.bind(this); this._boundOnCanPlay = this._onCanPlay.bind(this); - if (!source.complete) { + if (!source.complete) + { source.addEventListener('canplay', this._boundOnCanPlay); source.addEventListener('canplaythrough', this._boundOnCanPlay); @@ -47,28 +51,35 @@ VideoBaseTexture.prototype.constructor = VideoBaseTexture; module.exports = VideoBaseTexture; -VideoBaseTexture.prototype._onUpdate = function () { - if (this.autoUpdate) { +VideoBaseTexture.prototype._onUpdate = function () +{ + if (this.autoUpdate) + { window.requestAnimationFrame(this._boundOnUpdate); this.needsUpdate = true; } }; -VideoBaseTexture.prototype._onPlayStart = function () { - if (!this.autoUpdate) { +VideoBaseTexture.prototype._onPlayStart = function () +{ + if (!this.autoUpdate) + { window.requestAnimationFrame(this._boundOnUpdate); this.autoUpdate = true; } }; -VideoBaseTexture.prototype._onPlayStop = function () { +VideoBaseTexture.prototype._onPlayStop = function () +{ this.autoUpdate = false; }; -VideoBaseTexture.prototype._onCanPlay = function () { +VideoBaseTexture.prototype._onCanPlay = function () +{ this.hasLoaded = true; - if (this.source) { + if (this.source) + { this.source.removeEventListener('canplay', this._boundOnCanPlay); this.source.removeEventListener('canplaythrough', this._boundOnCanPlay); @@ -78,15 +89,18 @@ this.source.play(); // prevent multiple loaded dispatches.. - if(!this.__loaded){ + if(!this.__loaded) + { this.__loaded = true; this.emit('loaded', this); } } }; -VideoBaseTexture.prototype.destroy = function () { - if (this.source && this.source._pixiId) { +VideoBaseTexture.prototype.destroy = function () +{ + if (this.source && this.source._pixiId) + { utils.BaseTextureCache[ this.source._pixiId ] = null; delete utils.BaseTextureCache[ this.source._pixiId ]; @@ -105,14 +119,17 @@ * @param scaleMode {number} See {@link scaleModes} for possible values * @return {VideoBaseTexture} */ -VideoBaseTexture.fromVideo = function (video, scaleMode) { - if (!video._pixiId) { +VideoBaseTexture.fromVideo = function (video, scaleMode) +{ + if (!video._pixiId) + { video._pixiId = 'video_' + utils.uuid(); } var baseTexture = utils.BaseTextureCache[video._pixiId]; - if (!baseTexture) { + if (!baseTexture) + { baseTexture = new VideoBaseTexture(video, scaleMode); utils.BaseTextureCache[ video._pixiId ] = baseTexture; } @@ -147,17 +164,21 @@ * @param scaleMode {number} See {@link scaleModes} for possible values * @return {VideoBaseTexture} */ -VideoBaseTexture.fromUrl = function (videoSrc, scaleMode) { +VideoBaseTexture.fromUrl = function (videoSrc, scaleMode) +{ var video = document.createElement('video'); // array of objects or strings - if (Array.isArray(videoSrc)) { - for (var i = 0; i < videoSrc.length; ++i) { + if (Array.isArray(videoSrc)) + { + for (var i = 0; i < videoSrc.length; ++i) + { video.appendChild(createSource(videoSrc.src || videoSrc, videoSrc.mime)); } } // single object or string - else { + else + { video.appendChild(createSource(videoSrc.src || videoSrc, videoSrc.mime)); } @@ -169,8 +190,10 @@ VideoBaseTexture.fromUrls = VideoBaseTexture.fromUrl; -function createSource(path, type) { - if (!type) { +function createSource(path, type) +{ + if (!type) + { type = 'video/' + path.substr(path.lastIndexOf('.') + 1); } diff --git a/src/core/utils/EventData.js b/src/core/utils/EventData.js index 5d55a22..8cdf701 100644 --- a/src/core/utils/EventData.js +++ b/src/core/utils/EventData.js @@ -7,7 +7,8 @@ * @param name {string} The string name of the event that was triggered * @param data {object} Arbitrary event data to pass along */ -function EventData(target, name, data) { +function EventData(target, name, data) +{ // for duck typing in the ".on()" function this.__isEventObject = true; @@ -71,7 +72,8 @@ * Stops the propagation of events up the scene graph (prevents bubbling). * */ -EventData.prototype.stopPropagation = function stopPropagation() { +EventData.prototype.stopPropagation = function stopPropagation() +{ this.stopped = true; }; @@ -79,6 +81,7 @@ * Stops the propagation of events to sibling listeners (no longer calls any listeners). * */ -EventData.prototype.stopImmediatePropagation = function stopImmediatePropagation() { +EventData.prototype.stopImmediatePropagation = function stopImmediatePropagation() +{ this.stoppedImmediate = true; }; diff --git a/src/core/utils/EventTarget.js b/src/core/utils/EventTarget.js index 7ae8820..671a151 100644 --- a/src/core/utils/EventTarget.js +++ b/src/core/utils/EventTarget.js @@ -13,14 +13,16 @@ * var em = new MyEmitter(); * em.emit('eventName', 'some data', 'some more data', {}, null, ...); */ -function eventTarget(obj) { +function eventTarget(obj) +{ /** * Return a list of assigned event listeners. * * @param eventName {string} The events that should be listed. * @return {Array} An array of listener functions */ - obj.listeners = function listeners(eventName) { + obj.listeners = function listeners(eventName) + { this._listeners = this._listeners || {}; return this._listeners[eventName] ? this._listeners[eventName].slice() : []; @@ -33,22 +35,26 @@ * @param eventName {string} The name of the event. * @return {boolean} Indication if we've emitted an event. */ - obj.emit = obj.dispatchEvent = function emit(eventName, data) { + obj.emit = obj.dispatchEvent = function emit(eventName, data) + { this._listeners = this._listeners || {}; // fast return when there are no listeners - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return; } //backwards compat with old method ".emit({ type: 'something' })" - if (typeof eventName === 'object') { + if (typeof eventName === 'object') + { data = eventName; eventName = eventName.type; } //ensure we are using a real pixi event - if (!data || data.__isEventObject !== true) { + if (!data || data.__isEventObject !== true) + { data = new EventData(this, eventName, data); } @@ -58,23 +64,27 @@ fn = listeners[0], i; - for (i = 0; i < length; fn = listeners[++i]) { + for (i = 0; i < length; fn = listeners[++i]) + { //call the event listener fn.call(this, data); //if "stopImmediatePropagation" is called, stop calling sibling events - if (data.stoppedImmediate) { + if (data.stoppedImmediate) + { return this; } } //if "stopPropagation" is called then don't bubble the event - if (data.stopped) { + if (data.stopped) + { return this; } //bubble this event up the scene graph - if (this.parent && this.parent.emit) { + if (this.parent && this.parent.emit) + { this.parent.emit.call(this.parent, eventName, data); } @@ -88,7 +98,8 @@ * @param eventName {string} Name of the event. * @param callback {Functon} fn Callback function. */ - obj.on = obj.addEventListener = function on(eventName, fn) { + obj.on = obj.addEventListener = function on(eventName, fn) + { this._listeners = this._listeners || {}; (this._listeners[eventName] = this._listeners[eventName] || []) @@ -103,11 +114,13 @@ * @param eventName {string} Name of the event. * @param callback {Function} Callback function. */ - obj.once = function once(eventName, fn) { + obj.once = function once(eventName, fn) + { this._listeners = this._listeners || {}; var self = this; - function onceHandlerWrapper() { + function onceHandlerWrapper() + { fn.apply(self.off(eventName, onceHandlerWrapper), arguments); } onceHandlerWrapper._originalHandler = fn; @@ -122,23 +135,28 @@ * @param eventName {string} The event we want to remove. * @param callback {Function} The listener that we need to find. */ - obj.off = obj.removeEventListener = function off(eventName, fn) { + obj.off = obj.removeEventListener = function off(eventName, fn) + { this._listeners = this._listeners || {}; - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return this; } var list = this._listeners[eventName], i = fn ? list.length : 0; - while(i-- > 0) { - if (list[i] === fn || list[i]._originalHandler === fn) { + while(i-- > 0) + { + if (list[i] === fn || list[i]._originalHandler === fn) + { list.splice(i, 1); } } - if (list.length === 0) { + if (list.length === 0) + { delete this._listeners[eventName]; } @@ -150,10 +168,12 @@ * * @param eventName {string} The event you want to remove all listeners for. */ - obj.removeAllListeners = function removeAllListeners(eventName) { + obj.removeAllListeners = function removeAllListeners(eventName) + { this._listeners = this._listeners || {}; - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return this; } @@ -169,7 +189,8 @@ * * @param object {object} The obj to mix into */ - mixin: function mixin(obj) { + mixin: function mixin(obj) + { eventTarget(obj); } }; diff --git a/src/core/utils/PolyK.js b/src/core/utils/PolyK.js index 7325141..5e20c2b 100644 --- a/src/core/utils/PolyK.js +++ b/src/core/utils/PolyK.js @@ -47,7 +47,8 @@ * Triangulates shapes for webGL graphic fills. * */ -PolyK.Triangulate = function (p) { +PolyK.Triangulate = function (p) +{ var sign = true; var n = p.length >> 1; @@ -59,7 +60,8 @@ i = 0; var al = n; - while(al > 3) { + while(al > 3) + { var i0 = avl[(i+0)%al]; var i1 = avl[(i+1)%al]; var i2 = avl[(i+2)%al]; @@ -69,29 +71,35 @@ var cx = p[2*i2], cy = p[2*i2+1]; var earFound = false; - if (PolyK._convex(ax, ay, bx, by, cx, cy, sign)) { + if (PolyK._convex(ax, ay, bx, by, cx, cy, sign)) + { earFound = true; - for (var j = 0; j < al; j++) { + for (var j = 0; j < al; j++) + { var vi = avl[j]; if (vi === i0 || vi === i1 || vi === i2) continue; - if (PolyK._PointInTriangle(p[2*vi], p[2*vi+1], ax, ay, bx, by, cx, cy)) { + if (PolyK._PointInTriangle(p[2*vi], p[2*vi+1], ax, ay, bx, by, cx, cy)) + { earFound = false; break; } } } - if (earFound) { + if (earFound) + { tgs.push(i0, i1, i2); avl.splice((i+1)%al, 1); al--; i = 0; } - else if (i++ > 3*al) { + else if (i++ > 3*al) + { // need to flip flip reverse it! // reset! - if (sign) { + if (sign) + { tgs = []; avl = []; for (i = 0; i < n; i++) avl.push(i); @@ -101,7 +109,8 @@ sign = false; } - else { + else + { // window.console.log("PIXI Warning: shape too complex to fill"); return null; } @@ -126,7 +135,8 @@ * @private * @return {boolean} */ -PolyK._PointInTriangle = function (px, py, ax, ay, bx, by, cx, cy) { +PolyK._PointInTriangle = function (px, py, ax, ay, bx, by, cx, cy) +{ var v0x = cx-ax; var v0y = cy-ay; var v1x = bx-ax; @@ -154,6 +164,7 @@ * @private * @return {boolean} */ -PolyK._convex = function (ax, ay, bx, by, cx, cy, sign) { +PolyK._convex = function (ax, ay, bx, by, cx, cy, sign) +{ return ((ay-by)*(cx-bx) + (bx-ax)*(cy-by) >= 0) === sign; }; diff --git a/src/core/utils/index.js b/src/core/utils/index.js index ade9831..bfae7ae 100644 --- a/src/core/utils/index.js +++ b/src/core/utils/index.js @@ -16,7 +16,8 @@ * * @return {number} The next uuid to use. */ - uuid: function () { + uuid: function () + { return ++utils._uid; }, @@ -26,7 +27,8 @@ * @param hex {number} * @return {number[]} An array representing the [R, G, B] of the color. */ - hex2rgb: function (hex, out) { + hex2rgb: function (hex, out) + { out = out || []; out[0] = (hex >> 16 & 0xFF) / 255; @@ -42,7 +44,8 @@ * @param hex {number} * @return {string} The string color. */ - hex2string: function (hex) { + hex2string: function (hex) + { hex = hex.toString(16); hex = '000000'.substr(0, 6 - hex.length) + hex; @@ -55,7 +58,8 @@ * @param rgb {number[]} * @return {number} The color number */ - rgb2hex: function (rgb) { + rgb2hex: function (rgb) + { return ((rgb[0]*255 << 16) + (rgb[1]*255 << 8) + rgb[2]*255); }, @@ -64,8 +68,10 @@ * * @return {boolean} whether they are supported */ - canUseNewCanvasBlendModes: function () { - if (typeof document === 'undefined') { + canUseNewCanvasBlendModes: function () + { + if (typeof document === 'undefined') + { return false; } @@ -93,15 +99,19 @@ * @param number {number} * @return {number} the closest number that is a power of two */ - getNextPowerOfTwo: function (number) { + getNextPowerOfTwo: function (number) + { // see: http://en.wikipedia.org/wiki/Power_of_two#Fast_algorithm_to_check_if_a_positive_number_is_a_power_of_two - if (number > 0 && (number & (number - 1)) === 0) { + if (number > 0 && (number & (number - 1)) === 0) + { return number; } - else { + else + { var result = 1; - while (result < number) { + while (result < number) + { result <<= 1; } @@ -116,7 +126,8 @@ * @param height {number} * @return {boolean} */ - isPowerOfTwo: function (width, height) { + isPowerOfTwo: function (width, height) + { return (width > 0 && (width & (width - 1)) === 0 && height > 0 && (height & (height - 1)) === 0); }, @@ -130,12 +141,15 @@ * @constant * @static */ - sayHello: function (type) { - if (utils._saidHello) { + sayHello: function (type) + { + if (utils._saidHello) + { return; } - if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) { + if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) + { var args = [ '%c %c %c Pixi.js ' + CONST.VERSION + ' - ' + type + ' %c ' + ' %c ' + ' http://www.pixijs.com/ %c %c ♥%c♥%c♥ ', 'background: #ff66a5', @@ -151,7 +165,8 @@ console.log.apply(console, args); //jshint ignore:line } - else if (window.console) { + else if (window.console) + { console.log('Pixi.js ' + CONST.VERSION + ' - ' + type + ' - http://www.pixijs.com/'); //jshint ignore:line } @@ -166,15 +181,19 @@ * @class * @namespace PIXI */ - AjaxRequest: function () { + AjaxRequest: function () + { var activexmodes = ['Msxml2.XMLHTTP.6.0', 'Msxml2.XMLHTTP.3.0', 'Microsoft.XMLHTTP']; //activeX versions to check for in IE - if (window.ActiveXObject) { //Test for support for ActiveXObject in IE first (as XMLHttpRequest in IE7 is broken) - for (var i=0; i= 0 && index <= this.children.length) { - if (child.parent) { + if (index >= 0 && index <= this.children.length) + { + if (child.parent) + { child.parent.removeChild(child); } @@ -154,7 +173,8 @@ return child; } - else { + else + { throw new Error(child + 'addChildAt: The index '+ index +' supplied is out of bounds ' + this.children.length); } }; @@ -165,15 +185,18 @@ * @param child {DisplayObject} * @param child2 {DisplayObject} */ -DisplayObjectContainer.prototype.swapChildren = function (child, child2) { - if (child === child2) { +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) { + if (index1 < 0 || index2 < 0) + { throw new Error('swapChildren: Both the supplied DisplayObjects must be a child of the caller.'); } @@ -187,10 +210,12 @@ * @param child {DisplayObject} The DisplayObject instance to identify * @return {Number} The index position of the child display object to identify */ -DisplayObjectContainer.prototype.getChildIndex = function (child) { +DisplayObjectContainer.prototype.getChildIndex = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { throw new Error('The supplied DisplayObject must be a child of the caller'); } @@ -203,8 +228,10 @@ * @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 */ -DisplayObjectContainer.prototype.setChildIndex = function (child, index) { - if (index < 0 || index >= this.children.length) { +DisplayObjectContainer.prototype.setChildIndex = function (child, index) +{ + if (index < 0 || index >= this.children.length) + { throw new Error('The supplied index is out of bounds'); } @@ -220,8 +247,10 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child at the given index, if any. */ -DisplayObjectContainer.prototype.getChildAt = function (index) { - if (index < 0 || index >= this.children.length) { +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'); } @@ -234,10 +263,12 @@ * @param child {DisplayObject} The DisplayObject to remove * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChild = function (child) { +DisplayObjectContainer.prototype.removeChild = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { return; } @@ -250,7 +281,8 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChildAt = function (index) { +DisplayObjectContainer.prototype.removeChildAt = function (index) +{ var child = this.getChildAt(index); child.parent = null; @@ -265,24 +297,29 @@ * @param beginIndex {Number} The beginning position. Default value is 0. * @param endIndex {Number} The ending position. Default value is size of the container. */ -DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) { +DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) +{ var begin = beginIndex || 0; var end = typeof endIndex === 'number' ? endIndex : this.children.length; var range = end - begin; - if (range > 0 && range <= end) { + if (range > 0 && range <= end) + { var removed = this.children.splice(begin, range); - for (var i = 0; i < removed.length; ++i) { + for (var i = 0; i < removed.length; ++i) + { removed[i].parent = null; } return removed; } - else if (range === 0 && this.children.length === 0) { + else if (range === 0 && this.children.length === 0) + { return []; } - else { + else + { throw new RangeError('removeChildren: numeric values are outside the acceptable range.'); } }; @@ -291,7 +328,8 @@ * Generates and updates the cached sprite for this object. * */ -DisplayObjectContainer.prototype.updateCachedSprite = function () { +DisplayObjectContainer.prototype.updateCachedSprite = function () +{ this._generateCachedSprite(); }; @@ -304,7 +342,8 @@ * @param renderer {CanvasRenderer|WebGLRenderer} The renderer used to generate the texture. * @return {Texture} a texture of the graphics object */ -DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) { +DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) +{ var bounds = this.getLocalBounds(); var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0, renderer, scaleMode, resolution); @@ -322,18 +361,22 @@ * * @private */ -DisplayObjectContainer.prototype.updateTransform = function () { - if (!this.visible) { +DisplayObjectContainer.prototype.updateTransform = function () +{ + if (!this.visible) + { return; } this.displayObjectUpdateTransform(); - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { return; } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } }; @@ -346,8 +389,10 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getBounds = function () { - if (this.children.length === 0) { +DisplayObjectContainer.prototype.getBounds = function () +{ + if (this.children.length === 0) + { return math.Rectangle.EMPTY; } @@ -365,10 +410,12 @@ var childVisible = false; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -386,7 +433,8 @@ maxY = maxY > childMaxY ? maxY : childMaxY; } - if (!childVisible) { + if (!childVisible) + { return math.Rectangle.EMPTY; } @@ -407,12 +455,14 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getLocalBounds = function () { +DisplayObjectContainer.prototype.getLocalBounds = function () +{ var matrixCache = this.worldTransform; this.worldTransform = math.Matrix.IDENTITY; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } @@ -428,13 +478,16 @@ * * @param renderer {WebGLRenderer} The renderer */ -DisplayObjectContainer.prototype.renderWebGL = function (renderer) { +DisplayObjectContainer.prototype.renderWebGL = function (renderer) +{ // if the object is not visible or the alpha is 0 then no need to render this element - if (!this.visible || this.alpha <= 0) { + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } @@ -442,14 +495,17 @@ var i, j; // do a quick check to see if this element has a mask or a filter. - if (this._mask || this._filters) { + if (this._mask || this._filters) + { // push filter first as we need to ensure the stencil buffer is correct for any masking - if (this._filters) { + if (this._filters) + { renderer.spriteBatch.flush(); renderer.filterManager.pushFilter(this._filterBlock); } - if (this._mask) { + if (this._mask) + { renderer.spriteBatch.stop(); renderer.maskManager.pushMask(this.mask, renderer); renderer.spriteBatch.start(); @@ -459,36 +515,42 @@ this._renderWebGL(renderer); // now loop through the children and make sure they get rendered - for (i = 0, j = this.children.length; i < j; i++) { + for (i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderWebGL(renderer); } // time to stop the sprite batch as either a mask element or a filter draw will happen next renderer.spriteBatch.stop(); - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(this._mask, renderer); } - if (this._filters) { + if (this._filters) + { renderer.filterManager.popFilter(); } renderer.spriteBatch.start(); } - else { + else + { this._renderWebGL(renderer); // simple render children! - for (i = 0, j = this.children.length; i < j; ++i) { + for (i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderWebGL(renderer); } } }; -DisplayObjectContainer.prototype._renderWebGL = function (renderer) { +DisplayObjectContainer.prototype._renderWebGL = function (renderer) +{ // this is where content itself gets renderd.. @@ -499,25 +561,31 @@ * * @param renderer {CanvasRenderer} The renderer */ -DisplayObjectContainer.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0) { +DisplayObjectContainer.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -528,13 +596,16 @@ * @param renderer {WebGLRenderer|CanvasRenderer} The renderer * @private */ -DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) { +DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) +{ this._cachedSprite.worldAlpha = this.worldAlpha; - if (renderer.gl) { + if (renderer.gl) + { this._cachedSprite.renderWebGL(renderer); } - else { + else + { this._cachedSprite.renderCanvas(renderer); } }; @@ -544,10 +615,12 @@ * * @private */ -DisplayObjectContainer.prototype._generateCachedSprite = function () { +DisplayObjectContainer.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { // TODO - RenderTexture now *requires* a renderer instance, so this is like broken // because `renderer` isn't actually in scope here :P var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0); @@ -555,7 +628,8 @@ this._cachedSprite = new Sprite(renderTexture); this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.texture.resize(bounds.width | 0, bounds.height | 0); } @@ -580,8 +654,10 @@ * * @private */ -DisplayObjectContainer.prototype._destroyCachedSprite = function () { - if (!this._cachedSprite) { +DisplayObjectContainer.prototype._destroyCachedSprite = function () +{ + if (!this._cachedSprite) + { return; } diff --git a/src/core/display/Sprite.js b/src/core/display/Sprite.js index 707da24..5862aef 100644 --- a/src/core/display/Sprite.js +++ b/src/core/display/Sprite.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param texture {Texture} The texture for this sprite */ -function Sprite(texture) { +function Sprite(texture) +{ DisplayObjectContainer.call(this); /** @@ -85,12 +86,14 @@ this.texture = texture || Texture.EMPTY; } -Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) { +Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) +{ DisplayObjectContainer.prototype.destroy.call(this); this.anchor = null; - if (destroyTexture) { + if (destroyTexture) + { this._texture.destroy(destroyBaseTexture); } @@ -111,10 +114,12 @@ * @memberof Sprite# */ width: { - get: function () { + get: function () + { return this.scale.x * this.texture.frame.width; }, - set: function (value) { + set: function (value) + { this.scale.x = value / this.texture.frame.width; this._width = value; } @@ -127,10 +132,12 @@ * @memberof Sprite# */ height: { - get: function () { + get: function () + { return this.scale.y * this.texture.frame.height; }, - set: function (value) { + set: function (value) + { this.scale.y = value / this.texture.frame.height; this._height = value; } @@ -143,23 +150,29 @@ * @memberof Sprite# */ texture: { - get: function () { + get: function () + { return this._texture; }, - set: function (value) { - if (this._texture === value) { + set: function (value) + { + if (this._texture === value) + { return; } this._texture = value; this.cachedTint = 0xFFFFFF; - if (value) { + if (value) + { // wait for the texture to load - if (value.baseTexture.hasLoaded) { + if (value.baseTexture.hasLoaded) + { this._onTextureUpdate(); } - else { + else + { value.once('update', this._onTextureUpdate.bind(this)); } } @@ -172,18 +185,22 @@ * * @private */ -Sprite.prototype._onTextureUpdate = function () { +Sprite.prototype._onTextureUpdate = function () +{ // so if _width is 0 then width was not set.. - if (this._width) { + if (this._width) + { this.scale.x = this._width / this.texture.frame.width; } - if (this._height) { + if (this._height) + { this.scale.y = this._height / this.texture.frame.height; } }; -Sprite.prototype._renderWebGL = function (renderer) { +Sprite.prototype._renderWebGL = function (renderer) +{ // this is where content gets renderd.. // watch this space for a little render state manager.. @@ -197,7 +214,8 @@ * @param matrix {Matrix} the transformation matrix of the sprite * @return {Rectangle} the framing rectangle */ -Sprite.prototype.getBounds = function (matrix) { +Sprite.prototype.getBounds = function (matrix) +{ var width = this.texture.frame.width; var height = this.texture.frame.height; @@ -224,11 +242,13 @@ if(b === 0 && c === 0) { // scale may be negative! - if (a < 0) { + if (a < 0) + { a *= -1; } - if (d < 0) { + if (d < 0) + { d *= -1; } @@ -293,28 +313,34 @@ * * @param renderer {CanvasRenderer} The renderer */ -Sprite.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) { +Sprite.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) + { return; } - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; renderer.context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } // Ignore null sources - if (this.texture.valid) { + if (this.texture.valid) + { var resolution = this.texture.baseTexture.resolution / renderer.resolution; renderer.context.globalAlpha = this.worldAlpha; // If smoothingEnabled is supported and we need to change the smoothing property for this texture - if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) { + if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) + { renderer.scaleMode = this.texture.baseTexture.scaleMode; renderer.context[renderer.smoothProperty] = (renderer.scaleMode === CONST.scaleModes.LINEAR); } @@ -324,7 +350,8 @@ var dy = (this.texture.trim ? this.texture.trim.y : 0) - (this.anchor.y * this.texture.trim.height); // Allow for pixel rounding - if (renderer.roundPixels) { + if (renderer.roundPixels) + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -337,7 +364,8 @@ dx = dx | 0; dy = dy | 0; } - else { + else + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -348,8 +376,10 @@ ); } - if (this.tint !== 0xFFFFFF) { - if (this.cachedTint !== this.tint) { + if (this.tint !== 0xFFFFFF) + { + if (this.cachedTint !== this.tint) + { this.cachedTint = this.tint; // TODO clean up caching - how to clean up the caches? @@ -368,7 +398,8 @@ this.texture.crop.height / resolution ); } - else { + else + { renderer.context.drawImage( this.texture.baseTexture.source, this.texture.crop.x, @@ -383,11 +414,13 @@ } } - for (var i = 0, j = this.children.length; i < j; i++) { + for (var i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -402,10 +435,12 @@ * @param frameId {String} The frame Id of the texture in the cache * @return {Sprite} A new Sprite using a texture from the texture cache matching the frameId */ -Sprite.fromFrame = function (frameId) { +Sprite.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache' + this); } @@ -420,6 +455,7 @@ * @param imageId {String} The image url of the texture * @return {Sprite} A new Sprite using a texture from the texture cache matching the image id */ -Sprite.fromImage = function (imageId, crossorigin, scaleMode) { +Sprite.fromImage = function (imageId, crossorigin, scaleMode) +{ return new Sprite(Texture.fromImage(imageId, crossorigin, scaleMode)); }; diff --git a/src/core/display/SpriteBatch.js b/src/core/display/SpriteBatch.js index 3187777..c196fef 100644 --- a/src/core/display/SpriteBatch.js +++ b/src/core/display/SpriteBatch.js @@ -12,7 +12,8 @@ * ```js * var container = new SpriteBatch(); * - * for(var i = 0; i < 100; ++i) { + * for(var i = 0; i < 100; ++i) + * { * var sprite = new PIXI.Sprite.fromImage("myImage.png"); * container.addChild(sprite); * } @@ -25,7 +26,8 @@ */ //TODO RENAME to PARTICLE CONTAINER? -function SpriteBatch() { +function SpriteBatch() +{ DisplayObjectContainer.call(this); } @@ -38,7 +40,8 @@ * * @private */ -SpriteBatch.prototype.updateTransform = function () { +SpriteBatch.prototype.updateTransform = function () +{ // TODO don't need to! this.displayObjectUpdateTransform(); // PIXI.DisplayObjectContainer.prototype.updateTransform.call( this ); @@ -50,8 +53,10 @@ * @param renderer {WebGLRenderer} The webgl renderer * @private */ -SpriteBatch.prototype.renderWebGL = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderWebGL = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -71,8 +76,10 @@ * @param renderer {CanvasRenderer} The canvas renderer * @private */ -SpriteBatch.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -84,10 +91,12 @@ this.displayObjectUpdateTransform(); - for (var i = 0; i < this.children.length; ++i) { + for (var i = 0; i < this.children.length; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -95,9 +104,11 @@ context.globalAlpha = this.worldAlpha * child.alpha; - if (child.rotation % (Math.PI * 2) === 0) { + if (child.rotation % (Math.PI * 2) === 0) + { // this is the fastest way to optimise! - if rotation is 0 then we can avoid any kind of setTransform call - if (isRotated) { + if (isRotated) + { context.setTransform( transform.a, transform.b, @@ -122,8 +133,10 @@ frame.height * child.scale.y ); } - else { - if (!isRotated) { + else + { + if (!isRotated) + { isRotated = true; } @@ -131,7 +144,8 @@ var childTransform = child.worldTransform; - if (renderer.roundPixels) { + if (renderer.roundPixels) + { context.setTransform( childTransform.a, childTransform.b, @@ -141,7 +155,8 @@ childTransform.ty | 0 ); } - else { + else + { context.setTransform( childTransform.a, childTransform.b, diff --git a/src/core/index.js b/src/core/index.js index 3954b6f..eb4a82b 100644 --- a/src/core/index.js +++ b/src/core/index.js @@ -58,11 +58,13 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRenderer: function (width, height, options, noWebGL) { + autoDetectRenderer: function (width, height, options, noWebGL) + { width = width || 800; height = height || 600; - if (!noWebGL && require('webgl-enabled')()) { + if (!noWebGL && require('webgl-enabled')()) + { return new core.WebGLRenderer(width, height, options); } @@ -87,7 +89,8 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRecommendedRenderer: function (width, height, options) { + autoDetectRecommendedRenderer: function (width, height, options) + { var isAndroid = /Android/i.test(navigator.userAgent); return core.autoDetectRenderer(width, height, options, isAndroid); diff --git a/src/core/math/Matrix.js b/src/core/math/Matrix.js index c2f87e2..2ff4848 100644 --- a/src/core/math/Matrix.js +++ b/src/core/math/Matrix.js @@ -10,7 +10,8 @@ * @class * @namespace PIXI */ -function Matrix() { +function Matrix() +{ /** * @member {number} * @default 1 @@ -63,7 +64,8 @@ * * @param array {number[]} The array that the matrix will be populated from. */ -Matrix.prototype.fromArray = function (array) { +Matrix.prototype.fromArray = function (array) +{ this.a = array[0]; this.b = array[1]; this.c = array[3]; @@ -78,14 +80,17 @@ * @param transpose {boolean} Whether we need to transpose the matrix or not * @return {number[]} the newly created array which contains the matrix */ -Matrix.prototype.toArray = function (transpose) { - if (!this.array) { +Matrix.prototype.toArray = function (transpose) +{ + if (!this.array) + { this.array = new Float32Array(9); } var array = this.array; - if (transpose) { + if (transpose) + { array[0] = this.a; array[1] = this.b; array[2] = 0; @@ -96,7 +101,8 @@ array[7] = this.ty; array[8] = 1; } - else { + else + { array[0] = this.a; array[1] = this.c; array[2] = this.tx; @@ -119,7 +125,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, transformed through this matrix */ -Matrix.prototype.apply = function (pos, newPos) { +Matrix.prototype.apply = function (pos, newPos) +{ newPos = newPos || new Point(); newPos.x = this.a * pos.x + this.c * pos.y + this.tx; @@ -136,7 +143,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, inverse-transformed through this matrix */ -Matrix.prototype.applyInverse = function (pos, newPos) { +Matrix.prototype.applyInverse = function (pos, newPos) +{ newPos = newPos || new Point(); var id = 1 / (this.a * this.d + this.c * -this.b); @@ -154,7 +162,8 @@ * @param {number} y * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.translate = function (x, y) { +Matrix.prototype.translate = function (x, y) +{ this.tx += x; this.ty += y; @@ -168,7 +177,8 @@ * @param {number} y The amount to scale vertically * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.scale = function (x, y) { +Matrix.prototype.scale = function (x, y) +{ this.a *= x; this.d *= y; this.c *= x; @@ -186,7 +196,8 @@ * @param {number} angle - The angle in radians. * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.rotate = function (angle) { +Matrix.prototype.rotate = function (angle) +{ var cos = Math.cos( angle ); var sin = Math.sin( angle ); @@ -210,7 +221,8 @@ * @param {Matrix} matrix * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.append = function (matrix) { +Matrix.prototype.append = function (matrix) +{ var a1 = this.a; var b1 = this.b; var c1 = this.c; @@ -232,7 +244,8 @@ * * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.identity = function () { +Matrix.prototype.identity = function () +{ this.a = 1; this.b = 0; this.c = 0; diff --git a/src/core/math/Point.js b/src/core/math/Point.js index 7565b2d..632f346 100644 --- a/src/core/math/Point.js +++ b/src/core/math/Point.js @@ -7,7 +7,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -function Point(x, y) { +function Point(x, y) +{ /** * @member {number} * @default 0 @@ -29,7 +30,8 @@ * * @return {Point} a copy of the point */ -Point.prototype.clone = function () { +Point.prototype.clone = function () +{ return new Point(this.x, this.y); }; @@ -40,7 +42,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -Point.prototype.set = function (x, y) { +Point.prototype.set = function (x, y) +{ this.x = x || 0; this.y = y || ( (y !== 0) ? this.x : 0 ) ; }; diff --git a/src/core/math/shapes/Circle.js b/src/core/math/shapes/Circle.js index 69cfdc9..4d76efc 100644 --- a/src/core/math/shapes/Circle.js +++ b/src/core/math/shapes/Circle.js @@ -10,7 +10,8 @@ * @param y {number} The Y coordinate of the center of this circle * @param radius {number} The radius of the circle */ -function Circle(x, y, radius) { +function Circle(x, y, radius) +{ /** * @member {number} * @default 0 @@ -46,7 +47,8 @@ * @method clone * @return {Circle} a copy of the Circle */ -Circle.prototype.clone = function () { +Circle.prototype.clone = function () +{ return new Circle(this.x, this.y, this.radius); }; @@ -58,8 +60,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Circle */ -Circle.prototype.contains = function (x, y) { - if (this.radius <= 0) { +Circle.prototype.contains = function (x, y) +{ + if (this.radius <= 0) + { return false; } @@ -79,6 +83,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Circle.prototype.getBounds = function () { +Circle.prototype.getBounds = function () +{ return new Rectangle(this.x - this.radius, this.y - this.radius, this.radius * 2, this.radius * 2); }; diff --git a/src/core/math/shapes/Ellipse.js b/src/core/math/shapes/Ellipse.js index 4f2d066..fefd01a 100644 --- a/src/core/math/shapes/Ellipse.js +++ b/src/core/math/shapes/Ellipse.js @@ -11,7 +11,8 @@ * @param width {number} The half width of this ellipse * @param height {number} The half height of this ellipse */ -function Ellipse(x, y, width, height) { +function Ellipse(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -53,7 +54,8 @@ * @method clone * @return {Ellipse} a copy of the ellipse */ -Ellipse.prototype.clone = function () { +Ellipse.prototype.clone = function () +{ return new Ellipse(this.x, this.y, this.width, this.height); }; @@ -65,8 +67,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coords are within this ellipse */ -Ellipse.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Ellipse.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } @@ -86,6 +90,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Ellipse.prototype.getBounds = function () { +Ellipse.prototype.getBounds = function () +{ return new Rectangle(this.x - this.width, this.y - this.height, this.width, this.height); }; diff --git a/src/core/math/shapes/Polygon.js b/src/core/math/shapes/Polygon.js index ae89148..fea6d37 100644 --- a/src/core/math/shapes/Polygon.js +++ b/src/core/math/shapes/Polygon.js @@ -10,16 +10,20 @@ * arguments passed can be flat x,y values e.g. `new Polygon(x,y, x,y, x,y, ...)` where `x` and `y` are * Numbers. */ -function Polygon(points) { +function Polygon(points) +{ //if points isn't an array, use arguments as the array - if (!(points instanceof Array)) { + if (!(points instanceof Array)) + { points = Array.prototype.slice.call(arguments); } //if this is a flat array of numbers, convert it to points - if (points[0] instanceof Point) { + if (points[0] instanceof Point) + { var p = []; - for (var i = 0, il = points.length; i < il; i++) { + for (var i = 0, il = points.length; i < il; i++) + { p.push(points[i].x, points[i].y); } @@ -51,7 +55,8 @@ * * @return {Polygon} a copy of the polygon */ -Polygon.prototype.clone = function () { +Polygon.prototype.clone = function () +{ return new Polygon(this.points.slice()); }; @@ -62,19 +67,22 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this polygon */ -Polygon.prototype.contains = function (x, y) { +Polygon.prototype.contains = function (x, y) +{ var inside = false; // use some raycasting to test hits // https://github.com/substack/point-in-polygon/blob/master/index.js var length = this.points.length / 2; - for (var i = 0, j = length - 1; i < length; j = i++) { + for (var i = 0, j = length - 1; i < length; j = i++) + { var xi = this.points[i * 2], yi = this.points[i * 2 + 1], xj = this.points[j * 2], yj = this.points[j * 2 + 1], intersect = ((yi > y) !== (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi); - if (intersect) { + if (intersect) + { inside = !inside; } } diff --git a/src/core/math/shapes/Rectangle.js b/src/core/math/shapes/Rectangle.js index 16ac62a..4008b68 100644 --- a/src/core/math/shapes/Rectangle.js +++ b/src/core/math/shapes/Rectangle.js @@ -10,7 +10,8 @@ * @param width {number} The overall width of this rectangle * @param height {number} The overall height of this rectangle */ -function Rectangle(x, y, width, height) { +function Rectangle(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -60,7 +61,8 @@ * * @return {Rectangle} a copy of the rectangle */ -Rectangle.prototype.clone = function () { +Rectangle.prototype.clone = function () +{ return new Rectangle(this.x, this.y, this.width, this.height); }; @@ -71,13 +73,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rectangle */ -Rectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Rectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/math/shapes/RoundedRectangle.js b/src/core/math/shapes/RoundedRectangle.js index 27d286e..7bf6411 100644 --- a/src/core/math/shapes/RoundedRectangle.js +++ b/src/core/math/shapes/RoundedRectangle.js @@ -11,7 +11,8 @@ * @param height {number} The overall height of this rounded rectangle * @param radius {number} Controls the radius of the rounded corners */ -function RoundedRectangle(x, y, width, height, radius) { +function RoundedRectangle(x, y, width, height, radius) +{ /** * @member {number} * @default 0 @@ -58,7 +59,8 @@ * * @return {RoundedRectangle} a copy of the rounded rectangle */ -RoundedRectangle.prototype.clone = function () { +RoundedRectangle.prototype.clone = function () +{ return new RoundedRectangle(this.x, this.y, this.width, this.height, this.radius); }; @@ -69,13 +71,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rounded Rectangle */ -RoundedRectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +RoundedRectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/primitives/Graphics.js b/src/core/primitives/Graphics.js index 261c534..e902d2a 100644 --- a/src/core/primitives/Graphics.js +++ b/src/core/primitives/Graphics.js @@ -16,7 +16,8 @@ * @extends DisplayObjectContainer * @namespace PIXI */ -function Graphics() { +function Graphics() +{ DisplayObjectContainer.call(this); this.renderable = true; @@ -154,16 +155,20 @@ * @private */ cacheAsBitmap: { - get: function () { + get: function () + { return this._cacheAsBitmap; }, - set: function (value) { + set: function (value) + { this._cacheAsBitmap = value; - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._generateCachedSprite(); } - else { + else + { this.destroyCachedSprite(); this.dirty = true; } @@ -176,7 +181,8 @@ * * @return {Graphics} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ var clone = new Graphics(); clone.renderable = this.renderable; @@ -192,7 +198,8 @@ clone.cachedSpriteDirty = this.cachedSpriteDirty; // copy graphics data - for (var i = 0; i < this.graphicsData.length; ++i) { + for (var i = 0; i < this.graphicsData.length; ++i) + { clone.graphicsData.push(this.graphicsData.clone()); } @@ -211,17 +218,21 @@ * @param alpha {number} alpha of the line to draw, will update the objects stored style * @return {Graphics} */ -Graphics.prototype.lineStyle = function (lineWidth, color, alpha) { +Graphics.prototype.lineStyle = function (lineWidth, color, alpha) +{ this.lineWidth = lineWidth || 0; this.lineColor = color || 0; this.lineAlpha = (arguments.length < 3) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length) + { // halfway through a line? start a new one! this.drawShape( new math.Polygon( this.currentPath.shape.points.slice(-2) )); } - else { + else + { // otherwise its empty so lets just set the line properties this.currentPath.lineWidth = this.lineWidth; this.currentPath.lineColor = this.lineColor; @@ -239,7 +250,8 @@ * @param y {number} the Y coordinate to move to * @return {Graphics} */ -Graphics.prototype.moveTo = function (x, y) { +Graphics.prototype.moveTo = function (x, y) +{ this.drawShape(new math.Polygon([x,y])); return this; @@ -253,7 +265,8 @@ * @param y {number} the Y coordinate to draw to * @return {Graphics} */ -Graphics.prototype.lineTo = function (x, y) { +Graphics.prototype.lineTo = function (x, y) +{ this.currentPath.shape.points.push(x, y); this.dirty = true; @@ -270,13 +283,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -285,7 +302,8 @@ n = 20, points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { this.moveTo(0, 0); } @@ -293,7 +311,8 @@ var fromY = points[points.length-1]; var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; xa = fromX + ( (cpX - fromX) * j ); @@ -319,13 +338,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -342,7 +365,8 @@ var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; dt = (1 - j); @@ -373,13 +397,17 @@ * @param radius {number} The radius of the arc * @return {Graphics} */ -Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points.push(x1, y1); } } - else { + else + { this.moveTo(x1, y1); } @@ -392,12 +420,15 @@ b2 = x2 - x1, mm = Math.abs(a1 * b2 - b1 * a2); - if (mm < 1.0e-8 || radius === 0) { - if (points[points.length-2] !== x1 || points[points.length-1] !== y1) { + if (mm < 1.0e-8 || radius === 0) + { + if (points[points.length-2] !== x1 || points[points.length-1] !== y1) + { points.push(x1, y1); } } - else { + else + { var dd = a1 * a1 + b1 * b1, cc = a2 * a2 + b2 * b2, tt = a1 * a2 + b1 * b2, @@ -433,42 +464,51 @@ * @param anticlockwise {boolean} Optional. Specifies whether the drawing should be counterclockwise or clockwise. False is default, and indicates clockwise, while true indicates counter-clockwise. * @return {Graphics} */ -Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) { +Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) +{ var startX = cx + Math.cos(startAngle) * radius; var startY = cy + Math.sin(startAngle) * radius; var points; // TODO - This if-else makes no sense. It uses currentPath in the else where it doesn't exist... - if (this.currentPath) { + if (this.currentPath) + { points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { points.push(startX, startY); } - else if (points[points.length-2] !== startX || points[points.length-1] !== startY) { + else if (points[points.length-2] !== startX || points[points.length-1] !== startY) + { points.push(startX, startY); } } - else { + else + { this.moveTo(startX, startY); points = this.currentPath.shape.points; } - if (startAngle === endAngle) { + if (startAngle === endAngle) + { return this; } - if (!anticlockwise && endAngle <= startAngle) { + if (!anticlockwise && endAngle <= startAngle) + { endAngle += Math.PI * 2; } - else if (anticlockwise && startAngle <= endAngle) { + else if (anticlockwise && startAngle <= endAngle) + { startAngle += Math.PI * 2; } var sweep = anticlockwise ? (startAngle - endAngle) *-1 : (endAngle - startAngle); var segs = (Math.abs(sweep)/ (Math.PI * 2)) * 40; - if (sweep === 0) { + if (sweep === 0) + { return this; } @@ -482,7 +522,8 @@ var remainder = ( segMinus % 1 ) / segMinus; - for (var i = 0; i <= segMinus; ++i) { + for (var i = 0; i <= segMinus; ++i) + { var real = i + remainder * i; var angle = ((theta) + startAngle + (theta2 * real)); @@ -506,13 +547,16 @@ * @param alpha {number} the alpha of the fill * @return {Graphics} */ -Graphics.prototype.beginFill = function (color, alpha) { +Graphics.prototype.beginFill = function (color, alpha) +{ this.filling = true; this.fillColor = color || 0; this.fillAlpha = (alpha === undefined) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length <= 2) + { this.currentPath.fill = this.filling; this.currentPath.fillColor = this.fillColor; this.currentPath.fillAlpha = this.fillAlpha; @@ -526,7 +570,8 @@ * * @return {Graphics} */ -Graphics.prototype.endFill = function () { +Graphics.prototype.endFill = function () +{ this.filling = false; this.fillColor = null; this.fillAlpha = 1; @@ -542,7 +587,8 @@ * @param height {number} The height of the rectangle * @return {Graphics} */ -Graphics.prototype.drawRect = function ( x, y, width, height ) { +Graphics.prototype.drawRect = function ( x, y, width, height ) +{ this.drawShape(new math.Rectangle(x,y, width, height)); return this; @@ -556,7 +602,8 @@ * @param height {number} The height of the rectangle * @param radius {number} Radius of the rectangle corners */ -Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) { +Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) +{ this.drawShape(new math.RoundedRectangle(x, y, width, height, radius)); return this; @@ -570,7 +617,8 @@ * @param radius {number} The radius of the circle * @return {Graphics} */ -Graphics.prototype.drawCircle = function (x, y, radius) { +Graphics.prototype.drawCircle = function (x, y, radius) +{ this.drawShape(new math.Circle(x,y, radius)); return this; @@ -585,7 +633,8 @@ * @param height {number} The half height of the ellipse * @return {Graphics} */ -Graphics.prototype.drawEllipse = function (x, y, width, height) { +Graphics.prototype.drawEllipse = function (x, y, width, height) +{ this.drawShape(new math.Ellipse(x, y, width, height)); return this; @@ -597,8 +646,10 @@ * @param path {Array} The path data used to construct the polygon. * @return {Graphics} */ -Graphics.prototype.drawPolygon = function (path) { - if (!(path instanceof Array)) { +Graphics.prototype.drawPolygon = function (path) +{ + if (!(path instanceof Array)) + { path = Array.prototype.slice.call(arguments); } @@ -612,7 +663,8 @@ * * @return {Graphics} */ -Graphics.prototype.clear = function () { +Graphics.prototype.clear = function () +{ this.lineWidth = 0; this.filling = false; @@ -631,7 +683,8 @@ * @param scaleMode {number} Should be one of the scaleMode consts * @return {Texture} a texture of the graphics object */ -Graphics.prototype.generateTexture = function (resolution, scaleMode) { +Graphics.prototype.generateTexture = function (resolution, scaleMode) +{ resolution = resolution || 1; var bounds = this.getBounds(); @@ -655,17 +708,21 @@ * * @param renderer {WebGLRenderer} */ -Graphics.prototype._renderWebGL = function (renderer) { +Graphics.prototype._renderWebGL = function (renderer) +{ // if the sprite is not visible or the alpha is 0 then no need to render this element - if (this.isMask === true) { + if (this.isMask === true) + { return; } // this code may still be needed so leaving for now.. - // + // /* - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture on the gpu too! @@ -681,17 +738,24 @@ return; } - */ - - // check if the webgl graphic needs to be updated - if (this.glDirty) { - this.dirty = true; - this.glDirty = false; - } + else */ - renderer.setObjectRendererer(renderer.graphicsRenderer); - renderer.graphicsRenderer.render(this); + renderer.spriteBatch.stop(); + renderer.blendModeManager.setBlendMode(this.blendMode); + // check blend mode + renderer.blendModeManager.setBlendMode( this.blendMode ); + + // check if the webgl graphic needs to be updated + if (this.glDirty) + { + this.dirty = true; + this.glDirty = false; + } + + WebGLGraphics.renderGraphics(this, renderer); + + renderer.spriteBatch.start(); }; /** @@ -700,14 +764,18 @@ * @param renderer {CanvasRenderer} * @private */ -Graphics.prototype.renderCanvas = function (renderer) { +Graphics.prototype.renderCanvas = function (renderer) +{ // 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.isMask === true) { + if (!this.visible || this.alpha <= 0 || this.isMask === true) + { return; } - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture @@ -723,16 +791,19 @@ return; } - else { + else + { var context = renderer.context; var transform = this.worldTransform; - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } @@ -748,11 +819,13 @@ CanvasGraphics.renderGraphics(this, context); - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } } @@ -763,13 +836,16 @@ * * @return {Rectangle} the rectangular bounding area */ -Graphics.prototype.getBounds = function (matrix) { +Graphics.prototype.getBounds = function (matrix) +{ // return an empty object if the item is a mask! - if (this.isMask) { + if (this.isMask) + { return math.Rectangle.EMPTY; } - if (this.dirty) { + if (this.dirty) + { this.updateLocalBounds(); this.glDirty = true; @@ -841,23 +917,27 @@ * Update the bounds of the object * */ -Graphics.prototype.updateLocalBounds = function () { +Graphics.prototype.updateLocalBounds = function () +{ var minX = Infinity; var maxX = -Infinity; var minY = Infinity; var maxY = -Infinity; - if (this.graphicsData.length) { + if (this.graphicsData.length) + { var shape, points, x, y, w, h; - for (var i = 0; i < this.graphicsData.length; i++) { + for (var i = 0; i < this.graphicsData.length; i++) + { var data = this.graphicsData[i]; var type = data.type; var lineWidth = data.lineWidth; shape = data.shape; - if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) { + if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) + { x = shape.x - lineWidth/2; y = shape.y - lineWidth/2; w = shape.width + lineWidth; @@ -869,7 +949,8 @@ minY = y < minY ? y : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.CIRC) { + else if (type === CONST.SHAPES.CIRC) + { x = shape.x; y = shape.y; w = shape.radius + lineWidth/2; @@ -881,7 +962,8 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.ELIP) { + else if (type === CONST.SHAPES.ELIP) + { x = shape.x; y = shape.y; w = shape.width + lineWidth/2; @@ -893,11 +975,13 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else { + else + { // POLY points = shape.points; - for (var j = 0; j < points.length; j += 2) { + for (var j = 0; j < points.length; j += 2) + { x = points[j]; y = points[j+1]; @@ -910,7 +994,8 @@ } } } - else { + else + { minX = 0; maxX = 0; minY = 0; @@ -931,10 +1016,12 @@ * * @private */ -Graphics.prototype._generateCachedSprite = function () { +Graphics.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { var canvasBuffer = new CanvasBuffer(bounds.width, bounds.height); var texture = Texture.fromCanvas(canvasBuffer.canvas); @@ -943,7 +1030,8 @@ this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.buffer.resize(bounds.width, bounds.height); } @@ -968,7 +1056,8 @@ * * @private */ -Graphics.prototype.updateCachedSpriteTexture = function () { +Graphics.prototype.updateCachedSpriteTexture = function () +{ var cachedSprite = this._cachedSprite; var texture = cachedSprite.texture; var canvas = cachedSprite.buffer.canvas; @@ -989,7 +1078,8 @@ * Destroys a previous cached sprite. * */ -Graphics.prototype.destroyCachedSprite = function () { +Graphics.prototype.destroyCachedSprite = function () +{ this._cachedSprite.texture.destroy(true); // let the gc collect the unused sprite @@ -1003,10 +1093,13 @@ * @param {Circle|Rectangle|Ellipse|Line|Polygon} shape The Shape object to draw. * @return {GraphicsData} The generated GraphicsData object. */ -Graphics.prototype.drawShape = function (shape) { - if (this.currentPath) { +Graphics.prototype.drawShape = function (shape) +{ + if (this.currentPath) + { // check current path! - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath.shape.points.length <= 2) + { this.graphicsData.pop(); } } @@ -1017,7 +1110,8 @@ this.graphicsData.push(data); - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { data.shape.closed = this.filling; this.currentPath = data; } diff --git a/src/core/primitives/GraphicsData.js b/src/core/primitives/GraphicsData.js index 99decbe..788f6f2 100644 --- a/src/core/primitives/GraphicsData.js +++ b/src/core/primitives/GraphicsData.js @@ -4,7 +4,8 @@ * @class * @namespace PIXI */ -function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) { +function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) +{ this.lineWidth = lineWidth; this.lineColor = lineColor; this.lineAlpha = lineAlpha; @@ -27,7 +28,8 @@ * * @return {GraphicsData} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ return new GraphicsData( this.lineWidth, this.lineColor, diff --git a/src/core/renderers/canvas/CanvasRenderer.js b/src/core/renderers/canvas/CanvasRenderer.js index 15a0978..7aebd44 100644 --- a/src/core/renderers/canvas/CanvasRenderer.js +++ b/src/core/renderers/canvas/CanvasRenderer.js @@ -17,17 +17,22 @@ * @param [options.resolution=1] {number} the resolution of the renderer retina would be 2 * @param [options.clearBeforeRender=true] {boolean} This sets if the CanvasRenderer will clear the canvas or not before the new render pass. */ -function CanvasRenderer(width, height, options) { +function CanvasRenderer(width, height, options) +{ utils.sayHello('Canvas'); - if (options) { - for (var i in CONST.defaultRenderOptions) { - if (typeof options[i] === 'undefined') { + if (options) + { + for (var i in CONST.defaultRenderOptions) + { + if (typeof options[i] === 'undefined') + { options[i] = CONST.defaultRenderOptions[i]; } } } - else { + else + { options = CONST.defaultRenderOptions; } @@ -156,19 +161,24 @@ this.smoothProperty = null; - if (this.context.imageSmoothingEnabled) { + if (this.context.imageSmoothingEnabled) + { this.smoothProperty = 'imageSmoothingEnabled'; } - else if (this.context.webkitImageSmoothingEnabled) { + else if (this.context.webkitImageSmoothingEnabled) + { this.smoothProperty = 'webkitImageSmoothingEnabled'; } - else if (this.context.mozImageSmoothingEnabled) { + else if (this.context.mozImageSmoothingEnabled) + { this.smoothProperty = 'mozImageSmoothingEnabled'; } - else if (this.context.oImageSmoothingEnabled) { + else if (this.context.oImageSmoothingEnabled) + { this.smoothProperty = 'oImageSmoothingEnabled'; } - else if (this.context.msImageSmoothingEnabled) { + else if (this.context.msImageSmoothingEnabled) + { this.smoothProperty = 'msImageSmoothingEnabled'; } @@ -193,10 +203,12 @@ * @memberof CanvasRenderer# */ backgroundColor: { - get: function () { + get: function () + { return this._backgroundColor; }, - set: function (val) { + set: function (val) + { this._backgroundColor = val; this._backgroundColorString = utils.hex2string(val); } @@ -208,7 +220,8 @@ * * @param object {DisplayObject} the object to be rendered */ -CanvasRenderer.prototype.render = function (object) { +CanvasRenderer.prototype.render = function (object) +{ object.updateTransform(); this.context.setTransform(1,0,0,1,0,0); @@ -218,16 +231,20 @@ this.currentBlendMode = CONST.blendModes.NORMAL; this.context.globalCompositeOperation = this.blendModes[CONST.blendModes.NORMAL]; - if (navigator.isCocoonJS && this.view.screencanvas) { + if (navigator.isCocoonJS && this.view.screencanvas) + { this.context.fillStyle = 'black'; this.context.clear(); } - if (this.clearBeforeRender) { - if (this.transparent) { + if (this.clearBeforeRender) + { + if (this.transparent) + { this.context.clearRect(0, 0, this.width, this.height); } - else { + else + { this.context.fillStyle = this._backgroundColorString; this.context.fillRect(0, 0, this.width , this.height); } @@ -241,8 +258,10 @@ * * @param [removeView=false] {boolean} Removes the Canvas element from the DOM. */ -CanvasRenderer.prototype.destroy = function (removeView) { - if (removeView && this.view.parent) { +CanvasRenderer.prototype.destroy = function (removeView) +{ + if (removeView && this.view.parent) + { this.view.parent.removeChild(this.view); } @@ -257,14 +276,16 @@ * @param width {number} the new width of the canvas view * @param height {number} the new height of the canvas view */ -CanvasRenderer.prototype.resize = function (width, height) { +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) { + if (this.autoResize) + { this.view.style.width = this.width / this.resolution + 'px'; this.view.style.height = this.height / this.resolution + 'px'; } @@ -276,7 +297,8 @@ * @param displayObject {DisplayObject} The displayObject to render * @private */ -CanvasRenderer.prototype.renderDisplayObject = function (displayObject) { +CanvasRenderer.prototype.renderDisplayObject = function (displayObject) +{ displayObject.renderCanvas(this); }; @@ -285,11 +307,14 @@ * * @private */ -CanvasRenderer.prototype._mapBlendModes = function () { - if (!this.blendModes) { +CanvasRenderer.prototype._mapBlendModes = function () +{ + if (!this.blendModes) + { this.blendModes = {}; - if (utils.canUseNewCanvasBlendModes()) { + if (utils.canUseNewCanvasBlendModes()) + { this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? this.blendModes[CONST.blendModes.MULTIPLY] = 'multiply'; @@ -308,7 +333,8 @@ this.blendModes[CONST.blendModes.COLOR] = 'color'; this.blendModes[CONST.blendModes.LUMINOSITY] = 'luminosity'; } - else { + else + { // this means that the browser does not support the cool new blend modes in canvas 'cough' ie 'cough' this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? diff --git a/src/core/renderers/canvas/utils/CanvasBuffer.js b/src/core/renderers/canvas/utils/CanvasBuffer.js index ebe5d47..b183a66 100644 --- a/src/core/renderers/canvas/utils/CanvasBuffer.js +++ b/src/core/renderers/canvas/utils/CanvasBuffer.js @@ -6,7 +6,8 @@ * @param width {number} the width for the newly created canvas * @param height {number} the height for the newly created canvas */ -function CanvasBuffer(width, height) { +function CanvasBuffer(width, height) +{ /** * The Canvas object that belongs to this CanvasBuffer. * @@ -36,10 +37,12 @@ * @memberof CanvasBuffer# */ width: { - get: function () { + get: function () + { return this.canvas.width; }, - set: function (val) { + set: function (val) + { this.canvas.width = val; } }, @@ -50,10 +53,12 @@ * @memberof CanvasBuffer# */ height: { - get: function () { + get: function () + { return this.canvas.height; }, - set: function (val) { + set: function (val) + { this.canvas.height = val; } } @@ -64,7 +69,8 @@ * * @private */ -CanvasBuffer.prototype.clear = function () { +CanvasBuffer.prototype.clear = function () +{ this.context.setTransform(1, 0, 0, 1, 0, 0); this.context.clearRect(0,0, this.canvas.width, this.canvas.height); }; @@ -75,7 +81,8 @@ * @param width {number} the new width of the canvas * @param height {number} the new height of the canvas */ -CanvasBuffer.prototype.resize = function (width, height) { +CanvasBuffer.prototype.resize = function (width, height) +{ this.canvas.width = width; this.canvas.height = height; }; diff --git a/src/core/renderers/canvas/utils/CanvasGraphics.js b/src/core/renderers/canvas/utils/CanvasGraphics.js index c7eaa2a..3f2a91f 100644 --- a/src/core/renderers/canvas/utils/CanvasGraphics.js +++ b/src/core/renderers/canvas/utils/CanvasGraphics.js @@ -13,15 +13,18 @@ * @param graphics {Graphics} the actual graphics object to render * @param context {CanvasRenderingContext2D} the 2d drawing method of the canvas */ -CanvasGraphics.renderGraphics = function (graphics, context) { +CanvasGraphics.renderGraphics = function (graphics, context) +{ var worldAlpha = graphics.worldAlpha; - if (graphics.dirty) { + if (graphics.dirty) + { this.updateGraphicsTint(graphics); graphics.dirty = false; } - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; @@ -30,69 +33,82 @@ context.lineWidth = data.lineWidth; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { context.beginPath(); var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } - if (shape.closed) { + if (shape.closed) + { context.lineTo(points[0], points[1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fillRect(shape.x, shape.y, shape.width, shape.height); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.strokeRect(shape.x, shape.y, shape.width, shape.height); } } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.beginPath(); context.arc(shape.x, shape.y, shape.radius,0,2*Math.PI); context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas var w = shape.width * 2; @@ -119,18 +135,21 @@ context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; var width = shape.width; @@ -152,13 +171,15 @@ context.quadraticCurveTo(rx, ry, rx, ry + radius); context.closePath(); - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); @@ -174,45 +195,54 @@ * @param graphics {Graphics} the graphics which will be used as a mask * @param context {CanvasRenderingContext2D} the context 2d method of the canvas */ -CanvasGraphics.renderGraphicsMask = function (graphics, context) { +CanvasGraphics.renderGraphicsMask = function (graphics, context) +{ var len = graphics.graphicsData.length; - if (len === 0) { + if (len === 0) + { return; } context.beginPath(); - for (var i = 0; i < len; i++) { + for (var i = 0; i < len; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { context.rect(shape.x, shape.y, shape.width, shape.height); context.closePath(); } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.arc(shape.x, shape.y, shape.radius, 0, 2 * Math.PI); context.closePath(); } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas @@ -237,7 +267,8 @@ context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); context.closePath(); } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; @@ -262,8 +293,10 @@ } }; -CanvasGraphics.updateGraphicsTint = function (graphics) { - if (graphics.tint === 0xFFFFFF) { +CanvasGraphics.updateGraphicsTint = function (graphics) +{ + if (graphics.tint === 0xFFFFFF) + { return; } @@ -271,7 +304,8 @@ var tintG = (graphics.tint >> 8 & 0xFF) / 255; var tintB = (graphics.tint & 0xFF)/ 255; - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var fillColor = data.fillColor | 0; diff --git a/src/core/renderers/canvas/utils/CanvasMaskManager.js b/src/core/renderers/canvas/utils/CanvasMaskManager.js index e04a733..9827d36 100644 --- a/src/core/renderers/canvas/utils/CanvasMaskManager.js +++ b/src/core/renderers/canvas/utils/CanvasMaskManager.js @@ -6,7 +6,8 @@ * @class * @namespace PIXI */ -function CanvasMaskManager() {} +function CanvasMaskManager() +{} CanvasMaskManager.prototype.constructor = CanvasMaskManager; module.exports = CanvasMaskManager; @@ -17,7 +18,8 @@ * @param maskData {object} the maskData that will be pushed * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.pushMask = function (maskData, renderer) { +CanvasMaskManager.prototype.pushMask = function (maskData, renderer) +{ renderer.context.save(); var cacheAlpha = maskData.alpha; @@ -45,6 +47,7 @@ * * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.popMask = function (renderer) { +CanvasMaskManager.prototype.popMask = function (renderer) +{ renderer.context.restore(); }; diff --git a/src/core/renderers/canvas/utils/CanvasTinter.js b/src/core/renderers/canvas/utils/CanvasTinter.js index 17e0529..d2fb1bc 100644 --- a/src/core/renderers/canvas/utils/CanvasTinter.js +++ b/src/core/renderers/canvas/utils/CanvasTinter.js @@ -14,7 +14,8 @@ * @param color {number} the color to use to tint the sprite with * @return {HTMLCanvasElement} The tinted canvas */ -CanvasTinter.getTintedTexture = function (sprite, color) { +CanvasTinter.getTintedTexture = function (sprite, color) +{ var texture = sprite.texture; color = CanvasTinter.roundColor(color); @@ -23,7 +24,8 @@ texture.tintCache = texture.tintCache || {}; - if (texture.tintCache[stringColor]) { + if (texture.tintCache[stringColor]) + { return texture.tintCache[stringColor]; } @@ -33,14 +35,16 @@ //CanvasTinter.tintWithPerPixel(texture, stringColor, canvas); CanvasTinter.tintMethod(texture, color, canvas); - if (CanvasTinter.convertTintToImage) { + if (CanvasTinter.convertTintToImage) + { // is this better? var tintImage = new Image(); tintImage.src = canvas.toDataURL(); texture.tintCache[stringColor] = tintImage; } - else { + else + { texture.tintCache[stringColor] = canvas; // if we are not converting the texture to an image then we need to lose the reference to the canvas CanvasTinter.canvas = null; @@ -56,7 +60,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithMultiply = function (texture, color, canvas) { +CanvasTinter.tintWithMultiply = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -104,7 +109,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithOverlay = function (texture, color, canvas) { +CanvasTinter.tintWithOverlay = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -139,7 +145,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithPerPixel = function (texture, color, canvas) { +CanvasTinter.tintWithPerPixel = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -167,7 +174,8 @@ var pixels = pixelData.data; - for (var i = 0; i < pixels.length; i += 4) { + for (var i = 0; i < pixels.length; i += 4) + { pixels[i+0] *= r; pixels[i+1] *= g; pixels[i+2] *= b; @@ -181,7 +189,8 @@ * * @param color {number} the color to round, should be a hex color */ -CanvasTinter.roundColor = function (color) { +CanvasTinter.roundColor = function (color) +{ var step = CanvasTinter.cacheStepsPerColorChannel; var rgbValues = utils.hex2rgb(color); diff --git a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js index 9f2f89a..35edbaf 100644 --- a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js +++ b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLBlendModeManager(renderer) { +function WebGLBlendModeManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -23,8 +24,10 @@ * * @param blendMode {number} the blendMode, should be a Pixi const, such as BlendModes.ADD */ -WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) { - if (this.currentBlendMode === blendMode) { +WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) +{ + if (this.currentBlendMode === blendMode) + { return false; } diff --git a/src/core/renderers/webgl/managers/WebGLFilterManager.js b/src/core/renderers/webgl/managers/WebGLFilterManager.js index 1179258..2dac048 100644 --- a/src/core/renderers/webgl/managers/WebGLFilterManager.js +++ b/src/core/renderers/webgl/managers/WebGLFilterManager.js @@ -7,7 +7,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLFilterManager(renderer) { +function WebGLFilterManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -32,7 +33,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.texturePool.length = 0; self.initShaderBuffers(); }); @@ -46,7 +48,8 @@ * @param renderer {WebGLRenderer} * @param buffer {ArrayBuffer} */ -WebGLFilterManager.prototype.begin = function (buffer) { +WebGLFilterManager.prototype.begin = function (buffer) +{ this.defaultShader = this.renderer.shaderManager.defaultShader; this.width = this.renderer.projection.x * 2; @@ -60,7 +63,8 @@ * * @param filterBlock {object} the filter that will be pushed to the current filter stack */ -WebGLFilterManager.prototype.pushFilter = function (filterBlock) { +WebGLFilterManager.prototype.pushFilter = function (filterBlock) +{ var gl = this.renderer.gl; var projection = this.renderer.projection; @@ -78,10 +82,12 @@ this.offsetY += filterBlock._filterArea.y; var texture = this.texturePool.pop(); - if (!texture) { + if (!texture) + { texture = new FilterTexture(this.renderer.gl, this.width, this.height); } - else { + else + { texture.resize(this.width, this.height); } @@ -98,29 +104,35 @@ var localX = filterArea.x, localY = filterArea.y; - if (filterArea.x < 0) { + if (filterArea.x < 0) + { filterArea.width += filterArea.x; filterArea.x = 0; } - if (filterArea.y < 0) { + if (filterArea.y < 0) + { filterArea.height += filterArea.y; filterArea.y = 0; } - if (localX + filterArea.width > this.width) { + if (localX + filterArea.width > this.width) + { filterArea.width = this.width - localX; } - if (localY + filterArea.height > this.height) { + if (localY + filterArea.height > this.height) + { filterArea.height = this.height - localY; } - if (filterArea.width < 0) { + if (filterArea.width < 0) + { filterArea.width = 0; } - if (filterArea.height < 0) { + if (filterArea.height < 0) + { filterArea.height = 0; } @@ -154,7 +166,8 @@ * Removes the last filter from the filter stack and doesn't return it. * */ -WebGLFilterManager.prototype.popFilter = function () { +WebGLFilterManager.prototype.popFilter = function () +{ var gl = this.renderer.gl; var filterBlock = this.filterStack.pop(); @@ -163,7 +176,8 @@ var projection = this.renderer.projection; var offset = this.renderer.offset; - if (filterBlock.filterPasses.length > 1) { + if (filterBlock.filterPasses.length > 1) + { gl.viewport(0, 0, filterArea.width, filterArea.height); gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); @@ -193,7 +207,8 @@ var inputTexture = texture; var outputTexture = this.texturePool.pop(); - if (!outputTexture) { + if (!outputTexture) + { outputTexture = new FilterTexture(this.renderer.gl, this.width, this.height); } outputTexture.resize(this.width, this.height); @@ -204,7 +219,8 @@ gl.disable(gl.BLEND); - for (var i = 0; i < filterBlock.filterPasses.length-1; i++) { + for (var i = 0; i < filterBlock.filterPasses.length-1; i++) + { var filterPass = filterBlock.filterPasses[i]; gl.bindFramebuffer(gl.FRAMEBUFFER, outputTexture.frameBuffer ); @@ -243,10 +259,12 @@ var buffer = this.buffer; // time to render the filters texture to the previous scene - if (this.filterStack.length === 0) { + if (this.filterStack.length === 0) + { gl.colorMask(true, true, true, true);//this.transparent); } - else { + else + { var currentFilter = this.filterStack[this.filterStack.length-1]; filterArea = currentFilter._filterArea; @@ -332,13 +350,15 @@ * @param width {number} the horizontal range of the filter * @param height {number} the vertical range of the filter */ -WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) { +WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) +{ // use program var gl = this.renderer.gl; var shader = filter.shaders[gl.id]; - if (!shader) { + if (!shader) + { shader = new Shader(gl); shader.fragmentSrc = filter.fragmentSrc; @@ -356,7 +376,8 @@ gl.uniform2f(shader.projectionVector, width/2, -height/2); gl.uniform2f(shader.offsetVector, 0,0); - if (filter.uniforms.dimensions) { + 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]; @@ -386,7 +407,8 @@ * Initialises the shader buffers. * */ -WebGLFilterManager.prototype.initShaderBuffers = function () { +WebGLFilterManager.prototype.initShaderBuffers = function () +{ var gl = this.renderer.gl; // create some buffers @@ -432,7 +454,8 @@ * Destroys the filter and removes it from the filter stack. * */ -WebGLFilterManager.prototype.destroy = function () { +WebGLFilterManager.prototype.destroy = function () +{ var gl = this.renderer.gl; this.filterStack = null; @@ -441,7 +464,8 @@ this.offsetY = 0; // destroy textures - for (var i = 0; i < this.texturePool.length; i++) { + for (var i = 0; i < this.texturePool.length; i++) + { this.texturePool[i].destroy(); } diff --git a/src/core/renderers/webgl/managers/WebGLManager.js b/src/core/renderers/webgl/managers/WebGLManager.js index 9d47b5c..c30cd51 100644 --- a/src/core/renderers/webgl/managers/WebGLManager.js +++ b/src/core/renderers/webgl/managers/WebGLManager.js @@ -3,7 +3,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLManager(renderer) { +function WebGLManager(renderer) +{ /** * The renderer this manager works for. * @@ -15,6 +16,7 @@ WebGLManager.prototype.constructor = WebGLManager; module.exports = WebGLManager; -WebGLManager.prototype.destroy = function () { +WebGLManager.prototype.destroy = function () +{ this.renderer = null; }; diff --git a/src/core/renderers/webgl/managers/WebGLMaskManager.js b/src/core/renderers/webgl/managers/WebGLMaskManager.js index 2f90b64..e568812 100644 --- a/src/core/renderers/webgl/managers/WebGLMaskManager.js +++ b/src/core/renderers/webgl/managers/WebGLMaskManager.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLMaskManager(renderer) { +function WebGLMaskManager(renderer) +{ WebGLManager.call(this, renderer); } @@ -19,12 +20,15 @@ * * @param maskData {any[]} */ -WebGLMaskManager.prototype.pushMask = function (maskData) { - if (maskData.dirty) { +WebGLMaskManager.prototype.pushMask = function (maskData) +{ + if (maskData.dirty) + { WebGLGraphics.updateGraphics(maskData, this.renderer.gl); } - if (!maskData._webGL[this.renderer.gl.id].data.length) { + if (!maskData._webGL[this.renderer.gl.id].data.length) + { return; } @@ -36,6 +40,7 @@ * * @param maskData {any[]} */ -WebGLMaskManager.prototype.popMask = function (maskData) { +WebGLMaskManager.prototype.popMask = function (maskData) +{ this.renderer.stencilManager.popStencil(maskData, maskData._webGL[this.renderer.gl.id].data[0], this.renderer); }; diff --git a/src/core/renderers/webgl/managers/WebGLShaderManager.js b/src/core/renderers/webgl/managers/WebGLShaderManager.js index fef071c..90c6477 100644 --- a/src/core/renderers/webgl/managers/WebGLShaderManager.js +++ b/src/core/renderers/webgl/managers/WebGLShaderManager.js @@ -10,7 +10,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLShaderManager(renderer) { +function WebGLShaderManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -28,7 +29,8 @@ */ this.tempAttribState = []; - for (var i = 0; i < this.maxAttibs; i++) { + for (var i = 0; i < this.maxAttibs; i++) + { this.attribState[i] = false; } @@ -66,7 +68,8 @@ // listen for context and update necessary shaders var self = this; - this.renderer.on('context', function (event) { + this.renderer.on('context', function (event) + { var gl = event.data; // this shader is used for rendering primitives @@ -97,29 +100,36 @@ * * @param attribs {Array} attribs */ -WebGLShaderManager.prototype.setAttribs = function (attribs) { +WebGLShaderManager.prototype.setAttribs = function (attribs) +{ // reset temp state var i; - for (i = 0; i < this.tempAttribState.length; i++) { + for (i = 0; i < this.tempAttribState.length; i++) + { this.tempAttribState[i] = false; } // set the new attribs - for (var a in attribs) { + for (var a in attribs) + { this.tempAttribState[attribs[a]] = true; } var gl = this.renderer.gl; - for (i = 0; i < this.attribState.length; i++) { - if (this.attribState[i] !== this.tempAttribState[i]) { + for (i = 0; i < this.attribState.length; i++) + { + if (this.attribState[i] !== this.tempAttribState[i]) + { this.attribState[i] = this.tempAttribState[i]; - if (this.attribState[i]) { + if (this.attribState[i]) + { gl.enableVertexAttribArray(i); } - else { + else + { gl.disableVertexAttribArray(i); } } @@ -131,8 +141,10 @@ * * @param shader {Any} */ -WebGLShaderManager.prototype.setShader = function (shader) { - if (this._currentId === shader.uuid) { +WebGLShaderManager.prototype.setShader = function (shader) +{ + if (this._currentId === shader.uuid) + { return false; } @@ -150,7 +162,8 @@ * Destroys this object. * */ -WebGLShaderManager.prototype.destroy = function () { +WebGLShaderManager.prototype.destroy = function () +{ this.attribState = null; this.tempAttribState = null; diff --git a/src/core/renderers/webgl/managers/WebGLStencilManager.js b/src/core/renderers/webgl/managers/WebGLStencilManager.js index 9ec6398..4cb0134 100644 --- a/src/core/renderers/webgl/managers/WebGLStencilManager.js +++ b/src/core/renderers/webgl/managers/WebGLStencilManager.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLStencilManager(renderer) { +function WebGLStencilManager(renderer) +{ WebGLManager.call(this, renderer); this.stencilStack = []; @@ -24,12 +25,14 @@ * @param graphics {Graphics} * @param webGLData {any[]} */ -WebGLStencilManager.prototype.pushStencil = function (graphics, webGLData) { +WebGLStencilManager.prototype.pushStencil = function (graphics, webGLData) +{ var gl = this.renderer.gl; this.bindGraphics(graphics, webGLData, this.renderer); - if (this.stencilStack.length === 0) { + if (this.stencilStack.length === 0) + { gl.enable(gl.STENCIL_TEST); gl.clear(gl.STENCIL_BUFFER_BIT); this.reverse = true; @@ -47,14 +50,17 @@ // draw the triangle strip! - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } @@ -62,31 +68,38 @@ // draw a quad to increment.. gl.drawElements(gl.TRIANGLE_FAN, 4, gl.UNSIGNED_SHORT, ( webGLData.indices.length - 4 ) * 2 ); - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); } this.reverse = !this.reverse; } - else { - if (!this.reverse) { + else + { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } - else { + 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) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); } } @@ -103,7 +116,8 @@ * @param graphics {Graphics} * @param webGLData {Array} */ -WebGLStencilManager.prototype.bindGraphics = function (graphics, webGLData) { +WebGLStencilManager.prototype.bindGraphics = function (graphics, webGLData) +{ //if (this._currentGraphics === graphics)return; this._currentGraphics = graphics; @@ -114,7 +128,8 @@ offset = this.renderer.offset, shader;// = this.renderer.shaderManager.primitiveShader; - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { shader = this.renderer.shaderManager.complexPrimitiveShader; this.renderer.shaderManager.setShader(shader); @@ -141,7 +156,8 @@ // set the index buffer! gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, webGLData.indexBuffer); } - else { + else + { //this.renderer.shaderManager.activatePrimitiveShader(); shader = this.renderer.shaderManager.primitiveShader; this.renderer.shaderManager.setShader( shader ); @@ -154,7 +170,7 @@ gl.uniform2f(shader.uniforms.offsetVector._location, -offset.x, -offset.y); gl.uniform3fv(shader.uniforms.tint._location, utils.hex2rgb(graphics.tint)); - + gl.uniform1f(shader.uniforms.alpha._location, graphics.worldAlpha); @@ -172,19 +188,22 @@ * @param graphics {Graphics} * @param webGLData {Array} */ -WebGLStencilManager.prototype.popStencil = function (graphics, webGLData) { +WebGLStencilManager.prototype.popStencil = function (graphics, webGLData) +{ var gl = this.renderer.gl; this.stencilStack.pop(); this.count--; - if (this.stencilStack.length === 0) { + if (this.stencilStack.length === 0) + { // the stack is empty! gl.disable(gl.STENCIL_TEST); } - else { + else + { var level = this.count; @@ -192,14 +211,17 @@ gl.colorMask(false, false, false, false); - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { this.reverse = !this.reverse; - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } @@ -213,31 +235,38 @@ // draw the triangle strip! gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); - if (!this.reverse) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); } } - else { + else + { // console.log("<<>>") - if (!this.reverse) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } - else { + 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) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); } } @@ -253,7 +282,8 @@ * Destroys the mask stack. * */ -WebGLStencilManager.prototype.destroy = function () { +WebGLStencilManager.prototype.destroy = function () +{ this.renderer = null; this.stencilStack = null; }; diff --git a/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js b/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js index 913ba5e..1ea7d19 100644 --- a/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js +++ b/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function ComplexPrimitiveShader(gl) { +function ComplexPrimitiveShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -24,7 +25,8 @@ 'uniform float flipY;', 'varying vec4 vColor;', - 'void main(void) {', + '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);', @@ -37,7 +39,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = vColor;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/FastShader.js b/src/core/renderers/webgl/shaders/FastShader.js index bd2e29a..2e5e060 100644 --- a/src/core/renderers/webgl/shaders/FastShader.js +++ b/src/core/renderers/webgl/shaders/FastShader.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function FastShader(gl) { +function FastShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -28,7 +29,8 @@ 'const vec2 center = vec2(-1.0, 1.0);', - 'void main(void) {', + 'void main(void) + {', ' vec2 v;', ' vec2 sv = aVertexPosition * aScale;', ' v.x = (sv.x) * cos(aRotation) - (sv.y) * sin(aRotation);', @@ -49,7 +51,8 @@ 'uniform sampler2D uSampler;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/PrimitiveShader.js b/src/core/renderers/webgl/shaders/PrimitiveShader.js index 6f25409..a25f54f 100644 --- a/src/core/renderers/webgl/shaders/PrimitiveShader.js +++ b/src/core/renderers/webgl/shaders/PrimitiveShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function PrimitiveShader(gl) { +function PrimitiveShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -23,7 +24,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + '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);', @@ -36,7 +38,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = vColor;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/Shader.js b/src/core/renderers/webgl/shaders/Shader.js index f8964f5..fd75ef5 100644 --- a/src/core/renderers/webgl/shaders/Shader.js +++ b/src/core/renderers/webgl/shaders/Shader.js @@ -6,7 +6,8 @@ * @param [fragmentSrc] {string} The source of the fragment shader. * @param [vertexSrc] {string} The source of the vertex shader. */ -function Shader(gl, vertexSrc, fragmentSrc, customUniforms, customAttributes) { +function Shader(gl, vertexSrc, fragmentSrc, customUniforms, customAttributes) +{ /** * @member {number} * @readonly @@ -33,7 +34,8 @@ dimensions: { type: '4f', value: new Float32Array(4) } }; - for (var u in customUniforms) { + for (var u in customUniforms) + { this.uniforms[u] = customUniforms[u]; } @@ -43,7 +45,8 @@ aColor: 0 }; - for (var a in customAttributes) { + for (var a in customAttributes) + { this.attributes[a] = customAttributes[a]; } @@ -66,7 +69,8 @@ 'const vec2 center = vec2(-1.0, 1.0);', - 'void main(void) {', + 'void main(void) + {', ' gl_Position = vec4( ((aVertexPosition + offsetVector) / projectionVector) + center , 0.0, 1.0);', ' vTextureCoord = aTextureCoord;', ' vColor = vec4(aColor.rgb * aColor.a, aColor.a);', @@ -85,7 +89,8 @@ 'uniform sampler2D uSampler;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;', '}' ].join('\n'); @@ -96,7 +101,8 @@ Shader.prototype.constructor = Shader; module.exports = Shader; -Shader.prototype.init = function () { +Shader.prototype.init = function () +{ this.compile(); this.gl.useProgram(this.program); @@ -105,14 +111,18 @@ this.cacheAttributeLocations(Object.keys(this.attributes)); }; -Shader.prototype.cacheUniformLocations = function (keys) { - for (var i = 0; i < keys.length; ++i) { +Shader.prototype.cacheUniformLocations = function (keys) +{ + for (var i = 0; i < keys.length; ++i) + { this.uniforms[keys[i]]._location = this.gl.getUniformLocation(this.program, keys[i]); } }; -Shader.prototype.cacheAttributeLocations = function (keys) { - for (var i = 0; i < keys.length; ++i) { +Shader.prototype.cacheAttributeLocations = function (keys) +{ + for (var i = 0; i < keys.length; ++i) + { this.attributes[keys[i]] = this.gl.getAttribLocation(this.program, keys[i]); } @@ -124,14 +134,16 @@ // 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.attributes.aColor === -1) { + // if (this.attributes.aColor === -1) + { // this.attributes.aColor = 2; // } // End worst hack eva // }; -Shader.prototype.compile = function () { +Shader.prototype.compile = function () +{ var gl = this.gl; var glVertShader = this._glCompile(gl.VERTEX_SHADER, this.vertexSrc); @@ -144,13 +156,15 @@ gl.linkProgram(program); // if linking fails, then log and cleanup - if (!gl.getProgramParameter(program, gl.LINK_STATUS)) { + if (!gl.getProgramParameter(program, gl.LINK_STATUS)) + { window.console.error('Pixi.js Error: Could not initialize shader.'); window.console.error('gl.VALIDATE_STATUS', gl.getProgramParameter(program, gl.VALIDATE_STATUS)); window.console.error('gl.getError()', gl.getError()); // if there is a program info log, log it - if (gl.getProgramInfoLog(program) !== '') { + if (gl.getProgramInfoLog(program) !== '') + { window.console.warn('Pixi.js Warning: gl.getProgramInfoLog()', gl.getProgramInfoLog(program)); } @@ -165,18 +179,21 @@ return (this.program = program); }; -Shader.prototype.syncUniforms = function () { +Shader.prototype.syncUniforms = function () +{ var gl = this.gl; this.textureCount = 1; - for (var key in this.uniforms) { + for (var key in this.uniforms) + { var uniform = this.uniforms[key], location = uniform._location, value = uniform.value, i, il; - switch (uniform.type) { + switch (uniform.type) + { // single int value case 'i': case '1i': @@ -282,7 +299,8 @@ // a Color Value case 'c': - if (typeof value === 'number') { + if (typeof value === 'number') + { value = utils.hex2rgb(value); } @@ -311,11 +329,13 @@ // array of 2D Point objects case 'v2v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(2 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 2] = value[i].x; uniform._array[i * 2 + 1] = value[i].y; } @@ -325,11 +345,13 @@ // array of 3D Point objects case 'v3v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(3 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 3] = value[i].x; uniform._array[i * 3 + 1] = value[i].y; uniform._array[i * 3 + 2] = value[i].z; @@ -341,11 +363,13 @@ // array of 4D Point objects case 'v4v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(4 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 4] = value[i].x; uniform._array[i * 4 + 1] = value[i].y; uniform._array[i * 4 + 2] = value[i].z; @@ -359,7 +383,8 @@ // PIXI.Texture case 't': case 'sampler2D': - if (!uniform.value || !uniform.value.baseTexture || !uniform.value.baseTexture.hasLoaded) { + if (!uniform.value || !uniform.value.baseTexture || !uniform.value.baseTexture.hasLoaded) + { break; } @@ -376,7 +401,8 @@ this.textureCount++; // initialize the texture if we haven't yet - if (!uniform._init) { + if (!uniform._init) + { this.initSampler2D(uniform); uniform._init = true; @@ -394,11 +420,13 @@ * Initialises a Sampler2D uniform (which may only be available later on after initUniforms once the texture has loaded) * */ -Shader.prototype.initSampler2D = function (uniform) { +Shader.prototype.initSampler2D = function (uniform) +{ var gl = this.gl; // Extended texture data - if (uniform.textureData) { + if (uniform.textureData) + { var data = uniform.textureData; // GLTexture = mag linear, min linear_mipmap_linear, wrap repeat + gl.generateMipmap(gl.TEXTURE_2D); @@ -417,14 +445,16 @@ var wrapT = (data.wrapT) ? data.wrapT : gl.CLAMP_TO_EDGE; var format = (data.luminance) ? gl.LUMINANCE : gl.RGBA; - if (data.repeat) { + if (data.repeat) + { wrapS = gl.REPEAT; wrapT = gl.REPEAT; } gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, !!data.flipY); - if (data.width) { + if (data.width) + { var width = (data.width) ? data.width : 512; var height = (data.height) ? data.height : 2; var border = (data.border) ? data.border : 0; @@ -432,7 +462,8 @@ // 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 { + 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); } @@ -448,7 +479,8 @@ * Destroys the shader. * */ -Shader.prototype.destroy = function () { +Shader.prototype.destroy = function () +{ this.gl.deleteProgram(this.program); this.gl = null; @@ -459,13 +491,15 @@ this.fragmentSrc = null; }; -Shader.prototype._glCompile = function (type, src) { +Shader.prototype._glCompile = function (type, src) +{ var shader = this.gl.createShader(type); this.gl.shaderSource(shader, src); this.gl.compileShader(shader); - if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) { + if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) + { window.console.log(this.gl.getShaderInfoLog(shader)); return null; } diff --git a/src/core/renderers/webgl/shaders/StripShader.js b/src/core/renderers/webgl/shaders/StripShader.js index 193f6e1..a7abcc6 100644 --- a/src/core/renderers/webgl/shaders/StripShader.js +++ b/src/core/renderers/webgl/shaders/StripShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function StripShader(gl) { +function StripShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -20,7 +21,8 @@ 'varying vec2 vTextureCoord;', - 'void main(void) {', + '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);', @@ -36,7 +38,8 @@ 'varying vec2 vTextureCoord;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vec2(vTextureCoord.x, vTextureCoord.y)) * alpha;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/utils/FilterTexture.js b/src/core/renderers/webgl/utils/FilterTexture.js index d2c8423..4433d44 100644 --- a/src/core/renderers/webgl/utils/FilterTexture.js +++ b/src/core/renderers/webgl/utils/FilterTexture.js @@ -8,7 +8,8 @@ * @param height {number} the vertical range of the filter * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values */ -function FilterTexture(gl, width, height, scaleMode) { +function FilterTexture(gl, width, height, scaleMode) +{ /** * @member {WebGLContext} */ @@ -59,7 +60,8 @@ * Clears the filter texture. * */ -FilterTexture.prototype.clear = function () { +FilterTexture.prototype.clear = function () +{ var gl = this.gl; gl.clearColor(0,0,0, 0); @@ -72,8 +74,10 @@ * @param width {number} the new width of the texture * @param height {number} the new height of the texture */ -FilterTexture.prototype.resize = function (width, height) { - if (this.width === width && this.height === height) { +FilterTexture.prototype.resize = function (width, height) +{ + if (this.width === width && this.height === height) + { return; } @@ -96,7 +100,8 @@ * Destroys the filter texture. * */ -FilterTexture.prototype.destroy = function () { +FilterTexture.prototype.destroy = function () +{ var gl = this.gl; gl.deleteFramebuffer( this.frameBuffer ); gl.deleteTexture( this.texture ); diff --git a/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js b/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js index c4721e9..a63f4d7 100644 --- a/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js +++ b/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js @@ -14,7 +14,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this sprite batch works for. */ -function WebGLFastSpriteBatch(renderer) { +function WebGLFastSpriteBatch(renderer) +{ /** * The renderer instance this sprite batch operates on. * @@ -91,7 +92,8 @@ */ this.lastIndexCount = 0; - for (var i=0, j=0; i < numIndices; i += 6, j += 4) { + 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; @@ -144,7 +146,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.setupContext(); }); } @@ -157,7 +160,8 @@ * * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLFastSpriteBatch.prototype.setupContext = function () { +WebGLFastSpriteBatch.prototype.setupContext = function () +{ var gl = this.renderer.gl; // create a couple of buffers @@ -177,7 +181,8 @@ /** * @param spriteBatch {SpriteBatch} The SpriteBatch container to prepare for. */ -WebGLFastSpriteBatch.prototype.begin = function (spriteBatch) { +WebGLFastSpriteBatch.prototype.begin = function (spriteBatch) +{ this.shader = this.renderer.shaderManager.fastShader; this.matrix = spriteBatch.worldTransform.toArray(true); @@ -187,33 +192,38 @@ /** */ -WebGLFastSpriteBatch.prototype.end = function () { +WebGLFastSpriteBatch.prototype.end = function () +{ this.flush(); }; /** * @param spriteBatch {SpriteBatch} The SpriteBatch container to render. */ -WebGLFastSpriteBatch.prototype.render = function (spriteBatch) { +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) { + if (!sprite.texture._uvs) + { return; } this.currentBaseTexture = sprite.texture.baseTexture; // check blend mode - if (sprite.blendMode !== this.renderer.blendModeManager.currentBlendMode) { + if (sprite.blendMode !== this.renderer.blendModeManager.currentBlendMode) + { this.flush(); this.renderer.blendModeManager.setBlendMode(sprite.blendMode); } - for (var i=0,j= children.length; i= this.size) { + if (this.currentBatchSize >= this.size) + { this.flush(); } }; @@ -362,29 +379,35 @@ /** * */ -WebGLFastSpriteBatch.prototype.flush = function () { +WebGLFastSpriteBatch.prototype.flush = function () +{ // If the batch is length 0 then return as there is nothing to draw - if (this.currentBatchSize === 0) { + if (this.currentBatchSize === 0) + { return; } var gl = this.renderer.gl; // bind the current texture - if (!this.currentBaseTexture._glTextures[gl.id]) { + if (!this.currentBaseTexture._glTextures[gl.id]) + { this.renderer.updateTexture(this.currentBaseTexture, gl); } //TODO-SHOUD THIS BE ELSE??!?!?! - else { + else + { gl.bindTexture(gl.TEXTURE_2D, this.currentBaseTexture._glTextures[gl.id]); } // upload the verts to the buffer - if (this.currentBatchSize > ( this.size * 0.5 ) ) { + if (this.currentBatchSize > ( this.size * 0.5 ) ) + { gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); } - else { + else + { var view = this.vertices.subarray(0, this.currentBatchSize * this.vertByteSize); gl.bufferSubData(gl.ARRAY_BUFFER, 0, view); @@ -405,14 +428,16 @@ * Ends the batch and flushes * */ -WebGLFastSpriteBatch.prototype.stop = function () { +WebGLFastSpriteBatch.prototype.stop = function () +{ this.flush(); }; /** * */ -WebGLFastSpriteBatch.prototype.start = function () { +WebGLFastSpriteBatch.prototype.start = function () +{ var gl = this.renderer.gl; // bind the main texture diff --git a/src/core/renderers/webgl/utils/WebGLGraphics.js b/src/core/renderers/webgl/utils/WebGLGraphics.js index 55f4911..ab8f46e 100644 --- a/src/core/renderers/webgl/utils/WebGLGraphics.js +++ b/src/core/renderers/webgl/utils/WebGLGraphics.js @@ -19,7 +19,8 @@ * @param graphics {Graphics} * @param renderer {WebGLRenderer} */ -WebGLGraphics.renderGraphics = function (graphics, renderer) {//projection, offset) { +WebGLGraphics.renderGraphics = function (graphics, renderer) {//projection, offset) +{ var gl = renderer.gl; var projection = renderer.projection, @@ -27,7 +28,8 @@ shader = renderer.shaderManager.primitiveShader, webGLData; - if (graphics.dirty) { + if (graphics.dirty) + { WebGLGraphics.updateGraphics(graphics, gl); } @@ -35,8 +37,10 @@ // This could be speeded up for sure! - for (var i = 0; i < webGL.data.length; i++) { - if (webGL.data[i].mode === 1) { + for (var i = 0; i < webGL.data.length; i++) + { + if (webGL.data[i].mode === 1) + { webGLData = webGL.data[i]; renderer.stencilManager.pushStencil(graphics, webGLData, renderer); @@ -46,7 +50,8 @@ renderer.stencilManager.popStencil(graphics, webGLData, renderer); } - else { + else + { webGLData = webGL.data[i]; @@ -84,12 +89,14 @@ * @param graphicsData {Graphics} The graphics object to update * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLGraphics.updateGraphics = function (graphics, gl) { +WebGLGraphics.updateGraphics = function (graphics, gl) +{ // get the contexts graphics object var webGL = graphics._webGL[gl.id]; // if the graphics object does not exist in the webGL context time to create it! - if (!webGL) { + if (!webGL) + { webGL = graphics._webGL[gl.id] = {lastIndex:0, data:[], gl:gl}; } @@ -99,11 +106,13 @@ var i; // if the user cleared the graphics object we will need to clear every object - if (graphics.clearDirty) { + if (graphics.clearDirty) + { graphics.clearDirty = false; // lop through and return all the webGLDatas to the object pool so than can be reused later on - for (i = 0; i < webGL.data.length; i++) { + for (i = 0; i < webGL.data.length; i++) + { var graphicsData = webGL.data[i]; graphicsData.reset(); WebGLGraphics.graphicsDataPool.push( graphicsData ); @@ -119,58 +128,72 @@ // loop through the graphics datas and construct each one.. // if the object is a complex fill then the new stencil buffer technique will be used // other wise graphics objects will be pushed into a batch.. - for (i = webGL.lastIndex; i < graphics.graphicsData.length; i++) { + for (i = webGL.lastIndex; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { // need to add the points the the graphics object.. data.points = data.shape.points.slice(); - if (data.shape.closed) { + if (data.shape.closed) + { // close the poly if the value is true! - if (data.points[0] !== data.points[data.points.length-2] || data.points[1] !== data.points[data.points.length-1]) { + if (data.points[0] !== data.points[data.points.length-2] || data.points[1] !== data.points[data.points.length-1]) + { data.points.push(data.points[0], data.points[1]); } } // MAKE SURE WE HAVE THE CORRECT TYPE.. - if (data.fill) { - if (data.points.length >= 6) { - if (data.points.length < 6 * 2) { + if (data.fill) + { + if (data.points.length >= 6) + { + if (data.points.length < 6 * 2) + { webGLData = WebGLGraphics.switchMode(webGL, 0); var canDrawUsingSimple = WebGLGraphics.buildPoly(data, webGLData); // console.log(canDrawUsingSimple); - if (!canDrawUsingSimple) { + if (!canDrawUsingSimple) + { // console.log("<>>>") webGLData = WebGLGraphics.switchMode(webGL, 1); WebGLGraphics.buildComplexPoly(data, webGLData); } } - else { + else + { webGLData = WebGLGraphics.switchMode(webGL, 1); WebGLGraphics.buildComplexPoly(data, webGLData); } } } - if (data.lineWidth > 0) { + if (data.lineWidth > 0) + { webGLData = WebGLGraphics.switchMode(webGL, 0); WebGLGraphics.buildLine(data, webGLData); } } - else { + else + { webGLData = WebGLGraphics.switchMode(webGL, 0); - if (data.type === CONST.SHAPES.RECT) { + if (data.type === CONST.SHAPES.RECT) + { WebGLGraphics.buildRectangle(data, webGLData); } - else if (data.type === CONST.SHAPES.CIRC || data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.CIRC || data.type === CONST.SHAPES.ELIP) + { WebGLGraphics.buildCircle(data, webGLData); } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { WebGLGraphics.buildRoundedRectangle(data, webGLData); } } @@ -179,10 +202,12 @@ } // upload all the dirty data... - for (i = 0; i < webGL.data.length; i++) { + for (i = 0; i < webGL.data.length; i++) + { webGLData = webGL.data[i]; - if (webGLData.dirty) { + if (webGLData.dirty) + { webGLData.upload(); } } @@ -194,18 +219,22 @@ * @param webGL {WebGLContext} * @param type {number} */ -WebGLGraphics.switchMode = function (webGL, type) { +WebGLGraphics.switchMode = function (webGL, type) +{ var webGLData; - if (!webGL.data.length) { + if (!webGL.data.length) + { webGLData = WebGLGraphics.graphicsDataPool.pop() || new WebGLGraphicsData(webGL.gl); webGLData.mode = type; webGL.data.push(webGLData); } - else { + else + { webGLData = webGL.data[webGL.data.length-1]; - if (webGLData.mode !== type || type === 1) { + if (webGLData.mode !== type || type === 1) + { webGLData = WebGLGraphics.graphicsDataPool.pop() || new WebGLGraphicsData(webGL.gl); webGLData.mode = type; webGL.data.push(webGLData); @@ -225,7 +254,8 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildRectangle = function (graphicsData, webGLData) { +WebGLGraphics.buildRectangle = function (graphicsData, webGLData) +{ // --- // // need to convert points to a nice regular data // @@ -235,7 +265,8 @@ var width = rectData.width; var height = rectData.height; - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -265,7 +296,8 @@ indices.push(vertPos, vertPos, vertPos+1, vertPos+2, vertPos+3, vertPos+3); } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = [x, y, @@ -289,7 +321,8 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildRoundedRectangle = function (graphicsData, webGLData) { +WebGLGraphics.buildRoundedRectangle = function (graphicsData, webGLData) +{ var rrectData = graphicsData.shape; var x = rrectData.x; var y = rrectData.y; @@ -305,7 +338,8 @@ recPoints = recPoints.concat(WebGLGraphics.quadraticBezierCurve(x + width, y + radius, x + width, y, x + width - radius, y)); recPoints = recPoints.concat(WebGLGraphics.quadraticBezierCurve(x + radius, y, x, y, x, y + radius)); - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -323,7 +357,8 @@ // var i = 0; - for (i = 0; i < triangles.length; i+=3) { + for (i = 0; i < triangles.length; i+=3) + { indices.push(triangles[i] + vecPos); indices.push(triangles[i] + vecPos); indices.push(triangles[i+1] + vecPos); @@ -332,12 +367,14 @@ } - for (i = 0; i < recPoints.length; i++) { + for (i = 0; i < recPoints.length; i++) + { verts.push(recPoints[i], recPoints[++i], r, g, b, alpha); } } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = recPoints; @@ -362,7 +399,8 @@ * @param toY {number} Destination point y * @return {number[]} */ -WebGLGraphics.quadraticBezierCurve = function (fromX, fromY, cpX, cpY, toX, toY) { +WebGLGraphics.quadraticBezierCurve = function (fromX, fromY, cpX, cpY, toX, toY) +{ var xa, ya, @@ -373,14 +411,16 @@ n = 20, points = []; - function getPt(n1 , n2, perc) { + function getPt(n1 , n2, perc) + { var diff = n2 - n1; return n1 + ( diff * perc ); } var j = 0; - for (var i = 0; i <= n; i++ ) { + for (var i = 0; i <= n; i++ ) + { j = i / n; // The Green Line @@ -406,7 +446,8 @@ * @param graphicsData {Graphics} The graphics object to draw * @param webGLData {object} */ -WebGLGraphics.buildCircle = function (graphicsData, webGLData) { +WebGLGraphics.buildCircle = function (graphicsData, webGLData) +{ // need to convert points to a nice regular data var circleData = graphicsData.shape; var x = circleData.x; @@ -415,11 +456,13 @@ var height; // TODO - bit hacky?? - if (graphicsData.type === CONST.SHAPES.CIRC) { + if (graphicsData.type === CONST.SHAPES.CIRC) + { width = circleData.radius; height = circleData.radius; } - else { + else + { width = circleData.width; height = circleData.height; } @@ -429,7 +472,8 @@ var i = 0; - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -444,7 +488,8 @@ indices.push(vecPos); - for (i = 0; i < totalSegs + 1 ; i++) { + for (i = 0; i < totalSegs + 1 ; i++) + { verts.push(x,y, r, g, b, alpha); verts.push(x + Math.sin(seg * i) * width, @@ -457,12 +502,14 @@ indices.push(vecPos-1); } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = []; - for (i = 0; i < totalSegs + 1; i++) { + for (i = 0; i < totalSegs + 1; i++) + { graphicsData.points.push(x + Math.sin(seg * i) * width, y + Math.cos(seg * i) * height); } @@ -481,18 +528,22 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildLine = function (graphicsData, webGLData) { +WebGLGraphics.buildLine = function (graphicsData, webGLData) +{ // TODO OPTIMISE! var i = 0; var points = graphicsData.points; - if (points.length === 0) { + if (points.length === 0) + { return; } // if the line width is an odd number add 0.5 to align to a whole pixel - if (graphicsData.lineWidth%2) { - for (i = 0; i < points.length; i++) { + if (graphicsData.lineWidth%2) + { + for (i = 0; i < points.length; i++) + { points[i] += 0.5; } } @@ -502,7 +553,8 @@ var lastPoint = new math.Point(points[points.length - 2], points[points.length - 1]); // if the first point is the last point - gonna have issues :) - if (firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) { + if (firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) + { // need to clone as we are going to slightly modify the shape.. points = points.slice(); @@ -562,7 +614,8 @@ verts.push(p1x + perpx , p1y + perpy, r, g, b, alpha); - for (i = 1; i < length-1; i++) { + for (i = 1; i < length-1; i++) + { p1x = points[(i-1)*2]; p1y = points[(i-1)*2 + 1]; @@ -599,7 +652,8 @@ denom = a1*b2 - a2*b1; - if (Math.abs(denom) < 0.1 ) { + if (Math.abs(denom) < 0.1 ) + { denom+=10.1; verts.push(p2x - perpx , p2y - perpy, @@ -618,7 +672,8 @@ pdist = (px -p2x) * (px -p2x) + (py -p2y) + (py -p2y); - if (pdist > 140 * 140) { + if (pdist > 140 * 140) + { perp3x = perpx - perp2x; perp3y = perpy - perp2y; @@ -639,7 +694,8 @@ indexCount++; } - else { + else + { verts.push(px , py); verts.push(r, g, b, alpha); @@ -672,7 +728,8 @@ indices.push(indexStart); - for (i = 0; i < indexCount; i++) { + for (i = 0; i < indexCount; i++) + { indices.push(indexStart++); } @@ -687,11 +744,13 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildComplexPoly = function (graphicsData, webGLData) { +WebGLGraphics.buildComplexPoly = function (graphicsData, webGLData) +{ //TODO - no need to copy this as it gets turned into a FLoat32Array anyways.. var points = graphicsData.points.slice(); - if (points.length < 6) { + if (points.length < 6) + { return; } @@ -711,7 +770,8 @@ var x,y; // get size.. - for (var i = 0; i < points.length; i+=2) { + for (var i = 0; i < points.length; i+=2) + { x = points[i]; y = points[i+1]; @@ -732,7 +792,8 @@ //TODO - this aint needed! var length = points.length / 2; - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { indices.push( i ); } @@ -746,10 +807,12 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildPoly = function (graphicsData, webGLData) { +WebGLGraphics.buildPoly = function (graphicsData, webGLData) +{ var points = graphicsData.points; - if (points.length < 6) { + if (points.length < 6) + { return; } // get first and last point.. figure out the middle! @@ -767,7 +830,8 @@ var triangles = utils.PolyK.Triangulate(points); - if (!triangles) { + if (!triangles) + { return false; } @@ -775,7 +839,8 @@ var i = 0; - for (i = 0; i < triangles.length; i+=3) { + for (i = 0; i < triangles.length; i+=3) + { indices.push(triangles[i] + vertPos); indices.push(triangles[i] + vertPos); indices.push(triangles[i+1] + vertPos); @@ -783,7 +848,8 @@ indices.push(triangles[i+2] + vertPos); } - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { verts.push(points[i * 2], points[i * 2 + 1], r, g, b, alpha); } diff --git a/src/core/renderers/webgl/utils/WebGLGraphicsData.js b/src/core/renderers/webgl/utils/WebGLGraphicsData.js index c56d05e..c739ba7 100644 --- a/src/core/renderers/webgl/utils/WebGLGraphicsData.js +++ b/src/core/renderers/webgl/utils/WebGLGraphicsData.js @@ -2,7 +2,8 @@ * @class * @private */ -function WebGLGraphicsData(gl) { +function WebGLGraphicsData(gl) +{ this.gl = gl; //TODO does this need to be split before uploding?? @@ -22,7 +23,8 @@ /** * */ -WebGLGraphicsData.prototype.reset = function () { +WebGLGraphicsData.prototype.reset = function () +{ this.points.length = 0; this.indices.length = 0; }; @@ -30,7 +32,8 @@ /** * */ -WebGLGraphicsData.prototype.upload = function () { +WebGLGraphicsData.prototype.upload = function () +{ var gl = this.gl; // this.lastIndex = graphics.graphicsData.length; diff --git a/src/core/renderers/webgl/utils/WebGLSpriteBatch.js b/src/core/renderers/webgl/utils/WebGLSpriteBatch.js index 96eaa52..55befbb 100644 --- a/src/core/renderers/webgl/utils/WebGLSpriteBatch.js +++ b/src/core/renderers/webgl/utils/WebGLSpriteBatch.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this sprite batch works for. */ -function WebGLSpriteBatch(renderer) { +function WebGLSpriteBatch(renderer) +{ /** * * @@ -88,7 +89,8 @@ */ this.lastIndexCount = 0; - for (var i=0, j=0; i < numIndices; i += 6, j += 4) { + 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; @@ -162,7 +164,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.setupContext(); }); } @@ -173,7 +176,8 @@ /** * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLSpriteBatch.prototype.setupContext = function () { +WebGLSpriteBatch.prototype.setupContext = function () +{ var gl = this.renderer.gl; // setup default shader @@ -198,7 +202,8 @@ /** * */ -WebGLSpriteBatch.prototype.begin = function () { +WebGLSpriteBatch.prototype.begin = function () +{ // this.shader = this.renderer.shaderManager.defaultShader; this.start(); @@ -206,19 +211,22 @@ /** */ -WebGLSpriteBatch.prototype.end = function () { +WebGLSpriteBatch.prototype.end = function () +{ this.flush(); }; /** * @param sprite {Sprite} the sprite to render when using this spritebatch */ -WebGLSpriteBatch.prototype.render = function (sprite) { +WebGLSpriteBatch.prototype.render = function (sprite) +{ var texture = sprite.texture; //TODO set blend modes.. // check texture.. - if (this.currentBatchSize >= this.size) { + if (this.currentBatchSize >= this.size) + { this.flush(); this.currentBaseTexture = texture.baseTexture; } @@ -227,7 +235,8 @@ var uvs = texture._uvs; // if the uvs have not updated then no point rendering just yet! - if (!uvs) { + if (!uvs) + { return; } @@ -237,7 +246,8 @@ var w0, w1, h0, h1; - if (texture.trim) { + 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; @@ -248,7 +258,8 @@ h0 = h1 + texture.crop.height; } - else { + else + { w0 = (texture.frame.width ) * (1-aX); w1 = (texture.frame.width ) * -aX; @@ -272,7 +283,8 @@ var colors = this.colors; var positions = this.positions; - if (this.renderer.roundPixels) { + if (this.renderer.roundPixels) + { // xy positions[index] = a * w1 + c * h1 + tx | 0; positions[index+1] = d * h1 + b * w1 + ty | 0; @@ -289,7 +301,8 @@ positions[index+15] = a * w1 + c * h0 + tx | 0; positions[index+16] = d * h0 + b * w1 + ty | 0; } - else { + else + { // xy positions[index] = a * w1 + c * h1 + tx; positions[index+1] = d * h1 + b * w1 + ty; @@ -338,11 +351,13 @@ * * @param sprite {TilingSprite} the tilingSprite to render */ -WebGLSpriteBatch.prototype.renderTilingSprite = function (tilingSprite) { +WebGLSpriteBatch.prototype.renderTilingSprite = function (tilingSprite) +{ var texture = tilingSprite.tilingTexture; // check texture.. - if (this.currentBatchSize >= this.size) { + if (this.currentBatchSize >= this.size) + { //return; this.flush(); this.currentBaseTexture = texture.baseTexture; @@ -351,7 +366,8 @@ // set the textures uvs temporarily // TODO create a separate texture so that we can tile part of a texture - if (!tilingSprite._uvs) { + if (!tilingSprite._uvs) + { tilingSprite._uvs = new TextureUvs(); } @@ -454,16 +470,19 @@ * Renders the content and empties the current batch. * */ -WebGLSpriteBatch.prototype.flush = function () { +WebGLSpriteBatch.prototype.flush = function () +{ // If the batch is length 0 then return as there is nothing to draw - if (this.currentBatchSize === 0) { + if (this.currentBatchSize === 0) + { return; } var gl = this.renderer.gl; var shader; - if (this.dirty) { + if (this.dirty) + { this.dirty = false; // bind the main texture gl.activeTexture(gl.TEXTURE0); @@ -482,10 +501,12 @@ } // upload the verts to the buffer - if (this.currentBatchSize > ( this.size * 0.5 ) ) { + if (this.currentBatchSize > ( this.size * 0.5 ) ) + { gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); } - else { + else + { var view = this.positions.subarray(0, this.currentBatchSize * this.vertByteSize); gl.bufferSubData(gl.ARRAY_BUFFER, 0, view); } @@ -502,7 +523,8 @@ var shaderSwap = false; var sprite; - for (var i = 0, j = this.currentBatchSize; i < j; i++) { + for (var i = 0, j = this.currentBatchSize; i < j; i++) + { sprite = this.sprites[i]; @@ -513,24 +535,28 @@ blendSwap = currentBlendMode !== nextBlendMode; shaderSwap = currentShader !== nextShader; // should I use uuidS??? - if (currentBaseTexture !== nextTexture || blendSwap || shaderSwap) { + if (currentBaseTexture !== nextTexture || blendSwap || shaderSwap) + { this.renderBatch(currentBaseTexture, batchSize, start); start = i; batchSize = 0; currentBaseTexture = nextTexture; - if (blendSwap) { + if (blendSwap) + { currentBlendMode = nextBlendMode; this.renderer.blendModeManager.setBlendMode( currentBlendMode ); } - if (shaderSwap) { + if (shaderSwap) + { currentShader = nextShader; shader = currentShader.shaders ? currentShader.shaders[gl.id] : currentShader; - if (!shader) { + if (!shader) + { shader = new Shader(gl, null, currentShader.fragmentSrc, currentShader.uniforms); currentShader.shaders[gl.id] = shader; } @@ -538,7 +564,8 @@ // set shader function??? this.renderer.shaderManager.setShader(shader); - if (shader.dirty) { + if (shader.dirty) + { shader.syncUniforms(); } @@ -569,17 +596,21 @@ * @param size {number} * @param startIndex {number} */ -WebGLSpriteBatch.prototype.renderBatch = function (texture, size, startIndex) { - if (size === 0) { +WebGLSpriteBatch.prototype.renderBatch = function (texture, size, startIndex) +{ + if (size === 0) + { return; } var gl = this.renderer.gl; - if (!texture._glTextures[gl.id]) { + if (!texture._glTextures[gl.id]) + { this.renderer.updateTexture(texture); } - else { + else + { // bind the current texture gl.bindTexture(gl.TEXTURE_2D, texture._glTextures[gl.id]); } @@ -594,7 +625,8 @@ /** * */ -WebGLSpriteBatch.prototype.stop = function () { +WebGLSpriteBatch.prototype.stop = function () +{ this.flush(); this.dirty = true; }; @@ -602,7 +634,8 @@ /** * */ -WebGLSpriteBatch.prototype.start = function () { +WebGLSpriteBatch.prototype.start = function () +{ this.dirty = true; }; @@ -610,7 +643,8 @@ * Destroys the SpriteBatch. * */ -WebGLSpriteBatch.prototype.destroy = function () { +WebGLSpriteBatch.prototype.destroy = function () +{ this.renderer.gl.deleteBuffer(this.vertexBuffer); this.renderer.gl.deleteBuffer(this.indexBuffer); diff --git a/src/core/textures/BaseTexture.js b/src/core/textures/BaseTexture.js index 2bf77d4..513d358 100644 --- a/src/core/textures/BaseTexture.js +++ b/src/core/textures/BaseTexture.js @@ -10,7 +10,8 @@ * @param source {Image|Canvas} the source object of the texture. * @param [scaleMode=scaleModes.DEFAULT] {number} See {@link scaleModes} for possible values */ -function BaseTexture(source, scaleMode) { +function BaseTexture(source, scaleMode) +{ this.uuid = utils.uuid(); /** @@ -123,7 +124,8 @@ this._needsUpdate = false; // if no source passed don't try to load - if (source) { + if (source) + { this.loadSource(source); } @@ -149,13 +151,16 @@ Object.defineProperties(BaseTexture.prototype, { needsUpdate: { - get: function () { + get: function () + { return this._needsUpdate; }, - set: function (val) { + set: function (val) + { this._needsUpdate = val; - if (val) { + if (val) + { this.emit('update', this); } } @@ -171,9 +176,11 @@ * * The logic state after calling `loadSource` directly or indirectly (eg. `fromImage`, `new BaseTexture`) is: * - * if (texture.hasLoaded) { + * if (texture.hasLoaded) + { * // texture ready for use - * } else if (texture.isLoading) { + * } else if (texture.isLoading) + { * // listen to 'loaded' and/or 'error' events on texture * } else { * // not loading, not going to load UNLESS the source is reloaded @@ -183,12 +190,14 @@ * @protected * @param source {Image|Canvas} the source object of the texture. */ -BaseTexture.prototype.loadSource = function (source) { +BaseTexture.prototype.loadSource = function (source) +{ var wasLoading = this.isLoading; this.hasLoaded = false; this.isLoading = false; - if (wasLoading && this.source) { + if (wasLoading && this.source) + { this.source.onload = null; this.source.onerror = null; } @@ -196,20 +205,24 @@ this.source = source; // Apply source if loaded. Otherwise setup appropriate loading monitors. - if ((this.source.complete || this.source.getContext) && this.source.width && this.source.height) { + if ((this.source.complete || this.source.getContext) && this.source.width && this.source.height) + { this._sourceLoaded(); } - else if(!source.getContext) { + else if(!source.getContext) + { // Image fail / not ready this.isLoading = true; var scope = this; - source.onload = function () { + source.onload = function () + { source.onload = null; source.onerror = null; - if(!scope.isLoading) { + if(!scope.isLoading) + { return; } @@ -219,11 +232,13 @@ scope.emit('loaded', scope); }; - source.onerror = function () { + source.onerror = function () + { source.onload = null; source.onerror = null; - if(!scope.isLoading) { + if(!scope.isLoading) + { return; } @@ -234,24 +249,29 @@ // Per http://www.w3.org/TR/html5/embedded-content-0.html#the-img-element // "The value of `complete` can thus change while a script is executing." // So complete needs to be re-checked after the callbacks have been added.. - if (source.complete) { + if (source.complete) + { this.isLoading = false; // ..and if we're complete now, no need for callbacks source.onload = null; source.onerror = null; - if (source.width && source.height) { + if (source.width && source.height) + { this._sourceLoaded(); // If any previous subscribers possible - if (wasLoading) { + if (wasLoading) + { this.emit('loaded', this); } } - else { + else + { // If any previous subscribers possible - if (wasLoading) { + if (wasLoading) + { this.emit('error', this); } } @@ -265,7 +285,8 @@ * * @private */ -BaseTexture.prototype._sourceLoaded = function () { +BaseTexture.prototype._sourceLoaded = function () +{ this.hasLoaded = true; this.width = this.source.naturalWidth || this.source.width; @@ -278,16 +299,20 @@ * Destroys this base texture * */ -BaseTexture.prototype.destroy = function () { - if (this.imageUrl) { +BaseTexture.prototype.destroy = function () +{ + if (this.imageUrl) + { delete utils.BaseTextureCache[this.imageUrl]; delete utils.TextureCache[this.imageUrl]; this.imageUrl = null; - if (!navigator.isCocoonJS) { + if (!navigator.isCocoonJS) + { this.source.src = ''; } } - else if (this.source && this.source._pixiId) { + else if (this.source && this.source._pixiId) + { delete utils.BaseTextureCache[this.source._pixiId]; } this.source = null; @@ -301,7 +326,8 @@ * memory again. * */ -BaseTexture.prototype.dispose = function () { +BaseTexture.prototype.dispose = function () +{ this.emit('dispose', this); }; @@ -311,7 +337,8 @@ * * @param newSrc {string} the path of the image */ -BaseTexture.prototype.updateSourceImage = function (newSrc) { +BaseTexture.prototype.updateSourceImage = function (newSrc) +{ this.source.src = newSrc; this.loadSource(this.source); }; @@ -326,18 +353,22 @@ * @param [scaleMode=scaleModes.DEFAULT] {number} See {@link scaleModes} for possible values * @return BaseTexture */ -BaseTexture.fromImage = function (imageUrl, crossorigin, scaleMode) { +BaseTexture.fromImage = function (imageUrl, crossorigin, scaleMode) +{ var baseTexture = utils.BaseTextureCache[imageUrl]; - if (crossorigin === undefined && imageUrl.indexOf('data:') !== 0) { + if (crossorigin === undefined && imageUrl.indexOf('data:') !== 0) + { crossorigin = true; } - if (!baseTexture) { + if (!baseTexture) + { // new Image() breaks tex loading in some versions of Chrome. // See https://code.google.com/p/chromium/issues/detail?id=238071 var image = new Image();//document.createElement('img'); - if (crossorigin) { + if (crossorigin) + { image.crossOrigin = ''; } @@ -347,7 +378,8 @@ utils.BaseTextureCache[imageUrl] = baseTexture; // if there is an @2x at the end of the url we are going to assume its a highres image - if ( imageUrl.indexOf(CONST.RETINA_PREFIX + '.') !== -1) { + if ( imageUrl.indexOf(CONST.RETINA_PREFIX + '.') !== -1) + { baseTexture.resolution = 2; } } @@ -363,14 +395,17 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return BaseTexture */ -BaseTexture.fromCanvas = function (canvas, scaleMode) { - if (!canvas._pixiId) { +BaseTexture.fromCanvas = function (canvas, scaleMode) +{ + if (!canvas._pixiId) + { canvas._pixiId = 'canvas_' + utils.uuid(); } var baseTexture = utils.BaseTextureCache[canvas._pixiId]; - if (!baseTexture) { + if (!baseTexture) + { baseTexture = new BaseTexture(canvas, scaleMode); utils.BaseTextureCache[canvas._pixiId] = baseTexture; } diff --git a/src/core/textures/RenderTexture.js b/src/core/textures/RenderTexture.js index 6dad20f..53ae796 100644 --- a/src/core/textures/RenderTexture.js +++ b/src/core/textures/RenderTexture.js @@ -46,8 +46,10 @@ * @param [scaleMode] {number} See {@link scaleModes} for possible values * @param [resolution=1] {number} The resolution of the texture being generated */ -function RenderTexture(renderer, width, height, scaleMode, resolution) { - if (!renderer) { +function RenderTexture(renderer, width, height, scaleMode, resolution) +{ + if (!renderer) + { throw new Error('Unable to create RenderTexture, you must pass a renderer into the constructor.'); } @@ -133,7 +135,8 @@ */ this.renderer = renderer; - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { var gl = this.renderer.gl; this.textureBuffer = new FilterTexture(gl, this.width * this.resolution, this.height * this.resolution, this.baseTexture.scaleMode); @@ -142,7 +145,8 @@ this.render = this.renderWebGL; this.projection = new math.Point(this.width*0.5, -this.height*0.5); } - else { + else + { this.render = this.renderCanvas; this.textureBuffer = new CanvasBuffer(this.width* this.resolution, this.height* this.resolution); this.baseTexture.source = this.textureBuffer.canvas; @@ -167,8 +171,10 @@ * @param height {number} The height to resize to. * @param updateBase {boolean} Should the baseTexture.width and height values be resized as well? */ -RenderTexture.prototype.resize = function (width, height, updateBase) { - if (width === this.width && height === this.height) { +RenderTexture.prototype.resize = function (width, height, updateBase) +{ + if (width === this.width && height === this.height) + { return; } @@ -177,17 +183,20 @@ this.width = this.frame.width = this.crop.width = width; this.height = this.frame.height = this.crop.height = height; - if (updateBase) { + if (updateBase) + { this.baseTexture.width = this.width; this.baseTexture.height = this.height; } - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { this.projection.x = this.width / 2; this.projection.y = -this.height / 2; } - if (!this.valid) { + if (!this.valid) + { return; } @@ -198,12 +207,15 @@ * Clears the RenderTexture. * */ -RenderTexture.prototype.clear = function () { - if (!this.valid) { +RenderTexture.prototype.clear = function () +{ + if (!this.valid) + { return; } - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { this.renderer.gl.bindFramebuffer(this.renderer.gl.FRAMEBUFFER, this.textureBuffer.frameBuffer); } @@ -220,19 +232,23 @@ * @param [restoreWorldTransform=true] {boolean} If true the displayObject's worldTransform/worldAlpha and all children * transformations will be restored. Not restoring this information will be a little faster. */ -RenderTexture.prototype.renderWebGL = function (displayObject, matrix, clear, restoreWorldTransform) { - if (!this.valid) { +RenderTexture.prototype.renderWebGL = function (displayObject, matrix, clear, restoreWorldTransform) +{ + if (!this.valid) + { return; } - if (typeof restoreWorldTransform === 'undefined') { + if (typeof restoreWorldTransform === 'undefined') + { restoreWorldTransform = true; } var tempAlpha, tempTransform; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { tempAlpha = displayObject.worldAlpha; tempTransform = displayObject.worldTransform.toArray(); } @@ -245,7 +261,8 @@ wt.identity(); wt.translate(0, this.projection.y * 2); - if (matrix) { + if (matrix) + { wt.append(matrix); } @@ -258,7 +275,8 @@ var children = displayObject.children; var i, j; - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } @@ -269,7 +287,8 @@ gl.bindFramebuffer(gl.FRAMEBUFFER, this.textureBuffer.frameBuffer ); - if (clear) { + if (clear) + { this.textureBuffer.clear(); } @@ -279,11 +298,13 @@ this.renderer.spriteBatch.dirty = true; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { displayObject.worldAlpha = tempAlpha; displayObject.worldTransform.fromArray(tempTransform); - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } } @@ -300,26 +321,31 @@ * @param [restoreWorldTransform=true] {boolean} If true the displayObject's worldTransform/worldAlpha and all children * transformations will be restored. Not restoring this information will be a little faster. */ -RenderTexture.prototype.renderCanvas = function (displayObject, matrix, clear, restoreWorldTransform) { - if (!this.valid) { +RenderTexture.prototype.renderCanvas = function (displayObject, matrix, clear, restoreWorldTransform) +{ + if (!this.valid) + { return; } - if (typeof restoreWorldTransform === 'undefined') { + if (typeof restoreWorldTransform === 'undefined') + { restoreWorldTransform = true; } var tempAlpha, tempTransform; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { tempAlpha = displayObject.worldAlpha; tempTransform = displayObject.worldTransform.toArray(); } var wt = displayObject.worldTransform; wt.identity(); - if (matrix) { + if (matrix) + { wt.append(matrix); } @@ -330,11 +356,13 @@ var children = displayObject.children; var i, j; - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } - if (clear) { + if (clear) + { this.textureBuffer.clear(); } @@ -348,11 +376,13 @@ this.renderer.resolution = realResolution; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { displayObject.worldAlpha = tempAlpha; displayObject.worldTransform.fromArray(tempTransform); - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } } @@ -363,7 +393,8 @@ * * @return {Image} */ -RenderTexture.prototype.getImage = function () { +RenderTexture.prototype.getImage = function () +{ var image = new Image(); image.src = this.getBase64(); return image; @@ -374,7 +405,8 @@ * * @return {string} A base64 encoded string of the texture. */ -RenderTexture.prototype.getBase64 = function () { +RenderTexture.prototype.getBase64 = function () +{ return this.getCanvas().toDataURL(); }; @@ -383,8 +415,10 @@ * * @return {HTMLCanvasElement} A Canvas element with the texture rendered on. */ -RenderTexture.prototype.getCanvas = function () { - if (this.renderer.type === CONST.WEBGL_RENDERER) { +RenderTexture.prototype.getCanvas = function () +{ + if (this.renderer.type === CONST.WEBGL_RENDERER) + { var gl = this.renderer.gl; var width = this.textureBuffer.width; var height = this.textureBuffer.height; @@ -403,7 +437,8 @@ return tempCanvas.canvas; } - else { + else + { return this.textureBuffer.canvas; } }; diff --git a/src/core/textures/Texture.js b/src/core/textures/Texture.js index 3c65909..e97f0aa 100644 --- a/src/core/textures/Texture.js +++ b/src/core/textures/Texture.js @@ -17,7 +17,8 @@ * @param [crop] {Rectangle} The area of original texture * @param [trim] {Rectangle} Trimmed texture rectangle */ -function Texture(baseTexture, frame, crop, trim) { +function Texture(baseTexture, frame, crop, trim) +{ /** * Does this Texture have any frame data assigned to it? * @@ -25,12 +26,14 @@ */ this.noFrame = false; - if (!frame) { + if (!frame) + { this.noFrame = true; frame = new math.Rectangle(0, 0, 1, 1); } - if (baseTexture instanceof Texture) { + if (baseTexture instanceof Texture) + { baseTexture = baseTexture.baseTexture; } @@ -100,13 +103,16 @@ */ this.crop = crop || new math.Rectangle(0, 0, 1, 1); - if (baseTexture.hasLoaded) { - if (this.noFrame) { + if (baseTexture.hasLoaded) + { + if (this.noFrame) + { frame = new math.Rectangle(0, 0, baseTexture.width, baseTexture.height); } this.frame = frame; } - else { + else + { baseTexture.addEventListener('loaded', this.onBaseTextureLoaded.bind(this)); } } @@ -118,19 +124,23 @@ Object.defineProperties(Texture.prototype, { needsUpdate: { - get: function () { + get: function () + { return this.baseTexture.needsUpdate; }, - set: function (val) { + set: function (val) + { this.baseTexture.needsUpdate = val; } }, frame: { - get: function () { + get: function () + { return this._frame; }, - set: function (frame) { + set: function (frame) + { this._frame = frame; this.noFrame = false; @@ -143,20 +153,23 @@ 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 (!this.trim && (frame.x + frame.width > this.baseTexture.width || frame.y + frame.height > this.baseTexture.height)) + { throw new Error('Texture Error: frame does not fit inside the base Texture dimensions ' + this); } this.valid = frame && frame.width && frame.height && this.baseTexture.source && this.baseTexture.hasLoaded; - if (this.trim) { + 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) { + if (this.valid) + { this._updateUvs(); } } @@ -168,11 +181,13 @@ * * @private */ -Texture.prototype.onBaseTextureLoaded = function () { +Texture.prototype.onBaseTextureLoaded = function () +{ var baseTexture = this.baseTexture; baseTexture.removeEventListener('loaded', this.onLoaded); - if (this.noFrame) { + if (this.noFrame) + { this.frame = new math.Rectangle(0, 0, baseTexture.width, baseTexture.height); } @@ -184,8 +199,10 @@ * * @param destroyBase {boolean} Whether to destroy the base texture as well */ -Texture.prototype.destroy = function (destroyBase) { - if (destroyBase) { +Texture.prototype.destroy = function (destroyBase) +{ + if (destroyBase) + { this.baseTexture.destroy(); } @@ -197,8 +214,10 @@ * * @private */ -Texture.prototype._updateUvs = function () { - if (!this._uvs) { +Texture.prototype._updateUvs = function () +{ + if (!this._uvs) + { this._uvs = new TextureUvs(); } @@ -229,10 +248,12 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return Texture */ -Texture.fromImage = function (imageUrl, crossorigin, scaleMode) { +Texture.fromImage = function (imageUrl, crossorigin, scaleMode) +{ var texture = utils.TextureCache[imageUrl]; - if (!texture) { + if (!texture) + { texture = new Texture(BaseTexture.fromImage(imageUrl, crossorigin, scaleMode)); utils.TextureCache[imageUrl] = texture; } @@ -248,9 +269,11 @@ * @param frameId {string} The frame id of the texture * @return Texture */ -Texture.fromFrame = function (frameId) { +Texture.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache '); } return texture; @@ -264,7 +287,8 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return {Texture} */ -Texture.fromCanvas = function (canvas, scaleMode) { +Texture.fromCanvas = function (canvas, scaleMode) +{ return new Texture(BaseTexture.fromCanvas(canvas, scaleMode)); }; @@ -276,7 +300,8 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return {Texture} A Texture */ -Texture.fromVideo = function (video, scaleMode) { +Texture.fromVideo = function (video, scaleMode) +{ return new Texture(VideoBaseTexture.baseTextureFromVideo(video, scaleMode)); }; @@ -287,7 +312,8 @@ * @param texture {Texture} The Texture to add to the cache. * @param id {string} The id that the texture will be stored against. */ -Texture.addTextureToCache = function (texture, id) { +Texture.addTextureToCache = function (texture, id) +{ utils.TextureCache[id] = texture; }; @@ -298,7 +324,8 @@ * @param id {string} The id of the texture to be removed * @return {Texture} The texture that was removed */ -Texture.removeTextureFromCache = function (id) { +Texture.removeTextureFromCache = function (id) +{ var texture = utils.TextureCache[id]; delete utils.TextureCache[id]; diff --git a/src/core/textures/TextureUvs.js b/src/core/textures/TextureUvs.js index b9bbb58..5424d52 100644 --- a/src/core/textures/TextureUvs.js +++ b/src/core/textures/TextureUvs.js @@ -1,4 +1,5 @@ -function TextureUvs() { +function TextureUvs() +{ this.x0 = 0; this.y0 = 0; diff --git a/src/core/textures/VideoBaseTexture.js b/src/core/textures/VideoBaseTexture.js index e3e0c5a..1a826a9 100644 --- a/src/core/textures/VideoBaseTexture.js +++ b/src/core/textures/VideoBaseTexture.js @@ -12,15 +12,18 @@ * @param source {HTMLVideoElement} * @param [scaleMode] {number} See {@link scaleModes} for possible values */ -function VideoBaseTexture(source, scaleMode) { - if (!source){ +function VideoBaseTexture(source, scaleMode) +{ + if (!source) + { throw new Error('No video source element specified.'); } // hook in here to check if video is already available. // BaseTexture looks for a source.complete boolean, plus width & height. - if ((source.readyState === source.HAVE_ENOUGH_DATA || source.readyState === source.HAVE_FUTURE_DATA) && source.width && source.height) { + if ((source.readyState === source.HAVE_ENOUGH_DATA || source.readyState === source.HAVE_FUTURE_DATA) && source.width && source.height) + { source.complete = true; } @@ -31,7 +34,8 @@ this._boundOnUpdate = this._onUpdate.bind(this); this._boundOnCanPlay = this._onCanPlay.bind(this); - if (!source.complete) { + if (!source.complete) + { source.addEventListener('canplay', this._boundOnCanPlay); source.addEventListener('canplaythrough', this._boundOnCanPlay); @@ -47,28 +51,35 @@ VideoBaseTexture.prototype.constructor = VideoBaseTexture; module.exports = VideoBaseTexture; -VideoBaseTexture.prototype._onUpdate = function () { - if (this.autoUpdate) { +VideoBaseTexture.prototype._onUpdate = function () +{ + if (this.autoUpdate) + { window.requestAnimationFrame(this._boundOnUpdate); this.needsUpdate = true; } }; -VideoBaseTexture.prototype._onPlayStart = function () { - if (!this.autoUpdate) { +VideoBaseTexture.prototype._onPlayStart = function () +{ + if (!this.autoUpdate) + { window.requestAnimationFrame(this._boundOnUpdate); this.autoUpdate = true; } }; -VideoBaseTexture.prototype._onPlayStop = function () { +VideoBaseTexture.prototype._onPlayStop = function () +{ this.autoUpdate = false; }; -VideoBaseTexture.prototype._onCanPlay = function () { +VideoBaseTexture.prototype._onCanPlay = function () +{ this.hasLoaded = true; - if (this.source) { + if (this.source) + { this.source.removeEventListener('canplay', this._boundOnCanPlay); this.source.removeEventListener('canplaythrough', this._boundOnCanPlay); @@ -78,15 +89,18 @@ this.source.play(); // prevent multiple loaded dispatches.. - if(!this.__loaded){ + if(!this.__loaded) + { this.__loaded = true; this.emit('loaded', this); } } }; -VideoBaseTexture.prototype.destroy = function () { - if (this.source && this.source._pixiId) { +VideoBaseTexture.prototype.destroy = function () +{ + if (this.source && this.source._pixiId) + { utils.BaseTextureCache[ this.source._pixiId ] = null; delete utils.BaseTextureCache[ this.source._pixiId ]; @@ -105,14 +119,17 @@ * @param scaleMode {number} See {@link scaleModes} for possible values * @return {VideoBaseTexture} */ -VideoBaseTexture.fromVideo = function (video, scaleMode) { - if (!video._pixiId) { +VideoBaseTexture.fromVideo = function (video, scaleMode) +{ + if (!video._pixiId) + { video._pixiId = 'video_' + utils.uuid(); } var baseTexture = utils.BaseTextureCache[video._pixiId]; - if (!baseTexture) { + if (!baseTexture) + { baseTexture = new VideoBaseTexture(video, scaleMode); utils.BaseTextureCache[ video._pixiId ] = baseTexture; } @@ -147,17 +164,21 @@ * @param scaleMode {number} See {@link scaleModes} for possible values * @return {VideoBaseTexture} */ -VideoBaseTexture.fromUrl = function (videoSrc, scaleMode) { +VideoBaseTexture.fromUrl = function (videoSrc, scaleMode) +{ var video = document.createElement('video'); // array of objects or strings - if (Array.isArray(videoSrc)) { - for (var i = 0; i < videoSrc.length; ++i) { + if (Array.isArray(videoSrc)) + { + for (var i = 0; i < videoSrc.length; ++i) + { video.appendChild(createSource(videoSrc.src || videoSrc, videoSrc.mime)); } } // single object or string - else { + else + { video.appendChild(createSource(videoSrc.src || videoSrc, videoSrc.mime)); } @@ -169,8 +190,10 @@ VideoBaseTexture.fromUrls = VideoBaseTexture.fromUrl; -function createSource(path, type) { - if (!type) { +function createSource(path, type) +{ + if (!type) + { type = 'video/' + path.substr(path.lastIndexOf('.') + 1); } diff --git a/src/core/utils/EventData.js b/src/core/utils/EventData.js index 5d55a22..8cdf701 100644 --- a/src/core/utils/EventData.js +++ b/src/core/utils/EventData.js @@ -7,7 +7,8 @@ * @param name {string} The string name of the event that was triggered * @param data {object} Arbitrary event data to pass along */ -function EventData(target, name, data) { +function EventData(target, name, data) +{ // for duck typing in the ".on()" function this.__isEventObject = true; @@ -71,7 +72,8 @@ * Stops the propagation of events up the scene graph (prevents bubbling). * */ -EventData.prototype.stopPropagation = function stopPropagation() { +EventData.prototype.stopPropagation = function stopPropagation() +{ this.stopped = true; }; @@ -79,6 +81,7 @@ * Stops the propagation of events to sibling listeners (no longer calls any listeners). * */ -EventData.prototype.stopImmediatePropagation = function stopImmediatePropagation() { +EventData.prototype.stopImmediatePropagation = function stopImmediatePropagation() +{ this.stoppedImmediate = true; }; diff --git a/src/core/utils/EventTarget.js b/src/core/utils/EventTarget.js index 7ae8820..671a151 100644 --- a/src/core/utils/EventTarget.js +++ b/src/core/utils/EventTarget.js @@ -13,14 +13,16 @@ * var em = new MyEmitter(); * em.emit('eventName', 'some data', 'some more data', {}, null, ...); */ -function eventTarget(obj) { +function eventTarget(obj) +{ /** * Return a list of assigned event listeners. * * @param eventName {string} The events that should be listed. * @return {Array} An array of listener functions */ - obj.listeners = function listeners(eventName) { + obj.listeners = function listeners(eventName) + { this._listeners = this._listeners || {}; return this._listeners[eventName] ? this._listeners[eventName].slice() : []; @@ -33,22 +35,26 @@ * @param eventName {string} The name of the event. * @return {boolean} Indication if we've emitted an event. */ - obj.emit = obj.dispatchEvent = function emit(eventName, data) { + obj.emit = obj.dispatchEvent = function emit(eventName, data) + { this._listeners = this._listeners || {}; // fast return when there are no listeners - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return; } //backwards compat with old method ".emit({ type: 'something' })" - if (typeof eventName === 'object') { + if (typeof eventName === 'object') + { data = eventName; eventName = eventName.type; } //ensure we are using a real pixi event - if (!data || data.__isEventObject !== true) { + if (!data || data.__isEventObject !== true) + { data = new EventData(this, eventName, data); } @@ -58,23 +64,27 @@ fn = listeners[0], i; - for (i = 0; i < length; fn = listeners[++i]) { + for (i = 0; i < length; fn = listeners[++i]) + { //call the event listener fn.call(this, data); //if "stopImmediatePropagation" is called, stop calling sibling events - if (data.stoppedImmediate) { + if (data.stoppedImmediate) + { return this; } } //if "stopPropagation" is called then don't bubble the event - if (data.stopped) { + if (data.stopped) + { return this; } //bubble this event up the scene graph - if (this.parent && this.parent.emit) { + if (this.parent && this.parent.emit) + { this.parent.emit.call(this.parent, eventName, data); } @@ -88,7 +98,8 @@ * @param eventName {string} Name of the event. * @param callback {Functon} fn Callback function. */ - obj.on = obj.addEventListener = function on(eventName, fn) { + obj.on = obj.addEventListener = function on(eventName, fn) + { this._listeners = this._listeners || {}; (this._listeners[eventName] = this._listeners[eventName] || []) @@ -103,11 +114,13 @@ * @param eventName {string} Name of the event. * @param callback {Function} Callback function. */ - obj.once = function once(eventName, fn) { + obj.once = function once(eventName, fn) + { this._listeners = this._listeners || {}; var self = this; - function onceHandlerWrapper() { + function onceHandlerWrapper() + { fn.apply(self.off(eventName, onceHandlerWrapper), arguments); } onceHandlerWrapper._originalHandler = fn; @@ -122,23 +135,28 @@ * @param eventName {string} The event we want to remove. * @param callback {Function} The listener that we need to find. */ - obj.off = obj.removeEventListener = function off(eventName, fn) { + obj.off = obj.removeEventListener = function off(eventName, fn) + { this._listeners = this._listeners || {}; - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return this; } var list = this._listeners[eventName], i = fn ? list.length : 0; - while(i-- > 0) { - if (list[i] === fn || list[i]._originalHandler === fn) { + while(i-- > 0) + { + if (list[i] === fn || list[i]._originalHandler === fn) + { list.splice(i, 1); } } - if (list.length === 0) { + if (list.length === 0) + { delete this._listeners[eventName]; } @@ -150,10 +168,12 @@ * * @param eventName {string} The event you want to remove all listeners for. */ - obj.removeAllListeners = function removeAllListeners(eventName) { + obj.removeAllListeners = function removeAllListeners(eventName) + { this._listeners = this._listeners || {}; - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return this; } @@ -169,7 +189,8 @@ * * @param object {object} The obj to mix into */ - mixin: function mixin(obj) { + mixin: function mixin(obj) + { eventTarget(obj); } }; diff --git a/src/core/utils/PolyK.js b/src/core/utils/PolyK.js index 7325141..5e20c2b 100644 --- a/src/core/utils/PolyK.js +++ b/src/core/utils/PolyK.js @@ -47,7 +47,8 @@ * Triangulates shapes for webGL graphic fills. * */ -PolyK.Triangulate = function (p) { +PolyK.Triangulate = function (p) +{ var sign = true; var n = p.length >> 1; @@ -59,7 +60,8 @@ i = 0; var al = n; - while(al > 3) { + while(al > 3) + { var i0 = avl[(i+0)%al]; var i1 = avl[(i+1)%al]; var i2 = avl[(i+2)%al]; @@ -69,29 +71,35 @@ var cx = p[2*i2], cy = p[2*i2+1]; var earFound = false; - if (PolyK._convex(ax, ay, bx, by, cx, cy, sign)) { + if (PolyK._convex(ax, ay, bx, by, cx, cy, sign)) + { earFound = true; - for (var j = 0; j < al; j++) { + for (var j = 0; j < al; j++) + { var vi = avl[j]; if (vi === i0 || vi === i1 || vi === i2) continue; - if (PolyK._PointInTriangle(p[2*vi], p[2*vi+1], ax, ay, bx, by, cx, cy)) { + if (PolyK._PointInTriangle(p[2*vi], p[2*vi+1], ax, ay, bx, by, cx, cy)) + { earFound = false; break; } } } - if (earFound) { + if (earFound) + { tgs.push(i0, i1, i2); avl.splice((i+1)%al, 1); al--; i = 0; } - else if (i++ > 3*al) { + else if (i++ > 3*al) + { // need to flip flip reverse it! // reset! - if (sign) { + if (sign) + { tgs = []; avl = []; for (i = 0; i < n; i++) avl.push(i); @@ -101,7 +109,8 @@ sign = false; } - else { + else + { // window.console.log("PIXI Warning: shape too complex to fill"); return null; } @@ -126,7 +135,8 @@ * @private * @return {boolean} */ -PolyK._PointInTriangle = function (px, py, ax, ay, bx, by, cx, cy) { +PolyK._PointInTriangle = function (px, py, ax, ay, bx, by, cx, cy) +{ var v0x = cx-ax; var v0y = cy-ay; var v1x = bx-ax; @@ -154,6 +164,7 @@ * @private * @return {boolean} */ -PolyK._convex = function (ax, ay, bx, by, cx, cy, sign) { +PolyK._convex = function (ax, ay, bx, by, cx, cy, sign) +{ return ((ay-by)*(cx-bx) + (bx-ax)*(cy-by) >= 0) === sign; }; diff --git a/src/core/utils/index.js b/src/core/utils/index.js index ade9831..bfae7ae 100644 --- a/src/core/utils/index.js +++ b/src/core/utils/index.js @@ -16,7 +16,8 @@ * * @return {number} The next uuid to use. */ - uuid: function () { + uuid: function () + { return ++utils._uid; }, @@ -26,7 +27,8 @@ * @param hex {number} * @return {number[]} An array representing the [R, G, B] of the color. */ - hex2rgb: function (hex, out) { + hex2rgb: function (hex, out) + { out = out || []; out[0] = (hex >> 16 & 0xFF) / 255; @@ -42,7 +44,8 @@ * @param hex {number} * @return {string} The string color. */ - hex2string: function (hex) { + hex2string: function (hex) + { hex = hex.toString(16); hex = '000000'.substr(0, 6 - hex.length) + hex; @@ -55,7 +58,8 @@ * @param rgb {number[]} * @return {number} The color number */ - rgb2hex: function (rgb) { + rgb2hex: function (rgb) + { return ((rgb[0]*255 << 16) + (rgb[1]*255 << 8) + rgb[2]*255); }, @@ -64,8 +68,10 @@ * * @return {boolean} whether they are supported */ - canUseNewCanvasBlendModes: function () { - if (typeof document === 'undefined') { + canUseNewCanvasBlendModes: function () + { + if (typeof document === 'undefined') + { return false; } @@ -93,15 +99,19 @@ * @param number {number} * @return {number} the closest number that is a power of two */ - getNextPowerOfTwo: function (number) { + getNextPowerOfTwo: function (number) + { // see: http://en.wikipedia.org/wiki/Power_of_two#Fast_algorithm_to_check_if_a_positive_number_is_a_power_of_two - if (number > 0 && (number & (number - 1)) === 0) { + if (number > 0 && (number & (number - 1)) === 0) + { return number; } - else { + else + { var result = 1; - while (result < number) { + while (result < number) + { result <<= 1; } @@ -116,7 +126,8 @@ * @param height {number} * @return {boolean} */ - isPowerOfTwo: function (width, height) { + isPowerOfTwo: function (width, height) + { return (width > 0 && (width & (width - 1)) === 0 && height > 0 && (height & (height - 1)) === 0); }, @@ -130,12 +141,15 @@ * @constant * @static */ - sayHello: function (type) { - if (utils._saidHello) { + sayHello: function (type) + { + if (utils._saidHello) + { return; } - if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) { + if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) + { var args = [ '%c %c %c Pixi.js ' + CONST.VERSION + ' - ' + type + ' %c ' + ' %c ' + ' http://www.pixijs.com/ %c %c ♥%c♥%c♥ ', 'background: #ff66a5', @@ -151,7 +165,8 @@ console.log.apply(console, args); //jshint ignore:line } - else if (window.console) { + else if (window.console) + { console.log('Pixi.js ' + CONST.VERSION + ' - ' + type + ' - http://www.pixijs.com/'); //jshint ignore:line } @@ -166,15 +181,19 @@ * @class * @namespace PIXI */ - AjaxRequest: function () { + AjaxRequest: function () + { var activexmodes = ['Msxml2.XMLHTTP.6.0', 'Msxml2.XMLHTTP.3.0', 'Microsoft.XMLHTTP']; //activeX versions to check for in IE - if (window.ActiveXObject) { //Test for support for ActiveXObject in IE first (as XMLHttpRequest in IE7 is broken) - for (var i=0; i= this.textures.length) { + else if (round >= this.textures.length) + { this.gotoAndStop(this.textures.length - 1); - if (this.onComplete) { + if (this.onComplete) + { this.onComplete(); } } @@ -167,10 +182,12 @@ * @static * @param frames {string[]} the array of frames ids the movieclip will use as its texture frames */ -MovieClip.fromFrames = function (frames) { +MovieClip.fromFrames = function (frames) +{ var textures = []; - for (var i = 0; i < frames.length; ++i) { + for (var i = 0; i < frames.length; ++i) + { textures.push(new core.Texture.fromFrame(frames[i])); } @@ -183,10 +200,12 @@ * @static * @param images {string[]} the array of image urls the movieclip will use as its texture frames */ -MovieClip.fromImages = function (images) { +MovieClip.fromImages = function (images) +{ var textures = []; - for (var i = 0; i < images.length; ++i) { + for (var i = 0; i < images.length; ++i) + { textures.push(new core.Texture.fromImage(images[i])); } diff --git a/src/core/display/DisplayObject.js b/src/core/display/DisplayObject.js index 66ebc3c..20e778c 100644 --- a/src/core/display/DisplayObject.js +++ b/src/core/display/DisplayObject.js @@ -7,7 +7,8 @@ * @class * @namespace PIXI */ -function DisplayObject() { +function DisplayObject() +{ /** * The coordinate of the object relative to the local coordinates of the parent. * @@ -152,10 +153,12 @@ * @memberof DisplayObject# */ x: { - get: function () { + get: function () + { return this.position.x; }, - set: function (value) { + set: function (value) + { this.position.x = value; } }, @@ -167,10 +170,12 @@ * @memberof DisplayObject# */ y: { - get: function () { + get: function () + { return this.position.y; }, - set: function (value) { + set: function (value) + { this.position.y = value; } }, @@ -183,11 +188,13 @@ * @readonly */ worldVisible: { - get: function () { + get: function () + { var item = this; do { - if (!item.visible) { + if (!item.visible) + { return false; } @@ -207,17 +214,21 @@ * @memberof DisplayObject# */ mask: { - get: function () { + get: function () + { return this._mask; }, - set: function (value) { - if (this._mask) { + set: function (value) + { + if (this._mask) + { this._mask.isMask = false; } this._mask = value; - if (this._mask) { + if (this._mask) + { this._mask.isMask = true; } } @@ -232,18 +243,23 @@ * @memberof DisplayObject# */ filters: { - get: function () { + get: function () + { return this._filters; }, - set: function (value) { - if (value) { + set: function (value) + { + if (value) + { // now put all the passes in one place.. var passes = []; - for (var i = 0; i < value.length; i++) { + for (var i = 0; i < value.length; i++) + { var filterPasses = value[i].passes; - for (var j = 0; j < filterPasses.length; j++) { + for (var j = 0; j < filterPasses.length; j++) + { passes.push(filterPasses[j]); } } @@ -264,8 +280,9 @@ * * @private */ -DisplayObject.prototype.updateTransform = function () { - +DisplayObject.prototype.updateTransform = function () +{ + // create some matrix refs for easy access var pt = this.parent.worldTransform; var wt = this.worldTransform; @@ -274,9 +291,11 @@ var a, b, c, d, tx, ty; // so if rotation is between 0 then we can simplify the multiplication process.. - if (this.rotation % math.PI_2) { + if (this.rotation % math.PI_2) + { // 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) { + if (this.rotation !== this.rotationCache) + { this.rotationCache = this.rotation; this._sr = Math.sin(this.rotation); this._cr = Math.cos(this.rotation); @@ -291,7 +310,8 @@ ty = this.position.y; // check for pivot.. not often used so geared towards that fact! - if (this.pivot.x || this.pivot.y) { + 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; } @@ -304,7 +324,8 @@ wt.tx = tx * pt.a + ty * pt.c + pt.tx; wt.ty = tx * pt.b + ty * pt.d + pt.ty; } - else { + else + { // lets do the fast version as we know there is no rotation.. a = this.scale.x; d = this.scale.y; @@ -333,7 +354,8 @@ * @param matrix {Matrix} * @return {Rectangle} the rectangular bounding area */ -DisplayObject.prototype.getBounds = function (/* matrix */) { +DisplayObject.prototype.getBounds = function (/* matrix */) +{ return math.Rectangle.EMPTY; }; @@ -342,7 +364,8 @@ * * @return {Rectangle} the rectangular bounding area */ -DisplayObject.prototype.getLocalBounds = function () { +DisplayObject.prototype.getLocalBounds = function () +{ return this.getBounds(math.Matrix.IDENTITY); }; @@ -352,7 +375,8 @@ * @param position {Point} The world origin to calculate from * @return {Point} A point object representing the position of this object */ -DisplayObject.prototype.toGlobal = function (position) { +DisplayObject.prototype.toGlobal = function (position) +{ // don't need to u[date the lot this.displayObjectUpdateTransform(); return this.worldTransform.apply(position); @@ -365,8 +389,10 @@ * @param [from] {DisplayObject} The DisplayObject to calculate the global position from * @return {Point} A point object representing the position of this object */ -DisplayObject.prototype.toLocal = function (position, from) { - if (from) { +DisplayObject.prototype.toLocal = function (position, from) +{ + if (from) + { position = from.toGlobal(position); } @@ -381,7 +407,8 @@ * @param renderer {WebGLRenderer} The renderer * @private */ -DisplayObject.prototype.renderWebGL = function (/* renderer */) { +DisplayObject.prototype.renderWebGL = function (/* renderer */) +{ // OVERWRITE; }; @@ -391,6 +418,7 @@ * @param renderer {CanvasRenderer} The renderer * @private */ -DisplayObject.prototype.renderCanvas = function (/* renderer */) { +DisplayObject.prototype.renderCanvas = function (/* renderer */) +{ // OVERWRITE; }; diff --git a/src/core/display/DisplayObjectContainer.js b/src/core/display/DisplayObjectContainer.js index 689f40b..4625ee8 100644 --- a/src/core/display/DisplayObjectContainer.js +++ b/src/core/display/DisplayObjectContainer.js @@ -12,7 +12,8 @@ * @extends DisplayObject * @namespace PIXI */ -function DisplayObjectContainer() { +function DisplayObjectContainer() +{ DisplayObject.call(this); /** @@ -47,17 +48,21 @@ * @memberof DisplayObjectContainer# */ width: { - get: function () { + get: function () + { return this.scale.x * this.getLocalBounds().width; }, - set: function (value) { + set: function (value) + { var width = this.getLocalBounds().width; - if(width !== 0) { + if(width !== 0) + { this.scale.x = value / width; } - else { + else + { this.scale.x = 1; } @@ -73,17 +78,21 @@ * @memberof DisplayObjectContainer# */ height: { - get: function () { + get: function () + { return this.scale.y * this.getLocalBounds().height; }, - set: function (value) { + set: function (value) + { var height = this.getLocalBounds().height; - if (height !== 0) { + if (height !== 0) + { this.scale.y = value / height ; } - else { + else + { this.scale.y = 1; } @@ -100,18 +109,23 @@ * @memberof DisplayObject# */ cacheAsBitmap: { - get: function () { + get: function () + { return this._cacheAsBitmap; }, - set: function (value) { - if (this._cacheAsBitmap === value) { + set: function (value) + { + if (this._cacheAsBitmap === value) + { return; } - if (value) { + if (value) + { this._generateCachedSprite(); } - else { + else + { this._destroyCachedSprite(); } @@ -126,7 +140,8 @@ * @param child {DisplayObject} The DisplayObject to add to the container * @return {DisplayObject} The child that was added. */ -DisplayObjectContainer.prototype.addChild = function (child) { +DisplayObjectContainer.prototype.addChild = function (child) +{ return this.addChildAt(child, this.children.length); }; @@ -137,14 +152,18 @@ * @param index {Number} The index to place the child in * @return {DisplayObject} The child that was added. */ -DisplayObjectContainer.prototype.addChildAt = function (child, index) { +DisplayObjectContainer.prototype.addChildAt = function (child, index) +{ // prevent adding self as child - if (child === this) { + if (child === this) + { return; } - if (index >= 0 && index <= this.children.length) { - if (child.parent) { + if (index >= 0 && index <= this.children.length) + { + if (child.parent) + { child.parent.removeChild(child); } @@ -154,7 +173,8 @@ return child; } - else { + else + { throw new Error(child + 'addChildAt: The index '+ index +' supplied is out of bounds ' + this.children.length); } }; @@ -165,15 +185,18 @@ * @param child {DisplayObject} * @param child2 {DisplayObject} */ -DisplayObjectContainer.prototype.swapChildren = function (child, child2) { - if (child === child2) { +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) { + if (index1 < 0 || index2 < 0) + { throw new Error('swapChildren: Both the supplied DisplayObjects must be a child of the caller.'); } @@ -187,10 +210,12 @@ * @param child {DisplayObject} The DisplayObject instance to identify * @return {Number} The index position of the child display object to identify */ -DisplayObjectContainer.prototype.getChildIndex = function (child) { +DisplayObjectContainer.prototype.getChildIndex = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { throw new Error('The supplied DisplayObject must be a child of the caller'); } @@ -203,8 +228,10 @@ * @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 */ -DisplayObjectContainer.prototype.setChildIndex = function (child, index) { - if (index < 0 || index >= this.children.length) { +DisplayObjectContainer.prototype.setChildIndex = function (child, index) +{ + if (index < 0 || index >= this.children.length) + { throw new Error('The supplied index is out of bounds'); } @@ -220,8 +247,10 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child at the given index, if any. */ -DisplayObjectContainer.prototype.getChildAt = function (index) { - if (index < 0 || index >= this.children.length) { +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'); } @@ -234,10 +263,12 @@ * @param child {DisplayObject} The DisplayObject to remove * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChild = function (child) { +DisplayObjectContainer.prototype.removeChild = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { return; } @@ -250,7 +281,8 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChildAt = function (index) { +DisplayObjectContainer.prototype.removeChildAt = function (index) +{ var child = this.getChildAt(index); child.parent = null; @@ -265,24 +297,29 @@ * @param beginIndex {Number} The beginning position. Default value is 0. * @param endIndex {Number} The ending position. Default value is size of the container. */ -DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) { +DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) +{ var begin = beginIndex || 0; var end = typeof endIndex === 'number' ? endIndex : this.children.length; var range = end - begin; - if (range > 0 && range <= end) { + if (range > 0 && range <= end) + { var removed = this.children.splice(begin, range); - for (var i = 0; i < removed.length; ++i) { + for (var i = 0; i < removed.length; ++i) + { removed[i].parent = null; } return removed; } - else if (range === 0 && this.children.length === 0) { + else if (range === 0 && this.children.length === 0) + { return []; } - else { + else + { throw new RangeError('removeChildren: numeric values are outside the acceptable range.'); } }; @@ -291,7 +328,8 @@ * Generates and updates the cached sprite for this object. * */ -DisplayObjectContainer.prototype.updateCachedSprite = function () { +DisplayObjectContainer.prototype.updateCachedSprite = function () +{ this._generateCachedSprite(); }; @@ -304,7 +342,8 @@ * @param renderer {CanvasRenderer|WebGLRenderer} The renderer used to generate the texture. * @return {Texture} a texture of the graphics object */ -DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) { +DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) +{ var bounds = this.getLocalBounds(); var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0, renderer, scaleMode, resolution); @@ -322,18 +361,22 @@ * * @private */ -DisplayObjectContainer.prototype.updateTransform = function () { - if (!this.visible) { +DisplayObjectContainer.prototype.updateTransform = function () +{ + if (!this.visible) + { return; } this.displayObjectUpdateTransform(); - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { return; } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } }; @@ -346,8 +389,10 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getBounds = function () { - if (this.children.length === 0) { +DisplayObjectContainer.prototype.getBounds = function () +{ + if (this.children.length === 0) + { return math.Rectangle.EMPTY; } @@ -365,10 +410,12 @@ var childVisible = false; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -386,7 +433,8 @@ maxY = maxY > childMaxY ? maxY : childMaxY; } - if (!childVisible) { + if (!childVisible) + { return math.Rectangle.EMPTY; } @@ -407,12 +455,14 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getLocalBounds = function () { +DisplayObjectContainer.prototype.getLocalBounds = function () +{ var matrixCache = this.worldTransform; this.worldTransform = math.Matrix.IDENTITY; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } @@ -428,13 +478,16 @@ * * @param renderer {WebGLRenderer} The renderer */ -DisplayObjectContainer.prototype.renderWebGL = function (renderer) { +DisplayObjectContainer.prototype.renderWebGL = function (renderer) +{ // if the object is not visible or the alpha is 0 then no need to render this element - if (!this.visible || this.alpha <= 0) { + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } @@ -442,14 +495,17 @@ var i, j; // do a quick check to see if this element has a mask or a filter. - if (this._mask || this._filters) { + if (this._mask || this._filters) + { // push filter first as we need to ensure the stencil buffer is correct for any masking - if (this._filters) { + if (this._filters) + { renderer.spriteBatch.flush(); renderer.filterManager.pushFilter(this._filterBlock); } - if (this._mask) { + if (this._mask) + { renderer.spriteBatch.stop(); renderer.maskManager.pushMask(this.mask, renderer); renderer.spriteBatch.start(); @@ -459,36 +515,42 @@ this._renderWebGL(renderer); // now loop through the children and make sure they get rendered - for (i = 0, j = this.children.length; i < j; i++) { + for (i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderWebGL(renderer); } // time to stop the sprite batch as either a mask element or a filter draw will happen next renderer.spriteBatch.stop(); - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(this._mask, renderer); } - if (this._filters) { + if (this._filters) + { renderer.filterManager.popFilter(); } renderer.spriteBatch.start(); } - else { + else + { this._renderWebGL(renderer); // simple render children! - for (i = 0, j = this.children.length; i < j; ++i) { + for (i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderWebGL(renderer); } } }; -DisplayObjectContainer.prototype._renderWebGL = function (renderer) { +DisplayObjectContainer.prototype._renderWebGL = function (renderer) +{ // this is where content itself gets renderd.. @@ -499,25 +561,31 @@ * * @param renderer {CanvasRenderer} The renderer */ -DisplayObjectContainer.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0) { +DisplayObjectContainer.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -528,13 +596,16 @@ * @param renderer {WebGLRenderer|CanvasRenderer} The renderer * @private */ -DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) { +DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) +{ this._cachedSprite.worldAlpha = this.worldAlpha; - if (renderer.gl) { + if (renderer.gl) + { this._cachedSprite.renderWebGL(renderer); } - else { + else + { this._cachedSprite.renderCanvas(renderer); } }; @@ -544,10 +615,12 @@ * * @private */ -DisplayObjectContainer.prototype._generateCachedSprite = function () { +DisplayObjectContainer.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { // TODO - RenderTexture now *requires* a renderer instance, so this is like broken // because `renderer` isn't actually in scope here :P var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0); @@ -555,7 +628,8 @@ this._cachedSprite = new Sprite(renderTexture); this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.texture.resize(bounds.width | 0, bounds.height | 0); } @@ -580,8 +654,10 @@ * * @private */ -DisplayObjectContainer.prototype._destroyCachedSprite = function () { - if (!this._cachedSprite) { +DisplayObjectContainer.prototype._destroyCachedSprite = function () +{ + if (!this._cachedSprite) + { return; } diff --git a/src/core/display/Sprite.js b/src/core/display/Sprite.js index 707da24..5862aef 100644 --- a/src/core/display/Sprite.js +++ b/src/core/display/Sprite.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param texture {Texture} The texture for this sprite */ -function Sprite(texture) { +function Sprite(texture) +{ DisplayObjectContainer.call(this); /** @@ -85,12 +86,14 @@ this.texture = texture || Texture.EMPTY; } -Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) { +Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) +{ DisplayObjectContainer.prototype.destroy.call(this); this.anchor = null; - if (destroyTexture) { + if (destroyTexture) + { this._texture.destroy(destroyBaseTexture); } @@ -111,10 +114,12 @@ * @memberof Sprite# */ width: { - get: function () { + get: function () + { return this.scale.x * this.texture.frame.width; }, - set: function (value) { + set: function (value) + { this.scale.x = value / this.texture.frame.width; this._width = value; } @@ -127,10 +132,12 @@ * @memberof Sprite# */ height: { - get: function () { + get: function () + { return this.scale.y * this.texture.frame.height; }, - set: function (value) { + set: function (value) + { this.scale.y = value / this.texture.frame.height; this._height = value; } @@ -143,23 +150,29 @@ * @memberof Sprite# */ texture: { - get: function () { + get: function () + { return this._texture; }, - set: function (value) { - if (this._texture === value) { + set: function (value) + { + if (this._texture === value) + { return; } this._texture = value; this.cachedTint = 0xFFFFFF; - if (value) { + if (value) + { // wait for the texture to load - if (value.baseTexture.hasLoaded) { + if (value.baseTexture.hasLoaded) + { this._onTextureUpdate(); } - else { + else + { value.once('update', this._onTextureUpdate.bind(this)); } } @@ -172,18 +185,22 @@ * * @private */ -Sprite.prototype._onTextureUpdate = function () { +Sprite.prototype._onTextureUpdate = function () +{ // so if _width is 0 then width was not set.. - if (this._width) { + if (this._width) + { this.scale.x = this._width / this.texture.frame.width; } - if (this._height) { + if (this._height) + { this.scale.y = this._height / this.texture.frame.height; } }; -Sprite.prototype._renderWebGL = function (renderer) { +Sprite.prototype._renderWebGL = function (renderer) +{ // this is where content gets renderd.. // watch this space for a little render state manager.. @@ -197,7 +214,8 @@ * @param matrix {Matrix} the transformation matrix of the sprite * @return {Rectangle} the framing rectangle */ -Sprite.prototype.getBounds = function (matrix) { +Sprite.prototype.getBounds = function (matrix) +{ var width = this.texture.frame.width; var height = this.texture.frame.height; @@ -224,11 +242,13 @@ if(b === 0 && c === 0) { // scale may be negative! - if (a < 0) { + if (a < 0) + { a *= -1; } - if (d < 0) { + if (d < 0) + { d *= -1; } @@ -293,28 +313,34 @@ * * @param renderer {CanvasRenderer} The renderer */ -Sprite.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) { +Sprite.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) + { return; } - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; renderer.context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } // Ignore null sources - if (this.texture.valid) { + if (this.texture.valid) + { var resolution = this.texture.baseTexture.resolution / renderer.resolution; renderer.context.globalAlpha = this.worldAlpha; // If smoothingEnabled is supported and we need to change the smoothing property for this texture - if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) { + if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) + { renderer.scaleMode = this.texture.baseTexture.scaleMode; renderer.context[renderer.smoothProperty] = (renderer.scaleMode === CONST.scaleModes.LINEAR); } @@ -324,7 +350,8 @@ var dy = (this.texture.trim ? this.texture.trim.y : 0) - (this.anchor.y * this.texture.trim.height); // Allow for pixel rounding - if (renderer.roundPixels) { + if (renderer.roundPixels) + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -337,7 +364,8 @@ dx = dx | 0; dy = dy | 0; } - else { + else + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -348,8 +376,10 @@ ); } - if (this.tint !== 0xFFFFFF) { - if (this.cachedTint !== this.tint) { + if (this.tint !== 0xFFFFFF) + { + if (this.cachedTint !== this.tint) + { this.cachedTint = this.tint; // TODO clean up caching - how to clean up the caches? @@ -368,7 +398,8 @@ this.texture.crop.height / resolution ); } - else { + else + { renderer.context.drawImage( this.texture.baseTexture.source, this.texture.crop.x, @@ -383,11 +414,13 @@ } } - for (var i = 0, j = this.children.length; i < j; i++) { + for (var i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -402,10 +435,12 @@ * @param frameId {String} The frame Id of the texture in the cache * @return {Sprite} A new Sprite using a texture from the texture cache matching the frameId */ -Sprite.fromFrame = function (frameId) { +Sprite.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache' + this); } @@ -420,6 +455,7 @@ * @param imageId {String} The image url of the texture * @return {Sprite} A new Sprite using a texture from the texture cache matching the image id */ -Sprite.fromImage = function (imageId, crossorigin, scaleMode) { +Sprite.fromImage = function (imageId, crossorigin, scaleMode) +{ return new Sprite(Texture.fromImage(imageId, crossorigin, scaleMode)); }; diff --git a/src/core/display/SpriteBatch.js b/src/core/display/SpriteBatch.js index 3187777..c196fef 100644 --- a/src/core/display/SpriteBatch.js +++ b/src/core/display/SpriteBatch.js @@ -12,7 +12,8 @@ * ```js * var container = new SpriteBatch(); * - * for(var i = 0; i < 100; ++i) { + * for(var i = 0; i < 100; ++i) + * { * var sprite = new PIXI.Sprite.fromImage("myImage.png"); * container.addChild(sprite); * } @@ -25,7 +26,8 @@ */ //TODO RENAME to PARTICLE CONTAINER? -function SpriteBatch() { +function SpriteBatch() +{ DisplayObjectContainer.call(this); } @@ -38,7 +40,8 @@ * * @private */ -SpriteBatch.prototype.updateTransform = function () { +SpriteBatch.prototype.updateTransform = function () +{ // TODO don't need to! this.displayObjectUpdateTransform(); // PIXI.DisplayObjectContainer.prototype.updateTransform.call( this ); @@ -50,8 +53,10 @@ * @param renderer {WebGLRenderer} The webgl renderer * @private */ -SpriteBatch.prototype.renderWebGL = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderWebGL = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -71,8 +76,10 @@ * @param renderer {CanvasRenderer} The canvas renderer * @private */ -SpriteBatch.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -84,10 +91,12 @@ this.displayObjectUpdateTransform(); - for (var i = 0; i < this.children.length; ++i) { + for (var i = 0; i < this.children.length; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -95,9 +104,11 @@ context.globalAlpha = this.worldAlpha * child.alpha; - if (child.rotation % (Math.PI * 2) === 0) { + if (child.rotation % (Math.PI * 2) === 0) + { // this is the fastest way to optimise! - if rotation is 0 then we can avoid any kind of setTransform call - if (isRotated) { + if (isRotated) + { context.setTransform( transform.a, transform.b, @@ -122,8 +133,10 @@ frame.height * child.scale.y ); } - else { - if (!isRotated) { + else + { + if (!isRotated) + { isRotated = true; } @@ -131,7 +144,8 @@ var childTransform = child.worldTransform; - if (renderer.roundPixels) { + if (renderer.roundPixels) + { context.setTransform( childTransform.a, childTransform.b, @@ -141,7 +155,8 @@ childTransform.ty | 0 ); } - else { + else + { context.setTransform( childTransform.a, childTransform.b, diff --git a/src/core/index.js b/src/core/index.js index 3954b6f..eb4a82b 100644 --- a/src/core/index.js +++ b/src/core/index.js @@ -58,11 +58,13 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRenderer: function (width, height, options, noWebGL) { + autoDetectRenderer: function (width, height, options, noWebGL) + { width = width || 800; height = height || 600; - if (!noWebGL && require('webgl-enabled')()) { + if (!noWebGL && require('webgl-enabled')()) + { return new core.WebGLRenderer(width, height, options); } @@ -87,7 +89,8 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRecommendedRenderer: function (width, height, options) { + autoDetectRecommendedRenderer: function (width, height, options) + { var isAndroid = /Android/i.test(navigator.userAgent); return core.autoDetectRenderer(width, height, options, isAndroid); diff --git a/src/core/math/Matrix.js b/src/core/math/Matrix.js index c2f87e2..2ff4848 100644 --- a/src/core/math/Matrix.js +++ b/src/core/math/Matrix.js @@ -10,7 +10,8 @@ * @class * @namespace PIXI */ -function Matrix() { +function Matrix() +{ /** * @member {number} * @default 1 @@ -63,7 +64,8 @@ * * @param array {number[]} The array that the matrix will be populated from. */ -Matrix.prototype.fromArray = function (array) { +Matrix.prototype.fromArray = function (array) +{ this.a = array[0]; this.b = array[1]; this.c = array[3]; @@ -78,14 +80,17 @@ * @param transpose {boolean} Whether we need to transpose the matrix or not * @return {number[]} the newly created array which contains the matrix */ -Matrix.prototype.toArray = function (transpose) { - if (!this.array) { +Matrix.prototype.toArray = function (transpose) +{ + if (!this.array) + { this.array = new Float32Array(9); } var array = this.array; - if (transpose) { + if (transpose) + { array[0] = this.a; array[1] = this.b; array[2] = 0; @@ -96,7 +101,8 @@ array[7] = this.ty; array[8] = 1; } - else { + else + { array[0] = this.a; array[1] = this.c; array[2] = this.tx; @@ -119,7 +125,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, transformed through this matrix */ -Matrix.prototype.apply = function (pos, newPos) { +Matrix.prototype.apply = function (pos, newPos) +{ newPos = newPos || new Point(); newPos.x = this.a * pos.x + this.c * pos.y + this.tx; @@ -136,7 +143,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, inverse-transformed through this matrix */ -Matrix.prototype.applyInverse = function (pos, newPos) { +Matrix.prototype.applyInverse = function (pos, newPos) +{ newPos = newPos || new Point(); var id = 1 / (this.a * this.d + this.c * -this.b); @@ -154,7 +162,8 @@ * @param {number} y * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.translate = function (x, y) { +Matrix.prototype.translate = function (x, y) +{ this.tx += x; this.ty += y; @@ -168,7 +177,8 @@ * @param {number} y The amount to scale vertically * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.scale = function (x, y) { +Matrix.prototype.scale = function (x, y) +{ this.a *= x; this.d *= y; this.c *= x; @@ -186,7 +196,8 @@ * @param {number} angle - The angle in radians. * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.rotate = function (angle) { +Matrix.prototype.rotate = function (angle) +{ var cos = Math.cos( angle ); var sin = Math.sin( angle ); @@ -210,7 +221,8 @@ * @param {Matrix} matrix * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.append = function (matrix) { +Matrix.prototype.append = function (matrix) +{ var a1 = this.a; var b1 = this.b; var c1 = this.c; @@ -232,7 +244,8 @@ * * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.identity = function () { +Matrix.prototype.identity = function () +{ this.a = 1; this.b = 0; this.c = 0; diff --git a/src/core/math/Point.js b/src/core/math/Point.js index 7565b2d..632f346 100644 --- a/src/core/math/Point.js +++ b/src/core/math/Point.js @@ -7,7 +7,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -function Point(x, y) { +function Point(x, y) +{ /** * @member {number} * @default 0 @@ -29,7 +30,8 @@ * * @return {Point} a copy of the point */ -Point.prototype.clone = function () { +Point.prototype.clone = function () +{ return new Point(this.x, this.y); }; @@ -40,7 +42,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -Point.prototype.set = function (x, y) { +Point.prototype.set = function (x, y) +{ this.x = x || 0; this.y = y || ( (y !== 0) ? this.x : 0 ) ; }; diff --git a/src/core/math/shapes/Circle.js b/src/core/math/shapes/Circle.js index 69cfdc9..4d76efc 100644 --- a/src/core/math/shapes/Circle.js +++ b/src/core/math/shapes/Circle.js @@ -10,7 +10,8 @@ * @param y {number} The Y coordinate of the center of this circle * @param radius {number} The radius of the circle */ -function Circle(x, y, radius) { +function Circle(x, y, radius) +{ /** * @member {number} * @default 0 @@ -46,7 +47,8 @@ * @method clone * @return {Circle} a copy of the Circle */ -Circle.prototype.clone = function () { +Circle.prototype.clone = function () +{ return new Circle(this.x, this.y, this.radius); }; @@ -58,8 +60,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Circle */ -Circle.prototype.contains = function (x, y) { - if (this.radius <= 0) { +Circle.prototype.contains = function (x, y) +{ + if (this.radius <= 0) + { return false; } @@ -79,6 +83,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Circle.prototype.getBounds = function () { +Circle.prototype.getBounds = function () +{ return new Rectangle(this.x - this.radius, this.y - this.radius, this.radius * 2, this.radius * 2); }; diff --git a/src/core/math/shapes/Ellipse.js b/src/core/math/shapes/Ellipse.js index 4f2d066..fefd01a 100644 --- a/src/core/math/shapes/Ellipse.js +++ b/src/core/math/shapes/Ellipse.js @@ -11,7 +11,8 @@ * @param width {number} The half width of this ellipse * @param height {number} The half height of this ellipse */ -function Ellipse(x, y, width, height) { +function Ellipse(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -53,7 +54,8 @@ * @method clone * @return {Ellipse} a copy of the ellipse */ -Ellipse.prototype.clone = function () { +Ellipse.prototype.clone = function () +{ return new Ellipse(this.x, this.y, this.width, this.height); }; @@ -65,8 +67,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coords are within this ellipse */ -Ellipse.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Ellipse.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } @@ -86,6 +90,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Ellipse.prototype.getBounds = function () { +Ellipse.prototype.getBounds = function () +{ return new Rectangle(this.x - this.width, this.y - this.height, this.width, this.height); }; diff --git a/src/core/math/shapes/Polygon.js b/src/core/math/shapes/Polygon.js index ae89148..fea6d37 100644 --- a/src/core/math/shapes/Polygon.js +++ b/src/core/math/shapes/Polygon.js @@ -10,16 +10,20 @@ * arguments passed can be flat x,y values e.g. `new Polygon(x,y, x,y, x,y, ...)` where `x` and `y` are * Numbers. */ -function Polygon(points) { +function Polygon(points) +{ //if points isn't an array, use arguments as the array - if (!(points instanceof Array)) { + if (!(points instanceof Array)) + { points = Array.prototype.slice.call(arguments); } //if this is a flat array of numbers, convert it to points - if (points[0] instanceof Point) { + if (points[0] instanceof Point) + { var p = []; - for (var i = 0, il = points.length; i < il; i++) { + for (var i = 0, il = points.length; i < il; i++) + { p.push(points[i].x, points[i].y); } @@ -51,7 +55,8 @@ * * @return {Polygon} a copy of the polygon */ -Polygon.prototype.clone = function () { +Polygon.prototype.clone = function () +{ return new Polygon(this.points.slice()); }; @@ -62,19 +67,22 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this polygon */ -Polygon.prototype.contains = function (x, y) { +Polygon.prototype.contains = function (x, y) +{ var inside = false; // use some raycasting to test hits // https://github.com/substack/point-in-polygon/blob/master/index.js var length = this.points.length / 2; - for (var i = 0, j = length - 1; i < length; j = i++) { + for (var i = 0, j = length - 1; i < length; j = i++) + { var xi = this.points[i * 2], yi = this.points[i * 2 + 1], xj = this.points[j * 2], yj = this.points[j * 2 + 1], intersect = ((yi > y) !== (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi); - if (intersect) { + if (intersect) + { inside = !inside; } } diff --git a/src/core/math/shapes/Rectangle.js b/src/core/math/shapes/Rectangle.js index 16ac62a..4008b68 100644 --- a/src/core/math/shapes/Rectangle.js +++ b/src/core/math/shapes/Rectangle.js @@ -10,7 +10,8 @@ * @param width {number} The overall width of this rectangle * @param height {number} The overall height of this rectangle */ -function Rectangle(x, y, width, height) { +function Rectangle(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -60,7 +61,8 @@ * * @return {Rectangle} a copy of the rectangle */ -Rectangle.prototype.clone = function () { +Rectangle.prototype.clone = function () +{ return new Rectangle(this.x, this.y, this.width, this.height); }; @@ -71,13 +73,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rectangle */ -Rectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Rectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/math/shapes/RoundedRectangle.js b/src/core/math/shapes/RoundedRectangle.js index 27d286e..7bf6411 100644 --- a/src/core/math/shapes/RoundedRectangle.js +++ b/src/core/math/shapes/RoundedRectangle.js @@ -11,7 +11,8 @@ * @param height {number} The overall height of this rounded rectangle * @param radius {number} Controls the radius of the rounded corners */ -function RoundedRectangle(x, y, width, height, radius) { +function RoundedRectangle(x, y, width, height, radius) +{ /** * @member {number} * @default 0 @@ -58,7 +59,8 @@ * * @return {RoundedRectangle} a copy of the rounded rectangle */ -RoundedRectangle.prototype.clone = function () { +RoundedRectangle.prototype.clone = function () +{ return new RoundedRectangle(this.x, this.y, this.width, this.height, this.radius); }; @@ -69,13 +71,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rounded Rectangle */ -RoundedRectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +RoundedRectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/primitives/Graphics.js b/src/core/primitives/Graphics.js index 261c534..e902d2a 100644 --- a/src/core/primitives/Graphics.js +++ b/src/core/primitives/Graphics.js @@ -16,7 +16,8 @@ * @extends DisplayObjectContainer * @namespace PIXI */ -function Graphics() { +function Graphics() +{ DisplayObjectContainer.call(this); this.renderable = true; @@ -154,16 +155,20 @@ * @private */ cacheAsBitmap: { - get: function () { + get: function () + { return this._cacheAsBitmap; }, - set: function (value) { + set: function (value) + { this._cacheAsBitmap = value; - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._generateCachedSprite(); } - else { + else + { this.destroyCachedSprite(); this.dirty = true; } @@ -176,7 +181,8 @@ * * @return {Graphics} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ var clone = new Graphics(); clone.renderable = this.renderable; @@ -192,7 +198,8 @@ clone.cachedSpriteDirty = this.cachedSpriteDirty; // copy graphics data - for (var i = 0; i < this.graphicsData.length; ++i) { + for (var i = 0; i < this.graphicsData.length; ++i) + { clone.graphicsData.push(this.graphicsData.clone()); } @@ -211,17 +218,21 @@ * @param alpha {number} alpha of the line to draw, will update the objects stored style * @return {Graphics} */ -Graphics.prototype.lineStyle = function (lineWidth, color, alpha) { +Graphics.prototype.lineStyle = function (lineWidth, color, alpha) +{ this.lineWidth = lineWidth || 0; this.lineColor = color || 0; this.lineAlpha = (arguments.length < 3) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length) + { // halfway through a line? start a new one! this.drawShape( new math.Polygon( this.currentPath.shape.points.slice(-2) )); } - else { + else + { // otherwise its empty so lets just set the line properties this.currentPath.lineWidth = this.lineWidth; this.currentPath.lineColor = this.lineColor; @@ -239,7 +250,8 @@ * @param y {number} the Y coordinate to move to * @return {Graphics} */ -Graphics.prototype.moveTo = function (x, y) { +Graphics.prototype.moveTo = function (x, y) +{ this.drawShape(new math.Polygon([x,y])); return this; @@ -253,7 +265,8 @@ * @param y {number} the Y coordinate to draw to * @return {Graphics} */ -Graphics.prototype.lineTo = function (x, y) { +Graphics.prototype.lineTo = function (x, y) +{ this.currentPath.shape.points.push(x, y); this.dirty = true; @@ -270,13 +283,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -285,7 +302,8 @@ n = 20, points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { this.moveTo(0, 0); } @@ -293,7 +311,8 @@ var fromY = points[points.length-1]; var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; xa = fromX + ( (cpX - fromX) * j ); @@ -319,13 +338,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -342,7 +365,8 @@ var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; dt = (1 - j); @@ -373,13 +397,17 @@ * @param radius {number} The radius of the arc * @return {Graphics} */ -Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points.push(x1, y1); } } - else { + else + { this.moveTo(x1, y1); } @@ -392,12 +420,15 @@ b2 = x2 - x1, mm = Math.abs(a1 * b2 - b1 * a2); - if (mm < 1.0e-8 || radius === 0) { - if (points[points.length-2] !== x1 || points[points.length-1] !== y1) { + if (mm < 1.0e-8 || radius === 0) + { + if (points[points.length-2] !== x1 || points[points.length-1] !== y1) + { points.push(x1, y1); } } - else { + else + { var dd = a1 * a1 + b1 * b1, cc = a2 * a2 + b2 * b2, tt = a1 * a2 + b1 * b2, @@ -433,42 +464,51 @@ * @param anticlockwise {boolean} Optional. Specifies whether the drawing should be counterclockwise or clockwise. False is default, and indicates clockwise, while true indicates counter-clockwise. * @return {Graphics} */ -Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) { +Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) +{ var startX = cx + Math.cos(startAngle) * radius; var startY = cy + Math.sin(startAngle) * radius; var points; // TODO - This if-else makes no sense. It uses currentPath in the else where it doesn't exist... - if (this.currentPath) { + if (this.currentPath) + { points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { points.push(startX, startY); } - else if (points[points.length-2] !== startX || points[points.length-1] !== startY) { + else if (points[points.length-2] !== startX || points[points.length-1] !== startY) + { points.push(startX, startY); } } - else { + else + { this.moveTo(startX, startY); points = this.currentPath.shape.points; } - if (startAngle === endAngle) { + if (startAngle === endAngle) + { return this; } - if (!anticlockwise && endAngle <= startAngle) { + if (!anticlockwise && endAngle <= startAngle) + { endAngle += Math.PI * 2; } - else if (anticlockwise && startAngle <= endAngle) { + else if (anticlockwise && startAngle <= endAngle) + { startAngle += Math.PI * 2; } var sweep = anticlockwise ? (startAngle - endAngle) *-1 : (endAngle - startAngle); var segs = (Math.abs(sweep)/ (Math.PI * 2)) * 40; - if (sweep === 0) { + if (sweep === 0) + { return this; } @@ -482,7 +522,8 @@ var remainder = ( segMinus % 1 ) / segMinus; - for (var i = 0; i <= segMinus; ++i) { + for (var i = 0; i <= segMinus; ++i) + { var real = i + remainder * i; var angle = ((theta) + startAngle + (theta2 * real)); @@ -506,13 +547,16 @@ * @param alpha {number} the alpha of the fill * @return {Graphics} */ -Graphics.prototype.beginFill = function (color, alpha) { +Graphics.prototype.beginFill = function (color, alpha) +{ this.filling = true; this.fillColor = color || 0; this.fillAlpha = (alpha === undefined) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length <= 2) + { this.currentPath.fill = this.filling; this.currentPath.fillColor = this.fillColor; this.currentPath.fillAlpha = this.fillAlpha; @@ -526,7 +570,8 @@ * * @return {Graphics} */ -Graphics.prototype.endFill = function () { +Graphics.prototype.endFill = function () +{ this.filling = false; this.fillColor = null; this.fillAlpha = 1; @@ -542,7 +587,8 @@ * @param height {number} The height of the rectangle * @return {Graphics} */ -Graphics.prototype.drawRect = function ( x, y, width, height ) { +Graphics.prototype.drawRect = function ( x, y, width, height ) +{ this.drawShape(new math.Rectangle(x,y, width, height)); return this; @@ -556,7 +602,8 @@ * @param height {number} The height of the rectangle * @param radius {number} Radius of the rectangle corners */ -Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) { +Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) +{ this.drawShape(new math.RoundedRectangle(x, y, width, height, radius)); return this; @@ -570,7 +617,8 @@ * @param radius {number} The radius of the circle * @return {Graphics} */ -Graphics.prototype.drawCircle = function (x, y, radius) { +Graphics.prototype.drawCircle = function (x, y, radius) +{ this.drawShape(new math.Circle(x,y, radius)); return this; @@ -585,7 +633,8 @@ * @param height {number} The half height of the ellipse * @return {Graphics} */ -Graphics.prototype.drawEllipse = function (x, y, width, height) { +Graphics.prototype.drawEllipse = function (x, y, width, height) +{ this.drawShape(new math.Ellipse(x, y, width, height)); return this; @@ -597,8 +646,10 @@ * @param path {Array} The path data used to construct the polygon. * @return {Graphics} */ -Graphics.prototype.drawPolygon = function (path) { - if (!(path instanceof Array)) { +Graphics.prototype.drawPolygon = function (path) +{ + if (!(path instanceof Array)) + { path = Array.prototype.slice.call(arguments); } @@ -612,7 +663,8 @@ * * @return {Graphics} */ -Graphics.prototype.clear = function () { +Graphics.prototype.clear = function () +{ this.lineWidth = 0; this.filling = false; @@ -631,7 +683,8 @@ * @param scaleMode {number} Should be one of the scaleMode consts * @return {Texture} a texture of the graphics object */ -Graphics.prototype.generateTexture = function (resolution, scaleMode) { +Graphics.prototype.generateTexture = function (resolution, scaleMode) +{ resolution = resolution || 1; var bounds = this.getBounds(); @@ -655,17 +708,21 @@ * * @param renderer {WebGLRenderer} */ -Graphics.prototype._renderWebGL = function (renderer) { +Graphics.prototype._renderWebGL = function (renderer) +{ // if the sprite is not visible or the alpha is 0 then no need to render this element - if (this.isMask === true) { + if (this.isMask === true) + { return; } // this code may still be needed so leaving for now.. - // + // /* - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture on the gpu too! @@ -681,17 +738,24 @@ return; } - */ - - // check if the webgl graphic needs to be updated - if (this.glDirty) { - this.dirty = true; - this.glDirty = false; - } + else */ - renderer.setObjectRendererer(renderer.graphicsRenderer); - renderer.graphicsRenderer.render(this); + renderer.spriteBatch.stop(); + renderer.blendModeManager.setBlendMode(this.blendMode); + // check blend mode + renderer.blendModeManager.setBlendMode( this.blendMode ); + + // check if the webgl graphic needs to be updated + if (this.glDirty) + { + this.dirty = true; + this.glDirty = false; + } + + WebGLGraphics.renderGraphics(this, renderer); + + renderer.spriteBatch.start(); }; /** @@ -700,14 +764,18 @@ * @param renderer {CanvasRenderer} * @private */ -Graphics.prototype.renderCanvas = function (renderer) { +Graphics.prototype.renderCanvas = function (renderer) +{ // 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.isMask === true) { + if (!this.visible || this.alpha <= 0 || this.isMask === true) + { return; } - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture @@ -723,16 +791,19 @@ return; } - else { + else + { var context = renderer.context; var transform = this.worldTransform; - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } @@ -748,11 +819,13 @@ CanvasGraphics.renderGraphics(this, context); - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } } @@ -763,13 +836,16 @@ * * @return {Rectangle} the rectangular bounding area */ -Graphics.prototype.getBounds = function (matrix) { +Graphics.prototype.getBounds = function (matrix) +{ // return an empty object if the item is a mask! - if (this.isMask) { + if (this.isMask) + { return math.Rectangle.EMPTY; } - if (this.dirty) { + if (this.dirty) + { this.updateLocalBounds(); this.glDirty = true; @@ -841,23 +917,27 @@ * Update the bounds of the object * */ -Graphics.prototype.updateLocalBounds = function () { +Graphics.prototype.updateLocalBounds = function () +{ var minX = Infinity; var maxX = -Infinity; var minY = Infinity; var maxY = -Infinity; - if (this.graphicsData.length) { + if (this.graphicsData.length) + { var shape, points, x, y, w, h; - for (var i = 0; i < this.graphicsData.length; i++) { + for (var i = 0; i < this.graphicsData.length; i++) + { var data = this.graphicsData[i]; var type = data.type; var lineWidth = data.lineWidth; shape = data.shape; - if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) { + if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) + { x = shape.x - lineWidth/2; y = shape.y - lineWidth/2; w = shape.width + lineWidth; @@ -869,7 +949,8 @@ minY = y < minY ? y : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.CIRC) { + else if (type === CONST.SHAPES.CIRC) + { x = shape.x; y = shape.y; w = shape.radius + lineWidth/2; @@ -881,7 +962,8 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.ELIP) { + else if (type === CONST.SHAPES.ELIP) + { x = shape.x; y = shape.y; w = shape.width + lineWidth/2; @@ -893,11 +975,13 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else { + else + { // POLY points = shape.points; - for (var j = 0; j < points.length; j += 2) { + for (var j = 0; j < points.length; j += 2) + { x = points[j]; y = points[j+1]; @@ -910,7 +994,8 @@ } } } - else { + else + { minX = 0; maxX = 0; minY = 0; @@ -931,10 +1016,12 @@ * * @private */ -Graphics.prototype._generateCachedSprite = function () { +Graphics.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { var canvasBuffer = new CanvasBuffer(bounds.width, bounds.height); var texture = Texture.fromCanvas(canvasBuffer.canvas); @@ -943,7 +1030,8 @@ this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.buffer.resize(bounds.width, bounds.height); } @@ -968,7 +1056,8 @@ * * @private */ -Graphics.prototype.updateCachedSpriteTexture = function () { +Graphics.prototype.updateCachedSpriteTexture = function () +{ var cachedSprite = this._cachedSprite; var texture = cachedSprite.texture; var canvas = cachedSprite.buffer.canvas; @@ -989,7 +1078,8 @@ * Destroys a previous cached sprite. * */ -Graphics.prototype.destroyCachedSprite = function () { +Graphics.prototype.destroyCachedSprite = function () +{ this._cachedSprite.texture.destroy(true); // let the gc collect the unused sprite @@ -1003,10 +1093,13 @@ * @param {Circle|Rectangle|Ellipse|Line|Polygon} shape The Shape object to draw. * @return {GraphicsData} The generated GraphicsData object. */ -Graphics.prototype.drawShape = function (shape) { - if (this.currentPath) { +Graphics.prototype.drawShape = function (shape) +{ + if (this.currentPath) + { // check current path! - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath.shape.points.length <= 2) + { this.graphicsData.pop(); } } @@ -1017,7 +1110,8 @@ this.graphicsData.push(data); - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { data.shape.closed = this.filling; this.currentPath = data; } diff --git a/src/core/primitives/GraphicsData.js b/src/core/primitives/GraphicsData.js index 99decbe..788f6f2 100644 --- a/src/core/primitives/GraphicsData.js +++ b/src/core/primitives/GraphicsData.js @@ -4,7 +4,8 @@ * @class * @namespace PIXI */ -function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) { +function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) +{ this.lineWidth = lineWidth; this.lineColor = lineColor; this.lineAlpha = lineAlpha; @@ -27,7 +28,8 @@ * * @return {GraphicsData} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ return new GraphicsData( this.lineWidth, this.lineColor, diff --git a/src/core/renderers/canvas/CanvasRenderer.js b/src/core/renderers/canvas/CanvasRenderer.js index 15a0978..7aebd44 100644 --- a/src/core/renderers/canvas/CanvasRenderer.js +++ b/src/core/renderers/canvas/CanvasRenderer.js @@ -17,17 +17,22 @@ * @param [options.resolution=1] {number} the resolution of the renderer retina would be 2 * @param [options.clearBeforeRender=true] {boolean} This sets if the CanvasRenderer will clear the canvas or not before the new render pass. */ -function CanvasRenderer(width, height, options) { +function CanvasRenderer(width, height, options) +{ utils.sayHello('Canvas'); - if (options) { - for (var i in CONST.defaultRenderOptions) { - if (typeof options[i] === 'undefined') { + if (options) + { + for (var i in CONST.defaultRenderOptions) + { + if (typeof options[i] === 'undefined') + { options[i] = CONST.defaultRenderOptions[i]; } } } - else { + else + { options = CONST.defaultRenderOptions; } @@ -156,19 +161,24 @@ this.smoothProperty = null; - if (this.context.imageSmoothingEnabled) { + if (this.context.imageSmoothingEnabled) + { this.smoothProperty = 'imageSmoothingEnabled'; } - else if (this.context.webkitImageSmoothingEnabled) { + else if (this.context.webkitImageSmoothingEnabled) + { this.smoothProperty = 'webkitImageSmoothingEnabled'; } - else if (this.context.mozImageSmoothingEnabled) { + else if (this.context.mozImageSmoothingEnabled) + { this.smoothProperty = 'mozImageSmoothingEnabled'; } - else if (this.context.oImageSmoothingEnabled) { + else if (this.context.oImageSmoothingEnabled) + { this.smoothProperty = 'oImageSmoothingEnabled'; } - else if (this.context.msImageSmoothingEnabled) { + else if (this.context.msImageSmoothingEnabled) + { this.smoothProperty = 'msImageSmoothingEnabled'; } @@ -193,10 +203,12 @@ * @memberof CanvasRenderer# */ backgroundColor: { - get: function () { + get: function () + { return this._backgroundColor; }, - set: function (val) { + set: function (val) + { this._backgroundColor = val; this._backgroundColorString = utils.hex2string(val); } @@ -208,7 +220,8 @@ * * @param object {DisplayObject} the object to be rendered */ -CanvasRenderer.prototype.render = function (object) { +CanvasRenderer.prototype.render = function (object) +{ object.updateTransform(); this.context.setTransform(1,0,0,1,0,0); @@ -218,16 +231,20 @@ this.currentBlendMode = CONST.blendModes.NORMAL; this.context.globalCompositeOperation = this.blendModes[CONST.blendModes.NORMAL]; - if (navigator.isCocoonJS && this.view.screencanvas) { + if (navigator.isCocoonJS && this.view.screencanvas) + { this.context.fillStyle = 'black'; this.context.clear(); } - if (this.clearBeforeRender) { - if (this.transparent) { + if (this.clearBeforeRender) + { + if (this.transparent) + { this.context.clearRect(0, 0, this.width, this.height); } - else { + else + { this.context.fillStyle = this._backgroundColorString; this.context.fillRect(0, 0, this.width , this.height); } @@ -241,8 +258,10 @@ * * @param [removeView=false] {boolean} Removes the Canvas element from the DOM. */ -CanvasRenderer.prototype.destroy = function (removeView) { - if (removeView && this.view.parent) { +CanvasRenderer.prototype.destroy = function (removeView) +{ + if (removeView && this.view.parent) + { this.view.parent.removeChild(this.view); } @@ -257,14 +276,16 @@ * @param width {number} the new width of the canvas view * @param height {number} the new height of the canvas view */ -CanvasRenderer.prototype.resize = function (width, height) { +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) { + if (this.autoResize) + { this.view.style.width = this.width / this.resolution + 'px'; this.view.style.height = this.height / this.resolution + 'px'; } @@ -276,7 +297,8 @@ * @param displayObject {DisplayObject} The displayObject to render * @private */ -CanvasRenderer.prototype.renderDisplayObject = function (displayObject) { +CanvasRenderer.prototype.renderDisplayObject = function (displayObject) +{ displayObject.renderCanvas(this); }; @@ -285,11 +307,14 @@ * * @private */ -CanvasRenderer.prototype._mapBlendModes = function () { - if (!this.blendModes) { +CanvasRenderer.prototype._mapBlendModes = function () +{ + if (!this.blendModes) + { this.blendModes = {}; - if (utils.canUseNewCanvasBlendModes()) { + if (utils.canUseNewCanvasBlendModes()) + { this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? this.blendModes[CONST.blendModes.MULTIPLY] = 'multiply'; @@ -308,7 +333,8 @@ this.blendModes[CONST.blendModes.COLOR] = 'color'; this.blendModes[CONST.blendModes.LUMINOSITY] = 'luminosity'; } - else { + else + { // this means that the browser does not support the cool new blend modes in canvas 'cough' ie 'cough' this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? diff --git a/src/core/renderers/canvas/utils/CanvasBuffer.js b/src/core/renderers/canvas/utils/CanvasBuffer.js index ebe5d47..b183a66 100644 --- a/src/core/renderers/canvas/utils/CanvasBuffer.js +++ b/src/core/renderers/canvas/utils/CanvasBuffer.js @@ -6,7 +6,8 @@ * @param width {number} the width for the newly created canvas * @param height {number} the height for the newly created canvas */ -function CanvasBuffer(width, height) { +function CanvasBuffer(width, height) +{ /** * The Canvas object that belongs to this CanvasBuffer. * @@ -36,10 +37,12 @@ * @memberof CanvasBuffer# */ width: { - get: function () { + get: function () + { return this.canvas.width; }, - set: function (val) { + set: function (val) + { this.canvas.width = val; } }, @@ -50,10 +53,12 @@ * @memberof CanvasBuffer# */ height: { - get: function () { + get: function () + { return this.canvas.height; }, - set: function (val) { + set: function (val) + { this.canvas.height = val; } } @@ -64,7 +69,8 @@ * * @private */ -CanvasBuffer.prototype.clear = function () { +CanvasBuffer.prototype.clear = function () +{ this.context.setTransform(1, 0, 0, 1, 0, 0); this.context.clearRect(0,0, this.canvas.width, this.canvas.height); }; @@ -75,7 +81,8 @@ * @param width {number} the new width of the canvas * @param height {number} the new height of the canvas */ -CanvasBuffer.prototype.resize = function (width, height) { +CanvasBuffer.prototype.resize = function (width, height) +{ this.canvas.width = width; this.canvas.height = height; }; diff --git a/src/core/renderers/canvas/utils/CanvasGraphics.js b/src/core/renderers/canvas/utils/CanvasGraphics.js index c7eaa2a..3f2a91f 100644 --- a/src/core/renderers/canvas/utils/CanvasGraphics.js +++ b/src/core/renderers/canvas/utils/CanvasGraphics.js @@ -13,15 +13,18 @@ * @param graphics {Graphics} the actual graphics object to render * @param context {CanvasRenderingContext2D} the 2d drawing method of the canvas */ -CanvasGraphics.renderGraphics = function (graphics, context) { +CanvasGraphics.renderGraphics = function (graphics, context) +{ var worldAlpha = graphics.worldAlpha; - if (graphics.dirty) { + if (graphics.dirty) + { this.updateGraphicsTint(graphics); graphics.dirty = false; } - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; @@ -30,69 +33,82 @@ context.lineWidth = data.lineWidth; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { context.beginPath(); var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } - if (shape.closed) { + if (shape.closed) + { context.lineTo(points[0], points[1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fillRect(shape.x, shape.y, shape.width, shape.height); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.strokeRect(shape.x, shape.y, shape.width, shape.height); } } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.beginPath(); context.arc(shape.x, shape.y, shape.radius,0,2*Math.PI); context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas var w = shape.width * 2; @@ -119,18 +135,21 @@ context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; var width = shape.width; @@ -152,13 +171,15 @@ context.quadraticCurveTo(rx, ry, rx, ry + radius); context.closePath(); - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); @@ -174,45 +195,54 @@ * @param graphics {Graphics} the graphics which will be used as a mask * @param context {CanvasRenderingContext2D} the context 2d method of the canvas */ -CanvasGraphics.renderGraphicsMask = function (graphics, context) { +CanvasGraphics.renderGraphicsMask = function (graphics, context) +{ var len = graphics.graphicsData.length; - if (len === 0) { + if (len === 0) + { return; } context.beginPath(); - for (var i = 0; i < len; i++) { + for (var i = 0; i < len; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { context.rect(shape.x, shape.y, shape.width, shape.height); context.closePath(); } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.arc(shape.x, shape.y, shape.radius, 0, 2 * Math.PI); context.closePath(); } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas @@ -237,7 +267,8 @@ context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); context.closePath(); } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; @@ -262,8 +293,10 @@ } }; -CanvasGraphics.updateGraphicsTint = function (graphics) { - if (graphics.tint === 0xFFFFFF) { +CanvasGraphics.updateGraphicsTint = function (graphics) +{ + if (graphics.tint === 0xFFFFFF) + { return; } @@ -271,7 +304,8 @@ var tintG = (graphics.tint >> 8 & 0xFF) / 255; var tintB = (graphics.tint & 0xFF)/ 255; - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var fillColor = data.fillColor | 0; diff --git a/src/core/renderers/canvas/utils/CanvasMaskManager.js b/src/core/renderers/canvas/utils/CanvasMaskManager.js index e04a733..9827d36 100644 --- a/src/core/renderers/canvas/utils/CanvasMaskManager.js +++ b/src/core/renderers/canvas/utils/CanvasMaskManager.js @@ -6,7 +6,8 @@ * @class * @namespace PIXI */ -function CanvasMaskManager() {} +function CanvasMaskManager() +{} CanvasMaskManager.prototype.constructor = CanvasMaskManager; module.exports = CanvasMaskManager; @@ -17,7 +18,8 @@ * @param maskData {object} the maskData that will be pushed * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.pushMask = function (maskData, renderer) { +CanvasMaskManager.prototype.pushMask = function (maskData, renderer) +{ renderer.context.save(); var cacheAlpha = maskData.alpha; @@ -45,6 +47,7 @@ * * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.popMask = function (renderer) { +CanvasMaskManager.prototype.popMask = function (renderer) +{ renderer.context.restore(); }; diff --git a/src/core/renderers/canvas/utils/CanvasTinter.js b/src/core/renderers/canvas/utils/CanvasTinter.js index 17e0529..d2fb1bc 100644 --- a/src/core/renderers/canvas/utils/CanvasTinter.js +++ b/src/core/renderers/canvas/utils/CanvasTinter.js @@ -14,7 +14,8 @@ * @param color {number} the color to use to tint the sprite with * @return {HTMLCanvasElement} The tinted canvas */ -CanvasTinter.getTintedTexture = function (sprite, color) { +CanvasTinter.getTintedTexture = function (sprite, color) +{ var texture = sprite.texture; color = CanvasTinter.roundColor(color); @@ -23,7 +24,8 @@ texture.tintCache = texture.tintCache || {}; - if (texture.tintCache[stringColor]) { + if (texture.tintCache[stringColor]) + { return texture.tintCache[stringColor]; } @@ -33,14 +35,16 @@ //CanvasTinter.tintWithPerPixel(texture, stringColor, canvas); CanvasTinter.tintMethod(texture, color, canvas); - if (CanvasTinter.convertTintToImage) { + if (CanvasTinter.convertTintToImage) + { // is this better? var tintImage = new Image(); tintImage.src = canvas.toDataURL(); texture.tintCache[stringColor] = tintImage; } - else { + else + { texture.tintCache[stringColor] = canvas; // if we are not converting the texture to an image then we need to lose the reference to the canvas CanvasTinter.canvas = null; @@ -56,7 +60,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithMultiply = function (texture, color, canvas) { +CanvasTinter.tintWithMultiply = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -104,7 +109,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithOverlay = function (texture, color, canvas) { +CanvasTinter.tintWithOverlay = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -139,7 +145,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithPerPixel = function (texture, color, canvas) { +CanvasTinter.tintWithPerPixel = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -167,7 +174,8 @@ var pixels = pixelData.data; - for (var i = 0; i < pixels.length; i += 4) { + for (var i = 0; i < pixels.length; i += 4) + { pixels[i+0] *= r; pixels[i+1] *= g; pixels[i+2] *= b; @@ -181,7 +189,8 @@ * * @param color {number} the color to round, should be a hex color */ -CanvasTinter.roundColor = function (color) { +CanvasTinter.roundColor = function (color) +{ var step = CanvasTinter.cacheStepsPerColorChannel; var rgbValues = utils.hex2rgb(color); diff --git a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js index 9f2f89a..35edbaf 100644 --- a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js +++ b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLBlendModeManager(renderer) { +function WebGLBlendModeManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -23,8 +24,10 @@ * * @param blendMode {number} the blendMode, should be a Pixi const, such as BlendModes.ADD */ -WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) { - if (this.currentBlendMode === blendMode) { +WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) +{ + if (this.currentBlendMode === blendMode) + { return false; } diff --git a/src/core/renderers/webgl/managers/WebGLFilterManager.js b/src/core/renderers/webgl/managers/WebGLFilterManager.js index 1179258..2dac048 100644 --- a/src/core/renderers/webgl/managers/WebGLFilterManager.js +++ b/src/core/renderers/webgl/managers/WebGLFilterManager.js @@ -7,7 +7,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLFilterManager(renderer) { +function WebGLFilterManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -32,7 +33,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.texturePool.length = 0; self.initShaderBuffers(); }); @@ -46,7 +48,8 @@ * @param renderer {WebGLRenderer} * @param buffer {ArrayBuffer} */ -WebGLFilterManager.prototype.begin = function (buffer) { +WebGLFilterManager.prototype.begin = function (buffer) +{ this.defaultShader = this.renderer.shaderManager.defaultShader; this.width = this.renderer.projection.x * 2; @@ -60,7 +63,8 @@ * * @param filterBlock {object} the filter that will be pushed to the current filter stack */ -WebGLFilterManager.prototype.pushFilter = function (filterBlock) { +WebGLFilterManager.prototype.pushFilter = function (filterBlock) +{ var gl = this.renderer.gl; var projection = this.renderer.projection; @@ -78,10 +82,12 @@ this.offsetY += filterBlock._filterArea.y; var texture = this.texturePool.pop(); - if (!texture) { + if (!texture) + { texture = new FilterTexture(this.renderer.gl, this.width, this.height); } - else { + else + { texture.resize(this.width, this.height); } @@ -98,29 +104,35 @@ var localX = filterArea.x, localY = filterArea.y; - if (filterArea.x < 0) { + if (filterArea.x < 0) + { filterArea.width += filterArea.x; filterArea.x = 0; } - if (filterArea.y < 0) { + if (filterArea.y < 0) + { filterArea.height += filterArea.y; filterArea.y = 0; } - if (localX + filterArea.width > this.width) { + if (localX + filterArea.width > this.width) + { filterArea.width = this.width - localX; } - if (localY + filterArea.height > this.height) { + if (localY + filterArea.height > this.height) + { filterArea.height = this.height - localY; } - if (filterArea.width < 0) { + if (filterArea.width < 0) + { filterArea.width = 0; } - if (filterArea.height < 0) { + if (filterArea.height < 0) + { filterArea.height = 0; } @@ -154,7 +166,8 @@ * Removes the last filter from the filter stack and doesn't return it. * */ -WebGLFilterManager.prototype.popFilter = function () { +WebGLFilterManager.prototype.popFilter = function () +{ var gl = this.renderer.gl; var filterBlock = this.filterStack.pop(); @@ -163,7 +176,8 @@ var projection = this.renderer.projection; var offset = this.renderer.offset; - if (filterBlock.filterPasses.length > 1) { + if (filterBlock.filterPasses.length > 1) + { gl.viewport(0, 0, filterArea.width, filterArea.height); gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); @@ -193,7 +207,8 @@ var inputTexture = texture; var outputTexture = this.texturePool.pop(); - if (!outputTexture) { + if (!outputTexture) + { outputTexture = new FilterTexture(this.renderer.gl, this.width, this.height); } outputTexture.resize(this.width, this.height); @@ -204,7 +219,8 @@ gl.disable(gl.BLEND); - for (var i = 0; i < filterBlock.filterPasses.length-1; i++) { + for (var i = 0; i < filterBlock.filterPasses.length-1; i++) + { var filterPass = filterBlock.filterPasses[i]; gl.bindFramebuffer(gl.FRAMEBUFFER, outputTexture.frameBuffer ); @@ -243,10 +259,12 @@ var buffer = this.buffer; // time to render the filters texture to the previous scene - if (this.filterStack.length === 0) { + if (this.filterStack.length === 0) + { gl.colorMask(true, true, true, true);//this.transparent); } - else { + else + { var currentFilter = this.filterStack[this.filterStack.length-1]; filterArea = currentFilter._filterArea; @@ -332,13 +350,15 @@ * @param width {number} the horizontal range of the filter * @param height {number} the vertical range of the filter */ -WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) { +WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) +{ // use program var gl = this.renderer.gl; var shader = filter.shaders[gl.id]; - if (!shader) { + if (!shader) + { shader = new Shader(gl); shader.fragmentSrc = filter.fragmentSrc; @@ -356,7 +376,8 @@ gl.uniform2f(shader.projectionVector, width/2, -height/2); gl.uniform2f(shader.offsetVector, 0,0); - if (filter.uniforms.dimensions) { + 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]; @@ -386,7 +407,8 @@ * Initialises the shader buffers. * */ -WebGLFilterManager.prototype.initShaderBuffers = function () { +WebGLFilterManager.prototype.initShaderBuffers = function () +{ var gl = this.renderer.gl; // create some buffers @@ -432,7 +454,8 @@ * Destroys the filter and removes it from the filter stack. * */ -WebGLFilterManager.prototype.destroy = function () { +WebGLFilterManager.prototype.destroy = function () +{ var gl = this.renderer.gl; this.filterStack = null; @@ -441,7 +464,8 @@ this.offsetY = 0; // destroy textures - for (var i = 0; i < this.texturePool.length; i++) { + for (var i = 0; i < this.texturePool.length; i++) + { this.texturePool[i].destroy(); } diff --git a/src/core/renderers/webgl/managers/WebGLManager.js b/src/core/renderers/webgl/managers/WebGLManager.js index 9d47b5c..c30cd51 100644 --- a/src/core/renderers/webgl/managers/WebGLManager.js +++ b/src/core/renderers/webgl/managers/WebGLManager.js @@ -3,7 +3,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLManager(renderer) { +function WebGLManager(renderer) +{ /** * The renderer this manager works for. * @@ -15,6 +16,7 @@ WebGLManager.prototype.constructor = WebGLManager; module.exports = WebGLManager; -WebGLManager.prototype.destroy = function () { +WebGLManager.prototype.destroy = function () +{ this.renderer = null; }; diff --git a/src/core/renderers/webgl/managers/WebGLMaskManager.js b/src/core/renderers/webgl/managers/WebGLMaskManager.js index 2f90b64..e568812 100644 --- a/src/core/renderers/webgl/managers/WebGLMaskManager.js +++ b/src/core/renderers/webgl/managers/WebGLMaskManager.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLMaskManager(renderer) { +function WebGLMaskManager(renderer) +{ WebGLManager.call(this, renderer); } @@ -19,12 +20,15 @@ * * @param maskData {any[]} */ -WebGLMaskManager.prototype.pushMask = function (maskData) { - if (maskData.dirty) { +WebGLMaskManager.prototype.pushMask = function (maskData) +{ + if (maskData.dirty) + { WebGLGraphics.updateGraphics(maskData, this.renderer.gl); } - if (!maskData._webGL[this.renderer.gl.id].data.length) { + if (!maskData._webGL[this.renderer.gl.id].data.length) + { return; } @@ -36,6 +40,7 @@ * * @param maskData {any[]} */ -WebGLMaskManager.prototype.popMask = function (maskData) { +WebGLMaskManager.prototype.popMask = function (maskData) +{ this.renderer.stencilManager.popStencil(maskData, maskData._webGL[this.renderer.gl.id].data[0], this.renderer); }; diff --git a/src/core/renderers/webgl/managers/WebGLShaderManager.js b/src/core/renderers/webgl/managers/WebGLShaderManager.js index fef071c..90c6477 100644 --- a/src/core/renderers/webgl/managers/WebGLShaderManager.js +++ b/src/core/renderers/webgl/managers/WebGLShaderManager.js @@ -10,7 +10,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLShaderManager(renderer) { +function WebGLShaderManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -28,7 +29,8 @@ */ this.tempAttribState = []; - for (var i = 0; i < this.maxAttibs; i++) { + for (var i = 0; i < this.maxAttibs; i++) + { this.attribState[i] = false; } @@ -66,7 +68,8 @@ // listen for context and update necessary shaders var self = this; - this.renderer.on('context', function (event) { + this.renderer.on('context', function (event) + { var gl = event.data; // this shader is used for rendering primitives @@ -97,29 +100,36 @@ * * @param attribs {Array} attribs */ -WebGLShaderManager.prototype.setAttribs = function (attribs) { +WebGLShaderManager.prototype.setAttribs = function (attribs) +{ // reset temp state var i; - for (i = 0; i < this.tempAttribState.length; i++) { + for (i = 0; i < this.tempAttribState.length; i++) + { this.tempAttribState[i] = false; } // set the new attribs - for (var a in attribs) { + for (var a in attribs) + { this.tempAttribState[attribs[a]] = true; } var gl = this.renderer.gl; - for (i = 0; i < this.attribState.length; i++) { - if (this.attribState[i] !== this.tempAttribState[i]) { + for (i = 0; i < this.attribState.length; i++) + { + if (this.attribState[i] !== this.tempAttribState[i]) + { this.attribState[i] = this.tempAttribState[i]; - if (this.attribState[i]) { + if (this.attribState[i]) + { gl.enableVertexAttribArray(i); } - else { + else + { gl.disableVertexAttribArray(i); } } @@ -131,8 +141,10 @@ * * @param shader {Any} */ -WebGLShaderManager.prototype.setShader = function (shader) { - if (this._currentId === shader.uuid) { +WebGLShaderManager.prototype.setShader = function (shader) +{ + if (this._currentId === shader.uuid) + { return false; } @@ -150,7 +162,8 @@ * Destroys this object. * */ -WebGLShaderManager.prototype.destroy = function () { +WebGLShaderManager.prototype.destroy = function () +{ this.attribState = null; this.tempAttribState = null; diff --git a/src/core/renderers/webgl/managers/WebGLStencilManager.js b/src/core/renderers/webgl/managers/WebGLStencilManager.js index 9ec6398..4cb0134 100644 --- a/src/core/renderers/webgl/managers/WebGLStencilManager.js +++ b/src/core/renderers/webgl/managers/WebGLStencilManager.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLStencilManager(renderer) { +function WebGLStencilManager(renderer) +{ WebGLManager.call(this, renderer); this.stencilStack = []; @@ -24,12 +25,14 @@ * @param graphics {Graphics} * @param webGLData {any[]} */ -WebGLStencilManager.prototype.pushStencil = function (graphics, webGLData) { +WebGLStencilManager.prototype.pushStencil = function (graphics, webGLData) +{ var gl = this.renderer.gl; this.bindGraphics(graphics, webGLData, this.renderer); - if (this.stencilStack.length === 0) { + if (this.stencilStack.length === 0) + { gl.enable(gl.STENCIL_TEST); gl.clear(gl.STENCIL_BUFFER_BIT); this.reverse = true; @@ -47,14 +50,17 @@ // draw the triangle strip! - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } @@ -62,31 +68,38 @@ // draw a quad to increment.. gl.drawElements(gl.TRIANGLE_FAN, 4, gl.UNSIGNED_SHORT, ( webGLData.indices.length - 4 ) * 2 ); - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); } this.reverse = !this.reverse; } - else { - if (!this.reverse) { + else + { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } - else { + 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) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); } } @@ -103,7 +116,8 @@ * @param graphics {Graphics} * @param webGLData {Array} */ -WebGLStencilManager.prototype.bindGraphics = function (graphics, webGLData) { +WebGLStencilManager.prototype.bindGraphics = function (graphics, webGLData) +{ //if (this._currentGraphics === graphics)return; this._currentGraphics = graphics; @@ -114,7 +128,8 @@ offset = this.renderer.offset, shader;// = this.renderer.shaderManager.primitiveShader; - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { shader = this.renderer.shaderManager.complexPrimitiveShader; this.renderer.shaderManager.setShader(shader); @@ -141,7 +156,8 @@ // set the index buffer! gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, webGLData.indexBuffer); } - else { + else + { //this.renderer.shaderManager.activatePrimitiveShader(); shader = this.renderer.shaderManager.primitiveShader; this.renderer.shaderManager.setShader( shader ); @@ -154,7 +170,7 @@ gl.uniform2f(shader.uniforms.offsetVector._location, -offset.x, -offset.y); gl.uniform3fv(shader.uniforms.tint._location, utils.hex2rgb(graphics.tint)); - + gl.uniform1f(shader.uniforms.alpha._location, graphics.worldAlpha); @@ -172,19 +188,22 @@ * @param graphics {Graphics} * @param webGLData {Array} */ -WebGLStencilManager.prototype.popStencil = function (graphics, webGLData) { +WebGLStencilManager.prototype.popStencil = function (graphics, webGLData) +{ var gl = this.renderer.gl; this.stencilStack.pop(); this.count--; - if (this.stencilStack.length === 0) { + if (this.stencilStack.length === 0) + { // the stack is empty! gl.disable(gl.STENCIL_TEST); } - else { + else + { var level = this.count; @@ -192,14 +211,17 @@ gl.colorMask(false, false, false, false); - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { this.reverse = !this.reverse; - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } @@ -213,31 +235,38 @@ // draw the triangle strip! gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); - if (!this.reverse) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); } } - else { + else + { // console.log("<<>>") - if (!this.reverse) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } - else { + 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) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); } } @@ -253,7 +282,8 @@ * Destroys the mask stack. * */ -WebGLStencilManager.prototype.destroy = function () { +WebGLStencilManager.prototype.destroy = function () +{ this.renderer = null; this.stencilStack = null; }; diff --git a/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js b/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js index 913ba5e..1ea7d19 100644 --- a/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js +++ b/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function ComplexPrimitiveShader(gl) { +function ComplexPrimitiveShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -24,7 +25,8 @@ 'uniform float flipY;', 'varying vec4 vColor;', - 'void main(void) {', + '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);', @@ -37,7 +39,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = vColor;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/FastShader.js b/src/core/renderers/webgl/shaders/FastShader.js index bd2e29a..2e5e060 100644 --- a/src/core/renderers/webgl/shaders/FastShader.js +++ b/src/core/renderers/webgl/shaders/FastShader.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function FastShader(gl) { +function FastShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -28,7 +29,8 @@ 'const vec2 center = vec2(-1.0, 1.0);', - 'void main(void) {', + 'void main(void) + {', ' vec2 v;', ' vec2 sv = aVertexPosition * aScale;', ' v.x = (sv.x) * cos(aRotation) - (sv.y) * sin(aRotation);', @@ -49,7 +51,8 @@ 'uniform sampler2D uSampler;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/PrimitiveShader.js b/src/core/renderers/webgl/shaders/PrimitiveShader.js index 6f25409..a25f54f 100644 --- a/src/core/renderers/webgl/shaders/PrimitiveShader.js +++ b/src/core/renderers/webgl/shaders/PrimitiveShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function PrimitiveShader(gl) { +function PrimitiveShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -23,7 +24,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + '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);', @@ -36,7 +38,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = vColor;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/Shader.js b/src/core/renderers/webgl/shaders/Shader.js index f8964f5..fd75ef5 100644 --- a/src/core/renderers/webgl/shaders/Shader.js +++ b/src/core/renderers/webgl/shaders/Shader.js @@ -6,7 +6,8 @@ * @param [fragmentSrc] {string} The source of the fragment shader. * @param [vertexSrc] {string} The source of the vertex shader. */ -function Shader(gl, vertexSrc, fragmentSrc, customUniforms, customAttributes) { +function Shader(gl, vertexSrc, fragmentSrc, customUniforms, customAttributes) +{ /** * @member {number} * @readonly @@ -33,7 +34,8 @@ dimensions: { type: '4f', value: new Float32Array(4) } }; - for (var u in customUniforms) { + for (var u in customUniforms) + { this.uniforms[u] = customUniforms[u]; } @@ -43,7 +45,8 @@ aColor: 0 }; - for (var a in customAttributes) { + for (var a in customAttributes) + { this.attributes[a] = customAttributes[a]; } @@ -66,7 +69,8 @@ 'const vec2 center = vec2(-1.0, 1.0);', - 'void main(void) {', + 'void main(void) + {', ' gl_Position = vec4( ((aVertexPosition + offsetVector) / projectionVector) + center , 0.0, 1.0);', ' vTextureCoord = aTextureCoord;', ' vColor = vec4(aColor.rgb * aColor.a, aColor.a);', @@ -85,7 +89,8 @@ 'uniform sampler2D uSampler;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;', '}' ].join('\n'); @@ -96,7 +101,8 @@ Shader.prototype.constructor = Shader; module.exports = Shader; -Shader.prototype.init = function () { +Shader.prototype.init = function () +{ this.compile(); this.gl.useProgram(this.program); @@ -105,14 +111,18 @@ this.cacheAttributeLocations(Object.keys(this.attributes)); }; -Shader.prototype.cacheUniformLocations = function (keys) { - for (var i = 0; i < keys.length; ++i) { +Shader.prototype.cacheUniformLocations = function (keys) +{ + for (var i = 0; i < keys.length; ++i) + { this.uniforms[keys[i]]._location = this.gl.getUniformLocation(this.program, keys[i]); } }; -Shader.prototype.cacheAttributeLocations = function (keys) { - for (var i = 0; i < keys.length; ++i) { +Shader.prototype.cacheAttributeLocations = function (keys) +{ + for (var i = 0; i < keys.length; ++i) + { this.attributes[keys[i]] = this.gl.getAttribLocation(this.program, keys[i]); } @@ -124,14 +134,16 @@ // 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.attributes.aColor === -1) { + // if (this.attributes.aColor === -1) + { // this.attributes.aColor = 2; // } // End worst hack eva // }; -Shader.prototype.compile = function () { +Shader.prototype.compile = function () +{ var gl = this.gl; var glVertShader = this._glCompile(gl.VERTEX_SHADER, this.vertexSrc); @@ -144,13 +156,15 @@ gl.linkProgram(program); // if linking fails, then log and cleanup - if (!gl.getProgramParameter(program, gl.LINK_STATUS)) { + if (!gl.getProgramParameter(program, gl.LINK_STATUS)) + { window.console.error('Pixi.js Error: Could not initialize shader.'); window.console.error('gl.VALIDATE_STATUS', gl.getProgramParameter(program, gl.VALIDATE_STATUS)); window.console.error('gl.getError()', gl.getError()); // if there is a program info log, log it - if (gl.getProgramInfoLog(program) !== '') { + if (gl.getProgramInfoLog(program) !== '') + { window.console.warn('Pixi.js Warning: gl.getProgramInfoLog()', gl.getProgramInfoLog(program)); } @@ -165,18 +179,21 @@ return (this.program = program); }; -Shader.prototype.syncUniforms = function () { +Shader.prototype.syncUniforms = function () +{ var gl = this.gl; this.textureCount = 1; - for (var key in this.uniforms) { + for (var key in this.uniforms) + { var uniform = this.uniforms[key], location = uniform._location, value = uniform.value, i, il; - switch (uniform.type) { + switch (uniform.type) + { // single int value case 'i': case '1i': @@ -282,7 +299,8 @@ // a Color Value case 'c': - if (typeof value === 'number') { + if (typeof value === 'number') + { value = utils.hex2rgb(value); } @@ -311,11 +329,13 @@ // array of 2D Point objects case 'v2v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(2 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 2] = value[i].x; uniform._array[i * 2 + 1] = value[i].y; } @@ -325,11 +345,13 @@ // array of 3D Point objects case 'v3v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(3 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 3] = value[i].x; uniform._array[i * 3 + 1] = value[i].y; uniform._array[i * 3 + 2] = value[i].z; @@ -341,11 +363,13 @@ // array of 4D Point objects case 'v4v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(4 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 4] = value[i].x; uniform._array[i * 4 + 1] = value[i].y; uniform._array[i * 4 + 2] = value[i].z; @@ -359,7 +383,8 @@ // PIXI.Texture case 't': case 'sampler2D': - if (!uniform.value || !uniform.value.baseTexture || !uniform.value.baseTexture.hasLoaded) { + if (!uniform.value || !uniform.value.baseTexture || !uniform.value.baseTexture.hasLoaded) + { break; } @@ -376,7 +401,8 @@ this.textureCount++; // initialize the texture if we haven't yet - if (!uniform._init) { + if (!uniform._init) + { this.initSampler2D(uniform); uniform._init = true; @@ -394,11 +420,13 @@ * Initialises a Sampler2D uniform (which may only be available later on after initUniforms once the texture has loaded) * */ -Shader.prototype.initSampler2D = function (uniform) { +Shader.prototype.initSampler2D = function (uniform) +{ var gl = this.gl; // Extended texture data - if (uniform.textureData) { + if (uniform.textureData) + { var data = uniform.textureData; // GLTexture = mag linear, min linear_mipmap_linear, wrap repeat + gl.generateMipmap(gl.TEXTURE_2D); @@ -417,14 +445,16 @@ var wrapT = (data.wrapT) ? data.wrapT : gl.CLAMP_TO_EDGE; var format = (data.luminance) ? gl.LUMINANCE : gl.RGBA; - if (data.repeat) { + if (data.repeat) + { wrapS = gl.REPEAT; wrapT = gl.REPEAT; } gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, !!data.flipY); - if (data.width) { + if (data.width) + { var width = (data.width) ? data.width : 512; var height = (data.height) ? data.height : 2; var border = (data.border) ? data.border : 0; @@ -432,7 +462,8 @@ // 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 { + 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); } @@ -448,7 +479,8 @@ * Destroys the shader. * */ -Shader.prototype.destroy = function () { +Shader.prototype.destroy = function () +{ this.gl.deleteProgram(this.program); this.gl = null; @@ -459,13 +491,15 @@ this.fragmentSrc = null; }; -Shader.prototype._glCompile = function (type, src) { +Shader.prototype._glCompile = function (type, src) +{ var shader = this.gl.createShader(type); this.gl.shaderSource(shader, src); this.gl.compileShader(shader); - if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) { + if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) + { window.console.log(this.gl.getShaderInfoLog(shader)); return null; } diff --git a/src/core/renderers/webgl/shaders/StripShader.js b/src/core/renderers/webgl/shaders/StripShader.js index 193f6e1..a7abcc6 100644 --- a/src/core/renderers/webgl/shaders/StripShader.js +++ b/src/core/renderers/webgl/shaders/StripShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function StripShader(gl) { +function StripShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -20,7 +21,8 @@ 'varying vec2 vTextureCoord;', - 'void main(void) {', + '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);', @@ -36,7 +38,8 @@ 'varying vec2 vTextureCoord;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vec2(vTextureCoord.x, vTextureCoord.y)) * alpha;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/utils/FilterTexture.js b/src/core/renderers/webgl/utils/FilterTexture.js index d2c8423..4433d44 100644 --- a/src/core/renderers/webgl/utils/FilterTexture.js +++ b/src/core/renderers/webgl/utils/FilterTexture.js @@ -8,7 +8,8 @@ * @param height {number} the vertical range of the filter * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values */ -function FilterTexture(gl, width, height, scaleMode) { +function FilterTexture(gl, width, height, scaleMode) +{ /** * @member {WebGLContext} */ @@ -59,7 +60,8 @@ * Clears the filter texture. * */ -FilterTexture.prototype.clear = function () { +FilterTexture.prototype.clear = function () +{ var gl = this.gl; gl.clearColor(0,0,0, 0); @@ -72,8 +74,10 @@ * @param width {number} the new width of the texture * @param height {number} the new height of the texture */ -FilterTexture.prototype.resize = function (width, height) { - if (this.width === width && this.height === height) { +FilterTexture.prototype.resize = function (width, height) +{ + if (this.width === width && this.height === height) + { return; } @@ -96,7 +100,8 @@ * Destroys the filter texture. * */ -FilterTexture.prototype.destroy = function () { +FilterTexture.prototype.destroy = function () +{ var gl = this.gl; gl.deleteFramebuffer( this.frameBuffer ); gl.deleteTexture( this.texture ); diff --git a/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js b/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js index c4721e9..a63f4d7 100644 --- a/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js +++ b/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js @@ -14,7 +14,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this sprite batch works for. */ -function WebGLFastSpriteBatch(renderer) { +function WebGLFastSpriteBatch(renderer) +{ /** * The renderer instance this sprite batch operates on. * @@ -91,7 +92,8 @@ */ this.lastIndexCount = 0; - for (var i=0, j=0; i < numIndices; i += 6, j += 4) { + 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; @@ -144,7 +146,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.setupContext(); }); } @@ -157,7 +160,8 @@ * * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLFastSpriteBatch.prototype.setupContext = function () { +WebGLFastSpriteBatch.prototype.setupContext = function () +{ var gl = this.renderer.gl; // create a couple of buffers @@ -177,7 +181,8 @@ /** * @param spriteBatch {SpriteBatch} The SpriteBatch container to prepare for. */ -WebGLFastSpriteBatch.prototype.begin = function (spriteBatch) { +WebGLFastSpriteBatch.prototype.begin = function (spriteBatch) +{ this.shader = this.renderer.shaderManager.fastShader; this.matrix = spriteBatch.worldTransform.toArray(true); @@ -187,33 +192,38 @@ /** */ -WebGLFastSpriteBatch.prototype.end = function () { +WebGLFastSpriteBatch.prototype.end = function () +{ this.flush(); }; /** * @param spriteBatch {SpriteBatch} The SpriteBatch container to render. */ -WebGLFastSpriteBatch.prototype.render = function (spriteBatch) { +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) { + if (!sprite.texture._uvs) + { return; } this.currentBaseTexture = sprite.texture.baseTexture; // check blend mode - if (sprite.blendMode !== this.renderer.blendModeManager.currentBlendMode) { + if (sprite.blendMode !== this.renderer.blendModeManager.currentBlendMode) + { this.flush(); this.renderer.blendModeManager.setBlendMode(sprite.blendMode); } - for (var i=0,j= children.length; i= this.size) { + if (this.currentBatchSize >= this.size) + { this.flush(); } }; @@ -362,29 +379,35 @@ /** * */ -WebGLFastSpriteBatch.prototype.flush = function () { +WebGLFastSpriteBatch.prototype.flush = function () +{ // If the batch is length 0 then return as there is nothing to draw - if (this.currentBatchSize === 0) { + if (this.currentBatchSize === 0) + { return; } var gl = this.renderer.gl; // bind the current texture - if (!this.currentBaseTexture._glTextures[gl.id]) { + if (!this.currentBaseTexture._glTextures[gl.id]) + { this.renderer.updateTexture(this.currentBaseTexture, gl); } //TODO-SHOUD THIS BE ELSE??!?!?! - else { + else + { gl.bindTexture(gl.TEXTURE_2D, this.currentBaseTexture._glTextures[gl.id]); } // upload the verts to the buffer - if (this.currentBatchSize > ( this.size * 0.5 ) ) { + if (this.currentBatchSize > ( this.size * 0.5 ) ) + { gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); } - else { + else + { var view = this.vertices.subarray(0, this.currentBatchSize * this.vertByteSize); gl.bufferSubData(gl.ARRAY_BUFFER, 0, view); @@ -405,14 +428,16 @@ * Ends the batch and flushes * */ -WebGLFastSpriteBatch.prototype.stop = function () { +WebGLFastSpriteBatch.prototype.stop = function () +{ this.flush(); }; /** * */ -WebGLFastSpriteBatch.prototype.start = function () { +WebGLFastSpriteBatch.prototype.start = function () +{ var gl = this.renderer.gl; // bind the main texture diff --git a/src/core/renderers/webgl/utils/WebGLGraphics.js b/src/core/renderers/webgl/utils/WebGLGraphics.js index 55f4911..ab8f46e 100644 --- a/src/core/renderers/webgl/utils/WebGLGraphics.js +++ b/src/core/renderers/webgl/utils/WebGLGraphics.js @@ -19,7 +19,8 @@ * @param graphics {Graphics} * @param renderer {WebGLRenderer} */ -WebGLGraphics.renderGraphics = function (graphics, renderer) {//projection, offset) { +WebGLGraphics.renderGraphics = function (graphics, renderer) {//projection, offset) +{ var gl = renderer.gl; var projection = renderer.projection, @@ -27,7 +28,8 @@ shader = renderer.shaderManager.primitiveShader, webGLData; - if (graphics.dirty) { + if (graphics.dirty) + { WebGLGraphics.updateGraphics(graphics, gl); } @@ -35,8 +37,10 @@ // This could be speeded up for sure! - for (var i = 0; i < webGL.data.length; i++) { - if (webGL.data[i].mode === 1) { + for (var i = 0; i < webGL.data.length; i++) + { + if (webGL.data[i].mode === 1) + { webGLData = webGL.data[i]; renderer.stencilManager.pushStencil(graphics, webGLData, renderer); @@ -46,7 +50,8 @@ renderer.stencilManager.popStencil(graphics, webGLData, renderer); } - else { + else + { webGLData = webGL.data[i]; @@ -84,12 +89,14 @@ * @param graphicsData {Graphics} The graphics object to update * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLGraphics.updateGraphics = function (graphics, gl) { +WebGLGraphics.updateGraphics = function (graphics, gl) +{ // get the contexts graphics object var webGL = graphics._webGL[gl.id]; // if the graphics object does not exist in the webGL context time to create it! - if (!webGL) { + if (!webGL) + { webGL = graphics._webGL[gl.id] = {lastIndex:0, data:[], gl:gl}; } @@ -99,11 +106,13 @@ var i; // if the user cleared the graphics object we will need to clear every object - if (graphics.clearDirty) { + if (graphics.clearDirty) + { graphics.clearDirty = false; // lop through and return all the webGLDatas to the object pool so than can be reused later on - for (i = 0; i < webGL.data.length; i++) { + for (i = 0; i < webGL.data.length; i++) + { var graphicsData = webGL.data[i]; graphicsData.reset(); WebGLGraphics.graphicsDataPool.push( graphicsData ); @@ -119,58 +128,72 @@ // loop through the graphics datas and construct each one.. // if the object is a complex fill then the new stencil buffer technique will be used // other wise graphics objects will be pushed into a batch.. - for (i = webGL.lastIndex; i < graphics.graphicsData.length; i++) { + for (i = webGL.lastIndex; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { // need to add the points the the graphics object.. data.points = data.shape.points.slice(); - if (data.shape.closed) { + if (data.shape.closed) + { // close the poly if the value is true! - if (data.points[0] !== data.points[data.points.length-2] || data.points[1] !== data.points[data.points.length-1]) { + if (data.points[0] !== data.points[data.points.length-2] || data.points[1] !== data.points[data.points.length-1]) + { data.points.push(data.points[0], data.points[1]); } } // MAKE SURE WE HAVE THE CORRECT TYPE.. - if (data.fill) { - if (data.points.length >= 6) { - if (data.points.length < 6 * 2) { + if (data.fill) + { + if (data.points.length >= 6) + { + if (data.points.length < 6 * 2) + { webGLData = WebGLGraphics.switchMode(webGL, 0); var canDrawUsingSimple = WebGLGraphics.buildPoly(data, webGLData); // console.log(canDrawUsingSimple); - if (!canDrawUsingSimple) { + if (!canDrawUsingSimple) + { // console.log("<>>>") webGLData = WebGLGraphics.switchMode(webGL, 1); WebGLGraphics.buildComplexPoly(data, webGLData); } } - else { + else + { webGLData = WebGLGraphics.switchMode(webGL, 1); WebGLGraphics.buildComplexPoly(data, webGLData); } } } - if (data.lineWidth > 0) { + if (data.lineWidth > 0) + { webGLData = WebGLGraphics.switchMode(webGL, 0); WebGLGraphics.buildLine(data, webGLData); } } - else { + else + { webGLData = WebGLGraphics.switchMode(webGL, 0); - if (data.type === CONST.SHAPES.RECT) { + if (data.type === CONST.SHAPES.RECT) + { WebGLGraphics.buildRectangle(data, webGLData); } - else if (data.type === CONST.SHAPES.CIRC || data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.CIRC || data.type === CONST.SHAPES.ELIP) + { WebGLGraphics.buildCircle(data, webGLData); } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { WebGLGraphics.buildRoundedRectangle(data, webGLData); } } @@ -179,10 +202,12 @@ } // upload all the dirty data... - for (i = 0; i < webGL.data.length; i++) { + for (i = 0; i < webGL.data.length; i++) + { webGLData = webGL.data[i]; - if (webGLData.dirty) { + if (webGLData.dirty) + { webGLData.upload(); } } @@ -194,18 +219,22 @@ * @param webGL {WebGLContext} * @param type {number} */ -WebGLGraphics.switchMode = function (webGL, type) { +WebGLGraphics.switchMode = function (webGL, type) +{ var webGLData; - if (!webGL.data.length) { + if (!webGL.data.length) + { webGLData = WebGLGraphics.graphicsDataPool.pop() || new WebGLGraphicsData(webGL.gl); webGLData.mode = type; webGL.data.push(webGLData); } - else { + else + { webGLData = webGL.data[webGL.data.length-1]; - if (webGLData.mode !== type || type === 1) { + if (webGLData.mode !== type || type === 1) + { webGLData = WebGLGraphics.graphicsDataPool.pop() || new WebGLGraphicsData(webGL.gl); webGLData.mode = type; webGL.data.push(webGLData); @@ -225,7 +254,8 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildRectangle = function (graphicsData, webGLData) { +WebGLGraphics.buildRectangle = function (graphicsData, webGLData) +{ // --- // // need to convert points to a nice regular data // @@ -235,7 +265,8 @@ var width = rectData.width; var height = rectData.height; - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -265,7 +296,8 @@ indices.push(vertPos, vertPos, vertPos+1, vertPos+2, vertPos+3, vertPos+3); } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = [x, y, @@ -289,7 +321,8 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildRoundedRectangle = function (graphicsData, webGLData) { +WebGLGraphics.buildRoundedRectangle = function (graphicsData, webGLData) +{ var rrectData = graphicsData.shape; var x = rrectData.x; var y = rrectData.y; @@ -305,7 +338,8 @@ recPoints = recPoints.concat(WebGLGraphics.quadraticBezierCurve(x + width, y + radius, x + width, y, x + width - radius, y)); recPoints = recPoints.concat(WebGLGraphics.quadraticBezierCurve(x + radius, y, x, y, x, y + radius)); - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -323,7 +357,8 @@ // var i = 0; - for (i = 0; i < triangles.length; i+=3) { + for (i = 0; i < triangles.length; i+=3) + { indices.push(triangles[i] + vecPos); indices.push(triangles[i] + vecPos); indices.push(triangles[i+1] + vecPos); @@ -332,12 +367,14 @@ } - for (i = 0; i < recPoints.length; i++) { + for (i = 0; i < recPoints.length; i++) + { verts.push(recPoints[i], recPoints[++i], r, g, b, alpha); } } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = recPoints; @@ -362,7 +399,8 @@ * @param toY {number} Destination point y * @return {number[]} */ -WebGLGraphics.quadraticBezierCurve = function (fromX, fromY, cpX, cpY, toX, toY) { +WebGLGraphics.quadraticBezierCurve = function (fromX, fromY, cpX, cpY, toX, toY) +{ var xa, ya, @@ -373,14 +411,16 @@ n = 20, points = []; - function getPt(n1 , n2, perc) { + function getPt(n1 , n2, perc) + { var diff = n2 - n1; return n1 + ( diff * perc ); } var j = 0; - for (var i = 0; i <= n; i++ ) { + for (var i = 0; i <= n; i++ ) + { j = i / n; // The Green Line @@ -406,7 +446,8 @@ * @param graphicsData {Graphics} The graphics object to draw * @param webGLData {object} */ -WebGLGraphics.buildCircle = function (graphicsData, webGLData) { +WebGLGraphics.buildCircle = function (graphicsData, webGLData) +{ // need to convert points to a nice regular data var circleData = graphicsData.shape; var x = circleData.x; @@ -415,11 +456,13 @@ var height; // TODO - bit hacky?? - if (graphicsData.type === CONST.SHAPES.CIRC) { + if (graphicsData.type === CONST.SHAPES.CIRC) + { width = circleData.radius; height = circleData.radius; } - else { + else + { width = circleData.width; height = circleData.height; } @@ -429,7 +472,8 @@ var i = 0; - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -444,7 +488,8 @@ indices.push(vecPos); - for (i = 0; i < totalSegs + 1 ; i++) { + for (i = 0; i < totalSegs + 1 ; i++) + { verts.push(x,y, r, g, b, alpha); verts.push(x + Math.sin(seg * i) * width, @@ -457,12 +502,14 @@ indices.push(vecPos-1); } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = []; - for (i = 0; i < totalSegs + 1; i++) { + for (i = 0; i < totalSegs + 1; i++) + { graphicsData.points.push(x + Math.sin(seg * i) * width, y + Math.cos(seg * i) * height); } @@ -481,18 +528,22 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildLine = function (graphicsData, webGLData) { +WebGLGraphics.buildLine = function (graphicsData, webGLData) +{ // TODO OPTIMISE! var i = 0; var points = graphicsData.points; - if (points.length === 0) { + if (points.length === 0) + { return; } // if the line width is an odd number add 0.5 to align to a whole pixel - if (graphicsData.lineWidth%2) { - for (i = 0; i < points.length; i++) { + if (graphicsData.lineWidth%2) + { + for (i = 0; i < points.length; i++) + { points[i] += 0.5; } } @@ -502,7 +553,8 @@ var lastPoint = new math.Point(points[points.length - 2], points[points.length - 1]); // if the first point is the last point - gonna have issues :) - if (firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) { + if (firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) + { // need to clone as we are going to slightly modify the shape.. points = points.slice(); @@ -562,7 +614,8 @@ verts.push(p1x + perpx , p1y + perpy, r, g, b, alpha); - for (i = 1; i < length-1; i++) { + for (i = 1; i < length-1; i++) + { p1x = points[(i-1)*2]; p1y = points[(i-1)*2 + 1]; @@ -599,7 +652,8 @@ denom = a1*b2 - a2*b1; - if (Math.abs(denom) < 0.1 ) { + if (Math.abs(denom) < 0.1 ) + { denom+=10.1; verts.push(p2x - perpx , p2y - perpy, @@ -618,7 +672,8 @@ pdist = (px -p2x) * (px -p2x) + (py -p2y) + (py -p2y); - if (pdist > 140 * 140) { + if (pdist > 140 * 140) + { perp3x = perpx - perp2x; perp3y = perpy - perp2y; @@ -639,7 +694,8 @@ indexCount++; } - else { + else + { verts.push(px , py); verts.push(r, g, b, alpha); @@ -672,7 +728,8 @@ indices.push(indexStart); - for (i = 0; i < indexCount; i++) { + for (i = 0; i < indexCount; i++) + { indices.push(indexStart++); } @@ -687,11 +744,13 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildComplexPoly = function (graphicsData, webGLData) { +WebGLGraphics.buildComplexPoly = function (graphicsData, webGLData) +{ //TODO - no need to copy this as it gets turned into a FLoat32Array anyways.. var points = graphicsData.points.slice(); - if (points.length < 6) { + if (points.length < 6) + { return; } @@ -711,7 +770,8 @@ var x,y; // get size.. - for (var i = 0; i < points.length; i+=2) { + for (var i = 0; i < points.length; i+=2) + { x = points[i]; y = points[i+1]; @@ -732,7 +792,8 @@ //TODO - this aint needed! var length = points.length / 2; - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { indices.push( i ); } @@ -746,10 +807,12 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildPoly = function (graphicsData, webGLData) { +WebGLGraphics.buildPoly = function (graphicsData, webGLData) +{ var points = graphicsData.points; - if (points.length < 6) { + if (points.length < 6) + { return; } // get first and last point.. figure out the middle! @@ -767,7 +830,8 @@ var triangles = utils.PolyK.Triangulate(points); - if (!triangles) { + if (!triangles) + { return false; } @@ -775,7 +839,8 @@ var i = 0; - for (i = 0; i < triangles.length; i+=3) { + for (i = 0; i < triangles.length; i+=3) + { indices.push(triangles[i] + vertPos); indices.push(triangles[i] + vertPos); indices.push(triangles[i+1] + vertPos); @@ -783,7 +848,8 @@ indices.push(triangles[i+2] + vertPos); } - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { verts.push(points[i * 2], points[i * 2 + 1], r, g, b, alpha); } diff --git a/src/core/renderers/webgl/utils/WebGLGraphicsData.js b/src/core/renderers/webgl/utils/WebGLGraphicsData.js index c56d05e..c739ba7 100644 --- a/src/core/renderers/webgl/utils/WebGLGraphicsData.js +++ b/src/core/renderers/webgl/utils/WebGLGraphicsData.js @@ -2,7 +2,8 @@ * @class * @private */ -function WebGLGraphicsData(gl) { +function WebGLGraphicsData(gl) +{ this.gl = gl; //TODO does this need to be split before uploding?? @@ -22,7 +23,8 @@ /** * */ -WebGLGraphicsData.prototype.reset = function () { +WebGLGraphicsData.prototype.reset = function () +{ this.points.length = 0; this.indices.length = 0; }; @@ -30,7 +32,8 @@ /** * */ -WebGLGraphicsData.prototype.upload = function () { +WebGLGraphicsData.prototype.upload = function () +{ var gl = this.gl; // this.lastIndex = graphics.graphicsData.length; diff --git a/src/core/renderers/webgl/utils/WebGLSpriteBatch.js b/src/core/renderers/webgl/utils/WebGLSpriteBatch.js index 96eaa52..55befbb 100644 --- a/src/core/renderers/webgl/utils/WebGLSpriteBatch.js +++ b/src/core/renderers/webgl/utils/WebGLSpriteBatch.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this sprite batch works for. */ -function WebGLSpriteBatch(renderer) { +function WebGLSpriteBatch(renderer) +{ /** * * @@ -88,7 +89,8 @@ */ this.lastIndexCount = 0; - for (var i=0, j=0; i < numIndices; i += 6, j += 4) { + 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; @@ -162,7 +164,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.setupContext(); }); } @@ -173,7 +176,8 @@ /** * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLSpriteBatch.prototype.setupContext = function () { +WebGLSpriteBatch.prototype.setupContext = function () +{ var gl = this.renderer.gl; // setup default shader @@ -198,7 +202,8 @@ /** * */ -WebGLSpriteBatch.prototype.begin = function () { +WebGLSpriteBatch.prototype.begin = function () +{ // this.shader = this.renderer.shaderManager.defaultShader; this.start(); @@ -206,19 +211,22 @@ /** */ -WebGLSpriteBatch.prototype.end = function () { +WebGLSpriteBatch.prototype.end = function () +{ this.flush(); }; /** * @param sprite {Sprite} the sprite to render when using this spritebatch */ -WebGLSpriteBatch.prototype.render = function (sprite) { +WebGLSpriteBatch.prototype.render = function (sprite) +{ var texture = sprite.texture; //TODO set blend modes.. // check texture.. - if (this.currentBatchSize >= this.size) { + if (this.currentBatchSize >= this.size) + { this.flush(); this.currentBaseTexture = texture.baseTexture; } @@ -227,7 +235,8 @@ var uvs = texture._uvs; // if the uvs have not updated then no point rendering just yet! - if (!uvs) { + if (!uvs) + { return; } @@ -237,7 +246,8 @@ var w0, w1, h0, h1; - if (texture.trim) { + 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; @@ -248,7 +258,8 @@ h0 = h1 + texture.crop.height; } - else { + else + { w0 = (texture.frame.width ) * (1-aX); w1 = (texture.frame.width ) * -aX; @@ -272,7 +283,8 @@ var colors = this.colors; var positions = this.positions; - if (this.renderer.roundPixels) { + if (this.renderer.roundPixels) + { // xy positions[index] = a * w1 + c * h1 + tx | 0; positions[index+1] = d * h1 + b * w1 + ty | 0; @@ -289,7 +301,8 @@ positions[index+15] = a * w1 + c * h0 + tx | 0; positions[index+16] = d * h0 + b * w1 + ty | 0; } - else { + else + { // xy positions[index] = a * w1 + c * h1 + tx; positions[index+1] = d * h1 + b * w1 + ty; @@ -338,11 +351,13 @@ * * @param sprite {TilingSprite} the tilingSprite to render */ -WebGLSpriteBatch.prototype.renderTilingSprite = function (tilingSprite) { +WebGLSpriteBatch.prototype.renderTilingSprite = function (tilingSprite) +{ var texture = tilingSprite.tilingTexture; // check texture.. - if (this.currentBatchSize >= this.size) { + if (this.currentBatchSize >= this.size) + { //return; this.flush(); this.currentBaseTexture = texture.baseTexture; @@ -351,7 +366,8 @@ // set the textures uvs temporarily // TODO create a separate texture so that we can tile part of a texture - if (!tilingSprite._uvs) { + if (!tilingSprite._uvs) + { tilingSprite._uvs = new TextureUvs(); } @@ -454,16 +470,19 @@ * Renders the content and empties the current batch. * */ -WebGLSpriteBatch.prototype.flush = function () { +WebGLSpriteBatch.prototype.flush = function () +{ // If the batch is length 0 then return as there is nothing to draw - if (this.currentBatchSize === 0) { + if (this.currentBatchSize === 0) + { return; } var gl = this.renderer.gl; var shader; - if (this.dirty) { + if (this.dirty) + { this.dirty = false; // bind the main texture gl.activeTexture(gl.TEXTURE0); @@ -482,10 +501,12 @@ } // upload the verts to the buffer - if (this.currentBatchSize > ( this.size * 0.5 ) ) { + if (this.currentBatchSize > ( this.size * 0.5 ) ) + { gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); } - else { + else + { var view = this.positions.subarray(0, this.currentBatchSize * this.vertByteSize); gl.bufferSubData(gl.ARRAY_BUFFER, 0, view); } @@ -502,7 +523,8 @@ var shaderSwap = false; var sprite; - for (var i = 0, j = this.currentBatchSize; i < j; i++) { + for (var i = 0, j = this.currentBatchSize; i < j; i++) + { sprite = this.sprites[i]; @@ -513,24 +535,28 @@ blendSwap = currentBlendMode !== nextBlendMode; shaderSwap = currentShader !== nextShader; // should I use uuidS??? - if (currentBaseTexture !== nextTexture || blendSwap || shaderSwap) { + if (currentBaseTexture !== nextTexture || blendSwap || shaderSwap) + { this.renderBatch(currentBaseTexture, batchSize, start); start = i; batchSize = 0; currentBaseTexture = nextTexture; - if (blendSwap) { + if (blendSwap) + { currentBlendMode = nextBlendMode; this.renderer.blendModeManager.setBlendMode( currentBlendMode ); } - if (shaderSwap) { + if (shaderSwap) + { currentShader = nextShader; shader = currentShader.shaders ? currentShader.shaders[gl.id] : currentShader; - if (!shader) { + if (!shader) + { shader = new Shader(gl, null, currentShader.fragmentSrc, currentShader.uniforms); currentShader.shaders[gl.id] = shader; } @@ -538,7 +564,8 @@ // set shader function??? this.renderer.shaderManager.setShader(shader); - if (shader.dirty) { + if (shader.dirty) + { shader.syncUniforms(); } @@ -569,17 +596,21 @@ * @param size {number} * @param startIndex {number} */ -WebGLSpriteBatch.prototype.renderBatch = function (texture, size, startIndex) { - if (size === 0) { +WebGLSpriteBatch.prototype.renderBatch = function (texture, size, startIndex) +{ + if (size === 0) + { return; } var gl = this.renderer.gl; - if (!texture._glTextures[gl.id]) { + if (!texture._glTextures[gl.id]) + { this.renderer.updateTexture(texture); } - else { + else + { // bind the current texture gl.bindTexture(gl.TEXTURE_2D, texture._glTextures[gl.id]); } @@ -594,7 +625,8 @@ /** * */ -WebGLSpriteBatch.prototype.stop = function () { +WebGLSpriteBatch.prototype.stop = function () +{ this.flush(); this.dirty = true; }; @@ -602,7 +634,8 @@ /** * */ -WebGLSpriteBatch.prototype.start = function () { +WebGLSpriteBatch.prototype.start = function () +{ this.dirty = true; }; @@ -610,7 +643,8 @@ * Destroys the SpriteBatch. * */ -WebGLSpriteBatch.prototype.destroy = function () { +WebGLSpriteBatch.prototype.destroy = function () +{ this.renderer.gl.deleteBuffer(this.vertexBuffer); this.renderer.gl.deleteBuffer(this.indexBuffer); diff --git a/src/core/textures/BaseTexture.js b/src/core/textures/BaseTexture.js index 2bf77d4..513d358 100644 --- a/src/core/textures/BaseTexture.js +++ b/src/core/textures/BaseTexture.js @@ -10,7 +10,8 @@ * @param source {Image|Canvas} the source object of the texture. * @param [scaleMode=scaleModes.DEFAULT] {number} See {@link scaleModes} for possible values */ -function BaseTexture(source, scaleMode) { +function BaseTexture(source, scaleMode) +{ this.uuid = utils.uuid(); /** @@ -123,7 +124,8 @@ this._needsUpdate = false; // if no source passed don't try to load - if (source) { + if (source) + { this.loadSource(source); } @@ -149,13 +151,16 @@ Object.defineProperties(BaseTexture.prototype, { needsUpdate: { - get: function () { + get: function () + { return this._needsUpdate; }, - set: function (val) { + set: function (val) + { this._needsUpdate = val; - if (val) { + if (val) + { this.emit('update', this); } } @@ -171,9 +176,11 @@ * * The logic state after calling `loadSource` directly or indirectly (eg. `fromImage`, `new BaseTexture`) is: * - * if (texture.hasLoaded) { + * if (texture.hasLoaded) + { * // texture ready for use - * } else if (texture.isLoading) { + * } else if (texture.isLoading) + { * // listen to 'loaded' and/or 'error' events on texture * } else { * // not loading, not going to load UNLESS the source is reloaded @@ -183,12 +190,14 @@ * @protected * @param source {Image|Canvas} the source object of the texture. */ -BaseTexture.prototype.loadSource = function (source) { +BaseTexture.prototype.loadSource = function (source) +{ var wasLoading = this.isLoading; this.hasLoaded = false; this.isLoading = false; - if (wasLoading && this.source) { + if (wasLoading && this.source) + { this.source.onload = null; this.source.onerror = null; } @@ -196,20 +205,24 @@ this.source = source; // Apply source if loaded. Otherwise setup appropriate loading monitors. - if ((this.source.complete || this.source.getContext) && this.source.width && this.source.height) { + if ((this.source.complete || this.source.getContext) && this.source.width && this.source.height) + { this._sourceLoaded(); } - else if(!source.getContext) { + else if(!source.getContext) + { // Image fail / not ready this.isLoading = true; var scope = this; - source.onload = function () { + source.onload = function () + { source.onload = null; source.onerror = null; - if(!scope.isLoading) { + if(!scope.isLoading) + { return; } @@ -219,11 +232,13 @@ scope.emit('loaded', scope); }; - source.onerror = function () { + source.onerror = function () + { source.onload = null; source.onerror = null; - if(!scope.isLoading) { + if(!scope.isLoading) + { return; } @@ -234,24 +249,29 @@ // Per http://www.w3.org/TR/html5/embedded-content-0.html#the-img-element // "The value of `complete` can thus change while a script is executing." // So complete needs to be re-checked after the callbacks have been added.. - if (source.complete) { + if (source.complete) + { this.isLoading = false; // ..and if we're complete now, no need for callbacks source.onload = null; source.onerror = null; - if (source.width && source.height) { + if (source.width && source.height) + { this._sourceLoaded(); // If any previous subscribers possible - if (wasLoading) { + if (wasLoading) + { this.emit('loaded', this); } } - else { + else + { // If any previous subscribers possible - if (wasLoading) { + if (wasLoading) + { this.emit('error', this); } } @@ -265,7 +285,8 @@ * * @private */ -BaseTexture.prototype._sourceLoaded = function () { +BaseTexture.prototype._sourceLoaded = function () +{ this.hasLoaded = true; this.width = this.source.naturalWidth || this.source.width; @@ -278,16 +299,20 @@ * Destroys this base texture * */ -BaseTexture.prototype.destroy = function () { - if (this.imageUrl) { +BaseTexture.prototype.destroy = function () +{ + if (this.imageUrl) + { delete utils.BaseTextureCache[this.imageUrl]; delete utils.TextureCache[this.imageUrl]; this.imageUrl = null; - if (!navigator.isCocoonJS) { + if (!navigator.isCocoonJS) + { this.source.src = ''; } } - else if (this.source && this.source._pixiId) { + else if (this.source && this.source._pixiId) + { delete utils.BaseTextureCache[this.source._pixiId]; } this.source = null; @@ -301,7 +326,8 @@ * memory again. * */ -BaseTexture.prototype.dispose = function () { +BaseTexture.prototype.dispose = function () +{ this.emit('dispose', this); }; @@ -311,7 +337,8 @@ * * @param newSrc {string} the path of the image */ -BaseTexture.prototype.updateSourceImage = function (newSrc) { +BaseTexture.prototype.updateSourceImage = function (newSrc) +{ this.source.src = newSrc; this.loadSource(this.source); }; @@ -326,18 +353,22 @@ * @param [scaleMode=scaleModes.DEFAULT] {number} See {@link scaleModes} for possible values * @return BaseTexture */ -BaseTexture.fromImage = function (imageUrl, crossorigin, scaleMode) { +BaseTexture.fromImage = function (imageUrl, crossorigin, scaleMode) +{ var baseTexture = utils.BaseTextureCache[imageUrl]; - if (crossorigin === undefined && imageUrl.indexOf('data:') !== 0) { + if (crossorigin === undefined && imageUrl.indexOf('data:') !== 0) + { crossorigin = true; } - if (!baseTexture) { + if (!baseTexture) + { // new Image() breaks tex loading in some versions of Chrome. // See https://code.google.com/p/chromium/issues/detail?id=238071 var image = new Image();//document.createElement('img'); - if (crossorigin) { + if (crossorigin) + { image.crossOrigin = ''; } @@ -347,7 +378,8 @@ utils.BaseTextureCache[imageUrl] = baseTexture; // if there is an @2x at the end of the url we are going to assume its a highres image - if ( imageUrl.indexOf(CONST.RETINA_PREFIX + '.') !== -1) { + if ( imageUrl.indexOf(CONST.RETINA_PREFIX + '.') !== -1) + { baseTexture.resolution = 2; } } @@ -363,14 +395,17 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return BaseTexture */ -BaseTexture.fromCanvas = function (canvas, scaleMode) { - if (!canvas._pixiId) { +BaseTexture.fromCanvas = function (canvas, scaleMode) +{ + if (!canvas._pixiId) + { canvas._pixiId = 'canvas_' + utils.uuid(); } var baseTexture = utils.BaseTextureCache[canvas._pixiId]; - if (!baseTexture) { + if (!baseTexture) + { baseTexture = new BaseTexture(canvas, scaleMode); utils.BaseTextureCache[canvas._pixiId] = baseTexture; } diff --git a/src/core/textures/RenderTexture.js b/src/core/textures/RenderTexture.js index 6dad20f..53ae796 100644 --- a/src/core/textures/RenderTexture.js +++ b/src/core/textures/RenderTexture.js @@ -46,8 +46,10 @@ * @param [scaleMode] {number} See {@link scaleModes} for possible values * @param [resolution=1] {number} The resolution of the texture being generated */ -function RenderTexture(renderer, width, height, scaleMode, resolution) { - if (!renderer) { +function RenderTexture(renderer, width, height, scaleMode, resolution) +{ + if (!renderer) + { throw new Error('Unable to create RenderTexture, you must pass a renderer into the constructor.'); } @@ -133,7 +135,8 @@ */ this.renderer = renderer; - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { var gl = this.renderer.gl; this.textureBuffer = new FilterTexture(gl, this.width * this.resolution, this.height * this.resolution, this.baseTexture.scaleMode); @@ -142,7 +145,8 @@ this.render = this.renderWebGL; this.projection = new math.Point(this.width*0.5, -this.height*0.5); } - else { + else + { this.render = this.renderCanvas; this.textureBuffer = new CanvasBuffer(this.width* this.resolution, this.height* this.resolution); this.baseTexture.source = this.textureBuffer.canvas; @@ -167,8 +171,10 @@ * @param height {number} The height to resize to. * @param updateBase {boolean} Should the baseTexture.width and height values be resized as well? */ -RenderTexture.prototype.resize = function (width, height, updateBase) { - if (width === this.width && height === this.height) { +RenderTexture.prototype.resize = function (width, height, updateBase) +{ + if (width === this.width && height === this.height) + { return; } @@ -177,17 +183,20 @@ this.width = this.frame.width = this.crop.width = width; this.height = this.frame.height = this.crop.height = height; - if (updateBase) { + if (updateBase) + { this.baseTexture.width = this.width; this.baseTexture.height = this.height; } - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { this.projection.x = this.width / 2; this.projection.y = -this.height / 2; } - if (!this.valid) { + if (!this.valid) + { return; } @@ -198,12 +207,15 @@ * Clears the RenderTexture. * */ -RenderTexture.prototype.clear = function () { - if (!this.valid) { +RenderTexture.prototype.clear = function () +{ + if (!this.valid) + { return; } - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { this.renderer.gl.bindFramebuffer(this.renderer.gl.FRAMEBUFFER, this.textureBuffer.frameBuffer); } @@ -220,19 +232,23 @@ * @param [restoreWorldTransform=true] {boolean} If true the displayObject's worldTransform/worldAlpha and all children * transformations will be restored. Not restoring this information will be a little faster. */ -RenderTexture.prototype.renderWebGL = function (displayObject, matrix, clear, restoreWorldTransform) { - if (!this.valid) { +RenderTexture.prototype.renderWebGL = function (displayObject, matrix, clear, restoreWorldTransform) +{ + if (!this.valid) + { return; } - if (typeof restoreWorldTransform === 'undefined') { + if (typeof restoreWorldTransform === 'undefined') + { restoreWorldTransform = true; } var tempAlpha, tempTransform; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { tempAlpha = displayObject.worldAlpha; tempTransform = displayObject.worldTransform.toArray(); } @@ -245,7 +261,8 @@ wt.identity(); wt.translate(0, this.projection.y * 2); - if (matrix) { + if (matrix) + { wt.append(matrix); } @@ -258,7 +275,8 @@ var children = displayObject.children; var i, j; - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } @@ -269,7 +287,8 @@ gl.bindFramebuffer(gl.FRAMEBUFFER, this.textureBuffer.frameBuffer ); - if (clear) { + if (clear) + { this.textureBuffer.clear(); } @@ -279,11 +298,13 @@ this.renderer.spriteBatch.dirty = true; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { displayObject.worldAlpha = tempAlpha; displayObject.worldTransform.fromArray(tempTransform); - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } } @@ -300,26 +321,31 @@ * @param [restoreWorldTransform=true] {boolean} If true the displayObject's worldTransform/worldAlpha and all children * transformations will be restored. Not restoring this information will be a little faster. */ -RenderTexture.prototype.renderCanvas = function (displayObject, matrix, clear, restoreWorldTransform) { - if (!this.valid) { +RenderTexture.prototype.renderCanvas = function (displayObject, matrix, clear, restoreWorldTransform) +{ + if (!this.valid) + { return; } - if (typeof restoreWorldTransform === 'undefined') { + if (typeof restoreWorldTransform === 'undefined') + { restoreWorldTransform = true; } var tempAlpha, tempTransform; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { tempAlpha = displayObject.worldAlpha; tempTransform = displayObject.worldTransform.toArray(); } var wt = displayObject.worldTransform; wt.identity(); - if (matrix) { + if (matrix) + { wt.append(matrix); } @@ -330,11 +356,13 @@ var children = displayObject.children; var i, j; - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } - if (clear) { + if (clear) + { this.textureBuffer.clear(); } @@ -348,11 +376,13 @@ this.renderer.resolution = realResolution; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { displayObject.worldAlpha = tempAlpha; displayObject.worldTransform.fromArray(tempTransform); - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } } @@ -363,7 +393,8 @@ * * @return {Image} */ -RenderTexture.prototype.getImage = function () { +RenderTexture.prototype.getImage = function () +{ var image = new Image(); image.src = this.getBase64(); return image; @@ -374,7 +405,8 @@ * * @return {string} A base64 encoded string of the texture. */ -RenderTexture.prototype.getBase64 = function () { +RenderTexture.prototype.getBase64 = function () +{ return this.getCanvas().toDataURL(); }; @@ -383,8 +415,10 @@ * * @return {HTMLCanvasElement} A Canvas element with the texture rendered on. */ -RenderTexture.prototype.getCanvas = function () { - if (this.renderer.type === CONST.WEBGL_RENDERER) { +RenderTexture.prototype.getCanvas = function () +{ + if (this.renderer.type === CONST.WEBGL_RENDERER) + { var gl = this.renderer.gl; var width = this.textureBuffer.width; var height = this.textureBuffer.height; @@ -403,7 +437,8 @@ return tempCanvas.canvas; } - else { + else + { return this.textureBuffer.canvas; } }; diff --git a/src/core/textures/Texture.js b/src/core/textures/Texture.js index 3c65909..e97f0aa 100644 --- a/src/core/textures/Texture.js +++ b/src/core/textures/Texture.js @@ -17,7 +17,8 @@ * @param [crop] {Rectangle} The area of original texture * @param [trim] {Rectangle} Trimmed texture rectangle */ -function Texture(baseTexture, frame, crop, trim) { +function Texture(baseTexture, frame, crop, trim) +{ /** * Does this Texture have any frame data assigned to it? * @@ -25,12 +26,14 @@ */ this.noFrame = false; - if (!frame) { + if (!frame) + { this.noFrame = true; frame = new math.Rectangle(0, 0, 1, 1); } - if (baseTexture instanceof Texture) { + if (baseTexture instanceof Texture) + { baseTexture = baseTexture.baseTexture; } @@ -100,13 +103,16 @@ */ this.crop = crop || new math.Rectangle(0, 0, 1, 1); - if (baseTexture.hasLoaded) { - if (this.noFrame) { + if (baseTexture.hasLoaded) + { + if (this.noFrame) + { frame = new math.Rectangle(0, 0, baseTexture.width, baseTexture.height); } this.frame = frame; } - else { + else + { baseTexture.addEventListener('loaded', this.onBaseTextureLoaded.bind(this)); } } @@ -118,19 +124,23 @@ Object.defineProperties(Texture.prototype, { needsUpdate: { - get: function () { + get: function () + { return this.baseTexture.needsUpdate; }, - set: function (val) { + set: function (val) + { this.baseTexture.needsUpdate = val; } }, frame: { - get: function () { + get: function () + { return this._frame; }, - set: function (frame) { + set: function (frame) + { this._frame = frame; this.noFrame = false; @@ -143,20 +153,23 @@ 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 (!this.trim && (frame.x + frame.width > this.baseTexture.width || frame.y + frame.height > this.baseTexture.height)) + { throw new Error('Texture Error: frame does not fit inside the base Texture dimensions ' + this); } this.valid = frame && frame.width && frame.height && this.baseTexture.source && this.baseTexture.hasLoaded; - if (this.trim) { + 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) { + if (this.valid) + { this._updateUvs(); } } @@ -168,11 +181,13 @@ * * @private */ -Texture.prototype.onBaseTextureLoaded = function () { +Texture.prototype.onBaseTextureLoaded = function () +{ var baseTexture = this.baseTexture; baseTexture.removeEventListener('loaded', this.onLoaded); - if (this.noFrame) { + if (this.noFrame) + { this.frame = new math.Rectangle(0, 0, baseTexture.width, baseTexture.height); } @@ -184,8 +199,10 @@ * * @param destroyBase {boolean} Whether to destroy the base texture as well */ -Texture.prototype.destroy = function (destroyBase) { - if (destroyBase) { +Texture.prototype.destroy = function (destroyBase) +{ + if (destroyBase) + { this.baseTexture.destroy(); } @@ -197,8 +214,10 @@ * * @private */ -Texture.prototype._updateUvs = function () { - if (!this._uvs) { +Texture.prototype._updateUvs = function () +{ + if (!this._uvs) + { this._uvs = new TextureUvs(); } @@ -229,10 +248,12 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return Texture */ -Texture.fromImage = function (imageUrl, crossorigin, scaleMode) { +Texture.fromImage = function (imageUrl, crossorigin, scaleMode) +{ var texture = utils.TextureCache[imageUrl]; - if (!texture) { + if (!texture) + { texture = new Texture(BaseTexture.fromImage(imageUrl, crossorigin, scaleMode)); utils.TextureCache[imageUrl] = texture; } @@ -248,9 +269,11 @@ * @param frameId {string} The frame id of the texture * @return Texture */ -Texture.fromFrame = function (frameId) { +Texture.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache '); } return texture; @@ -264,7 +287,8 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return {Texture} */ -Texture.fromCanvas = function (canvas, scaleMode) { +Texture.fromCanvas = function (canvas, scaleMode) +{ return new Texture(BaseTexture.fromCanvas(canvas, scaleMode)); }; @@ -276,7 +300,8 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return {Texture} A Texture */ -Texture.fromVideo = function (video, scaleMode) { +Texture.fromVideo = function (video, scaleMode) +{ return new Texture(VideoBaseTexture.baseTextureFromVideo(video, scaleMode)); }; @@ -287,7 +312,8 @@ * @param texture {Texture} The Texture to add to the cache. * @param id {string} The id that the texture will be stored against. */ -Texture.addTextureToCache = function (texture, id) { +Texture.addTextureToCache = function (texture, id) +{ utils.TextureCache[id] = texture; }; @@ -298,7 +324,8 @@ * @param id {string} The id of the texture to be removed * @return {Texture} The texture that was removed */ -Texture.removeTextureFromCache = function (id) { +Texture.removeTextureFromCache = function (id) +{ var texture = utils.TextureCache[id]; delete utils.TextureCache[id]; diff --git a/src/core/textures/TextureUvs.js b/src/core/textures/TextureUvs.js index b9bbb58..5424d52 100644 --- a/src/core/textures/TextureUvs.js +++ b/src/core/textures/TextureUvs.js @@ -1,4 +1,5 @@ -function TextureUvs() { +function TextureUvs() +{ this.x0 = 0; this.y0 = 0; diff --git a/src/core/textures/VideoBaseTexture.js b/src/core/textures/VideoBaseTexture.js index e3e0c5a..1a826a9 100644 --- a/src/core/textures/VideoBaseTexture.js +++ b/src/core/textures/VideoBaseTexture.js @@ -12,15 +12,18 @@ * @param source {HTMLVideoElement} * @param [scaleMode] {number} See {@link scaleModes} for possible values */ -function VideoBaseTexture(source, scaleMode) { - if (!source){ +function VideoBaseTexture(source, scaleMode) +{ + if (!source) + { throw new Error('No video source element specified.'); } // hook in here to check if video is already available. // BaseTexture looks for a source.complete boolean, plus width & height. - if ((source.readyState === source.HAVE_ENOUGH_DATA || source.readyState === source.HAVE_FUTURE_DATA) && source.width && source.height) { + if ((source.readyState === source.HAVE_ENOUGH_DATA || source.readyState === source.HAVE_FUTURE_DATA) && source.width && source.height) + { source.complete = true; } @@ -31,7 +34,8 @@ this._boundOnUpdate = this._onUpdate.bind(this); this._boundOnCanPlay = this._onCanPlay.bind(this); - if (!source.complete) { + if (!source.complete) + { source.addEventListener('canplay', this._boundOnCanPlay); source.addEventListener('canplaythrough', this._boundOnCanPlay); @@ -47,28 +51,35 @@ VideoBaseTexture.prototype.constructor = VideoBaseTexture; module.exports = VideoBaseTexture; -VideoBaseTexture.prototype._onUpdate = function () { - if (this.autoUpdate) { +VideoBaseTexture.prototype._onUpdate = function () +{ + if (this.autoUpdate) + { window.requestAnimationFrame(this._boundOnUpdate); this.needsUpdate = true; } }; -VideoBaseTexture.prototype._onPlayStart = function () { - if (!this.autoUpdate) { +VideoBaseTexture.prototype._onPlayStart = function () +{ + if (!this.autoUpdate) + { window.requestAnimationFrame(this._boundOnUpdate); this.autoUpdate = true; } }; -VideoBaseTexture.prototype._onPlayStop = function () { +VideoBaseTexture.prototype._onPlayStop = function () +{ this.autoUpdate = false; }; -VideoBaseTexture.prototype._onCanPlay = function () { +VideoBaseTexture.prototype._onCanPlay = function () +{ this.hasLoaded = true; - if (this.source) { + if (this.source) + { this.source.removeEventListener('canplay', this._boundOnCanPlay); this.source.removeEventListener('canplaythrough', this._boundOnCanPlay); @@ -78,15 +89,18 @@ this.source.play(); // prevent multiple loaded dispatches.. - if(!this.__loaded){ + if(!this.__loaded) + { this.__loaded = true; this.emit('loaded', this); } } }; -VideoBaseTexture.prototype.destroy = function () { - if (this.source && this.source._pixiId) { +VideoBaseTexture.prototype.destroy = function () +{ + if (this.source && this.source._pixiId) + { utils.BaseTextureCache[ this.source._pixiId ] = null; delete utils.BaseTextureCache[ this.source._pixiId ]; @@ -105,14 +119,17 @@ * @param scaleMode {number} See {@link scaleModes} for possible values * @return {VideoBaseTexture} */ -VideoBaseTexture.fromVideo = function (video, scaleMode) { - if (!video._pixiId) { +VideoBaseTexture.fromVideo = function (video, scaleMode) +{ + if (!video._pixiId) + { video._pixiId = 'video_' + utils.uuid(); } var baseTexture = utils.BaseTextureCache[video._pixiId]; - if (!baseTexture) { + if (!baseTexture) + { baseTexture = new VideoBaseTexture(video, scaleMode); utils.BaseTextureCache[ video._pixiId ] = baseTexture; } @@ -147,17 +164,21 @@ * @param scaleMode {number} See {@link scaleModes} for possible values * @return {VideoBaseTexture} */ -VideoBaseTexture.fromUrl = function (videoSrc, scaleMode) { +VideoBaseTexture.fromUrl = function (videoSrc, scaleMode) +{ var video = document.createElement('video'); // array of objects or strings - if (Array.isArray(videoSrc)) { - for (var i = 0; i < videoSrc.length; ++i) { + if (Array.isArray(videoSrc)) + { + for (var i = 0; i < videoSrc.length; ++i) + { video.appendChild(createSource(videoSrc.src || videoSrc, videoSrc.mime)); } } // single object or string - else { + else + { video.appendChild(createSource(videoSrc.src || videoSrc, videoSrc.mime)); } @@ -169,8 +190,10 @@ VideoBaseTexture.fromUrls = VideoBaseTexture.fromUrl; -function createSource(path, type) { - if (!type) { +function createSource(path, type) +{ + if (!type) + { type = 'video/' + path.substr(path.lastIndexOf('.') + 1); } diff --git a/src/core/utils/EventData.js b/src/core/utils/EventData.js index 5d55a22..8cdf701 100644 --- a/src/core/utils/EventData.js +++ b/src/core/utils/EventData.js @@ -7,7 +7,8 @@ * @param name {string} The string name of the event that was triggered * @param data {object} Arbitrary event data to pass along */ -function EventData(target, name, data) { +function EventData(target, name, data) +{ // for duck typing in the ".on()" function this.__isEventObject = true; @@ -71,7 +72,8 @@ * Stops the propagation of events up the scene graph (prevents bubbling). * */ -EventData.prototype.stopPropagation = function stopPropagation() { +EventData.prototype.stopPropagation = function stopPropagation() +{ this.stopped = true; }; @@ -79,6 +81,7 @@ * Stops the propagation of events to sibling listeners (no longer calls any listeners). * */ -EventData.prototype.stopImmediatePropagation = function stopImmediatePropagation() { +EventData.prototype.stopImmediatePropagation = function stopImmediatePropagation() +{ this.stoppedImmediate = true; }; diff --git a/src/core/utils/EventTarget.js b/src/core/utils/EventTarget.js index 7ae8820..671a151 100644 --- a/src/core/utils/EventTarget.js +++ b/src/core/utils/EventTarget.js @@ -13,14 +13,16 @@ * var em = new MyEmitter(); * em.emit('eventName', 'some data', 'some more data', {}, null, ...); */ -function eventTarget(obj) { +function eventTarget(obj) +{ /** * Return a list of assigned event listeners. * * @param eventName {string} The events that should be listed. * @return {Array} An array of listener functions */ - obj.listeners = function listeners(eventName) { + obj.listeners = function listeners(eventName) + { this._listeners = this._listeners || {}; return this._listeners[eventName] ? this._listeners[eventName].slice() : []; @@ -33,22 +35,26 @@ * @param eventName {string} The name of the event. * @return {boolean} Indication if we've emitted an event. */ - obj.emit = obj.dispatchEvent = function emit(eventName, data) { + obj.emit = obj.dispatchEvent = function emit(eventName, data) + { this._listeners = this._listeners || {}; // fast return when there are no listeners - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return; } //backwards compat with old method ".emit({ type: 'something' })" - if (typeof eventName === 'object') { + if (typeof eventName === 'object') + { data = eventName; eventName = eventName.type; } //ensure we are using a real pixi event - if (!data || data.__isEventObject !== true) { + if (!data || data.__isEventObject !== true) + { data = new EventData(this, eventName, data); } @@ -58,23 +64,27 @@ fn = listeners[0], i; - for (i = 0; i < length; fn = listeners[++i]) { + for (i = 0; i < length; fn = listeners[++i]) + { //call the event listener fn.call(this, data); //if "stopImmediatePropagation" is called, stop calling sibling events - if (data.stoppedImmediate) { + if (data.stoppedImmediate) + { return this; } } //if "stopPropagation" is called then don't bubble the event - if (data.stopped) { + if (data.stopped) + { return this; } //bubble this event up the scene graph - if (this.parent && this.parent.emit) { + if (this.parent && this.parent.emit) + { this.parent.emit.call(this.parent, eventName, data); } @@ -88,7 +98,8 @@ * @param eventName {string} Name of the event. * @param callback {Functon} fn Callback function. */ - obj.on = obj.addEventListener = function on(eventName, fn) { + obj.on = obj.addEventListener = function on(eventName, fn) + { this._listeners = this._listeners || {}; (this._listeners[eventName] = this._listeners[eventName] || []) @@ -103,11 +114,13 @@ * @param eventName {string} Name of the event. * @param callback {Function} Callback function. */ - obj.once = function once(eventName, fn) { + obj.once = function once(eventName, fn) + { this._listeners = this._listeners || {}; var self = this; - function onceHandlerWrapper() { + function onceHandlerWrapper() + { fn.apply(self.off(eventName, onceHandlerWrapper), arguments); } onceHandlerWrapper._originalHandler = fn; @@ -122,23 +135,28 @@ * @param eventName {string} The event we want to remove. * @param callback {Function} The listener that we need to find. */ - obj.off = obj.removeEventListener = function off(eventName, fn) { + obj.off = obj.removeEventListener = function off(eventName, fn) + { this._listeners = this._listeners || {}; - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return this; } var list = this._listeners[eventName], i = fn ? list.length : 0; - while(i-- > 0) { - if (list[i] === fn || list[i]._originalHandler === fn) { + while(i-- > 0) + { + if (list[i] === fn || list[i]._originalHandler === fn) + { list.splice(i, 1); } } - if (list.length === 0) { + if (list.length === 0) + { delete this._listeners[eventName]; } @@ -150,10 +168,12 @@ * * @param eventName {string} The event you want to remove all listeners for. */ - obj.removeAllListeners = function removeAllListeners(eventName) { + obj.removeAllListeners = function removeAllListeners(eventName) + { this._listeners = this._listeners || {}; - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return this; } @@ -169,7 +189,8 @@ * * @param object {object} The obj to mix into */ - mixin: function mixin(obj) { + mixin: function mixin(obj) + { eventTarget(obj); } }; diff --git a/src/core/utils/PolyK.js b/src/core/utils/PolyK.js index 7325141..5e20c2b 100644 --- a/src/core/utils/PolyK.js +++ b/src/core/utils/PolyK.js @@ -47,7 +47,8 @@ * Triangulates shapes for webGL graphic fills. * */ -PolyK.Triangulate = function (p) { +PolyK.Triangulate = function (p) +{ var sign = true; var n = p.length >> 1; @@ -59,7 +60,8 @@ i = 0; var al = n; - while(al > 3) { + while(al > 3) + { var i0 = avl[(i+0)%al]; var i1 = avl[(i+1)%al]; var i2 = avl[(i+2)%al]; @@ -69,29 +71,35 @@ var cx = p[2*i2], cy = p[2*i2+1]; var earFound = false; - if (PolyK._convex(ax, ay, bx, by, cx, cy, sign)) { + if (PolyK._convex(ax, ay, bx, by, cx, cy, sign)) + { earFound = true; - for (var j = 0; j < al; j++) { + for (var j = 0; j < al; j++) + { var vi = avl[j]; if (vi === i0 || vi === i1 || vi === i2) continue; - if (PolyK._PointInTriangle(p[2*vi], p[2*vi+1], ax, ay, bx, by, cx, cy)) { + if (PolyK._PointInTriangle(p[2*vi], p[2*vi+1], ax, ay, bx, by, cx, cy)) + { earFound = false; break; } } } - if (earFound) { + if (earFound) + { tgs.push(i0, i1, i2); avl.splice((i+1)%al, 1); al--; i = 0; } - else if (i++ > 3*al) { + else if (i++ > 3*al) + { // need to flip flip reverse it! // reset! - if (sign) { + if (sign) + { tgs = []; avl = []; for (i = 0; i < n; i++) avl.push(i); @@ -101,7 +109,8 @@ sign = false; } - else { + else + { // window.console.log("PIXI Warning: shape too complex to fill"); return null; } @@ -126,7 +135,8 @@ * @private * @return {boolean} */ -PolyK._PointInTriangle = function (px, py, ax, ay, bx, by, cx, cy) { +PolyK._PointInTriangle = function (px, py, ax, ay, bx, by, cx, cy) +{ var v0x = cx-ax; var v0y = cy-ay; var v1x = bx-ax; @@ -154,6 +164,7 @@ * @private * @return {boolean} */ -PolyK._convex = function (ax, ay, bx, by, cx, cy, sign) { +PolyK._convex = function (ax, ay, bx, by, cx, cy, sign) +{ return ((ay-by)*(cx-bx) + (bx-ax)*(cy-by) >= 0) === sign; }; diff --git a/src/core/utils/index.js b/src/core/utils/index.js index ade9831..bfae7ae 100644 --- a/src/core/utils/index.js +++ b/src/core/utils/index.js @@ -16,7 +16,8 @@ * * @return {number} The next uuid to use. */ - uuid: function () { + uuid: function () + { return ++utils._uid; }, @@ -26,7 +27,8 @@ * @param hex {number} * @return {number[]} An array representing the [R, G, B] of the color. */ - hex2rgb: function (hex, out) { + hex2rgb: function (hex, out) + { out = out || []; out[0] = (hex >> 16 & 0xFF) / 255; @@ -42,7 +44,8 @@ * @param hex {number} * @return {string} The string color. */ - hex2string: function (hex) { + hex2string: function (hex) + { hex = hex.toString(16); hex = '000000'.substr(0, 6 - hex.length) + hex; @@ -55,7 +58,8 @@ * @param rgb {number[]} * @return {number} The color number */ - rgb2hex: function (rgb) { + rgb2hex: function (rgb) + { return ((rgb[0]*255 << 16) + (rgb[1]*255 << 8) + rgb[2]*255); }, @@ -64,8 +68,10 @@ * * @return {boolean} whether they are supported */ - canUseNewCanvasBlendModes: function () { - if (typeof document === 'undefined') { + canUseNewCanvasBlendModes: function () + { + if (typeof document === 'undefined') + { return false; } @@ -93,15 +99,19 @@ * @param number {number} * @return {number} the closest number that is a power of two */ - getNextPowerOfTwo: function (number) { + getNextPowerOfTwo: function (number) + { // see: http://en.wikipedia.org/wiki/Power_of_two#Fast_algorithm_to_check_if_a_positive_number_is_a_power_of_two - if (number > 0 && (number & (number - 1)) === 0) { + if (number > 0 && (number & (number - 1)) === 0) + { return number; } - else { + else + { var result = 1; - while (result < number) { + while (result < number) + { result <<= 1; } @@ -116,7 +126,8 @@ * @param height {number} * @return {boolean} */ - isPowerOfTwo: function (width, height) { + isPowerOfTwo: function (width, height) + { return (width > 0 && (width & (width - 1)) === 0 && height > 0 && (height & (height - 1)) === 0); }, @@ -130,12 +141,15 @@ * @constant * @static */ - sayHello: function (type) { - if (utils._saidHello) { + sayHello: function (type) + { + if (utils._saidHello) + { return; } - if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) { + if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) + { var args = [ '%c %c %c Pixi.js ' + CONST.VERSION + ' - ' + type + ' %c ' + ' %c ' + ' http://www.pixijs.com/ %c %c ♥%c♥%c♥ ', 'background: #ff66a5', @@ -151,7 +165,8 @@ console.log.apply(console, args); //jshint ignore:line } - else if (window.console) { + else if (window.console) + { console.log('Pixi.js ' + CONST.VERSION + ' - ' + type + ' - http://www.pixijs.com/'); //jshint ignore:line } @@ -166,15 +181,19 @@ * @class * @namespace PIXI */ - AjaxRequest: function () { + AjaxRequest: function () + { var activexmodes = ['Msxml2.XMLHTTP.6.0', 'Msxml2.XMLHTTP.3.0', 'Microsoft.XMLHTTP']; //activeX versions to check for in IE - if (window.ActiveXObject) { //Test for support for ActiveXObject in IE first (as XMLHttpRequest in IE7 is broken) - for (var i=0; i= this.textures.length) { + else if (round >= this.textures.length) + { this.gotoAndStop(this.textures.length - 1); - if (this.onComplete) { + if (this.onComplete) + { this.onComplete(); } } @@ -167,10 +182,12 @@ * @static * @param frames {string[]} the array of frames ids the movieclip will use as its texture frames */ -MovieClip.fromFrames = function (frames) { +MovieClip.fromFrames = function (frames) +{ var textures = []; - for (var i = 0; i < frames.length; ++i) { + for (var i = 0; i < frames.length; ++i) + { textures.push(new core.Texture.fromFrame(frames[i])); } @@ -183,10 +200,12 @@ * @static * @param images {string[]} the array of image urls the movieclip will use as its texture frames */ -MovieClip.fromImages = function (images) { +MovieClip.fromImages = function (images) +{ var textures = []; - for (var i = 0; i < images.length; ++i) { + for (var i = 0; i < images.length; ++i) + { textures.push(new core.Texture.fromImage(images[i])); } diff --git a/src/extras/Rope.js b/src/extras/Rope.js index c157ec4..9c87bc0 100644 --- a/src/extras/Rope.js +++ b/src/extras/Rope.js @@ -9,7 +9,8 @@ * @param {Array} points - An array of {Point}. * */ -function Rope(texture, points) { +function Rope(texture, points) +{ Strip.call(this, texture); this.points = points; @@ -31,10 +32,12 @@ * Refreshes * */ -Rope.prototype.refresh = function () { +Rope.prototype.refresh = function () +{ var points = this.points; - if (points.length < 1) { + if (points.length < 1) + { return; } @@ -59,20 +62,23 @@ var total = points.length, point, index, amount; - for (var i = 1; i < total; i++) { + for (var i = 1; i < total; i++) + { point = points[i]; index = i * 4; // time to do some smart drawing! amount = i / (total-1); - if (i%2) { + if (i%2) + { uvs[index] = amount; uvs[index+1] = 0; uvs[index+2] = amount; uvs[index+3] = 1; } - else { + else + { uvs[index] = amount; uvs[index+1] = 0; @@ -95,10 +101,12 @@ * * @private */ -Rope.prototype.updateTransform = function () { +Rope.prototype.updateTransform = function () +{ var points = this.points; - if (points.length < 1) { + if (points.length < 1) + { return; } @@ -113,14 +121,17 @@ var total = points.length, point, index, ratio, perpLength, num; - for (var i = 0; i < total; i++) { + for (var i = 0; i < total; i++) + { point = points[i]; index = i * 4; - if (i < points.length-1) { + if (i < points.length-1) + { nextPoint = points[i+1]; } - else { + else + { nextPoint = point; } @@ -129,7 +140,8 @@ ratio = (1 - (i / (total-1))) * 10; - if (ratio > 1) { + if (ratio > 1) + { ratio = 1; } @@ -157,7 +169,8 @@ * * @param texture {Texture} the texture that will be used */ -Rope.prototype.setTexture = function (texture) { +Rope.prototype.setTexture = function (texture) +{ // stop current texture this.texture = texture; //this.updateFrame = true; diff --git a/src/core/display/DisplayObject.js b/src/core/display/DisplayObject.js index 66ebc3c..20e778c 100644 --- a/src/core/display/DisplayObject.js +++ b/src/core/display/DisplayObject.js @@ -7,7 +7,8 @@ * @class * @namespace PIXI */ -function DisplayObject() { +function DisplayObject() +{ /** * The coordinate of the object relative to the local coordinates of the parent. * @@ -152,10 +153,12 @@ * @memberof DisplayObject# */ x: { - get: function () { + get: function () + { return this.position.x; }, - set: function (value) { + set: function (value) + { this.position.x = value; } }, @@ -167,10 +170,12 @@ * @memberof DisplayObject# */ y: { - get: function () { + get: function () + { return this.position.y; }, - set: function (value) { + set: function (value) + { this.position.y = value; } }, @@ -183,11 +188,13 @@ * @readonly */ worldVisible: { - get: function () { + get: function () + { var item = this; do { - if (!item.visible) { + if (!item.visible) + { return false; } @@ -207,17 +214,21 @@ * @memberof DisplayObject# */ mask: { - get: function () { + get: function () + { return this._mask; }, - set: function (value) { - if (this._mask) { + set: function (value) + { + if (this._mask) + { this._mask.isMask = false; } this._mask = value; - if (this._mask) { + if (this._mask) + { this._mask.isMask = true; } } @@ -232,18 +243,23 @@ * @memberof DisplayObject# */ filters: { - get: function () { + get: function () + { return this._filters; }, - set: function (value) { - if (value) { + set: function (value) + { + if (value) + { // now put all the passes in one place.. var passes = []; - for (var i = 0; i < value.length; i++) { + for (var i = 0; i < value.length; i++) + { var filterPasses = value[i].passes; - for (var j = 0; j < filterPasses.length; j++) { + for (var j = 0; j < filterPasses.length; j++) + { passes.push(filterPasses[j]); } } @@ -264,8 +280,9 @@ * * @private */ -DisplayObject.prototype.updateTransform = function () { - +DisplayObject.prototype.updateTransform = function () +{ + // create some matrix refs for easy access var pt = this.parent.worldTransform; var wt = this.worldTransform; @@ -274,9 +291,11 @@ var a, b, c, d, tx, ty; // so if rotation is between 0 then we can simplify the multiplication process.. - if (this.rotation % math.PI_2) { + if (this.rotation % math.PI_2) + { // 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) { + if (this.rotation !== this.rotationCache) + { this.rotationCache = this.rotation; this._sr = Math.sin(this.rotation); this._cr = Math.cos(this.rotation); @@ -291,7 +310,8 @@ ty = this.position.y; // check for pivot.. not often used so geared towards that fact! - if (this.pivot.x || this.pivot.y) { + 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; } @@ -304,7 +324,8 @@ wt.tx = tx * pt.a + ty * pt.c + pt.tx; wt.ty = tx * pt.b + ty * pt.d + pt.ty; } - else { + else + { // lets do the fast version as we know there is no rotation.. a = this.scale.x; d = this.scale.y; @@ -333,7 +354,8 @@ * @param matrix {Matrix} * @return {Rectangle} the rectangular bounding area */ -DisplayObject.prototype.getBounds = function (/* matrix */) { +DisplayObject.prototype.getBounds = function (/* matrix */) +{ return math.Rectangle.EMPTY; }; @@ -342,7 +364,8 @@ * * @return {Rectangle} the rectangular bounding area */ -DisplayObject.prototype.getLocalBounds = function () { +DisplayObject.prototype.getLocalBounds = function () +{ return this.getBounds(math.Matrix.IDENTITY); }; @@ -352,7 +375,8 @@ * @param position {Point} The world origin to calculate from * @return {Point} A point object representing the position of this object */ -DisplayObject.prototype.toGlobal = function (position) { +DisplayObject.prototype.toGlobal = function (position) +{ // don't need to u[date the lot this.displayObjectUpdateTransform(); return this.worldTransform.apply(position); @@ -365,8 +389,10 @@ * @param [from] {DisplayObject} The DisplayObject to calculate the global position from * @return {Point} A point object representing the position of this object */ -DisplayObject.prototype.toLocal = function (position, from) { - if (from) { +DisplayObject.prototype.toLocal = function (position, from) +{ + if (from) + { position = from.toGlobal(position); } @@ -381,7 +407,8 @@ * @param renderer {WebGLRenderer} The renderer * @private */ -DisplayObject.prototype.renderWebGL = function (/* renderer */) { +DisplayObject.prototype.renderWebGL = function (/* renderer */) +{ // OVERWRITE; }; @@ -391,6 +418,7 @@ * @param renderer {CanvasRenderer} The renderer * @private */ -DisplayObject.prototype.renderCanvas = function (/* renderer */) { +DisplayObject.prototype.renderCanvas = function (/* renderer */) +{ // OVERWRITE; }; diff --git a/src/core/display/DisplayObjectContainer.js b/src/core/display/DisplayObjectContainer.js index 689f40b..4625ee8 100644 --- a/src/core/display/DisplayObjectContainer.js +++ b/src/core/display/DisplayObjectContainer.js @@ -12,7 +12,8 @@ * @extends DisplayObject * @namespace PIXI */ -function DisplayObjectContainer() { +function DisplayObjectContainer() +{ DisplayObject.call(this); /** @@ -47,17 +48,21 @@ * @memberof DisplayObjectContainer# */ width: { - get: function () { + get: function () + { return this.scale.x * this.getLocalBounds().width; }, - set: function (value) { + set: function (value) + { var width = this.getLocalBounds().width; - if(width !== 0) { + if(width !== 0) + { this.scale.x = value / width; } - else { + else + { this.scale.x = 1; } @@ -73,17 +78,21 @@ * @memberof DisplayObjectContainer# */ height: { - get: function () { + get: function () + { return this.scale.y * this.getLocalBounds().height; }, - set: function (value) { + set: function (value) + { var height = this.getLocalBounds().height; - if (height !== 0) { + if (height !== 0) + { this.scale.y = value / height ; } - else { + else + { this.scale.y = 1; } @@ -100,18 +109,23 @@ * @memberof DisplayObject# */ cacheAsBitmap: { - get: function () { + get: function () + { return this._cacheAsBitmap; }, - set: function (value) { - if (this._cacheAsBitmap === value) { + set: function (value) + { + if (this._cacheAsBitmap === value) + { return; } - if (value) { + if (value) + { this._generateCachedSprite(); } - else { + else + { this._destroyCachedSprite(); } @@ -126,7 +140,8 @@ * @param child {DisplayObject} The DisplayObject to add to the container * @return {DisplayObject} The child that was added. */ -DisplayObjectContainer.prototype.addChild = function (child) { +DisplayObjectContainer.prototype.addChild = function (child) +{ return this.addChildAt(child, this.children.length); }; @@ -137,14 +152,18 @@ * @param index {Number} The index to place the child in * @return {DisplayObject} The child that was added. */ -DisplayObjectContainer.prototype.addChildAt = function (child, index) { +DisplayObjectContainer.prototype.addChildAt = function (child, index) +{ // prevent adding self as child - if (child === this) { + if (child === this) + { return; } - if (index >= 0 && index <= this.children.length) { - if (child.parent) { + if (index >= 0 && index <= this.children.length) + { + if (child.parent) + { child.parent.removeChild(child); } @@ -154,7 +173,8 @@ return child; } - else { + else + { throw new Error(child + 'addChildAt: The index '+ index +' supplied is out of bounds ' + this.children.length); } }; @@ -165,15 +185,18 @@ * @param child {DisplayObject} * @param child2 {DisplayObject} */ -DisplayObjectContainer.prototype.swapChildren = function (child, child2) { - if (child === child2) { +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) { + if (index1 < 0 || index2 < 0) + { throw new Error('swapChildren: Both the supplied DisplayObjects must be a child of the caller.'); } @@ -187,10 +210,12 @@ * @param child {DisplayObject} The DisplayObject instance to identify * @return {Number} The index position of the child display object to identify */ -DisplayObjectContainer.prototype.getChildIndex = function (child) { +DisplayObjectContainer.prototype.getChildIndex = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { throw new Error('The supplied DisplayObject must be a child of the caller'); } @@ -203,8 +228,10 @@ * @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 */ -DisplayObjectContainer.prototype.setChildIndex = function (child, index) { - if (index < 0 || index >= this.children.length) { +DisplayObjectContainer.prototype.setChildIndex = function (child, index) +{ + if (index < 0 || index >= this.children.length) + { throw new Error('The supplied index is out of bounds'); } @@ -220,8 +247,10 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child at the given index, if any. */ -DisplayObjectContainer.prototype.getChildAt = function (index) { - if (index < 0 || index >= this.children.length) { +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'); } @@ -234,10 +263,12 @@ * @param child {DisplayObject} The DisplayObject to remove * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChild = function (child) { +DisplayObjectContainer.prototype.removeChild = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { return; } @@ -250,7 +281,8 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChildAt = function (index) { +DisplayObjectContainer.prototype.removeChildAt = function (index) +{ var child = this.getChildAt(index); child.parent = null; @@ -265,24 +297,29 @@ * @param beginIndex {Number} The beginning position. Default value is 0. * @param endIndex {Number} The ending position. Default value is size of the container. */ -DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) { +DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) +{ var begin = beginIndex || 0; var end = typeof endIndex === 'number' ? endIndex : this.children.length; var range = end - begin; - if (range > 0 && range <= end) { + if (range > 0 && range <= end) + { var removed = this.children.splice(begin, range); - for (var i = 0; i < removed.length; ++i) { + for (var i = 0; i < removed.length; ++i) + { removed[i].parent = null; } return removed; } - else if (range === 0 && this.children.length === 0) { + else if (range === 0 && this.children.length === 0) + { return []; } - else { + else + { throw new RangeError('removeChildren: numeric values are outside the acceptable range.'); } }; @@ -291,7 +328,8 @@ * Generates and updates the cached sprite for this object. * */ -DisplayObjectContainer.prototype.updateCachedSprite = function () { +DisplayObjectContainer.prototype.updateCachedSprite = function () +{ this._generateCachedSprite(); }; @@ -304,7 +342,8 @@ * @param renderer {CanvasRenderer|WebGLRenderer} The renderer used to generate the texture. * @return {Texture} a texture of the graphics object */ -DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) { +DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) +{ var bounds = this.getLocalBounds(); var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0, renderer, scaleMode, resolution); @@ -322,18 +361,22 @@ * * @private */ -DisplayObjectContainer.prototype.updateTransform = function () { - if (!this.visible) { +DisplayObjectContainer.prototype.updateTransform = function () +{ + if (!this.visible) + { return; } this.displayObjectUpdateTransform(); - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { return; } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } }; @@ -346,8 +389,10 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getBounds = function () { - if (this.children.length === 0) { +DisplayObjectContainer.prototype.getBounds = function () +{ + if (this.children.length === 0) + { return math.Rectangle.EMPTY; } @@ -365,10 +410,12 @@ var childVisible = false; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -386,7 +433,8 @@ maxY = maxY > childMaxY ? maxY : childMaxY; } - if (!childVisible) { + if (!childVisible) + { return math.Rectangle.EMPTY; } @@ -407,12 +455,14 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getLocalBounds = function () { +DisplayObjectContainer.prototype.getLocalBounds = function () +{ var matrixCache = this.worldTransform; this.worldTransform = math.Matrix.IDENTITY; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } @@ -428,13 +478,16 @@ * * @param renderer {WebGLRenderer} The renderer */ -DisplayObjectContainer.prototype.renderWebGL = function (renderer) { +DisplayObjectContainer.prototype.renderWebGL = function (renderer) +{ // if the object is not visible or the alpha is 0 then no need to render this element - if (!this.visible || this.alpha <= 0) { + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } @@ -442,14 +495,17 @@ var i, j; // do a quick check to see if this element has a mask or a filter. - if (this._mask || this._filters) { + if (this._mask || this._filters) + { // push filter first as we need to ensure the stencil buffer is correct for any masking - if (this._filters) { + if (this._filters) + { renderer.spriteBatch.flush(); renderer.filterManager.pushFilter(this._filterBlock); } - if (this._mask) { + if (this._mask) + { renderer.spriteBatch.stop(); renderer.maskManager.pushMask(this.mask, renderer); renderer.spriteBatch.start(); @@ -459,36 +515,42 @@ this._renderWebGL(renderer); // now loop through the children and make sure they get rendered - for (i = 0, j = this.children.length; i < j; i++) { + for (i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderWebGL(renderer); } // time to stop the sprite batch as either a mask element or a filter draw will happen next renderer.spriteBatch.stop(); - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(this._mask, renderer); } - if (this._filters) { + if (this._filters) + { renderer.filterManager.popFilter(); } renderer.spriteBatch.start(); } - else { + else + { this._renderWebGL(renderer); // simple render children! - for (i = 0, j = this.children.length; i < j; ++i) { + for (i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderWebGL(renderer); } } }; -DisplayObjectContainer.prototype._renderWebGL = function (renderer) { +DisplayObjectContainer.prototype._renderWebGL = function (renderer) +{ // this is where content itself gets renderd.. @@ -499,25 +561,31 @@ * * @param renderer {CanvasRenderer} The renderer */ -DisplayObjectContainer.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0) { +DisplayObjectContainer.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -528,13 +596,16 @@ * @param renderer {WebGLRenderer|CanvasRenderer} The renderer * @private */ -DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) { +DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) +{ this._cachedSprite.worldAlpha = this.worldAlpha; - if (renderer.gl) { + if (renderer.gl) + { this._cachedSprite.renderWebGL(renderer); } - else { + else + { this._cachedSprite.renderCanvas(renderer); } }; @@ -544,10 +615,12 @@ * * @private */ -DisplayObjectContainer.prototype._generateCachedSprite = function () { +DisplayObjectContainer.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { // TODO - RenderTexture now *requires* a renderer instance, so this is like broken // because `renderer` isn't actually in scope here :P var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0); @@ -555,7 +628,8 @@ this._cachedSprite = new Sprite(renderTexture); this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.texture.resize(bounds.width | 0, bounds.height | 0); } @@ -580,8 +654,10 @@ * * @private */ -DisplayObjectContainer.prototype._destroyCachedSprite = function () { - if (!this._cachedSprite) { +DisplayObjectContainer.prototype._destroyCachedSprite = function () +{ + if (!this._cachedSprite) + { return; } diff --git a/src/core/display/Sprite.js b/src/core/display/Sprite.js index 707da24..5862aef 100644 --- a/src/core/display/Sprite.js +++ b/src/core/display/Sprite.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param texture {Texture} The texture for this sprite */ -function Sprite(texture) { +function Sprite(texture) +{ DisplayObjectContainer.call(this); /** @@ -85,12 +86,14 @@ this.texture = texture || Texture.EMPTY; } -Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) { +Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) +{ DisplayObjectContainer.prototype.destroy.call(this); this.anchor = null; - if (destroyTexture) { + if (destroyTexture) + { this._texture.destroy(destroyBaseTexture); } @@ -111,10 +114,12 @@ * @memberof Sprite# */ width: { - get: function () { + get: function () + { return this.scale.x * this.texture.frame.width; }, - set: function (value) { + set: function (value) + { this.scale.x = value / this.texture.frame.width; this._width = value; } @@ -127,10 +132,12 @@ * @memberof Sprite# */ height: { - get: function () { + get: function () + { return this.scale.y * this.texture.frame.height; }, - set: function (value) { + set: function (value) + { this.scale.y = value / this.texture.frame.height; this._height = value; } @@ -143,23 +150,29 @@ * @memberof Sprite# */ texture: { - get: function () { + get: function () + { return this._texture; }, - set: function (value) { - if (this._texture === value) { + set: function (value) + { + if (this._texture === value) + { return; } this._texture = value; this.cachedTint = 0xFFFFFF; - if (value) { + if (value) + { // wait for the texture to load - if (value.baseTexture.hasLoaded) { + if (value.baseTexture.hasLoaded) + { this._onTextureUpdate(); } - else { + else + { value.once('update', this._onTextureUpdate.bind(this)); } } @@ -172,18 +185,22 @@ * * @private */ -Sprite.prototype._onTextureUpdate = function () { +Sprite.prototype._onTextureUpdate = function () +{ // so if _width is 0 then width was not set.. - if (this._width) { + if (this._width) + { this.scale.x = this._width / this.texture.frame.width; } - if (this._height) { + if (this._height) + { this.scale.y = this._height / this.texture.frame.height; } }; -Sprite.prototype._renderWebGL = function (renderer) { +Sprite.prototype._renderWebGL = function (renderer) +{ // this is where content gets renderd.. // watch this space for a little render state manager.. @@ -197,7 +214,8 @@ * @param matrix {Matrix} the transformation matrix of the sprite * @return {Rectangle} the framing rectangle */ -Sprite.prototype.getBounds = function (matrix) { +Sprite.prototype.getBounds = function (matrix) +{ var width = this.texture.frame.width; var height = this.texture.frame.height; @@ -224,11 +242,13 @@ if(b === 0 && c === 0) { // scale may be negative! - if (a < 0) { + if (a < 0) + { a *= -1; } - if (d < 0) { + if (d < 0) + { d *= -1; } @@ -293,28 +313,34 @@ * * @param renderer {CanvasRenderer} The renderer */ -Sprite.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) { +Sprite.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) + { return; } - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; renderer.context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } // Ignore null sources - if (this.texture.valid) { + if (this.texture.valid) + { var resolution = this.texture.baseTexture.resolution / renderer.resolution; renderer.context.globalAlpha = this.worldAlpha; // If smoothingEnabled is supported and we need to change the smoothing property for this texture - if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) { + if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) + { renderer.scaleMode = this.texture.baseTexture.scaleMode; renderer.context[renderer.smoothProperty] = (renderer.scaleMode === CONST.scaleModes.LINEAR); } @@ -324,7 +350,8 @@ var dy = (this.texture.trim ? this.texture.trim.y : 0) - (this.anchor.y * this.texture.trim.height); // Allow for pixel rounding - if (renderer.roundPixels) { + if (renderer.roundPixels) + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -337,7 +364,8 @@ dx = dx | 0; dy = dy | 0; } - else { + else + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -348,8 +376,10 @@ ); } - if (this.tint !== 0xFFFFFF) { - if (this.cachedTint !== this.tint) { + if (this.tint !== 0xFFFFFF) + { + if (this.cachedTint !== this.tint) + { this.cachedTint = this.tint; // TODO clean up caching - how to clean up the caches? @@ -368,7 +398,8 @@ this.texture.crop.height / resolution ); } - else { + else + { renderer.context.drawImage( this.texture.baseTexture.source, this.texture.crop.x, @@ -383,11 +414,13 @@ } } - for (var i = 0, j = this.children.length; i < j; i++) { + for (var i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -402,10 +435,12 @@ * @param frameId {String} The frame Id of the texture in the cache * @return {Sprite} A new Sprite using a texture from the texture cache matching the frameId */ -Sprite.fromFrame = function (frameId) { +Sprite.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache' + this); } @@ -420,6 +455,7 @@ * @param imageId {String} The image url of the texture * @return {Sprite} A new Sprite using a texture from the texture cache matching the image id */ -Sprite.fromImage = function (imageId, crossorigin, scaleMode) { +Sprite.fromImage = function (imageId, crossorigin, scaleMode) +{ return new Sprite(Texture.fromImage(imageId, crossorigin, scaleMode)); }; diff --git a/src/core/display/SpriteBatch.js b/src/core/display/SpriteBatch.js index 3187777..c196fef 100644 --- a/src/core/display/SpriteBatch.js +++ b/src/core/display/SpriteBatch.js @@ -12,7 +12,8 @@ * ```js * var container = new SpriteBatch(); * - * for(var i = 0; i < 100; ++i) { + * for(var i = 0; i < 100; ++i) + * { * var sprite = new PIXI.Sprite.fromImage("myImage.png"); * container.addChild(sprite); * } @@ -25,7 +26,8 @@ */ //TODO RENAME to PARTICLE CONTAINER? -function SpriteBatch() { +function SpriteBatch() +{ DisplayObjectContainer.call(this); } @@ -38,7 +40,8 @@ * * @private */ -SpriteBatch.prototype.updateTransform = function () { +SpriteBatch.prototype.updateTransform = function () +{ // TODO don't need to! this.displayObjectUpdateTransform(); // PIXI.DisplayObjectContainer.prototype.updateTransform.call( this ); @@ -50,8 +53,10 @@ * @param renderer {WebGLRenderer} The webgl renderer * @private */ -SpriteBatch.prototype.renderWebGL = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderWebGL = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -71,8 +76,10 @@ * @param renderer {CanvasRenderer} The canvas renderer * @private */ -SpriteBatch.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -84,10 +91,12 @@ this.displayObjectUpdateTransform(); - for (var i = 0; i < this.children.length; ++i) { + for (var i = 0; i < this.children.length; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -95,9 +104,11 @@ context.globalAlpha = this.worldAlpha * child.alpha; - if (child.rotation % (Math.PI * 2) === 0) { + if (child.rotation % (Math.PI * 2) === 0) + { // this is the fastest way to optimise! - if rotation is 0 then we can avoid any kind of setTransform call - if (isRotated) { + if (isRotated) + { context.setTransform( transform.a, transform.b, @@ -122,8 +133,10 @@ frame.height * child.scale.y ); } - else { - if (!isRotated) { + else + { + if (!isRotated) + { isRotated = true; } @@ -131,7 +144,8 @@ var childTransform = child.worldTransform; - if (renderer.roundPixels) { + if (renderer.roundPixels) + { context.setTransform( childTransform.a, childTransform.b, @@ -141,7 +155,8 @@ childTransform.ty | 0 ); } - else { + else + { context.setTransform( childTransform.a, childTransform.b, diff --git a/src/core/index.js b/src/core/index.js index 3954b6f..eb4a82b 100644 --- a/src/core/index.js +++ b/src/core/index.js @@ -58,11 +58,13 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRenderer: function (width, height, options, noWebGL) { + autoDetectRenderer: function (width, height, options, noWebGL) + { width = width || 800; height = height || 600; - if (!noWebGL && require('webgl-enabled')()) { + if (!noWebGL && require('webgl-enabled')()) + { return new core.WebGLRenderer(width, height, options); } @@ -87,7 +89,8 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRecommendedRenderer: function (width, height, options) { + autoDetectRecommendedRenderer: function (width, height, options) + { var isAndroid = /Android/i.test(navigator.userAgent); return core.autoDetectRenderer(width, height, options, isAndroid); diff --git a/src/core/math/Matrix.js b/src/core/math/Matrix.js index c2f87e2..2ff4848 100644 --- a/src/core/math/Matrix.js +++ b/src/core/math/Matrix.js @@ -10,7 +10,8 @@ * @class * @namespace PIXI */ -function Matrix() { +function Matrix() +{ /** * @member {number} * @default 1 @@ -63,7 +64,8 @@ * * @param array {number[]} The array that the matrix will be populated from. */ -Matrix.prototype.fromArray = function (array) { +Matrix.prototype.fromArray = function (array) +{ this.a = array[0]; this.b = array[1]; this.c = array[3]; @@ -78,14 +80,17 @@ * @param transpose {boolean} Whether we need to transpose the matrix or not * @return {number[]} the newly created array which contains the matrix */ -Matrix.prototype.toArray = function (transpose) { - if (!this.array) { +Matrix.prototype.toArray = function (transpose) +{ + if (!this.array) + { this.array = new Float32Array(9); } var array = this.array; - if (transpose) { + if (transpose) + { array[0] = this.a; array[1] = this.b; array[2] = 0; @@ -96,7 +101,8 @@ array[7] = this.ty; array[8] = 1; } - else { + else + { array[0] = this.a; array[1] = this.c; array[2] = this.tx; @@ -119,7 +125,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, transformed through this matrix */ -Matrix.prototype.apply = function (pos, newPos) { +Matrix.prototype.apply = function (pos, newPos) +{ newPos = newPos || new Point(); newPos.x = this.a * pos.x + this.c * pos.y + this.tx; @@ -136,7 +143,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, inverse-transformed through this matrix */ -Matrix.prototype.applyInverse = function (pos, newPos) { +Matrix.prototype.applyInverse = function (pos, newPos) +{ newPos = newPos || new Point(); var id = 1 / (this.a * this.d + this.c * -this.b); @@ -154,7 +162,8 @@ * @param {number} y * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.translate = function (x, y) { +Matrix.prototype.translate = function (x, y) +{ this.tx += x; this.ty += y; @@ -168,7 +177,8 @@ * @param {number} y The amount to scale vertically * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.scale = function (x, y) { +Matrix.prototype.scale = function (x, y) +{ this.a *= x; this.d *= y; this.c *= x; @@ -186,7 +196,8 @@ * @param {number} angle - The angle in radians. * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.rotate = function (angle) { +Matrix.prototype.rotate = function (angle) +{ var cos = Math.cos( angle ); var sin = Math.sin( angle ); @@ -210,7 +221,8 @@ * @param {Matrix} matrix * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.append = function (matrix) { +Matrix.prototype.append = function (matrix) +{ var a1 = this.a; var b1 = this.b; var c1 = this.c; @@ -232,7 +244,8 @@ * * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.identity = function () { +Matrix.prototype.identity = function () +{ this.a = 1; this.b = 0; this.c = 0; diff --git a/src/core/math/Point.js b/src/core/math/Point.js index 7565b2d..632f346 100644 --- a/src/core/math/Point.js +++ b/src/core/math/Point.js @@ -7,7 +7,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -function Point(x, y) { +function Point(x, y) +{ /** * @member {number} * @default 0 @@ -29,7 +30,8 @@ * * @return {Point} a copy of the point */ -Point.prototype.clone = function () { +Point.prototype.clone = function () +{ return new Point(this.x, this.y); }; @@ -40,7 +42,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -Point.prototype.set = function (x, y) { +Point.prototype.set = function (x, y) +{ this.x = x || 0; this.y = y || ( (y !== 0) ? this.x : 0 ) ; }; diff --git a/src/core/math/shapes/Circle.js b/src/core/math/shapes/Circle.js index 69cfdc9..4d76efc 100644 --- a/src/core/math/shapes/Circle.js +++ b/src/core/math/shapes/Circle.js @@ -10,7 +10,8 @@ * @param y {number} The Y coordinate of the center of this circle * @param radius {number} The radius of the circle */ -function Circle(x, y, radius) { +function Circle(x, y, radius) +{ /** * @member {number} * @default 0 @@ -46,7 +47,8 @@ * @method clone * @return {Circle} a copy of the Circle */ -Circle.prototype.clone = function () { +Circle.prototype.clone = function () +{ return new Circle(this.x, this.y, this.radius); }; @@ -58,8 +60,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Circle */ -Circle.prototype.contains = function (x, y) { - if (this.radius <= 0) { +Circle.prototype.contains = function (x, y) +{ + if (this.radius <= 0) + { return false; } @@ -79,6 +83,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Circle.prototype.getBounds = function () { +Circle.prototype.getBounds = function () +{ return new Rectangle(this.x - this.radius, this.y - this.radius, this.radius * 2, this.radius * 2); }; diff --git a/src/core/math/shapes/Ellipse.js b/src/core/math/shapes/Ellipse.js index 4f2d066..fefd01a 100644 --- a/src/core/math/shapes/Ellipse.js +++ b/src/core/math/shapes/Ellipse.js @@ -11,7 +11,8 @@ * @param width {number} The half width of this ellipse * @param height {number} The half height of this ellipse */ -function Ellipse(x, y, width, height) { +function Ellipse(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -53,7 +54,8 @@ * @method clone * @return {Ellipse} a copy of the ellipse */ -Ellipse.prototype.clone = function () { +Ellipse.prototype.clone = function () +{ return new Ellipse(this.x, this.y, this.width, this.height); }; @@ -65,8 +67,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coords are within this ellipse */ -Ellipse.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Ellipse.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } @@ -86,6 +90,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Ellipse.prototype.getBounds = function () { +Ellipse.prototype.getBounds = function () +{ return new Rectangle(this.x - this.width, this.y - this.height, this.width, this.height); }; diff --git a/src/core/math/shapes/Polygon.js b/src/core/math/shapes/Polygon.js index ae89148..fea6d37 100644 --- a/src/core/math/shapes/Polygon.js +++ b/src/core/math/shapes/Polygon.js @@ -10,16 +10,20 @@ * arguments passed can be flat x,y values e.g. `new Polygon(x,y, x,y, x,y, ...)` where `x` and `y` are * Numbers. */ -function Polygon(points) { +function Polygon(points) +{ //if points isn't an array, use arguments as the array - if (!(points instanceof Array)) { + if (!(points instanceof Array)) + { points = Array.prototype.slice.call(arguments); } //if this is a flat array of numbers, convert it to points - if (points[0] instanceof Point) { + if (points[0] instanceof Point) + { var p = []; - for (var i = 0, il = points.length; i < il; i++) { + for (var i = 0, il = points.length; i < il; i++) + { p.push(points[i].x, points[i].y); } @@ -51,7 +55,8 @@ * * @return {Polygon} a copy of the polygon */ -Polygon.prototype.clone = function () { +Polygon.prototype.clone = function () +{ return new Polygon(this.points.slice()); }; @@ -62,19 +67,22 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this polygon */ -Polygon.prototype.contains = function (x, y) { +Polygon.prototype.contains = function (x, y) +{ var inside = false; // use some raycasting to test hits // https://github.com/substack/point-in-polygon/blob/master/index.js var length = this.points.length / 2; - for (var i = 0, j = length - 1; i < length; j = i++) { + for (var i = 0, j = length - 1; i < length; j = i++) + { var xi = this.points[i * 2], yi = this.points[i * 2 + 1], xj = this.points[j * 2], yj = this.points[j * 2 + 1], intersect = ((yi > y) !== (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi); - if (intersect) { + if (intersect) + { inside = !inside; } } diff --git a/src/core/math/shapes/Rectangle.js b/src/core/math/shapes/Rectangle.js index 16ac62a..4008b68 100644 --- a/src/core/math/shapes/Rectangle.js +++ b/src/core/math/shapes/Rectangle.js @@ -10,7 +10,8 @@ * @param width {number} The overall width of this rectangle * @param height {number} The overall height of this rectangle */ -function Rectangle(x, y, width, height) { +function Rectangle(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -60,7 +61,8 @@ * * @return {Rectangle} a copy of the rectangle */ -Rectangle.prototype.clone = function () { +Rectangle.prototype.clone = function () +{ return new Rectangle(this.x, this.y, this.width, this.height); }; @@ -71,13 +73,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rectangle */ -Rectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Rectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/math/shapes/RoundedRectangle.js b/src/core/math/shapes/RoundedRectangle.js index 27d286e..7bf6411 100644 --- a/src/core/math/shapes/RoundedRectangle.js +++ b/src/core/math/shapes/RoundedRectangle.js @@ -11,7 +11,8 @@ * @param height {number} The overall height of this rounded rectangle * @param radius {number} Controls the radius of the rounded corners */ -function RoundedRectangle(x, y, width, height, radius) { +function RoundedRectangle(x, y, width, height, radius) +{ /** * @member {number} * @default 0 @@ -58,7 +59,8 @@ * * @return {RoundedRectangle} a copy of the rounded rectangle */ -RoundedRectangle.prototype.clone = function () { +RoundedRectangle.prototype.clone = function () +{ return new RoundedRectangle(this.x, this.y, this.width, this.height, this.radius); }; @@ -69,13 +71,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rounded Rectangle */ -RoundedRectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +RoundedRectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/primitives/Graphics.js b/src/core/primitives/Graphics.js index 261c534..e902d2a 100644 --- a/src/core/primitives/Graphics.js +++ b/src/core/primitives/Graphics.js @@ -16,7 +16,8 @@ * @extends DisplayObjectContainer * @namespace PIXI */ -function Graphics() { +function Graphics() +{ DisplayObjectContainer.call(this); this.renderable = true; @@ -154,16 +155,20 @@ * @private */ cacheAsBitmap: { - get: function () { + get: function () + { return this._cacheAsBitmap; }, - set: function (value) { + set: function (value) + { this._cacheAsBitmap = value; - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._generateCachedSprite(); } - else { + else + { this.destroyCachedSprite(); this.dirty = true; } @@ -176,7 +181,8 @@ * * @return {Graphics} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ var clone = new Graphics(); clone.renderable = this.renderable; @@ -192,7 +198,8 @@ clone.cachedSpriteDirty = this.cachedSpriteDirty; // copy graphics data - for (var i = 0; i < this.graphicsData.length; ++i) { + for (var i = 0; i < this.graphicsData.length; ++i) + { clone.graphicsData.push(this.graphicsData.clone()); } @@ -211,17 +218,21 @@ * @param alpha {number} alpha of the line to draw, will update the objects stored style * @return {Graphics} */ -Graphics.prototype.lineStyle = function (lineWidth, color, alpha) { +Graphics.prototype.lineStyle = function (lineWidth, color, alpha) +{ this.lineWidth = lineWidth || 0; this.lineColor = color || 0; this.lineAlpha = (arguments.length < 3) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length) + { // halfway through a line? start a new one! this.drawShape( new math.Polygon( this.currentPath.shape.points.slice(-2) )); } - else { + else + { // otherwise its empty so lets just set the line properties this.currentPath.lineWidth = this.lineWidth; this.currentPath.lineColor = this.lineColor; @@ -239,7 +250,8 @@ * @param y {number} the Y coordinate to move to * @return {Graphics} */ -Graphics.prototype.moveTo = function (x, y) { +Graphics.prototype.moveTo = function (x, y) +{ this.drawShape(new math.Polygon([x,y])); return this; @@ -253,7 +265,8 @@ * @param y {number} the Y coordinate to draw to * @return {Graphics} */ -Graphics.prototype.lineTo = function (x, y) { +Graphics.prototype.lineTo = function (x, y) +{ this.currentPath.shape.points.push(x, y); this.dirty = true; @@ -270,13 +283,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -285,7 +302,8 @@ n = 20, points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { this.moveTo(0, 0); } @@ -293,7 +311,8 @@ var fromY = points[points.length-1]; var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; xa = fromX + ( (cpX - fromX) * j ); @@ -319,13 +338,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -342,7 +365,8 @@ var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; dt = (1 - j); @@ -373,13 +397,17 @@ * @param radius {number} The radius of the arc * @return {Graphics} */ -Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points.push(x1, y1); } } - else { + else + { this.moveTo(x1, y1); } @@ -392,12 +420,15 @@ b2 = x2 - x1, mm = Math.abs(a1 * b2 - b1 * a2); - if (mm < 1.0e-8 || radius === 0) { - if (points[points.length-2] !== x1 || points[points.length-1] !== y1) { + if (mm < 1.0e-8 || radius === 0) + { + if (points[points.length-2] !== x1 || points[points.length-1] !== y1) + { points.push(x1, y1); } } - else { + else + { var dd = a1 * a1 + b1 * b1, cc = a2 * a2 + b2 * b2, tt = a1 * a2 + b1 * b2, @@ -433,42 +464,51 @@ * @param anticlockwise {boolean} Optional. Specifies whether the drawing should be counterclockwise or clockwise. False is default, and indicates clockwise, while true indicates counter-clockwise. * @return {Graphics} */ -Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) { +Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) +{ var startX = cx + Math.cos(startAngle) * radius; var startY = cy + Math.sin(startAngle) * radius; var points; // TODO - This if-else makes no sense. It uses currentPath in the else where it doesn't exist... - if (this.currentPath) { + if (this.currentPath) + { points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { points.push(startX, startY); } - else if (points[points.length-2] !== startX || points[points.length-1] !== startY) { + else if (points[points.length-2] !== startX || points[points.length-1] !== startY) + { points.push(startX, startY); } } - else { + else + { this.moveTo(startX, startY); points = this.currentPath.shape.points; } - if (startAngle === endAngle) { + if (startAngle === endAngle) + { return this; } - if (!anticlockwise && endAngle <= startAngle) { + if (!anticlockwise && endAngle <= startAngle) + { endAngle += Math.PI * 2; } - else if (anticlockwise && startAngle <= endAngle) { + else if (anticlockwise && startAngle <= endAngle) + { startAngle += Math.PI * 2; } var sweep = anticlockwise ? (startAngle - endAngle) *-1 : (endAngle - startAngle); var segs = (Math.abs(sweep)/ (Math.PI * 2)) * 40; - if (sweep === 0) { + if (sweep === 0) + { return this; } @@ -482,7 +522,8 @@ var remainder = ( segMinus % 1 ) / segMinus; - for (var i = 0; i <= segMinus; ++i) { + for (var i = 0; i <= segMinus; ++i) + { var real = i + remainder * i; var angle = ((theta) + startAngle + (theta2 * real)); @@ -506,13 +547,16 @@ * @param alpha {number} the alpha of the fill * @return {Graphics} */ -Graphics.prototype.beginFill = function (color, alpha) { +Graphics.prototype.beginFill = function (color, alpha) +{ this.filling = true; this.fillColor = color || 0; this.fillAlpha = (alpha === undefined) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length <= 2) + { this.currentPath.fill = this.filling; this.currentPath.fillColor = this.fillColor; this.currentPath.fillAlpha = this.fillAlpha; @@ -526,7 +570,8 @@ * * @return {Graphics} */ -Graphics.prototype.endFill = function () { +Graphics.prototype.endFill = function () +{ this.filling = false; this.fillColor = null; this.fillAlpha = 1; @@ -542,7 +587,8 @@ * @param height {number} The height of the rectangle * @return {Graphics} */ -Graphics.prototype.drawRect = function ( x, y, width, height ) { +Graphics.prototype.drawRect = function ( x, y, width, height ) +{ this.drawShape(new math.Rectangle(x,y, width, height)); return this; @@ -556,7 +602,8 @@ * @param height {number} The height of the rectangle * @param radius {number} Radius of the rectangle corners */ -Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) { +Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) +{ this.drawShape(new math.RoundedRectangle(x, y, width, height, radius)); return this; @@ -570,7 +617,8 @@ * @param radius {number} The radius of the circle * @return {Graphics} */ -Graphics.prototype.drawCircle = function (x, y, radius) { +Graphics.prototype.drawCircle = function (x, y, radius) +{ this.drawShape(new math.Circle(x,y, radius)); return this; @@ -585,7 +633,8 @@ * @param height {number} The half height of the ellipse * @return {Graphics} */ -Graphics.prototype.drawEllipse = function (x, y, width, height) { +Graphics.prototype.drawEllipse = function (x, y, width, height) +{ this.drawShape(new math.Ellipse(x, y, width, height)); return this; @@ -597,8 +646,10 @@ * @param path {Array} The path data used to construct the polygon. * @return {Graphics} */ -Graphics.prototype.drawPolygon = function (path) { - if (!(path instanceof Array)) { +Graphics.prototype.drawPolygon = function (path) +{ + if (!(path instanceof Array)) + { path = Array.prototype.slice.call(arguments); } @@ -612,7 +663,8 @@ * * @return {Graphics} */ -Graphics.prototype.clear = function () { +Graphics.prototype.clear = function () +{ this.lineWidth = 0; this.filling = false; @@ -631,7 +683,8 @@ * @param scaleMode {number} Should be one of the scaleMode consts * @return {Texture} a texture of the graphics object */ -Graphics.prototype.generateTexture = function (resolution, scaleMode) { +Graphics.prototype.generateTexture = function (resolution, scaleMode) +{ resolution = resolution || 1; var bounds = this.getBounds(); @@ -655,17 +708,21 @@ * * @param renderer {WebGLRenderer} */ -Graphics.prototype._renderWebGL = function (renderer) { +Graphics.prototype._renderWebGL = function (renderer) +{ // if the sprite is not visible or the alpha is 0 then no need to render this element - if (this.isMask === true) { + if (this.isMask === true) + { return; } // this code may still be needed so leaving for now.. - // + // /* - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture on the gpu too! @@ -681,17 +738,24 @@ return; } - */ - - // check if the webgl graphic needs to be updated - if (this.glDirty) { - this.dirty = true; - this.glDirty = false; - } + else */ - renderer.setObjectRendererer(renderer.graphicsRenderer); - renderer.graphicsRenderer.render(this); + renderer.spriteBatch.stop(); + renderer.blendModeManager.setBlendMode(this.blendMode); + // check blend mode + renderer.blendModeManager.setBlendMode( this.blendMode ); + + // check if the webgl graphic needs to be updated + if (this.glDirty) + { + this.dirty = true; + this.glDirty = false; + } + + WebGLGraphics.renderGraphics(this, renderer); + + renderer.spriteBatch.start(); }; /** @@ -700,14 +764,18 @@ * @param renderer {CanvasRenderer} * @private */ -Graphics.prototype.renderCanvas = function (renderer) { +Graphics.prototype.renderCanvas = function (renderer) +{ // 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.isMask === true) { + if (!this.visible || this.alpha <= 0 || this.isMask === true) + { return; } - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture @@ -723,16 +791,19 @@ return; } - else { + else + { var context = renderer.context; var transform = this.worldTransform; - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } @@ -748,11 +819,13 @@ CanvasGraphics.renderGraphics(this, context); - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } } @@ -763,13 +836,16 @@ * * @return {Rectangle} the rectangular bounding area */ -Graphics.prototype.getBounds = function (matrix) { +Graphics.prototype.getBounds = function (matrix) +{ // return an empty object if the item is a mask! - if (this.isMask) { + if (this.isMask) + { return math.Rectangle.EMPTY; } - if (this.dirty) { + if (this.dirty) + { this.updateLocalBounds(); this.glDirty = true; @@ -841,23 +917,27 @@ * Update the bounds of the object * */ -Graphics.prototype.updateLocalBounds = function () { +Graphics.prototype.updateLocalBounds = function () +{ var minX = Infinity; var maxX = -Infinity; var minY = Infinity; var maxY = -Infinity; - if (this.graphicsData.length) { + if (this.graphicsData.length) + { var shape, points, x, y, w, h; - for (var i = 0; i < this.graphicsData.length; i++) { + for (var i = 0; i < this.graphicsData.length; i++) + { var data = this.graphicsData[i]; var type = data.type; var lineWidth = data.lineWidth; shape = data.shape; - if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) { + if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) + { x = shape.x - lineWidth/2; y = shape.y - lineWidth/2; w = shape.width + lineWidth; @@ -869,7 +949,8 @@ minY = y < minY ? y : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.CIRC) { + else if (type === CONST.SHAPES.CIRC) + { x = shape.x; y = shape.y; w = shape.radius + lineWidth/2; @@ -881,7 +962,8 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.ELIP) { + else if (type === CONST.SHAPES.ELIP) + { x = shape.x; y = shape.y; w = shape.width + lineWidth/2; @@ -893,11 +975,13 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else { + else + { // POLY points = shape.points; - for (var j = 0; j < points.length; j += 2) { + for (var j = 0; j < points.length; j += 2) + { x = points[j]; y = points[j+1]; @@ -910,7 +994,8 @@ } } } - else { + else + { minX = 0; maxX = 0; minY = 0; @@ -931,10 +1016,12 @@ * * @private */ -Graphics.prototype._generateCachedSprite = function () { +Graphics.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { var canvasBuffer = new CanvasBuffer(bounds.width, bounds.height); var texture = Texture.fromCanvas(canvasBuffer.canvas); @@ -943,7 +1030,8 @@ this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.buffer.resize(bounds.width, bounds.height); } @@ -968,7 +1056,8 @@ * * @private */ -Graphics.prototype.updateCachedSpriteTexture = function () { +Graphics.prototype.updateCachedSpriteTexture = function () +{ var cachedSprite = this._cachedSprite; var texture = cachedSprite.texture; var canvas = cachedSprite.buffer.canvas; @@ -989,7 +1078,8 @@ * Destroys a previous cached sprite. * */ -Graphics.prototype.destroyCachedSprite = function () { +Graphics.prototype.destroyCachedSprite = function () +{ this._cachedSprite.texture.destroy(true); // let the gc collect the unused sprite @@ -1003,10 +1093,13 @@ * @param {Circle|Rectangle|Ellipse|Line|Polygon} shape The Shape object to draw. * @return {GraphicsData} The generated GraphicsData object. */ -Graphics.prototype.drawShape = function (shape) { - if (this.currentPath) { +Graphics.prototype.drawShape = function (shape) +{ + if (this.currentPath) + { // check current path! - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath.shape.points.length <= 2) + { this.graphicsData.pop(); } } @@ -1017,7 +1110,8 @@ this.graphicsData.push(data); - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { data.shape.closed = this.filling; this.currentPath = data; } diff --git a/src/core/primitives/GraphicsData.js b/src/core/primitives/GraphicsData.js index 99decbe..788f6f2 100644 --- a/src/core/primitives/GraphicsData.js +++ b/src/core/primitives/GraphicsData.js @@ -4,7 +4,8 @@ * @class * @namespace PIXI */ -function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) { +function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) +{ this.lineWidth = lineWidth; this.lineColor = lineColor; this.lineAlpha = lineAlpha; @@ -27,7 +28,8 @@ * * @return {GraphicsData} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ return new GraphicsData( this.lineWidth, this.lineColor, diff --git a/src/core/renderers/canvas/CanvasRenderer.js b/src/core/renderers/canvas/CanvasRenderer.js index 15a0978..7aebd44 100644 --- a/src/core/renderers/canvas/CanvasRenderer.js +++ b/src/core/renderers/canvas/CanvasRenderer.js @@ -17,17 +17,22 @@ * @param [options.resolution=1] {number} the resolution of the renderer retina would be 2 * @param [options.clearBeforeRender=true] {boolean} This sets if the CanvasRenderer will clear the canvas or not before the new render pass. */ -function CanvasRenderer(width, height, options) { +function CanvasRenderer(width, height, options) +{ utils.sayHello('Canvas'); - if (options) { - for (var i in CONST.defaultRenderOptions) { - if (typeof options[i] === 'undefined') { + if (options) + { + for (var i in CONST.defaultRenderOptions) + { + if (typeof options[i] === 'undefined') + { options[i] = CONST.defaultRenderOptions[i]; } } } - else { + else + { options = CONST.defaultRenderOptions; } @@ -156,19 +161,24 @@ this.smoothProperty = null; - if (this.context.imageSmoothingEnabled) { + if (this.context.imageSmoothingEnabled) + { this.smoothProperty = 'imageSmoothingEnabled'; } - else if (this.context.webkitImageSmoothingEnabled) { + else if (this.context.webkitImageSmoothingEnabled) + { this.smoothProperty = 'webkitImageSmoothingEnabled'; } - else if (this.context.mozImageSmoothingEnabled) { + else if (this.context.mozImageSmoothingEnabled) + { this.smoothProperty = 'mozImageSmoothingEnabled'; } - else if (this.context.oImageSmoothingEnabled) { + else if (this.context.oImageSmoothingEnabled) + { this.smoothProperty = 'oImageSmoothingEnabled'; } - else if (this.context.msImageSmoothingEnabled) { + else if (this.context.msImageSmoothingEnabled) + { this.smoothProperty = 'msImageSmoothingEnabled'; } @@ -193,10 +203,12 @@ * @memberof CanvasRenderer# */ backgroundColor: { - get: function () { + get: function () + { return this._backgroundColor; }, - set: function (val) { + set: function (val) + { this._backgroundColor = val; this._backgroundColorString = utils.hex2string(val); } @@ -208,7 +220,8 @@ * * @param object {DisplayObject} the object to be rendered */ -CanvasRenderer.prototype.render = function (object) { +CanvasRenderer.prototype.render = function (object) +{ object.updateTransform(); this.context.setTransform(1,0,0,1,0,0); @@ -218,16 +231,20 @@ this.currentBlendMode = CONST.blendModes.NORMAL; this.context.globalCompositeOperation = this.blendModes[CONST.blendModes.NORMAL]; - if (navigator.isCocoonJS && this.view.screencanvas) { + if (navigator.isCocoonJS && this.view.screencanvas) + { this.context.fillStyle = 'black'; this.context.clear(); } - if (this.clearBeforeRender) { - if (this.transparent) { + if (this.clearBeforeRender) + { + if (this.transparent) + { this.context.clearRect(0, 0, this.width, this.height); } - else { + else + { this.context.fillStyle = this._backgroundColorString; this.context.fillRect(0, 0, this.width , this.height); } @@ -241,8 +258,10 @@ * * @param [removeView=false] {boolean} Removes the Canvas element from the DOM. */ -CanvasRenderer.prototype.destroy = function (removeView) { - if (removeView && this.view.parent) { +CanvasRenderer.prototype.destroy = function (removeView) +{ + if (removeView && this.view.parent) + { this.view.parent.removeChild(this.view); } @@ -257,14 +276,16 @@ * @param width {number} the new width of the canvas view * @param height {number} the new height of the canvas view */ -CanvasRenderer.prototype.resize = function (width, height) { +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) { + if (this.autoResize) + { this.view.style.width = this.width / this.resolution + 'px'; this.view.style.height = this.height / this.resolution + 'px'; } @@ -276,7 +297,8 @@ * @param displayObject {DisplayObject} The displayObject to render * @private */ -CanvasRenderer.prototype.renderDisplayObject = function (displayObject) { +CanvasRenderer.prototype.renderDisplayObject = function (displayObject) +{ displayObject.renderCanvas(this); }; @@ -285,11 +307,14 @@ * * @private */ -CanvasRenderer.prototype._mapBlendModes = function () { - if (!this.blendModes) { +CanvasRenderer.prototype._mapBlendModes = function () +{ + if (!this.blendModes) + { this.blendModes = {}; - if (utils.canUseNewCanvasBlendModes()) { + if (utils.canUseNewCanvasBlendModes()) + { this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? this.blendModes[CONST.blendModes.MULTIPLY] = 'multiply'; @@ -308,7 +333,8 @@ this.blendModes[CONST.blendModes.COLOR] = 'color'; this.blendModes[CONST.blendModes.LUMINOSITY] = 'luminosity'; } - else { + else + { // this means that the browser does not support the cool new blend modes in canvas 'cough' ie 'cough' this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? diff --git a/src/core/renderers/canvas/utils/CanvasBuffer.js b/src/core/renderers/canvas/utils/CanvasBuffer.js index ebe5d47..b183a66 100644 --- a/src/core/renderers/canvas/utils/CanvasBuffer.js +++ b/src/core/renderers/canvas/utils/CanvasBuffer.js @@ -6,7 +6,8 @@ * @param width {number} the width for the newly created canvas * @param height {number} the height for the newly created canvas */ -function CanvasBuffer(width, height) { +function CanvasBuffer(width, height) +{ /** * The Canvas object that belongs to this CanvasBuffer. * @@ -36,10 +37,12 @@ * @memberof CanvasBuffer# */ width: { - get: function () { + get: function () + { return this.canvas.width; }, - set: function (val) { + set: function (val) + { this.canvas.width = val; } }, @@ -50,10 +53,12 @@ * @memberof CanvasBuffer# */ height: { - get: function () { + get: function () + { return this.canvas.height; }, - set: function (val) { + set: function (val) + { this.canvas.height = val; } } @@ -64,7 +69,8 @@ * * @private */ -CanvasBuffer.prototype.clear = function () { +CanvasBuffer.prototype.clear = function () +{ this.context.setTransform(1, 0, 0, 1, 0, 0); this.context.clearRect(0,0, this.canvas.width, this.canvas.height); }; @@ -75,7 +81,8 @@ * @param width {number} the new width of the canvas * @param height {number} the new height of the canvas */ -CanvasBuffer.prototype.resize = function (width, height) { +CanvasBuffer.prototype.resize = function (width, height) +{ this.canvas.width = width; this.canvas.height = height; }; diff --git a/src/core/renderers/canvas/utils/CanvasGraphics.js b/src/core/renderers/canvas/utils/CanvasGraphics.js index c7eaa2a..3f2a91f 100644 --- a/src/core/renderers/canvas/utils/CanvasGraphics.js +++ b/src/core/renderers/canvas/utils/CanvasGraphics.js @@ -13,15 +13,18 @@ * @param graphics {Graphics} the actual graphics object to render * @param context {CanvasRenderingContext2D} the 2d drawing method of the canvas */ -CanvasGraphics.renderGraphics = function (graphics, context) { +CanvasGraphics.renderGraphics = function (graphics, context) +{ var worldAlpha = graphics.worldAlpha; - if (graphics.dirty) { + if (graphics.dirty) + { this.updateGraphicsTint(graphics); graphics.dirty = false; } - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; @@ -30,69 +33,82 @@ context.lineWidth = data.lineWidth; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { context.beginPath(); var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } - if (shape.closed) { + if (shape.closed) + { context.lineTo(points[0], points[1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fillRect(shape.x, shape.y, shape.width, shape.height); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.strokeRect(shape.x, shape.y, shape.width, shape.height); } } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.beginPath(); context.arc(shape.x, shape.y, shape.radius,0,2*Math.PI); context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas var w = shape.width * 2; @@ -119,18 +135,21 @@ context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; var width = shape.width; @@ -152,13 +171,15 @@ context.quadraticCurveTo(rx, ry, rx, ry + radius); context.closePath(); - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); @@ -174,45 +195,54 @@ * @param graphics {Graphics} the graphics which will be used as a mask * @param context {CanvasRenderingContext2D} the context 2d method of the canvas */ -CanvasGraphics.renderGraphicsMask = function (graphics, context) { +CanvasGraphics.renderGraphicsMask = function (graphics, context) +{ var len = graphics.graphicsData.length; - if (len === 0) { + if (len === 0) + { return; } context.beginPath(); - for (var i = 0; i < len; i++) { + for (var i = 0; i < len; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { context.rect(shape.x, shape.y, shape.width, shape.height); context.closePath(); } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.arc(shape.x, shape.y, shape.radius, 0, 2 * Math.PI); context.closePath(); } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas @@ -237,7 +267,8 @@ context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); context.closePath(); } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; @@ -262,8 +293,10 @@ } }; -CanvasGraphics.updateGraphicsTint = function (graphics) { - if (graphics.tint === 0xFFFFFF) { +CanvasGraphics.updateGraphicsTint = function (graphics) +{ + if (graphics.tint === 0xFFFFFF) + { return; } @@ -271,7 +304,8 @@ var tintG = (graphics.tint >> 8 & 0xFF) / 255; var tintB = (graphics.tint & 0xFF)/ 255; - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var fillColor = data.fillColor | 0; diff --git a/src/core/renderers/canvas/utils/CanvasMaskManager.js b/src/core/renderers/canvas/utils/CanvasMaskManager.js index e04a733..9827d36 100644 --- a/src/core/renderers/canvas/utils/CanvasMaskManager.js +++ b/src/core/renderers/canvas/utils/CanvasMaskManager.js @@ -6,7 +6,8 @@ * @class * @namespace PIXI */ -function CanvasMaskManager() {} +function CanvasMaskManager() +{} CanvasMaskManager.prototype.constructor = CanvasMaskManager; module.exports = CanvasMaskManager; @@ -17,7 +18,8 @@ * @param maskData {object} the maskData that will be pushed * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.pushMask = function (maskData, renderer) { +CanvasMaskManager.prototype.pushMask = function (maskData, renderer) +{ renderer.context.save(); var cacheAlpha = maskData.alpha; @@ -45,6 +47,7 @@ * * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.popMask = function (renderer) { +CanvasMaskManager.prototype.popMask = function (renderer) +{ renderer.context.restore(); }; diff --git a/src/core/renderers/canvas/utils/CanvasTinter.js b/src/core/renderers/canvas/utils/CanvasTinter.js index 17e0529..d2fb1bc 100644 --- a/src/core/renderers/canvas/utils/CanvasTinter.js +++ b/src/core/renderers/canvas/utils/CanvasTinter.js @@ -14,7 +14,8 @@ * @param color {number} the color to use to tint the sprite with * @return {HTMLCanvasElement} The tinted canvas */ -CanvasTinter.getTintedTexture = function (sprite, color) { +CanvasTinter.getTintedTexture = function (sprite, color) +{ var texture = sprite.texture; color = CanvasTinter.roundColor(color); @@ -23,7 +24,8 @@ texture.tintCache = texture.tintCache || {}; - if (texture.tintCache[stringColor]) { + if (texture.tintCache[stringColor]) + { return texture.tintCache[stringColor]; } @@ -33,14 +35,16 @@ //CanvasTinter.tintWithPerPixel(texture, stringColor, canvas); CanvasTinter.tintMethod(texture, color, canvas); - if (CanvasTinter.convertTintToImage) { + if (CanvasTinter.convertTintToImage) + { // is this better? var tintImage = new Image(); tintImage.src = canvas.toDataURL(); texture.tintCache[stringColor] = tintImage; } - else { + else + { texture.tintCache[stringColor] = canvas; // if we are not converting the texture to an image then we need to lose the reference to the canvas CanvasTinter.canvas = null; @@ -56,7 +60,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithMultiply = function (texture, color, canvas) { +CanvasTinter.tintWithMultiply = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -104,7 +109,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithOverlay = function (texture, color, canvas) { +CanvasTinter.tintWithOverlay = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -139,7 +145,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithPerPixel = function (texture, color, canvas) { +CanvasTinter.tintWithPerPixel = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -167,7 +174,8 @@ var pixels = pixelData.data; - for (var i = 0; i < pixels.length; i += 4) { + for (var i = 0; i < pixels.length; i += 4) + { pixels[i+0] *= r; pixels[i+1] *= g; pixels[i+2] *= b; @@ -181,7 +189,8 @@ * * @param color {number} the color to round, should be a hex color */ -CanvasTinter.roundColor = function (color) { +CanvasTinter.roundColor = function (color) +{ var step = CanvasTinter.cacheStepsPerColorChannel; var rgbValues = utils.hex2rgb(color); diff --git a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js index 9f2f89a..35edbaf 100644 --- a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js +++ b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLBlendModeManager(renderer) { +function WebGLBlendModeManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -23,8 +24,10 @@ * * @param blendMode {number} the blendMode, should be a Pixi const, such as BlendModes.ADD */ -WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) { - if (this.currentBlendMode === blendMode) { +WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) +{ + if (this.currentBlendMode === blendMode) + { return false; } diff --git a/src/core/renderers/webgl/managers/WebGLFilterManager.js b/src/core/renderers/webgl/managers/WebGLFilterManager.js index 1179258..2dac048 100644 --- a/src/core/renderers/webgl/managers/WebGLFilterManager.js +++ b/src/core/renderers/webgl/managers/WebGLFilterManager.js @@ -7,7 +7,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLFilterManager(renderer) { +function WebGLFilterManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -32,7 +33,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.texturePool.length = 0; self.initShaderBuffers(); }); @@ -46,7 +48,8 @@ * @param renderer {WebGLRenderer} * @param buffer {ArrayBuffer} */ -WebGLFilterManager.prototype.begin = function (buffer) { +WebGLFilterManager.prototype.begin = function (buffer) +{ this.defaultShader = this.renderer.shaderManager.defaultShader; this.width = this.renderer.projection.x * 2; @@ -60,7 +63,8 @@ * * @param filterBlock {object} the filter that will be pushed to the current filter stack */ -WebGLFilterManager.prototype.pushFilter = function (filterBlock) { +WebGLFilterManager.prototype.pushFilter = function (filterBlock) +{ var gl = this.renderer.gl; var projection = this.renderer.projection; @@ -78,10 +82,12 @@ this.offsetY += filterBlock._filterArea.y; var texture = this.texturePool.pop(); - if (!texture) { + if (!texture) + { texture = new FilterTexture(this.renderer.gl, this.width, this.height); } - else { + else + { texture.resize(this.width, this.height); } @@ -98,29 +104,35 @@ var localX = filterArea.x, localY = filterArea.y; - if (filterArea.x < 0) { + if (filterArea.x < 0) + { filterArea.width += filterArea.x; filterArea.x = 0; } - if (filterArea.y < 0) { + if (filterArea.y < 0) + { filterArea.height += filterArea.y; filterArea.y = 0; } - if (localX + filterArea.width > this.width) { + if (localX + filterArea.width > this.width) + { filterArea.width = this.width - localX; } - if (localY + filterArea.height > this.height) { + if (localY + filterArea.height > this.height) + { filterArea.height = this.height - localY; } - if (filterArea.width < 0) { + if (filterArea.width < 0) + { filterArea.width = 0; } - if (filterArea.height < 0) { + if (filterArea.height < 0) + { filterArea.height = 0; } @@ -154,7 +166,8 @@ * Removes the last filter from the filter stack and doesn't return it. * */ -WebGLFilterManager.prototype.popFilter = function () { +WebGLFilterManager.prototype.popFilter = function () +{ var gl = this.renderer.gl; var filterBlock = this.filterStack.pop(); @@ -163,7 +176,8 @@ var projection = this.renderer.projection; var offset = this.renderer.offset; - if (filterBlock.filterPasses.length > 1) { + if (filterBlock.filterPasses.length > 1) + { gl.viewport(0, 0, filterArea.width, filterArea.height); gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); @@ -193,7 +207,8 @@ var inputTexture = texture; var outputTexture = this.texturePool.pop(); - if (!outputTexture) { + if (!outputTexture) + { outputTexture = new FilterTexture(this.renderer.gl, this.width, this.height); } outputTexture.resize(this.width, this.height); @@ -204,7 +219,8 @@ gl.disable(gl.BLEND); - for (var i = 0; i < filterBlock.filterPasses.length-1; i++) { + for (var i = 0; i < filterBlock.filterPasses.length-1; i++) + { var filterPass = filterBlock.filterPasses[i]; gl.bindFramebuffer(gl.FRAMEBUFFER, outputTexture.frameBuffer ); @@ -243,10 +259,12 @@ var buffer = this.buffer; // time to render the filters texture to the previous scene - if (this.filterStack.length === 0) { + if (this.filterStack.length === 0) + { gl.colorMask(true, true, true, true);//this.transparent); } - else { + else + { var currentFilter = this.filterStack[this.filterStack.length-1]; filterArea = currentFilter._filterArea; @@ -332,13 +350,15 @@ * @param width {number} the horizontal range of the filter * @param height {number} the vertical range of the filter */ -WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) { +WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) +{ // use program var gl = this.renderer.gl; var shader = filter.shaders[gl.id]; - if (!shader) { + if (!shader) + { shader = new Shader(gl); shader.fragmentSrc = filter.fragmentSrc; @@ -356,7 +376,8 @@ gl.uniform2f(shader.projectionVector, width/2, -height/2); gl.uniform2f(shader.offsetVector, 0,0); - if (filter.uniforms.dimensions) { + 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]; @@ -386,7 +407,8 @@ * Initialises the shader buffers. * */ -WebGLFilterManager.prototype.initShaderBuffers = function () { +WebGLFilterManager.prototype.initShaderBuffers = function () +{ var gl = this.renderer.gl; // create some buffers @@ -432,7 +454,8 @@ * Destroys the filter and removes it from the filter stack. * */ -WebGLFilterManager.prototype.destroy = function () { +WebGLFilterManager.prototype.destroy = function () +{ var gl = this.renderer.gl; this.filterStack = null; @@ -441,7 +464,8 @@ this.offsetY = 0; // destroy textures - for (var i = 0; i < this.texturePool.length; i++) { + for (var i = 0; i < this.texturePool.length; i++) + { this.texturePool[i].destroy(); } diff --git a/src/core/renderers/webgl/managers/WebGLManager.js b/src/core/renderers/webgl/managers/WebGLManager.js index 9d47b5c..c30cd51 100644 --- a/src/core/renderers/webgl/managers/WebGLManager.js +++ b/src/core/renderers/webgl/managers/WebGLManager.js @@ -3,7 +3,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLManager(renderer) { +function WebGLManager(renderer) +{ /** * The renderer this manager works for. * @@ -15,6 +16,7 @@ WebGLManager.prototype.constructor = WebGLManager; module.exports = WebGLManager; -WebGLManager.prototype.destroy = function () { +WebGLManager.prototype.destroy = function () +{ this.renderer = null; }; diff --git a/src/core/renderers/webgl/managers/WebGLMaskManager.js b/src/core/renderers/webgl/managers/WebGLMaskManager.js index 2f90b64..e568812 100644 --- a/src/core/renderers/webgl/managers/WebGLMaskManager.js +++ b/src/core/renderers/webgl/managers/WebGLMaskManager.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLMaskManager(renderer) { +function WebGLMaskManager(renderer) +{ WebGLManager.call(this, renderer); } @@ -19,12 +20,15 @@ * * @param maskData {any[]} */ -WebGLMaskManager.prototype.pushMask = function (maskData) { - if (maskData.dirty) { +WebGLMaskManager.prototype.pushMask = function (maskData) +{ + if (maskData.dirty) + { WebGLGraphics.updateGraphics(maskData, this.renderer.gl); } - if (!maskData._webGL[this.renderer.gl.id].data.length) { + if (!maskData._webGL[this.renderer.gl.id].data.length) + { return; } @@ -36,6 +40,7 @@ * * @param maskData {any[]} */ -WebGLMaskManager.prototype.popMask = function (maskData) { +WebGLMaskManager.prototype.popMask = function (maskData) +{ this.renderer.stencilManager.popStencil(maskData, maskData._webGL[this.renderer.gl.id].data[0], this.renderer); }; diff --git a/src/core/renderers/webgl/managers/WebGLShaderManager.js b/src/core/renderers/webgl/managers/WebGLShaderManager.js index fef071c..90c6477 100644 --- a/src/core/renderers/webgl/managers/WebGLShaderManager.js +++ b/src/core/renderers/webgl/managers/WebGLShaderManager.js @@ -10,7 +10,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLShaderManager(renderer) { +function WebGLShaderManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -28,7 +29,8 @@ */ this.tempAttribState = []; - for (var i = 0; i < this.maxAttibs; i++) { + for (var i = 0; i < this.maxAttibs; i++) + { this.attribState[i] = false; } @@ -66,7 +68,8 @@ // listen for context and update necessary shaders var self = this; - this.renderer.on('context', function (event) { + this.renderer.on('context', function (event) + { var gl = event.data; // this shader is used for rendering primitives @@ -97,29 +100,36 @@ * * @param attribs {Array} attribs */ -WebGLShaderManager.prototype.setAttribs = function (attribs) { +WebGLShaderManager.prototype.setAttribs = function (attribs) +{ // reset temp state var i; - for (i = 0; i < this.tempAttribState.length; i++) { + for (i = 0; i < this.tempAttribState.length; i++) + { this.tempAttribState[i] = false; } // set the new attribs - for (var a in attribs) { + for (var a in attribs) + { this.tempAttribState[attribs[a]] = true; } var gl = this.renderer.gl; - for (i = 0; i < this.attribState.length; i++) { - if (this.attribState[i] !== this.tempAttribState[i]) { + for (i = 0; i < this.attribState.length; i++) + { + if (this.attribState[i] !== this.tempAttribState[i]) + { this.attribState[i] = this.tempAttribState[i]; - if (this.attribState[i]) { + if (this.attribState[i]) + { gl.enableVertexAttribArray(i); } - else { + else + { gl.disableVertexAttribArray(i); } } @@ -131,8 +141,10 @@ * * @param shader {Any} */ -WebGLShaderManager.prototype.setShader = function (shader) { - if (this._currentId === shader.uuid) { +WebGLShaderManager.prototype.setShader = function (shader) +{ + if (this._currentId === shader.uuid) + { return false; } @@ -150,7 +162,8 @@ * Destroys this object. * */ -WebGLShaderManager.prototype.destroy = function () { +WebGLShaderManager.prototype.destroy = function () +{ this.attribState = null; this.tempAttribState = null; diff --git a/src/core/renderers/webgl/managers/WebGLStencilManager.js b/src/core/renderers/webgl/managers/WebGLStencilManager.js index 9ec6398..4cb0134 100644 --- a/src/core/renderers/webgl/managers/WebGLStencilManager.js +++ b/src/core/renderers/webgl/managers/WebGLStencilManager.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLStencilManager(renderer) { +function WebGLStencilManager(renderer) +{ WebGLManager.call(this, renderer); this.stencilStack = []; @@ -24,12 +25,14 @@ * @param graphics {Graphics} * @param webGLData {any[]} */ -WebGLStencilManager.prototype.pushStencil = function (graphics, webGLData) { +WebGLStencilManager.prototype.pushStencil = function (graphics, webGLData) +{ var gl = this.renderer.gl; this.bindGraphics(graphics, webGLData, this.renderer); - if (this.stencilStack.length === 0) { + if (this.stencilStack.length === 0) + { gl.enable(gl.STENCIL_TEST); gl.clear(gl.STENCIL_BUFFER_BIT); this.reverse = true; @@ -47,14 +50,17 @@ // draw the triangle strip! - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } @@ -62,31 +68,38 @@ // draw a quad to increment.. gl.drawElements(gl.TRIANGLE_FAN, 4, gl.UNSIGNED_SHORT, ( webGLData.indices.length - 4 ) * 2 ); - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); } this.reverse = !this.reverse; } - else { - if (!this.reverse) { + else + { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } - else { + 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) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); } } @@ -103,7 +116,8 @@ * @param graphics {Graphics} * @param webGLData {Array} */ -WebGLStencilManager.prototype.bindGraphics = function (graphics, webGLData) { +WebGLStencilManager.prototype.bindGraphics = function (graphics, webGLData) +{ //if (this._currentGraphics === graphics)return; this._currentGraphics = graphics; @@ -114,7 +128,8 @@ offset = this.renderer.offset, shader;// = this.renderer.shaderManager.primitiveShader; - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { shader = this.renderer.shaderManager.complexPrimitiveShader; this.renderer.shaderManager.setShader(shader); @@ -141,7 +156,8 @@ // set the index buffer! gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, webGLData.indexBuffer); } - else { + else + { //this.renderer.shaderManager.activatePrimitiveShader(); shader = this.renderer.shaderManager.primitiveShader; this.renderer.shaderManager.setShader( shader ); @@ -154,7 +170,7 @@ gl.uniform2f(shader.uniforms.offsetVector._location, -offset.x, -offset.y); gl.uniform3fv(shader.uniforms.tint._location, utils.hex2rgb(graphics.tint)); - + gl.uniform1f(shader.uniforms.alpha._location, graphics.worldAlpha); @@ -172,19 +188,22 @@ * @param graphics {Graphics} * @param webGLData {Array} */ -WebGLStencilManager.prototype.popStencil = function (graphics, webGLData) { +WebGLStencilManager.prototype.popStencil = function (graphics, webGLData) +{ var gl = this.renderer.gl; this.stencilStack.pop(); this.count--; - if (this.stencilStack.length === 0) { + if (this.stencilStack.length === 0) + { // the stack is empty! gl.disable(gl.STENCIL_TEST); } - else { + else + { var level = this.count; @@ -192,14 +211,17 @@ gl.colorMask(false, false, false, false); - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { this.reverse = !this.reverse; - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } @@ -213,31 +235,38 @@ // draw the triangle strip! gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); - if (!this.reverse) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); } } - else { + else + { // console.log("<<>>") - if (!this.reverse) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } - else { + 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) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); } } @@ -253,7 +282,8 @@ * Destroys the mask stack. * */ -WebGLStencilManager.prototype.destroy = function () { +WebGLStencilManager.prototype.destroy = function () +{ this.renderer = null; this.stencilStack = null; }; diff --git a/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js b/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js index 913ba5e..1ea7d19 100644 --- a/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js +++ b/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function ComplexPrimitiveShader(gl) { +function ComplexPrimitiveShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -24,7 +25,8 @@ 'uniform float flipY;', 'varying vec4 vColor;', - 'void main(void) {', + '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);', @@ -37,7 +39,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = vColor;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/FastShader.js b/src/core/renderers/webgl/shaders/FastShader.js index bd2e29a..2e5e060 100644 --- a/src/core/renderers/webgl/shaders/FastShader.js +++ b/src/core/renderers/webgl/shaders/FastShader.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function FastShader(gl) { +function FastShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -28,7 +29,8 @@ 'const vec2 center = vec2(-1.0, 1.0);', - 'void main(void) {', + 'void main(void) + {', ' vec2 v;', ' vec2 sv = aVertexPosition * aScale;', ' v.x = (sv.x) * cos(aRotation) - (sv.y) * sin(aRotation);', @@ -49,7 +51,8 @@ 'uniform sampler2D uSampler;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/PrimitiveShader.js b/src/core/renderers/webgl/shaders/PrimitiveShader.js index 6f25409..a25f54f 100644 --- a/src/core/renderers/webgl/shaders/PrimitiveShader.js +++ b/src/core/renderers/webgl/shaders/PrimitiveShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function PrimitiveShader(gl) { +function PrimitiveShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -23,7 +24,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + '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);', @@ -36,7 +38,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = vColor;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/Shader.js b/src/core/renderers/webgl/shaders/Shader.js index f8964f5..fd75ef5 100644 --- a/src/core/renderers/webgl/shaders/Shader.js +++ b/src/core/renderers/webgl/shaders/Shader.js @@ -6,7 +6,8 @@ * @param [fragmentSrc] {string} The source of the fragment shader. * @param [vertexSrc] {string} The source of the vertex shader. */ -function Shader(gl, vertexSrc, fragmentSrc, customUniforms, customAttributes) { +function Shader(gl, vertexSrc, fragmentSrc, customUniforms, customAttributes) +{ /** * @member {number} * @readonly @@ -33,7 +34,8 @@ dimensions: { type: '4f', value: new Float32Array(4) } }; - for (var u in customUniforms) { + for (var u in customUniforms) + { this.uniforms[u] = customUniforms[u]; } @@ -43,7 +45,8 @@ aColor: 0 }; - for (var a in customAttributes) { + for (var a in customAttributes) + { this.attributes[a] = customAttributes[a]; } @@ -66,7 +69,8 @@ 'const vec2 center = vec2(-1.0, 1.0);', - 'void main(void) {', + 'void main(void) + {', ' gl_Position = vec4( ((aVertexPosition + offsetVector) / projectionVector) + center , 0.0, 1.0);', ' vTextureCoord = aTextureCoord;', ' vColor = vec4(aColor.rgb * aColor.a, aColor.a);', @@ -85,7 +89,8 @@ 'uniform sampler2D uSampler;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;', '}' ].join('\n'); @@ -96,7 +101,8 @@ Shader.prototype.constructor = Shader; module.exports = Shader; -Shader.prototype.init = function () { +Shader.prototype.init = function () +{ this.compile(); this.gl.useProgram(this.program); @@ -105,14 +111,18 @@ this.cacheAttributeLocations(Object.keys(this.attributes)); }; -Shader.prototype.cacheUniformLocations = function (keys) { - for (var i = 0; i < keys.length; ++i) { +Shader.prototype.cacheUniformLocations = function (keys) +{ + for (var i = 0; i < keys.length; ++i) + { this.uniforms[keys[i]]._location = this.gl.getUniformLocation(this.program, keys[i]); } }; -Shader.prototype.cacheAttributeLocations = function (keys) { - for (var i = 0; i < keys.length; ++i) { +Shader.prototype.cacheAttributeLocations = function (keys) +{ + for (var i = 0; i < keys.length; ++i) + { this.attributes[keys[i]] = this.gl.getAttribLocation(this.program, keys[i]); } @@ -124,14 +134,16 @@ // 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.attributes.aColor === -1) { + // if (this.attributes.aColor === -1) + { // this.attributes.aColor = 2; // } // End worst hack eva // }; -Shader.prototype.compile = function () { +Shader.prototype.compile = function () +{ var gl = this.gl; var glVertShader = this._glCompile(gl.VERTEX_SHADER, this.vertexSrc); @@ -144,13 +156,15 @@ gl.linkProgram(program); // if linking fails, then log and cleanup - if (!gl.getProgramParameter(program, gl.LINK_STATUS)) { + if (!gl.getProgramParameter(program, gl.LINK_STATUS)) + { window.console.error('Pixi.js Error: Could not initialize shader.'); window.console.error('gl.VALIDATE_STATUS', gl.getProgramParameter(program, gl.VALIDATE_STATUS)); window.console.error('gl.getError()', gl.getError()); // if there is a program info log, log it - if (gl.getProgramInfoLog(program) !== '') { + if (gl.getProgramInfoLog(program) !== '') + { window.console.warn('Pixi.js Warning: gl.getProgramInfoLog()', gl.getProgramInfoLog(program)); } @@ -165,18 +179,21 @@ return (this.program = program); }; -Shader.prototype.syncUniforms = function () { +Shader.prototype.syncUniforms = function () +{ var gl = this.gl; this.textureCount = 1; - for (var key in this.uniforms) { + for (var key in this.uniforms) + { var uniform = this.uniforms[key], location = uniform._location, value = uniform.value, i, il; - switch (uniform.type) { + switch (uniform.type) + { // single int value case 'i': case '1i': @@ -282,7 +299,8 @@ // a Color Value case 'c': - if (typeof value === 'number') { + if (typeof value === 'number') + { value = utils.hex2rgb(value); } @@ -311,11 +329,13 @@ // array of 2D Point objects case 'v2v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(2 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 2] = value[i].x; uniform._array[i * 2 + 1] = value[i].y; } @@ -325,11 +345,13 @@ // array of 3D Point objects case 'v3v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(3 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 3] = value[i].x; uniform._array[i * 3 + 1] = value[i].y; uniform._array[i * 3 + 2] = value[i].z; @@ -341,11 +363,13 @@ // array of 4D Point objects case 'v4v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(4 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 4] = value[i].x; uniform._array[i * 4 + 1] = value[i].y; uniform._array[i * 4 + 2] = value[i].z; @@ -359,7 +383,8 @@ // PIXI.Texture case 't': case 'sampler2D': - if (!uniform.value || !uniform.value.baseTexture || !uniform.value.baseTexture.hasLoaded) { + if (!uniform.value || !uniform.value.baseTexture || !uniform.value.baseTexture.hasLoaded) + { break; } @@ -376,7 +401,8 @@ this.textureCount++; // initialize the texture if we haven't yet - if (!uniform._init) { + if (!uniform._init) + { this.initSampler2D(uniform); uniform._init = true; @@ -394,11 +420,13 @@ * Initialises a Sampler2D uniform (which may only be available later on after initUniforms once the texture has loaded) * */ -Shader.prototype.initSampler2D = function (uniform) { +Shader.prototype.initSampler2D = function (uniform) +{ var gl = this.gl; // Extended texture data - if (uniform.textureData) { + if (uniform.textureData) + { var data = uniform.textureData; // GLTexture = mag linear, min linear_mipmap_linear, wrap repeat + gl.generateMipmap(gl.TEXTURE_2D); @@ -417,14 +445,16 @@ var wrapT = (data.wrapT) ? data.wrapT : gl.CLAMP_TO_EDGE; var format = (data.luminance) ? gl.LUMINANCE : gl.RGBA; - if (data.repeat) { + if (data.repeat) + { wrapS = gl.REPEAT; wrapT = gl.REPEAT; } gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, !!data.flipY); - if (data.width) { + if (data.width) + { var width = (data.width) ? data.width : 512; var height = (data.height) ? data.height : 2; var border = (data.border) ? data.border : 0; @@ -432,7 +462,8 @@ // 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 { + 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); } @@ -448,7 +479,8 @@ * Destroys the shader. * */ -Shader.prototype.destroy = function () { +Shader.prototype.destroy = function () +{ this.gl.deleteProgram(this.program); this.gl = null; @@ -459,13 +491,15 @@ this.fragmentSrc = null; }; -Shader.prototype._glCompile = function (type, src) { +Shader.prototype._glCompile = function (type, src) +{ var shader = this.gl.createShader(type); this.gl.shaderSource(shader, src); this.gl.compileShader(shader); - if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) { + if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) + { window.console.log(this.gl.getShaderInfoLog(shader)); return null; } diff --git a/src/core/renderers/webgl/shaders/StripShader.js b/src/core/renderers/webgl/shaders/StripShader.js index 193f6e1..a7abcc6 100644 --- a/src/core/renderers/webgl/shaders/StripShader.js +++ b/src/core/renderers/webgl/shaders/StripShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function StripShader(gl) { +function StripShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -20,7 +21,8 @@ 'varying vec2 vTextureCoord;', - 'void main(void) {', + '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);', @@ -36,7 +38,8 @@ 'varying vec2 vTextureCoord;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vec2(vTextureCoord.x, vTextureCoord.y)) * alpha;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/utils/FilterTexture.js b/src/core/renderers/webgl/utils/FilterTexture.js index d2c8423..4433d44 100644 --- a/src/core/renderers/webgl/utils/FilterTexture.js +++ b/src/core/renderers/webgl/utils/FilterTexture.js @@ -8,7 +8,8 @@ * @param height {number} the vertical range of the filter * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values */ -function FilterTexture(gl, width, height, scaleMode) { +function FilterTexture(gl, width, height, scaleMode) +{ /** * @member {WebGLContext} */ @@ -59,7 +60,8 @@ * Clears the filter texture. * */ -FilterTexture.prototype.clear = function () { +FilterTexture.prototype.clear = function () +{ var gl = this.gl; gl.clearColor(0,0,0, 0); @@ -72,8 +74,10 @@ * @param width {number} the new width of the texture * @param height {number} the new height of the texture */ -FilterTexture.prototype.resize = function (width, height) { - if (this.width === width && this.height === height) { +FilterTexture.prototype.resize = function (width, height) +{ + if (this.width === width && this.height === height) + { return; } @@ -96,7 +100,8 @@ * Destroys the filter texture. * */ -FilterTexture.prototype.destroy = function () { +FilterTexture.prototype.destroy = function () +{ var gl = this.gl; gl.deleteFramebuffer( this.frameBuffer ); gl.deleteTexture( this.texture ); diff --git a/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js b/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js index c4721e9..a63f4d7 100644 --- a/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js +++ b/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js @@ -14,7 +14,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this sprite batch works for. */ -function WebGLFastSpriteBatch(renderer) { +function WebGLFastSpriteBatch(renderer) +{ /** * The renderer instance this sprite batch operates on. * @@ -91,7 +92,8 @@ */ this.lastIndexCount = 0; - for (var i=0, j=0; i < numIndices; i += 6, j += 4) { + 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; @@ -144,7 +146,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.setupContext(); }); } @@ -157,7 +160,8 @@ * * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLFastSpriteBatch.prototype.setupContext = function () { +WebGLFastSpriteBatch.prototype.setupContext = function () +{ var gl = this.renderer.gl; // create a couple of buffers @@ -177,7 +181,8 @@ /** * @param spriteBatch {SpriteBatch} The SpriteBatch container to prepare for. */ -WebGLFastSpriteBatch.prototype.begin = function (spriteBatch) { +WebGLFastSpriteBatch.prototype.begin = function (spriteBatch) +{ this.shader = this.renderer.shaderManager.fastShader; this.matrix = spriteBatch.worldTransform.toArray(true); @@ -187,33 +192,38 @@ /** */ -WebGLFastSpriteBatch.prototype.end = function () { +WebGLFastSpriteBatch.prototype.end = function () +{ this.flush(); }; /** * @param spriteBatch {SpriteBatch} The SpriteBatch container to render. */ -WebGLFastSpriteBatch.prototype.render = function (spriteBatch) { +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) { + if (!sprite.texture._uvs) + { return; } this.currentBaseTexture = sprite.texture.baseTexture; // check blend mode - if (sprite.blendMode !== this.renderer.blendModeManager.currentBlendMode) { + if (sprite.blendMode !== this.renderer.blendModeManager.currentBlendMode) + { this.flush(); this.renderer.blendModeManager.setBlendMode(sprite.blendMode); } - for (var i=0,j= children.length; i= this.size) { + if (this.currentBatchSize >= this.size) + { this.flush(); } }; @@ -362,29 +379,35 @@ /** * */ -WebGLFastSpriteBatch.prototype.flush = function () { +WebGLFastSpriteBatch.prototype.flush = function () +{ // If the batch is length 0 then return as there is nothing to draw - if (this.currentBatchSize === 0) { + if (this.currentBatchSize === 0) + { return; } var gl = this.renderer.gl; // bind the current texture - if (!this.currentBaseTexture._glTextures[gl.id]) { + if (!this.currentBaseTexture._glTextures[gl.id]) + { this.renderer.updateTexture(this.currentBaseTexture, gl); } //TODO-SHOUD THIS BE ELSE??!?!?! - else { + else + { gl.bindTexture(gl.TEXTURE_2D, this.currentBaseTexture._glTextures[gl.id]); } // upload the verts to the buffer - if (this.currentBatchSize > ( this.size * 0.5 ) ) { + if (this.currentBatchSize > ( this.size * 0.5 ) ) + { gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); } - else { + else + { var view = this.vertices.subarray(0, this.currentBatchSize * this.vertByteSize); gl.bufferSubData(gl.ARRAY_BUFFER, 0, view); @@ -405,14 +428,16 @@ * Ends the batch and flushes * */ -WebGLFastSpriteBatch.prototype.stop = function () { +WebGLFastSpriteBatch.prototype.stop = function () +{ this.flush(); }; /** * */ -WebGLFastSpriteBatch.prototype.start = function () { +WebGLFastSpriteBatch.prototype.start = function () +{ var gl = this.renderer.gl; // bind the main texture diff --git a/src/core/renderers/webgl/utils/WebGLGraphics.js b/src/core/renderers/webgl/utils/WebGLGraphics.js index 55f4911..ab8f46e 100644 --- a/src/core/renderers/webgl/utils/WebGLGraphics.js +++ b/src/core/renderers/webgl/utils/WebGLGraphics.js @@ -19,7 +19,8 @@ * @param graphics {Graphics} * @param renderer {WebGLRenderer} */ -WebGLGraphics.renderGraphics = function (graphics, renderer) {//projection, offset) { +WebGLGraphics.renderGraphics = function (graphics, renderer) {//projection, offset) +{ var gl = renderer.gl; var projection = renderer.projection, @@ -27,7 +28,8 @@ shader = renderer.shaderManager.primitiveShader, webGLData; - if (graphics.dirty) { + if (graphics.dirty) + { WebGLGraphics.updateGraphics(graphics, gl); } @@ -35,8 +37,10 @@ // This could be speeded up for sure! - for (var i = 0; i < webGL.data.length; i++) { - if (webGL.data[i].mode === 1) { + for (var i = 0; i < webGL.data.length; i++) + { + if (webGL.data[i].mode === 1) + { webGLData = webGL.data[i]; renderer.stencilManager.pushStencil(graphics, webGLData, renderer); @@ -46,7 +50,8 @@ renderer.stencilManager.popStencil(graphics, webGLData, renderer); } - else { + else + { webGLData = webGL.data[i]; @@ -84,12 +89,14 @@ * @param graphicsData {Graphics} The graphics object to update * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLGraphics.updateGraphics = function (graphics, gl) { +WebGLGraphics.updateGraphics = function (graphics, gl) +{ // get the contexts graphics object var webGL = graphics._webGL[gl.id]; // if the graphics object does not exist in the webGL context time to create it! - if (!webGL) { + if (!webGL) + { webGL = graphics._webGL[gl.id] = {lastIndex:0, data:[], gl:gl}; } @@ -99,11 +106,13 @@ var i; // if the user cleared the graphics object we will need to clear every object - if (graphics.clearDirty) { + if (graphics.clearDirty) + { graphics.clearDirty = false; // lop through and return all the webGLDatas to the object pool so than can be reused later on - for (i = 0; i < webGL.data.length; i++) { + for (i = 0; i < webGL.data.length; i++) + { var graphicsData = webGL.data[i]; graphicsData.reset(); WebGLGraphics.graphicsDataPool.push( graphicsData ); @@ -119,58 +128,72 @@ // loop through the graphics datas and construct each one.. // if the object is a complex fill then the new stencil buffer technique will be used // other wise graphics objects will be pushed into a batch.. - for (i = webGL.lastIndex; i < graphics.graphicsData.length; i++) { + for (i = webGL.lastIndex; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { // need to add the points the the graphics object.. data.points = data.shape.points.slice(); - if (data.shape.closed) { + if (data.shape.closed) + { // close the poly if the value is true! - if (data.points[0] !== data.points[data.points.length-2] || data.points[1] !== data.points[data.points.length-1]) { + if (data.points[0] !== data.points[data.points.length-2] || data.points[1] !== data.points[data.points.length-1]) + { data.points.push(data.points[0], data.points[1]); } } // MAKE SURE WE HAVE THE CORRECT TYPE.. - if (data.fill) { - if (data.points.length >= 6) { - if (data.points.length < 6 * 2) { + if (data.fill) + { + if (data.points.length >= 6) + { + if (data.points.length < 6 * 2) + { webGLData = WebGLGraphics.switchMode(webGL, 0); var canDrawUsingSimple = WebGLGraphics.buildPoly(data, webGLData); // console.log(canDrawUsingSimple); - if (!canDrawUsingSimple) { + if (!canDrawUsingSimple) + { // console.log("<>>>") webGLData = WebGLGraphics.switchMode(webGL, 1); WebGLGraphics.buildComplexPoly(data, webGLData); } } - else { + else + { webGLData = WebGLGraphics.switchMode(webGL, 1); WebGLGraphics.buildComplexPoly(data, webGLData); } } } - if (data.lineWidth > 0) { + if (data.lineWidth > 0) + { webGLData = WebGLGraphics.switchMode(webGL, 0); WebGLGraphics.buildLine(data, webGLData); } } - else { + else + { webGLData = WebGLGraphics.switchMode(webGL, 0); - if (data.type === CONST.SHAPES.RECT) { + if (data.type === CONST.SHAPES.RECT) + { WebGLGraphics.buildRectangle(data, webGLData); } - else if (data.type === CONST.SHAPES.CIRC || data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.CIRC || data.type === CONST.SHAPES.ELIP) + { WebGLGraphics.buildCircle(data, webGLData); } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { WebGLGraphics.buildRoundedRectangle(data, webGLData); } } @@ -179,10 +202,12 @@ } // upload all the dirty data... - for (i = 0; i < webGL.data.length; i++) { + for (i = 0; i < webGL.data.length; i++) + { webGLData = webGL.data[i]; - if (webGLData.dirty) { + if (webGLData.dirty) + { webGLData.upload(); } } @@ -194,18 +219,22 @@ * @param webGL {WebGLContext} * @param type {number} */ -WebGLGraphics.switchMode = function (webGL, type) { +WebGLGraphics.switchMode = function (webGL, type) +{ var webGLData; - if (!webGL.data.length) { + if (!webGL.data.length) + { webGLData = WebGLGraphics.graphicsDataPool.pop() || new WebGLGraphicsData(webGL.gl); webGLData.mode = type; webGL.data.push(webGLData); } - else { + else + { webGLData = webGL.data[webGL.data.length-1]; - if (webGLData.mode !== type || type === 1) { + if (webGLData.mode !== type || type === 1) + { webGLData = WebGLGraphics.graphicsDataPool.pop() || new WebGLGraphicsData(webGL.gl); webGLData.mode = type; webGL.data.push(webGLData); @@ -225,7 +254,8 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildRectangle = function (graphicsData, webGLData) { +WebGLGraphics.buildRectangle = function (graphicsData, webGLData) +{ // --- // // need to convert points to a nice regular data // @@ -235,7 +265,8 @@ var width = rectData.width; var height = rectData.height; - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -265,7 +296,8 @@ indices.push(vertPos, vertPos, vertPos+1, vertPos+2, vertPos+3, vertPos+3); } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = [x, y, @@ -289,7 +321,8 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildRoundedRectangle = function (graphicsData, webGLData) { +WebGLGraphics.buildRoundedRectangle = function (graphicsData, webGLData) +{ var rrectData = graphicsData.shape; var x = rrectData.x; var y = rrectData.y; @@ -305,7 +338,8 @@ recPoints = recPoints.concat(WebGLGraphics.quadraticBezierCurve(x + width, y + radius, x + width, y, x + width - radius, y)); recPoints = recPoints.concat(WebGLGraphics.quadraticBezierCurve(x + radius, y, x, y, x, y + radius)); - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -323,7 +357,8 @@ // var i = 0; - for (i = 0; i < triangles.length; i+=3) { + for (i = 0; i < triangles.length; i+=3) + { indices.push(triangles[i] + vecPos); indices.push(triangles[i] + vecPos); indices.push(triangles[i+1] + vecPos); @@ -332,12 +367,14 @@ } - for (i = 0; i < recPoints.length; i++) { + for (i = 0; i < recPoints.length; i++) + { verts.push(recPoints[i], recPoints[++i], r, g, b, alpha); } } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = recPoints; @@ -362,7 +399,8 @@ * @param toY {number} Destination point y * @return {number[]} */ -WebGLGraphics.quadraticBezierCurve = function (fromX, fromY, cpX, cpY, toX, toY) { +WebGLGraphics.quadraticBezierCurve = function (fromX, fromY, cpX, cpY, toX, toY) +{ var xa, ya, @@ -373,14 +411,16 @@ n = 20, points = []; - function getPt(n1 , n2, perc) { + function getPt(n1 , n2, perc) + { var diff = n2 - n1; return n1 + ( diff * perc ); } var j = 0; - for (var i = 0; i <= n; i++ ) { + for (var i = 0; i <= n; i++ ) + { j = i / n; // The Green Line @@ -406,7 +446,8 @@ * @param graphicsData {Graphics} The graphics object to draw * @param webGLData {object} */ -WebGLGraphics.buildCircle = function (graphicsData, webGLData) { +WebGLGraphics.buildCircle = function (graphicsData, webGLData) +{ // need to convert points to a nice regular data var circleData = graphicsData.shape; var x = circleData.x; @@ -415,11 +456,13 @@ var height; // TODO - bit hacky?? - if (graphicsData.type === CONST.SHAPES.CIRC) { + if (graphicsData.type === CONST.SHAPES.CIRC) + { width = circleData.radius; height = circleData.radius; } - else { + else + { width = circleData.width; height = circleData.height; } @@ -429,7 +472,8 @@ var i = 0; - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -444,7 +488,8 @@ indices.push(vecPos); - for (i = 0; i < totalSegs + 1 ; i++) { + for (i = 0; i < totalSegs + 1 ; i++) + { verts.push(x,y, r, g, b, alpha); verts.push(x + Math.sin(seg * i) * width, @@ -457,12 +502,14 @@ indices.push(vecPos-1); } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = []; - for (i = 0; i < totalSegs + 1; i++) { + for (i = 0; i < totalSegs + 1; i++) + { graphicsData.points.push(x + Math.sin(seg * i) * width, y + Math.cos(seg * i) * height); } @@ -481,18 +528,22 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildLine = function (graphicsData, webGLData) { +WebGLGraphics.buildLine = function (graphicsData, webGLData) +{ // TODO OPTIMISE! var i = 0; var points = graphicsData.points; - if (points.length === 0) { + if (points.length === 0) + { return; } // if the line width is an odd number add 0.5 to align to a whole pixel - if (graphicsData.lineWidth%2) { - for (i = 0; i < points.length; i++) { + if (graphicsData.lineWidth%2) + { + for (i = 0; i < points.length; i++) + { points[i] += 0.5; } } @@ -502,7 +553,8 @@ var lastPoint = new math.Point(points[points.length - 2], points[points.length - 1]); // if the first point is the last point - gonna have issues :) - if (firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) { + if (firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) + { // need to clone as we are going to slightly modify the shape.. points = points.slice(); @@ -562,7 +614,8 @@ verts.push(p1x + perpx , p1y + perpy, r, g, b, alpha); - for (i = 1; i < length-1; i++) { + for (i = 1; i < length-1; i++) + { p1x = points[(i-1)*2]; p1y = points[(i-1)*2 + 1]; @@ -599,7 +652,8 @@ denom = a1*b2 - a2*b1; - if (Math.abs(denom) < 0.1 ) { + if (Math.abs(denom) < 0.1 ) + { denom+=10.1; verts.push(p2x - perpx , p2y - perpy, @@ -618,7 +672,8 @@ pdist = (px -p2x) * (px -p2x) + (py -p2y) + (py -p2y); - if (pdist > 140 * 140) { + if (pdist > 140 * 140) + { perp3x = perpx - perp2x; perp3y = perpy - perp2y; @@ -639,7 +694,8 @@ indexCount++; } - else { + else + { verts.push(px , py); verts.push(r, g, b, alpha); @@ -672,7 +728,8 @@ indices.push(indexStart); - for (i = 0; i < indexCount; i++) { + for (i = 0; i < indexCount; i++) + { indices.push(indexStart++); } @@ -687,11 +744,13 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildComplexPoly = function (graphicsData, webGLData) { +WebGLGraphics.buildComplexPoly = function (graphicsData, webGLData) +{ //TODO - no need to copy this as it gets turned into a FLoat32Array anyways.. var points = graphicsData.points.slice(); - if (points.length < 6) { + if (points.length < 6) + { return; } @@ -711,7 +770,8 @@ var x,y; // get size.. - for (var i = 0; i < points.length; i+=2) { + for (var i = 0; i < points.length; i+=2) + { x = points[i]; y = points[i+1]; @@ -732,7 +792,8 @@ //TODO - this aint needed! var length = points.length / 2; - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { indices.push( i ); } @@ -746,10 +807,12 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildPoly = function (graphicsData, webGLData) { +WebGLGraphics.buildPoly = function (graphicsData, webGLData) +{ var points = graphicsData.points; - if (points.length < 6) { + if (points.length < 6) + { return; } // get first and last point.. figure out the middle! @@ -767,7 +830,8 @@ var triangles = utils.PolyK.Triangulate(points); - if (!triangles) { + if (!triangles) + { return false; } @@ -775,7 +839,8 @@ var i = 0; - for (i = 0; i < triangles.length; i+=3) { + for (i = 0; i < triangles.length; i+=3) + { indices.push(triangles[i] + vertPos); indices.push(triangles[i] + vertPos); indices.push(triangles[i+1] + vertPos); @@ -783,7 +848,8 @@ indices.push(triangles[i+2] + vertPos); } - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { verts.push(points[i * 2], points[i * 2 + 1], r, g, b, alpha); } diff --git a/src/core/renderers/webgl/utils/WebGLGraphicsData.js b/src/core/renderers/webgl/utils/WebGLGraphicsData.js index c56d05e..c739ba7 100644 --- a/src/core/renderers/webgl/utils/WebGLGraphicsData.js +++ b/src/core/renderers/webgl/utils/WebGLGraphicsData.js @@ -2,7 +2,8 @@ * @class * @private */ -function WebGLGraphicsData(gl) { +function WebGLGraphicsData(gl) +{ this.gl = gl; //TODO does this need to be split before uploding?? @@ -22,7 +23,8 @@ /** * */ -WebGLGraphicsData.prototype.reset = function () { +WebGLGraphicsData.prototype.reset = function () +{ this.points.length = 0; this.indices.length = 0; }; @@ -30,7 +32,8 @@ /** * */ -WebGLGraphicsData.prototype.upload = function () { +WebGLGraphicsData.prototype.upload = function () +{ var gl = this.gl; // this.lastIndex = graphics.graphicsData.length; diff --git a/src/core/renderers/webgl/utils/WebGLSpriteBatch.js b/src/core/renderers/webgl/utils/WebGLSpriteBatch.js index 96eaa52..55befbb 100644 --- a/src/core/renderers/webgl/utils/WebGLSpriteBatch.js +++ b/src/core/renderers/webgl/utils/WebGLSpriteBatch.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this sprite batch works for. */ -function WebGLSpriteBatch(renderer) { +function WebGLSpriteBatch(renderer) +{ /** * * @@ -88,7 +89,8 @@ */ this.lastIndexCount = 0; - for (var i=0, j=0; i < numIndices; i += 6, j += 4) { + 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; @@ -162,7 +164,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.setupContext(); }); } @@ -173,7 +176,8 @@ /** * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLSpriteBatch.prototype.setupContext = function () { +WebGLSpriteBatch.prototype.setupContext = function () +{ var gl = this.renderer.gl; // setup default shader @@ -198,7 +202,8 @@ /** * */ -WebGLSpriteBatch.prototype.begin = function () { +WebGLSpriteBatch.prototype.begin = function () +{ // this.shader = this.renderer.shaderManager.defaultShader; this.start(); @@ -206,19 +211,22 @@ /** */ -WebGLSpriteBatch.prototype.end = function () { +WebGLSpriteBatch.prototype.end = function () +{ this.flush(); }; /** * @param sprite {Sprite} the sprite to render when using this spritebatch */ -WebGLSpriteBatch.prototype.render = function (sprite) { +WebGLSpriteBatch.prototype.render = function (sprite) +{ var texture = sprite.texture; //TODO set blend modes.. // check texture.. - if (this.currentBatchSize >= this.size) { + if (this.currentBatchSize >= this.size) + { this.flush(); this.currentBaseTexture = texture.baseTexture; } @@ -227,7 +235,8 @@ var uvs = texture._uvs; // if the uvs have not updated then no point rendering just yet! - if (!uvs) { + if (!uvs) + { return; } @@ -237,7 +246,8 @@ var w0, w1, h0, h1; - if (texture.trim) { + 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; @@ -248,7 +258,8 @@ h0 = h1 + texture.crop.height; } - else { + else + { w0 = (texture.frame.width ) * (1-aX); w1 = (texture.frame.width ) * -aX; @@ -272,7 +283,8 @@ var colors = this.colors; var positions = this.positions; - if (this.renderer.roundPixels) { + if (this.renderer.roundPixels) + { // xy positions[index] = a * w1 + c * h1 + tx | 0; positions[index+1] = d * h1 + b * w1 + ty | 0; @@ -289,7 +301,8 @@ positions[index+15] = a * w1 + c * h0 + tx | 0; positions[index+16] = d * h0 + b * w1 + ty | 0; } - else { + else + { // xy positions[index] = a * w1 + c * h1 + tx; positions[index+1] = d * h1 + b * w1 + ty; @@ -338,11 +351,13 @@ * * @param sprite {TilingSprite} the tilingSprite to render */ -WebGLSpriteBatch.prototype.renderTilingSprite = function (tilingSprite) { +WebGLSpriteBatch.prototype.renderTilingSprite = function (tilingSprite) +{ var texture = tilingSprite.tilingTexture; // check texture.. - if (this.currentBatchSize >= this.size) { + if (this.currentBatchSize >= this.size) + { //return; this.flush(); this.currentBaseTexture = texture.baseTexture; @@ -351,7 +366,8 @@ // set the textures uvs temporarily // TODO create a separate texture so that we can tile part of a texture - if (!tilingSprite._uvs) { + if (!tilingSprite._uvs) + { tilingSprite._uvs = new TextureUvs(); } @@ -454,16 +470,19 @@ * Renders the content and empties the current batch. * */ -WebGLSpriteBatch.prototype.flush = function () { +WebGLSpriteBatch.prototype.flush = function () +{ // If the batch is length 0 then return as there is nothing to draw - if (this.currentBatchSize === 0) { + if (this.currentBatchSize === 0) + { return; } var gl = this.renderer.gl; var shader; - if (this.dirty) { + if (this.dirty) + { this.dirty = false; // bind the main texture gl.activeTexture(gl.TEXTURE0); @@ -482,10 +501,12 @@ } // upload the verts to the buffer - if (this.currentBatchSize > ( this.size * 0.5 ) ) { + if (this.currentBatchSize > ( this.size * 0.5 ) ) + { gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); } - else { + else + { var view = this.positions.subarray(0, this.currentBatchSize * this.vertByteSize); gl.bufferSubData(gl.ARRAY_BUFFER, 0, view); } @@ -502,7 +523,8 @@ var shaderSwap = false; var sprite; - for (var i = 0, j = this.currentBatchSize; i < j; i++) { + for (var i = 0, j = this.currentBatchSize; i < j; i++) + { sprite = this.sprites[i]; @@ -513,24 +535,28 @@ blendSwap = currentBlendMode !== nextBlendMode; shaderSwap = currentShader !== nextShader; // should I use uuidS??? - if (currentBaseTexture !== nextTexture || blendSwap || shaderSwap) { + if (currentBaseTexture !== nextTexture || blendSwap || shaderSwap) + { this.renderBatch(currentBaseTexture, batchSize, start); start = i; batchSize = 0; currentBaseTexture = nextTexture; - if (blendSwap) { + if (blendSwap) + { currentBlendMode = nextBlendMode; this.renderer.blendModeManager.setBlendMode( currentBlendMode ); } - if (shaderSwap) { + if (shaderSwap) + { currentShader = nextShader; shader = currentShader.shaders ? currentShader.shaders[gl.id] : currentShader; - if (!shader) { + if (!shader) + { shader = new Shader(gl, null, currentShader.fragmentSrc, currentShader.uniforms); currentShader.shaders[gl.id] = shader; } @@ -538,7 +564,8 @@ // set shader function??? this.renderer.shaderManager.setShader(shader); - if (shader.dirty) { + if (shader.dirty) + { shader.syncUniforms(); } @@ -569,17 +596,21 @@ * @param size {number} * @param startIndex {number} */ -WebGLSpriteBatch.prototype.renderBatch = function (texture, size, startIndex) { - if (size === 0) { +WebGLSpriteBatch.prototype.renderBatch = function (texture, size, startIndex) +{ + if (size === 0) + { return; } var gl = this.renderer.gl; - if (!texture._glTextures[gl.id]) { + if (!texture._glTextures[gl.id]) + { this.renderer.updateTexture(texture); } - else { + else + { // bind the current texture gl.bindTexture(gl.TEXTURE_2D, texture._glTextures[gl.id]); } @@ -594,7 +625,8 @@ /** * */ -WebGLSpriteBatch.prototype.stop = function () { +WebGLSpriteBatch.prototype.stop = function () +{ this.flush(); this.dirty = true; }; @@ -602,7 +634,8 @@ /** * */ -WebGLSpriteBatch.prototype.start = function () { +WebGLSpriteBatch.prototype.start = function () +{ this.dirty = true; }; @@ -610,7 +643,8 @@ * Destroys the SpriteBatch. * */ -WebGLSpriteBatch.prototype.destroy = function () { +WebGLSpriteBatch.prototype.destroy = function () +{ this.renderer.gl.deleteBuffer(this.vertexBuffer); this.renderer.gl.deleteBuffer(this.indexBuffer); diff --git a/src/core/textures/BaseTexture.js b/src/core/textures/BaseTexture.js index 2bf77d4..513d358 100644 --- a/src/core/textures/BaseTexture.js +++ b/src/core/textures/BaseTexture.js @@ -10,7 +10,8 @@ * @param source {Image|Canvas} the source object of the texture. * @param [scaleMode=scaleModes.DEFAULT] {number} See {@link scaleModes} for possible values */ -function BaseTexture(source, scaleMode) { +function BaseTexture(source, scaleMode) +{ this.uuid = utils.uuid(); /** @@ -123,7 +124,8 @@ this._needsUpdate = false; // if no source passed don't try to load - if (source) { + if (source) + { this.loadSource(source); } @@ -149,13 +151,16 @@ Object.defineProperties(BaseTexture.prototype, { needsUpdate: { - get: function () { + get: function () + { return this._needsUpdate; }, - set: function (val) { + set: function (val) + { this._needsUpdate = val; - if (val) { + if (val) + { this.emit('update', this); } } @@ -171,9 +176,11 @@ * * The logic state after calling `loadSource` directly or indirectly (eg. `fromImage`, `new BaseTexture`) is: * - * if (texture.hasLoaded) { + * if (texture.hasLoaded) + { * // texture ready for use - * } else if (texture.isLoading) { + * } else if (texture.isLoading) + { * // listen to 'loaded' and/or 'error' events on texture * } else { * // not loading, not going to load UNLESS the source is reloaded @@ -183,12 +190,14 @@ * @protected * @param source {Image|Canvas} the source object of the texture. */ -BaseTexture.prototype.loadSource = function (source) { +BaseTexture.prototype.loadSource = function (source) +{ var wasLoading = this.isLoading; this.hasLoaded = false; this.isLoading = false; - if (wasLoading && this.source) { + if (wasLoading && this.source) + { this.source.onload = null; this.source.onerror = null; } @@ -196,20 +205,24 @@ this.source = source; // Apply source if loaded. Otherwise setup appropriate loading monitors. - if ((this.source.complete || this.source.getContext) && this.source.width && this.source.height) { + if ((this.source.complete || this.source.getContext) && this.source.width && this.source.height) + { this._sourceLoaded(); } - else if(!source.getContext) { + else if(!source.getContext) + { // Image fail / not ready this.isLoading = true; var scope = this; - source.onload = function () { + source.onload = function () + { source.onload = null; source.onerror = null; - if(!scope.isLoading) { + if(!scope.isLoading) + { return; } @@ -219,11 +232,13 @@ scope.emit('loaded', scope); }; - source.onerror = function () { + source.onerror = function () + { source.onload = null; source.onerror = null; - if(!scope.isLoading) { + if(!scope.isLoading) + { return; } @@ -234,24 +249,29 @@ // Per http://www.w3.org/TR/html5/embedded-content-0.html#the-img-element // "The value of `complete` can thus change while a script is executing." // So complete needs to be re-checked after the callbacks have been added.. - if (source.complete) { + if (source.complete) + { this.isLoading = false; // ..and if we're complete now, no need for callbacks source.onload = null; source.onerror = null; - if (source.width && source.height) { + if (source.width && source.height) + { this._sourceLoaded(); // If any previous subscribers possible - if (wasLoading) { + if (wasLoading) + { this.emit('loaded', this); } } - else { + else + { // If any previous subscribers possible - if (wasLoading) { + if (wasLoading) + { this.emit('error', this); } } @@ -265,7 +285,8 @@ * * @private */ -BaseTexture.prototype._sourceLoaded = function () { +BaseTexture.prototype._sourceLoaded = function () +{ this.hasLoaded = true; this.width = this.source.naturalWidth || this.source.width; @@ -278,16 +299,20 @@ * Destroys this base texture * */ -BaseTexture.prototype.destroy = function () { - if (this.imageUrl) { +BaseTexture.prototype.destroy = function () +{ + if (this.imageUrl) + { delete utils.BaseTextureCache[this.imageUrl]; delete utils.TextureCache[this.imageUrl]; this.imageUrl = null; - if (!navigator.isCocoonJS) { + if (!navigator.isCocoonJS) + { this.source.src = ''; } } - else if (this.source && this.source._pixiId) { + else if (this.source && this.source._pixiId) + { delete utils.BaseTextureCache[this.source._pixiId]; } this.source = null; @@ -301,7 +326,8 @@ * memory again. * */ -BaseTexture.prototype.dispose = function () { +BaseTexture.prototype.dispose = function () +{ this.emit('dispose', this); }; @@ -311,7 +337,8 @@ * * @param newSrc {string} the path of the image */ -BaseTexture.prototype.updateSourceImage = function (newSrc) { +BaseTexture.prototype.updateSourceImage = function (newSrc) +{ this.source.src = newSrc; this.loadSource(this.source); }; @@ -326,18 +353,22 @@ * @param [scaleMode=scaleModes.DEFAULT] {number} See {@link scaleModes} for possible values * @return BaseTexture */ -BaseTexture.fromImage = function (imageUrl, crossorigin, scaleMode) { +BaseTexture.fromImage = function (imageUrl, crossorigin, scaleMode) +{ var baseTexture = utils.BaseTextureCache[imageUrl]; - if (crossorigin === undefined && imageUrl.indexOf('data:') !== 0) { + if (crossorigin === undefined && imageUrl.indexOf('data:') !== 0) + { crossorigin = true; } - if (!baseTexture) { + if (!baseTexture) + { // new Image() breaks tex loading in some versions of Chrome. // See https://code.google.com/p/chromium/issues/detail?id=238071 var image = new Image();//document.createElement('img'); - if (crossorigin) { + if (crossorigin) + { image.crossOrigin = ''; } @@ -347,7 +378,8 @@ utils.BaseTextureCache[imageUrl] = baseTexture; // if there is an @2x at the end of the url we are going to assume its a highres image - if ( imageUrl.indexOf(CONST.RETINA_PREFIX + '.') !== -1) { + if ( imageUrl.indexOf(CONST.RETINA_PREFIX + '.') !== -1) + { baseTexture.resolution = 2; } } @@ -363,14 +395,17 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return BaseTexture */ -BaseTexture.fromCanvas = function (canvas, scaleMode) { - if (!canvas._pixiId) { +BaseTexture.fromCanvas = function (canvas, scaleMode) +{ + if (!canvas._pixiId) + { canvas._pixiId = 'canvas_' + utils.uuid(); } var baseTexture = utils.BaseTextureCache[canvas._pixiId]; - if (!baseTexture) { + if (!baseTexture) + { baseTexture = new BaseTexture(canvas, scaleMode); utils.BaseTextureCache[canvas._pixiId] = baseTexture; } diff --git a/src/core/textures/RenderTexture.js b/src/core/textures/RenderTexture.js index 6dad20f..53ae796 100644 --- a/src/core/textures/RenderTexture.js +++ b/src/core/textures/RenderTexture.js @@ -46,8 +46,10 @@ * @param [scaleMode] {number} See {@link scaleModes} for possible values * @param [resolution=1] {number} The resolution of the texture being generated */ -function RenderTexture(renderer, width, height, scaleMode, resolution) { - if (!renderer) { +function RenderTexture(renderer, width, height, scaleMode, resolution) +{ + if (!renderer) + { throw new Error('Unable to create RenderTexture, you must pass a renderer into the constructor.'); } @@ -133,7 +135,8 @@ */ this.renderer = renderer; - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { var gl = this.renderer.gl; this.textureBuffer = new FilterTexture(gl, this.width * this.resolution, this.height * this.resolution, this.baseTexture.scaleMode); @@ -142,7 +145,8 @@ this.render = this.renderWebGL; this.projection = new math.Point(this.width*0.5, -this.height*0.5); } - else { + else + { this.render = this.renderCanvas; this.textureBuffer = new CanvasBuffer(this.width* this.resolution, this.height* this.resolution); this.baseTexture.source = this.textureBuffer.canvas; @@ -167,8 +171,10 @@ * @param height {number} The height to resize to. * @param updateBase {boolean} Should the baseTexture.width and height values be resized as well? */ -RenderTexture.prototype.resize = function (width, height, updateBase) { - if (width === this.width && height === this.height) { +RenderTexture.prototype.resize = function (width, height, updateBase) +{ + if (width === this.width && height === this.height) + { return; } @@ -177,17 +183,20 @@ this.width = this.frame.width = this.crop.width = width; this.height = this.frame.height = this.crop.height = height; - if (updateBase) { + if (updateBase) + { this.baseTexture.width = this.width; this.baseTexture.height = this.height; } - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { this.projection.x = this.width / 2; this.projection.y = -this.height / 2; } - if (!this.valid) { + if (!this.valid) + { return; } @@ -198,12 +207,15 @@ * Clears the RenderTexture. * */ -RenderTexture.prototype.clear = function () { - if (!this.valid) { +RenderTexture.prototype.clear = function () +{ + if (!this.valid) + { return; } - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { this.renderer.gl.bindFramebuffer(this.renderer.gl.FRAMEBUFFER, this.textureBuffer.frameBuffer); } @@ -220,19 +232,23 @@ * @param [restoreWorldTransform=true] {boolean} If true the displayObject's worldTransform/worldAlpha and all children * transformations will be restored. Not restoring this information will be a little faster. */ -RenderTexture.prototype.renderWebGL = function (displayObject, matrix, clear, restoreWorldTransform) { - if (!this.valid) { +RenderTexture.prototype.renderWebGL = function (displayObject, matrix, clear, restoreWorldTransform) +{ + if (!this.valid) + { return; } - if (typeof restoreWorldTransform === 'undefined') { + if (typeof restoreWorldTransform === 'undefined') + { restoreWorldTransform = true; } var tempAlpha, tempTransform; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { tempAlpha = displayObject.worldAlpha; tempTransform = displayObject.worldTransform.toArray(); } @@ -245,7 +261,8 @@ wt.identity(); wt.translate(0, this.projection.y * 2); - if (matrix) { + if (matrix) + { wt.append(matrix); } @@ -258,7 +275,8 @@ var children = displayObject.children; var i, j; - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } @@ -269,7 +287,8 @@ gl.bindFramebuffer(gl.FRAMEBUFFER, this.textureBuffer.frameBuffer ); - if (clear) { + if (clear) + { this.textureBuffer.clear(); } @@ -279,11 +298,13 @@ this.renderer.spriteBatch.dirty = true; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { displayObject.worldAlpha = tempAlpha; displayObject.worldTransform.fromArray(tempTransform); - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } } @@ -300,26 +321,31 @@ * @param [restoreWorldTransform=true] {boolean} If true the displayObject's worldTransform/worldAlpha and all children * transformations will be restored. Not restoring this information will be a little faster. */ -RenderTexture.prototype.renderCanvas = function (displayObject, matrix, clear, restoreWorldTransform) { - if (!this.valid) { +RenderTexture.prototype.renderCanvas = function (displayObject, matrix, clear, restoreWorldTransform) +{ + if (!this.valid) + { return; } - if (typeof restoreWorldTransform === 'undefined') { + if (typeof restoreWorldTransform === 'undefined') + { restoreWorldTransform = true; } var tempAlpha, tempTransform; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { tempAlpha = displayObject.worldAlpha; tempTransform = displayObject.worldTransform.toArray(); } var wt = displayObject.worldTransform; wt.identity(); - if (matrix) { + if (matrix) + { wt.append(matrix); } @@ -330,11 +356,13 @@ var children = displayObject.children; var i, j; - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } - if (clear) { + if (clear) + { this.textureBuffer.clear(); } @@ -348,11 +376,13 @@ this.renderer.resolution = realResolution; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { displayObject.worldAlpha = tempAlpha; displayObject.worldTransform.fromArray(tempTransform); - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } } @@ -363,7 +393,8 @@ * * @return {Image} */ -RenderTexture.prototype.getImage = function () { +RenderTexture.prototype.getImage = function () +{ var image = new Image(); image.src = this.getBase64(); return image; @@ -374,7 +405,8 @@ * * @return {string} A base64 encoded string of the texture. */ -RenderTexture.prototype.getBase64 = function () { +RenderTexture.prototype.getBase64 = function () +{ return this.getCanvas().toDataURL(); }; @@ -383,8 +415,10 @@ * * @return {HTMLCanvasElement} A Canvas element with the texture rendered on. */ -RenderTexture.prototype.getCanvas = function () { - if (this.renderer.type === CONST.WEBGL_RENDERER) { +RenderTexture.prototype.getCanvas = function () +{ + if (this.renderer.type === CONST.WEBGL_RENDERER) + { var gl = this.renderer.gl; var width = this.textureBuffer.width; var height = this.textureBuffer.height; @@ -403,7 +437,8 @@ return tempCanvas.canvas; } - else { + else + { return this.textureBuffer.canvas; } }; diff --git a/src/core/textures/Texture.js b/src/core/textures/Texture.js index 3c65909..e97f0aa 100644 --- a/src/core/textures/Texture.js +++ b/src/core/textures/Texture.js @@ -17,7 +17,8 @@ * @param [crop] {Rectangle} The area of original texture * @param [trim] {Rectangle} Trimmed texture rectangle */ -function Texture(baseTexture, frame, crop, trim) { +function Texture(baseTexture, frame, crop, trim) +{ /** * Does this Texture have any frame data assigned to it? * @@ -25,12 +26,14 @@ */ this.noFrame = false; - if (!frame) { + if (!frame) + { this.noFrame = true; frame = new math.Rectangle(0, 0, 1, 1); } - if (baseTexture instanceof Texture) { + if (baseTexture instanceof Texture) + { baseTexture = baseTexture.baseTexture; } @@ -100,13 +103,16 @@ */ this.crop = crop || new math.Rectangle(0, 0, 1, 1); - if (baseTexture.hasLoaded) { - if (this.noFrame) { + if (baseTexture.hasLoaded) + { + if (this.noFrame) + { frame = new math.Rectangle(0, 0, baseTexture.width, baseTexture.height); } this.frame = frame; } - else { + else + { baseTexture.addEventListener('loaded', this.onBaseTextureLoaded.bind(this)); } } @@ -118,19 +124,23 @@ Object.defineProperties(Texture.prototype, { needsUpdate: { - get: function () { + get: function () + { return this.baseTexture.needsUpdate; }, - set: function (val) { + set: function (val) + { this.baseTexture.needsUpdate = val; } }, frame: { - get: function () { + get: function () + { return this._frame; }, - set: function (frame) { + set: function (frame) + { this._frame = frame; this.noFrame = false; @@ -143,20 +153,23 @@ 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 (!this.trim && (frame.x + frame.width > this.baseTexture.width || frame.y + frame.height > this.baseTexture.height)) + { throw new Error('Texture Error: frame does not fit inside the base Texture dimensions ' + this); } this.valid = frame && frame.width && frame.height && this.baseTexture.source && this.baseTexture.hasLoaded; - if (this.trim) { + 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) { + if (this.valid) + { this._updateUvs(); } } @@ -168,11 +181,13 @@ * * @private */ -Texture.prototype.onBaseTextureLoaded = function () { +Texture.prototype.onBaseTextureLoaded = function () +{ var baseTexture = this.baseTexture; baseTexture.removeEventListener('loaded', this.onLoaded); - if (this.noFrame) { + if (this.noFrame) + { this.frame = new math.Rectangle(0, 0, baseTexture.width, baseTexture.height); } @@ -184,8 +199,10 @@ * * @param destroyBase {boolean} Whether to destroy the base texture as well */ -Texture.prototype.destroy = function (destroyBase) { - if (destroyBase) { +Texture.prototype.destroy = function (destroyBase) +{ + if (destroyBase) + { this.baseTexture.destroy(); } @@ -197,8 +214,10 @@ * * @private */ -Texture.prototype._updateUvs = function () { - if (!this._uvs) { +Texture.prototype._updateUvs = function () +{ + if (!this._uvs) + { this._uvs = new TextureUvs(); } @@ -229,10 +248,12 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return Texture */ -Texture.fromImage = function (imageUrl, crossorigin, scaleMode) { +Texture.fromImage = function (imageUrl, crossorigin, scaleMode) +{ var texture = utils.TextureCache[imageUrl]; - if (!texture) { + if (!texture) + { texture = new Texture(BaseTexture.fromImage(imageUrl, crossorigin, scaleMode)); utils.TextureCache[imageUrl] = texture; } @@ -248,9 +269,11 @@ * @param frameId {string} The frame id of the texture * @return Texture */ -Texture.fromFrame = function (frameId) { +Texture.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache '); } return texture; @@ -264,7 +287,8 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return {Texture} */ -Texture.fromCanvas = function (canvas, scaleMode) { +Texture.fromCanvas = function (canvas, scaleMode) +{ return new Texture(BaseTexture.fromCanvas(canvas, scaleMode)); }; @@ -276,7 +300,8 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return {Texture} A Texture */ -Texture.fromVideo = function (video, scaleMode) { +Texture.fromVideo = function (video, scaleMode) +{ return new Texture(VideoBaseTexture.baseTextureFromVideo(video, scaleMode)); }; @@ -287,7 +312,8 @@ * @param texture {Texture} The Texture to add to the cache. * @param id {string} The id that the texture will be stored against. */ -Texture.addTextureToCache = function (texture, id) { +Texture.addTextureToCache = function (texture, id) +{ utils.TextureCache[id] = texture; }; @@ -298,7 +324,8 @@ * @param id {string} The id of the texture to be removed * @return {Texture} The texture that was removed */ -Texture.removeTextureFromCache = function (id) { +Texture.removeTextureFromCache = function (id) +{ var texture = utils.TextureCache[id]; delete utils.TextureCache[id]; diff --git a/src/core/textures/TextureUvs.js b/src/core/textures/TextureUvs.js index b9bbb58..5424d52 100644 --- a/src/core/textures/TextureUvs.js +++ b/src/core/textures/TextureUvs.js @@ -1,4 +1,5 @@ -function TextureUvs() { +function TextureUvs() +{ this.x0 = 0; this.y0 = 0; diff --git a/src/core/textures/VideoBaseTexture.js b/src/core/textures/VideoBaseTexture.js index e3e0c5a..1a826a9 100644 --- a/src/core/textures/VideoBaseTexture.js +++ b/src/core/textures/VideoBaseTexture.js @@ -12,15 +12,18 @@ * @param source {HTMLVideoElement} * @param [scaleMode] {number} See {@link scaleModes} for possible values */ -function VideoBaseTexture(source, scaleMode) { - if (!source){ +function VideoBaseTexture(source, scaleMode) +{ + if (!source) + { throw new Error('No video source element specified.'); } // hook in here to check if video is already available. // BaseTexture looks for a source.complete boolean, plus width & height. - if ((source.readyState === source.HAVE_ENOUGH_DATA || source.readyState === source.HAVE_FUTURE_DATA) && source.width && source.height) { + if ((source.readyState === source.HAVE_ENOUGH_DATA || source.readyState === source.HAVE_FUTURE_DATA) && source.width && source.height) + { source.complete = true; } @@ -31,7 +34,8 @@ this._boundOnUpdate = this._onUpdate.bind(this); this._boundOnCanPlay = this._onCanPlay.bind(this); - if (!source.complete) { + if (!source.complete) + { source.addEventListener('canplay', this._boundOnCanPlay); source.addEventListener('canplaythrough', this._boundOnCanPlay); @@ -47,28 +51,35 @@ VideoBaseTexture.prototype.constructor = VideoBaseTexture; module.exports = VideoBaseTexture; -VideoBaseTexture.prototype._onUpdate = function () { - if (this.autoUpdate) { +VideoBaseTexture.prototype._onUpdate = function () +{ + if (this.autoUpdate) + { window.requestAnimationFrame(this._boundOnUpdate); this.needsUpdate = true; } }; -VideoBaseTexture.prototype._onPlayStart = function () { - if (!this.autoUpdate) { +VideoBaseTexture.prototype._onPlayStart = function () +{ + if (!this.autoUpdate) + { window.requestAnimationFrame(this._boundOnUpdate); this.autoUpdate = true; } }; -VideoBaseTexture.prototype._onPlayStop = function () { +VideoBaseTexture.prototype._onPlayStop = function () +{ this.autoUpdate = false; }; -VideoBaseTexture.prototype._onCanPlay = function () { +VideoBaseTexture.prototype._onCanPlay = function () +{ this.hasLoaded = true; - if (this.source) { + if (this.source) + { this.source.removeEventListener('canplay', this._boundOnCanPlay); this.source.removeEventListener('canplaythrough', this._boundOnCanPlay); @@ -78,15 +89,18 @@ this.source.play(); // prevent multiple loaded dispatches.. - if(!this.__loaded){ + if(!this.__loaded) + { this.__loaded = true; this.emit('loaded', this); } } }; -VideoBaseTexture.prototype.destroy = function () { - if (this.source && this.source._pixiId) { +VideoBaseTexture.prototype.destroy = function () +{ + if (this.source && this.source._pixiId) + { utils.BaseTextureCache[ this.source._pixiId ] = null; delete utils.BaseTextureCache[ this.source._pixiId ]; @@ -105,14 +119,17 @@ * @param scaleMode {number} See {@link scaleModes} for possible values * @return {VideoBaseTexture} */ -VideoBaseTexture.fromVideo = function (video, scaleMode) { - if (!video._pixiId) { +VideoBaseTexture.fromVideo = function (video, scaleMode) +{ + if (!video._pixiId) + { video._pixiId = 'video_' + utils.uuid(); } var baseTexture = utils.BaseTextureCache[video._pixiId]; - if (!baseTexture) { + if (!baseTexture) + { baseTexture = new VideoBaseTexture(video, scaleMode); utils.BaseTextureCache[ video._pixiId ] = baseTexture; } @@ -147,17 +164,21 @@ * @param scaleMode {number} See {@link scaleModes} for possible values * @return {VideoBaseTexture} */ -VideoBaseTexture.fromUrl = function (videoSrc, scaleMode) { +VideoBaseTexture.fromUrl = function (videoSrc, scaleMode) +{ var video = document.createElement('video'); // array of objects or strings - if (Array.isArray(videoSrc)) { - for (var i = 0; i < videoSrc.length; ++i) { + if (Array.isArray(videoSrc)) + { + for (var i = 0; i < videoSrc.length; ++i) + { video.appendChild(createSource(videoSrc.src || videoSrc, videoSrc.mime)); } } // single object or string - else { + else + { video.appendChild(createSource(videoSrc.src || videoSrc, videoSrc.mime)); } @@ -169,8 +190,10 @@ VideoBaseTexture.fromUrls = VideoBaseTexture.fromUrl; -function createSource(path, type) { - if (!type) { +function createSource(path, type) +{ + if (!type) + { type = 'video/' + path.substr(path.lastIndexOf('.') + 1); } diff --git a/src/core/utils/EventData.js b/src/core/utils/EventData.js index 5d55a22..8cdf701 100644 --- a/src/core/utils/EventData.js +++ b/src/core/utils/EventData.js @@ -7,7 +7,8 @@ * @param name {string} The string name of the event that was triggered * @param data {object} Arbitrary event data to pass along */ -function EventData(target, name, data) { +function EventData(target, name, data) +{ // for duck typing in the ".on()" function this.__isEventObject = true; @@ -71,7 +72,8 @@ * Stops the propagation of events up the scene graph (prevents bubbling). * */ -EventData.prototype.stopPropagation = function stopPropagation() { +EventData.prototype.stopPropagation = function stopPropagation() +{ this.stopped = true; }; @@ -79,6 +81,7 @@ * Stops the propagation of events to sibling listeners (no longer calls any listeners). * */ -EventData.prototype.stopImmediatePropagation = function stopImmediatePropagation() { +EventData.prototype.stopImmediatePropagation = function stopImmediatePropagation() +{ this.stoppedImmediate = true; }; diff --git a/src/core/utils/EventTarget.js b/src/core/utils/EventTarget.js index 7ae8820..671a151 100644 --- a/src/core/utils/EventTarget.js +++ b/src/core/utils/EventTarget.js @@ -13,14 +13,16 @@ * var em = new MyEmitter(); * em.emit('eventName', 'some data', 'some more data', {}, null, ...); */ -function eventTarget(obj) { +function eventTarget(obj) +{ /** * Return a list of assigned event listeners. * * @param eventName {string} The events that should be listed. * @return {Array} An array of listener functions */ - obj.listeners = function listeners(eventName) { + obj.listeners = function listeners(eventName) + { this._listeners = this._listeners || {}; return this._listeners[eventName] ? this._listeners[eventName].slice() : []; @@ -33,22 +35,26 @@ * @param eventName {string} The name of the event. * @return {boolean} Indication if we've emitted an event. */ - obj.emit = obj.dispatchEvent = function emit(eventName, data) { + obj.emit = obj.dispatchEvent = function emit(eventName, data) + { this._listeners = this._listeners || {}; // fast return when there are no listeners - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return; } //backwards compat with old method ".emit({ type: 'something' })" - if (typeof eventName === 'object') { + if (typeof eventName === 'object') + { data = eventName; eventName = eventName.type; } //ensure we are using a real pixi event - if (!data || data.__isEventObject !== true) { + if (!data || data.__isEventObject !== true) + { data = new EventData(this, eventName, data); } @@ -58,23 +64,27 @@ fn = listeners[0], i; - for (i = 0; i < length; fn = listeners[++i]) { + for (i = 0; i < length; fn = listeners[++i]) + { //call the event listener fn.call(this, data); //if "stopImmediatePropagation" is called, stop calling sibling events - if (data.stoppedImmediate) { + if (data.stoppedImmediate) + { return this; } } //if "stopPropagation" is called then don't bubble the event - if (data.stopped) { + if (data.stopped) + { return this; } //bubble this event up the scene graph - if (this.parent && this.parent.emit) { + if (this.parent && this.parent.emit) + { this.parent.emit.call(this.parent, eventName, data); } @@ -88,7 +98,8 @@ * @param eventName {string} Name of the event. * @param callback {Functon} fn Callback function. */ - obj.on = obj.addEventListener = function on(eventName, fn) { + obj.on = obj.addEventListener = function on(eventName, fn) + { this._listeners = this._listeners || {}; (this._listeners[eventName] = this._listeners[eventName] || []) @@ -103,11 +114,13 @@ * @param eventName {string} Name of the event. * @param callback {Function} Callback function. */ - obj.once = function once(eventName, fn) { + obj.once = function once(eventName, fn) + { this._listeners = this._listeners || {}; var self = this; - function onceHandlerWrapper() { + function onceHandlerWrapper() + { fn.apply(self.off(eventName, onceHandlerWrapper), arguments); } onceHandlerWrapper._originalHandler = fn; @@ -122,23 +135,28 @@ * @param eventName {string} The event we want to remove. * @param callback {Function} The listener that we need to find. */ - obj.off = obj.removeEventListener = function off(eventName, fn) { + obj.off = obj.removeEventListener = function off(eventName, fn) + { this._listeners = this._listeners || {}; - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return this; } var list = this._listeners[eventName], i = fn ? list.length : 0; - while(i-- > 0) { - if (list[i] === fn || list[i]._originalHandler === fn) { + while(i-- > 0) + { + if (list[i] === fn || list[i]._originalHandler === fn) + { list.splice(i, 1); } } - if (list.length === 0) { + if (list.length === 0) + { delete this._listeners[eventName]; } @@ -150,10 +168,12 @@ * * @param eventName {string} The event you want to remove all listeners for. */ - obj.removeAllListeners = function removeAllListeners(eventName) { + obj.removeAllListeners = function removeAllListeners(eventName) + { this._listeners = this._listeners || {}; - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return this; } @@ -169,7 +189,8 @@ * * @param object {object} The obj to mix into */ - mixin: function mixin(obj) { + mixin: function mixin(obj) + { eventTarget(obj); } }; diff --git a/src/core/utils/PolyK.js b/src/core/utils/PolyK.js index 7325141..5e20c2b 100644 --- a/src/core/utils/PolyK.js +++ b/src/core/utils/PolyK.js @@ -47,7 +47,8 @@ * Triangulates shapes for webGL graphic fills. * */ -PolyK.Triangulate = function (p) { +PolyK.Triangulate = function (p) +{ var sign = true; var n = p.length >> 1; @@ -59,7 +60,8 @@ i = 0; var al = n; - while(al > 3) { + while(al > 3) + { var i0 = avl[(i+0)%al]; var i1 = avl[(i+1)%al]; var i2 = avl[(i+2)%al]; @@ -69,29 +71,35 @@ var cx = p[2*i2], cy = p[2*i2+1]; var earFound = false; - if (PolyK._convex(ax, ay, bx, by, cx, cy, sign)) { + if (PolyK._convex(ax, ay, bx, by, cx, cy, sign)) + { earFound = true; - for (var j = 0; j < al; j++) { + for (var j = 0; j < al; j++) + { var vi = avl[j]; if (vi === i0 || vi === i1 || vi === i2) continue; - if (PolyK._PointInTriangle(p[2*vi], p[2*vi+1], ax, ay, bx, by, cx, cy)) { + if (PolyK._PointInTriangle(p[2*vi], p[2*vi+1], ax, ay, bx, by, cx, cy)) + { earFound = false; break; } } } - if (earFound) { + if (earFound) + { tgs.push(i0, i1, i2); avl.splice((i+1)%al, 1); al--; i = 0; } - else if (i++ > 3*al) { + else if (i++ > 3*al) + { // need to flip flip reverse it! // reset! - if (sign) { + if (sign) + { tgs = []; avl = []; for (i = 0; i < n; i++) avl.push(i); @@ -101,7 +109,8 @@ sign = false; } - else { + else + { // window.console.log("PIXI Warning: shape too complex to fill"); return null; } @@ -126,7 +135,8 @@ * @private * @return {boolean} */ -PolyK._PointInTriangle = function (px, py, ax, ay, bx, by, cx, cy) { +PolyK._PointInTriangle = function (px, py, ax, ay, bx, by, cx, cy) +{ var v0x = cx-ax; var v0y = cy-ay; var v1x = bx-ax; @@ -154,6 +164,7 @@ * @private * @return {boolean} */ -PolyK._convex = function (ax, ay, bx, by, cx, cy, sign) { +PolyK._convex = function (ax, ay, bx, by, cx, cy, sign) +{ return ((ay-by)*(cx-bx) + (bx-ax)*(cy-by) >= 0) === sign; }; diff --git a/src/core/utils/index.js b/src/core/utils/index.js index ade9831..bfae7ae 100644 --- a/src/core/utils/index.js +++ b/src/core/utils/index.js @@ -16,7 +16,8 @@ * * @return {number} The next uuid to use. */ - uuid: function () { + uuid: function () + { return ++utils._uid; }, @@ -26,7 +27,8 @@ * @param hex {number} * @return {number[]} An array representing the [R, G, B] of the color. */ - hex2rgb: function (hex, out) { + hex2rgb: function (hex, out) + { out = out || []; out[0] = (hex >> 16 & 0xFF) / 255; @@ -42,7 +44,8 @@ * @param hex {number} * @return {string} The string color. */ - hex2string: function (hex) { + hex2string: function (hex) + { hex = hex.toString(16); hex = '000000'.substr(0, 6 - hex.length) + hex; @@ -55,7 +58,8 @@ * @param rgb {number[]} * @return {number} The color number */ - rgb2hex: function (rgb) { + rgb2hex: function (rgb) + { return ((rgb[0]*255 << 16) + (rgb[1]*255 << 8) + rgb[2]*255); }, @@ -64,8 +68,10 @@ * * @return {boolean} whether they are supported */ - canUseNewCanvasBlendModes: function () { - if (typeof document === 'undefined') { + canUseNewCanvasBlendModes: function () + { + if (typeof document === 'undefined') + { return false; } @@ -93,15 +99,19 @@ * @param number {number} * @return {number} the closest number that is a power of two */ - getNextPowerOfTwo: function (number) { + getNextPowerOfTwo: function (number) + { // see: http://en.wikipedia.org/wiki/Power_of_two#Fast_algorithm_to_check_if_a_positive_number_is_a_power_of_two - if (number > 0 && (number & (number - 1)) === 0) { + if (number > 0 && (number & (number - 1)) === 0) + { return number; } - else { + else + { var result = 1; - while (result < number) { + while (result < number) + { result <<= 1; } @@ -116,7 +126,8 @@ * @param height {number} * @return {boolean} */ - isPowerOfTwo: function (width, height) { + isPowerOfTwo: function (width, height) + { return (width > 0 && (width & (width - 1)) === 0 && height > 0 && (height & (height - 1)) === 0); }, @@ -130,12 +141,15 @@ * @constant * @static */ - sayHello: function (type) { - if (utils._saidHello) { + sayHello: function (type) + { + if (utils._saidHello) + { return; } - if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) { + if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) + { var args = [ '%c %c %c Pixi.js ' + CONST.VERSION + ' - ' + type + ' %c ' + ' %c ' + ' http://www.pixijs.com/ %c %c ♥%c♥%c♥ ', 'background: #ff66a5', @@ -151,7 +165,8 @@ console.log.apply(console, args); //jshint ignore:line } - else if (window.console) { + else if (window.console) + { console.log('Pixi.js ' + CONST.VERSION + ' - ' + type + ' - http://www.pixijs.com/'); //jshint ignore:line } @@ -166,15 +181,19 @@ * @class * @namespace PIXI */ - AjaxRequest: function () { + AjaxRequest: function () + { var activexmodes = ['Msxml2.XMLHTTP.6.0', 'Msxml2.XMLHTTP.3.0', 'Microsoft.XMLHTTP']; //activeX versions to check for in IE - if (window.ActiveXObject) { //Test for support for ActiveXObject in IE first (as XMLHttpRequest in IE7 is broken) - for (var i=0; i= this.textures.length) { + else if (round >= this.textures.length) + { this.gotoAndStop(this.textures.length - 1); - if (this.onComplete) { + if (this.onComplete) + { this.onComplete(); } } @@ -167,10 +182,12 @@ * @static * @param frames {string[]} the array of frames ids the movieclip will use as its texture frames */ -MovieClip.fromFrames = function (frames) { +MovieClip.fromFrames = function (frames) +{ var textures = []; - for (var i = 0; i < frames.length; ++i) { + for (var i = 0; i < frames.length; ++i) + { textures.push(new core.Texture.fromFrame(frames[i])); } @@ -183,10 +200,12 @@ * @static * @param images {string[]} the array of image urls the movieclip will use as its texture frames */ -MovieClip.fromImages = function (images) { +MovieClip.fromImages = function (images) +{ var textures = []; - for (var i = 0; i < images.length; ++i) { + for (var i = 0; i < images.length; ++i) + { textures.push(new core.Texture.fromImage(images[i])); } diff --git a/src/extras/Rope.js b/src/extras/Rope.js index c157ec4..9c87bc0 100644 --- a/src/extras/Rope.js +++ b/src/extras/Rope.js @@ -9,7 +9,8 @@ * @param {Array} points - An array of {Point}. * */ -function Rope(texture, points) { +function Rope(texture, points) +{ Strip.call(this, texture); this.points = points; @@ -31,10 +32,12 @@ * Refreshes * */ -Rope.prototype.refresh = function () { +Rope.prototype.refresh = function () +{ var points = this.points; - if (points.length < 1) { + if (points.length < 1) + { return; } @@ -59,20 +62,23 @@ var total = points.length, point, index, amount; - for (var i = 1; i < total; i++) { + for (var i = 1; i < total; i++) + { point = points[i]; index = i * 4; // time to do some smart drawing! amount = i / (total-1); - if (i%2) { + if (i%2) + { uvs[index] = amount; uvs[index+1] = 0; uvs[index+2] = amount; uvs[index+3] = 1; } - else { + else + { uvs[index] = amount; uvs[index+1] = 0; @@ -95,10 +101,12 @@ * * @private */ -Rope.prototype.updateTransform = function () { +Rope.prototype.updateTransform = function () +{ var points = this.points; - if (points.length < 1) { + if (points.length < 1) + { return; } @@ -113,14 +121,17 @@ var total = points.length, point, index, ratio, perpLength, num; - for (var i = 0; i < total; i++) { + for (var i = 0; i < total; i++) + { point = points[i]; index = i * 4; - if (i < points.length-1) { + if (i < points.length-1) + { nextPoint = points[i+1]; } - else { + else + { nextPoint = point; } @@ -129,7 +140,8 @@ ratio = (1 - (i / (total-1))) * 10; - if (ratio > 1) { + if (ratio > 1) + { ratio = 1; } @@ -157,7 +169,8 @@ * * @param texture {Texture} the texture that will be used */ -Rope.prototype.setTexture = function (texture) { +Rope.prototype.setTexture = function (texture) +{ // stop current texture this.texture = texture; //this.updateFrame = true; diff --git a/src/extras/Strip.js b/src/extras/Strip.js index c5e378f..57691b5 100644 --- a/src/extras/Strip.js +++ b/src/extras/Strip.js @@ -10,7 +10,8 @@ * @param height {number} the height * */ -function Strip(texture) { +function Strip(texture) +{ core.DisplayObjectContainer.call(this); /** @@ -70,9 +71,11 @@ * * @param renderer {WebGLRenderer} */ -Strip.prototype.renderWebGL = function (renderer) { +Strip.prototype.renderWebGL = function (renderer) +{ // if the sprite is not visible or the alpha is 0 then no need to render this element - if (!this.visible || this.alpha <= 0) { + if (!this.visible || this.alpha <= 0) + { return; } @@ -81,7 +84,8 @@ renderer.spriteBatch.stop(); // init! init! - if (!this._vertexBuffer) { + if (!this._vertexBuffer) + { this._initWebGL(renderer); } @@ -96,7 +100,8 @@ //TODO check culling }; -Strip.prototype._initWebGL = function (renderer) { +Strip.prototype._initWebGL = function (renderer) +{ // build the strip! var gl = renderer.gl; @@ -118,7 +123,8 @@ gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this.indices, gl.STATIC_DRAW); }; -Strip.prototype._renderStrip = function (renderer) { +Strip.prototype._renderStrip = function (renderer) +{ var gl = renderer.gl; var projection = renderer.projection, offset = renderer.offset, @@ -137,7 +143,8 @@ gl.uniform2f(shader.offsetVector, -offset.x, -offset.y); gl.uniform1f(shader.alpha, this.worldAlpha); - if (!this.dirty) { + if (!this.dirty) + { gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexBuffer); gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); @@ -150,10 +157,12 @@ gl.activeTexture(gl.TEXTURE0); // check if a texture is dirty.. - if (this.texture.baseTexture._dirty[gl.id]) { + if (this.texture.baseTexture._dirty[gl.id]) + { renderer.updateTexture(this.texture.baseTexture); } - else { + else + { // bind the current texture gl.bindTexture(gl.TEXTURE_2D, this.texture.baseTexture._glTextures[gl.id]); } @@ -163,7 +172,8 @@ } - else { + else + { this.dirty = false; gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexBuffer); @@ -178,10 +188,12 @@ gl.activeTexture(gl.TEXTURE0); // check if a texture is dirty.. - if (this.texture.baseTexture._dirty[gl.id]) { + if (this.texture.baseTexture._dirty[gl.id]) + { renderer.updateTexture(this.texture.baseTexture); } - else { + else + { gl.bindTexture(gl.TEXTURE_2D, this.texture.baseTexture._glTextures[gl.id]); } @@ -203,27 +215,33 @@ * * @param renderer {CanvasRenderer} */ -Strip.prototype.renderCanvas = function (renderer) { +Strip.prototype.renderCanvas = function (renderer) +{ var context = renderer.context; var transform = this.worldTransform; - if (renderer.roundPixels) { + if (renderer.roundPixels) + { context.setTransform(transform.a, transform.b, transform.c, transform.d, transform.tx | 0, transform.ty | 0); } - else { + else + { context.setTransform(transform.a, transform.b, transform.c, transform.d, transform.tx, transform.ty); } - if (this.drawMode === Strip.DrawModes.TRIANGLE_STRIP) { + if (this.drawMode === Strip.DrawModes.TRIANGLE_STRIP) + { this._renderCanvasTriangleStrip(context); } - else { + else + { this._renderCanvasTriangles(context); } }; -Strip.prototype._renderCanvasTriangleStrip = function (context) { +Strip.prototype._renderCanvasTriangleStrip = function (context) +{ // draw triangles!! var vertices = this.vertices; var uvs = this.uvs; @@ -231,14 +249,16 @@ var length = vertices.length / 2; // this.count++; - for (var i = 0; i < length - 2; i++) { + for (var i = 0; i < length - 2; i++) + { // draw some triangles! var index = i * 2; this._renderCanvasDrawTriangle(context, vertices, uvs, index, (index + 2), (index + 4)); } }; -Strip.prototype._renderCanvasTriangles = function (context) { +Strip.prototype._renderCanvasTriangles = function (context) +{ // draw triangles!! var vertices = this.vertices; var uvs = this.uvs; @@ -247,14 +267,16 @@ var length = indices.length; // this.count++; - for (var i = 0; i < length; i += 3) { + for (var i = 0; i < length; i += 3) + { // draw some triangles! var index0 = indices[i] * 2, index1 = indices[i + 1] * 2, index2 = indices[i + 2] * 2; this._renderCanvasDrawTriangle(context, vertices, uvs, index0, index1, index2); } }; -Strip.prototype._renderCanvasDrawTriangle = function (context, vertices, uvs, index0, index1, index2) { +Strip.prototype._renderCanvasDrawTriangle = function (context, vertices, uvs, index0, index1, index2) +{ var textureSource = this.texture.baseTexture.source; var textureWidth = this.texture.width; var textureHeight = this.texture.height; @@ -265,7 +287,8 @@ var u0 = uvs[index0] * textureWidth, u1 = uvs[index1] * textureWidth, u2 = uvs[index2] * textureWidth; var v0 = uvs[index0 + 1] * textureHeight, v1 = uvs[index1 + 1] * textureHeight, v2 = uvs[index2 + 1] * textureHeight; - if (this.canvasPadding > 0) { + if (this.canvasPadding > 0) + { var paddingX = this.canvasPadding / this.worldTransform.a; var paddingY = this.canvasPadding / this.worldTransform.d; var centerX = (x0 + x1 + x2) / 3; @@ -332,7 +355,8 @@ * @param strip {Strip} The Strip to render * @private */ -Strip.prototype.renderStripFlat = function (strip) { +Strip.prototype.renderStripFlat = function (strip) +{ var context = this.context; var vertices = strip.vertices; @@ -340,7 +364,8 @@ // this.count++; context.beginPath(); - for (var i=1; i < length-2; i++) { + for (var i=1; i < length-2; i++) + { // draw some triangles! var index = i*2; @@ -358,7 +383,8 @@ }; /* -Strip.prototype.setTexture = function (texture) { +Strip.prototype.setTexture = function (texture) +{ //TODO SET THE TEXTURES //TODO VISIBILITY @@ -377,7 +403,8 @@ * @private */ -Strip.prototype.onTextureUpdate = function () { +Strip.prototype.onTextureUpdate = function () +{ this.updateFrame = true; }; @@ -387,7 +414,8 @@ * @param matrix {Matrix} the transformation matrix of the sprite * @return {Rectangle} the framing rectangle */ -Strip.prototype.getBounds = function (matrix) { +Strip.prototype.getBounds = function (matrix) +{ var worldTransform = matrix || this.worldTransform; var a = worldTransform.a; @@ -404,7 +432,8 @@ var minY = Infinity; var vertices = this.vertices; - for (var i = 0, n = vertices.length; i < n; i += 2) { + for (var i = 0, n = vertices.length; i < n; i += 2) + { var rawX = vertices[i], rawY = vertices[i + 1]; var x = (a * rawX) + (c * rawY) + tx; var y = (d * rawY) + (b * rawX) + ty; @@ -416,7 +445,8 @@ maxY = y > maxY ? y : maxY; } - if (minX === -Infinity || maxY === Infinity) { + if (minX === -Infinity || maxY === Infinity) + { return core.math.Rectangle.EMPTY; } diff --git a/src/core/display/DisplayObject.js b/src/core/display/DisplayObject.js index 66ebc3c..20e778c 100644 --- a/src/core/display/DisplayObject.js +++ b/src/core/display/DisplayObject.js @@ -7,7 +7,8 @@ * @class * @namespace PIXI */ -function DisplayObject() { +function DisplayObject() +{ /** * The coordinate of the object relative to the local coordinates of the parent. * @@ -152,10 +153,12 @@ * @memberof DisplayObject# */ x: { - get: function () { + get: function () + { return this.position.x; }, - set: function (value) { + set: function (value) + { this.position.x = value; } }, @@ -167,10 +170,12 @@ * @memberof DisplayObject# */ y: { - get: function () { + get: function () + { return this.position.y; }, - set: function (value) { + set: function (value) + { this.position.y = value; } }, @@ -183,11 +188,13 @@ * @readonly */ worldVisible: { - get: function () { + get: function () + { var item = this; do { - if (!item.visible) { + if (!item.visible) + { return false; } @@ -207,17 +214,21 @@ * @memberof DisplayObject# */ mask: { - get: function () { + get: function () + { return this._mask; }, - set: function (value) { - if (this._mask) { + set: function (value) + { + if (this._mask) + { this._mask.isMask = false; } this._mask = value; - if (this._mask) { + if (this._mask) + { this._mask.isMask = true; } } @@ -232,18 +243,23 @@ * @memberof DisplayObject# */ filters: { - get: function () { + get: function () + { return this._filters; }, - set: function (value) { - if (value) { + set: function (value) + { + if (value) + { // now put all the passes in one place.. var passes = []; - for (var i = 0; i < value.length; i++) { + for (var i = 0; i < value.length; i++) + { var filterPasses = value[i].passes; - for (var j = 0; j < filterPasses.length; j++) { + for (var j = 0; j < filterPasses.length; j++) + { passes.push(filterPasses[j]); } } @@ -264,8 +280,9 @@ * * @private */ -DisplayObject.prototype.updateTransform = function () { - +DisplayObject.prototype.updateTransform = function () +{ + // create some matrix refs for easy access var pt = this.parent.worldTransform; var wt = this.worldTransform; @@ -274,9 +291,11 @@ var a, b, c, d, tx, ty; // so if rotation is between 0 then we can simplify the multiplication process.. - if (this.rotation % math.PI_2) { + if (this.rotation % math.PI_2) + { // 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) { + if (this.rotation !== this.rotationCache) + { this.rotationCache = this.rotation; this._sr = Math.sin(this.rotation); this._cr = Math.cos(this.rotation); @@ -291,7 +310,8 @@ ty = this.position.y; // check for pivot.. not often used so geared towards that fact! - if (this.pivot.x || this.pivot.y) { + 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; } @@ -304,7 +324,8 @@ wt.tx = tx * pt.a + ty * pt.c + pt.tx; wt.ty = tx * pt.b + ty * pt.d + pt.ty; } - else { + else + { // lets do the fast version as we know there is no rotation.. a = this.scale.x; d = this.scale.y; @@ -333,7 +354,8 @@ * @param matrix {Matrix} * @return {Rectangle} the rectangular bounding area */ -DisplayObject.prototype.getBounds = function (/* matrix */) { +DisplayObject.prototype.getBounds = function (/* matrix */) +{ return math.Rectangle.EMPTY; }; @@ -342,7 +364,8 @@ * * @return {Rectangle} the rectangular bounding area */ -DisplayObject.prototype.getLocalBounds = function () { +DisplayObject.prototype.getLocalBounds = function () +{ return this.getBounds(math.Matrix.IDENTITY); }; @@ -352,7 +375,8 @@ * @param position {Point} The world origin to calculate from * @return {Point} A point object representing the position of this object */ -DisplayObject.prototype.toGlobal = function (position) { +DisplayObject.prototype.toGlobal = function (position) +{ // don't need to u[date the lot this.displayObjectUpdateTransform(); return this.worldTransform.apply(position); @@ -365,8 +389,10 @@ * @param [from] {DisplayObject} The DisplayObject to calculate the global position from * @return {Point} A point object representing the position of this object */ -DisplayObject.prototype.toLocal = function (position, from) { - if (from) { +DisplayObject.prototype.toLocal = function (position, from) +{ + if (from) + { position = from.toGlobal(position); } @@ -381,7 +407,8 @@ * @param renderer {WebGLRenderer} The renderer * @private */ -DisplayObject.prototype.renderWebGL = function (/* renderer */) { +DisplayObject.prototype.renderWebGL = function (/* renderer */) +{ // OVERWRITE; }; @@ -391,6 +418,7 @@ * @param renderer {CanvasRenderer} The renderer * @private */ -DisplayObject.prototype.renderCanvas = function (/* renderer */) { +DisplayObject.prototype.renderCanvas = function (/* renderer */) +{ // OVERWRITE; }; diff --git a/src/core/display/DisplayObjectContainer.js b/src/core/display/DisplayObjectContainer.js index 689f40b..4625ee8 100644 --- a/src/core/display/DisplayObjectContainer.js +++ b/src/core/display/DisplayObjectContainer.js @@ -12,7 +12,8 @@ * @extends DisplayObject * @namespace PIXI */ -function DisplayObjectContainer() { +function DisplayObjectContainer() +{ DisplayObject.call(this); /** @@ -47,17 +48,21 @@ * @memberof DisplayObjectContainer# */ width: { - get: function () { + get: function () + { return this.scale.x * this.getLocalBounds().width; }, - set: function (value) { + set: function (value) + { var width = this.getLocalBounds().width; - if(width !== 0) { + if(width !== 0) + { this.scale.x = value / width; } - else { + else + { this.scale.x = 1; } @@ -73,17 +78,21 @@ * @memberof DisplayObjectContainer# */ height: { - get: function () { + get: function () + { return this.scale.y * this.getLocalBounds().height; }, - set: function (value) { + set: function (value) + { var height = this.getLocalBounds().height; - if (height !== 0) { + if (height !== 0) + { this.scale.y = value / height ; } - else { + else + { this.scale.y = 1; } @@ -100,18 +109,23 @@ * @memberof DisplayObject# */ cacheAsBitmap: { - get: function () { + get: function () + { return this._cacheAsBitmap; }, - set: function (value) { - if (this._cacheAsBitmap === value) { + set: function (value) + { + if (this._cacheAsBitmap === value) + { return; } - if (value) { + if (value) + { this._generateCachedSprite(); } - else { + else + { this._destroyCachedSprite(); } @@ -126,7 +140,8 @@ * @param child {DisplayObject} The DisplayObject to add to the container * @return {DisplayObject} The child that was added. */ -DisplayObjectContainer.prototype.addChild = function (child) { +DisplayObjectContainer.prototype.addChild = function (child) +{ return this.addChildAt(child, this.children.length); }; @@ -137,14 +152,18 @@ * @param index {Number} The index to place the child in * @return {DisplayObject} The child that was added. */ -DisplayObjectContainer.prototype.addChildAt = function (child, index) { +DisplayObjectContainer.prototype.addChildAt = function (child, index) +{ // prevent adding self as child - if (child === this) { + if (child === this) + { return; } - if (index >= 0 && index <= this.children.length) { - if (child.parent) { + if (index >= 0 && index <= this.children.length) + { + if (child.parent) + { child.parent.removeChild(child); } @@ -154,7 +173,8 @@ return child; } - else { + else + { throw new Error(child + 'addChildAt: The index '+ index +' supplied is out of bounds ' + this.children.length); } }; @@ -165,15 +185,18 @@ * @param child {DisplayObject} * @param child2 {DisplayObject} */ -DisplayObjectContainer.prototype.swapChildren = function (child, child2) { - if (child === child2) { +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) { + if (index1 < 0 || index2 < 0) + { throw new Error('swapChildren: Both the supplied DisplayObjects must be a child of the caller.'); } @@ -187,10 +210,12 @@ * @param child {DisplayObject} The DisplayObject instance to identify * @return {Number} The index position of the child display object to identify */ -DisplayObjectContainer.prototype.getChildIndex = function (child) { +DisplayObjectContainer.prototype.getChildIndex = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { throw new Error('The supplied DisplayObject must be a child of the caller'); } @@ -203,8 +228,10 @@ * @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 */ -DisplayObjectContainer.prototype.setChildIndex = function (child, index) { - if (index < 0 || index >= this.children.length) { +DisplayObjectContainer.prototype.setChildIndex = function (child, index) +{ + if (index < 0 || index >= this.children.length) + { throw new Error('The supplied index is out of bounds'); } @@ -220,8 +247,10 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child at the given index, if any. */ -DisplayObjectContainer.prototype.getChildAt = function (index) { - if (index < 0 || index >= this.children.length) { +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'); } @@ -234,10 +263,12 @@ * @param child {DisplayObject} The DisplayObject to remove * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChild = function (child) { +DisplayObjectContainer.prototype.removeChild = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { return; } @@ -250,7 +281,8 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChildAt = function (index) { +DisplayObjectContainer.prototype.removeChildAt = function (index) +{ var child = this.getChildAt(index); child.parent = null; @@ -265,24 +297,29 @@ * @param beginIndex {Number} The beginning position. Default value is 0. * @param endIndex {Number} The ending position. Default value is size of the container. */ -DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) { +DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) +{ var begin = beginIndex || 0; var end = typeof endIndex === 'number' ? endIndex : this.children.length; var range = end - begin; - if (range > 0 && range <= end) { + if (range > 0 && range <= end) + { var removed = this.children.splice(begin, range); - for (var i = 0; i < removed.length; ++i) { + for (var i = 0; i < removed.length; ++i) + { removed[i].parent = null; } return removed; } - else if (range === 0 && this.children.length === 0) { + else if (range === 0 && this.children.length === 0) + { return []; } - else { + else + { throw new RangeError('removeChildren: numeric values are outside the acceptable range.'); } }; @@ -291,7 +328,8 @@ * Generates and updates the cached sprite for this object. * */ -DisplayObjectContainer.prototype.updateCachedSprite = function () { +DisplayObjectContainer.prototype.updateCachedSprite = function () +{ this._generateCachedSprite(); }; @@ -304,7 +342,8 @@ * @param renderer {CanvasRenderer|WebGLRenderer} The renderer used to generate the texture. * @return {Texture} a texture of the graphics object */ -DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) { +DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) +{ var bounds = this.getLocalBounds(); var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0, renderer, scaleMode, resolution); @@ -322,18 +361,22 @@ * * @private */ -DisplayObjectContainer.prototype.updateTransform = function () { - if (!this.visible) { +DisplayObjectContainer.prototype.updateTransform = function () +{ + if (!this.visible) + { return; } this.displayObjectUpdateTransform(); - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { return; } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } }; @@ -346,8 +389,10 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getBounds = function () { - if (this.children.length === 0) { +DisplayObjectContainer.prototype.getBounds = function () +{ + if (this.children.length === 0) + { return math.Rectangle.EMPTY; } @@ -365,10 +410,12 @@ var childVisible = false; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -386,7 +433,8 @@ maxY = maxY > childMaxY ? maxY : childMaxY; } - if (!childVisible) { + if (!childVisible) + { return math.Rectangle.EMPTY; } @@ -407,12 +455,14 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getLocalBounds = function () { +DisplayObjectContainer.prototype.getLocalBounds = function () +{ var matrixCache = this.worldTransform; this.worldTransform = math.Matrix.IDENTITY; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } @@ -428,13 +478,16 @@ * * @param renderer {WebGLRenderer} The renderer */ -DisplayObjectContainer.prototype.renderWebGL = function (renderer) { +DisplayObjectContainer.prototype.renderWebGL = function (renderer) +{ // if the object is not visible or the alpha is 0 then no need to render this element - if (!this.visible || this.alpha <= 0) { + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } @@ -442,14 +495,17 @@ var i, j; // do a quick check to see if this element has a mask or a filter. - if (this._mask || this._filters) { + if (this._mask || this._filters) + { // push filter first as we need to ensure the stencil buffer is correct for any masking - if (this._filters) { + if (this._filters) + { renderer.spriteBatch.flush(); renderer.filterManager.pushFilter(this._filterBlock); } - if (this._mask) { + if (this._mask) + { renderer.spriteBatch.stop(); renderer.maskManager.pushMask(this.mask, renderer); renderer.spriteBatch.start(); @@ -459,36 +515,42 @@ this._renderWebGL(renderer); // now loop through the children and make sure they get rendered - for (i = 0, j = this.children.length; i < j; i++) { + for (i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderWebGL(renderer); } // time to stop the sprite batch as either a mask element or a filter draw will happen next renderer.spriteBatch.stop(); - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(this._mask, renderer); } - if (this._filters) { + if (this._filters) + { renderer.filterManager.popFilter(); } renderer.spriteBatch.start(); } - else { + else + { this._renderWebGL(renderer); // simple render children! - for (i = 0, j = this.children.length; i < j; ++i) { + for (i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderWebGL(renderer); } } }; -DisplayObjectContainer.prototype._renderWebGL = function (renderer) { +DisplayObjectContainer.prototype._renderWebGL = function (renderer) +{ // this is where content itself gets renderd.. @@ -499,25 +561,31 @@ * * @param renderer {CanvasRenderer} The renderer */ -DisplayObjectContainer.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0) { +DisplayObjectContainer.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -528,13 +596,16 @@ * @param renderer {WebGLRenderer|CanvasRenderer} The renderer * @private */ -DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) { +DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) +{ this._cachedSprite.worldAlpha = this.worldAlpha; - if (renderer.gl) { + if (renderer.gl) + { this._cachedSprite.renderWebGL(renderer); } - else { + else + { this._cachedSprite.renderCanvas(renderer); } }; @@ -544,10 +615,12 @@ * * @private */ -DisplayObjectContainer.prototype._generateCachedSprite = function () { +DisplayObjectContainer.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { // TODO - RenderTexture now *requires* a renderer instance, so this is like broken // because `renderer` isn't actually in scope here :P var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0); @@ -555,7 +628,8 @@ this._cachedSprite = new Sprite(renderTexture); this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.texture.resize(bounds.width | 0, bounds.height | 0); } @@ -580,8 +654,10 @@ * * @private */ -DisplayObjectContainer.prototype._destroyCachedSprite = function () { - if (!this._cachedSprite) { +DisplayObjectContainer.prototype._destroyCachedSprite = function () +{ + if (!this._cachedSprite) + { return; } diff --git a/src/core/display/Sprite.js b/src/core/display/Sprite.js index 707da24..5862aef 100644 --- a/src/core/display/Sprite.js +++ b/src/core/display/Sprite.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param texture {Texture} The texture for this sprite */ -function Sprite(texture) { +function Sprite(texture) +{ DisplayObjectContainer.call(this); /** @@ -85,12 +86,14 @@ this.texture = texture || Texture.EMPTY; } -Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) { +Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) +{ DisplayObjectContainer.prototype.destroy.call(this); this.anchor = null; - if (destroyTexture) { + if (destroyTexture) + { this._texture.destroy(destroyBaseTexture); } @@ -111,10 +114,12 @@ * @memberof Sprite# */ width: { - get: function () { + get: function () + { return this.scale.x * this.texture.frame.width; }, - set: function (value) { + set: function (value) + { this.scale.x = value / this.texture.frame.width; this._width = value; } @@ -127,10 +132,12 @@ * @memberof Sprite# */ height: { - get: function () { + get: function () + { return this.scale.y * this.texture.frame.height; }, - set: function (value) { + set: function (value) + { this.scale.y = value / this.texture.frame.height; this._height = value; } @@ -143,23 +150,29 @@ * @memberof Sprite# */ texture: { - get: function () { + get: function () + { return this._texture; }, - set: function (value) { - if (this._texture === value) { + set: function (value) + { + if (this._texture === value) + { return; } this._texture = value; this.cachedTint = 0xFFFFFF; - if (value) { + if (value) + { // wait for the texture to load - if (value.baseTexture.hasLoaded) { + if (value.baseTexture.hasLoaded) + { this._onTextureUpdate(); } - else { + else + { value.once('update', this._onTextureUpdate.bind(this)); } } @@ -172,18 +185,22 @@ * * @private */ -Sprite.prototype._onTextureUpdate = function () { +Sprite.prototype._onTextureUpdate = function () +{ // so if _width is 0 then width was not set.. - if (this._width) { + if (this._width) + { this.scale.x = this._width / this.texture.frame.width; } - if (this._height) { + if (this._height) + { this.scale.y = this._height / this.texture.frame.height; } }; -Sprite.prototype._renderWebGL = function (renderer) { +Sprite.prototype._renderWebGL = function (renderer) +{ // this is where content gets renderd.. // watch this space for a little render state manager.. @@ -197,7 +214,8 @@ * @param matrix {Matrix} the transformation matrix of the sprite * @return {Rectangle} the framing rectangle */ -Sprite.prototype.getBounds = function (matrix) { +Sprite.prototype.getBounds = function (matrix) +{ var width = this.texture.frame.width; var height = this.texture.frame.height; @@ -224,11 +242,13 @@ if(b === 0 && c === 0) { // scale may be negative! - if (a < 0) { + if (a < 0) + { a *= -1; } - if (d < 0) { + if (d < 0) + { d *= -1; } @@ -293,28 +313,34 @@ * * @param renderer {CanvasRenderer} The renderer */ -Sprite.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) { +Sprite.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) + { return; } - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; renderer.context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } // Ignore null sources - if (this.texture.valid) { + if (this.texture.valid) + { var resolution = this.texture.baseTexture.resolution / renderer.resolution; renderer.context.globalAlpha = this.worldAlpha; // If smoothingEnabled is supported and we need to change the smoothing property for this texture - if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) { + if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) + { renderer.scaleMode = this.texture.baseTexture.scaleMode; renderer.context[renderer.smoothProperty] = (renderer.scaleMode === CONST.scaleModes.LINEAR); } @@ -324,7 +350,8 @@ var dy = (this.texture.trim ? this.texture.trim.y : 0) - (this.anchor.y * this.texture.trim.height); // Allow for pixel rounding - if (renderer.roundPixels) { + if (renderer.roundPixels) + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -337,7 +364,8 @@ dx = dx | 0; dy = dy | 0; } - else { + else + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -348,8 +376,10 @@ ); } - if (this.tint !== 0xFFFFFF) { - if (this.cachedTint !== this.tint) { + if (this.tint !== 0xFFFFFF) + { + if (this.cachedTint !== this.tint) + { this.cachedTint = this.tint; // TODO clean up caching - how to clean up the caches? @@ -368,7 +398,8 @@ this.texture.crop.height / resolution ); } - else { + else + { renderer.context.drawImage( this.texture.baseTexture.source, this.texture.crop.x, @@ -383,11 +414,13 @@ } } - for (var i = 0, j = this.children.length; i < j; i++) { + for (var i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -402,10 +435,12 @@ * @param frameId {String} The frame Id of the texture in the cache * @return {Sprite} A new Sprite using a texture from the texture cache matching the frameId */ -Sprite.fromFrame = function (frameId) { +Sprite.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache' + this); } @@ -420,6 +455,7 @@ * @param imageId {String} The image url of the texture * @return {Sprite} A new Sprite using a texture from the texture cache matching the image id */ -Sprite.fromImage = function (imageId, crossorigin, scaleMode) { +Sprite.fromImage = function (imageId, crossorigin, scaleMode) +{ return new Sprite(Texture.fromImage(imageId, crossorigin, scaleMode)); }; diff --git a/src/core/display/SpriteBatch.js b/src/core/display/SpriteBatch.js index 3187777..c196fef 100644 --- a/src/core/display/SpriteBatch.js +++ b/src/core/display/SpriteBatch.js @@ -12,7 +12,8 @@ * ```js * var container = new SpriteBatch(); * - * for(var i = 0; i < 100; ++i) { + * for(var i = 0; i < 100; ++i) + * { * var sprite = new PIXI.Sprite.fromImage("myImage.png"); * container.addChild(sprite); * } @@ -25,7 +26,8 @@ */ //TODO RENAME to PARTICLE CONTAINER? -function SpriteBatch() { +function SpriteBatch() +{ DisplayObjectContainer.call(this); } @@ -38,7 +40,8 @@ * * @private */ -SpriteBatch.prototype.updateTransform = function () { +SpriteBatch.prototype.updateTransform = function () +{ // TODO don't need to! this.displayObjectUpdateTransform(); // PIXI.DisplayObjectContainer.prototype.updateTransform.call( this ); @@ -50,8 +53,10 @@ * @param renderer {WebGLRenderer} The webgl renderer * @private */ -SpriteBatch.prototype.renderWebGL = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderWebGL = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -71,8 +76,10 @@ * @param renderer {CanvasRenderer} The canvas renderer * @private */ -SpriteBatch.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -84,10 +91,12 @@ this.displayObjectUpdateTransform(); - for (var i = 0; i < this.children.length; ++i) { + for (var i = 0; i < this.children.length; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -95,9 +104,11 @@ context.globalAlpha = this.worldAlpha * child.alpha; - if (child.rotation % (Math.PI * 2) === 0) { + if (child.rotation % (Math.PI * 2) === 0) + { // this is the fastest way to optimise! - if rotation is 0 then we can avoid any kind of setTransform call - if (isRotated) { + if (isRotated) + { context.setTransform( transform.a, transform.b, @@ -122,8 +133,10 @@ frame.height * child.scale.y ); } - else { - if (!isRotated) { + else + { + if (!isRotated) + { isRotated = true; } @@ -131,7 +144,8 @@ var childTransform = child.worldTransform; - if (renderer.roundPixels) { + if (renderer.roundPixels) + { context.setTransform( childTransform.a, childTransform.b, @@ -141,7 +155,8 @@ childTransform.ty | 0 ); } - else { + else + { context.setTransform( childTransform.a, childTransform.b, diff --git a/src/core/index.js b/src/core/index.js index 3954b6f..eb4a82b 100644 --- a/src/core/index.js +++ b/src/core/index.js @@ -58,11 +58,13 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRenderer: function (width, height, options, noWebGL) { + autoDetectRenderer: function (width, height, options, noWebGL) + { width = width || 800; height = height || 600; - if (!noWebGL && require('webgl-enabled')()) { + if (!noWebGL && require('webgl-enabled')()) + { return new core.WebGLRenderer(width, height, options); } @@ -87,7 +89,8 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRecommendedRenderer: function (width, height, options) { + autoDetectRecommendedRenderer: function (width, height, options) + { var isAndroid = /Android/i.test(navigator.userAgent); return core.autoDetectRenderer(width, height, options, isAndroid); diff --git a/src/core/math/Matrix.js b/src/core/math/Matrix.js index c2f87e2..2ff4848 100644 --- a/src/core/math/Matrix.js +++ b/src/core/math/Matrix.js @@ -10,7 +10,8 @@ * @class * @namespace PIXI */ -function Matrix() { +function Matrix() +{ /** * @member {number} * @default 1 @@ -63,7 +64,8 @@ * * @param array {number[]} The array that the matrix will be populated from. */ -Matrix.prototype.fromArray = function (array) { +Matrix.prototype.fromArray = function (array) +{ this.a = array[0]; this.b = array[1]; this.c = array[3]; @@ -78,14 +80,17 @@ * @param transpose {boolean} Whether we need to transpose the matrix or not * @return {number[]} the newly created array which contains the matrix */ -Matrix.prototype.toArray = function (transpose) { - if (!this.array) { +Matrix.prototype.toArray = function (transpose) +{ + if (!this.array) + { this.array = new Float32Array(9); } var array = this.array; - if (transpose) { + if (transpose) + { array[0] = this.a; array[1] = this.b; array[2] = 0; @@ -96,7 +101,8 @@ array[7] = this.ty; array[8] = 1; } - else { + else + { array[0] = this.a; array[1] = this.c; array[2] = this.tx; @@ -119,7 +125,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, transformed through this matrix */ -Matrix.prototype.apply = function (pos, newPos) { +Matrix.prototype.apply = function (pos, newPos) +{ newPos = newPos || new Point(); newPos.x = this.a * pos.x + this.c * pos.y + this.tx; @@ -136,7 +143,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, inverse-transformed through this matrix */ -Matrix.prototype.applyInverse = function (pos, newPos) { +Matrix.prototype.applyInverse = function (pos, newPos) +{ newPos = newPos || new Point(); var id = 1 / (this.a * this.d + this.c * -this.b); @@ -154,7 +162,8 @@ * @param {number} y * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.translate = function (x, y) { +Matrix.prototype.translate = function (x, y) +{ this.tx += x; this.ty += y; @@ -168,7 +177,8 @@ * @param {number} y The amount to scale vertically * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.scale = function (x, y) { +Matrix.prototype.scale = function (x, y) +{ this.a *= x; this.d *= y; this.c *= x; @@ -186,7 +196,8 @@ * @param {number} angle - The angle in radians. * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.rotate = function (angle) { +Matrix.prototype.rotate = function (angle) +{ var cos = Math.cos( angle ); var sin = Math.sin( angle ); @@ -210,7 +221,8 @@ * @param {Matrix} matrix * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.append = function (matrix) { +Matrix.prototype.append = function (matrix) +{ var a1 = this.a; var b1 = this.b; var c1 = this.c; @@ -232,7 +244,8 @@ * * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.identity = function () { +Matrix.prototype.identity = function () +{ this.a = 1; this.b = 0; this.c = 0; diff --git a/src/core/math/Point.js b/src/core/math/Point.js index 7565b2d..632f346 100644 --- a/src/core/math/Point.js +++ b/src/core/math/Point.js @@ -7,7 +7,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -function Point(x, y) { +function Point(x, y) +{ /** * @member {number} * @default 0 @@ -29,7 +30,8 @@ * * @return {Point} a copy of the point */ -Point.prototype.clone = function () { +Point.prototype.clone = function () +{ return new Point(this.x, this.y); }; @@ -40,7 +42,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -Point.prototype.set = function (x, y) { +Point.prototype.set = function (x, y) +{ this.x = x || 0; this.y = y || ( (y !== 0) ? this.x : 0 ) ; }; diff --git a/src/core/math/shapes/Circle.js b/src/core/math/shapes/Circle.js index 69cfdc9..4d76efc 100644 --- a/src/core/math/shapes/Circle.js +++ b/src/core/math/shapes/Circle.js @@ -10,7 +10,8 @@ * @param y {number} The Y coordinate of the center of this circle * @param radius {number} The radius of the circle */ -function Circle(x, y, radius) { +function Circle(x, y, radius) +{ /** * @member {number} * @default 0 @@ -46,7 +47,8 @@ * @method clone * @return {Circle} a copy of the Circle */ -Circle.prototype.clone = function () { +Circle.prototype.clone = function () +{ return new Circle(this.x, this.y, this.radius); }; @@ -58,8 +60,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Circle */ -Circle.prototype.contains = function (x, y) { - if (this.radius <= 0) { +Circle.prototype.contains = function (x, y) +{ + if (this.radius <= 0) + { return false; } @@ -79,6 +83,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Circle.prototype.getBounds = function () { +Circle.prototype.getBounds = function () +{ return new Rectangle(this.x - this.radius, this.y - this.radius, this.radius * 2, this.radius * 2); }; diff --git a/src/core/math/shapes/Ellipse.js b/src/core/math/shapes/Ellipse.js index 4f2d066..fefd01a 100644 --- a/src/core/math/shapes/Ellipse.js +++ b/src/core/math/shapes/Ellipse.js @@ -11,7 +11,8 @@ * @param width {number} The half width of this ellipse * @param height {number} The half height of this ellipse */ -function Ellipse(x, y, width, height) { +function Ellipse(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -53,7 +54,8 @@ * @method clone * @return {Ellipse} a copy of the ellipse */ -Ellipse.prototype.clone = function () { +Ellipse.prototype.clone = function () +{ return new Ellipse(this.x, this.y, this.width, this.height); }; @@ -65,8 +67,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coords are within this ellipse */ -Ellipse.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Ellipse.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } @@ -86,6 +90,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Ellipse.prototype.getBounds = function () { +Ellipse.prototype.getBounds = function () +{ return new Rectangle(this.x - this.width, this.y - this.height, this.width, this.height); }; diff --git a/src/core/math/shapes/Polygon.js b/src/core/math/shapes/Polygon.js index ae89148..fea6d37 100644 --- a/src/core/math/shapes/Polygon.js +++ b/src/core/math/shapes/Polygon.js @@ -10,16 +10,20 @@ * arguments passed can be flat x,y values e.g. `new Polygon(x,y, x,y, x,y, ...)` where `x` and `y` are * Numbers. */ -function Polygon(points) { +function Polygon(points) +{ //if points isn't an array, use arguments as the array - if (!(points instanceof Array)) { + if (!(points instanceof Array)) + { points = Array.prototype.slice.call(arguments); } //if this is a flat array of numbers, convert it to points - if (points[0] instanceof Point) { + if (points[0] instanceof Point) + { var p = []; - for (var i = 0, il = points.length; i < il; i++) { + for (var i = 0, il = points.length; i < il; i++) + { p.push(points[i].x, points[i].y); } @@ -51,7 +55,8 @@ * * @return {Polygon} a copy of the polygon */ -Polygon.prototype.clone = function () { +Polygon.prototype.clone = function () +{ return new Polygon(this.points.slice()); }; @@ -62,19 +67,22 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this polygon */ -Polygon.prototype.contains = function (x, y) { +Polygon.prototype.contains = function (x, y) +{ var inside = false; // use some raycasting to test hits // https://github.com/substack/point-in-polygon/blob/master/index.js var length = this.points.length / 2; - for (var i = 0, j = length - 1; i < length; j = i++) { + for (var i = 0, j = length - 1; i < length; j = i++) + { var xi = this.points[i * 2], yi = this.points[i * 2 + 1], xj = this.points[j * 2], yj = this.points[j * 2 + 1], intersect = ((yi > y) !== (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi); - if (intersect) { + if (intersect) + { inside = !inside; } } diff --git a/src/core/math/shapes/Rectangle.js b/src/core/math/shapes/Rectangle.js index 16ac62a..4008b68 100644 --- a/src/core/math/shapes/Rectangle.js +++ b/src/core/math/shapes/Rectangle.js @@ -10,7 +10,8 @@ * @param width {number} The overall width of this rectangle * @param height {number} The overall height of this rectangle */ -function Rectangle(x, y, width, height) { +function Rectangle(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -60,7 +61,8 @@ * * @return {Rectangle} a copy of the rectangle */ -Rectangle.prototype.clone = function () { +Rectangle.prototype.clone = function () +{ return new Rectangle(this.x, this.y, this.width, this.height); }; @@ -71,13 +73,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rectangle */ -Rectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Rectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/math/shapes/RoundedRectangle.js b/src/core/math/shapes/RoundedRectangle.js index 27d286e..7bf6411 100644 --- a/src/core/math/shapes/RoundedRectangle.js +++ b/src/core/math/shapes/RoundedRectangle.js @@ -11,7 +11,8 @@ * @param height {number} The overall height of this rounded rectangle * @param radius {number} Controls the radius of the rounded corners */ -function RoundedRectangle(x, y, width, height, radius) { +function RoundedRectangle(x, y, width, height, radius) +{ /** * @member {number} * @default 0 @@ -58,7 +59,8 @@ * * @return {RoundedRectangle} a copy of the rounded rectangle */ -RoundedRectangle.prototype.clone = function () { +RoundedRectangle.prototype.clone = function () +{ return new RoundedRectangle(this.x, this.y, this.width, this.height, this.radius); }; @@ -69,13 +71,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rounded Rectangle */ -RoundedRectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +RoundedRectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/primitives/Graphics.js b/src/core/primitives/Graphics.js index 261c534..e902d2a 100644 --- a/src/core/primitives/Graphics.js +++ b/src/core/primitives/Graphics.js @@ -16,7 +16,8 @@ * @extends DisplayObjectContainer * @namespace PIXI */ -function Graphics() { +function Graphics() +{ DisplayObjectContainer.call(this); this.renderable = true; @@ -154,16 +155,20 @@ * @private */ cacheAsBitmap: { - get: function () { + get: function () + { return this._cacheAsBitmap; }, - set: function (value) { + set: function (value) + { this._cacheAsBitmap = value; - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._generateCachedSprite(); } - else { + else + { this.destroyCachedSprite(); this.dirty = true; } @@ -176,7 +181,8 @@ * * @return {Graphics} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ var clone = new Graphics(); clone.renderable = this.renderable; @@ -192,7 +198,8 @@ clone.cachedSpriteDirty = this.cachedSpriteDirty; // copy graphics data - for (var i = 0; i < this.graphicsData.length; ++i) { + for (var i = 0; i < this.graphicsData.length; ++i) + { clone.graphicsData.push(this.graphicsData.clone()); } @@ -211,17 +218,21 @@ * @param alpha {number} alpha of the line to draw, will update the objects stored style * @return {Graphics} */ -Graphics.prototype.lineStyle = function (lineWidth, color, alpha) { +Graphics.prototype.lineStyle = function (lineWidth, color, alpha) +{ this.lineWidth = lineWidth || 0; this.lineColor = color || 0; this.lineAlpha = (arguments.length < 3) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length) + { // halfway through a line? start a new one! this.drawShape( new math.Polygon( this.currentPath.shape.points.slice(-2) )); } - else { + else + { // otherwise its empty so lets just set the line properties this.currentPath.lineWidth = this.lineWidth; this.currentPath.lineColor = this.lineColor; @@ -239,7 +250,8 @@ * @param y {number} the Y coordinate to move to * @return {Graphics} */ -Graphics.prototype.moveTo = function (x, y) { +Graphics.prototype.moveTo = function (x, y) +{ this.drawShape(new math.Polygon([x,y])); return this; @@ -253,7 +265,8 @@ * @param y {number} the Y coordinate to draw to * @return {Graphics} */ -Graphics.prototype.lineTo = function (x, y) { +Graphics.prototype.lineTo = function (x, y) +{ this.currentPath.shape.points.push(x, y); this.dirty = true; @@ -270,13 +283,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -285,7 +302,8 @@ n = 20, points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { this.moveTo(0, 0); } @@ -293,7 +311,8 @@ var fromY = points[points.length-1]; var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; xa = fromX + ( (cpX - fromX) * j ); @@ -319,13 +338,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -342,7 +365,8 @@ var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; dt = (1 - j); @@ -373,13 +397,17 @@ * @param radius {number} The radius of the arc * @return {Graphics} */ -Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points.push(x1, y1); } } - else { + else + { this.moveTo(x1, y1); } @@ -392,12 +420,15 @@ b2 = x2 - x1, mm = Math.abs(a1 * b2 - b1 * a2); - if (mm < 1.0e-8 || radius === 0) { - if (points[points.length-2] !== x1 || points[points.length-1] !== y1) { + if (mm < 1.0e-8 || radius === 0) + { + if (points[points.length-2] !== x1 || points[points.length-1] !== y1) + { points.push(x1, y1); } } - else { + else + { var dd = a1 * a1 + b1 * b1, cc = a2 * a2 + b2 * b2, tt = a1 * a2 + b1 * b2, @@ -433,42 +464,51 @@ * @param anticlockwise {boolean} Optional. Specifies whether the drawing should be counterclockwise or clockwise. False is default, and indicates clockwise, while true indicates counter-clockwise. * @return {Graphics} */ -Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) { +Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) +{ var startX = cx + Math.cos(startAngle) * radius; var startY = cy + Math.sin(startAngle) * radius; var points; // TODO - This if-else makes no sense. It uses currentPath in the else where it doesn't exist... - if (this.currentPath) { + if (this.currentPath) + { points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { points.push(startX, startY); } - else if (points[points.length-2] !== startX || points[points.length-1] !== startY) { + else if (points[points.length-2] !== startX || points[points.length-1] !== startY) + { points.push(startX, startY); } } - else { + else + { this.moveTo(startX, startY); points = this.currentPath.shape.points; } - if (startAngle === endAngle) { + if (startAngle === endAngle) + { return this; } - if (!anticlockwise && endAngle <= startAngle) { + if (!anticlockwise && endAngle <= startAngle) + { endAngle += Math.PI * 2; } - else if (anticlockwise && startAngle <= endAngle) { + else if (anticlockwise && startAngle <= endAngle) + { startAngle += Math.PI * 2; } var sweep = anticlockwise ? (startAngle - endAngle) *-1 : (endAngle - startAngle); var segs = (Math.abs(sweep)/ (Math.PI * 2)) * 40; - if (sweep === 0) { + if (sweep === 0) + { return this; } @@ -482,7 +522,8 @@ var remainder = ( segMinus % 1 ) / segMinus; - for (var i = 0; i <= segMinus; ++i) { + for (var i = 0; i <= segMinus; ++i) + { var real = i + remainder * i; var angle = ((theta) + startAngle + (theta2 * real)); @@ -506,13 +547,16 @@ * @param alpha {number} the alpha of the fill * @return {Graphics} */ -Graphics.prototype.beginFill = function (color, alpha) { +Graphics.prototype.beginFill = function (color, alpha) +{ this.filling = true; this.fillColor = color || 0; this.fillAlpha = (alpha === undefined) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length <= 2) + { this.currentPath.fill = this.filling; this.currentPath.fillColor = this.fillColor; this.currentPath.fillAlpha = this.fillAlpha; @@ -526,7 +570,8 @@ * * @return {Graphics} */ -Graphics.prototype.endFill = function () { +Graphics.prototype.endFill = function () +{ this.filling = false; this.fillColor = null; this.fillAlpha = 1; @@ -542,7 +587,8 @@ * @param height {number} The height of the rectangle * @return {Graphics} */ -Graphics.prototype.drawRect = function ( x, y, width, height ) { +Graphics.prototype.drawRect = function ( x, y, width, height ) +{ this.drawShape(new math.Rectangle(x,y, width, height)); return this; @@ -556,7 +602,8 @@ * @param height {number} The height of the rectangle * @param radius {number} Radius of the rectangle corners */ -Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) { +Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) +{ this.drawShape(new math.RoundedRectangle(x, y, width, height, radius)); return this; @@ -570,7 +617,8 @@ * @param radius {number} The radius of the circle * @return {Graphics} */ -Graphics.prototype.drawCircle = function (x, y, radius) { +Graphics.prototype.drawCircle = function (x, y, radius) +{ this.drawShape(new math.Circle(x,y, radius)); return this; @@ -585,7 +633,8 @@ * @param height {number} The half height of the ellipse * @return {Graphics} */ -Graphics.prototype.drawEllipse = function (x, y, width, height) { +Graphics.prototype.drawEllipse = function (x, y, width, height) +{ this.drawShape(new math.Ellipse(x, y, width, height)); return this; @@ -597,8 +646,10 @@ * @param path {Array} The path data used to construct the polygon. * @return {Graphics} */ -Graphics.prototype.drawPolygon = function (path) { - if (!(path instanceof Array)) { +Graphics.prototype.drawPolygon = function (path) +{ + if (!(path instanceof Array)) + { path = Array.prototype.slice.call(arguments); } @@ -612,7 +663,8 @@ * * @return {Graphics} */ -Graphics.prototype.clear = function () { +Graphics.prototype.clear = function () +{ this.lineWidth = 0; this.filling = false; @@ -631,7 +683,8 @@ * @param scaleMode {number} Should be one of the scaleMode consts * @return {Texture} a texture of the graphics object */ -Graphics.prototype.generateTexture = function (resolution, scaleMode) { +Graphics.prototype.generateTexture = function (resolution, scaleMode) +{ resolution = resolution || 1; var bounds = this.getBounds(); @@ -655,17 +708,21 @@ * * @param renderer {WebGLRenderer} */ -Graphics.prototype._renderWebGL = function (renderer) { +Graphics.prototype._renderWebGL = function (renderer) +{ // if the sprite is not visible or the alpha is 0 then no need to render this element - if (this.isMask === true) { + if (this.isMask === true) + { return; } // this code may still be needed so leaving for now.. - // + // /* - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture on the gpu too! @@ -681,17 +738,24 @@ return; } - */ - - // check if the webgl graphic needs to be updated - if (this.glDirty) { - this.dirty = true; - this.glDirty = false; - } + else */ - renderer.setObjectRendererer(renderer.graphicsRenderer); - renderer.graphicsRenderer.render(this); + renderer.spriteBatch.stop(); + renderer.blendModeManager.setBlendMode(this.blendMode); + // check blend mode + renderer.blendModeManager.setBlendMode( this.blendMode ); + + // check if the webgl graphic needs to be updated + if (this.glDirty) + { + this.dirty = true; + this.glDirty = false; + } + + WebGLGraphics.renderGraphics(this, renderer); + + renderer.spriteBatch.start(); }; /** @@ -700,14 +764,18 @@ * @param renderer {CanvasRenderer} * @private */ -Graphics.prototype.renderCanvas = function (renderer) { +Graphics.prototype.renderCanvas = function (renderer) +{ // 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.isMask === true) { + if (!this.visible || this.alpha <= 0 || this.isMask === true) + { return; } - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture @@ -723,16 +791,19 @@ return; } - else { + else + { var context = renderer.context; var transform = this.worldTransform; - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } @@ -748,11 +819,13 @@ CanvasGraphics.renderGraphics(this, context); - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } } @@ -763,13 +836,16 @@ * * @return {Rectangle} the rectangular bounding area */ -Graphics.prototype.getBounds = function (matrix) { +Graphics.prototype.getBounds = function (matrix) +{ // return an empty object if the item is a mask! - if (this.isMask) { + if (this.isMask) + { return math.Rectangle.EMPTY; } - if (this.dirty) { + if (this.dirty) + { this.updateLocalBounds(); this.glDirty = true; @@ -841,23 +917,27 @@ * Update the bounds of the object * */ -Graphics.prototype.updateLocalBounds = function () { +Graphics.prototype.updateLocalBounds = function () +{ var minX = Infinity; var maxX = -Infinity; var minY = Infinity; var maxY = -Infinity; - if (this.graphicsData.length) { + if (this.graphicsData.length) + { var shape, points, x, y, w, h; - for (var i = 0; i < this.graphicsData.length; i++) { + for (var i = 0; i < this.graphicsData.length; i++) + { var data = this.graphicsData[i]; var type = data.type; var lineWidth = data.lineWidth; shape = data.shape; - if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) { + if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) + { x = shape.x - lineWidth/2; y = shape.y - lineWidth/2; w = shape.width + lineWidth; @@ -869,7 +949,8 @@ minY = y < minY ? y : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.CIRC) { + else if (type === CONST.SHAPES.CIRC) + { x = shape.x; y = shape.y; w = shape.radius + lineWidth/2; @@ -881,7 +962,8 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.ELIP) { + else if (type === CONST.SHAPES.ELIP) + { x = shape.x; y = shape.y; w = shape.width + lineWidth/2; @@ -893,11 +975,13 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else { + else + { // POLY points = shape.points; - for (var j = 0; j < points.length; j += 2) { + for (var j = 0; j < points.length; j += 2) + { x = points[j]; y = points[j+1]; @@ -910,7 +994,8 @@ } } } - else { + else + { minX = 0; maxX = 0; minY = 0; @@ -931,10 +1016,12 @@ * * @private */ -Graphics.prototype._generateCachedSprite = function () { +Graphics.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { var canvasBuffer = new CanvasBuffer(bounds.width, bounds.height); var texture = Texture.fromCanvas(canvasBuffer.canvas); @@ -943,7 +1030,8 @@ this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.buffer.resize(bounds.width, bounds.height); } @@ -968,7 +1056,8 @@ * * @private */ -Graphics.prototype.updateCachedSpriteTexture = function () { +Graphics.prototype.updateCachedSpriteTexture = function () +{ var cachedSprite = this._cachedSprite; var texture = cachedSprite.texture; var canvas = cachedSprite.buffer.canvas; @@ -989,7 +1078,8 @@ * Destroys a previous cached sprite. * */ -Graphics.prototype.destroyCachedSprite = function () { +Graphics.prototype.destroyCachedSprite = function () +{ this._cachedSprite.texture.destroy(true); // let the gc collect the unused sprite @@ -1003,10 +1093,13 @@ * @param {Circle|Rectangle|Ellipse|Line|Polygon} shape The Shape object to draw. * @return {GraphicsData} The generated GraphicsData object. */ -Graphics.prototype.drawShape = function (shape) { - if (this.currentPath) { +Graphics.prototype.drawShape = function (shape) +{ + if (this.currentPath) + { // check current path! - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath.shape.points.length <= 2) + { this.graphicsData.pop(); } } @@ -1017,7 +1110,8 @@ this.graphicsData.push(data); - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { data.shape.closed = this.filling; this.currentPath = data; } diff --git a/src/core/primitives/GraphicsData.js b/src/core/primitives/GraphicsData.js index 99decbe..788f6f2 100644 --- a/src/core/primitives/GraphicsData.js +++ b/src/core/primitives/GraphicsData.js @@ -4,7 +4,8 @@ * @class * @namespace PIXI */ -function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) { +function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) +{ this.lineWidth = lineWidth; this.lineColor = lineColor; this.lineAlpha = lineAlpha; @@ -27,7 +28,8 @@ * * @return {GraphicsData} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ return new GraphicsData( this.lineWidth, this.lineColor, diff --git a/src/core/renderers/canvas/CanvasRenderer.js b/src/core/renderers/canvas/CanvasRenderer.js index 15a0978..7aebd44 100644 --- a/src/core/renderers/canvas/CanvasRenderer.js +++ b/src/core/renderers/canvas/CanvasRenderer.js @@ -17,17 +17,22 @@ * @param [options.resolution=1] {number} the resolution of the renderer retina would be 2 * @param [options.clearBeforeRender=true] {boolean} This sets if the CanvasRenderer will clear the canvas or not before the new render pass. */ -function CanvasRenderer(width, height, options) { +function CanvasRenderer(width, height, options) +{ utils.sayHello('Canvas'); - if (options) { - for (var i in CONST.defaultRenderOptions) { - if (typeof options[i] === 'undefined') { + if (options) + { + for (var i in CONST.defaultRenderOptions) + { + if (typeof options[i] === 'undefined') + { options[i] = CONST.defaultRenderOptions[i]; } } } - else { + else + { options = CONST.defaultRenderOptions; } @@ -156,19 +161,24 @@ this.smoothProperty = null; - if (this.context.imageSmoothingEnabled) { + if (this.context.imageSmoothingEnabled) + { this.smoothProperty = 'imageSmoothingEnabled'; } - else if (this.context.webkitImageSmoothingEnabled) { + else if (this.context.webkitImageSmoothingEnabled) + { this.smoothProperty = 'webkitImageSmoothingEnabled'; } - else if (this.context.mozImageSmoothingEnabled) { + else if (this.context.mozImageSmoothingEnabled) + { this.smoothProperty = 'mozImageSmoothingEnabled'; } - else if (this.context.oImageSmoothingEnabled) { + else if (this.context.oImageSmoothingEnabled) + { this.smoothProperty = 'oImageSmoothingEnabled'; } - else if (this.context.msImageSmoothingEnabled) { + else if (this.context.msImageSmoothingEnabled) + { this.smoothProperty = 'msImageSmoothingEnabled'; } @@ -193,10 +203,12 @@ * @memberof CanvasRenderer# */ backgroundColor: { - get: function () { + get: function () + { return this._backgroundColor; }, - set: function (val) { + set: function (val) + { this._backgroundColor = val; this._backgroundColorString = utils.hex2string(val); } @@ -208,7 +220,8 @@ * * @param object {DisplayObject} the object to be rendered */ -CanvasRenderer.prototype.render = function (object) { +CanvasRenderer.prototype.render = function (object) +{ object.updateTransform(); this.context.setTransform(1,0,0,1,0,0); @@ -218,16 +231,20 @@ this.currentBlendMode = CONST.blendModes.NORMAL; this.context.globalCompositeOperation = this.blendModes[CONST.blendModes.NORMAL]; - if (navigator.isCocoonJS && this.view.screencanvas) { + if (navigator.isCocoonJS && this.view.screencanvas) + { this.context.fillStyle = 'black'; this.context.clear(); } - if (this.clearBeforeRender) { - if (this.transparent) { + if (this.clearBeforeRender) + { + if (this.transparent) + { this.context.clearRect(0, 0, this.width, this.height); } - else { + else + { this.context.fillStyle = this._backgroundColorString; this.context.fillRect(0, 0, this.width , this.height); } @@ -241,8 +258,10 @@ * * @param [removeView=false] {boolean} Removes the Canvas element from the DOM. */ -CanvasRenderer.prototype.destroy = function (removeView) { - if (removeView && this.view.parent) { +CanvasRenderer.prototype.destroy = function (removeView) +{ + if (removeView && this.view.parent) + { this.view.parent.removeChild(this.view); } @@ -257,14 +276,16 @@ * @param width {number} the new width of the canvas view * @param height {number} the new height of the canvas view */ -CanvasRenderer.prototype.resize = function (width, height) { +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) { + if (this.autoResize) + { this.view.style.width = this.width / this.resolution + 'px'; this.view.style.height = this.height / this.resolution + 'px'; } @@ -276,7 +297,8 @@ * @param displayObject {DisplayObject} The displayObject to render * @private */ -CanvasRenderer.prototype.renderDisplayObject = function (displayObject) { +CanvasRenderer.prototype.renderDisplayObject = function (displayObject) +{ displayObject.renderCanvas(this); }; @@ -285,11 +307,14 @@ * * @private */ -CanvasRenderer.prototype._mapBlendModes = function () { - if (!this.blendModes) { +CanvasRenderer.prototype._mapBlendModes = function () +{ + if (!this.blendModes) + { this.blendModes = {}; - if (utils.canUseNewCanvasBlendModes()) { + if (utils.canUseNewCanvasBlendModes()) + { this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? this.blendModes[CONST.blendModes.MULTIPLY] = 'multiply'; @@ -308,7 +333,8 @@ this.blendModes[CONST.blendModes.COLOR] = 'color'; this.blendModes[CONST.blendModes.LUMINOSITY] = 'luminosity'; } - else { + else + { // this means that the browser does not support the cool new blend modes in canvas 'cough' ie 'cough' this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? diff --git a/src/core/renderers/canvas/utils/CanvasBuffer.js b/src/core/renderers/canvas/utils/CanvasBuffer.js index ebe5d47..b183a66 100644 --- a/src/core/renderers/canvas/utils/CanvasBuffer.js +++ b/src/core/renderers/canvas/utils/CanvasBuffer.js @@ -6,7 +6,8 @@ * @param width {number} the width for the newly created canvas * @param height {number} the height for the newly created canvas */ -function CanvasBuffer(width, height) { +function CanvasBuffer(width, height) +{ /** * The Canvas object that belongs to this CanvasBuffer. * @@ -36,10 +37,12 @@ * @memberof CanvasBuffer# */ width: { - get: function () { + get: function () + { return this.canvas.width; }, - set: function (val) { + set: function (val) + { this.canvas.width = val; } }, @@ -50,10 +53,12 @@ * @memberof CanvasBuffer# */ height: { - get: function () { + get: function () + { return this.canvas.height; }, - set: function (val) { + set: function (val) + { this.canvas.height = val; } } @@ -64,7 +69,8 @@ * * @private */ -CanvasBuffer.prototype.clear = function () { +CanvasBuffer.prototype.clear = function () +{ this.context.setTransform(1, 0, 0, 1, 0, 0); this.context.clearRect(0,0, this.canvas.width, this.canvas.height); }; @@ -75,7 +81,8 @@ * @param width {number} the new width of the canvas * @param height {number} the new height of the canvas */ -CanvasBuffer.prototype.resize = function (width, height) { +CanvasBuffer.prototype.resize = function (width, height) +{ this.canvas.width = width; this.canvas.height = height; }; diff --git a/src/core/renderers/canvas/utils/CanvasGraphics.js b/src/core/renderers/canvas/utils/CanvasGraphics.js index c7eaa2a..3f2a91f 100644 --- a/src/core/renderers/canvas/utils/CanvasGraphics.js +++ b/src/core/renderers/canvas/utils/CanvasGraphics.js @@ -13,15 +13,18 @@ * @param graphics {Graphics} the actual graphics object to render * @param context {CanvasRenderingContext2D} the 2d drawing method of the canvas */ -CanvasGraphics.renderGraphics = function (graphics, context) { +CanvasGraphics.renderGraphics = function (graphics, context) +{ var worldAlpha = graphics.worldAlpha; - if (graphics.dirty) { + if (graphics.dirty) + { this.updateGraphicsTint(graphics); graphics.dirty = false; } - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; @@ -30,69 +33,82 @@ context.lineWidth = data.lineWidth; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { context.beginPath(); var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } - if (shape.closed) { + if (shape.closed) + { context.lineTo(points[0], points[1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fillRect(shape.x, shape.y, shape.width, shape.height); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.strokeRect(shape.x, shape.y, shape.width, shape.height); } } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.beginPath(); context.arc(shape.x, shape.y, shape.radius,0,2*Math.PI); context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas var w = shape.width * 2; @@ -119,18 +135,21 @@ context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; var width = shape.width; @@ -152,13 +171,15 @@ context.quadraticCurveTo(rx, ry, rx, ry + radius); context.closePath(); - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); @@ -174,45 +195,54 @@ * @param graphics {Graphics} the graphics which will be used as a mask * @param context {CanvasRenderingContext2D} the context 2d method of the canvas */ -CanvasGraphics.renderGraphicsMask = function (graphics, context) { +CanvasGraphics.renderGraphicsMask = function (graphics, context) +{ var len = graphics.graphicsData.length; - if (len === 0) { + if (len === 0) + { return; } context.beginPath(); - for (var i = 0; i < len; i++) { + for (var i = 0; i < len; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { context.rect(shape.x, shape.y, shape.width, shape.height); context.closePath(); } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.arc(shape.x, shape.y, shape.radius, 0, 2 * Math.PI); context.closePath(); } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas @@ -237,7 +267,8 @@ context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); context.closePath(); } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; @@ -262,8 +293,10 @@ } }; -CanvasGraphics.updateGraphicsTint = function (graphics) { - if (graphics.tint === 0xFFFFFF) { +CanvasGraphics.updateGraphicsTint = function (graphics) +{ + if (graphics.tint === 0xFFFFFF) + { return; } @@ -271,7 +304,8 @@ var tintG = (graphics.tint >> 8 & 0xFF) / 255; var tintB = (graphics.tint & 0xFF)/ 255; - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var fillColor = data.fillColor | 0; diff --git a/src/core/renderers/canvas/utils/CanvasMaskManager.js b/src/core/renderers/canvas/utils/CanvasMaskManager.js index e04a733..9827d36 100644 --- a/src/core/renderers/canvas/utils/CanvasMaskManager.js +++ b/src/core/renderers/canvas/utils/CanvasMaskManager.js @@ -6,7 +6,8 @@ * @class * @namespace PIXI */ -function CanvasMaskManager() {} +function CanvasMaskManager() +{} CanvasMaskManager.prototype.constructor = CanvasMaskManager; module.exports = CanvasMaskManager; @@ -17,7 +18,8 @@ * @param maskData {object} the maskData that will be pushed * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.pushMask = function (maskData, renderer) { +CanvasMaskManager.prototype.pushMask = function (maskData, renderer) +{ renderer.context.save(); var cacheAlpha = maskData.alpha; @@ -45,6 +47,7 @@ * * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.popMask = function (renderer) { +CanvasMaskManager.prototype.popMask = function (renderer) +{ renderer.context.restore(); }; diff --git a/src/core/renderers/canvas/utils/CanvasTinter.js b/src/core/renderers/canvas/utils/CanvasTinter.js index 17e0529..d2fb1bc 100644 --- a/src/core/renderers/canvas/utils/CanvasTinter.js +++ b/src/core/renderers/canvas/utils/CanvasTinter.js @@ -14,7 +14,8 @@ * @param color {number} the color to use to tint the sprite with * @return {HTMLCanvasElement} The tinted canvas */ -CanvasTinter.getTintedTexture = function (sprite, color) { +CanvasTinter.getTintedTexture = function (sprite, color) +{ var texture = sprite.texture; color = CanvasTinter.roundColor(color); @@ -23,7 +24,8 @@ texture.tintCache = texture.tintCache || {}; - if (texture.tintCache[stringColor]) { + if (texture.tintCache[stringColor]) + { return texture.tintCache[stringColor]; } @@ -33,14 +35,16 @@ //CanvasTinter.tintWithPerPixel(texture, stringColor, canvas); CanvasTinter.tintMethod(texture, color, canvas); - if (CanvasTinter.convertTintToImage) { + if (CanvasTinter.convertTintToImage) + { // is this better? var tintImage = new Image(); tintImage.src = canvas.toDataURL(); texture.tintCache[stringColor] = tintImage; } - else { + else + { texture.tintCache[stringColor] = canvas; // if we are not converting the texture to an image then we need to lose the reference to the canvas CanvasTinter.canvas = null; @@ -56,7 +60,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithMultiply = function (texture, color, canvas) { +CanvasTinter.tintWithMultiply = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -104,7 +109,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithOverlay = function (texture, color, canvas) { +CanvasTinter.tintWithOverlay = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -139,7 +145,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithPerPixel = function (texture, color, canvas) { +CanvasTinter.tintWithPerPixel = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -167,7 +174,8 @@ var pixels = pixelData.data; - for (var i = 0; i < pixels.length; i += 4) { + for (var i = 0; i < pixels.length; i += 4) + { pixels[i+0] *= r; pixels[i+1] *= g; pixels[i+2] *= b; @@ -181,7 +189,8 @@ * * @param color {number} the color to round, should be a hex color */ -CanvasTinter.roundColor = function (color) { +CanvasTinter.roundColor = function (color) +{ var step = CanvasTinter.cacheStepsPerColorChannel; var rgbValues = utils.hex2rgb(color); diff --git a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js index 9f2f89a..35edbaf 100644 --- a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js +++ b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLBlendModeManager(renderer) { +function WebGLBlendModeManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -23,8 +24,10 @@ * * @param blendMode {number} the blendMode, should be a Pixi const, such as BlendModes.ADD */ -WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) { - if (this.currentBlendMode === blendMode) { +WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) +{ + if (this.currentBlendMode === blendMode) + { return false; } diff --git a/src/core/renderers/webgl/managers/WebGLFilterManager.js b/src/core/renderers/webgl/managers/WebGLFilterManager.js index 1179258..2dac048 100644 --- a/src/core/renderers/webgl/managers/WebGLFilterManager.js +++ b/src/core/renderers/webgl/managers/WebGLFilterManager.js @@ -7,7 +7,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLFilterManager(renderer) { +function WebGLFilterManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -32,7 +33,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.texturePool.length = 0; self.initShaderBuffers(); }); @@ -46,7 +48,8 @@ * @param renderer {WebGLRenderer} * @param buffer {ArrayBuffer} */ -WebGLFilterManager.prototype.begin = function (buffer) { +WebGLFilterManager.prototype.begin = function (buffer) +{ this.defaultShader = this.renderer.shaderManager.defaultShader; this.width = this.renderer.projection.x * 2; @@ -60,7 +63,8 @@ * * @param filterBlock {object} the filter that will be pushed to the current filter stack */ -WebGLFilterManager.prototype.pushFilter = function (filterBlock) { +WebGLFilterManager.prototype.pushFilter = function (filterBlock) +{ var gl = this.renderer.gl; var projection = this.renderer.projection; @@ -78,10 +82,12 @@ this.offsetY += filterBlock._filterArea.y; var texture = this.texturePool.pop(); - if (!texture) { + if (!texture) + { texture = new FilterTexture(this.renderer.gl, this.width, this.height); } - else { + else + { texture.resize(this.width, this.height); } @@ -98,29 +104,35 @@ var localX = filterArea.x, localY = filterArea.y; - if (filterArea.x < 0) { + if (filterArea.x < 0) + { filterArea.width += filterArea.x; filterArea.x = 0; } - if (filterArea.y < 0) { + if (filterArea.y < 0) + { filterArea.height += filterArea.y; filterArea.y = 0; } - if (localX + filterArea.width > this.width) { + if (localX + filterArea.width > this.width) + { filterArea.width = this.width - localX; } - if (localY + filterArea.height > this.height) { + if (localY + filterArea.height > this.height) + { filterArea.height = this.height - localY; } - if (filterArea.width < 0) { + if (filterArea.width < 0) + { filterArea.width = 0; } - if (filterArea.height < 0) { + if (filterArea.height < 0) + { filterArea.height = 0; } @@ -154,7 +166,8 @@ * Removes the last filter from the filter stack and doesn't return it. * */ -WebGLFilterManager.prototype.popFilter = function () { +WebGLFilterManager.prototype.popFilter = function () +{ var gl = this.renderer.gl; var filterBlock = this.filterStack.pop(); @@ -163,7 +176,8 @@ var projection = this.renderer.projection; var offset = this.renderer.offset; - if (filterBlock.filterPasses.length > 1) { + if (filterBlock.filterPasses.length > 1) + { gl.viewport(0, 0, filterArea.width, filterArea.height); gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); @@ -193,7 +207,8 @@ var inputTexture = texture; var outputTexture = this.texturePool.pop(); - if (!outputTexture) { + if (!outputTexture) + { outputTexture = new FilterTexture(this.renderer.gl, this.width, this.height); } outputTexture.resize(this.width, this.height); @@ -204,7 +219,8 @@ gl.disable(gl.BLEND); - for (var i = 0; i < filterBlock.filterPasses.length-1; i++) { + for (var i = 0; i < filterBlock.filterPasses.length-1; i++) + { var filterPass = filterBlock.filterPasses[i]; gl.bindFramebuffer(gl.FRAMEBUFFER, outputTexture.frameBuffer ); @@ -243,10 +259,12 @@ var buffer = this.buffer; // time to render the filters texture to the previous scene - if (this.filterStack.length === 0) { + if (this.filterStack.length === 0) + { gl.colorMask(true, true, true, true);//this.transparent); } - else { + else + { var currentFilter = this.filterStack[this.filterStack.length-1]; filterArea = currentFilter._filterArea; @@ -332,13 +350,15 @@ * @param width {number} the horizontal range of the filter * @param height {number} the vertical range of the filter */ -WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) { +WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) +{ // use program var gl = this.renderer.gl; var shader = filter.shaders[gl.id]; - if (!shader) { + if (!shader) + { shader = new Shader(gl); shader.fragmentSrc = filter.fragmentSrc; @@ -356,7 +376,8 @@ gl.uniform2f(shader.projectionVector, width/2, -height/2); gl.uniform2f(shader.offsetVector, 0,0); - if (filter.uniforms.dimensions) { + 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]; @@ -386,7 +407,8 @@ * Initialises the shader buffers. * */ -WebGLFilterManager.prototype.initShaderBuffers = function () { +WebGLFilterManager.prototype.initShaderBuffers = function () +{ var gl = this.renderer.gl; // create some buffers @@ -432,7 +454,8 @@ * Destroys the filter and removes it from the filter stack. * */ -WebGLFilterManager.prototype.destroy = function () { +WebGLFilterManager.prototype.destroy = function () +{ var gl = this.renderer.gl; this.filterStack = null; @@ -441,7 +464,8 @@ this.offsetY = 0; // destroy textures - for (var i = 0; i < this.texturePool.length; i++) { + for (var i = 0; i < this.texturePool.length; i++) + { this.texturePool[i].destroy(); } diff --git a/src/core/renderers/webgl/managers/WebGLManager.js b/src/core/renderers/webgl/managers/WebGLManager.js index 9d47b5c..c30cd51 100644 --- a/src/core/renderers/webgl/managers/WebGLManager.js +++ b/src/core/renderers/webgl/managers/WebGLManager.js @@ -3,7 +3,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLManager(renderer) { +function WebGLManager(renderer) +{ /** * The renderer this manager works for. * @@ -15,6 +16,7 @@ WebGLManager.prototype.constructor = WebGLManager; module.exports = WebGLManager; -WebGLManager.prototype.destroy = function () { +WebGLManager.prototype.destroy = function () +{ this.renderer = null; }; diff --git a/src/core/renderers/webgl/managers/WebGLMaskManager.js b/src/core/renderers/webgl/managers/WebGLMaskManager.js index 2f90b64..e568812 100644 --- a/src/core/renderers/webgl/managers/WebGLMaskManager.js +++ b/src/core/renderers/webgl/managers/WebGLMaskManager.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLMaskManager(renderer) { +function WebGLMaskManager(renderer) +{ WebGLManager.call(this, renderer); } @@ -19,12 +20,15 @@ * * @param maskData {any[]} */ -WebGLMaskManager.prototype.pushMask = function (maskData) { - if (maskData.dirty) { +WebGLMaskManager.prototype.pushMask = function (maskData) +{ + if (maskData.dirty) + { WebGLGraphics.updateGraphics(maskData, this.renderer.gl); } - if (!maskData._webGL[this.renderer.gl.id].data.length) { + if (!maskData._webGL[this.renderer.gl.id].data.length) + { return; } @@ -36,6 +40,7 @@ * * @param maskData {any[]} */ -WebGLMaskManager.prototype.popMask = function (maskData) { +WebGLMaskManager.prototype.popMask = function (maskData) +{ this.renderer.stencilManager.popStencil(maskData, maskData._webGL[this.renderer.gl.id].data[0], this.renderer); }; diff --git a/src/core/renderers/webgl/managers/WebGLShaderManager.js b/src/core/renderers/webgl/managers/WebGLShaderManager.js index fef071c..90c6477 100644 --- a/src/core/renderers/webgl/managers/WebGLShaderManager.js +++ b/src/core/renderers/webgl/managers/WebGLShaderManager.js @@ -10,7 +10,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLShaderManager(renderer) { +function WebGLShaderManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -28,7 +29,8 @@ */ this.tempAttribState = []; - for (var i = 0; i < this.maxAttibs; i++) { + for (var i = 0; i < this.maxAttibs; i++) + { this.attribState[i] = false; } @@ -66,7 +68,8 @@ // listen for context and update necessary shaders var self = this; - this.renderer.on('context', function (event) { + this.renderer.on('context', function (event) + { var gl = event.data; // this shader is used for rendering primitives @@ -97,29 +100,36 @@ * * @param attribs {Array} attribs */ -WebGLShaderManager.prototype.setAttribs = function (attribs) { +WebGLShaderManager.prototype.setAttribs = function (attribs) +{ // reset temp state var i; - for (i = 0; i < this.tempAttribState.length; i++) { + for (i = 0; i < this.tempAttribState.length; i++) + { this.tempAttribState[i] = false; } // set the new attribs - for (var a in attribs) { + for (var a in attribs) + { this.tempAttribState[attribs[a]] = true; } var gl = this.renderer.gl; - for (i = 0; i < this.attribState.length; i++) { - if (this.attribState[i] !== this.tempAttribState[i]) { + for (i = 0; i < this.attribState.length; i++) + { + if (this.attribState[i] !== this.tempAttribState[i]) + { this.attribState[i] = this.tempAttribState[i]; - if (this.attribState[i]) { + if (this.attribState[i]) + { gl.enableVertexAttribArray(i); } - else { + else + { gl.disableVertexAttribArray(i); } } @@ -131,8 +141,10 @@ * * @param shader {Any} */ -WebGLShaderManager.prototype.setShader = function (shader) { - if (this._currentId === shader.uuid) { +WebGLShaderManager.prototype.setShader = function (shader) +{ + if (this._currentId === shader.uuid) + { return false; } @@ -150,7 +162,8 @@ * Destroys this object. * */ -WebGLShaderManager.prototype.destroy = function () { +WebGLShaderManager.prototype.destroy = function () +{ this.attribState = null; this.tempAttribState = null; diff --git a/src/core/renderers/webgl/managers/WebGLStencilManager.js b/src/core/renderers/webgl/managers/WebGLStencilManager.js index 9ec6398..4cb0134 100644 --- a/src/core/renderers/webgl/managers/WebGLStencilManager.js +++ b/src/core/renderers/webgl/managers/WebGLStencilManager.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLStencilManager(renderer) { +function WebGLStencilManager(renderer) +{ WebGLManager.call(this, renderer); this.stencilStack = []; @@ -24,12 +25,14 @@ * @param graphics {Graphics} * @param webGLData {any[]} */ -WebGLStencilManager.prototype.pushStencil = function (graphics, webGLData) { +WebGLStencilManager.prototype.pushStencil = function (graphics, webGLData) +{ var gl = this.renderer.gl; this.bindGraphics(graphics, webGLData, this.renderer); - if (this.stencilStack.length === 0) { + if (this.stencilStack.length === 0) + { gl.enable(gl.STENCIL_TEST); gl.clear(gl.STENCIL_BUFFER_BIT); this.reverse = true; @@ -47,14 +50,17 @@ // draw the triangle strip! - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } @@ -62,31 +68,38 @@ // draw a quad to increment.. gl.drawElements(gl.TRIANGLE_FAN, 4, gl.UNSIGNED_SHORT, ( webGLData.indices.length - 4 ) * 2 ); - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); } this.reverse = !this.reverse; } - else { - if (!this.reverse) { + else + { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } - else { + 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) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); } } @@ -103,7 +116,8 @@ * @param graphics {Graphics} * @param webGLData {Array} */ -WebGLStencilManager.prototype.bindGraphics = function (graphics, webGLData) { +WebGLStencilManager.prototype.bindGraphics = function (graphics, webGLData) +{ //if (this._currentGraphics === graphics)return; this._currentGraphics = graphics; @@ -114,7 +128,8 @@ offset = this.renderer.offset, shader;// = this.renderer.shaderManager.primitiveShader; - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { shader = this.renderer.shaderManager.complexPrimitiveShader; this.renderer.shaderManager.setShader(shader); @@ -141,7 +156,8 @@ // set the index buffer! gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, webGLData.indexBuffer); } - else { + else + { //this.renderer.shaderManager.activatePrimitiveShader(); shader = this.renderer.shaderManager.primitiveShader; this.renderer.shaderManager.setShader( shader ); @@ -154,7 +170,7 @@ gl.uniform2f(shader.uniforms.offsetVector._location, -offset.x, -offset.y); gl.uniform3fv(shader.uniforms.tint._location, utils.hex2rgb(graphics.tint)); - + gl.uniform1f(shader.uniforms.alpha._location, graphics.worldAlpha); @@ -172,19 +188,22 @@ * @param graphics {Graphics} * @param webGLData {Array} */ -WebGLStencilManager.prototype.popStencil = function (graphics, webGLData) { +WebGLStencilManager.prototype.popStencil = function (graphics, webGLData) +{ var gl = this.renderer.gl; this.stencilStack.pop(); this.count--; - if (this.stencilStack.length === 0) { + if (this.stencilStack.length === 0) + { // the stack is empty! gl.disable(gl.STENCIL_TEST); } - else { + else + { var level = this.count; @@ -192,14 +211,17 @@ gl.colorMask(false, false, false, false); - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { this.reverse = !this.reverse; - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } @@ -213,31 +235,38 @@ // draw the triangle strip! gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); - if (!this.reverse) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); } } - else { + else + { // console.log("<<>>") - if (!this.reverse) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } - else { + 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) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); } } @@ -253,7 +282,8 @@ * Destroys the mask stack. * */ -WebGLStencilManager.prototype.destroy = function () { +WebGLStencilManager.prototype.destroy = function () +{ this.renderer = null; this.stencilStack = null; }; diff --git a/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js b/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js index 913ba5e..1ea7d19 100644 --- a/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js +++ b/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function ComplexPrimitiveShader(gl) { +function ComplexPrimitiveShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -24,7 +25,8 @@ 'uniform float flipY;', 'varying vec4 vColor;', - 'void main(void) {', + '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);', @@ -37,7 +39,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = vColor;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/FastShader.js b/src/core/renderers/webgl/shaders/FastShader.js index bd2e29a..2e5e060 100644 --- a/src/core/renderers/webgl/shaders/FastShader.js +++ b/src/core/renderers/webgl/shaders/FastShader.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function FastShader(gl) { +function FastShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -28,7 +29,8 @@ 'const vec2 center = vec2(-1.0, 1.0);', - 'void main(void) {', + 'void main(void) + {', ' vec2 v;', ' vec2 sv = aVertexPosition * aScale;', ' v.x = (sv.x) * cos(aRotation) - (sv.y) * sin(aRotation);', @@ -49,7 +51,8 @@ 'uniform sampler2D uSampler;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/PrimitiveShader.js b/src/core/renderers/webgl/shaders/PrimitiveShader.js index 6f25409..a25f54f 100644 --- a/src/core/renderers/webgl/shaders/PrimitiveShader.js +++ b/src/core/renderers/webgl/shaders/PrimitiveShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function PrimitiveShader(gl) { +function PrimitiveShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -23,7 +24,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + '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);', @@ -36,7 +38,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = vColor;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/Shader.js b/src/core/renderers/webgl/shaders/Shader.js index f8964f5..fd75ef5 100644 --- a/src/core/renderers/webgl/shaders/Shader.js +++ b/src/core/renderers/webgl/shaders/Shader.js @@ -6,7 +6,8 @@ * @param [fragmentSrc] {string} The source of the fragment shader. * @param [vertexSrc] {string} The source of the vertex shader. */ -function Shader(gl, vertexSrc, fragmentSrc, customUniforms, customAttributes) { +function Shader(gl, vertexSrc, fragmentSrc, customUniforms, customAttributes) +{ /** * @member {number} * @readonly @@ -33,7 +34,8 @@ dimensions: { type: '4f', value: new Float32Array(4) } }; - for (var u in customUniforms) { + for (var u in customUniforms) + { this.uniforms[u] = customUniforms[u]; } @@ -43,7 +45,8 @@ aColor: 0 }; - for (var a in customAttributes) { + for (var a in customAttributes) + { this.attributes[a] = customAttributes[a]; } @@ -66,7 +69,8 @@ 'const vec2 center = vec2(-1.0, 1.0);', - 'void main(void) {', + 'void main(void) + {', ' gl_Position = vec4( ((aVertexPosition + offsetVector) / projectionVector) + center , 0.0, 1.0);', ' vTextureCoord = aTextureCoord;', ' vColor = vec4(aColor.rgb * aColor.a, aColor.a);', @@ -85,7 +89,8 @@ 'uniform sampler2D uSampler;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;', '}' ].join('\n'); @@ -96,7 +101,8 @@ Shader.prototype.constructor = Shader; module.exports = Shader; -Shader.prototype.init = function () { +Shader.prototype.init = function () +{ this.compile(); this.gl.useProgram(this.program); @@ -105,14 +111,18 @@ this.cacheAttributeLocations(Object.keys(this.attributes)); }; -Shader.prototype.cacheUniformLocations = function (keys) { - for (var i = 0; i < keys.length; ++i) { +Shader.prototype.cacheUniformLocations = function (keys) +{ + for (var i = 0; i < keys.length; ++i) + { this.uniforms[keys[i]]._location = this.gl.getUniformLocation(this.program, keys[i]); } }; -Shader.prototype.cacheAttributeLocations = function (keys) { - for (var i = 0; i < keys.length; ++i) { +Shader.prototype.cacheAttributeLocations = function (keys) +{ + for (var i = 0; i < keys.length; ++i) + { this.attributes[keys[i]] = this.gl.getAttribLocation(this.program, keys[i]); } @@ -124,14 +134,16 @@ // 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.attributes.aColor === -1) { + // if (this.attributes.aColor === -1) + { // this.attributes.aColor = 2; // } // End worst hack eva // }; -Shader.prototype.compile = function () { +Shader.prototype.compile = function () +{ var gl = this.gl; var glVertShader = this._glCompile(gl.VERTEX_SHADER, this.vertexSrc); @@ -144,13 +156,15 @@ gl.linkProgram(program); // if linking fails, then log and cleanup - if (!gl.getProgramParameter(program, gl.LINK_STATUS)) { + if (!gl.getProgramParameter(program, gl.LINK_STATUS)) + { window.console.error('Pixi.js Error: Could not initialize shader.'); window.console.error('gl.VALIDATE_STATUS', gl.getProgramParameter(program, gl.VALIDATE_STATUS)); window.console.error('gl.getError()', gl.getError()); // if there is a program info log, log it - if (gl.getProgramInfoLog(program) !== '') { + if (gl.getProgramInfoLog(program) !== '') + { window.console.warn('Pixi.js Warning: gl.getProgramInfoLog()', gl.getProgramInfoLog(program)); } @@ -165,18 +179,21 @@ return (this.program = program); }; -Shader.prototype.syncUniforms = function () { +Shader.prototype.syncUniforms = function () +{ var gl = this.gl; this.textureCount = 1; - for (var key in this.uniforms) { + for (var key in this.uniforms) + { var uniform = this.uniforms[key], location = uniform._location, value = uniform.value, i, il; - switch (uniform.type) { + switch (uniform.type) + { // single int value case 'i': case '1i': @@ -282,7 +299,8 @@ // a Color Value case 'c': - if (typeof value === 'number') { + if (typeof value === 'number') + { value = utils.hex2rgb(value); } @@ -311,11 +329,13 @@ // array of 2D Point objects case 'v2v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(2 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 2] = value[i].x; uniform._array[i * 2 + 1] = value[i].y; } @@ -325,11 +345,13 @@ // array of 3D Point objects case 'v3v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(3 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 3] = value[i].x; uniform._array[i * 3 + 1] = value[i].y; uniform._array[i * 3 + 2] = value[i].z; @@ -341,11 +363,13 @@ // array of 4D Point objects case 'v4v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(4 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 4] = value[i].x; uniform._array[i * 4 + 1] = value[i].y; uniform._array[i * 4 + 2] = value[i].z; @@ -359,7 +383,8 @@ // PIXI.Texture case 't': case 'sampler2D': - if (!uniform.value || !uniform.value.baseTexture || !uniform.value.baseTexture.hasLoaded) { + if (!uniform.value || !uniform.value.baseTexture || !uniform.value.baseTexture.hasLoaded) + { break; } @@ -376,7 +401,8 @@ this.textureCount++; // initialize the texture if we haven't yet - if (!uniform._init) { + if (!uniform._init) + { this.initSampler2D(uniform); uniform._init = true; @@ -394,11 +420,13 @@ * Initialises a Sampler2D uniform (which may only be available later on after initUniforms once the texture has loaded) * */ -Shader.prototype.initSampler2D = function (uniform) { +Shader.prototype.initSampler2D = function (uniform) +{ var gl = this.gl; // Extended texture data - if (uniform.textureData) { + if (uniform.textureData) + { var data = uniform.textureData; // GLTexture = mag linear, min linear_mipmap_linear, wrap repeat + gl.generateMipmap(gl.TEXTURE_2D); @@ -417,14 +445,16 @@ var wrapT = (data.wrapT) ? data.wrapT : gl.CLAMP_TO_EDGE; var format = (data.luminance) ? gl.LUMINANCE : gl.RGBA; - if (data.repeat) { + if (data.repeat) + { wrapS = gl.REPEAT; wrapT = gl.REPEAT; } gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, !!data.flipY); - if (data.width) { + if (data.width) + { var width = (data.width) ? data.width : 512; var height = (data.height) ? data.height : 2; var border = (data.border) ? data.border : 0; @@ -432,7 +462,8 @@ // 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 { + 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); } @@ -448,7 +479,8 @@ * Destroys the shader. * */ -Shader.prototype.destroy = function () { +Shader.prototype.destroy = function () +{ this.gl.deleteProgram(this.program); this.gl = null; @@ -459,13 +491,15 @@ this.fragmentSrc = null; }; -Shader.prototype._glCompile = function (type, src) { +Shader.prototype._glCompile = function (type, src) +{ var shader = this.gl.createShader(type); this.gl.shaderSource(shader, src); this.gl.compileShader(shader); - if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) { + if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) + { window.console.log(this.gl.getShaderInfoLog(shader)); return null; } diff --git a/src/core/renderers/webgl/shaders/StripShader.js b/src/core/renderers/webgl/shaders/StripShader.js index 193f6e1..a7abcc6 100644 --- a/src/core/renderers/webgl/shaders/StripShader.js +++ b/src/core/renderers/webgl/shaders/StripShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function StripShader(gl) { +function StripShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -20,7 +21,8 @@ 'varying vec2 vTextureCoord;', - 'void main(void) {', + '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);', @@ -36,7 +38,8 @@ 'varying vec2 vTextureCoord;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vec2(vTextureCoord.x, vTextureCoord.y)) * alpha;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/utils/FilterTexture.js b/src/core/renderers/webgl/utils/FilterTexture.js index d2c8423..4433d44 100644 --- a/src/core/renderers/webgl/utils/FilterTexture.js +++ b/src/core/renderers/webgl/utils/FilterTexture.js @@ -8,7 +8,8 @@ * @param height {number} the vertical range of the filter * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values */ -function FilterTexture(gl, width, height, scaleMode) { +function FilterTexture(gl, width, height, scaleMode) +{ /** * @member {WebGLContext} */ @@ -59,7 +60,8 @@ * Clears the filter texture. * */ -FilterTexture.prototype.clear = function () { +FilterTexture.prototype.clear = function () +{ var gl = this.gl; gl.clearColor(0,0,0, 0); @@ -72,8 +74,10 @@ * @param width {number} the new width of the texture * @param height {number} the new height of the texture */ -FilterTexture.prototype.resize = function (width, height) { - if (this.width === width && this.height === height) { +FilterTexture.prototype.resize = function (width, height) +{ + if (this.width === width && this.height === height) + { return; } @@ -96,7 +100,8 @@ * Destroys the filter texture. * */ -FilterTexture.prototype.destroy = function () { +FilterTexture.prototype.destroy = function () +{ var gl = this.gl; gl.deleteFramebuffer( this.frameBuffer ); gl.deleteTexture( this.texture ); diff --git a/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js b/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js index c4721e9..a63f4d7 100644 --- a/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js +++ b/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js @@ -14,7 +14,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this sprite batch works for. */ -function WebGLFastSpriteBatch(renderer) { +function WebGLFastSpriteBatch(renderer) +{ /** * The renderer instance this sprite batch operates on. * @@ -91,7 +92,8 @@ */ this.lastIndexCount = 0; - for (var i=0, j=0; i < numIndices; i += 6, j += 4) { + 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; @@ -144,7 +146,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.setupContext(); }); } @@ -157,7 +160,8 @@ * * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLFastSpriteBatch.prototype.setupContext = function () { +WebGLFastSpriteBatch.prototype.setupContext = function () +{ var gl = this.renderer.gl; // create a couple of buffers @@ -177,7 +181,8 @@ /** * @param spriteBatch {SpriteBatch} The SpriteBatch container to prepare for. */ -WebGLFastSpriteBatch.prototype.begin = function (spriteBatch) { +WebGLFastSpriteBatch.prototype.begin = function (spriteBatch) +{ this.shader = this.renderer.shaderManager.fastShader; this.matrix = spriteBatch.worldTransform.toArray(true); @@ -187,33 +192,38 @@ /** */ -WebGLFastSpriteBatch.prototype.end = function () { +WebGLFastSpriteBatch.prototype.end = function () +{ this.flush(); }; /** * @param spriteBatch {SpriteBatch} The SpriteBatch container to render. */ -WebGLFastSpriteBatch.prototype.render = function (spriteBatch) { +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) { + if (!sprite.texture._uvs) + { return; } this.currentBaseTexture = sprite.texture.baseTexture; // check blend mode - if (sprite.blendMode !== this.renderer.blendModeManager.currentBlendMode) { + if (sprite.blendMode !== this.renderer.blendModeManager.currentBlendMode) + { this.flush(); this.renderer.blendModeManager.setBlendMode(sprite.blendMode); } - for (var i=0,j= children.length; i= this.size) { + if (this.currentBatchSize >= this.size) + { this.flush(); } }; @@ -362,29 +379,35 @@ /** * */ -WebGLFastSpriteBatch.prototype.flush = function () { +WebGLFastSpriteBatch.prototype.flush = function () +{ // If the batch is length 0 then return as there is nothing to draw - if (this.currentBatchSize === 0) { + if (this.currentBatchSize === 0) + { return; } var gl = this.renderer.gl; // bind the current texture - if (!this.currentBaseTexture._glTextures[gl.id]) { + if (!this.currentBaseTexture._glTextures[gl.id]) + { this.renderer.updateTexture(this.currentBaseTexture, gl); } //TODO-SHOUD THIS BE ELSE??!?!?! - else { + else + { gl.bindTexture(gl.TEXTURE_2D, this.currentBaseTexture._glTextures[gl.id]); } // upload the verts to the buffer - if (this.currentBatchSize > ( this.size * 0.5 ) ) { + if (this.currentBatchSize > ( this.size * 0.5 ) ) + { gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); } - else { + else + { var view = this.vertices.subarray(0, this.currentBatchSize * this.vertByteSize); gl.bufferSubData(gl.ARRAY_BUFFER, 0, view); @@ -405,14 +428,16 @@ * Ends the batch and flushes * */ -WebGLFastSpriteBatch.prototype.stop = function () { +WebGLFastSpriteBatch.prototype.stop = function () +{ this.flush(); }; /** * */ -WebGLFastSpriteBatch.prototype.start = function () { +WebGLFastSpriteBatch.prototype.start = function () +{ var gl = this.renderer.gl; // bind the main texture diff --git a/src/core/renderers/webgl/utils/WebGLGraphics.js b/src/core/renderers/webgl/utils/WebGLGraphics.js index 55f4911..ab8f46e 100644 --- a/src/core/renderers/webgl/utils/WebGLGraphics.js +++ b/src/core/renderers/webgl/utils/WebGLGraphics.js @@ -19,7 +19,8 @@ * @param graphics {Graphics} * @param renderer {WebGLRenderer} */ -WebGLGraphics.renderGraphics = function (graphics, renderer) {//projection, offset) { +WebGLGraphics.renderGraphics = function (graphics, renderer) {//projection, offset) +{ var gl = renderer.gl; var projection = renderer.projection, @@ -27,7 +28,8 @@ shader = renderer.shaderManager.primitiveShader, webGLData; - if (graphics.dirty) { + if (graphics.dirty) + { WebGLGraphics.updateGraphics(graphics, gl); } @@ -35,8 +37,10 @@ // This could be speeded up for sure! - for (var i = 0; i < webGL.data.length; i++) { - if (webGL.data[i].mode === 1) { + for (var i = 0; i < webGL.data.length; i++) + { + if (webGL.data[i].mode === 1) + { webGLData = webGL.data[i]; renderer.stencilManager.pushStencil(graphics, webGLData, renderer); @@ -46,7 +50,8 @@ renderer.stencilManager.popStencil(graphics, webGLData, renderer); } - else { + else + { webGLData = webGL.data[i]; @@ -84,12 +89,14 @@ * @param graphicsData {Graphics} The graphics object to update * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLGraphics.updateGraphics = function (graphics, gl) { +WebGLGraphics.updateGraphics = function (graphics, gl) +{ // get the contexts graphics object var webGL = graphics._webGL[gl.id]; // if the graphics object does not exist in the webGL context time to create it! - if (!webGL) { + if (!webGL) + { webGL = graphics._webGL[gl.id] = {lastIndex:0, data:[], gl:gl}; } @@ -99,11 +106,13 @@ var i; // if the user cleared the graphics object we will need to clear every object - if (graphics.clearDirty) { + if (graphics.clearDirty) + { graphics.clearDirty = false; // lop through and return all the webGLDatas to the object pool so than can be reused later on - for (i = 0; i < webGL.data.length; i++) { + for (i = 0; i < webGL.data.length; i++) + { var graphicsData = webGL.data[i]; graphicsData.reset(); WebGLGraphics.graphicsDataPool.push( graphicsData ); @@ -119,58 +128,72 @@ // loop through the graphics datas and construct each one.. // if the object is a complex fill then the new stencil buffer technique will be used // other wise graphics objects will be pushed into a batch.. - for (i = webGL.lastIndex; i < graphics.graphicsData.length; i++) { + for (i = webGL.lastIndex; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { // need to add the points the the graphics object.. data.points = data.shape.points.slice(); - if (data.shape.closed) { + if (data.shape.closed) + { // close the poly if the value is true! - if (data.points[0] !== data.points[data.points.length-2] || data.points[1] !== data.points[data.points.length-1]) { + if (data.points[0] !== data.points[data.points.length-2] || data.points[1] !== data.points[data.points.length-1]) + { data.points.push(data.points[0], data.points[1]); } } // MAKE SURE WE HAVE THE CORRECT TYPE.. - if (data.fill) { - if (data.points.length >= 6) { - if (data.points.length < 6 * 2) { + if (data.fill) + { + if (data.points.length >= 6) + { + if (data.points.length < 6 * 2) + { webGLData = WebGLGraphics.switchMode(webGL, 0); var canDrawUsingSimple = WebGLGraphics.buildPoly(data, webGLData); // console.log(canDrawUsingSimple); - if (!canDrawUsingSimple) { + if (!canDrawUsingSimple) + { // console.log("<>>>") webGLData = WebGLGraphics.switchMode(webGL, 1); WebGLGraphics.buildComplexPoly(data, webGLData); } } - else { + else + { webGLData = WebGLGraphics.switchMode(webGL, 1); WebGLGraphics.buildComplexPoly(data, webGLData); } } } - if (data.lineWidth > 0) { + if (data.lineWidth > 0) + { webGLData = WebGLGraphics.switchMode(webGL, 0); WebGLGraphics.buildLine(data, webGLData); } } - else { + else + { webGLData = WebGLGraphics.switchMode(webGL, 0); - if (data.type === CONST.SHAPES.RECT) { + if (data.type === CONST.SHAPES.RECT) + { WebGLGraphics.buildRectangle(data, webGLData); } - else if (data.type === CONST.SHAPES.CIRC || data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.CIRC || data.type === CONST.SHAPES.ELIP) + { WebGLGraphics.buildCircle(data, webGLData); } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { WebGLGraphics.buildRoundedRectangle(data, webGLData); } } @@ -179,10 +202,12 @@ } // upload all the dirty data... - for (i = 0; i < webGL.data.length; i++) { + for (i = 0; i < webGL.data.length; i++) + { webGLData = webGL.data[i]; - if (webGLData.dirty) { + if (webGLData.dirty) + { webGLData.upload(); } } @@ -194,18 +219,22 @@ * @param webGL {WebGLContext} * @param type {number} */ -WebGLGraphics.switchMode = function (webGL, type) { +WebGLGraphics.switchMode = function (webGL, type) +{ var webGLData; - if (!webGL.data.length) { + if (!webGL.data.length) + { webGLData = WebGLGraphics.graphicsDataPool.pop() || new WebGLGraphicsData(webGL.gl); webGLData.mode = type; webGL.data.push(webGLData); } - else { + else + { webGLData = webGL.data[webGL.data.length-1]; - if (webGLData.mode !== type || type === 1) { + if (webGLData.mode !== type || type === 1) + { webGLData = WebGLGraphics.graphicsDataPool.pop() || new WebGLGraphicsData(webGL.gl); webGLData.mode = type; webGL.data.push(webGLData); @@ -225,7 +254,8 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildRectangle = function (graphicsData, webGLData) { +WebGLGraphics.buildRectangle = function (graphicsData, webGLData) +{ // --- // // need to convert points to a nice regular data // @@ -235,7 +265,8 @@ var width = rectData.width; var height = rectData.height; - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -265,7 +296,8 @@ indices.push(vertPos, vertPos, vertPos+1, vertPos+2, vertPos+3, vertPos+3); } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = [x, y, @@ -289,7 +321,8 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildRoundedRectangle = function (graphicsData, webGLData) { +WebGLGraphics.buildRoundedRectangle = function (graphicsData, webGLData) +{ var rrectData = graphicsData.shape; var x = rrectData.x; var y = rrectData.y; @@ -305,7 +338,8 @@ recPoints = recPoints.concat(WebGLGraphics.quadraticBezierCurve(x + width, y + radius, x + width, y, x + width - radius, y)); recPoints = recPoints.concat(WebGLGraphics.quadraticBezierCurve(x + radius, y, x, y, x, y + radius)); - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -323,7 +357,8 @@ // var i = 0; - for (i = 0; i < triangles.length; i+=3) { + for (i = 0; i < triangles.length; i+=3) + { indices.push(triangles[i] + vecPos); indices.push(triangles[i] + vecPos); indices.push(triangles[i+1] + vecPos); @@ -332,12 +367,14 @@ } - for (i = 0; i < recPoints.length; i++) { + for (i = 0; i < recPoints.length; i++) + { verts.push(recPoints[i], recPoints[++i], r, g, b, alpha); } } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = recPoints; @@ -362,7 +399,8 @@ * @param toY {number} Destination point y * @return {number[]} */ -WebGLGraphics.quadraticBezierCurve = function (fromX, fromY, cpX, cpY, toX, toY) { +WebGLGraphics.quadraticBezierCurve = function (fromX, fromY, cpX, cpY, toX, toY) +{ var xa, ya, @@ -373,14 +411,16 @@ n = 20, points = []; - function getPt(n1 , n2, perc) { + function getPt(n1 , n2, perc) + { var diff = n2 - n1; return n1 + ( diff * perc ); } var j = 0; - for (var i = 0; i <= n; i++ ) { + for (var i = 0; i <= n; i++ ) + { j = i / n; // The Green Line @@ -406,7 +446,8 @@ * @param graphicsData {Graphics} The graphics object to draw * @param webGLData {object} */ -WebGLGraphics.buildCircle = function (graphicsData, webGLData) { +WebGLGraphics.buildCircle = function (graphicsData, webGLData) +{ // need to convert points to a nice regular data var circleData = graphicsData.shape; var x = circleData.x; @@ -415,11 +456,13 @@ var height; // TODO - bit hacky?? - if (graphicsData.type === CONST.SHAPES.CIRC) { + if (graphicsData.type === CONST.SHAPES.CIRC) + { width = circleData.radius; height = circleData.radius; } - else { + else + { width = circleData.width; height = circleData.height; } @@ -429,7 +472,8 @@ var i = 0; - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -444,7 +488,8 @@ indices.push(vecPos); - for (i = 0; i < totalSegs + 1 ; i++) { + for (i = 0; i < totalSegs + 1 ; i++) + { verts.push(x,y, r, g, b, alpha); verts.push(x + Math.sin(seg * i) * width, @@ -457,12 +502,14 @@ indices.push(vecPos-1); } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = []; - for (i = 0; i < totalSegs + 1; i++) { + for (i = 0; i < totalSegs + 1; i++) + { graphicsData.points.push(x + Math.sin(seg * i) * width, y + Math.cos(seg * i) * height); } @@ -481,18 +528,22 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildLine = function (graphicsData, webGLData) { +WebGLGraphics.buildLine = function (graphicsData, webGLData) +{ // TODO OPTIMISE! var i = 0; var points = graphicsData.points; - if (points.length === 0) { + if (points.length === 0) + { return; } // if the line width is an odd number add 0.5 to align to a whole pixel - if (graphicsData.lineWidth%2) { - for (i = 0; i < points.length; i++) { + if (graphicsData.lineWidth%2) + { + for (i = 0; i < points.length; i++) + { points[i] += 0.5; } } @@ -502,7 +553,8 @@ var lastPoint = new math.Point(points[points.length - 2], points[points.length - 1]); // if the first point is the last point - gonna have issues :) - if (firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) { + if (firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) + { // need to clone as we are going to slightly modify the shape.. points = points.slice(); @@ -562,7 +614,8 @@ verts.push(p1x + perpx , p1y + perpy, r, g, b, alpha); - for (i = 1; i < length-1; i++) { + for (i = 1; i < length-1; i++) + { p1x = points[(i-1)*2]; p1y = points[(i-1)*2 + 1]; @@ -599,7 +652,8 @@ denom = a1*b2 - a2*b1; - if (Math.abs(denom) < 0.1 ) { + if (Math.abs(denom) < 0.1 ) + { denom+=10.1; verts.push(p2x - perpx , p2y - perpy, @@ -618,7 +672,8 @@ pdist = (px -p2x) * (px -p2x) + (py -p2y) + (py -p2y); - if (pdist > 140 * 140) { + if (pdist > 140 * 140) + { perp3x = perpx - perp2x; perp3y = perpy - perp2y; @@ -639,7 +694,8 @@ indexCount++; } - else { + else + { verts.push(px , py); verts.push(r, g, b, alpha); @@ -672,7 +728,8 @@ indices.push(indexStart); - for (i = 0; i < indexCount; i++) { + for (i = 0; i < indexCount; i++) + { indices.push(indexStart++); } @@ -687,11 +744,13 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildComplexPoly = function (graphicsData, webGLData) { +WebGLGraphics.buildComplexPoly = function (graphicsData, webGLData) +{ //TODO - no need to copy this as it gets turned into a FLoat32Array anyways.. var points = graphicsData.points.slice(); - if (points.length < 6) { + if (points.length < 6) + { return; } @@ -711,7 +770,8 @@ var x,y; // get size.. - for (var i = 0; i < points.length; i+=2) { + for (var i = 0; i < points.length; i+=2) + { x = points[i]; y = points[i+1]; @@ -732,7 +792,8 @@ //TODO - this aint needed! var length = points.length / 2; - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { indices.push( i ); } @@ -746,10 +807,12 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildPoly = function (graphicsData, webGLData) { +WebGLGraphics.buildPoly = function (graphicsData, webGLData) +{ var points = graphicsData.points; - if (points.length < 6) { + if (points.length < 6) + { return; } // get first and last point.. figure out the middle! @@ -767,7 +830,8 @@ var triangles = utils.PolyK.Triangulate(points); - if (!triangles) { + if (!triangles) + { return false; } @@ -775,7 +839,8 @@ var i = 0; - for (i = 0; i < triangles.length; i+=3) { + for (i = 0; i < triangles.length; i+=3) + { indices.push(triangles[i] + vertPos); indices.push(triangles[i] + vertPos); indices.push(triangles[i+1] + vertPos); @@ -783,7 +848,8 @@ indices.push(triangles[i+2] + vertPos); } - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { verts.push(points[i * 2], points[i * 2 + 1], r, g, b, alpha); } diff --git a/src/core/renderers/webgl/utils/WebGLGraphicsData.js b/src/core/renderers/webgl/utils/WebGLGraphicsData.js index c56d05e..c739ba7 100644 --- a/src/core/renderers/webgl/utils/WebGLGraphicsData.js +++ b/src/core/renderers/webgl/utils/WebGLGraphicsData.js @@ -2,7 +2,8 @@ * @class * @private */ -function WebGLGraphicsData(gl) { +function WebGLGraphicsData(gl) +{ this.gl = gl; //TODO does this need to be split before uploding?? @@ -22,7 +23,8 @@ /** * */ -WebGLGraphicsData.prototype.reset = function () { +WebGLGraphicsData.prototype.reset = function () +{ this.points.length = 0; this.indices.length = 0; }; @@ -30,7 +32,8 @@ /** * */ -WebGLGraphicsData.prototype.upload = function () { +WebGLGraphicsData.prototype.upload = function () +{ var gl = this.gl; // this.lastIndex = graphics.graphicsData.length; diff --git a/src/core/renderers/webgl/utils/WebGLSpriteBatch.js b/src/core/renderers/webgl/utils/WebGLSpriteBatch.js index 96eaa52..55befbb 100644 --- a/src/core/renderers/webgl/utils/WebGLSpriteBatch.js +++ b/src/core/renderers/webgl/utils/WebGLSpriteBatch.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this sprite batch works for. */ -function WebGLSpriteBatch(renderer) { +function WebGLSpriteBatch(renderer) +{ /** * * @@ -88,7 +89,8 @@ */ this.lastIndexCount = 0; - for (var i=0, j=0; i < numIndices; i += 6, j += 4) { + 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; @@ -162,7 +164,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.setupContext(); }); } @@ -173,7 +176,8 @@ /** * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLSpriteBatch.prototype.setupContext = function () { +WebGLSpriteBatch.prototype.setupContext = function () +{ var gl = this.renderer.gl; // setup default shader @@ -198,7 +202,8 @@ /** * */ -WebGLSpriteBatch.prototype.begin = function () { +WebGLSpriteBatch.prototype.begin = function () +{ // this.shader = this.renderer.shaderManager.defaultShader; this.start(); @@ -206,19 +211,22 @@ /** */ -WebGLSpriteBatch.prototype.end = function () { +WebGLSpriteBatch.prototype.end = function () +{ this.flush(); }; /** * @param sprite {Sprite} the sprite to render when using this spritebatch */ -WebGLSpriteBatch.prototype.render = function (sprite) { +WebGLSpriteBatch.prototype.render = function (sprite) +{ var texture = sprite.texture; //TODO set blend modes.. // check texture.. - if (this.currentBatchSize >= this.size) { + if (this.currentBatchSize >= this.size) + { this.flush(); this.currentBaseTexture = texture.baseTexture; } @@ -227,7 +235,8 @@ var uvs = texture._uvs; // if the uvs have not updated then no point rendering just yet! - if (!uvs) { + if (!uvs) + { return; } @@ -237,7 +246,8 @@ var w0, w1, h0, h1; - if (texture.trim) { + 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; @@ -248,7 +258,8 @@ h0 = h1 + texture.crop.height; } - else { + else + { w0 = (texture.frame.width ) * (1-aX); w1 = (texture.frame.width ) * -aX; @@ -272,7 +283,8 @@ var colors = this.colors; var positions = this.positions; - if (this.renderer.roundPixels) { + if (this.renderer.roundPixels) + { // xy positions[index] = a * w1 + c * h1 + tx | 0; positions[index+1] = d * h1 + b * w1 + ty | 0; @@ -289,7 +301,8 @@ positions[index+15] = a * w1 + c * h0 + tx | 0; positions[index+16] = d * h0 + b * w1 + ty | 0; } - else { + else + { // xy positions[index] = a * w1 + c * h1 + tx; positions[index+1] = d * h1 + b * w1 + ty; @@ -338,11 +351,13 @@ * * @param sprite {TilingSprite} the tilingSprite to render */ -WebGLSpriteBatch.prototype.renderTilingSprite = function (tilingSprite) { +WebGLSpriteBatch.prototype.renderTilingSprite = function (tilingSprite) +{ var texture = tilingSprite.tilingTexture; // check texture.. - if (this.currentBatchSize >= this.size) { + if (this.currentBatchSize >= this.size) + { //return; this.flush(); this.currentBaseTexture = texture.baseTexture; @@ -351,7 +366,8 @@ // set the textures uvs temporarily // TODO create a separate texture so that we can tile part of a texture - if (!tilingSprite._uvs) { + if (!tilingSprite._uvs) + { tilingSprite._uvs = new TextureUvs(); } @@ -454,16 +470,19 @@ * Renders the content and empties the current batch. * */ -WebGLSpriteBatch.prototype.flush = function () { +WebGLSpriteBatch.prototype.flush = function () +{ // If the batch is length 0 then return as there is nothing to draw - if (this.currentBatchSize === 0) { + if (this.currentBatchSize === 0) + { return; } var gl = this.renderer.gl; var shader; - if (this.dirty) { + if (this.dirty) + { this.dirty = false; // bind the main texture gl.activeTexture(gl.TEXTURE0); @@ -482,10 +501,12 @@ } // upload the verts to the buffer - if (this.currentBatchSize > ( this.size * 0.5 ) ) { + if (this.currentBatchSize > ( this.size * 0.5 ) ) + { gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); } - else { + else + { var view = this.positions.subarray(0, this.currentBatchSize * this.vertByteSize); gl.bufferSubData(gl.ARRAY_BUFFER, 0, view); } @@ -502,7 +523,8 @@ var shaderSwap = false; var sprite; - for (var i = 0, j = this.currentBatchSize; i < j; i++) { + for (var i = 0, j = this.currentBatchSize; i < j; i++) + { sprite = this.sprites[i]; @@ -513,24 +535,28 @@ blendSwap = currentBlendMode !== nextBlendMode; shaderSwap = currentShader !== nextShader; // should I use uuidS??? - if (currentBaseTexture !== nextTexture || blendSwap || shaderSwap) { + if (currentBaseTexture !== nextTexture || blendSwap || shaderSwap) + { this.renderBatch(currentBaseTexture, batchSize, start); start = i; batchSize = 0; currentBaseTexture = nextTexture; - if (blendSwap) { + if (blendSwap) + { currentBlendMode = nextBlendMode; this.renderer.blendModeManager.setBlendMode( currentBlendMode ); } - if (shaderSwap) { + if (shaderSwap) + { currentShader = nextShader; shader = currentShader.shaders ? currentShader.shaders[gl.id] : currentShader; - if (!shader) { + if (!shader) + { shader = new Shader(gl, null, currentShader.fragmentSrc, currentShader.uniforms); currentShader.shaders[gl.id] = shader; } @@ -538,7 +564,8 @@ // set shader function??? this.renderer.shaderManager.setShader(shader); - if (shader.dirty) { + if (shader.dirty) + { shader.syncUniforms(); } @@ -569,17 +596,21 @@ * @param size {number} * @param startIndex {number} */ -WebGLSpriteBatch.prototype.renderBatch = function (texture, size, startIndex) { - if (size === 0) { +WebGLSpriteBatch.prototype.renderBatch = function (texture, size, startIndex) +{ + if (size === 0) + { return; } var gl = this.renderer.gl; - if (!texture._glTextures[gl.id]) { + if (!texture._glTextures[gl.id]) + { this.renderer.updateTexture(texture); } - else { + else + { // bind the current texture gl.bindTexture(gl.TEXTURE_2D, texture._glTextures[gl.id]); } @@ -594,7 +625,8 @@ /** * */ -WebGLSpriteBatch.prototype.stop = function () { +WebGLSpriteBatch.prototype.stop = function () +{ this.flush(); this.dirty = true; }; @@ -602,7 +634,8 @@ /** * */ -WebGLSpriteBatch.prototype.start = function () { +WebGLSpriteBatch.prototype.start = function () +{ this.dirty = true; }; @@ -610,7 +643,8 @@ * Destroys the SpriteBatch. * */ -WebGLSpriteBatch.prototype.destroy = function () { +WebGLSpriteBatch.prototype.destroy = function () +{ this.renderer.gl.deleteBuffer(this.vertexBuffer); this.renderer.gl.deleteBuffer(this.indexBuffer); diff --git a/src/core/textures/BaseTexture.js b/src/core/textures/BaseTexture.js index 2bf77d4..513d358 100644 --- a/src/core/textures/BaseTexture.js +++ b/src/core/textures/BaseTexture.js @@ -10,7 +10,8 @@ * @param source {Image|Canvas} the source object of the texture. * @param [scaleMode=scaleModes.DEFAULT] {number} See {@link scaleModes} for possible values */ -function BaseTexture(source, scaleMode) { +function BaseTexture(source, scaleMode) +{ this.uuid = utils.uuid(); /** @@ -123,7 +124,8 @@ this._needsUpdate = false; // if no source passed don't try to load - if (source) { + if (source) + { this.loadSource(source); } @@ -149,13 +151,16 @@ Object.defineProperties(BaseTexture.prototype, { needsUpdate: { - get: function () { + get: function () + { return this._needsUpdate; }, - set: function (val) { + set: function (val) + { this._needsUpdate = val; - if (val) { + if (val) + { this.emit('update', this); } } @@ -171,9 +176,11 @@ * * The logic state after calling `loadSource` directly or indirectly (eg. `fromImage`, `new BaseTexture`) is: * - * if (texture.hasLoaded) { + * if (texture.hasLoaded) + { * // texture ready for use - * } else if (texture.isLoading) { + * } else if (texture.isLoading) + { * // listen to 'loaded' and/or 'error' events on texture * } else { * // not loading, not going to load UNLESS the source is reloaded @@ -183,12 +190,14 @@ * @protected * @param source {Image|Canvas} the source object of the texture. */ -BaseTexture.prototype.loadSource = function (source) { +BaseTexture.prototype.loadSource = function (source) +{ var wasLoading = this.isLoading; this.hasLoaded = false; this.isLoading = false; - if (wasLoading && this.source) { + if (wasLoading && this.source) + { this.source.onload = null; this.source.onerror = null; } @@ -196,20 +205,24 @@ this.source = source; // Apply source if loaded. Otherwise setup appropriate loading monitors. - if ((this.source.complete || this.source.getContext) && this.source.width && this.source.height) { + if ((this.source.complete || this.source.getContext) && this.source.width && this.source.height) + { this._sourceLoaded(); } - else if(!source.getContext) { + else if(!source.getContext) + { // Image fail / not ready this.isLoading = true; var scope = this; - source.onload = function () { + source.onload = function () + { source.onload = null; source.onerror = null; - if(!scope.isLoading) { + if(!scope.isLoading) + { return; } @@ -219,11 +232,13 @@ scope.emit('loaded', scope); }; - source.onerror = function () { + source.onerror = function () + { source.onload = null; source.onerror = null; - if(!scope.isLoading) { + if(!scope.isLoading) + { return; } @@ -234,24 +249,29 @@ // Per http://www.w3.org/TR/html5/embedded-content-0.html#the-img-element // "The value of `complete` can thus change while a script is executing." // So complete needs to be re-checked after the callbacks have been added.. - if (source.complete) { + if (source.complete) + { this.isLoading = false; // ..and if we're complete now, no need for callbacks source.onload = null; source.onerror = null; - if (source.width && source.height) { + if (source.width && source.height) + { this._sourceLoaded(); // If any previous subscribers possible - if (wasLoading) { + if (wasLoading) + { this.emit('loaded', this); } } - else { + else + { // If any previous subscribers possible - if (wasLoading) { + if (wasLoading) + { this.emit('error', this); } } @@ -265,7 +285,8 @@ * * @private */ -BaseTexture.prototype._sourceLoaded = function () { +BaseTexture.prototype._sourceLoaded = function () +{ this.hasLoaded = true; this.width = this.source.naturalWidth || this.source.width; @@ -278,16 +299,20 @@ * Destroys this base texture * */ -BaseTexture.prototype.destroy = function () { - if (this.imageUrl) { +BaseTexture.prototype.destroy = function () +{ + if (this.imageUrl) + { delete utils.BaseTextureCache[this.imageUrl]; delete utils.TextureCache[this.imageUrl]; this.imageUrl = null; - if (!navigator.isCocoonJS) { + if (!navigator.isCocoonJS) + { this.source.src = ''; } } - else if (this.source && this.source._pixiId) { + else if (this.source && this.source._pixiId) + { delete utils.BaseTextureCache[this.source._pixiId]; } this.source = null; @@ -301,7 +326,8 @@ * memory again. * */ -BaseTexture.prototype.dispose = function () { +BaseTexture.prototype.dispose = function () +{ this.emit('dispose', this); }; @@ -311,7 +337,8 @@ * * @param newSrc {string} the path of the image */ -BaseTexture.prototype.updateSourceImage = function (newSrc) { +BaseTexture.prototype.updateSourceImage = function (newSrc) +{ this.source.src = newSrc; this.loadSource(this.source); }; @@ -326,18 +353,22 @@ * @param [scaleMode=scaleModes.DEFAULT] {number} See {@link scaleModes} for possible values * @return BaseTexture */ -BaseTexture.fromImage = function (imageUrl, crossorigin, scaleMode) { +BaseTexture.fromImage = function (imageUrl, crossorigin, scaleMode) +{ var baseTexture = utils.BaseTextureCache[imageUrl]; - if (crossorigin === undefined && imageUrl.indexOf('data:') !== 0) { + if (crossorigin === undefined && imageUrl.indexOf('data:') !== 0) + { crossorigin = true; } - if (!baseTexture) { + if (!baseTexture) + { // new Image() breaks tex loading in some versions of Chrome. // See https://code.google.com/p/chromium/issues/detail?id=238071 var image = new Image();//document.createElement('img'); - if (crossorigin) { + if (crossorigin) + { image.crossOrigin = ''; } @@ -347,7 +378,8 @@ utils.BaseTextureCache[imageUrl] = baseTexture; // if there is an @2x at the end of the url we are going to assume its a highres image - if ( imageUrl.indexOf(CONST.RETINA_PREFIX + '.') !== -1) { + if ( imageUrl.indexOf(CONST.RETINA_PREFIX + '.') !== -1) + { baseTexture.resolution = 2; } } @@ -363,14 +395,17 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return BaseTexture */ -BaseTexture.fromCanvas = function (canvas, scaleMode) { - if (!canvas._pixiId) { +BaseTexture.fromCanvas = function (canvas, scaleMode) +{ + if (!canvas._pixiId) + { canvas._pixiId = 'canvas_' + utils.uuid(); } var baseTexture = utils.BaseTextureCache[canvas._pixiId]; - if (!baseTexture) { + if (!baseTexture) + { baseTexture = new BaseTexture(canvas, scaleMode); utils.BaseTextureCache[canvas._pixiId] = baseTexture; } diff --git a/src/core/textures/RenderTexture.js b/src/core/textures/RenderTexture.js index 6dad20f..53ae796 100644 --- a/src/core/textures/RenderTexture.js +++ b/src/core/textures/RenderTexture.js @@ -46,8 +46,10 @@ * @param [scaleMode] {number} See {@link scaleModes} for possible values * @param [resolution=1] {number} The resolution of the texture being generated */ -function RenderTexture(renderer, width, height, scaleMode, resolution) { - if (!renderer) { +function RenderTexture(renderer, width, height, scaleMode, resolution) +{ + if (!renderer) + { throw new Error('Unable to create RenderTexture, you must pass a renderer into the constructor.'); } @@ -133,7 +135,8 @@ */ this.renderer = renderer; - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { var gl = this.renderer.gl; this.textureBuffer = new FilterTexture(gl, this.width * this.resolution, this.height * this.resolution, this.baseTexture.scaleMode); @@ -142,7 +145,8 @@ this.render = this.renderWebGL; this.projection = new math.Point(this.width*0.5, -this.height*0.5); } - else { + else + { this.render = this.renderCanvas; this.textureBuffer = new CanvasBuffer(this.width* this.resolution, this.height* this.resolution); this.baseTexture.source = this.textureBuffer.canvas; @@ -167,8 +171,10 @@ * @param height {number} The height to resize to. * @param updateBase {boolean} Should the baseTexture.width and height values be resized as well? */ -RenderTexture.prototype.resize = function (width, height, updateBase) { - if (width === this.width && height === this.height) { +RenderTexture.prototype.resize = function (width, height, updateBase) +{ + if (width === this.width && height === this.height) + { return; } @@ -177,17 +183,20 @@ this.width = this.frame.width = this.crop.width = width; this.height = this.frame.height = this.crop.height = height; - if (updateBase) { + if (updateBase) + { this.baseTexture.width = this.width; this.baseTexture.height = this.height; } - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { this.projection.x = this.width / 2; this.projection.y = -this.height / 2; } - if (!this.valid) { + if (!this.valid) + { return; } @@ -198,12 +207,15 @@ * Clears the RenderTexture. * */ -RenderTexture.prototype.clear = function () { - if (!this.valid) { +RenderTexture.prototype.clear = function () +{ + if (!this.valid) + { return; } - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { this.renderer.gl.bindFramebuffer(this.renderer.gl.FRAMEBUFFER, this.textureBuffer.frameBuffer); } @@ -220,19 +232,23 @@ * @param [restoreWorldTransform=true] {boolean} If true the displayObject's worldTransform/worldAlpha and all children * transformations will be restored. Not restoring this information will be a little faster. */ -RenderTexture.prototype.renderWebGL = function (displayObject, matrix, clear, restoreWorldTransform) { - if (!this.valid) { +RenderTexture.prototype.renderWebGL = function (displayObject, matrix, clear, restoreWorldTransform) +{ + if (!this.valid) + { return; } - if (typeof restoreWorldTransform === 'undefined') { + if (typeof restoreWorldTransform === 'undefined') + { restoreWorldTransform = true; } var tempAlpha, tempTransform; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { tempAlpha = displayObject.worldAlpha; tempTransform = displayObject.worldTransform.toArray(); } @@ -245,7 +261,8 @@ wt.identity(); wt.translate(0, this.projection.y * 2); - if (matrix) { + if (matrix) + { wt.append(matrix); } @@ -258,7 +275,8 @@ var children = displayObject.children; var i, j; - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } @@ -269,7 +287,8 @@ gl.bindFramebuffer(gl.FRAMEBUFFER, this.textureBuffer.frameBuffer ); - if (clear) { + if (clear) + { this.textureBuffer.clear(); } @@ -279,11 +298,13 @@ this.renderer.spriteBatch.dirty = true; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { displayObject.worldAlpha = tempAlpha; displayObject.worldTransform.fromArray(tempTransform); - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } } @@ -300,26 +321,31 @@ * @param [restoreWorldTransform=true] {boolean} If true the displayObject's worldTransform/worldAlpha and all children * transformations will be restored. Not restoring this information will be a little faster. */ -RenderTexture.prototype.renderCanvas = function (displayObject, matrix, clear, restoreWorldTransform) { - if (!this.valid) { +RenderTexture.prototype.renderCanvas = function (displayObject, matrix, clear, restoreWorldTransform) +{ + if (!this.valid) + { return; } - if (typeof restoreWorldTransform === 'undefined') { + if (typeof restoreWorldTransform === 'undefined') + { restoreWorldTransform = true; } var tempAlpha, tempTransform; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { tempAlpha = displayObject.worldAlpha; tempTransform = displayObject.worldTransform.toArray(); } var wt = displayObject.worldTransform; wt.identity(); - if (matrix) { + if (matrix) + { wt.append(matrix); } @@ -330,11 +356,13 @@ var children = displayObject.children; var i, j; - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } - if (clear) { + if (clear) + { this.textureBuffer.clear(); } @@ -348,11 +376,13 @@ this.renderer.resolution = realResolution; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { displayObject.worldAlpha = tempAlpha; displayObject.worldTransform.fromArray(tempTransform); - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } } @@ -363,7 +393,8 @@ * * @return {Image} */ -RenderTexture.prototype.getImage = function () { +RenderTexture.prototype.getImage = function () +{ var image = new Image(); image.src = this.getBase64(); return image; @@ -374,7 +405,8 @@ * * @return {string} A base64 encoded string of the texture. */ -RenderTexture.prototype.getBase64 = function () { +RenderTexture.prototype.getBase64 = function () +{ return this.getCanvas().toDataURL(); }; @@ -383,8 +415,10 @@ * * @return {HTMLCanvasElement} A Canvas element with the texture rendered on. */ -RenderTexture.prototype.getCanvas = function () { - if (this.renderer.type === CONST.WEBGL_RENDERER) { +RenderTexture.prototype.getCanvas = function () +{ + if (this.renderer.type === CONST.WEBGL_RENDERER) + { var gl = this.renderer.gl; var width = this.textureBuffer.width; var height = this.textureBuffer.height; @@ -403,7 +437,8 @@ return tempCanvas.canvas; } - else { + else + { return this.textureBuffer.canvas; } }; diff --git a/src/core/textures/Texture.js b/src/core/textures/Texture.js index 3c65909..e97f0aa 100644 --- a/src/core/textures/Texture.js +++ b/src/core/textures/Texture.js @@ -17,7 +17,8 @@ * @param [crop] {Rectangle} The area of original texture * @param [trim] {Rectangle} Trimmed texture rectangle */ -function Texture(baseTexture, frame, crop, trim) { +function Texture(baseTexture, frame, crop, trim) +{ /** * Does this Texture have any frame data assigned to it? * @@ -25,12 +26,14 @@ */ this.noFrame = false; - if (!frame) { + if (!frame) + { this.noFrame = true; frame = new math.Rectangle(0, 0, 1, 1); } - if (baseTexture instanceof Texture) { + if (baseTexture instanceof Texture) + { baseTexture = baseTexture.baseTexture; } @@ -100,13 +103,16 @@ */ this.crop = crop || new math.Rectangle(0, 0, 1, 1); - if (baseTexture.hasLoaded) { - if (this.noFrame) { + if (baseTexture.hasLoaded) + { + if (this.noFrame) + { frame = new math.Rectangle(0, 0, baseTexture.width, baseTexture.height); } this.frame = frame; } - else { + else + { baseTexture.addEventListener('loaded', this.onBaseTextureLoaded.bind(this)); } } @@ -118,19 +124,23 @@ Object.defineProperties(Texture.prototype, { needsUpdate: { - get: function () { + get: function () + { return this.baseTexture.needsUpdate; }, - set: function (val) { + set: function (val) + { this.baseTexture.needsUpdate = val; } }, frame: { - get: function () { + get: function () + { return this._frame; }, - set: function (frame) { + set: function (frame) + { this._frame = frame; this.noFrame = false; @@ -143,20 +153,23 @@ 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 (!this.trim && (frame.x + frame.width > this.baseTexture.width || frame.y + frame.height > this.baseTexture.height)) + { throw new Error('Texture Error: frame does not fit inside the base Texture dimensions ' + this); } this.valid = frame && frame.width && frame.height && this.baseTexture.source && this.baseTexture.hasLoaded; - if (this.trim) { + 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) { + if (this.valid) + { this._updateUvs(); } } @@ -168,11 +181,13 @@ * * @private */ -Texture.prototype.onBaseTextureLoaded = function () { +Texture.prototype.onBaseTextureLoaded = function () +{ var baseTexture = this.baseTexture; baseTexture.removeEventListener('loaded', this.onLoaded); - if (this.noFrame) { + if (this.noFrame) + { this.frame = new math.Rectangle(0, 0, baseTexture.width, baseTexture.height); } @@ -184,8 +199,10 @@ * * @param destroyBase {boolean} Whether to destroy the base texture as well */ -Texture.prototype.destroy = function (destroyBase) { - if (destroyBase) { +Texture.prototype.destroy = function (destroyBase) +{ + if (destroyBase) + { this.baseTexture.destroy(); } @@ -197,8 +214,10 @@ * * @private */ -Texture.prototype._updateUvs = function () { - if (!this._uvs) { +Texture.prototype._updateUvs = function () +{ + if (!this._uvs) + { this._uvs = new TextureUvs(); } @@ -229,10 +248,12 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return Texture */ -Texture.fromImage = function (imageUrl, crossorigin, scaleMode) { +Texture.fromImage = function (imageUrl, crossorigin, scaleMode) +{ var texture = utils.TextureCache[imageUrl]; - if (!texture) { + if (!texture) + { texture = new Texture(BaseTexture.fromImage(imageUrl, crossorigin, scaleMode)); utils.TextureCache[imageUrl] = texture; } @@ -248,9 +269,11 @@ * @param frameId {string} The frame id of the texture * @return Texture */ -Texture.fromFrame = function (frameId) { +Texture.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache '); } return texture; @@ -264,7 +287,8 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return {Texture} */ -Texture.fromCanvas = function (canvas, scaleMode) { +Texture.fromCanvas = function (canvas, scaleMode) +{ return new Texture(BaseTexture.fromCanvas(canvas, scaleMode)); }; @@ -276,7 +300,8 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return {Texture} A Texture */ -Texture.fromVideo = function (video, scaleMode) { +Texture.fromVideo = function (video, scaleMode) +{ return new Texture(VideoBaseTexture.baseTextureFromVideo(video, scaleMode)); }; @@ -287,7 +312,8 @@ * @param texture {Texture} The Texture to add to the cache. * @param id {string} The id that the texture will be stored against. */ -Texture.addTextureToCache = function (texture, id) { +Texture.addTextureToCache = function (texture, id) +{ utils.TextureCache[id] = texture; }; @@ -298,7 +324,8 @@ * @param id {string} The id of the texture to be removed * @return {Texture} The texture that was removed */ -Texture.removeTextureFromCache = function (id) { +Texture.removeTextureFromCache = function (id) +{ var texture = utils.TextureCache[id]; delete utils.TextureCache[id]; diff --git a/src/core/textures/TextureUvs.js b/src/core/textures/TextureUvs.js index b9bbb58..5424d52 100644 --- a/src/core/textures/TextureUvs.js +++ b/src/core/textures/TextureUvs.js @@ -1,4 +1,5 @@ -function TextureUvs() { +function TextureUvs() +{ this.x0 = 0; this.y0 = 0; diff --git a/src/core/textures/VideoBaseTexture.js b/src/core/textures/VideoBaseTexture.js index e3e0c5a..1a826a9 100644 --- a/src/core/textures/VideoBaseTexture.js +++ b/src/core/textures/VideoBaseTexture.js @@ -12,15 +12,18 @@ * @param source {HTMLVideoElement} * @param [scaleMode] {number} See {@link scaleModes} for possible values */ -function VideoBaseTexture(source, scaleMode) { - if (!source){ +function VideoBaseTexture(source, scaleMode) +{ + if (!source) + { throw new Error('No video source element specified.'); } // hook in here to check if video is already available. // BaseTexture looks for a source.complete boolean, plus width & height. - if ((source.readyState === source.HAVE_ENOUGH_DATA || source.readyState === source.HAVE_FUTURE_DATA) && source.width && source.height) { + if ((source.readyState === source.HAVE_ENOUGH_DATA || source.readyState === source.HAVE_FUTURE_DATA) && source.width && source.height) + { source.complete = true; } @@ -31,7 +34,8 @@ this._boundOnUpdate = this._onUpdate.bind(this); this._boundOnCanPlay = this._onCanPlay.bind(this); - if (!source.complete) { + if (!source.complete) + { source.addEventListener('canplay', this._boundOnCanPlay); source.addEventListener('canplaythrough', this._boundOnCanPlay); @@ -47,28 +51,35 @@ VideoBaseTexture.prototype.constructor = VideoBaseTexture; module.exports = VideoBaseTexture; -VideoBaseTexture.prototype._onUpdate = function () { - if (this.autoUpdate) { +VideoBaseTexture.prototype._onUpdate = function () +{ + if (this.autoUpdate) + { window.requestAnimationFrame(this._boundOnUpdate); this.needsUpdate = true; } }; -VideoBaseTexture.prototype._onPlayStart = function () { - if (!this.autoUpdate) { +VideoBaseTexture.prototype._onPlayStart = function () +{ + if (!this.autoUpdate) + { window.requestAnimationFrame(this._boundOnUpdate); this.autoUpdate = true; } }; -VideoBaseTexture.prototype._onPlayStop = function () { +VideoBaseTexture.prototype._onPlayStop = function () +{ this.autoUpdate = false; }; -VideoBaseTexture.prototype._onCanPlay = function () { +VideoBaseTexture.prototype._onCanPlay = function () +{ this.hasLoaded = true; - if (this.source) { + if (this.source) + { this.source.removeEventListener('canplay', this._boundOnCanPlay); this.source.removeEventListener('canplaythrough', this._boundOnCanPlay); @@ -78,15 +89,18 @@ this.source.play(); // prevent multiple loaded dispatches.. - if(!this.__loaded){ + if(!this.__loaded) + { this.__loaded = true; this.emit('loaded', this); } } }; -VideoBaseTexture.prototype.destroy = function () { - if (this.source && this.source._pixiId) { +VideoBaseTexture.prototype.destroy = function () +{ + if (this.source && this.source._pixiId) + { utils.BaseTextureCache[ this.source._pixiId ] = null; delete utils.BaseTextureCache[ this.source._pixiId ]; @@ -105,14 +119,17 @@ * @param scaleMode {number} See {@link scaleModes} for possible values * @return {VideoBaseTexture} */ -VideoBaseTexture.fromVideo = function (video, scaleMode) { - if (!video._pixiId) { +VideoBaseTexture.fromVideo = function (video, scaleMode) +{ + if (!video._pixiId) + { video._pixiId = 'video_' + utils.uuid(); } var baseTexture = utils.BaseTextureCache[video._pixiId]; - if (!baseTexture) { + if (!baseTexture) + { baseTexture = new VideoBaseTexture(video, scaleMode); utils.BaseTextureCache[ video._pixiId ] = baseTexture; } @@ -147,17 +164,21 @@ * @param scaleMode {number} See {@link scaleModes} for possible values * @return {VideoBaseTexture} */ -VideoBaseTexture.fromUrl = function (videoSrc, scaleMode) { +VideoBaseTexture.fromUrl = function (videoSrc, scaleMode) +{ var video = document.createElement('video'); // array of objects or strings - if (Array.isArray(videoSrc)) { - for (var i = 0; i < videoSrc.length; ++i) { + if (Array.isArray(videoSrc)) + { + for (var i = 0; i < videoSrc.length; ++i) + { video.appendChild(createSource(videoSrc.src || videoSrc, videoSrc.mime)); } } // single object or string - else { + else + { video.appendChild(createSource(videoSrc.src || videoSrc, videoSrc.mime)); } @@ -169,8 +190,10 @@ VideoBaseTexture.fromUrls = VideoBaseTexture.fromUrl; -function createSource(path, type) { - if (!type) { +function createSource(path, type) +{ + if (!type) + { type = 'video/' + path.substr(path.lastIndexOf('.') + 1); } diff --git a/src/core/utils/EventData.js b/src/core/utils/EventData.js index 5d55a22..8cdf701 100644 --- a/src/core/utils/EventData.js +++ b/src/core/utils/EventData.js @@ -7,7 +7,8 @@ * @param name {string} The string name of the event that was triggered * @param data {object} Arbitrary event data to pass along */ -function EventData(target, name, data) { +function EventData(target, name, data) +{ // for duck typing in the ".on()" function this.__isEventObject = true; @@ -71,7 +72,8 @@ * Stops the propagation of events up the scene graph (prevents bubbling). * */ -EventData.prototype.stopPropagation = function stopPropagation() { +EventData.prototype.stopPropagation = function stopPropagation() +{ this.stopped = true; }; @@ -79,6 +81,7 @@ * Stops the propagation of events to sibling listeners (no longer calls any listeners). * */ -EventData.prototype.stopImmediatePropagation = function stopImmediatePropagation() { +EventData.prototype.stopImmediatePropagation = function stopImmediatePropagation() +{ this.stoppedImmediate = true; }; diff --git a/src/core/utils/EventTarget.js b/src/core/utils/EventTarget.js index 7ae8820..671a151 100644 --- a/src/core/utils/EventTarget.js +++ b/src/core/utils/EventTarget.js @@ -13,14 +13,16 @@ * var em = new MyEmitter(); * em.emit('eventName', 'some data', 'some more data', {}, null, ...); */ -function eventTarget(obj) { +function eventTarget(obj) +{ /** * Return a list of assigned event listeners. * * @param eventName {string} The events that should be listed. * @return {Array} An array of listener functions */ - obj.listeners = function listeners(eventName) { + obj.listeners = function listeners(eventName) + { this._listeners = this._listeners || {}; return this._listeners[eventName] ? this._listeners[eventName].slice() : []; @@ -33,22 +35,26 @@ * @param eventName {string} The name of the event. * @return {boolean} Indication if we've emitted an event. */ - obj.emit = obj.dispatchEvent = function emit(eventName, data) { + obj.emit = obj.dispatchEvent = function emit(eventName, data) + { this._listeners = this._listeners || {}; // fast return when there are no listeners - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return; } //backwards compat with old method ".emit({ type: 'something' })" - if (typeof eventName === 'object') { + if (typeof eventName === 'object') + { data = eventName; eventName = eventName.type; } //ensure we are using a real pixi event - if (!data || data.__isEventObject !== true) { + if (!data || data.__isEventObject !== true) + { data = new EventData(this, eventName, data); } @@ -58,23 +64,27 @@ fn = listeners[0], i; - for (i = 0; i < length; fn = listeners[++i]) { + for (i = 0; i < length; fn = listeners[++i]) + { //call the event listener fn.call(this, data); //if "stopImmediatePropagation" is called, stop calling sibling events - if (data.stoppedImmediate) { + if (data.stoppedImmediate) + { return this; } } //if "stopPropagation" is called then don't bubble the event - if (data.stopped) { + if (data.stopped) + { return this; } //bubble this event up the scene graph - if (this.parent && this.parent.emit) { + if (this.parent && this.parent.emit) + { this.parent.emit.call(this.parent, eventName, data); } @@ -88,7 +98,8 @@ * @param eventName {string} Name of the event. * @param callback {Functon} fn Callback function. */ - obj.on = obj.addEventListener = function on(eventName, fn) { + obj.on = obj.addEventListener = function on(eventName, fn) + { this._listeners = this._listeners || {}; (this._listeners[eventName] = this._listeners[eventName] || []) @@ -103,11 +114,13 @@ * @param eventName {string} Name of the event. * @param callback {Function} Callback function. */ - obj.once = function once(eventName, fn) { + obj.once = function once(eventName, fn) + { this._listeners = this._listeners || {}; var self = this; - function onceHandlerWrapper() { + function onceHandlerWrapper() + { fn.apply(self.off(eventName, onceHandlerWrapper), arguments); } onceHandlerWrapper._originalHandler = fn; @@ -122,23 +135,28 @@ * @param eventName {string} The event we want to remove. * @param callback {Function} The listener that we need to find. */ - obj.off = obj.removeEventListener = function off(eventName, fn) { + obj.off = obj.removeEventListener = function off(eventName, fn) + { this._listeners = this._listeners || {}; - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return this; } var list = this._listeners[eventName], i = fn ? list.length : 0; - while(i-- > 0) { - if (list[i] === fn || list[i]._originalHandler === fn) { + while(i-- > 0) + { + if (list[i] === fn || list[i]._originalHandler === fn) + { list.splice(i, 1); } } - if (list.length === 0) { + if (list.length === 0) + { delete this._listeners[eventName]; } @@ -150,10 +168,12 @@ * * @param eventName {string} The event you want to remove all listeners for. */ - obj.removeAllListeners = function removeAllListeners(eventName) { + obj.removeAllListeners = function removeAllListeners(eventName) + { this._listeners = this._listeners || {}; - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return this; } @@ -169,7 +189,8 @@ * * @param object {object} The obj to mix into */ - mixin: function mixin(obj) { + mixin: function mixin(obj) + { eventTarget(obj); } }; diff --git a/src/core/utils/PolyK.js b/src/core/utils/PolyK.js index 7325141..5e20c2b 100644 --- a/src/core/utils/PolyK.js +++ b/src/core/utils/PolyK.js @@ -47,7 +47,8 @@ * Triangulates shapes for webGL graphic fills. * */ -PolyK.Triangulate = function (p) { +PolyK.Triangulate = function (p) +{ var sign = true; var n = p.length >> 1; @@ -59,7 +60,8 @@ i = 0; var al = n; - while(al > 3) { + while(al > 3) + { var i0 = avl[(i+0)%al]; var i1 = avl[(i+1)%al]; var i2 = avl[(i+2)%al]; @@ -69,29 +71,35 @@ var cx = p[2*i2], cy = p[2*i2+1]; var earFound = false; - if (PolyK._convex(ax, ay, bx, by, cx, cy, sign)) { + if (PolyK._convex(ax, ay, bx, by, cx, cy, sign)) + { earFound = true; - for (var j = 0; j < al; j++) { + for (var j = 0; j < al; j++) + { var vi = avl[j]; if (vi === i0 || vi === i1 || vi === i2) continue; - if (PolyK._PointInTriangle(p[2*vi], p[2*vi+1], ax, ay, bx, by, cx, cy)) { + if (PolyK._PointInTriangle(p[2*vi], p[2*vi+1], ax, ay, bx, by, cx, cy)) + { earFound = false; break; } } } - if (earFound) { + if (earFound) + { tgs.push(i0, i1, i2); avl.splice((i+1)%al, 1); al--; i = 0; } - else if (i++ > 3*al) { + else if (i++ > 3*al) + { // need to flip flip reverse it! // reset! - if (sign) { + if (sign) + { tgs = []; avl = []; for (i = 0; i < n; i++) avl.push(i); @@ -101,7 +109,8 @@ sign = false; } - else { + else + { // window.console.log("PIXI Warning: shape too complex to fill"); return null; } @@ -126,7 +135,8 @@ * @private * @return {boolean} */ -PolyK._PointInTriangle = function (px, py, ax, ay, bx, by, cx, cy) { +PolyK._PointInTriangle = function (px, py, ax, ay, bx, by, cx, cy) +{ var v0x = cx-ax; var v0y = cy-ay; var v1x = bx-ax; @@ -154,6 +164,7 @@ * @private * @return {boolean} */ -PolyK._convex = function (ax, ay, bx, by, cx, cy, sign) { +PolyK._convex = function (ax, ay, bx, by, cx, cy, sign) +{ return ((ay-by)*(cx-bx) + (bx-ax)*(cy-by) >= 0) === sign; }; diff --git a/src/core/utils/index.js b/src/core/utils/index.js index ade9831..bfae7ae 100644 --- a/src/core/utils/index.js +++ b/src/core/utils/index.js @@ -16,7 +16,8 @@ * * @return {number} The next uuid to use. */ - uuid: function () { + uuid: function () + { return ++utils._uid; }, @@ -26,7 +27,8 @@ * @param hex {number} * @return {number[]} An array representing the [R, G, B] of the color. */ - hex2rgb: function (hex, out) { + hex2rgb: function (hex, out) + { out = out || []; out[0] = (hex >> 16 & 0xFF) / 255; @@ -42,7 +44,8 @@ * @param hex {number} * @return {string} The string color. */ - hex2string: function (hex) { + hex2string: function (hex) + { hex = hex.toString(16); hex = '000000'.substr(0, 6 - hex.length) + hex; @@ -55,7 +58,8 @@ * @param rgb {number[]} * @return {number} The color number */ - rgb2hex: function (rgb) { + rgb2hex: function (rgb) + { return ((rgb[0]*255 << 16) + (rgb[1]*255 << 8) + rgb[2]*255); }, @@ -64,8 +68,10 @@ * * @return {boolean} whether they are supported */ - canUseNewCanvasBlendModes: function () { - if (typeof document === 'undefined') { + canUseNewCanvasBlendModes: function () + { + if (typeof document === 'undefined') + { return false; } @@ -93,15 +99,19 @@ * @param number {number} * @return {number} the closest number that is a power of two */ - getNextPowerOfTwo: function (number) { + getNextPowerOfTwo: function (number) + { // see: http://en.wikipedia.org/wiki/Power_of_two#Fast_algorithm_to_check_if_a_positive_number_is_a_power_of_two - if (number > 0 && (number & (number - 1)) === 0) { + if (number > 0 && (number & (number - 1)) === 0) + { return number; } - else { + else + { var result = 1; - while (result < number) { + while (result < number) + { result <<= 1; } @@ -116,7 +126,8 @@ * @param height {number} * @return {boolean} */ - isPowerOfTwo: function (width, height) { + isPowerOfTwo: function (width, height) + { return (width > 0 && (width & (width - 1)) === 0 && height > 0 && (height & (height - 1)) === 0); }, @@ -130,12 +141,15 @@ * @constant * @static */ - sayHello: function (type) { - if (utils._saidHello) { + sayHello: function (type) + { + if (utils._saidHello) + { return; } - if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) { + if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) + { var args = [ '%c %c %c Pixi.js ' + CONST.VERSION + ' - ' + type + ' %c ' + ' %c ' + ' http://www.pixijs.com/ %c %c ♥%c♥%c♥ ', 'background: #ff66a5', @@ -151,7 +165,8 @@ console.log.apply(console, args); //jshint ignore:line } - else if (window.console) { + else if (window.console) + { console.log('Pixi.js ' + CONST.VERSION + ' - ' + type + ' - http://www.pixijs.com/'); //jshint ignore:line } @@ -166,15 +181,19 @@ * @class * @namespace PIXI */ - AjaxRequest: function () { + AjaxRequest: function () + { var activexmodes = ['Msxml2.XMLHTTP.6.0', 'Msxml2.XMLHTTP.3.0', 'Microsoft.XMLHTTP']; //activeX versions to check for in IE - if (window.ActiveXObject) { //Test for support for ActiveXObject in IE first (as XMLHttpRequest in IE7 is broken) - for (var i=0; i= this.textures.length) { + else if (round >= this.textures.length) + { this.gotoAndStop(this.textures.length - 1); - if (this.onComplete) { + if (this.onComplete) + { this.onComplete(); } } @@ -167,10 +182,12 @@ * @static * @param frames {string[]} the array of frames ids the movieclip will use as its texture frames */ -MovieClip.fromFrames = function (frames) { +MovieClip.fromFrames = function (frames) +{ var textures = []; - for (var i = 0; i < frames.length; ++i) { + for (var i = 0; i < frames.length; ++i) + { textures.push(new core.Texture.fromFrame(frames[i])); } @@ -183,10 +200,12 @@ * @static * @param images {string[]} the array of image urls the movieclip will use as its texture frames */ -MovieClip.fromImages = function (images) { +MovieClip.fromImages = function (images) +{ var textures = []; - for (var i = 0; i < images.length; ++i) { + for (var i = 0; i < images.length; ++i) + { textures.push(new core.Texture.fromImage(images[i])); } diff --git a/src/extras/Rope.js b/src/extras/Rope.js index c157ec4..9c87bc0 100644 --- a/src/extras/Rope.js +++ b/src/extras/Rope.js @@ -9,7 +9,8 @@ * @param {Array} points - An array of {Point}. * */ -function Rope(texture, points) { +function Rope(texture, points) +{ Strip.call(this, texture); this.points = points; @@ -31,10 +32,12 @@ * Refreshes * */ -Rope.prototype.refresh = function () { +Rope.prototype.refresh = function () +{ var points = this.points; - if (points.length < 1) { + if (points.length < 1) + { return; } @@ -59,20 +62,23 @@ var total = points.length, point, index, amount; - for (var i = 1; i < total; i++) { + for (var i = 1; i < total; i++) + { point = points[i]; index = i * 4; // time to do some smart drawing! amount = i / (total-1); - if (i%2) { + if (i%2) + { uvs[index] = amount; uvs[index+1] = 0; uvs[index+2] = amount; uvs[index+3] = 1; } - else { + else + { uvs[index] = amount; uvs[index+1] = 0; @@ -95,10 +101,12 @@ * * @private */ -Rope.prototype.updateTransform = function () { +Rope.prototype.updateTransform = function () +{ var points = this.points; - if (points.length < 1) { + if (points.length < 1) + { return; } @@ -113,14 +121,17 @@ var total = points.length, point, index, ratio, perpLength, num; - for (var i = 0; i < total; i++) { + for (var i = 0; i < total; i++) + { point = points[i]; index = i * 4; - if (i < points.length-1) { + if (i < points.length-1) + { nextPoint = points[i+1]; } - else { + else + { nextPoint = point; } @@ -129,7 +140,8 @@ ratio = (1 - (i / (total-1))) * 10; - if (ratio > 1) { + if (ratio > 1) + { ratio = 1; } @@ -157,7 +169,8 @@ * * @param texture {Texture} the texture that will be used */ -Rope.prototype.setTexture = function (texture) { +Rope.prototype.setTexture = function (texture) +{ // stop current texture this.texture = texture; //this.updateFrame = true; diff --git a/src/extras/Strip.js b/src/extras/Strip.js index c5e378f..57691b5 100644 --- a/src/extras/Strip.js +++ b/src/extras/Strip.js @@ -10,7 +10,8 @@ * @param height {number} the height * */ -function Strip(texture) { +function Strip(texture) +{ core.DisplayObjectContainer.call(this); /** @@ -70,9 +71,11 @@ * * @param renderer {WebGLRenderer} */ -Strip.prototype.renderWebGL = function (renderer) { +Strip.prototype.renderWebGL = function (renderer) +{ // if the sprite is not visible or the alpha is 0 then no need to render this element - if (!this.visible || this.alpha <= 0) { + if (!this.visible || this.alpha <= 0) + { return; } @@ -81,7 +84,8 @@ renderer.spriteBatch.stop(); // init! init! - if (!this._vertexBuffer) { + if (!this._vertexBuffer) + { this._initWebGL(renderer); } @@ -96,7 +100,8 @@ //TODO check culling }; -Strip.prototype._initWebGL = function (renderer) { +Strip.prototype._initWebGL = function (renderer) +{ // build the strip! var gl = renderer.gl; @@ -118,7 +123,8 @@ gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this.indices, gl.STATIC_DRAW); }; -Strip.prototype._renderStrip = function (renderer) { +Strip.prototype._renderStrip = function (renderer) +{ var gl = renderer.gl; var projection = renderer.projection, offset = renderer.offset, @@ -137,7 +143,8 @@ gl.uniform2f(shader.offsetVector, -offset.x, -offset.y); gl.uniform1f(shader.alpha, this.worldAlpha); - if (!this.dirty) { + if (!this.dirty) + { gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexBuffer); gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); @@ -150,10 +157,12 @@ gl.activeTexture(gl.TEXTURE0); // check if a texture is dirty.. - if (this.texture.baseTexture._dirty[gl.id]) { + if (this.texture.baseTexture._dirty[gl.id]) + { renderer.updateTexture(this.texture.baseTexture); } - else { + else + { // bind the current texture gl.bindTexture(gl.TEXTURE_2D, this.texture.baseTexture._glTextures[gl.id]); } @@ -163,7 +172,8 @@ } - else { + else + { this.dirty = false; gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexBuffer); @@ -178,10 +188,12 @@ gl.activeTexture(gl.TEXTURE0); // check if a texture is dirty.. - if (this.texture.baseTexture._dirty[gl.id]) { + if (this.texture.baseTexture._dirty[gl.id]) + { renderer.updateTexture(this.texture.baseTexture); } - else { + else + { gl.bindTexture(gl.TEXTURE_2D, this.texture.baseTexture._glTextures[gl.id]); } @@ -203,27 +215,33 @@ * * @param renderer {CanvasRenderer} */ -Strip.prototype.renderCanvas = function (renderer) { +Strip.prototype.renderCanvas = function (renderer) +{ var context = renderer.context; var transform = this.worldTransform; - if (renderer.roundPixels) { + if (renderer.roundPixels) + { context.setTransform(transform.a, transform.b, transform.c, transform.d, transform.tx | 0, transform.ty | 0); } - else { + else + { context.setTransform(transform.a, transform.b, transform.c, transform.d, transform.tx, transform.ty); } - if (this.drawMode === Strip.DrawModes.TRIANGLE_STRIP) { + if (this.drawMode === Strip.DrawModes.TRIANGLE_STRIP) + { this._renderCanvasTriangleStrip(context); } - else { + else + { this._renderCanvasTriangles(context); } }; -Strip.prototype._renderCanvasTriangleStrip = function (context) { +Strip.prototype._renderCanvasTriangleStrip = function (context) +{ // draw triangles!! var vertices = this.vertices; var uvs = this.uvs; @@ -231,14 +249,16 @@ var length = vertices.length / 2; // this.count++; - for (var i = 0; i < length - 2; i++) { + for (var i = 0; i < length - 2; i++) + { // draw some triangles! var index = i * 2; this._renderCanvasDrawTriangle(context, vertices, uvs, index, (index + 2), (index + 4)); } }; -Strip.prototype._renderCanvasTriangles = function (context) { +Strip.prototype._renderCanvasTriangles = function (context) +{ // draw triangles!! var vertices = this.vertices; var uvs = this.uvs; @@ -247,14 +267,16 @@ var length = indices.length; // this.count++; - for (var i = 0; i < length; i += 3) { + for (var i = 0; i < length; i += 3) + { // draw some triangles! var index0 = indices[i] * 2, index1 = indices[i + 1] * 2, index2 = indices[i + 2] * 2; this._renderCanvasDrawTriangle(context, vertices, uvs, index0, index1, index2); } }; -Strip.prototype._renderCanvasDrawTriangle = function (context, vertices, uvs, index0, index1, index2) { +Strip.prototype._renderCanvasDrawTriangle = function (context, vertices, uvs, index0, index1, index2) +{ var textureSource = this.texture.baseTexture.source; var textureWidth = this.texture.width; var textureHeight = this.texture.height; @@ -265,7 +287,8 @@ var u0 = uvs[index0] * textureWidth, u1 = uvs[index1] * textureWidth, u2 = uvs[index2] * textureWidth; var v0 = uvs[index0 + 1] * textureHeight, v1 = uvs[index1 + 1] * textureHeight, v2 = uvs[index2 + 1] * textureHeight; - if (this.canvasPadding > 0) { + if (this.canvasPadding > 0) + { var paddingX = this.canvasPadding / this.worldTransform.a; var paddingY = this.canvasPadding / this.worldTransform.d; var centerX = (x0 + x1 + x2) / 3; @@ -332,7 +355,8 @@ * @param strip {Strip} The Strip to render * @private */ -Strip.prototype.renderStripFlat = function (strip) { +Strip.prototype.renderStripFlat = function (strip) +{ var context = this.context; var vertices = strip.vertices; @@ -340,7 +364,8 @@ // this.count++; context.beginPath(); - for (var i=1; i < length-2; i++) { + for (var i=1; i < length-2; i++) + { // draw some triangles! var index = i*2; @@ -358,7 +383,8 @@ }; /* -Strip.prototype.setTexture = function (texture) { +Strip.prototype.setTexture = function (texture) +{ //TODO SET THE TEXTURES //TODO VISIBILITY @@ -377,7 +403,8 @@ * @private */ -Strip.prototype.onTextureUpdate = function () { +Strip.prototype.onTextureUpdate = function () +{ this.updateFrame = true; }; @@ -387,7 +414,8 @@ * @param matrix {Matrix} the transformation matrix of the sprite * @return {Rectangle} the framing rectangle */ -Strip.prototype.getBounds = function (matrix) { +Strip.prototype.getBounds = function (matrix) +{ var worldTransform = matrix || this.worldTransform; var a = worldTransform.a; @@ -404,7 +432,8 @@ var minY = Infinity; var vertices = this.vertices; - for (var i = 0, n = vertices.length; i < n; i += 2) { + for (var i = 0, n = vertices.length; i < n; i += 2) + { var rawX = vertices[i], rawY = vertices[i + 1]; var x = (a * rawX) + (c * rawY) + tx; var y = (d * rawY) + (b * rawX) + ty; @@ -416,7 +445,8 @@ maxY = y > maxY ? y : maxY; } - if (minX === -Infinity || maxY === Infinity) { + if (minX === -Infinity || maxY === Infinity) + { return core.math.Rectangle.EMPTY; } diff --git a/src/extras/TilingSprite.js b/src/extras/TilingSprite.js index 3ac22df..31da393 100644 --- a/src/extras/TilingSprite.js +++ b/src/extras/TilingSprite.js @@ -10,7 +10,8 @@ * @param width {number} the width of the tiling sprite * @param height {number} the height of the tiling sprite */ -function TilingSprite(texture, width, height) { +function TilingSprite(texture, width, height) +{ core.Sprite.call( this, texture); /** @@ -86,10 +87,12 @@ * @memberof TilingSprite# */ width: { - get: function () { + get: function () + { return this._width; }, - set: function (value) { + set: function (value) + { this._width = value; } }, @@ -101,20 +104,25 @@ * @memberof TilingSprite# */ height: { - get: function () { + get: function () + { return this._height; }, - set: function (value) { + set: function (value) + { this._height = value; } }, texture: { - get: function () { + get: function () + { return this._texture; }, - set: function (value) { - if (this._texture === value) { + set: function (value) + { + if (this._texture === value) + { return; } @@ -130,51 +138,61 @@ * * @param renderer {WebGLRenderer} */ -TilingSprite.prototype.renderWebGL = function (renderer) { - if (!this.visible || this.alpha <= 0) { +TilingSprite.prototype.renderWebGL = function (renderer) +{ + if (!this.visible || this.alpha <= 0) + { return; } var i, j; - if (this._mask) { + if (this._mask) + { renderer.spriteBatch.stop(); renderer.maskManager.pushMask(this.mask, renderer); renderer.spriteBatch.start(); } - if (this._filters) { + if (this._filters) + { renderer.spriteBatch.flush(); renderer.filterManager.pushFilter(this._filterBlock); } - if (!this.tilingTexture || this.refreshTexture) { + if (!this.tilingTexture || this.refreshTexture) + { this.generateTilingTexture(true); - if (this.tilingTexture && this.tilingTexture.needsUpdate) { + if (this.tilingTexture && this.tilingTexture.needsUpdate) + { //TODO - tweaking renderer.updateTexture(this.tilingTexture.baseTexture); this.tilingTexture.needsUpdate = false; // this.tilingTexture._uvs = null; } } - else { + else + { renderer.spriteBatch.renderTilingSprite(this); } // simple render children! - for (i=0,j=this.children.length; i= 0 && index <= this.children.length) { - if (child.parent) { + if (index >= 0 && index <= this.children.length) + { + if (child.parent) + { child.parent.removeChild(child); } @@ -154,7 +173,8 @@ return child; } - else { + else + { throw new Error(child + 'addChildAt: The index '+ index +' supplied is out of bounds ' + this.children.length); } }; @@ -165,15 +185,18 @@ * @param child {DisplayObject} * @param child2 {DisplayObject} */ -DisplayObjectContainer.prototype.swapChildren = function (child, child2) { - if (child === child2) { +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) { + if (index1 < 0 || index2 < 0) + { throw new Error('swapChildren: Both the supplied DisplayObjects must be a child of the caller.'); } @@ -187,10 +210,12 @@ * @param child {DisplayObject} The DisplayObject instance to identify * @return {Number} The index position of the child display object to identify */ -DisplayObjectContainer.prototype.getChildIndex = function (child) { +DisplayObjectContainer.prototype.getChildIndex = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { throw new Error('The supplied DisplayObject must be a child of the caller'); } @@ -203,8 +228,10 @@ * @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 */ -DisplayObjectContainer.prototype.setChildIndex = function (child, index) { - if (index < 0 || index >= this.children.length) { +DisplayObjectContainer.prototype.setChildIndex = function (child, index) +{ + if (index < 0 || index >= this.children.length) + { throw new Error('The supplied index is out of bounds'); } @@ -220,8 +247,10 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child at the given index, if any. */ -DisplayObjectContainer.prototype.getChildAt = function (index) { - if (index < 0 || index >= this.children.length) { +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'); } @@ -234,10 +263,12 @@ * @param child {DisplayObject} The DisplayObject to remove * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChild = function (child) { +DisplayObjectContainer.prototype.removeChild = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { return; } @@ -250,7 +281,8 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChildAt = function (index) { +DisplayObjectContainer.prototype.removeChildAt = function (index) +{ var child = this.getChildAt(index); child.parent = null; @@ -265,24 +297,29 @@ * @param beginIndex {Number} The beginning position. Default value is 0. * @param endIndex {Number} The ending position. Default value is size of the container. */ -DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) { +DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) +{ var begin = beginIndex || 0; var end = typeof endIndex === 'number' ? endIndex : this.children.length; var range = end - begin; - if (range > 0 && range <= end) { + if (range > 0 && range <= end) + { var removed = this.children.splice(begin, range); - for (var i = 0; i < removed.length; ++i) { + for (var i = 0; i < removed.length; ++i) + { removed[i].parent = null; } return removed; } - else if (range === 0 && this.children.length === 0) { + else if (range === 0 && this.children.length === 0) + { return []; } - else { + else + { throw new RangeError('removeChildren: numeric values are outside the acceptable range.'); } }; @@ -291,7 +328,8 @@ * Generates and updates the cached sprite for this object. * */ -DisplayObjectContainer.prototype.updateCachedSprite = function () { +DisplayObjectContainer.prototype.updateCachedSprite = function () +{ this._generateCachedSprite(); }; @@ -304,7 +342,8 @@ * @param renderer {CanvasRenderer|WebGLRenderer} The renderer used to generate the texture. * @return {Texture} a texture of the graphics object */ -DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) { +DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) +{ var bounds = this.getLocalBounds(); var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0, renderer, scaleMode, resolution); @@ -322,18 +361,22 @@ * * @private */ -DisplayObjectContainer.prototype.updateTransform = function () { - if (!this.visible) { +DisplayObjectContainer.prototype.updateTransform = function () +{ + if (!this.visible) + { return; } this.displayObjectUpdateTransform(); - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { return; } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } }; @@ -346,8 +389,10 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getBounds = function () { - if (this.children.length === 0) { +DisplayObjectContainer.prototype.getBounds = function () +{ + if (this.children.length === 0) + { return math.Rectangle.EMPTY; } @@ -365,10 +410,12 @@ var childVisible = false; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -386,7 +433,8 @@ maxY = maxY > childMaxY ? maxY : childMaxY; } - if (!childVisible) { + if (!childVisible) + { return math.Rectangle.EMPTY; } @@ -407,12 +455,14 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getLocalBounds = function () { +DisplayObjectContainer.prototype.getLocalBounds = function () +{ var matrixCache = this.worldTransform; this.worldTransform = math.Matrix.IDENTITY; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } @@ -428,13 +478,16 @@ * * @param renderer {WebGLRenderer} The renderer */ -DisplayObjectContainer.prototype.renderWebGL = function (renderer) { +DisplayObjectContainer.prototype.renderWebGL = function (renderer) +{ // if the object is not visible or the alpha is 0 then no need to render this element - if (!this.visible || this.alpha <= 0) { + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } @@ -442,14 +495,17 @@ var i, j; // do a quick check to see if this element has a mask or a filter. - if (this._mask || this._filters) { + if (this._mask || this._filters) + { // push filter first as we need to ensure the stencil buffer is correct for any masking - if (this._filters) { + if (this._filters) + { renderer.spriteBatch.flush(); renderer.filterManager.pushFilter(this._filterBlock); } - if (this._mask) { + if (this._mask) + { renderer.spriteBatch.stop(); renderer.maskManager.pushMask(this.mask, renderer); renderer.spriteBatch.start(); @@ -459,36 +515,42 @@ this._renderWebGL(renderer); // now loop through the children and make sure they get rendered - for (i = 0, j = this.children.length; i < j; i++) { + for (i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderWebGL(renderer); } // time to stop the sprite batch as either a mask element or a filter draw will happen next renderer.spriteBatch.stop(); - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(this._mask, renderer); } - if (this._filters) { + if (this._filters) + { renderer.filterManager.popFilter(); } renderer.spriteBatch.start(); } - else { + else + { this._renderWebGL(renderer); // simple render children! - for (i = 0, j = this.children.length; i < j; ++i) { + for (i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderWebGL(renderer); } } }; -DisplayObjectContainer.prototype._renderWebGL = function (renderer) { +DisplayObjectContainer.prototype._renderWebGL = function (renderer) +{ // this is where content itself gets renderd.. @@ -499,25 +561,31 @@ * * @param renderer {CanvasRenderer} The renderer */ -DisplayObjectContainer.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0) { +DisplayObjectContainer.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -528,13 +596,16 @@ * @param renderer {WebGLRenderer|CanvasRenderer} The renderer * @private */ -DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) { +DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) +{ this._cachedSprite.worldAlpha = this.worldAlpha; - if (renderer.gl) { + if (renderer.gl) + { this._cachedSprite.renderWebGL(renderer); } - else { + else + { this._cachedSprite.renderCanvas(renderer); } }; @@ -544,10 +615,12 @@ * * @private */ -DisplayObjectContainer.prototype._generateCachedSprite = function () { +DisplayObjectContainer.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { // TODO - RenderTexture now *requires* a renderer instance, so this is like broken // because `renderer` isn't actually in scope here :P var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0); @@ -555,7 +628,8 @@ this._cachedSprite = new Sprite(renderTexture); this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.texture.resize(bounds.width | 0, bounds.height | 0); } @@ -580,8 +654,10 @@ * * @private */ -DisplayObjectContainer.prototype._destroyCachedSprite = function () { - if (!this._cachedSprite) { +DisplayObjectContainer.prototype._destroyCachedSprite = function () +{ + if (!this._cachedSprite) + { return; } diff --git a/src/core/display/Sprite.js b/src/core/display/Sprite.js index 707da24..5862aef 100644 --- a/src/core/display/Sprite.js +++ b/src/core/display/Sprite.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param texture {Texture} The texture for this sprite */ -function Sprite(texture) { +function Sprite(texture) +{ DisplayObjectContainer.call(this); /** @@ -85,12 +86,14 @@ this.texture = texture || Texture.EMPTY; } -Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) { +Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) +{ DisplayObjectContainer.prototype.destroy.call(this); this.anchor = null; - if (destroyTexture) { + if (destroyTexture) + { this._texture.destroy(destroyBaseTexture); } @@ -111,10 +114,12 @@ * @memberof Sprite# */ width: { - get: function () { + get: function () + { return this.scale.x * this.texture.frame.width; }, - set: function (value) { + set: function (value) + { this.scale.x = value / this.texture.frame.width; this._width = value; } @@ -127,10 +132,12 @@ * @memberof Sprite# */ height: { - get: function () { + get: function () + { return this.scale.y * this.texture.frame.height; }, - set: function (value) { + set: function (value) + { this.scale.y = value / this.texture.frame.height; this._height = value; } @@ -143,23 +150,29 @@ * @memberof Sprite# */ texture: { - get: function () { + get: function () + { return this._texture; }, - set: function (value) { - if (this._texture === value) { + set: function (value) + { + if (this._texture === value) + { return; } this._texture = value; this.cachedTint = 0xFFFFFF; - if (value) { + if (value) + { // wait for the texture to load - if (value.baseTexture.hasLoaded) { + if (value.baseTexture.hasLoaded) + { this._onTextureUpdate(); } - else { + else + { value.once('update', this._onTextureUpdate.bind(this)); } } @@ -172,18 +185,22 @@ * * @private */ -Sprite.prototype._onTextureUpdate = function () { +Sprite.prototype._onTextureUpdate = function () +{ // so if _width is 0 then width was not set.. - if (this._width) { + if (this._width) + { this.scale.x = this._width / this.texture.frame.width; } - if (this._height) { + if (this._height) + { this.scale.y = this._height / this.texture.frame.height; } }; -Sprite.prototype._renderWebGL = function (renderer) { +Sprite.prototype._renderWebGL = function (renderer) +{ // this is where content gets renderd.. // watch this space for a little render state manager.. @@ -197,7 +214,8 @@ * @param matrix {Matrix} the transformation matrix of the sprite * @return {Rectangle} the framing rectangle */ -Sprite.prototype.getBounds = function (matrix) { +Sprite.prototype.getBounds = function (matrix) +{ var width = this.texture.frame.width; var height = this.texture.frame.height; @@ -224,11 +242,13 @@ if(b === 0 && c === 0) { // scale may be negative! - if (a < 0) { + if (a < 0) + { a *= -1; } - if (d < 0) { + if (d < 0) + { d *= -1; } @@ -293,28 +313,34 @@ * * @param renderer {CanvasRenderer} The renderer */ -Sprite.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) { +Sprite.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) + { return; } - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; renderer.context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } // Ignore null sources - if (this.texture.valid) { + if (this.texture.valid) + { var resolution = this.texture.baseTexture.resolution / renderer.resolution; renderer.context.globalAlpha = this.worldAlpha; // If smoothingEnabled is supported and we need to change the smoothing property for this texture - if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) { + if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) + { renderer.scaleMode = this.texture.baseTexture.scaleMode; renderer.context[renderer.smoothProperty] = (renderer.scaleMode === CONST.scaleModes.LINEAR); } @@ -324,7 +350,8 @@ var dy = (this.texture.trim ? this.texture.trim.y : 0) - (this.anchor.y * this.texture.trim.height); // Allow for pixel rounding - if (renderer.roundPixels) { + if (renderer.roundPixels) + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -337,7 +364,8 @@ dx = dx | 0; dy = dy | 0; } - else { + else + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -348,8 +376,10 @@ ); } - if (this.tint !== 0xFFFFFF) { - if (this.cachedTint !== this.tint) { + if (this.tint !== 0xFFFFFF) + { + if (this.cachedTint !== this.tint) + { this.cachedTint = this.tint; // TODO clean up caching - how to clean up the caches? @@ -368,7 +398,8 @@ this.texture.crop.height / resolution ); } - else { + else + { renderer.context.drawImage( this.texture.baseTexture.source, this.texture.crop.x, @@ -383,11 +414,13 @@ } } - for (var i = 0, j = this.children.length; i < j; i++) { + for (var i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -402,10 +435,12 @@ * @param frameId {String} The frame Id of the texture in the cache * @return {Sprite} A new Sprite using a texture from the texture cache matching the frameId */ -Sprite.fromFrame = function (frameId) { +Sprite.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache' + this); } @@ -420,6 +455,7 @@ * @param imageId {String} The image url of the texture * @return {Sprite} A new Sprite using a texture from the texture cache matching the image id */ -Sprite.fromImage = function (imageId, crossorigin, scaleMode) { +Sprite.fromImage = function (imageId, crossorigin, scaleMode) +{ return new Sprite(Texture.fromImage(imageId, crossorigin, scaleMode)); }; diff --git a/src/core/display/SpriteBatch.js b/src/core/display/SpriteBatch.js index 3187777..c196fef 100644 --- a/src/core/display/SpriteBatch.js +++ b/src/core/display/SpriteBatch.js @@ -12,7 +12,8 @@ * ```js * var container = new SpriteBatch(); * - * for(var i = 0; i < 100; ++i) { + * for(var i = 0; i < 100; ++i) + * { * var sprite = new PIXI.Sprite.fromImage("myImage.png"); * container.addChild(sprite); * } @@ -25,7 +26,8 @@ */ //TODO RENAME to PARTICLE CONTAINER? -function SpriteBatch() { +function SpriteBatch() +{ DisplayObjectContainer.call(this); } @@ -38,7 +40,8 @@ * * @private */ -SpriteBatch.prototype.updateTransform = function () { +SpriteBatch.prototype.updateTransform = function () +{ // TODO don't need to! this.displayObjectUpdateTransform(); // PIXI.DisplayObjectContainer.prototype.updateTransform.call( this ); @@ -50,8 +53,10 @@ * @param renderer {WebGLRenderer} The webgl renderer * @private */ -SpriteBatch.prototype.renderWebGL = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderWebGL = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -71,8 +76,10 @@ * @param renderer {CanvasRenderer} The canvas renderer * @private */ -SpriteBatch.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -84,10 +91,12 @@ this.displayObjectUpdateTransform(); - for (var i = 0; i < this.children.length; ++i) { + for (var i = 0; i < this.children.length; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -95,9 +104,11 @@ context.globalAlpha = this.worldAlpha * child.alpha; - if (child.rotation % (Math.PI * 2) === 0) { + if (child.rotation % (Math.PI * 2) === 0) + { // this is the fastest way to optimise! - if rotation is 0 then we can avoid any kind of setTransform call - if (isRotated) { + if (isRotated) + { context.setTransform( transform.a, transform.b, @@ -122,8 +133,10 @@ frame.height * child.scale.y ); } - else { - if (!isRotated) { + else + { + if (!isRotated) + { isRotated = true; } @@ -131,7 +144,8 @@ var childTransform = child.worldTransform; - if (renderer.roundPixels) { + if (renderer.roundPixels) + { context.setTransform( childTransform.a, childTransform.b, @@ -141,7 +155,8 @@ childTransform.ty | 0 ); } - else { + else + { context.setTransform( childTransform.a, childTransform.b, diff --git a/src/core/index.js b/src/core/index.js index 3954b6f..eb4a82b 100644 --- a/src/core/index.js +++ b/src/core/index.js @@ -58,11 +58,13 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRenderer: function (width, height, options, noWebGL) { + autoDetectRenderer: function (width, height, options, noWebGL) + { width = width || 800; height = height || 600; - if (!noWebGL && require('webgl-enabled')()) { + if (!noWebGL && require('webgl-enabled')()) + { return new core.WebGLRenderer(width, height, options); } @@ -87,7 +89,8 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRecommendedRenderer: function (width, height, options) { + autoDetectRecommendedRenderer: function (width, height, options) + { var isAndroid = /Android/i.test(navigator.userAgent); return core.autoDetectRenderer(width, height, options, isAndroid); diff --git a/src/core/math/Matrix.js b/src/core/math/Matrix.js index c2f87e2..2ff4848 100644 --- a/src/core/math/Matrix.js +++ b/src/core/math/Matrix.js @@ -10,7 +10,8 @@ * @class * @namespace PIXI */ -function Matrix() { +function Matrix() +{ /** * @member {number} * @default 1 @@ -63,7 +64,8 @@ * * @param array {number[]} The array that the matrix will be populated from. */ -Matrix.prototype.fromArray = function (array) { +Matrix.prototype.fromArray = function (array) +{ this.a = array[0]; this.b = array[1]; this.c = array[3]; @@ -78,14 +80,17 @@ * @param transpose {boolean} Whether we need to transpose the matrix or not * @return {number[]} the newly created array which contains the matrix */ -Matrix.prototype.toArray = function (transpose) { - if (!this.array) { +Matrix.prototype.toArray = function (transpose) +{ + if (!this.array) + { this.array = new Float32Array(9); } var array = this.array; - if (transpose) { + if (transpose) + { array[0] = this.a; array[1] = this.b; array[2] = 0; @@ -96,7 +101,8 @@ array[7] = this.ty; array[8] = 1; } - else { + else + { array[0] = this.a; array[1] = this.c; array[2] = this.tx; @@ -119,7 +125,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, transformed through this matrix */ -Matrix.prototype.apply = function (pos, newPos) { +Matrix.prototype.apply = function (pos, newPos) +{ newPos = newPos || new Point(); newPos.x = this.a * pos.x + this.c * pos.y + this.tx; @@ -136,7 +143,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, inverse-transformed through this matrix */ -Matrix.prototype.applyInverse = function (pos, newPos) { +Matrix.prototype.applyInverse = function (pos, newPos) +{ newPos = newPos || new Point(); var id = 1 / (this.a * this.d + this.c * -this.b); @@ -154,7 +162,8 @@ * @param {number} y * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.translate = function (x, y) { +Matrix.prototype.translate = function (x, y) +{ this.tx += x; this.ty += y; @@ -168,7 +177,8 @@ * @param {number} y The amount to scale vertically * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.scale = function (x, y) { +Matrix.prototype.scale = function (x, y) +{ this.a *= x; this.d *= y; this.c *= x; @@ -186,7 +196,8 @@ * @param {number} angle - The angle in radians. * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.rotate = function (angle) { +Matrix.prototype.rotate = function (angle) +{ var cos = Math.cos( angle ); var sin = Math.sin( angle ); @@ -210,7 +221,8 @@ * @param {Matrix} matrix * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.append = function (matrix) { +Matrix.prototype.append = function (matrix) +{ var a1 = this.a; var b1 = this.b; var c1 = this.c; @@ -232,7 +244,8 @@ * * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.identity = function () { +Matrix.prototype.identity = function () +{ this.a = 1; this.b = 0; this.c = 0; diff --git a/src/core/math/Point.js b/src/core/math/Point.js index 7565b2d..632f346 100644 --- a/src/core/math/Point.js +++ b/src/core/math/Point.js @@ -7,7 +7,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -function Point(x, y) { +function Point(x, y) +{ /** * @member {number} * @default 0 @@ -29,7 +30,8 @@ * * @return {Point} a copy of the point */ -Point.prototype.clone = function () { +Point.prototype.clone = function () +{ return new Point(this.x, this.y); }; @@ -40,7 +42,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -Point.prototype.set = function (x, y) { +Point.prototype.set = function (x, y) +{ this.x = x || 0; this.y = y || ( (y !== 0) ? this.x : 0 ) ; }; diff --git a/src/core/math/shapes/Circle.js b/src/core/math/shapes/Circle.js index 69cfdc9..4d76efc 100644 --- a/src/core/math/shapes/Circle.js +++ b/src/core/math/shapes/Circle.js @@ -10,7 +10,8 @@ * @param y {number} The Y coordinate of the center of this circle * @param radius {number} The radius of the circle */ -function Circle(x, y, radius) { +function Circle(x, y, radius) +{ /** * @member {number} * @default 0 @@ -46,7 +47,8 @@ * @method clone * @return {Circle} a copy of the Circle */ -Circle.prototype.clone = function () { +Circle.prototype.clone = function () +{ return new Circle(this.x, this.y, this.radius); }; @@ -58,8 +60,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Circle */ -Circle.prototype.contains = function (x, y) { - if (this.radius <= 0) { +Circle.prototype.contains = function (x, y) +{ + if (this.radius <= 0) + { return false; } @@ -79,6 +83,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Circle.prototype.getBounds = function () { +Circle.prototype.getBounds = function () +{ return new Rectangle(this.x - this.radius, this.y - this.radius, this.radius * 2, this.radius * 2); }; diff --git a/src/core/math/shapes/Ellipse.js b/src/core/math/shapes/Ellipse.js index 4f2d066..fefd01a 100644 --- a/src/core/math/shapes/Ellipse.js +++ b/src/core/math/shapes/Ellipse.js @@ -11,7 +11,8 @@ * @param width {number} The half width of this ellipse * @param height {number} The half height of this ellipse */ -function Ellipse(x, y, width, height) { +function Ellipse(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -53,7 +54,8 @@ * @method clone * @return {Ellipse} a copy of the ellipse */ -Ellipse.prototype.clone = function () { +Ellipse.prototype.clone = function () +{ return new Ellipse(this.x, this.y, this.width, this.height); }; @@ -65,8 +67,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coords are within this ellipse */ -Ellipse.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Ellipse.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } @@ -86,6 +90,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Ellipse.prototype.getBounds = function () { +Ellipse.prototype.getBounds = function () +{ return new Rectangle(this.x - this.width, this.y - this.height, this.width, this.height); }; diff --git a/src/core/math/shapes/Polygon.js b/src/core/math/shapes/Polygon.js index ae89148..fea6d37 100644 --- a/src/core/math/shapes/Polygon.js +++ b/src/core/math/shapes/Polygon.js @@ -10,16 +10,20 @@ * arguments passed can be flat x,y values e.g. `new Polygon(x,y, x,y, x,y, ...)` where `x` and `y` are * Numbers. */ -function Polygon(points) { +function Polygon(points) +{ //if points isn't an array, use arguments as the array - if (!(points instanceof Array)) { + if (!(points instanceof Array)) + { points = Array.prototype.slice.call(arguments); } //if this is a flat array of numbers, convert it to points - if (points[0] instanceof Point) { + if (points[0] instanceof Point) + { var p = []; - for (var i = 0, il = points.length; i < il; i++) { + for (var i = 0, il = points.length; i < il; i++) + { p.push(points[i].x, points[i].y); } @@ -51,7 +55,8 @@ * * @return {Polygon} a copy of the polygon */ -Polygon.prototype.clone = function () { +Polygon.prototype.clone = function () +{ return new Polygon(this.points.slice()); }; @@ -62,19 +67,22 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this polygon */ -Polygon.prototype.contains = function (x, y) { +Polygon.prototype.contains = function (x, y) +{ var inside = false; // use some raycasting to test hits // https://github.com/substack/point-in-polygon/blob/master/index.js var length = this.points.length / 2; - for (var i = 0, j = length - 1; i < length; j = i++) { + for (var i = 0, j = length - 1; i < length; j = i++) + { var xi = this.points[i * 2], yi = this.points[i * 2 + 1], xj = this.points[j * 2], yj = this.points[j * 2 + 1], intersect = ((yi > y) !== (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi); - if (intersect) { + if (intersect) + { inside = !inside; } } diff --git a/src/core/math/shapes/Rectangle.js b/src/core/math/shapes/Rectangle.js index 16ac62a..4008b68 100644 --- a/src/core/math/shapes/Rectangle.js +++ b/src/core/math/shapes/Rectangle.js @@ -10,7 +10,8 @@ * @param width {number} The overall width of this rectangle * @param height {number} The overall height of this rectangle */ -function Rectangle(x, y, width, height) { +function Rectangle(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -60,7 +61,8 @@ * * @return {Rectangle} a copy of the rectangle */ -Rectangle.prototype.clone = function () { +Rectangle.prototype.clone = function () +{ return new Rectangle(this.x, this.y, this.width, this.height); }; @@ -71,13 +73,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rectangle */ -Rectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Rectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/math/shapes/RoundedRectangle.js b/src/core/math/shapes/RoundedRectangle.js index 27d286e..7bf6411 100644 --- a/src/core/math/shapes/RoundedRectangle.js +++ b/src/core/math/shapes/RoundedRectangle.js @@ -11,7 +11,8 @@ * @param height {number} The overall height of this rounded rectangle * @param radius {number} Controls the radius of the rounded corners */ -function RoundedRectangle(x, y, width, height, radius) { +function RoundedRectangle(x, y, width, height, radius) +{ /** * @member {number} * @default 0 @@ -58,7 +59,8 @@ * * @return {RoundedRectangle} a copy of the rounded rectangle */ -RoundedRectangle.prototype.clone = function () { +RoundedRectangle.prototype.clone = function () +{ return new RoundedRectangle(this.x, this.y, this.width, this.height, this.radius); }; @@ -69,13 +71,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rounded Rectangle */ -RoundedRectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +RoundedRectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/primitives/Graphics.js b/src/core/primitives/Graphics.js index 261c534..e902d2a 100644 --- a/src/core/primitives/Graphics.js +++ b/src/core/primitives/Graphics.js @@ -16,7 +16,8 @@ * @extends DisplayObjectContainer * @namespace PIXI */ -function Graphics() { +function Graphics() +{ DisplayObjectContainer.call(this); this.renderable = true; @@ -154,16 +155,20 @@ * @private */ cacheAsBitmap: { - get: function () { + get: function () + { return this._cacheAsBitmap; }, - set: function (value) { + set: function (value) + { this._cacheAsBitmap = value; - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._generateCachedSprite(); } - else { + else + { this.destroyCachedSprite(); this.dirty = true; } @@ -176,7 +181,8 @@ * * @return {Graphics} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ var clone = new Graphics(); clone.renderable = this.renderable; @@ -192,7 +198,8 @@ clone.cachedSpriteDirty = this.cachedSpriteDirty; // copy graphics data - for (var i = 0; i < this.graphicsData.length; ++i) { + for (var i = 0; i < this.graphicsData.length; ++i) + { clone.graphicsData.push(this.graphicsData.clone()); } @@ -211,17 +218,21 @@ * @param alpha {number} alpha of the line to draw, will update the objects stored style * @return {Graphics} */ -Graphics.prototype.lineStyle = function (lineWidth, color, alpha) { +Graphics.prototype.lineStyle = function (lineWidth, color, alpha) +{ this.lineWidth = lineWidth || 0; this.lineColor = color || 0; this.lineAlpha = (arguments.length < 3) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length) + { // halfway through a line? start a new one! this.drawShape( new math.Polygon( this.currentPath.shape.points.slice(-2) )); } - else { + else + { // otherwise its empty so lets just set the line properties this.currentPath.lineWidth = this.lineWidth; this.currentPath.lineColor = this.lineColor; @@ -239,7 +250,8 @@ * @param y {number} the Y coordinate to move to * @return {Graphics} */ -Graphics.prototype.moveTo = function (x, y) { +Graphics.prototype.moveTo = function (x, y) +{ this.drawShape(new math.Polygon([x,y])); return this; @@ -253,7 +265,8 @@ * @param y {number} the Y coordinate to draw to * @return {Graphics} */ -Graphics.prototype.lineTo = function (x, y) { +Graphics.prototype.lineTo = function (x, y) +{ this.currentPath.shape.points.push(x, y); this.dirty = true; @@ -270,13 +283,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -285,7 +302,8 @@ n = 20, points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { this.moveTo(0, 0); } @@ -293,7 +311,8 @@ var fromY = points[points.length-1]; var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; xa = fromX + ( (cpX - fromX) * j ); @@ -319,13 +338,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -342,7 +365,8 @@ var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; dt = (1 - j); @@ -373,13 +397,17 @@ * @param radius {number} The radius of the arc * @return {Graphics} */ -Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points.push(x1, y1); } } - else { + else + { this.moveTo(x1, y1); } @@ -392,12 +420,15 @@ b2 = x2 - x1, mm = Math.abs(a1 * b2 - b1 * a2); - if (mm < 1.0e-8 || radius === 0) { - if (points[points.length-2] !== x1 || points[points.length-1] !== y1) { + if (mm < 1.0e-8 || radius === 0) + { + if (points[points.length-2] !== x1 || points[points.length-1] !== y1) + { points.push(x1, y1); } } - else { + else + { var dd = a1 * a1 + b1 * b1, cc = a2 * a2 + b2 * b2, tt = a1 * a2 + b1 * b2, @@ -433,42 +464,51 @@ * @param anticlockwise {boolean} Optional. Specifies whether the drawing should be counterclockwise or clockwise. False is default, and indicates clockwise, while true indicates counter-clockwise. * @return {Graphics} */ -Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) { +Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) +{ var startX = cx + Math.cos(startAngle) * radius; var startY = cy + Math.sin(startAngle) * radius; var points; // TODO - This if-else makes no sense. It uses currentPath in the else where it doesn't exist... - if (this.currentPath) { + if (this.currentPath) + { points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { points.push(startX, startY); } - else if (points[points.length-2] !== startX || points[points.length-1] !== startY) { + else if (points[points.length-2] !== startX || points[points.length-1] !== startY) + { points.push(startX, startY); } } - else { + else + { this.moveTo(startX, startY); points = this.currentPath.shape.points; } - if (startAngle === endAngle) { + if (startAngle === endAngle) + { return this; } - if (!anticlockwise && endAngle <= startAngle) { + if (!anticlockwise && endAngle <= startAngle) + { endAngle += Math.PI * 2; } - else if (anticlockwise && startAngle <= endAngle) { + else if (anticlockwise && startAngle <= endAngle) + { startAngle += Math.PI * 2; } var sweep = anticlockwise ? (startAngle - endAngle) *-1 : (endAngle - startAngle); var segs = (Math.abs(sweep)/ (Math.PI * 2)) * 40; - if (sweep === 0) { + if (sweep === 0) + { return this; } @@ -482,7 +522,8 @@ var remainder = ( segMinus % 1 ) / segMinus; - for (var i = 0; i <= segMinus; ++i) { + for (var i = 0; i <= segMinus; ++i) + { var real = i + remainder * i; var angle = ((theta) + startAngle + (theta2 * real)); @@ -506,13 +547,16 @@ * @param alpha {number} the alpha of the fill * @return {Graphics} */ -Graphics.prototype.beginFill = function (color, alpha) { +Graphics.prototype.beginFill = function (color, alpha) +{ this.filling = true; this.fillColor = color || 0; this.fillAlpha = (alpha === undefined) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length <= 2) + { this.currentPath.fill = this.filling; this.currentPath.fillColor = this.fillColor; this.currentPath.fillAlpha = this.fillAlpha; @@ -526,7 +570,8 @@ * * @return {Graphics} */ -Graphics.prototype.endFill = function () { +Graphics.prototype.endFill = function () +{ this.filling = false; this.fillColor = null; this.fillAlpha = 1; @@ -542,7 +587,8 @@ * @param height {number} The height of the rectangle * @return {Graphics} */ -Graphics.prototype.drawRect = function ( x, y, width, height ) { +Graphics.prototype.drawRect = function ( x, y, width, height ) +{ this.drawShape(new math.Rectangle(x,y, width, height)); return this; @@ -556,7 +602,8 @@ * @param height {number} The height of the rectangle * @param radius {number} Radius of the rectangle corners */ -Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) { +Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) +{ this.drawShape(new math.RoundedRectangle(x, y, width, height, radius)); return this; @@ -570,7 +617,8 @@ * @param radius {number} The radius of the circle * @return {Graphics} */ -Graphics.prototype.drawCircle = function (x, y, radius) { +Graphics.prototype.drawCircle = function (x, y, radius) +{ this.drawShape(new math.Circle(x,y, radius)); return this; @@ -585,7 +633,8 @@ * @param height {number} The half height of the ellipse * @return {Graphics} */ -Graphics.prototype.drawEllipse = function (x, y, width, height) { +Graphics.prototype.drawEllipse = function (x, y, width, height) +{ this.drawShape(new math.Ellipse(x, y, width, height)); return this; @@ -597,8 +646,10 @@ * @param path {Array} The path data used to construct the polygon. * @return {Graphics} */ -Graphics.prototype.drawPolygon = function (path) { - if (!(path instanceof Array)) { +Graphics.prototype.drawPolygon = function (path) +{ + if (!(path instanceof Array)) + { path = Array.prototype.slice.call(arguments); } @@ -612,7 +663,8 @@ * * @return {Graphics} */ -Graphics.prototype.clear = function () { +Graphics.prototype.clear = function () +{ this.lineWidth = 0; this.filling = false; @@ -631,7 +683,8 @@ * @param scaleMode {number} Should be one of the scaleMode consts * @return {Texture} a texture of the graphics object */ -Graphics.prototype.generateTexture = function (resolution, scaleMode) { +Graphics.prototype.generateTexture = function (resolution, scaleMode) +{ resolution = resolution || 1; var bounds = this.getBounds(); @@ -655,17 +708,21 @@ * * @param renderer {WebGLRenderer} */ -Graphics.prototype._renderWebGL = function (renderer) { +Graphics.prototype._renderWebGL = function (renderer) +{ // if the sprite is not visible or the alpha is 0 then no need to render this element - if (this.isMask === true) { + if (this.isMask === true) + { return; } // this code may still be needed so leaving for now.. - // + // /* - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture on the gpu too! @@ -681,17 +738,24 @@ return; } - */ - - // check if the webgl graphic needs to be updated - if (this.glDirty) { - this.dirty = true; - this.glDirty = false; - } + else */ - renderer.setObjectRendererer(renderer.graphicsRenderer); - renderer.graphicsRenderer.render(this); + renderer.spriteBatch.stop(); + renderer.blendModeManager.setBlendMode(this.blendMode); + // check blend mode + renderer.blendModeManager.setBlendMode( this.blendMode ); + + // check if the webgl graphic needs to be updated + if (this.glDirty) + { + this.dirty = true; + this.glDirty = false; + } + + WebGLGraphics.renderGraphics(this, renderer); + + renderer.spriteBatch.start(); }; /** @@ -700,14 +764,18 @@ * @param renderer {CanvasRenderer} * @private */ -Graphics.prototype.renderCanvas = function (renderer) { +Graphics.prototype.renderCanvas = function (renderer) +{ // 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.isMask === true) { + if (!this.visible || this.alpha <= 0 || this.isMask === true) + { return; } - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture @@ -723,16 +791,19 @@ return; } - else { + else + { var context = renderer.context; var transform = this.worldTransform; - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } @@ -748,11 +819,13 @@ CanvasGraphics.renderGraphics(this, context); - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } } @@ -763,13 +836,16 @@ * * @return {Rectangle} the rectangular bounding area */ -Graphics.prototype.getBounds = function (matrix) { +Graphics.prototype.getBounds = function (matrix) +{ // return an empty object if the item is a mask! - if (this.isMask) { + if (this.isMask) + { return math.Rectangle.EMPTY; } - if (this.dirty) { + if (this.dirty) + { this.updateLocalBounds(); this.glDirty = true; @@ -841,23 +917,27 @@ * Update the bounds of the object * */ -Graphics.prototype.updateLocalBounds = function () { +Graphics.prototype.updateLocalBounds = function () +{ var minX = Infinity; var maxX = -Infinity; var minY = Infinity; var maxY = -Infinity; - if (this.graphicsData.length) { + if (this.graphicsData.length) + { var shape, points, x, y, w, h; - for (var i = 0; i < this.graphicsData.length; i++) { + for (var i = 0; i < this.graphicsData.length; i++) + { var data = this.graphicsData[i]; var type = data.type; var lineWidth = data.lineWidth; shape = data.shape; - if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) { + if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) + { x = shape.x - lineWidth/2; y = shape.y - lineWidth/2; w = shape.width + lineWidth; @@ -869,7 +949,8 @@ minY = y < minY ? y : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.CIRC) { + else if (type === CONST.SHAPES.CIRC) + { x = shape.x; y = shape.y; w = shape.radius + lineWidth/2; @@ -881,7 +962,8 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.ELIP) { + else if (type === CONST.SHAPES.ELIP) + { x = shape.x; y = shape.y; w = shape.width + lineWidth/2; @@ -893,11 +975,13 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else { + else + { // POLY points = shape.points; - for (var j = 0; j < points.length; j += 2) { + for (var j = 0; j < points.length; j += 2) + { x = points[j]; y = points[j+1]; @@ -910,7 +994,8 @@ } } } - else { + else + { minX = 0; maxX = 0; minY = 0; @@ -931,10 +1016,12 @@ * * @private */ -Graphics.prototype._generateCachedSprite = function () { +Graphics.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { var canvasBuffer = new CanvasBuffer(bounds.width, bounds.height); var texture = Texture.fromCanvas(canvasBuffer.canvas); @@ -943,7 +1030,8 @@ this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.buffer.resize(bounds.width, bounds.height); } @@ -968,7 +1056,8 @@ * * @private */ -Graphics.prototype.updateCachedSpriteTexture = function () { +Graphics.prototype.updateCachedSpriteTexture = function () +{ var cachedSprite = this._cachedSprite; var texture = cachedSprite.texture; var canvas = cachedSprite.buffer.canvas; @@ -989,7 +1078,8 @@ * Destroys a previous cached sprite. * */ -Graphics.prototype.destroyCachedSprite = function () { +Graphics.prototype.destroyCachedSprite = function () +{ this._cachedSprite.texture.destroy(true); // let the gc collect the unused sprite @@ -1003,10 +1093,13 @@ * @param {Circle|Rectangle|Ellipse|Line|Polygon} shape The Shape object to draw. * @return {GraphicsData} The generated GraphicsData object. */ -Graphics.prototype.drawShape = function (shape) { - if (this.currentPath) { +Graphics.prototype.drawShape = function (shape) +{ + if (this.currentPath) + { // check current path! - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath.shape.points.length <= 2) + { this.graphicsData.pop(); } } @@ -1017,7 +1110,8 @@ this.graphicsData.push(data); - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { data.shape.closed = this.filling; this.currentPath = data; } diff --git a/src/core/primitives/GraphicsData.js b/src/core/primitives/GraphicsData.js index 99decbe..788f6f2 100644 --- a/src/core/primitives/GraphicsData.js +++ b/src/core/primitives/GraphicsData.js @@ -4,7 +4,8 @@ * @class * @namespace PIXI */ -function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) { +function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) +{ this.lineWidth = lineWidth; this.lineColor = lineColor; this.lineAlpha = lineAlpha; @@ -27,7 +28,8 @@ * * @return {GraphicsData} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ return new GraphicsData( this.lineWidth, this.lineColor, diff --git a/src/core/renderers/canvas/CanvasRenderer.js b/src/core/renderers/canvas/CanvasRenderer.js index 15a0978..7aebd44 100644 --- a/src/core/renderers/canvas/CanvasRenderer.js +++ b/src/core/renderers/canvas/CanvasRenderer.js @@ -17,17 +17,22 @@ * @param [options.resolution=1] {number} the resolution of the renderer retina would be 2 * @param [options.clearBeforeRender=true] {boolean} This sets if the CanvasRenderer will clear the canvas or not before the new render pass. */ -function CanvasRenderer(width, height, options) { +function CanvasRenderer(width, height, options) +{ utils.sayHello('Canvas'); - if (options) { - for (var i in CONST.defaultRenderOptions) { - if (typeof options[i] === 'undefined') { + if (options) + { + for (var i in CONST.defaultRenderOptions) + { + if (typeof options[i] === 'undefined') + { options[i] = CONST.defaultRenderOptions[i]; } } } - else { + else + { options = CONST.defaultRenderOptions; } @@ -156,19 +161,24 @@ this.smoothProperty = null; - if (this.context.imageSmoothingEnabled) { + if (this.context.imageSmoothingEnabled) + { this.smoothProperty = 'imageSmoothingEnabled'; } - else if (this.context.webkitImageSmoothingEnabled) { + else if (this.context.webkitImageSmoothingEnabled) + { this.smoothProperty = 'webkitImageSmoothingEnabled'; } - else if (this.context.mozImageSmoothingEnabled) { + else if (this.context.mozImageSmoothingEnabled) + { this.smoothProperty = 'mozImageSmoothingEnabled'; } - else if (this.context.oImageSmoothingEnabled) { + else if (this.context.oImageSmoothingEnabled) + { this.smoothProperty = 'oImageSmoothingEnabled'; } - else if (this.context.msImageSmoothingEnabled) { + else if (this.context.msImageSmoothingEnabled) + { this.smoothProperty = 'msImageSmoothingEnabled'; } @@ -193,10 +203,12 @@ * @memberof CanvasRenderer# */ backgroundColor: { - get: function () { + get: function () + { return this._backgroundColor; }, - set: function (val) { + set: function (val) + { this._backgroundColor = val; this._backgroundColorString = utils.hex2string(val); } @@ -208,7 +220,8 @@ * * @param object {DisplayObject} the object to be rendered */ -CanvasRenderer.prototype.render = function (object) { +CanvasRenderer.prototype.render = function (object) +{ object.updateTransform(); this.context.setTransform(1,0,0,1,0,0); @@ -218,16 +231,20 @@ this.currentBlendMode = CONST.blendModes.NORMAL; this.context.globalCompositeOperation = this.blendModes[CONST.blendModes.NORMAL]; - if (navigator.isCocoonJS && this.view.screencanvas) { + if (navigator.isCocoonJS && this.view.screencanvas) + { this.context.fillStyle = 'black'; this.context.clear(); } - if (this.clearBeforeRender) { - if (this.transparent) { + if (this.clearBeforeRender) + { + if (this.transparent) + { this.context.clearRect(0, 0, this.width, this.height); } - else { + else + { this.context.fillStyle = this._backgroundColorString; this.context.fillRect(0, 0, this.width , this.height); } @@ -241,8 +258,10 @@ * * @param [removeView=false] {boolean} Removes the Canvas element from the DOM. */ -CanvasRenderer.prototype.destroy = function (removeView) { - if (removeView && this.view.parent) { +CanvasRenderer.prototype.destroy = function (removeView) +{ + if (removeView && this.view.parent) + { this.view.parent.removeChild(this.view); } @@ -257,14 +276,16 @@ * @param width {number} the new width of the canvas view * @param height {number} the new height of the canvas view */ -CanvasRenderer.prototype.resize = function (width, height) { +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) { + if (this.autoResize) + { this.view.style.width = this.width / this.resolution + 'px'; this.view.style.height = this.height / this.resolution + 'px'; } @@ -276,7 +297,8 @@ * @param displayObject {DisplayObject} The displayObject to render * @private */ -CanvasRenderer.prototype.renderDisplayObject = function (displayObject) { +CanvasRenderer.prototype.renderDisplayObject = function (displayObject) +{ displayObject.renderCanvas(this); }; @@ -285,11 +307,14 @@ * * @private */ -CanvasRenderer.prototype._mapBlendModes = function () { - if (!this.blendModes) { +CanvasRenderer.prototype._mapBlendModes = function () +{ + if (!this.blendModes) + { this.blendModes = {}; - if (utils.canUseNewCanvasBlendModes()) { + if (utils.canUseNewCanvasBlendModes()) + { this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? this.blendModes[CONST.blendModes.MULTIPLY] = 'multiply'; @@ -308,7 +333,8 @@ this.blendModes[CONST.blendModes.COLOR] = 'color'; this.blendModes[CONST.blendModes.LUMINOSITY] = 'luminosity'; } - else { + else + { // this means that the browser does not support the cool new blend modes in canvas 'cough' ie 'cough' this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? diff --git a/src/core/renderers/canvas/utils/CanvasBuffer.js b/src/core/renderers/canvas/utils/CanvasBuffer.js index ebe5d47..b183a66 100644 --- a/src/core/renderers/canvas/utils/CanvasBuffer.js +++ b/src/core/renderers/canvas/utils/CanvasBuffer.js @@ -6,7 +6,8 @@ * @param width {number} the width for the newly created canvas * @param height {number} the height for the newly created canvas */ -function CanvasBuffer(width, height) { +function CanvasBuffer(width, height) +{ /** * The Canvas object that belongs to this CanvasBuffer. * @@ -36,10 +37,12 @@ * @memberof CanvasBuffer# */ width: { - get: function () { + get: function () + { return this.canvas.width; }, - set: function (val) { + set: function (val) + { this.canvas.width = val; } }, @@ -50,10 +53,12 @@ * @memberof CanvasBuffer# */ height: { - get: function () { + get: function () + { return this.canvas.height; }, - set: function (val) { + set: function (val) + { this.canvas.height = val; } } @@ -64,7 +69,8 @@ * * @private */ -CanvasBuffer.prototype.clear = function () { +CanvasBuffer.prototype.clear = function () +{ this.context.setTransform(1, 0, 0, 1, 0, 0); this.context.clearRect(0,0, this.canvas.width, this.canvas.height); }; @@ -75,7 +81,8 @@ * @param width {number} the new width of the canvas * @param height {number} the new height of the canvas */ -CanvasBuffer.prototype.resize = function (width, height) { +CanvasBuffer.prototype.resize = function (width, height) +{ this.canvas.width = width; this.canvas.height = height; }; diff --git a/src/core/renderers/canvas/utils/CanvasGraphics.js b/src/core/renderers/canvas/utils/CanvasGraphics.js index c7eaa2a..3f2a91f 100644 --- a/src/core/renderers/canvas/utils/CanvasGraphics.js +++ b/src/core/renderers/canvas/utils/CanvasGraphics.js @@ -13,15 +13,18 @@ * @param graphics {Graphics} the actual graphics object to render * @param context {CanvasRenderingContext2D} the 2d drawing method of the canvas */ -CanvasGraphics.renderGraphics = function (graphics, context) { +CanvasGraphics.renderGraphics = function (graphics, context) +{ var worldAlpha = graphics.worldAlpha; - if (graphics.dirty) { + if (graphics.dirty) + { this.updateGraphicsTint(graphics); graphics.dirty = false; } - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; @@ -30,69 +33,82 @@ context.lineWidth = data.lineWidth; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { context.beginPath(); var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } - if (shape.closed) { + if (shape.closed) + { context.lineTo(points[0], points[1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fillRect(shape.x, shape.y, shape.width, shape.height); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.strokeRect(shape.x, shape.y, shape.width, shape.height); } } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.beginPath(); context.arc(shape.x, shape.y, shape.radius,0,2*Math.PI); context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas var w = shape.width * 2; @@ -119,18 +135,21 @@ context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; var width = shape.width; @@ -152,13 +171,15 @@ context.quadraticCurveTo(rx, ry, rx, ry + radius); context.closePath(); - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); @@ -174,45 +195,54 @@ * @param graphics {Graphics} the graphics which will be used as a mask * @param context {CanvasRenderingContext2D} the context 2d method of the canvas */ -CanvasGraphics.renderGraphicsMask = function (graphics, context) { +CanvasGraphics.renderGraphicsMask = function (graphics, context) +{ var len = graphics.graphicsData.length; - if (len === 0) { + if (len === 0) + { return; } context.beginPath(); - for (var i = 0; i < len; i++) { + for (var i = 0; i < len; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { context.rect(shape.x, shape.y, shape.width, shape.height); context.closePath(); } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.arc(shape.x, shape.y, shape.radius, 0, 2 * Math.PI); context.closePath(); } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas @@ -237,7 +267,8 @@ context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); context.closePath(); } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; @@ -262,8 +293,10 @@ } }; -CanvasGraphics.updateGraphicsTint = function (graphics) { - if (graphics.tint === 0xFFFFFF) { +CanvasGraphics.updateGraphicsTint = function (graphics) +{ + if (graphics.tint === 0xFFFFFF) + { return; } @@ -271,7 +304,8 @@ var tintG = (graphics.tint >> 8 & 0xFF) / 255; var tintB = (graphics.tint & 0xFF)/ 255; - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var fillColor = data.fillColor | 0; diff --git a/src/core/renderers/canvas/utils/CanvasMaskManager.js b/src/core/renderers/canvas/utils/CanvasMaskManager.js index e04a733..9827d36 100644 --- a/src/core/renderers/canvas/utils/CanvasMaskManager.js +++ b/src/core/renderers/canvas/utils/CanvasMaskManager.js @@ -6,7 +6,8 @@ * @class * @namespace PIXI */ -function CanvasMaskManager() {} +function CanvasMaskManager() +{} CanvasMaskManager.prototype.constructor = CanvasMaskManager; module.exports = CanvasMaskManager; @@ -17,7 +18,8 @@ * @param maskData {object} the maskData that will be pushed * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.pushMask = function (maskData, renderer) { +CanvasMaskManager.prototype.pushMask = function (maskData, renderer) +{ renderer.context.save(); var cacheAlpha = maskData.alpha; @@ -45,6 +47,7 @@ * * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.popMask = function (renderer) { +CanvasMaskManager.prototype.popMask = function (renderer) +{ renderer.context.restore(); }; diff --git a/src/core/renderers/canvas/utils/CanvasTinter.js b/src/core/renderers/canvas/utils/CanvasTinter.js index 17e0529..d2fb1bc 100644 --- a/src/core/renderers/canvas/utils/CanvasTinter.js +++ b/src/core/renderers/canvas/utils/CanvasTinter.js @@ -14,7 +14,8 @@ * @param color {number} the color to use to tint the sprite with * @return {HTMLCanvasElement} The tinted canvas */ -CanvasTinter.getTintedTexture = function (sprite, color) { +CanvasTinter.getTintedTexture = function (sprite, color) +{ var texture = sprite.texture; color = CanvasTinter.roundColor(color); @@ -23,7 +24,8 @@ texture.tintCache = texture.tintCache || {}; - if (texture.tintCache[stringColor]) { + if (texture.tintCache[stringColor]) + { return texture.tintCache[stringColor]; } @@ -33,14 +35,16 @@ //CanvasTinter.tintWithPerPixel(texture, stringColor, canvas); CanvasTinter.tintMethod(texture, color, canvas); - if (CanvasTinter.convertTintToImage) { + if (CanvasTinter.convertTintToImage) + { // is this better? var tintImage = new Image(); tintImage.src = canvas.toDataURL(); texture.tintCache[stringColor] = tintImage; } - else { + else + { texture.tintCache[stringColor] = canvas; // if we are not converting the texture to an image then we need to lose the reference to the canvas CanvasTinter.canvas = null; @@ -56,7 +60,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithMultiply = function (texture, color, canvas) { +CanvasTinter.tintWithMultiply = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -104,7 +109,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithOverlay = function (texture, color, canvas) { +CanvasTinter.tintWithOverlay = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -139,7 +145,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithPerPixel = function (texture, color, canvas) { +CanvasTinter.tintWithPerPixel = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -167,7 +174,8 @@ var pixels = pixelData.data; - for (var i = 0; i < pixels.length; i += 4) { + for (var i = 0; i < pixels.length; i += 4) + { pixels[i+0] *= r; pixels[i+1] *= g; pixels[i+2] *= b; @@ -181,7 +189,8 @@ * * @param color {number} the color to round, should be a hex color */ -CanvasTinter.roundColor = function (color) { +CanvasTinter.roundColor = function (color) +{ var step = CanvasTinter.cacheStepsPerColorChannel; var rgbValues = utils.hex2rgb(color); diff --git a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js index 9f2f89a..35edbaf 100644 --- a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js +++ b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLBlendModeManager(renderer) { +function WebGLBlendModeManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -23,8 +24,10 @@ * * @param blendMode {number} the blendMode, should be a Pixi const, such as BlendModes.ADD */ -WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) { - if (this.currentBlendMode === blendMode) { +WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) +{ + if (this.currentBlendMode === blendMode) + { return false; } diff --git a/src/core/renderers/webgl/managers/WebGLFilterManager.js b/src/core/renderers/webgl/managers/WebGLFilterManager.js index 1179258..2dac048 100644 --- a/src/core/renderers/webgl/managers/WebGLFilterManager.js +++ b/src/core/renderers/webgl/managers/WebGLFilterManager.js @@ -7,7 +7,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLFilterManager(renderer) { +function WebGLFilterManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -32,7 +33,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.texturePool.length = 0; self.initShaderBuffers(); }); @@ -46,7 +48,8 @@ * @param renderer {WebGLRenderer} * @param buffer {ArrayBuffer} */ -WebGLFilterManager.prototype.begin = function (buffer) { +WebGLFilterManager.prototype.begin = function (buffer) +{ this.defaultShader = this.renderer.shaderManager.defaultShader; this.width = this.renderer.projection.x * 2; @@ -60,7 +63,8 @@ * * @param filterBlock {object} the filter that will be pushed to the current filter stack */ -WebGLFilterManager.prototype.pushFilter = function (filterBlock) { +WebGLFilterManager.prototype.pushFilter = function (filterBlock) +{ var gl = this.renderer.gl; var projection = this.renderer.projection; @@ -78,10 +82,12 @@ this.offsetY += filterBlock._filterArea.y; var texture = this.texturePool.pop(); - if (!texture) { + if (!texture) + { texture = new FilterTexture(this.renderer.gl, this.width, this.height); } - else { + else + { texture.resize(this.width, this.height); } @@ -98,29 +104,35 @@ var localX = filterArea.x, localY = filterArea.y; - if (filterArea.x < 0) { + if (filterArea.x < 0) + { filterArea.width += filterArea.x; filterArea.x = 0; } - if (filterArea.y < 0) { + if (filterArea.y < 0) + { filterArea.height += filterArea.y; filterArea.y = 0; } - if (localX + filterArea.width > this.width) { + if (localX + filterArea.width > this.width) + { filterArea.width = this.width - localX; } - if (localY + filterArea.height > this.height) { + if (localY + filterArea.height > this.height) + { filterArea.height = this.height - localY; } - if (filterArea.width < 0) { + if (filterArea.width < 0) + { filterArea.width = 0; } - if (filterArea.height < 0) { + if (filterArea.height < 0) + { filterArea.height = 0; } @@ -154,7 +166,8 @@ * Removes the last filter from the filter stack and doesn't return it. * */ -WebGLFilterManager.prototype.popFilter = function () { +WebGLFilterManager.prototype.popFilter = function () +{ var gl = this.renderer.gl; var filterBlock = this.filterStack.pop(); @@ -163,7 +176,8 @@ var projection = this.renderer.projection; var offset = this.renderer.offset; - if (filterBlock.filterPasses.length > 1) { + if (filterBlock.filterPasses.length > 1) + { gl.viewport(0, 0, filterArea.width, filterArea.height); gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); @@ -193,7 +207,8 @@ var inputTexture = texture; var outputTexture = this.texturePool.pop(); - if (!outputTexture) { + if (!outputTexture) + { outputTexture = new FilterTexture(this.renderer.gl, this.width, this.height); } outputTexture.resize(this.width, this.height); @@ -204,7 +219,8 @@ gl.disable(gl.BLEND); - for (var i = 0; i < filterBlock.filterPasses.length-1; i++) { + for (var i = 0; i < filterBlock.filterPasses.length-1; i++) + { var filterPass = filterBlock.filterPasses[i]; gl.bindFramebuffer(gl.FRAMEBUFFER, outputTexture.frameBuffer ); @@ -243,10 +259,12 @@ var buffer = this.buffer; // time to render the filters texture to the previous scene - if (this.filterStack.length === 0) { + if (this.filterStack.length === 0) + { gl.colorMask(true, true, true, true);//this.transparent); } - else { + else + { var currentFilter = this.filterStack[this.filterStack.length-1]; filterArea = currentFilter._filterArea; @@ -332,13 +350,15 @@ * @param width {number} the horizontal range of the filter * @param height {number} the vertical range of the filter */ -WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) { +WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) +{ // use program var gl = this.renderer.gl; var shader = filter.shaders[gl.id]; - if (!shader) { + if (!shader) + { shader = new Shader(gl); shader.fragmentSrc = filter.fragmentSrc; @@ -356,7 +376,8 @@ gl.uniform2f(shader.projectionVector, width/2, -height/2); gl.uniform2f(shader.offsetVector, 0,0); - if (filter.uniforms.dimensions) { + 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]; @@ -386,7 +407,8 @@ * Initialises the shader buffers. * */ -WebGLFilterManager.prototype.initShaderBuffers = function () { +WebGLFilterManager.prototype.initShaderBuffers = function () +{ var gl = this.renderer.gl; // create some buffers @@ -432,7 +454,8 @@ * Destroys the filter and removes it from the filter stack. * */ -WebGLFilterManager.prototype.destroy = function () { +WebGLFilterManager.prototype.destroy = function () +{ var gl = this.renderer.gl; this.filterStack = null; @@ -441,7 +464,8 @@ this.offsetY = 0; // destroy textures - for (var i = 0; i < this.texturePool.length; i++) { + for (var i = 0; i < this.texturePool.length; i++) + { this.texturePool[i].destroy(); } diff --git a/src/core/renderers/webgl/managers/WebGLManager.js b/src/core/renderers/webgl/managers/WebGLManager.js index 9d47b5c..c30cd51 100644 --- a/src/core/renderers/webgl/managers/WebGLManager.js +++ b/src/core/renderers/webgl/managers/WebGLManager.js @@ -3,7 +3,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLManager(renderer) { +function WebGLManager(renderer) +{ /** * The renderer this manager works for. * @@ -15,6 +16,7 @@ WebGLManager.prototype.constructor = WebGLManager; module.exports = WebGLManager; -WebGLManager.prototype.destroy = function () { +WebGLManager.prototype.destroy = function () +{ this.renderer = null; }; diff --git a/src/core/renderers/webgl/managers/WebGLMaskManager.js b/src/core/renderers/webgl/managers/WebGLMaskManager.js index 2f90b64..e568812 100644 --- a/src/core/renderers/webgl/managers/WebGLMaskManager.js +++ b/src/core/renderers/webgl/managers/WebGLMaskManager.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLMaskManager(renderer) { +function WebGLMaskManager(renderer) +{ WebGLManager.call(this, renderer); } @@ -19,12 +20,15 @@ * * @param maskData {any[]} */ -WebGLMaskManager.prototype.pushMask = function (maskData) { - if (maskData.dirty) { +WebGLMaskManager.prototype.pushMask = function (maskData) +{ + if (maskData.dirty) + { WebGLGraphics.updateGraphics(maskData, this.renderer.gl); } - if (!maskData._webGL[this.renderer.gl.id].data.length) { + if (!maskData._webGL[this.renderer.gl.id].data.length) + { return; } @@ -36,6 +40,7 @@ * * @param maskData {any[]} */ -WebGLMaskManager.prototype.popMask = function (maskData) { +WebGLMaskManager.prototype.popMask = function (maskData) +{ this.renderer.stencilManager.popStencil(maskData, maskData._webGL[this.renderer.gl.id].data[0], this.renderer); }; diff --git a/src/core/renderers/webgl/managers/WebGLShaderManager.js b/src/core/renderers/webgl/managers/WebGLShaderManager.js index fef071c..90c6477 100644 --- a/src/core/renderers/webgl/managers/WebGLShaderManager.js +++ b/src/core/renderers/webgl/managers/WebGLShaderManager.js @@ -10,7 +10,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLShaderManager(renderer) { +function WebGLShaderManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -28,7 +29,8 @@ */ this.tempAttribState = []; - for (var i = 0; i < this.maxAttibs; i++) { + for (var i = 0; i < this.maxAttibs; i++) + { this.attribState[i] = false; } @@ -66,7 +68,8 @@ // listen for context and update necessary shaders var self = this; - this.renderer.on('context', function (event) { + this.renderer.on('context', function (event) + { var gl = event.data; // this shader is used for rendering primitives @@ -97,29 +100,36 @@ * * @param attribs {Array} attribs */ -WebGLShaderManager.prototype.setAttribs = function (attribs) { +WebGLShaderManager.prototype.setAttribs = function (attribs) +{ // reset temp state var i; - for (i = 0; i < this.tempAttribState.length; i++) { + for (i = 0; i < this.tempAttribState.length; i++) + { this.tempAttribState[i] = false; } // set the new attribs - for (var a in attribs) { + for (var a in attribs) + { this.tempAttribState[attribs[a]] = true; } var gl = this.renderer.gl; - for (i = 0; i < this.attribState.length; i++) { - if (this.attribState[i] !== this.tempAttribState[i]) { + for (i = 0; i < this.attribState.length; i++) + { + if (this.attribState[i] !== this.tempAttribState[i]) + { this.attribState[i] = this.tempAttribState[i]; - if (this.attribState[i]) { + if (this.attribState[i]) + { gl.enableVertexAttribArray(i); } - else { + else + { gl.disableVertexAttribArray(i); } } @@ -131,8 +141,10 @@ * * @param shader {Any} */ -WebGLShaderManager.prototype.setShader = function (shader) { - if (this._currentId === shader.uuid) { +WebGLShaderManager.prototype.setShader = function (shader) +{ + if (this._currentId === shader.uuid) + { return false; } @@ -150,7 +162,8 @@ * Destroys this object. * */ -WebGLShaderManager.prototype.destroy = function () { +WebGLShaderManager.prototype.destroy = function () +{ this.attribState = null; this.tempAttribState = null; diff --git a/src/core/renderers/webgl/managers/WebGLStencilManager.js b/src/core/renderers/webgl/managers/WebGLStencilManager.js index 9ec6398..4cb0134 100644 --- a/src/core/renderers/webgl/managers/WebGLStencilManager.js +++ b/src/core/renderers/webgl/managers/WebGLStencilManager.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLStencilManager(renderer) { +function WebGLStencilManager(renderer) +{ WebGLManager.call(this, renderer); this.stencilStack = []; @@ -24,12 +25,14 @@ * @param graphics {Graphics} * @param webGLData {any[]} */ -WebGLStencilManager.prototype.pushStencil = function (graphics, webGLData) { +WebGLStencilManager.prototype.pushStencil = function (graphics, webGLData) +{ var gl = this.renderer.gl; this.bindGraphics(graphics, webGLData, this.renderer); - if (this.stencilStack.length === 0) { + if (this.stencilStack.length === 0) + { gl.enable(gl.STENCIL_TEST); gl.clear(gl.STENCIL_BUFFER_BIT); this.reverse = true; @@ -47,14 +50,17 @@ // draw the triangle strip! - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } @@ -62,31 +68,38 @@ // draw a quad to increment.. gl.drawElements(gl.TRIANGLE_FAN, 4, gl.UNSIGNED_SHORT, ( webGLData.indices.length - 4 ) * 2 ); - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); } this.reverse = !this.reverse; } - else { - if (!this.reverse) { + else + { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } - else { + 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) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); } } @@ -103,7 +116,8 @@ * @param graphics {Graphics} * @param webGLData {Array} */ -WebGLStencilManager.prototype.bindGraphics = function (graphics, webGLData) { +WebGLStencilManager.prototype.bindGraphics = function (graphics, webGLData) +{ //if (this._currentGraphics === graphics)return; this._currentGraphics = graphics; @@ -114,7 +128,8 @@ offset = this.renderer.offset, shader;// = this.renderer.shaderManager.primitiveShader; - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { shader = this.renderer.shaderManager.complexPrimitiveShader; this.renderer.shaderManager.setShader(shader); @@ -141,7 +156,8 @@ // set the index buffer! gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, webGLData.indexBuffer); } - else { + else + { //this.renderer.shaderManager.activatePrimitiveShader(); shader = this.renderer.shaderManager.primitiveShader; this.renderer.shaderManager.setShader( shader ); @@ -154,7 +170,7 @@ gl.uniform2f(shader.uniforms.offsetVector._location, -offset.x, -offset.y); gl.uniform3fv(shader.uniforms.tint._location, utils.hex2rgb(graphics.tint)); - + gl.uniform1f(shader.uniforms.alpha._location, graphics.worldAlpha); @@ -172,19 +188,22 @@ * @param graphics {Graphics} * @param webGLData {Array} */ -WebGLStencilManager.prototype.popStencil = function (graphics, webGLData) { +WebGLStencilManager.prototype.popStencil = function (graphics, webGLData) +{ var gl = this.renderer.gl; this.stencilStack.pop(); this.count--; - if (this.stencilStack.length === 0) { + if (this.stencilStack.length === 0) + { // the stack is empty! gl.disable(gl.STENCIL_TEST); } - else { + else + { var level = this.count; @@ -192,14 +211,17 @@ gl.colorMask(false, false, false, false); - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { this.reverse = !this.reverse; - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } @@ -213,31 +235,38 @@ // draw the triangle strip! gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); - if (!this.reverse) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); } } - else { + else + { // console.log("<<>>") - if (!this.reverse) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } - else { + 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) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); } } @@ -253,7 +282,8 @@ * Destroys the mask stack. * */ -WebGLStencilManager.prototype.destroy = function () { +WebGLStencilManager.prototype.destroy = function () +{ this.renderer = null; this.stencilStack = null; }; diff --git a/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js b/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js index 913ba5e..1ea7d19 100644 --- a/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js +++ b/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function ComplexPrimitiveShader(gl) { +function ComplexPrimitiveShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -24,7 +25,8 @@ 'uniform float flipY;', 'varying vec4 vColor;', - 'void main(void) {', + '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);', @@ -37,7 +39,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = vColor;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/FastShader.js b/src/core/renderers/webgl/shaders/FastShader.js index bd2e29a..2e5e060 100644 --- a/src/core/renderers/webgl/shaders/FastShader.js +++ b/src/core/renderers/webgl/shaders/FastShader.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function FastShader(gl) { +function FastShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -28,7 +29,8 @@ 'const vec2 center = vec2(-1.0, 1.0);', - 'void main(void) {', + 'void main(void) + {', ' vec2 v;', ' vec2 sv = aVertexPosition * aScale;', ' v.x = (sv.x) * cos(aRotation) - (sv.y) * sin(aRotation);', @@ -49,7 +51,8 @@ 'uniform sampler2D uSampler;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/PrimitiveShader.js b/src/core/renderers/webgl/shaders/PrimitiveShader.js index 6f25409..a25f54f 100644 --- a/src/core/renderers/webgl/shaders/PrimitiveShader.js +++ b/src/core/renderers/webgl/shaders/PrimitiveShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function PrimitiveShader(gl) { +function PrimitiveShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -23,7 +24,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + '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);', @@ -36,7 +38,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = vColor;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/Shader.js b/src/core/renderers/webgl/shaders/Shader.js index f8964f5..fd75ef5 100644 --- a/src/core/renderers/webgl/shaders/Shader.js +++ b/src/core/renderers/webgl/shaders/Shader.js @@ -6,7 +6,8 @@ * @param [fragmentSrc] {string} The source of the fragment shader. * @param [vertexSrc] {string} The source of the vertex shader. */ -function Shader(gl, vertexSrc, fragmentSrc, customUniforms, customAttributes) { +function Shader(gl, vertexSrc, fragmentSrc, customUniforms, customAttributes) +{ /** * @member {number} * @readonly @@ -33,7 +34,8 @@ dimensions: { type: '4f', value: new Float32Array(4) } }; - for (var u in customUniforms) { + for (var u in customUniforms) + { this.uniforms[u] = customUniforms[u]; } @@ -43,7 +45,8 @@ aColor: 0 }; - for (var a in customAttributes) { + for (var a in customAttributes) + { this.attributes[a] = customAttributes[a]; } @@ -66,7 +69,8 @@ 'const vec2 center = vec2(-1.0, 1.0);', - 'void main(void) {', + 'void main(void) + {', ' gl_Position = vec4( ((aVertexPosition + offsetVector) / projectionVector) + center , 0.0, 1.0);', ' vTextureCoord = aTextureCoord;', ' vColor = vec4(aColor.rgb * aColor.a, aColor.a);', @@ -85,7 +89,8 @@ 'uniform sampler2D uSampler;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;', '}' ].join('\n'); @@ -96,7 +101,8 @@ Shader.prototype.constructor = Shader; module.exports = Shader; -Shader.prototype.init = function () { +Shader.prototype.init = function () +{ this.compile(); this.gl.useProgram(this.program); @@ -105,14 +111,18 @@ this.cacheAttributeLocations(Object.keys(this.attributes)); }; -Shader.prototype.cacheUniformLocations = function (keys) { - for (var i = 0; i < keys.length; ++i) { +Shader.prototype.cacheUniformLocations = function (keys) +{ + for (var i = 0; i < keys.length; ++i) + { this.uniforms[keys[i]]._location = this.gl.getUniformLocation(this.program, keys[i]); } }; -Shader.prototype.cacheAttributeLocations = function (keys) { - for (var i = 0; i < keys.length; ++i) { +Shader.prototype.cacheAttributeLocations = function (keys) +{ + for (var i = 0; i < keys.length; ++i) + { this.attributes[keys[i]] = this.gl.getAttribLocation(this.program, keys[i]); } @@ -124,14 +134,16 @@ // 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.attributes.aColor === -1) { + // if (this.attributes.aColor === -1) + { // this.attributes.aColor = 2; // } // End worst hack eva // }; -Shader.prototype.compile = function () { +Shader.prototype.compile = function () +{ var gl = this.gl; var glVertShader = this._glCompile(gl.VERTEX_SHADER, this.vertexSrc); @@ -144,13 +156,15 @@ gl.linkProgram(program); // if linking fails, then log and cleanup - if (!gl.getProgramParameter(program, gl.LINK_STATUS)) { + if (!gl.getProgramParameter(program, gl.LINK_STATUS)) + { window.console.error('Pixi.js Error: Could not initialize shader.'); window.console.error('gl.VALIDATE_STATUS', gl.getProgramParameter(program, gl.VALIDATE_STATUS)); window.console.error('gl.getError()', gl.getError()); // if there is a program info log, log it - if (gl.getProgramInfoLog(program) !== '') { + if (gl.getProgramInfoLog(program) !== '') + { window.console.warn('Pixi.js Warning: gl.getProgramInfoLog()', gl.getProgramInfoLog(program)); } @@ -165,18 +179,21 @@ return (this.program = program); }; -Shader.prototype.syncUniforms = function () { +Shader.prototype.syncUniforms = function () +{ var gl = this.gl; this.textureCount = 1; - for (var key in this.uniforms) { + for (var key in this.uniforms) + { var uniform = this.uniforms[key], location = uniform._location, value = uniform.value, i, il; - switch (uniform.type) { + switch (uniform.type) + { // single int value case 'i': case '1i': @@ -282,7 +299,8 @@ // a Color Value case 'c': - if (typeof value === 'number') { + if (typeof value === 'number') + { value = utils.hex2rgb(value); } @@ -311,11 +329,13 @@ // array of 2D Point objects case 'v2v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(2 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 2] = value[i].x; uniform._array[i * 2 + 1] = value[i].y; } @@ -325,11 +345,13 @@ // array of 3D Point objects case 'v3v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(3 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 3] = value[i].x; uniform._array[i * 3 + 1] = value[i].y; uniform._array[i * 3 + 2] = value[i].z; @@ -341,11 +363,13 @@ // array of 4D Point objects case 'v4v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(4 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 4] = value[i].x; uniform._array[i * 4 + 1] = value[i].y; uniform._array[i * 4 + 2] = value[i].z; @@ -359,7 +383,8 @@ // PIXI.Texture case 't': case 'sampler2D': - if (!uniform.value || !uniform.value.baseTexture || !uniform.value.baseTexture.hasLoaded) { + if (!uniform.value || !uniform.value.baseTexture || !uniform.value.baseTexture.hasLoaded) + { break; } @@ -376,7 +401,8 @@ this.textureCount++; // initialize the texture if we haven't yet - if (!uniform._init) { + if (!uniform._init) + { this.initSampler2D(uniform); uniform._init = true; @@ -394,11 +420,13 @@ * Initialises a Sampler2D uniform (which may only be available later on after initUniforms once the texture has loaded) * */ -Shader.prototype.initSampler2D = function (uniform) { +Shader.prototype.initSampler2D = function (uniform) +{ var gl = this.gl; // Extended texture data - if (uniform.textureData) { + if (uniform.textureData) + { var data = uniform.textureData; // GLTexture = mag linear, min linear_mipmap_linear, wrap repeat + gl.generateMipmap(gl.TEXTURE_2D); @@ -417,14 +445,16 @@ var wrapT = (data.wrapT) ? data.wrapT : gl.CLAMP_TO_EDGE; var format = (data.luminance) ? gl.LUMINANCE : gl.RGBA; - if (data.repeat) { + if (data.repeat) + { wrapS = gl.REPEAT; wrapT = gl.REPEAT; } gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, !!data.flipY); - if (data.width) { + if (data.width) + { var width = (data.width) ? data.width : 512; var height = (data.height) ? data.height : 2; var border = (data.border) ? data.border : 0; @@ -432,7 +462,8 @@ // 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 { + 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); } @@ -448,7 +479,8 @@ * Destroys the shader. * */ -Shader.prototype.destroy = function () { +Shader.prototype.destroy = function () +{ this.gl.deleteProgram(this.program); this.gl = null; @@ -459,13 +491,15 @@ this.fragmentSrc = null; }; -Shader.prototype._glCompile = function (type, src) { +Shader.prototype._glCompile = function (type, src) +{ var shader = this.gl.createShader(type); this.gl.shaderSource(shader, src); this.gl.compileShader(shader); - if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) { + if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) + { window.console.log(this.gl.getShaderInfoLog(shader)); return null; } diff --git a/src/core/renderers/webgl/shaders/StripShader.js b/src/core/renderers/webgl/shaders/StripShader.js index 193f6e1..a7abcc6 100644 --- a/src/core/renderers/webgl/shaders/StripShader.js +++ b/src/core/renderers/webgl/shaders/StripShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function StripShader(gl) { +function StripShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -20,7 +21,8 @@ 'varying vec2 vTextureCoord;', - 'void main(void) {', + '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);', @@ -36,7 +38,8 @@ 'varying vec2 vTextureCoord;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vec2(vTextureCoord.x, vTextureCoord.y)) * alpha;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/utils/FilterTexture.js b/src/core/renderers/webgl/utils/FilterTexture.js index d2c8423..4433d44 100644 --- a/src/core/renderers/webgl/utils/FilterTexture.js +++ b/src/core/renderers/webgl/utils/FilterTexture.js @@ -8,7 +8,8 @@ * @param height {number} the vertical range of the filter * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values */ -function FilterTexture(gl, width, height, scaleMode) { +function FilterTexture(gl, width, height, scaleMode) +{ /** * @member {WebGLContext} */ @@ -59,7 +60,8 @@ * Clears the filter texture. * */ -FilterTexture.prototype.clear = function () { +FilterTexture.prototype.clear = function () +{ var gl = this.gl; gl.clearColor(0,0,0, 0); @@ -72,8 +74,10 @@ * @param width {number} the new width of the texture * @param height {number} the new height of the texture */ -FilterTexture.prototype.resize = function (width, height) { - if (this.width === width && this.height === height) { +FilterTexture.prototype.resize = function (width, height) +{ + if (this.width === width && this.height === height) + { return; } @@ -96,7 +100,8 @@ * Destroys the filter texture. * */ -FilterTexture.prototype.destroy = function () { +FilterTexture.prototype.destroy = function () +{ var gl = this.gl; gl.deleteFramebuffer( this.frameBuffer ); gl.deleteTexture( this.texture ); diff --git a/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js b/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js index c4721e9..a63f4d7 100644 --- a/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js +++ b/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js @@ -14,7 +14,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this sprite batch works for. */ -function WebGLFastSpriteBatch(renderer) { +function WebGLFastSpriteBatch(renderer) +{ /** * The renderer instance this sprite batch operates on. * @@ -91,7 +92,8 @@ */ this.lastIndexCount = 0; - for (var i=0, j=0; i < numIndices; i += 6, j += 4) { + 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; @@ -144,7 +146,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.setupContext(); }); } @@ -157,7 +160,8 @@ * * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLFastSpriteBatch.prototype.setupContext = function () { +WebGLFastSpriteBatch.prototype.setupContext = function () +{ var gl = this.renderer.gl; // create a couple of buffers @@ -177,7 +181,8 @@ /** * @param spriteBatch {SpriteBatch} The SpriteBatch container to prepare for. */ -WebGLFastSpriteBatch.prototype.begin = function (spriteBatch) { +WebGLFastSpriteBatch.prototype.begin = function (spriteBatch) +{ this.shader = this.renderer.shaderManager.fastShader; this.matrix = spriteBatch.worldTransform.toArray(true); @@ -187,33 +192,38 @@ /** */ -WebGLFastSpriteBatch.prototype.end = function () { +WebGLFastSpriteBatch.prototype.end = function () +{ this.flush(); }; /** * @param spriteBatch {SpriteBatch} The SpriteBatch container to render. */ -WebGLFastSpriteBatch.prototype.render = function (spriteBatch) { +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) { + if (!sprite.texture._uvs) + { return; } this.currentBaseTexture = sprite.texture.baseTexture; // check blend mode - if (sprite.blendMode !== this.renderer.blendModeManager.currentBlendMode) { + if (sprite.blendMode !== this.renderer.blendModeManager.currentBlendMode) + { this.flush(); this.renderer.blendModeManager.setBlendMode(sprite.blendMode); } - for (var i=0,j= children.length; i= this.size) { + if (this.currentBatchSize >= this.size) + { this.flush(); } }; @@ -362,29 +379,35 @@ /** * */ -WebGLFastSpriteBatch.prototype.flush = function () { +WebGLFastSpriteBatch.prototype.flush = function () +{ // If the batch is length 0 then return as there is nothing to draw - if (this.currentBatchSize === 0) { + if (this.currentBatchSize === 0) + { return; } var gl = this.renderer.gl; // bind the current texture - if (!this.currentBaseTexture._glTextures[gl.id]) { + if (!this.currentBaseTexture._glTextures[gl.id]) + { this.renderer.updateTexture(this.currentBaseTexture, gl); } //TODO-SHOUD THIS BE ELSE??!?!?! - else { + else + { gl.bindTexture(gl.TEXTURE_2D, this.currentBaseTexture._glTextures[gl.id]); } // upload the verts to the buffer - if (this.currentBatchSize > ( this.size * 0.5 ) ) { + if (this.currentBatchSize > ( this.size * 0.5 ) ) + { gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); } - else { + else + { var view = this.vertices.subarray(0, this.currentBatchSize * this.vertByteSize); gl.bufferSubData(gl.ARRAY_BUFFER, 0, view); @@ -405,14 +428,16 @@ * Ends the batch and flushes * */ -WebGLFastSpriteBatch.prototype.stop = function () { +WebGLFastSpriteBatch.prototype.stop = function () +{ this.flush(); }; /** * */ -WebGLFastSpriteBatch.prototype.start = function () { +WebGLFastSpriteBatch.prototype.start = function () +{ var gl = this.renderer.gl; // bind the main texture diff --git a/src/core/renderers/webgl/utils/WebGLGraphics.js b/src/core/renderers/webgl/utils/WebGLGraphics.js index 55f4911..ab8f46e 100644 --- a/src/core/renderers/webgl/utils/WebGLGraphics.js +++ b/src/core/renderers/webgl/utils/WebGLGraphics.js @@ -19,7 +19,8 @@ * @param graphics {Graphics} * @param renderer {WebGLRenderer} */ -WebGLGraphics.renderGraphics = function (graphics, renderer) {//projection, offset) { +WebGLGraphics.renderGraphics = function (graphics, renderer) {//projection, offset) +{ var gl = renderer.gl; var projection = renderer.projection, @@ -27,7 +28,8 @@ shader = renderer.shaderManager.primitiveShader, webGLData; - if (graphics.dirty) { + if (graphics.dirty) + { WebGLGraphics.updateGraphics(graphics, gl); } @@ -35,8 +37,10 @@ // This could be speeded up for sure! - for (var i = 0; i < webGL.data.length; i++) { - if (webGL.data[i].mode === 1) { + for (var i = 0; i < webGL.data.length; i++) + { + if (webGL.data[i].mode === 1) + { webGLData = webGL.data[i]; renderer.stencilManager.pushStencil(graphics, webGLData, renderer); @@ -46,7 +50,8 @@ renderer.stencilManager.popStencil(graphics, webGLData, renderer); } - else { + else + { webGLData = webGL.data[i]; @@ -84,12 +89,14 @@ * @param graphicsData {Graphics} The graphics object to update * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLGraphics.updateGraphics = function (graphics, gl) { +WebGLGraphics.updateGraphics = function (graphics, gl) +{ // get the contexts graphics object var webGL = graphics._webGL[gl.id]; // if the graphics object does not exist in the webGL context time to create it! - if (!webGL) { + if (!webGL) + { webGL = graphics._webGL[gl.id] = {lastIndex:0, data:[], gl:gl}; } @@ -99,11 +106,13 @@ var i; // if the user cleared the graphics object we will need to clear every object - if (graphics.clearDirty) { + if (graphics.clearDirty) + { graphics.clearDirty = false; // lop through and return all the webGLDatas to the object pool so than can be reused later on - for (i = 0; i < webGL.data.length; i++) { + for (i = 0; i < webGL.data.length; i++) + { var graphicsData = webGL.data[i]; graphicsData.reset(); WebGLGraphics.graphicsDataPool.push( graphicsData ); @@ -119,58 +128,72 @@ // loop through the graphics datas and construct each one.. // if the object is a complex fill then the new stencil buffer technique will be used // other wise graphics objects will be pushed into a batch.. - for (i = webGL.lastIndex; i < graphics.graphicsData.length; i++) { + for (i = webGL.lastIndex; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { // need to add the points the the graphics object.. data.points = data.shape.points.slice(); - if (data.shape.closed) { + if (data.shape.closed) + { // close the poly if the value is true! - if (data.points[0] !== data.points[data.points.length-2] || data.points[1] !== data.points[data.points.length-1]) { + if (data.points[0] !== data.points[data.points.length-2] || data.points[1] !== data.points[data.points.length-1]) + { data.points.push(data.points[0], data.points[1]); } } // MAKE SURE WE HAVE THE CORRECT TYPE.. - if (data.fill) { - if (data.points.length >= 6) { - if (data.points.length < 6 * 2) { + if (data.fill) + { + if (data.points.length >= 6) + { + if (data.points.length < 6 * 2) + { webGLData = WebGLGraphics.switchMode(webGL, 0); var canDrawUsingSimple = WebGLGraphics.buildPoly(data, webGLData); // console.log(canDrawUsingSimple); - if (!canDrawUsingSimple) { + if (!canDrawUsingSimple) + { // console.log("<>>>") webGLData = WebGLGraphics.switchMode(webGL, 1); WebGLGraphics.buildComplexPoly(data, webGLData); } } - else { + else + { webGLData = WebGLGraphics.switchMode(webGL, 1); WebGLGraphics.buildComplexPoly(data, webGLData); } } } - if (data.lineWidth > 0) { + if (data.lineWidth > 0) + { webGLData = WebGLGraphics.switchMode(webGL, 0); WebGLGraphics.buildLine(data, webGLData); } } - else { + else + { webGLData = WebGLGraphics.switchMode(webGL, 0); - if (data.type === CONST.SHAPES.RECT) { + if (data.type === CONST.SHAPES.RECT) + { WebGLGraphics.buildRectangle(data, webGLData); } - else if (data.type === CONST.SHAPES.CIRC || data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.CIRC || data.type === CONST.SHAPES.ELIP) + { WebGLGraphics.buildCircle(data, webGLData); } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { WebGLGraphics.buildRoundedRectangle(data, webGLData); } } @@ -179,10 +202,12 @@ } // upload all the dirty data... - for (i = 0; i < webGL.data.length; i++) { + for (i = 0; i < webGL.data.length; i++) + { webGLData = webGL.data[i]; - if (webGLData.dirty) { + if (webGLData.dirty) + { webGLData.upload(); } } @@ -194,18 +219,22 @@ * @param webGL {WebGLContext} * @param type {number} */ -WebGLGraphics.switchMode = function (webGL, type) { +WebGLGraphics.switchMode = function (webGL, type) +{ var webGLData; - if (!webGL.data.length) { + if (!webGL.data.length) + { webGLData = WebGLGraphics.graphicsDataPool.pop() || new WebGLGraphicsData(webGL.gl); webGLData.mode = type; webGL.data.push(webGLData); } - else { + else + { webGLData = webGL.data[webGL.data.length-1]; - if (webGLData.mode !== type || type === 1) { + if (webGLData.mode !== type || type === 1) + { webGLData = WebGLGraphics.graphicsDataPool.pop() || new WebGLGraphicsData(webGL.gl); webGLData.mode = type; webGL.data.push(webGLData); @@ -225,7 +254,8 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildRectangle = function (graphicsData, webGLData) { +WebGLGraphics.buildRectangle = function (graphicsData, webGLData) +{ // --- // // need to convert points to a nice regular data // @@ -235,7 +265,8 @@ var width = rectData.width; var height = rectData.height; - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -265,7 +296,8 @@ indices.push(vertPos, vertPos, vertPos+1, vertPos+2, vertPos+3, vertPos+3); } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = [x, y, @@ -289,7 +321,8 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildRoundedRectangle = function (graphicsData, webGLData) { +WebGLGraphics.buildRoundedRectangle = function (graphicsData, webGLData) +{ var rrectData = graphicsData.shape; var x = rrectData.x; var y = rrectData.y; @@ -305,7 +338,8 @@ recPoints = recPoints.concat(WebGLGraphics.quadraticBezierCurve(x + width, y + radius, x + width, y, x + width - radius, y)); recPoints = recPoints.concat(WebGLGraphics.quadraticBezierCurve(x + radius, y, x, y, x, y + radius)); - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -323,7 +357,8 @@ // var i = 0; - for (i = 0; i < triangles.length; i+=3) { + for (i = 0; i < triangles.length; i+=3) + { indices.push(triangles[i] + vecPos); indices.push(triangles[i] + vecPos); indices.push(triangles[i+1] + vecPos); @@ -332,12 +367,14 @@ } - for (i = 0; i < recPoints.length; i++) { + for (i = 0; i < recPoints.length; i++) + { verts.push(recPoints[i], recPoints[++i], r, g, b, alpha); } } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = recPoints; @@ -362,7 +399,8 @@ * @param toY {number} Destination point y * @return {number[]} */ -WebGLGraphics.quadraticBezierCurve = function (fromX, fromY, cpX, cpY, toX, toY) { +WebGLGraphics.quadraticBezierCurve = function (fromX, fromY, cpX, cpY, toX, toY) +{ var xa, ya, @@ -373,14 +411,16 @@ n = 20, points = []; - function getPt(n1 , n2, perc) { + function getPt(n1 , n2, perc) + { var diff = n2 - n1; return n1 + ( diff * perc ); } var j = 0; - for (var i = 0; i <= n; i++ ) { + for (var i = 0; i <= n; i++ ) + { j = i / n; // The Green Line @@ -406,7 +446,8 @@ * @param graphicsData {Graphics} The graphics object to draw * @param webGLData {object} */ -WebGLGraphics.buildCircle = function (graphicsData, webGLData) { +WebGLGraphics.buildCircle = function (graphicsData, webGLData) +{ // need to convert points to a nice regular data var circleData = graphicsData.shape; var x = circleData.x; @@ -415,11 +456,13 @@ var height; // TODO - bit hacky?? - if (graphicsData.type === CONST.SHAPES.CIRC) { + if (graphicsData.type === CONST.SHAPES.CIRC) + { width = circleData.radius; height = circleData.radius; } - else { + else + { width = circleData.width; height = circleData.height; } @@ -429,7 +472,8 @@ var i = 0; - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -444,7 +488,8 @@ indices.push(vecPos); - for (i = 0; i < totalSegs + 1 ; i++) { + for (i = 0; i < totalSegs + 1 ; i++) + { verts.push(x,y, r, g, b, alpha); verts.push(x + Math.sin(seg * i) * width, @@ -457,12 +502,14 @@ indices.push(vecPos-1); } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = []; - for (i = 0; i < totalSegs + 1; i++) { + for (i = 0; i < totalSegs + 1; i++) + { graphicsData.points.push(x + Math.sin(seg * i) * width, y + Math.cos(seg * i) * height); } @@ -481,18 +528,22 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildLine = function (graphicsData, webGLData) { +WebGLGraphics.buildLine = function (graphicsData, webGLData) +{ // TODO OPTIMISE! var i = 0; var points = graphicsData.points; - if (points.length === 0) { + if (points.length === 0) + { return; } // if the line width is an odd number add 0.5 to align to a whole pixel - if (graphicsData.lineWidth%2) { - for (i = 0; i < points.length; i++) { + if (graphicsData.lineWidth%2) + { + for (i = 0; i < points.length; i++) + { points[i] += 0.5; } } @@ -502,7 +553,8 @@ var lastPoint = new math.Point(points[points.length - 2], points[points.length - 1]); // if the first point is the last point - gonna have issues :) - if (firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) { + if (firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) + { // need to clone as we are going to slightly modify the shape.. points = points.slice(); @@ -562,7 +614,8 @@ verts.push(p1x + perpx , p1y + perpy, r, g, b, alpha); - for (i = 1; i < length-1; i++) { + for (i = 1; i < length-1; i++) + { p1x = points[(i-1)*2]; p1y = points[(i-1)*2 + 1]; @@ -599,7 +652,8 @@ denom = a1*b2 - a2*b1; - if (Math.abs(denom) < 0.1 ) { + if (Math.abs(denom) < 0.1 ) + { denom+=10.1; verts.push(p2x - perpx , p2y - perpy, @@ -618,7 +672,8 @@ pdist = (px -p2x) * (px -p2x) + (py -p2y) + (py -p2y); - if (pdist > 140 * 140) { + if (pdist > 140 * 140) + { perp3x = perpx - perp2x; perp3y = perpy - perp2y; @@ -639,7 +694,8 @@ indexCount++; } - else { + else + { verts.push(px , py); verts.push(r, g, b, alpha); @@ -672,7 +728,8 @@ indices.push(indexStart); - for (i = 0; i < indexCount; i++) { + for (i = 0; i < indexCount; i++) + { indices.push(indexStart++); } @@ -687,11 +744,13 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildComplexPoly = function (graphicsData, webGLData) { +WebGLGraphics.buildComplexPoly = function (graphicsData, webGLData) +{ //TODO - no need to copy this as it gets turned into a FLoat32Array anyways.. var points = graphicsData.points.slice(); - if (points.length < 6) { + if (points.length < 6) + { return; } @@ -711,7 +770,8 @@ var x,y; // get size.. - for (var i = 0; i < points.length; i+=2) { + for (var i = 0; i < points.length; i+=2) + { x = points[i]; y = points[i+1]; @@ -732,7 +792,8 @@ //TODO - this aint needed! var length = points.length / 2; - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { indices.push( i ); } @@ -746,10 +807,12 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildPoly = function (graphicsData, webGLData) { +WebGLGraphics.buildPoly = function (graphicsData, webGLData) +{ var points = graphicsData.points; - if (points.length < 6) { + if (points.length < 6) + { return; } // get first and last point.. figure out the middle! @@ -767,7 +830,8 @@ var triangles = utils.PolyK.Triangulate(points); - if (!triangles) { + if (!triangles) + { return false; } @@ -775,7 +839,8 @@ var i = 0; - for (i = 0; i < triangles.length; i+=3) { + for (i = 0; i < triangles.length; i+=3) + { indices.push(triangles[i] + vertPos); indices.push(triangles[i] + vertPos); indices.push(triangles[i+1] + vertPos); @@ -783,7 +848,8 @@ indices.push(triangles[i+2] + vertPos); } - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { verts.push(points[i * 2], points[i * 2 + 1], r, g, b, alpha); } diff --git a/src/core/renderers/webgl/utils/WebGLGraphicsData.js b/src/core/renderers/webgl/utils/WebGLGraphicsData.js index c56d05e..c739ba7 100644 --- a/src/core/renderers/webgl/utils/WebGLGraphicsData.js +++ b/src/core/renderers/webgl/utils/WebGLGraphicsData.js @@ -2,7 +2,8 @@ * @class * @private */ -function WebGLGraphicsData(gl) { +function WebGLGraphicsData(gl) +{ this.gl = gl; //TODO does this need to be split before uploding?? @@ -22,7 +23,8 @@ /** * */ -WebGLGraphicsData.prototype.reset = function () { +WebGLGraphicsData.prototype.reset = function () +{ this.points.length = 0; this.indices.length = 0; }; @@ -30,7 +32,8 @@ /** * */ -WebGLGraphicsData.prototype.upload = function () { +WebGLGraphicsData.prototype.upload = function () +{ var gl = this.gl; // this.lastIndex = graphics.graphicsData.length; diff --git a/src/core/renderers/webgl/utils/WebGLSpriteBatch.js b/src/core/renderers/webgl/utils/WebGLSpriteBatch.js index 96eaa52..55befbb 100644 --- a/src/core/renderers/webgl/utils/WebGLSpriteBatch.js +++ b/src/core/renderers/webgl/utils/WebGLSpriteBatch.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this sprite batch works for. */ -function WebGLSpriteBatch(renderer) { +function WebGLSpriteBatch(renderer) +{ /** * * @@ -88,7 +89,8 @@ */ this.lastIndexCount = 0; - for (var i=0, j=0; i < numIndices; i += 6, j += 4) { + 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; @@ -162,7 +164,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.setupContext(); }); } @@ -173,7 +176,8 @@ /** * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLSpriteBatch.prototype.setupContext = function () { +WebGLSpriteBatch.prototype.setupContext = function () +{ var gl = this.renderer.gl; // setup default shader @@ -198,7 +202,8 @@ /** * */ -WebGLSpriteBatch.prototype.begin = function () { +WebGLSpriteBatch.prototype.begin = function () +{ // this.shader = this.renderer.shaderManager.defaultShader; this.start(); @@ -206,19 +211,22 @@ /** */ -WebGLSpriteBatch.prototype.end = function () { +WebGLSpriteBatch.prototype.end = function () +{ this.flush(); }; /** * @param sprite {Sprite} the sprite to render when using this spritebatch */ -WebGLSpriteBatch.prototype.render = function (sprite) { +WebGLSpriteBatch.prototype.render = function (sprite) +{ var texture = sprite.texture; //TODO set blend modes.. // check texture.. - if (this.currentBatchSize >= this.size) { + if (this.currentBatchSize >= this.size) + { this.flush(); this.currentBaseTexture = texture.baseTexture; } @@ -227,7 +235,8 @@ var uvs = texture._uvs; // if the uvs have not updated then no point rendering just yet! - if (!uvs) { + if (!uvs) + { return; } @@ -237,7 +246,8 @@ var w0, w1, h0, h1; - if (texture.trim) { + 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; @@ -248,7 +258,8 @@ h0 = h1 + texture.crop.height; } - else { + else + { w0 = (texture.frame.width ) * (1-aX); w1 = (texture.frame.width ) * -aX; @@ -272,7 +283,8 @@ var colors = this.colors; var positions = this.positions; - if (this.renderer.roundPixels) { + if (this.renderer.roundPixels) + { // xy positions[index] = a * w1 + c * h1 + tx | 0; positions[index+1] = d * h1 + b * w1 + ty | 0; @@ -289,7 +301,8 @@ positions[index+15] = a * w1 + c * h0 + tx | 0; positions[index+16] = d * h0 + b * w1 + ty | 0; } - else { + else + { // xy positions[index] = a * w1 + c * h1 + tx; positions[index+1] = d * h1 + b * w1 + ty; @@ -338,11 +351,13 @@ * * @param sprite {TilingSprite} the tilingSprite to render */ -WebGLSpriteBatch.prototype.renderTilingSprite = function (tilingSprite) { +WebGLSpriteBatch.prototype.renderTilingSprite = function (tilingSprite) +{ var texture = tilingSprite.tilingTexture; // check texture.. - if (this.currentBatchSize >= this.size) { + if (this.currentBatchSize >= this.size) + { //return; this.flush(); this.currentBaseTexture = texture.baseTexture; @@ -351,7 +366,8 @@ // set the textures uvs temporarily // TODO create a separate texture so that we can tile part of a texture - if (!tilingSprite._uvs) { + if (!tilingSprite._uvs) + { tilingSprite._uvs = new TextureUvs(); } @@ -454,16 +470,19 @@ * Renders the content and empties the current batch. * */ -WebGLSpriteBatch.prototype.flush = function () { +WebGLSpriteBatch.prototype.flush = function () +{ // If the batch is length 0 then return as there is nothing to draw - if (this.currentBatchSize === 0) { + if (this.currentBatchSize === 0) + { return; } var gl = this.renderer.gl; var shader; - if (this.dirty) { + if (this.dirty) + { this.dirty = false; // bind the main texture gl.activeTexture(gl.TEXTURE0); @@ -482,10 +501,12 @@ } // upload the verts to the buffer - if (this.currentBatchSize > ( this.size * 0.5 ) ) { + if (this.currentBatchSize > ( this.size * 0.5 ) ) + { gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); } - else { + else + { var view = this.positions.subarray(0, this.currentBatchSize * this.vertByteSize); gl.bufferSubData(gl.ARRAY_BUFFER, 0, view); } @@ -502,7 +523,8 @@ var shaderSwap = false; var sprite; - for (var i = 0, j = this.currentBatchSize; i < j; i++) { + for (var i = 0, j = this.currentBatchSize; i < j; i++) + { sprite = this.sprites[i]; @@ -513,24 +535,28 @@ blendSwap = currentBlendMode !== nextBlendMode; shaderSwap = currentShader !== nextShader; // should I use uuidS??? - if (currentBaseTexture !== nextTexture || blendSwap || shaderSwap) { + if (currentBaseTexture !== nextTexture || blendSwap || shaderSwap) + { this.renderBatch(currentBaseTexture, batchSize, start); start = i; batchSize = 0; currentBaseTexture = nextTexture; - if (blendSwap) { + if (blendSwap) + { currentBlendMode = nextBlendMode; this.renderer.blendModeManager.setBlendMode( currentBlendMode ); } - if (shaderSwap) { + if (shaderSwap) + { currentShader = nextShader; shader = currentShader.shaders ? currentShader.shaders[gl.id] : currentShader; - if (!shader) { + if (!shader) + { shader = new Shader(gl, null, currentShader.fragmentSrc, currentShader.uniforms); currentShader.shaders[gl.id] = shader; } @@ -538,7 +564,8 @@ // set shader function??? this.renderer.shaderManager.setShader(shader); - if (shader.dirty) { + if (shader.dirty) + { shader.syncUniforms(); } @@ -569,17 +596,21 @@ * @param size {number} * @param startIndex {number} */ -WebGLSpriteBatch.prototype.renderBatch = function (texture, size, startIndex) { - if (size === 0) { +WebGLSpriteBatch.prototype.renderBatch = function (texture, size, startIndex) +{ + if (size === 0) + { return; } var gl = this.renderer.gl; - if (!texture._glTextures[gl.id]) { + if (!texture._glTextures[gl.id]) + { this.renderer.updateTexture(texture); } - else { + else + { // bind the current texture gl.bindTexture(gl.TEXTURE_2D, texture._glTextures[gl.id]); } @@ -594,7 +625,8 @@ /** * */ -WebGLSpriteBatch.prototype.stop = function () { +WebGLSpriteBatch.prototype.stop = function () +{ this.flush(); this.dirty = true; }; @@ -602,7 +634,8 @@ /** * */ -WebGLSpriteBatch.prototype.start = function () { +WebGLSpriteBatch.prototype.start = function () +{ this.dirty = true; }; @@ -610,7 +643,8 @@ * Destroys the SpriteBatch. * */ -WebGLSpriteBatch.prototype.destroy = function () { +WebGLSpriteBatch.prototype.destroy = function () +{ this.renderer.gl.deleteBuffer(this.vertexBuffer); this.renderer.gl.deleteBuffer(this.indexBuffer); diff --git a/src/core/textures/BaseTexture.js b/src/core/textures/BaseTexture.js index 2bf77d4..513d358 100644 --- a/src/core/textures/BaseTexture.js +++ b/src/core/textures/BaseTexture.js @@ -10,7 +10,8 @@ * @param source {Image|Canvas} the source object of the texture. * @param [scaleMode=scaleModes.DEFAULT] {number} See {@link scaleModes} for possible values */ -function BaseTexture(source, scaleMode) { +function BaseTexture(source, scaleMode) +{ this.uuid = utils.uuid(); /** @@ -123,7 +124,8 @@ this._needsUpdate = false; // if no source passed don't try to load - if (source) { + if (source) + { this.loadSource(source); } @@ -149,13 +151,16 @@ Object.defineProperties(BaseTexture.prototype, { needsUpdate: { - get: function () { + get: function () + { return this._needsUpdate; }, - set: function (val) { + set: function (val) + { this._needsUpdate = val; - if (val) { + if (val) + { this.emit('update', this); } } @@ -171,9 +176,11 @@ * * The logic state after calling `loadSource` directly or indirectly (eg. `fromImage`, `new BaseTexture`) is: * - * if (texture.hasLoaded) { + * if (texture.hasLoaded) + { * // texture ready for use - * } else if (texture.isLoading) { + * } else if (texture.isLoading) + { * // listen to 'loaded' and/or 'error' events on texture * } else { * // not loading, not going to load UNLESS the source is reloaded @@ -183,12 +190,14 @@ * @protected * @param source {Image|Canvas} the source object of the texture. */ -BaseTexture.prototype.loadSource = function (source) { +BaseTexture.prototype.loadSource = function (source) +{ var wasLoading = this.isLoading; this.hasLoaded = false; this.isLoading = false; - if (wasLoading && this.source) { + if (wasLoading && this.source) + { this.source.onload = null; this.source.onerror = null; } @@ -196,20 +205,24 @@ this.source = source; // Apply source if loaded. Otherwise setup appropriate loading monitors. - if ((this.source.complete || this.source.getContext) && this.source.width && this.source.height) { + if ((this.source.complete || this.source.getContext) && this.source.width && this.source.height) + { this._sourceLoaded(); } - else if(!source.getContext) { + else if(!source.getContext) + { // Image fail / not ready this.isLoading = true; var scope = this; - source.onload = function () { + source.onload = function () + { source.onload = null; source.onerror = null; - if(!scope.isLoading) { + if(!scope.isLoading) + { return; } @@ -219,11 +232,13 @@ scope.emit('loaded', scope); }; - source.onerror = function () { + source.onerror = function () + { source.onload = null; source.onerror = null; - if(!scope.isLoading) { + if(!scope.isLoading) + { return; } @@ -234,24 +249,29 @@ // Per http://www.w3.org/TR/html5/embedded-content-0.html#the-img-element // "The value of `complete` can thus change while a script is executing." // So complete needs to be re-checked after the callbacks have been added.. - if (source.complete) { + if (source.complete) + { this.isLoading = false; // ..and if we're complete now, no need for callbacks source.onload = null; source.onerror = null; - if (source.width && source.height) { + if (source.width && source.height) + { this._sourceLoaded(); // If any previous subscribers possible - if (wasLoading) { + if (wasLoading) + { this.emit('loaded', this); } } - else { + else + { // If any previous subscribers possible - if (wasLoading) { + if (wasLoading) + { this.emit('error', this); } } @@ -265,7 +285,8 @@ * * @private */ -BaseTexture.prototype._sourceLoaded = function () { +BaseTexture.prototype._sourceLoaded = function () +{ this.hasLoaded = true; this.width = this.source.naturalWidth || this.source.width; @@ -278,16 +299,20 @@ * Destroys this base texture * */ -BaseTexture.prototype.destroy = function () { - if (this.imageUrl) { +BaseTexture.prototype.destroy = function () +{ + if (this.imageUrl) + { delete utils.BaseTextureCache[this.imageUrl]; delete utils.TextureCache[this.imageUrl]; this.imageUrl = null; - if (!navigator.isCocoonJS) { + if (!navigator.isCocoonJS) + { this.source.src = ''; } } - else if (this.source && this.source._pixiId) { + else if (this.source && this.source._pixiId) + { delete utils.BaseTextureCache[this.source._pixiId]; } this.source = null; @@ -301,7 +326,8 @@ * memory again. * */ -BaseTexture.prototype.dispose = function () { +BaseTexture.prototype.dispose = function () +{ this.emit('dispose', this); }; @@ -311,7 +337,8 @@ * * @param newSrc {string} the path of the image */ -BaseTexture.prototype.updateSourceImage = function (newSrc) { +BaseTexture.prototype.updateSourceImage = function (newSrc) +{ this.source.src = newSrc; this.loadSource(this.source); }; @@ -326,18 +353,22 @@ * @param [scaleMode=scaleModes.DEFAULT] {number} See {@link scaleModes} for possible values * @return BaseTexture */ -BaseTexture.fromImage = function (imageUrl, crossorigin, scaleMode) { +BaseTexture.fromImage = function (imageUrl, crossorigin, scaleMode) +{ var baseTexture = utils.BaseTextureCache[imageUrl]; - if (crossorigin === undefined && imageUrl.indexOf('data:') !== 0) { + if (crossorigin === undefined && imageUrl.indexOf('data:') !== 0) + { crossorigin = true; } - if (!baseTexture) { + if (!baseTexture) + { // new Image() breaks tex loading in some versions of Chrome. // See https://code.google.com/p/chromium/issues/detail?id=238071 var image = new Image();//document.createElement('img'); - if (crossorigin) { + if (crossorigin) + { image.crossOrigin = ''; } @@ -347,7 +378,8 @@ utils.BaseTextureCache[imageUrl] = baseTexture; // if there is an @2x at the end of the url we are going to assume its a highres image - if ( imageUrl.indexOf(CONST.RETINA_PREFIX + '.') !== -1) { + if ( imageUrl.indexOf(CONST.RETINA_PREFIX + '.') !== -1) + { baseTexture.resolution = 2; } } @@ -363,14 +395,17 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return BaseTexture */ -BaseTexture.fromCanvas = function (canvas, scaleMode) { - if (!canvas._pixiId) { +BaseTexture.fromCanvas = function (canvas, scaleMode) +{ + if (!canvas._pixiId) + { canvas._pixiId = 'canvas_' + utils.uuid(); } var baseTexture = utils.BaseTextureCache[canvas._pixiId]; - if (!baseTexture) { + if (!baseTexture) + { baseTexture = new BaseTexture(canvas, scaleMode); utils.BaseTextureCache[canvas._pixiId] = baseTexture; } diff --git a/src/core/textures/RenderTexture.js b/src/core/textures/RenderTexture.js index 6dad20f..53ae796 100644 --- a/src/core/textures/RenderTexture.js +++ b/src/core/textures/RenderTexture.js @@ -46,8 +46,10 @@ * @param [scaleMode] {number} See {@link scaleModes} for possible values * @param [resolution=1] {number} The resolution of the texture being generated */ -function RenderTexture(renderer, width, height, scaleMode, resolution) { - if (!renderer) { +function RenderTexture(renderer, width, height, scaleMode, resolution) +{ + if (!renderer) + { throw new Error('Unable to create RenderTexture, you must pass a renderer into the constructor.'); } @@ -133,7 +135,8 @@ */ this.renderer = renderer; - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { var gl = this.renderer.gl; this.textureBuffer = new FilterTexture(gl, this.width * this.resolution, this.height * this.resolution, this.baseTexture.scaleMode); @@ -142,7 +145,8 @@ this.render = this.renderWebGL; this.projection = new math.Point(this.width*0.5, -this.height*0.5); } - else { + else + { this.render = this.renderCanvas; this.textureBuffer = new CanvasBuffer(this.width* this.resolution, this.height* this.resolution); this.baseTexture.source = this.textureBuffer.canvas; @@ -167,8 +171,10 @@ * @param height {number} The height to resize to. * @param updateBase {boolean} Should the baseTexture.width and height values be resized as well? */ -RenderTexture.prototype.resize = function (width, height, updateBase) { - if (width === this.width && height === this.height) { +RenderTexture.prototype.resize = function (width, height, updateBase) +{ + if (width === this.width && height === this.height) + { return; } @@ -177,17 +183,20 @@ this.width = this.frame.width = this.crop.width = width; this.height = this.frame.height = this.crop.height = height; - if (updateBase) { + if (updateBase) + { this.baseTexture.width = this.width; this.baseTexture.height = this.height; } - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { this.projection.x = this.width / 2; this.projection.y = -this.height / 2; } - if (!this.valid) { + if (!this.valid) + { return; } @@ -198,12 +207,15 @@ * Clears the RenderTexture. * */ -RenderTexture.prototype.clear = function () { - if (!this.valid) { +RenderTexture.prototype.clear = function () +{ + if (!this.valid) + { return; } - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { this.renderer.gl.bindFramebuffer(this.renderer.gl.FRAMEBUFFER, this.textureBuffer.frameBuffer); } @@ -220,19 +232,23 @@ * @param [restoreWorldTransform=true] {boolean} If true the displayObject's worldTransform/worldAlpha and all children * transformations will be restored. Not restoring this information will be a little faster. */ -RenderTexture.prototype.renderWebGL = function (displayObject, matrix, clear, restoreWorldTransform) { - if (!this.valid) { +RenderTexture.prototype.renderWebGL = function (displayObject, matrix, clear, restoreWorldTransform) +{ + if (!this.valid) + { return; } - if (typeof restoreWorldTransform === 'undefined') { + if (typeof restoreWorldTransform === 'undefined') + { restoreWorldTransform = true; } var tempAlpha, tempTransform; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { tempAlpha = displayObject.worldAlpha; tempTransform = displayObject.worldTransform.toArray(); } @@ -245,7 +261,8 @@ wt.identity(); wt.translate(0, this.projection.y * 2); - if (matrix) { + if (matrix) + { wt.append(matrix); } @@ -258,7 +275,8 @@ var children = displayObject.children; var i, j; - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } @@ -269,7 +287,8 @@ gl.bindFramebuffer(gl.FRAMEBUFFER, this.textureBuffer.frameBuffer ); - if (clear) { + if (clear) + { this.textureBuffer.clear(); } @@ -279,11 +298,13 @@ this.renderer.spriteBatch.dirty = true; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { displayObject.worldAlpha = tempAlpha; displayObject.worldTransform.fromArray(tempTransform); - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } } @@ -300,26 +321,31 @@ * @param [restoreWorldTransform=true] {boolean} If true the displayObject's worldTransform/worldAlpha and all children * transformations will be restored. Not restoring this information will be a little faster. */ -RenderTexture.prototype.renderCanvas = function (displayObject, matrix, clear, restoreWorldTransform) { - if (!this.valid) { +RenderTexture.prototype.renderCanvas = function (displayObject, matrix, clear, restoreWorldTransform) +{ + if (!this.valid) + { return; } - if (typeof restoreWorldTransform === 'undefined') { + if (typeof restoreWorldTransform === 'undefined') + { restoreWorldTransform = true; } var tempAlpha, tempTransform; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { tempAlpha = displayObject.worldAlpha; tempTransform = displayObject.worldTransform.toArray(); } var wt = displayObject.worldTransform; wt.identity(); - if (matrix) { + if (matrix) + { wt.append(matrix); } @@ -330,11 +356,13 @@ var children = displayObject.children; var i, j; - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } - if (clear) { + if (clear) + { this.textureBuffer.clear(); } @@ -348,11 +376,13 @@ this.renderer.resolution = realResolution; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { displayObject.worldAlpha = tempAlpha; displayObject.worldTransform.fromArray(tempTransform); - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } } @@ -363,7 +393,8 @@ * * @return {Image} */ -RenderTexture.prototype.getImage = function () { +RenderTexture.prototype.getImage = function () +{ var image = new Image(); image.src = this.getBase64(); return image; @@ -374,7 +405,8 @@ * * @return {string} A base64 encoded string of the texture. */ -RenderTexture.prototype.getBase64 = function () { +RenderTexture.prototype.getBase64 = function () +{ return this.getCanvas().toDataURL(); }; @@ -383,8 +415,10 @@ * * @return {HTMLCanvasElement} A Canvas element with the texture rendered on. */ -RenderTexture.prototype.getCanvas = function () { - if (this.renderer.type === CONST.WEBGL_RENDERER) { +RenderTexture.prototype.getCanvas = function () +{ + if (this.renderer.type === CONST.WEBGL_RENDERER) + { var gl = this.renderer.gl; var width = this.textureBuffer.width; var height = this.textureBuffer.height; @@ -403,7 +437,8 @@ return tempCanvas.canvas; } - else { + else + { return this.textureBuffer.canvas; } }; diff --git a/src/core/textures/Texture.js b/src/core/textures/Texture.js index 3c65909..e97f0aa 100644 --- a/src/core/textures/Texture.js +++ b/src/core/textures/Texture.js @@ -17,7 +17,8 @@ * @param [crop] {Rectangle} The area of original texture * @param [trim] {Rectangle} Trimmed texture rectangle */ -function Texture(baseTexture, frame, crop, trim) { +function Texture(baseTexture, frame, crop, trim) +{ /** * Does this Texture have any frame data assigned to it? * @@ -25,12 +26,14 @@ */ this.noFrame = false; - if (!frame) { + if (!frame) + { this.noFrame = true; frame = new math.Rectangle(0, 0, 1, 1); } - if (baseTexture instanceof Texture) { + if (baseTexture instanceof Texture) + { baseTexture = baseTexture.baseTexture; } @@ -100,13 +103,16 @@ */ this.crop = crop || new math.Rectangle(0, 0, 1, 1); - if (baseTexture.hasLoaded) { - if (this.noFrame) { + if (baseTexture.hasLoaded) + { + if (this.noFrame) + { frame = new math.Rectangle(0, 0, baseTexture.width, baseTexture.height); } this.frame = frame; } - else { + else + { baseTexture.addEventListener('loaded', this.onBaseTextureLoaded.bind(this)); } } @@ -118,19 +124,23 @@ Object.defineProperties(Texture.prototype, { needsUpdate: { - get: function () { + get: function () + { return this.baseTexture.needsUpdate; }, - set: function (val) { + set: function (val) + { this.baseTexture.needsUpdate = val; } }, frame: { - get: function () { + get: function () + { return this._frame; }, - set: function (frame) { + set: function (frame) + { this._frame = frame; this.noFrame = false; @@ -143,20 +153,23 @@ 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 (!this.trim && (frame.x + frame.width > this.baseTexture.width || frame.y + frame.height > this.baseTexture.height)) + { throw new Error('Texture Error: frame does not fit inside the base Texture dimensions ' + this); } this.valid = frame && frame.width && frame.height && this.baseTexture.source && this.baseTexture.hasLoaded; - if (this.trim) { + 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) { + if (this.valid) + { this._updateUvs(); } } @@ -168,11 +181,13 @@ * * @private */ -Texture.prototype.onBaseTextureLoaded = function () { +Texture.prototype.onBaseTextureLoaded = function () +{ var baseTexture = this.baseTexture; baseTexture.removeEventListener('loaded', this.onLoaded); - if (this.noFrame) { + if (this.noFrame) + { this.frame = new math.Rectangle(0, 0, baseTexture.width, baseTexture.height); } @@ -184,8 +199,10 @@ * * @param destroyBase {boolean} Whether to destroy the base texture as well */ -Texture.prototype.destroy = function (destroyBase) { - if (destroyBase) { +Texture.prototype.destroy = function (destroyBase) +{ + if (destroyBase) + { this.baseTexture.destroy(); } @@ -197,8 +214,10 @@ * * @private */ -Texture.prototype._updateUvs = function () { - if (!this._uvs) { +Texture.prototype._updateUvs = function () +{ + if (!this._uvs) + { this._uvs = new TextureUvs(); } @@ -229,10 +248,12 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return Texture */ -Texture.fromImage = function (imageUrl, crossorigin, scaleMode) { +Texture.fromImage = function (imageUrl, crossorigin, scaleMode) +{ var texture = utils.TextureCache[imageUrl]; - if (!texture) { + if (!texture) + { texture = new Texture(BaseTexture.fromImage(imageUrl, crossorigin, scaleMode)); utils.TextureCache[imageUrl] = texture; } @@ -248,9 +269,11 @@ * @param frameId {string} The frame id of the texture * @return Texture */ -Texture.fromFrame = function (frameId) { +Texture.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache '); } return texture; @@ -264,7 +287,8 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return {Texture} */ -Texture.fromCanvas = function (canvas, scaleMode) { +Texture.fromCanvas = function (canvas, scaleMode) +{ return new Texture(BaseTexture.fromCanvas(canvas, scaleMode)); }; @@ -276,7 +300,8 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return {Texture} A Texture */ -Texture.fromVideo = function (video, scaleMode) { +Texture.fromVideo = function (video, scaleMode) +{ return new Texture(VideoBaseTexture.baseTextureFromVideo(video, scaleMode)); }; @@ -287,7 +312,8 @@ * @param texture {Texture} The Texture to add to the cache. * @param id {string} The id that the texture will be stored against. */ -Texture.addTextureToCache = function (texture, id) { +Texture.addTextureToCache = function (texture, id) +{ utils.TextureCache[id] = texture; }; @@ -298,7 +324,8 @@ * @param id {string} The id of the texture to be removed * @return {Texture} The texture that was removed */ -Texture.removeTextureFromCache = function (id) { +Texture.removeTextureFromCache = function (id) +{ var texture = utils.TextureCache[id]; delete utils.TextureCache[id]; diff --git a/src/core/textures/TextureUvs.js b/src/core/textures/TextureUvs.js index b9bbb58..5424d52 100644 --- a/src/core/textures/TextureUvs.js +++ b/src/core/textures/TextureUvs.js @@ -1,4 +1,5 @@ -function TextureUvs() { +function TextureUvs() +{ this.x0 = 0; this.y0 = 0; diff --git a/src/core/textures/VideoBaseTexture.js b/src/core/textures/VideoBaseTexture.js index e3e0c5a..1a826a9 100644 --- a/src/core/textures/VideoBaseTexture.js +++ b/src/core/textures/VideoBaseTexture.js @@ -12,15 +12,18 @@ * @param source {HTMLVideoElement} * @param [scaleMode] {number} See {@link scaleModes} for possible values */ -function VideoBaseTexture(source, scaleMode) { - if (!source){ +function VideoBaseTexture(source, scaleMode) +{ + if (!source) + { throw new Error('No video source element specified.'); } // hook in here to check if video is already available. // BaseTexture looks for a source.complete boolean, plus width & height. - if ((source.readyState === source.HAVE_ENOUGH_DATA || source.readyState === source.HAVE_FUTURE_DATA) && source.width && source.height) { + if ((source.readyState === source.HAVE_ENOUGH_DATA || source.readyState === source.HAVE_FUTURE_DATA) && source.width && source.height) + { source.complete = true; } @@ -31,7 +34,8 @@ this._boundOnUpdate = this._onUpdate.bind(this); this._boundOnCanPlay = this._onCanPlay.bind(this); - if (!source.complete) { + if (!source.complete) + { source.addEventListener('canplay', this._boundOnCanPlay); source.addEventListener('canplaythrough', this._boundOnCanPlay); @@ -47,28 +51,35 @@ VideoBaseTexture.prototype.constructor = VideoBaseTexture; module.exports = VideoBaseTexture; -VideoBaseTexture.prototype._onUpdate = function () { - if (this.autoUpdate) { +VideoBaseTexture.prototype._onUpdate = function () +{ + if (this.autoUpdate) + { window.requestAnimationFrame(this._boundOnUpdate); this.needsUpdate = true; } }; -VideoBaseTexture.prototype._onPlayStart = function () { - if (!this.autoUpdate) { +VideoBaseTexture.prototype._onPlayStart = function () +{ + if (!this.autoUpdate) + { window.requestAnimationFrame(this._boundOnUpdate); this.autoUpdate = true; } }; -VideoBaseTexture.prototype._onPlayStop = function () { +VideoBaseTexture.prototype._onPlayStop = function () +{ this.autoUpdate = false; }; -VideoBaseTexture.prototype._onCanPlay = function () { +VideoBaseTexture.prototype._onCanPlay = function () +{ this.hasLoaded = true; - if (this.source) { + if (this.source) + { this.source.removeEventListener('canplay', this._boundOnCanPlay); this.source.removeEventListener('canplaythrough', this._boundOnCanPlay); @@ -78,15 +89,18 @@ this.source.play(); // prevent multiple loaded dispatches.. - if(!this.__loaded){ + if(!this.__loaded) + { this.__loaded = true; this.emit('loaded', this); } } }; -VideoBaseTexture.prototype.destroy = function () { - if (this.source && this.source._pixiId) { +VideoBaseTexture.prototype.destroy = function () +{ + if (this.source && this.source._pixiId) + { utils.BaseTextureCache[ this.source._pixiId ] = null; delete utils.BaseTextureCache[ this.source._pixiId ]; @@ -105,14 +119,17 @@ * @param scaleMode {number} See {@link scaleModes} for possible values * @return {VideoBaseTexture} */ -VideoBaseTexture.fromVideo = function (video, scaleMode) { - if (!video._pixiId) { +VideoBaseTexture.fromVideo = function (video, scaleMode) +{ + if (!video._pixiId) + { video._pixiId = 'video_' + utils.uuid(); } var baseTexture = utils.BaseTextureCache[video._pixiId]; - if (!baseTexture) { + if (!baseTexture) + { baseTexture = new VideoBaseTexture(video, scaleMode); utils.BaseTextureCache[ video._pixiId ] = baseTexture; } @@ -147,17 +164,21 @@ * @param scaleMode {number} See {@link scaleModes} for possible values * @return {VideoBaseTexture} */ -VideoBaseTexture.fromUrl = function (videoSrc, scaleMode) { +VideoBaseTexture.fromUrl = function (videoSrc, scaleMode) +{ var video = document.createElement('video'); // array of objects or strings - if (Array.isArray(videoSrc)) { - for (var i = 0; i < videoSrc.length; ++i) { + if (Array.isArray(videoSrc)) + { + for (var i = 0; i < videoSrc.length; ++i) + { video.appendChild(createSource(videoSrc.src || videoSrc, videoSrc.mime)); } } // single object or string - else { + else + { video.appendChild(createSource(videoSrc.src || videoSrc, videoSrc.mime)); } @@ -169,8 +190,10 @@ VideoBaseTexture.fromUrls = VideoBaseTexture.fromUrl; -function createSource(path, type) { - if (!type) { +function createSource(path, type) +{ + if (!type) + { type = 'video/' + path.substr(path.lastIndexOf('.') + 1); } diff --git a/src/core/utils/EventData.js b/src/core/utils/EventData.js index 5d55a22..8cdf701 100644 --- a/src/core/utils/EventData.js +++ b/src/core/utils/EventData.js @@ -7,7 +7,8 @@ * @param name {string} The string name of the event that was triggered * @param data {object} Arbitrary event data to pass along */ -function EventData(target, name, data) { +function EventData(target, name, data) +{ // for duck typing in the ".on()" function this.__isEventObject = true; @@ -71,7 +72,8 @@ * Stops the propagation of events up the scene graph (prevents bubbling). * */ -EventData.prototype.stopPropagation = function stopPropagation() { +EventData.prototype.stopPropagation = function stopPropagation() +{ this.stopped = true; }; @@ -79,6 +81,7 @@ * Stops the propagation of events to sibling listeners (no longer calls any listeners). * */ -EventData.prototype.stopImmediatePropagation = function stopImmediatePropagation() { +EventData.prototype.stopImmediatePropagation = function stopImmediatePropagation() +{ this.stoppedImmediate = true; }; diff --git a/src/core/utils/EventTarget.js b/src/core/utils/EventTarget.js index 7ae8820..671a151 100644 --- a/src/core/utils/EventTarget.js +++ b/src/core/utils/EventTarget.js @@ -13,14 +13,16 @@ * var em = new MyEmitter(); * em.emit('eventName', 'some data', 'some more data', {}, null, ...); */ -function eventTarget(obj) { +function eventTarget(obj) +{ /** * Return a list of assigned event listeners. * * @param eventName {string} The events that should be listed. * @return {Array} An array of listener functions */ - obj.listeners = function listeners(eventName) { + obj.listeners = function listeners(eventName) + { this._listeners = this._listeners || {}; return this._listeners[eventName] ? this._listeners[eventName].slice() : []; @@ -33,22 +35,26 @@ * @param eventName {string} The name of the event. * @return {boolean} Indication if we've emitted an event. */ - obj.emit = obj.dispatchEvent = function emit(eventName, data) { + obj.emit = obj.dispatchEvent = function emit(eventName, data) + { this._listeners = this._listeners || {}; // fast return when there are no listeners - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return; } //backwards compat with old method ".emit({ type: 'something' })" - if (typeof eventName === 'object') { + if (typeof eventName === 'object') + { data = eventName; eventName = eventName.type; } //ensure we are using a real pixi event - if (!data || data.__isEventObject !== true) { + if (!data || data.__isEventObject !== true) + { data = new EventData(this, eventName, data); } @@ -58,23 +64,27 @@ fn = listeners[0], i; - for (i = 0; i < length; fn = listeners[++i]) { + for (i = 0; i < length; fn = listeners[++i]) + { //call the event listener fn.call(this, data); //if "stopImmediatePropagation" is called, stop calling sibling events - if (data.stoppedImmediate) { + if (data.stoppedImmediate) + { return this; } } //if "stopPropagation" is called then don't bubble the event - if (data.stopped) { + if (data.stopped) + { return this; } //bubble this event up the scene graph - if (this.parent && this.parent.emit) { + if (this.parent && this.parent.emit) + { this.parent.emit.call(this.parent, eventName, data); } @@ -88,7 +98,8 @@ * @param eventName {string} Name of the event. * @param callback {Functon} fn Callback function. */ - obj.on = obj.addEventListener = function on(eventName, fn) { + obj.on = obj.addEventListener = function on(eventName, fn) + { this._listeners = this._listeners || {}; (this._listeners[eventName] = this._listeners[eventName] || []) @@ -103,11 +114,13 @@ * @param eventName {string} Name of the event. * @param callback {Function} Callback function. */ - obj.once = function once(eventName, fn) { + obj.once = function once(eventName, fn) + { this._listeners = this._listeners || {}; var self = this; - function onceHandlerWrapper() { + function onceHandlerWrapper() + { fn.apply(self.off(eventName, onceHandlerWrapper), arguments); } onceHandlerWrapper._originalHandler = fn; @@ -122,23 +135,28 @@ * @param eventName {string} The event we want to remove. * @param callback {Function} The listener that we need to find. */ - obj.off = obj.removeEventListener = function off(eventName, fn) { + obj.off = obj.removeEventListener = function off(eventName, fn) + { this._listeners = this._listeners || {}; - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return this; } var list = this._listeners[eventName], i = fn ? list.length : 0; - while(i-- > 0) { - if (list[i] === fn || list[i]._originalHandler === fn) { + while(i-- > 0) + { + if (list[i] === fn || list[i]._originalHandler === fn) + { list.splice(i, 1); } } - if (list.length === 0) { + if (list.length === 0) + { delete this._listeners[eventName]; } @@ -150,10 +168,12 @@ * * @param eventName {string} The event you want to remove all listeners for. */ - obj.removeAllListeners = function removeAllListeners(eventName) { + obj.removeAllListeners = function removeAllListeners(eventName) + { this._listeners = this._listeners || {}; - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return this; } @@ -169,7 +189,8 @@ * * @param object {object} The obj to mix into */ - mixin: function mixin(obj) { + mixin: function mixin(obj) + { eventTarget(obj); } }; diff --git a/src/core/utils/PolyK.js b/src/core/utils/PolyK.js index 7325141..5e20c2b 100644 --- a/src/core/utils/PolyK.js +++ b/src/core/utils/PolyK.js @@ -47,7 +47,8 @@ * Triangulates shapes for webGL graphic fills. * */ -PolyK.Triangulate = function (p) { +PolyK.Triangulate = function (p) +{ var sign = true; var n = p.length >> 1; @@ -59,7 +60,8 @@ i = 0; var al = n; - while(al > 3) { + while(al > 3) + { var i0 = avl[(i+0)%al]; var i1 = avl[(i+1)%al]; var i2 = avl[(i+2)%al]; @@ -69,29 +71,35 @@ var cx = p[2*i2], cy = p[2*i2+1]; var earFound = false; - if (PolyK._convex(ax, ay, bx, by, cx, cy, sign)) { + if (PolyK._convex(ax, ay, bx, by, cx, cy, sign)) + { earFound = true; - for (var j = 0; j < al; j++) { + for (var j = 0; j < al; j++) + { var vi = avl[j]; if (vi === i0 || vi === i1 || vi === i2) continue; - if (PolyK._PointInTriangle(p[2*vi], p[2*vi+1], ax, ay, bx, by, cx, cy)) { + if (PolyK._PointInTriangle(p[2*vi], p[2*vi+1], ax, ay, bx, by, cx, cy)) + { earFound = false; break; } } } - if (earFound) { + if (earFound) + { tgs.push(i0, i1, i2); avl.splice((i+1)%al, 1); al--; i = 0; } - else if (i++ > 3*al) { + else if (i++ > 3*al) + { // need to flip flip reverse it! // reset! - if (sign) { + if (sign) + { tgs = []; avl = []; for (i = 0; i < n; i++) avl.push(i); @@ -101,7 +109,8 @@ sign = false; } - else { + else + { // window.console.log("PIXI Warning: shape too complex to fill"); return null; } @@ -126,7 +135,8 @@ * @private * @return {boolean} */ -PolyK._PointInTriangle = function (px, py, ax, ay, bx, by, cx, cy) { +PolyK._PointInTriangle = function (px, py, ax, ay, bx, by, cx, cy) +{ var v0x = cx-ax; var v0y = cy-ay; var v1x = bx-ax; @@ -154,6 +164,7 @@ * @private * @return {boolean} */ -PolyK._convex = function (ax, ay, bx, by, cx, cy, sign) { +PolyK._convex = function (ax, ay, bx, by, cx, cy, sign) +{ return ((ay-by)*(cx-bx) + (bx-ax)*(cy-by) >= 0) === sign; }; diff --git a/src/core/utils/index.js b/src/core/utils/index.js index ade9831..bfae7ae 100644 --- a/src/core/utils/index.js +++ b/src/core/utils/index.js @@ -16,7 +16,8 @@ * * @return {number} The next uuid to use. */ - uuid: function () { + uuid: function () + { return ++utils._uid; }, @@ -26,7 +27,8 @@ * @param hex {number} * @return {number[]} An array representing the [R, G, B] of the color. */ - hex2rgb: function (hex, out) { + hex2rgb: function (hex, out) + { out = out || []; out[0] = (hex >> 16 & 0xFF) / 255; @@ -42,7 +44,8 @@ * @param hex {number} * @return {string} The string color. */ - hex2string: function (hex) { + hex2string: function (hex) + { hex = hex.toString(16); hex = '000000'.substr(0, 6 - hex.length) + hex; @@ -55,7 +58,8 @@ * @param rgb {number[]} * @return {number} The color number */ - rgb2hex: function (rgb) { + rgb2hex: function (rgb) + { return ((rgb[0]*255 << 16) + (rgb[1]*255 << 8) + rgb[2]*255); }, @@ -64,8 +68,10 @@ * * @return {boolean} whether they are supported */ - canUseNewCanvasBlendModes: function () { - if (typeof document === 'undefined') { + canUseNewCanvasBlendModes: function () + { + if (typeof document === 'undefined') + { return false; } @@ -93,15 +99,19 @@ * @param number {number} * @return {number} the closest number that is a power of two */ - getNextPowerOfTwo: function (number) { + getNextPowerOfTwo: function (number) + { // see: http://en.wikipedia.org/wiki/Power_of_two#Fast_algorithm_to_check_if_a_positive_number_is_a_power_of_two - if (number > 0 && (number & (number - 1)) === 0) { + if (number > 0 && (number & (number - 1)) === 0) + { return number; } - else { + else + { var result = 1; - while (result < number) { + while (result < number) + { result <<= 1; } @@ -116,7 +126,8 @@ * @param height {number} * @return {boolean} */ - isPowerOfTwo: function (width, height) { + isPowerOfTwo: function (width, height) + { return (width > 0 && (width & (width - 1)) === 0 && height > 0 && (height & (height - 1)) === 0); }, @@ -130,12 +141,15 @@ * @constant * @static */ - sayHello: function (type) { - if (utils._saidHello) { + sayHello: function (type) + { + if (utils._saidHello) + { return; } - if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) { + if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) + { var args = [ '%c %c %c Pixi.js ' + CONST.VERSION + ' - ' + type + ' %c ' + ' %c ' + ' http://www.pixijs.com/ %c %c ♥%c♥%c♥ ', 'background: #ff66a5', @@ -151,7 +165,8 @@ console.log.apply(console, args); //jshint ignore:line } - else if (window.console) { + else if (window.console) + { console.log('Pixi.js ' + CONST.VERSION + ' - ' + type + ' - http://www.pixijs.com/'); //jshint ignore:line } @@ -166,15 +181,19 @@ * @class * @namespace PIXI */ - AjaxRequest: function () { + AjaxRequest: function () + { var activexmodes = ['Msxml2.XMLHTTP.6.0', 'Msxml2.XMLHTTP.3.0', 'Microsoft.XMLHTTP']; //activeX versions to check for in IE - if (window.ActiveXObject) { //Test for support for ActiveXObject in IE first (as XMLHttpRequest in IE7 is broken) - for (var i=0; i= this.textures.length) { + else if (round >= this.textures.length) + { this.gotoAndStop(this.textures.length - 1); - if (this.onComplete) { + if (this.onComplete) + { this.onComplete(); } } @@ -167,10 +182,12 @@ * @static * @param frames {string[]} the array of frames ids the movieclip will use as its texture frames */ -MovieClip.fromFrames = function (frames) { +MovieClip.fromFrames = function (frames) +{ var textures = []; - for (var i = 0; i < frames.length; ++i) { + for (var i = 0; i < frames.length; ++i) + { textures.push(new core.Texture.fromFrame(frames[i])); } @@ -183,10 +200,12 @@ * @static * @param images {string[]} the array of image urls the movieclip will use as its texture frames */ -MovieClip.fromImages = function (images) { +MovieClip.fromImages = function (images) +{ var textures = []; - for (var i = 0; i < images.length; ++i) { + for (var i = 0; i < images.length; ++i) + { textures.push(new core.Texture.fromImage(images[i])); } diff --git a/src/extras/Rope.js b/src/extras/Rope.js index c157ec4..9c87bc0 100644 --- a/src/extras/Rope.js +++ b/src/extras/Rope.js @@ -9,7 +9,8 @@ * @param {Array} points - An array of {Point}. * */ -function Rope(texture, points) { +function Rope(texture, points) +{ Strip.call(this, texture); this.points = points; @@ -31,10 +32,12 @@ * Refreshes * */ -Rope.prototype.refresh = function () { +Rope.prototype.refresh = function () +{ var points = this.points; - if (points.length < 1) { + if (points.length < 1) + { return; } @@ -59,20 +62,23 @@ var total = points.length, point, index, amount; - for (var i = 1; i < total; i++) { + for (var i = 1; i < total; i++) + { point = points[i]; index = i * 4; // time to do some smart drawing! amount = i / (total-1); - if (i%2) { + if (i%2) + { uvs[index] = amount; uvs[index+1] = 0; uvs[index+2] = amount; uvs[index+3] = 1; } - else { + else + { uvs[index] = amount; uvs[index+1] = 0; @@ -95,10 +101,12 @@ * * @private */ -Rope.prototype.updateTransform = function () { +Rope.prototype.updateTransform = function () +{ var points = this.points; - if (points.length < 1) { + if (points.length < 1) + { return; } @@ -113,14 +121,17 @@ var total = points.length, point, index, ratio, perpLength, num; - for (var i = 0; i < total; i++) { + for (var i = 0; i < total; i++) + { point = points[i]; index = i * 4; - if (i < points.length-1) { + if (i < points.length-1) + { nextPoint = points[i+1]; } - else { + else + { nextPoint = point; } @@ -129,7 +140,8 @@ ratio = (1 - (i / (total-1))) * 10; - if (ratio > 1) { + if (ratio > 1) + { ratio = 1; } @@ -157,7 +169,8 @@ * * @param texture {Texture} the texture that will be used */ -Rope.prototype.setTexture = function (texture) { +Rope.prototype.setTexture = function (texture) +{ // stop current texture this.texture = texture; //this.updateFrame = true; diff --git a/src/extras/Strip.js b/src/extras/Strip.js index c5e378f..57691b5 100644 --- a/src/extras/Strip.js +++ b/src/extras/Strip.js @@ -10,7 +10,8 @@ * @param height {number} the height * */ -function Strip(texture) { +function Strip(texture) +{ core.DisplayObjectContainer.call(this); /** @@ -70,9 +71,11 @@ * * @param renderer {WebGLRenderer} */ -Strip.prototype.renderWebGL = function (renderer) { +Strip.prototype.renderWebGL = function (renderer) +{ // if the sprite is not visible or the alpha is 0 then no need to render this element - if (!this.visible || this.alpha <= 0) { + if (!this.visible || this.alpha <= 0) + { return; } @@ -81,7 +84,8 @@ renderer.spriteBatch.stop(); // init! init! - if (!this._vertexBuffer) { + if (!this._vertexBuffer) + { this._initWebGL(renderer); } @@ -96,7 +100,8 @@ //TODO check culling }; -Strip.prototype._initWebGL = function (renderer) { +Strip.prototype._initWebGL = function (renderer) +{ // build the strip! var gl = renderer.gl; @@ -118,7 +123,8 @@ gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this.indices, gl.STATIC_DRAW); }; -Strip.prototype._renderStrip = function (renderer) { +Strip.prototype._renderStrip = function (renderer) +{ var gl = renderer.gl; var projection = renderer.projection, offset = renderer.offset, @@ -137,7 +143,8 @@ gl.uniform2f(shader.offsetVector, -offset.x, -offset.y); gl.uniform1f(shader.alpha, this.worldAlpha); - if (!this.dirty) { + if (!this.dirty) + { gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexBuffer); gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); @@ -150,10 +157,12 @@ gl.activeTexture(gl.TEXTURE0); // check if a texture is dirty.. - if (this.texture.baseTexture._dirty[gl.id]) { + if (this.texture.baseTexture._dirty[gl.id]) + { renderer.updateTexture(this.texture.baseTexture); } - else { + else + { // bind the current texture gl.bindTexture(gl.TEXTURE_2D, this.texture.baseTexture._glTextures[gl.id]); } @@ -163,7 +172,8 @@ } - else { + else + { this.dirty = false; gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexBuffer); @@ -178,10 +188,12 @@ gl.activeTexture(gl.TEXTURE0); // check if a texture is dirty.. - if (this.texture.baseTexture._dirty[gl.id]) { + if (this.texture.baseTexture._dirty[gl.id]) + { renderer.updateTexture(this.texture.baseTexture); } - else { + else + { gl.bindTexture(gl.TEXTURE_2D, this.texture.baseTexture._glTextures[gl.id]); } @@ -203,27 +215,33 @@ * * @param renderer {CanvasRenderer} */ -Strip.prototype.renderCanvas = function (renderer) { +Strip.prototype.renderCanvas = function (renderer) +{ var context = renderer.context; var transform = this.worldTransform; - if (renderer.roundPixels) { + if (renderer.roundPixels) + { context.setTransform(transform.a, transform.b, transform.c, transform.d, transform.tx | 0, transform.ty | 0); } - else { + else + { context.setTransform(transform.a, transform.b, transform.c, transform.d, transform.tx, transform.ty); } - if (this.drawMode === Strip.DrawModes.TRIANGLE_STRIP) { + if (this.drawMode === Strip.DrawModes.TRIANGLE_STRIP) + { this._renderCanvasTriangleStrip(context); } - else { + else + { this._renderCanvasTriangles(context); } }; -Strip.prototype._renderCanvasTriangleStrip = function (context) { +Strip.prototype._renderCanvasTriangleStrip = function (context) +{ // draw triangles!! var vertices = this.vertices; var uvs = this.uvs; @@ -231,14 +249,16 @@ var length = vertices.length / 2; // this.count++; - for (var i = 0; i < length - 2; i++) { + for (var i = 0; i < length - 2; i++) + { // draw some triangles! var index = i * 2; this._renderCanvasDrawTriangle(context, vertices, uvs, index, (index + 2), (index + 4)); } }; -Strip.prototype._renderCanvasTriangles = function (context) { +Strip.prototype._renderCanvasTriangles = function (context) +{ // draw triangles!! var vertices = this.vertices; var uvs = this.uvs; @@ -247,14 +267,16 @@ var length = indices.length; // this.count++; - for (var i = 0; i < length; i += 3) { + for (var i = 0; i < length; i += 3) + { // draw some triangles! var index0 = indices[i] * 2, index1 = indices[i + 1] * 2, index2 = indices[i + 2] * 2; this._renderCanvasDrawTriangle(context, vertices, uvs, index0, index1, index2); } }; -Strip.prototype._renderCanvasDrawTriangle = function (context, vertices, uvs, index0, index1, index2) { +Strip.prototype._renderCanvasDrawTriangle = function (context, vertices, uvs, index0, index1, index2) +{ var textureSource = this.texture.baseTexture.source; var textureWidth = this.texture.width; var textureHeight = this.texture.height; @@ -265,7 +287,8 @@ var u0 = uvs[index0] * textureWidth, u1 = uvs[index1] * textureWidth, u2 = uvs[index2] * textureWidth; var v0 = uvs[index0 + 1] * textureHeight, v1 = uvs[index1 + 1] * textureHeight, v2 = uvs[index2 + 1] * textureHeight; - if (this.canvasPadding > 0) { + if (this.canvasPadding > 0) + { var paddingX = this.canvasPadding / this.worldTransform.a; var paddingY = this.canvasPadding / this.worldTransform.d; var centerX = (x0 + x1 + x2) / 3; @@ -332,7 +355,8 @@ * @param strip {Strip} The Strip to render * @private */ -Strip.prototype.renderStripFlat = function (strip) { +Strip.prototype.renderStripFlat = function (strip) +{ var context = this.context; var vertices = strip.vertices; @@ -340,7 +364,8 @@ // this.count++; context.beginPath(); - for (var i=1; i < length-2; i++) { + for (var i=1; i < length-2; i++) + { // draw some triangles! var index = i*2; @@ -358,7 +383,8 @@ }; /* -Strip.prototype.setTexture = function (texture) { +Strip.prototype.setTexture = function (texture) +{ //TODO SET THE TEXTURES //TODO VISIBILITY @@ -377,7 +403,8 @@ * @private */ -Strip.prototype.onTextureUpdate = function () { +Strip.prototype.onTextureUpdate = function () +{ this.updateFrame = true; }; @@ -387,7 +414,8 @@ * @param matrix {Matrix} the transformation matrix of the sprite * @return {Rectangle} the framing rectangle */ -Strip.prototype.getBounds = function (matrix) { +Strip.prototype.getBounds = function (matrix) +{ var worldTransform = matrix || this.worldTransform; var a = worldTransform.a; @@ -404,7 +432,8 @@ var minY = Infinity; var vertices = this.vertices; - for (var i = 0, n = vertices.length; i < n; i += 2) { + for (var i = 0, n = vertices.length; i < n; i += 2) + { var rawX = vertices[i], rawY = vertices[i + 1]; var x = (a * rawX) + (c * rawY) + tx; var y = (d * rawY) + (b * rawX) + ty; @@ -416,7 +445,8 @@ maxY = y > maxY ? y : maxY; } - if (minX === -Infinity || maxY === Infinity) { + if (minX === -Infinity || maxY === Infinity) + { return core.math.Rectangle.EMPTY; } diff --git a/src/extras/TilingSprite.js b/src/extras/TilingSprite.js index 3ac22df..31da393 100644 --- a/src/extras/TilingSprite.js +++ b/src/extras/TilingSprite.js @@ -10,7 +10,8 @@ * @param width {number} the width of the tiling sprite * @param height {number} the height of the tiling sprite */ -function TilingSprite(texture, width, height) { +function TilingSprite(texture, width, height) +{ core.Sprite.call( this, texture); /** @@ -86,10 +87,12 @@ * @memberof TilingSprite# */ width: { - get: function () { + get: function () + { return this._width; }, - set: function (value) { + set: function (value) + { this._width = value; } }, @@ -101,20 +104,25 @@ * @memberof TilingSprite# */ height: { - get: function () { + get: function () + { return this._height; }, - set: function (value) { + set: function (value) + { this._height = value; } }, texture: { - get: function () { + get: function () + { return this._texture; }, - set: function (value) { - if (this._texture === value) { + set: function (value) + { + if (this._texture === value) + { return; } @@ -130,51 +138,61 @@ * * @param renderer {WebGLRenderer} */ -TilingSprite.prototype.renderWebGL = function (renderer) { - if (!this.visible || this.alpha <= 0) { +TilingSprite.prototype.renderWebGL = function (renderer) +{ + if (!this.visible || this.alpha <= 0) + { return; } var i, j; - if (this._mask) { + if (this._mask) + { renderer.spriteBatch.stop(); renderer.maskManager.pushMask(this.mask, renderer); renderer.spriteBatch.start(); } - if (this._filters) { + if (this._filters) + { renderer.spriteBatch.flush(); renderer.filterManager.pushFilter(this._filterBlock); } - if (!this.tilingTexture || this.refreshTexture) { + if (!this.tilingTexture || this.refreshTexture) + { this.generateTilingTexture(true); - if (this.tilingTexture && this.tilingTexture.needsUpdate) { + if (this.tilingTexture && this.tilingTexture.needsUpdate) + { //TODO - tweaking renderer.updateTexture(this.tilingTexture.baseTexture); this.tilingTexture.needsUpdate = false; // this.tilingTexture._uvs = null; } } - else { + else + { renderer.spriteBatch.renderTilingSprite(this); } // simple render children! - for (i=0,j=this.children.length; i= 0 && index <= this.children.length) { - if (child.parent) { + if (index >= 0 && index <= this.children.length) + { + if (child.parent) + { child.parent.removeChild(child); } @@ -154,7 +173,8 @@ return child; } - else { + else + { throw new Error(child + 'addChildAt: The index '+ index +' supplied is out of bounds ' + this.children.length); } }; @@ -165,15 +185,18 @@ * @param child {DisplayObject} * @param child2 {DisplayObject} */ -DisplayObjectContainer.prototype.swapChildren = function (child, child2) { - if (child === child2) { +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) { + if (index1 < 0 || index2 < 0) + { throw new Error('swapChildren: Both the supplied DisplayObjects must be a child of the caller.'); } @@ -187,10 +210,12 @@ * @param child {DisplayObject} The DisplayObject instance to identify * @return {Number} The index position of the child display object to identify */ -DisplayObjectContainer.prototype.getChildIndex = function (child) { +DisplayObjectContainer.prototype.getChildIndex = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { throw new Error('The supplied DisplayObject must be a child of the caller'); } @@ -203,8 +228,10 @@ * @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 */ -DisplayObjectContainer.prototype.setChildIndex = function (child, index) { - if (index < 0 || index >= this.children.length) { +DisplayObjectContainer.prototype.setChildIndex = function (child, index) +{ + if (index < 0 || index >= this.children.length) + { throw new Error('The supplied index is out of bounds'); } @@ -220,8 +247,10 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child at the given index, if any. */ -DisplayObjectContainer.prototype.getChildAt = function (index) { - if (index < 0 || index >= this.children.length) { +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'); } @@ -234,10 +263,12 @@ * @param child {DisplayObject} The DisplayObject to remove * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChild = function (child) { +DisplayObjectContainer.prototype.removeChild = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { return; } @@ -250,7 +281,8 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChildAt = function (index) { +DisplayObjectContainer.prototype.removeChildAt = function (index) +{ var child = this.getChildAt(index); child.parent = null; @@ -265,24 +297,29 @@ * @param beginIndex {Number} The beginning position. Default value is 0. * @param endIndex {Number} The ending position. Default value is size of the container. */ -DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) { +DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) +{ var begin = beginIndex || 0; var end = typeof endIndex === 'number' ? endIndex : this.children.length; var range = end - begin; - if (range > 0 && range <= end) { + if (range > 0 && range <= end) + { var removed = this.children.splice(begin, range); - for (var i = 0; i < removed.length; ++i) { + for (var i = 0; i < removed.length; ++i) + { removed[i].parent = null; } return removed; } - else if (range === 0 && this.children.length === 0) { + else if (range === 0 && this.children.length === 0) + { return []; } - else { + else + { throw new RangeError('removeChildren: numeric values are outside the acceptable range.'); } }; @@ -291,7 +328,8 @@ * Generates and updates the cached sprite for this object. * */ -DisplayObjectContainer.prototype.updateCachedSprite = function () { +DisplayObjectContainer.prototype.updateCachedSprite = function () +{ this._generateCachedSprite(); }; @@ -304,7 +342,8 @@ * @param renderer {CanvasRenderer|WebGLRenderer} The renderer used to generate the texture. * @return {Texture} a texture of the graphics object */ -DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) { +DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) +{ var bounds = this.getLocalBounds(); var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0, renderer, scaleMode, resolution); @@ -322,18 +361,22 @@ * * @private */ -DisplayObjectContainer.prototype.updateTransform = function () { - if (!this.visible) { +DisplayObjectContainer.prototype.updateTransform = function () +{ + if (!this.visible) + { return; } this.displayObjectUpdateTransform(); - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { return; } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } }; @@ -346,8 +389,10 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getBounds = function () { - if (this.children.length === 0) { +DisplayObjectContainer.prototype.getBounds = function () +{ + if (this.children.length === 0) + { return math.Rectangle.EMPTY; } @@ -365,10 +410,12 @@ var childVisible = false; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -386,7 +433,8 @@ maxY = maxY > childMaxY ? maxY : childMaxY; } - if (!childVisible) { + if (!childVisible) + { return math.Rectangle.EMPTY; } @@ -407,12 +455,14 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getLocalBounds = function () { +DisplayObjectContainer.prototype.getLocalBounds = function () +{ var matrixCache = this.worldTransform; this.worldTransform = math.Matrix.IDENTITY; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } @@ -428,13 +478,16 @@ * * @param renderer {WebGLRenderer} The renderer */ -DisplayObjectContainer.prototype.renderWebGL = function (renderer) { +DisplayObjectContainer.prototype.renderWebGL = function (renderer) +{ // if the object is not visible or the alpha is 0 then no need to render this element - if (!this.visible || this.alpha <= 0) { + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } @@ -442,14 +495,17 @@ var i, j; // do a quick check to see if this element has a mask or a filter. - if (this._mask || this._filters) { + if (this._mask || this._filters) + { // push filter first as we need to ensure the stencil buffer is correct for any masking - if (this._filters) { + if (this._filters) + { renderer.spriteBatch.flush(); renderer.filterManager.pushFilter(this._filterBlock); } - if (this._mask) { + if (this._mask) + { renderer.spriteBatch.stop(); renderer.maskManager.pushMask(this.mask, renderer); renderer.spriteBatch.start(); @@ -459,36 +515,42 @@ this._renderWebGL(renderer); // now loop through the children and make sure they get rendered - for (i = 0, j = this.children.length; i < j; i++) { + for (i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderWebGL(renderer); } // time to stop the sprite batch as either a mask element or a filter draw will happen next renderer.spriteBatch.stop(); - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(this._mask, renderer); } - if (this._filters) { + if (this._filters) + { renderer.filterManager.popFilter(); } renderer.spriteBatch.start(); } - else { + else + { this._renderWebGL(renderer); // simple render children! - for (i = 0, j = this.children.length; i < j; ++i) { + for (i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderWebGL(renderer); } } }; -DisplayObjectContainer.prototype._renderWebGL = function (renderer) { +DisplayObjectContainer.prototype._renderWebGL = function (renderer) +{ // this is where content itself gets renderd.. @@ -499,25 +561,31 @@ * * @param renderer {CanvasRenderer} The renderer */ -DisplayObjectContainer.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0) { +DisplayObjectContainer.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -528,13 +596,16 @@ * @param renderer {WebGLRenderer|CanvasRenderer} The renderer * @private */ -DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) { +DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) +{ this._cachedSprite.worldAlpha = this.worldAlpha; - if (renderer.gl) { + if (renderer.gl) + { this._cachedSprite.renderWebGL(renderer); } - else { + else + { this._cachedSprite.renderCanvas(renderer); } }; @@ -544,10 +615,12 @@ * * @private */ -DisplayObjectContainer.prototype._generateCachedSprite = function () { +DisplayObjectContainer.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { // TODO - RenderTexture now *requires* a renderer instance, so this is like broken // because `renderer` isn't actually in scope here :P var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0); @@ -555,7 +628,8 @@ this._cachedSprite = new Sprite(renderTexture); this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.texture.resize(bounds.width | 0, bounds.height | 0); } @@ -580,8 +654,10 @@ * * @private */ -DisplayObjectContainer.prototype._destroyCachedSprite = function () { - if (!this._cachedSprite) { +DisplayObjectContainer.prototype._destroyCachedSprite = function () +{ + if (!this._cachedSprite) + { return; } diff --git a/src/core/display/Sprite.js b/src/core/display/Sprite.js index 707da24..5862aef 100644 --- a/src/core/display/Sprite.js +++ b/src/core/display/Sprite.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param texture {Texture} The texture for this sprite */ -function Sprite(texture) { +function Sprite(texture) +{ DisplayObjectContainer.call(this); /** @@ -85,12 +86,14 @@ this.texture = texture || Texture.EMPTY; } -Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) { +Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) +{ DisplayObjectContainer.prototype.destroy.call(this); this.anchor = null; - if (destroyTexture) { + if (destroyTexture) + { this._texture.destroy(destroyBaseTexture); } @@ -111,10 +114,12 @@ * @memberof Sprite# */ width: { - get: function () { + get: function () + { return this.scale.x * this.texture.frame.width; }, - set: function (value) { + set: function (value) + { this.scale.x = value / this.texture.frame.width; this._width = value; } @@ -127,10 +132,12 @@ * @memberof Sprite# */ height: { - get: function () { + get: function () + { return this.scale.y * this.texture.frame.height; }, - set: function (value) { + set: function (value) + { this.scale.y = value / this.texture.frame.height; this._height = value; } @@ -143,23 +150,29 @@ * @memberof Sprite# */ texture: { - get: function () { + get: function () + { return this._texture; }, - set: function (value) { - if (this._texture === value) { + set: function (value) + { + if (this._texture === value) + { return; } this._texture = value; this.cachedTint = 0xFFFFFF; - if (value) { + if (value) + { // wait for the texture to load - if (value.baseTexture.hasLoaded) { + if (value.baseTexture.hasLoaded) + { this._onTextureUpdate(); } - else { + else + { value.once('update', this._onTextureUpdate.bind(this)); } } @@ -172,18 +185,22 @@ * * @private */ -Sprite.prototype._onTextureUpdate = function () { +Sprite.prototype._onTextureUpdate = function () +{ // so if _width is 0 then width was not set.. - if (this._width) { + if (this._width) + { this.scale.x = this._width / this.texture.frame.width; } - if (this._height) { + if (this._height) + { this.scale.y = this._height / this.texture.frame.height; } }; -Sprite.prototype._renderWebGL = function (renderer) { +Sprite.prototype._renderWebGL = function (renderer) +{ // this is where content gets renderd.. // watch this space for a little render state manager.. @@ -197,7 +214,8 @@ * @param matrix {Matrix} the transformation matrix of the sprite * @return {Rectangle} the framing rectangle */ -Sprite.prototype.getBounds = function (matrix) { +Sprite.prototype.getBounds = function (matrix) +{ var width = this.texture.frame.width; var height = this.texture.frame.height; @@ -224,11 +242,13 @@ if(b === 0 && c === 0) { // scale may be negative! - if (a < 0) { + if (a < 0) + { a *= -1; } - if (d < 0) { + if (d < 0) + { d *= -1; } @@ -293,28 +313,34 @@ * * @param renderer {CanvasRenderer} The renderer */ -Sprite.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) { +Sprite.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) + { return; } - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; renderer.context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } // Ignore null sources - if (this.texture.valid) { + if (this.texture.valid) + { var resolution = this.texture.baseTexture.resolution / renderer.resolution; renderer.context.globalAlpha = this.worldAlpha; // If smoothingEnabled is supported and we need to change the smoothing property for this texture - if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) { + if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) + { renderer.scaleMode = this.texture.baseTexture.scaleMode; renderer.context[renderer.smoothProperty] = (renderer.scaleMode === CONST.scaleModes.LINEAR); } @@ -324,7 +350,8 @@ var dy = (this.texture.trim ? this.texture.trim.y : 0) - (this.anchor.y * this.texture.trim.height); // Allow for pixel rounding - if (renderer.roundPixels) { + if (renderer.roundPixels) + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -337,7 +364,8 @@ dx = dx | 0; dy = dy | 0; } - else { + else + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -348,8 +376,10 @@ ); } - if (this.tint !== 0xFFFFFF) { - if (this.cachedTint !== this.tint) { + if (this.tint !== 0xFFFFFF) + { + if (this.cachedTint !== this.tint) + { this.cachedTint = this.tint; // TODO clean up caching - how to clean up the caches? @@ -368,7 +398,8 @@ this.texture.crop.height / resolution ); } - else { + else + { renderer.context.drawImage( this.texture.baseTexture.source, this.texture.crop.x, @@ -383,11 +414,13 @@ } } - for (var i = 0, j = this.children.length; i < j; i++) { + for (var i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -402,10 +435,12 @@ * @param frameId {String} The frame Id of the texture in the cache * @return {Sprite} A new Sprite using a texture from the texture cache matching the frameId */ -Sprite.fromFrame = function (frameId) { +Sprite.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache' + this); } @@ -420,6 +455,7 @@ * @param imageId {String} The image url of the texture * @return {Sprite} A new Sprite using a texture from the texture cache matching the image id */ -Sprite.fromImage = function (imageId, crossorigin, scaleMode) { +Sprite.fromImage = function (imageId, crossorigin, scaleMode) +{ return new Sprite(Texture.fromImage(imageId, crossorigin, scaleMode)); }; diff --git a/src/core/display/SpriteBatch.js b/src/core/display/SpriteBatch.js index 3187777..c196fef 100644 --- a/src/core/display/SpriteBatch.js +++ b/src/core/display/SpriteBatch.js @@ -12,7 +12,8 @@ * ```js * var container = new SpriteBatch(); * - * for(var i = 0; i < 100; ++i) { + * for(var i = 0; i < 100; ++i) + * { * var sprite = new PIXI.Sprite.fromImage("myImage.png"); * container.addChild(sprite); * } @@ -25,7 +26,8 @@ */ //TODO RENAME to PARTICLE CONTAINER? -function SpriteBatch() { +function SpriteBatch() +{ DisplayObjectContainer.call(this); } @@ -38,7 +40,8 @@ * * @private */ -SpriteBatch.prototype.updateTransform = function () { +SpriteBatch.prototype.updateTransform = function () +{ // TODO don't need to! this.displayObjectUpdateTransform(); // PIXI.DisplayObjectContainer.prototype.updateTransform.call( this ); @@ -50,8 +53,10 @@ * @param renderer {WebGLRenderer} The webgl renderer * @private */ -SpriteBatch.prototype.renderWebGL = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderWebGL = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -71,8 +76,10 @@ * @param renderer {CanvasRenderer} The canvas renderer * @private */ -SpriteBatch.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -84,10 +91,12 @@ this.displayObjectUpdateTransform(); - for (var i = 0; i < this.children.length; ++i) { + for (var i = 0; i < this.children.length; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -95,9 +104,11 @@ context.globalAlpha = this.worldAlpha * child.alpha; - if (child.rotation % (Math.PI * 2) === 0) { + if (child.rotation % (Math.PI * 2) === 0) + { // this is the fastest way to optimise! - if rotation is 0 then we can avoid any kind of setTransform call - if (isRotated) { + if (isRotated) + { context.setTransform( transform.a, transform.b, @@ -122,8 +133,10 @@ frame.height * child.scale.y ); } - else { - if (!isRotated) { + else + { + if (!isRotated) + { isRotated = true; } @@ -131,7 +144,8 @@ var childTransform = child.worldTransform; - if (renderer.roundPixels) { + if (renderer.roundPixels) + { context.setTransform( childTransform.a, childTransform.b, @@ -141,7 +155,8 @@ childTransform.ty | 0 ); } - else { + else + { context.setTransform( childTransform.a, childTransform.b, diff --git a/src/core/index.js b/src/core/index.js index 3954b6f..eb4a82b 100644 --- a/src/core/index.js +++ b/src/core/index.js @@ -58,11 +58,13 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRenderer: function (width, height, options, noWebGL) { + autoDetectRenderer: function (width, height, options, noWebGL) + { width = width || 800; height = height || 600; - if (!noWebGL && require('webgl-enabled')()) { + if (!noWebGL && require('webgl-enabled')()) + { return new core.WebGLRenderer(width, height, options); } @@ -87,7 +89,8 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRecommendedRenderer: function (width, height, options) { + autoDetectRecommendedRenderer: function (width, height, options) + { var isAndroid = /Android/i.test(navigator.userAgent); return core.autoDetectRenderer(width, height, options, isAndroid); diff --git a/src/core/math/Matrix.js b/src/core/math/Matrix.js index c2f87e2..2ff4848 100644 --- a/src/core/math/Matrix.js +++ b/src/core/math/Matrix.js @@ -10,7 +10,8 @@ * @class * @namespace PIXI */ -function Matrix() { +function Matrix() +{ /** * @member {number} * @default 1 @@ -63,7 +64,8 @@ * * @param array {number[]} The array that the matrix will be populated from. */ -Matrix.prototype.fromArray = function (array) { +Matrix.prototype.fromArray = function (array) +{ this.a = array[0]; this.b = array[1]; this.c = array[3]; @@ -78,14 +80,17 @@ * @param transpose {boolean} Whether we need to transpose the matrix or not * @return {number[]} the newly created array which contains the matrix */ -Matrix.prototype.toArray = function (transpose) { - if (!this.array) { +Matrix.prototype.toArray = function (transpose) +{ + if (!this.array) + { this.array = new Float32Array(9); } var array = this.array; - if (transpose) { + if (transpose) + { array[0] = this.a; array[1] = this.b; array[2] = 0; @@ -96,7 +101,8 @@ array[7] = this.ty; array[8] = 1; } - else { + else + { array[0] = this.a; array[1] = this.c; array[2] = this.tx; @@ -119,7 +125,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, transformed through this matrix */ -Matrix.prototype.apply = function (pos, newPos) { +Matrix.prototype.apply = function (pos, newPos) +{ newPos = newPos || new Point(); newPos.x = this.a * pos.x + this.c * pos.y + this.tx; @@ -136,7 +143,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, inverse-transformed through this matrix */ -Matrix.prototype.applyInverse = function (pos, newPos) { +Matrix.prototype.applyInverse = function (pos, newPos) +{ newPos = newPos || new Point(); var id = 1 / (this.a * this.d + this.c * -this.b); @@ -154,7 +162,8 @@ * @param {number} y * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.translate = function (x, y) { +Matrix.prototype.translate = function (x, y) +{ this.tx += x; this.ty += y; @@ -168,7 +177,8 @@ * @param {number} y The amount to scale vertically * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.scale = function (x, y) { +Matrix.prototype.scale = function (x, y) +{ this.a *= x; this.d *= y; this.c *= x; @@ -186,7 +196,8 @@ * @param {number} angle - The angle in radians. * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.rotate = function (angle) { +Matrix.prototype.rotate = function (angle) +{ var cos = Math.cos( angle ); var sin = Math.sin( angle ); @@ -210,7 +221,8 @@ * @param {Matrix} matrix * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.append = function (matrix) { +Matrix.prototype.append = function (matrix) +{ var a1 = this.a; var b1 = this.b; var c1 = this.c; @@ -232,7 +244,8 @@ * * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.identity = function () { +Matrix.prototype.identity = function () +{ this.a = 1; this.b = 0; this.c = 0; diff --git a/src/core/math/Point.js b/src/core/math/Point.js index 7565b2d..632f346 100644 --- a/src/core/math/Point.js +++ b/src/core/math/Point.js @@ -7,7 +7,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -function Point(x, y) { +function Point(x, y) +{ /** * @member {number} * @default 0 @@ -29,7 +30,8 @@ * * @return {Point} a copy of the point */ -Point.prototype.clone = function () { +Point.prototype.clone = function () +{ return new Point(this.x, this.y); }; @@ -40,7 +42,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -Point.prototype.set = function (x, y) { +Point.prototype.set = function (x, y) +{ this.x = x || 0; this.y = y || ( (y !== 0) ? this.x : 0 ) ; }; diff --git a/src/core/math/shapes/Circle.js b/src/core/math/shapes/Circle.js index 69cfdc9..4d76efc 100644 --- a/src/core/math/shapes/Circle.js +++ b/src/core/math/shapes/Circle.js @@ -10,7 +10,8 @@ * @param y {number} The Y coordinate of the center of this circle * @param radius {number} The radius of the circle */ -function Circle(x, y, radius) { +function Circle(x, y, radius) +{ /** * @member {number} * @default 0 @@ -46,7 +47,8 @@ * @method clone * @return {Circle} a copy of the Circle */ -Circle.prototype.clone = function () { +Circle.prototype.clone = function () +{ return new Circle(this.x, this.y, this.radius); }; @@ -58,8 +60,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Circle */ -Circle.prototype.contains = function (x, y) { - if (this.radius <= 0) { +Circle.prototype.contains = function (x, y) +{ + if (this.radius <= 0) + { return false; } @@ -79,6 +83,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Circle.prototype.getBounds = function () { +Circle.prototype.getBounds = function () +{ return new Rectangle(this.x - this.radius, this.y - this.radius, this.radius * 2, this.radius * 2); }; diff --git a/src/core/math/shapes/Ellipse.js b/src/core/math/shapes/Ellipse.js index 4f2d066..fefd01a 100644 --- a/src/core/math/shapes/Ellipse.js +++ b/src/core/math/shapes/Ellipse.js @@ -11,7 +11,8 @@ * @param width {number} The half width of this ellipse * @param height {number} The half height of this ellipse */ -function Ellipse(x, y, width, height) { +function Ellipse(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -53,7 +54,8 @@ * @method clone * @return {Ellipse} a copy of the ellipse */ -Ellipse.prototype.clone = function () { +Ellipse.prototype.clone = function () +{ return new Ellipse(this.x, this.y, this.width, this.height); }; @@ -65,8 +67,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coords are within this ellipse */ -Ellipse.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Ellipse.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } @@ -86,6 +90,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Ellipse.prototype.getBounds = function () { +Ellipse.prototype.getBounds = function () +{ return new Rectangle(this.x - this.width, this.y - this.height, this.width, this.height); }; diff --git a/src/core/math/shapes/Polygon.js b/src/core/math/shapes/Polygon.js index ae89148..fea6d37 100644 --- a/src/core/math/shapes/Polygon.js +++ b/src/core/math/shapes/Polygon.js @@ -10,16 +10,20 @@ * arguments passed can be flat x,y values e.g. `new Polygon(x,y, x,y, x,y, ...)` where `x` and `y` are * Numbers. */ -function Polygon(points) { +function Polygon(points) +{ //if points isn't an array, use arguments as the array - if (!(points instanceof Array)) { + if (!(points instanceof Array)) + { points = Array.prototype.slice.call(arguments); } //if this is a flat array of numbers, convert it to points - if (points[0] instanceof Point) { + if (points[0] instanceof Point) + { var p = []; - for (var i = 0, il = points.length; i < il; i++) { + for (var i = 0, il = points.length; i < il; i++) + { p.push(points[i].x, points[i].y); } @@ -51,7 +55,8 @@ * * @return {Polygon} a copy of the polygon */ -Polygon.prototype.clone = function () { +Polygon.prototype.clone = function () +{ return new Polygon(this.points.slice()); }; @@ -62,19 +67,22 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this polygon */ -Polygon.prototype.contains = function (x, y) { +Polygon.prototype.contains = function (x, y) +{ var inside = false; // use some raycasting to test hits // https://github.com/substack/point-in-polygon/blob/master/index.js var length = this.points.length / 2; - for (var i = 0, j = length - 1; i < length; j = i++) { + for (var i = 0, j = length - 1; i < length; j = i++) + { var xi = this.points[i * 2], yi = this.points[i * 2 + 1], xj = this.points[j * 2], yj = this.points[j * 2 + 1], intersect = ((yi > y) !== (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi); - if (intersect) { + if (intersect) + { inside = !inside; } } diff --git a/src/core/math/shapes/Rectangle.js b/src/core/math/shapes/Rectangle.js index 16ac62a..4008b68 100644 --- a/src/core/math/shapes/Rectangle.js +++ b/src/core/math/shapes/Rectangle.js @@ -10,7 +10,8 @@ * @param width {number} The overall width of this rectangle * @param height {number} The overall height of this rectangle */ -function Rectangle(x, y, width, height) { +function Rectangle(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -60,7 +61,8 @@ * * @return {Rectangle} a copy of the rectangle */ -Rectangle.prototype.clone = function () { +Rectangle.prototype.clone = function () +{ return new Rectangle(this.x, this.y, this.width, this.height); }; @@ -71,13 +73,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rectangle */ -Rectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Rectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/math/shapes/RoundedRectangle.js b/src/core/math/shapes/RoundedRectangle.js index 27d286e..7bf6411 100644 --- a/src/core/math/shapes/RoundedRectangle.js +++ b/src/core/math/shapes/RoundedRectangle.js @@ -11,7 +11,8 @@ * @param height {number} The overall height of this rounded rectangle * @param radius {number} Controls the radius of the rounded corners */ -function RoundedRectangle(x, y, width, height, radius) { +function RoundedRectangle(x, y, width, height, radius) +{ /** * @member {number} * @default 0 @@ -58,7 +59,8 @@ * * @return {RoundedRectangle} a copy of the rounded rectangle */ -RoundedRectangle.prototype.clone = function () { +RoundedRectangle.prototype.clone = function () +{ return new RoundedRectangle(this.x, this.y, this.width, this.height, this.radius); }; @@ -69,13 +71,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rounded Rectangle */ -RoundedRectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +RoundedRectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/primitives/Graphics.js b/src/core/primitives/Graphics.js index 261c534..e902d2a 100644 --- a/src/core/primitives/Graphics.js +++ b/src/core/primitives/Graphics.js @@ -16,7 +16,8 @@ * @extends DisplayObjectContainer * @namespace PIXI */ -function Graphics() { +function Graphics() +{ DisplayObjectContainer.call(this); this.renderable = true; @@ -154,16 +155,20 @@ * @private */ cacheAsBitmap: { - get: function () { + get: function () + { return this._cacheAsBitmap; }, - set: function (value) { + set: function (value) + { this._cacheAsBitmap = value; - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._generateCachedSprite(); } - else { + else + { this.destroyCachedSprite(); this.dirty = true; } @@ -176,7 +181,8 @@ * * @return {Graphics} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ var clone = new Graphics(); clone.renderable = this.renderable; @@ -192,7 +198,8 @@ clone.cachedSpriteDirty = this.cachedSpriteDirty; // copy graphics data - for (var i = 0; i < this.graphicsData.length; ++i) { + for (var i = 0; i < this.graphicsData.length; ++i) + { clone.graphicsData.push(this.graphicsData.clone()); } @@ -211,17 +218,21 @@ * @param alpha {number} alpha of the line to draw, will update the objects stored style * @return {Graphics} */ -Graphics.prototype.lineStyle = function (lineWidth, color, alpha) { +Graphics.prototype.lineStyle = function (lineWidth, color, alpha) +{ this.lineWidth = lineWidth || 0; this.lineColor = color || 0; this.lineAlpha = (arguments.length < 3) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length) + { // halfway through a line? start a new one! this.drawShape( new math.Polygon( this.currentPath.shape.points.slice(-2) )); } - else { + else + { // otherwise its empty so lets just set the line properties this.currentPath.lineWidth = this.lineWidth; this.currentPath.lineColor = this.lineColor; @@ -239,7 +250,8 @@ * @param y {number} the Y coordinate to move to * @return {Graphics} */ -Graphics.prototype.moveTo = function (x, y) { +Graphics.prototype.moveTo = function (x, y) +{ this.drawShape(new math.Polygon([x,y])); return this; @@ -253,7 +265,8 @@ * @param y {number} the Y coordinate to draw to * @return {Graphics} */ -Graphics.prototype.lineTo = function (x, y) { +Graphics.prototype.lineTo = function (x, y) +{ this.currentPath.shape.points.push(x, y); this.dirty = true; @@ -270,13 +283,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -285,7 +302,8 @@ n = 20, points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { this.moveTo(0, 0); } @@ -293,7 +311,8 @@ var fromY = points[points.length-1]; var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; xa = fromX + ( (cpX - fromX) * j ); @@ -319,13 +338,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -342,7 +365,8 @@ var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; dt = (1 - j); @@ -373,13 +397,17 @@ * @param radius {number} The radius of the arc * @return {Graphics} */ -Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points.push(x1, y1); } } - else { + else + { this.moveTo(x1, y1); } @@ -392,12 +420,15 @@ b2 = x2 - x1, mm = Math.abs(a1 * b2 - b1 * a2); - if (mm < 1.0e-8 || radius === 0) { - if (points[points.length-2] !== x1 || points[points.length-1] !== y1) { + if (mm < 1.0e-8 || radius === 0) + { + if (points[points.length-2] !== x1 || points[points.length-1] !== y1) + { points.push(x1, y1); } } - else { + else + { var dd = a1 * a1 + b1 * b1, cc = a2 * a2 + b2 * b2, tt = a1 * a2 + b1 * b2, @@ -433,42 +464,51 @@ * @param anticlockwise {boolean} Optional. Specifies whether the drawing should be counterclockwise or clockwise. False is default, and indicates clockwise, while true indicates counter-clockwise. * @return {Graphics} */ -Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) { +Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) +{ var startX = cx + Math.cos(startAngle) * radius; var startY = cy + Math.sin(startAngle) * radius; var points; // TODO - This if-else makes no sense. It uses currentPath in the else where it doesn't exist... - if (this.currentPath) { + if (this.currentPath) + { points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { points.push(startX, startY); } - else if (points[points.length-2] !== startX || points[points.length-1] !== startY) { + else if (points[points.length-2] !== startX || points[points.length-1] !== startY) + { points.push(startX, startY); } } - else { + else + { this.moveTo(startX, startY); points = this.currentPath.shape.points; } - if (startAngle === endAngle) { + if (startAngle === endAngle) + { return this; } - if (!anticlockwise && endAngle <= startAngle) { + if (!anticlockwise && endAngle <= startAngle) + { endAngle += Math.PI * 2; } - else if (anticlockwise && startAngle <= endAngle) { + else if (anticlockwise && startAngle <= endAngle) + { startAngle += Math.PI * 2; } var sweep = anticlockwise ? (startAngle - endAngle) *-1 : (endAngle - startAngle); var segs = (Math.abs(sweep)/ (Math.PI * 2)) * 40; - if (sweep === 0) { + if (sweep === 0) + { return this; } @@ -482,7 +522,8 @@ var remainder = ( segMinus % 1 ) / segMinus; - for (var i = 0; i <= segMinus; ++i) { + for (var i = 0; i <= segMinus; ++i) + { var real = i + remainder * i; var angle = ((theta) + startAngle + (theta2 * real)); @@ -506,13 +547,16 @@ * @param alpha {number} the alpha of the fill * @return {Graphics} */ -Graphics.prototype.beginFill = function (color, alpha) { +Graphics.prototype.beginFill = function (color, alpha) +{ this.filling = true; this.fillColor = color || 0; this.fillAlpha = (alpha === undefined) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length <= 2) + { this.currentPath.fill = this.filling; this.currentPath.fillColor = this.fillColor; this.currentPath.fillAlpha = this.fillAlpha; @@ -526,7 +570,8 @@ * * @return {Graphics} */ -Graphics.prototype.endFill = function () { +Graphics.prototype.endFill = function () +{ this.filling = false; this.fillColor = null; this.fillAlpha = 1; @@ -542,7 +587,8 @@ * @param height {number} The height of the rectangle * @return {Graphics} */ -Graphics.prototype.drawRect = function ( x, y, width, height ) { +Graphics.prototype.drawRect = function ( x, y, width, height ) +{ this.drawShape(new math.Rectangle(x,y, width, height)); return this; @@ -556,7 +602,8 @@ * @param height {number} The height of the rectangle * @param radius {number} Radius of the rectangle corners */ -Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) { +Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) +{ this.drawShape(new math.RoundedRectangle(x, y, width, height, radius)); return this; @@ -570,7 +617,8 @@ * @param radius {number} The radius of the circle * @return {Graphics} */ -Graphics.prototype.drawCircle = function (x, y, radius) { +Graphics.prototype.drawCircle = function (x, y, radius) +{ this.drawShape(new math.Circle(x,y, radius)); return this; @@ -585,7 +633,8 @@ * @param height {number} The half height of the ellipse * @return {Graphics} */ -Graphics.prototype.drawEllipse = function (x, y, width, height) { +Graphics.prototype.drawEllipse = function (x, y, width, height) +{ this.drawShape(new math.Ellipse(x, y, width, height)); return this; @@ -597,8 +646,10 @@ * @param path {Array} The path data used to construct the polygon. * @return {Graphics} */ -Graphics.prototype.drawPolygon = function (path) { - if (!(path instanceof Array)) { +Graphics.prototype.drawPolygon = function (path) +{ + if (!(path instanceof Array)) + { path = Array.prototype.slice.call(arguments); } @@ -612,7 +663,8 @@ * * @return {Graphics} */ -Graphics.prototype.clear = function () { +Graphics.prototype.clear = function () +{ this.lineWidth = 0; this.filling = false; @@ -631,7 +683,8 @@ * @param scaleMode {number} Should be one of the scaleMode consts * @return {Texture} a texture of the graphics object */ -Graphics.prototype.generateTexture = function (resolution, scaleMode) { +Graphics.prototype.generateTexture = function (resolution, scaleMode) +{ resolution = resolution || 1; var bounds = this.getBounds(); @@ -655,17 +708,21 @@ * * @param renderer {WebGLRenderer} */ -Graphics.prototype._renderWebGL = function (renderer) { +Graphics.prototype._renderWebGL = function (renderer) +{ // if the sprite is not visible or the alpha is 0 then no need to render this element - if (this.isMask === true) { + if (this.isMask === true) + { return; } // this code may still be needed so leaving for now.. - // + // /* - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture on the gpu too! @@ -681,17 +738,24 @@ return; } - */ - - // check if the webgl graphic needs to be updated - if (this.glDirty) { - this.dirty = true; - this.glDirty = false; - } + else */ - renderer.setObjectRendererer(renderer.graphicsRenderer); - renderer.graphicsRenderer.render(this); + renderer.spriteBatch.stop(); + renderer.blendModeManager.setBlendMode(this.blendMode); + // check blend mode + renderer.blendModeManager.setBlendMode( this.blendMode ); + + // check if the webgl graphic needs to be updated + if (this.glDirty) + { + this.dirty = true; + this.glDirty = false; + } + + WebGLGraphics.renderGraphics(this, renderer); + + renderer.spriteBatch.start(); }; /** @@ -700,14 +764,18 @@ * @param renderer {CanvasRenderer} * @private */ -Graphics.prototype.renderCanvas = function (renderer) { +Graphics.prototype.renderCanvas = function (renderer) +{ // 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.isMask === true) { + if (!this.visible || this.alpha <= 0 || this.isMask === true) + { return; } - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture @@ -723,16 +791,19 @@ return; } - else { + else + { var context = renderer.context; var transform = this.worldTransform; - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } @@ -748,11 +819,13 @@ CanvasGraphics.renderGraphics(this, context); - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } } @@ -763,13 +836,16 @@ * * @return {Rectangle} the rectangular bounding area */ -Graphics.prototype.getBounds = function (matrix) { +Graphics.prototype.getBounds = function (matrix) +{ // return an empty object if the item is a mask! - if (this.isMask) { + if (this.isMask) + { return math.Rectangle.EMPTY; } - if (this.dirty) { + if (this.dirty) + { this.updateLocalBounds(); this.glDirty = true; @@ -841,23 +917,27 @@ * Update the bounds of the object * */ -Graphics.prototype.updateLocalBounds = function () { +Graphics.prototype.updateLocalBounds = function () +{ var minX = Infinity; var maxX = -Infinity; var minY = Infinity; var maxY = -Infinity; - if (this.graphicsData.length) { + if (this.graphicsData.length) + { var shape, points, x, y, w, h; - for (var i = 0; i < this.graphicsData.length; i++) { + for (var i = 0; i < this.graphicsData.length; i++) + { var data = this.graphicsData[i]; var type = data.type; var lineWidth = data.lineWidth; shape = data.shape; - if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) { + if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) + { x = shape.x - lineWidth/2; y = shape.y - lineWidth/2; w = shape.width + lineWidth; @@ -869,7 +949,8 @@ minY = y < minY ? y : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.CIRC) { + else if (type === CONST.SHAPES.CIRC) + { x = shape.x; y = shape.y; w = shape.radius + lineWidth/2; @@ -881,7 +962,8 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.ELIP) { + else if (type === CONST.SHAPES.ELIP) + { x = shape.x; y = shape.y; w = shape.width + lineWidth/2; @@ -893,11 +975,13 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else { + else + { // POLY points = shape.points; - for (var j = 0; j < points.length; j += 2) { + for (var j = 0; j < points.length; j += 2) + { x = points[j]; y = points[j+1]; @@ -910,7 +994,8 @@ } } } - else { + else + { minX = 0; maxX = 0; minY = 0; @@ -931,10 +1016,12 @@ * * @private */ -Graphics.prototype._generateCachedSprite = function () { +Graphics.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { var canvasBuffer = new CanvasBuffer(bounds.width, bounds.height); var texture = Texture.fromCanvas(canvasBuffer.canvas); @@ -943,7 +1030,8 @@ this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.buffer.resize(bounds.width, bounds.height); } @@ -968,7 +1056,8 @@ * * @private */ -Graphics.prototype.updateCachedSpriteTexture = function () { +Graphics.prototype.updateCachedSpriteTexture = function () +{ var cachedSprite = this._cachedSprite; var texture = cachedSprite.texture; var canvas = cachedSprite.buffer.canvas; @@ -989,7 +1078,8 @@ * Destroys a previous cached sprite. * */ -Graphics.prototype.destroyCachedSprite = function () { +Graphics.prototype.destroyCachedSprite = function () +{ this._cachedSprite.texture.destroy(true); // let the gc collect the unused sprite @@ -1003,10 +1093,13 @@ * @param {Circle|Rectangle|Ellipse|Line|Polygon} shape The Shape object to draw. * @return {GraphicsData} The generated GraphicsData object. */ -Graphics.prototype.drawShape = function (shape) { - if (this.currentPath) { +Graphics.prototype.drawShape = function (shape) +{ + if (this.currentPath) + { // check current path! - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath.shape.points.length <= 2) + { this.graphicsData.pop(); } } @@ -1017,7 +1110,8 @@ this.graphicsData.push(data); - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { data.shape.closed = this.filling; this.currentPath = data; } diff --git a/src/core/primitives/GraphicsData.js b/src/core/primitives/GraphicsData.js index 99decbe..788f6f2 100644 --- a/src/core/primitives/GraphicsData.js +++ b/src/core/primitives/GraphicsData.js @@ -4,7 +4,8 @@ * @class * @namespace PIXI */ -function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) { +function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) +{ this.lineWidth = lineWidth; this.lineColor = lineColor; this.lineAlpha = lineAlpha; @@ -27,7 +28,8 @@ * * @return {GraphicsData} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ return new GraphicsData( this.lineWidth, this.lineColor, diff --git a/src/core/renderers/canvas/CanvasRenderer.js b/src/core/renderers/canvas/CanvasRenderer.js index 15a0978..7aebd44 100644 --- a/src/core/renderers/canvas/CanvasRenderer.js +++ b/src/core/renderers/canvas/CanvasRenderer.js @@ -17,17 +17,22 @@ * @param [options.resolution=1] {number} the resolution of the renderer retina would be 2 * @param [options.clearBeforeRender=true] {boolean} This sets if the CanvasRenderer will clear the canvas or not before the new render pass. */ -function CanvasRenderer(width, height, options) { +function CanvasRenderer(width, height, options) +{ utils.sayHello('Canvas'); - if (options) { - for (var i in CONST.defaultRenderOptions) { - if (typeof options[i] === 'undefined') { + if (options) + { + for (var i in CONST.defaultRenderOptions) + { + if (typeof options[i] === 'undefined') + { options[i] = CONST.defaultRenderOptions[i]; } } } - else { + else + { options = CONST.defaultRenderOptions; } @@ -156,19 +161,24 @@ this.smoothProperty = null; - if (this.context.imageSmoothingEnabled) { + if (this.context.imageSmoothingEnabled) + { this.smoothProperty = 'imageSmoothingEnabled'; } - else if (this.context.webkitImageSmoothingEnabled) { + else if (this.context.webkitImageSmoothingEnabled) + { this.smoothProperty = 'webkitImageSmoothingEnabled'; } - else if (this.context.mozImageSmoothingEnabled) { + else if (this.context.mozImageSmoothingEnabled) + { this.smoothProperty = 'mozImageSmoothingEnabled'; } - else if (this.context.oImageSmoothingEnabled) { + else if (this.context.oImageSmoothingEnabled) + { this.smoothProperty = 'oImageSmoothingEnabled'; } - else if (this.context.msImageSmoothingEnabled) { + else if (this.context.msImageSmoothingEnabled) + { this.smoothProperty = 'msImageSmoothingEnabled'; } @@ -193,10 +203,12 @@ * @memberof CanvasRenderer# */ backgroundColor: { - get: function () { + get: function () + { return this._backgroundColor; }, - set: function (val) { + set: function (val) + { this._backgroundColor = val; this._backgroundColorString = utils.hex2string(val); } @@ -208,7 +220,8 @@ * * @param object {DisplayObject} the object to be rendered */ -CanvasRenderer.prototype.render = function (object) { +CanvasRenderer.prototype.render = function (object) +{ object.updateTransform(); this.context.setTransform(1,0,0,1,0,0); @@ -218,16 +231,20 @@ this.currentBlendMode = CONST.blendModes.NORMAL; this.context.globalCompositeOperation = this.blendModes[CONST.blendModes.NORMAL]; - if (navigator.isCocoonJS && this.view.screencanvas) { + if (navigator.isCocoonJS && this.view.screencanvas) + { this.context.fillStyle = 'black'; this.context.clear(); } - if (this.clearBeforeRender) { - if (this.transparent) { + if (this.clearBeforeRender) + { + if (this.transparent) + { this.context.clearRect(0, 0, this.width, this.height); } - else { + else + { this.context.fillStyle = this._backgroundColorString; this.context.fillRect(0, 0, this.width , this.height); } @@ -241,8 +258,10 @@ * * @param [removeView=false] {boolean} Removes the Canvas element from the DOM. */ -CanvasRenderer.prototype.destroy = function (removeView) { - if (removeView && this.view.parent) { +CanvasRenderer.prototype.destroy = function (removeView) +{ + if (removeView && this.view.parent) + { this.view.parent.removeChild(this.view); } @@ -257,14 +276,16 @@ * @param width {number} the new width of the canvas view * @param height {number} the new height of the canvas view */ -CanvasRenderer.prototype.resize = function (width, height) { +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) { + if (this.autoResize) + { this.view.style.width = this.width / this.resolution + 'px'; this.view.style.height = this.height / this.resolution + 'px'; } @@ -276,7 +297,8 @@ * @param displayObject {DisplayObject} The displayObject to render * @private */ -CanvasRenderer.prototype.renderDisplayObject = function (displayObject) { +CanvasRenderer.prototype.renderDisplayObject = function (displayObject) +{ displayObject.renderCanvas(this); }; @@ -285,11 +307,14 @@ * * @private */ -CanvasRenderer.prototype._mapBlendModes = function () { - if (!this.blendModes) { +CanvasRenderer.prototype._mapBlendModes = function () +{ + if (!this.blendModes) + { this.blendModes = {}; - if (utils.canUseNewCanvasBlendModes()) { + if (utils.canUseNewCanvasBlendModes()) + { this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? this.blendModes[CONST.blendModes.MULTIPLY] = 'multiply'; @@ -308,7 +333,8 @@ this.blendModes[CONST.blendModes.COLOR] = 'color'; this.blendModes[CONST.blendModes.LUMINOSITY] = 'luminosity'; } - else { + else + { // this means that the browser does not support the cool new blend modes in canvas 'cough' ie 'cough' this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? diff --git a/src/core/renderers/canvas/utils/CanvasBuffer.js b/src/core/renderers/canvas/utils/CanvasBuffer.js index ebe5d47..b183a66 100644 --- a/src/core/renderers/canvas/utils/CanvasBuffer.js +++ b/src/core/renderers/canvas/utils/CanvasBuffer.js @@ -6,7 +6,8 @@ * @param width {number} the width for the newly created canvas * @param height {number} the height for the newly created canvas */ -function CanvasBuffer(width, height) { +function CanvasBuffer(width, height) +{ /** * The Canvas object that belongs to this CanvasBuffer. * @@ -36,10 +37,12 @@ * @memberof CanvasBuffer# */ width: { - get: function () { + get: function () + { return this.canvas.width; }, - set: function (val) { + set: function (val) + { this.canvas.width = val; } }, @@ -50,10 +53,12 @@ * @memberof CanvasBuffer# */ height: { - get: function () { + get: function () + { return this.canvas.height; }, - set: function (val) { + set: function (val) + { this.canvas.height = val; } } @@ -64,7 +69,8 @@ * * @private */ -CanvasBuffer.prototype.clear = function () { +CanvasBuffer.prototype.clear = function () +{ this.context.setTransform(1, 0, 0, 1, 0, 0); this.context.clearRect(0,0, this.canvas.width, this.canvas.height); }; @@ -75,7 +81,8 @@ * @param width {number} the new width of the canvas * @param height {number} the new height of the canvas */ -CanvasBuffer.prototype.resize = function (width, height) { +CanvasBuffer.prototype.resize = function (width, height) +{ this.canvas.width = width; this.canvas.height = height; }; diff --git a/src/core/renderers/canvas/utils/CanvasGraphics.js b/src/core/renderers/canvas/utils/CanvasGraphics.js index c7eaa2a..3f2a91f 100644 --- a/src/core/renderers/canvas/utils/CanvasGraphics.js +++ b/src/core/renderers/canvas/utils/CanvasGraphics.js @@ -13,15 +13,18 @@ * @param graphics {Graphics} the actual graphics object to render * @param context {CanvasRenderingContext2D} the 2d drawing method of the canvas */ -CanvasGraphics.renderGraphics = function (graphics, context) { +CanvasGraphics.renderGraphics = function (graphics, context) +{ var worldAlpha = graphics.worldAlpha; - if (graphics.dirty) { + if (graphics.dirty) + { this.updateGraphicsTint(graphics); graphics.dirty = false; } - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; @@ -30,69 +33,82 @@ context.lineWidth = data.lineWidth; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { context.beginPath(); var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } - if (shape.closed) { + if (shape.closed) + { context.lineTo(points[0], points[1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fillRect(shape.x, shape.y, shape.width, shape.height); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.strokeRect(shape.x, shape.y, shape.width, shape.height); } } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.beginPath(); context.arc(shape.x, shape.y, shape.radius,0,2*Math.PI); context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas var w = shape.width * 2; @@ -119,18 +135,21 @@ context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; var width = shape.width; @@ -152,13 +171,15 @@ context.quadraticCurveTo(rx, ry, rx, ry + radius); context.closePath(); - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); @@ -174,45 +195,54 @@ * @param graphics {Graphics} the graphics which will be used as a mask * @param context {CanvasRenderingContext2D} the context 2d method of the canvas */ -CanvasGraphics.renderGraphicsMask = function (graphics, context) { +CanvasGraphics.renderGraphicsMask = function (graphics, context) +{ var len = graphics.graphicsData.length; - if (len === 0) { + if (len === 0) + { return; } context.beginPath(); - for (var i = 0; i < len; i++) { + for (var i = 0; i < len; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { context.rect(shape.x, shape.y, shape.width, shape.height); context.closePath(); } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.arc(shape.x, shape.y, shape.radius, 0, 2 * Math.PI); context.closePath(); } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas @@ -237,7 +267,8 @@ context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); context.closePath(); } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; @@ -262,8 +293,10 @@ } }; -CanvasGraphics.updateGraphicsTint = function (graphics) { - if (graphics.tint === 0xFFFFFF) { +CanvasGraphics.updateGraphicsTint = function (graphics) +{ + if (graphics.tint === 0xFFFFFF) + { return; } @@ -271,7 +304,8 @@ var tintG = (graphics.tint >> 8 & 0xFF) / 255; var tintB = (graphics.tint & 0xFF)/ 255; - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var fillColor = data.fillColor | 0; diff --git a/src/core/renderers/canvas/utils/CanvasMaskManager.js b/src/core/renderers/canvas/utils/CanvasMaskManager.js index e04a733..9827d36 100644 --- a/src/core/renderers/canvas/utils/CanvasMaskManager.js +++ b/src/core/renderers/canvas/utils/CanvasMaskManager.js @@ -6,7 +6,8 @@ * @class * @namespace PIXI */ -function CanvasMaskManager() {} +function CanvasMaskManager() +{} CanvasMaskManager.prototype.constructor = CanvasMaskManager; module.exports = CanvasMaskManager; @@ -17,7 +18,8 @@ * @param maskData {object} the maskData that will be pushed * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.pushMask = function (maskData, renderer) { +CanvasMaskManager.prototype.pushMask = function (maskData, renderer) +{ renderer.context.save(); var cacheAlpha = maskData.alpha; @@ -45,6 +47,7 @@ * * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.popMask = function (renderer) { +CanvasMaskManager.prototype.popMask = function (renderer) +{ renderer.context.restore(); }; diff --git a/src/core/renderers/canvas/utils/CanvasTinter.js b/src/core/renderers/canvas/utils/CanvasTinter.js index 17e0529..d2fb1bc 100644 --- a/src/core/renderers/canvas/utils/CanvasTinter.js +++ b/src/core/renderers/canvas/utils/CanvasTinter.js @@ -14,7 +14,8 @@ * @param color {number} the color to use to tint the sprite with * @return {HTMLCanvasElement} The tinted canvas */ -CanvasTinter.getTintedTexture = function (sprite, color) { +CanvasTinter.getTintedTexture = function (sprite, color) +{ var texture = sprite.texture; color = CanvasTinter.roundColor(color); @@ -23,7 +24,8 @@ texture.tintCache = texture.tintCache || {}; - if (texture.tintCache[stringColor]) { + if (texture.tintCache[stringColor]) + { return texture.tintCache[stringColor]; } @@ -33,14 +35,16 @@ //CanvasTinter.tintWithPerPixel(texture, stringColor, canvas); CanvasTinter.tintMethod(texture, color, canvas); - if (CanvasTinter.convertTintToImage) { + if (CanvasTinter.convertTintToImage) + { // is this better? var tintImage = new Image(); tintImage.src = canvas.toDataURL(); texture.tintCache[stringColor] = tintImage; } - else { + else + { texture.tintCache[stringColor] = canvas; // if we are not converting the texture to an image then we need to lose the reference to the canvas CanvasTinter.canvas = null; @@ -56,7 +60,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithMultiply = function (texture, color, canvas) { +CanvasTinter.tintWithMultiply = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -104,7 +109,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithOverlay = function (texture, color, canvas) { +CanvasTinter.tintWithOverlay = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -139,7 +145,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithPerPixel = function (texture, color, canvas) { +CanvasTinter.tintWithPerPixel = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -167,7 +174,8 @@ var pixels = pixelData.data; - for (var i = 0; i < pixels.length; i += 4) { + for (var i = 0; i < pixels.length; i += 4) + { pixels[i+0] *= r; pixels[i+1] *= g; pixels[i+2] *= b; @@ -181,7 +189,8 @@ * * @param color {number} the color to round, should be a hex color */ -CanvasTinter.roundColor = function (color) { +CanvasTinter.roundColor = function (color) +{ var step = CanvasTinter.cacheStepsPerColorChannel; var rgbValues = utils.hex2rgb(color); diff --git a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js index 9f2f89a..35edbaf 100644 --- a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js +++ b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLBlendModeManager(renderer) { +function WebGLBlendModeManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -23,8 +24,10 @@ * * @param blendMode {number} the blendMode, should be a Pixi const, such as BlendModes.ADD */ -WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) { - if (this.currentBlendMode === blendMode) { +WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) +{ + if (this.currentBlendMode === blendMode) + { return false; } diff --git a/src/core/renderers/webgl/managers/WebGLFilterManager.js b/src/core/renderers/webgl/managers/WebGLFilterManager.js index 1179258..2dac048 100644 --- a/src/core/renderers/webgl/managers/WebGLFilterManager.js +++ b/src/core/renderers/webgl/managers/WebGLFilterManager.js @@ -7,7 +7,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLFilterManager(renderer) { +function WebGLFilterManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -32,7 +33,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.texturePool.length = 0; self.initShaderBuffers(); }); @@ -46,7 +48,8 @@ * @param renderer {WebGLRenderer} * @param buffer {ArrayBuffer} */ -WebGLFilterManager.prototype.begin = function (buffer) { +WebGLFilterManager.prototype.begin = function (buffer) +{ this.defaultShader = this.renderer.shaderManager.defaultShader; this.width = this.renderer.projection.x * 2; @@ -60,7 +63,8 @@ * * @param filterBlock {object} the filter that will be pushed to the current filter stack */ -WebGLFilterManager.prototype.pushFilter = function (filterBlock) { +WebGLFilterManager.prototype.pushFilter = function (filterBlock) +{ var gl = this.renderer.gl; var projection = this.renderer.projection; @@ -78,10 +82,12 @@ this.offsetY += filterBlock._filterArea.y; var texture = this.texturePool.pop(); - if (!texture) { + if (!texture) + { texture = new FilterTexture(this.renderer.gl, this.width, this.height); } - else { + else + { texture.resize(this.width, this.height); } @@ -98,29 +104,35 @@ var localX = filterArea.x, localY = filterArea.y; - if (filterArea.x < 0) { + if (filterArea.x < 0) + { filterArea.width += filterArea.x; filterArea.x = 0; } - if (filterArea.y < 0) { + if (filterArea.y < 0) + { filterArea.height += filterArea.y; filterArea.y = 0; } - if (localX + filterArea.width > this.width) { + if (localX + filterArea.width > this.width) + { filterArea.width = this.width - localX; } - if (localY + filterArea.height > this.height) { + if (localY + filterArea.height > this.height) + { filterArea.height = this.height - localY; } - if (filterArea.width < 0) { + if (filterArea.width < 0) + { filterArea.width = 0; } - if (filterArea.height < 0) { + if (filterArea.height < 0) + { filterArea.height = 0; } @@ -154,7 +166,8 @@ * Removes the last filter from the filter stack and doesn't return it. * */ -WebGLFilterManager.prototype.popFilter = function () { +WebGLFilterManager.prototype.popFilter = function () +{ var gl = this.renderer.gl; var filterBlock = this.filterStack.pop(); @@ -163,7 +176,8 @@ var projection = this.renderer.projection; var offset = this.renderer.offset; - if (filterBlock.filterPasses.length > 1) { + if (filterBlock.filterPasses.length > 1) + { gl.viewport(0, 0, filterArea.width, filterArea.height); gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); @@ -193,7 +207,8 @@ var inputTexture = texture; var outputTexture = this.texturePool.pop(); - if (!outputTexture) { + if (!outputTexture) + { outputTexture = new FilterTexture(this.renderer.gl, this.width, this.height); } outputTexture.resize(this.width, this.height); @@ -204,7 +219,8 @@ gl.disable(gl.BLEND); - for (var i = 0; i < filterBlock.filterPasses.length-1; i++) { + for (var i = 0; i < filterBlock.filterPasses.length-1; i++) + { var filterPass = filterBlock.filterPasses[i]; gl.bindFramebuffer(gl.FRAMEBUFFER, outputTexture.frameBuffer ); @@ -243,10 +259,12 @@ var buffer = this.buffer; // time to render the filters texture to the previous scene - if (this.filterStack.length === 0) { + if (this.filterStack.length === 0) + { gl.colorMask(true, true, true, true);//this.transparent); } - else { + else + { var currentFilter = this.filterStack[this.filterStack.length-1]; filterArea = currentFilter._filterArea; @@ -332,13 +350,15 @@ * @param width {number} the horizontal range of the filter * @param height {number} the vertical range of the filter */ -WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) { +WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) +{ // use program var gl = this.renderer.gl; var shader = filter.shaders[gl.id]; - if (!shader) { + if (!shader) + { shader = new Shader(gl); shader.fragmentSrc = filter.fragmentSrc; @@ -356,7 +376,8 @@ gl.uniform2f(shader.projectionVector, width/2, -height/2); gl.uniform2f(shader.offsetVector, 0,0); - if (filter.uniforms.dimensions) { + 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]; @@ -386,7 +407,8 @@ * Initialises the shader buffers. * */ -WebGLFilterManager.prototype.initShaderBuffers = function () { +WebGLFilterManager.prototype.initShaderBuffers = function () +{ var gl = this.renderer.gl; // create some buffers @@ -432,7 +454,8 @@ * Destroys the filter and removes it from the filter stack. * */ -WebGLFilterManager.prototype.destroy = function () { +WebGLFilterManager.prototype.destroy = function () +{ var gl = this.renderer.gl; this.filterStack = null; @@ -441,7 +464,8 @@ this.offsetY = 0; // destroy textures - for (var i = 0; i < this.texturePool.length; i++) { + for (var i = 0; i < this.texturePool.length; i++) + { this.texturePool[i].destroy(); } diff --git a/src/core/renderers/webgl/managers/WebGLManager.js b/src/core/renderers/webgl/managers/WebGLManager.js index 9d47b5c..c30cd51 100644 --- a/src/core/renderers/webgl/managers/WebGLManager.js +++ b/src/core/renderers/webgl/managers/WebGLManager.js @@ -3,7 +3,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLManager(renderer) { +function WebGLManager(renderer) +{ /** * The renderer this manager works for. * @@ -15,6 +16,7 @@ WebGLManager.prototype.constructor = WebGLManager; module.exports = WebGLManager; -WebGLManager.prototype.destroy = function () { +WebGLManager.prototype.destroy = function () +{ this.renderer = null; }; diff --git a/src/core/renderers/webgl/managers/WebGLMaskManager.js b/src/core/renderers/webgl/managers/WebGLMaskManager.js index 2f90b64..e568812 100644 --- a/src/core/renderers/webgl/managers/WebGLMaskManager.js +++ b/src/core/renderers/webgl/managers/WebGLMaskManager.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLMaskManager(renderer) { +function WebGLMaskManager(renderer) +{ WebGLManager.call(this, renderer); } @@ -19,12 +20,15 @@ * * @param maskData {any[]} */ -WebGLMaskManager.prototype.pushMask = function (maskData) { - if (maskData.dirty) { +WebGLMaskManager.prototype.pushMask = function (maskData) +{ + if (maskData.dirty) + { WebGLGraphics.updateGraphics(maskData, this.renderer.gl); } - if (!maskData._webGL[this.renderer.gl.id].data.length) { + if (!maskData._webGL[this.renderer.gl.id].data.length) + { return; } @@ -36,6 +40,7 @@ * * @param maskData {any[]} */ -WebGLMaskManager.prototype.popMask = function (maskData) { +WebGLMaskManager.prototype.popMask = function (maskData) +{ this.renderer.stencilManager.popStencil(maskData, maskData._webGL[this.renderer.gl.id].data[0], this.renderer); }; diff --git a/src/core/renderers/webgl/managers/WebGLShaderManager.js b/src/core/renderers/webgl/managers/WebGLShaderManager.js index fef071c..90c6477 100644 --- a/src/core/renderers/webgl/managers/WebGLShaderManager.js +++ b/src/core/renderers/webgl/managers/WebGLShaderManager.js @@ -10,7 +10,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLShaderManager(renderer) { +function WebGLShaderManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -28,7 +29,8 @@ */ this.tempAttribState = []; - for (var i = 0; i < this.maxAttibs; i++) { + for (var i = 0; i < this.maxAttibs; i++) + { this.attribState[i] = false; } @@ -66,7 +68,8 @@ // listen for context and update necessary shaders var self = this; - this.renderer.on('context', function (event) { + this.renderer.on('context', function (event) + { var gl = event.data; // this shader is used for rendering primitives @@ -97,29 +100,36 @@ * * @param attribs {Array} attribs */ -WebGLShaderManager.prototype.setAttribs = function (attribs) { +WebGLShaderManager.prototype.setAttribs = function (attribs) +{ // reset temp state var i; - for (i = 0; i < this.tempAttribState.length; i++) { + for (i = 0; i < this.tempAttribState.length; i++) + { this.tempAttribState[i] = false; } // set the new attribs - for (var a in attribs) { + for (var a in attribs) + { this.tempAttribState[attribs[a]] = true; } var gl = this.renderer.gl; - for (i = 0; i < this.attribState.length; i++) { - if (this.attribState[i] !== this.tempAttribState[i]) { + for (i = 0; i < this.attribState.length; i++) + { + if (this.attribState[i] !== this.tempAttribState[i]) + { this.attribState[i] = this.tempAttribState[i]; - if (this.attribState[i]) { + if (this.attribState[i]) + { gl.enableVertexAttribArray(i); } - else { + else + { gl.disableVertexAttribArray(i); } } @@ -131,8 +141,10 @@ * * @param shader {Any} */ -WebGLShaderManager.prototype.setShader = function (shader) { - if (this._currentId === shader.uuid) { +WebGLShaderManager.prototype.setShader = function (shader) +{ + if (this._currentId === shader.uuid) + { return false; } @@ -150,7 +162,8 @@ * Destroys this object. * */ -WebGLShaderManager.prototype.destroy = function () { +WebGLShaderManager.prototype.destroy = function () +{ this.attribState = null; this.tempAttribState = null; diff --git a/src/core/renderers/webgl/managers/WebGLStencilManager.js b/src/core/renderers/webgl/managers/WebGLStencilManager.js index 9ec6398..4cb0134 100644 --- a/src/core/renderers/webgl/managers/WebGLStencilManager.js +++ b/src/core/renderers/webgl/managers/WebGLStencilManager.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLStencilManager(renderer) { +function WebGLStencilManager(renderer) +{ WebGLManager.call(this, renderer); this.stencilStack = []; @@ -24,12 +25,14 @@ * @param graphics {Graphics} * @param webGLData {any[]} */ -WebGLStencilManager.prototype.pushStencil = function (graphics, webGLData) { +WebGLStencilManager.prototype.pushStencil = function (graphics, webGLData) +{ var gl = this.renderer.gl; this.bindGraphics(graphics, webGLData, this.renderer); - if (this.stencilStack.length === 0) { + if (this.stencilStack.length === 0) + { gl.enable(gl.STENCIL_TEST); gl.clear(gl.STENCIL_BUFFER_BIT); this.reverse = true; @@ -47,14 +50,17 @@ // draw the triangle strip! - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } @@ -62,31 +68,38 @@ // draw a quad to increment.. gl.drawElements(gl.TRIANGLE_FAN, 4, gl.UNSIGNED_SHORT, ( webGLData.indices.length - 4 ) * 2 ); - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); } this.reverse = !this.reverse; } - else { - if (!this.reverse) { + else + { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } - else { + 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) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); } } @@ -103,7 +116,8 @@ * @param graphics {Graphics} * @param webGLData {Array} */ -WebGLStencilManager.prototype.bindGraphics = function (graphics, webGLData) { +WebGLStencilManager.prototype.bindGraphics = function (graphics, webGLData) +{ //if (this._currentGraphics === graphics)return; this._currentGraphics = graphics; @@ -114,7 +128,8 @@ offset = this.renderer.offset, shader;// = this.renderer.shaderManager.primitiveShader; - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { shader = this.renderer.shaderManager.complexPrimitiveShader; this.renderer.shaderManager.setShader(shader); @@ -141,7 +156,8 @@ // set the index buffer! gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, webGLData.indexBuffer); } - else { + else + { //this.renderer.shaderManager.activatePrimitiveShader(); shader = this.renderer.shaderManager.primitiveShader; this.renderer.shaderManager.setShader( shader ); @@ -154,7 +170,7 @@ gl.uniform2f(shader.uniforms.offsetVector._location, -offset.x, -offset.y); gl.uniform3fv(shader.uniforms.tint._location, utils.hex2rgb(graphics.tint)); - + gl.uniform1f(shader.uniforms.alpha._location, graphics.worldAlpha); @@ -172,19 +188,22 @@ * @param graphics {Graphics} * @param webGLData {Array} */ -WebGLStencilManager.prototype.popStencil = function (graphics, webGLData) { +WebGLStencilManager.prototype.popStencil = function (graphics, webGLData) +{ var gl = this.renderer.gl; this.stencilStack.pop(); this.count--; - if (this.stencilStack.length === 0) { + if (this.stencilStack.length === 0) + { // the stack is empty! gl.disable(gl.STENCIL_TEST); } - else { + else + { var level = this.count; @@ -192,14 +211,17 @@ gl.colorMask(false, false, false, false); - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { this.reverse = !this.reverse; - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } @@ -213,31 +235,38 @@ // draw the triangle strip! gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); - if (!this.reverse) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); } } - else { + else + { // console.log("<<>>") - if (!this.reverse) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } - else { + 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) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); } } @@ -253,7 +282,8 @@ * Destroys the mask stack. * */ -WebGLStencilManager.prototype.destroy = function () { +WebGLStencilManager.prototype.destroy = function () +{ this.renderer = null; this.stencilStack = null; }; diff --git a/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js b/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js index 913ba5e..1ea7d19 100644 --- a/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js +++ b/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function ComplexPrimitiveShader(gl) { +function ComplexPrimitiveShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -24,7 +25,8 @@ 'uniform float flipY;', 'varying vec4 vColor;', - 'void main(void) {', + '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);', @@ -37,7 +39,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = vColor;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/FastShader.js b/src/core/renderers/webgl/shaders/FastShader.js index bd2e29a..2e5e060 100644 --- a/src/core/renderers/webgl/shaders/FastShader.js +++ b/src/core/renderers/webgl/shaders/FastShader.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function FastShader(gl) { +function FastShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -28,7 +29,8 @@ 'const vec2 center = vec2(-1.0, 1.0);', - 'void main(void) {', + 'void main(void) + {', ' vec2 v;', ' vec2 sv = aVertexPosition * aScale;', ' v.x = (sv.x) * cos(aRotation) - (sv.y) * sin(aRotation);', @@ -49,7 +51,8 @@ 'uniform sampler2D uSampler;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/PrimitiveShader.js b/src/core/renderers/webgl/shaders/PrimitiveShader.js index 6f25409..a25f54f 100644 --- a/src/core/renderers/webgl/shaders/PrimitiveShader.js +++ b/src/core/renderers/webgl/shaders/PrimitiveShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function PrimitiveShader(gl) { +function PrimitiveShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -23,7 +24,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + '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);', @@ -36,7 +38,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = vColor;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/Shader.js b/src/core/renderers/webgl/shaders/Shader.js index f8964f5..fd75ef5 100644 --- a/src/core/renderers/webgl/shaders/Shader.js +++ b/src/core/renderers/webgl/shaders/Shader.js @@ -6,7 +6,8 @@ * @param [fragmentSrc] {string} The source of the fragment shader. * @param [vertexSrc] {string} The source of the vertex shader. */ -function Shader(gl, vertexSrc, fragmentSrc, customUniforms, customAttributes) { +function Shader(gl, vertexSrc, fragmentSrc, customUniforms, customAttributes) +{ /** * @member {number} * @readonly @@ -33,7 +34,8 @@ dimensions: { type: '4f', value: new Float32Array(4) } }; - for (var u in customUniforms) { + for (var u in customUniforms) + { this.uniforms[u] = customUniforms[u]; } @@ -43,7 +45,8 @@ aColor: 0 }; - for (var a in customAttributes) { + for (var a in customAttributes) + { this.attributes[a] = customAttributes[a]; } @@ -66,7 +69,8 @@ 'const vec2 center = vec2(-1.0, 1.0);', - 'void main(void) {', + 'void main(void) + {', ' gl_Position = vec4( ((aVertexPosition + offsetVector) / projectionVector) + center , 0.0, 1.0);', ' vTextureCoord = aTextureCoord;', ' vColor = vec4(aColor.rgb * aColor.a, aColor.a);', @@ -85,7 +89,8 @@ 'uniform sampler2D uSampler;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;', '}' ].join('\n'); @@ -96,7 +101,8 @@ Shader.prototype.constructor = Shader; module.exports = Shader; -Shader.prototype.init = function () { +Shader.prototype.init = function () +{ this.compile(); this.gl.useProgram(this.program); @@ -105,14 +111,18 @@ this.cacheAttributeLocations(Object.keys(this.attributes)); }; -Shader.prototype.cacheUniformLocations = function (keys) { - for (var i = 0; i < keys.length; ++i) { +Shader.prototype.cacheUniformLocations = function (keys) +{ + for (var i = 0; i < keys.length; ++i) + { this.uniforms[keys[i]]._location = this.gl.getUniformLocation(this.program, keys[i]); } }; -Shader.prototype.cacheAttributeLocations = function (keys) { - for (var i = 0; i < keys.length; ++i) { +Shader.prototype.cacheAttributeLocations = function (keys) +{ + for (var i = 0; i < keys.length; ++i) + { this.attributes[keys[i]] = this.gl.getAttribLocation(this.program, keys[i]); } @@ -124,14 +134,16 @@ // 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.attributes.aColor === -1) { + // if (this.attributes.aColor === -1) + { // this.attributes.aColor = 2; // } // End worst hack eva // }; -Shader.prototype.compile = function () { +Shader.prototype.compile = function () +{ var gl = this.gl; var glVertShader = this._glCompile(gl.VERTEX_SHADER, this.vertexSrc); @@ -144,13 +156,15 @@ gl.linkProgram(program); // if linking fails, then log and cleanup - if (!gl.getProgramParameter(program, gl.LINK_STATUS)) { + if (!gl.getProgramParameter(program, gl.LINK_STATUS)) + { window.console.error('Pixi.js Error: Could not initialize shader.'); window.console.error('gl.VALIDATE_STATUS', gl.getProgramParameter(program, gl.VALIDATE_STATUS)); window.console.error('gl.getError()', gl.getError()); // if there is a program info log, log it - if (gl.getProgramInfoLog(program) !== '') { + if (gl.getProgramInfoLog(program) !== '') + { window.console.warn('Pixi.js Warning: gl.getProgramInfoLog()', gl.getProgramInfoLog(program)); } @@ -165,18 +179,21 @@ return (this.program = program); }; -Shader.prototype.syncUniforms = function () { +Shader.prototype.syncUniforms = function () +{ var gl = this.gl; this.textureCount = 1; - for (var key in this.uniforms) { + for (var key in this.uniforms) + { var uniform = this.uniforms[key], location = uniform._location, value = uniform.value, i, il; - switch (uniform.type) { + switch (uniform.type) + { // single int value case 'i': case '1i': @@ -282,7 +299,8 @@ // a Color Value case 'c': - if (typeof value === 'number') { + if (typeof value === 'number') + { value = utils.hex2rgb(value); } @@ -311,11 +329,13 @@ // array of 2D Point objects case 'v2v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(2 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 2] = value[i].x; uniform._array[i * 2 + 1] = value[i].y; } @@ -325,11 +345,13 @@ // array of 3D Point objects case 'v3v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(3 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 3] = value[i].x; uniform._array[i * 3 + 1] = value[i].y; uniform._array[i * 3 + 2] = value[i].z; @@ -341,11 +363,13 @@ // array of 4D Point objects case 'v4v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(4 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 4] = value[i].x; uniform._array[i * 4 + 1] = value[i].y; uniform._array[i * 4 + 2] = value[i].z; @@ -359,7 +383,8 @@ // PIXI.Texture case 't': case 'sampler2D': - if (!uniform.value || !uniform.value.baseTexture || !uniform.value.baseTexture.hasLoaded) { + if (!uniform.value || !uniform.value.baseTexture || !uniform.value.baseTexture.hasLoaded) + { break; } @@ -376,7 +401,8 @@ this.textureCount++; // initialize the texture if we haven't yet - if (!uniform._init) { + if (!uniform._init) + { this.initSampler2D(uniform); uniform._init = true; @@ -394,11 +420,13 @@ * Initialises a Sampler2D uniform (which may only be available later on after initUniforms once the texture has loaded) * */ -Shader.prototype.initSampler2D = function (uniform) { +Shader.prototype.initSampler2D = function (uniform) +{ var gl = this.gl; // Extended texture data - if (uniform.textureData) { + if (uniform.textureData) + { var data = uniform.textureData; // GLTexture = mag linear, min linear_mipmap_linear, wrap repeat + gl.generateMipmap(gl.TEXTURE_2D); @@ -417,14 +445,16 @@ var wrapT = (data.wrapT) ? data.wrapT : gl.CLAMP_TO_EDGE; var format = (data.luminance) ? gl.LUMINANCE : gl.RGBA; - if (data.repeat) { + if (data.repeat) + { wrapS = gl.REPEAT; wrapT = gl.REPEAT; } gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, !!data.flipY); - if (data.width) { + if (data.width) + { var width = (data.width) ? data.width : 512; var height = (data.height) ? data.height : 2; var border = (data.border) ? data.border : 0; @@ -432,7 +462,8 @@ // 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 { + 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); } @@ -448,7 +479,8 @@ * Destroys the shader. * */ -Shader.prototype.destroy = function () { +Shader.prototype.destroy = function () +{ this.gl.deleteProgram(this.program); this.gl = null; @@ -459,13 +491,15 @@ this.fragmentSrc = null; }; -Shader.prototype._glCompile = function (type, src) { +Shader.prototype._glCompile = function (type, src) +{ var shader = this.gl.createShader(type); this.gl.shaderSource(shader, src); this.gl.compileShader(shader); - if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) { + if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) + { window.console.log(this.gl.getShaderInfoLog(shader)); return null; } diff --git a/src/core/renderers/webgl/shaders/StripShader.js b/src/core/renderers/webgl/shaders/StripShader.js index 193f6e1..a7abcc6 100644 --- a/src/core/renderers/webgl/shaders/StripShader.js +++ b/src/core/renderers/webgl/shaders/StripShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function StripShader(gl) { +function StripShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -20,7 +21,8 @@ 'varying vec2 vTextureCoord;', - 'void main(void) {', + '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);', @@ -36,7 +38,8 @@ 'varying vec2 vTextureCoord;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vec2(vTextureCoord.x, vTextureCoord.y)) * alpha;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/utils/FilterTexture.js b/src/core/renderers/webgl/utils/FilterTexture.js index d2c8423..4433d44 100644 --- a/src/core/renderers/webgl/utils/FilterTexture.js +++ b/src/core/renderers/webgl/utils/FilterTexture.js @@ -8,7 +8,8 @@ * @param height {number} the vertical range of the filter * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values */ -function FilterTexture(gl, width, height, scaleMode) { +function FilterTexture(gl, width, height, scaleMode) +{ /** * @member {WebGLContext} */ @@ -59,7 +60,8 @@ * Clears the filter texture. * */ -FilterTexture.prototype.clear = function () { +FilterTexture.prototype.clear = function () +{ var gl = this.gl; gl.clearColor(0,0,0, 0); @@ -72,8 +74,10 @@ * @param width {number} the new width of the texture * @param height {number} the new height of the texture */ -FilterTexture.prototype.resize = function (width, height) { - if (this.width === width && this.height === height) { +FilterTexture.prototype.resize = function (width, height) +{ + if (this.width === width && this.height === height) + { return; } @@ -96,7 +100,8 @@ * Destroys the filter texture. * */ -FilterTexture.prototype.destroy = function () { +FilterTexture.prototype.destroy = function () +{ var gl = this.gl; gl.deleteFramebuffer( this.frameBuffer ); gl.deleteTexture( this.texture ); diff --git a/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js b/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js index c4721e9..a63f4d7 100644 --- a/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js +++ b/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js @@ -14,7 +14,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this sprite batch works for. */ -function WebGLFastSpriteBatch(renderer) { +function WebGLFastSpriteBatch(renderer) +{ /** * The renderer instance this sprite batch operates on. * @@ -91,7 +92,8 @@ */ this.lastIndexCount = 0; - for (var i=0, j=0; i < numIndices; i += 6, j += 4) { + 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; @@ -144,7 +146,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.setupContext(); }); } @@ -157,7 +160,8 @@ * * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLFastSpriteBatch.prototype.setupContext = function () { +WebGLFastSpriteBatch.prototype.setupContext = function () +{ var gl = this.renderer.gl; // create a couple of buffers @@ -177,7 +181,8 @@ /** * @param spriteBatch {SpriteBatch} The SpriteBatch container to prepare for. */ -WebGLFastSpriteBatch.prototype.begin = function (spriteBatch) { +WebGLFastSpriteBatch.prototype.begin = function (spriteBatch) +{ this.shader = this.renderer.shaderManager.fastShader; this.matrix = spriteBatch.worldTransform.toArray(true); @@ -187,33 +192,38 @@ /** */ -WebGLFastSpriteBatch.prototype.end = function () { +WebGLFastSpriteBatch.prototype.end = function () +{ this.flush(); }; /** * @param spriteBatch {SpriteBatch} The SpriteBatch container to render. */ -WebGLFastSpriteBatch.prototype.render = function (spriteBatch) { +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) { + if (!sprite.texture._uvs) + { return; } this.currentBaseTexture = sprite.texture.baseTexture; // check blend mode - if (sprite.blendMode !== this.renderer.blendModeManager.currentBlendMode) { + if (sprite.blendMode !== this.renderer.blendModeManager.currentBlendMode) + { this.flush(); this.renderer.blendModeManager.setBlendMode(sprite.blendMode); } - for (var i=0,j= children.length; i= this.size) { + if (this.currentBatchSize >= this.size) + { this.flush(); } }; @@ -362,29 +379,35 @@ /** * */ -WebGLFastSpriteBatch.prototype.flush = function () { +WebGLFastSpriteBatch.prototype.flush = function () +{ // If the batch is length 0 then return as there is nothing to draw - if (this.currentBatchSize === 0) { + if (this.currentBatchSize === 0) + { return; } var gl = this.renderer.gl; // bind the current texture - if (!this.currentBaseTexture._glTextures[gl.id]) { + if (!this.currentBaseTexture._glTextures[gl.id]) + { this.renderer.updateTexture(this.currentBaseTexture, gl); } //TODO-SHOUD THIS BE ELSE??!?!?! - else { + else + { gl.bindTexture(gl.TEXTURE_2D, this.currentBaseTexture._glTextures[gl.id]); } // upload the verts to the buffer - if (this.currentBatchSize > ( this.size * 0.5 ) ) { + if (this.currentBatchSize > ( this.size * 0.5 ) ) + { gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); } - else { + else + { var view = this.vertices.subarray(0, this.currentBatchSize * this.vertByteSize); gl.bufferSubData(gl.ARRAY_BUFFER, 0, view); @@ -405,14 +428,16 @@ * Ends the batch and flushes * */ -WebGLFastSpriteBatch.prototype.stop = function () { +WebGLFastSpriteBatch.prototype.stop = function () +{ this.flush(); }; /** * */ -WebGLFastSpriteBatch.prototype.start = function () { +WebGLFastSpriteBatch.prototype.start = function () +{ var gl = this.renderer.gl; // bind the main texture diff --git a/src/core/renderers/webgl/utils/WebGLGraphics.js b/src/core/renderers/webgl/utils/WebGLGraphics.js index 55f4911..ab8f46e 100644 --- a/src/core/renderers/webgl/utils/WebGLGraphics.js +++ b/src/core/renderers/webgl/utils/WebGLGraphics.js @@ -19,7 +19,8 @@ * @param graphics {Graphics} * @param renderer {WebGLRenderer} */ -WebGLGraphics.renderGraphics = function (graphics, renderer) {//projection, offset) { +WebGLGraphics.renderGraphics = function (graphics, renderer) {//projection, offset) +{ var gl = renderer.gl; var projection = renderer.projection, @@ -27,7 +28,8 @@ shader = renderer.shaderManager.primitiveShader, webGLData; - if (graphics.dirty) { + if (graphics.dirty) + { WebGLGraphics.updateGraphics(graphics, gl); } @@ -35,8 +37,10 @@ // This could be speeded up for sure! - for (var i = 0; i < webGL.data.length; i++) { - if (webGL.data[i].mode === 1) { + for (var i = 0; i < webGL.data.length; i++) + { + if (webGL.data[i].mode === 1) + { webGLData = webGL.data[i]; renderer.stencilManager.pushStencil(graphics, webGLData, renderer); @@ -46,7 +50,8 @@ renderer.stencilManager.popStencil(graphics, webGLData, renderer); } - else { + else + { webGLData = webGL.data[i]; @@ -84,12 +89,14 @@ * @param graphicsData {Graphics} The graphics object to update * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLGraphics.updateGraphics = function (graphics, gl) { +WebGLGraphics.updateGraphics = function (graphics, gl) +{ // get the contexts graphics object var webGL = graphics._webGL[gl.id]; // if the graphics object does not exist in the webGL context time to create it! - if (!webGL) { + if (!webGL) + { webGL = graphics._webGL[gl.id] = {lastIndex:0, data:[], gl:gl}; } @@ -99,11 +106,13 @@ var i; // if the user cleared the graphics object we will need to clear every object - if (graphics.clearDirty) { + if (graphics.clearDirty) + { graphics.clearDirty = false; // lop through and return all the webGLDatas to the object pool so than can be reused later on - for (i = 0; i < webGL.data.length; i++) { + for (i = 0; i < webGL.data.length; i++) + { var graphicsData = webGL.data[i]; graphicsData.reset(); WebGLGraphics.graphicsDataPool.push( graphicsData ); @@ -119,58 +128,72 @@ // loop through the graphics datas and construct each one.. // if the object is a complex fill then the new stencil buffer technique will be used // other wise graphics objects will be pushed into a batch.. - for (i = webGL.lastIndex; i < graphics.graphicsData.length; i++) { + for (i = webGL.lastIndex; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { // need to add the points the the graphics object.. data.points = data.shape.points.slice(); - if (data.shape.closed) { + if (data.shape.closed) + { // close the poly if the value is true! - if (data.points[0] !== data.points[data.points.length-2] || data.points[1] !== data.points[data.points.length-1]) { + if (data.points[0] !== data.points[data.points.length-2] || data.points[1] !== data.points[data.points.length-1]) + { data.points.push(data.points[0], data.points[1]); } } // MAKE SURE WE HAVE THE CORRECT TYPE.. - if (data.fill) { - if (data.points.length >= 6) { - if (data.points.length < 6 * 2) { + if (data.fill) + { + if (data.points.length >= 6) + { + if (data.points.length < 6 * 2) + { webGLData = WebGLGraphics.switchMode(webGL, 0); var canDrawUsingSimple = WebGLGraphics.buildPoly(data, webGLData); // console.log(canDrawUsingSimple); - if (!canDrawUsingSimple) { + if (!canDrawUsingSimple) + { // console.log("<>>>") webGLData = WebGLGraphics.switchMode(webGL, 1); WebGLGraphics.buildComplexPoly(data, webGLData); } } - else { + else + { webGLData = WebGLGraphics.switchMode(webGL, 1); WebGLGraphics.buildComplexPoly(data, webGLData); } } } - if (data.lineWidth > 0) { + if (data.lineWidth > 0) + { webGLData = WebGLGraphics.switchMode(webGL, 0); WebGLGraphics.buildLine(data, webGLData); } } - else { + else + { webGLData = WebGLGraphics.switchMode(webGL, 0); - if (data.type === CONST.SHAPES.RECT) { + if (data.type === CONST.SHAPES.RECT) + { WebGLGraphics.buildRectangle(data, webGLData); } - else if (data.type === CONST.SHAPES.CIRC || data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.CIRC || data.type === CONST.SHAPES.ELIP) + { WebGLGraphics.buildCircle(data, webGLData); } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { WebGLGraphics.buildRoundedRectangle(data, webGLData); } } @@ -179,10 +202,12 @@ } // upload all the dirty data... - for (i = 0; i < webGL.data.length; i++) { + for (i = 0; i < webGL.data.length; i++) + { webGLData = webGL.data[i]; - if (webGLData.dirty) { + if (webGLData.dirty) + { webGLData.upload(); } } @@ -194,18 +219,22 @@ * @param webGL {WebGLContext} * @param type {number} */ -WebGLGraphics.switchMode = function (webGL, type) { +WebGLGraphics.switchMode = function (webGL, type) +{ var webGLData; - if (!webGL.data.length) { + if (!webGL.data.length) + { webGLData = WebGLGraphics.graphicsDataPool.pop() || new WebGLGraphicsData(webGL.gl); webGLData.mode = type; webGL.data.push(webGLData); } - else { + else + { webGLData = webGL.data[webGL.data.length-1]; - if (webGLData.mode !== type || type === 1) { + if (webGLData.mode !== type || type === 1) + { webGLData = WebGLGraphics.graphicsDataPool.pop() || new WebGLGraphicsData(webGL.gl); webGLData.mode = type; webGL.data.push(webGLData); @@ -225,7 +254,8 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildRectangle = function (graphicsData, webGLData) { +WebGLGraphics.buildRectangle = function (graphicsData, webGLData) +{ // --- // // need to convert points to a nice regular data // @@ -235,7 +265,8 @@ var width = rectData.width; var height = rectData.height; - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -265,7 +296,8 @@ indices.push(vertPos, vertPos, vertPos+1, vertPos+2, vertPos+3, vertPos+3); } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = [x, y, @@ -289,7 +321,8 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildRoundedRectangle = function (graphicsData, webGLData) { +WebGLGraphics.buildRoundedRectangle = function (graphicsData, webGLData) +{ var rrectData = graphicsData.shape; var x = rrectData.x; var y = rrectData.y; @@ -305,7 +338,8 @@ recPoints = recPoints.concat(WebGLGraphics.quadraticBezierCurve(x + width, y + radius, x + width, y, x + width - radius, y)); recPoints = recPoints.concat(WebGLGraphics.quadraticBezierCurve(x + radius, y, x, y, x, y + radius)); - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -323,7 +357,8 @@ // var i = 0; - for (i = 0; i < triangles.length; i+=3) { + for (i = 0; i < triangles.length; i+=3) + { indices.push(triangles[i] + vecPos); indices.push(triangles[i] + vecPos); indices.push(triangles[i+1] + vecPos); @@ -332,12 +367,14 @@ } - for (i = 0; i < recPoints.length; i++) { + for (i = 0; i < recPoints.length; i++) + { verts.push(recPoints[i], recPoints[++i], r, g, b, alpha); } } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = recPoints; @@ -362,7 +399,8 @@ * @param toY {number} Destination point y * @return {number[]} */ -WebGLGraphics.quadraticBezierCurve = function (fromX, fromY, cpX, cpY, toX, toY) { +WebGLGraphics.quadraticBezierCurve = function (fromX, fromY, cpX, cpY, toX, toY) +{ var xa, ya, @@ -373,14 +411,16 @@ n = 20, points = []; - function getPt(n1 , n2, perc) { + function getPt(n1 , n2, perc) + { var diff = n2 - n1; return n1 + ( diff * perc ); } var j = 0; - for (var i = 0; i <= n; i++ ) { + for (var i = 0; i <= n; i++ ) + { j = i / n; // The Green Line @@ -406,7 +446,8 @@ * @param graphicsData {Graphics} The graphics object to draw * @param webGLData {object} */ -WebGLGraphics.buildCircle = function (graphicsData, webGLData) { +WebGLGraphics.buildCircle = function (graphicsData, webGLData) +{ // need to convert points to a nice regular data var circleData = graphicsData.shape; var x = circleData.x; @@ -415,11 +456,13 @@ var height; // TODO - bit hacky?? - if (graphicsData.type === CONST.SHAPES.CIRC) { + if (graphicsData.type === CONST.SHAPES.CIRC) + { width = circleData.radius; height = circleData.radius; } - else { + else + { width = circleData.width; height = circleData.height; } @@ -429,7 +472,8 @@ var i = 0; - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -444,7 +488,8 @@ indices.push(vecPos); - for (i = 0; i < totalSegs + 1 ; i++) { + for (i = 0; i < totalSegs + 1 ; i++) + { verts.push(x,y, r, g, b, alpha); verts.push(x + Math.sin(seg * i) * width, @@ -457,12 +502,14 @@ indices.push(vecPos-1); } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = []; - for (i = 0; i < totalSegs + 1; i++) { + for (i = 0; i < totalSegs + 1; i++) + { graphicsData.points.push(x + Math.sin(seg * i) * width, y + Math.cos(seg * i) * height); } @@ -481,18 +528,22 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildLine = function (graphicsData, webGLData) { +WebGLGraphics.buildLine = function (graphicsData, webGLData) +{ // TODO OPTIMISE! var i = 0; var points = graphicsData.points; - if (points.length === 0) { + if (points.length === 0) + { return; } // if the line width is an odd number add 0.5 to align to a whole pixel - if (graphicsData.lineWidth%2) { - for (i = 0; i < points.length; i++) { + if (graphicsData.lineWidth%2) + { + for (i = 0; i < points.length; i++) + { points[i] += 0.5; } } @@ -502,7 +553,8 @@ var lastPoint = new math.Point(points[points.length - 2], points[points.length - 1]); // if the first point is the last point - gonna have issues :) - if (firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) { + if (firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) + { // need to clone as we are going to slightly modify the shape.. points = points.slice(); @@ -562,7 +614,8 @@ verts.push(p1x + perpx , p1y + perpy, r, g, b, alpha); - for (i = 1; i < length-1; i++) { + for (i = 1; i < length-1; i++) + { p1x = points[(i-1)*2]; p1y = points[(i-1)*2 + 1]; @@ -599,7 +652,8 @@ denom = a1*b2 - a2*b1; - if (Math.abs(denom) < 0.1 ) { + if (Math.abs(denom) < 0.1 ) + { denom+=10.1; verts.push(p2x - perpx , p2y - perpy, @@ -618,7 +672,8 @@ pdist = (px -p2x) * (px -p2x) + (py -p2y) + (py -p2y); - if (pdist > 140 * 140) { + if (pdist > 140 * 140) + { perp3x = perpx - perp2x; perp3y = perpy - perp2y; @@ -639,7 +694,8 @@ indexCount++; } - else { + else + { verts.push(px , py); verts.push(r, g, b, alpha); @@ -672,7 +728,8 @@ indices.push(indexStart); - for (i = 0; i < indexCount; i++) { + for (i = 0; i < indexCount; i++) + { indices.push(indexStart++); } @@ -687,11 +744,13 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildComplexPoly = function (graphicsData, webGLData) { +WebGLGraphics.buildComplexPoly = function (graphicsData, webGLData) +{ //TODO - no need to copy this as it gets turned into a FLoat32Array anyways.. var points = graphicsData.points.slice(); - if (points.length < 6) { + if (points.length < 6) + { return; } @@ -711,7 +770,8 @@ var x,y; // get size.. - for (var i = 0; i < points.length; i+=2) { + for (var i = 0; i < points.length; i+=2) + { x = points[i]; y = points[i+1]; @@ -732,7 +792,8 @@ //TODO - this aint needed! var length = points.length / 2; - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { indices.push( i ); } @@ -746,10 +807,12 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildPoly = function (graphicsData, webGLData) { +WebGLGraphics.buildPoly = function (graphicsData, webGLData) +{ var points = graphicsData.points; - if (points.length < 6) { + if (points.length < 6) + { return; } // get first and last point.. figure out the middle! @@ -767,7 +830,8 @@ var triangles = utils.PolyK.Triangulate(points); - if (!triangles) { + if (!triangles) + { return false; } @@ -775,7 +839,8 @@ var i = 0; - for (i = 0; i < triangles.length; i+=3) { + for (i = 0; i < triangles.length; i+=3) + { indices.push(triangles[i] + vertPos); indices.push(triangles[i] + vertPos); indices.push(triangles[i+1] + vertPos); @@ -783,7 +848,8 @@ indices.push(triangles[i+2] + vertPos); } - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { verts.push(points[i * 2], points[i * 2 + 1], r, g, b, alpha); } diff --git a/src/core/renderers/webgl/utils/WebGLGraphicsData.js b/src/core/renderers/webgl/utils/WebGLGraphicsData.js index c56d05e..c739ba7 100644 --- a/src/core/renderers/webgl/utils/WebGLGraphicsData.js +++ b/src/core/renderers/webgl/utils/WebGLGraphicsData.js @@ -2,7 +2,8 @@ * @class * @private */ -function WebGLGraphicsData(gl) { +function WebGLGraphicsData(gl) +{ this.gl = gl; //TODO does this need to be split before uploding?? @@ -22,7 +23,8 @@ /** * */ -WebGLGraphicsData.prototype.reset = function () { +WebGLGraphicsData.prototype.reset = function () +{ this.points.length = 0; this.indices.length = 0; }; @@ -30,7 +32,8 @@ /** * */ -WebGLGraphicsData.prototype.upload = function () { +WebGLGraphicsData.prototype.upload = function () +{ var gl = this.gl; // this.lastIndex = graphics.graphicsData.length; diff --git a/src/core/renderers/webgl/utils/WebGLSpriteBatch.js b/src/core/renderers/webgl/utils/WebGLSpriteBatch.js index 96eaa52..55befbb 100644 --- a/src/core/renderers/webgl/utils/WebGLSpriteBatch.js +++ b/src/core/renderers/webgl/utils/WebGLSpriteBatch.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this sprite batch works for. */ -function WebGLSpriteBatch(renderer) { +function WebGLSpriteBatch(renderer) +{ /** * * @@ -88,7 +89,8 @@ */ this.lastIndexCount = 0; - for (var i=0, j=0; i < numIndices; i += 6, j += 4) { + 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; @@ -162,7 +164,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.setupContext(); }); } @@ -173,7 +176,8 @@ /** * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLSpriteBatch.prototype.setupContext = function () { +WebGLSpriteBatch.prototype.setupContext = function () +{ var gl = this.renderer.gl; // setup default shader @@ -198,7 +202,8 @@ /** * */ -WebGLSpriteBatch.prototype.begin = function () { +WebGLSpriteBatch.prototype.begin = function () +{ // this.shader = this.renderer.shaderManager.defaultShader; this.start(); @@ -206,19 +211,22 @@ /** */ -WebGLSpriteBatch.prototype.end = function () { +WebGLSpriteBatch.prototype.end = function () +{ this.flush(); }; /** * @param sprite {Sprite} the sprite to render when using this spritebatch */ -WebGLSpriteBatch.prototype.render = function (sprite) { +WebGLSpriteBatch.prototype.render = function (sprite) +{ var texture = sprite.texture; //TODO set blend modes.. // check texture.. - if (this.currentBatchSize >= this.size) { + if (this.currentBatchSize >= this.size) + { this.flush(); this.currentBaseTexture = texture.baseTexture; } @@ -227,7 +235,8 @@ var uvs = texture._uvs; // if the uvs have not updated then no point rendering just yet! - if (!uvs) { + if (!uvs) + { return; } @@ -237,7 +246,8 @@ var w0, w1, h0, h1; - if (texture.trim) { + 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; @@ -248,7 +258,8 @@ h0 = h1 + texture.crop.height; } - else { + else + { w0 = (texture.frame.width ) * (1-aX); w1 = (texture.frame.width ) * -aX; @@ -272,7 +283,8 @@ var colors = this.colors; var positions = this.positions; - if (this.renderer.roundPixels) { + if (this.renderer.roundPixels) + { // xy positions[index] = a * w1 + c * h1 + tx | 0; positions[index+1] = d * h1 + b * w1 + ty | 0; @@ -289,7 +301,8 @@ positions[index+15] = a * w1 + c * h0 + tx | 0; positions[index+16] = d * h0 + b * w1 + ty | 0; } - else { + else + { // xy positions[index] = a * w1 + c * h1 + tx; positions[index+1] = d * h1 + b * w1 + ty; @@ -338,11 +351,13 @@ * * @param sprite {TilingSprite} the tilingSprite to render */ -WebGLSpriteBatch.prototype.renderTilingSprite = function (tilingSprite) { +WebGLSpriteBatch.prototype.renderTilingSprite = function (tilingSprite) +{ var texture = tilingSprite.tilingTexture; // check texture.. - if (this.currentBatchSize >= this.size) { + if (this.currentBatchSize >= this.size) + { //return; this.flush(); this.currentBaseTexture = texture.baseTexture; @@ -351,7 +366,8 @@ // set the textures uvs temporarily // TODO create a separate texture so that we can tile part of a texture - if (!tilingSprite._uvs) { + if (!tilingSprite._uvs) + { tilingSprite._uvs = new TextureUvs(); } @@ -454,16 +470,19 @@ * Renders the content and empties the current batch. * */ -WebGLSpriteBatch.prototype.flush = function () { +WebGLSpriteBatch.prototype.flush = function () +{ // If the batch is length 0 then return as there is nothing to draw - if (this.currentBatchSize === 0) { + if (this.currentBatchSize === 0) + { return; } var gl = this.renderer.gl; var shader; - if (this.dirty) { + if (this.dirty) + { this.dirty = false; // bind the main texture gl.activeTexture(gl.TEXTURE0); @@ -482,10 +501,12 @@ } // upload the verts to the buffer - if (this.currentBatchSize > ( this.size * 0.5 ) ) { + if (this.currentBatchSize > ( this.size * 0.5 ) ) + { gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); } - else { + else + { var view = this.positions.subarray(0, this.currentBatchSize * this.vertByteSize); gl.bufferSubData(gl.ARRAY_BUFFER, 0, view); } @@ -502,7 +523,8 @@ var shaderSwap = false; var sprite; - for (var i = 0, j = this.currentBatchSize; i < j; i++) { + for (var i = 0, j = this.currentBatchSize; i < j; i++) + { sprite = this.sprites[i]; @@ -513,24 +535,28 @@ blendSwap = currentBlendMode !== nextBlendMode; shaderSwap = currentShader !== nextShader; // should I use uuidS??? - if (currentBaseTexture !== nextTexture || blendSwap || shaderSwap) { + if (currentBaseTexture !== nextTexture || blendSwap || shaderSwap) + { this.renderBatch(currentBaseTexture, batchSize, start); start = i; batchSize = 0; currentBaseTexture = nextTexture; - if (blendSwap) { + if (blendSwap) + { currentBlendMode = nextBlendMode; this.renderer.blendModeManager.setBlendMode( currentBlendMode ); } - if (shaderSwap) { + if (shaderSwap) + { currentShader = nextShader; shader = currentShader.shaders ? currentShader.shaders[gl.id] : currentShader; - if (!shader) { + if (!shader) + { shader = new Shader(gl, null, currentShader.fragmentSrc, currentShader.uniforms); currentShader.shaders[gl.id] = shader; } @@ -538,7 +564,8 @@ // set shader function??? this.renderer.shaderManager.setShader(shader); - if (shader.dirty) { + if (shader.dirty) + { shader.syncUniforms(); } @@ -569,17 +596,21 @@ * @param size {number} * @param startIndex {number} */ -WebGLSpriteBatch.prototype.renderBatch = function (texture, size, startIndex) { - if (size === 0) { +WebGLSpriteBatch.prototype.renderBatch = function (texture, size, startIndex) +{ + if (size === 0) + { return; } var gl = this.renderer.gl; - if (!texture._glTextures[gl.id]) { + if (!texture._glTextures[gl.id]) + { this.renderer.updateTexture(texture); } - else { + else + { // bind the current texture gl.bindTexture(gl.TEXTURE_2D, texture._glTextures[gl.id]); } @@ -594,7 +625,8 @@ /** * */ -WebGLSpriteBatch.prototype.stop = function () { +WebGLSpriteBatch.prototype.stop = function () +{ this.flush(); this.dirty = true; }; @@ -602,7 +634,8 @@ /** * */ -WebGLSpriteBatch.prototype.start = function () { +WebGLSpriteBatch.prototype.start = function () +{ this.dirty = true; }; @@ -610,7 +643,8 @@ * Destroys the SpriteBatch. * */ -WebGLSpriteBatch.prototype.destroy = function () { +WebGLSpriteBatch.prototype.destroy = function () +{ this.renderer.gl.deleteBuffer(this.vertexBuffer); this.renderer.gl.deleteBuffer(this.indexBuffer); diff --git a/src/core/textures/BaseTexture.js b/src/core/textures/BaseTexture.js index 2bf77d4..513d358 100644 --- a/src/core/textures/BaseTexture.js +++ b/src/core/textures/BaseTexture.js @@ -10,7 +10,8 @@ * @param source {Image|Canvas} the source object of the texture. * @param [scaleMode=scaleModes.DEFAULT] {number} See {@link scaleModes} for possible values */ -function BaseTexture(source, scaleMode) { +function BaseTexture(source, scaleMode) +{ this.uuid = utils.uuid(); /** @@ -123,7 +124,8 @@ this._needsUpdate = false; // if no source passed don't try to load - if (source) { + if (source) + { this.loadSource(source); } @@ -149,13 +151,16 @@ Object.defineProperties(BaseTexture.prototype, { needsUpdate: { - get: function () { + get: function () + { return this._needsUpdate; }, - set: function (val) { + set: function (val) + { this._needsUpdate = val; - if (val) { + if (val) + { this.emit('update', this); } } @@ -171,9 +176,11 @@ * * The logic state after calling `loadSource` directly or indirectly (eg. `fromImage`, `new BaseTexture`) is: * - * if (texture.hasLoaded) { + * if (texture.hasLoaded) + { * // texture ready for use - * } else if (texture.isLoading) { + * } else if (texture.isLoading) + { * // listen to 'loaded' and/or 'error' events on texture * } else { * // not loading, not going to load UNLESS the source is reloaded @@ -183,12 +190,14 @@ * @protected * @param source {Image|Canvas} the source object of the texture. */ -BaseTexture.prototype.loadSource = function (source) { +BaseTexture.prototype.loadSource = function (source) +{ var wasLoading = this.isLoading; this.hasLoaded = false; this.isLoading = false; - if (wasLoading && this.source) { + if (wasLoading && this.source) + { this.source.onload = null; this.source.onerror = null; } @@ -196,20 +205,24 @@ this.source = source; // Apply source if loaded. Otherwise setup appropriate loading monitors. - if ((this.source.complete || this.source.getContext) && this.source.width && this.source.height) { + if ((this.source.complete || this.source.getContext) && this.source.width && this.source.height) + { this._sourceLoaded(); } - else if(!source.getContext) { + else if(!source.getContext) + { // Image fail / not ready this.isLoading = true; var scope = this; - source.onload = function () { + source.onload = function () + { source.onload = null; source.onerror = null; - if(!scope.isLoading) { + if(!scope.isLoading) + { return; } @@ -219,11 +232,13 @@ scope.emit('loaded', scope); }; - source.onerror = function () { + source.onerror = function () + { source.onload = null; source.onerror = null; - if(!scope.isLoading) { + if(!scope.isLoading) + { return; } @@ -234,24 +249,29 @@ // Per http://www.w3.org/TR/html5/embedded-content-0.html#the-img-element // "The value of `complete` can thus change while a script is executing." // So complete needs to be re-checked after the callbacks have been added.. - if (source.complete) { + if (source.complete) + { this.isLoading = false; // ..and if we're complete now, no need for callbacks source.onload = null; source.onerror = null; - if (source.width && source.height) { + if (source.width && source.height) + { this._sourceLoaded(); // If any previous subscribers possible - if (wasLoading) { + if (wasLoading) + { this.emit('loaded', this); } } - else { + else + { // If any previous subscribers possible - if (wasLoading) { + if (wasLoading) + { this.emit('error', this); } } @@ -265,7 +285,8 @@ * * @private */ -BaseTexture.prototype._sourceLoaded = function () { +BaseTexture.prototype._sourceLoaded = function () +{ this.hasLoaded = true; this.width = this.source.naturalWidth || this.source.width; @@ -278,16 +299,20 @@ * Destroys this base texture * */ -BaseTexture.prototype.destroy = function () { - if (this.imageUrl) { +BaseTexture.prototype.destroy = function () +{ + if (this.imageUrl) + { delete utils.BaseTextureCache[this.imageUrl]; delete utils.TextureCache[this.imageUrl]; this.imageUrl = null; - if (!navigator.isCocoonJS) { + if (!navigator.isCocoonJS) + { this.source.src = ''; } } - else if (this.source && this.source._pixiId) { + else if (this.source && this.source._pixiId) + { delete utils.BaseTextureCache[this.source._pixiId]; } this.source = null; @@ -301,7 +326,8 @@ * memory again. * */ -BaseTexture.prototype.dispose = function () { +BaseTexture.prototype.dispose = function () +{ this.emit('dispose', this); }; @@ -311,7 +337,8 @@ * * @param newSrc {string} the path of the image */ -BaseTexture.prototype.updateSourceImage = function (newSrc) { +BaseTexture.prototype.updateSourceImage = function (newSrc) +{ this.source.src = newSrc; this.loadSource(this.source); }; @@ -326,18 +353,22 @@ * @param [scaleMode=scaleModes.DEFAULT] {number} See {@link scaleModes} for possible values * @return BaseTexture */ -BaseTexture.fromImage = function (imageUrl, crossorigin, scaleMode) { +BaseTexture.fromImage = function (imageUrl, crossorigin, scaleMode) +{ var baseTexture = utils.BaseTextureCache[imageUrl]; - if (crossorigin === undefined && imageUrl.indexOf('data:') !== 0) { + if (crossorigin === undefined && imageUrl.indexOf('data:') !== 0) + { crossorigin = true; } - if (!baseTexture) { + if (!baseTexture) + { // new Image() breaks tex loading in some versions of Chrome. // See https://code.google.com/p/chromium/issues/detail?id=238071 var image = new Image();//document.createElement('img'); - if (crossorigin) { + if (crossorigin) + { image.crossOrigin = ''; } @@ -347,7 +378,8 @@ utils.BaseTextureCache[imageUrl] = baseTexture; // if there is an @2x at the end of the url we are going to assume its a highres image - if ( imageUrl.indexOf(CONST.RETINA_PREFIX + '.') !== -1) { + if ( imageUrl.indexOf(CONST.RETINA_PREFIX + '.') !== -1) + { baseTexture.resolution = 2; } } @@ -363,14 +395,17 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return BaseTexture */ -BaseTexture.fromCanvas = function (canvas, scaleMode) { - if (!canvas._pixiId) { +BaseTexture.fromCanvas = function (canvas, scaleMode) +{ + if (!canvas._pixiId) + { canvas._pixiId = 'canvas_' + utils.uuid(); } var baseTexture = utils.BaseTextureCache[canvas._pixiId]; - if (!baseTexture) { + if (!baseTexture) + { baseTexture = new BaseTexture(canvas, scaleMode); utils.BaseTextureCache[canvas._pixiId] = baseTexture; } diff --git a/src/core/textures/RenderTexture.js b/src/core/textures/RenderTexture.js index 6dad20f..53ae796 100644 --- a/src/core/textures/RenderTexture.js +++ b/src/core/textures/RenderTexture.js @@ -46,8 +46,10 @@ * @param [scaleMode] {number} See {@link scaleModes} for possible values * @param [resolution=1] {number} The resolution of the texture being generated */ -function RenderTexture(renderer, width, height, scaleMode, resolution) { - if (!renderer) { +function RenderTexture(renderer, width, height, scaleMode, resolution) +{ + if (!renderer) + { throw new Error('Unable to create RenderTexture, you must pass a renderer into the constructor.'); } @@ -133,7 +135,8 @@ */ this.renderer = renderer; - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { var gl = this.renderer.gl; this.textureBuffer = new FilterTexture(gl, this.width * this.resolution, this.height * this.resolution, this.baseTexture.scaleMode); @@ -142,7 +145,8 @@ this.render = this.renderWebGL; this.projection = new math.Point(this.width*0.5, -this.height*0.5); } - else { + else + { this.render = this.renderCanvas; this.textureBuffer = new CanvasBuffer(this.width* this.resolution, this.height* this.resolution); this.baseTexture.source = this.textureBuffer.canvas; @@ -167,8 +171,10 @@ * @param height {number} The height to resize to. * @param updateBase {boolean} Should the baseTexture.width and height values be resized as well? */ -RenderTexture.prototype.resize = function (width, height, updateBase) { - if (width === this.width && height === this.height) { +RenderTexture.prototype.resize = function (width, height, updateBase) +{ + if (width === this.width && height === this.height) + { return; } @@ -177,17 +183,20 @@ this.width = this.frame.width = this.crop.width = width; this.height = this.frame.height = this.crop.height = height; - if (updateBase) { + if (updateBase) + { this.baseTexture.width = this.width; this.baseTexture.height = this.height; } - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { this.projection.x = this.width / 2; this.projection.y = -this.height / 2; } - if (!this.valid) { + if (!this.valid) + { return; } @@ -198,12 +207,15 @@ * Clears the RenderTexture. * */ -RenderTexture.prototype.clear = function () { - if (!this.valid) { +RenderTexture.prototype.clear = function () +{ + if (!this.valid) + { return; } - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { this.renderer.gl.bindFramebuffer(this.renderer.gl.FRAMEBUFFER, this.textureBuffer.frameBuffer); } @@ -220,19 +232,23 @@ * @param [restoreWorldTransform=true] {boolean} If true the displayObject's worldTransform/worldAlpha and all children * transformations will be restored. Not restoring this information will be a little faster. */ -RenderTexture.prototype.renderWebGL = function (displayObject, matrix, clear, restoreWorldTransform) { - if (!this.valid) { +RenderTexture.prototype.renderWebGL = function (displayObject, matrix, clear, restoreWorldTransform) +{ + if (!this.valid) + { return; } - if (typeof restoreWorldTransform === 'undefined') { + if (typeof restoreWorldTransform === 'undefined') + { restoreWorldTransform = true; } var tempAlpha, tempTransform; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { tempAlpha = displayObject.worldAlpha; tempTransform = displayObject.worldTransform.toArray(); } @@ -245,7 +261,8 @@ wt.identity(); wt.translate(0, this.projection.y * 2); - if (matrix) { + if (matrix) + { wt.append(matrix); } @@ -258,7 +275,8 @@ var children = displayObject.children; var i, j; - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } @@ -269,7 +287,8 @@ gl.bindFramebuffer(gl.FRAMEBUFFER, this.textureBuffer.frameBuffer ); - if (clear) { + if (clear) + { this.textureBuffer.clear(); } @@ -279,11 +298,13 @@ this.renderer.spriteBatch.dirty = true; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { displayObject.worldAlpha = tempAlpha; displayObject.worldTransform.fromArray(tempTransform); - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } } @@ -300,26 +321,31 @@ * @param [restoreWorldTransform=true] {boolean} If true the displayObject's worldTransform/worldAlpha and all children * transformations will be restored. Not restoring this information will be a little faster. */ -RenderTexture.prototype.renderCanvas = function (displayObject, matrix, clear, restoreWorldTransform) { - if (!this.valid) { +RenderTexture.prototype.renderCanvas = function (displayObject, matrix, clear, restoreWorldTransform) +{ + if (!this.valid) + { return; } - if (typeof restoreWorldTransform === 'undefined') { + if (typeof restoreWorldTransform === 'undefined') + { restoreWorldTransform = true; } var tempAlpha, tempTransform; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { tempAlpha = displayObject.worldAlpha; tempTransform = displayObject.worldTransform.toArray(); } var wt = displayObject.worldTransform; wt.identity(); - if (matrix) { + if (matrix) + { wt.append(matrix); } @@ -330,11 +356,13 @@ var children = displayObject.children; var i, j; - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } - if (clear) { + if (clear) + { this.textureBuffer.clear(); } @@ -348,11 +376,13 @@ this.renderer.resolution = realResolution; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { displayObject.worldAlpha = tempAlpha; displayObject.worldTransform.fromArray(tempTransform); - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } } @@ -363,7 +393,8 @@ * * @return {Image} */ -RenderTexture.prototype.getImage = function () { +RenderTexture.prototype.getImage = function () +{ var image = new Image(); image.src = this.getBase64(); return image; @@ -374,7 +405,8 @@ * * @return {string} A base64 encoded string of the texture. */ -RenderTexture.prototype.getBase64 = function () { +RenderTexture.prototype.getBase64 = function () +{ return this.getCanvas().toDataURL(); }; @@ -383,8 +415,10 @@ * * @return {HTMLCanvasElement} A Canvas element with the texture rendered on. */ -RenderTexture.prototype.getCanvas = function () { - if (this.renderer.type === CONST.WEBGL_RENDERER) { +RenderTexture.prototype.getCanvas = function () +{ + if (this.renderer.type === CONST.WEBGL_RENDERER) + { var gl = this.renderer.gl; var width = this.textureBuffer.width; var height = this.textureBuffer.height; @@ -403,7 +437,8 @@ return tempCanvas.canvas; } - else { + else + { return this.textureBuffer.canvas; } }; diff --git a/src/core/textures/Texture.js b/src/core/textures/Texture.js index 3c65909..e97f0aa 100644 --- a/src/core/textures/Texture.js +++ b/src/core/textures/Texture.js @@ -17,7 +17,8 @@ * @param [crop] {Rectangle} The area of original texture * @param [trim] {Rectangle} Trimmed texture rectangle */ -function Texture(baseTexture, frame, crop, trim) { +function Texture(baseTexture, frame, crop, trim) +{ /** * Does this Texture have any frame data assigned to it? * @@ -25,12 +26,14 @@ */ this.noFrame = false; - if (!frame) { + if (!frame) + { this.noFrame = true; frame = new math.Rectangle(0, 0, 1, 1); } - if (baseTexture instanceof Texture) { + if (baseTexture instanceof Texture) + { baseTexture = baseTexture.baseTexture; } @@ -100,13 +103,16 @@ */ this.crop = crop || new math.Rectangle(0, 0, 1, 1); - if (baseTexture.hasLoaded) { - if (this.noFrame) { + if (baseTexture.hasLoaded) + { + if (this.noFrame) + { frame = new math.Rectangle(0, 0, baseTexture.width, baseTexture.height); } this.frame = frame; } - else { + else + { baseTexture.addEventListener('loaded', this.onBaseTextureLoaded.bind(this)); } } @@ -118,19 +124,23 @@ Object.defineProperties(Texture.prototype, { needsUpdate: { - get: function () { + get: function () + { return this.baseTexture.needsUpdate; }, - set: function (val) { + set: function (val) + { this.baseTexture.needsUpdate = val; } }, frame: { - get: function () { + get: function () + { return this._frame; }, - set: function (frame) { + set: function (frame) + { this._frame = frame; this.noFrame = false; @@ -143,20 +153,23 @@ 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 (!this.trim && (frame.x + frame.width > this.baseTexture.width || frame.y + frame.height > this.baseTexture.height)) + { throw new Error('Texture Error: frame does not fit inside the base Texture dimensions ' + this); } this.valid = frame && frame.width && frame.height && this.baseTexture.source && this.baseTexture.hasLoaded; - if (this.trim) { + 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) { + if (this.valid) + { this._updateUvs(); } } @@ -168,11 +181,13 @@ * * @private */ -Texture.prototype.onBaseTextureLoaded = function () { +Texture.prototype.onBaseTextureLoaded = function () +{ var baseTexture = this.baseTexture; baseTexture.removeEventListener('loaded', this.onLoaded); - if (this.noFrame) { + if (this.noFrame) + { this.frame = new math.Rectangle(0, 0, baseTexture.width, baseTexture.height); } @@ -184,8 +199,10 @@ * * @param destroyBase {boolean} Whether to destroy the base texture as well */ -Texture.prototype.destroy = function (destroyBase) { - if (destroyBase) { +Texture.prototype.destroy = function (destroyBase) +{ + if (destroyBase) + { this.baseTexture.destroy(); } @@ -197,8 +214,10 @@ * * @private */ -Texture.prototype._updateUvs = function () { - if (!this._uvs) { +Texture.prototype._updateUvs = function () +{ + if (!this._uvs) + { this._uvs = new TextureUvs(); } @@ -229,10 +248,12 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return Texture */ -Texture.fromImage = function (imageUrl, crossorigin, scaleMode) { +Texture.fromImage = function (imageUrl, crossorigin, scaleMode) +{ var texture = utils.TextureCache[imageUrl]; - if (!texture) { + if (!texture) + { texture = new Texture(BaseTexture.fromImage(imageUrl, crossorigin, scaleMode)); utils.TextureCache[imageUrl] = texture; } @@ -248,9 +269,11 @@ * @param frameId {string} The frame id of the texture * @return Texture */ -Texture.fromFrame = function (frameId) { +Texture.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache '); } return texture; @@ -264,7 +287,8 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return {Texture} */ -Texture.fromCanvas = function (canvas, scaleMode) { +Texture.fromCanvas = function (canvas, scaleMode) +{ return new Texture(BaseTexture.fromCanvas(canvas, scaleMode)); }; @@ -276,7 +300,8 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return {Texture} A Texture */ -Texture.fromVideo = function (video, scaleMode) { +Texture.fromVideo = function (video, scaleMode) +{ return new Texture(VideoBaseTexture.baseTextureFromVideo(video, scaleMode)); }; @@ -287,7 +312,8 @@ * @param texture {Texture} The Texture to add to the cache. * @param id {string} The id that the texture will be stored against. */ -Texture.addTextureToCache = function (texture, id) { +Texture.addTextureToCache = function (texture, id) +{ utils.TextureCache[id] = texture; }; @@ -298,7 +324,8 @@ * @param id {string} The id of the texture to be removed * @return {Texture} The texture that was removed */ -Texture.removeTextureFromCache = function (id) { +Texture.removeTextureFromCache = function (id) +{ var texture = utils.TextureCache[id]; delete utils.TextureCache[id]; diff --git a/src/core/textures/TextureUvs.js b/src/core/textures/TextureUvs.js index b9bbb58..5424d52 100644 --- a/src/core/textures/TextureUvs.js +++ b/src/core/textures/TextureUvs.js @@ -1,4 +1,5 @@ -function TextureUvs() { +function TextureUvs() +{ this.x0 = 0; this.y0 = 0; diff --git a/src/core/textures/VideoBaseTexture.js b/src/core/textures/VideoBaseTexture.js index e3e0c5a..1a826a9 100644 --- a/src/core/textures/VideoBaseTexture.js +++ b/src/core/textures/VideoBaseTexture.js @@ -12,15 +12,18 @@ * @param source {HTMLVideoElement} * @param [scaleMode] {number} See {@link scaleModes} for possible values */ -function VideoBaseTexture(source, scaleMode) { - if (!source){ +function VideoBaseTexture(source, scaleMode) +{ + if (!source) + { throw new Error('No video source element specified.'); } // hook in here to check if video is already available. // BaseTexture looks for a source.complete boolean, plus width & height. - if ((source.readyState === source.HAVE_ENOUGH_DATA || source.readyState === source.HAVE_FUTURE_DATA) && source.width && source.height) { + if ((source.readyState === source.HAVE_ENOUGH_DATA || source.readyState === source.HAVE_FUTURE_DATA) && source.width && source.height) + { source.complete = true; } @@ -31,7 +34,8 @@ this._boundOnUpdate = this._onUpdate.bind(this); this._boundOnCanPlay = this._onCanPlay.bind(this); - if (!source.complete) { + if (!source.complete) + { source.addEventListener('canplay', this._boundOnCanPlay); source.addEventListener('canplaythrough', this._boundOnCanPlay); @@ -47,28 +51,35 @@ VideoBaseTexture.prototype.constructor = VideoBaseTexture; module.exports = VideoBaseTexture; -VideoBaseTexture.prototype._onUpdate = function () { - if (this.autoUpdate) { +VideoBaseTexture.prototype._onUpdate = function () +{ + if (this.autoUpdate) + { window.requestAnimationFrame(this._boundOnUpdate); this.needsUpdate = true; } }; -VideoBaseTexture.prototype._onPlayStart = function () { - if (!this.autoUpdate) { +VideoBaseTexture.prototype._onPlayStart = function () +{ + if (!this.autoUpdate) + { window.requestAnimationFrame(this._boundOnUpdate); this.autoUpdate = true; } }; -VideoBaseTexture.prototype._onPlayStop = function () { +VideoBaseTexture.prototype._onPlayStop = function () +{ this.autoUpdate = false; }; -VideoBaseTexture.prototype._onCanPlay = function () { +VideoBaseTexture.prototype._onCanPlay = function () +{ this.hasLoaded = true; - if (this.source) { + if (this.source) + { this.source.removeEventListener('canplay', this._boundOnCanPlay); this.source.removeEventListener('canplaythrough', this._boundOnCanPlay); @@ -78,15 +89,18 @@ this.source.play(); // prevent multiple loaded dispatches.. - if(!this.__loaded){ + if(!this.__loaded) + { this.__loaded = true; this.emit('loaded', this); } } }; -VideoBaseTexture.prototype.destroy = function () { - if (this.source && this.source._pixiId) { +VideoBaseTexture.prototype.destroy = function () +{ + if (this.source && this.source._pixiId) + { utils.BaseTextureCache[ this.source._pixiId ] = null; delete utils.BaseTextureCache[ this.source._pixiId ]; @@ -105,14 +119,17 @@ * @param scaleMode {number} See {@link scaleModes} for possible values * @return {VideoBaseTexture} */ -VideoBaseTexture.fromVideo = function (video, scaleMode) { - if (!video._pixiId) { +VideoBaseTexture.fromVideo = function (video, scaleMode) +{ + if (!video._pixiId) + { video._pixiId = 'video_' + utils.uuid(); } var baseTexture = utils.BaseTextureCache[video._pixiId]; - if (!baseTexture) { + if (!baseTexture) + { baseTexture = new VideoBaseTexture(video, scaleMode); utils.BaseTextureCache[ video._pixiId ] = baseTexture; } @@ -147,17 +164,21 @@ * @param scaleMode {number} See {@link scaleModes} for possible values * @return {VideoBaseTexture} */ -VideoBaseTexture.fromUrl = function (videoSrc, scaleMode) { +VideoBaseTexture.fromUrl = function (videoSrc, scaleMode) +{ var video = document.createElement('video'); // array of objects or strings - if (Array.isArray(videoSrc)) { - for (var i = 0; i < videoSrc.length; ++i) { + if (Array.isArray(videoSrc)) + { + for (var i = 0; i < videoSrc.length; ++i) + { video.appendChild(createSource(videoSrc.src || videoSrc, videoSrc.mime)); } } // single object or string - else { + else + { video.appendChild(createSource(videoSrc.src || videoSrc, videoSrc.mime)); } @@ -169,8 +190,10 @@ VideoBaseTexture.fromUrls = VideoBaseTexture.fromUrl; -function createSource(path, type) { - if (!type) { +function createSource(path, type) +{ + if (!type) + { type = 'video/' + path.substr(path.lastIndexOf('.') + 1); } diff --git a/src/core/utils/EventData.js b/src/core/utils/EventData.js index 5d55a22..8cdf701 100644 --- a/src/core/utils/EventData.js +++ b/src/core/utils/EventData.js @@ -7,7 +7,8 @@ * @param name {string} The string name of the event that was triggered * @param data {object} Arbitrary event data to pass along */ -function EventData(target, name, data) { +function EventData(target, name, data) +{ // for duck typing in the ".on()" function this.__isEventObject = true; @@ -71,7 +72,8 @@ * Stops the propagation of events up the scene graph (prevents bubbling). * */ -EventData.prototype.stopPropagation = function stopPropagation() { +EventData.prototype.stopPropagation = function stopPropagation() +{ this.stopped = true; }; @@ -79,6 +81,7 @@ * Stops the propagation of events to sibling listeners (no longer calls any listeners). * */ -EventData.prototype.stopImmediatePropagation = function stopImmediatePropagation() { +EventData.prototype.stopImmediatePropagation = function stopImmediatePropagation() +{ this.stoppedImmediate = true; }; diff --git a/src/core/utils/EventTarget.js b/src/core/utils/EventTarget.js index 7ae8820..671a151 100644 --- a/src/core/utils/EventTarget.js +++ b/src/core/utils/EventTarget.js @@ -13,14 +13,16 @@ * var em = new MyEmitter(); * em.emit('eventName', 'some data', 'some more data', {}, null, ...); */ -function eventTarget(obj) { +function eventTarget(obj) +{ /** * Return a list of assigned event listeners. * * @param eventName {string} The events that should be listed. * @return {Array} An array of listener functions */ - obj.listeners = function listeners(eventName) { + obj.listeners = function listeners(eventName) + { this._listeners = this._listeners || {}; return this._listeners[eventName] ? this._listeners[eventName].slice() : []; @@ -33,22 +35,26 @@ * @param eventName {string} The name of the event. * @return {boolean} Indication if we've emitted an event. */ - obj.emit = obj.dispatchEvent = function emit(eventName, data) { + obj.emit = obj.dispatchEvent = function emit(eventName, data) + { this._listeners = this._listeners || {}; // fast return when there are no listeners - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return; } //backwards compat with old method ".emit({ type: 'something' })" - if (typeof eventName === 'object') { + if (typeof eventName === 'object') + { data = eventName; eventName = eventName.type; } //ensure we are using a real pixi event - if (!data || data.__isEventObject !== true) { + if (!data || data.__isEventObject !== true) + { data = new EventData(this, eventName, data); } @@ -58,23 +64,27 @@ fn = listeners[0], i; - for (i = 0; i < length; fn = listeners[++i]) { + for (i = 0; i < length; fn = listeners[++i]) + { //call the event listener fn.call(this, data); //if "stopImmediatePropagation" is called, stop calling sibling events - if (data.stoppedImmediate) { + if (data.stoppedImmediate) + { return this; } } //if "stopPropagation" is called then don't bubble the event - if (data.stopped) { + if (data.stopped) + { return this; } //bubble this event up the scene graph - if (this.parent && this.parent.emit) { + if (this.parent && this.parent.emit) + { this.parent.emit.call(this.parent, eventName, data); } @@ -88,7 +98,8 @@ * @param eventName {string} Name of the event. * @param callback {Functon} fn Callback function. */ - obj.on = obj.addEventListener = function on(eventName, fn) { + obj.on = obj.addEventListener = function on(eventName, fn) + { this._listeners = this._listeners || {}; (this._listeners[eventName] = this._listeners[eventName] || []) @@ -103,11 +114,13 @@ * @param eventName {string} Name of the event. * @param callback {Function} Callback function. */ - obj.once = function once(eventName, fn) { + obj.once = function once(eventName, fn) + { this._listeners = this._listeners || {}; var self = this; - function onceHandlerWrapper() { + function onceHandlerWrapper() + { fn.apply(self.off(eventName, onceHandlerWrapper), arguments); } onceHandlerWrapper._originalHandler = fn; @@ -122,23 +135,28 @@ * @param eventName {string} The event we want to remove. * @param callback {Function} The listener that we need to find. */ - obj.off = obj.removeEventListener = function off(eventName, fn) { + obj.off = obj.removeEventListener = function off(eventName, fn) + { this._listeners = this._listeners || {}; - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return this; } var list = this._listeners[eventName], i = fn ? list.length : 0; - while(i-- > 0) { - if (list[i] === fn || list[i]._originalHandler === fn) { + while(i-- > 0) + { + if (list[i] === fn || list[i]._originalHandler === fn) + { list.splice(i, 1); } } - if (list.length === 0) { + if (list.length === 0) + { delete this._listeners[eventName]; } @@ -150,10 +168,12 @@ * * @param eventName {string} The event you want to remove all listeners for. */ - obj.removeAllListeners = function removeAllListeners(eventName) { + obj.removeAllListeners = function removeAllListeners(eventName) + { this._listeners = this._listeners || {}; - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return this; } @@ -169,7 +189,8 @@ * * @param object {object} The obj to mix into */ - mixin: function mixin(obj) { + mixin: function mixin(obj) + { eventTarget(obj); } }; diff --git a/src/core/utils/PolyK.js b/src/core/utils/PolyK.js index 7325141..5e20c2b 100644 --- a/src/core/utils/PolyK.js +++ b/src/core/utils/PolyK.js @@ -47,7 +47,8 @@ * Triangulates shapes for webGL graphic fills. * */ -PolyK.Triangulate = function (p) { +PolyK.Triangulate = function (p) +{ var sign = true; var n = p.length >> 1; @@ -59,7 +60,8 @@ i = 0; var al = n; - while(al > 3) { + while(al > 3) + { var i0 = avl[(i+0)%al]; var i1 = avl[(i+1)%al]; var i2 = avl[(i+2)%al]; @@ -69,29 +71,35 @@ var cx = p[2*i2], cy = p[2*i2+1]; var earFound = false; - if (PolyK._convex(ax, ay, bx, by, cx, cy, sign)) { + if (PolyK._convex(ax, ay, bx, by, cx, cy, sign)) + { earFound = true; - for (var j = 0; j < al; j++) { + for (var j = 0; j < al; j++) + { var vi = avl[j]; if (vi === i0 || vi === i1 || vi === i2) continue; - if (PolyK._PointInTriangle(p[2*vi], p[2*vi+1], ax, ay, bx, by, cx, cy)) { + if (PolyK._PointInTriangle(p[2*vi], p[2*vi+1], ax, ay, bx, by, cx, cy)) + { earFound = false; break; } } } - if (earFound) { + if (earFound) + { tgs.push(i0, i1, i2); avl.splice((i+1)%al, 1); al--; i = 0; } - else if (i++ > 3*al) { + else if (i++ > 3*al) + { // need to flip flip reverse it! // reset! - if (sign) { + if (sign) + { tgs = []; avl = []; for (i = 0; i < n; i++) avl.push(i); @@ -101,7 +109,8 @@ sign = false; } - else { + else + { // window.console.log("PIXI Warning: shape too complex to fill"); return null; } @@ -126,7 +135,8 @@ * @private * @return {boolean} */ -PolyK._PointInTriangle = function (px, py, ax, ay, bx, by, cx, cy) { +PolyK._PointInTriangle = function (px, py, ax, ay, bx, by, cx, cy) +{ var v0x = cx-ax; var v0y = cy-ay; var v1x = bx-ax; @@ -154,6 +164,7 @@ * @private * @return {boolean} */ -PolyK._convex = function (ax, ay, bx, by, cx, cy, sign) { +PolyK._convex = function (ax, ay, bx, by, cx, cy, sign) +{ return ((ay-by)*(cx-bx) + (bx-ax)*(cy-by) >= 0) === sign; }; diff --git a/src/core/utils/index.js b/src/core/utils/index.js index ade9831..bfae7ae 100644 --- a/src/core/utils/index.js +++ b/src/core/utils/index.js @@ -16,7 +16,8 @@ * * @return {number} The next uuid to use. */ - uuid: function () { + uuid: function () + { return ++utils._uid; }, @@ -26,7 +27,8 @@ * @param hex {number} * @return {number[]} An array representing the [R, G, B] of the color. */ - hex2rgb: function (hex, out) { + hex2rgb: function (hex, out) + { out = out || []; out[0] = (hex >> 16 & 0xFF) / 255; @@ -42,7 +44,8 @@ * @param hex {number} * @return {string} The string color. */ - hex2string: function (hex) { + hex2string: function (hex) + { hex = hex.toString(16); hex = '000000'.substr(0, 6 - hex.length) + hex; @@ -55,7 +58,8 @@ * @param rgb {number[]} * @return {number} The color number */ - rgb2hex: function (rgb) { + rgb2hex: function (rgb) + { return ((rgb[0]*255 << 16) + (rgb[1]*255 << 8) + rgb[2]*255); }, @@ -64,8 +68,10 @@ * * @return {boolean} whether they are supported */ - canUseNewCanvasBlendModes: function () { - if (typeof document === 'undefined') { + canUseNewCanvasBlendModes: function () + { + if (typeof document === 'undefined') + { return false; } @@ -93,15 +99,19 @@ * @param number {number} * @return {number} the closest number that is a power of two */ - getNextPowerOfTwo: function (number) { + getNextPowerOfTwo: function (number) + { // see: http://en.wikipedia.org/wiki/Power_of_two#Fast_algorithm_to_check_if_a_positive_number_is_a_power_of_two - if (number > 0 && (number & (number - 1)) === 0) { + if (number > 0 && (number & (number - 1)) === 0) + { return number; } - else { + else + { var result = 1; - while (result < number) { + while (result < number) + { result <<= 1; } @@ -116,7 +126,8 @@ * @param height {number} * @return {boolean} */ - isPowerOfTwo: function (width, height) { + isPowerOfTwo: function (width, height) + { return (width > 0 && (width & (width - 1)) === 0 && height > 0 && (height & (height - 1)) === 0); }, @@ -130,12 +141,15 @@ * @constant * @static */ - sayHello: function (type) { - if (utils._saidHello) { + sayHello: function (type) + { + if (utils._saidHello) + { return; } - if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) { + if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) + { var args = [ '%c %c %c Pixi.js ' + CONST.VERSION + ' - ' + type + ' %c ' + ' %c ' + ' http://www.pixijs.com/ %c %c ♥%c♥%c♥ ', 'background: #ff66a5', @@ -151,7 +165,8 @@ console.log.apply(console, args); //jshint ignore:line } - else if (window.console) { + else if (window.console) + { console.log('Pixi.js ' + CONST.VERSION + ' - ' + type + ' - http://www.pixijs.com/'); //jshint ignore:line } @@ -166,15 +181,19 @@ * @class * @namespace PIXI */ - AjaxRequest: function () { + AjaxRequest: function () + { var activexmodes = ['Msxml2.XMLHTTP.6.0', 'Msxml2.XMLHTTP.3.0', 'Microsoft.XMLHTTP']; //activeX versions to check for in IE - if (window.ActiveXObject) { //Test for support for ActiveXObject in IE first (as XMLHttpRequest in IE7 is broken) - for (var i=0; i= this.textures.length) { + else if (round >= this.textures.length) + { this.gotoAndStop(this.textures.length - 1); - if (this.onComplete) { + if (this.onComplete) + { this.onComplete(); } } @@ -167,10 +182,12 @@ * @static * @param frames {string[]} the array of frames ids the movieclip will use as its texture frames */ -MovieClip.fromFrames = function (frames) { +MovieClip.fromFrames = function (frames) +{ var textures = []; - for (var i = 0; i < frames.length; ++i) { + for (var i = 0; i < frames.length; ++i) + { textures.push(new core.Texture.fromFrame(frames[i])); } @@ -183,10 +200,12 @@ * @static * @param images {string[]} the array of image urls the movieclip will use as its texture frames */ -MovieClip.fromImages = function (images) { +MovieClip.fromImages = function (images) +{ var textures = []; - for (var i = 0; i < images.length; ++i) { + for (var i = 0; i < images.length; ++i) + { textures.push(new core.Texture.fromImage(images[i])); } diff --git a/src/extras/Rope.js b/src/extras/Rope.js index c157ec4..9c87bc0 100644 --- a/src/extras/Rope.js +++ b/src/extras/Rope.js @@ -9,7 +9,8 @@ * @param {Array} points - An array of {Point}. * */ -function Rope(texture, points) { +function Rope(texture, points) +{ Strip.call(this, texture); this.points = points; @@ -31,10 +32,12 @@ * Refreshes * */ -Rope.prototype.refresh = function () { +Rope.prototype.refresh = function () +{ var points = this.points; - if (points.length < 1) { + if (points.length < 1) + { return; } @@ -59,20 +62,23 @@ var total = points.length, point, index, amount; - for (var i = 1; i < total; i++) { + for (var i = 1; i < total; i++) + { point = points[i]; index = i * 4; // time to do some smart drawing! amount = i / (total-1); - if (i%2) { + if (i%2) + { uvs[index] = amount; uvs[index+1] = 0; uvs[index+2] = amount; uvs[index+3] = 1; } - else { + else + { uvs[index] = amount; uvs[index+1] = 0; @@ -95,10 +101,12 @@ * * @private */ -Rope.prototype.updateTransform = function () { +Rope.prototype.updateTransform = function () +{ var points = this.points; - if (points.length < 1) { + if (points.length < 1) + { return; } @@ -113,14 +121,17 @@ var total = points.length, point, index, ratio, perpLength, num; - for (var i = 0; i < total; i++) { + for (var i = 0; i < total; i++) + { point = points[i]; index = i * 4; - if (i < points.length-1) { + if (i < points.length-1) + { nextPoint = points[i+1]; } - else { + else + { nextPoint = point; } @@ -129,7 +140,8 @@ ratio = (1 - (i / (total-1))) * 10; - if (ratio > 1) { + if (ratio > 1) + { ratio = 1; } @@ -157,7 +169,8 @@ * * @param texture {Texture} the texture that will be used */ -Rope.prototype.setTexture = function (texture) { +Rope.prototype.setTexture = function (texture) +{ // stop current texture this.texture = texture; //this.updateFrame = true; diff --git a/src/extras/Strip.js b/src/extras/Strip.js index c5e378f..57691b5 100644 --- a/src/extras/Strip.js +++ b/src/extras/Strip.js @@ -10,7 +10,8 @@ * @param height {number} the height * */ -function Strip(texture) { +function Strip(texture) +{ core.DisplayObjectContainer.call(this); /** @@ -70,9 +71,11 @@ * * @param renderer {WebGLRenderer} */ -Strip.prototype.renderWebGL = function (renderer) { +Strip.prototype.renderWebGL = function (renderer) +{ // if the sprite is not visible or the alpha is 0 then no need to render this element - if (!this.visible || this.alpha <= 0) { + if (!this.visible || this.alpha <= 0) + { return; } @@ -81,7 +84,8 @@ renderer.spriteBatch.stop(); // init! init! - if (!this._vertexBuffer) { + if (!this._vertexBuffer) + { this._initWebGL(renderer); } @@ -96,7 +100,8 @@ //TODO check culling }; -Strip.prototype._initWebGL = function (renderer) { +Strip.prototype._initWebGL = function (renderer) +{ // build the strip! var gl = renderer.gl; @@ -118,7 +123,8 @@ gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this.indices, gl.STATIC_DRAW); }; -Strip.prototype._renderStrip = function (renderer) { +Strip.prototype._renderStrip = function (renderer) +{ var gl = renderer.gl; var projection = renderer.projection, offset = renderer.offset, @@ -137,7 +143,8 @@ gl.uniform2f(shader.offsetVector, -offset.x, -offset.y); gl.uniform1f(shader.alpha, this.worldAlpha); - if (!this.dirty) { + if (!this.dirty) + { gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexBuffer); gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); @@ -150,10 +157,12 @@ gl.activeTexture(gl.TEXTURE0); // check if a texture is dirty.. - if (this.texture.baseTexture._dirty[gl.id]) { + if (this.texture.baseTexture._dirty[gl.id]) + { renderer.updateTexture(this.texture.baseTexture); } - else { + else + { // bind the current texture gl.bindTexture(gl.TEXTURE_2D, this.texture.baseTexture._glTextures[gl.id]); } @@ -163,7 +172,8 @@ } - else { + else + { this.dirty = false; gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexBuffer); @@ -178,10 +188,12 @@ gl.activeTexture(gl.TEXTURE0); // check if a texture is dirty.. - if (this.texture.baseTexture._dirty[gl.id]) { + if (this.texture.baseTexture._dirty[gl.id]) + { renderer.updateTexture(this.texture.baseTexture); } - else { + else + { gl.bindTexture(gl.TEXTURE_2D, this.texture.baseTexture._glTextures[gl.id]); } @@ -203,27 +215,33 @@ * * @param renderer {CanvasRenderer} */ -Strip.prototype.renderCanvas = function (renderer) { +Strip.prototype.renderCanvas = function (renderer) +{ var context = renderer.context; var transform = this.worldTransform; - if (renderer.roundPixels) { + if (renderer.roundPixels) + { context.setTransform(transform.a, transform.b, transform.c, transform.d, transform.tx | 0, transform.ty | 0); } - else { + else + { context.setTransform(transform.a, transform.b, transform.c, transform.d, transform.tx, transform.ty); } - if (this.drawMode === Strip.DrawModes.TRIANGLE_STRIP) { + if (this.drawMode === Strip.DrawModes.TRIANGLE_STRIP) + { this._renderCanvasTriangleStrip(context); } - else { + else + { this._renderCanvasTriangles(context); } }; -Strip.prototype._renderCanvasTriangleStrip = function (context) { +Strip.prototype._renderCanvasTriangleStrip = function (context) +{ // draw triangles!! var vertices = this.vertices; var uvs = this.uvs; @@ -231,14 +249,16 @@ var length = vertices.length / 2; // this.count++; - for (var i = 0; i < length - 2; i++) { + for (var i = 0; i < length - 2; i++) + { // draw some triangles! var index = i * 2; this._renderCanvasDrawTriangle(context, vertices, uvs, index, (index + 2), (index + 4)); } }; -Strip.prototype._renderCanvasTriangles = function (context) { +Strip.prototype._renderCanvasTriangles = function (context) +{ // draw triangles!! var vertices = this.vertices; var uvs = this.uvs; @@ -247,14 +267,16 @@ var length = indices.length; // this.count++; - for (var i = 0; i < length; i += 3) { + for (var i = 0; i < length; i += 3) + { // draw some triangles! var index0 = indices[i] * 2, index1 = indices[i + 1] * 2, index2 = indices[i + 2] * 2; this._renderCanvasDrawTriangle(context, vertices, uvs, index0, index1, index2); } }; -Strip.prototype._renderCanvasDrawTriangle = function (context, vertices, uvs, index0, index1, index2) { +Strip.prototype._renderCanvasDrawTriangle = function (context, vertices, uvs, index0, index1, index2) +{ var textureSource = this.texture.baseTexture.source; var textureWidth = this.texture.width; var textureHeight = this.texture.height; @@ -265,7 +287,8 @@ var u0 = uvs[index0] * textureWidth, u1 = uvs[index1] * textureWidth, u2 = uvs[index2] * textureWidth; var v0 = uvs[index0 + 1] * textureHeight, v1 = uvs[index1 + 1] * textureHeight, v2 = uvs[index2 + 1] * textureHeight; - if (this.canvasPadding > 0) { + if (this.canvasPadding > 0) + { var paddingX = this.canvasPadding / this.worldTransform.a; var paddingY = this.canvasPadding / this.worldTransform.d; var centerX = (x0 + x1 + x2) / 3; @@ -332,7 +355,8 @@ * @param strip {Strip} The Strip to render * @private */ -Strip.prototype.renderStripFlat = function (strip) { +Strip.prototype.renderStripFlat = function (strip) +{ var context = this.context; var vertices = strip.vertices; @@ -340,7 +364,8 @@ // this.count++; context.beginPath(); - for (var i=1; i < length-2; i++) { + for (var i=1; i < length-2; i++) + { // draw some triangles! var index = i*2; @@ -358,7 +383,8 @@ }; /* -Strip.prototype.setTexture = function (texture) { +Strip.prototype.setTexture = function (texture) +{ //TODO SET THE TEXTURES //TODO VISIBILITY @@ -377,7 +403,8 @@ * @private */ -Strip.prototype.onTextureUpdate = function () { +Strip.prototype.onTextureUpdate = function () +{ this.updateFrame = true; }; @@ -387,7 +414,8 @@ * @param matrix {Matrix} the transformation matrix of the sprite * @return {Rectangle} the framing rectangle */ -Strip.prototype.getBounds = function (matrix) { +Strip.prototype.getBounds = function (matrix) +{ var worldTransform = matrix || this.worldTransform; var a = worldTransform.a; @@ -404,7 +432,8 @@ var minY = Infinity; var vertices = this.vertices; - for (var i = 0, n = vertices.length; i < n; i += 2) { + for (var i = 0, n = vertices.length; i < n; i += 2) + { var rawX = vertices[i], rawY = vertices[i + 1]; var x = (a * rawX) + (c * rawY) + tx; var y = (d * rawY) + (b * rawX) + ty; @@ -416,7 +445,8 @@ maxY = y > maxY ? y : maxY; } - if (minX === -Infinity || maxY === Infinity) { + if (minX === -Infinity || maxY === Infinity) + { return core.math.Rectangle.EMPTY; } diff --git a/src/extras/TilingSprite.js b/src/extras/TilingSprite.js index 3ac22df..31da393 100644 --- a/src/extras/TilingSprite.js +++ b/src/extras/TilingSprite.js @@ -10,7 +10,8 @@ * @param width {number} the width of the tiling sprite * @param height {number} the height of the tiling sprite */ -function TilingSprite(texture, width, height) { +function TilingSprite(texture, width, height) +{ core.Sprite.call( this, texture); /** @@ -86,10 +87,12 @@ * @memberof TilingSprite# */ width: { - get: function () { + get: function () + { return this._width; }, - set: function (value) { + set: function (value) + { this._width = value; } }, @@ -101,20 +104,25 @@ * @memberof TilingSprite# */ height: { - get: function () { + get: function () + { return this._height; }, - set: function (value) { + set: function (value) + { this._height = value; } }, texture: { - get: function () { + get: function () + { return this._texture; }, - set: function (value) { - if (this._texture === value) { + set: function (value) + { + if (this._texture === value) + { return; } @@ -130,51 +138,61 @@ * * @param renderer {WebGLRenderer} */ -TilingSprite.prototype.renderWebGL = function (renderer) { - if (!this.visible || this.alpha <= 0) { +TilingSprite.prototype.renderWebGL = function (renderer) +{ + if (!this.visible || this.alpha <= 0) + { return; } var i, j; - if (this._mask) { + if (this._mask) + { renderer.spriteBatch.stop(); renderer.maskManager.pushMask(this.mask, renderer); renderer.spriteBatch.start(); } - if (this._filters) { + if (this._filters) + { renderer.spriteBatch.flush(); renderer.filterManager.pushFilter(this._filterBlock); } - if (!this.tilingTexture || this.refreshTexture) { + if (!this.tilingTexture || this.refreshTexture) + { this.generateTilingTexture(true); - if (this.tilingTexture && this.tilingTexture.needsUpdate) { + if (this.tilingTexture && this.tilingTexture.needsUpdate) + { //TODO - tweaking renderer.updateTexture(this.tilingTexture.baseTexture); this.tilingTexture.needsUpdate = false; // this.tilingTexture._uvs = null; } } - else { + else + { renderer.spriteBatch.renderTilingSprite(this); } // simple render children! - for (i=0,j=this.children.length; i= 0 && index <= this.children.length) { - if (child.parent) { + if (index >= 0 && index <= this.children.length) + { + if (child.parent) + { child.parent.removeChild(child); } @@ -154,7 +173,8 @@ return child; } - else { + else + { throw new Error(child + 'addChildAt: The index '+ index +' supplied is out of bounds ' + this.children.length); } }; @@ -165,15 +185,18 @@ * @param child {DisplayObject} * @param child2 {DisplayObject} */ -DisplayObjectContainer.prototype.swapChildren = function (child, child2) { - if (child === child2) { +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) { + if (index1 < 0 || index2 < 0) + { throw new Error('swapChildren: Both the supplied DisplayObjects must be a child of the caller.'); } @@ -187,10 +210,12 @@ * @param child {DisplayObject} The DisplayObject instance to identify * @return {Number} The index position of the child display object to identify */ -DisplayObjectContainer.prototype.getChildIndex = function (child) { +DisplayObjectContainer.prototype.getChildIndex = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { throw new Error('The supplied DisplayObject must be a child of the caller'); } @@ -203,8 +228,10 @@ * @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 */ -DisplayObjectContainer.prototype.setChildIndex = function (child, index) { - if (index < 0 || index >= this.children.length) { +DisplayObjectContainer.prototype.setChildIndex = function (child, index) +{ + if (index < 0 || index >= this.children.length) + { throw new Error('The supplied index is out of bounds'); } @@ -220,8 +247,10 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child at the given index, if any. */ -DisplayObjectContainer.prototype.getChildAt = function (index) { - if (index < 0 || index >= this.children.length) { +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'); } @@ -234,10 +263,12 @@ * @param child {DisplayObject} The DisplayObject to remove * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChild = function (child) { +DisplayObjectContainer.prototype.removeChild = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { return; } @@ -250,7 +281,8 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChildAt = function (index) { +DisplayObjectContainer.prototype.removeChildAt = function (index) +{ var child = this.getChildAt(index); child.parent = null; @@ -265,24 +297,29 @@ * @param beginIndex {Number} The beginning position. Default value is 0. * @param endIndex {Number} The ending position. Default value is size of the container. */ -DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) { +DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) +{ var begin = beginIndex || 0; var end = typeof endIndex === 'number' ? endIndex : this.children.length; var range = end - begin; - if (range > 0 && range <= end) { + if (range > 0 && range <= end) + { var removed = this.children.splice(begin, range); - for (var i = 0; i < removed.length; ++i) { + for (var i = 0; i < removed.length; ++i) + { removed[i].parent = null; } return removed; } - else if (range === 0 && this.children.length === 0) { + else if (range === 0 && this.children.length === 0) + { return []; } - else { + else + { throw new RangeError('removeChildren: numeric values are outside the acceptable range.'); } }; @@ -291,7 +328,8 @@ * Generates and updates the cached sprite for this object. * */ -DisplayObjectContainer.prototype.updateCachedSprite = function () { +DisplayObjectContainer.prototype.updateCachedSprite = function () +{ this._generateCachedSprite(); }; @@ -304,7 +342,8 @@ * @param renderer {CanvasRenderer|WebGLRenderer} The renderer used to generate the texture. * @return {Texture} a texture of the graphics object */ -DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) { +DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) +{ var bounds = this.getLocalBounds(); var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0, renderer, scaleMode, resolution); @@ -322,18 +361,22 @@ * * @private */ -DisplayObjectContainer.prototype.updateTransform = function () { - if (!this.visible) { +DisplayObjectContainer.prototype.updateTransform = function () +{ + if (!this.visible) + { return; } this.displayObjectUpdateTransform(); - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { return; } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } }; @@ -346,8 +389,10 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getBounds = function () { - if (this.children.length === 0) { +DisplayObjectContainer.prototype.getBounds = function () +{ + if (this.children.length === 0) + { return math.Rectangle.EMPTY; } @@ -365,10 +410,12 @@ var childVisible = false; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -386,7 +433,8 @@ maxY = maxY > childMaxY ? maxY : childMaxY; } - if (!childVisible) { + if (!childVisible) + { return math.Rectangle.EMPTY; } @@ -407,12 +455,14 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getLocalBounds = function () { +DisplayObjectContainer.prototype.getLocalBounds = function () +{ var matrixCache = this.worldTransform; this.worldTransform = math.Matrix.IDENTITY; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } @@ -428,13 +478,16 @@ * * @param renderer {WebGLRenderer} The renderer */ -DisplayObjectContainer.prototype.renderWebGL = function (renderer) { +DisplayObjectContainer.prototype.renderWebGL = function (renderer) +{ // if the object is not visible or the alpha is 0 then no need to render this element - if (!this.visible || this.alpha <= 0) { + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } @@ -442,14 +495,17 @@ var i, j; // do a quick check to see if this element has a mask or a filter. - if (this._mask || this._filters) { + if (this._mask || this._filters) + { // push filter first as we need to ensure the stencil buffer is correct for any masking - if (this._filters) { + if (this._filters) + { renderer.spriteBatch.flush(); renderer.filterManager.pushFilter(this._filterBlock); } - if (this._mask) { + if (this._mask) + { renderer.spriteBatch.stop(); renderer.maskManager.pushMask(this.mask, renderer); renderer.spriteBatch.start(); @@ -459,36 +515,42 @@ this._renderWebGL(renderer); // now loop through the children and make sure they get rendered - for (i = 0, j = this.children.length; i < j; i++) { + for (i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderWebGL(renderer); } // time to stop the sprite batch as either a mask element or a filter draw will happen next renderer.spriteBatch.stop(); - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(this._mask, renderer); } - if (this._filters) { + if (this._filters) + { renderer.filterManager.popFilter(); } renderer.spriteBatch.start(); } - else { + else + { this._renderWebGL(renderer); // simple render children! - for (i = 0, j = this.children.length; i < j; ++i) { + for (i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderWebGL(renderer); } } }; -DisplayObjectContainer.prototype._renderWebGL = function (renderer) { +DisplayObjectContainer.prototype._renderWebGL = function (renderer) +{ // this is where content itself gets renderd.. @@ -499,25 +561,31 @@ * * @param renderer {CanvasRenderer} The renderer */ -DisplayObjectContainer.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0) { +DisplayObjectContainer.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -528,13 +596,16 @@ * @param renderer {WebGLRenderer|CanvasRenderer} The renderer * @private */ -DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) { +DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) +{ this._cachedSprite.worldAlpha = this.worldAlpha; - if (renderer.gl) { + if (renderer.gl) + { this._cachedSprite.renderWebGL(renderer); } - else { + else + { this._cachedSprite.renderCanvas(renderer); } }; @@ -544,10 +615,12 @@ * * @private */ -DisplayObjectContainer.prototype._generateCachedSprite = function () { +DisplayObjectContainer.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { // TODO - RenderTexture now *requires* a renderer instance, so this is like broken // because `renderer` isn't actually in scope here :P var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0); @@ -555,7 +628,8 @@ this._cachedSprite = new Sprite(renderTexture); this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.texture.resize(bounds.width | 0, bounds.height | 0); } @@ -580,8 +654,10 @@ * * @private */ -DisplayObjectContainer.prototype._destroyCachedSprite = function () { - if (!this._cachedSprite) { +DisplayObjectContainer.prototype._destroyCachedSprite = function () +{ + if (!this._cachedSprite) + { return; } diff --git a/src/core/display/Sprite.js b/src/core/display/Sprite.js index 707da24..5862aef 100644 --- a/src/core/display/Sprite.js +++ b/src/core/display/Sprite.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param texture {Texture} The texture for this sprite */ -function Sprite(texture) { +function Sprite(texture) +{ DisplayObjectContainer.call(this); /** @@ -85,12 +86,14 @@ this.texture = texture || Texture.EMPTY; } -Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) { +Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) +{ DisplayObjectContainer.prototype.destroy.call(this); this.anchor = null; - if (destroyTexture) { + if (destroyTexture) + { this._texture.destroy(destroyBaseTexture); } @@ -111,10 +114,12 @@ * @memberof Sprite# */ width: { - get: function () { + get: function () + { return this.scale.x * this.texture.frame.width; }, - set: function (value) { + set: function (value) + { this.scale.x = value / this.texture.frame.width; this._width = value; } @@ -127,10 +132,12 @@ * @memberof Sprite# */ height: { - get: function () { + get: function () + { return this.scale.y * this.texture.frame.height; }, - set: function (value) { + set: function (value) + { this.scale.y = value / this.texture.frame.height; this._height = value; } @@ -143,23 +150,29 @@ * @memberof Sprite# */ texture: { - get: function () { + get: function () + { return this._texture; }, - set: function (value) { - if (this._texture === value) { + set: function (value) + { + if (this._texture === value) + { return; } this._texture = value; this.cachedTint = 0xFFFFFF; - if (value) { + if (value) + { // wait for the texture to load - if (value.baseTexture.hasLoaded) { + if (value.baseTexture.hasLoaded) + { this._onTextureUpdate(); } - else { + else + { value.once('update', this._onTextureUpdate.bind(this)); } } @@ -172,18 +185,22 @@ * * @private */ -Sprite.prototype._onTextureUpdate = function () { +Sprite.prototype._onTextureUpdate = function () +{ // so if _width is 0 then width was not set.. - if (this._width) { + if (this._width) + { this.scale.x = this._width / this.texture.frame.width; } - if (this._height) { + if (this._height) + { this.scale.y = this._height / this.texture.frame.height; } }; -Sprite.prototype._renderWebGL = function (renderer) { +Sprite.prototype._renderWebGL = function (renderer) +{ // this is where content gets renderd.. // watch this space for a little render state manager.. @@ -197,7 +214,8 @@ * @param matrix {Matrix} the transformation matrix of the sprite * @return {Rectangle} the framing rectangle */ -Sprite.prototype.getBounds = function (matrix) { +Sprite.prototype.getBounds = function (matrix) +{ var width = this.texture.frame.width; var height = this.texture.frame.height; @@ -224,11 +242,13 @@ if(b === 0 && c === 0) { // scale may be negative! - if (a < 0) { + if (a < 0) + { a *= -1; } - if (d < 0) { + if (d < 0) + { d *= -1; } @@ -293,28 +313,34 @@ * * @param renderer {CanvasRenderer} The renderer */ -Sprite.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) { +Sprite.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) + { return; } - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; renderer.context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } // Ignore null sources - if (this.texture.valid) { + if (this.texture.valid) + { var resolution = this.texture.baseTexture.resolution / renderer.resolution; renderer.context.globalAlpha = this.worldAlpha; // If smoothingEnabled is supported and we need to change the smoothing property for this texture - if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) { + if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) + { renderer.scaleMode = this.texture.baseTexture.scaleMode; renderer.context[renderer.smoothProperty] = (renderer.scaleMode === CONST.scaleModes.LINEAR); } @@ -324,7 +350,8 @@ var dy = (this.texture.trim ? this.texture.trim.y : 0) - (this.anchor.y * this.texture.trim.height); // Allow for pixel rounding - if (renderer.roundPixels) { + if (renderer.roundPixels) + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -337,7 +364,8 @@ dx = dx | 0; dy = dy | 0; } - else { + else + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -348,8 +376,10 @@ ); } - if (this.tint !== 0xFFFFFF) { - if (this.cachedTint !== this.tint) { + if (this.tint !== 0xFFFFFF) + { + if (this.cachedTint !== this.tint) + { this.cachedTint = this.tint; // TODO clean up caching - how to clean up the caches? @@ -368,7 +398,8 @@ this.texture.crop.height / resolution ); } - else { + else + { renderer.context.drawImage( this.texture.baseTexture.source, this.texture.crop.x, @@ -383,11 +414,13 @@ } } - for (var i = 0, j = this.children.length; i < j; i++) { + for (var i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -402,10 +435,12 @@ * @param frameId {String} The frame Id of the texture in the cache * @return {Sprite} A new Sprite using a texture from the texture cache matching the frameId */ -Sprite.fromFrame = function (frameId) { +Sprite.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache' + this); } @@ -420,6 +455,7 @@ * @param imageId {String} The image url of the texture * @return {Sprite} A new Sprite using a texture from the texture cache matching the image id */ -Sprite.fromImage = function (imageId, crossorigin, scaleMode) { +Sprite.fromImage = function (imageId, crossorigin, scaleMode) +{ return new Sprite(Texture.fromImage(imageId, crossorigin, scaleMode)); }; diff --git a/src/core/display/SpriteBatch.js b/src/core/display/SpriteBatch.js index 3187777..c196fef 100644 --- a/src/core/display/SpriteBatch.js +++ b/src/core/display/SpriteBatch.js @@ -12,7 +12,8 @@ * ```js * var container = new SpriteBatch(); * - * for(var i = 0; i < 100; ++i) { + * for(var i = 0; i < 100; ++i) + * { * var sprite = new PIXI.Sprite.fromImage("myImage.png"); * container.addChild(sprite); * } @@ -25,7 +26,8 @@ */ //TODO RENAME to PARTICLE CONTAINER? -function SpriteBatch() { +function SpriteBatch() +{ DisplayObjectContainer.call(this); } @@ -38,7 +40,8 @@ * * @private */ -SpriteBatch.prototype.updateTransform = function () { +SpriteBatch.prototype.updateTransform = function () +{ // TODO don't need to! this.displayObjectUpdateTransform(); // PIXI.DisplayObjectContainer.prototype.updateTransform.call( this ); @@ -50,8 +53,10 @@ * @param renderer {WebGLRenderer} The webgl renderer * @private */ -SpriteBatch.prototype.renderWebGL = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderWebGL = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -71,8 +76,10 @@ * @param renderer {CanvasRenderer} The canvas renderer * @private */ -SpriteBatch.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -84,10 +91,12 @@ this.displayObjectUpdateTransform(); - for (var i = 0; i < this.children.length; ++i) { + for (var i = 0; i < this.children.length; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -95,9 +104,11 @@ context.globalAlpha = this.worldAlpha * child.alpha; - if (child.rotation % (Math.PI * 2) === 0) { + if (child.rotation % (Math.PI * 2) === 0) + { // this is the fastest way to optimise! - if rotation is 0 then we can avoid any kind of setTransform call - if (isRotated) { + if (isRotated) + { context.setTransform( transform.a, transform.b, @@ -122,8 +133,10 @@ frame.height * child.scale.y ); } - else { - if (!isRotated) { + else + { + if (!isRotated) + { isRotated = true; } @@ -131,7 +144,8 @@ var childTransform = child.worldTransform; - if (renderer.roundPixels) { + if (renderer.roundPixels) + { context.setTransform( childTransform.a, childTransform.b, @@ -141,7 +155,8 @@ childTransform.ty | 0 ); } - else { + else + { context.setTransform( childTransform.a, childTransform.b, diff --git a/src/core/index.js b/src/core/index.js index 3954b6f..eb4a82b 100644 --- a/src/core/index.js +++ b/src/core/index.js @@ -58,11 +58,13 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRenderer: function (width, height, options, noWebGL) { + autoDetectRenderer: function (width, height, options, noWebGL) + { width = width || 800; height = height || 600; - if (!noWebGL && require('webgl-enabled')()) { + if (!noWebGL && require('webgl-enabled')()) + { return new core.WebGLRenderer(width, height, options); } @@ -87,7 +89,8 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRecommendedRenderer: function (width, height, options) { + autoDetectRecommendedRenderer: function (width, height, options) + { var isAndroid = /Android/i.test(navigator.userAgent); return core.autoDetectRenderer(width, height, options, isAndroid); diff --git a/src/core/math/Matrix.js b/src/core/math/Matrix.js index c2f87e2..2ff4848 100644 --- a/src/core/math/Matrix.js +++ b/src/core/math/Matrix.js @@ -10,7 +10,8 @@ * @class * @namespace PIXI */ -function Matrix() { +function Matrix() +{ /** * @member {number} * @default 1 @@ -63,7 +64,8 @@ * * @param array {number[]} The array that the matrix will be populated from. */ -Matrix.prototype.fromArray = function (array) { +Matrix.prototype.fromArray = function (array) +{ this.a = array[0]; this.b = array[1]; this.c = array[3]; @@ -78,14 +80,17 @@ * @param transpose {boolean} Whether we need to transpose the matrix or not * @return {number[]} the newly created array which contains the matrix */ -Matrix.prototype.toArray = function (transpose) { - if (!this.array) { +Matrix.prototype.toArray = function (transpose) +{ + if (!this.array) + { this.array = new Float32Array(9); } var array = this.array; - if (transpose) { + if (transpose) + { array[0] = this.a; array[1] = this.b; array[2] = 0; @@ -96,7 +101,8 @@ array[7] = this.ty; array[8] = 1; } - else { + else + { array[0] = this.a; array[1] = this.c; array[2] = this.tx; @@ -119,7 +125,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, transformed through this matrix */ -Matrix.prototype.apply = function (pos, newPos) { +Matrix.prototype.apply = function (pos, newPos) +{ newPos = newPos || new Point(); newPos.x = this.a * pos.x + this.c * pos.y + this.tx; @@ -136,7 +143,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, inverse-transformed through this matrix */ -Matrix.prototype.applyInverse = function (pos, newPos) { +Matrix.prototype.applyInverse = function (pos, newPos) +{ newPos = newPos || new Point(); var id = 1 / (this.a * this.d + this.c * -this.b); @@ -154,7 +162,8 @@ * @param {number} y * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.translate = function (x, y) { +Matrix.prototype.translate = function (x, y) +{ this.tx += x; this.ty += y; @@ -168,7 +177,8 @@ * @param {number} y The amount to scale vertically * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.scale = function (x, y) { +Matrix.prototype.scale = function (x, y) +{ this.a *= x; this.d *= y; this.c *= x; @@ -186,7 +196,8 @@ * @param {number} angle - The angle in radians. * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.rotate = function (angle) { +Matrix.prototype.rotate = function (angle) +{ var cos = Math.cos( angle ); var sin = Math.sin( angle ); @@ -210,7 +221,8 @@ * @param {Matrix} matrix * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.append = function (matrix) { +Matrix.prototype.append = function (matrix) +{ var a1 = this.a; var b1 = this.b; var c1 = this.c; @@ -232,7 +244,8 @@ * * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.identity = function () { +Matrix.prototype.identity = function () +{ this.a = 1; this.b = 0; this.c = 0; diff --git a/src/core/math/Point.js b/src/core/math/Point.js index 7565b2d..632f346 100644 --- a/src/core/math/Point.js +++ b/src/core/math/Point.js @@ -7,7 +7,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -function Point(x, y) { +function Point(x, y) +{ /** * @member {number} * @default 0 @@ -29,7 +30,8 @@ * * @return {Point} a copy of the point */ -Point.prototype.clone = function () { +Point.prototype.clone = function () +{ return new Point(this.x, this.y); }; @@ -40,7 +42,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -Point.prototype.set = function (x, y) { +Point.prototype.set = function (x, y) +{ this.x = x || 0; this.y = y || ( (y !== 0) ? this.x : 0 ) ; }; diff --git a/src/core/math/shapes/Circle.js b/src/core/math/shapes/Circle.js index 69cfdc9..4d76efc 100644 --- a/src/core/math/shapes/Circle.js +++ b/src/core/math/shapes/Circle.js @@ -10,7 +10,8 @@ * @param y {number} The Y coordinate of the center of this circle * @param radius {number} The radius of the circle */ -function Circle(x, y, radius) { +function Circle(x, y, radius) +{ /** * @member {number} * @default 0 @@ -46,7 +47,8 @@ * @method clone * @return {Circle} a copy of the Circle */ -Circle.prototype.clone = function () { +Circle.prototype.clone = function () +{ return new Circle(this.x, this.y, this.radius); }; @@ -58,8 +60,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Circle */ -Circle.prototype.contains = function (x, y) { - if (this.radius <= 0) { +Circle.prototype.contains = function (x, y) +{ + if (this.radius <= 0) + { return false; } @@ -79,6 +83,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Circle.prototype.getBounds = function () { +Circle.prototype.getBounds = function () +{ return new Rectangle(this.x - this.radius, this.y - this.radius, this.radius * 2, this.radius * 2); }; diff --git a/src/core/math/shapes/Ellipse.js b/src/core/math/shapes/Ellipse.js index 4f2d066..fefd01a 100644 --- a/src/core/math/shapes/Ellipse.js +++ b/src/core/math/shapes/Ellipse.js @@ -11,7 +11,8 @@ * @param width {number} The half width of this ellipse * @param height {number} The half height of this ellipse */ -function Ellipse(x, y, width, height) { +function Ellipse(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -53,7 +54,8 @@ * @method clone * @return {Ellipse} a copy of the ellipse */ -Ellipse.prototype.clone = function () { +Ellipse.prototype.clone = function () +{ return new Ellipse(this.x, this.y, this.width, this.height); }; @@ -65,8 +67,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coords are within this ellipse */ -Ellipse.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Ellipse.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } @@ -86,6 +90,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Ellipse.prototype.getBounds = function () { +Ellipse.prototype.getBounds = function () +{ return new Rectangle(this.x - this.width, this.y - this.height, this.width, this.height); }; diff --git a/src/core/math/shapes/Polygon.js b/src/core/math/shapes/Polygon.js index ae89148..fea6d37 100644 --- a/src/core/math/shapes/Polygon.js +++ b/src/core/math/shapes/Polygon.js @@ -10,16 +10,20 @@ * arguments passed can be flat x,y values e.g. `new Polygon(x,y, x,y, x,y, ...)` where `x` and `y` are * Numbers. */ -function Polygon(points) { +function Polygon(points) +{ //if points isn't an array, use arguments as the array - if (!(points instanceof Array)) { + if (!(points instanceof Array)) + { points = Array.prototype.slice.call(arguments); } //if this is a flat array of numbers, convert it to points - if (points[0] instanceof Point) { + if (points[0] instanceof Point) + { var p = []; - for (var i = 0, il = points.length; i < il; i++) { + for (var i = 0, il = points.length; i < il; i++) + { p.push(points[i].x, points[i].y); } @@ -51,7 +55,8 @@ * * @return {Polygon} a copy of the polygon */ -Polygon.prototype.clone = function () { +Polygon.prototype.clone = function () +{ return new Polygon(this.points.slice()); }; @@ -62,19 +67,22 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this polygon */ -Polygon.prototype.contains = function (x, y) { +Polygon.prototype.contains = function (x, y) +{ var inside = false; // use some raycasting to test hits // https://github.com/substack/point-in-polygon/blob/master/index.js var length = this.points.length / 2; - for (var i = 0, j = length - 1; i < length; j = i++) { + for (var i = 0, j = length - 1; i < length; j = i++) + { var xi = this.points[i * 2], yi = this.points[i * 2 + 1], xj = this.points[j * 2], yj = this.points[j * 2 + 1], intersect = ((yi > y) !== (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi); - if (intersect) { + if (intersect) + { inside = !inside; } } diff --git a/src/core/math/shapes/Rectangle.js b/src/core/math/shapes/Rectangle.js index 16ac62a..4008b68 100644 --- a/src/core/math/shapes/Rectangle.js +++ b/src/core/math/shapes/Rectangle.js @@ -10,7 +10,8 @@ * @param width {number} The overall width of this rectangle * @param height {number} The overall height of this rectangle */ -function Rectangle(x, y, width, height) { +function Rectangle(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -60,7 +61,8 @@ * * @return {Rectangle} a copy of the rectangle */ -Rectangle.prototype.clone = function () { +Rectangle.prototype.clone = function () +{ return new Rectangle(this.x, this.y, this.width, this.height); }; @@ -71,13 +73,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rectangle */ -Rectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Rectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/math/shapes/RoundedRectangle.js b/src/core/math/shapes/RoundedRectangle.js index 27d286e..7bf6411 100644 --- a/src/core/math/shapes/RoundedRectangle.js +++ b/src/core/math/shapes/RoundedRectangle.js @@ -11,7 +11,8 @@ * @param height {number} The overall height of this rounded rectangle * @param radius {number} Controls the radius of the rounded corners */ -function RoundedRectangle(x, y, width, height, radius) { +function RoundedRectangle(x, y, width, height, radius) +{ /** * @member {number} * @default 0 @@ -58,7 +59,8 @@ * * @return {RoundedRectangle} a copy of the rounded rectangle */ -RoundedRectangle.prototype.clone = function () { +RoundedRectangle.prototype.clone = function () +{ return new RoundedRectangle(this.x, this.y, this.width, this.height, this.radius); }; @@ -69,13 +71,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rounded Rectangle */ -RoundedRectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +RoundedRectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/primitives/Graphics.js b/src/core/primitives/Graphics.js index 261c534..e902d2a 100644 --- a/src/core/primitives/Graphics.js +++ b/src/core/primitives/Graphics.js @@ -16,7 +16,8 @@ * @extends DisplayObjectContainer * @namespace PIXI */ -function Graphics() { +function Graphics() +{ DisplayObjectContainer.call(this); this.renderable = true; @@ -154,16 +155,20 @@ * @private */ cacheAsBitmap: { - get: function () { + get: function () + { return this._cacheAsBitmap; }, - set: function (value) { + set: function (value) + { this._cacheAsBitmap = value; - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._generateCachedSprite(); } - else { + else + { this.destroyCachedSprite(); this.dirty = true; } @@ -176,7 +181,8 @@ * * @return {Graphics} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ var clone = new Graphics(); clone.renderable = this.renderable; @@ -192,7 +198,8 @@ clone.cachedSpriteDirty = this.cachedSpriteDirty; // copy graphics data - for (var i = 0; i < this.graphicsData.length; ++i) { + for (var i = 0; i < this.graphicsData.length; ++i) + { clone.graphicsData.push(this.graphicsData.clone()); } @@ -211,17 +218,21 @@ * @param alpha {number} alpha of the line to draw, will update the objects stored style * @return {Graphics} */ -Graphics.prototype.lineStyle = function (lineWidth, color, alpha) { +Graphics.prototype.lineStyle = function (lineWidth, color, alpha) +{ this.lineWidth = lineWidth || 0; this.lineColor = color || 0; this.lineAlpha = (arguments.length < 3) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length) + { // halfway through a line? start a new one! this.drawShape( new math.Polygon( this.currentPath.shape.points.slice(-2) )); } - else { + else + { // otherwise its empty so lets just set the line properties this.currentPath.lineWidth = this.lineWidth; this.currentPath.lineColor = this.lineColor; @@ -239,7 +250,8 @@ * @param y {number} the Y coordinate to move to * @return {Graphics} */ -Graphics.prototype.moveTo = function (x, y) { +Graphics.prototype.moveTo = function (x, y) +{ this.drawShape(new math.Polygon([x,y])); return this; @@ -253,7 +265,8 @@ * @param y {number} the Y coordinate to draw to * @return {Graphics} */ -Graphics.prototype.lineTo = function (x, y) { +Graphics.prototype.lineTo = function (x, y) +{ this.currentPath.shape.points.push(x, y); this.dirty = true; @@ -270,13 +283,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -285,7 +302,8 @@ n = 20, points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { this.moveTo(0, 0); } @@ -293,7 +311,8 @@ var fromY = points[points.length-1]; var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; xa = fromX + ( (cpX - fromX) * j ); @@ -319,13 +338,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -342,7 +365,8 @@ var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; dt = (1 - j); @@ -373,13 +397,17 @@ * @param radius {number} The radius of the arc * @return {Graphics} */ -Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points.push(x1, y1); } } - else { + else + { this.moveTo(x1, y1); } @@ -392,12 +420,15 @@ b2 = x2 - x1, mm = Math.abs(a1 * b2 - b1 * a2); - if (mm < 1.0e-8 || radius === 0) { - if (points[points.length-2] !== x1 || points[points.length-1] !== y1) { + if (mm < 1.0e-8 || radius === 0) + { + if (points[points.length-2] !== x1 || points[points.length-1] !== y1) + { points.push(x1, y1); } } - else { + else + { var dd = a1 * a1 + b1 * b1, cc = a2 * a2 + b2 * b2, tt = a1 * a2 + b1 * b2, @@ -433,42 +464,51 @@ * @param anticlockwise {boolean} Optional. Specifies whether the drawing should be counterclockwise or clockwise. False is default, and indicates clockwise, while true indicates counter-clockwise. * @return {Graphics} */ -Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) { +Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) +{ var startX = cx + Math.cos(startAngle) * radius; var startY = cy + Math.sin(startAngle) * radius; var points; // TODO - This if-else makes no sense. It uses currentPath in the else where it doesn't exist... - if (this.currentPath) { + if (this.currentPath) + { points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { points.push(startX, startY); } - else if (points[points.length-2] !== startX || points[points.length-1] !== startY) { + else if (points[points.length-2] !== startX || points[points.length-1] !== startY) + { points.push(startX, startY); } } - else { + else + { this.moveTo(startX, startY); points = this.currentPath.shape.points; } - if (startAngle === endAngle) { + if (startAngle === endAngle) + { return this; } - if (!anticlockwise && endAngle <= startAngle) { + if (!anticlockwise && endAngle <= startAngle) + { endAngle += Math.PI * 2; } - else if (anticlockwise && startAngle <= endAngle) { + else if (anticlockwise && startAngle <= endAngle) + { startAngle += Math.PI * 2; } var sweep = anticlockwise ? (startAngle - endAngle) *-1 : (endAngle - startAngle); var segs = (Math.abs(sweep)/ (Math.PI * 2)) * 40; - if (sweep === 0) { + if (sweep === 0) + { return this; } @@ -482,7 +522,8 @@ var remainder = ( segMinus % 1 ) / segMinus; - for (var i = 0; i <= segMinus; ++i) { + for (var i = 0; i <= segMinus; ++i) + { var real = i + remainder * i; var angle = ((theta) + startAngle + (theta2 * real)); @@ -506,13 +547,16 @@ * @param alpha {number} the alpha of the fill * @return {Graphics} */ -Graphics.prototype.beginFill = function (color, alpha) { +Graphics.prototype.beginFill = function (color, alpha) +{ this.filling = true; this.fillColor = color || 0; this.fillAlpha = (alpha === undefined) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length <= 2) + { this.currentPath.fill = this.filling; this.currentPath.fillColor = this.fillColor; this.currentPath.fillAlpha = this.fillAlpha; @@ -526,7 +570,8 @@ * * @return {Graphics} */ -Graphics.prototype.endFill = function () { +Graphics.prototype.endFill = function () +{ this.filling = false; this.fillColor = null; this.fillAlpha = 1; @@ -542,7 +587,8 @@ * @param height {number} The height of the rectangle * @return {Graphics} */ -Graphics.prototype.drawRect = function ( x, y, width, height ) { +Graphics.prototype.drawRect = function ( x, y, width, height ) +{ this.drawShape(new math.Rectangle(x,y, width, height)); return this; @@ -556,7 +602,8 @@ * @param height {number} The height of the rectangle * @param radius {number} Radius of the rectangle corners */ -Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) { +Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) +{ this.drawShape(new math.RoundedRectangle(x, y, width, height, radius)); return this; @@ -570,7 +617,8 @@ * @param radius {number} The radius of the circle * @return {Graphics} */ -Graphics.prototype.drawCircle = function (x, y, radius) { +Graphics.prototype.drawCircle = function (x, y, radius) +{ this.drawShape(new math.Circle(x,y, radius)); return this; @@ -585,7 +633,8 @@ * @param height {number} The half height of the ellipse * @return {Graphics} */ -Graphics.prototype.drawEllipse = function (x, y, width, height) { +Graphics.prototype.drawEllipse = function (x, y, width, height) +{ this.drawShape(new math.Ellipse(x, y, width, height)); return this; @@ -597,8 +646,10 @@ * @param path {Array} The path data used to construct the polygon. * @return {Graphics} */ -Graphics.prototype.drawPolygon = function (path) { - if (!(path instanceof Array)) { +Graphics.prototype.drawPolygon = function (path) +{ + if (!(path instanceof Array)) + { path = Array.prototype.slice.call(arguments); } @@ -612,7 +663,8 @@ * * @return {Graphics} */ -Graphics.prototype.clear = function () { +Graphics.prototype.clear = function () +{ this.lineWidth = 0; this.filling = false; @@ -631,7 +683,8 @@ * @param scaleMode {number} Should be one of the scaleMode consts * @return {Texture} a texture of the graphics object */ -Graphics.prototype.generateTexture = function (resolution, scaleMode) { +Graphics.prototype.generateTexture = function (resolution, scaleMode) +{ resolution = resolution || 1; var bounds = this.getBounds(); @@ -655,17 +708,21 @@ * * @param renderer {WebGLRenderer} */ -Graphics.prototype._renderWebGL = function (renderer) { +Graphics.prototype._renderWebGL = function (renderer) +{ // if the sprite is not visible or the alpha is 0 then no need to render this element - if (this.isMask === true) { + if (this.isMask === true) + { return; } // this code may still be needed so leaving for now.. - // + // /* - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture on the gpu too! @@ -681,17 +738,24 @@ return; } - */ - - // check if the webgl graphic needs to be updated - if (this.glDirty) { - this.dirty = true; - this.glDirty = false; - } + else */ - renderer.setObjectRendererer(renderer.graphicsRenderer); - renderer.graphicsRenderer.render(this); + renderer.spriteBatch.stop(); + renderer.blendModeManager.setBlendMode(this.blendMode); + // check blend mode + renderer.blendModeManager.setBlendMode( this.blendMode ); + + // check if the webgl graphic needs to be updated + if (this.glDirty) + { + this.dirty = true; + this.glDirty = false; + } + + WebGLGraphics.renderGraphics(this, renderer); + + renderer.spriteBatch.start(); }; /** @@ -700,14 +764,18 @@ * @param renderer {CanvasRenderer} * @private */ -Graphics.prototype.renderCanvas = function (renderer) { +Graphics.prototype.renderCanvas = function (renderer) +{ // 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.isMask === true) { + if (!this.visible || this.alpha <= 0 || this.isMask === true) + { return; } - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture @@ -723,16 +791,19 @@ return; } - else { + else + { var context = renderer.context; var transform = this.worldTransform; - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } @@ -748,11 +819,13 @@ CanvasGraphics.renderGraphics(this, context); - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } } @@ -763,13 +836,16 @@ * * @return {Rectangle} the rectangular bounding area */ -Graphics.prototype.getBounds = function (matrix) { +Graphics.prototype.getBounds = function (matrix) +{ // return an empty object if the item is a mask! - if (this.isMask) { + if (this.isMask) + { return math.Rectangle.EMPTY; } - if (this.dirty) { + if (this.dirty) + { this.updateLocalBounds(); this.glDirty = true; @@ -841,23 +917,27 @@ * Update the bounds of the object * */ -Graphics.prototype.updateLocalBounds = function () { +Graphics.prototype.updateLocalBounds = function () +{ var minX = Infinity; var maxX = -Infinity; var minY = Infinity; var maxY = -Infinity; - if (this.graphicsData.length) { + if (this.graphicsData.length) + { var shape, points, x, y, w, h; - for (var i = 0; i < this.graphicsData.length; i++) { + for (var i = 0; i < this.graphicsData.length; i++) + { var data = this.graphicsData[i]; var type = data.type; var lineWidth = data.lineWidth; shape = data.shape; - if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) { + if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) + { x = shape.x - lineWidth/2; y = shape.y - lineWidth/2; w = shape.width + lineWidth; @@ -869,7 +949,8 @@ minY = y < minY ? y : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.CIRC) { + else if (type === CONST.SHAPES.CIRC) + { x = shape.x; y = shape.y; w = shape.radius + lineWidth/2; @@ -881,7 +962,8 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.ELIP) { + else if (type === CONST.SHAPES.ELIP) + { x = shape.x; y = shape.y; w = shape.width + lineWidth/2; @@ -893,11 +975,13 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else { + else + { // POLY points = shape.points; - for (var j = 0; j < points.length; j += 2) { + for (var j = 0; j < points.length; j += 2) + { x = points[j]; y = points[j+1]; @@ -910,7 +994,8 @@ } } } - else { + else + { minX = 0; maxX = 0; minY = 0; @@ -931,10 +1016,12 @@ * * @private */ -Graphics.prototype._generateCachedSprite = function () { +Graphics.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { var canvasBuffer = new CanvasBuffer(bounds.width, bounds.height); var texture = Texture.fromCanvas(canvasBuffer.canvas); @@ -943,7 +1030,8 @@ this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.buffer.resize(bounds.width, bounds.height); } @@ -968,7 +1056,8 @@ * * @private */ -Graphics.prototype.updateCachedSpriteTexture = function () { +Graphics.prototype.updateCachedSpriteTexture = function () +{ var cachedSprite = this._cachedSprite; var texture = cachedSprite.texture; var canvas = cachedSprite.buffer.canvas; @@ -989,7 +1078,8 @@ * Destroys a previous cached sprite. * */ -Graphics.prototype.destroyCachedSprite = function () { +Graphics.prototype.destroyCachedSprite = function () +{ this._cachedSprite.texture.destroy(true); // let the gc collect the unused sprite @@ -1003,10 +1093,13 @@ * @param {Circle|Rectangle|Ellipse|Line|Polygon} shape The Shape object to draw. * @return {GraphicsData} The generated GraphicsData object. */ -Graphics.prototype.drawShape = function (shape) { - if (this.currentPath) { +Graphics.prototype.drawShape = function (shape) +{ + if (this.currentPath) + { // check current path! - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath.shape.points.length <= 2) + { this.graphicsData.pop(); } } @@ -1017,7 +1110,8 @@ this.graphicsData.push(data); - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { data.shape.closed = this.filling; this.currentPath = data; } diff --git a/src/core/primitives/GraphicsData.js b/src/core/primitives/GraphicsData.js index 99decbe..788f6f2 100644 --- a/src/core/primitives/GraphicsData.js +++ b/src/core/primitives/GraphicsData.js @@ -4,7 +4,8 @@ * @class * @namespace PIXI */ -function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) { +function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) +{ this.lineWidth = lineWidth; this.lineColor = lineColor; this.lineAlpha = lineAlpha; @@ -27,7 +28,8 @@ * * @return {GraphicsData} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ return new GraphicsData( this.lineWidth, this.lineColor, diff --git a/src/core/renderers/canvas/CanvasRenderer.js b/src/core/renderers/canvas/CanvasRenderer.js index 15a0978..7aebd44 100644 --- a/src/core/renderers/canvas/CanvasRenderer.js +++ b/src/core/renderers/canvas/CanvasRenderer.js @@ -17,17 +17,22 @@ * @param [options.resolution=1] {number} the resolution of the renderer retina would be 2 * @param [options.clearBeforeRender=true] {boolean} This sets if the CanvasRenderer will clear the canvas or not before the new render pass. */ -function CanvasRenderer(width, height, options) { +function CanvasRenderer(width, height, options) +{ utils.sayHello('Canvas'); - if (options) { - for (var i in CONST.defaultRenderOptions) { - if (typeof options[i] === 'undefined') { + if (options) + { + for (var i in CONST.defaultRenderOptions) + { + if (typeof options[i] === 'undefined') + { options[i] = CONST.defaultRenderOptions[i]; } } } - else { + else + { options = CONST.defaultRenderOptions; } @@ -156,19 +161,24 @@ this.smoothProperty = null; - if (this.context.imageSmoothingEnabled) { + if (this.context.imageSmoothingEnabled) + { this.smoothProperty = 'imageSmoothingEnabled'; } - else if (this.context.webkitImageSmoothingEnabled) { + else if (this.context.webkitImageSmoothingEnabled) + { this.smoothProperty = 'webkitImageSmoothingEnabled'; } - else if (this.context.mozImageSmoothingEnabled) { + else if (this.context.mozImageSmoothingEnabled) + { this.smoothProperty = 'mozImageSmoothingEnabled'; } - else if (this.context.oImageSmoothingEnabled) { + else if (this.context.oImageSmoothingEnabled) + { this.smoothProperty = 'oImageSmoothingEnabled'; } - else if (this.context.msImageSmoothingEnabled) { + else if (this.context.msImageSmoothingEnabled) + { this.smoothProperty = 'msImageSmoothingEnabled'; } @@ -193,10 +203,12 @@ * @memberof CanvasRenderer# */ backgroundColor: { - get: function () { + get: function () + { return this._backgroundColor; }, - set: function (val) { + set: function (val) + { this._backgroundColor = val; this._backgroundColorString = utils.hex2string(val); } @@ -208,7 +220,8 @@ * * @param object {DisplayObject} the object to be rendered */ -CanvasRenderer.prototype.render = function (object) { +CanvasRenderer.prototype.render = function (object) +{ object.updateTransform(); this.context.setTransform(1,0,0,1,0,0); @@ -218,16 +231,20 @@ this.currentBlendMode = CONST.blendModes.NORMAL; this.context.globalCompositeOperation = this.blendModes[CONST.blendModes.NORMAL]; - if (navigator.isCocoonJS && this.view.screencanvas) { + if (navigator.isCocoonJS && this.view.screencanvas) + { this.context.fillStyle = 'black'; this.context.clear(); } - if (this.clearBeforeRender) { - if (this.transparent) { + if (this.clearBeforeRender) + { + if (this.transparent) + { this.context.clearRect(0, 0, this.width, this.height); } - else { + else + { this.context.fillStyle = this._backgroundColorString; this.context.fillRect(0, 0, this.width , this.height); } @@ -241,8 +258,10 @@ * * @param [removeView=false] {boolean} Removes the Canvas element from the DOM. */ -CanvasRenderer.prototype.destroy = function (removeView) { - if (removeView && this.view.parent) { +CanvasRenderer.prototype.destroy = function (removeView) +{ + if (removeView && this.view.parent) + { this.view.parent.removeChild(this.view); } @@ -257,14 +276,16 @@ * @param width {number} the new width of the canvas view * @param height {number} the new height of the canvas view */ -CanvasRenderer.prototype.resize = function (width, height) { +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) { + if (this.autoResize) + { this.view.style.width = this.width / this.resolution + 'px'; this.view.style.height = this.height / this.resolution + 'px'; } @@ -276,7 +297,8 @@ * @param displayObject {DisplayObject} The displayObject to render * @private */ -CanvasRenderer.prototype.renderDisplayObject = function (displayObject) { +CanvasRenderer.prototype.renderDisplayObject = function (displayObject) +{ displayObject.renderCanvas(this); }; @@ -285,11 +307,14 @@ * * @private */ -CanvasRenderer.prototype._mapBlendModes = function () { - if (!this.blendModes) { +CanvasRenderer.prototype._mapBlendModes = function () +{ + if (!this.blendModes) + { this.blendModes = {}; - if (utils.canUseNewCanvasBlendModes()) { + if (utils.canUseNewCanvasBlendModes()) + { this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? this.blendModes[CONST.blendModes.MULTIPLY] = 'multiply'; @@ -308,7 +333,8 @@ this.blendModes[CONST.blendModes.COLOR] = 'color'; this.blendModes[CONST.blendModes.LUMINOSITY] = 'luminosity'; } - else { + else + { // this means that the browser does not support the cool new blend modes in canvas 'cough' ie 'cough' this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? diff --git a/src/core/renderers/canvas/utils/CanvasBuffer.js b/src/core/renderers/canvas/utils/CanvasBuffer.js index ebe5d47..b183a66 100644 --- a/src/core/renderers/canvas/utils/CanvasBuffer.js +++ b/src/core/renderers/canvas/utils/CanvasBuffer.js @@ -6,7 +6,8 @@ * @param width {number} the width for the newly created canvas * @param height {number} the height for the newly created canvas */ -function CanvasBuffer(width, height) { +function CanvasBuffer(width, height) +{ /** * The Canvas object that belongs to this CanvasBuffer. * @@ -36,10 +37,12 @@ * @memberof CanvasBuffer# */ width: { - get: function () { + get: function () + { return this.canvas.width; }, - set: function (val) { + set: function (val) + { this.canvas.width = val; } }, @@ -50,10 +53,12 @@ * @memberof CanvasBuffer# */ height: { - get: function () { + get: function () + { return this.canvas.height; }, - set: function (val) { + set: function (val) + { this.canvas.height = val; } } @@ -64,7 +69,8 @@ * * @private */ -CanvasBuffer.prototype.clear = function () { +CanvasBuffer.prototype.clear = function () +{ this.context.setTransform(1, 0, 0, 1, 0, 0); this.context.clearRect(0,0, this.canvas.width, this.canvas.height); }; @@ -75,7 +81,8 @@ * @param width {number} the new width of the canvas * @param height {number} the new height of the canvas */ -CanvasBuffer.prototype.resize = function (width, height) { +CanvasBuffer.prototype.resize = function (width, height) +{ this.canvas.width = width; this.canvas.height = height; }; diff --git a/src/core/renderers/canvas/utils/CanvasGraphics.js b/src/core/renderers/canvas/utils/CanvasGraphics.js index c7eaa2a..3f2a91f 100644 --- a/src/core/renderers/canvas/utils/CanvasGraphics.js +++ b/src/core/renderers/canvas/utils/CanvasGraphics.js @@ -13,15 +13,18 @@ * @param graphics {Graphics} the actual graphics object to render * @param context {CanvasRenderingContext2D} the 2d drawing method of the canvas */ -CanvasGraphics.renderGraphics = function (graphics, context) { +CanvasGraphics.renderGraphics = function (graphics, context) +{ var worldAlpha = graphics.worldAlpha; - if (graphics.dirty) { + if (graphics.dirty) + { this.updateGraphicsTint(graphics); graphics.dirty = false; } - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; @@ -30,69 +33,82 @@ context.lineWidth = data.lineWidth; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { context.beginPath(); var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } - if (shape.closed) { + if (shape.closed) + { context.lineTo(points[0], points[1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fillRect(shape.x, shape.y, shape.width, shape.height); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.strokeRect(shape.x, shape.y, shape.width, shape.height); } } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.beginPath(); context.arc(shape.x, shape.y, shape.radius,0,2*Math.PI); context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas var w = shape.width * 2; @@ -119,18 +135,21 @@ context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; var width = shape.width; @@ -152,13 +171,15 @@ context.quadraticCurveTo(rx, ry, rx, ry + radius); context.closePath(); - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); @@ -174,45 +195,54 @@ * @param graphics {Graphics} the graphics which will be used as a mask * @param context {CanvasRenderingContext2D} the context 2d method of the canvas */ -CanvasGraphics.renderGraphicsMask = function (graphics, context) { +CanvasGraphics.renderGraphicsMask = function (graphics, context) +{ var len = graphics.graphicsData.length; - if (len === 0) { + if (len === 0) + { return; } context.beginPath(); - for (var i = 0; i < len; i++) { + for (var i = 0; i < len; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { context.rect(shape.x, shape.y, shape.width, shape.height); context.closePath(); } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.arc(shape.x, shape.y, shape.radius, 0, 2 * Math.PI); context.closePath(); } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas @@ -237,7 +267,8 @@ context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); context.closePath(); } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; @@ -262,8 +293,10 @@ } }; -CanvasGraphics.updateGraphicsTint = function (graphics) { - if (graphics.tint === 0xFFFFFF) { +CanvasGraphics.updateGraphicsTint = function (graphics) +{ + if (graphics.tint === 0xFFFFFF) + { return; } @@ -271,7 +304,8 @@ var tintG = (graphics.tint >> 8 & 0xFF) / 255; var tintB = (graphics.tint & 0xFF)/ 255; - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var fillColor = data.fillColor | 0; diff --git a/src/core/renderers/canvas/utils/CanvasMaskManager.js b/src/core/renderers/canvas/utils/CanvasMaskManager.js index e04a733..9827d36 100644 --- a/src/core/renderers/canvas/utils/CanvasMaskManager.js +++ b/src/core/renderers/canvas/utils/CanvasMaskManager.js @@ -6,7 +6,8 @@ * @class * @namespace PIXI */ -function CanvasMaskManager() {} +function CanvasMaskManager() +{} CanvasMaskManager.prototype.constructor = CanvasMaskManager; module.exports = CanvasMaskManager; @@ -17,7 +18,8 @@ * @param maskData {object} the maskData that will be pushed * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.pushMask = function (maskData, renderer) { +CanvasMaskManager.prototype.pushMask = function (maskData, renderer) +{ renderer.context.save(); var cacheAlpha = maskData.alpha; @@ -45,6 +47,7 @@ * * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.popMask = function (renderer) { +CanvasMaskManager.prototype.popMask = function (renderer) +{ renderer.context.restore(); }; diff --git a/src/core/renderers/canvas/utils/CanvasTinter.js b/src/core/renderers/canvas/utils/CanvasTinter.js index 17e0529..d2fb1bc 100644 --- a/src/core/renderers/canvas/utils/CanvasTinter.js +++ b/src/core/renderers/canvas/utils/CanvasTinter.js @@ -14,7 +14,8 @@ * @param color {number} the color to use to tint the sprite with * @return {HTMLCanvasElement} The tinted canvas */ -CanvasTinter.getTintedTexture = function (sprite, color) { +CanvasTinter.getTintedTexture = function (sprite, color) +{ var texture = sprite.texture; color = CanvasTinter.roundColor(color); @@ -23,7 +24,8 @@ texture.tintCache = texture.tintCache || {}; - if (texture.tintCache[stringColor]) { + if (texture.tintCache[stringColor]) + { return texture.tintCache[stringColor]; } @@ -33,14 +35,16 @@ //CanvasTinter.tintWithPerPixel(texture, stringColor, canvas); CanvasTinter.tintMethod(texture, color, canvas); - if (CanvasTinter.convertTintToImage) { + if (CanvasTinter.convertTintToImage) + { // is this better? var tintImage = new Image(); tintImage.src = canvas.toDataURL(); texture.tintCache[stringColor] = tintImage; } - else { + else + { texture.tintCache[stringColor] = canvas; // if we are not converting the texture to an image then we need to lose the reference to the canvas CanvasTinter.canvas = null; @@ -56,7 +60,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithMultiply = function (texture, color, canvas) { +CanvasTinter.tintWithMultiply = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -104,7 +109,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithOverlay = function (texture, color, canvas) { +CanvasTinter.tintWithOverlay = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -139,7 +145,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithPerPixel = function (texture, color, canvas) { +CanvasTinter.tintWithPerPixel = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -167,7 +174,8 @@ var pixels = pixelData.data; - for (var i = 0; i < pixels.length; i += 4) { + for (var i = 0; i < pixels.length; i += 4) + { pixels[i+0] *= r; pixels[i+1] *= g; pixels[i+2] *= b; @@ -181,7 +189,8 @@ * * @param color {number} the color to round, should be a hex color */ -CanvasTinter.roundColor = function (color) { +CanvasTinter.roundColor = function (color) +{ var step = CanvasTinter.cacheStepsPerColorChannel; var rgbValues = utils.hex2rgb(color); diff --git a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js index 9f2f89a..35edbaf 100644 --- a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js +++ b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLBlendModeManager(renderer) { +function WebGLBlendModeManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -23,8 +24,10 @@ * * @param blendMode {number} the blendMode, should be a Pixi const, such as BlendModes.ADD */ -WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) { - if (this.currentBlendMode === blendMode) { +WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) +{ + if (this.currentBlendMode === blendMode) + { return false; } diff --git a/src/core/renderers/webgl/managers/WebGLFilterManager.js b/src/core/renderers/webgl/managers/WebGLFilterManager.js index 1179258..2dac048 100644 --- a/src/core/renderers/webgl/managers/WebGLFilterManager.js +++ b/src/core/renderers/webgl/managers/WebGLFilterManager.js @@ -7,7 +7,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLFilterManager(renderer) { +function WebGLFilterManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -32,7 +33,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.texturePool.length = 0; self.initShaderBuffers(); }); @@ -46,7 +48,8 @@ * @param renderer {WebGLRenderer} * @param buffer {ArrayBuffer} */ -WebGLFilterManager.prototype.begin = function (buffer) { +WebGLFilterManager.prototype.begin = function (buffer) +{ this.defaultShader = this.renderer.shaderManager.defaultShader; this.width = this.renderer.projection.x * 2; @@ -60,7 +63,8 @@ * * @param filterBlock {object} the filter that will be pushed to the current filter stack */ -WebGLFilterManager.prototype.pushFilter = function (filterBlock) { +WebGLFilterManager.prototype.pushFilter = function (filterBlock) +{ var gl = this.renderer.gl; var projection = this.renderer.projection; @@ -78,10 +82,12 @@ this.offsetY += filterBlock._filterArea.y; var texture = this.texturePool.pop(); - if (!texture) { + if (!texture) + { texture = new FilterTexture(this.renderer.gl, this.width, this.height); } - else { + else + { texture.resize(this.width, this.height); } @@ -98,29 +104,35 @@ var localX = filterArea.x, localY = filterArea.y; - if (filterArea.x < 0) { + if (filterArea.x < 0) + { filterArea.width += filterArea.x; filterArea.x = 0; } - if (filterArea.y < 0) { + if (filterArea.y < 0) + { filterArea.height += filterArea.y; filterArea.y = 0; } - if (localX + filterArea.width > this.width) { + if (localX + filterArea.width > this.width) + { filterArea.width = this.width - localX; } - if (localY + filterArea.height > this.height) { + if (localY + filterArea.height > this.height) + { filterArea.height = this.height - localY; } - if (filterArea.width < 0) { + if (filterArea.width < 0) + { filterArea.width = 0; } - if (filterArea.height < 0) { + if (filterArea.height < 0) + { filterArea.height = 0; } @@ -154,7 +166,8 @@ * Removes the last filter from the filter stack and doesn't return it. * */ -WebGLFilterManager.prototype.popFilter = function () { +WebGLFilterManager.prototype.popFilter = function () +{ var gl = this.renderer.gl; var filterBlock = this.filterStack.pop(); @@ -163,7 +176,8 @@ var projection = this.renderer.projection; var offset = this.renderer.offset; - if (filterBlock.filterPasses.length > 1) { + if (filterBlock.filterPasses.length > 1) + { gl.viewport(0, 0, filterArea.width, filterArea.height); gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); @@ -193,7 +207,8 @@ var inputTexture = texture; var outputTexture = this.texturePool.pop(); - if (!outputTexture) { + if (!outputTexture) + { outputTexture = new FilterTexture(this.renderer.gl, this.width, this.height); } outputTexture.resize(this.width, this.height); @@ -204,7 +219,8 @@ gl.disable(gl.BLEND); - for (var i = 0; i < filterBlock.filterPasses.length-1; i++) { + for (var i = 0; i < filterBlock.filterPasses.length-1; i++) + { var filterPass = filterBlock.filterPasses[i]; gl.bindFramebuffer(gl.FRAMEBUFFER, outputTexture.frameBuffer ); @@ -243,10 +259,12 @@ var buffer = this.buffer; // time to render the filters texture to the previous scene - if (this.filterStack.length === 0) { + if (this.filterStack.length === 0) + { gl.colorMask(true, true, true, true);//this.transparent); } - else { + else + { var currentFilter = this.filterStack[this.filterStack.length-1]; filterArea = currentFilter._filterArea; @@ -332,13 +350,15 @@ * @param width {number} the horizontal range of the filter * @param height {number} the vertical range of the filter */ -WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) { +WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) +{ // use program var gl = this.renderer.gl; var shader = filter.shaders[gl.id]; - if (!shader) { + if (!shader) + { shader = new Shader(gl); shader.fragmentSrc = filter.fragmentSrc; @@ -356,7 +376,8 @@ gl.uniform2f(shader.projectionVector, width/2, -height/2); gl.uniform2f(shader.offsetVector, 0,0); - if (filter.uniforms.dimensions) { + 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]; @@ -386,7 +407,8 @@ * Initialises the shader buffers. * */ -WebGLFilterManager.prototype.initShaderBuffers = function () { +WebGLFilterManager.prototype.initShaderBuffers = function () +{ var gl = this.renderer.gl; // create some buffers @@ -432,7 +454,8 @@ * Destroys the filter and removes it from the filter stack. * */ -WebGLFilterManager.prototype.destroy = function () { +WebGLFilterManager.prototype.destroy = function () +{ var gl = this.renderer.gl; this.filterStack = null; @@ -441,7 +464,8 @@ this.offsetY = 0; // destroy textures - for (var i = 0; i < this.texturePool.length; i++) { + for (var i = 0; i < this.texturePool.length; i++) + { this.texturePool[i].destroy(); } diff --git a/src/core/renderers/webgl/managers/WebGLManager.js b/src/core/renderers/webgl/managers/WebGLManager.js index 9d47b5c..c30cd51 100644 --- a/src/core/renderers/webgl/managers/WebGLManager.js +++ b/src/core/renderers/webgl/managers/WebGLManager.js @@ -3,7 +3,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLManager(renderer) { +function WebGLManager(renderer) +{ /** * The renderer this manager works for. * @@ -15,6 +16,7 @@ WebGLManager.prototype.constructor = WebGLManager; module.exports = WebGLManager; -WebGLManager.prototype.destroy = function () { +WebGLManager.prototype.destroy = function () +{ this.renderer = null; }; diff --git a/src/core/renderers/webgl/managers/WebGLMaskManager.js b/src/core/renderers/webgl/managers/WebGLMaskManager.js index 2f90b64..e568812 100644 --- a/src/core/renderers/webgl/managers/WebGLMaskManager.js +++ b/src/core/renderers/webgl/managers/WebGLMaskManager.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLMaskManager(renderer) { +function WebGLMaskManager(renderer) +{ WebGLManager.call(this, renderer); } @@ -19,12 +20,15 @@ * * @param maskData {any[]} */ -WebGLMaskManager.prototype.pushMask = function (maskData) { - if (maskData.dirty) { +WebGLMaskManager.prototype.pushMask = function (maskData) +{ + if (maskData.dirty) + { WebGLGraphics.updateGraphics(maskData, this.renderer.gl); } - if (!maskData._webGL[this.renderer.gl.id].data.length) { + if (!maskData._webGL[this.renderer.gl.id].data.length) + { return; } @@ -36,6 +40,7 @@ * * @param maskData {any[]} */ -WebGLMaskManager.prototype.popMask = function (maskData) { +WebGLMaskManager.prototype.popMask = function (maskData) +{ this.renderer.stencilManager.popStencil(maskData, maskData._webGL[this.renderer.gl.id].data[0], this.renderer); }; diff --git a/src/core/renderers/webgl/managers/WebGLShaderManager.js b/src/core/renderers/webgl/managers/WebGLShaderManager.js index fef071c..90c6477 100644 --- a/src/core/renderers/webgl/managers/WebGLShaderManager.js +++ b/src/core/renderers/webgl/managers/WebGLShaderManager.js @@ -10,7 +10,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLShaderManager(renderer) { +function WebGLShaderManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -28,7 +29,8 @@ */ this.tempAttribState = []; - for (var i = 0; i < this.maxAttibs; i++) { + for (var i = 0; i < this.maxAttibs; i++) + { this.attribState[i] = false; } @@ -66,7 +68,8 @@ // listen for context and update necessary shaders var self = this; - this.renderer.on('context', function (event) { + this.renderer.on('context', function (event) + { var gl = event.data; // this shader is used for rendering primitives @@ -97,29 +100,36 @@ * * @param attribs {Array} attribs */ -WebGLShaderManager.prototype.setAttribs = function (attribs) { +WebGLShaderManager.prototype.setAttribs = function (attribs) +{ // reset temp state var i; - for (i = 0; i < this.tempAttribState.length; i++) { + for (i = 0; i < this.tempAttribState.length; i++) + { this.tempAttribState[i] = false; } // set the new attribs - for (var a in attribs) { + for (var a in attribs) + { this.tempAttribState[attribs[a]] = true; } var gl = this.renderer.gl; - for (i = 0; i < this.attribState.length; i++) { - if (this.attribState[i] !== this.tempAttribState[i]) { + for (i = 0; i < this.attribState.length; i++) + { + if (this.attribState[i] !== this.tempAttribState[i]) + { this.attribState[i] = this.tempAttribState[i]; - if (this.attribState[i]) { + if (this.attribState[i]) + { gl.enableVertexAttribArray(i); } - else { + else + { gl.disableVertexAttribArray(i); } } @@ -131,8 +141,10 @@ * * @param shader {Any} */ -WebGLShaderManager.prototype.setShader = function (shader) { - if (this._currentId === shader.uuid) { +WebGLShaderManager.prototype.setShader = function (shader) +{ + if (this._currentId === shader.uuid) + { return false; } @@ -150,7 +162,8 @@ * Destroys this object. * */ -WebGLShaderManager.prototype.destroy = function () { +WebGLShaderManager.prototype.destroy = function () +{ this.attribState = null; this.tempAttribState = null; diff --git a/src/core/renderers/webgl/managers/WebGLStencilManager.js b/src/core/renderers/webgl/managers/WebGLStencilManager.js index 9ec6398..4cb0134 100644 --- a/src/core/renderers/webgl/managers/WebGLStencilManager.js +++ b/src/core/renderers/webgl/managers/WebGLStencilManager.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLStencilManager(renderer) { +function WebGLStencilManager(renderer) +{ WebGLManager.call(this, renderer); this.stencilStack = []; @@ -24,12 +25,14 @@ * @param graphics {Graphics} * @param webGLData {any[]} */ -WebGLStencilManager.prototype.pushStencil = function (graphics, webGLData) { +WebGLStencilManager.prototype.pushStencil = function (graphics, webGLData) +{ var gl = this.renderer.gl; this.bindGraphics(graphics, webGLData, this.renderer); - if (this.stencilStack.length === 0) { + if (this.stencilStack.length === 0) + { gl.enable(gl.STENCIL_TEST); gl.clear(gl.STENCIL_BUFFER_BIT); this.reverse = true; @@ -47,14 +50,17 @@ // draw the triangle strip! - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } @@ -62,31 +68,38 @@ // draw a quad to increment.. gl.drawElements(gl.TRIANGLE_FAN, 4, gl.UNSIGNED_SHORT, ( webGLData.indices.length - 4 ) * 2 ); - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); } this.reverse = !this.reverse; } - else { - if (!this.reverse) { + else + { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } - else { + 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) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); } } @@ -103,7 +116,8 @@ * @param graphics {Graphics} * @param webGLData {Array} */ -WebGLStencilManager.prototype.bindGraphics = function (graphics, webGLData) { +WebGLStencilManager.prototype.bindGraphics = function (graphics, webGLData) +{ //if (this._currentGraphics === graphics)return; this._currentGraphics = graphics; @@ -114,7 +128,8 @@ offset = this.renderer.offset, shader;// = this.renderer.shaderManager.primitiveShader; - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { shader = this.renderer.shaderManager.complexPrimitiveShader; this.renderer.shaderManager.setShader(shader); @@ -141,7 +156,8 @@ // set the index buffer! gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, webGLData.indexBuffer); } - else { + else + { //this.renderer.shaderManager.activatePrimitiveShader(); shader = this.renderer.shaderManager.primitiveShader; this.renderer.shaderManager.setShader( shader ); @@ -154,7 +170,7 @@ gl.uniform2f(shader.uniforms.offsetVector._location, -offset.x, -offset.y); gl.uniform3fv(shader.uniforms.tint._location, utils.hex2rgb(graphics.tint)); - + gl.uniform1f(shader.uniforms.alpha._location, graphics.worldAlpha); @@ -172,19 +188,22 @@ * @param graphics {Graphics} * @param webGLData {Array} */ -WebGLStencilManager.prototype.popStencil = function (graphics, webGLData) { +WebGLStencilManager.prototype.popStencil = function (graphics, webGLData) +{ var gl = this.renderer.gl; this.stencilStack.pop(); this.count--; - if (this.stencilStack.length === 0) { + if (this.stencilStack.length === 0) + { // the stack is empty! gl.disable(gl.STENCIL_TEST); } - else { + else + { var level = this.count; @@ -192,14 +211,17 @@ gl.colorMask(false, false, false, false); - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { this.reverse = !this.reverse; - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } @@ -213,31 +235,38 @@ // draw the triangle strip! gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); - if (!this.reverse) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); } } - else { + else + { // console.log("<<>>") - if (!this.reverse) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } - else { + 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) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); } } @@ -253,7 +282,8 @@ * Destroys the mask stack. * */ -WebGLStencilManager.prototype.destroy = function () { +WebGLStencilManager.prototype.destroy = function () +{ this.renderer = null; this.stencilStack = null; }; diff --git a/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js b/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js index 913ba5e..1ea7d19 100644 --- a/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js +++ b/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function ComplexPrimitiveShader(gl) { +function ComplexPrimitiveShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -24,7 +25,8 @@ 'uniform float flipY;', 'varying vec4 vColor;', - 'void main(void) {', + '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);', @@ -37,7 +39,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = vColor;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/FastShader.js b/src/core/renderers/webgl/shaders/FastShader.js index bd2e29a..2e5e060 100644 --- a/src/core/renderers/webgl/shaders/FastShader.js +++ b/src/core/renderers/webgl/shaders/FastShader.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function FastShader(gl) { +function FastShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -28,7 +29,8 @@ 'const vec2 center = vec2(-1.0, 1.0);', - 'void main(void) {', + 'void main(void) + {', ' vec2 v;', ' vec2 sv = aVertexPosition * aScale;', ' v.x = (sv.x) * cos(aRotation) - (sv.y) * sin(aRotation);', @@ -49,7 +51,8 @@ 'uniform sampler2D uSampler;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/PrimitiveShader.js b/src/core/renderers/webgl/shaders/PrimitiveShader.js index 6f25409..a25f54f 100644 --- a/src/core/renderers/webgl/shaders/PrimitiveShader.js +++ b/src/core/renderers/webgl/shaders/PrimitiveShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function PrimitiveShader(gl) { +function PrimitiveShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -23,7 +24,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + '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);', @@ -36,7 +38,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = vColor;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/Shader.js b/src/core/renderers/webgl/shaders/Shader.js index f8964f5..fd75ef5 100644 --- a/src/core/renderers/webgl/shaders/Shader.js +++ b/src/core/renderers/webgl/shaders/Shader.js @@ -6,7 +6,8 @@ * @param [fragmentSrc] {string} The source of the fragment shader. * @param [vertexSrc] {string} The source of the vertex shader. */ -function Shader(gl, vertexSrc, fragmentSrc, customUniforms, customAttributes) { +function Shader(gl, vertexSrc, fragmentSrc, customUniforms, customAttributes) +{ /** * @member {number} * @readonly @@ -33,7 +34,8 @@ dimensions: { type: '4f', value: new Float32Array(4) } }; - for (var u in customUniforms) { + for (var u in customUniforms) + { this.uniforms[u] = customUniforms[u]; } @@ -43,7 +45,8 @@ aColor: 0 }; - for (var a in customAttributes) { + for (var a in customAttributes) + { this.attributes[a] = customAttributes[a]; } @@ -66,7 +69,8 @@ 'const vec2 center = vec2(-1.0, 1.0);', - 'void main(void) {', + 'void main(void) + {', ' gl_Position = vec4( ((aVertexPosition + offsetVector) / projectionVector) + center , 0.0, 1.0);', ' vTextureCoord = aTextureCoord;', ' vColor = vec4(aColor.rgb * aColor.a, aColor.a);', @@ -85,7 +89,8 @@ 'uniform sampler2D uSampler;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;', '}' ].join('\n'); @@ -96,7 +101,8 @@ Shader.prototype.constructor = Shader; module.exports = Shader; -Shader.prototype.init = function () { +Shader.prototype.init = function () +{ this.compile(); this.gl.useProgram(this.program); @@ -105,14 +111,18 @@ this.cacheAttributeLocations(Object.keys(this.attributes)); }; -Shader.prototype.cacheUniformLocations = function (keys) { - for (var i = 0; i < keys.length; ++i) { +Shader.prototype.cacheUniformLocations = function (keys) +{ + for (var i = 0; i < keys.length; ++i) + { this.uniforms[keys[i]]._location = this.gl.getUniformLocation(this.program, keys[i]); } }; -Shader.prototype.cacheAttributeLocations = function (keys) { - for (var i = 0; i < keys.length; ++i) { +Shader.prototype.cacheAttributeLocations = function (keys) +{ + for (var i = 0; i < keys.length; ++i) + { this.attributes[keys[i]] = this.gl.getAttribLocation(this.program, keys[i]); } @@ -124,14 +134,16 @@ // 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.attributes.aColor === -1) { + // if (this.attributes.aColor === -1) + { // this.attributes.aColor = 2; // } // End worst hack eva // }; -Shader.prototype.compile = function () { +Shader.prototype.compile = function () +{ var gl = this.gl; var glVertShader = this._glCompile(gl.VERTEX_SHADER, this.vertexSrc); @@ -144,13 +156,15 @@ gl.linkProgram(program); // if linking fails, then log and cleanup - if (!gl.getProgramParameter(program, gl.LINK_STATUS)) { + if (!gl.getProgramParameter(program, gl.LINK_STATUS)) + { window.console.error('Pixi.js Error: Could not initialize shader.'); window.console.error('gl.VALIDATE_STATUS', gl.getProgramParameter(program, gl.VALIDATE_STATUS)); window.console.error('gl.getError()', gl.getError()); // if there is a program info log, log it - if (gl.getProgramInfoLog(program) !== '') { + if (gl.getProgramInfoLog(program) !== '') + { window.console.warn('Pixi.js Warning: gl.getProgramInfoLog()', gl.getProgramInfoLog(program)); } @@ -165,18 +179,21 @@ return (this.program = program); }; -Shader.prototype.syncUniforms = function () { +Shader.prototype.syncUniforms = function () +{ var gl = this.gl; this.textureCount = 1; - for (var key in this.uniforms) { + for (var key in this.uniforms) + { var uniform = this.uniforms[key], location = uniform._location, value = uniform.value, i, il; - switch (uniform.type) { + switch (uniform.type) + { // single int value case 'i': case '1i': @@ -282,7 +299,8 @@ // a Color Value case 'c': - if (typeof value === 'number') { + if (typeof value === 'number') + { value = utils.hex2rgb(value); } @@ -311,11 +329,13 @@ // array of 2D Point objects case 'v2v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(2 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 2] = value[i].x; uniform._array[i * 2 + 1] = value[i].y; } @@ -325,11 +345,13 @@ // array of 3D Point objects case 'v3v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(3 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 3] = value[i].x; uniform._array[i * 3 + 1] = value[i].y; uniform._array[i * 3 + 2] = value[i].z; @@ -341,11 +363,13 @@ // array of 4D Point objects case 'v4v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(4 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 4] = value[i].x; uniform._array[i * 4 + 1] = value[i].y; uniform._array[i * 4 + 2] = value[i].z; @@ -359,7 +383,8 @@ // PIXI.Texture case 't': case 'sampler2D': - if (!uniform.value || !uniform.value.baseTexture || !uniform.value.baseTexture.hasLoaded) { + if (!uniform.value || !uniform.value.baseTexture || !uniform.value.baseTexture.hasLoaded) + { break; } @@ -376,7 +401,8 @@ this.textureCount++; // initialize the texture if we haven't yet - if (!uniform._init) { + if (!uniform._init) + { this.initSampler2D(uniform); uniform._init = true; @@ -394,11 +420,13 @@ * Initialises a Sampler2D uniform (which may only be available later on after initUniforms once the texture has loaded) * */ -Shader.prototype.initSampler2D = function (uniform) { +Shader.prototype.initSampler2D = function (uniform) +{ var gl = this.gl; // Extended texture data - if (uniform.textureData) { + if (uniform.textureData) + { var data = uniform.textureData; // GLTexture = mag linear, min linear_mipmap_linear, wrap repeat + gl.generateMipmap(gl.TEXTURE_2D); @@ -417,14 +445,16 @@ var wrapT = (data.wrapT) ? data.wrapT : gl.CLAMP_TO_EDGE; var format = (data.luminance) ? gl.LUMINANCE : gl.RGBA; - if (data.repeat) { + if (data.repeat) + { wrapS = gl.REPEAT; wrapT = gl.REPEAT; } gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, !!data.flipY); - if (data.width) { + if (data.width) + { var width = (data.width) ? data.width : 512; var height = (data.height) ? data.height : 2; var border = (data.border) ? data.border : 0; @@ -432,7 +462,8 @@ // 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 { + 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); } @@ -448,7 +479,8 @@ * Destroys the shader. * */ -Shader.prototype.destroy = function () { +Shader.prototype.destroy = function () +{ this.gl.deleteProgram(this.program); this.gl = null; @@ -459,13 +491,15 @@ this.fragmentSrc = null; }; -Shader.prototype._glCompile = function (type, src) { +Shader.prototype._glCompile = function (type, src) +{ var shader = this.gl.createShader(type); this.gl.shaderSource(shader, src); this.gl.compileShader(shader); - if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) { + if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) + { window.console.log(this.gl.getShaderInfoLog(shader)); return null; } diff --git a/src/core/renderers/webgl/shaders/StripShader.js b/src/core/renderers/webgl/shaders/StripShader.js index 193f6e1..a7abcc6 100644 --- a/src/core/renderers/webgl/shaders/StripShader.js +++ b/src/core/renderers/webgl/shaders/StripShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function StripShader(gl) { +function StripShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -20,7 +21,8 @@ 'varying vec2 vTextureCoord;', - 'void main(void) {', + '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);', @@ -36,7 +38,8 @@ 'varying vec2 vTextureCoord;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vec2(vTextureCoord.x, vTextureCoord.y)) * alpha;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/utils/FilterTexture.js b/src/core/renderers/webgl/utils/FilterTexture.js index d2c8423..4433d44 100644 --- a/src/core/renderers/webgl/utils/FilterTexture.js +++ b/src/core/renderers/webgl/utils/FilterTexture.js @@ -8,7 +8,8 @@ * @param height {number} the vertical range of the filter * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values */ -function FilterTexture(gl, width, height, scaleMode) { +function FilterTexture(gl, width, height, scaleMode) +{ /** * @member {WebGLContext} */ @@ -59,7 +60,8 @@ * Clears the filter texture. * */ -FilterTexture.prototype.clear = function () { +FilterTexture.prototype.clear = function () +{ var gl = this.gl; gl.clearColor(0,0,0, 0); @@ -72,8 +74,10 @@ * @param width {number} the new width of the texture * @param height {number} the new height of the texture */ -FilterTexture.prototype.resize = function (width, height) { - if (this.width === width && this.height === height) { +FilterTexture.prototype.resize = function (width, height) +{ + if (this.width === width && this.height === height) + { return; } @@ -96,7 +100,8 @@ * Destroys the filter texture. * */ -FilterTexture.prototype.destroy = function () { +FilterTexture.prototype.destroy = function () +{ var gl = this.gl; gl.deleteFramebuffer( this.frameBuffer ); gl.deleteTexture( this.texture ); diff --git a/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js b/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js index c4721e9..a63f4d7 100644 --- a/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js +++ b/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js @@ -14,7 +14,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this sprite batch works for. */ -function WebGLFastSpriteBatch(renderer) { +function WebGLFastSpriteBatch(renderer) +{ /** * The renderer instance this sprite batch operates on. * @@ -91,7 +92,8 @@ */ this.lastIndexCount = 0; - for (var i=0, j=0; i < numIndices; i += 6, j += 4) { + 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; @@ -144,7 +146,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.setupContext(); }); } @@ -157,7 +160,8 @@ * * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLFastSpriteBatch.prototype.setupContext = function () { +WebGLFastSpriteBatch.prototype.setupContext = function () +{ var gl = this.renderer.gl; // create a couple of buffers @@ -177,7 +181,8 @@ /** * @param spriteBatch {SpriteBatch} The SpriteBatch container to prepare for. */ -WebGLFastSpriteBatch.prototype.begin = function (spriteBatch) { +WebGLFastSpriteBatch.prototype.begin = function (spriteBatch) +{ this.shader = this.renderer.shaderManager.fastShader; this.matrix = spriteBatch.worldTransform.toArray(true); @@ -187,33 +192,38 @@ /** */ -WebGLFastSpriteBatch.prototype.end = function () { +WebGLFastSpriteBatch.prototype.end = function () +{ this.flush(); }; /** * @param spriteBatch {SpriteBatch} The SpriteBatch container to render. */ -WebGLFastSpriteBatch.prototype.render = function (spriteBatch) { +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) { + if (!sprite.texture._uvs) + { return; } this.currentBaseTexture = sprite.texture.baseTexture; // check blend mode - if (sprite.blendMode !== this.renderer.blendModeManager.currentBlendMode) { + if (sprite.blendMode !== this.renderer.blendModeManager.currentBlendMode) + { this.flush(); this.renderer.blendModeManager.setBlendMode(sprite.blendMode); } - for (var i=0,j= children.length; i= this.size) { + if (this.currentBatchSize >= this.size) + { this.flush(); } }; @@ -362,29 +379,35 @@ /** * */ -WebGLFastSpriteBatch.prototype.flush = function () { +WebGLFastSpriteBatch.prototype.flush = function () +{ // If the batch is length 0 then return as there is nothing to draw - if (this.currentBatchSize === 0) { + if (this.currentBatchSize === 0) + { return; } var gl = this.renderer.gl; // bind the current texture - if (!this.currentBaseTexture._glTextures[gl.id]) { + if (!this.currentBaseTexture._glTextures[gl.id]) + { this.renderer.updateTexture(this.currentBaseTexture, gl); } //TODO-SHOUD THIS BE ELSE??!?!?! - else { + else + { gl.bindTexture(gl.TEXTURE_2D, this.currentBaseTexture._glTextures[gl.id]); } // upload the verts to the buffer - if (this.currentBatchSize > ( this.size * 0.5 ) ) { + if (this.currentBatchSize > ( this.size * 0.5 ) ) + { gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); } - else { + else + { var view = this.vertices.subarray(0, this.currentBatchSize * this.vertByteSize); gl.bufferSubData(gl.ARRAY_BUFFER, 0, view); @@ -405,14 +428,16 @@ * Ends the batch and flushes * */ -WebGLFastSpriteBatch.prototype.stop = function () { +WebGLFastSpriteBatch.prototype.stop = function () +{ this.flush(); }; /** * */ -WebGLFastSpriteBatch.prototype.start = function () { +WebGLFastSpriteBatch.prototype.start = function () +{ var gl = this.renderer.gl; // bind the main texture diff --git a/src/core/renderers/webgl/utils/WebGLGraphics.js b/src/core/renderers/webgl/utils/WebGLGraphics.js index 55f4911..ab8f46e 100644 --- a/src/core/renderers/webgl/utils/WebGLGraphics.js +++ b/src/core/renderers/webgl/utils/WebGLGraphics.js @@ -19,7 +19,8 @@ * @param graphics {Graphics} * @param renderer {WebGLRenderer} */ -WebGLGraphics.renderGraphics = function (graphics, renderer) {//projection, offset) { +WebGLGraphics.renderGraphics = function (graphics, renderer) {//projection, offset) +{ var gl = renderer.gl; var projection = renderer.projection, @@ -27,7 +28,8 @@ shader = renderer.shaderManager.primitiveShader, webGLData; - if (graphics.dirty) { + if (graphics.dirty) + { WebGLGraphics.updateGraphics(graphics, gl); } @@ -35,8 +37,10 @@ // This could be speeded up for sure! - for (var i = 0; i < webGL.data.length; i++) { - if (webGL.data[i].mode === 1) { + for (var i = 0; i < webGL.data.length; i++) + { + if (webGL.data[i].mode === 1) + { webGLData = webGL.data[i]; renderer.stencilManager.pushStencil(graphics, webGLData, renderer); @@ -46,7 +50,8 @@ renderer.stencilManager.popStencil(graphics, webGLData, renderer); } - else { + else + { webGLData = webGL.data[i]; @@ -84,12 +89,14 @@ * @param graphicsData {Graphics} The graphics object to update * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLGraphics.updateGraphics = function (graphics, gl) { +WebGLGraphics.updateGraphics = function (graphics, gl) +{ // get the contexts graphics object var webGL = graphics._webGL[gl.id]; // if the graphics object does not exist in the webGL context time to create it! - if (!webGL) { + if (!webGL) + { webGL = graphics._webGL[gl.id] = {lastIndex:0, data:[], gl:gl}; } @@ -99,11 +106,13 @@ var i; // if the user cleared the graphics object we will need to clear every object - if (graphics.clearDirty) { + if (graphics.clearDirty) + { graphics.clearDirty = false; // lop through and return all the webGLDatas to the object pool so than can be reused later on - for (i = 0; i < webGL.data.length; i++) { + for (i = 0; i < webGL.data.length; i++) + { var graphicsData = webGL.data[i]; graphicsData.reset(); WebGLGraphics.graphicsDataPool.push( graphicsData ); @@ -119,58 +128,72 @@ // loop through the graphics datas and construct each one.. // if the object is a complex fill then the new stencil buffer technique will be used // other wise graphics objects will be pushed into a batch.. - for (i = webGL.lastIndex; i < graphics.graphicsData.length; i++) { + for (i = webGL.lastIndex; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { // need to add the points the the graphics object.. data.points = data.shape.points.slice(); - if (data.shape.closed) { + if (data.shape.closed) + { // close the poly if the value is true! - if (data.points[0] !== data.points[data.points.length-2] || data.points[1] !== data.points[data.points.length-1]) { + if (data.points[0] !== data.points[data.points.length-2] || data.points[1] !== data.points[data.points.length-1]) + { data.points.push(data.points[0], data.points[1]); } } // MAKE SURE WE HAVE THE CORRECT TYPE.. - if (data.fill) { - if (data.points.length >= 6) { - if (data.points.length < 6 * 2) { + if (data.fill) + { + if (data.points.length >= 6) + { + if (data.points.length < 6 * 2) + { webGLData = WebGLGraphics.switchMode(webGL, 0); var canDrawUsingSimple = WebGLGraphics.buildPoly(data, webGLData); // console.log(canDrawUsingSimple); - if (!canDrawUsingSimple) { + if (!canDrawUsingSimple) + { // console.log("<>>>") webGLData = WebGLGraphics.switchMode(webGL, 1); WebGLGraphics.buildComplexPoly(data, webGLData); } } - else { + else + { webGLData = WebGLGraphics.switchMode(webGL, 1); WebGLGraphics.buildComplexPoly(data, webGLData); } } } - if (data.lineWidth > 0) { + if (data.lineWidth > 0) + { webGLData = WebGLGraphics.switchMode(webGL, 0); WebGLGraphics.buildLine(data, webGLData); } } - else { + else + { webGLData = WebGLGraphics.switchMode(webGL, 0); - if (data.type === CONST.SHAPES.RECT) { + if (data.type === CONST.SHAPES.RECT) + { WebGLGraphics.buildRectangle(data, webGLData); } - else if (data.type === CONST.SHAPES.CIRC || data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.CIRC || data.type === CONST.SHAPES.ELIP) + { WebGLGraphics.buildCircle(data, webGLData); } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { WebGLGraphics.buildRoundedRectangle(data, webGLData); } } @@ -179,10 +202,12 @@ } // upload all the dirty data... - for (i = 0; i < webGL.data.length; i++) { + for (i = 0; i < webGL.data.length; i++) + { webGLData = webGL.data[i]; - if (webGLData.dirty) { + if (webGLData.dirty) + { webGLData.upload(); } } @@ -194,18 +219,22 @@ * @param webGL {WebGLContext} * @param type {number} */ -WebGLGraphics.switchMode = function (webGL, type) { +WebGLGraphics.switchMode = function (webGL, type) +{ var webGLData; - if (!webGL.data.length) { + if (!webGL.data.length) + { webGLData = WebGLGraphics.graphicsDataPool.pop() || new WebGLGraphicsData(webGL.gl); webGLData.mode = type; webGL.data.push(webGLData); } - else { + else + { webGLData = webGL.data[webGL.data.length-1]; - if (webGLData.mode !== type || type === 1) { + if (webGLData.mode !== type || type === 1) + { webGLData = WebGLGraphics.graphicsDataPool.pop() || new WebGLGraphicsData(webGL.gl); webGLData.mode = type; webGL.data.push(webGLData); @@ -225,7 +254,8 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildRectangle = function (graphicsData, webGLData) { +WebGLGraphics.buildRectangle = function (graphicsData, webGLData) +{ // --- // // need to convert points to a nice regular data // @@ -235,7 +265,8 @@ var width = rectData.width; var height = rectData.height; - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -265,7 +296,8 @@ indices.push(vertPos, vertPos, vertPos+1, vertPos+2, vertPos+3, vertPos+3); } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = [x, y, @@ -289,7 +321,8 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildRoundedRectangle = function (graphicsData, webGLData) { +WebGLGraphics.buildRoundedRectangle = function (graphicsData, webGLData) +{ var rrectData = graphicsData.shape; var x = rrectData.x; var y = rrectData.y; @@ -305,7 +338,8 @@ recPoints = recPoints.concat(WebGLGraphics.quadraticBezierCurve(x + width, y + radius, x + width, y, x + width - radius, y)); recPoints = recPoints.concat(WebGLGraphics.quadraticBezierCurve(x + radius, y, x, y, x, y + radius)); - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -323,7 +357,8 @@ // var i = 0; - for (i = 0; i < triangles.length; i+=3) { + for (i = 0; i < triangles.length; i+=3) + { indices.push(triangles[i] + vecPos); indices.push(triangles[i] + vecPos); indices.push(triangles[i+1] + vecPos); @@ -332,12 +367,14 @@ } - for (i = 0; i < recPoints.length; i++) { + for (i = 0; i < recPoints.length; i++) + { verts.push(recPoints[i], recPoints[++i], r, g, b, alpha); } } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = recPoints; @@ -362,7 +399,8 @@ * @param toY {number} Destination point y * @return {number[]} */ -WebGLGraphics.quadraticBezierCurve = function (fromX, fromY, cpX, cpY, toX, toY) { +WebGLGraphics.quadraticBezierCurve = function (fromX, fromY, cpX, cpY, toX, toY) +{ var xa, ya, @@ -373,14 +411,16 @@ n = 20, points = []; - function getPt(n1 , n2, perc) { + function getPt(n1 , n2, perc) + { var diff = n2 - n1; return n1 + ( diff * perc ); } var j = 0; - for (var i = 0; i <= n; i++ ) { + for (var i = 0; i <= n; i++ ) + { j = i / n; // The Green Line @@ -406,7 +446,8 @@ * @param graphicsData {Graphics} The graphics object to draw * @param webGLData {object} */ -WebGLGraphics.buildCircle = function (graphicsData, webGLData) { +WebGLGraphics.buildCircle = function (graphicsData, webGLData) +{ // need to convert points to a nice regular data var circleData = graphicsData.shape; var x = circleData.x; @@ -415,11 +456,13 @@ var height; // TODO - bit hacky?? - if (graphicsData.type === CONST.SHAPES.CIRC) { + if (graphicsData.type === CONST.SHAPES.CIRC) + { width = circleData.radius; height = circleData.radius; } - else { + else + { width = circleData.width; height = circleData.height; } @@ -429,7 +472,8 @@ var i = 0; - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -444,7 +488,8 @@ indices.push(vecPos); - for (i = 0; i < totalSegs + 1 ; i++) { + for (i = 0; i < totalSegs + 1 ; i++) + { verts.push(x,y, r, g, b, alpha); verts.push(x + Math.sin(seg * i) * width, @@ -457,12 +502,14 @@ indices.push(vecPos-1); } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = []; - for (i = 0; i < totalSegs + 1; i++) { + for (i = 0; i < totalSegs + 1; i++) + { graphicsData.points.push(x + Math.sin(seg * i) * width, y + Math.cos(seg * i) * height); } @@ -481,18 +528,22 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildLine = function (graphicsData, webGLData) { +WebGLGraphics.buildLine = function (graphicsData, webGLData) +{ // TODO OPTIMISE! var i = 0; var points = graphicsData.points; - if (points.length === 0) { + if (points.length === 0) + { return; } // if the line width is an odd number add 0.5 to align to a whole pixel - if (graphicsData.lineWidth%2) { - for (i = 0; i < points.length; i++) { + if (graphicsData.lineWidth%2) + { + for (i = 0; i < points.length; i++) + { points[i] += 0.5; } } @@ -502,7 +553,8 @@ var lastPoint = new math.Point(points[points.length - 2], points[points.length - 1]); // if the first point is the last point - gonna have issues :) - if (firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) { + if (firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) + { // need to clone as we are going to slightly modify the shape.. points = points.slice(); @@ -562,7 +614,8 @@ verts.push(p1x + perpx , p1y + perpy, r, g, b, alpha); - for (i = 1; i < length-1; i++) { + for (i = 1; i < length-1; i++) + { p1x = points[(i-1)*2]; p1y = points[(i-1)*2 + 1]; @@ -599,7 +652,8 @@ denom = a1*b2 - a2*b1; - if (Math.abs(denom) < 0.1 ) { + if (Math.abs(denom) < 0.1 ) + { denom+=10.1; verts.push(p2x - perpx , p2y - perpy, @@ -618,7 +672,8 @@ pdist = (px -p2x) * (px -p2x) + (py -p2y) + (py -p2y); - if (pdist > 140 * 140) { + if (pdist > 140 * 140) + { perp3x = perpx - perp2x; perp3y = perpy - perp2y; @@ -639,7 +694,8 @@ indexCount++; } - else { + else + { verts.push(px , py); verts.push(r, g, b, alpha); @@ -672,7 +728,8 @@ indices.push(indexStart); - for (i = 0; i < indexCount; i++) { + for (i = 0; i < indexCount; i++) + { indices.push(indexStart++); } @@ -687,11 +744,13 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildComplexPoly = function (graphicsData, webGLData) { +WebGLGraphics.buildComplexPoly = function (graphicsData, webGLData) +{ //TODO - no need to copy this as it gets turned into a FLoat32Array anyways.. var points = graphicsData.points.slice(); - if (points.length < 6) { + if (points.length < 6) + { return; } @@ -711,7 +770,8 @@ var x,y; // get size.. - for (var i = 0; i < points.length; i+=2) { + for (var i = 0; i < points.length; i+=2) + { x = points[i]; y = points[i+1]; @@ -732,7 +792,8 @@ //TODO - this aint needed! var length = points.length / 2; - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { indices.push( i ); } @@ -746,10 +807,12 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildPoly = function (graphicsData, webGLData) { +WebGLGraphics.buildPoly = function (graphicsData, webGLData) +{ var points = graphicsData.points; - if (points.length < 6) { + if (points.length < 6) + { return; } // get first and last point.. figure out the middle! @@ -767,7 +830,8 @@ var triangles = utils.PolyK.Triangulate(points); - if (!triangles) { + if (!triangles) + { return false; } @@ -775,7 +839,8 @@ var i = 0; - for (i = 0; i < triangles.length; i+=3) { + for (i = 0; i < triangles.length; i+=3) + { indices.push(triangles[i] + vertPos); indices.push(triangles[i] + vertPos); indices.push(triangles[i+1] + vertPos); @@ -783,7 +848,8 @@ indices.push(triangles[i+2] + vertPos); } - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { verts.push(points[i * 2], points[i * 2 + 1], r, g, b, alpha); } diff --git a/src/core/renderers/webgl/utils/WebGLGraphicsData.js b/src/core/renderers/webgl/utils/WebGLGraphicsData.js index c56d05e..c739ba7 100644 --- a/src/core/renderers/webgl/utils/WebGLGraphicsData.js +++ b/src/core/renderers/webgl/utils/WebGLGraphicsData.js @@ -2,7 +2,8 @@ * @class * @private */ -function WebGLGraphicsData(gl) { +function WebGLGraphicsData(gl) +{ this.gl = gl; //TODO does this need to be split before uploding?? @@ -22,7 +23,8 @@ /** * */ -WebGLGraphicsData.prototype.reset = function () { +WebGLGraphicsData.prototype.reset = function () +{ this.points.length = 0; this.indices.length = 0; }; @@ -30,7 +32,8 @@ /** * */ -WebGLGraphicsData.prototype.upload = function () { +WebGLGraphicsData.prototype.upload = function () +{ var gl = this.gl; // this.lastIndex = graphics.graphicsData.length; diff --git a/src/core/renderers/webgl/utils/WebGLSpriteBatch.js b/src/core/renderers/webgl/utils/WebGLSpriteBatch.js index 96eaa52..55befbb 100644 --- a/src/core/renderers/webgl/utils/WebGLSpriteBatch.js +++ b/src/core/renderers/webgl/utils/WebGLSpriteBatch.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this sprite batch works for. */ -function WebGLSpriteBatch(renderer) { +function WebGLSpriteBatch(renderer) +{ /** * * @@ -88,7 +89,8 @@ */ this.lastIndexCount = 0; - for (var i=0, j=0; i < numIndices; i += 6, j += 4) { + 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; @@ -162,7 +164,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.setupContext(); }); } @@ -173,7 +176,8 @@ /** * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLSpriteBatch.prototype.setupContext = function () { +WebGLSpriteBatch.prototype.setupContext = function () +{ var gl = this.renderer.gl; // setup default shader @@ -198,7 +202,8 @@ /** * */ -WebGLSpriteBatch.prototype.begin = function () { +WebGLSpriteBatch.prototype.begin = function () +{ // this.shader = this.renderer.shaderManager.defaultShader; this.start(); @@ -206,19 +211,22 @@ /** */ -WebGLSpriteBatch.prototype.end = function () { +WebGLSpriteBatch.prototype.end = function () +{ this.flush(); }; /** * @param sprite {Sprite} the sprite to render when using this spritebatch */ -WebGLSpriteBatch.prototype.render = function (sprite) { +WebGLSpriteBatch.prototype.render = function (sprite) +{ var texture = sprite.texture; //TODO set blend modes.. // check texture.. - if (this.currentBatchSize >= this.size) { + if (this.currentBatchSize >= this.size) + { this.flush(); this.currentBaseTexture = texture.baseTexture; } @@ -227,7 +235,8 @@ var uvs = texture._uvs; // if the uvs have not updated then no point rendering just yet! - if (!uvs) { + if (!uvs) + { return; } @@ -237,7 +246,8 @@ var w0, w1, h0, h1; - if (texture.trim) { + 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; @@ -248,7 +258,8 @@ h0 = h1 + texture.crop.height; } - else { + else + { w0 = (texture.frame.width ) * (1-aX); w1 = (texture.frame.width ) * -aX; @@ -272,7 +283,8 @@ var colors = this.colors; var positions = this.positions; - if (this.renderer.roundPixels) { + if (this.renderer.roundPixels) + { // xy positions[index] = a * w1 + c * h1 + tx | 0; positions[index+1] = d * h1 + b * w1 + ty | 0; @@ -289,7 +301,8 @@ positions[index+15] = a * w1 + c * h0 + tx | 0; positions[index+16] = d * h0 + b * w1 + ty | 0; } - else { + else + { // xy positions[index] = a * w1 + c * h1 + tx; positions[index+1] = d * h1 + b * w1 + ty; @@ -338,11 +351,13 @@ * * @param sprite {TilingSprite} the tilingSprite to render */ -WebGLSpriteBatch.prototype.renderTilingSprite = function (tilingSprite) { +WebGLSpriteBatch.prototype.renderTilingSprite = function (tilingSprite) +{ var texture = tilingSprite.tilingTexture; // check texture.. - if (this.currentBatchSize >= this.size) { + if (this.currentBatchSize >= this.size) + { //return; this.flush(); this.currentBaseTexture = texture.baseTexture; @@ -351,7 +366,8 @@ // set the textures uvs temporarily // TODO create a separate texture so that we can tile part of a texture - if (!tilingSprite._uvs) { + if (!tilingSprite._uvs) + { tilingSprite._uvs = new TextureUvs(); } @@ -454,16 +470,19 @@ * Renders the content and empties the current batch. * */ -WebGLSpriteBatch.prototype.flush = function () { +WebGLSpriteBatch.prototype.flush = function () +{ // If the batch is length 0 then return as there is nothing to draw - if (this.currentBatchSize === 0) { + if (this.currentBatchSize === 0) + { return; } var gl = this.renderer.gl; var shader; - if (this.dirty) { + if (this.dirty) + { this.dirty = false; // bind the main texture gl.activeTexture(gl.TEXTURE0); @@ -482,10 +501,12 @@ } // upload the verts to the buffer - if (this.currentBatchSize > ( this.size * 0.5 ) ) { + if (this.currentBatchSize > ( this.size * 0.5 ) ) + { gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); } - else { + else + { var view = this.positions.subarray(0, this.currentBatchSize * this.vertByteSize); gl.bufferSubData(gl.ARRAY_BUFFER, 0, view); } @@ -502,7 +523,8 @@ var shaderSwap = false; var sprite; - for (var i = 0, j = this.currentBatchSize; i < j; i++) { + for (var i = 0, j = this.currentBatchSize; i < j; i++) + { sprite = this.sprites[i]; @@ -513,24 +535,28 @@ blendSwap = currentBlendMode !== nextBlendMode; shaderSwap = currentShader !== nextShader; // should I use uuidS??? - if (currentBaseTexture !== nextTexture || blendSwap || shaderSwap) { + if (currentBaseTexture !== nextTexture || blendSwap || shaderSwap) + { this.renderBatch(currentBaseTexture, batchSize, start); start = i; batchSize = 0; currentBaseTexture = nextTexture; - if (blendSwap) { + if (blendSwap) + { currentBlendMode = nextBlendMode; this.renderer.blendModeManager.setBlendMode( currentBlendMode ); } - if (shaderSwap) { + if (shaderSwap) + { currentShader = nextShader; shader = currentShader.shaders ? currentShader.shaders[gl.id] : currentShader; - if (!shader) { + if (!shader) + { shader = new Shader(gl, null, currentShader.fragmentSrc, currentShader.uniforms); currentShader.shaders[gl.id] = shader; } @@ -538,7 +564,8 @@ // set shader function??? this.renderer.shaderManager.setShader(shader); - if (shader.dirty) { + if (shader.dirty) + { shader.syncUniforms(); } @@ -569,17 +596,21 @@ * @param size {number} * @param startIndex {number} */ -WebGLSpriteBatch.prototype.renderBatch = function (texture, size, startIndex) { - if (size === 0) { +WebGLSpriteBatch.prototype.renderBatch = function (texture, size, startIndex) +{ + if (size === 0) + { return; } var gl = this.renderer.gl; - if (!texture._glTextures[gl.id]) { + if (!texture._glTextures[gl.id]) + { this.renderer.updateTexture(texture); } - else { + else + { // bind the current texture gl.bindTexture(gl.TEXTURE_2D, texture._glTextures[gl.id]); } @@ -594,7 +625,8 @@ /** * */ -WebGLSpriteBatch.prototype.stop = function () { +WebGLSpriteBatch.prototype.stop = function () +{ this.flush(); this.dirty = true; }; @@ -602,7 +634,8 @@ /** * */ -WebGLSpriteBatch.prototype.start = function () { +WebGLSpriteBatch.prototype.start = function () +{ this.dirty = true; }; @@ -610,7 +643,8 @@ * Destroys the SpriteBatch. * */ -WebGLSpriteBatch.prototype.destroy = function () { +WebGLSpriteBatch.prototype.destroy = function () +{ this.renderer.gl.deleteBuffer(this.vertexBuffer); this.renderer.gl.deleteBuffer(this.indexBuffer); diff --git a/src/core/textures/BaseTexture.js b/src/core/textures/BaseTexture.js index 2bf77d4..513d358 100644 --- a/src/core/textures/BaseTexture.js +++ b/src/core/textures/BaseTexture.js @@ -10,7 +10,8 @@ * @param source {Image|Canvas} the source object of the texture. * @param [scaleMode=scaleModes.DEFAULT] {number} See {@link scaleModes} for possible values */ -function BaseTexture(source, scaleMode) { +function BaseTexture(source, scaleMode) +{ this.uuid = utils.uuid(); /** @@ -123,7 +124,8 @@ this._needsUpdate = false; // if no source passed don't try to load - if (source) { + if (source) + { this.loadSource(source); } @@ -149,13 +151,16 @@ Object.defineProperties(BaseTexture.prototype, { needsUpdate: { - get: function () { + get: function () + { return this._needsUpdate; }, - set: function (val) { + set: function (val) + { this._needsUpdate = val; - if (val) { + if (val) + { this.emit('update', this); } } @@ -171,9 +176,11 @@ * * The logic state after calling `loadSource` directly or indirectly (eg. `fromImage`, `new BaseTexture`) is: * - * if (texture.hasLoaded) { + * if (texture.hasLoaded) + { * // texture ready for use - * } else if (texture.isLoading) { + * } else if (texture.isLoading) + { * // listen to 'loaded' and/or 'error' events on texture * } else { * // not loading, not going to load UNLESS the source is reloaded @@ -183,12 +190,14 @@ * @protected * @param source {Image|Canvas} the source object of the texture. */ -BaseTexture.prototype.loadSource = function (source) { +BaseTexture.prototype.loadSource = function (source) +{ var wasLoading = this.isLoading; this.hasLoaded = false; this.isLoading = false; - if (wasLoading && this.source) { + if (wasLoading && this.source) + { this.source.onload = null; this.source.onerror = null; } @@ -196,20 +205,24 @@ this.source = source; // Apply source if loaded. Otherwise setup appropriate loading monitors. - if ((this.source.complete || this.source.getContext) && this.source.width && this.source.height) { + if ((this.source.complete || this.source.getContext) && this.source.width && this.source.height) + { this._sourceLoaded(); } - else if(!source.getContext) { + else if(!source.getContext) + { // Image fail / not ready this.isLoading = true; var scope = this; - source.onload = function () { + source.onload = function () + { source.onload = null; source.onerror = null; - if(!scope.isLoading) { + if(!scope.isLoading) + { return; } @@ -219,11 +232,13 @@ scope.emit('loaded', scope); }; - source.onerror = function () { + source.onerror = function () + { source.onload = null; source.onerror = null; - if(!scope.isLoading) { + if(!scope.isLoading) + { return; } @@ -234,24 +249,29 @@ // Per http://www.w3.org/TR/html5/embedded-content-0.html#the-img-element // "The value of `complete` can thus change while a script is executing." // So complete needs to be re-checked after the callbacks have been added.. - if (source.complete) { + if (source.complete) + { this.isLoading = false; // ..and if we're complete now, no need for callbacks source.onload = null; source.onerror = null; - if (source.width && source.height) { + if (source.width && source.height) + { this._sourceLoaded(); // If any previous subscribers possible - if (wasLoading) { + if (wasLoading) + { this.emit('loaded', this); } } - else { + else + { // If any previous subscribers possible - if (wasLoading) { + if (wasLoading) + { this.emit('error', this); } } @@ -265,7 +285,8 @@ * * @private */ -BaseTexture.prototype._sourceLoaded = function () { +BaseTexture.prototype._sourceLoaded = function () +{ this.hasLoaded = true; this.width = this.source.naturalWidth || this.source.width; @@ -278,16 +299,20 @@ * Destroys this base texture * */ -BaseTexture.prototype.destroy = function () { - if (this.imageUrl) { +BaseTexture.prototype.destroy = function () +{ + if (this.imageUrl) + { delete utils.BaseTextureCache[this.imageUrl]; delete utils.TextureCache[this.imageUrl]; this.imageUrl = null; - if (!navigator.isCocoonJS) { + if (!navigator.isCocoonJS) + { this.source.src = ''; } } - else if (this.source && this.source._pixiId) { + else if (this.source && this.source._pixiId) + { delete utils.BaseTextureCache[this.source._pixiId]; } this.source = null; @@ -301,7 +326,8 @@ * memory again. * */ -BaseTexture.prototype.dispose = function () { +BaseTexture.prototype.dispose = function () +{ this.emit('dispose', this); }; @@ -311,7 +337,8 @@ * * @param newSrc {string} the path of the image */ -BaseTexture.prototype.updateSourceImage = function (newSrc) { +BaseTexture.prototype.updateSourceImage = function (newSrc) +{ this.source.src = newSrc; this.loadSource(this.source); }; @@ -326,18 +353,22 @@ * @param [scaleMode=scaleModes.DEFAULT] {number} See {@link scaleModes} for possible values * @return BaseTexture */ -BaseTexture.fromImage = function (imageUrl, crossorigin, scaleMode) { +BaseTexture.fromImage = function (imageUrl, crossorigin, scaleMode) +{ var baseTexture = utils.BaseTextureCache[imageUrl]; - if (crossorigin === undefined && imageUrl.indexOf('data:') !== 0) { + if (crossorigin === undefined && imageUrl.indexOf('data:') !== 0) + { crossorigin = true; } - if (!baseTexture) { + if (!baseTexture) + { // new Image() breaks tex loading in some versions of Chrome. // See https://code.google.com/p/chromium/issues/detail?id=238071 var image = new Image();//document.createElement('img'); - if (crossorigin) { + if (crossorigin) + { image.crossOrigin = ''; } @@ -347,7 +378,8 @@ utils.BaseTextureCache[imageUrl] = baseTexture; // if there is an @2x at the end of the url we are going to assume its a highres image - if ( imageUrl.indexOf(CONST.RETINA_PREFIX + '.') !== -1) { + if ( imageUrl.indexOf(CONST.RETINA_PREFIX + '.') !== -1) + { baseTexture.resolution = 2; } } @@ -363,14 +395,17 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return BaseTexture */ -BaseTexture.fromCanvas = function (canvas, scaleMode) { - if (!canvas._pixiId) { +BaseTexture.fromCanvas = function (canvas, scaleMode) +{ + if (!canvas._pixiId) + { canvas._pixiId = 'canvas_' + utils.uuid(); } var baseTexture = utils.BaseTextureCache[canvas._pixiId]; - if (!baseTexture) { + if (!baseTexture) + { baseTexture = new BaseTexture(canvas, scaleMode); utils.BaseTextureCache[canvas._pixiId] = baseTexture; } diff --git a/src/core/textures/RenderTexture.js b/src/core/textures/RenderTexture.js index 6dad20f..53ae796 100644 --- a/src/core/textures/RenderTexture.js +++ b/src/core/textures/RenderTexture.js @@ -46,8 +46,10 @@ * @param [scaleMode] {number} See {@link scaleModes} for possible values * @param [resolution=1] {number} The resolution of the texture being generated */ -function RenderTexture(renderer, width, height, scaleMode, resolution) { - if (!renderer) { +function RenderTexture(renderer, width, height, scaleMode, resolution) +{ + if (!renderer) + { throw new Error('Unable to create RenderTexture, you must pass a renderer into the constructor.'); } @@ -133,7 +135,8 @@ */ this.renderer = renderer; - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { var gl = this.renderer.gl; this.textureBuffer = new FilterTexture(gl, this.width * this.resolution, this.height * this.resolution, this.baseTexture.scaleMode); @@ -142,7 +145,8 @@ this.render = this.renderWebGL; this.projection = new math.Point(this.width*0.5, -this.height*0.5); } - else { + else + { this.render = this.renderCanvas; this.textureBuffer = new CanvasBuffer(this.width* this.resolution, this.height* this.resolution); this.baseTexture.source = this.textureBuffer.canvas; @@ -167,8 +171,10 @@ * @param height {number} The height to resize to. * @param updateBase {boolean} Should the baseTexture.width and height values be resized as well? */ -RenderTexture.prototype.resize = function (width, height, updateBase) { - if (width === this.width && height === this.height) { +RenderTexture.prototype.resize = function (width, height, updateBase) +{ + if (width === this.width && height === this.height) + { return; } @@ -177,17 +183,20 @@ this.width = this.frame.width = this.crop.width = width; this.height = this.frame.height = this.crop.height = height; - if (updateBase) { + if (updateBase) + { this.baseTexture.width = this.width; this.baseTexture.height = this.height; } - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { this.projection.x = this.width / 2; this.projection.y = -this.height / 2; } - if (!this.valid) { + if (!this.valid) + { return; } @@ -198,12 +207,15 @@ * Clears the RenderTexture. * */ -RenderTexture.prototype.clear = function () { - if (!this.valid) { +RenderTexture.prototype.clear = function () +{ + if (!this.valid) + { return; } - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { this.renderer.gl.bindFramebuffer(this.renderer.gl.FRAMEBUFFER, this.textureBuffer.frameBuffer); } @@ -220,19 +232,23 @@ * @param [restoreWorldTransform=true] {boolean} If true the displayObject's worldTransform/worldAlpha and all children * transformations will be restored. Not restoring this information will be a little faster. */ -RenderTexture.prototype.renderWebGL = function (displayObject, matrix, clear, restoreWorldTransform) { - if (!this.valid) { +RenderTexture.prototype.renderWebGL = function (displayObject, matrix, clear, restoreWorldTransform) +{ + if (!this.valid) + { return; } - if (typeof restoreWorldTransform === 'undefined') { + if (typeof restoreWorldTransform === 'undefined') + { restoreWorldTransform = true; } var tempAlpha, tempTransform; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { tempAlpha = displayObject.worldAlpha; tempTransform = displayObject.worldTransform.toArray(); } @@ -245,7 +261,8 @@ wt.identity(); wt.translate(0, this.projection.y * 2); - if (matrix) { + if (matrix) + { wt.append(matrix); } @@ -258,7 +275,8 @@ var children = displayObject.children; var i, j; - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } @@ -269,7 +287,8 @@ gl.bindFramebuffer(gl.FRAMEBUFFER, this.textureBuffer.frameBuffer ); - if (clear) { + if (clear) + { this.textureBuffer.clear(); } @@ -279,11 +298,13 @@ this.renderer.spriteBatch.dirty = true; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { displayObject.worldAlpha = tempAlpha; displayObject.worldTransform.fromArray(tempTransform); - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } } @@ -300,26 +321,31 @@ * @param [restoreWorldTransform=true] {boolean} If true the displayObject's worldTransform/worldAlpha and all children * transformations will be restored. Not restoring this information will be a little faster. */ -RenderTexture.prototype.renderCanvas = function (displayObject, matrix, clear, restoreWorldTransform) { - if (!this.valid) { +RenderTexture.prototype.renderCanvas = function (displayObject, matrix, clear, restoreWorldTransform) +{ + if (!this.valid) + { return; } - if (typeof restoreWorldTransform === 'undefined') { + if (typeof restoreWorldTransform === 'undefined') + { restoreWorldTransform = true; } var tempAlpha, tempTransform; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { tempAlpha = displayObject.worldAlpha; tempTransform = displayObject.worldTransform.toArray(); } var wt = displayObject.worldTransform; wt.identity(); - if (matrix) { + if (matrix) + { wt.append(matrix); } @@ -330,11 +356,13 @@ var children = displayObject.children; var i, j; - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } - if (clear) { + if (clear) + { this.textureBuffer.clear(); } @@ -348,11 +376,13 @@ this.renderer.resolution = realResolution; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { displayObject.worldAlpha = tempAlpha; displayObject.worldTransform.fromArray(tempTransform); - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } } @@ -363,7 +393,8 @@ * * @return {Image} */ -RenderTexture.prototype.getImage = function () { +RenderTexture.prototype.getImage = function () +{ var image = new Image(); image.src = this.getBase64(); return image; @@ -374,7 +405,8 @@ * * @return {string} A base64 encoded string of the texture. */ -RenderTexture.prototype.getBase64 = function () { +RenderTexture.prototype.getBase64 = function () +{ return this.getCanvas().toDataURL(); }; @@ -383,8 +415,10 @@ * * @return {HTMLCanvasElement} A Canvas element with the texture rendered on. */ -RenderTexture.prototype.getCanvas = function () { - if (this.renderer.type === CONST.WEBGL_RENDERER) { +RenderTexture.prototype.getCanvas = function () +{ + if (this.renderer.type === CONST.WEBGL_RENDERER) + { var gl = this.renderer.gl; var width = this.textureBuffer.width; var height = this.textureBuffer.height; @@ -403,7 +437,8 @@ return tempCanvas.canvas; } - else { + else + { return this.textureBuffer.canvas; } }; diff --git a/src/core/textures/Texture.js b/src/core/textures/Texture.js index 3c65909..e97f0aa 100644 --- a/src/core/textures/Texture.js +++ b/src/core/textures/Texture.js @@ -17,7 +17,8 @@ * @param [crop] {Rectangle} The area of original texture * @param [trim] {Rectangle} Trimmed texture rectangle */ -function Texture(baseTexture, frame, crop, trim) { +function Texture(baseTexture, frame, crop, trim) +{ /** * Does this Texture have any frame data assigned to it? * @@ -25,12 +26,14 @@ */ this.noFrame = false; - if (!frame) { + if (!frame) + { this.noFrame = true; frame = new math.Rectangle(0, 0, 1, 1); } - if (baseTexture instanceof Texture) { + if (baseTexture instanceof Texture) + { baseTexture = baseTexture.baseTexture; } @@ -100,13 +103,16 @@ */ this.crop = crop || new math.Rectangle(0, 0, 1, 1); - if (baseTexture.hasLoaded) { - if (this.noFrame) { + if (baseTexture.hasLoaded) + { + if (this.noFrame) + { frame = new math.Rectangle(0, 0, baseTexture.width, baseTexture.height); } this.frame = frame; } - else { + else + { baseTexture.addEventListener('loaded', this.onBaseTextureLoaded.bind(this)); } } @@ -118,19 +124,23 @@ Object.defineProperties(Texture.prototype, { needsUpdate: { - get: function () { + get: function () + { return this.baseTexture.needsUpdate; }, - set: function (val) { + set: function (val) + { this.baseTexture.needsUpdate = val; } }, frame: { - get: function () { + get: function () + { return this._frame; }, - set: function (frame) { + set: function (frame) + { this._frame = frame; this.noFrame = false; @@ -143,20 +153,23 @@ 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 (!this.trim && (frame.x + frame.width > this.baseTexture.width || frame.y + frame.height > this.baseTexture.height)) + { throw new Error('Texture Error: frame does not fit inside the base Texture dimensions ' + this); } this.valid = frame && frame.width && frame.height && this.baseTexture.source && this.baseTexture.hasLoaded; - if (this.trim) { + 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) { + if (this.valid) + { this._updateUvs(); } } @@ -168,11 +181,13 @@ * * @private */ -Texture.prototype.onBaseTextureLoaded = function () { +Texture.prototype.onBaseTextureLoaded = function () +{ var baseTexture = this.baseTexture; baseTexture.removeEventListener('loaded', this.onLoaded); - if (this.noFrame) { + if (this.noFrame) + { this.frame = new math.Rectangle(0, 0, baseTexture.width, baseTexture.height); } @@ -184,8 +199,10 @@ * * @param destroyBase {boolean} Whether to destroy the base texture as well */ -Texture.prototype.destroy = function (destroyBase) { - if (destroyBase) { +Texture.prototype.destroy = function (destroyBase) +{ + if (destroyBase) + { this.baseTexture.destroy(); } @@ -197,8 +214,10 @@ * * @private */ -Texture.prototype._updateUvs = function () { - if (!this._uvs) { +Texture.prototype._updateUvs = function () +{ + if (!this._uvs) + { this._uvs = new TextureUvs(); } @@ -229,10 +248,12 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return Texture */ -Texture.fromImage = function (imageUrl, crossorigin, scaleMode) { +Texture.fromImage = function (imageUrl, crossorigin, scaleMode) +{ var texture = utils.TextureCache[imageUrl]; - if (!texture) { + if (!texture) + { texture = new Texture(BaseTexture.fromImage(imageUrl, crossorigin, scaleMode)); utils.TextureCache[imageUrl] = texture; } @@ -248,9 +269,11 @@ * @param frameId {string} The frame id of the texture * @return Texture */ -Texture.fromFrame = function (frameId) { +Texture.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache '); } return texture; @@ -264,7 +287,8 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return {Texture} */ -Texture.fromCanvas = function (canvas, scaleMode) { +Texture.fromCanvas = function (canvas, scaleMode) +{ return new Texture(BaseTexture.fromCanvas(canvas, scaleMode)); }; @@ -276,7 +300,8 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return {Texture} A Texture */ -Texture.fromVideo = function (video, scaleMode) { +Texture.fromVideo = function (video, scaleMode) +{ return new Texture(VideoBaseTexture.baseTextureFromVideo(video, scaleMode)); }; @@ -287,7 +312,8 @@ * @param texture {Texture} The Texture to add to the cache. * @param id {string} The id that the texture will be stored against. */ -Texture.addTextureToCache = function (texture, id) { +Texture.addTextureToCache = function (texture, id) +{ utils.TextureCache[id] = texture; }; @@ -298,7 +324,8 @@ * @param id {string} The id of the texture to be removed * @return {Texture} The texture that was removed */ -Texture.removeTextureFromCache = function (id) { +Texture.removeTextureFromCache = function (id) +{ var texture = utils.TextureCache[id]; delete utils.TextureCache[id]; diff --git a/src/core/textures/TextureUvs.js b/src/core/textures/TextureUvs.js index b9bbb58..5424d52 100644 --- a/src/core/textures/TextureUvs.js +++ b/src/core/textures/TextureUvs.js @@ -1,4 +1,5 @@ -function TextureUvs() { +function TextureUvs() +{ this.x0 = 0; this.y0 = 0; diff --git a/src/core/textures/VideoBaseTexture.js b/src/core/textures/VideoBaseTexture.js index e3e0c5a..1a826a9 100644 --- a/src/core/textures/VideoBaseTexture.js +++ b/src/core/textures/VideoBaseTexture.js @@ -12,15 +12,18 @@ * @param source {HTMLVideoElement} * @param [scaleMode] {number} See {@link scaleModes} for possible values */ -function VideoBaseTexture(source, scaleMode) { - if (!source){ +function VideoBaseTexture(source, scaleMode) +{ + if (!source) + { throw new Error('No video source element specified.'); } // hook in here to check if video is already available. // BaseTexture looks for a source.complete boolean, plus width & height. - if ((source.readyState === source.HAVE_ENOUGH_DATA || source.readyState === source.HAVE_FUTURE_DATA) && source.width && source.height) { + if ((source.readyState === source.HAVE_ENOUGH_DATA || source.readyState === source.HAVE_FUTURE_DATA) && source.width && source.height) + { source.complete = true; } @@ -31,7 +34,8 @@ this._boundOnUpdate = this._onUpdate.bind(this); this._boundOnCanPlay = this._onCanPlay.bind(this); - if (!source.complete) { + if (!source.complete) + { source.addEventListener('canplay', this._boundOnCanPlay); source.addEventListener('canplaythrough', this._boundOnCanPlay); @@ -47,28 +51,35 @@ VideoBaseTexture.prototype.constructor = VideoBaseTexture; module.exports = VideoBaseTexture; -VideoBaseTexture.prototype._onUpdate = function () { - if (this.autoUpdate) { +VideoBaseTexture.prototype._onUpdate = function () +{ + if (this.autoUpdate) + { window.requestAnimationFrame(this._boundOnUpdate); this.needsUpdate = true; } }; -VideoBaseTexture.prototype._onPlayStart = function () { - if (!this.autoUpdate) { +VideoBaseTexture.prototype._onPlayStart = function () +{ + if (!this.autoUpdate) + { window.requestAnimationFrame(this._boundOnUpdate); this.autoUpdate = true; } }; -VideoBaseTexture.prototype._onPlayStop = function () { +VideoBaseTexture.prototype._onPlayStop = function () +{ this.autoUpdate = false; }; -VideoBaseTexture.prototype._onCanPlay = function () { +VideoBaseTexture.prototype._onCanPlay = function () +{ this.hasLoaded = true; - if (this.source) { + if (this.source) + { this.source.removeEventListener('canplay', this._boundOnCanPlay); this.source.removeEventListener('canplaythrough', this._boundOnCanPlay); @@ -78,15 +89,18 @@ this.source.play(); // prevent multiple loaded dispatches.. - if(!this.__loaded){ + if(!this.__loaded) + { this.__loaded = true; this.emit('loaded', this); } } }; -VideoBaseTexture.prototype.destroy = function () { - if (this.source && this.source._pixiId) { +VideoBaseTexture.prototype.destroy = function () +{ + if (this.source && this.source._pixiId) + { utils.BaseTextureCache[ this.source._pixiId ] = null; delete utils.BaseTextureCache[ this.source._pixiId ]; @@ -105,14 +119,17 @@ * @param scaleMode {number} See {@link scaleModes} for possible values * @return {VideoBaseTexture} */ -VideoBaseTexture.fromVideo = function (video, scaleMode) { - if (!video._pixiId) { +VideoBaseTexture.fromVideo = function (video, scaleMode) +{ + if (!video._pixiId) + { video._pixiId = 'video_' + utils.uuid(); } var baseTexture = utils.BaseTextureCache[video._pixiId]; - if (!baseTexture) { + if (!baseTexture) + { baseTexture = new VideoBaseTexture(video, scaleMode); utils.BaseTextureCache[ video._pixiId ] = baseTexture; } @@ -147,17 +164,21 @@ * @param scaleMode {number} See {@link scaleModes} for possible values * @return {VideoBaseTexture} */ -VideoBaseTexture.fromUrl = function (videoSrc, scaleMode) { +VideoBaseTexture.fromUrl = function (videoSrc, scaleMode) +{ var video = document.createElement('video'); // array of objects or strings - if (Array.isArray(videoSrc)) { - for (var i = 0; i < videoSrc.length; ++i) { + if (Array.isArray(videoSrc)) + { + for (var i = 0; i < videoSrc.length; ++i) + { video.appendChild(createSource(videoSrc.src || videoSrc, videoSrc.mime)); } } // single object or string - else { + else + { video.appendChild(createSource(videoSrc.src || videoSrc, videoSrc.mime)); } @@ -169,8 +190,10 @@ VideoBaseTexture.fromUrls = VideoBaseTexture.fromUrl; -function createSource(path, type) { - if (!type) { +function createSource(path, type) +{ + if (!type) + { type = 'video/' + path.substr(path.lastIndexOf('.') + 1); } diff --git a/src/core/utils/EventData.js b/src/core/utils/EventData.js index 5d55a22..8cdf701 100644 --- a/src/core/utils/EventData.js +++ b/src/core/utils/EventData.js @@ -7,7 +7,8 @@ * @param name {string} The string name of the event that was triggered * @param data {object} Arbitrary event data to pass along */ -function EventData(target, name, data) { +function EventData(target, name, data) +{ // for duck typing in the ".on()" function this.__isEventObject = true; @@ -71,7 +72,8 @@ * Stops the propagation of events up the scene graph (prevents bubbling). * */ -EventData.prototype.stopPropagation = function stopPropagation() { +EventData.prototype.stopPropagation = function stopPropagation() +{ this.stopped = true; }; @@ -79,6 +81,7 @@ * Stops the propagation of events to sibling listeners (no longer calls any listeners). * */ -EventData.prototype.stopImmediatePropagation = function stopImmediatePropagation() { +EventData.prototype.stopImmediatePropagation = function stopImmediatePropagation() +{ this.stoppedImmediate = true; }; diff --git a/src/core/utils/EventTarget.js b/src/core/utils/EventTarget.js index 7ae8820..671a151 100644 --- a/src/core/utils/EventTarget.js +++ b/src/core/utils/EventTarget.js @@ -13,14 +13,16 @@ * var em = new MyEmitter(); * em.emit('eventName', 'some data', 'some more data', {}, null, ...); */ -function eventTarget(obj) { +function eventTarget(obj) +{ /** * Return a list of assigned event listeners. * * @param eventName {string} The events that should be listed. * @return {Array} An array of listener functions */ - obj.listeners = function listeners(eventName) { + obj.listeners = function listeners(eventName) + { this._listeners = this._listeners || {}; return this._listeners[eventName] ? this._listeners[eventName].slice() : []; @@ -33,22 +35,26 @@ * @param eventName {string} The name of the event. * @return {boolean} Indication if we've emitted an event. */ - obj.emit = obj.dispatchEvent = function emit(eventName, data) { + obj.emit = obj.dispatchEvent = function emit(eventName, data) + { this._listeners = this._listeners || {}; // fast return when there are no listeners - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return; } //backwards compat with old method ".emit({ type: 'something' })" - if (typeof eventName === 'object') { + if (typeof eventName === 'object') + { data = eventName; eventName = eventName.type; } //ensure we are using a real pixi event - if (!data || data.__isEventObject !== true) { + if (!data || data.__isEventObject !== true) + { data = new EventData(this, eventName, data); } @@ -58,23 +64,27 @@ fn = listeners[0], i; - for (i = 0; i < length; fn = listeners[++i]) { + for (i = 0; i < length; fn = listeners[++i]) + { //call the event listener fn.call(this, data); //if "stopImmediatePropagation" is called, stop calling sibling events - if (data.stoppedImmediate) { + if (data.stoppedImmediate) + { return this; } } //if "stopPropagation" is called then don't bubble the event - if (data.stopped) { + if (data.stopped) + { return this; } //bubble this event up the scene graph - if (this.parent && this.parent.emit) { + if (this.parent && this.parent.emit) + { this.parent.emit.call(this.parent, eventName, data); } @@ -88,7 +98,8 @@ * @param eventName {string} Name of the event. * @param callback {Functon} fn Callback function. */ - obj.on = obj.addEventListener = function on(eventName, fn) { + obj.on = obj.addEventListener = function on(eventName, fn) + { this._listeners = this._listeners || {}; (this._listeners[eventName] = this._listeners[eventName] || []) @@ -103,11 +114,13 @@ * @param eventName {string} Name of the event. * @param callback {Function} Callback function. */ - obj.once = function once(eventName, fn) { + obj.once = function once(eventName, fn) + { this._listeners = this._listeners || {}; var self = this; - function onceHandlerWrapper() { + function onceHandlerWrapper() + { fn.apply(self.off(eventName, onceHandlerWrapper), arguments); } onceHandlerWrapper._originalHandler = fn; @@ -122,23 +135,28 @@ * @param eventName {string} The event we want to remove. * @param callback {Function} The listener that we need to find. */ - obj.off = obj.removeEventListener = function off(eventName, fn) { + obj.off = obj.removeEventListener = function off(eventName, fn) + { this._listeners = this._listeners || {}; - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return this; } var list = this._listeners[eventName], i = fn ? list.length : 0; - while(i-- > 0) { - if (list[i] === fn || list[i]._originalHandler === fn) { + while(i-- > 0) + { + if (list[i] === fn || list[i]._originalHandler === fn) + { list.splice(i, 1); } } - if (list.length === 0) { + if (list.length === 0) + { delete this._listeners[eventName]; } @@ -150,10 +168,12 @@ * * @param eventName {string} The event you want to remove all listeners for. */ - obj.removeAllListeners = function removeAllListeners(eventName) { + obj.removeAllListeners = function removeAllListeners(eventName) + { this._listeners = this._listeners || {}; - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return this; } @@ -169,7 +189,8 @@ * * @param object {object} The obj to mix into */ - mixin: function mixin(obj) { + mixin: function mixin(obj) + { eventTarget(obj); } }; diff --git a/src/core/utils/PolyK.js b/src/core/utils/PolyK.js index 7325141..5e20c2b 100644 --- a/src/core/utils/PolyK.js +++ b/src/core/utils/PolyK.js @@ -47,7 +47,8 @@ * Triangulates shapes for webGL graphic fills. * */ -PolyK.Triangulate = function (p) { +PolyK.Triangulate = function (p) +{ var sign = true; var n = p.length >> 1; @@ -59,7 +60,8 @@ i = 0; var al = n; - while(al > 3) { + while(al > 3) + { var i0 = avl[(i+0)%al]; var i1 = avl[(i+1)%al]; var i2 = avl[(i+2)%al]; @@ -69,29 +71,35 @@ var cx = p[2*i2], cy = p[2*i2+1]; var earFound = false; - if (PolyK._convex(ax, ay, bx, by, cx, cy, sign)) { + if (PolyK._convex(ax, ay, bx, by, cx, cy, sign)) + { earFound = true; - for (var j = 0; j < al; j++) { + for (var j = 0; j < al; j++) + { var vi = avl[j]; if (vi === i0 || vi === i1 || vi === i2) continue; - if (PolyK._PointInTriangle(p[2*vi], p[2*vi+1], ax, ay, bx, by, cx, cy)) { + if (PolyK._PointInTriangle(p[2*vi], p[2*vi+1], ax, ay, bx, by, cx, cy)) + { earFound = false; break; } } } - if (earFound) { + if (earFound) + { tgs.push(i0, i1, i2); avl.splice((i+1)%al, 1); al--; i = 0; } - else if (i++ > 3*al) { + else if (i++ > 3*al) + { // need to flip flip reverse it! // reset! - if (sign) { + if (sign) + { tgs = []; avl = []; for (i = 0; i < n; i++) avl.push(i); @@ -101,7 +109,8 @@ sign = false; } - else { + else + { // window.console.log("PIXI Warning: shape too complex to fill"); return null; } @@ -126,7 +135,8 @@ * @private * @return {boolean} */ -PolyK._PointInTriangle = function (px, py, ax, ay, bx, by, cx, cy) { +PolyK._PointInTriangle = function (px, py, ax, ay, bx, by, cx, cy) +{ var v0x = cx-ax; var v0y = cy-ay; var v1x = bx-ax; @@ -154,6 +164,7 @@ * @private * @return {boolean} */ -PolyK._convex = function (ax, ay, bx, by, cx, cy, sign) { +PolyK._convex = function (ax, ay, bx, by, cx, cy, sign) +{ return ((ay-by)*(cx-bx) + (bx-ax)*(cy-by) >= 0) === sign; }; diff --git a/src/core/utils/index.js b/src/core/utils/index.js index ade9831..bfae7ae 100644 --- a/src/core/utils/index.js +++ b/src/core/utils/index.js @@ -16,7 +16,8 @@ * * @return {number} The next uuid to use. */ - uuid: function () { + uuid: function () + { return ++utils._uid; }, @@ -26,7 +27,8 @@ * @param hex {number} * @return {number[]} An array representing the [R, G, B] of the color. */ - hex2rgb: function (hex, out) { + hex2rgb: function (hex, out) + { out = out || []; out[0] = (hex >> 16 & 0xFF) / 255; @@ -42,7 +44,8 @@ * @param hex {number} * @return {string} The string color. */ - hex2string: function (hex) { + hex2string: function (hex) + { hex = hex.toString(16); hex = '000000'.substr(0, 6 - hex.length) + hex; @@ -55,7 +58,8 @@ * @param rgb {number[]} * @return {number} The color number */ - rgb2hex: function (rgb) { + rgb2hex: function (rgb) + { return ((rgb[0]*255 << 16) + (rgb[1]*255 << 8) + rgb[2]*255); }, @@ -64,8 +68,10 @@ * * @return {boolean} whether they are supported */ - canUseNewCanvasBlendModes: function () { - if (typeof document === 'undefined') { + canUseNewCanvasBlendModes: function () + { + if (typeof document === 'undefined') + { return false; } @@ -93,15 +99,19 @@ * @param number {number} * @return {number} the closest number that is a power of two */ - getNextPowerOfTwo: function (number) { + getNextPowerOfTwo: function (number) + { // see: http://en.wikipedia.org/wiki/Power_of_two#Fast_algorithm_to_check_if_a_positive_number_is_a_power_of_two - if (number > 0 && (number & (number - 1)) === 0) { + if (number > 0 && (number & (number - 1)) === 0) + { return number; } - else { + else + { var result = 1; - while (result < number) { + while (result < number) + { result <<= 1; } @@ -116,7 +126,8 @@ * @param height {number} * @return {boolean} */ - isPowerOfTwo: function (width, height) { + isPowerOfTwo: function (width, height) + { return (width > 0 && (width & (width - 1)) === 0 && height > 0 && (height & (height - 1)) === 0); }, @@ -130,12 +141,15 @@ * @constant * @static */ - sayHello: function (type) { - if (utils._saidHello) { + sayHello: function (type) + { + if (utils._saidHello) + { return; } - if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) { + if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) + { var args = [ '%c %c %c Pixi.js ' + CONST.VERSION + ' - ' + type + ' %c ' + ' %c ' + ' http://www.pixijs.com/ %c %c ♥%c♥%c♥ ', 'background: #ff66a5', @@ -151,7 +165,8 @@ console.log.apply(console, args); //jshint ignore:line } - else if (window.console) { + else if (window.console) + { console.log('Pixi.js ' + CONST.VERSION + ' - ' + type + ' - http://www.pixijs.com/'); //jshint ignore:line } @@ -166,15 +181,19 @@ * @class * @namespace PIXI */ - AjaxRequest: function () { + AjaxRequest: function () + { var activexmodes = ['Msxml2.XMLHTTP.6.0', 'Msxml2.XMLHTTP.3.0', 'Microsoft.XMLHTTP']; //activeX versions to check for in IE - if (window.ActiveXObject) { //Test for support for ActiveXObject in IE first (as XMLHttpRequest in IE7 is broken) - for (var i=0; i= this.textures.length) { + else if (round >= this.textures.length) + { this.gotoAndStop(this.textures.length - 1); - if (this.onComplete) { + if (this.onComplete) + { this.onComplete(); } } @@ -167,10 +182,12 @@ * @static * @param frames {string[]} the array of frames ids the movieclip will use as its texture frames */ -MovieClip.fromFrames = function (frames) { +MovieClip.fromFrames = function (frames) +{ var textures = []; - for (var i = 0; i < frames.length; ++i) { + for (var i = 0; i < frames.length; ++i) + { textures.push(new core.Texture.fromFrame(frames[i])); } @@ -183,10 +200,12 @@ * @static * @param images {string[]} the array of image urls the movieclip will use as its texture frames */ -MovieClip.fromImages = function (images) { +MovieClip.fromImages = function (images) +{ var textures = []; - for (var i = 0; i < images.length; ++i) { + for (var i = 0; i < images.length; ++i) + { textures.push(new core.Texture.fromImage(images[i])); } diff --git a/src/extras/Rope.js b/src/extras/Rope.js index c157ec4..9c87bc0 100644 --- a/src/extras/Rope.js +++ b/src/extras/Rope.js @@ -9,7 +9,8 @@ * @param {Array} points - An array of {Point}. * */ -function Rope(texture, points) { +function Rope(texture, points) +{ Strip.call(this, texture); this.points = points; @@ -31,10 +32,12 @@ * Refreshes * */ -Rope.prototype.refresh = function () { +Rope.prototype.refresh = function () +{ var points = this.points; - if (points.length < 1) { + if (points.length < 1) + { return; } @@ -59,20 +62,23 @@ var total = points.length, point, index, amount; - for (var i = 1; i < total; i++) { + for (var i = 1; i < total; i++) + { point = points[i]; index = i * 4; // time to do some smart drawing! amount = i / (total-1); - if (i%2) { + if (i%2) + { uvs[index] = amount; uvs[index+1] = 0; uvs[index+2] = amount; uvs[index+3] = 1; } - else { + else + { uvs[index] = amount; uvs[index+1] = 0; @@ -95,10 +101,12 @@ * * @private */ -Rope.prototype.updateTransform = function () { +Rope.prototype.updateTransform = function () +{ var points = this.points; - if (points.length < 1) { + if (points.length < 1) + { return; } @@ -113,14 +121,17 @@ var total = points.length, point, index, ratio, perpLength, num; - for (var i = 0; i < total; i++) { + for (var i = 0; i < total; i++) + { point = points[i]; index = i * 4; - if (i < points.length-1) { + if (i < points.length-1) + { nextPoint = points[i+1]; } - else { + else + { nextPoint = point; } @@ -129,7 +140,8 @@ ratio = (1 - (i / (total-1))) * 10; - if (ratio > 1) { + if (ratio > 1) + { ratio = 1; } @@ -157,7 +169,8 @@ * * @param texture {Texture} the texture that will be used */ -Rope.prototype.setTexture = function (texture) { +Rope.prototype.setTexture = function (texture) +{ // stop current texture this.texture = texture; //this.updateFrame = true; diff --git a/src/extras/Strip.js b/src/extras/Strip.js index c5e378f..57691b5 100644 --- a/src/extras/Strip.js +++ b/src/extras/Strip.js @@ -10,7 +10,8 @@ * @param height {number} the height * */ -function Strip(texture) { +function Strip(texture) +{ core.DisplayObjectContainer.call(this); /** @@ -70,9 +71,11 @@ * * @param renderer {WebGLRenderer} */ -Strip.prototype.renderWebGL = function (renderer) { +Strip.prototype.renderWebGL = function (renderer) +{ // if the sprite is not visible or the alpha is 0 then no need to render this element - if (!this.visible || this.alpha <= 0) { + if (!this.visible || this.alpha <= 0) + { return; } @@ -81,7 +84,8 @@ renderer.spriteBatch.stop(); // init! init! - if (!this._vertexBuffer) { + if (!this._vertexBuffer) + { this._initWebGL(renderer); } @@ -96,7 +100,8 @@ //TODO check culling }; -Strip.prototype._initWebGL = function (renderer) { +Strip.prototype._initWebGL = function (renderer) +{ // build the strip! var gl = renderer.gl; @@ -118,7 +123,8 @@ gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this.indices, gl.STATIC_DRAW); }; -Strip.prototype._renderStrip = function (renderer) { +Strip.prototype._renderStrip = function (renderer) +{ var gl = renderer.gl; var projection = renderer.projection, offset = renderer.offset, @@ -137,7 +143,8 @@ gl.uniform2f(shader.offsetVector, -offset.x, -offset.y); gl.uniform1f(shader.alpha, this.worldAlpha); - if (!this.dirty) { + if (!this.dirty) + { gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexBuffer); gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); @@ -150,10 +157,12 @@ gl.activeTexture(gl.TEXTURE0); // check if a texture is dirty.. - if (this.texture.baseTexture._dirty[gl.id]) { + if (this.texture.baseTexture._dirty[gl.id]) + { renderer.updateTexture(this.texture.baseTexture); } - else { + else + { // bind the current texture gl.bindTexture(gl.TEXTURE_2D, this.texture.baseTexture._glTextures[gl.id]); } @@ -163,7 +172,8 @@ } - else { + else + { this.dirty = false; gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexBuffer); @@ -178,10 +188,12 @@ gl.activeTexture(gl.TEXTURE0); // check if a texture is dirty.. - if (this.texture.baseTexture._dirty[gl.id]) { + if (this.texture.baseTexture._dirty[gl.id]) + { renderer.updateTexture(this.texture.baseTexture); } - else { + else + { gl.bindTexture(gl.TEXTURE_2D, this.texture.baseTexture._glTextures[gl.id]); } @@ -203,27 +215,33 @@ * * @param renderer {CanvasRenderer} */ -Strip.prototype.renderCanvas = function (renderer) { +Strip.prototype.renderCanvas = function (renderer) +{ var context = renderer.context; var transform = this.worldTransform; - if (renderer.roundPixels) { + if (renderer.roundPixels) + { context.setTransform(transform.a, transform.b, transform.c, transform.d, transform.tx | 0, transform.ty | 0); } - else { + else + { context.setTransform(transform.a, transform.b, transform.c, transform.d, transform.tx, transform.ty); } - if (this.drawMode === Strip.DrawModes.TRIANGLE_STRIP) { + if (this.drawMode === Strip.DrawModes.TRIANGLE_STRIP) + { this._renderCanvasTriangleStrip(context); } - else { + else + { this._renderCanvasTriangles(context); } }; -Strip.prototype._renderCanvasTriangleStrip = function (context) { +Strip.prototype._renderCanvasTriangleStrip = function (context) +{ // draw triangles!! var vertices = this.vertices; var uvs = this.uvs; @@ -231,14 +249,16 @@ var length = vertices.length / 2; // this.count++; - for (var i = 0; i < length - 2; i++) { + for (var i = 0; i < length - 2; i++) + { // draw some triangles! var index = i * 2; this._renderCanvasDrawTriangle(context, vertices, uvs, index, (index + 2), (index + 4)); } }; -Strip.prototype._renderCanvasTriangles = function (context) { +Strip.prototype._renderCanvasTriangles = function (context) +{ // draw triangles!! var vertices = this.vertices; var uvs = this.uvs; @@ -247,14 +267,16 @@ var length = indices.length; // this.count++; - for (var i = 0; i < length; i += 3) { + for (var i = 0; i < length; i += 3) + { // draw some triangles! var index0 = indices[i] * 2, index1 = indices[i + 1] * 2, index2 = indices[i + 2] * 2; this._renderCanvasDrawTriangle(context, vertices, uvs, index0, index1, index2); } }; -Strip.prototype._renderCanvasDrawTriangle = function (context, vertices, uvs, index0, index1, index2) { +Strip.prototype._renderCanvasDrawTriangle = function (context, vertices, uvs, index0, index1, index2) +{ var textureSource = this.texture.baseTexture.source; var textureWidth = this.texture.width; var textureHeight = this.texture.height; @@ -265,7 +287,8 @@ var u0 = uvs[index0] * textureWidth, u1 = uvs[index1] * textureWidth, u2 = uvs[index2] * textureWidth; var v0 = uvs[index0 + 1] * textureHeight, v1 = uvs[index1 + 1] * textureHeight, v2 = uvs[index2 + 1] * textureHeight; - if (this.canvasPadding > 0) { + if (this.canvasPadding > 0) + { var paddingX = this.canvasPadding / this.worldTransform.a; var paddingY = this.canvasPadding / this.worldTransform.d; var centerX = (x0 + x1 + x2) / 3; @@ -332,7 +355,8 @@ * @param strip {Strip} The Strip to render * @private */ -Strip.prototype.renderStripFlat = function (strip) { +Strip.prototype.renderStripFlat = function (strip) +{ var context = this.context; var vertices = strip.vertices; @@ -340,7 +364,8 @@ // this.count++; context.beginPath(); - for (var i=1; i < length-2; i++) { + for (var i=1; i < length-2; i++) + { // draw some triangles! var index = i*2; @@ -358,7 +383,8 @@ }; /* -Strip.prototype.setTexture = function (texture) { +Strip.prototype.setTexture = function (texture) +{ //TODO SET THE TEXTURES //TODO VISIBILITY @@ -377,7 +403,8 @@ * @private */ -Strip.prototype.onTextureUpdate = function () { +Strip.prototype.onTextureUpdate = function () +{ this.updateFrame = true; }; @@ -387,7 +414,8 @@ * @param matrix {Matrix} the transformation matrix of the sprite * @return {Rectangle} the framing rectangle */ -Strip.prototype.getBounds = function (matrix) { +Strip.prototype.getBounds = function (matrix) +{ var worldTransform = matrix || this.worldTransform; var a = worldTransform.a; @@ -404,7 +432,8 @@ var minY = Infinity; var vertices = this.vertices; - for (var i = 0, n = vertices.length; i < n; i += 2) { + for (var i = 0, n = vertices.length; i < n; i += 2) + { var rawX = vertices[i], rawY = vertices[i + 1]; var x = (a * rawX) + (c * rawY) + tx; var y = (d * rawY) + (b * rawX) + ty; @@ -416,7 +445,8 @@ maxY = y > maxY ? y : maxY; } - if (minX === -Infinity || maxY === Infinity) { + if (minX === -Infinity || maxY === Infinity) + { return core.math.Rectangle.EMPTY; } diff --git a/src/extras/TilingSprite.js b/src/extras/TilingSprite.js index 3ac22df..31da393 100644 --- a/src/extras/TilingSprite.js +++ b/src/extras/TilingSprite.js @@ -10,7 +10,8 @@ * @param width {number} the width of the tiling sprite * @param height {number} the height of the tiling sprite */ -function TilingSprite(texture, width, height) { +function TilingSprite(texture, width, height) +{ core.Sprite.call( this, texture); /** @@ -86,10 +87,12 @@ * @memberof TilingSprite# */ width: { - get: function () { + get: function () + { return this._width; }, - set: function (value) { + set: function (value) + { this._width = value; } }, @@ -101,20 +104,25 @@ * @memberof TilingSprite# */ height: { - get: function () { + get: function () + { return this._height; }, - set: function (value) { + set: function (value) + { this._height = value; } }, texture: { - get: function () { + get: function () + { return this._texture; }, - set: function (value) { - if (this._texture === value) { + set: function (value) + { + if (this._texture === value) + { return; } @@ -130,51 +138,61 @@ * * @param renderer {WebGLRenderer} */ -TilingSprite.prototype.renderWebGL = function (renderer) { - if (!this.visible || this.alpha <= 0) { +TilingSprite.prototype.renderWebGL = function (renderer) +{ + if (!this.visible || this.alpha <= 0) + { return; } var i, j; - if (this._mask) { + if (this._mask) + { renderer.spriteBatch.stop(); renderer.maskManager.pushMask(this.mask, renderer); renderer.spriteBatch.start(); } - if (this._filters) { + if (this._filters) + { renderer.spriteBatch.flush(); renderer.filterManager.pushFilter(this._filterBlock); } - if (!this.tilingTexture || this.refreshTexture) { + if (!this.tilingTexture || this.refreshTexture) + { this.generateTilingTexture(true); - if (this.tilingTexture && this.tilingTexture.needsUpdate) { + if (this.tilingTexture && this.tilingTexture.needsUpdate) + { //TODO - tweaking renderer.updateTexture(this.tilingTexture.baseTexture); this.tilingTexture.needsUpdate = false; // this.tilingTexture._uvs = null; } } - else { + else + { renderer.spriteBatch.renderTilingSprite(this); } // simple render children! - for (i=0,j=this.children.length; i= 0 && index <= this.children.length) { - if (child.parent) { + if (index >= 0 && index <= this.children.length) + { + if (child.parent) + { child.parent.removeChild(child); } @@ -154,7 +173,8 @@ return child; } - else { + else + { throw new Error(child + 'addChildAt: The index '+ index +' supplied is out of bounds ' + this.children.length); } }; @@ -165,15 +185,18 @@ * @param child {DisplayObject} * @param child2 {DisplayObject} */ -DisplayObjectContainer.prototype.swapChildren = function (child, child2) { - if (child === child2) { +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) { + if (index1 < 0 || index2 < 0) + { throw new Error('swapChildren: Both the supplied DisplayObjects must be a child of the caller.'); } @@ -187,10 +210,12 @@ * @param child {DisplayObject} The DisplayObject instance to identify * @return {Number} The index position of the child display object to identify */ -DisplayObjectContainer.prototype.getChildIndex = function (child) { +DisplayObjectContainer.prototype.getChildIndex = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { throw new Error('The supplied DisplayObject must be a child of the caller'); } @@ -203,8 +228,10 @@ * @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 */ -DisplayObjectContainer.prototype.setChildIndex = function (child, index) { - if (index < 0 || index >= this.children.length) { +DisplayObjectContainer.prototype.setChildIndex = function (child, index) +{ + if (index < 0 || index >= this.children.length) + { throw new Error('The supplied index is out of bounds'); } @@ -220,8 +247,10 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child at the given index, if any. */ -DisplayObjectContainer.prototype.getChildAt = function (index) { - if (index < 0 || index >= this.children.length) { +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'); } @@ -234,10 +263,12 @@ * @param child {DisplayObject} The DisplayObject to remove * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChild = function (child) { +DisplayObjectContainer.prototype.removeChild = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { return; } @@ -250,7 +281,8 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChildAt = function (index) { +DisplayObjectContainer.prototype.removeChildAt = function (index) +{ var child = this.getChildAt(index); child.parent = null; @@ -265,24 +297,29 @@ * @param beginIndex {Number} The beginning position. Default value is 0. * @param endIndex {Number} The ending position. Default value is size of the container. */ -DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) { +DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) +{ var begin = beginIndex || 0; var end = typeof endIndex === 'number' ? endIndex : this.children.length; var range = end - begin; - if (range > 0 && range <= end) { + if (range > 0 && range <= end) + { var removed = this.children.splice(begin, range); - for (var i = 0; i < removed.length; ++i) { + for (var i = 0; i < removed.length; ++i) + { removed[i].parent = null; } return removed; } - else if (range === 0 && this.children.length === 0) { + else if (range === 0 && this.children.length === 0) + { return []; } - else { + else + { throw new RangeError('removeChildren: numeric values are outside the acceptable range.'); } }; @@ -291,7 +328,8 @@ * Generates and updates the cached sprite for this object. * */ -DisplayObjectContainer.prototype.updateCachedSprite = function () { +DisplayObjectContainer.prototype.updateCachedSprite = function () +{ this._generateCachedSprite(); }; @@ -304,7 +342,8 @@ * @param renderer {CanvasRenderer|WebGLRenderer} The renderer used to generate the texture. * @return {Texture} a texture of the graphics object */ -DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) { +DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) +{ var bounds = this.getLocalBounds(); var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0, renderer, scaleMode, resolution); @@ -322,18 +361,22 @@ * * @private */ -DisplayObjectContainer.prototype.updateTransform = function () { - if (!this.visible) { +DisplayObjectContainer.prototype.updateTransform = function () +{ + if (!this.visible) + { return; } this.displayObjectUpdateTransform(); - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { return; } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } }; @@ -346,8 +389,10 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getBounds = function () { - if (this.children.length === 0) { +DisplayObjectContainer.prototype.getBounds = function () +{ + if (this.children.length === 0) + { return math.Rectangle.EMPTY; } @@ -365,10 +410,12 @@ var childVisible = false; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -386,7 +433,8 @@ maxY = maxY > childMaxY ? maxY : childMaxY; } - if (!childVisible) { + if (!childVisible) + { return math.Rectangle.EMPTY; } @@ -407,12 +455,14 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getLocalBounds = function () { +DisplayObjectContainer.prototype.getLocalBounds = function () +{ var matrixCache = this.worldTransform; this.worldTransform = math.Matrix.IDENTITY; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } @@ -428,13 +478,16 @@ * * @param renderer {WebGLRenderer} The renderer */ -DisplayObjectContainer.prototype.renderWebGL = function (renderer) { +DisplayObjectContainer.prototype.renderWebGL = function (renderer) +{ // if the object is not visible or the alpha is 0 then no need to render this element - if (!this.visible || this.alpha <= 0) { + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } @@ -442,14 +495,17 @@ var i, j; // do a quick check to see if this element has a mask or a filter. - if (this._mask || this._filters) { + if (this._mask || this._filters) + { // push filter first as we need to ensure the stencil buffer is correct for any masking - if (this._filters) { + if (this._filters) + { renderer.spriteBatch.flush(); renderer.filterManager.pushFilter(this._filterBlock); } - if (this._mask) { + if (this._mask) + { renderer.spriteBatch.stop(); renderer.maskManager.pushMask(this.mask, renderer); renderer.spriteBatch.start(); @@ -459,36 +515,42 @@ this._renderWebGL(renderer); // now loop through the children and make sure they get rendered - for (i = 0, j = this.children.length; i < j; i++) { + for (i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderWebGL(renderer); } // time to stop the sprite batch as either a mask element or a filter draw will happen next renderer.spriteBatch.stop(); - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(this._mask, renderer); } - if (this._filters) { + if (this._filters) + { renderer.filterManager.popFilter(); } renderer.spriteBatch.start(); } - else { + else + { this._renderWebGL(renderer); // simple render children! - for (i = 0, j = this.children.length; i < j; ++i) { + for (i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderWebGL(renderer); } } }; -DisplayObjectContainer.prototype._renderWebGL = function (renderer) { +DisplayObjectContainer.prototype._renderWebGL = function (renderer) +{ // this is where content itself gets renderd.. @@ -499,25 +561,31 @@ * * @param renderer {CanvasRenderer} The renderer */ -DisplayObjectContainer.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0) { +DisplayObjectContainer.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -528,13 +596,16 @@ * @param renderer {WebGLRenderer|CanvasRenderer} The renderer * @private */ -DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) { +DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) +{ this._cachedSprite.worldAlpha = this.worldAlpha; - if (renderer.gl) { + if (renderer.gl) + { this._cachedSprite.renderWebGL(renderer); } - else { + else + { this._cachedSprite.renderCanvas(renderer); } }; @@ -544,10 +615,12 @@ * * @private */ -DisplayObjectContainer.prototype._generateCachedSprite = function () { +DisplayObjectContainer.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { // TODO - RenderTexture now *requires* a renderer instance, so this is like broken // because `renderer` isn't actually in scope here :P var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0); @@ -555,7 +628,8 @@ this._cachedSprite = new Sprite(renderTexture); this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.texture.resize(bounds.width | 0, bounds.height | 0); } @@ -580,8 +654,10 @@ * * @private */ -DisplayObjectContainer.prototype._destroyCachedSprite = function () { - if (!this._cachedSprite) { +DisplayObjectContainer.prototype._destroyCachedSprite = function () +{ + if (!this._cachedSprite) + { return; } diff --git a/src/core/display/Sprite.js b/src/core/display/Sprite.js index 707da24..5862aef 100644 --- a/src/core/display/Sprite.js +++ b/src/core/display/Sprite.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param texture {Texture} The texture for this sprite */ -function Sprite(texture) { +function Sprite(texture) +{ DisplayObjectContainer.call(this); /** @@ -85,12 +86,14 @@ this.texture = texture || Texture.EMPTY; } -Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) { +Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) +{ DisplayObjectContainer.prototype.destroy.call(this); this.anchor = null; - if (destroyTexture) { + if (destroyTexture) + { this._texture.destroy(destroyBaseTexture); } @@ -111,10 +114,12 @@ * @memberof Sprite# */ width: { - get: function () { + get: function () + { return this.scale.x * this.texture.frame.width; }, - set: function (value) { + set: function (value) + { this.scale.x = value / this.texture.frame.width; this._width = value; } @@ -127,10 +132,12 @@ * @memberof Sprite# */ height: { - get: function () { + get: function () + { return this.scale.y * this.texture.frame.height; }, - set: function (value) { + set: function (value) + { this.scale.y = value / this.texture.frame.height; this._height = value; } @@ -143,23 +150,29 @@ * @memberof Sprite# */ texture: { - get: function () { + get: function () + { return this._texture; }, - set: function (value) { - if (this._texture === value) { + set: function (value) + { + if (this._texture === value) + { return; } this._texture = value; this.cachedTint = 0xFFFFFF; - if (value) { + if (value) + { // wait for the texture to load - if (value.baseTexture.hasLoaded) { + if (value.baseTexture.hasLoaded) + { this._onTextureUpdate(); } - else { + else + { value.once('update', this._onTextureUpdate.bind(this)); } } @@ -172,18 +185,22 @@ * * @private */ -Sprite.prototype._onTextureUpdate = function () { +Sprite.prototype._onTextureUpdate = function () +{ // so if _width is 0 then width was not set.. - if (this._width) { + if (this._width) + { this.scale.x = this._width / this.texture.frame.width; } - if (this._height) { + if (this._height) + { this.scale.y = this._height / this.texture.frame.height; } }; -Sprite.prototype._renderWebGL = function (renderer) { +Sprite.prototype._renderWebGL = function (renderer) +{ // this is where content gets renderd.. // watch this space for a little render state manager.. @@ -197,7 +214,8 @@ * @param matrix {Matrix} the transformation matrix of the sprite * @return {Rectangle} the framing rectangle */ -Sprite.prototype.getBounds = function (matrix) { +Sprite.prototype.getBounds = function (matrix) +{ var width = this.texture.frame.width; var height = this.texture.frame.height; @@ -224,11 +242,13 @@ if(b === 0 && c === 0) { // scale may be negative! - if (a < 0) { + if (a < 0) + { a *= -1; } - if (d < 0) { + if (d < 0) + { d *= -1; } @@ -293,28 +313,34 @@ * * @param renderer {CanvasRenderer} The renderer */ -Sprite.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) { +Sprite.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) + { return; } - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; renderer.context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } // Ignore null sources - if (this.texture.valid) { + if (this.texture.valid) + { var resolution = this.texture.baseTexture.resolution / renderer.resolution; renderer.context.globalAlpha = this.worldAlpha; // If smoothingEnabled is supported and we need to change the smoothing property for this texture - if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) { + if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) + { renderer.scaleMode = this.texture.baseTexture.scaleMode; renderer.context[renderer.smoothProperty] = (renderer.scaleMode === CONST.scaleModes.LINEAR); } @@ -324,7 +350,8 @@ var dy = (this.texture.trim ? this.texture.trim.y : 0) - (this.anchor.y * this.texture.trim.height); // Allow for pixel rounding - if (renderer.roundPixels) { + if (renderer.roundPixels) + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -337,7 +364,8 @@ dx = dx | 0; dy = dy | 0; } - else { + else + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -348,8 +376,10 @@ ); } - if (this.tint !== 0xFFFFFF) { - if (this.cachedTint !== this.tint) { + if (this.tint !== 0xFFFFFF) + { + if (this.cachedTint !== this.tint) + { this.cachedTint = this.tint; // TODO clean up caching - how to clean up the caches? @@ -368,7 +398,8 @@ this.texture.crop.height / resolution ); } - else { + else + { renderer.context.drawImage( this.texture.baseTexture.source, this.texture.crop.x, @@ -383,11 +414,13 @@ } } - for (var i = 0, j = this.children.length; i < j; i++) { + for (var i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -402,10 +435,12 @@ * @param frameId {String} The frame Id of the texture in the cache * @return {Sprite} A new Sprite using a texture from the texture cache matching the frameId */ -Sprite.fromFrame = function (frameId) { +Sprite.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache' + this); } @@ -420,6 +455,7 @@ * @param imageId {String} The image url of the texture * @return {Sprite} A new Sprite using a texture from the texture cache matching the image id */ -Sprite.fromImage = function (imageId, crossorigin, scaleMode) { +Sprite.fromImage = function (imageId, crossorigin, scaleMode) +{ return new Sprite(Texture.fromImage(imageId, crossorigin, scaleMode)); }; diff --git a/src/core/display/SpriteBatch.js b/src/core/display/SpriteBatch.js index 3187777..c196fef 100644 --- a/src/core/display/SpriteBatch.js +++ b/src/core/display/SpriteBatch.js @@ -12,7 +12,8 @@ * ```js * var container = new SpriteBatch(); * - * for(var i = 0; i < 100; ++i) { + * for(var i = 0; i < 100; ++i) + * { * var sprite = new PIXI.Sprite.fromImage("myImage.png"); * container.addChild(sprite); * } @@ -25,7 +26,8 @@ */ //TODO RENAME to PARTICLE CONTAINER? -function SpriteBatch() { +function SpriteBatch() +{ DisplayObjectContainer.call(this); } @@ -38,7 +40,8 @@ * * @private */ -SpriteBatch.prototype.updateTransform = function () { +SpriteBatch.prototype.updateTransform = function () +{ // TODO don't need to! this.displayObjectUpdateTransform(); // PIXI.DisplayObjectContainer.prototype.updateTransform.call( this ); @@ -50,8 +53,10 @@ * @param renderer {WebGLRenderer} The webgl renderer * @private */ -SpriteBatch.prototype.renderWebGL = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderWebGL = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -71,8 +76,10 @@ * @param renderer {CanvasRenderer} The canvas renderer * @private */ -SpriteBatch.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -84,10 +91,12 @@ this.displayObjectUpdateTransform(); - for (var i = 0; i < this.children.length; ++i) { + for (var i = 0; i < this.children.length; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -95,9 +104,11 @@ context.globalAlpha = this.worldAlpha * child.alpha; - if (child.rotation % (Math.PI * 2) === 0) { + if (child.rotation % (Math.PI * 2) === 0) + { // this is the fastest way to optimise! - if rotation is 0 then we can avoid any kind of setTransform call - if (isRotated) { + if (isRotated) + { context.setTransform( transform.a, transform.b, @@ -122,8 +133,10 @@ frame.height * child.scale.y ); } - else { - if (!isRotated) { + else + { + if (!isRotated) + { isRotated = true; } @@ -131,7 +144,8 @@ var childTransform = child.worldTransform; - if (renderer.roundPixels) { + if (renderer.roundPixels) + { context.setTransform( childTransform.a, childTransform.b, @@ -141,7 +155,8 @@ childTransform.ty | 0 ); } - else { + else + { context.setTransform( childTransform.a, childTransform.b, diff --git a/src/core/index.js b/src/core/index.js index 3954b6f..eb4a82b 100644 --- a/src/core/index.js +++ b/src/core/index.js @@ -58,11 +58,13 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRenderer: function (width, height, options, noWebGL) { + autoDetectRenderer: function (width, height, options, noWebGL) + { width = width || 800; height = height || 600; - if (!noWebGL && require('webgl-enabled')()) { + if (!noWebGL && require('webgl-enabled')()) + { return new core.WebGLRenderer(width, height, options); } @@ -87,7 +89,8 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRecommendedRenderer: function (width, height, options) { + autoDetectRecommendedRenderer: function (width, height, options) + { var isAndroid = /Android/i.test(navigator.userAgent); return core.autoDetectRenderer(width, height, options, isAndroid); diff --git a/src/core/math/Matrix.js b/src/core/math/Matrix.js index c2f87e2..2ff4848 100644 --- a/src/core/math/Matrix.js +++ b/src/core/math/Matrix.js @@ -10,7 +10,8 @@ * @class * @namespace PIXI */ -function Matrix() { +function Matrix() +{ /** * @member {number} * @default 1 @@ -63,7 +64,8 @@ * * @param array {number[]} The array that the matrix will be populated from. */ -Matrix.prototype.fromArray = function (array) { +Matrix.prototype.fromArray = function (array) +{ this.a = array[0]; this.b = array[1]; this.c = array[3]; @@ -78,14 +80,17 @@ * @param transpose {boolean} Whether we need to transpose the matrix or not * @return {number[]} the newly created array which contains the matrix */ -Matrix.prototype.toArray = function (transpose) { - if (!this.array) { +Matrix.prototype.toArray = function (transpose) +{ + if (!this.array) + { this.array = new Float32Array(9); } var array = this.array; - if (transpose) { + if (transpose) + { array[0] = this.a; array[1] = this.b; array[2] = 0; @@ -96,7 +101,8 @@ array[7] = this.ty; array[8] = 1; } - else { + else + { array[0] = this.a; array[1] = this.c; array[2] = this.tx; @@ -119,7 +125,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, transformed through this matrix */ -Matrix.prototype.apply = function (pos, newPos) { +Matrix.prototype.apply = function (pos, newPos) +{ newPos = newPos || new Point(); newPos.x = this.a * pos.x + this.c * pos.y + this.tx; @@ -136,7 +143,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, inverse-transformed through this matrix */ -Matrix.prototype.applyInverse = function (pos, newPos) { +Matrix.prototype.applyInverse = function (pos, newPos) +{ newPos = newPos || new Point(); var id = 1 / (this.a * this.d + this.c * -this.b); @@ -154,7 +162,8 @@ * @param {number} y * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.translate = function (x, y) { +Matrix.prototype.translate = function (x, y) +{ this.tx += x; this.ty += y; @@ -168,7 +177,8 @@ * @param {number} y The amount to scale vertically * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.scale = function (x, y) { +Matrix.prototype.scale = function (x, y) +{ this.a *= x; this.d *= y; this.c *= x; @@ -186,7 +196,8 @@ * @param {number} angle - The angle in radians. * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.rotate = function (angle) { +Matrix.prototype.rotate = function (angle) +{ var cos = Math.cos( angle ); var sin = Math.sin( angle ); @@ -210,7 +221,8 @@ * @param {Matrix} matrix * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.append = function (matrix) { +Matrix.prototype.append = function (matrix) +{ var a1 = this.a; var b1 = this.b; var c1 = this.c; @@ -232,7 +244,8 @@ * * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.identity = function () { +Matrix.prototype.identity = function () +{ this.a = 1; this.b = 0; this.c = 0; diff --git a/src/core/math/Point.js b/src/core/math/Point.js index 7565b2d..632f346 100644 --- a/src/core/math/Point.js +++ b/src/core/math/Point.js @@ -7,7 +7,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -function Point(x, y) { +function Point(x, y) +{ /** * @member {number} * @default 0 @@ -29,7 +30,8 @@ * * @return {Point} a copy of the point */ -Point.prototype.clone = function () { +Point.prototype.clone = function () +{ return new Point(this.x, this.y); }; @@ -40,7 +42,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -Point.prototype.set = function (x, y) { +Point.prototype.set = function (x, y) +{ this.x = x || 0; this.y = y || ( (y !== 0) ? this.x : 0 ) ; }; diff --git a/src/core/math/shapes/Circle.js b/src/core/math/shapes/Circle.js index 69cfdc9..4d76efc 100644 --- a/src/core/math/shapes/Circle.js +++ b/src/core/math/shapes/Circle.js @@ -10,7 +10,8 @@ * @param y {number} The Y coordinate of the center of this circle * @param radius {number} The radius of the circle */ -function Circle(x, y, radius) { +function Circle(x, y, radius) +{ /** * @member {number} * @default 0 @@ -46,7 +47,8 @@ * @method clone * @return {Circle} a copy of the Circle */ -Circle.prototype.clone = function () { +Circle.prototype.clone = function () +{ return new Circle(this.x, this.y, this.radius); }; @@ -58,8 +60,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Circle */ -Circle.prototype.contains = function (x, y) { - if (this.radius <= 0) { +Circle.prototype.contains = function (x, y) +{ + if (this.radius <= 0) + { return false; } @@ -79,6 +83,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Circle.prototype.getBounds = function () { +Circle.prototype.getBounds = function () +{ return new Rectangle(this.x - this.radius, this.y - this.radius, this.radius * 2, this.radius * 2); }; diff --git a/src/core/math/shapes/Ellipse.js b/src/core/math/shapes/Ellipse.js index 4f2d066..fefd01a 100644 --- a/src/core/math/shapes/Ellipse.js +++ b/src/core/math/shapes/Ellipse.js @@ -11,7 +11,8 @@ * @param width {number} The half width of this ellipse * @param height {number} The half height of this ellipse */ -function Ellipse(x, y, width, height) { +function Ellipse(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -53,7 +54,8 @@ * @method clone * @return {Ellipse} a copy of the ellipse */ -Ellipse.prototype.clone = function () { +Ellipse.prototype.clone = function () +{ return new Ellipse(this.x, this.y, this.width, this.height); }; @@ -65,8 +67,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coords are within this ellipse */ -Ellipse.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Ellipse.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } @@ -86,6 +90,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Ellipse.prototype.getBounds = function () { +Ellipse.prototype.getBounds = function () +{ return new Rectangle(this.x - this.width, this.y - this.height, this.width, this.height); }; diff --git a/src/core/math/shapes/Polygon.js b/src/core/math/shapes/Polygon.js index ae89148..fea6d37 100644 --- a/src/core/math/shapes/Polygon.js +++ b/src/core/math/shapes/Polygon.js @@ -10,16 +10,20 @@ * arguments passed can be flat x,y values e.g. `new Polygon(x,y, x,y, x,y, ...)` where `x` and `y` are * Numbers. */ -function Polygon(points) { +function Polygon(points) +{ //if points isn't an array, use arguments as the array - if (!(points instanceof Array)) { + if (!(points instanceof Array)) + { points = Array.prototype.slice.call(arguments); } //if this is a flat array of numbers, convert it to points - if (points[0] instanceof Point) { + if (points[0] instanceof Point) + { var p = []; - for (var i = 0, il = points.length; i < il; i++) { + for (var i = 0, il = points.length; i < il; i++) + { p.push(points[i].x, points[i].y); } @@ -51,7 +55,8 @@ * * @return {Polygon} a copy of the polygon */ -Polygon.prototype.clone = function () { +Polygon.prototype.clone = function () +{ return new Polygon(this.points.slice()); }; @@ -62,19 +67,22 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this polygon */ -Polygon.prototype.contains = function (x, y) { +Polygon.prototype.contains = function (x, y) +{ var inside = false; // use some raycasting to test hits // https://github.com/substack/point-in-polygon/blob/master/index.js var length = this.points.length / 2; - for (var i = 0, j = length - 1; i < length; j = i++) { + for (var i = 0, j = length - 1; i < length; j = i++) + { var xi = this.points[i * 2], yi = this.points[i * 2 + 1], xj = this.points[j * 2], yj = this.points[j * 2 + 1], intersect = ((yi > y) !== (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi); - if (intersect) { + if (intersect) + { inside = !inside; } } diff --git a/src/core/math/shapes/Rectangle.js b/src/core/math/shapes/Rectangle.js index 16ac62a..4008b68 100644 --- a/src/core/math/shapes/Rectangle.js +++ b/src/core/math/shapes/Rectangle.js @@ -10,7 +10,8 @@ * @param width {number} The overall width of this rectangle * @param height {number} The overall height of this rectangle */ -function Rectangle(x, y, width, height) { +function Rectangle(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -60,7 +61,8 @@ * * @return {Rectangle} a copy of the rectangle */ -Rectangle.prototype.clone = function () { +Rectangle.prototype.clone = function () +{ return new Rectangle(this.x, this.y, this.width, this.height); }; @@ -71,13 +73,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rectangle */ -Rectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Rectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/math/shapes/RoundedRectangle.js b/src/core/math/shapes/RoundedRectangle.js index 27d286e..7bf6411 100644 --- a/src/core/math/shapes/RoundedRectangle.js +++ b/src/core/math/shapes/RoundedRectangle.js @@ -11,7 +11,8 @@ * @param height {number} The overall height of this rounded rectangle * @param radius {number} Controls the radius of the rounded corners */ -function RoundedRectangle(x, y, width, height, radius) { +function RoundedRectangle(x, y, width, height, radius) +{ /** * @member {number} * @default 0 @@ -58,7 +59,8 @@ * * @return {RoundedRectangle} a copy of the rounded rectangle */ -RoundedRectangle.prototype.clone = function () { +RoundedRectangle.prototype.clone = function () +{ return new RoundedRectangle(this.x, this.y, this.width, this.height, this.radius); }; @@ -69,13 +71,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rounded Rectangle */ -RoundedRectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +RoundedRectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/primitives/Graphics.js b/src/core/primitives/Graphics.js index 261c534..e902d2a 100644 --- a/src/core/primitives/Graphics.js +++ b/src/core/primitives/Graphics.js @@ -16,7 +16,8 @@ * @extends DisplayObjectContainer * @namespace PIXI */ -function Graphics() { +function Graphics() +{ DisplayObjectContainer.call(this); this.renderable = true; @@ -154,16 +155,20 @@ * @private */ cacheAsBitmap: { - get: function () { + get: function () + { return this._cacheAsBitmap; }, - set: function (value) { + set: function (value) + { this._cacheAsBitmap = value; - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._generateCachedSprite(); } - else { + else + { this.destroyCachedSprite(); this.dirty = true; } @@ -176,7 +181,8 @@ * * @return {Graphics} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ var clone = new Graphics(); clone.renderable = this.renderable; @@ -192,7 +198,8 @@ clone.cachedSpriteDirty = this.cachedSpriteDirty; // copy graphics data - for (var i = 0; i < this.graphicsData.length; ++i) { + for (var i = 0; i < this.graphicsData.length; ++i) + { clone.graphicsData.push(this.graphicsData.clone()); } @@ -211,17 +218,21 @@ * @param alpha {number} alpha of the line to draw, will update the objects stored style * @return {Graphics} */ -Graphics.prototype.lineStyle = function (lineWidth, color, alpha) { +Graphics.prototype.lineStyle = function (lineWidth, color, alpha) +{ this.lineWidth = lineWidth || 0; this.lineColor = color || 0; this.lineAlpha = (arguments.length < 3) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length) + { // halfway through a line? start a new one! this.drawShape( new math.Polygon( this.currentPath.shape.points.slice(-2) )); } - else { + else + { // otherwise its empty so lets just set the line properties this.currentPath.lineWidth = this.lineWidth; this.currentPath.lineColor = this.lineColor; @@ -239,7 +250,8 @@ * @param y {number} the Y coordinate to move to * @return {Graphics} */ -Graphics.prototype.moveTo = function (x, y) { +Graphics.prototype.moveTo = function (x, y) +{ this.drawShape(new math.Polygon([x,y])); return this; @@ -253,7 +265,8 @@ * @param y {number} the Y coordinate to draw to * @return {Graphics} */ -Graphics.prototype.lineTo = function (x, y) { +Graphics.prototype.lineTo = function (x, y) +{ this.currentPath.shape.points.push(x, y); this.dirty = true; @@ -270,13 +283,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -285,7 +302,8 @@ n = 20, points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { this.moveTo(0, 0); } @@ -293,7 +311,8 @@ var fromY = points[points.length-1]; var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; xa = fromX + ( (cpX - fromX) * j ); @@ -319,13 +338,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -342,7 +365,8 @@ var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; dt = (1 - j); @@ -373,13 +397,17 @@ * @param radius {number} The radius of the arc * @return {Graphics} */ -Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points.push(x1, y1); } } - else { + else + { this.moveTo(x1, y1); } @@ -392,12 +420,15 @@ b2 = x2 - x1, mm = Math.abs(a1 * b2 - b1 * a2); - if (mm < 1.0e-8 || radius === 0) { - if (points[points.length-2] !== x1 || points[points.length-1] !== y1) { + if (mm < 1.0e-8 || radius === 0) + { + if (points[points.length-2] !== x1 || points[points.length-1] !== y1) + { points.push(x1, y1); } } - else { + else + { var dd = a1 * a1 + b1 * b1, cc = a2 * a2 + b2 * b2, tt = a1 * a2 + b1 * b2, @@ -433,42 +464,51 @@ * @param anticlockwise {boolean} Optional. Specifies whether the drawing should be counterclockwise or clockwise. False is default, and indicates clockwise, while true indicates counter-clockwise. * @return {Graphics} */ -Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) { +Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) +{ var startX = cx + Math.cos(startAngle) * radius; var startY = cy + Math.sin(startAngle) * radius; var points; // TODO - This if-else makes no sense. It uses currentPath in the else where it doesn't exist... - if (this.currentPath) { + if (this.currentPath) + { points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { points.push(startX, startY); } - else if (points[points.length-2] !== startX || points[points.length-1] !== startY) { + else if (points[points.length-2] !== startX || points[points.length-1] !== startY) + { points.push(startX, startY); } } - else { + else + { this.moveTo(startX, startY); points = this.currentPath.shape.points; } - if (startAngle === endAngle) { + if (startAngle === endAngle) + { return this; } - if (!anticlockwise && endAngle <= startAngle) { + if (!anticlockwise && endAngle <= startAngle) + { endAngle += Math.PI * 2; } - else if (anticlockwise && startAngle <= endAngle) { + else if (anticlockwise && startAngle <= endAngle) + { startAngle += Math.PI * 2; } var sweep = anticlockwise ? (startAngle - endAngle) *-1 : (endAngle - startAngle); var segs = (Math.abs(sweep)/ (Math.PI * 2)) * 40; - if (sweep === 0) { + if (sweep === 0) + { return this; } @@ -482,7 +522,8 @@ var remainder = ( segMinus % 1 ) / segMinus; - for (var i = 0; i <= segMinus; ++i) { + for (var i = 0; i <= segMinus; ++i) + { var real = i + remainder * i; var angle = ((theta) + startAngle + (theta2 * real)); @@ -506,13 +547,16 @@ * @param alpha {number} the alpha of the fill * @return {Graphics} */ -Graphics.prototype.beginFill = function (color, alpha) { +Graphics.prototype.beginFill = function (color, alpha) +{ this.filling = true; this.fillColor = color || 0; this.fillAlpha = (alpha === undefined) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length <= 2) + { this.currentPath.fill = this.filling; this.currentPath.fillColor = this.fillColor; this.currentPath.fillAlpha = this.fillAlpha; @@ -526,7 +570,8 @@ * * @return {Graphics} */ -Graphics.prototype.endFill = function () { +Graphics.prototype.endFill = function () +{ this.filling = false; this.fillColor = null; this.fillAlpha = 1; @@ -542,7 +587,8 @@ * @param height {number} The height of the rectangle * @return {Graphics} */ -Graphics.prototype.drawRect = function ( x, y, width, height ) { +Graphics.prototype.drawRect = function ( x, y, width, height ) +{ this.drawShape(new math.Rectangle(x,y, width, height)); return this; @@ -556,7 +602,8 @@ * @param height {number} The height of the rectangle * @param radius {number} Radius of the rectangle corners */ -Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) { +Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) +{ this.drawShape(new math.RoundedRectangle(x, y, width, height, radius)); return this; @@ -570,7 +617,8 @@ * @param radius {number} The radius of the circle * @return {Graphics} */ -Graphics.prototype.drawCircle = function (x, y, radius) { +Graphics.prototype.drawCircle = function (x, y, radius) +{ this.drawShape(new math.Circle(x,y, radius)); return this; @@ -585,7 +633,8 @@ * @param height {number} The half height of the ellipse * @return {Graphics} */ -Graphics.prototype.drawEllipse = function (x, y, width, height) { +Graphics.prototype.drawEllipse = function (x, y, width, height) +{ this.drawShape(new math.Ellipse(x, y, width, height)); return this; @@ -597,8 +646,10 @@ * @param path {Array} The path data used to construct the polygon. * @return {Graphics} */ -Graphics.prototype.drawPolygon = function (path) { - if (!(path instanceof Array)) { +Graphics.prototype.drawPolygon = function (path) +{ + if (!(path instanceof Array)) + { path = Array.prototype.slice.call(arguments); } @@ -612,7 +663,8 @@ * * @return {Graphics} */ -Graphics.prototype.clear = function () { +Graphics.prototype.clear = function () +{ this.lineWidth = 0; this.filling = false; @@ -631,7 +683,8 @@ * @param scaleMode {number} Should be one of the scaleMode consts * @return {Texture} a texture of the graphics object */ -Graphics.prototype.generateTexture = function (resolution, scaleMode) { +Graphics.prototype.generateTexture = function (resolution, scaleMode) +{ resolution = resolution || 1; var bounds = this.getBounds(); @@ -655,17 +708,21 @@ * * @param renderer {WebGLRenderer} */ -Graphics.prototype._renderWebGL = function (renderer) { +Graphics.prototype._renderWebGL = function (renderer) +{ // if the sprite is not visible or the alpha is 0 then no need to render this element - if (this.isMask === true) { + if (this.isMask === true) + { return; } // this code may still be needed so leaving for now.. - // + // /* - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture on the gpu too! @@ -681,17 +738,24 @@ return; } - */ - - // check if the webgl graphic needs to be updated - if (this.glDirty) { - this.dirty = true; - this.glDirty = false; - } + else */ - renderer.setObjectRendererer(renderer.graphicsRenderer); - renderer.graphicsRenderer.render(this); + renderer.spriteBatch.stop(); + renderer.blendModeManager.setBlendMode(this.blendMode); + // check blend mode + renderer.blendModeManager.setBlendMode( this.blendMode ); + + // check if the webgl graphic needs to be updated + if (this.glDirty) + { + this.dirty = true; + this.glDirty = false; + } + + WebGLGraphics.renderGraphics(this, renderer); + + renderer.spriteBatch.start(); }; /** @@ -700,14 +764,18 @@ * @param renderer {CanvasRenderer} * @private */ -Graphics.prototype.renderCanvas = function (renderer) { +Graphics.prototype.renderCanvas = function (renderer) +{ // 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.isMask === true) { + if (!this.visible || this.alpha <= 0 || this.isMask === true) + { return; } - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture @@ -723,16 +791,19 @@ return; } - else { + else + { var context = renderer.context; var transform = this.worldTransform; - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } @@ -748,11 +819,13 @@ CanvasGraphics.renderGraphics(this, context); - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } } @@ -763,13 +836,16 @@ * * @return {Rectangle} the rectangular bounding area */ -Graphics.prototype.getBounds = function (matrix) { +Graphics.prototype.getBounds = function (matrix) +{ // return an empty object if the item is a mask! - if (this.isMask) { + if (this.isMask) + { return math.Rectangle.EMPTY; } - if (this.dirty) { + if (this.dirty) + { this.updateLocalBounds(); this.glDirty = true; @@ -841,23 +917,27 @@ * Update the bounds of the object * */ -Graphics.prototype.updateLocalBounds = function () { +Graphics.prototype.updateLocalBounds = function () +{ var minX = Infinity; var maxX = -Infinity; var minY = Infinity; var maxY = -Infinity; - if (this.graphicsData.length) { + if (this.graphicsData.length) + { var shape, points, x, y, w, h; - for (var i = 0; i < this.graphicsData.length; i++) { + for (var i = 0; i < this.graphicsData.length; i++) + { var data = this.graphicsData[i]; var type = data.type; var lineWidth = data.lineWidth; shape = data.shape; - if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) { + if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) + { x = shape.x - lineWidth/2; y = shape.y - lineWidth/2; w = shape.width + lineWidth; @@ -869,7 +949,8 @@ minY = y < minY ? y : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.CIRC) { + else if (type === CONST.SHAPES.CIRC) + { x = shape.x; y = shape.y; w = shape.radius + lineWidth/2; @@ -881,7 +962,8 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.ELIP) { + else if (type === CONST.SHAPES.ELIP) + { x = shape.x; y = shape.y; w = shape.width + lineWidth/2; @@ -893,11 +975,13 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else { + else + { // POLY points = shape.points; - for (var j = 0; j < points.length; j += 2) { + for (var j = 0; j < points.length; j += 2) + { x = points[j]; y = points[j+1]; @@ -910,7 +994,8 @@ } } } - else { + else + { minX = 0; maxX = 0; minY = 0; @@ -931,10 +1016,12 @@ * * @private */ -Graphics.prototype._generateCachedSprite = function () { +Graphics.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { var canvasBuffer = new CanvasBuffer(bounds.width, bounds.height); var texture = Texture.fromCanvas(canvasBuffer.canvas); @@ -943,7 +1030,8 @@ this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.buffer.resize(bounds.width, bounds.height); } @@ -968,7 +1056,8 @@ * * @private */ -Graphics.prototype.updateCachedSpriteTexture = function () { +Graphics.prototype.updateCachedSpriteTexture = function () +{ var cachedSprite = this._cachedSprite; var texture = cachedSprite.texture; var canvas = cachedSprite.buffer.canvas; @@ -989,7 +1078,8 @@ * Destroys a previous cached sprite. * */ -Graphics.prototype.destroyCachedSprite = function () { +Graphics.prototype.destroyCachedSprite = function () +{ this._cachedSprite.texture.destroy(true); // let the gc collect the unused sprite @@ -1003,10 +1093,13 @@ * @param {Circle|Rectangle|Ellipse|Line|Polygon} shape The Shape object to draw. * @return {GraphicsData} The generated GraphicsData object. */ -Graphics.prototype.drawShape = function (shape) { - if (this.currentPath) { +Graphics.prototype.drawShape = function (shape) +{ + if (this.currentPath) + { // check current path! - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath.shape.points.length <= 2) + { this.graphicsData.pop(); } } @@ -1017,7 +1110,8 @@ this.graphicsData.push(data); - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { data.shape.closed = this.filling; this.currentPath = data; } diff --git a/src/core/primitives/GraphicsData.js b/src/core/primitives/GraphicsData.js index 99decbe..788f6f2 100644 --- a/src/core/primitives/GraphicsData.js +++ b/src/core/primitives/GraphicsData.js @@ -4,7 +4,8 @@ * @class * @namespace PIXI */ -function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) { +function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) +{ this.lineWidth = lineWidth; this.lineColor = lineColor; this.lineAlpha = lineAlpha; @@ -27,7 +28,8 @@ * * @return {GraphicsData} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ return new GraphicsData( this.lineWidth, this.lineColor, diff --git a/src/core/renderers/canvas/CanvasRenderer.js b/src/core/renderers/canvas/CanvasRenderer.js index 15a0978..7aebd44 100644 --- a/src/core/renderers/canvas/CanvasRenderer.js +++ b/src/core/renderers/canvas/CanvasRenderer.js @@ -17,17 +17,22 @@ * @param [options.resolution=1] {number} the resolution of the renderer retina would be 2 * @param [options.clearBeforeRender=true] {boolean} This sets if the CanvasRenderer will clear the canvas or not before the new render pass. */ -function CanvasRenderer(width, height, options) { +function CanvasRenderer(width, height, options) +{ utils.sayHello('Canvas'); - if (options) { - for (var i in CONST.defaultRenderOptions) { - if (typeof options[i] === 'undefined') { + if (options) + { + for (var i in CONST.defaultRenderOptions) + { + if (typeof options[i] === 'undefined') + { options[i] = CONST.defaultRenderOptions[i]; } } } - else { + else + { options = CONST.defaultRenderOptions; } @@ -156,19 +161,24 @@ this.smoothProperty = null; - if (this.context.imageSmoothingEnabled) { + if (this.context.imageSmoothingEnabled) + { this.smoothProperty = 'imageSmoothingEnabled'; } - else if (this.context.webkitImageSmoothingEnabled) { + else if (this.context.webkitImageSmoothingEnabled) + { this.smoothProperty = 'webkitImageSmoothingEnabled'; } - else if (this.context.mozImageSmoothingEnabled) { + else if (this.context.mozImageSmoothingEnabled) + { this.smoothProperty = 'mozImageSmoothingEnabled'; } - else if (this.context.oImageSmoothingEnabled) { + else if (this.context.oImageSmoothingEnabled) + { this.smoothProperty = 'oImageSmoothingEnabled'; } - else if (this.context.msImageSmoothingEnabled) { + else if (this.context.msImageSmoothingEnabled) + { this.smoothProperty = 'msImageSmoothingEnabled'; } @@ -193,10 +203,12 @@ * @memberof CanvasRenderer# */ backgroundColor: { - get: function () { + get: function () + { return this._backgroundColor; }, - set: function (val) { + set: function (val) + { this._backgroundColor = val; this._backgroundColorString = utils.hex2string(val); } @@ -208,7 +220,8 @@ * * @param object {DisplayObject} the object to be rendered */ -CanvasRenderer.prototype.render = function (object) { +CanvasRenderer.prototype.render = function (object) +{ object.updateTransform(); this.context.setTransform(1,0,0,1,0,0); @@ -218,16 +231,20 @@ this.currentBlendMode = CONST.blendModes.NORMAL; this.context.globalCompositeOperation = this.blendModes[CONST.blendModes.NORMAL]; - if (navigator.isCocoonJS && this.view.screencanvas) { + if (navigator.isCocoonJS && this.view.screencanvas) + { this.context.fillStyle = 'black'; this.context.clear(); } - if (this.clearBeforeRender) { - if (this.transparent) { + if (this.clearBeforeRender) + { + if (this.transparent) + { this.context.clearRect(0, 0, this.width, this.height); } - else { + else + { this.context.fillStyle = this._backgroundColorString; this.context.fillRect(0, 0, this.width , this.height); } @@ -241,8 +258,10 @@ * * @param [removeView=false] {boolean} Removes the Canvas element from the DOM. */ -CanvasRenderer.prototype.destroy = function (removeView) { - if (removeView && this.view.parent) { +CanvasRenderer.prototype.destroy = function (removeView) +{ + if (removeView && this.view.parent) + { this.view.parent.removeChild(this.view); } @@ -257,14 +276,16 @@ * @param width {number} the new width of the canvas view * @param height {number} the new height of the canvas view */ -CanvasRenderer.prototype.resize = function (width, height) { +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) { + if (this.autoResize) + { this.view.style.width = this.width / this.resolution + 'px'; this.view.style.height = this.height / this.resolution + 'px'; } @@ -276,7 +297,8 @@ * @param displayObject {DisplayObject} The displayObject to render * @private */ -CanvasRenderer.prototype.renderDisplayObject = function (displayObject) { +CanvasRenderer.prototype.renderDisplayObject = function (displayObject) +{ displayObject.renderCanvas(this); }; @@ -285,11 +307,14 @@ * * @private */ -CanvasRenderer.prototype._mapBlendModes = function () { - if (!this.blendModes) { +CanvasRenderer.prototype._mapBlendModes = function () +{ + if (!this.blendModes) + { this.blendModes = {}; - if (utils.canUseNewCanvasBlendModes()) { + if (utils.canUseNewCanvasBlendModes()) + { this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? this.blendModes[CONST.blendModes.MULTIPLY] = 'multiply'; @@ -308,7 +333,8 @@ this.blendModes[CONST.blendModes.COLOR] = 'color'; this.blendModes[CONST.blendModes.LUMINOSITY] = 'luminosity'; } - else { + else + { // this means that the browser does not support the cool new blend modes in canvas 'cough' ie 'cough' this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? diff --git a/src/core/renderers/canvas/utils/CanvasBuffer.js b/src/core/renderers/canvas/utils/CanvasBuffer.js index ebe5d47..b183a66 100644 --- a/src/core/renderers/canvas/utils/CanvasBuffer.js +++ b/src/core/renderers/canvas/utils/CanvasBuffer.js @@ -6,7 +6,8 @@ * @param width {number} the width for the newly created canvas * @param height {number} the height for the newly created canvas */ -function CanvasBuffer(width, height) { +function CanvasBuffer(width, height) +{ /** * The Canvas object that belongs to this CanvasBuffer. * @@ -36,10 +37,12 @@ * @memberof CanvasBuffer# */ width: { - get: function () { + get: function () + { return this.canvas.width; }, - set: function (val) { + set: function (val) + { this.canvas.width = val; } }, @@ -50,10 +53,12 @@ * @memberof CanvasBuffer# */ height: { - get: function () { + get: function () + { return this.canvas.height; }, - set: function (val) { + set: function (val) + { this.canvas.height = val; } } @@ -64,7 +69,8 @@ * * @private */ -CanvasBuffer.prototype.clear = function () { +CanvasBuffer.prototype.clear = function () +{ this.context.setTransform(1, 0, 0, 1, 0, 0); this.context.clearRect(0,0, this.canvas.width, this.canvas.height); }; @@ -75,7 +81,8 @@ * @param width {number} the new width of the canvas * @param height {number} the new height of the canvas */ -CanvasBuffer.prototype.resize = function (width, height) { +CanvasBuffer.prototype.resize = function (width, height) +{ this.canvas.width = width; this.canvas.height = height; }; diff --git a/src/core/renderers/canvas/utils/CanvasGraphics.js b/src/core/renderers/canvas/utils/CanvasGraphics.js index c7eaa2a..3f2a91f 100644 --- a/src/core/renderers/canvas/utils/CanvasGraphics.js +++ b/src/core/renderers/canvas/utils/CanvasGraphics.js @@ -13,15 +13,18 @@ * @param graphics {Graphics} the actual graphics object to render * @param context {CanvasRenderingContext2D} the 2d drawing method of the canvas */ -CanvasGraphics.renderGraphics = function (graphics, context) { +CanvasGraphics.renderGraphics = function (graphics, context) +{ var worldAlpha = graphics.worldAlpha; - if (graphics.dirty) { + if (graphics.dirty) + { this.updateGraphicsTint(graphics); graphics.dirty = false; } - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; @@ -30,69 +33,82 @@ context.lineWidth = data.lineWidth; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { context.beginPath(); var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } - if (shape.closed) { + if (shape.closed) + { context.lineTo(points[0], points[1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fillRect(shape.x, shape.y, shape.width, shape.height); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.strokeRect(shape.x, shape.y, shape.width, shape.height); } } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.beginPath(); context.arc(shape.x, shape.y, shape.radius,0,2*Math.PI); context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas var w = shape.width * 2; @@ -119,18 +135,21 @@ context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; var width = shape.width; @@ -152,13 +171,15 @@ context.quadraticCurveTo(rx, ry, rx, ry + radius); context.closePath(); - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); @@ -174,45 +195,54 @@ * @param graphics {Graphics} the graphics which will be used as a mask * @param context {CanvasRenderingContext2D} the context 2d method of the canvas */ -CanvasGraphics.renderGraphicsMask = function (graphics, context) { +CanvasGraphics.renderGraphicsMask = function (graphics, context) +{ var len = graphics.graphicsData.length; - if (len === 0) { + if (len === 0) + { return; } context.beginPath(); - for (var i = 0; i < len; i++) { + for (var i = 0; i < len; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { context.rect(shape.x, shape.y, shape.width, shape.height); context.closePath(); } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.arc(shape.x, shape.y, shape.radius, 0, 2 * Math.PI); context.closePath(); } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas @@ -237,7 +267,8 @@ context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); context.closePath(); } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; @@ -262,8 +293,10 @@ } }; -CanvasGraphics.updateGraphicsTint = function (graphics) { - if (graphics.tint === 0xFFFFFF) { +CanvasGraphics.updateGraphicsTint = function (graphics) +{ + if (graphics.tint === 0xFFFFFF) + { return; } @@ -271,7 +304,8 @@ var tintG = (graphics.tint >> 8 & 0xFF) / 255; var tintB = (graphics.tint & 0xFF)/ 255; - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var fillColor = data.fillColor | 0; diff --git a/src/core/renderers/canvas/utils/CanvasMaskManager.js b/src/core/renderers/canvas/utils/CanvasMaskManager.js index e04a733..9827d36 100644 --- a/src/core/renderers/canvas/utils/CanvasMaskManager.js +++ b/src/core/renderers/canvas/utils/CanvasMaskManager.js @@ -6,7 +6,8 @@ * @class * @namespace PIXI */ -function CanvasMaskManager() {} +function CanvasMaskManager() +{} CanvasMaskManager.prototype.constructor = CanvasMaskManager; module.exports = CanvasMaskManager; @@ -17,7 +18,8 @@ * @param maskData {object} the maskData that will be pushed * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.pushMask = function (maskData, renderer) { +CanvasMaskManager.prototype.pushMask = function (maskData, renderer) +{ renderer.context.save(); var cacheAlpha = maskData.alpha; @@ -45,6 +47,7 @@ * * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.popMask = function (renderer) { +CanvasMaskManager.prototype.popMask = function (renderer) +{ renderer.context.restore(); }; diff --git a/src/core/renderers/canvas/utils/CanvasTinter.js b/src/core/renderers/canvas/utils/CanvasTinter.js index 17e0529..d2fb1bc 100644 --- a/src/core/renderers/canvas/utils/CanvasTinter.js +++ b/src/core/renderers/canvas/utils/CanvasTinter.js @@ -14,7 +14,8 @@ * @param color {number} the color to use to tint the sprite with * @return {HTMLCanvasElement} The tinted canvas */ -CanvasTinter.getTintedTexture = function (sprite, color) { +CanvasTinter.getTintedTexture = function (sprite, color) +{ var texture = sprite.texture; color = CanvasTinter.roundColor(color); @@ -23,7 +24,8 @@ texture.tintCache = texture.tintCache || {}; - if (texture.tintCache[stringColor]) { + if (texture.tintCache[stringColor]) + { return texture.tintCache[stringColor]; } @@ -33,14 +35,16 @@ //CanvasTinter.tintWithPerPixel(texture, stringColor, canvas); CanvasTinter.tintMethod(texture, color, canvas); - if (CanvasTinter.convertTintToImage) { + if (CanvasTinter.convertTintToImage) + { // is this better? var tintImage = new Image(); tintImage.src = canvas.toDataURL(); texture.tintCache[stringColor] = tintImage; } - else { + else + { texture.tintCache[stringColor] = canvas; // if we are not converting the texture to an image then we need to lose the reference to the canvas CanvasTinter.canvas = null; @@ -56,7 +60,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithMultiply = function (texture, color, canvas) { +CanvasTinter.tintWithMultiply = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -104,7 +109,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithOverlay = function (texture, color, canvas) { +CanvasTinter.tintWithOverlay = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -139,7 +145,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithPerPixel = function (texture, color, canvas) { +CanvasTinter.tintWithPerPixel = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -167,7 +174,8 @@ var pixels = pixelData.data; - for (var i = 0; i < pixels.length; i += 4) { + for (var i = 0; i < pixels.length; i += 4) + { pixels[i+0] *= r; pixels[i+1] *= g; pixels[i+2] *= b; @@ -181,7 +189,8 @@ * * @param color {number} the color to round, should be a hex color */ -CanvasTinter.roundColor = function (color) { +CanvasTinter.roundColor = function (color) +{ var step = CanvasTinter.cacheStepsPerColorChannel; var rgbValues = utils.hex2rgb(color); diff --git a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js index 9f2f89a..35edbaf 100644 --- a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js +++ b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLBlendModeManager(renderer) { +function WebGLBlendModeManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -23,8 +24,10 @@ * * @param blendMode {number} the blendMode, should be a Pixi const, such as BlendModes.ADD */ -WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) { - if (this.currentBlendMode === blendMode) { +WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) +{ + if (this.currentBlendMode === blendMode) + { return false; } diff --git a/src/core/renderers/webgl/managers/WebGLFilterManager.js b/src/core/renderers/webgl/managers/WebGLFilterManager.js index 1179258..2dac048 100644 --- a/src/core/renderers/webgl/managers/WebGLFilterManager.js +++ b/src/core/renderers/webgl/managers/WebGLFilterManager.js @@ -7,7 +7,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLFilterManager(renderer) { +function WebGLFilterManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -32,7 +33,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.texturePool.length = 0; self.initShaderBuffers(); }); @@ -46,7 +48,8 @@ * @param renderer {WebGLRenderer} * @param buffer {ArrayBuffer} */ -WebGLFilterManager.prototype.begin = function (buffer) { +WebGLFilterManager.prototype.begin = function (buffer) +{ this.defaultShader = this.renderer.shaderManager.defaultShader; this.width = this.renderer.projection.x * 2; @@ -60,7 +63,8 @@ * * @param filterBlock {object} the filter that will be pushed to the current filter stack */ -WebGLFilterManager.prototype.pushFilter = function (filterBlock) { +WebGLFilterManager.prototype.pushFilter = function (filterBlock) +{ var gl = this.renderer.gl; var projection = this.renderer.projection; @@ -78,10 +82,12 @@ this.offsetY += filterBlock._filterArea.y; var texture = this.texturePool.pop(); - if (!texture) { + if (!texture) + { texture = new FilterTexture(this.renderer.gl, this.width, this.height); } - else { + else + { texture.resize(this.width, this.height); } @@ -98,29 +104,35 @@ var localX = filterArea.x, localY = filterArea.y; - if (filterArea.x < 0) { + if (filterArea.x < 0) + { filterArea.width += filterArea.x; filterArea.x = 0; } - if (filterArea.y < 0) { + if (filterArea.y < 0) + { filterArea.height += filterArea.y; filterArea.y = 0; } - if (localX + filterArea.width > this.width) { + if (localX + filterArea.width > this.width) + { filterArea.width = this.width - localX; } - if (localY + filterArea.height > this.height) { + if (localY + filterArea.height > this.height) + { filterArea.height = this.height - localY; } - if (filterArea.width < 0) { + if (filterArea.width < 0) + { filterArea.width = 0; } - if (filterArea.height < 0) { + if (filterArea.height < 0) + { filterArea.height = 0; } @@ -154,7 +166,8 @@ * Removes the last filter from the filter stack and doesn't return it. * */ -WebGLFilterManager.prototype.popFilter = function () { +WebGLFilterManager.prototype.popFilter = function () +{ var gl = this.renderer.gl; var filterBlock = this.filterStack.pop(); @@ -163,7 +176,8 @@ var projection = this.renderer.projection; var offset = this.renderer.offset; - if (filterBlock.filterPasses.length > 1) { + if (filterBlock.filterPasses.length > 1) + { gl.viewport(0, 0, filterArea.width, filterArea.height); gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); @@ -193,7 +207,8 @@ var inputTexture = texture; var outputTexture = this.texturePool.pop(); - if (!outputTexture) { + if (!outputTexture) + { outputTexture = new FilterTexture(this.renderer.gl, this.width, this.height); } outputTexture.resize(this.width, this.height); @@ -204,7 +219,8 @@ gl.disable(gl.BLEND); - for (var i = 0; i < filterBlock.filterPasses.length-1; i++) { + for (var i = 0; i < filterBlock.filterPasses.length-1; i++) + { var filterPass = filterBlock.filterPasses[i]; gl.bindFramebuffer(gl.FRAMEBUFFER, outputTexture.frameBuffer ); @@ -243,10 +259,12 @@ var buffer = this.buffer; // time to render the filters texture to the previous scene - if (this.filterStack.length === 0) { + if (this.filterStack.length === 0) + { gl.colorMask(true, true, true, true);//this.transparent); } - else { + else + { var currentFilter = this.filterStack[this.filterStack.length-1]; filterArea = currentFilter._filterArea; @@ -332,13 +350,15 @@ * @param width {number} the horizontal range of the filter * @param height {number} the vertical range of the filter */ -WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) { +WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) +{ // use program var gl = this.renderer.gl; var shader = filter.shaders[gl.id]; - if (!shader) { + if (!shader) + { shader = new Shader(gl); shader.fragmentSrc = filter.fragmentSrc; @@ -356,7 +376,8 @@ gl.uniform2f(shader.projectionVector, width/2, -height/2); gl.uniform2f(shader.offsetVector, 0,0); - if (filter.uniforms.dimensions) { + 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]; @@ -386,7 +407,8 @@ * Initialises the shader buffers. * */ -WebGLFilterManager.prototype.initShaderBuffers = function () { +WebGLFilterManager.prototype.initShaderBuffers = function () +{ var gl = this.renderer.gl; // create some buffers @@ -432,7 +454,8 @@ * Destroys the filter and removes it from the filter stack. * */ -WebGLFilterManager.prototype.destroy = function () { +WebGLFilterManager.prototype.destroy = function () +{ var gl = this.renderer.gl; this.filterStack = null; @@ -441,7 +464,8 @@ this.offsetY = 0; // destroy textures - for (var i = 0; i < this.texturePool.length; i++) { + for (var i = 0; i < this.texturePool.length; i++) + { this.texturePool[i].destroy(); } diff --git a/src/core/renderers/webgl/managers/WebGLManager.js b/src/core/renderers/webgl/managers/WebGLManager.js index 9d47b5c..c30cd51 100644 --- a/src/core/renderers/webgl/managers/WebGLManager.js +++ b/src/core/renderers/webgl/managers/WebGLManager.js @@ -3,7 +3,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLManager(renderer) { +function WebGLManager(renderer) +{ /** * The renderer this manager works for. * @@ -15,6 +16,7 @@ WebGLManager.prototype.constructor = WebGLManager; module.exports = WebGLManager; -WebGLManager.prototype.destroy = function () { +WebGLManager.prototype.destroy = function () +{ this.renderer = null; }; diff --git a/src/core/renderers/webgl/managers/WebGLMaskManager.js b/src/core/renderers/webgl/managers/WebGLMaskManager.js index 2f90b64..e568812 100644 --- a/src/core/renderers/webgl/managers/WebGLMaskManager.js +++ b/src/core/renderers/webgl/managers/WebGLMaskManager.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLMaskManager(renderer) { +function WebGLMaskManager(renderer) +{ WebGLManager.call(this, renderer); } @@ -19,12 +20,15 @@ * * @param maskData {any[]} */ -WebGLMaskManager.prototype.pushMask = function (maskData) { - if (maskData.dirty) { +WebGLMaskManager.prototype.pushMask = function (maskData) +{ + if (maskData.dirty) + { WebGLGraphics.updateGraphics(maskData, this.renderer.gl); } - if (!maskData._webGL[this.renderer.gl.id].data.length) { + if (!maskData._webGL[this.renderer.gl.id].data.length) + { return; } @@ -36,6 +40,7 @@ * * @param maskData {any[]} */ -WebGLMaskManager.prototype.popMask = function (maskData) { +WebGLMaskManager.prototype.popMask = function (maskData) +{ this.renderer.stencilManager.popStencil(maskData, maskData._webGL[this.renderer.gl.id].data[0], this.renderer); }; diff --git a/src/core/renderers/webgl/managers/WebGLShaderManager.js b/src/core/renderers/webgl/managers/WebGLShaderManager.js index fef071c..90c6477 100644 --- a/src/core/renderers/webgl/managers/WebGLShaderManager.js +++ b/src/core/renderers/webgl/managers/WebGLShaderManager.js @@ -10,7 +10,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLShaderManager(renderer) { +function WebGLShaderManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -28,7 +29,8 @@ */ this.tempAttribState = []; - for (var i = 0; i < this.maxAttibs; i++) { + for (var i = 0; i < this.maxAttibs; i++) + { this.attribState[i] = false; } @@ -66,7 +68,8 @@ // listen for context and update necessary shaders var self = this; - this.renderer.on('context', function (event) { + this.renderer.on('context', function (event) + { var gl = event.data; // this shader is used for rendering primitives @@ -97,29 +100,36 @@ * * @param attribs {Array} attribs */ -WebGLShaderManager.prototype.setAttribs = function (attribs) { +WebGLShaderManager.prototype.setAttribs = function (attribs) +{ // reset temp state var i; - for (i = 0; i < this.tempAttribState.length; i++) { + for (i = 0; i < this.tempAttribState.length; i++) + { this.tempAttribState[i] = false; } // set the new attribs - for (var a in attribs) { + for (var a in attribs) + { this.tempAttribState[attribs[a]] = true; } var gl = this.renderer.gl; - for (i = 0; i < this.attribState.length; i++) { - if (this.attribState[i] !== this.tempAttribState[i]) { + for (i = 0; i < this.attribState.length; i++) + { + if (this.attribState[i] !== this.tempAttribState[i]) + { this.attribState[i] = this.tempAttribState[i]; - if (this.attribState[i]) { + if (this.attribState[i]) + { gl.enableVertexAttribArray(i); } - else { + else + { gl.disableVertexAttribArray(i); } } @@ -131,8 +141,10 @@ * * @param shader {Any} */ -WebGLShaderManager.prototype.setShader = function (shader) { - if (this._currentId === shader.uuid) { +WebGLShaderManager.prototype.setShader = function (shader) +{ + if (this._currentId === shader.uuid) + { return false; } @@ -150,7 +162,8 @@ * Destroys this object. * */ -WebGLShaderManager.prototype.destroy = function () { +WebGLShaderManager.prototype.destroy = function () +{ this.attribState = null; this.tempAttribState = null; diff --git a/src/core/renderers/webgl/managers/WebGLStencilManager.js b/src/core/renderers/webgl/managers/WebGLStencilManager.js index 9ec6398..4cb0134 100644 --- a/src/core/renderers/webgl/managers/WebGLStencilManager.js +++ b/src/core/renderers/webgl/managers/WebGLStencilManager.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLStencilManager(renderer) { +function WebGLStencilManager(renderer) +{ WebGLManager.call(this, renderer); this.stencilStack = []; @@ -24,12 +25,14 @@ * @param graphics {Graphics} * @param webGLData {any[]} */ -WebGLStencilManager.prototype.pushStencil = function (graphics, webGLData) { +WebGLStencilManager.prototype.pushStencil = function (graphics, webGLData) +{ var gl = this.renderer.gl; this.bindGraphics(graphics, webGLData, this.renderer); - if (this.stencilStack.length === 0) { + if (this.stencilStack.length === 0) + { gl.enable(gl.STENCIL_TEST); gl.clear(gl.STENCIL_BUFFER_BIT); this.reverse = true; @@ -47,14 +50,17 @@ // draw the triangle strip! - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } @@ -62,31 +68,38 @@ // draw a quad to increment.. gl.drawElements(gl.TRIANGLE_FAN, 4, gl.UNSIGNED_SHORT, ( webGLData.indices.length - 4 ) * 2 ); - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); } this.reverse = !this.reverse; } - else { - if (!this.reverse) { + else + { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } - else { + 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) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); } } @@ -103,7 +116,8 @@ * @param graphics {Graphics} * @param webGLData {Array} */ -WebGLStencilManager.prototype.bindGraphics = function (graphics, webGLData) { +WebGLStencilManager.prototype.bindGraphics = function (graphics, webGLData) +{ //if (this._currentGraphics === graphics)return; this._currentGraphics = graphics; @@ -114,7 +128,8 @@ offset = this.renderer.offset, shader;// = this.renderer.shaderManager.primitiveShader; - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { shader = this.renderer.shaderManager.complexPrimitiveShader; this.renderer.shaderManager.setShader(shader); @@ -141,7 +156,8 @@ // set the index buffer! gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, webGLData.indexBuffer); } - else { + else + { //this.renderer.shaderManager.activatePrimitiveShader(); shader = this.renderer.shaderManager.primitiveShader; this.renderer.shaderManager.setShader( shader ); @@ -154,7 +170,7 @@ gl.uniform2f(shader.uniforms.offsetVector._location, -offset.x, -offset.y); gl.uniform3fv(shader.uniforms.tint._location, utils.hex2rgb(graphics.tint)); - + gl.uniform1f(shader.uniforms.alpha._location, graphics.worldAlpha); @@ -172,19 +188,22 @@ * @param graphics {Graphics} * @param webGLData {Array} */ -WebGLStencilManager.prototype.popStencil = function (graphics, webGLData) { +WebGLStencilManager.prototype.popStencil = function (graphics, webGLData) +{ var gl = this.renderer.gl; this.stencilStack.pop(); this.count--; - if (this.stencilStack.length === 0) { + if (this.stencilStack.length === 0) + { // the stack is empty! gl.disable(gl.STENCIL_TEST); } - else { + else + { var level = this.count; @@ -192,14 +211,17 @@ gl.colorMask(false, false, false, false); - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { this.reverse = !this.reverse; - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } @@ -213,31 +235,38 @@ // draw the triangle strip! gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); - if (!this.reverse) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); } } - else { + else + { // console.log("<<>>") - if (!this.reverse) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } - else { + 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) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); } } @@ -253,7 +282,8 @@ * Destroys the mask stack. * */ -WebGLStencilManager.prototype.destroy = function () { +WebGLStencilManager.prototype.destroy = function () +{ this.renderer = null; this.stencilStack = null; }; diff --git a/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js b/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js index 913ba5e..1ea7d19 100644 --- a/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js +++ b/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function ComplexPrimitiveShader(gl) { +function ComplexPrimitiveShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -24,7 +25,8 @@ 'uniform float flipY;', 'varying vec4 vColor;', - 'void main(void) {', + '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);', @@ -37,7 +39,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = vColor;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/FastShader.js b/src/core/renderers/webgl/shaders/FastShader.js index bd2e29a..2e5e060 100644 --- a/src/core/renderers/webgl/shaders/FastShader.js +++ b/src/core/renderers/webgl/shaders/FastShader.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function FastShader(gl) { +function FastShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -28,7 +29,8 @@ 'const vec2 center = vec2(-1.0, 1.0);', - 'void main(void) {', + 'void main(void) + {', ' vec2 v;', ' vec2 sv = aVertexPosition * aScale;', ' v.x = (sv.x) * cos(aRotation) - (sv.y) * sin(aRotation);', @@ -49,7 +51,8 @@ 'uniform sampler2D uSampler;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/PrimitiveShader.js b/src/core/renderers/webgl/shaders/PrimitiveShader.js index 6f25409..a25f54f 100644 --- a/src/core/renderers/webgl/shaders/PrimitiveShader.js +++ b/src/core/renderers/webgl/shaders/PrimitiveShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function PrimitiveShader(gl) { +function PrimitiveShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -23,7 +24,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + '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);', @@ -36,7 +38,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = vColor;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/Shader.js b/src/core/renderers/webgl/shaders/Shader.js index f8964f5..fd75ef5 100644 --- a/src/core/renderers/webgl/shaders/Shader.js +++ b/src/core/renderers/webgl/shaders/Shader.js @@ -6,7 +6,8 @@ * @param [fragmentSrc] {string} The source of the fragment shader. * @param [vertexSrc] {string} The source of the vertex shader. */ -function Shader(gl, vertexSrc, fragmentSrc, customUniforms, customAttributes) { +function Shader(gl, vertexSrc, fragmentSrc, customUniforms, customAttributes) +{ /** * @member {number} * @readonly @@ -33,7 +34,8 @@ dimensions: { type: '4f', value: new Float32Array(4) } }; - for (var u in customUniforms) { + for (var u in customUniforms) + { this.uniforms[u] = customUniforms[u]; } @@ -43,7 +45,8 @@ aColor: 0 }; - for (var a in customAttributes) { + for (var a in customAttributes) + { this.attributes[a] = customAttributes[a]; } @@ -66,7 +69,8 @@ 'const vec2 center = vec2(-1.0, 1.0);', - 'void main(void) {', + 'void main(void) + {', ' gl_Position = vec4( ((aVertexPosition + offsetVector) / projectionVector) + center , 0.0, 1.0);', ' vTextureCoord = aTextureCoord;', ' vColor = vec4(aColor.rgb * aColor.a, aColor.a);', @@ -85,7 +89,8 @@ 'uniform sampler2D uSampler;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;', '}' ].join('\n'); @@ -96,7 +101,8 @@ Shader.prototype.constructor = Shader; module.exports = Shader; -Shader.prototype.init = function () { +Shader.prototype.init = function () +{ this.compile(); this.gl.useProgram(this.program); @@ -105,14 +111,18 @@ this.cacheAttributeLocations(Object.keys(this.attributes)); }; -Shader.prototype.cacheUniformLocations = function (keys) { - for (var i = 0; i < keys.length; ++i) { +Shader.prototype.cacheUniformLocations = function (keys) +{ + for (var i = 0; i < keys.length; ++i) + { this.uniforms[keys[i]]._location = this.gl.getUniformLocation(this.program, keys[i]); } }; -Shader.prototype.cacheAttributeLocations = function (keys) { - for (var i = 0; i < keys.length; ++i) { +Shader.prototype.cacheAttributeLocations = function (keys) +{ + for (var i = 0; i < keys.length; ++i) + { this.attributes[keys[i]] = this.gl.getAttribLocation(this.program, keys[i]); } @@ -124,14 +134,16 @@ // 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.attributes.aColor === -1) { + // if (this.attributes.aColor === -1) + { // this.attributes.aColor = 2; // } // End worst hack eva // }; -Shader.prototype.compile = function () { +Shader.prototype.compile = function () +{ var gl = this.gl; var glVertShader = this._glCompile(gl.VERTEX_SHADER, this.vertexSrc); @@ -144,13 +156,15 @@ gl.linkProgram(program); // if linking fails, then log and cleanup - if (!gl.getProgramParameter(program, gl.LINK_STATUS)) { + if (!gl.getProgramParameter(program, gl.LINK_STATUS)) + { window.console.error('Pixi.js Error: Could not initialize shader.'); window.console.error('gl.VALIDATE_STATUS', gl.getProgramParameter(program, gl.VALIDATE_STATUS)); window.console.error('gl.getError()', gl.getError()); // if there is a program info log, log it - if (gl.getProgramInfoLog(program) !== '') { + if (gl.getProgramInfoLog(program) !== '') + { window.console.warn('Pixi.js Warning: gl.getProgramInfoLog()', gl.getProgramInfoLog(program)); } @@ -165,18 +179,21 @@ return (this.program = program); }; -Shader.prototype.syncUniforms = function () { +Shader.prototype.syncUniforms = function () +{ var gl = this.gl; this.textureCount = 1; - for (var key in this.uniforms) { + for (var key in this.uniforms) + { var uniform = this.uniforms[key], location = uniform._location, value = uniform.value, i, il; - switch (uniform.type) { + switch (uniform.type) + { // single int value case 'i': case '1i': @@ -282,7 +299,8 @@ // a Color Value case 'c': - if (typeof value === 'number') { + if (typeof value === 'number') + { value = utils.hex2rgb(value); } @@ -311,11 +329,13 @@ // array of 2D Point objects case 'v2v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(2 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 2] = value[i].x; uniform._array[i * 2 + 1] = value[i].y; } @@ -325,11 +345,13 @@ // array of 3D Point objects case 'v3v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(3 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 3] = value[i].x; uniform._array[i * 3 + 1] = value[i].y; uniform._array[i * 3 + 2] = value[i].z; @@ -341,11 +363,13 @@ // array of 4D Point objects case 'v4v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(4 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 4] = value[i].x; uniform._array[i * 4 + 1] = value[i].y; uniform._array[i * 4 + 2] = value[i].z; @@ -359,7 +383,8 @@ // PIXI.Texture case 't': case 'sampler2D': - if (!uniform.value || !uniform.value.baseTexture || !uniform.value.baseTexture.hasLoaded) { + if (!uniform.value || !uniform.value.baseTexture || !uniform.value.baseTexture.hasLoaded) + { break; } @@ -376,7 +401,8 @@ this.textureCount++; // initialize the texture if we haven't yet - if (!uniform._init) { + if (!uniform._init) + { this.initSampler2D(uniform); uniform._init = true; @@ -394,11 +420,13 @@ * Initialises a Sampler2D uniform (which may only be available later on after initUniforms once the texture has loaded) * */ -Shader.prototype.initSampler2D = function (uniform) { +Shader.prototype.initSampler2D = function (uniform) +{ var gl = this.gl; // Extended texture data - if (uniform.textureData) { + if (uniform.textureData) + { var data = uniform.textureData; // GLTexture = mag linear, min linear_mipmap_linear, wrap repeat + gl.generateMipmap(gl.TEXTURE_2D); @@ -417,14 +445,16 @@ var wrapT = (data.wrapT) ? data.wrapT : gl.CLAMP_TO_EDGE; var format = (data.luminance) ? gl.LUMINANCE : gl.RGBA; - if (data.repeat) { + if (data.repeat) + { wrapS = gl.REPEAT; wrapT = gl.REPEAT; } gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, !!data.flipY); - if (data.width) { + if (data.width) + { var width = (data.width) ? data.width : 512; var height = (data.height) ? data.height : 2; var border = (data.border) ? data.border : 0; @@ -432,7 +462,8 @@ // 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 { + 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); } @@ -448,7 +479,8 @@ * Destroys the shader. * */ -Shader.prototype.destroy = function () { +Shader.prototype.destroy = function () +{ this.gl.deleteProgram(this.program); this.gl = null; @@ -459,13 +491,15 @@ this.fragmentSrc = null; }; -Shader.prototype._glCompile = function (type, src) { +Shader.prototype._glCompile = function (type, src) +{ var shader = this.gl.createShader(type); this.gl.shaderSource(shader, src); this.gl.compileShader(shader); - if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) { + if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) + { window.console.log(this.gl.getShaderInfoLog(shader)); return null; } diff --git a/src/core/renderers/webgl/shaders/StripShader.js b/src/core/renderers/webgl/shaders/StripShader.js index 193f6e1..a7abcc6 100644 --- a/src/core/renderers/webgl/shaders/StripShader.js +++ b/src/core/renderers/webgl/shaders/StripShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function StripShader(gl) { +function StripShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -20,7 +21,8 @@ 'varying vec2 vTextureCoord;', - 'void main(void) {', + '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);', @@ -36,7 +38,8 @@ 'varying vec2 vTextureCoord;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vec2(vTextureCoord.x, vTextureCoord.y)) * alpha;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/utils/FilterTexture.js b/src/core/renderers/webgl/utils/FilterTexture.js index d2c8423..4433d44 100644 --- a/src/core/renderers/webgl/utils/FilterTexture.js +++ b/src/core/renderers/webgl/utils/FilterTexture.js @@ -8,7 +8,8 @@ * @param height {number} the vertical range of the filter * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values */ -function FilterTexture(gl, width, height, scaleMode) { +function FilterTexture(gl, width, height, scaleMode) +{ /** * @member {WebGLContext} */ @@ -59,7 +60,8 @@ * Clears the filter texture. * */ -FilterTexture.prototype.clear = function () { +FilterTexture.prototype.clear = function () +{ var gl = this.gl; gl.clearColor(0,0,0, 0); @@ -72,8 +74,10 @@ * @param width {number} the new width of the texture * @param height {number} the new height of the texture */ -FilterTexture.prototype.resize = function (width, height) { - if (this.width === width && this.height === height) { +FilterTexture.prototype.resize = function (width, height) +{ + if (this.width === width && this.height === height) + { return; } @@ -96,7 +100,8 @@ * Destroys the filter texture. * */ -FilterTexture.prototype.destroy = function () { +FilterTexture.prototype.destroy = function () +{ var gl = this.gl; gl.deleteFramebuffer( this.frameBuffer ); gl.deleteTexture( this.texture ); diff --git a/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js b/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js index c4721e9..a63f4d7 100644 --- a/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js +++ b/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js @@ -14,7 +14,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this sprite batch works for. */ -function WebGLFastSpriteBatch(renderer) { +function WebGLFastSpriteBatch(renderer) +{ /** * The renderer instance this sprite batch operates on. * @@ -91,7 +92,8 @@ */ this.lastIndexCount = 0; - for (var i=0, j=0; i < numIndices; i += 6, j += 4) { + 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; @@ -144,7 +146,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.setupContext(); }); } @@ -157,7 +160,8 @@ * * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLFastSpriteBatch.prototype.setupContext = function () { +WebGLFastSpriteBatch.prototype.setupContext = function () +{ var gl = this.renderer.gl; // create a couple of buffers @@ -177,7 +181,8 @@ /** * @param spriteBatch {SpriteBatch} The SpriteBatch container to prepare for. */ -WebGLFastSpriteBatch.prototype.begin = function (spriteBatch) { +WebGLFastSpriteBatch.prototype.begin = function (spriteBatch) +{ this.shader = this.renderer.shaderManager.fastShader; this.matrix = spriteBatch.worldTransform.toArray(true); @@ -187,33 +192,38 @@ /** */ -WebGLFastSpriteBatch.prototype.end = function () { +WebGLFastSpriteBatch.prototype.end = function () +{ this.flush(); }; /** * @param spriteBatch {SpriteBatch} The SpriteBatch container to render. */ -WebGLFastSpriteBatch.prototype.render = function (spriteBatch) { +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) { + if (!sprite.texture._uvs) + { return; } this.currentBaseTexture = sprite.texture.baseTexture; // check blend mode - if (sprite.blendMode !== this.renderer.blendModeManager.currentBlendMode) { + if (sprite.blendMode !== this.renderer.blendModeManager.currentBlendMode) + { this.flush(); this.renderer.blendModeManager.setBlendMode(sprite.blendMode); } - for (var i=0,j= children.length; i= this.size) { + if (this.currentBatchSize >= this.size) + { this.flush(); } }; @@ -362,29 +379,35 @@ /** * */ -WebGLFastSpriteBatch.prototype.flush = function () { +WebGLFastSpriteBatch.prototype.flush = function () +{ // If the batch is length 0 then return as there is nothing to draw - if (this.currentBatchSize === 0) { + if (this.currentBatchSize === 0) + { return; } var gl = this.renderer.gl; // bind the current texture - if (!this.currentBaseTexture._glTextures[gl.id]) { + if (!this.currentBaseTexture._glTextures[gl.id]) + { this.renderer.updateTexture(this.currentBaseTexture, gl); } //TODO-SHOUD THIS BE ELSE??!?!?! - else { + else + { gl.bindTexture(gl.TEXTURE_2D, this.currentBaseTexture._glTextures[gl.id]); } // upload the verts to the buffer - if (this.currentBatchSize > ( this.size * 0.5 ) ) { + if (this.currentBatchSize > ( this.size * 0.5 ) ) + { gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); } - else { + else + { var view = this.vertices.subarray(0, this.currentBatchSize * this.vertByteSize); gl.bufferSubData(gl.ARRAY_BUFFER, 0, view); @@ -405,14 +428,16 @@ * Ends the batch and flushes * */ -WebGLFastSpriteBatch.prototype.stop = function () { +WebGLFastSpriteBatch.prototype.stop = function () +{ this.flush(); }; /** * */ -WebGLFastSpriteBatch.prototype.start = function () { +WebGLFastSpriteBatch.prototype.start = function () +{ var gl = this.renderer.gl; // bind the main texture diff --git a/src/core/renderers/webgl/utils/WebGLGraphics.js b/src/core/renderers/webgl/utils/WebGLGraphics.js index 55f4911..ab8f46e 100644 --- a/src/core/renderers/webgl/utils/WebGLGraphics.js +++ b/src/core/renderers/webgl/utils/WebGLGraphics.js @@ -19,7 +19,8 @@ * @param graphics {Graphics} * @param renderer {WebGLRenderer} */ -WebGLGraphics.renderGraphics = function (graphics, renderer) {//projection, offset) { +WebGLGraphics.renderGraphics = function (graphics, renderer) {//projection, offset) +{ var gl = renderer.gl; var projection = renderer.projection, @@ -27,7 +28,8 @@ shader = renderer.shaderManager.primitiveShader, webGLData; - if (graphics.dirty) { + if (graphics.dirty) + { WebGLGraphics.updateGraphics(graphics, gl); } @@ -35,8 +37,10 @@ // This could be speeded up for sure! - for (var i = 0; i < webGL.data.length; i++) { - if (webGL.data[i].mode === 1) { + for (var i = 0; i < webGL.data.length; i++) + { + if (webGL.data[i].mode === 1) + { webGLData = webGL.data[i]; renderer.stencilManager.pushStencil(graphics, webGLData, renderer); @@ -46,7 +50,8 @@ renderer.stencilManager.popStencil(graphics, webGLData, renderer); } - else { + else + { webGLData = webGL.data[i]; @@ -84,12 +89,14 @@ * @param graphicsData {Graphics} The graphics object to update * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLGraphics.updateGraphics = function (graphics, gl) { +WebGLGraphics.updateGraphics = function (graphics, gl) +{ // get the contexts graphics object var webGL = graphics._webGL[gl.id]; // if the graphics object does not exist in the webGL context time to create it! - if (!webGL) { + if (!webGL) + { webGL = graphics._webGL[gl.id] = {lastIndex:0, data:[], gl:gl}; } @@ -99,11 +106,13 @@ var i; // if the user cleared the graphics object we will need to clear every object - if (graphics.clearDirty) { + if (graphics.clearDirty) + { graphics.clearDirty = false; // lop through and return all the webGLDatas to the object pool so than can be reused later on - for (i = 0; i < webGL.data.length; i++) { + for (i = 0; i < webGL.data.length; i++) + { var graphicsData = webGL.data[i]; graphicsData.reset(); WebGLGraphics.graphicsDataPool.push( graphicsData ); @@ -119,58 +128,72 @@ // loop through the graphics datas and construct each one.. // if the object is a complex fill then the new stencil buffer technique will be used // other wise graphics objects will be pushed into a batch.. - for (i = webGL.lastIndex; i < graphics.graphicsData.length; i++) { + for (i = webGL.lastIndex; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { // need to add the points the the graphics object.. data.points = data.shape.points.slice(); - if (data.shape.closed) { + if (data.shape.closed) + { // close the poly if the value is true! - if (data.points[0] !== data.points[data.points.length-2] || data.points[1] !== data.points[data.points.length-1]) { + if (data.points[0] !== data.points[data.points.length-2] || data.points[1] !== data.points[data.points.length-1]) + { data.points.push(data.points[0], data.points[1]); } } // MAKE SURE WE HAVE THE CORRECT TYPE.. - if (data.fill) { - if (data.points.length >= 6) { - if (data.points.length < 6 * 2) { + if (data.fill) + { + if (data.points.length >= 6) + { + if (data.points.length < 6 * 2) + { webGLData = WebGLGraphics.switchMode(webGL, 0); var canDrawUsingSimple = WebGLGraphics.buildPoly(data, webGLData); // console.log(canDrawUsingSimple); - if (!canDrawUsingSimple) { + if (!canDrawUsingSimple) + { // console.log("<>>>") webGLData = WebGLGraphics.switchMode(webGL, 1); WebGLGraphics.buildComplexPoly(data, webGLData); } } - else { + else + { webGLData = WebGLGraphics.switchMode(webGL, 1); WebGLGraphics.buildComplexPoly(data, webGLData); } } } - if (data.lineWidth > 0) { + if (data.lineWidth > 0) + { webGLData = WebGLGraphics.switchMode(webGL, 0); WebGLGraphics.buildLine(data, webGLData); } } - else { + else + { webGLData = WebGLGraphics.switchMode(webGL, 0); - if (data.type === CONST.SHAPES.RECT) { + if (data.type === CONST.SHAPES.RECT) + { WebGLGraphics.buildRectangle(data, webGLData); } - else if (data.type === CONST.SHAPES.CIRC || data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.CIRC || data.type === CONST.SHAPES.ELIP) + { WebGLGraphics.buildCircle(data, webGLData); } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { WebGLGraphics.buildRoundedRectangle(data, webGLData); } } @@ -179,10 +202,12 @@ } // upload all the dirty data... - for (i = 0; i < webGL.data.length; i++) { + for (i = 0; i < webGL.data.length; i++) + { webGLData = webGL.data[i]; - if (webGLData.dirty) { + if (webGLData.dirty) + { webGLData.upload(); } } @@ -194,18 +219,22 @@ * @param webGL {WebGLContext} * @param type {number} */ -WebGLGraphics.switchMode = function (webGL, type) { +WebGLGraphics.switchMode = function (webGL, type) +{ var webGLData; - if (!webGL.data.length) { + if (!webGL.data.length) + { webGLData = WebGLGraphics.graphicsDataPool.pop() || new WebGLGraphicsData(webGL.gl); webGLData.mode = type; webGL.data.push(webGLData); } - else { + else + { webGLData = webGL.data[webGL.data.length-1]; - if (webGLData.mode !== type || type === 1) { + if (webGLData.mode !== type || type === 1) + { webGLData = WebGLGraphics.graphicsDataPool.pop() || new WebGLGraphicsData(webGL.gl); webGLData.mode = type; webGL.data.push(webGLData); @@ -225,7 +254,8 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildRectangle = function (graphicsData, webGLData) { +WebGLGraphics.buildRectangle = function (graphicsData, webGLData) +{ // --- // // need to convert points to a nice regular data // @@ -235,7 +265,8 @@ var width = rectData.width; var height = rectData.height; - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -265,7 +296,8 @@ indices.push(vertPos, vertPos, vertPos+1, vertPos+2, vertPos+3, vertPos+3); } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = [x, y, @@ -289,7 +321,8 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildRoundedRectangle = function (graphicsData, webGLData) { +WebGLGraphics.buildRoundedRectangle = function (graphicsData, webGLData) +{ var rrectData = graphicsData.shape; var x = rrectData.x; var y = rrectData.y; @@ -305,7 +338,8 @@ recPoints = recPoints.concat(WebGLGraphics.quadraticBezierCurve(x + width, y + radius, x + width, y, x + width - radius, y)); recPoints = recPoints.concat(WebGLGraphics.quadraticBezierCurve(x + radius, y, x, y, x, y + radius)); - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -323,7 +357,8 @@ // var i = 0; - for (i = 0; i < triangles.length; i+=3) { + for (i = 0; i < triangles.length; i+=3) + { indices.push(triangles[i] + vecPos); indices.push(triangles[i] + vecPos); indices.push(triangles[i+1] + vecPos); @@ -332,12 +367,14 @@ } - for (i = 0; i < recPoints.length; i++) { + for (i = 0; i < recPoints.length; i++) + { verts.push(recPoints[i], recPoints[++i], r, g, b, alpha); } } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = recPoints; @@ -362,7 +399,8 @@ * @param toY {number} Destination point y * @return {number[]} */ -WebGLGraphics.quadraticBezierCurve = function (fromX, fromY, cpX, cpY, toX, toY) { +WebGLGraphics.quadraticBezierCurve = function (fromX, fromY, cpX, cpY, toX, toY) +{ var xa, ya, @@ -373,14 +411,16 @@ n = 20, points = []; - function getPt(n1 , n2, perc) { + function getPt(n1 , n2, perc) + { var diff = n2 - n1; return n1 + ( diff * perc ); } var j = 0; - for (var i = 0; i <= n; i++ ) { + for (var i = 0; i <= n; i++ ) + { j = i / n; // The Green Line @@ -406,7 +446,8 @@ * @param graphicsData {Graphics} The graphics object to draw * @param webGLData {object} */ -WebGLGraphics.buildCircle = function (graphicsData, webGLData) { +WebGLGraphics.buildCircle = function (graphicsData, webGLData) +{ // need to convert points to a nice regular data var circleData = graphicsData.shape; var x = circleData.x; @@ -415,11 +456,13 @@ var height; // TODO - bit hacky?? - if (graphicsData.type === CONST.SHAPES.CIRC) { + if (graphicsData.type === CONST.SHAPES.CIRC) + { width = circleData.radius; height = circleData.radius; } - else { + else + { width = circleData.width; height = circleData.height; } @@ -429,7 +472,8 @@ var i = 0; - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -444,7 +488,8 @@ indices.push(vecPos); - for (i = 0; i < totalSegs + 1 ; i++) { + for (i = 0; i < totalSegs + 1 ; i++) + { verts.push(x,y, r, g, b, alpha); verts.push(x + Math.sin(seg * i) * width, @@ -457,12 +502,14 @@ indices.push(vecPos-1); } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = []; - for (i = 0; i < totalSegs + 1; i++) { + for (i = 0; i < totalSegs + 1; i++) + { graphicsData.points.push(x + Math.sin(seg * i) * width, y + Math.cos(seg * i) * height); } @@ -481,18 +528,22 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildLine = function (graphicsData, webGLData) { +WebGLGraphics.buildLine = function (graphicsData, webGLData) +{ // TODO OPTIMISE! var i = 0; var points = graphicsData.points; - if (points.length === 0) { + if (points.length === 0) + { return; } // if the line width is an odd number add 0.5 to align to a whole pixel - if (graphicsData.lineWidth%2) { - for (i = 0; i < points.length; i++) { + if (graphicsData.lineWidth%2) + { + for (i = 0; i < points.length; i++) + { points[i] += 0.5; } } @@ -502,7 +553,8 @@ var lastPoint = new math.Point(points[points.length - 2], points[points.length - 1]); // if the first point is the last point - gonna have issues :) - if (firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) { + if (firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) + { // need to clone as we are going to slightly modify the shape.. points = points.slice(); @@ -562,7 +614,8 @@ verts.push(p1x + perpx , p1y + perpy, r, g, b, alpha); - for (i = 1; i < length-1; i++) { + for (i = 1; i < length-1; i++) + { p1x = points[(i-1)*2]; p1y = points[(i-1)*2 + 1]; @@ -599,7 +652,8 @@ denom = a1*b2 - a2*b1; - if (Math.abs(denom) < 0.1 ) { + if (Math.abs(denom) < 0.1 ) + { denom+=10.1; verts.push(p2x - perpx , p2y - perpy, @@ -618,7 +672,8 @@ pdist = (px -p2x) * (px -p2x) + (py -p2y) + (py -p2y); - if (pdist > 140 * 140) { + if (pdist > 140 * 140) + { perp3x = perpx - perp2x; perp3y = perpy - perp2y; @@ -639,7 +694,8 @@ indexCount++; } - else { + else + { verts.push(px , py); verts.push(r, g, b, alpha); @@ -672,7 +728,8 @@ indices.push(indexStart); - for (i = 0; i < indexCount; i++) { + for (i = 0; i < indexCount; i++) + { indices.push(indexStart++); } @@ -687,11 +744,13 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildComplexPoly = function (graphicsData, webGLData) { +WebGLGraphics.buildComplexPoly = function (graphicsData, webGLData) +{ //TODO - no need to copy this as it gets turned into a FLoat32Array anyways.. var points = graphicsData.points.slice(); - if (points.length < 6) { + if (points.length < 6) + { return; } @@ -711,7 +770,8 @@ var x,y; // get size.. - for (var i = 0; i < points.length; i+=2) { + for (var i = 0; i < points.length; i+=2) + { x = points[i]; y = points[i+1]; @@ -732,7 +792,8 @@ //TODO - this aint needed! var length = points.length / 2; - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { indices.push( i ); } @@ -746,10 +807,12 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildPoly = function (graphicsData, webGLData) { +WebGLGraphics.buildPoly = function (graphicsData, webGLData) +{ var points = graphicsData.points; - if (points.length < 6) { + if (points.length < 6) + { return; } // get first and last point.. figure out the middle! @@ -767,7 +830,8 @@ var triangles = utils.PolyK.Triangulate(points); - if (!triangles) { + if (!triangles) + { return false; } @@ -775,7 +839,8 @@ var i = 0; - for (i = 0; i < triangles.length; i+=3) { + for (i = 0; i < triangles.length; i+=3) + { indices.push(triangles[i] + vertPos); indices.push(triangles[i] + vertPos); indices.push(triangles[i+1] + vertPos); @@ -783,7 +848,8 @@ indices.push(triangles[i+2] + vertPos); } - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { verts.push(points[i * 2], points[i * 2 + 1], r, g, b, alpha); } diff --git a/src/core/renderers/webgl/utils/WebGLGraphicsData.js b/src/core/renderers/webgl/utils/WebGLGraphicsData.js index c56d05e..c739ba7 100644 --- a/src/core/renderers/webgl/utils/WebGLGraphicsData.js +++ b/src/core/renderers/webgl/utils/WebGLGraphicsData.js @@ -2,7 +2,8 @@ * @class * @private */ -function WebGLGraphicsData(gl) { +function WebGLGraphicsData(gl) +{ this.gl = gl; //TODO does this need to be split before uploding?? @@ -22,7 +23,8 @@ /** * */ -WebGLGraphicsData.prototype.reset = function () { +WebGLGraphicsData.prototype.reset = function () +{ this.points.length = 0; this.indices.length = 0; }; @@ -30,7 +32,8 @@ /** * */ -WebGLGraphicsData.prototype.upload = function () { +WebGLGraphicsData.prototype.upload = function () +{ var gl = this.gl; // this.lastIndex = graphics.graphicsData.length; diff --git a/src/core/renderers/webgl/utils/WebGLSpriteBatch.js b/src/core/renderers/webgl/utils/WebGLSpriteBatch.js index 96eaa52..55befbb 100644 --- a/src/core/renderers/webgl/utils/WebGLSpriteBatch.js +++ b/src/core/renderers/webgl/utils/WebGLSpriteBatch.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this sprite batch works for. */ -function WebGLSpriteBatch(renderer) { +function WebGLSpriteBatch(renderer) +{ /** * * @@ -88,7 +89,8 @@ */ this.lastIndexCount = 0; - for (var i=0, j=0; i < numIndices; i += 6, j += 4) { + 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; @@ -162,7 +164,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.setupContext(); }); } @@ -173,7 +176,8 @@ /** * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLSpriteBatch.prototype.setupContext = function () { +WebGLSpriteBatch.prototype.setupContext = function () +{ var gl = this.renderer.gl; // setup default shader @@ -198,7 +202,8 @@ /** * */ -WebGLSpriteBatch.prototype.begin = function () { +WebGLSpriteBatch.prototype.begin = function () +{ // this.shader = this.renderer.shaderManager.defaultShader; this.start(); @@ -206,19 +211,22 @@ /** */ -WebGLSpriteBatch.prototype.end = function () { +WebGLSpriteBatch.prototype.end = function () +{ this.flush(); }; /** * @param sprite {Sprite} the sprite to render when using this spritebatch */ -WebGLSpriteBatch.prototype.render = function (sprite) { +WebGLSpriteBatch.prototype.render = function (sprite) +{ var texture = sprite.texture; //TODO set blend modes.. // check texture.. - if (this.currentBatchSize >= this.size) { + if (this.currentBatchSize >= this.size) + { this.flush(); this.currentBaseTexture = texture.baseTexture; } @@ -227,7 +235,8 @@ var uvs = texture._uvs; // if the uvs have not updated then no point rendering just yet! - if (!uvs) { + if (!uvs) + { return; } @@ -237,7 +246,8 @@ var w0, w1, h0, h1; - if (texture.trim) { + 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; @@ -248,7 +258,8 @@ h0 = h1 + texture.crop.height; } - else { + else + { w0 = (texture.frame.width ) * (1-aX); w1 = (texture.frame.width ) * -aX; @@ -272,7 +283,8 @@ var colors = this.colors; var positions = this.positions; - if (this.renderer.roundPixels) { + if (this.renderer.roundPixels) + { // xy positions[index] = a * w1 + c * h1 + tx | 0; positions[index+1] = d * h1 + b * w1 + ty | 0; @@ -289,7 +301,8 @@ positions[index+15] = a * w1 + c * h0 + tx | 0; positions[index+16] = d * h0 + b * w1 + ty | 0; } - else { + else + { // xy positions[index] = a * w1 + c * h1 + tx; positions[index+1] = d * h1 + b * w1 + ty; @@ -338,11 +351,13 @@ * * @param sprite {TilingSprite} the tilingSprite to render */ -WebGLSpriteBatch.prototype.renderTilingSprite = function (tilingSprite) { +WebGLSpriteBatch.prototype.renderTilingSprite = function (tilingSprite) +{ var texture = tilingSprite.tilingTexture; // check texture.. - if (this.currentBatchSize >= this.size) { + if (this.currentBatchSize >= this.size) + { //return; this.flush(); this.currentBaseTexture = texture.baseTexture; @@ -351,7 +366,8 @@ // set the textures uvs temporarily // TODO create a separate texture so that we can tile part of a texture - if (!tilingSprite._uvs) { + if (!tilingSprite._uvs) + { tilingSprite._uvs = new TextureUvs(); } @@ -454,16 +470,19 @@ * Renders the content and empties the current batch. * */ -WebGLSpriteBatch.prototype.flush = function () { +WebGLSpriteBatch.prototype.flush = function () +{ // If the batch is length 0 then return as there is nothing to draw - if (this.currentBatchSize === 0) { + if (this.currentBatchSize === 0) + { return; } var gl = this.renderer.gl; var shader; - if (this.dirty) { + if (this.dirty) + { this.dirty = false; // bind the main texture gl.activeTexture(gl.TEXTURE0); @@ -482,10 +501,12 @@ } // upload the verts to the buffer - if (this.currentBatchSize > ( this.size * 0.5 ) ) { + if (this.currentBatchSize > ( this.size * 0.5 ) ) + { gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); } - else { + else + { var view = this.positions.subarray(0, this.currentBatchSize * this.vertByteSize); gl.bufferSubData(gl.ARRAY_BUFFER, 0, view); } @@ -502,7 +523,8 @@ var shaderSwap = false; var sprite; - for (var i = 0, j = this.currentBatchSize; i < j; i++) { + for (var i = 0, j = this.currentBatchSize; i < j; i++) + { sprite = this.sprites[i]; @@ -513,24 +535,28 @@ blendSwap = currentBlendMode !== nextBlendMode; shaderSwap = currentShader !== nextShader; // should I use uuidS??? - if (currentBaseTexture !== nextTexture || blendSwap || shaderSwap) { + if (currentBaseTexture !== nextTexture || blendSwap || shaderSwap) + { this.renderBatch(currentBaseTexture, batchSize, start); start = i; batchSize = 0; currentBaseTexture = nextTexture; - if (blendSwap) { + if (blendSwap) + { currentBlendMode = nextBlendMode; this.renderer.blendModeManager.setBlendMode( currentBlendMode ); } - if (shaderSwap) { + if (shaderSwap) + { currentShader = nextShader; shader = currentShader.shaders ? currentShader.shaders[gl.id] : currentShader; - if (!shader) { + if (!shader) + { shader = new Shader(gl, null, currentShader.fragmentSrc, currentShader.uniforms); currentShader.shaders[gl.id] = shader; } @@ -538,7 +564,8 @@ // set shader function??? this.renderer.shaderManager.setShader(shader); - if (shader.dirty) { + if (shader.dirty) + { shader.syncUniforms(); } @@ -569,17 +596,21 @@ * @param size {number} * @param startIndex {number} */ -WebGLSpriteBatch.prototype.renderBatch = function (texture, size, startIndex) { - if (size === 0) { +WebGLSpriteBatch.prototype.renderBatch = function (texture, size, startIndex) +{ + if (size === 0) + { return; } var gl = this.renderer.gl; - if (!texture._glTextures[gl.id]) { + if (!texture._glTextures[gl.id]) + { this.renderer.updateTexture(texture); } - else { + else + { // bind the current texture gl.bindTexture(gl.TEXTURE_2D, texture._glTextures[gl.id]); } @@ -594,7 +625,8 @@ /** * */ -WebGLSpriteBatch.prototype.stop = function () { +WebGLSpriteBatch.prototype.stop = function () +{ this.flush(); this.dirty = true; }; @@ -602,7 +634,8 @@ /** * */ -WebGLSpriteBatch.prototype.start = function () { +WebGLSpriteBatch.prototype.start = function () +{ this.dirty = true; }; @@ -610,7 +643,8 @@ * Destroys the SpriteBatch. * */ -WebGLSpriteBatch.prototype.destroy = function () { +WebGLSpriteBatch.prototype.destroy = function () +{ this.renderer.gl.deleteBuffer(this.vertexBuffer); this.renderer.gl.deleteBuffer(this.indexBuffer); diff --git a/src/core/textures/BaseTexture.js b/src/core/textures/BaseTexture.js index 2bf77d4..513d358 100644 --- a/src/core/textures/BaseTexture.js +++ b/src/core/textures/BaseTexture.js @@ -10,7 +10,8 @@ * @param source {Image|Canvas} the source object of the texture. * @param [scaleMode=scaleModes.DEFAULT] {number} See {@link scaleModes} for possible values */ -function BaseTexture(source, scaleMode) { +function BaseTexture(source, scaleMode) +{ this.uuid = utils.uuid(); /** @@ -123,7 +124,8 @@ this._needsUpdate = false; // if no source passed don't try to load - if (source) { + if (source) + { this.loadSource(source); } @@ -149,13 +151,16 @@ Object.defineProperties(BaseTexture.prototype, { needsUpdate: { - get: function () { + get: function () + { return this._needsUpdate; }, - set: function (val) { + set: function (val) + { this._needsUpdate = val; - if (val) { + if (val) + { this.emit('update', this); } } @@ -171,9 +176,11 @@ * * The logic state after calling `loadSource` directly or indirectly (eg. `fromImage`, `new BaseTexture`) is: * - * if (texture.hasLoaded) { + * if (texture.hasLoaded) + { * // texture ready for use - * } else if (texture.isLoading) { + * } else if (texture.isLoading) + { * // listen to 'loaded' and/or 'error' events on texture * } else { * // not loading, not going to load UNLESS the source is reloaded @@ -183,12 +190,14 @@ * @protected * @param source {Image|Canvas} the source object of the texture. */ -BaseTexture.prototype.loadSource = function (source) { +BaseTexture.prototype.loadSource = function (source) +{ var wasLoading = this.isLoading; this.hasLoaded = false; this.isLoading = false; - if (wasLoading && this.source) { + if (wasLoading && this.source) + { this.source.onload = null; this.source.onerror = null; } @@ -196,20 +205,24 @@ this.source = source; // Apply source if loaded. Otherwise setup appropriate loading monitors. - if ((this.source.complete || this.source.getContext) && this.source.width && this.source.height) { + if ((this.source.complete || this.source.getContext) && this.source.width && this.source.height) + { this._sourceLoaded(); } - else if(!source.getContext) { + else if(!source.getContext) + { // Image fail / not ready this.isLoading = true; var scope = this; - source.onload = function () { + source.onload = function () + { source.onload = null; source.onerror = null; - if(!scope.isLoading) { + if(!scope.isLoading) + { return; } @@ -219,11 +232,13 @@ scope.emit('loaded', scope); }; - source.onerror = function () { + source.onerror = function () + { source.onload = null; source.onerror = null; - if(!scope.isLoading) { + if(!scope.isLoading) + { return; } @@ -234,24 +249,29 @@ // Per http://www.w3.org/TR/html5/embedded-content-0.html#the-img-element // "The value of `complete` can thus change while a script is executing." // So complete needs to be re-checked after the callbacks have been added.. - if (source.complete) { + if (source.complete) + { this.isLoading = false; // ..and if we're complete now, no need for callbacks source.onload = null; source.onerror = null; - if (source.width && source.height) { + if (source.width && source.height) + { this._sourceLoaded(); // If any previous subscribers possible - if (wasLoading) { + if (wasLoading) + { this.emit('loaded', this); } } - else { + else + { // If any previous subscribers possible - if (wasLoading) { + if (wasLoading) + { this.emit('error', this); } } @@ -265,7 +285,8 @@ * * @private */ -BaseTexture.prototype._sourceLoaded = function () { +BaseTexture.prototype._sourceLoaded = function () +{ this.hasLoaded = true; this.width = this.source.naturalWidth || this.source.width; @@ -278,16 +299,20 @@ * Destroys this base texture * */ -BaseTexture.prototype.destroy = function () { - if (this.imageUrl) { +BaseTexture.prototype.destroy = function () +{ + if (this.imageUrl) + { delete utils.BaseTextureCache[this.imageUrl]; delete utils.TextureCache[this.imageUrl]; this.imageUrl = null; - if (!navigator.isCocoonJS) { + if (!navigator.isCocoonJS) + { this.source.src = ''; } } - else if (this.source && this.source._pixiId) { + else if (this.source && this.source._pixiId) + { delete utils.BaseTextureCache[this.source._pixiId]; } this.source = null; @@ -301,7 +326,8 @@ * memory again. * */ -BaseTexture.prototype.dispose = function () { +BaseTexture.prototype.dispose = function () +{ this.emit('dispose', this); }; @@ -311,7 +337,8 @@ * * @param newSrc {string} the path of the image */ -BaseTexture.prototype.updateSourceImage = function (newSrc) { +BaseTexture.prototype.updateSourceImage = function (newSrc) +{ this.source.src = newSrc; this.loadSource(this.source); }; @@ -326,18 +353,22 @@ * @param [scaleMode=scaleModes.DEFAULT] {number} See {@link scaleModes} for possible values * @return BaseTexture */ -BaseTexture.fromImage = function (imageUrl, crossorigin, scaleMode) { +BaseTexture.fromImage = function (imageUrl, crossorigin, scaleMode) +{ var baseTexture = utils.BaseTextureCache[imageUrl]; - if (crossorigin === undefined && imageUrl.indexOf('data:') !== 0) { + if (crossorigin === undefined && imageUrl.indexOf('data:') !== 0) + { crossorigin = true; } - if (!baseTexture) { + if (!baseTexture) + { // new Image() breaks tex loading in some versions of Chrome. // See https://code.google.com/p/chromium/issues/detail?id=238071 var image = new Image();//document.createElement('img'); - if (crossorigin) { + if (crossorigin) + { image.crossOrigin = ''; } @@ -347,7 +378,8 @@ utils.BaseTextureCache[imageUrl] = baseTexture; // if there is an @2x at the end of the url we are going to assume its a highres image - if ( imageUrl.indexOf(CONST.RETINA_PREFIX + '.') !== -1) { + if ( imageUrl.indexOf(CONST.RETINA_PREFIX + '.') !== -1) + { baseTexture.resolution = 2; } } @@ -363,14 +395,17 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return BaseTexture */ -BaseTexture.fromCanvas = function (canvas, scaleMode) { - if (!canvas._pixiId) { +BaseTexture.fromCanvas = function (canvas, scaleMode) +{ + if (!canvas._pixiId) + { canvas._pixiId = 'canvas_' + utils.uuid(); } var baseTexture = utils.BaseTextureCache[canvas._pixiId]; - if (!baseTexture) { + if (!baseTexture) + { baseTexture = new BaseTexture(canvas, scaleMode); utils.BaseTextureCache[canvas._pixiId] = baseTexture; } diff --git a/src/core/textures/RenderTexture.js b/src/core/textures/RenderTexture.js index 6dad20f..53ae796 100644 --- a/src/core/textures/RenderTexture.js +++ b/src/core/textures/RenderTexture.js @@ -46,8 +46,10 @@ * @param [scaleMode] {number} See {@link scaleModes} for possible values * @param [resolution=1] {number} The resolution of the texture being generated */ -function RenderTexture(renderer, width, height, scaleMode, resolution) { - if (!renderer) { +function RenderTexture(renderer, width, height, scaleMode, resolution) +{ + if (!renderer) + { throw new Error('Unable to create RenderTexture, you must pass a renderer into the constructor.'); } @@ -133,7 +135,8 @@ */ this.renderer = renderer; - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { var gl = this.renderer.gl; this.textureBuffer = new FilterTexture(gl, this.width * this.resolution, this.height * this.resolution, this.baseTexture.scaleMode); @@ -142,7 +145,8 @@ this.render = this.renderWebGL; this.projection = new math.Point(this.width*0.5, -this.height*0.5); } - else { + else + { this.render = this.renderCanvas; this.textureBuffer = new CanvasBuffer(this.width* this.resolution, this.height* this.resolution); this.baseTexture.source = this.textureBuffer.canvas; @@ -167,8 +171,10 @@ * @param height {number} The height to resize to. * @param updateBase {boolean} Should the baseTexture.width and height values be resized as well? */ -RenderTexture.prototype.resize = function (width, height, updateBase) { - if (width === this.width && height === this.height) { +RenderTexture.prototype.resize = function (width, height, updateBase) +{ + if (width === this.width && height === this.height) + { return; } @@ -177,17 +183,20 @@ this.width = this.frame.width = this.crop.width = width; this.height = this.frame.height = this.crop.height = height; - if (updateBase) { + if (updateBase) + { this.baseTexture.width = this.width; this.baseTexture.height = this.height; } - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { this.projection.x = this.width / 2; this.projection.y = -this.height / 2; } - if (!this.valid) { + if (!this.valid) + { return; } @@ -198,12 +207,15 @@ * Clears the RenderTexture. * */ -RenderTexture.prototype.clear = function () { - if (!this.valid) { +RenderTexture.prototype.clear = function () +{ + if (!this.valid) + { return; } - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { this.renderer.gl.bindFramebuffer(this.renderer.gl.FRAMEBUFFER, this.textureBuffer.frameBuffer); } @@ -220,19 +232,23 @@ * @param [restoreWorldTransform=true] {boolean} If true the displayObject's worldTransform/worldAlpha and all children * transformations will be restored. Not restoring this information will be a little faster. */ -RenderTexture.prototype.renderWebGL = function (displayObject, matrix, clear, restoreWorldTransform) { - if (!this.valid) { +RenderTexture.prototype.renderWebGL = function (displayObject, matrix, clear, restoreWorldTransform) +{ + if (!this.valid) + { return; } - if (typeof restoreWorldTransform === 'undefined') { + if (typeof restoreWorldTransform === 'undefined') + { restoreWorldTransform = true; } var tempAlpha, tempTransform; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { tempAlpha = displayObject.worldAlpha; tempTransform = displayObject.worldTransform.toArray(); } @@ -245,7 +261,8 @@ wt.identity(); wt.translate(0, this.projection.y * 2); - if (matrix) { + if (matrix) + { wt.append(matrix); } @@ -258,7 +275,8 @@ var children = displayObject.children; var i, j; - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } @@ -269,7 +287,8 @@ gl.bindFramebuffer(gl.FRAMEBUFFER, this.textureBuffer.frameBuffer ); - if (clear) { + if (clear) + { this.textureBuffer.clear(); } @@ -279,11 +298,13 @@ this.renderer.spriteBatch.dirty = true; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { displayObject.worldAlpha = tempAlpha; displayObject.worldTransform.fromArray(tempTransform); - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } } @@ -300,26 +321,31 @@ * @param [restoreWorldTransform=true] {boolean} If true the displayObject's worldTransform/worldAlpha and all children * transformations will be restored. Not restoring this information will be a little faster. */ -RenderTexture.prototype.renderCanvas = function (displayObject, matrix, clear, restoreWorldTransform) { - if (!this.valid) { +RenderTexture.prototype.renderCanvas = function (displayObject, matrix, clear, restoreWorldTransform) +{ + if (!this.valid) + { return; } - if (typeof restoreWorldTransform === 'undefined') { + if (typeof restoreWorldTransform === 'undefined') + { restoreWorldTransform = true; } var tempAlpha, tempTransform; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { tempAlpha = displayObject.worldAlpha; tempTransform = displayObject.worldTransform.toArray(); } var wt = displayObject.worldTransform; wt.identity(); - if (matrix) { + if (matrix) + { wt.append(matrix); } @@ -330,11 +356,13 @@ var children = displayObject.children; var i, j; - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } - if (clear) { + if (clear) + { this.textureBuffer.clear(); } @@ -348,11 +376,13 @@ this.renderer.resolution = realResolution; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { displayObject.worldAlpha = tempAlpha; displayObject.worldTransform.fromArray(tempTransform); - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } } @@ -363,7 +393,8 @@ * * @return {Image} */ -RenderTexture.prototype.getImage = function () { +RenderTexture.prototype.getImage = function () +{ var image = new Image(); image.src = this.getBase64(); return image; @@ -374,7 +405,8 @@ * * @return {string} A base64 encoded string of the texture. */ -RenderTexture.prototype.getBase64 = function () { +RenderTexture.prototype.getBase64 = function () +{ return this.getCanvas().toDataURL(); }; @@ -383,8 +415,10 @@ * * @return {HTMLCanvasElement} A Canvas element with the texture rendered on. */ -RenderTexture.prototype.getCanvas = function () { - if (this.renderer.type === CONST.WEBGL_RENDERER) { +RenderTexture.prototype.getCanvas = function () +{ + if (this.renderer.type === CONST.WEBGL_RENDERER) + { var gl = this.renderer.gl; var width = this.textureBuffer.width; var height = this.textureBuffer.height; @@ -403,7 +437,8 @@ return tempCanvas.canvas; } - else { + else + { return this.textureBuffer.canvas; } }; diff --git a/src/core/textures/Texture.js b/src/core/textures/Texture.js index 3c65909..e97f0aa 100644 --- a/src/core/textures/Texture.js +++ b/src/core/textures/Texture.js @@ -17,7 +17,8 @@ * @param [crop] {Rectangle} The area of original texture * @param [trim] {Rectangle} Trimmed texture rectangle */ -function Texture(baseTexture, frame, crop, trim) { +function Texture(baseTexture, frame, crop, trim) +{ /** * Does this Texture have any frame data assigned to it? * @@ -25,12 +26,14 @@ */ this.noFrame = false; - if (!frame) { + if (!frame) + { this.noFrame = true; frame = new math.Rectangle(0, 0, 1, 1); } - if (baseTexture instanceof Texture) { + if (baseTexture instanceof Texture) + { baseTexture = baseTexture.baseTexture; } @@ -100,13 +103,16 @@ */ this.crop = crop || new math.Rectangle(0, 0, 1, 1); - if (baseTexture.hasLoaded) { - if (this.noFrame) { + if (baseTexture.hasLoaded) + { + if (this.noFrame) + { frame = new math.Rectangle(0, 0, baseTexture.width, baseTexture.height); } this.frame = frame; } - else { + else + { baseTexture.addEventListener('loaded', this.onBaseTextureLoaded.bind(this)); } } @@ -118,19 +124,23 @@ Object.defineProperties(Texture.prototype, { needsUpdate: { - get: function () { + get: function () + { return this.baseTexture.needsUpdate; }, - set: function (val) { + set: function (val) + { this.baseTexture.needsUpdate = val; } }, frame: { - get: function () { + get: function () + { return this._frame; }, - set: function (frame) { + set: function (frame) + { this._frame = frame; this.noFrame = false; @@ -143,20 +153,23 @@ 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 (!this.trim && (frame.x + frame.width > this.baseTexture.width || frame.y + frame.height > this.baseTexture.height)) + { throw new Error('Texture Error: frame does not fit inside the base Texture dimensions ' + this); } this.valid = frame && frame.width && frame.height && this.baseTexture.source && this.baseTexture.hasLoaded; - if (this.trim) { + 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) { + if (this.valid) + { this._updateUvs(); } } @@ -168,11 +181,13 @@ * * @private */ -Texture.prototype.onBaseTextureLoaded = function () { +Texture.prototype.onBaseTextureLoaded = function () +{ var baseTexture = this.baseTexture; baseTexture.removeEventListener('loaded', this.onLoaded); - if (this.noFrame) { + if (this.noFrame) + { this.frame = new math.Rectangle(0, 0, baseTexture.width, baseTexture.height); } @@ -184,8 +199,10 @@ * * @param destroyBase {boolean} Whether to destroy the base texture as well */ -Texture.prototype.destroy = function (destroyBase) { - if (destroyBase) { +Texture.prototype.destroy = function (destroyBase) +{ + if (destroyBase) + { this.baseTexture.destroy(); } @@ -197,8 +214,10 @@ * * @private */ -Texture.prototype._updateUvs = function () { - if (!this._uvs) { +Texture.prototype._updateUvs = function () +{ + if (!this._uvs) + { this._uvs = new TextureUvs(); } @@ -229,10 +248,12 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return Texture */ -Texture.fromImage = function (imageUrl, crossorigin, scaleMode) { +Texture.fromImage = function (imageUrl, crossorigin, scaleMode) +{ var texture = utils.TextureCache[imageUrl]; - if (!texture) { + if (!texture) + { texture = new Texture(BaseTexture.fromImage(imageUrl, crossorigin, scaleMode)); utils.TextureCache[imageUrl] = texture; } @@ -248,9 +269,11 @@ * @param frameId {string} The frame id of the texture * @return Texture */ -Texture.fromFrame = function (frameId) { +Texture.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache '); } return texture; @@ -264,7 +287,8 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return {Texture} */ -Texture.fromCanvas = function (canvas, scaleMode) { +Texture.fromCanvas = function (canvas, scaleMode) +{ return new Texture(BaseTexture.fromCanvas(canvas, scaleMode)); }; @@ -276,7 +300,8 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return {Texture} A Texture */ -Texture.fromVideo = function (video, scaleMode) { +Texture.fromVideo = function (video, scaleMode) +{ return new Texture(VideoBaseTexture.baseTextureFromVideo(video, scaleMode)); }; @@ -287,7 +312,8 @@ * @param texture {Texture} The Texture to add to the cache. * @param id {string} The id that the texture will be stored against. */ -Texture.addTextureToCache = function (texture, id) { +Texture.addTextureToCache = function (texture, id) +{ utils.TextureCache[id] = texture; }; @@ -298,7 +324,8 @@ * @param id {string} The id of the texture to be removed * @return {Texture} The texture that was removed */ -Texture.removeTextureFromCache = function (id) { +Texture.removeTextureFromCache = function (id) +{ var texture = utils.TextureCache[id]; delete utils.TextureCache[id]; diff --git a/src/core/textures/TextureUvs.js b/src/core/textures/TextureUvs.js index b9bbb58..5424d52 100644 --- a/src/core/textures/TextureUvs.js +++ b/src/core/textures/TextureUvs.js @@ -1,4 +1,5 @@ -function TextureUvs() { +function TextureUvs() +{ this.x0 = 0; this.y0 = 0; diff --git a/src/core/textures/VideoBaseTexture.js b/src/core/textures/VideoBaseTexture.js index e3e0c5a..1a826a9 100644 --- a/src/core/textures/VideoBaseTexture.js +++ b/src/core/textures/VideoBaseTexture.js @@ -12,15 +12,18 @@ * @param source {HTMLVideoElement} * @param [scaleMode] {number} See {@link scaleModes} for possible values */ -function VideoBaseTexture(source, scaleMode) { - if (!source){ +function VideoBaseTexture(source, scaleMode) +{ + if (!source) + { throw new Error('No video source element specified.'); } // hook in here to check if video is already available. // BaseTexture looks for a source.complete boolean, plus width & height. - if ((source.readyState === source.HAVE_ENOUGH_DATA || source.readyState === source.HAVE_FUTURE_DATA) && source.width && source.height) { + if ((source.readyState === source.HAVE_ENOUGH_DATA || source.readyState === source.HAVE_FUTURE_DATA) && source.width && source.height) + { source.complete = true; } @@ -31,7 +34,8 @@ this._boundOnUpdate = this._onUpdate.bind(this); this._boundOnCanPlay = this._onCanPlay.bind(this); - if (!source.complete) { + if (!source.complete) + { source.addEventListener('canplay', this._boundOnCanPlay); source.addEventListener('canplaythrough', this._boundOnCanPlay); @@ -47,28 +51,35 @@ VideoBaseTexture.prototype.constructor = VideoBaseTexture; module.exports = VideoBaseTexture; -VideoBaseTexture.prototype._onUpdate = function () { - if (this.autoUpdate) { +VideoBaseTexture.prototype._onUpdate = function () +{ + if (this.autoUpdate) + { window.requestAnimationFrame(this._boundOnUpdate); this.needsUpdate = true; } }; -VideoBaseTexture.prototype._onPlayStart = function () { - if (!this.autoUpdate) { +VideoBaseTexture.prototype._onPlayStart = function () +{ + if (!this.autoUpdate) + { window.requestAnimationFrame(this._boundOnUpdate); this.autoUpdate = true; } }; -VideoBaseTexture.prototype._onPlayStop = function () { +VideoBaseTexture.prototype._onPlayStop = function () +{ this.autoUpdate = false; }; -VideoBaseTexture.prototype._onCanPlay = function () { +VideoBaseTexture.prototype._onCanPlay = function () +{ this.hasLoaded = true; - if (this.source) { + if (this.source) + { this.source.removeEventListener('canplay', this._boundOnCanPlay); this.source.removeEventListener('canplaythrough', this._boundOnCanPlay); @@ -78,15 +89,18 @@ this.source.play(); // prevent multiple loaded dispatches.. - if(!this.__loaded){ + if(!this.__loaded) + { this.__loaded = true; this.emit('loaded', this); } } }; -VideoBaseTexture.prototype.destroy = function () { - if (this.source && this.source._pixiId) { +VideoBaseTexture.prototype.destroy = function () +{ + if (this.source && this.source._pixiId) + { utils.BaseTextureCache[ this.source._pixiId ] = null; delete utils.BaseTextureCache[ this.source._pixiId ]; @@ -105,14 +119,17 @@ * @param scaleMode {number} See {@link scaleModes} for possible values * @return {VideoBaseTexture} */ -VideoBaseTexture.fromVideo = function (video, scaleMode) { - if (!video._pixiId) { +VideoBaseTexture.fromVideo = function (video, scaleMode) +{ + if (!video._pixiId) + { video._pixiId = 'video_' + utils.uuid(); } var baseTexture = utils.BaseTextureCache[video._pixiId]; - if (!baseTexture) { + if (!baseTexture) + { baseTexture = new VideoBaseTexture(video, scaleMode); utils.BaseTextureCache[ video._pixiId ] = baseTexture; } @@ -147,17 +164,21 @@ * @param scaleMode {number} See {@link scaleModes} for possible values * @return {VideoBaseTexture} */ -VideoBaseTexture.fromUrl = function (videoSrc, scaleMode) { +VideoBaseTexture.fromUrl = function (videoSrc, scaleMode) +{ var video = document.createElement('video'); // array of objects or strings - if (Array.isArray(videoSrc)) { - for (var i = 0; i < videoSrc.length; ++i) { + if (Array.isArray(videoSrc)) + { + for (var i = 0; i < videoSrc.length; ++i) + { video.appendChild(createSource(videoSrc.src || videoSrc, videoSrc.mime)); } } // single object or string - else { + else + { video.appendChild(createSource(videoSrc.src || videoSrc, videoSrc.mime)); } @@ -169,8 +190,10 @@ VideoBaseTexture.fromUrls = VideoBaseTexture.fromUrl; -function createSource(path, type) { - if (!type) { +function createSource(path, type) +{ + if (!type) + { type = 'video/' + path.substr(path.lastIndexOf('.') + 1); } diff --git a/src/core/utils/EventData.js b/src/core/utils/EventData.js index 5d55a22..8cdf701 100644 --- a/src/core/utils/EventData.js +++ b/src/core/utils/EventData.js @@ -7,7 +7,8 @@ * @param name {string} The string name of the event that was triggered * @param data {object} Arbitrary event data to pass along */ -function EventData(target, name, data) { +function EventData(target, name, data) +{ // for duck typing in the ".on()" function this.__isEventObject = true; @@ -71,7 +72,8 @@ * Stops the propagation of events up the scene graph (prevents bubbling). * */ -EventData.prototype.stopPropagation = function stopPropagation() { +EventData.prototype.stopPropagation = function stopPropagation() +{ this.stopped = true; }; @@ -79,6 +81,7 @@ * Stops the propagation of events to sibling listeners (no longer calls any listeners). * */ -EventData.prototype.stopImmediatePropagation = function stopImmediatePropagation() { +EventData.prototype.stopImmediatePropagation = function stopImmediatePropagation() +{ this.stoppedImmediate = true; }; diff --git a/src/core/utils/EventTarget.js b/src/core/utils/EventTarget.js index 7ae8820..671a151 100644 --- a/src/core/utils/EventTarget.js +++ b/src/core/utils/EventTarget.js @@ -13,14 +13,16 @@ * var em = new MyEmitter(); * em.emit('eventName', 'some data', 'some more data', {}, null, ...); */ -function eventTarget(obj) { +function eventTarget(obj) +{ /** * Return a list of assigned event listeners. * * @param eventName {string} The events that should be listed. * @return {Array} An array of listener functions */ - obj.listeners = function listeners(eventName) { + obj.listeners = function listeners(eventName) + { this._listeners = this._listeners || {}; return this._listeners[eventName] ? this._listeners[eventName].slice() : []; @@ -33,22 +35,26 @@ * @param eventName {string} The name of the event. * @return {boolean} Indication if we've emitted an event. */ - obj.emit = obj.dispatchEvent = function emit(eventName, data) { + obj.emit = obj.dispatchEvent = function emit(eventName, data) + { this._listeners = this._listeners || {}; // fast return when there are no listeners - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return; } //backwards compat with old method ".emit({ type: 'something' })" - if (typeof eventName === 'object') { + if (typeof eventName === 'object') + { data = eventName; eventName = eventName.type; } //ensure we are using a real pixi event - if (!data || data.__isEventObject !== true) { + if (!data || data.__isEventObject !== true) + { data = new EventData(this, eventName, data); } @@ -58,23 +64,27 @@ fn = listeners[0], i; - for (i = 0; i < length; fn = listeners[++i]) { + for (i = 0; i < length; fn = listeners[++i]) + { //call the event listener fn.call(this, data); //if "stopImmediatePropagation" is called, stop calling sibling events - if (data.stoppedImmediate) { + if (data.stoppedImmediate) + { return this; } } //if "stopPropagation" is called then don't bubble the event - if (data.stopped) { + if (data.stopped) + { return this; } //bubble this event up the scene graph - if (this.parent && this.parent.emit) { + if (this.parent && this.parent.emit) + { this.parent.emit.call(this.parent, eventName, data); } @@ -88,7 +98,8 @@ * @param eventName {string} Name of the event. * @param callback {Functon} fn Callback function. */ - obj.on = obj.addEventListener = function on(eventName, fn) { + obj.on = obj.addEventListener = function on(eventName, fn) + { this._listeners = this._listeners || {}; (this._listeners[eventName] = this._listeners[eventName] || []) @@ -103,11 +114,13 @@ * @param eventName {string} Name of the event. * @param callback {Function} Callback function. */ - obj.once = function once(eventName, fn) { + obj.once = function once(eventName, fn) + { this._listeners = this._listeners || {}; var self = this; - function onceHandlerWrapper() { + function onceHandlerWrapper() + { fn.apply(self.off(eventName, onceHandlerWrapper), arguments); } onceHandlerWrapper._originalHandler = fn; @@ -122,23 +135,28 @@ * @param eventName {string} The event we want to remove. * @param callback {Function} The listener that we need to find. */ - obj.off = obj.removeEventListener = function off(eventName, fn) { + obj.off = obj.removeEventListener = function off(eventName, fn) + { this._listeners = this._listeners || {}; - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return this; } var list = this._listeners[eventName], i = fn ? list.length : 0; - while(i-- > 0) { - if (list[i] === fn || list[i]._originalHandler === fn) { + while(i-- > 0) + { + if (list[i] === fn || list[i]._originalHandler === fn) + { list.splice(i, 1); } } - if (list.length === 0) { + if (list.length === 0) + { delete this._listeners[eventName]; } @@ -150,10 +168,12 @@ * * @param eventName {string} The event you want to remove all listeners for. */ - obj.removeAllListeners = function removeAllListeners(eventName) { + obj.removeAllListeners = function removeAllListeners(eventName) + { this._listeners = this._listeners || {}; - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return this; } @@ -169,7 +189,8 @@ * * @param object {object} The obj to mix into */ - mixin: function mixin(obj) { + mixin: function mixin(obj) + { eventTarget(obj); } }; diff --git a/src/core/utils/PolyK.js b/src/core/utils/PolyK.js index 7325141..5e20c2b 100644 --- a/src/core/utils/PolyK.js +++ b/src/core/utils/PolyK.js @@ -47,7 +47,8 @@ * Triangulates shapes for webGL graphic fills. * */ -PolyK.Triangulate = function (p) { +PolyK.Triangulate = function (p) +{ var sign = true; var n = p.length >> 1; @@ -59,7 +60,8 @@ i = 0; var al = n; - while(al > 3) { + while(al > 3) + { var i0 = avl[(i+0)%al]; var i1 = avl[(i+1)%al]; var i2 = avl[(i+2)%al]; @@ -69,29 +71,35 @@ var cx = p[2*i2], cy = p[2*i2+1]; var earFound = false; - if (PolyK._convex(ax, ay, bx, by, cx, cy, sign)) { + if (PolyK._convex(ax, ay, bx, by, cx, cy, sign)) + { earFound = true; - for (var j = 0; j < al; j++) { + for (var j = 0; j < al; j++) + { var vi = avl[j]; if (vi === i0 || vi === i1 || vi === i2) continue; - if (PolyK._PointInTriangle(p[2*vi], p[2*vi+1], ax, ay, bx, by, cx, cy)) { + if (PolyK._PointInTriangle(p[2*vi], p[2*vi+1], ax, ay, bx, by, cx, cy)) + { earFound = false; break; } } } - if (earFound) { + if (earFound) + { tgs.push(i0, i1, i2); avl.splice((i+1)%al, 1); al--; i = 0; } - else if (i++ > 3*al) { + else if (i++ > 3*al) + { // need to flip flip reverse it! // reset! - if (sign) { + if (sign) + { tgs = []; avl = []; for (i = 0; i < n; i++) avl.push(i); @@ -101,7 +109,8 @@ sign = false; } - else { + else + { // window.console.log("PIXI Warning: shape too complex to fill"); return null; } @@ -126,7 +135,8 @@ * @private * @return {boolean} */ -PolyK._PointInTriangle = function (px, py, ax, ay, bx, by, cx, cy) { +PolyK._PointInTriangle = function (px, py, ax, ay, bx, by, cx, cy) +{ var v0x = cx-ax; var v0y = cy-ay; var v1x = bx-ax; @@ -154,6 +164,7 @@ * @private * @return {boolean} */ -PolyK._convex = function (ax, ay, bx, by, cx, cy, sign) { +PolyK._convex = function (ax, ay, bx, by, cx, cy, sign) +{ return ((ay-by)*(cx-bx) + (bx-ax)*(cy-by) >= 0) === sign; }; diff --git a/src/core/utils/index.js b/src/core/utils/index.js index ade9831..bfae7ae 100644 --- a/src/core/utils/index.js +++ b/src/core/utils/index.js @@ -16,7 +16,8 @@ * * @return {number} The next uuid to use. */ - uuid: function () { + uuid: function () + { return ++utils._uid; }, @@ -26,7 +27,8 @@ * @param hex {number} * @return {number[]} An array representing the [R, G, B] of the color. */ - hex2rgb: function (hex, out) { + hex2rgb: function (hex, out) + { out = out || []; out[0] = (hex >> 16 & 0xFF) / 255; @@ -42,7 +44,8 @@ * @param hex {number} * @return {string} The string color. */ - hex2string: function (hex) { + hex2string: function (hex) + { hex = hex.toString(16); hex = '000000'.substr(0, 6 - hex.length) + hex; @@ -55,7 +58,8 @@ * @param rgb {number[]} * @return {number} The color number */ - rgb2hex: function (rgb) { + rgb2hex: function (rgb) + { return ((rgb[0]*255 << 16) + (rgb[1]*255 << 8) + rgb[2]*255); }, @@ -64,8 +68,10 @@ * * @return {boolean} whether they are supported */ - canUseNewCanvasBlendModes: function () { - if (typeof document === 'undefined') { + canUseNewCanvasBlendModes: function () + { + if (typeof document === 'undefined') + { return false; } @@ -93,15 +99,19 @@ * @param number {number} * @return {number} the closest number that is a power of two */ - getNextPowerOfTwo: function (number) { + getNextPowerOfTwo: function (number) + { // see: http://en.wikipedia.org/wiki/Power_of_two#Fast_algorithm_to_check_if_a_positive_number_is_a_power_of_two - if (number > 0 && (number & (number - 1)) === 0) { + if (number > 0 && (number & (number - 1)) === 0) + { return number; } - else { + else + { var result = 1; - while (result < number) { + while (result < number) + { result <<= 1; } @@ -116,7 +126,8 @@ * @param height {number} * @return {boolean} */ - isPowerOfTwo: function (width, height) { + isPowerOfTwo: function (width, height) + { return (width > 0 && (width & (width - 1)) === 0 && height > 0 && (height & (height - 1)) === 0); }, @@ -130,12 +141,15 @@ * @constant * @static */ - sayHello: function (type) { - if (utils._saidHello) { + sayHello: function (type) + { + if (utils._saidHello) + { return; } - if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) { + if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) + { var args = [ '%c %c %c Pixi.js ' + CONST.VERSION + ' - ' + type + ' %c ' + ' %c ' + ' http://www.pixijs.com/ %c %c ♥%c♥%c♥ ', 'background: #ff66a5', @@ -151,7 +165,8 @@ console.log.apply(console, args); //jshint ignore:line } - else if (window.console) { + else if (window.console) + { console.log('Pixi.js ' + CONST.VERSION + ' - ' + type + ' - http://www.pixijs.com/'); //jshint ignore:line } @@ -166,15 +181,19 @@ * @class * @namespace PIXI */ - AjaxRequest: function () { + AjaxRequest: function () + { var activexmodes = ['Msxml2.XMLHTTP.6.0', 'Msxml2.XMLHTTP.3.0', 'Microsoft.XMLHTTP']; //activeX versions to check for in IE - if (window.ActiveXObject) { //Test for support for ActiveXObject in IE first (as XMLHttpRequest in IE7 is broken) - for (var i=0; i= this.textures.length) { + else if (round >= this.textures.length) + { this.gotoAndStop(this.textures.length - 1); - if (this.onComplete) { + if (this.onComplete) + { this.onComplete(); } } @@ -167,10 +182,12 @@ * @static * @param frames {string[]} the array of frames ids the movieclip will use as its texture frames */ -MovieClip.fromFrames = function (frames) { +MovieClip.fromFrames = function (frames) +{ var textures = []; - for (var i = 0; i < frames.length; ++i) { + for (var i = 0; i < frames.length; ++i) + { textures.push(new core.Texture.fromFrame(frames[i])); } @@ -183,10 +200,12 @@ * @static * @param images {string[]} the array of image urls the movieclip will use as its texture frames */ -MovieClip.fromImages = function (images) { +MovieClip.fromImages = function (images) +{ var textures = []; - for (var i = 0; i < images.length; ++i) { + for (var i = 0; i < images.length; ++i) + { textures.push(new core.Texture.fromImage(images[i])); } diff --git a/src/extras/Rope.js b/src/extras/Rope.js index c157ec4..9c87bc0 100644 --- a/src/extras/Rope.js +++ b/src/extras/Rope.js @@ -9,7 +9,8 @@ * @param {Array} points - An array of {Point}. * */ -function Rope(texture, points) { +function Rope(texture, points) +{ Strip.call(this, texture); this.points = points; @@ -31,10 +32,12 @@ * Refreshes * */ -Rope.prototype.refresh = function () { +Rope.prototype.refresh = function () +{ var points = this.points; - if (points.length < 1) { + if (points.length < 1) + { return; } @@ -59,20 +62,23 @@ var total = points.length, point, index, amount; - for (var i = 1; i < total; i++) { + for (var i = 1; i < total; i++) + { point = points[i]; index = i * 4; // time to do some smart drawing! amount = i / (total-1); - if (i%2) { + if (i%2) + { uvs[index] = amount; uvs[index+1] = 0; uvs[index+2] = amount; uvs[index+3] = 1; } - else { + else + { uvs[index] = amount; uvs[index+1] = 0; @@ -95,10 +101,12 @@ * * @private */ -Rope.prototype.updateTransform = function () { +Rope.prototype.updateTransform = function () +{ var points = this.points; - if (points.length < 1) { + if (points.length < 1) + { return; } @@ -113,14 +121,17 @@ var total = points.length, point, index, ratio, perpLength, num; - for (var i = 0; i < total; i++) { + for (var i = 0; i < total; i++) + { point = points[i]; index = i * 4; - if (i < points.length-1) { + if (i < points.length-1) + { nextPoint = points[i+1]; } - else { + else + { nextPoint = point; } @@ -129,7 +140,8 @@ ratio = (1 - (i / (total-1))) * 10; - if (ratio > 1) { + if (ratio > 1) + { ratio = 1; } @@ -157,7 +169,8 @@ * * @param texture {Texture} the texture that will be used */ -Rope.prototype.setTexture = function (texture) { +Rope.prototype.setTexture = function (texture) +{ // stop current texture this.texture = texture; //this.updateFrame = true; diff --git a/src/extras/Strip.js b/src/extras/Strip.js index c5e378f..57691b5 100644 --- a/src/extras/Strip.js +++ b/src/extras/Strip.js @@ -10,7 +10,8 @@ * @param height {number} the height * */ -function Strip(texture) { +function Strip(texture) +{ core.DisplayObjectContainer.call(this); /** @@ -70,9 +71,11 @@ * * @param renderer {WebGLRenderer} */ -Strip.prototype.renderWebGL = function (renderer) { +Strip.prototype.renderWebGL = function (renderer) +{ // if the sprite is not visible or the alpha is 0 then no need to render this element - if (!this.visible || this.alpha <= 0) { + if (!this.visible || this.alpha <= 0) + { return; } @@ -81,7 +84,8 @@ renderer.spriteBatch.stop(); // init! init! - if (!this._vertexBuffer) { + if (!this._vertexBuffer) + { this._initWebGL(renderer); } @@ -96,7 +100,8 @@ //TODO check culling }; -Strip.prototype._initWebGL = function (renderer) { +Strip.prototype._initWebGL = function (renderer) +{ // build the strip! var gl = renderer.gl; @@ -118,7 +123,8 @@ gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this.indices, gl.STATIC_DRAW); }; -Strip.prototype._renderStrip = function (renderer) { +Strip.prototype._renderStrip = function (renderer) +{ var gl = renderer.gl; var projection = renderer.projection, offset = renderer.offset, @@ -137,7 +143,8 @@ gl.uniform2f(shader.offsetVector, -offset.x, -offset.y); gl.uniform1f(shader.alpha, this.worldAlpha); - if (!this.dirty) { + if (!this.dirty) + { gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexBuffer); gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); @@ -150,10 +157,12 @@ gl.activeTexture(gl.TEXTURE0); // check if a texture is dirty.. - if (this.texture.baseTexture._dirty[gl.id]) { + if (this.texture.baseTexture._dirty[gl.id]) + { renderer.updateTexture(this.texture.baseTexture); } - else { + else + { // bind the current texture gl.bindTexture(gl.TEXTURE_2D, this.texture.baseTexture._glTextures[gl.id]); } @@ -163,7 +172,8 @@ } - else { + else + { this.dirty = false; gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexBuffer); @@ -178,10 +188,12 @@ gl.activeTexture(gl.TEXTURE0); // check if a texture is dirty.. - if (this.texture.baseTexture._dirty[gl.id]) { + if (this.texture.baseTexture._dirty[gl.id]) + { renderer.updateTexture(this.texture.baseTexture); } - else { + else + { gl.bindTexture(gl.TEXTURE_2D, this.texture.baseTexture._glTextures[gl.id]); } @@ -203,27 +215,33 @@ * * @param renderer {CanvasRenderer} */ -Strip.prototype.renderCanvas = function (renderer) { +Strip.prototype.renderCanvas = function (renderer) +{ var context = renderer.context; var transform = this.worldTransform; - if (renderer.roundPixels) { + if (renderer.roundPixels) + { context.setTransform(transform.a, transform.b, transform.c, transform.d, transform.tx | 0, transform.ty | 0); } - else { + else + { context.setTransform(transform.a, transform.b, transform.c, transform.d, transform.tx, transform.ty); } - if (this.drawMode === Strip.DrawModes.TRIANGLE_STRIP) { + if (this.drawMode === Strip.DrawModes.TRIANGLE_STRIP) + { this._renderCanvasTriangleStrip(context); } - else { + else + { this._renderCanvasTriangles(context); } }; -Strip.prototype._renderCanvasTriangleStrip = function (context) { +Strip.prototype._renderCanvasTriangleStrip = function (context) +{ // draw triangles!! var vertices = this.vertices; var uvs = this.uvs; @@ -231,14 +249,16 @@ var length = vertices.length / 2; // this.count++; - for (var i = 0; i < length - 2; i++) { + for (var i = 0; i < length - 2; i++) + { // draw some triangles! var index = i * 2; this._renderCanvasDrawTriangle(context, vertices, uvs, index, (index + 2), (index + 4)); } }; -Strip.prototype._renderCanvasTriangles = function (context) { +Strip.prototype._renderCanvasTriangles = function (context) +{ // draw triangles!! var vertices = this.vertices; var uvs = this.uvs; @@ -247,14 +267,16 @@ var length = indices.length; // this.count++; - for (var i = 0; i < length; i += 3) { + for (var i = 0; i < length; i += 3) + { // draw some triangles! var index0 = indices[i] * 2, index1 = indices[i + 1] * 2, index2 = indices[i + 2] * 2; this._renderCanvasDrawTriangle(context, vertices, uvs, index0, index1, index2); } }; -Strip.prototype._renderCanvasDrawTriangle = function (context, vertices, uvs, index0, index1, index2) { +Strip.prototype._renderCanvasDrawTriangle = function (context, vertices, uvs, index0, index1, index2) +{ var textureSource = this.texture.baseTexture.source; var textureWidth = this.texture.width; var textureHeight = this.texture.height; @@ -265,7 +287,8 @@ var u0 = uvs[index0] * textureWidth, u1 = uvs[index1] * textureWidth, u2 = uvs[index2] * textureWidth; var v0 = uvs[index0 + 1] * textureHeight, v1 = uvs[index1 + 1] * textureHeight, v2 = uvs[index2 + 1] * textureHeight; - if (this.canvasPadding > 0) { + if (this.canvasPadding > 0) + { var paddingX = this.canvasPadding / this.worldTransform.a; var paddingY = this.canvasPadding / this.worldTransform.d; var centerX = (x0 + x1 + x2) / 3; @@ -332,7 +355,8 @@ * @param strip {Strip} The Strip to render * @private */ -Strip.prototype.renderStripFlat = function (strip) { +Strip.prototype.renderStripFlat = function (strip) +{ var context = this.context; var vertices = strip.vertices; @@ -340,7 +364,8 @@ // this.count++; context.beginPath(); - for (var i=1; i < length-2; i++) { + for (var i=1; i < length-2; i++) + { // draw some triangles! var index = i*2; @@ -358,7 +383,8 @@ }; /* -Strip.prototype.setTexture = function (texture) { +Strip.prototype.setTexture = function (texture) +{ //TODO SET THE TEXTURES //TODO VISIBILITY @@ -377,7 +403,8 @@ * @private */ -Strip.prototype.onTextureUpdate = function () { +Strip.prototype.onTextureUpdate = function () +{ this.updateFrame = true; }; @@ -387,7 +414,8 @@ * @param matrix {Matrix} the transformation matrix of the sprite * @return {Rectangle} the framing rectangle */ -Strip.prototype.getBounds = function (matrix) { +Strip.prototype.getBounds = function (matrix) +{ var worldTransform = matrix || this.worldTransform; var a = worldTransform.a; @@ -404,7 +432,8 @@ var minY = Infinity; var vertices = this.vertices; - for (var i = 0, n = vertices.length; i < n; i += 2) { + for (var i = 0, n = vertices.length; i < n; i += 2) + { var rawX = vertices[i], rawY = vertices[i + 1]; var x = (a * rawX) + (c * rawY) + tx; var y = (d * rawY) + (b * rawX) + ty; @@ -416,7 +445,8 @@ maxY = y > maxY ? y : maxY; } - if (minX === -Infinity || maxY === Infinity) { + if (minX === -Infinity || maxY === Infinity) + { return core.math.Rectangle.EMPTY; } diff --git a/src/extras/TilingSprite.js b/src/extras/TilingSprite.js index 3ac22df..31da393 100644 --- a/src/extras/TilingSprite.js +++ b/src/extras/TilingSprite.js @@ -10,7 +10,8 @@ * @param width {number} the width of the tiling sprite * @param height {number} the height of the tiling sprite */ -function TilingSprite(texture, width, height) { +function TilingSprite(texture, width, height) +{ core.Sprite.call( this, texture); /** @@ -86,10 +87,12 @@ * @memberof TilingSprite# */ width: { - get: function () { + get: function () + { return this._width; }, - set: function (value) { + set: function (value) + { this._width = value; } }, @@ -101,20 +104,25 @@ * @memberof TilingSprite# */ height: { - get: function () { + get: function () + { return this._height; }, - set: function (value) { + set: function (value) + { this._height = value; } }, texture: { - get: function () { + get: function () + { return this._texture; }, - set: function (value) { - if (this._texture === value) { + set: function (value) + { + if (this._texture === value) + { return; } @@ -130,51 +138,61 @@ * * @param renderer {WebGLRenderer} */ -TilingSprite.prototype.renderWebGL = function (renderer) { - if (!this.visible || this.alpha <= 0) { +TilingSprite.prototype.renderWebGL = function (renderer) +{ + if (!this.visible || this.alpha <= 0) + { return; } var i, j; - if (this._mask) { + if (this._mask) + { renderer.spriteBatch.stop(); renderer.maskManager.pushMask(this.mask, renderer); renderer.spriteBatch.start(); } - if (this._filters) { + if (this._filters) + { renderer.spriteBatch.flush(); renderer.filterManager.pushFilter(this._filterBlock); } - if (!this.tilingTexture || this.refreshTexture) { + if (!this.tilingTexture || this.refreshTexture) + { this.generateTilingTexture(true); - if (this.tilingTexture && this.tilingTexture.needsUpdate) { + if (this.tilingTexture && this.tilingTexture.needsUpdate) + { //TODO - tweaking renderer.updateTexture(this.tilingTexture.baseTexture); this.tilingTexture.needsUpdate = false; // this.tilingTexture._uvs = null; } } - else { + else + { renderer.spriteBatch.renderTilingSprite(this); } // simple render children! - for (i=0,j=this.children.length; i= 0 && index <= this.children.length) { - if (child.parent) { + if (index >= 0 && index <= this.children.length) + { + if (child.parent) + { child.parent.removeChild(child); } @@ -154,7 +173,8 @@ return child; } - else { + else + { throw new Error(child + 'addChildAt: The index '+ index +' supplied is out of bounds ' + this.children.length); } }; @@ -165,15 +185,18 @@ * @param child {DisplayObject} * @param child2 {DisplayObject} */ -DisplayObjectContainer.prototype.swapChildren = function (child, child2) { - if (child === child2) { +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) { + if (index1 < 0 || index2 < 0) + { throw new Error('swapChildren: Both the supplied DisplayObjects must be a child of the caller.'); } @@ -187,10 +210,12 @@ * @param child {DisplayObject} The DisplayObject instance to identify * @return {Number} The index position of the child display object to identify */ -DisplayObjectContainer.prototype.getChildIndex = function (child) { +DisplayObjectContainer.prototype.getChildIndex = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { throw new Error('The supplied DisplayObject must be a child of the caller'); } @@ -203,8 +228,10 @@ * @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 */ -DisplayObjectContainer.prototype.setChildIndex = function (child, index) { - if (index < 0 || index >= this.children.length) { +DisplayObjectContainer.prototype.setChildIndex = function (child, index) +{ + if (index < 0 || index >= this.children.length) + { throw new Error('The supplied index is out of bounds'); } @@ -220,8 +247,10 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child at the given index, if any. */ -DisplayObjectContainer.prototype.getChildAt = function (index) { - if (index < 0 || index >= this.children.length) { +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'); } @@ -234,10 +263,12 @@ * @param child {DisplayObject} The DisplayObject to remove * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChild = function (child) { +DisplayObjectContainer.prototype.removeChild = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { return; } @@ -250,7 +281,8 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChildAt = function (index) { +DisplayObjectContainer.prototype.removeChildAt = function (index) +{ var child = this.getChildAt(index); child.parent = null; @@ -265,24 +297,29 @@ * @param beginIndex {Number} The beginning position. Default value is 0. * @param endIndex {Number} The ending position. Default value is size of the container. */ -DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) { +DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) +{ var begin = beginIndex || 0; var end = typeof endIndex === 'number' ? endIndex : this.children.length; var range = end - begin; - if (range > 0 && range <= end) { + if (range > 0 && range <= end) + { var removed = this.children.splice(begin, range); - for (var i = 0; i < removed.length; ++i) { + for (var i = 0; i < removed.length; ++i) + { removed[i].parent = null; } return removed; } - else if (range === 0 && this.children.length === 0) { + else if (range === 0 && this.children.length === 0) + { return []; } - else { + else + { throw new RangeError('removeChildren: numeric values are outside the acceptable range.'); } }; @@ -291,7 +328,8 @@ * Generates and updates the cached sprite for this object. * */ -DisplayObjectContainer.prototype.updateCachedSprite = function () { +DisplayObjectContainer.prototype.updateCachedSprite = function () +{ this._generateCachedSprite(); }; @@ -304,7 +342,8 @@ * @param renderer {CanvasRenderer|WebGLRenderer} The renderer used to generate the texture. * @return {Texture} a texture of the graphics object */ -DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) { +DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) +{ var bounds = this.getLocalBounds(); var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0, renderer, scaleMode, resolution); @@ -322,18 +361,22 @@ * * @private */ -DisplayObjectContainer.prototype.updateTransform = function () { - if (!this.visible) { +DisplayObjectContainer.prototype.updateTransform = function () +{ + if (!this.visible) + { return; } this.displayObjectUpdateTransform(); - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { return; } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } }; @@ -346,8 +389,10 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getBounds = function () { - if (this.children.length === 0) { +DisplayObjectContainer.prototype.getBounds = function () +{ + if (this.children.length === 0) + { return math.Rectangle.EMPTY; } @@ -365,10 +410,12 @@ var childVisible = false; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -386,7 +433,8 @@ maxY = maxY > childMaxY ? maxY : childMaxY; } - if (!childVisible) { + if (!childVisible) + { return math.Rectangle.EMPTY; } @@ -407,12 +455,14 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getLocalBounds = function () { +DisplayObjectContainer.prototype.getLocalBounds = function () +{ var matrixCache = this.worldTransform; this.worldTransform = math.Matrix.IDENTITY; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } @@ -428,13 +478,16 @@ * * @param renderer {WebGLRenderer} The renderer */ -DisplayObjectContainer.prototype.renderWebGL = function (renderer) { +DisplayObjectContainer.prototype.renderWebGL = function (renderer) +{ // if the object is not visible or the alpha is 0 then no need to render this element - if (!this.visible || this.alpha <= 0) { + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } @@ -442,14 +495,17 @@ var i, j; // do a quick check to see if this element has a mask or a filter. - if (this._mask || this._filters) { + if (this._mask || this._filters) + { // push filter first as we need to ensure the stencil buffer is correct for any masking - if (this._filters) { + if (this._filters) + { renderer.spriteBatch.flush(); renderer.filterManager.pushFilter(this._filterBlock); } - if (this._mask) { + if (this._mask) + { renderer.spriteBatch.stop(); renderer.maskManager.pushMask(this.mask, renderer); renderer.spriteBatch.start(); @@ -459,36 +515,42 @@ this._renderWebGL(renderer); // now loop through the children and make sure they get rendered - for (i = 0, j = this.children.length; i < j; i++) { + for (i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderWebGL(renderer); } // time to stop the sprite batch as either a mask element or a filter draw will happen next renderer.spriteBatch.stop(); - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(this._mask, renderer); } - if (this._filters) { + if (this._filters) + { renderer.filterManager.popFilter(); } renderer.spriteBatch.start(); } - else { + else + { this._renderWebGL(renderer); // simple render children! - for (i = 0, j = this.children.length; i < j; ++i) { + for (i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderWebGL(renderer); } } }; -DisplayObjectContainer.prototype._renderWebGL = function (renderer) { +DisplayObjectContainer.prototype._renderWebGL = function (renderer) +{ // this is where content itself gets renderd.. @@ -499,25 +561,31 @@ * * @param renderer {CanvasRenderer} The renderer */ -DisplayObjectContainer.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0) { +DisplayObjectContainer.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -528,13 +596,16 @@ * @param renderer {WebGLRenderer|CanvasRenderer} The renderer * @private */ -DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) { +DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) +{ this._cachedSprite.worldAlpha = this.worldAlpha; - if (renderer.gl) { + if (renderer.gl) + { this._cachedSprite.renderWebGL(renderer); } - else { + else + { this._cachedSprite.renderCanvas(renderer); } }; @@ -544,10 +615,12 @@ * * @private */ -DisplayObjectContainer.prototype._generateCachedSprite = function () { +DisplayObjectContainer.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { // TODO - RenderTexture now *requires* a renderer instance, so this is like broken // because `renderer` isn't actually in scope here :P var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0); @@ -555,7 +628,8 @@ this._cachedSprite = new Sprite(renderTexture); this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.texture.resize(bounds.width | 0, bounds.height | 0); } @@ -580,8 +654,10 @@ * * @private */ -DisplayObjectContainer.prototype._destroyCachedSprite = function () { - if (!this._cachedSprite) { +DisplayObjectContainer.prototype._destroyCachedSprite = function () +{ + if (!this._cachedSprite) + { return; } diff --git a/src/core/display/Sprite.js b/src/core/display/Sprite.js index 707da24..5862aef 100644 --- a/src/core/display/Sprite.js +++ b/src/core/display/Sprite.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param texture {Texture} The texture for this sprite */ -function Sprite(texture) { +function Sprite(texture) +{ DisplayObjectContainer.call(this); /** @@ -85,12 +86,14 @@ this.texture = texture || Texture.EMPTY; } -Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) { +Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) +{ DisplayObjectContainer.prototype.destroy.call(this); this.anchor = null; - if (destroyTexture) { + if (destroyTexture) + { this._texture.destroy(destroyBaseTexture); } @@ -111,10 +114,12 @@ * @memberof Sprite# */ width: { - get: function () { + get: function () + { return this.scale.x * this.texture.frame.width; }, - set: function (value) { + set: function (value) + { this.scale.x = value / this.texture.frame.width; this._width = value; } @@ -127,10 +132,12 @@ * @memberof Sprite# */ height: { - get: function () { + get: function () + { return this.scale.y * this.texture.frame.height; }, - set: function (value) { + set: function (value) + { this.scale.y = value / this.texture.frame.height; this._height = value; } @@ -143,23 +150,29 @@ * @memberof Sprite# */ texture: { - get: function () { + get: function () + { return this._texture; }, - set: function (value) { - if (this._texture === value) { + set: function (value) + { + if (this._texture === value) + { return; } this._texture = value; this.cachedTint = 0xFFFFFF; - if (value) { + if (value) + { // wait for the texture to load - if (value.baseTexture.hasLoaded) { + if (value.baseTexture.hasLoaded) + { this._onTextureUpdate(); } - else { + else + { value.once('update', this._onTextureUpdate.bind(this)); } } @@ -172,18 +185,22 @@ * * @private */ -Sprite.prototype._onTextureUpdate = function () { +Sprite.prototype._onTextureUpdate = function () +{ // so if _width is 0 then width was not set.. - if (this._width) { + if (this._width) + { this.scale.x = this._width / this.texture.frame.width; } - if (this._height) { + if (this._height) + { this.scale.y = this._height / this.texture.frame.height; } }; -Sprite.prototype._renderWebGL = function (renderer) { +Sprite.prototype._renderWebGL = function (renderer) +{ // this is where content gets renderd.. // watch this space for a little render state manager.. @@ -197,7 +214,8 @@ * @param matrix {Matrix} the transformation matrix of the sprite * @return {Rectangle} the framing rectangle */ -Sprite.prototype.getBounds = function (matrix) { +Sprite.prototype.getBounds = function (matrix) +{ var width = this.texture.frame.width; var height = this.texture.frame.height; @@ -224,11 +242,13 @@ if(b === 0 && c === 0) { // scale may be negative! - if (a < 0) { + if (a < 0) + { a *= -1; } - if (d < 0) { + if (d < 0) + { d *= -1; } @@ -293,28 +313,34 @@ * * @param renderer {CanvasRenderer} The renderer */ -Sprite.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) { +Sprite.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) + { return; } - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; renderer.context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } // Ignore null sources - if (this.texture.valid) { + if (this.texture.valid) + { var resolution = this.texture.baseTexture.resolution / renderer.resolution; renderer.context.globalAlpha = this.worldAlpha; // If smoothingEnabled is supported and we need to change the smoothing property for this texture - if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) { + if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) + { renderer.scaleMode = this.texture.baseTexture.scaleMode; renderer.context[renderer.smoothProperty] = (renderer.scaleMode === CONST.scaleModes.LINEAR); } @@ -324,7 +350,8 @@ var dy = (this.texture.trim ? this.texture.trim.y : 0) - (this.anchor.y * this.texture.trim.height); // Allow for pixel rounding - if (renderer.roundPixels) { + if (renderer.roundPixels) + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -337,7 +364,8 @@ dx = dx | 0; dy = dy | 0; } - else { + else + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -348,8 +376,10 @@ ); } - if (this.tint !== 0xFFFFFF) { - if (this.cachedTint !== this.tint) { + if (this.tint !== 0xFFFFFF) + { + if (this.cachedTint !== this.tint) + { this.cachedTint = this.tint; // TODO clean up caching - how to clean up the caches? @@ -368,7 +398,8 @@ this.texture.crop.height / resolution ); } - else { + else + { renderer.context.drawImage( this.texture.baseTexture.source, this.texture.crop.x, @@ -383,11 +414,13 @@ } } - for (var i = 0, j = this.children.length; i < j; i++) { + for (var i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -402,10 +435,12 @@ * @param frameId {String} The frame Id of the texture in the cache * @return {Sprite} A new Sprite using a texture from the texture cache matching the frameId */ -Sprite.fromFrame = function (frameId) { +Sprite.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache' + this); } @@ -420,6 +455,7 @@ * @param imageId {String} The image url of the texture * @return {Sprite} A new Sprite using a texture from the texture cache matching the image id */ -Sprite.fromImage = function (imageId, crossorigin, scaleMode) { +Sprite.fromImage = function (imageId, crossorigin, scaleMode) +{ return new Sprite(Texture.fromImage(imageId, crossorigin, scaleMode)); }; diff --git a/src/core/display/SpriteBatch.js b/src/core/display/SpriteBatch.js index 3187777..c196fef 100644 --- a/src/core/display/SpriteBatch.js +++ b/src/core/display/SpriteBatch.js @@ -12,7 +12,8 @@ * ```js * var container = new SpriteBatch(); * - * for(var i = 0; i < 100; ++i) { + * for(var i = 0; i < 100; ++i) + * { * var sprite = new PIXI.Sprite.fromImage("myImage.png"); * container.addChild(sprite); * } @@ -25,7 +26,8 @@ */ //TODO RENAME to PARTICLE CONTAINER? -function SpriteBatch() { +function SpriteBatch() +{ DisplayObjectContainer.call(this); } @@ -38,7 +40,8 @@ * * @private */ -SpriteBatch.prototype.updateTransform = function () { +SpriteBatch.prototype.updateTransform = function () +{ // TODO don't need to! this.displayObjectUpdateTransform(); // PIXI.DisplayObjectContainer.prototype.updateTransform.call( this ); @@ -50,8 +53,10 @@ * @param renderer {WebGLRenderer} The webgl renderer * @private */ -SpriteBatch.prototype.renderWebGL = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderWebGL = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -71,8 +76,10 @@ * @param renderer {CanvasRenderer} The canvas renderer * @private */ -SpriteBatch.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -84,10 +91,12 @@ this.displayObjectUpdateTransform(); - for (var i = 0; i < this.children.length; ++i) { + for (var i = 0; i < this.children.length; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -95,9 +104,11 @@ context.globalAlpha = this.worldAlpha * child.alpha; - if (child.rotation % (Math.PI * 2) === 0) { + if (child.rotation % (Math.PI * 2) === 0) + { // this is the fastest way to optimise! - if rotation is 0 then we can avoid any kind of setTransform call - if (isRotated) { + if (isRotated) + { context.setTransform( transform.a, transform.b, @@ -122,8 +133,10 @@ frame.height * child.scale.y ); } - else { - if (!isRotated) { + else + { + if (!isRotated) + { isRotated = true; } @@ -131,7 +144,8 @@ var childTransform = child.worldTransform; - if (renderer.roundPixels) { + if (renderer.roundPixels) + { context.setTransform( childTransform.a, childTransform.b, @@ -141,7 +155,8 @@ childTransform.ty | 0 ); } - else { + else + { context.setTransform( childTransform.a, childTransform.b, diff --git a/src/core/index.js b/src/core/index.js index 3954b6f..eb4a82b 100644 --- a/src/core/index.js +++ b/src/core/index.js @@ -58,11 +58,13 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRenderer: function (width, height, options, noWebGL) { + autoDetectRenderer: function (width, height, options, noWebGL) + { width = width || 800; height = height || 600; - if (!noWebGL && require('webgl-enabled')()) { + if (!noWebGL && require('webgl-enabled')()) + { return new core.WebGLRenderer(width, height, options); } @@ -87,7 +89,8 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRecommendedRenderer: function (width, height, options) { + autoDetectRecommendedRenderer: function (width, height, options) + { var isAndroid = /Android/i.test(navigator.userAgent); return core.autoDetectRenderer(width, height, options, isAndroid); diff --git a/src/core/math/Matrix.js b/src/core/math/Matrix.js index c2f87e2..2ff4848 100644 --- a/src/core/math/Matrix.js +++ b/src/core/math/Matrix.js @@ -10,7 +10,8 @@ * @class * @namespace PIXI */ -function Matrix() { +function Matrix() +{ /** * @member {number} * @default 1 @@ -63,7 +64,8 @@ * * @param array {number[]} The array that the matrix will be populated from. */ -Matrix.prototype.fromArray = function (array) { +Matrix.prototype.fromArray = function (array) +{ this.a = array[0]; this.b = array[1]; this.c = array[3]; @@ -78,14 +80,17 @@ * @param transpose {boolean} Whether we need to transpose the matrix or not * @return {number[]} the newly created array which contains the matrix */ -Matrix.prototype.toArray = function (transpose) { - if (!this.array) { +Matrix.prototype.toArray = function (transpose) +{ + if (!this.array) + { this.array = new Float32Array(9); } var array = this.array; - if (transpose) { + if (transpose) + { array[0] = this.a; array[1] = this.b; array[2] = 0; @@ -96,7 +101,8 @@ array[7] = this.ty; array[8] = 1; } - else { + else + { array[0] = this.a; array[1] = this.c; array[2] = this.tx; @@ -119,7 +125,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, transformed through this matrix */ -Matrix.prototype.apply = function (pos, newPos) { +Matrix.prototype.apply = function (pos, newPos) +{ newPos = newPos || new Point(); newPos.x = this.a * pos.x + this.c * pos.y + this.tx; @@ -136,7 +143,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, inverse-transformed through this matrix */ -Matrix.prototype.applyInverse = function (pos, newPos) { +Matrix.prototype.applyInverse = function (pos, newPos) +{ newPos = newPos || new Point(); var id = 1 / (this.a * this.d + this.c * -this.b); @@ -154,7 +162,8 @@ * @param {number} y * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.translate = function (x, y) { +Matrix.prototype.translate = function (x, y) +{ this.tx += x; this.ty += y; @@ -168,7 +177,8 @@ * @param {number} y The amount to scale vertically * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.scale = function (x, y) { +Matrix.prototype.scale = function (x, y) +{ this.a *= x; this.d *= y; this.c *= x; @@ -186,7 +196,8 @@ * @param {number} angle - The angle in radians. * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.rotate = function (angle) { +Matrix.prototype.rotate = function (angle) +{ var cos = Math.cos( angle ); var sin = Math.sin( angle ); @@ -210,7 +221,8 @@ * @param {Matrix} matrix * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.append = function (matrix) { +Matrix.prototype.append = function (matrix) +{ var a1 = this.a; var b1 = this.b; var c1 = this.c; @@ -232,7 +244,8 @@ * * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.identity = function () { +Matrix.prototype.identity = function () +{ this.a = 1; this.b = 0; this.c = 0; diff --git a/src/core/math/Point.js b/src/core/math/Point.js index 7565b2d..632f346 100644 --- a/src/core/math/Point.js +++ b/src/core/math/Point.js @@ -7,7 +7,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -function Point(x, y) { +function Point(x, y) +{ /** * @member {number} * @default 0 @@ -29,7 +30,8 @@ * * @return {Point} a copy of the point */ -Point.prototype.clone = function () { +Point.prototype.clone = function () +{ return new Point(this.x, this.y); }; @@ -40,7 +42,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -Point.prototype.set = function (x, y) { +Point.prototype.set = function (x, y) +{ this.x = x || 0; this.y = y || ( (y !== 0) ? this.x : 0 ) ; }; diff --git a/src/core/math/shapes/Circle.js b/src/core/math/shapes/Circle.js index 69cfdc9..4d76efc 100644 --- a/src/core/math/shapes/Circle.js +++ b/src/core/math/shapes/Circle.js @@ -10,7 +10,8 @@ * @param y {number} The Y coordinate of the center of this circle * @param radius {number} The radius of the circle */ -function Circle(x, y, radius) { +function Circle(x, y, radius) +{ /** * @member {number} * @default 0 @@ -46,7 +47,8 @@ * @method clone * @return {Circle} a copy of the Circle */ -Circle.prototype.clone = function () { +Circle.prototype.clone = function () +{ return new Circle(this.x, this.y, this.radius); }; @@ -58,8 +60,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Circle */ -Circle.prototype.contains = function (x, y) { - if (this.radius <= 0) { +Circle.prototype.contains = function (x, y) +{ + if (this.radius <= 0) + { return false; } @@ -79,6 +83,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Circle.prototype.getBounds = function () { +Circle.prototype.getBounds = function () +{ return new Rectangle(this.x - this.radius, this.y - this.radius, this.radius * 2, this.radius * 2); }; diff --git a/src/core/math/shapes/Ellipse.js b/src/core/math/shapes/Ellipse.js index 4f2d066..fefd01a 100644 --- a/src/core/math/shapes/Ellipse.js +++ b/src/core/math/shapes/Ellipse.js @@ -11,7 +11,8 @@ * @param width {number} The half width of this ellipse * @param height {number} The half height of this ellipse */ -function Ellipse(x, y, width, height) { +function Ellipse(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -53,7 +54,8 @@ * @method clone * @return {Ellipse} a copy of the ellipse */ -Ellipse.prototype.clone = function () { +Ellipse.prototype.clone = function () +{ return new Ellipse(this.x, this.y, this.width, this.height); }; @@ -65,8 +67,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coords are within this ellipse */ -Ellipse.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Ellipse.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } @@ -86,6 +90,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Ellipse.prototype.getBounds = function () { +Ellipse.prototype.getBounds = function () +{ return new Rectangle(this.x - this.width, this.y - this.height, this.width, this.height); }; diff --git a/src/core/math/shapes/Polygon.js b/src/core/math/shapes/Polygon.js index ae89148..fea6d37 100644 --- a/src/core/math/shapes/Polygon.js +++ b/src/core/math/shapes/Polygon.js @@ -10,16 +10,20 @@ * arguments passed can be flat x,y values e.g. `new Polygon(x,y, x,y, x,y, ...)` where `x` and `y` are * Numbers. */ -function Polygon(points) { +function Polygon(points) +{ //if points isn't an array, use arguments as the array - if (!(points instanceof Array)) { + if (!(points instanceof Array)) + { points = Array.prototype.slice.call(arguments); } //if this is a flat array of numbers, convert it to points - if (points[0] instanceof Point) { + if (points[0] instanceof Point) + { var p = []; - for (var i = 0, il = points.length; i < il; i++) { + for (var i = 0, il = points.length; i < il; i++) + { p.push(points[i].x, points[i].y); } @@ -51,7 +55,8 @@ * * @return {Polygon} a copy of the polygon */ -Polygon.prototype.clone = function () { +Polygon.prototype.clone = function () +{ return new Polygon(this.points.slice()); }; @@ -62,19 +67,22 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this polygon */ -Polygon.prototype.contains = function (x, y) { +Polygon.prototype.contains = function (x, y) +{ var inside = false; // use some raycasting to test hits // https://github.com/substack/point-in-polygon/blob/master/index.js var length = this.points.length / 2; - for (var i = 0, j = length - 1; i < length; j = i++) { + for (var i = 0, j = length - 1; i < length; j = i++) + { var xi = this.points[i * 2], yi = this.points[i * 2 + 1], xj = this.points[j * 2], yj = this.points[j * 2 + 1], intersect = ((yi > y) !== (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi); - if (intersect) { + if (intersect) + { inside = !inside; } } diff --git a/src/core/math/shapes/Rectangle.js b/src/core/math/shapes/Rectangle.js index 16ac62a..4008b68 100644 --- a/src/core/math/shapes/Rectangle.js +++ b/src/core/math/shapes/Rectangle.js @@ -10,7 +10,8 @@ * @param width {number} The overall width of this rectangle * @param height {number} The overall height of this rectangle */ -function Rectangle(x, y, width, height) { +function Rectangle(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -60,7 +61,8 @@ * * @return {Rectangle} a copy of the rectangle */ -Rectangle.prototype.clone = function () { +Rectangle.prototype.clone = function () +{ return new Rectangle(this.x, this.y, this.width, this.height); }; @@ -71,13 +73,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rectangle */ -Rectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Rectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/math/shapes/RoundedRectangle.js b/src/core/math/shapes/RoundedRectangle.js index 27d286e..7bf6411 100644 --- a/src/core/math/shapes/RoundedRectangle.js +++ b/src/core/math/shapes/RoundedRectangle.js @@ -11,7 +11,8 @@ * @param height {number} The overall height of this rounded rectangle * @param radius {number} Controls the radius of the rounded corners */ -function RoundedRectangle(x, y, width, height, radius) { +function RoundedRectangle(x, y, width, height, radius) +{ /** * @member {number} * @default 0 @@ -58,7 +59,8 @@ * * @return {RoundedRectangle} a copy of the rounded rectangle */ -RoundedRectangle.prototype.clone = function () { +RoundedRectangle.prototype.clone = function () +{ return new RoundedRectangle(this.x, this.y, this.width, this.height, this.radius); }; @@ -69,13 +71,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rounded Rectangle */ -RoundedRectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +RoundedRectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/primitives/Graphics.js b/src/core/primitives/Graphics.js index 261c534..e902d2a 100644 --- a/src/core/primitives/Graphics.js +++ b/src/core/primitives/Graphics.js @@ -16,7 +16,8 @@ * @extends DisplayObjectContainer * @namespace PIXI */ -function Graphics() { +function Graphics() +{ DisplayObjectContainer.call(this); this.renderable = true; @@ -154,16 +155,20 @@ * @private */ cacheAsBitmap: { - get: function () { + get: function () + { return this._cacheAsBitmap; }, - set: function (value) { + set: function (value) + { this._cacheAsBitmap = value; - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._generateCachedSprite(); } - else { + else + { this.destroyCachedSprite(); this.dirty = true; } @@ -176,7 +181,8 @@ * * @return {Graphics} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ var clone = new Graphics(); clone.renderable = this.renderable; @@ -192,7 +198,8 @@ clone.cachedSpriteDirty = this.cachedSpriteDirty; // copy graphics data - for (var i = 0; i < this.graphicsData.length; ++i) { + for (var i = 0; i < this.graphicsData.length; ++i) + { clone.graphicsData.push(this.graphicsData.clone()); } @@ -211,17 +218,21 @@ * @param alpha {number} alpha of the line to draw, will update the objects stored style * @return {Graphics} */ -Graphics.prototype.lineStyle = function (lineWidth, color, alpha) { +Graphics.prototype.lineStyle = function (lineWidth, color, alpha) +{ this.lineWidth = lineWidth || 0; this.lineColor = color || 0; this.lineAlpha = (arguments.length < 3) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length) + { // halfway through a line? start a new one! this.drawShape( new math.Polygon( this.currentPath.shape.points.slice(-2) )); } - else { + else + { // otherwise its empty so lets just set the line properties this.currentPath.lineWidth = this.lineWidth; this.currentPath.lineColor = this.lineColor; @@ -239,7 +250,8 @@ * @param y {number} the Y coordinate to move to * @return {Graphics} */ -Graphics.prototype.moveTo = function (x, y) { +Graphics.prototype.moveTo = function (x, y) +{ this.drawShape(new math.Polygon([x,y])); return this; @@ -253,7 +265,8 @@ * @param y {number} the Y coordinate to draw to * @return {Graphics} */ -Graphics.prototype.lineTo = function (x, y) { +Graphics.prototype.lineTo = function (x, y) +{ this.currentPath.shape.points.push(x, y); this.dirty = true; @@ -270,13 +283,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -285,7 +302,8 @@ n = 20, points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { this.moveTo(0, 0); } @@ -293,7 +311,8 @@ var fromY = points[points.length-1]; var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; xa = fromX + ( (cpX - fromX) * j ); @@ -319,13 +338,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -342,7 +365,8 @@ var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; dt = (1 - j); @@ -373,13 +397,17 @@ * @param radius {number} The radius of the arc * @return {Graphics} */ -Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points.push(x1, y1); } } - else { + else + { this.moveTo(x1, y1); } @@ -392,12 +420,15 @@ b2 = x2 - x1, mm = Math.abs(a1 * b2 - b1 * a2); - if (mm < 1.0e-8 || radius === 0) { - if (points[points.length-2] !== x1 || points[points.length-1] !== y1) { + if (mm < 1.0e-8 || radius === 0) + { + if (points[points.length-2] !== x1 || points[points.length-1] !== y1) + { points.push(x1, y1); } } - else { + else + { var dd = a1 * a1 + b1 * b1, cc = a2 * a2 + b2 * b2, tt = a1 * a2 + b1 * b2, @@ -433,42 +464,51 @@ * @param anticlockwise {boolean} Optional. Specifies whether the drawing should be counterclockwise or clockwise. False is default, and indicates clockwise, while true indicates counter-clockwise. * @return {Graphics} */ -Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) { +Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) +{ var startX = cx + Math.cos(startAngle) * radius; var startY = cy + Math.sin(startAngle) * radius; var points; // TODO - This if-else makes no sense. It uses currentPath in the else where it doesn't exist... - if (this.currentPath) { + if (this.currentPath) + { points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { points.push(startX, startY); } - else if (points[points.length-2] !== startX || points[points.length-1] !== startY) { + else if (points[points.length-2] !== startX || points[points.length-1] !== startY) + { points.push(startX, startY); } } - else { + else + { this.moveTo(startX, startY); points = this.currentPath.shape.points; } - if (startAngle === endAngle) { + if (startAngle === endAngle) + { return this; } - if (!anticlockwise && endAngle <= startAngle) { + if (!anticlockwise && endAngle <= startAngle) + { endAngle += Math.PI * 2; } - else if (anticlockwise && startAngle <= endAngle) { + else if (anticlockwise && startAngle <= endAngle) + { startAngle += Math.PI * 2; } var sweep = anticlockwise ? (startAngle - endAngle) *-1 : (endAngle - startAngle); var segs = (Math.abs(sweep)/ (Math.PI * 2)) * 40; - if (sweep === 0) { + if (sweep === 0) + { return this; } @@ -482,7 +522,8 @@ var remainder = ( segMinus % 1 ) / segMinus; - for (var i = 0; i <= segMinus; ++i) { + for (var i = 0; i <= segMinus; ++i) + { var real = i + remainder * i; var angle = ((theta) + startAngle + (theta2 * real)); @@ -506,13 +547,16 @@ * @param alpha {number} the alpha of the fill * @return {Graphics} */ -Graphics.prototype.beginFill = function (color, alpha) { +Graphics.prototype.beginFill = function (color, alpha) +{ this.filling = true; this.fillColor = color || 0; this.fillAlpha = (alpha === undefined) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length <= 2) + { this.currentPath.fill = this.filling; this.currentPath.fillColor = this.fillColor; this.currentPath.fillAlpha = this.fillAlpha; @@ -526,7 +570,8 @@ * * @return {Graphics} */ -Graphics.prototype.endFill = function () { +Graphics.prototype.endFill = function () +{ this.filling = false; this.fillColor = null; this.fillAlpha = 1; @@ -542,7 +587,8 @@ * @param height {number} The height of the rectangle * @return {Graphics} */ -Graphics.prototype.drawRect = function ( x, y, width, height ) { +Graphics.prototype.drawRect = function ( x, y, width, height ) +{ this.drawShape(new math.Rectangle(x,y, width, height)); return this; @@ -556,7 +602,8 @@ * @param height {number} The height of the rectangle * @param radius {number} Radius of the rectangle corners */ -Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) { +Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) +{ this.drawShape(new math.RoundedRectangle(x, y, width, height, radius)); return this; @@ -570,7 +617,8 @@ * @param radius {number} The radius of the circle * @return {Graphics} */ -Graphics.prototype.drawCircle = function (x, y, radius) { +Graphics.prototype.drawCircle = function (x, y, radius) +{ this.drawShape(new math.Circle(x,y, radius)); return this; @@ -585,7 +633,8 @@ * @param height {number} The half height of the ellipse * @return {Graphics} */ -Graphics.prototype.drawEllipse = function (x, y, width, height) { +Graphics.prototype.drawEllipse = function (x, y, width, height) +{ this.drawShape(new math.Ellipse(x, y, width, height)); return this; @@ -597,8 +646,10 @@ * @param path {Array} The path data used to construct the polygon. * @return {Graphics} */ -Graphics.prototype.drawPolygon = function (path) { - if (!(path instanceof Array)) { +Graphics.prototype.drawPolygon = function (path) +{ + if (!(path instanceof Array)) + { path = Array.prototype.slice.call(arguments); } @@ -612,7 +663,8 @@ * * @return {Graphics} */ -Graphics.prototype.clear = function () { +Graphics.prototype.clear = function () +{ this.lineWidth = 0; this.filling = false; @@ -631,7 +683,8 @@ * @param scaleMode {number} Should be one of the scaleMode consts * @return {Texture} a texture of the graphics object */ -Graphics.prototype.generateTexture = function (resolution, scaleMode) { +Graphics.prototype.generateTexture = function (resolution, scaleMode) +{ resolution = resolution || 1; var bounds = this.getBounds(); @@ -655,17 +708,21 @@ * * @param renderer {WebGLRenderer} */ -Graphics.prototype._renderWebGL = function (renderer) { +Graphics.prototype._renderWebGL = function (renderer) +{ // if the sprite is not visible or the alpha is 0 then no need to render this element - if (this.isMask === true) { + if (this.isMask === true) + { return; } // this code may still be needed so leaving for now.. - // + // /* - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture on the gpu too! @@ -681,17 +738,24 @@ return; } - */ - - // check if the webgl graphic needs to be updated - if (this.glDirty) { - this.dirty = true; - this.glDirty = false; - } + else */ - renderer.setObjectRendererer(renderer.graphicsRenderer); - renderer.graphicsRenderer.render(this); + renderer.spriteBatch.stop(); + renderer.blendModeManager.setBlendMode(this.blendMode); + // check blend mode + renderer.blendModeManager.setBlendMode( this.blendMode ); + + // check if the webgl graphic needs to be updated + if (this.glDirty) + { + this.dirty = true; + this.glDirty = false; + } + + WebGLGraphics.renderGraphics(this, renderer); + + renderer.spriteBatch.start(); }; /** @@ -700,14 +764,18 @@ * @param renderer {CanvasRenderer} * @private */ -Graphics.prototype.renderCanvas = function (renderer) { +Graphics.prototype.renderCanvas = function (renderer) +{ // 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.isMask === true) { + if (!this.visible || this.alpha <= 0 || this.isMask === true) + { return; } - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture @@ -723,16 +791,19 @@ return; } - else { + else + { var context = renderer.context; var transform = this.worldTransform; - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } @@ -748,11 +819,13 @@ CanvasGraphics.renderGraphics(this, context); - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } } @@ -763,13 +836,16 @@ * * @return {Rectangle} the rectangular bounding area */ -Graphics.prototype.getBounds = function (matrix) { +Graphics.prototype.getBounds = function (matrix) +{ // return an empty object if the item is a mask! - if (this.isMask) { + if (this.isMask) + { return math.Rectangle.EMPTY; } - if (this.dirty) { + if (this.dirty) + { this.updateLocalBounds(); this.glDirty = true; @@ -841,23 +917,27 @@ * Update the bounds of the object * */ -Graphics.prototype.updateLocalBounds = function () { +Graphics.prototype.updateLocalBounds = function () +{ var minX = Infinity; var maxX = -Infinity; var minY = Infinity; var maxY = -Infinity; - if (this.graphicsData.length) { + if (this.graphicsData.length) + { var shape, points, x, y, w, h; - for (var i = 0; i < this.graphicsData.length; i++) { + for (var i = 0; i < this.graphicsData.length; i++) + { var data = this.graphicsData[i]; var type = data.type; var lineWidth = data.lineWidth; shape = data.shape; - if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) { + if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) + { x = shape.x - lineWidth/2; y = shape.y - lineWidth/2; w = shape.width + lineWidth; @@ -869,7 +949,8 @@ minY = y < minY ? y : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.CIRC) { + else if (type === CONST.SHAPES.CIRC) + { x = shape.x; y = shape.y; w = shape.radius + lineWidth/2; @@ -881,7 +962,8 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.ELIP) { + else if (type === CONST.SHAPES.ELIP) + { x = shape.x; y = shape.y; w = shape.width + lineWidth/2; @@ -893,11 +975,13 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else { + else + { // POLY points = shape.points; - for (var j = 0; j < points.length; j += 2) { + for (var j = 0; j < points.length; j += 2) + { x = points[j]; y = points[j+1]; @@ -910,7 +994,8 @@ } } } - else { + else + { minX = 0; maxX = 0; minY = 0; @@ -931,10 +1016,12 @@ * * @private */ -Graphics.prototype._generateCachedSprite = function () { +Graphics.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { var canvasBuffer = new CanvasBuffer(bounds.width, bounds.height); var texture = Texture.fromCanvas(canvasBuffer.canvas); @@ -943,7 +1030,8 @@ this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.buffer.resize(bounds.width, bounds.height); } @@ -968,7 +1056,8 @@ * * @private */ -Graphics.prototype.updateCachedSpriteTexture = function () { +Graphics.prototype.updateCachedSpriteTexture = function () +{ var cachedSprite = this._cachedSprite; var texture = cachedSprite.texture; var canvas = cachedSprite.buffer.canvas; @@ -989,7 +1078,8 @@ * Destroys a previous cached sprite. * */ -Graphics.prototype.destroyCachedSprite = function () { +Graphics.prototype.destroyCachedSprite = function () +{ this._cachedSprite.texture.destroy(true); // let the gc collect the unused sprite @@ -1003,10 +1093,13 @@ * @param {Circle|Rectangle|Ellipse|Line|Polygon} shape The Shape object to draw. * @return {GraphicsData} The generated GraphicsData object. */ -Graphics.prototype.drawShape = function (shape) { - if (this.currentPath) { +Graphics.prototype.drawShape = function (shape) +{ + if (this.currentPath) + { // check current path! - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath.shape.points.length <= 2) + { this.graphicsData.pop(); } } @@ -1017,7 +1110,8 @@ this.graphicsData.push(data); - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { data.shape.closed = this.filling; this.currentPath = data; } diff --git a/src/core/primitives/GraphicsData.js b/src/core/primitives/GraphicsData.js index 99decbe..788f6f2 100644 --- a/src/core/primitives/GraphicsData.js +++ b/src/core/primitives/GraphicsData.js @@ -4,7 +4,8 @@ * @class * @namespace PIXI */ -function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) { +function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) +{ this.lineWidth = lineWidth; this.lineColor = lineColor; this.lineAlpha = lineAlpha; @@ -27,7 +28,8 @@ * * @return {GraphicsData} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ return new GraphicsData( this.lineWidth, this.lineColor, diff --git a/src/core/renderers/canvas/CanvasRenderer.js b/src/core/renderers/canvas/CanvasRenderer.js index 15a0978..7aebd44 100644 --- a/src/core/renderers/canvas/CanvasRenderer.js +++ b/src/core/renderers/canvas/CanvasRenderer.js @@ -17,17 +17,22 @@ * @param [options.resolution=1] {number} the resolution of the renderer retina would be 2 * @param [options.clearBeforeRender=true] {boolean} This sets if the CanvasRenderer will clear the canvas or not before the new render pass. */ -function CanvasRenderer(width, height, options) { +function CanvasRenderer(width, height, options) +{ utils.sayHello('Canvas'); - if (options) { - for (var i in CONST.defaultRenderOptions) { - if (typeof options[i] === 'undefined') { + if (options) + { + for (var i in CONST.defaultRenderOptions) + { + if (typeof options[i] === 'undefined') + { options[i] = CONST.defaultRenderOptions[i]; } } } - else { + else + { options = CONST.defaultRenderOptions; } @@ -156,19 +161,24 @@ this.smoothProperty = null; - if (this.context.imageSmoothingEnabled) { + if (this.context.imageSmoothingEnabled) + { this.smoothProperty = 'imageSmoothingEnabled'; } - else if (this.context.webkitImageSmoothingEnabled) { + else if (this.context.webkitImageSmoothingEnabled) + { this.smoothProperty = 'webkitImageSmoothingEnabled'; } - else if (this.context.mozImageSmoothingEnabled) { + else if (this.context.mozImageSmoothingEnabled) + { this.smoothProperty = 'mozImageSmoothingEnabled'; } - else if (this.context.oImageSmoothingEnabled) { + else if (this.context.oImageSmoothingEnabled) + { this.smoothProperty = 'oImageSmoothingEnabled'; } - else if (this.context.msImageSmoothingEnabled) { + else if (this.context.msImageSmoothingEnabled) + { this.smoothProperty = 'msImageSmoothingEnabled'; } @@ -193,10 +203,12 @@ * @memberof CanvasRenderer# */ backgroundColor: { - get: function () { + get: function () + { return this._backgroundColor; }, - set: function (val) { + set: function (val) + { this._backgroundColor = val; this._backgroundColorString = utils.hex2string(val); } @@ -208,7 +220,8 @@ * * @param object {DisplayObject} the object to be rendered */ -CanvasRenderer.prototype.render = function (object) { +CanvasRenderer.prototype.render = function (object) +{ object.updateTransform(); this.context.setTransform(1,0,0,1,0,0); @@ -218,16 +231,20 @@ this.currentBlendMode = CONST.blendModes.NORMAL; this.context.globalCompositeOperation = this.blendModes[CONST.blendModes.NORMAL]; - if (navigator.isCocoonJS && this.view.screencanvas) { + if (navigator.isCocoonJS && this.view.screencanvas) + { this.context.fillStyle = 'black'; this.context.clear(); } - if (this.clearBeforeRender) { - if (this.transparent) { + if (this.clearBeforeRender) + { + if (this.transparent) + { this.context.clearRect(0, 0, this.width, this.height); } - else { + else + { this.context.fillStyle = this._backgroundColorString; this.context.fillRect(0, 0, this.width , this.height); } @@ -241,8 +258,10 @@ * * @param [removeView=false] {boolean} Removes the Canvas element from the DOM. */ -CanvasRenderer.prototype.destroy = function (removeView) { - if (removeView && this.view.parent) { +CanvasRenderer.prototype.destroy = function (removeView) +{ + if (removeView && this.view.parent) + { this.view.parent.removeChild(this.view); } @@ -257,14 +276,16 @@ * @param width {number} the new width of the canvas view * @param height {number} the new height of the canvas view */ -CanvasRenderer.prototype.resize = function (width, height) { +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) { + if (this.autoResize) + { this.view.style.width = this.width / this.resolution + 'px'; this.view.style.height = this.height / this.resolution + 'px'; } @@ -276,7 +297,8 @@ * @param displayObject {DisplayObject} The displayObject to render * @private */ -CanvasRenderer.prototype.renderDisplayObject = function (displayObject) { +CanvasRenderer.prototype.renderDisplayObject = function (displayObject) +{ displayObject.renderCanvas(this); }; @@ -285,11 +307,14 @@ * * @private */ -CanvasRenderer.prototype._mapBlendModes = function () { - if (!this.blendModes) { +CanvasRenderer.prototype._mapBlendModes = function () +{ + if (!this.blendModes) + { this.blendModes = {}; - if (utils.canUseNewCanvasBlendModes()) { + if (utils.canUseNewCanvasBlendModes()) + { this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? this.blendModes[CONST.blendModes.MULTIPLY] = 'multiply'; @@ -308,7 +333,8 @@ this.blendModes[CONST.blendModes.COLOR] = 'color'; this.blendModes[CONST.blendModes.LUMINOSITY] = 'luminosity'; } - else { + else + { // this means that the browser does not support the cool new blend modes in canvas 'cough' ie 'cough' this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? diff --git a/src/core/renderers/canvas/utils/CanvasBuffer.js b/src/core/renderers/canvas/utils/CanvasBuffer.js index ebe5d47..b183a66 100644 --- a/src/core/renderers/canvas/utils/CanvasBuffer.js +++ b/src/core/renderers/canvas/utils/CanvasBuffer.js @@ -6,7 +6,8 @@ * @param width {number} the width for the newly created canvas * @param height {number} the height for the newly created canvas */ -function CanvasBuffer(width, height) { +function CanvasBuffer(width, height) +{ /** * The Canvas object that belongs to this CanvasBuffer. * @@ -36,10 +37,12 @@ * @memberof CanvasBuffer# */ width: { - get: function () { + get: function () + { return this.canvas.width; }, - set: function (val) { + set: function (val) + { this.canvas.width = val; } }, @@ -50,10 +53,12 @@ * @memberof CanvasBuffer# */ height: { - get: function () { + get: function () + { return this.canvas.height; }, - set: function (val) { + set: function (val) + { this.canvas.height = val; } } @@ -64,7 +69,8 @@ * * @private */ -CanvasBuffer.prototype.clear = function () { +CanvasBuffer.prototype.clear = function () +{ this.context.setTransform(1, 0, 0, 1, 0, 0); this.context.clearRect(0,0, this.canvas.width, this.canvas.height); }; @@ -75,7 +81,8 @@ * @param width {number} the new width of the canvas * @param height {number} the new height of the canvas */ -CanvasBuffer.prototype.resize = function (width, height) { +CanvasBuffer.prototype.resize = function (width, height) +{ this.canvas.width = width; this.canvas.height = height; }; diff --git a/src/core/renderers/canvas/utils/CanvasGraphics.js b/src/core/renderers/canvas/utils/CanvasGraphics.js index c7eaa2a..3f2a91f 100644 --- a/src/core/renderers/canvas/utils/CanvasGraphics.js +++ b/src/core/renderers/canvas/utils/CanvasGraphics.js @@ -13,15 +13,18 @@ * @param graphics {Graphics} the actual graphics object to render * @param context {CanvasRenderingContext2D} the 2d drawing method of the canvas */ -CanvasGraphics.renderGraphics = function (graphics, context) { +CanvasGraphics.renderGraphics = function (graphics, context) +{ var worldAlpha = graphics.worldAlpha; - if (graphics.dirty) { + if (graphics.dirty) + { this.updateGraphicsTint(graphics); graphics.dirty = false; } - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; @@ -30,69 +33,82 @@ context.lineWidth = data.lineWidth; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { context.beginPath(); var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } - if (shape.closed) { + if (shape.closed) + { context.lineTo(points[0], points[1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fillRect(shape.x, shape.y, shape.width, shape.height); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.strokeRect(shape.x, shape.y, shape.width, shape.height); } } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.beginPath(); context.arc(shape.x, shape.y, shape.radius,0,2*Math.PI); context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas var w = shape.width * 2; @@ -119,18 +135,21 @@ context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; var width = shape.width; @@ -152,13 +171,15 @@ context.quadraticCurveTo(rx, ry, rx, ry + radius); context.closePath(); - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); @@ -174,45 +195,54 @@ * @param graphics {Graphics} the graphics which will be used as a mask * @param context {CanvasRenderingContext2D} the context 2d method of the canvas */ -CanvasGraphics.renderGraphicsMask = function (graphics, context) { +CanvasGraphics.renderGraphicsMask = function (graphics, context) +{ var len = graphics.graphicsData.length; - if (len === 0) { + if (len === 0) + { return; } context.beginPath(); - for (var i = 0; i < len; i++) { + for (var i = 0; i < len; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { context.rect(shape.x, shape.y, shape.width, shape.height); context.closePath(); } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.arc(shape.x, shape.y, shape.radius, 0, 2 * Math.PI); context.closePath(); } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas @@ -237,7 +267,8 @@ context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); context.closePath(); } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; @@ -262,8 +293,10 @@ } }; -CanvasGraphics.updateGraphicsTint = function (graphics) { - if (graphics.tint === 0xFFFFFF) { +CanvasGraphics.updateGraphicsTint = function (graphics) +{ + if (graphics.tint === 0xFFFFFF) + { return; } @@ -271,7 +304,8 @@ var tintG = (graphics.tint >> 8 & 0xFF) / 255; var tintB = (graphics.tint & 0xFF)/ 255; - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var fillColor = data.fillColor | 0; diff --git a/src/core/renderers/canvas/utils/CanvasMaskManager.js b/src/core/renderers/canvas/utils/CanvasMaskManager.js index e04a733..9827d36 100644 --- a/src/core/renderers/canvas/utils/CanvasMaskManager.js +++ b/src/core/renderers/canvas/utils/CanvasMaskManager.js @@ -6,7 +6,8 @@ * @class * @namespace PIXI */ -function CanvasMaskManager() {} +function CanvasMaskManager() +{} CanvasMaskManager.prototype.constructor = CanvasMaskManager; module.exports = CanvasMaskManager; @@ -17,7 +18,8 @@ * @param maskData {object} the maskData that will be pushed * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.pushMask = function (maskData, renderer) { +CanvasMaskManager.prototype.pushMask = function (maskData, renderer) +{ renderer.context.save(); var cacheAlpha = maskData.alpha; @@ -45,6 +47,7 @@ * * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.popMask = function (renderer) { +CanvasMaskManager.prototype.popMask = function (renderer) +{ renderer.context.restore(); }; diff --git a/src/core/renderers/canvas/utils/CanvasTinter.js b/src/core/renderers/canvas/utils/CanvasTinter.js index 17e0529..d2fb1bc 100644 --- a/src/core/renderers/canvas/utils/CanvasTinter.js +++ b/src/core/renderers/canvas/utils/CanvasTinter.js @@ -14,7 +14,8 @@ * @param color {number} the color to use to tint the sprite with * @return {HTMLCanvasElement} The tinted canvas */ -CanvasTinter.getTintedTexture = function (sprite, color) { +CanvasTinter.getTintedTexture = function (sprite, color) +{ var texture = sprite.texture; color = CanvasTinter.roundColor(color); @@ -23,7 +24,8 @@ texture.tintCache = texture.tintCache || {}; - if (texture.tintCache[stringColor]) { + if (texture.tintCache[stringColor]) + { return texture.tintCache[stringColor]; } @@ -33,14 +35,16 @@ //CanvasTinter.tintWithPerPixel(texture, stringColor, canvas); CanvasTinter.tintMethod(texture, color, canvas); - if (CanvasTinter.convertTintToImage) { + if (CanvasTinter.convertTintToImage) + { // is this better? var tintImage = new Image(); tintImage.src = canvas.toDataURL(); texture.tintCache[stringColor] = tintImage; } - else { + else + { texture.tintCache[stringColor] = canvas; // if we are not converting the texture to an image then we need to lose the reference to the canvas CanvasTinter.canvas = null; @@ -56,7 +60,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithMultiply = function (texture, color, canvas) { +CanvasTinter.tintWithMultiply = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -104,7 +109,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithOverlay = function (texture, color, canvas) { +CanvasTinter.tintWithOverlay = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -139,7 +145,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithPerPixel = function (texture, color, canvas) { +CanvasTinter.tintWithPerPixel = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -167,7 +174,8 @@ var pixels = pixelData.data; - for (var i = 0; i < pixels.length; i += 4) { + for (var i = 0; i < pixels.length; i += 4) + { pixels[i+0] *= r; pixels[i+1] *= g; pixels[i+2] *= b; @@ -181,7 +189,8 @@ * * @param color {number} the color to round, should be a hex color */ -CanvasTinter.roundColor = function (color) { +CanvasTinter.roundColor = function (color) +{ var step = CanvasTinter.cacheStepsPerColorChannel; var rgbValues = utils.hex2rgb(color); diff --git a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js index 9f2f89a..35edbaf 100644 --- a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js +++ b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLBlendModeManager(renderer) { +function WebGLBlendModeManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -23,8 +24,10 @@ * * @param blendMode {number} the blendMode, should be a Pixi const, such as BlendModes.ADD */ -WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) { - if (this.currentBlendMode === blendMode) { +WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) +{ + if (this.currentBlendMode === blendMode) + { return false; } diff --git a/src/core/renderers/webgl/managers/WebGLFilterManager.js b/src/core/renderers/webgl/managers/WebGLFilterManager.js index 1179258..2dac048 100644 --- a/src/core/renderers/webgl/managers/WebGLFilterManager.js +++ b/src/core/renderers/webgl/managers/WebGLFilterManager.js @@ -7,7 +7,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLFilterManager(renderer) { +function WebGLFilterManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -32,7 +33,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.texturePool.length = 0; self.initShaderBuffers(); }); @@ -46,7 +48,8 @@ * @param renderer {WebGLRenderer} * @param buffer {ArrayBuffer} */ -WebGLFilterManager.prototype.begin = function (buffer) { +WebGLFilterManager.prototype.begin = function (buffer) +{ this.defaultShader = this.renderer.shaderManager.defaultShader; this.width = this.renderer.projection.x * 2; @@ -60,7 +63,8 @@ * * @param filterBlock {object} the filter that will be pushed to the current filter stack */ -WebGLFilterManager.prototype.pushFilter = function (filterBlock) { +WebGLFilterManager.prototype.pushFilter = function (filterBlock) +{ var gl = this.renderer.gl; var projection = this.renderer.projection; @@ -78,10 +82,12 @@ this.offsetY += filterBlock._filterArea.y; var texture = this.texturePool.pop(); - if (!texture) { + if (!texture) + { texture = new FilterTexture(this.renderer.gl, this.width, this.height); } - else { + else + { texture.resize(this.width, this.height); } @@ -98,29 +104,35 @@ var localX = filterArea.x, localY = filterArea.y; - if (filterArea.x < 0) { + if (filterArea.x < 0) + { filterArea.width += filterArea.x; filterArea.x = 0; } - if (filterArea.y < 0) { + if (filterArea.y < 0) + { filterArea.height += filterArea.y; filterArea.y = 0; } - if (localX + filterArea.width > this.width) { + if (localX + filterArea.width > this.width) + { filterArea.width = this.width - localX; } - if (localY + filterArea.height > this.height) { + if (localY + filterArea.height > this.height) + { filterArea.height = this.height - localY; } - if (filterArea.width < 0) { + if (filterArea.width < 0) + { filterArea.width = 0; } - if (filterArea.height < 0) { + if (filterArea.height < 0) + { filterArea.height = 0; } @@ -154,7 +166,8 @@ * Removes the last filter from the filter stack and doesn't return it. * */ -WebGLFilterManager.prototype.popFilter = function () { +WebGLFilterManager.prototype.popFilter = function () +{ var gl = this.renderer.gl; var filterBlock = this.filterStack.pop(); @@ -163,7 +176,8 @@ var projection = this.renderer.projection; var offset = this.renderer.offset; - if (filterBlock.filterPasses.length > 1) { + if (filterBlock.filterPasses.length > 1) + { gl.viewport(0, 0, filterArea.width, filterArea.height); gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); @@ -193,7 +207,8 @@ var inputTexture = texture; var outputTexture = this.texturePool.pop(); - if (!outputTexture) { + if (!outputTexture) + { outputTexture = new FilterTexture(this.renderer.gl, this.width, this.height); } outputTexture.resize(this.width, this.height); @@ -204,7 +219,8 @@ gl.disable(gl.BLEND); - for (var i = 0; i < filterBlock.filterPasses.length-1; i++) { + for (var i = 0; i < filterBlock.filterPasses.length-1; i++) + { var filterPass = filterBlock.filterPasses[i]; gl.bindFramebuffer(gl.FRAMEBUFFER, outputTexture.frameBuffer ); @@ -243,10 +259,12 @@ var buffer = this.buffer; // time to render the filters texture to the previous scene - if (this.filterStack.length === 0) { + if (this.filterStack.length === 0) + { gl.colorMask(true, true, true, true);//this.transparent); } - else { + else + { var currentFilter = this.filterStack[this.filterStack.length-1]; filterArea = currentFilter._filterArea; @@ -332,13 +350,15 @@ * @param width {number} the horizontal range of the filter * @param height {number} the vertical range of the filter */ -WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) { +WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) +{ // use program var gl = this.renderer.gl; var shader = filter.shaders[gl.id]; - if (!shader) { + if (!shader) + { shader = new Shader(gl); shader.fragmentSrc = filter.fragmentSrc; @@ -356,7 +376,8 @@ gl.uniform2f(shader.projectionVector, width/2, -height/2); gl.uniform2f(shader.offsetVector, 0,0); - if (filter.uniforms.dimensions) { + 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]; @@ -386,7 +407,8 @@ * Initialises the shader buffers. * */ -WebGLFilterManager.prototype.initShaderBuffers = function () { +WebGLFilterManager.prototype.initShaderBuffers = function () +{ var gl = this.renderer.gl; // create some buffers @@ -432,7 +454,8 @@ * Destroys the filter and removes it from the filter stack. * */ -WebGLFilterManager.prototype.destroy = function () { +WebGLFilterManager.prototype.destroy = function () +{ var gl = this.renderer.gl; this.filterStack = null; @@ -441,7 +464,8 @@ this.offsetY = 0; // destroy textures - for (var i = 0; i < this.texturePool.length; i++) { + for (var i = 0; i < this.texturePool.length; i++) + { this.texturePool[i].destroy(); } diff --git a/src/core/renderers/webgl/managers/WebGLManager.js b/src/core/renderers/webgl/managers/WebGLManager.js index 9d47b5c..c30cd51 100644 --- a/src/core/renderers/webgl/managers/WebGLManager.js +++ b/src/core/renderers/webgl/managers/WebGLManager.js @@ -3,7 +3,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLManager(renderer) { +function WebGLManager(renderer) +{ /** * The renderer this manager works for. * @@ -15,6 +16,7 @@ WebGLManager.prototype.constructor = WebGLManager; module.exports = WebGLManager; -WebGLManager.prototype.destroy = function () { +WebGLManager.prototype.destroy = function () +{ this.renderer = null; }; diff --git a/src/core/renderers/webgl/managers/WebGLMaskManager.js b/src/core/renderers/webgl/managers/WebGLMaskManager.js index 2f90b64..e568812 100644 --- a/src/core/renderers/webgl/managers/WebGLMaskManager.js +++ b/src/core/renderers/webgl/managers/WebGLMaskManager.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLMaskManager(renderer) { +function WebGLMaskManager(renderer) +{ WebGLManager.call(this, renderer); } @@ -19,12 +20,15 @@ * * @param maskData {any[]} */ -WebGLMaskManager.prototype.pushMask = function (maskData) { - if (maskData.dirty) { +WebGLMaskManager.prototype.pushMask = function (maskData) +{ + if (maskData.dirty) + { WebGLGraphics.updateGraphics(maskData, this.renderer.gl); } - if (!maskData._webGL[this.renderer.gl.id].data.length) { + if (!maskData._webGL[this.renderer.gl.id].data.length) + { return; } @@ -36,6 +40,7 @@ * * @param maskData {any[]} */ -WebGLMaskManager.prototype.popMask = function (maskData) { +WebGLMaskManager.prototype.popMask = function (maskData) +{ this.renderer.stencilManager.popStencil(maskData, maskData._webGL[this.renderer.gl.id].data[0], this.renderer); }; diff --git a/src/core/renderers/webgl/managers/WebGLShaderManager.js b/src/core/renderers/webgl/managers/WebGLShaderManager.js index fef071c..90c6477 100644 --- a/src/core/renderers/webgl/managers/WebGLShaderManager.js +++ b/src/core/renderers/webgl/managers/WebGLShaderManager.js @@ -10,7 +10,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLShaderManager(renderer) { +function WebGLShaderManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -28,7 +29,8 @@ */ this.tempAttribState = []; - for (var i = 0; i < this.maxAttibs; i++) { + for (var i = 0; i < this.maxAttibs; i++) + { this.attribState[i] = false; } @@ -66,7 +68,8 @@ // listen for context and update necessary shaders var self = this; - this.renderer.on('context', function (event) { + this.renderer.on('context', function (event) + { var gl = event.data; // this shader is used for rendering primitives @@ -97,29 +100,36 @@ * * @param attribs {Array} attribs */ -WebGLShaderManager.prototype.setAttribs = function (attribs) { +WebGLShaderManager.prototype.setAttribs = function (attribs) +{ // reset temp state var i; - for (i = 0; i < this.tempAttribState.length; i++) { + for (i = 0; i < this.tempAttribState.length; i++) + { this.tempAttribState[i] = false; } // set the new attribs - for (var a in attribs) { + for (var a in attribs) + { this.tempAttribState[attribs[a]] = true; } var gl = this.renderer.gl; - for (i = 0; i < this.attribState.length; i++) { - if (this.attribState[i] !== this.tempAttribState[i]) { + for (i = 0; i < this.attribState.length; i++) + { + if (this.attribState[i] !== this.tempAttribState[i]) + { this.attribState[i] = this.tempAttribState[i]; - if (this.attribState[i]) { + if (this.attribState[i]) + { gl.enableVertexAttribArray(i); } - else { + else + { gl.disableVertexAttribArray(i); } } @@ -131,8 +141,10 @@ * * @param shader {Any} */ -WebGLShaderManager.prototype.setShader = function (shader) { - if (this._currentId === shader.uuid) { +WebGLShaderManager.prototype.setShader = function (shader) +{ + if (this._currentId === shader.uuid) + { return false; } @@ -150,7 +162,8 @@ * Destroys this object. * */ -WebGLShaderManager.prototype.destroy = function () { +WebGLShaderManager.prototype.destroy = function () +{ this.attribState = null; this.tempAttribState = null; diff --git a/src/core/renderers/webgl/managers/WebGLStencilManager.js b/src/core/renderers/webgl/managers/WebGLStencilManager.js index 9ec6398..4cb0134 100644 --- a/src/core/renderers/webgl/managers/WebGLStencilManager.js +++ b/src/core/renderers/webgl/managers/WebGLStencilManager.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLStencilManager(renderer) { +function WebGLStencilManager(renderer) +{ WebGLManager.call(this, renderer); this.stencilStack = []; @@ -24,12 +25,14 @@ * @param graphics {Graphics} * @param webGLData {any[]} */ -WebGLStencilManager.prototype.pushStencil = function (graphics, webGLData) { +WebGLStencilManager.prototype.pushStencil = function (graphics, webGLData) +{ var gl = this.renderer.gl; this.bindGraphics(graphics, webGLData, this.renderer); - if (this.stencilStack.length === 0) { + if (this.stencilStack.length === 0) + { gl.enable(gl.STENCIL_TEST); gl.clear(gl.STENCIL_BUFFER_BIT); this.reverse = true; @@ -47,14 +50,17 @@ // draw the triangle strip! - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } @@ -62,31 +68,38 @@ // draw a quad to increment.. gl.drawElements(gl.TRIANGLE_FAN, 4, gl.UNSIGNED_SHORT, ( webGLData.indices.length - 4 ) * 2 ); - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); } this.reverse = !this.reverse; } - else { - if (!this.reverse) { + else + { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } - else { + 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) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); } } @@ -103,7 +116,8 @@ * @param graphics {Graphics} * @param webGLData {Array} */ -WebGLStencilManager.prototype.bindGraphics = function (graphics, webGLData) { +WebGLStencilManager.prototype.bindGraphics = function (graphics, webGLData) +{ //if (this._currentGraphics === graphics)return; this._currentGraphics = graphics; @@ -114,7 +128,8 @@ offset = this.renderer.offset, shader;// = this.renderer.shaderManager.primitiveShader; - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { shader = this.renderer.shaderManager.complexPrimitiveShader; this.renderer.shaderManager.setShader(shader); @@ -141,7 +156,8 @@ // set the index buffer! gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, webGLData.indexBuffer); } - else { + else + { //this.renderer.shaderManager.activatePrimitiveShader(); shader = this.renderer.shaderManager.primitiveShader; this.renderer.shaderManager.setShader( shader ); @@ -154,7 +170,7 @@ gl.uniform2f(shader.uniforms.offsetVector._location, -offset.x, -offset.y); gl.uniform3fv(shader.uniforms.tint._location, utils.hex2rgb(graphics.tint)); - + gl.uniform1f(shader.uniforms.alpha._location, graphics.worldAlpha); @@ -172,19 +188,22 @@ * @param graphics {Graphics} * @param webGLData {Array} */ -WebGLStencilManager.prototype.popStencil = function (graphics, webGLData) { +WebGLStencilManager.prototype.popStencil = function (graphics, webGLData) +{ var gl = this.renderer.gl; this.stencilStack.pop(); this.count--; - if (this.stencilStack.length === 0) { + if (this.stencilStack.length === 0) + { // the stack is empty! gl.disable(gl.STENCIL_TEST); } - else { + else + { var level = this.count; @@ -192,14 +211,17 @@ gl.colorMask(false, false, false, false); - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { this.reverse = !this.reverse; - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } @@ -213,31 +235,38 @@ // draw the triangle strip! gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); - if (!this.reverse) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); } } - else { + else + { // console.log("<<>>") - if (!this.reverse) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } - else { + 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) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); } } @@ -253,7 +282,8 @@ * Destroys the mask stack. * */ -WebGLStencilManager.prototype.destroy = function () { +WebGLStencilManager.prototype.destroy = function () +{ this.renderer = null; this.stencilStack = null; }; diff --git a/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js b/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js index 913ba5e..1ea7d19 100644 --- a/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js +++ b/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function ComplexPrimitiveShader(gl) { +function ComplexPrimitiveShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -24,7 +25,8 @@ 'uniform float flipY;', 'varying vec4 vColor;', - 'void main(void) {', + '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);', @@ -37,7 +39,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = vColor;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/FastShader.js b/src/core/renderers/webgl/shaders/FastShader.js index bd2e29a..2e5e060 100644 --- a/src/core/renderers/webgl/shaders/FastShader.js +++ b/src/core/renderers/webgl/shaders/FastShader.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function FastShader(gl) { +function FastShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -28,7 +29,8 @@ 'const vec2 center = vec2(-1.0, 1.0);', - 'void main(void) {', + 'void main(void) + {', ' vec2 v;', ' vec2 sv = aVertexPosition * aScale;', ' v.x = (sv.x) * cos(aRotation) - (sv.y) * sin(aRotation);', @@ -49,7 +51,8 @@ 'uniform sampler2D uSampler;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/PrimitiveShader.js b/src/core/renderers/webgl/shaders/PrimitiveShader.js index 6f25409..a25f54f 100644 --- a/src/core/renderers/webgl/shaders/PrimitiveShader.js +++ b/src/core/renderers/webgl/shaders/PrimitiveShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function PrimitiveShader(gl) { +function PrimitiveShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -23,7 +24,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + '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);', @@ -36,7 +38,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = vColor;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/Shader.js b/src/core/renderers/webgl/shaders/Shader.js index f8964f5..fd75ef5 100644 --- a/src/core/renderers/webgl/shaders/Shader.js +++ b/src/core/renderers/webgl/shaders/Shader.js @@ -6,7 +6,8 @@ * @param [fragmentSrc] {string} The source of the fragment shader. * @param [vertexSrc] {string} The source of the vertex shader. */ -function Shader(gl, vertexSrc, fragmentSrc, customUniforms, customAttributes) { +function Shader(gl, vertexSrc, fragmentSrc, customUniforms, customAttributes) +{ /** * @member {number} * @readonly @@ -33,7 +34,8 @@ dimensions: { type: '4f', value: new Float32Array(4) } }; - for (var u in customUniforms) { + for (var u in customUniforms) + { this.uniforms[u] = customUniforms[u]; } @@ -43,7 +45,8 @@ aColor: 0 }; - for (var a in customAttributes) { + for (var a in customAttributes) + { this.attributes[a] = customAttributes[a]; } @@ -66,7 +69,8 @@ 'const vec2 center = vec2(-1.0, 1.0);', - 'void main(void) {', + 'void main(void) + {', ' gl_Position = vec4( ((aVertexPosition + offsetVector) / projectionVector) + center , 0.0, 1.0);', ' vTextureCoord = aTextureCoord;', ' vColor = vec4(aColor.rgb * aColor.a, aColor.a);', @@ -85,7 +89,8 @@ 'uniform sampler2D uSampler;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;', '}' ].join('\n'); @@ -96,7 +101,8 @@ Shader.prototype.constructor = Shader; module.exports = Shader; -Shader.prototype.init = function () { +Shader.prototype.init = function () +{ this.compile(); this.gl.useProgram(this.program); @@ -105,14 +111,18 @@ this.cacheAttributeLocations(Object.keys(this.attributes)); }; -Shader.prototype.cacheUniformLocations = function (keys) { - for (var i = 0; i < keys.length; ++i) { +Shader.prototype.cacheUniformLocations = function (keys) +{ + for (var i = 0; i < keys.length; ++i) + { this.uniforms[keys[i]]._location = this.gl.getUniformLocation(this.program, keys[i]); } }; -Shader.prototype.cacheAttributeLocations = function (keys) { - for (var i = 0; i < keys.length; ++i) { +Shader.prototype.cacheAttributeLocations = function (keys) +{ + for (var i = 0; i < keys.length; ++i) + { this.attributes[keys[i]] = this.gl.getAttribLocation(this.program, keys[i]); } @@ -124,14 +134,16 @@ // 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.attributes.aColor === -1) { + // if (this.attributes.aColor === -1) + { // this.attributes.aColor = 2; // } // End worst hack eva // }; -Shader.prototype.compile = function () { +Shader.prototype.compile = function () +{ var gl = this.gl; var glVertShader = this._glCompile(gl.VERTEX_SHADER, this.vertexSrc); @@ -144,13 +156,15 @@ gl.linkProgram(program); // if linking fails, then log and cleanup - if (!gl.getProgramParameter(program, gl.LINK_STATUS)) { + if (!gl.getProgramParameter(program, gl.LINK_STATUS)) + { window.console.error('Pixi.js Error: Could not initialize shader.'); window.console.error('gl.VALIDATE_STATUS', gl.getProgramParameter(program, gl.VALIDATE_STATUS)); window.console.error('gl.getError()', gl.getError()); // if there is a program info log, log it - if (gl.getProgramInfoLog(program) !== '') { + if (gl.getProgramInfoLog(program) !== '') + { window.console.warn('Pixi.js Warning: gl.getProgramInfoLog()', gl.getProgramInfoLog(program)); } @@ -165,18 +179,21 @@ return (this.program = program); }; -Shader.prototype.syncUniforms = function () { +Shader.prototype.syncUniforms = function () +{ var gl = this.gl; this.textureCount = 1; - for (var key in this.uniforms) { + for (var key in this.uniforms) + { var uniform = this.uniforms[key], location = uniform._location, value = uniform.value, i, il; - switch (uniform.type) { + switch (uniform.type) + { // single int value case 'i': case '1i': @@ -282,7 +299,8 @@ // a Color Value case 'c': - if (typeof value === 'number') { + if (typeof value === 'number') + { value = utils.hex2rgb(value); } @@ -311,11 +329,13 @@ // array of 2D Point objects case 'v2v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(2 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 2] = value[i].x; uniform._array[i * 2 + 1] = value[i].y; } @@ -325,11 +345,13 @@ // array of 3D Point objects case 'v3v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(3 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 3] = value[i].x; uniform._array[i * 3 + 1] = value[i].y; uniform._array[i * 3 + 2] = value[i].z; @@ -341,11 +363,13 @@ // array of 4D Point objects case 'v4v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(4 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 4] = value[i].x; uniform._array[i * 4 + 1] = value[i].y; uniform._array[i * 4 + 2] = value[i].z; @@ -359,7 +383,8 @@ // PIXI.Texture case 't': case 'sampler2D': - if (!uniform.value || !uniform.value.baseTexture || !uniform.value.baseTexture.hasLoaded) { + if (!uniform.value || !uniform.value.baseTexture || !uniform.value.baseTexture.hasLoaded) + { break; } @@ -376,7 +401,8 @@ this.textureCount++; // initialize the texture if we haven't yet - if (!uniform._init) { + if (!uniform._init) + { this.initSampler2D(uniform); uniform._init = true; @@ -394,11 +420,13 @@ * Initialises a Sampler2D uniform (which may only be available later on after initUniforms once the texture has loaded) * */ -Shader.prototype.initSampler2D = function (uniform) { +Shader.prototype.initSampler2D = function (uniform) +{ var gl = this.gl; // Extended texture data - if (uniform.textureData) { + if (uniform.textureData) + { var data = uniform.textureData; // GLTexture = mag linear, min linear_mipmap_linear, wrap repeat + gl.generateMipmap(gl.TEXTURE_2D); @@ -417,14 +445,16 @@ var wrapT = (data.wrapT) ? data.wrapT : gl.CLAMP_TO_EDGE; var format = (data.luminance) ? gl.LUMINANCE : gl.RGBA; - if (data.repeat) { + if (data.repeat) + { wrapS = gl.REPEAT; wrapT = gl.REPEAT; } gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, !!data.flipY); - if (data.width) { + if (data.width) + { var width = (data.width) ? data.width : 512; var height = (data.height) ? data.height : 2; var border = (data.border) ? data.border : 0; @@ -432,7 +462,8 @@ // 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 { + 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); } @@ -448,7 +479,8 @@ * Destroys the shader. * */ -Shader.prototype.destroy = function () { +Shader.prototype.destroy = function () +{ this.gl.deleteProgram(this.program); this.gl = null; @@ -459,13 +491,15 @@ this.fragmentSrc = null; }; -Shader.prototype._glCompile = function (type, src) { +Shader.prototype._glCompile = function (type, src) +{ var shader = this.gl.createShader(type); this.gl.shaderSource(shader, src); this.gl.compileShader(shader); - if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) { + if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) + { window.console.log(this.gl.getShaderInfoLog(shader)); return null; } diff --git a/src/core/renderers/webgl/shaders/StripShader.js b/src/core/renderers/webgl/shaders/StripShader.js index 193f6e1..a7abcc6 100644 --- a/src/core/renderers/webgl/shaders/StripShader.js +++ b/src/core/renderers/webgl/shaders/StripShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function StripShader(gl) { +function StripShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -20,7 +21,8 @@ 'varying vec2 vTextureCoord;', - 'void main(void) {', + '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);', @@ -36,7 +38,8 @@ 'varying vec2 vTextureCoord;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vec2(vTextureCoord.x, vTextureCoord.y)) * alpha;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/utils/FilterTexture.js b/src/core/renderers/webgl/utils/FilterTexture.js index d2c8423..4433d44 100644 --- a/src/core/renderers/webgl/utils/FilterTexture.js +++ b/src/core/renderers/webgl/utils/FilterTexture.js @@ -8,7 +8,8 @@ * @param height {number} the vertical range of the filter * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values */ -function FilterTexture(gl, width, height, scaleMode) { +function FilterTexture(gl, width, height, scaleMode) +{ /** * @member {WebGLContext} */ @@ -59,7 +60,8 @@ * Clears the filter texture. * */ -FilterTexture.prototype.clear = function () { +FilterTexture.prototype.clear = function () +{ var gl = this.gl; gl.clearColor(0,0,0, 0); @@ -72,8 +74,10 @@ * @param width {number} the new width of the texture * @param height {number} the new height of the texture */ -FilterTexture.prototype.resize = function (width, height) { - if (this.width === width && this.height === height) { +FilterTexture.prototype.resize = function (width, height) +{ + if (this.width === width && this.height === height) + { return; } @@ -96,7 +100,8 @@ * Destroys the filter texture. * */ -FilterTexture.prototype.destroy = function () { +FilterTexture.prototype.destroy = function () +{ var gl = this.gl; gl.deleteFramebuffer( this.frameBuffer ); gl.deleteTexture( this.texture ); diff --git a/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js b/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js index c4721e9..a63f4d7 100644 --- a/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js +++ b/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js @@ -14,7 +14,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this sprite batch works for. */ -function WebGLFastSpriteBatch(renderer) { +function WebGLFastSpriteBatch(renderer) +{ /** * The renderer instance this sprite batch operates on. * @@ -91,7 +92,8 @@ */ this.lastIndexCount = 0; - for (var i=0, j=0; i < numIndices; i += 6, j += 4) { + 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; @@ -144,7 +146,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.setupContext(); }); } @@ -157,7 +160,8 @@ * * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLFastSpriteBatch.prototype.setupContext = function () { +WebGLFastSpriteBatch.prototype.setupContext = function () +{ var gl = this.renderer.gl; // create a couple of buffers @@ -177,7 +181,8 @@ /** * @param spriteBatch {SpriteBatch} The SpriteBatch container to prepare for. */ -WebGLFastSpriteBatch.prototype.begin = function (spriteBatch) { +WebGLFastSpriteBatch.prototype.begin = function (spriteBatch) +{ this.shader = this.renderer.shaderManager.fastShader; this.matrix = spriteBatch.worldTransform.toArray(true); @@ -187,33 +192,38 @@ /** */ -WebGLFastSpriteBatch.prototype.end = function () { +WebGLFastSpriteBatch.prototype.end = function () +{ this.flush(); }; /** * @param spriteBatch {SpriteBatch} The SpriteBatch container to render. */ -WebGLFastSpriteBatch.prototype.render = function (spriteBatch) { +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) { + if (!sprite.texture._uvs) + { return; } this.currentBaseTexture = sprite.texture.baseTexture; // check blend mode - if (sprite.blendMode !== this.renderer.blendModeManager.currentBlendMode) { + if (sprite.blendMode !== this.renderer.blendModeManager.currentBlendMode) + { this.flush(); this.renderer.blendModeManager.setBlendMode(sprite.blendMode); } - for (var i=0,j= children.length; i= this.size) { + if (this.currentBatchSize >= this.size) + { this.flush(); } }; @@ -362,29 +379,35 @@ /** * */ -WebGLFastSpriteBatch.prototype.flush = function () { +WebGLFastSpriteBatch.prototype.flush = function () +{ // If the batch is length 0 then return as there is nothing to draw - if (this.currentBatchSize === 0) { + if (this.currentBatchSize === 0) + { return; } var gl = this.renderer.gl; // bind the current texture - if (!this.currentBaseTexture._glTextures[gl.id]) { + if (!this.currentBaseTexture._glTextures[gl.id]) + { this.renderer.updateTexture(this.currentBaseTexture, gl); } //TODO-SHOUD THIS BE ELSE??!?!?! - else { + else + { gl.bindTexture(gl.TEXTURE_2D, this.currentBaseTexture._glTextures[gl.id]); } // upload the verts to the buffer - if (this.currentBatchSize > ( this.size * 0.5 ) ) { + if (this.currentBatchSize > ( this.size * 0.5 ) ) + { gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); } - else { + else + { var view = this.vertices.subarray(0, this.currentBatchSize * this.vertByteSize); gl.bufferSubData(gl.ARRAY_BUFFER, 0, view); @@ -405,14 +428,16 @@ * Ends the batch and flushes * */ -WebGLFastSpriteBatch.prototype.stop = function () { +WebGLFastSpriteBatch.prototype.stop = function () +{ this.flush(); }; /** * */ -WebGLFastSpriteBatch.prototype.start = function () { +WebGLFastSpriteBatch.prototype.start = function () +{ var gl = this.renderer.gl; // bind the main texture diff --git a/src/core/renderers/webgl/utils/WebGLGraphics.js b/src/core/renderers/webgl/utils/WebGLGraphics.js index 55f4911..ab8f46e 100644 --- a/src/core/renderers/webgl/utils/WebGLGraphics.js +++ b/src/core/renderers/webgl/utils/WebGLGraphics.js @@ -19,7 +19,8 @@ * @param graphics {Graphics} * @param renderer {WebGLRenderer} */ -WebGLGraphics.renderGraphics = function (graphics, renderer) {//projection, offset) { +WebGLGraphics.renderGraphics = function (graphics, renderer) {//projection, offset) +{ var gl = renderer.gl; var projection = renderer.projection, @@ -27,7 +28,8 @@ shader = renderer.shaderManager.primitiveShader, webGLData; - if (graphics.dirty) { + if (graphics.dirty) + { WebGLGraphics.updateGraphics(graphics, gl); } @@ -35,8 +37,10 @@ // This could be speeded up for sure! - for (var i = 0; i < webGL.data.length; i++) { - if (webGL.data[i].mode === 1) { + for (var i = 0; i < webGL.data.length; i++) + { + if (webGL.data[i].mode === 1) + { webGLData = webGL.data[i]; renderer.stencilManager.pushStencil(graphics, webGLData, renderer); @@ -46,7 +50,8 @@ renderer.stencilManager.popStencil(graphics, webGLData, renderer); } - else { + else + { webGLData = webGL.data[i]; @@ -84,12 +89,14 @@ * @param graphicsData {Graphics} The graphics object to update * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLGraphics.updateGraphics = function (graphics, gl) { +WebGLGraphics.updateGraphics = function (graphics, gl) +{ // get the contexts graphics object var webGL = graphics._webGL[gl.id]; // if the graphics object does not exist in the webGL context time to create it! - if (!webGL) { + if (!webGL) + { webGL = graphics._webGL[gl.id] = {lastIndex:0, data:[], gl:gl}; } @@ -99,11 +106,13 @@ var i; // if the user cleared the graphics object we will need to clear every object - if (graphics.clearDirty) { + if (graphics.clearDirty) + { graphics.clearDirty = false; // lop through and return all the webGLDatas to the object pool so than can be reused later on - for (i = 0; i < webGL.data.length; i++) { + for (i = 0; i < webGL.data.length; i++) + { var graphicsData = webGL.data[i]; graphicsData.reset(); WebGLGraphics.graphicsDataPool.push( graphicsData ); @@ -119,58 +128,72 @@ // loop through the graphics datas and construct each one.. // if the object is a complex fill then the new stencil buffer technique will be used // other wise graphics objects will be pushed into a batch.. - for (i = webGL.lastIndex; i < graphics.graphicsData.length; i++) { + for (i = webGL.lastIndex; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { // need to add the points the the graphics object.. data.points = data.shape.points.slice(); - if (data.shape.closed) { + if (data.shape.closed) + { // close the poly if the value is true! - if (data.points[0] !== data.points[data.points.length-2] || data.points[1] !== data.points[data.points.length-1]) { + if (data.points[0] !== data.points[data.points.length-2] || data.points[1] !== data.points[data.points.length-1]) + { data.points.push(data.points[0], data.points[1]); } } // MAKE SURE WE HAVE THE CORRECT TYPE.. - if (data.fill) { - if (data.points.length >= 6) { - if (data.points.length < 6 * 2) { + if (data.fill) + { + if (data.points.length >= 6) + { + if (data.points.length < 6 * 2) + { webGLData = WebGLGraphics.switchMode(webGL, 0); var canDrawUsingSimple = WebGLGraphics.buildPoly(data, webGLData); // console.log(canDrawUsingSimple); - if (!canDrawUsingSimple) { + if (!canDrawUsingSimple) + { // console.log("<>>>") webGLData = WebGLGraphics.switchMode(webGL, 1); WebGLGraphics.buildComplexPoly(data, webGLData); } } - else { + else + { webGLData = WebGLGraphics.switchMode(webGL, 1); WebGLGraphics.buildComplexPoly(data, webGLData); } } } - if (data.lineWidth > 0) { + if (data.lineWidth > 0) + { webGLData = WebGLGraphics.switchMode(webGL, 0); WebGLGraphics.buildLine(data, webGLData); } } - else { + else + { webGLData = WebGLGraphics.switchMode(webGL, 0); - if (data.type === CONST.SHAPES.RECT) { + if (data.type === CONST.SHAPES.RECT) + { WebGLGraphics.buildRectangle(data, webGLData); } - else if (data.type === CONST.SHAPES.CIRC || data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.CIRC || data.type === CONST.SHAPES.ELIP) + { WebGLGraphics.buildCircle(data, webGLData); } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { WebGLGraphics.buildRoundedRectangle(data, webGLData); } } @@ -179,10 +202,12 @@ } // upload all the dirty data... - for (i = 0; i < webGL.data.length; i++) { + for (i = 0; i < webGL.data.length; i++) + { webGLData = webGL.data[i]; - if (webGLData.dirty) { + if (webGLData.dirty) + { webGLData.upload(); } } @@ -194,18 +219,22 @@ * @param webGL {WebGLContext} * @param type {number} */ -WebGLGraphics.switchMode = function (webGL, type) { +WebGLGraphics.switchMode = function (webGL, type) +{ var webGLData; - if (!webGL.data.length) { + if (!webGL.data.length) + { webGLData = WebGLGraphics.graphicsDataPool.pop() || new WebGLGraphicsData(webGL.gl); webGLData.mode = type; webGL.data.push(webGLData); } - else { + else + { webGLData = webGL.data[webGL.data.length-1]; - if (webGLData.mode !== type || type === 1) { + if (webGLData.mode !== type || type === 1) + { webGLData = WebGLGraphics.graphicsDataPool.pop() || new WebGLGraphicsData(webGL.gl); webGLData.mode = type; webGL.data.push(webGLData); @@ -225,7 +254,8 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildRectangle = function (graphicsData, webGLData) { +WebGLGraphics.buildRectangle = function (graphicsData, webGLData) +{ // --- // // need to convert points to a nice regular data // @@ -235,7 +265,8 @@ var width = rectData.width; var height = rectData.height; - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -265,7 +296,8 @@ indices.push(vertPos, vertPos, vertPos+1, vertPos+2, vertPos+3, vertPos+3); } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = [x, y, @@ -289,7 +321,8 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildRoundedRectangle = function (graphicsData, webGLData) { +WebGLGraphics.buildRoundedRectangle = function (graphicsData, webGLData) +{ var rrectData = graphicsData.shape; var x = rrectData.x; var y = rrectData.y; @@ -305,7 +338,8 @@ recPoints = recPoints.concat(WebGLGraphics.quadraticBezierCurve(x + width, y + radius, x + width, y, x + width - radius, y)); recPoints = recPoints.concat(WebGLGraphics.quadraticBezierCurve(x + radius, y, x, y, x, y + radius)); - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -323,7 +357,8 @@ // var i = 0; - for (i = 0; i < triangles.length; i+=3) { + for (i = 0; i < triangles.length; i+=3) + { indices.push(triangles[i] + vecPos); indices.push(triangles[i] + vecPos); indices.push(triangles[i+1] + vecPos); @@ -332,12 +367,14 @@ } - for (i = 0; i < recPoints.length; i++) { + for (i = 0; i < recPoints.length; i++) + { verts.push(recPoints[i], recPoints[++i], r, g, b, alpha); } } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = recPoints; @@ -362,7 +399,8 @@ * @param toY {number} Destination point y * @return {number[]} */ -WebGLGraphics.quadraticBezierCurve = function (fromX, fromY, cpX, cpY, toX, toY) { +WebGLGraphics.quadraticBezierCurve = function (fromX, fromY, cpX, cpY, toX, toY) +{ var xa, ya, @@ -373,14 +411,16 @@ n = 20, points = []; - function getPt(n1 , n2, perc) { + function getPt(n1 , n2, perc) + { var diff = n2 - n1; return n1 + ( diff * perc ); } var j = 0; - for (var i = 0; i <= n; i++ ) { + for (var i = 0; i <= n; i++ ) + { j = i / n; // The Green Line @@ -406,7 +446,8 @@ * @param graphicsData {Graphics} The graphics object to draw * @param webGLData {object} */ -WebGLGraphics.buildCircle = function (graphicsData, webGLData) { +WebGLGraphics.buildCircle = function (graphicsData, webGLData) +{ // need to convert points to a nice regular data var circleData = graphicsData.shape; var x = circleData.x; @@ -415,11 +456,13 @@ var height; // TODO - bit hacky?? - if (graphicsData.type === CONST.SHAPES.CIRC) { + if (graphicsData.type === CONST.SHAPES.CIRC) + { width = circleData.radius; height = circleData.radius; } - else { + else + { width = circleData.width; height = circleData.height; } @@ -429,7 +472,8 @@ var i = 0; - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -444,7 +488,8 @@ indices.push(vecPos); - for (i = 0; i < totalSegs + 1 ; i++) { + for (i = 0; i < totalSegs + 1 ; i++) + { verts.push(x,y, r, g, b, alpha); verts.push(x + Math.sin(seg * i) * width, @@ -457,12 +502,14 @@ indices.push(vecPos-1); } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = []; - for (i = 0; i < totalSegs + 1; i++) { + for (i = 0; i < totalSegs + 1; i++) + { graphicsData.points.push(x + Math.sin(seg * i) * width, y + Math.cos(seg * i) * height); } @@ -481,18 +528,22 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildLine = function (graphicsData, webGLData) { +WebGLGraphics.buildLine = function (graphicsData, webGLData) +{ // TODO OPTIMISE! var i = 0; var points = graphicsData.points; - if (points.length === 0) { + if (points.length === 0) + { return; } // if the line width is an odd number add 0.5 to align to a whole pixel - if (graphicsData.lineWidth%2) { - for (i = 0; i < points.length; i++) { + if (graphicsData.lineWidth%2) + { + for (i = 0; i < points.length; i++) + { points[i] += 0.5; } } @@ -502,7 +553,8 @@ var lastPoint = new math.Point(points[points.length - 2], points[points.length - 1]); // if the first point is the last point - gonna have issues :) - if (firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) { + if (firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) + { // need to clone as we are going to slightly modify the shape.. points = points.slice(); @@ -562,7 +614,8 @@ verts.push(p1x + perpx , p1y + perpy, r, g, b, alpha); - for (i = 1; i < length-1; i++) { + for (i = 1; i < length-1; i++) + { p1x = points[(i-1)*2]; p1y = points[(i-1)*2 + 1]; @@ -599,7 +652,8 @@ denom = a1*b2 - a2*b1; - if (Math.abs(denom) < 0.1 ) { + if (Math.abs(denom) < 0.1 ) + { denom+=10.1; verts.push(p2x - perpx , p2y - perpy, @@ -618,7 +672,8 @@ pdist = (px -p2x) * (px -p2x) + (py -p2y) + (py -p2y); - if (pdist > 140 * 140) { + if (pdist > 140 * 140) + { perp3x = perpx - perp2x; perp3y = perpy - perp2y; @@ -639,7 +694,8 @@ indexCount++; } - else { + else + { verts.push(px , py); verts.push(r, g, b, alpha); @@ -672,7 +728,8 @@ indices.push(indexStart); - for (i = 0; i < indexCount; i++) { + for (i = 0; i < indexCount; i++) + { indices.push(indexStart++); } @@ -687,11 +744,13 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildComplexPoly = function (graphicsData, webGLData) { +WebGLGraphics.buildComplexPoly = function (graphicsData, webGLData) +{ //TODO - no need to copy this as it gets turned into a FLoat32Array anyways.. var points = graphicsData.points.slice(); - if (points.length < 6) { + if (points.length < 6) + { return; } @@ -711,7 +770,8 @@ var x,y; // get size.. - for (var i = 0; i < points.length; i+=2) { + for (var i = 0; i < points.length; i+=2) + { x = points[i]; y = points[i+1]; @@ -732,7 +792,8 @@ //TODO - this aint needed! var length = points.length / 2; - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { indices.push( i ); } @@ -746,10 +807,12 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildPoly = function (graphicsData, webGLData) { +WebGLGraphics.buildPoly = function (graphicsData, webGLData) +{ var points = graphicsData.points; - if (points.length < 6) { + if (points.length < 6) + { return; } // get first and last point.. figure out the middle! @@ -767,7 +830,8 @@ var triangles = utils.PolyK.Triangulate(points); - if (!triangles) { + if (!triangles) + { return false; } @@ -775,7 +839,8 @@ var i = 0; - for (i = 0; i < triangles.length; i+=3) { + for (i = 0; i < triangles.length; i+=3) + { indices.push(triangles[i] + vertPos); indices.push(triangles[i] + vertPos); indices.push(triangles[i+1] + vertPos); @@ -783,7 +848,8 @@ indices.push(triangles[i+2] + vertPos); } - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { verts.push(points[i * 2], points[i * 2 + 1], r, g, b, alpha); } diff --git a/src/core/renderers/webgl/utils/WebGLGraphicsData.js b/src/core/renderers/webgl/utils/WebGLGraphicsData.js index c56d05e..c739ba7 100644 --- a/src/core/renderers/webgl/utils/WebGLGraphicsData.js +++ b/src/core/renderers/webgl/utils/WebGLGraphicsData.js @@ -2,7 +2,8 @@ * @class * @private */ -function WebGLGraphicsData(gl) { +function WebGLGraphicsData(gl) +{ this.gl = gl; //TODO does this need to be split before uploding?? @@ -22,7 +23,8 @@ /** * */ -WebGLGraphicsData.prototype.reset = function () { +WebGLGraphicsData.prototype.reset = function () +{ this.points.length = 0; this.indices.length = 0; }; @@ -30,7 +32,8 @@ /** * */ -WebGLGraphicsData.prototype.upload = function () { +WebGLGraphicsData.prototype.upload = function () +{ var gl = this.gl; // this.lastIndex = graphics.graphicsData.length; diff --git a/src/core/renderers/webgl/utils/WebGLSpriteBatch.js b/src/core/renderers/webgl/utils/WebGLSpriteBatch.js index 96eaa52..55befbb 100644 --- a/src/core/renderers/webgl/utils/WebGLSpriteBatch.js +++ b/src/core/renderers/webgl/utils/WebGLSpriteBatch.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this sprite batch works for. */ -function WebGLSpriteBatch(renderer) { +function WebGLSpriteBatch(renderer) +{ /** * * @@ -88,7 +89,8 @@ */ this.lastIndexCount = 0; - for (var i=0, j=0; i < numIndices; i += 6, j += 4) { + 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; @@ -162,7 +164,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.setupContext(); }); } @@ -173,7 +176,8 @@ /** * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLSpriteBatch.prototype.setupContext = function () { +WebGLSpriteBatch.prototype.setupContext = function () +{ var gl = this.renderer.gl; // setup default shader @@ -198,7 +202,8 @@ /** * */ -WebGLSpriteBatch.prototype.begin = function () { +WebGLSpriteBatch.prototype.begin = function () +{ // this.shader = this.renderer.shaderManager.defaultShader; this.start(); @@ -206,19 +211,22 @@ /** */ -WebGLSpriteBatch.prototype.end = function () { +WebGLSpriteBatch.prototype.end = function () +{ this.flush(); }; /** * @param sprite {Sprite} the sprite to render when using this spritebatch */ -WebGLSpriteBatch.prototype.render = function (sprite) { +WebGLSpriteBatch.prototype.render = function (sprite) +{ var texture = sprite.texture; //TODO set blend modes.. // check texture.. - if (this.currentBatchSize >= this.size) { + if (this.currentBatchSize >= this.size) + { this.flush(); this.currentBaseTexture = texture.baseTexture; } @@ -227,7 +235,8 @@ var uvs = texture._uvs; // if the uvs have not updated then no point rendering just yet! - if (!uvs) { + if (!uvs) + { return; } @@ -237,7 +246,8 @@ var w0, w1, h0, h1; - if (texture.trim) { + 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; @@ -248,7 +258,8 @@ h0 = h1 + texture.crop.height; } - else { + else + { w0 = (texture.frame.width ) * (1-aX); w1 = (texture.frame.width ) * -aX; @@ -272,7 +283,8 @@ var colors = this.colors; var positions = this.positions; - if (this.renderer.roundPixels) { + if (this.renderer.roundPixels) + { // xy positions[index] = a * w1 + c * h1 + tx | 0; positions[index+1] = d * h1 + b * w1 + ty | 0; @@ -289,7 +301,8 @@ positions[index+15] = a * w1 + c * h0 + tx | 0; positions[index+16] = d * h0 + b * w1 + ty | 0; } - else { + else + { // xy positions[index] = a * w1 + c * h1 + tx; positions[index+1] = d * h1 + b * w1 + ty; @@ -338,11 +351,13 @@ * * @param sprite {TilingSprite} the tilingSprite to render */ -WebGLSpriteBatch.prototype.renderTilingSprite = function (tilingSprite) { +WebGLSpriteBatch.prototype.renderTilingSprite = function (tilingSprite) +{ var texture = tilingSprite.tilingTexture; // check texture.. - if (this.currentBatchSize >= this.size) { + if (this.currentBatchSize >= this.size) + { //return; this.flush(); this.currentBaseTexture = texture.baseTexture; @@ -351,7 +366,8 @@ // set the textures uvs temporarily // TODO create a separate texture so that we can tile part of a texture - if (!tilingSprite._uvs) { + if (!tilingSprite._uvs) + { tilingSprite._uvs = new TextureUvs(); } @@ -454,16 +470,19 @@ * Renders the content and empties the current batch. * */ -WebGLSpriteBatch.prototype.flush = function () { +WebGLSpriteBatch.prototype.flush = function () +{ // If the batch is length 0 then return as there is nothing to draw - if (this.currentBatchSize === 0) { + if (this.currentBatchSize === 0) + { return; } var gl = this.renderer.gl; var shader; - if (this.dirty) { + if (this.dirty) + { this.dirty = false; // bind the main texture gl.activeTexture(gl.TEXTURE0); @@ -482,10 +501,12 @@ } // upload the verts to the buffer - if (this.currentBatchSize > ( this.size * 0.5 ) ) { + if (this.currentBatchSize > ( this.size * 0.5 ) ) + { gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); } - else { + else + { var view = this.positions.subarray(0, this.currentBatchSize * this.vertByteSize); gl.bufferSubData(gl.ARRAY_BUFFER, 0, view); } @@ -502,7 +523,8 @@ var shaderSwap = false; var sprite; - for (var i = 0, j = this.currentBatchSize; i < j; i++) { + for (var i = 0, j = this.currentBatchSize; i < j; i++) + { sprite = this.sprites[i]; @@ -513,24 +535,28 @@ blendSwap = currentBlendMode !== nextBlendMode; shaderSwap = currentShader !== nextShader; // should I use uuidS??? - if (currentBaseTexture !== nextTexture || blendSwap || shaderSwap) { + if (currentBaseTexture !== nextTexture || blendSwap || shaderSwap) + { this.renderBatch(currentBaseTexture, batchSize, start); start = i; batchSize = 0; currentBaseTexture = nextTexture; - if (blendSwap) { + if (blendSwap) + { currentBlendMode = nextBlendMode; this.renderer.blendModeManager.setBlendMode( currentBlendMode ); } - if (shaderSwap) { + if (shaderSwap) + { currentShader = nextShader; shader = currentShader.shaders ? currentShader.shaders[gl.id] : currentShader; - if (!shader) { + if (!shader) + { shader = new Shader(gl, null, currentShader.fragmentSrc, currentShader.uniforms); currentShader.shaders[gl.id] = shader; } @@ -538,7 +564,8 @@ // set shader function??? this.renderer.shaderManager.setShader(shader); - if (shader.dirty) { + if (shader.dirty) + { shader.syncUniforms(); } @@ -569,17 +596,21 @@ * @param size {number} * @param startIndex {number} */ -WebGLSpriteBatch.prototype.renderBatch = function (texture, size, startIndex) { - if (size === 0) { +WebGLSpriteBatch.prototype.renderBatch = function (texture, size, startIndex) +{ + if (size === 0) + { return; } var gl = this.renderer.gl; - if (!texture._glTextures[gl.id]) { + if (!texture._glTextures[gl.id]) + { this.renderer.updateTexture(texture); } - else { + else + { // bind the current texture gl.bindTexture(gl.TEXTURE_2D, texture._glTextures[gl.id]); } @@ -594,7 +625,8 @@ /** * */ -WebGLSpriteBatch.prototype.stop = function () { +WebGLSpriteBatch.prototype.stop = function () +{ this.flush(); this.dirty = true; }; @@ -602,7 +634,8 @@ /** * */ -WebGLSpriteBatch.prototype.start = function () { +WebGLSpriteBatch.prototype.start = function () +{ this.dirty = true; }; @@ -610,7 +643,8 @@ * Destroys the SpriteBatch. * */ -WebGLSpriteBatch.prototype.destroy = function () { +WebGLSpriteBatch.prototype.destroy = function () +{ this.renderer.gl.deleteBuffer(this.vertexBuffer); this.renderer.gl.deleteBuffer(this.indexBuffer); diff --git a/src/core/textures/BaseTexture.js b/src/core/textures/BaseTexture.js index 2bf77d4..513d358 100644 --- a/src/core/textures/BaseTexture.js +++ b/src/core/textures/BaseTexture.js @@ -10,7 +10,8 @@ * @param source {Image|Canvas} the source object of the texture. * @param [scaleMode=scaleModes.DEFAULT] {number} See {@link scaleModes} for possible values */ -function BaseTexture(source, scaleMode) { +function BaseTexture(source, scaleMode) +{ this.uuid = utils.uuid(); /** @@ -123,7 +124,8 @@ this._needsUpdate = false; // if no source passed don't try to load - if (source) { + if (source) + { this.loadSource(source); } @@ -149,13 +151,16 @@ Object.defineProperties(BaseTexture.prototype, { needsUpdate: { - get: function () { + get: function () + { return this._needsUpdate; }, - set: function (val) { + set: function (val) + { this._needsUpdate = val; - if (val) { + if (val) + { this.emit('update', this); } } @@ -171,9 +176,11 @@ * * The logic state after calling `loadSource` directly or indirectly (eg. `fromImage`, `new BaseTexture`) is: * - * if (texture.hasLoaded) { + * if (texture.hasLoaded) + { * // texture ready for use - * } else if (texture.isLoading) { + * } else if (texture.isLoading) + { * // listen to 'loaded' and/or 'error' events on texture * } else { * // not loading, not going to load UNLESS the source is reloaded @@ -183,12 +190,14 @@ * @protected * @param source {Image|Canvas} the source object of the texture. */ -BaseTexture.prototype.loadSource = function (source) { +BaseTexture.prototype.loadSource = function (source) +{ var wasLoading = this.isLoading; this.hasLoaded = false; this.isLoading = false; - if (wasLoading && this.source) { + if (wasLoading && this.source) + { this.source.onload = null; this.source.onerror = null; } @@ -196,20 +205,24 @@ this.source = source; // Apply source if loaded. Otherwise setup appropriate loading monitors. - if ((this.source.complete || this.source.getContext) && this.source.width && this.source.height) { + if ((this.source.complete || this.source.getContext) && this.source.width && this.source.height) + { this._sourceLoaded(); } - else if(!source.getContext) { + else if(!source.getContext) + { // Image fail / not ready this.isLoading = true; var scope = this; - source.onload = function () { + source.onload = function () + { source.onload = null; source.onerror = null; - if(!scope.isLoading) { + if(!scope.isLoading) + { return; } @@ -219,11 +232,13 @@ scope.emit('loaded', scope); }; - source.onerror = function () { + source.onerror = function () + { source.onload = null; source.onerror = null; - if(!scope.isLoading) { + if(!scope.isLoading) + { return; } @@ -234,24 +249,29 @@ // Per http://www.w3.org/TR/html5/embedded-content-0.html#the-img-element // "The value of `complete` can thus change while a script is executing." // So complete needs to be re-checked after the callbacks have been added.. - if (source.complete) { + if (source.complete) + { this.isLoading = false; // ..and if we're complete now, no need for callbacks source.onload = null; source.onerror = null; - if (source.width && source.height) { + if (source.width && source.height) + { this._sourceLoaded(); // If any previous subscribers possible - if (wasLoading) { + if (wasLoading) + { this.emit('loaded', this); } } - else { + else + { // If any previous subscribers possible - if (wasLoading) { + if (wasLoading) + { this.emit('error', this); } } @@ -265,7 +285,8 @@ * * @private */ -BaseTexture.prototype._sourceLoaded = function () { +BaseTexture.prototype._sourceLoaded = function () +{ this.hasLoaded = true; this.width = this.source.naturalWidth || this.source.width; @@ -278,16 +299,20 @@ * Destroys this base texture * */ -BaseTexture.prototype.destroy = function () { - if (this.imageUrl) { +BaseTexture.prototype.destroy = function () +{ + if (this.imageUrl) + { delete utils.BaseTextureCache[this.imageUrl]; delete utils.TextureCache[this.imageUrl]; this.imageUrl = null; - if (!navigator.isCocoonJS) { + if (!navigator.isCocoonJS) + { this.source.src = ''; } } - else if (this.source && this.source._pixiId) { + else if (this.source && this.source._pixiId) + { delete utils.BaseTextureCache[this.source._pixiId]; } this.source = null; @@ -301,7 +326,8 @@ * memory again. * */ -BaseTexture.prototype.dispose = function () { +BaseTexture.prototype.dispose = function () +{ this.emit('dispose', this); }; @@ -311,7 +337,8 @@ * * @param newSrc {string} the path of the image */ -BaseTexture.prototype.updateSourceImage = function (newSrc) { +BaseTexture.prototype.updateSourceImage = function (newSrc) +{ this.source.src = newSrc; this.loadSource(this.source); }; @@ -326,18 +353,22 @@ * @param [scaleMode=scaleModes.DEFAULT] {number} See {@link scaleModes} for possible values * @return BaseTexture */ -BaseTexture.fromImage = function (imageUrl, crossorigin, scaleMode) { +BaseTexture.fromImage = function (imageUrl, crossorigin, scaleMode) +{ var baseTexture = utils.BaseTextureCache[imageUrl]; - if (crossorigin === undefined && imageUrl.indexOf('data:') !== 0) { + if (crossorigin === undefined && imageUrl.indexOf('data:') !== 0) + { crossorigin = true; } - if (!baseTexture) { + if (!baseTexture) + { // new Image() breaks tex loading in some versions of Chrome. // See https://code.google.com/p/chromium/issues/detail?id=238071 var image = new Image();//document.createElement('img'); - if (crossorigin) { + if (crossorigin) + { image.crossOrigin = ''; } @@ -347,7 +378,8 @@ utils.BaseTextureCache[imageUrl] = baseTexture; // if there is an @2x at the end of the url we are going to assume its a highres image - if ( imageUrl.indexOf(CONST.RETINA_PREFIX + '.') !== -1) { + if ( imageUrl.indexOf(CONST.RETINA_PREFIX + '.') !== -1) + { baseTexture.resolution = 2; } } @@ -363,14 +395,17 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return BaseTexture */ -BaseTexture.fromCanvas = function (canvas, scaleMode) { - if (!canvas._pixiId) { +BaseTexture.fromCanvas = function (canvas, scaleMode) +{ + if (!canvas._pixiId) + { canvas._pixiId = 'canvas_' + utils.uuid(); } var baseTexture = utils.BaseTextureCache[canvas._pixiId]; - if (!baseTexture) { + if (!baseTexture) + { baseTexture = new BaseTexture(canvas, scaleMode); utils.BaseTextureCache[canvas._pixiId] = baseTexture; } diff --git a/src/core/textures/RenderTexture.js b/src/core/textures/RenderTexture.js index 6dad20f..53ae796 100644 --- a/src/core/textures/RenderTexture.js +++ b/src/core/textures/RenderTexture.js @@ -46,8 +46,10 @@ * @param [scaleMode] {number} See {@link scaleModes} for possible values * @param [resolution=1] {number} The resolution of the texture being generated */ -function RenderTexture(renderer, width, height, scaleMode, resolution) { - if (!renderer) { +function RenderTexture(renderer, width, height, scaleMode, resolution) +{ + if (!renderer) + { throw new Error('Unable to create RenderTexture, you must pass a renderer into the constructor.'); } @@ -133,7 +135,8 @@ */ this.renderer = renderer; - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { var gl = this.renderer.gl; this.textureBuffer = new FilterTexture(gl, this.width * this.resolution, this.height * this.resolution, this.baseTexture.scaleMode); @@ -142,7 +145,8 @@ this.render = this.renderWebGL; this.projection = new math.Point(this.width*0.5, -this.height*0.5); } - else { + else + { this.render = this.renderCanvas; this.textureBuffer = new CanvasBuffer(this.width* this.resolution, this.height* this.resolution); this.baseTexture.source = this.textureBuffer.canvas; @@ -167,8 +171,10 @@ * @param height {number} The height to resize to. * @param updateBase {boolean} Should the baseTexture.width and height values be resized as well? */ -RenderTexture.prototype.resize = function (width, height, updateBase) { - if (width === this.width && height === this.height) { +RenderTexture.prototype.resize = function (width, height, updateBase) +{ + if (width === this.width && height === this.height) + { return; } @@ -177,17 +183,20 @@ this.width = this.frame.width = this.crop.width = width; this.height = this.frame.height = this.crop.height = height; - if (updateBase) { + if (updateBase) + { this.baseTexture.width = this.width; this.baseTexture.height = this.height; } - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { this.projection.x = this.width / 2; this.projection.y = -this.height / 2; } - if (!this.valid) { + if (!this.valid) + { return; } @@ -198,12 +207,15 @@ * Clears the RenderTexture. * */ -RenderTexture.prototype.clear = function () { - if (!this.valid) { +RenderTexture.prototype.clear = function () +{ + if (!this.valid) + { return; } - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { this.renderer.gl.bindFramebuffer(this.renderer.gl.FRAMEBUFFER, this.textureBuffer.frameBuffer); } @@ -220,19 +232,23 @@ * @param [restoreWorldTransform=true] {boolean} If true the displayObject's worldTransform/worldAlpha and all children * transformations will be restored. Not restoring this information will be a little faster. */ -RenderTexture.prototype.renderWebGL = function (displayObject, matrix, clear, restoreWorldTransform) { - if (!this.valid) { +RenderTexture.prototype.renderWebGL = function (displayObject, matrix, clear, restoreWorldTransform) +{ + if (!this.valid) + { return; } - if (typeof restoreWorldTransform === 'undefined') { + if (typeof restoreWorldTransform === 'undefined') + { restoreWorldTransform = true; } var tempAlpha, tempTransform; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { tempAlpha = displayObject.worldAlpha; tempTransform = displayObject.worldTransform.toArray(); } @@ -245,7 +261,8 @@ wt.identity(); wt.translate(0, this.projection.y * 2); - if (matrix) { + if (matrix) + { wt.append(matrix); } @@ -258,7 +275,8 @@ var children = displayObject.children; var i, j; - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } @@ -269,7 +287,8 @@ gl.bindFramebuffer(gl.FRAMEBUFFER, this.textureBuffer.frameBuffer ); - if (clear) { + if (clear) + { this.textureBuffer.clear(); } @@ -279,11 +298,13 @@ this.renderer.spriteBatch.dirty = true; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { displayObject.worldAlpha = tempAlpha; displayObject.worldTransform.fromArray(tempTransform); - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } } @@ -300,26 +321,31 @@ * @param [restoreWorldTransform=true] {boolean} If true the displayObject's worldTransform/worldAlpha and all children * transformations will be restored. Not restoring this information will be a little faster. */ -RenderTexture.prototype.renderCanvas = function (displayObject, matrix, clear, restoreWorldTransform) { - if (!this.valid) { +RenderTexture.prototype.renderCanvas = function (displayObject, matrix, clear, restoreWorldTransform) +{ + if (!this.valid) + { return; } - if (typeof restoreWorldTransform === 'undefined') { + if (typeof restoreWorldTransform === 'undefined') + { restoreWorldTransform = true; } var tempAlpha, tempTransform; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { tempAlpha = displayObject.worldAlpha; tempTransform = displayObject.worldTransform.toArray(); } var wt = displayObject.worldTransform; wt.identity(); - if (matrix) { + if (matrix) + { wt.append(matrix); } @@ -330,11 +356,13 @@ var children = displayObject.children; var i, j; - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } - if (clear) { + if (clear) + { this.textureBuffer.clear(); } @@ -348,11 +376,13 @@ this.renderer.resolution = realResolution; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { displayObject.worldAlpha = tempAlpha; displayObject.worldTransform.fromArray(tempTransform); - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } } @@ -363,7 +393,8 @@ * * @return {Image} */ -RenderTexture.prototype.getImage = function () { +RenderTexture.prototype.getImage = function () +{ var image = new Image(); image.src = this.getBase64(); return image; @@ -374,7 +405,8 @@ * * @return {string} A base64 encoded string of the texture. */ -RenderTexture.prototype.getBase64 = function () { +RenderTexture.prototype.getBase64 = function () +{ return this.getCanvas().toDataURL(); }; @@ -383,8 +415,10 @@ * * @return {HTMLCanvasElement} A Canvas element with the texture rendered on. */ -RenderTexture.prototype.getCanvas = function () { - if (this.renderer.type === CONST.WEBGL_RENDERER) { +RenderTexture.prototype.getCanvas = function () +{ + if (this.renderer.type === CONST.WEBGL_RENDERER) + { var gl = this.renderer.gl; var width = this.textureBuffer.width; var height = this.textureBuffer.height; @@ -403,7 +437,8 @@ return tempCanvas.canvas; } - else { + else + { return this.textureBuffer.canvas; } }; diff --git a/src/core/textures/Texture.js b/src/core/textures/Texture.js index 3c65909..e97f0aa 100644 --- a/src/core/textures/Texture.js +++ b/src/core/textures/Texture.js @@ -17,7 +17,8 @@ * @param [crop] {Rectangle} The area of original texture * @param [trim] {Rectangle} Trimmed texture rectangle */ -function Texture(baseTexture, frame, crop, trim) { +function Texture(baseTexture, frame, crop, trim) +{ /** * Does this Texture have any frame data assigned to it? * @@ -25,12 +26,14 @@ */ this.noFrame = false; - if (!frame) { + if (!frame) + { this.noFrame = true; frame = new math.Rectangle(0, 0, 1, 1); } - if (baseTexture instanceof Texture) { + if (baseTexture instanceof Texture) + { baseTexture = baseTexture.baseTexture; } @@ -100,13 +103,16 @@ */ this.crop = crop || new math.Rectangle(0, 0, 1, 1); - if (baseTexture.hasLoaded) { - if (this.noFrame) { + if (baseTexture.hasLoaded) + { + if (this.noFrame) + { frame = new math.Rectangle(0, 0, baseTexture.width, baseTexture.height); } this.frame = frame; } - else { + else + { baseTexture.addEventListener('loaded', this.onBaseTextureLoaded.bind(this)); } } @@ -118,19 +124,23 @@ Object.defineProperties(Texture.prototype, { needsUpdate: { - get: function () { + get: function () + { return this.baseTexture.needsUpdate; }, - set: function (val) { + set: function (val) + { this.baseTexture.needsUpdate = val; } }, frame: { - get: function () { + get: function () + { return this._frame; }, - set: function (frame) { + set: function (frame) + { this._frame = frame; this.noFrame = false; @@ -143,20 +153,23 @@ 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 (!this.trim && (frame.x + frame.width > this.baseTexture.width || frame.y + frame.height > this.baseTexture.height)) + { throw new Error('Texture Error: frame does not fit inside the base Texture dimensions ' + this); } this.valid = frame && frame.width && frame.height && this.baseTexture.source && this.baseTexture.hasLoaded; - if (this.trim) { + 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) { + if (this.valid) + { this._updateUvs(); } } @@ -168,11 +181,13 @@ * * @private */ -Texture.prototype.onBaseTextureLoaded = function () { +Texture.prototype.onBaseTextureLoaded = function () +{ var baseTexture = this.baseTexture; baseTexture.removeEventListener('loaded', this.onLoaded); - if (this.noFrame) { + if (this.noFrame) + { this.frame = new math.Rectangle(0, 0, baseTexture.width, baseTexture.height); } @@ -184,8 +199,10 @@ * * @param destroyBase {boolean} Whether to destroy the base texture as well */ -Texture.prototype.destroy = function (destroyBase) { - if (destroyBase) { +Texture.prototype.destroy = function (destroyBase) +{ + if (destroyBase) + { this.baseTexture.destroy(); } @@ -197,8 +214,10 @@ * * @private */ -Texture.prototype._updateUvs = function () { - if (!this._uvs) { +Texture.prototype._updateUvs = function () +{ + if (!this._uvs) + { this._uvs = new TextureUvs(); } @@ -229,10 +248,12 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return Texture */ -Texture.fromImage = function (imageUrl, crossorigin, scaleMode) { +Texture.fromImage = function (imageUrl, crossorigin, scaleMode) +{ var texture = utils.TextureCache[imageUrl]; - if (!texture) { + if (!texture) + { texture = new Texture(BaseTexture.fromImage(imageUrl, crossorigin, scaleMode)); utils.TextureCache[imageUrl] = texture; } @@ -248,9 +269,11 @@ * @param frameId {string} The frame id of the texture * @return Texture */ -Texture.fromFrame = function (frameId) { +Texture.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache '); } return texture; @@ -264,7 +287,8 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return {Texture} */ -Texture.fromCanvas = function (canvas, scaleMode) { +Texture.fromCanvas = function (canvas, scaleMode) +{ return new Texture(BaseTexture.fromCanvas(canvas, scaleMode)); }; @@ -276,7 +300,8 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return {Texture} A Texture */ -Texture.fromVideo = function (video, scaleMode) { +Texture.fromVideo = function (video, scaleMode) +{ return new Texture(VideoBaseTexture.baseTextureFromVideo(video, scaleMode)); }; @@ -287,7 +312,8 @@ * @param texture {Texture} The Texture to add to the cache. * @param id {string} The id that the texture will be stored against. */ -Texture.addTextureToCache = function (texture, id) { +Texture.addTextureToCache = function (texture, id) +{ utils.TextureCache[id] = texture; }; @@ -298,7 +324,8 @@ * @param id {string} The id of the texture to be removed * @return {Texture} The texture that was removed */ -Texture.removeTextureFromCache = function (id) { +Texture.removeTextureFromCache = function (id) +{ var texture = utils.TextureCache[id]; delete utils.TextureCache[id]; diff --git a/src/core/textures/TextureUvs.js b/src/core/textures/TextureUvs.js index b9bbb58..5424d52 100644 --- a/src/core/textures/TextureUvs.js +++ b/src/core/textures/TextureUvs.js @@ -1,4 +1,5 @@ -function TextureUvs() { +function TextureUvs() +{ this.x0 = 0; this.y0 = 0; diff --git a/src/core/textures/VideoBaseTexture.js b/src/core/textures/VideoBaseTexture.js index e3e0c5a..1a826a9 100644 --- a/src/core/textures/VideoBaseTexture.js +++ b/src/core/textures/VideoBaseTexture.js @@ -12,15 +12,18 @@ * @param source {HTMLVideoElement} * @param [scaleMode] {number} See {@link scaleModes} for possible values */ -function VideoBaseTexture(source, scaleMode) { - if (!source){ +function VideoBaseTexture(source, scaleMode) +{ + if (!source) + { throw new Error('No video source element specified.'); } // hook in here to check if video is already available. // BaseTexture looks for a source.complete boolean, plus width & height. - if ((source.readyState === source.HAVE_ENOUGH_DATA || source.readyState === source.HAVE_FUTURE_DATA) && source.width && source.height) { + if ((source.readyState === source.HAVE_ENOUGH_DATA || source.readyState === source.HAVE_FUTURE_DATA) && source.width && source.height) + { source.complete = true; } @@ -31,7 +34,8 @@ this._boundOnUpdate = this._onUpdate.bind(this); this._boundOnCanPlay = this._onCanPlay.bind(this); - if (!source.complete) { + if (!source.complete) + { source.addEventListener('canplay', this._boundOnCanPlay); source.addEventListener('canplaythrough', this._boundOnCanPlay); @@ -47,28 +51,35 @@ VideoBaseTexture.prototype.constructor = VideoBaseTexture; module.exports = VideoBaseTexture; -VideoBaseTexture.prototype._onUpdate = function () { - if (this.autoUpdate) { +VideoBaseTexture.prototype._onUpdate = function () +{ + if (this.autoUpdate) + { window.requestAnimationFrame(this._boundOnUpdate); this.needsUpdate = true; } }; -VideoBaseTexture.prototype._onPlayStart = function () { - if (!this.autoUpdate) { +VideoBaseTexture.prototype._onPlayStart = function () +{ + if (!this.autoUpdate) + { window.requestAnimationFrame(this._boundOnUpdate); this.autoUpdate = true; } }; -VideoBaseTexture.prototype._onPlayStop = function () { +VideoBaseTexture.prototype._onPlayStop = function () +{ this.autoUpdate = false; }; -VideoBaseTexture.prototype._onCanPlay = function () { +VideoBaseTexture.prototype._onCanPlay = function () +{ this.hasLoaded = true; - if (this.source) { + if (this.source) + { this.source.removeEventListener('canplay', this._boundOnCanPlay); this.source.removeEventListener('canplaythrough', this._boundOnCanPlay); @@ -78,15 +89,18 @@ this.source.play(); // prevent multiple loaded dispatches.. - if(!this.__loaded){ + if(!this.__loaded) + { this.__loaded = true; this.emit('loaded', this); } } }; -VideoBaseTexture.prototype.destroy = function () { - if (this.source && this.source._pixiId) { +VideoBaseTexture.prototype.destroy = function () +{ + if (this.source && this.source._pixiId) + { utils.BaseTextureCache[ this.source._pixiId ] = null; delete utils.BaseTextureCache[ this.source._pixiId ]; @@ -105,14 +119,17 @@ * @param scaleMode {number} See {@link scaleModes} for possible values * @return {VideoBaseTexture} */ -VideoBaseTexture.fromVideo = function (video, scaleMode) { - if (!video._pixiId) { +VideoBaseTexture.fromVideo = function (video, scaleMode) +{ + if (!video._pixiId) + { video._pixiId = 'video_' + utils.uuid(); } var baseTexture = utils.BaseTextureCache[video._pixiId]; - if (!baseTexture) { + if (!baseTexture) + { baseTexture = new VideoBaseTexture(video, scaleMode); utils.BaseTextureCache[ video._pixiId ] = baseTexture; } @@ -147,17 +164,21 @@ * @param scaleMode {number} See {@link scaleModes} for possible values * @return {VideoBaseTexture} */ -VideoBaseTexture.fromUrl = function (videoSrc, scaleMode) { +VideoBaseTexture.fromUrl = function (videoSrc, scaleMode) +{ var video = document.createElement('video'); // array of objects or strings - if (Array.isArray(videoSrc)) { - for (var i = 0; i < videoSrc.length; ++i) { + if (Array.isArray(videoSrc)) + { + for (var i = 0; i < videoSrc.length; ++i) + { video.appendChild(createSource(videoSrc.src || videoSrc, videoSrc.mime)); } } // single object or string - else { + else + { video.appendChild(createSource(videoSrc.src || videoSrc, videoSrc.mime)); } @@ -169,8 +190,10 @@ VideoBaseTexture.fromUrls = VideoBaseTexture.fromUrl; -function createSource(path, type) { - if (!type) { +function createSource(path, type) +{ + if (!type) + { type = 'video/' + path.substr(path.lastIndexOf('.') + 1); } diff --git a/src/core/utils/EventData.js b/src/core/utils/EventData.js index 5d55a22..8cdf701 100644 --- a/src/core/utils/EventData.js +++ b/src/core/utils/EventData.js @@ -7,7 +7,8 @@ * @param name {string} The string name of the event that was triggered * @param data {object} Arbitrary event data to pass along */ -function EventData(target, name, data) { +function EventData(target, name, data) +{ // for duck typing in the ".on()" function this.__isEventObject = true; @@ -71,7 +72,8 @@ * Stops the propagation of events up the scene graph (prevents bubbling). * */ -EventData.prototype.stopPropagation = function stopPropagation() { +EventData.prototype.stopPropagation = function stopPropagation() +{ this.stopped = true; }; @@ -79,6 +81,7 @@ * Stops the propagation of events to sibling listeners (no longer calls any listeners). * */ -EventData.prototype.stopImmediatePropagation = function stopImmediatePropagation() { +EventData.prototype.stopImmediatePropagation = function stopImmediatePropagation() +{ this.stoppedImmediate = true; }; diff --git a/src/core/utils/EventTarget.js b/src/core/utils/EventTarget.js index 7ae8820..671a151 100644 --- a/src/core/utils/EventTarget.js +++ b/src/core/utils/EventTarget.js @@ -13,14 +13,16 @@ * var em = new MyEmitter(); * em.emit('eventName', 'some data', 'some more data', {}, null, ...); */ -function eventTarget(obj) { +function eventTarget(obj) +{ /** * Return a list of assigned event listeners. * * @param eventName {string} The events that should be listed. * @return {Array} An array of listener functions */ - obj.listeners = function listeners(eventName) { + obj.listeners = function listeners(eventName) + { this._listeners = this._listeners || {}; return this._listeners[eventName] ? this._listeners[eventName].slice() : []; @@ -33,22 +35,26 @@ * @param eventName {string} The name of the event. * @return {boolean} Indication if we've emitted an event. */ - obj.emit = obj.dispatchEvent = function emit(eventName, data) { + obj.emit = obj.dispatchEvent = function emit(eventName, data) + { this._listeners = this._listeners || {}; // fast return when there are no listeners - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return; } //backwards compat with old method ".emit({ type: 'something' })" - if (typeof eventName === 'object') { + if (typeof eventName === 'object') + { data = eventName; eventName = eventName.type; } //ensure we are using a real pixi event - if (!data || data.__isEventObject !== true) { + if (!data || data.__isEventObject !== true) + { data = new EventData(this, eventName, data); } @@ -58,23 +64,27 @@ fn = listeners[0], i; - for (i = 0; i < length; fn = listeners[++i]) { + for (i = 0; i < length; fn = listeners[++i]) + { //call the event listener fn.call(this, data); //if "stopImmediatePropagation" is called, stop calling sibling events - if (data.stoppedImmediate) { + if (data.stoppedImmediate) + { return this; } } //if "stopPropagation" is called then don't bubble the event - if (data.stopped) { + if (data.stopped) + { return this; } //bubble this event up the scene graph - if (this.parent && this.parent.emit) { + if (this.parent && this.parent.emit) + { this.parent.emit.call(this.parent, eventName, data); } @@ -88,7 +98,8 @@ * @param eventName {string} Name of the event. * @param callback {Functon} fn Callback function. */ - obj.on = obj.addEventListener = function on(eventName, fn) { + obj.on = obj.addEventListener = function on(eventName, fn) + { this._listeners = this._listeners || {}; (this._listeners[eventName] = this._listeners[eventName] || []) @@ -103,11 +114,13 @@ * @param eventName {string} Name of the event. * @param callback {Function} Callback function. */ - obj.once = function once(eventName, fn) { + obj.once = function once(eventName, fn) + { this._listeners = this._listeners || {}; var self = this; - function onceHandlerWrapper() { + function onceHandlerWrapper() + { fn.apply(self.off(eventName, onceHandlerWrapper), arguments); } onceHandlerWrapper._originalHandler = fn; @@ -122,23 +135,28 @@ * @param eventName {string} The event we want to remove. * @param callback {Function} The listener that we need to find. */ - obj.off = obj.removeEventListener = function off(eventName, fn) { + obj.off = obj.removeEventListener = function off(eventName, fn) + { this._listeners = this._listeners || {}; - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return this; } var list = this._listeners[eventName], i = fn ? list.length : 0; - while(i-- > 0) { - if (list[i] === fn || list[i]._originalHandler === fn) { + while(i-- > 0) + { + if (list[i] === fn || list[i]._originalHandler === fn) + { list.splice(i, 1); } } - if (list.length === 0) { + if (list.length === 0) + { delete this._listeners[eventName]; } @@ -150,10 +168,12 @@ * * @param eventName {string} The event you want to remove all listeners for. */ - obj.removeAllListeners = function removeAllListeners(eventName) { + obj.removeAllListeners = function removeAllListeners(eventName) + { this._listeners = this._listeners || {}; - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return this; } @@ -169,7 +189,8 @@ * * @param object {object} The obj to mix into */ - mixin: function mixin(obj) { + mixin: function mixin(obj) + { eventTarget(obj); } }; diff --git a/src/core/utils/PolyK.js b/src/core/utils/PolyK.js index 7325141..5e20c2b 100644 --- a/src/core/utils/PolyK.js +++ b/src/core/utils/PolyK.js @@ -47,7 +47,8 @@ * Triangulates shapes for webGL graphic fills. * */ -PolyK.Triangulate = function (p) { +PolyK.Triangulate = function (p) +{ var sign = true; var n = p.length >> 1; @@ -59,7 +60,8 @@ i = 0; var al = n; - while(al > 3) { + while(al > 3) + { var i0 = avl[(i+0)%al]; var i1 = avl[(i+1)%al]; var i2 = avl[(i+2)%al]; @@ -69,29 +71,35 @@ var cx = p[2*i2], cy = p[2*i2+1]; var earFound = false; - if (PolyK._convex(ax, ay, bx, by, cx, cy, sign)) { + if (PolyK._convex(ax, ay, bx, by, cx, cy, sign)) + { earFound = true; - for (var j = 0; j < al; j++) { + for (var j = 0; j < al; j++) + { var vi = avl[j]; if (vi === i0 || vi === i1 || vi === i2) continue; - if (PolyK._PointInTriangle(p[2*vi], p[2*vi+1], ax, ay, bx, by, cx, cy)) { + if (PolyK._PointInTriangle(p[2*vi], p[2*vi+1], ax, ay, bx, by, cx, cy)) + { earFound = false; break; } } } - if (earFound) { + if (earFound) + { tgs.push(i0, i1, i2); avl.splice((i+1)%al, 1); al--; i = 0; } - else if (i++ > 3*al) { + else if (i++ > 3*al) + { // need to flip flip reverse it! // reset! - if (sign) { + if (sign) + { tgs = []; avl = []; for (i = 0; i < n; i++) avl.push(i); @@ -101,7 +109,8 @@ sign = false; } - else { + else + { // window.console.log("PIXI Warning: shape too complex to fill"); return null; } @@ -126,7 +135,8 @@ * @private * @return {boolean} */ -PolyK._PointInTriangle = function (px, py, ax, ay, bx, by, cx, cy) { +PolyK._PointInTriangle = function (px, py, ax, ay, bx, by, cx, cy) +{ var v0x = cx-ax; var v0y = cy-ay; var v1x = bx-ax; @@ -154,6 +164,7 @@ * @private * @return {boolean} */ -PolyK._convex = function (ax, ay, bx, by, cx, cy, sign) { +PolyK._convex = function (ax, ay, bx, by, cx, cy, sign) +{ return ((ay-by)*(cx-bx) + (bx-ax)*(cy-by) >= 0) === sign; }; diff --git a/src/core/utils/index.js b/src/core/utils/index.js index ade9831..bfae7ae 100644 --- a/src/core/utils/index.js +++ b/src/core/utils/index.js @@ -16,7 +16,8 @@ * * @return {number} The next uuid to use. */ - uuid: function () { + uuid: function () + { return ++utils._uid; }, @@ -26,7 +27,8 @@ * @param hex {number} * @return {number[]} An array representing the [R, G, B] of the color. */ - hex2rgb: function (hex, out) { + hex2rgb: function (hex, out) + { out = out || []; out[0] = (hex >> 16 & 0xFF) / 255; @@ -42,7 +44,8 @@ * @param hex {number} * @return {string} The string color. */ - hex2string: function (hex) { + hex2string: function (hex) + { hex = hex.toString(16); hex = '000000'.substr(0, 6 - hex.length) + hex; @@ -55,7 +58,8 @@ * @param rgb {number[]} * @return {number} The color number */ - rgb2hex: function (rgb) { + rgb2hex: function (rgb) + { return ((rgb[0]*255 << 16) + (rgb[1]*255 << 8) + rgb[2]*255); }, @@ -64,8 +68,10 @@ * * @return {boolean} whether they are supported */ - canUseNewCanvasBlendModes: function () { - if (typeof document === 'undefined') { + canUseNewCanvasBlendModes: function () + { + if (typeof document === 'undefined') + { return false; } @@ -93,15 +99,19 @@ * @param number {number} * @return {number} the closest number that is a power of two */ - getNextPowerOfTwo: function (number) { + getNextPowerOfTwo: function (number) + { // see: http://en.wikipedia.org/wiki/Power_of_two#Fast_algorithm_to_check_if_a_positive_number_is_a_power_of_two - if (number > 0 && (number & (number - 1)) === 0) { + if (number > 0 && (number & (number - 1)) === 0) + { return number; } - else { + else + { var result = 1; - while (result < number) { + while (result < number) + { result <<= 1; } @@ -116,7 +126,8 @@ * @param height {number} * @return {boolean} */ - isPowerOfTwo: function (width, height) { + isPowerOfTwo: function (width, height) + { return (width > 0 && (width & (width - 1)) === 0 && height > 0 && (height & (height - 1)) === 0); }, @@ -130,12 +141,15 @@ * @constant * @static */ - sayHello: function (type) { - if (utils._saidHello) { + sayHello: function (type) + { + if (utils._saidHello) + { return; } - if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) { + if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) + { var args = [ '%c %c %c Pixi.js ' + CONST.VERSION + ' - ' + type + ' %c ' + ' %c ' + ' http://www.pixijs.com/ %c %c ♥%c♥%c♥ ', 'background: #ff66a5', @@ -151,7 +165,8 @@ console.log.apply(console, args); //jshint ignore:line } - else if (window.console) { + else if (window.console) + { console.log('Pixi.js ' + CONST.VERSION + ' - ' + type + ' - http://www.pixijs.com/'); //jshint ignore:line } @@ -166,15 +181,19 @@ * @class * @namespace PIXI */ - AjaxRequest: function () { + AjaxRequest: function () + { var activexmodes = ['Msxml2.XMLHTTP.6.0', 'Msxml2.XMLHTTP.3.0', 'Microsoft.XMLHTTP']; //activeX versions to check for in IE - if (window.ActiveXObject) { //Test for support for ActiveXObject in IE first (as XMLHttpRequest in IE7 is broken) - for (var i=0; i= this.textures.length) { + else if (round >= this.textures.length) + { this.gotoAndStop(this.textures.length - 1); - if (this.onComplete) { + if (this.onComplete) + { this.onComplete(); } } @@ -167,10 +182,12 @@ * @static * @param frames {string[]} the array of frames ids the movieclip will use as its texture frames */ -MovieClip.fromFrames = function (frames) { +MovieClip.fromFrames = function (frames) +{ var textures = []; - for (var i = 0; i < frames.length; ++i) { + for (var i = 0; i < frames.length; ++i) + { textures.push(new core.Texture.fromFrame(frames[i])); } @@ -183,10 +200,12 @@ * @static * @param images {string[]} the array of image urls the movieclip will use as its texture frames */ -MovieClip.fromImages = function (images) { +MovieClip.fromImages = function (images) +{ var textures = []; - for (var i = 0; i < images.length; ++i) { + for (var i = 0; i < images.length; ++i) + { textures.push(new core.Texture.fromImage(images[i])); } diff --git a/src/extras/Rope.js b/src/extras/Rope.js index c157ec4..9c87bc0 100644 --- a/src/extras/Rope.js +++ b/src/extras/Rope.js @@ -9,7 +9,8 @@ * @param {Array} points - An array of {Point}. * */ -function Rope(texture, points) { +function Rope(texture, points) +{ Strip.call(this, texture); this.points = points; @@ -31,10 +32,12 @@ * Refreshes * */ -Rope.prototype.refresh = function () { +Rope.prototype.refresh = function () +{ var points = this.points; - if (points.length < 1) { + if (points.length < 1) + { return; } @@ -59,20 +62,23 @@ var total = points.length, point, index, amount; - for (var i = 1; i < total; i++) { + for (var i = 1; i < total; i++) + { point = points[i]; index = i * 4; // time to do some smart drawing! amount = i / (total-1); - if (i%2) { + if (i%2) + { uvs[index] = amount; uvs[index+1] = 0; uvs[index+2] = amount; uvs[index+3] = 1; } - else { + else + { uvs[index] = amount; uvs[index+1] = 0; @@ -95,10 +101,12 @@ * * @private */ -Rope.prototype.updateTransform = function () { +Rope.prototype.updateTransform = function () +{ var points = this.points; - if (points.length < 1) { + if (points.length < 1) + { return; } @@ -113,14 +121,17 @@ var total = points.length, point, index, ratio, perpLength, num; - for (var i = 0; i < total; i++) { + for (var i = 0; i < total; i++) + { point = points[i]; index = i * 4; - if (i < points.length-1) { + if (i < points.length-1) + { nextPoint = points[i+1]; } - else { + else + { nextPoint = point; } @@ -129,7 +140,8 @@ ratio = (1 - (i / (total-1))) * 10; - if (ratio > 1) { + if (ratio > 1) + { ratio = 1; } @@ -157,7 +169,8 @@ * * @param texture {Texture} the texture that will be used */ -Rope.prototype.setTexture = function (texture) { +Rope.prototype.setTexture = function (texture) +{ // stop current texture this.texture = texture; //this.updateFrame = true; diff --git a/src/extras/Strip.js b/src/extras/Strip.js index c5e378f..57691b5 100644 --- a/src/extras/Strip.js +++ b/src/extras/Strip.js @@ -10,7 +10,8 @@ * @param height {number} the height * */ -function Strip(texture) { +function Strip(texture) +{ core.DisplayObjectContainer.call(this); /** @@ -70,9 +71,11 @@ * * @param renderer {WebGLRenderer} */ -Strip.prototype.renderWebGL = function (renderer) { +Strip.prototype.renderWebGL = function (renderer) +{ // if the sprite is not visible or the alpha is 0 then no need to render this element - if (!this.visible || this.alpha <= 0) { + if (!this.visible || this.alpha <= 0) + { return; } @@ -81,7 +84,8 @@ renderer.spriteBatch.stop(); // init! init! - if (!this._vertexBuffer) { + if (!this._vertexBuffer) + { this._initWebGL(renderer); } @@ -96,7 +100,8 @@ //TODO check culling }; -Strip.prototype._initWebGL = function (renderer) { +Strip.prototype._initWebGL = function (renderer) +{ // build the strip! var gl = renderer.gl; @@ -118,7 +123,8 @@ gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this.indices, gl.STATIC_DRAW); }; -Strip.prototype._renderStrip = function (renderer) { +Strip.prototype._renderStrip = function (renderer) +{ var gl = renderer.gl; var projection = renderer.projection, offset = renderer.offset, @@ -137,7 +143,8 @@ gl.uniform2f(shader.offsetVector, -offset.x, -offset.y); gl.uniform1f(shader.alpha, this.worldAlpha); - if (!this.dirty) { + if (!this.dirty) + { gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexBuffer); gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); @@ -150,10 +157,12 @@ gl.activeTexture(gl.TEXTURE0); // check if a texture is dirty.. - if (this.texture.baseTexture._dirty[gl.id]) { + if (this.texture.baseTexture._dirty[gl.id]) + { renderer.updateTexture(this.texture.baseTexture); } - else { + else + { // bind the current texture gl.bindTexture(gl.TEXTURE_2D, this.texture.baseTexture._glTextures[gl.id]); } @@ -163,7 +172,8 @@ } - else { + else + { this.dirty = false; gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexBuffer); @@ -178,10 +188,12 @@ gl.activeTexture(gl.TEXTURE0); // check if a texture is dirty.. - if (this.texture.baseTexture._dirty[gl.id]) { + if (this.texture.baseTexture._dirty[gl.id]) + { renderer.updateTexture(this.texture.baseTexture); } - else { + else + { gl.bindTexture(gl.TEXTURE_2D, this.texture.baseTexture._glTextures[gl.id]); } @@ -203,27 +215,33 @@ * * @param renderer {CanvasRenderer} */ -Strip.prototype.renderCanvas = function (renderer) { +Strip.prototype.renderCanvas = function (renderer) +{ var context = renderer.context; var transform = this.worldTransform; - if (renderer.roundPixels) { + if (renderer.roundPixels) + { context.setTransform(transform.a, transform.b, transform.c, transform.d, transform.tx | 0, transform.ty | 0); } - else { + else + { context.setTransform(transform.a, transform.b, transform.c, transform.d, transform.tx, transform.ty); } - if (this.drawMode === Strip.DrawModes.TRIANGLE_STRIP) { + if (this.drawMode === Strip.DrawModes.TRIANGLE_STRIP) + { this._renderCanvasTriangleStrip(context); } - else { + else + { this._renderCanvasTriangles(context); } }; -Strip.prototype._renderCanvasTriangleStrip = function (context) { +Strip.prototype._renderCanvasTriangleStrip = function (context) +{ // draw triangles!! var vertices = this.vertices; var uvs = this.uvs; @@ -231,14 +249,16 @@ var length = vertices.length / 2; // this.count++; - for (var i = 0; i < length - 2; i++) { + for (var i = 0; i < length - 2; i++) + { // draw some triangles! var index = i * 2; this._renderCanvasDrawTriangle(context, vertices, uvs, index, (index + 2), (index + 4)); } }; -Strip.prototype._renderCanvasTriangles = function (context) { +Strip.prototype._renderCanvasTriangles = function (context) +{ // draw triangles!! var vertices = this.vertices; var uvs = this.uvs; @@ -247,14 +267,16 @@ var length = indices.length; // this.count++; - for (var i = 0; i < length; i += 3) { + for (var i = 0; i < length; i += 3) + { // draw some triangles! var index0 = indices[i] * 2, index1 = indices[i + 1] * 2, index2 = indices[i + 2] * 2; this._renderCanvasDrawTriangle(context, vertices, uvs, index0, index1, index2); } }; -Strip.prototype._renderCanvasDrawTriangle = function (context, vertices, uvs, index0, index1, index2) { +Strip.prototype._renderCanvasDrawTriangle = function (context, vertices, uvs, index0, index1, index2) +{ var textureSource = this.texture.baseTexture.source; var textureWidth = this.texture.width; var textureHeight = this.texture.height; @@ -265,7 +287,8 @@ var u0 = uvs[index0] * textureWidth, u1 = uvs[index1] * textureWidth, u2 = uvs[index2] * textureWidth; var v0 = uvs[index0 + 1] * textureHeight, v1 = uvs[index1 + 1] * textureHeight, v2 = uvs[index2 + 1] * textureHeight; - if (this.canvasPadding > 0) { + if (this.canvasPadding > 0) + { var paddingX = this.canvasPadding / this.worldTransform.a; var paddingY = this.canvasPadding / this.worldTransform.d; var centerX = (x0 + x1 + x2) / 3; @@ -332,7 +355,8 @@ * @param strip {Strip} The Strip to render * @private */ -Strip.prototype.renderStripFlat = function (strip) { +Strip.prototype.renderStripFlat = function (strip) +{ var context = this.context; var vertices = strip.vertices; @@ -340,7 +364,8 @@ // this.count++; context.beginPath(); - for (var i=1; i < length-2; i++) { + for (var i=1; i < length-2; i++) + { // draw some triangles! var index = i*2; @@ -358,7 +383,8 @@ }; /* -Strip.prototype.setTexture = function (texture) { +Strip.prototype.setTexture = function (texture) +{ //TODO SET THE TEXTURES //TODO VISIBILITY @@ -377,7 +403,8 @@ * @private */ -Strip.prototype.onTextureUpdate = function () { +Strip.prototype.onTextureUpdate = function () +{ this.updateFrame = true; }; @@ -387,7 +414,8 @@ * @param matrix {Matrix} the transformation matrix of the sprite * @return {Rectangle} the framing rectangle */ -Strip.prototype.getBounds = function (matrix) { +Strip.prototype.getBounds = function (matrix) +{ var worldTransform = matrix || this.worldTransform; var a = worldTransform.a; @@ -404,7 +432,8 @@ var minY = Infinity; var vertices = this.vertices; - for (var i = 0, n = vertices.length; i < n; i += 2) { + for (var i = 0, n = vertices.length; i < n; i += 2) + { var rawX = vertices[i], rawY = vertices[i + 1]; var x = (a * rawX) + (c * rawY) + tx; var y = (d * rawY) + (b * rawX) + ty; @@ -416,7 +445,8 @@ maxY = y > maxY ? y : maxY; } - if (minX === -Infinity || maxY === Infinity) { + if (minX === -Infinity || maxY === Infinity) + { return core.math.Rectangle.EMPTY; } diff --git a/src/extras/TilingSprite.js b/src/extras/TilingSprite.js index 3ac22df..31da393 100644 --- a/src/extras/TilingSprite.js +++ b/src/extras/TilingSprite.js @@ -10,7 +10,8 @@ * @param width {number} the width of the tiling sprite * @param height {number} the height of the tiling sprite */ -function TilingSprite(texture, width, height) { +function TilingSprite(texture, width, height) +{ core.Sprite.call( this, texture); /** @@ -86,10 +87,12 @@ * @memberof TilingSprite# */ width: { - get: function () { + get: function () + { return this._width; }, - set: function (value) { + set: function (value) + { this._width = value; } }, @@ -101,20 +104,25 @@ * @memberof TilingSprite# */ height: { - get: function () { + get: function () + { return this._height; }, - set: function (value) { + set: function (value) + { this._height = value; } }, texture: { - get: function () { + get: function () + { return this._texture; }, - set: function (value) { - if (this._texture === value) { + set: function (value) + { + if (this._texture === value) + { return; } @@ -130,51 +138,61 @@ * * @param renderer {WebGLRenderer} */ -TilingSprite.prototype.renderWebGL = function (renderer) { - if (!this.visible || this.alpha <= 0) { +TilingSprite.prototype.renderWebGL = function (renderer) +{ + if (!this.visible || this.alpha <= 0) + { return; } var i, j; - if (this._mask) { + if (this._mask) + { renderer.spriteBatch.stop(); renderer.maskManager.pushMask(this.mask, renderer); renderer.spriteBatch.start(); } - if (this._filters) { + if (this._filters) + { renderer.spriteBatch.flush(); renderer.filterManager.pushFilter(this._filterBlock); } - if (!this.tilingTexture || this.refreshTexture) { + if (!this.tilingTexture || this.refreshTexture) + { this.generateTilingTexture(true); - if (this.tilingTexture && this.tilingTexture.needsUpdate) { + if (this.tilingTexture && this.tilingTexture.needsUpdate) + { //TODO - tweaking renderer.updateTexture(this.tilingTexture.baseTexture); this.tilingTexture.needsUpdate = false; // this.tilingTexture._uvs = null; } } - else { + else + { renderer.spriteBatch.renderTilingSprite(this); } // simple render children! - for (i=0,j=this.children.length; i= 0 && index <= this.children.length) { - if (child.parent) { + if (index >= 0 && index <= this.children.length) + { + if (child.parent) + { child.parent.removeChild(child); } @@ -154,7 +173,8 @@ return child; } - else { + else + { throw new Error(child + 'addChildAt: The index '+ index +' supplied is out of bounds ' + this.children.length); } }; @@ -165,15 +185,18 @@ * @param child {DisplayObject} * @param child2 {DisplayObject} */ -DisplayObjectContainer.prototype.swapChildren = function (child, child2) { - if (child === child2) { +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) { + if (index1 < 0 || index2 < 0) + { throw new Error('swapChildren: Both the supplied DisplayObjects must be a child of the caller.'); } @@ -187,10 +210,12 @@ * @param child {DisplayObject} The DisplayObject instance to identify * @return {Number} The index position of the child display object to identify */ -DisplayObjectContainer.prototype.getChildIndex = function (child) { +DisplayObjectContainer.prototype.getChildIndex = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { throw new Error('The supplied DisplayObject must be a child of the caller'); } @@ -203,8 +228,10 @@ * @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 */ -DisplayObjectContainer.prototype.setChildIndex = function (child, index) { - if (index < 0 || index >= this.children.length) { +DisplayObjectContainer.prototype.setChildIndex = function (child, index) +{ + if (index < 0 || index >= this.children.length) + { throw new Error('The supplied index is out of bounds'); } @@ -220,8 +247,10 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child at the given index, if any. */ -DisplayObjectContainer.prototype.getChildAt = function (index) { - if (index < 0 || index >= this.children.length) { +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'); } @@ -234,10 +263,12 @@ * @param child {DisplayObject} The DisplayObject to remove * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChild = function (child) { +DisplayObjectContainer.prototype.removeChild = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { return; } @@ -250,7 +281,8 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChildAt = function (index) { +DisplayObjectContainer.prototype.removeChildAt = function (index) +{ var child = this.getChildAt(index); child.parent = null; @@ -265,24 +297,29 @@ * @param beginIndex {Number} The beginning position. Default value is 0. * @param endIndex {Number} The ending position. Default value is size of the container. */ -DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) { +DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) +{ var begin = beginIndex || 0; var end = typeof endIndex === 'number' ? endIndex : this.children.length; var range = end - begin; - if (range > 0 && range <= end) { + if (range > 0 && range <= end) + { var removed = this.children.splice(begin, range); - for (var i = 0; i < removed.length; ++i) { + for (var i = 0; i < removed.length; ++i) + { removed[i].parent = null; } return removed; } - else if (range === 0 && this.children.length === 0) { + else if (range === 0 && this.children.length === 0) + { return []; } - else { + else + { throw new RangeError('removeChildren: numeric values are outside the acceptable range.'); } }; @@ -291,7 +328,8 @@ * Generates and updates the cached sprite for this object. * */ -DisplayObjectContainer.prototype.updateCachedSprite = function () { +DisplayObjectContainer.prototype.updateCachedSprite = function () +{ this._generateCachedSprite(); }; @@ -304,7 +342,8 @@ * @param renderer {CanvasRenderer|WebGLRenderer} The renderer used to generate the texture. * @return {Texture} a texture of the graphics object */ -DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) { +DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) +{ var bounds = this.getLocalBounds(); var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0, renderer, scaleMode, resolution); @@ -322,18 +361,22 @@ * * @private */ -DisplayObjectContainer.prototype.updateTransform = function () { - if (!this.visible) { +DisplayObjectContainer.prototype.updateTransform = function () +{ + if (!this.visible) + { return; } this.displayObjectUpdateTransform(); - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { return; } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } }; @@ -346,8 +389,10 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getBounds = function () { - if (this.children.length === 0) { +DisplayObjectContainer.prototype.getBounds = function () +{ + if (this.children.length === 0) + { return math.Rectangle.EMPTY; } @@ -365,10 +410,12 @@ var childVisible = false; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -386,7 +433,8 @@ maxY = maxY > childMaxY ? maxY : childMaxY; } - if (!childVisible) { + if (!childVisible) + { return math.Rectangle.EMPTY; } @@ -407,12 +455,14 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getLocalBounds = function () { +DisplayObjectContainer.prototype.getLocalBounds = function () +{ var matrixCache = this.worldTransform; this.worldTransform = math.Matrix.IDENTITY; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } @@ -428,13 +478,16 @@ * * @param renderer {WebGLRenderer} The renderer */ -DisplayObjectContainer.prototype.renderWebGL = function (renderer) { +DisplayObjectContainer.prototype.renderWebGL = function (renderer) +{ // if the object is not visible or the alpha is 0 then no need to render this element - if (!this.visible || this.alpha <= 0) { + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } @@ -442,14 +495,17 @@ var i, j; // do a quick check to see if this element has a mask or a filter. - if (this._mask || this._filters) { + if (this._mask || this._filters) + { // push filter first as we need to ensure the stencil buffer is correct for any masking - if (this._filters) { + if (this._filters) + { renderer.spriteBatch.flush(); renderer.filterManager.pushFilter(this._filterBlock); } - if (this._mask) { + if (this._mask) + { renderer.spriteBatch.stop(); renderer.maskManager.pushMask(this.mask, renderer); renderer.spriteBatch.start(); @@ -459,36 +515,42 @@ this._renderWebGL(renderer); // now loop through the children and make sure they get rendered - for (i = 0, j = this.children.length; i < j; i++) { + for (i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderWebGL(renderer); } // time to stop the sprite batch as either a mask element or a filter draw will happen next renderer.spriteBatch.stop(); - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(this._mask, renderer); } - if (this._filters) { + if (this._filters) + { renderer.filterManager.popFilter(); } renderer.spriteBatch.start(); } - else { + else + { this._renderWebGL(renderer); // simple render children! - for (i = 0, j = this.children.length; i < j; ++i) { + for (i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderWebGL(renderer); } } }; -DisplayObjectContainer.prototype._renderWebGL = function (renderer) { +DisplayObjectContainer.prototype._renderWebGL = function (renderer) +{ // this is where content itself gets renderd.. @@ -499,25 +561,31 @@ * * @param renderer {CanvasRenderer} The renderer */ -DisplayObjectContainer.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0) { +DisplayObjectContainer.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -528,13 +596,16 @@ * @param renderer {WebGLRenderer|CanvasRenderer} The renderer * @private */ -DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) { +DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) +{ this._cachedSprite.worldAlpha = this.worldAlpha; - if (renderer.gl) { + if (renderer.gl) + { this._cachedSprite.renderWebGL(renderer); } - else { + else + { this._cachedSprite.renderCanvas(renderer); } }; @@ -544,10 +615,12 @@ * * @private */ -DisplayObjectContainer.prototype._generateCachedSprite = function () { +DisplayObjectContainer.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { // TODO - RenderTexture now *requires* a renderer instance, so this is like broken // because `renderer` isn't actually in scope here :P var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0); @@ -555,7 +628,8 @@ this._cachedSprite = new Sprite(renderTexture); this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.texture.resize(bounds.width | 0, bounds.height | 0); } @@ -580,8 +654,10 @@ * * @private */ -DisplayObjectContainer.prototype._destroyCachedSprite = function () { - if (!this._cachedSprite) { +DisplayObjectContainer.prototype._destroyCachedSprite = function () +{ + if (!this._cachedSprite) + { return; } diff --git a/src/core/display/Sprite.js b/src/core/display/Sprite.js index 707da24..5862aef 100644 --- a/src/core/display/Sprite.js +++ b/src/core/display/Sprite.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param texture {Texture} The texture for this sprite */ -function Sprite(texture) { +function Sprite(texture) +{ DisplayObjectContainer.call(this); /** @@ -85,12 +86,14 @@ this.texture = texture || Texture.EMPTY; } -Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) { +Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) +{ DisplayObjectContainer.prototype.destroy.call(this); this.anchor = null; - if (destroyTexture) { + if (destroyTexture) + { this._texture.destroy(destroyBaseTexture); } @@ -111,10 +114,12 @@ * @memberof Sprite# */ width: { - get: function () { + get: function () + { return this.scale.x * this.texture.frame.width; }, - set: function (value) { + set: function (value) + { this.scale.x = value / this.texture.frame.width; this._width = value; } @@ -127,10 +132,12 @@ * @memberof Sprite# */ height: { - get: function () { + get: function () + { return this.scale.y * this.texture.frame.height; }, - set: function (value) { + set: function (value) + { this.scale.y = value / this.texture.frame.height; this._height = value; } @@ -143,23 +150,29 @@ * @memberof Sprite# */ texture: { - get: function () { + get: function () + { return this._texture; }, - set: function (value) { - if (this._texture === value) { + set: function (value) + { + if (this._texture === value) + { return; } this._texture = value; this.cachedTint = 0xFFFFFF; - if (value) { + if (value) + { // wait for the texture to load - if (value.baseTexture.hasLoaded) { + if (value.baseTexture.hasLoaded) + { this._onTextureUpdate(); } - else { + else + { value.once('update', this._onTextureUpdate.bind(this)); } } @@ -172,18 +185,22 @@ * * @private */ -Sprite.prototype._onTextureUpdate = function () { +Sprite.prototype._onTextureUpdate = function () +{ // so if _width is 0 then width was not set.. - if (this._width) { + if (this._width) + { this.scale.x = this._width / this.texture.frame.width; } - if (this._height) { + if (this._height) + { this.scale.y = this._height / this.texture.frame.height; } }; -Sprite.prototype._renderWebGL = function (renderer) { +Sprite.prototype._renderWebGL = function (renderer) +{ // this is where content gets renderd.. // watch this space for a little render state manager.. @@ -197,7 +214,8 @@ * @param matrix {Matrix} the transformation matrix of the sprite * @return {Rectangle} the framing rectangle */ -Sprite.prototype.getBounds = function (matrix) { +Sprite.prototype.getBounds = function (matrix) +{ var width = this.texture.frame.width; var height = this.texture.frame.height; @@ -224,11 +242,13 @@ if(b === 0 && c === 0) { // scale may be negative! - if (a < 0) { + if (a < 0) + { a *= -1; } - if (d < 0) { + if (d < 0) + { d *= -1; } @@ -293,28 +313,34 @@ * * @param renderer {CanvasRenderer} The renderer */ -Sprite.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) { +Sprite.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) + { return; } - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; renderer.context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } // Ignore null sources - if (this.texture.valid) { + if (this.texture.valid) + { var resolution = this.texture.baseTexture.resolution / renderer.resolution; renderer.context.globalAlpha = this.worldAlpha; // If smoothingEnabled is supported and we need to change the smoothing property for this texture - if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) { + if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) + { renderer.scaleMode = this.texture.baseTexture.scaleMode; renderer.context[renderer.smoothProperty] = (renderer.scaleMode === CONST.scaleModes.LINEAR); } @@ -324,7 +350,8 @@ var dy = (this.texture.trim ? this.texture.trim.y : 0) - (this.anchor.y * this.texture.trim.height); // Allow for pixel rounding - if (renderer.roundPixels) { + if (renderer.roundPixels) + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -337,7 +364,8 @@ dx = dx | 0; dy = dy | 0; } - else { + else + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -348,8 +376,10 @@ ); } - if (this.tint !== 0xFFFFFF) { - if (this.cachedTint !== this.tint) { + if (this.tint !== 0xFFFFFF) + { + if (this.cachedTint !== this.tint) + { this.cachedTint = this.tint; // TODO clean up caching - how to clean up the caches? @@ -368,7 +398,8 @@ this.texture.crop.height / resolution ); } - else { + else + { renderer.context.drawImage( this.texture.baseTexture.source, this.texture.crop.x, @@ -383,11 +414,13 @@ } } - for (var i = 0, j = this.children.length; i < j; i++) { + for (var i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -402,10 +435,12 @@ * @param frameId {String} The frame Id of the texture in the cache * @return {Sprite} A new Sprite using a texture from the texture cache matching the frameId */ -Sprite.fromFrame = function (frameId) { +Sprite.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache' + this); } @@ -420,6 +455,7 @@ * @param imageId {String} The image url of the texture * @return {Sprite} A new Sprite using a texture from the texture cache matching the image id */ -Sprite.fromImage = function (imageId, crossorigin, scaleMode) { +Sprite.fromImage = function (imageId, crossorigin, scaleMode) +{ return new Sprite(Texture.fromImage(imageId, crossorigin, scaleMode)); }; diff --git a/src/core/display/SpriteBatch.js b/src/core/display/SpriteBatch.js index 3187777..c196fef 100644 --- a/src/core/display/SpriteBatch.js +++ b/src/core/display/SpriteBatch.js @@ -12,7 +12,8 @@ * ```js * var container = new SpriteBatch(); * - * for(var i = 0; i < 100; ++i) { + * for(var i = 0; i < 100; ++i) + * { * var sprite = new PIXI.Sprite.fromImage("myImage.png"); * container.addChild(sprite); * } @@ -25,7 +26,8 @@ */ //TODO RENAME to PARTICLE CONTAINER? -function SpriteBatch() { +function SpriteBatch() +{ DisplayObjectContainer.call(this); } @@ -38,7 +40,8 @@ * * @private */ -SpriteBatch.prototype.updateTransform = function () { +SpriteBatch.prototype.updateTransform = function () +{ // TODO don't need to! this.displayObjectUpdateTransform(); // PIXI.DisplayObjectContainer.prototype.updateTransform.call( this ); @@ -50,8 +53,10 @@ * @param renderer {WebGLRenderer} The webgl renderer * @private */ -SpriteBatch.prototype.renderWebGL = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderWebGL = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -71,8 +76,10 @@ * @param renderer {CanvasRenderer} The canvas renderer * @private */ -SpriteBatch.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -84,10 +91,12 @@ this.displayObjectUpdateTransform(); - for (var i = 0; i < this.children.length; ++i) { + for (var i = 0; i < this.children.length; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -95,9 +104,11 @@ context.globalAlpha = this.worldAlpha * child.alpha; - if (child.rotation % (Math.PI * 2) === 0) { + if (child.rotation % (Math.PI * 2) === 0) + { // this is the fastest way to optimise! - if rotation is 0 then we can avoid any kind of setTransform call - if (isRotated) { + if (isRotated) + { context.setTransform( transform.a, transform.b, @@ -122,8 +133,10 @@ frame.height * child.scale.y ); } - else { - if (!isRotated) { + else + { + if (!isRotated) + { isRotated = true; } @@ -131,7 +144,8 @@ var childTransform = child.worldTransform; - if (renderer.roundPixels) { + if (renderer.roundPixels) + { context.setTransform( childTransform.a, childTransform.b, @@ -141,7 +155,8 @@ childTransform.ty | 0 ); } - else { + else + { context.setTransform( childTransform.a, childTransform.b, diff --git a/src/core/index.js b/src/core/index.js index 3954b6f..eb4a82b 100644 --- a/src/core/index.js +++ b/src/core/index.js @@ -58,11 +58,13 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRenderer: function (width, height, options, noWebGL) { + autoDetectRenderer: function (width, height, options, noWebGL) + { width = width || 800; height = height || 600; - if (!noWebGL && require('webgl-enabled')()) { + if (!noWebGL && require('webgl-enabled')()) + { return new core.WebGLRenderer(width, height, options); } @@ -87,7 +89,8 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRecommendedRenderer: function (width, height, options) { + autoDetectRecommendedRenderer: function (width, height, options) + { var isAndroid = /Android/i.test(navigator.userAgent); return core.autoDetectRenderer(width, height, options, isAndroid); diff --git a/src/core/math/Matrix.js b/src/core/math/Matrix.js index c2f87e2..2ff4848 100644 --- a/src/core/math/Matrix.js +++ b/src/core/math/Matrix.js @@ -10,7 +10,8 @@ * @class * @namespace PIXI */ -function Matrix() { +function Matrix() +{ /** * @member {number} * @default 1 @@ -63,7 +64,8 @@ * * @param array {number[]} The array that the matrix will be populated from. */ -Matrix.prototype.fromArray = function (array) { +Matrix.prototype.fromArray = function (array) +{ this.a = array[0]; this.b = array[1]; this.c = array[3]; @@ -78,14 +80,17 @@ * @param transpose {boolean} Whether we need to transpose the matrix or not * @return {number[]} the newly created array which contains the matrix */ -Matrix.prototype.toArray = function (transpose) { - if (!this.array) { +Matrix.prototype.toArray = function (transpose) +{ + if (!this.array) + { this.array = new Float32Array(9); } var array = this.array; - if (transpose) { + if (transpose) + { array[0] = this.a; array[1] = this.b; array[2] = 0; @@ -96,7 +101,8 @@ array[7] = this.ty; array[8] = 1; } - else { + else + { array[0] = this.a; array[1] = this.c; array[2] = this.tx; @@ -119,7 +125,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, transformed through this matrix */ -Matrix.prototype.apply = function (pos, newPos) { +Matrix.prototype.apply = function (pos, newPos) +{ newPos = newPos || new Point(); newPos.x = this.a * pos.x + this.c * pos.y + this.tx; @@ -136,7 +143,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, inverse-transformed through this matrix */ -Matrix.prototype.applyInverse = function (pos, newPos) { +Matrix.prototype.applyInverse = function (pos, newPos) +{ newPos = newPos || new Point(); var id = 1 / (this.a * this.d + this.c * -this.b); @@ -154,7 +162,8 @@ * @param {number} y * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.translate = function (x, y) { +Matrix.prototype.translate = function (x, y) +{ this.tx += x; this.ty += y; @@ -168,7 +177,8 @@ * @param {number} y The amount to scale vertically * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.scale = function (x, y) { +Matrix.prototype.scale = function (x, y) +{ this.a *= x; this.d *= y; this.c *= x; @@ -186,7 +196,8 @@ * @param {number} angle - The angle in radians. * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.rotate = function (angle) { +Matrix.prototype.rotate = function (angle) +{ var cos = Math.cos( angle ); var sin = Math.sin( angle ); @@ -210,7 +221,8 @@ * @param {Matrix} matrix * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.append = function (matrix) { +Matrix.prototype.append = function (matrix) +{ var a1 = this.a; var b1 = this.b; var c1 = this.c; @@ -232,7 +244,8 @@ * * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.identity = function () { +Matrix.prototype.identity = function () +{ this.a = 1; this.b = 0; this.c = 0; diff --git a/src/core/math/Point.js b/src/core/math/Point.js index 7565b2d..632f346 100644 --- a/src/core/math/Point.js +++ b/src/core/math/Point.js @@ -7,7 +7,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -function Point(x, y) { +function Point(x, y) +{ /** * @member {number} * @default 0 @@ -29,7 +30,8 @@ * * @return {Point} a copy of the point */ -Point.prototype.clone = function () { +Point.prototype.clone = function () +{ return new Point(this.x, this.y); }; @@ -40,7 +42,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -Point.prototype.set = function (x, y) { +Point.prototype.set = function (x, y) +{ this.x = x || 0; this.y = y || ( (y !== 0) ? this.x : 0 ) ; }; diff --git a/src/core/math/shapes/Circle.js b/src/core/math/shapes/Circle.js index 69cfdc9..4d76efc 100644 --- a/src/core/math/shapes/Circle.js +++ b/src/core/math/shapes/Circle.js @@ -10,7 +10,8 @@ * @param y {number} The Y coordinate of the center of this circle * @param radius {number} The radius of the circle */ -function Circle(x, y, radius) { +function Circle(x, y, radius) +{ /** * @member {number} * @default 0 @@ -46,7 +47,8 @@ * @method clone * @return {Circle} a copy of the Circle */ -Circle.prototype.clone = function () { +Circle.prototype.clone = function () +{ return new Circle(this.x, this.y, this.radius); }; @@ -58,8 +60,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Circle */ -Circle.prototype.contains = function (x, y) { - if (this.radius <= 0) { +Circle.prototype.contains = function (x, y) +{ + if (this.radius <= 0) + { return false; } @@ -79,6 +83,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Circle.prototype.getBounds = function () { +Circle.prototype.getBounds = function () +{ return new Rectangle(this.x - this.radius, this.y - this.radius, this.radius * 2, this.radius * 2); }; diff --git a/src/core/math/shapes/Ellipse.js b/src/core/math/shapes/Ellipse.js index 4f2d066..fefd01a 100644 --- a/src/core/math/shapes/Ellipse.js +++ b/src/core/math/shapes/Ellipse.js @@ -11,7 +11,8 @@ * @param width {number} The half width of this ellipse * @param height {number} The half height of this ellipse */ -function Ellipse(x, y, width, height) { +function Ellipse(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -53,7 +54,8 @@ * @method clone * @return {Ellipse} a copy of the ellipse */ -Ellipse.prototype.clone = function () { +Ellipse.prototype.clone = function () +{ return new Ellipse(this.x, this.y, this.width, this.height); }; @@ -65,8 +67,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coords are within this ellipse */ -Ellipse.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Ellipse.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } @@ -86,6 +90,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Ellipse.prototype.getBounds = function () { +Ellipse.prototype.getBounds = function () +{ return new Rectangle(this.x - this.width, this.y - this.height, this.width, this.height); }; diff --git a/src/core/math/shapes/Polygon.js b/src/core/math/shapes/Polygon.js index ae89148..fea6d37 100644 --- a/src/core/math/shapes/Polygon.js +++ b/src/core/math/shapes/Polygon.js @@ -10,16 +10,20 @@ * arguments passed can be flat x,y values e.g. `new Polygon(x,y, x,y, x,y, ...)` where `x` and `y` are * Numbers. */ -function Polygon(points) { +function Polygon(points) +{ //if points isn't an array, use arguments as the array - if (!(points instanceof Array)) { + if (!(points instanceof Array)) + { points = Array.prototype.slice.call(arguments); } //if this is a flat array of numbers, convert it to points - if (points[0] instanceof Point) { + if (points[0] instanceof Point) + { var p = []; - for (var i = 0, il = points.length; i < il; i++) { + for (var i = 0, il = points.length; i < il; i++) + { p.push(points[i].x, points[i].y); } @@ -51,7 +55,8 @@ * * @return {Polygon} a copy of the polygon */ -Polygon.prototype.clone = function () { +Polygon.prototype.clone = function () +{ return new Polygon(this.points.slice()); }; @@ -62,19 +67,22 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this polygon */ -Polygon.prototype.contains = function (x, y) { +Polygon.prototype.contains = function (x, y) +{ var inside = false; // use some raycasting to test hits // https://github.com/substack/point-in-polygon/blob/master/index.js var length = this.points.length / 2; - for (var i = 0, j = length - 1; i < length; j = i++) { + for (var i = 0, j = length - 1; i < length; j = i++) + { var xi = this.points[i * 2], yi = this.points[i * 2 + 1], xj = this.points[j * 2], yj = this.points[j * 2 + 1], intersect = ((yi > y) !== (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi); - if (intersect) { + if (intersect) + { inside = !inside; } } diff --git a/src/core/math/shapes/Rectangle.js b/src/core/math/shapes/Rectangle.js index 16ac62a..4008b68 100644 --- a/src/core/math/shapes/Rectangle.js +++ b/src/core/math/shapes/Rectangle.js @@ -10,7 +10,8 @@ * @param width {number} The overall width of this rectangle * @param height {number} The overall height of this rectangle */ -function Rectangle(x, y, width, height) { +function Rectangle(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -60,7 +61,8 @@ * * @return {Rectangle} a copy of the rectangle */ -Rectangle.prototype.clone = function () { +Rectangle.prototype.clone = function () +{ return new Rectangle(this.x, this.y, this.width, this.height); }; @@ -71,13 +73,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rectangle */ -Rectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Rectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/math/shapes/RoundedRectangle.js b/src/core/math/shapes/RoundedRectangle.js index 27d286e..7bf6411 100644 --- a/src/core/math/shapes/RoundedRectangle.js +++ b/src/core/math/shapes/RoundedRectangle.js @@ -11,7 +11,8 @@ * @param height {number} The overall height of this rounded rectangle * @param radius {number} Controls the radius of the rounded corners */ -function RoundedRectangle(x, y, width, height, radius) { +function RoundedRectangle(x, y, width, height, radius) +{ /** * @member {number} * @default 0 @@ -58,7 +59,8 @@ * * @return {RoundedRectangle} a copy of the rounded rectangle */ -RoundedRectangle.prototype.clone = function () { +RoundedRectangle.prototype.clone = function () +{ return new RoundedRectangle(this.x, this.y, this.width, this.height, this.radius); }; @@ -69,13 +71,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rounded Rectangle */ -RoundedRectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +RoundedRectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/primitives/Graphics.js b/src/core/primitives/Graphics.js index 261c534..e902d2a 100644 --- a/src/core/primitives/Graphics.js +++ b/src/core/primitives/Graphics.js @@ -16,7 +16,8 @@ * @extends DisplayObjectContainer * @namespace PIXI */ -function Graphics() { +function Graphics() +{ DisplayObjectContainer.call(this); this.renderable = true; @@ -154,16 +155,20 @@ * @private */ cacheAsBitmap: { - get: function () { + get: function () + { return this._cacheAsBitmap; }, - set: function (value) { + set: function (value) + { this._cacheAsBitmap = value; - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._generateCachedSprite(); } - else { + else + { this.destroyCachedSprite(); this.dirty = true; } @@ -176,7 +181,8 @@ * * @return {Graphics} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ var clone = new Graphics(); clone.renderable = this.renderable; @@ -192,7 +198,8 @@ clone.cachedSpriteDirty = this.cachedSpriteDirty; // copy graphics data - for (var i = 0; i < this.graphicsData.length; ++i) { + for (var i = 0; i < this.graphicsData.length; ++i) + { clone.graphicsData.push(this.graphicsData.clone()); } @@ -211,17 +218,21 @@ * @param alpha {number} alpha of the line to draw, will update the objects stored style * @return {Graphics} */ -Graphics.prototype.lineStyle = function (lineWidth, color, alpha) { +Graphics.prototype.lineStyle = function (lineWidth, color, alpha) +{ this.lineWidth = lineWidth || 0; this.lineColor = color || 0; this.lineAlpha = (arguments.length < 3) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length) + { // halfway through a line? start a new one! this.drawShape( new math.Polygon( this.currentPath.shape.points.slice(-2) )); } - else { + else + { // otherwise its empty so lets just set the line properties this.currentPath.lineWidth = this.lineWidth; this.currentPath.lineColor = this.lineColor; @@ -239,7 +250,8 @@ * @param y {number} the Y coordinate to move to * @return {Graphics} */ -Graphics.prototype.moveTo = function (x, y) { +Graphics.prototype.moveTo = function (x, y) +{ this.drawShape(new math.Polygon([x,y])); return this; @@ -253,7 +265,8 @@ * @param y {number} the Y coordinate to draw to * @return {Graphics} */ -Graphics.prototype.lineTo = function (x, y) { +Graphics.prototype.lineTo = function (x, y) +{ this.currentPath.shape.points.push(x, y); this.dirty = true; @@ -270,13 +283,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -285,7 +302,8 @@ n = 20, points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { this.moveTo(0, 0); } @@ -293,7 +311,8 @@ var fromY = points[points.length-1]; var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; xa = fromX + ( (cpX - fromX) * j ); @@ -319,13 +338,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -342,7 +365,8 @@ var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; dt = (1 - j); @@ -373,13 +397,17 @@ * @param radius {number} The radius of the arc * @return {Graphics} */ -Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points.push(x1, y1); } } - else { + else + { this.moveTo(x1, y1); } @@ -392,12 +420,15 @@ b2 = x2 - x1, mm = Math.abs(a1 * b2 - b1 * a2); - if (mm < 1.0e-8 || radius === 0) { - if (points[points.length-2] !== x1 || points[points.length-1] !== y1) { + if (mm < 1.0e-8 || radius === 0) + { + if (points[points.length-2] !== x1 || points[points.length-1] !== y1) + { points.push(x1, y1); } } - else { + else + { var dd = a1 * a1 + b1 * b1, cc = a2 * a2 + b2 * b2, tt = a1 * a2 + b1 * b2, @@ -433,42 +464,51 @@ * @param anticlockwise {boolean} Optional. Specifies whether the drawing should be counterclockwise or clockwise. False is default, and indicates clockwise, while true indicates counter-clockwise. * @return {Graphics} */ -Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) { +Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) +{ var startX = cx + Math.cos(startAngle) * radius; var startY = cy + Math.sin(startAngle) * radius; var points; // TODO - This if-else makes no sense. It uses currentPath in the else where it doesn't exist... - if (this.currentPath) { + if (this.currentPath) + { points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { points.push(startX, startY); } - else if (points[points.length-2] !== startX || points[points.length-1] !== startY) { + else if (points[points.length-2] !== startX || points[points.length-1] !== startY) + { points.push(startX, startY); } } - else { + else + { this.moveTo(startX, startY); points = this.currentPath.shape.points; } - if (startAngle === endAngle) { + if (startAngle === endAngle) + { return this; } - if (!anticlockwise && endAngle <= startAngle) { + if (!anticlockwise && endAngle <= startAngle) + { endAngle += Math.PI * 2; } - else if (anticlockwise && startAngle <= endAngle) { + else if (anticlockwise && startAngle <= endAngle) + { startAngle += Math.PI * 2; } var sweep = anticlockwise ? (startAngle - endAngle) *-1 : (endAngle - startAngle); var segs = (Math.abs(sweep)/ (Math.PI * 2)) * 40; - if (sweep === 0) { + if (sweep === 0) + { return this; } @@ -482,7 +522,8 @@ var remainder = ( segMinus % 1 ) / segMinus; - for (var i = 0; i <= segMinus; ++i) { + for (var i = 0; i <= segMinus; ++i) + { var real = i + remainder * i; var angle = ((theta) + startAngle + (theta2 * real)); @@ -506,13 +547,16 @@ * @param alpha {number} the alpha of the fill * @return {Graphics} */ -Graphics.prototype.beginFill = function (color, alpha) { +Graphics.prototype.beginFill = function (color, alpha) +{ this.filling = true; this.fillColor = color || 0; this.fillAlpha = (alpha === undefined) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length <= 2) + { this.currentPath.fill = this.filling; this.currentPath.fillColor = this.fillColor; this.currentPath.fillAlpha = this.fillAlpha; @@ -526,7 +570,8 @@ * * @return {Graphics} */ -Graphics.prototype.endFill = function () { +Graphics.prototype.endFill = function () +{ this.filling = false; this.fillColor = null; this.fillAlpha = 1; @@ -542,7 +587,8 @@ * @param height {number} The height of the rectangle * @return {Graphics} */ -Graphics.prototype.drawRect = function ( x, y, width, height ) { +Graphics.prototype.drawRect = function ( x, y, width, height ) +{ this.drawShape(new math.Rectangle(x,y, width, height)); return this; @@ -556,7 +602,8 @@ * @param height {number} The height of the rectangle * @param radius {number} Radius of the rectangle corners */ -Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) { +Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) +{ this.drawShape(new math.RoundedRectangle(x, y, width, height, radius)); return this; @@ -570,7 +617,8 @@ * @param radius {number} The radius of the circle * @return {Graphics} */ -Graphics.prototype.drawCircle = function (x, y, radius) { +Graphics.prototype.drawCircle = function (x, y, radius) +{ this.drawShape(new math.Circle(x,y, radius)); return this; @@ -585,7 +633,8 @@ * @param height {number} The half height of the ellipse * @return {Graphics} */ -Graphics.prototype.drawEllipse = function (x, y, width, height) { +Graphics.prototype.drawEllipse = function (x, y, width, height) +{ this.drawShape(new math.Ellipse(x, y, width, height)); return this; @@ -597,8 +646,10 @@ * @param path {Array} The path data used to construct the polygon. * @return {Graphics} */ -Graphics.prototype.drawPolygon = function (path) { - if (!(path instanceof Array)) { +Graphics.prototype.drawPolygon = function (path) +{ + if (!(path instanceof Array)) + { path = Array.prototype.slice.call(arguments); } @@ -612,7 +663,8 @@ * * @return {Graphics} */ -Graphics.prototype.clear = function () { +Graphics.prototype.clear = function () +{ this.lineWidth = 0; this.filling = false; @@ -631,7 +683,8 @@ * @param scaleMode {number} Should be one of the scaleMode consts * @return {Texture} a texture of the graphics object */ -Graphics.prototype.generateTexture = function (resolution, scaleMode) { +Graphics.prototype.generateTexture = function (resolution, scaleMode) +{ resolution = resolution || 1; var bounds = this.getBounds(); @@ -655,17 +708,21 @@ * * @param renderer {WebGLRenderer} */ -Graphics.prototype._renderWebGL = function (renderer) { +Graphics.prototype._renderWebGL = function (renderer) +{ // if the sprite is not visible or the alpha is 0 then no need to render this element - if (this.isMask === true) { + if (this.isMask === true) + { return; } // this code may still be needed so leaving for now.. - // + // /* - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture on the gpu too! @@ -681,17 +738,24 @@ return; } - */ - - // check if the webgl graphic needs to be updated - if (this.glDirty) { - this.dirty = true; - this.glDirty = false; - } + else */ - renderer.setObjectRendererer(renderer.graphicsRenderer); - renderer.graphicsRenderer.render(this); + renderer.spriteBatch.stop(); + renderer.blendModeManager.setBlendMode(this.blendMode); + // check blend mode + renderer.blendModeManager.setBlendMode( this.blendMode ); + + // check if the webgl graphic needs to be updated + if (this.glDirty) + { + this.dirty = true; + this.glDirty = false; + } + + WebGLGraphics.renderGraphics(this, renderer); + + renderer.spriteBatch.start(); }; /** @@ -700,14 +764,18 @@ * @param renderer {CanvasRenderer} * @private */ -Graphics.prototype.renderCanvas = function (renderer) { +Graphics.prototype.renderCanvas = function (renderer) +{ // 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.isMask === true) { + if (!this.visible || this.alpha <= 0 || this.isMask === true) + { return; } - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture @@ -723,16 +791,19 @@ return; } - else { + else + { var context = renderer.context; var transform = this.worldTransform; - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } @@ -748,11 +819,13 @@ CanvasGraphics.renderGraphics(this, context); - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } } @@ -763,13 +836,16 @@ * * @return {Rectangle} the rectangular bounding area */ -Graphics.prototype.getBounds = function (matrix) { +Graphics.prototype.getBounds = function (matrix) +{ // return an empty object if the item is a mask! - if (this.isMask) { + if (this.isMask) + { return math.Rectangle.EMPTY; } - if (this.dirty) { + if (this.dirty) + { this.updateLocalBounds(); this.glDirty = true; @@ -841,23 +917,27 @@ * Update the bounds of the object * */ -Graphics.prototype.updateLocalBounds = function () { +Graphics.prototype.updateLocalBounds = function () +{ var minX = Infinity; var maxX = -Infinity; var minY = Infinity; var maxY = -Infinity; - if (this.graphicsData.length) { + if (this.graphicsData.length) + { var shape, points, x, y, w, h; - for (var i = 0; i < this.graphicsData.length; i++) { + for (var i = 0; i < this.graphicsData.length; i++) + { var data = this.graphicsData[i]; var type = data.type; var lineWidth = data.lineWidth; shape = data.shape; - if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) { + if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) + { x = shape.x - lineWidth/2; y = shape.y - lineWidth/2; w = shape.width + lineWidth; @@ -869,7 +949,8 @@ minY = y < minY ? y : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.CIRC) { + else if (type === CONST.SHAPES.CIRC) + { x = shape.x; y = shape.y; w = shape.radius + lineWidth/2; @@ -881,7 +962,8 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.ELIP) { + else if (type === CONST.SHAPES.ELIP) + { x = shape.x; y = shape.y; w = shape.width + lineWidth/2; @@ -893,11 +975,13 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else { + else + { // POLY points = shape.points; - for (var j = 0; j < points.length; j += 2) { + for (var j = 0; j < points.length; j += 2) + { x = points[j]; y = points[j+1]; @@ -910,7 +994,8 @@ } } } - else { + else + { minX = 0; maxX = 0; minY = 0; @@ -931,10 +1016,12 @@ * * @private */ -Graphics.prototype._generateCachedSprite = function () { +Graphics.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { var canvasBuffer = new CanvasBuffer(bounds.width, bounds.height); var texture = Texture.fromCanvas(canvasBuffer.canvas); @@ -943,7 +1030,8 @@ this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.buffer.resize(bounds.width, bounds.height); } @@ -968,7 +1056,8 @@ * * @private */ -Graphics.prototype.updateCachedSpriteTexture = function () { +Graphics.prototype.updateCachedSpriteTexture = function () +{ var cachedSprite = this._cachedSprite; var texture = cachedSprite.texture; var canvas = cachedSprite.buffer.canvas; @@ -989,7 +1078,8 @@ * Destroys a previous cached sprite. * */ -Graphics.prototype.destroyCachedSprite = function () { +Graphics.prototype.destroyCachedSprite = function () +{ this._cachedSprite.texture.destroy(true); // let the gc collect the unused sprite @@ -1003,10 +1093,13 @@ * @param {Circle|Rectangle|Ellipse|Line|Polygon} shape The Shape object to draw. * @return {GraphicsData} The generated GraphicsData object. */ -Graphics.prototype.drawShape = function (shape) { - if (this.currentPath) { +Graphics.prototype.drawShape = function (shape) +{ + if (this.currentPath) + { // check current path! - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath.shape.points.length <= 2) + { this.graphicsData.pop(); } } @@ -1017,7 +1110,8 @@ this.graphicsData.push(data); - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { data.shape.closed = this.filling; this.currentPath = data; } diff --git a/src/core/primitives/GraphicsData.js b/src/core/primitives/GraphicsData.js index 99decbe..788f6f2 100644 --- a/src/core/primitives/GraphicsData.js +++ b/src/core/primitives/GraphicsData.js @@ -4,7 +4,8 @@ * @class * @namespace PIXI */ -function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) { +function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) +{ this.lineWidth = lineWidth; this.lineColor = lineColor; this.lineAlpha = lineAlpha; @@ -27,7 +28,8 @@ * * @return {GraphicsData} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ return new GraphicsData( this.lineWidth, this.lineColor, diff --git a/src/core/renderers/canvas/CanvasRenderer.js b/src/core/renderers/canvas/CanvasRenderer.js index 15a0978..7aebd44 100644 --- a/src/core/renderers/canvas/CanvasRenderer.js +++ b/src/core/renderers/canvas/CanvasRenderer.js @@ -17,17 +17,22 @@ * @param [options.resolution=1] {number} the resolution of the renderer retina would be 2 * @param [options.clearBeforeRender=true] {boolean} This sets if the CanvasRenderer will clear the canvas or not before the new render pass. */ -function CanvasRenderer(width, height, options) { +function CanvasRenderer(width, height, options) +{ utils.sayHello('Canvas'); - if (options) { - for (var i in CONST.defaultRenderOptions) { - if (typeof options[i] === 'undefined') { + if (options) + { + for (var i in CONST.defaultRenderOptions) + { + if (typeof options[i] === 'undefined') + { options[i] = CONST.defaultRenderOptions[i]; } } } - else { + else + { options = CONST.defaultRenderOptions; } @@ -156,19 +161,24 @@ this.smoothProperty = null; - if (this.context.imageSmoothingEnabled) { + if (this.context.imageSmoothingEnabled) + { this.smoothProperty = 'imageSmoothingEnabled'; } - else if (this.context.webkitImageSmoothingEnabled) { + else if (this.context.webkitImageSmoothingEnabled) + { this.smoothProperty = 'webkitImageSmoothingEnabled'; } - else if (this.context.mozImageSmoothingEnabled) { + else if (this.context.mozImageSmoothingEnabled) + { this.smoothProperty = 'mozImageSmoothingEnabled'; } - else if (this.context.oImageSmoothingEnabled) { + else if (this.context.oImageSmoothingEnabled) + { this.smoothProperty = 'oImageSmoothingEnabled'; } - else if (this.context.msImageSmoothingEnabled) { + else if (this.context.msImageSmoothingEnabled) + { this.smoothProperty = 'msImageSmoothingEnabled'; } @@ -193,10 +203,12 @@ * @memberof CanvasRenderer# */ backgroundColor: { - get: function () { + get: function () + { return this._backgroundColor; }, - set: function (val) { + set: function (val) + { this._backgroundColor = val; this._backgroundColorString = utils.hex2string(val); } @@ -208,7 +220,8 @@ * * @param object {DisplayObject} the object to be rendered */ -CanvasRenderer.prototype.render = function (object) { +CanvasRenderer.prototype.render = function (object) +{ object.updateTransform(); this.context.setTransform(1,0,0,1,0,0); @@ -218,16 +231,20 @@ this.currentBlendMode = CONST.blendModes.NORMAL; this.context.globalCompositeOperation = this.blendModes[CONST.blendModes.NORMAL]; - if (navigator.isCocoonJS && this.view.screencanvas) { + if (navigator.isCocoonJS && this.view.screencanvas) + { this.context.fillStyle = 'black'; this.context.clear(); } - if (this.clearBeforeRender) { - if (this.transparent) { + if (this.clearBeforeRender) + { + if (this.transparent) + { this.context.clearRect(0, 0, this.width, this.height); } - else { + else + { this.context.fillStyle = this._backgroundColorString; this.context.fillRect(0, 0, this.width , this.height); } @@ -241,8 +258,10 @@ * * @param [removeView=false] {boolean} Removes the Canvas element from the DOM. */ -CanvasRenderer.prototype.destroy = function (removeView) { - if (removeView && this.view.parent) { +CanvasRenderer.prototype.destroy = function (removeView) +{ + if (removeView && this.view.parent) + { this.view.parent.removeChild(this.view); } @@ -257,14 +276,16 @@ * @param width {number} the new width of the canvas view * @param height {number} the new height of the canvas view */ -CanvasRenderer.prototype.resize = function (width, height) { +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) { + if (this.autoResize) + { this.view.style.width = this.width / this.resolution + 'px'; this.view.style.height = this.height / this.resolution + 'px'; } @@ -276,7 +297,8 @@ * @param displayObject {DisplayObject} The displayObject to render * @private */ -CanvasRenderer.prototype.renderDisplayObject = function (displayObject) { +CanvasRenderer.prototype.renderDisplayObject = function (displayObject) +{ displayObject.renderCanvas(this); }; @@ -285,11 +307,14 @@ * * @private */ -CanvasRenderer.prototype._mapBlendModes = function () { - if (!this.blendModes) { +CanvasRenderer.prototype._mapBlendModes = function () +{ + if (!this.blendModes) + { this.blendModes = {}; - if (utils.canUseNewCanvasBlendModes()) { + if (utils.canUseNewCanvasBlendModes()) + { this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? this.blendModes[CONST.blendModes.MULTIPLY] = 'multiply'; @@ -308,7 +333,8 @@ this.blendModes[CONST.blendModes.COLOR] = 'color'; this.blendModes[CONST.blendModes.LUMINOSITY] = 'luminosity'; } - else { + else + { // this means that the browser does not support the cool new blend modes in canvas 'cough' ie 'cough' this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? diff --git a/src/core/renderers/canvas/utils/CanvasBuffer.js b/src/core/renderers/canvas/utils/CanvasBuffer.js index ebe5d47..b183a66 100644 --- a/src/core/renderers/canvas/utils/CanvasBuffer.js +++ b/src/core/renderers/canvas/utils/CanvasBuffer.js @@ -6,7 +6,8 @@ * @param width {number} the width for the newly created canvas * @param height {number} the height for the newly created canvas */ -function CanvasBuffer(width, height) { +function CanvasBuffer(width, height) +{ /** * The Canvas object that belongs to this CanvasBuffer. * @@ -36,10 +37,12 @@ * @memberof CanvasBuffer# */ width: { - get: function () { + get: function () + { return this.canvas.width; }, - set: function (val) { + set: function (val) + { this.canvas.width = val; } }, @@ -50,10 +53,12 @@ * @memberof CanvasBuffer# */ height: { - get: function () { + get: function () + { return this.canvas.height; }, - set: function (val) { + set: function (val) + { this.canvas.height = val; } } @@ -64,7 +69,8 @@ * * @private */ -CanvasBuffer.prototype.clear = function () { +CanvasBuffer.prototype.clear = function () +{ this.context.setTransform(1, 0, 0, 1, 0, 0); this.context.clearRect(0,0, this.canvas.width, this.canvas.height); }; @@ -75,7 +81,8 @@ * @param width {number} the new width of the canvas * @param height {number} the new height of the canvas */ -CanvasBuffer.prototype.resize = function (width, height) { +CanvasBuffer.prototype.resize = function (width, height) +{ this.canvas.width = width; this.canvas.height = height; }; diff --git a/src/core/renderers/canvas/utils/CanvasGraphics.js b/src/core/renderers/canvas/utils/CanvasGraphics.js index c7eaa2a..3f2a91f 100644 --- a/src/core/renderers/canvas/utils/CanvasGraphics.js +++ b/src/core/renderers/canvas/utils/CanvasGraphics.js @@ -13,15 +13,18 @@ * @param graphics {Graphics} the actual graphics object to render * @param context {CanvasRenderingContext2D} the 2d drawing method of the canvas */ -CanvasGraphics.renderGraphics = function (graphics, context) { +CanvasGraphics.renderGraphics = function (graphics, context) +{ var worldAlpha = graphics.worldAlpha; - if (graphics.dirty) { + if (graphics.dirty) + { this.updateGraphicsTint(graphics); graphics.dirty = false; } - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; @@ -30,69 +33,82 @@ context.lineWidth = data.lineWidth; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { context.beginPath(); var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } - if (shape.closed) { + if (shape.closed) + { context.lineTo(points[0], points[1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fillRect(shape.x, shape.y, shape.width, shape.height); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.strokeRect(shape.x, shape.y, shape.width, shape.height); } } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.beginPath(); context.arc(shape.x, shape.y, shape.radius,0,2*Math.PI); context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas var w = shape.width * 2; @@ -119,18 +135,21 @@ context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; var width = shape.width; @@ -152,13 +171,15 @@ context.quadraticCurveTo(rx, ry, rx, ry + radius); context.closePath(); - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); @@ -174,45 +195,54 @@ * @param graphics {Graphics} the graphics which will be used as a mask * @param context {CanvasRenderingContext2D} the context 2d method of the canvas */ -CanvasGraphics.renderGraphicsMask = function (graphics, context) { +CanvasGraphics.renderGraphicsMask = function (graphics, context) +{ var len = graphics.graphicsData.length; - if (len === 0) { + if (len === 0) + { return; } context.beginPath(); - for (var i = 0; i < len; i++) { + for (var i = 0; i < len; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { context.rect(shape.x, shape.y, shape.width, shape.height); context.closePath(); } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.arc(shape.x, shape.y, shape.radius, 0, 2 * Math.PI); context.closePath(); } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas @@ -237,7 +267,8 @@ context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); context.closePath(); } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; @@ -262,8 +293,10 @@ } }; -CanvasGraphics.updateGraphicsTint = function (graphics) { - if (graphics.tint === 0xFFFFFF) { +CanvasGraphics.updateGraphicsTint = function (graphics) +{ + if (graphics.tint === 0xFFFFFF) + { return; } @@ -271,7 +304,8 @@ var tintG = (graphics.tint >> 8 & 0xFF) / 255; var tintB = (graphics.tint & 0xFF)/ 255; - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var fillColor = data.fillColor | 0; diff --git a/src/core/renderers/canvas/utils/CanvasMaskManager.js b/src/core/renderers/canvas/utils/CanvasMaskManager.js index e04a733..9827d36 100644 --- a/src/core/renderers/canvas/utils/CanvasMaskManager.js +++ b/src/core/renderers/canvas/utils/CanvasMaskManager.js @@ -6,7 +6,8 @@ * @class * @namespace PIXI */ -function CanvasMaskManager() {} +function CanvasMaskManager() +{} CanvasMaskManager.prototype.constructor = CanvasMaskManager; module.exports = CanvasMaskManager; @@ -17,7 +18,8 @@ * @param maskData {object} the maskData that will be pushed * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.pushMask = function (maskData, renderer) { +CanvasMaskManager.prototype.pushMask = function (maskData, renderer) +{ renderer.context.save(); var cacheAlpha = maskData.alpha; @@ -45,6 +47,7 @@ * * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.popMask = function (renderer) { +CanvasMaskManager.prototype.popMask = function (renderer) +{ renderer.context.restore(); }; diff --git a/src/core/renderers/canvas/utils/CanvasTinter.js b/src/core/renderers/canvas/utils/CanvasTinter.js index 17e0529..d2fb1bc 100644 --- a/src/core/renderers/canvas/utils/CanvasTinter.js +++ b/src/core/renderers/canvas/utils/CanvasTinter.js @@ -14,7 +14,8 @@ * @param color {number} the color to use to tint the sprite with * @return {HTMLCanvasElement} The tinted canvas */ -CanvasTinter.getTintedTexture = function (sprite, color) { +CanvasTinter.getTintedTexture = function (sprite, color) +{ var texture = sprite.texture; color = CanvasTinter.roundColor(color); @@ -23,7 +24,8 @@ texture.tintCache = texture.tintCache || {}; - if (texture.tintCache[stringColor]) { + if (texture.tintCache[stringColor]) + { return texture.tintCache[stringColor]; } @@ -33,14 +35,16 @@ //CanvasTinter.tintWithPerPixel(texture, stringColor, canvas); CanvasTinter.tintMethod(texture, color, canvas); - if (CanvasTinter.convertTintToImage) { + if (CanvasTinter.convertTintToImage) + { // is this better? var tintImage = new Image(); tintImage.src = canvas.toDataURL(); texture.tintCache[stringColor] = tintImage; } - else { + else + { texture.tintCache[stringColor] = canvas; // if we are not converting the texture to an image then we need to lose the reference to the canvas CanvasTinter.canvas = null; @@ -56,7 +60,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithMultiply = function (texture, color, canvas) { +CanvasTinter.tintWithMultiply = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -104,7 +109,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithOverlay = function (texture, color, canvas) { +CanvasTinter.tintWithOverlay = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -139,7 +145,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithPerPixel = function (texture, color, canvas) { +CanvasTinter.tintWithPerPixel = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -167,7 +174,8 @@ var pixels = pixelData.data; - for (var i = 0; i < pixels.length; i += 4) { + for (var i = 0; i < pixels.length; i += 4) + { pixels[i+0] *= r; pixels[i+1] *= g; pixels[i+2] *= b; @@ -181,7 +189,8 @@ * * @param color {number} the color to round, should be a hex color */ -CanvasTinter.roundColor = function (color) { +CanvasTinter.roundColor = function (color) +{ var step = CanvasTinter.cacheStepsPerColorChannel; var rgbValues = utils.hex2rgb(color); diff --git a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js index 9f2f89a..35edbaf 100644 --- a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js +++ b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLBlendModeManager(renderer) { +function WebGLBlendModeManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -23,8 +24,10 @@ * * @param blendMode {number} the blendMode, should be a Pixi const, such as BlendModes.ADD */ -WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) { - if (this.currentBlendMode === blendMode) { +WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) +{ + if (this.currentBlendMode === blendMode) + { return false; } diff --git a/src/core/renderers/webgl/managers/WebGLFilterManager.js b/src/core/renderers/webgl/managers/WebGLFilterManager.js index 1179258..2dac048 100644 --- a/src/core/renderers/webgl/managers/WebGLFilterManager.js +++ b/src/core/renderers/webgl/managers/WebGLFilterManager.js @@ -7,7 +7,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLFilterManager(renderer) { +function WebGLFilterManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -32,7 +33,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.texturePool.length = 0; self.initShaderBuffers(); }); @@ -46,7 +48,8 @@ * @param renderer {WebGLRenderer} * @param buffer {ArrayBuffer} */ -WebGLFilterManager.prototype.begin = function (buffer) { +WebGLFilterManager.prototype.begin = function (buffer) +{ this.defaultShader = this.renderer.shaderManager.defaultShader; this.width = this.renderer.projection.x * 2; @@ -60,7 +63,8 @@ * * @param filterBlock {object} the filter that will be pushed to the current filter stack */ -WebGLFilterManager.prototype.pushFilter = function (filterBlock) { +WebGLFilterManager.prototype.pushFilter = function (filterBlock) +{ var gl = this.renderer.gl; var projection = this.renderer.projection; @@ -78,10 +82,12 @@ this.offsetY += filterBlock._filterArea.y; var texture = this.texturePool.pop(); - if (!texture) { + if (!texture) + { texture = new FilterTexture(this.renderer.gl, this.width, this.height); } - else { + else + { texture.resize(this.width, this.height); } @@ -98,29 +104,35 @@ var localX = filterArea.x, localY = filterArea.y; - if (filterArea.x < 0) { + if (filterArea.x < 0) + { filterArea.width += filterArea.x; filterArea.x = 0; } - if (filterArea.y < 0) { + if (filterArea.y < 0) + { filterArea.height += filterArea.y; filterArea.y = 0; } - if (localX + filterArea.width > this.width) { + if (localX + filterArea.width > this.width) + { filterArea.width = this.width - localX; } - if (localY + filterArea.height > this.height) { + if (localY + filterArea.height > this.height) + { filterArea.height = this.height - localY; } - if (filterArea.width < 0) { + if (filterArea.width < 0) + { filterArea.width = 0; } - if (filterArea.height < 0) { + if (filterArea.height < 0) + { filterArea.height = 0; } @@ -154,7 +166,8 @@ * Removes the last filter from the filter stack and doesn't return it. * */ -WebGLFilterManager.prototype.popFilter = function () { +WebGLFilterManager.prototype.popFilter = function () +{ var gl = this.renderer.gl; var filterBlock = this.filterStack.pop(); @@ -163,7 +176,8 @@ var projection = this.renderer.projection; var offset = this.renderer.offset; - if (filterBlock.filterPasses.length > 1) { + if (filterBlock.filterPasses.length > 1) + { gl.viewport(0, 0, filterArea.width, filterArea.height); gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); @@ -193,7 +207,8 @@ var inputTexture = texture; var outputTexture = this.texturePool.pop(); - if (!outputTexture) { + if (!outputTexture) + { outputTexture = new FilterTexture(this.renderer.gl, this.width, this.height); } outputTexture.resize(this.width, this.height); @@ -204,7 +219,8 @@ gl.disable(gl.BLEND); - for (var i = 0; i < filterBlock.filterPasses.length-1; i++) { + for (var i = 0; i < filterBlock.filterPasses.length-1; i++) + { var filterPass = filterBlock.filterPasses[i]; gl.bindFramebuffer(gl.FRAMEBUFFER, outputTexture.frameBuffer ); @@ -243,10 +259,12 @@ var buffer = this.buffer; // time to render the filters texture to the previous scene - if (this.filterStack.length === 0) { + if (this.filterStack.length === 0) + { gl.colorMask(true, true, true, true);//this.transparent); } - else { + else + { var currentFilter = this.filterStack[this.filterStack.length-1]; filterArea = currentFilter._filterArea; @@ -332,13 +350,15 @@ * @param width {number} the horizontal range of the filter * @param height {number} the vertical range of the filter */ -WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) { +WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) +{ // use program var gl = this.renderer.gl; var shader = filter.shaders[gl.id]; - if (!shader) { + if (!shader) + { shader = new Shader(gl); shader.fragmentSrc = filter.fragmentSrc; @@ -356,7 +376,8 @@ gl.uniform2f(shader.projectionVector, width/2, -height/2); gl.uniform2f(shader.offsetVector, 0,0); - if (filter.uniforms.dimensions) { + 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]; @@ -386,7 +407,8 @@ * Initialises the shader buffers. * */ -WebGLFilterManager.prototype.initShaderBuffers = function () { +WebGLFilterManager.prototype.initShaderBuffers = function () +{ var gl = this.renderer.gl; // create some buffers @@ -432,7 +454,8 @@ * Destroys the filter and removes it from the filter stack. * */ -WebGLFilterManager.prototype.destroy = function () { +WebGLFilterManager.prototype.destroy = function () +{ var gl = this.renderer.gl; this.filterStack = null; @@ -441,7 +464,8 @@ this.offsetY = 0; // destroy textures - for (var i = 0; i < this.texturePool.length; i++) { + for (var i = 0; i < this.texturePool.length; i++) + { this.texturePool[i].destroy(); } diff --git a/src/core/renderers/webgl/managers/WebGLManager.js b/src/core/renderers/webgl/managers/WebGLManager.js index 9d47b5c..c30cd51 100644 --- a/src/core/renderers/webgl/managers/WebGLManager.js +++ b/src/core/renderers/webgl/managers/WebGLManager.js @@ -3,7 +3,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLManager(renderer) { +function WebGLManager(renderer) +{ /** * The renderer this manager works for. * @@ -15,6 +16,7 @@ WebGLManager.prototype.constructor = WebGLManager; module.exports = WebGLManager; -WebGLManager.prototype.destroy = function () { +WebGLManager.prototype.destroy = function () +{ this.renderer = null; }; diff --git a/src/core/renderers/webgl/managers/WebGLMaskManager.js b/src/core/renderers/webgl/managers/WebGLMaskManager.js index 2f90b64..e568812 100644 --- a/src/core/renderers/webgl/managers/WebGLMaskManager.js +++ b/src/core/renderers/webgl/managers/WebGLMaskManager.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLMaskManager(renderer) { +function WebGLMaskManager(renderer) +{ WebGLManager.call(this, renderer); } @@ -19,12 +20,15 @@ * * @param maskData {any[]} */ -WebGLMaskManager.prototype.pushMask = function (maskData) { - if (maskData.dirty) { +WebGLMaskManager.prototype.pushMask = function (maskData) +{ + if (maskData.dirty) + { WebGLGraphics.updateGraphics(maskData, this.renderer.gl); } - if (!maskData._webGL[this.renderer.gl.id].data.length) { + if (!maskData._webGL[this.renderer.gl.id].data.length) + { return; } @@ -36,6 +40,7 @@ * * @param maskData {any[]} */ -WebGLMaskManager.prototype.popMask = function (maskData) { +WebGLMaskManager.prototype.popMask = function (maskData) +{ this.renderer.stencilManager.popStencil(maskData, maskData._webGL[this.renderer.gl.id].data[0], this.renderer); }; diff --git a/src/core/renderers/webgl/managers/WebGLShaderManager.js b/src/core/renderers/webgl/managers/WebGLShaderManager.js index fef071c..90c6477 100644 --- a/src/core/renderers/webgl/managers/WebGLShaderManager.js +++ b/src/core/renderers/webgl/managers/WebGLShaderManager.js @@ -10,7 +10,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLShaderManager(renderer) { +function WebGLShaderManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -28,7 +29,8 @@ */ this.tempAttribState = []; - for (var i = 0; i < this.maxAttibs; i++) { + for (var i = 0; i < this.maxAttibs; i++) + { this.attribState[i] = false; } @@ -66,7 +68,8 @@ // listen for context and update necessary shaders var self = this; - this.renderer.on('context', function (event) { + this.renderer.on('context', function (event) + { var gl = event.data; // this shader is used for rendering primitives @@ -97,29 +100,36 @@ * * @param attribs {Array} attribs */ -WebGLShaderManager.prototype.setAttribs = function (attribs) { +WebGLShaderManager.prototype.setAttribs = function (attribs) +{ // reset temp state var i; - for (i = 0; i < this.tempAttribState.length; i++) { + for (i = 0; i < this.tempAttribState.length; i++) + { this.tempAttribState[i] = false; } // set the new attribs - for (var a in attribs) { + for (var a in attribs) + { this.tempAttribState[attribs[a]] = true; } var gl = this.renderer.gl; - for (i = 0; i < this.attribState.length; i++) { - if (this.attribState[i] !== this.tempAttribState[i]) { + for (i = 0; i < this.attribState.length; i++) + { + if (this.attribState[i] !== this.tempAttribState[i]) + { this.attribState[i] = this.tempAttribState[i]; - if (this.attribState[i]) { + if (this.attribState[i]) + { gl.enableVertexAttribArray(i); } - else { + else + { gl.disableVertexAttribArray(i); } } @@ -131,8 +141,10 @@ * * @param shader {Any} */ -WebGLShaderManager.prototype.setShader = function (shader) { - if (this._currentId === shader.uuid) { +WebGLShaderManager.prototype.setShader = function (shader) +{ + if (this._currentId === shader.uuid) + { return false; } @@ -150,7 +162,8 @@ * Destroys this object. * */ -WebGLShaderManager.prototype.destroy = function () { +WebGLShaderManager.prototype.destroy = function () +{ this.attribState = null; this.tempAttribState = null; diff --git a/src/core/renderers/webgl/managers/WebGLStencilManager.js b/src/core/renderers/webgl/managers/WebGLStencilManager.js index 9ec6398..4cb0134 100644 --- a/src/core/renderers/webgl/managers/WebGLStencilManager.js +++ b/src/core/renderers/webgl/managers/WebGLStencilManager.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLStencilManager(renderer) { +function WebGLStencilManager(renderer) +{ WebGLManager.call(this, renderer); this.stencilStack = []; @@ -24,12 +25,14 @@ * @param graphics {Graphics} * @param webGLData {any[]} */ -WebGLStencilManager.prototype.pushStencil = function (graphics, webGLData) { +WebGLStencilManager.prototype.pushStencil = function (graphics, webGLData) +{ var gl = this.renderer.gl; this.bindGraphics(graphics, webGLData, this.renderer); - if (this.stencilStack.length === 0) { + if (this.stencilStack.length === 0) + { gl.enable(gl.STENCIL_TEST); gl.clear(gl.STENCIL_BUFFER_BIT); this.reverse = true; @@ -47,14 +50,17 @@ // draw the triangle strip! - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } @@ -62,31 +68,38 @@ // draw a quad to increment.. gl.drawElements(gl.TRIANGLE_FAN, 4, gl.UNSIGNED_SHORT, ( webGLData.indices.length - 4 ) * 2 ); - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); } this.reverse = !this.reverse; } - else { - if (!this.reverse) { + else + { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } - else { + 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) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); } } @@ -103,7 +116,8 @@ * @param graphics {Graphics} * @param webGLData {Array} */ -WebGLStencilManager.prototype.bindGraphics = function (graphics, webGLData) { +WebGLStencilManager.prototype.bindGraphics = function (graphics, webGLData) +{ //if (this._currentGraphics === graphics)return; this._currentGraphics = graphics; @@ -114,7 +128,8 @@ offset = this.renderer.offset, shader;// = this.renderer.shaderManager.primitiveShader; - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { shader = this.renderer.shaderManager.complexPrimitiveShader; this.renderer.shaderManager.setShader(shader); @@ -141,7 +156,8 @@ // set the index buffer! gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, webGLData.indexBuffer); } - else { + else + { //this.renderer.shaderManager.activatePrimitiveShader(); shader = this.renderer.shaderManager.primitiveShader; this.renderer.shaderManager.setShader( shader ); @@ -154,7 +170,7 @@ gl.uniform2f(shader.uniforms.offsetVector._location, -offset.x, -offset.y); gl.uniform3fv(shader.uniforms.tint._location, utils.hex2rgb(graphics.tint)); - + gl.uniform1f(shader.uniforms.alpha._location, graphics.worldAlpha); @@ -172,19 +188,22 @@ * @param graphics {Graphics} * @param webGLData {Array} */ -WebGLStencilManager.prototype.popStencil = function (graphics, webGLData) { +WebGLStencilManager.prototype.popStencil = function (graphics, webGLData) +{ var gl = this.renderer.gl; this.stencilStack.pop(); this.count--; - if (this.stencilStack.length === 0) { + if (this.stencilStack.length === 0) + { // the stack is empty! gl.disable(gl.STENCIL_TEST); } - else { + else + { var level = this.count; @@ -192,14 +211,17 @@ gl.colorMask(false, false, false, false); - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { this.reverse = !this.reverse; - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } @@ -213,31 +235,38 @@ // draw the triangle strip! gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); - if (!this.reverse) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); } } - else { + else + { // console.log("<<>>") - if (!this.reverse) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } - else { + 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) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); } } @@ -253,7 +282,8 @@ * Destroys the mask stack. * */ -WebGLStencilManager.prototype.destroy = function () { +WebGLStencilManager.prototype.destroy = function () +{ this.renderer = null; this.stencilStack = null; }; diff --git a/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js b/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js index 913ba5e..1ea7d19 100644 --- a/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js +++ b/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function ComplexPrimitiveShader(gl) { +function ComplexPrimitiveShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -24,7 +25,8 @@ 'uniform float flipY;', 'varying vec4 vColor;', - 'void main(void) {', + '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);', @@ -37,7 +39,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = vColor;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/FastShader.js b/src/core/renderers/webgl/shaders/FastShader.js index bd2e29a..2e5e060 100644 --- a/src/core/renderers/webgl/shaders/FastShader.js +++ b/src/core/renderers/webgl/shaders/FastShader.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function FastShader(gl) { +function FastShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -28,7 +29,8 @@ 'const vec2 center = vec2(-1.0, 1.0);', - 'void main(void) {', + 'void main(void) + {', ' vec2 v;', ' vec2 sv = aVertexPosition * aScale;', ' v.x = (sv.x) * cos(aRotation) - (sv.y) * sin(aRotation);', @@ -49,7 +51,8 @@ 'uniform sampler2D uSampler;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/PrimitiveShader.js b/src/core/renderers/webgl/shaders/PrimitiveShader.js index 6f25409..a25f54f 100644 --- a/src/core/renderers/webgl/shaders/PrimitiveShader.js +++ b/src/core/renderers/webgl/shaders/PrimitiveShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function PrimitiveShader(gl) { +function PrimitiveShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -23,7 +24,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + '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);', @@ -36,7 +38,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = vColor;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/Shader.js b/src/core/renderers/webgl/shaders/Shader.js index f8964f5..fd75ef5 100644 --- a/src/core/renderers/webgl/shaders/Shader.js +++ b/src/core/renderers/webgl/shaders/Shader.js @@ -6,7 +6,8 @@ * @param [fragmentSrc] {string} The source of the fragment shader. * @param [vertexSrc] {string} The source of the vertex shader. */ -function Shader(gl, vertexSrc, fragmentSrc, customUniforms, customAttributes) { +function Shader(gl, vertexSrc, fragmentSrc, customUniforms, customAttributes) +{ /** * @member {number} * @readonly @@ -33,7 +34,8 @@ dimensions: { type: '4f', value: new Float32Array(4) } }; - for (var u in customUniforms) { + for (var u in customUniforms) + { this.uniforms[u] = customUniforms[u]; } @@ -43,7 +45,8 @@ aColor: 0 }; - for (var a in customAttributes) { + for (var a in customAttributes) + { this.attributes[a] = customAttributes[a]; } @@ -66,7 +69,8 @@ 'const vec2 center = vec2(-1.0, 1.0);', - 'void main(void) {', + 'void main(void) + {', ' gl_Position = vec4( ((aVertexPosition + offsetVector) / projectionVector) + center , 0.0, 1.0);', ' vTextureCoord = aTextureCoord;', ' vColor = vec4(aColor.rgb * aColor.a, aColor.a);', @@ -85,7 +89,8 @@ 'uniform sampler2D uSampler;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;', '}' ].join('\n'); @@ -96,7 +101,8 @@ Shader.prototype.constructor = Shader; module.exports = Shader; -Shader.prototype.init = function () { +Shader.prototype.init = function () +{ this.compile(); this.gl.useProgram(this.program); @@ -105,14 +111,18 @@ this.cacheAttributeLocations(Object.keys(this.attributes)); }; -Shader.prototype.cacheUniformLocations = function (keys) { - for (var i = 0; i < keys.length; ++i) { +Shader.prototype.cacheUniformLocations = function (keys) +{ + for (var i = 0; i < keys.length; ++i) + { this.uniforms[keys[i]]._location = this.gl.getUniformLocation(this.program, keys[i]); } }; -Shader.prototype.cacheAttributeLocations = function (keys) { - for (var i = 0; i < keys.length; ++i) { +Shader.prototype.cacheAttributeLocations = function (keys) +{ + for (var i = 0; i < keys.length; ++i) + { this.attributes[keys[i]] = this.gl.getAttribLocation(this.program, keys[i]); } @@ -124,14 +134,16 @@ // 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.attributes.aColor === -1) { + // if (this.attributes.aColor === -1) + { // this.attributes.aColor = 2; // } // End worst hack eva // }; -Shader.prototype.compile = function () { +Shader.prototype.compile = function () +{ var gl = this.gl; var glVertShader = this._glCompile(gl.VERTEX_SHADER, this.vertexSrc); @@ -144,13 +156,15 @@ gl.linkProgram(program); // if linking fails, then log and cleanup - if (!gl.getProgramParameter(program, gl.LINK_STATUS)) { + if (!gl.getProgramParameter(program, gl.LINK_STATUS)) + { window.console.error('Pixi.js Error: Could not initialize shader.'); window.console.error('gl.VALIDATE_STATUS', gl.getProgramParameter(program, gl.VALIDATE_STATUS)); window.console.error('gl.getError()', gl.getError()); // if there is a program info log, log it - if (gl.getProgramInfoLog(program) !== '') { + if (gl.getProgramInfoLog(program) !== '') + { window.console.warn('Pixi.js Warning: gl.getProgramInfoLog()', gl.getProgramInfoLog(program)); } @@ -165,18 +179,21 @@ return (this.program = program); }; -Shader.prototype.syncUniforms = function () { +Shader.prototype.syncUniforms = function () +{ var gl = this.gl; this.textureCount = 1; - for (var key in this.uniforms) { + for (var key in this.uniforms) + { var uniform = this.uniforms[key], location = uniform._location, value = uniform.value, i, il; - switch (uniform.type) { + switch (uniform.type) + { // single int value case 'i': case '1i': @@ -282,7 +299,8 @@ // a Color Value case 'c': - if (typeof value === 'number') { + if (typeof value === 'number') + { value = utils.hex2rgb(value); } @@ -311,11 +329,13 @@ // array of 2D Point objects case 'v2v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(2 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 2] = value[i].x; uniform._array[i * 2 + 1] = value[i].y; } @@ -325,11 +345,13 @@ // array of 3D Point objects case 'v3v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(3 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 3] = value[i].x; uniform._array[i * 3 + 1] = value[i].y; uniform._array[i * 3 + 2] = value[i].z; @@ -341,11 +363,13 @@ // array of 4D Point objects case 'v4v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(4 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 4] = value[i].x; uniform._array[i * 4 + 1] = value[i].y; uniform._array[i * 4 + 2] = value[i].z; @@ -359,7 +383,8 @@ // PIXI.Texture case 't': case 'sampler2D': - if (!uniform.value || !uniform.value.baseTexture || !uniform.value.baseTexture.hasLoaded) { + if (!uniform.value || !uniform.value.baseTexture || !uniform.value.baseTexture.hasLoaded) + { break; } @@ -376,7 +401,8 @@ this.textureCount++; // initialize the texture if we haven't yet - if (!uniform._init) { + if (!uniform._init) + { this.initSampler2D(uniform); uniform._init = true; @@ -394,11 +420,13 @@ * Initialises a Sampler2D uniform (which may only be available later on after initUniforms once the texture has loaded) * */ -Shader.prototype.initSampler2D = function (uniform) { +Shader.prototype.initSampler2D = function (uniform) +{ var gl = this.gl; // Extended texture data - if (uniform.textureData) { + if (uniform.textureData) + { var data = uniform.textureData; // GLTexture = mag linear, min linear_mipmap_linear, wrap repeat + gl.generateMipmap(gl.TEXTURE_2D); @@ -417,14 +445,16 @@ var wrapT = (data.wrapT) ? data.wrapT : gl.CLAMP_TO_EDGE; var format = (data.luminance) ? gl.LUMINANCE : gl.RGBA; - if (data.repeat) { + if (data.repeat) + { wrapS = gl.REPEAT; wrapT = gl.REPEAT; } gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, !!data.flipY); - if (data.width) { + if (data.width) + { var width = (data.width) ? data.width : 512; var height = (data.height) ? data.height : 2; var border = (data.border) ? data.border : 0; @@ -432,7 +462,8 @@ // 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 { + 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); } @@ -448,7 +479,8 @@ * Destroys the shader. * */ -Shader.prototype.destroy = function () { +Shader.prototype.destroy = function () +{ this.gl.deleteProgram(this.program); this.gl = null; @@ -459,13 +491,15 @@ this.fragmentSrc = null; }; -Shader.prototype._glCompile = function (type, src) { +Shader.prototype._glCompile = function (type, src) +{ var shader = this.gl.createShader(type); this.gl.shaderSource(shader, src); this.gl.compileShader(shader); - if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) { + if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) + { window.console.log(this.gl.getShaderInfoLog(shader)); return null; } diff --git a/src/core/renderers/webgl/shaders/StripShader.js b/src/core/renderers/webgl/shaders/StripShader.js index 193f6e1..a7abcc6 100644 --- a/src/core/renderers/webgl/shaders/StripShader.js +++ b/src/core/renderers/webgl/shaders/StripShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function StripShader(gl) { +function StripShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -20,7 +21,8 @@ 'varying vec2 vTextureCoord;', - 'void main(void) {', + '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);', @@ -36,7 +38,8 @@ 'varying vec2 vTextureCoord;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vec2(vTextureCoord.x, vTextureCoord.y)) * alpha;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/utils/FilterTexture.js b/src/core/renderers/webgl/utils/FilterTexture.js index d2c8423..4433d44 100644 --- a/src/core/renderers/webgl/utils/FilterTexture.js +++ b/src/core/renderers/webgl/utils/FilterTexture.js @@ -8,7 +8,8 @@ * @param height {number} the vertical range of the filter * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values */ -function FilterTexture(gl, width, height, scaleMode) { +function FilterTexture(gl, width, height, scaleMode) +{ /** * @member {WebGLContext} */ @@ -59,7 +60,8 @@ * Clears the filter texture. * */ -FilterTexture.prototype.clear = function () { +FilterTexture.prototype.clear = function () +{ var gl = this.gl; gl.clearColor(0,0,0, 0); @@ -72,8 +74,10 @@ * @param width {number} the new width of the texture * @param height {number} the new height of the texture */ -FilterTexture.prototype.resize = function (width, height) { - if (this.width === width && this.height === height) { +FilterTexture.prototype.resize = function (width, height) +{ + if (this.width === width && this.height === height) + { return; } @@ -96,7 +100,8 @@ * Destroys the filter texture. * */ -FilterTexture.prototype.destroy = function () { +FilterTexture.prototype.destroy = function () +{ var gl = this.gl; gl.deleteFramebuffer( this.frameBuffer ); gl.deleteTexture( this.texture ); diff --git a/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js b/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js index c4721e9..a63f4d7 100644 --- a/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js +++ b/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js @@ -14,7 +14,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this sprite batch works for. */ -function WebGLFastSpriteBatch(renderer) { +function WebGLFastSpriteBatch(renderer) +{ /** * The renderer instance this sprite batch operates on. * @@ -91,7 +92,8 @@ */ this.lastIndexCount = 0; - for (var i=0, j=0; i < numIndices; i += 6, j += 4) { + 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; @@ -144,7 +146,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.setupContext(); }); } @@ -157,7 +160,8 @@ * * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLFastSpriteBatch.prototype.setupContext = function () { +WebGLFastSpriteBatch.prototype.setupContext = function () +{ var gl = this.renderer.gl; // create a couple of buffers @@ -177,7 +181,8 @@ /** * @param spriteBatch {SpriteBatch} The SpriteBatch container to prepare for. */ -WebGLFastSpriteBatch.prototype.begin = function (spriteBatch) { +WebGLFastSpriteBatch.prototype.begin = function (spriteBatch) +{ this.shader = this.renderer.shaderManager.fastShader; this.matrix = spriteBatch.worldTransform.toArray(true); @@ -187,33 +192,38 @@ /** */ -WebGLFastSpriteBatch.prototype.end = function () { +WebGLFastSpriteBatch.prototype.end = function () +{ this.flush(); }; /** * @param spriteBatch {SpriteBatch} The SpriteBatch container to render. */ -WebGLFastSpriteBatch.prototype.render = function (spriteBatch) { +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) { + if (!sprite.texture._uvs) + { return; } this.currentBaseTexture = sprite.texture.baseTexture; // check blend mode - if (sprite.blendMode !== this.renderer.blendModeManager.currentBlendMode) { + if (sprite.blendMode !== this.renderer.blendModeManager.currentBlendMode) + { this.flush(); this.renderer.blendModeManager.setBlendMode(sprite.blendMode); } - for (var i=0,j= children.length; i= this.size) { + if (this.currentBatchSize >= this.size) + { this.flush(); } }; @@ -362,29 +379,35 @@ /** * */ -WebGLFastSpriteBatch.prototype.flush = function () { +WebGLFastSpriteBatch.prototype.flush = function () +{ // If the batch is length 0 then return as there is nothing to draw - if (this.currentBatchSize === 0) { + if (this.currentBatchSize === 0) + { return; } var gl = this.renderer.gl; // bind the current texture - if (!this.currentBaseTexture._glTextures[gl.id]) { + if (!this.currentBaseTexture._glTextures[gl.id]) + { this.renderer.updateTexture(this.currentBaseTexture, gl); } //TODO-SHOUD THIS BE ELSE??!?!?! - else { + else + { gl.bindTexture(gl.TEXTURE_2D, this.currentBaseTexture._glTextures[gl.id]); } // upload the verts to the buffer - if (this.currentBatchSize > ( this.size * 0.5 ) ) { + if (this.currentBatchSize > ( this.size * 0.5 ) ) + { gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); } - else { + else + { var view = this.vertices.subarray(0, this.currentBatchSize * this.vertByteSize); gl.bufferSubData(gl.ARRAY_BUFFER, 0, view); @@ -405,14 +428,16 @@ * Ends the batch and flushes * */ -WebGLFastSpriteBatch.prototype.stop = function () { +WebGLFastSpriteBatch.prototype.stop = function () +{ this.flush(); }; /** * */ -WebGLFastSpriteBatch.prototype.start = function () { +WebGLFastSpriteBatch.prototype.start = function () +{ var gl = this.renderer.gl; // bind the main texture diff --git a/src/core/renderers/webgl/utils/WebGLGraphics.js b/src/core/renderers/webgl/utils/WebGLGraphics.js index 55f4911..ab8f46e 100644 --- a/src/core/renderers/webgl/utils/WebGLGraphics.js +++ b/src/core/renderers/webgl/utils/WebGLGraphics.js @@ -19,7 +19,8 @@ * @param graphics {Graphics} * @param renderer {WebGLRenderer} */ -WebGLGraphics.renderGraphics = function (graphics, renderer) {//projection, offset) { +WebGLGraphics.renderGraphics = function (graphics, renderer) {//projection, offset) +{ var gl = renderer.gl; var projection = renderer.projection, @@ -27,7 +28,8 @@ shader = renderer.shaderManager.primitiveShader, webGLData; - if (graphics.dirty) { + if (graphics.dirty) + { WebGLGraphics.updateGraphics(graphics, gl); } @@ -35,8 +37,10 @@ // This could be speeded up for sure! - for (var i = 0; i < webGL.data.length; i++) { - if (webGL.data[i].mode === 1) { + for (var i = 0; i < webGL.data.length; i++) + { + if (webGL.data[i].mode === 1) + { webGLData = webGL.data[i]; renderer.stencilManager.pushStencil(graphics, webGLData, renderer); @@ -46,7 +50,8 @@ renderer.stencilManager.popStencil(graphics, webGLData, renderer); } - else { + else + { webGLData = webGL.data[i]; @@ -84,12 +89,14 @@ * @param graphicsData {Graphics} The graphics object to update * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLGraphics.updateGraphics = function (graphics, gl) { +WebGLGraphics.updateGraphics = function (graphics, gl) +{ // get the contexts graphics object var webGL = graphics._webGL[gl.id]; // if the graphics object does not exist in the webGL context time to create it! - if (!webGL) { + if (!webGL) + { webGL = graphics._webGL[gl.id] = {lastIndex:0, data:[], gl:gl}; } @@ -99,11 +106,13 @@ var i; // if the user cleared the graphics object we will need to clear every object - if (graphics.clearDirty) { + if (graphics.clearDirty) + { graphics.clearDirty = false; // lop through and return all the webGLDatas to the object pool so than can be reused later on - for (i = 0; i < webGL.data.length; i++) { + for (i = 0; i < webGL.data.length; i++) + { var graphicsData = webGL.data[i]; graphicsData.reset(); WebGLGraphics.graphicsDataPool.push( graphicsData ); @@ -119,58 +128,72 @@ // loop through the graphics datas and construct each one.. // if the object is a complex fill then the new stencil buffer technique will be used // other wise graphics objects will be pushed into a batch.. - for (i = webGL.lastIndex; i < graphics.graphicsData.length; i++) { + for (i = webGL.lastIndex; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { // need to add the points the the graphics object.. data.points = data.shape.points.slice(); - if (data.shape.closed) { + if (data.shape.closed) + { // close the poly if the value is true! - if (data.points[0] !== data.points[data.points.length-2] || data.points[1] !== data.points[data.points.length-1]) { + if (data.points[0] !== data.points[data.points.length-2] || data.points[1] !== data.points[data.points.length-1]) + { data.points.push(data.points[0], data.points[1]); } } // MAKE SURE WE HAVE THE CORRECT TYPE.. - if (data.fill) { - if (data.points.length >= 6) { - if (data.points.length < 6 * 2) { + if (data.fill) + { + if (data.points.length >= 6) + { + if (data.points.length < 6 * 2) + { webGLData = WebGLGraphics.switchMode(webGL, 0); var canDrawUsingSimple = WebGLGraphics.buildPoly(data, webGLData); // console.log(canDrawUsingSimple); - if (!canDrawUsingSimple) { + if (!canDrawUsingSimple) + { // console.log("<>>>") webGLData = WebGLGraphics.switchMode(webGL, 1); WebGLGraphics.buildComplexPoly(data, webGLData); } } - else { + else + { webGLData = WebGLGraphics.switchMode(webGL, 1); WebGLGraphics.buildComplexPoly(data, webGLData); } } } - if (data.lineWidth > 0) { + if (data.lineWidth > 0) + { webGLData = WebGLGraphics.switchMode(webGL, 0); WebGLGraphics.buildLine(data, webGLData); } } - else { + else + { webGLData = WebGLGraphics.switchMode(webGL, 0); - if (data.type === CONST.SHAPES.RECT) { + if (data.type === CONST.SHAPES.RECT) + { WebGLGraphics.buildRectangle(data, webGLData); } - else if (data.type === CONST.SHAPES.CIRC || data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.CIRC || data.type === CONST.SHAPES.ELIP) + { WebGLGraphics.buildCircle(data, webGLData); } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { WebGLGraphics.buildRoundedRectangle(data, webGLData); } } @@ -179,10 +202,12 @@ } // upload all the dirty data... - for (i = 0; i < webGL.data.length; i++) { + for (i = 0; i < webGL.data.length; i++) + { webGLData = webGL.data[i]; - if (webGLData.dirty) { + if (webGLData.dirty) + { webGLData.upload(); } } @@ -194,18 +219,22 @@ * @param webGL {WebGLContext} * @param type {number} */ -WebGLGraphics.switchMode = function (webGL, type) { +WebGLGraphics.switchMode = function (webGL, type) +{ var webGLData; - if (!webGL.data.length) { + if (!webGL.data.length) + { webGLData = WebGLGraphics.graphicsDataPool.pop() || new WebGLGraphicsData(webGL.gl); webGLData.mode = type; webGL.data.push(webGLData); } - else { + else + { webGLData = webGL.data[webGL.data.length-1]; - if (webGLData.mode !== type || type === 1) { + if (webGLData.mode !== type || type === 1) + { webGLData = WebGLGraphics.graphicsDataPool.pop() || new WebGLGraphicsData(webGL.gl); webGLData.mode = type; webGL.data.push(webGLData); @@ -225,7 +254,8 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildRectangle = function (graphicsData, webGLData) { +WebGLGraphics.buildRectangle = function (graphicsData, webGLData) +{ // --- // // need to convert points to a nice regular data // @@ -235,7 +265,8 @@ var width = rectData.width; var height = rectData.height; - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -265,7 +296,8 @@ indices.push(vertPos, vertPos, vertPos+1, vertPos+2, vertPos+3, vertPos+3); } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = [x, y, @@ -289,7 +321,8 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildRoundedRectangle = function (graphicsData, webGLData) { +WebGLGraphics.buildRoundedRectangle = function (graphicsData, webGLData) +{ var rrectData = graphicsData.shape; var x = rrectData.x; var y = rrectData.y; @@ -305,7 +338,8 @@ recPoints = recPoints.concat(WebGLGraphics.quadraticBezierCurve(x + width, y + radius, x + width, y, x + width - radius, y)); recPoints = recPoints.concat(WebGLGraphics.quadraticBezierCurve(x + radius, y, x, y, x, y + radius)); - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -323,7 +357,8 @@ // var i = 0; - for (i = 0; i < triangles.length; i+=3) { + for (i = 0; i < triangles.length; i+=3) + { indices.push(triangles[i] + vecPos); indices.push(triangles[i] + vecPos); indices.push(triangles[i+1] + vecPos); @@ -332,12 +367,14 @@ } - for (i = 0; i < recPoints.length; i++) { + for (i = 0; i < recPoints.length; i++) + { verts.push(recPoints[i], recPoints[++i], r, g, b, alpha); } } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = recPoints; @@ -362,7 +399,8 @@ * @param toY {number} Destination point y * @return {number[]} */ -WebGLGraphics.quadraticBezierCurve = function (fromX, fromY, cpX, cpY, toX, toY) { +WebGLGraphics.quadraticBezierCurve = function (fromX, fromY, cpX, cpY, toX, toY) +{ var xa, ya, @@ -373,14 +411,16 @@ n = 20, points = []; - function getPt(n1 , n2, perc) { + function getPt(n1 , n2, perc) + { var diff = n2 - n1; return n1 + ( diff * perc ); } var j = 0; - for (var i = 0; i <= n; i++ ) { + for (var i = 0; i <= n; i++ ) + { j = i / n; // The Green Line @@ -406,7 +446,8 @@ * @param graphicsData {Graphics} The graphics object to draw * @param webGLData {object} */ -WebGLGraphics.buildCircle = function (graphicsData, webGLData) { +WebGLGraphics.buildCircle = function (graphicsData, webGLData) +{ // need to convert points to a nice regular data var circleData = graphicsData.shape; var x = circleData.x; @@ -415,11 +456,13 @@ var height; // TODO - bit hacky?? - if (graphicsData.type === CONST.SHAPES.CIRC) { + if (graphicsData.type === CONST.SHAPES.CIRC) + { width = circleData.radius; height = circleData.radius; } - else { + else + { width = circleData.width; height = circleData.height; } @@ -429,7 +472,8 @@ var i = 0; - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -444,7 +488,8 @@ indices.push(vecPos); - for (i = 0; i < totalSegs + 1 ; i++) { + for (i = 0; i < totalSegs + 1 ; i++) + { verts.push(x,y, r, g, b, alpha); verts.push(x + Math.sin(seg * i) * width, @@ -457,12 +502,14 @@ indices.push(vecPos-1); } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = []; - for (i = 0; i < totalSegs + 1; i++) { + for (i = 0; i < totalSegs + 1; i++) + { graphicsData.points.push(x + Math.sin(seg * i) * width, y + Math.cos(seg * i) * height); } @@ -481,18 +528,22 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildLine = function (graphicsData, webGLData) { +WebGLGraphics.buildLine = function (graphicsData, webGLData) +{ // TODO OPTIMISE! var i = 0; var points = graphicsData.points; - if (points.length === 0) { + if (points.length === 0) + { return; } // if the line width is an odd number add 0.5 to align to a whole pixel - if (graphicsData.lineWidth%2) { - for (i = 0; i < points.length; i++) { + if (graphicsData.lineWidth%2) + { + for (i = 0; i < points.length; i++) + { points[i] += 0.5; } } @@ -502,7 +553,8 @@ var lastPoint = new math.Point(points[points.length - 2], points[points.length - 1]); // if the first point is the last point - gonna have issues :) - if (firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) { + if (firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) + { // need to clone as we are going to slightly modify the shape.. points = points.slice(); @@ -562,7 +614,8 @@ verts.push(p1x + perpx , p1y + perpy, r, g, b, alpha); - for (i = 1; i < length-1; i++) { + for (i = 1; i < length-1; i++) + { p1x = points[(i-1)*2]; p1y = points[(i-1)*2 + 1]; @@ -599,7 +652,8 @@ denom = a1*b2 - a2*b1; - if (Math.abs(denom) < 0.1 ) { + if (Math.abs(denom) < 0.1 ) + { denom+=10.1; verts.push(p2x - perpx , p2y - perpy, @@ -618,7 +672,8 @@ pdist = (px -p2x) * (px -p2x) + (py -p2y) + (py -p2y); - if (pdist > 140 * 140) { + if (pdist > 140 * 140) + { perp3x = perpx - perp2x; perp3y = perpy - perp2y; @@ -639,7 +694,8 @@ indexCount++; } - else { + else + { verts.push(px , py); verts.push(r, g, b, alpha); @@ -672,7 +728,8 @@ indices.push(indexStart); - for (i = 0; i < indexCount; i++) { + for (i = 0; i < indexCount; i++) + { indices.push(indexStart++); } @@ -687,11 +744,13 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildComplexPoly = function (graphicsData, webGLData) { +WebGLGraphics.buildComplexPoly = function (graphicsData, webGLData) +{ //TODO - no need to copy this as it gets turned into a FLoat32Array anyways.. var points = graphicsData.points.slice(); - if (points.length < 6) { + if (points.length < 6) + { return; } @@ -711,7 +770,8 @@ var x,y; // get size.. - for (var i = 0; i < points.length; i+=2) { + for (var i = 0; i < points.length; i+=2) + { x = points[i]; y = points[i+1]; @@ -732,7 +792,8 @@ //TODO - this aint needed! var length = points.length / 2; - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { indices.push( i ); } @@ -746,10 +807,12 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildPoly = function (graphicsData, webGLData) { +WebGLGraphics.buildPoly = function (graphicsData, webGLData) +{ var points = graphicsData.points; - if (points.length < 6) { + if (points.length < 6) + { return; } // get first and last point.. figure out the middle! @@ -767,7 +830,8 @@ var triangles = utils.PolyK.Triangulate(points); - if (!triangles) { + if (!triangles) + { return false; } @@ -775,7 +839,8 @@ var i = 0; - for (i = 0; i < triangles.length; i+=3) { + for (i = 0; i < triangles.length; i+=3) + { indices.push(triangles[i] + vertPos); indices.push(triangles[i] + vertPos); indices.push(triangles[i+1] + vertPos); @@ -783,7 +848,8 @@ indices.push(triangles[i+2] + vertPos); } - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { verts.push(points[i * 2], points[i * 2 + 1], r, g, b, alpha); } diff --git a/src/core/renderers/webgl/utils/WebGLGraphicsData.js b/src/core/renderers/webgl/utils/WebGLGraphicsData.js index c56d05e..c739ba7 100644 --- a/src/core/renderers/webgl/utils/WebGLGraphicsData.js +++ b/src/core/renderers/webgl/utils/WebGLGraphicsData.js @@ -2,7 +2,8 @@ * @class * @private */ -function WebGLGraphicsData(gl) { +function WebGLGraphicsData(gl) +{ this.gl = gl; //TODO does this need to be split before uploding?? @@ -22,7 +23,8 @@ /** * */ -WebGLGraphicsData.prototype.reset = function () { +WebGLGraphicsData.prototype.reset = function () +{ this.points.length = 0; this.indices.length = 0; }; @@ -30,7 +32,8 @@ /** * */ -WebGLGraphicsData.prototype.upload = function () { +WebGLGraphicsData.prototype.upload = function () +{ var gl = this.gl; // this.lastIndex = graphics.graphicsData.length; diff --git a/src/core/renderers/webgl/utils/WebGLSpriteBatch.js b/src/core/renderers/webgl/utils/WebGLSpriteBatch.js index 96eaa52..55befbb 100644 --- a/src/core/renderers/webgl/utils/WebGLSpriteBatch.js +++ b/src/core/renderers/webgl/utils/WebGLSpriteBatch.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this sprite batch works for. */ -function WebGLSpriteBatch(renderer) { +function WebGLSpriteBatch(renderer) +{ /** * * @@ -88,7 +89,8 @@ */ this.lastIndexCount = 0; - for (var i=0, j=0; i < numIndices; i += 6, j += 4) { + 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; @@ -162,7 +164,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.setupContext(); }); } @@ -173,7 +176,8 @@ /** * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLSpriteBatch.prototype.setupContext = function () { +WebGLSpriteBatch.prototype.setupContext = function () +{ var gl = this.renderer.gl; // setup default shader @@ -198,7 +202,8 @@ /** * */ -WebGLSpriteBatch.prototype.begin = function () { +WebGLSpriteBatch.prototype.begin = function () +{ // this.shader = this.renderer.shaderManager.defaultShader; this.start(); @@ -206,19 +211,22 @@ /** */ -WebGLSpriteBatch.prototype.end = function () { +WebGLSpriteBatch.prototype.end = function () +{ this.flush(); }; /** * @param sprite {Sprite} the sprite to render when using this spritebatch */ -WebGLSpriteBatch.prototype.render = function (sprite) { +WebGLSpriteBatch.prototype.render = function (sprite) +{ var texture = sprite.texture; //TODO set blend modes.. // check texture.. - if (this.currentBatchSize >= this.size) { + if (this.currentBatchSize >= this.size) + { this.flush(); this.currentBaseTexture = texture.baseTexture; } @@ -227,7 +235,8 @@ var uvs = texture._uvs; // if the uvs have not updated then no point rendering just yet! - if (!uvs) { + if (!uvs) + { return; } @@ -237,7 +246,8 @@ var w0, w1, h0, h1; - if (texture.trim) { + 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; @@ -248,7 +258,8 @@ h0 = h1 + texture.crop.height; } - else { + else + { w0 = (texture.frame.width ) * (1-aX); w1 = (texture.frame.width ) * -aX; @@ -272,7 +283,8 @@ var colors = this.colors; var positions = this.positions; - if (this.renderer.roundPixels) { + if (this.renderer.roundPixels) + { // xy positions[index] = a * w1 + c * h1 + tx | 0; positions[index+1] = d * h1 + b * w1 + ty | 0; @@ -289,7 +301,8 @@ positions[index+15] = a * w1 + c * h0 + tx | 0; positions[index+16] = d * h0 + b * w1 + ty | 0; } - else { + else + { // xy positions[index] = a * w1 + c * h1 + tx; positions[index+1] = d * h1 + b * w1 + ty; @@ -338,11 +351,13 @@ * * @param sprite {TilingSprite} the tilingSprite to render */ -WebGLSpriteBatch.prototype.renderTilingSprite = function (tilingSprite) { +WebGLSpriteBatch.prototype.renderTilingSprite = function (tilingSprite) +{ var texture = tilingSprite.tilingTexture; // check texture.. - if (this.currentBatchSize >= this.size) { + if (this.currentBatchSize >= this.size) + { //return; this.flush(); this.currentBaseTexture = texture.baseTexture; @@ -351,7 +366,8 @@ // set the textures uvs temporarily // TODO create a separate texture so that we can tile part of a texture - if (!tilingSprite._uvs) { + if (!tilingSprite._uvs) + { tilingSprite._uvs = new TextureUvs(); } @@ -454,16 +470,19 @@ * Renders the content and empties the current batch. * */ -WebGLSpriteBatch.prototype.flush = function () { +WebGLSpriteBatch.prototype.flush = function () +{ // If the batch is length 0 then return as there is nothing to draw - if (this.currentBatchSize === 0) { + if (this.currentBatchSize === 0) + { return; } var gl = this.renderer.gl; var shader; - if (this.dirty) { + if (this.dirty) + { this.dirty = false; // bind the main texture gl.activeTexture(gl.TEXTURE0); @@ -482,10 +501,12 @@ } // upload the verts to the buffer - if (this.currentBatchSize > ( this.size * 0.5 ) ) { + if (this.currentBatchSize > ( this.size * 0.5 ) ) + { gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); } - else { + else + { var view = this.positions.subarray(0, this.currentBatchSize * this.vertByteSize); gl.bufferSubData(gl.ARRAY_BUFFER, 0, view); } @@ -502,7 +523,8 @@ var shaderSwap = false; var sprite; - for (var i = 0, j = this.currentBatchSize; i < j; i++) { + for (var i = 0, j = this.currentBatchSize; i < j; i++) + { sprite = this.sprites[i]; @@ -513,24 +535,28 @@ blendSwap = currentBlendMode !== nextBlendMode; shaderSwap = currentShader !== nextShader; // should I use uuidS??? - if (currentBaseTexture !== nextTexture || blendSwap || shaderSwap) { + if (currentBaseTexture !== nextTexture || blendSwap || shaderSwap) + { this.renderBatch(currentBaseTexture, batchSize, start); start = i; batchSize = 0; currentBaseTexture = nextTexture; - if (blendSwap) { + if (blendSwap) + { currentBlendMode = nextBlendMode; this.renderer.blendModeManager.setBlendMode( currentBlendMode ); } - if (shaderSwap) { + if (shaderSwap) + { currentShader = nextShader; shader = currentShader.shaders ? currentShader.shaders[gl.id] : currentShader; - if (!shader) { + if (!shader) + { shader = new Shader(gl, null, currentShader.fragmentSrc, currentShader.uniforms); currentShader.shaders[gl.id] = shader; } @@ -538,7 +564,8 @@ // set shader function??? this.renderer.shaderManager.setShader(shader); - if (shader.dirty) { + if (shader.dirty) + { shader.syncUniforms(); } @@ -569,17 +596,21 @@ * @param size {number} * @param startIndex {number} */ -WebGLSpriteBatch.prototype.renderBatch = function (texture, size, startIndex) { - if (size === 0) { +WebGLSpriteBatch.prototype.renderBatch = function (texture, size, startIndex) +{ + if (size === 0) + { return; } var gl = this.renderer.gl; - if (!texture._glTextures[gl.id]) { + if (!texture._glTextures[gl.id]) + { this.renderer.updateTexture(texture); } - else { + else + { // bind the current texture gl.bindTexture(gl.TEXTURE_2D, texture._glTextures[gl.id]); } @@ -594,7 +625,8 @@ /** * */ -WebGLSpriteBatch.prototype.stop = function () { +WebGLSpriteBatch.prototype.stop = function () +{ this.flush(); this.dirty = true; }; @@ -602,7 +634,8 @@ /** * */ -WebGLSpriteBatch.prototype.start = function () { +WebGLSpriteBatch.prototype.start = function () +{ this.dirty = true; }; @@ -610,7 +643,8 @@ * Destroys the SpriteBatch. * */ -WebGLSpriteBatch.prototype.destroy = function () { +WebGLSpriteBatch.prototype.destroy = function () +{ this.renderer.gl.deleteBuffer(this.vertexBuffer); this.renderer.gl.deleteBuffer(this.indexBuffer); diff --git a/src/core/textures/BaseTexture.js b/src/core/textures/BaseTexture.js index 2bf77d4..513d358 100644 --- a/src/core/textures/BaseTexture.js +++ b/src/core/textures/BaseTexture.js @@ -10,7 +10,8 @@ * @param source {Image|Canvas} the source object of the texture. * @param [scaleMode=scaleModes.DEFAULT] {number} See {@link scaleModes} for possible values */ -function BaseTexture(source, scaleMode) { +function BaseTexture(source, scaleMode) +{ this.uuid = utils.uuid(); /** @@ -123,7 +124,8 @@ this._needsUpdate = false; // if no source passed don't try to load - if (source) { + if (source) + { this.loadSource(source); } @@ -149,13 +151,16 @@ Object.defineProperties(BaseTexture.prototype, { needsUpdate: { - get: function () { + get: function () + { return this._needsUpdate; }, - set: function (val) { + set: function (val) + { this._needsUpdate = val; - if (val) { + if (val) + { this.emit('update', this); } } @@ -171,9 +176,11 @@ * * The logic state after calling `loadSource` directly or indirectly (eg. `fromImage`, `new BaseTexture`) is: * - * if (texture.hasLoaded) { + * if (texture.hasLoaded) + { * // texture ready for use - * } else if (texture.isLoading) { + * } else if (texture.isLoading) + { * // listen to 'loaded' and/or 'error' events on texture * } else { * // not loading, not going to load UNLESS the source is reloaded @@ -183,12 +190,14 @@ * @protected * @param source {Image|Canvas} the source object of the texture. */ -BaseTexture.prototype.loadSource = function (source) { +BaseTexture.prototype.loadSource = function (source) +{ var wasLoading = this.isLoading; this.hasLoaded = false; this.isLoading = false; - if (wasLoading && this.source) { + if (wasLoading && this.source) + { this.source.onload = null; this.source.onerror = null; } @@ -196,20 +205,24 @@ this.source = source; // Apply source if loaded. Otherwise setup appropriate loading monitors. - if ((this.source.complete || this.source.getContext) && this.source.width && this.source.height) { + if ((this.source.complete || this.source.getContext) && this.source.width && this.source.height) + { this._sourceLoaded(); } - else if(!source.getContext) { + else if(!source.getContext) + { // Image fail / not ready this.isLoading = true; var scope = this; - source.onload = function () { + source.onload = function () + { source.onload = null; source.onerror = null; - if(!scope.isLoading) { + if(!scope.isLoading) + { return; } @@ -219,11 +232,13 @@ scope.emit('loaded', scope); }; - source.onerror = function () { + source.onerror = function () + { source.onload = null; source.onerror = null; - if(!scope.isLoading) { + if(!scope.isLoading) + { return; } @@ -234,24 +249,29 @@ // Per http://www.w3.org/TR/html5/embedded-content-0.html#the-img-element // "The value of `complete` can thus change while a script is executing." // So complete needs to be re-checked after the callbacks have been added.. - if (source.complete) { + if (source.complete) + { this.isLoading = false; // ..and if we're complete now, no need for callbacks source.onload = null; source.onerror = null; - if (source.width && source.height) { + if (source.width && source.height) + { this._sourceLoaded(); // If any previous subscribers possible - if (wasLoading) { + if (wasLoading) + { this.emit('loaded', this); } } - else { + else + { // If any previous subscribers possible - if (wasLoading) { + if (wasLoading) + { this.emit('error', this); } } @@ -265,7 +285,8 @@ * * @private */ -BaseTexture.prototype._sourceLoaded = function () { +BaseTexture.prototype._sourceLoaded = function () +{ this.hasLoaded = true; this.width = this.source.naturalWidth || this.source.width; @@ -278,16 +299,20 @@ * Destroys this base texture * */ -BaseTexture.prototype.destroy = function () { - if (this.imageUrl) { +BaseTexture.prototype.destroy = function () +{ + if (this.imageUrl) + { delete utils.BaseTextureCache[this.imageUrl]; delete utils.TextureCache[this.imageUrl]; this.imageUrl = null; - if (!navigator.isCocoonJS) { + if (!navigator.isCocoonJS) + { this.source.src = ''; } } - else if (this.source && this.source._pixiId) { + else if (this.source && this.source._pixiId) + { delete utils.BaseTextureCache[this.source._pixiId]; } this.source = null; @@ -301,7 +326,8 @@ * memory again. * */ -BaseTexture.prototype.dispose = function () { +BaseTexture.prototype.dispose = function () +{ this.emit('dispose', this); }; @@ -311,7 +337,8 @@ * * @param newSrc {string} the path of the image */ -BaseTexture.prototype.updateSourceImage = function (newSrc) { +BaseTexture.prototype.updateSourceImage = function (newSrc) +{ this.source.src = newSrc; this.loadSource(this.source); }; @@ -326,18 +353,22 @@ * @param [scaleMode=scaleModes.DEFAULT] {number} See {@link scaleModes} for possible values * @return BaseTexture */ -BaseTexture.fromImage = function (imageUrl, crossorigin, scaleMode) { +BaseTexture.fromImage = function (imageUrl, crossorigin, scaleMode) +{ var baseTexture = utils.BaseTextureCache[imageUrl]; - if (crossorigin === undefined && imageUrl.indexOf('data:') !== 0) { + if (crossorigin === undefined && imageUrl.indexOf('data:') !== 0) + { crossorigin = true; } - if (!baseTexture) { + if (!baseTexture) + { // new Image() breaks tex loading in some versions of Chrome. // See https://code.google.com/p/chromium/issues/detail?id=238071 var image = new Image();//document.createElement('img'); - if (crossorigin) { + if (crossorigin) + { image.crossOrigin = ''; } @@ -347,7 +378,8 @@ utils.BaseTextureCache[imageUrl] = baseTexture; // if there is an @2x at the end of the url we are going to assume its a highres image - if ( imageUrl.indexOf(CONST.RETINA_PREFIX + '.') !== -1) { + if ( imageUrl.indexOf(CONST.RETINA_PREFIX + '.') !== -1) + { baseTexture.resolution = 2; } } @@ -363,14 +395,17 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return BaseTexture */ -BaseTexture.fromCanvas = function (canvas, scaleMode) { - if (!canvas._pixiId) { +BaseTexture.fromCanvas = function (canvas, scaleMode) +{ + if (!canvas._pixiId) + { canvas._pixiId = 'canvas_' + utils.uuid(); } var baseTexture = utils.BaseTextureCache[canvas._pixiId]; - if (!baseTexture) { + if (!baseTexture) + { baseTexture = new BaseTexture(canvas, scaleMode); utils.BaseTextureCache[canvas._pixiId] = baseTexture; } diff --git a/src/core/textures/RenderTexture.js b/src/core/textures/RenderTexture.js index 6dad20f..53ae796 100644 --- a/src/core/textures/RenderTexture.js +++ b/src/core/textures/RenderTexture.js @@ -46,8 +46,10 @@ * @param [scaleMode] {number} See {@link scaleModes} for possible values * @param [resolution=1] {number} The resolution of the texture being generated */ -function RenderTexture(renderer, width, height, scaleMode, resolution) { - if (!renderer) { +function RenderTexture(renderer, width, height, scaleMode, resolution) +{ + if (!renderer) + { throw new Error('Unable to create RenderTexture, you must pass a renderer into the constructor.'); } @@ -133,7 +135,8 @@ */ this.renderer = renderer; - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { var gl = this.renderer.gl; this.textureBuffer = new FilterTexture(gl, this.width * this.resolution, this.height * this.resolution, this.baseTexture.scaleMode); @@ -142,7 +145,8 @@ this.render = this.renderWebGL; this.projection = new math.Point(this.width*0.5, -this.height*0.5); } - else { + else + { this.render = this.renderCanvas; this.textureBuffer = new CanvasBuffer(this.width* this.resolution, this.height* this.resolution); this.baseTexture.source = this.textureBuffer.canvas; @@ -167,8 +171,10 @@ * @param height {number} The height to resize to. * @param updateBase {boolean} Should the baseTexture.width and height values be resized as well? */ -RenderTexture.prototype.resize = function (width, height, updateBase) { - if (width === this.width && height === this.height) { +RenderTexture.prototype.resize = function (width, height, updateBase) +{ + if (width === this.width && height === this.height) + { return; } @@ -177,17 +183,20 @@ this.width = this.frame.width = this.crop.width = width; this.height = this.frame.height = this.crop.height = height; - if (updateBase) { + if (updateBase) + { this.baseTexture.width = this.width; this.baseTexture.height = this.height; } - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { this.projection.x = this.width / 2; this.projection.y = -this.height / 2; } - if (!this.valid) { + if (!this.valid) + { return; } @@ -198,12 +207,15 @@ * Clears the RenderTexture. * */ -RenderTexture.prototype.clear = function () { - if (!this.valid) { +RenderTexture.prototype.clear = function () +{ + if (!this.valid) + { return; } - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { this.renderer.gl.bindFramebuffer(this.renderer.gl.FRAMEBUFFER, this.textureBuffer.frameBuffer); } @@ -220,19 +232,23 @@ * @param [restoreWorldTransform=true] {boolean} If true the displayObject's worldTransform/worldAlpha and all children * transformations will be restored. Not restoring this information will be a little faster. */ -RenderTexture.prototype.renderWebGL = function (displayObject, matrix, clear, restoreWorldTransform) { - if (!this.valid) { +RenderTexture.prototype.renderWebGL = function (displayObject, matrix, clear, restoreWorldTransform) +{ + if (!this.valid) + { return; } - if (typeof restoreWorldTransform === 'undefined') { + if (typeof restoreWorldTransform === 'undefined') + { restoreWorldTransform = true; } var tempAlpha, tempTransform; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { tempAlpha = displayObject.worldAlpha; tempTransform = displayObject.worldTransform.toArray(); } @@ -245,7 +261,8 @@ wt.identity(); wt.translate(0, this.projection.y * 2); - if (matrix) { + if (matrix) + { wt.append(matrix); } @@ -258,7 +275,8 @@ var children = displayObject.children; var i, j; - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } @@ -269,7 +287,8 @@ gl.bindFramebuffer(gl.FRAMEBUFFER, this.textureBuffer.frameBuffer ); - if (clear) { + if (clear) + { this.textureBuffer.clear(); } @@ -279,11 +298,13 @@ this.renderer.spriteBatch.dirty = true; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { displayObject.worldAlpha = tempAlpha; displayObject.worldTransform.fromArray(tempTransform); - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } } @@ -300,26 +321,31 @@ * @param [restoreWorldTransform=true] {boolean} If true the displayObject's worldTransform/worldAlpha and all children * transformations will be restored. Not restoring this information will be a little faster. */ -RenderTexture.prototype.renderCanvas = function (displayObject, matrix, clear, restoreWorldTransform) { - if (!this.valid) { +RenderTexture.prototype.renderCanvas = function (displayObject, matrix, clear, restoreWorldTransform) +{ + if (!this.valid) + { return; } - if (typeof restoreWorldTransform === 'undefined') { + if (typeof restoreWorldTransform === 'undefined') + { restoreWorldTransform = true; } var tempAlpha, tempTransform; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { tempAlpha = displayObject.worldAlpha; tempTransform = displayObject.worldTransform.toArray(); } var wt = displayObject.worldTransform; wt.identity(); - if (matrix) { + if (matrix) + { wt.append(matrix); } @@ -330,11 +356,13 @@ var children = displayObject.children; var i, j; - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } - if (clear) { + if (clear) + { this.textureBuffer.clear(); } @@ -348,11 +376,13 @@ this.renderer.resolution = realResolution; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { displayObject.worldAlpha = tempAlpha; displayObject.worldTransform.fromArray(tempTransform); - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } } @@ -363,7 +393,8 @@ * * @return {Image} */ -RenderTexture.prototype.getImage = function () { +RenderTexture.prototype.getImage = function () +{ var image = new Image(); image.src = this.getBase64(); return image; @@ -374,7 +405,8 @@ * * @return {string} A base64 encoded string of the texture. */ -RenderTexture.prototype.getBase64 = function () { +RenderTexture.prototype.getBase64 = function () +{ return this.getCanvas().toDataURL(); }; @@ -383,8 +415,10 @@ * * @return {HTMLCanvasElement} A Canvas element with the texture rendered on. */ -RenderTexture.prototype.getCanvas = function () { - if (this.renderer.type === CONST.WEBGL_RENDERER) { +RenderTexture.prototype.getCanvas = function () +{ + if (this.renderer.type === CONST.WEBGL_RENDERER) + { var gl = this.renderer.gl; var width = this.textureBuffer.width; var height = this.textureBuffer.height; @@ -403,7 +437,8 @@ return tempCanvas.canvas; } - else { + else + { return this.textureBuffer.canvas; } }; diff --git a/src/core/textures/Texture.js b/src/core/textures/Texture.js index 3c65909..e97f0aa 100644 --- a/src/core/textures/Texture.js +++ b/src/core/textures/Texture.js @@ -17,7 +17,8 @@ * @param [crop] {Rectangle} The area of original texture * @param [trim] {Rectangle} Trimmed texture rectangle */ -function Texture(baseTexture, frame, crop, trim) { +function Texture(baseTexture, frame, crop, trim) +{ /** * Does this Texture have any frame data assigned to it? * @@ -25,12 +26,14 @@ */ this.noFrame = false; - if (!frame) { + if (!frame) + { this.noFrame = true; frame = new math.Rectangle(0, 0, 1, 1); } - if (baseTexture instanceof Texture) { + if (baseTexture instanceof Texture) + { baseTexture = baseTexture.baseTexture; } @@ -100,13 +103,16 @@ */ this.crop = crop || new math.Rectangle(0, 0, 1, 1); - if (baseTexture.hasLoaded) { - if (this.noFrame) { + if (baseTexture.hasLoaded) + { + if (this.noFrame) + { frame = new math.Rectangle(0, 0, baseTexture.width, baseTexture.height); } this.frame = frame; } - else { + else + { baseTexture.addEventListener('loaded', this.onBaseTextureLoaded.bind(this)); } } @@ -118,19 +124,23 @@ Object.defineProperties(Texture.prototype, { needsUpdate: { - get: function () { + get: function () + { return this.baseTexture.needsUpdate; }, - set: function (val) { + set: function (val) + { this.baseTexture.needsUpdate = val; } }, frame: { - get: function () { + get: function () + { return this._frame; }, - set: function (frame) { + set: function (frame) + { this._frame = frame; this.noFrame = false; @@ -143,20 +153,23 @@ 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 (!this.trim && (frame.x + frame.width > this.baseTexture.width || frame.y + frame.height > this.baseTexture.height)) + { throw new Error('Texture Error: frame does not fit inside the base Texture dimensions ' + this); } this.valid = frame && frame.width && frame.height && this.baseTexture.source && this.baseTexture.hasLoaded; - if (this.trim) { + 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) { + if (this.valid) + { this._updateUvs(); } } @@ -168,11 +181,13 @@ * * @private */ -Texture.prototype.onBaseTextureLoaded = function () { +Texture.prototype.onBaseTextureLoaded = function () +{ var baseTexture = this.baseTexture; baseTexture.removeEventListener('loaded', this.onLoaded); - if (this.noFrame) { + if (this.noFrame) + { this.frame = new math.Rectangle(0, 0, baseTexture.width, baseTexture.height); } @@ -184,8 +199,10 @@ * * @param destroyBase {boolean} Whether to destroy the base texture as well */ -Texture.prototype.destroy = function (destroyBase) { - if (destroyBase) { +Texture.prototype.destroy = function (destroyBase) +{ + if (destroyBase) + { this.baseTexture.destroy(); } @@ -197,8 +214,10 @@ * * @private */ -Texture.prototype._updateUvs = function () { - if (!this._uvs) { +Texture.prototype._updateUvs = function () +{ + if (!this._uvs) + { this._uvs = new TextureUvs(); } @@ -229,10 +248,12 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return Texture */ -Texture.fromImage = function (imageUrl, crossorigin, scaleMode) { +Texture.fromImage = function (imageUrl, crossorigin, scaleMode) +{ var texture = utils.TextureCache[imageUrl]; - if (!texture) { + if (!texture) + { texture = new Texture(BaseTexture.fromImage(imageUrl, crossorigin, scaleMode)); utils.TextureCache[imageUrl] = texture; } @@ -248,9 +269,11 @@ * @param frameId {string} The frame id of the texture * @return Texture */ -Texture.fromFrame = function (frameId) { +Texture.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache '); } return texture; @@ -264,7 +287,8 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return {Texture} */ -Texture.fromCanvas = function (canvas, scaleMode) { +Texture.fromCanvas = function (canvas, scaleMode) +{ return new Texture(BaseTexture.fromCanvas(canvas, scaleMode)); }; @@ -276,7 +300,8 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return {Texture} A Texture */ -Texture.fromVideo = function (video, scaleMode) { +Texture.fromVideo = function (video, scaleMode) +{ return new Texture(VideoBaseTexture.baseTextureFromVideo(video, scaleMode)); }; @@ -287,7 +312,8 @@ * @param texture {Texture} The Texture to add to the cache. * @param id {string} The id that the texture will be stored against. */ -Texture.addTextureToCache = function (texture, id) { +Texture.addTextureToCache = function (texture, id) +{ utils.TextureCache[id] = texture; }; @@ -298,7 +324,8 @@ * @param id {string} The id of the texture to be removed * @return {Texture} The texture that was removed */ -Texture.removeTextureFromCache = function (id) { +Texture.removeTextureFromCache = function (id) +{ var texture = utils.TextureCache[id]; delete utils.TextureCache[id]; diff --git a/src/core/textures/TextureUvs.js b/src/core/textures/TextureUvs.js index b9bbb58..5424d52 100644 --- a/src/core/textures/TextureUvs.js +++ b/src/core/textures/TextureUvs.js @@ -1,4 +1,5 @@ -function TextureUvs() { +function TextureUvs() +{ this.x0 = 0; this.y0 = 0; diff --git a/src/core/textures/VideoBaseTexture.js b/src/core/textures/VideoBaseTexture.js index e3e0c5a..1a826a9 100644 --- a/src/core/textures/VideoBaseTexture.js +++ b/src/core/textures/VideoBaseTexture.js @@ -12,15 +12,18 @@ * @param source {HTMLVideoElement} * @param [scaleMode] {number} See {@link scaleModes} for possible values */ -function VideoBaseTexture(source, scaleMode) { - if (!source){ +function VideoBaseTexture(source, scaleMode) +{ + if (!source) + { throw new Error('No video source element specified.'); } // hook in here to check if video is already available. // BaseTexture looks for a source.complete boolean, plus width & height. - if ((source.readyState === source.HAVE_ENOUGH_DATA || source.readyState === source.HAVE_FUTURE_DATA) && source.width && source.height) { + if ((source.readyState === source.HAVE_ENOUGH_DATA || source.readyState === source.HAVE_FUTURE_DATA) && source.width && source.height) + { source.complete = true; } @@ -31,7 +34,8 @@ this._boundOnUpdate = this._onUpdate.bind(this); this._boundOnCanPlay = this._onCanPlay.bind(this); - if (!source.complete) { + if (!source.complete) + { source.addEventListener('canplay', this._boundOnCanPlay); source.addEventListener('canplaythrough', this._boundOnCanPlay); @@ -47,28 +51,35 @@ VideoBaseTexture.prototype.constructor = VideoBaseTexture; module.exports = VideoBaseTexture; -VideoBaseTexture.prototype._onUpdate = function () { - if (this.autoUpdate) { +VideoBaseTexture.prototype._onUpdate = function () +{ + if (this.autoUpdate) + { window.requestAnimationFrame(this._boundOnUpdate); this.needsUpdate = true; } }; -VideoBaseTexture.prototype._onPlayStart = function () { - if (!this.autoUpdate) { +VideoBaseTexture.prototype._onPlayStart = function () +{ + if (!this.autoUpdate) + { window.requestAnimationFrame(this._boundOnUpdate); this.autoUpdate = true; } }; -VideoBaseTexture.prototype._onPlayStop = function () { +VideoBaseTexture.prototype._onPlayStop = function () +{ this.autoUpdate = false; }; -VideoBaseTexture.prototype._onCanPlay = function () { +VideoBaseTexture.prototype._onCanPlay = function () +{ this.hasLoaded = true; - if (this.source) { + if (this.source) + { this.source.removeEventListener('canplay', this._boundOnCanPlay); this.source.removeEventListener('canplaythrough', this._boundOnCanPlay); @@ -78,15 +89,18 @@ this.source.play(); // prevent multiple loaded dispatches.. - if(!this.__loaded){ + if(!this.__loaded) + { this.__loaded = true; this.emit('loaded', this); } } }; -VideoBaseTexture.prototype.destroy = function () { - if (this.source && this.source._pixiId) { +VideoBaseTexture.prototype.destroy = function () +{ + if (this.source && this.source._pixiId) + { utils.BaseTextureCache[ this.source._pixiId ] = null; delete utils.BaseTextureCache[ this.source._pixiId ]; @@ -105,14 +119,17 @@ * @param scaleMode {number} See {@link scaleModes} for possible values * @return {VideoBaseTexture} */ -VideoBaseTexture.fromVideo = function (video, scaleMode) { - if (!video._pixiId) { +VideoBaseTexture.fromVideo = function (video, scaleMode) +{ + if (!video._pixiId) + { video._pixiId = 'video_' + utils.uuid(); } var baseTexture = utils.BaseTextureCache[video._pixiId]; - if (!baseTexture) { + if (!baseTexture) + { baseTexture = new VideoBaseTexture(video, scaleMode); utils.BaseTextureCache[ video._pixiId ] = baseTexture; } @@ -147,17 +164,21 @@ * @param scaleMode {number} See {@link scaleModes} for possible values * @return {VideoBaseTexture} */ -VideoBaseTexture.fromUrl = function (videoSrc, scaleMode) { +VideoBaseTexture.fromUrl = function (videoSrc, scaleMode) +{ var video = document.createElement('video'); // array of objects or strings - if (Array.isArray(videoSrc)) { - for (var i = 0; i < videoSrc.length; ++i) { + if (Array.isArray(videoSrc)) + { + for (var i = 0; i < videoSrc.length; ++i) + { video.appendChild(createSource(videoSrc.src || videoSrc, videoSrc.mime)); } } // single object or string - else { + else + { video.appendChild(createSource(videoSrc.src || videoSrc, videoSrc.mime)); } @@ -169,8 +190,10 @@ VideoBaseTexture.fromUrls = VideoBaseTexture.fromUrl; -function createSource(path, type) { - if (!type) { +function createSource(path, type) +{ + if (!type) + { type = 'video/' + path.substr(path.lastIndexOf('.') + 1); } diff --git a/src/core/utils/EventData.js b/src/core/utils/EventData.js index 5d55a22..8cdf701 100644 --- a/src/core/utils/EventData.js +++ b/src/core/utils/EventData.js @@ -7,7 +7,8 @@ * @param name {string} The string name of the event that was triggered * @param data {object} Arbitrary event data to pass along */ -function EventData(target, name, data) { +function EventData(target, name, data) +{ // for duck typing in the ".on()" function this.__isEventObject = true; @@ -71,7 +72,8 @@ * Stops the propagation of events up the scene graph (prevents bubbling). * */ -EventData.prototype.stopPropagation = function stopPropagation() { +EventData.prototype.stopPropagation = function stopPropagation() +{ this.stopped = true; }; @@ -79,6 +81,7 @@ * Stops the propagation of events to sibling listeners (no longer calls any listeners). * */ -EventData.prototype.stopImmediatePropagation = function stopImmediatePropagation() { +EventData.prototype.stopImmediatePropagation = function stopImmediatePropagation() +{ this.stoppedImmediate = true; }; diff --git a/src/core/utils/EventTarget.js b/src/core/utils/EventTarget.js index 7ae8820..671a151 100644 --- a/src/core/utils/EventTarget.js +++ b/src/core/utils/EventTarget.js @@ -13,14 +13,16 @@ * var em = new MyEmitter(); * em.emit('eventName', 'some data', 'some more data', {}, null, ...); */ -function eventTarget(obj) { +function eventTarget(obj) +{ /** * Return a list of assigned event listeners. * * @param eventName {string} The events that should be listed. * @return {Array} An array of listener functions */ - obj.listeners = function listeners(eventName) { + obj.listeners = function listeners(eventName) + { this._listeners = this._listeners || {}; return this._listeners[eventName] ? this._listeners[eventName].slice() : []; @@ -33,22 +35,26 @@ * @param eventName {string} The name of the event. * @return {boolean} Indication if we've emitted an event. */ - obj.emit = obj.dispatchEvent = function emit(eventName, data) { + obj.emit = obj.dispatchEvent = function emit(eventName, data) + { this._listeners = this._listeners || {}; // fast return when there are no listeners - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return; } //backwards compat with old method ".emit({ type: 'something' })" - if (typeof eventName === 'object') { + if (typeof eventName === 'object') + { data = eventName; eventName = eventName.type; } //ensure we are using a real pixi event - if (!data || data.__isEventObject !== true) { + if (!data || data.__isEventObject !== true) + { data = new EventData(this, eventName, data); } @@ -58,23 +64,27 @@ fn = listeners[0], i; - for (i = 0; i < length; fn = listeners[++i]) { + for (i = 0; i < length; fn = listeners[++i]) + { //call the event listener fn.call(this, data); //if "stopImmediatePropagation" is called, stop calling sibling events - if (data.stoppedImmediate) { + if (data.stoppedImmediate) + { return this; } } //if "stopPropagation" is called then don't bubble the event - if (data.stopped) { + if (data.stopped) + { return this; } //bubble this event up the scene graph - if (this.parent && this.parent.emit) { + if (this.parent && this.parent.emit) + { this.parent.emit.call(this.parent, eventName, data); } @@ -88,7 +98,8 @@ * @param eventName {string} Name of the event. * @param callback {Functon} fn Callback function. */ - obj.on = obj.addEventListener = function on(eventName, fn) { + obj.on = obj.addEventListener = function on(eventName, fn) + { this._listeners = this._listeners || {}; (this._listeners[eventName] = this._listeners[eventName] || []) @@ -103,11 +114,13 @@ * @param eventName {string} Name of the event. * @param callback {Function} Callback function. */ - obj.once = function once(eventName, fn) { + obj.once = function once(eventName, fn) + { this._listeners = this._listeners || {}; var self = this; - function onceHandlerWrapper() { + function onceHandlerWrapper() + { fn.apply(self.off(eventName, onceHandlerWrapper), arguments); } onceHandlerWrapper._originalHandler = fn; @@ -122,23 +135,28 @@ * @param eventName {string} The event we want to remove. * @param callback {Function} The listener that we need to find. */ - obj.off = obj.removeEventListener = function off(eventName, fn) { + obj.off = obj.removeEventListener = function off(eventName, fn) + { this._listeners = this._listeners || {}; - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return this; } var list = this._listeners[eventName], i = fn ? list.length : 0; - while(i-- > 0) { - if (list[i] === fn || list[i]._originalHandler === fn) { + while(i-- > 0) + { + if (list[i] === fn || list[i]._originalHandler === fn) + { list.splice(i, 1); } } - if (list.length === 0) { + if (list.length === 0) + { delete this._listeners[eventName]; } @@ -150,10 +168,12 @@ * * @param eventName {string} The event you want to remove all listeners for. */ - obj.removeAllListeners = function removeAllListeners(eventName) { + obj.removeAllListeners = function removeAllListeners(eventName) + { this._listeners = this._listeners || {}; - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return this; } @@ -169,7 +189,8 @@ * * @param object {object} The obj to mix into */ - mixin: function mixin(obj) { + mixin: function mixin(obj) + { eventTarget(obj); } }; diff --git a/src/core/utils/PolyK.js b/src/core/utils/PolyK.js index 7325141..5e20c2b 100644 --- a/src/core/utils/PolyK.js +++ b/src/core/utils/PolyK.js @@ -47,7 +47,8 @@ * Triangulates shapes for webGL graphic fills. * */ -PolyK.Triangulate = function (p) { +PolyK.Triangulate = function (p) +{ var sign = true; var n = p.length >> 1; @@ -59,7 +60,8 @@ i = 0; var al = n; - while(al > 3) { + while(al > 3) + { var i0 = avl[(i+0)%al]; var i1 = avl[(i+1)%al]; var i2 = avl[(i+2)%al]; @@ -69,29 +71,35 @@ var cx = p[2*i2], cy = p[2*i2+1]; var earFound = false; - if (PolyK._convex(ax, ay, bx, by, cx, cy, sign)) { + if (PolyK._convex(ax, ay, bx, by, cx, cy, sign)) + { earFound = true; - for (var j = 0; j < al; j++) { + for (var j = 0; j < al; j++) + { var vi = avl[j]; if (vi === i0 || vi === i1 || vi === i2) continue; - if (PolyK._PointInTriangle(p[2*vi], p[2*vi+1], ax, ay, bx, by, cx, cy)) { + if (PolyK._PointInTriangle(p[2*vi], p[2*vi+1], ax, ay, bx, by, cx, cy)) + { earFound = false; break; } } } - if (earFound) { + if (earFound) + { tgs.push(i0, i1, i2); avl.splice((i+1)%al, 1); al--; i = 0; } - else if (i++ > 3*al) { + else if (i++ > 3*al) + { // need to flip flip reverse it! // reset! - if (sign) { + if (sign) + { tgs = []; avl = []; for (i = 0; i < n; i++) avl.push(i); @@ -101,7 +109,8 @@ sign = false; } - else { + else + { // window.console.log("PIXI Warning: shape too complex to fill"); return null; } @@ -126,7 +135,8 @@ * @private * @return {boolean} */ -PolyK._PointInTriangle = function (px, py, ax, ay, bx, by, cx, cy) { +PolyK._PointInTriangle = function (px, py, ax, ay, bx, by, cx, cy) +{ var v0x = cx-ax; var v0y = cy-ay; var v1x = bx-ax; @@ -154,6 +164,7 @@ * @private * @return {boolean} */ -PolyK._convex = function (ax, ay, bx, by, cx, cy, sign) { +PolyK._convex = function (ax, ay, bx, by, cx, cy, sign) +{ return ((ay-by)*(cx-bx) + (bx-ax)*(cy-by) >= 0) === sign; }; diff --git a/src/core/utils/index.js b/src/core/utils/index.js index ade9831..bfae7ae 100644 --- a/src/core/utils/index.js +++ b/src/core/utils/index.js @@ -16,7 +16,8 @@ * * @return {number} The next uuid to use. */ - uuid: function () { + uuid: function () + { return ++utils._uid; }, @@ -26,7 +27,8 @@ * @param hex {number} * @return {number[]} An array representing the [R, G, B] of the color. */ - hex2rgb: function (hex, out) { + hex2rgb: function (hex, out) + { out = out || []; out[0] = (hex >> 16 & 0xFF) / 255; @@ -42,7 +44,8 @@ * @param hex {number} * @return {string} The string color. */ - hex2string: function (hex) { + hex2string: function (hex) + { hex = hex.toString(16); hex = '000000'.substr(0, 6 - hex.length) + hex; @@ -55,7 +58,8 @@ * @param rgb {number[]} * @return {number} The color number */ - rgb2hex: function (rgb) { + rgb2hex: function (rgb) + { return ((rgb[0]*255 << 16) + (rgb[1]*255 << 8) + rgb[2]*255); }, @@ -64,8 +68,10 @@ * * @return {boolean} whether they are supported */ - canUseNewCanvasBlendModes: function () { - if (typeof document === 'undefined') { + canUseNewCanvasBlendModes: function () + { + if (typeof document === 'undefined') + { return false; } @@ -93,15 +99,19 @@ * @param number {number} * @return {number} the closest number that is a power of two */ - getNextPowerOfTwo: function (number) { + getNextPowerOfTwo: function (number) + { // see: http://en.wikipedia.org/wiki/Power_of_two#Fast_algorithm_to_check_if_a_positive_number_is_a_power_of_two - if (number > 0 && (number & (number - 1)) === 0) { + if (number > 0 && (number & (number - 1)) === 0) + { return number; } - else { + else + { var result = 1; - while (result < number) { + while (result < number) + { result <<= 1; } @@ -116,7 +126,8 @@ * @param height {number} * @return {boolean} */ - isPowerOfTwo: function (width, height) { + isPowerOfTwo: function (width, height) + { return (width > 0 && (width & (width - 1)) === 0 && height > 0 && (height & (height - 1)) === 0); }, @@ -130,12 +141,15 @@ * @constant * @static */ - sayHello: function (type) { - if (utils._saidHello) { + sayHello: function (type) + { + if (utils._saidHello) + { return; } - if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) { + if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) + { var args = [ '%c %c %c Pixi.js ' + CONST.VERSION + ' - ' + type + ' %c ' + ' %c ' + ' http://www.pixijs.com/ %c %c ♥%c♥%c♥ ', 'background: #ff66a5', @@ -151,7 +165,8 @@ console.log.apply(console, args); //jshint ignore:line } - else if (window.console) { + else if (window.console) + { console.log('Pixi.js ' + CONST.VERSION + ' - ' + type + ' - http://www.pixijs.com/'); //jshint ignore:line } @@ -166,15 +181,19 @@ * @class * @namespace PIXI */ - AjaxRequest: function () { + AjaxRequest: function () + { var activexmodes = ['Msxml2.XMLHTTP.6.0', 'Msxml2.XMLHTTP.3.0', 'Microsoft.XMLHTTP']; //activeX versions to check for in IE - if (window.ActiveXObject) { //Test for support for ActiveXObject in IE first (as XMLHttpRequest in IE7 is broken) - for (var i=0; i= this.textures.length) { + else if (round >= this.textures.length) + { this.gotoAndStop(this.textures.length - 1); - if (this.onComplete) { + if (this.onComplete) + { this.onComplete(); } } @@ -167,10 +182,12 @@ * @static * @param frames {string[]} the array of frames ids the movieclip will use as its texture frames */ -MovieClip.fromFrames = function (frames) { +MovieClip.fromFrames = function (frames) +{ var textures = []; - for (var i = 0; i < frames.length; ++i) { + for (var i = 0; i < frames.length; ++i) + { textures.push(new core.Texture.fromFrame(frames[i])); } @@ -183,10 +200,12 @@ * @static * @param images {string[]} the array of image urls the movieclip will use as its texture frames */ -MovieClip.fromImages = function (images) { +MovieClip.fromImages = function (images) +{ var textures = []; - for (var i = 0; i < images.length; ++i) { + for (var i = 0; i < images.length; ++i) + { textures.push(new core.Texture.fromImage(images[i])); } diff --git a/src/extras/Rope.js b/src/extras/Rope.js index c157ec4..9c87bc0 100644 --- a/src/extras/Rope.js +++ b/src/extras/Rope.js @@ -9,7 +9,8 @@ * @param {Array} points - An array of {Point}. * */ -function Rope(texture, points) { +function Rope(texture, points) +{ Strip.call(this, texture); this.points = points; @@ -31,10 +32,12 @@ * Refreshes * */ -Rope.prototype.refresh = function () { +Rope.prototype.refresh = function () +{ var points = this.points; - if (points.length < 1) { + if (points.length < 1) + { return; } @@ -59,20 +62,23 @@ var total = points.length, point, index, amount; - for (var i = 1; i < total; i++) { + for (var i = 1; i < total; i++) + { point = points[i]; index = i * 4; // time to do some smart drawing! amount = i / (total-1); - if (i%2) { + if (i%2) + { uvs[index] = amount; uvs[index+1] = 0; uvs[index+2] = amount; uvs[index+3] = 1; } - else { + else + { uvs[index] = amount; uvs[index+1] = 0; @@ -95,10 +101,12 @@ * * @private */ -Rope.prototype.updateTransform = function () { +Rope.prototype.updateTransform = function () +{ var points = this.points; - if (points.length < 1) { + if (points.length < 1) + { return; } @@ -113,14 +121,17 @@ var total = points.length, point, index, ratio, perpLength, num; - for (var i = 0; i < total; i++) { + for (var i = 0; i < total; i++) + { point = points[i]; index = i * 4; - if (i < points.length-1) { + if (i < points.length-1) + { nextPoint = points[i+1]; } - else { + else + { nextPoint = point; } @@ -129,7 +140,8 @@ ratio = (1 - (i / (total-1))) * 10; - if (ratio > 1) { + if (ratio > 1) + { ratio = 1; } @@ -157,7 +169,8 @@ * * @param texture {Texture} the texture that will be used */ -Rope.prototype.setTexture = function (texture) { +Rope.prototype.setTexture = function (texture) +{ // stop current texture this.texture = texture; //this.updateFrame = true; diff --git a/src/extras/Strip.js b/src/extras/Strip.js index c5e378f..57691b5 100644 --- a/src/extras/Strip.js +++ b/src/extras/Strip.js @@ -10,7 +10,8 @@ * @param height {number} the height * */ -function Strip(texture) { +function Strip(texture) +{ core.DisplayObjectContainer.call(this); /** @@ -70,9 +71,11 @@ * * @param renderer {WebGLRenderer} */ -Strip.prototype.renderWebGL = function (renderer) { +Strip.prototype.renderWebGL = function (renderer) +{ // if the sprite is not visible or the alpha is 0 then no need to render this element - if (!this.visible || this.alpha <= 0) { + if (!this.visible || this.alpha <= 0) + { return; } @@ -81,7 +84,8 @@ renderer.spriteBatch.stop(); // init! init! - if (!this._vertexBuffer) { + if (!this._vertexBuffer) + { this._initWebGL(renderer); } @@ -96,7 +100,8 @@ //TODO check culling }; -Strip.prototype._initWebGL = function (renderer) { +Strip.prototype._initWebGL = function (renderer) +{ // build the strip! var gl = renderer.gl; @@ -118,7 +123,8 @@ gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this.indices, gl.STATIC_DRAW); }; -Strip.prototype._renderStrip = function (renderer) { +Strip.prototype._renderStrip = function (renderer) +{ var gl = renderer.gl; var projection = renderer.projection, offset = renderer.offset, @@ -137,7 +143,8 @@ gl.uniform2f(shader.offsetVector, -offset.x, -offset.y); gl.uniform1f(shader.alpha, this.worldAlpha); - if (!this.dirty) { + if (!this.dirty) + { gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexBuffer); gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); @@ -150,10 +157,12 @@ gl.activeTexture(gl.TEXTURE0); // check if a texture is dirty.. - if (this.texture.baseTexture._dirty[gl.id]) { + if (this.texture.baseTexture._dirty[gl.id]) + { renderer.updateTexture(this.texture.baseTexture); } - else { + else + { // bind the current texture gl.bindTexture(gl.TEXTURE_2D, this.texture.baseTexture._glTextures[gl.id]); } @@ -163,7 +172,8 @@ } - else { + else + { this.dirty = false; gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexBuffer); @@ -178,10 +188,12 @@ gl.activeTexture(gl.TEXTURE0); // check if a texture is dirty.. - if (this.texture.baseTexture._dirty[gl.id]) { + if (this.texture.baseTexture._dirty[gl.id]) + { renderer.updateTexture(this.texture.baseTexture); } - else { + else + { gl.bindTexture(gl.TEXTURE_2D, this.texture.baseTexture._glTextures[gl.id]); } @@ -203,27 +215,33 @@ * * @param renderer {CanvasRenderer} */ -Strip.prototype.renderCanvas = function (renderer) { +Strip.prototype.renderCanvas = function (renderer) +{ var context = renderer.context; var transform = this.worldTransform; - if (renderer.roundPixels) { + if (renderer.roundPixels) + { context.setTransform(transform.a, transform.b, transform.c, transform.d, transform.tx | 0, transform.ty | 0); } - else { + else + { context.setTransform(transform.a, transform.b, transform.c, transform.d, transform.tx, transform.ty); } - if (this.drawMode === Strip.DrawModes.TRIANGLE_STRIP) { + if (this.drawMode === Strip.DrawModes.TRIANGLE_STRIP) + { this._renderCanvasTriangleStrip(context); } - else { + else + { this._renderCanvasTriangles(context); } }; -Strip.prototype._renderCanvasTriangleStrip = function (context) { +Strip.prototype._renderCanvasTriangleStrip = function (context) +{ // draw triangles!! var vertices = this.vertices; var uvs = this.uvs; @@ -231,14 +249,16 @@ var length = vertices.length / 2; // this.count++; - for (var i = 0; i < length - 2; i++) { + for (var i = 0; i < length - 2; i++) + { // draw some triangles! var index = i * 2; this._renderCanvasDrawTriangle(context, vertices, uvs, index, (index + 2), (index + 4)); } }; -Strip.prototype._renderCanvasTriangles = function (context) { +Strip.prototype._renderCanvasTriangles = function (context) +{ // draw triangles!! var vertices = this.vertices; var uvs = this.uvs; @@ -247,14 +267,16 @@ var length = indices.length; // this.count++; - for (var i = 0; i < length; i += 3) { + for (var i = 0; i < length; i += 3) + { // draw some triangles! var index0 = indices[i] * 2, index1 = indices[i + 1] * 2, index2 = indices[i + 2] * 2; this._renderCanvasDrawTriangle(context, vertices, uvs, index0, index1, index2); } }; -Strip.prototype._renderCanvasDrawTriangle = function (context, vertices, uvs, index0, index1, index2) { +Strip.prototype._renderCanvasDrawTriangle = function (context, vertices, uvs, index0, index1, index2) +{ var textureSource = this.texture.baseTexture.source; var textureWidth = this.texture.width; var textureHeight = this.texture.height; @@ -265,7 +287,8 @@ var u0 = uvs[index0] * textureWidth, u1 = uvs[index1] * textureWidth, u2 = uvs[index2] * textureWidth; var v0 = uvs[index0 + 1] * textureHeight, v1 = uvs[index1 + 1] * textureHeight, v2 = uvs[index2 + 1] * textureHeight; - if (this.canvasPadding > 0) { + if (this.canvasPadding > 0) + { var paddingX = this.canvasPadding / this.worldTransform.a; var paddingY = this.canvasPadding / this.worldTransform.d; var centerX = (x0 + x1 + x2) / 3; @@ -332,7 +355,8 @@ * @param strip {Strip} The Strip to render * @private */ -Strip.prototype.renderStripFlat = function (strip) { +Strip.prototype.renderStripFlat = function (strip) +{ var context = this.context; var vertices = strip.vertices; @@ -340,7 +364,8 @@ // this.count++; context.beginPath(); - for (var i=1; i < length-2; i++) { + for (var i=1; i < length-2; i++) + { // draw some triangles! var index = i*2; @@ -358,7 +383,8 @@ }; /* -Strip.prototype.setTexture = function (texture) { +Strip.prototype.setTexture = function (texture) +{ //TODO SET THE TEXTURES //TODO VISIBILITY @@ -377,7 +403,8 @@ * @private */ -Strip.prototype.onTextureUpdate = function () { +Strip.prototype.onTextureUpdate = function () +{ this.updateFrame = true; }; @@ -387,7 +414,8 @@ * @param matrix {Matrix} the transformation matrix of the sprite * @return {Rectangle} the framing rectangle */ -Strip.prototype.getBounds = function (matrix) { +Strip.prototype.getBounds = function (matrix) +{ var worldTransform = matrix || this.worldTransform; var a = worldTransform.a; @@ -404,7 +432,8 @@ var minY = Infinity; var vertices = this.vertices; - for (var i = 0, n = vertices.length; i < n; i += 2) { + for (var i = 0, n = vertices.length; i < n; i += 2) + { var rawX = vertices[i], rawY = vertices[i + 1]; var x = (a * rawX) + (c * rawY) + tx; var y = (d * rawY) + (b * rawX) + ty; @@ -416,7 +445,8 @@ maxY = y > maxY ? y : maxY; } - if (minX === -Infinity || maxY === Infinity) { + if (minX === -Infinity || maxY === Infinity) + { return core.math.Rectangle.EMPTY; } diff --git a/src/extras/TilingSprite.js b/src/extras/TilingSprite.js index 3ac22df..31da393 100644 --- a/src/extras/TilingSprite.js +++ b/src/extras/TilingSprite.js @@ -10,7 +10,8 @@ * @param width {number} the width of the tiling sprite * @param height {number} the height of the tiling sprite */ -function TilingSprite(texture, width, height) { +function TilingSprite(texture, width, height) +{ core.Sprite.call( this, texture); /** @@ -86,10 +87,12 @@ * @memberof TilingSprite# */ width: { - get: function () { + get: function () + { return this._width; }, - set: function (value) { + set: function (value) + { this._width = value; } }, @@ -101,20 +104,25 @@ * @memberof TilingSprite# */ height: { - get: function () { + get: function () + { return this._height; }, - set: function (value) { + set: function (value) + { this._height = value; } }, texture: { - get: function () { + get: function () + { return this._texture; }, - set: function (value) { - if (this._texture === value) { + set: function (value) + { + if (this._texture === value) + { return; } @@ -130,51 +138,61 @@ * * @param renderer {WebGLRenderer} */ -TilingSprite.prototype.renderWebGL = function (renderer) { - if (!this.visible || this.alpha <= 0) { +TilingSprite.prototype.renderWebGL = function (renderer) +{ + if (!this.visible || this.alpha <= 0) + { return; } var i, j; - if (this._mask) { + if (this._mask) + { renderer.spriteBatch.stop(); renderer.maskManager.pushMask(this.mask, renderer); renderer.spriteBatch.start(); } - if (this._filters) { + if (this._filters) + { renderer.spriteBatch.flush(); renderer.filterManager.pushFilter(this._filterBlock); } - if (!this.tilingTexture || this.refreshTexture) { + if (!this.tilingTexture || this.refreshTexture) + { this.generateTilingTexture(true); - if (this.tilingTexture && this.tilingTexture.needsUpdate) { + if (this.tilingTexture && this.tilingTexture.needsUpdate) + { //TODO - tweaking renderer.updateTexture(this.tilingTexture.baseTexture); this.tilingTexture.needsUpdate = false; // this.tilingTexture._uvs = null; } } - else { + else + { renderer.spriteBatch.renderTilingSprite(this); } // simple render children! - for (i=0,j=this.children.length; i= 0 && index <= this.children.length) { - if (child.parent) { + if (index >= 0 && index <= this.children.length) + { + if (child.parent) + { child.parent.removeChild(child); } @@ -154,7 +173,8 @@ return child; } - else { + else + { throw new Error(child + 'addChildAt: The index '+ index +' supplied is out of bounds ' + this.children.length); } }; @@ -165,15 +185,18 @@ * @param child {DisplayObject} * @param child2 {DisplayObject} */ -DisplayObjectContainer.prototype.swapChildren = function (child, child2) { - if (child === child2) { +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) { + if (index1 < 0 || index2 < 0) + { throw new Error('swapChildren: Both the supplied DisplayObjects must be a child of the caller.'); } @@ -187,10 +210,12 @@ * @param child {DisplayObject} The DisplayObject instance to identify * @return {Number} The index position of the child display object to identify */ -DisplayObjectContainer.prototype.getChildIndex = function (child) { +DisplayObjectContainer.prototype.getChildIndex = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { throw new Error('The supplied DisplayObject must be a child of the caller'); } @@ -203,8 +228,10 @@ * @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 */ -DisplayObjectContainer.prototype.setChildIndex = function (child, index) { - if (index < 0 || index >= this.children.length) { +DisplayObjectContainer.prototype.setChildIndex = function (child, index) +{ + if (index < 0 || index >= this.children.length) + { throw new Error('The supplied index is out of bounds'); } @@ -220,8 +247,10 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child at the given index, if any. */ -DisplayObjectContainer.prototype.getChildAt = function (index) { - if (index < 0 || index >= this.children.length) { +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'); } @@ -234,10 +263,12 @@ * @param child {DisplayObject} The DisplayObject to remove * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChild = function (child) { +DisplayObjectContainer.prototype.removeChild = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { return; } @@ -250,7 +281,8 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChildAt = function (index) { +DisplayObjectContainer.prototype.removeChildAt = function (index) +{ var child = this.getChildAt(index); child.parent = null; @@ -265,24 +297,29 @@ * @param beginIndex {Number} The beginning position. Default value is 0. * @param endIndex {Number} The ending position. Default value is size of the container. */ -DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) { +DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) +{ var begin = beginIndex || 0; var end = typeof endIndex === 'number' ? endIndex : this.children.length; var range = end - begin; - if (range > 0 && range <= end) { + if (range > 0 && range <= end) + { var removed = this.children.splice(begin, range); - for (var i = 0; i < removed.length; ++i) { + for (var i = 0; i < removed.length; ++i) + { removed[i].parent = null; } return removed; } - else if (range === 0 && this.children.length === 0) { + else if (range === 0 && this.children.length === 0) + { return []; } - else { + else + { throw new RangeError('removeChildren: numeric values are outside the acceptable range.'); } }; @@ -291,7 +328,8 @@ * Generates and updates the cached sprite for this object. * */ -DisplayObjectContainer.prototype.updateCachedSprite = function () { +DisplayObjectContainer.prototype.updateCachedSprite = function () +{ this._generateCachedSprite(); }; @@ -304,7 +342,8 @@ * @param renderer {CanvasRenderer|WebGLRenderer} The renderer used to generate the texture. * @return {Texture} a texture of the graphics object */ -DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) { +DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) +{ var bounds = this.getLocalBounds(); var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0, renderer, scaleMode, resolution); @@ -322,18 +361,22 @@ * * @private */ -DisplayObjectContainer.prototype.updateTransform = function () { - if (!this.visible) { +DisplayObjectContainer.prototype.updateTransform = function () +{ + if (!this.visible) + { return; } this.displayObjectUpdateTransform(); - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { return; } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } }; @@ -346,8 +389,10 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getBounds = function () { - if (this.children.length === 0) { +DisplayObjectContainer.prototype.getBounds = function () +{ + if (this.children.length === 0) + { return math.Rectangle.EMPTY; } @@ -365,10 +410,12 @@ var childVisible = false; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -386,7 +433,8 @@ maxY = maxY > childMaxY ? maxY : childMaxY; } - if (!childVisible) { + if (!childVisible) + { return math.Rectangle.EMPTY; } @@ -407,12 +455,14 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getLocalBounds = function () { +DisplayObjectContainer.prototype.getLocalBounds = function () +{ var matrixCache = this.worldTransform; this.worldTransform = math.Matrix.IDENTITY; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } @@ -428,13 +478,16 @@ * * @param renderer {WebGLRenderer} The renderer */ -DisplayObjectContainer.prototype.renderWebGL = function (renderer) { +DisplayObjectContainer.prototype.renderWebGL = function (renderer) +{ // if the object is not visible or the alpha is 0 then no need to render this element - if (!this.visible || this.alpha <= 0) { + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } @@ -442,14 +495,17 @@ var i, j; // do a quick check to see if this element has a mask or a filter. - if (this._mask || this._filters) { + if (this._mask || this._filters) + { // push filter first as we need to ensure the stencil buffer is correct for any masking - if (this._filters) { + if (this._filters) + { renderer.spriteBatch.flush(); renderer.filterManager.pushFilter(this._filterBlock); } - if (this._mask) { + if (this._mask) + { renderer.spriteBatch.stop(); renderer.maskManager.pushMask(this.mask, renderer); renderer.spriteBatch.start(); @@ -459,36 +515,42 @@ this._renderWebGL(renderer); // now loop through the children and make sure they get rendered - for (i = 0, j = this.children.length; i < j; i++) { + for (i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderWebGL(renderer); } // time to stop the sprite batch as either a mask element or a filter draw will happen next renderer.spriteBatch.stop(); - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(this._mask, renderer); } - if (this._filters) { + if (this._filters) + { renderer.filterManager.popFilter(); } renderer.spriteBatch.start(); } - else { + else + { this._renderWebGL(renderer); // simple render children! - for (i = 0, j = this.children.length; i < j; ++i) { + for (i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderWebGL(renderer); } } }; -DisplayObjectContainer.prototype._renderWebGL = function (renderer) { +DisplayObjectContainer.prototype._renderWebGL = function (renderer) +{ // this is where content itself gets renderd.. @@ -499,25 +561,31 @@ * * @param renderer {CanvasRenderer} The renderer */ -DisplayObjectContainer.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0) { +DisplayObjectContainer.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -528,13 +596,16 @@ * @param renderer {WebGLRenderer|CanvasRenderer} The renderer * @private */ -DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) { +DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) +{ this._cachedSprite.worldAlpha = this.worldAlpha; - if (renderer.gl) { + if (renderer.gl) + { this._cachedSprite.renderWebGL(renderer); } - else { + else + { this._cachedSprite.renderCanvas(renderer); } }; @@ -544,10 +615,12 @@ * * @private */ -DisplayObjectContainer.prototype._generateCachedSprite = function () { +DisplayObjectContainer.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { // TODO - RenderTexture now *requires* a renderer instance, so this is like broken // because `renderer` isn't actually in scope here :P var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0); @@ -555,7 +628,8 @@ this._cachedSprite = new Sprite(renderTexture); this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.texture.resize(bounds.width | 0, bounds.height | 0); } @@ -580,8 +654,10 @@ * * @private */ -DisplayObjectContainer.prototype._destroyCachedSprite = function () { - if (!this._cachedSprite) { +DisplayObjectContainer.prototype._destroyCachedSprite = function () +{ + if (!this._cachedSprite) + { return; } diff --git a/src/core/display/Sprite.js b/src/core/display/Sprite.js index 707da24..5862aef 100644 --- a/src/core/display/Sprite.js +++ b/src/core/display/Sprite.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param texture {Texture} The texture for this sprite */ -function Sprite(texture) { +function Sprite(texture) +{ DisplayObjectContainer.call(this); /** @@ -85,12 +86,14 @@ this.texture = texture || Texture.EMPTY; } -Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) { +Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) +{ DisplayObjectContainer.prototype.destroy.call(this); this.anchor = null; - if (destroyTexture) { + if (destroyTexture) + { this._texture.destroy(destroyBaseTexture); } @@ -111,10 +114,12 @@ * @memberof Sprite# */ width: { - get: function () { + get: function () + { return this.scale.x * this.texture.frame.width; }, - set: function (value) { + set: function (value) + { this.scale.x = value / this.texture.frame.width; this._width = value; } @@ -127,10 +132,12 @@ * @memberof Sprite# */ height: { - get: function () { + get: function () + { return this.scale.y * this.texture.frame.height; }, - set: function (value) { + set: function (value) + { this.scale.y = value / this.texture.frame.height; this._height = value; } @@ -143,23 +150,29 @@ * @memberof Sprite# */ texture: { - get: function () { + get: function () + { return this._texture; }, - set: function (value) { - if (this._texture === value) { + set: function (value) + { + if (this._texture === value) + { return; } this._texture = value; this.cachedTint = 0xFFFFFF; - if (value) { + if (value) + { // wait for the texture to load - if (value.baseTexture.hasLoaded) { + if (value.baseTexture.hasLoaded) + { this._onTextureUpdate(); } - else { + else + { value.once('update', this._onTextureUpdate.bind(this)); } } @@ -172,18 +185,22 @@ * * @private */ -Sprite.prototype._onTextureUpdate = function () { +Sprite.prototype._onTextureUpdate = function () +{ // so if _width is 0 then width was not set.. - if (this._width) { + if (this._width) + { this.scale.x = this._width / this.texture.frame.width; } - if (this._height) { + if (this._height) + { this.scale.y = this._height / this.texture.frame.height; } }; -Sprite.prototype._renderWebGL = function (renderer) { +Sprite.prototype._renderWebGL = function (renderer) +{ // this is where content gets renderd.. // watch this space for a little render state manager.. @@ -197,7 +214,8 @@ * @param matrix {Matrix} the transformation matrix of the sprite * @return {Rectangle} the framing rectangle */ -Sprite.prototype.getBounds = function (matrix) { +Sprite.prototype.getBounds = function (matrix) +{ var width = this.texture.frame.width; var height = this.texture.frame.height; @@ -224,11 +242,13 @@ if(b === 0 && c === 0) { // scale may be negative! - if (a < 0) { + if (a < 0) + { a *= -1; } - if (d < 0) { + if (d < 0) + { d *= -1; } @@ -293,28 +313,34 @@ * * @param renderer {CanvasRenderer} The renderer */ -Sprite.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) { +Sprite.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) + { return; } - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; renderer.context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } // Ignore null sources - if (this.texture.valid) { + if (this.texture.valid) + { var resolution = this.texture.baseTexture.resolution / renderer.resolution; renderer.context.globalAlpha = this.worldAlpha; // If smoothingEnabled is supported and we need to change the smoothing property for this texture - if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) { + if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) + { renderer.scaleMode = this.texture.baseTexture.scaleMode; renderer.context[renderer.smoothProperty] = (renderer.scaleMode === CONST.scaleModes.LINEAR); } @@ -324,7 +350,8 @@ var dy = (this.texture.trim ? this.texture.trim.y : 0) - (this.anchor.y * this.texture.trim.height); // Allow for pixel rounding - if (renderer.roundPixels) { + if (renderer.roundPixels) + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -337,7 +364,8 @@ dx = dx | 0; dy = dy | 0; } - else { + else + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -348,8 +376,10 @@ ); } - if (this.tint !== 0xFFFFFF) { - if (this.cachedTint !== this.tint) { + if (this.tint !== 0xFFFFFF) + { + if (this.cachedTint !== this.tint) + { this.cachedTint = this.tint; // TODO clean up caching - how to clean up the caches? @@ -368,7 +398,8 @@ this.texture.crop.height / resolution ); } - else { + else + { renderer.context.drawImage( this.texture.baseTexture.source, this.texture.crop.x, @@ -383,11 +414,13 @@ } } - for (var i = 0, j = this.children.length; i < j; i++) { + for (var i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -402,10 +435,12 @@ * @param frameId {String} The frame Id of the texture in the cache * @return {Sprite} A new Sprite using a texture from the texture cache matching the frameId */ -Sprite.fromFrame = function (frameId) { +Sprite.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache' + this); } @@ -420,6 +455,7 @@ * @param imageId {String} The image url of the texture * @return {Sprite} A new Sprite using a texture from the texture cache matching the image id */ -Sprite.fromImage = function (imageId, crossorigin, scaleMode) { +Sprite.fromImage = function (imageId, crossorigin, scaleMode) +{ return new Sprite(Texture.fromImage(imageId, crossorigin, scaleMode)); }; diff --git a/src/core/display/SpriteBatch.js b/src/core/display/SpriteBatch.js index 3187777..c196fef 100644 --- a/src/core/display/SpriteBatch.js +++ b/src/core/display/SpriteBatch.js @@ -12,7 +12,8 @@ * ```js * var container = new SpriteBatch(); * - * for(var i = 0; i < 100; ++i) { + * for(var i = 0; i < 100; ++i) + * { * var sprite = new PIXI.Sprite.fromImage("myImage.png"); * container.addChild(sprite); * } @@ -25,7 +26,8 @@ */ //TODO RENAME to PARTICLE CONTAINER? -function SpriteBatch() { +function SpriteBatch() +{ DisplayObjectContainer.call(this); } @@ -38,7 +40,8 @@ * * @private */ -SpriteBatch.prototype.updateTransform = function () { +SpriteBatch.prototype.updateTransform = function () +{ // TODO don't need to! this.displayObjectUpdateTransform(); // PIXI.DisplayObjectContainer.prototype.updateTransform.call( this ); @@ -50,8 +53,10 @@ * @param renderer {WebGLRenderer} The webgl renderer * @private */ -SpriteBatch.prototype.renderWebGL = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderWebGL = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -71,8 +76,10 @@ * @param renderer {CanvasRenderer} The canvas renderer * @private */ -SpriteBatch.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -84,10 +91,12 @@ this.displayObjectUpdateTransform(); - for (var i = 0; i < this.children.length; ++i) { + for (var i = 0; i < this.children.length; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -95,9 +104,11 @@ context.globalAlpha = this.worldAlpha * child.alpha; - if (child.rotation % (Math.PI * 2) === 0) { + if (child.rotation % (Math.PI * 2) === 0) + { // this is the fastest way to optimise! - if rotation is 0 then we can avoid any kind of setTransform call - if (isRotated) { + if (isRotated) + { context.setTransform( transform.a, transform.b, @@ -122,8 +133,10 @@ frame.height * child.scale.y ); } - else { - if (!isRotated) { + else + { + if (!isRotated) + { isRotated = true; } @@ -131,7 +144,8 @@ var childTransform = child.worldTransform; - if (renderer.roundPixels) { + if (renderer.roundPixels) + { context.setTransform( childTransform.a, childTransform.b, @@ -141,7 +155,8 @@ childTransform.ty | 0 ); } - else { + else + { context.setTransform( childTransform.a, childTransform.b, diff --git a/src/core/index.js b/src/core/index.js index 3954b6f..eb4a82b 100644 --- a/src/core/index.js +++ b/src/core/index.js @@ -58,11 +58,13 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRenderer: function (width, height, options, noWebGL) { + autoDetectRenderer: function (width, height, options, noWebGL) + { width = width || 800; height = height || 600; - if (!noWebGL && require('webgl-enabled')()) { + if (!noWebGL && require('webgl-enabled')()) + { return new core.WebGLRenderer(width, height, options); } @@ -87,7 +89,8 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRecommendedRenderer: function (width, height, options) { + autoDetectRecommendedRenderer: function (width, height, options) + { var isAndroid = /Android/i.test(navigator.userAgent); return core.autoDetectRenderer(width, height, options, isAndroid); diff --git a/src/core/math/Matrix.js b/src/core/math/Matrix.js index c2f87e2..2ff4848 100644 --- a/src/core/math/Matrix.js +++ b/src/core/math/Matrix.js @@ -10,7 +10,8 @@ * @class * @namespace PIXI */ -function Matrix() { +function Matrix() +{ /** * @member {number} * @default 1 @@ -63,7 +64,8 @@ * * @param array {number[]} The array that the matrix will be populated from. */ -Matrix.prototype.fromArray = function (array) { +Matrix.prototype.fromArray = function (array) +{ this.a = array[0]; this.b = array[1]; this.c = array[3]; @@ -78,14 +80,17 @@ * @param transpose {boolean} Whether we need to transpose the matrix or not * @return {number[]} the newly created array which contains the matrix */ -Matrix.prototype.toArray = function (transpose) { - if (!this.array) { +Matrix.prototype.toArray = function (transpose) +{ + if (!this.array) + { this.array = new Float32Array(9); } var array = this.array; - if (transpose) { + if (transpose) + { array[0] = this.a; array[1] = this.b; array[2] = 0; @@ -96,7 +101,8 @@ array[7] = this.ty; array[8] = 1; } - else { + else + { array[0] = this.a; array[1] = this.c; array[2] = this.tx; @@ -119,7 +125,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, transformed through this matrix */ -Matrix.prototype.apply = function (pos, newPos) { +Matrix.prototype.apply = function (pos, newPos) +{ newPos = newPos || new Point(); newPos.x = this.a * pos.x + this.c * pos.y + this.tx; @@ -136,7 +143,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, inverse-transformed through this matrix */ -Matrix.prototype.applyInverse = function (pos, newPos) { +Matrix.prototype.applyInverse = function (pos, newPos) +{ newPos = newPos || new Point(); var id = 1 / (this.a * this.d + this.c * -this.b); @@ -154,7 +162,8 @@ * @param {number} y * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.translate = function (x, y) { +Matrix.prototype.translate = function (x, y) +{ this.tx += x; this.ty += y; @@ -168,7 +177,8 @@ * @param {number} y The amount to scale vertically * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.scale = function (x, y) { +Matrix.prototype.scale = function (x, y) +{ this.a *= x; this.d *= y; this.c *= x; @@ -186,7 +196,8 @@ * @param {number} angle - The angle in radians. * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.rotate = function (angle) { +Matrix.prototype.rotate = function (angle) +{ var cos = Math.cos( angle ); var sin = Math.sin( angle ); @@ -210,7 +221,8 @@ * @param {Matrix} matrix * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.append = function (matrix) { +Matrix.prototype.append = function (matrix) +{ var a1 = this.a; var b1 = this.b; var c1 = this.c; @@ -232,7 +244,8 @@ * * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.identity = function () { +Matrix.prototype.identity = function () +{ this.a = 1; this.b = 0; this.c = 0; diff --git a/src/core/math/Point.js b/src/core/math/Point.js index 7565b2d..632f346 100644 --- a/src/core/math/Point.js +++ b/src/core/math/Point.js @@ -7,7 +7,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -function Point(x, y) { +function Point(x, y) +{ /** * @member {number} * @default 0 @@ -29,7 +30,8 @@ * * @return {Point} a copy of the point */ -Point.prototype.clone = function () { +Point.prototype.clone = function () +{ return new Point(this.x, this.y); }; @@ -40,7 +42,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -Point.prototype.set = function (x, y) { +Point.prototype.set = function (x, y) +{ this.x = x || 0; this.y = y || ( (y !== 0) ? this.x : 0 ) ; }; diff --git a/src/core/math/shapes/Circle.js b/src/core/math/shapes/Circle.js index 69cfdc9..4d76efc 100644 --- a/src/core/math/shapes/Circle.js +++ b/src/core/math/shapes/Circle.js @@ -10,7 +10,8 @@ * @param y {number} The Y coordinate of the center of this circle * @param radius {number} The radius of the circle */ -function Circle(x, y, radius) { +function Circle(x, y, radius) +{ /** * @member {number} * @default 0 @@ -46,7 +47,8 @@ * @method clone * @return {Circle} a copy of the Circle */ -Circle.prototype.clone = function () { +Circle.prototype.clone = function () +{ return new Circle(this.x, this.y, this.radius); }; @@ -58,8 +60,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Circle */ -Circle.prototype.contains = function (x, y) { - if (this.radius <= 0) { +Circle.prototype.contains = function (x, y) +{ + if (this.radius <= 0) + { return false; } @@ -79,6 +83,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Circle.prototype.getBounds = function () { +Circle.prototype.getBounds = function () +{ return new Rectangle(this.x - this.radius, this.y - this.radius, this.radius * 2, this.radius * 2); }; diff --git a/src/core/math/shapes/Ellipse.js b/src/core/math/shapes/Ellipse.js index 4f2d066..fefd01a 100644 --- a/src/core/math/shapes/Ellipse.js +++ b/src/core/math/shapes/Ellipse.js @@ -11,7 +11,8 @@ * @param width {number} The half width of this ellipse * @param height {number} The half height of this ellipse */ -function Ellipse(x, y, width, height) { +function Ellipse(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -53,7 +54,8 @@ * @method clone * @return {Ellipse} a copy of the ellipse */ -Ellipse.prototype.clone = function () { +Ellipse.prototype.clone = function () +{ return new Ellipse(this.x, this.y, this.width, this.height); }; @@ -65,8 +67,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coords are within this ellipse */ -Ellipse.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Ellipse.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } @@ -86,6 +90,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Ellipse.prototype.getBounds = function () { +Ellipse.prototype.getBounds = function () +{ return new Rectangle(this.x - this.width, this.y - this.height, this.width, this.height); }; diff --git a/src/core/math/shapes/Polygon.js b/src/core/math/shapes/Polygon.js index ae89148..fea6d37 100644 --- a/src/core/math/shapes/Polygon.js +++ b/src/core/math/shapes/Polygon.js @@ -10,16 +10,20 @@ * arguments passed can be flat x,y values e.g. `new Polygon(x,y, x,y, x,y, ...)` where `x` and `y` are * Numbers. */ -function Polygon(points) { +function Polygon(points) +{ //if points isn't an array, use arguments as the array - if (!(points instanceof Array)) { + if (!(points instanceof Array)) + { points = Array.prototype.slice.call(arguments); } //if this is a flat array of numbers, convert it to points - if (points[0] instanceof Point) { + if (points[0] instanceof Point) + { var p = []; - for (var i = 0, il = points.length; i < il; i++) { + for (var i = 0, il = points.length; i < il; i++) + { p.push(points[i].x, points[i].y); } @@ -51,7 +55,8 @@ * * @return {Polygon} a copy of the polygon */ -Polygon.prototype.clone = function () { +Polygon.prototype.clone = function () +{ return new Polygon(this.points.slice()); }; @@ -62,19 +67,22 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this polygon */ -Polygon.prototype.contains = function (x, y) { +Polygon.prototype.contains = function (x, y) +{ var inside = false; // use some raycasting to test hits // https://github.com/substack/point-in-polygon/blob/master/index.js var length = this.points.length / 2; - for (var i = 0, j = length - 1; i < length; j = i++) { + for (var i = 0, j = length - 1; i < length; j = i++) + { var xi = this.points[i * 2], yi = this.points[i * 2 + 1], xj = this.points[j * 2], yj = this.points[j * 2 + 1], intersect = ((yi > y) !== (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi); - if (intersect) { + if (intersect) + { inside = !inside; } } diff --git a/src/core/math/shapes/Rectangle.js b/src/core/math/shapes/Rectangle.js index 16ac62a..4008b68 100644 --- a/src/core/math/shapes/Rectangle.js +++ b/src/core/math/shapes/Rectangle.js @@ -10,7 +10,8 @@ * @param width {number} The overall width of this rectangle * @param height {number} The overall height of this rectangle */ -function Rectangle(x, y, width, height) { +function Rectangle(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -60,7 +61,8 @@ * * @return {Rectangle} a copy of the rectangle */ -Rectangle.prototype.clone = function () { +Rectangle.prototype.clone = function () +{ return new Rectangle(this.x, this.y, this.width, this.height); }; @@ -71,13 +73,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rectangle */ -Rectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Rectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/math/shapes/RoundedRectangle.js b/src/core/math/shapes/RoundedRectangle.js index 27d286e..7bf6411 100644 --- a/src/core/math/shapes/RoundedRectangle.js +++ b/src/core/math/shapes/RoundedRectangle.js @@ -11,7 +11,8 @@ * @param height {number} The overall height of this rounded rectangle * @param radius {number} Controls the radius of the rounded corners */ -function RoundedRectangle(x, y, width, height, radius) { +function RoundedRectangle(x, y, width, height, radius) +{ /** * @member {number} * @default 0 @@ -58,7 +59,8 @@ * * @return {RoundedRectangle} a copy of the rounded rectangle */ -RoundedRectangle.prototype.clone = function () { +RoundedRectangle.prototype.clone = function () +{ return new RoundedRectangle(this.x, this.y, this.width, this.height, this.radius); }; @@ -69,13 +71,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rounded Rectangle */ -RoundedRectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +RoundedRectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/primitives/Graphics.js b/src/core/primitives/Graphics.js index 261c534..e902d2a 100644 --- a/src/core/primitives/Graphics.js +++ b/src/core/primitives/Graphics.js @@ -16,7 +16,8 @@ * @extends DisplayObjectContainer * @namespace PIXI */ -function Graphics() { +function Graphics() +{ DisplayObjectContainer.call(this); this.renderable = true; @@ -154,16 +155,20 @@ * @private */ cacheAsBitmap: { - get: function () { + get: function () + { return this._cacheAsBitmap; }, - set: function (value) { + set: function (value) + { this._cacheAsBitmap = value; - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._generateCachedSprite(); } - else { + else + { this.destroyCachedSprite(); this.dirty = true; } @@ -176,7 +181,8 @@ * * @return {Graphics} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ var clone = new Graphics(); clone.renderable = this.renderable; @@ -192,7 +198,8 @@ clone.cachedSpriteDirty = this.cachedSpriteDirty; // copy graphics data - for (var i = 0; i < this.graphicsData.length; ++i) { + for (var i = 0; i < this.graphicsData.length; ++i) + { clone.graphicsData.push(this.graphicsData.clone()); } @@ -211,17 +218,21 @@ * @param alpha {number} alpha of the line to draw, will update the objects stored style * @return {Graphics} */ -Graphics.prototype.lineStyle = function (lineWidth, color, alpha) { +Graphics.prototype.lineStyle = function (lineWidth, color, alpha) +{ this.lineWidth = lineWidth || 0; this.lineColor = color || 0; this.lineAlpha = (arguments.length < 3) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length) + { // halfway through a line? start a new one! this.drawShape( new math.Polygon( this.currentPath.shape.points.slice(-2) )); } - else { + else + { // otherwise its empty so lets just set the line properties this.currentPath.lineWidth = this.lineWidth; this.currentPath.lineColor = this.lineColor; @@ -239,7 +250,8 @@ * @param y {number} the Y coordinate to move to * @return {Graphics} */ -Graphics.prototype.moveTo = function (x, y) { +Graphics.prototype.moveTo = function (x, y) +{ this.drawShape(new math.Polygon([x,y])); return this; @@ -253,7 +265,8 @@ * @param y {number} the Y coordinate to draw to * @return {Graphics} */ -Graphics.prototype.lineTo = function (x, y) { +Graphics.prototype.lineTo = function (x, y) +{ this.currentPath.shape.points.push(x, y); this.dirty = true; @@ -270,13 +283,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -285,7 +302,8 @@ n = 20, points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { this.moveTo(0, 0); } @@ -293,7 +311,8 @@ var fromY = points[points.length-1]; var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; xa = fromX + ( (cpX - fromX) * j ); @@ -319,13 +338,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -342,7 +365,8 @@ var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; dt = (1 - j); @@ -373,13 +397,17 @@ * @param radius {number} The radius of the arc * @return {Graphics} */ -Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points.push(x1, y1); } } - else { + else + { this.moveTo(x1, y1); } @@ -392,12 +420,15 @@ b2 = x2 - x1, mm = Math.abs(a1 * b2 - b1 * a2); - if (mm < 1.0e-8 || radius === 0) { - if (points[points.length-2] !== x1 || points[points.length-1] !== y1) { + if (mm < 1.0e-8 || radius === 0) + { + if (points[points.length-2] !== x1 || points[points.length-1] !== y1) + { points.push(x1, y1); } } - else { + else + { var dd = a1 * a1 + b1 * b1, cc = a2 * a2 + b2 * b2, tt = a1 * a2 + b1 * b2, @@ -433,42 +464,51 @@ * @param anticlockwise {boolean} Optional. Specifies whether the drawing should be counterclockwise or clockwise. False is default, and indicates clockwise, while true indicates counter-clockwise. * @return {Graphics} */ -Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) { +Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) +{ var startX = cx + Math.cos(startAngle) * radius; var startY = cy + Math.sin(startAngle) * radius; var points; // TODO - This if-else makes no sense. It uses currentPath in the else where it doesn't exist... - if (this.currentPath) { + if (this.currentPath) + { points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { points.push(startX, startY); } - else if (points[points.length-2] !== startX || points[points.length-1] !== startY) { + else if (points[points.length-2] !== startX || points[points.length-1] !== startY) + { points.push(startX, startY); } } - else { + else + { this.moveTo(startX, startY); points = this.currentPath.shape.points; } - if (startAngle === endAngle) { + if (startAngle === endAngle) + { return this; } - if (!anticlockwise && endAngle <= startAngle) { + if (!anticlockwise && endAngle <= startAngle) + { endAngle += Math.PI * 2; } - else if (anticlockwise && startAngle <= endAngle) { + else if (anticlockwise && startAngle <= endAngle) + { startAngle += Math.PI * 2; } var sweep = anticlockwise ? (startAngle - endAngle) *-1 : (endAngle - startAngle); var segs = (Math.abs(sweep)/ (Math.PI * 2)) * 40; - if (sweep === 0) { + if (sweep === 0) + { return this; } @@ -482,7 +522,8 @@ var remainder = ( segMinus % 1 ) / segMinus; - for (var i = 0; i <= segMinus; ++i) { + for (var i = 0; i <= segMinus; ++i) + { var real = i + remainder * i; var angle = ((theta) + startAngle + (theta2 * real)); @@ -506,13 +547,16 @@ * @param alpha {number} the alpha of the fill * @return {Graphics} */ -Graphics.prototype.beginFill = function (color, alpha) { +Graphics.prototype.beginFill = function (color, alpha) +{ this.filling = true; this.fillColor = color || 0; this.fillAlpha = (alpha === undefined) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length <= 2) + { this.currentPath.fill = this.filling; this.currentPath.fillColor = this.fillColor; this.currentPath.fillAlpha = this.fillAlpha; @@ -526,7 +570,8 @@ * * @return {Graphics} */ -Graphics.prototype.endFill = function () { +Graphics.prototype.endFill = function () +{ this.filling = false; this.fillColor = null; this.fillAlpha = 1; @@ -542,7 +587,8 @@ * @param height {number} The height of the rectangle * @return {Graphics} */ -Graphics.prototype.drawRect = function ( x, y, width, height ) { +Graphics.prototype.drawRect = function ( x, y, width, height ) +{ this.drawShape(new math.Rectangle(x,y, width, height)); return this; @@ -556,7 +602,8 @@ * @param height {number} The height of the rectangle * @param radius {number} Radius of the rectangle corners */ -Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) { +Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) +{ this.drawShape(new math.RoundedRectangle(x, y, width, height, radius)); return this; @@ -570,7 +617,8 @@ * @param radius {number} The radius of the circle * @return {Graphics} */ -Graphics.prototype.drawCircle = function (x, y, radius) { +Graphics.prototype.drawCircle = function (x, y, radius) +{ this.drawShape(new math.Circle(x,y, radius)); return this; @@ -585,7 +633,8 @@ * @param height {number} The half height of the ellipse * @return {Graphics} */ -Graphics.prototype.drawEllipse = function (x, y, width, height) { +Graphics.prototype.drawEllipse = function (x, y, width, height) +{ this.drawShape(new math.Ellipse(x, y, width, height)); return this; @@ -597,8 +646,10 @@ * @param path {Array} The path data used to construct the polygon. * @return {Graphics} */ -Graphics.prototype.drawPolygon = function (path) { - if (!(path instanceof Array)) { +Graphics.prototype.drawPolygon = function (path) +{ + if (!(path instanceof Array)) + { path = Array.prototype.slice.call(arguments); } @@ -612,7 +663,8 @@ * * @return {Graphics} */ -Graphics.prototype.clear = function () { +Graphics.prototype.clear = function () +{ this.lineWidth = 0; this.filling = false; @@ -631,7 +683,8 @@ * @param scaleMode {number} Should be one of the scaleMode consts * @return {Texture} a texture of the graphics object */ -Graphics.prototype.generateTexture = function (resolution, scaleMode) { +Graphics.prototype.generateTexture = function (resolution, scaleMode) +{ resolution = resolution || 1; var bounds = this.getBounds(); @@ -655,17 +708,21 @@ * * @param renderer {WebGLRenderer} */ -Graphics.prototype._renderWebGL = function (renderer) { +Graphics.prototype._renderWebGL = function (renderer) +{ // if the sprite is not visible or the alpha is 0 then no need to render this element - if (this.isMask === true) { + if (this.isMask === true) + { return; } // this code may still be needed so leaving for now.. - // + // /* - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture on the gpu too! @@ -681,17 +738,24 @@ return; } - */ - - // check if the webgl graphic needs to be updated - if (this.glDirty) { - this.dirty = true; - this.glDirty = false; - } + else */ - renderer.setObjectRendererer(renderer.graphicsRenderer); - renderer.graphicsRenderer.render(this); + renderer.spriteBatch.stop(); + renderer.blendModeManager.setBlendMode(this.blendMode); + // check blend mode + renderer.blendModeManager.setBlendMode( this.blendMode ); + + // check if the webgl graphic needs to be updated + if (this.glDirty) + { + this.dirty = true; + this.glDirty = false; + } + + WebGLGraphics.renderGraphics(this, renderer); + + renderer.spriteBatch.start(); }; /** @@ -700,14 +764,18 @@ * @param renderer {CanvasRenderer} * @private */ -Graphics.prototype.renderCanvas = function (renderer) { +Graphics.prototype.renderCanvas = function (renderer) +{ // 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.isMask === true) { + if (!this.visible || this.alpha <= 0 || this.isMask === true) + { return; } - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture @@ -723,16 +791,19 @@ return; } - else { + else + { var context = renderer.context; var transform = this.worldTransform; - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } @@ -748,11 +819,13 @@ CanvasGraphics.renderGraphics(this, context); - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } } @@ -763,13 +836,16 @@ * * @return {Rectangle} the rectangular bounding area */ -Graphics.prototype.getBounds = function (matrix) { +Graphics.prototype.getBounds = function (matrix) +{ // return an empty object if the item is a mask! - if (this.isMask) { + if (this.isMask) + { return math.Rectangle.EMPTY; } - if (this.dirty) { + if (this.dirty) + { this.updateLocalBounds(); this.glDirty = true; @@ -841,23 +917,27 @@ * Update the bounds of the object * */ -Graphics.prototype.updateLocalBounds = function () { +Graphics.prototype.updateLocalBounds = function () +{ var minX = Infinity; var maxX = -Infinity; var minY = Infinity; var maxY = -Infinity; - if (this.graphicsData.length) { + if (this.graphicsData.length) + { var shape, points, x, y, w, h; - for (var i = 0; i < this.graphicsData.length; i++) { + for (var i = 0; i < this.graphicsData.length; i++) + { var data = this.graphicsData[i]; var type = data.type; var lineWidth = data.lineWidth; shape = data.shape; - if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) { + if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) + { x = shape.x - lineWidth/2; y = shape.y - lineWidth/2; w = shape.width + lineWidth; @@ -869,7 +949,8 @@ minY = y < minY ? y : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.CIRC) { + else if (type === CONST.SHAPES.CIRC) + { x = shape.x; y = shape.y; w = shape.radius + lineWidth/2; @@ -881,7 +962,8 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.ELIP) { + else if (type === CONST.SHAPES.ELIP) + { x = shape.x; y = shape.y; w = shape.width + lineWidth/2; @@ -893,11 +975,13 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else { + else + { // POLY points = shape.points; - for (var j = 0; j < points.length; j += 2) { + for (var j = 0; j < points.length; j += 2) + { x = points[j]; y = points[j+1]; @@ -910,7 +994,8 @@ } } } - else { + else + { minX = 0; maxX = 0; minY = 0; @@ -931,10 +1016,12 @@ * * @private */ -Graphics.prototype._generateCachedSprite = function () { +Graphics.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { var canvasBuffer = new CanvasBuffer(bounds.width, bounds.height); var texture = Texture.fromCanvas(canvasBuffer.canvas); @@ -943,7 +1030,8 @@ this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.buffer.resize(bounds.width, bounds.height); } @@ -968,7 +1056,8 @@ * * @private */ -Graphics.prototype.updateCachedSpriteTexture = function () { +Graphics.prototype.updateCachedSpriteTexture = function () +{ var cachedSprite = this._cachedSprite; var texture = cachedSprite.texture; var canvas = cachedSprite.buffer.canvas; @@ -989,7 +1078,8 @@ * Destroys a previous cached sprite. * */ -Graphics.prototype.destroyCachedSprite = function () { +Graphics.prototype.destroyCachedSprite = function () +{ this._cachedSprite.texture.destroy(true); // let the gc collect the unused sprite @@ -1003,10 +1093,13 @@ * @param {Circle|Rectangle|Ellipse|Line|Polygon} shape The Shape object to draw. * @return {GraphicsData} The generated GraphicsData object. */ -Graphics.prototype.drawShape = function (shape) { - if (this.currentPath) { +Graphics.prototype.drawShape = function (shape) +{ + if (this.currentPath) + { // check current path! - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath.shape.points.length <= 2) + { this.graphicsData.pop(); } } @@ -1017,7 +1110,8 @@ this.graphicsData.push(data); - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { data.shape.closed = this.filling; this.currentPath = data; } diff --git a/src/core/primitives/GraphicsData.js b/src/core/primitives/GraphicsData.js index 99decbe..788f6f2 100644 --- a/src/core/primitives/GraphicsData.js +++ b/src/core/primitives/GraphicsData.js @@ -4,7 +4,8 @@ * @class * @namespace PIXI */ -function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) { +function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) +{ this.lineWidth = lineWidth; this.lineColor = lineColor; this.lineAlpha = lineAlpha; @@ -27,7 +28,8 @@ * * @return {GraphicsData} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ return new GraphicsData( this.lineWidth, this.lineColor, diff --git a/src/core/renderers/canvas/CanvasRenderer.js b/src/core/renderers/canvas/CanvasRenderer.js index 15a0978..7aebd44 100644 --- a/src/core/renderers/canvas/CanvasRenderer.js +++ b/src/core/renderers/canvas/CanvasRenderer.js @@ -17,17 +17,22 @@ * @param [options.resolution=1] {number} the resolution of the renderer retina would be 2 * @param [options.clearBeforeRender=true] {boolean} This sets if the CanvasRenderer will clear the canvas or not before the new render pass. */ -function CanvasRenderer(width, height, options) { +function CanvasRenderer(width, height, options) +{ utils.sayHello('Canvas'); - if (options) { - for (var i in CONST.defaultRenderOptions) { - if (typeof options[i] === 'undefined') { + if (options) + { + for (var i in CONST.defaultRenderOptions) + { + if (typeof options[i] === 'undefined') + { options[i] = CONST.defaultRenderOptions[i]; } } } - else { + else + { options = CONST.defaultRenderOptions; } @@ -156,19 +161,24 @@ this.smoothProperty = null; - if (this.context.imageSmoothingEnabled) { + if (this.context.imageSmoothingEnabled) + { this.smoothProperty = 'imageSmoothingEnabled'; } - else if (this.context.webkitImageSmoothingEnabled) { + else if (this.context.webkitImageSmoothingEnabled) + { this.smoothProperty = 'webkitImageSmoothingEnabled'; } - else if (this.context.mozImageSmoothingEnabled) { + else if (this.context.mozImageSmoothingEnabled) + { this.smoothProperty = 'mozImageSmoothingEnabled'; } - else if (this.context.oImageSmoothingEnabled) { + else if (this.context.oImageSmoothingEnabled) + { this.smoothProperty = 'oImageSmoothingEnabled'; } - else if (this.context.msImageSmoothingEnabled) { + else if (this.context.msImageSmoothingEnabled) + { this.smoothProperty = 'msImageSmoothingEnabled'; } @@ -193,10 +203,12 @@ * @memberof CanvasRenderer# */ backgroundColor: { - get: function () { + get: function () + { return this._backgroundColor; }, - set: function (val) { + set: function (val) + { this._backgroundColor = val; this._backgroundColorString = utils.hex2string(val); } @@ -208,7 +220,8 @@ * * @param object {DisplayObject} the object to be rendered */ -CanvasRenderer.prototype.render = function (object) { +CanvasRenderer.prototype.render = function (object) +{ object.updateTransform(); this.context.setTransform(1,0,0,1,0,0); @@ -218,16 +231,20 @@ this.currentBlendMode = CONST.blendModes.NORMAL; this.context.globalCompositeOperation = this.blendModes[CONST.blendModes.NORMAL]; - if (navigator.isCocoonJS && this.view.screencanvas) { + if (navigator.isCocoonJS && this.view.screencanvas) + { this.context.fillStyle = 'black'; this.context.clear(); } - if (this.clearBeforeRender) { - if (this.transparent) { + if (this.clearBeforeRender) + { + if (this.transparent) + { this.context.clearRect(0, 0, this.width, this.height); } - else { + else + { this.context.fillStyle = this._backgroundColorString; this.context.fillRect(0, 0, this.width , this.height); } @@ -241,8 +258,10 @@ * * @param [removeView=false] {boolean} Removes the Canvas element from the DOM. */ -CanvasRenderer.prototype.destroy = function (removeView) { - if (removeView && this.view.parent) { +CanvasRenderer.prototype.destroy = function (removeView) +{ + if (removeView && this.view.parent) + { this.view.parent.removeChild(this.view); } @@ -257,14 +276,16 @@ * @param width {number} the new width of the canvas view * @param height {number} the new height of the canvas view */ -CanvasRenderer.prototype.resize = function (width, height) { +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) { + if (this.autoResize) + { this.view.style.width = this.width / this.resolution + 'px'; this.view.style.height = this.height / this.resolution + 'px'; } @@ -276,7 +297,8 @@ * @param displayObject {DisplayObject} The displayObject to render * @private */ -CanvasRenderer.prototype.renderDisplayObject = function (displayObject) { +CanvasRenderer.prototype.renderDisplayObject = function (displayObject) +{ displayObject.renderCanvas(this); }; @@ -285,11 +307,14 @@ * * @private */ -CanvasRenderer.prototype._mapBlendModes = function () { - if (!this.blendModes) { +CanvasRenderer.prototype._mapBlendModes = function () +{ + if (!this.blendModes) + { this.blendModes = {}; - if (utils.canUseNewCanvasBlendModes()) { + if (utils.canUseNewCanvasBlendModes()) + { this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? this.blendModes[CONST.blendModes.MULTIPLY] = 'multiply'; @@ -308,7 +333,8 @@ this.blendModes[CONST.blendModes.COLOR] = 'color'; this.blendModes[CONST.blendModes.LUMINOSITY] = 'luminosity'; } - else { + else + { // this means that the browser does not support the cool new blend modes in canvas 'cough' ie 'cough' this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? diff --git a/src/core/renderers/canvas/utils/CanvasBuffer.js b/src/core/renderers/canvas/utils/CanvasBuffer.js index ebe5d47..b183a66 100644 --- a/src/core/renderers/canvas/utils/CanvasBuffer.js +++ b/src/core/renderers/canvas/utils/CanvasBuffer.js @@ -6,7 +6,8 @@ * @param width {number} the width for the newly created canvas * @param height {number} the height for the newly created canvas */ -function CanvasBuffer(width, height) { +function CanvasBuffer(width, height) +{ /** * The Canvas object that belongs to this CanvasBuffer. * @@ -36,10 +37,12 @@ * @memberof CanvasBuffer# */ width: { - get: function () { + get: function () + { return this.canvas.width; }, - set: function (val) { + set: function (val) + { this.canvas.width = val; } }, @@ -50,10 +53,12 @@ * @memberof CanvasBuffer# */ height: { - get: function () { + get: function () + { return this.canvas.height; }, - set: function (val) { + set: function (val) + { this.canvas.height = val; } } @@ -64,7 +69,8 @@ * * @private */ -CanvasBuffer.prototype.clear = function () { +CanvasBuffer.prototype.clear = function () +{ this.context.setTransform(1, 0, 0, 1, 0, 0); this.context.clearRect(0,0, this.canvas.width, this.canvas.height); }; @@ -75,7 +81,8 @@ * @param width {number} the new width of the canvas * @param height {number} the new height of the canvas */ -CanvasBuffer.prototype.resize = function (width, height) { +CanvasBuffer.prototype.resize = function (width, height) +{ this.canvas.width = width; this.canvas.height = height; }; diff --git a/src/core/renderers/canvas/utils/CanvasGraphics.js b/src/core/renderers/canvas/utils/CanvasGraphics.js index c7eaa2a..3f2a91f 100644 --- a/src/core/renderers/canvas/utils/CanvasGraphics.js +++ b/src/core/renderers/canvas/utils/CanvasGraphics.js @@ -13,15 +13,18 @@ * @param graphics {Graphics} the actual graphics object to render * @param context {CanvasRenderingContext2D} the 2d drawing method of the canvas */ -CanvasGraphics.renderGraphics = function (graphics, context) { +CanvasGraphics.renderGraphics = function (graphics, context) +{ var worldAlpha = graphics.worldAlpha; - if (graphics.dirty) { + if (graphics.dirty) + { this.updateGraphicsTint(graphics); graphics.dirty = false; } - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; @@ -30,69 +33,82 @@ context.lineWidth = data.lineWidth; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { context.beginPath(); var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } - if (shape.closed) { + if (shape.closed) + { context.lineTo(points[0], points[1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fillRect(shape.x, shape.y, shape.width, shape.height); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.strokeRect(shape.x, shape.y, shape.width, shape.height); } } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.beginPath(); context.arc(shape.x, shape.y, shape.radius,0,2*Math.PI); context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas var w = shape.width * 2; @@ -119,18 +135,21 @@ context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; var width = shape.width; @@ -152,13 +171,15 @@ context.quadraticCurveTo(rx, ry, rx, ry + radius); context.closePath(); - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); @@ -174,45 +195,54 @@ * @param graphics {Graphics} the graphics which will be used as a mask * @param context {CanvasRenderingContext2D} the context 2d method of the canvas */ -CanvasGraphics.renderGraphicsMask = function (graphics, context) { +CanvasGraphics.renderGraphicsMask = function (graphics, context) +{ var len = graphics.graphicsData.length; - if (len === 0) { + if (len === 0) + { return; } context.beginPath(); - for (var i = 0; i < len; i++) { + for (var i = 0; i < len; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { context.rect(shape.x, shape.y, shape.width, shape.height); context.closePath(); } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.arc(shape.x, shape.y, shape.radius, 0, 2 * Math.PI); context.closePath(); } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas @@ -237,7 +267,8 @@ context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); context.closePath(); } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; @@ -262,8 +293,10 @@ } }; -CanvasGraphics.updateGraphicsTint = function (graphics) { - if (graphics.tint === 0xFFFFFF) { +CanvasGraphics.updateGraphicsTint = function (graphics) +{ + if (graphics.tint === 0xFFFFFF) + { return; } @@ -271,7 +304,8 @@ var tintG = (graphics.tint >> 8 & 0xFF) / 255; var tintB = (graphics.tint & 0xFF)/ 255; - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var fillColor = data.fillColor | 0; diff --git a/src/core/renderers/canvas/utils/CanvasMaskManager.js b/src/core/renderers/canvas/utils/CanvasMaskManager.js index e04a733..9827d36 100644 --- a/src/core/renderers/canvas/utils/CanvasMaskManager.js +++ b/src/core/renderers/canvas/utils/CanvasMaskManager.js @@ -6,7 +6,8 @@ * @class * @namespace PIXI */ -function CanvasMaskManager() {} +function CanvasMaskManager() +{} CanvasMaskManager.prototype.constructor = CanvasMaskManager; module.exports = CanvasMaskManager; @@ -17,7 +18,8 @@ * @param maskData {object} the maskData that will be pushed * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.pushMask = function (maskData, renderer) { +CanvasMaskManager.prototype.pushMask = function (maskData, renderer) +{ renderer.context.save(); var cacheAlpha = maskData.alpha; @@ -45,6 +47,7 @@ * * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.popMask = function (renderer) { +CanvasMaskManager.prototype.popMask = function (renderer) +{ renderer.context.restore(); }; diff --git a/src/core/renderers/canvas/utils/CanvasTinter.js b/src/core/renderers/canvas/utils/CanvasTinter.js index 17e0529..d2fb1bc 100644 --- a/src/core/renderers/canvas/utils/CanvasTinter.js +++ b/src/core/renderers/canvas/utils/CanvasTinter.js @@ -14,7 +14,8 @@ * @param color {number} the color to use to tint the sprite with * @return {HTMLCanvasElement} The tinted canvas */ -CanvasTinter.getTintedTexture = function (sprite, color) { +CanvasTinter.getTintedTexture = function (sprite, color) +{ var texture = sprite.texture; color = CanvasTinter.roundColor(color); @@ -23,7 +24,8 @@ texture.tintCache = texture.tintCache || {}; - if (texture.tintCache[stringColor]) { + if (texture.tintCache[stringColor]) + { return texture.tintCache[stringColor]; } @@ -33,14 +35,16 @@ //CanvasTinter.tintWithPerPixel(texture, stringColor, canvas); CanvasTinter.tintMethod(texture, color, canvas); - if (CanvasTinter.convertTintToImage) { + if (CanvasTinter.convertTintToImage) + { // is this better? var tintImage = new Image(); tintImage.src = canvas.toDataURL(); texture.tintCache[stringColor] = tintImage; } - else { + else + { texture.tintCache[stringColor] = canvas; // if we are not converting the texture to an image then we need to lose the reference to the canvas CanvasTinter.canvas = null; @@ -56,7 +60,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithMultiply = function (texture, color, canvas) { +CanvasTinter.tintWithMultiply = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -104,7 +109,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithOverlay = function (texture, color, canvas) { +CanvasTinter.tintWithOverlay = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -139,7 +145,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithPerPixel = function (texture, color, canvas) { +CanvasTinter.tintWithPerPixel = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -167,7 +174,8 @@ var pixels = pixelData.data; - for (var i = 0; i < pixels.length; i += 4) { + for (var i = 0; i < pixels.length; i += 4) + { pixels[i+0] *= r; pixels[i+1] *= g; pixels[i+2] *= b; @@ -181,7 +189,8 @@ * * @param color {number} the color to round, should be a hex color */ -CanvasTinter.roundColor = function (color) { +CanvasTinter.roundColor = function (color) +{ var step = CanvasTinter.cacheStepsPerColorChannel; var rgbValues = utils.hex2rgb(color); diff --git a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js index 9f2f89a..35edbaf 100644 --- a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js +++ b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLBlendModeManager(renderer) { +function WebGLBlendModeManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -23,8 +24,10 @@ * * @param blendMode {number} the blendMode, should be a Pixi const, such as BlendModes.ADD */ -WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) { - if (this.currentBlendMode === blendMode) { +WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) +{ + if (this.currentBlendMode === blendMode) + { return false; } diff --git a/src/core/renderers/webgl/managers/WebGLFilterManager.js b/src/core/renderers/webgl/managers/WebGLFilterManager.js index 1179258..2dac048 100644 --- a/src/core/renderers/webgl/managers/WebGLFilterManager.js +++ b/src/core/renderers/webgl/managers/WebGLFilterManager.js @@ -7,7 +7,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLFilterManager(renderer) { +function WebGLFilterManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -32,7 +33,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.texturePool.length = 0; self.initShaderBuffers(); }); @@ -46,7 +48,8 @@ * @param renderer {WebGLRenderer} * @param buffer {ArrayBuffer} */ -WebGLFilterManager.prototype.begin = function (buffer) { +WebGLFilterManager.prototype.begin = function (buffer) +{ this.defaultShader = this.renderer.shaderManager.defaultShader; this.width = this.renderer.projection.x * 2; @@ -60,7 +63,8 @@ * * @param filterBlock {object} the filter that will be pushed to the current filter stack */ -WebGLFilterManager.prototype.pushFilter = function (filterBlock) { +WebGLFilterManager.prototype.pushFilter = function (filterBlock) +{ var gl = this.renderer.gl; var projection = this.renderer.projection; @@ -78,10 +82,12 @@ this.offsetY += filterBlock._filterArea.y; var texture = this.texturePool.pop(); - if (!texture) { + if (!texture) + { texture = new FilterTexture(this.renderer.gl, this.width, this.height); } - else { + else + { texture.resize(this.width, this.height); } @@ -98,29 +104,35 @@ var localX = filterArea.x, localY = filterArea.y; - if (filterArea.x < 0) { + if (filterArea.x < 0) + { filterArea.width += filterArea.x; filterArea.x = 0; } - if (filterArea.y < 0) { + if (filterArea.y < 0) + { filterArea.height += filterArea.y; filterArea.y = 0; } - if (localX + filterArea.width > this.width) { + if (localX + filterArea.width > this.width) + { filterArea.width = this.width - localX; } - if (localY + filterArea.height > this.height) { + if (localY + filterArea.height > this.height) + { filterArea.height = this.height - localY; } - if (filterArea.width < 0) { + if (filterArea.width < 0) + { filterArea.width = 0; } - if (filterArea.height < 0) { + if (filterArea.height < 0) + { filterArea.height = 0; } @@ -154,7 +166,8 @@ * Removes the last filter from the filter stack and doesn't return it. * */ -WebGLFilterManager.prototype.popFilter = function () { +WebGLFilterManager.prototype.popFilter = function () +{ var gl = this.renderer.gl; var filterBlock = this.filterStack.pop(); @@ -163,7 +176,8 @@ var projection = this.renderer.projection; var offset = this.renderer.offset; - if (filterBlock.filterPasses.length > 1) { + if (filterBlock.filterPasses.length > 1) + { gl.viewport(0, 0, filterArea.width, filterArea.height); gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); @@ -193,7 +207,8 @@ var inputTexture = texture; var outputTexture = this.texturePool.pop(); - if (!outputTexture) { + if (!outputTexture) + { outputTexture = new FilterTexture(this.renderer.gl, this.width, this.height); } outputTexture.resize(this.width, this.height); @@ -204,7 +219,8 @@ gl.disable(gl.BLEND); - for (var i = 0; i < filterBlock.filterPasses.length-1; i++) { + for (var i = 0; i < filterBlock.filterPasses.length-1; i++) + { var filterPass = filterBlock.filterPasses[i]; gl.bindFramebuffer(gl.FRAMEBUFFER, outputTexture.frameBuffer ); @@ -243,10 +259,12 @@ var buffer = this.buffer; // time to render the filters texture to the previous scene - if (this.filterStack.length === 0) { + if (this.filterStack.length === 0) + { gl.colorMask(true, true, true, true);//this.transparent); } - else { + else + { var currentFilter = this.filterStack[this.filterStack.length-1]; filterArea = currentFilter._filterArea; @@ -332,13 +350,15 @@ * @param width {number} the horizontal range of the filter * @param height {number} the vertical range of the filter */ -WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) { +WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) +{ // use program var gl = this.renderer.gl; var shader = filter.shaders[gl.id]; - if (!shader) { + if (!shader) + { shader = new Shader(gl); shader.fragmentSrc = filter.fragmentSrc; @@ -356,7 +376,8 @@ gl.uniform2f(shader.projectionVector, width/2, -height/2); gl.uniform2f(shader.offsetVector, 0,0); - if (filter.uniforms.dimensions) { + 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]; @@ -386,7 +407,8 @@ * Initialises the shader buffers. * */ -WebGLFilterManager.prototype.initShaderBuffers = function () { +WebGLFilterManager.prototype.initShaderBuffers = function () +{ var gl = this.renderer.gl; // create some buffers @@ -432,7 +454,8 @@ * Destroys the filter and removes it from the filter stack. * */ -WebGLFilterManager.prototype.destroy = function () { +WebGLFilterManager.prototype.destroy = function () +{ var gl = this.renderer.gl; this.filterStack = null; @@ -441,7 +464,8 @@ this.offsetY = 0; // destroy textures - for (var i = 0; i < this.texturePool.length; i++) { + for (var i = 0; i < this.texturePool.length; i++) + { this.texturePool[i].destroy(); } diff --git a/src/core/renderers/webgl/managers/WebGLManager.js b/src/core/renderers/webgl/managers/WebGLManager.js index 9d47b5c..c30cd51 100644 --- a/src/core/renderers/webgl/managers/WebGLManager.js +++ b/src/core/renderers/webgl/managers/WebGLManager.js @@ -3,7 +3,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLManager(renderer) { +function WebGLManager(renderer) +{ /** * The renderer this manager works for. * @@ -15,6 +16,7 @@ WebGLManager.prototype.constructor = WebGLManager; module.exports = WebGLManager; -WebGLManager.prototype.destroy = function () { +WebGLManager.prototype.destroy = function () +{ this.renderer = null; }; diff --git a/src/core/renderers/webgl/managers/WebGLMaskManager.js b/src/core/renderers/webgl/managers/WebGLMaskManager.js index 2f90b64..e568812 100644 --- a/src/core/renderers/webgl/managers/WebGLMaskManager.js +++ b/src/core/renderers/webgl/managers/WebGLMaskManager.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLMaskManager(renderer) { +function WebGLMaskManager(renderer) +{ WebGLManager.call(this, renderer); } @@ -19,12 +20,15 @@ * * @param maskData {any[]} */ -WebGLMaskManager.prototype.pushMask = function (maskData) { - if (maskData.dirty) { +WebGLMaskManager.prototype.pushMask = function (maskData) +{ + if (maskData.dirty) + { WebGLGraphics.updateGraphics(maskData, this.renderer.gl); } - if (!maskData._webGL[this.renderer.gl.id].data.length) { + if (!maskData._webGL[this.renderer.gl.id].data.length) + { return; } @@ -36,6 +40,7 @@ * * @param maskData {any[]} */ -WebGLMaskManager.prototype.popMask = function (maskData) { +WebGLMaskManager.prototype.popMask = function (maskData) +{ this.renderer.stencilManager.popStencil(maskData, maskData._webGL[this.renderer.gl.id].data[0], this.renderer); }; diff --git a/src/core/renderers/webgl/managers/WebGLShaderManager.js b/src/core/renderers/webgl/managers/WebGLShaderManager.js index fef071c..90c6477 100644 --- a/src/core/renderers/webgl/managers/WebGLShaderManager.js +++ b/src/core/renderers/webgl/managers/WebGLShaderManager.js @@ -10,7 +10,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLShaderManager(renderer) { +function WebGLShaderManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -28,7 +29,8 @@ */ this.tempAttribState = []; - for (var i = 0; i < this.maxAttibs; i++) { + for (var i = 0; i < this.maxAttibs; i++) + { this.attribState[i] = false; } @@ -66,7 +68,8 @@ // listen for context and update necessary shaders var self = this; - this.renderer.on('context', function (event) { + this.renderer.on('context', function (event) + { var gl = event.data; // this shader is used for rendering primitives @@ -97,29 +100,36 @@ * * @param attribs {Array} attribs */ -WebGLShaderManager.prototype.setAttribs = function (attribs) { +WebGLShaderManager.prototype.setAttribs = function (attribs) +{ // reset temp state var i; - for (i = 0; i < this.tempAttribState.length; i++) { + for (i = 0; i < this.tempAttribState.length; i++) + { this.tempAttribState[i] = false; } // set the new attribs - for (var a in attribs) { + for (var a in attribs) + { this.tempAttribState[attribs[a]] = true; } var gl = this.renderer.gl; - for (i = 0; i < this.attribState.length; i++) { - if (this.attribState[i] !== this.tempAttribState[i]) { + for (i = 0; i < this.attribState.length; i++) + { + if (this.attribState[i] !== this.tempAttribState[i]) + { this.attribState[i] = this.tempAttribState[i]; - if (this.attribState[i]) { + if (this.attribState[i]) + { gl.enableVertexAttribArray(i); } - else { + else + { gl.disableVertexAttribArray(i); } } @@ -131,8 +141,10 @@ * * @param shader {Any} */ -WebGLShaderManager.prototype.setShader = function (shader) { - if (this._currentId === shader.uuid) { +WebGLShaderManager.prototype.setShader = function (shader) +{ + if (this._currentId === shader.uuid) + { return false; } @@ -150,7 +162,8 @@ * Destroys this object. * */ -WebGLShaderManager.prototype.destroy = function () { +WebGLShaderManager.prototype.destroy = function () +{ this.attribState = null; this.tempAttribState = null; diff --git a/src/core/renderers/webgl/managers/WebGLStencilManager.js b/src/core/renderers/webgl/managers/WebGLStencilManager.js index 9ec6398..4cb0134 100644 --- a/src/core/renderers/webgl/managers/WebGLStencilManager.js +++ b/src/core/renderers/webgl/managers/WebGLStencilManager.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLStencilManager(renderer) { +function WebGLStencilManager(renderer) +{ WebGLManager.call(this, renderer); this.stencilStack = []; @@ -24,12 +25,14 @@ * @param graphics {Graphics} * @param webGLData {any[]} */ -WebGLStencilManager.prototype.pushStencil = function (graphics, webGLData) { +WebGLStencilManager.prototype.pushStencil = function (graphics, webGLData) +{ var gl = this.renderer.gl; this.bindGraphics(graphics, webGLData, this.renderer); - if (this.stencilStack.length === 0) { + if (this.stencilStack.length === 0) + { gl.enable(gl.STENCIL_TEST); gl.clear(gl.STENCIL_BUFFER_BIT); this.reverse = true; @@ -47,14 +50,17 @@ // draw the triangle strip! - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } @@ -62,31 +68,38 @@ // draw a quad to increment.. gl.drawElements(gl.TRIANGLE_FAN, 4, gl.UNSIGNED_SHORT, ( webGLData.indices.length - 4 ) * 2 ); - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); } this.reverse = !this.reverse; } - else { - if (!this.reverse) { + else + { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } - else { + 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) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); } } @@ -103,7 +116,8 @@ * @param graphics {Graphics} * @param webGLData {Array} */ -WebGLStencilManager.prototype.bindGraphics = function (graphics, webGLData) { +WebGLStencilManager.prototype.bindGraphics = function (graphics, webGLData) +{ //if (this._currentGraphics === graphics)return; this._currentGraphics = graphics; @@ -114,7 +128,8 @@ offset = this.renderer.offset, shader;// = this.renderer.shaderManager.primitiveShader; - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { shader = this.renderer.shaderManager.complexPrimitiveShader; this.renderer.shaderManager.setShader(shader); @@ -141,7 +156,8 @@ // set the index buffer! gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, webGLData.indexBuffer); } - else { + else + { //this.renderer.shaderManager.activatePrimitiveShader(); shader = this.renderer.shaderManager.primitiveShader; this.renderer.shaderManager.setShader( shader ); @@ -154,7 +170,7 @@ gl.uniform2f(shader.uniforms.offsetVector._location, -offset.x, -offset.y); gl.uniform3fv(shader.uniforms.tint._location, utils.hex2rgb(graphics.tint)); - + gl.uniform1f(shader.uniforms.alpha._location, graphics.worldAlpha); @@ -172,19 +188,22 @@ * @param graphics {Graphics} * @param webGLData {Array} */ -WebGLStencilManager.prototype.popStencil = function (graphics, webGLData) { +WebGLStencilManager.prototype.popStencil = function (graphics, webGLData) +{ var gl = this.renderer.gl; this.stencilStack.pop(); this.count--; - if (this.stencilStack.length === 0) { + if (this.stencilStack.length === 0) + { // the stack is empty! gl.disable(gl.STENCIL_TEST); } - else { + else + { var level = this.count; @@ -192,14 +211,17 @@ gl.colorMask(false, false, false, false); - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { this.reverse = !this.reverse; - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } @@ -213,31 +235,38 @@ // draw the triangle strip! gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); - if (!this.reverse) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); } } - else { + else + { // console.log("<<>>") - if (!this.reverse) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } - else { + 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) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); } } @@ -253,7 +282,8 @@ * Destroys the mask stack. * */ -WebGLStencilManager.prototype.destroy = function () { +WebGLStencilManager.prototype.destroy = function () +{ this.renderer = null; this.stencilStack = null; }; diff --git a/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js b/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js index 913ba5e..1ea7d19 100644 --- a/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js +++ b/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function ComplexPrimitiveShader(gl) { +function ComplexPrimitiveShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -24,7 +25,8 @@ 'uniform float flipY;', 'varying vec4 vColor;', - 'void main(void) {', + '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);', @@ -37,7 +39,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = vColor;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/FastShader.js b/src/core/renderers/webgl/shaders/FastShader.js index bd2e29a..2e5e060 100644 --- a/src/core/renderers/webgl/shaders/FastShader.js +++ b/src/core/renderers/webgl/shaders/FastShader.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function FastShader(gl) { +function FastShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -28,7 +29,8 @@ 'const vec2 center = vec2(-1.0, 1.0);', - 'void main(void) {', + 'void main(void) + {', ' vec2 v;', ' vec2 sv = aVertexPosition * aScale;', ' v.x = (sv.x) * cos(aRotation) - (sv.y) * sin(aRotation);', @@ -49,7 +51,8 @@ 'uniform sampler2D uSampler;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/PrimitiveShader.js b/src/core/renderers/webgl/shaders/PrimitiveShader.js index 6f25409..a25f54f 100644 --- a/src/core/renderers/webgl/shaders/PrimitiveShader.js +++ b/src/core/renderers/webgl/shaders/PrimitiveShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function PrimitiveShader(gl) { +function PrimitiveShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -23,7 +24,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + '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);', @@ -36,7 +38,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = vColor;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/Shader.js b/src/core/renderers/webgl/shaders/Shader.js index f8964f5..fd75ef5 100644 --- a/src/core/renderers/webgl/shaders/Shader.js +++ b/src/core/renderers/webgl/shaders/Shader.js @@ -6,7 +6,8 @@ * @param [fragmentSrc] {string} The source of the fragment shader. * @param [vertexSrc] {string} The source of the vertex shader. */ -function Shader(gl, vertexSrc, fragmentSrc, customUniforms, customAttributes) { +function Shader(gl, vertexSrc, fragmentSrc, customUniforms, customAttributes) +{ /** * @member {number} * @readonly @@ -33,7 +34,8 @@ dimensions: { type: '4f', value: new Float32Array(4) } }; - for (var u in customUniforms) { + for (var u in customUniforms) + { this.uniforms[u] = customUniforms[u]; } @@ -43,7 +45,8 @@ aColor: 0 }; - for (var a in customAttributes) { + for (var a in customAttributes) + { this.attributes[a] = customAttributes[a]; } @@ -66,7 +69,8 @@ 'const vec2 center = vec2(-1.0, 1.0);', - 'void main(void) {', + 'void main(void) + {', ' gl_Position = vec4( ((aVertexPosition + offsetVector) / projectionVector) + center , 0.0, 1.0);', ' vTextureCoord = aTextureCoord;', ' vColor = vec4(aColor.rgb * aColor.a, aColor.a);', @@ -85,7 +89,8 @@ 'uniform sampler2D uSampler;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;', '}' ].join('\n'); @@ -96,7 +101,8 @@ Shader.prototype.constructor = Shader; module.exports = Shader; -Shader.prototype.init = function () { +Shader.prototype.init = function () +{ this.compile(); this.gl.useProgram(this.program); @@ -105,14 +111,18 @@ this.cacheAttributeLocations(Object.keys(this.attributes)); }; -Shader.prototype.cacheUniformLocations = function (keys) { - for (var i = 0; i < keys.length; ++i) { +Shader.prototype.cacheUniformLocations = function (keys) +{ + for (var i = 0; i < keys.length; ++i) + { this.uniforms[keys[i]]._location = this.gl.getUniformLocation(this.program, keys[i]); } }; -Shader.prototype.cacheAttributeLocations = function (keys) { - for (var i = 0; i < keys.length; ++i) { +Shader.prototype.cacheAttributeLocations = function (keys) +{ + for (var i = 0; i < keys.length; ++i) + { this.attributes[keys[i]] = this.gl.getAttribLocation(this.program, keys[i]); } @@ -124,14 +134,16 @@ // 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.attributes.aColor === -1) { + // if (this.attributes.aColor === -1) + { // this.attributes.aColor = 2; // } // End worst hack eva // }; -Shader.prototype.compile = function () { +Shader.prototype.compile = function () +{ var gl = this.gl; var glVertShader = this._glCompile(gl.VERTEX_SHADER, this.vertexSrc); @@ -144,13 +156,15 @@ gl.linkProgram(program); // if linking fails, then log and cleanup - if (!gl.getProgramParameter(program, gl.LINK_STATUS)) { + if (!gl.getProgramParameter(program, gl.LINK_STATUS)) + { window.console.error('Pixi.js Error: Could not initialize shader.'); window.console.error('gl.VALIDATE_STATUS', gl.getProgramParameter(program, gl.VALIDATE_STATUS)); window.console.error('gl.getError()', gl.getError()); // if there is a program info log, log it - if (gl.getProgramInfoLog(program) !== '') { + if (gl.getProgramInfoLog(program) !== '') + { window.console.warn('Pixi.js Warning: gl.getProgramInfoLog()', gl.getProgramInfoLog(program)); } @@ -165,18 +179,21 @@ return (this.program = program); }; -Shader.prototype.syncUniforms = function () { +Shader.prototype.syncUniforms = function () +{ var gl = this.gl; this.textureCount = 1; - for (var key in this.uniforms) { + for (var key in this.uniforms) + { var uniform = this.uniforms[key], location = uniform._location, value = uniform.value, i, il; - switch (uniform.type) { + switch (uniform.type) + { // single int value case 'i': case '1i': @@ -282,7 +299,8 @@ // a Color Value case 'c': - if (typeof value === 'number') { + if (typeof value === 'number') + { value = utils.hex2rgb(value); } @@ -311,11 +329,13 @@ // array of 2D Point objects case 'v2v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(2 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 2] = value[i].x; uniform._array[i * 2 + 1] = value[i].y; } @@ -325,11 +345,13 @@ // array of 3D Point objects case 'v3v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(3 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 3] = value[i].x; uniform._array[i * 3 + 1] = value[i].y; uniform._array[i * 3 + 2] = value[i].z; @@ -341,11 +363,13 @@ // array of 4D Point objects case 'v4v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(4 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 4] = value[i].x; uniform._array[i * 4 + 1] = value[i].y; uniform._array[i * 4 + 2] = value[i].z; @@ -359,7 +383,8 @@ // PIXI.Texture case 't': case 'sampler2D': - if (!uniform.value || !uniform.value.baseTexture || !uniform.value.baseTexture.hasLoaded) { + if (!uniform.value || !uniform.value.baseTexture || !uniform.value.baseTexture.hasLoaded) + { break; } @@ -376,7 +401,8 @@ this.textureCount++; // initialize the texture if we haven't yet - if (!uniform._init) { + if (!uniform._init) + { this.initSampler2D(uniform); uniform._init = true; @@ -394,11 +420,13 @@ * Initialises a Sampler2D uniform (which may only be available later on after initUniforms once the texture has loaded) * */ -Shader.prototype.initSampler2D = function (uniform) { +Shader.prototype.initSampler2D = function (uniform) +{ var gl = this.gl; // Extended texture data - if (uniform.textureData) { + if (uniform.textureData) + { var data = uniform.textureData; // GLTexture = mag linear, min linear_mipmap_linear, wrap repeat + gl.generateMipmap(gl.TEXTURE_2D); @@ -417,14 +445,16 @@ var wrapT = (data.wrapT) ? data.wrapT : gl.CLAMP_TO_EDGE; var format = (data.luminance) ? gl.LUMINANCE : gl.RGBA; - if (data.repeat) { + if (data.repeat) + { wrapS = gl.REPEAT; wrapT = gl.REPEAT; } gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, !!data.flipY); - if (data.width) { + if (data.width) + { var width = (data.width) ? data.width : 512; var height = (data.height) ? data.height : 2; var border = (data.border) ? data.border : 0; @@ -432,7 +462,8 @@ // 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 { + 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); } @@ -448,7 +479,8 @@ * Destroys the shader. * */ -Shader.prototype.destroy = function () { +Shader.prototype.destroy = function () +{ this.gl.deleteProgram(this.program); this.gl = null; @@ -459,13 +491,15 @@ this.fragmentSrc = null; }; -Shader.prototype._glCompile = function (type, src) { +Shader.prototype._glCompile = function (type, src) +{ var shader = this.gl.createShader(type); this.gl.shaderSource(shader, src); this.gl.compileShader(shader); - if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) { + if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) + { window.console.log(this.gl.getShaderInfoLog(shader)); return null; } diff --git a/src/core/renderers/webgl/shaders/StripShader.js b/src/core/renderers/webgl/shaders/StripShader.js index 193f6e1..a7abcc6 100644 --- a/src/core/renderers/webgl/shaders/StripShader.js +++ b/src/core/renderers/webgl/shaders/StripShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function StripShader(gl) { +function StripShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -20,7 +21,8 @@ 'varying vec2 vTextureCoord;', - 'void main(void) {', + '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);', @@ -36,7 +38,8 @@ 'varying vec2 vTextureCoord;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vec2(vTextureCoord.x, vTextureCoord.y)) * alpha;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/utils/FilterTexture.js b/src/core/renderers/webgl/utils/FilterTexture.js index d2c8423..4433d44 100644 --- a/src/core/renderers/webgl/utils/FilterTexture.js +++ b/src/core/renderers/webgl/utils/FilterTexture.js @@ -8,7 +8,8 @@ * @param height {number} the vertical range of the filter * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values */ -function FilterTexture(gl, width, height, scaleMode) { +function FilterTexture(gl, width, height, scaleMode) +{ /** * @member {WebGLContext} */ @@ -59,7 +60,8 @@ * Clears the filter texture. * */ -FilterTexture.prototype.clear = function () { +FilterTexture.prototype.clear = function () +{ var gl = this.gl; gl.clearColor(0,0,0, 0); @@ -72,8 +74,10 @@ * @param width {number} the new width of the texture * @param height {number} the new height of the texture */ -FilterTexture.prototype.resize = function (width, height) { - if (this.width === width && this.height === height) { +FilterTexture.prototype.resize = function (width, height) +{ + if (this.width === width && this.height === height) + { return; } @@ -96,7 +100,8 @@ * Destroys the filter texture. * */ -FilterTexture.prototype.destroy = function () { +FilterTexture.prototype.destroy = function () +{ var gl = this.gl; gl.deleteFramebuffer( this.frameBuffer ); gl.deleteTexture( this.texture ); diff --git a/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js b/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js index c4721e9..a63f4d7 100644 --- a/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js +++ b/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js @@ -14,7 +14,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this sprite batch works for. */ -function WebGLFastSpriteBatch(renderer) { +function WebGLFastSpriteBatch(renderer) +{ /** * The renderer instance this sprite batch operates on. * @@ -91,7 +92,8 @@ */ this.lastIndexCount = 0; - for (var i=0, j=0; i < numIndices; i += 6, j += 4) { + 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; @@ -144,7 +146,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.setupContext(); }); } @@ -157,7 +160,8 @@ * * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLFastSpriteBatch.prototype.setupContext = function () { +WebGLFastSpriteBatch.prototype.setupContext = function () +{ var gl = this.renderer.gl; // create a couple of buffers @@ -177,7 +181,8 @@ /** * @param spriteBatch {SpriteBatch} The SpriteBatch container to prepare for. */ -WebGLFastSpriteBatch.prototype.begin = function (spriteBatch) { +WebGLFastSpriteBatch.prototype.begin = function (spriteBatch) +{ this.shader = this.renderer.shaderManager.fastShader; this.matrix = spriteBatch.worldTransform.toArray(true); @@ -187,33 +192,38 @@ /** */ -WebGLFastSpriteBatch.prototype.end = function () { +WebGLFastSpriteBatch.prototype.end = function () +{ this.flush(); }; /** * @param spriteBatch {SpriteBatch} The SpriteBatch container to render. */ -WebGLFastSpriteBatch.prototype.render = function (spriteBatch) { +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) { + if (!sprite.texture._uvs) + { return; } this.currentBaseTexture = sprite.texture.baseTexture; // check blend mode - if (sprite.blendMode !== this.renderer.blendModeManager.currentBlendMode) { + if (sprite.blendMode !== this.renderer.blendModeManager.currentBlendMode) + { this.flush(); this.renderer.blendModeManager.setBlendMode(sprite.blendMode); } - for (var i=0,j= children.length; i= this.size) { + if (this.currentBatchSize >= this.size) + { this.flush(); } }; @@ -362,29 +379,35 @@ /** * */ -WebGLFastSpriteBatch.prototype.flush = function () { +WebGLFastSpriteBatch.prototype.flush = function () +{ // If the batch is length 0 then return as there is nothing to draw - if (this.currentBatchSize === 0) { + if (this.currentBatchSize === 0) + { return; } var gl = this.renderer.gl; // bind the current texture - if (!this.currentBaseTexture._glTextures[gl.id]) { + if (!this.currentBaseTexture._glTextures[gl.id]) + { this.renderer.updateTexture(this.currentBaseTexture, gl); } //TODO-SHOUD THIS BE ELSE??!?!?! - else { + else + { gl.bindTexture(gl.TEXTURE_2D, this.currentBaseTexture._glTextures[gl.id]); } // upload the verts to the buffer - if (this.currentBatchSize > ( this.size * 0.5 ) ) { + if (this.currentBatchSize > ( this.size * 0.5 ) ) + { gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); } - else { + else + { var view = this.vertices.subarray(0, this.currentBatchSize * this.vertByteSize); gl.bufferSubData(gl.ARRAY_BUFFER, 0, view); @@ -405,14 +428,16 @@ * Ends the batch and flushes * */ -WebGLFastSpriteBatch.prototype.stop = function () { +WebGLFastSpriteBatch.prototype.stop = function () +{ this.flush(); }; /** * */ -WebGLFastSpriteBatch.prototype.start = function () { +WebGLFastSpriteBatch.prototype.start = function () +{ var gl = this.renderer.gl; // bind the main texture diff --git a/src/core/renderers/webgl/utils/WebGLGraphics.js b/src/core/renderers/webgl/utils/WebGLGraphics.js index 55f4911..ab8f46e 100644 --- a/src/core/renderers/webgl/utils/WebGLGraphics.js +++ b/src/core/renderers/webgl/utils/WebGLGraphics.js @@ -19,7 +19,8 @@ * @param graphics {Graphics} * @param renderer {WebGLRenderer} */ -WebGLGraphics.renderGraphics = function (graphics, renderer) {//projection, offset) { +WebGLGraphics.renderGraphics = function (graphics, renderer) {//projection, offset) +{ var gl = renderer.gl; var projection = renderer.projection, @@ -27,7 +28,8 @@ shader = renderer.shaderManager.primitiveShader, webGLData; - if (graphics.dirty) { + if (graphics.dirty) + { WebGLGraphics.updateGraphics(graphics, gl); } @@ -35,8 +37,10 @@ // This could be speeded up for sure! - for (var i = 0; i < webGL.data.length; i++) { - if (webGL.data[i].mode === 1) { + for (var i = 0; i < webGL.data.length; i++) + { + if (webGL.data[i].mode === 1) + { webGLData = webGL.data[i]; renderer.stencilManager.pushStencil(graphics, webGLData, renderer); @@ -46,7 +50,8 @@ renderer.stencilManager.popStencil(graphics, webGLData, renderer); } - else { + else + { webGLData = webGL.data[i]; @@ -84,12 +89,14 @@ * @param graphicsData {Graphics} The graphics object to update * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLGraphics.updateGraphics = function (graphics, gl) { +WebGLGraphics.updateGraphics = function (graphics, gl) +{ // get the contexts graphics object var webGL = graphics._webGL[gl.id]; // if the graphics object does not exist in the webGL context time to create it! - if (!webGL) { + if (!webGL) + { webGL = graphics._webGL[gl.id] = {lastIndex:0, data:[], gl:gl}; } @@ -99,11 +106,13 @@ var i; // if the user cleared the graphics object we will need to clear every object - if (graphics.clearDirty) { + if (graphics.clearDirty) + { graphics.clearDirty = false; // lop through and return all the webGLDatas to the object pool so than can be reused later on - for (i = 0; i < webGL.data.length; i++) { + for (i = 0; i < webGL.data.length; i++) + { var graphicsData = webGL.data[i]; graphicsData.reset(); WebGLGraphics.graphicsDataPool.push( graphicsData ); @@ -119,58 +128,72 @@ // loop through the graphics datas and construct each one.. // if the object is a complex fill then the new stencil buffer technique will be used // other wise graphics objects will be pushed into a batch.. - for (i = webGL.lastIndex; i < graphics.graphicsData.length; i++) { + for (i = webGL.lastIndex; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { // need to add the points the the graphics object.. data.points = data.shape.points.slice(); - if (data.shape.closed) { + if (data.shape.closed) + { // close the poly if the value is true! - if (data.points[0] !== data.points[data.points.length-2] || data.points[1] !== data.points[data.points.length-1]) { + if (data.points[0] !== data.points[data.points.length-2] || data.points[1] !== data.points[data.points.length-1]) + { data.points.push(data.points[0], data.points[1]); } } // MAKE SURE WE HAVE THE CORRECT TYPE.. - if (data.fill) { - if (data.points.length >= 6) { - if (data.points.length < 6 * 2) { + if (data.fill) + { + if (data.points.length >= 6) + { + if (data.points.length < 6 * 2) + { webGLData = WebGLGraphics.switchMode(webGL, 0); var canDrawUsingSimple = WebGLGraphics.buildPoly(data, webGLData); // console.log(canDrawUsingSimple); - if (!canDrawUsingSimple) { + if (!canDrawUsingSimple) + { // console.log("<>>>") webGLData = WebGLGraphics.switchMode(webGL, 1); WebGLGraphics.buildComplexPoly(data, webGLData); } } - else { + else + { webGLData = WebGLGraphics.switchMode(webGL, 1); WebGLGraphics.buildComplexPoly(data, webGLData); } } } - if (data.lineWidth > 0) { + if (data.lineWidth > 0) + { webGLData = WebGLGraphics.switchMode(webGL, 0); WebGLGraphics.buildLine(data, webGLData); } } - else { + else + { webGLData = WebGLGraphics.switchMode(webGL, 0); - if (data.type === CONST.SHAPES.RECT) { + if (data.type === CONST.SHAPES.RECT) + { WebGLGraphics.buildRectangle(data, webGLData); } - else if (data.type === CONST.SHAPES.CIRC || data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.CIRC || data.type === CONST.SHAPES.ELIP) + { WebGLGraphics.buildCircle(data, webGLData); } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { WebGLGraphics.buildRoundedRectangle(data, webGLData); } } @@ -179,10 +202,12 @@ } // upload all the dirty data... - for (i = 0; i < webGL.data.length; i++) { + for (i = 0; i < webGL.data.length; i++) + { webGLData = webGL.data[i]; - if (webGLData.dirty) { + if (webGLData.dirty) + { webGLData.upload(); } } @@ -194,18 +219,22 @@ * @param webGL {WebGLContext} * @param type {number} */ -WebGLGraphics.switchMode = function (webGL, type) { +WebGLGraphics.switchMode = function (webGL, type) +{ var webGLData; - if (!webGL.data.length) { + if (!webGL.data.length) + { webGLData = WebGLGraphics.graphicsDataPool.pop() || new WebGLGraphicsData(webGL.gl); webGLData.mode = type; webGL.data.push(webGLData); } - else { + else + { webGLData = webGL.data[webGL.data.length-1]; - if (webGLData.mode !== type || type === 1) { + if (webGLData.mode !== type || type === 1) + { webGLData = WebGLGraphics.graphicsDataPool.pop() || new WebGLGraphicsData(webGL.gl); webGLData.mode = type; webGL.data.push(webGLData); @@ -225,7 +254,8 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildRectangle = function (graphicsData, webGLData) { +WebGLGraphics.buildRectangle = function (graphicsData, webGLData) +{ // --- // // need to convert points to a nice regular data // @@ -235,7 +265,8 @@ var width = rectData.width; var height = rectData.height; - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -265,7 +296,8 @@ indices.push(vertPos, vertPos, vertPos+1, vertPos+2, vertPos+3, vertPos+3); } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = [x, y, @@ -289,7 +321,8 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildRoundedRectangle = function (graphicsData, webGLData) { +WebGLGraphics.buildRoundedRectangle = function (graphicsData, webGLData) +{ var rrectData = graphicsData.shape; var x = rrectData.x; var y = rrectData.y; @@ -305,7 +338,8 @@ recPoints = recPoints.concat(WebGLGraphics.quadraticBezierCurve(x + width, y + radius, x + width, y, x + width - radius, y)); recPoints = recPoints.concat(WebGLGraphics.quadraticBezierCurve(x + radius, y, x, y, x, y + radius)); - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -323,7 +357,8 @@ // var i = 0; - for (i = 0; i < triangles.length; i+=3) { + for (i = 0; i < triangles.length; i+=3) + { indices.push(triangles[i] + vecPos); indices.push(triangles[i] + vecPos); indices.push(triangles[i+1] + vecPos); @@ -332,12 +367,14 @@ } - for (i = 0; i < recPoints.length; i++) { + for (i = 0; i < recPoints.length; i++) + { verts.push(recPoints[i], recPoints[++i], r, g, b, alpha); } } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = recPoints; @@ -362,7 +399,8 @@ * @param toY {number} Destination point y * @return {number[]} */ -WebGLGraphics.quadraticBezierCurve = function (fromX, fromY, cpX, cpY, toX, toY) { +WebGLGraphics.quadraticBezierCurve = function (fromX, fromY, cpX, cpY, toX, toY) +{ var xa, ya, @@ -373,14 +411,16 @@ n = 20, points = []; - function getPt(n1 , n2, perc) { + function getPt(n1 , n2, perc) + { var diff = n2 - n1; return n1 + ( diff * perc ); } var j = 0; - for (var i = 0; i <= n; i++ ) { + for (var i = 0; i <= n; i++ ) + { j = i / n; // The Green Line @@ -406,7 +446,8 @@ * @param graphicsData {Graphics} The graphics object to draw * @param webGLData {object} */ -WebGLGraphics.buildCircle = function (graphicsData, webGLData) { +WebGLGraphics.buildCircle = function (graphicsData, webGLData) +{ // need to convert points to a nice regular data var circleData = graphicsData.shape; var x = circleData.x; @@ -415,11 +456,13 @@ var height; // TODO - bit hacky?? - if (graphicsData.type === CONST.SHAPES.CIRC) { + if (graphicsData.type === CONST.SHAPES.CIRC) + { width = circleData.radius; height = circleData.radius; } - else { + else + { width = circleData.width; height = circleData.height; } @@ -429,7 +472,8 @@ var i = 0; - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -444,7 +488,8 @@ indices.push(vecPos); - for (i = 0; i < totalSegs + 1 ; i++) { + for (i = 0; i < totalSegs + 1 ; i++) + { verts.push(x,y, r, g, b, alpha); verts.push(x + Math.sin(seg * i) * width, @@ -457,12 +502,14 @@ indices.push(vecPos-1); } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = []; - for (i = 0; i < totalSegs + 1; i++) { + for (i = 0; i < totalSegs + 1; i++) + { graphicsData.points.push(x + Math.sin(seg * i) * width, y + Math.cos(seg * i) * height); } @@ -481,18 +528,22 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildLine = function (graphicsData, webGLData) { +WebGLGraphics.buildLine = function (graphicsData, webGLData) +{ // TODO OPTIMISE! var i = 0; var points = graphicsData.points; - if (points.length === 0) { + if (points.length === 0) + { return; } // if the line width is an odd number add 0.5 to align to a whole pixel - if (graphicsData.lineWidth%2) { - for (i = 0; i < points.length; i++) { + if (graphicsData.lineWidth%2) + { + for (i = 0; i < points.length; i++) + { points[i] += 0.5; } } @@ -502,7 +553,8 @@ var lastPoint = new math.Point(points[points.length - 2], points[points.length - 1]); // if the first point is the last point - gonna have issues :) - if (firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) { + if (firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) + { // need to clone as we are going to slightly modify the shape.. points = points.slice(); @@ -562,7 +614,8 @@ verts.push(p1x + perpx , p1y + perpy, r, g, b, alpha); - for (i = 1; i < length-1; i++) { + for (i = 1; i < length-1; i++) + { p1x = points[(i-1)*2]; p1y = points[(i-1)*2 + 1]; @@ -599,7 +652,8 @@ denom = a1*b2 - a2*b1; - if (Math.abs(denom) < 0.1 ) { + if (Math.abs(denom) < 0.1 ) + { denom+=10.1; verts.push(p2x - perpx , p2y - perpy, @@ -618,7 +672,8 @@ pdist = (px -p2x) * (px -p2x) + (py -p2y) + (py -p2y); - if (pdist > 140 * 140) { + if (pdist > 140 * 140) + { perp3x = perpx - perp2x; perp3y = perpy - perp2y; @@ -639,7 +694,8 @@ indexCount++; } - else { + else + { verts.push(px , py); verts.push(r, g, b, alpha); @@ -672,7 +728,8 @@ indices.push(indexStart); - for (i = 0; i < indexCount; i++) { + for (i = 0; i < indexCount; i++) + { indices.push(indexStart++); } @@ -687,11 +744,13 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildComplexPoly = function (graphicsData, webGLData) { +WebGLGraphics.buildComplexPoly = function (graphicsData, webGLData) +{ //TODO - no need to copy this as it gets turned into a FLoat32Array anyways.. var points = graphicsData.points.slice(); - if (points.length < 6) { + if (points.length < 6) + { return; } @@ -711,7 +770,8 @@ var x,y; // get size.. - for (var i = 0; i < points.length; i+=2) { + for (var i = 0; i < points.length; i+=2) + { x = points[i]; y = points[i+1]; @@ -732,7 +792,8 @@ //TODO - this aint needed! var length = points.length / 2; - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { indices.push( i ); } @@ -746,10 +807,12 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildPoly = function (graphicsData, webGLData) { +WebGLGraphics.buildPoly = function (graphicsData, webGLData) +{ var points = graphicsData.points; - if (points.length < 6) { + if (points.length < 6) + { return; } // get first and last point.. figure out the middle! @@ -767,7 +830,8 @@ var triangles = utils.PolyK.Triangulate(points); - if (!triangles) { + if (!triangles) + { return false; } @@ -775,7 +839,8 @@ var i = 0; - for (i = 0; i < triangles.length; i+=3) { + for (i = 0; i < triangles.length; i+=3) + { indices.push(triangles[i] + vertPos); indices.push(triangles[i] + vertPos); indices.push(triangles[i+1] + vertPos); @@ -783,7 +848,8 @@ indices.push(triangles[i+2] + vertPos); } - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { verts.push(points[i * 2], points[i * 2 + 1], r, g, b, alpha); } diff --git a/src/core/renderers/webgl/utils/WebGLGraphicsData.js b/src/core/renderers/webgl/utils/WebGLGraphicsData.js index c56d05e..c739ba7 100644 --- a/src/core/renderers/webgl/utils/WebGLGraphicsData.js +++ b/src/core/renderers/webgl/utils/WebGLGraphicsData.js @@ -2,7 +2,8 @@ * @class * @private */ -function WebGLGraphicsData(gl) { +function WebGLGraphicsData(gl) +{ this.gl = gl; //TODO does this need to be split before uploding?? @@ -22,7 +23,8 @@ /** * */ -WebGLGraphicsData.prototype.reset = function () { +WebGLGraphicsData.prototype.reset = function () +{ this.points.length = 0; this.indices.length = 0; }; @@ -30,7 +32,8 @@ /** * */ -WebGLGraphicsData.prototype.upload = function () { +WebGLGraphicsData.prototype.upload = function () +{ var gl = this.gl; // this.lastIndex = graphics.graphicsData.length; diff --git a/src/core/renderers/webgl/utils/WebGLSpriteBatch.js b/src/core/renderers/webgl/utils/WebGLSpriteBatch.js index 96eaa52..55befbb 100644 --- a/src/core/renderers/webgl/utils/WebGLSpriteBatch.js +++ b/src/core/renderers/webgl/utils/WebGLSpriteBatch.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this sprite batch works for. */ -function WebGLSpriteBatch(renderer) { +function WebGLSpriteBatch(renderer) +{ /** * * @@ -88,7 +89,8 @@ */ this.lastIndexCount = 0; - for (var i=0, j=0; i < numIndices; i += 6, j += 4) { + 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; @@ -162,7 +164,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.setupContext(); }); } @@ -173,7 +176,8 @@ /** * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLSpriteBatch.prototype.setupContext = function () { +WebGLSpriteBatch.prototype.setupContext = function () +{ var gl = this.renderer.gl; // setup default shader @@ -198,7 +202,8 @@ /** * */ -WebGLSpriteBatch.prototype.begin = function () { +WebGLSpriteBatch.prototype.begin = function () +{ // this.shader = this.renderer.shaderManager.defaultShader; this.start(); @@ -206,19 +211,22 @@ /** */ -WebGLSpriteBatch.prototype.end = function () { +WebGLSpriteBatch.prototype.end = function () +{ this.flush(); }; /** * @param sprite {Sprite} the sprite to render when using this spritebatch */ -WebGLSpriteBatch.prototype.render = function (sprite) { +WebGLSpriteBatch.prototype.render = function (sprite) +{ var texture = sprite.texture; //TODO set blend modes.. // check texture.. - if (this.currentBatchSize >= this.size) { + if (this.currentBatchSize >= this.size) + { this.flush(); this.currentBaseTexture = texture.baseTexture; } @@ -227,7 +235,8 @@ var uvs = texture._uvs; // if the uvs have not updated then no point rendering just yet! - if (!uvs) { + if (!uvs) + { return; } @@ -237,7 +246,8 @@ var w0, w1, h0, h1; - if (texture.trim) { + 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; @@ -248,7 +258,8 @@ h0 = h1 + texture.crop.height; } - else { + else + { w0 = (texture.frame.width ) * (1-aX); w1 = (texture.frame.width ) * -aX; @@ -272,7 +283,8 @@ var colors = this.colors; var positions = this.positions; - if (this.renderer.roundPixels) { + if (this.renderer.roundPixels) + { // xy positions[index] = a * w1 + c * h1 + tx | 0; positions[index+1] = d * h1 + b * w1 + ty | 0; @@ -289,7 +301,8 @@ positions[index+15] = a * w1 + c * h0 + tx | 0; positions[index+16] = d * h0 + b * w1 + ty | 0; } - else { + else + { // xy positions[index] = a * w1 + c * h1 + tx; positions[index+1] = d * h1 + b * w1 + ty; @@ -338,11 +351,13 @@ * * @param sprite {TilingSprite} the tilingSprite to render */ -WebGLSpriteBatch.prototype.renderTilingSprite = function (tilingSprite) { +WebGLSpriteBatch.prototype.renderTilingSprite = function (tilingSprite) +{ var texture = tilingSprite.tilingTexture; // check texture.. - if (this.currentBatchSize >= this.size) { + if (this.currentBatchSize >= this.size) + { //return; this.flush(); this.currentBaseTexture = texture.baseTexture; @@ -351,7 +366,8 @@ // set the textures uvs temporarily // TODO create a separate texture so that we can tile part of a texture - if (!tilingSprite._uvs) { + if (!tilingSprite._uvs) + { tilingSprite._uvs = new TextureUvs(); } @@ -454,16 +470,19 @@ * Renders the content and empties the current batch. * */ -WebGLSpriteBatch.prototype.flush = function () { +WebGLSpriteBatch.prototype.flush = function () +{ // If the batch is length 0 then return as there is nothing to draw - if (this.currentBatchSize === 0) { + if (this.currentBatchSize === 0) + { return; } var gl = this.renderer.gl; var shader; - if (this.dirty) { + if (this.dirty) + { this.dirty = false; // bind the main texture gl.activeTexture(gl.TEXTURE0); @@ -482,10 +501,12 @@ } // upload the verts to the buffer - if (this.currentBatchSize > ( this.size * 0.5 ) ) { + if (this.currentBatchSize > ( this.size * 0.5 ) ) + { gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); } - else { + else + { var view = this.positions.subarray(0, this.currentBatchSize * this.vertByteSize); gl.bufferSubData(gl.ARRAY_BUFFER, 0, view); } @@ -502,7 +523,8 @@ var shaderSwap = false; var sprite; - for (var i = 0, j = this.currentBatchSize; i < j; i++) { + for (var i = 0, j = this.currentBatchSize; i < j; i++) + { sprite = this.sprites[i]; @@ -513,24 +535,28 @@ blendSwap = currentBlendMode !== nextBlendMode; shaderSwap = currentShader !== nextShader; // should I use uuidS??? - if (currentBaseTexture !== nextTexture || blendSwap || shaderSwap) { + if (currentBaseTexture !== nextTexture || blendSwap || shaderSwap) + { this.renderBatch(currentBaseTexture, batchSize, start); start = i; batchSize = 0; currentBaseTexture = nextTexture; - if (blendSwap) { + if (blendSwap) + { currentBlendMode = nextBlendMode; this.renderer.blendModeManager.setBlendMode( currentBlendMode ); } - if (shaderSwap) { + if (shaderSwap) + { currentShader = nextShader; shader = currentShader.shaders ? currentShader.shaders[gl.id] : currentShader; - if (!shader) { + if (!shader) + { shader = new Shader(gl, null, currentShader.fragmentSrc, currentShader.uniforms); currentShader.shaders[gl.id] = shader; } @@ -538,7 +564,8 @@ // set shader function??? this.renderer.shaderManager.setShader(shader); - if (shader.dirty) { + if (shader.dirty) + { shader.syncUniforms(); } @@ -569,17 +596,21 @@ * @param size {number} * @param startIndex {number} */ -WebGLSpriteBatch.prototype.renderBatch = function (texture, size, startIndex) { - if (size === 0) { +WebGLSpriteBatch.prototype.renderBatch = function (texture, size, startIndex) +{ + if (size === 0) + { return; } var gl = this.renderer.gl; - if (!texture._glTextures[gl.id]) { + if (!texture._glTextures[gl.id]) + { this.renderer.updateTexture(texture); } - else { + else + { // bind the current texture gl.bindTexture(gl.TEXTURE_2D, texture._glTextures[gl.id]); } @@ -594,7 +625,8 @@ /** * */ -WebGLSpriteBatch.prototype.stop = function () { +WebGLSpriteBatch.prototype.stop = function () +{ this.flush(); this.dirty = true; }; @@ -602,7 +634,8 @@ /** * */ -WebGLSpriteBatch.prototype.start = function () { +WebGLSpriteBatch.prototype.start = function () +{ this.dirty = true; }; @@ -610,7 +643,8 @@ * Destroys the SpriteBatch. * */ -WebGLSpriteBatch.prototype.destroy = function () { +WebGLSpriteBatch.prototype.destroy = function () +{ this.renderer.gl.deleteBuffer(this.vertexBuffer); this.renderer.gl.deleteBuffer(this.indexBuffer); diff --git a/src/core/textures/BaseTexture.js b/src/core/textures/BaseTexture.js index 2bf77d4..513d358 100644 --- a/src/core/textures/BaseTexture.js +++ b/src/core/textures/BaseTexture.js @@ -10,7 +10,8 @@ * @param source {Image|Canvas} the source object of the texture. * @param [scaleMode=scaleModes.DEFAULT] {number} See {@link scaleModes} for possible values */ -function BaseTexture(source, scaleMode) { +function BaseTexture(source, scaleMode) +{ this.uuid = utils.uuid(); /** @@ -123,7 +124,8 @@ this._needsUpdate = false; // if no source passed don't try to load - if (source) { + if (source) + { this.loadSource(source); } @@ -149,13 +151,16 @@ Object.defineProperties(BaseTexture.prototype, { needsUpdate: { - get: function () { + get: function () + { return this._needsUpdate; }, - set: function (val) { + set: function (val) + { this._needsUpdate = val; - if (val) { + if (val) + { this.emit('update', this); } } @@ -171,9 +176,11 @@ * * The logic state after calling `loadSource` directly or indirectly (eg. `fromImage`, `new BaseTexture`) is: * - * if (texture.hasLoaded) { + * if (texture.hasLoaded) + { * // texture ready for use - * } else if (texture.isLoading) { + * } else if (texture.isLoading) + { * // listen to 'loaded' and/or 'error' events on texture * } else { * // not loading, not going to load UNLESS the source is reloaded @@ -183,12 +190,14 @@ * @protected * @param source {Image|Canvas} the source object of the texture. */ -BaseTexture.prototype.loadSource = function (source) { +BaseTexture.prototype.loadSource = function (source) +{ var wasLoading = this.isLoading; this.hasLoaded = false; this.isLoading = false; - if (wasLoading && this.source) { + if (wasLoading && this.source) + { this.source.onload = null; this.source.onerror = null; } @@ -196,20 +205,24 @@ this.source = source; // Apply source if loaded. Otherwise setup appropriate loading monitors. - if ((this.source.complete || this.source.getContext) && this.source.width && this.source.height) { + if ((this.source.complete || this.source.getContext) && this.source.width && this.source.height) + { this._sourceLoaded(); } - else if(!source.getContext) { + else if(!source.getContext) + { // Image fail / not ready this.isLoading = true; var scope = this; - source.onload = function () { + source.onload = function () + { source.onload = null; source.onerror = null; - if(!scope.isLoading) { + if(!scope.isLoading) + { return; } @@ -219,11 +232,13 @@ scope.emit('loaded', scope); }; - source.onerror = function () { + source.onerror = function () + { source.onload = null; source.onerror = null; - if(!scope.isLoading) { + if(!scope.isLoading) + { return; } @@ -234,24 +249,29 @@ // Per http://www.w3.org/TR/html5/embedded-content-0.html#the-img-element // "The value of `complete` can thus change while a script is executing." // So complete needs to be re-checked after the callbacks have been added.. - if (source.complete) { + if (source.complete) + { this.isLoading = false; // ..and if we're complete now, no need for callbacks source.onload = null; source.onerror = null; - if (source.width && source.height) { + if (source.width && source.height) + { this._sourceLoaded(); // If any previous subscribers possible - if (wasLoading) { + if (wasLoading) + { this.emit('loaded', this); } } - else { + else + { // If any previous subscribers possible - if (wasLoading) { + if (wasLoading) + { this.emit('error', this); } } @@ -265,7 +285,8 @@ * * @private */ -BaseTexture.prototype._sourceLoaded = function () { +BaseTexture.prototype._sourceLoaded = function () +{ this.hasLoaded = true; this.width = this.source.naturalWidth || this.source.width; @@ -278,16 +299,20 @@ * Destroys this base texture * */ -BaseTexture.prototype.destroy = function () { - if (this.imageUrl) { +BaseTexture.prototype.destroy = function () +{ + if (this.imageUrl) + { delete utils.BaseTextureCache[this.imageUrl]; delete utils.TextureCache[this.imageUrl]; this.imageUrl = null; - if (!navigator.isCocoonJS) { + if (!navigator.isCocoonJS) + { this.source.src = ''; } } - else if (this.source && this.source._pixiId) { + else if (this.source && this.source._pixiId) + { delete utils.BaseTextureCache[this.source._pixiId]; } this.source = null; @@ -301,7 +326,8 @@ * memory again. * */ -BaseTexture.prototype.dispose = function () { +BaseTexture.prototype.dispose = function () +{ this.emit('dispose', this); }; @@ -311,7 +337,8 @@ * * @param newSrc {string} the path of the image */ -BaseTexture.prototype.updateSourceImage = function (newSrc) { +BaseTexture.prototype.updateSourceImage = function (newSrc) +{ this.source.src = newSrc; this.loadSource(this.source); }; @@ -326,18 +353,22 @@ * @param [scaleMode=scaleModes.DEFAULT] {number} See {@link scaleModes} for possible values * @return BaseTexture */ -BaseTexture.fromImage = function (imageUrl, crossorigin, scaleMode) { +BaseTexture.fromImage = function (imageUrl, crossorigin, scaleMode) +{ var baseTexture = utils.BaseTextureCache[imageUrl]; - if (crossorigin === undefined && imageUrl.indexOf('data:') !== 0) { + if (crossorigin === undefined && imageUrl.indexOf('data:') !== 0) + { crossorigin = true; } - if (!baseTexture) { + if (!baseTexture) + { // new Image() breaks tex loading in some versions of Chrome. // See https://code.google.com/p/chromium/issues/detail?id=238071 var image = new Image();//document.createElement('img'); - if (crossorigin) { + if (crossorigin) + { image.crossOrigin = ''; } @@ -347,7 +378,8 @@ utils.BaseTextureCache[imageUrl] = baseTexture; // if there is an @2x at the end of the url we are going to assume its a highres image - if ( imageUrl.indexOf(CONST.RETINA_PREFIX + '.') !== -1) { + if ( imageUrl.indexOf(CONST.RETINA_PREFIX + '.') !== -1) + { baseTexture.resolution = 2; } } @@ -363,14 +395,17 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return BaseTexture */ -BaseTexture.fromCanvas = function (canvas, scaleMode) { - if (!canvas._pixiId) { +BaseTexture.fromCanvas = function (canvas, scaleMode) +{ + if (!canvas._pixiId) + { canvas._pixiId = 'canvas_' + utils.uuid(); } var baseTexture = utils.BaseTextureCache[canvas._pixiId]; - if (!baseTexture) { + if (!baseTexture) + { baseTexture = new BaseTexture(canvas, scaleMode); utils.BaseTextureCache[canvas._pixiId] = baseTexture; } diff --git a/src/core/textures/RenderTexture.js b/src/core/textures/RenderTexture.js index 6dad20f..53ae796 100644 --- a/src/core/textures/RenderTexture.js +++ b/src/core/textures/RenderTexture.js @@ -46,8 +46,10 @@ * @param [scaleMode] {number} See {@link scaleModes} for possible values * @param [resolution=1] {number} The resolution of the texture being generated */ -function RenderTexture(renderer, width, height, scaleMode, resolution) { - if (!renderer) { +function RenderTexture(renderer, width, height, scaleMode, resolution) +{ + if (!renderer) + { throw new Error('Unable to create RenderTexture, you must pass a renderer into the constructor.'); } @@ -133,7 +135,8 @@ */ this.renderer = renderer; - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { var gl = this.renderer.gl; this.textureBuffer = new FilterTexture(gl, this.width * this.resolution, this.height * this.resolution, this.baseTexture.scaleMode); @@ -142,7 +145,8 @@ this.render = this.renderWebGL; this.projection = new math.Point(this.width*0.5, -this.height*0.5); } - else { + else + { this.render = this.renderCanvas; this.textureBuffer = new CanvasBuffer(this.width* this.resolution, this.height* this.resolution); this.baseTexture.source = this.textureBuffer.canvas; @@ -167,8 +171,10 @@ * @param height {number} The height to resize to. * @param updateBase {boolean} Should the baseTexture.width and height values be resized as well? */ -RenderTexture.prototype.resize = function (width, height, updateBase) { - if (width === this.width && height === this.height) { +RenderTexture.prototype.resize = function (width, height, updateBase) +{ + if (width === this.width && height === this.height) + { return; } @@ -177,17 +183,20 @@ this.width = this.frame.width = this.crop.width = width; this.height = this.frame.height = this.crop.height = height; - if (updateBase) { + if (updateBase) + { this.baseTexture.width = this.width; this.baseTexture.height = this.height; } - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { this.projection.x = this.width / 2; this.projection.y = -this.height / 2; } - if (!this.valid) { + if (!this.valid) + { return; } @@ -198,12 +207,15 @@ * Clears the RenderTexture. * */ -RenderTexture.prototype.clear = function () { - if (!this.valid) { +RenderTexture.prototype.clear = function () +{ + if (!this.valid) + { return; } - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { this.renderer.gl.bindFramebuffer(this.renderer.gl.FRAMEBUFFER, this.textureBuffer.frameBuffer); } @@ -220,19 +232,23 @@ * @param [restoreWorldTransform=true] {boolean} If true the displayObject's worldTransform/worldAlpha and all children * transformations will be restored. Not restoring this information will be a little faster. */ -RenderTexture.prototype.renderWebGL = function (displayObject, matrix, clear, restoreWorldTransform) { - if (!this.valid) { +RenderTexture.prototype.renderWebGL = function (displayObject, matrix, clear, restoreWorldTransform) +{ + if (!this.valid) + { return; } - if (typeof restoreWorldTransform === 'undefined') { + if (typeof restoreWorldTransform === 'undefined') + { restoreWorldTransform = true; } var tempAlpha, tempTransform; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { tempAlpha = displayObject.worldAlpha; tempTransform = displayObject.worldTransform.toArray(); } @@ -245,7 +261,8 @@ wt.identity(); wt.translate(0, this.projection.y * 2); - if (matrix) { + if (matrix) + { wt.append(matrix); } @@ -258,7 +275,8 @@ var children = displayObject.children; var i, j; - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } @@ -269,7 +287,8 @@ gl.bindFramebuffer(gl.FRAMEBUFFER, this.textureBuffer.frameBuffer ); - if (clear) { + if (clear) + { this.textureBuffer.clear(); } @@ -279,11 +298,13 @@ this.renderer.spriteBatch.dirty = true; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { displayObject.worldAlpha = tempAlpha; displayObject.worldTransform.fromArray(tempTransform); - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } } @@ -300,26 +321,31 @@ * @param [restoreWorldTransform=true] {boolean} If true the displayObject's worldTransform/worldAlpha and all children * transformations will be restored. Not restoring this information will be a little faster. */ -RenderTexture.prototype.renderCanvas = function (displayObject, matrix, clear, restoreWorldTransform) { - if (!this.valid) { +RenderTexture.prototype.renderCanvas = function (displayObject, matrix, clear, restoreWorldTransform) +{ + if (!this.valid) + { return; } - if (typeof restoreWorldTransform === 'undefined') { + if (typeof restoreWorldTransform === 'undefined') + { restoreWorldTransform = true; } var tempAlpha, tempTransform; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { tempAlpha = displayObject.worldAlpha; tempTransform = displayObject.worldTransform.toArray(); } var wt = displayObject.worldTransform; wt.identity(); - if (matrix) { + if (matrix) + { wt.append(matrix); } @@ -330,11 +356,13 @@ var children = displayObject.children; var i, j; - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } - if (clear) { + if (clear) + { this.textureBuffer.clear(); } @@ -348,11 +376,13 @@ this.renderer.resolution = realResolution; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { displayObject.worldAlpha = tempAlpha; displayObject.worldTransform.fromArray(tempTransform); - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } } @@ -363,7 +393,8 @@ * * @return {Image} */ -RenderTexture.prototype.getImage = function () { +RenderTexture.prototype.getImage = function () +{ var image = new Image(); image.src = this.getBase64(); return image; @@ -374,7 +405,8 @@ * * @return {string} A base64 encoded string of the texture. */ -RenderTexture.prototype.getBase64 = function () { +RenderTexture.prototype.getBase64 = function () +{ return this.getCanvas().toDataURL(); }; @@ -383,8 +415,10 @@ * * @return {HTMLCanvasElement} A Canvas element with the texture rendered on. */ -RenderTexture.prototype.getCanvas = function () { - if (this.renderer.type === CONST.WEBGL_RENDERER) { +RenderTexture.prototype.getCanvas = function () +{ + if (this.renderer.type === CONST.WEBGL_RENDERER) + { var gl = this.renderer.gl; var width = this.textureBuffer.width; var height = this.textureBuffer.height; @@ -403,7 +437,8 @@ return tempCanvas.canvas; } - else { + else + { return this.textureBuffer.canvas; } }; diff --git a/src/core/textures/Texture.js b/src/core/textures/Texture.js index 3c65909..e97f0aa 100644 --- a/src/core/textures/Texture.js +++ b/src/core/textures/Texture.js @@ -17,7 +17,8 @@ * @param [crop] {Rectangle} The area of original texture * @param [trim] {Rectangle} Trimmed texture rectangle */ -function Texture(baseTexture, frame, crop, trim) { +function Texture(baseTexture, frame, crop, trim) +{ /** * Does this Texture have any frame data assigned to it? * @@ -25,12 +26,14 @@ */ this.noFrame = false; - if (!frame) { + if (!frame) + { this.noFrame = true; frame = new math.Rectangle(0, 0, 1, 1); } - if (baseTexture instanceof Texture) { + if (baseTexture instanceof Texture) + { baseTexture = baseTexture.baseTexture; } @@ -100,13 +103,16 @@ */ this.crop = crop || new math.Rectangle(0, 0, 1, 1); - if (baseTexture.hasLoaded) { - if (this.noFrame) { + if (baseTexture.hasLoaded) + { + if (this.noFrame) + { frame = new math.Rectangle(0, 0, baseTexture.width, baseTexture.height); } this.frame = frame; } - else { + else + { baseTexture.addEventListener('loaded', this.onBaseTextureLoaded.bind(this)); } } @@ -118,19 +124,23 @@ Object.defineProperties(Texture.prototype, { needsUpdate: { - get: function () { + get: function () + { return this.baseTexture.needsUpdate; }, - set: function (val) { + set: function (val) + { this.baseTexture.needsUpdate = val; } }, frame: { - get: function () { + get: function () + { return this._frame; }, - set: function (frame) { + set: function (frame) + { this._frame = frame; this.noFrame = false; @@ -143,20 +153,23 @@ 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 (!this.trim && (frame.x + frame.width > this.baseTexture.width || frame.y + frame.height > this.baseTexture.height)) + { throw new Error('Texture Error: frame does not fit inside the base Texture dimensions ' + this); } this.valid = frame && frame.width && frame.height && this.baseTexture.source && this.baseTexture.hasLoaded; - if (this.trim) { + 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) { + if (this.valid) + { this._updateUvs(); } } @@ -168,11 +181,13 @@ * * @private */ -Texture.prototype.onBaseTextureLoaded = function () { +Texture.prototype.onBaseTextureLoaded = function () +{ var baseTexture = this.baseTexture; baseTexture.removeEventListener('loaded', this.onLoaded); - if (this.noFrame) { + if (this.noFrame) + { this.frame = new math.Rectangle(0, 0, baseTexture.width, baseTexture.height); } @@ -184,8 +199,10 @@ * * @param destroyBase {boolean} Whether to destroy the base texture as well */ -Texture.prototype.destroy = function (destroyBase) { - if (destroyBase) { +Texture.prototype.destroy = function (destroyBase) +{ + if (destroyBase) + { this.baseTexture.destroy(); } @@ -197,8 +214,10 @@ * * @private */ -Texture.prototype._updateUvs = function () { - if (!this._uvs) { +Texture.prototype._updateUvs = function () +{ + if (!this._uvs) + { this._uvs = new TextureUvs(); } @@ -229,10 +248,12 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return Texture */ -Texture.fromImage = function (imageUrl, crossorigin, scaleMode) { +Texture.fromImage = function (imageUrl, crossorigin, scaleMode) +{ var texture = utils.TextureCache[imageUrl]; - if (!texture) { + if (!texture) + { texture = new Texture(BaseTexture.fromImage(imageUrl, crossorigin, scaleMode)); utils.TextureCache[imageUrl] = texture; } @@ -248,9 +269,11 @@ * @param frameId {string} The frame id of the texture * @return Texture */ -Texture.fromFrame = function (frameId) { +Texture.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache '); } return texture; @@ -264,7 +287,8 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return {Texture} */ -Texture.fromCanvas = function (canvas, scaleMode) { +Texture.fromCanvas = function (canvas, scaleMode) +{ return new Texture(BaseTexture.fromCanvas(canvas, scaleMode)); }; @@ -276,7 +300,8 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return {Texture} A Texture */ -Texture.fromVideo = function (video, scaleMode) { +Texture.fromVideo = function (video, scaleMode) +{ return new Texture(VideoBaseTexture.baseTextureFromVideo(video, scaleMode)); }; @@ -287,7 +312,8 @@ * @param texture {Texture} The Texture to add to the cache. * @param id {string} The id that the texture will be stored against. */ -Texture.addTextureToCache = function (texture, id) { +Texture.addTextureToCache = function (texture, id) +{ utils.TextureCache[id] = texture; }; @@ -298,7 +324,8 @@ * @param id {string} The id of the texture to be removed * @return {Texture} The texture that was removed */ -Texture.removeTextureFromCache = function (id) { +Texture.removeTextureFromCache = function (id) +{ var texture = utils.TextureCache[id]; delete utils.TextureCache[id]; diff --git a/src/core/textures/TextureUvs.js b/src/core/textures/TextureUvs.js index b9bbb58..5424d52 100644 --- a/src/core/textures/TextureUvs.js +++ b/src/core/textures/TextureUvs.js @@ -1,4 +1,5 @@ -function TextureUvs() { +function TextureUvs() +{ this.x0 = 0; this.y0 = 0; diff --git a/src/core/textures/VideoBaseTexture.js b/src/core/textures/VideoBaseTexture.js index e3e0c5a..1a826a9 100644 --- a/src/core/textures/VideoBaseTexture.js +++ b/src/core/textures/VideoBaseTexture.js @@ -12,15 +12,18 @@ * @param source {HTMLVideoElement} * @param [scaleMode] {number} See {@link scaleModes} for possible values */ -function VideoBaseTexture(source, scaleMode) { - if (!source){ +function VideoBaseTexture(source, scaleMode) +{ + if (!source) + { throw new Error('No video source element specified.'); } // hook in here to check if video is already available. // BaseTexture looks for a source.complete boolean, plus width & height. - if ((source.readyState === source.HAVE_ENOUGH_DATA || source.readyState === source.HAVE_FUTURE_DATA) && source.width && source.height) { + if ((source.readyState === source.HAVE_ENOUGH_DATA || source.readyState === source.HAVE_FUTURE_DATA) && source.width && source.height) + { source.complete = true; } @@ -31,7 +34,8 @@ this._boundOnUpdate = this._onUpdate.bind(this); this._boundOnCanPlay = this._onCanPlay.bind(this); - if (!source.complete) { + if (!source.complete) + { source.addEventListener('canplay', this._boundOnCanPlay); source.addEventListener('canplaythrough', this._boundOnCanPlay); @@ -47,28 +51,35 @@ VideoBaseTexture.prototype.constructor = VideoBaseTexture; module.exports = VideoBaseTexture; -VideoBaseTexture.prototype._onUpdate = function () { - if (this.autoUpdate) { +VideoBaseTexture.prototype._onUpdate = function () +{ + if (this.autoUpdate) + { window.requestAnimationFrame(this._boundOnUpdate); this.needsUpdate = true; } }; -VideoBaseTexture.prototype._onPlayStart = function () { - if (!this.autoUpdate) { +VideoBaseTexture.prototype._onPlayStart = function () +{ + if (!this.autoUpdate) + { window.requestAnimationFrame(this._boundOnUpdate); this.autoUpdate = true; } }; -VideoBaseTexture.prototype._onPlayStop = function () { +VideoBaseTexture.prototype._onPlayStop = function () +{ this.autoUpdate = false; }; -VideoBaseTexture.prototype._onCanPlay = function () { +VideoBaseTexture.prototype._onCanPlay = function () +{ this.hasLoaded = true; - if (this.source) { + if (this.source) + { this.source.removeEventListener('canplay', this._boundOnCanPlay); this.source.removeEventListener('canplaythrough', this._boundOnCanPlay); @@ -78,15 +89,18 @@ this.source.play(); // prevent multiple loaded dispatches.. - if(!this.__loaded){ + if(!this.__loaded) + { this.__loaded = true; this.emit('loaded', this); } } }; -VideoBaseTexture.prototype.destroy = function () { - if (this.source && this.source._pixiId) { +VideoBaseTexture.prototype.destroy = function () +{ + if (this.source && this.source._pixiId) + { utils.BaseTextureCache[ this.source._pixiId ] = null; delete utils.BaseTextureCache[ this.source._pixiId ]; @@ -105,14 +119,17 @@ * @param scaleMode {number} See {@link scaleModes} for possible values * @return {VideoBaseTexture} */ -VideoBaseTexture.fromVideo = function (video, scaleMode) { - if (!video._pixiId) { +VideoBaseTexture.fromVideo = function (video, scaleMode) +{ + if (!video._pixiId) + { video._pixiId = 'video_' + utils.uuid(); } var baseTexture = utils.BaseTextureCache[video._pixiId]; - if (!baseTexture) { + if (!baseTexture) + { baseTexture = new VideoBaseTexture(video, scaleMode); utils.BaseTextureCache[ video._pixiId ] = baseTexture; } @@ -147,17 +164,21 @@ * @param scaleMode {number} See {@link scaleModes} for possible values * @return {VideoBaseTexture} */ -VideoBaseTexture.fromUrl = function (videoSrc, scaleMode) { +VideoBaseTexture.fromUrl = function (videoSrc, scaleMode) +{ var video = document.createElement('video'); // array of objects or strings - if (Array.isArray(videoSrc)) { - for (var i = 0; i < videoSrc.length; ++i) { + if (Array.isArray(videoSrc)) + { + for (var i = 0; i < videoSrc.length; ++i) + { video.appendChild(createSource(videoSrc.src || videoSrc, videoSrc.mime)); } } // single object or string - else { + else + { video.appendChild(createSource(videoSrc.src || videoSrc, videoSrc.mime)); } @@ -169,8 +190,10 @@ VideoBaseTexture.fromUrls = VideoBaseTexture.fromUrl; -function createSource(path, type) { - if (!type) { +function createSource(path, type) +{ + if (!type) + { type = 'video/' + path.substr(path.lastIndexOf('.') + 1); } diff --git a/src/core/utils/EventData.js b/src/core/utils/EventData.js index 5d55a22..8cdf701 100644 --- a/src/core/utils/EventData.js +++ b/src/core/utils/EventData.js @@ -7,7 +7,8 @@ * @param name {string} The string name of the event that was triggered * @param data {object} Arbitrary event data to pass along */ -function EventData(target, name, data) { +function EventData(target, name, data) +{ // for duck typing in the ".on()" function this.__isEventObject = true; @@ -71,7 +72,8 @@ * Stops the propagation of events up the scene graph (prevents bubbling). * */ -EventData.prototype.stopPropagation = function stopPropagation() { +EventData.prototype.stopPropagation = function stopPropagation() +{ this.stopped = true; }; @@ -79,6 +81,7 @@ * Stops the propagation of events to sibling listeners (no longer calls any listeners). * */ -EventData.prototype.stopImmediatePropagation = function stopImmediatePropagation() { +EventData.prototype.stopImmediatePropagation = function stopImmediatePropagation() +{ this.stoppedImmediate = true; }; diff --git a/src/core/utils/EventTarget.js b/src/core/utils/EventTarget.js index 7ae8820..671a151 100644 --- a/src/core/utils/EventTarget.js +++ b/src/core/utils/EventTarget.js @@ -13,14 +13,16 @@ * var em = new MyEmitter(); * em.emit('eventName', 'some data', 'some more data', {}, null, ...); */ -function eventTarget(obj) { +function eventTarget(obj) +{ /** * Return a list of assigned event listeners. * * @param eventName {string} The events that should be listed. * @return {Array} An array of listener functions */ - obj.listeners = function listeners(eventName) { + obj.listeners = function listeners(eventName) + { this._listeners = this._listeners || {}; return this._listeners[eventName] ? this._listeners[eventName].slice() : []; @@ -33,22 +35,26 @@ * @param eventName {string} The name of the event. * @return {boolean} Indication if we've emitted an event. */ - obj.emit = obj.dispatchEvent = function emit(eventName, data) { + obj.emit = obj.dispatchEvent = function emit(eventName, data) + { this._listeners = this._listeners || {}; // fast return when there are no listeners - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return; } //backwards compat with old method ".emit({ type: 'something' })" - if (typeof eventName === 'object') { + if (typeof eventName === 'object') + { data = eventName; eventName = eventName.type; } //ensure we are using a real pixi event - if (!data || data.__isEventObject !== true) { + if (!data || data.__isEventObject !== true) + { data = new EventData(this, eventName, data); } @@ -58,23 +64,27 @@ fn = listeners[0], i; - for (i = 0; i < length; fn = listeners[++i]) { + for (i = 0; i < length; fn = listeners[++i]) + { //call the event listener fn.call(this, data); //if "stopImmediatePropagation" is called, stop calling sibling events - if (data.stoppedImmediate) { + if (data.stoppedImmediate) + { return this; } } //if "stopPropagation" is called then don't bubble the event - if (data.stopped) { + if (data.stopped) + { return this; } //bubble this event up the scene graph - if (this.parent && this.parent.emit) { + if (this.parent && this.parent.emit) + { this.parent.emit.call(this.parent, eventName, data); } @@ -88,7 +98,8 @@ * @param eventName {string} Name of the event. * @param callback {Functon} fn Callback function. */ - obj.on = obj.addEventListener = function on(eventName, fn) { + obj.on = obj.addEventListener = function on(eventName, fn) + { this._listeners = this._listeners || {}; (this._listeners[eventName] = this._listeners[eventName] || []) @@ -103,11 +114,13 @@ * @param eventName {string} Name of the event. * @param callback {Function} Callback function. */ - obj.once = function once(eventName, fn) { + obj.once = function once(eventName, fn) + { this._listeners = this._listeners || {}; var self = this; - function onceHandlerWrapper() { + function onceHandlerWrapper() + { fn.apply(self.off(eventName, onceHandlerWrapper), arguments); } onceHandlerWrapper._originalHandler = fn; @@ -122,23 +135,28 @@ * @param eventName {string} The event we want to remove. * @param callback {Function} The listener that we need to find. */ - obj.off = obj.removeEventListener = function off(eventName, fn) { + obj.off = obj.removeEventListener = function off(eventName, fn) + { this._listeners = this._listeners || {}; - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return this; } var list = this._listeners[eventName], i = fn ? list.length : 0; - while(i-- > 0) { - if (list[i] === fn || list[i]._originalHandler === fn) { + while(i-- > 0) + { + if (list[i] === fn || list[i]._originalHandler === fn) + { list.splice(i, 1); } } - if (list.length === 0) { + if (list.length === 0) + { delete this._listeners[eventName]; } @@ -150,10 +168,12 @@ * * @param eventName {string} The event you want to remove all listeners for. */ - obj.removeAllListeners = function removeAllListeners(eventName) { + obj.removeAllListeners = function removeAllListeners(eventName) + { this._listeners = this._listeners || {}; - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return this; } @@ -169,7 +189,8 @@ * * @param object {object} The obj to mix into */ - mixin: function mixin(obj) { + mixin: function mixin(obj) + { eventTarget(obj); } }; diff --git a/src/core/utils/PolyK.js b/src/core/utils/PolyK.js index 7325141..5e20c2b 100644 --- a/src/core/utils/PolyK.js +++ b/src/core/utils/PolyK.js @@ -47,7 +47,8 @@ * Triangulates shapes for webGL graphic fills. * */ -PolyK.Triangulate = function (p) { +PolyK.Triangulate = function (p) +{ var sign = true; var n = p.length >> 1; @@ -59,7 +60,8 @@ i = 0; var al = n; - while(al > 3) { + while(al > 3) + { var i0 = avl[(i+0)%al]; var i1 = avl[(i+1)%al]; var i2 = avl[(i+2)%al]; @@ -69,29 +71,35 @@ var cx = p[2*i2], cy = p[2*i2+1]; var earFound = false; - if (PolyK._convex(ax, ay, bx, by, cx, cy, sign)) { + if (PolyK._convex(ax, ay, bx, by, cx, cy, sign)) + { earFound = true; - for (var j = 0; j < al; j++) { + for (var j = 0; j < al; j++) + { var vi = avl[j]; if (vi === i0 || vi === i1 || vi === i2) continue; - if (PolyK._PointInTriangle(p[2*vi], p[2*vi+1], ax, ay, bx, by, cx, cy)) { + if (PolyK._PointInTriangle(p[2*vi], p[2*vi+1], ax, ay, bx, by, cx, cy)) + { earFound = false; break; } } } - if (earFound) { + if (earFound) + { tgs.push(i0, i1, i2); avl.splice((i+1)%al, 1); al--; i = 0; } - else if (i++ > 3*al) { + else if (i++ > 3*al) + { // need to flip flip reverse it! // reset! - if (sign) { + if (sign) + { tgs = []; avl = []; for (i = 0; i < n; i++) avl.push(i); @@ -101,7 +109,8 @@ sign = false; } - else { + else + { // window.console.log("PIXI Warning: shape too complex to fill"); return null; } @@ -126,7 +135,8 @@ * @private * @return {boolean} */ -PolyK._PointInTriangle = function (px, py, ax, ay, bx, by, cx, cy) { +PolyK._PointInTriangle = function (px, py, ax, ay, bx, by, cx, cy) +{ var v0x = cx-ax; var v0y = cy-ay; var v1x = bx-ax; @@ -154,6 +164,7 @@ * @private * @return {boolean} */ -PolyK._convex = function (ax, ay, bx, by, cx, cy, sign) { +PolyK._convex = function (ax, ay, bx, by, cx, cy, sign) +{ return ((ay-by)*(cx-bx) + (bx-ax)*(cy-by) >= 0) === sign; }; diff --git a/src/core/utils/index.js b/src/core/utils/index.js index ade9831..bfae7ae 100644 --- a/src/core/utils/index.js +++ b/src/core/utils/index.js @@ -16,7 +16,8 @@ * * @return {number} The next uuid to use. */ - uuid: function () { + uuid: function () + { return ++utils._uid; }, @@ -26,7 +27,8 @@ * @param hex {number} * @return {number[]} An array representing the [R, G, B] of the color. */ - hex2rgb: function (hex, out) { + hex2rgb: function (hex, out) + { out = out || []; out[0] = (hex >> 16 & 0xFF) / 255; @@ -42,7 +44,8 @@ * @param hex {number} * @return {string} The string color. */ - hex2string: function (hex) { + hex2string: function (hex) + { hex = hex.toString(16); hex = '000000'.substr(0, 6 - hex.length) + hex; @@ -55,7 +58,8 @@ * @param rgb {number[]} * @return {number} The color number */ - rgb2hex: function (rgb) { + rgb2hex: function (rgb) + { return ((rgb[0]*255 << 16) + (rgb[1]*255 << 8) + rgb[2]*255); }, @@ -64,8 +68,10 @@ * * @return {boolean} whether they are supported */ - canUseNewCanvasBlendModes: function () { - if (typeof document === 'undefined') { + canUseNewCanvasBlendModes: function () + { + if (typeof document === 'undefined') + { return false; } @@ -93,15 +99,19 @@ * @param number {number} * @return {number} the closest number that is a power of two */ - getNextPowerOfTwo: function (number) { + getNextPowerOfTwo: function (number) + { // see: http://en.wikipedia.org/wiki/Power_of_two#Fast_algorithm_to_check_if_a_positive_number_is_a_power_of_two - if (number > 0 && (number & (number - 1)) === 0) { + if (number > 0 && (number & (number - 1)) === 0) + { return number; } - else { + else + { var result = 1; - while (result < number) { + while (result < number) + { result <<= 1; } @@ -116,7 +126,8 @@ * @param height {number} * @return {boolean} */ - isPowerOfTwo: function (width, height) { + isPowerOfTwo: function (width, height) + { return (width > 0 && (width & (width - 1)) === 0 && height > 0 && (height & (height - 1)) === 0); }, @@ -130,12 +141,15 @@ * @constant * @static */ - sayHello: function (type) { - if (utils._saidHello) { + sayHello: function (type) + { + if (utils._saidHello) + { return; } - if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) { + if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) + { var args = [ '%c %c %c Pixi.js ' + CONST.VERSION + ' - ' + type + ' %c ' + ' %c ' + ' http://www.pixijs.com/ %c %c ♥%c♥%c♥ ', 'background: #ff66a5', @@ -151,7 +165,8 @@ console.log.apply(console, args); //jshint ignore:line } - else if (window.console) { + else if (window.console) + { console.log('Pixi.js ' + CONST.VERSION + ' - ' + type + ' - http://www.pixijs.com/'); //jshint ignore:line } @@ -166,15 +181,19 @@ * @class * @namespace PIXI */ - AjaxRequest: function () { + AjaxRequest: function () + { var activexmodes = ['Msxml2.XMLHTTP.6.0', 'Msxml2.XMLHTTP.3.0', 'Microsoft.XMLHTTP']; //activeX versions to check for in IE - if (window.ActiveXObject) { //Test for support for ActiveXObject in IE first (as XMLHttpRequest in IE7 is broken) - for (var i=0; i= this.textures.length) { + else if (round >= this.textures.length) + { this.gotoAndStop(this.textures.length - 1); - if (this.onComplete) { + if (this.onComplete) + { this.onComplete(); } } @@ -167,10 +182,12 @@ * @static * @param frames {string[]} the array of frames ids the movieclip will use as its texture frames */ -MovieClip.fromFrames = function (frames) { +MovieClip.fromFrames = function (frames) +{ var textures = []; - for (var i = 0; i < frames.length; ++i) { + for (var i = 0; i < frames.length; ++i) + { textures.push(new core.Texture.fromFrame(frames[i])); } @@ -183,10 +200,12 @@ * @static * @param images {string[]} the array of image urls the movieclip will use as its texture frames */ -MovieClip.fromImages = function (images) { +MovieClip.fromImages = function (images) +{ var textures = []; - for (var i = 0; i < images.length; ++i) { + for (var i = 0; i < images.length; ++i) + { textures.push(new core.Texture.fromImage(images[i])); } diff --git a/src/extras/Rope.js b/src/extras/Rope.js index c157ec4..9c87bc0 100644 --- a/src/extras/Rope.js +++ b/src/extras/Rope.js @@ -9,7 +9,8 @@ * @param {Array} points - An array of {Point}. * */ -function Rope(texture, points) { +function Rope(texture, points) +{ Strip.call(this, texture); this.points = points; @@ -31,10 +32,12 @@ * Refreshes * */ -Rope.prototype.refresh = function () { +Rope.prototype.refresh = function () +{ var points = this.points; - if (points.length < 1) { + if (points.length < 1) + { return; } @@ -59,20 +62,23 @@ var total = points.length, point, index, amount; - for (var i = 1; i < total; i++) { + for (var i = 1; i < total; i++) + { point = points[i]; index = i * 4; // time to do some smart drawing! amount = i / (total-1); - if (i%2) { + if (i%2) + { uvs[index] = amount; uvs[index+1] = 0; uvs[index+2] = amount; uvs[index+3] = 1; } - else { + else + { uvs[index] = amount; uvs[index+1] = 0; @@ -95,10 +101,12 @@ * * @private */ -Rope.prototype.updateTransform = function () { +Rope.prototype.updateTransform = function () +{ var points = this.points; - if (points.length < 1) { + if (points.length < 1) + { return; } @@ -113,14 +121,17 @@ var total = points.length, point, index, ratio, perpLength, num; - for (var i = 0; i < total; i++) { + for (var i = 0; i < total; i++) + { point = points[i]; index = i * 4; - if (i < points.length-1) { + if (i < points.length-1) + { nextPoint = points[i+1]; } - else { + else + { nextPoint = point; } @@ -129,7 +140,8 @@ ratio = (1 - (i / (total-1))) * 10; - if (ratio > 1) { + if (ratio > 1) + { ratio = 1; } @@ -157,7 +169,8 @@ * * @param texture {Texture} the texture that will be used */ -Rope.prototype.setTexture = function (texture) { +Rope.prototype.setTexture = function (texture) +{ // stop current texture this.texture = texture; //this.updateFrame = true; diff --git a/src/extras/Strip.js b/src/extras/Strip.js index c5e378f..57691b5 100644 --- a/src/extras/Strip.js +++ b/src/extras/Strip.js @@ -10,7 +10,8 @@ * @param height {number} the height * */ -function Strip(texture) { +function Strip(texture) +{ core.DisplayObjectContainer.call(this); /** @@ -70,9 +71,11 @@ * * @param renderer {WebGLRenderer} */ -Strip.prototype.renderWebGL = function (renderer) { +Strip.prototype.renderWebGL = function (renderer) +{ // if the sprite is not visible or the alpha is 0 then no need to render this element - if (!this.visible || this.alpha <= 0) { + if (!this.visible || this.alpha <= 0) + { return; } @@ -81,7 +84,8 @@ renderer.spriteBatch.stop(); // init! init! - if (!this._vertexBuffer) { + if (!this._vertexBuffer) + { this._initWebGL(renderer); } @@ -96,7 +100,8 @@ //TODO check culling }; -Strip.prototype._initWebGL = function (renderer) { +Strip.prototype._initWebGL = function (renderer) +{ // build the strip! var gl = renderer.gl; @@ -118,7 +123,8 @@ gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this.indices, gl.STATIC_DRAW); }; -Strip.prototype._renderStrip = function (renderer) { +Strip.prototype._renderStrip = function (renderer) +{ var gl = renderer.gl; var projection = renderer.projection, offset = renderer.offset, @@ -137,7 +143,8 @@ gl.uniform2f(shader.offsetVector, -offset.x, -offset.y); gl.uniform1f(shader.alpha, this.worldAlpha); - if (!this.dirty) { + if (!this.dirty) + { gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexBuffer); gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); @@ -150,10 +157,12 @@ gl.activeTexture(gl.TEXTURE0); // check if a texture is dirty.. - if (this.texture.baseTexture._dirty[gl.id]) { + if (this.texture.baseTexture._dirty[gl.id]) + { renderer.updateTexture(this.texture.baseTexture); } - else { + else + { // bind the current texture gl.bindTexture(gl.TEXTURE_2D, this.texture.baseTexture._glTextures[gl.id]); } @@ -163,7 +172,8 @@ } - else { + else + { this.dirty = false; gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexBuffer); @@ -178,10 +188,12 @@ gl.activeTexture(gl.TEXTURE0); // check if a texture is dirty.. - if (this.texture.baseTexture._dirty[gl.id]) { + if (this.texture.baseTexture._dirty[gl.id]) + { renderer.updateTexture(this.texture.baseTexture); } - else { + else + { gl.bindTexture(gl.TEXTURE_2D, this.texture.baseTexture._glTextures[gl.id]); } @@ -203,27 +215,33 @@ * * @param renderer {CanvasRenderer} */ -Strip.prototype.renderCanvas = function (renderer) { +Strip.prototype.renderCanvas = function (renderer) +{ var context = renderer.context; var transform = this.worldTransform; - if (renderer.roundPixels) { + if (renderer.roundPixels) + { context.setTransform(transform.a, transform.b, transform.c, transform.d, transform.tx | 0, transform.ty | 0); } - else { + else + { context.setTransform(transform.a, transform.b, transform.c, transform.d, transform.tx, transform.ty); } - if (this.drawMode === Strip.DrawModes.TRIANGLE_STRIP) { + if (this.drawMode === Strip.DrawModes.TRIANGLE_STRIP) + { this._renderCanvasTriangleStrip(context); } - else { + else + { this._renderCanvasTriangles(context); } }; -Strip.prototype._renderCanvasTriangleStrip = function (context) { +Strip.prototype._renderCanvasTriangleStrip = function (context) +{ // draw triangles!! var vertices = this.vertices; var uvs = this.uvs; @@ -231,14 +249,16 @@ var length = vertices.length / 2; // this.count++; - for (var i = 0; i < length - 2; i++) { + for (var i = 0; i < length - 2; i++) + { // draw some triangles! var index = i * 2; this._renderCanvasDrawTriangle(context, vertices, uvs, index, (index + 2), (index + 4)); } }; -Strip.prototype._renderCanvasTriangles = function (context) { +Strip.prototype._renderCanvasTriangles = function (context) +{ // draw triangles!! var vertices = this.vertices; var uvs = this.uvs; @@ -247,14 +267,16 @@ var length = indices.length; // this.count++; - for (var i = 0; i < length; i += 3) { + for (var i = 0; i < length; i += 3) + { // draw some triangles! var index0 = indices[i] * 2, index1 = indices[i + 1] * 2, index2 = indices[i + 2] * 2; this._renderCanvasDrawTriangle(context, vertices, uvs, index0, index1, index2); } }; -Strip.prototype._renderCanvasDrawTriangle = function (context, vertices, uvs, index0, index1, index2) { +Strip.prototype._renderCanvasDrawTriangle = function (context, vertices, uvs, index0, index1, index2) +{ var textureSource = this.texture.baseTexture.source; var textureWidth = this.texture.width; var textureHeight = this.texture.height; @@ -265,7 +287,8 @@ var u0 = uvs[index0] * textureWidth, u1 = uvs[index1] * textureWidth, u2 = uvs[index2] * textureWidth; var v0 = uvs[index0 + 1] * textureHeight, v1 = uvs[index1 + 1] * textureHeight, v2 = uvs[index2 + 1] * textureHeight; - if (this.canvasPadding > 0) { + if (this.canvasPadding > 0) + { var paddingX = this.canvasPadding / this.worldTransform.a; var paddingY = this.canvasPadding / this.worldTransform.d; var centerX = (x0 + x1 + x2) / 3; @@ -332,7 +355,8 @@ * @param strip {Strip} The Strip to render * @private */ -Strip.prototype.renderStripFlat = function (strip) { +Strip.prototype.renderStripFlat = function (strip) +{ var context = this.context; var vertices = strip.vertices; @@ -340,7 +364,8 @@ // this.count++; context.beginPath(); - for (var i=1; i < length-2; i++) { + for (var i=1; i < length-2; i++) + { // draw some triangles! var index = i*2; @@ -358,7 +383,8 @@ }; /* -Strip.prototype.setTexture = function (texture) { +Strip.prototype.setTexture = function (texture) +{ //TODO SET THE TEXTURES //TODO VISIBILITY @@ -377,7 +403,8 @@ * @private */ -Strip.prototype.onTextureUpdate = function () { +Strip.prototype.onTextureUpdate = function () +{ this.updateFrame = true; }; @@ -387,7 +414,8 @@ * @param matrix {Matrix} the transformation matrix of the sprite * @return {Rectangle} the framing rectangle */ -Strip.prototype.getBounds = function (matrix) { +Strip.prototype.getBounds = function (matrix) +{ var worldTransform = matrix || this.worldTransform; var a = worldTransform.a; @@ -404,7 +432,8 @@ var minY = Infinity; var vertices = this.vertices; - for (var i = 0, n = vertices.length; i < n; i += 2) { + for (var i = 0, n = vertices.length; i < n; i += 2) + { var rawX = vertices[i], rawY = vertices[i + 1]; var x = (a * rawX) + (c * rawY) + tx; var y = (d * rawY) + (b * rawX) + ty; @@ -416,7 +445,8 @@ maxY = y > maxY ? y : maxY; } - if (minX === -Infinity || maxY === Infinity) { + if (minX === -Infinity || maxY === Infinity) + { return core.math.Rectangle.EMPTY; } diff --git a/src/extras/TilingSprite.js b/src/extras/TilingSprite.js index 3ac22df..31da393 100644 --- a/src/extras/TilingSprite.js +++ b/src/extras/TilingSprite.js @@ -10,7 +10,8 @@ * @param width {number} the width of the tiling sprite * @param height {number} the height of the tiling sprite */ -function TilingSprite(texture, width, height) { +function TilingSprite(texture, width, height) +{ core.Sprite.call( this, texture); /** @@ -86,10 +87,12 @@ * @memberof TilingSprite# */ width: { - get: function () { + get: function () + { return this._width; }, - set: function (value) { + set: function (value) + { this._width = value; } }, @@ -101,20 +104,25 @@ * @memberof TilingSprite# */ height: { - get: function () { + get: function () + { return this._height; }, - set: function (value) { + set: function (value) + { this._height = value; } }, texture: { - get: function () { + get: function () + { return this._texture; }, - set: function (value) { - if (this._texture === value) { + set: function (value) + { + if (this._texture === value) + { return; } @@ -130,51 +138,61 @@ * * @param renderer {WebGLRenderer} */ -TilingSprite.prototype.renderWebGL = function (renderer) { - if (!this.visible || this.alpha <= 0) { +TilingSprite.prototype.renderWebGL = function (renderer) +{ + if (!this.visible || this.alpha <= 0) + { return; } var i, j; - if (this._mask) { + if (this._mask) + { renderer.spriteBatch.stop(); renderer.maskManager.pushMask(this.mask, renderer); renderer.spriteBatch.start(); } - if (this._filters) { + if (this._filters) + { renderer.spriteBatch.flush(); renderer.filterManager.pushFilter(this._filterBlock); } - if (!this.tilingTexture || this.refreshTexture) { + if (!this.tilingTexture || this.refreshTexture) + { this.generateTilingTexture(true); - if (this.tilingTexture && this.tilingTexture.needsUpdate) { + if (this.tilingTexture && this.tilingTexture.needsUpdate) + { //TODO - tweaking renderer.updateTexture(this.tilingTexture.baseTexture); this.tilingTexture.needsUpdate = false; // this.tilingTexture._uvs = null; } } - else { + else + { renderer.spriteBatch.renderTilingSprite(this); } // simple render children! - for (i=0,j=this.children.length; i= 0 && index <= this.children.length) { - if (child.parent) { + if (index >= 0 && index <= this.children.length) + { + if (child.parent) + { child.parent.removeChild(child); } @@ -154,7 +173,8 @@ return child; } - else { + else + { throw new Error(child + 'addChildAt: The index '+ index +' supplied is out of bounds ' + this.children.length); } }; @@ -165,15 +185,18 @@ * @param child {DisplayObject} * @param child2 {DisplayObject} */ -DisplayObjectContainer.prototype.swapChildren = function (child, child2) { - if (child === child2) { +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) { + if (index1 < 0 || index2 < 0) + { throw new Error('swapChildren: Both the supplied DisplayObjects must be a child of the caller.'); } @@ -187,10 +210,12 @@ * @param child {DisplayObject} The DisplayObject instance to identify * @return {Number} The index position of the child display object to identify */ -DisplayObjectContainer.prototype.getChildIndex = function (child) { +DisplayObjectContainer.prototype.getChildIndex = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { throw new Error('The supplied DisplayObject must be a child of the caller'); } @@ -203,8 +228,10 @@ * @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 */ -DisplayObjectContainer.prototype.setChildIndex = function (child, index) { - if (index < 0 || index >= this.children.length) { +DisplayObjectContainer.prototype.setChildIndex = function (child, index) +{ + if (index < 0 || index >= this.children.length) + { throw new Error('The supplied index is out of bounds'); } @@ -220,8 +247,10 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child at the given index, if any. */ -DisplayObjectContainer.prototype.getChildAt = function (index) { - if (index < 0 || index >= this.children.length) { +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'); } @@ -234,10 +263,12 @@ * @param child {DisplayObject} The DisplayObject to remove * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChild = function (child) { +DisplayObjectContainer.prototype.removeChild = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { return; } @@ -250,7 +281,8 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChildAt = function (index) { +DisplayObjectContainer.prototype.removeChildAt = function (index) +{ var child = this.getChildAt(index); child.parent = null; @@ -265,24 +297,29 @@ * @param beginIndex {Number} The beginning position. Default value is 0. * @param endIndex {Number} The ending position. Default value is size of the container. */ -DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) { +DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) +{ var begin = beginIndex || 0; var end = typeof endIndex === 'number' ? endIndex : this.children.length; var range = end - begin; - if (range > 0 && range <= end) { + if (range > 0 && range <= end) + { var removed = this.children.splice(begin, range); - for (var i = 0; i < removed.length; ++i) { + for (var i = 0; i < removed.length; ++i) + { removed[i].parent = null; } return removed; } - else if (range === 0 && this.children.length === 0) { + else if (range === 0 && this.children.length === 0) + { return []; } - else { + else + { throw new RangeError('removeChildren: numeric values are outside the acceptable range.'); } }; @@ -291,7 +328,8 @@ * Generates and updates the cached sprite for this object. * */ -DisplayObjectContainer.prototype.updateCachedSprite = function () { +DisplayObjectContainer.prototype.updateCachedSprite = function () +{ this._generateCachedSprite(); }; @@ -304,7 +342,8 @@ * @param renderer {CanvasRenderer|WebGLRenderer} The renderer used to generate the texture. * @return {Texture} a texture of the graphics object */ -DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) { +DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) +{ var bounds = this.getLocalBounds(); var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0, renderer, scaleMode, resolution); @@ -322,18 +361,22 @@ * * @private */ -DisplayObjectContainer.prototype.updateTransform = function () { - if (!this.visible) { +DisplayObjectContainer.prototype.updateTransform = function () +{ + if (!this.visible) + { return; } this.displayObjectUpdateTransform(); - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { return; } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } }; @@ -346,8 +389,10 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getBounds = function () { - if (this.children.length === 0) { +DisplayObjectContainer.prototype.getBounds = function () +{ + if (this.children.length === 0) + { return math.Rectangle.EMPTY; } @@ -365,10 +410,12 @@ var childVisible = false; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -386,7 +433,8 @@ maxY = maxY > childMaxY ? maxY : childMaxY; } - if (!childVisible) { + if (!childVisible) + { return math.Rectangle.EMPTY; } @@ -407,12 +455,14 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getLocalBounds = function () { +DisplayObjectContainer.prototype.getLocalBounds = function () +{ var matrixCache = this.worldTransform; this.worldTransform = math.Matrix.IDENTITY; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } @@ -428,13 +478,16 @@ * * @param renderer {WebGLRenderer} The renderer */ -DisplayObjectContainer.prototype.renderWebGL = function (renderer) { +DisplayObjectContainer.prototype.renderWebGL = function (renderer) +{ // if the object is not visible or the alpha is 0 then no need to render this element - if (!this.visible || this.alpha <= 0) { + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } @@ -442,14 +495,17 @@ var i, j; // do a quick check to see if this element has a mask or a filter. - if (this._mask || this._filters) { + if (this._mask || this._filters) + { // push filter first as we need to ensure the stencil buffer is correct for any masking - if (this._filters) { + if (this._filters) + { renderer.spriteBatch.flush(); renderer.filterManager.pushFilter(this._filterBlock); } - if (this._mask) { + if (this._mask) + { renderer.spriteBatch.stop(); renderer.maskManager.pushMask(this.mask, renderer); renderer.spriteBatch.start(); @@ -459,36 +515,42 @@ this._renderWebGL(renderer); // now loop through the children and make sure they get rendered - for (i = 0, j = this.children.length; i < j; i++) { + for (i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderWebGL(renderer); } // time to stop the sprite batch as either a mask element or a filter draw will happen next renderer.spriteBatch.stop(); - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(this._mask, renderer); } - if (this._filters) { + if (this._filters) + { renderer.filterManager.popFilter(); } renderer.spriteBatch.start(); } - else { + else + { this._renderWebGL(renderer); // simple render children! - for (i = 0, j = this.children.length; i < j; ++i) { + for (i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderWebGL(renderer); } } }; -DisplayObjectContainer.prototype._renderWebGL = function (renderer) { +DisplayObjectContainer.prototype._renderWebGL = function (renderer) +{ // this is where content itself gets renderd.. @@ -499,25 +561,31 @@ * * @param renderer {CanvasRenderer} The renderer */ -DisplayObjectContainer.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0) { +DisplayObjectContainer.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -528,13 +596,16 @@ * @param renderer {WebGLRenderer|CanvasRenderer} The renderer * @private */ -DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) { +DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) +{ this._cachedSprite.worldAlpha = this.worldAlpha; - if (renderer.gl) { + if (renderer.gl) + { this._cachedSprite.renderWebGL(renderer); } - else { + else + { this._cachedSprite.renderCanvas(renderer); } }; @@ -544,10 +615,12 @@ * * @private */ -DisplayObjectContainer.prototype._generateCachedSprite = function () { +DisplayObjectContainer.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { // TODO - RenderTexture now *requires* a renderer instance, so this is like broken // because `renderer` isn't actually in scope here :P var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0); @@ -555,7 +628,8 @@ this._cachedSprite = new Sprite(renderTexture); this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.texture.resize(bounds.width | 0, bounds.height | 0); } @@ -580,8 +654,10 @@ * * @private */ -DisplayObjectContainer.prototype._destroyCachedSprite = function () { - if (!this._cachedSprite) { +DisplayObjectContainer.prototype._destroyCachedSprite = function () +{ + if (!this._cachedSprite) + { return; } diff --git a/src/core/display/Sprite.js b/src/core/display/Sprite.js index 707da24..5862aef 100644 --- a/src/core/display/Sprite.js +++ b/src/core/display/Sprite.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param texture {Texture} The texture for this sprite */ -function Sprite(texture) { +function Sprite(texture) +{ DisplayObjectContainer.call(this); /** @@ -85,12 +86,14 @@ this.texture = texture || Texture.EMPTY; } -Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) { +Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) +{ DisplayObjectContainer.prototype.destroy.call(this); this.anchor = null; - if (destroyTexture) { + if (destroyTexture) + { this._texture.destroy(destroyBaseTexture); } @@ -111,10 +114,12 @@ * @memberof Sprite# */ width: { - get: function () { + get: function () + { return this.scale.x * this.texture.frame.width; }, - set: function (value) { + set: function (value) + { this.scale.x = value / this.texture.frame.width; this._width = value; } @@ -127,10 +132,12 @@ * @memberof Sprite# */ height: { - get: function () { + get: function () + { return this.scale.y * this.texture.frame.height; }, - set: function (value) { + set: function (value) + { this.scale.y = value / this.texture.frame.height; this._height = value; } @@ -143,23 +150,29 @@ * @memberof Sprite# */ texture: { - get: function () { + get: function () + { return this._texture; }, - set: function (value) { - if (this._texture === value) { + set: function (value) + { + if (this._texture === value) + { return; } this._texture = value; this.cachedTint = 0xFFFFFF; - if (value) { + if (value) + { // wait for the texture to load - if (value.baseTexture.hasLoaded) { + if (value.baseTexture.hasLoaded) + { this._onTextureUpdate(); } - else { + else + { value.once('update', this._onTextureUpdate.bind(this)); } } @@ -172,18 +185,22 @@ * * @private */ -Sprite.prototype._onTextureUpdate = function () { +Sprite.prototype._onTextureUpdate = function () +{ // so if _width is 0 then width was not set.. - if (this._width) { + if (this._width) + { this.scale.x = this._width / this.texture.frame.width; } - if (this._height) { + if (this._height) + { this.scale.y = this._height / this.texture.frame.height; } }; -Sprite.prototype._renderWebGL = function (renderer) { +Sprite.prototype._renderWebGL = function (renderer) +{ // this is where content gets renderd.. // watch this space for a little render state manager.. @@ -197,7 +214,8 @@ * @param matrix {Matrix} the transformation matrix of the sprite * @return {Rectangle} the framing rectangle */ -Sprite.prototype.getBounds = function (matrix) { +Sprite.prototype.getBounds = function (matrix) +{ var width = this.texture.frame.width; var height = this.texture.frame.height; @@ -224,11 +242,13 @@ if(b === 0 && c === 0) { // scale may be negative! - if (a < 0) { + if (a < 0) + { a *= -1; } - if (d < 0) { + if (d < 0) + { d *= -1; } @@ -293,28 +313,34 @@ * * @param renderer {CanvasRenderer} The renderer */ -Sprite.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) { +Sprite.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) + { return; } - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; renderer.context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } // Ignore null sources - if (this.texture.valid) { + if (this.texture.valid) + { var resolution = this.texture.baseTexture.resolution / renderer.resolution; renderer.context.globalAlpha = this.worldAlpha; // If smoothingEnabled is supported and we need to change the smoothing property for this texture - if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) { + if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) + { renderer.scaleMode = this.texture.baseTexture.scaleMode; renderer.context[renderer.smoothProperty] = (renderer.scaleMode === CONST.scaleModes.LINEAR); } @@ -324,7 +350,8 @@ var dy = (this.texture.trim ? this.texture.trim.y : 0) - (this.anchor.y * this.texture.trim.height); // Allow for pixel rounding - if (renderer.roundPixels) { + if (renderer.roundPixels) + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -337,7 +364,8 @@ dx = dx | 0; dy = dy | 0; } - else { + else + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -348,8 +376,10 @@ ); } - if (this.tint !== 0xFFFFFF) { - if (this.cachedTint !== this.tint) { + if (this.tint !== 0xFFFFFF) + { + if (this.cachedTint !== this.tint) + { this.cachedTint = this.tint; // TODO clean up caching - how to clean up the caches? @@ -368,7 +398,8 @@ this.texture.crop.height / resolution ); } - else { + else + { renderer.context.drawImage( this.texture.baseTexture.source, this.texture.crop.x, @@ -383,11 +414,13 @@ } } - for (var i = 0, j = this.children.length; i < j; i++) { + for (var i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -402,10 +435,12 @@ * @param frameId {String} The frame Id of the texture in the cache * @return {Sprite} A new Sprite using a texture from the texture cache matching the frameId */ -Sprite.fromFrame = function (frameId) { +Sprite.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache' + this); } @@ -420,6 +455,7 @@ * @param imageId {String} The image url of the texture * @return {Sprite} A new Sprite using a texture from the texture cache matching the image id */ -Sprite.fromImage = function (imageId, crossorigin, scaleMode) { +Sprite.fromImage = function (imageId, crossorigin, scaleMode) +{ return new Sprite(Texture.fromImage(imageId, crossorigin, scaleMode)); }; diff --git a/src/core/display/SpriteBatch.js b/src/core/display/SpriteBatch.js index 3187777..c196fef 100644 --- a/src/core/display/SpriteBatch.js +++ b/src/core/display/SpriteBatch.js @@ -12,7 +12,8 @@ * ```js * var container = new SpriteBatch(); * - * for(var i = 0; i < 100; ++i) { + * for(var i = 0; i < 100; ++i) + * { * var sprite = new PIXI.Sprite.fromImage("myImage.png"); * container.addChild(sprite); * } @@ -25,7 +26,8 @@ */ //TODO RENAME to PARTICLE CONTAINER? -function SpriteBatch() { +function SpriteBatch() +{ DisplayObjectContainer.call(this); } @@ -38,7 +40,8 @@ * * @private */ -SpriteBatch.prototype.updateTransform = function () { +SpriteBatch.prototype.updateTransform = function () +{ // TODO don't need to! this.displayObjectUpdateTransform(); // PIXI.DisplayObjectContainer.prototype.updateTransform.call( this ); @@ -50,8 +53,10 @@ * @param renderer {WebGLRenderer} The webgl renderer * @private */ -SpriteBatch.prototype.renderWebGL = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderWebGL = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -71,8 +76,10 @@ * @param renderer {CanvasRenderer} The canvas renderer * @private */ -SpriteBatch.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -84,10 +91,12 @@ this.displayObjectUpdateTransform(); - for (var i = 0; i < this.children.length; ++i) { + for (var i = 0; i < this.children.length; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -95,9 +104,11 @@ context.globalAlpha = this.worldAlpha * child.alpha; - if (child.rotation % (Math.PI * 2) === 0) { + if (child.rotation % (Math.PI * 2) === 0) + { // this is the fastest way to optimise! - if rotation is 0 then we can avoid any kind of setTransform call - if (isRotated) { + if (isRotated) + { context.setTransform( transform.a, transform.b, @@ -122,8 +133,10 @@ frame.height * child.scale.y ); } - else { - if (!isRotated) { + else + { + if (!isRotated) + { isRotated = true; } @@ -131,7 +144,8 @@ var childTransform = child.worldTransform; - if (renderer.roundPixels) { + if (renderer.roundPixels) + { context.setTransform( childTransform.a, childTransform.b, @@ -141,7 +155,8 @@ childTransform.ty | 0 ); } - else { + else + { context.setTransform( childTransform.a, childTransform.b, diff --git a/src/core/index.js b/src/core/index.js index 3954b6f..eb4a82b 100644 --- a/src/core/index.js +++ b/src/core/index.js @@ -58,11 +58,13 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRenderer: function (width, height, options, noWebGL) { + autoDetectRenderer: function (width, height, options, noWebGL) + { width = width || 800; height = height || 600; - if (!noWebGL && require('webgl-enabled')()) { + if (!noWebGL && require('webgl-enabled')()) + { return new core.WebGLRenderer(width, height, options); } @@ -87,7 +89,8 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRecommendedRenderer: function (width, height, options) { + autoDetectRecommendedRenderer: function (width, height, options) + { var isAndroid = /Android/i.test(navigator.userAgent); return core.autoDetectRenderer(width, height, options, isAndroid); diff --git a/src/core/math/Matrix.js b/src/core/math/Matrix.js index c2f87e2..2ff4848 100644 --- a/src/core/math/Matrix.js +++ b/src/core/math/Matrix.js @@ -10,7 +10,8 @@ * @class * @namespace PIXI */ -function Matrix() { +function Matrix() +{ /** * @member {number} * @default 1 @@ -63,7 +64,8 @@ * * @param array {number[]} The array that the matrix will be populated from. */ -Matrix.prototype.fromArray = function (array) { +Matrix.prototype.fromArray = function (array) +{ this.a = array[0]; this.b = array[1]; this.c = array[3]; @@ -78,14 +80,17 @@ * @param transpose {boolean} Whether we need to transpose the matrix or not * @return {number[]} the newly created array which contains the matrix */ -Matrix.prototype.toArray = function (transpose) { - if (!this.array) { +Matrix.prototype.toArray = function (transpose) +{ + if (!this.array) + { this.array = new Float32Array(9); } var array = this.array; - if (transpose) { + if (transpose) + { array[0] = this.a; array[1] = this.b; array[2] = 0; @@ -96,7 +101,8 @@ array[7] = this.ty; array[8] = 1; } - else { + else + { array[0] = this.a; array[1] = this.c; array[2] = this.tx; @@ -119,7 +125,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, transformed through this matrix */ -Matrix.prototype.apply = function (pos, newPos) { +Matrix.prototype.apply = function (pos, newPos) +{ newPos = newPos || new Point(); newPos.x = this.a * pos.x + this.c * pos.y + this.tx; @@ -136,7 +143,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, inverse-transformed through this matrix */ -Matrix.prototype.applyInverse = function (pos, newPos) { +Matrix.prototype.applyInverse = function (pos, newPos) +{ newPos = newPos || new Point(); var id = 1 / (this.a * this.d + this.c * -this.b); @@ -154,7 +162,8 @@ * @param {number} y * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.translate = function (x, y) { +Matrix.prototype.translate = function (x, y) +{ this.tx += x; this.ty += y; @@ -168,7 +177,8 @@ * @param {number} y The amount to scale vertically * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.scale = function (x, y) { +Matrix.prototype.scale = function (x, y) +{ this.a *= x; this.d *= y; this.c *= x; @@ -186,7 +196,8 @@ * @param {number} angle - The angle in radians. * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.rotate = function (angle) { +Matrix.prototype.rotate = function (angle) +{ var cos = Math.cos( angle ); var sin = Math.sin( angle ); @@ -210,7 +221,8 @@ * @param {Matrix} matrix * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.append = function (matrix) { +Matrix.prototype.append = function (matrix) +{ var a1 = this.a; var b1 = this.b; var c1 = this.c; @@ -232,7 +244,8 @@ * * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.identity = function () { +Matrix.prototype.identity = function () +{ this.a = 1; this.b = 0; this.c = 0; diff --git a/src/core/math/Point.js b/src/core/math/Point.js index 7565b2d..632f346 100644 --- a/src/core/math/Point.js +++ b/src/core/math/Point.js @@ -7,7 +7,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -function Point(x, y) { +function Point(x, y) +{ /** * @member {number} * @default 0 @@ -29,7 +30,8 @@ * * @return {Point} a copy of the point */ -Point.prototype.clone = function () { +Point.prototype.clone = function () +{ return new Point(this.x, this.y); }; @@ -40,7 +42,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -Point.prototype.set = function (x, y) { +Point.prototype.set = function (x, y) +{ this.x = x || 0; this.y = y || ( (y !== 0) ? this.x : 0 ) ; }; diff --git a/src/core/math/shapes/Circle.js b/src/core/math/shapes/Circle.js index 69cfdc9..4d76efc 100644 --- a/src/core/math/shapes/Circle.js +++ b/src/core/math/shapes/Circle.js @@ -10,7 +10,8 @@ * @param y {number} The Y coordinate of the center of this circle * @param radius {number} The radius of the circle */ -function Circle(x, y, radius) { +function Circle(x, y, radius) +{ /** * @member {number} * @default 0 @@ -46,7 +47,8 @@ * @method clone * @return {Circle} a copy of the Circle */ -Circle.prototype.clone = function () { +Circle.prototype.clone = function () +{ return new Circle(this.x, this.y, this.radius); }; @@ -58,8 +60,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Circle */ -Circle.prototype.contains = function (x, y) { - if (this.radius <= 0) { +Circle.prototype.contains = function (x, y) +{ + if (this.radius <= 0) + { return false; } @@ -79,6 +83,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Circle.prototype.getBounds = function () { +Circle.prototype.getBounds = function () +{ return new Rectangle(this.x - this.radius, this.y - this.radius, this.radius * 2, this.radius * 2); }; diff --git a/src/core/math/shapes/Ellipse.js b/src/core/math/shapes/Ellipse.js index 4f2d066..fefd01a 100644 --- a/src/core/math/shapes/Ellipse.js +++ b/src/core/math/shapes/Ellipse.js @@ -11,7 +11,8 @@ * @param width {number} The half width of this ellipse * @param height {number} The half height of this ellipse */ -function Ellipse(x, y, width, height) { +function Ellipse(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -53,7 +54,8 @@ * @method clone * @return {Ellipse} a copy of the ellipse */ -Ellipse.prototype.clone = function () { +Ellipse.prototype.clone = function () +{ return new Ellipse(this.x, this.y, this.width, this.height); }; @@ -65,8 +67,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coords are within this ellipse */ -Ellipse.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Ellipse.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } @@ -86,6 +90,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Ellipse.prototype.getBounds = function () { +Ellipse.prototype.getBounds = function () +{ return new Rectangle(this.x - this.width, this.y - this.height, this.width, this.height); }; diff --git a/src/core/math/shapes/Polygon.js b/src/core/math/shapes/Polygon.js index ae89148..fea6d37 100644 --- a/src/core/math/shapes/Polygon.js +++ b/src/core/math/shapes/Polygon.js @@ -10,16 +10,20 @@ * arguments passed can be flat x,y values e.g. `new Polygon(x,y, x,y, x,y, ...)` where `x` and `y` are * Numbers. */ -function Polygon(points) { +function Polygon(points) +{ //if points isn't an array, use arguments as the array - if (!(points instanceof Array)) { + if (!(points instanceof Array)) + { points = Array.prototype.slice.call(arguments); } //if this is a flat array of numbers, convert it to points - if (points[0] instanceof Point) { + if (points[0] instanceof Point) + { var p = []; - for (var i = 0, il = points.length; i < il; i++) { + for (var i = 0, il = points.length; i < il; i++) + { p.push(points[i].x, points[i].y); } @@ -51,7 +55,8 @@ * * @return {Polygon} a copy of the polygon */ -Polygon.prototype.clone = function () { +Polygon.prototype.clone = function () +{ return new Polygon(this.points.slice()); }; @@ -62,19 +67,22 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this polygon */ -Polygon.prototype.contains = function (x, y) { +Polygon.prototype.contains = function (x, y) +{ var inside = false; // use some raycasting to test hits // https://github.com/substack/point-in-polygon/blob/master/index.js var length = this.points.length / 2; - for (var i = 0, j = length - 1; i < length; j = i++) { + for (var i = 0, j = length - 1; i < length; j = i++) + { var xi = this.points[i * 2], yi = this.points[i * 2 + 1], xj = this.points[j * 2], yj = this.points[j * 2 + 1], intersect = ((yi > y) !== (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi); - if (intersect) { + if (intersect) + { inside = !inside; } } diff --git a/src/core/math/shapes/Rectangle.js b/src/core/math/shapes/Rectangle.js index 16ac62a..4008b68 100644 --- a/src/core/math/shapes/Rectangle.js +++ b/src/core/math/shapes/Rectangle.js @@ -10,7 +10,8 @@ * @param width {number} The overall width of this rectangle * @param height {number} The overall height of this rectangle */ -function Rectangle(x, y, width, height) { +function Rectangle(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -60,7 +61,8 @@ * * @return {Rectangle} a copy of the rectangle */ -Rectangle.prototype.clone = function () { +Rectangle.prototype.clone = function () +{ return new Rectangle(this.x, this.y, this.width, this.height); }; @@ -71,13 +73,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rectangle */ -Rectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Rectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/math/shapes/RoundedRectangle.js b/src/core/math/shapes/RoundedRectangle.js index 27d286e..7bf6411 100644 --- a/src/core/math/shapes/RoundedRectangle.js +++ b/src/core/math/shapes/RoundedRectangle.js @@ -11,7 +11,8 @@ * @param height {number} The overall height of this rounded rectangle * @param radius {number} Controls the radius of the rounded corners */ -function RoundedRectangle(x, y, width, height, radius) { +function RoundedRectangle(x, y, width, height, radius) +{ /** * @member {number} * @default 0 @@ -58,7 +59,8 @@ * * @return {RoundedRectangle} a copy of the rounded rectangle */ -RoundedRectangle.prototype.clone = function () { +RoundedRectangle.prototype.clone = function () +{ return new RoundedRectangle(this.x, this.y, this.width, this.height, this.radius); }; @@ -69,13 +71,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rounded Rectangle */ -RoundedRectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +RoundedRectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/primitives/Graphics.js b/src/core/primitives/Graphics.js index 261c534..e902d2a 100644 --- a/src/core/primitives/Graphics.js +++ b/src/core/primitives/Graphics.js @@ -16,7 +16,8 @@ * @extends DisplayObjectContainer * @namespace PIXI */ -function Graphics() { +function Graphics() +{ DisplayObjectContainer.call(this); this.renderable = true; @@ -154,16 +155,20 @@ * @private */ cacheAsBitmap: { - get: function () { + get: function () + { return this._cacheAsBitmap; }, - set: function (value) { + set: function (value) + { this._cacheAsBitmap = value; - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._generateCachedSprite(); } - else { + else + { this.destroyCachedSprite(); this.dirty = true; } @@ -176,7 +181,8 @@ * * @return {Graphics} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ var clone = new Graphics(); clone.renderable = this.renderable; @@ -192,7 +198,8 @@ clone.cachedSpriteDirty = this.cachedSpriteDirty; // copy graphics data - for (var i = 0; i < this.graphicsData.length; ++i) { + for (var i = 0; i < this.graphicsData.length; ++i) + { clone.graphicsData.push(this.graphicsData.clone()); } @@ -211,17 +218,21 @@ * @param alpha {number} alpha of the line to draw, will update the objects stored style * @return {Graphics} */ -Graphics.prototype.lineStyle = function (lineWidth, color, alpha) { +Graphics.prototype.lineStyle = function (lineWidth, color, alpha) +{ this.lineWidth = lineWidth || 0; this.lineColor = color || 0; this.lineAlpha = (arguments.length < 3) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length) + { // halfway through a line? start a new one! this.drawShape( new math.Polygon( this.currentPath.shape.points.slice(-2) )); } - else { + else + { // otherwise its empty so lets just set the line properties this.currentPath.lineWidth = this.lineWidth; this.currentPath.lineColor = this.lineColor; @@ -239,7 +250,8 @@ * @param y {number} the Y coordinate to move to * @return {Graphics} */ -Graphics.prototype.moveTo = function (x, y) { +Graphics.prototype.moveTo = function (x, y) +{ this.drawShape(new math.Polygon([x,y])); return this; @@ -253,7 +265,8 @@ * @param y {number} the Y coordinate to draw to * @return {Graphics} */ -Graphics.prototype.lineTo = function (x, y) { +Graphics.prototype.lineTo = function (x, y) +{ this.currentPath.shape.points.push(x, y); this.dirty = true; @@ -270,13 +283,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -285,7 +302,8 @@ n = 20, points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { this.moveTo(0, 0); } @@ -293,7 +311,8 @@ var fromY = points[points.length-1]; var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; xa = fromX + ( (cpX - fromX) * j ); @@ -319,13 +338,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -342,7 +365,8 @@ var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; dt = (1 - j); @@ -373,13 +397,17 @@ * @param radius {number} The radius of the arc * @return {Graphics} */ -Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points.push(x1, y1); } } - else { + else + { this.moveTo(x1, y1); } @@ -392,12 +420,15 @@ b2 = x2 - x1, mm = Math.abs(a1 * b2 - b1 * a2); - if (mm < 1.0e-8 || radius === 0) { - if (points[points.length-2] !== x1 || points[points.length-1] !== y1) { + if (mm < 1.0e-8 || radius === 0) + { + if (points[points.length-2] !== x1 || points[points.length-1] !== y1) + { points.push(x1, y1); } } - else { + else + { var dd = a1 * a1 + b1 * b1, cc = a2 * a2 + b2 * b2, tt = a1 * a2 + b1 * b2, @@ -433,42 +464,51 @@ * @param anticlockwise {boolean} Optional. Specifies whether the drawing should be counterclockwise or clockwise. False is default, and indicates clockwise, while true indicates counter-clockwise. * @return {Graphics} */ -Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) { +Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) +{ var startX = cx + Math.cos(startAngle) * radius; var startY = cy + Math.sin(startAngle) * radius; var points; // TODO - This if-else makes no sense. It uses currentPath in the else where it doesn't exist... - if (this.currentPath) { + if (this.currentPath) + { points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { points.push(startX, startY); } - else if (points[points.length-2] !== startX || points[points.length-1] !== startY) { + else if (points[points.length-2] !== startX || points[points.length-1] !== startY) + { points.push(startX, startY); } } - else { + else + { this.moveTo(startX, startY); points = this.currentPath.shape.points; } - if (startAngle === endAngle) { + if (startAngle === endAngle) + { return this; } - if (!anticlockwise && endAngle <= startAngle) { + if (!anticlockwise && endAngle <= startAngle) + { endAngle += Math.PI * 2; } - else if (anticlockwise && startAngle <= endAngle) { + else if (anticlockwise && startAngle <= endAngle) + { startAngle += Math.PI * 2; } var sweep = anticlockwise ? (startAngle - endAngle) *-1 : (endAngle - startAngle); var segs = (Math.abs(sweep)/ (Math.PI * 2)) * 40; - if (sweep === 0) { + if (sweep === 0) + { return this; } @@ -482,7 +522,8 @@ var remainder = ( segMinus % 1 ) / segMinus; - for (var i = 0; i <= segMinus; ++i) { + for (var i = 0; i <= segMinus; ++i) + { var real = i + remainder * i; var angle = ((theta) + startAngle + (theta2 * real)); @@ -506,13 +547,16 @@ * @param alpha {number} the alpha of the fill * @return {Graphics} */ -Graphics.prototype.beginFill = function (color, alpha) { +Graphics.prototype.beginFill = function (color, alpha) +{ this.filling = true; this.fillColor = color || 0; this.fillAlpha = (alpha === undefined) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length <= 2) + { this.currentPath.fill = this.filling; this.currentPath.fillColor = this.fillColor; this.currentPath.fillAlpha = this.fillAlpha; @@ -526,7 +570,8 @@ * * @return {Graphics} */ -Graphics.prototype.endFill = function () { +Graphics.prototype.endFill = function () +{ this.filling = false; this.fillColor = null; this.fillAlpha = 1; @@ -542,7 +587,8 @@ * @param height {number} The height of the rectangle * @return {Graphics} */ -Graphics.prototype.drawRect = function ( x, y, width, height ) { +Graphics.prototype.drawRect = function ( x, y, width, height ) +{ this.drawShape(new math.Rectangle(x,y, width, height)); return this; @@ -556,7 +602,8 @@ * @param height {number} The height of the rectangle * @param radius {number} Radius of the rectangle corners */ -Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) { +Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) +{ this.drawShape(new math.RoundedRectangle(x, y, width, height, radius)); return this; @@ -570,7 +617,8 @@ * @param radius {number} The radius of the circle * @return {Graphics} */ -Graphics.prototype.drawCircle = function (x, y, radius) { +Graphics.prototype.drawCircle = function (x, y, radius) +{ this.drawShape(new math.Circle(x,y, radius)); return this; @@ -585,7 +633,8 @@ * @param height {number} The half height of the ellipse * @return {Graphics} */ -Graphics.prototype.drawEllipse = function (x, y, width, height) { +Graphics.prototype.drawEllipse = function (x, y, width, height) +{ this.drawShape(new math.Ellipse(x, y, width, height)); return this; @@ -597,8 +646,10 @@ * @param path {Array} The path data used to construct the polygon. * @return {Graphics} */ -Graphics.prototype.drawPolygon = function (path) { - if (!(path instanceof Array)) { +Graphics.prototype.drawPolygon = function (path) +{ + if (!(path instanceof Array)) + { path = Array.prototype.slice.call(arguments); } @@ -612,7 +663,8 @@ * * @return {Graphics} */ -Graphics.prototype.clear = function () { +Graphics.prototype.clear = function () +{ this.lineWidth = 0; this.filling = false; @@ -631,7 +683,8 @@ * @param scaleMode {number} Should be one of the scaleMode consts * @return {Texture} a texture of the graphics object */ -Graphics.prototype.generateTexture = function (resolution, scaleMode) { +Graphics.prototype.generateTexture = function (resolution, scaleMode) +{ resolution = resolution || 1; var bounds = this.getBounds(); @@ -655,17 +708,21 @@ * * @param renderer {WebGLRenderer} */ -Graphics.prototype._renderWebGL = function (renderer) { +Graphics.prototype._renderWebGL = function (renderer) +{ // if the sprite is not visible or the alpha is 0 then no need to render this element - if (this.isMask === true) { + if (this.isMask === true) + { return; } // this code may still be needed so leaving for now.. - // + // /* - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture on the gpu too! @@ -681,17 +738,24 @@ return; } - */ - - // check if the webgl graphic needs to be updated - if (this.glDirty) { - this.dirty = true; - this.glDirty = false; - } + else */ - renderer.setObjectRendererer(renderer.graphicsRenderer); - renderer.graphicsRenderer.render(this); + renderer.spriteBatch.stop(); + renderer.blendModeManager.setBlendMode(this.blendMode); + // check blend mode + renderer.blendModeManager.setBlendMode( this.blendMode ); + + // check if the webgl graphic needs to be updated + if (this.glDirty) + { + this.dirty = true; + this.glDirty = false; + } + + WebGLGraphics.renderGraphics(this, renderer); + + renderer.spriteBatch.start(); }; /** @@ -700,14 +764,18 @@ * @param renderer {CanvasRenderer} * @private */ -Graphics.prototype.renderCanvas = function (renderer) { +Graphics.prototype.renderCanvas = function (renderer) +{ // 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.isMask === true) { + if (!this.visible || this.alpha <= 0 || this.isMask === true) + { return; } - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture @@ -723,16 +791,19 @@ return; } - else { + else + { var context = renderer.context; var transform = this.worldTransform; - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } @@ -748,11 +819,13 @@ CanvasGraphics.renderGraphics(this, context); - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } } @@ -763,13 +836,16 @@ * * @return {Rectangle} the rectangular bounding area */ -Graphics.prototype.getBounds = function (matrix) { +Graphics.prototype.getBounds = function (matrix) +{ // return an empty object if the item is a mask! - if (this.isMask) { + if (this.isMask) + { return math.Rectangle.EMPTY; } - if (this.dirty) { + if (this.dirty) + { this.updateLocalBounds(); this.glDirty = true; @@ -841,23 +917,27 @@ * Update the bounds of the object * */ -Graphics.prototype.updateLocalBounds = function () { +Graphics.prototype.updateLocalBounds = function () +{ var minX = Infinity; var maxX = -Infinity; var minY = Infinity; var maxY = -Infinity; - if (this.graphicsData.length) { + if (this.graphicsData.length) + { var shape, points, x, y, w, h; - for (var i = 0; i < this.graphicsData.length; i++) { + for (var i = 0; i < this.graphicsData.length; i++) + { var data = this.graphicsData[i]; var type = data.type; var lineWidth = data.lineWidth; shape = data.shape; - if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) { + if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) + { x = shape.x - lineWidth/2; y = shape.y - lineWidth/2; w = shape.width + lineWidth; @@ -869,7 +949,8 @@ minY = y < minY ? y : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.CIRC) { + else if (type === CONST.SHAPES.CIRC) + { x = shape.x; y = shape.y; w = shape.radius + lineWidth/2; @@ -881,7 +962,8 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.ELIP) { + else if (type === CONST.SHAPES.ELIP) + { x = shape.x; y = shape.y; w = shape.width + lineWidth/2; @@ -893,11 +975,13 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else { + else + { // POLY points = shape.points; - for (var j = 0; j < points.length; j += 2) { + for (var j = 0; j < points.length; j += 2) + { x = points[j]; y = points[j+1]; @@ -910,7 +994,8 @@ } } } - else { + else + { minX = 0; maxX = 0; minY = 0; @@ -931,10 +1016,12 @@ * * @private */ -Graphics.prototype._generateCachedSprite = function () { +Graphics.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { var canvasBuffer = new CanvasBuffer(bounds.width, bounds.height); var texture = Texture.fromCanvas(canvasBuffer.canvas); @@ -943,7 +1030,8 @@ this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.buffer.resize(bounds.width, bounds.height); } @@ -968,7 +1056,8 @@ * * @private */ -Graphics.prototype.updateCachedSpriteTexture = function () { +Graphics.prototype.updateCachedSpriteTexture = function () +{ var cachedSprite = this._cachedSprite; var texture = cachedSprite.texture; var canvas = cachedSprite.buffer.canvas; @@ -989,7 +1078,8 @@ * Destroys a previous cached sprite. * */ -Graphics.prototype.destroyCachedSprite = function () { +Graphics.prototype.destroyCachedSprite = function () +{ this._cachedSprite.texture.destroy(true); // let the gc collect the unused sprite @@ -1003,10 +1093,13 @@ * @param {Circle|Rectangle|Ellipse|Line|Polygon} shape The Shape object to draw. * @return {GraphicsData} The generated GraphicsData object. */ -Graphics.prototype.drawShape = function (shape) { - if (this.currentPath) { +Graphics.prototype.drawShape = function (shape) +{ + if (this.currentPath) + { // check current path! - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath.shape.points.length <= 2) + { this.graphicsData.pop(); } } @@ -1017,7 +1110,8 @@ this.graphicsData.push(data); - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { data.shape.closed = this.filling; this.currentPath = data; } diff --git a/src/core/primitives/GraphicsData.js b/src/core/primitives/GraphicsData.js index 99decbe..788f6f2 100644 --- a/src/core/primitives/GraphicsData.js +++ b/src/core/primitives/GraphicsData.js @@ -4,7 +4,8 @@ * @class * @namespace PIXI */ -function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) { +function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) +{ this.lineWidth = lineWidth; this.lineColor = lineColor; this.lineAlpha = lineAlpha; @@ -27,7 +28,8 @@ * * @return {GraphicsData} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ return new GraphicsData( this.lineWidth, this.lineColor, diff --git a/src/core/renderers/canvas/CanvasRenderer.js b/src/core/renderers/canvas/CanvasRenderer.js index 15a0978..7aebd44 100644 --- a/src/core/renderers/canvas/CanvasRenderer.js +++ b/src/core/renderers/canvas/CanvasRenderer.js @@ -17,17 +17,22 @@ * @param [options.resolution=1] {number} the resolution of the renderer retina would be 2 * @param [options.clearBeforeRender=true] {boolean} This sets if the CanvasRenderer will clear the canvas or not before the new render pass. */ -function CanvasRenderer(width, height, options) { +function CanvasRenderer(width, height, options) +{ utils.sayHello('Canvas'); - if (options) { - for (var i in CONST.defaultRenderOptions) { - if (typeof options[i] === 'undefined') { + if (options) + { + for (var i in CONST.defaultRenderOptions) + { + if (typeof options[i] === 'undefined') + { options[i] = CONST.defaultRenderOptions[i]; } } } - else { + else + { options = CONST.defaultRenderOptions; } @@ -156,19 +161,24 @@ this.smoothProperty = null; - if (this.context.imageSmoothingEnabled) { + if (this.context.imageSmoothingEnabled) + { this.smoothProperty = 'imageSmoothingEnabled'; } - else if (this.context.webkitImageSmoothingEnabled) { + else if (this.context.webkitImageSmoothingEnabled) + { this.smoothProperty = 'webkitImageSmoothingEnabled'; } - else if (this.context.mozImageSmoothingEnabled) { + else if (this.context.mozImageSmoothingEnabled) + { this.smoothProperty = 'mozImageSmoothingEnabled'; } - else if (this.context.oImageSmoothingEnabled) { + else if (this.context.oImageSmoothingEnabled) + { this.smoothProperty = 'oImageSmoothingEnabled'; } - else if (this.context.msImageSmoothingEnabled) { + else if (this.context.msImageSmoothingEnabled) + { this.smoothProperty = 'msImageSmoothingEnabled'; } @@ -193,10 +203,12 @@ * @memberof CanvasRenderer# */ backgroundColor: { - get: function () { + get: function () + { return this._backgroundColor; }, - set: function (val) { + set: function (val) + { this._backgroundColor = val; this._backgroundColorString = utils.hex2string(val); } @@ -208,7 +220,8 @@ * * @param object {DisplayObject} the object to be rendered */ -CanvasRenderer.prototype.render = function (object) { +CanvasRenderer.prototype.render = function (object) +{ object.updateTransform(); this.context.setTransform(1,0,0,1,0,0); @@ -218,16 +231,20 @@ this.currentBlendMode = CONST.blendModes.NORMAL; this.context.globalCompositeOperation = this.blendModes[CONST.blendModes.NORMAL]; - if (navigator.isCocoonJS && this.view.screencanvas) { + if (navigator.isCocoonJS && this.view.screencanvas) + { this.context.fillStyle = 'black'; this.context.clear(); } - if (this.clearBeforeRender) { - if (this.transparent) { + if (this.clearBeforeRender) + { + if (this.transparent) + { this.context.clearRect(0, 0, this.width, this.height); } - else { + else + { this.context.fillStyle = this._backgroundColorString; this.context.fillRect(0, 0, this.width , this.height); } @@ -241,8 +258,10 @@ * * @param [removeView=false] {boolean} Removes the Canvas element from the DOM. */ -CanvasRenderer.prototype.destroy = function (removeView) { - if (removeView && this.view.parent) { +CanvasRenderer.prototype.destroy = function (removeView) +{ + if (removeView && this.view.parent) + { this.view.parent.removeChild(this.view); } @@ -257,14 +276,16 @@ * @param width {number} the new width of the canvas view * @param height {number} the new height of the canvas view */ -CanvasRenderer.prototype.resize = function (width, height) { +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) { + if (this.autoResize) + { this.view.style.width = this.width / this.resolution + 'px'; this.view.style.height = this.height / this.resolution + 'px'; } @@ -276,7 +297,8 @@ * @param displayObject {DisplayObject} The displayObject to render * @private */ -CanvasRenderer.prototype.renderDisplayObject = function (displayObject) { +CanvasRenderer.prototype.renderDisplayObject = function (displayObject) +{ displayObject.renderCanvas(this); }; @@ -285,11 +307,14 @@ * * @private */ -CanvasRenderer.prototype._mapBlendModes = function () { - if (!this.blendModes) { +CanvasRenderer.prototype._mapBlendModes = function () +{ + if (!this.blendModes) + { this.blendModes = {}; - if (utils.canUseNewCanvasBlendModes()) { + if (utils.canUseNewCanvasBlendModes()) + { this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? this.blendModes[CONST.blendModes.MULTIPLY] = 'multiply'; @@ -308,7 +333,8 @@ this.blendModes[CONST.blendModes.COLOR] = 'color'; this.blendModes[CONST.blendModes.LUMINOSITY] = 'luminosity'; } - else { + else + { // this means that the browser does not support the cool new blend modes in canvas 'cough' ie 'cough' this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? diff --git a/src/core/renderers/canvas/utils/CanvasBuffer.js b/src/core/renderers/canvas/utils/CanvasBuffer.js index ebe5d47..b183a66 100644 --- a/src/core/renderers/canvas/utils/CanvasBuffer.js +++ b/src/core/renderers/canvas/utils/CanvasBuffer.js @@ -6,7 +6,8 @@ * @param width {number} the width for the newly created canvas * @param height {number} the height for the newly created canvas */ -function CanvasBuffer(width, height) { +function CanvasBuffer(width, height) +{ /** * The Canvas object that belongs to this CanvasBuffer. * @@ -36,10 +37,12 @@ * @memberof CanvasBuffer# */ width: { - get: function () { + get: function () + { return this.canvas.width; }, - set: function (val) { + set: function (val) + { this.canvas.width = val; } }, @@ -50,10 +53,12 @@ * @memberof CanvasBuffer# */ height: { - get: function () { + get: function () + { return this.canvas.height; }, - set: function (val) { + set: function (val) + { this.canvas.height = val; } } @@ -64,7 +69,8 @@ * * @private */ -CanvasBuffer.prototype.clear = function () { +CanvasBuffer.prototype.clear = function () +{ this.context.setTransform(1, 0, 0, 1, 0, 0); this.context.clearRect(0,0, this.canvas.width, this.canvas.height); }; @@ -75,7 +81,8 @@ * @param width {number} the new width of the canvas * @param height {number} the new height of the canvas */ -CanvasBuffer.prototype.resize = function (width, height) { +CanvasBuffer.prototype.resize = function (width, height) +{ this.canvas.width = width; this.canvas.height = height; }; diff --git a/src/core/renderers/canvas/utils/CanvasGraphics.js b/src/core/renderers/canvas/utils/CanvasGraphics.js index c7eaa2a..3f2a91f 100644 --- a/src/core/renderers/canvas/utils/CanvasGraphics.js +++ b/src/core/renderers/canvas/utils/CanvasGraphics.js @@ -13,15 +13,18 @@ * @param graphics {Graphics} the actual graphics object to render * @param context {CanvasRenderingContext2D} the 2d drawing method of the canvas */ -CanvasGraphics.renderGraphics = function (graphics, context) { +CanvasGraphics.renderGraphics = function (graphics, context) +{ var worldAlpha = graphics.worldAlpha; - if (graphics.dirty) { + if (graphics.dirty) + { this.updateGraphicsTint(graphics); graphics.dirty = false; } - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; @@ -30,69 +33,82 @@ context.lineWidth = data.lineWidth; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { context.beginPath(); var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } - if (shape.closed) { + if (shape.closed) + { context.lineTo(points[0], points[1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fillRect(shape.x, shape.y, shape.width, shape.height); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.strokeRect(shape.x, shape.y, shape.width, shape.height); } } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.beginPath(); context.arc(shape.x, shape.y, shape.radius,0,2*Math.PI); context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas var w = shape.width * 2; @@ -119,18 +135,21 @@ context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; var width = shape.width; @@ -152,13 +171,15 @@ context.quadraticCurveTo(rx, ry, rx, ry + radius); context.closePath(); - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); @@ -174,45 +195,54 @@ * @param graphics {Graphics} the graphics which will be used as a mask * @param context {CanvasRenderingContext2D} the context 2d method of the canvas */ -CanvasGraphics.renderGraphicsMask = function (graphics, context) { +CanvasGraphics.renderGraphicsMask = function (graphics, context) +{ var len = graphics.graphicsData.length; - if (len === 0) { + if (len === 0) + { return; } context.beginPath(); - for (var i = 0; i < len; i++) { + for (var i = 0; i < len; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { context.rect(shape.x, shape.y, shape.width, shape.height); context.closePath(); } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.arc(shape.x, shape.y, shape.radius, 0, 2 * Math.PI); context.closePath(); } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas @@ -237,7 +267,8 @@ context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); context.closePath(); } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; @@ -262,8 +293,10 @@ } }; -CanvasGraphics.updateGraphicsTint = function (graphics) { - if (graphics.tint === 0xFFFFFF) { +CanvasGraphics.updateGraphicsTint = function (graphics) +{ + if (graphics.tint === 0xFFFFFF) + { return; } @@ -271,7 +304,8 @@ var tintG = (graphics.tint >> 8 & 0xFF) / 255; var tintB = (graphics.tint & 0xFF)/ 255; - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var fillColor = data.fillColor | 0; diff --git a/src/core/renderers/canvas/utils/CanvasMaskManager.js b/src/core/renderers/canvas/utils/CanvasMaskManager.js index e04a733..9827d36 100644 --- a/src/core/renderers/canvas/utils/CanvasMaskManager.js +++ b/src/core/renderers/canvas/utils/CanvasMaskManager.js @@ -6,7 +6,8 @@ * @class * @namespace PIXI */ -function CanvasMaskManager() {} +function CanvasMaskManager() +{} CanvasMaskManager.prototype.constructor = CanvasMaskManager; module.exports = CanvasMaskManager; @@ -17,7 +18,8 @@ * @param maskData {object} the maskData that will be pushed * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.pushMask = function (maskData, renderer) { +CanvasMaskManager.prototype.pushMask = function (maskData, renderer) +{ renderer.context.save(); var cacheAlpha = maskData.alpha; @@ -45,6 +47,7 @@ * * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.popMask = function (renderer) { +CanvasMaskManager.prototype.popMask = function (renderer) +{ renderer.context.restore(); }; diff --git a/src/core/renderers/canvas/utils/CanvasTinter.js b/src/core/renderers/canvas/utils/CanvasTinter.js index 17e0529..d2fb1bc 100644 --- a/src/core/renderers/canvas/utils/CanvasTinter.js +++ b/src/core/renderers/canvas/utils/CanvasTinter.js @@ -14,7 +14,8 @@ * @param color {number} the color to use to tint the sprite with * @return {HTMLCanvasElement} The tinted canvas */ -CanvasTinter.getTintedTexture = function (sprite, color) { +CanvasTinter.getTintedTexture = function (sprite, color) +{ var texture = sprite.texture; color = CanvasTinter.roundColor(color); @@ -23,7 +24,8 @@ texture.tintCache = texture.tintCache || {}; - if (texture.tintCache[stringColor]) { + if (texture.tintCache[stringColor]) + { return texture.tintCache[stringColor]; } @@ -33,14 +35,16 @@ //CanvasTinter.tintWithPerPixel(texture, stringColor, canvas); CanvasTinter.tintMethod(texture, color, canvas); - if (CanvasTinter.convertTintToImage) { + if (CanvasTinter.convertTintToImage) + { // is this better? var tintImage = new Image(); tintImage.src = canvas.toDataURL(); texture.tintCache[stringColor] = tintImage; } - else { + else + { texture.tintCache[stringColor] = canvas; // if we are not converting the texture to an image then we need to lose the reference to the canvas CanvasTinter.canvas = null; @@ -56,7 +60,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithMultiply = function (texture, color, canvas) { +CanvasTinter.tintWithMultiply = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -104,7 +109,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithOverlay = function (texture, color, canvas) { +CanvasTinter.tintWithOverlay = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -139,7 +145,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithPerPixel = function (texture, color, canvas) { +CanvasTinter.tintWithPerPixel = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -167,7 +174,8 @@ var pixels = pixelData.data; - for (var i = 0; i < pixels.length; i += 4) { + for (var i = 0; i < pixels.length; i += 4) + { pixels[i+0] *= r; pixels[i+1] *= g; pixels[i+2] *= b; @@ -181,7 +189,8 @@ * * @param color {number} the color to round, should be a hex color */ -CanvasTinter.roundColor = function (color) { +CanvasTinter.roundColor = function (color) +{ var step = CanvasTinter.cacheStepsPerColorChannel; var rgbValues = utils.hex2rgb(color); diff --git a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js index 9f2f89a..35edbaf 100644 --- a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js +++ b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLBlendModeManager(renderer) { +function WebGLBlendModeManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -23,8 +24,10 @@ * * @param blendMode {number} the blendMode, should be a Pixi const, such as BlendModes.ADD */ -WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) { - if (this.currentBlendMode === blendMode) { +WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) +{ + if (this.currentBlendMode === blendMode) + { return false; } diff --git a/src/core/renderers/webgl/managers/WebGLFilterManager.js b/src/core/renderers/webgl/managers/WebGLFilterManager.js index 1179258..2dac048 100644 --- a/src/core/renderers/webgl/managers/WebGLFilterManager.js +++ b/src/core/renderers/webgl/managers/WebGLFilterManager.js @@ -7,7 +7,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLFilterManager(renderer) { +function WebGLFilterManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -32,7 +33,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.texturePool.length = 0; self.initShaderBuffers(); }); @@ -46,7 +48,8 @@ * @param renderer {WebGLRenderer} * @param buffer {ArrayBuffer} */ -WebGLFilterManager.prototype.begin = function (buffer) { +WebGLFilterManager.prototype.begin = function (buffer) +{ this.defaultShader = this.renderer.shaderManager.defaultShader; this.width = this.renderer.projection.x * 2; @@ -60,7 +63,8 @@ * * @param filterBlock {object} the filter that will be pushed to the current filter stack */ -WebGLFilterManager.prototype.pushFilter = function (filterBlock) { +WebGLFilterManager.prototype.pushFilter = function (filterBlock) +{ var gl = this.renderer.gl; var projection = this.renderer.projection; @@ -78,10 +82,12 @@ this.offsetY += filterBlock._filterArea.y; var texture = this.texturePool.pop(); - if (!texture) { + if (!texture) + { texture = new FilterTexture(this.renderer.gl, this.width, this.height); } - else { + else + { texture.resize(this.width, this.height); } @@ -98,29 +104,35 @@ var localX = filterArea.x, localY = filterArea.y; - if (filterArea.x < 0) { + if (filterArea.x < 0) + { filterArea.width += filterArea.x; filterArea.x = 0; } - if (filterArea.y < 0) { + if (filterArea.y < 0) + { filterArea.height += filterArea.y; filterArea.y = 0; } - if (localX + filterArea.width > this.width) { + if (localX + filterArea.width > this.width) + { filterArea.width = this.width - localX; } - if (localY + filterArea.height > this.height) { + if (localY + filterArea.height > this.height) + { filterArea.height = this.height - localY; } - if (filterArea.width < 0) { + if (filterArea.width < 0) + { filterArea.width = 0; } - if (filterArea.height < 0) { + if (filterArea.height < 0) + { filterArea.height = 0; } @@ -154,7 +166,8 @@ * Removes the last filter from the filter stack and doesn't return it. * */ -WebGLFilterManager.prototype.popFilter = function () { +WebGLFilterManager.prototype.popFilter = function () +{ var gl = this.renderer.gl; var filterBlock = this.filterStack.pop(); @@ -163,7 +176,8 @@ var projection = this.renderer.projection; var offset = this.renderer.offset; - if (filterBlock.filterPasses.length > 1) { + if (filterBlock.filterPasses.length > 1) + { gl.viewport(0, 0, filterArea.width, filterArea.height); gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); @@ -193,7 +207,8 @@ var inputTexture = texture; var outputTexture = this.texturePool.pop(); - if (!outputTexture) { + if (!outputTexture) + { outputTexture = new FilterTexture(this.renderer.gl, this.width, this.height); } outputTexture.resize(this.width, this.height); @@ -204,7 +219,8 @@ gl.disable(gl.BLEND); - for (var i = 0; i < filterBlock.filterPasses.length-1; i++) { + for (var i = 0; i < filterBlock.filterPasses.length-1; i++) + { var filterPass = filterBlock.filterPasses[i]; gl.bindFramebuffer(gl.FRAMEBUFFER, outputTexture.frameBuffer ); @@ -243,10 +259,12 @@ var buffer = this.buffer; // time to render the filters texture to the previous scene - if (this.filterStack.length === 0) { + if (this.filterStack.length === 0) + { gl.colorMask(true, true, true, true);//this.transparent); } - else { + else + { var currentFilter = this.filterStack[this.filterStack.length-1]; filterArea = currentFilter._filterArea; @@ -332,13 +350,15 @@ * @param width {number} the horizontal range of the filter * @param height {number} the vertical range of the filter */ -WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) { +WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) +{ // use program var gl = this.renderer.gl; var shader = filter.shaders[gl.id]; - if (!shader) { + if (!shader) + { shader = new Shader(gl); shader.fragmentSrc = filter.fragmentSrc; @@ -356,7 +376,8 @@ gl.uniform2f(shader.projectionVector, width/2, -height/2); gl.uniform2f(shader.offsetVector, 0,0); - if (filter.uniforms.dimensions) { + 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]; @@ -386,7 +407,8 @@ * Initialises the shader buffers. * */ -WebGLFilterManager.prototype.initShaderBuffers = function () { +WebGLFilterManager.prototype.initShaderBuffers = function () +{ var gl = this.renderer.gl; // create some buffers @@ -432,7 +454,8 @@ * Destroys the filter and removes it from the filter stack. * */ -WebGLFilterManager.prototype.destroy = function () { +WebGLFilterManager.prototype.destroy = function () +{ var gl = this.renderer.gl; this.filterStack = null; @@ -441,7 +464,8 @@ this.offsetY = 0; // destroy textures - for (var i = 0; i < this.texturePool.length; i++) { + for (var i = 0; i < this.texturePool.length; i++) + { this.texturePool[i].destroy(); } diff --git a/src/core/renderers/webgl/managers/WebGLManager.js b/src/core/renderers/webgl/managers/WebGLManager.js index 9d47b5c..c30cd51 100644 --- a/src/core/renderers/webgl/managers/WebGLManager.js +++ b/src/core/renderers/webgl/managers/WebGLManager.js @@ -3,7 +3,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLManager(renderer) { +function WebGLManager(renderer) +{ /** * The renderer this manager works for. * @@ -15,6 +16,7 @@ WebGLManager.prototype.constructor = WebGLManager; module.exports = WebGLManager; -WebGLManager.prototype.destroy = function () { +WebGLManager.prototype.destroy = function () +{ this.renderer = null; }; diff --git a/src/core/renderers/webgl/managers/WebGLMaskManager.js b/src/core/renderers/webgl/managers/WebGLMaskManager.js index 2f90b64..e568812 100644 --- a/src/core/renderers/webgl/managers/WebGLMaskManager.js +++ b/src/core/renderers/webgl/managers/WebGLMaskManager.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLMaskManager(renderer) { +function WebGLMaskManager(renderer) +{ WebGLManager.call(this, renderer); } @@ -19,12 +20,15 @@ * * @param maskData {any[]} */ -WebGLMaskManager.prototype.pushMask = function (maskData) { - if (maskData.dirty) { +WebGLMaskManager.prototype.pushMask = function (maskData) +{ + if (maskData.dirty) + { WebGLGraphics.updateGraphics(maskData, this.renderer.gl); } - if (!maskData._webGL[this.renderer.gl.id].data.length) { + if (!maskData._webGL[this.renderer.gl.id].data.length) + { return; } @@ -36,6 +40,7 @@ * * @param maskData {any[]} */ -WebGLMaskManager.prototype.popMask = function (maskData) { +WebGLMaskManager.prototype.popMask = function (maskData) +{ this.renderer.stencilManager.popStencil(maskData, maskData._webGL[this.renderer.gl.id].data[0], this.renderer); }; diff --git a/src/core/renderers/webgl/managers/WebGLShaderManager.js b/src/core/renderers/webgl/managers/WebGLShaderManager.js index fef071c..90c6477 100644 --- a/src/core/renderers/webgl/managers/WebGLShaderManager.js +++ b/src/core/renderers/webgl/managers/WebGLShaderManager.js @@ -10,7 +10,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLShaderManager(renderer) { +function WebGLShaderManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -28,7 +29,8 @@ */ this.tempAttribState = []; - for (var i = 0; i < this.maxAttibs; i++) { + for (var i = 0; i < this.maxAttibs; i++) + { this.attribState[i] = false; } @@ -66,7 +68,8 @@ // listen for context and update necessary shaders var self = this; - this.renderer.on('context', function (event) { + this.renderer.on('context', function (event) + { var gl = event.data; // this shader is used for rendering primitives @@ -97,29 +100,36 @@ * * @param attribs {Array} attribs */ -WebGLShaderManager.prototype.setAttribs = function (attribs) { +WebGLShaderManager.prototype.setAttribs = function (attribs) +{ // reset temp state var i; - for (i = 0; i < this.tempAttribState.length; i++) { + for (i = 0; i < this.tempAttribState.length; i++) + { this.tempAttribState[i] = false; } // set the new attribs - for (var a in attribs) { + for (var a in attribs) + { this.tempAttribState[attribs[a]] = true; } var gl = this.renderer.gl; - for (i = 0; i < this.attribState.length; i++) { - if (this.attribState[i] !== this.tempAttribState[i]) { + for (i = 0; i < this.attribState.length; i++) + { + if (this.attribState[i] !== this.tempAttribState[i]) + { this.attribState[i] = this.tempAttribState[i]; - if (this.attribState[i]) { + if (this.attribState[i]) + { gl.enableVertexAttribArray(i); } - else { + else + { gl.disableVertexAttribArray(i); } } @@ -131,8 +141,10 @@ * * @param shader {Any} */ -WebGLShaderManager.prototype.setShader = function (shader) { - if (this._currentId === shader.uuid) { +WebGLShaderManager.prototype.setShader = function (shader) +{ + if (this._currentId === shader.uuid) + { return false; } @@ -150,7 +162,8 @@ * Destroys this object. * */ -WebGLShaderManager.prototype.destroy = function () { +WebGLShaderManager.prototype.destroy = function () +{ this.attribState = null; this.tempAttribState = null; diff --git a/src/core/renderers/webgl/managers/WebGLStencilManager.js b/src/core/renderers/webgl/managers/WebGLStencilManager.js index 9ec6398..4cb0134 100644 --- a/src/core/renderers/webgl/managers/WebGLStencilManager.js +++ b/src/core/renderers/webgl/managers/WebGLStencilManager.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLStencilManager(renderer) { +function WebGLStencilManager(renderer) +{ WebGLManager.call(this, renderer); this.stencilStack = []; @@ -24,12 +25,14 @@ * @param graphics {Graphics} * @param webGLData {any[]} */ -WebGLStencilManager.prototype.pushStencil = function (graphics, webGLData) { +WebGLStencilManager.prototype.pushStencil = function (graphics, webGLData) +{ var gl = this.renderer.gl; this.bindGraphics(graphics, webGLData, this.renderer); - if (this.stencilStack.length === 0) { + if (this.stencilStack.length === 0) + { gl.enable(gl.STENCIL_TEST); gl.clear(gl.STENCIL_BUFFER_BIT); this.reverse = true; @@ -47,14 +50,17 @@ // draw the triangle strip! - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } @@ -62,31 +68,38 @@ // draw a quad to increment.. gl.drawElements(gl.TRIANGLE_FAN, 4, gl.UNSIGNED_SHORT, ( webGLData.indices.length - 4 ) * 2 ); - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); } this.reverse = !this.reverse; } - else { - if (!this.reverse) { + else + { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } - else { + 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) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); } } @@ -103,7 +116,8 @@ * @param graphics {Graphics} * @param webGLData {Array} */ -WebGLStencilManager.prototype.bindGraphics = function (graphics, webGLData) { +WebGLStencilManager.prototype.bindGraphics = function (graphics, webGLData) +{ //if (this._currentGraphics === graphics)return; this._currentGraphics = graphics; @@ -114,7 +128,8 @@ offset = this.renderer.offset, shader;// = this.renderer.shaderManager.primitiveShader; - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { shader = this.renderer.shaderManager.complexPrimitiveShader; this.renderer.shaderManager.setShader(shader); @@ -141,7 +156,8 @@ // set the index buffer! gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, webGLData.indexBuffer); } - else { + else + { //this.renderer.shaderManager.activatePrimitiveShader(); shader = this.renderer.shaderManager.primitiveShader; this.renderer.shaderManager.setShader( shader ); @@ -154,7 +170,7 @@ gl.uniform2f(shader.uniforms.offsetVector._location, -offset.x, -offset.y); gl.uniform3fv(shader.uniforms.tint._location, utils.hex2rgb(graphics.tint)); - + gl.uniform1f(shader.uniforms.alpha._location, graphics.worldAlpha); @@ -172,19 +188,22 @@ * @param graphics {Graphics} * @param webGLData {Array} */ -WebGLStencilManager.prototype.popStencil = function (graphics, webGLData) { +WebGLStencilManager.prototype.popStencil = function (graphics, webGLData) +{ var gl = this.renderer.gl; this.stencilStack.pop(); this.count--; - if (this.stencilStack.length === 0) { + if (this.stencilStack.length === 0) + { // the stack is empty! gl.disable(gl.STENCIL_TEST); } - else { + else + { var level = this.count; @@ -192,14 +211,17 @@ gl.colorMask(false, false, false, false); - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { this.reverse = !this.reverse; - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } @@ -213,31 +235,38 @@ // draw the triangle strip! gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); - if (!this.reverse) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); } } - else { + else + { // console.log("<<>>") - if (!this.reverse) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } - else { + 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) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); } } @@ -253,7 +282,8 @@ * Destroys the mask stack. * */ -WebGLStencilManager.prototype.destroy = function () { +WebGLStencilManager.prototype.destroy = function () +{ this.renderer = null; this.stencilStack = null; }; diff --git a/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js b/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js index 913ba5e..1ea7d19 100644 --- a/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js +++ b/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function ComplexPrimitiveShader(gl) { +function ComplexPrimitiveShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -24,7 +25,8 @@ 'uniform float flipY;', 'varying vec4 vColor;', - 'void main(void) {', + '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);', @@ -37,7 +39,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = vColor;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/FastShader.js b/src/core/renderers/webgl/shaders/FastShader.js index bd2e29a..2e5e060 100644 --- a/src/core/renderers/webgl/shaders/FastShader.js +++ b/src/core/renderers/webgl/shaders/FastShader.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function FastShader(gl) { +function FastShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -28,7 +29,8 @@ 'const vec2 center = vec2(-1.0, 1.0);', - 'void main(void) {', + 'void main(void) + {', ' vec2 v;', ' vec2 sv = aVertexPosition * aScale;', ' v.x = (sv.x) * cos(aRotation) - (sv.y) * sin(aRotation);', @@ -49,7 +51,8 @@ 'uniform sampler2D uSampler;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/PrimitiveShader.js b/src/core/renderers/webgl/shaders/PrimitiveShader.js index 6f25409..a25f54f 100644 --- a/src/core/renderers/webgl/shaders/PrimitiveShader.js +++ b/src/core/renderers/webgl/shaders/PrimitiveShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function PrimitiveShader(gl) { +function PrimitiveShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -23,7 +24,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + '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);', @@ -36,7 +38,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = vColor;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/Shader.js b/src/core/renderers/webgl/shaders/Shader.js index f8964f5..fd75ef5 100644 --- a/src/core/renderers/webgl/shaders/Shader.js +++ b/src/core/renderers/webgl/shaders/Shader.js @@ -6,7 +6,8 @@ * @param [fragmentSrc] {string} The source of the fragment shader. * @param [vertexSrc] {string} The source of the vertex shader. */ -function Shader(gl, vertexSrc, fragmentSrc, customUniforms, customAttributes) { +function Shader(gl, vertexSrc, fragmentSrc, customUniforms, customAttributes) +{ /** * @member {number} * @readonly @@ -33,7 +34,8 @@ dimensions: { type: '4f', value: new Float32Array(4) } }; - for (var u in customUniforms) { + for (var u in customUniforms) + { this.uniforms[u] = customUniforms[u]; } @@ -43,7 +45,8 @@ aColor: 0 }; - for (var a in customAttributes) { + for (var a in customAttributes) + { this.attributes[a] = customAttributes[a]; } @@ -66,7 +69,8 @@ 'const vec2 center = vec2(-1.0, 1.0);', - 'void main(void) {', + 'void main(void) + {', ' gl_Position = vec4( ((aVertexPosition + offsetVector) / projectionVector) + center , 0.0, 1.0);', ' vTextureCoord = aTextureCoord;', ' vColor = vec4(aColor.rgb * aColor.a, aColor.a);', @@ -85,7 +89,8 @@ 'uniform sampler2D uSampler;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;', '}' ].join('\n'); @@ -96,7 +101,8 @@ Shader.prototype.constructor = Shader; module.exports = Shader; -Shader.prototype.init = function () { +Shader.prototype.init = function () +{ this.compile(); this.gl.useProgram(this.program); @@ -105,14 +111,18 @@ this.cacheAttributeLocations(Object.keys(this.attributes)); }; -Shader.prototype.cacheUniformLocations = function (keys) { - for (var i = 0; i < keys.length; ++i) { +Shader.prototype.cacheUniformLocations = function (keys) +{ + for (var i = 0; i < keys.length; ++i) + { this.uniforms[keys[i]]._location = this.gl.getUniformLocation(this.program, keys[i]); } }; -Shader.prototype.cacheAttributeLocations = function (keys) { - for (var i = 0; i < keys.length; ++i) { +Shader.prototype.cacheAttributeLocations = function (keys) +{ + for (var i = 0; i < keys.length; ++i) + { this.attributes[keys[i]] = this.gl.getAttribLocation(this.program, keys[i]); } @@ -124,14 +134,16 @@ // 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.attributes.aColor === -1) { + // if (this.attributes.aColor === -1) + { // this.attributes.aColor = 2; // } // End worst hack eva // }; -Shader.prototype.compile = function () { +Shader.prototype.compile = function () +{ var gl = this.gl; var glVertShader = this._glCompile(gl.VERTEX_SHADER, this.vertexSrc); @@ -144,13 +156,15 @@ gl.linkProgram(program); // if linking fails, then log and cleanup - if (!gl.getProgramParameter(program, gl.LINK_STATUS)) { + if (!gl.getProgramParameter(program, gl.LINK_STATUS)) + { window.console.error('Pixi.js Error: Could not initialize shader.'); window.console.error('gl.VALIDATE_STATUS', gl.getProgramParameter(program, gl.VALIDATE_STATUS)); window.console.error('gl.getError()', gl.getError()); // if there is a program info log, log it - if (gl.getProgramInfoLog(program) !== '') { + if (gl.getProgramInfoLog(program) !== '') + { window.console.warn('Pixi.js Warning: gl.getProgramInfoLog()', gl.getProgramInfoLog(program)); } @@ -165,18 +179,21 @@ return (this.program = program); }; -Shader.prototype.syncUniforms = function () { +Shader.prototype.syncUniforms = function () +{ var gl = this.gl; this.textureCount = 1; - for (var key in this.uniforms) { + for (var key in this.uniforms) + { var uniform = this.uniforms[key], location = uniform._location, value = uniform.value, i, il; - switch (uniform.type) { + switch (uniform.type) + { // single int value case 'i': case '1i': @@ -282,7 +299,8 @@ // a Color Value case 'c': - if (typeof value === 'number') { + if (typeof value === 'number') + { value = utils.hex2rgb(value); } @@ -311,11 +329,13 @@ // array of 2D Point objects case 'v2v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(2 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 2] = value[i].x; uniform._array[i * 2 + 1] = value[i].y; } @@ -325,11 +345,13 @@ // array of 3D Point objects case 'v3v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(3 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 3] = value[i].x; uniform._array[i * 3 + 1] = value[i].y; uniform._array[i * 3 + 2] = value[i].z; @@ -341,11 +363,13 @@ // array of 4D Point objects case 'v4v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(4 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 4] = value[i].x; uniform._array[i * 4 + 1] = value[i].y; uniform._array[i * 4 + 2] = value[i].z; @@ -359,7 +383,8 @@ // PIXI.Texture case 't': case 'sampler2D': - if (!uniform.value || !uniform.value.baseTexture || !uniform.value.baseTexture.hasLoaded) { + if (!uniform.value || !uniform.value.baseTexture || !uniform.value.baseTexture.hasLoaded) + { break; } @@ -376,7 +401,8 @@ this.textureCount++; // initialize the texture if we haven't yet - if (!uniform._init) { + if (!uniform._init) + { this.initSampler2D(uniform); uniform._init = true; @@ -394,11 +420,13 @@ * Initialises a Sampler2D uniform (which may only be available later on after initUniforms once the texture has loaded) * */ -Shader.prototype.initSampler2D = function (uniform) { +Shader.prototype.initSampler2D = function (uniform) +{ var gl = this.gl; // Extended texture data - if (uniform.textureData) { + if (uniform.textureData) + { var data = uniform.textureData; // GLTexture = mag linear, min linear_mipmap_linear, wrap repeat + gl.generateMipmap(gl.TEXTURE_2D); @@ -417,14 +445,16 @@ var wrapT = (data.wrapT) ? data.wrapT : gl.CLAMP_TO_EDGE; var format = (data.luminance) ? gl.LUMINANCE : gl.RGBA; - if (data.repeat) { + if (data.repeat) + { wrapS = gl.REPEAT; wrapT = gl.REPEAT; } gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, !!data.flipY); - if (data.width) { + if (data.width) + { var width = (data.width) ? data.width : 512; var height = (data.height) ? data.height : 2; var border = (data.border) ? data.border : 0; @@ -432,7 +462,8 @@ // 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 { + 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); } @@ -448,7 +479,8 @@ * Destroys the shader. * */ -Shader.prototype.destroy = function () { +Shader.prototype.destroy = function () +{ this.gl.deleteProgram(this.program); this.gl = null; @@ -459,13 +491,15 @@ this.fragmentSrc = null; }; -Shader.prototype._glCompile = function (type, src) { +Shader.prototype._glCompile = function (type, src) +{ var shader = this.gl.createShader(type); this.gl.shaderSource(shader, src); this.gl.compileShader(shader); - if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) { + if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) + { window.console.log(this.gl.getShaderInfoLog(shader)); return null; } diff --git a/src/core/renderers/webgl/shaders/StripShader.js b/src/core/renderers/webgl/shaders/StripShader.js index 193f6e1..a7abcc6 100644 --- a/src/core/renderers/webgl/shaders/StripShader.js +++ b/src/core/renderers/webgl/shaders/StripShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function StripShader(gl) { +function StripShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -20,7 +21,8 @@ 'varying vec2 vTextureCoord;', - 'void main(void) {', + '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);', @@ -36,7 +38,8 @@ 'varying vec2 vTextureCoord;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vec2(vTextureCoord.x, vTextureCoord.y)) * alpha;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/utils/FilterTexture.js b/src/core/renderers/webgl/utils/FilterTexture.js index d2c8423..4433d44 100644 --- a/src/core/renderers/webgl/utils/FilterTexture.js +++ b/src/core/renderers/webgl/utils/FilterTexture.js @@ -8,7 +8,8 @@ * @param height {number} the vertical range of the filter * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values */ -function FilterTexture(gl, width, height, scaleMode) { +function FilterTexture(gl, width, height, scaleMode) +{ /** * @member {WebGLContext} */ @@ -59,7 +60,8 @@ * Clears the filter texture. * */ -FilterTexture.prototype.clear = function () { +FilterTexture.prototype.clear = function () +{ var gl = this.gl; gl.clearColor(0,0,0, 0); @@ -72,8 +74,10 @@ * @param width {number} the new width of the texture * @param height {number} the new height of the texture */ -FilterTexture.prototype.resize = function (width, height) { - if (this.width === width && this.height === height) { +FilterTexture.prototype.resize = function (width, height) +{ + if (this.width === width && this.height === height) + { return; } @@ -96,7 +100,8 @@ * Destroys the filter texture. * */ -FilterTexture.prototype.destroy = function () { +FilterTexture.prototype.destroy = function () +{ var gl = this.gl; gl.deleteFramebuffer( this.frameBuffer ); gl.deleteTexture( this.texture ); diff --git a/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js b/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js index c4721e9..a63f4d7 100644 --- a/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js +++ b/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js @@ -14,7 +14,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this sprite batch works for. */ -function WebGLFastSpriteBatch(renderer) { +function WebGLFastSpriteBatch(renderer) +{ /** * The renderer instance this sprite batch operates on. * @@ -91,7 +92,8 @@ */ this.lastIndexCount = 0; - for (var i=0, j=0; i < numIndices; i += 6, j += 4) { + 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; @@ -144,7 +146,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.setupContext(); }); } @@ -157,7 +160,8 @@ * * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLFastSpriteBatch.prototype.setupContext = function () { +WebGLFastSpriteBatch.prototype.setupContext = function () +{ var gl = this.renderer.gl; // create a couple of buffers @@ -177,7 +181,8 @@ /** * @param spriteBatch {SpriteBatch} The SpriteBatch container to prepare for. */ -WebGLFastSpriteBatch.prototype.begin = function (spriteBatch) { +WebGLFastSpriteBatch.prototype.begin = function (spriteBatch) +{ this.shader = this.renderer.shaderManager.fastShader; this.matrix = spriteBatch.worldTransform.toArray(true); @@ -187,33 +192,38 @@ /** */ -WebGLFastSpriteBatch.prototype.end = function () { +WebGLFastSpriteBatch.prototype.end = function () +{ this.flush(); }; /** * @param spriteBatch {SpriteBatch} The SpriteBatch container to render. */ -WebGLFastSpriteBatch.prototype.render = function (spriteBatch) { +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) { + if (!sprite.texture._uvs) + { return; } this.currentBaseTexture = sprite.texture.baseTexture; // check blend mode - if (sprite.blendMode !== this.renderer.blendModeManager.currentBlendMode) { + if (sprite.blendMode !== this.renderer.blendModeManager.currentBlendMode) + { this.flush(); this.renderer.blendModeManager.setBlendMode(sprite.blendMode); } - for (var i=0,j= children.length; i= this.size) { + if (this.currentBatchSize >= this.size) + { this.flush(); } }; @@ -362,29 +379,35 @@ /** * */ -WebGLFastSpriteBatch.prototype.flush = function () { +WebGLFastSpriteBatch.prototype.flush = function () +{ // If the batch is length 0 then return as there is nothing to draw - if (this.currentBatchSize === 0) { + if (this.currentBatchSize === 0) + { return; } var gl = this.renderer.gl; // bind the current texture - if (!this.currentBaseTexture._glTextures[gl.id]) { + if (!this.currentBaseTexture._glTextures[gl.id]) + { this.renderer.updateTexture(this.currentBaseTexture, gl); } //TODO-SHOUD THIS BE ELSE??!?!?! - else { + else + { gl.bindTexture(gl.TEXTURE_2D, this.currentBaseTexture._glTextures[gl.id]); } // upload the verts to the buffer - if (this.currentBatchSize > ( this.size * 0.5 ) ) { + if (this.currentBatchSize > ( this.size * 0.5 ) ) + { gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); } - else { + else + { var view = this.vertices.subarray(0, this.currentBatchSize * this.vertByteSize); gl.bufferSubData(gl.ARRAY_BUFFER, 0, view); @@ -405,14 +428,16 @@ * Ends the batch and flushes * */ -WebGLFastSpriteBatch.prototype.stop = function () { +WebGLFastSpriteBatch.prototype.stop = function () +{ this.flush(); }; /** * */ -WebGLFastSpriteBatch.prototype.start = function () { +WebGLFastSpriteBatch.prototype.start = function () +{ var gl = this.renderer.gl; // bind the main texture diff --git a/src/core/renderers/webgl/utils/WebGLGraphics.js b/src/core/renderers/webgl/utils/WebGLGraphics.js index 55f4911..ab8f46e 100644 --- a/src/core/renderers/webgl/utils/WebGLGraphics.js +++ b/src/core/renderers/webgl/utils/WebGLGraphics.js @@ -19,7 +19,8 @@ * @param graphics {Graphics} * @param renderer {WebGLRenderer} */ -WebGLGraphics.renderGraphics = function (graphics, renderer) {//projection, offset) { +WebGLGraphics.renderGraphics = function (graphics, renderer) {//projection, offset) +{ var gl = renderer.gl; var projection = renderer.projection, @@ -27,7 +28,8 @@ shader = renderer.shaderManager.primitiveShader, webGLData; - if (graphics.dirty) { + if (graphics.dirty) + { WebGLGraphics.updateGraphics(graphics, gl); } @@ -35,8 +37,10 @@ // This could be speeded up for sure! - for (var i = 0; i < webGL.data.length; i++) { - if (webGL.data[i].mode === 1) { + for (var i = 0; i < webGL.data.length; i++) + { + if (webGL.data[i].mode === 1) + { webGLData = webGL.data[i]; renderer.stencilManager.pushStencil(graphics, webGLData, renderer); @@ -46,7 +50,8 @@ renderer.stencilManager.popStencil(graphics, webGLData, renderer); } - else { + else + { webGLData = webGL.data[i]; @@ -84,12 +89,14 @@ * @param graphicsData {Graphics} The graphics object to update * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLGraphics.updateGraphics = function (graphics, gl) { +WebGLGraphics.updateGraphics = function (graphics, gl) +{ // get the contexts graphics object var webGL = graphics._webGL[gl.id]; // if the graphics object does not exist in the webGL context time to create it! - if (!webGL) { + if (!webGL) + { webGL = graphics._webGL[gl.id] = {lastIndex:0, data:[], gl:gl}; } @@ -99,11 +106,13 @@ var i; // if the user cleared the graphics object we will need to clear every object - if (graphics.clearDirty) { + if (graphics.clearDirty) + { graphics.clearDirty = false; // lop through and return all the webGLDatas to the object pool so than can be reused later on - for (i = 0; i < webGL.data.length; i++) { + for (i = 0; i < webGL.data.length; i++) + { var graphicsData = webGL.data[i]; graphicsData.reset(); WebGLGraphics.graphicsDataPool.push( graphicsData ); @@ -119,58 +128,72 @@ // loop through the graphics datas and construct each one.. // if the object is a complex fill then the new stencil buffer technique will be used // other wise graphics objects will be pushed into a batch.. - for (i = webGL.lastIndex; i < graphics.graphicsData.length; i++) { + for (i = webGL.lastIndex; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { // need to add the points the the graphics object.. data.points = data.shape.points.slice(); - if (data.shape.closed) { + if (data.shape.closed) + { // close the poly if the value is true! - if (data.points[0] !== data.points[data.points.length-2] || data.points[1] !== data.points[data.points.length-1]) { + if (data.points[0] !== data.points[data.points.length-2] || data.points[1] !== data.points[data.points.length-1]) + { data.points.push(data.points[0], data.points[1]); } } // MAKE SURE WE HAVE THE CORRECT TYPE.. - if (data.fill) { - if (data.points.length >= 6) { - if (data.points.length < 6 * 2) { + if (data.fill) + { + if (data.points.length >= 6) + { + if (data.points.length < 6 * 2) + { webGLData = WebGLGraphics.switchMode(webGL, 0); var canDrawUsingSimple = WebGLGraphics.buildPoly(data, webGLData); // console.log(canDrawUsingSimple); - if (!canDrawUsingSimple) { + if (!canDrawUsingSimple) + { // console.log("<>>>") webGLData = WebGLGraphics.switchMode(webGL, 1); WebGLGraphics.buildComplexPoly(data, webGLData); } } - else { + else + { webGLData = WebGLGraphics.switchMode(webGL, 1); WebGLGraphics.buildComplexPoly(data, webGLData); } } } - if (data.lineWidth > 0) { + if (data.lineWidth > 0) + { webGLData = WebGLGraphics.switchMode(webGL, 0); WebGLGraphics.buildLine(data, webGLData); } } - else { + else + { webGLData = WebGLGraphics.switchMode(webGL, 0); - if (data.type === CONST.SHAPES.RECT) { + if (data.type === CONST.SHAPES.RECT) + { WebGLGraphics.buildRectangle(data, webGLData); } - else if (data.type === CONST.SHAPES.CIRC || data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.CIRC || data.type === CONST.SHAPES.ELIP) + { WebGLGraphics.buildCircle(data, webGLData); } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { WebGLGraphics.buildRoundedRectangle(data, webGLData); } } @@ -179,10 +202,12 @@ } // upload all the dirty data... - for (i = 0; i < webGL.data.length; i++) { + for (i = 0; i < webGL.data.length; i++) + { webGLData = webGL.data[i]; - if (webGLData.dirty) { + if (webGLData.dirty) + { webGLData.upload(); } } @@ -194,18 +219,22 @@ * @param webGL {WebGLContext} * @param type {number} */ -WebGLGraphics.switchMode = function (webGL, type) { +WebGLGraphics.switchMode = function (webGL, type) +{ var webGLData; - if (!webGL.data.length) { + if (!webGL.data.length) + { webGLData = WebGLGraphics.graphicsDataPool.pop() || new WebGLGraphicsData(webGL.gl); webGLData.mode = type; webGL.data.push(webGLData); } - else { + else + { webGLData = webGL.data[webGL.data.length-1]; - if (webGLData.mode !== type || type === 1) { + if (webGLData.mode !== type || type === 1) + { webGLData = WebGLGraphics.graphicsDataPool.pop() || new WebGLGraphicsData(webGL.gl); webGLData.mode = type; webGL.data.push(webGLData); @@ -225,7 +254,8 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildRectangle = function (graphicsData, webGLData) { +WebGLGraphics.buildRectangle = function (graphicsData, webGLData) +{ // --- // // need to convert points to a nice regular data // @@ -235,7 +265,8 @@ var width = rectData.width; var height = rectData.height; - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -265,7 +296,8 @@ indices.push(vertPos, vertPos, vertPos+1, vertPos+2, vertPos+3, vertPos+3); } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = [x, y, @@ -289,7 +321,8 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildRoundedRectangle = function (graphicsData, webGLData) { +WebGLGraphics.buildRoundedRectangle = function (graphicsData, webGLData) +{ var rrectData = graphicsData.shape; var x = rrectData.x; var y = rrectData.y; @@ -305,7 +338,8 @@ recPoints = recPoints.concat(WebGLGraphics.quadraticBezierCurve(x + width, y + radius, x + width, y, x + width - radius, y)); recPoints = recPoints.concat(WebGLGraphics.quadraticBezierCurve(x + radius, y, x, y, x, y + radius)); - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -323,7 +357,8 @@ // var i = 0; - for (i = 0; i < triangles.length; i+=3) { + for (i = 0; i < triangles.length; i+=3) + { indices.push(triangles[i] + vecPos); indices.push(triangles[i] + vecPos); indices.push(triangles[i+1] + vecPos); @@ -332,12 +367,14 @@ } - for (i = 0; i < recPoints.length; i++) { + for (i = 0; i < recPoints.length; i++) + { verts.push(recPoints[i], recPoints[++i], r, g, b, alpha); } } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = recPoints; @@ -362,7 +399,8 @@ * @param toY {number} Destination point y * @return {number[]} */ -WebGLGraphics.quadraticBezierCurve = function (fromX, fromY, cpX, cpY, toX, toY) { +WebGLGraphics.quadraticBezierCurve = function (fromX, fromY, cpX, cpY, toX, toY) +{ var xa, ya, @@ -373,14 +411,16 @@ n = 20, points = []; - function getPt(n1 , n2, perc) { + function getPt(n1 , n2, perc) + { var diff = n2 - n1; return n1 + ( diff * perc ); } var j = 0; - for (var i = 0; i <= n; i++ ) { + for (var i = 0; i <= n; i++ ) + { j = i / n; // The Green Line @@ -406,7 +446,8 @@ * @param graphicsData {Graphics} The graphics object to draw * @param webGLData {object} */ -WebGLGraphics.buildCircle = function (graphicsData, webGLData) { +WebGLGraphics.buildCircle = function (graphicsData, webGLData) +{ // need to convert points to a nice regular data var circleData = graphicsData.shape; var x = circleData.x; @@ -415,11 +456,13 @@ var height; // TODO - bit hacky?? - if (graphicsData.type === CONST.SHAPES.CIRC) { + if (graphicsData.type === CONST.SHAPES.CIRC) + { width = circleData.radius; height = circleData.radius; } - else { + else + { width = circleData.width; height = circleData.height; } @@ -429,7 +472,8 @@ var i = 0; - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -444,7 +488,8 @@ indices.push(vecPos); - for (i = 0; i < totalSegs + 1 ; i++) { + for (i = 0; i < totalSegs + 1 ; i++) + { verts.push(x,y, r, g, b, alpha); verts.push(x + Math.sin(seg * i) * width, @@ -457,12 +502,14 @@ indices.push(vecPos-1); } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = []; - for (i = 0; i < totalSegs + 1; i++) { + for (i = 0; i < totalSegs + 1; i++) + { graphicsData.points.push(x + Math.sin(seg * i) * width, y + Math.cos(seg * i) * height); } @@ -481,18 +528,22 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildLine = function (graphicsData, webGLData) { +WebGLGraphics.buildLine = function (graphicsData, webGLData) +{ // TODO OPTIMISE! var i = 0; var points = graphicsData.points; - if (points.length === 0) { + if (points.length === 0) + { return; } // if the line width is an odd number add 0.5 to align to a whole pixel - if (graphicsData.lineWidth%2) { - for (i = 0; i < points.length; i++) { + if (graphicsData.lineWidth%2) + { + for (i = 0; i < points.length; i++) + { points[i] += 0.5; } } @@ -502,7 +553,8 @@ var lastPoint = new math.Point(points[points.length - 2], points[points.length - 1]); // if the first point is the last point - gonna have issues :) - if (firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) { + if (firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) + { // need to clone as we are going to slightly modify the shape.. points = points.slice(); @@ -562,7 +614,8 @@ verts.push(p1x + perpx , p1y + perpy, r, g, b, alpha); - for (i = 1; i < length-1; i++) { + for (i = 1; i < length-1; i++) + { p1x = points[(i-1)*2]; p1y = points[(i-1)*2 + 1]; @@ -599,7 +652,8 @@ denom = a1*b2 - a2*b1; - if (Math.abs(denom) < 0.1 ) { + if (Math.abs(denom) < 0.1 ) + { denom+=10.1; verts.push(p2x - perpx , p2y - perpy, @@ -618,7 +672,8 @@ pdist = (px -p2x) * (px -p2x) + (py -p2y) + (py -p2y); - if (pdist > 140 * 140) { + if (pdist > 140 * 140) + { perp3x = perpx - perp2x; perp3y = perpy - perp2y; @@ -639,7 +694,8 @@ indexCount++; } - else { + else + { verts.push(px , py); verts.push(r, g, b, alpha); @@ -672,7 +728,8 @@ indices.push(indexStart); - for (i = 0; i < indexCount; i++) { + for (i = 0; i < indexCount; i++) + { indices.push(indexStart++); } @@ -687,11 +744,13 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildComplexPoly = function (graphicsData, webGLData) { +WebGLGraphics.buildComplexPoly = function (graphicsData, webGLData) +{ //TODO - no need to copy this as it gets turned into a FLoat32Array anyways.. var points = graphicsData.points.slice(); - if (points.length < 6) { + if (points.length < 6) + { return; } @@ -711,7 +770,8 @@ var x,y; // get size.. - for (var i = 0; i < points.length; i+=2) { + for (var i = 0; i < points.length; i+=2) + { x = points[i]; y = points[i+1]; @@ -732,7 +792,8 @@ //TODO - this aint needed! var length = points.length / 2; - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { indices.push( i ); } @@ -746,10 +807,12 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildPoly = function (graphicsData, webGLData) { +WebGLGraphics.buildPoly = function (graphicsData, webGLData) +{ var points = graphicsData.points; - if (points.length < 6) { + if (points.length < 6) + { return; } // get first and last point.. figure out the middle! @@ -767,7 +830,8 @@ var triangles = utils.PolyK.Triangulate(points); - if (!triangles) { + if (!triangles) + { return false; } @@ -775,7 +839,8 @@ var i = 0; - for (i = 0; i < triangles.length; i+=3) { + for (i = 0; i < triangles.length; i+=3) + { indices.push(triangles[i] + vertPos); indices.push(triangles[i] + vertPos); indices.push(triangles[i+1] + vertPos); @@ -783,7 +848,8 @@ indices.push(triangles[i+2] + vertPos); } - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { verts.push(points[i * 2], points[i * 2 + 1], r, g, b, alpha); } diff --git a/src/core/renderers/webgl/utils/WebGLGraphicsData.js b/src/core/renderers/webgl/utils/WebGLGraphicsData.js index c56d05e..c739ba7 100644 --- a/src/core/renderers/webgl/utils/WebGLGraphicsData.js +++ b/src/core/renderers/webgl/utils/WebGLGraphicsData.js @@ -2,7 +2,8 @@ * @class * @private */ -function WebGLGraphicsData(gl) { +function WebGLGraphicsData(gl) +{ this.gl = gl; //TODO does this need to be split before uploding?? @@ -22,7 +23,8 @@ /** * */ -WebGLGraphicsData.prototype.reset = function () { +WebGLGraphicsData.prototype.reset = function () +{ this.points.length = 0; this.indices.length = 0; }; @@ -30,7 +32,8 @@ /** * */ -WebGLGraphicsData.prototype.upload = function () { +WebGLGraphicsData.prototype.upload = function () +{ var gl = this.gl; // this.lastIndex = graphics.graphicsData.length; diff --git a/src/core/renderers/webgl/utils/WebGLSpriteBatch.js b/src/core/renderers/webgl/utils/WebGLSpriteBatch.js index 96eaa52..55befbb 100644 --- a/src/core/renderers/webgl/utils/WebGLSpriteBatch.js +++ b/src/core/renderers/webgl/utils/WebGLSpriteBatch.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this sprite batch works for. */ -function WebGLSpriteBatch(renderer) { +function WebGLSpriteBatch(renderer) +{ /** * * @@ -88,7 +89,8 @@ */ this.lastIndexCount = 0; - for (var i=0, j=0; i < numIndices; i += 6, j += 4) { + 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; @@ -162,7 +164,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.setupContext(); }); } @@ -173,7 +176,8 @@ /** * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLSpriteBatch.prototype.setupContext = function () { +WebGLSpriteBatch.prototype.setupContext = function () +{ var gl = this.renderer.gl; // setup default shader @@ -198,7 +202,8 @@ /** * */ -WebGLSpriteBatch.prototype.begin = function () { +WebGLSpriteBatch.prototype.begin = function () +{ // this.shader = this.renderer.shaderManager.defaultShader; this.start(); @@ -206,19 +211,22 @@ /** */ -WebGLSpriteBatch.prototype.end = function () { +WebGLSpriteBatch.prototype.end = function () +{ this.flush(); }; /** * @param sprite {Sprite} the sprite to render when using this spritebatch */ -WebGLSpriteBatch.prototype.render = function (sprite) { +WebGLSpriteBatch.prototype.render = function (sprite) +{ var texture = sprite.texture; //TODO set blend modes.. // check texture.. - if (this.currentBatchSize >= this.size) { + if (this.currentBatchSize >= this.size) + { this.flush(); this.currentBaseTexture = texture.baseTexture; } @@ -227,7 +235,8 @@ var uvs = texture._uvs; // if the uvs have not updated then no point rendering just yet! - if (!uvs) { + if (!uvs) + { return; } @@ -237,7 +246,8 @@ var w0, w1, h0, h1; - if (texture.trim) { + 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; @@ -248,7 +258,8 @@ h0 = h1 + texture.crop.height; } - else { + else + { w0 = (texture.frame.width ) * (1-aX); w1 = (texture.frame.width ) * -aX; @@ -272,7 +283,8 @@ var colors = this.colors; var positions = this.positions; - if (this.renderer.roundPixels) { + if (this.renderer.roundPixels) + { // xy positions[index] = a * w1 + c * h1 + tx | 0; positions[index+1] = d * h1 + b * w1 + ty | 0; @@ -289,7 +301,8 @@ positions[index+15] = a * w1 + c * h0 + tx | 0; positions[index+16] = d * h0 + b * w1 + ty | 0; } - else { + else + { // xy positions[index] = a * w1 + c * h1 + tx; positions[index+1] = d * h1 + b * w1 + ty; @@ -338,11 +351,13 @@ * * @param sprite {TilingSprite} the tilingSprite to render */ -WebGLSpriteBatch.prototype.renderTilingSprite = function (tilingSprite) { +WebGLSpriteBatch.prototype.renderTilingSprite = function (tilingSprite) +{ var texture = tilingSprite.tilingTexture; // check texture.. - if (this.currentBatchSize >= this.size) { + if (this.currentBatchSize >= this.size) + { //return; this.flush(); this.currentBaseTexture = texture.baseTexture; @@ -351,7 +366,8 @@ // set the textures uvs temporarily // TODO create a separate texture so that we can tile part of a texture - if (!tilingSprite._uvs) { + if (!tilingSprite._uvs) + { tilingSprite._uvs = new TextureUvs(); } @@ -454,16 +470,19 @@ * Renders the content and empties the current batch. * */ -WebGLSpriteBatch.prototype.flush = function () { +WebGLSpriteBatch.prototype.flush = function () +{ // If the batch is length 0 then return as there is nothing to draw - if (this.currentBatchSize === 0) { + if (this.currentBatchSize === 0) + { return; } var gl = this.renderer.gl; var shader; - if (this.dirty) { + if (this.dirty) + { this.dirty = false; // bind the main texture gl.activeTexture(gl.TEXTURE0); @@ -482,10 +501,12 @@ } // upload the verts to the buffer - if (this.currentBatchSize > ( this.size * 0.5 ) ) { + if (this.currentBatchSize > ( this.size * 0.5 ) ) + { gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); } - else { + else + { var view = this.positions.subarray(0, this.currentBatchSize * this.vertByteSize); gl.bufferSubData(gl.ARRAY_BUFFER, 0, view); } @@ -502,7 +523,8 @@ var shaderSwap = false; var sprite; - for (var i = 0, j = this.currentBatchSize; i < j; i++) { + for (var i = 0, j = this.currentBatchSize; i < j; i++) + { sprite = this.sprites[i]; @@ -513,24 +535,28 @@ blendSwap = currentBlendMode !== nextBlendMode; shaderSwap = currentShader !== nextShader; // should I use uuidS??? - if (currentBaseTexture !== nextTexture || blendSwap || shaderSwap) { + if (currentBaseTexture !== nextTexture || blendSwap || shaderSwap) + { this.renderBatch(currentBaseTexture, batchSize, start); start = i; batchSize = 0; currentBaseTexture = nextTexture; - if (blendSwap) { + if (blendSwap) + { currentBlendMode = nextBlendMode; this.renderer.blendModeManager.setBlendMode( currentBlendMode ); } - if (shaderSwap) { + if (shaderSwap) + { currentShader = nextShader; shader = currentShader.shaders ? currentShader.shaders[gl.id] : currentShader; - if (!shader) { + if (!shader) + { shader = new Shader(gl, null, currentShader.fragmentSrc, currentShader.uniforms); currentShader.shaders[gl.id] = shader; } @@ -538,7 +564,8 @@ // set shader function??? this.renderer.shaderManager.setShader(shader); - if (shader.dirty) { + if (shader.dirty) + { shader.syncUniforms(); } @@ -569,17 +596,21 @@ * @param size {number} * @param startIndex {number} */ -WebGLSpriteBatch.prototype.renderBatch = function (texture, size, startIndex) { - if (size === 0) { +WebGLSpriteBatch.prototype.renderBatch = function (texture, size, startIndex) +{ + if (size === 0) + { return; } var gl = this.renderer.gl; - if (!texture._glTextures[gl.id]) { + if (!texture._glTextures[gl.id]) + { this.renderer.updateTexture(texture); } - else { + else + { // bind the current texture gl.bindTexture(gl.TEXTURE_2D, texture._glTextures[gl.id]); } @@ -594,7 +625,8 @@ /** * */ -WebGLSpriteBatch.prototype.stop = function () { +WebGLSpriteBatch.prototype.stop = function () +{ this.flush(); this.dirty = true; }; @@ -602,7 +634,8 @@ /** * */ -WebGLSpriteBatch.prototype.start = function () { +WebGLSpriteBatch.prototype.start = function () +{ this.dirty = true; }; @@ -610,7 +643,8 @@ * Destroys the SpriteBatch. * */ -WebGLSpriteBatch.prototype.destroy = function () { +WebGLSpriteBatch.prototype.destroy = function () +{ this.renderer.gl.deleteBuffer(this.vertexBuffer); this.renderer.gl.deleteBuffer(this.indexBuffer); diff --git a/src/core/textures/BaseTexture.js b/src/core/textures/BaseTexture.js index 2bf77d4..513d358 100644 --- a/src/core/textures/BaseTexture.js +++ b/src/core/textures/BaseTexture.js @@ -10,7 +10,8 @@ * @param source {Image|Canvas} the source object of the texture. * @param [scaleMode=scaleModes.DEFAULT] {number} See {@link scaleModes} for possible values */ -function BaseTexture(source, scaleMode) { +function BaseTexture(source, scaleMode) +{ this.uuid = utils.uuid(); /** @@ -123,7 +124,8 @@ this._needsUpdate = false; // if no source passed don't try to load - if (source) { + if (source) + { this.loadSource(source); } @@ -149,13 +151,16 @@ Object.defineProperties(BaseTexture.prototype, { needsUpdate: { - get: function () { + get: function () + { return this._needsUpdate; }, - set: function (val) { + set: function (val) + { this._needsUpdate = val; - if (val) { + if (val) + { this.emit('update', this); } } @@ -171,9 +176,11 @@ * * The logic state after calling `loadSource` directly or indirectly (eg. `fromImage`, `new BaseTexture`) is: * - * if (texture.hasLoaded) { + * if (texture.hasLoaded) + { * // texture ready for use - * } else if (texture.isLoading) { + * } else if (texture.isLoading) + { * // listen to 'loaded' and/or 'error' events on texture * } else { * // not loading, not going to load UNLESS the source is reloaded @@ -183,12 +190,14 @@ * @protected * @param source {Image|Canvas} the source object of the texture. */ -BaseTexture.prototype.loadSource = function (source) { +BaseTexture.prototype.loadSource = function (source) +{ var wasLoading = this.isLoading; this.hasLoaded = false; this.isLoading = false; - if (wasLoading && this.source) { + if (wasLoading && this.source) + { this.source.onload = null; this.source.onerror = null; } @@ -196,20 +205,24 @@ this.source = source; // Apply source if loaded. Otherwise setup appropriate loading monitors. - if ((this.source.complete || this.source.getContext) && this.source.width && this.source.height) { + if ((this.source.complete || this.source.getContext) && this.source.width && this.source.height) + { this._sourceLoaded(); } - else if(!source.getContext) { + else if(!source.getContext) + { // Image fail / not ready this.isLoading = true; var scope = this; - source.onload = function () { + source.onload = function () + { source.onload = null; source.onerror = null; - if(!scope.isLoading) { + if(!scope.isLoading) + { return; } @@ -219,11 +232,13 @@ scope.emit('loaded', scope); }; - source.onerror = function () { + source.onerror = function () + { source.onload = null; source.onerror = null; - if(!scope.isLoading) { + if(!scope.isLoading) + { return; } @@ -234,24 +249,29 @@ // Per http://www.w3.org/TR/html5/embedded-content-0.html#the-img-element // "The value of `complete` can thus change while a script is executing." // So complete needs to be re-checked after the callbacks have been added.. - if (source.complete) { + if (source.complete) + { this.isLoading = false; // ..and if we're complete now, no need for callbacks source.onload = null; source.onerror = null; - if (source.width && source.height) { + if (source.width && source.height) + { this._sourceLoaded(); // If any previous subscribers possible - if (wasLoading) { + if (wasLoading) + { this.emit('loaded', this); } } - else { + else + { // If any previous subscribers possible - if (wasLoading) { + if (wasLoading) + { this.emit('error', this); } } @@ -265,7 +285,8 @@ * * @private */ -BaseTexture.prototype._sourceLoaded = function () { +BaseTexture.prototype._sourceLoaded = function () +{ this.hasLoaded = true; this.width = this.source.naturalWidth || this.source.width; @@ -278,16 +299,20 @@ * Destroys this base texture * */ -BaseTexture.prototype.destroy = function () { - if (this.imageUrl) { +BaseTexture.prototype.destroy = function () +{ + if (this.imageUrl) + { delete utils.BaseTextureCache[this.imageUrl]; delete utils.TextureCache[this.imageUrl]; this.imageUrl = null; - if (!navigator.isCocoonJS) { + if (!navigator.isCocoonJS) + { this.source.src = ''; } } - else if (this.source && this.source._pixiId) { + else if (this.source && this.source._pixiId) + { delete utils.BaseTextureCache[this.source._pixiId]; } this.source = null; @@ -301,7 +326,8 @@ * memory again. * */ -BaseTexture.prototype.dispose = function () { +BaseTexture.prototype.dispose = function () +{ this.emit('dispose', this); }; @@ -311,7 +337,8 @@ * * @param newSrc {string} the path of the image */ -BaseTexture.prototype.updateSourceImage = function (newSrc) { +BaseTexture.prototype.updateSourceImage = function (newSrc) +{ this.source.src = newSrc; this.loadSource(this.source); }; @@ -326,18 +353,22 @@ * @param [scaleMode=scaleModes.DEFAULT] {number} See {@link scaleModes} for possible values * @return BaseTexture */ -BaseTexture.fromImage = function (imageUrl, crossorigin, scaleMode) { +BaseTexture.fromImage = function (imageUrl, crossorigin, scaleMode) +{ var baseTexture = utils.BaseTextureCache[imageUrl]; - if (crossorigin === undefined && imageUrl.indexOf('data:') !== 0) { + if (crossorigin === undefined && imageUrl.indexOf('data:') !== 0) + { crossorigin = true; } - if (!baseTexture) { + if (!baseTexture) + { // new Image() breaks tex loading in some versions of Chrome. // See https://code.google.com/p/chromium/issues/detail?id=238071 var image = new Image();//document.createElement('img'); - if (crossorigin) { + if (crossorigin) + { image.crossOrigin = ''; } @@ -347,7 +378,8 @@ utils.BaseTextureCache[imageUrl] = baseTexture; // if there is an @2x at the end of the url we are going to assume its a highres image - if ( imageUrl.indexOf(CONST.RETINA_PREFIX + '.') !== -1) { + if ( imageUrl.indexOf(CONST.RETINA_PREFIX + '.') !== -1) + { baseTexture.resolution = 2; } } @@ -363,14 +395,17 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return BaseTexture */ -BaseTexture.fromCanvas = function (canvas, scaleMode) { - if (!canvas._pixiId) { +BaseTexture.fromCanvas = function (canvas, scaleMode) +{ + if (!canvas._pixiId) + { canvas._pixiId = 'canvas_' + utils.uuid(); } var baseTexture = utils.BaseTextureCache[canvas._pixiId]; - if (!baseTexture) { + if (!baseTexture) + { baseTexture = new BaseTexture(canvas, scaleMode); utils.BaseTextureCache[canvas._pixiId] = baseTexture; } diff --git a/src/core/textures/RenderTexture.js b/src/core/textures/RenderTexture.js index 6dad20f..53ae796 100644 --- a/src/core/textures/RenderTexture.js +++ b/src/core/textures/RenderTexture.js @@ -46,8 +46,10 @@ * @param [scaleMode] {number} See {@link scaleModes} for possible values * @param [resolution=1] {number} The resolution of the texture being generated */ -function RenderTexture(renderer, width, height, scaleMode, resolution) { - if (!renderer) { +function RenderTexture(renderer, width, height, scaleMode, resolution) +{ + if (!renderer) + { throw new Error('Unable to create RenderTexture, you must pass a renderer into the constructor.'); } @@ -133,7 +135,8 @@ */ this.renderer = renderer; - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { var gl = this.renderer.gl; this.textureBuffer = new FilterTexture(gl, this.width * this.resolution, this.height * this.resolution, this.baseTexture.scaleMode); @@ -142,7 +145,8 @@ this.render = this.renderWebGL; this.projection = new math.Point(this.width*0.5, -this.height*0.5); } - else { + else + { this.render = this.renderCanvas; this.textureBuffer = new CanvasBuffer(this.width* this.resolution, this.height* this.resolution); this.baseTexture.source = this.textureBuffer.canvas; @@ -167,8 +171,10 @@ * @param height {number} The height to resize to. * @param updateBase {boolean} Should the baseTexture.width and height values be resized as well? */ -RenderTexture.prototype.resize = function (width, height, updateBase) { - if (width === this.width && height === this.height) { +RenderTexture.prototype.resize = function (width, height, updateBase) +{ + if (width === this.width && height === this.height) + { return; } @@ -177,17 +183,20 @@ this.width = this.frame.width = this.crop.width = width; this.height = this.frame.height = this.crop.height = height; - if (updateBase) { + if (updateBase) + { this.baseTexture.width = this.width; this.baseTexture.height = this.height; } - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { this.projection.x = this.width / 2; this.projection.y = -this.height / 2; } - if (!this.valid) { + if (!this.valid) + { return; } @@ -198,12 +207,15 @@ * Clears the RenderTexture. * */ -RenderTexture.prototype.clear = function () { - if (!this.valid) { +RenderTexture.prototype.clear = function () +{ + if (!this.valid) + { return; } - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { this.renderer.gl.bindFramebuffer(this.renderer.gl.FRAMEBUFFER, this.textureBuffer.frameBuffer); } @@ -220,19 +232,23 @@ * @param [restoreWorldTransform=true] {boolean} If true the displayObject's worldTransform/worldAlpha and all children * transformations will be restored. Not restoring this information will be a little faster. */ -RenderTexture.prototype.renderWebGL = function (displayObject, matrix, clear, restoreWorldTransform) { - if (!this.valid) { +RenderTexture.prototype.renderWebGL = function (displayObject, matrix, clear, restoreWorldTransform) +{ + if (!this.valid) + { return; } - if (typeof restoreWorldTransform === 'undefined') { + if (typeof restoreWorldTransform === 'undefined') + { restoreWorldTransform = true; } var tempAlpha, tempTransform; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { tempAlpha = displayObject.worldAlpha; tempTransform = displayObject.worldTransform.toArray(); } @@ -245,7 +261,8 @@ wt.identity(); wt.translate(0, this.projection.y * 2); - if (matrix) { + if (matrix) + { wt.append(matrix); } @@ -258,7 +275,8 @@ var children = displayObject.children; var i, j; - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } @@ -269,7 +287,8 @@ gl.bindFramebuffer(gl.FRAMEBUFFER, this.textureBuffer.frameBuffer ); - if (clear) { + if (clear) + { this.textureBuffer.clear(); } @@ -279,11 +298,13 @@ this.renderer.spriteBatch.dirty = true; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { displayObject.worldAlpha = tempAlpha; displayObject.worldTransform.fromArray(tempTransform); - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } } @@ -300,26 +321,31 @@ * @param [restoreWorldTransform=true] {boolean} If true the displayObject's worldTransform/worldAlpha and all children * transformations will be restored. Not restoring this information will be a little faster. */ -RenderTexture.prototype.renderCanvas = function (displayObject, matrix, clear, restoreWorldTransform) { - if (!this.valid) { +RenderTexture.prototype.renderCanvas = function (displayObject, matrix, clear, restoreWorldTransform) +{ + if (!this.valid) + { return; } - if (typeof restoreWorldTransform === 'undefined') { + if (typeof restoreWorldTransform === 'undefined') + { restoreWorldTransform = true; } var tempAlpha, tempTransform; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { tempAlpha = displayObject.worldAlpha; tempTransform = displayObject.worldTransform.toArray(); } var wt = displayObject.worldTransform; wt.identity(); - if (matrix) { + if (matrix) + { wt.append(matrix); } @@ -330,11 +356,13 @@ var children = displayObject.children; var i, j; - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } - if (clear) { + if (clear) + { this.textureBuffer.clear(); } @@ -348,11 +376,13 @@ this.renderer.resolution = realResolution; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { displayObject.worldAlpha = tempAlpha; displayObject.worldTransform.fromArray(tempTransform); - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } } @@ -363,7 +393,8 @@ * * @return {Image} */ -RenderTexture.prototype.getImage = function () { +RenderTexture.prototype.getImage = function () +{ var image = new Image(); image.src = this.getBase64(); return image; @@ -374,7 +405,8 @@ * * @return {string} A base64 encoded string of the texture. */ -RenderTexture.prototype.getBase64 = function () { +RenderTexture.prototype.getBase64 = function () +{ return this.getCanvas().toDataURL(); }; @@ -383,8 +415,10 @@ * * @return {HTMLCanvasElement} A Canvas element with the texture rendered on. */ -RenderTexture.prototype.getCanvas = function () { - if (this.renderer.type === CONST.WEBGL_RENDERER) { +RenderTexture.prototype.getCanvas = function () +{ + if (this.renderer.type === CONST.WEBGL_RENDERER) + { var gl = this.renderer.gl; var width = this.textureBuffer.width; var height = this.textureBuffer.height; @@ -403,7 +437,8 @@ return tempCanvas.canvas; } - else { + else + { return this.textureBuffer.canvas; } }; diff --git a/src/core/textures/Texture.js b/src/core/textures/Texture.js index 3c65909..e97f0aa 100644 --- a/src/core/textures/Texture.js +++ b/src/core/textures/Texture.js @@ -17,7 +17,8 @@ * @param [crop] {Rectangle} The area of original texture * @param [trim] {Rectangle} Trimmed texture rectangle */ -function Texture(baseTexture, frame, crop, trim) { +function Texture(baseTexture, frame, crop, trim) +{ /** * Does this Texture have any frame data assigned to it? * @@ -25,12 +26,14 @@ */ this.noFrame = false; - if (!frame) { + if (!frame) + { this.noFrame = true; frame = new math.Rectangle(0, 0, 1, 1); } - if (baseTexture instanceof Texture) { + if (baseTexture instanceof Texture) + { baseTexture = baseTexture.baseTexture; } @@ -100,13 +103,16 @@ */ this.crop = crop || new math.Rectangle(0, 0, 1, 1); - if (baseTexture.hasLoaded) { - if (this.noFrame) { + if (baseTexture.hasLoaded) + { + if (this.noFrame) + { frame = new math.Rectangle(0, 0, baseTexture.width, baseTexture.height); } this.frame = frame; } - else { + else + { baseTexture.addEventListener('loaded', this.onBaseTextureLoaded.bind(this)); } } @@ -118,19 +124,23 @@ Object.defineProperties(Texture.prototype, { needsUpdate: { - get: function () { + get: function () + { return this.baseTexture.needsUpdate; }, - set: function (val) { + set: function (val) + { this.baseTexture.needsUpdate = val; } }, frame: { - get: function () { + get: function () + { return this._frame; }, - set: function (frame) { + set: function (frame) + { this._frame = frame; this.noFrame = false; @@ -143,20 +153,23 @@ 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 (!this.trim && (frame.x + frame.width > this.baseTexture.width || frame.y + frame.height > this.baseTexture.height)) + { throw new Error('Texture Error: frame does not fit inside the base Texture dimensions ' + this); } this.valid = frame && frame.width && frame.height && this.baseTexture.source && this.baseTexture.hasLoaded; - if (this.trim) { + 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) { + if (this.valid) + { this._updateUvs(); } } @@ -168,11 +181,13 @@ * * @private */ -Texture.prototype.onBaseTextureLoaded = function () { +Texture.prototype.onBaseTextureLoaded = function () +{ var baseTexture = this.baseTexture; baseTexture.removeEventListener('loaded', this.onLoaded); - if (this.noFrame) { + if (this.noFrame) + { this.frame = new math.Rectangle(0, 0, baseTexture.width, baseTexture.height); } @@ -184,8 +199,10 @@ * * @param destroyBase {boolean} Whether to destroy the base texture as well */ -Texture.prototype.destroy = function (destroyBase) { - if (destroyBase) { +Texture.prototype.destroy = function (destroyBase) +{ + if (destroyBase) + { this.baseTexture.destroy(); } @@ -197,8 +214,10 @@ * * @private */ -Texture.prototype._updateUvs = function () { - if (!this._uvs) { +Texture.prototype._updateUvs = function () +{ + if (!this._uvs) + { this._uvs = new TextureUvs(); } @@ -229,10 +248,12 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return Texture */ -Texture.fromImage = function (imageUrl, crossorigin, scaleMode) { +Texture.fromImage = function (imageUrl, crossorigin, scaleMode) +{ var texture = utils.TextureCache[imageUrl]; - if (!texture) { + if (!texture) + { texture = new Texture(BaseTexture.fromImage(imageUrl, crossorigin, scaleMode)); utils.TextureCache[imageUrl] = texture; } @@ -248,9 +269,11 @@ * @param frameId {string} The frame id of the texture * @return Texture */ -Texture.fromFrame = function (frameId) { +Texture.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache '); } return texture; @@ -264,7 +287,8 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return {Texture} */ -Texture.fromCanvas = function (canvas, scaleMode) { +Texture.fromCanvas = function (canvas, scaleMode) +{ return new Texture(BaseTexture.fromCanvas(canvas, scaleMode)); }; @@ -276,7 +300,8 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return {Texture} A Texture */ -Texture.fromVideo = function (video, scaleMode) { +Texture.fromVideo = function (video, scaleMode) +{ return new Texture(VideoBaseTexture.baseTextureFromVideo(video, scaleMode)); }; @@ -287,7 +312,8 @@ * @param texture {Texture} The Texture to add to the cache. * @param id {string} The id that the texture will be stored against. */ -Texture.addTextureToCache = function (texture, id) { +Texture.addTextureToCache = function (texture, id) +{ utils.TextureCache[id] = texture; }; @@ -298,7 +324,8 @@ * @param id {string} The id of the texture to be removed * @return {Texture} The texture that was removed */ -Texture.removeTextureFromCache = function (id) { +Texture.removeTextureFromCache = function (id) +{ var texture = utils.TextureCache[id]; delete utils.TextureCache[id]; diff --git a/src/core/textures/TextureUvs.js b/src/core/textures/TextureUvs.js index b9bbb58..5424d52 100644 --- a/src/core/textures/TextureUvs.js +++ b/src/core/textures/TextureUvs.js @@ -1,4 +1,5 @@ -function TextureUvs() { +function TextureUvs() +{ this.x0 = 0; this.y0 = 0; diff --git a/src/core/textures/VideoBaseTexture.js b/src/core/textures/VideoBaseTexture.js index e3e0c5a..1a826a9 100644 --- a/src/core/textures/VideoBaseTexture.js +++ b/src/core/textures/VideoBaseTexture.js @@ -12,15 +12,18 @@ * @param source {HTMLVideoElement} * @param [scaleMode] {number} See {@link scaleModes} for possible values */ -function VideoBaseTexture(source, scaleMode) { - if (!source){ +function VideoBaseTexture(source, scaleMode) +{ + if (!source) + { throw new Error('No video source element specified.'); } // hook in here to check if video is already available. // BaseTexture looks for a source.complete boolean, plus width & height. - if ((source.readyState === source.HAVE_ENOUGH_DATA || source.readyState === source.HAVE_FUTURE_DATA) && source.width && source.height) { + if ((source.readyState === source.HAVE_ENOUGH_DATA || source.readyState === source.HAVE_FUTURE_DATA) && source.width && source.height) + { source.complete = true; } @@ -31,7 +34,8 @@ this._boundOnUpdate = this._onUpdate.bind(this); this._boundOnCanPlay = this._onCanPlay.bind(this); - if (!source.complete) { + if (!source.complete) + { source.addEventListener('canplay', this._boundOnCanPlay); source.addEventListener('canplaythrough', this._boundOnCanPlay); @@ -47,28 +51,35 @@ VideoBaseTexture.prototype.constructor = VideoBaseTexture; module.exports = VideoBaseTexture; -VideoBaseTexture.prototype._onUpdate = function () { - if (this.autoUpdate) { +VideoBaseTexture.prototype._onUpdate = function () +{ + if (this.autoUpdate) + { window.requestAnimationFrame(this._boundOnUpdate); this.needsUpdate = true; } }; -VideoBaseTexture.prototype._onPlayStart = function () { - if (!this.autoUpdate) { +VideoBaseTexture.prototype._onPlayStart = function () +{ + if (!this.autoUpdate) + { window.requestAnimationFrame(this._boundOnUpdate); this.autoUpdate = true; } }; -VideoBaseTexture.prototype._onPlayStop = function () { +VideoBaseTexture.prototype._onPlayStop = function () +{ this.autoUpdate = false; }; -VideoBaseTexture.prototype._onCanPlay = function () { +VideoBaseTexture.prototype._onCanPlay = function () +{ this.hasLoaded = true; - if (this.source) { + if (this.source) + { this.source.removeEventListener('canplay', this._boundOnCanPlay); this.source.removeEventListener('canplaythrough', this._boundOnCanPlay); @@ -78,15 +89,18 @@ this.source.play(); // prevent multiple loaded dispatches.. - if(!this.__loaded){ + if(!this.__loaded) + { this.__loaded = true; this.emit('loaded', this); } } }; -VideoBaseTexture.prototype.destroy = function () { - if (this.source && this.source._pixiId) { +VideoBaseTexture.prototype.destroy = function () +{ + if (this.source && this.source._pixiId) + { utils.BaseTextureCache[ this.source._pixiId ] = null; delete utils.BaseTextureCache[ this.source._pixiId ]; @@ -105,14 +119,17 @@ * @param scaleMode {number} See {@link scaleModes} for possible values * @return {VideoBaseTexture} */ -VideoBaseTexture.fromVideo = function (video, scaleMode) { - if (!video._pixiId) { +VideoBaseTexture.fromVideo = function (video, scaleMode) +{ + if (!video._pixiId) + { video._pixiId = 'video_' + utils.uuid(); } var baseTexture = utils.BaseTextureCache[video._pixiId]; - if (!baseTexture) { + if (!baseTexture) + { baseTexture = new VideoBaseTexture(video, scaleMode); utils.BaseTextureCache[ video._pixiId ] = baseTexture; } @@ -147,17 +164,21 @@ * @param scaleMode {number} See {@link scaleModes} for possible values * @return {VideoBaseTexture} */ -VideoBaseTexture.fromUrl = function (videoSrc, scaleMode) { +VideoBaseTexture.fromUrl = function (videoSrc, scaleMode) +{ var video = document.createElement('video'); // array of objects or strings - if (Array.isArray(videoSrc)) { - for (var i = 0; i < videoSrc.length; ++i) { + if (Array.isArray(videoSrc)) + { + for (var i = 0; i < videoSrc.length; ++i) + { video.appendChild(createSource(videoSrc.src || videoSrc, videoSrc.mime)); } } // single object or string - else { + else + { video.appendChild(createSource(videoSrc.src || videoSrc, videoSrc.mime)); } @@ -169,8 +190,10 @@ VideoBaseTexture.fromUrls = VideoBaseTexture.fromUrl; -function createSource(path, type) { - if (!type) { +function createSource(path, type) +{ + if (!type) + { type = 'video/' + path.substr(path.lastIndexOf('.') + 1); } diff --git a/src/core/utils/EventData.js b/src/core/utils/EventData.js index 5d55a22..8cdf701 100644 --- a/src/core/utils/EventData.js +++ b/src/core/utils/EventData.js @@ -7,7 +7,8 @@ * @param name {string} The string name of the event that was triggered * @param data {object} Arbitrary event data to pass along */ -function EventData(target, name, data) { +function EventData(target, name, data) +{ // for duck typing in the ".on()" function this.__isEventObject = true; @@ -71,7 +72,8 @@ * Stops the propagation of events up the scene graph (prevents bubbling). * */ -EventData.prototype.stopPropagation = function stopPropagation() { +EventData.prototype.stopPropagation = function stopPropagation() +{ this.stopped = true; }; @@ -79,6 +81,7 @@ * Stops the propagation of events to sibling listeners (no longer calls any listeners). * */ -EventData.prototype.stopImmediatePropagation = function stopImmediatePropagation() { +EventData.prototype.stopImmediatePropagation = function stopImmediatePropagation() +{ this.stoppedImmediate = true; }; diff --git a/src/core/utils/EventTarget.js b/src/core/utils/EventTarget.js index 7ae8820..671a151 100644 --- a/src/core/utils/EventTarget.js +++ b/src/core/utils/EventTarget.js @@ -13,14 +13,16 @@ * var em = new MyEmitter(); * em.emit('eventName', 'some data', 'some more data', {}, null, ...); */ -function eventTarget(obj) { +function eventTarget(obj) +{ /** * Return a list of assigned event listeners. * * @param eventName {string} The events that should be listed. * @return {Array} An array of listener functions */ - obj.listeners = function listeners(eventName) { + obj.listeners = function listeners(eventName) + { this._listeners = this._listeners || {}; return this._listeners[eventName] ? this._listeners[eventName].slice() : []; @@ -33,22 +35,26 @@ * @param eventName {string} The name of the event. * @return {boolean} Indication if we've emitted an event. */ - obj.emit = obj.dispatchEvent = function emit(eventName, data) { + obj.emit = obj.dispatchEvent = function emit(eventName, data) + { this._listeners = this._listeners || {}; // fast return when there are no listeners - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return; } //backwards compat with old method ".emit({ type: 'something' })" - if (typeof eventName === 'object') { + if (typeof eventName === 'object') + { data = eventName; eventName = eventName.type; } //ensure we are using a real pixi event - if (!data || data.__isEventObject !== true) { + if (!data || data.__isEventObject !== true) + { data = new EventData(this, eventName, data); } @@ -58,23 +64,27 @@ fn = listeners[0], i; - for (i = 0; i < length; fn = listeners[++i]) { + for (i = 0; i < length; fn = listeners[++i]) + { //call the event listener fn.call(this, data); //if "stopImmediatePropagation" is called, stop calling sibling events - if (data.stoppedImmediate) { + if (data.stoppedImmediate) + { return this; } } //if "stopPropagation" is called then don't bubble the event - if (data.stopped) { + if (data.stopped) + { return this; } //bubble this event up the scene graph - if (this.parent && this.parent.emit) { + if (this.parent && this.parent.emit) + { this.parent.emit.call(this.parent, eventName, data); } @@ -88,7 +98,8 @@ * @param eventName {string} Name of the event. * @param callback {Functon} fn Callback function. */ - obj.on = obj.addEventListener = function on(eventName, fn) { + obj.on = obj.addEventListener = function on(eventName, fn) + { this._listeners = this._listeners || {}; (this._listeners[eventName] = this._listeners[eventName] || []) @@ -103,11 +114,13 @@ * @param eventName {string} Name of the event. * @param callback {Function} Callback function. */ - obj.once = function once(eventName, fn) { + obj.once = function once(eventName, fn) + { this._listeners = this._listeners || {}; var self = this; - function onceHandlerWrapper() { + function onceHandlerWrapper() + { fn.apply(self.off(eventName, onceHandlerWrapper), arguments); } onceHandlerWrapper._originalHandler = fn; @@ -122,23 +135,28 @@ * @param eventName {string} The event we want to remove. * @param callback {Function} The listener that we need to find. */ - obj.off = obj.removeEventListener = function off(eventName, fn) { + obj.off = obj.removeEventListener = function off(eventName, fn) + { this._listeners = this._listeners || {}; - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return this; } var list = this._listeners[eventName], i = fn ? list.length : 0; - while(i-- > 0) { - if (list[i] === fn || list[i]._originalHandler === fn) { + while(i-- > 0) + { + if (list[i] === fn || list[i]._originalHandler === fn) + { list.splice(i, 1); } } - if (list.length === 0) { + if (list.length === 0) + { delete this._listeners[eventName]; } @@ -150,10 +168,12 @@ * * @param eventName {string} The event you want to remove all listeners for. */ - obj.removeAllListeners = function removeAllListeners(eventName) { + obj.removeAllListeners = function removeAllListeners(eventName) + { this._listeners = this._listeners || {}; - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return this; } @@ -169,7 +189,8 @@ * * @param object {object} The obj to mix into */ - mixin: function mixin(obj) { + mixin: function mixin(obj) + { eventTarget(obj); } }; diff --git a/src/core/utils/PolyK.js b/src/core/utils/PolyK.js index 7325141..5e20c2b 100644 --- a/src/core/utils/PolyK.js +++ b/src/core/utils/PolyK.js @@ -47,7 +47,8 @@ * Triangulates shapes for webGL graphic fills. * */ -PolyK.Triangulate = function (p) { +PolyK.Triangulate = function (p) +{ var sign = true; var n = p.length >> 1; @@ -59,7 +60,8 @@ i = 0; var al = n; - while(al > 3) { + while(al > 3) + { var i0 = avl[(i+0)%al]; var i1 = avl[(i+1)%al]; var i2 = avl[(i+2)%al]; @@ -69,29 +71,35 @@ var cx = p[2*i2], cy = p[2*i2+1]; var earFound = false; - if (PolyK._convex(ax, ay, bx, by, cx, cy, sign)) { + if (PolyK._convex(ax, ay, bx, by, cx, cy, sign)) + { earFound = true; - for (var j = 0; j < al; j++) { + for (var j = 0; j < al; j++) + { var vi = avl[j]; if (vi === i0 || vi === i1 || vi === i2) continue; - if (PolyK._PointInTriangle(p[2*vi], p[2*vi+1], ax, ay, bx, by, cx, cy)) { + if (PolyK._PointInTriangle(p[2*vi], p[2*vi+1], ax, ay, bx, by, cx, cy)) + { earFound = false; break; } } } - if (earFound) { + if (earFound) + { tgs.push(i0, i1, i2); avl.splice((i+1)%al, 1); al--; i = 0; } - else if (i++ > 3*al) { + else if (i++ > 3*al) + { // need to flip flip reverse it! // reset! - if (sign) { + if (sign) + { tgs = []; avl = []; for (i = 0; i < n; i++) avl.push(i); @@ -101,7 +109,8 @@ sign = false; } - else { + else + { // window.console.log("PIXI Warning: shape too complex to fill"); return null; } @@ -126,7 +135,8 @@ * @private * @return {boolean} */ -PolyK._PointInTriangle = function (px, py, ax, ay, bx, by, cx, cy) { +PolyK._PointInTriangle = function (px, py, ax, ay, bx, by, cx, cy) +{ var v0x = cx-ax; var v0y = cy-ay; var v1x = bx-ax; @@ -154,6 +164,7 @@ * @private * @return {boolean} */ -PolyK._convex = function (ax, ay, bx, by, cx, cy, sign) { +PolyK._convex = function (ax, ay, bx, by, cx, cy, sign) +{ return ((ay-by)*(cx-bx) + (bx-ax)*(cy-by) >= 0) === sign; }; diff --git a/src/core/utils/index.js b/src/core/utils/index.js index ade9831..bfae7ae 100644 --- a/src/core/utils/index.js +++ b/src/core/utils/index.js @@ -16,7 +16,8 @@ * * @return {number} The next uuid to use. */ - uuid: function () { + uuid: function () + { return ++utils._uid; }, @@ -26,7 +27,8 @@ * @param hex {number} * @return {number[]} An array representing the [R, G, B] of the color. */ - hex2rgb: function (hex, out) { + hex2rgb: function (hex, out) + { out = out || []; out[0] = (hex >> 16 & 0xFF) / 255; @@ -42,7 +44,8 @@ * @param hex {number} * @return {string} The string color. */ - hex2string: function (hex) { + hex2string: function (hex) + { hex = hex.toString(16); hex = '000000'.substr(0, 6 - hex.length) + hex; @@ -55,7 +58,8 @@ * @param rgb {number[]} * @return {number} The color number */ - rgb2hex: function (rgb) { + rgb2hex: function (rgb) + { return ((rgb[0]*255 << 16) + (rgb[1]*255 << 8) + rgb[2]*255); }, @@ -64,8 +68,10 @@ * * @return {boolean} whether they are supported */ - canUseNewCanvasBlendModes: function () { - if (typeof document === 'undefined') { + canUseNewCanvasBlendModes: function () + { + if (typeof document === 'undefined') + { return false; } @@ -93,15 +99,19 @@ * @param number {number} * @return {number} the closest number that is a power of two */ - getNextPowerOfTwo: function (number) { + getNextPowerOfTwo: function (number) + { // see: http://en.wikipedia.org/wiki/Power_of_two#Fast_algorithm_to_check_if_a_positive_number_is_a_power_of_two - if (number > 0 && (number & (number - 1)) === 0) { + if (number > 0 && (number & (number - 1)) === 0) + { return number; } - else { + else + { var result = 1; - while (result < number) { + while (result < number) + { result <<= 1; } @@ -116,7 +126,8 @@ * @param height {number} * @return {boolean} */ - isPowerOfTwo: function (width, height) { + isPowerOfTwo: function (width, height) + { return (width > 0 && (width & (width - 1)) === 0 && height > 0 && (height & (height - 1)) === 0); }, @@ -130,12 +141,15 @@ * @constant * @static */ - sayHello: function (type) { - if (utils._saidHello) { + sayHello: function (type) + { + if (utils._saidHello) + { return; } - if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) { + if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) + { var args = [ '%c %c %c Pixi.js ' + CONST.VERSION + ' - ' + type + ' %c ' + ' %c ' + ' http://www.pixijs.com/ %c %c ♥%c♥%c♥ ', 'background: #ff66a5', @@ -151,7 +165,8 @@ console.log.apply(console, args); //jshint ignore:line } - else if (window.console) { + else if (window.console) + { console.log('Pixi.js ' + CONST.VERSION + ' - ' + type + ' - http://www.pixijs.com/'); //jshint ignore:line } @@ -166,15 +181,19 @@ * @class * @namespace PIXI */ - AjaxRequest: function () { + AjaxRequest: function () + { var activexmodes = ['Msxml2.XMLHTTP.6.0', 'Msxml2.XMLHTTP.3.0', 'Microsoft.XMLHTTP']; //activeX versions to check for in IE - if (window.ActiveXObject) { //Test for support for ActiveXObject in IE first (as XMLHttpRequest in IE7 is broken) - for (var i=0; i= this.textures.length) { + else if (round >= this.textures.length) + { this.gotoAndStop(this.textures.length - 1); - if (this.onComplete) { + if (this.onComplete) + { this.onComplete(); } } @@ -167,10 +182,12 @@ * @static * @param frames {string[]} the array of frames ids the movieclip will use as its texture frames */ -MovieClip.fromFrames = function (frames) { +MovieClip.fromFrames = function (frames) +{ var textures = []; - for (var i = 0; i < frames.length; ++i) { + for (var i = 0; i < frames.length; ++i) + { textures.push(new core.Texture.fromFrame(frames[i])); } @@ -183,10 +200,12 @@ * @static * @param images {string[]} the array of image urls the movieclip will use as its texture frames */ -MovieClip.fromImages = function (images) { +MovieClip.fromImages = function (images) +{ var textures = []; - for (var i = 0; i < images.length; ++i) { + for (var i = 0; i < images.length; ++i) + { textures.push(new core.Texture.fromImage(images[i])); } diff --git a/src/extras/Rope.js b/src/extras/Rope.js index c157ec4..9c87bc0 100644 --- a/src/extras/Rope.js +++ b/src/extras/Rope.js @@ -9,7 +9,8 @@ * @param {Array} points - An array of {Point}. * */ -function Rope(texture, points) { +function Rope(texture, points) +{ Strip.call(this, texture); this.points = points; @@ -31,10 +32,12 @@ * Refreshes * */ -Rope.prototype.refresh = function () { +Rope.prototype.refresh = function () +{ var points = this.points; - if (points.length < 1) { + if (points.length < 1) + { return; } @@ -59,20 +62,23 @@ var total = points.length, point, index, amount; - for (var i = 1; i < total; i++) { + for (var i = 1; i < total; i++) + { point = points[i]; index = i * 4; // time to do some smart drawing! amount = i / (total-1); - if (i%2) { + if (i%2) + { uvs[index] = amount; uvs[index+1] = 0; uvs[index+2] = amount; uvs[index+3] = 1; } - else { + else + { uvs[index] = amount; uvs[index+1] = 0; @@ -95,10 +101,12 @@ * * @private */ -Rope.prototype.updateTransform = function () { +Rope.prototype.updateTransform = function () +{ var points = this.points; - if (points.length < 1) { + if (points.length < 1) + { return; } @@ -113,14 +121,17 @@ var total = points.length, point, index, ratio, perpLength, num; - for (var i = 0; i < total; i++) { + for (var i = 0; i < total; i++) + { point = points[i]; index = i * 4; - if (i < points.length-1) { + if (i < points.length-1) + { nextPoint = points[i+1]; } - else { + else + { nextPoint = point; } @@ -129,7 +140,8 @@ ratio = (1 - (i / (total-1))) * 10; - if (ratio > 1) { + if (ratio > 1) + { ratio = 1; } @@ -157,7 +169,8 @@ * * @param texture {Texture} the texture that will be used */ -Rope.prototype.setTexture = function (texture) { +Rope.prototype.setTexture = function (texture) +{ // stop current texture this.texture = texture; //this.updateFrame = true; diff --git a/src/extras/Strip.js b/src/extras/Strip.js index c5e378f..57691b5 100644 --- a/src/extras/Strip.js +++ b/src/extras/Strip.js @@ -10,7 +10,8 @@ * @param height {number} the height * */ -function Strip(texture) { +function Strip(texture) +{ core.DisplayObjectContainer.call(this); /** @@ -70,9 +71,11 @@ * * @param renderer {WebGLRenderer} */ -Strip.prototype.renderWebGL = function (renderer) { +Strip.prototype.renderWebGL = function (renderer) +{ // if the sprite is not visible or the alpha is 0 then no need to render this element - if (!this.visible || this.alpha <= 0) { + if (!this.visible || this.alpha <= 0) + { return; } @@ -81,7 +84,8 @@ renderer.spriteBatch.stop(); // init! init! - if (!this._vertexBuffer) { + if (!this._vertexBuffer) + { this._initWebGL(renderer); } @@ -96,7 +100,8 @@ //TODO check culling }; -Strip.prototype._initWebGL = function (renderer) { +Strip.prototype._initWebGL = function (renderer) +{ // build the strip! var gl = renderer.gl; @@ -118,7 +123,8 @@ gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this.indices, gl.STATIC_DRAW); }; -Strip.prototype._renderStrip = function (renderer) { +Strip.prototype._renderStrip = function (renderer) +{ var gl = renderer.gl; var projection = renderer.projection, offset = renderer.offset, @@ -137,7 +143,8 @@ gl.uniform2f(shader.offsetVector, -offset.x, -offset.y); gl.uniform1f(shader.alpha, this.worldAlpha); - if (!this.dirty) { + if (!this.dirty) + { gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexBuffer); gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); @@ -150,10 +157,12 @@ gl.activeTexture(gl.TEXTURE0); // check if a texture is dirty.. - if (this.texture.baseTexture._dirty[gl.id]) { + if (this.texture.baseTexture._dirty[gl.id]) + { renderer.updateTexture(this.texture.baseTexture); } - else { + else + { // bind the current texture gl.bindTexture(gl.TEXTURE_2D, this.texture.baseTexture._glTextures[gl.id]); } @@ -163,7 +172,8 @@ } - else { + else + { this.dirty = false; gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexBuffer); @@ -178,10 +188,12 @@ gl.activeTexture(gl.TEXTURE0); // check if a texture is dirty.. - if (this.texture.baseTexture._dirty[gl.id]) { + if (this.texture.baseTexture._dirty[gl.id]) + { renderer.updateTexture(this.texture.baseTexture); } - else { + else + { gl.bindTexture(gl.TEXTURE_2D, this.texture.baseTexture._glTextures[gl.id]); } @@ -203,27 +215,33 @@ * * @param renderer {CanvasRenderer} */ -Strip.prototype.renderCanvas = function (renderer) { +Strip.prototype.renderCanvas = function (renderer) +{ var context = renderer.context; var transform = this.worldTransform; - if (renderer.roundPixels) { + if (renderer.roundPixels) + { context.setTransform(transform.a, transform.b, transform.c, transform.d, transform.tx | 0, transform.ty | 0); } - else { + else + { context.setTransform(transform.a, transform.b, transform.c, transform.d, transform.tx, transform.ty); } - if (this.drawMode === Strip.DrawModes.TRIANGLE_STRIP) { + if (this.drawMode === Strip.DrawModes.TRIANGLE_STRIP) + { this._renderCanvasTriangleStrip(context); } - else { + else + { this._renderCanvasTriangles(context); } }; -Strip.prototype._renderCanvasTriangleStrip = function (context) { +Strip.prototype._renderCanvasTriangleStrip = function (context) +{ // draw triangles!! var vertices = this.vertices; var uvs = this.uvs; @@ -231,14 +249,16 @@ var length = vertices.length / 2; // this.count++; - for (var i = 0; i < length - 2; i++) { + for (var i = 0; i < length - 2; i++) + { // draw some triangles! var index = i * 2; this._renderCanvasDrawTriangle(context, vertices, uvs, index, (index + 2), (index + 4)); } }; -Strip.prototype._renderCanvasTriangles = function (context) { +Strip.prototype._renderCanvasTriangles = function (context) +{ // draw triangles!! var vertices = this.vertices; var uvs = this.uvs; @@ -247,14 +267,16 @@ var length = indices.length; // this.count++; - for (var i = 0; i < length; i += 3) { + for (var i = 0; i < length; i += 3) + { // draw some triangles! var index0 = indices[i] * 2, index1 = indices[i + 1] * 2, index2 = indices[i + 2] * 2; this._renderCanvasDrawTriangle(context, vertices, uvs, index0, index1, index2); } }; -Strip.prototype._renderCanvasDrawTriangle = function (context, vertices, uvs, index0, index1, index2) { +Strip.prototype._renderCanvasDrawTriangle = function (context, vertices, uvs, index0, index1, index2) +{ var textureSource = this.texture.baseTexture.source; var textureWidth = this.texture.width; var textureHeight = this.texture.height; @@ -265,7 +287,8 @@ var u0 = uvs[index0] * textureWidth, u1 = uvs[index1] * textureWidth, u2 = uvs[index2] * textureWidth; var v0 = uvs[index0 + 1] * textureHeight, v1 = uvs[index1 + 1] * textureHeight, v2 = uvs[index2 + 1] * textureHeight; - if (this.canvasPadding > 0) { + if (this.canvasPadding > 0) + { var paddingX = this.canvasPadding / this.worldTransform.a; var paddingY = this.canvasPadding / this.worldTransform.d; var centerX = (x0 + x1 + x2) / 3; @@ -332,7 +355,8 @@ * @param strip {Strip} The Strip to render * @private */ -Strip.prototype.renderStripFlat = function (strip) { +Strip.prototype.renderStripFlat = function (strip) +{ var context = this.context; var vertices = strip.vertices; @@ -340,7 +364,8 @@ // this.count++; context.beginPath(); - for (var i=1; i < length-2; i++) { + for (var i=1; i < length-2; i++) + { // draw some triangles! var index = i*2; @@ -358,7 +383,8 @@ }; /* -Strip.prototype.setTexture = function (texture) { +Strip.prototype.setTexture = function (texture) +{ //TODO SET THE TEXTURES //TODO VISIBILITY @@ -377,7 +403,8 @@ * @private */ -Strip.prototype.onTextureUpdate = function () { +Strip.prototype.onTextureUpdate = function () +{ this.updateFrame = true; }; @@ -387,7 +414,8 @@ * @param matrix {Matrix} the transformation matrix of the sprite * @return {Rectangle} the framing rectangle */ -Strip.prototype.getBounds = function (matrix) { +Strip.prototype.getBounds = function (matrix) +{ var worldTransform = matrix || this.worldTransform; var a = worldTransform.a; @@ -404,7 +432,8 @@ var minY = Infinity; var vertices = this.vertices; - for (var i = 0, n = vertices.length; i < n; i += 2) { + for (var i = 0, n = vertices.length; i < n; i += 2) + { var rawX = vertices[i], rawY = vertices[i + 1]; var x = (a * rawX) + (c * rawY) + tx; var y = (d * rawY) + (b * rawX) + ty; @@ -416,7 +445,8 @@ maxY = y > maxY ? y : maxY; } - if (minX === -Infinity || maxY === Infinity) { + if (minX === -Infinity || maxY === Infinity) + { return core.math.Rectangle.EMPTY; } diff --git a/src/extras/TilingSprite.js b/src/extras/TilingSprite.js index 3ac22df..31da393 100644 --- a/src/extras/TilingSprite.js +++ b/src/extras/TilingSprite.js @@ -10,7 +10,8 @@ * @param width {number} the width of the tiling sprite * @param height {number} the height of the tiling sprite */ -function TilingSprite(texture, width, height) { +function TilingSprite(texture, width, height) +{ core.Sprite.call( this, texture); /** @@ -86,10 +87,12 @@ * @memberof TilingSprite# */ width: { - get: function () { + get: function () + { return this._width; }, - set: function (value) { + set: function (value) + { this._width = value; } }, @@ -101,20 +104,25 @@ * @memberof TilingSprite# */ height: { - get: function () { + get: function () + { return this._height; }, - set: function (value) { + set: function (value) + { this._height = value; } }, texture: { - get: function () { + get: function () + { return this._texture; }, - set: function (value) { - if (this._texture === value) { + set: function (value) + { + if (this._texture === value) + { return; } @@ -130,51 +138,61 @@ * * @param renderer {WebGLRenderer} */ -TilingSprite.prototype.renderWebGL = function (renderer) { - if (!this.visible || this.alpha <= 0) { +TilingSprite.prototype.renderWebGL = function (renderer) +{ + if (!this.visible || this.alpha <= 0) + { return; } var i, j; - if (this._mask) { + if (this._mask) + { renderer.spriteBatch.stop(); renderer.maskManager.pushMask(this.mask, renderer); renderer.spriteBatch.start(); } - if (this._filters) { + if (this._filters) + { renderer.spriteBatch.flush(); renderer.filterManager.pushFilter(this._filterBlock); } - if (!this.tilingTexture || this.refreshTexture) { + if (!this.tilingTexture || this.refreshTexture) + { this.generateTilingTexture(true); - if (this.tilingTexture && this.tilingTexture.needsUpdate) { + if (this.tilingTexture && this.tilingTexture.needsUpdate) + { //TODO - tweaking renderer.updateTexture(this.tilingTexture.baseTexture); this.tilingTexture.needsUpdate = false; // this.tilingTexture._uvs = null; } } - else { + else + { renderer.spriteBatch.renderTilingSprite(this); } // simple render children! - for (i=0,j=this.children.length; i= 0 && index <= this.children.length) { - if (child.parent) { + if (index >= 0 && index <= this.children.length) + { + if (child.parent) + { child.parent.removeChild(child); } @@ -154,7 +173,8 @@ return child; } - else { + else + { throw new Error(child + 'addChildAt: The index '+ index +' supplied is out of bounds ' + this.children.length); } }; @@ -165,15 +185,18 @@ * @param child {DisplayObject} * @param child2 {DisplayObject} */ -DisplayObjectContainer.prototype.swapChildren = function (child, child2) { - if (child === child2) { +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) { + if (index1 < 0 || index2 < 0) + { throw new Error('swapChildren: Both the supplied DisplayObjects must be a child of the caller.'); } @@ -187,10 +210,12 @@ * @param child {DisplayObject} The DisplayObject instance to identify * @return {Number} The index position of the child display object to identify */ -DisplayObjectContainer.prototype.getChildIndex = function (child) { +DisplayObjectContainer.prototype.getChildIndex = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { throw new Error('The supplied DisplayObject must be a child of the caller'); } @@ -203,8 +228,10 @@ * @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 */ -DisplayObjectContainer.prototype.setChildIndex = function (child, index) { - if (index < 0 || index >= this.children.length) { +DisplayObjectContainer.prototype.setChildIndex = function (child, index) +{ + if (index < 0 || index >= this.children.length) + { throw new Error('The supplied index is out of bounds'); } @@ -220,8 +247,10 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child at the given index, if any. */ -DisplayObjectContainer.prototype.getChildAt = function (index) { - if (index < 0 || index >= this.children.length) { +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'); } @@ -234,10 +263,12 @@ * @param child {DisplayObject} The DisplayObject to remove * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChild = function (child) { +DisplayObjectContainer.prototype.removeChild = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { return; } @@ -250,7 +281,8 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChildAt = function (index) { +DisplayObjectContainer.prototype.removeChildAt = function (index) +{ var child = this.getChildAt(index); child.parent = null; @@ -265,24 +297,29 @@ * @param beginIndex {Number} The beginning position. Default value is 0. * @param endIndex {Number} The ending position. Default value is size of the container. */ -DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) { +DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) +{ var begin = beginIndex || 0; var end = typeof endIndex === 'number' ? endIndex : this.children.length; var range = end - begin; - if (range > 0 && range <= end) { + if (range > 0 && range <= end) + { var removed = this.children.splice(begin, range); - for (var i = 0; i < removed.length; ++i) { + for (var i = 0; i < removed.length; ++i) + { removed[i].parent = null; } return removed; } - else if (range === 0 && this.children.length === 0) { + else if (range === 0 && this.children.length === 0) + { return []; } - else { + else + { throw new RangeError('removeChildren: numeric values are outside the acceptable range.'); } }; @@ -291,7 +328,8 @@ * Generates and updates the cached sprite for this object. * */ -DisplayObjectContainer.prototype.updateCachedSprite = function () { +DisplayObjectContainer.prototype.updateCachedSprite = function () +{ this._generateCachedSprite(); }; @@ -304,7 +342,8 @@ * @param renderer {CanvasRenderer|WebGLRenderer} The renderer used to generate the texture. * @return {Texture} a texture of the graphics object */ -DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) { +DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) +{ var bounds = this.getLocalBounds(); var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0, renderer, scaleMode, resolution); @@ -322,18 +361,22 @@ * * @private */ -DisplayObjectContainer.prototype.updateTransform = function () { - if (!this.visible) { +DisplayObjectContainer.prototype.updateTransform = function () +{ + if (!this.visible) + { return; } this.displayObjectUpdateTransform(); - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { return; } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } }; @@ -346,8 +389,10 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getBounds = function () { - if (this.children.length === 0) { +DisplayObjectContainer.prototype.getBounds = function () +{ + if (this.children.length === 0) + { return math.Rectangle.EMPTY; } @@ -365,10 +410,12 @@ var childVisible = false; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -386,7 +433,8 @@ maxY = maxY > childMaxY ? maxY : childMaxY; } - if (!childVisible) { + if (!childVisible) + { return math.Rectangle.EMPTY; } @@ -407,12 +455,14 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getLocalBounds = function () { +DisplayObjectContainer.prototype.getLocalBounds = function () +{ var matrixCache = this.worldTransform; this.worldTransform = math.Matrix.IDENTITY; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } @@ -428,13 +478,16 @@ * * @param renderer {WebGLRenderer} The renderer */ -DisplayObjectContainer.prototype.renderWebGL = function (renderer) { +DisplayObjectContainer.prototype.renderWebGL = function (renderer) +{ // if the object is not visible or the alpha is 0 then no need to render this element - if (!this.visible || this.alpha <= 0) { + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } @@ -442,14 +495,17 @@ var i, j; // do a quick check to see if this element has a mask or a filter. - if (this._mask || this._filters) { + if (this._mask || this._filters) + { // push filter first as we need to ensure the stencil buffer is correct for any masking - if (this._filters) { + if (this._filters) + { renderer.spriteBatch.flush(); renderer.filterManager.pushFilter(this._filterBlock); } - if (this._mask) { + if (this._mask) + { renderer.spriteBatch.stop(); renderer.maskManager.pushMask(this.mask, renderer); renderer.spriteBatch.start(); @@ -459,36 +515,42 @@ this._renderWebGL(renderer); // now loop through the children and make sure they get rendered - for (i = 0, j = this.children.length; i < j; i++) { + for (i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderWebGL(renderer); } // time to stop the sprite batch as either a mask element or a filter draw will happen next renderer.spriteBatch.stop(); - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(this._mask, renderer); } - if (this._filters) { + if (this._filters) + { renderer.filterManager.popFilter(); } renderer.spriteBatch.start(); } - else { + else + { this._renderWebGL(renderer); // simple render children! - for (i = 0, j = this.children.length; i < j; ++i) { + for (i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderWebGL(renderer); } } }; -DisplayObjectContainer.prototype._renderWebGL = function (renderer) { +DisplayObjectContainer.prototype._renderWebGL = function (renderer) +{ // this is where content itself gets renderd.. @@ -499,25 +561,31 @@ * * @param renderer {CanvasRenderer} The renderer */ -DisplayObjectContainer.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0) { +DisplayObjectContainer.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -528,13 +596,16 @@ * @param renderer {WebGLRenderer|CanvasRenderer} The renderer * @private */ -DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) { +DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) +{ this._cachedSprite.worldAlpha = this.worldAlpha; - if (renderer.gl) { + if (renderer.gl) + { this._cachedSprite.renderWebGL(renderer); } - else { + else + { this._cachedSprite.renderCanvas(renderer); } }; @@ -544,10 +615,12 @@ * * @private */ -DisplayObjectContainer.prototype._generateCachedSprite = function () { +DisplayObjectContainer.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { // TODO - RenderTexture now *requires* a renderer instance, so this is like broken // because `renderer` isn't actually in scope here :P var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0); @@ -555,7 +628,8 @@ this._cachedSprite = new Sprite(renderTexture); this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.texture.resize(bounds.width | 0, bounds.height | 0); } @@ -580,8 +654,10 @@ * * @private */ -DisplayObjectContainer.prototype._destroyCachedSprite = function () { - if (!this._cachedSprite) { +DisplayObjectContainer.prototype._destroyCachedSprite = function () +{ + if (!this._cachedSprite) + { return; } diff --git a/src/core/display/Sprite.js b/src/core/display/Sprite.js index 707da24..5862aef 100644 --- a/src/core/display/Sprite.js +++ b/src/core/display/Sprite.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param texture {Texture} The texture for this sprite */ -function Sprite(texture) { +function Sprite(texture) +{ DisplayObjectContainer.call(this); /** @@ -85,12 +86,14 @@ this.texture = texture || Texture.EMPTY; } -Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) { +Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) +{ DisplayObjectContainer.prototype.destroy.call(this); this.anchor = null; - if (destroyTexture) { + if (destroyTexture) + { this._texture.destroy(destroyBaseTexture); } @@ -111,10 +114,12 @@ * @memberof Sprite# */ width: { - get: function () { + get: function () + { return this.scale.x * this.texture.frame.width; }, - set: function (value) { + set: function (value) + { this.scale.x = value / this.texture.frame.width; this._width = value; } @@ -127,10 +132,12 @@ * @memberof Sprite# */ height: { - get: function () { + get: function () + { return this.scale.y * this.texture.frame.height; }, - set: function (value) { + set: function (value) + { this.scale.y = value / this.texture.frame.height; this._height = value; } @@ -143,23 +150,29 @@ * @memberof Sprite# */ texture: { - get: function () { + get: function () + { return this._texture; }, - set: function (value) { - if (this._texture === value) { + set: function (value) + { + if (this._texture === value) + { return; } this._texture = value; this.cachedTint = 0xFFFFFF; - if (value) { + if (value) + { // wait for the texture to load - if (value.baseTexture.hasLoaded) { + if (value.baseTexture.hasLoaded) + { this._onTextureUpdate(); } - else { + else + { value.once('update', this._onTextureUpdate.bind(this)); } } @@ -172,18 +185,22 @@ * * @private */ -Sprite.prototype._onTextureUpdate = function () { +Sprite.prototype._onTextureUpdate = function () +{ // so if _width is 0 then width was not set.. - if (this._width) { + if (this._width) + { this.scale.x = this._width / this.texture.frame.width; } - if (this._height) { + if (this._height) + { this.scale.y = this._height / this.texture.frame.height; } }; -Sprite.prototype._renderWebGL = function (renderer) { +Sprite.prototype._renderWebGL = function (renderer) +{ // this is where content gets renderd.. // watch this space for a little render state manager.. @@ -197,7 +214,8 @@ * @param matrix {Matrix} the transformation matrix of the sprite * @return {Rectangle} the framing rectangle */ -Sprite.prototype.getBounds = function (matrix) { +Sprite.prototype.getBounds = function (matrix) +{ var width = this.texture.frame.width; var height = this.texture.frame.height; @@ -224,11 +242,13 @@ if(b === 0 && c === 0) { // scale may be negative! - if (a < 0) { + if (a < 0) + { a *= -1; } - if (d < 0) { + if (d < 0) + { d *= -1; } @@ -293,28 +313,34 @@ * * @param renderer {CanvasRenderer} The renderer */ -Sprite.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) { +Sprite.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) + { return; } - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; renderer.context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } // Ignore null sources - if (this.texture.valid) { + if (this.texture.valid) + { var resolution = this.texture.baseTexture.resolution / renderer.resolution; renderer.context.globalAlpha = this.worldAlpha; // If smoothingEnabled is supported and we need to change the smoothing property for this texture - if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) { + if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) + { renderer.scaleMode = this.texture.baseTexture.scaleMode; renderer.context[renderer.smoothProperty] = (renderer.scaleMode === CONST.scaleModes.LINEAR); } @@ -324,7 +350,8 @@ var dy = (this.texture.trim ? this.texture.trim.y : 0) - (this.anchor.y * this.texture.trim.height); // Allow for pixel rounding - if (renderer.roundPixels) { + if (renderer.roundPixels) + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -337,7 +364,8 @@ dx = dx | 0; dy = dy | 0; } - else { + else + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -348,8 +376,10 @@ ); } - if (this.tint !== 0xFFFFFF) { - if (this.cachedTint !== this.tint) { + if (this.tint !== 0xFFFFFF) + { + if (this.cachedTint !== this.tint) + { this.cachedTint = this.tint; // TODO clean up caching - how to clean up the caches? @@ -368,7 +398,8 @@ this.texture.crop.height / resolution ); } - else { + else + { renderer.context.drawImage( this.texture.baseTexture.source, this.texture.crop.x, @@ -383,11 +414,13 @@ } } - for (var i = 0, j = this.children.length; i < j; i++) { + for (var i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -402,10 +435,12 @@ * @param frameId {String} The frame Id of the texture in the cache * @return {Sprite} A new Sprite using a texture from the texture cache matching the frameId */ -Sprite.fromFrame = function (frameId) { +Sprite.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache' + this); } @@ -420,6 +455,7 @@ * @param imageId {String} The image url of the texture * @return {Sprite} A new Sprite using a texture from the texture cache matching the image id */ -Sprite.fromImage = function (imageId, crossorigin, scaleMode) { +Sprite.fromImage = function (imageId, crossorigin, scaleMode) +{ return new Sprite(Texture.fromImage(imageId, crossorigin, scaleMode)); }; diff --git a/src/core/display/SpriteBatch.js b/src/core/display/SpriteBatch.js index 3187777..c196fef 100644 --- a/src/core/display/SpriteBatch.js +++ b/src/core/display/SpriteBatch.js @@ -12,7 +12,8 @@ * ```js * var container = new SpriteBatch(); * - * for(var i = 0; i < 100; ++i) { + * for(var i = 0; i < 100; ++i) + * { * var sprite = new PIXI.Sprite.fromImage("myImage.png"); * container.addChild(sprite); * } @@ -25,7 +26,8 @@ */ //TODO RENAME to PARTICLE CONTAINER? -function SpriteBatch() { +function SpriteBatch() +{ DisplayObjectContainer.call(this); } @@ -38,7 +40,8 @@ * * @private */ -SpriteBatch.prototype.updateTransform = function () { +SpriteBatch.prototype.updateTransform = function () +{ // TODO don't need to! this.displayObjectUpdateTransform(); // PIXI.DisplayObjectContainer.prototype.updateTransform.call( this ); @@ -50,8 +53,10 @@ * @param renderer {WebGLRenderer} The webgl renderer * @private */ -SpriteBatch.prototype.renderWebGL = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderWebGL = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -71,8 +76,10 @@ * @param renderer {CanvasRenderer} The canvas renderer * @private */ -SpriteBatch.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -84,10 +91,12 @@ this.displayObjectUpdateTransform(); - for (var i = 0; i < this.children.length; ++i) { + for (var i = 0; i < this.children.length; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -95,9 +104,11 @@ context.globalAlpha = this.worldAlpha * child.alpha; - if (child.rotation % (Math.PI * 2) === 0) { + if (child.rotation % (Math.PI * 2) === 0) + { // this is the fastest way to optimise! - if rotation is 0 then we can avoid any kind of setTransform call - if (isRotated) { + if (isRotated) + { context.setTransform( transform.a, transform.b, @@ -122,8 +133,10 @@ frame.height * child.scale.y ); } - else { - if (!isRotated) { + else + { + if (!isRotated) + { isRotated = true; } @@ -131,7 +144,8 @@ var childTransform = child.worldTransform; - if (renderer.roundPixels) { + if (renderer.roundPixels) + { context.setTransform( childTransform.a, childTransform.b, @@ -141,7 +155,8 @@ childTransform.ty | 0 ); } - else { + else + { context.setTransform( childTransform.a, childTransform.b, diff --git a/src/core/index.js b/src/core/index.js index 3954b6f..eb4a82b 100644 --- a/src/core/index.js +++ b/src/core/index.js @@ -58,11 +58,13 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRenderer: function (width, height, options, noWebGL) { + autoDetectRenderer: function (width, height, options, noWebGL) + { width = width || 800; height = height || 600; - if (!noWebGL && require('webgl-enabled')()) { + if (!noWebGL && require('webgl-enabled')()) + { return new core.WebGLRenderer(width, height, options); } @@ -87,7 +89,8 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRecommendedRenderer: function (width, height, options) { + autoDetectRecommendedRenderer: function (width, height, options) + { var isAndroid = /Android/i.test(navigator.userAgent); return core.autoDetectRenderer(width, height, options, isAndroid); diff --git a/src/core/math/Matrix.js b/src/core/math/Matrix.js index c2f87e2..2ff4848 100644 --- a/src/core/math/Matrix.js +++ b/src/core/math/Matrix.js @@ -10,7 +10,8 @@ * @class * @namespace PIXI */ -function Matrix() { +function Matrix() +{ /** * @member {number} * @default 1 @@ -63,7 +64,8 @@ * * @param array {number[]} The array that the matrix will be populated from. */ -Matrix.prototype.fromArray = function (array) { +Matrix.prototype.fromArray = function (array) +{ this.a = array[0]; this.b = array[1]; this.c = array[3]; @@ -78,14 +80,17 @@ * @param transpose {boolean} Whether we need to transpose the matrix or not * @return {number[]} the newly created array which contains the matrix */ -Matrix.prototype.toArray = function (transpose) { - if (!this.array) { +Matrix.prototype.toArray = function (transpose) +{ + if (!this.array) + { this.array = new Float32Array(9); } var array = this.array; - if (transpose) { + if (transpose) + { array[0] = this.a; array[1] = this.b; array[2] = 0; @@ -96,7 +101,8 @@ array[7] = this.ty; array[8] = 1; } - else { + else + { array[0] = this.a; array[1] = this.c; array[2] = this.tx; @@ -119,7 +125,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, transformed through this matrix */ -Matrix.prototype.apply = function (pos, newPos) { +Matrix.prototype.apply = function (pos, newPos) +{ newPos = newPos || new Point(); newPos.x = this.a * pos.x + this.c * pos.y + this.tx; @@ -136,7 +143,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, inverse-transformed through this matrix */ -Matrix.prototype.applyInverse = function (pos, newPos) { +Matrix.prototype.applyInverse = function (pos, newPos) +{ newPos = newPos || new Point(); var id = 1 / (this.a * this.d + this.c * -this.b); @@ -154,7 +162,8 @@ * @param {number} y * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.translate = function (x, y) { +Matrix.prototype.translate = function (x, y) +{ this.tx += x; this.ty += y; @@ -168,7 +177,8 @@ * @param {number} y The amount to scale vertically * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.scale = function (x, y) { +Matrix.prototype.scale = function (x, y) +{ this.a *= x; this.d *= y; this.c *= x; @@ -186,7 +196,8 @@ * @param {number} angle - The angle in radians. * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.rotate = function (angle) { +Matrix.prototype.rotate = function (angle) +{ var cos = Math.cos( angle ); var sin = Math.sin( angle ); @@ -210,7 +221,8 @@ * @param {Matrix} matrix * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.append = function (matrix) { +Matrix.prototype.append = function (matrix) +{ var a1 = this.a; var b1 = this.b; var c1 = this.c; @@ -232,7 +244,8 @@ * * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.identity = function () { +Matrix.prototype.identity = function () +{ this.a = 1; this.b = 0; this.c = 0; diff --git a/src/core/math/Point.js b/src/core/math/Point.js index 7565b2d..632f346 100644 --- a/src/core/math/Point.js +++ b/src/core/math/Point.js @@ -7,7 +7,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -function Point(x, y) { +function Point(x, y) +{ /** * @member {number} * @default 0 @@ -29,7 +30,8 @@ * * @return {Point} a copy of the point */ -Point.prototype.clone = function () { +Point.prototype.clone = function () +{ return new Point(this.x, this.y); }; @@ -40,7 +42,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -Point.prototype.set = function (x, y) { +Point.prototype.set = function (x, y) +{ this.x = x || 0; this.y = y || ( (y !== 0) ? this.x : 0 ) ; }; diff --git a/src/core/math/shapes/Circle.js b/src/core/math/shapes/Circle.js index 69cfdc9..4d76efc 100644 --- a/src/core/math/shapes/Circle.js +++ b/src/core/math/shapes/Circle.js @@ -10,7 +10,8 @@ * @param y {number} The Y coordinate of the center of this circle * @param radius {number} The radius of the circle */ -function Circle(x, y, radius) { +function Circle(x, y, radius) +{ /** * @member {number} * @default 0 @@ -46,7 +47,8 @@ * @method clone * @return {Circle} a copy of the Circle */ -Circle.prototype.clone = function () { +Circle.prototype.clone = function () +{ return new Circle(this.x, this.y, this.radius); }; @@ -58,8 +60,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Circle */ -Circle.prototype.contains = function (x, y) { - if (this.radius <= 0) { +Circle.prototype.contains = function (x, y) +{ + if (this.radius <= 0) + { return false; } @@ -79,6 +83,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Circle.prototype.getBounds = function () { +Circle.prototype.getBounds = function () +{ return new Rectangle(this.x - this.radius, this.y - this.radius, this.radius * 2, this.radius * 2); }; diff --git a/src/core/math/shapes/Ellipse.js b/src/core/math/shapes/Ellipse.js index 4f2d066..fefd01a 100644 --- a/src/core/math/shapes/Ellipse.js +++ b/src/core/math/shapes/Ellipse.js @@ -11,7 +11,8 @@ * @param width {number} The half width of this ellipse * @param height {number} The half height of this ellipse */ -function Ellipse(x, y, width, height) { +function Ellipse(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -53,7 +54,8 @@ * @method clone * @return {Ellipse} a copy of the ellipse */ -Ellipse.prototype.clone = function () { +Ellipse.prototype.clone = function () +{ return new Ellipse(this.x, this.y, this.width, this.height); }; @@ -65,8 +67,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coords are within this ellipse */ -Ellipse.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Ellipse.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } @@ -86,6 +90,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Ellipse.prototype.getBounds = function () { +Ellipse.prototype.getBounds = function () +{ return new Rectangle(this.x - this.width, this.y - this.height, this.width, this.height); }; diff --git a/src/core/math/shapes/Polygon.js b/src/core/math/shapes/Polygon.js index ae89148..fea6d37 100644 --- a/src/core/math/shapes/Polygon.js +++ b/src/core/math/shapes/Polygon.js @@ -10,16 +10,20 @@ * arguments passed can be flat x,y values e.g. `new Polygon(x,y, x,y, x,y, ...)` where `x` and `y` are * Numbers. */ -function Polygon(points) { +function Polygon(points) +{ //if points isn't an array, use arguments as the array - if (!(points instanceof Array)) { + if (!(points instanceof Array)) + { points = Array.prototype.slice.call(arguments); } //if this is a flat array of numbers, convert it to points - if (points[0] instanceof Point) { + if (points[0] instanceof Point) + { var p = []; - for (var i = 0, il = points.length; i < il; i++) { + for (var i = 0, il = points.length; i < il; i++) + { p.push(points[i].x, points[i].y); } @@ -51,7 +55,8 @@ * * @return {Polygon} a copy of the polygon */ -Polygon.prototype.clone = function () { +Polygon.prototype.clone = function () +{ return new Polygon(this.points.slice()); }; @@ -62,19 +67,22 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this polygon */ -Polygon.prototype.contains = function (x, y) { +Polygon.prototype.contains = function (x, y) +{ var inside = false; // use some raycasting to test hits // https://github.com/substack/point-in-polygon/blob/master/index.js var length = this.points.length / 2; - for (var i = 0, j = length - 1; i < length; j = i++) { + for (var i = 0, j = length - 1; i < length; j = i++) + { var xi = this.points[i * 2], yi = this.points[i * 2 + 1], xj = this.points[j * 2], yj = this.points[j * 2 + 1], intersect = ((yi > y) !== (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi); - if (intersect) { + if (intersect) + { inside = !inside; } } diff --git a/src/core/math/shapes/Rectangle.js b/src/core/math/shapes/Rectangle.js index 16ac62a..4008b68 100644 --- a/src/core/math/shapes/Rectangle.js +++ b/src/core/math/shapes/Rectangle.js @@ -10,7 +10,8 @@ * @param width {number} The overall width of this rectangle * @param height {number} The overall height of this rectangle */ -function Rectangle(x, y, width, height) { +function Rectangle(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -60,7 +61,8 @@ * * @return {Rectangle} a copy of the rectangle */ -Rectangle.prototype.clone = function () { +Rectangle.prototype.clone = function () +{ return new Rectangle(this.x, this.y, this.width, this.height); }; @@ -71,13 +73,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rectangle */ -Rectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Rectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/math/shapes/RoundedRectangle.js b/src/core/math/shapes/RoundedRectangle.js index 27d286e..7bf6411 100644 --- a/src/core/math/shapes/RoundedRectangle.js +++ b/src/core/math/shapes/RoundedRectangle.js @@ -11,7 +11,8 @@ * @param height {number} The overall height of this rounded rectangle * @param radius {number} Controls the radius of the rounded corners */ -function RoundedRectangle(x, y, width, height, radius) { +function RoundedRectangle(x, y, width, height, radius) +{ /** * @member {number} * @default 0 @@ -58,7 +59,8 @@ * * @return {RoundedRectangle} a copy of the rounded rectangle */ -RoundedRectangle.prototype.clone = function () { +RoundedRectangle.prototype.clone = function () +{ return new RoundedRectangle(this.x, this.y, this.width, this.height, this.radius); }; @@ -69,13 +71,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rounded Rectangle */ -RoundedRectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +RoundedRectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/primitives/Graphics.js b/src/core/primitives/Graphics.js index 261c534..e902d2a 100644 --- a/src/core/primitives/Graphics.js +++ b/src/core/primitives/Graphics.js @@ -16,7 +16,8 @@ * @extends DisplayObjectContainer * @namespace PIXI */ -function Graphics() { +function Graphics() +{ DisplayObjectContainer.call(this); this.renderable = true; @@ -154,16 +155,20 @@ * @private */ cacheAsBitmap: { - get: function () { + get: function () + { return this._cacheAsBitmap; }, - set: function (value) { + set: function (value) + { this._cacheAsBitmap = value; - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._generateCachedSprite(); } - else { + else + { this.destroyCachedSprite(); this.dirty = true; } @@ -176,7 +181,8 @@ * * @return {Graphics} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ var clone = new Graphics(); clone.renderable = this.renderable; @@ -192,7 +198,8 @@ clone.cachedSpriteDirty = this.cachedSpriteDirty; // copy graphics data - for (var i = 0; i < this.graphicsData.length; ++i) { + for (var i = 0; i < this.graphicsData.length; ++i) + { clone.graphicsData.push(this.graphicsData.clone()); } @@ -211,17 +218,21 @@ * @param alpha {number} alpha of the line to draw, will update the objects stored style * @return {Graphics} */ -Graphics.prototype.lineStyle = function (lineWidth, color, alpha) { +Graphics.prototype.lineStyle = function (lineWidth, color, alpha) +{ this.lineWidth = lineWidth || 0; this.lineColor = color || 0; this.lineAlpha = (arguments.length < 3) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length) + { // halfway through a line? start a new one! this.drawShape( new math.Polygon( this.currentPath.shape.points.slice(-2) )); } - else { + else + { // otherwise its empty so lets just set the line properties this.currentPath.lineWidth = this.lineWidth; this.currentPath.lineColor = this.lineColor; @@ -239,7 +250,8 @@ * @param y {number} the Y coordinate to move to * @return {Graphics} */ -Graphics.prototype.moveTo = function (x, y) { +Graphics.prototype.moveTo = function (x, y) +{ this.drawShape(new math.Polygon([x,y])); return this; @@ -253,7 +265,8 @@ * @param y {number} the Y coordinate to draw to * @return {Graphics} */ -Graphics.prototype.lineTo = function (x, y) { +Graphics.prototype.lineTo = function (x, y) +{ this.currentPath.shape.points.push(x, y); this.dirty = true; @@ -270,13 +283,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -285,7 +302,8 @@ n = 20, points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { this.moveTo(0, 0); } @@ -293,7 +311,8 @@ var fromY = points[points.length-1]; var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; xa = fromX + ( (cpX - fromX) * j ); @@ -319,13 +338,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -342,7 +365,8 @@ var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; dt = (1 - j); @@ -373,13 +397,17 @@ * @param radius {number} The radius of the arc * @return {Graphics} */ -Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points.push(x1, y1); } } - else { + else + { this.moveTo(x1, y1); } @@ -392,12 +420,15 @@ b2 = x2 - x1, mm = Math.abs(a1 * b2 - b1 * a2); - if (mm < 1.0e-8 || radius === 0) { - if (points[points.length-2] !== x1 || points[points.length-1] !== y1) { + if (mm < 1.0e-8 || radius === 0) + { + if (points[points.length-2] !== x1 || points[points.length-1] !== y1) + { points.push(x1, y1); } } - else { + else + { var dd = a1 * a1 + b1 * b1, cc = a2 * a2 + b2 * b2, tt = a1 * a2 + b1 * b2, @@ -433,42 +464,51 @@ * @param anticlockwise {boolean} Optional. Specifies whether the drawing should be counterclockwise or clockwise. False is default, and indicates clockwise, while true indicates counter-clockwise. * @return {Graphics} */ -Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) { +Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) +{ var startX = cx + Math.cos(startAngle) * radius; var startY = cy + Math.sin(startAngle) * radius; var points; // TODO - This if-else makes no sense. It uses currentPath in the else where it doesn't exist... - if (this.currentPath) { + if (this.currentPath) + { points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { points.push(startX, startY); } - else if (points[points.length-2] !== startX || points[points.length-1] !== startY) { + else if (points[points.length-2] !== startX || points[points.length-1] !== startY) + { points.push(startX, startY); } } - else { + else + { this.moveTo(startX, startY); points = this.currentPath.shape.points; } - if (startAngle === endAngle) { + if (startAngle === endAngle) + { return this; } - if (!anticlockwise && endAngle <= startAngle) { + if (!anticlockwise && endAngle <= startAngle) + { endAngle += Math.PI * 2; } - else if (anticlockwise && startAngle <= endAngle) { + else if (anticlockwise && startAngle <= endAngle) + { startAngle += Math.PI * 2; } var sweep = anticlockwise ? (startAngle - endAngle) *-1 : (endAngle - startAngle); var segs = (Math.abs(sweep)/ (Math.PI * 2)) * 40; - if (sweep === 0) { + if (sweep === 0) + { return this; } @@ -482,7 +522,8 @@ var remainder = ( segMinus % 1 ) / segMinus; - for (var i = 0; i <= segMinus; ++i) { + for (var i = 0; i <= segMinus; ++i) + { var real = i + remainder * i; var angle = ((theta) + startAngle + (theta2 * real)); @@ -506,13 +547,16 @@ * @param alpha {number} the alpha of the fill * @return {Graphics} */ -Graphics.prototype.beginFill = function (color, alpha) { +Graphics.prototype.beginFill = function (color, alpha) +{ this.filling = true; this.fillColor = color || 0; this.fillAlpha = (alpha === undefined) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length <= 2) + { this.currentPath.fill = this.filling; this.currentPath.fillColor = this.fillColor; this.currentPath.fillAlpha = this.fillAlpha; @@ -526,7 +570,8 @@ * * @return {Graphics} */ -Graphics.prototype.endFill = function () { +Graphics.prototype.endFill = function () +{ this.filling = false; this.fillColor = null; this.fillAlpha = 1; @@ -542,7 +587,8 @@ * @param height {number} The height of the rectangle * @return {Graphics} */ -Graphics.prototype.drawRect = function ( x, y, width, height ) { +Graphics.prototype.drawRect = function ( x, y, width, height ) +{ this.drawShape(new math.Rectangle(x,y, width, height)); return this; @@ -556,7 +602,8 @@ * @param height {number} The height of the rectangle * @param radius {number} Radius of the rectangle corners */ -Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) { +Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) +{ this.drawShape(new math.RoundedRectangle(x, y, width, height, radius)); return this; @@ -570,7 +617,8 @@ * @param radius {number} The radius of the circle * @return {Graphics} */ -Graphics.prototype.drawCircle = function (x, y, radius) { +Graphics.prototype.drawCircle = function (x, y, radius) +{ this.drawShape(new math.Circle(x,y, radius)); return this; @@ -585,7 +633,8 @@ * @param height {number} The half height of the ellipse * @return {Graphics} */ -Graphics.prototype.drawEllipse = function (x, y, width, height) { +Graphics.prototype.drawEllipse = function (x, y, width, height) +{ this.drawShape(new math.Ellipse(x, y, width, height)); return this; @@ -597,8 +646,10 @@ * @param path {Array} The path data used to construct the polygon. * @return {Graphics} */ -Graphics.prototype.drawPolygon = function (path) { - if (!(path instanceof Array)) { +Graphics.prototype.drawPolygon = function (path) +{ + if (!(path instanceof Array)) + { path = Array.prototype.slice.call(arguments); } @@ -612,7 +663,8 @@ * * @return {Graphics} */ -Graphics.prototype.clear = function () { +Graphics.prototype.clear = function () +{ this.lineWidth = 0; this.filling = false; @@ -631,7 +683,8 @@ * @param scaleMode {number} Should be one of the scaleMode consts * @return {Texture} a texture of the graphics object */ -Graphics.prototype.generateTexture = function (resolution, scaleMode) { +Graphics.prototype.generateTexture = function (resolution, scaleMode) +{ resolution = resolution || 1; var bounds = this.getBounds(); @@ -655,17 +708,21 @@ * * @param renderer {WebGLRenderer} */ -Graphics.prototype._renderWebGL = function (renderer) { +Graphics.prototype._renderWebGL = function (renderer) +{ // if the sprite is not visible or the alpha is 0 then no need to render this element - if (this.isMask === true) { + if (this.isMask === true) + { return; } // this code may still be needed so leaving for now.. - // + // /* - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture on the gpu too! @@ -681,17 +738,24 @@ return; } - */ - - // check if the webgl graphic needs to be updated - if (this.glDirty) { - this.dirty = true; - this.glDirty = false; - } + else */ - renderer.setObjectRendererer(renderer.graphicsRenderer); - renderer.graphicsRenderer.render(this); + renderer.spriteBatch.stop(); + renderer.blendModeManager.setBlendMode(this.blendMode); + // check blend mode + renderer.blendModeManager.setBlendMode( this.blendMode ); + + // check if the webgl graphic needs to be updated + if (this.glDirty) + { + this.dirty = true; + this.glDirty = false; + } + + WebGLGraphics.renderGraphics(this, renderer); + + renderer.spriteBatch.start(); }; /** @@ -700,14 +764,18 @@ * @param renderer {CanvasRenderer} * @private */ -Graphics.prototype.renderCanvas = function (renderer) { +Graphics.prototype.renderCanvas = function (renderer) +{ // 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.isMask === true) { + if (!this.visible || this.alpha <= 0 || this.isMask === true) + { return; } - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture @@ -723,16 +791,19 @@ return; } - else { + else + { var context = renderer.context; var transform = this.worldTransform; - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } @@ -748,11 +819,13 @@ CanvasGraphics.renderGraphics(this, context); - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } } @@ -763,13 +836,16 @@ * * @return {Rectangle} the rectangular bounding area */ -Graphics.prototype.getBounds = function (matrix) { +Graphics.prototype.getBounds = function (matrix) +{ // return an empty object if the item is a mask! - if (this.isMask) { + if (this.isMask) + { return math.Rectangle.EMPTY; } - if (this.dirty) { + if (this.dirty) + { this.updateLocalBounds(); this.glDirty = true; @@ -841,23 +917,27 @@ * Update the bounds of the object * */ -Graphics.prototype.updateLocalBounds = function () { +Graphics.prototype.updateLocalBounds = function () +{ var minX = Infinity; var maxX = -Infinity; var minY = Infinity; var maxY = -Infinity; - if (this.graphicsData.length) { + if (this.graphicsData.length) + { var shape, points, x, y, w, h; - for (var i = 0; i < this.graphicsData.length; i++) { + for (var i = 0; i < this.graphicsData.length; i++) + { var data = this.graphicsData[i]; var type = data.type; var lineWidth = data.lineWidth; shape = data.shape; - if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) { + if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) + { x = shape.x - lineWidth/2; y = shape.y - lineWidth/2; w = shape.width + lineWidth; @@ -869,7 +949,8 @@ minY = y < minY ? y : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.CIRC) { + else if (type === CONST.SHAPES.CIRC) + { x = shape.x; y = shape.y; w = shape.radius + lineWidth/2; @@ -881,7 +962,8 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.ELIP) { + else if (type === CONST.SHAPES.ELIP) + { x = shape.x; y = shape.y; w = shape.width + lineWidth/2; @@ -893,11 +975,13 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else { + else + { // POLY points = shape.points; - for (var j = 0; j < points.length; j += 2) { + for (var j = 0; j < points.length; j += 2) + { x = points[j]; y = points[j+1]; @@ -910,7 +994,8 @@ } } } - else { + else + { minX = 0; maxX = 0; minY = 0; @@ -931,10 +1016,12 @@ * * @private */ -Graphics.prototype._generateCachedSprite = function () { +Graphics.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { var canvasBuffer = new CanvasBuffer(bounds.width, bounds.height); var texture = Texture.fromCanvas(canvasBuffer.canvas); @@ -943,7 +1030,8 @@ this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.buffer.resize(bounds.width, bounds.height); } @@ -968,7 +1056,8 @@ * * @private */ -Graphics.prototype.updateCachedSpriteTexture = function () { +Graphics.prototype.updateCachedSpriteTexture = function () +{ var cachedSprite = this._cachedSprite; var texture = cachedSprite.texture; var canvas = cachedSprite.buffer.canvas; @@ -989,7 +1078,8 @@ * Destroys a previous cached sprite. * */ -Graphics.prototype.destroyCachedSprite = function () { +Graphics.prototype.destroyCachedSprite = function () +{ this._cachedSprite.texture.destroy(true); // let the gc collect the unused sprite @@ -1003,10 +1093,13 @@ * @param {Circle|Rectangle|Ellipse|Line|Polygon} shape The Shape object to draw. * @return {GraphicsData} The generated GraphicsData object. */ -Graphics.prototype.drawShape = function (shape) { - if (this.currentPath) { +Graphics.prototype.drawShape = function (shape) +{ + if (this.currentPath) + { // check current path! - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath.shape.points.length <= 2) + { this.graphicsData.pop(); } } @@ -1017,7 +1110,8 @@ this.graphicsData.push(data); - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { data.shape.closed = this.filling; this.currentPath = data; } diff --git a/src/core/primitives/GraphicsData.js b/src/core/primitives/GraphicsData.js index 99decbe..788f6f2 100644 --- a/src/core/primitives/GraphicsData.js +++ b/src/core/primitives/GraphicsData.js @@ -4,7 +4,8 @@ * @class * @namespace PIXI */ -function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) { +function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) +{ this.lineWidth = lineWidth; this.lineColor = lineColor; this.lineAlpha = lineAlpha; @@ -27,7 +28,8 @@ * * @return {GraphicsData} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ return new GraphicsData( this.lineWidth, this.lineColor, diff --git a/src/core/renderers/canvas/CanvasRenderer.js b/src/core/renderers/canvas/CanvasRenderer.js index 15a0978..7aebd44 100644 --- a/src/core/renderers/canvas/CanvasRenderer.js +++ b/src/core/renderers/canvas/CanvasRenderer.js @@ -17,17 +17,22 @@ * @param [options.resolution=1] {number} the resolution of the renderer retina would be 2 * @param [options.clearBeforeRender=true] {boolean} This sets if the CanvasRenderer will clear the canvas or not before the new render pass. */ -function CanvasRenderer(width, height, options) { +function CanvasRenderer(width, height, options) +{ utils.sayHello('Canvas'); - if (options) { - for (var i in CONST.defaultRenderOptions) { - if (typeof options[i] === 'undefined') { + if (options) + { + for (var i in CONST.defaultRenderOptions) + { + if (typeof options[i] === 'undefined') + { options[i] = CONST.defaultRenderOptions[i]; } } } - else { + else + { options = CONST.defaultRenderOptions; } @@ -156,19 +161,24 @@ this.smoothProperty = null; - if (this.context.imageSmoothingEnabled) { + if (this.context.imageSmoothingEnabled) + { this.smoothProperty = 'imageSmoothingEnabled'; } - else if (this.context.webkitImageSmoothingEnabled) { + else if (this.context.webkitImageSmoothingEnabled) + { this.smoothProperty = 'webkitImageSmoothingEnabled'; } - else if (this.context.mozImageSmoothingEnabled) { + else if (this.context.mozImageSmoothingEnabled) + { this.smoothProperty = 'mozImageSmoothingEnabled'; } - else if (this.context.oImageSmoothingEnabled) { + else if (this.context.oImageSmoothingEnabled) + { this.smoothProperty = 'oImageSmoothingEnabled'; } - else if (this.context.msImageSmoothingEnabled) { + else if (this.context.msImageSmoothingEnabled) + { this.smoothProperty = 'msImageSmoothingEnabled'; } @@ -193,10 +203,12 @@ * @memberof CanvasRenderer# */ backgroundColor: { - get: function () { + get: function () + { return this._backgroundColor; }, - set: function (val) { + set: function (val) + { this._backgroundColor = val; this._backgroundColorString = utils.hex2string(val); } @@ -208,7 +220,8 @@ * * @param object {DisplayObject} the object to be rendered */ -CanvasRenderer.prototype.render = function (object) { +CanvasRenderer.prototype.render = function (object) +{ object.updateTransform(); this.context.setTransform(1,0,0,1,0,0); @@ -218,16 +231,20 @@ this.currentBlendMode = CONST.blendModes.NORMAL; this.context.globalCompositeOperation = this.blendModes[CONST.blendModes.NORMAL]; - if (navigator.isCocoonJS && this.view.screencanvas) { + if (navigator.isCocoonJS && this.view.screencanvas) + { this.context.fillStyle = 'black'; this.context.clear(); } - if (this.clearBeforeRender) { - if (this.transparent) { + if (this.clearBeforeRender) + { + if (this.transparent) + { this.context.clearRect(0, 0, this.width, this.height); } - else { + else + { this.context.fillStyle = this._backgroundColorString; this.context.fillRect(0, 0, this.width , this.height); } @@ -241,8 +258,10 @@ * * @param [removeView=false] {boolean} Removes the Canvas element from the DOM. */ -CanvasRenderer.prototype.destroy = function (removeView) { - if (removeView && this.view.parent) { +CanvasRenderer.prototype.destroy = function (removeView) +{ + if (removeView && this.view.parent) + { this.view.parent.removeChild(this.view); } @@ -257,14 +276,16 @@ * @param width {number} the new width of the canvas view * @param height {number} the new height of the canvas view */ -CanvasRenderer.prototype.resize = function (width, height) { +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) { + if (this.autoResize) + { this.view.style.width = this.width / this.resolution + 'px'; this.view.style.height = this.height / this.resolution + 'px'; } @@ -276,7 +297,8 @@ * @param displayObject {DisplayObject} The displayObject to render * @private */ -CanvasRenderer.prototype.renderDisplayObject = function (displayObject) { +CanvasRenderer.prototype.renderDisplayObject = function (displayObject) +{ displayObject.renderCanvas(this); }; @@ -285,11 +307,14 @@ * * @private */ -CanvasRenderer.prototype._mapBlendModes = function () { - if (!this.blendModes) { +CanvasRenderer.prototype._mapBlendModes = function () +{ + if (!this.blendModes) + { this.blendModes = {}; - if (utils.canUseNewCanvasBlendModes()) { + if (utils.canUseNewCanvasBlendModes()) + { this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? this.blendModes[CONST.blendModes.MULTIPLY] = 'multiply'; @@ -308,7 +333,8 @@ this.blendModes[CONST.blendModes.COLOR] = 'color'; this.blendModes[CONST.blendModes.LUMINOSITY] = 'luminosity'; } - else { + else + { // this means that the browser does not support the cool new blend modes in canvas 'cough' ie 'cough' this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? diff --git a/src/core/renderers/canvas/utils/CanvasBuffer.js b/src/core/renderers/canvas/utils/CanvasBuffer.js index ebe5d47..b183a66 100644 --- a/src/core/renderers/canvas/utils/CanvasBuffer.js +++ b/src/core/renderers/canvas/utils/CanvasBuffer.js @@ -6,7 +6,8 @@ * @param width {number} the width for the newly created canvas * @param height {number} the height for the newly created canvas */ -function CanvasBuffer(width, height) { +function CanvasBuffer(width, height) +{ /** * The Canvas object that belongs to this CanvasBuffer. * @@ -36,10 +37,12 @@ * @memberof CanvasBuffer# */ width: { - get: function () { + get: function () + { return this.canvas.width; }, - set: function (val) { + set: function (val) + { this.canvas.width = val; } }, @@ -50,10 +53,12 @@ * @memberof CanvasBuffer# */ height: { - get: function () { + get: function () + { return this.canvas.height; }, - set: function (val) { + set: function (val) + { this.canvas.height = val; } } @@ -64,7 +69,8 @@ * * @private */ -CanvasBuffer.prototype.clear = function () { +CanvasBuffer.prototype.clear = function () +{ this.context.setTransform(1, 0, 0, 1, 0, 0); this.context.clearRect(0,0, this.canvas.width, this.canvas.height); }; @@ -75,7 +81,8 @@ * @param width {number} the new width of the canvas * @param height {number} the new height of the canvas */ -CanvasBuffer.prototype.resize = function (width, height) { +CanvasBuffer.prototype.resize = function (width, height) +{ this.canvas.width = width; this.canvas.height = height; }; diff --git a/src/core/renderers/canvas/utils/CanvasGraphics.js b/src/core/renderers/canvas/utils/CanvasGraphics.js index c7eaa2a..3f2a91f 100644 --- a/src/core/renderers/canvas/utils/CanvasGraphics.js +++ b/src/core/renderers/canvas/utils/CanvasGraphics.js @@ -13,15 +13,18 @@ * @param graphics {Graphics} the actual graphics object to render * @param context {CanvasRenderingContext2D} the 2d drawing method of the canvas */ -CanvasGraphics.renderGraphics = function (graphics, context) { +CanvasGraphics.renderGraphics = function (graphics, context) +{ var worldAlpha = graphics.worldAlpha; - if (graphics.dirty) { + if (graphics.dirty) + { this.updateGraphicsTint(graphics); graphics.dirty = false; } - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; @@ -30,69 +33,82 @@ context.lineWidth = data.lineWidth; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { context.beginPath(); var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } - if (shape.closed) { + if (shape.closed) + { context.lineTo(points[0], points[1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fillRect(shape.x, shape.y, shape.width, shape.height); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.strokeRect(shape.x, shape.y, shape.width, shape.height); } } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.beginPath(); context.arc(shape.x, shape.y, shape.radius,0,2*Math.PI); context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas var w = shape.width * 2; @@ -119,18 +135,21 @@ context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; var width = shape.width; @@ -152,13 +171,15 @@ context.quadraticCurveTo(rx, ry, rx, ry + radius); context.closePath(); - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); @@ -174,45 +195,54 @@ * @param graphics {Graphics} the graphics which will be used as a mask * @param context {CanvasRenderingContext2D} the context 2d method of the canvas */ -CanvasGraphics.renderGraphicsMask = function (graphics, context) { +CanvasGraphics.renderGraphicsMask = function (graphics, context) +{ var len = graphics.graphicsData.length; - if (len === 0) { + if (len === 0) + { return; } context.beginPath(); - for (var i = 0; i < len; i++) { + for (var i = 0; i < len; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { context.rect(shape.x, shape.y, shape.width, shape.height); context.closePath(); } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.arc(shape.x, shape.y, shape.radius, 0, 2 * Math.PI); context.closePath(); } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas @@ -237,7 +267,8 @@ context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); context.closePath(); } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; @@ -262,8 +293,10 @@ } }; -CanvasGraphics.updateGraphicsTint = function (graphics) { - if (graphics.tint === 0xFFFFFF) { +CanvasGraphics.updateGraphicsTint = function (graphics) +{ + if (graphics.tint === 0xFFFFFF) + { return; } @@ -271,7 +304,8 @@ var tintG = (graphics.tint >> 8 & 0xFF) / 255; var tintB = (graphics.tint & 0xFF)/ 255; - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var fillColor = data.fillColor | 0; diff --git a/src/core/renderers/canvas/utils/CanvasMaskManager.js b/src/core/renderers/canvas/utils/CanvasMaskManager.js index e04a733..9827d36 100644 --- a/src/core/renderers/canvas/utils/CanvasMaskManager.js +++ b/src/core/renderers/canvas/utils/CanvasMaskManager.js @@ -6,7 +6,8 @@ * @class * @namespace PIXI */ -function CanvasMaskManager() {} +function CanvasMaskManager() +{} CanvasMaskManager.prototype.constructor = CanvasMaskManager; module.exports = CanvasMaskManager; @@ -17,7 +18,8 @@ * @param maskData {object} the maskData that will be pushed * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.pushMask = function (maskData, renderer) { +CanvasMaskManager.prototype.pushMask = function (maskData, renderer) +{ renderer.context.save(); var cacheAlpha = maskData.alpha; @@ -45,6 +47,7 @@ * * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.popMask = function (renderer) { +CanvasMaskManager.prototype.popMask = function (renderer) +{ renderer.context.restore(); }; diff --git a/src/core/renderers/canvas/utils/CanvasTinter.js b/src/core/renderers/canvas/utils/CanvasTinter.js index 17e0529..d2fb1bc 100644 --- a/src/core/renderers/canvas/utils/CanvasTinter.js +++ b/src/core/renderers/canvas/utils/CanvasTinter.js @@ -14,7 +14,8 @@ * @param color {number} the color to use to tint the sprite with * @return {HTMLCanvasElement} The tinted canvas */ -CanvasTinter.getTintedTexture = function (sprite, color) { +CanvasTinter.getTintedTexture = function (sprite, color) +{ var texture = sprite.texture; color = CanvasTinter.roundColor(color); @@ -23,7 +24,8 @@ texture.tintCache = texture.tintCache || {}; - if (texture.tintCache[stringColor]) { + if (texture.tintCache[stringColor]) + { return texture.tintCache[stringColor]; } @@ -33,14 +35,16 @@ //CanvasTinter.tintWithPerPixel(texture, stringColor, canvas); CanvasTinter.tintMethod(texture, color, canvas); - if (CanvasTinter.convertTintToImage) { + if (CanvasTinter.convertTintToImage) + { // is this better? var tintImage = new Image(); tintImage.src = canvas.toDataURL(); texture.tintCache[stringColor] = tintImage; } - else { + else + { texture.tintCache[stringColor] = canvas; // if we are not converting the texture to an image then we need to lose the reference to the canvas CanvasTinter.canvas = null; @@ -56,7 +60,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithMultiply = function (texture, color, canvas) { +CanvasTinter.tintWithMultiply = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -104,7 +109,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithOverlay = function (texture, color, canvas) { +CanvasTinter.tintWithOverlay = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -139,7 +145,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithPerPixel = function (texture, color, canvas) { +CanvasTinter.tintWithPerPixel = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -167,7 +174,8 @@ var pixels = pixelData.data; - for (var i = 0; i < pixels.length; i += 4) { + for (var i = 0; i < pixels.length; i += 4) + { pixels[i+0] *= r; pixels[i+1] *= g; pixels[i+2] *= b; @@ -181,7 +189,8 @@ * * @param color {number} the color to round, should be a hex color */ -CanvasTinter.roundColor = function (color) { +CanvasTinter.roundColor = function (color) +{ var step = CanvasTinter.cacheStepsPerColorChannel; var rgbValues = utils.hex2rgb(color); diff --git a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js index 9f2f89a..35edbaf 100644 --- a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js +++ b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLBlendModeManager(renderer) { +function WebGLBlendModeManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -23,8 +24,10 @@ * * @param blendMode {number} the blendMode, should be a Pixi const, such as BlendModes.ADD */ -WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) { - if (this.currentBlendMode === blendMode) { +WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) +{ + if (this.currentBlendMode === blendMode) + { return false; } diff --git a/src/core/renderers/webgl/managers/WebGLFilterManager.js b/src/core/renderers/webgl/managers/WebGLFilterManager.js index 1179258..2dac048 100644 --- a/src/core/renderers/webgl/managers/WebGLFilterManager.js +++ b/src/core/renderers/webgl/managers/WebGLFilterManager.js @@ -7,7 +7,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLFilterManager(renderer) { +function WebGLFilterManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -32,7 +33,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.texturePool.length = 0; self.initShaderBuffers(); }); @@ -46,7 +48,8 @@ * @param renderer {WebGLRenderer} * @param buffer {ArrayBuffer} */ -WebGLFilterManager.prototype.begin = function (buffer) { +WebGLFilterManager.prototype.begin = function (buffer) +{ this.defaultShader = this.renderer.shaderManager.defaultShader; this.width = this.renderer.projection.x * 2; @@ -60,7 +63,8 @@ * * @param filterBlock {object} the filter that will be pushed to the current filter stack */ -WebGLFilterManager.prototype.pushFilter = function (filterBlock) { +WebGLFilterManager.prototype.pushFilter = function (filterBlock) +{ var gl = this.renderer.gl; var projection = this.renderer.projection; @@ -78,10 +82,12 @@ this.offsetY += filterBlock._filterArea.y; var texture = this.texturePool.pop(); - if (!texture) { + if (!texture) + { texture = new FilterTexture(this.renderer.gl, this.width, this.height); } - else { + else + { texture.resize(this.width, this.height); } @@ -98,29 +104,35 @@ var localX = filterArea.x, localY = filterArea.y; - if (filterArea.x < 0) { + if (filterArea.x < 0) + { filterArea.width += filterArea.x; filterArea.x = 0; } - if (filterArea.y < 0) { + if (filterArea.y < 0) + { filterArea.height += filterArea.y; filterArea.y = 0; } - if (localX + filterArea.width > this.width) { + if (localX + filterArea.width > this.width) + { filterArea.width = this.width - localX; } - if (localY + filterArea.height > this.height) { + if (localY + filterArea.height > this.height) + { filterArea.height = this.height - localY; } - if (filterArea.width < 0) { + if (filterArea.width < 0) + { filterArea.width = 0; } - if (filterArea.height < 0) { + if (filterArea.height < 0) + { filterArea.height = 0; } @@ -154,7 +166,8 @@ * Removes the last filter from the filter stack and doesn't return it. * */ -WebGLFilterManager.prototype.popFilter = function () { +WebGLFilterManager.prototype.popFilter = function () +{ var gl = this.renderer.gl; var filterBlock = this.filterStack.pop(); @@ -163,7 +176,8 @@ var projection = this.renderer.projection; var offset = this.renderer.offset; - if (filterBlock.filterPasses.length > 1) { + if (filterBlock.filterPasses.length > 1) + { gl.viewport(0, 0, filterArea.width, filterArea.height); gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); @@ -193,7 +207,8 @@ var inputTexture = texture; var outputTexture = this.texturePool.pop(); - if (!outputTexture) { + if (!outputTexture) + { outputTexture = new FilterTexture(this.renderer.gl, this.width, this.height); } outputTexture.resize(this.width, this.height); @@ -204,7 +219,8 @@ gl.disable(gl.BLEND); - for (var i = 0; i < filterBlock.filterPasses.length-1; i++) { + for (var i = 0; i < filterBlock.filterPasses.length-1; i++) + { var filterPass = filterBlock.filterPasses[i]; gl.bindFramebuffer(gl.FRAMEBUFFER, outputTexture.frameBuffer ); @@ -243,10 +259,12 @@ var buffer = this.buffer; // time to render the filters texture to the previous scene - if (this.filterStack.length === 0) { + if (this.filterStack.length === 0) + { gl.colorMask(true, true, true, true);//this.transparent); } - else { + else + { var currentFilter = this.filterStack[this.filterStack.length-1]; filterArea = currentFilter._filterArea; @@ -332,13 +350,15 @@ * @param width {number} the horizontal range of the filter * @param height {number} the vertical range of the filter */ -WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) { +WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) +{ // use program var gl = this.renderer.gl; var shader = filter.shaders[gl.id]; - if (!shader) { + if (!shader) + { shader = new Shader(gl); shader.fragmentSrc = filter.fragmentSrc; @@ -356,7 +376,8 @@ gl.uniform2f(shader.projectionVector, width/2, -height/2); gl.uniform2f(shader.offsetVector, 0,0); - if (filter.uniforms.dimensions) { + 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]; @@ -386,7 +407,8 @@ * Initialises the shader buffers. * */ -WebGLFilterManager.prototype.initShaderBuffers = function () { +WebGLFilterManager.prototype.initShaderBuffers = function () +{ var gl = this.renderer.gl; // create some buffers @@ -432,7 +454,8 @@ * Destroys the filter and removes it from the filter stack. * */ -WebGLFilterManager.prototype.destroy = function () { +WebGLFilterManager.prototype.destroy = function () +{ var gl = this.renderer.gl; this.filterStack = null; @@ -441,7 +464,8 @@ this.offsetY = 0; // destroy textures - for (var i = 0; i < this.texturePool.length; i++) { + for (var i = 0; i < this.texturePool.length; i++) + { this.texturePool[i].destroy(); } diff --git a/src/core/renderers/webgl/managers/WebGLManager.js b/src/core/renderers/webgl/managers/WebGLManager.js index 9d47b5c..c30cd51 100644 --- a/src/core/renderers/webgl/managers/WebGLManager.js +++ b/src/core/renderers/webgl/managers/WebGLManager.js @@ -3,7 +3,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLManager(renderer) { +function WebGLManager(renderer) +{ /** * The renderer this manager works for. * @@ -15,6 +16,7 @@ WebGLManager.prototype.constructor = WebGLManager; module.exports = WebGLManager; -WebGLManager.prototype.destroy = function () { +WebGLManager.prototype.destroy = function () +{ this.renderer = null; }; diff --git a/src/core/renderers/webgl/managers/WebGLMaskManager.js b/src/core/renderers/webgl/managers/WebGLMaskManager.js index 2f90b64..e568812 100644 --- a/src/core/renderers/webgl/managers/WebGLMaskManager.js +++ b/src/core/renderers/webgl/managers/WebGLMaskManager.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLMaskManager(renderer) { +function WebGLMaskManager(renderer) +{ WebGLManager.call(this, renderer); } @@ -19,12 +20,15 @@ * * @param maskData {any[]} */ -WebGLMaskManager.prototype.pushMask = function (maskData) { - if (maskData.dirty) { +WebGLMaskManager.prototype.pushMask = function (maskData) +{ + if (maskData.dirty) + { WebGLGraphics.updateGraphics(maskData, this.renderer.gl); } - if (!maskData._webGL[this.renderer.gl.id].data.length) { + if (!maskData._webGL[this.renderer.gl.id].data.length) + { return; } @@ -36,6 +40,7 @@ * * @param maskData {any[]} */ -WebGLMaskManager.prototype.popMask = function (maskData) { +WebGLMaskManager.prototype.popMask = function (maskData) +{ this.renderer.stencilManager.popStencil(maskData, maskData._webGL[this.renderer.gl.id].data[0], this.renderer); }; diff --git a/src/core/renderers/webgl/managers/WebGLShaderManager.js b/src/core/renderers/webgl/managers/WebGLShaderManager.js index fef071c..90c6477 100644 --- a/src/core/renderers/webgl/managers/WebGLShaderManager.js +++ b/src/core/renderers/webgl/managers/WebGLShaderManager.js @@ -10,7 +10,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLShaderManager(renderer) { +function WebGLShaderManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -28,7 +29,8 @@ */ this.tempAttribState = []; - for (var i = 0; i < this.maxAttibs; i++) { + for (var i = 0; i < this.maxAttibs; i++) + { this.attribState[i] = false; } @@ -66,7 +68,8 @@ // listen for context and update necessary shaders var self = this; - this.renderer.on('context', function (event) { + this.renderer.on('context', function (event) + { var gl = event.data; // this shader is used for rendering primitives @@ -97,29 +100,36 @@ * * @param attribs {Array} attribs */ -WebGLShaderManager.prototype.setAttribs = function (attribs) { +WebGLShaderManager.prototype.setAttribs = function (attribs) +{ // reset temp state var i; - for (i = 0; i < this.tempAttribState.length; i++) { + for (i = 0; i < this.tempAttribState.length; i++) + { this.tempAttribState[i] = false; } // set the new attribs - for (var a in attribs) { + for (var a in attribs) + { this.tempAttribState[attribs[a]] = true; } var gl = this.renderer.gl; - for (i = 0; i < this.attribState.length; i++) { - if (this.attribState[i] !== this.tempAttribState[i]) { + for (i = 0; i < this.attribState.length; i++) + { + if (this.attribState[i] !== this.tempAttribState[i]) + { this.attribState[i] = this.tempAttribState[i]; - if (this.attribState[i]) { + if (this.attribState[i]) + { gl.enableVertexAttribArray(i); } - else { + else + { gl.disableVertexAttribArray(i); } } @@ -131,8 +141,10 @@ * * @param shader {Any} */ -WebGLShaderManager.prototype.setShader = function (shader) { - if (this._currentId === shader.uuid) { +WebGLShaderManager.prototype.setShader = function (shader) +{ + if (this._currentId === shader.uuid) + { return false; } @@ -150,7 +162,8 @@ * Destroys this object. * */ -WebGLShaderManager.prototype.destroy = function () { +WebGLShaderManager.prototype.destroy = function () +{ this.attribState = null; this.tempAttribState = null; diff --git a/src/core/renderers/webgl/managers/WebGLStencilManager.js b/src/core/renderers/webgl/managers/WebGLStencilManager.js index 9ec6398..4cb0134 100644 --- a/src/core/renderers/webgl/managers/WebGLStencilManager.js +++ b/src/core/renderers/webgl/managers/WebGLStencilManager.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLStencilManager(renderer) { +function WebGLStencilManager(renderer) +{ WebGLManager.call(this, renderer); this.stencilStack = []; @@ -24,12 +25,14 @@ * @param graphics {Graphics} * @param webGLData {any[]} */ -WebGLStencilManager.prototype.pushStencil = function (graphics, webGLData) { +WebGLStencilManager.prototype.pushStencil = function (graphics, webGLData) +{ var gl = this.renderer.gl; this.bindGraphics(graphics, webGLData, this.renderer); - if (this.stencilStack.length === 0) { + if (this.stencilStack.length === 0) + { gl.enable(gl.STENCIL_TEST); gl.clear(gl.STENCIL_BUFFER_BIT); this.reverse = true; @@ -47,14 +50,17 @@ // draw the triangle strip! - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } @@ -62,31 +68,38 @@ // draw a quad to increment.. gl.drawElements(gl.TRIANGLE_FAN, 4, gl.UNSIGNED_SHORT, ( webGLData.indices.length - 4 ) * 2 ); - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); } this.reverse = !this.reverse; } - else { - if (!this.reverse) { + else + { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } - else { + 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) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); } } @@ -103,7 +116,8 @@ * @param graphics {Graphics} * @param webGLData {Array} */ -WebGLStencilManager.prototype.bindGraphics = function (graphics, webGLData) { +WebGLStencilManager.prototype.bindGraphics = function (graphics, webGLData) +{ //if (this._currentGraphics === graphics)return; this._currentGraphics = graphics; @@ -114,7 +128,8 @@ offset = this.renderer.offset, shader;// = this.renderer.shaderManager.primitiveShader; - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { shader = this.renderer.shaderManager.complexPrimitiveShader; this.renderer.shaderManager.setShader(shader); @@ -141,7 +156,8 @@ // set the index buffer! gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, webGLData.indexBuffer); } - else { + else + { //this.renderer.shaderManager.activatePrimitiveShader(); shader = this.renderer.shaderManager.primitiveShader; this.renderer.shaderManager.setShader( shader ); @@ -154,7 +170,7 @@ gl.uniform2f(shader.uniforms.offsetVector._location, -offset.x, -offset.y); gl.uniform3fv(shader.uniforms.tint._location, utils.hex2rgb(graphics.tint)); - + gl.uniform1f(shader.uniforms.alpha._location, graphics.worldAlpha); @@ -172,19 +188,22 @@ * @param graphics {Graphics} * @param webGLData {Array} */ -WebGLStencilManager.prototype.popStencil = function (graphics, webGLData) { +WebGLStencilManager.prototype.popStencil = function (graphics, webGLData) +{ var gl = this.renderer.gl; this.stencilStack.pop(); this.count--; - if (this.stencilStack.length === 0) { + if (this.stencilStack.length === 0) + { // the stack is empty! gl.disable(gl.STENCIL_TEST); } - else { + else + { var level = this.count; @@ -192,14 +211,17 @@ gl.colorMask(false, false, false, false); - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { this.reverse = !this.reverse; - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } @@ -213,31 +235,38 @@ // draw the triangle strip! gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); - if (!this.reverse) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); } } - else { + else + { // console.log("<<>>") - if (!this.reverse) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } - else { + 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) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); } } @@ -253,7 +282,8 @@ * Destroys the mask stack. * */ -WebGLStencilManager.prototype.destroy = function () { +WebGLStencilManager.prototype.destroy = function () +{ this.renderer = null; this.stencilStack = null; }; diff --git a/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js b/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js index 913ba5e..1ea7d19 100644 --- a/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js +++ b/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function ComplexPrimitiveShader(gl) { +function ComplexPrimitiveShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -24,7 +25,8 @@ 'uniform float flipY;', 'varying vec4 vColor;', - 'void main(void) {', + '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);', @@ -37,7 +39,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = vColor;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/FastShader.js b/src/core/renderers/webgl/shaders/FastShader.js index bd2e29a..2e5e060 100644 --- a/src/core/renderers/webgl/shaders/FastShader.js +++ b/src/core/renderers/webgl/shaders/FastShader.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function FastShader(gl) { +function FastShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -28,7 +29,8 @@ 'const vec2 center = vec2(-1.0, 1.0);', - 'void main(void) {', + 'void main(void) + {', ' vec2 v;', ' vec2 sv = aVertexPosition * aScale;', ' v.x = (sv.x) * cos(aRotation) - (sv.y) * sin(aRotation);', @@ -49,7 +51,8 @@ 'uniform sampler2D uSampler;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/PrimitiveShader.js b/src/core/renderers/webgl/shaders/PrimitiveShader.js index 6f25409..a25f54f 100644 --- a/src/core/renderers/webgl/shaders/PrimitiveShader.js +++ b/src/core/renderers/webgl/shaders/PrimitiveShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function PrimitiveShader(gl) { +function PrimitiveShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -23,7 +24,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + '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);', @@ -36,7 +38,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = vColor;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/Shader.js b/src/core/renderers/webgl/shaders/Shader.js index f8964f5..fd75ef5 100644 --- a/src/core/renderers/webgl/shaders/Shader.js +++ b/src/core/renderers/webgl/shaders/Shader.js @@ -6,7 +6,8 @@ * @param [fragmentSrc] {string} The source of the fragment shader. * @param [vertexSrc] {string} The source of the vertex shader. */ -function Shader(gl, vertexSrc, fragmentSrc, customUniforms, customAttributes) { +function Shader(gl, vertexSrc, fragmentSrc, customUniforms, customAttributes) +{ /** * @member {number} * @readonly @@ -33,7 +34,8 @@ dimensions: { type: '4f', value: new Float32Array(4) } }; - for (var u in customUniforms) { + for (var u in customUniforms) + { this.uniforms[u] = customUniforms[u]; } @@ -43,7 +45,8 @@ aColor: 0 }; - for (var a in customAttributes) { + for (var a in customAttributes) + { this.attributes[a] = customAttributes[a]; } @@ -66,7 +69,8 @@ 'const vec2 center = vec2(-1.0, 1.0);', - 'void main(void) {', + 'void main(void) + {', ' gl_Position = vec4( ((aVertexPosition + offsetVector) / projectionVector) + center , 0.0, 1.0);', ' vTextureCoord = aTextureCoord;', ' vColor = vec4(aColor.rgb * aColor.a, aColor.a);', @@ -85,7 +89,8 @@ 'uniform sampler2D uSampler;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;', '}' ].join('\n'); @@ -96,7 +101,8 @@ Shader.prototype.constructor = Shader; module.exports = Shader; -Shader.prototype.init = function () { +Shader.prototype.init = function () +{ this.compile(); this.gl.useProgram(this.program); @@ -105,14 +111,18 @@ this.cacheAttributeLocations(Object.keys(this.attributes)); }; -Shader.prototype.cacheUniformLocations = function (keys) { - for (var i = 0; i < keys.length; ++i) { +Shader.prototype.cacheUniformLocations = function (keys) +{ + for (var i = 0; i < keys.length; ++i) + { this.uniforms[keys[i]]._location = this.gl.getUniformLocation(this.program, keys[i]); } }; -Shader.prototype.cacheAttributeLocations = function (keys) { - for (var i = 0; i < keys.length; ++i) { +Shader.prototype.cacheAttributeLocations = function (keys) +{ + for (var i = 0; i < keys.length; ++i) + { this.attributes[keys[i]] = this.gl.getAttribLocation(this.program, keys[i]); } @@ -124,14 +134,16 @@ // 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.attributes.aColor === -1) { + // if (this.attributes.aColor === -1) + { // this.attributes.aColor = 2; // } // End worst hack eva // }; -Shader.prototype.compile = function () { +Shader.prototype.compile = function () +{ var gl = this.gl; var glVertShader = this._glCompile(gl.VERTEX_SHADER, this.vertexSrc); @@ -144,13 +156,15 @@ gl.linkProgram(program); // if linking fails, then log and cleanup - if (!gl.getProgramParameter(program, gl.LINK_STATUS)) { + if (!gl.getProgramParameter(program, gl.LINK_STATUS)) + { window.console.error('Pixi.js Error: Could not initialize shader.'); window.console.error('gl.VALIDATE_STATUS', gl.getProgramParameter(program, gl.VALIDATE_STATUS)); window.console.error('gl.getError()', gl.getError()); // if there is a program info log, log it - if (gl.getProgramInfoLog(program) !== '') { + if (gl.getProgramInfoLog(program) !== '') + { window.console.warn('Pixi.js Warning: gl.getProgramInfoLog()', gl.getProgramInfoLog(program)); } @@ -165,18 +179,21 @@ return (this.program = program); }; -Shader.prototype.syncUniforms = function () { +Shader.prototype.syncUniforms = function () +{ var gl = this.gl; this.textureCount = 1; - for (var key in this.uniforms) { + for (var key in this.uniforms) + { var uniform = this.uniforms[key], location = uniform._location, value = uniform.value, i, il; - switch (uniform.type) { + switch (uniform.type) + { // single int value case 'i': case '1i': @@ -282,7 +299,8 @@ // a Color Value case 'c': - if (typeof value === 'number') { + if (typeof value === 'number') + { value = utils.hex2rgb(value); } @@ -311,11 +329,13 @@ // array of 2D Point objects case 'v2v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(2 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 2] = value[i].x; uniform._array[i * 2 + 1] = value[i].y; } @@ -325,11 +345,13 @@ // array of 3D Point objects case 'v3v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(3 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 3] = value[i].x; uniform._array[i * 3 + 1] = value[i].y; uniform._array[i * 3 + 2] = value[i].z; @@ -341,11 +363,13 @@ // array of 4D Point objects case 'v4v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(4 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 4] = value[i].x; uniform._array[i * 4 + 1] = value[i].y; uniform._array[i * 4 + 2] = value[i].z; @@ -359,7 +383,8 @@ // PIXI.Texture case 't': case 'sampler2D': - if (!uniform.value || !uniform.value.baseTexture || !uniform.value.baseTexture.hasLoaded) { + if (!uniform.value || !uniform.value.baseTexture || !uniform.value.baseTexture.hasLoaded) + { break; } @@ -376,7 +401,8 @@ this.textureCount++; // initialize the texture if we haven't yet - if (!uniform._init) { + if (!uniform._init) + { this.initSampler2D(uniform); uniform._init = true; @@ -394,11 +420,13 @@ * Initialises a Sampler2D uniform (which may only be available later on after initUniforms once the texture has loaded) * */ -Shader.prototype.initSampler2D = function (uniform) { +Shader.prototype.initSampler2D = function (uniform) +{ var gl = this.gl; // Extended texture data - if (uniform.textureData) { + if (uniform.textureData) + { var data = uniform.textureData; // GLTexture = mag linear, min linear_mipmap_linear, wrap repeat + gl.generateMipmap(gl.TEXTURE_2D); @@ -417,14 +445,16 @@ var wrapT = (data.wrapT) ? data.wrapT : gl.CLAMP_TO_EDGE; var format = (data.luminance) ? gl.LUMINANCE : gl.RGBA; - if (data.repeat) { + if (data.repeat) + { wrapS = gl.REPEAT; wrapT = gl.REPEAT; } gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, !!data.flipY); - if (data.width) { + if (data.width) + { var width = (data.width) ? data.width : 512; var height = (data.height) ? data.height : 2; var border = (data.border) ? data.border : 0; @@ -432,7 +462,8 @@ // 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 { + 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); } @@ -448,7 +479,8 @@ * Destroys the shader. * */ -Shader.prototype.destroy = function () { +Shader.prototype.destroy = function () +{ this.gl.deleteProgram(this.program); this.gl = null; @@ -459,13 +491,15 @@ this.fragmentSrc = null; }; -Shader.prototype._glCompile = function (type, src) { +Shader.prototype._glCompile = function (type, src) +{ var shader = this.gl.createShader(type); this.gl.shaderSource(shader, src); this.gl.compileShader(shader); - if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) { + if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) + { window.console.log(this.gl.getShaderInfoLog(shader)); return null; } diff --git a/src/core/renderers/webgl/shaders/StripShader.js b/src/core/renderers/webgl/shaders/StripShader.js index 193f6e1..a7abcc6 100644 --- a/src/core/renderers/webgl/shaders/StripShader.js +++ b/src/core/renderers/webgl/shaders/StripShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function StripShader(gl) { +function StripShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -20,7 +21,8 @@ 'varying vec2 vTextureCoord;', - 'void main(void) {', + '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);', @@ -36,7 +38,8 @@ 'varying vec2 vTextureCoord;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vec2(vTextureCoord.x, vTextureCoord.y)) * alpha;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/utils/FilterTexture.js b/src/core/renderers/webgl/utils/FilterTexture.js index d2c8423..4433d44 100644 --- a/src/core/renderers/webgl/utils/FilterTexture.js +++ b/src/core/renderers/webgl/utils/FilterTexture.js @@ -8,7 +8,8 @@ * @param height {number} the vertical range of the filter * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values */ -function FilterTexture(gl, width, height, scaleMode) { +function FilterTexture(gl, width, height, scaleMode) +{ /** * @member {WebGLContext} */ @@ -59,7 +60,8 @@ * Clears the filter texture. * */ -FilterTexture.prototype.clear = function () { +FilterTexture.prototype.clear = function () +{ var gl = this.gl; gl.clearColor(0,0,0, 0); @@ -72,8 +74,10 @@ * @param width {number} the new width of the texture * @param height {number} the new height of the texture */ -FilterTexture.prototype.resize = function (width, height) { - if (this.width === width && this.height === height) { +FilterTexture.prototype.resize = function (width, height) +{ + if (this.width === width && this.height === height) + { return; } @@ -96,7 +100,8 @@ * Destroys the filter texture. * */ -FilterTexture.prototype.destroy = function () { +FilterTexture.prototype.destroy = function () +{ var gl = this.gl; gl.deleteFramebuffer( this.frameBuffer ); gl.deleteTexture( this.texture ); diff --git a/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js b/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js index c4721e9..a63f4d7 100644 --- a/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js +++ b/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js @@ -14,7 +14,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this sprite batch works for. */ -function WebGLFastSpriteBatch(renderer) { +function WebGLFastSpriteBatch(renderer) +{ /** * The renderer instance this sprite batch operates on. * @@ -91,7 +92,8 @@ */ this.lastIndexCount = 0; - for (var i=0, j=0; i < numIndices; i += 6, j += 4) { + 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; @@ -144,7 +146,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.setupContext(); }); } @@ -157,7 +160,8 @@ * * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLFastSpriteBatch.prototype.setupContext = function () { +WebGLFastSpriteBatch.prototype.setupContext = function () +{ var gl = this.renderer.gl; // create a couple of buffers @@ -177,7 +181,8 @@ /** * @param spriteBatch {SpriteBatch} The SpriteBatch container to prepare for. */ -WebGLFastSpriteBatch.prototype.begin = function (spriteBatch) { +WebGLFastSpriteBatch.prototype.begin = function (spriteBatch) +{ this.shader = this.renderer.shaderManager.fastShader; this.matrix = spriteBatch.worldTransform.toArray(true); @@ -187,33 +192,38 @@ /** */ -WebGLFastSpriteBatch.prototype.end = function () { +WebGLFastSpriteBatch.prototype.end = function () +{ this.flush(); }; /** * @param spriteBatch {SpriteBatch} The SpriteBatch container to render. */ -WebGLFastSpriteBatch.prototype.render = function (spriteBatch) { +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) { + if (!sprite.texture._uvs) + { return; } this.currentBaseTexture = sprite.texture.baseTexture; // check blend mode - if (sprite.blendMode !== this.renderer.blendModeManager.currentBlendMode) { + if (sprite.blendMode !== this.renderer.blendModeManager.currentBlendMode) + { this.flush(); this.renderer.blendModeManager.setBlendMode(sprite.blendMode); } - for (var i=0,j= children.length; i= this.size) { + if (this.currentBatchSize >= this.size) + { this.flush(); } }; @@ -362,29 +379,35 @@ /** * */ -WebGLFastSpriteBatch.prototype.flush = function () { +WebGLFastSpriteBatch.prototype.flush = function () +{ // If the batch is length 0 then return as there is nothing to draw - if (this.currentBatchSize === 0) { + if (this.currentBatchSize === 0) + { return; } var gl = this.renderer.gl; // bind the current texture - if (!this.currentBaseTexture._glTextures[gl.id]) { + if (!this.currentBaseTexture._glTextures[gl.id]) + { this.renderer.updateTexture(this.currentBaseTexture, gl); } //TODO-SHOUD THIS BE ELSE??!?!?! - else { + else + { gl.bindTexture(gl.TEXTURE_2D, this.currentBaseTexture._glTextures[gl.id]); } // upload the verts to the buffer - if (this.currentBatchSize > ( this.size * 0.5 ) ) { + if (this.currentBatchSize > ( this.size * 0.5 ) ) + { gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); } - else { + else + { var view = this.vertices.subarray(0, this.currentBatchSize * this.vertByteSize); gl.bufferSubData(gl.ARRAY_BUFFER, 0, view); @@ -405,14 +428,16 @@ * Ends the batch and flushes * */ -WebGLFastSpriteBatch.prototype.stop = function () { +WebGLFastSpriteBatch.prototype.stop = function () +{ this.flush(); }; /** * */ -WebGLFastSpriteBatch.prototype.start = function () { +WebGLFastSpriteBatch.prototype.start = function () +{ var gl = this.renderer.gl; // bind the main texture diff --git a/src/core/renderers/webgl/utils/WebGLGraphics.js b/src/core/renderers/webgl/utils/WebGLGraphics.js index 55f4911..ab8f46e 100644 --- a/src/core/renderers/webgl/utils/WebGLGraphics.js +++ b/src/core/renderers/webgl/utils/WebGLGraphics.js @@ -19,7 +19,8 @@ * @param graphics {Graphics} * @param renderer {WebGLRenderer} */ -WebGLGraphics.renderGraphics = function (graphics, renderer) {//projection, offset) { +WebGLGraphics.renderGraphics = function (graphics, renderer) {//projection, offset) +{ var gl = renderer.gl; var projection = renderer.projection, @@ -27,7 +28,8 @@ shader = renderer.shaderManager.primitiveShader, webGLData; - if (graphics.dirty) { + if (graphics.dirty) + { WebGLGraphics.updateGraphics(graphics, gl); } @@ -35,8 +37,10 @@ // This could be speeded up for sure! - for (var i = 0; i < webGL.data.length; i++) { - if (webGL.data[i].mode === 1) { + for (var i = 0; i < webGL.data.length; i++) + { + if (webGL.data[i].mode === 1) + { webGLData = webGL.data[i]; renderer.stencilManager.pushStencil(graphics, webGLData, renderer); @@ -46,7 +50,8 @@ renderer.stencilManager.popStencil(graphics, webGLData, renderer); } - else { + else + { webGLData = webGL.data[i]; @@ -84,12 +89,14 @@ * @param graphicsData {Graphics} The graphics object to update * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLGraphics.updateGraphics = function (graphics, gl) { +WebGLGraphics.updateGraphics = function (graphics, gl) +{ // get the contexts graphics object var webGL = graphics._webGL[gl.id]; // if the graphics object does not exist in the webGL context time to create it! - if (!webGL) { + if (!webGL) + { webGL = graphics._webGL[gl.id] = {lastIndex:0, data:[], gl:gl}; } @@ -99,11 +106,13 @@ var i; // if the user cleared the graphics object we will need to clear every object - if (graphics.clearDirty) { + if (graphics.clearDirty) + { graphics.clearDirty = false; // lop through and return all the webGLDatas to the object pool so than can be reused later on - for (i = 0; i < webGL.data.length; i++) { + for (i = 0; i < webGL.data.length; i++) + { var graphicsData = webGL.data[i]; graphicsData.reset(); WebGLGraphics.graphicsDataPool.push( graphicsData ); @@ -119,58 +128,72 @@ // loop through the graphics datas and construct each one.. // if the object is a complex fill then the new stencil buffer technique will be used // other wise graphics objects will be pushed into a batch.. - for (i = webGL.lastIndex; i < graphics.graphicsData.length; i++) { + for (i = webGL.lastIndex; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { // need to add the points the the graphics object.. data.points = data.shape.points.slice(); - if (data.shape.closed) { + if (data.shape.closed) + { // close the poly if the value is true! - if (data.points[0] !== data.points[data.points.length-2] || data.points[1] !== data.points[data.points.length-1]) { + if (data.points[0] !== data.points[data.points.length-2] || data.points[1] !== data.points[data.points.length-1]) + { data.points.push(data.points[0], data.points[1]); } } // MAKE SURE WE HAVE THE CORRECT TYPE.. - if (data.fill) { - if (data.points.length >= 6) { - if (data.points.length < 6 * 2) { + if (data.fill) + { + if (data.points.length >= 6) + { + if (data.points.length < 6 * 2) + { webGLData = WebGLGraphics.switchMode(webGL, 0); var canDrawUsingSimple = WebGLGraphics.buildPoly(data, webGLData); // console.log(canDrawUsingSimple); - if (!canDrawUsingSimple) { + if (!canDrawUsingSimple) + { // console.log("<>>>") webGLData = WebGLGraphics.switchMode(webGL, 1); WebGLGraphics.buildComplexPoly(data, webGLData); } } - else { + else + { webGLData = WebGLGraphics.switchMode(webGL, 1); WebGLGraphics.buildComplexPoly(data, webGLData); } } } - if (data.lineWidth > 0) { + if (data.lineWidth > 0) + { webGLData = WebGLGraphics.switchMode(webGL, 0); WebGLGraphics.buildLine(data, webGLData); } } - else { + else + { webGLData = WebGLGraphics.switchMode(webGL, 0); - if (data.type === CONST.SHAPES.RECT) { + if (data.type === CONST.SHAPES.RECT) + { WebGLGraphics.buildRectangle(data, webGLData); } - else if (data.type === CONST.SHAPES.CIRC || data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.CIRC || data.type === CONST.SHAPES.ELIP) + { WebGLGraphics.buildCircle(data, webGLData); } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { WebGLGraphics.buildRoundedRectangle(data, webGLData); } } @@ -179,10 +202,12 @@ } // upload all the dirty data... - for (i = 0; i < webGL.data.length; i++) { + for (i = 0; i < webGL.data.length; i++) + { webGLData = webGL.data[i]; - if (webGLData.dirty) { + if (webGLData.dirty) + { webGLData.upload(); } } @@ -194,18 +219,22 @@ * @param webGL {WebGLContext} * @param type {number} */ -WebGLGraphics.switchMode = function (webGL, type) { +WebGLGraphics.switchMode = function (webGL, type) +{ var webGLData; - if (!webGL.data.length) { + if (!webGL.data.length) + { webGLData = WebGLGraphics.graphicsDataPool.pop() || new WebGLGraphicsData(webGL.gl); webGLData.mode = type; webGL.data.push(webGLData); } - else { + else + { webGLData = webGL.data[webGL.data.length-1]; - if (webGLData.mode !== type || type === 1) { + if (webGLData.mode !== type || type === 1) + { webGLData = WebGLGraphics.graphicsDataPool.pop() || new WebGLGraphicsData(webGL.gl); webGLData.mode = type; webGL.data.push(webGLData); @@ -225,7 +254,8 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildRectangle = function (graphicsData, webGLData) { +WebGLGraphics.buildRectangle = function (graphicsData, webGLData) +{ // --- // // need to convert points to a nice regular data // @@ -235,7 +265,8 @@ var width = rectData.width; var height = rectData.height; - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -265,7 +296,8 @@ indices.push(vertPos, vertPos, vertPos+1, vertPos+2, vertPos+3, vertPos+3); } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = [x, y, @@ -289,7 +321,8 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildRoundedRectangle = function (graphicsData, webGLData) { +WebGLGraphics.buildRoundedRectangle = function (graphicsData, webGLData) +{ var rrectData = graphicsData.shape; var x = rrectData.x; var y = rrectData.y; @@ -305,7 +338,8 @@ recPoints = recPoints.concat(WebGLGraphics.quadraticBezierCurve(x + width, y + radius, x + width, y, x + width - radius, y)); recPoints = recPoints.concat(WebGLGraphics.quadraticBezierCurve(x + radius, y, x, y, x, y + radius)); - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -323,7 +357,8 @@ // var i = 0; - for (i = 0; i < triangles.length; i+=3) { + for (i = 0; i < triangles.length; i+=3) + { indices.push(triangles[i] + vecPos); indices.push(triangles[i] + vecPos); indices.push(triangles[i+1] + vecPos); @@ -332,12 +367,14 @@ } - for (i = 0; i < recPoints.length; i++) { + for (i = 0; i < recPoints.length; i++) + { verts.push(recPoints[i], recPoints[++i], r, g, b, alpha); } } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = recPoints; @@ -362,7 +399,8 @@ * @param toY {number} Destination point y * @return {number[]} */ -WebGLGraphics.quadraticBezierCurve = function (fromX, fromY, cpX, cpY, toX, toY) { +WebGLGraphics.quadraticBezierCurve = function (fromX, fromY, cpX, cpY, toX, toY) +{ var xa, ya, @@ -373,14 +411,16 @@ n = 20, points = []; - function getPt(n1 , n2, perc) { + function getPt(n1 , n2, perc) + { var diff = n2 - n1; return n1 + ( diff * perc ); } var j = 0; - for (var i = 0; i <= n; i++ ) { + for (var i = 0; i <= n; i++ ) + { j = i / n; // The Green Line @@ -406,7 +446,8 @@ * @param graphicsData {Graphics} The graphics object to draw * @param webGLData {object} */ -WebGLGraphics.buildCircle = function (graphicsData, webGLData) { +WebGLGraphics.buildCircle = function (graphicsData, webGLData) +{ // need to convert points to a nice regular data var circleData = graphicsData.shape; var x = circleData.x; @@ -415,11 +456,13 @@ var height; // TODO - bit hacky?? - if (graphicsData.type === CONST.SHAPES.CIRC) { + if (graphicsData.type === CONST.SHAPES.CIRC) + { width = circleData.radius; height = circleData.radius; } - else { + else + { width = circleData.width; height = circleData.height; } @@ -429,7 +472,8 @@ var i = 0; - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -444,7 +488,8 @@ indices.push(vecPos); - for (i = 0; i < totalSegs + 1 ; i++) { + for (i = 0; i < totalSegs + 1 ; i++) + { verts.push(x,y, r, g, b, alpha); verts.push(x + Math.sin(seg * i) * width, @@ -457,12 +502,14 @@ indices.push(vecPos-1); } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = []; - for (i = 0; i < totalSegs + 1; i++) { + for (i = 0; i < totalSegs + 1; i++) + { graphicsData.points.push(x + Math.sin(seg * i) * width, y + Math.cos(seg * i) * height); } @@ -481,18 +528,22 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildLine = function (graphicsData, webGLData) { +WebGLGraphics.buildLine = function (graphicsData, webGLData) +{ // TODO OPTIMISE! var i = 0; var points = graphicsData.points; - if (points.length === 0) { + if (points.length === 0) + { return; } // if the line width is an odd number add 0.5 to align to a whole pixel - if (graphicsData.lineWidth%2) { - for (i = 0; i < points.length; i++) { + if (graphicsData.lineWidth%2) + { + for (i = 0; i < points.length; i++) + { points[i] += 0.5; } } @@ -502,7 +553,8 @@ var lastPoint = new math.Point(points[points.length - 2], points[points.length - 1]); // if the first point is the last point - gonna have issues :) - if (firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) { + if (firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) + { // need to clone as we are going to slightly modify the shape.. points = points.slice(); @@ -562,7 +614,8 @@ verts.push(p1x + perpx , p1y + perpy, r, g, b, alpha); - for (i = 1; i < length-1; i++) { + for (i = 1; i < length-1; i++) + { p1x = points[(i-1)*2]; p1y = points[(i-1)*2 + 1]; @@ -599,7 +652,8 @@ denom = a1*b2 - a2*b1; - if (Math.abs(denom) < 0.1 ) { + if (Math.abs(denom) < 0.1 ) + { denom+=10.1; verts.push(p2x - perpx , p2y - perpy, @@ -618,7 +672,8 @@ pdist = (px -p2x) * (px -p2x) + (py -p2y) + (py -p2y); - if (pdist > 140 * 140) { + if (pdist > 140 * 140) + { perp3x = perpx - perp2x; perp3y = perpy - perp2y; @@ -639,7 +694,8 @@ indexCount++; } - else { + else + { verts.push(px , py); verts.push(r, g, b, alpha); @@ -672,7 +728,8 @@ indices.push(indexStart); - for (i = 0; i < indexCount; i++) { + for (i = 0; i < indexCount; i++) + { indices.push(indexStart++); } @@ -687,11 +744,13 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildComplexPoly = function (graphicsData, webGLData) { +WebGLGraphics.buildComplexPoly = function (graphicsData, webGLData) +{ //TODO - no need to copy this as it gets turned into a FLoat32Array anyways.. var points = graphicsData.points.slice(); - if (points.length < 6) { + if (points.length < 6) + { return; } @@ -711,7 +770,8 @@ var x,y; // get size.. - for (var i = 0; i < points.length; i+=2) { + for (var i = 0; i < points.length; i+=2) + { x = points[i]; y = points[i+1]; @@ -732,7 +792,8 @@ //TODO - this aint needed! var length = points.length / 2; - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { indices.push( i ); } @@ -746,10 +807,12 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildPoly = function (graphicsData, webGLData) { +WebGLGraphics.buildPoly = function (graphicsData, webGLData) +{ var points = graphicsData.points; - if (points.length < 6) { + if (points.length < 6) + { return; } // get first and last point.. figure out the middle! @@ -767,7 +830,8 @@ var triangles = utils.PolyK.Triangulate(points); - if (!triangles) { + if (!triangles) + { return false; } @@ -775,7 +839,8 @@ var i = 0; - for (i = 0; i < triangles.length; i+=3) { + for (i = 0; i < triangles.length; i+=3) + { indices.push(triangles[i] + vertPos); indices.push(triangles[i] + vertPos); indices.push(triangles[i+1] + vertPos); @@ -783,7 +848,8 @@ indices.push(triangles[i+2] + vertPos); } - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { verts.push(points[i * 2], points[i * 2 + 1], r, g, b, alpha); } diff --git a/src/core/renderers/webgl/utils/WebGLGraphicsData.js b/src/core/renderers/webgl/utils/WebGLGraphicsData.js index c56d05e..c739ba7 100644 --- a/src/core/renderers/webgl/utils/WebGLGraphicsData.js +++ b/src/core/renderers/webgl/utils/WebGLGraphicsData.js @@ -2,7 +2,8 @@ * @class * @private */ -function WebGLGraphicsData(gl) { +function WebGLGraphicsData(gl) +{ this.gl = gl; //TODO does this need to be split before uploding?? @@ -22,7 +23,8 @@ /** * */ -WebGLGraphicsData.prototype.reset = function () { +WebGLGraphicsData.prototype.reset = function () +{ this.points.length = 0; this.indices.length = 0; }; @@ -30,7 +32,8 @@ /** * */ -WebGLGraphicsData.prototype.upload = function () { +WebGLGraphicsData.prototype.upload = function () +{ var gl = this.gl; // this.lastIndex = graphics.graphicsData.length; diff --git a/src/core/renderers/webgl/utils/WebGLSpriteBatch.js b/src/core/renderers/webgl/utils/WebGLSpriteBatch.js index 96eaa52..55befbb 100644 --- a/src/core/renderers/webgl/utils/WebGLSpriteBatch.js +++ b/src/core/renderers/webgl/utils/WebGLSpriteBatch.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this sprite batch works for. */ -function WebGLSpriteBatch(renderer) { +function WebGLSpriteBatch(renderer) +{ /** * * @@ -88,7 +89,8 @@ */ this.lastIndexCount = 0; - for (var i=0, j=0; i < numIndices; i += 6, j += 4) { + 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; @@ -162,7 +164,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.setupContext(); }); } @@ -173,7 +176,8 @@ /** * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLSpriteBatch.prototype.setupContext = function () { +WebGLSpriteBatch.prototype.setupContext = function () +{ var gl = this.renderer.gl; // setup default shader @@ -198,7 +202,8 @@ /** * */ -WebGLSpriteBatch.prototype.begin = function () { +WebGLSpriteBatch.prototype.begin = function () +{ // this.shader = this.renderer.shaderManager.defaultShader; this.start(); @@ -206,19 +211,22 @@ /** */ -WebGLSpriteBatch.prototype.end = function () { +WebGLSpriteBatch.prototype.end = function () +{ this.flush(); }; /** * @param sprite {Sprite} the sprite to render when using this spritebatch */ -WebGLSpriteBatch.prototype.render = function (sprite) { +WebGLSpriteBatch.prototype.render = function (sprite) +{ var texture = sprite.texture; //TODO set blend modes.. // check texture.. - if (this.currentBatchSize >= this.size) { + if (this.currentBatchSize >= this.size) + { this.flush(); this.currentBaseTexture = texture.baseTexture; } @@ -227,7 +235,8 @@ var uvs = texture._uvs; // if the uvs have not updated then no point rendering just yet! - if (!uvs) { + if (!uvs) + { return; } @@ -237,7 +246,8 @@ var w0, w1, h0, h1; - if (texture.trim) { + 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; @@ -248,7 +258,8 @@ h0 = h1 + texture.crop.height; } - else { + else + { w0 = (texture.frame.width ) * (1-aX); w1 = (texture.frame.width ) * -aX; @@ -272,7 +283,8 @@ var colors = this.colors; var positions = this.positions; - if (this.renderer.roundPixels) { + if (this.renderer.roundPixels) + { // xy positions[index] = a * w1 + c * h1 + tx | 0; positions[index+1] = d * h1 + b * w1 + ty | 0; @@ -289,7 +301,8 @@ positions[index+15] = a * w1 + c * h0 + tx | 0; positions[index+16] = d * h0 + b * w1 + ty | 0; } - else { + else + { // xy positions[index] = a * w1 + c * h1 + tx; positions[index+1] = d * h1 + b * w1 + ty; @@ -338,11 +351,13 @@ * * @param sprite {TilingSprite} the tilingSprite to render */ -WebGLSpriteBatch.prototype.renderTilingSprite = function (tilingSprite) { +WebGLSpriteBatch.prototype.renderTilingSprite = function (tilingSprite) +{ var texture = tilingSprite.tilingTexture; // check texture.. - if (this.currentBatchSize >= this.size) { + if (this.currentBatchSize >= this.size) + { //return; this.flush(); this.currentBaseTexture = texture.baseTexture; @@ -351,7 +366,8 @@ // set the textures uvs temporarily // TODO create a separate texture so that we can tile part of a texture - if (!tilingSprite._uvs) { + if (!tilingSprite._uvs) + { tilingSprite._uvs = new TextureUvs(); } @@ -454,16 +470,19 @@ * Renders the content and empties the current batch. * */ -WebGLSpriteBatch.prototype.flush = function () { +WebGLSpriteBatch.prototype.flush = function () +{ // If the batch is length 0 then return as there is nothing to draw - if (this.currentBatchSize === 0) { + if (this.currentBatchSize === 0) + { return; } var gl = this.renderer.gl; var shader; - if (this.dirty) { + if (this.dirty) + { this.dirty = false; // bind the main texture gl.activeTexture(gl.TEXTURE0); @@ -482,10 +501,12 @@ } // upload the verts to the buffer - if (this.currentBatchSize > ( this.size * 0.5 ) ) { + if (this.currentBatchSize > ( this.size * 0.5 ) ) + { gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); } - else { + else + { var view = this.positions.subarray(0, this.currentBatchSize * this.vertByteSize); gl.bufferSubData(gl.ARRAY_BUFFER, 0, view); } @@ -502,7 +523,8 @@ var shaderSwap = false; var sprite; - for (var i = 0, j = this.currentBatchSize; i < j; i++) { + for (var i = 0, j = this.currentBatchSize; i < j; i++) + { sprite = this.sprites[i]; @@ -513,24 +535,28 @@ blendSwap = currentBlendMode !== nextBlendMode; shaderSwap = currentShader !== nextShader; // should I use uuidS??? - if (currentBaseTexture !== nextTexture || blendSwap || shaderSwap) { + if (currentBaseTexture !== nextTexture || blendSwap || shaderSwap) + { this.renderBatch(currentBaseTexture, batchSize, start); start = i; batchSize = 0; currentBaseTexture = nextTexture; - if (blendSwap) { + if (blendSwap) + { currentBlendMode = nextBlendMode; this.renderer.blendModeManager.setBlendMode( currentBlendMode ); } - if (shaderSwap) { + if (shaderSwap) + { currentShader = nextShader; shader = currentShader.shaders ? currentShader.shaders[gl.id] : currentShader; - if (!shader) { + if (!shader) + { shader = new Shader(gl, null, currentShader.fragmentSrc, currentShader.uniforms); currentShader.shaders[gl.id] = shader; } @@ -538,7 +564,8 @@ // set shader function??? this.renderer.shaderManager.setShader(shader); - if (shader.dirty) { + if (shader.dirty) + { shader.syncUniforms(); } @@ -569,17 +596,21 @@ * @param size {number} * @param startIndex {number} */ -WebGLSpriteBatch.prototype.renderBatch = function (texture, size, startIndex) { - if (size === 0) { +WebGLSpriteBatch.prototype.renderBatch = function (texture, size, startIndex) +{ + if (size === 0) + { return; } var gl = this.renderer.gl; - if (!texture._glTextures[gl.id]) { + if (!texture._glTextures[gl.id]) + { this.renderer.updateTexture(texture); } - else { + else + { // bind the current texture gl.bindTexture(gl.TEXTURE_2D, texture._glTextures[gl.id]); } @@ -594,7 +625,8 @@ /** * */ -WebGLSpriteBatch.prototype.stop = function () { +WebGLSpriteBatch.prototype.stop = function () +{ this.flush(); this.dirty = true; }; @@ -602,7 +634,8 @@ /** * */ -WebGLSpriteBatch.prototype.start = function () { +WebGLSpriteBatch.prototype.start = function () +{ this.dirty = true; }; @@ -610,7 +643,8 @@ * Destroys the SpriteBatch. * */ -WebGLSpriteBatch.prototype.destroy = function () { +WebGLSpriteBatch.prototype.destroy = function () +{ this.renderer.gl.deleteBuffer(this.vertexBuffer); this.renderer.gl.deleteBuffer(this.indexBuffer); diff --git a/src/core/textures/BaseTexture.js b/src/core/textures/BaseTexture.js index 2bf77d4..513d358 100644 --- a/src/core/textures/BaseTexture.js +++ b/src/core/textures/BaseTexture.js @@ -10,7 +10,8 @@ * @param source {Image|Canvas} the source object of the texture. * @param [scaleMode=scaleModes.DEFAULT] {number} See {@link scaleModes} for possible values */ -function BaseTexture(source, scaleMode) { +function BaseTexture(source, scaleMode) +{ this.uuid = utils.uuid(); /** @@ -123,7 +124,8 @@ this._needsUpdate = false; // if no source passed don't try to load - if (source) { + if (source) + { this.loadSource(source); } @@ -149,13 +151,16 @@ Object.defineProperties(BaseTexture.prototype, { needsUpdate: { - get: function () { + get: function () + { return this._needsUpdate; }, - set: function (val) { + set: function (val) + { this._needsUpdate = val; - if (val) { + if (val) + { this.emit('update', this); } } @@ -171,9 +176,11 @@ * * The logic state after calling `loadSource` directly or indirectly (eg. `fromImage`, `new BaseTexture`) is: * - * if (texture.hasLoaded) { + * if (texture.hasLoaded) + { * // texture ready for use - * } else if (texture.isLoading) { + * } else if (texture.isLoading) + { * // listen to 'loaded' and/or 'error' events on texture * } else { * // not loading, not going to load UNLESS the source is reloaded @@ -183,12 +190,14 @@ * @protected * @param source {Image|Canvas} the source object of the texture. */ -BaseTexture.prototype.loadSource = function (source) { +BaseTexture.prototype.loadSource = function (source) +{ var wasLoading = this.isLoading; this.hasLoaded = false; this.isLoading = false; - if (wasLoading && this.source) { + if (wasLoading && this.source) + { this.source.onload = null; this.source.onerror = null; } @@ -196,20 +205,24 @@ this.source = source; // Apply source if loaded. Otherwise setup appropriate loading monitors. - if ((this.source.complete || this.source.getContext) && this.source.width && this.source.height) { + if ((this.source.complete || this.source.getContext) && this.source.width && this.source.height) + { this._sourceLoaded(); } - else if(!source.getContext) { + else if(!source.getContext) + { // Image fail / not ready this.isLoading = true; var scope = this; - source.onload = function () { + source.onload = function () + { source.onload = null; source.onerror = null; - if(!scope.isLoading) { + if(!scope.isLoading) + { return; } @@ -219,11 +232,13 @@ scope.emit('loaded', scope); }; - source.onerror = function () { + source.onerror = function () + { source.onload = null; source.onerror = null; - if(!scope.isLoading) { + if(!scope.isLoading) + { return; } @@ -234,24 +249,29 @@ // Per http://www.w3.org/TR/html5/embedded-content-0.html#the-img-element // "The value of `complete` can thus change while a script is executing." // So complete needs to be re-checked after the callbacks have been added.. - if (source.complete) { + if (source.complete) + { this.isLoading = false; // ..and if we're complete now, no need for callbacks source.onload = null; source.onerror = null; - if (source.width && source.height) { + if (source.width && source.height) + { this._sourceLoaded(); // If any previous subscribers possible - if (wasLoading) { + if (wasLoading) + { this.emit('loaded', this); } } - else { + else + { // If any previous subscribers possible - if (wasLoading) { + if (wasLoading) + { this.emit('error', this); } } @@ -265,7 +285,8 @@ * * @private */ -BaseTexture.prototype._sourceLoaded = function () { +BaseTexture.prototype._sourceLoaded = function () +{ this.hasLoaded = true; this.width = this.source.naturalWidth || this.source.width; @@ -278,16 +299,20 @@ * Destroys this base texture * */ -BaseTexture.prototype.destroy = function () { - if (this.imageUrl) { +BaseTexture.prototype.destroy = function () +{ + if (this.imageUrl) + { delete utils.BaseTextureCache[this.imageUrl]; delete utils.TextureCache[this.imageUrl]; this.imageUrl = null; - if (!navigator.isCocoonJS) { + if (!navigator.isCocoonJS) + { this.source.src = ''; } } - else if (this.source && this.source._pixiId) { + else if (this.source && this.source._pixiId) + { delete utils.BaseTextureCache[this.source._pixiId]; } this.source = null; @@ -301,7 +326,8 @@ * memory again. * */ -BaseTexture.prototype.dispose = function () { +BaseTexture.prototype.dispose = function () +{ this.emit('dispose', this); }; @@ -311,7 +337,8 @@ * * @param newSrc {string} the path of the image */ -BaseTexture.prototype.updateSourceImage = function (newSrc) { +BaseTexture.prototype.updateSourceImage = function (newSrc) +{ this.source.src = newSrc; this.loadSource(this.source); }; @@ -326,18 +353,22 @@ * @param [scaleMode=scaleModes.DEFAULT] {number} See {@link scaleModes} for possible values * @return BaseTexture */ -BaseTexture.fromImage = function (imageUrl, crossorigin, scaleMode) { +BaseTexture.fromImage = function (imageUrl, crossorigin, scaleMode) +{ var baseTexture = utils.BaseTextureCache[imageUrl]; - if (crossorigin === undefined && imageUrl.indexOf('data:') !== 0) { + if (crossorigin === undefined && imageUrl.indexOf('data:') !== 0) + { crossorigin = true; } - if (!baseTexture) { + if (!baseTexture) + { // new Image() breaks tex loading in some versions of Chrome. // See https://code.google.com/p/chromium/issues/detail?id=238071 var image = new Image();//document.createElement('img'); - if (crossorigin) { + if (crossorigin) + { image.crossOrigin = ''; } @@ -347,7 +378,8 @@ utils.BaseTextureCache[imageUrl] = baseTexture; // if there is an @2x at the end of the url we are going to assume its a highres image - if ( imageUrl.indexOf(CONST.RETINA_PREFIX + '.') !== -1) { + if ( imageUrl.indexOf(CONST.RETINA_PREFIX + '.') !== -1) + { baseTexture.resolution = 2; } } @@ -363,14 +395,17 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return BaseTexture */ -BaseTexture.fromCanvas = function (canvas, scaleMode) { - if (!canvas._pixiId) { +BaseTexture.fromCanvas = function (canvas, scaleMode) +{ + if (!canvas._pixiId) + { canvas._pixiId = 'canvas_' + utils.uuid(); } var baseTexture = utils.BaseTextureCache[canvas._pixiId]; - if (!baseTexture) { + if (!baseTexture) + { baseTexture = new BaseTexture(canvas, scaleMode); utils.BaseTextureCache[canvas._pixiId] = baseTexture; } diff --git a/src/core/textures/RenderTexture.js b/src/core/textures/RenderTexture.js index 6dad20f..53ae796 100644 --- a/src/core/textures/RenderTexture.js +++ b/src/core/textures/RenderTexture.js @@ -46,8 +46,10 @@ * @param [scaleMode] {number} See {@link scaleModes} for possible values * @param [resolution=1] {number} The resolution of the texture being generated */ -function RenderTexture(renderer, width, height, scaleMode, resolution) { - if (!renderer) { +function RenderTexture(renderer, width, height, scaleMode, resolution) +{ + if (!renderer) + { throw new Error('Unable to create RenderTexture, you must pass a renderer into the constructor.'); } @@ -133,7 +135,8 @@ */ this.renderer = renderer; - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { var gl = this.renderer.gl; this.textureBuffer = new FilterTexture(gl, this.width * this.resolution, this.height * this.resolution, this.baseTexture.scaleMode); @@ -142,7 +145,8 @@ this.render = this.renderWebGL; this.projection = new math.Point(this.width*0.5, -this.height*0.5); } - else { + else + { this.render = this.renderCanvas; this.textureBuffer = new CanvasBuffer(this.width* this.resolution, this.height* this.resolution); this.baseTexture.source = this.textureBuffer.canvas; @@ -167,8 +171,10 @@ * @param height {number} The height to resize to. * @param updateBase {boolean} Should the baseTexture.width and height values be resized as well? */ -RenderTexture.prototype.resize = function (width, height, updateBase) { - if (width === this.width && height === this.height) { +RenderTexture.prototype.resize = function (width, height, updateBase) +{ + if (width === this.width && height === this.height) + { return; } @@ -177,17 +183,20 @@ this.width = this.frame.width = this.crop.width = width; this.height = this.frame.height = this.crop.height = height; - if (updateBase) { + if (updateBase) + { this.baseTexture.width = this.width; this.baseTexture.height = this.height; } - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { this.projection.x = this.width / 2; this.projection.y = -this.height / 2; } - if (!this.valid) { + if (!this.valid) + { return; } @@ -198,12 +207,15 @@ * Clears the RenderTexture. * */ -RenderTexture.prototype.clear = function () { - if (!this.valid) { +RenderTexture.prototype.clear = function () +{ + if (!this.valid) + { return; } - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { this.renderer.gl.bindFramebuffer(this.renderer.gl.FRAMEBUFFER, this.textureBuffer.frameBuffer); } @@ -220,19 +232,23 @@ * @param [restoreWorldTransform=true] {boolean} If true the displayObject's worldTransform/worldAlpha and all children * transformations will be restored. Not restoring this information will be a little faster. */ -RenderTexture.prototype.renderWebGL = function (displayObject, matrix, clear, restoreWorldTransform) { - if (!this.valid) { +RenderTexture.prototype.renderWebGL = function (displayObject, matrix, clear, restoreWorldTransform) +{ + if (!this.valid) + { return; } - if (typeof restoreWorldTransform === 'undefined') { + if (typeof restoreWorldTransform === 'undefined') + { restoreWorldTransform = true; } var tempAlpha, tempTransform; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { tempAlpha = displayObject.worldAlpha; tempTransform = displayObject.worldTransform.toArray(); } @@ -245,7 +261,8 @@ wt.identity(); wt.translate(0, this.projection.y * 2); - if (matrix) { + if (matrix) + { wt.append(matrix); } @@ -258,7 +275,8 @@ var children = displayObject.children; var i, j; - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } @@ -269,7 +287,8 @@ gl.bindFramebuffer(gl.FRAMEBUFFER, this.textureBuffer.frameBuffer ); - if (clear) { + if (clear) + { this.textureBuffer.clear(); } @@ -279,11 +298,13 @@ this.renderer.spriteBatch.dirty = true; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { displayObject.worldAlpha = tempAlpha; displayObject.worldTransform.fromArray(tempTransform); - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } } @@ -300,26 +321,31 @@ * @param [restoreWorldTransform=true] {boolean} If true the displayObject's worldTransform/worldAlpha and all children * transformations will be restored. Not restoring this information will be a little faster. */ -RenderTexture.prototype.renderCanvas = function (displayObject, matrix, clear, restoreWorldTransform) { - if (!this.valid) { +RenderTexture.prototype.renderCanvas = function (displayObject, matrix, clear, restoreWorldTransform) +{ + if (!this.valid) + { return; } - if (typeof restoreWorldTransform === 'undefined') { + if (typeof restoreWorldTransform === 'undefined') + { restoreWorldTransform = true; } var tempAlpha, tempTransform; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { tempAlpha = displayObject.worldAlpha; tempTransform = displayObject.worldTransform.toArray(); } var wt = displayObject.worldTransform; wt.identity(); - if (matrix) { + if (matrix) + { wt.append(matrix); } @@ -330,11 +356,13 @@ var children = displayObject.children; var i, j; - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } - if (clear) { + if (clear) + { this.textureBuffer.clear(); } @@ -348,11 +376,13 @@ this.renderer.resolution = realResolution; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { displayObject.worldAlpha = tempAlpha; displayObject.worldTransform.fromArray(tempTransform); - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } } @@ -363,7 +393,8 @@ * * @return {Image} */ -RenderTexture.prototype.getImage = function () { +RenderTexture.prototype.getImage = function () +{ var image = new Image(); image.src = this.getBase64(); return image; @@ -374,7 +405,8 @@ * * @return {string} A base64 encoded string of the texture. */ -RenderTexture.prototype.getBase64 = function () { +RenderTexture.prototype.getBase64 = function () +{ return this.getCanvas().toDataURL(); }; @@ -383,8 +415,10 @@ * * @return {HTMLCanvasElement} A Canvas element with the texture rendered on. */ -RenderTexture.prototype.getCanvas = function () { - if (this.renderer.type === CONST.WEBGL_RENDERER) { +RenderTexture.prototype.getCanvas = function () +{ + if (this.renderer.type === CONST.WEBGL_RENDERER) + { var gl = this.renderer.gl; var width = this.textureBuffer.width; var height = this.textureBuffer.height; @@ -403,7 +437,8 @@ return tempCanvas.canvas; } - else { + else + { return this.textureBuffer.canvas; } }; diff --git a/src/core/textures/Texture.js b/src/core/textures/Texture.js index 3c65909..e97f0aa 100644 --- a/src/core/textures/Texture.js +++ b/src/core/textures/Texture.js @@ -17,7 +17,8 @@ * @param [crop] {Rectangle} The area of original texture * @param [trim] {Rectangle} Trimmed texture rectangle */ -function Texture(baseTexture, frame, crop, trim) { +function Texture(baseTexture, frame, crop, trim) +{ /** * Does this Texture have any frame data assigned to it? * @@ -25,12 +26,14 @@ */ this.noFrame = false; - if (!frame) { + if (!frame) + { this.noFrame = true; frame = new math.Rectangle(0, 0, 1, 1); } - if (baseTexture instanceof Texture) { + if (baseTexture instanceof Texture) + { baseTexture = baseTexture.baseTexture; } @@ -100,13 +103,16 @@ */ this.crop = crop || new math.Rectangle(0, 0, 1, 1); - if (baseTexture.hasLoaded) { - if (this.noFrame) { + if (baseTexture.hasLoaded) + { + if (this.noFrame) + { frame = new math.Rectangle(0, 0, baseTexture.width, baseTexture.height); } this.frame = frame; } - else { + else + { baseTexture.addEventListener('loaded', this.onBaseTextureLoaded.bind(this)); } } @@ -118,19 +124,23 @@ Object.defineProperties(Texture.prototype, { needsUpdate: { - get: function () { + get: function () + { return this.baseTexture.needsUpdate; }, - set: function (val) { + set: function (val) + { this.baseTexture.needsUpdate = val; } }, frame: { - get: function () { + get: function () + { return this._frame; }, - set: function (frame) { + set: function (frame) + { this._frame = frame; this.noFrame = false; @@ -143,20 +153,23 @@ 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 (!this.trim && (frame.x + frame.width > this.baseTexture.width || frame.y + frame.height > this.baseTexture.height)) + { throw new Error('Texture Error: frame does not fit inside the base Texture dimensions ' + this); } this.valid = frame && frame.width && frame.height && this.baseTexture.source && this.baseTexture.hasLoaded; - if (this.trim) { + 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) { + if (this.valid) + { this._updateUvs(); } } @@ -168,11 +181,13 @@ * * @private */ -Texture.prototype.onBaseTextureLoaded = function () { +Texture.prototype.onBaseTextureLoaded = function () +{ var baseTexture = this.baseTexture; baseTexture.removeEventListener('loaded', this.onLoaded); - if (this.noFrame) { + if (this.noFrame) + { this.frame = new math.Rectangle(0, 0, baseTexture.width, baseTexture.height); } @@ -184,8 +199,10 @@ * * @param destroyBase {boolean} Whether to destroy the base texture as well */ -Texture.prototype.destroy = function (destroyBase) { - if (destroyBase) { +Texture.prototype.destroy = function (destroyBase) +{ + if (destroyBase) + { this.baseTexture.destroy(); } @@ -197,8 +214,10 @@ * * @private */ -Texture.prototype._updateUvs = function () { - if (!this._uvs) { +Texture.prototype._updateUvs = function () +{ + if (!this._uvs) + { this._uvs = new TextureUvs(); } @@ -229,10 +248,12 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return Texture */ -Texture.fromImage = function (imageUrl, crossorigin, scaleMode) { +Texture.fromImage = function (imageUrl, crossorigin, scaleMode) +{ var texture = utils.TextureCache[imageUrl]; - if (!texture) { + if (!texture) + { texture = new Texture(BaseTexture.fromImage(imageUrl, crossorigin, scaleMode)); utils.TextureCache[imageUrl] = texture; } @@ -248,9 +269,11 @@ * @param frameId {string} The frame id of the texture * @return Texture */ -Texture.fromFrame = function (frameId) { +Texture.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache '); } return texture; @@ -264,7 +287,8 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return {Texture} */ -Texture.fromCanvas = function (canvas, scaleMode) { +Texture.fromCanvas = function (canvas, scaleMode) +{ return new Texture(BaseTexture.fromCanvas(canvas, scaleMode)); }; @@ -276,7 +300,8 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return {Texture} A Texture */ -Texture.fromVideo = function (video, scaleMode) { +Texture.fromVideo = function (video, scaleMode) +{ return new Texture(VideoBaseTexture.baseTextureFromVideo(video, scaleMode)); }; @@ -287,7 +312,8 @@ * @param texture {Texture} The Texture to add to the cache. * @param id {string} The id that the texture will be stored against. */ -Texture.addTextureToCache = function (texture, id) { +Texture.addTextureToCache = function (texture, id) +{ utils.TextureCache[id] = texture; }; @@ -298,7 +324,8 @@ * @param id {string} The id of the texture to be removed * @return {Texture} The texture that was removed */ -Texture.removeTextureFromCache = function (id) { +Texture.removeTextureFromCache = function (id) +{ var texture = utils.TextureCache[id]; delete utils.TextureCache[id]; diff --git a/src/core/textures/TextureUvs.js b/src/core/textures/TextureUvs.js index b9bbb58..5424d52 100644 --- a/src/core/textures/TextureUvs.js +++ b/src/core/textures/TextureUvs.js @@ -1,4 +1,5 @@ -function TextureUvs() { +function TextureUvs() +{ this.x0 = 0; this.y0 = 0; diff --git a/src/core/textures/VideoBaseTexture.js b/src/core/textures/VideoBaseTexture.js index e3e0c5a..1a826a9 100644 --- a/src/core/textures/VideoBaseTexture.js +++ b/src/core/textures/VideoBaseTexture.js @@ -12,15 +12,18 @@ * @param source {HTMLVideoElement} * @param [scaleMode] {number} See {@link scaleModes} for possible values */ -function VideoBaseTexture(source, scaleMode) { - if (!source){ +function VideoBaseTexture(source, scaleMode) +{ + if (!source) + { throw new Error('No video source element specified.'); } // hook in here to check if video is already available. // BaseTexture looks for a source.complete boolean, plus width & height. - if ((source.readyState === source.HAVE_ENOUGH_DATA || source.readyState === source.HAVE_FUTURE_DATA) && source.width && source.height) { + if ((source.readyState === source.HAVE_ENOUGH_DATA || source.readyState === source.HAVE_FUTURE_DATA) && source.width && source.height) + { source.complete = true; } @@ -31,7 +34,8 @@ this._boundOnUpdate = this._onUpdate.bind(this); this._boundOnCanPlay = this._onCanPlay.bind(this); - if (!source.complete) { + if (!source.complete) + { source.addEventListener('canplay', this._boundOnCanPlay); source.addEventListener('canplaythrough', this._boundOnCanPlay); @@ -47,28 +51,35 @@ VideoBaseTexture.prototype.constructor = VideoBaseTexture; module.exports = VideoBaseTexture; -VideoBaseTexture.prototype._onUpdate = function () { - if (this.autoUpdate) { +VideoBaseTexture.prototype._onUpdate = function () +{ + if (this.autoUpdate) + { window.requestAnimationFrame(this._boundOnUpdate); this.needsUpdate = true; } }; -VideoBaseTexture.prototype._onPlayStart = function () { - if (!this.autoUpdate) { +VideoBaseTexture.prototype._onPlayStart = function () +{ + if (!this.autoUpdate) + { window.requestAnimationFrame(this._boundOnUpdate); this.autoUpdate = true; } }; -VideoBaseTexture.prototype._onPlayStop = function () { +VideoBaseTexture.prototype._onPlayStop = function () +{ this.autoUpdate = false; }; -VideoBaseTexture.prototype._onCanPlay = function () { +VideoBaseTexture.prototype._onCanPlay = function () +{ this.hasLoaded = true; - if (this.source) { + if (this.source) + { this.source.removeEventListener('canplay', this._boundOnCanPlay); this.source.removeEventListener('canplaythrough', this._boundOnCanPlay); @@ -78,15 +89,18 @@ this.source.play(); // prevent multiple loaded dispatches.. - if(!this.__loaded){ + if(!this.__loaded) + { this.__loaded = true; this.emit('loaded', this); } } }; -VideoBaseTexture.prototype.destroy = function () { - if (this.source && this.source._pixiId) { +VideoBaseTexture.prototype.destroy = function () +{ + if (this.source && this.source._pixiId) + { utils.BaseTextureCache[ this.source._pixiId ] = null; delete utils.BaseTextureCache[ this.source._pixiId ]; @@ -105,14 +119,17 @@ * @param scaleMode {number} See {@link scaleModes} for possible values * @return {VideoBaseTexture} */ -VideoBaseTexture.fromVideo = function (video, scaleMode) { - if (!video._pixiId) { +VideoBaseTexture.fromVideo = function (video, scaleMode) +{ + if (!video._pixiId) + { video._pixiId = 'video_' + utils.uuid(); } var baseTexture = utils.BaseTextureCache[video._pixiId]; - if (!baseTexture) { + if (!baseTexture) + { baseTexture = new VideoBaseTexture(video, scaleMode); utils.BaseTextureCache[ video._pixiId ] = baseTexture; } @@ -147,17 +164,21 @@ * @param scaleMode {number} See {@link scaleModes} for possible values * @return {VideoBaseTexture} */ -VideoBaseTexture.fromUrl = function (videoSrc, scaleMode) { +VideoBaseTexture.fromUrl = function (videoSrc, scaleMode) +{ var video = document.createElement('video'); // array of objects or strings - if (Array.isArray(videoSrc)) { - for (var i = 0; i < videoSrc.length; ++i) { + if (Array.isArray(videoSrc)) + { + for (var i = 0; i < videoSrc.length; ++i) + { video.appendChild(createSource(videoSrc.src || videoSrc, videoSrc.mime)); } } // single object or string - else { + else + { video.appendChild(createSource(videoSrc.src || videoSrc, videoSrc.mime)); } @@ -169,8 +190,10 @@ VideoBaseTexture.fromUrls = VideoBaseTexture.fromUrl; -function createSource(path, type) { - if (!type) { +function createSource(path, type) +{ + if (!type) + { type = 'video/' + path.substr(path.lastIndexOf('.') + 1); } diff --git a/src/core/utils/EventData.js b/src/core/utils/EventData.js index 5d55a22..8cdf701 100644 --- a/src/core/utils/EventData.js +++ b/src/core/utils/EventData.js @@ -7,7 +7,8 @@ * @param name {string} The string name of the event that was triggered * @param data {object} Arbitrary event data to pass along */ -function EventData(target, name, data) { +function EventData(target, name, data) +{ // for duck typing in the ".on()" function this.__isEventObject = true; @@ -71,7 +72,8 @@ * Stops the propagation of events up the scene graph (prevents bubbling). * */ -EventData.prototype.stopPropagation = function stopPropagation() { +EventData.prototype.stopPropagation = function stopPropagation() +{ this.stopped = true; }; @@ -79,6 +81,7 @@ * Stops the propagation of events to sibling listeners (no longer calls any listeners). * */ -EventData.prototype.stopImmediatePropagation = function stopImmediatePropagation() { +EventData.prototype.stopImmediatePropagation = function stopImmediatePropagation() +{ this.stoppedImmediate = true; }; diff --git a/src/core/utils/EventTarget.js b/src/core/utils/EventTarget.js index 7ae8820..671a151 100644 --- a/src/core/utils/EventTarget.js +++ b/src/core/utils/EventTarget.js @@ -13,14 +13,16 @@ * var em = new MyEmitter(); * em.emit('eventName', 'some data', 'some more data', {}, null, ...); */ -function eventTarget(obj) { +function eventTarget(obj) +{ /** * Return a list of assigned event listeners. * * @param eventName {string} The events that should be listed. * @return {Array} An array of listener functions */ - obj.listeners = function listeners(eventName) { + obj.listeners = function listeners(eventName) + { this._listeners = this._listeners || {}; return this._listeners[eventName] ? this._listeners[eventName].slice() : []; @@ -33,22 +35,26 @@ * @param eventName {string} The name of the event. * @return {boolean} Indication if we've emitted an event. */ - obj.emit = obj.dispatchEvent = function emit(eventName, data) { + obj.emit = obj.dispatchEvent = function emit(eventName, data) + { this._listeners = this._listeners || {}; // fast return when there are no listeners - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return; } //backwards compat with old method ".emit({ type: 'something' })" - if (typeof eventName === 'object') { + if (typeof eventName === 'object') + { data = eventName; eventName = eventName.type; } //ensure we are using a real pixi event - if (!data || data.__isEventObject !== true) { + if (!data || data.__isEventObject !== true) + { data = new EventData(this, eventName, data); } @@ -58,23 +64,27 @@ fn = listeners[0], i; - for (i = 0; i < length; fn = listeners[++i]) { + for (i = 0; i < length; fn = listeners[++i]) + { //call the event listener fn.call(this, data); //if "stopImmediatePropagation" is called, stop calling sibling events - if (data.stoppedImmediate) { + if (data.stoppedImmediate) + { return this; } } //if "stopPropagation" is called then don't bubble the event - if (data.stopped) { + if (data.stopped) + { return this; } //bubble this event up the scene graph - if (this.parent && this.parent.emit) { + if (this.parent && this.parent.emit) + { this.parent.emit.call(this.parent, eventName, data); } @@ -88,7 +98,8 @@ * @param eventName {string} Name of the event. * @param callback {Functon} fn Callback function. */ - obj.on = obj.addEventListener = function on(eventName, fn) { + obj.on = obj.addEventListener = function on(eventName, fn) + { this._listeners = this._listeners || {}; (this._listeners[eventName] = this._listeners[eventName] || []) @@ -103,11 +114,13 @@ * @param eventName {string} Name of the event. * @param callback {Function} Callback function. */ - obj.once = function once(eventName, fn) { + obj.once = function once(eventName, fn) + { this._listeners = this._listeners || {}; var self = this; - function onceHandlerWrapper() { + function onceHandlerWrapper() + { fn.apply(self.off(eventName, onceHandlerWrapper), arguments); } onceHandlerWrapper._originalHandler = fn; @@ -122,23 +135,28 @@ * @param eventName {string} The event we want to remove. * @param callback {Function} The listener that we need to find. */ - obj.off = obj.removeEventListener = function off(eventName, fn) { + obj.off = obj.removeEventListener = function off(eventName, fn) + { this._listeners = this._listeners || {}; - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return this; } var list = this._listeners[eventName], i = fn ? list.length : 0; - while(i-- > 0) { - if (list[i] === fn || list[i]._originalHandler === fn) { + while(i-- > 0) + { + if (list[i] === fn || list[i]._originalHandler === fn) + { list.splice(i, 1); } } - if (list.length === 0) { + if (list.length === 0) + { delete this._listeners[eventName]; } @@ -150,10 +168,12 @@ * * @param eventName {string} The event you want to remove all listeners for. */ - obj.removeAllListeners = function removeAllListeners(eventName) { + obj.removeAllListeners = function removeAllListeners(eventName) + { this._listeners = this._listeners || {}; - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return this; } @@ -169,7 +189,8 @@ * * @param object {object} The obj to mix into */ - mixin: function mixin(obj) { + mixin: function mixin(obj) + { eventTarget(obj); } }; diff --git a/src/core/utils/PolyK.js b/src/core/utils/PolyK.js index 7325141..5e20c2b 100644 --- a/src/core/utils/PolyK.js +++ b/src/core/utils/PolyK.js @@ -47,7 +47,8 @@ * Triangulates shapes for webGL graphic fills. * */ -PolyK.Triangulate = function (p) { +PolyK.Triangulate = function (p) +{ var sign = true; var n = p.length >> 1; @@ -59,7 +60,8 @@ i = 0; var al = n; - while(al > 3) { + while(al > 3) + { var i0 = avl[(i+0)%al]; var i1 = avl[(i+1)%al]; var i2 = avl[(i+2)%al]; @@ -69,29 +71,35 @@ var cx = p[2*i2], cy = p[2*i2+1]; var earFound = false; - if (PolyK._convex(ax, ay, bx, by, cx, cy, sign)) { + if (PolyK._convex(ax, ay, bx, by, cx, cy, sign)) + { earFound = true; - for (var j = 0; j < al; j++) { + for (var j = 0; j < al; j++) + { var vi = avl[j]; if (vi === i0 || vi === i1 || vi === i2) continue; - if (PolyK._PointInTriangle(p[2*vi], p[2*vi+1], ax, ay, bx, by, cx, cy)) { + if (PolyK._PointInTriangle(p[2*vi], p[2*vi+1], ax, ay, bx, by, cx, cy)) + { earFound = false; break; } } } - if (earFound) { + if (earFound) + { tgs.push(i0, i1, i2); avl.splice((i+1)%al, 1); al--; i = 0; } - else if (i++ > 3*al) { + else if (i++ > 3*al) + { // need to flip flip reverse it! // reset! - if (sign) { + if (sign) + { tgs = []; avl = []; for (i = 0; i < n; i++) avl.push(i); @@ -101,7 +109,8 @@ sign = false; } - else { + else + { // window.console.log("PIXI Warning: shape too complex to fill"); return null; } @@ -126,7 +135,8 @@ * @private * @return {boolean} */ -PolyK._PointInTriangle = function (px, py, ax, ay, bx, by, cx, cy) { +PolyK._PointInTriangle = function (px, py, ax, ay, bx, by, cx, cy) +{ var v0x = cx-ax; var v0y = cy-ay; var v1x = bx-ax; @@ -154,6 +164,7 @@ * @private * @return {boolean} */ -PolyK._convex = function (ax, ay, bx, by, cx, cy, sign) { +PolyK._convex = function (ax, ay, bx, by, cx, cy, sign) +{ return ((ay-by)*(cx-bx) + (bx-ax)*(cy-by) >= 0) === sign; }; diff --git a/src/core/utils/index.js b/src/core/utils/index.js index ade9831..bfae7ae 100644 --- a/src/core/utils/index.js +++ b/src/core/utils/index.js @@ -16,7 +16,8 @@ * * @return {number} The next uuid to use. */ - uuid: function () { + uuid: function () + { return ++utils._uid; }, @@ -26,7 +27,8 @@ * @param hex {number} * @return {number[]} An array representing the [R, G, B] of the color. */ - hex2rgb: function (hex, out) { + hex2rgb: function (hex, out) + { out = out || []; out[0] = (hex >> 16 & 0xFF) / 255; @@ -42,7 +44,8 @@ * @param hex {number} * @return {string} The string color. */ - hex2string: function (hex) { + hex2string: function (hex) + { hex = hex.toString(16); hex = '000000'.substr(0, 6 - hex.length) + hex; @@ -55,7 +58,8 @@ * @param rgb {number[]} * @return {number} The color number */ - rgb2hex: function (rgb) { + rgb2hex: function (rgb) + { return ((rgb[0]*255 << 16) + (rgb[1]*255 << 8) + rgb[2]*255); }, @@ -64,8 +68,10 @@ * * @return {boolean} whether they are supported */ - canUseNewCanvasBlendModes: function () { - if (typeof document === 'undefined') { + canUseNewCanvasBlendModes: function () + { + if (typeof document === 'undefined') + { return false; } @@ -93,15 +99,19 @@ * @param number {number} * @return {number} the closest number that is a power of two */ - getNextPowerOfTwo: function (number) { + getNextPowerOfTwo: function (number) + { // see: http://en.wikipedia.org/wiki/Power_of_two#Fast_algorithm_to_check_if_a_positive_number_is_a_power_of_two - if (number > 0 && (number & (number - 1)) === 0) { + if (number > 0 && (number & (number - 1)) === 0) + { return number; } - else { + else + { var result = 1; - while (result < number) { + while (result < number) + { result <<= 1; } @@ -116,7 +126,8 @@ * @param height {number} * @return {boolean} */ - isPowerOfTwo: function (width, height) { + isPowerOfTwo: function (width, height) + { return (width > 0 && (width & (width - 1)) === 0 && height > 0 && (height & (height - 1)) === 0); }, @@ -130,12 +141,15 @@ * @constant * @static */ - sayHello: function (type) { - if (utils._saidHello) { + sayHello: function (type) + { + if (utils._saidHello) + { return; } - if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) { + if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) + { var args = [ '%c %c %c Pixi.js ' + CONST.VERSION + ' - ' + type + ' %c ' + ' %c ' + ' http://www.pixijs.com/ %c %c ♥%c♥%c♥ ', 'background: #ff66a5', @@ -151,7 +165,8 @@ console.log.apply(console, args); //jshint ignore:line } - else if (window.console) { + else if (window.console) + { console.log('Pixi.js ' + CONST.VERSION + ' - ' + type + ' - http://www.pixijs.com/'); //jshint ignore:line } @@ -166,15 +181,19 @@ * @class * @namespace PIXI */ - AjaxRequest: function () { + AjaxRequest: function () + { var activexmodes = ['Msxml2.XMLHTTP.6.0', 'Msxml2.XMLHTTP.3.0', 'Microsoft.XMLHTTP']; //activeX versions to check for in IE - if (window.ActiveXObject) { //Test for support for ActiveXObject in IE first (as XMLHttpRequest in IE7 is broken) - for (var i=0; i= this.textures.length) { + else if (round >= this.textures.length) + { this.gotoAndStop(this.textures.length - 1); - if (this.onComplete) { + if (this.onComplete) + { this.onComplete(); } } @@ -167,10 +182,12 @@ * @static * @param frames {string[]} the array of frames ids the movieclip will use as its texture frames */ -MovieClip.fromFrames = function (frames) { +MovieClip.fromFrames = function (frames) +{ var textures = []; - for (var i = 0; i < frames.length; ++i) { + for (var i = 0; i < frames.length; ++i) + { textures.push(new core.Texture.fromFrame(frames[i])); } @@ -183,10 +200,12 @@ * @static * @param images {string[]} the array of image urls the movieclip will use as its texture frames */ -MovieClip.fromImages = function (images) { +MovieClip.fromImages = function (images) +{ var textures = []; - for (var i = 0; i < images.length; ++i) { + for (var i = 0; i < images.length; ++i) + { textures.push(new core.Texture.fromImage(images[i])); } diff --git a/src/extras/Rope.js b/src/extras/Rope.js index c157ec4..9c87bc0 100644 --- a/src/extras/Rope.js +++ b/src/extras/Rope.js @@ -9,7 +9,8 @@ * @param {Array} points - An array of {Point}. * */ -function Rope(texture, points) { +function Rope(texture, points) +{ Strip.call(this, texture); this.points = points; @@ -31,10 +32,12 @@ * Refreshes * */ -Rope.prototype.refresh = function () { +Rope.prototype.refresh = function () +{ var points = this.points; - if (points.length < 1) { + if (points.length < 1) + { return; } @@ -59,20 +62,23 @@ var total = points.length, point, index, amount; - for (var i = 1; i < total; i++) { + for (var i = 1; i < total; i++) + { point = points[i]; index = i * 4; // time to do some smart drawing! amount = i / (total-1); - if (i%2) { + if (i%2) + { uvs[index] = amount; uvs[index+1] = 0; uvs[index+2] = amount; uvs[index+3] = 1; } - else { + else + { uvs[index] = amount; uvs[index+1] = 0; @@ -95,10 +101,12 @@ * * @private */ -Rope.prototype.updateTransform = function () { +Rope.prototype.updateTransform = function () +{ var points = this.points; - if (points.length < 1) { + if (points.length < 1) + { return; } @@ -113,14 +121,17 @@ var total = points.length, point, index, ratio, perpLength, num; - for (var i = 0; i < total; i++) { + for (var i = 0; i < total; i++) + { point = points[i]; index = i * 4; - if (i < points.length-1) { + if (i < points.length-1) + { nextPoint = points[i+1]; } - else { + else + { nextPoint = point; } @@ -129,7 +140,8 @@ ratio = (1 - (i / (total-1))) * 10; - if (ratio > 1) { + if (ratio > 1) + { ratio = 1; } @@ -157,7 +169,8 @@ * * @param texture {Texture} the texture that will be used */ -Rope.prototype.setTexture = function (texture) { +Rope.prototype.setTexture = function (texture) +{ // stop current texture this.texture = texture; //this.updateFrame = true; diff --git a/src/extras/Strip.js b/src/extras/Strip.js index c5e378f..57691b5 100644 --- a/src/extras/Strip.js +++ b/src/extras/Strip.js @@ -10,7 +10,8 @@ * @param height {number} the height * */ -function Strip(texture) { +function Strip(texture) +{ core.DisplayObjectContainer.call(this); /** @@ -70,9 +71,11 @@ * * @param renderer {WebGLRenderer} */ -Strip.prototype.renderWebGL = function (renderer) { +Strip.prototype.renderWebGL = function (renderer) +{ // if the sprite is not visible or the alpha is 0 then no need to render this element - if (!this.visible || this.alpha <= 0) { + if (!this.visible || this.alpha <= 0) + { return; } @@ -81,7 +84,8 @@ renderer.spriteBatch.stop(); // init! init! - if (!this._vertexBuffer) { + if (!this._vertexBuffer) + { this._initWebGL(renderer); } @@ -96,7 +100,8 @@ //TODO check culling }; -Strip.prototype._initWebGL = function (renderer) { +Strip.prototype._initWebGL = function (renderer) +{ // build the strip! var gl = renderer.gl; @@ -118,7 +123,8 @@ gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this.indices, gl.STATIC_DRAW); }; -Strip.prototype._renderStrip = function (renderer) { +Strip.prototype._renderStrip = function (renderer) +{ var gl = renderer.gl; var projection = renderer.projection, offset = renderer.offset, @@ -137,7 +143,8 @@ gl.uniform2f(shader.offsetVector, -offset.x, -offset.y); gl.uniform1f(shader.alpha, this.worldAlpha); - if (!this.dirty) { + if (!this.dirty) + { gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexBuffer); gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); @@ -150,10 +157,12 @@ gl.activeTexture(gl.TEXTURE0); // check if a texture is dirty.. - if (this.texture.baseTexture._dirty[gl.id]) { + if (this.texture.baseTexture._dirty[gl.id]) + { renderer.updateTexture(this.texture.baseTexture); } - else { + else + { // bind the current texture gl.bindTexture(gl.TEXTURE_2D, this.texture.baseTexture._glTextures[gl.id]); } @@ -163,7 +172,8 @@ } - else { + else + { this.dirty = false; gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexBuffer); @@ -178,10 +188,12 @@ gl.activeTexture(gl.TEXTURE0); // check if a texture is dirty.. - if (this.texture.baseTexture._dirty[gl.id]) { + if (this.texture.baseTexture._dirty[gl.id]) + { renderer.updateTexture(this.texture.baseTexture); } - else { + else + { gl.bindTexture(gl.TEXTURE_2D, this.texture.baseTexture._glTextures[gl.id]); } @@ -203,27 +215,33 @@ * * @param renderer {CanvasRenderer} */ -Strip.prototype.renderCanvas = function (renderer) { +Strip.prototype.renderCanvas = function (renderer) +{ var context = renderer.context; var transform = this.worldTransform; - if (renderer.roundPixels) { + if (renderer.roundPixels) + { context.setTransform(transform.a, transform.b, transform.c, transform.d, transform.tx | 0, transform.ty | 0); } - else { + else + { context.setTransform(transform.a, transform.b, transform.c, transform.d, transform.tx, transform.ty); } - if (this.drawMode === Strip.DrawModes.TRIANGLE_STRIP) { + if (this.drawMode === Strip.DrawModes.TRIANGLE_STRIP) + { this._renderCanvasTriangleStrip(context); } - else { + else + { this._renderCanvasTriangles(context); } }; -Strip.prototype._renderCanvasTriangleStrip = function (context) { +Strip.prototype._renderCanvasTriangleStrip = function (context) +{ // draw triangles!! var vertices = this.vertices; var uvs = this.uvs; @@ -231,14 +249,16 @@ var length = vertices.length / 2; // this.count++; - for (var i = 0; i < length - 2; i++) { + for (var i = 0; i < length - 2; i++) + { // draw some triangles! var index = i * 2; this._renderCanvasDrawTriangle(context, vertices, uvs, index, (index + 2), (index + 4)); } }; -Strip.prototype._renderCanvasTriangles = function (context) { +Strip.prototype._renderCanvasTriangles = function (context) +{ // draw triangles!! var vertices = this.vertices; var uvs = this.uvs; @@ -247,14 +267,16 @@ var length = indices.length; // this.count++; - for (var i = 0; i < length; i += 3) { + for (var i = 0; i < length; i += 3) + { // draw some triangles! var index0 = indices[i] * 2, index1 = indices[i + 1] * 2, index2 = indices[i + 2] * 2; this._renderCanvasDrawTriangle(context, vertices, uvs, index0, index1, index2); } }; -Strip.prototype._renderCanvasDrawTriangle = function (context, vertices, uvs, index0, index1, index2) { +Strip.prototype._renderCanvasDrawTriangle = function (context, vertices, uvs, index0, index1, index2) +{ var textureSource = this.texture.baseTexture.source; var textureWidth = this.texture.width; var textureHeight = this.texture.height; @@ -265,7 +287,8 @@ var u0 = uvs[index0] * textureWidth, u1 = uvs[index1] * textureWidth, u2 = uvs[index2] * textureWidth; var v0 = uvs[index0 + 1] * textureHeight, v1 = uvs[index1 + 1] * textureHeight, v2 = uvs[index2 + 1] * textureHeight; - if (this.canvasPadding > 0) { + if (this.canvasPadding > 0) + { var paddingX = this.canvasPadding / this.worldTransform.a; var paddingY = this.canvasPadding / this.worldTransform.d; var centerX = (x0 + x1 + x2) / 3; @@ -332,7 +355,8 @@ * @param strip {Strip} The Strip to render * @private */ -Strip.prototype.renderStripFlat = function (strip) { +Strip.prototype.renderStripFlat = function (strip) +{ var context = this.context; var vertices = strip.vertices; @@ -340,7 +364,8 @@ // this.count++; context.beginPath(); - for (var i=1; i < length-2; i++) { + for (var i=1; i < length-2; i++) + { // draw some triangles! var index = i*2; @@ -358,7 +383,8 @@ }; /* -Strip.prototype.setTexture = function (texture) { +Strip.prototype.setTexture = function (texture) +{ //TODO SET THE TEXTURES //TODO VISIBILITY @@ -377,7 +403,8 @@ * @private */ -Strip.prototype.onTextureUpdate = function () { +Strip.prototype.onTextureUpdate = function () +{ this.updateFrame = true; }; @@ -387,7 +414,8 @@ * @param matrix {Matrix} the transformation matrix of the sprite * @return {Rectangle} the framing rectangle */ -Strip.prototype.getBounds = function (matrix) { +Strip.prototype.getBounds = function (matrix) +{ var worldTransform = matrix || this.worldTransform; var a = worldTransform.a; @@ -404,7 +432,8 @@ var minY = Infinity; var vertices = this.vertices; - for (var i = 0, n = vertices.length; i < n; i += 2) { + for (var i = 0, n = vertices.length; i < n; i += 2) + { var rawX = vertices[i], rawY = vertices[i + 1]; var x = (a * rawX) + (c * rawY) + tx; var y = (d * rawY) + (b * rawX) + ty; @@ -416,7 +445,8 @@ maxY = y > maxY ? y : maxY; } - if (minX === -Infinity || maxY === Infinity) { + if (minX === -Infinity || maxY === Infinity) + { return core.math.Rectangle.EMPTY; } diff --git a/src/extras/TilingSprite.js b/src/extras/TilingSprite.js index 3ac22df..31da393 100644 --- a/src/extras/TilingSprite.js +++ b/src/extras/TilingSprite.js @@ -10,7 +10,8 @@ * @param width {number} the width of the tiling sprite * @param height {number} the height of the tiling sprite */ -function TilingSprite(texture, width, height) { +function TilingSprite(texture, width, height) +{ core.Sprite.call( this, texture); /** @@ -86,10 +87,12 @@ * @memberof TilingSprite# */ width: { - get: function () { + get: function () + { return this._width; }, - set: function (value) { + set: function (value) + { this._width = value; } }, @@ -101,20 +104,25 @@ * @memberof TilingSprite# */ height: { - get: function () { + get: function () + { return this._height; }, - set: function (value) { + set: function (value) + { this._height = value; } }, texture: { - get: function () { + get: function () + { return this._texture; }, - set: function (value) { - if (this._texture === value) { + set: function (value) + { + if (this._texture === value) + { return; } @@ -130,51 +138,61 @@ * * @param renderer {WebGLRenderer} */ -TilingSprite.prototype.renderWebGL = function (renderer) { - if (!this.visible || this.alpha <= 0) { +TilingSprite.prototype.renderWebGL = function (renderer) +{ + if (!this.visible || this.alpha <= 0) + { return; } var i, j; - if (this._mask) { + if (this._mask) + { renderer.spriteBatch.stop(); renderer.maskManager.pushMask(this.mask, renderer); renderer.spriteBatch.start(); } - if (this._filters) { + if (this._filters) + { renderer.spriteBatch.flush(); renderer.filterManager.pushFilter(this._filterBlock); } - if (!this.tilingTexture || this.refreshTexture) { + if (!this.tilingTexture || this.refreshTexture) + { this.generateTilingTexture(true); - if (this.tilingTexture && this.tilingTexture.needsUpdate) { + if (this.tilingTexture && this.tilingTexture.needsUpdate) + { //TODO - tweaking renderer.updateTexture(this.tilingTexture.baseTexture); this.tilingTexture.needsUpdate = false; // this.tilingTexture._uvs = null; } } - else { + else + { renderer.spriteBatch.renderTilingSprite(this); } // simple render children! - for (i=0,j=this.children.length; i= 0 && index <= this.children.length) { - if (child.parent) { + if (index >= 0 && index <= this.children.length) + { + if (child.parent) + { child.parent.removeChild(child); } @@ -154,7 +173,8 @@ return child; } - else { + else + { throw new Error(child + 'addChildAt: The index '+ index +' supplied is out of bounds ' + this.children.length); } }; @@ -165,15 +185,18 @@ * @param child {DisplayObject} * @param child2 {DisplayObject} */ -DisplayObjectContainer.prototype.swapChildren = function (child, child2) { - if (child === child2) { +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) { + if (index1 < 0 || index2 < 0) + { throw new Error('swapChildren: Both the supplied DisplayObjects must be a child of the caller.'); } @@ -187,10 +210,12 @@ * @param child {DisplayObject} The DisplayObject instance to identify * @return {Number} The index position of the child display object to identify */ -DisplayObjectContainer.prototype.getChildIndex = function (child) { +DisplayObjectContainer.prototype.getChildIndex = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { throw new Error('The supplied DisplayObject must be a child of the caller'); } @@ -203,8 +228,10 @@ * @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 */ -DisplayObjectContainer.prototype.setChildIndex = function (child, index) { - if (index < 0 || index >= this.children.length) { +DisplayObjectContainer.prototype.setChildIndex = function (child, index) +{ + if (index < 0 || index >= this.children.length) + { throw new Error('The supplied index is out of bounds'); } @@ -220,8 +247,10 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child at the given index, if any. */ -DisplayObjectContainer.prototype.getChildAt = function (index) { - if (index < 0 || index >= this.children.length) { +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'); } @@ -234,10 +263,12 @@ * @param child {DisplayObject} The DisplayObject to remove * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChild = function (child) { +DisplayObjectContainer.prototype.removeChild = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { return; } @@ -250,7 +281,8 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChildAt = function (index) { +DisplayObjectContainer.prototype.removeChildAt = function (index) +{ var child = this.getChildAt(index); child.parent = null; @@ -265,24 +297,29 @@ * @param beginIndex {Number} The beginning position. Default value is 0. * @param endIndex {Number} The ending position. Default value is size of the container. */ -DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) { +DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) +{ var begin = beginIndex || 0; var end = typeof endIndex === 'number' ? endIndex : this.children.length; var range = end - begin; - if (range > 0 && range <= end) { + if (range > 0 && range <= end) + { var removed = this.children.splice(begin, range); - for (var i = 0; i < removed.length; ++i) { + for (var i = 0; i < removed.length; ++i) + { removed[i].parent = null; } return removed; } - else if (range === 0 && this.children.length === 0) { + else if (range === 0 && this.children.length === 0) + { return []; } - else { + else + { throw new RangeError('removeChildren: numeric values are outside the acceptable range.'); } }; @@ -291,7 +328,8 @@ * Generates and updates the cached sprite for this object. * */ -DisplayObjectContainer.prototype.updateCachedSprite = function () { +DisplayObjectContainer.prototype.updateCachedSprite = function () +{ this._generateCachedSprite(); }; @@ -304,7 +342,8 @@ * @param renderer {CanvasRenderer|WebGLRenderer} The renderer used to generate the texture. * @return {Texture} a texture of the graphics object */ -DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) { +DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) +{ var bounds = this.getLocalBounds(); var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0, renderer, scaleMode, resolution); @@ -322,18 +361,22 @@ * * @private */ -DisplayObjectContainer.prototype.updateTransform = function () { - if (!this.visible) { +DisplayObjectContainer.prototype.updateTransform = function () +{ + if (!this.visible) + { return; } this.displayObjectUpdateTransform(); - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { return; } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } }; @@ -346,8 +389,10 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getBounds = function () { - if (this.children.length === 0) { +DisplayObjectContainer.prototype.getBounds = function () +{ + if (this.children.length === 0) + { return math.Rectangle.EMPTY; } @@ -365,10 +410,12 @@ var childVisible = false; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -386,7 +433,8 @@ maxY = maxY > childMaxY ? maxY : childMaxY; } - if (!childVisible) { + if (!childVisible) + { return math.Rectangle.EMPTY; } @@ -407,12 +455,14 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getLocalBounds = function () { +DisplayObjectContainer.prototype.getLocalBounds = function () +{ var matrixCache = this.worldTransform; this.worldTransform = math.Matrix.IDENTITY; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } @@ -428,13 +478,16 @@ * * @param renderer {WebGLRenderer} The renderer */ -DisplayObjectContainer.prototype.renderWebGL = function (renderer) { +DisplayObjectContainer.prototype.renderWebGL = function (renderer) +{ // if the object is not visible or the alpha is 0 then no need to render this element - if (!this.visible || this.alpha <= 0) { + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } @@ -442,14 +495,17 @@ var i, j; // do a quick check to see if this element has a mask or a filter. - if (this._mask || this._filters) { + if (this._mask || this._filters) + { // push filter first as we need to ensure the stencil buffer is correct for any masking - if (this._filters) { + if (this._filters) + { renderer.spriteBatch.flush(); renderer.filterManager.pushFilter(this._filterBlock); } - if (this._mask) { + if (this._mask) + { renderer.spriteBatch.stop(); renderer.maskManager.pushMask(this.mask, renderer); renderer.spriteBatch.start(); @@ -459,36 +515,42 @@ this._renderWebGL(renderer); // now loop through the children and make sure they get rendered - for (i = 0, j = this.children.length; i < j; i++) { + for (i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderWebGL(renderer); } // time to stop the sprite batch as either a mask element or a filter draw will happen next renderer.spriteBatch.stop(); - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(this._mask, renderer); } - if (this._filters) { + if (this._filters) + { renderer.filterManager.popFilter(); } renderer.spriteBatch.start(); } - else { + else + { this._renderWebGL(renderer); // simple render children! - for (i = 0, j = this.children.length; i < j; ++i) { + for (i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderWebGL(renderer); } } }; -DisplayObjectContainer.prototype._renderWebGL = function (renderer) { +DisplayObjectContainer.prototype._renderWebGL = function (renderer) +{ // this is where content itself gets renderd.. @@ -499,25 +561,31 @@ * * @param renderer {CanvasRenderer} The renderer */ -DisplayObjectContainer.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0) { +DisplayObjectContainer.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -528,13 +596,16 @@ * @param renderer {WebGLRenderer|CanvasRenderer} The renderer * @private */ -DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) { +DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) +{ this._cachedSprite.worldAlpha = this.worldAlpha; - if (renderer.gl) { + if (renderer.gl) + { this._cachedSprite.renderWebGL(renderer); } - else { + else + { this._cachedSprite.renderCanvas(renderer); } }; @@ -544,10 +615,12 @@ * * @private */ -DisplayObjectContainer.prototype._generateCachedSprite = function () { +DisplayObjectContainer.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { // TODO - RenderTexture now *requires* a renderer instance, so this is like broken // because `renderer` isn't actually in scope here :P var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0); @@ -555,7 +628,8 @@ this._cachedSprite = new Sprite(renderTexture); this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.texture.resize(bounds.width | 0, bounds.height | 0); } @@ -580,8 +654,10 @@ * * @private */ -DisplayObjectContainer.prototype._destroyCachedSprite = function () { - if (!this._cachedSprite) { +DisplayObjectContainer.prototype._destroyCachedSprite = function () +{ + if (!this._cachedSprite) + { return; } diff --git a/src/core/display/Sprite.js b/src/core/display/Sprite.js index 707da24..5862aef 100644 --- a/src/core/display/Sprite.js +++ b/src/core/display/Sprite.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param texture {Texture} The texture for this sprite */ -function Sprite(texture) { +function Sprite(texture) +{ DisplayObjectContainer.call(this); /** @@ -85,12 +86,14 @@ this.texture = texture || Texture.EMPTY; } -Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) { +Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) +{ DisplayObjectContainer.prototype.destroy.call(this); this.anchor = null; - if (destroyTexture) { + if (destroyTexture) + { this._texture.destroy(destroyBaseTexture); } @@ -111,10 +114,12 @@ * @memberof Sprite# */ width: { - get: function () { + get: function () + { return this.scale.x * this.texture.frame.width; }, - set: function (value) { + set: function (value) + { this.scale.x = value / this.texture.frame.width; this._width = value; } @@ -127,10 +132,12 @@ * @memberof Sprite# */ height: { - get: function () { + get: function () + { return this.scale.y * this.texture.frame.height; }, - set: function (value) { + set: function (value) + { this.scale.y = value / this.texture.frame.height; this._height = value; } @@ -143,23 +150,29 @@ * @memberof Sprite# */ texture: { - get: function () { + get: function () + { return this._texture; }, - set: function (value) { - if (this._texture === value) { + set: function (value) + { + if (this._texture === value) + { return; } this._texture = value; this.cachedTint = 0xFFFFFF; - if (value) { + if (value) + { // wait for the texture to load - if (value.baseTexture.hasLoaded) { + if (value.baseTexture.hasLoaded) + { this._onTextureUpdate(); } - else { + else + { value.once('update', this._onTextureUpdate.bind(this)); } } @@ -172,18 +185,22 @@ * * @private */ -Sprite.prototype._onTextureUpdate = function () { +Sprite.prototype._onTextureUpdate = function () +{ // so if _width is 0 then width was not set.. - if (this._width) { + if (this._width) + { this.scale.x = this._width / this.texture.frame.width; } - if (this._height) { + if (this._height) + { this.scale.y = this._height / this.texture.frame.height; } }; -Sprite.prototype._renderWebGL = function (renderer) { +Sprite.prototype._renderWebGL = function (renderer) +{ // this is where content gets renderd.. // watch this space for a little render state manager.. @@ -197,7 +214,8 @@ * @param matrix {Matrix} the transformation matrix of the sprite * @return {Rectangle} the framing rectangle */ -Sprite.prototype.getBounds = function (matrix) { +Sprite.prototype.getBounds = function (matrix) +{ var width = this.texture.frame.width; var height = this.texture.frame.height; @@ -224,11 +242,13 @@ if(b === 0 && c === 0) { // scale may be negative! - if (a < 0) { + if (a < 0) + { a *= -1; } - if (d < 0) { + if (d < 0) + { d *= -1; } @@ -293,28 +313,34 @@ * * @param renderer {CanvasRenderer} The renderer */ -Sprite.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) { +Sprite.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) + { return; } - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; renderer.context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } // Ignore null sources - if (this.texture.valid) { + if (this.texture.valid) + { var resolution = this.texture.baseTexture.resolution / renderer.resolution; renderer.context.globalAlpha = this.worldAlpha; // If smoothingEnabled is supported and we need to change the smoothing property for this texture - if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) { + if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) + { renderer.scaleMode = this.texture.baseTexture.scaleMode; renderer.context[renderer.smoothProperty] = (renderer.scaleMode === CONST.scaleModes.LINEAR); } @@ -324,7 +350,8 @@ var dy = (this.texture.trim ? this.texture.trim.y : 0) - (this.anchor.y * this.texture.trim.height); // Allow for pixel rounding - if (renderer.roundPixels) { + if (renderer.roundPixels) + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -337,7 +364,8 @@ dx = dx | 0; dy = dy | 0; } - else { + else + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -348,8 +376,10 @@ ); } - if (this.tint !== 0xFFFFFF) { - if (this.cachedTint !== this.tint) { + if (this.tint !== 0xFFFFFF) + { + if (this.cachedTint !== this.tint) + { this.cachedTint = this.tint; // TODO clean up caching - how to clean up the caches? @@ -368,7 +398,8 @@ this.texture.crop.height / resolution ); } - else { + else + { renderer.context.drawImage( this.texture.baseTexture.source, this.texture.crop.x, @@ -383,11 +414,13 @@ } } - for (var i = 0, j = this.children.length; i < j; i++) { + for (var i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -402,10 +435,12 @@ * @param frameId {String} The frame Id of the texture in the cache * @return {Sprite} A new Sprite using a texture from the texture cache matching the frameId */ -Sprite.fromFrame = function (frameId) { +Sprite.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache' + this); } @@ -420,6 +455,7 @@ * @param imageId {String} The image url of the texture * @return {Sprite} A new Sprite using a texture from the texture cache matching the image id */ -Sprite.fromImage = function (imageId, crossorigin, scaleMode) { +Sprite.fromImage = function (imageId, crossorigin, scaleMode) +{ return new Sprite(Texture.fromImage(imageId, crossorigin, scaleMode)); }; diff --git a/src/core/display/SpriteBatch.js b/src/core/display/SpriteBatch.js index 3187777..c196fef 100644 --- a/src/core/display/SpriteBatch.js +++ b/src/core/display/SpriteBatch.js @@ -12,7 +12,8 @@ * ```js * var container = new SpriteBatch(); * - * for(var i = 0; i < 100; ++i) { + * for(var i = 0; i < 100; ++i) + * { * var sprite = new PIXI.Sprite.fromImage("myImage.png"); * container.addChild(sprite); * } @@ -25,7 +26,8 @@ */ //TODO RENAME to PARTICLE CONTAINER? -function SpriteBatch() { +function SpriteBatch() +{ DisplayObjectContainer.call(this); } @@ -38,7 +40,8 @@ * * @private */ -SpriteBatch.prototype.updateTransform = function () { +SpriteBatch.prototype.updateTransform = function () +{ // TODO don't need to! this.displayObjectUpdateTransform(); // PIXI.DisplayObjectContainer.prototype.updateTransform.call( this ); @@ -50,8 +53,10 @@ * @param renderer {WebGLRenderer} The webgl renderer * @private */ -SpriteBatch.prototype.renderWebGL = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderWebGL = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -71,8 +76,10 @@ * @param renderer {CanvasRenderer} The canvas renderer * @private */ -SpriteBatch.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -84,10 +91,12 @@ this.displayObjectUpdateTransform(); - for (var i = 0; i < this.children.length; ++i) { + for (var i = 0; i < this.children.length; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -95,9 +104,11 @@ context.globalAlpha = this.worldAlpha * child.alpha; - if (child.rotation % (Math.PI * 2) === 0) { + if (child.rotation % (Math.PI * 2) === 0) + { // this is the fastest way to optimise! - if rotation is 0 then we can avoid any kind of setTransform call - if (isRotated) { + if (isRotated) + { context.setTransform( transform.a, transform.b, @@ -122,8 +133,10 @@ frame.height * child.scale.y ); } - else { - if (!isRotated) { + else + { + if (!isRotated) + { isRotated = true; } @@ -131,7 +144,8 @@ var childTransform = child.worldTransform; - if (renderer.roundPixels) { + if (renderer.roundPixels) + { context.setTransform( childTransform.a, childTransform.b, @@ -141,7 +155,8 @@ childTransform.ty | 0 ); } - else { + else + { context.setTransform( childTransform.a, childTransform.b, diff --git a/src/core/index.js b/src/core/index.js index 3954b6f..eb4a82b 100644 --- a/src/core/index.js +++ b/src/core/index.js @@ -58,11 +58,13 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRenderer: function (width, height, options, noWebGL) { + autoDetectRenderer: function (width, height, options, noWebGL) + { width = width || 800; height = height || 600; - if (!noWebGL && require('webgl-enabled')()) { + if (!noWebGL && require('webgl-enabled')()) + { return new core.WebGLRenderer(width, height, options); } @@ -87,7 +89,8 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRecommendedRenderer: function (width, height, options) { + autoDetectRecommendedRenderer: function (width, height, options) + { var isAndroid = /Android/i.test(navigator.userAgent); return core.autoDetectRenderer(width, height, options, isAndroid); diff --git a/src/core/math/Matrix.js b/src/core/math/Matrix.js index c2f87e2..2ff4848 100644 --- a/src/core/math/Matrix.js +++ b/src/core/math/Matrix.js @@ -10,7 +10,8 @@ * @class * @namespace PIXI */ -function Matrix() { +function Matrix() +{ /** * @member {number} * @default 1 @@ -63,7 +64,8 @@ * * @param array {number[]} The array that the matrix will be populated from. */ -Matrix.prototype.fromArray = function (array) { +Matrix.prototype.fromArray = function (array) +{ this.a = array[0]; this.b = array[1]; this.c = array[3]; @@ -78,14 +80,17 @@ * @param transpose {boolean} Whether we need to transpose the matrix or not * @return {number[]} the newly created array which contains the matrix */ -Matrix.prototype.toArray = function (transpose) { - if (!this.array) { +Matrix.prototype.toArray = function (transpose) +{ + if (!this.array) + { this.array = new Float32Array(9); } var array = this.array; - if (transpose) { + if (transpose) + { array[0] = this.a; array[1] = this.b; array[2] = 0; @@ -96,7 +101,8 @@ array[7] = this.ty; array[8] = 1; } - else { + else + { array[0] = this.a; array[1] = this.c; array[2] = this.tx; @@ -119,7 +125,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, transformed through this matrix */ -Matrix.prototype.apply = function (pos, newPos) { +Matrix.prototype.apply = function (pos, newPos) +{ newPos = newPos || new Point(); newPos.x = this.a * pos.x + this.c * pos.y + this.tx; @@ -136,7 +143,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, inverse-transformed through this matrix */ -Matrix.prototype.applyInverse = function (pos, newPos) { +Matrix.prototype.applyInverse = function (pos, newPos) +{ newPos = newPos || new Point(); var id = 1 / (this.a * this.d + this.c * -this.b); @@ -154,7 +162,8 @@ * @param {number} y * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.translate = function (x, y) { +Matrix.prototype.translate = function (x, y) +{ this.tx += x; this.ty += y; @@ -168,7 +177,8 @@ * @param {number} y The amount to scale vertically * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.scale = function (x, y) { +Matrix.prototype.scale = function (x, y) +{ this.a *= x; this.d *= y; this.c *= x; @@ -186,7 +196,8 @@ * @param {number} angle - The angle in radians. * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.rotate = function (angle) { +Matrix.prototype.rotate = function (angle) +{ var cos = Math.cos( angle ); var sin = Math.sin( angle ); @@ -210,7 +221,8 @@ * @param {Matrix} matrix * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.append = function (matrix) { +Matrix.prototype.append = function (matrix) +{ var a1 = this.a; var b1 = this.b; var c1 = this.c; @@ -232,7 +244,8 @@ * * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.identity = function () { +Matrix.prototype.identity = function () +{ this.a = 1; this.b = 0; this.c = 0; diff --git a/src/core/math/Point.js b/src/core/math/Point.js index 7565b2d..632f346 100644 --- a/src/core/math/Point.js +++ b/src/core/math/Point.js @@ -7,7 +7,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -function Point(x, y) { +function Point(x, y) +{ /** * @member {number} * @default 0 @@ -29,7 +30,8 @@ * * @return {Point} a copy of the point */ -Point.prototype.clone = function () { +Point.prototype.clone = function () +{ return new Point(this.x, this.y); }; @@ -40,7 +42,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -Point.prototype.set = function (x, y) { +Point.prototype.set = function (x, y) +{ this.x = x || 0; this.y = y || ( (y !== 0) ? this.x : 0 ) ; }; diff --git a/src/core/math/shapes/Circle.js b/src/core/math/shapes/Circle.js index 69cfdc9..4d76efc 100644 --- a/src/core/math/shapes/Circle.js +++ b/src/core/math/shapes/Circle.js @@ -10,7 +10,8 @@ * @param y {number} The Y coordinate of the center of this circle * @param radius {number} The radius of the circle */ -function Circle(x, y, radius) { +function Circle(x, y, radius) +{ /** * @member {number} * @default 0 @@ -46,7 +47,8 @@ * @method clone * @return {Circle} a copy of the Circle */ -Circle.prototype.clone = function () { +Circle.prototype.clone = function () +{ return new Circle(this.x, this.y, this.radius); }; @@ -58,8 +60,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Circle */ -Circle.prototype.contains = function (x, y) { - if (this.radius <= 0) { +Circle.prototype.contains = function (x, y) +{ + if (this.radius <= 0) + { return false; } @@ -79,6 +83,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Circle.prototype.getBounds = function () { +Circle.prototype.getBounds = function () +{ return new Rectangle(this.x - this.radius, this.y - this.radius, this.radius * 2, this.radius * 2); }; diff --git a/src/core/math/shapes/Ellipse.js b/src/core/math/shapes/Ellipse.js index 4f2d066..fefd01a 100644 --- a/src/core/math/shapes/Ellipse.js +++ b/src/core/math/shapes/Ellipse.js @@ -11,7 +11,8 @@ * @param width {number} The half width of this ellipse * @param height {number} The half height of this ellipse */ -function Ellipse(x, y, width, height) { +function Ellipse(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -53,7 +54,8 @@ * @method clone * @return {Ellipse} a copy of the ellipse */ -Ellipse.prototype.clone = function () { +Ellipse.prototype.clone = function () +{ return new Ellipse(this.x, this.y, this.width, this.height); }; @@ -65,8 +67,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coords are within this ellipse */ -Ellipse.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Ellipse.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } @@ -86,6 +90,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Ellipse.prototype.getBounds = function () { +Ellipse.prototype.getBounds = function () +{ return new Rectangle(this.x - this.width, this.y - this.height, this.width, this.height); }; diff --git a/src/core/math/shapes/Polygon.js b/src/core/math/shapes/Polygon.js index ae89148..fea6d37 100644 --- a/src/core/math/shapes/Polygon.js +++ b/src/core/math/shapes/Polygon.js @@ -10,16 +10,20 @@ * arguments passed can be flat x,y values e.g. `new Polygon(x,y, x,y, x,y, ...)` where `x` and `y` are * Numbers. */ -function Polygon(points) { +function Polygon(points) +{ //if points isn't an array, use arguments as the array - if (!(points instanceof Array)) { + if (!(points instanceof Array)) + { points = Array.prototype.slice.call(arguments); } //if this is a flat array of numbers, convert it to points - if (points[0] instanceof Point) { + if (points[0] instanceof Point) + { var p = []; - for (var i = 0, il = points.length; i < il; i++) { + for (var i = 0, il = points.length; i < il; i++) + { p.push(points[i].x, points[i].y); } @@ -51,7 +55,8 @@ * * @return {Polygon} a copy of the polygon */ -Polygon.prototype.clone = function () { +Polygon.prototype.clone = function () +{ return new Polygon(this.points.slice()); }; @@ -62,19 +67,22 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this polygon */ -Polygon.prototype.contains = function (x, y) { +Polygon.prototype.contains = function (x, y) +{ var inside = false; // use some raycasting to test hits // https://github.com/substack/point-in-polygon/blob/master/index.js var length = this.points.length / 2; - for (var i = 0, j = length - 1; i < length; j = i++) { + for (var i = 0, j = length - 1; i < length; j = i++) + { var xi = this.points[i * 2], yi = this.points[i * 2 + 1], xj = this.points[j * 2], yj = this.points[j * 2 + 1], intersect = ((yi > y) !== (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi); - if (intersect) { + if (intersect) + { inside = !inside; } } diff --git a/src/core/math/shapes/Rectangle.js b/src/core/math/shapes/Rectangle.js index 16ac62a..4008b68 100644 --- a/src/core/math/shapes/Rectangle.js +++ b/src/core/math/shapes/Rectangle.js @@ -10,7 +10,8 @@ * @param width {number} The overall width of this rectangle * @param height {number} The overall height of this rectangle */ -function Rectangle(x, y, width, height) { +function Rectangle(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -60,7 +61,8 @@ * * @return {Rectangle} a copy of the rectangle */ -Rectangle.prototype.clone = function () { +Rectangle.prototype.clone = function () +{ return new Rectangle(this.x, this.y, this.width, this.height); }; @@ -71,13 +73,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rectangle */ -Rectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Rectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/math/shapes/RoundedRectangle.js b/src/core/math/shapes/RoundedRectangle.js index 27d286e..7bf6411 100644 --- a/src/core/math/shapes/RoundedRectangle.js +++ b/src/core/math/shapes/RoundedRectangle.js @@ -11,7 +11,8 @@ * @param height {number} The overall height of this rounded rectangle * @param radius {number} Controls the radius of the rounded corners */ -function RoundedRectangle(x, y, width, height, radius) { +function RoundedRectangle(x, y, width, height, radius) +{ /** * @member {number} * @default 0 @@ -58,7 +59,8 @@ * * @return {RoundedRectangle} a copy of the rounded rectangle */ -RoundedRectangle.prototype.clone = function () { +RoundedRectangle.prototype.clone = function () +{ return new RoundedRectangle(this.x, this.y, this.width, this.height, this.radius); }; @@ -69,13 +71,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rounded Rectangle */ -RoundedRectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +RoundedRectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/primitives/Graphics.js b/src/core/primitives/Graphics.js index 261c534..e902d2a 100644 --- a/src/core/primitives/Graphics.js +++ b/src/core/primitives/Graphics.js @@ -16,7 +16,8 @@ * @extends DisplayObjectContainer * @namespace PIXI */ -function Graphics() { +function Graphics() +{ DisplayObjectContainer.call(this); this.renderable = true; @@ -154,16 +155,20 @@ * @private */ cacheAsBitmap: { - get: function () { + get: function () + { return this._cacheAsBitmap; }, - set: function (value) { + set: function (value) + { this._cacheAsBitmap = value; - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._generateCachedSprite(); } - else { + else + { this.destroyCachedSprite(); this.dirty = true; } @@ -176,7 +181,8 @@ * * @return {Graphics} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ var clone = new Graphics(); clone.renderable = this.renderable; @@ -192,7 +198,8 @@ clone.cachedSpriteDirty = this.cachedSpriteDirty; // copy graphics data - for (var i = 0; i < this.graphicsData.length; ++i) { + for (var i = 0; i < this.graphicsData.length; ++i) + { clone.graphicsData.push(this.graphicsData.clone()); } @@ -211,17 +218,21 @@ * @param alpha {number} alpha of the line to draw, will update the objects stored style * @return {Graphics} */ -Graphics.prototype.lineStyle = function (lineWidth, color, alpha) { +Graphics.prototype.lineStyle = function (lineWidth, color, alpha) +{ this.lineWidth = lineWidth || 0; this.lineColor = color || 0; this.lineAlpha = (arguments.length < 3) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length) + { // halfway through a line? start a new one! this.drawShape( new math.Polygon( this.currentPath.shape.points.slice(-2) )); } - else { + else + { // otherwise its empty so lets just set the line properties this.currentPath.lineWidth = this.lineWidth; this.currentPath.lineColor = this.lineColor; @@ -239,7 +250,8 @@ * @param y {number} the Y coordinate to move to * @return {Graphics} */ -Graphics.prototype.moveTo = function (x, y) { +Graphics.prototype.moveTo = function (x, y) +{ this.drawShape(new math.Polygon([x,y])); return this; @@ -253,7 +265,8 @@ * @param y {number} the Y coordinate to draw to * @return {Graphics} */ -Graphics.prototype.lineTo = function (x, y) { +Graphics.prototype.lineTo = function (x, y) +{ this.currentPath.shape.points.push(x, y); this.dirty = true; @@ -270,13 +283,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -285,7 +302,8 @@ n = 20, points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { this.moveTo(0, 0); } @@ -293,7 +311,8 @@ var fromY = points[points.length-1]; var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; xa = fromX + ( (cpX - fromX) * j ); @@ -319,13 +338,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -342,7 +365,8 @@ var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; dt = (1 - j); @@ -373,13 +397,17 @@ * @param radius {number} The radius of the arc * @return {Graphics} */ -Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points.push(x1, y1); } } - else { + else + { this.moveTo(x1, y1); } @@ -392,12 +420,15 @@ b2 = x2 - x1, mm = Math.abs(a1 * b2 - b1 * a2); - if (mm < 1.0e-8 || radius === 0) { - if (points[points.length-2] !== x1 || points[points.length-1] !== y1) { + if (mm < 1.0e-8 || radius === 0) + { + if (points[points.length-2] !== x1 || points[points.length-1] !== y1) + { points.push(x1, y1); } } - else { + else + { var dd = a1 * a1 + b1 * b1, cc = a2 * a2 + b2 * b2, tt = a1 * a2 + b1 * b2, @@ -433,42 +464,51 @@ * @param anticlockwise {boolean} Optional. Specifies whether the drawing should be counterclockwise or clockwise. False is default, and indicates clockwise, while true indicates counter-clockwise. * @return {Graphics} */ -Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) { +Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) +{ var startX = cx + Math.cos(startAngle) * radius; var startY = cy + Math.sin(startAngle) * radius; var points; // TODO - This if-else makes no sense. It uses currentPath in the else where it doesn't exist... - if (this.currentPath) { + if (this.currentPath) + { points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { points.push(startX, startY); } - else if (points[points.length-2] !== startX || points[points.length-1] !== startY) { + else if (points[points.length-2] !== startX || points[points.length-1] !== startY) + { points.push(startX, startY); } } - else { + else + { this.moveTo(startX, startY); points = this.currentPath.shape.points; } - if (startAngle === endAngle) { + if (startAngle === endAngle) + { return this; } - if (!anticlockwise && endAngle <= startAngle) { + if (!anticlockwise && endAngle <= startAngle) + { endAngle += Math.PI * 2; } - else if (anticlockwise && startAngle <= endAngle) { + else if (anticlockwise && startAngle <= endAngle) + { startAngle += Math.PI * 2; } var sweep = anticlockwise ? (startAngle - endAngle) *-1 : (endAngle - startAngle); var segs = (Math.abs(sweep)/ (Math.PI * 2)) * 40; - if (sweep === 0) { + if (sweep === 0) + { return this; } @@ -482,7 +522,8 @@ var remainder = ( segMinus % 1 ) / segMinus; - for (var i = 0; i <= segMinus; ++i) { + for (var i = 0; i <= segMinus; ++i) + { var real = i + remainder * i; var angle = ((theta) + startAngle + (theta2 * real)); @@ -506,13 +547,16 @@ * @param alpha {number} the alpha of the fill * @return {Graphics} */ -Graphics.prototype.beginFill = function (color, alpha) { +Graphics.prototype.beginFill = function (color, alpha) +{ this.filling = true; this.fillColor = color || 0; this.fillAlpha = (alpha === undefined) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length <= 2) + { this.currentPath.fill = this.filling; this.currentPath.fillColor = this.fillColor; this.currentPath.fillAlpha = this.fillAlpha; @@ -526,7 +570,8 @@ * * @return {Graphics} */ -Graphics.prototype.endFill = function () { +Graphics.prototype.endFill = function () +{ this.filling = false; this.fillColor = null; this.fillAlpha = 1; @@ -542,7 +587,8 @@ * @param height {number} The height of the rectangle * @return {Graphics} */ -Graphics.prototype.drawRect = function ( x, y, width, height ) { +Graphics.prototype.drawRect = function ( x, y, width, height ) +{ this.drawShape(new math.Rectangle(x,y, width, height)); return this; @@ -556,7 +602,8 @@ * @param height {number} The height of the rectangle * @param radius {number} Radius of the rectangle corners */ -Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) { +Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) +{ this.drawShape(new math.RoundedRectangle(x, y, width, height, radius)); return this; @@ -570,7 +617,8 @@ * @param radius {number} The radius of the circle * @return {Graphics} */ -Graphics.prototype.drawCircle = function (x, y, radius) { +Graphics.prototype.drawCircle = function (x, y, radius) +{ this.drawShape(new math.Circle(x,y, radius)); return this; @@ -585,7 +633,8 @@ * @param height {number} The half height of the ellipse * @return {Graphics} */ -Graphics.prototype.drawEllipse = function (x, y, width, height) { +Graphics.prototype.drawEllipse = function (x, y, width, height) +{ this.drawShape(new math.Ellipse(x, y, width, height)); return this; @@ -597,8 +646,10 @@ * @param path {Array} The path data used to construct the polygon. * @return {Graphics} */ -Graphics.prototype.drawPolygon = function (path) { - if (!(path instanceof Array)) { +Graphics.prototype.drawPolygon = function (path) +{ + if (!(path instanceof Array)) + { path = Array.prototype.slice.call(arguments); } @@ -612,7 +663,8 @@ * * @return {Graphics} */ -Graphics.prototype.clear = function () { +Graphics.prototype.clear = function () +{ this.lineWidth = 0; this.filling = false; @@ -631,7 +683,8 @@ * @param scaleMode {number} Should be one of the scaleMode consts * @return {Texture} a texture of the graphics object */ -Graphics.prototype.generateTexture = function (resolution, scaleMode) { +Graphics.prototype.generateTexture = function (resolution, scaleMode) +{ resolution = resolution || 1; var bounds = this.getBounds(); @@ -655,17 +708,21 @@ * * @param renderer {WebGLRenderer} */ -Graphics.prototype._renderWebGL = function (renderer) { +Graphics.prototype._renderWebGL = function (renderer) +{ // if the sprite is not visible or the alpha is 0 then no need to render this element - if (this.isMask === true) { + if (this.isMask === true) + { return; } // this code may still be needed so leaving for now.. - // + // /* - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture on the gpu too! @@ -681,17 +738,24 @@ return; } - */ - - // check if the webgl graphic needs to be updated - if (this.glDirty) { - this.dirty = true; - this.glDirty = false; - } + else */ - renderer.setObjectRendererer(renderer.graphicsRenderer); - renderer.graphicsRenderer.render(this); + renderer.spriteBatch.stop(); + renderer.blendModeManager.setBlendMode(this.blendMode); + // check blend mode + renderer.blendModeManager.setBlendMode( this.blendMode ); + + // check if the webgl graphic needs to be updated + if (this.glDirty) + { + this.dirty = true; + this.glDirty = false; + } + + WebGLGraphics.renderGraphics(this, renderer); + + renderer.spriteBatch.start(); }; /** @@ -700,14 +764,18 @@ * @param renderer {CanvasRenderer} * @private */ -Graphics.prototype.renderCanvas = function (renderer) { +Graphics.prototype.renderCanvas = function (renderer) +{ // 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.isMask === true) { + if (!this.visible || this.alpha <= 0 || this.isMask === true) + { return; } - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture @@ -723,16 +791,19 @@ return; } - else { + else + { var context = renderer.context; var transform = this.worldTransform; - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } @@ -748,11 +819,13 @@ CanvasGraphics.renderGraphics(this, context); - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } } @@ -763,13 +836,16 @@ * * @return {Rectangle} the rectangular bounding area */ -Graphics.prototype.getBounds = function (matrix) { +Graphics.prototype.getBounds = function (matrix) +{ // return an empty object if the item is a mask! - if (this.isMask) { + if (this.isMask) + { return math.Rectangle.EMPTY; } - if (this.dirty) { + if (this.dirty) + { this.updateLocalBounds(); this.glDirty = true; @@ -841,23 +917,27 @@ * Update the bounds of the object * */ -Graphics.prototype.updateLocalBounds = function () { +Graphics.prototype.updateLocalBounds = function () +{ var minX = Infinity; var maxX = -Infinity; var minY = Infinity; var maxY = -Infinity; - if (this.graphicsData.length) { + if (this.graphicsData.length) + { var shape, points, x, y, w, h; - for (var i = 0; i < this.graphicsData.length; i++) { + for (var i = 0; i < this.graphicsData.length; i++) + { var data = this.graphicsData[i]; var type = data.type; var lineWidth = data.lineWidth; shape = data.shape; - if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) { + if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) + { x = shape.x - lineWidth/2; y = shape.y - lineWidth/2; w = shape.width + lineWidth; @@ -869,7 +949,8 @@ minY = y < minY ? y : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.CIRC) { + else if (type === CONST.SHAPES.CIRC) + { x = shape.x; y = shape.y; w = shape.radius + lineWidth/2; @@ -881,7 +962,8 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.ELIP) { + else if (type === CONST.SHAPES.ELIP) + { x = shape.x; y = shape.y; w = shape.width + lineWidth/2; @@ -893,11 +975,13 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else { + else + { // POLY points = shape.points; - for (var j = 0; j < points.length; j += 2) { + for (var j = 0; j < points.length; j += 2) + { x = points[j]; y = points[j+1]; @@ -910,7 +994,8 @@ } } } - else { + else + { minX = 0; maxX = 0; minY = 0; @@ -931,10 +1016,12 @@ * * @private */ -Graphics.prototype._generateCachedSprite = function () { +Graphics.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { var canvasBuffer = new CanvasBuffer(bounds.width, bounds.height); var texture = Texture.fromCanvas(canvasBuffer.canvas); @@ -943,7 +1030,8 @@ this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.buffer.resize(bounds.width, bounds.height); } @@ -968,7 +1056,8 @@ * * @private */ -Graphics.prototype.updateCachedSpriteTexture = function () { +Graphics.prototype.updateCachedSpriteTexture = function () +{ var cachedSprite = this._cachedSprite; var texture = cachedSprite.texture; var canvas = cachedSprite.buffer.canvas; @@ -989,7 +1078,8 @@ * Destroys a previous cached sprite. * */ -Graphics.prototype.destroyCachedSprite = function () { +Graphics.prototype.destroyCachedSprite = function () +{ this._cachedSprite.texture.destroy(true); // let the gc collect the unused sprite @@ -1003,10 +1093,13 @@ * @param {Circle|Rectangle|Ellipse|Line|Polygon} shape The Shape object to draw. * @return {GraphicsData} The generated GraphicsData object. */ -Graphics.prototype.drawShape = function (shape) { - if (this.currentPath) { +Graphics.prototype.drawShape = function (shape) +{ + if (this.currentPath) + { // check current path! - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath.shape.points.length <= 2) + { this.graphicsData.pop(); } } @@ -1017,7 +1110,8 @@ this.graphicsData.push(data); - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { data.shape.closed = this.filling; this.currentPath = data; } diff --git a/src/core/primitives/GraphicsData.js b/src/core/primitives/GraphicsData.js index 99decbe..788f6f2 100644 --- a/src/core/primitives/GraphicsData.js +++ b/src/core/primitives/GraphicsData.js @@ -4,7 +4,8 @@ * @class * @namespace PIXI */ -function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) { +function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) +{ this.lineWidth = lineWidth; this.lineColor = lineColor; this.lineAlpha = lineAlpha; @@ -27,7 +28,8 @@ * * @return {GraphicsData} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ return new GraphicsData( this.lineWidth, this.lineColor, diff --git a/src/core/renderers/canvas/CanvasRenderer.js b/src/core/renderers/canvas/CanvasRenderer.js index 15a0978..7aebd44 100644 --- a/src/core/renderers/canvas/CanvasRenderer.js +++ b/src/core/renderers/canvas/CanvasRenderer.js @@ -17,17 +17,22 @@ * @param [options.resolution=1] {number} the resolution of the renderer retina would be 2 * @param [options.clearBeforeRender=true] {boolean} This sets if the CanvasRenderer will clear the canvas or not before the new render pass. */ -function CanvasRenderer(width, height, options) { +function CanvasRenderer(width, height, options) +{ utils.sayHello('Canvas'); - if (options) { - for (var i in CONST.defaultRenderOptions) { - if (typeof options[i] === 'undefined') { + if (options) + { + for (var i in CONST.defaultRenderOptions) + { + if (typeof options[i] === 'undefined') + { options[i] = CONST.defaultRenderOptions[i]; } } } - else { + else + { options = CONST.defaultRenderOptions; } @@ -156,19 +161,24 @@ this.smoothProperty = null; - if (this.context.imageSmoothingEnabled) { + if (this.context.imageSmoothingEnabled) + { this.smoothProperty = 'imageSmoothingEnabled'; } - else if (this.context.webkitImageSmoothingEnabled) { + else if (this.context.webkitImageSmoothingEnabled) + { this.smoothProperty = 'webkitImageSmoothingEnabled'; } - else if (this.context.mozImageSmoothingEnabled) { + else if (this.context.mozImageSmoothingEnabled) + { this.smoothProperty = 'mozImageSmoothingEnabled'; } - else if (this.context.oImageSmoothingEnabled) { + else if (this.context.oImageSmoothingEnabled) + { this.smoothProperty = 'oImageSmoothingEnabled'; } - else if (this.context.msImageSmoothingEnabled) { + else if (this.context.msImageSmoothingEnabled) + { this.smoothProperty = 'msImageSmoothingEnabled'; } @@ -193,10 +203,12 @@ * @memberof CanvasRenderer# */ backgroundColor: { - get: function () { + get: function () + { return this._backgroundColor; }, - set: function (val) { + set: function (val) + { this._backgroundColor = val; this._backgroundColorString = utils.hex2string(val); } @@ -208,7 +220,8 @@ * * @param object {DisplayObject} the object to be rendered */ -CanvasRenderer.prototype.render = function (object) { +CanvasRenderer.prototype.render = function (object) +{ object.updateTransform(); this.context.setTransform(1,0,0,1,0,0); @@ -218,16 +231,20 @@ this.currentBlendMode = CONST.blendModes.NORMAL; this.context.globalCompositeOperation = this.blendModes[CONST.blendModes.NORMAL]; - if (navigator.isCocoonJS && this.view.screencanvas) { + if (navigator.isCocoonJS && this.view.screencanvas) + { this.context.fillStyle = 'black'; this.context.clear(); } - if (this.clearBeforeRender) { - if (this.transparent) { + if (this.clearBeforeRender) + { + if (this.transparent) + { this.context.clearRect(0, 0, this.width, this.height); } - else { + else + { this.context.fillStyle = this._backgroundColorString; this.context.fillRect(0, 0, this.width , this.height); } @@ -241,8 +258,10 @@ * * @param [removeView=false] {boolean} Removes the Canvas element from the DOM. */ -CanvasRenderer.prototype.destroy = function (removeView) { - if (removeView && this.view.parent) { +CanvasRenderer.prototype.destroy = function (removeView) +{ + if (removeView && this.view.parent) + { this.view.parent.removeChild(this.view); } @@ -257,14 +276,16 @@ * @param width {number} the new width of the canvas view * @param height {number} the new height of the canvas view */ -CanvasRenderer.prototype.resize = function (width, height) { +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) { + if (this.autoResize) + { this.view.style.width = this.width / this.resolution + 'px'; this.view.style.height = this.height / this.resolution + 'px'; } @@ -276,7 +297,8 @@ * @param displayObject {DisplayObject} The displayObject to render * @private */ -CanvasRenderer.prototype.renderDisplayObject = function (displayObject) { +CanvasRenderer.prototype.renderDisplayObject = function (displayObject) +{ displayObject.renderCanvas(this); }; @@ -285,11 +307,14 @@ * * @private */ -CanvasRenderer.prototype._mapBlendModes = function () { - if (!this.blendModes) { +CanvasRenderer.prototype._mapBlendModes = function () +{ + if (!this.blendModes) + { this.blendModes = {}; - if (utils.canUseNewCanvasBlendModes()) { + if (utils.canUseNewCanvasBlendModes()) + { this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? this.blendModes[CONST.blendModes.MULTIPLY] = 'multiply'; @@ -308,7 +333,8 @@ this.blendModes[CONST.blendModes.COLOR] = 'color'; this.blendModes[CONST.blendModes.LUMINOSITY] = 'luminosity'; } - else { + else + { // this means that the browser does not support the cool new blend modes in canvas 'cough' ie 'cough' this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? diff --git a/src/core/renderers/canvas/utils/CanvasBuffer.js b/src/core/renderers/canvas/utils/CanvasBuffer.js index ebe5d47..b183a66 100644 --- a/src/core/renderers/canvas/utils/CanvasBuffer.js +++ b/src/core/renderers/canvas/utils/CanvasBuffer.js @@ -6,7 +6,8 @@ * @param width {number} the width for the newly created canvas * @param height {number} the height for the newly created canvas */ -function CanvasBuffer(width, height) { +function CanvasBuffer(width, height) +{ /** * The Canvas object that belongs to this CanvasBuffer. * @@ -36,10 +37,12 @@ * @memberof CanvasBuffer# */ width: { - get: function () { + get: function () + { return this.canvas.width; }, - set: function (val) { + set: function (val) + { this.canvas.width = val; } }, @@ -50,10 +53,12 @@ * @memberof CanvasBuffer# */ height: { - get: function () { + get: function () + { return this.canvas.height; }, - set: function (val) { + set: function (val) + { this.canvas.height = val; } } @@ -64,7 +69,8 @@ * * @private */ -CanvasBuffer.prototype.clear = function () { +CanvasBuffer.prototype.clear = function () +{ this.context.setTransform(1, 0, 0, 1, 0, 0); this.context.clearRect(0,0, this.canvas.width, this.canvas.height); }; @@ -75,7 +81,8 @@ * @param width {number} the new width of the canvas * @param height {number} the new height of the canvas */ -CanvasBuffer.prototype.resize = function (width, height) { +CanvasBuffer.prototype.resize = function (width, height) +{ this.canvas.width = width; this.canvas.height = height; }; diff --git a/src/core/renderers/canvas/utils/CanvasGraphics.js b/src/core/renderers/canvas/utils/CanvasGraphics.js index c7eaa2a..3f2a91f 100644 --- a/src/core/renderers/canvas/utils/CanvasGraphics.js +++ b/src/core/renderers/canvas/utils/CanvasGraphics.js @@ -13,15 +13,18 @@ * @param graphics {Graphics} the actual graphics object to render * @param context {CanvasRenderingContext2D} the 2d drawing method of the canvas */ -CanvasGraphics.renderGraphics = function (graphics, context) { +CanvasGraphics.renderGraphics = function (graphics, context) +{ var worldAlpha = graphics.worldAlpha; - if (graphics.dirty) { + if (graphics.dirty) + { this.updateGraphicsTint(graphics); graphics.dirty = false; } - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; @@ -30,69 +33,82 @@ context.lineWidth = data.lineWidth; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { context.beginPath(); var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } - if (shape.closed) { + if (shape.closed) + { context.lineTo(points[0], points[1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fillRect(shape.x, shape.y, shape.width, shape.height); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.strokeRect(shape.x, shape.y, shape.width, shape.height); } } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.beginPath(); context.arc(shape.x, shape.y, shape.radius,0,2*Math.PI); context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas var w = shape.width * 2; @@ -119,18 +135,21 @@ context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; var width = shape.width; @@ -152,13 +171,15 @@ context.quadraticCurveTo(rx, ry, rx, ry + radius); context.closePath(); - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); @@ -174,45 +195,54 @@ * @param graphics {Graphics} the graphics which will be used as a mask * @param context {CanvasRenderingContext2D} the context 2d method of the canvas */ -CanvasGraphics.renderGraphicsMask = function (graphics, context) { +CanvasGraphics.renderGraphicsMask = function (graphics, context) +{ var len = graphics.graphicsData.length; - if (len === 0) { + if (len === 0) + { return; } context.beginPath(); - for (var i = 0; i < len; i++) { + for (var i = 0; i < len; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { context.rect(shape.x, shape.y, shape.width, shape.height); context.closePath(); } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.arc(shape.x, shape.y, shape.radius, 0, 2 * Math.PI); context.closePath(); } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas @@ -237,7 +267,8 @@ context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); context.closePath(); } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; @@ -262,8 +293,10 @@ } }; -CanvasGraphics.updateGraphicsTint = function (graphics) { - if (graphics.tint === 0xFFFFFF) { +CanvasGraphics.updateGraphicsTint = function (graphics) +{ + if (graphics.tint === 0xFFFFFF) + { return; } @@ -271,7 +304,8 @@ var tintG = (graphics.tint >> 8 & 0xFF) / 255; var tintB = (graphics.tint & 0xFF)/ 255; - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var fillColor = data.fillColor | 0; diff --git a/src/core/renderers/canvas/utils/CanvasMaskManager.js b/src/core/renderers/canvas/utils/CanvasMaskManager.js index e04a733..9827d36 100644 --- a/src/core/renderers/canvas/utils/CanvasMaskManager.js +++ b/src/core/renderers/canvas/utils/CanvasMaskManager.js @@ -6,7 +6,8 @@ * @class * @namespace PIXI */ -function CanvasMaskManager() {} +function CanvasMaskManager() +{} CanvasMaskManager.prototype.constructor = CanvasMaskManager; module.exports = CanvasMaskManager; @@ -17,7 +18,8 @@ * @param maskData {object} the maskData that will be pushed * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.pushMask = function (maskData, renderer) { +CanvasMaskManager.prototype.pushMask = function (maskData, renderer) +{ renderer.context.save(); var cacheAlpha = maskData.alpha; @@ -45,6 +47,7 @@ * * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.popMask = function (renderer) { +CanvasMaskManager.prototype.popMask = function (renderer) +{ renderer.context.restore(); }; diff --git a/src/core/renderers/canvas/utils/CanvasTinter.js b/src/core/renderers/canvas/utils/CanvasTinter.js index 17e0529..d2fb1bc 100644 --- a/src/core/renderers/canvas/utils/CanvasTinter.js +++ b/src/core/renderers/canvas/utils/CanvasTinter.js @@ -14,7 +14,8 @@ * @param color {number} the color to use to tint the sprite with * @return {HTMLCanvasElement} The tinted canvas */ -CanvasTinter.getTintedTexture = function (sprite, color) { +CanvasTinter.getTintedTexture = function (sprite, color) +{ var texture = sprite.texture; color = CanvasTinter.roundColor(color); @@ -23,7 +24,8 @@ texture.tintCache = texture.tintCache || {}; - if (texture.tintCache[stringColor]) { + if (texture.tintCache[stringColor]) + { return texture.tintCache[stringColor]; } @@ -33,14 +35,16 @@ //CanvasTinter.tintWithPerPixel(texture, stringColor, canvas); CanvasTinter.tintMethod(texture, color, canvas); - if (CanvasTinter.convertTintToImage) { + if (CanvasTinter.convertTintToImage) + { // is this better? var tintImage = new Image(); tintImage.src = canvas.toDataURL(); texture.tintCache[stringColor] = tintImage; } - else { + else + { texture.tintCache[stringColor] = canvas; // if we are not converting the texture to an image then we need to lose the reference to the canvas CanvasTinter.canvas = null; @@ -56,7 +60,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithMultiply = function (texture, color, canvas) { +CanvasTinter.tintWithMultiply = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -104,7 +109,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithOverlay = function (texture, color, canvas) { +CanvasTinter.tintWithOverlay = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -139,7 +145,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithPerPixel = function (texture, color, canvas) { +CanvasTinter.tintWithPerPixel = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -167,7 +174,8 @@ var pixels = pixelData.data; - for (var i = 0; i < pixels.length; i += 4) { + for (var i = 0; i < pixels.length; i += 4) + { pixels[i+0] *= r; pixels[i+1] *= g; pixels[i+2] *= b; @@ -181,7 +189,8 @@ * * @param color {number} the color to round, should be a hex color */ -CanvasTinter.roundColor = function (color) { +CanvasTinter.roundColor = function (color) +{ var step = CanvasTinter.cacheStepsPerColorChannel; var rgbValues = utils.hex2rgb(color); diff --git a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js index 9f2f89a..35edbaf 100644 --- a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js +++ b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLBlendModeManager(renderer) { +function WebGLBlendModeManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -23,8 +24,10 @@ * * @param blendMode {number} the blendMode, should be a Pixi const, such as BlendModes.ADD */ -WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) { - if (this.currentBlendMode === blendMode) { +WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) +{ + if (this.currentBlendMode === blendMode) + { return false; } diff --git a/src/core/renderers/webgl/managers/WebGLFilterManager.js b/src/core/renderers/webgl/managers/WebGLFilterManager.js index 1179258..2dac048 100644 --- a/src/core/renderers/webgl/managers/WebGLFilterManager.js +++ b/src/core/renderers/webgl/managers/WebGLFilterManager.js @@ -7,7 +7,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLFilterManager(renderer) { +function WebGLFilterManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -32,7 +33,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.texturePool.length = 0; self.initShaderBuffers(); }); @@ -46,7 +48,8 @@ * @param renderer {WebGLRenderer} * @param buffer {ArrayBuffer} */ -WebGLFilterManager.prototype.begin = function (buffer) { +WebGLFilterManager.prototype.begin = function (buffer) +{ this.defaultShader = this.renderer.shaderManager.defaultShader; this.width = this.renderer.projection.x * 2; @@ -60,7 +63,8 @@ * * @param filterBlock {object} the filter that will be pushed to the current filter stack */ -WebGLFilterManager.prototype.pushFilter = function (filterBlock) { +WebGLFilterManager.prototype.pushFilter = function (filterBlock) +{ var gl = this.renderer.gl; var projection = this.renderer.projection; @@ -78,10 +82,12 @@ this.offsetY += filterBlock._filterArea.y; var texture = this.texturePool.pop(); - if (!texture) { + if (!texture) + { texture = new FilterTexture(this.renderer.gl, this.width, this.height); } - else { + else + { texture.resize(this.width, this.height); } @@ -98,29 +104,35 @@ var localX = filterArea.x, localY = filterArea.y; - if (filterArea.x < 0) { + if (filterArea.x < 0) + { filterArea.width += filterArea.x; filterArea.x = 0; } - if (filterArea.y < 0) { + if (filterArea.y < 0) + { filterArea.height += filterArea.y; filterArea.y = 0; } - if (localX + filterArea.width > this.width) { + if (localX + filterArea.width > this.width) + { filterArea.width = this.width - localX; } - if (localY + filterArea.height > this.height) { + if (localY + filterArea.height > this.height) + { filterArea.height = this.height - localY; } - if (filterArea.width < 0) { + if (filterArea.width < 0) + { filterArea.width = 0; } - if (filterArea.height < 0) { + if (filterArea.height < 0) + { filterArea.height = 0; } @@ -154,7 +166,8 @@ * Removes the last filter from the filter stack and doesn't return it. * */ -WebGLFilterManager.prototype.popFilter = function () { +WebGLFilterManager.prototype.popFilter = function () +{ var gl = this.renderer.gl; var filterBlock = this.filterStack.pop(); @@ -163,7 +176,8 @@ var projection = this.renderer.projection; var offset = this.renderer.offset; - if (filterBlock.filterPasses.length > 1) { + if (filterBlock.filterPasses.length > 1) + { gl.viewport(0, 0, filterArea.width, filterArea.height); gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); @@ -193,7 +207,8 @@ var inputTexture = texture; var outputTexture = this.texturePool.pop(); - if (!outputTexture) { + if (!outputTexture) + { outputTexture = new FilterTexture(this.renderer.gl, this.width, this.height); } outputTexture.resize(this.width, this.height); @@ -204,7 +219,8 @@ gl.disable(gl.BLEND); - for (var i = 0; i < filterBlock.filterPasses.length-1; i++) { + for (var i = 0; i < filterBlock.filterPasses.length-1; i++) + { var filterPass = filterBlock.filterPasses[i]; gl.bindFramebuffer(gl.FRAMEBUFFER, outputTexture.frameBuffer ); @@ -243,10 +259,12 @@ var buffer = this.buffer; // time to render the filters texture to the previous scene - if (this.filterStack.length === 0) { + if (this.filterStack.length === 0) + { gl.colorMask(true, true, true, true);//this.transparent); } - else { + else + { var currentFilter = this.filterStack[this.filterStack.length-1]; filterArea = currentFilter._filterArea; @@ -332,13 +350,15 @@ * @param width {number} the horizontal range of the filter * @param height {number} the vertical range of the filter */ -WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) { +WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) +{ // use program var gl = this.renderer.gl; var shader = filter.shaders[gl.id]; - if (!shader) { + if (!shader) + { shader = new Shader(gl); shader.fragmentSrc = filter.fragmentSrc; @@ -356,7 +376,8 @@ gl.uniform2f(shader.projectionVector, width/2, -height/2); gl.uniform2f(shader.offsetVector, 0,0); - if (filter.uniforms.dimensions) { + 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]; @@ -386,7 +407,8 @@ * Initialises the shader buffers. * */ -WebGLFilterManager.prototype.initShaderBuffers = function () { +WebGLFilterManager.prototype.initShaderBuffers = function () +{ var gl = this.renderer.gl; // create some buffers @@ -432,7 +454,8 @@ * Destroys the filter and removes it from the filter stack. * */ -WebGLFilterManager.prototype.destroy = function () { +WebGLFilterManager.prototype.destroy = function () +{ var gl = this.renderer.gl; this.filterStack = null; @@ -441,7 +464,8 @@ this.offsetY = 0; // destroy textures - for (var i = 0; i < this.texturePool.length; i++) { + for (var i = 0; i < this.texturePool.length; i++) + { this.texturePool[i].destroy(); } diff --git a/src/core/renderers/webgl/managers/WebGLManager.js b/src/core/renderers/webgl/managers/WebGLManager.js index 9d47b5c..c30cd51 100644 --- a/src/core/renderers/webgl/managers/WebGLManager.js +++ b/src/core/renderers/webgl/managers/WebGLManager.js @@ -3,7 +3,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLManager(renderer) { +function WebGLManager(renderer) +{ /** * The renderer this manager works for. * @@ -15,6 +16,7 @@ WebGLManager.prototype.constructor = WebGLManager; module.exports = WebGLManager; -WebGLManager.prototype.destroy = function () { +WebGLManager.prototype.destroy = function () +{ this.renderer = null; }; diff --git a/src/core/renderers/webgl/managers/WebGLMaskManager.js b/src/core/renderers/webgl/managers/WebGLMaskManager.js index 2f90b64..e568812 100644 --- a/src/core/renderers/webgl/managers/WebGLMaskManager.js +++ b/src/core/renderers/webgl/managers/WebGLMaskManager.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLMaskManager(renderer) { +function WebGLMaskManager(renderer) +{ WebGLManager.call(this, renderer); } @@ -19,12 +20,15 @@ * * @param maskData {any[]} */ -WebGLMaskManager.prototype.pushMask = function (maskData) { - if (maskData.dirty) { +WebGLMaskManager.prototype.pushMask = function (maskData) +{ + if (maskData.dirty) + { WebGLGraphics.updateGraphics(maskData, this.renderer.gl); } - if (!maskData._webGL[this.renderer.gl.id].data.length) { + if (!maskData._webGL[this.renderer.gl.id].data.length) + { return; } @@ -36,6 +40,7 @@ * * @param maskData {any[]} */ -WebGLMaskManager.prototype.popMask = function (maskData) { +WebGLMaskManager.prototype.popMask = function (maskData) +{ this.renderer.stencilManager.popStencil(maskData, maskData._webGL[this.renderer.gl.id].data[0], this.renderer); }; diff --git a/src/core/renderers/webgl/managers/WebGLShaderManager.js b/src/core/renderers/webgl/managers/WebGLShaderManager.js index fef071c..90c6477 100644 --- a/src/core/renderers/webgl/managers/WebGLShaderManager.js +++ b/src/core/renderers/webgl/managers/WebGLShaderManager.js @@ -10,7 +10,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLShaderManager(renderer) { +function WebGLShaderManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -28,7 +29,8 @@ */ this.tempAttribState = []; - for (var i = 0; i < this.maxAttibs; i++) { + for (var i = 0; i < this.maxAttibs; i++) + { this.attribState[i] = false; } @@ -66,7 +68,8 @@ // listen for context and update necessary shaders var self = this; - this.renderer.on('context', function (event) { + this.renderer.on('context', function (event) + { var gl = event.data; // this shader is used for rendering primitives @@ -97,29 +100,36 @@ * * @param attribs {Array} attribs */ -WebGLShaderManager.prototype.setAttribs = function (attribs) { +WebGLShaderManager.prototype.setAttribs = function (attribs) +{ // reset temp state var i; - for (i = 0; i < this.tempAttribState.length; i++) { + for (i = 0; i < this.tempAttribState.length; i++) + { this.tempAttribState[i] = false; } // set the new attribs - for (var a in attribs) { + for (var a in attribs) + { this.tempAttribState[attribs[a]] = true; } var gl = this.renderer.gl; - for (i = 0; i < this.attribState.length; i++) { - if (this.attribState[i] !== this.tempAttribState[i]) { + for (i = 0; i < this.attribState.length; i++) + { + if (this.attribState[i] !== this.tempAttribState[i]) + { this.attribState[i] = this.tempAttribState[i]; - if (this.attribState[i]) { + if (this.attribState[i]) + { gl.enableVertexAttribArray(i); } - else { + else + { gl.disableVertexAttribArray(i); } } @@ -131,8 +141,10 @@ * * @param shader {Any} */ -WebGLShaderManager.prototype.setShader = function (shader) { - if (this._currentId === shader.uuid) { +WebGLShaderManager.prototype.setShader = function (shader) +{ + if (this._currentId === shader.uuid) + { return false; } @@ -150,7 +162,8 @@ * Destroys this object. * */ -WebGLShaderManager.prototype.destroy = function () { +WebGLShaderManager.prototype.destroy = function () +{ this.attribState = null; this.tempAttribState = null; diff --git a/src/core/renderers/webgl/managers/WebGLStencilManager.js b/src/core/renderers/webgl/managers/WebGLStencilManager.js index 9ec6398..4cb0134 100644 --- a/src/core/renderers/webgl/managers/WebGLStencilManager.js +++ b/src/core/renderers/webgl/managers/WebGLStencilManager.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLStencilManager(renderer) { +function WebGLStencilManager(renderer) +{ WebGLManager.call(this, renderer); this.stencilStack = []; @@ -24,12 +25,14 @@ * @param graphics {Graphics} * @param webGLData {any[]} */ -WebGLStencilManager.prototype.pushStencil = function (graphics, webGLData) { +WebGLStencilManager.prototype.pushStencil = function (graphics, webGLData) +{ var gl = this.renderer.gl; this.bindGraphics(graphics, webGLData, this.renderer); - if (this.stencilStack.length === 0) { + if (this.stencilStack.length === 0) + { gl.enable(gl.STENCIL_TEST); gl.clear(gl.STENCIL_BUFFER_BIT); this.reverse = true; @@ -47,14 +50,17 @@ // draw the triangle strip! - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } @@ -62,31 +68,38 @@ // draw a quad to increment.. gl.drawElements(gl.TRIANGLE_FAN, 4, gl.UNSIGNED_SHORT, ( webGLData.indices.length - 4 ) * 2 ); - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); } this.reverse = !this.reverse; } - else { - if (!this.reverse) { + else + { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } - else { + 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) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); } } @@ -103,7 +116,8 @@ * @param graphics {Graphics} * @param webGLData {Array} */ -WebGLStencilManager.prototype.bindGraphics = function (graphics, webGLData) { +WebGLStencilManager.prototype.bindGraphics = function (graphics, webGLData) +{ //if (this._currentGraphics === graphics)return; this._currentGraphics = graphics; @@ -114,7 +128,8 @@ offset = this.renderer.offset, shader;// = this.renderer.shaderManager.primitiveShader; - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { shader = this.renderer.shaderManager.complexPrimitiveShader; this.renderer.shaderManager.setShader(shader); @@ -141,7 +156,8 @@ // set the index buffer! gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, webGLData.indexBuffer); } - else { + else + { //this.renderer.shaderManager.activatePrimitiveShader(); shader = this.renderer.shaderManager.primitiveShader; this.renderer.shaderManager.setShader( shader ); @@ -154,7 +170,7 @@ gl.uniform2f(shader.uniforms.offsetVector._location, -offset.x, -offset.y); gl.uniform3fv(shader.uniforms.tint._location, utils.hex2rgb(graphics.tint)); - + gl.uniform1f(shader.uniforms.alpha._location, graphics.worldAlpha); @@ -172,19 +188,22 @@ * @param graphics {Graphics} * @param webGLData {Array} */ -WebGLStencilManager.prototype.popStencil = function (graphics, webGLData) { +WebGLStencilManager.prototype.popStencil = function (graphics, webGLData) +{ var gl = this.renderer.gl; this.stencilStack.pop(); this.count--; - if (this.stencilStack.length === 0) { + if (this.stencilStack.length === 0) + { // the stack is empty! gl.disable(gl.STENCIL_TEST); } - else { + else + { var level = this.count; @@ -192,14 +211,17 @@ gl.colorMask(false, false, false, false); - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { this.reverse = !this.reverse; - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } @@ -213,31 +235,38 @@ // draw the triangle strip! gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); - if (!this.reverse) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); } } - else { + else + { // console.log("<<>>") - if (!this.reverse) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } - else { + 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) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); } } @@ -253,7 +282,8 @@ * Destroys the mask stack. * */ -WebGLStencilManager.prototype.destroy = function () { +WebGLStencilManager.prototype.destroy = function () +{ this.renderer = null; this.stencilStack = null; }; diff --git a/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js b/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js index 913ba5e..1ea7d19 100644 --- a/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js +++ b/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function ComplexPrimitiveShader(gl) { +function ComplexPrimitiveShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -24,7 +25,8 @@ 'uniform float flipY;', 'varying vec4 vColor;', - 'void main(void) {', + '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);', @@ -37,7 +39,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = vColor;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/FastShader.js b/src/core/renderers/webgl/shaders/FastShader.js index bd2e29a..2e5e060 100644 --- a/src/core/renderers/webgl/shaders/FastShader.js +++ b/src/core/renderers/webgl/shaders/FastShader.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function FastShader(gl) { +function FastShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -28,7 +29,8 @@ 'const vec2 center = vec2(-1.0, 1.0);', - 'void main(void) {', + 'void main(void) + {', ' vec2 v;', ' vec2 sv = aVertexPosition * aScale;', ' v.x = (sv.x) * cos(aRotation) - (sv.y) * sin(aRotation);', @@ -49,7 +51,8 @@ 'uniform sampler2D uSampler;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/PrimitiveShader.js b/src/core/renderers/webgl/shaders/PrimitiveShader.js index 6f25409..a25f54f 100644 --- a/src/core/renderers/webgl/shaders/PrimitiveShader.js +++ b/src/core/renderers/webgl/shaders/PrimitiveShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function PrimitiveShader(gl) { +function PrimitiveShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -23,7 +24,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + '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);', @@ -36,7 +38,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = vColor;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/Shader.js b/src/core/renderers/webgl/shaders/Shader.js index f8964f5..fd75ef5 100644 --- a/src/core/renderers/webgl/shaders/Shader.js +++ b/src/core/renderers/webgl/shaders/Shader.js @@ -6,7 +6,8 @@ * @param [fragmentSrc] {string} The source of the fragment shader. * @param [vertexSrc] {string} The source of the vertex shader. */ -function Shader(gl, vertexSrc, fragmentSrc, customUniforms, customAttributes) { +function Shader(gl, vertexSrc, fragmentSrc, customUniforms, customAttributes) +{ /** * @member {number} * @readonly @@ -33,7 +34,8 @@ dimensions: { type: '4f', value: new Float32Array(4) } }; - for (var u in customUniforms) { + for (var u in customUniforms) + { this.uniforms[u] = customUniforms[u]; } @@ -43,7 +45,8 @@ aColor: 0 }; - for (var a in customAttributes) { + for (var a in customAttributes) + { this.attributes[a] = customAttributes[a]; } @@ -66,7 +69,8 @@ 'const vec2 center = vec2(-1.0, 1.0);', - 'void main(void) {', + 'void main(void) + {', ' gl_Position = vec4( ((aVertexPosition + offsetVector) / projectionVector) + center , 0.0, 1.0);', ' vTextureCoord = aTextureCoord;', ' vColor = vec4(aColor.rgb * aColor.a, aColor.a);', @@ -85,7 +89,8 @@ 'uniform sampler2D uSampler;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;', '}' ].join('\n'); @@ -96,7 +101,8 @@ Shader.prototype.constructor = Shader; module.exports = Shader; -Shader.prototype.init = function () { +Shader.prototype.init = function () +{ this.compile(); this.gl.useProgram(this.program); @@ -105,14 +111,18 @@ this.cacheAttributeLocations(Object.keys(this.attributes)); }; -Shader.prototype.cacheUniformLocations = function (keys) { - for (var i = 0; i < keys.length; ++i) { +Shader.prototype.cacheUniformLocations = function (keys) +{ + for (var i = 0; i < keys.length; ++i) + { this.uniforms[keys[i]]._location = this.gl.getUniformLocation(this.program, keys[i]); } }; -Shader.prototype.cacheAttributeLocations = function (keys) { - for (var i = 0; i < keys.length; ++i) { +Shader.prototype.cacheAttributeLocations = function (keys) +{ + for (var i = 0; i < keys.length; ++i) + { this.attributes[keys[i]] = this.gl.getAttribLocation(this.program, keys[i]); } @@ -124,14 +134,16 @@ // 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.attributes.aColor === -1) { + // if (this.attributes.aColor === -1) + { // this.attributes.aColor = 2; // } // End worst hack eva // }; -Shader.prototype.compile = function () { +Shader.prototype.compile = function () +{ var gl = this.gl; var glVertShader = this._glCompile(gl.VERTEX_SHADER, this.vertexSrc); @@ -144,13 +156,15 @@ gl.linkProgram(program); // if linking fails, then log and cleanup - if (!gl.getProgramParameter(program, gl.LINK_STATUS)) { + if (!gl.getProgramParameter(program, gl.LINK_STATUS)) + { window.console.error('Pixi.js Error: Could not initialize shader.'); window.console.error('gl.VALIDATE_STATUS', gl.getProgramParameter(program, gl.VALIDATE_STATUS)); window.console.error('gl.getError()', gl.getError()); // if there is a program info log, log it - if (gl.getProgramInfoLog(program) !== '') { + if (gl.getProgramInfoLog(program) !== '') + { window.console.warn('Pixi.js Warning: gl.getProgramInfoLog()', gl.getProgramInfoLog(program)); } @@ -165,18 +179,21 @@ return (this.program = program); }; -Shader.prototype.syncUniforms = function () { +Shader.prototype.syncUniforms = function () +{ var gl = this.gl; this.textureCount = 1; - for (var key in this.uniforms) { + for (var key in this.uniforms) + { var uniform = this.uniforms[key], location = uniform._location, value = uniform.value, i, il; - switch (uniform.type) { + switch (uniform.type) + { // single int value case 'i': case '1i': @@ -282,7 +299,8 @@ // a Color Value case 'c': - if (typeof value === 'number') { + if (typeof value === 'number') + { value = utils.hex2rgb(value); } @@ -311,11 +329,13 @@ // array of 2D Point objects case 'v2v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(2 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 2] = value[i].x; uniform._array[i * 2 + 1] = value[i].y; } @@ -325,11 +345,13 @@ // array of 3D Point objects case 'v3v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(3 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 3] = value[i].x; uniform._array[i * 3 + 1] = value[i].y; uniform._array[i * 3 + 2] = value[i].z; @@ -341,11 +363,13 @@ // array of 4D Point objects case 'v4v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(4 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 4] = value[i].x; uniform._array[i * 4 + 1] = value[i].y; uniform._array[i * 4 + 2] = value[i].z; @@ -359,7 +383,8 @@ // PIXI.Texture case 't': case 'sampler2D': - if (!uniform.value || !uniform.value.baseTexture || !uniform.value.baseTexture.hasLoaded) { + if (!uniform.value || !uniform.value.baseTexture || !uniform.value.baseTexture.hasLoaded) + { break; } @@ -376,7 +401,8 @@ this.textureCount++; // initialize the texture if we haven't yet - if (!uniform._init) { + if (!uniform._init) + { this.initSampler2D(uniform); uniform._init = true; @@ -394,11 +420,13 @@ * Initialises a Sampler2D uniform (which may only be available later on after initUniforms once the texture has loaded) * */ -Shader.prototype.initSampler2D = function (uniform) { +Shader.prototype.initSampler2D = function (uniform) +{ var gl = this.gl; // Extended texture data - if (uniform.textureData) { + if (uniform.textureData) + { var data = uniform.textureData; // GLTexture = mag linear, min linear_mipmap_linear, wrap repeat + gl.generateMipmap(gl.TEXTURE_2D); @@ -417,14 +445,16 @@ var wrapT = (data.wrapT) ? data.wrapT : gl.CLAMP_TO_EDGE; var format = (data.luminance) ? gl.LUMINANCE : gl.RGBA; - if (data.repeat) { + if (data.repeat) + { wrapS = gl.REPEAT; wrapT = gl.REPEAT; } gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, !!data.flipY); - if (data.width) { + if (data.width) + { var width = (data.width) ? data.width : 512; var height = (data.height) ? data.height : 2; var border = (data.border) ? data.border : 0; @@ -432,7 +462,8 @@ // 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 { + 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); } @@ -448,7 +479,8 @@ * Destroys the shader. * */ -Shader.prototype.destroy = function () { +Shader.prototype.destroy = function () +{ this.gl.deleteProgram(this.program); this.gl = null; @@ -459,13 +491,15 @@ this.fragmentSrc = null; }; -Shader.prototype._glCompile = function (type, src) { +Shader.prototype._glCompile = function (type, src) +{ var shader = this.gl.createShader(type); this.gl.shaderSource(shader, src); this.gl.compileShader(shader); - if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) { + if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) + { window.console.log(this.gl.getShaderInfoLog(shader)); return null; } diff --git a/src/core/renderers/webgl/shaders/StripShader.js b/src/core/renderers/webgl/shaders/StripShader.js index 193f6e1..a7abcc6 100644 --- a/src/core/renderers/webgl/shaders/StripShader.js +++ b/src/core/renderers/webgl/shaders/StripShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function StripShader(gl) { +function StripShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -20,7 +21,8 @@ 'varying vec2 vTextureCoord;', - 'void main(void) {', + '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);', @@ -36,7 +38,8 @@ 'varying vec2 vTextureCoord;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vec2(vTextureCoord.x, vTextureCoord.y)) * alpha;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/utils/FilterTexture.js b/src/core/renderers/webgl/utils/FilterTexture.js index d2c8423..4433d44 100644 --- a/src/core/renderers/webgl/utils/FilterTexture.js +++ b/src/core/renderers/webgl/utils/FilterTexture.js @@ -8,7 +8,8 @@ * @param height {number} the vertical range of the filter * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values */ -function FilterTexture(gl, width, height, scaleMode) { +function FilterTexture(gl, width, height, scaleMode) +{ /** * @member {WebGLContext} */ @@ -59,7 +60,8 @@ * Clears the filter texture. * */ -FilterTexture.prototype.clear = function () { +FilterTexture.prototype.clear = function () +{ var gl = this.gl; gl.clearColor(0,0,0, 0); @@ -72,8 +74,10 @@ * @param width {number} the new width of the texture * @param height {number} the new height of the texture */ -FilterTexture.prototype.resize = function (width, height) { - if (this.width === width && this.height === height) { +FilterTexture.prototype.resize = function (width, height) +{ + if (this.width === width && this.height === height) + { return; } @@ -96,7 +100,8 @@ * Destroys the filter texture. * */ -FilterTexture.prototype.destroy = function () { +FilterTexture.prototype.destroy = function () +{ var gl = this.gl; gl.deleteFramebuffer( this.frameBuffer ); gl.deleteTexture( this.texture ); diff --git a/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js b/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js index c4721e9..a63f4d7 100644 --- a/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js +++ b/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js @@ -14,7 +14,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this sprite batch works for. */ -function WebGLFastSpriteBatch(renderer) { +function WebGLFastSpriteBatch(renderer) +{ /** * The renderer instance this sprite batch operates on. * @@ -91,7 +92,8 @@ */ this.lastIndexCount = 0; - for (var i=0, j=0; i < numIndices; i += 6, j += 4) { + 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; @@ -144,7 +146,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.setupContext(); }); } @@ -157,7 +160,8 @@ * * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLFastSpriteBatch.prototype.setupContext = function () { +WebGLFastSpriteBatch.prototype.setupContext = function () +{ var gl = this.renderer.gl; // create a couple of buffers @@ -177,7 +181,8 @@ /** * @param spriteBatch {SpriteBatch} The SpriteBatch container to prepare for. */ -WebGLFastSpriteBatch.prototype.begin = function (spriteBatch) { +WebGLFastSpriteBatch.prototype.begin = function (spriteBatch) +{ this.shader = this.renderer.shaderManager.fastShader; this.matrix = spriteBatch.worldTransform.toArray(true); @@ -187,33 +192,38 @@ /** */ -WebGLFastSpriteBatch.prototype.end = function () { +WebGLFastSpriteBatch.prototype.end = function () +{ this.flush(); }; /** * @param spriteBatch {SpriteBatch} The SpriteBatch container to render. */ -WebGLFastSpriteBatch.prototype.render = function (spriteBatch) { +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) { + if (!sprite.texture._uvs) + { return; } this.currentBaseTexture = sprite.texture.baseTexture; // check blend mode - if (sprite.blendMode !== this.renderer.blendModeManager.currentBlendMode) { + if (sprite.blendMode !== this.renderer.blendModeManager.currentBlendMode) + { this.flush(); this.renderer.blendModeManager.setBlendMode(sprite.blendMode); } - for (var i=0,j= children.length; i= this.size) { + if (this.currentBatchSize >= this.size) + { this.flush(); } }; @@ -362,29 +379,35 @@ /** * */ -WebGLFastSpriteBatch.prototype.flush = function () { +WebGLFastSpriteBatch.prototype.flush = function () +{ // If the batch is length 0 then return as there is nothing to draw - if (this.currentBatchSize === 0) { + if (this.currentBatchSize === 0) + { return; } var gl = this.renderer.gl; // bind the current texture - if (!this.currentBaseTexture._glTextures[gl.id]) { + if (!this.currentBaseTexture._glTextures[gl.id]) + { this.renderer.updateTexture(this.currentBaseTexture, gl); } //TODO-SHOUD THIS BE ELSE??!?!?! - else { + else + { gl.bindTexture(gl.TEXTURE_2D, this.currentBaseTexture._glTextures[gl.id]); } // upload the verts to the buffer - if (this.currentBatchSize > ( this.size * 0.5 ) ) { + if (this.currentBatchSize > ( this.size * 0.5 ) ) + { gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); } - else { + else + { var view = this.vertices.subarray(0, this.currentBatchSize * this.vertByteSize); gl.bufferSubData(gl.ARRAY_BUFFER, 0, view); @@ -405,14 +428,16 @@ * Ends the batch and flushes * */ -WebGLFastSpriteBatch.prototype.stop = function () { +WebGLFastSpriteBatch.prototype.stop = function () +{ this.flush(); }; /** * */ -WebGLFastSpriteBatch.prototype.start = function () { +WebGLFastSpriteBatch.prototype.start = function () +{ var gl = this.renderer.gl; // bind the main texture diff --git a/src/core/renderers/webgl/utils/WebGLGraphics.js b/src/core/renderers/webgl/utils/WebGLGraphics.js index 55f4911..ab8f46e 100644 --- a/src/core/renderers/webgl/utils/WebGLGraphics.js +++ b/src/core/renderers/webgl/utils/WebGLGraphics.js @@ -19,7 +19,8 @@ * @param graphics {Graphics} * @param renderer {WebGLRenderer} */ -WebGLGraphics.renderGraphics = function (graphics, renderer) {//projection, offset) { +WebGLGraphics.renderGraphics = function (graphics, renderer) {//projection, offset) +{ var gl = renderer.gl; var projection = renderer.projection, @@ -27,7 +28,8 @@ shader = renderer.shaderManager.primitiveShader, webGLData; - if (graphics.dirty) { + if (graphics.dirty) + { WebGLGraphics.updateGraphics(graphics, gl); } @@ -35,8 +37,10 @@ // This could be speeded up for sure! - for (var i = 0; i < webGL.data.length; i++) { - if (webGL.data[i].mode === 1) { + for (var i = 0; i < webGL.data.length; i++) + { + if (webGL.data[i].mode === 1) + { webGLData = webGL.data[i]; renderer.stencilManager.pushStencil(graphics, webGLData, renderer); @@ -46,7 +50,8 @@ renderer.stencilManager.popStencil(graphics, webGLData, renderer); } - else { + else + { webGLData = webGL.data[i]; @@ -84,12 +89,14 @@ * @param graphicsData {Graphics} The graphics object to update * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLGraphics.updateGraphics = function (graphics, gl) { +WebGLGraphics.updateGraphics = function (graphics, gl) +{ // get the contexts graphics object var webGL = graphics._webGL[gl.id]; // if the graphics object does not exist in the webGL context time to create it! - if (!webGL) { + if (!webGL) + { webGL = graphics._webGL[gl.id] = {lastIndex:0, data:[], gl:gl}; } @@ -99,11 +106,13 @@ var i; // if the user cleared the graphics object we will need to clear every object - if (graphics.clearDirty) { + if (graphics.clearDirty) + { graphics.clearDirty = false; // lop through and return all the webGLDatas to the object pool so than can be reused later on - for (i = 0; i < webGL.data.length; i++) { + for (i = 0; i < webGL.data.length; i++) + { var graphicsData = webGL.data[i]; graphicsData.reset(); WebGLGraphics.graphicsDataPool.push( graphicsData ); @@ -119,58 +128,72 @@ // loop through the graphics datas and construct each one.. // if the object is a complex fill then the new stencil buffer technique will be used // other wise graphics objects will be pushed into a batch.. - for (i = webGL.lastIndex; i < graphics.graphicsData.length; i++) { + for (i = webGL.lastIndex; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { // need to add the points the the graphics object.. data.points = data.shape.points.slice(); - if (data.shape.closed) { + if (data.shape.closed) + { // close the poly if the value is true! - if (data.points[0] !== data.points[data.points.length-2] || data.points[1] !== data.points[data.points.length-1]) { + if (data.points[0] !== data.points[data.points.length-2] || data.points[1] !== data.points[data.points.length-1]) + { data.points.push(data.points[0], data.points[1]); } } // MAKE SURE WE HAVE THE CORRECT TYPE.. - if (data.fill) { - if (data.points.length >= 6) { - if (data.points.length < 6 * 2) { + if (data.fill) + { + if (data.points.length >= 6) + { + if (data.points.length < 6 * 2) + { webGLData = WebGLGraphics.switchMode(webGL, 0); var canDrawUsingSimple = WebGLGraphics.buildPoly(data, webGLData); // console.log(canDrawUsingSimple); - if (!canDrawUsingSimple) { + if (!canDrawUsingSimple) + { // console.log("<>>>") webGLData = WebGLGraphics.switchMode(webGL, 1); WebGLGraphics.buildComplexPoly(data, webGLData); } } - else { + else + { webGLData = WebGLGraphics.switchMode(webGL, 1); WebGLGraphics.buildComplexPoly(data, webGLData); } } } - if (data.lineWidth > 0) { + if (data.lineWidth > 0) + { webGLData = WebGLGraphics.switchMode(webGL, 0); WebGLGraphics.buildLine(data, webGLData); } } - else { + else + { webGLData = WebGLGraphics.switchMode(webGL, 0); - if (data.type === CONST.SHAPES.RECT) { + if (data.type === CONST.SHAPES.RECT) + { WebGLGraphics.buildRectangle(data, webGLData); } - else if (data.type === CONST.SHAPES.CIRC || data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.CIRC || data.type === CONST.SHAPES.ELIP) + { WebGLGraphics.buildCircle(data, webGLData); } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { WebGLGraphics.buildRoundedRectangle(data, webGLData); } } @@ -179,10 +202,12 @@ } // upload all the dirty data... - for (i = 0; i < webGL.data.length; i++) { + for (i = 0; i < webGL.data.length; i++) + { webGLData = webGL.data[i]; - if (webGLData.dirty) { + if (webGLData.dirty) + { webGLData.upload(); } } @@ -194,18 +219,22 @@ * @param webGL {WebGLContext} * @param type {number} */ -WebGLGraphics.switchMode = function (webGL, type) { +WebGLGraphics.switchMode = function (webGL, type) +{ var webGLData; - if (!webGL.data.length) { + if (!webGL.data.length) + { webGLData = WebGLGraphics.graphicsDataPool.pop() || new WebGLGraphicsData(webGL.gl); webGLData.mode = type; webGL.data.push(webGLData); } - else { + else + { webGLData = webGL.data[webGL.data.length-1]; - if (webGLData.mode !== type || type === 1) { + if (webGLData.mode !== type || type === 1) + { webGLData = WebGLGraphics.graphicsDataPool.pop() || new WebGLGraphicsData(webGL.gl); webGLData.mode = type; webGL.data.push(webGLData); @@ -225,7 +254,8 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildRectangle = function (graphicsData, webGLData) { +WebGLGraphics.buildRectangle = function (graphicsData, webGLData) +{ // --- // // need to convert points to a nice regular data // @@ -235,7 +265,8 @@ var width = rectData.width; var height = rectData.height; - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -265,7 +296,8 @@ indices.push(vertPos, vertPos, vertPos+1, vertPos+2, vertPos+3, vertPos+3); } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = [x, y, @@ -289,7 +321,8 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildRoundedRectangle = function (graphicsData, webGLData) { +WebGLGraphics.buildRoundedRectangle = function (graphicsData, webGLData) +{ var rrectData = graphicsData.shape; var x = rrectData.x; var y = rrectData.y; @@ -305,7 +338,8 @@ recPoints = recPoints.concat(WebGLGraphics.quadraticBezierCurve(x + width, y + radius, x + width, y, x + width - radius, y)); recPoints = recPoints.concat(WebGLGraphics.quadraticBezierCurve(x + radius, y, x, y, x, y + radius)); - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -323,7 +357,8 @@ // var i = 0; - for (i = 0; i < triangles.length; i+=3) { + for (i = 0; i < triangles.length; i+=3) + { indices.push(triangles[i] + vecPos); indices.push(triangles[i] + vecPos); indices.push(triangles[i+1] + vecPos); @@ -332,12 +367,14 @@ } - for (i = 0; i < recPoints.length; i++) { + for (i = 0; i < recPoints.length; i++) + { verts.push(recPoints[i], recPoints[++i], r, g, b, alpha); } } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = recPoints; @@ -362,7 +399,8 @@ * @param toY {number} Destination point y * @return {number[]} */ -WebGLGraphics.quadraticBezierCurve = function (fromX, fromY, cpX, cpY, toX, toY) { +WebGLGraphics.quadraticBezierCurve = function (fromX, fromY, cpX, cpY, toX, toY) +{ var xa, ya, @@ -373,14 +411,16 @@ n = 20, points = []; - function getPt(n1 , n2, perc) { + function getPt(n1 , n2, perc) + { var diff = n2 - n1; return n1 + ( diff * perc ); } var j = 0; - for (var i = 0; i <= n; i++ ) { + for (var i = 0; i <= n; i++ ) + { j = i / n; // The Green Line @@ -406,7 +446,8 @@ * @param graphicsData {Graphics} The graphics object to draw * @param webGLData {object} */ -WebGLGraphics.buildCircle = function (graphicsData, webGLData) { +WebGLGraphics.buildCircle = function (graphicsData, webGLData) +{ // need to convert points to a nice regular data var circleData = graphicsData.shape; var x = circleData.x; @@ -415,11 +456,13 @@ var height; // TODO - bit hacky?? - if (graphicsData.type === CONST.SHAPES.CIRC) { + if (graphicsData.type === CONST.SHAPES.CIRC) + { width = circleData.radius; height = circleData.radius; } - else { + else + { width = circleData.width; height = circleData.height; } @@ -429,7 +472,8 @@ var i = 0; - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -444,7 +488,8 @@ indices.push(vecPos); - for (i = 0; i < totalSegs + 1 ; i++) { + for (i = 0; i < totalSegs + 1 ; i++) + { verts.push(x,y, r, g, b, alpha); verts.push(x + Math.sin(seg * i) * width, @@ -457,12 +502,14 @@ indices.push(vecPos-1); } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = []; - for (i = 0; i < totalSegs + 1; i++) { + for (i = 0; i < totalSegs + 1; i++) + { graphicsData.points.push(x + Math.sin(seg * i) * width, y + Math.cos(seg * i) * height); } @@ -481,18 +528,22 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildLine = function (graphicsData, webGLData) { +WebGLGraphics.buildLine = function (graphicsData, webGLData) +{ // TODO OPTIMISE! var i = 0; var points = graphicsData.points; - if (points.length === 0) { + if (points.length === 0) + { return; } // if the line width is an odd number add 0.5 to align to a whole pixel - if (graphicsData.lineWidth%2) { - for (i = 0; i < points.length; i++) { + if (graphicsData.lineWidth%2) + { + for (i = 0; i < points.length; i++) + { points[i] += 0.5; } } @@ -502,7 +553,8 @@ var lastPoint = new math.Point(points[points.length - 2], points[points.length - 1]); // if the first point is the last point - gonna have issues :) - if (firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) { + if (firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) + { // need to clone as we are going to slightly modify the shape.. points = points.slice(); @@ -562,7 +614,8 @@ verts.push(p1x + perpx , p1y + perpy, r, g, b, alpha); - for (i = 1; i < length-1; i++) { + for (i = 1; i < length-1; i++) + { p1x = points[(i-1)*2]; p1y = points[(i-1)*2 + 1]; @@ -599,7 +652,8 @@ denom = a1*b2 - a2*b1; - if (Math.abs(denom) < 0.1 ) { + if (Math.abs(denom) < 0.1 ) + { denom+=10.1; verts.push(p2x - perpx , p2y - perpy, @@ -618,7 +672,8 @@ pdist = (px -p2x) * (px -p2x) + (py -p2y) + (py -p2y); - if (pdist > 140 * 140) { + if (pdist > 140 * 140) + { perp3x = perpx - perp2x; perp3y = perpy - perp2y; @@ -639,7 +694,8 @@ indexCount++; } - else { + else + { verts.push(px , py); verts.push(r, g, b, alpha); @@ -672,7 +728,8 @@ indices.push(indexStart); - for (i = 0; i < indexCount; i++) { + for (i = 0; i < indexCount; i++) + { indices.push(indexStart++); } @@ -687,11 +744,13 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildComplexPoly = function (graphicsData, webGLData) { +WebGLGraphics.buildComplexPoly = function (graphicsData, webGLData) +{ //TODO - no need to copy this as it gets turned into a FLoat32Array anyways.. var points = graphicsData.points.slice(); - if (points.length < 6) { + if (points.length < 6) + { return; } @@ -711,7 +770,8 @@ var x,y; // get size.. - for (var i = 0; i < points.length; i+=2) { + for (var i = 0; i < points.length; i+=2) + { x = points[i]; y = points[i+1]; @@ -732,7 +792,8 @@ //TODO - this aint needed! var length = points.length / 2; - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { indices.push( i ); } @@ -746,10 +807,12 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildPoly = function (graphicsData, webGLData) { +WebGLGraphics.buildPoly = function (graphicsData, webGLData) +{ var points = graphicsData.points; - if (points.length < 6) { + if (points.length < 6) + { return; } // get first and last point.. figure out the middle! @@ -767,7 +830,8 @@ var triangles = utils.PolyK.Triangulate(points); - if (!triangles) { + if (!triangles) + { return false; } @@ -775,7 +839,8 @@ var i = 0; - for (i = 0; i < triangles.length; i+=3) { + for (i = 0; i < triangles.length; i+=3) + { indices.push(triangles[i] + vertPos); indices.push(triangles[i] + vertPos); indices.push(triangles[i+1] + vertPos); @@ -783,7 +848,8 @@ indices.push(triangles[i+2] + vertPos); } - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { verts.push(points[i * 2], points[i * 2 + 1], r, g, b, alpha); } diff --git a/src/core/renderers/webgl/utils/WebGLGraphicsData.js b/src/core/renderers/webgl/utils/WebGLGraphicsData.js index c56d05e..c739ba7 100644 --- a/src/core/renderers/webgl/utils/WebGLGraphicsData.js +++ b/src/core/renderers/webgl/utils/WebGLGraphicsData.js @@ -2,7 +2,8 @@ * @class * @private */ -function WebGLGraphicsData(gl) { +function WebGLGraphicsData(gl) +{ this.gl = gl; //TODO does this need to be split before uploding?? @@ -22,7 +23,8 @@ /** * */ -WebGLGraphicsData.prototype.reset = function () { +WebGLGraphicsData.prototype.reset = function () +{ this.points.length = 0; this.indices.length = 0; }; @@ -30,7 +32,8 @@ /** * */ -WebGLGraphicsData.prototype.upload = function () { +WebGLGraphicsData.prototype.upload = function () +{ var gl = this.gl; // this.lastIndex = graphics.graphicsData.length; diff --git a/src/core/renderers/webgl/utils/WebGLSpriteBatch.js b/src/core/renderers/webgl/utils/WebGLSpriteBatch.js index 96eaa52..55befbb 100644 --- a/src/core/renderers/webgl/utils/WebGLSpriteBatch.js +++ b/src/core/renderers/webgl/utils/WebGLSpriteBatch.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this sprite batch works for. */ -function WebGLSpriteBatch(renderer) { +function WebGLSpriteBatch(renderer) +{ /** * * @@ -88,7 +89,8 @@ */ this.lastIndexCount = 0; - for (var i=0, j=0; i < numIndices; i += 6, j += 4) { + 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; @@ -162,7 +164,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.setupContext(); }); } @@ -173,7 +176,8 @@ /** * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLSpriteBatch.prototype.setupContext = function () { +WebGLSpriteBatch.prototype.setupContext = function () +{ var gl = this.renderer.gl; // setup default shader @@ -198,7 +202,8 @@ /** * */ -WebGLSpriteBatch.prototype.begin = function () { +WebGLSpriteBatch.prototype.begin = function () +{ // this.shader = this.renderer.shaderManager.defaultShader; this.start(); @@ -206,19 +211,22 @@ /** */ -WebGLSpriteBatch.prototype.end = function () { +WebGLSpriteBatch.prototype.end = function () +{ this.flush(); }; /** * @param sprite {Sprite} the sprite to render when using this spritebatch */ -WebGLSpriteBatch.prototype.render = function (sprite) { +WebGLSpriteBatch.prototype.render = function (sprite) +{ var texture = sprite.texture; //TODO set blend modes.. // check texture.. - if (this.currentBatchSize >= this.size) { + if (this.currentBatchSize >= this.size) + { this.flush(); this.currentBaseTexture = texture.baseTexture; } @@ -227,7 +235,8 @@ var uvs = texture._uvs; // if the uvs have not updated then no point rendering just yet! - if (!uvs) { + if (!uvs) + { return; } @@ -237,7 +246,8 @@ var w0, w1, h0, h1; - if (texture.trim) { + 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; @@ -248,7 +258,8 @@ h0 = h1 + texture.crop.height; } - else { + else + { w0 = (texture.frame.width ) * (1-aX); w1 = (texture.frame.width ) * -aX; @@ -272,7 +283,8 @@ var colors = this.colors; var positions = this.positions; - if (this.renderer.roundPixels) { + if (this.renderer.roundPixels) + { // xy positions[index] = a * w1 + c * h1 + tx | 0; positions[index+1] = d * h1 + b * w1 + ty | 0; @@ -289,7 +301,8 @@ positions[index+15] = a * w1 + c * h0 + tx | 0; positions[index+16] = d * h0 + b * w1 + ty | 0; } - else { + else + { // xy positions[index] = a * w1 + c * h1 + tx; positions[index+1] = d * h1 + b * w1 + ty; @@ -338,11 +351,13 @@ * * @param sprite {TilingSprite} the tilingSprite to render */ -WebGLSpriteBatch.prototype.renderTilingSprite = function (tilingSprite) { +WebGLSpriteBatch.prototype.renderTilingSprite = function (tilingSprite) +{ var texture = tilingSprite.tilingTexture; // check texture.. - if (this.currentBatchSize >= this.size) { + if (this.currentBatchSize >= this.size) + { //return; this.flush(); this.currentBaseTexture = texture.baseTexture; @@ -351,7 +366,8 @@ // set the textures uvs temporarily // TODO create a separate texture so that we can tile part of a texture - if (!tilingSprite._uvs) { + if (!tilingSprite._uvs) + { tilingSprite._uvs = new TextureUvs(); } @@ -454,16 +470,19 @@ * Renders the content and empties the current batch. * */ -WebGLSpriteBatch.prototype.flush = function () { +WebGLSpriteBatch.prototype.flush = function () +{ // If the batch is length 0 then return as there is nothing to draw - if (this.currentBatchSize === 0) { + if (this.currentBatchSize === 0) + { return; } var gl = this.renderer.gl; var shader; - if (this.dirty) { + if (this.dirty) + { this.dirty = false; // bind the main texture gl.activeTexture(gl.TEXTURE0); @@ -482,10 +501,12 @@ } // upload the verts to the buffer - if (this.currentBatchSize > ( this.size * 0.5 ) ) { + if (this.currentBatchSize > ( this.size * 0.5 ) ) + { gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); } - else { + else + { var view = this.positions.subarray(0, this.currentBatchSize * this.vertByteSize); gl.bufferSubData(gl.ARRAY_BUFFER, 0, view); } @@ -502,7 +523,8 @@ var shaderSwap = false; var sprite; - for (var i = 0, j = this.currentBatchSize; i < j; i++) { + for (var i = 0, j = this.currentBatchSize; i < j; i++) + { sprite = this.sprites[i]; @@ -513,24 +535,28 @@ blendSwap = currentBlendMode !== nextBlendMode; shaderSwap = currentShader !== nextShader; // should I use uuidS??? - if (currentBaseTexture !== nextTexture || blendSwap || shaderSwap) { + if (currentBaseTexture !== nextTexture || blendSwap || shaderSwap) + { this.renderBatch(currentBaseTexture, batchSize, start); start = i; batchSize = 0; currentBaseTexture = nextTexture; - if (blendSwap) { + if (blendSwap) + { currentBlendMode = nextBlendMode; this.renderer.blendModeManager.setBlendMode( currentBlendMode ); } - if (shaderSwap) { + if (shaderSwap) + { currentShader = nextShader; shader = currentShader.shaders ? currentShader.shaders[gl.id] : currentShader; - if (!shader) { + if (!shader) + { shader = new Shader(gl, null, currentShader.fragmentSrc, currentShader.uniforms); currentShader.shaders[gl.id] = shader; } @@ -538,7 +564,8 @@ // set shader function??? this.renderer.shaderManager.setShader(shader); - if (shader.dirty) { + if (shader.dirty) + { shader.syncUniforms(); } @@ -569,17 +596,21 @@ * @param size {number} * @param startIndex {number} */ -WebGLSpriteBatch.prototype.renderBatch = function (texture, size, startIndex) { - if (size === 0) { +WebGLSpriteBatch.prototype.renderBatch = function (texture, size, startIndex) +{ + if (size === 0) + { return; } var gl = this.renderer.gl; - if (!texture._glTextures[gl.id]) { + if (!texture._glTextures[gl.id]) + { this.renderer.updateTexture(texture); } - else { + else + { // bind the current texture gl.bindTexture(gl.TEXTURE_2D, texture._glTextures[gl.id]); } @@ -594,7 +625,8 @@ /** * */ -WebGLSpriteBatch.prototype.stop = function () { +WebGLSpriteBatch.prototype.stop = function () +{ this.flush(); this.dirty = true; }; @@ -602,7 +634,8 @@ /** * */ -WebGLSpriteBatch.prototype.start = function () { +WebGLSpriteBatch.prototype.start = function () +{ this.dirty = true; }; @@ -610,7 +643,8 @@ * Destroys the SpriteBatch. * */ -WebGLSpriteBatch.prototype.destroy = function () { +WebGLSpriteBatch.prototype.destroy = function () +{ this.renderer.gl.deleteBuffer(this.vertexBuffer); this.renderer.gl.deleteBuffer(this.indexBuffer); diff --git a/src/core/textures/BaseTexture.js b/src/core/textures/BaseTexture.js index 2bf77d4..513d358 100644 --- a/src/core/textures/BaseTexture.js +++ b/src/core/textures/BaseTexture.js @@ -10,7 +10,8 @@ * @param source {Image|Canvas} the source object of the texture. * @param [scaleMode=scaleModes.DEFAULT] {number} See {@link scaleModes} for possible values */ -function BaseTexture(source, scaleMode) { +function BaseTexture(source, scaleMode) +{ this.uuid = utils.uuid(); /** @@ -123,7 +124,8 @@ this._needsUpdate = false; // if no source passed don't try to load - if (source) { + if (source) + { this.loadSource(source); } @@ -149,13 +151,16 @@ Object.defineProperties(BaseTexture.prototype, { needsUpdate: { - get: function () { + get: function () + { return this._needsUpdate; }, - set: function (val) { + set: function (val) + { this._needsUpdate = val; - if (val) { + if (val) + { this.emit('update', this); } } @@ -171,9 +176,11 @@ * * The logic state after calling `loadSource` directly or indirectly (eg. `fromImage`, `new BaseTexture`) is: * - * if (texture.hasLoaded) { + * if (texture.hasLoaded) + { * // texture ready for use - * } else if (texture.isLoading) { + * } else if (texture.isLoading) + { * // listen to 'loaded' and/or 'error' events on texture * } else { * // not loading, not going to load UNLESS the source is reloaded @@ -183,12 +190,14 @@ * @protected * @param source {Image|Canvas} the source object of the texture. */ -BaseTexture.prototype.loadSource = function (source) { +BaseTexture.prototype.loadSource = function (source) +{ var wasLoading = this.isLoading; this.hasLoaded = false; this.isLoading = false; - if (wasLoading && this.source) { + if (wasLoading && this.source) + { this.source.onload = null; this.source.onerror = null; } @@ -196,20 +205,24 @@ this.source = source; // Apply source if loaded. Otherwise setup appropriate loading monitors. - if ((this.source.complete || this.source.getContext) && this.source.width && this.source.height) { + if ((this.source.complete || this.source.getContext) && this.source.width && this.source.height) + { this._sourceLoaded(); } - else if(!source.getContext) { + else if(!source.getContext) + { // Image fail / not ready this.isLoading = true; var scope = this; - source.onload = function () { + source.onload = function () + { source.onload = null; source.onerror = null; - if(!scope.isLoading) { + if(!scope.isLoading) + { return; } @@ -219,11 +232,13 @@ scope.emit('loaded', scope); }; - source.onerror = function () { + source.onerror = function () + { source.onload = null; source.onerror = null; - if(!scope.isLoading) { + if(!scope.isLoading) + { return; } @@ -234,24 +249,29 @@ // Per http://www.w3.org/TR/html5/embedded-content-0.html#the-img-element // "The value of `complete` can thus change while a script is executing." // So complete needs to be re-checked after the callbacks have been added.. - if (source.complete) { + if (source.complete) + { this.isLoading = false; // ..and if we're complete now, no need for callbacks source.onload = null; source.onerror = null; - if (source.width && source.height) { + if (source.width && source.height) + { this._sourceLoaded(); // If any previous subscribers possible - if (wasLoading) { + if (wasLoading) + { this.emit('loaded', this); } } - else { + else + { // If any previous subscribers possible - if (wasLoading) { + if (wasLoading) + { this.emit('error', this); } } @@ -265,7 +285,8 @@ * * @private */ -BaseTexture.prototype._sourceLoaded = function () { +BaseTexture.prototype._sourceLoaded = function () +{ this.hasLoaded = true; this.width = this.source.naturalWidth || this.source.width; @@ -278,16 +299,20 @@ * Destroys this base texture * */ -BaseTexture.prototype.destroy = function () { - if (this.imageUrl) { +BaseTexture.prototype.destroy = function () +{ + if (this.imageUrl) + { delete utils.BaseTextureCache[this.imageUrl]; delete utils.TextureCache[this.imageUrl]; this.imageUrl = null; - if (!navigator.isCocoonJS) { + if (!navigator.isCocoonJS) + { this.source.src = ''; } } - else if (this.source && this.source._pixiId) { + else if (this.source && this.source._pixiId) + { delete utils.BaseTextureCache[this.source._pixiId]; } this.source = null; @@ -301,7 +326,8 @@ * memory again. * */ -BaseTexture.prototype.dispose = function () { +BaseTexture.prototype.dispose = function () +{ this.emit('dispose', this); }; @@ -311,7 +337,8 @@ * * @param newSrc {string} the path of the image */ -BaseTexture.prototype.updateSourceImage = function (newSrc) { +BaseTexture.prototype.updateSourceImage = function (newSrc) +{ this.source.src = newSrc; this.loadSource(this.source); }; @@ -326,18 +353,22 @@ * @param [scaleMode=scaleModes.DEFAULT] {number} See {@link scaleModes} for possible values * @return BaseTexture */ -BaseTexture.fromImage = function (imageUrl, crossorigin, scaleMode) { +BaseTexture.fromImage = function (imageUrl, crossorigin, scaleMode) +{ var baseTexture = utils.BaseTextureCache[imageUrl]; - if (crossorigin === undefined && imageUrl.indexOf('data:') !== 0) { + if (crossorigin === undefined && imageUrl.indexOf('data:') !== 0) + { crossorigin = true; } - if (!baseTexture) { + if (!baseTexture) + { // new Image() breaks tex loading in some versions of Chrome. // See https://code.google.com/p/chromium/issues/detail?id=238071 var image = new Image();//document.createElement('img'); - if (crossorigin) { + if (crossorigin) + { image.crossOrigin = ''; } @@ -347,7 +378,8 @@ utils.BaseTextureCache[imageUrl] = baseTexture; // if there is an @2x at the end of the url we are going to assume its a highres image - if ( imageUrl.indexOf(CONST.RETINA_PREFIX + '.') !== -1) { + if ( imageUrl.indexOf(CONST.RETINA_PREFIX + '.') !== -1) + { baseTexture.resolution = 2; } } @@ -363,14 +395,17 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return BaseTexture */ -BaseTexture.fromCanvas = function (canvas, scaleMode) { - if (!canvas._pixiId) { +BaseTexture.fromCanvas = function (canvas, scaleMode) +{ + if (!canvas._pixiId) + { canvas._pixiId = 'canvas_' + utils.uuid(); } var baseTexture = utils.BaseTextureCache[canvas._pixiId]; - if (!baseTexture) { + if (!baseTexture) + { baseTexture = new BaseTexture(canvas, scaleMode); utils.BaseTextureCache[canvas._pixiId] = baseTexture; } diff --git a/src/core/textures/RenderTexture.js b/src/core/textures/RenderTexture.js index 6dad20f..53ae796 100644 --- a/src/core/textures/RenderTexture.js +++ b/src/core/textures/RenderTexture.js @@ -46,8 +46,10 @@ * @param [scaleMode] {number} See {@link scaleModes} for possible values * @param [resolution=1] {number} The resolution of the texture being generated */ -function RenderTexture(renderer, width, height, scaleMode, resolution) { - if (!renderer) { +function RenderTexture(renderer, width, height, scaleMode, resolution) +{ + if (!renderer) + { throw new Error('Unable to create RenderTexture, you must pass a renderer into the constructor.'); } @@ -133,7 +135,8 @@ */ this.renderer = renderer; - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { var gl = this.renderer.gl; this.textureBuffer = new FilterTexture(gl, this.width * this.resolution, this.height * this.resolution, this.baseTexture.scaleMode); @@ -142,7 +145,8 @@ this.render = this.renderWebGL; this.projection = new math.Point(this.width*0.5, -this.height*0.5); } - else { + else + { this.render = this.renderCanvas; this.textureBuffer = new CanvasBuffer(this.width* this.resolution, this.height* this.resolution); this.baseTexture.source = this.textureBuffer.canvas; @@ -167,8 +171,10 @@ * @param height {number} The height to resize to. * @param updateBase {boolean} Should the baseTexture.width and height values be resized as well? */ -RenderTexture.prototype.resize = function (width, height, updateBase) { - if (width === this.width && height === this.height) { +RenderTexture.prototype.resize = function (width, height, updateBase) +{ + if (width === this.width && height === this.height) + { return; } @@ -177,17 +183,20 @@ this.width = this.frame.width = this.crop.width = width; this.height = this.frame.height = this.crop.height = height; - if (updateBase) { + if (updateBase) + { this.baseTexture.width = this.width; this.baseTexture.height = this.height; } - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { this.projection.x = this.width / 2; this.projection.y = -this.height / 2; } - if (!this.valid) { + if (!this.valid) + { return; } @@ -198,12 +207,15 @@ * Clears the RenderTexture. * */ -RenderTexture.prototype.clear = function () { - if (!this.valid) { +RenderTexture.prototype.clear = function () +{ + if (!this.valid) + { return; } - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { this.renderer.gl.bindFramebuffer(this.renderer.gl.FRAMEBUFFER, this.textureBuffer.frameBuffer); } @@ -220,19 +232,23 @@ * @param [restoreWorldTransform=true] {boolean} If true the displayObject's worldTransform/worldAlpha and all children * transformations will be restored. Not restoring this information will be a little faster. */ -RenderTexture.prototype.renderWebGL = function (displayObject, matrix, clear, restoreWorldTransform) { - if (!this.valid) { +RenderTexture.prototype.renderWebGL = function (displayObject, matrix, clear, restoreWorldTransform) +{ + if (!this.valid) + { return; } - if (typeof restoreWorldTransform === 'undefined') { + if (typeof restoreWorldTransform === 'undefined') + { restoreWorldTransform = true; } var tempAlpha, tempTransform; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { tempAlpha = displayObject.worldAlpha; tempTransform = displayObject.worldTransform.toArray(); } @@ -245,7 +261,8 @@ wt.identity(); wt.translate(0, this.projection.y * 2); - if (matrix) { + if (matrix) + { wt.append(matrix); } @@ -258,7 +275,8 @@ var children = displayObject.children; var i, j; - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } @@ -269,7 +287,8 @@ gl.bindFramebuffer(gl.FRAMEBUFFER, this.textureBuffer.frameBuffer ); - if (clear) { + if (clear) + { this.textureBuffer.clear(); } @@ -279,11 +298,13 @@ this.renderer.spriteBatch.dirty = true; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { displayObject.worldAlpha = tempAlpha; displayObject.worldTransform.fromArray(tempTransform); - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } } @@ -300,26 +321,31 @@ * @param [restoreWorldTransform=true] {boolean} If true the displayObject's worldTransform/worldAlpha and all children * transformations will be restored. Not restoring this information will be a little faster. */ -RenderTexture.prototype.renderCanvas = function (displayObject, matrix, clear, restoreWorldTransform) { - if (!this.valid) { +RenderTexture.prototype.renderCanvas = function (displayObject, matrix, clear, restoreWorldTransform) +{ + if (!this.valid) + { return; } - if (typeof restoreWorldTransform === 'undefined') { + if (typeof restoreWorldTransform === 'undefined') + { restoreWorldTransform = true; } var tempAlpha, tempTransform; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { tempAlpha = displayObject.worldAlpha; tempTransform = displayObject.worldTransform.toArray(); } var wt = displayObject.worldTransform; wt.identity(); - if (matrix) { + if (matrix) + { wt.append(matrix); } @@ -330,11 +356,13 @@ var children = displayObject.children; var i, j; - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } - if (clear) { + if (clear) + { this.textureBuffer.clear(); } @@ -348,11 +376,13 @@ this.renderer.resolution = realResolution; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { displayObject.worldAlpha = tempAlpha; displayObject.worldTransform.fromArray(tempTransform); - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } } @@ -363,7 +393,8 @@ * * @return {Image} */ -RenderTexture.prototype.getImage = function () { +RenderTexture.prototype.getImage = function () +{ var image = new Image(); image.src = this.getBase64(); return image; @@ -374,7 +405,8 @@ * * @return {string} A base64 encoded string of the texture. */ -RenderTexture.prototype.getBase64 = function () { +RenderTexture.prototype.getBase64 = function () +{ return this.getCanvas().toDataURL(); }; @@ -383,8 +415,10 @@ * * @return {HTMLCanvasElement} A Canvas element with the texture rendered on. */ -RenderTexture.prototype.getCanvas = function () { - if (this.renderer.type === CONST.WEBGL_RENDERER) { +RenderTexture.prototype.getCanvas = function () +{ + if (this.renderer.type === CONST.WEBGL_RENDERER) + { var gl = this.renderer.gl; var width = this.textureBuffer.width; var height = this.textureBuffer.height; @@ -403,7 +437,8 @@ return tempCanvas.canvas; } - else { + else + { return this.textureBuffer.canvas; } }; diff --git a/src/core/textures/Texture.js b/src/core/textures/Texture.js index 3c65909..e97f0aa 100644 --- a/src/core/textures/Texture.js +++ b/src/core/textures/Texture.js @@ -17,7 +17,8 @@ * @param [crop] {Rectangle} The area of original texture * @param [trim] {Rectangle} Trimmed texture rectangle */ -function Texture(baseTexture, frame, crop, trim) { +function Texture(baseTexture, frame, crop, trim) +{ /** * Does this Texture have any frame data assigned to it? * @@ -25,12 +26,14 @@ */ this.noFrame = false; - if (!frame) { + if (!frame) + { this.noFrame = true; frame = new math.Rectangle(0, 0, 1, 1); } - if (baseTexture instanceof Texture) { + if (baseTexture instanceof Texture) + { baseTexture = baseTexture.baseTexture; } @@ -100,13 +103,16 @@ */ this.crop = crop || new math.Rectangle(0, 0, 1, 1); - if (baseTexture.hasLoaded) { - if (this.noFrame) { + if (baseTexture.hasLoaded) + { + if (this.noFrame) + { frame = new math.Rectangle(0, 0, baseTexture.width, baseTexture.height); } this.frame = frame; } - else { + else + { baseTexture.addEventListener('loaded', this.onBaseTextureLoaded.bind(this)); } } @@ -118,19 +124,23 @@ Object.defineProperties(Texture.prototype, { needsUpdate: { - get: function () { + get: function () + { return this.baseTexture.needsUpdate; }, - set: function (val) { + set: function (val) + { this.baseTexture.needsUpdate = val; } }, frame: { - get: function () { + get: function () + { return this._frame; }, - set: function (frame) { + set: function (frame) + { this._frame = frame; this.noFrame = false; @@ -143,20 +153,23 @@ 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 (!this.trim && (frame.x + frame.width > this.baseTexture.width || frame.y + frame.height > this.baseTexture.height)) + { throw new Error('Texture Error: frame does not fit inside the base Texture dimensions ' + this); } this.valid = frame && frame.width && frame.height && this.baseTexture.source && this.baseTexture.hasLoaded; - if (this.trim) { + 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) { + if (this.valid) + { this._updateUvs(); } } @@ -168,11 +181,13 @@ * * @private */ -Texture.prototype.onBaseTextureLoaded = function () { +Texture.prototype.onBaseTextureLoaded = function () +{ var baseTexture = this.baseTexture; baseTexture.removeEventListener('loaded', this.onLoaded); - if (this.noFrame) { + if (this.noFrame) + { this.frame = new math.Rectangle(0, 0, baseTexture.width, baseTexture.height); } @@ -184,8 +199,10 @@ * * @param destroyBase {boolean} Whether to destroy the base texture as well */ -Texture.prototype.destroy = function (destroyBase) { - if (destroyBase) { +Texture.prototype.destroy = function (destroyBase) +{ + if (destroyBase) + { this.baseTexture.destroy(); } @@ -197,8 +214,10 @@ * * @private */ -Texture.prototype._updateUvs = function () { - if (!this._uvs) { +Texture.prototype._updateUvs = function () +{ + if (!this._uvs) + { this._uvs = new TextureUvs(); } @@ -229,10 +248,12 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return Texture */ -Texture.fromImage = function (imageUrl, crossorigin, scaleMode) { +Texture.fromImage = function (imageUrl, crossorigin, scaleMode) +{ var texture = utils.TextureCache[imageUrl]; - if (!texture) { + if (!texture) + { texture = new Texture(BaseTexture.fromImage(imageUrl, crossorigin, scaleMode)); utils.TextureCache[imageUrl] = texture; } @@ -248,9 +269,11 @@ * @param frameId {string} The frame id of the texture * @return Texture */ -Texture.fromFrame = function (frameId) { +Texture.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache '); } return texture; @@ -264,7 +287,8 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return {Texture} */ -Texture.fromCanvas = function (canvas, scaleMode) { +Texture.fromCanvas = function (canvas, scaleMode) +{ return new Texture(BaseTexture.fromCanvas(canvas, scaleMode)); }; @@ -276,7 +300,8 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return {Texture} A Texture */ -Texture.fromVideo = function (video, scaleMode) { +Texture.fromVideo = function (video, scaleMode) +{ return new Texture(VideoBaseTexture.baseTextureFromVideo(video, scaleMode)); }; @@ -287,7 +312,8 @@ * @param texture {Texture} The Texture to add to the cache. * @param id {string} The id that the texture will be stored against. */ -Texture.addTextureToCache = function (texture, id) { +Texture.addTextureToCache = function (texture, id) +{ utils.TextureCache[id] = texture; }; @@ -298,7 +324,8 @@ * @param id {string} The id of the texture to be removed * @return {Texture} The texture that was removed */ -Texture.removeTextureFromCache = function (id) { +Texture.removeTextureFromCache = function (id) +{ var texture = utils.TextureCache[id]; delete utils.TextureCache[id]; diff --git a/src/core/textures/TextureUvs.js b/src/core/textures/TextureUvs.js index b9bbb58..5424d52 100644 --- a/src/core/textures/TextureUvs.js +++ b/src/core/textures/TextureUvs.js @@ -1,4 +1,5 @@ -function TextureUvs() { +function TextureUvs() +{ this.x0 = 0; this.y0 = 0; diff --git a/src/core/textures/VideoBaseTexture.js b/src/core/textures/VideoBaseTexture.js index e3e0c5a..1a826a9 100644 --- a/src/core/textures/VideoBaseTexture.js +++ b/src/core/textures/VideoBaseTexture.js @@ -12,15 +12,18 @@ * @param source {HTMLVideoElement} * @param [scaleMode] {number} See {@link scaleModes} for possible values */ -function VideoBaseTexture(source, scaleMode) { - if (!source){ +function VideoBaseTexture(source, scaleMode) +{ + if (!source) + { throw new Error('No video source element specified.'); } // hook in here to check if video is already available. // BaseTexture looks for a source.complete boolean, plus width & height. - if ((source.readyState === source.HAVE_ENOUGH_DATA || source.readyState === source.HAVE_FUTURE_DATA) && source.width && source.height) { + if ((source.readyState === source.HAVE_ENOUGH_DATA || source.readyState === source.HAVE_FUTURE_DATA) && source.width && source.height) + { source.complete = true; } @@ -31,7 +34,8 @@ this._boundOnUpdate = this._onUpdate.bind(this); this._boundOnCanPlay = this._onCanPlay.bind(this); - if (!source.complete) { + if (!source.complete) + { source.addEventListener('canplay', this._boundOnCanPlay); source.addEventListener('canplaythrough', this._boundOnCanPlay); @@ -47,28 +51,35 @@ VideoBaseTexture.prototype.constructor = VideoBaseTexture; module.exports = VideoBaseTexture; -VideoBaseTexture.prototype._onUpdate = function () { - if (this.autoUpdate) { +VideoBaseTexture.prototype._onUpdate = function () +{ + if (this.autoUpdate) + { window.requestAnimationFrame(this._boundOnUpdate); this.needsUpdate = true; } }; -VideoBaseTexture.prototype._onPlayStart = function () { - if (!this.autoUpdate) { +VideoBaseTexture.prototype._onPlayStart = function () +{ + if (!this.autoUpdate) + { window.requestAnimationFrame(this._boundOnUpdate); this.autoUpdate = true; } }; -VideoBaseTexture.prototype._onPlayStop = function () { +VideoBaseTexture.prototype._onPlayStop = function () +{ this.autoUpdate = false; }; -VideoBaseTexture.prototype._onCanPlay = function () { +VideoBaseTexture.prototype._onCanPlay = function () +{ this.hasLoaded = true; - if (this.source) { + if (this.source) + { this.source.removeEventListener('canplay', this._boundOnCanPlay); this.source.removeEventListener('canplaythrough', this._boundOnCanPlay); @@ -78,15 +89,18 @@ this.source.play(); // prevent multiple loaded dispatches.. - if(!this.__loaded){ + if(!this.__loaded) + { this.__loaded = true; this.emit('loaded', this); } } }; -VideoBaseTexture.prototype.destroy = function () { - if (this.source && this.source._pixiId) { +VideoBaseTexture.prototype.destroy = function () +{ + if (this.source && this.source._pixiId) + { utils.BaseTextureCache[ this.source._pixiId ] = null; delete utils.BaseTextureCache[ this.source._pixiId ]; @@ -105,14 +119,17 @@ * @param scaleMode {number} See {@link scaleModes} for possible values * @return {VideoBaseTexture} */ -VideoBaseTexture.fromVideo = function (video, scaleMode) { - if (!video._pixiId) { +VideoBaseTexture.fromVideo = function (video, scaleMode) +{ + if (!video._pixiId) + { video._pixiId = 'video_' + utils.uuid(); } var baseTexture = utils.BaseTextureCache[video._pixiId]; - if (!baseTexture) { + if (!baseTexture) + { baseTexture = new VideoBaseTexture(video, scaleMode); utils.BaseTextureCache[ video._pixiId ] = baseTexture; } @@ -147,17 +164,21 @@ * @param scaleMode {number} See {@link scaleModes} for possible values * @return {VideoBaseTexture} */ -VideoBaseTexture.fromUrl = function (videoSrc, scaleMode) { +VideoBaseTexture.fromUrl = function (videoSrc, scaleMode) +{ var video = document.createElement('video'); // array of objects or strings - if (Array.isArray(videoSrc)) { - for (var i = 0; i < videoSrc.length; ++i) { + if (Array.isArray(videoSrc)) + { + for (var i = 0; i < videoSrc.length; ++i) + { video.appendChild(createSource(videoSrc.src || videoSrc, videoSrc.mime)); } } // single object or string - else { + else + { video.appendChild(createSource(videoSrc.src || videoSrc, videoSrc.mime)); } @@ -169,8 +190,10 @@ VideoBaseTexture.fromUrls = VideoBaseTexture.fromUrl; -function createSource(path, type) { - if (!type) { +function createSource(path, type) +{ + if (!type) + { type = 'video/' + path.substr(path.lastIndexOf('.') + 1); } diff --git a/src/core/utils/EventData.js b/src/core/utils/EventData.js index 5d55a22..8cdf701 100644 --- a/src/core/utils/EventData.js +++ b/src/core/utils/EventData.js @@ -7,7 +7,8 @@ * @param name {string} The string name of the event that was triggered * @param data {object} Arbitrary event data to pass along */ -function EventData(target, name, data) { +function EventData(target, name, data) +{ // for duck typing in the ".on()" function this.__isEventObject = true; @@ -71,7 +72,8 @@ * Stops the propagation of events up the scene graph (prevents bubbling). * */ -EventData.prototype.stopPropagation = function stopPropagation() { +EventData.prototype.stopPropagation = function stopPropagation() +{ this.stopped = true; }; @@ -79,6 +81,7 @@ * Stops the propagation of events to sibling listeners (no longer calls any listeners). * */ -EventData.prototype.stopImmediatePropagation = function stopImmediatePropagation() { +EventData.prototype.stopImmediatePropagation = function stopImmediatePropagation() +{ this.stoppedImmediate = true; }; diff --git a/src/core/utils/EventTarget.js b/src/core/utils/EventTarget.js index 7ae8820..671a151 100644 --- a/src/core/utils/EventTarget.js +++ b/src/core/utils/EventTarget.js @@ -13,14 +13,16 @@ * var em = new MyEmitter(); * em.emit('eventName', 'some data', 'some more data', {}, null, ...); */ -function eventTarget(obj) { +function eventTarget(obj) +{ /** * Return a list of assigned event listeners. * * @param eventName {string} The events that should be listed. * @return {Array} An array of listener functions */ - obj.listeners = function listeners(eventName) { + obj.listeners = function listeners(eventName) + { this._listeners = this._listeners || {}; return this._listeners[eventName] ? this._listeners[eventName].slice() : []; @@ -33,22 +35,26 @@ * @param eventName {string} The name of the event. * @return {boolean} Indication if we've emitted an event. */ - obj.emit = obj.dispatchEvent = function emit(eventName, data) { + obj.emit = obj.dispatchEvent = function emit(eventName, data) + { this._listeners = this._listeners || {}; // fast return when there are no listeners - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return; } //backwards compat with old method ".emit({ type: 'something' })" - if (typeof eventName === 'object') { + if (typeof eventName === 'object') + { data = eventName; eventName = eventName.type; } //ensure we are using a real pixi event - if (!data || data.__isEventObject !== true) { + if (!data || data.__isEventObject !== true) + { data = new EventData(this, eventName, data); } @@ -58,23 +64,27 @@ fn = listeners[0], i; - for (i = 0; i < length; fn = listeners[++i]) { + for (i = 0; i < length; fn = listeners[++i]) + { //call the event listener fn.call(this, data); //if "stopImmediatePropagation" is called, stop calling sibling events - if (data.stoppedImmediate) { + if (data.stoppedImmediate) + { return this; } } //if "stopPropagation" is called then don't bubble the event - if (data.stopped) { + if (data.stopped) + { return this; } //bubble this event up the scene graph - if (this.parent && this.parent.emit) { + if (this.parent && this.parent.emit) + { this.parent.emit.call(this.parent, eventName, data); } @@ -88,7 +98,8 @@ * @param eventName {string} Name of the event. * @param callback {Functon} fn Callback function. */ - obj.on = obj.addEventListener = function on(eventName, fn) { + obj.on = obj.addEventListener = function on(eventName, fn) + { this._listeners = this._listeners || {}; (this._listeners[eventName] = this._listeners[eventName] || []) @@ -103,11 +114,13 @@ * @param eventName {string} Name of the event. * @param callback {Function} Callback function. */ - obj.once = function once(eventName, fn) { + obj.once = function once(eventName, fn) + { this._listeners = this._listeners || {}; var self = this; - function onceHandlerWrapper() { + function onceHandlerWrapper() + { fn.apply(self.off(eventName, onceHandlerWrapper), arguments); } onceHandlerWrapper._originalHandler = fn; @@ -122,23 +135,28 @@ * @param eventName {string} The event we want to remove. * @param callback {Function} The listener that we need to find. */ - obj.off = obj.removeEventListener = function off(eventName, fn) { + obj.off = obj.removeEventListener = function off(eventName, fn) + { this._listeners = this._listeners || {}; - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return this; } var list = this._listeners[eventName], i = fn ? list.length : 0; - while(i-- > 0) { - if (list[i] === fn || list[i]._originalHandler === fn) { + while(i-- > 0) + { + if (list[i] === fn || list[i]._originalHandler === fn) + { list.splice(i, 1); } } - if (list.length === 0) { + if (list.length === 0) + { delete this._listeners[eventName]; } @@ -150,10 +168,12 @@ * * @param eventName {string} The event you want to remove all listeners for. */ - obj.removeAllListeners = function removeAllListeners(eventName) { + obj.removeAllListeners = function removeAllListeners(eventName) + { this._listeners = this._listeners || {}; - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return this; } @@ -169,7 +189,8 @@ * * @param object {object} The obj to mix into */ - mixin: function mixin(obj) { + mixin: function mixin(obj) + { eventTarget(obj); } }; diff --git a/src/core/utils/PolyK.js b/src/core/utils/PolyK.js index 7325141..5e20c2b 100644 --- a/src/core/utils/PolyK.js +++ b/src/core/utils/PolyK.js @@ -47,7 +47,8 @@ * Triangulates shapes for webGL graphic fills. * */ -PolyK.Triangulate = function (p) { +PolyK.Triangulate = function (p) +{ var sign = true; var n = p.length >> 1; @@ -59,7 +60,8 @@ i = 0; var al = n; - while(al > 3) { + while(al > 3) + { var i0 = avl[(i+0)%al]; var i1 = avl[(i+1)%al]; var i2 = avl[(i+2)%al]; @@ -69,29 +71,35 @@ var cx = p[2*i2], cy = p[2*i2+1]; var earFound = false; - if (PolyK._convex(ax, ay, bx, by, cx, cy, sign)) { + if (PolyK._convex(ax, ay, bx, by, cx, cy, sign)) + { earFound = true; - for (var j = 0; j < al; j++) { + for (var j = 0; j < al; j++) + { var vi = avl[j]; if (vi === i0 || vi === i1 || vi === i2) continue; - if (PolyK._PointInTriangle(p[2*vi], p[2*vi+1], ax, ay, bx, by, cx, cy)) { + if (PolyK._PointInTriangle(p[2*vi], p[2*vi+1], ax, ay, bx, by, cx, cy)) + { earFound = false; break; } } } - if (earFound) { + if (earFound) + { tgs.push(i0, i1, i2); avl.splice((i+1)%al, 1); al--; i = 0; } - else if (i++ > 3*al) { + else if (i++ > 3*al) + { // need to flip flip reverse it! // reset! - if (sign) { + if (sign) + { tgs = []; avl = []; for (i = 0; i < n; i++) avl.push(i); @@ -101,7 +109,8 @@ sign = false; } - else { + else + { // window.console.log("PIXI Warning: shape too complex to fill"); return null; } @@ -126,7 +135,8 @@ * @private * @return {boolean} */ -PolyK._PointInTriangle = function (px, py, ax, ay, bx, by, cx, cy) { +PolyK._PointInTriangle = function (px, py, ax, ay, bx, by, cx, cy) +{ var v0x = cx-ax; var v0y = cy-ay; var v1x = bx-ax; @@ -154,6 +164,7 @@ * @private * @return {boolean} */ -PolyK._convex = function (ax, ay, bx, by, cx, cy, sign) { +PolyK._convex = function (ax, ay, bx, by, cx, cy, sign) +{ return ((ay-by)*(cx-bx) + (bx-ax)*(cy-by) >= 0) === sign; }; diff --git a/src/core/utils/index.js b/src/core/utils/index.js index ade9831..bfae7ae 100644 --- a/src/core/utils/index.js +++ b/src/core/utils/index.js @@ -16,7 +16,8 @@ * * @return {number} The next uuid to use. */ - uuid: function () { + uuid: function () + { return ++utils._uid; }, @@ -26,7 +27,8 @@ * @param hex {number} * @return {number[]} An array representing the [R, G, B] of the color. */ - hex2rgb: function (hex, out) { + hex2rgb: function (hex, out) + { out = out || []; out[0] = (hex >> 16 & 0xFF) / 255; @@ -42,7 +44,8 @@ * @param hex {number} * @return {string} The string color. */ - hex2string: function (hex) { + hex2string: function (hex) + { hex = hex.toString(16); hex = '000000'.substr(0, 6 - hex.length) + hex; @@ -55,7 +58,8 @@ * @param rgb {number[]} * @return {number} The color number */ - rgb2hex: function (rgb) { + rgb2hex: function (rgb) + { return ((rgb[0]*255 << 16) + (rgb[1]*255 << 8) + rgb[2]*255); }, @@ -64,8 +68,10 @@ * * @return {boolean} whether they are supported */ - canUseNewCanvasBlendModes: function () { - if (typeof document === 'undefined') { + canUseNewCanvasBlendModes: function () + { + if (typeof document === 'undefined') + { return false; } @@ -93,15 +99,19 @@ * @param number {number} * @return {number} the closest number that is a power of two */ - getNextPowerOfTwo: function (number) { + getNextPowerOfTwo: function (number) + { // see: http://en.wikipedia.org/wiki/Power_of_two#Fast_algorithm_to_check_if_a_positive_number_is_a_power_of_two - if (number > 0 && (number & (number - 1)) === 0) { + if (number > 0 && (number & (number - 1)) === 0) + { return number; } - else { + else + { var result = 1; - while (result < number) { + while (result < number) + { result <<= 1; } @@ -116,7 +126,8 @@ * @param height {number} * @return {boolean} */ - isPowerOfTwo: function (width, height) { + isPowerOfTwo: function (width, height) + { return (width > 0 && (width & (width - 1)) === 0 && height > 0 && (height & (height - 1)) === 0); }, @@ -130,12 +141,15 @@ * @constant * @static */ - sayHello: function (type) { - if (utils._saidHello) { + sayHello: function (type) + { + if (utils._saidHello) + { return; } - if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) { + if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) + { var args = [ '%c %c %c Pixi.js ' + CONST.VERSION + ' - ' + type + ' %c ' + ' %c ' + ' http://www.pixijs.com/ %c %c ♥%c♥%c♥ ', 'background: #ff66a5', @@ -151,7 +165,8 @@ console.log.apply(console, args); //jshint ignore:line } - else if (window.console) { + else if (window.console) + { console.log('Pixi.js ' + CONST.VERSION + ' - ' + type + ' - http://www.pixijs.com/'); //jshint ignore:line } @@ -166,15 +181,19 @@ * @class * @namespace PIXI */ - AjaxRequest: function () { + AjaxRequest: function () + { var activexmodes = ['Msxml2.XMLHTTP.6.0', 'Msxml2.XMLHTTP.3.0', 'Microsoft.XMLHTTP']; //activeX versions to check for in IE - if (window.ActiveXObject) { //Test for support for ActiveXObject in IE first (as XMLHttpRequest in IE7 is broken) - for (var i=0; i= this.textures.length) { + else if (round >= this.textures.length) + { this.gotoAndStop(this.textures.length - 1); - if (this.onComplete) { + if (this.onComplete) + { this.onComplete(); } } @@ -167,10 +182,12 @@ * @static * @param frames {string[]} the array of frames ids the movieclip will use as its texture frames */ -MovieClip.fromFrames = function (frames) { +MovieClip.fromFrames = function (frames) +{ var textures = []; - for (var i = 0; i < frames.length; ++i) { + for (var i = 0; i < frames.length; ++i) + { textures.push(new core.Texture.fromFrame(frames[i])); } @@ -183,10 +200,12 @@ * @static * @param images {string[]} the array of image urls the movieclip will use as its texture frames */ -MovieClip.fromImages = function (images) { +MovieClip.fromImages = function (images) +{ var textures = []; - for (var i = 0; i < images.length; ++i) { + for (var i = 0; i < images.length; ++i) + { textures.push(new core.Texture.fromImage(images[i])); } diff --git a/src/extras/Rope.js b/src/extras/Rope.js index c157ec4..9c87bc0 100644 --- a/src/extras/Rope.js +++ b/src/extras/Rope.js @@ -9,7 +9,8 @@ * @param {Array} points - An array of {Point}. * */ -function Rope(texture, points) { +function Rope(texture, points) +{ Strip.call(this, texture); this.points = points; @@ -31,10 +32,12 @@ * Refreshes * */ -Rope.prototype.refresh = function () { +Rope.prototype.refresh = function () +{ var points = this.points; - if (points.length < 1) { + if (points.length < 1) + { return; } @@ -59,20 +62,23 @@ var total = points.length, point, index, amount; - for (var i = 1; i < total; i++) { + for (var i = 1; i < total; i++) + { point = points[i]; index = i * 4; // time to do some smart drawing! amount = i / (total-1); - if (i%2) { + if (i%2) + { uvs[index] = amount; uvs[index+1] = 0; uvs[index+2] = amount; uvs[index+3] = 1; } - else { + else + { uvs[index] = amount; uvs[index+1] = 0; @@ -95,10 +101,12 @@ * * @private */ -Rope.prototype.updateTransform = function () { +Rope.prototype.updateTransform = function () +{ var points = this.points; - if (points.length < 1) { + if (points.length < 1) + { return; } @@ -113,14 +121,17 @@ var total = points.length, point, index, ratio, perpLength, num; - for (var i = 0; i < total; i++) { + for (var i = 0; i < total; i++) + { point = points[i]; index = i * 4; - if (i < points.length-1) { + if (i < points.length-1) + { nextPoint = points[i+1]; } - else { + else + { nextPoint = point; } @@ -129,7 +140,8 @@ ratio = (1 - (i / (total-1))) * 10; - if (ratio > 1) { + if (ratio > 1) + { ratio = 1; } @@ -157,7 +169,8 @@ * * @param texture {Texture} the texture that will be used */ -Rope.prototype.setTexture = function (texture) { +Rope.prototype.setTexture = function (texture) +{ // stop current texture this.texture = texture; //this.updateFrame = true; diff --git a/src/extras/Strip.js b/src/extras/Strip.js index c5e378f..57691b5 100644 --- a/src/extras/Strip.js +++ b/src/extras/Strip.js @@ -10,7 +10,8 @@ * @param height {number} the height * */ -function Strip(texture) { +function Strip(texture) +{ core.DisplayObjectContainer.call(this); /** @@ -70,9 +71,11 @@ * * @param renderer {WebGLRenderer} */ -Strip.prototype.renderWebGL = function (renderer) { +Strip.prototype.renderWebGL = function (renderer) +{ // if the sprite is not visible or the alpha is 0 then no need to render this element - if (!this.visible || this.alpha <= 0) { + if (!this.visible || this.alpha <= 0) + { return; } @@ -81,7 +84,8 @@ renderer.spriteBatch.stop(); // init! init! - if (!this._vertexBuffer) { + if (!this._vertexBuffer) + { this._initWebGL(renderer); } @@ -96,7 +100,8 @@ //TODO check culling }; -Strip.prototype._initWebGL = function (renderer) { +Strip.prototype._initWebGL = function (renderer) +{ // build the strip! var gl = renderer.gl; @@ -118,7 +123,8 @@ gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this.indices, gl.STATIC_DRAW); }; -Strip.prototype._renderStrip = function (renderer) { +Strip.prototype._renderStrip = function (renderer) +{ var gl = renderer.gl; var projection = renderer.projection, offset = renderer.offset, @@ -137,7 +143,8 @@ gl.uniform2f(shader.offsetVector, -offset.x, -offset.y); gl.uniform1f(shader.alpha, this.worldAlpha); - if (!this.dirty) { + if (!this.dirty) + { gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexBuffer); gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); @@ -150,10 +157,12 @@ gl.activeTexture(gl.TEXTURE0); // check if a texture is dirty.. - if (this.texture.baseTexture._dirty[gl.id]) { + if (this.texture.baseTexture._dirty[gl.id]) + { renderer.updateTexture(this.texture.baseTexture); } - else { + else + { // bind the current texture gl.bindTexture(gl.TEXTURE_2D, this.texture.baseTexture._glTextures[gl.id]); } @@ -163,7 +172,8 @@ } - else { + else + { this.dirty = false; gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexBuffer); @@ -178,10 +188,12 @@ gl.activeTexture(gl.TEXTURE0); // check if a texture is dirty.. - if (this.texture.baseTexture._dirty[gl.id]) { + if (this.texture.baseTexture._dirty[gl.id]) + { renderer.updateTexture(this.texture.baseTexture); } - else { + else + { gl.bindTexture(gl.TEXTURE_2D, this.texture.baseTexture._glTextures[gl.id]); } @@ -203,27 +215,33 @@ * * @param renderer {CanvasRenderer} */ -Strip.prototype.renderCanvas = function (renderer) { +Strip.prototype.renderCanvas = function (renderer) +{ var context = renderer.context; var transform = this.worldTransform; - if (renderer.roundPixels) { + if (renderer.roundPixels) + { context.setTransform(transform.a, transform.b, transform.c, transform.d, transform.tx | 0, transform.ty | 0); } - else { + else + { context.setTransform(transform.a, transform.b, transform.c, transform.d, transform.tx, transform.ty); } - if (this.drawMode === Strip.DrawModes.TRIANGLE_STRIP) { + if (this.drawMode === Strip.DrawModes.TRIANGLE_STRIP) + { this._renderCanvasTriangleStrip(context); } - else { + else + { this._renderCanvasTriangles(context); } }; -Strip.prototype._renderCanvasTriangleStrip = function (context) { +Strip.prototype._renderCanvasTriangleStrip = function (context) +{ // draw triangles!! var vertices = this.vertices; var uvs = this.uvs; @@ -231,14 +249,16 @@ var length = vertices.length / 2; // this.count++; - for (var i = 0; i < length - 2; i++) { + for (var i = 0; i < length - 2; i++) + { // draw some triangles! var index = i * 2; this._renderCanvasDrawTriangle(context, vertices, uvs, index, (index + 2), (index + 4)); } }; -Strip.prototype._renderCanvasTriangles = function (context) { +Strip.prototype._renderCanvasTriangles = function (context) +{ // draw triangles!! var vertices = this.vertices; var uvs = this.uvs; @@ -247,14 +267,16 @@ var length = indices.length; // this.count++; - for (var i = 0; i < length; i += 3) { + for (var i = 0; i < length; i += 3) + { // draw some triangles! var index0 = indices[i] * 2, index1 = indices[i + 1] * 2, index2 = indices[i + 2] * 2; this._renderCanvasDrawTriangle(context, vertices, uvs, index0, index1, index2); } }; -Strip.prototype._renderCanvasDrawTriangle = function (context, vertices, uvs, index0, index1, index2) { +Strip.prototype._renderCanvasDrawTriangle = function (context, vertices, uvs, index0, index1, index2) +{ var textureSource = this.texture.baseTexture.source; var textureWidth = this.texture.width; var textureHeight = this.texture.height; @@ -265,7 +287,8 @@ var u0 = uvs[index0] * textureWidth, u1 = uvs[index1] * textureWidth, u2 = uvs[index2] * textureWidth; var v0 = uvs[index0 + 1] * textureHeight, v1 = uvs[index1 + 1] * textureHeight, v2 = uvs[index2 + 1] * textureHeight; - if (this.canvasPadding > 0) { + if (this.canvasPadding > 0) + { var paddingX = this.canvasPadding / this.worldTransform.a; var paddingY = this.canvasPadding / this.worldTransform.d; var centerX = (x0 + x1 + x2) / 3; @@ -332,7 +355,8 @@ * @param strip {Strip} The Strip to render * @private */ -Strip.prototype.renderStripFlat = function (strip) { +Strip.prototype.renderStripFlat = function (strip) +{ var context = this.context; var vertices = strip.vertices; @@ -340,7 +364,8 @@ // this.count++; context.beginPath(); - for (var i=1; i < length-2; i++) { + for (var i=1; i < length-2; i++) + { // draw some triangles! var index = i*2; @@ -358,7 +383,8 @@ }; /* -Strip.prototype.setTexture = function (texture) { +Strip.prototype.setTexture = function (texture) +{ //TODO SET THE TEXTURES //TODO VISIBILITY @@ -377,7 +403,8 @@ * @private */ -Strip.prototype.onTextureUpdate = function () { +Strip.prototype.onTextureUpdate = function () +{ this.updateFrame = true; }; @@ -387,7 +414,8 @@ * @param matrix {Matrix} the transformation matrix of the sprite * @return {Rectangle} the framing rectangle */ -Strip.prototype.getBounds = function (matrix) { +Strip.prototype.getBounds = function (matrix) +{ var worldTransform = matrix || this.worldTransform; var a = worldTransform.a; @@ -404,7 +432,8 @@ var minY = Infinity; var vertices = this.vertices; - for (var i = 0, n = vertices.length; i < n; i += 2) { + for (var i = 0, n = vertices.length; i < n; i += 2) + { var rawX = vertices[i], rawY = vertices[i + 1]; var x = (a * rawX) + (c * rawY) + tx; var y = (d * rawY) + (b * rawX) + ty; @@ -416,7 +445,8 @@ maxY = y > maxY ? y : maxY; } - if (minX === -Infinity || maxY === Infinity) { + if (minX === -Infinity || maxY === Infinity) + { return core.math.Rectangle.EMPTY; } diff --git a/src/extras/TilingSprite.js b/src/extras/TilingSprite.js index 3ac22df..31da393 100644 --- a/src/extras/TilingSprite.js +++ b/src/extras/TilingSprite.js @@ -10,7 +10,8 @@ * @param width {number} the width of the tiling sprite * @param height {number} the height of the tiling sprite */ -function TilingSprite(texture, width, height) { +function TilingSprite(texture, width, height) +{ core.Sprite.call( this, texture); /** @@ -86,10 +87,12 @@ * @memberof TilingSprite# */ width: { - get: function () { + get: function () + { return this._width; }, - set: function (value) { + set: function (value) + { this._width = value; } }, @@ -101,20 +104,25 @@ * @memberof TilingSprite# */ height: { - get: function () { + get: function () + { return this._height; }, - set: function (value) { + set: function (value) + { this._height = value; } }, texture: { - get: function () { + get: function () + { return this._texture; }, - set: function (value) { - if (this._texture === value) { + set: function (value) + { + if (this._texture === value) + { return; } @@ -130,51 +138,61 @@ * * @param renderer {WebGLRenderer} */ -TilingSprite.prototype.renderWebGL = function (renderer) { - if (!this.visible || this.alpha <= 0) { +TilingSprite.prototype.renderWebGL = function (renderer) +{ + if (!this.visible || this.alpha <= 0) + { return; } var i, j; - if (this._mask) { + if (this._mask) + { renderer.spriteBatch.stop(); renderer.maskManager.pushMask(this.mask, renderer); renderer.spriteBatch.start(); } - if (this._filters) { + if (this._filters) + { renderer.spriteBatch.flush(); renderer.filterManager.pushFilter(this._filterBlock); } - if (!this.tilingTexture || this.refreshTexture) { + if (!this.tilingTexture || this.refreshTexture) + { this.generateTilingTexture(true); - if (this.tilingTexture && this.tilingTexture.needsUpdate) { + if (this.tilingTexture && this.tilingTexture.needsUpdate) + { //TODO - tweaking renderer.updateTexture(this.tilingTexture.baseTexture); this.tilingTexture.needsUpdate = false; // this.tilingTexture._uvs = null; } } - else { + else + { renderer.spriteBatch.renderTilingSprite(this); } // simple render children! - for (i=0,j=this.children.length; i= 0 && index <= this.children.length) { - if (child.parent) { + if (index >= 0 && index <= this.children.length) + { + if (child.parent) + { child.parent.removeChild(child); } @@ -154,7 +173,8 @@ return child; } - else { + else + { throw new Error(child + 'addChildAt: The index '+ index +' supplied is out of bounds ' + this.children.length); } }; @@ -165,15 +185,18 @@ * @param child {DisplayObject} * @param child2 {DisplayObject} */ -DisplayObjectContainer.prototype.swapChildren = function (child, child2) { - if (child === child2) { +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) { + if (index1 < 0 || index2 < 0) + { throw new Error('swapChildren: Both the supplied DisplayObjects must be a child of the caller.'); } @@ -187,10 +210,12 @@ * @param child {DisplayObject} The DisplayObject instance to identify * @return {Number} The index position of the child display object to identify */ -DisplayObjectContainer.prototype.getChildIndex = function (child) { +DisplayObjectContainer.prototype.getChildIndex = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { throw new Error('The supplied DisplayObject must be a child of the caller'); } @@ -203,8 +228,10 @@ * @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 */ -DisplayObjectContainer.prototype.setChildIndex = function (child, index) { - if (index < 0 || index >= this.children.length) { +DisplayObjectContainer.prototype.setChildIndex = function (child, index) +{ + if (index < 0 || index >= this.children.length) + { throw new Error('The supplied index is out of bounds'); } @@ -220,8 +247,10 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child at the given index, if any. */ -DisplayObjectContainer.prototype.getChildAt = function (index) { - if (index < 0 || index >= this.children.length) { +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'); } @@ -234,10 +263,12 @@ * @param child {DisplayObject} The DisplayObject to remove * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChild = function (child) { +DisplayObjectContainer.prototype.removeChild = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { return; } @@ -250,7 +281,8 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChildAt = function (index) { +DisplayObjectContainer.prototype.removeChildAt = function (index) +{ var child = this.getChildAt(index); child.parent = null; @@ -265,24 +297,29 @@ * @param beginIndex {Number} The beginning position. Default value is 0. * @param endIndex {Number} The ending position. Default value is size of the container. */ -DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) { +DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) +{ var begin = beginIndex || 0; var end = typeof endIndex === 'number' ? endIndex : this.children.length; var range = end - begin; - if (range > 0 && range <= end) { + if (range > 0 && range <= end) + { var removed = this.children.splice(begin, range); - for (var i = 0; i < removed.length; ++i) { + for (var i = 0; i < removed.length; ++i) + { removed[i].parent = null; } return removed; } - else if (range === 0 && this.children.length === 0) { + else if (range === 0 && this.children.length === 0) + { return []; } - else { + else + { throw new RangeError('removeChildren: numeric values are outside the acceptable range.'); } }; @@ -291,7 +328,8 @@ * Generates and updates the cached sprite for this object. * */ -DisplayObjectContainer.prototype.updateCachedSprite = function () { +DisplayObjectContainer.prototype.updateCachedSprite = function () +{ this._generateCachedSprite(); }; @@ -304,7 +342,8 @@ * @param renderer {CanvasRenderer|WebGLRenderer} The renderer used to generate the texture. * @return {Texture} a texture of the graphics object */ -DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) { +DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) +{ var bounds = this.getLocalBounds(); var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0, renderer, scaleMode, resolution); @@ -322,18 +361,22 @@ * * @private */ -DisplayObjectContainer.prototype.updateTransform = function () { - if (!this.visible) { +DisplayObjectContainer.prototype.updateTransform = function () +{ + if (!this.visible) + { return; } this.displayObjectUpdateTransform(); - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { return; } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } }; @@ -346,8 +389,10 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getBounds = function () { - if (this.children.length === 0) { +DisplayObjectContainer.prototype.getBounds = function () +{ + if (this.children.length === 0) + { return math.Rectangle.EMPTY; } @@ -365,10 +410,12 @@ var childVisible = false; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -386,7 +433,8 @@ maxY = maxY > childMaxY ? maxY : childMaxY; } - if (!childVisible) { + if (!childVisible) + { return math.Rectangle.EMPTY; } @@ -407,12 +455,14 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getLocalBounds = function () { +DisplayObjectContainer.prototype.getLocalBounds = function () +{ var matrixCache = this.worldTransform; this.worldTransform = math.Matrix.IDENTITY; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } @@ -428,13 +478,16 @@ * * @param renderer {WebGLRenderer} The renderer */ -DisplayObjectContainer.prototype.renderWebGL = function (renderer) { +DisplayObjectContainer.prototype.renderWebGL = function (renderer) +{ // if the object is not visible or the alpha is 0 then no need to render this element - if (!this.visible || this.alpha <= 0) { + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } @@ -442,14 +495,17 @@ var i, j; // do a quick check to see if this element has a mask or a filter. - if (this._mask || this._filters) { + if (this._mask || this._filters) + { // push filter first as we need to ensure the stencil buffer is correct for any masking - if (this._filters) { + if (this._filters) + { renderer.spriteBatch.flush(); renderer.filterManager.pushFilter(this._filterBlock); } - if (this._mask) { + if (this._mask) + { renderer.spriteBatch.stop(); renderer.maskManager.pushMask(this.mask, renderer); renderer.spriteBatch.start(); @@ -459,36 +515,42 @@ this._renderWebGL(renderer); // now loop through the children and make sure they get rendered - for (i = 0, j = this.children.length; i < j; i++) { + for (i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderWebGL(renderer); } // time to stop the sprite batch as either a mask element or a filter draw will happen next renderer.spriteBatch.stop(); - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(this._mask, renderer); } - if (this._filters) { + if (this._filters) + { renderer.filterManager.popFilter(); } renderer.spriteBatch.start(); } - else { + else + { this._renderWebGL(renderer); // simple render children! - for (i = 0, j = this.children.length; i < j; ++i) { + for (i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderWebGL(renderer); } } }; -DisplayObjectContainer.prototype._renderWebGL = function (renderer) { +DisplayObjectContainer.prototype._renderWebGL = function (renderer) +{ // this is where content itself gets renderd.. @@ -499,25 +561,31 @@ * * @param renderer {CanvasRenderer} The renderer */ -DisplayObjectContainer.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0) { +DisplayObjectContainer.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -528,13 +596,16 @@ * @param renderer {WebGLRenderer|CanvasRenderer} The renderer * @private */ -DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) { +DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) +{ this._cachedSprite.worldAlpha = this.worldAlpha; - if (renderer.gl) { + if (renderer.gl) + { this._cachedSprite.renderWebGL(renderer); } - else { + else + { this._cachedSprite.renderCanvas(renderer); } }; @@ -544,10 +615,12 @@ * * @private */ -DisplayObjectContainer.prototype._generateCachedSprite = function () { +DisplayObjectContainer.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { // TODO - RenderTexture now *requires* a renderer instance, so this is like broken // because `renderer` isn't actually in scope here :P var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0); @@ -555,7 +628,8 @@ this._cachedSprite = new Sprite(renderTexture); this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.texture.resize(bounds.width | 0, bounds.height | 0); } @@ -580,8 +654,10 @@ * * @private */ -DisplayObjectContainer.prototype._destroyCachedSprite = function () { - if (!this._cachedSprite) { +DisplayObjectContainer.prototype._destroyCachedSprite = function () +{ + if (!this._cachedSprite) + { return; } diff --git a/src/core/display/Sprite.js b/src/core/display/Sprite.js index 707da24..5862aef 100644 --- a/src/core/display/Sprite.js +++ b/src/core/display/Sprite.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param texture {Texture} The texture for this sprite */ -function Sprite(texture) { +function Sprite(texture) +{ DisplayObjectContainer.call(this); /** @@ -85,12 +86,14 @@ this.texture = texture || Texture.EMPTY; } -Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) { +Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) +{ DisplayObjectContainer.prototype.destroy.call(this); this.anchor = null; - if (destroyTexture) { + if (destroyTexture) + { this._texture.destroy(destroyBaseTexture); } @@ -111,10 +114,12 @@ * @memberof Sprite# */ width: { - get: function () { + get: function () + { return this.scale.x * this.texture.frame.width; }, - set: function (value) { + set: function (value) + { this.scale.x = value / this.texture.frame.width; this._width = value; } @@ -127,10 +132,12 @@ * @memberof Sprite# */ height: { - get: function () { + get: function () + { return this.scale.y * this.texture.frame.height; }, - set: function (value) { + set: function (value) + { this.scale.y = value / this.texture.frame.height; this._height = value; } @@ -143,23 +150,29 @@ * @memberof Sprite# */ texture: { - get: function () { + get: function () + { return this._texture; }, - set: function (value) { - if (this._texture === value) { + set: function (value) + { + if (this._texture === value) + { return; } this._texture = value; this.cachedTint = 0xFFFFFF; - if (value) { + if (value) + { // wait for the texture to load - if (value.baseTexture.hasLoaded) { + if (value.baseTexture.hasLoaded) + { this._onTextureUpdate(); } - else { + else + { value.once('update', this._onTextureUpdate.bind(this)); } } @@ -172,18 +185,22 @@ * * @private */ -Sprite.prototype._onTextureUpdate = function () { +Sprite.prototype._onTextureUpdate = function () +{ // so if _width is 0 then width was not set.. - if (this._width) { + if (this._width) + { this.scale.x = this._width / this.texture.frame.width; } - if (this._height) { + if (this._height) + { this.scale.y = this._height / this.texture.frame.height; } }; -Sprite.prototype._renderWebGL = function (renderer) { +Sprite.prototype._renderWebGL = function (renderer) +{ // this is where content gets renderd.. // watch this space for a little render state manager.. @@ -197,7 +214,8 @@ * @param matrix {Matrix} the transformation matrix of the sprite * @return {Rectangle} the framing rectangle */ -Sprite.prototype.getBounds = function (matrix) { +Sprite.prototype.getBounds = function (matrix) +{ var width = this.texture.frame.width; var height = this.texture.frame.height; @@ -224,11 +242,13 @@ if(b === 0 && c === 0) { // scale may be negative! - if (a < 0) { + if (a < 0) + { a *= -1; } - if (d < 0) { + if (d < 0) + { d *= -1; } @@ -293,28 +313,34 @@ * * @param renderer {CanvasRenderer} The renderer */ -Sprite.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) { +Sprite.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) + { return; } - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; renderer.context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } // Ignore null sources - if (this.texture.valid) { + if (this.texture.valid) + { var resolution = this.texture.baseTexture.resolution / renderer.resolution; renderer.context.globalAlpha = this.worldAlpha; // If smoothingEnabled is supported and we need to change the smoothing property for this texture - if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) { + if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) + { renderer.scaleMode = this.texture.baseTexture.scaleMode; renderer.context[renderer.smoothProperty] = (renderer.scaleMode === CONST.scaleModes.LINEAR); } @@ -324,7 +350,8 @@ var dy = (this.texture.trim ? this.texture.trim.y : 0) - (this.anchor.y * this.texture.trim.height); // Allow for pixel rounding - if (renderer.roundPixels) { + if (renderer.roundPixels) + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -337,7 +364,8 @@ dx = dx | 0; dy = dy | 0; } - else { + else + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -348,8 +376,10 @@ ); } - if (this.tint !== 0xFFFFFF) { - if (this.cachedTint !== this.tint) { + if (this.tint !== 0xFFFFFF) + { + if (this.cachedTint !== this.tint) + { this.cachedTint = this.tint; // TODO clean up caching - how to clean up the caches? @@ -368,7 +398,8 @@ this.texture.crop.height / resolution ); } - else { + else + { renderer.context.drawImage( this.texture.baseTexture.source, this.texture.crop.x, @@ -383,11 +414,13 @@ } } - for (var i = 0, j = this.children.length; i < j; i++) { + for (var i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -402,10 +435,12 @@ * @param frameId {String} The frame Id of the texture in the cache * @return {Sprite} A new Sprite using a texture from the texture cache matching the frameId */ -Sprite.fromFrame = function (frameId) { +Sprite.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache' + this); } @@ -420,6 +455,7 @@ * @param imageId {String} The image url of the texture * @return {Sprite} A new Sprite using a texture from the texture cache matching the image id */ -Sprite.fromImage = function (imageId, crossorigin, scaleMode) { +Sprite.fromImage = function (imageId, crossorigin, scaleMode) +{ return new Sprite(Texture.fromImage(imageId, crossorigin, scaleMode)); }; diff --git a/src/core/display/SpriteBatch.js b/src/core/display/SpriteBatch.js index 3187777..c196fef 100644 --- a/src/core/display/SpriteBatch.js +++ b/src/core/display/SpriteBatch.js @@ -12,7 +12,8 @@ * ```js * var container = new SpriteBatch(); * - * for(var i = 0; i < 100; ++i) { + * for(var i = 0; i < 100; ++i) + * { * var sprite = new PIXI.Sprite.fromImage("myImage.png"); * container.addChild(sprite); * } @@ -25,7 +26,8 @@ */ //TODO RENAME to PARTICLE CONTAINER? -function SpriteBatch() { +function SpriteBatch() +{ DisplayObjectContainer.call(this); } @@ -38,7 +40,8 @@ * * @private */ -SpriteBatch.prototype.updateTransform = function () { +SpriteBatch.prototype.updateTransform = function () +{ // TODO don't need to! this.displayObjectUpdateTransform(); // PIXI.DisplayObjectContainer.prototype.updateTransform.call( this ); @@ -50,8 +53,10 @@ * @param renderer {WebGLRenderer} The webgl renderer * @private */ -SpriteBatch.prototype.renderWebGL = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderWebGL = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -71,8 +76,10 @@ * @param renderer {CanvasRenderer} The canvas renderer * @private */ -SpriteBatch.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -84,10 +91,12 @@ this.displayObjectUpdateTransform(); - for (var i = 0; i < this.children.length; ++i) { + for (var i = 0; i < this.children.length; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -95,9 +104,11 @@ context.globalAlpha = this.worldAlpha * child.alpha; - if (child.rotation % (Math.PI * 2) === 0) { + if (child.rotation % (Math.PI * 2) === 0) + { // this is the fastest way to optimise! - if rotation is 0 then we can avoid any kind of setTransform call - if (isRotated) { + if (isRotated) + { context.setTransform( transform.a, transform.b, @@ -122,8 +133,10 @@ frame.height * child.scale.y ); } - else { - if (!isRotated) { + else + { + if (!isRotated) + { isRotated = true; } @@ -131,7 +144,8 @@ var childTransform = child.worldTransform; - if (renderer.roundPixels) { + if (renderer.roundPixels) + { context.setTransform( childTransform.a, childTransform.b, @@ -141,7 +155,8 @@ childTransform.ty | 0 ); } - else { + else + { context.setTransform( childTransform.a, childTransform.b, diff --git a/src/core/index.js b/src/core/index.js index 3954b6f..eb4a82b 100644 --- a/src/core/index.js +++ b/src/core/index.js @@ -58,11 +58,13 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRenderer: function (width, height, options, noWebGL) { + autoDetectRenderer: function (width, height, options, noWebGL) + { width = width || 800; height = height || 600; - if (!noWebGL && require('webgl-enabled')()) { + if (!noWebGL && require('webgl-enabled')()) + { return new core.WebGLRenderer(width, height, options); } @@ -87,7 +89,8 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRecommendedRenderer: function (width, height, options) { + autoDetectRecommendedRenderer: function (width, height, options) + { var isAndroid = /Android/i.test(navigator.userAgent); return core.autoDetectRenderer(width, height, options, isAndroid); diff --git a/src/core/math/Matrix.js b/src/core/math/Matrix.js index c2f87e2..2ff4848 100644 --- a/src/core/math/Matrix.js +++ b/src/core/math/Matrix.js @@ -10,7 +10,8 @@ * @class * @namespace PIXI */ -function Matrix() { +function Matrix() +{ /** * @member {number} * @default 1 @@ -63,7 +64,8 @@ * * @param array {number[]} The array that the matrix will be populated from. */ -Matrix.prototype.fromArray = function (array) { +Matrix.prototype.fromArray = function (array) +{ this.a = array[0]; this.b = array[1]; this.c = array[3]; @@ -78,14 +80,17 @@ * @param transpose {boolean} Whether we need to transpose the matrix or not * @return {number[]} the newly created array which contains the matrix */ -Matrix.prototype.toArray = function (transpose) { - if (!this.array) { +Matrix.prototype.toArray = function (transpose) +{ + if (!this.array) + { this.array = new Float32Array(9); } var array = this.array; - if (transpose) { + if (transpose) + { array[0] = this.a; array[1] = this.b; array[2] = 0; @@ -96,7 +101,8 @@ array[7] = this.ty; array[8] = 1; } - else { + else + { array[0] = this.a; array[1] = this.c; array[2] = this.tx; @@ -119,7 +125,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, transformed through this matrix */ -Matrix.prototype.apply = function (pos, newPos) { +Matrix.prototype.apply = function (pos, newPos) +{ newPos = newPos || new Point(); newPos.x = this.a * pos.x + this.c * pos.y + this.tx; @@ -136,7 +143,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, inverse-transformed through this matrix */ -Matrix.prototype.applyInverse = function (pos, newPos) { +Matrix.prototype.applyInverse = function (pos, newPos) +{ newPos = newPos || new Point(); var id = 1 / (this.a * this.d + this.c * -this.b); @@ -154,7 +162,8 @@ * @param {number} y * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.translate = function (x, y) { +Matrix.prototype.translate = function (x, y) +{ this.tx += x; this.ty += y; @@ -168,7 +177,8 @@ * @param {number} y The amount to scale vertically * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.scale = function (x, y) { +Matrix.prototype.scale = function (x, y) +{ this.a *= x; this.d *= y; this.c *= x; @@ -186,7 +196,8 @@ * @param {number} angle - The angle in radians. * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.rotate = function (angle) { +Matrix.prototype.rotate = function (angle) +{ var cos = Math.cos( angle ); var sin = Math.sin( angle ); @@ -210,7 +221,8 @@ * @param {Matrix} matrix * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.append = function (matrix) { +Matrix.prototype.append = function (matrix) +{ var a1 = this.a; var b1 = this.b; var c1 = this.c; @@ -232,7 +244,8 @@ * * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.identity = function () { +Matrix.prototype.identity = function () +{ this.a = 1; this.b = 0; this.c = 0; diff --git a/src/core/math/Point.js b/src/core/math/Point.js index 7565b2d..632f346 100644 --- a/src/core/math/Point.js +++ b/src/core/math/Point.js @@ -7,7 +7,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -function Point(x, y) { +function Point(x, y) +{ /** * @member {number} * @default 0 @@ -29,7 +30,8 @@ * * @return {Point} a copy of the point */ -Point.prototype.clone = function () { +Point.prototype.clone = function () +{ return new Point(this.x, this.y); }; @@ -40,7 +42,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -Point.prototype.set = function (x, y) { +Point.prototype.set = function (x, y) +{ this.x = x || 0; this.y = y || ( (y !== 0) ? this.x : 0 ) ; }; diff --git a/src/core/math/shapes/Circle.js b/src/core/math/shapes/Circle.js index 69cfdc9..4d76efc 100644 --- a/src/core/math/shapes/Circle.js +++ b/src/core/math/shapes/Circle.js @@ -10,7 +10,8 @@ * @param y {number} The Y coordinate of the center of this circle * @param radius {number} The radius of the circle */ -function Circle(x, y, radius) { +function Circle(x, y, radius) +{ /** * @member {number} * @default 0 @@ -46,7 +47,8 @@ * @method clone * @return {Circle} a copy of the Circle */ -Circle.prototype.clone = function () { +Circle.prototype.clone = function () +{ return new Circle(this.x, this.y, this.radius); }; @@ -58,8 +60,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Circle */ -Circle.prototype.contains = function (x, y) { - if (this.radius <= 0) { +Circle.prototype.contains = function (x, y) +{ + if (this.radius <= 0) + { return false; } @@ -79,6 +83,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Circle.prototype.getBounds = function () { +Circle.prototype.getBounds = function () +{ return new Rectangle(this.x - this.radius, this.y - this.radius, this.radius * 2, this.radius * 2); }; diff --git a/src/core/math/shapes/Ellipse.js b/src/core/math/shapes/Ellipse.js index 4f2d066..fefd01a 100644 --- a/src/core/math/shapes/Ellipse.js +++ b/src/core/math/shapes/Ellipse.js @@ -11,7 +11,8 @@ * @param width {number} The half width of this ellipse * @param height {number} The half height of this ellipse */ -function Ellipse(x, y, width, height) { +function Ellipse(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -53,7 +54,8 @@ * @method clone * @return {Ellipse} a copy of the ellipse */ -Ellipse.prototype.clone = function () { +Ellipse.prototype.clone = function () +{ return new Ellipse(this.x, this.y, this.width, this.height); }; @@ -65,8 +67,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coords are within this ellipse */ -Ellipse.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Ellipse.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } @@ -86,6 +90,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Ellipse.prototype.getBounds = function () { +Ellipse.prototype.getBounds = function () +{ return new Rectangle(this.x - this.width, this.y - this.height, this.width, this.height); }; diff --git a/src/core/math/shapes/Polygon.js b/src/core/math/shapes/Polygon.js index ae89148..fea6d37 100644 --- a/src/core/math/shapes/Polygon.js +++ b/src/core/math/shapes/Polygon.js @@ -10,16 +10,20 @@ * arguments passed can be flat x,y values e.g. `new Polygon(x,y, x,y, x,y, ...)` where `x` and `y` are * Numbers. */ -function Polygon(points) { +function Polygon(points) +{ //if points isn't an array, use arguments as the array - if (!(points instanceof Array)) { + if (!(points instanceof Array)) + { points = Array.prototype.slice.call(arguments); } //if this is a flat array of numbers, convert it to points - if (points[0] instanceof Point) { + if (points[0] instanceof Point) + { var p = []; - for (var i = 0, il = points.length; i < il; i++) { + for (var i = 0, il = points.length; i < il; i++) + { p.push(points[i].x, points[i].y); } @@ -51,7 +55,8 @@ * * @return {Polygon} a copy of the polygon */ -Polygon.prototype.clone = function () { +Polygon.prototype.clone = function () +{ return new Polygon(this.points.slice()); }; @@ -62,19 +67,22 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this polygon */ -Polygon.prototype.contains = function (x, y) { +Polygon.prototype.contains = function (x, y) +{ var inside = false; // use some raycasting to test hits // https://github.com/substack/point-in-polygon/blob/master/index.js var length = this.points.length / 2; - for (var i = 0, j = length - 1; i < length; j = i++) { + for (var i = 0, j = length - 1; i < length; j = i++) + { var xi = this.points[i * 2], yi = this.points[i * 2 + 1], xj = this.points[j * 2], yj = this.points[j * 2 + 1], intersect = ((yi > y) !== (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi); - if (intersect) { + if (intersect) + { inside = !inside; } } diff --git a/src/core/math/shapes/Rectangle.js b/src/core/math/shapes/Rectangle.js index 16ac62a..4008b68 100644 --- a/src/core/math/shapes/Rectangle.js +++ b/src/core/math/shapes/Rectangle.js @@ -10,7 +10,8 @@ * @param width {number} The overall width of this rectangle * @param height {number} The overall height of this rectangle */ -function Rectangle(x, y, width, height) { +function Rectangle(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -60,7 +61,8 @@ * * @return {Rectangle} a copy of the rectangle */ -Rectangle.prototype.clone = function () { +Rectangle.prototype.clone = function () +{ return new Rectangle(this.x, this.y, this.width, this.height); }; @@ -71,13 +73,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rectangle */ -Rectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Rectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/math/shapes/RoundedRectangle.js b/src/core/math/shapes/RoundedRectangle.js index 27d286e..7bf6411 100644 --- a/src/core/math/shapes/RoundedRectangle.js +++ b/src/core/math/shapes/RoundedRectangle.js @@ -11,7 +11,8 @@ * @param height {number} The overall height of this rounded rectangle * @param radius {number} Controls the radius of the rounded corners */ -function RoundedRectangle(x, y, width, height, radius) { +function RoundedRectangle(x, y, width, height, radius) +{ /** * @member {number} * @default 0 @@ -58,7 +59,8 @@ * * @return {RoundedRectangle} a copy of the rounded rectangle */ -RoundedRectangle.prototype.clone = function () { +RoundedRectangle.prototype.clone = function () +{ return new RoundedRectangle(this.x, this.y, this.width, this.height, this.radius); }; @@ -69,13 +71,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rounded Rectangle */ -RoundedRectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +RoundedRectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/primitives/Graphics.js b/src/core/primitives/Graphics.js index 261c534..e902d2a 100644 --- a/src/core/primitives/Graphics.js +++ b/src/core/primitives/Graphics.js @@ -16,7 +16,8 @@ * @extends DisplayObjectContainer * @namespace PIXI */ -function Graphics() { +function Graphics() +{ DisplayObjectContainer.call(this); this.renderable = true; @@ -154,16 +155,20 @@ * @private */ cacheAsBitmap: { - get: function () { + get: function () + { return this._cacheAsBitmap; }, - set: function (value) { + set: function (value) + { this._cacheAsBitmap = value; - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._generateCachedSprite(); } - else { + else + { this.destroyCachedSprite(); this.dirty = true; } @@ -176,7 +181,8 @@ * * @return {Graphics} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ var clone = new Graphics(); clone.renderable = this.renderable; @@ -192,7 +198,8 @@ clone.cachedSpriteDirty = this.cachedSpriteDirty; // copy graphics data - for (var i = 0; i < this.graphicsData.length; ++i) { + for (var i = 0; i < this.graphicsData.length; ++i) + { clone.graphicsData.push(this.graphicsData.clone()); } @@ -211,17 +218,21 @@ * @param alpha {number} alpha of the line to draw, will update the objects stored style * @return {Graphics} */ -Graphics.prototype.lineStyle = function (lineWidth, color, alpha) { +Graphics.prototype.lineStyle = function (lineWidth, color, alpha) +{ this.lineWidth = lineWidth || 0; this.lineColor = color || 0; this.lineAlpha = (arguments.length < 3) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length) + { // halfway through a line? start a new one! this.drawShape( new math.Polygon( this.currentPath.shape.points.slice(-2) )); } - else { + else + { // otherwise its empty so lets just set the line properties this.currentPath.lineWidth = this.lineWidth; this.currentPath.lineColor = this.lineColor; @@ -239,7 +250,8 @@ * @param y {number} the Y coordinate to move to * @return {Graphics} */ -Graphics.prototype.moveTo = function (x, y) { +Graphics.prototype.moveTo = function (x, y) +{ this.drawShape(new math.Polygon([x,y])); return this; @@ -253,7 +265,8 @@ * @param y {number} the Y coordinate to draw to * @return {Graphics} */ -Graphics.prototype.lineTo = function (x, y) { +Graphics.prototype.lineTo = function (x, y) +{ this.currentPath.shape.points.push(x, y); this.dirty = true; @@ -270,13 +283,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -285,7 +302,8 @@ n = 20, points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { this.moveTo(0, 0); } @@ -293,7 +311,8 @@ var fromY = points[points.length-1]; var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; xa = fromX + ( (cpX - fromX) * j ); @@ -319,13 +338,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -342,7 +365,8 @@ var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; dt = (1 - j); @@ -373,13 +397,17 @@ * @param radius {number} The radius of the arc * @return {Graphics} */ -Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points.push(x1, y1); } } - else { + else + { this.moveTo(x1, y1); } @@ -392,12 +420,15 @@ b2 = x2 - x1, mm = Math.abs(a1 * b2 - b1 * a2); - if (mm < 1.0e-8 || radius === 0) { - if (points[points.length-2] !== x1 || points[points.length-1] !== y1) { + if (mm < 1.0e-8 || radius === 0) + { + if (points[points.length-2] !== x1 || points[points.length-1] !== y1) + { points.push(x1, y1); } } - else { + else + { var dd = a1 * a1 + b1 * b1, cc = a2 * a2 + b2 * b2, tt = a1 * a2 + b1 * b2, @@ -433,42 +464,51 @@ * @param anticlockwise {boolean} Optional. Specifies whether the drawing should be counterclockwise or clockwise. False is default, and indicates clockwise, while true indicates counter-clockwise. * @return {Graphics} */ -Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) { +Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) +{ var startX = cx + Math.cos(startAngle) * radius; var startY = cy + Math.sin(startAngle) * radius; var points; // TODO - This if-else makes no sense. It uses currentPath in the else where it doesn't exist... - if (this.currentPath) { + if (this.currentPath) + { points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { points.push(startX, startY); } - else if (points[points.length-2] !== startX || points[points.length-1] !== startY) { + else if (points[points.length-2] !== startX || points[points.length-1] !== startY) + { points.push(startX, startY); } } - else { + else + { this.moveTo(startX, startY); points = this.currentPath.shape.points; } - if (startAngle === endAngle) { + if (startAngle === endAngle) + { return this; } - if (!anticlockwise && endAngle <= startAngle) { + if (!anticlockwise && endAngle <= startAngle) + { endAngle += Math.PI * 2; } - else if (anticlockwise && startAngle <= endAngle) { + else if (anticlockwise && startAngle <= endAngle) + { startAngle += Math.PI * 2; } var sweep = anticlockwise ? (startAngle - endAngle) *-1 : (endAngle - startAngle); var segs = (Math.abs(sweep)/ (Math.PI * 2)) * 40; - if (sweep === 0) { + if (sweep === 0) + { return this; } @@ -482,7 +522,8 @@ var remainder = ( segMinus % 1 ) / segMinus; - for (var i = 0; i <= segMinus; ++i) { + for (var i = 0; i <= segMinus; ++i) + { var real = i + remainder * i; var angle = ((theta) + startAngle + (theta2 * real)); @@ -506,13 +547,16 @@ * @param alpha {number} the alpha of the fill * @return {Graphics} */ -Graphics.prototype.beginFill = function (color, alpha) { +Graphics.prototype.beginFill = function (color, alpha) +{ this.filling = true; this.fillColor = color || 0; this.fillAlpha = (alpha === undefined) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length <= 2) + { this.currentPath.fill = this.filling; this.currentPath.fillColor = this.fillColor; this.currentPath.fillAlpha = this.fillAlpha; @@ -526,7 +570,8 @@ * * @return {Graphics} */ -Graphics.prototype.endFill = function () { +Graphics.prototype.endFill = function () +{ this.filling = false; this.fillColor = null; this.fillAlpha = 1; @@ -542,7 +587,8 @@ * @param height {number} The height of the rectangle * @return {Graphics} */ -Graphics.prototype.drawRect = function ( x, y, width, height ) { +Graphics.prototype.drawRect = function ( x, y, width, height ) +{ this.drawShape(new math.Rectangle(x,y, width, height)); return this; @@ -556,7 +602,8 @@ * @param height {number} The height of the rectangle * @param radius {number} Radius of the rectangle corners */ -Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) { +Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) +{ this.drawShape(new math.RoundedRectangle(x, y, width, height, radius)); return this; @@ -570,7 +617,8 @@ * @param radius {number} The radius of the circle * @return {Graphics} */ -Graphics.prototype.drawCircle = function (x, y, radius) { +Graphics.prototype.drawCircle = function (x, y, radius) +{ this.drawShape(new math.Circle(x,y, radius)); return this; @@ -585,7 +633,8 @@ * @param height {number} The half height of the ellipse * @return {Graphics} */ -Graphics.prototype.drawEllipse = function (x, y, width, height) { +Graphics.prototype.drawEllipse = function (x, y, width, height) +{ this.drawShape(new math.Ellipse(x, y, width, height)); return this; @@ -597,8 +646,10 @@ * @param path {Array} The path data used to construct the polygon. * @return {Graphics} */ -Graphics.prototype.drawPolygon = function (path) { - if (!(path instanceof Array)) { +Graphics.prototype.drawPolygon = function (path) +{ + if (!(path instanceof Array)) + { path = Array.prototype.slice.call(arguments); } @@ -612,7 +663,8 @@ * * @return {Graphics} */ -Graphics.prototype.clear = function () { +Graphics.prototype.clear = function () +{ this.lineWidth = 0; this.filling = false; @@ -631,7 +683,8 @@ * @param scaleMode {number} Should be one of the scaleMode consts * @return {Texture} a texture of the graphics object */ -Graphics.prototype.generateTexture = function (resolution, scaleMode) { +Graphics.prototype.generateTexture = function (resolution, scaleMode) +{ resolution = resolution || 1; var bounds = this.getBounds(); @@ -655,17 +708,21 @@ * * @param renderer {WebGLRenderer} */ -Graphics.prototype._renderWebGL = function (renderer) { +Graphics.prototype._renderWebGL = function (renderer) +{ // if the sprite is not visible or the alpha is 0 then no need to render this element - if (this.isMask === true) { + if (this.isMask === true) + { return; } // this code may still be needed so leaving for now.. - // + // /* - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture on the gpu too! @@ -681,17 +738,24 @@ return; } - */ - - // check if the webgl graphic needs to be updated - if (this.glDirty) { - this.dirty = true; - this.glDirty = false; - } + else */ - renderer.setObjectRendererer(renderer.graphicsRenderer); - renderer.graphicsRenderer.render(this); + renderer.spriteBatch.stop(); + renderer.blendModeManager.setBlendMode(this.blendMode); + // check blend mode + renderer.blendModeManager.setBlendMode( this.blendMode ); + + // check if the webgl graphic needs to be updated + if (this.glDirty) + { + this.dirty = true; + this.glDirty = false; + } + + WebGLGraphics.renderGraphics(this, renderer); + + renderer.spriteBatch.start(); }; /** @@ -700,14 +764,18 @@ * @param renderer {CanvasRenderer} * @private */ -Graphics.prototype.renderCanvas = function (renderer) { +Graphics.prototype.renderCanvas = function (renderer) +{ // 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.isMask === true) { + if (!this.visible || this.alpha <= 0 || this.isMask === true) + { return; } - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture @@ -723,16 +791,19 @@ return; } - else { + else + { var context = renderer.context; var transform = this.worldTransform; - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } @@ -748,11 +819,13 @@ CanvasGraphics.renderGraphics(this, context); - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } } @@ -763,13 +836,16 @@ * * @return {Rectangle} the rectangular bounding area */ -Graphics.prototype.getBounds = function (matrix) { +Graphics.prototype.getBounds = function (matrix) +{ // return an empty object if the item is a mask! - if (this.isMask) { + if (this.isMask) + { return math.Rectangle.EMPTY; } - if (this.dirty) { + if (this.dirty) + { this.updateLocalBounds(); this.glDirty = true; @@ -841,23 +917,27 @@ * Update the bounds of the object * */ -Graphics.prototype.updateLocalBounds = function () { +Graphics.prototype.updateLocalBounds = function () +{ var minX = Infinity; var maxX = -Infinity; var minY = Infinity; var maxY = -Infinity; - if (this.graphicsData.length) { + if (this.graphicsData.length) + { var shape, points, x, y, w, h; - for (var i = 0; i < this.graphicsData.length; i++) { + for (var i = 0; i < this.graphicsData.length; i++) + { var data = this.graphicsData[i]; var type = data.type; var lineWidth = data.lineWidth; shape = data.shape; - if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) { + if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) + { x = shape.x - lineWidth/2; y = shape.y - lineWidth/2; w = shape.width + lineWidth; @@ -869,7 +949,8 @@ minY = y < minY ? y : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.CIRC) { + else if (type === CONST.SHAPES.CIRC) + { x = shape.x; y = shape.y; w = shape.radius + lineWidth/2; @@ -881,7 +962,8 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.ELIP) { + else if (type === CONST.SHAPES.ELIP) + { x = shape.x; y = shape.y; w = shape.width + lineWidth/2; @@ -893,11 +975,13 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else { + else + { // POLY points = shape.points; - for (var j = 0; j < points.length; j += 2) { + for (var j = 0; j < points.length; j += 2) + { x = points[j]; y = points[j+1]; @@ -910,7 +994,8 @@ } } } - else { + else + { minX = 0; maxX = 0; minY = 0; @@ -931,10 +1016,12 @@ * * @private */ -Graphics.prototype._generateCachedSprite = function () { +Graphics.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { var canvasBuffer = new CanvasBuffer(bounds.width, bounds.height); var texture = Texture.fromCanvas(canvasBuffer.canvas); @@ -943,7 +1030,8 @@ this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.buffer.resize(bounds.width, bounds.height); } @@ -968,7 +1056,8 @@ * * @private */ -Graphics.prototype.updateCachedSpriteTexture = function () { +Graphics.prototype.updateCachedSpriteTexture = function () +{ var cachedSprite = this._cachedSprite; var texture = cachedSprite.texture; var canvas = cachedSprite.buffer.canvas; @@ -989,7 +1078,8 @@ * Destroys a previous cached sprite. * */ -Graphics.prototype.destroyCachedSprite = function () { +Graphics.prototype.destroyCachedSprite = function () +{ this._cachedSprite.texture.destroy(true); // let the gc collect the unused sprite @@ -1003,10 +1093,13 @@ * @param {Circle|Rectangle|Ellipse|Line|Polygon} shape The Shape object to draw. * @return {GraphicsData} The generated GraphicsData object. */ -Graphics.prototype.drawShape = function (shape) { - if (this.currentPath) { +Graphics.prototype.drawShape = function (shape) +{ + if (this.currentPath) + { // check current path! - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath.shape.points.length <= 2) + { this.graphicsData.pop(); } } @@ -1017,7 +1110,8 @@ this.graphicsData.push(data); - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { data.shape.closed = this.filling; this.currentPath = data; } diff --git a/src/core/primitives/GraphicsData.js b/src/core/primitives/GraphicsData.js index 99decbe..788f6f2 100644 --- a/src/core/primitives/GraphicsData.js +++ b/src/core/primitives/GraphicsData.js @@ -4,7 +4,8 @@ * @class * @namespace PIXI */ -function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) { +function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) +{ this.lineWidth = lineWidth; this.lineColor = lineColor; this.lineAlpha = lineAlpha; @@ -27,7 +28,8 @@ * * @return {GraphicsData} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ return new GraphicsData( this.lineWidth, this.lineColor, diff --git a/src/core/renderers/canvas/CanvasRenderer.js b/src/core/renderers/canvas/CanvasRenderer.js index 15a0978..7aebd44 100644 --- a/src/core/renderers/canvas/CanvasRenderer.js +++ b/src/core/renderers/canvas/CanvasRenderer.js @@ -17,17 +17,22 @@ * @param [options.resolution=1] {number} the resolution of the renderer retina would be 2 * @param [options.clearBeforeRender=true] {boolean} This sets if the CanvasRenderer will clear the canvas or not before the new render pass. */ -function CanvasRenderer(width, height, options) { +function CanvasRenderer(width, height, options) +{ utils.sayHello('Canvas'); - if (options) { - for (var i in CONST.defaultRenderOptions) { - if (typeof options[i] === 'undefined') { + if (options) + { + for (var i in CONST.defaultRenderOptions) + { + if (typeof options[i] === 'undefined') + { options[i] = CONST.defaultRenderOptions[i]; } } } - else { + else + { options = CONST.defaultRenderOptions; } @@ -156,19 +161,24 @@ this.smoothProperty = null; - if (this.context.imageSmoothingEnabled) { + if (this.context.imageSmoothingEnabled) + { this.smoothProperty = 'imageSmoothingEnabled'; } - else if (this.context.webkitImageSmoothingEnabled) { + else if (this.context.webkitImageSmoothingEnabled) + { this.smoothProperty = 'webkitImageSmoothingEnabled'; } - else if (this.context.mozImageSmoothingEnabled) { + else if (this.context.mozImageSmoothingEnabled) + { this.smoothProperty = 'mozImageSmoothingEnabled'; } - else if (this.context.oImageSmoothingEnabled) { + else if (this.context.oImageSmoothingEnabled) + { this.smoothProperty = 'oImageSmoothingEnabled'; } - else if (this.context.msImageSmoothingEnabled) { + else if (this.context.msImageSmoothingEnabled) + { this.smoothProperty = 'msImageSmoothingEnabled'; } @@ -193,10 +203,12 @@ * @memberof CanvasRenderer# */ backgroundColor: { - get: function () { + get: function () + { return this._backgroundColor; }, - set: function (val) { + set: function (val) + { this._backgroundColor = val; this._backgroundColorString = utils.hex2string(val); } @@ -208,7 +220,8 @@ * * @param object {DisplayObject} the object to be rendered */ -CanvasRenderer.prototype.render = function (object) { +CanvasRenderer.prototype.render = function (object) +{ object.updateTransform(); this.context.setTransform(1,0,0,1,0,0); @@ -218,16 +231,20 @@ this.currentBlendMode = CONST.blendModes.NORMAL; this.context.globalCompositeOperation = this.blendModes[CONST.blendModes.NORMAL]; - if (navigator.isCocoonJS && this.view.screencanvas) { + if (navigator.isCocoonJS && this.view.screencanvas) + { this.context.fillStyle = 'black'; this.context.clear(); } - if (this.clearBeforeRender) { - if (this.transparent) { + if (this.clearBeforeRender) + { + if (this.transparent) + { this.context.clearRect(0, 0, this.width, this.height); } - else { + else + { this.context.fillStyle = this._backgroundColorString; this.context.fillRect(0, 0, this.width , this.height); } @@ -241,8 +258,10 @@ * * @param [removeView=false] {boolean} Removes the Canvas element from the DOM. */ -CanvasRenderer.prototype.destroy = function (removeView) { - if (removeView && this.view.parent) { +CanvasRenderer.prototype.destroy = function (removeView) +{ + if (removeView && this.view.parent) + { this.view.parent.removeChild(this.view); } @@ -257,14 +276,16 @@ * @param width {number} the new width of the canvas view * @param height {number} the new height of the canvas view */ -CanvasRenderer.prototype.resize = function (width, height) { +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) { + if (this.autoResize) + { this.view.style.width = this.width / this.resolution + 'px'; this.view.style.height = this.height / this.resolution + 'px'; } @@ -276,7 +297,8 @@ * @param displayObject {DisplayObject} The displayObject to render * @private */ -CanvasRenderer.prototype.renderDisplayObject = function (displayObject) { +CanvasRenderer.prototype.renderDisplayObject = function (displayObject) +{ displayObject.renderCanvas(this); }; @@ -285,11 +307,14 @@ * * @private */ -CanvasRenderer.prototype._mapBlendModes = function () { - if (!this.blendModes) { +CanvasRenderer.prototype._mapBlendModes = function () +{ + if (!this.blendModes) + { this.blendModes = {}; - if (utils.canUseNewCanvasBlendModes()) { + if (utils.canUseNewCanvasBlendModes()) + { this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? this.blendModes[CONST.blendModes.MULTIPLY] = 'multiply'; @@ -308,7 +333,8 @@ this.blendModes[CONST.blendModes.COLOR] = 'color'; this.blendModes[CONST.blendModes.LUMINOSITY] = 'luminosity'; } - else { + else + { // this means that the browser does not support the cool new blend modes in canvas 'cough' ie 'cough' this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? diff --git a/src/core/renderers/canvas/utils/CanvasBuffer.js b/src/core/renderers/canvas/utils/CanvasBuffer.js index ebe5d47..b183a66 100644 --- a/src/core/renderers/canvas/utils/CanvasBuffer.js +++ b/src/core/renderers/canvas/utils/CanvasBuffer.js @@ -6,7 +6,8 @@ * @param width {number} the width for the newly created canvas * @param height {number} the height for the newly created canvas */ -function CanvasBuffer(width, height) { +function CanvasBuffer(width, height) +{ /** * The Canvas object that belongs to this CanvasBuffer. * @@ -36,10 +37,12 @@ * @memberof CanvasBuffer# */ width: { - get: function () { + get: function () + { return this.canvas.width; }, - set: function (val) { + set: function (val) + { this.canvas.width = val; } }, @@ -50,10 +53,12 @@ * @memberof CanvasBuffer# */ height: { - get: function () { + get: function () + { return this.canvas.height; }, - set: function (val) { + set: function (val) + { this.canvas.height = val; } } @@ -64,7 +69,8 @@ * * @private */ -CanvasBuffer.prototype.clear = function () { +CanvasBuffer.prototype.clear = function () +{ this.context.setTransform(1, 0, 0, 1, 0, 0); this.context.clearRect(0,0, this.canvas.width, this.canvas.height); }; @@ -75,7 +81,8 @@ * @param width {number} the new width of the canvas * @param height {number} the new height of the canvas */ -CanvasBuffer.prototype.resize = function (width, height) { +CanvasBuffer.prototype.resize = function (width, height) +{ this.canvas.width = width; this.canvas.height = height; }; diff --git a/src/core/renderers/canvas/utils/CanvasGraphics.js b/src/core/renderers/canvas/utils/CanvasGraphics.js index c7eaa2a..3f2a91f 100644 --- a/src/core/renderers/canvas/utils/CanvasGraphics.js +++ b/src/core/renderers/canvas/utils/CanvasGraphics.js @@ -13,15 +13,18 @@ * @param graphics {Graphics} the actual graphics object to render * @param context {CanvasRenderingContext2D} the 2d drawing method of the canvas */ -CanvasGraphics.renderGraphics = function (graphics, context) { +CanvasGraphics.renderGraphics = function (graphics, context) +{ var worldAlpha = graphics.worldAlpha; - if (graphics.dirty) { + if (graphics.dirty) + { this.updateGraphicsTint(graphics); graphics.dirty = false; } - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; @@ -30,69 +33,82 @@ context.lineWidth = data.lineWidth; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { context.beginPath(); var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } - if (shape.closed) { + if (shape.closed) + { context.lineTo(points[0], points[1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fillRect(shape.x, shape.y, shape.width, shape.height); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.strokeRect(shape.x, shape.y, shape.width, shape.height); } } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.beginPath(); context.arc(shape.x, shape.y, shape.radius,0,2*Math.PI); context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas var w = shape.width * 2; @@ -119,18 +135,21 @@ context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; var width = shape.width; @@ -152,13 +171,15 @@ context.quadraticCurveTo(rx, ry, rx, ry + radius); context.closePath(); - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); @@ -174,45 +195,54 @@ * @param graphics {Graphics} the graphics which will be used as a mask * @param context {CanvasRenderingContext2D} the context 2d method of the canvas */ -CanvasGraphics.renderGraphicsMask = function (graphics, context) { +CanvasGraphics.renderGraphicsMask = function (graphics, context) +{ var len = graphics.graphicsData.length; - if (len === 0) { + if (len === 0) + { return; } context.beginPath(); - for (var i = 0; i < len; i++) { + for (var i = 0; i < len; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { context.rect(shape.x, shape.y, shape.width, shape.height); context.closePath(); } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.arc(shape.x, shape.y, shape.radius, 0, 2 * Math.PI); context.closePath(); } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas @@ -237,7 +267,8 @@ context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); context.closePath(); } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; @@ -262,8 +293,10 @@ } }; -CanvasGraphics.updateGraphicsTint = function (graphics) { - if (graphics.tint === 0xFFFFFF) { +CanvasGraphics.updateGraphicsTint = function (graphics) +{ + if (graphics.tint === 0xFFFFFF) + { return; } @@ -271,7 +304,8 @@ var tintG = (graphics.tint >> 8 & 0xFF) / 255; var tintB = (graphics.tint & 0xFF)/ 255; - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var fillColor = data.fillColor | 0; diff --git a/src/core/renderers/canvas/utils/CanvasMaskManager.js b/src/core/renderers/canvas/utils/CanvasMaskManager.js index e04a733..9827d36 100644 --- a/src/core/renderers/canvas/utils/CanvasMaskManager.js +++ b/src/core/renderers/canvas/utils/CanvasMaskManager.js @@ -6,7 +6,8 @@ * @class * @namespace PIXI */ -function CanvasMaskManager() {} +function CanvasMaskManager() +{} CanvasMaskManager.prototype.constructor = CanvasMaskManager; module.exports = CanvasMaskManager; @@ -17,7 +18,8 @@ * @param maskData {object} the maskData that will be pushed * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.pushMask = function (maskData, renderer) { +CanvasMaskManager.prototype.pushMask = function (maskData, renderer) +{ renderer.context.save(); var cacheAlpha = maskData.alpha; @@ -45,6 +47,7 @@ * * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.popMask = function (renderer) { +CanvasMaskManager.prototype.popMask = function (renderer) +{ renderer.context.restore(); }; diff --git a/src/core/renderers/canvas/utils/CanvasTinter.js b/src/core/renderers/canvas/utils/CanvasTinter.js index 17e0529..d2fb1bc 100644 --- a/src/core/renderers/canvas/utils/CanvasTinter.js +++ b/src/core/renderers/canvas/utils/CanvasTinter.js @@ -14,7 +14,8 @@ * @param color {number} the color to use to tint the sprite with * @return {HTMLCanvasElement} The tinted canvas */ -CanvasTinter.getTintedTexture = function (sprite, color) { +CanvasTinter.getTintedTexture = function (sprite, color) +{ var texture = sprite.texture; color = CanvasTinter.roundColor(color); @@ -23,7 +24,8 @@ texture.tintCache = texture.tintCache || {}; - if (texture.tintCache[stringColor]) { + if (texture.tintCache[stringColor]) + { return texture.tintCache[stringColor]; } @@ -33,14 +35,16 @@ //CanvasTinter.tintWithPerPixel(texture, stringColor, canvas); CanvasTinter.tintMethod(texture, color, canvas); - if (CanvasTinter.convertTintToImage) { + if (CanvasTinter.convertTintToImage) + { // is this better? var tintImage = new Image(); tintImage.src = canvas.toDataURL(); texture.tintCache[stringColor] = tintImage; } - else { + else + { texture.tintCache[stringColor] = canvas; // if we are not converting the texture to an image then we need to lose the reference to the canvas CanvasTinter.canvas = null; @@ -56,7 +60,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithMultiply = function (texture, color, canvas) { +CanvasTinter.tintWithMultiply = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -104,7 +109,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithOverlay = function (texture, color, canvas) { +CanvasTinter.tintWithOverlay = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -139,7 +145,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithPerPixel = function (texture, color, canvas) { +CanvasTinter.tintWithPerPixel = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -167,7 +174,8 @@ var pixels = pixelData.data; - for (var i = 0; i < pixels.length; i += 4) { + for (var i = 0; i < pixels.length; i += 4) + { pixels[i+0] *= r; pixels[i+1] *= g; pixels[i+2] *= b; @@ -181,7 +189,8 @@ * * @param color {number} the color to round, should be a hex color */ -CanvasTinter.roundColor = function (color) { +CanvasTinter.roundColor = function (color) +{ var step = CanvasTinter.cacheStepsPerColorChannel; var rgbValues = utils.hex2rgb(color); diff --git a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js index 9f2f89a..35edbaf 100644 --- a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js +++ b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLBlendModeManager(renderer) { +function WebGLBlendModeManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -23,8 +24,10 @@ * * @param blendMode {number} the blendMode, should be a Pixi const, such as BlendModes.ADD */ -WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) { - if (this.currentBlendMode === blendMode) { +WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) +{ + if (this.currentBlendMode === blendMode) + { return false; } diff --git a/src/core/renderers/webgl/managers/WebGLFilterManager.js b/src/core/renderers/webgl/managers/WebGLFilterManager.js index 1179258..2dac048 100644 --- a/src/core/renderers/webgl/managers/WebGLFilterManager.js +++ b/src/core/renderers/webgl/managers/WebGLFilterManager.js @@ -7,7 +7,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLFilterManager(renderer) { +function WebGLFilterManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -32,7 +33,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.texturePool.length = 0; self.initShaderBuffers(); }); @@ -46,7 +48,8 @@ * @param renderer {WebGLRenderer} * @param buffer {ArrayBuffer} */ -WebGLFilterManager.prototype.begin = function (buffer) { +WebGLFilterManager.prototype.begin = function (buffer) +{ this.defaultShader = this.renderer.shaderManager.defaultShader; this.width = this.renderer.projection.x * 2; @@ -60,7 +63,8 @@ * * @param filterBlock {object} the filter that will be pushed to the current filter stack */ -WebGLFilterManager.prototype.pushFilter = function (filterBlock) { +WebGLFilterManager.prototype.pushFilter = function (filterBlock) +{ var gl = this.renderer.gl; var projection = this.renderer.projection; @@ -78,10 +82,12 @@ this.offsetY += filterBlock._filterArea.y; var texture = this.texturePool.pop(); - if (!texture) { + if (!texture) + { texture = new FilterTexture(this.renderer.gl, this.width, this.height); } - else { + else + { texture.resize(this.width, this.height); } @@ -98,29 +104,35 @@ var localX = filterArea.x, localY = filterArea.y; - if (filterArea.x < 0) { + if (filterArea.x < 0) + { filterArea.width += filterArea.x; filterArea.x = 0; } - if (filterArea.y < 0) { + if (filterArea.y < 0) + { filterArea.height += filterArea.y; filterArea.y = 0; } - if (localX + filterArea.width > this.width) { + if (localX + filterArea.width > this.width) + { filterArea.width = this.width - localX; } - if (localY + filterArea.height > this.height) { + if (localY + filterArea.height > this.height) + { filterArea.height = this.height - localY; } - if (filterArea.width < 0) { + if (filterArea.width < 0) + { filterArea.width = 0; } - if (filterArea.height < 0) { + if (filterArea.height < 0) + { filterArea.height = 0; } @@ -154,7 +166,8 @@ * Removes the last filter from the filter stack and doesn't return it. * */ -WebGLFilterManager.prototype.popFilter = function () { +WebGLFilterManager.prototype.popFilter = function () +{ var gl = this.renderer.gl; var filterBlock = this.filterStack.pop(); @@ -163,7 +176,8 @@ var projection = this.renderer.projection; var offset = this.renderer.offset; - if (filterBlock.filterPasses.length > 1) { + if (filterBlock.filterPasses.length > 1) + { gl.viewport(0, 0, filterArea.width, filterArea.height); gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); @@ -193,7 +207,8 @@ var inputTexture = texture; var outputTexture = this.texturePool.pop(); - if (!outputTexture) { + if (!outputTexture) + { outputTexture = new FilterTexture(this.renderer.gl, this.width, this.height); } outputTexture.resize(this.width, this.height); @@ -204,7 +219,8 @@ gl.disable(gl.BLEND); - for (var i = 0; i < filterBlock.filterPasses.length-1; i++) { + for (var i = 0; i < filterBlock.filterPasses.length-1; i++) + { var filterPass = filterBlock.filterPasses[i]; gl.bindFramebuffer(gl.FRAMEBUFFER, outputTexture.frameBuffer ); @@ -243,10 +259,12 @@ var buffer = this.buffer; // time to render the filters texture to the previous scene - if (this.filterStack.length === 0) { + if (this.filterStack.length === 0) + { gl.colorMask(true, true, true, true);//this.transparent); } - else { + else + { var currentFilter = this.filterStack[this.filterStack.length-1]; filterArea = currentFilter._filterArea; @@ -332,13 +350,15 @@ * @param width {number} the horizontal range of the filter * @param height {number} the vertical range of the filter */ -WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) { +WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) +{ // use program var gl = this.renderer.gl; var shader = filter.shaders[gl.id]; - if (!shader) { + if (!shader) + { shader = new Shader(gl); shader.fragmentSrc = filter.fragmentSrc; @@ -356,7 +376,8 @@ gl.uniform2f(shader.projectionVector, width/2, -height/2); gl.uniform2f(shader.offsetVector, 0,0); - if (filter.uniforms.dimensions) { + 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]; @@ -386,7 +407,8 @@ * Initialises the shader buffers. * */ -WebGLFilterManager.prototype.initShaderBuffers = function () { +WebGLFilterManager.prototype.initShaderBuffers = function () +{ var gl = this.renderer.gl; // create some buffers @@ -432,7 +454,8 @@ * Destroys the filter and removes it from the filter stack. * */ -WebGLFilterManager.prototype.destroy = function () { +WebGLFilterManager.prototype.destroy = function () +{ var gl = this.renderer.gl; this.filterStack = null; @@ -441,7 +464,8 @@ this.offsetY = 0; // destroy textures - for (var i = 0; i < this.texturePool.length; i++) { + for (var i = 0; i < this.texturePool.length; i++) + { this.texturePool[i].destroy(); } diff --git a/src/core/renderers/webgl/managers/WebGLManager.js b/src/core/renderers/webgl/managers/WebGLManager.js index 9d47b5c..c30cd51 100644 --- a/src/core/renderers/webgl/managers/WebGLManager.js +++ b/src/core/renderers/webgl/managers/WebGLManager.js @@ -3,7 +3,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLManager(renderer) { +function WebGLManager(renderer) +{ /** * The renderer this manager works for. * @@ -15,6 +16,7 @@ WebGLManager.prototype.constructor = WebGLManager; module.exports = WebGLManager; -WebGLManager.prototype.destroy = function () { +WebGLManager.prototype.destroy = function () +{ this.renderer = null; }; diff --git a/src/core/renderers/webgl/managers/WebGLMaskManager.js b/src/core/renderers/webgl/managers/WebGLMaskManager.js index 2f90b64..e568812 100644 --- a/src/core/renderers/webgl/managers/WebGLMaskManager.js +++ b/src/core/renderers/webgl/managers/WebGLMaskManager.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLMaskManager(renderer) { +function WebGLMaskManager(renderer) +{ WebGLManager.call(this, renderer); } @@ -19,12 +20,15 @@ * * @param maskData {any[]} */ -WebGLMaskManager.prototype.pushMask = function (maskData) { - if (maskData.dirty) { +WebGLMaskManager.prototype.pushMask = function (maskData) +{ + if (maskData.dirty) + { WebGLGraphics.updateGraphics(maskData, this.renderer.gl); } - if (!maskData._webGL[this.renderer.gl.id].data.length) { + if (!maskData._webGL[this.renderer.gl.id].data.length) + { return; } @@ -36,6 +40,7 @@ * * @param maskData {any[]} */ -WebGLMaskManager.prototype.popMask = function (maskData) { +WebGLMaskManager.prototype.popMask = function (maskData) +{ this.renderer.stencilManager.popStencil(maskData, maskData._webGL[this.renderer.gl.id].data[0], this.renderer); }; diff --git a/src/core/renderers/webgl/managers/WebGLShaderManager.js b/src/core/renderers/webgl/managers/WebGLShaderManager.js index fef071c..90c6477 100644 --- a/src/core/renderers/webgl/managers/WebGLShaderManager.js +++ b/src/core/renderers/webgl/managers/WebGLShaderManager.js @@ -10,7 +10,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLShaderManager(renderer) { +function WebGLShaderManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -28,7 +29,8 @@ */ this.tempAttribState = []; - for (var i = 0; i < this.maxAttibs; i++) { + for (var i = 0; i < this.maxAttibs; i++) + { this.attribState[i] = false; } @@ -66,7 +68,8 @@ // listen for context and update necessary shaders var self = this; - this.renderer.on('context', function (event) { + this.renderer.on('context', function (event) + { var gl = event.data; // this shader is used for rendering primitives @@ -97,29 +100,36 @@ * * @param attribs {Array} attribs */ -WebGLShaderManager.prototype.setAttribs = function (attribs) { +WebGLShaderManager.prototype.setAttribs = function (attribs) +{ // reset temp state var i; - for (i = 0; i < this.tempAttribState.length; i++) { + for (i = 0; i < this.tempAttribState.length; i++) + { this.tempAttribState[i] = false; } // set the new attribs - for (var a in attribs) { + for (var a in attribs) + { this.tempAttribState[attribs[a]] = true; } var gl = this.renderer.gl; - for (i = 0; i < this.attribState.length; i++) { - if (this.attribState[i] !== this.tempAttribState[i]) { + for (i = 0; i < this.attribState.length; i++) + { + if (this.attribState[i] !== this.tempAttribState[i]) + { this.attribState[i] = this.tempAttribState[i]; - if (this.attribState[i]) { + if (this.attribState[i]) + { gl.enableVertexAttribArray(i); } - else { + else + { gl.disableVertexAttribArray(i); } } @@ -131,8 +141,10 @@ * * @param shader {Any} */ -WebGLShaderManager.prototype.setShader = function (shader) { - if (this._currentId === shader.uuid) { +WebGLShaderManager.prototype.setShader = function (shader) +{ + if (this._currentId === shader.uuid) + { return false; } @@ -150,7 +162,8 @@ * Destroys this object. * */ -WebGLShaderManager.prototype.destroy = function () { +WebGLShaderManager.prototype.destroy = function () +{ this.attribState = null; this.tempAttribState = null; diff --git a/src/core/renderers/webgl/managers/WebGLStencilManager.js b/src/core/renderers/webgl/managers/WebGLStencilManager.js index 9ec6398..4cb0134 100644 --- a/src/core/renderers/webgl/managers/WebGLStencilManager.js +++ b/src/core/renderers/webgl/managers/WebGLStencilManager.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLStencilManager(renderer) { +function WebGLStencilManager(renderer) +{ WebGLManager.call(this, renderer); this.stencilStack = []; @@ -24,12 +25,14 @@ * @param graphics {Graphics} * @param webGLData {any[]} */ -WebGLStencilManager.prototype.pushStencil = function (graphics, webGLData) { +WebGLStencilManager.prototype.pushStencil = function (graphics, webGLData) +{ var gl = this.renderer.gl; this.bindGraphics(graphics, webGLData, this.renderer); - if (this.stencilStack.length === 0) { + if (this.stencilStack.length === 0) + { gl.enable(gl.STENCIL_TEST); gl.clear(gl.STENCIL_BUFFER_BIT); this.reverse = true; @@ -47,14 +50,17 @@ // draw the triangle strip! - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } @@ -62,31 +68,38 @@ // draw a quad to increment.. gl.drawElements(gl.TRIANGLE_FAN, 4, gl.UNSIGNED_SHORT, ( webGLData.indices.length - 4 ) * 2 ); - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); } this.reverse = !this.reverse; } - else { - if (!this.reverse) { + else + { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } - else { + 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) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); } } @@ -103,7 +116,8 @@ * @param graphics {Graphics} * @param webGLData {Array} */ -WebGLStencilManager.prototype.bindGraphics = function (graphics, webGLData) { +WebGLStencilManager.prototype.bindGraphics = function (graphics, webGLData) +{ //if (this._currentGraphics === graphics)return; this._currentGraphics = graphics; @@ -114,7 +128,8 @@ offset = this.renderer.offset, shader;// = this.renderer.shaderManager.primitiveShader; - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { shader = this.renderer.shaderManager.complexPrimitiveShader; this.renderer.shaderManager.setShader(shader); @@ -141,7 +156,8 @@ // set the index buffer! gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, webGLData.indexBuffer); } - else { + else + { //this.renderer.shaderManager.activatePrimitiveShader(); shader = this.renderer.shaderManager.primitiveShader; this.renderer.shaderManager.setShader( shader ); @@ -154,7 +170,7 @@ gl.uniform2f(shader.uniforms.offsetVector._location, -offset.x, -offset.y); gl.uniform3fv(shader.uniforms.tint._location, utils.hex2rgb(graphics.tint)); - + gl.uniform1f(shader.uniforms.alpha._location, graphics.worldAlpha); @@ -172,19 +188,22 @@ * @param graphics {Graphics} * @param webGLData {Array} */ -WebGLStencilManager.prototype.popStencil = function (graphics, webGLData) { +WebGLStencilManager.prototype.popStencil = function (graphics, webGLData) +{ var gl = this.renderer.gl; this.stencilStack.pop(); this.count--; - if (this.stencilStack.length === 0) { + if (this.stencilStack.length === 0) + { // the stack is empty! gl.disable(gl.STENCIL_TEST); } - else { + else + { var level = this.count; @@ -192,14 +211,17 @@ gl.colorMask(false, false, false, false); - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { this.reverse = !this.reverse; - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } @@ -213,31 +235,38 @@ // draw the triangle strip! gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); - if (!this.reverse) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); } } - else { + else + { // console.log("<<>>") - if (!this.reverse) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } - else { + 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) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); } } @@ -253,7 +282,8 @@ * Destroys the mask stack. * */ -WebGLStencilManager.prototype.destroy = function () { +WebGLStencilManager.prototype.destroy = function () +{ this.renderer = null; this.stencilStack = null; }; diff --git a/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js b/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js index 913ba5e..1ea7d19 100644 --- a/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js +++ b/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function ComplexPrimitiveShader(gl) { +function ComplexPrimitiveShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -24,7 +25,8 @@ 'uniform float flipY;', 'varying vec4 vColor;', - 'void main(void) {', + '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);', @@ -37,7 +39,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = vColor;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/FastShader.js b/src/core/renderers/webgl/shaders/FastShader.js index bd2e29a..2e5e060 100644 --- a/src/core/renderers/webgl/shaders/FastShader.js +++ b/src/core/renderers/webgl/shaders/FastShader.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function FastShader(gl) { +function FastShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -28,7 +29,8 @@ 'const vec2 center = vec2(-1.0, 1.0);', - 'void main(void) {', + 'void main(void) + {', ' vec2 v;', ' vec2 sv = aVertexPosition * aScale;', ' v.x = (sv.x) * cos(aRotation) - (sv.y) * sin(aRotation);', @@ -49,7 +51,8 @@ 'uniform sampler2D uSampler;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/PrimitiveShader.js b/src/core/renderers/webgl/shaders/PrimitiveShader.js index 6f25409..a25f54f 100644 --- a/src/core/renderers/webgl/shaders/PrimitiveShader.js +++ b/src/core/renderers/webgl/shaders/PrimitiveShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function PrimitiveShader(gl) { +function PrimitiveShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -23,7 +24,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + '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);', @@ -36,7 +38,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = vColor;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/Shader.js b/src/core/renderers/webgl/shaders/Shader.js index f8964f5..fd75ef5 100644 --- a/src/core/renderers/webgl/shaders/Shader.js +++ b/src/core/renderers/webgl/shaders/Shader.js @@ -6,7 +6,8 @@ * @param [fragmentSrc] {string} The source of the fragment shader. * @param [vertexSrc] {string} The source of the vertex shader. */ -function Shader(gl, vertexSrc, fragmentSrc, customUniforms, customAttributes) { +function Shader(gl, vertexSrc, fragmentSrc, customUniforms, customAttributes) +{ /** * @member {number} * @readonly @@ -33,7 +34,8 @@ dimensions: { type: '4f', value: new Float32Array(4) } }; - for (var u in customUniforms) { + for (var u in customUniforms) + { this.uniforms[u] = customUniforms[u]; } @@ -43,7 +45,8 @@ aColor: 0 }; - for (var a in customAttributes) { + for (var a in customAttributes) + { this.attributes[a] = customAttributes[a]; } @@ -66,7 +69,8 @@ 'const vec2 center = vec2(-1.0, 1.0);', - 'void main(void) {', + 'void main(void) + {', ' gl_Position = vec4( ((aVertexPosition + offsetVector) / projectionVector) + center , 0.0, 1.0);', ' vTextureCoord = aTextureCoord;', ' vColor = vec4(aColor.rgb * aColor.a, aColor.a);', @@ -85,7 +89,8 @@ 'uniform sampler2D uSampler;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;', '}' ].join('\n'); @@ -96,7 +101,8 @@ Shader.prototype.constructor = Shader; module.exports = Shader; -Shader.prototype.init = function () { +Shader.prototype.init = function () +{ this.compile(); this.gl.useProgram(this.program); @@ -105,14 +111,18 @@ this.cacheAttributeLocations(Object.keys(this.attributes)); }; -Shader.prototype.cacheUniformLocations = function (keys) { - for (var i = 0; i < keys.length; ++i) { +Shader.prototype.cacheUniformLocations = function (keys) +{ + for (var i = 0; i < keys.length; ++i) + { this.uniforms[keys[i]]._location = this.gl.getUniformLocation(this.program, keys[i]); } }; -Shader.prototype.cacheAttributeLocations = function (keys) { - for (var i = 0; i < keys.length; ++i) { +Shader.prototype.cacheAttributeLocations = function (keys) +{ + for (var i = 0; i < keys.length; ++i) + { this.attributes[keys[i]] = this.gl.getAttribLocation(this.program, keys[i]); } @@ -124,14 +134,16 @@ // 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.attributes.aColor === -1) { + // if (this.attributes.aColor === -1) + { // this.attributes.aColor = 2; // } // End worst hack eva // }; -Shader.prototype.compile = function () { +Shader.prototype.compile = function () +{ var gl = this.gl; var glVertShader = this._glCompile(gl.VERTEX_SHADER, this.vertexSrc); @@ -144,13 +156,15 @@ gl.linkProgram(program); // if linking fails, then log and cleanup - if (!gl.getProgramParameter(program, gl.LINK_STATUS)) { + if (!gl.getProgramParameter(program, gl.LINK_STATUS)) + { window.console.error('Pixi.js Error: Could not initialize shader.'); window.console.error('gl.VALIDATE_STATUS', gl.getProgramParameter(program, gl.VALIDATE_STATUS)); window.console.error('gl.getError()', gl.getError()); // if there is a program info log, log it - if (gl.getProgramInfoLog(program) !== '') { + if (gl.getProgramInfoLog(program) !== '') + { window.console.warn('Pixi.js Warning: gl.getProgramInfoLog()', gl.getProgramInfoLog(program)); } @@ -165,18 +179,21 @@ return (this.program = program); }; -Shader.prototype.syncUniforms = function () { +Shader.prototype.syncUniforms = function () +{ var gl = this.gl; this.textureCount = 1; - for (var key in this.uniforms) { + for (var key in this.uniforms) + { var uniform = this.uniforms[key], location = uniform._location, value = uniform.value, i, il; - switch (uniform.type) { + switch (uniform.type) + { // single int value case 'i': case '1i': @@ -282,7 +299,8 @@ // a Color Value case 'c': - if (typeof value === 'number') { + if (typeof value === 'number') + { value = utils.hex2rgb(value); } @@ -311,11 +329,13 @@ // array of 2D Point objects case 'v2v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(2 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 2] = value[i].x; uniform._array[i * 2 + 1] = value[i].y; } @@ -325,11 +345,13 @@ // array of 3D Point objects case 'v3v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(3 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 3] = value[i].x; uniform._array[i * 3 + 1] = value[i].y; uniform._array[i * 3 + 2] = value[i].z; @@ -341,11 +363,13 @@ // array of 4D Point objects case 'v4v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(4 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 4] = value[i].x; uniform._array[i * 4 + 1] = value[i].y; uniform._array[i * 4 + 2] = value[i].z; @@ -359,7 +383,8 @@ // PIXI.Texture case 't': case 'sampler2D': - if (!uniform.value || !uniform.value.baseTexture || !uniform.value.baseTexture.hasLoaded) { + if (!uniform.value || !uniform.value.baseTexture || !uniform.value.baseTexture.hasLoaded) + { break; } @@ -376,7 +401,8 @@ this.textureCount++; // initialize the texture if we haven't yet - if (!uniform._init) { + if (!uniform._init) + { this.initSampler2D(uniform); uniform._init = true; @@ -394,11 +420,13 @@ * Initialises a Sampler2D uniform (which may only be available later on after initUniforms once the texture has loaded) * */ -Shader.prototype.initSampler2D = function (uniform) { +Shader.prototype.initSampler2D = function (uniform) +{ var gl = this.gl; // Extended texture data - if (uniform.textureData) { + if (uniform.textureData) + { var data = uniform.textureData; // GLTexture = mag linear, min linear_mipmap_linear, wrap repeat + gl.generateMipmap(gl.TEXTURE_2D); @@ -417,14 +445,16 @@ var wrapT = (data.wrapT) ? data.wrapT : gl.CLAMP_TO_EDGE; var format = (data.luminance) ? gl.LUMINANCE : gl.RGBA; - if (data.repeat) { + if (data.repeat) + { wrapS = gl.REPEAT; wrapT = gl.REPEAT; } gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, !!data.flipY); - if (data.width) { + if (data.width) + { var width = (data.width) ? data.width : 512; var height = (data.height) ? data.height : 2; var border = (data.border) ? data.border : 0; @@ -432,7 +462,8 @@ // 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 { + 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); } @@ -448,7 +479,8 @@ * Destroys the shader. * */ -Shader.prototype.destroy = function () { +Shader.prototype.destroy = function () +{ this.gl.deleteProgram(this.program); this.gl = null; @@ -459,13 +491,15 @@ this.fragmentSrc = null; }; -Shader.prototype._glCompile = function (type, src) { +Shader.prototype._glCompile = function (type, src) +{ var shader = this.gl.createShader(type); this.gl.shaderSource(shader, src); this.gl.compileShader(shader); - if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) { + if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) + { window.console.log(this.gl.getShaderInfoLog(shader)); return null; } diff --git a/src/core/renderers/webgl/shaders/StripShader.js b/src/core/renderers/webgl/shaders/StripShader.js index 193f6e1..a7abcc6 100644 --- a/src/core/renderers/webgl/shaders/StripShader.js +++ b/src/core/renderers/webgl/shaders/StripShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function StripShader(gl) { +function StripShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -20,7 +21,8 @@ 'varying vec2 vTextureCoord;', - 'void main(void) {', + '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);', @@ -36,7 +38,8 @@ 'varying vec2 vTextureCoord;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vec2(vTextureCoord.x, vTextureCoord.y)) * alpha;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/utils/FilterTexture.js b/src/core/renderers/webgl/utils/FilterTexture.js index d2c8423..4433d44 100644 --- a/src/core/renderers/webgl/utils/FilterTexture.js +++ b/src/core/renderers/webgl/utils/FilterTexture.js @@ -8,7 +8,8 @@ * @param height {number} the vertical range of the filter * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values */ -function FilterTexture(gl, width, height, scaleMode) { +function FilterTexture(gl, width, height, scaleMode) +{ /** * @member {WebGLContext} */ @@ -59,7 +60,8 @@ * Clears the filter texture. * */ -FilterTexture.prototype.clear = function () { +FilterTexture.prototype.clear = function () +{ var gl = this.gl; gl.clearColor(0,0,0, 0); @@ -72,8 +74,10 @@ * @param width {number} the new width of the texture * @param height {number} the new height of the texture */ -FilterTexture.prototype.resize = function (width, height) { - if (this.width === width && this.height === height) { +FilterTexture.prototype.resize = function (width, height) +{ + if (this.width === width && this.height === height) + { return; } @@ -96,7 +100,8 @@ * Destroys the filter texture. * */ -FilterTexture.prototype.destroy = function () { +FilterTexture.prototype.destroy = function () +{ var gl = this.gl; gl.deleteFramebuffer( this.frameBuffer ); gl.deleteTexture( this.texture ); diff --git a/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js b/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js index c4721e9..a63f4d7 100644 --- a/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js +++ b/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js @@ -14,7 +14,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this sprite batch works for. */ -function WebGLFastSpriteBatch(renderer) { +function WebGLFastSpriteBatch(renderer) +{ /** * The renderer instance this sprite batch operates on. * @@ -91,7 +92,8 @@ */ this.lastIndexCount = 0; - for (var i=0, j=0; i < numIndices; i += 6, j += 4) { + 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; @@ -144,7 +146,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.setupContext(); }); } @@ -157,7 +160,8 @@ * * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLFastSpriteBatch.prototype.setupContext = function () { +WebGLFastSpriteBatch.prototype.setupContext = function () +{ var gl = this.renderer.gl; // create a couple of buffers @@ -177,7 +181,8 @@ /** * @param spriteBatch {SpriteBatch} The SpriteBatch container to prepare for. */ -WebGLFastSpriteBatch.prototype.begin = function (spriteBatch) { +WebGLFastSpriteBatch.prototype.begin = function (spriteBatch) +{ this.shader = this.renderer.shaderManager.fastShader; this.matrix = spriteBatch.worldTransform.toArray(true); @@ -187,33 +192,38 @@ /** */ -WebGLFastSpriteBatch.prototype.end = function () { +WebGLFastSpriteBatch.prototype.end = function () +{ this.flush(); }; /** * @param spriteBatch {SpriteBatch} The SpriteBatch container to render. */ -WebGLFastSpriteBatch.prototype.render = function (spriteBatch) { +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) { + if (!sprite.texture._uvs) + { return; } this.currentBaseTexture = sprite.texture.baseTexture; // check blend mode - if (sprite.blendMode !== this.renderer.blendModeManager.currentBlendMode) { + if (sprite.blendMode !== this.renderer.blendModeManager.currentBlendMode) + { this.flush(); this.renderer.blendModeManager.setBlendMode(sprite.blendMode); } - for (var i=0,j= children.length; i= this.size) { + if (this.currentBatchSize >= this.size) + { this.flush(); } }; @@ -362,29 +379,35 @@ /** * */ -WebGLFastSpriteBatch.prototype.flush = function () { +WebGLFastSpriteBatch.prototype.flush = function () +{ // If the batch is length 0 then return as there is nothing to draw - if (this.currentBatchSize === 0) { + if (this.currentBatchSize === 0) + { return; } var gl = this.renderer.gl; // bind the current texture - if (!this.currentBaseTexture._glTextures[gl.id]) { + if (!this.currentBaseTexture._glTextures[gl.id]) + { this.renderer.updateTexture(this.currentBaseTexture, gl); } //TODO-SHOUD THIS BE ELSE??!?!?! - else { + else + { gl.bindTexture(gl.TEXTURE_2D, this.currentBaseTexture._glTextures[gl.id]); } // upload the verts to the buffer - if (this.currentBatchSize > ( this.size * 0.5 ) ) { + if (this.currentBatchSize > ( this.size * 0.5 ) ) + { gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); } - else { + else + { var view = this.vertices.subarray(0, this.currentBatchSize * this.vertByteSize); gl.bufferSubData(gl.ARRAY_BUFFER, 0, view); @@ -405,14 +428,16 @@ * Ends the batch and flushes * */ -WebGLFastSpriteBatch.prototype.stop = function () { +WebGLFastSpriteBatch.prototype.stop = function () +{ this.flush(); }; /** * */ -WebGLFastSpriteBatch.prototype.start = function () { +WebGLFastSpriteBatch.prototype.start = function () +{ var gl = this.renderer.gl; // bind the main texture diff --git a/src/core/renderers/webgl/utils/WebGLGraphics.js b/src/core/renderers/webgl/utils/WebGLGraphics.js index 55f4911..ab8f46e 100644 --- a/src/core/renderers/webgl/utils/WebGLGraphics.js +++ b/src/core/renderers/webgl/utils/WebGLGraphics.js @@ -19,7 +19,8 @@ * @param graphics {Graphics} * @param renderer {WebGLRenderer} */ -WebGLGraphics.renderGraphics = function (graphics, renderer) {//projection, offset) { +WebGLGraphics.renderGraphics = function (graphics, renderer) {//projection, offset) +{ var gl = renderer.gl; var projection = renderer.projection, @@ -27,7 +28,8 @@ shader = renderer.shaderManager.primitiveShader, webGLData; - if (graphics.dirty) { + if (graphics.dirty) + { WebGLGraphics.updateGraphics(graphics, gl); } @@ -35,8 +37,10 @@ // This could be speeded up for sure! - for (var i = 0; i < webGL.data.length; i++) { - if (webGL.data[i].mode === 1) { + for (var i = 0; i < webGL.data.length; i++) + { + if (webGL.data[i].mode === 1) + { webGLData = webGL.data[i]; renderer.stencilManager.pushStencil(graphics, webGLData, renderer); @@ -46,7 +50,8 @@ renderer.stencilManager.popStencil(graphics, webGLData, renderer); } - else { + else + { webGLData = webGL.data[i]; @@ -84,12 +89,14 @@ * @param graphicsData {Graphics} The graphics object to update * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLGraphics.updateGraphics = function (graphics, gl) { +WebGLGraphics.updateGraphics = function (graphics, gl) +{ // get the contexts graphics object var webGL = graphics._webGL[gl.id]; // if the graphics object does not exist in the webGL context time to create it! - if (!webGL) { + if (!webGL) + { webGL = graphics._webGL[gl.id] = {lastIndex:0, data:[], gl:gl}; } @@ -99,11 +106,13 @@ var i; // if the user cleared the graphics object we will need to clear every object - if (graphics.clearDirty) { + if (graphics.clearDirty) + { graphics.clearDirty = false; // lop through and return all the webGLDatas to the object pool so than can be reused later on - for (i = 0; i < webGL.data.length; i++) { + for (i = 0; i < webGL.data.length; i++) + { var graphicsData = webGL.data[i]; graphicsData.reset(); WebGLGraphics.graphicsDataPool.push( graphicsData ); @@ -119,58 +128,72 @@ // loop through the graphics datas and construct each one.. // if the object is a complex fill then the new stencil buffer technique will be used // other wise graphics objects will be pushed into a batch.. - for (i = webGL.lastIndex; i < graphics.graphicsData.length; i++) { + for (i = webGL.lastIndex; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { // need to add the points the the graphics object.. data.points = data.shape.points.slice(); - if (data.shape.closed) { + if (data.shape.closed) + { // close the poly if the value is true! - if (data.points[0] !== data.points[data.points.length-2] || data.points[1] !== data.points[data.points.length-1]) { + if (data.points[0] !== data.points[data.points.length-2] || data.points[1] !== data.points[data.points.length-1]) + { data.points.push(data.points[0], data.points[1]); } } // MAKE SURE WE HAVE THE CORRECT TYPE.. - if (data.fill) { - if (data.points.length >= 6) { - if (data.points.length < 6 * 2) { + if (data.fill) + { + if (data.points.length >= 6) + { + if (data.points.length < 6 * 2) + { webGLData = WebGLGraphics.switchMode(webGL, 0); var canDrawUsingSimple = WebGLGraphics.buildPoly(data, webGLData); // console.log(canDrawUsingSimple); - if (!canDrawUsingSimple) { + if (!canDrawUsingSimple) + { // console.log("<>>>") webGLData = WebGLGraphics.switchMode(webGL, 1); WebGLGraphics.buildComplexPoly(data, webGLData); } } - else { + else + { webGLData = WebGLGraphics.switchMode(webGL, 1); WebGLGraphics.buildComplexPoly(data, webGLData); } } } - if (data.lineWidth > 0) { + if (data.lineWidth > 0) + { webGLData = WebGLGraphics.switchMode(webGL, 0); WebGLGraphics.buildLine(data, webGLData); } } - else { + else + { webGLData = WebGLGraphics.switchMode(webGL, 0); - if (data.type === CONST.SHAPES.RECT) { + if (data.type === CONST.SHAPES.RECT) + { WebGLGraphics.buildRectangle(data, webGLData); } - else if (data.type === CONST.SHAPES.CIRC || data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.CIRC || data.type === CONST.SHAPES.ELIP) + { WebGLGraphics.buildCircle(data, webGLData); } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { WebGLGraphics.buildRoundedRectangle(data, webGLData); } } @@ -179,10 +202,12 @@ } // upload all the dirty data... - for (i = 0; i < webGL.data.length; i++) { + for (i = 0; i < webGL.data.length; i++) + { webGLData = webGL.data[i]; - if (webGLData.dirty) { + if (webGLData.dirty) + { webGLData.upload(); } } @@ -194,18 +219,22 @@ * @param webGL {WebGLContext} * @param type {number} */ -WebGLGraphics.switchMode = function (webGL, type) { +WebGLGraphics.switchMode = function (webGL, type) +{ var webGLData; - if (!webGL.data.length) { + if (!webGL.data.length) + { webGLData = WebGLGraphics.graphicsDataPool.pop() || new WebGLGraphicsData(webGL.gl); webGLData.mode = type; webGL.data.push(webGLData); } - else { + else + { webGLData = webGL.data[webGL.data.length-1]; - if (webGLData.mode !== type || type === 1) { + if (webGLData.mode !== type || type === 1) + { webGLData = WebGLGraphics.graphicsDataPool.pop() || new WebGLGraphicsData(webGL.gl); webGLData.mode = type; webGL.data.push(webGLData); @@ -225,7 +254,8 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildRectangle = function (graphicsData, webGLData) { +WebGLGraphics.buildRectangle = function (graphicsData, webGLData) +{ // --- // // need to convert points to a nice regular data // @@ -235,7 +265,8 @@ var width = rectData.width; var height = rectData.height; - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -265,7 +296,8 @@ indices.push(vertPos, vertPos, vertPos+1, vertPos+2, vertPos+3, vertPos+3); } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = [x, y, @@ -289,7 +321,8 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildRoundedRectangle = function (graphicsData, webGLData) { +WebGLGraphics.buildRoundedRectangle = function (graphicsData, webGLData) +{ var rrectData = graphicsData.shape; var x = rrectData.x; var y = rrectData.y; @@ -305,7 +338,8 @@ recPoints = recPoints.concat(WebGLGraphics.quadraticBezierCurve(x + width, y + radius, x + width, y, x + width - radius, y)); recPoints = recPoints.concat(WebGLGraphics.quadraticBezierCurve(x + radius, y, x, y, x, y + radius)); - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -323,7 +357,8 @@ // var i = 0; - for (i = 0; i < triangles.length; i+=3) { + for (i = 0; i < triangles.length; i+=3) + { indices.push(triangles[i] + vecPos); indices.push(triangles[i] + vecPos); indices.push(triangles[i+1] + vecPos); @@ -332,12 +367,14 @@ } - for (i = 0; i < recPoints.length; i++) { + for (i = 0; i < recPoints.length; i++) + { verts.push(recPoints[i], recPoints[++i], r, g, b, alpha); } } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = recPoints; @@ -362,7 +399,8 @@ * @param toY {number} Destination point y * @return {number[]} */ -WebGLGraphics.quadraticBezierCurve = function (fromX, fromY, cpX, cpY, toX, toY) { +WebGLGraphics.quadraticBezierCurve = function (fromX, fromY, cpX, cpY, toX, toY) +{ var xa, ya, @@ -373,14 +411,16 @@ n = 20, points = []; - function getPt(n1 , n2, perc) { + function getPt(n1 , n2, perc) + { var diff = n2 - n1; return n1 + ( diff * perc ); } var j = 0; - for (var i = 0; i <= n; i++ ) { + for (var i = 0; i <= n; i++ ) + { j = i / n; // The Green Line @@ -406,7 +446,8 @@ * @param graphicsData {Graphics} The graphics object to draw * @param webGLData {object} */ -WebGLGraphics.buildCircle = function (graphicsData, webGLData) { +WebGLGraphics.buildCircle = function (graphicsData, webGLData) +{ // need to convert points to a nice regular data var circleData = graphicsData.shape; var x = circleData.x; @@ -415,11 +456,13 @@ var height; // TODO - bit hacky?? - if (graphicsData.type === CONST.SHAPES.CIRC) { + if (graphicsData.type === CONST.SHAPES.CIRC) + { width = circleData.radius; height = circleData.radius; } - else { + else + { width = circleData.width; height = circleData.height; } @@ -429,7 +472,8 @@ var i = 0; - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -444,7 +488,8 @@ indices.push(vecPos); - for (i = 0; i < totalSegs + 1 ; i++) { + for (i = 0; i < totalSegs + 1 ; i++) + { verts.push(x,y, r, g, b, alpha); verts.push(x + Math.sin(seg * i) * width, @@ -457,12 +502,14 @@ indices.push(vecPos-1); } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = []; - for (i = 0; i < totalSegs + 1; i++) { + for (i = 0; i < totalSegs + 1; i++) + { graphicsData.points.push(x + Math.sin(seg * i) * width, y + Math.cos(seg * i) * height); } @@ -481,18 +528,22 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildLine = function (graphicsData, webGLData) { +WebGLGraphics.buildLine = function (graphicsData, webGLData) +{ // TODO OPTIMISE! var i = 0; var points = graphicsData.points; - if (points.length === 0) { + if (points.length === 0) + { return; } // if the line width is an odd number add 0.5 to align to a whole pixel - if (graphicsData.lineWidth%2) { - for (i = 0; i < points.length; i++) { + if (graphicsData.lineWidth%2) + { + for (i = 0; i < points.length; i++) + { points[i] += 0.5; } } @@ -502,7 +553,8 @@ var lastPoint = new math.Point(points[points.length - 2], points[points.length - 1]); // if the first point is the last point - gonna have issues :) - if (firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) { + if (firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) + { // need to clone as we are going to slightly modify the shape.. points = points.slice(); @@ -562,7 +614,8 @@ verts.push(p1x + perpx , p1y + perpy, r, g, b, alpha); - for (i = 1; i < length-1; i++) { + for (i = 1; i < length-1; i++) + { p1x = points[(i-1)*2]; p1y = points[(i-1)*2 + 1]; @@ -599,7 +652,8 @@ denom = a1*b2 - a2*b1; - if (Math.abs(denom) < 0.1 ) { + if (Math.abs(denom) < 0.1 ) + { denom+=10.1; verts.push(p2x - perpx , p2y - perpy, @@ -618,7 +672,8 @@ pdist = (px -p2x) * (px -p2x) + (py -p2y) + (py -p2y); - if (pdist > 140 * 140) { + if (pdist > 140 * 140) + { perp3x = perpx - perp2x; perp3y = perpy - perp2y; @@ -639,7 +694,8 @@ indexCount++; } - else { + else + { verts.push(px , py); verts.push(r, g, b, alpha); @@ -672,7 +728,8 @@ indices.push(indexStart); - for (i = 0; i < indexCount; i++) { + for (i = 0; i < indexCount; i++) + { indices.push(indexStart++); } @@ -687,11 +744,13 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildComplexPoly = function (graphicsData, webGLData) { +WebGLGraphics.buildComplexPoly = function (graphicsData, webGLData) +{ //TODO - no need to copy this as it gets turned into a FLoat32Array anyways.. var points = graphicsData.points.slice(); - if (points.length < 6) { + if (points.length < 6) + { return; } @@ -711,7 +770,8 @@ var x,y; // get size.. - for (var i = 0; i < points.length; i+=2) { + for (var i = 0; i < points.length; i+=2) + { x = points[i]; y = points[i+1]; @@ -732,7 +792,8 @@ //TODO - this aint needed! var length = points.length / 2; - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { indices.push( i ); } @@ -746,10 +807,12 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildPoly = function (graphicsData, webGLData) { +WebGLGraphics.buildPoly = function (graphicsData, webGLData) +{ var points = graphicsData.points; - if (points.length < 6) { + if (points.length < 6) + { return; } // get first and last point.. figure out the middle! @@ -767,7 +830,8 @@ var triangles = utils.PolyK.Triangulate(points); - if (!triangles) { + if (!triangles) + { return false; } @@ -775,7 +839,8 @@ var i = 0; - for (i = 0; i < triangles.length; i+=3) { + for (i = 0; i < triangles.length; i+=3) + { indices.push(triangles[i] + vertPos); indices.push(triangles[i] + vertPos); indices.push(triangles[i+1] + vertPos); @@ -783,7 +848,8 @@ indices.push(triangles[i+2] + vertPos); } - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { verts.push(points[i * 2], points[i * 2 + 1], r, g, b, alpha); } diff --git a/src/core/renderers/webgl/utils/WebGLGraphicsData.js b/src/core/renderers/webgl/utils/WebGLGraphicsData.js index c56d05e..c739ba7 100644 --- a/src/core/renderers/webgl/utils/WebGLGraphicsData.js +++ b/src/core/renderers/webgl/utils/WebGLGraphicsData.js @@ -2,7 +2,8 @@ * @class * @private */ -function WebGLGraphicsData(gl) { +function WebGLGraphicsData(gl) +{ this.gl = gl; //TODO does this need to be split before uploding?? @@ -22,7 +23,8 @@ /** * */ -WebGLGraphicsData.prototype.reset = function () { +WebGLGraphicsData.prototype.reset = function () +{ this.points.length = 0; this.indices.length = 0; }; @@ -30,7 +32,8 @@ /** * */ -WebGLGraphicsData.prototype.upload = function () { +WebGLGraphicsData.prototype.upload = function () +{ var gl = this.gl; // this.lastIndex = graphics.graphicsData.length; diff --git a/src/core/renderers/webgl/utils/WebGLSpriteBatch.js b/src/core/renderers/webgl/utils/WebGLSpriteBatch.js index 96eaa52..55befbb 100644 --- a/src/core/renderers/webgl/utils/WebGLSpriteBatch.js +++ b/src/core/renderers/webgl/utils/WebGLSpriteBatch.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this sprite batch works for. */ -function WebGLSpriteBatch(renderer) { +function WebGLSpriteBatch(renderer) +{ /** * * @@ -88,7 +89,8 @@ */ this.lastIndexCount = 0; - for (var i=0, j=0; i < numIndices; i += 6, j += 4) { + 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; @@ -162,7 +164,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.setupContext(); }); } @@ -173,7 +176,8 @@ /** * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLSpriteBatch.prototype.setupContext = function () { +WebGLSpriteBatch.prototype.setupContext = function () +{ var gl = this.renderer.gl; // setup default shader @@ -198,7 +202,8 @@ /** * */ -WebGLSpriteBatch.prototype.begin = function () { +WebGLSpriteBatch.prototype.begin = function () +{ // this.shader = this.renderer.shaderManager.defaultShader; this.start(); @@ -206,19 +211,22 @@ /** */ -WebGLSpriteBatch.prototype.end = function () { +WebGLSpriteBatch.prototype.end = function () +{ this.flush(); }; /** * @param sprite {Sprite} the sprite to render when using this spritebatch */ -WebGLSpriteBatch.prototype.render = function (sprite) { +WebGLSpriteBatch.prototype.render = function (sprite) +{ var texture = sprite.texture; //TODO set blend modes.. // check texture.. - if (this.currentBatchSize >= this.size) { + if (this.currentBatchSize >= this.size) + { this.flush(); this.currentBaseTexture = texture.baseTexture; } @@ -227,7 +235,8 @@ var uvs = texture._uvs; // if the uvs have not updated then no point rendering just yet! - if (!uvs) { + if (!uvs) + { return; } @@ -237,7 +246,8 @@ var w0, w1, h0, h1; - if (texture.trim) { + 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; @@ -248,7 +258,8 @@ h0 = h1 + texture.crop.height; } - else { + else + { w0 = (texture.frame.width ) * (1-aX); w1 = (texture.frame.width ) * -aX; @@ -272,7 +283,8 @@ var colors = this.colors; var positions = this.positions; - if (this.renderer.roundPixels) { + if (this.renderer.roundPixels) + { // xy positions[index] = a * w1 + c * h1 + tx | 0; positions[index+1] = d * h1 + b * w1 + ty | 0; @@ -289,7 +301,8 @@ positions[index+15] = a * w1 + c * h0 + tx | 0; positions[index+16] = d * h0 + b * w1 + ty | 0; } - else { + else + { // xy positions[index] = a * w1 + c * h1 + tx; positions[index+1] = d * h1 + b * w1 + ty; @@ -338,11 +351,13 @@ * * @param sprite {TilingSprite} the tilingSprite to render */ -WebGLSpriteBatch.prototype.renderTilingSprite = function (tilingSprite) { +WebGLSpriteBatch.prototype.renderTilingSprite = function (tilingSprite) +{ var texture = tilingSprite.tilingTexture; // check texture.. - if (this.currentBatchSize >= this.size) { + if (this.currentBatchSize >= this.size) + { //return; this.flush(); this.currentBaseTexture = texture.baseTexture; @@ -351,7 +366,8 @@ // set the textures uvs temporarily // TODO create a separate texture so that we can tile part of a texture - if (!tilingSprite._uvs) { + if (!tilingSprite._uvs) + { tilingSprite._uvs = new TextureUvs(); } @@ -454,16 +470,19 @@ * Renders the content and empties the current batch. * */ -WebGLSpriteBatch.prototype.flush = function () { +WebGLSpriteBatch.prototype.flush = function () +{ // If the batch is length 0 then return as there is nothing to draw - if (this.currentBatchSize === 0) { + if (this.currentBatchSize === 0) + { return; } var gl = this.renderer.gl; var shader; - if (this.dirty) { + if (this.dirty) + { this.dirty = false; // bind the main texture gl.activeTexture(gl.TEXTURE0); @@ -482,10 +501,12 @@ } // upload the verts to the buffer - if (this.currentBatchSize > ( this.size * 0.5 ) ) { + if (this.currentBatchSize > ( this.size * 0.5 ) ) + { gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); } - else { + else + { var view = this.positions.subarray(0, this.currentBatchSize * this.vertByteSize); gl.bufferSubData(gl.ARRAY_BUFFER, 0, view); } @@ -502,7 +523,8 @@ var shaderSwap = false; var sprite; - for (var i = 0, j = this.currentBatchSize; i < j; i++) { + for (var i = 0, j = this.currentBatchSize; i < j; i++) + { sprite = this.sprites[i]; @@ -513,24 +535,28 @@ blendSwap = currentBlendMode !== nextBlendMode; shaderSwap = currentShader !== nextShader; // should I use uuidS??? - if (currentBaseTexture !== nextTexture || blendSwap || shaderSwap) { + if (currentBaseTexture !== nextTexture || blendSwap || shaderSwap) + { this.renderBatch(currentBaseTexture, batchSize, start); start = i; batchSize = 0; currentBaseTexture = nextTexture; - if (blendSwap) { + if (blendSwap) + { currentBlendMode = nextBlendMode; this.renderer.blendModeManager.setBlendMode( currentBlendMode ); } - if (shaderSwap) { + if (shaderSwap) + { currentShader = nextShader; shader = currentShader.shaders ? currentShader.shaders[gl.id] : currentShader; - if (!shader) { + if (!shader) + { shader = new Shader(gl, null, currentShader.fragmentSrc, currentShader.uniforms); currentShader.shaders[gl.id] = shader; } @@ -538,7 +564,8 @@ // set shader function??? this.renderer.shaderManager.setShader(shader); - if (shader.dirty) { + if (shader.dirty) + { shader.syncUniforms(); } @@ -569,17 +596,21 @@ * @param size {number} * @param startIndex {number} */ -WebGLSpriteBatch.prototype.renderBatch = function (texture, size, startIndex) { - if (size === 0) { +WebGLSpriteBatch.prototype.renderBatch = function (texture, size, startIndex) +{ + if (size === 0) + { return; } var gl = this.renderer.gl; - if (!texture._glTextures[gl.id]) { + if (!texture._glTextures[gl.id]) + { this.renderer.updateTexture(texture); } - else { + else + { // bind the current texture gl.bindTexture(gl.TEXTURE_2D, texture._glTextures[gl.id]); } @@ -594,7 +625,8 @@ /** * */ -WebGLSpriteBatch.prototype.stop = function () { +WebGLSpriteBatch.prototype.stop = function () +{ this.flush(); this.dirty = true; }; @@ -602,7 +634,8 @@ /** * */ -WebGLSpriteBatch.prototype.start = function () { +WebGLSpriteBatch.prototype.start = function () +{ this.dirty = true; }; @@ -610,7 +643,8 @@ * Destroys the SpriteBatch. * */ -WebGLSpriteBatch.prototype.destroy = function () { +WebGLSpriteBatch.prototype.destroy = function () +{ this.renderer.gl.deleteBuffer(this.vertexBuffer); this.renderer.gl.deleteBuffer(this.indexBuffer); diff --git a/src/core/textures/BaseTexture.js b/src/core/textures/BaseTexture.js index 2bf77d4..513d358 100644 --- a/src/core/textures/BaseTexture.js +++ b/src/core/textures/BaseTexture.js @@ -10,7 +10,8 @@ * @param source {Image|Canvas} the source object of the texture. * @param [scaleMode=scaleModes.DEFAULT] {number} See {@link scaleModes} for possible values */ -function BaseTexture(source, scaleMode) { +function BaseTexture(source, scaleMode) +{ this.uuid = utils.uuid(); /** @@ -123,7 +124,8 @@ this._needsUpdate = false; // if no source passed don't try to load - if (source) { + if (source) + { this.loadSource(source); } @@ -149,13 +151,16 @@ Object.defineProperties(BaseTexture.prototype, { needsUpdate: { - get: function () { + get: function () + { return this._needsUpdate; }, - set: function (val) { + set: function (val) + { this._needsUpdate = val; - if (val) { + if (val) + { this.emit('update', this); } } @@ -171,9 +176,11 @@ * * The logic state after calling `loadSource` directly or indirectly (eg. `fromImage`, `new BaseTexture`) is: * - * if (texture.hasLoaded) { + * if (texture.hasLoaded) + { * // texture ready for use - * } else if (texture.isLoading) { + * } else if (texture.isLoading) + { * // listen to 'loaded' and/or 'error' events on texture * } else { * // not loading, not going to load UNLESS the source is reloaded @@ -183,12 +190,14 @@ * @protected * @param source {Image|Canvas} the source object of the texture. */ -BaseTexture.prototype.loadSource = function (source) { +BaseTexture.prototype.loadSource = function (source) +{ var wasLoading = this.isLoading; this.hasLoaded = false; this.isLoading = false; - if (wasLoading && this.source) { + if (wasLoading && this.source) + { this.source.onload = null; this.source.onerror = null; } @@ -196,20 +205,24 @@ this.source = source; // Apply source if loaded. Otherwise setup appropriate loading monitors. - if ((this.source.complete || this.source.getContext) && this.source.width && this.source.height) { + if ((this.source.complete || this.source.getContext) && this.source.width && this.source.height) + { this._sourceLoaded(); } - else if(!source.getContext) { + else if(!source.getContext) + { // Image fail / not ready this.isLoading = true; var scope = this; - source.onload = function () { + source.onload = function () + { source.onload = null; source.onerror = null; - if(!scope.isLoading) { + if(!scope.isLoading) + { return; } @@ -219,11 +232,13 @@ scope.emit('loaded', scope); }; - source.onerror = function () { + source.onerror = function () + { source.onload = null; source.onerror = null; - if(!scope.isLoading) { + if(!scope.isLoading) + { return; } @@ -234,24 +249,29 @@ // Per http://www.w3.org/TR/html5/embedded-content-0.html#the-img-element // "The value of `complete` can thus change while a script is executing." // So complete needs to be re-checked after the callbacks have been added.. - if (source.complete) { + if (source.complete) + { this.isLoading = false; // ..and if we're complete now, no need for callbacks source.onload = null; source.onerror = null; - if (source.width && source.height) { + if (source.width && source.height) + { this._sourceLoaded(); // If any previous subscribers possible - if (wasLoading) { + if (wasLoading) + { this.emit('loaded', this); } } - else { + else + { // If any previous subscribers possible - if (wasLoading) { + if (wasLoading) + { this.emit('error', this); } } @@ -265,7 +285,8 @@ * * @private */ -BaseTexture.prototype._sourceLoaded = function () { +BaseTexture.prototype._sourceLoaded = function () +{ this.hasLoaded = true; this.width = this.source.naturalWidth || this.source.width; @@ -278,16 +299,20 @@ * Destroys this base texture * */ -BaseTexture.prototype.destroy = function () { - if (this.imageUrl) { +BaseTexture.prototype.destroy = function () +{ + if (this.imageUrl) + { delete utils.BaseTextureCache[this.imageUrl]; delete utils.TextureCache[this.imageUrl]; this.imageUrl = null; - if (!navigator.isCocoonJS) { + if (!navigator.isCocoonJS) + { this.source.src = ''; } } - else if (this.source && this.source._pixiId) { + else if (this.source && this.source._pixiId) + { delete utils.BaseTextureCache[this.source._pixiId]; } this.source = null; @@ -301,7 +326,8 @@ * memory again. * */ -BaseTexture.prototype.dispose = function () { +BaseTexture.prototype.dispose = function () +{ this.emit('dispose', this); }; @@ -311,7 +337,8 @@ * * @param newSrc {string} the path of the image */ -BaseTexture.prototype.updateSourceImage = function (newSrc) { +BaseTexture.prototype.updateSourceImage = function (newSrc) +{ this.source.src = newSrc; this.loadSource(this.source); }; @@ -326,18 +353,22 @@ * @param [scaleMode=scaleModes.DEFAULT] {number} See {@link scaleModes} for possible values * @return BaseTexture */ -BaseTexture.fromImage = function (imageUrl, crossorigin, scaleMode) { +BaseTexture.fromImage = function (imageUrl, crossorigin, scaleMode) +{ var baseTexture = utils.BaseTextureCache[imageUrl]; - if (crossorigin === undefined && imageUrl.indexOf('data:') !== 0) { + if (crossorigin === undefined && imageUrl.indexOf('data:') !== 0) + { crossorigin = true; } - if (!baseTexture) { + if (!baseTexture) + { // new Image() breaks tex loading in some versions of Chrome. // See https://code.google.com/p/chromium/issues/detail?id=238071 var image = new Image();//document.createElement('img'); - if (crossorigin) { + if (crossorigin) + { image.crossOrigin = ''; } @@ -347,7 +378,8 @@ utils.BaseTextureCache[imageUrl] = baseTexture; // if there is an @2x at the end of the url we are going to assume its a highres image - if ( imageUrl.indexOf(CONST.RETINA_PREFIX + '.') !== -1) { + if ( imageUrl.indexOf(CONST.RETINA_PREFIX + '.') !== -1) + { baseTexture.resolution = 2; } } @@ -363,14 +395,17 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return BaseTexture */ -BaseTexture.fromCanvas = function (canvas, scaleMode) { - if (!canvas._pixiId) { +BaseTexture.fromCanvas = function (canvas, scaleMode) +{ + if (!canvas._pixiId) + { canvas._pixiId = 'canvas_' + utils.uuid(); } var baseTexture = utils.BaseTextureCache[canvas._pixiId]; - if (!baseTexture) { + if (!baseTexture) + { baseTexture = new BaseTexture(canvas, scaleMode); utils.BaseTextureCache[canvas._pixiId] = baseTexture; } diff --git a/src/core/textures/RenderTexture.js b/src/core/textures/RenderTexture.js index 6dad20f..53ae796 100644 --- a/src/core/textures/RenderTexture.js +++ b/src/core/textures/RenderTexture.js @@ -46,8 +46,10 @@ * @param [scaleMode] {number} See {@link scaleModes} for possible values * @param [resolution=1] {number} The resolution of the texture being generated */ -function RenderTexture(renderer, width, height, scaleMode, resolution) { - if (!renderer) { +function RenderTexture(renderer, width, height, scaleMode, resolution) +{ + if (!renderer) + { throw new Error('Unable to create RenderTexture, you must pass a renderer into the constructor.'); } @@ -133,7 +135,8 @@ */ this.renderer = renderer; - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { var gl = this.renderer.gl; this.textureBuffer = new FilterTexture(gl, this.width * this.resolution, this.height * this.resolution, this.baseTexture.scaleMode); @@ -142,7 +145,8 @@ this.render = this.renderWebGL; this.projection = new math.Point(this.width*0.5, -this.height*0.5); } - else { + else + { this.render = this.renderCanvas; this.textureBuffer = new CanvasBuffer(this.width* this.resolution, this.height* this.resolution); this.baseTexture.source = this.textureBuffer.canvas; @@ -167,8 +171,10 @@ * @param height {number} The height to resize to. * @param updateBase {boolean} Should the baseTexture.width and height values be resized as well? */ -RenderTexture.prototype.resize = function (width, height, updateBase) { - if (width === this.width && height === this.height) { +RenderTexture.prototype.resize = function (width, height, updateBase) +{ + if (width === this.width && height === this.height) + { return; } @@ -177,17 +183,20 @@ this.width = this.frame.width = this.crop.width = width; this.height = this.frame.height = this.crop.height = height; - if (updateBase) { + if (updateBase) + { this.baseTexture.width = this.width; this.baseTexture.height = this.height; } - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { this.projection.x = this.width / 2; this.projection.y = -this.height / 2; } - if (!this.valid) { + if (!this.valid) + { return; } @@ -198,12 +207,15 @@ * Clears the RenderTexture. * */ -RenderTexture.prototype.clear = function () { - if (!this.valid) { +RenderTexture.prototype.clear = function () +{ + if (!this.valid) + { return; } - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { this.renderer.gl.bindFramebuffer(this.renderer.gl.FRAMEBUFFER, this.textureBuffer.frameBuffer); } @@ -220,19 +232,23 @@ * @param [restoreWorldTransform=true] {boolean} If true the displayObject's worldTransform/worldAlpha and all children * transformations will be restored. Not restoring this information will be a little faster. */ -RenderTexture.prototype.renderWebGL = function (displayObject, matrix, clear, restoreWorldTransform) { - if (!this.valid) { +RenderTexture.prototype.renderWebGL = function (displayObject, matrix, clear, restoreWorldTransform) +{ + if (!this.valid) + { return; } - if (typeof restoreWorldTransform === 'undefined') { + if (typeof restoreWorldTransform === 'undefined') + { restoreWorldTransform = true; } var tempAlpha, tempTransform; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { tempAlpha = displayObject.worldAlpha; tempTransform = displayObject.worldTransform.toArray(); } @@ -245,7 +261,8 @@ wt.identity(); wt.translate(0, this.projection.y * 2); - if (matrix) { + if (matrix) + { wt.append(matrix); } @@ -258,7 +275,8 @@ var children = displayObject.children; var i, j; - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } @@ -269,7 +287,8 @@ gl.bindFramebuffer(gl.FRAMEBUFFER, this.textureBuffer.frameBuffer ); - if (clear) { + if (clear) + { this.textureBuffer.clear(); } @@ -279,11 +298,13 @@ this.renderer.spriteBatch.dirty = true; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { displayObject.worldAlpha = tempAlpha; displayObject.worldTransform.fromArray(tempTransform); - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } } @@ -300,26 +321,31 @@ * @param [restoreWorldTransform=true] {boolean} If true the displayObject's worldTransform/worldAlpha and all children * transformations will be restored. Not restoring this information will be a little faster. */ -RenderTexture.prototype.renderCanvas = function (displayObject, matrix, clear, restoreWorldTransform) { - if (!this.valid) { +RenderTexture.prototype.renderCanvas = function (displayObject, matrix, clear, restoreWorldTransform) +{ + if (!this.valid) + { return; } - if (typeof restoreWorldTransform === 'undefined') { + if (typeof restoreWorldTransform === 'undefined') + { restoreWorldTransform = true; } var tempAlpha, tempTransform; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { tempAlpha = displayObject.worldAlpha; tempTransform = displayObject.worldTransform.toArray(); } var wt = displayObject.worldTransform; wt.identity(); - if (matrix) { + if (matrix) + { wt.append(matrix); } @@ -330,11 +356,13 @@ var children = displayObject.children; var i, j; - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } - if (clear) { + if (clear) + { this.textureBuffer.clear(); } @@ -348,11 +376,13 @@ this.renderer.resolution = realResolution; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { displayObject.worldAlpha = tempAlpha; displayObject.worldTransform.fromArray(tempTransform); - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } } @@ -363,7 +393,8 @@ * * @return {Image} */ -RenderTexture.prototype.getImage = function () { +RenderTexture.prototype.getImage = function () +{ var image = new Image(); image.src = this.getBase64(); return image; @@ -374,7 +405,8 @@ * * @return {string} A base64 encoded string of the texture. */ -RenderTexture.prototype.getBase64 = function () { +RenderTexture.prototype.getBase64 = function () +{ return this.getCanvas().toDataURL(); }; @@ -383,8 +415,10 @@ * * @return {HTMLCanvasElement} A Canvas element with the texture rendered on. */ -RenderTexture.prototype.getCanvas = function () { - if (this.renderer.type === CONST.WEBGL_RENDERER) { +RenderTexture.prototype.getCanvas = function () +{ + if (this.renderer.type === CONST.WEBGL_RENDERER) + { var gl = this.renderer.gl; var width = this.textureBuffer.width; var height = this.textureBuffer.height; @@ -403,7 +437,8 @@ return tempCanvas.canvas; } - else { + else + { return this.textureBuffer.canvas; } }; diff --git a/src/core/textures/Texture.js b/src/core/textures/Texture.js index 3c65909..e97f0aa 100644 --- a/src/core/textures/Texture.js +++ b/src/core/textures/Texture.js @@ -17,7 +17,8 @@ * @param [crop] {Rectangle} The area of original texture * @param [trim] {Rectangle} Trimmed texture rectangle */ -function Texture(baseTexture, frame, crop, trim) { +function Texture(baseTexture, frame, crop, trim) +{ /** * Does this Texture have any frame data assigned to it? * @@ -25,12 +26,14 @@ */ this.noFrame = false; - if (!frame) { + if (!frame) + { this.noFrame = true; frame = new math.Rectangle(0, 0, 1, 1); } - if (baseTexture instanceof Texture) { + if (baseTexture instanceof Texture) + { baseTexture = baseTexture.baseTexture; } @@ -100,13 +103,16 @@ */ this.crop = crop || new math.Rectangle(0, 0, 1, 1); - if (baseTexture.hasLoaded) { - if (this.noFrame) { + if (baseTexture.hasLoaded) + { + if (this.noFrame) + { frame = new math.Rectangle(0, 0, baseTexture.width, baseTexture.height); } this.frame = frame; } - else { + else + { baseTexture.addEventListener('loaded', this.onBaseTextureLoaded.bind(this)); } } @@ -118,19 +124,23 @@ Object.defineProperties(Texture.prototype, { needsUpdate: { - get: function () { + get: function () + { return this.baseTexture.needsUpdate; }, - set: function (val) { + set: function (val) + { this.baseTexture.needsUpdate = val; } }, frame: { - get: function () { + get: function () + { return this._frame; }, - set: function (frame) { + set: function (frame) + { this._frame = frame; this.noFrame = false; @@ -143,20 +153,23 @@ 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 (!this.trim && (frame.x + frame.width > this.baseTexture.width || frame.y + frame.height > this.baseTexture.height)) + { throw new Error('Texture Error: frame does not fit inside the base Texture dimensions ' + this); } this.valid = frame && frame.width && frame.height && this.baseTexture.source && this.baseTexture.hasLoaded; - if (this.trim) { + 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) { + if (this.valid) + { this._updateUvs(); } } @@ -168,11 +181,13 @@ * * @private */ -Texture.prototype.onBaseTextureLoaded = function () { +Texture.prototype.onBaseTextureLoaded = function () +{ var baseTexture = this.baseTexture; baseTexture.removeEventListener('loaded', this.onLoaded); - if (this.noFrame) { + if (this.noFrame) + { this.frame = new math.Rectangle(0, 0, baseTexture.width, baseTexture.height); } @@ -184,8 +199,10 @@ * * @param destroyBase {boolean} Whether to destroy the base texture as well */ -Texture.prototype.destroy = function (destroyBase) { - if (destroyBase) { +Texture.prototype.destroy = function (destroyBase) +{ + if (destroyBase) + { this.baseTexture.destroy(); } @@ -197,8 +214,10 @@ * * @private */ -Texture.prototype._updateUvs = function () { - if (!this._uvs) { +Texture.prototype._updateUvs = function () +{ + if (!this._uvs) + { this._uvs = new TextureUvs(); } @@ -229,10 +248,12 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return Texture */ -Texture.fromImage = function (imageUrl, crossorigin, scaleMode) { +Texture.fromImage = function (imageUrl, crossorigin, scaleMode) +{ var texture = utils.TextureCache[imageUrl]; - if (!texture) { + if (!texture) + { texture = new Texture(BaseTexture.fromImage(imageUrl, crossorigin, scaleMode)); utils.TextureCache[imageUrl] = texture; } @@ -248,9 +269,11 @@ * @param frameId {string} The frame id of the texture * @return Texture */ -Texture.fromFrame = function (frameId) { +Texture.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache '); } return texture; @@ -264,7 +287,8 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return {Texture} */ -Texture.fromCanvas = function (canvas, scaleMode) { +Texture.fromCanvas = function (canvas, scaleMode) +{ return new Texture(BaseTexture.fromCanvas(canvas, scaleMode)); }; @@ -276,7 +300,8 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return {Texture} A Texture */ -Texture.fromVideo = function (video, scaleMode) { +Texture.fromVideo = function (video, scaleMode) +{ return new Texture(VideoBaseTexture.baseTextureFromVideo(video, scaleMode)); }; @@ -287,7 +312,8 @@ * @param texture {Texture} The Texture to add to the cache. * @param id {string} The id that the texture will be stored against. */ -Texture.addTextureToCache = function (texture, id) { +Texture.addTextureToCache = function (texture, id) +{ utils.TextureCache[id] = texture; }; @@ -298,7 +324,8 @@ * @param id {string} The id of the texture to be removed * @return {Texture} The texture that was removed */ -Texture.removeTextureFromCache = function (id) { +Texture.removeTextureFromCache = function (id) +{ var texture = utils.TextureCache[id]; delete utils.TextureCache[id]; diff --git a/src/core/textures/TextureUvs.js b/src/core/textures/TextureUvs.js index b9bbb58..5424d52 100644 --- a/src/core/textures/TextureUvs.js +++ b/src/core/textures/TextureUvs.js @@ -1,4 +1,5 @@ -function TextureUvs() { +function TextureUvs() +{ this.x0 = 0; this.y0 = 0; diff --git a/src/core/textures/VideoBaseTexture.js b/src/core/textures/VideoBaseTexture.js index e3e0c5a..1a826a9 100644 --- a/src/core/textures/VideoBaseTexture.js +++ b/src/core/textures/VideoBaseTexture.js @@ -12,15 +12,18 @@ * @param source {HTMLVideoElement} * @param [scaleMode] {number} See {@link scaleModes} for possible values */ -function VideoBaseTexture(source, scaleMode) { - if (!source){ +function VideoBaseTexture(source, scaleMode) +{ + if (!source) + { throw new Error('No video source element specified.'); } // hook in here to check if video is already available. // BaseTexture looks for a source.complete boolean, plus width & height. - if ((source.readyState === source.HAVE_ENOUGH_DATA || source.readyState === source.HAVE_FUTURE_DATA) && source.width && source.height) { + if ((source.readyState === source.HAVE_ENOUGH_DATA || source.readyState === source.HAVE_FUTURE_DATA) && source.width && source.height) + { source.complete = true; } @@ -31,7 +34,8 @@ this._boundOnUpdate = this._onUpdate.bind(this); this._boundOnCanPlay = this._onCanPlay.bind(this); - if (!source.complete) { + if (!source.complete) + { source.addEventListener('canplay', this._boundOnCanPlay); source.addEventListener('canplaythrough', this._boundOnCanPlay); @@ -47,28 +51,35 @@ VideoBaseTexture.prototype.constructor = VideoBaseTexture; module.exports = VideoBaseTexture; -VideoBaseTexture.prototype._onUpdate = function () { - if (this.autoUpdate) { +VideoBaseTexture.prototype._onUpdate = function () +{ + if (this.autoUpdate) + { window.requestAnimationFrame(this._boundOnUpdate); this.needsUpdate = true; } }; -VideoBaseTexture.prototype._onPlayStart = function () { - if (!this.autoUpdate) { +VideoBaseTexture.prototype._onPlayStart = function () +{ + if (!this.autoUpdate) + { window.requestAnimationFrame(this._boundOnUpdate); this.autoUpdate = true; } }; -VideoBaseTexture.prototype._onPlayStop = function () { +VideoBaseTexture.prototype._onPlayStop = function () +{ this.autoUpdate = false; }; -VideoBaseTexture.prototype._onCanPlay = function () { +VideoBaseTexture.prototype._onCanPlay = function () +{ this.hasLoaded = true; - if (this.source) { + if (this.source) + { this.source.removeEventListener('canplay', this._boundOnCanPlay); this.source.removeEventListener('canplaythrough', this._boundOnCanPlay); @@ -78,15 +89,18 @@ this.source.play(); // prevent multiple loaded dispatches.. - if(!this.__loaded){ + if(!this.__loaded) + { this.__loaded = true; this.emit('loaded', this); } } }; -VideoBaseTexture.prototype.destroy = function () { - if (this.source && this.source._pixiId) { +VideoBaseTexture.prototype.destroy = function () +{ + if (this.source && this.source._pixiId) + { utils.BaseTextureCache[ this.source._pixiId ] = null; delete utils.BaseTextureCache[ this.source._pixiId ]; @@ -105,14 +119,17 @@ * @param scaleMode {number} See {@link scaleModes} for possible values * @return {VideoBaseTexture} */ -VideoBaseTexture.fromVideo = function (video, scaleMode) { - if (!video._pixiId) { +VideoBaseTexture.fromVideo = function (video, scaleMode) +{ + if (!video._pixiId) + { video._pixiId = 'video_' + utils.uuid(); } var baseTexture = utils.BaseTextureCache[video._pixiId]; - if (!baseTexture) { + if (!baseTexture) + { baseTexture = new VideoBaseTexture(video, scaleMode); utils.BaseTextureCache[ video._pixiId ] = baseTexture; } @@ -147,17 +164,21 @@ * @param scaleMode {number} See {@link scaleModes} for possible values * @return {VideoBaseTexture} */ -VideoBaseTexture.fromUrl = function (videoSrc, scaleMode) { +VideoBaseTexture.fromUrl = function (videoSrc, scaleMode) +{ var video = document.createElement('video'); // array of objects or strings - if (Array.isArray(videoSrc)) { - for (var i = 0; i < videoSrc.length; ++i) { + if (Array.isArray(videoSrc)) + { + for (var i = 0; i < videoSrc.length; ++i) + { video.appendChild(createSource(videoSrc.src || videoSrc, videoSrc.mime)); } } // single object or string - else { + else + { video.appendChild(createSource(videoSrc.src || videoSrc, videoSrc.mime)); } @@ -169,8 +190,10 @@ VideoBaseTexture.fromUrls = VideoBaseTexture.fromUrl; -function createSource(path, type) { - if (!type) { +function createSource(path, type) +{ + if (!type) + { type = 'video/' + path.substr(path.lastIndexOf('.') + 1); } diff --git a/src/core/utils/EventData.js b/src/core/utils/EventData.js index 5d55a22..8cdf701 100644 --- a/src/core/utils/EventData.js +++ b/src/core/utils/EventData.js @@ -7,7 +7,8 @@ * @param name {string} The string name of the event that was triggered * @param data {object} Arbitrary event data to pass along */ -function EventData(target, name, data) { +function EventData(target, name, data) +{ // for duck typing in the ".on()" function this.__isEventObject = true; @@ -71,7 +72,8 @@ * Stops the propagation of events up the scene graph (prevents bubbling). * */ -EventData.prototype.stopPropagation = function stopPropagation() { +EventData.prototype.stopPropagation = function stopPropagation() +{ this.stopped = true; }; @@ -79,6 +81,7 @@ * Stops the propagation of events to sibling listeners (no longer calls any listeners). * */ -EventData.prototype.stopImmediatePropagation = function stopImmediatePropagation() { +EventData.prototype.stopImmediatePropagation = function stopImmediatePropagation() +{ this.stoppedImmediate = true; }; diff --git a/src/core/utils/EventTarget.js b/src/core/utils/EventTarget.js index 7ae8820..671a151 100644 --- a/src/core/utils/EventTarget.js +++ b/src/core/utils/EventTarget.js @@ -13,14 +13,16 @@ * var em = new MyEmitter(); * em.emit('eventName', 'some data', 'some more data', {}, null, ...); */ -function eventTarget(obj) { +function eventTarget(obj) +{ /** * Return a list of assigned event listeners. * * @param eventName {string} The events that should be listed. * @return {Array} An array of listener functions */ - obj.listeners = function listeners(eventName) { + obj.listeners = function listeners(eventName) + { this._listeners = this._listeners || {}; return this._listeners[eventName] ? this._listeners[eventName].slice() : []; @@ -33,22 +35,26 @@ * @param eventName {string} The name of the event. * @return {boolean} Indication if we've emitted an event. */ - obj.emit = obj.dispatchEvent = function emit(eventName, data) { + obj.emit = obj.dispatchEvent = function emit(eventName, data) + { this._listeners = this._listeners || {}; // fast return when there are no listeners - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return; } //backwards compat with old method ".emit({ type: 'something' })" - if (typeof eventName === 'object') { + if (typeof eventName === 'object') + { data = eventName; eventName = eventName.type; } //ensure we are using a real pixi event - if (!data || data.__isEventObject !== true) { + if (!data || data.__isEventObject !== true) + { data = new EventData(this, eventName, data); } @@ -58,23 +64,27 @@ fn = listeners[0], i; - for (i = 0; i < length; fn = listeners[++i]) { + for (i = 0; i < length; fn = listeners[++i]) + { //call the event listener fn.call(this, data); //if "stopImmediatePropagation" is called, stop calling sibling events - if (data.stoppedImmediate) { + if (data.stoppedImmediate) + { return this; } } //if "stopPropagation" is called then don't bubble the event - if (data.stopped) { + if (data.stopped) + { return this; } //bubble this event up the scene graph - if (this.parent && this.parent.emit) { + if (this.parent && this.parent.emit) + { this.parent.emit.call(this.parent, eventName, data); } @@ -88,7 +98,8 @@ * @param eventName {string} Name of the event. * @param callback {Functon} fn Callback function. */ - obj.on = obj.addEventListener = function on(eventName, fn) { + obj.on = obj.addEventListener = function on(eventName, fn) + { this._listeners = this._listeners || {}; (this._listeners[eventName] = this._listeners[eventName] || []) @@ -103,11 +114,13 @@ * @param eventName {string} Name of the event. * @param callback {Function} Callback function. */ - obj.once = function once(eventName, fn) { + obj.once = function once(eventName, fn) + { this._listeners = this._listeners || {}; var self = this; - function onceHandlerWrapper() { + function onceHandlerWrapper() + { fn.apply(self.off(eventName, onceHandlerWrapper), arguments); } onceHandlerWrapper._originalHandler = fn; @@ -122,23 +135,28 @@ * @param eventName {string} The event we want to remove. * @param callback {Function} The listener that we need to find. */ - obj.off = obj.removeEventListener = function off(eventName, fn) { + obj.off = obj.removeEventListener = function off(eventName, fn) + { this._listeners = this._listeners || {}; - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return this; } var list = this._listeners[eventName], i = fn ? list.length : 0; - while(i-- > 0) { - if (list[i] === fn || list[i]._originalHandler === fn) { + while(i-- > 0) + { + if (list[i] === fn || list[i]._originalHandler === fn) + { list.splice(i, 1); } } - if (list.length === 0) { + if (list.length === 0) + { delete this._listeners[eventName]; } @@ -150,10 +168,12 @@ * * @param eventName {string} The event you want to remove all listeners for. */ - obj.removeAllListeners = function removeAllListeners(eventName) { + obj.removeAllListeners = function removeAllListeners(eventName) + { this._listeners = this._listeners || {}; - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return this; } @@ -169,7 +189,8 @@ * * @param object {object} The obj to mix into */ - mixin: function mixin(obj) { + mixin: function mixin(obj) + { eventTarget(obj); } }; diff --git a/src/core/utils/PolyK.js b/src/core/utils/PolyK.js index 7325141..5e20c2b 100644 --- a/src/core/utils/PolyK.js +++ b/src/core/utils/PolyK.js @@ -47,7 +47,8 @@ * Triangulates shapes for webGL graphic fills. * */ -PolyK.Triangulate = function (p) { +PolyK.Triangulate = function (p) +{ var sign = true; var n = p.length >> 1; @@ -59,7 +60,8 @@ i = 0; var al = n; - while(al > 3) { + while(al > 3) + { var i0 = avl[(i+0)%al]; var i1 = avl[(i+1)%al]; var i2 = avl[(i+2)%al]; @@ -69,29 +71,35 @@ var cx = p[2*i2], cy = p[2*i2+1]; var earFound = false; - if (PolyK._convex(ax, ay, bx, by, cx, cy, sign)) { + if (PolyK._convex(ax, ay, bx, by, cx, cy, sign)) + { earFound = true; - for (var j = 0; j < al; j++) { + for (var j = 0; j < al; j++) + { var vi = avl[j]; if (vi === i0 || vi === i1 || vi === i2) continue; - if (PolyK._PointInTriangle(p[2*vi], p[2*vi+1], ax, ay, bx, by, cx, cy)) { + if (PolyK._PointInTriangle(p[2*vi], p[2*vi+1], ax, ay, bx, by, cx, cy)) + { earFound = false; break; } } } - if (earFound) { + if (earFound) + { tgs.push(i0, i1, i2); avl.splice((i+1)%al, 1); al--; i = 0; } - else if (i++ > 3*al) { + else if (i++ > 3*al) + { // need to flip flip reverse it! // reset! - if (sign) { + if (sign) + { tgs = []; avl = []; for (i = 0; i < n; i++) avl.push(i); @@ -101,7 +109,8 @@ sign = false; } - else { + else + { // window.console.log("PIXI Warning: shape too complex to fill"); return null; } @@ -126,7 +135,8 @@ * @private * @return {boolean} */ -PolyK._PointInTriangle = function (px, py, ax, ay, bx, by, cx, cy) { +PolyK._PointInTriangle = function (px, py, ax, ay, bx, by, cx, cy) +{ var v0x = cx-ax; var v0y = cy-ay; var v1x = bx-ax; @@ -154,6 +164,7 @@ * @private * @return {boolean} */ -PolyK._convex = function (ax, ay, bx, by, cx, cy, sign) { +PolyK._convex = function (ax, ay, bx, by, cx, cy, sign) +{ return ((ay-by)*(cx-bx) + (bx-ax)*(cy-by) >= 0) === sign; }; diff --git a/src/core/utils/index.js b/src/core/utils/index.js index ade9831..bfae7ae 100644 --- a/src/core/utils/index.js +++ b/src/core/utils/index.js @@ -16,7 +16,8 @@ * * @return {number} The next uuid to use. */ - uuid: function () { + uuid: function () + { return ++utils._uid; }, @@ -26,7 +27,8 @@ * @param hex {number} * @return {number[]} An array representing the [R, G, B] of the color. */ - hex2rgb: function (hex, out) { + hex2rgb: function (hex, out) + { out = out || []; out[0] = (hex >> 16 & 0xFF) / 255; @@ -42,7 +44,8 @@ * @param hex {number} * @return {string} The string color. */ - hex2string: function (hex) { + hex2string: function (hex) + { hex = hex.toString(16); hex = '000000'.substr(0, 6 - hex.length) + hex; @@ -55,7 +58,8 @@ * @param rgb {number[]} * @return {number} The color number */ - rgb2hex: function (rgb) { + rgb2hex: function (rgb) + { return ((rgb[0]*255 << 16) + (rgb[1]*255 << 8) + rgb[2]*255); }, @@ -64,8 +68,10 @@ * * @return {boolean} whether they are supported */ - canUseNewCanvasBlendModes: function () { - if (typeof document === 'undefined') { + canUseNewCanvasBlendModes: function () + { + if (typeof document === 'undefined') + { return false; } @@ -93,15 +99,19 @@ * @param number {number} * @return {number} the closest number that is a power of two */ - getNextPowerOfTwo: function (number) { + getNextPowerOfTwo: function (number) + { // see: http://en.wikipedia.org/wiki/Power_of_two#Fast_algorithm_to_check_if_a_positive_number_is_a_power_of_two - if (number > 0 && (number & (number - 1)) === 0) { + if (number > 0 && (number & (number - 1)) === 0) + { return number; } - else { + else + { var result = 1; - while (result < number) { + while (result < number) + { result <<= 1; } @@ -116,7 +126,8 @@ * @param height {number} * @return {boolean} */ - isPowerOfTwo: function (width, height) { + isPowerOfTwo: function (width, height) + { return (width > 0 && (width & (width - 1)) === 0 && height > 0 && (height & (height - 1)) === 0); }, @@ -130,12 +141,15 @@ * @constant * @static */ - sayHello: function (type) { - if (utils._saidHello) { + sayHello: function (type) + { + if (utils._saidHello) + { return; } - if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) { + if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) + { var args = [ '%c %c %c Pixi.js ' + CONST.VERSION + ' - ' + type + ' %c ' + ' %c ' + ' http://www.pixijs.com/ %c %c ♥%c♥%c♥ ', 'background: #ff66a5', @@ -151,7 +165,8 @@ console.log.apply(console, args); //jshint ignore:line } - else if (window.console) { + else if (window.console) + { console.log('Pixi.js ' + CONST.VERSION + ' - ' + type + ' - http://www.pixijs.com/'); //jshint ignore:line } @@ -166,15 +181,19 @@ * @class * @namespace PIXI */ - AjaxRequest: function () { + AjaxRequest: function () + { var activexmodes = ['Msxml2.XMLHTTP.6.0', 'Msxml2.XMLHTTP.3.0', 'Microsoft.XMLHTTP']; //activeX versions to check for in IE - if (window.ActiveXObject) { //Test for support for ActiveXObject in IE first (as XMLHttpRequest in IE7 is broken) - for (var i=0; i= this.textures.length) { + else if (round >= this.textures.length) + { this.gotoAndStop(this.textures.length - 1); - if (this.onComplete) { + if (this.onComplete) + { this.onComplete(); } } @@ -167,10 +182,12 @@ * @static * @param frames {string[]} the array of frames ids the movieclip will use as its texture frames */ -MovieClip.fromFrames = function (frames) { +MovieClip.fromFrames = function (frames) +{ var textures = []; - for (var i = 0; i < frames.length; ++i) { + for (var i = 0; i < frames.length; ++i) + { textures.push(new core.Texture.fromFrame(frames[i])); } @@ -183,10 +200,12 @@ * @static * @param images {string[]} the array of image urls the movieclip will use as its texture frames */ -MovieClip.fromImages = function (images) { +MovieClip.fromImages = function (images) +{ var textures = []; - for (var i = 0; i < images.length; ++i) { + for (var i = 0; i < images.length; ++i) + { textures.push(new core.Texture.fromImage(images[i])); } diff --git a/src/extras/Rope.js b/src/extras/Rope.js index c157ec4..9c87bc0 100644 --- a/src/extras/Rope.js +++ b/src/extras/Rope.js @@ -9,7 +9,8 @@ * @param {Array} points - An array of {Point}. * */ -function Rope(texture, points) { +function Rope(texture, points) +{ Strip.call(this, texture); this.points = points; @@ -31,10 +32,12 @@ * Refreshes * */ -Rope.prototype.refresh = function () { +Rope.prototype.refresh = function () +{ var points = this.points; - if (points.length < 1) { + if (points.length < 1) + { return; } @@ -59,20 +62,23 @@ var total = points.length, point, index, amount; - for (var i = 1; i < total; i++) { + for (var i = 1; i < total; i++) + { point = points[i]; index = i * 4; // time to do some smart drawing! amount = i / (total-1); - if (i%2) { + if (i%2) + { uvs[index] = amount; uvs[index+1] = 0; uvs[index+2] = amount; uvs[index+3] = 1; } - else { + else + { uvs[index] = amount; uvs[index+1] = 0; @@ -95,10 +101,12 @@ * * @private */ -Rope.prototype.updateTransform = function () { +Rope.prototype.updateTransform = function () +{ var points = this.points; - if (points.length < 1) { + if (points.length < 1) + { return; } @@ -113,14 +121,17 @@ var total = points.length, point, index, ratio, perpLength, num; - for (var i = 0; i < total; i++) { + for (var i = 0; i < total; i++) + { point = points[i]; index = i * 4; - if (i < points.length-1) { + if (i < points.length-1) + { nextPoint = points[i+1]; } - else { + else + { nextPoint = point; } @@ -129,7 +140,8 @@ ratio = (1 - (i / (total-1))) * 10; - if (ratio > 1) { + if (ratio > 1) + { ratio = 1; } @@ -157,7 +169,8 @@ * * @param texture {Texture} the texture that will be used */ -Rope.prototype.setTexture = function (texture) { +Rope.prototype.setTexture = function (texture) +{ // stop current texture this.texture = texture; //this.updateFrame = true; diff --git a/src/extras/Strip.js b/src/extras/Strip.js index c5e378f..57691b5 100644 --- a/src/extras/Strip.js +++ b/src/extras/Strip.js @@ -10,7 +10,8 @@ * @param height {number} the height * */ -function Strip(texture) { +function Strip(texture) +{ core.DisplayObjectContainer.call(this); /** @@ -70,9 +71,11 @@ * * @param renderer {WebGLRenderer} */ -Strip.prototype.renderWebGL = function (renderer) { +Strip.prototype.renderWebGL = function (renderer) +{ // if the sprite is not visible or the alpha is 0 then no need to render this element - if (!this.visible || this.alpha <= 0) { + if (!this.visible || this.alpha <= 0) + { return; } @@ -81,7 +84,8 @@ renderer.spriteBatch.stop(); // init! init! - if (!this._vertexBuffer) { + if (!this._vertexBuffer) + { this._initWebGL(renderer); } @@ -96,7 +100,8 @@ //TODO check culling }; -Strip.prototype._initWebGL = function (renderer) { +Strip.prototype._initWebGL = function (renderer) +{ // build the strip! var gl = renderer.gl; @@ -118,7 +123,8 @@ gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this.indices, gl.STATIC_DRAW); }; -Strip.prototype._renderStrip = function (renderer) { +Strip.prototype._renderStrip = function (renderer) +{ var gl = renderer.gl; var projection = renderer.projection, offset = renderer.offset, @@ -137,7 +143,8 @@ gl.uniform2f(shader.offsetVector, -offset.x, -offset.y); gl.uniform1f(shader.alpha, this.worldAlpha); - if (!this.dirty) { + if (!this.dirty) + { gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexBuffer); gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); @@ -150,10 +157,12 @@ gl.activeTexture(gl.TEXTURE0); // check if a texture is dirty.. - if (this.texture.baseTexture._dirty[gl.id]) { + if (this.texture.baseTexture._dirty[gl.id]) + { renderer.updateTexture(this.texture.baseTexture); } - else { + else + { // bind the current texture gl.bindTexture(gl.TEXTURE_2D, this.texture.baseTexture._glTextures[gl.id]); } @@ -163,7 +172,8 @@ } - else { + else + { this.dirty = false; gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexBuffer); @@ -178,10 +188,12 @@ gl.activeTexture(gl.TEXTURE0); // check if a texture is dirty.. - if (this.texture.baseTexture._dirty[gl.id]) { + if (this.texture.baseTexture._dirty[gl.id]) + { renderer.updateTexture(this.texture.baseTexture); } - else { + else + { gl.bindTexture(gl.TEXTURE_2D, this.texture.baseTexture._glTextures[gl.id]); } @@ -203,27 +215,33 @@ * * @param renderer {CanvasRenderer} */ -Strip.prototype.renderCanvas = function (renderer) { +Strip.prototype.renderCanvas = function (renderer) +{ var context = renderer.context; var transform = this.worldTransform; - if (renderer.roundPixels) { + if (renderer.roundPixels) + { context.setTransform(transform.a, transform.b, transform.c, transform.d, transform.tx | 0, transform.ty | 0); } - else { + else + { context.setTransform(transform.a, transform.b, transform.c, transform.d, transform.tx, transform.ty); } - if (this.drawMode === Strip.DrawModes.TRIANGLE_STRIP) { + if (this.drawMode === Strip.DrawModes.TRIANGLE_STRIP) + { this._renderCanvasTriangleStrip(context); } - else { + else + { this._renderCanvasTriangles(context); } }; -Strip.prototype._renderCanvasTriangleStrip = function (context) { +Strip.prototype._renderCanvasTriangleStrip = function (context) +{ // draw triangles!! var vertices = this.vertices; var uvs = this.uvs; @@ -231,14 +249,16 @@ var length = vertices.length / 2; // this.count++; - for (var i = 0; i < length - 2; i++) { + for (var i = 0; i < length - 2; i++) + { // draw some triangles! var index = i * 2; this._renderCanvasDrawTriangle(context, vertices, uvs, index, (index + 2), (index + 4)); } }; -Strip.prototype._renderCanvasTriangles = function (context) { +Strip.prototype._renderCanvasTriangles = function (context) +{ // draw triangles!! var vertices = this.vertices; var uvs = this.uvs; @@ -247,14 +267,16 @@ var length = indices.length; // this.count++; - for (var i = 0; i < length; i += 3) { + for (var i = 0; i < length; i += 3) + { // draw some triangles! var index0 = indices[i] * 2, index1 = indices[i + 1] * 2, index2 = indices[i + 2] * 2; this._renderCanvasDrawTriangle(context, vertices, uvs, index0, index1, index2); } }; -Strip.prototype._renderCanvasDrawTriangle = function (context, vertices, uvs, index0, index1, index2) { +Strip.prototype._renderCanvasDrawTriangle = function (context, vertices, uvs, index0, index1, index2) +{ var textureSource = this.texture.baseTexture.source; var textureWidth = this.texture.width; var textureHeight = this.texture.height; @@ -265,7 +287,8 @@ var u0 = uvs[index0] * textureWidth, u1 = uvs[index1] * textureWidth, u2 = uvs[index2] * textureWidth; var v0 = uvs[index0 + 1] * textureHeight, v1 = uvs[index1 + 1] * textureHeight, v2 = uvs[index2 + 1] * textureHeight; - if (this.canvasPadding > 0) { + if (this.canvasPadding > 0) + { var paddingX = this.canvasPadding / this.worldTransform.a; var paddingY = this.canvasPadding / this.worldTransform.d; var centerX = (x0 + x1 + x2) / 3; @@ -332,7 +355,8 @@ * @param strip {Strip} The Strip to render * @private */ -Strip.prototype.renderStripFlat = function (strip) { +Strip.prototype.renderStripFlat = function (strip) +{ var context = this.context; var vertices = strip.vertices; @@ -340,7 +364,8 @@ // this.count++; context.beginPath(); - for (var i=1; i < length-2; i++) { + for (var i=1; i < length-2; i++) + { // draw some triangles! var index = i*2; @@ -358,7 +383,8 @@ }; /* -Strip.prototype.setTexture = function (texture) { +Strip.prototype.setTexture = function (texture) +{ //TODO SET THE TEXTURES //TODO VISIBILITY @@ -377,7 +403,8 @@ * @private */ -Strip.prototype.onTextureUpdate = function () { +Strip.prototype.onTextureUpdate = function () +{ this.updateFrame = true; }; @@ -387,7 +414,8 @@ * @param matrix {Matrix} the transformation matrix of the sprite * @return {Rectangle} the framing rectangle */ -Strip.prototype.getBounds = function (matrix) { +Strip.prototype.getBounds = function (matrix) +{ var worldTransform = matrix || this.worldTransform; var a = worldTransform.a; @@ -404,7 +432,8 @@ var minY = Infinity; var vertices = this.vertices; - for (var i = 0, n = vertices.length; i < n; i += 2) { + for (var i = 0, n = vertices.length; i < n; i += 2) + { var rawX = vertices[i], rawY = vertices[i + 1]; var x = (a * rawX) + (c * rawY) + tx; var y = (d * rawY) + (b * rawX) + ty; @@ -416,7 +445,8 @@ maxY = y > maxY ? y : maxY; } - if (minX === -Infinity || maxY === Infinity) { + if (minX === -Infinity || maxY === Infinity) + { return core.math.Rectangle.EMPTY; } diff --git a/src/extras/TilingSprite.js b/src/extras/TilingSprite.js index 3ac22df..31da393 100644 --- a/src/extras/TilingSprite.js +++ b/src/extras/TilingSprite.js @@ -10,7 +10,8 @@ * @param width {number} the width of the tiling sprite * @param height {number} the height of the tiling sprite */ -function TilingSprite(texture, width, height) { +function TilingSprite(texture, width, height) +{ core.Sprite.call( this, texture); /** @@ -86,10 +87,12 @@ * @memberof TilingSprite# */ width: { - get: function () { + get: function () + { return this._width; }, - set: function (value) { + set: function (value) + { this._width = value; } }, @@ -101,20 +104,25 @@ * @memberof TilingSprite# */ height: { - get: function () { + get: function () + { return this._height; }, - set: function (value) { + set: function (value) + { this._height = value; } }, texture: { - get: function () { + get: function () + { return this._texture; }, - set: function (value) { - if (this._texture === value) { + set: function (value) + { + if (this._texture === value) + { return; } @@ -130,51 +138,61 @@ * * @param renderer {WebGLRenderer} */ -TilingSprite.prototype.renderWebGL = function (renderer) { - if (!this.visible || this.alpha <= 0) { +TilingSprite.prototype.renderWebGL = function (renderer) +{ + if (!this.visible || this.alpha <= 0) + { return; } var i, j; - if (this._mask) { + if (this._mask) + { renderer.spriteBatch.stop(); renderer.maskManager.pushMask(this.mask, renderer); renderer.spriteBatch.start(); } - if (this._filters) { + if (this._filters) + { renderer.spriteBatch.flush(); renderer.filterManager.pushFilter(this._filterBlock); } - if (!this.tilingTexture || this.refreshTexture) { + if (!this.tilingTexture || this.refreshTexture) + { this.generateTilingTexture(true); - if (this.tilingTexture && this.tilingTexture.needsUpdate) { + if (this.tilingTexture && this.tilingTexture.needsUpdate) + { //TODO - tweaking renderer.updateTexture(this.tilingTexture.baseTexture); this.tilingTexture.needsUpdate = false; // this.tilingTexture._uvs = null; } } - else { + else + { renderer.spriteBatch.renderTilingSprite(this); } // simple render children! - for (i=0,j=this.children.length; i= 0 && index <= this.children.length) { - if (child.parent) { + if (index >= 0 && index <= this.children.length) + { + if (child.parent) + { child.parent.removeChild(child); } @@ -154,7 +173,8 @@ return child; } - else { + else + { throw new Error(child + 'addChildAt: The index '+ index +' supplied is out of bounds ' + this.children.length); } }; @@ -165,15 +185,18 @@ * @param child {DisplayObject} * @param child2 {DisplayObject} */ -DisplayObjectContainer.prototype.swapChildren = function (child, child2) { - if (child === child2) { +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) { + if (index1 < 0 || index2 < 0) + { throw new Error('swapChildren: Both the supplied DisplayObjects must be a child of the caller.'); } @@ -187,10 +210,12 @@ * @param child {DisplayObject} The DisplayObject instance to identify * @return {Number} The index position of the child display object to identify */ -DisplayObjectContainer.prototype.getChildIndex = function (child) { +DisplayObjectContainer.prototype.getChildIndex = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { throw new Error('The supplied DisplayObject must be a child of the caller'); } @@ -203,8 +228,10 @@ * @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 */ -DisplayObjectContainer.prototype.setChildIndex = function (child, index) { - if (index < 0 || index >= this.children.length) { +DisplayObjectContainer.prototype.setChildIndex = function (child, index) +{ + if (index < 0 || index >= this.children.length) + { throw new Error('The supplied index is out of bounds'); } @@ -220,8 +247,10 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child at the given index, if any. */ -DisplayObjectContainer.prototype.getChildAt = function (index) { - if (index < 0 || index >= this.children.length) { +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'); } @@ -234,10 +263,12 @@ * @param child {DisplayObject} The DisplayObject to remove * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChild = function (child) { +DisplayObjectContainer.prototype.removeChild = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { return; } @@ -250,7 +281,8 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChildAt = function (index) { +DisplayObjectContainer.prototype.removeChildAt = function (index) +{ var child = this.getChildAt(index); child.parent = null; @@ -265,24 +297,29 @@ * @param beginIndex {Number} The beginning position. Default value is 0. * @param endIndex {Number} The ending position. Default value is size of the container. */ -DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) { +DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) +{ var begin = beginIndex || 0; var end = typeof endIndex === 'number' ? endIndex : this.children.length; var range = end - begin; - if (range > 0 && range <= end) { + if (range > 0 && range <= end) + { var removed = this.children.splice(begin, range); - for (var i = 0; i < removed.length; ++i) { + for (var i = 0; i < removed.length; ++i) + { removed[i].parent = null; } return removed; } - else if (range === 0 && this.children.length === 0) { + else if (range === 0 && this.children.length === 0) + { return []; } - else { + else + { throw new RangeError('removeChildren: numeric values are outside the acceptable range.'); } }; @@ -291,7 +328,8 @@ * Generates and updates the cached sprite for this object. * */ -DisplayObjectContainer.prototype.updateCachedSprite = function () { +DisplayObjectContainer.prototype.updateCachedSprite = function () +{ this._generateCachedSprite(); }; @@ -304,7 +342,8 @@ * @param renderer {CanvasRenderer|WebGLRenderer} The renderer used to generate the texture. * @return {Texture} a texture of the graphics object */ -DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) { +DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) +{ var bounds = this.getLocalBounds(); var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0, renderer, scaleMode, resolution); @@ -322,18 +361,22 @@ * * @private */ -DisplayObjectContainer.prototype.updateTransform = function () { - if (!this.visible) { +DisplayObjectContainer.prototype.updateTransform = function () +{ + if (!this.visible) + { return; } this.displayObjectUpdateTransform(); - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { return; } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } }; @@ -346,8 +389,10 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getBounds = function () { - if (this.children.length === 0) { +DisplayObjectContainer.prototype.getBounds = function () +{ + if (this.children.length === 0) + { return math.Rectangle.EMPTY; } @@ -365,10 +410,12 @@ var childVisible = false; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -386,7 +433,8 @@ maxY = maxY > childMaxY ? maxY : childMaxY; } - if (!childVisible) { + if (!childVisible) + { return math.Rectangle.EMPTY; } @@ -407,12 +455,14 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getLocalBounds = function () { +DisplayObjectContainer.prototype.getLocalBounds = function () +{ var matrixCache = this.worldTransform; this.worldTransform = math.Matrix.IDENTITY; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } @@ -428,13 +478,16 @@ * * @param renderer {WebGLRenderer} The renderer */ -DisplayObjectContainer.prototype.renderWebGL = function (renderer) { +DisplayObjectContainer.prototype.renderWebGL = function (renderer) +{ // if the object is not visible or the alpha is 0 then no need to render this element - if (!this.visible || this.alpha <= 0) { + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } @@ -442,14 +495,17 @@ var i, j; // do a quick check to see if this element has a mask or a filter. - if (this._mask || this._filters) { + if (this._mask || this._filters) + { // push filter first as we need to ensure the stencil buffer is correct for any masking - if (this._filters) { + if (this._filters) + { renderer.spriteBatch.flush(); renderer.filterManager.pushFilter(this._filterBlock); } - if (this._mask) { + if (this._mask) + { renderer.spriteBatch.stop(); renderer.maskManager.pushMask(this.mask, renderer); renderer.spriteBatch.start(); @@ -459,36 +515,42 @@ this._renderWebGL(renderer); // now loop through the children and make sure they get rendered - for (i = 0, j = this.children.length; i < j; i++) { + for (i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderWebGL(renderer); } // time to stop the sprite batch as either a mask element or a filter draw will happen next renderer.spriteBatch.stop(); - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(this._mask, renderer); } - if (this._filters) { + if (this._filters) + { renderer.filterManager.popFilter(); } renderer.spriteBatch.start(); } - else { + else + { this._renderWebGL(renderer); // simple render children! - for (i = 0, j = this.children.length; i < j; ++i) { + for (i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderWebGL(renderer); } } }; -DisplayObjectContainer.prototype._renderWebGL = function (renderer) { +DisplayObjectContainer.prototype._renderWebGL = function (renderer) +{ // this is where content itself gets renderd.. @@ -499,25 +561,31 @@ * * @param renderer {CanvasRenderer} The renderer */ -DisplayObjectContainer.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0) { +DisplayObjectContainer.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -528,13 +596,16 @@ * @param renderer {WebGLRenderer|CanvasRenderer} The renderer * @private */ -DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) { +DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) +{ this._cachedSprite.worldAlpha = this.worldAlpha; - if (renderer.gl) { + if (renderer.gl) + { this._cachedSprite.renderWebGL(renderer); } - else { + else + { this._cachedSprite.renderCanvas(renderer); } }; @@ -544,10 +615,12 @@ * * @private */ -DisplayObjectContainer.prototype._generateCachedSprite = function () { +DisplayObjectContainer.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { // TODO - RenderTexture now *requires* a renderer instance, so this is like broken // because `renderer` isn't actually in scope here :P var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0); @@ -555,7 +628,8 @@ this._cachedSprite = new Sprite(renderTexture); this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.texture.resize(bounds.width | 0, bounds.height | 0); } @@ -580,8 +654,10 @@ * * @private */ -DisplayObjectContainer.prototype._destroyCachedSprite = function () { - if (!this._cachedSprite) { +DisplayObjectContainer.prototype._destroyCachedSprite = function () +{ + if (!this._cachedSprite) + { return; } diff --git a/src/core/display/Sprite.js b/src/core/display/Sprite.js index 707da24..5862aef 100644 --- a/src/core/display/Sprite.js +++ b/src/core/display/Sprite.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param texture {Texture} The texture for this sprite */ -function Sprite(texture) { +function Sprite(texture) +{ DisplayObjectContainer.call(this); /** @@ -85,12 +86,14 @@ this.texture = texture || Texture.EMPTY; } -Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) { +Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) +{ DisplayObjectContainer.prototype.destroy.call(this); this.anchor = null; - if (destroyTexture) { + if (destroyTexture) + { this._texture.destroy(destroyBaseTexture); } @@ -111,10 +114,12 @@ * @memberof Sprite# */ width: { - get: function () { + get: function () + { return this.scale.x * this.texture.frame.width; }, - set: function (value) { + set: function (value) + { this.scale.x = value / this.texture.frame.width; this._width = value; } @@ -127,10 +132,12 @@ * @memberof Sprite# */ height: { - get: function () { + get: function () + { return this.scale.y * this.texture.frame.height; }, - set: function (value) { + set: function (value) + { this.scale.y = value / this.texture.frame.height; this._height = value; } @@ -143,23 +150,29 @@ * @memberof Sprite# */ texture: { - get: function () { + get: function () + { return this._texture; }, - set: function (value) { - if (this._texture === value) { + set: function (value) + { + if (this._texture === value) + { return; } this._texture = value; this.cachedTint = 0xFFFFFF; - if (value) { + if (value) + { // wait for the texture to load - if (value.baseTexture.hasLoaded) { + if (value.baseTexture.hasLoaded) + { this._onTextureUpdate(); } - else { + else + { value.once('update', this._onTextureUpdate.bind(this)); } } @@ -172,18 +185,22 @@ * * @private */ -Sprite.prototype._onTextureUpdate = function () { +Sprite.prototype._onTextureUpdate = function () +{ // so if _width is 0 then width was not set.. - if (this._width) { + if (this._width) + { this.scale.x = this._width / this.texture.frame.width; } - if (this._height) { + if (this._height) + { this.scale.y = this._height / this.texture.frame.height; } }; -Sprite.prototype._renderWebGL = function (renderer) { +Sprite.prototype._renderWebGL = function (renderer) +{ // this is where content gets renderd.. // watch this space for a little render state manager.. @@ -197,7 +214,8 @@ * @param matrix {Matrix} the transformation matrix of the sprite * @return {Rectangle} the framing rectangle */ -Sprite.prototype.getBounds = function (matrix) { +Sprite.prototype.getBounds = function (matrix) +{ var width = this.texture.frame.width; var height = this.texture.frame.height; @@ -224,11 +242,13 @@ if(b === 0 && c === 0) { // scale may be negative! - if (a < 0) { + if (a < 0) + { a *= -1; } - if (d < 0) { + if (d < 0) + { d *= -1; } @@ -293,28 +313,34 @@ * * @param renderer {CanvasRenderer} The renderer */ -Sprite.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) { +Sprite.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) + { return; } - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; renderer.context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } // Ignore null sources - if (this.texture.valid) { + if (this.texture.valid) + { var resolution = this.texture.baseTexture.resolution / renderer.resolution; renderer.context.globalAlpha = this.worldAlpha; // If smoothingEnabled is supported and we need to change the smoothing property for this texture - if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) { + if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) + { renderer.scaleMode = this.texture.baseTexture.scaleMode; renderer.context[renderer.smoothProperty] = (renderer.scaleMode === CONST.scaleModes.LINEAR); } @@ -324,7 +350,8 @@ var dy = (this.texture.trim ? this.texture.trim.y : 0) - (this.anchor.y * this.texture.trim.height); // Allow for pixel rounding - if (renderer.roundPixels) { + if (renderer.roundPixels) + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -337,7 +364,8 @@ dx = dx | 0; dy = dy | 0; } - else { + else + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -348,8 +376,10 @@ ); } - if (this.tint !== 0xFFFFFF) { - if (this.cachedTint !== this.tint) { + if (this.tint !== 0xFFFFFF) + { + if (this.cachedTint !== this.tint) + { this.cachedTint = this.tint; // TODO clean up caching - how to clean up the caches? @@ -368,7 +398,8 @@ this.texture.crop.height / resolution ); } - else { + else + { renderer.context.drawImage( this.texture.baseTexture.source, this.texture.crop.x, @@ -383,11 +414,13 @@ } } - for (var i = 0, j = this.children.length; i < j; i++) { + for (var i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -402,10 +435,12 @@ * @param frameId {String} The frame Id of the texture in the cache * @return {Sprite} A new Sprite using a texture from the texture cache matching the frameId */ -Sprite.fromFrame = function (frameId) { +Sprite.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache' + this); } @@ -420,6 +455,7 @@ * @param imageId {String} The image url of the texture * @return {Sprite} A new Sprite using a texture from the texture cache matching the image id */ -Sprite.fromImage = function (imageId, crossorigin, scaleMode) { +Sprite.fromImage = function (imageId, crossorigin, scaleMode) +{ return new Sprite(Texture.fromImage(imageId, crossorigin, scaleMode)); }; diff --git a/src/core/display/SpriteBatch.js b/src/core/display/SpriteBatch.js index 3187777..c196fef 100644 --- a/src/core/display/SpriteBatch.js +++ b/src/core/display/SpriteBatch.js @@ -12,7 +12,8 @@ * ```js * var container = new SpriteBatch(); * - * for(var i = 0; i < 100; ++i) { + * for(var i = 0; i < 100; ++i) + * { * var sprite = new PIXI.Sprite.fromImage("myImage.png"); * container.addChild(sprite); * } @@ -25,7 +26,8 @@ */ //TODO RENAME to PARTICLE CONTAINER? -function SpriteBatch() { +function SpriteBatch() +{ DisplayObjectContainer.call(this); } @@ -38,7 +40,8 @@ * * @private */ -SpriteBatch.prototype.updateTransform = function () { +SpriteBatch.prototype.updateTransform = function () +{ // TODO don't need to! this.displayObjectUpdateTransform(); // PIXI.DisplayObjectContainer.prototype.updateTransform.call( this ); @@ -50,8 +53,10 @@ * @param renderer {WebGLRenderer} The webgl renderer * @private */ -SpriteBatch.prototype.renderWebGL = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderWebGL = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -71,8 +76,10 @@ * @param renderer {CanvasRenderer} The canvas renderer * @private */ -SpriteBatch.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -84,10 +91,12 @@ this.displayObjectUpdateTransform(); - for (var i = 0; i < this.children.length; ++i) { + for (var i = 0; i < this.children.length; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -95,9 +104,11 @@ context.globalAlpha = this.worldAlpha * child.alpha; - if (child.rotation % (Math.PI * 2) === 0) { + if (child.rotation % (Math.PI * 2) === 0) + { // this is the fastest way to optimise! - if rotation is 0 then we can avoid any kind of setTransform call - if (isRotated) { + if (isRotated) + { context.setTransform( transform.a, transform.b, @@ -122,8 +133,10 @@ frame.height * child.scale.y ); } - else { - if (!isRotated) { + else + { + if (!isRotated) + { isRotated = true; } @@ -131,7 +144,8 @@ var childTransform = child.worldTransform; - if (renderer.roundPixels) { + if (renderer.roundPixels) + { context.setTransform( childTransform.a, childTransform.b, @@ -141,7 +155,8 @@ childTransform.ty | 0 ); } - else { + else + { context.setTransform( childTransform.a, childTransform.b, diff --git a/src/core/index.js b/src/core/index.js index 3954b6f..eb4a82b 100644 --- a/src/core/index.js +++ b/src/core/index.js @@ -58,11 +58,13 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRenderer: function (width, height, options, noWebGL) { + autoDetectRenderer: function (width, height, options, noWebGL) + { width = width || 800; height = height || 600; - if (!noWebGL && require('webgl-enabled')()) { + if (!noWebGL && require('webgl-enabled')()) + { return new core.WebGLRenderer(width, height, options); } @@ -87,7 +89,8 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRecommendedRenderer: function (width, height, options) { + autoDetectRecommendedRenderer: function (width, height, options) + { var isAndroid = /Android/i.test(navigator.userAgent); return core.autoDetectRenderer(width, height, options, isAndroid); diff --git a/src/core/math/Matrix.js b/src/core/math/Matrix.js index c2f87e2..2ff4848 100644 --- a/src/core/math/Matrix.js +++ b/src/core/math/Matrix.js @@ -10,7 +10,8 @@ * @class * @namespace PIXI */ -function Matrix() { +function Matrix() +{ /** * @member {number} * @default 1 @@ -63,7 +64,8 @@ * * @param array {number[]} The array that the matrix will be populated from. */ -Matrix.prototype.fromArray = function (array) { +Matrix.prototype.fromArray = function (array) +{ this.a = array[0]; this.b = array[1]; this.c = array[3]; @@ -78,14 +80,17 @@ * @param transpose {boolean} Whether we need to transpose the matrix or not * @return {number[]} the newly created array which contains the matrix */ -Matrix.prototype.toArray = function (transpose) { - if (!this.array) { +Matrix.prototype.toArray = function (transpose) +{ + if (!this.array) + { this.array = new Float32Array(9); } var array = this.array; - if (transpose) { + if (transpose) + { array[0] = this.a; array[1] = this.b; array[2] = 0; @@ -96,7 +101,8 @@ array[7] = this.ty; array[8] = 1; } - else { + else + { array[0] = this.a; array[1] = this.c; array[2] = this.tx; @@ -119,7 +125,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, transformed through this matrix */ -Matrix.prototype.apply = function (pos, newPos) { +Matrix.prototype.apply = function (pos, newPos) +{ newPos = newPos || new Point(); newPos.x = this.a * pos.x + this.c * pos.y + this.tx; @@ -136,7 +143,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, inverse-transformed through this matrix */ -Matrix.prototype.applyInverse = function (pos, newPos) { +Matrix.prototype.applyInverse = function (pos, newPos) +{ newPos = newPos || new Point(); var id = 1 / (this.a * this.d + this.c * -this.b); @@ -154,7 +162,8 @@ * @param {number} y * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.translate = function (x, y) { +Matrix.prototype.translate = function (x, y) +{ this.tx += x; this.ty += y; @@ -168,7 +177,8 @@ * @param {number} y The amount to scale vertically * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.scale = function (x, y) { +Matrix.prototype.scale = function (x, y) +{ this.a *= x; this.d *= y; this.c *= x; @@ -186,7 +196,8 @@ * @param {number} angle - The angle in radians. * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.rotate = function (angle) { +Matrix.prototype.rotate = function (angle) +{ var cos = Math.cos( angle ); var sin = Math.sin( angle ); @@ -210,7 +221,8 @@ * @param {Matrix} matrix * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.append = function (matrix) { +Matrix.prototype.append = function (matrix) +{ var a1 = this.a; var b1 = this.b; var c1 = this.c; @@ -232,7 +244,8 @@ * * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.identity = function () { +Matrix.prototype.identity = function () +{ this.a = 1; this.b = 0; this.c = 0; diff --git a/src/core/math/Point.js b/src/core/math/Point.js index 7565b2d..632f346 100644 --- a/src/core/math/Point.js +++ b/src/core/math/Point.js @@ -7,7 +7,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -function Point(x, y) { +function Point(x, y) +{ /** * @member {number} * @default 0 @@ -29,7 +30,8 @@ * * @return {Point} a copy of the point */ -Point.prototype.clone = function () { +Point.prototype.clone = function () +{ return new Point(this.x, this.y); }; @@ -40,7 +42,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -Point.prototype.set = function (x, y) { +Point.prototype.set = function (x, y) +{ this.x = x || 0; this.y = y || ( (y !== 0) ? this.x : 0 ) ; }; diff --git a/src/core/math/shapes/Circle.js b/src/core/math/shapes/Circle.js index 69cfdc9..4d76efc 100644 --- a/src/core/math/shapes/Circle.js +++ b/src/core/math/shapes/Circle.js @@ -10,7 +10,8 @@ * @param y {number} The Y coordinate of the center of this circle * @param radius {number} The radius of the circle */ -function Circle(x, y, radius) { +function Circle(x, y, radius) +{ /** * @member {number} * @default 0 @@ -46,7 +47,8 @@ * @method clone * @return {Circle} a copy of the Circle */ -Circle.prototype.clone = function () { +Circle.prototype.clone = function () +{ return new Circle(this.x, this.y, this.radius); }; @@ -58,8 +60,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Circle */ -Circle.prototype.contains = function (x, y) { - if (this.radius <= 0) { +Circle.prototype.contains = function (x, y) +{ + if (this.radius <= 0) + { return false; } @@ -79,6 +83,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Circle.prototype.getBounds = function () { +Circle.prototype.getBounds = function () +{ return new Rectangle(this.x - this.radius, this.y - this.radius, this.radius * 2, this.radius * 2); }; diff --git a/src/core/math/shapes/Ellipse.js b/src/core/math/shapes/Ellipse.js index 4f2d066..fefd01a 100644 --- a/src/core/math/shapes/Ellipse.js +++ b/src/core/math/shapes/Ellipse.js @@ -11,7 +11,8 @@ * @param width {number} The half width of this ellipse * @param height {number} The half height of this ellipse */ -function Ellipse(x, y, width, height) { +function Ellipse(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -53,7 +54,8 @@ * @method clone * @return {Ellipse} a copy of the ellipse */ -Ellipse.prototype.clone = function () { +Ellipse.prototype.clone = function () +{ return new Ellipse(this.x, this.y, this.width, this.height); }; @@ -65,8 +67,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coords are within this ellipse */ -Ellipse.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Ellipse.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } @@ -86,6 +90,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Ellipse.prototype.getBounds = function () { +Ellipse.prototype.getBounds = function () +{ return new Rectangle(this.x - this.width, this.y - this.height, this.width, this.height); }; diff --git a/src/core/math/shapes/Polygon.js b/src/core/math/shapes/Polygon.js index ae89148..fea6d37 100644 --- a/src/core/math/shapes/Polygon.js +++ b/src/core/math/shapes/Polygon.js @@ -10,16 +10,20 @@ * arguments passed can be flat x,y values e.g. `new Polygon(x,y, x,y, x,y, ...)` where `x` and `y` are * Numbers. */ -function Polygon(points) { +function Polygon(points) +{ //if points isn't an array, use arguments as the array - if (!(points instanceof Array)) { + if (!(points instanceof Array)) + { points = Array.prototype.slice.call(arguments); } //if this is a flat array of numbers, convert it to points - if (points[0] instanceof Point) { + if (points[0] instanceof Point) + { var p = []; - for (var i = 0, il = points.length; i < il; i++) { + for (var i = 0, il = points.length; i < il; i++) + { p.push(points[i].x, points[i].y); } @@ -51,7 +55,8 @@ * * @return {Polygon} a copy of the polygon */ -Polygon.prototype.clone = function () { +Polygon.prototype.clone = function () +{ return new Polygon(this.points.slice()); }; @@ -62,19 +67,22 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this polygon */ -Polygon.prototype.contains = function (x, y) { +Polygon.prototype.contains = function (x, y) +{ var inside = false; // use some raycasting to test hits // https://github.com/substack/point-in-polygon/blob/master/index.js var length = this.points.length / 2; - for (var i = 0, j = length - 1; i < length; j = i++) { + for (var i = 0, j = length - 1; i < length; j = i++) + { var xi = this.points[i * 2], yi = this.points[i * 2 + 1], xj = this.points[j * 2], yj = this.points[j * 2 + 1], intersect = ((yi > y) !== (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi); - if (intersect) { + if (intersect) + { inside = !inside; } } diff --git a/src/core/math/shapes/Rectangle.js b/src/core/math/shapes/Rectangle.js index 16ac62a..4008b68 100644 --- a/src/core/math/shapes/Rectangle.js +++ b/src/core/math/shapes/Rectangle.js @@ -10,7 +10,8 @@ * @param width {number} The overall width of this rectangle * @param height {number} The overall height of this rectangle */ -function Rectangle(x, y, width, height) { +function Rectangle(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -60,7 +61,8 @@ * * @return {Rectangle} a copy of the rectangle */ -Rectangle.prototype.clone = function () { +Rectangle.prototype.clone = function () +{ return new Rectangle(this.x, this.y, this.width, this.height); }; @@ -71,13 +73,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rectangle */ -Rectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Rectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/math/shapes/RoundedRectangle.js b/src/core/math/shapes/RoundedRectangle.js index 27d286e..7bf6411 100644 --- a/src/core/math/shapes/RoundedRectangle.js +++ b/src/core/math/shapes/RoundedRectangle.js @@ -11,7 +11,8 @@ * @param height {number} The overall height of this rounded rectangle * @param radius {number} Controls the radius of the rounded corners */ -function RoundedRectangle(x, y, width, height, radius) { +function RoundedRectangle(x, y, width, height, radius) +{ /** * @member {number} * @default 0 @@ -58,7 +59,8 @@ * * @return {RoundedRectangle} a copy of the rounded rectangle */ -RoundedRectangle.prototype.clone = function () { +RoundedRectangle.prototype.clone = function () +{ return new RoundedRectangle(this.x, this.y, this.width, this.height, this.radius); }; @@ -69,13 +71,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rounded Rectangle */ -RoundedRectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +RoundedRectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/primitives/Graphics.js b/src/core/primitives/Graphics.js index 261c534..e902d2a 100644 --- a/src/core/primitives/Graphics.js +++ b/src/core/primitives/Graphics.js @@ -16,7 +16,8 @@ * @extends DisplayObjectContainer * @namespace PIXI */ -function Graphics() { +function Graphics() +{ DisplayObjectContainer.call(this); this.renderable = true; @@ -154,16 +155,20 @@ * @private */ cacheAsBitmap: { - get: function () { + get: function () + { return this._cacheAsBitmap; }, - set: function (value) { + set: function (value) + { this._cacheAsBitmap = value; - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._generateCachedSprite(); } - else { + else + { this.destroyCachedSprite(); this.dirty = true; } @@ -176,7 +181,8 @@ * * @return {Graphics} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ var clone = new Graphics(); clone.renderable = this.renderable; @@ -192,7 +198,8 @@ clone.cachedSpriteDirty = this.cachedSpriteDirty; // copy graphics data - for (var i = 0; i < this.graphicsData.length; ++i) { + for (var i = 0; i < this.graphicsData.length; ++i) + { clone.graphicsData.push(this.graphicsData.clone()); } @@ -211,17 +218,21 @@ * @param alpha {number} alpha of the line to draw, will update the objects stored style * @return {Graphics} */ -Graphics.prototype.lineStyle = function (lineWidth, color, alpha) { +Graphics.prototype.lineStyle = function (lineWidth, color, alpha) +{ this.lineWidth = lineWidth || 0; this.lineColor = color || 0; this.lineAlpha = (arguments.length < 3) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length) + { // halfway through a line? start a new one! this.drawShape( new math.Polygon( this.currentPath.shape.points.slice(-2) )); } - else { + else + { // otherwise its empty so lets just set the line properties this.currentPath.lineWidth = this.lineWidth; this.currentPath.lineColor = this.lineColor; @@ -239,7 +250,8 @@ * @param y {number} the Y coordinate to move to * @return {Graphics} */ -Graphics.prototype.moveTo = function (x, y) { +Graphics.prototype.moveTo = function (x, y) +{ this.drawShape(new math.Polygon([x,y])); return this; @@ -253,7 +265,8 @@ * @param y {number} the Y coordinate to draw to * @return {Graphics} */ -Graphics.prototype.lineTo = function (x, y) { +Graphics.prototype.lineTo = function (x, y) +{ this.currentPath.shape.points.push(x, y); this.dirty = true; @@ -270,13 +283,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -285,7 +302,8 @@ n = 20, points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { this.moveTo(0, 0); } @@ -293,7 +311,8 @@ var fromY = points[points.length-1]; var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; xa = fromX + ( (cpX - fromX) * j ); @@ -319,13 +338,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -342,7 +365,8 @@ var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; dt = (1 - j); @@ -373,13 +397,17 @@ * @param radius {number} The radius of the arc * @return {Graphics} */ -Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points.push(x1, y1); } } - else { + else + { this.moveTo(x1, y1); } @@ -392,12 +420,15 @@ b2 = x2 - x1, mm = Math.abs(a1 * b2 - b1 * a2); - if (mm < 1.0e-8 || radius === 0) { - if (points[points.length-2] !== x1 || points[points.length-1] !== y1) { + if (mm < 1.0e-8 || radius === 0) + { + if (points[points.length-2] !== x1 || points[points.length-1] !== y1) + { points.push(x1, y1); } } - else { + else + { var dd = a1 * a1 + b1 * b1, cc = a2 * a2 + b2 * b2, tt = a1 * a2 + b1 * b2, @@ -433,42 +464,51 @@ * @param anticlockwise {boolean} Optional. Specifies whether the drawing should be counterclockwise or clockwise. False is default, and indicates clockwise, while true indicates counter-clockwise. * @return {Graphics} */ -Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) { +Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) +{ var startX = cx + Math.cos(startAngle) * radius; var startY = cy + Math.sin(startAngle) * radius; var points; // TODO - This if-else makes no sense. It uses currentPath in the else where it doesn't exist... - if (this.currentPath) { + if (this.currentPath) + { points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { points.push(startX, startY); } - else if (points[points.length-2] !== startX || points[points.length-1] !== startY) { + else if (points[points.length-2] !== startX || points[points.length-1] !== startY) + { points.push(startX, startY); } } - else { + else + { this.moveTo(startX, startY); points = this.currentPath.shape.points; } - if (startAngle === endAngle) { + if (startAngle === endAngle) + { return this; } - if (!anticlockwise && endAngle <= startAngle) { + if (!anticlockwise && endAngle <= startAngle) + { endAngle += Math.PI * 2; } - else if (anticlockwise && startAngle <= endAngle) { + else if (anticlockwise && startAngle <= endAngle) + { startAngle += Math.PI * 2; } var sweep = anticlockwise ? (startAngle - endAngle) *-1 : (endAngle - startAngle); var segs = (Math.abs(sweep)/ (Math.PI * 2)) * 40; - if (sweep === 0) { + if (sweep === 0) + { return this; } @@ -482,7 +522,8 @@ var remainder = ( segMinus % 1 ) / segMinus; - for (var i = 0; i <= segMinus; ++i) { + for (var i = 0; i <= segMinus; ++i) + { var real = i + remainder * i; var angle = ((theta) + startAngle + (theta2 * real)); @@ -506,13 +547,16 @@ * @param alpha {number} the alpha of the fill * @return {Graphics} */ -Graphics.prototype.beginFill = function (color, alpha) { +Graphics.prototype.beginFill = function (color, alpha) +{ this.filling = true; this.fillColor = color || 0; this.fillAlpha = (alpha === undefined) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length <= 2) + { this.currentPath.fill = this.filling; this.currentPath.fillColor = this.fillColor; this.currentPath.fillAlpha = this.fillAlpha; @@ -526,7 +570,8 @@ * * @return {Graphics} */ -Graphics.prototype.endFill = function () { +Graphics.prototype.endFill = function () +{ this.filling = false; this.fillColor = null; this.fillAlpha = 1; @@ -542,7 +587,8 @@ * @param height {number} The height of the rectangle * @return {Graphics} */ -Graphics.prototype.drawRect = function ( x, y, width, height ) { +Graphics.prototype.drawRect = function ( x, y, width, height ) +{ this.drawShape(new math.Rectangle(x,y, width, height)); return this; @@ -556,7 +602,8 @@ * @param height {number} The height of the rectangle * @param radius {number} Radius of the rectangle corners */ -Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) { +Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) +{ this.drawShape(new math.RoundedRectangle(x, y, width, height, radius)); return this; @@ -570,7 +617,8 @@ * @param radius {number} The radius of the circle * @return {Graphics} */ -Graphics.prototype.drawCircle = function (x, y, radius) { +Graphics.prototype.drawCircle = function (x, y, radius) +{ this.drawShape(new math.Circle(x,y, radius)); return this; @@ -585,7 +633,8 @@ * @param height {number} The half height of the ellipse * @return {Graphics} */ -Graphics.prototype.drawEllipse = function (x, y, width, height) { +Graphics.prototype.drawEllipse = function (x, y, width, height) +{ this.drawShape(new math.Ellipse(x, y, width, height)); return this; @@ -597,8 +646,10 @@ * @param path {Array} The path data used to construct the polygon. * @return {Graphics} */ -Graphics.prototype.drawPolygon = function (path) { - if (!(path instanceof Array)) { +Graphics.prototype.drawPolygon = function (path) +{ + if (!(path instanceof Array)) + { path = Array.prototype.slice.call(arguments); } @@ -612,7 +663,8 @@ * * @return {Graphics} */ -Graphics.prototype.clear = function () { +Graphics.prototype.clear = function () +{ this.lineWidth = 0; this.filling = false; @@ -631,7 +683,8 @@ * @param scaleMode {number} Should be one of the scaleMode consts * @return {Texture} a texture of the graphics object */ -Graphics.prototype.generateTexture = function (resolution, scaleMode) { +Graphics.prototype.generateTexture = function (resolution, scaleMode) +{ resolution = resolution || 1; var bounds = this.getBounds(); @@ -655,17 +708,21 @@ * * @param renderer {WebGLRenderer} */ -Graphics.prototype._renderWebGL = function (renderer) { +Graphics.prototype._renderWebGL = function (renderer) +{ // if the sprite is not visible or the alpha is 0 then no need to render this element - if (this.isMask === true) { + if (this.isMask === true) + { return; } // this code may still be needed so leaving for now.. - // + // /* - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture on the gpu too! @@ -681,17 +738,24 @@ return; } - */ - - // check if the webgl graphic needs to be updated - if (this.glDirty) { - this.dirty = true; - this.glDirty = false; - } + else */ - renderer.setObjectRendererer(renderer.graphicsRenderer); - renderer.graphicsRenderer.render(this); + renderer.spriteBatch.stop(); + renderer.blendModeManager.setBlendMode(this.blendMode); + // check blend mode + renderer.blendModeManager.setBlendMode( this.blendMode ); + + // check if the webgl graphic needs to be updated + if (this.glDirty) + { + this.dirty = true; + this.glDirty = false; + } + + WebGLGraphics.renderGraphics(this, renderer); + + renderer.spriteBatch.start(); }; /** @@ -700,14 +764,18 @@ * @param renderer {CanvasRenderer} * @private */ -Graphics.prototype.renderCanvas = function (renderer) { +Graphics.prototype.renderCanvas = function (renderer) +{ // 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.isMask === true) { + if (!this.visible || this.alpha <= 0 || this.isMask === true) + { return; } - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture @@ -723,16 +791,19 @@ return; } - else { + else + { var context = renderer.context; var transform = this.worldTransform; - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } @@ -748,11 +819,13 @@ CanvasGraphics.renderGraphics(this, context); - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } } @@ -763,13 +836,16 @@ * * @return {Rectangle} the rectangular bounding area */ -Graphics.prototype.getBounds = function (matrix) { +Graphics.prototype.getBounds = function (matrix) +{ // return an empty object if the item is a mask! - if (this.isMask) { + if (this.isMask) + { return math.Rectangle.EMPTY; } - if (this.dirty) { + if (this.dirty) + { this.updateLocalBounds(); this.glDirty = true; @@ -841,23 +917,27 @@ * Update the bounds of the object * */ -Graphics.prototype.updateLocalBounds = function () { +Graphics.prototype.updateLocalBounds = function () +{ var minX = Infinity; var maxX = -Infinity; var minY = Infinity; var maxY = -Infinity; - if (this.graphicsData.length) { + if (this.graphicsData.length) + { var shape, points, x, y, w, h; - for (var i = 0; i < this.graphicsData.length; i++) { + for (var i = 0; i < this.graphicsData.length; i++) + { var data = this.graphicsData[i]; var type = data.type; var lineWidth = data.lineWidth; shape = data.shape; - if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) { + if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) + { x = shape.x - lineWidth/2; y = shape.y - lineWidth/2; w = shape.width + lineWidth; @@ -869,7 +949,8 @@ minY = y < minY ? y : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.CIRC) { + else if (type === CONST.SHAPES.CIRC) + { x = shape.x; y = shape.y; w = shape.radius + lineWidth/2; @@ -881,7 +962,8 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.ELIP) { + else if (type === CONST.SHAPES.ELIP) + { x = shape.x; y = shape.y; w = shape.width + lineWidth/2; @@ -893,11 +975,13 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else { + else + { // POLY points = shape.points; - for (var j = 0; j < points.length; j += 2) { + for (var j = 0; j < points.length; j += 2) + { x = points[j]; y = points[j+1]; @@ -910,7 +994,8 @@ } } } - else { + else + { minX = 0; maxX = 0; minY = 0; @@ -931,10 +1016,12 @@ * * @private */ -Graphics.prototype._generateCachedSprite = function () { +Graphics.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { var canvasBuffer = new CanvasBuffer(bounds.width, bounds.height); var texture = Texture.fromCanvas(canvasBuffer.canvas); @@ -943,7 +1030,8 @@ this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.buffer.resize(bounds.width, bounds.height); } @@ -968,7 +1056,8 @@ * * @private */ -Graphics.prototype.updateCachedSpriteTexture = function () { +Graphics.prototype.updateCachedSpriteTexture = function () +{ var cachedSprite = this._cachedSprite; var texture = cachedSprite.texture; var canvas = cachedSprite.buffer.canvas; @@ -989,7 +1078,8 @@ * Destroys a previous cached sprite. * */ -Graphics.prototype.destroyCachedSprite = function () { +Graphics.prototype.destroyCachedSprite = function () +{ this._cachedSprite.texture.destroy(true); // let the gc collect the unused sprite @@ -1003,10 +1093,13 @@ * @param {Circle|Rectangle|Ellipse|Line|Polygon} shape The Shape object to draw. * @return {GraphicsData} The generated GraphicsData object. */ -Graphics.prototype.drawShape = function (shape) { - if (this.currentPath) { +Graphics.prototype.drawShape = function (shape) +{ + if (this.currentPath) + { // check current path! - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath.shape.points.length <= 2) + { this.graphicsData.pop(); } } @@ -1017,7 +1110,8 @@ this.graphicsData.push(data); - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { data.shape.closed = this.filling; this.currentPath = data; } diff --git a/src/core/primitives/GraphicsData.js b/src/core/primitives/GraphicsData.js index 99decbe..788f6f2 100644 --- a/src/core/primitives/GraphicsData.js +++ b/src/core/primitives/GraphicsData.js @@ -4,7 +4,8 @@ * @class * @namespace PIXI */ -function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) { +function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) +{ this.lineWidth = lineWidth; this.lineColor = lineColor; this.lineAlpha = lineAlpha; @@ -27,7 +28,8 @@ * * @return {GraphicsData} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ return new GraphicsData( this.lineWidth, this.lineColor, diff --git a/src/core/renderers/canvas/CanvasRenderer.js b/src/core/renderers/canvas/CanvasRenderer.js index 15a0978..7aebd44 100644 --- a/src/core/renderers/canvas/CanvasRenderer.js +++ b/src/core/renderers/canvas/CanvasRenderer.js @@ -17,17 +17,22 @@ * @param [options.resolution=1] {number} the resolution of the renderer retina would be 2 * @param [options.clearBeforeRender=true] {boolean} This sets if the CanvasRenderer will clear the canvas or not before the new render pass. */ -function CanvasRenderer(width, height, options) { +function CanvasRenderer(width, height, options) +{ utils.sayHello('Canvas'); - if (options) { - for (var i in CONST.defaultRenderOptions) { - if (typeof options[i] === 'undefined') { + if (options) + { + for (var i in CONST.defaultRenderOptions) + { + if (typeof options[i] === 'undefined') + { options[i] = CONST.defaultRenderOptions[i]; } } } - else { + else + { options = CONST.defaultRenderOptions; } @@ -156,19 +161,24 @@ this.smoothProperty = null; - if (this.context.imageSmoothingEnabled) { + if (this.context.imageSmoothingEnabled) + { this.smoothProperty = 'imageSmoothingEnabled'; } - else if (this.context.webkitImageSmoothingEnabled) { + else if (this.context.webkitImageSmoothingEnabled) + { this.smoothProperty = 'webkitImageSmoothingEnabled'; } - else if (this.context.mozImageSmoothingEnabled) { + else if (this.context.mozImageSmoothingEnabled) + { this.smoothProperty = 'mozImageSmoothingEnabled'; } - else if (this.context.oImageSmoothingEnabled) { + else if (this.context.oImageSmoothingEnabled) + { this.smoothProperty = 'oImageSmoothingEnabled'; } - else if (this.context.msImageSmoothingEnabled) { + else if (this.context.msImageSmoothingEnabled) + { this.smoothProperty = 'msImageSmoothingEnabled'; } @@ -193,10 +203,12 @@ * @memberof CanvasRenderer# */ backgroundColor: { - get: function () { + get: function () + { return this._backgroundColor; }, - set: function (val) { + set: function (val) + { this._backgroundColor = val; this._backgroundColorString = utils.hex2string(val); } @@ -208,7 +220,8 @@ * * @param object {DisplayObject} the object to be rendered */ -CanvasRenderer.prototype.render = function (object) { +CanvasRenderer.prototype.render = function (object) +{ object.updateTransform(); this.context.setTransform(1,0,0,1,0,0); @@ -218,16 +231,20 @@ this.currentBlendMode = CONST.blendModes.NORMAL; this.context.globalCompositeOperation = this.blendModes[CONST.blendModes.NORMAL]; - if (navigator.isCocoonJS && this.view.screencanvas) { + if (navigator.isCocoonJS && this.view.screencanvas) + { this.context.fillStyle = 'black'; this.context.clear(); } - if (this.clearBeforeRender) { - if (this.transparent) { + if (this.clearBeforeRender) + { + if (this.transparent) + { this.context.clearRect(0, 0, this.width, this.height); } - else { + else + { this.context.fillStyle = this._backgroundColorString; this.context.fillRect(0, 0, this.width , this.height); } @@ -241,8 +258,10 @@ * * @param [removeView=false] {boolean} Removes the Canvas element from the DOM. */ -CanvasRenderer.prototype.destroy = function (removeView) { - if (removeView && this.view.parent) { +CanvasRenderer.prototype.destroy = function (removeView) +{ + if (removeView && this.view.parent) + { this.view.parent.removeChild(this.view); } @@ -257,14 +276,16 @@ * @param width {number} the new width of the canvas view * @param height {number} the new height of the canvas view */ -CanvasRenderer.prototype.resize = function (width, height) { +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) { + if (this.autoResize) + { this.view.style.width = this.width / this.resolution + 'px'; this.view.style.height = this.height / this.resolution + 'px'; } @@ -276,7 +297,8 @@ * @param displayObject {DisplayObject} The displayObject to render * @private */ -CanvasRenderer.prototype.renderDisplayObject = function (displayObject) { +CanvasRenderer.prototype.renderDisplayObject = function (displayObject) +{ displayObject.renderCanvas(this); }; @@ -285,11 +307,14 @@ * * @private */ -CanvasRenderer.prototype._mapBlendModes = function () { - if (!this.blendModes) { +CanvasRenderer.prototype._mapBlendModes = function () +{ + if (!this.blendModes) + { this.blendModes = {}; - if (utils.canUseNewCanvasBlendModes()) { + if (utils.canUseNewCanvasBlendModes()) + { this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? this.blendModes[CONST.blendModes.MULTIPLY] = 'multiply'; @@ -308,7 +333,8 @@ this.blendModes[CONST.blendModes.COLOR] = 'color'; this.blendModes[CONST.blendModes.LUMINOSITY] = 'luminosity'; } - else { + else + { // this means that the browser does not support the cool new blend modes in canvas 'cough' ie 'cough' this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? diff --git a/src/core/renderers/canvas/utils/CanvasBuffer.js b/src/core/renderers/canvas/utils/CanvasBuffer.js index ebe5d47..b183a66 100644 --- a/src/core/renderers/canvas/utils/CanvasBuffer.js +++ b/src/core/renderers/canvas/utils/CanvasBuffer.js @@ -6,7 +6,8 @@ * @param width {number} the width for the newly created canvas * @param height {number} the height for the newly created canvas */ -function CanvasBuffer(width, height) { +function CanvasBuffer(width, height) +{ /** * The Canvas object that belongs to this CanvasBuffer. * @@ -36,10 +37,12 @@ * @memberof CanvasBuffer# */ width: { - get: function () { + get: function () + { return this.canvas.width; }, - set: function (val) { + set: function (val) + { this.canvas.width = val; } }, @@ -50,10 +53,12 @@ * @memberof CanvasBuffer# */ height: { - get: function () { + get: function () + { return this.canvas.height; }, - set: function (val) { + set: function (val) + { this.canvas.height = val; } } @@ -64,7 +69,8 @@ * * @private */ -CanvasBuffer.prototype.clear = function () { +CanvasBuffer.prototype.clear = function () +{ this.context.setTransform(1, 0, 0, 1, 0, 0); this.context.clearRect(0,0, this.canvas.width, this.canvas.height); }; @@ -75,7 +81,8 @@ * @param width {number} the new width of the canvas * @param height {number} the new height of the canvas */ -CanvasBuffer.prototype.resize = function (width, height) { +CanvasBuffer.prototype.resize = function (width, height) +{ this.canvas.width = width; this.canvas.height = height; }; diff --git a/src/core/renderers/canvas/utils/CanvasGraphics.js b/src/core/renderers/canvas/utils/CanvasGraphics.js index c7eaa2a..3f2a91f 100644 --- a/src/core/renderers/canvas/utils/CanvasGraphics.js +++ b/src/core/renderers/canvas/utils/CanvasGraphics.js @@ -13,15 +13,18 @@ * @param graphics {Graphics} the actual graphics object to render * @param context {CanvasRenderingContext2D} the 2d drawing method of the canvas */ -CanvasGraphics.renderGraphics = function (graphics, context) { +CanvasGraphics.renderGraphics = function (graphics, context) +{ var worldAlpha = graphics.worldAlpha; - if (graphics.dirty) { + if (graphics.dirty) + { this.updateGraphicsTint(graphics); graphics.dirty = false; } - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; @@ -30,69 +33,82 @@ context.lineWidth = data.lineWidth; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { context.beginPath(); var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } - if (shape.closed) { + if (shape.closed) + { context.lineTo(points[0], points[1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fillRect(shape.x, shape.y, shape.width, shape.height); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.strokeRect(shape.x, shape.y, shape.width, shape.height); } } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.beginPath(); context.arc(shape.x, shape.y, shape.radius,0,2*Math.PI); context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas var w = shape.width * 2; @@ -119,18 +135,21 @@ context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; var width = shape.width; @@ -152,13 +171,15 @@ context.quadraticCurveTo(rx, ry, rx, ry + radius); context.closePath(); - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); @@ -174,45 +195,54 @@ * @param graphics {Graphics} the graphics which will be used as a mask * @param context {CanvasRenderingContext2D} the context 2d method of the canvas */ -CanvasGraphics.renderGraphicsMask = function (graphics, context) { +CanvasGraphics.renderGraphicsMask = function (graphics, context) +{ var len = graphics.graphicsData.length; - if (len === 0) { + if (len === 0) + { return; } context.beginPath(); - for (var i = 0; i < len; i++) { + for (var i = 0; i < len; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { context.rect(shape.x, shape.y, shape.width, shape.height); context.closePath(); } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.arc(shape.x, shape.y, shape.radius, 0, 2 * Math.PI); context.closePath(); } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas @@ -237,7 +267,8 @@ context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); context.closePath(); } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; @@ -262,8 +293,10 @@ } }; -CanvasGraphics.updateGraphicsTint = function (graphics) { - if (graphics.tint === 0xFFFFFF) { +CanvasGraphics.updateGraphicsTint = function (graphics) +{ + if (graphics.tint === 0xFFFFFF) + { return; } @@ -271,7 +304,8 @@ var tintG = (graphics.tint >> 8 & 0xFF) / 255; var tintB = (graphics.tint & 0xFF)/ 255; - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var fillColor = data.fillColor | 0; diff --git a/src/core/renderers/canvas/utils/CanvasMaskManager.js b/src/core/renderers/canvas/utils/CanvasMaskManager.js index e04a733..9827d36 100644 --- a/src/core/renderers/canvas/utils/CanvasMaskManager.js +++ b/src/core/renderers/canvas/utils/CanvasMaskManager.js @@ -6,7 +6,8 @@ * @class * @namespace PIXI */ -function CanvasMaskManager() {} +function CanvasMaskManager() +{} CanvasMaskManager.prototype.constructor = CanvasMaskManager; module.exports = CanvasMaskManager; @@ -17,7 +18,8 @@ * @param maskData {object} the maskData that will be pushed * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.pushMask = function (maskData, renderer) { +CanvasMaskManager.prototype.pushMask = function (maskData, renderer) +{ renderer.context.save(); var cacheAlpha = maskData.alpha; @@ -45,6 +47,7 @@ * * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.popMask = function (renderer) { +CanvasMaskManager.prototype.popMask = function (renderer) +{ renderer.context.restore(); }; diff --git a/src/core/renderers/canvas/utils/CanvasTinter.js b/src/core/renderers/canvas/utils/CanvasTinter.js index 17e0529..d2fb1bc 100644 --- a/src/core/renderers/canvas/utils/CanvasTinter.js +++ b/src/core/renderers/canvas/utils/CanvasTinter.js @@ -14,7 +14,8 @@ * @param color {number} the color to use to tint the sprite with * @return {HTMLCanvasElement} The tinted canvas */ -CanvasTinter.getTintedTexture = function (sprite, color) { +CanvasTinter.getTintedTexture = function (sprite, color) +{ var texture = sprite.texture; color = CanvasTinter.roundColor(color); @@ -23,7 +24,8 @@ texture.tintCache = texture.tintCache || {}; - if (texture.tintCache[stringColor]) { + if (texture.tintCache[stringColor]) + { return texture.tintCache[stringColor]; } @@ -33,14 +35,16 @@ //CanvasTinter.tintWithPerPixel(texture, stringColor, canvas); CanvasTinter.tintMethod(texture, color, canvas); - if (CanvasTinter.convertTintToImage) { + if (CanvasTinter.convertTintToImage) + { // is this better? var tintImage = new Image(); tintImage.src = canvas.toDataURL(); texture.tintCache[stringColor] = tintImage; } - else { + else + { texture.tintCache[stringColor] = canvas; // if we are not converting the texture to an image then we need to lose the reference to the canvas CanvasTinter.canvas = null; @@ -56,7 +60,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithMultiply = function (texture, color, canvas) { +CanvasTinter.tintWithMultiply = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -104,7 +109,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithOverlay = function (texture, color, canvas) { +CanvasTinter.tintWithOverlay = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -139,7 +145,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithPerPixel = function (texture, color, canvas) { +CanvasTinter.tintWithPerPixel = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -167,7 +174,8 @@ var pixels = pixelData.data; - for (var i = 0; i < pixels.length; i += 4) { + for (var i = 0; i < pixels.length; i += 4) + { pixels[i+0] *= r; pixels[i+1] *= g; pixels[i+2] *= b; @@ -181,7 +189,8 @@ * * @param color {number} the color to round, should be a hex color */ -CanvasTinter.roundColor = function (color) { +CanvasTinter.roundColor = function (color) +{ var step = CanvasTinter.cacheStepsPerColorChannel; var rgbValues = utils.hex2rgb(color); diff --git a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js index 9f2f89a..35edbaf 100644 --- a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js +++ b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLBlendModeManager(renderer) { +function WebGLBlendModeManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -23,8 +24,10 @@ * * @param blendMode {number} the blendMode, should be a Pixi const, such as BlendModes.ADD */ -WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) { - if (this.currentBlendMode === blendMode) { +WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) +{ + if (this.currentBlendMode === blendMode) + { return false; } diff --git a/src/core/renderers/webgl/managers/WebGLFilterManager.js b/src/core/renderers/webgl/managers/WebGLFilterManager.js index 1179258..2dac048 100644 --- a/src/core/renderers/webgl/managers/WebGLFilterManager.js +++ b/src/core/renderers/webgl/managers/WebGLFilterManager.js @@ -7,7 +7,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLFilterManager(renderer) { +function WebGLFilterManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -32,7 +33,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.texturePool.length = 0; self.initShaderBuffers(); }); @@ -46,7 +48,8 @@ * @param renderer {WebGLRenderer} * @param buffer {ArrayBuffer} */ -WebGLFilterManager.prototype.begin = function (buffer) { +WebGLFilterManager.prototype.begin = function (buffer) +{ this.defaultShader = this.renderer.shaderManager.defaultShader; this.width = this.renderer.projection.x * 2; @@ -60,7 +63,8 @@ * * @param filterBlock {object} the filter that will be pushed to the current filter stack */ -WebGLFilterManager.prototype.pushFilter = function (filterBlock) { +WebGLFilterManager.prototype.pushFilter = function (filterBlock) +{ var gl = this.renderer.gl; var projection = this.renderer.projection; @@ -78,10 +82,12 @@ this.offsetY += filterBlock._filterArea.y; var texture = this.texturePool.pop(); - if (!texture) { + if (!texture) + { texture = new FilterTexture(this.renderer.gl, this.width, this.height); } - else { + else + { texture.resize(this.width, this.height); } @@ -98,29 +104,35 @@ var localX = filterArea.x, localY = filterArea.y; - if (filterArea.x < 0) { + if (filterArea.x < 0) + { filterArea.width += filterArea.x; filterArea.x = 0; } - if (filterArea.y < 0) { + if (filterArea.y < 0) + { filterArea.height += filterArea.y; filterArea.y = 0; } - if (localX + filterArea.width > this.width) { + if (localX + filterArea.width > this.width) + { filterArea.width = this.width - localX; } - if (localY + filterArea.height > this.height) { + if (localY + filterArea.height > this.height) + { filterArea.height = this.height - localY; } - if (filterArea.width < 0) { + if (filterArea.width < 0) + { filterArea.width = 0; } - if (filterArea.height < 0) { + if (filterArea.height < 0) + { filterArea.height = 0; } @@ -154,7 +166,8 @@ * Removes the last filter from the filter stack and doesn't return it. * */ -WebGLFilterManager.prototype.popFilter = function () { +WebGLFilterManager.prototype.popFilter = function () +{ var gl = this.renderer.gl; var filterBlock = this.filterStack.pop(); @@ -163,7 +176,8 @@ var projection = this.renderer.projection; var offset = this.renderer.offset; - if (filterBlock.filterPasses.length > 1) { + if (filterBlock.filterPasses.length > 1) + { gl.viewport(0, 0, filterArea.width, filterArea.height); gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); @@ -193,7 +207,8 @@ var inputTexture = texture; var outputTexture = this.texturePool.pop(); - if (!outputTexture) { + if (!outputTexture) + { outputTexture = new FilterTexture(this.renderer.gl, this.width, this.height); } outputTexture.resize(this.width, this.height); @@ -204,7 +219,8 @@ gl.disable(gl.BLEND); - for (var i = 0; i < filterBlock.filterPasses.length-1; i++) { + for (var i = 0; i < filterBlock.filterPasses.length-1; i++) + { var filterPass = filterBlock.filterPasses[i]; gl.bindFramebuffer(gl.FRAMEBUFFER, outputTexture.frameBuffer ); @@ -243,10 +259,12 @@ var buffer = this.buffer; // time to render the filters texture to the previous scene - if (this.filterStack.length === 0) { + if (this.filterStack.length === 0) + { gl.colorMask(true, true, true, true);//this.transparent); } - else { + else + { var currentFilter = this.filterStack[this.filterStack.length-1]; filterArea = currentFilter._filterArea; @@ -332,13 +350,15 @@ * @param width {number} the horizontal range of the filter * @param height {number} the vertical range of the filter */ -WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) { +WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) +{ // use program var gl = this.renderer.gl; var shader = filter.shaders[gl.id]; - if (!shader) { + if (!shader) + { shader = new Shader(gl); shader.fragmentSrc = filter.fragmentSrc; @@ -356,7 +376,8 @@ gl.uniform2f(shader.projectionVector, width/2, -height/2); gl.uniform2f(shader.offsetVector, 0,0); - if (filter.uniforms.dimensions) { + 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]; @@ -386,7 +407,8 @@ * Initialises the shader buffers. * */ -WebGLFilterManager.prototype.initShaderBuffers = function () { +WebGLFilterManager.prototype.initShaderBuffers = function () +{ var gl = this.renderer.gl; // create some buffers @@ -432,7 +454,8 @@ * Destroys the filter and removes it from the filter stack. * */ -WebGLFilterManager.prototype.destroy = function () { +WebGLFilterManager.prototype.destroy = function () +{ var gl = this.renderer.gl; this.filterStack = null; @@ -441,7 +464,8 @@ this.offsetY = 0; // destroy textures - for (var i = 0; i < this.texturePool.length; i++) { + for (var i = 0; i < this.texturePool.length; i++) + { this.texturePool[i].destroy(); } diff --git a/src/core/renderers/webgl/managers/WebGLManager.js b/src/core/renderers/webgl/managers/WebGLManager.js index 9d47b5c..c30cd51 100644 --- a/src/core/renderers/webgl/managers/WebGLManager.js +++ b/src/core/renderers/webgl/managers/WebGLManager.js @@ -3,7 +3,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLManager(renderer) { +function WebGLManager(renderer) +{ /** * The renderer this manager works for. * @@ -15,6 +16,7 @@ WebGLManager.prototype.constructor = WebGLManager; module.exports = WebGLManager; -WebGLManager.prototype.destroy = function () { +WebGLManager.prototype.destroy = function () +{ this.renderer = null; }; diff --git a/src/core/renderers/webgl/managers/WebGLMaskManager.js b/src/core/renderers/webgl/managers/WebGLMaskManager.js index 2f90b64..e568812 100644 --- a/src/core/renderers/webgl/managers/WebGLMaskManager.js +++ b/src/core/renderers/webgl/managers/WebGLMaskManager.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLMaskManager(renderer) { +function WebGLMaskManager(renderer) +{ WebGLManager.call(this, renderer); } @@ -19,12 +20,15 @@ * * @param maskData {any[]} */ -WebGLMaskManager.prototype.pushMask = function (maskData) { - if (maskData.dirty) { +WebGLMaskManager.prototype.pushMask = function (maskData) +{ + if (maskData.dirty) + { WebGLGraphics.updateGraphics(maskData, this.renderer.gl); } - if (!maskData._webGL[this.renderer.gl.id].data.length) { + if (!maskData._webGL[this.renderer.gl.id].data.length) + { return; } @@ -36,6 +40,7 @@ * * @param maskData {any[]} */ -WebGLMaskManager.prototype.popMask = function (maskData) { +WebGLMaskManager.prototype.popMask = function (maskData) +{ this.renderer.stencilManager.popStencil(maskData, maskData._webGL[this.renderer.gl.id].data[0], this.renderer); }; diff --git a/src/core/renderers/webgl/managers/WebGLShaderManager.js b/src/core/renderers/webgl/managers/WebGLShaderManager.js index fef071c..90c6477 100644 --- a/src/core/renderers/webgl/managers/WebGLShaderManager.js +++ b/src/core/renderers/webgl/managers/WebGLShaderManager.js @@ -10,7 +10,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLShaderManager(renderer) { +function WebGLShaderManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -28,7 +29,8 @@ */ this.tempAttribState = []; - for (var i = 0; i < this.maxAttibs; i++) { + for (var i = 0; i < this.maxAttibs; i++) + { this.attribState[i] = false; } @@ -66,7 +68,8 @@ // listen for context and update necessary shaders var self = this; - this.renderer.on('context', function (event) { + this.renderer.on('context', function (event) + { var gl = event.data; // this shader is used for rendering primitives @@ -97,29 +100,36 @@ * * @param attribs {Array} attribs */ -WebGLShaderManager.prototype.setAttribs = function (attribs) { +WebGLShaderManager.prototype.setAttribs = function (attribs) +{ // reset temp state var i; - for (i = 0; i < this.tempAttribState.length; i++) { + for (i = 0; i < this.tempAttribState.length; i++) + { this.tempAttribState[i] = false; } // set the new attribs - for (var a in attribs) { + for (var a in attribs) + { this.tempAttribState[attribs[a]] = true; } var gl = this.renderer.gl; - for (i = 0; i < this.attribState.length; i++) { - if (this.attribState[i] !== this.tempAttribState[i]) { + for (i = 0; i < this.attribState.length; i++) + { + if (this.attribState[i] !== this.tempAttribState[i]) + { this.attribState[i] = this.tempAttribState[i]; - if (this.attribState[i]) { + if (this.attribState[i]) + { gl.enableVertexAttribArray(i); } - else { + else + { gl.disableVertexAttribArray(i); } } @@ -131,8 +141,10 @@ * * @param shader {Any} */ -WebGLShaderManager.prototype.setShader = function (shader) { - if (this._currentId === shader.uuid) { +WebGLShaderManager.prototype.setShader = function (shader) +{ + if (this._currentId === shader.uuid) + { return false; } @@ -150,7 +162,8 @@ * Destroys this object. * */ -WebGLShaderManager.prototype.destroy = function () { +WebGLShaderManager.prototype.destroy = function () +{ this.attribState = null; this.tempAttribState = null; diff --git a/src/core/renderers/webgl/managers/WebGLStencilManager.js b/src/core/renderers/webgl/managers/WebGLStencilManager.js index 9ec6398..4cb0134 100644 --- a/src/core/renderers/webgl/managers/WebGLStencilManager.js +++ b/src/core/renderers/webgl/managers/WebGLStencilManager.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLStencilManager(renderer) { +function WebGLStencilManager(renderer) +{ WebGLManager.call(this, renderer); this.stencilStack = []; @@ -24,12 +25,14 @@ * @param graphics {Graphics} * @param webGLData {any[]} */ -WebGLStencilManager.prototype.pushStencil = function (graphics, webGLData) { +WebGLStencilManager.prototype.pushStencil = function (graphics, webGLData) +{ var gl = this.renderer.gl; this.bindGraphics(graphics, webGLData, this.renderer); - if (this.stencilStack.length === 0) { + if (this.stencilStack.length === 0) + { gl.enable(gl.STENCIL_TEST); gl.clear(gl.STENCIL_BUFFER_BIT); this.reverse = true; @@ -47,14 +50,17 @@ // draw the triangle strip! - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } @@ -62,31 +68,38 @@ // draw a quad to increment.. gl.drawElements(gl.TRIANGLE_FAN, 4, gl.UNSIGNED_SHORT, ( webGLData.indices.length - 4 ) * 2 ); - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); } this.reverse = !this.reverse; } - else { - if (!this.reverse) { + else + { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } - else { + 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) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); } } @@ -103,7 +116,8 @@ * @param graphics {Graphics} * @param webGLData {Array} */ -WebGLStencilManager.prototype.bindGraphics = function (graphics, webGLData) { +WebGLStencilManager.prototype.bindGraphics = function (graphics, webGLData) +{ //if (this._currentGraphics === graphics)return; this._currentGraphics = graphics; @@ -114,7 +128,8 @@ offset = this.renderer.offset, shader;// = this.renderer.shaderManager.primitiveShader; - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { shader = this.renderer.shaderManager.complexPrimitiveShader; this.renderer.shaderManager.setShader(shader); @@ -141,7 +156,8 @@ // set the index buffer! gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, webGLData.indexBuffer); } - else { + else + { //this.renderer.shaderManager.activatePrimitiveShader(); shader = this.renderer.shaderManager.primitiveShader; this.renderer.shaderManager.setShader( shader ); @@ -154,7 +170,7 @@ gl.uniform2f(shader.uniforms.offsetVector._location, -offset.x, -offset.y); gl.uniform3fv(shader.uniforms.tint._location, utils.hex2rgb(graphics.tint)); - + gl.uniform1f(shader.uniforms.alpha._location, graphics.worldAlpha); @@ -172,19 +188,22 @@ * @param graphics {Graphics} * @param webGLData {Array} */ -WebGLStencilManager.prototype.popStencil = function (graphics, webGLData) { +WebGLStencilManager.prototype.popStencil = function (graphics, webGLData) +{ var gl = this.renderer.gl; this.stencilStack.pop(); this.count--; - if (this.stencilStack.length === 0) { + if (this.stencilStack.length === 0) + { // the stack is empty! gl.disable(gl.STENCIL_TEST); } - else { + else + { var level = this.count; @@ -192,14 +211,17 @@ gl.colorMask(false, false, false, false); - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { this.reverse = !this.reverse; - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } @@ -213,31 +235,38 @@ // draw the triangle strip! gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); - if (!this.reverse) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); } } - else { + else + { // console.log("<<>>") - if (!this.reverse) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } - else { + 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) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); } } @@ -253,7 +282,8 @@ * Destroys the mask stack. * */ -WebGLStencilManager.prototype.destroy = function () { +WebGLStencilManager.prototype.destroy = function () +{ this.renderer = null; this.stencilStack = null; }; diff --git a/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js b/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js index 913ba5e..1ea7d19 100644 --- a/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js +++ b/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function ComplexPrimitiveShader(gl) { +function ComplexPrimitiveShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -24,7 +25,8 @@ 'uniform float flipY;', 'varying vec4 vColor;', - 'void main(void) {', + '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);', @@ -37,7 +39,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = vColor;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/FastShader.js b/src/core/renderers/webgl/shaders/FastShader.js index bd2e29a..2e5e060 100644 --- a/src/core/renderers/webgl/shaders/FastShader.js +++ b/src/core/renderers/webgl/shaders/FastShader.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function FastShader(gl) { +function FastShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -28,7 +29,8 @@ 'const vec2 center = vec2(-1.0, 1.0);', - 'void main(void) {', + 'void main(void) + {', ' vec2 v;', ' vec2 sv = aVertexPosition * aScale;', ' v.x = (sv.x) * cos(aRotation) - (sv.y) * sin(aRotation);', @@ -49,7 +51,8 @@ 'uniform sampler2D uSampler;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/PrimitiveShader.js b/src/core/renderers/webgl/shaders/PrimitiveShader.js index 6f25409..a25f54f 100644 --- a/src/core/renderers/webgl/shaders/PrimitiveShader.js +++ b/src/core/renderers/webgl/shaders/PrimitiveShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function PrimitiveShader(gl) { +function PrimitiveShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -23,7 +24,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + '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);', @@ -36,7 +38,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = vColor;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/Shader.js b/src/core/renderers/webgl/shaders/Shader.js index f8964f5..fd75ef5 100644 --- a/src/core/renderers/webgl/shaders/Shader.js +++ b/src/core/renderers/webgl/shaders/Shader.js @@ -6,7 +6,8 @@ * @param [fragmentSrc] {string} The source of the fragment shader. * @param [vertexSrc] {string} The source of the vertex shader. */ -function Shader(gl, vertexSrc, fragmentSrc, customUniforms, customAttributes) { +function Shader(gl, vertexSrc, fragmentSrc, customUniforms, customAttributes) +{ /** * @member {number} * @readonly @@ -33,7 +34,8 @@ dimensions: { type: '4f', value: new Float32Array(4) } }; - for (var u in customUniforms) { + for (var u in customUniforms) + { this.uniforms[u] = customUniforms[u]; } @@ -43,7 +45,8 @@ aColor: 0 }; - for (var a in customAttributes) { + for (var a in customAttributes) + { this.attributes[a] = customAttributes[a]; } @@ -66,7 +69,8 @@ 'const vec2 center = vec2(-1.0, 1.0);', - 'void main(void) {', + 'void main(void) + {', ' gl_Position = vec4( ((aVertexPosition + offsetVector) / projectionVector) + center , 0.0, 1.0);', ' vTextureCoord = aTextureCoord;', ' vColor = vec4(aColor.rgb * aColor.a, aColor.a);', @@ -85,7 +89,8 @@ 'uniform sampler2D uSampler;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;', '}' ].join('\n'); @@ -96,7 +101,8 @@ Shader.prototype.constructor = Shader; module.exports = Shader; -Shader.prototype.init = function () { +Shader.prototype.init = function () +{ this.compile(); this.gl.useProgram(this.program); @@ -105,14 +111,18 @@ this.cacheAttributeLocations(Object.keys(this.attributes)); }; -Shader.prototype.cacheUniformLocations = function (keys) { - for (var i = 0; i < keys.length; ++i) { +Shader.prototype.cacheUniformLocations = function (keys) +{ + for (var i = 0; i < keys.length; ++i) + { this.uniforms[keys[i]]._location = this.gl.getUniformLocation(this.program, keys[i]); } }; -Shader.prototype.cacheAttributeLocations = function (keys) { - for (var i = 0; i < keys.length; ++i) { +Shader.prototype.cacheAttributeLocations = function (keys) +{ + for (var i = 0; i < keys.length; ++i) + { this.attributes[keys[i]] = this.gl.getAttribLocation(this.program, keys[i]); } @@ -124,14 +134,16 @@ // 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.attributes.aColor === -1) { + // if (this.attributes.aColor === -1) + { // this.attributes.aColor = 2; // } // End worst hack eva // }; -Shader.prototype.compile = function () { +Shader.prototype.compile = function () +{ var gl = this.gl; var glVertShader = this._glCompile(gl.VERTEX_SHADER, this.vertexSrc); @@ -144,13 +156,15 @@ gl.linkProgram(program); // if linking fails, then log and cleanup - if (!gl.getProgramParameter(program, gl.LINK_STATUS)) { + if (!gl.getProgramParameter(program, gl.LINK_STATUS)) + { window.console.error('Pixi.js Error: Could not initialize shader.'); window.console.error('gl.VALIDATE_STATUS', gl.getProgramParameter(program, gl.VALIDATE_STATUS)); window.console.error('gl.getError()', gl.getError()); // if there is a program info log, log it - if (gl.getProgramInfoLog(program) !== '') { + if (gl.getProgramInfoLog(program) !== '') + { window.console.warn('Pixi.js Warning: gl.getProgramInfoLog()', gl.getProgramInfoLog(program)); } @@ -165,18 +179,21 @@ return (this.program = program); }; -Shader.prototype.syncUniforms = function () { +Shader.prototype.syncUniforms = function () +{ var gl = this.gl; this.textureCount = 1; - for (var key in this.uniforms) { + for (var key in this.uniforms) + { var uniform = this.uniforms[key], location = uniform._location, value = uniform.value, i, il; - switch (uniform.type) { + switch (uniform.type) + { // single int value case 'i': case '1i': @@ -282,7 +299,8 @@ // a Color Value case 'c': - if (typeof value === 'number') { + if (typeof value === 'number') + { value = utils.hex2rgb(value); } @@ -311,11 +329,13 @@ // array of 2D Point objects case 'v2v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(2 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 2] = value[i].x; uniform._array[i * 2 + 1] = value[i].y; } @@ -325,11 +345,13 @@ // array of 3D Point objects case 'v3v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(3 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 3] = value[i].x; uniform._array[i * 3 + 1] = value[i].y; uniform._array[i * 3 + 2] = value[i].z; @@ -341,11 +363,13 @@ // array of 4D Point objects case 'v4v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(4 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 4] = value[i].x; uniform._array[i * 4 + 1] = value[i].y; uniform._array[i * 4 + 2] = value[i].z; @@ -359,7 +383,8 @@ // PIXI.Texture case 't': case 'sampler2D': - if (!uniform.value || !uniform.value.baseTexture || !uniform.value.baseTexture.hasLoaded) { + if (!uniform.value || !uniform.value.baseTexture || !uniform.value.baseTexture.hasLoaded) + { break; } @@ -376,7 +401,8 @@ this.textureCount++; // initialize the texture if we haven't yet - if (!uniform._init) { + if (!uniform._init) + { this.initSampler2D(uniform); uniform._init = true; @@ -394,11 +420,13 @@ * Initialises a Sampler2D uniform (which may only be available later on after initUniforms once the texture has loaded) * */ -Shader.prototype.initSampler2D = function (uniform) { +Shader.prototype.initSampler2D = function (uniform) +{ var gl = this.gl; // Extended texture data - if (uniform.textureData) { + if (uniform.textureData) + { var data = uniform.textureData; // GLTexture = mag linear, min linear_mipmap_linear, wrap repeat + gl.generateMipmap(gl.TEXTURE_2D); @@ -417,14 +445,16 @@ var wrapT = (data.wrapT) ? data.wrapT : gl.CLAMP_TO_EDGE; var format = (data.luminance) ? gl.LUMINANCE : gl.RGBA; - if (data.repeat) { + if (data.repeat) + { wrapS = gl.REPEAT; wrapT = gl.REPEAT; } gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, !!data.flipY); - if (data.width) { + if (data.width) + { var width = (data.width) ? data.width : 512; var height = (data.height) ? data.height : 2; var border = (data.border) ? data.border : 0; @@ -432,7 +462,8 @@ // 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 { + 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); } @@ -448,7 +479,8 @@ * Destroys the shader. * */ -Shader.prototype.destroy = function () { +Shader.prototype.destroy = function () +{ this.gl.deleteProgram(this.program); this.gl = null; @@ -459,13 +491,15 @@ this.fragmentSrc = null; }; -Shader.prototype._glCompile = function (type, src) { +Shader.prototype._glCompile = function (type, src) +{ var shader = this.gl.createShader(type); this.gl.shaderSource(shader, src); this.gl.compileShader(shader); - if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) { + if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) + { window.console.log(this.gl.getShaderInfoLog(shader)); return null; } diff --git a/src/core/renderers/webgl/shaders/StripShader.js b/src/core/renderers/webgl/shaders/StripShader.js index 193f6e1..a7abcc6 100644 --- a/src/core/renderers/webgl/shaders/StripShader.js +++ b/src/core/renderers/webgl/shaders/StripShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function StripShader(gl) { +function StripShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -20,7 +21,8 @@ 'varying vec2 vTextureCoord;', - 'void main(void) {', + '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);', @@ -36,7 +38,8 @@ 'varying vec2 vTextureCoord;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vec2(vTextureCoord.x, vTextureCoord.y)) * alpha;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/utils/FilterTexture.js b/src/core/renderers/webgl/utils/FilterTexture.js index d2c8423..4433d44 100644 --- a/src/core/renderers/webgl/utils/FilterTexture.js +++ b/src/core/renderers/webgl/utils/FilterTexture.js @@ -8,7 +8,8 @@ * @param height {number} the vertical range of the filter * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values */ -function FilterTexture(gl, width, height, scaleMode) { +function FilterTexture(gl, width, height, scaleMode) +{ /** * @member {WebGLContext} */ @@ -59,7 +60,8 @@ * Clears the filter texture. * */ -FilterTexture.prototype.clear = function () { +FilterTexture.prototype.clear = function () +{ var gl = this.gl; gl.clearColor(0,0,0, 0); @@ -72,8 +74,10 @@ * @param width {number} the new width of the texture * @param height {number} the new height of the texture */ -FilterTexture.prototype.resize = function (width, height) { - if (this.width === width && this.height === height) { +FilterTexture.prototype.resize = function (width, height) +{ + if (this.width === width && this.height === height) + { return; } @@ -96,7 +100,8 @@ * Destroys the filter texture. * */ -FilterTexture.prototype.destroy = function () { +FilterTexture.prototype.destroy = function () +{ var gl = this.gl; gl.deleteFramebuffer( this.frameBuffer ); gl.deleteTexture( this.texture ); diff --git a/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js b/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js index c4721e9..a63f4d7 100644 --- a/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js +++ b/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js @@ -14,7 +14,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this sprite batch works for. */ -function WebGLFastSpriteBatch(renderer) { +function WebGLFastSpriteBatch(renderer) +{ /** * The renderer instance this sprite batch operates on. * @@ -91,7 +92,8 @@ */ this.lastIndexCount = 0; - for (var i=0, j=0; i < numIndices; i += 6, j += 4) { + 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; @@ -144,7 +146,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.setupContext(); }); } @@ -157,7 +160,8 @@ * * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLFastSpriteBatch.prototype.setupContext = function () { +WebGLFastSpriteBatch.prototype.setupContext = function () +{ var gl = this.renderer.gl; // create a couple of buffers @@ -177,7 +181,8 @@ /** * @param spriteBatch {SpriteBatch} The SpriteBatch container to prepare for. */ -WebGLFastSpriteBatch.prototype.begin = function (spriteBatch) { +WebGLFastSpriteBatch.prototype.begin = function (spriteBatch) +{ this.shader = this.renderer.shaderManager.fastShader; this.matrix = spriteBatch.worldTransform.toArray(true); @@ -187,33 +192,38 @@ /** */ -WebGLFastSpriteBatch.prototype.end = function () { +WebGLFastSpriteBatch.prototype.end = function () +{ this.flush(); }; /** * @param spriteBatch {SpriteBatch} The SpriteBatch container to render. */ -WebGLFastSpriteBatch.prototype.render = function (spriteBatch) { +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) { + if (!sprite.texture._uvs) + { return; } this.currentBaseTexture = sprite.texture.baseTexture; // check blend mode - if (sprite.blendMode !== this.renderer.blendModeManager.currentBlendMode) { + if (sprite.blendMode !== this.renderer.blendModeManager.currentBlendMode) + { this.flush(); this.renderer.blendModeManager.setBlendMode(sprite.blendMode); } - for (var i=0,j= children.length; i= this.size) { + if (this.currentBatchSize >= this.size) + { this.flush(); } }; @@ -362,29 +379,35 @@ /** * */ -WebGLFastSpriteBatch.prototype.flush = function () { +WebGLFastSpriteBatch.prototype.flush = function () +{ // If the batch is length 0 then return as there is nothing to draw - if (this.currentBatchSize === 0) { + if (this.currentBatchSize === 0) + { return; } var gl = this.renderer.gl; // bind the current texture - if (!this.currentBaseTexture._glTextures[gl.id]) { + if (!this.currentBaseTexture._glTextures[gl.id]) + { this.renderer.updateTexture(this.currentBaseTexture, gl); } //TODO-SHOUD THIS BE ELSE??!?!?! - else { + else + { gl.bindTexture(gl.TEXTURE_2D, this.currentBaseTexture._glTextures[gl.id]); } // upload the verts to the buffer - if (this.currentBatchSize > ( this.size * 0.5 ) ) { + if (this.currentBatchSize > ( this.size * 0.5 ) ) + { gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); } - else { + else + { var view = this.vertices.subarray(0, this.currentBatchSize * this.vertByteSize); gl.bufferSubData(gl.ARRAY_BUFFER, 0, view); @@ -405,14 +428,16 @@ * Ends the batch and flushes * */ -WebGLFastSpriteBatch.prototype.stop = function () { +WebGLFastSpriteBatch.prototype.stop = function () +{ this.flush(); }; /** * */ -WebGLFastSpriteBatch.prototype.start = function () { +WebGLFastSpriteBatch.prototype.start = function () +{ var gl = this.renderer.gl; // bind the main texture diff --git a/src/core/renderers/webgl/utils/WebGLGraphics.js b/src/core/renderers/webgl/utils/WebGLGraphics.js index 55f4911..ab8f46e 100644 --- a/src/core/renderers/webgl/utils/WebGLGraphics.js +++ b/src/core/renderers/webgl/utils/WebGLGraphics.js @@ -19,7 +19,8 @@ * @param graphics {Graphics} * @param renderer {WebGLRenderer} */ -WebGLGraphics.renderGraphics = function (graphics, renderer) {//projection, offset) { +WebGLGraphics.renderGraphics = function (graphics, renderer) {//projection, offset) +{ var gl = renderer.gl; var projection = renderer.projection, @@ -27,7 +28,8 @@ shader = renderer.shaderManager.primitiveShader, webGLData; - if (graphics.dirty) { + if (graphics.dirty) + { WebGLGraphics.updateGraphics(graphics, gl); } @@ -35,8 +37,10 @@ // This could be speeded up for sure! - for (var i = 0; i < webGL.data.length; i++) { - if (webGL.data[i].mode === 1) { + for (var i = 0; i < webGL.data.length; i++) + { + if (webGL.data[i].mode === 1) + { webGLData = webGL.data[i]; renderer.stencilManager.pushStencil(graphics, webGLData, renderer); @@ -46,7 +50,8 @@ renderer.stencilManager.popStencil(graphics, webGLData, renderer); } - else { + else + { webGLData = webGL.data[i]; @@ -84,12 +89,14 @@ * @param graphicsData {Graphics} The graphics object to update * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLGraphics.updateGraphics = function (graphics, gl) { +WebGLGraphics.updateGraphics = function (graphics, gl) +{ // get the contexts graphics object var webGL = graphics._webGL[gl.id]; // if the graphics object does not exist in the webGL context time to create it! - if (!webGL) { + if (!webGL) + { webGL = graphics._webGL[gl.id] = {lastIndex:0, data:[], gl:gl}; } @@ -99,11 +106,13 @@ var i; // if the user cleared the graphics object we will need to clear every object - if (graphics.clearDirty) { + if (graphics.clearDirty) + { graphics.clearDirty = false; // lop through and return all the webGLDatas to the object pool so than can be reused later on - for (i = 0; i < webGL.data.length; i++) { + for (i = 0; i < webGL.data.length; i++) + { var graphicsData = webGL.data[i]; graphicsData.reset(); WebGLGraphics.graphicsDataPool.push( graphicsData ); @@ -119,58 +128,72 @@ // loop through the graphics datas and construct each one.. // if the object is a complex fill then the new stencil buffer technique will be used // other wise graphics objects will be pushed into a batch.. - for (i = webGL.lastIndex; i < graphics.graphicsData.length; i++) { + for (i = webGL.lastIndex; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { // need to add the points the the graphics object.. data.points = data.shape.points.slice(); - if (data.shape.closed) { + if (data.shape.closed) + { // close the poly if the value is true! - if (data.points[0] !== data.points[data.points.length-2] || data.points[1] !== data.points[data.points.length-1]) { + if (data.points[0] !== data.points[data.points.length-2] || data.points[1] !== data.points[data.points.length-1]) + { data.points.push(data.points[0], data.points[1]); } } // MAKE SURE WE HAVE THE CORRECT TYPE.. - if (data.fill) { - if (data.points.length >= 6) { - if (data.points.length < 6 * 2) { + if (data.fill) + { + if (data.points.length >= 6) + { + if (data.points.length < 6 * 2) + { webGLData = WebGLGraphics.switchMode(webGL, 0); var canDrawUsingSimple = WebGLGraphics.buildPoly(data, webGLData); // console.log(canDrawUsingSimple); - if (!canDrawUsingSimple) { + if (!canDrawUsingSimple) + { // console.log("<>>>") webGLData = WebGLGraphics.switchMode(webGL, 1); WebGLGraphics.buildComplexPoly(data, webGLData); } } - else { + else + { webGLData = WebGLGraphics.switchMode(webGL, 1); WebGLGraphics.buildComplexPoly(data, webGLData); } } } - if (data.lineWidth > 0) { + if (data.lineWidth > 0) + { webGLData = WebGLGraphics.switchMode(webGL, 0); WebGLGraphics.buildLine(data, webGLData); } } - else { + else + { webGLData = WebGLGraphics.switchMode(webGL, 0); - if (data.type === CONST.SHAPES.RECT) { + if (data.type === CONST.SHAPES.RECT) + { WebGLGraphics.buildRectangle(data, webGLData); } - else if (data.type === CONST.SHAPES.CIRC || data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.CIRC || data.type === CONST.SHAPES.ELIP) + { WebGLGraphics.buildCircle(data, webGLData); } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { WebGLGraphics.buildRoundedRectangle(data, webGLData); } } @@ -179,10 +202,12 @@ } // upload all the dirty data... - for (i = 0; i < webGL.data.length; i++) { + for (i = 0; i < webGL.data.length; i++) + { webGLData = webGL.data[i]; - if (webGLData.dirty) { + if (webGLData.dirty) + { webGLData.upload(); } } @@ -194,18 +219,22 @@ * @param webGL {WebGLContext} * @param type {number} */ -WebGLGraphics.switchMode = function (webGL, type) { +WebGLGraphics.switchMode = function (webGL, type) +{ var webGLData; - if (!webGL.data.length) { + if (!webGL.data.length) + { webGLData = WebGLGraphics.graphicsDataPool.pop() || new WebGLGraphicsData(webGL.gl); webGLData.mode = type; webGL.data.push(webGLData); } - else { + else + { webGLData = webGL.data[webGL.data.length-1]; - if (webGLData.mode !== type || type === 1) { + if (webGLData.mode !== type || type === 1) + { webGLData = WebGLGraphics.graphicsDataPool.pop() || new WebGLGraphicsData(webGL.gl); webGLData.mode = type; webGL.data.push(webGLData); @@ -225,7 +254,8 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildRectangle = function (graphicsData, webGLData) { +WebGLGraphics.buildRectangle = function (graphicsData, webGLData) +{ // --- // // need to convert points to a nice regular data // @@ -235,7 +265,8 @@ var width = rectData.width; var height = rectData.height; - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -265,7 +296,8 @@ indices.push(vertPos, vertPos, vertPos+1, vertPos+2, vertPos+3, vertPos+3); } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = [x, y, @@ -289,7 +321,8 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildRoundedRectangle = function (graphicsData, webGLData) { +WebGLGraphics.buildRoundedRectangle = function (graphicsData, webGLData) +{ var rrectData = graphicsData.shape; var x = rrectData.x; var y = rrectData.y; @@ -305,7 +338,8 @@ recPoints = recPoints.concat(WebGLGraphics.quadraticBezierCurve(x + width, y + radius, x + width, y, x + width - radius, y)); recPoints = recPoints.concat(WebGLGraphics.quadraticBezierCurve(x + radius, y, x, y, x, y + radius)); - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -323,7 +357,8 @@ // var i = 0; - for (i = 0; i < triangles.length; i+=3) { + for (i = 0; i < triangles.length; i+=3) + { indices.push(triangles[i] + vecPos); indices.push(triangles[i] + vecPos); indices.push(triangles[i+1] + vecPos); @@ -332,12 +367,14 @@ } - for (i = 0; i < recPoints.length; i++) { + for (i = 0; i < recPoints.length; i++) + { verts.push(recPoints[i], recPoints[++i], r, g, b, alpha); } } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = recPoints; @@ -362,7 +399,8 @@ * @param toY {number} Destination point y * @return {number[]} */ -WebGLGraphics.quadraticBezierCurve = function (fromX, fromY, cpX, cpY, toX, toY) { +WebGLGraphics.quadraticBezierCurve = function (fromX, fromY, cpX, cpY, toX, toY) +{ var xa, ya, @@ -373,14 +411,16 @@ n = 20, points = []; - function getPt(n1 , n2, perc) { + function getPt(n1 , n2, perc) + { var diff = n2 - n1; return n1 + ( diff * perc ); } var j = 0; - for (var i = 0; i <= n; i++ ) { + for (var i = 0; i <= n; i++ ) + { j = i / n; // The Green Line @@ -406,7 +446,8 @@ * @param graphicsData {Graphics} The graphics object to draw * @param webGLData {object} */ -WebGLGraphics.buildCircle = function (graphicsData, webGLData) { +WebGLGraphics.buildCircle = function (graphicsData, webGLData) +{ // need to convert points to a nice regular data var circleData = graphicsData.shape; var x = circleData.x; @@ -415,11 +456,13 @@ var height; // TODO - bit hacky?? - if (graphicsData.type === CONST.SHAPES.CIRC) { + if (graphicsData.type === CONST.SHAPES.CIRC) + { width = circleData.radius; height = circleData.radius; } - else { + else + { width = circleData.width; height = circleData.height; } @@ -429,7 +472,8 @@ var i = 0; - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -444,7 +488,8 @@ indices.push(vecPos); - for (i = 0; i < totalSegs + 1 ; i++) { + for (i = 0; i < totalSegs + 1 ; i++) + { verts.push(x,y, r, g, b, alpha); verts.push(x + Math.sin(seg * i) * width, @@ -457,12 +502,14 @@ indices.push(vecPos-1); } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = []; - for (i = 0; i < totalSegs + 1; i++) { + for (i = 0; i < totalSegs + 1; i++) + { graphicsData.points.push(x + Math.sin(seg * i) * width, y + Math.cos(seg * i) * height); } @@ -481,18 +528,22 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildLine = function (graphicsData, webGLData) { +WebGLGraphics.buildLine = function (graphicsData, webGLData) +{ // TODO OPTIMISE! var i = 0; var points = graphicsData.points; - if (points.length === 0) { + if (points.length === 0) + { return; } // if the line width is an odd number add 0.5 to align to a whole pixel - if (graphicsData.lineWidth%2) { - for (i = 0; i < points.length; i++) { + if (graphicsData.lineWidth%2) + { + for (i = 0; i < points.length; i++) + { points[i] += 0.5; } } @@ -502,7 +553,8 @@ var lastPoint = new math.Point(points[points.length - 2], points[points.length - 1]); // if the first point is the last point - gonna have issues :) - if (firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) { + if (firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) + { // need to clone as we are going to slightly modify the shape.. points = points.slice(); @@ -562,7 +614,8 @@ verts.push(p1x + perpx , p1y + perpy, r, g, b, alpha); - for (i = 1; i < length-1; i++) { + for (i = 1; i < length-1; i++) + { p1x = points[(i-1)*2]; p1y = points[(i-1)*2 + 1]; @@ -599,7 +652,8 @@ denom = a1*b2 - a2*b1; - if (Math.abs(denom) < 0.1 ) { + if (Math.abs(denom) < 0.1 ) + { denom+=10.1; verts.push(p2x - perpx , p2y - perpy, @@ -618,7 +672,8 @@ pdist = (px -p2x) * (px -p2x) + (py -p2y) + (py -p2y); - if (pdist > 140 * 140) { + if (pdist > 140 * 140) + { perp3x = perpx - perp2x; perp3y = perpy - perp2y; @@ -639,7 +694,8 @@ indexCount++; } - else { + else + { verts.push(px , py); verts.push(r, g, b, alpha); @@ -672,7 +728,8 @@ indices.push(indexStart); - for (i = 0; i < indexCount; i++) { + for (i = 0; i < indexCount; i++) + { indices.push(indexStart++); } @@ -687,11 +744,13 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildComplexPoly = function (graphicsData, webGLData) { +WebGLGraphics.buildComplexPoly = function (graphicsData, webGLData) +{ //TODO - no need to copy this as it gets turned into a FLoat32Array anyways.. var points = graphicsData.points.slice(); - if (points.length < 6) { + if (points.length < 6) + { return; } @@ -711,7 +770,8 @@ var x,y; // get size.. - for (var i = 0; i < points.length; i+=2) { + for (var i = 0; i < points.length; i+=2) + { x = points[i]; y = points[i+1]; @@ -732,7 +792,8 @@ //TODO - this aint needed! var length = points.length / 2; - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { indices.push( i ); } @@ -746,10 +807,12 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildPoly = function (graphicsData, webGLData) { +WebGLGraphics.buildPoly = function (graphicsData, webGLData) +{ var points = graphicsData.points; - if (points.length < 6) { + if (points.length < 6) + { return; } // get first and last point.. figure out the middle! @@ -767,7 +830,8 @@ var triangles = utils.PolyK.Triangulate(points); - if (!triangles) { + if (!triangles) + { return false; } @@ -775,7 +839,8 @@ var i = 0; - for (i = 0; i < triangles.length; i+=3) { + for (i = 0; i < triangles.length; i+=3) + { indices.push(triangles[i] + vertPos); indices.push(triangles[i] + vertPos); indices.push(triangles[i+1] + vertPos); @@ -783,7 +848,8 @@ indices.push(triangles[i+2] + vertPos); } - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { verts.push(points[i * 2], points[i * 2 + 1], r, g, b, alpha); } diff --git a/src/core/renderers/webgl/utils/WebGLGraphicsData.js b/src/core/renderers/webgl/utils/WebGLGraphicsData.js index c56d05e..c739ba7 100644 --- a/src/core/renderers/webgl/utils/WebGLGraphicsData.js +++ b/src/core/renderers/webgl/utils/WebGLGraphicsData.js @@ -2,7 +2,8 @@ * @class * @private */ -function WebGLGraphicsData(gl) { +function WebGLGraphicsData(gl) +{ this.gl = gl; //TODO does this need to be split before uploding?? @@ -22,7 +23,8 @@ /** * */ -WebGLGraphicsData.prototype.reset = function () { +WebGLGraphicsData.prototype.reset = function () +{ this.points.length = 0; this.indices.length = 0; }; @@ -30,7 +32,8 @@ /** * */ -WebGLGraphicsData.prototype.upload = function () { +WebGLGraphicsData.prototype.upload = function () +{ var gl = this.gl; // this.lastIndex = graphics.graphicsData.length; diff --git a/src/core/renderers/webgl/utils/WebGLSpriteBatch.js b/src/core/renderers/webgl/utils/WebGLSpriteBatch.js index 96eaa52..55befbb 100644 --- a/src/core/renderers/webgl/utils/WebGLSpriteBatch.js +++ b/src/core/renderers/webgl/utils/WebGLSpriteBatch.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this sprite batch works for. */ -function WebGLSpriteBatch(renderer) { +function WebGLSpriteBatch(renderer) +{ /** * * @@ -88,7 +89,8 @@ */ this.lastIndexCount = 0; - for (var i=0, j=0; i < numIndices; i += 6, j += 4) { + 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; @@ -162,7 +164,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.setupContext(); }); } @@ -173,7 +176,8 @@ /** * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLSpriteBatch.prototype.setupContext = function () { +WebGLSpriteBatch.prototype.setupContext = function () +{ var gl = this.renderer.gl; // setup default shader @@ -198,7 +202,8 @@ /** * */ -WebGLSpriteBatch.prototype.begin = function () { +WebGLSpriteBatch.prototype.begin = function () +{ // this.shader = this.renderer.shaderManager.defaultShader; this.start(); @@ -206,19 +211,22 @@ /** */ -WebGLSpriteBatch.prototype.end = function () { +WebGLSpriteBatch.prototype.end = function () +{ this.flush(); }; /** * @param sprite {Sprite} the sprite to render when using this spritebatch */ -WebGLSpriteBatch.prototype.render = function (sprite) { +WebGLSpriteBatch.prototype.render = function (sprite) +{ var texture = sprite.texture; //TODO set blend modes.. // check texture.. - if (this.currentBatchSize >= this.size) { + if (this.currentBatchSize >= this.size) + { this.flush(); this.currentBaseTexture = texture.baseTexture; } @@ -227,7 +235,8 @@ var uvs = texture._uvs; // if the uvs have not updated then no point rendering just yet! - if (!uvs) { + if (!uvs) + { return; } @@ -237,7 +246,8 @@ var w0, w1, h0, h1; - if (texture.trim) { + 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; @@ -248,7 +258,8 @@ h0 = h1 + texture.crop.height; } - else { + else + { w0 = (texture.frame.width ) * (1-aX); w1 = (texture.frame.width ) * -aX; @@ -272,7 +283,8 @@ var colors = this.colors; var positions = this.positions; - if (this.renderer.roundPixels) { + if (this.renderer.roundPixels) + { // xy positions[index] = a * w1 + c * h1 + tx | 0; positions[index+1] = d * h1 + b * w1 + ty | 0; @@ -289,7 +301,8 @@ positions[index+15] = a * w1 + c * h0 + tx | 0; positions[index+16] = d * h0 + b * w1 + ty | 0; } - else { + else + { // xy positions[index] = a * w1 + c * h1 + tx; positions[index+1] = d * h1 + b * w1 + ty; @@ -338,11 +351,13 @@ * * @param sprite {TilingSprite} the tilingSprite to render */ -WebGLSpriteBatch.prototype.renderTilingSprite = function (tilingSprite) { +WebGLSpriteBatch.prototype.renderTilingSprite = function (tilingSprite) +{ var texture = tilingSprite.tilingTexture; // check texture.. - if (this.currentBatchSize >= this.size) { + if (this.currentBatchSize >= this.size) + { //return; this.flush(); this.currentBaseTexture = texture.baseTexture; @@ -351,7 +366,8 @@ // set the textures uvs temporarily // TODO create a separate texture so that we can tile part of a texture - if (!tilingSprite._uvs) { + if (!tilingSprite._uvs) + { tilingSprite._uvs = new TextureUvs(); } @@ -454,16 +470,19 @@ * Renders the content and empties the current batch. * */ -WebGLSpriteBatch.prototype.flush = function () { +WebGLSpriteBatch.prototype.flush = function () +{ // If the batch is length 0 then return as there is nothing to draw - if (this.currentBatchSize === 0) { + if (this.currentBatchSize === 0) + { return; } var gl = this.renderer.gl; var shader; - if (this.dirty) { + if (this.dirty) + { this.dirty = false; // bind the main texture gl.activeTexture(gl.TEXTURE0); @@ -482,10 +501,12 @@ } // upload the verts to the buffer - if (this.currentBatchSize > ( this.size * 0.5 ) ) { + if (this.currentBatchSize > ( this.size * 0.5 ) ) + { gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); } - else { + else + { var view = this.positions.subarray(0, this.currentBatchSize * this.vertByteSize); gl.bufferSubData(gl.ARRAY_BUFFER, 0, view); } @@ -502,7 +523,8 @@ var shaderSwap = false; var sprite; - for (var i = 0, j = this.currentBatchSize; i < j; i++) { + for (var i = 0, j = this.currentBatchSize; i < j; i++) + { sprite = this.sprites[i]; @@ -513,24 +535,28 @@ blendSwap = currentBlendMode !== nextBlendMode; shaderSwap = currentShader !== nextShader; // should I use uuidS??? - if (currentBaseTexture !== nextTexture || blendSwap || shaderSwap) { + if (currentBaseTexture !== nextTexture || blendSwap || shaderSwap) + { this.renderBatch(currentBaseTexture, batchSize, start); start = i; batchSize = 0; currentBaseTexture = nextTexture; - if (blendSwap) { + if (blendSwap) + { currentBlendMode = nextBlendMode; this.renderer.blendModeManager.setBlendMode( currentBlendMode ); } - if (shaderSwap) { + if (shaderSwap) + { currentShader = nextShader; shader = currentShader.shaders ? currentShader.shaders[gl.id] : currentShader; - if (!shader) { + if (!shader) + { shader = new Shader(gl, null, currentShader.fragmentSrc, currentShader.uniforms); currentShader.shaders[gl.id] = shader; } @@ -538,7 +564,8 @@ // set shader function??? this.renderer.shaderManager.setShader(shader); - if (shader.dirty) { + if (shader.dirty) + { shader.syncUniforms(); } @@ -569,17 +596,21 @@ * @param size {number} * @param startIndex {number} */ -WebGLSpriteBatch.prototype.renderBatch = function (texture, size, startIndex) { - if (size === 0) { +WebGLSpriteBatch.prototype.renderBatch = function (texture, size, startIndex) +{ + if (size === 0) + { return; } var gl = this.renderer.gl; - if (!texture._glTextures[gl.id]) { + if (!texture._glTextures[gl.id]) + { this.renderer.updateTexture(texture); } - else { + else + { // bind the current texture gl.bindTexture(gl.TEXTURE_2D, texture._glTextures[gl.id]); } @@ -594,7 +625,8 @@ /** * */ -WebGLSpriteBatch.prototype.stop = function () { +WebGLSpriteBatch.prototype.stop = function () +{ this.flush(); this.dirty = true; }; @@ -602,7 +634,8 @@ /** * */ -WebGLSpriteBatch.prototype.start = function () { +WebGLSpriteBatch.prototype.start = function () +{ this.dirty = true; }; @@ -610,7 +643,8 @@ * Destroys the SpriteBatch. * */ -WebGLSpriteBatch.prototype.destroy = function () { +WebGLSpriteBatch.prototype.destroy = function () +{ this.renderer.gl.deleteBuffer(this.vertexBuffer); this.renderer.gl.deleteBuffer(this.indexBuffer); diff --git a/src/core/textures/BaseTexture.js b/src/core/textures/BaseTexture.js index 2bf77d4..513d358 100644 --- a/src/core/textures/BaseTexture.js +++ b/src/core/textures/BaseTexture.js @@ -10,7 +10,8 @@ * @param source {Image|Canvas} the source object of the texture. * @param [scaleMode=scaleModes.DEFAULT] {number} See {@link scaleModes} for possible values */ -function BaseTexture(source, scaleMode) { +function BaseTexture(source, scaleMode) +{ this.uuid = utils.uuid(); /** @@ -123,7 +124,8 @@ this._needsUpdate = false; // if no source passed don't try to load - if (source) { + if (source) + { this.loadSource(source); } @@ -149,13 +151,16 @@ Object.defineProperties(BaseTexture.prototype, { needsUpdate: { - get: function () { + get: function () + { return this._needsUpdate; }, - set: function (val) { + set: function (val) + { this._needsUpdate = val; - if (val) { + if (val) + { this.emit('update', this); } } @@ -171,9 +176,11 @@ * * The logic state after calling `loadSource` directly or indirectly (eg. `fromImage`, `new BaseTexture`) is: * - * if (texture.hasLoaded) { + * if (texture.hasLoaded) + { * // texture ready for use - * } else if (texture.isLoading) { + * } else if (texture.isLoading) + { * // listen to 'loaded' and/or 'error' events on texture * } else { * // not loading, not going to load UNLESS the source is reloaded @@ -183,12 +190,14 @@ * @protected * @param source {Image|Canvas} the source object of the texture. */ -BaseTexture.prototype.loadSource = function (source) { +BaseTexture.prototype.loadSource = function (source) +{ var wasLoading = this.isLoading; this.hasLoaded = false; this.isLoading = false; - if (wasLoading && this.source) { + if (wasLoading && this.source) + { this.source.onload = null; this.source.onerror = null; } @@ -196,20 +205,24 @@ this.source = source; // Apply source if loaded. Otherwise setup appropriate loading monitors. - if ((this.source.complete || this.source.getContext) && this.source.width && this.source.height) { + if ((this.source.complete || this.source.getContext) && this.source.width && this.source.height) + { this._sourceLoaded(); } - else if(!source.getContext) { + else if(!source.getContext) + { // Image fail / not ready this.isLoading = true; var scope = this; - source.onload = function () { + source.onload = function () + { source.onload = null; source.onerror = null; - if(!scope.isLoading) { + if(!scope.isLoading) + { return; } @@ -219,11 +232,13 @@ scope.emit('loaded', scope); }; - source.onerror = function () { + source.onerror = function () + { source.onload = null; source.onerror = null; - if(!scope.isLoading) { + if(!scope.isLoading) + { return; } @@ -234,24 +249,29 @@ // Per http://www.w3.org/TR/html5/embedded-content-0.html#the-img-element // "The value of `complete` can thus change while a script is executing." // So complete needs to be re-checked after the callbacks have been added.. - if (source.complete) { + if (source.complete) + { this.isLoading = false; // ..and if we're complete now, no need for callbacks source.onload = null; source.onerror = null; - if (source.width && source.height) { + if (source.width && source.height) + { this._sourceLoaded(); // If any previous subscribers possible - if (wasLoading) { + if (wasLoading) + { this.emit('loaded', this); } } - else { + else + { // If any previous subscribers possible - if (wasLoading) { + if (wasLoading) + { this.emit('error', this); } } @@ -265,7 +285,8 @@ * * @private */ -BaseTexture.prototype._sourceLoaded = function () { +BaseTexture.prototype._sourceLoaded = function () +{ this.hasLoaded = true; this.width = this.source.naturalWidth || this.source.width; @@ -278,16 +299,20 @@ * Destroys this base texture * */ -BaseTexture.prototype.destroy = function () { - if (this.imageUrl) { +BaseTexture.prototype.destroy = function () +{ + if (this.imageUrl) + { delete utils.BaseTextureCache[this.imageUrl]; delete utils.TextureCache[this.imageUrl]; this.imageUrl = null; - if (!navigator.isCocoonJS) { + if (!navigator.isCocoonJS) + { this.source.src = ''; } } - else if (this.source && this.source._pixiId) { + else if (this.source && this.source._pixiId) + { delete utils.BaseTextureCache[this.source._pixiId]; } this.source = null; @@ -301,7 +326,8 @@ * memory again. * */ -BaseTexture.prototype.dispose = function () { +BaseTexture.prototype.dispose = function () +{ this.emit('dispose', this); }; @@ -311,7 +337,8 @@ * * @param newSrc {string} the path of the image */ -BaseTexture.prototype.updateSourceImage = function (newSrc) { +BaseTexture.prototype.updateSourceImage = function (newSrc) +{ this.source.src = newSrc; this.loadSource(this.source); }; @@ -326,18 +353,22 @@ * @param [scaleMode=scaleModes.DEFAULT] {number} See {@link scaleModes} for possible values * @return BaseTexture */ -BaseTexture.fromImage = function (imageUrl, crossorigin, scaleMode) { +BaseTexture.fromImage = function (imageUrl, crossorigin, scaleMode) +{ var baseTexture = utils.BaseTextureCache[imageUrl]; - if (crossorigin === undefined && imageUrl.indexOf('data:') !== 0) { + if (crossorigin === undefined && imageUrl.indexOf('data:') !== 0) + { crossorigin = true; } - if (!baseTexture) { + if (!baseTexture) + { // new Image() breaks tex loading in some versions of Chrome. // See https://code.google.com/p/chromium/issues/detail?id=238071 var image = new Image();//document.createElement('img'); - if (crossorigin) { + if (crossorigin) + { image.crossOrigin = ''; } @@ -347,7 +378,8 @@ utils.BaseTextureCache[imageUrl] = baseTexture; // if there is an @2x at the end of the url we are going to assume its a highres image - if ( imageUrl.indexOf(CONST.RETINA_PREFIX + '.') !== -1) { + if ( imageUrl.indexOf(CONST.RETINA_PREFIX + '.') !== -1) + { baseTexture.resolution = 2; } } @@ -363,14 +395,17 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return BaseTexture */ -BaseTexture.fromCanvas = function (canvas, scaleMode) { - if (!canvas._pixiId) { +BaseTexture.fromCanvas = function (canvas, scaleMode) +{ + if (!canvas._pixiId) + { canvas._pixiId = 'canvas_' + utils.uuid(); } var baseTexture = utils.BaseTextureCache[canvas._pixiId]; - if (!baseTexture) { + if (!baseTexture) + { baseTexture = new BaseTexture(canvas, scaleMode); utils.BaseTextureCache[canvas._pixiId] = baseTexture; } diff --git a/src/core/textures/RenderTexture.js b/src/core/textures/RenderTexture.js index 6dad20f..53ae796 100644 --- a/src/core/textures/RenderTexture.js +++ b/src/core/textures/RenderTexture.js @@ -46,8 +46,10 @@ * @param [scaleMode] {number} See {@link scaleModes} for possible values * @param [resolution=1] {number} The resolution of the texture being generated */ -function RenderTexture(renderer, width, height, scaleMode, resolution) { - if (!renderer) { +function RenderTexture(renderer, width, height, scaleMode, resolution) +{ + if (!renderer) + { throw new Error('Unable to create RenderTexture, you must pass a renderer into the constructor.'); } @@ -133,7 +135,8 @@ */ this.renderer = renderer; - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { var gl = this.renderer.gl; this.textureBuffer = new FilterTexture(gl, this.width * this.resolution, this.height * this.resolution, this.baseTexture.scaleMode); @@ -142,7 +145,8 @@ this.render = this.renderWebGL; this.projection = new math.Point(this.width*0.5, -this.height*0.5); } - else { + else + { this.render = this.renderCanvas; this.textureBuffer = new CanvasBuffer(this.width* this.resolution, this.height* this.resolution); this.baseTexture.source = this.textureBuffer.canvas; @@ -167,8 +171,10 @@ * @param height {number} The height to resize to. * @param updateBase {boolean} Should the baseTexture.width and height values be resized as well? */ -RenderTexture.prototype.resize = function (width, height, updateBase) { - if (width === this.width && height === this.height) { +RenderTexture.prototype.resize = function (width, height, updateBase) +{ + if (width === this.width && height === this.height) + { return; } @@ -177,17 +183,20 @@ this.width = this.frame.width = this.crop.width = width; this.height = this.frame.height = this.crop.height = height; - if (updateBase) { + if (updateBase) + { this.baseTexture.width = this.width; this.baseTexture.height = this.height; } - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { this.projection.x = this.width / 2; this.projection.y = -this.height / 2; } - if (!this.valid) { + if (!this.valid) + { return; } @@ -198,12 +207,15 @@ * Clears the RenderTexture. * */ -RenderTexture.prototype.clear = function () { - if (!this.valid) { +RenderTexture.prototype.clear = function () +{ + if (!this.valid) + { return; } - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { this.renderer.gl.bindFramebuffer(this.renderer.gl.FRAMEBUFFER, this.textureBuffer.frameBuffer); } @@ -220,19 +232,23 @@ * @param [restoreWorldTransform=true] {boolean} If true the displayObject's worldTransform/worldAlpha and all children * transformations will be restored. Not restoring this information will be a little faster. */ -RenderTexture.prototype.renderWebGL = function (displayObject, matrix, clear, restoreWorldTransform) { - if (!this.valid) { +RenderTexture.prototype.renderWebGL = function (displayObject, matrix, clear, restoreWorldTransform) +{ + if (!this.valid) + { return; } - if (typeof restoreWorldTransform === 'undefined') { + if (typeof restoreWorldTransform === 'undefined') + { restoreWorldTransform = true; } var tempAlpha, tempTransform; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { tempAlpha = displayObject.worldAlpha; tempTransform = displayObject.worldTransform.toArray(); } @@ -245,7 +261,8 @@ wt.identity(); wt.translate(0, this.projection.y * 2); - if (matrix) { + if (matrix) + { wt.append(matrix); } @@ -258,7 +275,8 @@ var children = displayObject.children; var i, j; - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } @@ -269,7 +287,8 @@ gl.bindFramebuffer(gl.FRAMEBUFFER, this.textureBuffer.frameBuffer ); - if (clear) { + if (clear) + { this.textureBuffer.clear(); } @@ -279,11 +298,13 @@ this.renderer.spriteBatch.dirty = true; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { displayObject.worldAlpha = tempAlpha; displayObject.worldTransform.fromArray(tempTransform); - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } } @@ -300,26 +321,31 @@ * @param [restoreWorldTransform=true] {boolean} If true the displayObject's worldTransform/worldAlpha and all children * transformations will be restored. Not restoring this information will be a little faster. */ -RenderTexture.prototype.renderCanvas = function (displayObject, matrix, clear, restoreWorldTransform) { - if (!this.valid) { +RenderTexture.prototype.renderCanvas = function (displayObject, matrix, clear, restoreWorldTransform) +{ + if (!this.valid) + { return; } - if (typeof restoreWorldTransform === 'undefined') { + if (typeof restoreWorldTransform === 'undefined') + { restoreWorldTransform = true; } var tempAlpha, tempTransform; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { tempAlpha = displayObject.worldAlpha; tempTransform = displayObject.worldTransform.toArray(); } var wt = displayObject.worldTransform; wt.identity(); - if (matrix) { + if (matrix) + { wt.append(matrix); } @@ -330,11 +356,13 @@ var children = displayObject.children; var i, j; - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } - if (clear) { + if (clear) + { this.textureBuffer.clear(); } @@ -348,11 +376,13 @@ this.renderer.resolution = realResolution; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { displayObject.worldAlpha = tempAlpha; displayObject.worldTransform.fromArray(tempTransform); - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } } @@ -363,7 +393,8 @@ * * @return {Image} */ -RenderTexture.prototype.getImage = function () { +RenderTexture.prototype.getImage = function () +{ var image = new Image(); image.src = this.getBase64(); return image; @@ -374,7 +405,8 @@ * * @return {string} A base64 encoded string of the texture. */ -RenderTexture.prototype.getBase64 = function () { +RenderTexture.prototype.getBase64 = function () +{ return this.getCanvas().toDataURL(); }; @@ -383,8 +415,10 @@ * * @return {HTMLCanvasElement} A Canvas element with the texture rendered on. */ -RenderTexture.prototype.getCanvas = function () { - if (this.renderer.type === CONST.WEBGL_RENDERER) { +RenderTexture.prototype.getCanvas = function () +{ + if (this.renderer.type === CONST.WEBGL_RENDERER) + { var gl = this.renderer.gl; var width = this.textureBuffer.width; var height = this.textureBuffer.height; @@ -403,7 +437,8 @@ return tempCanvas.canvas; } - else { + else + { return this.textureBuffer.canvas; } }; diff --git a/src/core/textures/Texture.js b/src/core/textures/Texture.js index 3c65909..e97f0aa 100644 --- a/src/core/textures/Texture.js +++ b/src/core/textures/Texture.js @@ -17,7 +17,8 @@ * @param [crop] {Rectangle} The area of original texture * @param [trim] {Rectangle} Trimmed texture rectangle */ -function Texture(baseTexture, frame, crop, trim) { +function Texture(baseTexture, frame, crop, trim) +{ /** * Does this Texture have any frame data assigned to it? * @@ -25,12 +26,14 @@ */ this.noFrame = false; - if (!frame) { + if (!frame) + { this.noFrame = true; frame = new math.Rectangle(0, 0, 1, 1); } - if (baseTexture instanceof Texture) { + if (baseTexture instanceof Texture) + { baseTexture = baseTexture.baseTexture; } @@ -100,13 +103,16 @@ */ this.crop = crop || new math.Rectangle(0, 0, 1, 1); - if (baseTexture.hasLoaded) { - if (this.noFrame) { + if (baseTexture.hasLoaded) + { + if (this.noFrame) + { frame = new math.Rectangle(0, 0, baseTexture.width, baseTexture.height); } this.frame = frame; } - else { + else + { baseTexture.addEventListener('loaded', this.onBaseTextureLoaded.bind(this)); } } @@ -118,19 +124,23 @@ Object.defineProperties(Texture.prototype, { needsUpdate: { - get: function () { + get: function () + { return this.baseTexture.needsUpdate; }, - set: function (val) { + set: function (val) + { this.baseTexture.needsUpdate = val; } }, frame: { - get: function () { + get: function () + { return this._frame; }, - set: function (frame) { + set: function (frame) + { this._frame = frame; this.noFrame = false; @@ -143,20 +153,23 @@ 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 (!this.trim && (frame.x + frame.width > this.baseTexture.width || frame.y + frame.height > this.baseTexture.height)) + { throw new Error('Texture Error: frame does not fit inside the base Texture dimensions ' + this); } this.valid = frame && frame.width && frame.height && this.baseTexture.source && this.baseTexture.hasLoaded; - if (this.trim) { + 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) { + if (this.valid) + { this._updateUvs(); } } @@ -168,11 +181,13 @@ * * @private */ -Texture.prototype.onBaseTextureLoaded = function () { +Texture.prototype.onBaseTextureLoaded = function () +{ var baseTexture = this.baseTexture; baseTexture.removeEventListener('loaded', this.onLoaded); - if (this.noFrame) { + if (this.noFrame) + { this.frame = new math.Rectangle(0, 0, baseTexture.width, baseTexture.height); } @@ -184,8 +199,10 @@ * * @param destroyBase {boolean} Whether to destroy the base texture as well */ -Texture.prototype.destroy = function (destroyBase) { - if (destroyBase) { +Texture.prototype.destroy = function (destroyBase) +{ + if (destroyBase) + { this.baseTexture.destroy(); } @@ -197,8 +214,10 @@ * * @private */ -Texture.prototype._updateUvs = function () { - if (!this._uvs) { +Texture.prototype._updateUvs = function () +{ + if (!this._uvs) + { this._uvs = new TextureUvs(); } @@ -229,10 +248,12 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return Texture */ -Texture.fromImage = function (imageUrl, crossorigin, scaleMode) { +Texture.fromImage = function (imageUrl, crossorigin, scaleMode) +{ var texture = utils.TextureCache[imageUrl]; - if (!texture) { + if (!texture) + { texture = new Texture(BaseTexture.fromImage(imageUrl, crossorigin, scaleMode)); utils.TextureCache[imageUrl] = texture; } @@ -248,9 +269,11 @@ * @param frameId {string} The frame id of the texture * @return Texture */ -Texture.fromFrame = function (frameId) { +Texture.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache '); } return texture; @@ -264,7 +287,8 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return {Texture} */ -Texture.fromCanvas = function (canvas, scaleMode) { +Texture.fromCanvas = function (canvas, scaleMode) +{ return new Texture(BaseTexture.fromCanvas(canvas, scaleMode)); }; @@ -276,7 +300,8 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return {Texture} A Texture */ -Texture.fromVideo = function (video, scaleMode) { +Texture.fromVideo = function (video, scaleMode) +{ return new Texture(VideoBaseTexture.baseTextureFromVideo(video, scaleMode)); }; @@ -287,7 +312,8 @@ * @param texture {Texture} The Texture to add to the cache. * @param id {string} The id that the texture will be stored against. */ -Texture.addTextureToCache = function (texture, id) { +Texture.addTextureToCache = function (texture, id) +{ utils.TextureCache[id] = texture; }; @@ -298,7 +324,8 @@ * @param id {string} The id of the texture to be removed * @return {Texture} The texture that was removed */ -Texture.removeTextureFromCache = function (id) { +Texture.removeTextureFromCache = function (id) +{ var texture = utils.TextureCache[id]; delete utils.TextureCache[id]; diff --git a/src/core/textures/TextureUvs.js b/src/core/textures/TextureUvs.js index b9bbb58..5424d52 100644 --- a/src/core/textures/TextureUvs.js +++ b/src/core/textures/TextureUvs.js @@ -1,4 +1,5 @@ -function TextureUvs() { +function TextureUvs() +{ this.x0 = 0; this.y0 = 0; diff --git a/src/core/textures/VideoBaseTexture.js b/src/core/textures/VideoBaseTexture.js index e3e0c5a..1a826a9 100644 --- a/src/core/textures/VideoBaseTexture.js +++ b/src/core/textures/VideoBaseTexture.js @@ -12,15 +12,18 @@ * @param source {HTMLVideoElement} * @param [scaleMode] {number} See {@link scaleModes} for possible values */ -function VideoBaseTexture(source, scaleMode) { - if (!source){ +function VideoBaseTexture(source, scaleMode) +{ + if (!source) + { throw new Error('No video source element specified.'); } // hook in here to check if video is already available. // BaseTexture looks for a source.complete boolean, plus width & height. - if ((source.readyState === source.HAVE_ENOUGH_DATA || source.readyState === source.HAVE_FUTURE_DATA) && source.width && source.height) { + if ((source.readyState === source.HAVE_ENOUGH_DATA || source.readyState === source.HAVE_FUTURE_DATA) && source.width && source.height) + { source.complete = true; } @@ -31,7 +34,8 @@ this._boundOnUpdate = this._onUpdate.bind(this); this._boundOnCanPlay = this._onCanPlay.bind(this); - if (!source.complete) { + if (!source.complete) + { source.addEventListener('canplay', this._boundOnCanPlay); source.addEventListener('canplaythrough', this._boundOnCanPlay); @@ -47,28 +51,35 @@ VideoBaseTexture.prototype.constructor = VideoBaseTexture; module.exports = VideoBaseTexture; -VideoBaseTexture.prototype._onUpdate = function () { - if (this.autoUpdate) { +VideoBaseTexture.prototype._onUpdate = function () +{ + if (this.autoUpdate) + { window.requestAnimationFrame(this._boundOnUpdate); this.needsUpdate = true; } }; -VideoBaseTexture.prototype._onPlayStart = function () { - if (!this.autoUpdate) { +VideoBaseTexture.prototype._onPlayStart = function () +{ + if (!this.autoUpdate) + { window.requestAnimationFrame(this._boundOnUpdate); this.autoUpdate = true; } }; -VideoBaseTexture.prototype._onPlayStop = function () { +VideoBaseTexture.prototype._onPlayStop = function () +{ this.autoUpdate = false; }; -VideoBaseTexture.prototype._onCanPlay = function () { +VideoBaseTexture.prototype._onCanPlay = function () +{ this.hasLoaded = true; - if (this.source) { + if (this.source) + { this.source.removeEventListener('canplay', this._boundOnCanPlay); this.source.removeEventListener('canplaythrough', this._boundOnCanPlay); @@ -78,15 +89,18 @@ this.source.play(); // prevent multiple loaded dispatches.. - if(!this.__loaded){ + if(!this.__loaded) + { this.__loaded = true; this.emit('loaded', this); } } }; -VideoBaseTexture.prototype.destroy = function () { - if (this.source && this.source._pixiId) { +VideoBaseTexture.prototype.destroy = function () +{ + if (this.source && this.source._pixiId) + { utils.BaseTextureCache[ this.source._pixiId ] = null; delete utils.BaseTextureCache[ this.source._pixiId ]; @@ -105,14 +119,17 @@ * @param scaleMode {number} See {@link scaleModes} for possible values * @return {VideoBaseTexture} */ -VideoBaseTexture.fromVideo = function (video, scaleMode) { - if (!video._pixiId) { +VideoBaseTexture.fromVideo = function (video, scaleMode) +{ + if (!video._pixiId) + { video._pixiId = 'video_' + utils.uuid(); } var baseTexture = utils.BaseTextureCache[video._pixiId]; - if (!baseTexture) { + if (!baseTexture) + { baseTexture = new VideoBaseTexture(video, scaleMode); utils.BaseTextureCache[ video._pixiId ] = baseTexture; } @@ -147,17 +164,21 @@ * @param scaleMode {number} See {@link scaleModes} for possible values * @return {VideoBaseTexture} */ -VideoBaseTexture.fromUrl = function (videoSrc, scaleMode) { +VideoBaseTexture.fromUrl = function (videoSrc, scaleMode) +{ var video = document.createElement('video'); // array of objects or strings - if (Array.isArray(videoSrc)) { - for (var i = 0; i < videoSrc.length; ++i) { + if (Array.isArray(videoSrc)) + { + for (var i = 0; i < videoSrc.length; ++i) + { video.appendChild(createSource(videoSrc.src || videoSrc, videoSrc.mime)); } } // single object or string - else { + else + { video.appendChild(createSource(videoSrc.src || videoSrc, videoSrc.mime)); } @@ -169,8 +190,10 @@ VideoBaseTexture.fromUrls = VideoBaseTexture.fromUrl; -function createSource(path, type) { - if (!type) { +function createSource(path, type) +{ + if (!type) + { type = 'video/' + path.substr(path.lastIndexOf('.') + 1); } diff --git a/src/core/utils/EventData.js b/src/core/utils/EventData.js index 5d55a22..8cdf701 100644 --- a/src/core/utils/EventData.js +++ b/src/core/utils/EventData.js @@ -7,7 +7,8 @@ * @param name {string} The string name of the event that was triggered * @param data {object} Arbitrary event data to pass along */ -function EventData(target, name, data) { +function EventData(target, name, data) +{ // for duck typing in the ".on()" function this.__isEventObject = true; @@ -71,7 +72,8 @@ * Stops the propagation of events up the scene graph (prevents bubbling). * */ -EventData.prototype.stopPropagation = function stopPropagation() { +EventData.prototype.stopPropagation = function stopPropagation() +{ this.stopped = true; }; @@ -79,6 +81,7 @@ * Stops the propagation of events to sibling listeners (no longer calls any listeners). * */ -EventData.prototype.stopImmediatePropagation = function stopImmediatePropagation() { +EventData.prototype.stopImmediatePropagation = function stopImmediatePropagation() +{ this.stoppedImmediate = true; }; diff --git a/src/core/utils/EventTarget.js b/src/core/utils/EventTarget.js index 7ae8820..671a151 100644 --- a/src/core/utils/EventTarget.js +++ b/src/core/utils/EventTarget.js @@ -13,14 +13,16 @@ * var em = new MyEmitter(); * em.emit('eventName', 'some data', 'some more data', {}, null, ...); */ -function eventTarget(obj) { +function eventTarget(obj) +{ /** * Return a list of assigned event listeners. * * @param eventName {string} The events that should be listed. * @return {Array} An array of listener functions */ - obj.listeners = function listeners(eventName) { + obj.listeners = function listeners(eventName) + { this._listeners = this._listeners || {}; return this._listeners[eventName] ? this._listeners[eventName].slice() : []; @@ -33,22 +35,26 @@ * @param eventName {string} The name of the event. * @return {boolean} Indication if we've emitted an event. */ - obj.emit = obj.dispatchEvent = function emit(eventName, data) { + obj.emit = obj.dispatchEvent = function emit(eventName, data) + { this._listeners = this._listeners || {}; // fast return when there are no listeners - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return; } //backwards compat with old method ".emit({ type: 'something' })" - if (typeof eventName === 'object') { + if (typeof eventName === 'object') + { data = eventName; eventName = eventName.type; } //ensure we are using a real pixi event - if (!data || data.__isEventObject !== true) { + if (!data || data.__isEventObject !== true) + { data = new EventData(this, eventName, data); } @@ -58,23 +64,27 @@ fn = listeners[0], i; - for (i = 0; i < length; fn = listeners[++i]) { + for (i = 0; i < length; fn = listeners[++i]) + { //call the event listener fn.call(this, data); //if "stopImmediatePropagation" is called, stop calling sibling events - if (data.stoppedImmediate) { + if (data.stoppedImmediate) + { return this; } } //if "stopPropagation" is called then don't bubble the event - if (data.stopped) { + if (data.stopped) + { return this; } //bubble this event up the scene graph - if (this.parent && this.parent.emit) { + if (this.parent && this.parent.emit) + { this.parent.emit.call(this.parent, eventName, data); } @@ -88,7 +98,8 @@ * @param eventName {string} Name of the event. * @param callback {Functon} fn Callback function. */ - obj.on = obj.addEventListener = function on(eventName, fn) { + obj.on = obj.addEventListener = function on(eventName, fn) + { this._listeners = this._listeners || {}; (this._listeners[eventName] = this._listeners[eventName] || []) @@ -103,11 +114,13 @@ * @param eventName {string} Name of the event. * @param callback {Function} Callback function. */ - obj.once = function once(eventName, fn) { + obj.once = function once(eventName, fn) + { this._listeners = this._listeners || {}; var self = this; - function onceHandlerWrapper() { + function onceHandlerWrapper() + { fn.apply(self.off(eventName, onceHandlerWrapper), arguments); } onceHandlerWrapper._originalHandler = fn; @@ -122,23 +135,28 @@ * @param eventName {string} The event we want to remove. * @param callback {Function} The listener that we need to find. */ - obj.off = obj.removeEventListener = function off(eventName, fn) { + obj.off = obj.removeEventListener = function off(eventName, fn) + { this._listeners = this._listeners || {}; - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return this; } var list = this._listeners[eventName], i = fn ? list.length : 0; - while(i-- > 0) { - if (list[i] === fn || list[i]._originalHandler === fn) { + while(i-- > 0) + { + if (list[i] === fn || list[i]._originalHandler === fn) + { list.splice(i, 1); } } - if (list.length === 0) { + if (list.length === 0) + { delete this._listeners[eventName]; } @@ -150,10 +168,12 @@ * * @param eventName {string} The event you want to remove all listeners for. */ - obj.removeAllListeners = function removeAllListeners(eventName) { + obj.removeAllListeners = function removeAllListeners(eventName) + { this._listeners = this._listeners || {}; - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return this; } @@ -169,7 +189,8 @@ * * @param object {object} The obj to mix into */ - mixin: function mixin(obj) { + mixin: function mixin(obj) + { eventTarget(obj); } }; diff --git a/src/core/utils/PolyK.js b/src/core/utils/PolyK.js index 7325141..5e20c2b 100644 --- a/src/core/utils/PolyK.js +++ b/src/core/utils/PolyK.js @@ -47,7 +47,8 @@ * Triangulates shapes for webGL graphic fills. * */ -PolyK.Triangulate = function (p) { +PolyK.Triangulate = function (p) +{ var sign = true; var n = p.length >> 1; @@ -59,7 +60,8 @@ i = 0; var al = n; - while(al > 3) { + while(al > 3) + { var i0 = avl[(i+0)%al]; var i1 = avl[(i+1)%al]; var i2 = avl[(i+2)%al]; @@ -69,29 +71,35 @@ var cx = p[2*i2], cy = p[2*i2+1]; var earFound = false; - if (PolyK._convex(ax, ay, bx, by, cx, cy, sign)) { + if (PolyK._convex(ax, ay, bx, by, cx, cy, sign)) + { earFound = true; - for (var j = 0; j < al; j++) { + for (var j = 0; j < al; j++) + { var vi = avl[j]; if (vi === i0 || vi === i1 || vi === i2) continue; - if (PolyK._PointInTriangle(p[2*vi], p[2*vi+1], ax, ay, bx, by, cx, cy)) { + if (PolyK._PointInTriangle(p[2*vi], p[2*vi+1], ax, ay, bx, by, cx, cy)) + { earFound = false; break; } } } - if (earFound) { + if (earFound) + { tgs.push(i0, i1, i2); avl.splice((i+1)%al, 1); al--; i = 0; } - else if (i++ > 3*al) { + else if (i++ > 3*al) + { // need to flip flip reverse it! // reset! - if (sign) { + if (sign) + { tgs = []; avl = []; for (i = 0; i < n; i++) avl.push(i); @@ -101,7 +109,8 @@ sign = false; } - else { + else + { // window.console.log("PIXI Warning: shape too complex to fill"); return null; } @@ -126,7 +135,8 @@ * @private * @return {boolean} */ -PolyK._PointInTriangle = function (px, py, ax, ay, bx, by, cx, cy) { +PolyK._PointInTriangle = function (px, py, ax, ay, bx, by, cx, cy) +{ var v0x = cx-ax; var v0y = cy-ay; var v1x = bx-ax; @@ -154,6 +164,7 @@ * @private * @return {boolean} */ -PolyK._convex = function (ax, ay, bx, by, cx, cy, sign) { +PolyK._convex = function (ax, ay, bx, by, cx, cy, sign) +{ return ((ay-by)*(cx-bx) + (bx-ax)*(cy-by) >= 0) === sign; }; diff --git a/src/core/utils/index.js b/src/core/utils/index.js index ade9831..bfae7ae 100644 --- a/src/core/utils/index.js +++ b/src/core/utils/index.js @@ -16,7 +16,8 @@ * * @return {number} The next uuid to use. */ - uuid: function () { + uuid: function () + { return ++utils._uid; }, @@ -26,7 +27,8 @@ * @param hex {number} * @return {number[]} An array representing the [R, G, B] of the color. */ - hex2rgb: function (hex, out) { + hex2rgb: function (hex, out) + { out = out || []; out[0] = (hex >> 16 & 0xFF) / 255; @@ -42,7 +44,8 @@ * @param hex {number} * @return {string} The string color. */ - hex2string: function (hex) { + hex2string: function (hex) + { hex = hex.toString(16); hex = '000000'.substr(0, 6 - hex.length) + hex; @@ -55,7 +58,8 @@ * @param rgb {number[]} * @return {number} The color number */ - rgb2hex: function (rgb) { + rgb2hex: function (rgb) + { return ((rgb[0]*255 << 16) + (rgb[1]*255 << 8) + rgb[2]*255); }, @@ -64,8 +68,10 @@ * * @return {boolean} whether they are supported */ - canUseNewCanvasBlendModes: function () { - if (typeof document === 'undefined') { + canUseNewCanvasBlendModes: function () + { + if (typeof document === 'undefined') + { return false; } @@ -93,15 +99,19 @@ * @param number {number} * @return {number} the closest number that is a power of two */ - getNextPowerOfTwo: function (number) { + getNextPowerOfTwo: function (number) + { // see: http://en.wikipedia.org/wiki/Power_of_two#Fast_algorithm_to_check_if_a_positive_number_is_a_power_of_two - if (number > 0 && (number & (number - 1)) === 0) { + if (number > 0 && (number & (number - 1)) === 0) + { return number; } - else { + else + { var result = 1; - while (result < number) { + while (result < number) + { result <<= 1; } @@ -116,7 +126,8 @@ * @param height {number} * @return {boolean} */ - isPowerOfTwo: function (width, height) { + isPowerOfTwo: function (width, height) + { return (width > 0 && (width & (width - 1)) === 0 && height > 0 && (height & (height - 1)) === 0); }, @@ -130,12 +141,15 @@ * @constant * @static */ - sayHello: function (type) { - if (utils._saidHello) { + sayHello: function (type) + { + if (utils._saidHello) + { return; } - if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) { + if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) + { var args = [ '%c %c %c Pixi.js ' + CONST.VERSION + ' - ' + type + ' %c ' + ' %c ' + ' http://www.pixijs.com/ %c %c ♥%c♥%c♥ ', 'background: #ff66a5', @@ -151,7 +165,8 @@ console.log.apply(console, args); //jshint ignore:line } - else if (window.console) { + else if (window.console) + { console.log('Pixi.js ' + CONST.VERSION + ' - ' + type + ' - http://www.pixijs.com/'); //jshint ignore:line } @@ -166,15 +181,19 @@ * @class * @namespace PIXI */ - AjaxRequest: function () { + AjaxRequest: function () + { var activexmodes = ['Msxml2.XMLHTTP.6.0', 'Msxml2.XMLHTTP.3.0', 'Microsoft.XMLHTTP']; //activeX versions to check for in IE - if (window.ActiveXObject) { //Test for support for ActiveXObject in IE first (as XMLHttpRequest in IE7 is broken) - for (var i=0; i= this.textures.length) { + else if (round >= this.textures.length) + { this.gotoAndStop(this.textures.length - 1); - if (this.onComplete) { + if (this.onComplete) + { this.onComplete(); } } @@ -167,10 +182,12 @@ * @static * @param frames {string[]} the array of frames ids the movieclip will use as its texture frames */ -MovieClip.fromFrames = function (frames) { +MovieClip.fromFrames = function (frames) +{ var textures = []; - for (var i = 0; i < frames.length; ++i) { + for (var i = 0; i < frames.length; ++i) + { textures.push(new core.Texture.fromFrame(frames[i])); } @@ -183,10 +200,12 @@ * @static * @param images {string[]} the array of image urls the movieclip will use as its texture frames */ -MovieClip.fromImages = function (images) { +MovieClip.fromImages = function (images) +{ var textures = []; - for (var i = 0; i < images.length; ++i) { + for (var i = 0; i < images.length; ++i) + { textures.push(new core.Texture.fromImage(images[i])); } diff --git a/src/extras/Rope.js b/src/extras/Rope.js index c157ec4..9c87bc0 100644 --- a/src/extras/Rope.js +++ b/src/extras/Rope.js @@ -9,7 +9,8 @@ * @param {Array} points - An array of {Point}. * */ -function Rope(texture, points) { +function Rope(texture, points) +{ Strip.call(this, texture); this.points = points; @@ -31,10 +32,12 @@ * Refreshes * */ -Rope.prototype.refresh = function () { +Rope.prototype.refresh = function () +{ var points = this.points; - if (points.length < 1) { + if (points.length < 1) + { return; } @@ -59,20 +62,23 @@ var total = points.length, point, index, amount; - for (var i = 1; i < total; i++) { + for (var i = 1; i < total; i++) + { point = points[i]; index = i * 4; // time to do some smart drawing! amount = i / (total-1); - if (i%2) { + if (i%2) + { uvs[index] = amount; uvs[index+1] = 0; uvs[index+2] = amount; uvs[index+3] = 1; } - else { + else + { uvs[index] = amount; uvs[index+1] = 0; @@ -95,10 +101,12 @@ * * @private */ -Rope.prototype.updateTransform = function () { +Rope.prototype.updateTransform = function () +{ var points = this.points; - if (points.length < 1) { + if (points.length < 1) + { return; } @@ -113,14 +121,17 @@ var total = points.length, point, index, ratio, perpLength, num; - for (var i = 0; i < total; i++) { + for (var i = 0; i < total; i++) + { point = points[i]; index = i * 4; - if (i < points.length-1) { + if (i < points.length-1) + { nextPoint = points[i+1]; } - else { + else + { nextPoint = point; } @@ -129,7 +140,8 @@ ratio = (1 - (i / (total-1))) * 10; - if (ratio > 1) { + if (ratio > 1) + { ratio = 1; } @@ -157,7 +169,8 @@ * * @param texture {Texture} the texture that will be used */ -Rope.prototype.setTexture = function (texture) { +Rope.prototype.setTexture = function (texture) +{ // stop current texture this.texture = texture; //this.updateFrame = true; diff --git a/src/extras/Strip.js b/src/extras/Strip.js index c5e378f..57691b5 100644 --- a/src/extras/Strip.js +++ b/src/extras/Strip.js @@ -10,7 +10,8 @@ * @param height {number} the height * */ -function Strip(texture) { +function Strip(texture) +{ core.DisplayObjectContainer.call(this); /** @@ -70,9 +71,11 @@ * * @param renderer {WebGLRenderer} */ -Strip.prototype.renderWebGL = function (renderer) { +Strip.prototype.renderWebGL = function (renderer) +{ // if the sprite is not visible or the alpha is 0 then no need to render this element - if (!this.visible || this.alpha <= 0) { + if (!this.visible || this.alpha <= 0) + { return; } @@ -81,7 +84,8 @@ renderer.spriteBatch.stop(); // init! init! - if (!this._vertexBuffer) { + if (!this._vertexBuffer) + { this._initWebGL(renderer); } @@ -96,7 +100,8 @@ //TODO check culling }; -Strip.prototype._initWebGL = function (renderer) { +Strip.prototype._initWebGL = function (renderer) +{ // build the strip! var gl = renderer.gl; @@ -118,7 +123,8 @@ gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this.indices, gl.STATIC_DRAW); }; -Strip.prototype._renderStrip = function (renderer) { +Strip.prototype._renderStrip = function (renderer) +{ var gl = renderer.gl; var projection = renderer.projection, offset = renderer.offset, @@ -137,7 +143,8 @@ gl.uniform2f(shader.offsetVector, -offset.x, -offset.y); gl.uniform1f(shader.alpha, this.worldAlpha); - if (!this.dirty) { + if (!this.dirty) + { gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexBuffer); gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); @@ -150,10 +157,12 @@ gl.activeTexture(gl.TEXTURE0); // check if a texture is dirty.. - if (this.texture.baseTexture._dirty[gl.id]) { + if (this.texture.baseTexture._dirty[gl.id]) + { renderer.updateTexture(this.texture.baseTexture); } - else { + else + { // bind the current texture gl.bindTexture(gl.TEXTURE_2D, this.texture.baseTexture._glTextures[gl.id]); } @@ -163,7 +172,8 @@ } - else { + else + { this.dirty = false; gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexBuffer); @@ -178,10 +188,12 @@ gl.activeTexture(gl.TEXTURE0); // check if a texture is dirty.. - if (this.texture.baseTexture._dirty[gl.id]) { + if (this.texture.baseTexture._dirty[gl.id]) + { renderer.updateTexture(this.texture.baseTexture); } - else { + else + { gl.bindTexture(gl.TEXTURE_2D, this.texture.baseTexture._glTextures[gl.id]); } @@ -203,27 +215,33 @@ * * @param renderer {CanvasRenderer} */ -Strip.prototype.renderCanvas = function (renderer) { +Strip.prototype.renderCanvas = function (renderer) +{ var context = renderer.context; var transform = this.worldTransform; - if (renderer.roundPixels) { + if (renderer.roundPixels) + { context.setTransform(transform.a, transform.b, transform.c, transform.d, transform.tx | 0, transform.ty | 0); } - else { + else + { context.setTransform(transform.a, transform.b, transform.c, transform.d, transform.tx, transform.ty); } - if (this.drawMode === Strip.DrawModes.TRIANGLE_STRIP) { + if (this.drawMode === Strip.DrawModes.TRIANGLE_STRIP) + { this._renderCanvasTriangleStrip(context); } - else { + else + { this._renderCanvasTriangles(context); } }; -Strip.prototype._renderCanvasTriangleStrip = function (context) { +Strip.prototype._renderCanvasTriangleStrip = function (context) +{ // draw triangles!! var vertices = this.vertices; var uvs = this.uvs; @@ -231,14 +249,16 @@ var length = vertices.length / 2; // this.count++; - for (var i = 0; i < length - 2; i++) { + for (var i = 0; i < length - 2; i++) + { // draw some triangles! var index = i * 2; this._renderCanvasDrawTriangle(context, vertices, uvs, index, (index + 2), (index + 4)); } }; -Strip.prototype._renderCanvasTriangles = function (context) { +Strip.prototype._renderCanvasTriangles = function (context) +{ // draw triangles!! var vertices = this.vertices; var uvs = this.uvs; @@ -247,14 +267,16 @@ var length = indices.length; // this.count++; - for (var i = 0; i < length; i += 3) { + for (var i = 0; i < length; i += 3) + { // draw some triangles! var index0 = indices[i] * 2, index1 = indices[i + 1] * 2, index2 = indices[i + 2] * 2; this._renderCanvasDrawTriangle(context, vertices, uvs, index0, index1, index2); } }; -Strip.prototype._renderCanvasDrawTriangle = function (context, vertices, uvs, index0, index1, index2) { +Strip.prototype._renderCanvasDrawTriangle = function (context, vertices, uvs, index0, index1, index2) +{ var textureSource = this.texture.baseTexture.source; var textureWidth = this.texture.width; var textureHeight = this.texture.height; @@ -265,7 +287,8 @@ var u0 = uvs[index0] * textureWidth, u1 = uvs[index1] * textureWidth, u2 = uvs[index2] * textureWidth; var v0 = uvs[index0 + 1] * textureHeight, v1 = uvs[index1 + 1] * textureHeight, v2 = uvs[index2 + 1] * textureHeight; - if (this.canvasPadding > 0) { + if (this.canvasPadding > 0) + { var paddingX = this.canvasPadding / this.worldTransform.a; var paddingY = this.canvasPadding / this.worldTransform.d; var centerX = (x0 + x1 + x2) / 3; @@ -332,7 +355,8 @@ * @param strip {Strip} The Strip to render * @private */ -Strip.prototype.renderStripFlat = function (strip) { +Strip.prototype.renderStripFlat = function (strip) +{ var context = this.context; var vertices = strip.vertices; @@ -340,7 +364,8 @@ // this.count++; context.beginPath(); - for (var i=1; i < length-2; i++) { + for (var i=1; i < length-2; i++) + { // draw some triangles! var index = i*2; @@ -358,7 +383,8 @@ }; /* -Strip.prototype.setTexture = function (texture) { +Strip.prototype.setTexture = function (texture) +{ //TODO SET THE TEXTURES //TODO VISIBILITY @@ -377,7 +403,8 @@ * @private */ -Strip.prototype.onTextureUpdate = function () { +Strip.prototype.onTextureUpdate = function () +{ this.updateFrame = true; }; @@ -387,7 +414,8 @@ * @param matrix {Matrix} the transformation matrix of the sprite * @return {Rectangle} the framing rectangle */ -Strip.prototype.getBounds = function (matrix) { +Strip.prototype.getBounds = function (matrix) +{ var worldTransform = matrix || this.worldTransform; var a = worldTransform.a; @@ -404,7 +432,8 @@ var minY = Infinity; var vertices = this.vertices; - for (var i = 0, n = vertices.length; i < n; i += 2) { + for (var i = 0, n = vertices.length; i < n; i += 2) + { var rawX = vertices[i], rawY = vertices[i + 1]; var x = (a * rawX) + (c * rawY) + tx; var y = (d * rawY) + (b * rawX) + ty; @@ -416,7 +445,8 @@ maxY = y > maxY ? y : maxY; } - if (minX === -Infinity || maxY === Infinity) { + if (minX === -Infinity || maxY === Infinity) + { return core.math.Rectangle.EMPTY; } diff --git a/src/extras/TilingSprite.js b/src/extras/TilingSprite.js index 3ac22df..31da393 100644 --- a/src/extras/TilingSprite.js +++ b/src/extras/TilingSprite.js @@ -10,7 +10,8 @@ * @param width {number} the width of the tiling sprite * @param height {number} the height of the tiling sprite */ -function TilingSprite(texture, width, height) { +function TilingSprite(texture, width, height) +{ core.Sprite.call( this, texture); /** @@ -86,10 +87,12 @@ * @memberof TilingSprite# */ width: { - get: function () { + get: function () + { return this._width; }, - set: function (value) { + set: function (value) + { this._width = value; } }, @@ -101,20 +104,25 @@ * @memberof TilingSprite# */ height: { - get: function () { + get: function () + { return this._height; }, - set: function (value) { + set: function (value) + { this._height = value; } }, texture: { - get: function () { + get: function () + { return this._texture; }, - set: function (value) { - if (this._texture === value) { + set: function (value) + { + if (this._texture === value) + { return; } @@ -130,51 +138,61 @@ * * @param renderer {WebGLRenderer} */ -TilingSprite.prototype.renderWebGL = function (renderer) { - if (!this.visible || this.alpha <= 0) { +TilingSprite.prototype.renderWebGL = function (renderer) +{ + if (!this.visible || this.alpha <= 0) + { return; } var i, j; - if (this._mask) { + if (this._mask) + { renderer.spriteBatch.stop(); renderer.maskManager.pushMask(this.mask, renderer); renderer.spriteBatch.start(); } - if (this._filters) { + if (this._filters) + { renderer.spriteBatch.flush(); renderer.filterManager.pushFilter(this._filterBlock); } - if (!this.tilingTexture || this.refreshTexture) { + if (!this.tilingTexture || this.refreshTexture) + { this.generateTilingTexture(true); - if (this.tilingTexture && this.tilingTexture.needsUpdate) { + if (this.tilingTexture && this.tilingTexture.needsUpdate) + { //TODO - tweaking renderer.updateTexture(this.tilingTexture.baseTexture); this.tilingTexture.needsUpdate = false; // this.tilingTexture._uvs = null; } } - else { + else + { renderer.spriteBatch.renderTilingSprite(this); } // simple render children! - for (i=0,j=this.children.length; i= 0 && index <= this.children.length) { - if (child.parent) { + if (index >= 0 && index <= this.children.length) + { + if (child.parent) + { child.parent.removeChild(child); } @@ -154,7 +173,8 @@ return child; } - else { + else + { throw new Error(child + 'addChildAt: The index '+ index +' supplied is out of bounds ' + this.children.length); } }; @@ -165,15 +185,18 @@ * @param child {DisplayObject} * @param child2 {DisplayObject} */ -DisplayObjectContainer.prototype.swapChildren = function (child, child2) { - if (child === child2) { +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) { + if (index1 < 0 || index2 < 0) + { throw new Error('swapChildren: Both the supplied DisplayObjects must be a child of the caller.'); } @@ -187,10 +210,12 @@ * @param child {DisplayObject} The DisplayObject instance to identify * @return {Number} The index position of the child display object to identify */ -DisplayObjectContainer.prototype.getChildIndex = function (child) { +DisplayObjectContainer.prototype.getChildIndex = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { throw new Error('The supplied DisplayObject must be a child of the caller'); } @@ -203,8 +228,10 @@ * @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 */ -DisplayObjectContainer.prototype.setChildIndex = function (child, index) { - if (index < 0 || index >= this.children.length) { +DisplayObjectContainer.prototype.setChildIndex = function (child, index) +{ + if (index < 0 || index >= this.children.length) + { throw new Error('The supplied index is out of bounds'); } @@ -220,8 +247,10 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child at the given index, if any. */ -DisplayObjectContainer.prototype.getChildAt = function (index) { - if (index < 0 || index >= this.children.length) { +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'); } @@ -234,10 +263,12 @@ * @param child {DisplayObject} The DisplayObject to remove * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChild = function (child) { +DisplayObjectContainer.prototype.removeChild = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { return; } @@ -250,7 +281,8 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChildAt = function (index) { +DisplayObjectContainer.prototype.removeChildAt = function (index) +{ var child = this.getChildAt(index); child.parent = null; @@ -265,24 +297,29 @@ * @param beginIndex {Number} The beginning position. Default value is 0. * @param endIndex {Number} The ending position. Default value is size of the container. */ -DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) { +DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) +{ var begin = beginIndex || 0; var end = typeof endIndex === 'number' ? endIndex : this.children.length; var range = end - begin; - if (range > 0 && range <= end) { + if (range > 0 && range <= end) + { var removed = this.children.splice(begin, range); - for (var i = 0; i < removed.length; ++i) { + for (var i = 0; i < removed.length; ++i) + { removed[i].parent = null; } return removed; } - else if (range === 0 && this.children.length === 0) { + else if (range === 0 && this.children.length === 0) + { return []; } - else { + else + { throw new RangeError('removeChildren: numeric values are outside the acceptable range.'); } }; @@ -291,7 +328,8 @@ * Generates and updates the cached sprite for this object. * */ -DisplayObjectContainer.prototype.updateCachedSprite = function () { +DisplayObjectContainer.prototype.updateCachedSprite = function () +{ this._generateCachedSprite(); }; @@ -304,7 +342,8 @@ * @param renderer {CanvasRenderer|WebGLRenderer} The renderer used to generate the texture. * @return {Texture} a texture of the graphics object */ -DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) { +DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) +{ var bounds = this.getLocalBounds(); var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0, renderer, scaleMode, resolution); @@ -322,18 +361,22 @@ * * @private */ -DisplayObjectContainer.prototype.updateTransform = function () { - if (!this.visible) { +DisplayObjectContainer.prototype.updateTransform = function () +{ + if (!this.visible) + { return; } this.displayObjectUpdateTransform(); - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { return; } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } }; @@ -346,8 +389,10 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getBounds = function () { - if (this.children.length === 0) { +DisplayObjectContainer.prototype.getBounds = function () +{ + if (this.children.length === 0) + { return math.Rectangle.EMPTY; } @@ -365,10 +410,12 @@ var childVisible = false; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -386,7 +433,8 @@ maxY = maxY > childMaxY ? maxY : childMaxY; } - if (!childVisible) { + if (!childVisible) + { return math.Rectangle.EMPTY; } @@ -407,12 +455,14 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getLocalBounds = function () { +DisplayObjectContainer.prototype.getLocalBounds = function () +{ var matrixCache = this.worldTransform; this.worldTransform = math.Matrix.IDENTITY; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } @@ -428,13 +478,16 @@ * * @param renderer {WebGLRenderer} The renderer */ -DisplayObjectContainer.prototype.renderWebGL = function (renderer) { +DisplayObjectContainer.prototype.renderWebGL = function (renderer) +{ // if the object is not visible or the alpha is 0 then no need to render this element - if (!this.visible || this.alpha <= 0) { + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } @@ -442,14 +495,17 @@ var i, j; // do a quick check to see if this element has a mask or a filter. - if (this._mask || this._filters) { + if (this._mask || this._filters) + { // push filter first as we need to ensure the stencil buffer is correct for any masking - if (this._filters) { + if (this._filters) + { renderer.spriteBatch.flush(); renderer.filterManager.pushFilter(this._filterBlock); } - if (this._mask) { + if (this._mask) + { renderer.spriteBatch.stop(); renderer.maskManager.pushMask(this.mask, renderer); renderer.spriteBatch.start(); @@ -459,36 +515,42 @@ this._renderWebGL(renderer); // now loop through the children and make sure they get rendered - for (i = 0, j = this.children.length; i < j; i++) { + for (i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderWebGL(renderer); } // time to stop the sprite batch as either a mask element or a filter draw will happen next renderer.spriteBatch.stop(); - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(this._mask, renderer); } - if (this._filters) { + if (this._filters) + { renderer.filterManager.popFilter(); } renderer.spriteBatch.start(); } - else { + else + { this._renderWebGL(renderer); // simple render children! - for (i = 0, j = this.children.length; i < j; ++i) { + for (i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderWebGL(renderer); } } }; -DisplayObjectContainer.prototype._renderWebGL = function (renderer) { +DisplayObjectContainer.prototype._renderWebGL = function (renderer) +{ // this is where content itself gets renderd.. @@ -499,25 +561,31 @@ * * @param renderer {CanvasRenderer} The renderer */ -DisplayObjectContainer.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0) { +DisplayObjectContainer.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -528,13 +596,16 @@ * @param renderer {WebGLRenderer|CanvasRenderer} The renderer * @private */ -DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) { +DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) +{ this._cachedSprite.worldAlpha = this.worldAlpha; - if (renderer.gl) { + if (renderer.gl) + { this._cachedSprite.renderWebGL(renderer); } - else { + else + { this._cachedSprite.renderCanvas(renderer); } }; @@ -544,10 +615,12 @@ * * @private */ -DisplayObjectContainer.prototype._generateCachedSprite = function () { +DisplayObjectContainer.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { // TODO - RenderTexture now *requires* a renderer instance, so this is like broken // because `renderer` isn't actually in scope here :P var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0); @@ -555,7 +628,8 @@ this._cachedSprite = new Sprite(renderTexture); this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.texture.resize(bounds.width | 0, bounds.height | 0); } @@ -580,8 +654,10 @@ * * @private */ -DisplayObjectContainer.prototype._destroyCachedSprite = function () { - if (!this._cachedSprite) { +DisplayObjectContainer.prototype._destroyCachedSprite = function () +{ + if (!this._cachedSprite) + { return; } diff --git a/src/core/display/Sprite.js b/src/core/display/Sprite.js index 707da24..5862aef 100644 --- a/src/core/display/Sprite.js +++ b/src/core/display/Sprite.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param texture {Texture} The texture for this sprite */ -function Sprite(texture) { +function Sprite(texture) +{ DisplayObjectContainer.call(this); /** @@ -85,12 +86,14 @@ this.texture = texture || Texture.EMPTY; } -Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) { +Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) +{ DisplayObjectContainer.prototype.destroy.call(this); this.anchor = null; - if (destroyTexture) { + if (destroyTexture) + { this._texture.destroy(destroyBaseTexture); } @@ -111,10 +114,12 @@ * @memberof Sprite# */ width: { - get: function () { + get: function () + { return this.scale.x * this.texture.frame.width; }, - set: function (value) { + set: function (value) + { this.scale.x = value / this.texture.frame.width; this._width = value; } @@ -127,10 +132,12 @@ * @memberof Sprite# */ height: { - get: function () { + get: function () + { return this.scale.y * this.texture.frame.height; }, - set: function (value) { + set: function (value) + { this.scale.y = value / this.texture.frame.height; this._height = value; } @@ -143,23 +150,29 @@ * @memberof Sprite# */ texture: { - get: function () { + get: function () + { return this._texture; }, - set: function (value) { - if (this._texture === value) { + set: function (value) + { + if (this._texture === value) + { return; } this._texture = value; this.cachedTint = 0xFFFFFF; - if (value) { + if (value) + { // wait for the texture to load - if (value.baseTexture.hasLoaded) { + if (value.baseTexture.hasLoaded) + { this._onTextureUpdate(); } - else { + else + { value.once('update', this._onTextureUpdate.bind(this)); } } @@ -172,18 +185,22 @@ * * @private */ -Sprite.prototype._onTextureUpdate = function () { +Sprite.prototype._onTextureUpdate = function () +{ // so if _width is 0 then width was not set.. - if (this._width) { + if (this._width) + { this.scale.x = this._width / this.texture.frame.width; } - if (this._height) { + if (this._height) + { this.scale.y = this._height / this.texture.frame.height; } }; -Sprite.prototype._renderWebGL = function (renderer) { +Sprite.prototype._renderWebGL = function (renderer) +{ // this is where content gets renderd.. // watch this space for a little render state manager.. @@ -197,7 +214,8 @@ * @param matrix {Matrix} the transformation matrix of the sprite * @return {Rectangle} the framing rectangle */ -Sprite.prototype.getBounds = function (matrix) { +Sprite.prototype.getBounds = function (matrix) +{ var width = this.texture.frame.width; var height = this.texture.frame.height; @@ -224,11 +242,13 @@ if(b === 0 && c === 0) { // scale may be negative! - if (a < 0) { + if (a < 0) + { a *= -1; } - if (d < 0) { + if (d < 0) + { d *= -1; } @@ -293,28 +313,34 @@ * * @param renderer {CanvasRenderer} The renderer */ -Sprite.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) { +Sprite.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) + { return; } - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; renderer.context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } // Ignore null sources - if (this.texture.valid) { + if (this.texture.valid) + { var resolution = this.texture.baseTexture.resolution / renderer.resolution; renderer.context.globalAlpha = this.worldAlpha; // If smoothingEnabled is supported and we need to change the smoothing property for this texture - if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) { + if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) + { renderer.scaleMode = this.texture.baseTexture.scaleMode; renderer.context[renderer.smoothProperty] = (renderer.scaleMode === CONST.scaleModes.LINEAR); } @@ -324,7 +350,8 @@ var dy = (this.texture.trim ? this.texture.trim.y : 0) - (this.anchor.y * this.texture.trim.height); // Allow for pixel rounding - if (renderer.roundPixels) { + if (renderer.roundPixels) + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -337,7 +364,8 @@ dx = dx | 0; dy = dy | 0; } - else { + else + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -348,8 +376,10 @@ ); } - if (this.tint !== 0xFFFFFF) { - if (this.cachedTint !== this.tint) { + if (this.tint !== 0xFFFFFF) + { + if (this.cachedTint !== this.tint) + { this.cachedTint = this.tint; // TODO clean up caching - how to clean up the caches? @@ -368,7 +398,8 @@ this.texture.crop.height / resolution ); } - else { + else + { renderer.context.drawImage( this.texture.baseTexture.source, this.texture.crop.x, @@ -383,11 +414,13 @@ } } - for (var i = 0, j = this.children.length; i < j; i++) { + for (var i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -402,10 +435,12 @@ * @param frameId {String} The frame Id of the texture in the cache * @return {Sprite} A new Sprite using a texture from the texture cache matching the frameId */ -Sprite.fromFrame = function (frameId) { +Sprite.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache' + this); } @@ -420,6 +455,7 @@ * @param imageId {String} The image url of the texture * @return {Sprite} A new Sprite using a texture from the texture cache matching the image id */ -Sprite.fromImage = function (imageId, crossorigin, scaleMode) { +Sprite.fromImage = function (imageId, crossorigin, scaleMode) +{ return new Sprite(Texture.fromImage(imageId, crossorigin, scaleMode)); }; diff --git a/src/core/display/SpriteBatch.js b/src/core/display/SpriteBatch.js index 3187777..c196fef 100644 --- a/src/core/display/SpriteBatch.js +++ b/src/core/display/SpriteBatch.js @@ -12,7 +12,8 @@ * ```js * var container = new SpriteBatch(); * - * for(var i = 0; i < 100; ++i) { + * for(var i = 0; i < 100; ++i) + * { * var sprite = new PIXI.Sprite.fromImage("myImage.png"); * container.addChild(sprite); * } @@ -25,7 +26,8 @@ */ //TODO RENAME to PARTICLE CONTAINER? -function SpriteBatch() { +function SpriteBatch() +{ DisplayObjectContainer.call(this); } @@ -38,7 +40,8 @@ * * @private */ -SpriteBatch.prototype.updateTransform = function () { +SpriteBatch.prototype.updateTransform = function () +{ // TODO don't need to! this.displayObjectUpdateTransform(); // PIXI.DisplayObjectContainer.prototype.updateTransform.call( this ); @@ -50,8 +53,10 @@ * @param renderer {WebGLRenderer} The webgl renderer * @private */ -SpriteBatch.prototype.renderWebGL = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderWebGL = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -71,8 +76,10 @@ * @param renderer {CanvasRenderer} The canvas renderer * @private */ -SpriteBatch.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -84,10 +91,12 @@ this.displayObjectUpdateTransform(); - for (var i = 0; i < this.children.length; ++i) { + for (var i = 0; i < this.children.length; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -95,9 +104,11 @@ context.globalAlpha = this.worldAlpha * child.alpha; - if (child.rotation % (Math.PI * 2) === 0) { + if (child.rotation % (Math.PI * 2) === 0) + { // this is the fastest way to optimise! - if rotation is 0 then we can avoid any kind of setTransform call - if (isRotated) { + if (isRotated) + { context.setTransform( transform.a, transform.b, @@ -122,8 +133,10 @@ frame.height * child.scale.y ); } - else { - if (!isRotated) { + else + { + if (!isRotated) + { isRotated = true; } @@ -131,7 +144,8 @@ var childTransform = child.worldTransform; - if (renderer.roundPixels) { + if (renderer.roundPixels) + { context.setTransform( childTransform.a, childTransform.b, @@ -141,7 +155,8 @@ childTransform.ty | 0 ); } - else { + else + { context.setTransform( childTransform.a, childTransform.b, diff --git a/src/core/index.js b/src/core/index.js index 3954b6f..eb4a82b 100644 --- a/src/core/index.js +++ b/src/core/index.js @@ -58,11 +58,13 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRenderer: function (width, height, options, noWebGL) { + autoDetectRenderer: function (width, height, options, noWebGL) + { width = width || 800; height = height || 600; - if (!noWebGL && require('webgl-enabled')()) { + if (!noWebGL && require('webgl-enabled')()) + { return new core.WebGLRenderer(width, height, options); } @@ -87,7 +89,8 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRecommendedRenderer: function (width, height, options) { + autoDetectRecommendedRenderer: function (width, height, options) + { var isAndroid = /Android/i.test(navigator.userAgent); return core.autoDetectRenderer(width, height, options, isAndroid); diff --git a/src/core/math/Matrix.js b/src/core/math/Matrix.js index c2f87e2..2ff4848 100644 --- a/src/core/math/Matrix.js +++ b/src/core/math/Matrix.js @@ -10,7 +10,8 @@ * @class * @namespace PIXI */ -function Matrix() { +function Matrix() +{ /** * @member {number} * @default 1 @@ -63,7 +64,8 @@ * * @param array {number[]} The array that the matrix will be populated from. */ -Matrix.prototype.fromArray = function (array) { +Matrix.prototype.fromArray = function (array) +{ this.a = array[0]; this.b = array[1]; this.c = array[3]; @@ -78,14 +80,17 @@ * @param transpose {boolean} Whether we need to transpose the matrix or not * @return {number[]} the newly created array which contains the matrix */ -Matrix.prototype.toArray = function (transpose) { - if (!this.array) { +Matrix.prototype.toArray = function (transpose) +{ + if (!this.array) + { this.array = new Float32Array(9); } var array = this.array; - if (transpose) { + if (transpose) + { array[0] = this.a; array[1] = this.b; array[2] = 0; @@ -96,7 +101,8 @@ array[7] = this.ty; array[8] = 1; } - else { + else + { array[0] = this.a; array[1] = this.c; array[2] = this.tx; @@ -119,7 +125,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, transformed through this matrix */ -Matrix.prototype.apply = function (pos, newPos) { +Matrix.prototype.apply = function (pos, newPos) +{ newPos = newPos || new Point(); newPos.x = this.a * pos.x + this.c * pos.y + this.tx; @@ -136,7 +143,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, inverse-transformed through this matrix */ -Matrix.prototype.applyInverse = function (pos, newPos) { +Matrix.prototype.applyInverse = function (pos, newPos) +{ newPos = newPos || new Point(); var id = 1 / (this.a * this.d + this.c * -this.b); @@ -154,7 +162,8 @@ * @param {number} y * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.translate = function (x, y) { +Matrix.prototype.translate = function (x, y) +{ this.tx += x; this.ty += y; @@ -168,7 +177,8 @@ * @param {number} y The amount to scale vertically * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.scale = function (x, y) { +Matrix.prototype.scale = function (x, y) +{ this.a *= x; this.d *= y; this.c *= x; @@ -186,7 +196,8 @@ * @param {number} angle - The angle in radians. * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.rotate = function (angle) { +Matrix.prototype.rotate = function (angle) +{ var cos = Math.cos( angle ); var sin = Math.sin( angle ); @@ -210,7 +221,8 @@ * @param {Matrix} matrix * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.append = function (matrix) { +Matrix.prototype.append = function (matrix) +{ var a1 = this.a; var b1 = this.b; var c1 = this.c; @@ -232,7 +244,8 @@ * * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.identity = function () { +Matrix.prototype.identity = function () +{ this.a = 1; this.b = 0; this.c = 0; diff --git a/src/core/math/Point.js b/src/core/math/Point.js index 7565b2d..632f346 100644 --- a/src/core/math/Point.js +++ b/src/core/math/Point.js @@ -7,7 +7,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -function Point(x, y) { +function Point(x, y) +{ /** * @member {number} * @default 0 @@ -29,7 +30,8 @@ * * @return {Point} a copy of the point */ -Point.prototype.clone = function () { +Point.prototype.clone = function () +{ return new Point(this.x, this.y); }; @@ -40,7 +42,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -Point.prototype.set = function (x, y) { +Point.prototype.set = function (x, y) +{ this.x = x || 0; this.y = y || ( (y !== 0) ? this.x : 0 ) ; }; diff --git a/src/core/math/shapes/Circle.js b/src/core/math/shapes/Circle.js index 69cfdc9..4d76efc 100644 --- a/src/core/math/shapes/Circle.js +++ b/src/core/math/shapes/Circle.js @@ -10,7 +10,8 @@ * @param y {number} The Y coordinate of the center of this circle * @param radius {number} The radius of the circle */ -function Circle(x, y, radius) { +function Circle(x, y, radius) +{ /** * @member {number} * @default 0 @@ -46,7 +47,8 @@ * @method clone * @return {Circle} a copy of the Circle */ -Circle.prototype.clone = function () { +Circle.prototype.clone = function () +{ return new Circle(this.x, this.y, this.radius); }; @@ -58,8 +60,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Circle */ -Circle.prototype.contains = function (x, y) { - if (this.radius <= 0) { +Circle.prototype.contains = function (x, y) +{ + if (this.radius <= 0) + { return false; } @@ -79,6 +83,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Circle.prototype.getBounds = function () { +Circle.prototype.getBounds = function () +{ return new Rectangle(this.x - this.radius, this.y - this.radius, this.radius * 2, this.radius * 2); }; diff --git a/src/core/math/shapes/Ellipse.js b/src/core/math/shapes/Ellipse.js index 4f2d066..fefd01a 100644 --- a/src/core/math/shapes/Ellipse.js +++ b/src/core/math/shapes/Ellipse.js @@ -11,7 +11,8 @@ * @param width {number} The half width of this ellipse * @param height {number} The half height of this ellipse */ -function Ellipse(x, y, width, height) { +function Ellipse(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -53,7 +54,8 @@ * @method clone * @return {Ellipse} a copy of the ellipse */ -Ellipse.prototype.clone = function () { +Ellipse.prototype.clone = function () +{ return new Ellipse(this.x, this.y, this.width, this.height); }; @@ -65,8 +67,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coords are within this ellipse */ -Ellipse.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Ellipse.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } @@ -86,6 +90,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Ellipse.prototype.getBounds = function () { +Ellipse.prototype.getBounds = function () +{ return new Rectangle(this.x - this.width, this.y - this.height, this.width, this.height); }; diff --git a/src/core/math/shapes/Polygon.js b/src/core/math/shapes/Polygon.js index ae89148..fea6d37 100644 --- a/src/core/math/shapes/Polygon.js +++ b/src/core/math/shapes/Polygon.js @@ -10,16 +10,20 @@ * arguments passed can be flat x,y values e.g. `new Polygon(x,y, x,y, x,y, ...)` where `x` and `y` are * Numbers. */ -function Polygon(points) { +function Polygon(points) +{ //if points isn't an array, use arguments as the array - if (!(points instanceof Array)) { + if (!(points instanceof Array)) + { points = Array.prototype.slice.call(arguments); } //if this is a flat array of numbers, convert it to points - if (points[0] instanceof Point) { + if (points[0] instanceof Point) + { var p = []; - for (var i = 0, il = points.length; i < il; i++) { + for (var i = 0, il = points.length; i < il; i++) + { p.push(points[i].x, points[i].y); } @@ -51,7 +55,8 @@ * * @return {Polygon} a copy of the polygon */ -Polygon.prototype.clone = function () { +Polygon.prototype.clone = function () +{ return new Polygon(this.points.slice()); }; @@ -62,19 +67,22 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this polygon */ -Polygon.prototype.contains = function (x, y) { +Polygon.prototype.contains = function (x, y) +{ var inside = false; // use some raycasting to test hits // https://github.com/substack/point-in-polygon/blob/master/index.js var length = this.points.length / 2; - for (var i = 0, j = length - 1; i < length; j = i++) { + for (var i = 0, j = length - 1; i < length; j = i++) + { var xi = this.points[i * 2], yi = this.points[i * 2 + 1], xj = this.points[j * 2], yj = this.points[j * 2 + 1], intersect = ((yi > y) !== (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi); - if (intersect) { + if (intersect) + { inside = !inside; } } diff --git a/src/core/math/shapes/Rectangle.js b/src/core/math/shapes/Rectangle.js index 16ac62a..4008b68 100644 --- a/src/core/math/shapes/Rectangle.js +++ b/src/core/math/shapes/Rectangle.js @@ -10,7 +10,8 @@ * @param width {number} The overall width of this rectangle * @param height {number} The overall height of this rectangle */ -function Rectangle(x, y, width, height) { +function Rectangle(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -60,7 +61,8 @@ * * @return {Rectangle} a copy of the rectangle */ -Rectangle.prototype.clone = function () { +Rectangle.prototype.clone = function () +{ return new Rectangle(this.x, this.y, this.width, this.height); }; @@ -71,13 +73,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rectangle */ -Rectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Rectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/math/shapes/RoundedRectangle.js b/src/core/math/shapes/RoundedRectangle.js index 27d286e..7bf6411 100644 --- a/src/core/math/shapes/RoundedRectangle.js +++ b/src/core/math/shapes/RoundedRectangle.js @@ -11,7 +11,8 @@ * @param height {number} The overall height of this rounded rectangle * @param radius {number} Controls the radius of the rounded corners */ -function RoundedRectangle(x, y, width, height, radius) { +function RoundedRectangle(x, y, width, height, radius) +{ /** * @member {number} * @default 0 @@ -58,7 +59,8 @@ * * @return {RoundedRectangle} a copy of the rounded rectangle */ -RoundedRectangle.prototype.clone = function () { +RoundedRectangle.prototype.clone = function () +{ return new RoundedRectangle(this.x, this.y, this.width, this.height, this.radius); }; @@ -69,13 +71,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rounded Rectangle */ -RoundedRectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +RoundedRectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/primitives/Graphics.js b/src/core/primitives/Graphics.js index 261c534..e902d2a 100644 --- a/src/core/primitives/Graphics.js +++ b/src/core/primitives/Graphics.js @@ -16,7 +16,8 @@ * @extends DisplayObjectContainer * @namespace PIXI */ -function Graphics() { +function Graphics() +{ DisplayObjectContainer.call(this); this.renderable = true; @@ -154,16 +155,20 @@ * @private */ cacheAsBitmap: { - get: function () { + get: function () + { return this._cacheAsBitmap; }, - set: function (value) { + set: function (value) + { this._cacheAsBitmap = value; - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._generateCachedSprite(); } - else { + else + { this.destroyCachedSprite(); this.dirty = true; } @@ -176,7 +181,8 @@ * * @return {Graphics} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ var clone = new Graphics(); clone.renderable = this.renderable; @@ -192,7 +198,8 @@ clone.cachedSpriteDirty = this.cachedSpriteDirty; // copy graphics data - for (var i = 0; i < this.graphicsData.length; ++i) { + for (var i = 0; i < this.graphicsData.length; ++i) + { clone.graphicsData.push(this.graphicsData.clone()); } @@ -211,17 +218,21 @@ * @param alpha {number} alpha of the line to draw, will update the objects stored style * @return {Graphics} */ -Graphics.prototype.lineStyle = function (lineWidth, color, alpha) { +Graphics.prototype.lineStyle = function (lineWidth, color, alpha) +{ this.lineWidth = lineWidth || 0; this.lineColor = color || 0; this.lineAlpha = (arguments.length < 3) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length) + { // halfway through a line? start a new one! this.drawShape( new math.Polygon( this.currentPath.shape.points.slice(-2) )); } - else { + else + { // otherwise its empty so lets just set the line properties this.currentPath.lineWidth = this.lineWidth; this.currentPath.lineColor = this.lineColor; @@ -239,7 +250,8 @@ * @param y {number} the Y coordinate to move to * @return {Graphics} */ -Graphics.prototype.moveTo = function (x, y) { +Graphics.prototype.moveTo = function (x, y) +{ this.drawShape(new math.Polygon([x,y])); return this; @@ -253,7 +265,8 @@ * @param y {number} the Y coordinate to draw to * @return {Graphics} */ -Graphics.prototype.lineTo = function (x, y) { +Graphics.prototype.lineTo = function (x, y) +{ this.currentPath.shape.points.push(x, y); this.dirty = true; @@ -270,13 +283,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -285,7 +302,8 @@ n = 20, points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { this.moveTo(0, 0); } @@ -293,7 +311,8 @@ var fromY = points[points.length-1]; var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; xa = fromX + ( (cpX - fromX) * j ); @@ -319,13 +338,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -342,7 +365,8 @@ var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; dt = (1 - j); @@ -373,13 +397,17 @@ * @param radius {number} The radius of the arc * @return {Graphics} */ -Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points.push(x1, y1); } } - else { + else + { this.moveTo(x1, y1); } @@ -392,12 +420,15 @@ b2 = x2 - x1, mm = Math.abs(a1 * b2 - b1 * a2); - if (mm < 1.0e-8 || radius === 0) { - if (points[points.length-2] !== x1 || points[points.length-1] !== y1) { + if (mm < 1.0e-8 || radius === 0) + { + if (points[points.length-2] !== x1 || points[points.length-1] !== y1) + { points.push(x1, y1); } } - else { + else + { var dd = a1 * a1 + b1 * b1, cc = a2 * a2 + b2 * b2, tt = a1 * a2 + b1 * b2, @@ -433,42 +464,51 @@ * @param anticlockwise {boolean} Optional. Specifies whether the drawing should be counterclockwise or clockwise. False is default, and indicates clockwise, while true indicates counter-clockwise. * @return {Graphics} */ -Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) { +Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) +{ var startX = cx + Math.cos(startAngle) * radius; var startY = cy + Math.sin(startAngle) * radius; var points; // TODO - This if-else makes no sense. It uses currentPath in the else where it doesn't exist... - if (this.currentPath) { + if (this.currentPath) + { points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { points.push(startX, startY); } - else if (points[points.length-2] !== startX || points[points.length-1] !== startY) { + else if (points[points.length-2] !== startX || points[points.length-1] !== startY) + { points.push(startX, startY); } } - else { + else + { this.moveTo(startX, startY); points = this.currentPath.shape.points; } - if (startAngle === endAngle) { + if (startAngle === endAngle) + { return this; } - if (!anticlockwise && endAngle <= startAngle) { + if (!anticlockwise && endAngle <= startAngle) + { endAngle += Math.PI * 2; } - else if (anticlockwise && startAngle <= endAngle) { + else if (anticlockwise && startAngle <= endAngle) + { startAngle += Math.PI * 2; } var sweep = anticlockwise ? (startAngle - endAngle) *-1 : (endAngle - startAngle); var segs = (Math.abs(sweep)/ (Math.PI * 2)) * 40; - if (sweep === 0) { + if (sweep === 0) + { return this; } @@ -482,7 +522,8 @@ var remainder = ( segMinus % 1 ) / segMinus; - for (var i = 0; i <= segMinus; ++i) { + for (var i = 0; i <= segMinus; ++i) + { var real = i + remainder * i; var angle = ((theta) + startAngle + (theta2 * real)); @@ -506,13 +547,16 @@ * @param alpha {number} the alpha of the fill * @return {Graphics} */ -Graphics.prototype.beginFill = function (color, alpha) { +Graphics.prototype.beginFill = function (color, alpha) +{ this.filling = true; this.fillColor = color || 0; this.fillAlpha = (alpha === undefined) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length <= 2) + { this.currentPath.fill = this.filling; this.currentPath.fillColor = this.fillColor; this.currentPath.fillAlpha = this.fillAlpha; @@ -526,7 +570,8 @@ * * @return {Graphics} */ -Graphics.prototype.endFill = function () { +Graphics.prototype.endFill = function () +{ this.filling = false; this.fillColor = null; this.fillAlpha = 1; @@ -542,7 +587,8 @@ * @param height {number} The height of the rectangle * @return {Graphics} */ -Graphics.prototype.drawRect = function ( x, y, width, height ) { +Graphics.prototype.drawRect = function ( x, y, width, height ) +{ this.drawShape(new math.Rectangle(x,y, width, height)); return this; @@ -556,7 +602,8 @@ * @param height {number} The height of the rectangle * @param radius {number} Radius of the rectangle corners */ -Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) { +Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) +{ this.drawShape(new math.RoundedRectangle(x, y, width, height, radius)); return this; @@ -570,7 +617,8 @@ * @param radius {number} The radius of the circle * @return {Graphics} */ -Graphics.prototype.drawCircle = function (x, y, radius) { +Graphics.prototype.drawCircle = function (x, y, radius) +{ this.drawShape(new math.Circle(x,y, radius)); return this; @@ -585,7 +633,8 @@ * @param height {number} The half height of the ellipse * @return {Graphics} */ -Graphics.prototype.drawEllipse = function (x, y, width, height) { +Graphics.prototype.drawEllipse = function (x, y, width, height) +{ this.drawShape(new math.Ellipse(x, y, width, height)); return this; @@ -597,8 +646,10 @@ * @param path {Array} The path data used to construct the polygon. * @return {Graphics} */ -Graphics.prototype.drawPolygon = function (path) { - if (!(path instanceof Array)) { +Graphics.prototype.drawPolygon = function (path) +{ + if (!(path instanceof Array)) + { path = Array.prototype.slice.call(arguments); } @@ -612,7 +663,8 @@ * * @return {Graphics} */ -Graphics.prototype.clear = function () { +Graphics.prototype.clear = function () +{ this.lineWidth = 0; this.filling = false; @@ -631,7 +683,8 @@ * @param scaleMode {number} Should be one of the scaleMode consts * @return {Texture} a texture of the graphics object */ -Graphics.prototype.generateTexture = function (resolution, scaleMode) { +Graphics.prototype.generateTexture = function (resolution, scaleMode) +{ resolution = resolution || 1; var bounds = this.getBounds(); @@ -655,17 +708,21 @@ * * @param renderer {WebGLRenderer} */ -Graphics.prototype._renderWebGL = function (renderer) { +Graphics.prototype._renderWebGL = function (renderer) +{ // if the sprite is not visible or the alpha is 0 then no need to render this element - if (this.isMask === true) { + if (this.isMask === true) + { return; } // this code may still be needed so leaving for now.. - // + // /* - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture on the gpu too! @@ -681,17 +738,24 @@ return; } - */ - - // check if the webgl graphic needs to be updated - if (this.glDirty) { - this.dirty = true; - this.glDirty = false; - } + else */ - renderer.setObjectRendererer(renderer.graphicsRenderer); - renderer.graphicsRenderer.render(this); + renderer.spriteBatch.stop(); + renderer.blendModeManager.setBlendMode(this.blendMode); + // check blend mode + renderer.blendModeManager.setBlendMode( this.blendMode ); + + // check if the webgl graphic needs to be updated + if (this.glDirty) + { + this.dirty = true; + this.glDirty = false; + } + + WebGLGraphics.renderGraphics(this, renderer); + + renderer.spriteBatch.start(); }; /** @@ -700,14 +764,18 @@ * @param renderer {CanvasRenderer} * @private */ -Graphics.prototype.renderCanvas = function (renderer) { +Graphics.prototype.renderCanvas = function (renderer) +{ // 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.isMask === true) { + if (!this.visible || this.alpha <= 0 || this.isMask === true) + { return; } - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture @@ -723,16 +791,19 @@ return; } - else { + else + { var context = renderer.context; var transform = this.worldTransform; - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } @@ -748,11 +819,13 @@ CanvasGraphics.renderGraphics(this, context); - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } } @@ -763,13 +836,16 @@ * * @return {Rectangle} the rectangular bounding area */ -Graphics.prototype.getBounds = function (matrix) { +Graphics.prototype.getBounds = function (matrix) +{ // return an empty object if the item is a mask! - if (this.isMask) { + if (this.isMask) + { return math.Rectangle.EMPTY; } - if (this.dirty) { + if (this.dirty) + { this.updateLocalBounds(); this.glDirty = true; @@ -841,23 +917,27 @@ * Update the bounds of the object * */ -Graphics.prototype.updateLocalBounds = function () { +Graphics.prototype.updateLocalBounds = function () +{ var minX = Infinity; var maxX = -Infinity; var minY = Infinity; var maxY = -Infinity; - if (this.graphicsData.length) { + if (this.graphicsData.length) + { var shape, points, x, y, w, h; - for (var i = 0; i < this.graphicsData.length; i++) { + for (var i = 0; i < this.graphicsData.length; i++) + { var data = this.graphicsData[i]; var type = data.type; var lineWidth = data.lineWidth; shape = data.shape; - if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) { + if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) + { x = shape.x - lineWidth/2; y = shape.y - lineWidth/2; w = shape.width + lineWidth; @@ -869,7 +949,8 @@ minY = y < minY ? y : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.CIRC) { + else if (type === CONST.SHAPES.CIRC) + { x = shape.x; y = shape.y; w = shape.radius + lineWidth/2; @@ -881,7 +962,8 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.ELIP) { + else if (type === CONST.SHAPES.ELIP) + { x = shape.x; y = shape.y; w = shape.width + lineWidth/2; @@ -893,11 +975,13 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else { + else + { // POLY points = shape.points; - for (var j = 0; j < points.length; j += 2) { + for (var j = 0; j < points.length; j += 2) + { x = points[j]; y = points[j+1]; @@ -910,7 +994,8 @@ } } } - else { + else + { minX = 0; maxX = 0; minY = 0; @@ -931,10 +1016,12 @@ * * @private */ -Graphics.prototype._generateCachedSprite = function () { +Graphics.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { var canvasBuffer = new CanvasBuffer(bounds.width, bounds.height); var texture = Texture.fromCanvas(canvasBuffer.canvas); @@ -943,7 +1030,8 @@ this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.buffer.resize(bounds.width, bounds.height); } @@ -968,7 +1056,8 @@ * * @private */ -Graphics.prototype.updateCachedSpriteTexture = function () { +Graphics.prototype.updateCachedSpriteTexture = function () +{ var cachedSprite = this._cachedSprite; var texture = cachedSprite.texture; var canvas = cachedSprite.buffer.canvas; @@ -989,7 +1078,8 @@ * Destroys a previous cached sprite. * */ -Graphics.prototype.destroyCachedSprite = function () { +Graphics.prototype.destroyCachedSprite = function () +{ this._cachedSprite.texture.destroy(true); // let the gc collect the unused sprite @@ -1003,10 +1093,13 @@ * @param {Circle|Rectangle|Ellipse|Line|Polygon} shape The Shape object to draw. * @return {GraphicsData} The generated GraphicsData object. */ -Graphics.prototype.drawShape = function (shape) { - if (this.currentPath) { +Graphics.prototype.drawShape = function (shape) +{ + if (this.currentPath) + { // check current path! - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath.shape.points.length <= 2) + { this.graphicsData.pop(); } } @@ -1017,7 +1110,8 @@ this.graphicsData.push(data); - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { data.shape.closed = this.filling; this.currentPath = data; } diff --git a/src/core/primitives/GraphicsData.js b/src/core/primitives/GraphicsData.js index 99decbe..788f6f2 100644 --- a/src/core/primitives/GraphicsData.js +++ b/src/core/primitives/GraphicsData.js @@ -4,7 +4,8 @@ * @class * @namespace PIXI */ -function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) { +function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) +{ this.lineWidth = lineWidth; this.lineColor = lineColor; this.lineAlpha = lineAlpha; @@ -27,7 +28,8 @@ * * @return {GraphicsData} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ return new GraphicsData( this.lineWidth, this.lineColor, diff --git a/src/core/renderers/canvas/CanvasRenderer.js b/src/core/renderers/canvas/CanvasRenderer.js index 15a0978..7aebd44 100644 --- a/src/core/renderers/canvas/CanvasRenderer.js +++ b/src/core/renderers/canvas/CanvasRenderer.js @@ -17,17 +17,22 @@ * @param [options.resolution=1] {number} the resolution of the renderer retina would be 2 * @param [options.clearBeforeRender=true] {boolean} This sets if the CanvasRenderer will clear the canvas or not before the new render pass. */ -function CanvasRenderer(width, height, options) { +function CanvasRenderer(width, height, options) +{ utils.sayHello('Canvas'); - if (options) { - for (var i in CONST.defaultRenderOptions) { - if (typeof options[i] === 'undefined') { + if (options) + { + for (var i in CONST.defaultRenderOptions) + { + if (typeof options[i] === 'undefined') + { options[i] = CONST.defaultRenderOptions[i]; } } } - else { + else + { options = CONST.defaultRenderOptions; } @@ -156,19 +161,24 @@ this.smoothProperty = null; - if (this.context.imageSmoothingEnabled) { + if (this.context.imageSmoothingEnabled) + { this.smoothProperty = 'imageSmoothingEnabled'; } - else if (this.context.webkitImageSmoothingEnabled) { + else if (this.context.webkitImageSmoothingEnabled) + { this.smoothProperty = 'webkitImageSmoothingEnabled'; } - else if (this.context.mozImageSmoothingEnabled) { + else if (this.context.mozImageSmoothingEnabled) + { this.smoothProperty = 'mozImageSmoothingEnabled'; } - else if (this.context.oImageSmoothingEnabled) { + else if (this.context.oImageSmoothingEnabled) + { this.smoothProperty = 'oImageSmoothingEnabled'; } - else if (this.context.msImageSmoothingEnabled) { + else if (this.context.msImageSmoothingEnabled) + { this.smoothProperty = 'msImageSmoothingEnabled'; } @@ -193,10 +203,12 @@ * @memberof CanvasRenderer# */ backgroundColor: { - get: function () { + get: function () + { return this._backgroundColor; }, - set: function (val) { + set: function (val) + { this._backgroundColor = val; this._backgroundColorString = utils.hex2string(val); } @@ -208,7 +220,8 @@ * * @param object {DisplayObject} the object to be rendered */ -CanvasRenderer.prototype.render = function (object) { +CanvasRenderer.prototype.render = function (object) +{ object.updateTransform(); this.context.setTransform(1,0,0,1,0,0); @@ -218,16 +231,20 @@ this.currentBlendMode = CONST.blendModes.NORMAL; this.context.globalCompositeOperation = this.blendModes[CONST.blendModes.NORMAL]; - if (navigator.isCocoonJS && this.view.screencanvas) { + if (navigator.isCocoonJS && this.view.screencanvas) + { this.context.fillStyle = 'black'; this.context.clear(); } - if (this.clearBeforeRender) { - if (this.transparent) { + if (this.clearBeforeRender) + { + if (this.transparent) + { this.context.clearRect(0, 0, this.width, this.height); } - else { + else + { this.context.fillStyle = this._backgroundColorString; this.context.fillRect(0, 0, this.width , this.height); } @@ -241,8 +258,10 @@ * * @param [removeView=false] {boolean} Removes the Canvas element from the DOM. */ -CanvasRenderer.prototype.destroy = function (removeView) { - if (removeView && this.view.parent) { +CanvasRenderer.prototype.destroy = function (removeView) +{ + if (removeView && this.view.parent) + { this.view.parent.removeChild(this.view); } @@ -257,14 +276,16 @@ * @param width {number} the new width of the canvas view * @param height {number} the new height of the canvas view */ -CanvasRenderer.prototype.resize = function (width, height) { +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) { + if (this.autoResize) + { this.view.style.width = this.width / this.resolution + 'px'; this.view.style.height = this.height / this.resolution + 'px'; } @@ -276,7 +297,8 @@ * @param displayObject {DisplayObject} The displayObject to render * @private */ -CanvasRenderer.prototype.renderDisplayObject = function (displayObject) { +CanvasRenderer.prototype.renderDisplayObject = function (displayObject) +{ displayObject.renderCanvas(this); }; @@ -285,11 +307,14 @@ * * @private */ -CanvasRenderer.prototype._mapBlendModes = function () { - if (!this.blendModes) { +CanvasRenderer.prototype._mapBlendModes = function () +{ + if (!this.blendModes) + { this.blendModes = {}; - if (utils.canUseNewCanvasBlendModes()) { + if (utils.canUseNewCanvasBlendModes()) + { this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? this.blendModes[CONST.blendModes.MULTIPLY] = 'multiply'; @@ -308,7 +333,8 @@ this.blendModes[CONST.blendModes.COLOR] = 'color'; this.blendModes[CONST.blendModes.LUMINOSITY] = 'luminosity'; } - else { + else + { // this means that the browser does not support the cool new blend modes in canvas 'cough' ie 'cough' this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? diff --git a/src/core/renderers/canvas/utils/CanvasBuffer.js b/src/core/renderers/canvas/utils/CanvasBuffer.js index ebe5d47..b183a66 100644 --- a/src/core/renderers/canvas/utils/CanvasBuffer.js +++ b/src/core/renderers/canvas/utils/CanvasBuffer.js @@ -6,7 +6,8 @@ * @param width {number} the width for the newly created canvas * @param height {number} the height for the newly created canvas */ -function CanvasBuffer(width, height) { +function CanvasBuffer(width, height) +{ /** * The Canvas object that belongs to this CanvasBuffer. * @@ -36,10 +37,12 @@ * @memberof CanvasBuffer# */ width: { - get: function () { + get: function () + { return this.canvas.width; }, - set: function (val) { + set: function (val) + { this.canvas.width = val; } }, @@ -50,10 +53,12 @@ * @memberof CanvasBuffer# */ height: { - get: function () { + get: function () + { return this.canvas.height; }, - set: function (val) { + set: function (val) + { this.canvas.height = val; } } @@ -64,7 +69,8 @@ * * @private */ -CanvasBuffer.prototype.clear = function () { +CanvasBuffer.prototype.clear = function () +{ this.context.setTransform(1, 0, 0, 1, 0, 0); this.context.clearRect(0,0, this.canvas.width, this.canvas.height); }; @@ -75,7 +81,8 @@ * @param width {number} the new width of the canvas * @param height {number} the new height of the canvas */ -CanvasBuffer.prototype.resize = function (width, height) { +CanvasBuffer.prototype.resize = function (width, height) +{ this.canvas.width = width; this.canvas.height = height; }; diff --git a/src/core/renderers/canvas/utils/CanvasGraphics.js b/src/core/renderers/canvas/utils/CanvasGraphics.js index c7eaa2a..3f2a91f 100644 --- a/src/core/renderers/canvas/utils/CanvasGraphics.js +++ b/src/core/renderers/canvas/utils/CanvasGraphics.js @@ -13,15 +13,18 @@ * @param graphics {Graphics} the actual graphics object to render * @param context {CanvasRenderingContext2D} the 2d drawing method of the canvas */ -CanvasGraphics.renderGraphics = function (graphics, context) { +CanvasGraphics.renderGraphics = function (graphics, context) +{ var worldAlpha = graphics.worldAlpha; - if (graphics.dirty) { + if (graphics.dirty) + { this.updateGraphicsTint(graphics); graphics.dirty = false; } - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; @@ -30,69 +33,82 @@ context.lineWidth = data.lineWidth; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { context.beginPath(); var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } - if (shape.closed) { + if (shape.closed) + { context.lineTo(points[0], points[1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fillRect(shape.x, shape.y, shape.width, shape.height); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.strokeRect(shape.x, shape.y, shape.width, shape.height); } } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.beginPath(); context.arc(shape.x, shape.y, shape.radius,0,2*Math.PI); context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas var w = shape.width * 2; @@ -119,18 +135,21 @@ context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; var width = shape.width; @@ -152,13 +171,15 @@ context.quadraticCurveTo(rx, ry, rx, ry + radius); context.closePath(); - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); @@ -174,45 +195,54 @@ * @param graphics {Graphics} the graphics which will be used as a mask * @param context {CanvasRenderingContext2D} the context 2d method of the canvas */ -CanvasGraphics.renderGraphicsMask = function (graphics, context) { +CanvasGraphics.renderGraphicsMask = function (graphics, context) +{ var len = graphics.graphicsData.length; - if (len === 0) { + if (len === 0) + { return; } context.beginPath(); - for (var i = 0; i < len; i++) { + for (var i = 0; i < len; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { context.rect(shape.x, shape.y, shape.width, shape.height); context.closePath(); } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.arc(shape.x, shape.y, shape.radius, 0, 2 * Math.PI); context.closePath(); } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas @@ -237,7 +267,8 @@ context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); context.closePath(); } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; @@ -262,8 +293,10 @@ } }; -CanvasGraphics.updateGraphicsTint = function (graphics) { - if (graphics.tint === 0xFFFFFF) { +CanvasGraphics.updateGraphicsTint = function (graphics) +{ + if (graphics.tint === 0xFFFFFF) + { return; } @@ -271,7 +304,8 @@ var tintG = (graphics.tint >> 8 & 0xFF) / 255; var tintB = (graphics.tint & 0xFF)/ 255; - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var fillColor = data.fillColor | 0; diff --git a/src/core/renderers/canvas/utils/CanvasMaskManager.js b/src/core/renderers/canvas/utils/CanvasMaskManager.js index e04a733..9827d36 100644 --- a/src/core/renderers/canvas/utils/CanvasMaskManager.js +++ b/src/core/renderers/canvas/utils/CanvasMaskManager.js @@ -6,7 +6,8 @@ * @class * @namespace PIXI */ -function CanvasMaskManager() {} +function CanvasMaskManager() +{} CanvasMaskManager.prototype.constructor = CanvasMaskManager; module.exports = CanvasMaskManager; @@ -17,7 +18,8 @@ * @param maskData {object} the maskData that will be pushed * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.pushMask = function (maskData, renderer) { +CanvasMaskManager.prototype.pushMask = function (maskData, renderer) +{ renderer.context.save(); var cacheAlpha = maskData.alpha; @@ -45,6 +47,7 @@ * * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.popMask = function (renderer) { +CanvasMaskManager.prototype.popMask = function (renderer) +{ renderer.context.restore(); }; diff --git a/src/core/renderers/canvas/utils/CanvasTinter.js b/src/core/renderers/canvas/utils/CanvasTinter.js index 17e0529..d2fb1bc 100644 --- a/src/core/renderers/canvas/utils/CanvasTinter.js +++ b/src/core/renderers/canvas/utils/CanvasTinter.js @@ -14,7 +14,8 @@ * @param color {number} the color to use to tint the sprite with * @return {HTMLCanvasElement} The tinted canvas */ -CanvasTinter.getTintedTexture = function (sprite, color) { +CanvasTinter.getTintedTexture = function (sprite, color) +{ var texture = sprite.texture; color = CanvasTinter.roundColor(color); @@ -23,7 +24,8 @@ texture.tintCache = texture.tintCache || {}; - if (texture.tintCache[stringColor]) { + if (texture.tintCache[stringColor]) + { return texture.tintCache[stringColor]; } @@ -33,14 +35,16 @@ //CanvasTinter.tintWithPerPixel(texture, stringColor, canvas); CanvasTinter.tintMethod(texture, color, canvas); - if (CanvasTinter.convertTintToImage) { + if (CanvasTinter.convertTintToImage) + { // is this better? var tintImage = new Image(); tintImage.src = canvas.toDataURL(); texture.tintCache[stringColor] = tintImage; } - else { + else + { texture.tintCache[stringColor] = canvas; // if we are not converting the texture to an image then we need to lose the reference to the canvas CanvasTinter.canvas = null; @@ -56,7 +60,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithMultiply = function (texture, color, canvas) { +CanvasTinter.tintWithMultiply = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -104,7 +109,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithOverlay = function (texture, color, canvas) { +CanvasTinter.tintWithOverlay = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -139,7 +145,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithPerPixel = function (texture, color, canvas) { +CanvasTinter.tintWithPerPixel = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -167,7 +174,8 @@ var pixels = pixelData.data; - for (var i = 0; i < pixels.length; i += 4) { + for (var i = 0; i < pixels.length; i += 4) + { pixels[i+0] *= r; pixels[i+1] *= g; pixels[i+2] *= b; @@ -181,7 +189,8 @@ * * @param color {number} the color to round, should be a hex color */ -CanvasTinter.roundColor = function (color) { +CanvasTinter.roundColor = function (color) +{ var step = CanvasTinter.cacheStepsPerColorChannel; var rgbValues = utils.hex2rgb(color); diff --git a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js index 9f2f89a..35edbaf 100644 --- a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js +++ b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLBlendModeManager(renderer) { +function WebGLBlendModeManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -23,8 +24,10 @@ * * @param blendMode {number} the blendMode, should be a Pixi const, such as BlendModes.ADD */ -WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) { - if (this.currentBlendMode === blendMode) { +WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) +{ + if (this.currentBlendMode === blendMode) + { return false; } diff --git a/src/core/renderers/webgl/managers/WebGLFilterManager.js b/src/core/renderers/webgl/managers/WebGLFilterManager.js index 1179258..2dac048 100644 --- a/src/core/renderers/webgl/managers/WebGLFilterManager.js +++ b/src/core/renderers/webgl/managers/WebGLFilterManager.js @@ -7,7 +7,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLFilterManager(renderer) { +function WebGLFilterManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -32,7 +33,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.texturePool.length = 0; self.initShaderBuffers(); }); @@ -46,7 +48,8 @@ * @param renderer {WebGLRenderer} * @param buffer {ArrayBuffer} */ -WebGLFilterManager.prototype.begin = function (buffer) { +WebGLFilterManager.prototype.begin = function (buffer) +{ this.defaultShader = this.renderer.shaderManager.defaultShader; this.width = this.renderer.projection.x * 2; @@ -60,7 +63,8 @@ * * @param filterBlock {object} the filter that will be pushed to the current filter stack */ -WebGLFilterManager.prototype.pushFilter = function (filterBlock) { +WebGLFilterManager.prototype.pushFilter = function (filterBlock) +{ var gl = this.renderer.gl; var projection = this.renderer.projection; @@ -78,10 +82,12 @@ this.offsetY += filterBlock._filterArea.y; var texture = this.texturePool.pop(); - if (!texture) { + if (!texture) + { texture = new FilterTexture(this.renderer.gl, this.width, this.height); } - else { + else + { texture.resize(this.width, this.height); } @@ -98,29 +104,35 @@ var localX = filterArea.x, localY = filterArea.y; - if (filterArea.x < 0) { + if (filterArea.x < 0) + { filterArea.width += filterArea.x; filterArea.x = 0; } - if (filterArea.y < 0) { + if (filterArea.y < 0) + { filterArea.height += filterArea.y; filterArea.y = 0; } - if (localX + filterArea.width > this.width) { + if (localX + filterArea.width > this.width) + { filterArea.width = this.width - localX; } - if (localY + filterArea.height > this.height) { + if (localY + filterArea.height > this.height) + { filterArea.height = this.height - localY; } - if (filterArea.width < 0) { + if (filterArea.width < 0) + { filterArea.width = 0; } - if (filterArea.height < 0) { + if (filterArea.height < 0) + { filterArea.height = 0; } @@ -154,7 +166,8 @@ * Removes the last filter from the filter stack and doesn't return it. * */ -WebGLFilterManager.prototype.popFilter = function () { +WebGLFilterManager.prototype.popFilter = function () +{ var gl = this.renderer.gl; var filterBlock = this.filterStack.pop(); @@ -163,7 +176,8 @@ var projection = this.renderer.projection; var offset = this.renderer.offset; - if (filterBlock.filterPasses.length > 1) { + if (filterBlock.filterPasses.length > 1) + { gl.viewport(0, 0, filterArea.width, filterArea.height); gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); @@ -193,7 +207,8 @@ var inputTexture = texture; var outputTexture = this.texturePool.pop(); - if (!outputTexture) { + if (!outputTexture) + { outputTexture = new FilterTexture(this.renderer.gl, this.width, this.height); } outputTexture.resize(this.width, this.height); @@ -204,7 +219,8 @@ gl.disable(gl.BLEND); - for (var i = 0; i < filterBlock.filterPasses.length-1; i++) { + for (var i = 0; i < filterBlock.filterPasses.length-1; i++) + { var filterPass = filterBlock.filterPasses[i]; gl.bindFramebuffer(gl.FRAMEBUFFER, outputTexture.frameBuffer ); @@ -243,10 +259,12 @@ var buffer = this.buffer; // time to render the filters texture to the previous scene - if (this.filterStack.length === 0) { + if (this.filterStack.length === 0) + { gl.colorMask(true, true, true, true);//this.transparent); } - else { + else + { var currentFilter = this.filterStack[this.filterStack.length-1]; filterArea = currentFilter._filterArea; @@ -332,13 +350,15 @@ * @param width {number} the horizontal range of the filter * @param height {number} the vertical range of the filter */ -WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) { +WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) +{ // use program var gl = this.renderer.gl; var shader = filter.shaders[gl.id]; - if (!shader) { + if (!shader) + { shader = new Shader(gl); shader.fragmentSrc = filter.fragmentSrc; @@ -356,7 +376,8 @@ gl.uniform2f(shader.projectionVector, width/2, -height/2); gl.uniform2f(shader.offsetVector, 0,0); - if (filter.uniforms.dimensions) { + 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]; @@ -386,7 +407,8 @@ * Initialises the shader buffers. * */ -WebGLFilterManager.prototype.initShaderBuffers = function () { +WebGLFilterManager.prototype.initShaderBuffers = function () +{ var gl = this.renderer.gl; // create some buffers @@ -432,7 +454,8 @@ * Destroys the filter and removes it from the filter stack. * */ -WebGLFilterManager.prototype.destroy = function () { +WebGLFilterManager.prototype.destroy = function () +{ var gl = this.renderer.gl; this.filterStack = null; @@ -441,7 +464,8 @@ this.offsetY = 0; // destroy textures - for (var i = 0; i < this.texturePool.length; i++) { + for (var i = 0; i < this.texturePool.length; i++) + { this.texturePool[i].destroy(); } diff --git a/src/core/renderers/webgl/managers/WebGLManager.js b/src/core/renderers/webgl/managers/WebGLManager.js index 9d47b5c..c30cd51 100644 --- a/src/core/renderers/webgl/managers/WebGLManager.js +++ b/src/core/renderers/webgl/managers/WebGLManager.js @@ -3,7 +3,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLManager(renderer) { +function WebGLManager(renderer) +{ /** * The renderer this manager works for. * @@ -15,6 +16,7 @@ WebGLManager.prototype.constructor = WebGLManager; module.exports = WebGLManager; -WebGLManager.prototype.destroy = function () { +WebGLManager.prototype.destroy = function () +{ this.renderer = null; }; diff --git a/src/core/renderers/webgl/managers/WebGLMaskManager.js b/src/core/renderers/webgl/managers/WebGLMaskManager.js index 2f90b64..e568812 100644 --- a/src/core/renderers/webgl/managers/WebGLMaskManager.js +++ b/src/core/renderers/webgl/managers/WebGLMaskManager.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLMaskManager(renderer) { +function WebGLMaskManager(renderer) +{ WebGLManager.call(this, renderer); } @@ -19,12 +20,15 @@ * * @param maskData {any[]} */ -WebGLMaskManager.prototype.pushMask = function (maskData) { - if (maskData.dirty) { +WebGLMaskManager.prototype.pushMask = function (maskData) +{ + if (maskData.dirty) + { WebGLGraphics.updateGraphics(maskData, this.renderer.gl); } - if (!maskData._webGL[this.renderer.gl.id].data.length) { + if (!maskData._webGL[this.renderer.gl.id].data.length) + { return; } @@ -36,6 +40,7 @@ * * @param maskData {any[]} */ -WebGLMaskManager.prototype.popMask = function (maskData) { +WebGLMaskManager.prototype.popMask = function (maskData) +{ this.renderer.stencilManager.popStencil(maskData, maskData._webGL[this.renderer.gl.id].data[0], this.renderer); }; diff --git a/src/core/renderers/webgl/managers/WebGLShaderManager.js b/src/core/renderers/webgl/managers/WebGLShaderManager.js index fef071c..90c6477 100644 --- a/src/core/renderers/webgl/managers/WebGLShaderManager.js +++ b/src/core/renderers/webgl/managers/WebGLShaderManager.js @@ -10,7 +10,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLShaderManager(renderer) { +function WebGLShaderManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -28,7 +29,8 @@ */ this.tempAttribState = []; - for (var i = 0; i < this.maxAttibs; i++) { + for (var i = 0; i < this.maxAttibs; i++) + { this.attribState[i] = false; } @@ -66,7 +68,8 @@ // listen for context and update necessary shaders var self = this; - this.renderer.on('context', function (event) { + this.renderer.on('context', function (event) + { var gl = event.data; // this shader is used for rendering primitives @@ -97,29 +100,36 @@ * * @param attribs {Array} attribs */ -WebGLShaderManager.prototype.setAttribs = function (attribs) { +WebGLShaderManager.prototype.setAttribs = function (attribs) +{ // reset temp state var i; - for (i = 0; i < this.tempAttribState.length; i++) { + for (i = 0; i < this.tempAttribState.length; i++) + { this.tempAttribState[i] = false; } // set the new attribs - for (var a in attribs) { + for (var a in attribs) + { this.tempAttribState[attribs[a]] = true; } var gl = this.renderer.gl; - for (i = 0; i < this.attribState.length; i++) { - if (this.attribState[i] !== this.tempAttribState[i]) { + for (i = 0; i < this.attribState.length; i++) + { + if (this.attribState[i] !== this.tempAttribState[i]) + { this.attribState[i] = this.tempAttribState[i]; - if (this.attribState[i]) { + if (this.attribState[i]) + { gl.enableVertexAttribArray(i); } - else { + else + { gl.disableVertexAttribArray(i); } } @@ -131,8 +141,10 @@ * * @param shader {Any} */ -WebGLShaderManager.prototype.setShader = function (shader) { - if (this._currentId === shader.uuid) { +WebGLShaderManager.prototype.setShader = function (shader) +{ + if (this._currentId === shader.uuid) + { return false; } @@ -150,7 +162,8 @@ * Destroys this object. * */ -WebGLShaderManager.prototype.destroy = function () { +WebGLShaderManager.prototype.destroy = function () +{ this.attribState = null; this.tempAttribState = null; diff --git a/src/core/renderers/webgl/managers/WebGLStencilManager.js b/src/core/renderers/webgl/managers/WebGLStencilManager.js index 9ec6398..4cb0134 100644 --- a/src/core/renderers/webgl/managers/WebGLStencilManager.js +++ b/src/core/renderers/webgl/managers/WebGLStencilManager.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLStencilManager(renderer) { +function WebGLStencilManager(renderer) +{ WebGLManager.call(this, renderer); this.stencilStack = []; @@ -24,12 +25,14 @@ * @param graphics {Graphics} * @param webGLData {any[]} */ -WebGLStencilManager.prototype.pushStencil = function (graphics, webGLData) { +WebGLStencilManager.prototype.pushStencil = function (graphics, webGLData) +{ var gl = this.renderer.gl; this.bindGraphics(graphics, webGLData, this.renderer); - if (this.stencilStack.length === 0) { + if (this.stencilStack.length === 0) + { gl.enable(gl.STENCIL_TEST); gl.clear(gl.STENCIL_BUFFER_BIT); this.reverse = true; @@ -47,14 +50,17 @@ // draw the triangle strip! - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } @@ -62,31 +68,38 @@ // draw a quad to increment.. gl.drawElements(gl.TRIANGLE_FAN, 4, gl.UNSIGNED_SHORT, ( webGLData.indices.length - 4 ) * 2 ); - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); } this.reverse = !this.reverse; } - else { - if (!this.reverse) { + else + { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } - else { + 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) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); } } @@ -103,7 +116,8 @@ * @param graphics {Graphics} * @param webGLData {Array} */ -WebGLStencilManager.prototype.bindGraphics = function (graphics, webGLData) { +WebGLStencilManager.prototype.bindGraphics = function (graphics, webGLData) +{ //if (this._currentGraphics === graphics)return; this._currentGraphics = graphics; @@ -114,7 +128,8 @@ offset = this.renderer.offset, shader;// = this.renderer.shaderManager.primitiveShader; - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { shader = this.renderer.shaderManager.complexPrimitiveShader; this.renderer.shaderManager.setShader(shader); @@ -141,7 +156,8 @@ // set the index buffer! gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, webGLData.indexBuffer); } - else { + else + { //this.renderer.shaderManager.activatePrimitiveShader(); shader = this.renderer.shaderManager.primitiveShader; this.renderer.shaderManager.setShader( shader ); @@ -154,7 +170,7 @@ gl.uniform2f(shader.uniforms.offsetVector._location, -offset.x, -offset.y); gl.uniform3fv(shader.uniforms.tint._location, utils.hex2rgb(graphics.tint)); - + gl.uniform1f(shader.uniforms.alpha._location, graphics.worldAlpha); @@ -172,19 +188,22 @@ * @param graphics {Graphics} * @param webGLData {Array} */ -WebGLStencilManager.prototype.popStencil = function (graphics, webGLData) { +WebGLStencilManager.prototype.popStencil = function (graphics, webGLData) +{ var gl = this.renderer.gl; this.stencilStack.pop(); this.count--; - if (this.stencilStack.length === 0) { + if (this.stencilStack.length === 0) + { // the stack is empty! gl.disable(gl.STENCIL_TEST); } - else { + else + { var level = this.count; @@ -192,14 +211,17 @@ gl.colorMask(false, false, false, false); - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { this.reverse = !this.reverse; - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } @@ -213,31 +235,38 @@ // draw the triangle strip! gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); - if (!this.reverse) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); } } - else { + else + { // console.log("<<>>") - if (!this.reverse) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } - else { + 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) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); } } @@ -253,7 +282,8 @@ * Destroys the mask stack. * */ -WebGLStencilManager.prototype.destroy = function () { +WebGLStencilManager.prototype.destroy = function () +{ this.renderer = null; this.stencilStack = null; }; diff --git a/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js b/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js index 913ba5e..1ea7d19 100644 --- a/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js +++ b/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function ComplexPrimitiveShader(gl) { +function ComplexPrimitiveShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -24,7 +25,8 @@ 'uniform float flipY;', 'varying vec4 vColor;', - 'void main(void) {', + '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);', @@ -37,7 +39,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = vColor;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/FastShader.js b/src/core/renderers/webgl/shaders/FastShader.js index bd2e29a..2e5e060 100644 --- a/src/core/renderers/webgl/shaders/FastShader.js +++ b/src/core/renderers/webgl/shaders/FastShader.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function FastShader(gl) { +function FastShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -28,7 +29,8 @@ 'const vec2 center = vec2(-1.0, 1.0);', - 'void main(void) {', + 'void main(void) + {', ' vec2 v;', ' vec2 sv = aVertexPosition * aScale;', ' v.x = (sv.x) * cos(aRotation) - (sv.y) * sin(aRotation);', @@ -49,7 +51,8 @@ 'uniform sampler2D uSampler;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/PrimitiveShader.js b/src/core/renderers/webgl/shaders/PrimitiveShader.js index 6f25409..a25f54f 100644 --- a/src/core/renderers/webgl/shaders/PrimitiveShader.js +++ b/src/core/renderers/webgl/shaders/PrimitiveShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function PrimitiveShader(gl) { +function PrimitiveShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -23,7 +24,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + '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);', @@ -36,7 +38,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = vColor;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/Shader.js b/src/core/renderers/webgl/shaders/Shader.js index f8964f5..fd75ef5 100644 --- a/src/core/renderers/webgl/shaders/Shader.js +++ b/src/core/renderers/webgl/shaders/Shader.js @@ -6,7 +6,8 @@ * @param [fragmentSrc] {string} The source of the fragment shader. * @param [vertexSrc] {string} The source of the vertex shader. */ -function Shader(gl, vertexSrc, fragmentSrc, customUniforms, customAttributes) { +function Shader(gl, vertexSrc, fragmentSrc, customUniforms, customAttributes) +{ /** * @member {number} * @readonly @@ -33,7 +34,8 @@ dimensions: { type: '4f', value: new Float32Array(4) } }; - for (var u in customUniforms) { + for (var u in customUniforms) + { this.uniforms[u] = customUniforms[u]; } @@ -43,7 +45,8 @@ aColor: 0 }; - for (var a in customAttributes) { + for (var a in customAttributes) + { this.attributes[a] = customAttributes[a]; } @@ -66,7 +69,8 @@ 'const vec2 center = vec2(-1.0, 1.0);', - 'void main(void) {', + 'void main(void) + {', ' gl_Position = vec4( ((aVertexPosition + offsetVector) / projectionVector) + center , 0.0, 1.0);', ' vTextureCoord = aTextureCoord;', ' vColor = vec4(aColor.rgb * aColor.a, aColor.a);', @@ -85,7 +89,8 @@ 'uniform sampler2D uSampler;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;', '}' ].join('\n'); @@ -96,7 +101,8 @@ Shader.prototype.constructor = Shader; module.exports = Shader; -Shader.prototype.init = function () { +Shader.prototype.init = function () +{ this.compile(); this.gl.useProgram(this.program); @@ -105,14 +111,18 @@ this.cacheAttributeLocations(Object.keys(this.attributes)); }; -Shader.prototype.cacheUniformLocations = function (keys) { - for (var i = 0; i < keys.length; ++i) { +Shader.prototype.cacheUniformLocations = function (keys) +{ + for (var i = 0; i < keys.length; ++i) + { this.uniforms[keys[i]]._location = this.gl.getUniformLocation(this.program, keys[i]); } }; -Shader.prototype.cacheAttributeLocations = function (keys) { - for (var i = 0; i < keys.length; ++i) { +Shader.prototype.cacheAttributeLocations = function (keys) +{ + for (var i = 0; i < keys.length; ++i) + { this.attributes[keys[i]] = this.gl.getAttribLocation(this.program, keys[i]); } @@ -124,14 +134,16 @@ // 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.attributes.aColor === -1) { + // if (this.attributes.aColor === -1) + { // this.attributes.aColor = 2; // } // End worst hack eva // }; -Shader.prototype.compile = function () { +Shader.prototype.compile = function () +{ var gl = this.gl; var glVertShader = this._glCompile(gl.VERTEX_SHADER, this.vertexSrc); @@ -144,13 +156,15 @@ gl.linkProgram(program); // if linking fails, then log and cleanup - if (!gl.getProgramParameter(program, gl.LINK_STATUS)) { + if (!gl.getProgramParameter(program, gl.LINK_STATUS)) + { window.console.error('Pixi.js Error: Could not initialize shader.'); window.console.error('gl.VALIDATE_STATUS', gl.getProgramParameter(program, gl.VALIDATE_STATUS)); window.console.error('gl.getError()', gl.getError()); // if there is a program info log, log it - if (gl.getProgramInfoLog(program) !== '') { + if (gl.getProgramInfoLog(program) !== '') + { window.console.warn('Pixi.js Warning: gl.getProgramInfoLog()', gl.getProgramInfoLog(program)); } @@ -165,18 +179,21 @@ return (this.program = program); }; -Shader.prototype.syncUniforms = function () { +Shader.prototype.syncUniforms = function () +{ var gl = this.gl; this.textureCount = 1; - for (var key in this.uniforms) { + for (var key in this.uniforms) + { var uniform = this.uniforms[key], location = uniform._location, value = uniform.value, i, il; - switch (uniform.type) { + switch (uniform.type) + { // single int value case 'i': case '1i': @@ -282,7 +299,8 @@ // a Color Value case 'c': - if (typeof value === 'number') { + if (typeof value === 'number') + { value = utils.hex2rgb(value); } @@ -311,11 +329,13 @@ // array of 2D Point objects case 'v2v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(2 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 2] = value[i].x; uniform._array[i * 2 + 1] = value[i].y; } @@ -325,11 +345,13 @@ // array of 3D Point objects case 'v3v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(3 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 3] = value[i].x; uniform._array[i * 3 + 1] = value[i].y; uniform._array[i * 3 + 2] = value[i].z; @@ -341,11 +363,13 @@ // array of 4D Point objects case 'v4v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(4 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 4] = value[i].x; uniform._array[i * 4 + 1] = value[i].y; uniform._array[i * 4 + 2] = value[i].z; @@ -359,7 +383,8 @@ // PIXI.Texture case 't': case 'sampler2D': - if (!uniform.value || !uniform.value.baseTexture || !uniform.value.baseTexture.hasLoaded) { + if (!uniform.value || !uniform.value.baseTexture || !uniform.value.baseTexture.hasLoaded) + { break; } @@ -376,7 +401,8 @@ this.textureCount++; // initialize the texture if we haven't yet - if (!uniform._init) { + if (!uniform._init) + { this.initSampler2D(uniform); uniform._init = true; @@ -394,11 +420,13 @@ * Initialises a Sampler2D uniform (which may only be available later on after initUniforms once the texture has loaded) * */ -Shader.prototype.initSampler2D = function (uniform) { +Shader.prototype.initSampler2D = function (uniform) +{ var gl = this.gl; // Extended texture data - if (uniform.textureData) { + if (uniform.textureData) + { var data = uniform.textureData; // GLTexture = mag linear, min linear_mipmap_linear, wrap repeat + gl.generateMipmap(gl.TEXTURE_2D); @@ -417,14 +445,16 @@ var wrapT = (data.wrapT) ? data.wrapT : gl.CLAMP_TO_EDGE; var format = (data.luminance) ? gl.LUMINANCE : gl.RGBA; - if (data.repeat) { + if (data.repeat) + { wrapS = gl.REPEAT; wrapT = gl.REPEAT; } gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, !!data.flipY); - if (data.width) { + if (data.width) + { var width = (data.width) ? data.width : 512; var height = (data.height) ? data.height : 2; var border = (data.border) ? data.border : 0; @@ -432,7 +462,8 @@ // 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 { + 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); } @@ -448,7 +479,8 @@ * Destroys the shader. * */ -Shader.prototype.destroy = function () { +Shader.prototype.destroy = function () +{ this.gl.deleteProgram(this.program); this.gl = null; @@ -459,13 +491,15 @@ this.fragmentSrc = null; }; -Shader.prototype._glCompile = function (type, src) { +Shader.prototype._glCompile = function (type, src) +{ var shader = this.gl.createShader(type); this.gl.shaderSource(shader, src); this.gl.compileShader(shader); - if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) { + if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) + { window.console.log(this.gl.getShaderInfoLog(shader)); return null; } diff --git a/src/core/renderers/webgl/shaders/StripShader.js b/src/core/renderers/webgl/shaders/StripShader.js index 193f6e1..a7abcc6 100644 --- a/src/core/renderers/webgl/shaders/StripShader.js +++ b/src/core/renderers/webgl/shaders/StripShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function StripShader(gl) { +function StripShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -20,7 +21,8 @@ 'varying vec2 vTextureCoord;', - 'void main(void) {', + '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);', @@ -36,7 +38,8 @@ 'varying vec2 vTextureCoord;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vec2(vTextureCoord.x, vTextureCoord.y)) * alpha;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/utils/FilterTexture.js b/src/core/renderers/webgl/utils/FilterTexture.js index d2c8423..4433d44 100644 --- a/src/core/renderers/webgl/utils/FilterTexture.js +++ b/src/core/renderers/webgl/utils/FilterTexture.js @@ -8,7 +8,8 @@ * @param height {number} the vertical range of the filter * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values */ -function FilterTexture(gl, width, height, scaleMode) { +function FilterTexture(gl, width, height, scaleMode) +{ /** * @member {WebGLContext} */ @@ -59,7 +60,8 @@ * Clears the filter texture. * */ -FilterTexture.prototype.clear = function () { +FilterTexture.prototype.clear = function () +{ var gl = this.gl; gl.clearColor(0,0,0, 0); @@ -72,8 +74,10 @@ * @param width {number} the new width of the texture * @param height {number} the new height of the texture */ -FilterTexture.prototype.resize = function (width, height) { - if (this.width === width && this.height === height) { +FilterTexture.prototype.resize = function (width, height) +{ + if (this.width === width && this.height === height) + { return; } @@ -96,7 +100,8 @@ * Destroys the filter texture. * */ -FilterTexture.prototype.destroy = function () { +FilterTexture.prototype.destroy = function () +{ var gl = this.gl; gl.deleteFramebuffer( this.frameBuffer ); gl.deleteTexture( this.texture ); diff --git a/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js b/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js index c4721e9..a63f4d7 100644 --- a/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js +++ b/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js @@ -14,7 +14,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this sprite batch works for. */ -function WebGLFastSpriteBatch(renderer) { +function WebGLFastSpriteBatch(renderer) +{ /** * The renderer instance this sprite batch operates on. * @@ -91,7 +92,8 @@ */ this.lastIndexCount = 0; - for (var i=0, j=0; i < numIndices; i += 6, j += 4) { + 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; @@ -144,7 +146,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.setupContext(); }); } @@ -157,7 +160,8 @@ * * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLFastSpriteBatch.prototype.setupContext = function () { +WebGLFastSpriteBatch.prototype.setupContext = function () +{ var gl = this.renderer.gl; // create a couple of buffers @@ -177,7 +181,8 @@ /** * @param spriteBatch {SpriteBatch} The SpriteBatch container to prepare for. */ -WebGLFastSpriteBatch.prototype.begin = function (spriteBatch) { +WebGLFastSpriteBatch.prototype.begin = function (spriteBatch) +{ this.shader = this.renderer.shaderManager.fastShader; this.matrix = spriteBatch.worldTransform.toArray(true); @@ -187,33 +192,38 @@ /** */ -WebGLFastSpriteBatch.prototype.end = function () { +WebGLFastSpriteBatch.prototype.end = function () +{ this.flush(); }; /** * @param spriteBatch {SpriteBatch} The SpriteBatch container to render. */ -WebGLFastSpriteBatch.prototype.render = function (spriteBatch) { +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) { + if (!sprite.texture._uvs) + { return; } this.currentBaseTexture = sprite.texture.baseTexture; // check blend mode - if (sprite.blendMode !== this.renderer.blendModeManager.currentBlendMode) { + if (sprite.blendMode !== this.renderer.blendModeManager.currentBlendMode) + { this.flush(); this.renderer.blendModeManager.setBlendMode(sprite.blendMode); } - for (var i=0,j= children.length; i= this.size) { + if (this.currentBatchSize >= this.size) + { this.flush(); } }; @@ -362,29 +379,35 @@ /** * */ -WebGLFastSpriteBatch.prototype.flush = function () { +WebGLFastSpriteBatch.prototype.flush = function () +{ // If the batch is length 0 then return as there is nothing to draw - if (this.currentBatchSize === 0) { + if (this.currentBatchSize === 0) + { return; } var gl = this.renderer.gl; // bind the current texture - if (!this.currentBaseTexture._glTextures[gl.id]) { + if (!this.currentBaseTexture._glTextures[gl.id]) + { this.renderer.updateTexture(this.currentBaseTexture, gl); } //TODO-SHOUD THIS BE ELSE??!?!?! - else { + else + { gl.bindTexture(gl.TEXTURE_2D, this.currentBaseTexture._glTextures[gl.id]); } // upload the verts to the buffer - if (this.currentBatchSize > ( this.size * 0.5 ) ) { + if (this.currentBatchSize > ( this.size * 0.5 ) ) + { gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); } - else { + else + { var view = this.vertices.subarray(0, this.currentBatchSize * this.vertByteSize); gl.bufferSubData(gl.ARRAY_BUFFER, 0, view); @@ -405,14 +428,16 @@ * Ends the batch and flushes * */ -WebGLFastSpriteBatch.prototype.stop = function () { +WebGLFastSpriteBatch.prototype.stop = function () +{ this.flush(); }; /** * */ -WebGLFastSpriteBatch.prototype.start = function () { +WebGLFastSpriteBatch.prototype.start = function () +{ var gl = this.renderer.gl; // bind the main texture diff --git a/src/core/renderers/webgl/utils/WebGLGraphics.js b/src/core/renderers/webgl/utils/WebGLGraphics.js index 55f4911..ab8f46e 100644 --- a/src/core/renderers/webgl/utils/WebGLGraphics.js +++ b/src/core/renderers/webgl/utils/WebGLGraphics.js @@ -19,7 +19,8 @@ * @param graphics {Graphics} * @param renderer {WebGLRenderer} */ -WebGLGraphics.renderGraphics = function (graphics, renderer) {//projection, offset) { +WebGLGraphics.renderGraphics = function (graphics, renderer) {//projection, offset) +{ var gl = renderer.gl; var projection = renderer.projection, @@ -27,7 +28,8 @@ shader = renderer.shaderManager.primitiveShader, webGLData; - if (graphics.dirty) { + if (graphics.dirty) + { WebGLGraphics.updateGraphics(graphics, gl); } @@ -35,8 +37,10 @@ // This could be speeded up for sure! - for (var i = 0; i < webGL.data.length; i++) { - if (webGL.data[i].mode === 1) { + for (var i = 0; i < webGL.data.length; i++) + { + if (webGL.data[i].mode === 1) + { webGLData = webGL.data[i]; renderer.stencilManager.pushStencil(graphics, webGLData, renderer); @@ -46,7 +50,8 @@ renderer.stencilManager.popStencil(graphics, webGLData, renderer); } - else { + else + { webGLData = webGL.data[i]; @@ -84,12 +89,14 @@ * @param graphicsData {Graphics} The graphics object to update * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLGraphics.updateGraphics = function (graphics, gl) { +WebGLGraphics.updateGraphics = function (graphics, gl) +{ // get the contexts graphics object var webGL = graphics._webGL[gl.id]; // if the graphics object does not exist in the webGL context time to create it! - if (!webGL) { + if (!webGL) + { webGL = graphics._webGL[gl.id] = {lastIndex:0, data:[], gl:gl}; } @@ -99,11 +106,13 @@ var i; // if the user cleared the graphics object we will need to clear every object - if (graphics.clearDirty) { + if (graphics.clearDirty) + { graphics.clearDirty = false; // lop through and return all the webGLDatas to the object pool so than can be reused later on - for (i = 0; i < webGL.data.length; i++) { + for (i = 0; i < webGL.data.length; i++) + { var graphicsData = webGL.data[i]; graphicsData.reset(); WebGLGraphics.graphicsDataPool.push( graphicsData ); @@ -119,58 +128,72 @@ // loop through the graphics datas and construct each one.. // if the object is a complex fill then the new stencil buffer technique will be used // other wise graphics objects will be pushed into a batch.. - for (i = webGL.lastIndex; i < graphics.graphicsData.length; i++) { + for (i = webGL.lastIndex; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { // need to add the points the the graphics object.. data.points = data.shape.points.slice(); - if (data.shape.closed) { + if (data.shape.closed) + { // close the poly if the value is true! - if (data.points[0] !== data.points[data.points.length-2] || data.points[1] !== data.points[data.points.length-1]) { + if (data.points[0] !== data.points[data.points.length-2] || data.points[1] !== data.points[data.points.length-1]) + { data.points.push(data.points[0], data.points[1]); } } // MAKE SURE WE HAVE THE CORRECT TYPE.. - if (data.fill) { - if (data.points.length >= 6) { - if (data.points.length < 6 * 2) { + if (data.fill) + { + if (data.points.length >= 6) + { + if (data.points.length < 6 * 2) + { webGLData = WebGLGraphics.switchMode(webGL, 0); var canDrawUsingSimple = WebGLGraphics.buildPoly(data, webGLData); // console.log(canDrawUsingSimple); - if (!canDrawUsingSimple) { + if (!canDrawUsingSimple) + { // console.log("<>>>") webGLData = WebGLGraphics.switchMode(webGL, 1); WebGLGraphics.buildComplexPoly(data, webGLData); } } - else { + else + { webGLData = WebGLGraphics.switchMode(webGL, 1); WebGLGraphics.buildComplexPoly(data, webGLData); } } } - if (data.lineWidth > 0) { + if (data.lineWidth > 0) + { webGLData = WebGLGraphics.switchMode(webGL, 0); WebGLGraphics.buildLine(data, webGLData); } } - else { + else + { webGLData = WebGLGraphics.switchMode(webGL, 0); - if (data.type === CONST.SHAPES.RECT) { + if (data.type === CONST.SHAPES.RECT) + { WebGLGraphics.buildRectangle(data, webGLData); } - else if (data.type === CONST.SHAPES.CIRC || data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.CIRC || data.type === CONST.SHAPES.ELIP) + { WebGLGraphics.buildCircle(data, webGLData); } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { WebGLGraphics.buildRoundedRectangle(data, webGLData); } } @@ -179,10 +202,12 @@ } // upload all the dirty data... - for (i = 0; i < webGL.data.length; i++) { + for (i = 0; i < webGL.data.length; i++) + { webGLData = webGL.data[i]; - if (webGLData.dirty) { + if (webGLData.dirty) + { webGLData.upload(); } } @@ -194,18 +219,22 @@ * @param webGL {WebGLContext} * @param type {number} */ -WebGLGraphics.switchMode = function (webGL, type) { +WebGLGraphics.switchMode = function (webGL, type) +{ var webGLData; - if (!webGL.data.length) { + if (!webGL.data.length) + { webGLData = WebGLGraphics.graphicsDataPool.pop() || new WebGLGraphicsData(webGL.gl); webGLData.mode = type; webGL.data.push(webGLData); } - else { + else + { webGLData = webGL.data[webGL.data.length-1]; - if (webGLData.mode !== type || type === 1) { + if (webGLData.mode !== type || type === 1) + { webGLData = WebGLGraphics.graphicsDataPool.pop() || new WebGLGraphicsData(webGL.gl); webGLData.mode = type; webGL.data.push(webGLData); @@ -225,7 +254,8 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildRectangle = function (graphicsData, webGLData) { +WebGLGraphics.buildRectangle = function (graphicsData, webGLData) +{ // --- // // need to convert points to a nice regular data // @@ -235,7 +265,8 @@ var width = rectData.width; var height = rectData.height; - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -265,7 +296,8 @@ indices.push(vertPos, vertPos, vertPos+1, vertPos+2, vertPos+3, vertPos+3); } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = [x, y, @@ -289,7 +321,8 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildRoundedRectangle = function (graphicsData, webGLData) { +WebGLGraphics.buildRoundedRectangle = function (graphicsData, webGLData) +{ var rrectData = graphicsData.shape; var x = rrectData.x; var y = rrectData.y; @@ -305,7 +338,8 @@ recPoints = recPoints.concat(WebGLGraphics.quadraticBezierCurve(x + width, y + radius, x + width, y, x + width - radius, y)); recPoints = recPoints.concat(WebGLGraphics.quadraticBezierCurve(x + radius, y, x, y, x, y + radius)); - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -323,7 +357,8 @@ // var i = 0; - for (i = 0; i < triangles.length; i+=3) { + for (i = 0; i < triangles.length; i+=3) + { indices.push(triangles[i] + vecPos); indices.push(triangles[i] + vecPos); indices.push(triangles[i+1] + vecPos); @@ -332,12 +367,14 @@ } - for (i = 0; i < recPoints.length; i++) { + for (i = 0; i < recPoints.length; i++) + { verts.push(recPoints[i], recPoints[++i], r, g, b, alpha); } } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = recPoints; @@ -362,7 +399,8 @@ * @param toY {number} Destination point y * @return {number[]} */ -WebGLGraphics.quadraticBezierCurve = function (fromX, fromY, cpX, cpY, toX, toY) { +WebGLGraphics.quadraticBezierCurve = function (fromX, fromY, cpX, cpY, toX, toY) +{ var xa, ya, @@ -373,14 +411,16 @@ n = 20, points = []; - function getPt(n1 , n2, perc) { + function getPt(n1 , n2, perc) + { var diff = n2 - n1; return n1 + ( diff * perc ); } var j = 0; - for (var i = 0; i <= n; i++ ) { + for (var i = 0; i <= n; i++ ) + { j = i / n; // The Green Line @@ -406,7 +446,8 @@ * @param graphicsData {Graphics} The graphics object to draw * @param webGLData {object} */ -WebGLGraphics.buildCircle = function (graphicsData, webGLData) { +WebGLGraphics.buildCircle = function (graphicsData, webGLData) +{ // need to convert points to a nice regular data var circleData = graphicsData.shape; var x = circleData.x; @@ -415,11 +456,13 @@ var height; // TODO - bit hacky?? - if (graphicsData.type === CONST.SHAPES.CIRC) { + if (graphicsData.type === CONST.SHAPES.CIRC) + { width = circleData.radius; height = circleData.radius; } - else { + else + { width = circleData.width; height = circleData.height; } @@ -429,7 +472,8 @@ var i = 0; - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -444,7 +488,8 @@ indices.push(vecPos); - for (i = 0; i < totalSegs + 1 ; i++) { + for (i = 0; i < totalSegs + 1 ; i++) + { verts.push(x,y, r, g, b, alpha); verts.push(x + Math.sin(seg * i) * width, @@ -457,12 +502,14 @@ indices.push(vecPos-1); } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = []; - for (i = 0; i < totalSegs + 1; i++) { + for (i = 0; i < totalSegs + 1; i++) + { graphicsData.points.push(x + Math.sin(seg * i) * width, y + Math.cos(seg * i) * height); } @@ -481,18 +528,22 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildLine = function (graphicsData, webGLData) { +WebGLGraphics.buildLine = function (graphicsData, webGLData) +{ // TODO OPTIMISE! var i = 0; var points = graphicsData.points; - if (points.length === 0) { + if (points.length === 0) + { return; } // if the line width is an odd number add 0.5 to align to a whole pixel - if (graphicsData.lineWidth%2) { - for (i = 0; i < points.length; i++) { + if (graphicsData.lineWidth%2) + { + for (i = 0; i < points.length; i++) + { points[i] += 0.5; } } @@ -502,7 +553,8 @@ var lastPoint = new math.Point(points[points.length - 2], points[points.length - 1]); // if the first point is the last point - gonna have issues :) - if (firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) { + if (firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) + { // need to clone as we are going to slightly modify the shape.. points = points.slice(); @@ -562,7 +614,8 @@ verts.push(p1x + perpx , p1y + perpy, r, g, b, alpha); - for (i = 1; i < length-1; i++) { + for (i = 1; i < length-1; i++) + { p1x = points[(i-1)*2]; p1y = points[(i-1)*2 + 1]; @@ -599,7 +652,8 @@ denom = a1*b2 - a2*b1; - if (Math.abs(denom) < 0.1 ) { + if (Math.abs(denom) < 0.1 ) + { denom+=10.1; verts.push(p2x - perpx , p2y - perpy, @@ -618,7 +672,8 @@ pdist = (px -p2x) * (px -p2x) + (py -p2y) + (py -p2y); - if (pdist > 140 * 140) { + if (pdist > 140 * 140) + { perp3x = perpx - perp2x; perp3y = perpy - perp2y; @@ -639,7 +694,8 @@ indexCount++; } - else { + else + { verts.push(px , py); verts.push(r, g, b, alpha); @@ -672,7 +728,8 @@ indices.push(indexStart); - for (i = 0; i < indexCount; i++) { + for (i = 0; i < indexCount; i++) + { indices.push(indexStart++); } @@ -687,11 +744,13 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildComplexPoly = function (graphicsData, webGLData) { +WebGLGraphics.buildComplexPoly = function (graphicsData, webGLData) +{ //TODO - no need to copy this as it gets turned into a FLoat32Array anyways.. var points = graphicsData.points.slice(); - if (points.length < 6) { + if (points.length < 6) + { return; } @@ -711,7 +770,8 @@ var x,y; // get size.. - for (var i = 0; i < points.length; i+=2) { + for (var i = 0; i < points.length; i+=2) + { x = points[i]; y = points[i+1]; @@ -732,7 +792,8 @@ //TODO - this aint needed! var length = points.length / 2; - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { indices.push( i ); } @@ -746,10 +807,12 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildPoly = function (graphicsData, webGLData) { +WebGLGraphics.buildPoly = function (graphicsData, webGLData) +{ var points = graphicsData.points; - if (points.length < 6) { + if (points.length < 6) + { return; } // get first and last point.. figure out the middle! @@ -767,7 +830,8 @@ var triangles = utils.PolyK.Triangulate(points); - if (!triangles) { + if (!triangles) + { return false; } @@ -775,7 +839,8 @@ var i = 0; - for (i = 0; i < triangles.length; i+=3) { + for (i = 0; i < triangles.length; i+=3) + { indices.push(triangles[i] + vertPos); indices.push(triangles[i] + vertPos); indices.push(triangles[i+1] + vertPos); @@ -783,7 +848,8 @@ indices.push(triangles[i+2] + vertPos); } - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { verts.push(points[i * 2], points[i * 2 + 1], r, g, b, alpha); } diff --git a/src/core/renderers/webgl/utils/WebGLGraphicsData.js b/src/core/renderers/webgl/utils/WebGLGraphicsData.js index c56d05e..c739ba7 100644 --- a/src/core/renderers/webgl/utils/WebGLGraphicsData.js +++ b/src/core/renderers/webgl/utils/WebGLGraphicsData.js @@ -2,7 +2,8 @@ * @class * @private */ -function WebGLGraphicsData(gl) { +function WebGLGraphicsData(gl) +{ this.gl = gl; //TODO does this need to be split before uploding?? @@ -22,7 +23,8 @@ /** * */ -WebGLGraphicsData.prototype.reset = function () { +WebGLGraphicsData.prototype.reset = function () +{ this.points.length = 0; this.indices.length = 0; }; @@ -30,7 +32,8 @@ /** * */ -WebGLGraphicsData.prototype.upload = function () { +WebGLGraphicsData.prototype.upload = function () +{ var gl = this.gl; // this.lastIndex = graphics.graphicsData.length; diff --git a/src/core/renderers/webgl/utils/WebGLSpriteBatch.js b/src/core/renderers/webgl/utils/WebGLSpriteBatch.js index 96eaa52..55befbb 100644 --- a/src/core/renderers/webgl/utils/WebGLSpriteBatch.js +++ b/src/core/renderers/webgl/utils/WebGLSpriteBatch.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this sprite batch works for. */ -function WebGLSpriteBatch(renderer) { +function WebGLSpriteBatch(renderer) +{ /** * * @@ -88,7 +89,8 @@ */ this.lastIndexCount = 0; - for (var i=0, j=0; i < numIndices; i += 6, j += 4) { + 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; @@ -162,7 +164,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.setupContext(); }); } @@ -173,7 +176,8 @@ /** * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLSpriteBatch.prototype.setupContext = function () { +WebGLSpriteBatch.prototype.setupContext = function () +{ var gl = this.renderer.gl; // setup default shader @@ -198,7 +202,8 @@ /** * */ -WebGLSpriteBatch.prototype.begin = function () { +WebGLSpriteBatch.prototype.begin = function () +{ // this.shader = this.renderer.shaderManager.defaultShader; this.start(); @@ -206,19 +211,22 @@ /** */ -WebGLSpriteBatch.prototype.end = function () { +WebGLSpriteBatch.prototype.end = function () +{ this.flush(); }; /** * @param sprite {Sprite} the sprite to render when using this spritebatch */ -WebGLSpriteBatch.prototype.render = function (sprite) { +WebGLSpriteBatch.prototype.render = function (sprite) +{ var texture = sprite.texture; //TODO set blend modes.. // check texture.. - if (this.currentBatchSize >= this.size) { + if (this.currentBatchSize >= this.size) + { this.flush(); this.currentBaseTexture = texture.baseTexture; } @@ -227,7 +235,8 @@ var uvs = texture._uvs; // if the uvs have not updated then no point rendering just yet! - if (!uvs) { + if (!uvs) + { return; } @@ -237,7 +246,8 @@ var w0, w1, h0, h1; - if (texture.trim) { + 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; @@ -248,7 +258,8 @@ h0 = h1 + texture.crop.height; } - else { + else + { w0 = (texture.frame.width ) * (1-aX); w1 = (texture.frame.width ) * -aX; @@ -272,7 +283,8 @@ var colors = this.colors; var positions = this.positions; - if (this.renderer.roundPixels) { + if (this.renderer.roundPixels) + { // xy positions[index] = a * w1 + c * h1 + tx | 0; positions[index+1] = d * h1 + b * w1 + ty | 0; @@ -289,7 +301,8 @@ positions[index+15] = a * w1 + c * h0 + tx | 0; positions[index+16] = d * h0 + b * w1 + ty | 0; } - else { + else + { // xy positions[index] = a * w1 + c * h1 + tx; positions[index+1] = d * h1 + b * w1 + ty; @@ -338,11 +351,13 @@ * * @param sprite {TilingSprite} the tilingSprite to render */ -WebGLSpriteBatch.prototype.renderTilingSprite = function (tilingSprite) { +WebGLSpriteBatch.prototype.renderTilingSprite = function (tilingSprite) +{ var texture = tilingSprite.tilingTexture; // check texture.. - if (this.currentBatchSize >= this.size) { + if (this.currentBatchSize >= this.size) + { //return; this.flush(); this.currentBaseTexture = texture.baseTexture; @@ -351,7 +366,8 @@ // set the textures uvs temporarily // TODO create a separate texture so that we can tile part of a texture - if (!tilingSprite._uvs) { + if (!tilingSprite._uvs) + { tilingSprite._uvs = new TextureUvs(); } @@ -454,16 +470,19 @@ * Renders the content and empties the current batch. * */ -WebGLSpriteBatch.prototype.flush = function () { +WebGLSpriteBatch.prototype.flush = function () +{ // If the batch is length 0 then return as there is nothing to draw - if (this.currentBatchSize === 0) { + if (this.currentBatchSize === 0) + { return; } var gl = this.renderer.gl; var shader; - if (this.dirty) { + if (this.dirty) + { this.dirty = false; // bind the main texture gl.activeTexture(gl.TEXTURE0); @@ -482,10 +501,12 @@ } // upload the verts to the buffer - if (this.currentBatchSize > ( this.size * 0.5 ) ) { + if (this.currentBatchSize > ( this.size * 0.5 ) ) + { gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); } - else { + else + { var view = this.positions.subarray(0, this.currentBatchSize * this.vertByteSize); gl.bufferSubData(gl.ARRAY_BUFFER, 0, view); } @@ -502,7 +523,8 @@ var shaderSwap = false; var sprite; - for (var i = 0, j = this.currentBatchSize; i < j; i++) { + for (var i = 0, j = this.currentBatchSize; i < j; i++) + { sprite = this.sprites[i]; @@ -513,24 +535,28 @@ blendSwap = currentBlendMode !== nextBlendMode; shaderSwap = currentShader !== nextShader; // should I use uuidS??? - if (currentBaseTexture !== nextTexture || blendSwap || shaderSwap) { + if (currentBaseTexture !== nextTexture || blendSwap || shaderSwap) + { this.renderBatch(currentBaseTexture, batchSize, start); start = i; batchSize = 0; currentBaseTexture = nextTexture; - if (blendSwap) { + if (blendSwap) + { currentBlendMode = nextBlendMode; this.renderer.blendModeManager.setBlendMode( currentBlendMode ); } - if (shaderSwap) { + if (shaderSwap) + { currentShader = nextShader; shader = currentShader.shaders ? currentShader.shaders[gl.id] : currentShader; - if (!shader) { + if (!shader) + { shader = new Shader(gl, null, currentShader.fragmentSrc, currentShader.uniforms); currentShader.shaders[gl.id] = shader; } @@ -538,7 +564,8 @@ // set shader function??? this.renderer.shaderManager.setShader(shader); - if (shader.dirty) { + if (shader.dirty) + { shader.syncUniforms(); } @@ -569,17 +596,21 @@ * @param size {number} * @param startIndex {number} */ -WebGLSpriteBatch.prototype.renderBatch = function (texture, size, startIndex) { - if (size === 0) { +WebGLSpriteBatch.prototype.renderBatch = function (texture, size, startIndex) +{ + if (size === 0) + { return; } var gl = this.renderer.gl; - if (!texture._glTextures[gl.id]) { + if (!texture._glTextures[gl.id]) + { this.renderer.updateTexture(texture); } - else { + else + { // bind the current texture gl.bindTexture(gl.TEXTURE_2D, texture._glTextures[gl.id]); } @@ -594,7 +625,8 @@ /** * */ -WebGLSpriteBatch.prototype.stop = function () { +WebGLSpriteBatch.prototype.stop = function () +{ this.flush(); this.dirty = true; }; @@ -602,7 +634,8 @@ /** * */ -WebGLSpriteBatch.prototype.start = function () { +WebGLSpriteBatch.prototype.start = function () +{ this.dirty = true; }; @@ -610,7 +643,8 @@ * Destroys the SpriteBatch. * */ -WebGLSpriteBatch.prototype.destroy = function () { +WebGLSpriteBatch.prototype.destroy = function () +{ this.renderer.gl.deleteBuffer(this.vertexBuffer); this.renderer.gl.deleteBuffer(this.indexBuffer); diff --git a/src/core/textures/BaseTexture.js b/src/core/textures/BaseTexture.js index 2bf77d4..513d358 100644 --- a/src/core/textures/BaseTexture.js +++ b/src/core/textures/BaseTexture.js @@ -10,7 +10,8 @@ * @param source {Image|Canvas} the source object of the texture. * @param [scaleMode=scaleModes.DEFAULT] {number} See {@link scaleModes} for possible values */ -function BaseTexture(source, scaleMode) { +function BaseTexture(source, scaleMode) +{ this.uuid = utils.uuid(); /** @@ -123,7 +124,8 @@ this._needsUpdate = false; // if no source passed don't try to load - if (source) { + if (source) + { this.loadSource(source); } @@ -149,13 +151,16 @@ Object.defineProperties(BaseTexture.prototype, { needsUpdate: { - get: function () { + get: function () + { return this._needsUpdate; }, - set: function (val) { + set: function (val) + { this._needsUpdate = val; - if (val) { + if (val) + { this.emit('update', this); } } @@ -171,9 +176,11 @@ * * The logic state after calling `loadSource` directly or indirectly (eg. `fromImage`, `new BaseTexture`) is: * - * if (texture.hasLoaded) { + * if (texture.hasLoaded) + { * // texture ready for use - * } else if (texture.isLoading) { + * } else if (texture.isLoading) + { * // listen to 'loaded' and/or 'error' events on texture * } else { * // not loading, not going to load UNLESS the source is reloaded @@ -183,12 +190,14 @@ * @protected * @param source {Image|Canvas} the source object of the texture. */ -BaseTexture.prototype.loadSource = function (source) { +BaseTexture.prototype.loadSource = function (source) +{ var wasLoading = this.isLoading; this.hasLoaded = false; this.isLoading = false; - if (wasLoading && this.source) { + if (wasLoading && this.source) + { this.source.onload = null; this.source.onerror = null; } @@ -196,20 +205,24 @@ this.source = source; // Apply source if loaded. Otherwise setup appropriate loading monitors. - if ((this.source.complete || this.source.getContext) && this.source.width && this.source.height) { + if ((this.source.complete || this.source.getContext) && this.source.width && this.source.height) + { this._sourceLoaded(); } - else if(!source.getContext) { + else if(!source.getContext) + { // Image fail / not ready this.isLoading = true; var scope = this; - source.onload = function () { + source.onload = function () + { source.onload = null; source.onerror = null; - if(!scope.isLoading) { + if(!scope.isLoading) + { return; } @@ -219,11 +232,13 @@ scope.emit('loaded', scope); }; - source.onerror = function () { + source.onerror = function () + { source.onload = null; source.onerror = null; - if(!scope.isLoading) { + if(!scope.isLoading) + { return; } @@ -234,24 +249,29 @@ // Per http://www.w3.org/TR/html5/embedded-content-0.html#the-img-element // "The value of `complete` can thus change while a script is executing." // So complete needs to be re-checked after the callbacks have been added.. - if (source.complete) { + if (source.complete) + { this.isLoading = false; // ..and if we're complete now, no need for callbacks source.onload = null; source.onerror = null; - if (source.width && source.height) { + if (source.width && source.height) + { this._sourceLoaded(); // If any previous subscribers possible - if (wasLoading) { + if (wasLoading) + { this.emit('loaded', this); } } - else { + else + { // If any previous subscribers possible - if (wasLoading) { + if (wasLoading) + { this.emit('error', this); } } @@ -265,7 +285,8 @@ * * @private */ -BaseTexture.prototype._sourceLoaded = function () { +BaseTexture.prototype._sourceLoaded = function () +{ this.hasLoaded = true; this.width = this.source.naturalWidth || this.source.width; @@ -278,16 +299,20 @@ * Destroys this base texture * */ -BaseTexture.prototype.destroy = function () { - if (this.imageUrl) { +BaseTexture.prototype.destroy = function () +{ + if (this.imageUrl) + { delete utils.BaseTextureCache[this.imageUrl]; delete utils.TextureCache[this.imageUrl]; this.imageUrl = null; - if (!navigator.isCocoonJS) { + if (!navigator.isCocoonJS) + { this.source.src = ''; } } - else if (this.source && this.source._pixiId) { + else if (this.source && this.source._pixiId) + { delete utils.BaseTextureCache[this.source._pixiId]; } this.source = null; @@ -301,7 +326,8 @@ * memory again. * */ -BaseTexture.prototype.dispose = function () { +BaseTexture.prototype.dispose = function () +{ this.emit('dispose', this); }; @@ -311,7 +337,8 @@ * * @param newSrc {string} the path of the image */ -BaseTexture.prototype.updateSourceImage = function (newSrc) { +BaseTexture.prototype.updateSourceImage = function (newSrc) +{ this.source.src = newSrc; this.loadSource(this.source); }; @@ -326,18 +353,22 @@ * @param [scaleMode=scaleModes.DEFAULT] {number} See {@link scaleModes} for possible values * @return BaseTexture */ -BaseTexture.fromImage = function (imageUrl, crossorigin, scaleMode) { +BaseTexture.fromImage = function (imageUrl, crossorigin, scaleMode) +{ var baseTexture = utils.BaseTextureCache[imageUrl]; - if (crossorigin === undefined && imageUrl.indexOf('data:') !== 0) { + if (crossorigin === undefined && imageUrl.indexOf('data:') !== 0) + { crossorigin = true; } - if (!baseTexture) { + if (!baseTexture) + { // new Image() breaks tex loading in some versions of Chrome. // See https://code.google.com/p/chromium/issues/detail?id=238071 var image = new Image();//document.createElement('img'); - if (crossorigin) { + if (crossorigin) + { image.crossOrigin = ''; } @@ -347,7 +378,8 @@ utils.BaseTextureCache[imageUrl] = baseTexture; // if there is an @2x at the end of the url we are going to assume its a highres image - if ( imageUrl.indexOf(CONST.RETINA_PREFIX + '.') !== -1) { + if ( imageUrl.indexOf(CONST.RETINA_PREFIX + '.') !== -1) + { baseTexture.resolution = 2; } } @@ -363,14 +395,17 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return BaseTexture */ -BaseTexture.fromCanvas = function (canvas, scaleMode) { - if (!canvas._pixiId) { +BaseTexture.fromCanvas = function (canvas, scaleMode) +{ + if (!canvas._pixiId) + { canvas._pixiId = 'canvas_' + utils.uuid(); } var baseTexture = utils.BaseTextureCache[canvas._pixiId]; - if (!baseTexture) { + if (!baseTexture) + { baseTexture = new BaseTexture(canvas, scaleMode); utils.BaseTextureCache[canvas._pixiId] = baseTexture; } diff --git a/src/core/textures/RenderTexture.js b/src/core/textures/RenderTexture.js index 6dad20f..53ae796 100644 --- a/src/core/textures/RenderTexture.js +++ b/src/core/textures/RenderTexture.js @@ -46,8 +46,10 @@ * @param [scaleMode] {number} See {@link scaleModes} for possible values * @param [resolution=1] {number} The resolution of the texture being generated */ -function RenderTexture(renderer, width, height, scaleMode, resolution) { - if (!renderer) { +function RenderTexture(renderer, width, height, scaleMode, resolution) +{ + if (!renderer) + { throw new Error('Unable to create RenderTexture, you must pass a renderer into the constructor.'); } @@ -133,7 +135,8 @@ */ this.renderer = renderer; - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { var gl = this.renderer.gl; this.textureBuffer = new FilterTexture(gl, this.width * this.resolution, this.height * this.resolution, this.baseTexture.scaleMode); @@ -142,7 +145,8 @@ this.render = this.renderWebGL; this.projection = new math.Point(this.width*0.5, -this.height*0.5); } - else { + else + { this.render = this.renderCanvas; this.textureBuffer = new CanvasBuffer(this.width* this.resolution, this.height* this.resolution); this.baseTexture.source = this.textureBuffer.canvas; @@ -167,8 +171,10 @@ * @param height {number} The height to resize to. * @param updateBase {boolean} Should the baseTexture.width and height values be resized as well? */ -RenderTexture.prototype.resize = function (width, height, updateBase) { - if (width === this.width && height === this.height) { +RenderTexture.prototype.resize = function (width, height, updateBase) +{ + if (width === this.width && height === this.height) + { return; } @@ -177,17 +183,20 @@ this.width = this.frame.width = this.crop.width = width; this.height = this.frame.height = this.crop.height = height; - if (updateBase) { + if (updateBase) + { this.baseTexture.width = this.width; this.baseTexture.height = this.height; } - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { this.projection.x = this.width / 2; this.projection.y = -this.height / 2; } - if (!this.valid) { + if (!this.valid) + { return; } @@ -198,12 +207,15 @@ * Clears the RenderTexture. * */ -RenderTexture.prototype.clear = function () { - if (!this.valid) { +RenderTexture.prototype.clear = function () +{ + if (!this.valid) + { return; } - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { this.renderer.gl.bindFramebuffer(this.renderer.gl.FRAMEBUFFER, this.textureBuffer.frameBuffer); } @@ -220,19 +232,23 @@ * @param [restoreWorldTransform=true] {boolean} If true the displayObject's worldTransform/worldAlpha and all children * transformations will be restored. Not restoring this information will be a little faster. */ -RenderTexture.prototype.renderWebGL = function (displayObject, matrix, clear, restoreWorldTransform) { - if (!this.valid) { +RenderTexture.prototype.renderWebGL = function (displayObject, matrix, clear, restoreWorldTransform) +{ + if (!this.valid) + { return; } - if (typeof restoreWorldTransform === 'undefined') { + if (typeof restoreWorldTransform === 'undefined') + { restoreWorldTransform = true; } var tempAlpha, tempTransform; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { tempAlpha = displayObject.worldAlpha; tempTransform = displayObject.worldTransform.toArray(); } @@ -245,7 +261,8 @@ wt.identity(); wt.translate(0, this.projection.y * 2); - if (matrix) { + if (matrix) + { wt.append(matrix); } @@ -258,7 +275,8 @@ var children = displayObject.children; var i, j; - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } @@ -269,7 +287,8 @@ gl.bindFramebuffer(gl.FRAMEBUFFER, this.textureBuffer.frameBuffer ); - if (clear) { + if (clear) + { this.textureBuffer.clear(); } @@ -279,11 +298,13 @@ this.renderer.spriteBatch.dirty = true; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { displayObject.worldAlpha = tempAlpha; displayObject.worldTransform.fromArray(tempTransform); - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } } @@ -300,26 +321,31 @@ * @param [restoreWorldTransform=true] {boolean} If true the displayObject's worldTransform/worldAlpha and all children * transformations will be restored. Not restoring this information will be a little faster. */ -RenderTexture.prototype.renderCanvas = function (displayObject, matrix, clear, restoreWorldTransform) { - if (!this.valid) { +RenderTexture.prototype.renderCanvas = function (displayObject, matrix, clear, restoreWorldTransform) +{ + if (!this.valid) + { return; } - if (typeof restoreWorldTransform === 'undefined') { + if (typeof restoreWorldTransform === 'undefined') + { restoreWorldTransform = true; } var tempAlpha, tempTransform; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { tempAlpha = displayObject.worldAlpha; tempTransform = displayObject.worldTransform.toArray(); } var wt = displayObject.worldTransform; wt.identity(); - if (matrix) { + if (matrix) + { wt.append(matrix); } @@ -330,11 +356,13 @@ var children = displayObject.children; var i, j; - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } - if (clear) { + if (clear) + { this.textureBuffer.clear(); } @@ -348,11 +376,13 @@ this.renderer.resolution = realResolution; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { displayObject.worldAlpha = tempAlpha; displayObject.worldTransform.fromArray(tempTransform); - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } } @@ -363,7 +393,8 @@ * * @return {Image} */ -RenderTexture.prototype.getImage = function () { +RenderTexture.prototype.getImage = function () +{ var image = new Image(); image.src = this.getBase64(); return image; @@ -374,7 +405,8 @@ * * @return {string} A base64 encoded string of the texture. */ -RenderTexture.prototype.getBase64 = function () { +RenderTexture.prototype.getBase64 = function () +{ return this.getCanvas().toDataURL(); }; @@ -383,8 +415,10 @@ * * @return {HTMLCanvasElement} A Canvas element with the texture rendered on. */ -RenderTexture.prototype.getCanvas = function () { - if (this.renderer.type === CONST.WEBGL_RENDERER) { +RenderTexture.prototype.getCanvas = function () +{ + if (this.renderer.type === CONST.WEBGL_RENDERER) + { var gl = this.renderer.gl; var width = this.textureBuffer.width; var height = this.textureBuffer.height; @@ -403,7 +437,8 @@ return tempCanvas.canvas; } - else { + else + { return this.textureBuffer.canvas; } }; diff --git a/src/core/textures/Texture.js b/src/core/textures/Texture.js index 3c65909..e97f0aa 100644 --- a/src/core/textures/Texture.js +++ b/src/core/textures/Texture.js @@ -17,7 +17,8 @@ * @param [crop] {Rectangle} The area of original texture * @param [trim] {Rectangle} Trimmed texture rectangle */ -function Texture(baseTexture, frame, crop, trim) { +function Texture(baseTexture, frame, crop, trim) +{ /** * Does this Texture have any frame data assigned to it? * @@ -25,12 +26,14 @@ */ this.noFrame = false; - if (!frame) { + if (!frame) + { this.noFrame = true; frame = new math.Rectangle(0, 0, 1, 1); } - if (baseTexture instanceof Texture) { + if (baseTexture instanceof Texture) + { baseTexture = baseTexture.baseTexture; } @@ -100,13 +103,16 @@ */ this.crop = crop || new math.Rectangle(0, 0, 1, 1); - if (baseTexture.hasLoaded) { - if (this.noFrame) { + if (baseTexture.hasLoaded) + { + if (this.noFrame) + { frame = new math.Rectangle(0, 0, baseTexture.width, baseTexture.height); } this.frame = frame; } - else { + else + { baseTexture.addEventListener('loaded', this.onBaseTextureLoaded.bind(this)); } } @@ -118,19 +124,23 @@ Object.defineProperties(Texture.prototype, { needsUpdate: { - get: function () { + get: function () + { return this.baseTexture.needsUpdate; }, - set: function (val) { + set: function (val) + { this.baseTexture.needsUpdate = val; } }, frame: { - get: function () { + get: function () + { return this._frame; }, - set: function (frame) { + set: function (frame) + { this._frame = frame; this.noFrame = false; @@ -143,20 +153,23 @@ 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 (!this.trim && (frame.x + frame.width > this.baseTexture.width || frame.y + frame.height > this.baseTexture.height)) + { throw new Error('Texture Error: frame does not fit inside the base Texture dimensions ' + this); } this.valid = frame && frame.width && frame.height && this.baseTexture.source && this.baseTexture.hasLoaded; - if (this.trim) { + 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) { + if (this.valid) + { this._updateUvs(); } } @@ -168,11 +181,13 @@ * * @private */ -Texture.prototype.onBaseTextureLoaded = function () { +Texture.prototype.onBaseTextureLoaded = function () +{ var baseTexture = this.baseTexture; baseTexture.removeEventListener('loaded', this.onLoaded); - if (this.noFrame) { + if (this.noFrame) + { this.frame = new math.Rectangle(0, 0, baseTexture.width, baseTexture.height); } @@ -184,8 +199,10 @@ * * @param destroyBase {boolean} Whether to destroy the base texture as well */ -Texture.prototype.destroy = function (destroyBase) { - if (destroyBase) { +Texture.prototype.destroy = function (destroyBase) +{ + if (destroyBase) + { this.baseTexture.destroy(); } @@ -197,8 +214,10 @@ * * @private */ -Texture.prototype._updateUvs = function () { - if (!this._uvs) { +Texture.prototype._updateUvs = function () +{ + if (!this._uvs) + { this._uvs = new TextureUvs(); } @@ -229,10 +248,12 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return Texture */ -Texture.fromImage = function (imageUrl, crossorigin, scaleMode) { +Texture.fromImage = function (imageUrl, crossorigin, scaleMode) +{ var texture = utils.TextureCache[imageUrl]; - if (!texture) { + if (!texture) + { texture = new Texture(BaseTexture.fromImage(imageUrl, crossorigin, scaleMode)); utils.TextureCache[imageUrl] = texture; } @@ -248,9 +269,11 @@ * @param frameId {string} The frame id of the texture * @return Texture */ -Texture.fromFrame = function (frameId) { +Texture.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache '); } return texture; @@ -264,7 +287,8 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return {Texture} */ -Texture.fromCanvas = function (canvas, scaleMode) { +Texture.fromCanvas = function (canvas, scaleMode) +{ return new Texture(BaseTexture.fromCanvas(canvas, scaleMode)); }; @@ -276,7 +300,8 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return {Texture} A Texture */ -Texture.fromVideo = function (video, scaleMode) { +Texture.fromVideo = function (video, scaleMode) +{ return new Texture(VideoBaseTexture.baseTextureFromVideo(video, scaleMode)); }; @@ -287,7 +312,8 @@ * @param texture {Texture} The Texture to add to the cache. * @param id {string} The id that the texture will be stored against. */ -Texture.addTextureToCache = function (texture, id) { +Texture.addTextureToCache = function (texture, id) +{ utils.TextureCache[id] = texture; }; @@ -298,7 +324,8 @@ * @param id {string} The id of the texture to be removed * @return {Texture} The texture that was removed */ -Texture.removeTextureFromCache = function (id) { +Texture.removeTextureFromCache = function (id) +{ var texture = utils.TextureCache[id]; delete utils.TextureCache[id]; diff --git a/src/core/textures/TextureUvs.js b/src/core/textures/TextureUvs.js index b9bbb58..5424d52 100644 --- a/src/core/textures/TextureUvs.js +++ b/src/core/textures/TextureUvs.js @@ -1,4 +1,5 @@ -function TextureUvs() { +function TextureUvs() +{ this.x0 = 0; this.y0 = 0; diff --git a/src/core/textures/VideoBaseTexture.js b/src/core/textures/VideoBaseTexture.js index e3e0c5a..1a826a9 100644 --- a/src/core/textures/VideoBaseTexture.js +++ b/src/core/textures/VideoBaseTexture.js @@ -12,15 +12,18 @@ * @param source {HTMLVideoElement} * @param [scaleMode] {number} See {@link scaleModes} for possible values */ -function VideoBaseTexture(source, scaleMode) { - if (!source){ +function VideoBaseTexture(source, scaleMode) +{ + if (!source) + { throw new Error('No video source element specified.'); } // hook in here to check if video is already available. // BaseTexture looks for a source.complete boolean, plus width & height. - if ((source.readyState === source.HAVE_ENOUGH_DATA || source.readyState === source.HAVE_FUTURE_DATA) && source.width && source.height) { + if ((source.readyState === source.HAVE_ENOUGH_DATA || source.readyState === source.HAVE_FUTURE_DATA) && source.width && source.height) + { source.complete = true; } @@ -31,7 +34,8 @@ this._boundOnUpdate = this._onUpdate.bind(this); this._boundOnCanPlay = this._onCanPlay.bind(this); - if (!source.complete) { + if (!source.complete) + { source.addEventListener('canplay', this._boundOnCanPlay); source.addEventListener('canplaythrough', this._boundOnCanPlay); @@ -47,28 +51,35 @@ VideoBaseTexture.prototype.constructor = VideoBaseTexture; module.exports = VideoBaseTexture; -VideoBaseTexture.prototype._onUpdate = function () { - if (this.autoUpdate) { +VideoBaseTexture.prototype._onUpdate = function () +{ + if (this.autoUpdate) + { window.requestAnimationFrame(this._boundOnUpdate); this.needsUpdate = true; } }; -VideoBaseTexture.prototype._onPlayStart = function () { - if (!this.autoUpdate) { +VideoBaseTexture.prototype._onPlayStart = function () +{ + if (!this.autoUpdate) + { window.requestAnimationFrame(this._boundOnUpdate); this.autoUpdate = true; } }; -VideoBaseTexture.prototype._onPlayStop = function () { +VideoBaseTexture.prototype._onPlayStop = function () +{ this.autoUpdate = false; }; -VideoBaseTexture.prototype._onCanPlay = function () { +VideoBaseTexture.prototype._onCanPlay = function () +{ this.hasLoaded = true; - if (this.source) { + if (this.source) + { this.source.removeEventListener('canplay', this._boundOnCanPlay); this.source.removeEventListener('canplaythrough', this._boundOnCanPlay); @@ -78,15 +89,18 @@ this.source.play(); // prevent multiple loaded dispatches.. - if(!this.__loaded){ + if(!this.__loaded) + { this.__loaded = true; this.emit('loaded', this); } } }; -VideoBaseTexture.prototype.destroy = function () { - if (this.source && this.source._pixiId) { +VideoBaseTexture.prototype.destroy = function () +{ + if (this.source && this.source._pixiId) + { utils.BaseTextureCache[ this.source._pixiId ] = null; delete utils.BaseTextureCache[ this.source._pixiId ]; @@ -105,14 +119,17 @@ * @param scaleMode {number} See {@link scaleModes} for possible values * @return {VideoBaseTexture} */ -VideoBaseTexture.fromVideo = function (video, scaleMode) { - if (!video._pixiId) { +VideoBaseTexture.fromVideo = function (video, scaleMode) +{ + if (!video._pixiId) + { video._pixiId = 'video_' + utils.uuid(); } var baseTexture = utils.BaseTextureCache[video._pixiId]; - if (!baseTexture) { + if (!baseTexture) + { baseTexture = new VideoBaseTexture(video, scaleMode); utils.BaseTextureCache[ video._pixiId ] = baseTexture; } @@ -147,17 +164,21 @@ * @param scaleMode {number} See {@link scaleModes} for possible values * @return {VideoBaseTexture} */ -VideoBaseTexture.fromUrl = function (videoSrc, scaleMode) { +VideoBaseTexture.fromUrl = function (videoSrc, scaleMode) +{ var video = document.createElement('video'); // array of objects or strings - if (Array.isArray(videoSrc)) { - for (var i = 0; i < videoSrc.length; ++i) { + if (Array.isArray(videoSrc)) + { + for (var i = 0; i < videoSrc.length; ++i) + { video.appendChild(createSource(videoSrc.src || videoSrc, videoSrc.mime)); } } // single object or string - else { + else + { video.appendChild(createSource(videoSrc.src || videoSrc, videoSrc.mime)); } @@ -169,8 +190,10 @@ VideoBaseTexture.fromUrls = VideoBaseTexture.fromUrl; -function createSource(path, type) { - if (!type) { +function createSource(path, type) +{ + if (!type) + { type = 'video/' + path.substr(path.lastIndexOf('.') + 1); } diff --git a/src/core/utils/EventData.js b/src/core/utils/EventData.js index 5d55a22..8cdf701 100644 --- a/src/core/utils/EventData.js +++ b/src/core/utils/EventData.js @@ -7,7 +7,8 @@ * @param name {string} The string name of the event that was triggered * @param data {object} Arbitrary event data to pass along */ -function EventData(target, name, data) { +function EventData(target, name, data) +{ // for duck typing in the ".on()" function this.__isEventObject = true; @@ -71,7 +72,8 @@ * Stops the propagation of events up the scene graph (prevents bubbling). * */ -EventData.prototype.stopPropagation = function stopPropagation() { +EventData.prototype.stopPropagation = function stopPropagation() +{ this.stopped = true; }; @@ -79,6 +81,7 @@ * Stops the propagation of events to sibling listeners (no longer calls any listeners). * */ -EventData.prototype.stopImmediatePropagation = function stopImmediatePropagation() { +EventData.prototype.stopImmediatePropagation = function stopImmediatePropagation() +{ this.stoppedImmediate = true; }; diff --git a/src/core/utils/EventTarget.js b/src/core/utils/EventTarget.js index 7ae8820..671a151 100644 --- a/src/core/utils/EventTarget.js +++ b/src/core/utils/EventTarget.js @@ -13,14 +13,16 @@ * var em = new MyEmitter(); * em.emit('eventName', 'some data', 'some more data', {}, null, ...); */ -function eventTarget(obj) { +function eventTarget(obj) +{ /** * Return a list of assigned event listeners. * * @param eventName {string} The events that should be listed. * @return {Array} An array of listener functions */ - obj.listeners = function listeners(eventName) { + obj.listeners = function listeners(eventName) + { this._listeners = this._listeners || {}; return this._listeners[eventName] ? this._listeners[eventName].slice() : []; @@ -33,22 +35,26 @@ * @param eventName {string} The name of the event. * @return {boolean} Indication if we've emitted an event. */ - obj.emit = obj.dispatchEvent = function emit(eventName, data) { + obj.emit = obj.dispatchEvent = function emit(eventName, data) + { this._listeners = this._listeners || {}; // fast return when there are no listeners - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return; } //backwards compat with old method ".emit({ type: 'something' })" - if (typeof eventName === 'object') { + if (typeof eventName === 'object') + { data = eventName; eventName = eventName.type; } //ensure we are using a real pixi event - if (!data || data.__isEventObject !== true) { + if (!data || data.__isEventObject !== true) + { data = new EventData(this, eventName, data); } @@ -58,23 +64,27 @@ fn = listeners[0], i; - for (i = 0; i < length; fn = listeners[++i]) { + for (i = 0; i < length; fn = listeners[++i]) + { //call the event listener fn.call(this, data); //if "stopImmediatePropagation" is called, stop calling sibling events - if (data.stoppedImmediate) { + if (data.stoppedImmediate) + { return this; } } //if "stopPropagation" is called then don't bubble the event - if (data.stopped) { + if (data.stopped) + { return this; } //bubble this event up the scene graph - if (this.parent && this.parent.emit) { + if (this.parent && this.parent.emit) + { this.parent.emit.call(this.parent, eventName, data); } @@ -88,7 +98,8 @@ * @param eventName {string} Name of the event. * @param callback {Functon} fn Callback function. */ - obj.on = obj.addEventListener = function on(eventName, fn) { + obj.on = obj.addEventListener = function on(eventName, fn) + { this._listeners = this._listeners || {}; (this._listeners[eventName] = this._listeners[eventName] || []) @@ -103,11 +114,13 @@ * @param eventName {string} Name of the event. * @param callback {Function} Callback function. */ - obj.once = function once(eventName, fn) { + obj.once = function once(eventName, fn) + { this._listeners = this._listeners || {}; var self = this; - function onceHandlerWrapper() { + function onceHandlerWrapper() + { fn.apply(self.off(eventName, onceHandlerWrapper), arguments); } onceHandlerWrapper._originalHandler = fn; @@ -122,23 +135,28 @@ * @param eventName {string} The event we want to remove. * @param callback {Function} The listener that we need to find. */ - obj.off = obj.removeEventListener = function off(eventName, fn) { + obj.off = obj.removeEventListener = function off(eventName, fn) + { this._listeners = this._listeners || {}; - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return this; } var list = this._listeners[eventName], i = fn ? list.length : 0; - while(i-- > 0) { - if (list[i] === fn || list[i]._originalHandler === fn) { + while(i-- > 0) + { + if (list[i] === fn || list[i]._originalHandler === fn) + { list.splice(i, 1); } } - if (list.length === 0) { + if (list.length === 0) + { delete this._listeners[eventName]; } @@ -150,10 +168,12 @@ * * @param eventName {string} The event you want to remove all listeners for. */ - obj.removeAllListeners = function removeAllListeners(eventName) { + obj.removeAllListeners = function removeAllListeners(eventName) + { this._listeners = this._listeners || {}; - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return this; } @@ -169,7 +189,8 @@ * * @param object {object} The obj to mix into */ - mixin: function mixin(obj) { + mixin: function mixin(obj) + { eventTarget(obj); } }; diff --git a/src/core/utils/PolyK.js b/src/core/utils/PolyK.js index 7325141..5e20c2b 100644 --- a/src/core/utils/PolyK.js +++ b/src/core/utils/PolyK.js @@ -47,7 +47,8 @@ * Triangulates shapes for webGL graphic fills. * */ -PolyK.Triangulate = function (p) { +PolyK.Triangulate = function (p) +{ var sign = true; var n = p.length >> 1; @@ -59,7 +60,8 @@ i = 0; var al = n; - while(al > 3) { + while(al > 3) + { var i0 = avl[(i+0)%al]; var i1 = avl[(i+1)%al]; var i2 = avl[(i+2)%al]; @@ -69,29 +71,35 @@ var cx = p[2*i2], cy = p[2*i2+1]; var earFound = false; - if (PolyK._convex(ax, ay, bx, by, cx, cy, sign)) { + if (PolyK._convex(ax, ay, bx, by, cx, cy, sign)) + { earFound = true; - for (var j = 0; j < al; j++) { + for (var j = 0; j < al; j++) + { var vi = avl[j]; if (vi === i0 || vi === i1 || vi === i2) continue; - if (PolyK._PointInTriangle(p[2*vi], p[2*vi+1], ax, ay, bx, by, cx, cy)) { + if (PolyK._PointInTriangle(p[2*vi], p[2*vi+1], ax, ay, bx, by, cx, cy)) + { earFound = false; break; } } } - if (earFound) { + if (earFound) + { tgs.push(i0, i1, i2); avl.splice((i+1)%al, 1); al--; i = 0; } - else if (i++ > 3*al) { + else if (i++ > 3*al) + { // need to flip flip reverse it! // reset! - if (sign) { + if (sign) + { tgs = []; avl = []; for (i = 0; i < n; i++) avl.push(i); @@ -101,7 +109,8 @@ sign = false; } - else { + else + { // window.console.log("PIXI Warning: shape too complex to fill"); return null; } @@ -126,7 +135,8 @@ * @private * @return {boolean} */ -PolyK._PointInTriangle = function (px, py, ax, ay, bx, by, cx, cy) { +PolyK._PointInTriangle = function (px, py, ax, ay, bx, by, cx, cy) +{ var v0x = cx-ax; var v0y = cy-ay; var v1x = bx-ax; @@ -154,6 +164,7 @@ * @private * @return {boolean} */ -PolyK._convex = function (ax, ay, bx, by, cx, cy, sign) { +PolyK._convex = function (ax, ay, bx, by, cx, cy, sign) +{ return ((ay-by)*(cx-bx) + (bx-ax)*(cy-by) >= 0) === sign; }; diff --git a/src/core/utils/index.js b/src/core/utils/index.js index ade9831..bfae7ae 100644 --- a/src/core/utils/index.js +++ b/src/core/utils/index.js @@ -16,7 +16,8 @@ * * @return {number} The next uuid to use. */ - uuid: function () { + uuid: function () + { return ++utils._uid; }, @@ -26,7 +27,8 @@ * @param hex {number} * @return {number[]} An array representing the [R, G, B] of the color. */ - hex2rgb: function (hex, out) { + hex2rgb: function (hex, out) + { out = out || []; out[0] = (hex >> 16 & 0xFF) / 255; @@ -42,7 +44,8 @@ * @param hex {number} * @return {string} The string color. */ - hex2string: function (hex) { + hex2string: function (hex) + { hex = hex.toString(16); hex = '000000'.substr(0, 6 - hex.length) + hex; @@ -55,7 +58,8 @@ * @param rgb {number[]} * @return {number} The color number */ - rgb2hex: function (rgb) { + rgb2hex: function (rgb) + { return ((rgb[0]*255 << 16) + (rgb[1]*255 << 8) + rgb[2]*255); }, @@ -64,8 +68,10 @@ * * @return {boolean} whether they are supported */ - canUseNewCanvasBlendModes: function () { - if (typeof document === 'undefined') { + canUseNewCanvasBlendModes: function () + { + if (typeof document === 'undefined') + { return false; } @@ -93,15 +99,19 @@ * @param number {number} * @return {number} the closest number that is a power of two */ - getNextPowerOfTwo: function (number) { + getNextPowerOfTwo: function (number) + { // see: http://en.wikipedia.org/wiki/Power_of_two#Fast_algorithm_to_check_if_a_positive_number_is_a_power_of_two - if (number > 0 && (number & (number - 1)) === 0) { + if (number > 0 && (number & (number - 1)) === 0) + { return number; } - else { + else + { var result = 1; - while (result < number) { + while (result < number) + { result <<= 1; } @@ -116,7 +126,8 @@ * @param height {number} * @return {boolean} */ - isPowerOfTwo: function (width, height) { + isPowerOfTwo: function (width, height) + { return (width > 0 && (width & (width - 1)) === 0 && height > 0 && (height & (height - 1)) === 0); }, @@ -130,12 +141,15 @@ * @constant * @static */ - sayHello: function (type) { - if (utils._saidHello) { + sayHello: function (type) + { + if (utils._saidHello) + { return; } - if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) { + if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) + { var args = [ '%c %c %c Pixi.js ' + CONST.VERSION + ' - ' + type + ' %c ' + ' %c ' + ' http://www.pixijs.com/ %c %c ♥%c♥%c♥ ', 'background: #ff66a5', @@ -151,7 +165,8 @@ console.log.apply(console, args); //jshint ignore:line } - else if (window.console) { + else if (window.console) + { console.log('Pixi.js ' + CONST.VERSION + ' - ' + type + ' - http://www.pixijs.com/'); //jshint ignore:line } @@ -166,15 +181,19 @@ * @class * @namespace PIXI */ - AjaxRequest: function () { + AjaxRequest: function () + { var activexmodes = ['Msxml2.XMLHTTP.6.0', 'Msxml2.XMLHTTP.3.0', 'Microsoft.XMLHTTP']; //activeX versions to check for in IE - if (window.ActiveXObject) { //Test for support for ActiveXObject in IE first (as XMLHttpRequest in IE7 is broken) - for (var i=0; i= this.textures.length) { + else if (round >= this.textures.length) + { this.gotoAndStop(this.textures.length - 1); - if (this.onComplete) { + if (this.onComplete) + { this.onComplete(); } } @@ -167,10 +182,12 @@ * @static * @param frames {string[]} the array of frames ids the movieclip will use as its texture frames */ -MovieClip.fromFrames = function (frames) { +MovieClip.fromFrames = function (frames) +{ var textures = []; - for (var i = 0; i < frames.length; ++i) { + for (var i = 0; i < frames.length; ++i) + { textures.push(new core.Texture.fromFrame(frames[i])); } @@ -183,10 +200,12 @@ * @static * @param images {string[]} the array of image urls the movieclip will use as its texture frames */ -MovieClip.fromImages = function (images) { +MovieClip.fromImages = function (images) +{ var textures = []; - for (var i = 0; i < images.length; ++i) { + for (var i = 0; i < images.length; ++i) + { textures.push(new core.Texture.fromImage(images[i])); } diff --git a/src/extras/Rope.js b/src/extras/Rope.js index c157ec4..9c87bc0 100644 --- a/src/extras/Rope.js +++ b/src/extras/Rope.js @@ -9,7 +9,8 @@ * @param {Array} points - An array of {Point}. * */ -function Rope(texture, points) { +function Rope(texture, points) +{ Strip.call(this, texture); this.points = points; @@ -31,10 +32,12 @@ * Refreshes * */ -Rope.prototype.refresh = function () { +Rope.prototype.refresh = function () +{ var points = this.points; - if (points.length < 1) { + if (points.length < 1) + { return; } @@ -59,20 +62,23 @@ var total = points.length, point, index, amount; - for (var i = 1; i < total; i++) { + for (var i = 1; i < total; i++) + { point = points[i]; index = i * 4; // time to do some smart drawing! amount = i / (total-1); - if (i%2) { + if (i%2) + { uvs[index] = amount; uvs[index+1] = 0; uvs[index+2] = amount; uvs[index+3] = 1; } - else { + else + { uvs[index] = amount; uvs[index+1] = 0; @@ -95,10 +101,12 @@ * * @private */ -Rope.prototype.updateTransform = function () { +Rope.prototype.updateTransform = function () +{ var points = this.points; - if (points.length < 1) { + if (points.length < 1) + { return; } @@ -113,14 +121,17 @@ var total = points.length, point, index, ratio, perpLength, num; - for (var i = 0; i < total; i++) { + for (var i = 0; i < total; i++) + { point = points[i]; index = i * 4; - if (i < points.length-1) { + if (i < points.length-1) + { nextPoint = points[i+1]; } - else { + else + { nextPoint = point; } @@ -129,7 +140,8 @@ ratio = (1 - (i / (total-1))) * 10; - if (ratio > 1) { + if (ratio > 1) + { ratio = 1; } @@ -157,7 +169,8 @@ * * @param texture {Texture} the texture that will be used */ -Rope.prototype.setTexture = function (texture) { +Rope.prototype.setTexture = function (texture) +{ // stop current texture this.texture = texture; //this.updateFrame = true; diff --git a/src/extras/Strip.js b/src/extras/Strip.js index c5e378f..57691b5 100644 --- a/src/extras/Strip.js +++ b/src/extras/Strip.js @@ -10,7 +10,8 @@ * @param height {number} the height * */ -function Strip(texture) { +function Strip(texture) +{ core.DisplayObjectContainer.call(this); /** @@ -70,9 +71,11 @@ * * @param renderer {WebGLRenderer} */ -Strip.prototype.renderWebGL = function (renderer) { +Strip.prototype.renderWebGL = function (renderer) +{ // if the sprite is not visible or the alpha is 0 then no need to render this element - if (!this.visible || this.alpha <= 0) { + if (!this.visible || this.alpha <= 0) + { return; } @@ -81,7 +84,8 @@ renderer.spriteBatch.stop(); // init! init! - if (!this._vertexBuffer) { + if (!this._vertexBuffer) + { this._initWebGL(renderer); } @@ -96,7 +100,8 @@ //TODO check culling }; -Strip.prototype._initWebGL = function (renderer) { +Strip.prototype._initWebGL = function (renderer) +{ // build the strip! var gl = renderer.gl; @@ -118,7 +123,8 @@ gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this.indices, gl.STATIC_DRAW); }; -Strip.prototype._renderStrip = function (renderer) { +Strip.prototype._renderStrip = function (renderer) +{ var gl = renderer.gl; var projection = renderer.projection, offset = renderer.offset, @@ -137,7 +143,8 @@ gl.uniform2f(shader.offsetVector, -offset.x, -offset.y); gl.uniform1f(shader.alpha, this.worldAlpha); - if (!this.dirty) { + if (!this.dirty) + { gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexBuffer); gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); @@ -150,10 +157,12 @@ gl.activeTexture(gl.TEXTURE0); // check if a texture is dirty.. - if (this.texture.baseTexture._dirty[gl.id]) { + if (this.texture.baseTexture._dirty[gl.id]) + { renderer.updateTexture(this.texture.baseTexture); } - else { + else + { // bind the current texture gl.bindTexture(gl.TEXTURE_2D, this.texture.baseTexture._glTextures[gl.id]); } @@ -163,7 +172,8 @@ } - else { + else + { this.dirty = false; gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexBuffer); @@ -178,10 +188,12 @@ gl.activeTexture(gl.TEXTURE0); // check if a texture is dirty.. - if (this.texture.baseTexture._dirty[gl.id]) { + if (this.texture.baseTexture._dirty[gl.id]) + { renderer.updateTexture(this.texture.baseTexture); } - else { + else + { gl.bindTexture(gl.TEXTURE_2D, this.texture.baseTexture._glTextures[gl.id]); } @@ -203,27 +215,33 @@ * * @param renderer {CanvasRenderer} */ -Strip.prototype.renderCanvas = function (renderer) { +Strip.prototype.renderCanvas = function (renderer) +{ var context = renderer.context; var transform = this.worldTransform; - if (renderer.roundPixels) { + if (renderer.roundPixels) + { context.setTransform(transform.a, transform.b, transform.c, transform.d, transform.tx | 0, transform.ty | 0); } - else { + else + { context.setTransform(transform.a, transform.b, transform.c, transform.d, transform.tx, transform.ty); } - if (this.drawMode === Strip.DrawModes.TRIANGLE_STRIP) { + if (this.drawMode === Strip.DrawModes.TRIANGLE_STRIP) + { this._renderCanvasTriangleStrip(context); } - else { + else + { this._renderCanvasTriangles(context); } }; -Strip.prototype._renderCanvasTriangleStrip = function (context) { +Strip.prototype._renderCanvasTriangleStrip = function (context) +{ // draw triangles!! var vertices = this.vertices; var uvs = this.uvs; @@ -231,14 +249,16 @@ var length = vertices.length / 2; // this.count++; - for (var i = 0; i < length - 2; i++) { + for (var i = 0; i < length - 2; i++) + { // draw some triangles! var index = i * 2; this._renderCanvasDrawTriangle(context, vertices, uvs, index, (index + 2), (index + 4)); } }; -Strip.prototype._renderCanvasTriangles = function (context) { +Strip.prototype._renderCanvasTriangles = function (context) +{ // draw triangles!! var vertices = this.vertices; var uvs = this.uvs; @@ -247,14 +267,16 @@ var length = indices.length; // this.count++; - for (var i = 0; i < length; i += 3) { + for (var i = 0; i < length; i += 3) + { // draw some triangles! var index0 = indices[i] * 2, index1 = indices[i + 1] * 2, index2 = indices[i + 2] * 2; this._renderCanvasDrawTriangle(context, vertices, uvs, index0, index1, index2); } }; -Strip.prototype._renderCanvasDrawTriangle = function (context, vertices, uvs, index0, index1, index2) { +Strip.prototype._renderCanvasDrawTriangle = function (context, vertices, uvs, index0, index1, index2) +{ var textureSource = this.texture.baseTexture.source; var textureWidth = this.texture.width; var textureHeight = this.texture.height; @@ -265,7 +287,8 @@ var u0 = uvs[index0] * textureWidth, u1 = uvs[index1] * textureWidth, u2 = uvs[index2] * textureWidth; var v0 = uvs[index0 + 1] * textureHeight, v1 = uvs[index1 + 1] * textureHeight, v2 = uvs[index2 + 1] * textureHeight; - if (this.canvasPadding > 0) { + if (this.canvasPadding > 0) + { var paddingX = this.canvasPadding / this.worldTransform.a; var paddingY = this.canvasPadding / this.worldTransform.d; var centerX = (x0 + x1 + x2) / 3; @@ -332,7 +355,8 @@ * @param strip {Strip} The Strip to render * @private */ -Strip.prototype.renderStripFlat = function (strip) { +Strip.prototype.renderStripFlat = function (strip) +{ var context = this.context; var vertices = strip.vertices; @@ -340,7 +364,8 @@ // this.count++; context.beginPath(); - for (var i=1; i < length-2; i++) { + for (var i=1; i < length-2; i++) + { // draw some triangles! var index = i*2; @@ -358,7 +383,8 @@ }; /* -Strip.prototype.setTexture = function (texture) { +Strip.prototype.setTexture = function (texture) +{ //TODO SET THE TEXTURES //TODO VISIBILITY @@ -377,7 +403,8 @@ * @private */ -Strip.prototype.onTextureUpdate = function () { +Strip.prototype.onTextureUpdate = function () +{ this.updateFrame = true; }; @@ -387,7 +414,8 @@ * @param matrix {Matrix} the transformation matrix of the sprite * @return {Rectangle} the framing rectangle */ -Strip.prototype.getBounds = function (matrix) { +Strip.prototype.getBounds = function (matrix) +{ var worldTransform = matrix || this.worldTransform; var a = worldTransform.a; @@ -404,7 +432,8 @@ var minY = Infinity; var vertices = this.vertices; - for (var i = 0, n = vertices.length; i < n; i += 2) { + for (var i = 0, n = vertices.length; i < n; i += 2) + { var rawX = vertices[i], rawY = vertices[i + 1]; var x = (a * rawX) + (c * rawY) + tx; var y = (d * rawY) + (b * rawX) + ty; @@ -416,7 +445,8 @@ maxY = y > maxY ? y : maxY; } - if (minX === -Infinity || maxY === Infinity) { + if (minX === -Infinity || maxY === Infinity) + { return core.math.Rectangle.EMPTY; } diff --git a/src/extras/TilingSprite.js b/src/extras/TilingSprite.js index 3ac22df..31da393 100644 --- a/src/extras/TilingSprite.js +++ b/src/extras/TilingSprite.js @@ -10,7 +10,8 @@ * @param width {number} the width of the tiling sprite * @param height {number} the height of the tiling sprite */ -function TilingSprite(texture, width, height) { +function TilingSprite(texture, width, height) +{ core.Sprite.call( this, texture); /** @@ -86,10 +87,12 @@ * @memberof TilingSprite# */ width: { - get: function () { + get: function () + { return this._width; }, - set: function (value) { + set: function (value) + { this._width = value; } }, @@ -101,20 +104,25 @@ * @memberof TilingSprite# */ height: { - get: function () { + get: function () + { return this._height; }, - set: function (value) { + set: function (value) + { this._height = value; } }, texture: { - get: function () { + get: function () + { return this._texture; }, - set: function (value) { - if (this._texture === value) { + set: function (value) + { + if (this._texture === value) + { return; } @@ -130,51 +138,61 @@ * * @param renderer {WebGLRenderer} */ -TilingSprite.prototype.renderWebGL = function (renderer) { - if (!this.visible || this.alpha <= 0) { +TilingSprite.prototype.renderWebGL = function (renderer) +{ + if (!this.visible || this.alpha <= 0) + { return; } var i, j; - if (this._mask) { + if (this._mask) + { renderer.spriteBatch.stop(); renderer.maskManager.pushMask(this.mask, renderer); renderer.spriteBatch.start(); } - if (this._filters) { + if (this._filters) + { renderer.spriteBatch.flush(); renderer.filterManager.pushFilter(this._filterBlock); } - if (!this.tilingTexture || this.refreshTexture) { + if (!this.tilingTexture || this.refreshTexture) + { this.generateTilingTexture(true); - if (this.tilingTexture && this.tilingTexture.needsUpdate) { + if (this.tilingTexture && this.tilingTexture.needsUpdate) + { //TODO - tweaking renderer.updateTexture(this.tilingTexture.baseTexture); this.tilingTexture.needsUpdate = false; // this.tilingTexture._uvs = null; } } - else { + else + { renderer.spriteBatch.renderTilingSprite(this); } // simple render children! - for (i=0,j=this.children.length; i= 0 && index <= this.children.length) { - if (child.parent) { + if (index >= 0 && index <= this.children.length) + { + if (child.parent) + { child.parent.removeChild(child); } @@ -154,7 +173,8 @@ return child; } - else { + else + { throw new Error(child + 'addChildAt: The index '+ index +' supplied is out of bounds ' + this.children.length); } }; @@ -165,15 +185,18 @@ * @param child {DisplayObject} * @param child2 {DisplayObject} */ -DisplayObjectContainer.prototype.swapChildren = function (child, child2) { - if (child === child2) { +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) { + if (index1 < 0 || index2 < 0) + { throw new Error('swapChildren: Both the supplied DisplayObjects must be a child of the caller.'); } @@ -187,10 +210,12 @@ * @param child {DisplayObject} The DisplayObject instance to identify * @return {Number} The index position of the child display object to identify */ -DisplayObjectContainer.prototype.getChildIndex = function (child) { +DisplayObjectContainer.prototype.getChildIndex = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { throw new Error('The supplied DisplayObject must be a child of the caller'); } @@ -203,8 +228,10 @@ * @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 */ -DisplayObjectContainer.prototype.setChildIndex = function (child, index) { - if (index < 0 || index >= this.children.length) { +DisplayObjectContainer.prototype.setChildIndex = function (child, index) +{ + if (index < 0 || index >= this.children.length) + { throw new Error('The supplied index is out of bounds'); } @@ -220,8 +247,10 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child at the given index, if any. */ -DisplayObjectContainer.prototype.getChildAt = function (index) { - if (index < 0 || index >= this.children.length) { +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'); } @@ -234,10 +263,12 @@ * @param child {DisplayObject} The DisplayObject to remove * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChild = function (child) { +DisplayObjectContainer.prototype.removeChild = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { return; } @@ -250,7 +281,8 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChildAt = function (index) { +DisplayObjectContainer.prototype.removeChildAt = function (index) +{ var child = this.getChildAt(index); child.parent = null; @@ -265,24 +297,29 @@ * @param beginIndex {Number} The beginning position. Default value is 0. * @param endIndex {Number} The ending position. Default value is size of the container. */ -DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) { +DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) +{ var begin = beginIndex || 0; var end = typeof endIndex === 'number' ? endIndex : this.children.length; var range = end - begin; - if (range > 0 && range <= end) { + if (range > 0 && range <= end) + { var removed = this.children.splice(begin, range); - for (var i = 0; i < removed.length; ++i) { + for (var i = 0; i < removed.length; ++i) + { removed[i].parent = null; } return removed; } - else if (range === 0 && this.children.length === 0) { + else if (range === 0 && this.children.length === 0) + { return []; } - else { + else + { throw new RangeError('removeChildren: numeric values are outside the acceptable range.'); } }; @@ -291,7 +328,8 @@ * Generates and updates the cached sprite for this object. * */ -DisplayObjectContainer.prototype.updateCachedSprite = function () { +DisplayObjectContainer.prototype.updateCachedSprite = function () +{ this._generateCachedSprite(); }; @@ -304,7 +342,8 @@ * @param renderer {CanvasRenderer|WebGLRenderer} The renderer used to generate the texture. * @return {Texture} a texture of the graphics object */ -DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) { +DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) +{ var bounds = this.getLocalBounds(); var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0, renderer, scaleMode, resolution); @@ -322,18 +361,22 @@ * * @private */ -DisplayObjectContainer.prototype.updateTransform = function () { - if (!this.visible) { +DisplayObjectContainer.prototype.updateTransform = function () +{ + if (!this.visible) + { return; } this.displayObjectUpdateTransform(); - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { return; } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } }; @@ -346,8 +389,10 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getBounds = function () { - if (this.children.length === 0) { +DisplayObjectContainer.prototype.getBounds = function () +{ + if (this.children.length === 0) + { return math.Rectangle.EMPTY; } @@ -365,10 +410,12 @@ var childVisible = false; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -386,7 +433,8 @@ maxY = maxY > childMaxY ? maxY : childMaxY; } - if (!childVisible) { + if (!childVisible) + { return math.Rectangle.EMPTY; } @@ -407,12 +455,14 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getLocalBounds = function () { +DisplayObjectContainer.prototype.getLocalBounds = function () +{ var matrixCache = this.worldTransform; this.worldTransform = math.Matrix.IDENTITY; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } @@ -428,13 +478,16 @@ * * @param renderer {WebGLRenderer} The renderer */ -DisplayObjectContainer.prototype.renderWebGL = function (renderer) { +DisplayObjectContainer.prototype.renderWebGL = function (renderer) +{ // if the object is not visible or the alpha is 0 then no need to render this element - if (!this.visible || this.alpha <= 0) { + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } @@ -442,14 +495,17 @@ var i, j; // do a quick check to see if this element has a mask or a filter. - if (this._mask || this._filters) { + if (this._mask || this._filters) + { // push filter first as we need to ensure the stencil buffer is correct for any masking - if (this._filters) { + if (this._filters) + { renderer.spriteBatch.flush(); renderer.filterManager.pushFilter(this._filterBlock); } - if (this._mask) { + if (this._mask) + { renderer.spriteBatch.stop(); renderer.maskManager.pushMask(this.mask, renderer); renderer.spriteBatch.start(); @@ -459,36 +515,42 @@ this._renderWebGL(renderer); // now loop through the children and make sure they get rendered - for (i = 0, j = this.children.length; i < j; i++) { + for (i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderWebGL(renderer); } // time to stop the sprite batch as either a mask element or a filter draw will happen next renderer.spriteBatch.stop(); - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(this._mask, renderer); } - if (this._filters) { + if (this._filters) + { renderer.filterManager.popFilter(); } renderer.spriteBatch.start(); } - else { + else + { this._renderWebGL(renderer); // simple render children! - for (i = 0, j = this.children.length; i < j; ++i) { + for (i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderWebGL(renderer); } } }; -DisplayObjectContainer.prototype._renderWebGL = function (renderer) { +DisplayObjectContainer.prototype._renderWebGL = function (renderer) +{ // this is where content itself gets renderd.. @@ -499,25 +561,31 @@ * * @param renderer {CanvasRenderer} The renderer */ -DisplayObjectContainer.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0) { +DisplayObjectContainer.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -528,13 +596,16 @@ * @param renderer {WebGLRenderer|CanvasRenderer} The renderer * @private */ -DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) { +DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) +{ this._cachedSprite.worldAlpha = this.worldAlpha; - if (renderer.gl) { + if (renderer.gl) + { this._cachedSprite.renderWebGL(renderer); } - else { + else + { this._cachedSprite.renderCanvas(renderer); } }; @@ -544,10 +615,12 @@ * * @private */ -DisplayObjectContainer.prototype._generateCachedSprite = function () { +DisplayObjectContainer.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { // TODO - RenderTexture now *requires* a renderer instance, so this is like broken // because `renderer` isn't actually in scope here :P var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0); @@ -555,7 +628,8 @@ this._cachedSprite = new Sprite(renderTexture); this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.texture.resize(bounds.width | 0, bounds.height | 0); } @@ -580,8 +654,10 @@ * * @private */ -DisplayObjectContainer.prototype._destroyCachedSprite = function () { - if (!this._cachedSprite) { +DisplayObjectContainer.prototype._destroyCachedSprite = function () +{ + if (!this._cachedSprite) + { return; } diff --git a/src/core/display/Sprite.js b/src/core/display/Sprite.js index 707da24..5862aef 100644 --- a/src/core/display/Sprite.js +++ b/src/core/display/Sprite.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param texture {Texture} The texture for this sprite */ -function Sprite(texture) { +function Sprite(texture) +{ DisplayObjectContainer.call(this); /** @@ -85,12 +86,14 @@ this.texture = texture || Texture.EMPTY; } -Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) { +Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) +{ DisplayObjectContainer.prototype.destroy.call(this); this.anchor = null; - if (destroyTexture) { + if (destroyTexture) + { this._texture.destroy(destroyBaseTexture); } @@ -111,10 +114,12 @@ * @memberof Sprite# */ width: { - get: function () { + get: function () + { return this.scale.x * this.texture.frame.width; }, - set: function (value) { + set: function (value) + { this.scale.x = value / this.texture.frame.width; this._width = value; } @@ -127,10 +132,12 @@ * @memberof Sprite# */ height: { - get: function () { + get: function () + { return this.scale.y * this.texture.frame.height; }, - set: function (value) { + set: function (value) + { this.scale.y = value / this.texture.frame.height; this._height = value; } @@ -143,23 +150,29 @@ * @memberof Sprite# */ texture: { - get: function () { + get: function () + { return this._texture; }, - set: function (value) { - if (this._texture === value) { + set: function (value) + { + if (this._texture === value) + { return; } this._texture = value; this.cachedTint = 0xFFFFFF; - if (value) { + if (value) + { // wait for the texture to load - if (value.baseTexture.hasLoaded) { + if (value.baseTexture.hasLoaded) + { this._onTextureUpdate(); } - else { + else + { value.once('update', this._onTextureUpdate.bind(this)); } } @@ -172,18 +185,22 @@ * * @private */ -Sprite.prototype._onTextureUpdate = function () { +Sprite.prototype._onTextureUpdate = function () +{ // so if _width is 0 then width was not set.. - if (this._width) { + if (this._width) + { this.scale.x = this._width / this.texture.frame.width; } - if (this._height) { + if (this._height) + { this.scale.y = this._height / this.texture.frame.height; } }; -Sprite.prototype._renderWebGL = function (renderer) { +Sprite.prototype._renderWebGL = function (renderer) +{ // this is where content gets renderd.. // watch this space for a little render state manager.. @@ -197,7 +214,8 @@ * @param matrix {Matrix} the transformation matrix of the sprite * @return {Rectangle} the framing rectangle */ -Sprite.prototype.getBounds = function (matrix) { +Sprite.prototype.getBounds = function (matrix) +{ var width = this.texture.frame.width; var height = this.texture.frame.height; @@ -224,11 +242,13 @@ if(b === 0 && c === 0) { // scale may be negative! - if (a < 0) { + if (a < 0) + { a *= -1; } - if (d < 0) { + if (d < 0) + { d *= -1; } @@ -293,28 +313,34 @@ * * @param renderer {CanvasRenderer} The renderer */ -Sprite.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) { +Sprite.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) + { return; } - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; renderer.context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } // Ignore null sources - if (this.texture.valid) { + if (this.texture.valid) + { var resolution = this.texture.baseTexture.resolution / renderer.resolution; renderer.context.globalAlpha = this.worldAlpha; // If smoothingEnabled is supported and we need to change the smoothing property for this texture - if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) { + if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) + { renderer.scaleMode = this.texture.baseTexture.scaleMode; renderer.context[renderer.smoothProperty] = (renderer.scaleMode === CONST.scaleModes.LINEAR); } @@ -324,7 +350,8 @@ var dy = (this.texture.trim ? this.texture.trim.y : 0) - (this.anchor.y * this.texture.trim.height); // Allow for pixel rounding - if (renderer.roundPixels) { + if (renderer.roundPixels) + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -337,7 +364,8 @@ dx = dx | 0; dy = dy | 0; } - else { + else + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -348,8 +376,10 @@ ); } - if (this.tint !== 0xFFFFFF) { - if (this.cachedTint !== this.tint) { + if (this.tint !== 0xFFFFFF) + { + if (this.cachedTint !== this.tint) + { this.cachedTint = this.tint; // TODO clean up caching - how to clean up the caches? @@ -368,7 +398,8 @@ this.texture.crop.height / resolution ); } - else { + else + { renderer.context.drawImage( this.texture.baseTexture.source, this.texture.crop.x, @@ -383,11 +414,13 @@ } } - for (var i = 0, j = this.children.length; i < j; i++) { + for (var i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -402,10 +435,12 @@ * @param frameId {String} The frame Id of the texture in the cache * @return {Sprite} A new Sprite using a texture from the texture cache matching the frameId */ -Sprite.fromFrame = function (frameId) { +Sprite.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache' + this); } @@ -420,6 +455,7 @@ * @param imageId {String} The image url of the texture * @return {Sprite} A new Sprite using a texture from the texture cache matching the image id */ -Sprite.fromImage = function (imageId, crossorigin, scaleMode) { +Sprite.fromImage = function (imageId, crossorigin, scaleMode) +{ return new Sprite(Texture.fromImage(imageId, crossorigin, scaleMode)); }; diff --git a/src/core/display/SpriteBatch.js b/src/core/display/SpriteBatch.js index 3187777..c196fef 100644 --- a/src/core/display/SpriteBatch.js +++ b/src/core/display/SpriteBatch.js @@ -12,7 +12,8 @@ * ```js * var container = new SpriteBatch(); * - * for(var i = 0; i < 100; ++i) { + * for(var i = 0; i < 100; ++i) + * { * var sprite = new PIXI.Sprite.fromImage("myImage.png"); * container.addChild(sprite); * } @@ -25,7 +26,8 @@ */ //TODO RENAME to PARTICLE CONTAINER? -function SpriteBatch() { +function SpriteBatch() +{ DisplayObjectContainer.call(this); } @@ -38,7 +40,8 @@ * * @private */ -SpriteBatch.prototype.updateTransform = function () { +SpriteBatch.prototype.updateTransform = function () +{ // TODO don't need to! this.displayObjectUpdateTransform(); // PIXI.DisplayObjectContainer.prototype.updateTransform.call( this ); @@ -50,8 +53,10 @@ * @param renderer {WebGLRenderer} The webgl renderer * @private */ -SpriteBatch.prototype.renderWebGL = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderWebGL = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -71,8 +76,10 @@ * @param renderer {CanvasRenderer} The canvas renderer * @private */ -SpriteBatch.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -84,10 +91,12 @@ this.displayObjectUpdateTransform(); - for (var i = 0; i < this.children.length; ++i) { + for (var i = 0; i < this.children.length; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -95,9 +104,11 @@ context.globalAlpha = this.worldAlpha * child.alpha; - if (child.rotation % (Math.PI * 2) === 0) { + if (child.rotation % (Math.PI * 2) === 0) + { // this is the fastest way to optimise! - if rotation is 0 then we can avoid any kind of setTransform call - if (isRotated) { + if (isRotated) + { context.setTransform( transform.a, transform.b, @@ -122,8 +133,10 @@ frame.height * child.scale.y ); } - else { - if (!isRotated) { + else + { + if (!isRotated) + { isRotated = true; } @@ -131,7 +144,8 @@ var childTransform = child.worldTransform; - if (renderer.roundPixels) { + if (renderer.roundPixels) + { context.setTransform( childTransform.a, childTransform.b, @@ -141,7 +155,8 @@ childTransform.ty | 0 ); } - else { + else + { context.setTransform( childTransform.a, childTransform.b, diff --git a/src/core/index.js b/src/core/index.js index 3954b6f..eb4a82b 100644 --- a/src/core/index.js +++ b/src/core/index.js @@ -58,11 +58,13 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRenderer: function (width, height, options, noWebGL) { + autoDetectRenderer: function (width, height, options, noWebGL) + { width = width || 800; height = height || 600; - if (!noWebGL && require('webgl-enabled')()) { + if (!noWebGL && require('webgl-enabled')()) + { return new core.WebGLRenderer(width, height, options); } @@ -87,7 +89,8 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRecommendedRenderer: function (width, height, options) { + autoDetectRecommendedRenderer: function (width, height, options) + { var isAndroid = /Android/i.test(navigator.userAgent); return core.autoDetectRenderer(width, height, options, isAndroid); diff --git a/src/core/math/Matrix.js b/src/core/math/Matrix.js index c2f87e2..2ff4848 100644 --- a/src/core/math/Matrix.js +++ b/src/core/math/Matrix.js @@ -10,7 +10,8 @@ * @class * @namespace PIXI */ -function Matrix() { +function Matrix() +{ /** * @member {number} * @default 1 @@ -63,7 +64,8 @@ * * @param array {number[]} The array that the matrix will be populated from. */ -Matrix.prototype.fromArray = function (array) { +Matrix.prototype.fromArray = function (array) +{ this.a = array[0]; this.b = array[1]; this.c = array[3]; @@ -78,14 +80,17 @@ * @param transpose {boolean} Whether we need to transpose the matrix or not * @return {number[]} the newly created array which contains the matrix */ -Matrix.prototype.toArray = function (transpose) { - if (!this.array) { +Matrix.prototype.toArray = function (transpose) +{ + if (!this.array) + { this.array = new Float32Array(9); } var array = this.array; - if (transpose) { + if (transpose) + { array[0] = this.a; array[1] = this.b; array[2] = 0; @@ -96,7 +101,8 @@ array[7] = this.ty; array[8] = 1; } - else { + else + { array[0] = this.a; array[1] = this.c; array[2] = this.tx; @@ -119,7 +125,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, transformed through this matrix */ -Matrix.prototype.apply = function (pos, newPos) { +Matrix.prototype.apply = function (pos, newPos) +{ newPos = newPos || new Point(); newPos.x = this.a * pos.x + this.c * pos.y + this.tx; @@ -136,7 +143,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, inverse-transformed through this matrix */ -Matrix.prototype.applyInverse = function (pos, newPos) { +Matrix.prototype.applyInverse = function (pos, newPos) +{ newPos = newPos || new Point(); var id = 1 / (this.a * this.d + this.c * -this.b); @@ -154,7 +162,8 @@ * @param {number} y * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.translate = function (x, y) { +Matrix.prototype.translate = function (x, y) +{ this.tx += x; this.ty += y; @@ -168,7 +177,8 @@ * @param {number} y The amount to scale vertically * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.scale = function (x, y) { +Matrix.prototype.scale = function (x, y) +{ this.a *= x; this.d *= y; this.c *= x; @@ -186,7 +196,8 @@ * @param {number} angle - The angle in radians. * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.rotate = function (angle) { +Matrix.prototype.rotate = function (angle) +{ var cos = Math.cos( angle ); var sin = Math.sin( angle ); @@ -210,7 +221,8 @@ * @param {Matrix} matrix * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.append = function (matrix) { +Matrix.prototype.append = function (matrix) +{ var a1 = this.a; var b1 = this.b; var c1 = this.c; @@ -232,7 +244,8 @@ * * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.identity = function () { +Matrix.prototype.identity = function () +{ this.a = 1; this.b = 0; this.c = 0; diff --git a/src/core/math/Point.js b/src/core/math/Point.js index 7565b2d..632f346 100644 --- a/src/core/math/Point.js +++ b/src/core/math/Point.js @@ -7,7 +7,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -function Point(x, y) { +function Point(x, y) +{ /** * @member {number} * @default 0 @@ -29,7 +30,8 @@ * * @return {Point} a copy of the point */ -Point.prototype.clone = function () { +Point.prototype.clone = function () +{ return new Point(this.x, this.y); }; @@ -40,7 +42,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -Point.prototype.set = function (x, y) { +Point.prototype.set = function (x, y) +{ this.x = x || 0; this.y = y || ( (y !== 0) ? this.x : 0 ) ; }; diff --git a/src/core/math/shapes/Circle.js b/src/core/math/shapes/Circle.js index 69cfdc9..4d76efc 100644 --- a/src/core/math/shapes/Circle.js +++ b/src/core/math/shapes/Circle.js @@ -10,7 +10,8 @@ * @param y {number} The Y coordinate of the center of this circle * @param radius {number} The radius of the circle */ -function Circle(x, y, radius) { +function Circle(x, y, radius) +{ /** * @member {number} * @default 0 @@ -46,7 +47,8 @@ * @method clone * @return {Circle} a copy of the Circle */ -Circle.prototype.clone = function () { +Circle.prototype.clone = function () +{ return new Circle(this.x, this.y, this.radius); }; @@ -58,8 +60,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Circle */ -Circle.prototype.contains = function (x, y) { - if (this.radius <= 0) { +Circle.prototype.contains = function (x, y) +{ + if (this.radius <= 0) + { return false; } @@ -79,6 +83,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Circle.prototype.getBounds = function () { +Circle.prototype.getBounds = function () +{ return new Rectangle(this.x - this.radius, this.y - this.radius, this.radius * 2, this.radius * 2); }; diff --git a/src/core/math/shapes/Ellipse.js b/src/core/math/shapes/Ellipse.js index 4f2d066..fefd01a 100644 --- a/src/core/math/shapes/Ellipse.js +++ b/src/core/math/shapes/Ellipse.js @@ -11,7 +11,8 @@ * @param width {number} The half width of this ellipse * @param height {number} The half height of this ellipse */ -function Ellipse(x, y, width, height) { +function Ellipse(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -53,7 +54,8 @@ * @method clone * @return {Ellipse} a copy of the ellipse */ -Ellipse.prototype.clone = function () { +Ellipse.prototype.clone = function () +{ return new Ellipse(this.x, this.y, this.width, this.height); }; @@ -65,8 +67,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coords are within this ellipse */ -Ellipse.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Ellipse.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } @@ -86,6 +90,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Ellipse.prototype.getBounds = function () { +Ellipse.prototype.getBounds = function () +{ return new Rectangle(this.x - this.width, this.y - this.height, this.width, this.height); }; diff --git a/src/core/math/shapes/Polygon.js b/src/core/math/shapes/Polygon.js index ae89148..fea6d37 100644 --- a/src/core/math/shapes/Polygon.js +++ b/src/core/math/shapes/Polygon.js @@ -10,16 +10,20 @@ * arguments passed can be flat x,y values e.g. `new Polygon(x,y, x,y, x,y, ...)` where `x` and `y` are * Numbers. */ -function Polygon(points) { +function Polygon(points) +{ //if points isn't an array, use arguments as the array - if (!(points instanceof Array)) { + if (!(points instanceof Array)) + { points = Array.prototype.slice.call(arguments); } //if this is a flat array of numbers, convert it to points - if (points[0] instanceof Point) { + if (points[0] instanceof Point) + { var p = []; - for (var i = 0, il = points.length; i < il; i++) { + for (var i = 0, il = points.length; i < il; i++) + { p.push(points[i].x, points[i].y); } @@ -51,7 +55,8 @@ * * @return {Polygon} a copy of the polygon */ -Polygon.prototype.clone = function () { +Polygon.prototype.clone = function () +{ return new Polygon(this.points.slice()); }; @@ -62,19 +67,22 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this polygon */ -Polygon.prototype.contains = function (x, y) { +Polygon.prototype.contains = function (x, y) +{ var inside = false; // use some raycasting to test hits // https://github.com/substack/point-in-polygon/blob/master/index.js var length = this.points.length / 2; - for (var i = 0, j = length - 1; i < length; j = i++) { + for (var i = 0, j = length - 1; i < length; j = i++) + { var xi = this.points[i * 2], yi = this.points[i * 2 + 1], xj = this.points[j * 2], yj = this.points[j * 2 + 1], intersect = ((yi > y) !== (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi); - if (intersect) { + if (intersect) + { inside = !inside; } } diff --git a/src/core/math/shapes/Rectangle.js b/src/core/math/shapes/Rectangle.js index 16ac62a..4008b68 100644 --- a/src/core/math/shapes/Rectangle.js +++ b/src/core/math/shapes/Rectangle.js @@ -10,7 +10,8 @@ * @param width {number} The overall width of this rectangle * @param height {number} The overall height of this rectangle */ -function Rectangle(x, y, width, height) { +function Rectangle(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -60,7 +61,8 @@ * * @return {Rectangle} a copy of the rectangle */ -Rectangle.prototype.clone = function () { +Rectangle.prototype.clone = function () +{ return new Rectangle(this.x, this.y, this.width, this.height); }; @@ -71,13 +73,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rectangle */ -Rectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Rectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/math/shapes/RoundedRectangle.js b/src/core/math/shapes/RoundedRectangle.js index 27d286e..7bf6411 100644 --- a/src/core/math/shapes/RoundedRectangle.js +++ b/src/core/math/shapes/RoundedRectangle.js @@ -11,7 +11,8 @@ * @param height {number} The overall height of this rounded rectangle * @param radius {number} Controls the radius of the rounded corners */ -function RoundedRectangle(x, y, width, height, radius) { +function RoundedRectangle(x, y, width, height, radius) +{ /** * @member {number} * @default 0 @@ -58,7 +59,8 @@ * * @return {RoundedRectangle} a copy of the rounded rectangle */ -RoundedRectangle.prototype.clone = function () { +RoundedRectangle.prototype.clone = function () +{ return new RoundedRectangle(this.x, this.y, this.width, this.height, this.radius); }; @@ -69,13 +71,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rounded Rectangle */ -RoundedRectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +RoundedRectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/primitives/Graphics.js b/src/core/primitives/Graphics.js index 261c534..e902d2a 100644 --- a/src/core/primitives/Graphics.js +++ b/src/core/primitives/Graphics.js @@ -16,7 +16,8 @@ * @extends DisplayObjectContainer * @namespace PIXI */ -function Graphics() { +function Graphics() +{ DisplayObjectContainer.call(this); this.renderable = true; @@ -154,16 +155,20 @@ * @private */ cacheAsBitmap: { - get: function () { + get: function () + { return this._cacheAsBitmap; }, - set: function (value) { + set: function (value) + { this._cacheAsBitmap = value; - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._generateCachedSprite(); } - else { + else + { this.destroyCachedSprite(); this.dirty = true; } @@ -176,7 +181,8 @@ * * @return {Graphics} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ var clone = new Graphics(); clone.renderable = this.renderable; @@ -192,7 +198,8 @@ clone.cachedSpriteDirty = this.cachedSpriteDirty; // copy graphics data - for (var i = 0; i < this.graphicsData.length; ++i) { + for (var i = 0; i < this.graphicsData.length; ++i) + { clone.graphicsData.push(this.graphicsData.clone()); } @@ -211,17 +218,21 @@ * @param alpha {number} alpha of the line to draw, will update the objects stored style * @return {Graphics} */ -Graphics.prototype.lineStyle = function (lineWidth, color, alpha) { +Graphics.prototype.lineStyle = function (lineWidth, color, alpha) +{ this.lineWidth = lineWidth || 0; this.lineColor = color || 0; this.lineAlpha = (arguments.length < 3) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length) + { // halfway through a line? start a new one! this.drawShape( new math.Polygon( this.currentPath.shape.points.slice(-2) )); } - else { + else + { // otherwise its empty so lets just set the line properties this.currentPath.lineWidth = this.lineWidth; this.currentPath.lineColor = this.lineColor; @@ -239,7 +250,8 @@ * @param y {number} the Y coordinate to move to * @return {Graphics} */ -Graphics.prototype.moveTo = function (x, y) { +Graphics.prototype.moveTo = function (x, y) +{ this.drawShape(new math.Polygon([x,y])); return this; @@ -253,7 +265,8 @@ * @param y {number} the Y coordinate to draw to * @return {Graphics} */ -Graphics.prototype.lineTo = function (x, y) { +Graphics.prototype.lineTo = function (x, y) +{ this.currentPath.shape.points.push(x, y); this.dirty = true; @@ -270,13 +283,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -285,7 +302,8 @@ n = 20, points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { this.moveTo(0, 0); } @@ -293,7 +311,8 @@ var fromY = points[points.length-1]; var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; xa = fromX + ( (cpX - fromX) * j ); @@ -319,13 +338,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -342,7 +365,8 @@ var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; dt = (1 - j); @@ -373,13 +397,17 @@ * @param radius {number} The radius of the arc * @return {Graphics} */ -Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points.push(x1, y1); } } - else { + else + { this.moveTo(x1, y1); } @@ -392,12 +420,15 @@ b2 = x2 - x1, mm = Math.abs(a1 * b2 - b1 * a2); - if (mm < 1.0e-8 || radius === 0) { - if (points[points.length-2] !== x1 || points[points.length-1] !== y1) { + if (mm < 1.0e-8 || radius === 0) + { + if (points[points.length-2] !== x1 || points[points.length-1] !== y1) + { points.push(x1, y1); } } - else { + else + { var dd = a1 * a1 + b1 * b1, cc = a2 * a2 + b2 * b2, tt = a1 * a2 + b1 * b2, @@ -433,42 +464,51 @@ * @param anticlockwise {boolean} Optional. Specifies whether the drawing should be counterclockwise or clockwise. False is default, and indicates clockwise, while true indicates counter-clockwise. * @return {Graphics} */ -Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) { +Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) +{ var startX = cx + Math.cos(startAngle) * radius; var startY = cy + Math.sin(startAngle) * radius; var points; // TODO - This if-else makes no sense. It uses currentPath in the else where it doesn't exist... - if (this.currentPath) { + if (this.currentPath) + { points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { points.push(startX, startY); } - else if (points[points.length-2] !== startX || points[points.length-1] !== startY) { + else if (points[points.length-2] !== startX || points[points.length-1] !== startY) + { points.push(startX, startY); } } - else { + else + { this.moveTo(startX, startY); points = this.currentPath.shape.points; } - if (startAngle === endAngle) { + if (startAngle === endAngle) + { return this; } - if (!anticlockwise && endAngle <= startAngle) { + if (!anticlockwise && endAngle <= startAngle) + { endAngle += Math.PI * 2; } - else if (anticlockwise && startAngle <= endAngle) { + else if (anticlockwise && startAngle <= endAngle) + { startAngle += Math.PI * 2; } var sweep = anticlockwise ? (startAngle - endAngle) *-1 : (endAngle - startAngle); var segs = (Math.abs(sweep)/ (Math.PI * 2)) * 40; - if (sweep === 0) { + if (sweep === 0) + { return this; } @@ -482,7 +522,8 @@ var remainder = ( segMinus % 1 ) / segMinus; - for (var i = 0; i <= segMinus; ++i) { + for (var i = 0; i <= segMinus; ++i) + { var real = i + remainder * i; var angle = ((theta) + startAngle + (theta2 * real)); @@ -506,13 +547,16 @@ * @param alpha {number} the alpha of the fill * @return {Graphics} */ -Graphics.prototype.beginFill = function (color, alpha) { +Graphics.prototype.beginFill = function (color, alpha) +{ this.filling = true; this.fillColor = color || 0; this.fillAlpha = (alpha === undefined) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length <= 2) + { this.currentPath.fill = this.filling; this.currentPath.fillColor = this.fillColor; this.currentPath.fillAlpha = this.fillAlpha; @@ -526,7 +570,8 @@ * * @return {Graphics} */ -Graphics.prototype.endFill = function () { +Graphics.prototype.endFill = function () +{ this.filling = false; this.fillColor = null; this.fillAlpha = 1; @@ -542,7 +587,8 @@ * @param height {number} The height of the rectangle * @return {Graphics} */ -Graphics.prototype.drawRect = function ( x, y, width, height ) { +Graphics.prototype.drawRect = function ( x, y, width, height ) +{ this.drawShape(new math.Rectangle(x,y, width, height)); return this; @@ -556,7 +602,8 @@ * @param height {number} The height of the rectangle * @param radius {number} Radius of the rectangle corners */ -Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) { +Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) +{ this.drawShape(new math.RoundedRectangle(x, y, width, height, radius)); return this; @@ -570,7 +617,8 @@ * @param radius {number} The radius of the circle * @return {Graphics} */ -Graphics.prototype.drawCircle = function (x, y, radius) { +Graphics.prototype.drawCircle = function (x, y, radius) +{ this.drawShape(new math.Circle(x,y, radius)); return this; @@ -585,7 +633,8 @@ * @param height {number} The half height of the ellipse * @return {Graphics} */ -Graphics.prototype.drawEllipse = function (x, y, width, height) { +Graphics.prototype.drawEllipse = function (x, y, width, height) +{ this.drawShape(new math.Ellipse(x, y, width, height)); return this; @@ -597,8 +646,10 @@ * @param path {Array} The path data used to construct the polygon. * @return {Graphics} */ -Graphics.prototype.drawPolygon = function (path) { - if (!(path instanceof Array)) { +Graphics.prototype.drawPolygon = function (path) +{ + if (!(path instanceof Array)) + { path = Array.prototype.slice.call(arguments); } @@ -612,7 +663,8 @@ * * @return {Graphics} */ -Graphics.prototype.clear = function () { +Graphics.prototype.clear = function () +{ this.lineWidth = 0; this.filling = false; @@ -631,7 +683,8 @@ * @param scaleMode {number} Should be one of the scaleMode consts * @return {Texture} a texture of the graphics object */ -Graphics.prototype.generateTexture = function (resolution, scaleMode) { +Graphics.prototype.generateTexture = function (resolution, scaleMode) +{ resolution = resolution || 1; var bounds = this.getBounds(); @@ -655,17 +708,21 @@ * * @param renderer {WebGLRenderer} */ -Graphics.prototype._renderWebGL = function (renderer) { +Graphics.prototype._renderWebGL = function (renderer) +{ // if the sprite is not visible or the alpha is 0 then no need to render this element - if (this.isMask === true) { + if (this.isMask === true) + { return; } // this code may still be needed so leaving for now.. - // + // /* - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture on the gpu too! @@ -681,17 +738,24 @@ return; } - */ - - // check if the webgl graphic needs to be updated - if (this.glDirty) { - this.dirty = true; - this.glDirty = false; - } + else */ - renderer.setObjectRendererer(renderer.graphicsRenderer); - renderer.graphicsRenderer.render(this); + renderer.spriteBatch.stop(); + renderer.blendModeManager.setBlendMode(this.blendMode); + // check blend mode + renderer.blendModeManager.setBlendMode( this.blendMode ); + + // check if the webgl graphic needs to be updated + if (this.glDirty) + { + this.dirty = true; + this.glDirty = false; + } + + WebGLGraphics.renderGraphics(this, renderer); + + renderer.spriteBatch.start(); }; /** @@ -700,14 +764,18 @@ * @param renderer {CanvasRenderer} * @private */ -Graphics.prototype.renderCanvas = function (renderer) { +Graphics.prototype.renderCanvas = function (renderer) +{ // 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.isMask === true) { + if (!this.visible || this.alpha <= 0 || this.isMask === true) + { return; } - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture @@ -723,16 +791,19 @@ return; } - else { + else + { var context = renderer.context; var transform = this.worldTransform; - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } @@ -748,11 +819,13 @@ CanvasGraphics.renderGraphics(this, context); - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } } @@ -763,13 +836,16 @@ * * @return {Rectangle} the rectangular bounding area */ -Graphics.prototype.getBounds = function (matrix) { +Graphics.prototype.getBounds = function (matrix) +{ // return an empty object if the item is a mask! - if (this.isMask) { + if (this.isMask) + { return math.Rectangle.EMPTY; } - if (this.dirty) { + if (this.dirty) + { this.updateLocalBounds(); this.glDirty = true; @@ -841,23 +917,27 @@ * Update the bounds of the object * */ -Graphics.prototype.updateLocalBounds = function () { +Graphics.prototype.updateLocalBounds = function () +{ var minX = Infinity; var maxX = -Infinity; var minY = Infinity; var maxY = -Infinity; - if (this.graphicsData.length) { + if (this.graphicsData.length) + { var shape, points, x, y, w, h; - for (var i = 0; i < this.graphicsData.length; i++) { + for (var i = 0; i < this.graphicsData.length; i++) + { var data = this.graphicsData[i]; var type = data.type; var lineWidth = data.lineWidth; shape = data.shape; - if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) { + if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) + { x = shape.x - lineWidth/2; y = shape.y - lineWidth/2; w = shape.width + lineWidth; @@ -869,7 +949,8 @@ minY = y < minY ? y : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.CIRC) { + else if (type === CONST.SHAPES.CIRC) + { x = shape.x; y = shape.y; w = shape.radius + lineWidth/2; @@ -881,7 +962,8 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.ELIP) { + else if (type === CONST.SHAPES.ELIP) + { x = shape.x; y = shape.y; w = shape.width + lineWidth/2; @@ -893,11 +975,13 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else { + else + { // POLY points = shape.points; - for (var j = 0; j < points.length; j += 2) { + for (var j = 0; j < points.length; j += 2) + { x = points[j]; y = points[j+1]; @@ -910,7 +994,8 @@ } } } - else { + else + { minX = 0; maxX = 0; minY = 0; @@ -931,10 +1016,12 @@ * * @private */ -Graphics.prototype._generateCachedSprite = function () { +Graphics.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { var canvasBuffer = new CanvasBuffer(bounds.width, bounds.height); var texture = Texture.fromCanvas(canvasBuffer.canvas); @@ -943,7 +1030,8 @@ this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.buffer.resize(bounds.width, bounds.height); } @@ -968,7 +1056,8 @@ * * @private */ -Graphics.prototype.updateCachedSpriteTexture = function () { +Graphics.prototype.updateCachedSpriteTexture = function () +{ var cachedSprite = this._cachedSprite; var texture = cachedSprite.texture; var canvas = cachedSprite.buffer.canvas; @@ -989,7 +1078,8 @@ * Destroys a previous cached sprite. * */ -Graphics.prototype.destroyCachedSprite = function () { +Graphics.prototype.destroyCachedSprite = function () +{ this._cachedSprite.texture.destroy(true); // let the gc collect the unused sprite @@ -1003,10 +1093,13 @@ * @param {Circle|Rectangle|Ellipse|Line|Polygon} shape The Shape object to draw. * @return {GraphicsData} The generated GraphicsData object. */ -Graphics.prototype.drawShape = function (shape) { - if (this.currentPath) { +Graphics.prototype.drawShape = function (shape) +{ + if (this.currentPath) + { // check current path! - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath.shape.points.length <= 2) + { this.graphicsData.pop(); } } @@ -1017,7 +1110,8 @@ this.graphicsData.push(data); - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { data.shape.closed = this.filling; this.currentPath = data; } diff --git a/src/core/primitives/GraphicsData.js b/src/core/primitives/GraphicsData.js index 99decbe..788f6f2 100644 --- a/src/core/primitives/GraphicsData.js +++ b/src/core/primitives/GraphicsData.js @@ -4,7 +4,8 @@ * @class * @namespace PIXI */ -function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) { +function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) +{ this.lineWidth = lineWidth; this.lineColor = lineColor; this.lineAlpha = lineAlpha; @@ -27,7 +28,8 @@ * * @return {GraphicsData} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ return new GraphicsData( this.lineWidth, this.lineColor, diff --git a/src/core/renderers/canvas/CanvasRenderer.js b/src/core/renderers/canvas/CanvasRenderer.js index 15a0978..7aebd44 100644 --- a/src/core/renderers/canvas/CanvasRenderer.js +++ b/src/core/renderers/canvas/CanvasRenderer.js @@ -17,17 +17,22 @@ * @param [options.resolution=1] {number} the resolution of the renderer retina would be 2 * @param [options.clearBeforeRender=true] {boolean} This sets if the CanvasRenderer will clear the canvas or not before the new render pass. */ -function CanvasRenderer(width, height, options) { +function CanvasRenderer(width, height, options) +{ utils.sayHello('Canvas'); - if (options) { - for (var i in CONST.defaultRenderOptions) { - if (typeof options[i] === 'undefined') { + if (options) + { + for (var i in CONST.defaultRenderOptions) + { + if (typeof options[i] === 'undefined') + { options[i] = CONST.defaultRenderOptions[i]; } } } - else { + else + { options = CONST.defaultRenderOptions; } @@ -156,19 +161,24 @@ this.smoothProperty = null; - if (this.context.imageSmoothingEnabled) { + if (this.context.imageSmoothingEnabled) + { this.smoothProperty = 'imageSmoothingEnabled'; } - else if (this.context.webkitImageSmoothingEnabled) { + else if (this.context.webkitImageSmoothingEnabled) + { this.smoothProperty = 'webkitImageSmoothingEnabled'; } - else if (this.context.mozImageSmoothingEnabled) { + else if (this.context.mozImageSmoothingEnabled) + { this.smoothProperty = 'mozImageSmoothingEnabled'; } - else if (this.context.oImageSmoothingEnabled) { + else if (this.context.oImageSmoothingEnabled) + { this.smoothProperty = 'oImageSmoothingEnabled'; } - else if (this.context.msImageSmoothingEnabled) { + else if (this.context.msImageSmoothingEnabled) + { this.smoothProperty = 'msImageSmoothingEnabled'; } @@ -193,10 +203,12 @@ * @memberof CanvasRenderer# */ backgroundColor: { - get: function () { + get: function () + { return this._backgroundColor; }, - set: function (val) { + set: function (val) + { this._backgroundColor = val; this._backgroundColorString = utils.hex2string(val); } @@ -208,7 +220,8 @@ * * @param object {DisplayObject} the object to be rendered */ -CanvasRenderer.prototype.render = function (object) { +CanvasRenderer.prototype.render = function (object) +{ object.updateTransform(); this.context.setTransform(1,0,0,1,0,0); @@ -218,16 +231,20 @@ this.currentBlendMode = CONST.blendModes.NORMAL; this.context.globalCompositeOperation = this.blendModes[CONST.blendModes.NORMAL]; - if (navigator.isCocoonJS && this.view.screencanvas) { + if (navigator.isCocoonJS && this.view.screencanvas) + { this.context.fillStyle = 'black'; this.context.clear(); } - if (this.clearBeforeRender) { - if (this.transparent) { + if (this.clearBeforeRender) + { + if (this.transparent) + { this.context.clearRect(0, 0, this.width, this.height); } - else { + else + { this.context.fillStyle = this._backgroundColorString; this.context.fillRect(0, 0, this.width , this.height); } @@ -241,8 +258,10 @@ * * @param [removeView=false] {boolean} Removes the Canvas element from the DOM. */ -CanvasRenderer.prototype.destroy = function (removeView) { - if (removeView && this.view.parent) { +CanvasRenderer.prototype.destroy = function (removeView) +{ + if (removeView && this.view.parent) + { this.view.parent.removeChild(this.view); } @@ -257,14 +276,16 @@ * @param width {number} the new width of the canvas view * @param height {number} the new height of the canvas view */ -CanvasRenderer.prototype.resize = function (width, height) { +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) { + if (this.autoResize) + { this.view.style.width = this.width / this.resolution + 'px'; this.view.style.height = this.height / this.resolution + 'px'; } @@ -276,7 +297,8 @@ * @param displayObject {DisplayObject} The displayObject to render * @private */ -CanvasRenderer.prototype.renderDisplayObject = function (displayObject) { +CanvasRenderer.prototype.renderDisplayObject = function (displayObject) +{ displayObject.renderCanvas(this); }; @@ -285,11 +307,14 @@ * * @private */ -CanvasRenderer.prototype._mapBlendModes = function () { - if (!this.blendModes) { +CanvasRenderer.prototype._mapBlendModes = function () +{ + if (!this.blendModes) + { this.blendModes = {}; - if (utils.canUseNewCanvasBlendModes()) { + if (utils.canUseNewCanvasBlendModes()) + { this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? this.blendModes[CONST.blendModes.MULTIPLY] = 'multiply'; @@ -308,7 +333,8 @@ this.blendModes[CONST.blendModes.COLOR] = 'color'; this.blendModes[CONST.blendModes.LUMINOSITY] = 'luminosity'; } - else { + else + { // this means that the browser does not support the cool new blend modes in canvas 'cough' ie 'cough' this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? diff --git a/src/core/renderers/canvas/utils/CanvasBuffer.js b/src/core/renderers/canvas/utils/CanvasBuffer.js index ebe5d47..b183a66 100644 --- a/src/core/renderers/canvas/utils/CanvasBuffer.js +++ b/src/core/renderers/canvas/utils/CanvasBuffer.js @@ -6,7 +6,8 @@ * @param width {number} the width for the newly created canvas * @param height {number} the height for the newly created canvas */ -function CanvasBuffer(width, height) { +function CanvasBuffer(width, height) +{ /** * The Canvas object that belongs to this CanvasBuffer. * @@ -36,10 +37,12 @@ * @memberof CanvasBuffer# */ width: { - get: function () { + get: function () + { return this.canvas.width; }, - set: function (val) { + set: function (val) + { this.canvas.width = val; } }, @@ -50,10 +53,12 @@ * @memberof CanvasBuffer# */ height: { - get: function () { + get: function () + { return this.canvas.height; }, - set: function (val) { + set: function (val) + { this.canvas.height = val; } } @@ -64,7 +69,8 @@ * * @private */ -CanvasBuffer.prototype.clear = function () { +CanvasBuffer.prototype.clear = function () +{ this.context.setTransform(1, 0, 0, 1, 0, 0); this.context.clearRect(0,0, this.canvas.width, this.canvas.height); }; @@ -75,7 +81,8 @@ * @param width {number} the new width of the canvas * @param height {number} the new height of the canvas */ -CanvasBuffer.prototype.resize = function (width, height) { +CanvasBuffer.prototype.resize = function (width, height) +{ this.canvas.width = width; this.canvas.height = height; }; diff --git a/src/core/renderers/canvas/utils/CanvasGraphics.js b/src/core/renderers/canvas/utils/CanvasGraphics.js index c7eaa2a..3f2a91f 100644 --- a/src/core/renderers/canvas/utils/CanvasGraphics.js +++ b/src/core/renderers/canvas/utils/CanvasGraphics.js @@ -13,15 +13,18 @@ * @param graphics {Graphics} the actual graphics object to render * @param context {CanvasRenderingContext2D} the 2d drawing method of the canvas */ -CanvasGraphics.renderGraphics = function (graphics, context) { +CanvasGraphics.renderGraphics = function (graphics, context) +{ var worldAlpha = graphics.worldAlpha; - if (graphics.dirty) { + if (graphics.dirty) + { this.updateGraphicsTint(graphics); graphics.dirty = false; } - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; @@ -30,69 +33,82 @@ context.lineWidth = data.lineWidth; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { context.beginPath(); var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } - if (shape.closed) { + if (shape.closed) + { context.lineTo(points[0], points[1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fillRect(shape.x, shape.y, shape.width, shape.height); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.strokeRect(shape.x, shape.y, shape.width, shape.height); } } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.beginPath(); context.arc(shape.x, shape.y, shape.radius,0,2*Math.PI); context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas var w = shape.width * 2; @@ -119,18 +135,21 @@ context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; var width = shape.width; @@ -152,13 +171,15 @@ context.quadraticCurveTo(rx, ry, rx, ry + radius); context.closePath(); - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); @@ -174,45 +195,54 @@ * @param graphics {Graphics} the graphics which will be used as a mask * @param context {CanvasRenderingContext2D} the context 2d method of the canvas */ -CanvasGraphics.renderGraphicsMask = function (graphics, context) { +CanvasGraphics.renderGraphicsMask = function (graphics, context) +{ var len = graphics.graphicsData.length; - if (len === 0) { + if (len === 0) + { return; } context.beginPath(); - for (var i = 0; i < len; i++) { + for (var i = 0; i < len; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { context.rect(shape.x, shape.y, shape.width, shape.height); context.closePath(); } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.arc(shape.x, shape.y, shape.radius, 0, 2 * Math.PI); context.closePath(); } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas @@ -237,7 +267,8 @@ context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); context.closePath(); } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; @@ -262,8 +293,10 @@ } }; -CanvasGraphics.updateGraphicsTint = function (graphics) { - if (graphics.tint === 0xFFFFFF) { +CanvasGraphics.updateGraphicsTint = function (graphics) +{ + if (graphics.tint === 0xFFFFFF) + { return; } @@ -271,7 +304,8 @@ var tintG = (graphics.tint >> 8 & 0xFF) / 255; var tintB = (graphics.tint & 0xFF)/ 255; - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var fillColor = data.fillColor | 0; diff --git a/src/core/renderers/canvas/utils/CanvasMaskManager.js b/src/core/renderers/canvas/utils/CanvasMaskManager.js index e04a733..9827d36 100644 --- a/src/core/renderers/canvas/utils/CanvasMaskManager.js +++ b/src/core/renderers/canvas/utils/CanvasMaskManager.js @@ -6,7 +6,8 @@ * @class * @namespace PIXI */ -function CanvasMaskManager() {} +function CanvasMaskManager() +{} CanvasMaskManager.prototype.constructor = CanvasMaskManager; module.exports = CanvasMaskManager; @@ -17,7 +18,8 @@ * @param maskData {object} the maskData that will be pushed * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.pushMask = function (maskData, renderer) { +CanvasMaskManager.prototype.pushMask = function (maskData, renderer) +{ renderer.context.save(); var cacheAlpha = maskData.alpha; @@ -45,6 +47,7 @@ * * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.popMask = function (renderer) { +CanvasMaskManager.prototype.popMask = function (renderer) +{ renderer.context.restore(); }; diff --git a/src/core/renderers/canvas/utils/CanvasTinter.js b/src/core/renderers/canvas/utils/CanvasTinter.js index 17e0529..d2fb1bc 100644 --- a/src/core/renderers/canvas/utils/CanvasTinter.js +++ b/src/core/renderers/canvas/utils/CanvasTinter.js @@ -14,7 +14,8 @@ * @param color {number} the color to use to tint the sprite with * @return {HTMLCanvasElement} The tinted canvas */ -CanvasTinter.getTintedTexture = function (sprite, color) { +CanvasTinter.getTintedTexture = function (sprite, color) +{ var texture = sprite.texture; color = CanvasTinter.roundColor(color); @@ -23,7 +24,8 @@ texture.tintCache = texture.tintCache || {}; - if (texture.tintCache[stringColor]) { + if (texture.tintCache[stringColor]) + { return texture.tintCache[stringColor]; } @@ -33,14 +35,16 @@ //CanvasTinter.tintWithPerPixel(texture, stringColor, canvas); CanvasTinter.tintMethod(texture, color, canvas); - if (CanvasTinter.convertTintToImage) { + if (CanvasTinter.convertTintToImage) + { // is this better? var tintImage = new Image(); tintImage.src = canvas.toDataURL(); texture.tintCache[stringColor] = tintImage; } - else { + else + { texture.tintCache[stringColor] = canvas; // if we are not converting the texture to an image then we need to lose the reference to the canvas CanvasTinter.canvas = null; @@ -56,7 +60,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithMultiply = function (texture, color, canvas) { +CanvasTinter.tintWithMultiply = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -104,7 +109,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithOverlay = function (texture, color, canvas) { +CanvasTinter.tintWithOverlay = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -139,7 +145,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithPerPixel = function (texture, color, canvas) { +CanvasTinter.tintWithPerPixel = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -167,7 +174,8 @@ var pixels = pixelData.data; - for (var i = 0; i < pixels.length; i += 4) { + for (var i = 0; i < pixels.length; i += 4) + { pixels[i+0] *= r; pixels[i+1] *= g; pixels[i+2] *= b; @@ -181,7 +189,8 @@ * * @param color {number} the color to round, should be a hex color */ -CanvasTinter.roundColor = function (color) { +CanvasTinter.roundColor = function (color) +{ var step = CanvasTinter.cacheStepsPerColorChannel; var rgbValues = utils.hex2rgb(color); diff --git a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js index 9f2f89a..35edbaf 100644 --- a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js +++ b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLBlendModeManager(renderer) { +function WebGLBlendModeManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -23,8 +24,10 @@ * * @param blendMode {number} the blendMode, should be a Pixi const, such as BlendModes.ADD */ -WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) { - if (this.currentBlendMode === blendMode) { +WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) +{ + if (this.currentBlendMode === blendMode) + { return false; } diff --git a/src/core/renderers/webgl/managers/WebGLFilterManager.js b/src/core/renderers/webgl/managers/WebGLFilterManager.js index 1179258..2dac048 100644 --- a/src/core/renderers/webgl/managers/WebGLFilterManager.js +++ b/src/core/renderers/webgl/managers/WebGLFilterManager.js @@ -7,7 +7,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLFilterManager(renderer) { +function WebGLFilterManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -32,7 +33,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.texturePool.length = 0; self.initShaderBuffers(); }); @@ -46,7 +48,8 @@ * @param renderer {WebGLRenderer} * @param buffer {ArrayBuffer} */ -WebGLFilterManager.prototype.begin = function (buffer) { +WebGLFilterManager.prototype.begin = function (buffer) +{ this.defaultShader = this.renderer.shaderManager.defaultShader; this.width = this.renderer.projection.x * 2; @@ -60,7 +63,8 @@ * * @param filterBlock {object} the filter that will be pushed to the current filter stack */ -WebGLFilterManager.prototype.pushFilter = function (filterBlock) { +WebGLFilterManager.prototype.pushFilter = function (filterBlock) +{ var gl = this.renderer.gl; var projection = this.renderer.projection; @@ -78,10 +82,12 @@ this.offsetY += filterBlock._filterArea.y; var texture = this.texturePool.pop(); - if (!texture) { + if (!texture) + { texture = new FilterTexture(this.renderer.gl, this.width, this.height); } - else { + else + { texture.resize(this.width, this.height); } @@ -98,29 +104,35 @@ var localX = filterArea.x, localY = filterArea.y; - if (filterArea.x < 0) { + if (filterArea.x < 0) + { filterArea.width += filterArea.x; filterArea.x = 0; } - if (filterArea.y < 0) { + if (filterArea.y < 0) + { filterArea.height += filterArea.y; filterArea.y = 0; } - if (localX + filterArea.width > this.width) { + if (localX + filterArea.width > this.width) + { filterArea.width = this.width - localX; } - if (localY + filterArea.height > this.height) { + if (localY + filterArea.height > this.height) + { filterArea.height = this.height - localY; } - if (filterArea.width < 0) { + if (filterArea.width < 0) + { filterArea.width = 0; } - if (filterArea.height < 0) { + if (filterArea.height < 0) + { filterArea.height = 0; } @@ -154,7 +166,8 @@ * Removes the last filter from the filter stack and doesn't return it. * */ -WebGLFilterManager.prototype.popFilter = function () { +WebGLFilterManager.prototype.popFilter = function () +{ var gl = this.renderer.gl; var filterBlock = this.filterStack.pop(); @@ -163,7 +176,8 @@ var projection = this.renderer.projection; var offset = this.renderer.offset; - if (filterBlock.filterPasses.length > 1) { + if (filterBlock.filterPasses.length > 1) + { gl.viewport(0, 0, filterArea.width, filterArea.height); gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); @@ -193,7 +207,8 @@ var inputTexture = texture; var outputTexture = this.texturePool.pop(); - if (!outputTexture) { + if (!outputTexture) + { outputTexture = new FilterTexture(this.renderer.gl, this.width, this.height); } outputTexture.resize(this.width, this.height); @@ -204,7 +219,8 @@ gl.disable(gl.BLEND); - for (var i = 0; i < filterBlock.filterPasses.length-1; i++) { + for (var i = 0; i < filterBlock.filterPasses.length-1; i++) + { var filterPass = filterBlock.filterPasses[i]; gl.bindFramebuffer(gl.FRAMEBUFFER, outputTexture.frameBuffer ); @@ -243,10 +259,12 @@ var buffer = this.buffer; // time to render the filters texture to the previous scene - if (this.filterStack.length === 0) { + if (this.filterStack.length === 0) + { gl.colorMask(true, true, true, true);//this.transparent); } - else { + else + { var currentFilter = this.filterStack[this.filterStack.length-1]; filterArea = currentFilter._filterArea; @@ -332,13 +350,15 @@ * @param width {number} the horizontal range of the filter * @param height {number} the vertical range of the filter */ -WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) { +WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) +{ // use program var gl = this.renderer.gl; var shader = filter.shaders[gl.id]; - if (!shader) { + if (!shader) + { shader = new Shader(gl); shader.fragmentSrc = filter.fragmentSrc; @@ -356,7 +376,8 @@ gl.uniform2f(shader.projectionVector, width/2, -height/2); gl.uniform2f(shader.offsetVector, 0,0); - if (filter.uniforms.dimensions) { + 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]; @@ -386,7 +407,8 @@ * Initialises the shader buffers. * */ -WebGLFilterManager.prototype.initShaderBuffers = function () { +WebGLFilterManager.prototype.initShaderBuffers = function () +{ var gl = this.renderer.gl; // create some buffers @@ -432,7 +454,8 @@ * Destroys the filter and removes it from the filter stack. * */ -WebGLFilterManager.prototype.destroy = function () { +WebGLFilterManager.prototype.destroy = function () +{ var gl = this.renderer.gl; this.filterStack = null; @@ -441,7 +464,8 @@ this.offsetY = 0; // destroy textures - for (var i = 0; i < this.texturePool.length; i++) { + for (var i = 0; i < this.texturePool.length; i++) + { this.texturePool[i].destroy(); } diff --git a/src/core/renderers/webgl/managers/WebGLManager.js b/src/core/renderers/webgl/managers/WebGLManager.js index 9d47b5c..c30cd51 100644 --- a/src/core/renderers/webgl/managers/WebGLManager.js +++ b/src/core/renderers/webgl/managers/WebGLManager.js @@ -3,7 +3,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLManager(renderer) { +function WebGLManager(renderer) +{ /** * The renderer this manager works for. * @@ -15,6 +16,7 @@ WebGLManager.prototype.constructor = WebGLManager; module.exports = WebGLManager; -WebGLManager.prototype.destroy = function () { +WebGLManager.prototype.destroy = function () +{ this.renderer = null; }; diff --git a/src/core/renderers/webgl/managers/WebGLMaskManager.js b/src/core/renderers/webgl/managers/WebGLMaskManager.js index 2f90b64..e568812 100644 --- a/src/core/renderers/webgl/managers/WebGLMaskManager.js +++ b/src/core/renderers/webgl/managers/WebGLMaskManager.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLMaskManager(renderer) { +function WebGLMaskManager(renderer) +{ WebGLManager.call(this, renderer); } @@ -19,12 +20,15 @@ * * @param maskData {any[]} */ -WebGLMaskManager.prototype.pushMask = function (maskData) { - if (maskData.dirty) { +WebGLMaskManager.prototype.pushMask = function (maskData) +{ + if (maskData.dirty) + { WebGLGraphics.updateGraphics(maskData, this.renderer.gl); } - if (!maskData._webGL[this.renderer.gl.id].data.length) { + if (!maskData._webGL[this.renderer.gl.id].data.length) + { return; } @@ -36,6 +40,7 @@ * * @param maskData {any[]} */ -WebGLMaskManager.prototype.popMask = function (maskData) { +WebGLMaskManager.prototype.popMask = function (maskData) +{ this.renderer.stencilManager.popStencil(maskData, maskData._webGL[this.renderer.gl.id].data[0], this.renderer); }; diff --git a/src/core/renderers/webgl/managers/WebGLShaderManager.js b/src/core/renderers/webgl/managers/WebGLShaderManager.js index fef071c..90c6477 100644 --- a/src/core/renderers/webgl/managers/WebGLShaderManager.js +++ b/src/core/renderers/webgl/managers/WebGLShaderManager.js @@ -10,7 +10,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLShaderManager(renderer) { +function WebGLShaderManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -28,7 +29,8 @@ */ this.tempAttribState = []; - for (var i = 0; i < this.maxAttibs; i++) { + for (var i = 0; i < this.maxAttibs; i++) + { this.attribState[i] = false; } @@ -66,7 +68,8 @@ // listen for context and update necessary shaders var self = this; - this.renderer.on('context', function (event) { + this.renderer.on('context', function (event) + { var gl = event.data; // this shader is used for rendering primitives @@ -97,29 +100,36 @@ * * @param attribs {Array} attribs */ -WebGLShaderManager.prototype.setAttribs = function (attribs) { +WebGLShaderManager.prototype.setAttribs = function (attribs) +{ // reset temp state var i; - for (i = 0; i < this.tempAttribState.length; i++) { + for (i = 0; i < this.tempAttribState.length; i++) + { this.tempAttribState[i] = false; } // set the new attribs - for (var a in attribs) { + for (var a in attribs) + { this.tempAttribState[attribs[a]] = true; } var gl = this.renderer.gl; - for (i = 0; i < this.attribState.length; i++) { - if (this.attribState[i] !== this.tempAttribState[i]) { + for (i = 0; i < this.attribState.length; i++) + { + if (this.attribState[i] !== this.tempAttribState[i]) + { this.attribState[i] = this.tempAttribState[i]; - if (this.attribState[i]) { + if (this.attribState[i]) + { gl.enableVertexAttribArray(i); } - else { + else + { gl.disableVertexAttribArray(i); } } @@ -131,8 +141,10 @@ * * @param shader {Any} */ -WebGLShaderManager.prototype.setShader = function (shader) { - if (this._currentId === shader.uuid) { +WebGLShaderManager.prototype.setShader = function (shader) +{ + if (this._currentId === shader.uuid) + { return false; } @@ -150,7 +162,8 @@ * Destroys this object. * */ -WebGLShaderManager.prototype.destroy = function () { +WebGLShaderManager.prototype.destroy = function () +{ this.attribState = null; this.tempAttribState = null; diff --git a/src/core/renderers/webgl/managers/WebGLStencilManager.js b/src/core/renderers/webgl/managers/WebGLStencilManager.js index 9ec6398..4cb0134 100644 --- a/src/core/renderers/webgl/managers/WebGLStencilManager.js +++ b/src/core/renderers/webgl/managers/WebGLStencilManager.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLStencilManager(renderer) { +function WebGLStencilManager(renderer) +{ WebGLManager.call(this, renderer); this.stencilStack = []; @@ -24,12 +25,14 @@ * @param graphics {Graphics} * @param webGLData {any[]} */ -WebGLStencilManager.prototype.pushStencil = function (graphics, webGLData) { +WebGLStencilManager.prototype.pushStencil = function (graphics, webGLData) +{ var gl = this.renderer.gl; this.bindGraphics(graphics, webGLData, this.renderer); - if (this.stencilStack.length === 0) { + if (this.stencilStack.length === 0) + { gl.enable(gl.STENCIL_TEST); gl.clear(gl.STENCIL_BUFFER_BIT); this.reverse = true; @@ -47,14 +50,17 @@ // draw the triangle strip! - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } @@ -62,31 +68,38 @@ // draw a quad to increment.. gl.drawElements(gl.TRIANGLE_FAN, 4, gl.UNSIGNED_SHORT, ( webGLData.indices.length - 4 ) * 2 ); - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); } this.reverse = !this.reverse; } - else { - if (!this.reverse) { + else + { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } - else { + 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) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); } } @@ -103,7 +116,8 @@ * @param graphics {Graphics} * @param webGLData {Array} */ -WebGLStencilManager.prototype.bindGraphics = function (graphics, webGLData) { +WebGLStencilManager.prototype.bindGraphics = function (graphics, webGLData) +{ //if (this._currentGraphics === graphics)return; this._currentGraphics = graphics; @@ -114,7 +128,8 @@ offset = this.renderer.offset, shader;// = this.renderer.shaderManager.primitiveShader; - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { shader = this.renderer.shaderManager.complexPrimitiveShader; this.renderer.shaderManager.setShader(shader); @@ -141,7 +156,8 @@ // set the index buffer! gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, webGLData.indexBuffer); } - else { + else + { //this.renderer.shaderManager.activatePrimitiveShader(); shader = this.renderer.shaderManager.primitiveShader; this.renderer.shaderManager.setShader( shader ); @@ -154,7 +170,7 @@ gl.uniform2f(shader.uniforms.offsetVector._location, -offset.x, -offset.y); gl.uniform3fv(shader.uniforms.tint._location, utils.hex2rgb(graphics.tint)); - + gl.uniform1f(shader.uniforms.alpha._location, graphics.worldAlpha); @@ -172,19 +188,22 @@ * @param graphics {Graphics} * @param webGLData {Array} */ -WebGLStencilManager.prototype.popStencil = function (graphics, webGLData) { +WebGLStencilManager.prototype.popStencil = function (graphics, webGLData) +{ var gl = this.renderer.gl; this.stencilStack.pop(); this.count--; - if (this.stencilStack.length === 0) { + if (this.stencilStack.length === 0) + { // the stack is empty! gl.disable(gl.STENCIL_TEST); } - else { + else + { var level = this.count; @@ -192,14 +211,17 @@ gl.colorMask(false, false, false, false); - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { this.reverse = !this.reverse; - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } @@ -213,31 +235,38 @@ // draw the triangle strip! gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); - if (!this.reverse) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); } } - else { + else + { // console.log("<<>>") - if (!this.reverse) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } - else { + 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) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); } } @@ -253,7 +282,8 @@ * Destroys the mask stack. * */ -WebGLStencilManager.prototype.destroy = function () { +WebGLStencilManager.prototype.destroy = function () +{ this.renderer = null; this.stencilStack = null; }; diff --git a/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js b/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js index 913ba5e..1ea7d19 100644 --- a/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js +++ b/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function ComplexPrimitiveShader(gl) { +function ComplexPrimitiveShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -24,7 +25,8 @@ 'uniform float flipY;', 'varying vec4 vColor;', - 'void main(void) {', + '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);', @@ -37,7 +39,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = vColor;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/FastShader.js b/src/core/renderers/webgl/shaders/FastShader.js index bd2e29a..2e5e060 100644 --- a/src/core/renderers/webgl/shaders/FastShader.js +++ b/src/core/renderers/webgl/shaders/FastShader.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function FastShader(gl) { +function FastShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -28,7 +29,8 @@ 'const vec2 center = vec2(-1.0, 1.0);', - 'void main(void) {', + 'void main(void) + {', ' vec2 v;', ' vec2 sv = aVertexPosition * aScale;', ' v.x = (sv.x) * cos(aRotation) - (sv.y) * sin(aRotation);', @@ -49,7 +51,8 @@ 'uniform sampler2D uSampler;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/PrimitiveShader.js b/src/core/renderers/webgl/shaders/PrimitiveShader.js index 6f25409..a25f54f 100644 --- a/src/core/renderers/webgl/shaders/PrimitiveShader.js +++ b/src/core/renderers/webgl/shaders/PrimitiveShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function PrimitiveShader(gl) { +function PrimitiveShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -23,7 +24,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + '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);', @@ -36,7 +38,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = vColor;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/Shader.js b/src/core/renderers/webgl/shaders/Shader.js index f8964f5..fd75ef5 100644 --- a/src/core/renderers/webgl/shaders/Shader.js +++ b/src/core/renderers/webgl/shaders/Shader.js @@ -6,7 +6,8 @@ * @param [fragmentSrc] {string} The source of the fragment shader. * @param [vertexSrc] {string} The source of the vertex shader. */ -function Shader(gl, vertexSrc, fragmentSrc, customUniforms, customAttributes) { +function Shader(gl, vertexSrc, fragmentSrc, customUniforms, customAttributes) +{ /** * @member {number} * @readonly @@ -33,7 +34,8 @@ dimensions: { type: '4f', value: new Float32Array(4) } }; - for (var u in customUniforms) { + for (var u in customUniforms) + { this.uniforms[u] = customUniforms[u]; } @@ -43,7 +45,8 @@ aColor: 0 }; - for (var a in customAttributes) { + for (var a in customAttributes) + { this.attributes[a] = customAttributes[a]; } @@ -66,7 +69,8 @@ 'const vec2 center = vec2(-1.0, 1.0);', - 'void main(void) {', + 'void main(void) + {', ' gl_Position = vec4( ((aVertexPosition + offsetVector) / projectionVector) + center , 0.0, 1.0);', ' vTextureCoord = aTextureCoord;', ' vColor = vec4(aColor.rgb * aColor.a, aColor.a);', @@ -85,7 +89,8 @@ 'uniform sampler2D uSampler;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;', '}' ].join('\n'); @@ -96,7 +101,8 @@ Shader.prototype.constructor = Shader; module.exports = Shader; -Shader.prototype.init = function () { +Shader.prototype.init = function () +{ this.compile(); this.gl.useProgram(this.program); @@ -105,14 +111,18 @@ this.cacheAttributeLocations(Object.keys(this.attributes)); }; -Shader.prototype.cacheUniformLocations = function (keys) { - for (var i = 0; i < keys.length; ++i) { +Shader.prototype.cacheUniformLocations = function (keys) +{ + for (var i = 0; i < keys.length; ++i) + { this.uniforms[keys[i]]._location = this.gl.getUniformLocation(this.program, keys[i]); } }; -Shader.prototype.cacheAttributeLocations = function (keys) { - for (var i = 0; i < keys.length; ++i) { +Shader.prototype.cacheAttributeLocations = function (keys) +{ + for (var i = 0; i < keys.length; ++i) + { this.attributes[keys[i]] = this.gl.getAttribLocation(this.program, keys[i]); } @@ -124,14 +134,16 @@ // 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.attributes.aColor === -1) { + // if (this.attributes.aColor === -1) + { // this.attributes.aColor = 2; // } // End worst hack eva // }; -Shader.prototype.compile = function () { +Shader.prototype.compile = function () +{ var gl = this.gl; var glVertShader = this._glCompile(gl.VERTEX_SHADER, this.vertexSrc); @@ -144,13 +156,15 @@ gl.linkProgram(program); // if linking fails, then log and cleanup - if (!gl.getProgramParameter(program, gl.LINK_STATUS)) { + if (!gl.getProgramParameter(program, gl.LINK_STATUS)) + { window.console.error('Pixi.js Error: Could not initialize shader.'); window.console.error('gl.VALIDATE_STATUS', gl.getProgramParameter(program, gl.VALIDATE_STATUS)); window.console.error('gl.getError()', gl.getError()); // if there is a program info log, log it - if (gl.getProgramInfoLog(program) !== '') { + if (gl.getProgramInfoLog(program) !== '') + { window.console.warn('Pixi.js Warning: gl.getProgramInfoLog()', gl.getProgramInfoLog(program)); } @@ -165,18 +179,21 @@ return (this.program = program); }; -Shader.prototype.syncUniforms = function () { +Shader.prototype.syncUniforms = function () +{ var gl = this.gl; this.textureCount = 1; - for (var key in this.uniforms) { + for (var key in this.uniforms) + { var uniform = this.uniforms[key], location = uniform._location, value = uniform.value, i, il; - switch (uniform.type) { + switch (uniform.type) + { // single int value case 'i': case '1i': @@ -282,7 +299,8 @@ // a Color Value case 'c': - if (typeof value === 'number') { + if (typeof value === 'number') + { value = utils.hex2rgb(value); } @@ -311,11 +329,13 @@ // array of 2D Point objects case 'v2v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(2 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 2] = value[i].x; uniform._array[i * 2 + 1] = value[i].y; } @@ -325,11 +345,13 @@ // array of 3D Point objects case 'v3v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(3 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 3] = value[i].x; uniform._array[i * 3 + 1] = value[i].y; uniform._array[i * 3 + 2] = value[i].z; @@ -341,11 +363,13 @@ // array of 4D Point objects case 'v4v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(4 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 4] = value[i].x; uniform._array[i * 4 + 1] = value[i].y; uniform._array[i * 4 + 2] = value[i].z; @@ -359,7 +383,8 @@ // PIXI.Texture case 't': case 'sampler2D': - if (!uniform.value || !uniform.value.baseTexture || !uniform.value.baseTexture.hasLoaded) { + if (!uniform.value || !uniform.value.baseTexture || !uniform.value.baseTexture.hasLoaded) + { break; } @@ -376,7 +401,8 @@ this.textureCount++; // initialize the texture if we haven't yet - if (!uniform._init) { + if (!uniform._init) + { this.initSampler2D(uniform); uniform._init = true; @@ -394,11 +420,13 @@ * Initialises a Sampler2D uniform (which may only be available later on after initUniforms once the texture has loaded) * */ -Shader.prototype.initSampler2D = function (uniform) { +Shader.prototype.initSampler2D = function (uniform) +{ var gl = this.gl; // Extended texture data - if (uniform.textureData) { + if (uniform.textureData) + { var data = uniform.textureData; // GLTexture = mag linear, min linear_mipmap_linear, wrap repeat + gl.generateMipmap(gl.TEXTURE_2D); @@ -417,14 +445,16 @@ var wrapT = (data.wrapT) ? data.wrapT : gl.CLAMP_TO_EDGE; var format = (data.luminance) ? gl.LUMINANCE : gl.RGBA; - if (data.repeat) { + if (data.repeat) + { wrapS = gl.REPEAT; wrapT = gl.REPEAT; } gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, !!data.flipY); - if (data.width) { + if (data.width) + { var width = (data.width) ? data.width : 512; var height = (data.height) ? data.height : 2; var border = (data.border) ? data.border : 0; @@ -432,7 +462,8 @@ // 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 { + 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); } @@ -448,7 +479,8 @@ * Destroys the shader. * */ -Shader.prototype.destroy = function () { +Shader.prototype.destroy = function () +{ this.gl.deleteProgram(this.program); this.gl = null; @@ -459,13 +491,15 @@ this.fragmentSrc = null; }; -Shader.prototype._glCompile = function (type, src) { +Shader.prototype._glCompile = function (type, src) +{ var shader = this.gl.createShader(type); this.gl.shaderSource(shader, src); this.gl.compileShader(shader); - if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) { + if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) + { window.console.log(this.gl.getShaderInfoLog(shader)); return null; } diff --git a/src/core/renderers/webgl/shaders/StripShader.js b/src/core/renderers/webgl/shaders/StripShader.js index 193f6e1..a7abcc6 100644 --- a/src/core/renderers/webgl/shaders/StripShader.js +++ b/src/core/renderers/webgl/shaders/StripShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function StripShader(gl) { +function StripShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -20,7 +21,8 @@ 'varying vec2 vTextureCoord;', - 'void main(void) {', + '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);', @@ -36,7 +38,8 @@ 'varying vec2 vTextureCoord;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vec2(vTextureCoord.x, vTextureCoord.y)) * alpha;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/utils/FilterTexture.js b/src/core/renderers/webgl/utils/FilterTexture.js index d2c8423..4433d44 100644 --- a/src/core/renderers/webgl/utils/FilterTexture.js +++ b/src/core/renderers/webgl/utils/FilterTexture.js @@ -8,7 +8,8 @@ * @param height {number} the vertical range of the filter * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values */ -function FilterTexture(gl, width, height, scaleMode) { +function FilterTexture(gl, width, height, scaleMode) +{ /** * @member {WebGLContext} */ @@ -59,7 +60,8 @@ * Clears the filter texture. * */ -FilterTexture.prototype.clear = function () { +FilterTexture.prototype.clear = function () +{ var gl = this.gl; gl.clearColor(0,0,0, 0); @@ -72,8 +74,10 @@ * @param width {number} the new width of the texture * @param height {number} the new height of the texture */ -FilterTexture.prototype.resize = function (width, height) { - if (this.width === width && this.height === height) { +FilterTexture.prototype.resize = function (width, height) +{ + if (this.width === width && this.height === height) + { return; } @@ -96,7 +100,8 @@ * Destroys the filter texture. * */ -FilterTexture.prototype.destroy = function () { +FilterTexture.prototype.destroy = function () +{ var gl = this.gl; gl.deleteFramebuffer( this.frameBuffer ); gl.deleteTexture( this.texture ); diff --git a/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js b/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js index c4721e9..a63f4d7 100644 --- a/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js +++ b/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js @@ -14,7 +14,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this sprite batch works for. */ -function WebGLFastSpriteBatch(renderer) { +function WebGLFastSpriteBatch(renderer) +{ /** * The renderer instance this sprite batch operates on. * @@ -91,7 +92,8 @@ */ this.lastIndexCount = 0; - for (var i=0, j=0; i < numIndices; i += 6, j += 4) { + 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; @@ -144,7 +146,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.setupContext(); }); } @@ -157,7 +160,8 @@ * * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLFastSpriteBatch.prototype.setupContext = function () { +WebGLFastSpriteBatch.prototype.setupContext = function () +{ var gl = this.renderer.gl; // create a couple of buffers @@ -177,7 +181,8 @@ /** * @param spriteBatch {SpriteBatch} The SpriteBatch container to prepare for. */ -WebGLFastSpriteBatch.prototype.begin = function (spriteBatch) { +WebGLFastSpriteBatch.prototype.begin = function (spriteBatch) +{ this.shader = this.renderer.shaderManager.fastShader; this.matrix = spriteBatch.worldTransform.toArray(true); @@ -187,33 +192,38 @@ /** */ -WebGLFastSpriteBatch.prototype.end = function () { +WebGLFastSpriteBatch.prototype.end = function () +{ this.flush(); }; /** * @param spriteBatch {SpriteBatch} The SpriteBatch container to render. */ -WebGLFastSpriteBatch.prototype.render = function (spriteBatch) { +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) { + if (!sprite.texture._uvs) + { return; } this.currentBaseTexture = sprite.texture.baseTexture; // check blend mode - if (sprite.blendMode !== this.renderer.blendModeManager.currentBlendMode) { + if (sprite.blendMode !== this.renderer.blendModeManager.currentBlendMode) + { this.flush(); this.renderer.blendModeManager.setBlendMode(sprite.blendMode); } - for (var i=0,j= children.length; i= this.size) { + if (this.currentBatchSize >= this.size) + { this.flush(); } }; @@ -362,29 +379,35 @@ /** * */ -WebGLFastSpriteBatch.prototype.flush = function () { +WebGLFastSpriteBatch.prototype.flush = function () +{ // If the batch is length 0 then return as there is nothing to draw - if (this.currentBatchSize === 0) { + if (this.currentBatchSize === 0) + { return; } var gl = this.renderer.gl; // bind the current texture - if (!this.currentBaseTexture._glTextures[gl.id]) { + if (!this.currentBaseTexture._glTextures[gl.id]) + { this.renderer.updateTexture(this.currentBaseTexture, gl); } //TODO-SHOUD THIS BE ELSE??!?!?! - else { + else + { gl.bindTexture(gl.TEXTURE_2D, this.currentBaseTexture._glTextures[gl.id]); } // upload the verts to the buffer - if (this.currentBatchSize > ( this.size * 0.5 ) ) { + if (this.currentBatchSize > ( this.size * 0.5 ) ) + { gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); } - else { + else + { var view = this.vertices.subarray(0, this.currentBatchSize * this.vertByteSize); gl.bufferSubData(gl.ARRAY_BUFFER, 0, view); @@ -405,14 +428,16 @@ * Ends the batch and flushes * */ -WebGLFastSpriteBatch.prototype.stop = function () { +WebGLFastSpriteBatch.prototype.stop = function () +{ this.flush(); }; /** * */ -WebGLFastSpriteBatch.prototype.start = function () { +WebGLFastSpriteBatch.prototype.start = function () +{ var gl = this.renderer.gl; // bind the main texture diff --git a/src/core/renderers/webgl/utils/WebGLGraphics.js b/src/core/renderers/webgl/utils/WebGLGraphics.js index 55f4911..ab8f46e 100644 --- a/src/core/renderers/webgl/utils/WebGLGraphics.js +++ b/src/core/renderers/webgl/utils/WebGLGraphics.js @@ -19,7 +19,8 @@ * @param graphics {Graphics} * @param renderer {WebGLRenderer} */ -WebGLGraphics.renderGraphics = function (graphics, renderer) {//projection, offset) { +WebGLGraphics.renderGraphics = function (graphics, renderer) {//projection, offset) +{ var gl = renderer.gl; var projection = renderer.projection, @@ -27,7 +28,8 @@ shader = renderer.shaderManager.primitiveShader, webGLData; - if (graphics.dirty) { + if (graphics.dirty) + { WebGLGraphics.updateGraphics(graphics, gl); } @@ -35,8 +37,10 @@ // This could be speeded up for sure! - for (var i = 0; i < webGL.data.length; i++) { - if (webGL.data[i].mode === 1) { + for (var i = 0; i < webGL.data.length; i++) + { + if (webGL.data[i].mode === 1) + { webGLData = webGL.data[i]; renderer.stencilManager.pushStencil(graphics, webGLData, renderer); @@ -46,7 +50,8 @@ renderer.stencilManager.popStencil(graphics, webGLData, renderer); } - else { + else + { webGLData = webGL.data[i]; @@ -84,12 +89,14 @@ * @param graphicsData {Graphics} The graphics object to update * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLGraphics.updateGraphics = function (graphics, gl) { +WebGLGraphics.updateGraphics = function (graphics, gl) +{ // get the contexts graphics object var webGL = graphics._webGL[gl.id]; // if the graphics object does not exist in the webGL context time to create it! - if (!webGL) { + if (!webGL) + { webGL = graphics._webGL[gl.id] = {lastIndex:0, data:[], gl:gl}; } @@ -99,11 +106,13 @@ var i; // if the user cleared the graphics object we will need to clear every object - if (graphics.clearDirty) { + if (graphics.clearDirty) + { graphics.clearDirty = false; // lop through and return all the webGLDatas to the object pool so than can be reused later on - for (i = 0; i < webGL.data.length; i++) { + for (i = 0; i < webGL.data.length; i++) + { var graphicsData = webGL.data[i]; graphicsData.reset(); WebGLGraphics.graphicsDataPool.push( graphicsData ); @@ -119,58 +128,72 @@ // loop through the graphics datas and construct each one.. // if the object is a complex fill then the new stencil buffer technique will be used // other wise graphics objects will be pushed into a batch.. - for (i = webGL.lastIndex; i < graphics.graphicsData.length; i++) { + for (i = webGL.lastIndex; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { // need to add the points the the graphics object.. data.points = data.shape.points.slice(); - if (data.shape.closed) { + if (data.shape.closed) + { // close the poly if the value is true! - if (data.points[0] !== data.points[data.points.length-2] || data.points[1] !== data.points[data.points.length-1]) { + if (data.points[0] !== data.points[data.points.length-2] || data.points[1] !== data.points[data.points.length-1]) + { data.points.push(data.points[0], data.points[1]); } } // MAKE SURE WE HAVE THE CORRECT TYPE.. - if (data.fill) { - if (data.points.length >= 6) { - if (data.points.length < 6 * 2) { + if (data.fill) + { + if (data.points.length >= 6) + { + if (data.points.length < 6 * 2) + { webGLData = WebGLGraphics.switchMode(webGL, 0); var canDrawUsingSimple = WebGLGraphics.buildPoly(data, webGLData); // console.log(canDrawUsingSimple); - if (!canDrawUsingSimple) { + if (!canDrawUsingSimple) + { // console.log("<>>>") webGLData = WebGLGraphics.switchMode(webGL, 1); WebGLGraphics.buildComplexPoly(data, webGLData); } } - else { + else + { webGLData = WebGLGraphics.switchMode(webGL, 1); WebGLGraphics.buildComplexPoly(data, webGLData); } } } - if (data.lineWidth > 0) { + if (data.lineWidth > 0) + { webGLData = WebGLGraphics.switchMode(webGL, 0); WebGLGraphics.buildLine(data, webGLData); } } - else { + else + { webGLData = WebGLGraphics.switchMode(webGL, 0); - if (data.type === CONST.SHAPES.RECT) { + if (data.type === CONST.SHAPES.RECT) + { WebGLGraphics.buildRectangle(data, webGLData); } - else if (data.type === CONST.SHAPES.CIRC || data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.CIRC || data.type === CONST.SHAPES.ELIP) + { WebGLGraphics.buildCircle(data, webGLData); } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { WebGLGraphics.buildRoundedRectangle(data, webGLData); } } @@ -179,10 +202,12 @@ } // upload all the dirty data... - for (i = 0; i < webGL.data.length; i++) { + for (i = 0; i < webGL.data.length; i++) + { webGLData = webGL.data[i]; - if (webGLData.dirty) { + if (webGLData.dirty) + { webGLData.upload(); } } @@ -194,18 +219,22 @@ * @param webGL {WebGLContext} * @param type {number} */ -WebGLGraphics.switchMode = function (webGL, type) { +WebGLGraphics.switchMode = function (webGL, type) +{ var webGLData; - if (!webGL.data.length) { + if (!webGL.data.length) + { webGLData = WebGLGraphics.graphicsDataPool.pop() || new WebGLGraphicsData(webGL.gl); webGLData.mode = type; webGL.data.push(webGLData); } - else { + else + { webGLData = webGL.data[webGL.data.length-1]; - if (webGLData.mode !== type || type === 1) { + if (webGLData.mode !== type || type === 1) + { webGLData = WebGLGraphics.graphicsDataPool.pop() || new WebGLGraphicsData(webGL.gl); webGLData.mode = type; webGL.data.push(webGLData); @@ -225,7 +254,8 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildRectangle = function (graphicsData, webGLData) { +WebGLGraphics.buildRectangle = function (graphicsData, webGLData) +{ // --- // // need to convert points to a nice regular data // @@ -235,7 +265,8 @@ var width = rectData.width; var height = rectData.height; - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -265,7 +296,8 @@ indices.push(vertPos, vertPos, vertPos+1, vertPos+2, vertPos+3, vertPos+3); } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = [x, y, @@ -289,7 +321,8 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildRoundedRectangle = function (graphicsData, webGLData) { +WebGLGraphics.buildRoundedRectangle = function (graphicsData, webGLData) +{ var rrectData = graphicsData.shape; var x = rrectData.x; var y = rrectData.y; @@ -305,7 +338,8 @@ recPoints = recPoints.concat(WebGLGraphics.quadraticBezierCurve(x + width, y + radius, x + width, y, x + width - radius, y)); recPoints = recPoints.concat(WebGLGraphics.quadraticBezierCurve(x + radius, y, x, y, x, y + radius)); - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -323,7 +357,8 @@ // var i = 0; - for (i = 0; i < triangles.length; i+=3) { + for (i = 0; i < triangles.length; i+=3) + { indices.push(triangles[i] + vecPos); indices.push(triangles[i] + vecPos); indices.push(triangles[i+1] + vecPos); @@ -332,12 +367,14 @@ } - for (i = 0; i < recPoints.length; i++) { + for (i = 0; i < recPoints.length; i++) + { verts.push(recPoints[i], recPoints[++i], r, g, b, alpha); } } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = recPoints; @@ -362,7 +399,8 @@ * @param toY {number} Destination point y * @return {number[]} */ -WebGLGraphics.quadraticBezierCurve = function (fromX, fromY, cpX, cpY, toX, toY) { +WebGLGraphics.quadraticBezierCurve = function (fromX, fromY, cpX, cpY, toX, toY) +{ var xa, ya, @@ -373,14 +411,16 @@ n = 20, points = []; - function getPt(n1 , n2, perc) { + function getPt(n1 , n2, perc) + { var diff = n2 - n1; return n1 + ( diff * perc ); } var j = 0; - for (var i = 0; i <= n; i++ ) { + for (var i = 0; i <= n; i++ ) + { j = i / n; // The Green Line @@ -406,7 +446,8 @@ * @param graphicsData {Graphics} The graphics object to draw * @param webGLData {object} */ -WebGLGraphics.buildCircle = function (graphicsData, webGLData) { +WebGLGraphics.buildCircle = function (graphicsData, webGLData) +{ // need to convert points to a nice regular data var circleData = graphicsData.shape; var x = circleData.x; @@ -415,11 +456,13 @@ var height; // TODO - bit hacky?? - if (graphicsData.type === CONST.SHAPES.CIRC) { + if (graphicsData.type === CONST.SHAPES.CIRC) + { width = circleData.radius; height = circleData.radius; } - else { + else + { width = circleData.width; height = circleData.height; } @@ -429,7 +472,8 @@ var i = 0; - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -444,7 +488,8 @@ indices.push(vecPos); - for (i = 0; i < totalSegs + 1 ; i++) { + for (i = 0; i < totalSegs + 1 ; i++) + { verts.push(x,y, r, g, b, alpha); verts.push(x + Math.sin(seg * i) * width, @@ -457,12 +502,14 @@ indices.push(vecPos-1); } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = []; - for (i = 0; i < totalSegs + 1; i++) { + for (i = 0; i < totalSegs + 1; i++) + { graphicsData.points.push(x + Math.sin(seg * i) * width, y + Math.cos(seg * i) * height); } @@ -481,18 +528,22 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildLine = function (graphicsData, webGLData) { +WebGLGraphics.buildLine = function (graphicsData, webGLData) +{ // TODO OPTIMISE! var i = 0; var points = graphicsData.points; - if (points.length === 0) { + if (points.length === 0) + { return; } // if the line width is an odd number add 0.5 to align to a whole pixel - if (graphicsData.lineWidth%2) { - for (i = 0; i < points.length; i++) { + if (graphicsData.lineWidth%2) + { + for (i = 0; i < points.length; i++) + { points[i] += 0.5; } } @@ -502,7 +553,8 @@ var lastPoint = new math.Point(points[points.length - 2], points[points.length - 1]); // if the first point is the last point - gonna have issues :) - if (firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) { + if (firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) + { // need to clone as we are going to slightly modify the shape.. points = points.slice(); @@ -562,7 +614,8 @@ verts.push(p1x + perpx , p1y + perpy, r, g, b, alpha); - for (i = 1; i < length-1; i++) { + for (i = 1; i < length-1; i++) + { p1x = points[(i-1)*2]; p1y = points[(i-1)*2 + 1]; @@ -599,7 +652,8 @@ denom = a1*b2 - a2*b1; - if (Math.abs(denom) < 0.1 ) { + if (Math.abs(denom) < 0.1 ) + { denom+=10.1; verts.push(p2x - perpx , p2y - perpy, @@ -618,7 +672,8 @@ pdist = (px -p2x) * (px -p2x) + (py -p2y) + (py -p2y); - if (pdist > 140 * 140) { + if (pdist > 140 * 140) + { perp3x = perpx - perp2x; perp3y = perpy - perp2y; @@ -639,7 +694,8 @@ indexCount++; } - else { + else + { verts.push(px , py); verts.push(r, g, b, alpha); @@ -672,7 +728,8 @@ indices.push(indexStart); - for (i = 0; i < indexCount; i++) { + for (i = 0; i < indexCount; i++) + { indices.push(indexStart++); } @@ -687,11 +744,13 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildComplexPoly = function (graphicsData, webGLData) { +WebGLGraphics.buildComplexPoly = function (graphicsData, webGLData) +{ //TODO - no need to copy this as it gets turned into a FLoat32Array anyways.. var points = graphicsData.points.slice(); - if (points.length < 6) { + if (points.length < 6) + { return; } @@ -711,7 +770,8 @@ var x,y; // get size.. - for (var i = 0; i < points.length; i+=2) { + for (var i = 0; i < points.length; i+=2) + { x = points[i]; y = points[i+1]; @@ -732,7 +792,8 @@ //TODO - this aint needed! var length = points.length / 2; - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { indices.push( i ); } @@ -746,10 +807,12 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildPoly = function (graphicsData, webGLData) { +WebGLGraphics.buildPoly = function (graphicsData, webGLData) +{ var points = graphicsData.points; - if (points.length < 6) { + if (points.length < 6) + { return; } // get first and last point.. figure out the middle! @@ -767,7 +830,8 @@ var triangles = utils.PolyK.Triangulate(points); - if (!triangles) { + if (!triangles) + { return false; } @@ -775,7 +839,8 @@ var i = 0; - for (i = 0; i < triangles.length; i+=3) { + for (i = 0; i < triangles.length; i+=3) + { indices.push(triangles[i] + vertPos); indices.push(triangles[i] + vertPos); indices.push(triangles[i+1] + vertPos); @@ -783,7 +848,8 @@ indices.push(triangles[i+2] + vertPos); } - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { verts.push(points[i * 2], points[i * 2 + 1], r, g, b, alpha); } diff --git a/src/core/renderers/webgl/utils/WebGLGraphicsData.js b/src/core/renderers/webgl/utils/WebGLGraphicsData.js index c56d05e..c739ba7 100644 --- a/src/core/renderers/webgl/utils/WebGLGraphicsData.js +++ b/src/core/renderers/webgl/utils/WebGLGraphicsData.js @@ -2,7 +2,8 @@ * @class * @private */ -function WebGLGraphicsData(gl) { +function WebGLGraphicsData(gl) +{ this.gl = gl; //TODO does this need to be split before uploding?? @@ -22,7 +23,8 @@ /** * */ -WebGLGraphicsData.prototype.reset = function () { +WebGLGraphicsData.prototype.reset = function () +{ this.points.length = 0; this.indices.length = 0; }; @@ -30,7 +32,8 @@ /** * */ -WebGLGraphicsData.prototype.upload = function () { +WebGLGraphicsData.prototype.upload = function () +{ var gl = this.gl; // this.lastIndex = graphics.graphicsData.length; diff --git a/src/core/renderers/webgl/utils/WebGLSpriteBatch.js b/src/core/renderers/webgl/utils/WebGLSpriteBatch.js index 96eaa52..55befbb 100644 --- a/src/core/renderers/webgl/utils/WebGLSpriteBatch.js +++ b/src/core/renderers/webgl/utils/WebGLSpriteBatch.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this sprite batch works for. */ -function WebGLSpriteBatch(renderer) { +function WebGLSpriteBatch(renderer) +{ /** * * @@ -88,7 +89,8 @@ */ this.lastIndexCount = 0; - for (var i=0, j=0; i < numIndices; i += 6, j += 4) { + 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; @@ -162,7 +164,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.setupContext(); }); } @@ -173,7 +176,8 @@ /** * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLSpriteBatch.prototype.setupContext = function () { +WebGLSpriteBatch.prototype.setupContext = function () +{ var gl = this.renderer.gl; // setup default shader @@ -198,7 +202,8 @@ /** * */ -WebGLSpriteBatch.prototype.begin = function () { +WebGLSpriteBatch.prototype.begin = function () +{ // this.shader = this.renderer.shaderManager.defaultShader; this.start(); @@ -206,19 +211,22 @@ /** */ -WebGLSpriteBatch.prototype.end = function () { +WebGLSpriteBatch.prototype.end = function () +{ this.flush(); }; /** * @param sprite {Sprite} the sprite to render when using this spritebatch */ -WebGLSpriteBatch.prototype.render = function (sprite) { +WebGLSpriteBatch.prototype.render = function (sprite) +{ var texture = sprite.texture; //TODO set blend modes.. // check texture.. - if (this.currentBatchSize >= this.size) { + if (this.currentBatchSize >= this.size) + { this.flush(); this.currentBaseTexture = texture.baseTexture; } @@ -227,7 +235,8 @@ var uvs = texture._uvs; // if the uvs have not updated then no point rendering just yet! - if (!uvs) { + if (!uvs) + { return; } @@ -237,7 +246,8 @@ var w0, w1, h0, h1; - if (texture.trim) { + 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; @@ -248,7 +258,8 @@ h0 = h1 + texture.crop.height; } - else { + else + { w0 = (texture.frame.width ) * (1-aX); w1 = (texture.frame.width ) * -aX; @@ -272,7 +283,8 @@ var colors = this.colors; var positions = this.positions; - if (this.renderer.roundPixels) { + if (this.renderer.roundPixels) + { // xy positions[index] = a * w1 + c * h1 + tx | 0; positions[index+1] = d * h1 + b * w1 + ty | 0; @@ -289,7 +301,8 @@ positions[index+15] = a * w1 + c * h0 + tx | 0; positions[index+16] = d * h0 + b * w1 + ty | 0; } - else { + else + { // xy positions[index] = a * w1 + c * h1 + tx; positions[index+1] = d * h1 + b * w1 + ty; @@ -338,11 +351,13 @@ * * @param sprite {TilingSprite} the tilingSprite to render */ -WebGLSpriteBatch.prototype.renderTilingSprite = function (tilingSprite) { +WebGLSpriteBatch.prototype.renderTilingSprite = function (tilingSprite) +{ var texture = tilingSprite.tilingTexture; // check texture.. - if (this.currentBatchSize >= this.size) { + if (this.currentBatchSize >= this.size) + { //return; this.flush(); this.currentBaseTexture = texture.baseTexture; @@ -351,7 +366,8 @@ // set the textures uvs temporarily // TODO create a separate texture so that we can tile part of a texture - if (!tilingSprite._uvs) { + if (!tilingSprite._uvs) + { tilingSprite._uvs = new TextureUvs(); } @@ -454,16 +470,19 @@ * Renders the content and empties the current batch. * */ -WebGLSpriteBatch.prototype.flush = function () { +WebGLSpriteBatch.prototype.flush = function () +{ // If the batch is length 0 then return as there is nothing to draw - if (this.currentBatchSize === 0) { + if (this.currentBatchSize === 0) + { return; } var gl = this.renderer.gl; var shader; - if (this.dirty) { + if (this.dirty) + { this.dirty = false; // bind the main texture gl.activeTexture(gl.TEXTURE0); @@ -482,10 +501,12 @@ } // upload the verts to the buffer - if (this.currentBatchSize > ( this.size * 0.5 ) ) { + if (this.currentBatchSize > ( this.size * 0.5 ) ) + { gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); } - else { + else + { var view = this.positions.subarray(0, this.currentBatchSize * this.vertByteSize); gl.bufferSubData(gl.ARRAY_BUFFER, 0, view); } @@ -502,7 +523,8 @@ var shaderSwap = false; var sprite; - for (var i = 0, j = this.currentBatchSize; i < j; i++) { + for (var i = 0, j = this.currentBatchSize; i < j; i++) + { sprite = this.sprites[i]; @@ -513,24 +535,28 @@ blendSwap = currentBlendMode !== nextBlendMode; shaderSwap = currentShader !== nextShader; // should I use uuidS??? - if (currentBaseTexture !== nextTexture || blendSwap || shaderSwap) { + if (currentBaseTexture !== nextTexture || blendSwap || shaderSwap) + { this.renderBatch(currentBaseTexture, batchSize, start); start = i; batchSize = 0; currentBaseTexture = nextTexture; - if (blendSwap) { + if (blendSwap) + { currentBlendMode = nextBlendMode; this.renderer.blendModeManager.setBlendMode( currentBlendMode ); } - if (shaderSwap) { + if (shaderSwap) + { currentShader = nextShader; shader = currentShader.shaders ? currentShader.shaders[gl.id] : currentShader; - if (!shader) { + if (!shader) + { shader = new Shader(gl, null, currentShader.fragmentSrc, currentShader.uniforms); currentShader.shaders[gl.id] = shader; } @@ -538,7 +564,8 @@ // set shader function??? this.renderer.shaderManager.setShader(shader); - if (shader.dirty) { + if (shader.dirty) + { shader.syncUniforms(); } @@ -569,17 +596,21 @@ * @param size {number} * @param startIndex {number} */ -WebGLSpriteBatch.prototype.renderBatch = function (texture, size, startIndex) { - if (size === 0) { +WebGLSpriteBatch.prototype.renderBatch = function (texture, size, startIndex) +{ + if (size === 0) + { return; } var gl = this.renderer.gl; - if (!texture._glTextures[gl.id]) { + if (!texture._glTextures[gl.id]) + { this.renderer.updateTexture(texture); } - else { + else + { // bind the current texture gl.bindTexture(gl.TEXTURE_2D, texture._glTextures[gl.id]); } @@ -594,7 +625,8 @@ /** * */ -WebGLSpriteBatch.prototype.stop = function () { +WebGLSpriteBatch.prototype.stop = function () +{ this.flush(); this.dirty = true; }; @@ -602,7 +634,8 @@ /** * */ -WebGLSpriteBatch.prototype.start = function () { +WebGLSpriteBatch.prototype.start = function () +{ this.dirty = true; }; @@ -610,7 +643,8 @@ * Destroys the SpriteBatch. * */ -WebGLSpriteBatch.prototype.destroy = function () { +WebGLSpriteBatch.prototype.destroy = function () +{ this.renderer.gl.deleteBuffer(this.vertexBuffer); this.renderer.gl.deleteBuffer(this.indexBuffer); diff --git a/src/core/textures/BaseTexture.js b/src/core/textures/BaseTexture.js index 2bf77d4..513d358 100644 --- a/src/core/textures/BaseTexture.js +++ b/src/core/textures/BaseTexture.js @@ -10,7 +10,8 @@ * @param source {Image|Canvas} the source object of the texture. * @param [scaleMode=scaleModes.DEFAULT] {number} See {@link scaleModes} for possible values */ -function BaseTexture(source, scaleMode) { +function BaseTexture(source, scaleMode) +{ this.uuid = utils.uuid(); /** @@ -123,7 +124,8 @@ this._needsUpdate = false; // if no source passed don't try to load - if (source) { + if (source) + { this.loadSource(source); } @@ -149,13 +151,16 @@ Object.defineProperties(BaseTexture.prototype, { needsUpdate: { - get: function () { + get: function () + { return this._needsUpdate; }, - set: function (val) { + set: function (val) + { this._needsUpdate = val; - if (val) { + if (val) + { this.emit('update', this); } } @@ -171,9 +176,11 @@ * * The logic state after calling `loadSource` directly or indirectly (eg. `fromImage`, `new BaseTexture`) is: * - * if (texture.hasLoaded) { + * if (texture.hasLoaded) + { * // texture ready for use - * } else if (texture.isLoading) { + * } else if (texture.isLoading) + { * // listen to 'loaded' and/or 'error' events on texture * } else { * // not loading, not going to load UNLESS the source is reloaded @@ -183,12 +190,14 @@ * @protected * @param source {Image|Canvas} the source object of the texture. */ -BaseTexture.prototype.loadSource = function (source) { +BaseTexture.prototype.loadSource = function (source) +{ var wasLoading = this.isLoading; this.hasLoaded = false; this.isLoading = false; - if (wasLoading && this.source) { + if (wasLoading && this.source) + { this.source.onload = null; this.source.onerror = null; } @@ -196,20 +205,24 @@ this.source = source; // Apply source if loaded. Otherwise setup appropriate loading monitors. - if ((this.source.complete || this.source.getContext) && this.source.width && this.source.height) { + if ((this.source.complete || this.source.getContext) && this.source.width && this.source.height) + { this._sourceLoaded(); } - else if(!source.getContext) { + else if(!source.getContext) + { // Image fail / not ready this.isLoading = true; var scope = this; - source.onload = function () { + source.onload = function () + { source.onload = null; source.onerror = null; - if(!scope.isLoading) { + if(!scope.isLoading) + { return; } @@ -219,11 +232,13 @@ scope.emit('loaded', scope); }; - source.onerror = function () { + source.onerror = function () + { source.onload = null; source.onerror = null; - if(!scope.isLoading) { + if(!scope.isLoading) + { return; } @@ -234,24 +249,29 @@ // Per http://www.w3.org/TR/html5/embedded-content-0.html#the-img-element // "The value of `complete` can thus change while a script is executing." // So complete needs to be re-checked after the callbacks have been added.. - if (source.complete) { + if (source.complete) + { this.isLoading = false; // ..and if we're complete now, no need for callbacks source.onload = null; source.onerror = null; - if (source.width && source.height) { + if (source.width && source.height) + { this._sourceLoaded(); // If any previous subscribers possible - if (wasLoading) { + if (wasLoading) + { this.emit('loaded', this); } } - else { + else + { // If any previous subscribers possible - if (wasLoading) { + if (wasLoading) + { this.emit('error', this); } } @@ -265,7 +285,8 @@ * * @private */ -BaseTexture.prototype._sourceLoaded = function () { +BaseTexture.prototype._sourceLoaded = function () +{ this.hasLoaded = true; this.width = this.source.naturalWidth || this.source.width; @@ -278,16 +299,20 @@ * Destroys this base texture * */ -BaseTexture.prototype.destroy = function () { - if (this.imageUrl) { +BaseTexture.prototype.destroy = function () +{ + if (this.imageUrl) + { delete utils.BaseTextureCache[this.imageUrl]; delete utils.TextureCache[this.imageUrl]; this.imageUrl = null; - if (!navigator.isCocoonJS) { + if (!navigator.isCocoonJS) + { this.source.src = ''; } } - else if (this.source && this.source._pixiId) { + else if (this.source && this.source._pixiId) + { delete utils.BaseTextureCache[this.source._pixiId]; } this.source = null; @@ -301,7 +326,8 @@ * memory again. * */ -BaseTexture.prototype.dispose = function () { +BaseTexture.prototype.dispose = function () +{ this.emit('dispose', this); }; @@ -311,7 +337,8 @@ * * @param newSrc {string} the path of the image */ -BaseTexture.prototype.updateSourceImage = function (newSrc) { +BaseTexture.prototype.updateSourceImage = function (newSrc) +{ this.source.src = newSrc; this.loadSource(this.source); }; @@ -326,18 +353,22 @@ * @param [scaleMode=scaleModes.DEFAULT] {number} See {@link scaleModes} for possible values * @return BaseTexture */ -BaseTexture.fromImage = function (imageUrl, crossorigin, scaleMode) { +BaseTexture.fromImage = function (imageUrl, crossorigin, scaleMode) +{ var baseTexture = utils.BaseTextureCache[imageUrl]; - if (crossorigin === undefined && imageUrl.indexOf('data:') !== 0) { + if (crossorigin === undefined && imageUrl.indexOf('data:') !== 0) + { crossorigin = true; } - if (!baseTexture) { + if (!baseTexture) + { // new Image() breaks tex loading in some versions of Chrome. // See https://code.google.com/p/chromium/issues/detail?id=238071 var image = new Image();//document.createElement('img'); - if (crossorigin) { + if (crossorigin) + { image.crossOrigin = ''; } @@ -347,7 +378,8 @@ utils.BaseTextureCache[imageUrl] = baseTexture; // if there is an @2x at the end of the url we are going to assume its a highres image - if ( imageUrl.indexOf(CONST.RETINA_PREFIX + '.') !== -1) { + if ( imageUrl.indexOf(CONST.RETINA_PREFIX + '.') !== -1) + { baseTexture.resolution = 2; } } @@ -363,14 +395,17 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return BaseTexture */ -BaseTexture.fromCanvas = function (canvas, scaleMode) { - if (!canvas._pixiId) { +BaseTexture.fromCanvas = function (canvas, scaleMode) +{ + if (!canvas._pixiId) + { canvas._pixiId = 'canvas_' + utils.uuid(); } var baseTexture = utils.BaseTextureCache[canvas._pixiId]; - if (!baseTexture) { + if (!baseTexture) + { baseTexture = new BaseTexture(canvas, scaleMode); utils.BaseTextureCache[canvas._pixiId] = baseTexture; } diff --git a/src/core/textures/RenderTexture.js b/src/core/textures/RenderTexture.js index 6dad20f..53ae796 100644 --- a/src/core/textures/RenderTexture.js +++ b/src/core/textures/RenderTexture.js @@ -46,8 +46,10 @@ * @param [scaleMode] {number} See {@link scaleModes} for possible values * @param [resolution=1] {number} The resolution of the texture being generated */ -function RenderTexture(renderer, width, height, scaleMode, resolution) { - if (!renderer) { +function RenderTexture(renderer, width, height, scaleMode, resolution) +{ + if (!renderer) + { throw new Error('Unable to create RenderTexture, you must pass a renderer into the constructor.'); } @@ -133,7 +135,8 @@ */ this.renderer = renderer; - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { var gl = this.renderer.gl; this.textureBuffer = new FilterTexture(gl, this.width * this.resolution, this.height * this.resolution, this.baseTexture.scaleMode); @@ -142,7 +145,8 @@ this.render = this.renderWebGL; this.projection = new math.Point(this.width*0.5, -this.height*0.5); } - else { + else + { this.render = this.renderCanvas; this.textureBuffer = new CanvasBuffer(this.width* this.resolution, this.height* this.resolution); this.baseTexture.source = this.textureBuffer.canvas; @@ -167,8 +171,10 @@ * @param height {number} The height to resize to. * @param updateBase {boolean} Should the baseTexture.width and height values be resized as well? */ -RenderTexture.prototype.resize = function (width, height, updateBase) { - if (width === this.width && height === this.height) { +RenderTexture.prototype.resize = function (width, height, updateBase) +{ + if (width === this.width && height === this.height) + { return; } @@ -177,17 +183,20 @@ this.width = this.frame.width = this.crop.width = width; this.height = this.frame.height = this.crop.height = height; - if (updateBase) { + if (updateBase) + { this.baseTexture.width = this.width; this.baseTexture.height = this.height; } - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { this.projection.x = this.width / 2; this.projection.y = -this.height / 2; } - if (!this.valid) { + if (!this.valid) + { return; } @@ -198,12 +207,15 @@ * Clears the RenderTexture. * */ -RenderTexture.prototype.clear = function () { - if (!this.valid) { +RenderTexture.prototype.clear = function () +{ + if (!this.valid) + { return; } - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { this.renderer.gl.bindFramebuffer(this.renderer.gl.FRAMEBUFFER, this.textureBuffer.frameBuffer); } @@ -220,19 +232,23 @@ * @param [restoreWorldTransform=true] {boolean} If true the displayObject's worldTransform/worldAlpha and all children * transformations will be restored. Not restoring this information will be a little faster. */ -RenderTexture.prototype.renderWebGL = function (displayObject, matrix, clear, restoreWorldTransform) { - if (!this.valid) { +RenderTexture.prototype.renderWebGL = function (displayObject, matrix, clear, restoreWorldTransform) +{ + if (!this.valid) + { return; } - if (typeof restoreWorldTransform === 'undefined') { + if (typeof restoreWorldTransform === 'undefined') + { restoreWorldTransform = true; } var tempAlpha, tempTransform; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { tempAlpha = displayObject.worldAlpha; tempTransform = displayObject.worldTransform.toArray(); } @@ -245,7 +261,8 @@ wt.identity(); wt.translate(0, this.projection.y * 2); - if (matrix) { + if (matrix) + { wt.append(matrix); } @@ -258,7 +275,8 @@ var children = displayObject.children; var i, j; - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } @@ -269,7 +287,8 @@ gl.bindFramebuffer(gl.FRAMEBUFFER, this.textureBuffer.frameBuffer ); - if (clear) { + if (clear) + { this.textureBuffer.clear(); } @@ -279,11 +298,13 @@ this.renderer.spriteBatch.dirty = true; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { displayObject.worldAlpha = tempAlpha; displayObject.worldTransform.fromArray(tempTransform); - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } } @@ -300,26 +321,31 @@ * @param [restoreWorldTransform=true] {boolean} If true the displayObject's worldTransform/worldAlpha and all children * transformations will be restored. Not restoring this information will be a little faster. */ -RenderTexture.prototype.renderCanvas = function (displayObject, matrix, clear, restoreWorldTransform) { - if (!this.valid) { +RenderTexture.prototype.renderCanvas = function (displayObject, matrix, clear, restoreWorldTransform) +{ + if (!this.valid) + { return; } - if (typeof restoreWorldTransform === 'undefined') { + if (typeof restoreWorldTransform === 'undefined') + { restoreWorldTransform = true; } var tempAlpha, tempTransform; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { tempAlpha = displayObject.worldAlpha; tempTransform = displayObject.worldTransform.toArray(); } var wt = displayObject.worldTransform; wt.identity(); - if (matrix) { + if (matrix) + { wt.append(matrix); } @@ -330,11 +356,13 @@ var children = displayObject.children; var i, j; - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } - if (clear) { + if (clear) + { this.textureBuffer.clear(); } @@ -348,11 +376,13 @@ this.renderer.resolution = realResolution; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { displayObject.worldAlpha = tempAlpha; displayObject.worldTransform.fromArray(tempTransform); - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } } @@ -363,7 +393,8 @@ * * @return {Image} */ -RenderTexture.prototype.getImage = function () { +RenderTexture.prototype.getImage = function () +{ var image = new Image(); image.src = this.getBase64(); return image; @@ -374,7 +405,8 @@ * * @return {string} A base64 encoded string of the texture. */ -RenderTexture.prototype.getBase64 = function () { +RenderTexture.prototype.getBase64 = function () +{ return this.getCanvas().toDataURL(); }; @@ -383,8 +415,10 @@ * * @return {HTMLCanvasElement} A Canvas element with the texture rendered on. */ -RenderTexture.prototype.getCanvas = function () { - if (this.renderer.type === CONST.WEBGL_RENDERER) { +RenderTexture.prototype.getCanvas = function () +{ + if (this.renderer.type === CONST.WEBGL_RENDERER) + { var gl = this.renderer.gl; var width = this.textureBuffer.width; var height = this.textureBuffer.height; @@ -403,7 +437,8 @@ return tempCanvas.canvas; } - else { + else + { return this.textureBuffer.canvas; } }; diff --git a/src/core/textures/Texture.js b/src/core/textures/Texture.js index 3c65909..e97f0aa 100644 --- a/src/core/textures/Texture.js +++ b/src/core/textures/Texture.js @@ -17,7 +17,8 @@ * @param [crop] {Rectangle} The area of original texture * @param [trim] {Rectangle} Trimmed texture rectangle */ -function Texture(baseTexture, frame, crop, trim) { +function Texture(baseTexture, frame, crop, trim) +{ /** * Does this Texture have any frame data assigned to it? * @@ -25,12 +26,14 @@ */ this.noFrame = false; - if (!frame) { + if (!frame) + { this.noFrame = true; frame = new math.Rectangle(0, 0, 1, 1); } - if (baseTexture instanceof Texture) { + if (baseTexture instanceof Texture) + { baseTexture = baseTexture.baseTexture; } @@ -100,13 +103,16 @@ */ this.crop = crop || new math.Rectangle(0, 0, 1, 1); - if (baseTexture.hasLoaded) { - if (this.noFrame) { + if (baseTexture.hasLoaded) + { + if (this.noFrame) + { frame = new math.Rectangle(0, 0, baseTexture.width, baseTexture.height); } this.frame = frame; } - else { + else + { baseTexture.addEventListener('loaded', this.onBaseTextureLoaded.bind(this)); } } @@ -118,19 +124,23 @@ Object.defineProperties(Texture.prototype, { needsUpdate: { - get: function () { + get: function () + { return this.baseTexture.needsUpdate; }, - set: function (val) { + set: function (val) + { this.baseTexture.needsUpdate = val; } }, frame: { - get: function () { + get: function () + { return this._frame; }, - set: function (frame) { + set: function (frame) + { this._frame = frame; this.noFrame = false; @@ -143,20 +153,23 @@ 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 (!this.trim && (frame.x + frame.width > this.baseTexture.width || frame.y + frame.height > this.baseTexture.height)) + { throw new Error('Texture Error: frame does not fit inside the base Texture dimensions ' + this); } this.valid = frame && frame.width && frame.height && this.baseTexture.source && this.baseTexture.hasLoaded; - if (this.trim) { + 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) { + if (this.valid) + { this._updateUvs(); } } @@ -168,11 +181,13 @@ * * @private */ -Texture.prototype.onBaseTextureLoaded = function () { +Texture.prototype.onBaseTextureLoaded = function () +{ var baseTexture = this.baseTexture; baseTexture.removeEventListener('loaded', this.onLoaded); - if (this.noFrame) { + if (this.noFrame) + { this.frame = new math.Rectangle(0, 0, baseTexture.width, baseTexture.height); } @@ -184,8 +199,10 @@ * * @param destroyBase {boolean} Whether to destroy the base texture as well */ -Texture.prototype.destroy = function (destroyBase) { - if (destroyBase) { +Texture.prototype.destroy = function (destroyBase) +{ + if (destroyBase) + { this.baseTexture.destroy(); } @@ -197,8 +214,10 @@ * * @private */ -Texture.prototype._updateUvs = function () { - if (!this._uvs) { +Texture.prototype._updateUvs = function () +{ + if (!this._uvs) + { this._uvs = new TextureUvs(); } @@ -229,10 +248,12 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return Texture */ -Texture.fromImage = function (imageUrl, crossorigin, scaleMode) { +Texture.fromImage = function (imageUrl, crossorigin, scaleMode) +{ var texture = utils.TextureCache[imageUrl]; - if (!texture) { + if (!texture) + { texture = new Texture(BaseTexture.fromImage(imageUrl, crossorigin, scaleMode)); utils.TextureCache[imageUrl] = texture; } @@ -248,9 +269,11 @@ * @param frameId {string} The frame id of the texture * @return Texture */ -Texture.fromFrame = function (frameId) { +Texture.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache '); } return texture; @@ -264,7 +287,8 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return {Texture} */ -Texture.fromCanvas = function (canvas, scaleMode) { +Texture.fromCanvas = function (canvas, scaleMode) +{ return new Texture(BaseTexture.fromCanvas(canvas, scaleMode)); }; @@ -276,7 +300,8 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return {Texture} A Texture */ -Texture.fromVideo = function (video, scaleMode) { +Texture.fromVideo = function (video, scaleMode) +{ return new Texture(VideoBaseTexture.baseTextureFromVideo(video, scaleMode)); }; @@ -287,7 +312,8 @@ * @param texture {Texture} The Texture to add to the cache. * @param id {string} The id that the texture will be stored against. */ -Texture.addTextureToCache = function (texture, id) { +Texture.addTextureToCache = function (texture, id) +{ utils.TextureCache[id] = texture; }; @@ -298,7 +324,8 @@ * @param id {string} The id of the texture to be removed * @return {Texture} The texture that was removed */ -Texture.removeTextureFromCache = function (id) { +Texture.removeTextureFromCache = function (id) +{ var texture = utils.TextureCache[id]; delete utils.TextureCache[id]; diff --git a/src/core/textures/TextureUvs.js b/src/core/textures/TextureUvs.js index b9bbb58..5424d52 100644 --- a/src/core/textures/TextureUvs.js +++ b/src/core/textures/TextureUvs.js @@ -1,4 +1,5 @@ -function TextureUvs() { +function TextureUvs() +{ this.x0 = 0; this.y0 = 0; diff --git a/src/core/textures/VideoBaseTexture.js b/src/core/textures/VideoBaseTexture.js index e3e0c5a..1a826a9 100644 --- a/src/core/textures/VideoBaseTexture.js +++ b/src/core/textures/VideoBaseTexture.js @@ -12,15 +12,18 @@ * @param source {HTMLVideoElement} * @param [scaleMode] {number} See {@link scaleModes} for possible values */ -function VideoBaseTexture(source, scaleMode) { - if (!source){ +function VideoBaseTexture(source, scaleMode) +{ + if (!source) + { throw new Error('No video source element specified.'); } // hook in here to check if video is already available. // BaseTexture looks for a source.complete boolean, plus width & height. - if ((source.readyState === source.HAVE_ENOUGH_DATA || source.readyState === source.HAVE_FUTURE_DATA) && source.width && source.height) { + if ((source.readyState === source.HAVE_ENOUGH_DATA || source.readyState === source.HAVE_FUTURE_DATA) && source.width && source.height) + { source.complete = true; } @@ -31,7 +34,8 @@ this._boundOnUpdate = this._onUpdate.bind(this); this._boundOnCanPlay = this._onCanPlay.bind(this); - if (!source.complete) { + if (!source.complete) + { source.addEventListener('canplay', this._boundOnCanPlay); source.addEventListener('canplaythrough', this._boundOnCanPlay); @@ -47,28 +51,35 @@ VideoBaseTexture.prototype.constructor = VideoBaseTexture; module.exports = VideoBaseTexture; -VideoBaseTexture.prototype._onUpdate = function () { - if (this.autoUpdate) { +VideoBaseTexture.prototype._onUpdate = function () +{ + if (this.autoUpdate) + { window.requestAnimationFrame(this._boundOnUpdate); this.needsUpdate = true; } }; -VideoBaseTexture.prototype._onPlayStart = function () { - if (!this.autoUpdate) { +VideoBaseTexture.prototype._onPlayStart = function () +{ + if (!this.autoUpdate) + { window.requestAnimationFrame(this._boundOnUpdate); this.autoUpdate = true; } }; -VideoBaseTexture.prototype._onPlayStop = function () { +VideoBaseTexture.prototype._onPlayStop = function () +{ this.autoUpdate = false; }; -VideoBaseTexture.prototype._onCanPlay = function () { +VideoBaseTexture.prototype._onCanPlay = function () +{ this.hasLoaded = true; - if (this.source) { + if (this.source) + { this.source.removeEventListener('canplay', this._boundOnCanPlay); this.source.removeEventListener('canplaythrough', this._boundOnCanPlay); @@ -78,15 +89,18 @@ this.source.play(); // prevent multiple loaded dispatches.. - if(!this.__loaded){ + if(!this.__loaded) + { this.__loaded = true; this.emit('loaded', this); } } }; -VideoBaseTexture.prototype.destroy = function () { - if (this.source && this.source._pixiId) { +VideoBaseTexture.prototype.destroy = function () +{ + if (this.source && this.source._pixiId) + { utils.BaseTextureCache[ this.source._pixiId ] = null; delete utils.BaseTextureCache[ this.source._pixiId ]; @@ -105,14 +119,17 @@ * @param scaleMode {number} See {@link scaleModes} for possible values * @return {VideoBaseTexture} */ -VideoBaseTexture.fromVideo = function (video, scaleMode) { - if (!video._pixiId) { +VideoBaseTexture.fromVideo = function (video, scaleMode) +{ + if (!video._pixiId) + { video._pixiId = 'video_' + utils.uuid(); } var baseTexture = utils.BaseTextureCache[video._pixiId]; - if (!baseTexture) { + if (!baseTexture) + { baseTexture = new VideoBaseTexture(video, scaleMode); utils.BaseTextureCache[ video._pixiId ] = baseTexture; } @@ -147,17 +164,21 @@ * @param scaleMode {number} See {@link scaleModes} for possible values * @return {VideoBaseTexture} */ -VideoBaseTexture.fromUrl = function (videoSrc, scaleMode) { +VideoBaseTexture.fromUrl = function (videoSrc, scaleMode) +{ var video = document.createElement('video'); // array of objects or strings - if (Array.isArray(videoSrc)) { - for (var i = 0; i < videoSrc.length; ++i) { + if (Array.isArray(videoSrc)) + { + for (var i = 0; i < videoSrc.length; ++i) + { video.appendChild(createSource(videoSrc.src || videoSrc, videoSrc.mime)); } } // single object or string - else { + else + { video.appendChild(createSource(videoSrc.src || videoSrc, videoSrc.mime)); } @@ -169,8 +190,10 @@ VideoBaseTexture.fromUrls = VideoBaseTexture.fromUrl; -function createSource(path, type) { - if (!type) { +function createSource(path, type) +{ + if (!type) + { type = 'video/' + path.substr(path.lastIndexOf('.') + 1); } diff --git a/src/core/utils/EventData.js b/src/core/utils/EventData.js index 5d55a22..8cdf701 100644 --- a/src/core/utils/EventData.js +++ b/src/core/utils/EventData.js @@ -7,7 +7,8 @@ * @param name {string} The string name of the event that was triggered * @param data {object} Arbitrary event data to pass along */ -function EventData(target, name, data) { +function EventData(target, name, data) +{ // for duck typing in the ".on()" function this.__isEventObject = true; @@ -71,7 +72,8 @@ * Stops the propagation of events up the scene graph (prevents bubbling). * */ -EventData.prototype.stopPropagation = function stopPropagation() { +EventData.prototype.stopPropagation = function stopPropagation() +{ this.stopped = true; }; @@ -79,6 +81,7 @@ * Stops the propagation of events to sibling listeners (no longer calls any listeners). * */ -EventData.prototype.stopImmediatePropagation = function stopImmediatePropagation() { +EventData.prototype.stopImmediatePropagation = function stopImmediatePropagation() +{ this.stoppedImmediate = true; }; diff --git a/src/core/utils/EventTarget.js b/src/core/utils/EventTarget.js index 7ae8820..671a151 100644 --- a/src/core/utils/EventTarget.js +++ b/src/core/utils/EventTarget.js @@ -13,14 +13,16 @@ * var em = new MyEmitter(); * em.emit('eventName', 'some data', 'some more data', {}, null, ...); */ -function eventTarget(obj) { +function eventTarget(obj) +{ /** * Return a list of assigned event listeners. * * @param eventName {string} The events that should be listed. * @return {Array} An array of listener functions */ - obj.listeners = function listeners(eventName) { + obj.listeners = function listeners(eventName) + { this._listeners = this._listeners || {}; return this._listeners[eventName] ? this._listeners[eventName].slice() : []; @@ -33,22 +35,26 @@ * @param eventName {string} The name of the event. * @return {boolean} Indication if we've emitted an event. */ - obj.emit = obj.dispatchEvent = function emit(eventName, data) { + obj.emit = obj.dispatchEvent = function emit(eventName, data) + { this._listeners = this._listeners || {}; // fast return when there are no listeners - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return; } //backwards compat with old method ".emit({ type: 'something' })" - if (typeof eventName === 'object') { + if (typeof eventName === 'object') + { data = eventName; eventName = eventName.type; } //ensure we are using a real pixi event - if (!data || data.__isEventObject !== true) { + if (!data || data.__isEventObject !== true) + { data = new EventData(this, eventName, data); } @@ -58,23 +64,27 @@ fn = listeners[0], i; - for (i = 0; i < length; fn = listeners[++i]) { + for (i = 0; i < length; fn = listeners[++i]) + { //call the event listener fn.call(this, data); //if "stopImmediatePropagation" is called, stop calling sibling events - if (data.stoppedImmediate) { + if (data.stoppedImmediate) + { return this; } } //if "stopPropagation" is called then don't bubble the event - if (data.stopped) { + if (data.stopped) + { return this; } //bubble this event up the scene graph - if (this.parent && this.parent.emit) { + if (this.parent && this.parent.emit) + { this.parent.emit.call(this.parent, eventName, data); } @@ -88,7 +98,8 @@ * @param eventName {string} Name of the event. * @param callback {Functon} fn Callback function. */ - obj.on = obj.addEventListener = function on(eventName, fn) { + obj.on = obj.addEventListener = function on(eventName, fn) + { this._listeners = this._listeners || {}; (this._listeners[eventName] = this._listeners[eventName] || []) @@ -103,11 +114,13 @@ * @param eventName {string} Name of the event. * @param callback {Function} Callback function. */ - obj.once = function once(eventName, fn) { + obj.once = function once(eventName, fn) + { this._listeners = this._listeners || {}; var self = this; - function onceHandlerWrapper() { + function onceHandlerWrapper() + { fn.apply(self.off(eventName, onceHandlerWrapper), arguments); } onceHandlerWrapper._originalHandler = fn; @@ -122,23 +135,28 @@ * @param eventName {string} The event we want to remove. * @param callback {Function} The listener that we need to find. */ - obj.off = obj.removeEventListener = function off(eventName, fn) { + obj.off = obj.removeEventListener = function off(eventName, fn) + { this._listeners = this._listeners || {}; - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return this; } var list = this._listeners[eventName], i = fn ? list.length : 0; - while(i-- > 0) { - if (list[i] === fn || list[i]._originalHandler === fn) { + while(i-- > 0) + { + if (list[i] === fn || list[i]._originalHandler === fn) + { list.splice(i, 1); } } - if (list.length === 0) { + if (list.length === 0) + { delete this._listeners[eventName]; } @@ -150,10 +168,12 @@ * * @param eventName {string} The event you want to remove all listeners for. */ - obj.removeAllListeners = function removeAllListeners(eventName) { + obj.removeAllListeners = function removeAllListeners(eventName) + { this._listeners = this._listeners || {}; - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return this; } @@ -169,7 +189,8 @@ * * @param object {object} The obj to mix into */ - mixin: function mixin(obj) { + mixin: function mixin(obj) + { eventTarget(obj); } }; diff --git a/src/core/utils/PolyK.js b/src/core/utils/PolyK.js index 7325141..5e20c2b 100644 --- a/src/core/utils/PolyK.js +++ b/src/core/utils/PolyK.js @@ -47,7 +47,8 @@ * Triangulates shapes for webGL graphic fills. * */ -PolyK.Triangulate = function (p) { +PolyK.Triangulate = function (p) +{ var sign = true; var n = p.length >> 1; @@ -59,7 +60,8 @@ i = 0; var al = n; - while(al > 3) { + while(al > 3) + { var i0 = avl[(i+0)%al]; var i1 = avl[(i+1)%al]; var i2 = avl[(i+2)%al]; @@ -69,29 +71,35 @@ var cx = p[2*i2], cy = p[2*i2+1]; var earFound = false; - if (PolyK._convex(ax, ay, bx, by, cx, cy, sign)) { + if (PolyK._convex(ax, ay, bx, by, cx, cy, sign)) + { earFound = true; - for (var j = 0; j < al; j++) { + for (var j = 0; j < al; j++) + { var vi = avl[j]; if (vi === i0 || vi === i1 || vi === i2) continue; - if (PolyK._PointInTriangle(p[2*vi], p[2*vi+1], ax, ay, bx, by, cx, cy)) { + if (PolyK._PointInTriangle(p[2*vi], p[2*vi+1], ax, ay, bx, by, cx, cy)) + { earFound = false; break; } } } - if (earFound) { + if (earFound) + { tgs.push(i0, i1, i2); avl.splice((i+1)%al, 1); al--; i = 0; } - else if (i++ > 3*al) { + else if (i++ > 3*al) + { // need to flip flip reverse it! // reset! - if (sign) { + if (sign) + { tgs = []; avl = []; for (i = 0; i < n; i++) avl.push(i); @@ -101,7 +109,8 @@ sign = false; } - else { + else + { // window.console.log("PIXI Warning: shape too complex to fill"); return null; } @@ -126,7 +135,8 @@ * @private * @return {boolean} */ -PolyK._PointInTriangle = function (px, py, ax, ay, bx, by, cx, cy) { +PolyK._PointInTriangle = function (px, py, ax, ay, bx, by, cx, cy) +{ var v0x = cx-ax; var v0y = cy-ay; var v1x = bx-ax; @@ -154,6 +164,7 @@ * @private * @return {boolean} */ -PolyK._convex = function (ax, ay, bx, by, cx, cy, sign) { +PolyK._convex = function (ax, ay, bx, by, cx, cy, sign) +{ return ((ay-by)*(cx-bx) + (bx-ax)*(cy-by) >= 0) === sign; }; diff --git a/src/core/utils/index.js b/src/core/utils/index.js index ade9831..bfae7ae 100644 --- a/src/core/utils/index.js +++ b/src/core/utils/index.js @@ -16,7 +16,8 @@ * * @return {number} The next uuid to use. */ - uuid: function () { + uuid: function () + { return ++utils._uid; }, @@ -26,7 +27,8 @@ * @param hex {number} * @return {number[]} An array representing the [R, G, B] of the color. */ - hex2rgb: function (hex, out) { + hex2rgb: function (hex, out) + { out = out || []; out[0] = (hex >> 16 & 0xFF) / 255; @@ -42,7 +44,8 @@ * @param hex {number} * @return {string} The string color. */ - hex2string: function (hex) { + hex2string: function (hex) + { hex = hex.toString(16); hex = '000000'.substr(0, 6 - hex.length) + hex; @@ -55,7 +58,8 @@ * @param rgb {number[]} * @return {number} The color number */ - rgb2hex: function (rgb) { + rgb2hex: function (rgb) + { return ((rgb[0]*255 << 16) + (rgb[1]*255 << 8) + rgb[2]*255); }, @@ -64,8 +68,10 @@ * * @return {boolean} whether they are supported */ - canUseNewCanvasBlendModes: function () { - if (typeof document === 'undefined') { + canUseNewCanvasBlendModes: function () + { + if (typeof document === 'undefined') + { return false; } @@ -93,15 +99,19 @@ * @param number {number} * @return {number} the closest number that is a power of two */ - getNextPowerOfTwo: function (number) { + getNextPowerOfTwo: function (number) + { // see: http://en.wikipedia.org/wiki/Power_of_two#Fast_algorithm_to_check_if_a_positive_number_is_a_power_of_two - if (number > 0 && (number & (number - 1)) === 0) { + if (number > 0 && (number & (number - 1)) === 0) + { return number; } - else { + else + { var result = 1; - while (result < number) { + while (result < number) + { result <<= 1; } @@ -116,7 +126,8 @@ * @param height {number} * @return {boolean} */ - isPowerOfTwo: function (width, height) { + isPowerOfTwo: function (width, height) + { return (width > 0 && (width & (width - 1)) === 0 && height > 0 && (height & (height - 1)) === 0); }, @@ -130,12 +141,15 @@ * @constant * @static */ - sayHello: function (type) { - if (utils._saidHello) { + sayHello: function (type) + { + if (utils._saidHello) + { return; } - if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) { + if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) + { var args = [ '%c %c %c Pixi.js ' + CONST.VERSION + ' - ' + type + ' %c ' + ' %c ' + ' http://www.pixijs.com/ %c %c ♥%c♥%c♥ ', 'background: #ff66a5', @@ -151,7 +165,8 @@ console.log.apply(console, args); //jshint ignore:line } - else if (window.console) { + else if (window.console) + { console.log('Pixi.js ' + CONST.VERSION + ' - ' + type + ' - http://www.pixijs.com/'); //jshint ignore:line } @@ -166,15 +181,19 @@ * @class * @namespace PIXI */ - AjaxRequest: function () { + AjaxRequest: function () + { var activexmodes = ['Msxml2.XMLHTTP.6.0', 'Msxml2.XMLHTTP.3.0', 'Microsoft.XMLHTTP']; //activeX versions to check for in IE - if (window.ActiveXObject) { //Test for support for ActiveXObject in IE first (as XMLHttpRequest in IE7 is broken) - for (var i=0; i= this.textures.length) { + else if (round >= this.textures.length) + { this.gotoAndStop(this.textures.length - 1); - if (this.onComplete) { + if (this.onComplete) + { this.onComplete(); } } @@ -167,10 +182,12 @@ * @static * @param frames {string[]} the array of frames ids the movieclip will use as its texture frames */ -MovieClip.fromFrames = function (frames) { +MovieClip.fromFrames = function (frames) +{ var textures = []; - for (var i = 0; i < frames.length; ++i) { + for (var i = 0; i < frames.length; ++i) + { textures.push(new core.Texture.fromFrame(frames[i])); } @@ -183,10 +200,12 @@ * @static * @param images {string[]} the array of image urls the movieclip will use as its texture frames */ -MovieClip.fromImages = function (images) { +MovieClip.fromImages = function (images) +{ var textures = []; - for (var i = 0; i < images.length; ++i) { + for (var i = 0; i < images.length; ++i) + { textures.push(new core.Texture.fromImage(images[i])); } diff --git a/src/extras/Rope.js b/src/extras/Rope.js index c157ec4..9c87bc0 100644 --- a/src/extras/Rope.js +++ b/src/extras/Rope.js @@ -9,7 +9,8 @@ * @param {Array} points - An array of {Point}. * */ -function Rope(texture, points) { +function Rope(texture, points) +{ Strip.call(this, texture); this.points = points; @@ -31,10 +32,12 @@ * Refreshes * */ -Rope.prototype.refresh = function () { +Rope.prototype.refresh = function () +{ var points = this.points; - if (points.length < 1) { + if (points.length < 1) + { return; } @@ -59,20 +62,23 @@ var total = points.length, point, index, amount; - for (var i = 1; i < total; i++) { + for (var i = 1; i < total; i++) + { point = points[i]; index = i * 4; // time to do some smart drawing! amount = i / (total-1); - if (i%2) { + if (i%2) + { uvs[index] = amount; uvs[index+1] = 0; uvs[index+2] = amount; uvs[index+3] = 1; } - else { + else + { uvs[index] = amount; uvs[index+1] = 0; @@ -95,10 +101,12 @@ * * @private */ -Rope.prototype.updateTransform = function () { +Rope.prototype.updateTransform = function () +{ var points = this.points; - if (points.length < 1) { + if (points.length < 1) + { return; } @@ -113,14 +121,17 @@ var total = points.length, point, index, ratio, perpLength, num; - for (var i = 0; i < total; i++) { + for (var i = 0; i < total; i++) + { point = points[i]; index = i * 4; - if (i < points.length-1) { + if (i < points.length-1) + { nextPoint = points[i+1]; } - else { + else + { nextPoint = point; } @@ -129,7 +140,8 @@ ratio = (1 - (i / (total-1))) * 10; - if (ratio > 1) { + if (ratio > 1) + { ratio = 1; } @@ -157,7 +169,8 @@ * * @param texture {Texture} the texture that will be used */ -Rope.prototype.setTexture = function (texture) { +Rope.prototype.setTexture = function (texture) +{ // stop current texture this.texture = texture; //this.updateFrame = true; diff --git a/src/extras/Strip.js b/src/extras/Strip.js index c5e378f..57691b5 100644 --- a/src/extras/Strip.js +++ b/src/extras/Strip.js @@ -10,7 +10,8 @@ * @param height {number} the height * */ -function Strip(texture) { +function Strip(texture) +{ core.DisplayObjectContainer.call(this); /** @@ -70,9 +71,11 @@ * * @param renderer {WebGLRenderer} */ -Strip.prototype.renderWebGL = function (renderer) { +Strip.prototype.renderWebGL = function (renderer) +{ // if the sprite is not visible or the alpha is 0 then no need to render this element - if (!this.visible || this.alpha <= 0) { + if (!this.visible || this.alpha <= 0) + { return; } @@ -81,7 +84,8 @@ renderer.spriteBatch.stop(); // init! init! - if (!this._vertexBuffer) { + if (!this._vertexBuffer) + { this._initWebGL(renderer); } @@ -96,7 +100,8 @@ //TODO check culling }; -Strip.prototype._initWebGL = function (renderer) { +Strip.prototype._initWebGL = function (renderer) +{ // build the strip! var gl = renderer.gl; @@ -118,7 +123,8 @@ gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this.indices, gl.STATIC_DRAW); }; -Strip.prototype._renderStrip = function (renderer) { +Strip.prototype._renderStrip = function (renderer) +{ var gl = renderer.gl; var projection = renderer.projection, offset = renderer.offset, @@ -137,7 +143,8 @@ gl.uniform2f(shader.offsetVector, -offset.x, -offset.y); gl.uniform1f(shader.alpha, this.worldAlpha); - if (!this.dirty) { + if (!this.dirty) + { gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexBuffer); gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); @@ -150,10 +157,12 @@ gl.activeTexture(gl.TEXTURE0); // check if a texture is dirty.. - if (this.texture.baseTexture._dirty[gl.id]) { + if (this.texture.baseTexture._dirty[gl.id]) + { renderer.updateTexture(this.texture.baseTexture); } - else { + else + { // bind the current texture gl.bindTexture(gl.TEXTURE_2D, this.texture.baseTexture._glTextures[gl.id]); } @@ -163,7 +172,8 @@ } - else { + else + { this.dirty = false; gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexBuffer); @@ -178,10 +188,12 @@ gl.activeTexture(gl.TEXTURE0); // check if a texture is dirty.. - if (this.texture.baseTexture._dirty[gl.id]) { + if (this.texture.baseTexture._dirty[gl.id]) + { renderer.updateTexture(this.texture.baseTexture); } - else { + else + { gl.bindTexture(gl.TEXTURE_2D, this.texture.baseTexture._glTextures[gl.id]); } @@ -203,27 +215,33 @@ * * @param renderer {CanvasRenderer} */ -Strip.prototype.renderCanvas = function (renderer) { +Strip.prototype.renderCanvas = function (renderer) +{ var context = renderer.context; var transform = this.worldTransform; - if (renderer.roundPixels) { + if (renderer.roundPixels) + { context.setTransform(transform.a, transform.b, transform.c, transform.d, transform.tx | 0, transform.ty | 0); } - else { + else + { context.setTransform(transform.a, transform.b, transform.c, transform.d, transform.tx, transform.ty); } - if (this.drawMode === Strip.DrawModes.TRIANGLE_STRIP) { + if (this.drawMode === Strip.DrawModes.TRIANGLE_STRIP) + { this._renderCanvasTriangleStrip(context); } - else { + else + { this._renderCanvasTriangles(context); } }; -Strip.prototype._renderCanvasTriangleStrip = function (context) { +Strip.prototype._renderCanvasTriangleStrip = function (context) +{ // draw triangles!! var vertices = this.vertices; var uvs = this.uvs; @@ -231,14 +249,16 @@ var length = vertices.length / 2; // this.count++; - for (var i = 0; i < length - 2; i++) { + for (var i = 0; i < length - 2; i++) + { // draw some triangles! var index = i * 2; this._renderCanvasDrawTriangle(context, vertices, uvs, index, (index + 2), (index + 4)); } }; -Strip.prototype._renderCanvasTriangles = function (context) { +Strip.prototype._renderCanvasTriangles = function (context) +{ // draw triangles!! var vertices = this.vertices; var uvs = this.uvs; @@ -247,14 +267,16 @@ var length = indices.length; // this.count++; - for (var i = 0; i < length; i += 3) { + for (var i = 0; i < length; i += 3) + { // draw some triangles! var index0 = indices[i] * 2, index1 = indices[i + 1] * 2, index2 = indices[i + 2] * 2; this._renderCanvasDrawTriangle(context, vertices, uvs, index0, index1, index2); } }; -Strip.prototype._renderCanvasDrawTriangle = function (context, vertices, uvs, index0, index1, index2) { +Strip.prototype._renderCanvasDrawTriangle = function (context, vertices, uvs, index0, index1, index2) +{ var textureSource = this.texture.baseTexture.source; var textureWidth = this.texture.width; var textureHeight = this.texture.height; @@ -265,7 +287,8 @@ var u0 = uvs[index0] * textureWidth, u1 = uvs[index1] * textureWidth, u2 = uvs[index2] * textureWidth; var v0 = uvs[index0 + 1] * textureHeight, v1 = uvs[index1 + 1] * textureHeight, v2 = uvs[index2 + 1] * textureHeight; - if (this.canvasPadding > 0) { + if (this.canvasPadding > 0) + { var paddingX = this.canvasPadding / this.worldTransform.a; var paddingY = this.canvasPadding / this.worldTransform.d; var centerX = (x0 + x1 + x2) / 3; @@ -332,7 +355,8 @@ * @param strip {Strip} The Strip to render * @private */ -Strip.prototype.renderStripFlat = function (strip) { +Strip.prototype.renderStripFlat = function (strip) +{ var context = this.context; var vertices = strip.vertices; @@ -340,7 +364,8 @@ // this.count++; context.beginPath(); - for (var i=1; i < length-2; i++) { + for (var i=1; i < length-2; i++) + { // draw some triangles! var index = i*2; @@ -358,7 +383,8 @@ }; /* -Strip.prototype.setTexture = function (texture) { +Strip.prototype.setTexture = function (texture) +{ //TODO SET THE TEXTURES //TODO VISIBILITY @@ -377,7 +403,8 @@ * @private */ -Strip.prototype.onTextureUpdate = function () { +Strip.prototype.onTextureUpdate = function () +{ this.updateFrame = true; }; @@ -387,7 +414,8 @@ * @param matrix {Matrix} the transformation matrix of the sprite * @return {Rectangle} the framing rectangle */ -Strip.prototype.getBounds = function (matrix) { +Strip.prototype.getBounds = function (matrix) +{ var worldTransform = matrix || this.worldTransform; var a = worldTransform.a; @@ -404,7 +432,8 @@ var minY = Infinity; var vertices = this.vertices; - for (var i = 0, n = vertices.length; i < n; i += 2) { + for (var i = 0, n = vertices.length; i < n; i += 2) + { var rawX = vertices[i], rawY = vertices[i + 1]; var x = (a * rawX) + (c * rawY) + tx; var y = (d * rawY) + (b * rawX) + ty; @@ -416,7 +445,8 @@ maxY = y > maxY ? y : maxY; } - if (minX === -Infinity || maxY === Infinity) { + if (minX === -Infinity || maxY === Infinity) + { return core.math.Rectangle.EMPTY; } diff --git a/src/extras/TilingSprite.js b/src/extras/TilingSprite.js index 3ac22df..31da393 100644 --- a/src/extras/TilingSprite.js +++ b/src/extras/TilingSprite.js @@ -10,7 +10,8 @@ * @param width {number} the width of the tiling sprite * @param height {number} the height of the tiling sprite */ -function TilingSprite(texture, width, height) { +function TilingSprite(texture, width, height) +{ core.Sprite.call( this, texture); /** @@ -86,10 +87,12 @@ * @memberof TilingSprite# */ width: { - get: function () { + get: function () + { return this._width; }, - set: function (value) { + set: function (value) + { this._width = value; } }, @@ -101,20 +104,25 @@ * @memberof TilingSprite# */ height: { - get: function () { + get: function () + { return this._height; }, - set: function (value) { + set: function (value) + { this._height = value; } }, texture: { - get: function () { + get: function () + { return this._texture; }, - set: function (value) { - if (this._texture === value) { + set: function (value) + { + if (this._texture === value) + { return; } @@ -130,51 +138,61 @@ * * @param renderer {WebGLRenderer} */ -TilingSprite.prototype.renderWebGL = function (renderer) { - if (!this.visible || this.alpha <= 0) { +TilingSprite.prototype.renderWebGL = function (renderer) +{ + if (!this.visible || this.alpha <= 0) + { return; } var i, j; - if (this._mask) { + if (this._mask) + { renderer.spriteBatch.stop(); renderer.maskManager.pushMask(this.mask, renderer); renderer.spriteBatch.start(); } - if (this._filters) { + if (this._filters) + { renderer.spriteBatch.flush(); renderer.filterManager.pushFilter(this._filterBlock); } - if (!this.tilingTexture || this.refreshTexture) { + if (!this.tilingTexture || this.refreshTexture) + { this.generateTilingTexture(true); - if (this.tilingTexture && this.tilingTexture.needsUpdate) { + if (this.tilingTexture && this.tilingTexture.needsUpdate) + { //TODO - tweaking renderer.updateTexture(this.tilingTexture.baseTexture); this.tilingTexture.needsUpdate = false; // this.tilingTexture._uvs = null; } } - else { + else + { renderer.spriteBatch.renderTilingSprite(this); } // simple render children! - for (i=0,j=this.children.length; i= 0 && index <= this.children.length) { - if (child.parent) { + if (index >= 0 && index <= this.children.length) + { + if (child.parent) + { child.parent.removeChild(child); } @@ -154,7 +173,8 @@ return child; } - else { + else + { throw new Error(child + 'addChildAt: The index '+ index +' supplied is out of bounds ' + this.children.length); } }; @@ -165,15 +185,18 @@ * @param child {DisplayObject} * @param child2 {DisplayObject} */ -DisplayObjectContainer.prototype.swapChildren = function (child, child2) { - if (child === child2) { +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) { + if (index1 < 0 || index2 < 0) + { throw new Error('swapChildren: Both the supplied DisplayObjects must be a child of the caller.'); } @@ -187,10 +210,12 @@ * @param child {DisplayObject} The DisplayObject instance to identify * @return {Number} The index position of the child display object to identify */ -DisplayObjectContainer.prototype.getChildIndex = function (child) { +DisplayObjectContainer.prototype.getChildIndex = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { throw new Error('The supplied DisplayObject must be a child of the caller'); } @@ -203,8 +228,10 @@ * @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 */ -DisplayObjectContainer.prototype.setChildIndex = function (child, index) { - if (index < 0 || index >= this.children.length) { +DisplayObjectContainer.prototype.setChildIndex = function (child, index) +{ + if (index < 0 || index >= this.children.length) + { throw new Error('The supplied index is out of bounds'); } @@ -220,8 +247,10 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child at the given index, if any. */ -DisplayObjectContainer.prototype.getChildAt = function (index) { - if (index < 0 || index >= this.children.length) { +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'); } @@ -234,10 +263,12 @@ * @param child {DisplayObject} The DisplayObject to remove * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChild = function (child) { +DisplayObjectContainer.prototype.removeChild = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { return; } @@ -250,7 +281,8 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChildAt = function (index) { +DisplayObjectContainer.prototype.removeChildAt = function (index) +{ var child = this.getChildAt(index); child.parent = null; @@ -265,24 +297,29 @@ * @param beginIndex {Number} The beginning position. Default value is 0. * @param endIndex {Number} The ending position. Default value is size of the container. */ -DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) { +DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) +{ var begin = beginIndex || 0; var end = typeof endIndex === 'number' ? endIndex : this.children.length; var range = end - begin; - if (range > 0 && range <= end) { + if (range > 0 && range <= end) + { var removed = this.children.splice(begin, range); - for (var i = 0; i < removed.length; ++i) { + for (var i = 0; i < removed.length; ++i) + { removed[i].parent = null; } return removed; } - else if (range === 0 && this.children.length === 0) { + else if (range === 0 && this.children.length === 0) + { return []; } - else { + else + { throw new RangeError('removeChildren: numeric values are outside the acceptable range.'); } }; @@ -291,7 +328,8 @@ * Generates and updates the cached sprite for this object. * */ -DisplayObjectContainer.prototype.updateCachedSprite = function () { +DisplayObjectContainer.prototype.updateCachedSprite = function () +{ this._generateCachedSprite(); }; @@ -304,7 +342,8 @@ * @param renderer {CanvasRenderer|WebGLRenderer} The renderer used to generate the texture. * @return {Texture} a texture of the graphics object */ -DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) { +DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) +{ var bounds = this.getLocalBounds(); var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0, renderer, scaleMode, resolution); @@ -322,18 +361,22 @@ * * @private */ -DisplayObjectContainer.prototype.updateTransform = function () { - if (!this.visible) { +DisplayObjectContainer.prototype.updateTransform = function () +{ + if (!this.visible) + { return; } this.displayObjectUpdateTransform(); - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { return; } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } }; @@ -346,8 +389,10 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getBounds = function () { - if (this.children.length === 0) { +DisplayObjectContainer.prototype.getBounds = function () +{ + if (this.children.length === 0) + { return math.Rectangle.EMPTY; } @@ -365,10 +410,12 @@ var childVisible = false; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -386,7 +433,8 @@ maxY = maxY > childMaxY ? maxY : childMaxY; } - if (!childVisible) { + if (!childVisible) + { return math.Rectangle.EMPTY; } @@ -407,12 +455,14 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getLocalBounds = function () { +DisplayObjectContainer.prototype.getLocalBounds = function () +{ var matrixCache = this.worldTransform; this.worldTransform = math.Matrix.IDENTITY; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } @@ -428,13 +478,16 @@ * * @param renderer {WebGLRenderer} The renderer */ -DisplayObjectContainer.prototype.renderWebGL = function (renderer) { +DisplayObjectContainer.prototype.renderWebGL = function (renderer) +{ // if the object is not visible or the alpha is 0 then no need to render this element - if (!this.visible || this.alpha <= 0) { + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } @@ -442,14 +495,17 @@ var i, j; // do a quick check to see if this element has a mask or a filter. - if (this._mask || this._filters) { + if (this._mask || this._filters) + { // push filter first as we need to ensure the stencil buffer is correct for any masking - if (this._filters) { + if (this._filters) + { renderer.spriteBatch.flush(); renderer.filterManager.pushFilter(this._filterBlock); } - if (this._mask) { + if (this._mask) + { renderer.spriteBatch.stop(); renderer.maskManager.pushMask(this.mask, renderer); renderer.spriteBatch.start(); @@ -459,36 +515,42 @@ this._renderWebGL(renderer); // now loop through the children and make sure they get rendered - for (i = 0, j = this.children.length; i < j; i++) { + for (i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderWebGL(renderer); } // time to stop the sprite batch as either a mask element or a filter draw will happen next renderer.spriteBatch.stop(); - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(this._mask, renderer); } - if (this._filters) { + if (this._filters) + { renderer.filterManager.popFilter(); } renderer.spriteBatch.start(); } - else { + else + { this._renderWebGL(renderer); // simple render children! - for (i = 0, j = this.children.length; i < j; ++i) { + for (i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderWebGL(renderer); } } }; -DisplayObjectContainer.prototype._renderWebGL = function (renderer) { +DisplayObjectContainer.prototype._renderWebGL = function (renderer) +{ // this is where content itself gets renderd.. @@ -499,25 +561,31 @@ * * @param renderer {CanvasRenderer} The renderer */ -DisplayObjectContainer.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0) { +DisplayObjectContainer.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -528,13 +596,16 @@ * @param renderer {WebGLRenderer|CanvasRenderer} The renderer * @private */ -DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) { +DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) +{ this._cachedSprite.worldAlpha = this.worldAlpha; - if (renderer.gl) { + if (renderer.gl) + { this._cachedSprite.renderWebGL(renderer); } - else { + else + { this._cachedSprite.renderCanvas(renderer); } }; @@ -544,10 +615,12 @@ * * @private */ -DisplayObjectContainer.prototype._generateCachedSprite = function () { +DisplayObjectContainer.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { // TODO - RenderTexture now *requires* a renderer instance, so this is like broken // because `renderer` isn't actually in scope here :P var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0); @@ -555,7 +628,8 @@ this._cachedSprite = new Sprite(renderTexture); this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.texture.resize(bounds.width | 0, bounds.height | 0); } @@ -580,8 +654,10 @@ * * @private */ -DisplayObjectContainer.prototype._destroyCachedSprite = function () { - if (!this._cachedSprite) { +DisplayObjectContainer.prototype._destroyCachedSprite = function () +{ + if (!this._cachedSprite) + { return; } diff --git a/src/core/display/Sprite.js b/src/core/display/Sprite.js index 707da24..5862aef 100644 --- a/src/core/display/Sprite.js +++ b/src/core/display/Sprite.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param texture {Texture} The texture for this sprite */ -function Sprite(texture) { +function Sprite(texture) +{ DisplayObjectContainer.call(this); /** @@ -85,12 +86,14 @@ this.texture = texture || Texture.EMPTY; } -Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) { +Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) +{ DisplayObjectContainer.prototype.destroy.call(this); this.anchor = null; - if (destroyTexture) { + if (destroyTexture) + { this._texture.destroy(destroyBaseTexture); } @@ -111,10 +114,12 @@ * @memberof Sprite# */ width: { - get: function () { + get: function () + { return this.scale.x * this.texture.frame.width; }, - set: function (value) { + set: function (value) + { this.scale.x = value / this.texture.frame.width; this._width = value; } @@ -127,10 +132,12 @@ * @memberof Sprite# */ height: { - get: function () { + get: function () + { return this.scale.y * this.texture.frame.height; }, - set: function (value) { + set: function (value) + { this.scale.y = value / this.texture.frame.height; this._height = value; } @@ -143,23 +150,29 @@ * @memberof Sprite# */ texture: { - get: function () { + get: function () + { return this._texture; }, - set: function (value) { - if (this._texture === value) { + set: function (value) + { + if (this._texture === value) + { return; } this._texture = value; this.cachedTint = 0xFFFFFF; - if (value) { + if (value) + { // wait for the texture to load - if (value.baseTexture.hasLoaded) { + if (value.baseTexture.hasLoaded) + { this._onTextureUpdate(); } - else { + else + { value.once('update', this._onTextureUpdate.bind(this)); } } @@ -172,18 +185,22 @@ * * @private */ -Sprite.prototype._onTextureUpdate = function () { +Sprite.prototype._onTextureUpdate = function () +{ // so if _width is 0 then width was not set.. - if (this._width) { + if (this._width) + { this.scale.x = this._width / this.texture.frame.width; } - if (this._height) { + if (this._height) + { this.scale.y = this._height / this.texture.frame.height; } }; -Sprite.prototype._renderWebGL = function (renderer) { +Sprite.prototype._renderWebGL = function (renderer) +{ // this is where content gets renderd.. // watch this space for a little render state manager.. @@ -197,7 +214,8 @@ * @param matrix {Matrix} the transformation matrix of the sprite * @return {Rectangle} the framing rectangle */ -Sprite.prototype.getBounds = function (matrix) { +Sprite.prototype.getBounds = function (matrix) +{ var width = this.texture.frame.width; var height = this.texture.frame.height; @@ -224,11 +242,13 @@ if(b === 0 && c === 0) { // scale may be negative! - if (a < 0) { + if (a < 0) + { a *= -1; } - if (d < 0) { + if (d < 0) + { d *= -1; } @@ -293,28 +313,34 @@ * * @param renderer {CanvasRenderer} The renderer */ -Sprite.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) { +Sprite.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) + { return; } - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; renderer.context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } // Ignore null sources - if (this.texture.valid) { + if (this.texture.valid) + { var resolution = this.texture.baseTexture.resolution / renderer.resolution; renderer.context.globalAlpha = this.worldAlpha; // If smoothingEnabled is supported and we need to change the smoothing property for this texture - if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) { + if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) + { renderer.scaleMode = this.texture.baseTexture.scaleMode; renderer.context[renderer.smoothProperty] = (renderer.scaleMode === CONST.scaleModes.LINEAR); } @@ -324,7 +350,8 @@ var dy = (this.texture.trim ? this.texture.trim.y : 0) - (this.anchor.y * this.texture.trim.height); // Allow for pixel rounding - if (renderer.roundPixels) { + if (renderer.roundPixels) + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -337,7 +364,8 @@ dx = dx | 0; dy = dy | 0; } - else { + else + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -348,8 +376,10 @@ ); } - if (this.tint !== 0xFFFFFF) { - if (this.cachedTint !== this.tint) { + if (this.tint !== 0xFFFFFF) + { + if (this.cachedTint !== this.tint) + { this.cachedTint = this.tint; // TODO clean up caching - how to clean up the caches? @@ -368,7 +398,8 @@ this.texture.crop.height / resolution ); } - else { + else + { renderer.context.drawImage( this.texture.baseTexture.source, this.texture.crop.x, @@ -383,11 +414,13 @@ } } - for (var i = 0, j = this.children.length; i < j; i++) { + for (var i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -402,10 +435,12 @@ * @param frameId {String} The frame Id of the texture in the cache * @return {Sprite} A new Sprite using a texture from the texture cache matching the frameId */ -Sprite.fromFrame = function (frameId) { +Sprite.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache' + this); } @@ -420,6 +455,7 @@ * @param imageId {String} The image url of the texture * @return {Sprite} A new Sprite using a texture from the texture cache matching the image id */ -Sprite.fromImage = function (imageId, crossorigin, scaleMode) { +Sprite.fromImage = function (imageId, crossorigin, scaleMode) +{ return new Sprite(Texture.fromImage(imageId, crossorigin, scaleMode)); }; diff --git a/src/core/display/SpriteBatch.js b/src/core/display/SpriteBatch.js index 3187777..c196fef 100644 --- a/src/core/display/SpriteBatch.js +++ b/src/core/display/SpriteBatch.js @@ -12,7 +12,8 @@ * ```js * var container = new SpriteBatch(); * - * for(var i = 0; i < 100; ++i) { + * for(var i = 0; i < 100; ++i) + * { * var sprite = new PIXI.Sprite.fromImage("myImage.png"); * container.addChild(sprite); * } @@ -25,7 +26,8 @@ */ //TODO RENAME to PARTICLE CONTAINER? -function SpriteBatch() { +function SpriteBatch() +{ DisplayObjectContainer.call(this); } @@ -38,7 +40,8 @@ * * @private */ -SpriteBatch.prototype.updateTransform = function () { +SpriteBatch.prototype.updateTransform = function () +{ // TODO don't need to! this.displayObjectUpdateTransform(); // PIXI.DisplayObjectContainer.prototype.updateTransform.call( this ); @@ -50,8 +53,10 @@ * @param renderer {WebGLRenderer} The webgl renderer * @private */ -SpriteBatch.prototype.renderWebGL = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderWebGL = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -71,8 +76,10 @@ * @param renderer {CanvasRenderer} The canvas renderer * @private */ -SpriteBatch.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -84,10 +91,12 @@ this.displayObjectUpdateTransform(); - for (var i = 0; i < this.children.length; ++i) { + for (var i = 0; i < this.children.length; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -95,9 +104,11 @@ context.globalAlpha = this.worldAlpha * child.alpha; - if (child.rotation % (Math.PI * 2) === 0) { + if (child.rotation % (Math.PI * 2) === 0) + { // this is the fastest way to optimise! - if rotation is 0 then we can avoid any kind of setTransform call - if (isRotated) { + if (isRotated) + { context.setTransform( transform.a, transform.b, @@ -122,8 +133,10 @@ frame.height * child.scale.y ); } - else { - if (!isRotated) { + else + { + if (!isRotated) + { isRotated = true; } @@ -131,7 +144,8 @@ var childTransform = child.worldTransform; - if (renderer.roundPixels) { + if (renderer.roundPixels) + { context.setTransform( childTransform.a, childTransform.b, @@ -141,7 +155,8 @@ childTransform.ty | 0 ); } - else { + else + { context.setTransform( childTransform.a, childTransform.b, diff --git a/src/core/index.js b/src/core/index.js index 3954b6f..eb4a82b 100644 --- a/src/core/index.js +++ b/src/core/index.js @@ -58,11 +58,13 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRenderer: function (width, height, options, noWebGL) { + autoDetectRenderer: function (width, height, options, noWebGL) + { width = width || 800; height = height || 600; - if (!noWebGL && require('webgl-enabled')()) { + if (!noWebGL && require('webgl-enabled')()) + { return new core.WebGLRenderer(width, height, options); } @@ -87,7 +89,8 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRecommendedRenderer: function (width, height, options) { + autoDetectRecommendedRenderer: function (width, height, options) + { var isAndroid = /Android/i.test(navigator.userAgent); return core.autoDetectRenderer(width, height, options, isAndroid); diff --git a/src/core/math/Matrix.js b/src/core/math/Matrix.js index c2f87e2..2ff4848 100644 --- a/src/core/math/Matrix.js +++ b/src/core/math/Matrix.js @@ -10,7 +10,8 @@ * @class * @namespace PIXI */ -function Matrix() { +function Matrix() +{ /** * @member {number} * @default 1 @@ -63,7 +64,8 @@ * * @param array {number[]} The array that the matrix will be populated from. */ -Matrix.prototype.fromArray = function (array) { +Matrix.prototype.fromArray = function (array) +{ this.a = array[0]; this.b = array[1]; this.c = array[3]; @@ -78,14 +80,17 @@ * @param transpose {boolean} Whether we need to transpose the matrix or not * @return {number[]} the newly created array which contains the matrix */ -Matrix.prototype.toArray = function (transpose) { - if (!this.array) { +Matrix.prototype.toArray = function (transpose) +{ + if (!this.array) + { this.array = new Float32Array(9); } var array = this.array; - if (transpose) { + if (transpose) + { array[0] = this.a; array[1] = this.b; array[2] = 0; @@ -96,7 +101,8 @@ array[7] = this.ty; array[8] = 1; } - else { + else + { array[0] = this.a; array[1] = this.c; array[2] = this.tx; @@ -119,7 +125,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, transformed through this matrix */ -Matrix.prototype.apply = function (pos, newPos) { +Matrix.prototype.apply = function (pos, newPos) +{ newPos = newPos || new Point(); newPos.x = this.a * pos.x + this.c * pos.y + this.tx; @@ -136,7 +143,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, inverse-transformed through this matrix */ -Matrix.prototype.applyInverse = function (pos, newPos) { +Matrix.prototype.applyInverse = function (pos, newPos) +{ newPos = newPos || new Point(); var id = 1 / (this.a * this.d + this.c * -this.b); @@ -154,7 +162,8 @@ * @param {number} y * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.translate = function (x, y) { +Matrix.prototype.translate = function (x, y) +{ this.tx += x; this.ty += y; @@ -168,7 +177,8 @@ * @param {number} y The amount to scale vertically * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.scale = function (x, y) { +Matrix.prototype.scale = function (x, y) +{ this.a *= x; this.d *= y; this.c *= x; @@ -186,7 +196,8 @@ * @param {number} angle - The angle in radians. * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.rotate = function (angle) { +Matrix.prototype.rotate = function (angle) +{ var cos = Math.cos( angle ); var sin = Math.sin( angle ); @@ -210,7 +221,8 @@ * @param {Matrix} matrix * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.append = function (matrix) { +Matrix.prototype.append = function (matrix) +{ var a1 = this.a; var b1 = this.b; var c1 = this.c; @@ -232,7 +244,8 @@ * * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.identity = function () { +Matrix.prototype.identity = function () +{ this.a = 1; this.b = 0; this.c = 0; diff --git a/src/core/math/Point.js b/src/core/math/Point.js index 7565b2d..632f346 100644 --- a/src/core/math/Point.js +++ b/src/core/math/Point.js @@ -7,7 +7,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -function Point(x, y) { +function Point(x, y) +{ /** * @member {number} * @default 0 @@ -29,7 +30,8 @@ * * @return {Point} a copy of the point */ -Point.prototype.clone = function () { +Point.prototype.clone = function () +{ return new Point(this.x, this.y); }; @@ -40,7 +42,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -Point.prototype.set = function (x, y) { +Point.prototype.set = function (x, y) +{ this.x = x || 0; this.y = y || ( (y !== 0) ? this.x : 0 ) ; }; diff --git a/src/core/math/shapes/Circle.js b/src/core/math/shapes/Circle.js index 69cfdc9..4d76efc 100644 --- a/src/core/math/shapes/Circle.js +++ b/src/core/math/shapes/Circle.js @@ -10,7 +10,8 @@ * @param y {number} The Y coordinate of the center of this circle * @param radius {number} The radius of the circle */ -function Circle(x, y, radius) { +function Circle(x, y, radius) +{ /** * @member {number} * @default 0 @@ -46,7 +47,8 @@ * @method clone * @return {Circle} a copy of the Circle */ -Circle.prototype.clone = function () { +Circle.prototype.clone = function () +{ return new Circle(this.x, this.y, this.radius); }; @@ -58,8 +60,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Circle */ -Circle.prototype.contains = function (x, y) { - if (this.radius <= 0) { +Circle.prototype.contains = function (x, y) +{ + if (this.radius <= 0) + { return false; } @@ -79,6 +83,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Circle.prototype.getBounds = function () { +Circle.prototype.getBounds = function () +{ return new Rectangle(this.x - this.radius, this.y - this.radius, this.radius * 2, this.radius * 2); }; diff --git a/src/core/math/shapes/Ellipse.js b/src/core/math/shapes/Ellipse.js index 4f2d066..fefd01a 100644 --- a/src/core/math/shapes/Ellipse.js +++ b/src/core/math/shapes/Ellipse.js @@ -11,7 +11,8 @@ * @param width {number} The half width of this ellipse * @param height {number} The half height of this ellipse */ -function Ellipse(x, y, width, height) { +function Ellipse(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -53,7 +54,8 @@ * @method clone * @return {Ellipse} a copy of the ellipse */ -Ellipse.prototype.clone = function () { +Ellipse.prototype.clone = function () +{ return new Ellipse(this.x, this.y, this.width, this.height); }; @@ -65,8 +67,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coords are within this ellipse */ -Ellipse.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Ellipse.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } @@ -86,6 +90,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Ellipse.prototype.getBounds = function () { +Ellipse.prototype.getBounds = function () +{ return new Rectangle(this.x - this.width, this.y - this.height, this.width, this.height); }; diff --git a/src/core/math/shapes/Polygon.js b/src/core/math/shapes/Polygon.js index ae89148..fea6d37 100644 --- a/src/core/math/shapes/Polygon.js +++ b/src/core/math/shapes/Polygon.js @@ -10,16 +10,20 @@ * arguments passed can be flat x,y values e.g. `new Polygon(x,y, x,y, x,y, ...)` where `x` and `y` are * Numbers. */ -function Polygon(points) { +function Polygon(points) +{ //if points isn't an array, use arguments as the array - if (!(points instanceof Array)) { + if (!(points instanceof Array)) + { points = Array.prototype.slice.call(arguments); } //if this is a flat array of numbers, convert it to points - if (points[0] instanceof Point) { + if (points[0] instanceof Point) + { var p = []; - for (var i = 0, il = points.length; i < il; i++) { + for (var i = 0, il = points.length; i < il; i++) + { p.push(points[i].x, points[i].y); } @@ -51,7 +55,8 @@ * * @return {Polygon} a copy of the polygon */ -Polygon.prototype.clone = function () { +Polygon.prototype.clone = function () +{ return new Polygon(this.points.slice()); }; @@ -62,19 +67,22 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this polygon */ -Polygon.prototype.contains = function (x, y) { +Polygon.prototype.contains = function (x, y) +{ var inside = false; // use some raycasting to test hits // https://github.com/substack/point-in-polygon/blob/master/index.js var length = this.points.length / 2; - for (var i = 0, j = length - 1; i < length; j = i++) { + for (var i = 0, j = length - 1; i < length; j = i++) + { var xi = this.points[i * 2], yi = this.points[i * 2 + 1], xj = this.points[j * 2], yj = this.points[j * 2 + 1], intersect = ((yi > y) !== (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi); - if (intersect) { + if (intersect) + { inside = !inside; } } diff --git a/src/core/math/shapes/Rectangle.js b/src/core/math/shapes/Rectangle.js index 16ac62a..4008b68 100644 --- a/src/core/math/shapes/Rectangle.js +++ b/src/core/math/shapes/Rectangle.js @@ -10,7 +10,8 @@ * @param width {number} The overall width of this rectangle * @param height {number} The overall height of this rectangle */ -function Rectangle(x, y, width, height) { +function Rectangle(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -60,7 +61,8 @@ * * @return {Rectangle} a copy of the rectangle */ -Rectangle.prototype.clone = function () { +Rectangle.prototype.clone = function () +{ return new Rectangle(this.x, this.y, this.width, this.height); }; @@ -71,13 +73,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rectangle */ -Rectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Rectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/math/shapes/RoundedRectangle.js b/src/core/math/shapes/RoundedRectangle.js index 27d286e..7bf6411 100644 --- a/src/core/math/shapes/RoundedRectangle.js +++ b/src/core/math/shapes/RoundedRectangle.js @@ -11,7 +11,8 @@ * @param height {number} The overall height of this rounded rectangle * @param radius {number} Controls the radius of the rounded corners */ -function RoundedRectangle(x, y, width, height, radius) { +function RoundedRectangle(x, y, width, height, radius) +{ /** * @member {number} * @default 0 @@ -58,7 +59,8 @@ * * @return {RoundedRectangle} a copy of the rounded rectangle */ -RoundedRectangle.prototype.clone = function () { +RoundedRectangle.prototype.clone = function () +{ return new RoundedRectangle(this.x, this.y, this.width, this.height, this.radius); }; @@ -69,13 +71,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rounded Rectangle */ -RoundedRectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +RoundedRectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/primitives/Graphics.js b/src/core/primitives/Graphics.js index 261c534..e902d2a 100644 --- a/src/core/primitives/Graphics.js +++ b/src/core/primitives/Graphics.js @@ -16,7 +16,8 @@ * @extends DisplayObjectContainer * @namespace PIXI */ -function Graphics() { +function Graphics() +{ DisplayObjectContainer.call(this); this.renderable = true; @@ -154,16 +155,20 @@ * @private */ cacheAsBitmap: { - get: function () { + get: function () + { return this._cacheAsBitmap; }, - set: function (value) { + set: function (value) + { this._cacheAsBitmap = value; - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._generateCachedSprite(); } - else { + else + { this.destroyCachedSprite(); this.dirty = true; } @@ -176,7 +181,8 @@ * * @return {Graphics} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ var clone = new Graphics(); clone.renderable = this.renderable; @@ -192,7 +198,8 @@ clone.cachedSpriteDirty = this.cachedSpriteDirty; // copy graphics data - for (var i = 0; i < this.graphicsData.length; ++i) { + for (var i = 0; i < this.graphicsData.length; ++i) + { clone.graphicsData.push(this.graphicsData.clone()); } @@ -211,17 +218,21 @@ * @param alpha {number} alpha of the line to draw, will update the objects stored style * @return {Graphics} */ -Graphics.prototype.lineStyle = function (lineWidth, color, alpha) { +Graphics.prototype.lineStyle = function (lineWidth, color, alpha) +{ this.lineWidth = lineWidth || 0; this.lineColor = color || 0; this.lineAlpha = (arguments.length < 3) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length) + { // halfway through a line? start a new one! this.drawShape( new math.Polygon( this.currentPath.shape.points.slice(-2) )); } - else { + else + { // otherwise its empty so lets just set the line properties this.currentPath.lineWidth = this.lineWidth; this.currentPath.lineColor = this.lineColor; @@ -239,7 +250,8 @@ * @param y {number} the Y coordinate to move to * @return {Graphics} */ -Graphics.prototype.moveTo = function (x, y) { +Graphics.prototype.moveTo = function (x, y) +{ this.drawShape(new math.Polygon([x,y])); return this; @@ -253,7 +265,8 @@ * @param y {number} the Y coordinate to draw to * @return {Graphics} */ -Graphics.prototype.lineTo = function (x, y) { +Graphics.prototype.lineTo = function (x, y) +{ this.currentPath.shape.points.push(x, y); this.dirty = true; @@ -270,13 +283,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -285,7 +302,8 @@ n = 20, points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { this.moveTo(0, 0); } @@ -293,7 +311,8 @@ var fromY = points[points.length-1]; var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; xa = fromX + ( (cpX - fromX) * j ); @@ -319,13 +338,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -342,7 +365,8 @@ var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; dt = (1 - j); @@ -373,13 +397,17 @@ * @param radius {number} The radius of the arc * @return {Graphics} */ -Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points.push(x1, y1); } } - else { + else + { this.moveTo(x1, y1); } @@ -392,12 +420,15 @@ b2 = x2 - x1, mm = Math.abs(a1 * b2 - b1 * a2); - if (mm < 1.0e-8 || radius === 0) { - if (points[points.length-2] !== x1 || points[points.length-1] !== y1) { + if (mm < 1.0e-8 || radius === 0) + { + if (points[points.length-2] !== x1 || points[points.length-1] !== y1) + { points.push(x1, y1); } } - else { + else + { var dd = a1 * a1 + b1 * b1, cc = a2 * a2 + b2 * b2, tt = a1 * a2 + b1 * b2, @@ -433,42 +464,51 @@ * @param anticlockwise {boolean} Optional. Specifies whether the drawing should be counterclockwise or clockwise. False is default, and indicates clockwise, while true indicates counter-clockwise. * @return {Graphics} */ -Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) { +Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) +{ var startX = cx + Math.cos(startAngle) * radius; var startY = cy + Math.sin(startAngle) * radius; var points; // TODO - This if-else makes no sense. It uses currentPath in the else where it doesn't exist... - if (this.currentPath) { + if (this.currentPath) + { points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { points.push(startX, startY); } - else if (points[points.length-2] !== startX || points[points.length-1] !== startY) { + else if (points[points.length-2] !== startX || points[points.length-1] !== startY) + { points.push(startX, startY); } } - else { + else + { this.moveTo(startX, startY); points = this.currentPath.shape.points; } - if (startAngle === endAngle) { + if (startAngle === endAngle) + { return this; } - if (!anticlockwise && endAngle <= startAngle) { + if (!anticlockwise && endAngle <= startAngle) + { endAngle += Math.PI * 2; } - else if (anticlockwise && startAngle <= endAngle) { + else if (anticlockwise && startAngle <= endAngle) + { startAngle += Math.PI * 2; } var sweep = anticlockwise ? (startAngle - endAngle) *-1 : (endAngle - startAngle); var segs = (Math.abs(sweep)/ (Math.PI * 2)) * 40; - if (sweep === 0) { + if (sweep === 0) + { return this; } @@ -482,7 +522,8 @@ var remainder = ( segMinus % 1 ) / segMinus; - for (var i = 0; i <= segMinus; ++i) { + for (var i = 0; i <= segMinus; ++i) + { var real = i + remainder * i; var angle = ((theta) + startAngle + (theta2 * real)); @@ -506,13 +547,16 @@ * @param alpha {number} the alpha of the fill * @return {Graphics} */ -Graphics.prototype.beginFill = function (color, alpha) { +Graphics.prototype.beginFill = function (color, alpha) +{ this.filling = true; this.fillColor = color || 0; this.fillAlpha = (alpha === undefined) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length <= 2) + { this.currentPath.fill = this.filling; this.currentPath.fillColor = this.fillColor; this.currentPath.fillAlpha = this.fillAlpha; @@ -526,7 +570,8 @@ * * @return {Graphics} */ -Graphics.prototype.endFill = function () { +Graphics.prototype.endFill = function () +{ this.filling = false; this.fillColor = null; this.fillAlpha = 1; @@ -542,7 +587,8 @@ * @param height {number} The height of the rectangle * @return {Graphics} */ -Graphics.prototype.drawRect = function ( x, y, width, height ) { +Graphics.prototype.drawRect = function ( x, y, width, height ) +{ this.drawShape(new math.Rectangle(x,y, width, height)); return this; @@ -556,7 +602,8 @@ * @param height {number} The height of the rectangle * @param radius {number} Radius of the rectangle corners */ -Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) { +Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) +{ this.drawShape(new math.RoundedRectangle(x, y, width, height, radius)); return this; @@ -570,7 +617,8 @@ * @param radius {number} The radius of the circle * @return {Graphics} */ -Graphics.prototype.drawCircle = function (x, y, radius) { +Graphics.prototype.drawCircle = function (x, y, radius) +{ this.drawShape(new math.Circle(x,y, radius)); return this; @@ -585,7 +633,8 @@ * @param height {number} The half height of the ellipse * @return {Graphics} */ -Graphics.prototype.drawEllipse = function (x, y, width, height) { +Graphics.prototype.drawEllipse = function (x, y, width, height) +{ this.drawShape(new math.Ellipse(x, y, width, height)); return this; @@ -597,8 +646,10 @@ * @param path {Array} The path data used to construct the polygon. * @return {Graphics} */ -Graphics.prototype.drawPolygon = function (path) { - if (!(path instanceof Array)) { +Graphics.prototype.drawPolygon = function (path) +{ + if (!(path instanceof Array)) + { path = Array.prototype.slice.call(arguments); } @@ -612,7 +663,8 @@ * * @return {Graphics} */ -Graphics.prototype.clear = function () { +Graphics.prototype.clear = function () +{ this.lineWidth = 0; this.filling = false; @@ -631,7 +683,8 @@ * @param scaleMode {number} Should be one of the scaleMode consts * @return {Texture} a texture of the graphics object */ -Graphics.prototype.generateTexture = function (resolution, scaleMode) { +Graphics.prototype.generateTexture = function (resolution, scaleMode) +{ resolution = resolution || 1; var bounds = this.getBounds(); @@ -655,17 +708,21 @@ * * @param renderer {WebGLRenderer} */ -Graphics.prototype._renderWebGL = function (renderer) { +Graphics.prototype._renderWebGL = function (renderer) +{ // if the sprite is not visible or the alpha is 0 then no need to render this element - if (this.isMask === true) { + if (this.isMask === true) + { return; } // this code may still be needed so leaving for now.. - // + // /* - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture on the gpu too! @@ -681,17 +738,24 @@ return; } - */ - - // check if the webgl graphic needs to be updated - if (this.glDirty) { - this.dirty = true; - this.glDirty = false; - } + else */ - renderer.setObjectRendererer(renderer.graphicsRenderer); - renderer.graphicsRenderer.render(this); + renderer.spriteBatch.stop(); + renderer.blendModeManager.setBlendMode(this.blendMode); + // check blend mode + renderer.blendModeManager.setBlendMode( this.blendMode ); + + // check if the webgl graphic needs to be updated + if (this.glDirty) + { + this.dirty = true; + this.glDirty = false; + } + + WebGLGraphics.renderGraphics(this, renderer); + + renderer.spriteBatch.start(); }; /** @@ -700,14 +764,18 @@ * @param renderer {CanvasRenderer} * @private */ -Graphics.prototype.renderCanvas = function (renderer) { +Graphics.prototype.renderCanvas = function (renderer) +{ // 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.isMask === true) { + if (!this.visible || this.alpha <= 0 || this.isMask === true) + { return; } - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture @@ -723,16 +791,19 @@ return; } - else { + else + { var context = renderer.context; var transform = this.worldTransform; - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } @@ -748,11 +819,13 @@ CanvasGraphics.renderGraphics(this, context); - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } } @@ -763,13 +836,16 @@ * * @return {Rectangle} the rectangular bounding area */ -Graphics.prototype.getBounds = function (matrix) { +Graphics.prototype.getBounds = function (matrix) +{ // return an empty object if the item is a mask! - if (this.isMask) { + if (this.isMask) + { return math.Rectangle.EMPTY; } - if (this.dirty) { + if (this.dirty) + { this.updateLocalBounds(); this.glDirty = true; @@ -841,23 +917,27 @@ * Update the bounds of the object * */ -Graphics.prototype.updateLocalBounds = function () { +Graphics.prototype.updateLocalBounds = function () +{ var minX = Infinity; var maxX = -Infinity; var minY = Infinity; var maxY = -Infinity; - if (this.graphicsData.length) { + if (this.graphicsData.length) + { var shape, points, x, y, w, h; - for (var i = 0; i < this.graphicsData.length; i++) { + for (var i = 0; i < this.graphicsData.length; i++) + { var data = this.graphicsData[i]; var type = data.type; var lineWidth = data.lineWidth; shape = data.shape; - if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) { + if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) + { x = shape.x - lineWidth/2; y = shape.y - lineWidth/2; w = shape.width + lineWidth; @@ -869,7 +949,8 @@ minY = y < minY ? y : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.CIRC) { + else if (type === CONST.SHAPES.CIRC) + { x = shape.x; y = shape.y; w = shape.radius + lineWidth/2; @@ -881,7 +962,8 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.ELIP) { + else if (type === CONST.SHAPES.ELIP) + { x = shape.x; y = shape.y; w = shape.width + lineWidth/2; @@ -893,11 +975,13 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else { + else + { // POLY points = shape.points; - for (var j = 0; j < points.length; j += 2) { + for (var j = 0; j < points.length; j += 2) + { x = points[j]; y = points[j+1]; @@ -910,7 +994,8 @@ } } } - else { + else + { minX = 0; maxX = 0; minY = 0; @@ -931,10 +1016,12 @@ * * @private */ -Graphics.prototype._generateCachedSprite = function () { +Graphics.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { var canvasBuffer = new CanvasBuffer(bounds.width, bounds.height); var texture = Texture.fromCanvas(canvasBuffer.canvas); @@ -943,7 +1030,8 @@ this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.buffer.resize(bounds.width, bounds.height); } @@ -968,7 +1056,8 @@ * * @private */ -Graphics.prototype.updateCachedSpriteTexture = function () { +Graphics.prototype.updateCachedSpriteTexture = function () +{ var cachedSprite = this._cachedSprite; var texture = cachedSprite.texture; var canvas = cachedSprite.buffer.canvas; @@ -989,7 +1078,8 @@ * Destroys a previous cached sprite. * */ -Graphics.prototype.destroyCachedSprite = function () { +Graphics.prototype.destroyCachedSprite = function () +{ this._cachedSprite.texture.destroy(true); // let the gc collect the unused sprite @@ -1003,10 +1093,13 @@ * @param {Circle|Rectangle|Ellipse|Line|Polygon} shape The Shape object to draw. * @return {GraphicsData} The generated GraphicsData object. */ -Graphics.prototype.drawShape = function (shape) { - if (this.currentPath) { +Graphics.prototype.drawShape = function (shape) +{ + if (this.currentPath) + { // check current path! - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath.shape.points.length <= 2) + { this.graphicsData.pop(); } } @@ -1017,7 +1110,8 @@ this.graphicsData.push(data); - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { data.shape.closed = this.filling; this.currentPath = data; } diff --git a/src/core/primitives/GraphicsData.js b/src/core/primitives/GraphicsData.js index 99decbe..788f6f2 100644 --- a/src/core/primitives/GraphicsData.js +++ b/src/core/primitives/GraphicsData.js @@ -4,7 +4,8 @@ * @class * @namespace PIXI */ -function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) { +function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) +{ this.lineWidth = lineWidth; this.lineColor = lineColor; this.lineAlpha = lineAlpha; @@ -27,7 +28,8 @@ * * @return {GraphicsData} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ return new GraphicsData( this.lineWidth, this.lineColor, diff --git a/src/core/renderers/canvas/CanvasRenderer.js b/src/core/renderers/canvas/CanvasRenderer.js index 15a0978..7aebd44 100644 --- a/src/core/renderers/canvas/CanvasRenderer.js +++ b/src/core/renderers/canvas/CanvasRenderer.js @@ -17,17 +17,22 @@ * @param [options.resolution=1] {number} the resolution of the renderer retina would be 2 * @param [options.clearBeforeRender=true] {boolean} This sets if the CanvasRenderer will clear the canvas or not before the new render pass. */ -function CanvasRenderer(width, height, options) { +function CanvasRenderer(width, height, options) +{ utils.sayHello('Canvas'); - if (options) { - for (var i in CONST.defaultRenderOptions) { - if (typeof options[i] === 'undefined') { + if (options) + { + for (var i in CONST.defaultRenderOptions) + { + if (typeof options[i] === 'undefined') + { options[i] = CONST.defaultRenderOptions[i]; } } } - else { + else + { options = CONST.defaultRenderOptions; } @@ -156,19 +161,24 @@ this.smoothProperty = null; - if (this.context.imageSmoothingEnabled) { + if (this.context.imageSmoothingEnabled) + { this.smoothProperty = 'imageSmoothingEnabled'; } - else if (this.context.webkitImageSmoothingEnabled) { + else if (this.context.webkitImageSmoothingEnabled) + { this.smoothProperty = 'webkitImageSmoothingEnabled'; } - else if (this.context.mozImageSmoothingEnabled) { + else if (this.context.mozImageSmoothingEnabled) + { this.smoothProperty = 'mozImageSmoothingEnabled'; } - else if (this.context.oImageSmoothingEnabled) { + else if (this.context.oImageSmoothingEnabled) + { this.smoothProperty = 'oImageSmoothingEnabled'; } - else if (this.context.msImageSmoothingEnabled) { + else if (this.context.msImageSmoothingEnabled) + { this.smoothProperty = 'msImageSmoothingEnabled'; } @@ -193,10 +203,12 @@ * @memberof CanvasRenderer# */ backgroundColor: { - get: function () { + get: function () + { return this._backgroundColor; }, - set: function (val) { + set: function (val) + { this._backgroundColor = val; this._backgroundColorString = utils.hex2string(val); } @@ -208,7 +220,8 @@ * * @param object {DisplayObject} the object to be rendered */ -CanvasRenderer.prototype.render = function (object) { +CanvasRenderer.prototype.render = function (object) +{ object.updateTransform(); this.context.setTransform(1,0,0,1,0,0); @@ -218,16 +231,20 @@ this.currentBlendMode = CONST.blendModes.NORMAL; this.context.globalCompositeOperation = this.blendModes[CONST.blendModes.NORMAL]; - if (navigator.isCocoonJS && this.view.screencanvas) { + if (navigator.isCocoonJS && this.view.screencanvas) + { this.context.fillStyle = 'black'; this.context.clear(); } - if (this.clearBeforeRender) { - if (this.transparent) { + if (this.clearBeforeRender) + { + if (this.transparent) + { this.context.clearRect(0, 0, this.width, this.height); } - else { + else + { this.context.fillStyle = this._backgroundColorString; this.context.fillRect(0, 0, this.width , this.height); } @@ -241,8 +258,10 @@ * * @param [removeView=false] {boolean} Removes the Canvas element from the DOM. */ -CanvasRenderer.prototype.destroy = function (removeView) { - if (removeView && this.view.parent) { +CanvasRenderer.prototype.destroy = function (removeView) +{ + if (removeView && this.view.parent) + { this.view.parent.removeChild(this.view); } @@ -257,14 +276,16 @@ * @param width {number} the new width of the canvas view * @param height {number} the new height of the canvas view */ -CanvasRenderer.prototype.resize = function (width, height) { +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) { + if (this.autoResize) + { this.view.style.width = this.width / this.resolution + 'px'; this.view.style.height = this.height / this.resolution + 'px'; } @@ -276,7 +297,8 @@ * @param displayObject {DisplayObject} The displayObject to render * @private */ -CanvasRenderer.prototype.renderDisplayObject = function (displayObject) { +CanvasRenderer.prototype.renderDisplayObject = function (displayObject) +{ displayObject.renderCanvas(this); }; @@ -285,11 +307,14 @@ * * @private */ -CanvasRenderer.prototype._mapBlendModes = function () { - if (!this.blendModes) { +CanvasRenderer.prototype._mapBlendModes = function () +{ + if (!this.blendModes) + { this.blendModes = {}; - if (utils.canUseNewCanvasBlendModes()) { + if (utils.canUseNewCanvasBlendModes()) + { this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? this.blendModes[CONST.blendModes.MULTIPLY] = 'multiply'; @@ -308,7 +333,8 @@ this.blendModes[CONST.blendModes.COLOR] = 'color'; this.blendModes[CONST.blendModes.LUMINOSITY] = 'luminosity'; } - else { + else + { // this means that the browser does not support the cool new blend modes in canvas 'cough' ie 'cough' this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? diff --git a/src/core/renderers/canvas/utils/CanvasBuffer.js b/src/core/renderers/canvas/utils/CanvasBuffer.js index ebe5d47..b183a66 100644 --- a/src/core/renderers/canvas/utils/CanvasBuffer.js +++ b/src/core/renderers/canvas/utils/CanvasBuffer.js @@ -6,7 +6,8 @@ * @param width {number} the width for the newly created canvas * @param height {number} the height for the newly created canvas */ -function CanvasBuffer(width, height) { +function CanvasBuffer(width, height) +{ /** * The Canvas object that belongs to this CanvasBuffer. * @@ -36,10 +37,12 @@ * @memberof CanvasBuffer# */ width: { - get: function () { + get: function () + { return this.canvas.width; }, - set: function (val) { + set: function (val) + { this.canvas.width = val; } }, @@ -50,10 +53,12 @@ * @memberof CanvasBuffer# */ height: { - get: function () { + get: function () + { return this.canvas.height; }, - set: function (val) { + set: function (val) + { this.canvas.height = val; } } @@ -64,7 +69,8 @@ * * @private */ -CanvasBuffer.prototype.clear = function () { +CanvasBuffer.prototype.clear = function () +{ this.context.setTransform(1, 0, 0, 1, 0, 0); this.context.clearRect(0,0, this.canvas.width, this.canvas.height); }; @@ -75,7 +81,8 @@ * @param width {number} the new width of the canvas * @param height {number} the new height of the canvas */ -CanvasBuffer.prototype.resize = function (width, height) { +CanvasBuffer.prototype.resize = function (width, height) +{ this.canvas.width = width; this.canvas.height = height; }; diff --git a/src/core/renderers/canvas/utils/CanvasGraphics.js b/src/core/renderers/canvas/utils/CanvasGraphics.js index c7eaa2a..3f2a91f 100644 --- a/src/core/renderers/canvas/utils/CanvasGraphics.js +++ b/src/core/renderers/canvas/utils/CanvasGraphics.js @@ -13,15 +13,18 @@ * @param graphics {Graphics} the actual graphics object to render * @param context {CanvasRenderingContext2D} the 2d drawing method of the canvas */ -CanvasGraphics.renderGraphics = function (graphics, context) { +CanvasGraphics.renderGraphics = function (graphics, context) +{ var worldAlpha = graphics.worldAlpha; - if (graphics.dirty) { + if (graphics.dirty) + { this.updateGraphicsTint(graphics); graphics.dirty = false; } - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; @@ -30,69 +33,82 @@ context.lineWidth = data.lineWidth; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { context.beginPath(); var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } - if (shape.closed) { + if (shape.closed) + { context.lineTo(points[0], points[1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fillRect(shape.x, shape.y, shape.width, shape.height); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.strokeRect(shape.x, shape.y, shape.width, shape.height); } } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.beginPath(); context.arc(shape.x, shape.y, shape.radius,0,2*Math.PI); context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas var w = shape.width * 2; @@ -119,18 +135,21 @@ context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; var width = shape.width; @@ -152,13 +171,15 @@ context.quadraticCurveTo(rx, ry, rx, ry + radius); context.closePath(); - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); @@ -174,45 +195,54 @@ * @param graphics {Graphics} the graphics which will be used as a mask * @param context {CanvasRenderingContext2D} the context 2d method of the canvas */ -CanvasGraphics.renderGraphicsMask = function (graphics, context) { +CanvasGraphics.renderGraphicsMask = function (graphics, context) +{ var len = graphics.graphicsData.length; - if (len === 0) { + if (len === 0) + { return; } context.beginPath(); - for (var i = 0; i < len; i++) { + for (var i = 0; i < len; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { context.rect(shape.x, shape.y, shape.width, shape.height); context.closePath(); } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.arc(shape.x, shape.y, shape.radius, 0, 2 * Math.PI); context.closePath(); } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas @@ -237,7 +267,8 @@ context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); context.closePath(); } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; @@ -262,8 +293,10 @@ } }; -CanvasGraphics.updateGraphicsTint = function (graphics) { - if (graphics.tint === 0xFFFFFF) { +CanvasGraphics.updateGraphicsTint = function (graphics) +{ + if (graphics.tint === 0xFFFFFF) + { return; } @@ -271,7 +304,8 @@ var tintG = (graphics.tint >> 8 & 0xFF) / 255; var tintB = (graphics.tint & 0xFF)/ 255; - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var fillColor = data.fillColor | 0; diff --git a/src/core/renderers/canvas/utils/CanvasMaskManager.js b/src/core/renderers/canvas/utils/CanvasMaskManager.js index e04a733..9827d36 100644 --- a/src/core/renderers/canvas/utils/CanvasMaskManager.js +++ b/src/core/renderers/canvas/utils/CanvasMaskManager.js @@ -6,7 +6,8 @@ * @class * @namespace PIXI */ -function CanvasMaskManager() {} +function CanvasMaskManager() +{} CanvasMaskManager.prototype.constructor = CanvasMaskManager; module.exports = CanvasMaskManager; @@ -17,7 +18,8 @@ * @param maskData {object} the maskData that will be pushed * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.pushMask = function (maskData, renderer) { +CanvasMaskManager.prototype.pushMask = function (maskData, renderer) +{ renderer.context.save(); var cacheAlpha = maskData.alpha; @@ -45,6 +47,7 @@ * * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.popMask = function (renderer) { +CanvasMaskManager.prototype.popMask = function (renderer) +{ renderer.context.restore(); }; diff --git a/src/core/renderers/canvas/utils/CanvasTinter.js b/src/core/renderers/canvas/utils/CanvasTinter.js index 17e0529..d2fb1bc 100644 --- a/src/core/renderers/canvas/utils/CanvasTinter.js +++ b/src/core/renderers/canvas/utils/CanvasTinter.js @@ -14,7 +14,8 @@ * @param color {number} the color to use to tint the sprite with * @return {HTMLCanvasElement} The tinted canvas */ -CanvasTinter.getTintedTexture = function (sprite, color) { +CanvasTinter.getTintedTexture = function (sprite, color) +{ var texture = sprite.texture; color = CanvasTinter.roundColor(color); @@ -23,7 +24,8 @@ texture.tintCache = texture.tintCache || {}; - if (texture.tintCache[stringColor]) { + if (texture.tintCache[stringColor]) + { return texture.tintCache[stringColor]; } @@ -33,14 +35,16 @@ //CanvasTinter.tintWithPerPixel(texture, stringColor, canvas); CanvasTinter.tintMethod(texture, color, canvas); - if (CanvasTinter.convertTintToImage) { + if (CanvasTinter.convertTintToImage) + { // is this better? var tintImage = new Image(); tintImage.src = canvas.toDataURL(); texture.tintCache[stringColor] = tintImage; } - else { + else + { texture.tintCache[stringColor] = canvas; // if we are not converting the texture to an image then we need to lose the reference to the canvas CanvasTinter.canvas = null; @@ -56,7 +60,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithMultiply = function (texture, color, canvas) { +CanvasTinter.tintWithMultiply = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -104,7 +109,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithOverlay = function (texture, color, canvas) { +CanvasTinter.tintWithOverlay = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -139,7 +145,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithPerPixel = function (texture, color, canvas) { +CanvasTinter.tintWithPerPixel = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -167,7 +174,8 @@ var pixels = pixelData.data; - for (var i = 0; i < pixels.length; i += 4) { + for (var i = 0; i < pixels.length; i += 4) + { pixels[i+0] *= r; pixels[i+1] *= g; pixels[i+2] *= b; @@ -181,7 +189,8 @@ * * @param color {number} the color to round, should be a hex color */ -CanvasTinter.roundColor = function (color) { +CanvasTinter.roundColor = function (color) +{ var step = CanvasTinter.cacheStepsPerColorChannel; var rgbValues = utils.hex2rgb(color); diff --git a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js index 9f2f89a..35edbaf 100644 --- a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js +++ b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLBlendModeManager(renderer) { +function WebGLBlendModeManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -23,8 +24,10 @@ * * @param blendMode {number} the blendMode, should be a Pixi const, such as BlendModes.ADD */ -WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) { - if (this.currentBlendMode === blendMode) { +WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) +{ + if (this.currentBlendMode === blendMode) + { return false; } diff --git a/src/core/renderers/webgl/managers/WebGLFilterManager.js b/src/core/renderers/webgl/managers/WebGLFilterManager.js index 1179258..2dac048 100644 --- a/src/core/renderers/webgl/managers/WebGLFilterManager.js +++ b/src/core/renderers/webgl/managers/WebGLFilterManager.js @@ -7,7 +7,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLFilterManager(renderer) { +function WebGLFilterManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -32,7 +33,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.texturePool.length = 0; self.initShaderBuffers(); }); @@ -46,7 +48,8 @@ * @param renderer {WebGLRenderer} * @param buffer {ArrayBuffer} */ -WebGLFilterManager.prototype.begin = function (buffer) { +WebGLFilterManager.prototype.begin = function (buffer) +{ this.defaultShader = this.renderer.shaderManager.defaultShader; this.width = this.renderer.projection.x * 2; @@ -60,7 +63,8 @@ * * @param filterBlock {object} the filter that will be pushed to the current filter stack */ -WebGLFilterManager.prototype.pushFilter = function (filterBlock) { +WebGLFilterManager.prototype.pushFilter = function (filterBlock) +{ var gl = this.renderer.gl; var projection = this.renderer.projection; @@ -78,10 +82,12 @@ this.offsetY += filterBlock._filterArea.y; var texture = this.texturePool.pop(); - if (!texture) { + if (!texture) + { texture = new FilterTexture(this.renderer.gl, this.width, this.height); } - else { + else + { texture.resize(this.width, this.height); } @@ -98,29 +104,35 @@ var localX = filterArea.x, localY = filterArea.y; - if (filterArea.x < 0) { + if (filterArea.x < 0) + { filterArea.width += filterArea.x; filterArea.x = 0; } - if (filterArea.y < 0) { + if (filterArea.y < 0) + { filterArea.height += filterArea.y; filterArea.y = 0; } - if (localX + filterArea.width > this.width) { + if (localX + filterArea.width > this.width) + { filterArea.width = this.width - localX; } - if (localY + filterArea.height > this.height) { + if (localY + filterArea.height > this.height) + { filterArea.height = this.height - localY; } - if (filterArea.width < 0) { + if (filterArea.width < 0) + { filterArea.width = 0; } - if (filterArea.height < 0) { + if (filterArea.height < 0) + { filterArea.height = 0; } @@ -154,7 +166,8 @@ * Removes the last filter from the filter stack and doesn't return it. * */ -WebGLFilterManager.prototype.popFilter = function () { +WebGLFilterManager.prototype.popFilter = function () +{ var gl = this.renderer.gl; var filterBlock = this.filterStack.pop(); @@ -163,7 +176,8 @@ var projection = this.renderer.projection; var offset = this.renderer.offset; - if (filterBlock.filterPasses.length > 1) { + if (filterBlock.filterPasses.length > 1) + { gl.viewport(0, 0, filterArea.width, filterArea.height); gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); @@ -193,7 +207,8 @@ var inputTexture = texture; var outputTexture = this.texturePool.pop(); - if (!outputTexture) { + if (!outputTexture) + { outputTexture = new FilterTexture(this.renderer.gl, this.width, this.height); } outputTexture.resize(this.width, this.height); @@ -204,7 +219,8 @@ gl.disable(gl.BLEND); - for (var i = 0; i < filterBlock.filterPasses.length-1; i++) { + for (var i = 0; i < filterBlock.filterPasses.length-1; i++) + { var filterPass = filterBlock.filterPasses[i]; gl.bindFramebuffer(gl.FRAMEBUFFER, outputTexture.frameBuffer ); @@ -243,10 +259,12 @@ var buffer = this.buffer; // time to render the filters texture to the previous scene - if (this.filterStack.length === 0) { + if (this.filterStack.length === 0) + { gl.colorMask(true, true, true, true);//this.transparent); } - else { + else + { var currentFilter = this.filterStack[this.filterStack.length-1]; filterArea = currentFilter._filterArea; @@ -332,13 +350,15 @@ * @param width {number} the horizontal range of the filter * @param height {number} the vertical range of the filter */ -WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) { +WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) +{ // use program var gl = this.renderer.gl; var shader = filter.shaders[gl.id]; - if (!shader) { + if (!shader) + { shader = new Shader(gl); shader.fragmentSrc = filter.fragmentSrc; @@ -356,7 +376,8 @@ gl.uniform2f(shader.projectionVector, width/2, -height/2); gl.uniform2f(shader.offsetVector, 0,0); - if (filter.uniforms.dimensions) { + 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]; @@ -386,7 +407,8 @@ * Initialises the shader buffers. * */ -WebGLFilterManager.prototype.initShaderBuffers = function () { +WebGLFilterManager.prototype.initShaderBuffers = function () +{ var gl = this.renderer.gl; // create some buffers @@ -432,7 +454,8 @@ * Destroys the filter and removes it from the filter stack. * */ -WebGLFilterManager.prototype.destroy = function () { +WebGLFilterManager.prototype.destroy = function () +{ var gl = this.renderer.gl; this.filterStack = null; @@ -441,7 +464,8 @@ this.offsetY = 0; // destroy textures - for (var i = 0; i < this.texturePool.length; i++) { + for (var i = 0; i < this.texturePool.length; i++) + { this.texturePool[i].destroy(); } diff --git a/src/core/renderers/webgl/managers/WebGLManager.js b/src/core/renderers/webgl/managers/WebGLManager.js index 9d47b5c..c30cd51 100644 --- a/src/core/renderers/webgl/managers/WebGLManager.js +++ b/src/core/renderers/webgl/managers/WebGLManager.js @@ -3,7 +3,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLManager(renderer) { +function WebGLManager(renderer) +{ /** * The renderer this manager works for. * @@ -15,6 +16,7 @@ WebGLManager.prototype.constructor = WebGLManager; module.exports = WebGLManager; -WebGLManager.prototype.destroy = function () { +WebGLManager.prototype.destroy = function () +{ this.renderer = null; }; diff --git a/src/core/renderers/webgl/managers/WebGLMaskManager.js b/src/core/renderers/webgl/managers/WebGLMaskManager.js index 2f90b64..e568812 100644 --- a/src/core/renderers/webgl/managers/WebGLMaskManager.js +++ b/src/core/renderers/webgl/managers/WebGLMaskManager.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLMaskManager(renderer) { +function WebGLMaskManager(renderer) +{ WebGLManager.call(this, renderer); } @@ -19,12 +20,15 @@ * * @param maskData {any[]} */ -WebGLMaskManager.prototype.pushMask = function (maskData) { - if (maskData.dirty) { +WebGLMaskManager.prototype.pushMask = function (maskData) +{ + if (maskData.dirty) + { WebGLGraphics.updateGraphics(maskData, this.renderer.gl); } - if (!maskData._webGL[this.renderer.gl.id].data.length) { + if (!maskData._webGL[this.renderer.gl.id].data.length) + { return; } @@ -36,6 +40,7 @@ * * @param maskData {any[]} */ -WebGLMaskManager.prototype.popMask = function (maskData) { +WebGLMaskManager.prototype.popMask = function (maskData) +{ this.renderer.stencilManager.popStencil(maskData, maskData._webGL[this.renderer.gl.id].data[0], this.renderer); }; diff --git a/src/core/renderers/webgl/managers/WebGLShaderManager.js b/src/core/renderers/webgl/managers/WebGLShaderManager.js index fef071c..90c6477 100644 --- a/src/core/renderers/webgl/managers/WebGLShaderManager.js +++ b/src/core/renderers/webgl/managers/WebGLShaderManager.js @@ -10,7 +10,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLShaderManager(renderer) { +function WebGLShaderManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -28,7 +29,8 @@ */ this.tempAttribState = []; - for (var i = 0; i < this.maxAttibs; i++) { + for (var i = 0; i < this.maxAttibs; i++) + { this.attribState[i] = false; } @@ -66,7 +68,8 @@ // listen for context and update necessary shaders var self = this; - this.renderer.on('context', function (event) { + this.renderer.on('context', function (event) + { var gl = event.data; // this shader is used for rendering primitives @@ -97,29 +100,36 @@ * * @param attribs {Array} attribs */ -WebGLShaderManager.prototype.setAttribs = function (attribs) { +WebGLShaderManager.prototype.setAttribs = function (attribs) +{ // reset temp state var i; - for (i = 0; i < this.tempAttribState.length; i++) { + for (i = 0; i < this.tempAttribState.length; i++) + { this.tempAttribState[i] = false; } // set the new attribs - for (var a in attribs) { + for (var a in attribs) + { this.tempAttribState[attribs[a]] = true; } var gl = this.renderer.gl; - for (i = 0; i < this.attribState.length; i++) { - if (this.attribState[i] !== this.tempAttribState[i]) { + for (i = 0; i < this.attribState.length; i++) + { + if (this.attribState[i] !== this.tempAttribState[i]) + { this.attribState[i] = this.tempAttribState[i]; - if (this.attribState[i]) { + if (this.attribState[i]) + { gl.enableVertexAttribArray(i); } - else { + else + { gl.disableVertexAttribArray(i); } } @@ -131,8 +141,10 @@ * * @param shader {Any} */ -WebGLShaderManager.prototype.setShader = function (shader) { - if (this._currentId === shader.uuid) { +WebGLShaderManager.prototype.setShader = function (shader) +{ + if (this._currentId === shader.uuid) + { return false; } @@ -150,7 +162,8 @@ * Destroys this object. * */ -WebGLShaderManager.prototype.destroy = function () { +WebGLShaderManager.prototype.destroy = function () +{ this.attribState = null; this.tempAttribState = null; diff --git a/src/core/renderers/webgl/managers/WebGLStencilManager.js b/src/core/renderers/webgl/managers/WebGLStencilManager.js index 9ec6398..4cb0134 100644 --- a/src/core/renderers/webgl/managers/WebGLStencilManager.js +++ b/src/core/renderers/webgl/managers/WebGLStencilManager.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLStencilManager(renderer) { +function WebGLStencilManager(renderer) +{ WebGLManager.call(this, renderer); this.stencilStack = []; @@ -24,12 +25,14 @@ * @param graphics {Graphics} * @param webGLData {any[]} */ -WebGLStencilManager.prototype.pushStencil = function (graphics, webGLData) { +WebGLStencilManager.prototype.pushStencil = function (graphics, webGLData) +{ var gl = this.renderer.gl; this.bindGraphics(graphics, webGLData, this.renderer); - if (this.stencilStack.length === 0) { + if (this.stencilStack.length === 0) + { gl.enable(gl.STENCIL_TEST); gl.clear(gl.STENCIL_BUFFER_BIT); this.reverse = true; @@ -47,14 +50,17 @@ // draw the triangle strip! - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } @@ -62,31 +68,38 @@ // draw a quad to increment.. gl.drawElements(gl.TRIANGLE_FAN, 4, gl.UNSIGNED_SHORT, ( webGLData.indices.length - 4 ) * 2 ); - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); } this.reverse = !this.reverse; } - else { - if (!this.reverse) { + else + { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } - else { + 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) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); } } @@ -103,7 +116,8 @@ * @param graphics {Graphics} * @param webGLData {Array} */ -WebGLStencilManager.prototype.bindGraphics = function (graphics, webGLData) { +WebGLStencilManager.prototype.bindGraphics = function (graphics, webGLData) +{ //if (this._currentGraphics === graphics)return; this._currentGraphics = graphics; @@ -114,7 +128,8 @@ offset = this.renderer.offset, shader;// = this.renderer.shaderManager.primitiveShader; - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { shader = this.renderer.shaderManager.complexPrimitiveShader; this.renderer.shaderManager.setShader(shader); @@ -141,7 +156,8 @@ // set the index buffer! gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, webGLData.indexBuffer); } - else { + else + { //this.renderer.shaderManager.activatePrimitiveShader(); shader = this.renderer.shaderManager.primitiveShader; this.renderer.shaderManager.setShader( shader ); @@ -154,7 +170,7 @@ gl.uniform2f(shader.uniforms.offsetVector._location, -offset.x, -offset.y); gl.uniform3fv(shader.uniforms.tint._location, utils.hex2rgb(graphics.tint)); - + gl.uniform1f(shader.uniforms.alpha._location, graphics.worldAlpha); @@ -172,19 +188,22 @@ * @param graphics {Graphics} * @param webGLData {Array} */ -WebGLStencilManager.prototype.popStencil = function (graphics, webGLData) { +WebGLStencilManager.prototype.popStencil = function (graphics, webGLData) +{ var gl = this.renderer.gl; this.stencilStack.pop(); this.count--; - if (this.stencilStack.length === 0) { + if (this.stencilStack.length === 0) + { // the stack is empty! gl.disable(gl.STENCIL_TEST); } - else { + else + { var level = this.count; @@ -192,14 +211,17 @@ gl.colorMask(false, false, false, false); - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { this.reverse = !this.reverse; - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } @@ -213,31 +235,38 @@ // draw the triangle strip! gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); - if (!this.reverse) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); } } - else { + else + { // console.log("<<>>") - if (!this.reverse) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } - else { + 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) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); } } @@ -253,7 +282,8 @@ * Destroys the mask stack. * */ -WebGLStencilManager.prototype.destroy = function () { +WebGLStencilManager.prototype.destroy = function () +{ this.renderer = null; this.stencilStack = null; }; diff --git a/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js b/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js index 913ba5e..1ea7d19 100644 --- a/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js +++ b/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function ComplexPrimitiveShader(gl) { +function ComplexPrimitiveShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -24,7 +25,8 @@ 'uniform float flipY;', 'varying vec4 vColor;', - 'void main(void) {', + '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);', @@ -37,7 +39,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = vColor;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/FastShader.js b/src/core/renderers/webgl/shaders/FastShader.js index bd2e29a..2e5e060 100644 --- a/src/core/renderers/webgl/shaders/FastShader.js +++ b/src/core/renderers/webgl/shaders/FastShader.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function FastShader(gl) { +function FastShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -28,7 +29,8 @@ 'const vec2 center = vec2(-1.0, 1.0);', - 'void main(void) {', + 'void main(void) + {', ' vec2 v;', ' vec2 sv = aVertexPosition * aScale;', ' v.x = (sv.x) * cos(aRotation) - (sv.y) * sin(aRotation);', @@ -49,7 +51,8 @@ 'uniform sampler2D uSampler;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/PrimitiveShader.js b/src/core/renderers/webgl/shaders/PrimitiveShader.js index 6f25409..a25f54f 100644 --- a/src/core/renderers/webgl/shaders/PrimitiveShader.js +++ b/src/core/renderers/webgl/shaders/PrimitiveShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function PrimitiveShader(gl) { +function PrimitiveShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -23,7 +24,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + '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);', @@ -36,7 +38,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = vColor;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/Shader.js b/src/core/renderers/webgl/shaders/Shader.js index f8964f5..fd75ef5 100644 --- a/src/core/renderers/webgl/shaders/Shader.js +++ b/src/core/renderers/webgl/shaders/Shader.js @@ -6,7 +6,8 @@ * @param [fragmentSrc] {string} The source of the fragment shader. * @param [vertexSrc] {string} The source of the vertex shader. */ -function Shader(gl, vertexSrc, fragmentSrc, customUniforms, customAttributes) { +function Shader(gl, vertexSrc, fragmentSrc, customUniforms, customAttributes) +{ /** * @member {number} * @readonly @@ -33,7 +34,8 @@ dimensions: { type: '4f', value: new Float32Array(4) } }; - for (var u in customUniforms) { + for (var u in customUniforms) + { this.uniforms[u] = customUniforms[u]; } @@ -43,7 +45,8 @@ aColor: 0 }; - for (var a in customAttributes) { + for (var a in customAttributes) + { this.attributes[a] = customAttributes[a]; } @@ -66,7 +69,8 @@ 'const vec2 center = vec2(-1.0, 1.0);', - 'void main(void) {', + 'void main(void) + {', ' gl_Position = vec4( ((aVertexPosition + offsetVector) / projectionVector) + center , 0.0, 1.0);', ' vTextureCoord = aTextureCoord;', ' vColor = vec4(aColor.rgb * aColor.a, aColor.a);', @@ -85,7 +89,8 @@ 'uniform sampler2D uSampler;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;', '}' ].join('\n'); @@ -96,7 +101,8 @@ Shader.prototype.constructor = Shader; module.exports = Shader; -Shader.prototype.init = function () { +Shader.prototype.init = function () +{ this.compile(); this.gl.useProgram(this.program); @@ -105,14 +111,18 @@ this.cacheAttributeLocations(Object.keys(this.attributes)); }; -Shader.prototype.cacheUniformLocations = function (keys) { - for (var i = 0; i < keys.length; ++i) { +Shader.prototype.cacheUniformLocations = function (keys) +{ + for (var i = 0; i < keys.length; ++i) + { this.uniforms[keys[i]]._location = this.gl.getUniformLocation(this.program, keys[i]); } }; -Shader.prototype.cacheAttributeLocations = function (keys) { - for (var i = 0; i < keys.length; ++i) { +Shader.prototype.cacheAttributeLocations = function (keys) +{ + for (var i = 0; i < keys.length; ++i) + { this.attributes[keys[i]] = this.gl.getAttribLocation(this.program, keys[i]); } @@ -124,14 +134,16 @@ // 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.attributes.aColor === -1) { + // if (this.attributes.aColor === -1) + { // this.attributes.aColor = 2; // } // End worst hack eva // }; -Shader.prototype.compile = function () { +Shader.prototype.compile = function () +{ var gl = this.gl; var glVertShader = this._glCompile(gl.VERTEX_SHADER, this.vertexSrc); @@ -144,13 +156,15 @@ gl.linkProgram(program); // if linking fails, then log and cleanup - if (!gl.getProgramParameter(program, gl.LINK_STATUS)) { + if (!gl.getProgramParameter(program, gl.LINK_STATUS)) + { window.console.error('Pixi.js Error: Could not initialize shader.'); window.console.error('gl.VALIDATE_STATUS', gl.getProgramParameter(program, gl.VALIDATE_STATUS)); window.console.error('gl.getError()', gl.getError()); // if there is a program info log, log it - if (gl.getProgramInfoLog(program) !== '') { + if (gl.getProgramInfoLog(program) !== '') + { window.console.warn('Pixi.js Warning: gl.getProgramInfoLog()', gl.getProgramInfoLog(program)); } @@ -165,18 +179,21 @@ return (this.program = program); }; -Shader.prototype.syncUniforms = function () { +Shader.prototype.syncUniforms = function () +{ var gl = this.gl; this.textureCount = 1; - for (var key in this.uniforms) { + for (var key in this.uniforms) + { var uniform = this.uniforms[key], location = uniform._location, value = uniform.value, i, il; - switch (uniform.type) { + switch (uniform.type) + { // single int value case 'i': case '1i': @@ -282,7 +299,8 @@ // a Color Value case 'c': - if (typeof value === 'number') { + if (typeof value === 'number') + { value = utils.hex2rgb(value); } @@ -311,11 +329,13 @@ // array of 2D Point objects case 'v2v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(2 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 2] = value[i].x; uniform._array[i * 2 + 1] = value[i].y; } @@ -325,11 +345,13 @@ // array of 3D Point objects case 'v3v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(3 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 3] = value[i].x; uniform._array[i * 3 + 1] = value[i].y; uniform._array[i * 3 + 2] = value[i].z; @@ -341,11 +363,13 @@ // array of 4D Point objects case 'v4v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(4 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 4] = value[i].x; uniform._array[i * 4 + 1] = value[i].y; uniform._array[i * 4 + 2] = value[i].z; @@ -359,7 +383,8 @@ // PIXI.Texture case 't': case 'sampler2D': - if (!uniform.value || !uniform.value.baseTexture || !uniform.value.baseTexture.hasLoaded) { + if (!uniform.value || !uniform.value.baseTexture || !uniform.value.baseTexture.hasLoaded) + { break; } @@ -376,7 +401,8 @@ this.textureCount++; // initialize the texture if we haven't yet - if (!uniform._init) { + if (!uniform._init) + { this.initSampler2D(uniform); uniform._init = true; @@ -394,11 +420,13 @@ * Initialises a Sampler2D uniform (which may only be available later on after initUniforms once the texture has loaded) * */ -Shader.prototype.initSampler2D = function (uniform) { +Shader.prototype.initSampler2D = function (uniform) +{ var gl = this.gl; // Extended texture data - if (uniform.textureData) { + if (uniform.textureData) + { var data = uniform.textureData; // GLTexture = mag linear, min linear_mipmap_linear, wrap repeat + gl.generateMipmap(gl.TEXTURE_2D); @@ -417,14 +445,16 @@ var wrapT = (data.wrapT) ? data.wrapT : gl.CLAMP_TO_EDGE; var format = (data.luminance) ? gl.LUMINANCE : gl.RGBA; - if (data.repeat) { + if (data.repeat) + { wrapS = gl.REPEAT; wrapT = gl.REPEAT; } gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, !!data.flipY); - if (data.width) { + if (data.width) + { var width = (data.width) ? data.width : 512; var height = (data.height) ? data.height : 2; var border = (data.border) ? data.border : 0; @@ -432,7 +462,8 @@ // 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 { + 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); } @@ -448,7 +479,8 @@ * Destroys the shader. * */ -Shader.prototype.destroy = function () { +Shader.prototype.destroy = function () +{ this.gl.deleteProgram(this.program); this.gl = null; @@ -459,13 +491,15 @@ this.fragmentSrc = null; }; -Shader.prototype._glCompile = function (type, src) { +Shader.prototype._glCompile = function (type, src) +{ var shader = this.gl.createShader(type); this.gl.shaderSource(shader, src); this.gl.compileShader(shader); - if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) { + if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) + { window.console.log(this.gl.getShaderInfoLog(shader)); return null; } diff --git a/src/core/renderers/webgl/shaders/StripShader.js b/src/core/renderers/webgl/shaders/StripShader.js index 193f6e1..a7abcc6 100644 --- a/src/core/renderers/webgl/shaders/StripShader.js +++ b/src/core/renderers/webgl/shaders/StripShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function StripShader(gl) { +function StripShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -20,7 +21,8 @@ 'varying vec2 vTextureCoord;', - 'void main(void) {', + '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);', @@ -36,7 +38,8 @@ 'varying vec2 vTextureCoord;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vec2(vTextureCoord.x, vTextureCoord.y)) * alpha;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/utils/FilterTexture.js b/src/core/renderers/webgl/utils/FilterTexture.js index d2c8423..4433d44 100644 --- a/src/core/renderers/webgl/utils/FilterTexture.js +++ b/src/core/renderers/webgl/utils/FilterTexture.js @@ -8,7 +8,8 @@ * @param height {number} the vertical range of the filter * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values */ -function FilterTexture(gl, width, height, scaleMode) { +function FilterTexture(gl, width, height, scaleMode) +{ /** * @member {WebGLContext} */ @@ -59,7 +60,8 @@ * Clears the filter texture. * */ -FilterTexture.prototype.clear = function () { +FilterTexture.prototype.clear = function () +{ var gl = this.gl; gl.clearColor(0,0,0, 0); @@ -72,8 +74,10 @@ * @param width {number} the new width of the texture * @param height {number} the new height of the texture */ -FilterTexture.prototype.resize = function (width, height) { - if (this.width === width && this.height === height) { +FilterTexture.prototype.resize = function (width, height) +{ + if (this.width === width && this.height === height) + { return; } @@ -96,7 +100,8 @@ * Destroys the filter texture. * */ -FilterTexture.prototype.destroy = function () { +FilterTexture.prototype.destroy = function () +{ var gl = this.gl; gl.deleteFramebuffer( this.frameBuffer ); gl.deleteTexture( this.texture ); diff --git a/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js b/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js index c4721e9..a63f4d7 100644 --- a/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js +++ b/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js @@ -14,7 +14,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this sprite batch works for. */ -function WebGLFastSpriteBatch(renderer) { +function WebGLFastSpriteBatch(renderer) +{ /** * The renderer instance this sprite batch operates on. * @@ -91,7 +92,8 @@ */ this.lastIndexCount = 0; - for (var i=0, j=0; i < numIndices; i += 6, j += 4) { + 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; @@ -144,7 +146,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.setupContext(); }); } @@ -157,7 +160,8 @@ * * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLFastSpriteBatch.prototype.setupContext = function () { +WebGLFastSpriteBatch.prototype.setupContext = function () +{ var gl = this.renderer.gl; // create a couple of buffers @@ -177,7 +181,8 @@ /** * @param spriteBatch {SpriteBatch} The SpriteBatch container to prepare for. */ -WebGLFastSpriteBatch.prototype.begin = function (spriteBatch) { +WebGLFastSpriteBatch.prototype.begin = function (spriteBatch) +{ this.shader = this.renderer.shaderManager.fastShader; this.matrix = spriteBatch.worldTransform.toArray(true); @@ -187,33 +192,38 @@ /** */ -WebGLFastSpriteBatch.prototype.end = function () { +WebGLFastSpriteBatch.prototype.end = function () +{ this.flush(); }; /** * @param spriteBatch {SpriteBatch} The SpriteBatch container to render. */ -WebGLFastSpriteBatch.prototype.render = function (spriteBatch) { +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) { + if (!sprite.texture._uvs) + { return; } this.currentBaseTexture = sprite.texture.baseTexture; // check blend mode - if (sprite.blendMode !== this.renderer.blendModeManager.currentBlendMode) { + if (sprite.blendMode !== this.renderer.blendModeManager.currentBlendMode) + { this.flush(); this.renderer.blendModeManager.setBlendMode(sprite.blendMode); } - for (var i=0,j= children.length; i= this.size) { + if (this.currentBatchSize >= this.size) + { this.flush(); } }; @@ -362,29 +379,35 @@ /** * */ -WebGLFastSpriteBatch.prototype.flush = function () { +WebGLFastSpriteBatch.prototype.flush = function () +{ // If the batch is length 0 then return as there is nothing to draw - if (this.currentBatchSize === 0) { + if (this.currentBatchSize === 0) + { return; } var gl = this.renderer.gl; // bind the current texture - if (!this.currentBaseTexture._glTextures[gl.id]) { + if (!this.currentBaseTexture._glTextures[gl.id]) + { this.renderer.updateTexture(this.currentBaseTexture, gl); } //TODO-SHOUD THIS BE ELSE??!?!?! - else { + else + { gl.bindTexture(gl.TEXTURE_2D, this.currentBaseTexture._glTextures[gl.id]); } // upload the verts to the buffer - if (this.currentBatchSize > ( this.size * 0.5 ) ) { + if (this.currentBatchSize > ( this.size * 0.5 ) ) + { gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); } - else { + else + { var view = this.vertices.subarray(0, this.currentBatchSize * this.vertByteSize); gl.bufferSubData(gl.ARRAY_BUFFER, 0, view); @@ -405,14 +428,16 @@ * Ends the batch and flushes * */ -WebGLFastSpriteBatch.prototype.stop = function () { +WebGLFastSpriteBatch.prototype.stop = function () +{ this.flush(); }; /** * */ -WebGLFastSpriteBatch.prototype.start = function () { +WebGLFastSpriteBatch.prototype.start = function () +{ var gl = this.renderer.gl; // bind the main texture diff --git a/src/core/renderers/webgl/utils/WebGLGraphics.js b/src/core/renderers/webgl/utils/WebGLGraphics.js index 55f4911..ab8f46e 100644 --- a/src/core/renderers/webgl/utils/WebGLGraphics.js +++ b/src/core/renderers/webgl/utils/WebGLGraphics.js @@ -19,7 +19,8 @@ * @param graphics {Graphics} * @param renderer {WebGLRenderer} */ -WebGLGraphics.renderGraphics = function (graphics, renderer) {//projection, offset) { +WebGLGraphics.renderGraphics = function (graphics, renderer) {//projection, offset) +{ var gl = renderer.gl; var projection = renderer.projection, @@ -27,7 +28,8 @@ shader = renderer.shaderManager.primitiveShader, webGLData; - if (graphics.dirty) { + if (graphics.dirty) + { WebGLGraphics.updateGraphics(graphics, gl); } @@ -35,8 +37,10 @@ // This could be speeded up for sure! - for (var i = 0; i < webGL.data.length; i++) { - if (webGL.data[i].mode === 1) { + for (var i = 0; i < webGL.data.length; i++) + { + if (webGL.data[i].mode === 1) + { webGLData = webGL.data[i]; renderer.stencilManager.pushStencil(graphics, webGLData, renderer); @@ -46,7 +50,8 @@ renderer.stencilManager.popStencil(graphics, webGLData, renderer); } - else { + else + { webGLData = webGL.data[i]; @@ -84,12 +89,14 @@ * @param graphicsData {Graphics} The graphics object to update * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLGraphics.updateGraphics = function (graphics, gl) { +WebGLGraphics.updateGraphics = function (graphics, gl) +{ // get the contexts graphics object var webGL = graphics._webGL[gl.id]; // if the graphics object does not exist in the webGL context time to create it! - if (!webGL) { + if (!webGL) + { webGL = graphics._webGL[gl.id] = {lastIndex:0, data:[], gl:gl}; } @@ -99,11 +106,13 @@ var i; // if the user cleared the graphics object we will need to clear every object - if (graphics.clearDirty) { + if (graphics.clearDirty) + { graphics.clearDirty = false; // lop through and return all the webGLDatas to the object pool so than can be reused later on - for (i = 0; i < webGL.data.length; i++) { + for (i = 0; i < webGL.data.length; i++) + { var graphicsData = webGL.data[i]; graphicsData.reset(); WebGLGraphics.graphicsDataPool.push( graphicsData ); @@ -119,58 +128,72 @@ // loop through the graphics datas and construct each one.. // if the object is a complex fill then the new stencil buffer technique will be used // other wise graphics objects will be pushed into a batch.. - for (i = webGL.lastIndex; i < graphics.graphicsData.length; i++) { + for (i = webGL.lastIndex; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { // need to add the points the the graphics object.. data.points = data.shape.points.slice(); - if (data.shape.closed) { + if (data.shape.closed) + { // close the poly if the value is true! - if (data.points[0] !== data.points[data.points.length-2] || data.points[1] !== data.points[data.points.length-1]) { + if (data.points[0] !== data.points[data.points.length-2] || data.points[1] !== data.points[data.points.length-1]) + { data.points.push(data.points[0], data.points[1]); } } // MAKE SURE WE HAVE THE CORRECT TYPE.. - if (data.fill) { - if (data.points.length >= 6) { - if (data.points.length < 6 * 2) { + if (data.fill) + { + if (data.points.length >= 6) + { + if (data.points.length < 6 * 2) + { webGLData = WebGLGraphics.switchMode(webGL, 0); var canDrawUsingSimple = WebGLGraphics.buildPoly(data, webGLData); // console.log(canDrawUsingSimple); - if (!canDrawUsingSimple) { + if (!canDrawUsingSimple) + { // console.log("<>>>") webGLData = WebGLGraphics.switchMode(webGL, 1); WebGLGraphics.buildComplexPoly(data, webGLData); } } - else { + else + { webGLData = WebGLGraphics.switchMode(webGL, 1); WebGLGraphics.buildComplexPoly(data, webGLData); } } } - if (data.lineWidth > 0) { + if (data.lineWidth > 0) + { webGLData = WebGLGraphics.switchMode(webGL, 0); WebGLGraphics.buildLine(data, webGLData); } } - else { + else + { webGLData = WebGLGraphics.switchMode(webGL, 0); - if (data.type === CONST.SHAPES.RECT) { + if (data.type === CONST.SHAPES.RECT) + { WebGLGraphics.buildRectangle(data, webGLData); } - else if (data.type === CONST.SHAPES.CIRC || data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.CIRC || data.type === CONST.SHAPES.ELIP) + { WebGLGraphics.buildCircle(data, webGLData); } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { WebGLGraphics.buildRoundedRectangle(data, webGLData); } } @@ -179,10 +202,12 @@ } // upload all the dirty data... - for (i = 0; i < webGL.data.length; i++) { + for (i = 0; i < webGL.data.length; i++) + { webGLData = webGL.data[i]; - if (webGLData.dirty) { + if (webGLData.dirty) + { webGLData.upload(); } } @@ -194,18 +219,22 @@ * @param webGL {WebGLContext} * @param type {number} */ -WebGLGraphics.switchMode = function (webGL, type) { +WebGLGraphics.switchMode = function (webGL, type) +{ var webGLData; - if (!webGL.data.length) { + if (!webGL.data.length) + { webGLData = WebGLGraphics.graphicsDataPool.pop() || new WebGLGraphicsData(webGL.gl); webGLData.mode = type; webGL.data.push(webGLData); } - else { + else + { webGLData = webGL.data[webGL.data.length-1]; - if (webGLData.mode !== type || type === 1) { + if (webGLData.mode !== type || type === 1) + { webGLData = WebGLGraphics.graphicsDataPool.pop() || new WebGLGraphicsData(webGL.gl); webGLData.mode = type; webGL.data.push(webGLData); @@ -225,7 +254,8 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildRectangle = function (graphicsData, webGLData) { +WebGLGraphics.buildRectangle = function (graphicsData, webGLData) +{ // --- // // need to convert points to a nice regular data // @@ -235,7 +265,8 @@ var width = rectData.width; var height = rectData.height; - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -265,7 +296,8 @@ indices.push(vertPos, vertPos, vertPos+1, vertPos+2, vertPos+3, vertPos+3); } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = [x, y, @@ -289,7 +321,8 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildRoundedRectangle = function (graphicsData, webGLData) { +WebGLGraphics.buildRoundedRectangle = function (graphicsData, webGLData) +{ var rrectData = graphicsData.shape; var x = rrectData.x; var y = rrectData.y; @@ -305,7 +338,8 @@ recPoints = recPoints.concat(WebGLGraphics.quadraticBezierCurve(x + width, y + radius, x + width, y, x + width - radius, y)); recPoints = recPoints.concat(WebGLGraphics.quadraticBezierCurve(x + radius, y, x, y, x, y + radius)); - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -323,7 +357,8 @@ // var i = 0; - for (i = 0; i < triangles.length; i+=3) { + for (i = 0; i < triangles.length; i+=3) + { indices.push(triangles[i] + vecPos); indices.push(triangles[i] + vecPos); indices.push(triangles[i+1] + vecPos); @@ -332,12 +367,14 @@ } - for (i = 0; i < recPoints.length; i++) { + for (i = 0; i < recPoints.length; i++) + { verts.push(recPoints[i], recPoints[++i], r, g, b, alpha); } } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = recPoints; @@ -362,7 +399,8 @@ * @param toY {number} Destination point y * @return {number[]} */ -WebGLGraphics.quadraticBezierCurve = function (fromX, fromY, cpX, cpY, toX, toY) { +WebGLGraphics.quadraticBezierCurve = function (fromX, fromY, cpX, cpY, toX, toY) +{ var xa, ya, @@ -373,14 +411,16 @@ n = 20, points = []; - function getPt(n1 , n2, perc) { + function getPt(n1 , n2, perc) + { var diff = n2 - n1; return n1 + ( diff * perc ); } var j = 0; - for (var i = 0; i <= n; i++ ) { + for (var i = 0; i <= n; i++ ) + { j = i / n; // The Green Line @@ -406,7 +446,8 @@ * @param graphicsData {Graphics} The graphics object to draw * @param webGLData {object} */ -WebGLGraphics.buildCircle = function (graphicsData, webGLData) { +WebGLGraphics.buildCircle = function (graphicsData, webGLData) +{ // need to convert points to a nice regular data var circleData = graphicsData.shape; var x = circleData.x; @@ -415,11 +456,13 @@ var height; // TODO - bit hacky?? - if (graphicsData.type === CONST.SHAPES.CIRC) { + if (graphicsData.type === CONST.SHAPES.CIRC) + { width = circleData.radius; height = circleData.radius; } - else { + else + { width = circleData.width; height = circleData.height; } @@ -429,7 +472,8 @@ var i = 0; - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -444,7 +488,8 @@ indices.push(vecPos); - for (i = 0; i < totalSegs + 1 ; i++) { + for (i = 0; i < totalSegs + 1 ; i++) + { verts.push(x,y, r, g, b, alpha); verts.push(x + Math.sin(seg * i) * width, @@ -457,12 +502,14 @@ indices.push(vecPos-1); } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = []; - for (i = 0; i < totalSegs + 1; i++) { + for (i = 0; i < totalSegs + 1; i++) + { graphicsData.points.push(x + Math.sin(seg * i) * width, y + Math.cos(seg * i) * height); } @@ -481,18 +528,22 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildLine = function (graphicsData, webGLData) { +WebGLGraphics.buildLine = function (graphicsData, webGLData) +{ // TODO OPTIMISE! var i = 0; var points = graphicsData.points; - if (points.length === 0) { + if (points.length === 0) + { return; } // if the line width is an odd number add 0.5 to align to a whole pixel - if (graphicsData.lineWidth%2) { - for (i = 0; i < points.length; i++) { + if (graphicsData.lineWidth%2) + { + for (i = 0; i < points.length; i++) + { points[i] += 0.5; } } @@ -502,7 +553,8 @@ var lastPoint = new math.Point(points[points.length - 2], points[points.length - 1]); // if the first point is the last point - gonna have issues :) - if (firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) { + if (firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) + { // need to clone as we are going to slightly modify the shape.. points = points.slice(); @@ -562,7 +614,8 @@ verts.push(p1x + perpx , p1y + perpy, r, g, b, alpha); - for (i = 1; i < length-1; i++) { + for (i = 1; i < length-1; i++) + { p1x = points[(i-1)*2]; p1y = points[(i-1)*2 + 1]; @@ -599,7 +652,8 @@ denom = a1*b2 - a2*b1; - if (Math.abs(denom) < 0.1 ) { + if (Math.abs(denom) < 0.1 ) + { denom+=10.1; verts.push(p2x - perpx , p2y - perpy, @@ -618,7 +672,8 @@ pdist = (px -p2x) * (px -p2x) + (py -p2y) + (py -p2y); - if (pdist > 140 * 140) { + if (pdist > 140 * 140) + { perp3x = perpx - perp2x; perp3y = perpy - perp2y; @@ -639,7 +694,8 @@ indexCount++; } - else { + else + { verts.push(px , py); verts.push(r, g, b, alpha); @@ -672,7 +728,8 @@ indices.push(indexStart); - for (i = 0; i < indexCount; i++) { + for (i = 0; i < indexCount; i++) + { indices.push(indexStart++); } @@ -687,11 +744,13 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildComplexPoly = function (graphicsData, webGLData) { +WebGLGraphics.buildComplexPoly = function (graphicsData, webGLData) +{ //TODO - no need to copy this as it gets turned into a FLoat32Array anyways.. var points = graphicsData.points.slice(); - if (points.length < 6) { + if (points.length < 6) + { return; } @@ -711,7 +770,8 @@ var x,y; // get size.. - for (var i = 0; i < points.length; i+=2) { + for (var i = 0; i < points.length; i+=2) + { x = points[i]; y = points[i+1]; @@ -732,7 +792,8 @@ //TODO - this aint needed! var length = points.length / 2; - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { indices.push( i ); } @@ -746,10 +807,12 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildPoly = function (graphicsData, webGLData) { +WebGLGraphics.buildPoly = function (graphicsData, webGLData) +{ var points = graphicsData.points; - if (points.length < 6) { + if (points.length < 6) + { return; } // get first and last point.. figure out the middle! @@ -767,7 +830,8 @@ var triangles = utils.PolyK.Triangulate(points); - if (!triangles) { + if (!triangles) + { return false; } @@ -775,7 +839,8 @@ var i = 0; - for (i = 0; i < triangles.length; i+=3) { + for (i = 0; i < triangles.length; i+=3) + { indices.push(triangles[i] + vertPos); indices.push(triangles[i] + vertPos); indices.push(triangles[i+1] + vertPos); @@ -783,7 +848,8 @@ indices.push(triangles[i+2] + vertPos); } - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { verts.push(points[i * 2], points[i * 2 + 1], r, g, b, alpha); } diff --git a/src/core/renderers/webgl/utils/WebGLGraphicsData.js b/src/core/renderers/webgl/utils/WebGLGraphicsData.js index c56d05e..c739ba7 100644 --- a/src/core/renderers/webgl/utils/WebGLGraphicsData.js +++ b/src/core/renderers/webgl/utils/WebGLGraphicsData.js @@ -2,7 +2,8 @@ * @class * @private */ -function WebGLGraphicsData(gl) { +function WebGLGraphicsData(gl) +{ this.gl = gl; //TODO does this need to be split before uploding?? @@ -22,7 +23,8 @@ /** * */ -WebGLGraphicsData.prototype.reset = function () { +WebGLGraphicsData.prototype.reset = function () +{ this.points.length = 0; this.indices.length = 0; }; @@ -30,7 +32,8 @@ /** * */ -WebGLGraphicsData.prototype.upload = function () { +WebGLGraphicsData.prototype.upload = function () +{ var gl = this.gl; // this.lastIndex = graphics.graphicsData.length; diff --git a/src/core/renderers/webgl/utils/WebGLSpriteBatch.js b/src/core/renderers/webgl/utils/WebGLSpriteBatch.js index 96eaa52..55befbb 100644 --- a/src/core/renderers/webgl/utils/WebGLSpriteBatch.js +++ b/src/core/renderers/webgl/utils/WebGLSpriteBatch.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this sprite batch works for. */ -function WebGLSpriteBatch(renderer) { +function WebGLSpriteBatch(renderer) +{ /** * * @@ -88,7 +89,8 @@ */ this.lastIndexCount = 0; - for (var i=0, j=0; i < numIndices; i += 6, j += 4) { + 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; @@ -162,7 +164,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.setupContext(); }); } @@ -173,7 +176,8 @@ /** * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLSpriteBatch.prototype.setupContext = function () { +WebGLSpriteBatch.prototype.setupContext = function () +{ var gl = this.renderer.gl; // setup default shader @@ -198,7 +202,8 @@ /** * */ -WebGLSpriteBatch.prototype.begin = function () { +WebGLSpriteBatch.prototype.begin = function () +{ // this.shader = this.renderer.shaderManager.defaultShader; this.start(); @@ -206,19 +211,22 @@ /** */ -WebGLSpriteBatch.prototype.end = function () { +WebGLSpriteBatch.prototype.end = function () +{ this.flush(); }; /** * @param sprite {Sprite} the sprite to render when using this spritebatch */ -WebGLSpriteBatch.prototype.render = function (sprite) { +WebGLSpriteBatch.prototype.render = function (sprite) +{ var texture = sprite.texture; //TODO set blend modes.. // check texture.. - if (this.currentBatchSize >= this.size) { + if (this.currentBatchSize >= this.size) + { this.flush(); this.currentBaseTexture = texture.baseTexture; } @@ -227,7 +235,8 @@ var uvs = texture._uvs; // if the uvs have not updated then no point rendering just yet! - if (!uvs) { + if (!uvs) + { return; } @@ -237,7 +246,8 @@ var w0, w1, h0, h1; - if (texture.trim) { + 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; @@ -248,7 +258,8 @@ h0 = h1 + texture.crop.height; } - else { + else + { w0 = (texture.frame.width ) * (1-aX); w1 = (texture.frame.width ) * -aX; @@ -272,7 +283,8 @@ var colors = this.colors; var positions = this.positions; - if (this.renderer.roundPixels) { + if (this.renderer.roundPixels) + { // xy positions[index] = a * w1 + c * h1 + tx | 0; positions[index+1] = d * h1 + b * w1 + ty | 0; @@ -289,7 +301,8 @@ positions[index+15] = a * w1 + c * h0 + tx | 0; positions[index+16] = d * h0 + b * w1 + ty | 0; } - else { + else + { // xy positions[index] = a * w1 + c * h1 + tx; positions[index+1] = d * h1 + b * w1 + ty; @@ -338,11 +351,13 @@ * * @param sprite {TilingSprite} the tilingSprite to render */ -WebGLSpriteBatch.prototype.renderTilingSprite = function (tilingSprite) { +WebGLSpriteBatch.prototype.renderTilingSprite = function (tilingSprite) +{ var texture = tilingSprite.tilingTexture; // check texture.. - if (this.currentBatchSize >= this.size) { + if (this.currentBatchSize >= this.size) + { //return; this.flush(); this.currentBaseTexture = texture.baseTexture; @@ -351,7 +366,8 @@ // set the textures uvs temporarily // TODO create a separate texture so that we can tile part of a texture - if (!tilingSprite._uvs) { + if (!tilingSprite._uvs) + { tilingSprite._uvs = new TextureUvs(); } @@ -454,16 +470,19 @@ * Renders the content and empties the current batch. * */ -WebGLSpriteBatch.prototype.flush = function () { +WebGLSpriteBatch.prototype.flush = function () +{ // If the batch is length 0 then return as there is nothing to draw - if (this.currentBatchSize === 0) { + if (this.currentBatchSize === 0) + { return; } var gl = this.renderer.gl; var shader; - if (this.dirty) { + if (this.dirty) + { this.dirty = false; // bind the main texture gl.activeTexture(gl.TEXTURE0); @@ -482,10 +501,12 @@ } // upload the verts to the buffer - if (this.currentBatchSize > ( this.size * 0.5 ) ) { + if (this.currentBatchSize > ( this.size * 0.5 ) ) + { gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); } - else { + else + { var view = this.positions.subarray(0, this.currentBatchSize * this.vertByteSize); gl.bufferSubData(gl.ARRAY_BUFFER, 0, view); } @@ -502,7 +523,8 @@ var shaderSwap = false; var sprite; - for (var i = 0, j = this.currentBatchSize; i < j; i++) { + for (var i = 0, j = this.currentBatchSize; i < j; i++) + { sprite = this.sprites[i]; @@ -513,24 +535,28 @@ blendSwap = currentBlendMode !== nextBlendMode; shaderSwap = currentShader !== nextShader; // should I use uuidS??? - if (currentBaseTexture !== nextTexture || blendSwap || shaderSwap) { + if (currentBaseTexture !== nextTexture || blendSwap || shaderSwap) + { this.renderBatch(currentBaseTexture, batchSize, start); start = i; batchSize = 0; currentBaseTexture = nextTexture; - if (blendSwap) { + if (blendSwap) + { currentBlendMode = nextBlendMode; this.renderer.blendModeManager.setBlendMode( currentBlendMode ); } - if (shaderSwap) { + if (shaderSwap) + { currentShader = nextShader; shader = currentShader.shaders ? currentShader.shaders[gl.id] : currentShader; - if (!shader) { + if (!shader) + { shader = new Shader(gl, null, currentShader.fragmentSrc, currentShader.uniforms); currentShader.shaders[gl.id] = shader; } @@ -538,7 +564,8 @@ // set shader function??? this.renderer.shaderManager.setShader(shader); - if (shader.dirty) { + if (shader.dirty) + { shader.syncUniforms(); } @@ -569,17 +596,21 @@ * @param size {number} * @param startIndex {number} */ -WebGLSpriteBatch.prototype.renderBatch = function (texture, size, startIndex) { - if (size === 0) { +WebGLSpriteBatch.prototype.renderBatch = function (texture, size, startIndex) +{ + if (size === 0) + { return; } var gl = this.renderer.gl; - if (!texture._glTextures[gl.id]) { + if (!texture._glTextures[gl.id]) + { this.renderer.updateTexture(texture); } - else { + else + { // bind the current texture gl.bindTexture(gl.TEXTURE_2D, texture._glTextures[gl.id]); } @@ -594,7 +625,8 @@ /** * */ -WebGLSpriteBatch.prototype.stop = function () { +WebGLSpriteBatch.prototype.stop = function () +{ this.flush(); this.dirty = true; }; @@ -602,7 +634,8 @@ /** * */ -WebGLSpriteBatch.prototype.start = function () { +WebGLSpriteBatch.prototype.start = function () +{ this.dirty = true; }; @@ -610,7 +643,8 @@ * Destroys the SpriteBatch. * */ -WebGLSpriteBatch.prototype.destroy = function () { +WebGLSpriteBatch.prototype.destroy = function () +{ this.renderer.gl.deleteBuffer(this.vertexBuffer); this.renderer.gl.deleteBuffer(this.indexBuffer); diff --git a/src/core/textures/BaseTexture.js b/src/core/textures/BaseTexture.js index 2bf77d4..513d358 100644 --- a/src/core/textures/BaseTexture.js +++ b/src/core/textures/BaseTexture.js @@ -10,7 +10,8 @@ * @param source {Image|Canvas} the source object of the texture. * @param [scaleMode=scaleModes.DEFAULT] {number} See {@link scaleModes} for possible values */ -function BaseTexture(source, scaleMode) { +function BaseTexture(source, scaleMode) +{ this.uuid = utils.uuid(); /** @@ -123,7 +124,8 @@ this._needsUpdate = false; // if no source passed don't try to load - if (source) { + if (source) + { this.loadSource(source); } @@ -149,13 +151,16 @@ Object.defineProperties(BaseTexture.prototype, { needsUpdate: { - get: function () { + get: function () + { return this._needsUpdate; }, - set: function (val) { + set: function (val) + { this._needsUpdate = val; - if (val) { + if (val) + { this.emit('update', this); } } @@ -171,9 +176,11 @@ * * The logic state after calling `loadSource` directly or indirectly (eg. `fromImage`, `new BaseTexture`) is: * - * if (texture.hasLoaded) { + * if (texture.hasLoaded) + { * // texture ready for use - * } else if (texture.isLoading) { + * } else if (texture.isLoading) + { * // listen to 'loaded' and/or 'error' events on texture * } else { * // not loading, not going to load UNLESS the source is reloaded @@ -183,12 +190,14 @@ * @protected * @param source {Image|Canvas} the source object of the texture. */ -BaseTexture.prototype.loadSource = function (source) { +BaseTexture.prototype.loadSource = function (source) +{ var wasLoading = this.isLoading; this.hasLoaded = false; this.isLoading = false; - if (wasLoading && this.source) { + if (wasLoading && this.source) + { this.source.onload = null; this.source.onerror = null; } @@ -196,20 +205,24 @@ this.source = source; // Apply source if loaded. Otherwise setup appropriate loading monitors. - if ((this.source.complete || this.source.getContext) && this.source.width && this.source.height) { + if ((this.source.complete || this.source.getContext) && this.source.width && this.source.height) + { this._sourceLoaded(); } - else if(!source.getContext) { + else if(!source.getContext) + { // Image fail / not ready this.isLoading = true; var scope = this; - source.onload = function () { + source.onload = function () + { source.onload = null; source.onerror = null; - if(!scope.isLoading) { + if(!scope.isLoading) + { return; } @@ -219,11 +232,13 @@ scope.emit('loaded', scope); }; - source.onerror = function () { + source.onerror = function () + { source.onload = null; source.onerror = null; - if(!scope.isLoading) { + if(!scope.isLoading) + { return; } @@ -234,24 +249,29 @@ // Per http://www.w3.org/TR/html5/embedded-content-0.html#the-img-element // "The value of `complete` can thus change while a script is executing." // So complete needs to be re-checked after the callbacks have been added.. - if (source.complete) { + if (source.complete) + { this.isLoading = false; // ..and if we're complete now, no need for callbacks source.onload = null; source.onerror = null; - if (source.width && source.height) { + if (source.width && source.height) + { this._sourceLoaded(); // If any previous subscribers possible - if (wasLoading) { + if (wasLoading) + { this.emit('loaded', this); } } - else { + else + { // If any previous subscribers possible - if (wasLoading) { + if (wasLoading) + { this.emit('error', this); } } @@ -265,7 +285,8 @@ * * @private */ -BaseTexture.prototype._sourceLoaded = function () { +BaseTexture.prototype._sourceLoaded = function () +{ this.hasLoaded = true; this.width = this.source.naturalWidth || this.source.width; @@ -278,16 +299,20 @@ * Destroys this base texture * */ -BaseTexture.prototype.destroy = function () { - if (this.imageUrl) { +BaseTexture.prototype.destroy = function () +{ + if (this.imageUrl) + { delete utils.BaseTextureCache[this.imageUrl]; delete utils.TextureCache[this.imageUrl]; this.imageUrl = null; - if (!navigator.isCocoonJS) { + if (!navigator.isCocoonJS) + { this.source.src = ''; } } - else if (this.source && this.source._pixiId) { + else if (this.source && this.source._pixiId) + { delete utils.BaseTextureCache[this.source._pixiId]; } this.source = null; @@ -301,7 +326,8 @@ * memory again. * */ -BaseTexture.prototype.dispose = function () { +BaseTexture.prototype.dispose = function () +{ this.emit('dispose', this); }; @@ -311,7 +337,8 @@ * * @param newSrc {string} the path of the image */ -BaseTexture.prototype.updateSourceImage = function (newSrc) { +BaseTexture.prototype.updateSourceImage = function (newSrc) +{ this.source.src = newSrc; this.loadSource(this.source); }; @@ -326,18 +353,22 @@ * @param [scaleMode=scaleModes.DEFAULT] {number} See {@link scaleModes} for possible values * @return BaseTexture */ -BaseTexture.fromImage = function (imageUrl, crossorigin, scaleMode) { +BaseTexture.fromImage = function (imageUrl, crossorigin, scaleMode) +{ var baseTexture = utils.BaseTextureCache[imageUrl]; - if (crossorigin === undefined && imageUrl.indexOf('data:') !== 0) { + if (crossorigin === undefined && imageUrl.indexOf('data:') !== 0) + { crossorigin = true; } - if (!baseTexture) { + if (!baseTexture) + { // new Image() breaks tex loading in some versions of Chrome. // See https://code.google.com/p/chromium/issues/detail?id=238071 var image = new Image();//document.createElement('img'); - if (crossorigin) { + if (crossorigin) + { image.crossOrigin = ''; } @@ -347,7 +378,8 @@ utils.BaseTextureCache[imageUrl] = baseTexture; // if there is an @2x at the end of the url we are going to assume its a highres image - if ( imageUrl.indexOf(CONST.RETINA_PREFIX + '.') !== -1) { + if ( imageUrl.indexOf(CONST.RETINA_PREFIX + '.') !== -1) + { baseTexture.resolution = 2; } } @@ -363,14 +395,17 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return BaseTexture */ -BaseTexture.fromCanvas = function (canvas, scaleMode) { - if (!canvas._pixiId) { +BaseTexture.fromCanvas = function (canvas, scaleMode) +{ + if (!canvas._pixiId) + { canvas._pixiId = 'canvas_' + utils.uuid(); } var baseTexture = utils.BaseTextureCache[canvas._pixiId]; - if (!baseTexture) { + if (!baseTexture) + { baseTexture = new BaseTexture(canvas, scaleMode); utils.BaseTextureCache[canvas._pixiId] = baseTexture; } diff --git a/src/core/textures/RenderTexture.js b/src/core/textures/RenderTexture.js index 6dad20f..53ae796 100644 --- a/src/core/textures/RenderTexture.js +++ b/src/core/textures/RenderTexture.js @@ -46,8 +46,10 @@ * @param [scaleMode] {number} See {@link scaleModes} for possible values * @param [resolution=1] {number} The resolution of the texture being generated */ -function RenderTexture(renderer, width, height, scaleMode, resolution) { - if (!renderer) { +function RenderTexture(renderer, width, height, scaleMode, resolution) +{ + if (!renderer) + { throw new Error('Unable to create RenderTexture, you must pass a renderer into the constructor.'); } @@ -133,7 +135,8 @@ */ this.renderer = renderer; - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { var gl = this.renderer.gl; this.textureBuffer = new FilterTexture(gl, this.width * this.resolution, this.height * this.resolution, this.baseTexture.scaleMode); @@ -142,7 +145,8 @@ this.render = this.renderWebGL; this.projection = new math.Point(this.width*0.5, -this.height*0.5); } - else { + else + { this.render = this.renderCanvas; this.textureBuffer = new CanvasBuffer(this.width* this.resolution, this.height* this.resolution); this.baseTexture.source = this.textureBuffer.canvas; @@ -167,8 +171,10 @@ * @param height {number} The height to resize to. * @param updateBase {boolean} Should the baseTexture.width and height values be resized as well? */ -RenderTexture.prototype.resize = function (width, height, updateBase) { - if (width === this.width && height === this.height) { +RenderTexture.prototype.resize = function (width, height, updateBase) +{ + if (width === this.width && height === this.height) + { return; } @@ -177,17 +183,20 @@ this.width = this.frame.width = this.crop.width = width; this.height = this.frame.height = this.crop.height = height; - if (updateBase) { + if (updateBase) + { this.baseTexture.width = this.width; this.baseTexture.height = this.height; } - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { this.projection.x = this.width / 2; this.projection.y = -this.height / 2; } - if (!this.valid) { + if (!this.valid) + { return; } @@ -198,12 +207,15 @@ * Clears the RenderTexture. * */ -RenderTexture.prototype.clear = function () { - if (!this.valid) { +RenderTexture.prototype.clear = function () +{ + if (!this.valid) + { return; } - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { this.renderer.gl.bindFramebuffer(this.renderer.gl.FRAMEBUFFER, this.textureBuffer.frameBuffer); } @@ -220,19 +232,23 @@ * @param [restoreWorldTransform=true] {boolean} If true the displayObject's worldTransform/worldAlpha and all children * transformations will be restored. Not restoring this information will be a little faster. */ -RenderTexture.prototype.renderWebGL = function (displayObject, matrix, clear, restoreWorldTransform) { - if (!this.valid) { +RenderTexture.prototype.renderWebGL = function (displayObject, matrix, clear, restoreWorldTransform) +{ + if (!this.valid) + { return; } - if (typeof restoreWorldTransform === 'undefined') { + if (typeof restoreWorldTransform === 'undefined') + { restoreWorldTransform = true; } var tempAlpha, tempTransform; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { tempAlpha = displayObject.worldAlpha; tempTransform = displayObject.worldTransform.toArray(); } @@ -245,7 +261,8 @@ wt.identity(); wt.translate(0, this.projection.y * 2); - if (matrix) { + if (matrix) + { wt.append(matrix); } @@ -258,7 +275,8 @@ var children = displayObject.children; var i, j; - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } @@ -269,7 +287,8 @@ gl.bindFramebuffer(gl.FRAMEBUFFER, this.textureBuffer.frameBuffer ); - if (clear) { + if (clear) + { this.textureBuffer.clear(); } @@ -279,11 +298,13 @@ this.renderer.spriteBatch.dirty = true; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { displayObject.worldAlpha = tempAlpha; displayObject.worldTransform.fromArray(tempTransform); - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } } @@ -300,26 +321,31 @@ * @param [restoreWorldTransform=true] {boolean} If true the displayObject's worldTransform/worldAlpha and all children * transformations will be restored. Not restoring this information will be a little faster. */ -RenderTexture.prototype.renderCanvas = function (displayObject, matrix, clear, restoreWorldTransform) { - if (!this.valid) { +RenderTexture.prototype.renderCanvas = function (displayObject, matrix, clear, restoreWorldTransform) +{ + if (!this.valid) + { return; } - if (typeof restoreWorldTransform === 'undefined') { + if (typeof restoreWorldTransform === 'undefined') + { restoreWorldTransform = true; } var tempAlpha, tempTransform; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { tempAlpha = displayObject.worldAlpha; tempTransform = displayObject.worldTransform.toArray(); } var wt = displayObject.worldTransform; wt.identity(); - if (matrix) { + if (matrix) + { wt.append(matrix); } @@ -330,11 +356,13 @@ var children = displayObject.children; var i, j; - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } - if (clear) { + if (clear) + { this.textureBuffer.clear(); } @@ -348,11 +376,13 @@ this.renderer.resolution = realResolution; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { displayObject.worldAlpha = tempAlpha; displayObject.worldTransform.fromArray(tempTransform); - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } } @@ -363,7 +393,8 @@ * * @return {Image} */ -RenderTexture.prototype.getImage = function () { +RenderTexture.prototype.getImage = function () +{ var image = new Image(); image.src = this.getBase64(); return image; @@ -374,7 +405,8 @@ * * @return {string} A base64 encoded string of the texture. */ -RenderTexture.prototype.getBase64 = function () { +RenderTexture.prototype.getBase64 = function () +{ return this.getCanvas().toDataURL(); }; @@ -383,8 +415,10 @@ * * @return {HTMLCanvasElement} A Canvas element with the texture rendered on. */ -RenderTexture.prototype.getCanvas = function () { - if (this.renderer.type === CONST.WEBGL_RENDERER) { +RenderTexture.prototype.getCanvas = function () +{ + if (this.renderer.type === CONST.WEBGL_RENDERER) + { var gl = this.renderer.gl; var width = this.textureBuffer.width; var height = this.textureBuffer.height; @@ -403,7 +437,8 @@ return tempCanvas.canvas; } - else { + else + { return this.textureBuffer.canvas; } }; diff --git a/src/core/textures/Texture.js b/src/core/textures/Texture.js index 3c65909..e97f0aa 100644 --- a/src/core/textures/Texture.js +++ b/src/core/textures/Texture.js @@ -17,7 +17,8 @@ * @param [crop] {Rectangle} The area of original texture * @param [trim] {Rectangle} Trimmed texture rectangle */ -function Texture(baseTexture, frame, crop, trim) { +function Texture(baseTexture, frame, crop, trim) +{ /** * Does this Texture have any frame data assigned to it? * @@ -25,12 +26,14 @@ */ this.noFrame = false; - if (!frame) { + if (!frame) + { this.noFrame = true; frame = new math.Rectangle(0, 0, 1, 1); } - if (baseTexture instanceof Texture) { + if (baseTexture instanceof Texture) + { baseTexture = baseTexture.baseTexture; } @@ -100,13 +103,16 @@ */ this.crop = crop || new math.Rectangle(0, 0, 1, 1); - if (baseTexture.hasLoaded) { - if (this.noFrame) { + if (baseTexture.hasLoaded) + { + if (this.noFrame) + { frame = new math.Rectangle(0, 0, baseTexture.width, baseTexture.height); } this.frame = frame; } - else { + else + { baseTexture.addEventListener('loaded', this.onBaseTextureLoaded.bind(this)); } } @@ -118,19 +124,23 @@ Object.defineProperties(Texture.prototype, { needsUpdate: { - get: function () { + get: function () + { return this.baseTexture.needsUpdate; }, - set: function (val) { + set: function (val) + { this.baseTexture.needsUpdate = val; } }, frame: { - get: function () { + get: function () + { return this._frame; }, - set: function (frame) { + set: function (frame) + { this._frame = frame; this.noFrame = false; @@ -143,20 +153,23 @@ 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 (!this.trim && (frame.x + frame.width > this.baseTexture.width || frame.y + frame.height > this.baseTexture.height)) + { throw new Error('Texture Error: frame does not fit inside the base Texture dimensions ' + this); } this.valid = frame && frame.width && frame.height && this.baseTexture.source && this.baseTexture.hasLoaded; - if (this.trim) { + 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) { + if (this.valid) + { this._updateUvs(); } } @@ -168,11 +181,13 @@ * * @private */ -Texture.prototype.onBaseTextureLoaded = function () { +Texture.prototype.onBaseTextureLoaded = function () +{ var baseTexture = this.baseTexture; baseTexture.removeEventListener('loaded', this.onLoaded); - if (this.noFrame) { + if (this.noFrame) + { this.frame = new math.Rectangle(0, 0, baseTexture.width, baseTexture.height); } @@ -184,8 +199,10 @@ * * @param destroyBase {boolean} Whether to destroy the base texture as well */ -Texture.prototype.destroy = function (destroyBase) { - if (destroyBase) { +Texture.prototype.destroy = function (destroyBase) +{ + if (destroyBase) + { this.baseTexture.destroy(); } @@ -197,8 +214,10 @@ * * @private */ -Texture.prototype._updateUvs = function () { - if (!this._uvs) { +Texture.prototype._updateUvs = function () +{ + if (!this._uvs) + { this._uvs = new TextureUvs(); } @@ -229,10 +248,12 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return Texture */ -Texture.fromImage = function (imageUrl, crossorigin, scaleMode) { +Texture.fromImage = function (imageUrl, crossorigin, scaleMode) +{ var texture = utils.TextureCache[imageUrl]; - if (!texture) { + if (!texture) + { texture = new Texture(BaseTexture.fromImage(imageUrl, crossorigin, scaleMode)); utils.TextureCache[imageUrl] = texture; } @@ -248,9 +269,11 @@ * @param frameId {string} The frame id of the texture * @return Texture */ -Texture.fromFrame = function (frameId) { +Texture.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache '); } return texture; @@ -264,7 +287,8 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return {Texture} */ -Texture.fromCanvas = function (canvas, scaleMode) { +Texture.fromCanvas = function (canvas, scaleMode) +{ return new Texture(BaseTexture.fromCanvas(canvas, scaleMode)); }; @@ -276,7 +300,8 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return {Texture} A Texture */ -Texture.fromVideo = function (video, scaleMode) { +Texture.fromVideo = function (video, scaleMode) +{ return new Texture(VideoBaseTexture.baseTextureFromVideo(video, scaleMode)); }; @@ -287,7 +312,8 @@ * @param texture {Texture} The Texture to add to the cache. * @param id {string} The id that the texture will be stored against. */ -Texture.addTextureToCache = function (texture, id) { +Texture.addTextureToCache = function (texture, id) +{ utils.TextureCache[id] = texture; }; @@ -298,7 +324,8 @@ * @param id {string} The id of the texture to be removed * @return {Texture} The texture that was removed */ -Texture.removeTextureFromCache = function (id) { +Texture.removeTextureFromCache = function (id) +{ var texture = utils.TextureCache[id]; delete utils.TextureCache[id]; diff --git a/src/core/textures/TextureUvs.js b/src/core/textures/TextureUvs.js index b9bbb58..5424d52 100644 --- a/src/core/textures/TextureUvs.js +++ b/src/core/textures/TextureUvs.js @@ -1,4 +1,5 @@ -function TextureUvs() { +function TextureUvs() +{ this.x0 = 0; this.y0 = 0; diff --git a/src/core/textures/VideoBaseTexture.js b/src/core/textures/VideoBaseTexture.js index e3e0c5a..1a826a9 100644 --- a/src/core/textures/VideoBaseTexture.js +++ b/src/core/textures/VideoBaseTexture.js @@ -12,15 +12,18 @@ * @param source {HTMLVideoElement} * @param [scaleMode] {number} See {@link scaleModes} for possible values */ -function VideoBaseTexture(source, scaleMode) { - if (!source){ +function VideoBaseTexture(source, scaleMode) +{ + if (!source) + { throw new Error('No video source element specified.'); } // hook in here to check if video is already available. // BaseTexture looks for a source.complete boolean, plus width & height. - if ((source.readyState === source.HAVE_ENOUGH_DATA || source.readyState === source.HAVE_FUTURE_DATA) && source.width && source.height) { + if ((source.readyState === source.HAVE_ENOUGH_DATA || source.readyState === source.HAVE_FUTURE_DATA) && source.width && source.height) + { source.complete = true; } @@ -31,7 +34,8 @@ this._boundOnUpdate = this._onUpdate.bind(this); this._boundOnCanPlay = this._onCanPlay.bind(this); - if (!source.complete) { + if (!source.complete) + { source.addEventListener('canplay', this._boundOnCanPlay); source.addEventListener('canplaythrough', this._boundOnCanPlay); @@ -47,28 +51,35 @@ VideoBaseTexture.prototype.constructor = VideoBaseTexture; module.exports = VideoBaseTexture; -VideoBaseTexture.prototype._onUpdate = function () { - if (this.autoUpdate) { +VideoBaseTexture.prototype._onUpdate = function () +{ + if (this.autoUpdate) + { window.requestAnimationFrame(this._boundOnUpdate); this.needsUpdate = true; } }; -VideoBaseTexture.prototype._onPlayStart = function () { - if (!this.autoUpdate) { +VideoBaseTexture.prototype._onPlayStart = function () +{ + if (!this.autoUpdate) + { window.requestAnimationFrame(this._boundOnUpdate); this.autoUpdate = true; } }; -VideoBaseTexture.prototype._onPlayStop = function () { +VideoBaseTexture.prototype._onPlayStop = function () +{ this.autoUpdate = false; }; -VideoBaseTexture.prototype._onCanPlay = function () { +VideoBaseTexture.prototype._onCanPlay = function () +{ this.hasLoaded = true; - if (this.source) { + if (this.source) + { this.source.removeEventListener('canplay', this._boundOnCanPlay); this.source.removeEventListener('canplaythrough', this._boundOnCanPlay); @@ -78,15 +89,18 @@ this.source.play(); // prevent multiple loaded dispatches.. - if(!this.__loaded){ + if(!this.__loaded) + { this.__loaded = true; this.emit('loaded', this); } } }; -VideoBaseTexture.prototype.destroy = function () { - if (this.source && this.source._pixiId) { +VideoBaseTexture.prototype.destroy = function () +{ + if (this.source && this.source._pixiId) + { utils.BaseTextureCache[ this.source._pixiId ] = null; delete utils.BaseTextureCache[ this.source._pixiId ]; @@ -105,14 +119,17 @@ * @param scaleMode {number} See {@link scaleModes} for possible values * @return {VideoBaseTexture} */ -VideoBaseTexture.fromVideo = function (video, scaleMode) { - if (!video._pixiId) { +VideoBaseTexture.fromVideo = function (video, scaleMode) +{ + if (!video._pixiId) + { video._pixiId = 'video_' + utils.uuid(); } var baseTexture = utils.BaseTextureCache[video._pixiId]; - if (!baseTexture) { + if (!baseTexture) + { baseTexture = new VideoBaseTexture(video, scaleMode); utils.BaseTextureCache[ video._pixiId ] = baseTexture; } @@ -147,17 +164,21 @@ * @param scaleMode {number} See {@link scaleModes} for possible values * @return {VideoBaseTexture} */ -VideoBaseTexture.fromUrl = function (videoSrc, scaleMode) { +VideoBaseTexture.fromUrl = function (videoSrc, scaleMode) +{ var video = document.createElement('video'); // array of objects or strings - if (Array.isArray(videoSrc)) { - for (var i = 0; i < videoSrc.length; ++i) { + if (Array.isArray(videoSrc)) + { + for (var i = 0; i < videoSrc.length; ++i) + { video.appendChild(createSource(videoSrc.src || videoSrc, videoSrc.mime)); } } // single object or string - else { + else + { video.appendChild(createSource(videoSrc.src || videoSrc, videoSrc.mime)); } @@ -169,8 +190,10 @@ VideoBaseTexture.fromUrls = VideoBaseTexture.fromUrl; -function createSource(path, type) { - if (!type) { +function createSource(path, type) +{ + if (!type) + { type = 'video/' + path.substr(path.lastIndexOf('.') + 1); } diff --git a/src/core/utils/EventData.js b/src/core/utils/EventData.js index 5d55a22..8cdf701 100644 --- a/src/core/utils/EventData.js +++ b/src/core/utils/EventData.js @@ -7,7 +7,8 @@ * @param name {string} The string name of the event that was triggered * @param data {object} Arbitrary event data to pass along */ -function EventData(target, name, data) { +function EventData(target, name, data) +{ // for duck typing in the ".on()" function this.__isEventObject = true; @@ -71,7 +72,8 @@ * Stops the propagation of events up the scene graph (prevents bubbling). * */ -EventData.prototype.stopPropagation = function stopPropagation() { +EventData.prototype.stopPropagation = function stopPropagation() +{ this.stopped = true; }; @@ -79,6 +81,7 @@ * Stops the propagation of events to sibling listeners (no longer calls any listeners). * */ -EventData.prototype.stopImmediatePropagation = function stopImmediatePropagation() { +EventData.prototype.stopImmediatePropagation = function stopImmediatePropagation() +{ this.stoppedImmediate = true; }; diff --git a/src/core/utils/EventTarget.js b/src/core/utils/EventTarget.js index 7ae8820..671a151 100644 --- a/src/core/utils/EventTarget.js +++ b/src/core/utils/EventTarget.js @@ -13,14 +13,16 @@ * var em = new MyEmitter(); * em.emit('eventName', 'some data', 'some more data', {}, null, ...); */ -function eventTarget(obj) { +function eventTarget(obj) +{ /** * Return a list of assigned event listeners. * * @param eventName {string} The events that should be listed. * @return {Array} An array of listener functions */ - obj.listeners = function listeners(eventName) { + obj.listeners = function listeners(eventName) + { this._listeners = this._listeners || {}; return this._listeners[eventName] ? this._listeners[eventName].slice() : []; @@ -33,22 +35,26 @@ * @param eventName {string} The name of the event. * @return {boolean} Indication if we've emitted an event. */ - obj.emit = obj.dispatchEvent = function emit(eventName, data) { + obj.emit = obj.dispatchEvent = function emit(eventName, data) + { this._listeners = this._listeners || {}; // fast return when there are no listeners - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return; } //backwards compat with old method ".emit({ type: 'something' })" - if (typeof eventName === 'object') { + if (typeof eventName === 'object') + { data = eventName; eventName = eventName.type; } //ensure we are using a real pixi event - if (!data || data.__isEventObject !== true) { + if (!data || data.__isEventObject !== true) + { data = new EventData(this, eventName, data); } @@ -58,23 +64,27 @@ fn = listeners[0], i; - for (i = 0; i < length; fn = listeners[++i]) { + for (i = 0; i < length; fn = listeners[++i]) + { //call the event listener fn.call(this, data); //if "stopImmediatePropagation" is called, stop calling sibling events - if (data.stoppedImmediate) { + if (data.stoppedImmediate) + { return this; } } //if "stopPropagation" is called then don't bubble the event - if (data.stopped) { + if (data.stopped) + { return this; } //bubble this event up the scene graph - if (this.parent && this.parent.emit) { + if (this.parent && this.parent.emit) + { this.parent.emit.call(this.parent, eventName, data); } @@ -88,7 +98,8 @@ * @param eventName {string} Name of the event. * @param callback {Functon} fn Callback function. */ - obj.on = obj.addEventListener = function on(eventName, fn) { + obj.on = obj.addEventListener = function on(eventName, fn) + { this._listeners = this._listeners || {}; (this._listeners[eventName] = this._listeners[eventName] || []) @@ -103,11 +114,13 @@ * @param eventName {string} Name of the event. * @param callback {Function} Callback function. */ - obj.once = function once(eventName, fn) { + obj.once = function once(eventName, fn) + { this._listeners = this._listeners || {}; var self = this; - function onceHandlerWrapper() { + function onceHandlerWrapper() + { fn.apply(self.off(eventName, onceHandlerWrapper), arguments); } onceHandlerWrapper._originalHandler = fn; @@ -122,23 +135,28 @@ * @param eventName {string} The event we want to remove. * @param callback {Function} The listener that we need to find. */ - obj.off = obj.removeEventListener = function off(eventName, fn) { + obj.off = obj.removeEventListener = function off(eventName, fn) + { this._listeners = this._listeners || {}; - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return this; } var list = this._listeners[eventName], i = fn ? list.length : 0; - while(i-- > 0) { - if (list[i] === fn || list[i]._originalHandler === fn) { + while(i-- > 0) + { + if (list[i] === fn || list[i]._originalHandler === fn) + { list.splice(i, 1); } } - if (list.length === 0) { + if (list.length === 0) + { delete this._listeners[eventName]; } @@ -150,10 +168,12 @@ * * @param eventName {string} The event you want to remove all listeners for. */ - obj.removeAllListeners = function removeAllListeners(eventName) { + obj.removeAllListeners = function removeAllListeners(eventName) + { this._listeners = this._listeners || {}; - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return this; } @@ -169,7 +189,8 @@ * * @param object {object} The obj to mix into */ - mixin: function mixin(obj) { + mixin: function mixin(obj) + { eventTarget(obj); } }; diff --git a/src/core/utils/PolyK.js b/src/core/utils/PolyK.js index 7325141..5e20c2b 100644 --- a/src/core/utils/PolyK.js +++ b/src/core/utils/PolyK.js @@ -47,7 +47,8 @@ * Triangulates shapes for webGL graphic fills. * */ -PolyK.Triangulate = function (p) { +PolyK.Triangulate = function (p) +{ var sign = true; var n = p.length >> 1; @@ -59,7 +60,8 @@ i = 0; var al = n; - while(al > 3) { + while(al > 3) + { var i0 = avl[(i+0)%al]; var i1 = avl[(i+1)%al]; var i2 = avl[(i+2)%al]; @@ -69,29 +71,35 @@ var cx = p[2*i2], cy = p[2*i2+1]; var earFound = false; - if (PolyK._convex(ax, ay, bx, by, cx, cy, sign)) { + if (PolyK._convex(ax, ay, bx, by, cx, cy, sign)) + { earFound = true; - for (var j = 0; j < al; j++) { + for (var j = 0; j < al; j++) + { var vi = avl[j]; if (vi === i0 || vi === i1 || vi === i2) continue; - if (PolyK._PointInTriangle(p[2*vi], p[2*vi+1], ax, ay, bx, by, cx, cy)) { + if (PolyK._PointInTriangle(p[2*vi], p[2*vi+1], ax, ay, bx, by, cx, cy)) + { earFound = false; break; } } } - if (earFound) { + if (earFound) + { tgs.push(i0, i1, i2); avl.splice((i+1)%al, 1); al--; i = 0; } - else if (i++ > 3*al) { + else if (i++ > 3*al) + { // need to flip flip reverse it! // reset! - if (sign) { + if (sign) + { tgs = []; avl = []; for (i = 0; i < n; i++) avl.push(i); @@ -101,7 +109,8 @@ sign = false; } - else { + else + { // window.console.log("PIXI Warning: shape too complex to fill"); return null; } @@ -126,7 +135,8 @@ * @private * @return {boolean} */ -PolyK._PointInTriangle = function (px, py, ax, ay, bx, by, cx, cy) { +PolyK._PointInTriangle = function (px, py, ax, ay, bx, by, cx, cy) +{ var v0x = cx-ax; var v0y = cy-ay; var v1x = bx-ax; @@ -154,6 +164,7 @@ * @private * @return {boolean} */ -PolyK._convex = function (ax, ay, bx, by, cx, cy, sign) { +PolyK._convex = function (ax, ay, bx, by, cx, cy, sign) +{ return ((ay-by)*(cx-bx) + (bx-ax)*(cy-by) >= 0) === sign; }; diff --git a/src/core/utils/index.js b/src/core/utils/index.js index ade9831..bfae7ae 100644 --- a/src/core/utils/index.js +++ b/src/core/utils/index.js @@ -16,7 +16,8 @@ * * @return {number} The next uuid to use. */ - uuid: function () { + uuid: function () + { return ++utils._uid; }, @@ -26,7 +27,8 @@ * @param hex {number} * @return {number[]} An array representing the [R, G, B] of the color. */ - hex2rgb: function (hex, out) { + hex2rgb: function (hex, out) + { out = out || []; out[0] = (hex >> 16 & 0xFF) / 255; @@ -42,7 +44,8 @@ * @param hex {number} * @return {string} The string color. */ - hex2string: function (hex) { + hex2string: function (hex) + { hex = hex.toString(16); hex = '000000'.substr(0, 6 - hex.length) + hex; @@ -55,7 +58,8 @@ * @param rgb {number[]} * @return {number} The color number */ - rgb2hex: function (rgb) { + rgb2hex: function (rgb) + { return ((rgb[0]*255 << 16) + (rgb[1]*255 << 8) + rgb[2]*255); }, @@ -64,8 +68,10 @@ * * @return {boolean} whether they are supported */ - canUseNewCanvasBlendModes: function () { - if (typeof document === 'undefined') { + canUseNewCanvasBlendModes: function () + { + if (typeof document === 'undefined') + { return false; } @@ -93,15 +99,19 @@ * @param number {number} * @return {number} the closest number that is a power of two */ - getNextPowerOfTwo: function (number) { + getNextPowerOfTwo: function (number) + { // see: http://en.wikipedia.org/wiki/Power_of_two#Fast_algorithm_to_check_if_a_positive_number_is_a_power_of_two - if (number > 0 && (number & (number - 1)) === 0) { + if (number > 0 && (number & (number - 1)) === 0) + { return number; } - else { + else + { var result = 1; - while (result < number) { + while (result < number) + { result <<= 1; } @@ -116,7 +126,8 @@ * @param height {number} * @return {boolean} */ - isPowerOfTwo: function (width, height) { + isPowerOfTwo: function (width, height) + { return (width > 0 && (width & (width - 1)) === 0 && height > 0 && (height & (height - 1)) === 0); }, @@ -130,12 +141,15 @@ * @constant * @static */ - sayHello: function (type) { - if (utils._saidHello) { + sayHello: function (type) + { + if (utils._saidHello) + { return; } - if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) { + if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) + { var args = [ '%c %c %c Pixi.js ' + CONST.VERSION + ' - ' + type + ' %c ' + ' %c ' + ' http://www.pixijs.com/ %c %c ♥%c♥%c♥ ', 'background: #ff66a5', @@ -151,7 +165,8 @@ console.log.apply(console, args); //jshint ignore:line } - else if (window.console) { + else if (window.console) + { console.log('Pixi.js ' + CONST.VERSION + ' - ' + type + ' - http://www.pixijs.com/'); //jshint ignore:line } @@ -166,15 +181,19 @@ * @class * @namespace PIXI */ - AjaxRequest: function () { + AjaxRequest: function () + { var activexmodes = ['Msxml2.XMLHTTP.6.0', 'Msxml2.XMLHTTP.3.0', 'Microsoft.XMLHTTP']; //activeX versions to check for in IE - if (window.ActiveXObject) { //Test for support for ActiveXObject in IE first (as XMLHttpRequest in IE7 is broken) - for (var i=0; i= this.textures.length) { + else if (round >= this.textures.length) + { this.gotoAndStop(this.textures.length - 1); - if (this.onComplete) { + if (this.onComplete) + { this.onComplete(); } } @@ -167,10 +182,12 @@ * @static * @param frames {string[]} the array of frames ids the movieclip will use as its texture frames */ -MovieClip.fromFrames = function (frames) { +MovieClip.fromFrames = function (frames) +{ var textures = []; - for (var i = 0; i < frames.length; ++i) { + for (var i = 0; i < frames.length; ++i) + { textures.push(new core.Texture.fromFrame(frames[i])); } @@ -183,10 +200,12 @@ * @static * @param images {string[]} the array of image urls the movieclip will use as its texture frames */ -MovieClip.fromImages = function (images) { +MovieClip.fromImages = function (images) +{ var textures = []; - for (var i = 0; i < images.length; ++i) { + for (var i = 0; i < images.length; ++i) + { textures.push(new core.Texture.fromImage(images[i])); } diff --git a/src/extras/Rope.js b/src/extras/Rope.js index c157ec4..9c87bc0 100644 --- a/src/extras/Rope.js +++ b/src/extras/Rope.js @@ -9,7 +9,8 @@ * @param {Array} points - An array of {Point}. * */ -function Rope(texture, points) { +function Rope(texture, points) +{ Strip.call(this, texture); this.points = points; @@ -31,10 +32,12 @@ * Refreshes * */ -Rope.prototype.refresh = function () { +Rope.prototype.refresh = function () +{ var points = this.points; - if (points.length < 1) { + if (points.length < 1) + { return; } @@ -59,20 +62,23 @@ var total = points.length, point, index, amount; - for (var i = 1; i < total; i++) { + for (var i = 1; i < total; i++) + { point = points[i]; index = i * 4; // time to do some smart drawing! amount = i / (total-1); - if (i%2) { + if (i%2) + { uvs[index] = amount; uvs[index+1] = 0; uvs[index+2] = amount; uvs[index+3] = 1; } - else { + else + { uvs[index] = amount; uvs[index+1] = 0; @@ -95,10 +101,12 @@ * * @private */ -Rope.prototype.updateTransform = function () { +Rope.prototype.updateTransform = function () +{ var points = this.points; - if (points.length < 1) { + if (points.length < 1) + { return; } @@ -113,14 +121,17 @@ var total = points.length, point, index, ratio, perpLength, num; - for (var i = 0; i < total; i++) { + for (var i = 0; i < total; i++) + { point = points[i]; index = i * 4; - if (i < points.length-1) { + if (i < points.length-1) + { nextPoint = points[i+1]; } - else { + else + { nextPoint = point; } @@ -129,7 +140,8 @@ ratio = (1 - (i / (total-1))) * 10; - if (ratio > 1) { + if (ratio > 1) + { ratio = 1; } @@ -157,7 +169,8 @@ * * @param texture {Texture} the texture that will be used */ -Rope.prototype.setTexture = function (texture) { +Rope.prototype.setTexture = function (texture) +{ // stop current texture this.texture = texture; //this.updateFrame = true; diff --git a/src/extras/Strip.js b/src/extras/Strip.js index c5e378f..57691b5 100644 --- a/src/extras/Strip.js +++ b/src/extras/Strip.js @@ -10,7 +10,8 @@ * @param height {number} the height * */ -function Strip(texture) { +function Strip(texture) +{ core.DisplayObjectContainer.call(this); /** @@ -70,9 +71,11 @@ * * @param renderer {WebGLRenderer} */ -Strip.prototype.renderWebGL = function (renderer) { +Strip.prototype.renderWebGL = function (renderer) +{ // if the sprite is not visible or the alpha is 0 then no need to render this element - if (!this.visible || this.alpha <= 0) { + if (!this.visible || this.alpha <= 0) + { return; } @@ -81,7 +84,8 @@ renderer.spriteBatch.stop(); // init! init! - if (!this._vertexBuffer) { + if (!this._vertexBuffer) + { this._initWebGL(renderer); } @@ -96,7 +100,8 @@ //TODO check culling }; -Strip.prototype._initWebGL = function (renderer) { +Strip.prototype._initWebGL = function (renderer) +{ // build the strip! var gl = renderer.gl; @@ -118,7 +123,8 @@ gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this.indices, gl.STATIC_DRAW); }; -Strip.prototype._renderStrip = function (renderer) { +Strip.prototype._renderStrip = function (renderer) +{ var gl = renderer.gl; var projection = renderer.projection, offset = renderer.offset, @@ -137,7 +143,8 @@ gl.uniform2f(shader.offsetVector, -offset.x, -offset.y); gl.uniform1f(shader.alpha, this.worldAlpha); - if (!this.dirty) { + if (!this.dirty) + { gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexBuffer); gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); @@ -150,10 +157,12 @@ gl.activeTexture(gl.TEXTURE0); // check if a texture is dirty.. - if (this.texture.baseTexture._dirty[gl.id]) { + if (this.texture.baseTexture._dirty[gl.id]) + { renderer.updateTexture(this.texture.baseTexture); } - else { + else + { // bind the current texture gl.bindTexture(gl.TEXTURE_2D, this.texture.baseTexture._glTextures[gl.id]); } @@ -163,7 +172,8 @@ } - else { + else + { this.dirty = false; gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexBuffer); @@ -178,10 +188,12 @@ gl.activeTexture(gl.TEXTURE0); // check if a texture is dirty.. - if (this.texture.baseTexture._dirty[gl.id]) { + if (this.texture.baseTexture._dirty[gl.id]) + { renderer.updateTexture(this.texture.baseTexture); } - else { + else + { gl.bindTexture(gl.TEXTURE_2D, this.texture.baseTexture._glTextures[gl.id]); } @@ -203,27 +215,33 @@ * * @param renderer {CanvasRenderer} */ -Strip.prototype.renderCanvas = function (renderer) { +Strip.prototype.renderCanvas = function (renderer) +{ var context = renderer.context; var transform = this.worldTransform; - if (renderer.roundPixels) { + if (renderer.roundPixels) + { context.setTransform(transform.a, transform.b, transform.c, transform.d, transform.tx | 0, transform.ty | 0); } - else { + else + { context.setTransform(transform.a, transform.b, transform.c, transform.d, transform.tx, transform.ty); } - if (this.drawMode === Strip.DrawModes.TRIANGLE_STRIP) { + if (this.drawMode === Strip.DrawModes.TRIANGLE_STRIP) + { this._renderCanvasTriangleStrip(context); } - else { + else + { this._renderCanvasTriangles(context); } }; -Strip.prototype._renderCanvasTriangleStrip = function (context) { +Strip.prototype._renderCanvasTriangleStrip = function (context) +{ // draw triangles!! var vertices = this.vertices; var uvs = this.uvs; @@ -231,14 +249,16 @@ var length = vertices.length / 2; // this.count++; - for (var i = 0; i < length - 2; i++) { + for (var i = 0; i < length - 2; i++) + { // draw some triangles! var index = i * 2; this._renderCanvasDrawTriangle(context, vertices, uvs, index, (index + 2), (index + 4)); } }; -Strip.prototype._renderCanvasTriangles = function (context) { +Strip.prototype._renderCanvasTriangles = function (context) +{ // draw triangles!! var vertices = this.vertices; var uvs = this.uvs; @@ -247,14 +267,16 @@ var length = indices.length; // this.count++; - for (var i = 0; i < length; i += 3) { + for (var i = 0; i < length; i += 3) + { // draw some triangles! var index0 = indices[i] * 2, index1 = indices[i + 1] * 2, index2 = indices[i + 2] * 2; this._renderCanvasDrawTriangle(context, vertices, uvs, index0, index1, index2); } }; -Strip.prototype._renderCanvasDrawTriangle = function (context, vertices, uvs, index0, index1, index2) { +Strip.prototype._renderCanvasDrawTriangle = function (context, vertices, uvs, index0, index1, index2) +{ var textureSource = this.texture.baseTexture.source; var textureWidth = this.texture.width; var textureHeight = this.texture.height; @@ -265,7 +287,8 @@ var u0 = uvs[index0] * textureWidth, u1 = uvs[index1] * textureWidth, u2 = uvs[index2] * textureWidth; var v0 = uvs[index0 + 1] * textureHeight, v1 = uvs[index1 + 1] * textureHeight, v2 = uvs[index2 + 1] * textureHeight; - if (this.canvasPadding > 0) { + if (this.canvasPadding > 0) + { var paddingX = this.canvasPadding / this.worldTransform.a; var paddingY = this.canvasPadding / this.worldTransform.d; var centerX = (x0 + x1 + x2) / 3; @@ -332,7 +355,8 @@ * @param strip {Strip} The Strip to render * @private */ -Strip.prototype.renderStripFlat = function (strip) { +Strip.prototype.renderStripFlat = function (strip) +{ var context = this.context; var vertices = strip.vertices; @@ -340,7 +364,8 @@ // this.count++; context.beginPath(); - for (var i=1; i < length-2; i++) { + for (var i=1; i < length-2; i++) + { // draw some triangles! var index = i*2; @@ -358,7 +383,8 @@ }; /* -Strip.prototype.setTexture = function (texture) { +Strip.prototype.setTexture = function (texture) +{ //TODO SET THE TEXTURES //TODO VISIBILITY @@ -377,7 +403,8 @@ * @private */ -Strip.prototype.onTextureUpdate = function () { +Strip.prototype.onTextureUpdate = function () +{ this.updateFrame = true; }; @@ -387,7 +414,8 @@ * @param matrix {Matrix} the transformation matrix of the sprite * @return {Rectangle} the framing rectangle */ -Strip.prototype.getBounds = function (matrix) { +Strip.prototype.getBounds = function (matrix) +{ var worldTransform = matrix || this.worldTransform; var a = worldTransform.a; @@ -404,7 +432,8 @@ var minY = Infinity; var vertices = this.vertices; - for (var i = 0, n = vertices.length; i < n; i += 2) { + for (var i = 0, n = vertices.length; i < n; i += 2) + { var rawX = vertices[i], rawY = vertices[i + 1]; var x = (a * rawX) + (c * rawY) + tx; var y = (d * rawY) + (b * rawX) + ty; @@ -416,7 +445,8 @@ maxY = y > maxY ? y : maxY; } - if (minX === -Infinity || maxY === Infinity) { + if (minX === -Infinity || maxY === Infinity) + { return core.math.Rectangle.EMPTY; } diff --git a/src/extras/TilingSprite.js b/src/extras/TilingSprite.js index 3ac22df..31da393 100644 --- a/src/extras/TilingSprite.js +++ b/src/extras/TilingSprite.js @@ -10,7 +10,8 @@ * @param width {number} the width of the tiling sprite * @param height {number} the height of the tiling sprite */ -function TilingSprite(texture, width, height) { +function TilingSprite(texture, width, height) +{ core.Sprite.call( this, texture); /** @@ -86,10 +87,12 @@ * @memberof TilingSprite# */ width: { - get: function () { + get: function () + { return this._width; }, - set: function (value) { + set: function (value) + { this._width = value; } }, @@ -101,20 +104,25 @@ * @memberof TilingSprite# */ height: { - get: function () { + get: function () + { return this._height; }, - set: function (value) { + set: function (value) + { this._height = value; } }, texture: { - get: function () { + get: function () + { return this._texture; }, - set: function (value) { - if (this._texture === value) { + set: function (value) + { + if (this._texture === value) + { return; } @@ -130,51 +138,61 @@ * * @param renderer {WebGLRenderer} */ -TilingSprite.prototype.renderWebGL = function (renderer) { - if (!this.visible || this.alpha <= 0) { +TilingSprite.prototype.renderWebGL = function (renderer) +{ + if (!this.visible || this.alpha <= 0) + { return; } var i, j; - if (this._mask) { + if (this._mask) + { renderer.spriteBatch.stop(); renderer.maskManager.pushMask(this.mask, renderer); renderer.spriteBatch.start(); } - if (this._filters) { + if (this._filters) + { renderer.spriteBatch.flush(); renderer.filterManager.pushFilter(this._filterBlock); } - if (!this.tilingTexture || this.refreshTexture) { + if (!this.tilingTexture || this.refreshTexture) + { this.generateTilingTexture(true); - if (this.tilingTexture && this.tilingTexture.needsUpdate) { + if (this.tilingTexture && this.tilingTexture.needsUpdate) + { //TODO - tweaking renderer.updateTexture(this.tilingTexture.baseTexture); this.tilingTexture.needsUpdate = false; // this.tilingTexture._uvs = null; } } - else { + else + { renderer.spriteBatch.renderTilingSprite(this); } // simple render children! - for (i=0,j=this.children.length; i= 0 && index <= this.children.length) { - if (child.parent) { + if (index >= 0 && index <= this.children.length) + { + if (child.parent) + { child.parent.removeChild(child); } @@ -154,7 +173,8 @@ return child; } - else { + else + { throw new Error(child + 'addChildAt: The index '+ index +' supplied is out of bounds ' + this.children.length); } }; @@ -165,15 +185,18 @@ * @param child {DisplayObject} * @param child2 {DisplayObject} */ -DisplayObjectContainer.prototype.swapChildren = function (child, child2) { - if (child === child2) { +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) { + if (index1 < 0 || index2 < 0) + { throw new Error('swapChildren: Both the supplied DisplayObjects must be a child of the caller.'); } @@ -187,10 +210,12 @@ * @param child {DisplayObject} The DisplayObject instance to identify * @return {Number} The index position of the child display object to identify */ -DisplayObjectContainer.prototype.getChildIndex = function (child) { +DisplayObjectContainer.prototype.getChildIndex = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { throw new Error('The supplied DisplayObject must be a child of the caller'); } @@ -203,8 +228,10 @@ * @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 */ -DisplayObjectContainer.prototype.setChildIndex = function (child, index) { - if (index < 0 || index >= this.children.length) { +DisplayObjectContainer.prototype.setChildIndex = function (child, index) +{ + if (index < 0 || index >= this.children.length) + { throw new Error('The supplied index is out of bounds'); } @@ -220,8 +247,10 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child at the given index, if any. */ -DisplayObjectContainer.prototype.getChildAt = function (index) { - if (index < 0 || index >= this.children.length) { +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'); } @@ -234,10 +263,12 @@ * @param child {DisplayObject} The DisplayObject to remove * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChild = function (child) { +DisplayObjectContainer.prototype.removeChild = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { return; } @@ -250,7 +281,8 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChildAt = function (index) { +DisplayObjectContainer.prototype.removeChildAt = function (index) +{ var child = this.getChildAt(index); child.parent = null; @@ -265,24 +297,29 @@ * @param beginIndex {Number} The beginning position. Default value is 0. * @param endIndex {Number} The ending position. Default value is size of the container. */ -DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) { +DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) +{ var begin = beginIndex || 0; var end = typeof endIndex === 'number' ? endIndex : this.children.length; var range = end - begin; - if (range > 0 && range <= end) { + if (range > 0 && range <= end) + { var removed = this.children.splice(begin, range); - for (var i = 0; i < removed.length; ++i) { + for (var i = 0; i < removed.length; ++i) + { removed[i].parent = null; } return removed; } - else if (range === 0 && this.children.length === 0) { + else if (range === 0 && this.children.length === 0) + { return []; } - else { + else + { throw new RangeError('removeChildren: numeric values are outside the acceptable range.'); } }; @@ -291,7 +328,8 @@ * Generates and updates the cached sprite for this object. * */ -DisplayObjectContainer.prototype.updateCachedSprite = function () { +DisplayObjectContainer.prototype.updateCachedSprite = function () +{ this._generateCachedSprite(); }; @@ -304,7 +342,8 @@ * @param renderer {CanvasRenderer|WebGLRenderer} The renderer used to generate the texture. * @return {Texture} a texture of the graphics object */ -DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) { +DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) +{ var bounds = this.getLocalBounds(); var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0, renderer, scaleMode, resolution); @@ -322,18 +361,22 @@ * * @private */ -DisplayObjectContainer.prototype.updateTransform = function () { - if (!this.visible) { +DisplayObjectContainer.prototype.updateTransform = function () +{ + if (!this.visible) + { return; } this.displayObjectUpdateTransform(); - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { return; } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } }; @@ -346,8 +389,10 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getBounds = function () { - if (this.children.length === 0) { +DisplayObjectContainer.prototype.getBounds = function () +{ + if (this.children.length === 0) + { return math.Rectangle.EMPTY; } @@ -365,10 +410,12 @@ var childVisible = false; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -386,7 +433,8 @@ maxY = maxY > childMaxY ? maxY : childMaxY; } - if (!childVisible) { + if (!childVisible) + { return math.Rectangle.EMPTY; } @@ -407,12 +455,14 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getLocalBounds = function () { +DisplayObjectContainer.prototype.getLocalBounds = function () +{ var matrixCache = this.worldTransform; this.worldTransform = math.Matrix.IDENTITY; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } @@ -428,13 +478,16 @@ * * @param renderer {WebGLRenderer} The renderer */ -DisplayObjectContainer.prototype.renderWebGL = function (renderer) { +DisplayObjectContainer.prototype.renderWebGL = function (renderer) +{ // if the object is not visible or the alpha is 0 then no need to render this element - if (!this.visible || this.alpha <= 0) { + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } @@ -442,14 +495,17 @@ var i, j; // do a quick check to see if this element has a mask or a filter. - if (this._mask || this._filters) { + if (this._mask || this._filters) + { // push filter first as we need to ensure the stencil buffer is correct for any masking - if (this._filters) { + if (this._filters) + { renderer.spriteBatch.flush(); renderer.filterManager.pushFilter(this._filterBlock); } - if (this._mask) { + if (this._mask) + { renderer.spriteBatch.stop(); renderer.maskManager.pushMask(this.mask, renderer); renderer.spriteBatch.start(); @@ -459,36 +515,42 @@ this._renderWebGL(renderer); // now loop through the children and make sure they get rendered - for (i = 0, j = this.children.length; i < j; i++) { + for (i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderWebGL(renderer); } // time to stop the sprite batch as either a mask element or a filter draw will happen next renderer.spriteBatch.stop(); - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(this._mask, renderer); } - if (this._filters) { + if (this._filters) + { renderer.filterManager.popFilter(); } renderer.spriteBatch.start(); } - else { + else + { this._renderWebGL(renderer); // simple render children! - for (i = 0, j = this.children.length; i < j; ++i) { + for (i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderWebGL(renderer); } } }; -DisplayObjectContainer.prototype._renderWebGL = function (renderer) { +DisplayObjectContainer.prototype._renderWebGL = function (renderer) +{ // this is where content itself gets renderd.. @@ -499,25 +561,31 @@ * * @param renderer {CanvasRenderer} The renderer */ -DisplayObjectContainer.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0) { +DisplayObjectContainer.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -528,13 +596,16 @@ * @param renderer {WebGLRenderer|CanvasRenderer} The renderer * @private */ -DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) { +DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) +{ this._cachedSprite.worldAlpha = this.worldAlpha; - if (renderer.gl) { + if (renderer.gl) + { this._cachedSprite.renderWebGL(renderer); } - else { + else + { this._cachedSprite.renderCanvas(renderer); } }; @@ -544,10 +615,12 @@ * * @private */ -DisplayObjectContainer.prototype._generateCachedSprite = function () { +DisplayObjectContainer.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { // TODO - RenderTexture now *requires* a renderer instance, so this is like broken // because `renderer` isn't actually in scope here :P var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0); @@ -555,7 +628,8 @@ this._cachedSprite = new Sprite(renderTexture); this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.texture.resize(bounds.width | 0, bounds.height | 0); } @@ -580,8 +654,10 @@ * * @private */ -DisplayObjectContainer.prototype._destroyCachedSprite = function () { - if (!this._cachedSprite) { +DisplayObjectContainer.prototype._destroyCachedSprite = function () +{ + if (!this._cachedSprite) + { return; } diff --git a/src/core/display/Sprite.js b/src/core/display/Sprite.js index 707da24..5862aef 100644 --- a/src/core/display/Sprite.js +++ b/src/core/display/Sprite.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param texture {Texture} The texture for this sprite */ -function Sprite(texture) { +function Sprite(texture) +{ DisplayObjectContainer.call(this); /** @@ -85,12 +86,14 @@ this.texture = texture || Texture.EMPTY; } -Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) { +Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) +{ DisplayObjectContainer.prototype.destroy.call(this); this.anchor = null; - if (destroyTexture) { + if (destroyTexture) + { this._texture.destroy(destroyBaseTexture); } @@ -111,10 +114,12 @@ * @memberof Sprite# */ width: { - get: function () { + get: function () + { return this.scale.x * this.texture.frame.width; }, - set: function (value) { + set: function (value) + { this.scale.x = value / this.texture.frame.width; this._width = value; } @@ -127,10 +132,12 @@ * @memberof Sprite# */ height: { - get: function () { + get: function () + { return this.scale.y * this.texture.frame.height; }, - set: function (value) { + set: function (value) + { this.scale.y = value / this.texture.frame.height; this._height = value; } @@ -143,23 +150,29 @@ * @memberof Sprite# */ texture: { - get: function () { + get: function () + { return this._texture; }, - set: function (value) { - if (this._texture === value) { + set: function (value) + { + if (this._texture === value) + { return; } this._texture = value; this.cachedTint = 0xFFFFFF; - if (value) { + if (value) + { // wait for the texture to load - if (value.baseTexture.hasLoaded) { + if (value.baseTexture.hasLoaded) + { this._onTextureUpdate(); } - else { + else + { value.once('update', this._onTextureUpdate.bind(this)); } } @@ -172,18 +185,22 @@ * * @private */ -Sprite.prototype._onTextureUpdate = function () { +Sprite.prototype._onTextureUpdate = function () +{ // so if _width is 0 then width was not set.. - if (this._width) { + if (this._width) + { this.scale.x = this._width / this.texture.frame.width; } - if (this._height) { + if (this._height) + { this.scale.y = this._height / this.texture.frame.height; } }; -Sprite.prototype._renderWebGL = function (renderer) { +Sprite.prototype._renderWebGL = function (renderer) +{ // this is where content gets renderd.. // watch this space for a little render state manager.. @@ -197,7 +214,8 @@ * @param matrix {Matrix} the transformation matrix of the sprite * @return {Rectangle} the framing rectangle */ -Sprite.prototype.getBounds = function (matrix) { +Sprite.prototype.getBounds = function (matrix) +{ var width = this.texture.frame.width; var height = this.texture.frame.height; @@ -224,11 +242,13 @@ if(b === 0 && c === 0) { // scale may be negative! - if (a < 0) { + if (a < 0) + { a *= -1; } - if (d < 0) { + if (d < 0) + { d *= -1; } @@ -293,28 +313,34 @@ * * @param renderer {CanvasRenderer} The renderer */ -Sprite.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) { +Sprite.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) + { return; } - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; renderer.context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } // Ignore null sources - if (this.texture.valid) { + if (this.texture.valid) + { var resolution = this.texture.baseTexture.resolution / renderer.resolution; renderer.context.globalAlpha = this.worldAlpha; // If smoothingEnabled is supported and we need to change the smoothing property for this texture - if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) { + if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) + { renderer.scaleMode = this.texture.baseTexture.scaleMode; renderer.context[renderer.smoothProperty] = (renderer.scaleMode === CONST.scaleModes.LINEAR); } @@ -324,7 +350,8 @@ var dy = (this.texture.trim ? this.texture.trim.y : 0) - (this.anchor.y * this.texture.trim.height); // Allow for pixel rounding - if (renderer.roundPixels) { + if (renderer.roundPixels) + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -337,7 +364,8 @@ dx = dx | 0; dy = dy | 0; } - else { + else + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -348,8 +376,10 @@ ); } - if (this.tint !== 0xFFFFFF) { - if (this.cachedTint !== this.tint) { + if (this.tint !== 0xFFFFFF) + { + if (this.cachedTint !== this.tint) + { this.cachedTint = this.tint; // TODO clean up caching - how to clean up the caches? @@ -368,7 +398,8 @@ this.texture.crop.height / resolution ); } - else { + else + { renderer.context.drawImage( this.texture.baseTexture.source, this.texture.crop.x, @@ -383,11 +414,13 @@ } } - for (var i = 0, j = this.children.length; i < j; i++) { + for (var i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -402,10 +435,12 @@ * @param frameId {String} The frame Id of the texture in the cache * @return {Sprite} A new Sprite using a texture from the texture cache matching the frameId */ -Sprite.fromFrame = function (frameId) { +Sprite.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache' + this); } @@ -420,6 +455,7 @@ * @param imageId {String} The image url of the texture * @return {Sprite} A new Sprite using a texture from the texture cache matching the image id */ -Sprite.fromImage = function (imageId, crossorigin, scaleMode) { +Sprite.fromImage = function (imageId, crossorigin, scaleMode) +{ return new Sprite(Texture.fromImage(imageId, crossorigin, scaleMode)); }; diff --git a/src/core/display/SpriteBatch.js b/src/core/display/SpriteBatch.js index 3187777..c196fef 100644 --- a/src/core/display/SpriteBatch.js +++ b/src/core/display/SpriteBatch.js @@ -12,7 +12,8 @@ * ```js * var container = new SpriteBatch(); * - * for(var i = 0; i < 100; ++i) { + * for(var i = 0; i < 100; ++i) + * { * var sprite = new PIXI.Sprite.fromImage("myImage.png"); * container.addChild(sprite); * } @@ -25,7 +26,8 @@ */ //TODO RENAME to PARTICLE CONTAINER? -function SpriteBatch() { +function SpriteBatch() +{ DisplayObjectContainer.call(this); } @@ -38,7 +40,8 @@ * * @private */ -SpriteBatch.prototype.updateTransform = function () { +SpriteBatch.prototype.updateTransform = function () +{ // TODO don't need to! this.displayObjectUpdateTransform(); // PIXI.DisplayObjectContainer.prototype.updateTransform.call( this ); @@ -50,8 +53,10 @@ * @param renderer {WebGLRenderer} The webgl renderer * @private */ -SpriteBatch.prototype.renderWebGL = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderWebGL = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -71,8 +76,10 @@ * @param renderer {CanvasRenderer} The canvas renderer * @private */ -SpriteBatch.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -84,10 +91,12 @@ this.displayObjectUpdateTransform(); - for (var i = 0; i < this.children.length; ++i) { + for (var i = 0; i < this.children.length; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -95,9 +104,11 @@ context.globalAlpha = this.worldAlpha * child.alpha; - if (child.rotation % (Math.PI * 2) === 0) { + if (child.rotation % (Math.PI * 2) === 0) + { // this is the fastest way to optimise! - if rotation is 0 then we can avoid any kind of setTransform call - if (isRotated) { + if (isRotated) + { context.setTransform( transform.a, transform.b, @@ -122,8 +133,10 @@ frame.height * child.scale.y ); } - else { - if (!isRotated) { + else + { + if (!isRotated) + { isRotated = true; } @@ -131,7 +144,8 @@ var childTransform = child.worldTransform; - if (renderer.roundPixels) { + if (renderer.roundPixels) + { context.setTransform( childTransform.a, childTransform.b, @@ -141,7 +155,8 @@ childTransform.ty | 0 ); } - else { + else + { context.setTransform( childTransform.a, childTransform.b, diff --git a/src/core/index.js b/src/core/index.js index 3954b6f..eb4a82b 100644 --- a/src/core/index.js +++ b/src/core/index.js @@ -58,11 +58,13 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRenderer: function (width, height, options, noWebGL) { + autoDetectRenderer: function (width, height, options, noWebGL) + { width = width || 800; height = height || 600; - if (!noWebGL && require('webgl-enabled')()) { + if (!noWebGL && require('webgl-enabled')()) + { return new core.WebGLRenderer(width, height, options); } @@ -87,7 +89,8 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRecommendedRenderer: function (width, height, options) { + autoDetectRecommendedRenderer: function (width, height, options) + { var isAndroid = /Android/i.test(navigator.userAgent); return core.autoDetectRenderer(width, height, options, isAndroid); diff --git a/src/core/math/Matrix.js b/src/core/math/Matrix.js index c2f87e2..2ff4848 100644 --- a/src/core/math/Matrix.js +++ b/src/core/math/Matrix.js @@ -10,7 +10,8 @@ * @class * @namespace PIXI */ -function Matrix() { +function Matrix() +{ /** * @member {number} * @default 1 @@ -63,7 +64,8 @@ * * @param array {number[]} The array that the matrix will be populated from. */ -Matrix.prototype.fromArray = function (array) { +Matrix.prototype.fromArray = function (array) +{ this.a = array[0]; this.b = array[1]; this.c = array[3]; @@ -78,14 +80,17 @@ * @param transpose {boolean} Whether we need to transpose the matrix or not * @return {number[]} the newly created array which contains the matrix */ -Matrix.prototype.toArray = function (transpose) { - if (!this.array) { +Matrix.prototype.toArray = function (transpose) +{ + if (!this.array) + { this.array = new Float32Array(9); } var array = this.array; - if (transpose) { + if (transpose) + { array[0] = this.a; array[1] = this.b; array[2] = 0; @@ -96,7 +101,8 @@ array[7] = this.ty; array[8] = 1; } - else { + else + { array[0] = this.a; array[1] = this.c; array[2] = this.tx; @@ -119,7 +125,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, transformed through this matrix */ -Matrix.prototype.apply = function (pos, newPos) { +Matrix.prototype.apply = function (pos, newPos) +{ newPos = newPos || new Point(); newPos.x = this.a * pos.x + this.c * pos.y + this.tx; @@ -136,7 +143,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, inverse-transformed through this matrix */ -Matrix.prototype.applyInverse = function (pos, newPos) { +Matrix.prototype.applyInverse = function (pos, newPos) +{ newPos = newPos || new Point(); var id = 1 / (this.a * this.d + this.c * -this.b); @@ -154,7 +162,8 @@ * @param {number} y * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.translate = function (x, y) { +Matrix.prototype.translate = function (x, y) +{ this.tx += x; this.ty += y; @@ -168,7 +177,8 @@ * @param {number} y The amount to scale vertically * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.scale = function (x, y) { +Matrix.prototype.scale = function (x, y) +{ this.a *= x; this.d *= y; this.c *= x; @@ -186,7 +196,8 @@ * @param {number} angle - The angle in radians. * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.rotate = function (angle) { +Matrix.prototype.rotate = function (angle) +{ var cos = Math.cos( angle ); var sin = Math.sin( angle ); @@ -210,7 +221,8 @@ * @param {Matrix} matrix * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.append = function (matrix) { +Matrix.prototype.append = function (matrix) +{ var a1 = this.a; var b1 = this.b; var c1 = this.c; @@ -232,7 +244,8 @@ * * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.identity = function () { +Matrix.prototype.identity = function () +{ this.a = 1; this.b = 0; this.c = 0; diff --git a/src/core/math/Point.js b/src/core/math/Point.js index 7565b2d..632f346 100644 --- a/src/core/math/Point.js +++ b/src/core/math/Point.js @@ -7,7 +7,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -function Point(x, y) { +function Point(x, y) +{ /** * @member {number} * @default 0 @@ -29,7 +30,8 @@ * * @return {Point} a copy of the point */ -Point.prototype.clone = function () { +Point.prototype.clone = function () +{ return new Point(this.x, this.y); }; @@ -40,7 +42,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -Point.prototype.set = function (x, y) { +Point.prototype.set = function (x, y) +{ this.x = x || 0; this.y = y || ( (y !== 0) ? this.x : 0 ) ; }; diff --git a/src/core/math/shapes/Circle.js b/src/core/math/shapes/Circle.js index 69cfdc9..4d76efc 100644 --- a/src/core/math/shapes/Circle.js +++ b/src/core/math/shapes/Circle.js @@ -10,7 +10,8 @@ * @param y {number} The Y coordinate of the center of this circle * @param radius {number} The radius of the circle */ -function Circle(x, y, radius) { +function Circle(x, y, radius) +{ /** * @member {number} * @default 0 @@ -46,7 +47,8 @@ * @method clone * @return {Circle} a copy of the Circle */ -Circle.prototype.clone = function () { +Circle.prototype.clone = function () +{ return new Circle(this.x, this.y, this.radius); }; @@ -58,8 +60,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Circle */ -Circle.prototype.contains = function (x, y) { - if (this.radius <= 0) { +Circle.prototype.contains = function (x, y) +{ + if (this.radius <= 0) + { return false; } @@ -79,6 +83,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Circle.prototype.getBounds = function () { +Circle.prototype.getBounds = function () +{ return new Rectangle(this.x - this.radius, this.y - this.radius, this.radius * 2, this.radius * 2); }; diff --git a/src/core/math/shapes/Ellipse.js b/src/core/math/shapes/Ellipse.js index 4f2d066..fefd01a 100644 --- a/src/core/math/shapes/Ellipse.js +++ b/src/core/math/shapes/Ellipse.js @@ -11,7 +11,8 @@ * @param width {number} The half width of this ellipse * @param height {number} The half height of this ellipse */ -function Ellipse(x, y, width, height) { +function Ellipse(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -53,7 +54,8 @@ * @method clone * @return {Ellipse} a copy of the ellipse */ -Ellipse.prototype.clone = function () { +Ellipse.prototype.clone = function () +{ return new Ellipse(this.x, this.y, this.width, this.height); }; @@ -65,8 +67,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coords are within this ellipse */ -Ellipse.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Ellipse.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } @@ -86,6 +90,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Ellipse.prototype.getBounds = function () { +Ellipse.prototype.getBounds = function () +{ return new Rectangle(this.x - this.width, this.y - this.height, this.width, this.height); }; diff --git a/src/core/math/shapes/Polygon.js b/src/core/math/shapes/Polygon.js index ae89148..fea6d37 100644 --- a/src/core/math/shapes/Polygon.js +++ b/src/core/math/shapes/Polygon.js @@ -10,16 +10,20 @@ * arguments passed can be flat x,y values e.g. `new Polygon(x,y, x,y, x,y, ...)` where `x` and `y` are * Numbers. */ -function Polygon(points) { +function Polygon(points) +{ //if points isn't an array, use arguments as the array - if (!(points instanceof Array)) { + if (!(points instanceof Array)) + { points = Array.prototype.slice.call(arguments); } //if this is a flat array of numbers, convert it to points - if (points[0] instanceof Point) { + if (points[0] instanceof Point) + { var p = []; - for (var i = 0, il = points.length; i < il; i++) { + for (var i = 0, il = points.length; i < il; i++) + { p.push(points[i].x, points[i].y); } @@ -51,7 +55,8 @@ * * @return {Polygon} a copy of the polygon */ -Polygon.prototype.clone = function () { +Polygon.prototype.clone = function () +{ return new Polygon(this.points.slice()); }; @@ -62,19 +67,22 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this polygon */ -Polygon.prototype.contains = function (x, y) { +Polygon.prototype.contains = function (x, y) +{ var inside = false; // use some raycasting to test hits // https://github.com/substack/point-in-polygon/blob/master/index.js var length = this.points.length / 2; - for (var i = 0, j = length - 1; i < length; j = i++) { + for (var i = 0, j = length - 1; i < length; j = i++) + { var xi = this.points[i * 2], yi = this.points[i * 2 + 1], xj = this.points[j * 2], yj = this.points[j * 2 + 1], intersect = ((yi > y) !== (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi); - if (intersect) { + if (intersect) + { inside = !inside; } } diff --git a/src/core/math/shapes/Rectangle.js b/src/core/math/shapes/Rectangle.js index 16ac62a..4008b68 100644 --- a/src/core/math/shapes/Rectangle.js +++ b/src/core/math/shapes/Rectangle.js @@ -10,7 +10,8 @@ * @param width {number} The overall width of this rectangle * @param height {number} The overall height of this rectangle */ -function Rectangle(x, y, width, height) { +function Rectangle(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -60,7 +61,8 @@ * * @return {Rectangle} a copy of the rectangle */ -Rectangle.prototype.clone = function () { +Rectangle.prototype.clone = function () +{ return new Rectangle(this.x, this.y, this.width, this.height); }; @@ -71,13 +73,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rectangle */ -Rectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Rectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/math/shapes/RoundedRectangle.js b/src/core/math/shapes/RoundedRectangle.js index 27d286e..7bf6411 100644 --- a/src/core/math/shapes/RoundedRectangle.js +++ b/src/core/math/shapes/RoundedRectangle.js @@ -11,7 +11,8 @@ * @param height {number} The overall height of this rounded rectangle * @param radius {number} Controls the radius of the rounded corners */ -function RoundedRectangle(x, y, width, height, radius) { +function RoundedRectangle(x, y, width, height, radius) +{ /** * @member {number} * @default 0 @@ -58,7 +59,8 @@ * * @return {RoundedRectangle} a copy of the rounded rectangle */ -RoundedRectangle.prototype.clone = function () { +RoundedRectangle.prototype.clone = function () +{ return new RoundedRectangle(this.x, this.y, this.width, this.height, this.radius); }; @@ -69,13 +71,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rounded Rectangle */ -RoundedRectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +RoundedRectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/primitives/Graphics.js b/src/core/primitives/Graphics.js index 261c534..e902d2a 100644 --- a/src/core/primitives/Graphics.js +++ b/src/core/primitives/Graphics.js @@ -16,7 +16,8 @@ * @extends DisplayObjectContainer * @namespace PIXI */ -function Graphics() { +function Graphics() +{ DisplayObjectContainer.call(this); this.renderable = true; @@ -154,16 +155,20 @@ * @private */ cacheAsBitmap: { - get: function () { + get: function () + { return this._cacheAsBitmap; }, - set: function (value) { + set: function (value) + { this._cacheAsBitmap = value; - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._generateCachedSprite(); } - else { + else + { this.destroyCachedSprite(); this.dirty = true; } @@ -176,7 +181,8 @@ * * @return {Graphics} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ var clone = new Graphics(); clone.renderable = this.renderable; @@ -192,7 +198,8 @@ clone.cachedSpriteDirty = this.cachedSpriteDirty; // copy graphics data - for (var i = 0; i < this.graphicsData.length; ++i) { + for (var i = 0; i < this.graphicsData.length; ++i) + { clone.graphicsData.push(this.graphicsData.clone()); } @@ -211,17 +218,21 @@ * @param alpha {number} alpha of the line to draw, will update the objects stored style * @return {Graphics} */ -Graphics.prototype.lineStyle = function (lineWidth, color, alpha) { +Graphics.prototype.lineStyle = function (lineWidth, color, alpha) +{ this.lineWidth = lineWidth || 0; this.lineColor = color || 0; this.lineAlpha = (arguments.length < 3) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length) + { // halfway through a line? start a new one! this.drawShape( new math.Polygon( this.currentPath.shape.points.slice(-2) )); } - else { + else + { // otherwise its empty so lets just set the line properties this.currentPath.lineWidth = this.lineWidth; this.currentPath.lineColor = this.lineColor; @@ -239,7 +250,8 @@ * @param y {number} the Y coordinate to move to * @return {Graphics} */ -Graphics.prototype.moveTo = function (x, y) { +Graphics.prototype.moveTo = function (x, y) +{ this.drawShape(new math.Polygon([x,y])); return this; @@ -253,7 +265,8 @@ * @param y {number} the Y coordinate to draw to * @return {Graphics} */ -Graphics.prototype.lineTo = function (x, y) { +Graphics.prototype.lineTo = function (x, y) +{ this.currentPath.shape.points.push(x, y); this.dirty = true; @@ -270,13 +283,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -285,7 +302,8 @@ n = 20, points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { this.moveTo(0, 0); } @@ -293,7 +311,8 @@ var fromY = points[points.length-1]; var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; xa = fromX + ( (cpX - fromX) * j ); @@ -319,13 +338,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -342,7 +365,8 @@ var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; dt = (1 - j); @@ -373,13 +397,17 @@ * @param radius {number} The radius of the arc * @return {Graphics} */ -Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points.push(x1, y1); } } - else { + else + { this.moveTo(x1, y1); } @@ -392,12 +420,15 @@ b2 = x2 - x1, mm = Math.abs(a1 * b2 - b1 * a2); - if (mm < 1.0e-8 || radius === 0) { - if (points[points.length-2] !== x1 || points[points.length-1] !== y1) { + if (mm < 1.0e-8 || radius === 0) + { + if (points[points.length-2] !== x1 || points[points.length-1] !== y1) + { points.push(x1, y1); } } - else { + else + { var dd = a1 * a1 + b1 * b1, cc = a2 * a2 + b2 * b2, tt = a1 * a2 + b1 * b2, @@ -433,42 +464,51 @@ * @param anticlockwise {boolean} Optional. Specifies whether the drawing should be counterclockwise or clockwise. False is default, and indicates clockwise, while true indicates counter-clockwise. * @return {Graphics} */ -Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) { +Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) +{ var startX = cx + Math.cos(startAngle) * radius; var startY = cy + Math.sin(startAngle) * radius; var points; // TODO - This if-else makes no sense. It uses currentPath in the else where it doesn't exist... - if (this.currentPath) { + if (this.currentPath) + { points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { points.push(startX, startY); } - else if (points[points.length-2] !== startX || points[points.length-1] !== startY) { + else if (points[points.length-2] !== startX || points[points.length-1] !== startY) + { points.push(startX, startY); } } - else { + else + { this.moveTo(startX, startY); points = this.currentPath.shape.points; } - if (startAngle === endAngle) { + if (startAngle === endAngle) + { return this; } - if (!anticlockwise && endAngle <= startAngle) { + if (!anticlockwise && endAngle <= startAngle) + { endAngle += Math.PI * 2; } - else if (anticlockwise && startAngle <= endAngle) { + else if (anticlockwise && startAngle <= endAngle) + { startAngle += Math.PI * 2; } var sweep = anticlockwise ? (startAngle - endAngle) *-1 : (endAngle - startAngle); var segs = (Math.abs(sweep)/ (Math.PI * 2)) * 40; - if (sweep === 0) { + if (sweep === 0) + { return this; } @@ -482,7 +522,8 @@ var remainder = ( segMinus % 1 ) / segMinus; - for (var i = 0; i <= segMinus; ++i) { + for (var i = 0; i <= segMinus; ++i) + { var real = i + remainder * i; var angle = ((theta) + startAngle + (theta2 * real)); @@ -506,13 +547,16 @@ * @param alpha {number} the alpha of the fill * @return {Graphics} */ -Graphics.prototype.beginFill = function (color, alpha) { +Graphics.prototype.beginFill = function (color, alpha) +{ this.filling = true; this.fillColor = color || 0; this.fillAlpha = (alpha === undefined) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length <= 2) + { this.currentPath.fill = this.filling; this.currentPath.fillColor = this.fillColor; this.currentPath.fillAlpha = this.fillAlpha; @@ -526,7 +570,8 @@ * * @return {Graphics} */ -Graphics.prototype.endFill = function () { +Graphics.prototype.endFill = function () +{ this.filling = false; this.fillColor = null; this.fillAlpha = 1; @@ -542,7 +587,8 @@ * @param height {number} The height of the rectangle * @return {Graphics} */ -Graphics.prototype.drawRect = function ( x, y, width, height ) { +Graphics.prototype.drawRect = function ( x, y, width, height ) +{ this.drawShape(new math.Rectangle(x,y, width, height)); return this; @@ -556,7 +602,8 @@ * @param height {number} The height of the rectangle * @param radius {number} Radius of the rectangle corners */ -Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) { +Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) +{ this.drawShape(new math.RoundedRectangle(x, y, width, height, radius)); return this; @@ -570,7 +617,8 @@ * @param radius {number} The radius of the circle * @return {Graphics} */ -Graphics.prototype.drawCircle = function (x, y, radius) { +Graphics.prototype.drawCircle = function (x, y, radius) +{ this.drawShape(new math.Circle(x,y, radius)); return this; @@ -585,7 +633,8 @@ * @param height {number} The half height of the ellipse * @return {Graphics} */ -Graphics.prototype.drawEllipse = function (x, y, width, height) { +Graphics.prototype.drawEllipse = function (x, y, width, height) +{ this.drawShape(new math.Ellipse(x, y, width, height)); return this; @@ -597,8 +646,10 @@ * @param path {Array} The path data used to construct the polygon. * @return {Graphics} */ -Graphics.prototype.drawPolygon = function (path) { - if (!(path instanceof Array)) { +Graphics.prototype.drawPolygon = function (path) +{ + if (!(path instanceof Array)) + { path = Array.prototype.slice.call(arguments); } @@ -612,7 +663,8 @@ * * @return {Graphics} */ -Graphics.prototype.clear = function () { +Graphics.prototype.clear = function () +{ this.lineWidth = 0; this.filling = false; @@ -631,7 +683,8 @@ * @param scaleMode {number} Should be one of the scaleMode consts * @return {Texture} a texture of the graphics object */ -Graphics.prototype.generateTexture = function (resolution, scaleMode) { +Graphics.prototype.generateTexture = function (resolution, scaleMode) +{ resolution = resolution || 1; var bounds = this.getBounds(); @@ -655,17 +708,21 @@ * * @param renderer {WebGLRenderer} */ -Graphics.prototype._renderWebGL = function (renderer) { +Graphics.prototype._renderWebGL = function (renderer) +{ // if the sprite is not visible or the alpha is 0 then no need to render this element - if (this.isMask === true) { + if (this.isMask === true) + { return; } // this code may still be needed so leaving for now.. - // + // /* - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture on the gpu too! @@ -681,17 +738,24 @@ return; } - */ - - // check if the webgl graphic needs to be updated - if (this.glDirty) { - this.dirty = true; - this.glDirty = false; - } + else */ - renderer.setObjectRendererer(renderer.graphicsRenderer); - renderer.graphicsRenderer.render(this); + renderer.spriteBatch.stop(); + renderer.blendModeManager.setBlendMode(this.blendMode); + // check blend mode + renderer.blendModeManager.setBlendMode( this.blendMode ); + + // check if the webgl graphic needs to be updated + if (this.glDirty) + { + this.dirty = true; + this.glDirty = false; + } + + WebGLGraphics.renderGraphics(this, renderer); + + renderer.spriteBatch.start(); }; /** @@ -700,14 +764,18 @@ * @param renderer {CanvasRenderer} * @private */ -Graphics.prototype.renderCanvas = function (renderer) { +Graphics.prototype.renderCanvas = function (renderer) +{ // 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.isMask === true) { + if (!this.visible || this.alpha <= 0 || this.isMask === true) + { return; } - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture @@ -723,16 +791,19 @@ return; } - else { + else + { var context = renderer.context; var transform = this.worldTransform; - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } @@ -748,11 +819,13 @@ CanvasGraphics.renderGraphics(this, context); - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } } @@ -763,13 +836,16 @@ * * @return {Rectangle} the rectangular bounding area */ -Graphics.prototype.getBounds = function (matrix) { +Graphics.prototype.getBounds = function (matrix) +{ // return an empty object if the item is a mask! - if (this.isMask) { + if (this.isMask) + { return math.Rectangle.EMPTY; } - if (this.dirty) { + if (this.dirty) + { this.updateLocalBounds(); this.glDirty = true; @@ -841,23 +917,27 @@ * Update the bounds of the object * */ -Graphics.prototype.updateLocalBounds = function () { +Graphics.prototype.updateLocalBounds = function () +{ var minX = Infinity; var maxX = -Infinity; var minY = Infinity; var maxY = -Infinity; - if (this.graphicsData.length) { + if (this.graphicsData.length) + { var shape, points, x, y, w, h; - for (var i = 0; i < this.graphicsData.length; i++) { + for (var i = 0; i < this.graphicsData.length; i++) + { var data = this.graphicsData[i]; var type = data.type; var lineWidth = data.lineWidth; shape = data.shape; - if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) { + if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) + { x = shape.x - lineWidth/2; y = shape.y - lineWidth/2; w = shape.width + lineWidth; @@ -869,7 +949,8 @@ minY = y < minY ? y : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.CIRC) { + else if (type === CONST.SHAPES.CIRC) + { x = shape.x; y = shape.y; w = shape.radius + lineWidth/2; @@ -881,7 +962,8 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.ELIP) { + else if (type === CONST.SHAPES.ELIP) + { x = shape.x; y = shape.y; w = shape.width + lineWidth/2; @@ -893,11 +975,13 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else { + else + { // POLY points = shape.points; - for (var j = 0; j < points.length; j += 2) { + for (var j = 0; j < points.length; j += 2) + { x = points[j]; y = points[j+1]; @@ -910,7 +994,8 @@ } } } - else { + else + { minX = 0; maxX = 0; minY = 0; @@ -931,10 +1016,12 @@ * * @private */ -Graphics.prototype._generateCachedSprite = function () { +Graphics.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { var canvasBuffer = new CanvasBuffer(bounds.width, bounds.height); var texture = Texture.fromCanvas(canvasBuffer.canvas); @@ -943,7 +1030,8 @@ this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.buffer.resize(bounds.width, bounds.height); } @@ -968,7 +1056,8 @@ * * @private */ -Graphics.prototype.updateCachedSpriteTexture = function () { +Graphics.prototype.updateCachedSpriteTexture = function () +{ var cachedSprite = this._cachedSprite; var texture = cachedSprite.texture; var canvas = cachedSprite.buffer.canvas; @@ -989,7 +1078,8 @@ * Destroys a previous cached sprite. * */ -Graphics.prototype.destroyCachedSprite = function () { +Graphics.prototype.destroyCachedSprite = function () +{ this._cachedSprite.texture.destroy(true); // let the gc collect the unused sprite @@ -1003,10 +1093,13 @@ * @param {Circle|Rectangle|Ellipse|Line|Polygon} shape The Shape object to draw. * @return {GraphicsData} The generated GraphicsData object. */ -Graphics.prototype.drawShape = function (shape) { - if (this.currentPath) { +Graphics.prototype.drawShape = function (shape) +{ + if (this.currentPath) + { // check current path! - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath.shape.points.length <= 2) + { this.graphicsData.pop(); } } @@ -1017,7 +1110,8 @@ this.graphicsData.push(data); - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { data.shape.closed = this.filling; this.currentPath = data; } diff --git a/src/core/primitives/GraphicsData.js b/src/core/primitives/GraphicsData.js index 99decbe..788f6f2 100644 --- a/src/core/primitives/GraphicsData.js +++ b/src/core/primitives/GraphicsData.js @@ -4,7 +4,8 @@ * @class * @namespace PIXI */ -function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) { +function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) +{ this.lineWidth = lineWidth; this.lineColor = lineColor; this.lineAlpha = lineAlpha; @@ -27,7 +28,8 @@ * * @return {GraphicsData} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ return new GraphicsData( this.lineWidth, this.lineColor, diff --git a/src/core/renderers/canvas/CanvasRenderer.js b/src/core/renderers/canvas/CanvasRenderer.js index 15a0978..7aebd44 100644 --- a/src/core/renderers/canvas/CanvasRenderer.js +++ b/src/core/renderers/canvas/CanvasRenderer.js @@ -17,17 +17,22 @@ * @param [options.resolution=1] {number} the resolution of the renderer retina would be 2 * @param [options.clearBeforeRender=true] {boolean} This sets if the CanvasRenderer will clear the canvas or not before the new render pass. */ -function CanvasRenderer(width, height, options) { +function CanvasRenderer(width, height, options) +{ utils.sayHello('Canvas'); - if (options) { - for (var i in CONST.defaultRenderOptions) { - if (typeof options[i] === 'undefined') { + if (options) + { + for (var i in CONST.defaultRenderOptions) + { + if (typeof options[i] === 'undefined') + { options[i] = CONST.defaultRenderOptions[i]; } } } - else { + else + { options = CONST.defaultRenderOptions; } @@ -156,19 +161,24 @@ this.smoothProperty = null; - if (this.context.imageSmoothingEnabled) { + if (this.context.imageSmoothingEnabled) + { this.smoothProperty = 'imageSmoothingEnabled'; } - else if (this.context.webkitImageSmoothingEnabled) { + else if (this.context.webkitImageSmoothingEnabled) + { this.smoothProperty = 'webkitImageSmoothingEnabled'; } - else if (this.context.mozImageSmoothingEnabled) { + else if (this.context.mozImageSmoothingEnabled) + { this.smoothProperty = 'mozImageSmoothingEnabled'; } - else if (this.context.oImageSmoothingEnabled) { + else if (this.context.oImageSmoothingEnabled) + { this.smoothProperty = 'oImageSmoothingEnabled'; } - else if (this.context.msImageSmoothingEnabled) { + else if (this.context.msImageSmoothingEnabled) + { this.smoothProperty = 'msImageSmoothingEnabled'; } @@ -193,10 +203,12 @@ * @memberof CanvasRenderer# */ backgroundColor: { - get: function () { + get: function () + { return this._backgroundColor; }, - set: function (val) { + set: function (val) + { this._backgroundColor = val; this._backgroundColorString = utils.hex2string(val); } @@ -208,7 +220,8 @@ * * @param object {DisplayObject} the object to be rendered */ -CanvasRenderer.prototype.render = function (object) { +CanvasRenderer.prototype.render = function (object) +{ object.updateTransform(); this.context.setTransform(1,0,0,1,0,0); @@ -218,16 +231,20 @@ this.currentBlendMode = CONST.blendModes.NORMAL; this.context.globalCompositeOperation = this.blendModes[CONST.blendModes.NORMAL]; - if (navigator.isCocoonJS && this.view.screencanvas) { + if (navigator.isCocoonJS && this.view.screencanvas) + { this.context.fillStyle = 'black'; this.context.clear(); } - if (this.clearBeforeRender) { - if (this.transparent) { + if (this.clearBeforeRender) + { + if (this.transparent) + { this.context.clearRect(0, 0, this.width, this.height); } - else { + else + { this.context.fillStyle = this._backgroundColorString; this.context.fillRect(0, 0, this.width , this.height); } @@ -241,8 +258,10 @@ * * @param [removeView=false] {boolean} Removes the Canvas element from the DOM. */ -CanvasRenderer.prototype.destroy = function (removeView) { - if (removeView && this.view.parent) { +CanvasRenderer.prototype.destroy = function (removeView) +{ + if (removeView && this.view.parent) + { this.view.parent.removeChild(this.view); } @@ -257,14 +276,16 @@ * @param width {number} the new width of the canvas view * @param height {number} the new height of the canvas view */ -CanvasRenderer.prototype.resize = function (width, height) { +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) { + if (this.autoResize) + { this.view.style.width = this.width / this.resolution + 'px'; this.view.style.height = this.height / this.resolution + 'px'; } @@ -276,7 +297,8 @@ * @param displayObject {DisplayObject} The displayObject to render * @private */ -CanvasRenderer.prototype.renderDisplayObject = function (displayObject) { +CanvasRenderer.prototype.renderDisplayObject = function (displayObject) +{ displayObject.renderCanvas(this); }; @@ -285,11 +307,14 @@ * * @private */ -CanvasRenderer.prototype._mapBlendModes = function () { - if (!this.blendModes) { +CanvasRenderer.prototype._mapBlendModes = function () +{ + if (!this.blendModes) + { this.blendModes = {}; - if (utils.canUseNewCanvasBlendModes()) { + if (utils.canUseNewCanvasBlendModes()) + { this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? this.blendModes[CONST.blendModes.MULTIPLY] = 'multiply'; @@ -308,7 +333,8 @@ this.blendModes[CONST.blendModes.COLOR] = 'color'; this.blendModes[CONST.blendModes.LUMINOSITY] = 'luminosity'; } - else { + else + { // this means that the browser does not support the cool new blend modes in canvas 'cough' ie 'cough' this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? diff --git a/src/core/renderers/canvas/utils/CanvasBuffer.js b/src/core/renderers/canvas/utils/CanvasBuffer.js index ebe5d47..b183a66 100644 --- a/src/core/renderers/canvas/utils/CanvasBuffer.js +++ b/src/core/renderers/canvas/utils/CanvasBuffer.js @@ -6,7 +6,8 @@ * @param width {number} the width for the newly created canvas * @param height {number} the height for the newly created canvas */ -function CanvasBuffer(width, height) { +function CanvasBuffer(width, height) +{ /** * The Canvas object that belongs to this CanvasBuffer. * @@ -36,10 +37,12 @@ * @memberof CanvasBuffer# */ width: { - get: function () { + get: function () + { return this.canvas.width; }, - set: function (val) { + set: function (val) + { this.canvas.width = val; } }, @@ -50,10 +53,12 @@ * @memberof CanvasBuffer# */ height: { - get: function () { + get: function () + { return this.canvas.height; }, - set: function (val) { + set: function (val) + { this.canvas.height = val; } } @@ -64,7 +69,8 @@ * * @private */ -CanvasBuffer.prototype.clear = function () { +CanvasBuffer.prototype.clear = function () +{ this.context.setTransform(1, 0, 0, 1, 0, 0); this.context.clearRect(0,0, this.canvas.width, this.canvas.height); }; @@ -75,7 +81,8 @@ * @param width {number} the new width of the canvas * @param height {number} the new height of the canvas */ -CanvasBuffer.prototype.resize = function (width, height) { +CanvasBuffer.prototype.resize = function (width, height) +{ this.canvas.width = width; this.canvas.height = height; }; diff --git a/src/core/renderers/canvas/utils/CanvasGraphics.js b/src/core/renderers/canvas/utils/CanvasGraphics.js index c7eaa2a..3f2a91f 100644 --- a/src/core/renderers/canvas/utils/CanvasGraphics.js +++ b/src/core/renderers/canvas/utils/CanvasGraphics.js @@ -13,15 +13,18 @@ * @param graphics {Graphics} the actual graphics object to render * @param context {CanvasRenderingContext2D} the 2d drawing method of the canvas */ -CanvasGraphics.renderGraphics = function (graphics, context) { +CanvasGraphics.renderGraphics = function (graphics, context) +{ var worldAlpha = graphics.worldAlpha; - if (graphics.dirty) { + if (graphics.dirty) + { this.updateGraphicsTint(graphics); graphics.dirty = false; } - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; @@ -30,69 +33,82 @@ context.lineWidth = data.lineWidth; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { context.beginPath(); var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } - if (shape.closed) { + if (shape.closed) + { context.lineTo(points[0], points[1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fillRect(shape.x, shape.y, shape.width, shape.height); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.strokeRect(shape.x, shape.y, shape.width, shape.height); } } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.beginPath(); context.arc(shape.x, shape.y, shape.radius,0,2*Math.PI); context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas var w = shape.width * 2; @@ -119,18 +135,21 @@ context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; var width = shape.width; @@ -152,13 +171,15 @@ context.quadraticCurveTo(rx, ry, rx, ry + radius); context.closePath(); - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); @@ -174,45 +195,54 @@ * @param graphics {Graphics} the graphics which will be used as a mask * @param context {CanvasRenderingContext2D} the context 2d method of the canvas */ -CanvasGraphics.renderGraphicsMask = function (graphics, context) { +CanvasGraphics.renderGraphicsMask = function (graphics, context) +{ var len = graphics.graphicsData.length; - if (len === 0) { + if (len === 0) + { return; } context.beginPath(); - for (var i = 0; i < len; i++) { + for (var i = 0; i < len; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { context.rect(shape.x, shape.y, shape.width, shape.height); context.closePath(); } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.arc(shape.x, shape.y, shape.radius, 0, 2 * Math.PI); context.closePath(); } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas @@ -237,7 +267,8 @@ context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); context.closePath(); } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; @@ -262,8 +293,10 @@ } }; -CanvasGraphics.updateGraphicsTint = function (graphics) { - if (graphics.tint === 0xFFFFFF) { +CanvasGraphics.updateGraphicsTint = function (graphics) +{ + if (graphics.tint === 0xFFFFFF) + { return; } @@ -271,7 +304,8 @@ var tintG = (graphics.tint >> 8 & 0xFF) / 255; var tintB = (graphics.tint & 0xFF)/ 255; - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var fillColor = data.fillColor | 0; diff --git a/src/core/renderers/canvas/utils/CanvasMaskManager.js b/src/core/renderers/canvas/utils/CanvasMaskManager.js index e04a733..9827d36 100644 --- a/src/core/renderers/canvas/utils/CanvasMaskManager.js +++ b/src/core/renderers/canvas/utils/CanvasMaskManager.js @@ -6,7 +6,8 @@ * @class * @namespace PIXI */ -function CanvasMaskManager() {} +function CanvasMaskManager() +{} CanvasMaskManager.prototype.constructor = CanvasMaskManager; module.exports = CanvasMaskManager; @@ -17,7 +18,8 @@ * @param maskData {object} the maskData that will be pushed * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.pushMask = function (maskData, renderer) { +CanvasMaskManager.prototype.pushMask = function (maskData, renderer) +{ renderer.context.save(); var cacheAlpha = maskData.alpha; @@ -45,6 +47,7 @@ * * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.popMask = function (renderer) { +CanvasMaskManager.prototype.popMask = function (renderer) +{ renderer.context.restore(); }; diff --git a/src/core/renderers/canvas/utils/CanvasTinter.js b/src/core/renderers/canvas/utils/CanvasTinter.js index 17e0529..d2fb1bc 100644 --- a/src/core/renderers/canvas/utils/CanvasTinter.js +++ b/src/core/renderers/canvas/utils/CanvasTinter.js @@ -14,7 +14,8 @@ * @param color {number} the color to use to tint the sprite with * @return {HTMLCanvasElement} The tinted canvas */ -CanvasTinter.getTintedTexture = function (sprite, color) { +CanvasTinter.getTintedTexture = function (sprite, color) +{ var texture = sprite.texture; color = CanvasTinter.roundColor(color); @@ -23,7 +24,8 @@ texture.tintCache = texture.tintCache || {}; - if (texture.tintCache[stringColor]) { + if (texture.tintCache[stringColor]) + { return texture.tintCache[stringColor]; } @@ -33,14 +35,16 @@ //CanvasTinter.tintWithPerPixel(texture, stringColor, canvas); CanvasTinter.tintMethod(texture, color, canvas); - if (CanvasTinter.convertTintToImage) { + if (CanvasTinter.convertTintToImage) + { // is this better? var tintImage = new Image(); tintImage.src = canvas.toDataURL(); texture.tintCache[stringColor] = tintImage; } - else { + else + { texture.tintCache[stringColor] = canvas; // if we are not converting the texture to an image then we need to lose the reference to the canvas CanvasTinter.canvas = null; @@ -56,7 +60,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithMultiply = function (texture, color, canvas) { +CanvasTinter.tintWithMultiply = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -104,7 +109,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithOverlay = function (texture, color, canvas) { +CanvasTinter.tintWithOverlay = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -139,7 +145,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithPerPixel = function (texture, color, canvas) { +CanvasTinter.tintWithPerPixel = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -167,7 +174,8 @@ var pixels = pixelData.data; - for (var i = 0; i < pixels.length; i += 4) { + for (var i = 0; i < pixels.length; i += 4) + { pixels[i+0] *= r; pixels[i+1] *= g; pixels[i+2] *= b; @@ -181,7 +189,8 @@ * * @param color {number} the color to round, should be a hex color */ -CanvasTinter.roundColor = function (color) { +CanvasTinter.roundColor = function (color) +{ var step = CanvasTinter.cacheStepsPerColorChannel; var rgbValues = utils.hex2rgb(color); diff --git a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js index 9f2f89a..35edbaf 100644 --- a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js +++ b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLBlendModeManager(renderer) { +function WebGLBlendModeManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -23,8 +24,10 @@ * * @param blendMode {number} the blendMode, should be a Pixi const, such as BlendModes.ADD */ -WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) { - if (this.currentBlendMode === blendMode) { +WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) +{ + if (this.currentBlendMode === blendMode) + { return false; } diff --git a/src/core/renderers/webgl/managers/WebGLFilterManager.js b/src/core/renderers/webgl/managers/WebGLFilterManager.js index 1179258..2dac048 100644 --- a/src/core/renderers/webgl/managers/WebGLFilterManager.js +++ b/src/core/renderers/webgl/managers/WebGLFilterManager.js @@ -7,7 +7,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLFilterManager(renderer) { +function WebGLFilterManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -32,7 +33,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.texturePool.length = 0; self.initShaderBuffers(); }); @@ -46,7 +48,8 @@ * @param renderer {WebGLRenderer} * @param buffer {ArrayBuffer} */ -WebGLFilterManager.prototype.begin = function (buffer) { +WebGLFilterManager.prototype.begin = function (buffer) +{ this.defaultShader = this.renderer.shaderManager.defaultShader; this.width = this.renderer.projection.x * 2; @@ -60,7 +63,8 @@ * * @param filterBlock {object} the filter that will be pushed to the current filter stack */ -WebGLFilterManager.prototype.pushFilter = function (filterBlock) { +WebGLFilterManager.prototype.pushFilter = function (filterBlock) +{ var gl = this.renderer.gl; var projection = this.renderer.projection; @@ -78,10 +82,12 @@ this.offsetY += filterBlock._filterArea.y; var texture = this.texturePool.pop(); - if (!texture) { + if (!texture) + { texture = new FilterTexture(this.renderer.gl, this.width, this.height); } - else { + else + { texture.resize(this.width, this.height); } @@ -98,29 +104,35 @@ var localX = filterArea.x, localY = filterArea.y; - if (filterArea.x < 0) { + if (filterArea.x < 0) + { filterArea.width += filterArea.x; filterArea.x = 0; } - if (filterArea.y < 0) { + if (filterArea.y < 0) + { filterArea.height += filterArea.y; filterArea.y = 0; } - if (localX + filterArea.width > this.width) { + if (localX + filterArea.width > this.width) + { filterArea.width = this.width - localX; } - if (localY + filterArea.height > this.height) { + if (localY + filterArea.height > this.height) + { filterArea.height = this.height - localY; } - if (filterArea.width < 0) { + if (filterArea.width < 0) + { filterArea.width = 0; } - if (filterArea.height < 0) { + if (filterArea.height < 0) + { filterArea.height = 0; } @@ -154,7 +166,8 @@ * Removes the last filter from the filter stack and doesn't return it. * */ -WebGLFilterManager.prototype.popFilter = function () { +WebGLFilterManager.prototype.popFilter = function () +{ var gl = this.renderer.gl; var filterBlock = this.filterStack.pop(); @@ -163,7 +176,8 @@ var projection = this.renderer.projection; var offset = this.renderer.offset; - if (filterBlock.filterPasses.length > 1) { + if (filterBlock.filterPasses.length > 1) + { gl.viewport(0, 0, filterArea.width, filterArea.height); gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); @@ -193,7 +207,8 @@ var inputTexture = texture; var outputTexture = this.texturePool.pop(); - if (!outputTexture) { + if (!outputTexture) + { outputTexture = new FilterTexture(this.renderer.gl, this.width, this.height); } outputTexture.resize(this.width, this.height); @@ -204,7 +219,8 @@ gl.disable(gl.BLEND); - for (var i = 0; i < filterBlock.filterPasses.length-1; i++) { + for (var i = 0; i < filterBlock.filterPasses.length-1; i++) + { var filterPass = filterBlock.filterPasses[i]; gl.bindFramebuffer(gl.FRAMEBUFFER, outputTexture.frameBuffer ); @@ -243,10 +259,12 @@ var buffer = this.buffer; // time to render the filters texture to the previous scene - if (this.filterStack.length === 0) { + if (this.filterStack.length === 0) + { gl.colorMask(true, true, true, true);//this.transparent); } - else { + else + { var currentFilter = this.filterStack[this.filterStack.length-1]; filterArea = currentFilter._filterArea; @@ -332,13 +350,15 @@ * @param width {number} the horizontal range of the filter * @param height {number} the vertical range of the filter */ -WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) { +WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) +{ // use program var gl = this.renderer.gl; var shader = filter.shaders[gl.id]; - if (!shader) { + if (!shader) + { shader = new Shader(gl); shader.fragmentSrc = filter.fragmentSrc; @@ -356,7 +376,8 @@ gl.uniform2f(shader.projectionVector, width/2, -height/2); gl.uniform2f(shader.offsetVector, 0,0); - if (filter.uniforms.dimensions) { + 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]; @@ -386,7 +407,8 @@ * Initialises the shader buffers. * */ -WebGLFilterManager.prototype.initShaderBuffers = function () { +WebGLFilterManager.prototype.initShaderBuffers = function () +{ var gl = this.renderer.gl; // create some buffers @@ -432,7 +454,8 @@ * Destroys the filter and removes it from the filter stack. * */ -WebGLFilterManager.prototype.destroy = function () { +WebGLFilterManager.prototype.destroy = function () +{ var gl = this.renderer.gl; this.filterStack = null; @@ -441,7 +464,8 @@ this.offsetY = 0; // destroy textures - for (var i = 0; i < this.texturePool.length; i++) { + for (var i = 0; i < this.texturePool.length; i++) + { this.texturePool[i].destroy(); } diff --git a/src/core/renderers/webgl/managers/WebGLManager.js b/src/core/renderers/webgl/managers/WebGLManager.js index 9d47b5c..c30cd51 100644 --- a/src/core/renderers/webgl/managers/WebGLManager.js +++ b/src/core/renderers/webgl/managers/WebGLManager.js @@ -3,7 +3,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLManager(renderer) { +function WebGLManager(renderer) +{ /** * The renderer this manager works for. * @@ -15,6 +16,7 @@ WebGLManager.prototype.constructor = WebGLManager; module.exports = WebGLManager; -WebGLManager.prototype.destroy = function () { +WebGLManager.prototype.destroy = function () +{ this.renderer = null; }; diff --git a/src/core/renderers/webgl/managers/WebGLMaskManager.js b/src/core/renderers/webgl/managers/WebGLMaskManager.js index 2f90b64..e568812 100644 --- a/src/core/renderers/webgl/managers/WebGLMaskManager.js +++ b/src/core/renderers/webgl/managers/WebGLMaskManager.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLMaskManager(renderer) { +function WebGLMaskManager(renderer) +{ WebGLManager.call(this, renderer); } @@ -19,12 +20,15 @@ * * @param maskData {any[]} */ -WebGLMaskManager.prototype.pushMask = function (maskData) { - if (maskData.dirty) { +WebGLMaskManager.prototype.pushMask = function (maskData) +{ + if (maskData.dirty) + { WebGLGraphics.updateGraphics(maskData, this.renderer.gl); } - if (!maskData._webGL[this.renderer.gl.id].data.length) { + if (!maskData._webGL[this.renderer.gl.id].data.length) + { return; } @@ -36,6 +40,7 @@ * * @param maskData {any[]} */ -WebGLMaskManager.prototype.popMask = function (maskData) { +WebGLMaskManager.prototype.popMask = function (maskData) +{ this.renderer.stencilManager.popStencil(maskData, maskData._webGL[this.renderer.gl.id].data[0], this.renderer); }; diff --git a/src/core/renderers/webgl/managers/WebGLShaderManager.js b/src/core/renderers/webgl/managers/WebGLShaderManager.js index fef071c..90c6477 100644 --- a/src/core/renderers/webgl/managers/WebGLShaderManager.js +++ b/src/core/renderers/webgl/managers/WebGLShaderManager.js @@ -10,7 +10,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLShaderManager(renderer) { +function WebGLShaderManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -28,7 +29,8 @@ */ this.tempAttribState = []; - for (var i = 0; i < this.maxAttibs; i++) { + for (var i = 0; i < this.maxAttibs; i++) + { this.attribState[i] = false; } @@ -66,7 +68,8 @@ // listen for context and update necessary shaders var self = this; - this.renderer.on('context', function (event) { + this.renderer.on('context', function (event) + { var gl = event.data; // this shader is used for rendering primitives @@ -97,29 +100,36 @@ * * @param attribs {Array} attribs */ -WebGLShaderManager.prototype.setAttribs = function (attribs) { +WebGLShaderManager.prototype.setAttribs = function (attribs) +{ // reset temp state var i; - for (i = 0; i < this.tempAttribState.length; i++) { + for (i = 0; i < this.tempAttribState.length; i++) + { this.tempAttribState[i] = false; } // set the new attribs - for (var a in attribs) { + for (var a in attribs) + { this.tempAttribState[attribs[a]] = true; } var gl = this.renderer.gl; - for (i = 0; i < this.attribState.length; i++) { - if (this.attribState[i] !== this.tempAttribState[i]) { + for (i = 0; i < this.attribState.length; i++) + { + if (this.attribState[i] !== this.tempAttribState[i]) + { this.attribState[i] = this.tempAttribState[i]; - if (this.attribState[i]) { + if (this.attribState[i]) + { gl.enableVertexAttribArray(i); } - else { + else + { gl.disableVertexAttribArray(i); } } @@ -131,8 +141,10 @@ * * @param shader {Any} */ -WebGLShaderManager.prototype.setShader = function (shader) { - if (this._currentId === shader.uuid) { +WebGLShaderManager.prototype.setShader = function (shader) +{ + if (this._currentId === shader.uuid) + { return false; } @@ -150,7 +162,8 @@ * Destroys this object. * */ -WebGLShaderManager.prototype.destroy = function () { +WebGLShaderManager.prototype.destroy = function () +{ this.attribState = null; this.tempAttribState = null; diff --git a/src/core/renderers/webgl/managers/WebGLStencilManager.js b/src/core/renderers/webgl/managers/WebGLStencilManager.js index 9ec6398..4cb0134 100644 --- a/src/core/renderers/webgl/managers/WebGLStencilManager.js +++ b/src/core/renderers/webgl/managers/WebGLStencilManager.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLStencilManager(renderer) { +function WebGLStencilManager(renderer) +{ WebGLManager.call(this, renderer); this.stencilStack = []; @@ -24,12 +25,14 @@ * @param graphics {Graphics} * @param webGLData {any[]} */ -WebGLStencilManager.prototype.pushStencil = function (graphics, webGLData) { +WebGLStencilManager.prototype.pushStencil = function (graphics, webGLData) +{ var gl = this.renderer.gl; this.bindGraphics(graphics, webGLData, this.renderer); - if (this.stencilStack.length === 0) { + if (this.stencilStack.length === 0) + { gl.enable(gl.STENCIL_TEST); gl.clear(gl.STENCIL_BUFFER_BIT); this.reverse = true; @@ -47,14 +50,17 @@ // draw the triangle strip! - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } @@ -62,31 +68,38 @@ // draw a quad to increment.. gl.drawElements(gl.TRIANGLE_FAN, 4, gl.UNSIGNED_SHORT, ( webGLData.indices.length - 4 ) * 2 ); - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); } this.reverse = !this.reverse; } - else { - if (!this.reverse) { + else + { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } - else { + 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) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); } } @@ -103,7 +116,8 @@ * @param graphics {Graphics} * @param webGLData {Array} */ -WebGLStencilManager.prototype.bindGraphics = function (graphics, webGLData) { +WebGLStencilManager.prototype.bindGraphics = function (graphics, webGLData) +{ //if (this._currentGraphics === graphics)return; this._currentGraphics = graphics; @@ -114,7 +128,8 @@ offset = this.renderer.offset, shader;// = this.renderer.shaderManager.primitiveShader; - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { shader = this.renderer.shaderManager.complexPrimitiveShader; this.renderer.shaderManager.setShader(shader); @@ -141,7 +156,8 @@ // set the index buffer! gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, webGLData.indexBuffer); } - else { + else + { //this.renderer.shaderManager.activatePrimitiveShader(); shader = this.renderer.shaderManager.primitiveShader; this.renderer.shaderManager.setShader( shader ); @@ -154,7 +170,7 @@ gl.uniform2f(shader.uniforms.offsetVector._location, -offset.x, -offset.y); gl.uniform3fv(shader.uniforms.tint._location, utils.hex2rgb(graphics.tint)); - + gl.uniform1f(shader.uniforms.alpha._location, graphics.worldAlpha); @@ -172,19 +188,22 @@ * @param graphics {Graphics} * @param webGLData {Array} */ -WebGLStencilManager.prototype.popStencil = function (graphics, webGLData) { +WebGLStencilManager.prototype.popStencil = function (graphics, webGLData) +{ var gl = this.renderer.gl; this.stencilStack.pop(); this.count--; - if (this.stencilStack.length === 0) { + if (this.stencilStack.length === 0) + { // the stack is empty! gl.disable(gl.STENCIL_TEST); } - else { + else + { var level = this.count; @@ -192,14 +211,17 @@ gl.colorMask(false, false, false, false); - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { this.reverse = !this.reverse; - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } @@ -213,31 +235,38 @@ // draw the triangle strip! gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); - if (!this.reverse) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); } } - else { + else + { // console.log("<<>>") - if (!this.reverse) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } - else { + 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) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); } } @@ -253,7 +282,8 @@ * Destroys the mask stack. * */ -WebGLStencilManager.prototype.destroy = function () { +WebGLStencilManager.prototype.destroy = function () +{ this.renderer = null; this.stencilStack = null; }; diff --git a/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js b/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js index 913ba5e..1ea7d19 100644 --- a/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js +++ b/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function ComplexPrimitiveShader(gl) { +function ComplexPrimitiveShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -24,7 +25,8 @@ 'uniform float flipY;', 'varying vec4 vColor;', - 'void main(void) {', + '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);', @@ -37,7 +39,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = vColor;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/FastShader.js b/src/core/renderers/webgl/shaders/FastShader.js index bd2e29a..2e5e060 100644 --- a/src/core/renderers/webgl/shaders/FastShader.js +++ b/src/core/renderers/webgl/shaders/FastShader.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function FastShader(gl) { +function FastShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -28,7 +29,8 @@ 'const vec2 center = vec2(-1.0, 1.0);', - 'void main(void) {', + 'void main(void) + {', ' vec2 v;', ' vec2 sv = aVertexPosition * aScale;', ' v.x = (sv.x) * cos(aRotation) - (sv.y) * sin(aRotation);', @@ -49,7 +51,8 @@ 'uniform sampler2D uSampler;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/PrimitiveShader.js b/src/core/renderers/webgl/shaders/PrimitiveShader.js index 6f25409..a25f54f 100644 --- a/src/core/renderers/webgl/shaders/PrimitiveShader.js +++ b/src/core/renderers/webgl/shaders/PrimitiveShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function PrimitiveShader(gl) { +function PrimitiveShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -23,7 +24,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + '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);', @@ -36,7 +38,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = vColor;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/Shader.js b/src/core/renderers/webgl/shaders/Shader.js index f8964f5..fd75ef5 100644 --- a/src/core/renderers/webgl/shaders/Shader.js +++ b/src/core/renderers/webgl/shaders/Shader.js @@ -6,7 +6,8 @@ * @param [fragmentSrc] {string} The source of the fragment shader. * @param [vertexSrc] {string} The source of the vertex shader. */ -function Shader(gl, vertexSrc, fragmentSrc, customUniforms, customAttributes) { +function Shader(gl, vertexSrc, fragmentSrc, customUniforms, customAttributes) +{ /** * @member {number} * @readonly @@ -33,7 +34,8 @@ dimensions: { type: '4f', value: new Float32Array(4) } }; - for (var u in customUniforms) { + for (var u in customUniforms) + { this.uniforms[u] = customUniforms[u]; } @@ -43,7 +45,8 @@ aColor: 0 }; - for (var a in customAttributes) { + for (var a in customAttributes) + { this.attributes[a] = customAttributes[a]; } @@ -66,7 +69,8 @@ 'const vec2 center = vec2(-1.0, 1.0);', - 'void main(void) {', + 'void main(void) + {', ' gl_Position = vec4( ((aVertexPosition + offsetVector) / projectionVector) + center , 0.0, 1.0);', ' vTextureCoord = aTextureCoord;', ' vColor = vec4(aColor.rgb * aColor.a, aColor.a);', @@ -85,7 +89,8 @@ 'uniform sampler2D uSampler;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;', '}' ].join('\n'); @@ -96,7 +101,8 @@ Shader.prototype.constructor = Shader; module.exports = Shader; -Shader.prototype.init = function () { +Shader.prototype.init = function () +{ this.compile(); this.gl.useProgram(this.program); @@ -105,14 +111,18 @@ this.cacheAttributeLocations(Object.keys(this.attributes)); }; -Shader.prototype.cacheUniformLocations = function (keys) { - for (var i = 0; i < keys.length; ++i) { +Shader.prototype.cacheUniformLocations = function (keys) +{ + for (var i = 0; i < keys.length; ++i) + { this.uniforms[keys[i]]._location = this.gl.getUniformLocation(this.program, keys[i]); } }; -Shader.prototype.cacheAttributeLocations = function (keys) { - for (var i = 0; i < keys.length; ++i) { +Shader.prototype.cacheAttributeLocations = function (keys) +{ + for (var i = 0; i < keys.length; ++i) + { this.attributes[keys[i]] = this.gl.getAttribLocation(this.program, keys[i]); } @@ -124,14 +134,16 @@ // 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.attributes.aColor === -1) { + // if (this.attributes.aColor === -1) + { // this.attributes.aColor = 2; // } // End worst hack eva // }; -Shader.prototype.compile = function () { +Shader.prototype.compile = function () +{ var gl = this.gl; var glVertShader = this._glCompile(gl.VERTEX_SHADER, this.vertexSrc); @@ -144,13 +156,15 @@ gl.linkProgram(program); // if linking fails, then log and cleanup - if (!gl.getProgramParameter(program, gl.LINK_STATUS)) { + if (!gl.getProgramParameter(program, gl.LINK_STATUS)) + { window.console.error('Pixi.js Error: Could not initialize shader.'); window.console.error('gl.VALIDATE_STATUS', gl.getProgramParameter(program, gl.VALIDATE_STATUS)); window.console.error('gl.getError()', gl.getError()); // if there is a program info log, log it - if (gl.getProgramInfoLog(program) !== '') { + if (gl.getProgramInfoLog(program) !== '') + { window.console.warn('Pixi.js Warning: gl.getProgramInfoLog()', gl.getProgramInfoLog(program)); } @@ -165,18 +179,21 @@ return (this.program = program); }; -Shader.prototype.syncUniforms = function () { +Shader.prototype.syncUniforms = function () +{ var gl = this.gl; this.textureCount = 1; - for (var key in this.uniforms) { + for (var key in this.uniforms) + { var uniform = this.uniforms[key], location = uniform._location, value = uniform.value, i, il; - switch (uniform.type) { + switch (uniform.type) + { // single int value case 'i': case '1i': @@ -282,7 +299,8 @@ // a Color Value case 'c': - if (typeof value === 'number') { + if (typeof value === 'number') + { value = utils.hex2rgb(value); } @@ -311,11 +329,13 @@ // array of 2D Point objects case 'v2v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(2 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 2] = value[i].x; uniform._array[i * 2 + 1] = value[i].y; } @@ -325,11 +345,13 @@ // array of 3D Point objects case 'v3v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(3 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 3] = value[i].x; uniform._array[i * 3 + 1] = value[i].y; uniform._array[i * 3 + 2] = value[i].z; @@ -341,11 +363,13 @@ // array of 4D Point objects case 'v4v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(4 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 4] = value[i].x; uniform._array[i * 4 + 1] = value[i].y; uniform._array[i * 4 + 2] = value[i].z; @@ -359,7 +383,8 @@ // PIXI.Texture case 't': case 'sampler2D': - if (!uniform.value || !uniform.value.baseTexture || !uniform.value.baseTexture.hasLoaded) { + if (!uniform.value || !uniform.value.baseTexture || !uniform.value.baseTexture.hasLoaded) + { break; } @@ -376,7 +401,8 @@ this.textureCount++; // initialize the texture if we haven't yet - if (!uniform._init) { + if (!uniform._init) + { this.initSampler2D(uniform); uniform._init = true; @@ -394,11 +420,13 @@ * Initialises a Sampler2D uniform (which may only be available later on after initUniforms once the texture has loaded) * */ -Shader.prototype.initSampler2D = function (uniform) { +Shader.prototype.initSampler2D = function (uniform) +{ var gl = this.gl; // Extended texture data - if (uniform.textureData) { + if (uniform.textureData) + { var data = uniform.textureData; // GLTexture = mag linear, min linear_mipmap_linear, wrap repeat + gl.generateMipmap(gl.TEXTURE_2D); @@ -417,14 +445,16 @@ var wrapT = (data.wrapT) ? data.wrapT : gl.CLAMP_TO_EDGE; var format = (data.luminance) ? gl.LUMINANCE : gl.RGBA; - if (data.repeat) { + if (data.repeat) + { wrapS = gl.REPEAT; wrapT = gl.REPEAT; } gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, !!data.flipY); - if (data.width) { + if (data.width) + { var width = (data.width) ? data.width : 512; var height = (data.height) ? data.height : 2; var border = (data.border) ? data.border : 0; @@ -432,7 +462,8 @@ // 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 { + 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); } @@ -448,7 +479,8 @@ * Destroys the shader. * */ -Shader.prototype.destroy = function () { +Shader.prototype.destroy = function () +{ this.gl.deleteProgram(this.program); this.gl = null; @@ -459,13 +491,15 @@ this.fragmentSrc = null; }; -Shader.prototype._glCompile = function (type, src) { +Shader.prototype._glCompile = function (type, src) +{ var shader = this.gl.createShader(type); this.gl.shaderSource(shader, src); this.gl.compileShader(shader); - if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) { + if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) + { window.console.log(this.gl.getShaderInfoLog(shader)); return null; } diff --git a/src/core/renderers/webgl/shaders/StripShader.js b/src/core/renderers/webgl/shaders/StripShader.js index 193f6e1..a7abcc6 100644 --- a/src/core/renderers/webgl/shaders/StripShader.js +++ b/src/core/renderers/webgl/shaders/StripShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function StripShader(gl) { +function StripShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -20,7 +21,8 @@ 'varying vec2 vTextureCoord;', - 'void main(void) {', + '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);', @@ -36,7 +38,8 @@ 'varying vec2 vTextureCoord;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vec2(vTextureCoord.x, vTextureCoord.y)) * alpha;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/utils/FilterTexture.js b/src/core/renderers/webgl/utils/FilterTexture.js index d2c8423..4433d44 100644 --- a/src/core/renderers/webgl/utils/FilterTexture.js +++ b/src/core/renderers/webgl/utils/FilterTexture.js @@ -8,7 +8,8 @@ * @param height {number} the vertical range of the filter * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values */ -function FilterTexture(gl, width, height, scaleMode) { +function FilterTexture(gl, width, height, scaleMode) +{ /** * @member {WebGLContext} */ @@ -59,7 +60,8 @@ * Clears the filter texture. * */ -FilterTexture.prototype.clear = function () { +FilterTexture.prototype.clear = function () +{ var gl = this.gl; gl.clearColor(0,0,0, 0); @@ -72,8 +74,10 @@ * @param width {number} the new width of the texture * @param height {number} the new height of the texture */ -FilterTexture.prototype.resize = function (width, height) { - if (this.width === width && this.height === height) { +FilterTexture.prototype.resize = function (width, height) +{ + if (this.width === width && this.height === height) + { return; } @@ -96,7 +100,8 @@ * Destroys the filter texture. * */ -FilterTexture.prototype.destroy = function () { +FilterTexture.prototype.destroy = function () +{ var gl = this.gl; gl.deleteFramebuffer( this.frameBuffer ); gl.deleteTexture( this.texture ); diff --git a/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js b/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js index c4721e9..a63f4d7 100644 --- a/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js +++ b/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js @@ -14,7 +14,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this sprite batch works for. */ -function WebGLFastSpriteBatch(renderer) { +function WebGLFastSpriteBatch(renderer) +{ /** * The renderer instance this sprite batch operates on. * @@ -91,7 +92,8 @@ */ this.lastIndexCount = 0; - for (var i=0, j=0; i < numIndices; i += 6, j += 4) { + 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; @@ -144,7 +146,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.setupContext(); }); } @@ -157,7 +160,8 @@ * * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLFastSpriteBatch.prototype.setupContext = function () { +WebGLFastSpriteBatch.prototype.setupContext = function () +{ var gl = this.renderer.gl; // create a couple of buffers @@ -177,7 +181,8 @@ /** * @param spriteBatch {SpriteBatch} The SpriteBatch container to prepare for. */ -WebGLFastSpriteBatch.prototype.begin = function (spriteBatch) { +WebGLFastSpriteBatch.prototype.begin = function (spriteBatch) +{ this.shader = this.renderer.shaderManager.fastShader; this.matrix = spriteBatch.worldTransform.toArray(true); @@ -187,33 +192,38 @@ /** */ -WebGLFastSpriteBatch.prototype.end = function () { +WebGLFastSpriteBatch.prototype.end = function () +{ this.flush(); }; /** * @param spriteBatch {SpriteBatch} The SpriteBatch container to render. */ -WebGLFastSpriteBatch.prototype.render = function (spriteBatch) { +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) { + if (!sprite.texture._uvs) + { return; } this.currentBaseTexture = sprite.texture.baseTexture; // check blend mode - if (sprite.blendMode !== this.renderer.blendModeManager.currentBlendMode) { + if (sprite.blendMode !== this.renderer.blendModeManager.currentBlendMode) + { this.flush(); this.renderer.blendModeManager.setBlendMode(sprite.blendMode); } - for (var i=0,j= children.length; i= this.size) { + if (this.currentBatchSize >= this.size) + { this.flush(); } }; @@ -362,29 +379,35 @@ /** * */ -WebGLFastSpriteBatch.prototype.flush = function () { +WebGLFastSpriteBatch.prototype.flush = function () +{ // If the batch is length 0 then return as there is nothing to draw - if (this.currentBatchSize === 0) { + if (this.currentBatchSize === 0) + { return; } var gl = this.renderer.gl; // bind the current texture - if (!this.currentBaseTexture._glTextures[gl.id]) { + if (!this.currentBaseTexture._glTextures[gl.id]) + { this.renderer.updateTexture(this.currentBaseTexture, gl); } //TODO-SHOUD THIS BE ELSE??!?!?! - else { + else + { gl.bindTexture(gl.TEXTURE_2D, this.currentBaseTexture._glTextures[gl.id]); } // upload the verts to the buffer - if (this.currentBatchSize > ( this.size * 0.5 ) ) { + if (this.currentBatchSize > ( this.size * 0.5 ) ) + { gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); } - else { + else + { var view = this.vertices.subarray(0, this.currentBatchSize * this.vertByteSize); gl.bufferSubData(gl.ARRAY_BUFFER, 0, view); @@ -405,14 +428,16 @@ * Ends the batch and flushes * */ -WebGLFastSpriteBatch.prototype.stop = function () { +WebGLFastSpriteBatch.prototype.stop = function () +{ this.flush(); }; /** * */ -WebGLFastSpriteBatch.prototype.start = function () { +WebGLFastSpriteBatch.prototype.start = function () +{ var gl = this.renderer.gl; // bind the main texture diff --git a/src/core/renderers/webgl/utils/WebGLGraphics.js b/src/core/renderers/webgl/utils/WebGLGraphics.js index 55f4911..ab8f46e 100644 --- a/src/core/renderers/webgl/utils/WebGLGraphics.js +++ b/src/core/renderers/webgl/utils/WebGLGraphics.js @@ -19,7 +19,8 @@ * @param graphics {Graphics} * @param renderer {WebGLRenderer} */ -WebGLGraphics.renderGraphics = function (graphics, renderer) {//projection, offset) { +WebGLGraphics.renderGraphics = function (graphics, renderer) {//projection, offset) +{ var gl = renderer.gl; var projection = renderer.projection, @@ -27,7 +28,8 @@ shader = renderer.shaderManager.primitiveShader, webGLData; - if (graphics.dirty) { + if (graphics.dirty) + { WebGLGraphics.updateGraphics(graphics, gl); } @@ -35,8 +37,10 @@ // This could be speeded up for sure! - for (var i = 0; i < webGL.data.length; i++) { - if (webGL.data[i].mode === 1) { + for (var i = 0; i < webGL.data.length; i++) + { + if (webGL.data[i].mode === 1) + { webGLData = webGL.data[i]; renderer.stencilManager.pushStencil(graphics, webGLData, renderer); @@ -46,7 +50,8 @@ renderer.stencilManager.popStencil(graphics, webGLData, renderer); } - else { + else + { webGLData = webGL.data[i]; @@ -84,12 +89,14 @@ * @param graphicsData {Graphics} The graphics object to update * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLGraphics.updateGraphics = function (graphics, gl) { +WebGLGraphics.updateGraphics = function (graphics, gl) +{ // get the contexts graphics object var webGL = graphics._webGL[gl.id]; // if the graphics object does not exist in the webGL context time to create it! - if (!webGL) { + if (!webGL) + { webGL = graphics._webGL[gl.id] = {lastIndex:0, data:[], gl:gl}; } @@ -99,11 +106,13 @@ var i; // if the user cleared the graphics object we will need to clear every object - if (graphics.clearDirty) { + if (graphics.clearDirty) + { graphics.clearDirty = false; // lop through and return all the webGLDatas to the object pool so than can be reused later on - for (i = 0; i < webGL.data.length; i++) { + for (i = 0; i < webGL.data.length; i++) + { var graphicsData = webGL.data[i]; graphicsData.reset(); WebGLGraphics.graphicsDataPool.push( graphicsData ); @@ -119,58 +128,72 @@ // loop through the graphics datas and construct each one.. // if the object is a complex fill then the new stencil buffer technique will be used // other wise graphics objects will be pushed into a batch.. - for (i = webGL.lastIndex; i < graphics.graphicsData.length; i++) { + for (i = webGL.lastIndex; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { // need to add the points the the graphics object.. data.points = data.shape.points.slice(); - if (data.shape.closed) { + if (data.shape.closed) + { // close the poly if the value is true! - if (data.points[0] !== data.points[data.points.length-2] || data.points[1] !== data.points[data.points.length-1]) { + if (data.points[0] !== data.points[data.points.length-2] || data.points[1] !== data.points[data.points.length-1]) + { data.points.push(data.points[0], data.points[1]); } } // MAKE SURE WE HAVE THE CORRECT TYPE.. - if (data.fill) { - if (data.points.length >= 6) { - if (data.points.length < 6 * 2) { + if (data.fill) + { + if (data.points.length >= 6) + { + if (data.points.length < 6 * 2) + { webGLData = WebGLGraphics.switchMode(webGL, 0); var canDrawUsingSimple = WebGLGraphics.buildPoly(data, webGLData); // console.log(canDrawUsingSimple); - if (!canDrawUsingSimple) { + if (!canDrawUsingSimple) + { // console.log("<>>>") webGLData = WebGLGraphics.switchMode(webGL, 1); WebGLGraphics.buildComplexPoly(data, webGLData); } } - else { + else + { webGLData = WebGLGraphics.switchMode(webGL, 1); WebGLGraphics.buildComplexPoly(data, webGLData); } } } - if (data.lineWidth > 0) { + if (data.lineWidth > 0) + { webGLData = WebGLGraphics.switchMode(webGL, 0); WebGLGraphics.buildLine(data, webGLData); } } - else { + else + { webGLData = WebGLGraphics.switchMode(webGL, 0); - if (data.type === CONST.SHAPES.RECT) { + if (data.type === CONST.SHAPES.RECT) + { WebGLGraphics.buildRectangle(data, webGLData); } - else if (data.type === CONST.SHAPES.CIRC || data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.CIRC || data.type === CONST.SHAPES.ELIP) + { WebGLGraphics.buildCircle(data, webGLData); } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { WebGLGraphics.buildRoundedRectangle(data, webGLData); } } @@ -179,10 +202,12 @@ } // upload all the dirty data... - for (i = 0; i < webGL.data.length; i++) { + for (i = 0; i < webGL.data.length; i++) + { webGLData = webGL.data[i]; - if (webGLData.dirty) { + if (webGLData.dirty) + { webGLData.upload(); } } @@ -194,18 +219,22 @@ * @param webGL {WebGLContext} * @param type {number} */ -WebGLGraphics.switchMode = function (webGL, type) { +WebGLGraphics.switchMode = function (webGL, type) +{ var webGLData; - if (!webGL.data.length) { + if (!webGL.data.length) + { webGLData = WebGLGraphics.graphicsDataPool.pop() || new WebGLGraphicsData(webGL.gl); webGLData.mode = type; webGL.data.push(webGLData); } - else { + else + { webGLData = webGL.data[webGL.data.length-1]; - if (webGLData.mode !== type || type === 1) { + if (webGLData.mode !== type || type === 1) + { webGLData = WebGLGraphics.graphicsDataPool.pop() || new WebGLGraphicsData(webGL.gl); webGLData.mode = type; webGL.data.push(webGLData); @@ -225,7 +254,8 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildRectangle = function (graphicsData, webGLData) { +WebGLGraphics.buildRectangle = function (graphicsData, webGLData) +{ // --- // // need to convert points to a nice regular data // @@ -235,7 +265,8 @@ var width = rectData.width; var height = rectData.height; - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -265,7 +296,8 @@ indices.push(vertPos, vertPos, vertPos+1, vertPos+2, vertPos+3, vertPos+3); } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = [x, y, @@ -289,7 +321,8 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildRoundedRectangle = function (graphicsData, webGLData) { +WebGLGraphics.buildRoundedRectangle = function (graphicsData, webGLData) +{ var rrectData = graphicsData.shape; var x = rrectData.x; var y = rrectData.y; @@ -305,7 +338,8 @@ recPoints = recPoints.concat(WebGLGraphics.quadraticBezierCurve(x + width, y + radius, x + width, y, x + width - radius, y)); recPoints = recPoints.concat(WebGLGraphics.quadraticBezierCurve(x + radius, y, x, y, x, y + radius)); - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -323,7 +357,8 @@ // var i = 0; - for (i = 0; i < triangles.length; i+=3) { + for (i = 0; i < triangles.length; i+=3) + { indices.push(triangles[i] + vecPos); indices.push(triangles[i] + vecPos); indices.push(triangles[i+1] + vecPos); @@ -332,12 +367,14 @@ } - for (i = 0; i < recPoints.length; i++) { + for (i = 0; i < recPoints.length; i++) + { verts.push(recPoints[i], recPoints[++i], r, g, b, alpha); } } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = recPoints; @@ -362,7 +399,8 @@ * @param toY {number} Destination point y * @return {number[]} */ -WebGLGraphics.quadraticBezierCurve = function (fromX, fromY, cpX, cpY, toX, toY) { +WebGLGraphics.quadraticBezierCurve = function (fromX, fromY, cpX, cpY, toX, toY) +{ var xa, ya, @@ -373,14 +411,16 @@ n = 20, points = []; - function getPt(n1 , n2, perc) { + function getPt(n1 , n2, perc) + { var diff = n2 - n1; return n1 + ( diff * perc ); } var j = 0; - for (var i = 0; i <= n; i++ ) { + for (var i = 0; i <= n; i++ ) + { j = i / n; // The Green Line @@ -406,7 +446,8 @@ * @param graphicsData {Graphics} The graphics object to draw * @param webGLData {object} */ -WebGLGraphics.buildCircle = function (graphicsData, webGLData) { +WebGLGraphics.buildCircle = function (graphicsData, webGLData) +{ // need to convert points to a nice regular data var circleData = graphicsData.shape; var x = circleData.x; @@ -415,11 +456,13 @@ var height; // TODO - bit hacky?? - if (graphicsData.type === CONST.SHAPES.CIRC) { + if (graphicsData.type === CONST.SHAPES.CIRC) + { width = circleData.radius; height = circleData.radius; } - else { + else + { width = circleData.width; height = circleData.height; } @@ -429,7 +472,8 @@ var i = 0; - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -444,7 +488,8 @@ indices.push(vecPos); - for (i = 0; i < totalSegs + 1 ; i++) { + for (i = 0; i < totalSegs + 1 ; i++) + { verts.push(x,y, r, g, b, alpha); verts.push(x + Math.sin(seg * i) * width, @@ -457,12 +502,14 @@ indices.push(vecPos-1); } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = []; - for (i = 0; i < totalSegs + 1; i++) { + for (i = 0; i < totalSegs + 1; i++) + { graphicsData.points.push(x + Math.sin(seg * i) * width, y + Math.cos(seg * i) * height); } @@ -481,18 +528,22 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildLine = function (graphicsData, webGLData) { +WebGLGraphics.buildLine = function (graphicsData, webGLData) +{ // TODO OPTIMISE! var i = 0; var points = graphicsData.points; - if (points.length === 0) { + if (points.length === 0) + { return; } // if the line width is an odd number add 0.5 to align to a whole pixel - if (graphicsData.lineWidth%2) { - for (i = 0; i < points.length; i++) { + if (graphicsData.lineWidth%2) + { + for (i = 0; i < points.length; i++) + { points[i] += 0.5; } } @@ -502,7 +553,8 @@ var lastPoint = new math.Point(points[points.length - 2], points[points.length - 1]); // if the first point is the last point - gonna have issues :) - if (firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) { + if (firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) + { // need to clone as we are going to slightly modify the shape.. points = points.slice(); @@ -562,7 +614,8 @@ verts.push(p1x + perpx , p1y + perpy, r, g, b, alpha); - for (i = 1; i < length-1; i++) { + for (i = 1; i < length-1; i++) + { p1x = points[(i-1)*2]; p1y = points[(i-1)*2 + 1]; @@ -599,7 +652,8 @@ denom = a1*b2 - a2*b1; - if (Math.abs(denom) < 0.1 ) { + if (Math.abs(denom) < 0.1 ) + { denom+=10.1; verts.push(p2x - perpx , p2y - perpy, @@ -618,7 +672,8 @@ pdist = (px -p2x) * (px -p2x) + (py -p2y) + (py -p2y); - if (pdist > 140 * 140) { + if (pdist > 140 * 140) + { perp3x = perpx - perp2x; perp3y = perpy - perp2y; @@ -639,7 +694,8 @@ indexCount++; } - else { + else + { verts.push(px , py); verts.push(r, g, b, alpha); @@ -672,7 +728,8 @@ indices.push(indexStart); - for (i = 0; i < indexCount; i++) { + for (i = 0; i < indexCount; i++) + { indices.push(indexStart++); } @@ -687,11 +744,13 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildComplexPoly = function (graphicsData, webGLData) { +WebGLGraphics.buildComplexPoly = function (graphicsData, webGLData) +{ //TODO - no need to copy this as it gets turned into a FLoat32Array anyways.. var points = graphicsData.points.slice(); - if (points.length < 6) { + if (points.length < 6) + { return; } @@ -711,7 +770,8 @@ var x,y; // get size.. - for (var i = 0; i < points.length; i+=2) { + for (var i = 0; i < points.length; i+=2) + { x = points[i]; y = points[i+1]; @@ -732,7 +792,8 @@ //TODO - this aint needed! var length = points.length / 2; - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { indices.push( i ); } @@ -746,10 +807,12 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildPoly = function (graphicsData, webGLData) { +WebGLGraphics.buildPoly = function (graphicsData, webGLData) +{ var points = graphicsData.points; - if (points.length < 6) { + if (points.length < 6) + { return; } // get first and last point.. figure out the middle! @@ -767,7 +830,8 @@ var triangles = utils.PolyK.Triangulate(points); - if (!triangles) { + if (!triangles) + { return false; } @@ -775,7 +839,8 @@ var i = 0; - for (i = 0; i < triangles.length; i+=3) { + for (i = 0; i < triangles.length; i+=3) + { indices.push(triangles[i] + vertPos); indices.push(triangles[i] + vertPos); indices.push(triangles[i+1] + vertPos); @@ -783,7 +848,8 @@ indices.push(triangles[i+2] + vertPos); } - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { verts.push(points[i * 2], points[i * 2 + 1], r, g, b, alpha); } diff --git a/src/core/renderers/webgl/utils/WebGLGraphicsData.js b/src/core/renderers/webgl/utils/WebGLGraphicsData.js index c56d05e..c739ba7 100644 --- a/src/core/renderers/webgl/utils/WebGLGraphicsData.js +++ b/src/core/renderers/webgl/utils/WebGLGraphicsData.js @@ -2,7 +2,8 @@ * @class * @private */ -function WebGLGraphicsData(gl) { +function WebGLGraphicsData(gl) +{ this.gl = gl; //TODO does this need to be split before uploding?? @@ -22,7 +23,8 @@ /** * */ -WebGLGraphicsData.prototype.reset = function () { +WebGLGraphicsData.prototype.reset = function () +{ this.points.length = 0; this.indices.length = 0; }; @@ -30,7 +32,8 @@ /** * */ -WebGLGraphicsData.prototype.upload = function () { +WebGLGraphicsData.prototype.upload = function () +{ var gl = this.gl; // this.lastIndex = graphics.graphicsData.length; diff --git a/src/core/renderers/webgl/utils/WebGLSpriteBatch.js b/src/core/renderers/webgl/utils/WebGLSpriteBatch.js index 96eaa52..55befbb 100644 --- a/src/core/renderers/webgl/utils/WebGLSpriteBatch.js +++ b/src/core/renderers/webgl/utils/WebGLSpriteBatch.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this sprite batch works for. */ -function WebGLSpriteBatch(renderer) { +function WebGLSpriteBatch(renderer) +{ /** * * @@ -88,7 +89,8 @@ */ this.lastIndexCount = 0; - for (var i=0, j=0; i < numIndices; i += 6, j += 4) { + 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; @@ -162,7 +164,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.setupContext(); }); } @@ -173,7 +176,8 @@ /** * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLSpriteBatch.prototype.setupContext = function () { +WebGLSpriteBatch.prototype.setupContext = function () +{ var gl = this.renderer.gl; // setup default shader @@ -198,7 +202,8 @@ /** * */ -WebGLSpriteBatch.prototype.begin = function () { +WebGLSpriteBatch.prototype.begin = function () +{ // this.shader = this.renderer.shaderManager.defaultShader; this.start(); @@ -206,19 +211,22 @@ /** */ -WebGLSpriteBatch.prototype.end = function () { +WebGLSpriteBatch.prototype.end = function () +{ this.flush(); }; /** * @param sprite {Sprite} the sprite to render when using this spritebatch */ -WebGLSpriteBatch.prototype.render = function (sprite) { +WebGLSpriteBatch.prototype.render = function (sprite) +{ var texture = sprite.texture; //TODO set blend modes.. // check texture.. - if (this.currentBatchSize >= this.size) { + if (this.currentBatchSize >= this.size) + { this.flush(); this.currentBaseTexture = texture.baseTexture; } @@ -227,7 +235,8 @@ var uvs = texture._uvs; // if the uvs have not updated then no point rendering just yet! - if (!uvs) { + if (!uvs) + { return; } @@ -237,7 +246,8 @@ var w0, w1, h0, h1; - if (texture.trim) { + 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; @@ -248,7 +258,8 @@ h0 = h1 + texture.crop.height; } - else { + else + { w0 = (texture.frame.width ) * (1-aX); w1 = (texture.frame.width ) * -aX; @@ -272,7 +283,8 @@ var colors = this.colors; var positions = this.positions; - if (this.renderer.roundPixels) { + if (this.renderer.roundPixels) + { // xy positions[index] = a * w1 + c * h1 + tx | 0; positions[index+1] = d * h1 + b * w1 + ty | 0; @@ -289,7 +301,8 @@ positions[index+15] = a * w1 + c * h0 + tx | 0; positions[index+16] = d * h0 + b * w1 + ty | 0; } - else { + else + { // xy positions[index] = a * w1 + c * h1 + tx; positions[index+1] = d * h1 + b * w1 + ty; @@ -338,11 +351,13 @@ * * @param sprite {TilingSprite} the tilingSprite to render */ -WebGLSpriteBatch.prototype.renderTilingSprite = function (tilingSprite) { +WebGLSpriteBatch.prototype.renderTilingSprite = function (tilingSprite) +{ var texture = tilingSprite.tilingTexture; // check texture.. - if (this.currentBatchSize >= this.size) { + if (this.currentBatchSize >= this.size) + { //return; this.flush(); this.currentBaseTexture = texture.baseTexture; @@ -351,7 +366,8 @@ // set the textures uvs temporarily // TODO create a separate texture so that we can tile part of a texture - if (!tilingSprite._uvs) { + if (!tilingSprite._uvs) + { tilingSprite._uvs = new TextureUvs(); } @@ -454,16 +470,19 @@ * Renders the content and empties the current batch. * */ -WebGLSpriteBatch.prototype.flush = function () { +WebGLSpriteBatch.prototype.flush = function () +{ // If the batch is length 0 then return as there is nothing to draw - if (this.currentBatchSize === 0) { + if (this.currentBatchSize === 0) + { return; } var gl = this.renderer.gl; var shader; - if (this.dirty) { + if (this.dirty) + { this.dirty = false; // bind the main texture gl.activeTexture(gl.TEXTURE0); @@ -482,10 +501,12 @@ } // upload the verts to the buffer - if (this.currentBatchSize > ( this.size * 0.5 ) ) { + if (this.currentBatchSize > ( this.size * 0.5 ) ) + { gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); } - else { + else + { var view = this.positions.subarray(0, this.currentBatchSize * this.vertByteSize); gl.bufferSubData(gl.ARRAY_BUFFER, 0, view); } @@ -502,7 +523,8 @@ var shaderSwap = false; var sprite; - for (var i = 0, j = this.currentBatchSize; i < j; i++) { + for (var i = 0, j = this.currentBatchSize; i < j; i++) + { sprite = this.sprites[i]; @@ -513,24 +535,28 @@ blendSwap = currentBlendMode !== nextBlendMode; shaderSwap = currentShader !== nextShader; // should I use uuidS??? - if (currentBaseTexture !== nextTexture || blendSwap || shaderSwap) { + if (currentBaseTexture !== nextTexture || blendSwap || shaderSwap) + { this.renderBatch(currentBaseTexture, batchSize, start); start = i; batchSize = 0; currentBaseTexture = nextTexture; - if (blendSwap) { + if (blendSwap) + { currentBlendMode = nextBlendMode; this.renderer.blendModeManager.setBlendMode( currentBlendMode ); } - if (shaderSwap) { + if (shaderSwap) + { currentShader = nextShader; shader = currentShader.shaders ? currentShader.shaders[gl.id] : currentShader; - if (!shader) { + if (!shader) + { shader = new Shader(gl, null, currentShader.fragmentSrc, currentShader.uniforms); currentShader.shaders[gl.id] = shader; } @@ -538,7 +564,8 @@ // set shader function??? this.renderer.shaderManager.setShader(shader); - if (shader.dirty) { + if (shader.dirty) + { shader.syncUniforms(); } @@ -569,17 +596,21 @@ * @param size {number} * @param startIndex {number} */ -WebGLSpriteBatch.prototype.renderBatch = function (texture, size, startIndex) { - if (size === 0) { +WebGLSpriteBatch.prototype.renderBatch = function (texture, size, startIndex) +{ + if (size === 0) + { return; } var gl = this.renderer.gl; - if (!texture._glTextures[gl.id]) { + if (!texture._glTextures[gl.id]) + { this.renderer.updateTexture(texture); } - else { + else + { // bind the current texture gl.bindTexture(gl.TEXTURE_2D, texture._glTextures[gl.id]); } @@ -594,7 +625,8 @@ /** * */ -WebGLSpriteBatch.prototype.stop = function () { +WebGLSpriteBatch.prototype.stop = function () +{ this.flush(); this.dirty = true; }; @@ -602,7 +634,8 @@ /** * */ -WebGLSpriteBatch.prototype.start = function () { +WebGLSpriteBatch.prototype.start = function () +{ this.dirty = true; }; @@ -610,7 +643,8 @@ * Destroys the SpriteBatch. * */ -WebGLSpriteBatch.prototype.destroy = function () { +WebGLSpriteBatch.prototype.destroy = function () +{ this.renderer.gl.deleteBuffer(this.vertexBuffer); this.renderer.gl.deleteBuffer(this.indexBuffer); diff --git a/src/core/textures/BaseTexture.js b/src/core/textures/BaseTexture.js index 2bf77d4..513d358 100644 --- a/src/core/textures/BaseTexture.js +++ b/src/core/textures/BaseTexture.js @@ -10,7 +10,8 @@ * @param source {Image|Canvas} the source object of the texture. * @param [scaleMode=scaleModes.DEFAULT] {number} See {@link scaleModes} for possible values */ -function BaseTexture(source, scaleMode) { +function BaseTexture(source, scaleMode) +{ this.uuid = utils.uuid(); /** @@ -123,7 +124,8 @@ this._needsUpdate = false; // if no source passed don't try to load - if (source) { + if (source) + { this.loadSource(source); } @@ -149,13 +151,16 @@ Object.defineProperties(BaseTexture.prototype, { needsUpdate: { - get: function () { + get: function () + { return this._needsUpdate; }, - set: function (val) { + set: function (val) + { this._needsUpdate = val; - if (val) { + if (val) + { this.emit('update', this); } } @@ -171,9 +176,11 @@ * * The logic state after calling `loadSource` directly or indirectly (eg. `fromImage`, `new BaseTexture`) is: * - * if (texture.hasLoaded) { + * if (texture.hasLoaded) + { * // texture ready for use - * } else if (texture.isLoading) { + * } else if (texture.isLoading) + { * // listen to 'loaded' and/or 'error' events on texture * } else { * // not loading, not going to load UNLESS the source is reloaded @@ -183,12 +190,14 @@ * @protected * @param source {Image|Canvas} the source object of the texture. */ -BaseTexture.prototype.loadSource = function (source) { +BaseTexture.prototype.loadSource = function (source) +{ var wasLoading = this.isLoading; this.hasLoaded = false; this.isLoading = false; - if (wasLoading && this.source) { + if (wasLoading && this.source) + { this.source.onload = null; this.source.onerror = null; } @@ -196,20 +205,24 @@ this.source = source; // Apply source if loaded. Otherwise setup appropriate loading monitors. - if ((this.source.complete || this.source.getContext) && this.source.width && this.source.height) { + if ((this.source.complete || this.source.getContext) && this.source.width && this.source.height) + { this._sourceLoaded(); } - else if(!source.getContext) { + else if(!source.getContext) + { // Image fail / not ready this.isLoading = true; var scope = this; - source.onload = function () { + source.onload = function () + { source.onload = null; source.onerror = null; - if(!scope.isLoading) { + if(!scope.isLoading) + { return; } @@ -219,11 +232,13 @@ scope.emit('loaded', scope); }; - source.onerror = function () { + source.onerror = function () + { source.onload = null; source.onerror = null; - if(!scope.isLoading) { + if(!scope.isLoading) + { return; } @@ -234,24 +249,29 @@ // Per http://www.w3.org/TR/html5/embedded-content-0.html#the-img-element // "The value of `complete` can thus change while a script is executing." // So complete needs to be re-checked after the callbacks have been added.. - if (source.complete) { + if (source.complete) + { this.isLoading = false; // ..and if we're complete now, no need for callbacks source.onload = null; source.onerror = null; - if (source.width && source.height) { + if (source.width && source.height) + { this._sourceLoaded(); // If any previous subscribers possible - if (wasLoading) { + if (wasLoading) + { this.emit('loaded', this); } } - else { + else + { // If any previous subscribers possible - if (wasLoading) { + if (wasLoading) + { this.emit('error', this); } } @@ -265,7 +285,8 @@ * * @private */ -BaseTexture.prototype._sourceLoaded = function () { +BaseTexture.prototype._sourceLoaded = function () +{ this.hasLoaded = true; this.width = this.source.naturalWidth || this.source.width; @@ -278,16 +299,20 @@ * Destroys this base texture * */ -BaseTexture.prototype.destroy = function () { - if (this.imageUrl) { +BaseTexture.prototype.destroy = function () +{ + if (this.imageUrl) + { delete utils.BaseTextureCache[this.imageUrl]; delete utils.TextureCache[this.imageUrl]; this.imageUrl = null; - if (!navigator.isCocoonJS) { + if (!navigator.isCocoonJS) + { this.source.src = ''; } } - else if (this.source && this.source._pixiId) { + else if (this.source && this.source._pixiId) + { delete utils.BaseTextureCache[this.source._pixiId]; } this.source = null; @@ -301,7 +326,8 @@ * memory again. * */ -BaseTexture.prototype.dispose = function () { +BaseTexture.prototype.dispose = function () +{ this.emit('dispose', this); }; @@ -311,7 +337,8 @@ * * @param newSrc {string} the path of the image */ -BaseTexture.prototype.updateSourceImage = function (newSrc) { +BaseTexture.prototype.updateSourceImage = function (newSrc) +{ this.source.src = newSrc; this.loadSource(this.source); }; @@ -326,18 +353,22 @@ * @param [scaleMode=scaleModes.DEFAULT] {number} See {@link scaleModes} for possible values * @return BaseTexture */ -BaseTexture.fromImage = function (imageUrl, crossorigin, scaleMode) { +BaseTexture.fromImage = function (imageUrl, crossorigin, scaleMode) +{ var baseTexture = utils.BaseTextureCache[imageUrl]; - if (crossorigin === undefined && imageUrl.indexOf('data:') !== 0) { + if (crossorigin === undefined && imageUrl.indexOf('data:') !== 0) + { crossorigin = true; } - if (!baseTexture) { + if (!baseTexture) + { // new Image() breaks tex loading in some versions of Chrome. // See https://code.google.com/p/chromium/issues/detail?id=238071 var image = new Image();//document.createElement('img'); - if (crossorigin) { + if (crossorigin) + { image.crossOrigin = ''; } @@ -347,7 +378,8 @@ utils.BaseTextureCache[imageUrl] = baseTexture; // if there is an @2x at the end of the url we are going to assume its a highres image - if ( imageUrl.indexOf(CONST.RETINA_PREFIX + '.') !== -1) { + if ( imageUrl.indexOf(CONST.RETINA_PREFIX + '.') !== -1) + { baseTexture.resolution = 2; } } @@ -363,14 +395,17 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return BaseTexture */ -BaseTexture.fromCanvas = function (canvas, scaleMode) { - if (!canvas._pixiId) { +BaseTexture.fromCanvas = function (canvas, scaleMode) +{ + if (!canvas._pixiId) + { canvas._pixiId = 'canvas_' + utils.uuid(); } var baseTexture = utils.BaseTextureCache[canvas._pixiId]; - if (!baseTexture) { + if (!baseTexture) + { baseTexture = new BaseTexture(canvas, scaleMode); utils.BaseTextureCache[canvas._pixiId] = baseTexture; } diff --git a/src/core/textures/RenderTexture.js b/src/core/textures/RenderTexture.js index 6dad20f..53ae796 100644 --- a/src/core/textures/RenderTexture.js +++ b/src/core/textures/RenderTexture.js @@ -46,8 +46,10 @@ * @param [scaleMode] {number} See {@link scaleModes} for possible values * @param [resolution=1] {number} The resolution of the texture being generated */ -function RenderTexture(renderer, width, height, scaleMode, resolution) { - if (!renderer) { +function RenderTexture(renderer, width, height, scaleMode, resolution) +{ + if (!renderer) + { throw new Error('Unable to create RenderTexture, you must pass a renderer into the constructor.'); } @@ -133,7 +135,8 @@ */ this.renderer = renderer; - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { var gl = this.renderer.gl; this.textureBuffer = new FilterTexture(gl, this.width * this.resolution, this.height * this.resolution, this.baseTexture.scaleMode); @@ -142,7 +145,8 @@ this.render = this.renderWebGL; this.projection = new math.Point(this.width*0.5, -this.height*0.5); } - else { + else + { this.render = this.renderCanvas; this.textureBuffer = new CanvasBuffer(this.width* this.resolution, this.height* this.resolution); this.baseTexture.source = this.textureBuffer.canvas; @@ -167,8 +171,10 @@ * @param height {number} The height to resize to. * @param updateBase {boolean} Should the baseTexture.width and height values be resized as well? */ -RenderTexture.prototype.resize = function (width, height, updateBase) { - if (width === this.width && height === this.height) { +RenderTexture.prototype.resize = function (width, height, updateBase) +{ + if (width === this.width && height === this.height) + { return; } @@ -177,17 +183,20 @@ this.width = this.frame.width = this.crop.width = width; this.height = this.frame.height = this.crop.height = height; - if (updateBase) { + if (updateBase) + { this.baseTexture.width = this.width; this.baseTexture.height = this.height; } - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { this.projection.x = this.width / 2; this.projection.y = -this.height / 2; } - if (!this.valid) { + if (!this.valid) + { return; } @@ -198,12 +207,15 @@ * Clears the RenderTexture. * */ -RenderTexture.prototype.clear = function () { - if (!this.valid) { +RenderTexture.prototype.clear = function () +{ + if (!this.valid) + { return; } - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { this.renderer.gl.bindFramebuffer(this.renderer.gl.FRAMEBUFFER, this.textureBuffer.frameBuffer); } @@ -220,19 +232,23 @@ * @param [restoreWorldTransform=true] {boolean} If true the displayObject's worldTransform/worldAlpha and all children * transformations will be restored. Not restoring this information will be a little faster. */ -RenderTexture.prototype.renderWebGL = function (displayObject, matrix, clear, restoreWorldTransform) { - if (!this.valid) { +RenderTexture.prototype.renderWebGL = function (displayObject, matrix, clear, restoreWorldTransform) +{ + if (!this.valid) + { return; } - if (typeof restoreWorldTransform === 'undefined') { + if (typeof restoreWorldTransform === 'undefined') + { restoreWorldTransform = true; } var tempAlpha, tempTransform; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { tempAlpha = displayObject.worldAlpha; tempTransform = displayObject.worldTransform.toArray(); } @@ -245,7 +261,8 @@ wt.identity(); wt.translate(0, this.projection.y * 2); - if (matrix) { + if (matrix) + { wt.append(matrix); } @@ -258,7 +275,8 @@ var children = displayObject.children; var i, j; - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } @@ -269,7 +287,8 @@ gl.bindFramebuffer(gl.FRAMEBUFFER, this.textureBuffer.frameBuffer ); - if (clear) { + if (clear) + { this.textureBuffer.clear(); } @@ -279,11 +298,13 @@ this.renderer.spriteBatch.dirty = true; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { displayObject.worldAlpha = tempAlpha; displayObject.worldTransform.fromArray(tempTransform); - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } } @@ -300,26 +321,31 @@ * @param [restoreWorldTransform=true] {boolean} If true the displayObject's worldTransform/worldAlpha and all children * transformations will be restored. Not restoring this information will be a little faster. */ -RenderTexture.prototype.renderCanvas = function (displayObject, matrix, clear, restoreWorldTransform) { - if (!this.valid) { +RenderTexture.prototype.renderCanvas = function (displayObject, matrix, clear, restoreWorldTransform) +{ + if (!this.valid) + { return; } - if (typeof restoreWorldTransform === 'undefined') { + if (typeof restoreWorldTransform === 'undefined') + { restoreWorldTransform = true; } var tempAlpha, tempTransform; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { tempAlpha = displayObject.worldAlpha; tempTransform = displayObject.worldTransform.toArray(); } var wt = displayObject.worldTransform; wt.identity(); - if (matrix) { + if (matrix) + { wt.append(matrix); } @@ -330,11 +356,13 @@ var children = displayObject.children; var i, j; - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } - if (clear) { + if (clear) + { this.textureBuffer.clear(); } @@ -348,11 +376,13 @@ this.renderer.resolution = realResolution; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { displayObject.worldAlpha = tempAlpha; displayObject.worldTransform.fromArray(tempTransform); - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } } @@ -363,7 +393,8 @@ * * @return {Image} */ -RenderTexture.prototype.getImage = function () { +RenderTexture.prototype.getImage = function () +{ var image = new Image(); image.src = this.getBase64(); return image; @@ -374,7 +405,8 @@ * * @return {string} A base64 encoded string of the texture. */ -RenderTexture.prototype.getBase64 = function () { +RenderTexture.prototype.getBase64 = function () +{ return this.getCanvas().toDataURL(); }; @@ -383,8 +415,10 @@ * * @return {HTMLCanvasElement} A Canvas element with the texture rendered on. */ -RenderTexture.prototype.getCanvas = function () { - if (this.renderer.type === CONST.WEBGL_RENDERER) { +RenderTexture.prototype.getCanvas = function () +{ + if (this.renderer.type === CONST.WEBGL_RENDERER) + { var gl = this.renderer.gl; var width = this.textureBuffer.width; var height = this.textureBuffer.height; @@ -403,7 +437,8 @@ return tempCanvas.canvas; } - else { + else + { return this.textureBuffer.canvas; } }; diff --git a/src/core/textures/Texture.js b/src/core/textures/Texture.js index 3c65909..e97f0aa 100644 --- a/src/core/textures/Texture.js +++ b/src/core/textures/Texture.js @@ -17,7 +17,8 @@ * @param [crop] {Rectangle} The area of original texture * @param [trim] {Rectangle} Trimmed texture rectangle */ -function Texture(baseTexture, frame, crop, trim) { +function Texture(baseTexture, frame, crop, trim) +{ /** * Does this Texture have any frame data assigned to it? * @@ -25,12 +26,14 @@ */ this.noFrame = false; - if (!frame) { + if (!frame) + { this.noFrame = true; frame = new math.Rectangle(0, 0, 1, 1); } - if (baseTexture instanceof Texture) { + if (baseTexture instanceof Texture) + { baseTexture = baseTexture.baseTexture; } @@ -100,13 +103,16 @@ */ this.crop = crop || new math.Rectangle(0, 0, 1, 1); - if (baseTexture.hasLoaded) { - if (this.noFrame) { + if (baseTexture.hasLoaded) + { + if (this.noFrame) + { frame = new math.Rectangle(0, 0, baseTexture.width, baseTexture.height); } this.frame = frame; } - else { + else + { baseTexture.addEventListener('loaded', this.onBaseTextureLoaded.bind(this)); } } @@ -118,19 +124,23 @@ Object.defineProperties(Texture.prototype, { needsUpdate: { - get: function () { + get: function () + { return this.baseTexture.needsUpdate; }, - set: function (val) { + set: function (val) + { this.baseTexture.needsUpdate = val; } }, frame: { - get: function () { + get: function () + { return this._frame; }, - set: function (frame) { + set: function (frame) + { this._frame = frame; this.noFrame = false; @@ -143,20 +153,23 @@ 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 (!this.trim && (frame.x + frame.width > this.baseTexture.width || frame.y + frame.height > this.baseTexture.height)) + { throw new Error('Texture Error: frame does not fit inside the base Texture dimensions ' + this); } this.valid = frame && frame.width && frame.height && this.baseTexture.source && this.baseTexture.hasLoaded; - if (this.trim) { + 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) { + if (this.valid) + { this._updateUvs(); } } @@ -168,11 +181,13 @@ * * @private */ -Texture.prototype.onBaseTextureLoaded = function () { +Texture.prototype.onBaseTextureLoaded = function () +{ var baseTexture = this.baseTexture; baseTexture.removeEventListener('loaded', this.onLoaded); - if (this.noFrame) { + if (this.noFrame) + { this.frame = new math.Rectangle(0, 0, baseTexture.width, baseTexture.height); } @@ -184,8 +199,10 @@ * * @param destroyBase {boolean} Whether to destroy the base texture as well */ -Texture.prototype.destroy = function (destroyBase) { - if (destroyBase) { +Texture.prototype.destroy = function (destroyBase) +{ + if (destroyBase) + { this.baseTexture.destroy(); } @@ -197,8 +214,10 @@ * * @private */ -Texture.prototype._updateUvs = function () { - if (!this._uvs) { +Texture.prototype._updateUvs = function () +{ + if (!this._uvs) + { this._uvs = new TextureUvs(); } @@ -229,10 +248,12 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return Texture */ -Texture.fromImage = function (imageUrl, crossorigin, scaleMode) { +Texture.fromImage = function (imageUrl, crossorigin, scaleMode) +{ var texture = utils.TextureCache[imageUrl]; - if (!texture) { + if (!texture) + { texture = new Texture(BaseTexture.fromImage(imageUrl, crossorigin, scaleMode)); utils.TextureCache[imageUrl] = texture; } @@ -248,9 +269,11 @@ * @param frameId {string} The frame id of the texture * @return Texture */ -Texture.fromFrame = function (frameId) { +Texture.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache '); } return texture; @@ -264,7 +287,8 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return {Texture} */ -Texture.fromCanvas = function (canvas, scaleMode) { +Texture.fromCanvas = function (canvas, scaleMode) +{ return new Texture(BaseTexture.fromCanvas(canvas, scaleMode)); }; @@ -276,7 +300,8 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return {Texture} A Texture */ -Texture.fromVideo = function (video, scaleMode) { +Texture.fromVideo = function (video, scaleMode) +{ return new Texture(VideoBaseTexture.baseTextureFromVideo(video, scaleMode)); }; @@ -287,7 +312,8 @@ * @param texture {Texture} The Texture to add to the cache. * @param id {string} The id that the texture will be stored against. */ -Texture.addTextureToCache = function (texture, id) { +Texture.addTextureToCache = function (texture, id) +{ utils.TextureCache[id] = texture; }; @@ -298,7 +324,8 @@ * @param id {string} The id of the texture to be removed * @return {Texture} The texture that was removed */ -Texture.removeTextureFromCache = function (id) { +Texture.removeTextureFromCache = function (id) +{ var texture = utils.TextureCache[id]; delete utils.TextureCache[id]; diff --git a/src/core/textures/TextureUvs.js b/src/core/textures/TextureUvs.js index b9bbb58..5424d52 100644 --- a/src/core/textures/TextureUvs.js +++ b/src/core/textures/TextureUvs.js @@ -1,4 +1,5 @@ -function TextureUvs() { +function TextureUvs() +{ this.x0 = 0; this.y0 = 0; diff --git a/src/core/textures/VideoBaseTexture.js b/src/core/textures/VideoBaseTexture.js index e3e0c5a..1a826a9 100644 --- a/src/core/textures/VideoBaseTexture.js +++ b/src/core/textures/VideoBaseTexture.js @@ -12,15 +12,18 @@ * @param source {HTMLVideoElement} * @param [scaleMode] {number} See {@link scaleModes} for possible values */ -function VideoBaseTexture(source, scaleMode) { - if (!source){ +function VideoBaseTexture(source, scaleMode) +{ + if (!source) + { throw new Error('No video source element specified.'); } // hook in here to check if video is already available. // BaseTexture looks for a source.complete boolean, plus width & height. - if ((source.readyState === source.HAVE_ENOUGH_DATA || source.readyState === source.HAVE_FUTURE_DATA) && source.width && source.height) { + if ((source.readyState === source.HAVE_ENOUGH_DATA || source.readyState === source.HAVE_FUTURE_DATA) && source.width && source.height) + { source.complete = true; } @@ -31,7 +34,8 @@ this._boundOnUpdate = this._onUpdate.bind(this); this._boundOnCanPlay = this._onCanPlay.bind(this); - if (!source.complete) { + if (!source.complete) + { source.addEventListener('canplay', this._boundOnCanPlay); source.addEventListener('canplaythrough', this._boundOnCanPlay); @@ -47,28 +51,35 @@ VideoBaseTexture.prototype.constructor = VideoBaseTexture; module.exports = VideoBaseTexture; -VideoBaseTexture.prototype._onUpdate = function () { - if (this.autoUpdate) { +VideoBaseTexture.prototype._onUpdate = function () +{ + if (this.autoUpdate) + { window.requestAnimationFrame(this._boundOnUpdate); this.needsUpdate = true; } }; -VideoBaseTexture.prototype._onPlayStart = function () { - if (!this.autoUpdate) { +VideoBaseTexture.prototype._onPlayStart = function () +{ + if (!this.autoUpdate) + { window.requestAnimationFrame(this._boundOnUpdate); this.autoUpdate = true; } }; -VideoBaseTexture.prototype._onPlayStop = function () { +VideoBaseTexture.prototype._onPlayStop = function () +{ this.autoUpdate = false; }; -VideoBaseTexture.prototype._onCanPlay = function () { +VideoBaseTexture.prototype._onCanPlay = function () +{ this.hasLoaded = true; - if (this.source) { + if (this.source) + { this.source.removeEventListener('canplay', this._boundOnCanPlay); this.source.removeEventListener('canplaythrough', this._boundOnCanPlay); @@ -78,15 +89,18 @@ this.source.play(); // prevent multiple loaded dispatches.. - if(!this.__loaded){ + if(!this.__loaded) + { this.__loaded = true; this.emit('loaded', this); } } }; -VideoBaseTexture.prototype.destroy = function () { - if (this.source && this.source._pixiId) { +VideoBaseTexture.prototype.destroy = function () +{ + if (this.source && this.source._pixiId) + { utils.BaseTextureCache[ this.source._pixiId ] = null; delete utils.BaseTextureCache[ this.source._pixiId ]; @@ -105,14 +119,17 @@ * @param scaleMode {number} See {@link scaleModes} for possible values * @return {VideoBaseTexture} */ -VideoBaseTexture.fromVideo = function (video, scaleMode) { - if (!video._pixiId) { +VideoBaseTexture.fromVideo = function (video, scaleMode) +{ + if (!video._pixiId) + { video._pixiId = 'video_' + utils.uuid(); } var baseTexture = utils.BaseTextureCache[video._pixiId]; - if (!baseTexture) { + if (!baseTexture) + { baseTexture = new VideoBaseTexture(video, scaleMode); utils.BaseTextureCache[ video._pixiId ] = baseTexture; } @@ -147,17 +164,21 @@ * @param scaleMode {number} See {@link scaleModes} for possible values * @return {VideoBaseTexture} */ -VideoBaseTexture.fromUrl = function (videoSrc, scaleMode) { +VideoBaseTexture.fromUrl = function (videoSrc, scaleMode) +{ var video = document.createElement('video'); // array of objects or strings - if (Array.isArray(videoSrc)) { - for (var i = 0; i < videoSrc.length; ++i) { + if (Array.isArray(videoSrc)) + { + for (var i = 0; i < videoSrc.length; ++i) + { video.appendChild(createSource(videoSrc.src || videoSrc, videoSrc.mime)); } } // single object or string - else { + else + { video.appendChild(createSource(videoSrc.src || videoSrc, videoSrc.mime)); } @@ -169,8 +190,10 @@ VideoBaseTexture.fromUrls = VideoBaseTexture.fromUrl; -function createSource(path, type) { - if (!type) { +function createSource(path, type) +{ + if (!type) + { type = 'video/' + path.substr(path.lastIndexOf('.') + 1); } diff --git a/src/core/utils/EventData.js b/src/core/utils/EventData.js index 5d55a22..8cdf701 100644 --- a/src/core/utils/EventData.js +++ b/src/core/utils/EventData.js @@ -7,7 +7,8 @@ * @param name {string} The string name of the event that was triggered * @param data {object} Arbitrary event data to pass along */ -function EventData(target, name, data) { +function EventData(target, name, data) +{ // for duck typing in the ".on()" function this.__isEventObject = true; @@ -71,7 +72,8 @@ * Stops the propagation of events up the scene graph (prevents bubbling). * */ -EventData.prototype.stopPropagation = function stopPropagation() { +EventData.prototype.stopPropagation = function stopPropagation() +{ this.stopped = true; }; @@ -79,6 +81,7 @@ * Stops the propagation of events to sibling listeners (no longer calls any listeners). * */ -EventData.prototype.stopImmediatePropagation = function stopImmediatePropagation() { +EventData.prototype.stopImmediatePropagation = function stopImmediatePropagation() +{ this.stoppedImmediate = true; }; diff --git a/src/core/utils/EventTarget.js b/src/core/utils/EventTarget.js index 7ae8820..671a151 100644 --- a/src/core/utils/EventTarget.js +++ b/src/core/utils/EventTarget.js @@ -13,14 +13,16 @@ * var em = new MyEmitter(); * em.emit('eventName', 'some data', 'some more data', {}, null, ...); */ -function eventTarget(obj) { +function eventTarget(obj) +{ /** * Return a list of assigned event listeners. * * @param eventName {string} The events that should be listed. * @return {Array} An array of listener functions */ - obj.listeners = function listeners(eventName) { + obj.listeners = function listeners(eventName) + { this._listeners = this._listeners || {}; return this._listeners[eventName] ? this._listeners[eventName].slice() : []; @@ -33,22 +35,26 @@ * @param eventName {string} The name of the event. * @return {boolean} Indication if we've emitted an event. */ - obj.emit = obj.dispatchEvent = function emit(eventName, data) { + obj.emit = obj.dispatchEvent = function emit(eventName, data) + { this._listeners = this._listeners || {}; // fast return when there are no listeners - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return; } //backwards compat with old method ".emit({ type: 'something' })" - if (typeof eventName === 'object') { + if (typeof eventName === 'object') + { data = eventName; eventName = eventName.type; } //ensure we are using a real pixi event - if (!data || data.__isEventObject !== true) { + if (!data || data.__isEventObject !== true) + { data = new EventData(this, eventName, data); } @@ -58,23 +64,27 @@ fn = listeners[0], i; - for (i = 0; i < length; fn = listeners[++i]) { + for (i = 0; i < length; fn = listeners[++i]) + { //call the event listener fn.call(this, data); //if "stopImmediatePropagation" is called, stop calling sibling events - if (data.stoppedImmediate) { + if (data.stoppedImmediate) + { return this; } } //if "stopPropagation" is called then don't bubble the event - if (data.stopped) { + if (data.stopped) + { return this; } //bubble this event up the scene graph - if (this.parent && this.parent.emit) { + if (this.parent && this.parent.emit) + { this.parent.emit.call(this.parent, eventName, data); } @@ -88,7 +98,8 @@ * @param eventName {string} Name of the event. * @param callback {Functon} fn Callback function. */ - obj.on = obj.addEventListener = function on(eventName, fn) { + obj.on = obj.addEventListener = function on(eventName, fn) + { this._listeners = this._listeners || {}; (this._listeners[eventName] = this._listeners[eventName] || []) @@ -103,11 +114,13 @@ * @param eventName {string} Name of the event. * @param callback {Function} Callback function. */ - obj.once = function once(eventName, fn) { + obj.once = function once(eventName, fn) + { this._listeners = this._listeners || {}; var self = this; - function onceHandlerWrapper() { + function onceHandlerWrapper() + { fn.apply(self.off(eventName, onceHandlerWrapper), arguments); } onceHandlerWrapper._originalHandler = fn; @@ -122,23 +135,28 @@ * @param eventName {string} The event we want to remove. * @param callback {Function} The listener that we need to find. */ - obj.off = obj.removeEventListener = function off(eventName, fn) { + obj.off = obj.removeEventListener = function off(eventName, fn) + { this._listeners = this._listeners || {}; - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return this; } var list = this._listeners[eventName], i = fn ? list.length : 0; - while(i-- > 0) { - if (list[i] === fn || list[i]._originalHandler === fn) { + while(i-- > 0) + { + if (list[i] === fn || list[i]._originalHandler === fn) + { list.splice(i, 1); } } - if (list.length === 0) { + if (list.length === 0) + { delete this._listeners[eventName]; } @@ -150,10 +168,12 @@ * * @param eventName {string} The event you want to remove all listeners for. */ - obj.removeAllListeners = function removeAllListeners(eventName) { + obj.removeAllListeners = function removeAllListeners(eventName) + { this._listeners = this._listeners || {}; - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return this; } @@ -169,7 +189,8 @@ * * @param object {object} The obj to mix into */ - mixin: function mixin(obj) { + mixin: function mixin(obj) + { eventTarget(obj); } }; diff --git a/src/core/utils/PolyK.js b/src/core/utils/PolyK.js index 7325141..5e20c2b 100644 --- a/src/core/utils/PolyK.js +++ b/src/core/utils/PolyK.js @@ -47,7 +47,8 @@ * Triangulates shapes for webGL graphic fills. * */ -PolyK.Triangulate = function (p) { +PolyK.Triangulate = function (p) +{ var sign = true; var n = p.length >> 1; @@ -59,7 +60,8 @@ i = 0; var al = n; - while(al > 3) { + while(al > 3) + { var i0 = avl[(i+0)%al]; var i1 = avl[(i+1)%al]; var i2 = avl[(i+2)%al]; @@ -69,29 +71,35 @@ var cx = p[2*i2], cy = p[2*i2+1]; var earFound = false; - if (PolyK._convex(ax, ay, bx, by, cx, cy, sign)) { + if (PolyK._convex(ax, ay, bx, by, cx, cy, sign)) + { earFound = true; - for (var j = 0; j < al; j++) { + for (var j = 0; j < al; j++) + { var vi = avl[j]; if (vi === i0 || vi === i1 || vi === i2) continue; - if (PolyK._PointInTriangle(p[2*vi], p[2*vi+1], ax, ay, bx, by, cx, cy)) { + if (PolyK._PointInTriangle(p[2*vi], p[2*vi+1], ax, ay, bx, by, cx, cy)) + { earFound = false; break; } } } - if (earFound) { + if (earFound) + { tgs.push(i0, i1, i2); avl.splice((i+1)%al, 1); al--; i = 0; } - else if (i++ > 3*al) { + else if (i++ > 3*al) + { // need to flip flip reverse it! // reset! - if (sign) { + if (sign) + { tgs = []; avl = []; for (i = 0; i < n; i++) avl.push(i); @@ -101,7 +109,8 @@ sign = false; } - else { + else + { // window.console.log("PIXI Warning: shape too complex to fill"); return null; } @@ -126,7 +135,8 @@ * @private * @return {boolean} */ -PolyK._PointInTriangle = function (px, py, ax, ay, bx, by, cx, cy) { +PolyK._PointInTriangle = function (px, py, ax, ay, bx, by, cx, cy) +{ var v0x = cx-ax; var v0y = cy-ay; var v1x = bx-ax; @@ -154,6 +164,7 @@ * @private * @return {boolean} */ -PolyK._convex = function (ax, ay, bx, by, cx, cy, sign) { +PolyK._convex = function (ax, ay, bx, by, cx, cy, sign) +{ return ((ay-by)*(cx-bx) + (bx-ax)*(cy-by) >= 0) === sign; }; diff --git a/src/core/utils/index.js b/src/core/utils/index.js index ade9831..bfae7ae 100644 --- a/src/core/utils/index.js +++ b/src/core/utils/index.js @@ -16,7 +16,8 @@ * * @return {number} The next uuid to use. */ - uuid: function () { + uuid: function () + { return ++utils._uid; }, @@ -26,7 +27,8 @@ * @param hex {number} * @return {number[]} An array representing the [R, G, B] of the color. */ - hex2rgb: function (hex, out) { + hex2rgb: function (hex, out) + { out = out || []; out[0] = (hex >> 16 & 0xFF) / 255; @@ -42,7 +44,8 @@ * @param hex {number} * @return {string} The string color. */ - hex2string: function (hex) { + hex2string: function (hex) + { hex = hex.toString(16); hex = '000000'.substr(0, 6 - hex.length) + hex; @@ -55,7 +58,8 @@ * @param rgb {number[]} * @return {number} The color number */ - rgb2hex: function (rgb) { + rgb2hex: function (rgb) + { return ((rgb[0]*255 << 16) + (rgb[1]*255 << 8) + rgb[2]*255); }, @@ -64,8 +68,10 @@ * * @return {boolean} whether they are supported */ - canUseNewCanvasBlendModes: function () { - if (typeof document === 'undefined') { + canUseNewCanvasBlendModes: function () + { + if (typeof document === 'undefined') + { return false; } @@ -93,15 +99,19 @@ * @param number {number} * @return {number} the closest number that is a power of two */ - getNextPowerOfTwo: function (number) { + getNextPowerOfTwo: function (number) + { // see: http://en.wikipedia.org/wiki/Power_of_two#Fast_algorithm_to_check_if_a_positive_number_is_a_power_of_two - if (number > 0 && (number & (number - 1)) === 0) { + if (number > 0 && (number & (number - 1)) === 0) + { return number; } - else { + else + { var result = 1; - while (result < number) { + while (result < number) + { result <<= 1; } @@ -116,7 +126,8 @@ * @param height {number} * @return {boolean} */ - isPowerOfTwo: function (width, height) { + isPowerOfTwo: function (width, height) + { return (width > 0 && (width & (width - 1)) === 0 && height > 0 && (height & (height - 1)) === 0); }, @@ -130,12 +141,15 @@ * @constant * @static */ - sayHello: function (type) { - if (utils._saidHello) { + sayHello: function (type) + { + if (utils._saidHello) + { return; } - if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) { + if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) + { var args = [ '%c %c %c Pixi.js ' + CONST.VERSION + ' - ' + type + ' %c ' + ' %c ' + ' http://www.pixijs.com/ %c %c ♥%c♥%c♥ ', 'background: #ff66a5', @@ -151,7 +165,8 @@ console.log.apply(console, args); //jshint ignore:line } - else if (window.console) { + else if (window.console) + { console.log('Pixi.js ' + CONST.VERSION + ' - ' + type + ' - http://www.pixijs.com/'); //jshint ignore:line } @@ -166,15 +181,19 @@ * @class * @namespace PIXI */ - AjaxRequest: function () { + AjaxRequest: function () + { var activexmodes = ['Msxml2.XMLHTTP.6.0', 'Msxml2.XMLHTTP.3.0', 'Microsoft.XMLHTTP']; //activeX versions to check for in IE - if (window.ActiveXObject) { //Test for support for ActiveXObject in IE first (as XMLHttpRequest in IE7 is broken) - for (var i=0; i= this.textures.length) { + else if (round >= this.textures.length) + { this.gotoAndStop(this.textures.length - 1); - if (this.onComplete) { + if (this.onComplete) + { this.onComplete(); } } @@ -167,10 +182,12 @@ * @static * @param frames {string[]} the array of frames ids the movieclip will use as its texture frames */ -MovieClip.fromFrames = function (frames) { +MovieClip.fromFrames = function (frames) +{ var textures = []; - for (var i = 0; i < frames.length; ++i) { + for (var i = 0; i < frames.length; ++i) + { textures.push(new core.Texture.fromFrame(frames[i])); } @@ -183,10 +200,12 @@ * @static * @param images {string[]} the array of image urls the movieclip will use as its texture frames */ -MovieClip.fromImages = function (images) { +MovieClip.fromImages = function (images) +{ var textures = []; - for (var i = 0; i < images.length; ++i) { + for (var i = 0; i < images.length; ++i) + { textures.push(new core.Texture.fromImage(images[i])); } diff --git a/src/extras/Rope.js b/src/extras/Rope.js index c157ec4..9c87bc0 100644 --- a/src/extras/Rope.js +++ b/src/extras/Rope.js @@ -9,7 +9,8 @@ * @param {Array} points - An array of {Point}. * */ -function Rope(texture, points) { +function Rope(texture, points) +{ Strip.call(this, texture); this.points = points; @@ -31,10 +32,12 @@ * Refreshes * */ -Rope.prototype.refresh = function () { +Rope.prototype.refresh = function () +{ var points = this.points; - if (points.length < 1) { + if (points.length < 1) + { return; } @@ -59,20 +62,23 @@ var total = points.length, point, index, amount; - for (var i = 1; i < total; i++) { + for (var i = 1; i < total; i++) + { point = points[i]; index = i * 4; // time to do some smart drawing! amount = i / (total-1); - if (i%2) { + if (i%2) + { uvs[index] = amount; uvs[index+1] = 0; uvs[index+2] = amount; uvs[index+3] = 1; } - else { + else + { uvs[index] = amount; uvs[index+1] = 0; @@ -95,10 +101,12 @@ * * @private */ -Rope.prototype.updateTransform = function () { +Rope.prototype.updateTransform = function () +{ var points = this.points; - if (points.length < 1) { + if (points.length < 1) + { return; } @@ -113,14 +121,17 @@ var total = points.length, point, index, ratio, perpLength, num; - for (var i = 0; i < total; i++) { + for (var i = 0; i < total; i++) + { point = points[i]; index = i * 4; - if (i < points.length-1) { + if (i < points.length-1) + { nextPoint = points[i+1]; } - else { + else + { nextPoint = point; } @@ -129,7 +140,8 @@ ratio = (1 - (i / (total-1))) * 10; - if (ratio > 1) { + if (ratio > 1) + { ratio = 1; } @@ -157,7 +169,8 @@ * * @param texture {Texture} the texture that will be used */ -Rope.prototype.setTexture = function (texture) { +Rope.prototype.setTexture = function (texture) +{ // stop current texture this.texture = texture; //this.updateFrame = true; diff --git a/src/extras/Strip.js b/src/extras/Strip.js index c5e378f..57691b5 100644 --- a/src/extras/Strip.js +++ b/src/extras/Strip.js @@ -10,7 +10,8 @@ * @param height {number} the height * */ -function Strip(texture) { +function Strip(texture) +{ core.DisplayObjectContainer.call(this); /** @@ -70,9 +71,11 @@ * * @param renderer {WebGLRenderer} */ -Strip.prototype.renderWebGL = function (renderer) { +Strip.prototype.renderWebGL = function (renderer) +{ // if the sprite is not visible or the alpha is 0 then no need to render this element - if (!this.visible || this.alpha <= 0) { + if (!this.visible || this.alpha <= 0) + { return; } @@ -81,7 +84,8 @@ renderer.spriteBatch.stop(); // init! init! - if (!this._vertexBuffer) { + if (!this._vertexBuffer) + { this._initWebGL(renderer); } @@ -96,7 +100,8 @@ //TODO check culling }; -Strip.prototype._initWebGL = function (renderer) { +Strip.prototype._initWebGL = function (renderer) +{ // build the strip! var gl = renderer.gl; @@ -118,7 +123,8 @@ gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this.indices, gl.STATIC_DRAW); }; -Strip.prototype._renderStrip = function (renderer) { +Strip.prototype._renderStrip = function (renderer) +{ var gl = renderer.gl; var projection = renderer.projection, offset = renderer.offset, @@ -137,7 +143,8 @@ gl.uniform2f(shader.offsetVector, -offset.x, -offset.y); gl.uniform1f(shader.alpha, this.worldAlpha); - if (!this.dirty) { + if (!this.dirty) + { gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexBuffer); gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); @@ -150,10 +157,12 @@ gl.activeTexture(gl.TEXTURE0); // check if a texture is dirty.. - if (this.texture.baseTexture._dirty[gl.id]) { + if (this.texture.baseTexture._dirty[gl.id]) + { renderer.updateTexture(this.texture.baseTexture); } - else { + else + { // bind the current texture gl.bindTexture(gl.TEXTURE_2D, this.texture.baseTexture._glTextures[gl.id]); } @@ -163,7 +172,8 @@ } - else { + else + { this.dirty = false; gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexBuffer); @@ -178,10 +188,12 @@ gl.activeTexture(gl.TEXTURE0); // check if a texture is dirty.. - if (this.texture.baseTexture._dirty[gl.id]) { + if (this.texture.baseTexture._dirty[gl.id]) + { renderer.updateTexture(this.texture.baseTexture); } - else { + else + { gl.bindTexture(gl.TEXTURE_2D, this.texture.baseTexture._glTextures[gl.id]); } @@ -203,27 +215,33 @@ * * @param renderer {CanvasRenderer} */ -Strip.prototype.renderCanvas = function (renderer) { +Strip.prototype.renderCanvas = function (renderer) +{ var context = renderer.context; var transform = this.worldTransform; - if (renderer.roundPixels) { + if (renderer.roundPixels) + { context.setTransform(transform.a, transform.b, transform.c, transform.d, transform.tx | 0, transform.ty | 0); } - else { + else + { context.setTransform(transform.a, transform.b, transform.c, transform.d, transform.tx, transform.ty); } - if (this.drawMode === Strip.DrawModes.TRIANGLE_STRIP) { + if (this.drawMode === Strip.DrawModes.TRIANGLE_STRIP) + { this._renderCanvasTriangleStrip(context); } - else { + else + { this._renderCanvasTriangles(context); } }; -Strip.prototype._renderCanvasTriangleStrip = function (context) { +Strip.prototype._renderCanvasTriangleStrip = function (context) +{ // draw triangles!! var vertices = this.vertices; var uvs = this.uvs; @@ -231,14 +249,16 @@ var length = vertices.length / 2; // this.count++; - for (var i = 0; i < length - 2; i++) { + for (var i = 0; i < length - 2; i++) + { // draw some triangles! var index = i * 2; this._renderCanvasDrawTriangle(context, vertices, uvs, index, (index + 2), (index + 4)); } }; -Strip.prototype._renderCanvasTriangles = function (context) { +Strip.prototype._renderCanvasTriangles = function (context) +{ // draw triangles!! var vertices = this.vertices; var uvs = this.uvs; @@ -247,14 +267,16 @@ var length = indices.length; // this.count++; - for (var i = 0; i < length; i += 3) { + for (var i = 0; i < length; i += 3) + { // draw some triangles! var index0 = indices[i] * 2, index1 = indices[i + 1] * 2, index2 = indices[i + 2] * 2; this._renderCanvasDrawTriangle(context, vertices, uvs, index0, index1, index2); } }; -Strip.prototype._renderCanvasDrawTriangle = function (context, vertices, uvs, index0, index1, index2) { +Strip.prototype._renderCanvasDrawTriangle = function (context, vertices, uvs, index0, index1, index2) +{ var textureSource = this.texture.baseTexture.source; var textureWidth = this.texture.width; var textureHeight = this.texture.height; @@ -265,7 +287,8 @@ var u0 = uvs[index0] * textureWidth, u1 = uvs[index1] * textureWidth, u2 = uvs[index2] * textureWidth; var v0 = uvs[index0 + 1] * textureHeight, v1 = uvs[index1 + 1] * textureHeight, v2 = uvs[index2 + 1] * textureHeight; - if (this.canvasPadding > 0) { + if (this.canvasPadding > 0) + { var paddingX = this.canvasPadding / this.worldTransform.a; var paddingY = this.canvasPadding / this.worldTransform.d; var centerX = (x0 + x1 + x2) / 3; @@ -332,7 +355,8 @@ * @param strip {Strip} The Strip to render * @private */ -Strip.prototype.renderStripFlat = function (strip) { +Strip.prototype.renderStripFlat = function (strip) +{ var context = this.context; var vertices = strip.vertices; @@ -340,7 +364,8 @@ // this.count++; context.beginPath(); - for (var i=1; i < length-2; i++) { + for (var i=1; i < length-2; i++) + { // draw some triangles! var index = i*2; @@ -358,7 +383,8 @@ }; /* -Strip.prototype.setTexture = function (texture) { +Strip.prototype.setTexture = function (texture) +{ //TODO SET THE TEXTURES //TODO VISIBILITY @@ -377,7 +403,8 @@ * @private */ -Strip.prototype.onTextureUpdate = function () { +Strip.prototype.onTextureUpdate = function () +{ this.updateFrame = true; }; @@ -387,7 +414,8 @@ * @param matrix {Matrix} the transformation matrix of the sprite * @return {Rectangle} the framing rectangle */ -Strip.prototype.getBounds = function (matrix) { +Strip.prototype.getBounds = function (matrix) +{ var worldTransform = matrix || this.worldTransform; var a = worldTransform.a; @@ -404,7 +432,8 @@ var minY = Infinity; var vertices = this.vertices; - for (var i = 0, n = vertices.length; i < n; i += 2) { + for (var i = 0, n = vertices.length; i < n; i += 2) + { var rawX = vertices[i], rawY = vertices[i + 1]; var x = (a * rawX) + (c * rawY) + tx; var y = (d * rawY) + (b * rawX) + ty; @@ -416,7 +445,8 @@ maxY = y > maxY ? y : maxY; } - if (minX === -Infinity || maxY === Infinity) { + if (minX === -Infinity || maxY === Infinity) + { return core.math.Rectangle.EMPTY; } diff --git a/src/extras/TilingSprite.js b/src/extras/TilingSprite.js index 3ac22df..31da393 100644 --- a/src/extras/TilingSprite.js +++ b/src/extras/TilingSprite.js @@ -10,7 +10,8 @@ * @param width {number} the width of the tiling sprite * @param height {number} the height of the tiling sprite */ -function TilingSprite(texture, width, height) { +function TilingSprite(texture, width, height) +{ core.Sprite.call( this, texture); /** @@ -86,10 +87,12 @@ * @memberof TilingSprite# */ width: { - get: function () { + get: function () + { return this._width; }, - set: function (value) { + set: function (value) + { this._width = value; } }, @@ -101,20 +104,25 @@ * @memberof TilingSprite# */ height: { - get: function () { + get: function () + { return this._height; }, - set: function (value) { + set: function (value) + { this._height = value; } }, texture: { - get: function () { + get: function () + { return this._texture; }, - set: function (value) { - if (this._texture === value) { + set: function (value) + { + if (this._texture === value) + { return; } @@ -130,51 +138,61 @@ * * @param renderer {WebGLRenderer} */ -TilingSprite.prototype.renderWebGL = function (renderer) { - if (!this.visible || this.alpha <= 0) { +TilingSprite.prototype.renderWebGL = function (renderer) +{ + if (!this.visible || this.alpha <= 0) + { return; } var i, j; - if (this._mask) { + if (this._mask) + { renderer.spriteBatch.stop(); renderer.maskManager.pushMask(this.mask, renderer); renderer.spriteBatch.start(); } - if (this._filters) { + if (this._filters) + { renderer.spriteBatch.flush(); renderer.filterManager.pushFilter(this._filterBlock); } - if (!this.tilingTexture || this.refreshTexture) { + if (!this.tilingTexture || this.refreshTexture) + { this.generateTilingTexture(true); - if (this.tilingTexture && this.tilingTexture.needsUpdate) { + if (this.tilingTexture && this.tilingTexture.needsUpdate) + { //TODO - tweaking renderer.updateTexture(this.tilingTexture.baseTexture); this.tilingTexture.needsUpdate = false; // this.tilingTexture._uvs = null; } } - else { + else + { renderer.spriteBatch.renderTilingSprite(this); } // simple render children! - for (i=0,j=this.children.length; i= 0 && index <= this.children.length) { - if (child.parent) { + if (index >= 0 && index <= this.children.length) + { + if (child.parent) + { child.parent.removeChild(child); } @@ -154,7 +173,8 @@ return child; } - else { + else + { throw new Error(child + 'addChildAt: The index '+ index +' supplied is out of bounds ' + this.children.length); } }; @@ -165,15 +185,18 @@ * @param child {DisplayObject} * @param child2 {DisplayObject} */ -DisplayObjectContainer.prototype.swapChildren = function (child, child2) { - if (child === child2) { +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) { + if (index1 < 0 || index2 < 0) + { throw new Error('swapChildren: Both the supplied DisplayObjects must be a child of the caller.'); } @@ -187,10 +210,12 @@ * @param child {DisplayObject} The DisplayObject instance to identify * @return {Number} The index position of the child display object to identify */ -DisplayObjectContainer.prototype.getChildIndex = function (child) { +DisplayObjectContainer.prototype.getChildIndex = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { throw new Error('The supplied DisplayObject must be a child of the caller'); } @@ -203,8 +228,10 @@ * @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 */ -DisplayObjectContainer.prototype.setChildIndex = function (child, index) { - if (index < 0 || index >= this.children.length) { +DisplayObjectContainer.prototype.setChildIndex = function (child, index) +{ + if (index < 0 || index >= this.children.length) + { throw new Error('The supplied index is out of bounds'); } @@ -220,8 +247,10 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child at the given index, if any. */ -DisplayObjectContainer.prototype.getChildAt = function (index) { - if (index < 0 || index >= this.children.length) { +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'); } @@ -234,10 +263,12 @@ * @param child {DisplayObject} The DisplayObject to remove * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChild = function (child) { +DisplayObjectContainer.prototype.removeChild = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { return; } @@ -250,7 +281,8 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChildAt = function (index) { +DisplayObjectContainer.prototype.removeChildAt = function (index) +{ var child = this.getChildAt(index); child.parent = null; @@ -265,24 +297,29 @@ * @param beginIndex {Number} The beginning position. Default value is 0. * @param endIndex {Number} The ending position. Default value is size of the container. */ -DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) { +DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) +{ var begin = beginIndex || 0; var end = typeof endIndex === 'number' ? endIndex : this.children.length; var range = end - begin; - if (range > 0 && range <= end) { + if (range > 0 && range <= end) + { var removed = this.children.splice(begin, range); - for (var i = 0; i < removed.length; ++i) { + for (var i = 0; i < removed.length; ++i) + { removed[i].parent = null; } return removed; } - else if (range === 0 && this.children.length === 0) { + else if (range === 0 && this.children.length === 0) + { return []; } - else { + else + { throw new RangeError('removeChildren: numeric values are outside the acceptable range.'); } }; @@ -291,7 +328,8 @@ * Generates and updates the cached sprite for this object. * */ -DisplayObjectContainer.prototype.updateCachedSprite = function () { +DisplayObjectContainer.prototype.updateCachedSprite = function () +{ this._generateCachedSprite(); }; @@ -304,7 +342,8 @@ * @param renderer {CanvasRenderer|WebGLRenderer} The renderer used to generate the texture. * @return {Texture} a texture of the graphics object */ -DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) { +DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) +{ var bounds = this.getLocalBounds(); var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0, renderer, scaleMode, resolution); @@ -322,18 +361,22 @@ * * @private */ -DisplayObjectContainer.prototype.updateTransform = function () { - if (!this.visible) { +DisplayObjectContainer.prototype.updateTransform = function () +{ + if (!this.visible) + { return; } this.displayObjectUpdateTransform(); - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { return; } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } }; @@ -346,8 +389,10 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getBounds = function () { - if (this.children.length === 0) { +DisplayObjectContainer.prototype.getBounds = function () +{ + if (this.children.length === 0) + { return math.Rectangle.EMPTY; } @@ -365,10 +410,12 @@ var childVisible = false; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -386,7 +433,8 @@ maxY = maxY > childMaxY ? maxY : childMaxY; } - if (!childVisible) { + if (!childVisible) + { return math.Rectangle.EMPTY; } @@ -407,12 +455,14 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getLocalBounds = function () { +DisplayObjectContainer.prototype.getLocalBounds = function () +{ var matrixCache = this.worldTransform; this.worldTransform = math.Matrix.IDENTITY; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } @@ -428,13 +478,16 @@ * * @param renderer {WebGLRenderer} The renderer */ -DisplayObjectContainer.prototype.renderWebGL = function (renderer) { +DisplayObjectContainer.prototype.renderWebGL = function (renderer) +{ // if the object is not visible or the alpha is 0 then no need to render this element - if (!this.visible || this.alpha <= 0) { + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } @@ -442,14 +495,17 @@ var i, j; // do a quick check to see if this element has a mask or a filter. - if (this._mask || this._filters) { + if (this._mask || this._filters) + { // push filter first as we need to ensure the stencil buffer is correct for any masking - if (this._filters) { + if (this._filters) + { renderer.spriteBatch.flush(); renderer.filterManager.pushFilter(this._filterBlock); } - if (this._mask) { + if (this._mask) + { renderer.spriteBatch.stop(); renderer.maskManager.pushMask(this.mask, renderer); renderer.spriteBatch.start(); @@ -459,36 +515,42 @@ this._renderWebGL(renderer); // now loop through the children and make sure they get rendered - for (i = 0, j = this.children.length; i < j; i++) { + for (i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderWebGL(renderer); } // time to stop the sprite batch as either a mask element or a filter draw will happen next renderer.spriteBatch.stop(); - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(this._mask, renderer); } - if (this._filters) { + if (this._filters) + { renderer.filterManager.popFilter(); } renderer.spriteBatch.start(); } - else { + else + { this._renderWebGL(renderer); // simple render children! - for (i = 0, j = this.children.length; i < j; ++i) { + for (i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderWebGL(renderer); } } }; -DisplayObjectContainer.prototype._renderWebGL = function (renderer) { +DisplayObjectContainer.prototype._renderWebGL = function (renderer) +{ // this is where content itself gets renderd.. @@ -499,25 +561,31 @@ * * @param renderer {CanvasRenderer} The renderer */ -DisplayObjectContainer.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0) { +DisplayObjectContainer.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -528,13 +596,16 @@ * @param renderer {WebGLRenderer|CanvasRenderer} The renderer * @private */ -DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) { +DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) +{ this._cachedSprite.worldAlpha = this.worldAlpha; - if (renderer.gl) { + if (renderer.gl) + { this._cachedSprite.renderWebGL(renderer); } - else { + else + { this._cachedSprite.renderCanvas(renderer); } }; @@ -544,10 +615,12 @@ * * @private */ -DisplayObjectContainer.prototype._generateCachedSprite = function () { +DisplayObjectContainer.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { // TODO - RenderTexture now *requires* a renderer instance, so this is like broken // because `renderer` isn't actually in scope here :P var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0); @@ -555,7 +628,8 @@ this._cachedSprite = new Sprite(renderTexture); this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.texture.resize(bounds.width | 0, bounds.height | 0); } @@ -580,8 +654,10 @@ * * @private */ -DisplayObjectContainer.prototype._destroyCachedSprite = function () { - if (!this._cachedSprite) { +DisplayObjectContainer.prototype._destroyCachedSprite = function () +{ + if (!this._cachedSprite) + { return; } diff --git a/src/core/display/Sprite.js b/src/core/display/Sprite.js index 707da24..5862aef 100644 --- a/src/core/display/Sprite.js +++ b/src/core/display/Sprite.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param texture {Texture} The texture for this sprite */ -function Sprite(texture) { +function Sprite(texture) +{ DisplayObjectContainer.call(this); /** @@ -85,12 +86,14 @@ this.texture = texture || Texture.EMPTY; } -Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) { +Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) +{ DisplayObjectContainer.prototype.destroy.call(this); this.anchor = null; - if (destroyTexture) { + if (destroyTexture) + { this._texture.destroy(destroyBaseTexture); } @@ -111,10 +114,12 @@ * @memberof Sprite# */ width: { - get: function () { + get: function () + { return this.scale.x * this.texture.frame.width; }, - set: function (value) { + set: function (value) + { this.scale.x = value / this.texture.frame.width; this._width = value; } @@ -127,10 +132,12 @@ * @memberof Sprite# */ height: { - get: function () { + get: function () + { return this.scale.y * this.texture.frame.height; }, - set: function (value) { + set: function (value) + { this.scale.y = value / this.texture.frame.height; this._height = value; } @@ -143,23 +150,29 @@ * @memberof Sprite# */ texture: { - get: function () { + get: function () + { return this._texture; }, - set: function (value) { - if (this._texture === value) { + set: function (value) + { + if (this._texture === value) + { return; } this._texture = value; this.cachedTint = 0xFFFFFF; - if (value) { + if (value) + { // wait for the texture to load - if (value.baseTexture.hasLoaded) { + if (value.baseTexture.hasLoaded) + { this._onTextureUpdate(); } - else { + else + { value.once('update', this._onTextureUpdate.bind(this)); } } @@ -172,18 +185,22 @@ * * @private */ -Sprite.prototype._onTextureUpdate = function () { +Sprite.prototype._onTextureUpdate = function () +{ // so if _width is 0 then width was not set.. - if (this._width) { + if (this._width) + { this.scale.x = this._width / this.texture.frame.width; } - if (this._height) { + if (this._height) + { this.scale.y = this._height / this.texture.frame.height; } }; -Sprite.prototype._renderWebGL = function (renderer) { +Sprite.prototype._renderWebGL = function (renderer) +{ // this is where content gets renderd.. // watch this space for a little render state manager.. @@ -197,7 +214,8 @@ * @param matrix {Matrix} the transformation matrix of the sprite * @return {Rectangle} the framing rectangle */ -Sprite.prototype.getBounds = function (matrix) { +Sprite.prototype.getBounds = function (matrix) +{ var width = this.texture.frame.width; var height = this.texture.frame.height; @@ -224,11 +242,13 @@ if(b === 0 && c === 0) { // scale may be negative! - if (a < 0) { + if (a < 0) + { a *= -1; } - if (d < 0) { + if (d < 0) + { d *= -1; } @@ -293,28 +313,34 @@ * * @param renderer {CanvasRenderer} The renderer */ -Sprite.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) { +Sprite.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) + { return; } - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; renderer.context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } // Ignore null sources - if (this.texture.valid) { + if (this.texture.valid) + { var resolution = this.texture.baseTexture.resolution / renderer.resolution; renderer.context.globalAlpha = this.worldAlpha; // If smoothingEnabled is supported and we need to change the smoothing property for this texture - if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) { + if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) + { renderer.scaleMode = this.texture.baseTexture.scaleMode; renderer.context[renderer.smoothProperty] = (renderer.scaleMode === CONST.scaleModes.LINEAR); } @@ -324,7 +350,8 @@ var dy = (this.texture.trim ? this.texture.trim.y : 0) - (this.anchor.y * this.texture.trim.height); // Allow for pixel rounding - if (renderer.roundPixels) { + if (renderer.roundPixels) + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -337,7 +364,8 @@ dx = dx | 0; dy = dy | 0; } - else { + else + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -348,8 +376,10 @@ ); } - if (this.tint !== 0xFFFFFF) { - if (this.cachedTint !== this.tint) { + if (this.tint !== 0xFFFFFF) + { + if (this.cachedTint !== this.tint) + { this.cachedTint = this.tint; // TODO clean up caching - how to clean up the caches? @@ -368,7 +398,8 @@ this.texture.crop.height / resolution ); } - else { + else + { renderer.context.drawImage( this.texture.baseTexture.source, this.texture.crop.x, @@ -383,11 +414,13 @@ } } - for (var i = 0, j = this.children.length; i < j; i++) { + for (var i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -402,10 +435,12 @@ * @param frameId {String} The frame Id of the texture in the cache * @return {Sprite} A new Sprite using a texture from the texture cache matching the frameId */ -Sprite.fromFrame = function (frameId) { +Sprite.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache' + this); } @@ -420,6 +455,7 @@ * @param imageId {String} The image url of the texture * @return {Sprite} A new Sprite using a texture from the texture cache matching the image id */ -Sprite.fromImage = function (imageId, crossorigin, scaleMode) { +Sprite.fromImage = function (imageId, crossorigin, scaleMode) +{ return new Sprite(Texture.fromImage(imageId, crossorigin, scaleMode)); }; diff --git a/src/core/display/SpriteBatch.js b/src/core/display/SpriteBatch.js index 3187777..c196fef 100644 --- a/src/core/display/SpriteBatch.js +++ b/src/core/display/SpriteBatch.js @@ -12,7 +12,8 @@ * ```js * var container = new SpriteBatch(); * - * for(var i = 0; i < 100; ++i) { + * for(var i = 0; i < 100; ++i) + * { * var sprite = new PIXI.Sprite.fromImage("myImage.png"); * container.addChild(sprite); * } @@ -25,7 +26,8 @@ */ //TODO RENAME to PARTICLE CONTAINER? -function SpriteBatch() { +function SpriteBatch() +{ DisplayObjectContainer.call(this); } @@ -38,7 +40,8 @@ * * @private */ -SpriteBatch.prototype.updateTransform = function () { +SpriteBatch.prototype.updateTransform = function () +{ // TODO don't need to! this.displayObjectUpdateTransform(); // PIXI.DisplayObjectContainer.prototype.updateTransform.call( this ); @@ -50,8 +53,10 @@ * @param renderer {WebGLRenderer} The webgl renderer * @private */ -SpriteBatch.prototype.renderWebGL = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderWebGL = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -71,8 +76,10 @@ * @param renderer {CanvasRenderer} The canvas renderer * @private */ -SpriteBatch.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -84,10 +91,12 @@ this.displayObjectUpdateTransform(); - for (var i = 0; i < this.children.length; ++i) { + for (var i = 0; i < this.children.length; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -95,9 +104,11 @@ context.globalAlpha = this.worldAlpha * child.alpha; - if (child.rotation % (Math.PI * 2) === 0) { + if (child.rotation % (Math.PI * 2) === 0) + { // this is the fastest way to optimise! - if rotation is 0 then we can avoid any kind of setTransform call - if (isRotated) { + if (isRotated) + { context.setTransform( transform.a, transform.b, @@ -122,8 +133,10 @@ frame.height * child.scale.y ); } - else { - if (!isRotated) { + else + { + if (!isRotated) + { isRotated = true; } @@ -131,7 +144,8 @@ var childTransform = child.worldTransform; - if (renderer.roundPixels) { + if (renderer.roundPixels) + { context.setTransform( childTransform.a, childTransform.b, @@ -141,7 +155,8 @@ childTransform.ty | 0 ); } - else { + else + { context.setTransform( childTransform.a, childTransform.b, diff --git a/src/core/index.js b/src/core/index.js index 3954b6f..eb4a82b 100644 --- a/src/core/index.js +++ b/src/core/index.js @@ -58,11 +58,13 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRenderer: function (width, height, options, noWebGL) { + autoDetectRenderer: function (width, height, options, noWebGL) + { width = width || 800; height = height || 600; - if (!noWebGL && require('webgl-enabled')()) { + if (!noWebGL && require('webgl-enabled')()) + { return new core.WebGLRenderer(width, height, options); } @@ -87,7 +89,8 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRecommendedRenderer: function (width, height, options) { + autoDetectRecommendedRenderer: function (width, height, options) + { var isAndroid = /Android/i.test(navigator.userAgent); return core.autoDetectRenderer(width, height, options, isAndroid); diff --git a/src/core/math/Matrix.js b/src/core/math/Matrix.js index c2f87e2..2ff4848 100644 --- a/src/core/math/Matrix.js +++ b/src/core/math/Matrix.js @@ -10,7 +10,8 @@ * @class * @namespace PIXI */ -function Matrix() { +function Matrix() +{ /** * @member {number} * @default 1 @@ -63,7 +64,8 @@ * * @param array {number[]} The array that the matrix will be populated from. */ -Matrix.prototype.fromArray = function (array) { +Matrix.prototype.fromArray = function (array) +{ this.a = array[0]; this.b = array[1]; this.c = array[3]; @@ -78,14 +80,17 @@ * @param transpose {boolean} Whether we need to transpose the matrix or not * @return {number[]} the newly created array which contains the matrix */ -Matrix.prototype.toArray = function (transpose) { - if (!this.array) { +Matrix.prototype.toArray = function (transpose) +{ + if (!this.array) + { this.array = new Float32Array(9); } var array = this.array; - if (transpose) { + if (transpose) + { array[0] = this.a; array[1] = this.b; array[2] = 0; @@ -96,7 +101,8 @@ array[7] = this.ty; array[8] = 1; } - else { + else + { array[0] = this.a; array[1] = this.c; array[2] = this.tx; @@ -119,7 +125,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, transformed through this matrix */ -Matrix.prototype.apply = function (pos, newPos) { +Matrix.prototype.apply = function (pos, newPos) +{ newPos = newPos || new Point(); newPos.x = this.a * pos.x + this.c * pos.y + this.tx; @@ -136,7 +143,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, inverse-transformed through this matrix */ -Matrix.prototype.applyInverse = function (pos, newPos) { +Matrix.prototype.applyInverse = function (pos, newPos) +{ newPos = newPos || new Point(); var id = 1 / (this.a * this.d + this.c * -this.b); @@ -154,7 +162,8 @@ * @param {number} y * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.translate = function (x, y) { +Matrix.prototype.translate = function (x, y) +{ this.tx += x; this.ty += y; @@ -168,7 +177,8 @@ * @param {number} y The amount to scale vertically * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.scale = function (x, y) { +Matrix.prototype.scale = function (x, y) +{ this.a *= x; this.d *= y; this.c *= x; @@ -186,7 +196,8 @@ * @param {number} angle - The angle in radians. * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.rotate = function (angle) { +Matrix.prototype.rotate = function (angle) +{ var cos = Math.cos( angle ); var sin = Math.sin( angle ); @@ -210,7 +221,8 @@ * @param {Matrix} matrix * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.append = function (matrix) { +Matrix.prototype.append = function (matrix) +{ var a1 = this.a; var b1 = this.b; var c1 = this.c; @@ -232,7 +244,8 @@ * * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.identity = function () { +Matrix.prototype.identity = function () +{ this.a = 1; this.b = 0; this.c = 0; diff --git a/src/core/math/Point.js b/src/core/math/Point.js index 7565b2d..632f346 100644 --- a/src/core/math/Point.js +++ b/src/core/math/Point.js @@ -7,7 +7,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -function Point(x, y) { +function Point(x, y) +{ /** * @member {number} * @default 0 @@ -29,7 +30,8 @@ * * @return {Point} a copy of the point */ -Point.prototype.clone = function () { +Point.prototype.clone = function () +{ return new Point(this.x, this.y); }; @@ -40,7 +42,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -Point.prototype.set = function (x, y) { +Point.prototype.set = function (x, y) +{ this.x = x || 0; this.y = y || ( (y !== 0) ? this.x : 0 ) ; }; diff --git a/src/core/math/shapes/Circle.js b/src/core/math/shapes/Circle.js index 69cfdc9..4d76efc 100644 --- a/src/core/math/shapes/Circle.js +++ b/src/core/math/shapes/Circle.js @@ -10,7 +10,8 @@ * @param y {number} The Y coordinate of the center of this circle * @param radius {number} The radius of the circle */ -function Circle(x, y, radius) { +function Circle(x, y, radius) +{ /** * @member {number} * @default 0 @@ -46,7 +47,8 @@ * @method clone * @return {Circle} a copy of the Circle */ -Circle.prototype.clone = function () { +Circle.prototype.clone = function () +{ return new Circle(this.x, this.y, this.radius); }; @@ -58,8 +60,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Circle */ -Circle.prototype.contains = function (x, y) { - if (this.radius <= 0) { +Circle.prototype.contains = function (x, y) +{ + if (this.radius <= 0) + { return false; } @@ -79,6 +83,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Circle.prototype.getBounds = function () { +Circle.prototype.getBounds = function () +{ return new Rectangle(this.x - this.radius, this.y - this.radius, this.radius * 2, this.radius * 2); }; diff --git a/src/core/math/shapes/Ellipse.js b/src/core/math/shapes/Ellipse.js index 4f2d066..fefd01a 100644 --- a/src/core/math/shapes/Ellipse.js +++ b/src/core/math/shapes/Ellipse.js @@ -11,7 +11,8 @@ * @param width {number} The half width of this ellipse * @param height {number} The half height of this ellipse */ -function Ellipse(x, y, width, height) { +function Ellipse(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -53,7 +54,8 @@ * @method clone * @return {Ellipse} a copy of the ellipse */ -Ellipse.prototype.clone = function () { +Ellipse.prototype.clone = function () +{ return new Ellipse(this.x, this.y, this.width, this.height); }; @@ -65,8 +67,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coords are within this ellipse */ -Ellipse.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Ellipse.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } @@ -86,6 +90,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Ellipse.prototype.getBounds = function () { +Ellipse.prototype.getBounds = function () +{ return new Rectangle(this.x - this.width, this.y - this.height, this.width, this.height); }; diff --git a/src/core/math/shapes/Polygon.js b/src/core/math/shapes/Polygon.js index ae89148..fea6d37 100644 --- a/src/core/math/shapes/Polygon.js +++ b/src/core/math/shapes/Polygon.js @@ -10,16 +10,20 @@ * arguments passed can be flat x,y values e.g. `new Polygon(x,y, x,y, x,y, ...)` where `x` and `y` are * Numbers. */ -function Polygon(points) { +function Polygon(points) +{ //if points isn't an array, use arguments as the array - if (!(points instanceof Array)) { + if (!(points instanceof Array)) + { points = Array.prototype.slice.call(arguments); } //if this is a flat array of numbers, convert it to points - if (points[0] instanceof Point) { + if (points[0] instanceof Point) + { var p = []; - for (var i = 0, il = points.length; i < il; i++) { + for (var i = 0, il = points.length; i < il; i++) + { p.push(points[i].x, points[i].y); } @@ -51,7 +55,8 @@ * * @return {Polygon} a copy of the polygon */ -Polygon.prototype.clone = function () { +Polygon.prototype.clone = function () +{ return new Polygon(this.points.slice()); }; @@ -62,19 +67,22 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this polygon */ -Polygon.prototype.contains = function (x, y) { +Polygon.prototype.contains = function (x, y) +{ var inside = false; // use some raycasting to test hits // https://github.com/substack/point-in-polygon/blob/master/index.js var length = this.points.length / 2; - for (var i = 0, j = length - 1; i < length; j = i++) { + for (var i = 0, j = length - 1; i < length; j = i++) + { var xi = this.points[i * 2], yi = this.points[i * 2 + 1], xj = this.points[j * 2], yj = this.points[j * 2 + 1], intersect = ((yi > y) !== (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi); - if (intersect) { + if (intersect) + { inside = !inside; } } diff --git a/src/core/math/shapes/Rectangle.js b/src/core/math/shapes/Rectangle.js index 16ac62a..4008b68 100644 --- a/src/core/math/shapes/Rectangle.js +++ b/src/core/math/shapes/Rectangle.js @@ -10,7 +10,8 @@ * @param width {number} The overall width of this rectangle * @param height {number} The overall height of this rectangle */ -function Rectangle(x, y, width, height) { +function Rectangle(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -60,7 +61,8 @@ * * @return {Rectangle} a copy of the rectangle */ -Rectangle.prototype.clone = function () { +Rectangle.prototype.clone = function () +{ return new Rectangle(this.x, this.y, this.width, this.height); }; @@ -71,13 +73,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rectangle */ -Rectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Rectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/math/shapes/RoundedRectangle.js b/src/core/math/shapes/RoundedRectangle.js index 27d286e..7bf6411 100644 --- a/src/core/math/shapes/RoundedRectangle.js +++ b/src/core/math/shapes/RoundedRectangle.js @@ -11,7 +11,8 @@ * @param height {number} The overall height of this rounded rectangle * @param radius {number} Controls the radius of the rounded corners */ -function RoundedRectangle(x, y, width, height, radius) { +function RoundedRectangle(x, y, width, height, radius) +{ /** * @member {number} * @default 0 @@ -58,7 +59,8 @@ * * @return {RoundedRectangle} a copy of the rounded rectangle */ -RoundedRectangle.prototype.clone = function () { +RoundedRectangle.prototype.clone = function () +{ return new RoundedRectangle(this.x, this.y, this.width, this.height, this.radius); }; @@ -69,13 +71,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rounded Rectangle */ -RoundedRectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +RoundedRectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/primitives/Graphics.js b/src/core/primitives/Graphics.js index 261c534..e902d2a 100644 --- a/src/core/primitives/Graphics.js +++ b/src/core/primitives/Graphics.js @@ -16,7 +16,8 @@ * @extends DisplayObjectContainer * @namespace PIXI */ -function Graphics() { +function Graphics() +{ DisplayObjectContainer.call(this); this.renderable = true; @@ -154,16 +155,20 @@ * @private */ cacheAsBitmap: { - get: function () { + get: function () + { return this._cacheAsBitmap; }, - set: function (value) { + set: function (value) + { this._cacheAsBitmap = value; - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._generateCachedSprite(); } - else { + else + { this.destroyCachedSprite(); this.dirty = true; } @@ -176,7 +181,8 @@ * * @return {Graphics} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ var clone = new Graphics(); clone.renderable = this.renderable; @@ -192,7 +198,8 @@ clone.cachedSpriteDirty = this.cachedSpriteDirty; // copy graphics data - for (var i = 0; i < this.graphicsData.length; ++i) { + for (var i = 0; i < this.graphicsData.length; ++i) + { clone.graphicsData.push(this.graphicsData.clone()); } @@ -211,17 +218,21 @@ * @param alpha {number} alpha of the line to draw, will update the objects stored style * @return {Graphics} */ -Graphics.prototype.lineStyle = function (lineWidth, color, alpha) { +Graphics.prototype.lineStyle = function (lineWidth, color, alpha) +{ this.lineWidth = lineWidth || 0; this.lineColor = color || 0; this.lineAlpha = (arguments.length < 3) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length) + { // halfway through a line? start a new one! this.drawShape( new math.Polygon( this.currentPath.shape.points.slice(-2) )); } - else { + else + { // otherwise its empty so lets just set the line properties this.currentPath.lineWidth = this.lineWidth; this.currentPath.lineColor = this.lineColor; @@ -239,7 +250,8 @@ * @param y {number} the Y coordinate to move to * @return {Graphics} */ -Graphics.prototype.moveTo = function (x, y) { +Graphics.prototype.moveTo = function (x, y) +{ this.drawShape(new math.Polygon([x,y])); return this; @@ -253,7 +265,8 @@ * @param y {number} the Y coordinate to draw to * @return {Graphics} */ -Graphics.prototype.lineTo = function (x, y) { +Graphics.prototype.lineTo = function (x, y) +{ this.currentPath.shape.points.push(x, y); this.dirty = true; @@ -270,13 +283,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -285,7 +302,8 @@ n = 20, points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { this.moveTo(0, 0); } @@ -293,7 +311,8 @@ var fromY = points[points.length-1]; var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; xa = fromX + ( (cpX - fromX) * j ); @@ -319,13 +338,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -342,7 +365,8 @@ var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; dt = (1 - j); @@ -373,13 +397,17 @@ * @param radius {number} The radius of the arc * @return {Graphics} */ -Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points.push(x1, y1); } } - else { + else + { this.moveTo(x1, y1); } @@ -392,12 +420,15 @@ b2 = x2 - x1, mm = Math.abs(a1 * b2 - b1 * a2); - if (mm < 1.0e-8 || radius === 0) { - if (points[points.length-2] !== x1 || points[points.length-1] !== y1) { + if (mm < 1.0e-8 || radius === 0) + { + if (points[points.length-2] !== x1 || points[points.length-1] !== y1) + { points.push(x1, y1); } } - else { + else + { var dd = a1 * a1 + b1 * b1, cc = a2 * a2 + b2 * b2, tt = a1 * a2 + b1 * b2, @@ -433,42 +464,51 @@ * @param anticlockwise {boolean} Optional. Specifies whether the drawing should be counterclockwise or clockwise. False is default, and indicates clockwise, while true indicates counter-clockwise. * @return {Graphics} */ -Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) { +Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) +{ var startX = cx + Math.cos(startAngle) * radius; var startY = cy + Math.sin(startAngle) * radius; var points; // TODO - This if-else makes no sense. It uses currentPath in the else where it doesn't exist... - if (this.currentPath) { + if (this.currentPath) + { points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { points.push(startX, startY); } - else if (points[points.length-2] !== startX || points[points.length-1] !== startY) { + else if (points[points.length-2] !== startX || points[points.length-1] !== startY) + { points.push(startX, startY); } } - else { + else + { this.moveTo(startX, startY); points = this.currentPath.shape.points; } - if (startAngle === endAngle) { + if (startAngle === endAngle) + { return this; } - if (!anticlockwise && endAngle <= startAngle) { + if (!anticlockwise && endAngle <= startAngle) + { endAngle += Math.PI * 2; } - else if (anticlockwise && startAngle <= endAngle) { + else if (anticlockwise && startAngle <= endAngle) + { startAngle += Math.PI * 2; } var sweep = anticlockwise ? (startAngle - endAngle) *-1 : (endAngle - startAngle); var segs = (Math.abs(sweep)/ (Math.PI * 2)) * 40; - if (sweep === 0) { + if (sweep === 0) + { return this; } @@ -482,7 +522,8 @@ var remainder = ( segMinus % 1 ) / segMinus; - for (var i = 0; i <= segMinus; ++i) { + for (var i = 0; i <= segMinus; ++i) + { var real = i + remainder * i; var angle = ((theta) + startAngle + (theta2 * real)); @@ -506,13 +547,16 @@ * @param alpha {number} the alpha of the fill * @return {Graphics} */ -Graphics.prototype.beginFill = function (color, alpha) { +Graphics.prototype.beginFill = function (color, alpha) +{ this.filling = true; this.fillColor = color || 0; this.fillAlpha = (alpha === undefined) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length <= 2) + { this.currentPath.fill = this.filling; this.currentPath.fillColor = this.fillColor; this.currentPath.fillAlpha = this.fillAlpha; @@ -526,7 +570,8 @@ * * @return {Graphics} */ -Graphics.prototype.endFill = function () { +Graphics.prototype.endFill = function () +{ this.filling = false; this.fillColor = null; this.fillAlpha = 1; @@ -542,7 +587,8 @@ * @param height {number} The height of the rectangle * @return {Graphics} */ -Graphics.prototype.drawRect = function ( x, y, width, height ) { +Graphics.prototype.drawRect = function ( x, y, width, height ) +{ this.drawShape(new math.Rectangle(x,y, width, height)); return this; @@ -556,7 +602,8 @@ * @param height {number} The height of the rectangle * @param radius {number} Radius of the rectangle corners */ -Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) { +Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) +{ this.drawShape(new math.RoundedRectangle(x, y, width, height, radius)); return this; @@ -570,7 +617,8 @@ * @param radius {number} The radius of the circle * @return {Graphics} */ -Graphics.prototype.drawCircle = function (x, y, radius) { +Graphics.prototype.drawCircle = function (x, y, radius) +{ this.drawShape(new math.Circle(x,y, radius)); return this; @@ -585,7 +633,8 @@ * @param height {number} The half height of the ellipse * @return {Graphics} */ -Graphics.prototype.drawEllipse = function (x, y, width, height) { +Graphics.prototype.drawEllipse = function (x, y, width, height) +{ this.drawShape(new math.Ellipse(x, y, width, height)); return this; @@ -597,8 +646,10 @@ * @param path {Array} The path data used to construct the polygon. * @return {Graphics} */ -Graphics.prototype.drawPolygon = function (path) { - if (!(path instanceof Array)) { +Graphics.prototype.drawPolygon = function (path) +{ + if (!(path instanceof Array)) + { path = Array.prototype.slice.call(arguments); } @@ -612,7 +663,8 @@ * * @return {Graphics} */ -Graphics.prototype.clear = function () { +Graphics.prototype.clear = function () +{ this.lineWidth = 0; this.filling = false; @@ -631,7 +683,8 @@ * @param scaleMode {number} Should be one of the scaleMode consts * @return {Texture} a texture of the graphics object */ -Graphics.prototype.generateTexture = function (resolution, scaleMode) { +Graphics.prototype.generateTexture = function (resolution, scaleMode) +{ resolution = resolution || 1; var bounds = this.getBounds(); @@ -655,17 +708,21 @@ * * @param renderer {WebGLRenderer} */ -Graphics.prototype._renderWebGL = function (renderer) { +Graphics.prototype._renderWebGL = function (renderer) +{ // if the sprite is not visible or the alpha is 0 then no need to render this element - if (this.isMask === true) { + if (this.isMask === true) + { return; } // this code may still be needed so leaving for now.. - // + // /* - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture on the gpu too! @@ -681,17 +738,24 @@ return; } - */ - - // check if the webgl graphic needs to be updated - if (this.glDirty) { - this.dirty = true; - this.glDirty = false; - } + else */ - renderer.setObjectRendererer(renderer.graphicsRenderer); - renderer.graphicsRenderer.render(this); + renderer.spriteBatch.stop(); + renderer.blendModeManager.setBlendMode(this.blendMode); + // check blend mode + renderer.blendModeManager.setBlendMode( this.blendMode ); + + // check if the webgl graphic needs to be updated + if (this.glDirty) + { + this.dirty = true; + this.glDirty = false; + } + + WebGLGraphics.renderGraphics(this, renderer); + + renderer.spriteBatch.start(); }; /** @@ -700,14 +764,18 @@ * @param renderer {CanvasRenderer} * @private */ -Graphics.prototype.renderCanvas = function (renderer) { +Graphics.prototype.renderCanvas = function (renderer) +{ // 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.isMask === true) { + if (!this.visible || this.alpha <= 0 || this.isMask === true) + { return; } - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture @@ -723,16 +791,19 @@ return; } - else { + else + { var context = renderer.context; var transform = this.worldTransform; - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } @@ -748,11 +819,13 @@ CanvasGraphics.renderGraphics(this, context); - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } } @@ -763,13 +836,16 @@ * * @return {Rectangle} the rectangular bounding area */ -Graphics.prototype.getBounds = function (matrix) { +Graphics.prototype.getBounds = function (matrix) +{ // return an empty object if the item is a mask! - if (this.isMask) { + if (this.isMask) + { return math.Rectangle.EMPTY; } - if (this.dirty) { + if (this.dirty) + { this.updateLocalBounds(); this.glDirty = true; @@ -841,23 +917,27 @@ * Update the bounds of the object * */ -Graphics.prototype.updateLocalBounds = function () { +Graphics.prototype.updateLocalBounds = function () +{ var minX = Infinity; var maxX = -Infinity; var minY = Infinity; var maxY = -Infinity; - if (this.graphicsData.length) { + if (this.graphicsData.length) + { var shape, points, x, y, w, h; - for (var i = 0; i < this.graphicsData.length; i++) { + for (var i = 0; i < this.graphicsData.length; i++) + { var data = this.graphicsData[i]; var type = data.type; var lineWidth = data.lineWidth; shape = data.shape; - if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) { + if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) + { x = shape.x - lineWidth/2; y = shape.y - lineWidth/2; w = shape.width + lineWidth; @@ -869,7 +949,8 @@ minY = y < minY ? y : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.CIRC) { + else if (type === CONST.SHAPES.CIRC) + { x = shape.x; y = shape.y; w = shape.radius + lineWidth/2; @@ -881,7 +962,8 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.ELIP) { + else if (type === CONST.SHAPES.ELIP) + { x = shape.x; y = shape.y; w = shape.width + lineWidth/2; @@ -893,11 +975,13 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else { + else + { // POLY points = shape.points; - for (var j = 0; j < points.length; j += 2) { + for (var j = 0; j < points.length; j += 2) + { x = points[j]; y = points[j+1]; @@ -910,7 +994,8 @@ } } } - else { + else + { minX = 0; maxX = 0; minY = 0; @@ -931,10 +1016,12 @@ * * @private */ -Graphics.prototype._generateCachedSprite = function () { +Graphics.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { var canvasBuffer = new CanvasBuffer(bounds.width, bounds.height); var texture = Texture.fromCanvas(canvasBuffer.canvas); @@ -943,7 +1030,8 @@ this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.buffer.resize(bounds.width, bounds.height); } @@ -968,7 +1056,8 @@ * * @private */ -Graphics.prototype.updateCachedSpriteTexture = function () { +Graphics.prototype.updateCachedSpriteTexture = function () +{ var cachedSprite = this._cachedSprite; var texture = cachedSprite.texture; var canvas = cachedSprite.buffer.canvas; @@ -989,7 +1078,8 @@ * Destroys a previous cached sprite. * */ -Graphics.prototype.destroyCachedSprite = function () { +Graphics.prototype.destroyCachedSprite = function () +{ this._cachedSprite.texture.destroy(true); // let the gc collect the unused sprite @@ -1003,10 +1093,13 @@ * @param {Circle|Rectangle|Ellipse|Line|Polygon} shape The Shape object to draw. * @return {GraphicsData} The generated GraphicsData object. */ -Graphics.prototype.drawShape = function (shape) { - if (this.currentPath) { +Graphics.prototype.drawShape = function (shape) +{ + if (this.currentPath) + { // check current path! - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath.shape.points.length <= 2) + { this.graphicsData.pop(); } } @@ -1017,7 +1110,8 @@ this.graphicsData.push(data); - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { data.shape.closed = this.filling; this.currentPath = data; } diff --git a/src/core/primitives/GraphicsData.js b/src/core/primitives/GraphicsData.js index 99decbe..788f6f2 100644 --- a/src/core/primitives/GraphicsData.js +++ b/src/core/primitives/GraphicsData.js @@ -4,7 +4,8 @@ * @class * @namespace PIXI */ -function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) { +function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) +{ this.lineWidth = lineWidth; this.lineColor = lineColor; this.lineAlpha = lineAlpha; @@ -27,7 +28,8 @@ * * @return {GraphicsData} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ return new GraphicsData( this.lineWidth, this.lineColor, diff --git a/src/core/renderers/canvas/CanvasRenderer.js b/src/core/renderers/canvas/CanvasRenderer.js index 15a0978..7aebd44 100644 --- a/src/core/renderers/canvas/CanvasRenderer.js +++ b/src/core/renderers/canvas/CanvasRenderer.js @@ -17,17 +17,22 @@ * @param [options.resolution=1] {number} the resolution of the renderer retina would be 2 * @param [options.clearBeforeRender=true] {boolean} This sets if the CanvasRenderer will clear the canvas or not before the new render pass. */ -function CanvasRenderer(width, height, options) { +function CanvasRenderer(width, height, options) +{ utils.sayHello('Canvas'); - if (options) { - for (var i in CONST.defaultRenderOptions) { - if (typeof options[i] === 'undefined') { + if (options) + { + for (var i in CONST.defaultRenderOptions) + { + if (typeof options[i] === 'undefined') + { options[i] = CONST.defaultRenderOptions[i]; } } } - else { + else + { options = CONST.defaultRenderOptions; } @@ -156,19 +161,24 @@ this.smoothProperty = null; - if (this.context.imageSmoothingEnabled) { + if (this.context.imageSmoothingEnabled) + { this.smoothProperty = 'imageSmoothingEnabled'; } - else if (this.context.webkitImageSmoothingEnabled) { + else if (this.context.webkitImageSmoothingEnabled) + { this.smoothProperty = 'webkitImageSmoothingEnabled'; } - else if (this.context.mozImageSmoothingEnabled) { + else if (this.context.mozImageSmoothingEnabled) + { this.smoothProperty = 'mozImageSmoothingEnabled'; } - else if (this.context.oImageSmoothingEnabled) { + else if (this.context.oImageSmoothingEnabled) + { this.smoothProperty = 'oImageSmoothingEnabled'; } - else if (this.context.msImageSmoothingEnabled) { + else if (this.context.msImageSmoothingEnabled) + { this.smoothProperty = 'msImageSmoothingEnabled'; } @@ -193,10 +203,12 @@ * @memberof CanvasRenderer# */ backgroundColor: { - get: function () { + get: function () + { return this._backgroundColor; }, - set: function (val) { + set: function (val) + { this._backgroundColor = val; this._backgroundColorString = utils.hex2string(val); } @@ -208,7 +220,8 @@ * * @param object {DisplayObject} the object to be rendered */ -CanvasRenderer.prototype.render = function (object) { +CanvasRenderer.prototype.render = function (object) +{ object.updateTransform(); this.context.setTransform(1,0,0,1,0,0); @@ -218,16 +231,20 @@ this.currentBlendMode = CONST.blendModes.NORMAL; this.context.globalCompositeOperation = this.blendModes[CONST.blendModes.NORMAL]; - if (navigator.isCocoonJS && this.view.screencanvas) { + if (navigator.isCocoonJS && this.view.screencanvas) + { this.context.fillStyle = 'black'; this.context.clear(); } - if (this.clearBeforeRender) { - if (this.transparent) { + if (this.clearBeforeRender) + { + if (this.transparent) + { this.context.clearRect(0, 0, this.width, this.height); } - else { + else + { this.context.fillStyle = this._backgroundColorString; this.context.fillRect(0, 0, this.width , this.height); } @@ -241,8 +258,10 @@ * * @param [removeView=false] {boolean} Removes the Canvas element from the DOM. */ -CanvasRenderer.prototype.destroy = function (removeView) { - if (removeView && this.view.parent) { +CanvasRenderer.prototype.destroy = function (removeView) +{ + if (removeView && this.view.parent) + { this.view.parent.removeChild(this.view); } @@ -257,14 +276,16 @@ * @param width {number} the new width of the canvas view * @param height {number} the new height of the canvas view */ -CanvasRenderer.prototype.resize = function (width, height) { +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) { + if (this.autoResize) + { this.view.style.width = this.width / this.resolution + 'px'; this.view.style.height = this.height / this.resolution + 'px'; } @@ -276,7 +297,8 @@ * @param displayObject {DisplayObject} The displayObject to render * @private */ -CanvasRenderer.prototype.renderDisplayObject = function (displayObject) { +CanvasRenderer.prototype.renderDisplayObject = function (displayObject) +{ displayObject.renderCanvas(this); }; @@ -285,11 +307,14 @@ * * @private */ -CanvasRenderer.prototype._mapBlendModes = function () { - if (!this.blendModes) { +CanvasRenderer.prototype._mapBlendModes = function () +{ + if (!this.blendModes) + { this.blendModes = {}; - if (utils.canUseNewCanvasBlendModes()) { + if (utils.canUseNewCanvasBlendModes()) + { this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? this.blendModes[CONST.blendModes.MULTIPLY] = 'multiply'; @@ -308,7 +333,8 @@ this.blendModes[CONST.blendModes.COLOR] = 'color'; this.blendModes[CONST.blendModes.LUMINOSITY] = 'luminosity'; } - else { + else + { // this means that the browser does not support the cool new blend modes in canvas 'cough' ie 'cough' this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? diff --git a/src/core/renderers/canvas/utils/CanvasBuffer.js b/src/core/renderers/canvas/utils/CanvasBuffer.js index ebe5d47..b183a66 100644 --- a/src/core/renderers/canvas/utils/CanvasBuffer.js +++ b/src/core/renderers/canvas/utils/CanvasBuffer.js @@ -6,7 +6,8 @@ * @param width {number} the width for the newly created canvas * @param height {number} the height for the newly created canvas */ -function CanvasBuffer(width, height) { +function CanvasBuffer(width, height) +{ /** * The Canvas object that belongs to this CanvasBuffer. * @@ -36,10 +37,12 @@ * @memberof CanvasBuffer# */ width: { - get: function () { + get: function () + { return this.canvas.width; }, - set: function (val) { + set: function (val) + { this.canvas.width = val; } }, @@ -50,10 +53,12 @@ * @memberof CanvasBuffer# */ height: { - get: function () { + get: function () + { return this.canvas.height; }, - set: function (val) { + set: function (val) + { this.canvas.height = val; } } @@ -64,7 +69,8 @@ * * @private */ -CanvasBuffer.prototype.clear = function () { +CanvasBuffer.prototype.clear = function () +{ this.context.setTransform(1, 0, 0, 1, 0, 0); this.context.clearRect(0,0, this.canvas.width, this.canvas.height); }; @@ -75,7 +81,8 @@ * @param width {number} the new width of the canvas * @param height {number} the new height of the canvas */ -CanvasBuffer.prototype.resize = function (width, height) { +CanvasBuffer.prototype.resize = function (width, height) +{ this.canvas.width = width; this.canvas.height = height; }; diff --git a/src/core/renderers/canvas/utils/CanvasGraphics.js b/src/core/renderers/canvas/utils/CanvasGraphics.js index c7eaa2a..3f2a91f 100644 --- a/src/core/renderers/canvas/utils/CanvasGraphics.js +++ b/src/core/renderers/canvas/utils/CanvasGraphics.js @@ -13,15 +13,18 @@ * @param graphics {Graphics} the actual graphics object to render * @param context {CanvasRenderingContext2D} the 2d drawing method of the canvas */ -CanvasGraphics.renderGraphics = function (graphics, context) { +CanvasGraphics.renderGraphics = function (graphics, context) +{ var worldAlpha = graphics.worldAlpha; - if (graphics.dirty) { + if (graphics.dirty) + { this.updateGraphicsTint(graphics); graphics.dirty = false; } - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; @@ -30,69 +33,82 @@ context.lineWidth = data.lineWidth; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { context.beginPath(); var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } - if (shape.closed) { + if (shape.closed) + { context.lineTo(points[0], points[1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fillRect(shape.x, shape.y, shape.width, shape.height); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.strokeRect(shape.x, shape.y, shape.width, shape.height); } } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.beginPath(); context.arc(shape.x, shape.y, shape.radius,0,2*Math.PI); context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas var w = shape.width * 2; @@ -119,18 +135,21 @@ context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; var width = shape.width; @@ -152,13 +171,15 @@ context.quadraticCurveTo(rx, ry, rx, ry + radius); context.closePath(); - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); @@ -174,45 +195,54 @@ * @param graphics {Graphics} the graphics which will be used as a mask * @param context {CanvasRenderingContext2D} the context 2d method of the canvas */ -CanvasGraphics.renderGraphicsMask = function (graphics, context) { +CanvasGraphics.renderGraphicsMask = function (graphics, context) +{ var len = graphics.graphicsData.length; - if (len === 0) { + if (len === 0) + { return; } context.beginPath(); - for (var i = 0; i < len; i++) { + for (var i = 0; i < len; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { context.rect(shape.x, shape.y, shape.width, shape.height); context.closePath(); } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.arc(shape.x, shape.y, shape.radius, 0, 2 * Math.PI); context.closePath(); } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas @@ -237,7 +267,8 @@ context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); context.closePath(); } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; @@ -262,8 +293,10 @@ } }; -CanvasGraphics.updateGraphicsTint = function (graphics) { - if (graphics.tint === 0xFFFFFF) { +CanvasGraphics.updateGraphicsTint = function (graphics) +{ + if (graphics.tint === 0xFFFFFF) + { return; } @@ -271,7 +304,8 @@ var tintG = (graphics.tint >> 8 & 0xFF) / 255; var tintB = (graphics.tint & 0xFF)/ 255; - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var fillColor = data.fillColor | 0; diff --git a/src/core/renderers/canvas/utils/CanvasMaskManager.js b/src/core/renderers/canvas/utils/CanvasMaskManager.js index e04a733..9827d36 100644 --- a/src/core/renderers/canvas/utils/CanvasMaskManager.js +++ b/src/core/renderers/canvas/utils/CanvasMaskManager.js @@ -6,7 +6,8 @@ * @class * @namespace PIXI */ -function CanvasMaskManager() {} +function CanvasMaskManager() +{} CanvasMaskManager.prototype.constructor = CanvasMaskManager; module.exports = CanvasMaskManager; @@ -17,7 +18,8 @@ * @param maskData {object} the maskData that will be pushed * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.pushMask = function (maskData, renderer) { +CanvasMaskManager.prototype.pushMask = function (maskData, renderer) +{ renderer.context.save(); var cacheAlpha = maskData.alpha; @@ -45,6 +47,7 @@ * * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.popMask = function (renderer) { +CanvasMaskManager.prototype.popMask = function (renderer) +{ renderer.context.restore(); }; diff --git a/src/core/renderers/canvas/utils/CanvasTinter.js b/src/core/renderers/canvas/utils/CanvasTinter.js index 17e0529..d2fb1bc 100644 --- a/src/core/renderers/canvas/utils/CanvasTinter.js +++ b/src/core/renderers/canvas/utils/CanvasTinter.js @@ -14,7 +14,8 @@ * @param color {number} the color to use to tint the sprite with * @return {HTMLCanvasElement} The tinted canvas */ -CanvasTinter.getTintedTexture = function (sprite, color) { +CanvasTinter.getTintedTexture = function (sprite, color) +{ var texture = sprite.texture; color = CanvasTinter.roundColor(color); @@ -23,7 +24,8 @@ texture.tintCache = texture.tintCache || {}; - if (texture.tintCache[stringColor]) { + if (texture.tintCache[stringColor]) + { return texture.tintCache[stringColor]; } @@ -33,14 +35,16 @@ //CanvasTinter.tintWithPerPixel(texture, stringColor, canvas); CanvasTinter.tintMethod(texture, color, canvas); - if (CanvasTinter.convertTintToImage) { + if (CanvasTinter.convertTintToImage) + { // is this better? var tintImage = new Image(); tintImage.src = canvas.toDataURL(); texture.tintCache[stringColor] = tintImage; } - else { + else + { texture.tintCache[stringColor] = canvas; // if we are not converting the texture to an image then we need to lose the reference to the canvas CanvasTinter.canvas = null; @@ -56,7 +60,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithMultiply = function (texture, color, canvas) { +CanvasTinter.tintWithMultiply = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -104,7 +109,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithOverlay = function (texture, color, canvas) { +CanvasTinter.tintWithOverlay = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -139,7 +145,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithPerPixel = function (texture, color, canvas) { +CanvasTinter.tintWithPerPixel = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -167,7 +174,8 @@ var pixels = pixelData.data; - for (var i = 0; i < pixels.length; i += 4) { + for (var i = 0; i < pixels.length; i += 4) + { pixels[i+0] *= r; pixels[i+1] *= g; pixels[i+2] *= b; @@ -181,7 +189,8 @@ * * @param color {number} the color to round, should be a hex color */ -CanvasTinter.roundColor = function (color) { +CanvasTinter.roundColor = function (color) +{ var step = CanvasTinter.cacheStepsPerColorChannel; var rgbValues = utils.hex2rgb(color); diff --git a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js index 9f2f89a..35edbaf 100644 --- a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js +++ b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLBlendModeManager(renderer) { +function WebGLBlendModeManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -23,8 +24,10 @@ * * @param blendMode {number} the blendMode, should be a Pixi const, such as BlendModes.ADD */ -WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) { - if (this.currentBlendMode === blendMode) { +WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) +{ + if (this.currentBlendMode === blendMode) + { return false; } diff --git a/src/core/renderers/webgl/managers/WebGLFilterManager.js b/src/core/renderers/webgl/managers/WebGLFilterManager.js index 1179258..2dac048 100644 --- a/src/core/renderers/webgl/managers/WebGLFilterManager.js +++ b/src/core/renderers/webgl/managers/WebGLFilterManager.js @@ -7,7 +7,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLFilterManager(renderer) { +function WebGLFilterManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -32,7 +33,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.texturePool.length = 0; self.initShaderBuffers(); }); @@ -46,7 +48,8 @@ * @param renderer {WebGLRenderer} * @param buffer {ArrayBuffer} */ -WebGLFilterManager.prototype.begin = function (buffer) { +WebGLFilterManager.prototype.begin = function (buffer) +{ this.defaultShader = this.renderer.shaderManager.defaultShader; this.width = this.renderer.projection.x * 2; @@ -60,7 +63,8 @@ * * @param filterBlock {object} the filter that will be pushed to the current filter stack */ -WebGLFilterManager.prototype.pushFilter = function (filterBlock) { +WebGLFilterManager.prototype.pushFilter = function (filterBlock) +{ var gl = this.renderer.gl; var projection = this.renderer.projection; @@ -78,10 +82,12 @@ this.offsetY += filterBlock._filterArea.y; var texture = this.texturePool.pop(); - if (!texture) { + if (!texture) + { texture = new FilterTexture(this.renderer.gl, this.width, this.height); } - else { + else + { texture.resize(this.width, this.height); } @@ -98,29 +104,35 @@ var localX = filterArea.x, localY = filterArea.y; - if (filterArea.x < 0) { + if (filterArea.x < 0) + { filterArea.width += filterArea.x; filterArea.x = 0; } - if (filterArea.y < 0) { + if (filterArea.y < 0) + { filterArea.height += filterArea.y; filterArea.y = 0; } - if (localX + filterArea.width > this.width) { + if (localX + filterArea.width > this.width) + { filterArea.width = this.width - localX; } - if (localY + filterArea.height > this.height) { + if (localY + filterArea.height > this.height) + { filterArea.height = this.height - localY; } - if (filterArea.width < 0) { + if (filterArea.width < 0) + { filterArea.width = 0; } - if (filterArea.height < 0) { + if (filterArea.height < 0) + { filterArea.height = 0; } @@ -154,7 +166,8 @@ * Removes the last filter from the filter stack and doesn't return it. * */ -WebGLFilterManager.prototype.popFilter = function () { +WebGLFilterManager.prototype.popFilter = function () +{ var gl = this.renderer.gl; var filterBlock = this.filterStack.pop(); @@ -163,7 +176,8 @@ var projection = this.renderer.projection; var offset = this.renderer.offset; - if (filterBlock.filterPasses.length > 1) { + if (filterBlock.filterPasses.length > 1) + { gl.viewport(0, 0, filterArea.width, filterArea.height); gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); @@ -193,7 +207,8 @@ var inputTexture = texture; var outputTexture = this.texturePool.pop(); - if (!outputTexture) { + if (!outputTexture) + { outputTexture = new FilterTexture(this.renderer.gl, this.width, this.height); } outputTexture.resize(this.width, this.height); @@ -204,7 +219,8 @@ gl.disable(gl.BLEND); - for (var i = 0; i < filterBlock.filterPasses.length-1; i++) { + for (var i = 0; i < filterBlock.filterPasses.length-1; i++) + { var filterPass = filterBlock.filterPasses[i]; gl.bindFramebuffer(gl.FRAMEBUFFER, outputTexture.frameBuffer ); @@ -243,10 +259,12 @@ var buffer = this.buffer; // time to render the filters texture to the previous scene - if (this.filterStack.length === 0) { + if (this.filterStack.length === 0) + { gl.colorMask(true, true, true, true);//this.transparent); } - else { + else + { var currentFilter = this.filterStack[this.filterStack.length-1]; filterArea = currentFilter._filterArea; @@ -332,13 +350,15 @@ * @param width {number} the horizontal range of the filter * @param height {number} the vertical range of the filter */ -WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) { +WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) +{ // use program var gl = this.renderer.gl; var shader = filter.shaders[gl.id]; - if (!shader) { + if (!shader) + { shader = new Shader(gl); shader.fragmentSrc = filter.fragmentSrc; @@ -356,7 +376,8 @@ gl.uniform2f(shader.projectionVector, width/2, -height/2); gl.uniform2f(shader.offsetVector, 0,0); - if (filter.uniforms.dimensions) { + 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]; @@ -386,7 +407,8 @@ * Initialises the shader buffers. * */ -WebGLFilterManager.prototype.initShaderBuffers = function () { +WebGLFilterManager.prototype.initShaderBuffers = function () +{ var gl = this.renderer.gl; // create some buffers @@ -432,7 +454,8 @@ * Destroys the filter and removes it from the filter stack. * */ -WebGLFilterManager.prototype.destroy = function () { +WebGLFilterManager.prototype.destroy = function () +{ var gl = this.renderer.gl; this.filterStack = null; @@ -441,7 +464,8 @@ this.offsetY = 0; // destroy textures - for (var i = 0; i < this.texturePool.length; i++) { + for (var i = 0; i < this.texturePool.length; i++) + { this.texturePool[i].destroy(); } diff --git a/src/core/renderers/webgl/managers/WebGLManager.js b/src/core/renderers/webgl/managers/WebGLManager.js index 9d47b5c..c30cd51 100644 --- a/src/core/renderers/webgl/managers/WebGLManager.js +++ b/src/core/renderers/webgl/managers/WebGLManager.js @@ -3,7 +3,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLManager(renderer) { +function WebGLManager(renderer) +{ /** * The renderer this manager works for. * @@ -15,6 +16,7 @@ WebGLManager.prototype.constructor = WebGLManager; module.exports = WebGLManager; -WebGLManager.prototype.destroy = function () { +WebGLManager.prototype.destroy = function () +{ this.renderer = null; }; diff --git a/src/core/renderers/webgl/managers/WebGLMaskManager.js b/src/core/renderers/webgl/managers/WebGLMaskManager.js index 2f90b64..e568812 100644 --- a/src/core/renderers/webgl/managers/WebGLMaskManager.js +++ b/src/core/renderers/webgl/managers/WebGLMaskManager.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLMaskManager(renderer) { +function WebGLMaskManager(renderer) +{ WebGLManager.call(this, renderer); } @@ -19,12 +20,15 @@ * * @param maskData {any[]} */ -WebGLMaskManager.prototype.pushMask = function (maskData) { - if (maskData.dirty) { +WebGLMaskManager.prototype.pushMask = function (maskData) +{ + if (maskData.dirty) + { WebGLGraphics.updateGraphics(maskData, this.renderer.gl); } - if (!maskData._webGL[this.renderer.gl.id].data.length) { + if (!maskData._webGL[this.renderer.gl.id].data.length) + { return; } @@ -36,6 +40,7 @@ * * @param maskData {any[]} */ -WebGLMaskManager.prototype.popMask = function (maskData) { +WebGLMaskManager.prototype.popMask = function (maskData) +{ this.renderer.stencilManager.popStencil(maskData, maskData._webGL[this.renderer.gl.id].data[0], this.renderer); }; diff --git a/src/core/renderers/webgl/managers/WebGLShaderManager.js b/src/core/renderers/webgl/managers/WebGLShaderManager.js index fef071c..90c6477 100644 --- a/src/core/renderers/webgl/managers/WebGLShaderManager.js +++ b/src/core/renderers/webgl/managers/WebGLShaderManager.js @@ -10,7 +10,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLShaderManager(renderer) { +function WebGLShaderManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -28,7 +29,8 @@ */ this.tempAttribState = []; - for (var i = 0; i < this.maxAttibs; i++) { + for (var i = 0; i < this.maxAttibs; i++) + { this.attribState[i] = false; } @@ -66,7 +68,8 @@ // listen for context and update necessary shaders var self = this; - this.renderer.on('context', function (event) { + this.renderer.on('context', function (event) + { var gl = event.data; // this shader is used for rendering primitives @@ -97,29 +100,36 @@ * * @param attribs {Array} attribs */ -WebGLShaderManager.prototype.setAttribs = function (attribs) { +WebGLShaderManager.prototype.setAttribs = function (attribs) +{ // reset temp state var i; - for (i = 0; i < this.tempAttribState.length; i++) { + for (i = 0; i < this.tempAttribState.length; i++) + { this.tempAttribState[i] = false; } // set the new attribs - for (var a in attribs) { + for (var a in attribs) + { this.tempAttribState[attribs[a]] = true; } var gl = this.renderer.gl; - for (i = 0; i < this.attribState.length; i++) { - if (this.attribState[i] !== this.tempAttribState[i]) { + for (i = 0; i < this.attribState.length; i++) + { + if (this.attribState[i] !== this.tempAttribState[i]) + { this.attribState[i] = this.tempAttribState[i]; - if (this.attribState[i]) { + if (this.attribState[i]) + { gl.enableVertexAttribArray(i); } - else { + else + { gl.disableVertexAttribArray(i); } } @@ -131,8 +141,10 @@ * * @param shader {Any} */ -WebGLShaderManager.prototype.setShader = function (shader) { - if (this._currentId === shader.uuid) { +WebGLShaderManager.prototype.setShader = function (shader) +{ + if (this._currentId === shader.uuid) + { return false; } @@ -150,7 +162,8 @@ * Destroys this object. * */ -WebGLShaderManager.prototype.destroy = function () { +WebGLShaderManager.prototype.destroy = function () +{ this.attribState = null; this.tempAttribState = null; diff --git a/src/core/renderers/webgl/managers/WebGLStencilManager.js b/src/core/renderers/webgl/managers/WebGLStencilManager.js index 9ec6398..4cb0134 100644 --- a/src/core/renderers/webgl/managers/WebGLStencilManager.js +++ b/src/core/renderers/webgl/managers/WebGLStencilManager.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLStencilManager(renderer) { +function WebGLStencilManager(renderer) +{ WebGLManager.call(this, renderer); this.stencilStack = []; @@ -24,12 +25,14 @@ * @param graphics {Graphics} * @param webGLData {any[]} */ -WebGLStencilManager.prototype.pushStencil = function (graphics, webGLData) { +WebGLStencilManager.prototype.pushStencil = function (graphics, webGLData) +{ var gl = this.renderer.gl; this.bindGraphics(graphics, webGLData, this.renderer); - if (this.stencilStack.length === 0) { + if (this.stencilStack.length === 0) + { gl.enable(gl.STENCIL_TEST); gl.clear(gl.STENCIL_BUFFER_BIT); this.reverse = true; @@ -47,14 +50,17 @@ // draw the triangle strip! - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } @@ -62,31 +68,38 @@ // draw a quad to increment.. gl.drawElements(gl.TRIANGLE_FAN, 4, gl.UNSIGNED_SHORT, ( webGLData.indices.length - 4 ) * 2 ); - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); } this.reverse = !this.reverse; } - else { - if (!this.reverse) { + else + { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } - else { + 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) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); } } @@ -103,7 +116,8 @@ * @param graphics {Graphics} * @param webGLData {Array} */ -WebGLStencilManager.prototype.bindGraphics = function (graphics, webGLData) { +WebGLStencilManager.prototype.bindGraphics = function (graphics, webGLData) +{ //if (this._currentGraphics === graphics)return; this._currentGraphics = graphics; @@ -114,7 +128,8 @@ offset = this.renderer.offset, shader;// = this.renderer.shaderManager.primitiveShader; - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { shader = this.renderer.shaderManager.complexPrimitiveShader; this.renderer.shaderManager.setShader(shader); @@ -141,7 +156,8 @@ // set the index buffer! gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, webGLData.indexBuffer); } - else { + else + { //this.renderer.shaderManager.activatePrimitiveShader(); shader = this.renderer.shaderManager.primitiveShader; this.renderer.shaderManager.setShader( shader ); @@ -154,7 +170,7 @@ gl.uniform2f(shader.uniforms.offsetVector._location, -offset.x, -offset.y); gl.uniform3fv(shader.uniforms.tint._location, utils.hex2rgb(graphics.tint)); - + gl.uniform1f(shader.uniforms.alpha._location, graphics.worldAlpha); @@ -172,19 +188,22 @@ * @param graphics {Graphics} * @param webGLData {Array} */ -WebGLStencilManager.prototype.popStencil = function (graphics, webGLData) { +WebGLStencilManager.prototype.popStencil = function (graphics, webGLData) +{ var gl = this.renderer.gl; this.stencilStack.pop(); this.count--; - if (this.stencilStack.length === 0) { + if (this.stencilStack.length === 0) + { // the stack is empty! gl.disable(gl.STENCIL_TEST); } - else { + else + { var level = this.count; @@ -192,14 +211,17 @@ gl.colorMask(false, false, false, false); - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { this.reverse = !this.reverse; - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } @@ -213,31 +235,38 @@ // draw the triangle strip! gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); - if (!this.reverse) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); } } - else { + else + { // console.log("<<>>") - if (!this.reverse) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } - else { + 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) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); } } @@ -253,7 +282,8 @@ * Destroys the mask stack. * */ -WebGLStencilManager.prototype.destroy = function () { +WebGLStencilManager.prototype.destroy = function () +{ this.renderer = null; this.stencilStack = null; }; diff --git a/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js b/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js index 913ba5e..1ea7d19 100644 --- a/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js +++ b/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function ComplexPrimitiveShader(gl) { +function ComplexPrimitiveShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -24,7 +25,8 @@ 'uniform float flipY;', 'varying vec4 vColor;', - 'void main(void) {', + '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);', @@ -37,7 +39,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = vColor;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/FastShader.js b/src/core/renderers/webgl/shaders/FastShader.js index bd2e29a..2e5e060 100644 --- a/src/core/renderers/webgl/shaders/FastShader.js +++ b/src/core/renderers/webgl/shaders/FastShader.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function FastShader(gl) { +function FastShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -28,7 +29,8 @@ 'const vec2 center = vec2(-1.0, 1.0);', - 'void main(void) {', + 'void main(void) + {', ' vec2 v;', ' vec2 sv = aVertexPosition * aScale;', ' v.x = (sv.x) * cos(aRotation) - (sv.y) * sin(aRotation);', @@ -49,7 +51,8 @@ 'uniform sampler2D uSampler;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/PrimitiveShader.js b/src/core/renderers/webgl/shaders/PrimitiveShader.js index 6f25409..a25f54f 100644 --- a/src/core/renderers/webgl/shaders/PrimitiveShader.js +++ b/src/core/renderers/webgl/shaders/PrimitiveShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function PrimitiveShader(gl) { +function PrimitiveShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -23,7 +24,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + '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);', @@ -36,7 +38,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = vColor;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/Shader.js b/src/core/renderers/webgl/shaders/Shader.js index f8964f5..fd75ef5 100644 --- a/src/core/renderers/webgl/shaders/Shader.js +++ b/src/core/renderers/webgl/shaders/Shader.js @@ -6,7 +6,8 @@ * @param [fragmentSrc] {string} The source of the fragment shader. * @param [vertexSrc] {string} The source of the vertex shader. */ -function Shader(gl, vertexSrc, fragmentSrc, customUniforms, customAttributes) { +function Shader(gl, vertexSrc, fragmentSrc, customUniforms, customAttributes) +{ /** * @member {number} * @readonly @@ -33,7 +34,8 @@ dimensions: { type: '4f', value: new Float32Array(4) } }; - for (var u in customUniforms) { + for (var u in customUniforms) + { this.uniforms[u] = customUniforms[u]; } @@ -43,7 +45,8 @@ aColor: 0 }; - for (var a in customAttributes) { + for (var a in customAttributes) + { this.attributes[a] = customAttributes[a]; } @@ -66,7 +69,8 @@ 'const vec2 center = vec2(-1.0, 1.0);', - 'void main(void) {', + 'void main(void) + {', ' gl_Position = vec4( ((aVertexPosition + offsetVector) / projectionVector) + center , 0.0, 1.0);', ' vTextureCoord = aTextureCoord;', ' vColor = vec4(aColor.rgb * aColor.a, aColor.a);', @@ -85,7 +89,8 @@ 'uniform sampler2D uSampler;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;', '}' ].join('\n'); @@ -96,7 +101,8 @@ Shader.prototype.constructor = Shader; module.exports = Shader; -Shader.prototype.init = function () { +Shader.prototype.init = function () +{ this.compile(); this.gl.useProgram(this.program); @@ -105,14 +111,18 @@ this.cacheAttributeLocations(Object.keys(this.attributes)); }; -Shader.prototype.cacheUniformLocations = function (keys) { - for (var i = 0; i < keys.length; ++i) { +Shader.prototype.cacheUniformLocations = function (keys) +{ + for (var i = 0; i < keys.length; ++i) + { this.uniforms[keys[i]]._location = this.gl.getUniformLocation(this.program, keys[i]); } }; -Shader.prototype.cacheAttributeLocations = function (keys) { - for (var i = 0; i < keys.length; ++i) { +Shader.prototype.cacheAttributeLocations = function (keys) +{ + for (var i = 0; i < keys.length; ++i) + { this.attributes[keys[i]] = this.gl.getAttribLocation(this.program, keys[i]); } @@ -124,14 +134,16 @@ // 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.attributes.aColor === -1) { + // if (this.attributes.aColor === -1) + { // this.attributes.aColor = 2; // } // End worst hack eva // }; -Shader.prototype.compile = function () { +Shader.prototype.compile = function () +{ var gl = this.gl; var glVertShader = this._glCompile(gl.VERTEX_SHADER, this.vertexSrc); @@ -144,13 +156,15 @@ gl.linkProgram(program); // if linking fails, then log and cleanup - if (!gl.getProgramParameter(program, gl.LINK_STATUS)) { + if (!gl.getProgramParameter(program, gl.LINK_STATUS)) + { window.console.error('Pixi.js Error: Could not initialize shader.'); window.console.error('gl.VALIDATE_STATUS', gl.getProgramParameter(program, gl.VALIDATE_STATUS)); window.console.error('gl.getError()', gl.getError()); // if there is a program info log, log it - if (gl.getProgramInfoLog(program) !== '') { + if (gl.getProgramInfoLog(program) !== '') + { window.console.warn('Pixi.js Warning: gl.getProgramInfoLog()', gl.getProgramInfoLog(program)); } @@ -165,18 +179,21 @@ return (this.program = program); }; -Shader.prototype.syncUniforms = function () { +Shader.prototype.syncUniforms = function () +{ var gl = this.gl; this.textureCount = 1; - for (var key in this.uniforms) { + for (var key in this.uniforms) + { var uniform = this.uniforms[key], location = uniform._location, value = uniform.value, i, il; - switch (uniform.type) { + switch (uniform.type) + { // single int value case 'i': case '1i': @@ -282,7 +299,8 @@ // a Color Value case 'c': - if (typeof value === 'number') { + if (typeof value === 'number') + { value = utils.hex2rgb(value); } @@ -311,11 +329,13 @@ // array of 2D Point objects case 'v2v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(2 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 2] = value[i].x; uniform._array[i * 2 + 1] = value[i].y; } @@ -325,11 +345,13 @@ // array of 3D Point objects case 'v3v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(3 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 3] = value[i].x; uniform._array[i * 3 + 1] = value[i].y; uniform._array[i * 3 + 2] = value[i].z; @@ -341,11 +363,13 @@ // array of 4D Point objects case 'v4v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(4 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 4] = value[i].x; uniform._array[i * 4 + 1] = value[i].y; uniform._array[i * 4 + 2] = value[i].z; @@ -359,7 +383,8 @@ // PIXI.Texture case 't': case 'sampler2D': - if (!uniform.value || !uniform.value.baseTexture || !uniform.value.baseTexture.hasLoaded) { + if (!uniform.value || !uniform.value.baseTexture || !uniform.value.baseTexture.hasLoaded) + { break; } @@ -376,7 +401,8 @@ this.textureCount++; // initialize the texture if we haven't yet - if (!uniform._init) { + if (!uniform._init) + { this.initSampler2D(uniform); uniform._init = true; @@ -394,11 +420,13 @@ * Initialises a Sampler2D uniform (which may only be available later on after initUniforms once the texture has loaded) * */ -Shader.prototype.initSampler2D = function (uniform) { +Shader.prototype.initSampler2D = function (uniform) +{ var gl = this.gl; // Extended texture data - if (uniform.textureData) { + if (uniform.textureData) + { var data = uniform.textureData; // GLTexture = mag linear, min linear_mipmap_linear, wrap repeat + gl.generateMipmap(gl.TEXTURE_2D); @@ -417,14 +445,16 @@ var wrapT = (data.wrapT) ? data.wrapT : gl.CLAMP_TO_EDGE; var format = (data.luminance) ? gl.LUMINANCE : gl.RGBA; - if (data.repeat) { + if (data.repeat) + { wrapS = gl.REPEAT; wrapT = gl.REPEAT; } gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, !!data.flipY); - if (data.width) { + if (data.width) + { var width = (data.width) ? data.width : 512; var height = (data.height) ? data.height : 2; var border = (data.border) ? data.border : 0; @@ -432,7 +462,8 @@ // 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 { + 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); } @@ -448,7 +479,8 @@ * Destroys the shader. * */ -Shader.prototype.destroy = function () { +Shader.prototype.destroy = function () +{ this.gl.deleteProgram(this.program); this.gl = null; @@ -459,13 +491,15 @@ this.fragmentSrc = null; }; -Shader.prototype._glCompile = function (type, src) { +Shader.prototype._glCompile = function (type, src) +{ var shader = this.gl.createShader(type); this.gl.shaderSource(shader, src); this.gl.compileShader(shader); - if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) { + if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) + { window.console.log(this.gl.getShaderInfoLog(shader)); return null; } diff --git a/src/core/renderers/webgl/shaders/StripShader.js b/src/core/renderers/webgl/shaders/StripShader.js index 193f6e1..a7abcc6 100644 --- a/src/core/renderers/webgl/shaders/StripShader.js +++ b/src/core/renderers/webgl/shaders/StripShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function StripShader(gl) { +function StripShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -20,7 +21,8 @@ 'varying vec2 vTextureCoord;', - 'void main(void) {', + '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);', @@ -36,7 +38,8 @@ 'varying vec2 vTextureCoord;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vec2(vTextureCoord.x, vTextureCoord.y)) * alpha;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/utils/FilterTexture.js b/src/core/renderers/webgl/utils/FilterTexture.js index d2c8423..4433d44 100644 --- a/src/core/renderers/webgl/utils/FilterTexture.js +++ b/src/core/renderers/webgl/utils/FilterTexture.js @@ -8,7 +8,8 @@ * @param height {number} the vertical range of the filter * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values */ -function FilterTexture(gl, width, height, scaleMode) { +function FilterTexture(gl, width, height, scaleMode) +{ /** * @member {WebGLContext} */ @@ -59,7 +60,8 @@ * Clears the filter texture. * */ -FilterTexture.prototype.clear = function () { +FilterTexture.prototype.clear = function () +{ var gl = this.gl; gl.clearColor(0,0,0, 0); @@ -72,8 +74,10 @@ * @param width {number} the new width of the texture * @param height {number} the new height of the texture */ -FilterTexture.prototype.resize = function (width, height) { - if (this.width === width && this.height === height) { +FilterTexture.prototype.resize = function (width, height) +{ + if (this.width === width && this.height === height) + { return; } @@ -96,7 +100,8 @@ * Destroys the filter texture. * */ -FilterTexture.prototype.destroy = function () { +FilterTexture.prototype.destroy = function () +{ var gl = this.gl; gl.deleteFramebuffer( this.frameBuffer ); gl.deleteTexture( this.texture ); diff --git a/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js b/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js index c4721e9..a63f4d7 100644 --- a/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js +++ b/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js @@ -14,7 +14,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this sprite batch works for. */ -function WebGLFastSpriteBatch(renderer) { +function WebGLFastSpriteBatch(renderer) +{ /** * The renderer instance this sprite batch operates on. * @@ -91,7 +92,8 @@ */ this.lastIndexCount = 0; - for (var i=0, j=0; i < numIndices; i += 6, j += 4) { + 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; @@ -144,7 +146,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.setupContext(); }); } @@ -157,7 +160,8 @@ * * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLFastSpriteBatch.prototype.setupContext = function () { +WebGLFastSpriteBatch.prototype.setupContext = function () +{ var gl = this.renderer.gl; // create a couple of buffers @@ -177,7 +181,8 @@ /** * @param spriteBatch {SpriteBatch} The SpriteBatch container to prepare for. */ -WebGLFastSpriteBatch.prototype.begin = function (spriteBatch) { +WebGLFastSpriteBatch.prototype.begin = function (spriteBatch) +{ this.shader = this.renderer.shaderManager.fastShader; this.matrix = spriteBatch.worldTransform.toArray(true); @@ -187,33 +192,38 @@ /** */ -WebGLFastSpriteBatch.prototype.end = function () { +WebGLFastSpriteBatch.prototype.end = function () +{ this.flush(); }; /** * @param spriteBatch {SpriteBatch} The SpriteBatch container to render. */ -WebGLFastSpriteBatch.prototype.render = function (spriteBatch) { +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) { + if (!sprite.texture._uvs) + { return; } this.currentBaseTexture = sprite.texture.baseTexture; // check blend mode - if (sprite.blendMode !== this.renderer.blendModeManager.currentBlendMode) { + if (sprite.blendMode !== this.renderer.blendModeManager.currentBlendMode) + { this.flush(); this.renderer.blendModeManager.setBlendMode(sprite.blendMode); } - for (var i=0,j= children.length; i= this.size) { + if (this.currentBatchSize >= this.size) + { this.flush(); } }; @@ -362,29 +379,35 @@ /** * */ -WebGLFastSpriteBatch.prototype.flush = function () { +WebGLFastSpriteBatch.prototype.flush = function () +{ // If the batch is length 0 then return as there is nothing to draw - if (this.currentBatchSize === 0) { + if (this.currentBatchSize === 0) + { return; } var gl = this.renderer.gl; // bind the current texture - if (!this.currentBaseTexture._glTextures[gl.id]) { + if (!this.currentBaseTexture._glTextures[gl.id]) + { this.renderer.updateTexture(this.currentBaseTexture, gl); } //TODO-SHOUD THIS BE ELSE??!?!?! - else { + else + { gl.bindTexture(gl.TEXTURE_2D, this.currentBaseTexture._glTextures[gl.id]); } // upload the verts to the buffer - if (this.currentBatchSize > ( this.size * 0.5 ) ) { + if (this.currentBatchSize > ( this.size * 0.5 ) ) + { gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); } - else { + else + { var view = this.vertices.subarray(0, this.currentBatchSize * this.vertByteSize); gl.bufferSubData(gl.ARRAY_BUFFER, 0, view); @@ -405,14 +428,16 @@ * Ends the batch and flushes * */ -WebGLFastSpriteBatch.prototype.stop = function () { +WebGLFastSpriteBatch.prototype.stop = function () +{ this.flush(); }; /** * */ -WebGLFastSpriteBatch.prototype.start = function () { +WebGLFastSpriteBatch.prototype.start = function () +{ var gl = this.renderer.gl; // bind the main texture diff --git a/src/core/renderers/webgl/utils/WebGLGraphics.js b/src/core/renderers/webgl/utils/WebGLGraphics.js index 55f4911..ab8f46e 100644 --- a/src/core/renderers/webgl/utils/WebGLGraphics.js +++ b/src/core/renderers/webgl/utils/WebGLGraphics.js @@ -19,7 +19,8 @@ * @param graphics {Graphics} * @param renderer {WebGLRenderer} */ -WebGLGraphics.renderGraphics = function (graphics, renderer) {//projection, offset) { +WebGLGraphics.renderGraphics = function (graphics, renderer) {//projection, offset) +{ var gl = renderer.gl; var projection = renderer.projection, @@ -27,7 +28,8 @@ shader = renderer.shaderManager.primitiveShader, webGLData; - if (graphics.dirty) { + if (graphics.dirty) + { WebGLGraphics.updateGraphics(graphics, gl); } @@ -35,8 +37,10 @@ // This could be speeded up for sure! - for (var i = 0; i < webGL.data.length; i++) { - if (webGL.data[i].mode === 1) { + for (var i = 0; i < webGL.data.length; i++) + { + if (webGL.data[i].mode === 1) + { webGLData = webGL.data[i]; renderer.stencilManager.pushStencil(graphics, webGLData, renderer); @@ -46,7 +50,8 @@ renderer.stencilManager.popStencil(graphics, webGLData, renderer); } - else { + else + { webGLData = webGL.data[i]; @@ -84,12 +89,14 @@ * @param graphicsData {Graphics} The graphics object to update * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLGraphics.updateGraphics = function (graphics, gl) { +WebGLGraphics.updateGraphics = function (graphics, gl) +{ // get the contexts graphics object var webGL = graphics._webGL[gl.id]; // if the graphics object does not exist in the webGL context time to create it! - if (!webGL) { + if (!webGL) + { webGL = graphics._webGL[gl.id] = {lastIndex:0, data:[], gl:gl}; } @@ -99,11 +106,13 @@ var i; // if the user cleared the graphics object we will need to clear every object - if (graphics.clearDirty) { + if (graphics.clearDirty) + { graphics.clearDirty = false; // lop through and return all the webGLDatas to the object pool so than can be reused later on - for (i = 0; i < webGL.data.length; i++) { + for (i = 0; i < webGL.data.length; i++) + { var graphicsData = webGL.data[i]; graphicsData.reset(); WebGLGraphics.graphicsDataPool.push( graphicsData ); @@ -119,58 +128,72 @@ // loop through the graphics datas and construct each one.. // if the object is a complex fill then the new stencil buffer technique will be used // other wise graphics objects will be pushed into a batch.. - for (i = webGL.lastIndex; i < graphics.graphicsData.length; i++) { + for (i = webGL.lastIndex; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { // need to add the points the the graphics object.. data.points = data.shape.points.slice(); - if (data.shape.closed) { + if (data.shape.closed) + { // close the poly if the value is true! - if (data.points[0] !== data.points[data.points.length-2] || data.points[1] !== data.points[data.points.length-1]) { + if (data.points[0] !== data.points[data.points.length-2] || data.points[1] !== data.points[data.points.length-1]) + { data.points.push(data.points[0], data.points[1]); } } // MAKE SURE WE HAVE THE CORRECT TYPE.. - if (data.fill) { - if (data.points.length >= 6) { - if (data.points.length < 6 * 2) { + if (data.fill) + { + if (data.points.length >= 6) + { + if (data.points.length < 6 * 2) + { webGLData = WebGLGraphics.switchMode(webGL, 0); var canDrawUsingSimple = WebGLGraphics.buildPoly(data, webGLData); // console.log(canDrawUsingSimple); - if (!canDrawUsingSimple) { + if (!canDrawUsingSimple) + { // console.log("<>>>") webGLData = WebGLGraphics.switchMode(webGL, 1); WebGLGraphics.buildComplexPoly(data, webGLData); } } - else { + else + { webGLData = WebGLGraphics.switchMode(webGL, 1); WebGLGraphics.buildComplexPoly(data, webGLData); } } } - if (data.lineWidth > 0) { + if (data.lineWidth > 0) + { webGLData = WebGLGraphics.switchMode(webGL, 0); WebGLGraphics.buildLine(data, webGLData); } } - else { + else + { webGLData = WebGLGraphics.switchMode(webGL, 0); - if (data.type === CONST.SHAPES.RECT) { + if (data.type === CONST.SHAPES.RECT) + { WebGLGraphics.buildRectangle(data, webGLData); } - else if (data.type === CONST.SHAPES.CIRC || data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.CIRC || data.type === CONST.SHAPES.ELIP) + { WebGLGraphics.buildCircle(data, webGLData); } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { WebGLGraphics.buildRoundedRectangle(data, webGLData); } } @@ -179,10 +202,12 @@ } // upload all the dirty data... - for (i = 0; i < webGL.data.length; i++) { + for (i = 0; i < webGL.data.length; i++) + { webGLData = webGL.data[i]; - if (webGLData.dirty) { + if (webGLData.dirty) + { webGLData.upload(); } } @@ -194,18 +219,22 @@ * @param webGL {WebGLContext} * @param type {number} */ -WebGLGraphics.switchMode = function (webGL, type) { +WebGLGraphics.switchMode = function (webGL, type) +{ var webGLData; - if (!webGL.data.length) { + if (!webGL.data.length) + { webGLData = WebGLGraphics.graphicsDataPool.pop() || new WebGLGraphicsData(webGL.gl); webGLData.mode = type; webGL.data.push(webGLData); } - else { + else + { webGLData = webGL.data[webGL.data.length-1]; - if (webGLData.mode !== type || type === 1) { + if (webGLData.mode !== type || type === 1) + { webGLData = WebGLGraphics.graphicsDataPool.pop() || new WebGLGraphicsData(webGL.gl); webGLData.mode = type; webGL.data.push(webGLData); @@ -225,7 +254,8 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildRectangle = function (graphicsData, webGLData) { +WebGLGraphics.buildRectangle = function (graphicsData, webGLData) +{ // --- // // need to convert points to a nice regular data // @@ -235,7 +265,8 @@ var width = rectData.width; var height = rectData.height; - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -265,7 +296,8 @@ indices.push(vertPos, vertPos, vertPos+1, vertPos+2, vertPos+3, vertPos+3); } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = [x, y, @@ -289,7 +321,8 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildRoundedRectangle = function (graphicsData, webGLData) { +WebGLGraphics.buildRoundedRectangle = function (graphicsData, webGLData) +{ var rrectData = graphicsData.shape; var x = rrectData.x; var y = rrectData.y; @@ -305,7 +338,8 @@ recPoints = recPoints.concat(WebGLGraphics.quadraticBezierCurve(x + width, y + radius, x + width, y, x + width - radius, y)); recPoints = recPoints.concat(WebGLGraphics.quadraticBezierCurve(x + radius, y, x, y, x, y + radius)); - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -323,7 +357,8 @@ // var i = 0; - for (i = 0; i < triangles.length; i+=3) { + for (i = 0; i < triangles.length; i+=3) + { indices.push(triangles[i] + vecPos); indices.push(triangles[i] + vecPos); indices.push(triangles[i+1] + vecPos); @@ -332,12 +367,14 @@ } - for (i = 0; i < recPoints.length; i++) { + for (i = 0; i < recPoints.length; i++) + { verts.push(recPoints[i], recPoints[++i], r, g, b, alpha); } } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = recPoints; @@ -362,7 +399,8 @@ * @param toY {number} Destination point y * @return {number[]} */ -WebGLGraphics.quadraticBezierCurve = function (fromX, fromY, cpX, cpY, toX, toY) { +WebGLGraphics.quadraticBezierCurve = function (fromX, fromY, cpX, cpY, toX, toY) +{ var xa, ya, @@ -373,14 +411,16 @@ n = 20, points = []; - function getPt(n1 , n2, perc) { + function getPt(n1 , n2, perc) + { var diff = n2 - n1; return n1 + ( diff * perc ); } var j = 0; - for (var i = 0; i <= n; i++ ) { + for (var i = 0; i <= n; i++ ) + { j = i / n; // The Green Line @@ -406,7 +446,8 @@ * @param graphicsData {Graphics} The graphics object to draw * @param webGLData {object} */ -WebGLGraphics.buildCircle = function (graphicsData, webGLData) { +WebGLGraphics.buildCircle = function (graphicsData, webGLData) +{ // need to convert points to a nice regular data var circleData = graphicsData.shape; var x = circleData.x; @@ -415,11 +456,13 @@ var height; // TODO - bit hacky?? - if (graphicsData.type === CONST.SHAPES.CIRC) { + if (graphicsData.type === CONST.SHAPES.CIRC) + { width = circleData.radius; height = circleData.radius; } - else { + else + { width = circleData.width; height = circleData.height; } @@ -429,7 +472,8 @@ var i = 0; - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -444,7 +488,8 @@ indices.push(vecPos); - for (i = 0; i < totalSegs + 1 ; i++) { + for (i = 0; i < totalSegs + 1 ; i++) + { verts.push(x,y, r, g, b, alpha); verts.push(x + Math.sin(seg * i) * width, @@ -457,12 +502,14 @@ indices.push(vecPos-1); } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = []; - for (i = 0; i < totalSegs + 1; i++) { + for (i = 0; i < totalSegs + 1; i++) + { graphicsData.points.push(x + Math.sin(seg * i) * width, y + Math.cos(seg * i) * height); } @@ -481,18 +528,22 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildLine = function (graphicsData, webGLData) { +WebGLGraphics.buildLine = function (graphicsData, webGLData) +{ // TODO OPTIMISE! var i = 0; var points = graphicsData.points; - if (points.length === 0) { + if (points.length === 0) + { return; } // if the line width is an odd number add 0.5 to align to a whole pixel - if (graphicsData.lineWidth%2) { - for (i = 0; i < points.length; i++) { + if (graphicsData.lineWidth%2) + { + for (i = 0; i < points.length; i++) + { points[i] += 0.5; } } @@ -502,7 +553,8 @@ var lastPoint = new math.Point(points[points.length - 2], points[points.length - 1]); // if the first point is the last point - gonna have issues :) - if (firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) { + if (firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) + { // need to clone as we are going to slightly modify the shape.. points = points.slice(); @@ -562,7 +614,8 @@ verts.push(p1x + perpx , p1y + perpy, r, g, b, alpha); - for (i = 1; i < length-1; i++) { + for (i = 1; i < length-1; i++) + { p1x = points[(i-1)*2]; p1y = points[(i-1)*2 + 1]; @@ -599,7 +652,8 @@ denom = a1*b2 - a2*b1; - if (Math.abs(denom) < 0.1 ) { + if (Math.abs(denom) < 0.1 ) + { denom+=10.1; verts.push(p2x - perpx , p2y - perpy, @@ -618,7 +672,8 @@ pdist = (px -p2x) * (px -p2x) + (py -p2y) + (py -p2y); - if (pdist > 140 * 140) { + if (pdist > 140 * 140) + { perp3x = perpx - perp2x; perp3y = perpy - perp2y; @@ -639,7 +694,8 @@ indexCount++; } - else { + else + { verts.push(px , py); verts.push(r, g, b, alpha); @@ -672,7 +728,8 @@ indices.push(indexStart); - for (i = 0; i < indexCount; i++) { + for (i = 0; i < indexCount; i++) + { indices.push(indexStart++); } @@ -687,11 +744,13 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildComplexPoly = function (graphicsData, webGLData) { +WebGLGraphics.buildComplexPoly = function (graphicsData, webGLData) +{ //TODO - no need to copy this as it gets turned into a FLoat32Array anyways.. var points = graphicsData.points.slice(); - if (points.length < 6) { + if (points.length < 6) + { return; } @@ -711,7 +770,8 @@ var x,y; // get size.. - for (var i = 0; i < points.length; i+=2) { + for (var i = 0; i < points.length; i+=2) + { x = points[i]; y = points[i+1]; @@ -732,7 +792,8 @@ //TODO - this aint needed! var length = points.length / 2; - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { indices.push( i ); } @@ -746,10 +807,12 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildPoly = function (graphicsData, webGLData) { +WebGLGraphics.buildPoly = function (graphicsData, webGLData) +{ var points = graphicsData.points; - if (points.length < 6) { + if (points.length < 6) + { return; } // get first and last point.. figure out the middle! @@ -767,7 +830,8 @@ var triangles = utils.PolyK.Triangulate(points); - if (!triangles) { + if (!triangles) + { return false; } @@ -775,7 +839,8 @@ var i = 0; - for (i = 0; i < triangles.length; i+=3) { + for (i = 0; i < triangles.length; i+=3) + { indices.push(triangles[i] + vertPos); indices.push(triangles[i] + vertPos); indices.push(triangles[i+1] + vertPos); @@ -783,7 +848,8 @@ indices.push(triangles[i+2] + vertPos); } - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { verts.push(points[i * 2], points[i * 2 + 1], r, g, b, alpha); } diff --git a/src/core/renderers/webgl/utils/WebGLGraphicsData.js b/src/core/renderers/webgl/utils/WebGLGraphicsData.js index c56d05e..c739ba7 100644 --- a/src/core/renderers/webgl/utils/WebGLGraphicsData.js +++ b/src/core/renderers/webgl/utils/WebGLGraphicsData.js @@ -2,7 +2,8 @@ * @class * @private */ -function WebGLGraphicsData(gl) { +function WebGLGraphicsData(gl) +{ this.gl = gl; //TODO does this need to be split before uploding?? @@ -22,7 +23,8 @@ /** * */ -WebGLGraphicsData.prototype.reset = function () { +WebGLGraphicsData.prototype.reset = function () +{ this.points.length = 0; this.indices.length = 0; }; @@ -30,7 +32,8 @@ /** * */ -WebGLGraphicsData.prototype.upload = function () { +WebGLGraphicsData.prototype.upload = function () +{ var gl = this.gl; // this.lastIndex = graphics.graphicsData.length; diff --git a/src/core/renderers/webgl/utils/WebGLSpriteBatch.js b/src/core/renderers/webgl/utils/WebGLSpriteBatch.js index 96eaa52..55befbb 100644 --- a/src/core/renderers/webgl/utils/WebGLSpriteBatch.js +++ b/src/core/renderers/webgl/utils/WebGLSpriteBatch.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this sprite batch works for. */ -function WebGLSpriteBatch(renderer) { +function WebGLSpriteBatch(renderer) +{ /** * * @@ -88,7 +89,8 @@ */ this.lastIndexCount = 0; - for (var i=0, j=0; i < numIndices; i += 6, j += 4) { + 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; @@ -162,7 +164,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.setupContext(); }); } @@ -173,7 +176,8 @@ /** * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLSpriteBatch.prototype.setupContext = function () { +WebGLSpriteBatch.prototype.setupContext = function () +{ var gl = this.renderer.gl; // setup default shader @@ -198,7 +202,8 @@ /** * */ -WebGLSpriteBatch.prototype.begin = function () { +WebGLSpriteBatch.prototype.begin = function () +{ // this.shader = this.renderer.shaderManager.defaultShader; this.start(); @@ -206,19 +211,22 @@ /** */ -WebGLSpriteBatch.prototype.end = function () { +WebGLSpriteBatch.prototype.end = function () +{ this.flush(); }; /** * @param sprite {Sprite} the sprite to render when using this spritebatch */ -WebGLSpriteBatch.prototype.render = function (sprite) { +WebGLSpriteBatch.prototype.render = function (sprite) +{ var texture = sprite.texture; //TODO set blend modes.. // check texture.. - if (this.currentBatchSize >= this.size) { + if (this.currentBatchSize >= this.size) + { this.flush(); this.currentBaseTexture = texture.baseTexture; } @@ -227,7 +235,8 @@ var uvs = texture._uvs; // if the uvs have not updated then no point rendering just yet! - if (!uvs) { + if (!uvs) + { return; } @@ -237,7 +246,8 @@ var w0, w1, h0, h1; - if (texture.trim) { + 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; @@ -248,7 +258,8 @@ h0 = h1 + texture.crop.height; } - else { + else + { w0 = (texture.frame.width ) * (1-aX); w1 = (texture.frame.width ) * -aX; @@ -272,7 +283,8 @@ var colors = this.colors; var positions = this.positions; - if (this.renderer.roundPixels) { + if (this.renderer.roundPixels) + { // xy positions[index] = a * w1 + c * h1 + tx | 0; positions[index+1] = d * h1 + b * w1 + ty | 0; @@ -289,7 +301,8 @@ positions[index+15] = a * w1 + c * h0 + tx | 0; positions[index+16] = d * h0 + b * w1 + ty | 0; } - else { + else + { // xy positions[index] = a * w1 + c * h1 + tx; positions[index+1] = d * h1 + b * w1 + ty; @@ -338,11 +351,13 @@ * * @param sprite {TilingSprite} the tilingSprite to render */ -WebGLSpriteBatch.prototype.renderTilingSprite = function (tilingSprite) { +WebGLSpriteBatch.prototype.renderTilingSprite = function (tilingSprite) +{ var texture = tilingSprite.tilingTexture; // check texture.. - if (this.currentBatchSize >= this.size) { + if (this.currentBatchSize >= this.size) + { //return; this.flush(); this.currentBaseTexture = texture.baseTexture; @@ -351,7 +366,8 @@ // set the textures uvs temporarily // TODO create a separate texture so that we can tile part of a texture - if (!tilingSprite._uvs) { + if (!tilingSprite._uvs) + { tilingSprite._uvs = new TextureUvs(); } @@ -454,16 +470,19 @@ * Renders the content and empties the current batch. * */ -WebGLSpriteBatch.prototype.flush = function () { +WebGLSpriteBatch.prototype.flush = function () +{ // If the batch is length 0 then return as there is nothing to draw - if (this.currentBatchSize === 0) { + if (this.currentBatchSize === 0) + { return; } var gl = this.renderer.gl; var shader; - if (this.dirty) { + if (this.dirty) + { this.dirty = false; // bind the main texture gl.activeTexture(gl.TEXTURE0); @@ -482,10 +501,12 @@ } // upload the verts to the buffer - if (this.currentBatchSize > ( this.size * 0.5 ) ) { + if (this.currentBatchSize > ( this.size * 0.5 ) ) + { gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); } - else { + else + { var view = this.positions.subarray(0, this.currentBatchSize * this.vertByteSize); gl.bufferSubData(gl.ARRAY_BUFFER, 0, view); } @@ -502,7 +523,8 @@ var shaderSwap = false; var sprite; - for (var i = 0, j = this.currentBatchSize; i < j; i++) { + for (var i = 0, j = this.currentBatchSize; i < j; i++) + { sprite = this.sprites[i]; @@ -513,24 +535,28 @@ blendSwap = currentBlendMode !== nextBlendMode; shaderSwap = currentShader !== nextShader; // should I use uuidS??? - if (currentBaseTexture !== nextTexture || blendSwap || shaderSwap) { + if (currentBaseTexture !== nextTexture || blendSwap || shaderSwap) + { this.renderBatch(currentBaseTexture, batchSize, start); start = i; batchSize = 0; currentBaseTexture = nextTexture; - if (blendSwap) { + if (blendSwap) + { currentBlendMode = nextBlendMode; this.renderer.blendModeManager.setBlendMode( currentBlendMode ); } - if (shaderSwap) { + if (shaderSwap) + { currentShader = nextShader; shader = currentShader.shaders ? currentShader.shaders[gl.id] : currentShader; - if (!shader) { + if (!shader) + { shader = new Shader(gl, null, currentShader.fragmentSrc, currentShader.uniforms); currentShader.shaders[gl.id] = shader; } @@ -538,7 +564,8 @@ // set shader function??? this.renderer.shaderManager.setShader(shader); - if (shader.dirty) { + if (shader.dirty) + { shader.syncUniforms(); } @@ -569,17 +596,21 @@ * @param size {number} * @param startIndex {number} */ -WebGLSpriteBatch.prototype.renderBatch = function (texture, size, startIndex) { - if (size === 0) { +WebGLSpriteBatch.prototype.renderBatch = function (texture, size, startIndex) +{ + if (size === 0) + { return; } var gl = this.renderer.gl; - if (!texture._glTextures[gl.id]) { + if (!texture._glTextures[gl.id]) + { this.renderer.updateTexture(texture); } - else { + else + { // bind the current texture gl.bindTexture(gl.TEXTURE_2D, texture._glTextures[gl.id]); } @@ -594,7 +625,8 @@ /** * */ -WebGLSpriteBatch.prototype.stop = function () { +WebGLSpriteBatch.prototype.stop = function () +{ this.flush(); this.dirty = true; }; @@ -602,7 +634,8 @@ /** * */ -WebGLSpriteBatch.prototype.start = function () { +WebGLSpriteBatch.prototype.start = function () +{ this.dirty = true; }; @@ -610,7 +643,8 @@ * Destroys the SpriteBatch. * */ -WebGLSpriteBatch.prototype.destroy = function () { +WebGLSpriteBatch.prototype.destroy = function () +{ this.renderer.gl.deleteBuffer(this.vertexBuffer); this.renderer.gl.deleteBuffer(this.indexBuffer); diff --git a/src/core/textures/BaseTexture.js b/src/core/textures/BaseTexture.js index 2bf77d4..513d358 100644 --- a/src/core/textures/BaseTexture.js +++ b/src/core/textures/BaseTexture.js @@ -10,7 +10,8 @@ * @param source {Image|Canvas} the source object of the texture. * @param [scaleMode=scaleModes.DEFAULT] {number} See {@link scaleModes} for possible values */ -function BaseTexture(source, scaleMode) { +function BaseTexture(source, scaleMode) +{ this.uuid = utils.uuid(); /** @@ -123,7 +124,8 @@ this._needsUpdate = false; // if no source passed don't try to load - if (source) { + if (source) + { this.loadSource(source); } @@ -149,13 +151,16 @@ Object.defineProperties(BaseTexture.prototype, { needsUpdate: { - get: function () { + get: function () + { return this._needsUpdate; }, - set: function (val) { + set: function (val) + { this._needsUpdate = val; - if (val) { + if (val) + { this.emit('update', this); } } @@ -171,9 +176,11 @@ * * The logic state after calling `loadSource` directly or indirectly (eg. `fromImage`, `new BaseTexture`) is: * - * if (texture.hasLoaded) { + * if (texture.hasLoaded) + { * // texture ready for use - * } else if (texture.isLoading) { + * } else if (texture.isLoading) + { * // listen to 'loaded' and/or 'error' events on texture * } else { * // not loading, not going to load UNLESS the source is reloaded @@ -183,12 +190,14 @@ * @protected * @param source {Image|Canvas} the source object of the texture. */ -BaseTexture.prototype.loadSource = function (source) { +BaseTexture.prototype.loadSource = function (source) +{ var wasLoading = this.isLoading; this.hasLoaded = false; this.isLoading = false; - if (wasLoading && this.source) { + if (wasLoading && this.source) + { this.source.onload = null; this.source.onerror = null; } @@ -196,20 +205,24 @@ this.source = source; // Apply source if loaded. Otherwise setup appropriate loading monitors. - if ((this.source.complete || this.source.getContext) && this.source.width && this.source.height) { + if ((this.source.complete || this.source.getContext) && this.source.width && this.source.height) + { this._sourceLoaded(); } - else if(!source.getContext) { + else if(!source.getContext) + { // Image fail / not ready this.isLoading = true; var scope = this; - source.onload = function () { + source.onload = function () + { source.onload = null; source.onerror = null; - if(!scope.isLoading) { + if(!scope.isLoading) + { return; } @@ -219,11 +232,13 @@ scope.emit('loaded', scope); }; - source.onerror = function () { + source.onerror = function () + { source.onload = null; source.onerror = null; - if(!scope.isLoading) { + if(!scope.isLoading) + { return; } @@ -234,24 +249,29 @@ // Per http://www.w3.org/TR/html5/embedded-content-0.html#the-img-element // "The value of `complete` can thus change while a script is executing." // So complete needs to be re-checked after the callbacks have been added.. - if (source.complete) { + if (source.complete) + { this.isLoading = false; // ..and if we're complete now, no need for callbacks source.onload = null; source.onerror = null; - if (source.width && source.height) { + if (source.width && source.height) + { this._sourceLoaded(); // If any previous subscribers possible - if (wasLoading) { + if (wasLoading) + { this.emit('loaded', this); } } - else { + else + { // If any previous subscribers possible - if (wasLoading) { + if (wasLoading) + { this.emit('error', this); } } @@ -265,7 +285,8 @@ * * @private */ -BaseTexture.prototype._sourceLoaded = function () { +BaseTexture.prototype._sourceLoaded = function () +{ this.hasLoaded = true; this.width = this.source.naturalWidth || this.source.width; @@ -278,16 +299,20 @@ * Destroys this base texture * */ -BaseTexture.prototype.destroy = function () { - if (this.imageUrl) { +BaseTexture.prototype.destroy = function () +{ + if (this.imageUrl) + { delete utils.BaseTextureCache[this.imageUrl]; delete utils.TextureCache[this.imageUrl]; this.imageUrl = null; - if (!navigator.isCocoonJS) { + if (!navigator.isCocoonJS) + { this.source.src = ''; } } - else if (this.source && this.source._pixiId) { + else if (this.source && this.source._pixiId) + { delete utils.BaseTextureCache[this.source._pixiId]; } this.source = null; @@ -301,7 +326,8 @@ * memory again. * */ -BaseTexture.prototype.dispose = function () { +BaseTexture.prototype.dispose = function () +{ this.emit('dispose', this); }; @@ -311,7 +337,8 @@ * * @param newSrc {string} the path of the image */ -BaseTexture.prototype.updateSourceImage = function (newSrc) { +BaseTexture.prototype.updateSourceImage = function (newSrc) +{ this.source.src = newSrc; this.loadSource(this.source); }; @@ -326,18 +353,22 @@ * @param [scaleMode=scaleModes.DEFAULT] {number} See {@link scaleModes} for possible values * @return BaseTexture */ -BaseTexture.fromImage = function (imageUrl, crossorigin, scaleMode) { +BaseTexture.fromImage = function (imageUrl, crossorigin, scaleMode) +{ var baseTexture = utils.BaseTextureCache[imageUrl]; - if (crossorigin === undefined && imageUrl.indexOf('data:') !== 0) { + if (crossorigin === undefined && imageUrl.indexOf('data:') !== 0) + { crossorigin = true; } - if (!baseTexture) { + if (!baseTexture) + { // new Image() breaks tex loading in some versions of Chrome. // See https://code.google.com/p/chromium/issues/detail?id=238071 var image = new Image();//document.createElement('img'); - if (crossorigin) { + if (crossorigin) + { image.crossOrigin = ''; } @@ -347,7 +378,8 @@ utils.BaseTextureCache[imageUrl] = baseTexture; // if there is an @2x at the end of the url we are going to assume its a highres image - if ( imageUrl.indexOf(CONST.RETINA_PREFIX + '.') !== -1) { + if ( imageUrl.indexOf(CONST.RETINA_PREFIX + '.') !== -1) + { baseTexture.resolution = 2; } } @@ -363,14 +395,17 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return BaseTexture */ -BaseTexture.fromCanvas = function (canvas, scaleMode) { - if (!canvas._pixiId) { +BaseTexture.fromCanvas = function (canvas, scaleMode) +{ + if (!canvas._pixiId) + { canvas._pixiId = 'canvas_' + utils.uuid(); } var baseTexture = utils.BaseTextureCache[canvas._pixiId]; - if (!baseTexture) { + if (!baseTexture) + { baseTexture = new BaseTexture(canvas, scaleMode); utils.BaseTextureCache[canvas._pixiId] = baseTexture; } diff --git a/src/core/textures/RenderTexture.js b/src/core/textures/RenderTexture.js index 6dad20f..53ae796 100644 --- a/src/core/textures/RenderTexture.js +++ b/src/core/textures/RenderTexture.js @@ -46,8 +46,10 @@ * @param [scaleMode] {number} See {@link scaleModes} for possible values * @param [resolution=1] {number} The resolution of the texture being generated */ -function RenderTexture(renderer, width, height, scaleMode, resolution) { - if (!renderer) { +function RenderTexture(renderer, width, height, scaleMode, resolution) +{ + if (!renderer) + { throw new Error('Unable to create RenderTexture, you must pass a renderer into the constructor.'); } @@ -133,7 +135,8 @@ */ this.renderer = renderer; - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { var gl = this.renderer.gl; this.textureBuffer = new FilterTexture(gl, this.width * this.resolution, this.height * this.resolution, this.baseTexture.scaleMode); @@ -142,7 +145,8 @@ this.render = this.renderWebGL; this.projection = new math.Point(this.width*0.5, -this.height*0.5); } - else { + else + { this.render = this.renderCanvas; this.textureBuffer = new CanvasBuffer(this.width* this.resolution, this.height* this.resolution); this.baseTexture.source = this.textureBuffer.canvas; @@ -167,8 +171,10 @@ * @param height {number} The height to resize to. * @param updateBase {boolean} Should the baseTexture.width and height values be resized as well? */ -RenderTexture.prototype.resize = function (width, height, updateBase) { - if (width === this.width && height === this.height) { +RenderTexture.prototype.resize = function (width, height, updateBase) +{ + if (width === this.width && height === this.height) + { return; } @@ -177,17 +183,20 @@ this.width = this.frame.width = this.crop.width = width; this.height = this.frame.height = this.crop.height = height; - if (updateBase) { + if (updateBase) + { this.baseTexture.width = this.width; this.baseTexture.height = this.height; } - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { this.projection.x = this.width / 2; this.projection.y = -this.height / 2; } - if (!this.valid) { + if (!this.valid) + { return; } @@ -198,12 +207,15 @@ * Clears the RenderTexture. * */ -RenderTexture.prototype.clear = function () { - if (!this.valid) { +RenderTexture.prototype.clear = function () +{ + if (!this.valid) + { return; } - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { this.renderer.gl.bindFramebuffer(this.renderer.gl.FRAMEBUFFER, this.textureBuffer.frameBuffer); } @@ -220,19 +232,23 @@ * @param [restoreWorldTransform=true] {boolean} If true the displayObject's worldTransform/worldAlpha and all children * transformations will be restored. Not restoring this information will be a little faster. */ -RenderTexture.prototype.renderWebGL = function (displayObject, matrix, clear, restoreWorldTransform) { - if (!this.valid) { +RenderTexture.prototype.renderWebGL = function (displayObject, matrix, clear, restoreWorldTransform) +{ + if (!this.valid) + { return; } - if (typeof restoreWorldTransform === 'undefined') { + if (typeof restoreWorldTransform === 'undefined') + { restoreWorldTransform = true; } var tempAlpha, tempTransform; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { tempAlpha = displayObject.worldAlpha; tempTransform = displayObject.worldTransform.toArray(); } @@ -245,7 +261,8 @@ wt.identity(); wt.translate(0, this.projection.y * 2); - if (matrix) { + if (matrix) + { wt.append(matrix); } @@ -258,7 +275,8 @@ var children = displayObject.children; var i, j; - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } @@ -269,7 +287,8 @@ gl.bindFramebuffer(gl.FRAMEBUFFER, this.textureBuffer.frameBuffer ); - if (clear) { + if (clear) + { this.textureBuffer.clear(); } @@ -279,11 +298,13 @@ this.renderer.spriteBatch.dirty = true; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { displayObject.worldAlpha = tempAlpha; displayObject.worldTransform.fromArray(tempTransform); - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } } @@ -300,26 +321,31 @@ * @param [restoreWorldTransform=true] {boolean} If true the displayObject's worldTransform/worldAlpha and all children * transformations will be restored. Not restoring this information will be a little faster. */ -RenderTexture.prototype.renderCanvas = function (displayObject, matrix, clear, restoreWorldTransform) { - if (!this.valid) { +RenderTexture.prototype.renderCanvas = function (displayObject, matrix, clear, restoreWorldTransform) +{ + if (!this.valid) + { return; } - if (typeof restoreWorldTransform === 'undefined') { + if (typeof restoreWorldTransform === 'undefined') + { restoreWorldTransform = true; } var tempAlpha, tempTransform; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { tempAlpha = displayObject.worldAlpha; tempTransform = displayObject.worldTransform.toArray(); } var wt = displayObject.worldTransform; wt.identity(); - if (matrix) { + if (matrix) + { wt.append(matrix); } @@ -330,11 +356,13 @@ var children = displayObject.children; var i, j; - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } - if (clear) { + if (clear) + { this.textureBuffer.clear(); } @@ -348,11 +376,13 @@ this.renderer.resolution = realResolution; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { displayObject.worldAlpha = tempAlpha; displayObject.worldTransform.fromArray(tempTransform); - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } } @@ -363,7 +393,8 @@ * * @return {Image} */ -RenderTexture.prototype.getImage = function () { +RenderTexture.prototype.getImage = function () +{ var image = new Image(); image.src = this.getBase64(); return image; @@ -374,7 +405,8 @@ * * @return {string} A base64 encoded string of the texture. */ -RenderTexture.prototype.getBase64 = function () { +RenderTexture.prototype.getBase64 = function () +{ return this.getCanvas().toDataURL(); }; @@ -383,8 +415,10 @@ * * @return {HTMLCanvasElement} A Canvas element with the texture rendered on. */ -RenderTexture.prototype.getCanvas = function () { - if (this.renderer.type === CONST.WEBGL_RENDERER) { +RenderTexture.prototype.getCanvas = function () +{ + if (this.renderer.type === CONST.WEBGL_RENDERER) + { var gl = this.renderer.gl; var width = this.textureBuffer.width; var height = this.textureBuffer.height; @@ -403,7 +437,8 @@ return tempCanvas.canvas; } - else { + else + { return this.textureBuffer.canvas; } }; diff --git a/src/core/textures/Texture.js b/src/core/textures/Texture.js index 3c65909..e97f0aa 100644 --- a/src/core/textures/Texture.js +++ b/src/core/textures/Texture.js @@ -17,7 +17,8 @@ * @param [crop] {Rectangle} The area of original texture * @param [trim] {Rectangle} Trimmed texture rectangle */ -function Texture(baseTexture, frame, crop, trim) { +function Texture(baseTexture, frame, crop, trim) +{ /** * Does this Texture have any frame data assigned to it? * @@ -25,12 +26,14 @@ */ this.noFrame = false; - if (!frame) { + if (!frame) + { this.noFrame = true; frame = new math.Rectangle(0, 0, 1, 1); } - if (baseTexture instanceof Texture) { + if (baseTexture instanceof Texture) + { baseTexture = baseTexture.baseTexture; } @@ -100,13 +103,16 @@ */ this.crop = crop || new math.Rectangle(0, 0, 1, 1); - if (baseTexture.hasLoaded) { - if (this.noFrame) { + if (baseTexture.hasLoaded) + { + if (this.noFrame) + { frame = new math.Rectangle(0, 0, baseTexture.width, baseTexture.height); } this.frame = frame; } - else { + else + { baseTexture.addEventListener('loaded', this.onBaseTextureLoaded.bind(this)); } } @@ -118,19 +124,23 @@ Object.defineProperties(Texture.prototype, { needsUpdate: { - get: function () { + get: function () + { return this.baseTexture.needsUpdate; }, - set: function (val) { + set: function (val) + { this.baseTexture.needsUpdate = val; } }, frame: { - get: function () { + get: function () + { return this._frame; }, - set: function (frame) { + set: function (frame) + { this._frame = frame; this.noFrame = false; @@ -143,20 +153,23 @@ 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 (!this.trim && (frame.x + frame.width > this.baseTexture.width || frame.y + frame.height > this.baseTexture.height)) + { throw new Error('Texture Error: frame does not fit inside the base Texture dimensions ' + this); } this.valid = frame && frame.width && frame.height && this.baseTexture.source && this.baseTexture.hasLoaded; - if (this.trim) { + 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) { + if (this.valid) + { this._updateUvs(); } } @@ -168,11 +181,13 @@ * * @private */ -Texture.prototype.onBaseTextureLoaded = function () { +Texture.prototype.onBaseTextureLoaded = function () +{ var baseTexture = this.baseTexture; baseTexture.removeEventListener('loaded', this.onLoaded); - if (this.noFrame) { + if (this.noFrame) + { this.frame = new math.Rectangle(0, 0, baseTexture.width, baseTexture.height); } @@ -184,8 +199,10 @@ * * @param destroyBase {boolean} Whether to destroy the base texture as well */ -Texture.prototype.destroy = function (destroyBase) { - if (destroyBase) { +Texture.prototype.destroy = function (destroyBase) +{ + if (destroyBase) + { this.baseTexture.destroy(); } @@ -197,8 +214,10 @@ * * @private */ -Texture.prototype._updateUvs = function () { - if (!this._uvs) { +Texture.prototype._updateUvs = function () +{ + if (!this._uvs) + { this._uvs = new TextureUvs(); } @@ -229,10 +248,12 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return Texture */ -Texture.fromImage = function (imageUrl, crossorigin, scaleMode) { +Texture.fromImage = function (imageUrl, crossorigin, scaleMode) +{ var texture = utils.TextureCache[imageUrl]; - if (!texture) { + if (!texture) + { texture = new Texture(BaseTexture.fromImage(imageUrl, crossorigin, scaleMode)); utils.TextureCache[imageUrl] = texture; } @@ -248,9 +269,11 @@ * @param frameId {string} The frame id of the texture * @return Texture */ -Texture.fromFrame = function (frameId) { +Texture.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache '); } return texture; @@ -264,7 +287,8 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return {Texture} */ -Texture.fromCanvas = function (canvas, scaleMode) { +Texture.fromCanvas = function (canvas, scaleMode) +{ return new Texture(BaseTexture.fromCanvas(canvas, scaleMode)); }; @@ -276,7 +300,8 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return {Texture} A Texture */ -Texture.fromVideo = function (video, scaleMode) { +Texture.fromVideo = function (video, scaleMode) +{ return new Texture(VideoBaseTexture.baseTextureFromVideo(video, scaleMode)); }; @@ -287,7 +312,8 @@ * @param texture {Texture} The Texture to add to the cache. * @param id {string} The id that the texture will be stored against. */ -Texture.addTextureToCache = function (texture, id) { +Texture.addTextureToCache = function (texture, id) +{ utils.TextureCache[id] = texture; }; @@ -298,7 +324,8 @@ * @param id {string} The id of the texture to be removed * @return {Texture} The texture that was removed */ -Texture.removeTextureFromCache = function (id) { +Texture.removeTextureFromCache = function (id) +{ var texture = utils.TextureCache[id]; delete utils.TextureCache[id]; diff --git a/src/core/textures/TextureUvs.js b/src/core/textures/TextureUvs.js index b9bbb58..5424d52 100644 --- a/src/core/textures/TextureUvs.js +++ b/src/core/textures/TextureUvs.js @@ -1,4 +1,5 @@ -function TextureUvs() { +function TextureUvs() +{ this.x0 = 0; this.y0 = 0; diff --git a/src/core/textures/VideoBaseTexture.js b/src/core/textures/VideoBaseTexture.js index e3e0c5a..1a826a9 100644 --- a/src/core/textures/VideoBaseTexture.js +++ b/src/core/textures/VideoBaseTexture.js @@ -12,15 +12,18 @@ * @param source {HTMLVideoElement} * @param [scaleMode] {number} See {@link scaleModes} for possible values */ -function VideoBaseTexture(source, scaleMode) { - if (!source){ +function VideoBaseTexture(source, scaleMode) +{ + if (!source) + { throw new Error('No video source element specified.'); } // hook in here to check if video is already available. // BaseTexture looks for a source.complete boolean, plus width & height. - if ((source.readyState === source.HAVE_ENOUGH_DATA || source.readyState === source.HAVE_FUTURE_DATA) && source.width && source.height) { + if ((source.readyState === source.HAVE_ENOUGH_DATA || source.readyState === source.HAVE_FUTURE_DATA) && source.width && source.height) + { source.complete = true; } @@ -31,7 +34,8 @@ this._boundOnUpdate = this._onUpdate.bind(this); this._boundOnCanPlay = this._onCanPlay.bind(this); - if (!source.complete) { + if (!source.complete) + { source.addEventListener('canplay', this._boundOnCanPlay); source.addEventListener('canplaythrough', this._boundOnCanPlay); @@ -47,28 +51,35 @@ VideoBaseTexture.prototype.constructor = VideoBaseTexture; module.exports = VideoBaseTexture; -VideoBaseTexture.prototype._onUpdate = function () { - if (this.autoUpdate) { +VideoBaseTexture.prototype._onUpdate = function () +{ + if (this.autoUpdate) + { window.requestAnimationFrame(this._boundOnUpdate); this.needsUpdate = true; } }; -VideoBaseTexture.prototype._onPlayStart = function () { - if (!this.autoUpdate) { +VideoBaseTexture.prototype._onPlayStart = function () +{ + if (!this.autoUpdate) + { window.requestAnimationFrame(this._boundOnUpdate); this.autoUpdate = true; } }; -VideoBaseTexture.prototype._onPlayStop = function () { +VideoBaseTexture.prototype._onPlayStop = function () +{ this.autoUpdate = false; }; -VideoBaseTexture.prototype._onCanPlay = function () { +VideoBaseTexture.prototype._onCanPlay = function () +{ this.hasLoaded = true; - if (this.source) { + if (this.source) + { this.source.removeEventListener('canplay', this._boundOnCanPlay); this.source.removeEventListener('canplaythrough', this._boundOnCanPlay); @@ -78,15 +89,18 @@ this.source.play(); // prevent multiple loaded dispatches.. - if(!this.__loaded){ + if(!this.__loaded) + { this.__loaded = true; this.emit('loaded', this); } } }; -VideoBaseTexture.prototype.destroy = function () { - if (this.source && this.source._pixiId) { +VideoBaseTexture.prototype.destroy = function () +{ + if (this.source && this.source._pixiId) + { utils.BaseTextureCache[ this.source._pixiId ] = null; delete utils.BaseTextureCache[ this.source._pixiId ]; @@ -105,14 +119,17 @@ * @param scaleMode {number} See {@link scaleModes} for possible values * @return {VideoBaseTexture} */ -VideoBaseTexture.fromVideo = function (video, scaleMode) { - if (!video._pixiId) { +VideoBaseTexture.fromVideo = function (video, scaleMode) +{ + if (!video._pixiId) + { video._pixiId = 'video_' + utils.uuid(); } var baseTexture = utils.BaseTextureCache[video._pixiId]; - if (!baseTexture) { + if (!baseTexture) + { baseTexture = new VideoBaseTexture(video, scaleMode); utils.BaseTextureCache[ video._pixiId ] = baseTexture; } @@ -147,17 +164,21 @@ * @param scaleMode {number} See {@link scaleModes} for possible values * @return {VideoBaseTexture} */ -VideoBaseTexture.fromUrl = function (videoSrc, scaleMode) { +VideoBaseTexture.fromUrl = function (videoSrc, scaleMode) +{ var video = document.createElement('video'); // array of objects or strings - if (Array.isArray(videoSrc)) { - for (var i = 0; i < videoSrc.length; ++i) { + if (Array.isArray(videoSrc)) + { + for (var i = 0; i < videoSrc.length; ++i) + { video.appendChild(createSource(videoSrc.src || videoSrc, videoSrc.mime)); } } // single object or string - else { + else + { video.appendChild(createSource(videoSrc.src || videoSrc, videoSrc.mime)); } @@ -169,8 +190,10 @@ VideoBaseTexture.fromUrls = VideoBaseTexture.fromUrl; -function createSource(path, type) { - if (!type) { +function createSource(path, type) +{ + if (!type) + { type = 'video/' + path.substr(path.lastIndexOf('.') + 1); } diff --git a/src/core/utils/EventData.js b/src/core/utils/EventData.js index 5d55a22..8cdf701 100644 --- a/src/core/utils/EventData.js +++ b/src/core/utils/EventData.js @@ -7,7 +7,8 @@ * @param name {string} The string name of the event that was triggered * @param data {object} Arbitrary event data to pass along */ -function EventData(target, name, data) { +function EventData(target, name, data) +{ // for duck typing in the ".on()" function this.__isEventObject = true; @@ -71,7 +72,8 @@ * Stops the propagation of events up the scene graph (prevents bubbling). * */ -EventData.prototype.stopPropagation = function stopPropagation() { +EventData.prototype.stopPropagation = function stopPropagation() +{ this.stopped = true; }; @@ -79,6 +81,7 @@ * Stops the propagation of events to sibling listeners (no longer calls any listeners). * */ -EventData.prototype.stopImmediatePropagation = function stopImmediatePropagation() { +EventData.prototype.stopImmediatePropagation = function stopImmediatePropagation() +{ this.stoppedImmediate = true; }; diff --git a/src/core/utils/EventTarget.js b/src/core/utils/EventTarget.js index 7ae8820..671a151 100644 --- a/src/core/utils/EventTarget.js +++ b/src/core/utils/EventTarget.js @@ -13,14 +13,16 @@ * var em = new MyEmitter(); * em.emit('eventName', 'some data', 'some more data', {}, null, ...); */ -function eventTarget(obj) { +function eventTarget(obj) +{ /** * Return a list of assigned event listeners. * * @param eventName {string} The events that should be listed. * @return {Array} An array of listener functions */ - obj.listeners = function listeners(eventName) { + obj.listeners = function listeners(eventName) + { this._listeners = this._listeners || {}; return this._listeners[eventName] ? this._listeners[eventName].slice() : []; @@ -33,22 +35,26 @@ * @param eventName {string} The name of the event. * @return {boolean} Indication if we've emitted an event. */ - obj.emit = obj.dispatchEvent = function emit(eventName, data) { + obj.emit = obj.dispatchEvent = function emit(eventName, data) + { this._listeners = this._listeners || {}; // fast return when there are no listeners - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return; } //backwards compat with old method ".emit({ type: 'something' })" - if (typeof eventName === 'object') { + if (typeof eventName === 'object') + { data = eventName; eventName = eventName.type; } //ensure we are using a real pixi event - if (!data || data.__isEventObject !== true) { + if (!data || data.__isEventObject !== true) + { data = new EventData(this, eventName, data); } @@ -58,23 +64,27 @@ fn = listeners[0], i; - for (i = 0; i < length; fn = listeners[++i]) { + for (i = 0; i < length; fn = listeners[++i]) + { //call the event listener fn.call(this, data); //if "stopImmediatePropagation" is called, stop calling sibling events - if (data.stoppedImmediate) { + if (data.stoppedImmediate) + { return this; } } //if "stopPropagation" is called then don't bubble the event - if (data.stopped) { + if (data.stopped) + { return this; } //bubble this event up the scene graph - if (this.parent && this.parent.emit) { + if (this.parent && this.parent.emit) + { this.parent.emit.call(this.parent, eventName, data); } @@ -88,7 +98,8 @@ * @param eventName {string} Name of the event. * @param callback {Functon} fn Callback function. */ - obj.on = obj.addEventListener = function on(eventName, fn) { + obj.on = obj.addEventListener = function on(eventName, fn) + { this._listeners = this._listeners || {}; (this._listeners[eventName] = this._listeners[eventName] || []) @@ -103,11 +114,13 @@ * @param eventName {string} Name of the event. * @param callback {Function} Callback function. */ - obj.once = function once(eventName, fn) { + obj.once = function once(eventName, fn) + { this._listeners = this._listeners || {}; var self = this; - function onceHandlerWrapper() { + function onceHandlerWrapper() + { fn.apply(self.off(eventName, onceHandlerWrapper), arguments); } onceHandlerWrapper._originalHandler = fn; @@ -122,23 +135,28 @@ * @param eventName {string} The event we want to remove. * @param callback {Function} The listener that we need to find. */ - obj.off = obj.removeEventListener = function off(eventName, fn) { + obj.off = obj.removeEventListener = function off(eventName, fn) + { this._listeners = this._listeners || {}; - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return this; } var list = this._listeners[eventName], i = fn ? list.length : 0; - while(i-- > 0) { - if (list[i] === fn || list[i]._originalHandler === fn) { + while(i-- > 0) + { + if (list[i] === fn || list[i]._originalHandler === fn) + { list.splice(i, 1); } } - if (list.length === 0) { + if (list.length === 0) + { delete this._listeners[eventName]; } @@ -150,10 +168,12 @@ * * @param eventName {string} The event you want to remove all listeners for. */ - obj.removeAllListeners = function removeAllListeners(eventName) { + obj.removeAllListeners = function removeAllListeners(eventName) + { this._listeners = this._listeners || {}; - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return this; } @@ -169,7 +189,8 @@ * * @param object {object} The obj to mix into */ - mixin: function mixin(obj) { + mixin: function mixin(obj) + { eventTarget(obj); } }; diff --git a/src/core/utils/PolyK.js b/src/core/utils/PolyK.js index 7325141..5e20c2b 100644 --- a/src/core/utils/PolyK.js +++ b/src/core/utils/PolyK.js @@ -47,7 +47,8 @@ * Triangulates shapes for webGL graphic fills. * */ -PolyK.Triangulate = function (p) { +PolyK.Triangulate = function (p) +{ var sign = true; var n = p.length >> 1; @@ -59,7 +60,8 @@ i = 0; var al = n; - while(al > 3) { + while(al > 3) + { var i0 = avl[(i+0)%al]; var i1 = avl[(i+1)%al]; var i2 = avl[(i+2)%al]; @@ -69,29 +71,35 @@ var cx = p[2*i2], cy = p[2*i2+1]; var earFound = false; - if (PolyK._convex(ax, ay, bx, by, cx, cy, sign)) { + if (PolyK._convex(ax, ay, bx, by, cx, cy, sign)) + { earFound = true; - for (var j = 0; j < al; j++) { + for (var j = 0; j < al; j++) + { var vi = avl[j]; if (vi === i0 || vi === i1 || vi === i2) continue; - if (PolyK._PointInTriangle(p[2*vi], p[2*vi+1], ax, ay, bx, by, cx, cy)) { + if (PolyK._PointInTriangle(p[2*vi], p[2*vi+1], ax, ay, bx, by, cx, cy)) + { earFound = false; break; } } } - if (earFound) { + if (earFound) + { tgs.push(i0, i1, i2); avl.splice((i+1)%al, 1); al--; i = 0; } - else if (i++ > 3*al) { + else if (i++ > 3*al) + { // need to flip flip reverse it! // reset! - if (sign) { + if (sign) + { tgs = []; avl = []; for (i = 0; i < n; i++) avl.push(i); @@ -101,7 +109,8 @@ sign = false; } - else { + else + { // window.console.log("PIXI Warning: shape too complex to fill"); return null; } @@ -126,7 +135,8 @@ * @private * @return {boolean} */ -PolyK._PointInTriangle = function (px, py, ax, ay, bx, by, cx, cy) { +PolyK._PointInTriangle = function (px, py, ax, ay, bx, by, cx, cy) +{ var v0x = cx-ax; var v0y = cy-ay; var v1x = bx-ax; @@ -154,6 +164,7 @@ * @private * @return {boolean} */ -PolyK._convex = function (ax, ay, bx, by, cx, cy, sign) { +PolyK._convex = function (ax, ay, bx, by, cx, cy, sign) +{ return ((ay-by)*(cx-bx) + (bx-ax)*(cy-by) >= 0) === sign; }; diff --git a/src/core/utils/index.js b/src/core/utils/index.js index ade9831..bfae7ae 100644 --- a/src/core/utils/index.js +++ b/src/core/utils/index.js @@ -16,7 +16,8 @@ * * @return {number} The next uuid to use. */ - uuid: function () { + uuid: function () + { return ++utils._uid; }, @@ -26,7 +27,8 @@ * @param hex {number} * @return {number[]} An array representing the [R, G, B] of the color. */ - hex2rgb: function (hex, out) { + hex2rgb: function (hex, out) + { out = out || []; out[0] = (hex >> 16 & 0xFF) / 255; @@ -42,7 +44,8 @@ * @param hex {number} * @return {string} The string color. */ - hex2string: function (hex) { + hex2string: function (hex) + { hex = hex.toString(16); hex = '000000'.substr(0, 6 - hex.length) + hex; @@ -55,7 +58,8 @@ * @param rgb {number[]} * @return {number} The color number */ - rgb2hex: function (rgb) { + rgb2hex: function (rgb) + { return ((rgb[0]*255 << 16) + (rgb[1]*255 << 8) + rgb[2]*255); }, @@ -64,8 +68,10 @@ * * @return {boolean} whether they are supported */ - canUseNewCanvasBlendModes: function () { - if (typeof document === 'undefined') { + canUseNewCanvasBlendModes: function () + { + if (typeof document === 'undefined') + { return false; } @@ -93,15 +99,19 @@ * @param number {number} * @return {number} the closest number that is a power of two */ - getNextPowerOfTwo: function (number) { + getNextPowerOfTwo: function (number) + { // see: http://en.wikipedia.org/wiki/Power_of_two#Fast_algorithm_to_check_if_a_positive_number_is_a_power_of_two - if (number > 0 && (number & (number - 1)) === 0) { + if (number > 0 && (number & (number - 1)) === 0) + { return number; } - else { + else + { var result = 1; - while (result < number) { + while (result < number) + { result <<= 1; } @@ -116,7 +126,8 @@ * @param height {number} * @return {boolean} */ - isPowerOfTwo: function (width, height) { + isPowerOfTwo: function (width, height) + { return (width > 0 && (width & (width - 1)) === 0 && height > 0 && (height & (height - 1)) === 0); }, @@ -130,12 +141,15 @@ * @constant * @static */ - sayHello: function (type) { - if (utils._saidHello) { + sayHello: function (type) + { + if (utils._saidHello) + { return; } - if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) { + if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) + { var args = [ '%c %c %c Pixi.js ' + CONST.VERSION + ' - ' + type + ' %c ' + ' %c ' + ' http://www.pixijs.com/ %c %c ♥%c♥%c♥ ', 'background: #ff66a5', @@ -151,7 +165,8 @@ console.log.apply(console, args); //jshint ignore:line } - else if (window.console) { + else if (window.console) + { console.log('Pixi.js ' + CONST.VERSION + ' - ' + type + ' - http://www.pixijs.com/'); //jshint ignore:line } @@ -166,15 +181,19 @@ * @class * @namespace PIXI */ - AjaxRequest: function () { + AjaxRequest: function () + { var activexmodes = ['Msxml2.XMLHTTP.6.0', 'Msxml2.XMLHTTP.3.0', 'Microsoft.XMLHTTP']; //activeX versions to check for in IE - if (window.ActiveXObject) { //Test for support for ActiveXObject in IE first (as XMLHttpRequest in IE7 is broken) - for (var i=0; i= this.textures.length) { + else if (round >= this.textures.length) + { this.gotoAndStop(this.textures.length - 1); - if (this.onComplete) { + if (this.onComplete) + { this.onComplete(); } } @@ -167,10 +182,12 @@ * @static * @param frames {string[]} the array of frames ids the movieclip will use as its texture frames */ -MovieClip.fromFrames = function (frames) { +MovieClip.fromFrames = function (frames) +{ var textures = []; - for (var i = 0; i < frames.length; ++i) { + for (var i = 0; i < frames.length; ++i) + { textures.push(new core.Texture.fromFrame(frames[i])); } @@ -183,10 +200,12 @@ * @static * @param images {string[]} the array of image urls the movieclip will use as its texture frames */ -MovieClip.fromImages = function (images) { +MovieClip.fromImages = function (images) +{ var textures = []; - for (var i = 0; i < images.length; ++i) { + for (var i = 0; i < images.length; ++i) + { textures.push(new core.Texture.fromImage(images[i])); } diff --git a/src/extras/Rope.js b/src/extras/Rope.js index c157ec4..9c87bc0 100644 --- a/src/extras/Rope.js +++ b/src/extras/Rope.js @@ -9,7 +9,8 @@ * @param {Array} points - An array of {Point}. * */ -function Rope(texture, points) { +function Rope(texture, points) +{ Strip.call(this, texture); this.points = points; @@ -31,10 +32,12 @@ * Refreshes * */ -Rope.prototype.refresh = function () { +Rope.prototype.refresh = function () +{ var points = this.points; - if (points.length < 1) { + if (points.length < 1) + { return; } @@ -59,20 +62,23 @@ var total = points.length, point, index, amount; - for (var i = 1; i < total; i++) { + for (var i = 1; i < total; i++) + { point = points[i]; index = i * 4; // time to do some smart drawing! amount = i / (total-1); - if (i%2) { + if (i%2) + { uvs[index] = amount; uvs[index+1] = 0; uvs[index+2] = amount; uvs[index+3] = 1; } - else { + else + { uvs[index] = amount; uvs[index+1] = 0; @@ -95,10 +101,12 @@ * * @private */ -Rope.prototype.updateTransform = function () { +Rope.prototype.updateTransform = function () +{ var points = this.points; - if (points.length < 1) { + if (points.length < 1) + { return; } @@ -113,14 +121,17 @@ var total = points.length, point, index, ratio, perpLength, num; - for (var i = 0; i < total; i++) { + for (var i = 0; i < total; i++) + { point = points[i]; index = i * 4; - if (i < points.length-1) { + if (i < points.length-1) + { nextPoint = points[i+1]; } - else { + else + { nextPoint = point; } @@ -129,7 +140,8 @@ ratio = (1 - (i / (total-1))) * 10; - if (ratio > 1) { + if (ratio > 1) + { ratio = 1; } @@ -157,7 +169,8 @@ * * @param texture {Texture} the texture that will be used */ -Rope.prototype.setTexture = function (texture) { +Rope.prototype.setTexture = function (texture) +{ // stop current texture this.texture = texture; //this.updateFrame = true; diff --git a/src/extras/Strip.js b/src/extras/Strip.js index c5e378f..57691b5 100644 --- a/src/extras/Strip.js +++ b/src/extras/Strip.js @@ -10,7 +10,8 @@ * @param height {number} the height * */ -function Strip(texture) { +function Strip(texture) +{ core.DisplayObjectContainer.call(this); /** @@ -70,9 +71,11 @@ * * @param renderer {WebGLRenderer} */ -Strip.prototype.renderWebGL = function (renderer) { +Strip.prototype.renderWebGL = function (renderer) +{ // if the sprite is not visible or the alpha is 0 then no need to render this element - if (!this.visible || this.alpha <= 0) { + if (!this.visible || this.alpha <= 0) + { return; } @@ -81,7 +84,8 @@ renderer.spriteBatch.stop(); // init! init! - if (!this._vertexBuffer) { + if (!this._vertexBuffer) + { this._initWebGL(renderer); } @@ -96,7 +100,8 @@ //TODO check culling }; -Strip.prototype._initWebGL = function (renderer) { +Strip.prototype._initWebGL = function (renderer) +{ // build the strip! var gl = renderer.gl; @@ -118,7 +123,8 @@ gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this.indices, gl.STATIC_DRAW); }; -Strip.prototype._renderStrip = function (renderer) { +Strip.prototype._renderStrip = function (renderer) +{ var gl = renderer.gl; var projection = renderer.projection, offset = renderer.offset, @@ -137,7 +143,8 @@ gl.uniform2f(shader.offsetVector, -offset.x, -offset.y); gl.uniform1f(shader.alpha, this.worldAlpha); - if (!this.dirty) { + if (!this.dirty) + { gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexBuffer); gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); @@ -150,10 +157,12 @@ gl.activeTexture(gl.TEXTURE0); // check if a texture is dirty.. - if (this.texture.baseTexture._dirty[gl.id]) { + if (this.texture.baseTexture._dirty[gl.id]) + { renderer.updateTexture(this.texture.baseTexture); } - else { + else + { // bind the current texture gl.bindTexture(gl.TEXTURE_2D, this.texture.baseTexture._glTextures[gl.id]); } @@ -163,7 +172,8 @@ } - else { + else + { this.dirty = false; gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexBuffer); @@ -178,10 +188,12 @@ gl.activeTexture(gl.TEXTURE0); // check if a texture is dirty.. - if (this.texture.baseTexture._dirty[gl.id]) { + if (this.texture.baseTexture._dirty[gl.id]) + { renderer.updateTexture(this.texture.baseTexture); } - else { + else + { gl.bindTexture(gl.TEXTURE_2D, this.texture.baseTexture._glTextures[gl.id]); } @@ -203,27 +215,33 @@ * * @param renderer {CanvasRenderer} */ -Strip.prototype.renderCanvas = function (renderer) { +Strip.prototype.renderCanvas = function (renderer) +{ var context = renderer.context; var transform = this.worldTransform; - if (renderer.roundPixels) { + if (renderer.roundPixels) + { context.setTransform(transform.a, transform.b, transform.c, transform.d, transform.tx | 0, transform.ty | 0); } - else { + else + { context.setTransform(transform.a, transform.b, transform.c, transform.d, transform.tx, transform.ty); } - if (this.drawMode === Strip.DrawModes.TRIANGLE_STRIP) { + if (this.drawMode === Strip.DrawModes.TRIANGLE_STRIP) + { this._renderCanvasTriangleStrip(context); } - else { + else + { this._renderCanvasTriangles(context); } }; -Strip.prototype._renderCanvasTriangleStrip = function (context) { +Strip.prototype._renderCanvasTriangleStrip = function (context) +{ // draw triangles!! var vertices = this.vertices; var uvs = this.uvs; @@ -231,14 +249,16 @@ var length = vertices.length / 2; // this.count++; - for (var i = 0; i < length - 2; i++) { + for (var i = 0; i < length - 2; i++) + { // draw some triangles! var index = i * 2; this._renderCanvasDrawTriangle(context, vertices, uvs, index, (index + 2), (index + 4)); } }; -Strip.prototype._renderCanvasTriangles = function (context) { +Strip.prototype._renderCanvasTriangles = function (context) +{ // draw triangles!! var vertices = this.vertices; var uvs = this.uvs; @@ -247,14 +267,16 @@ var length = indices.length; // this.count++; - for (var i = 0; i < length; i += 3) { + for (var i = 0; i < length; i += 3) + { // draw some triangles! var index0 = indices[i] * 2, index1 = indices[i + 1] * 2, index2 = indices[i + 2] * 2; this._renderCanvasDrawTriangle(context, vertices, uvs, index0, index1, index2); } }; -Strip.prototype._renderCanvasDrawTriangle = function (context, vertices, uvs, index0, index1, index2) { +Strip.prototype._renderCanvasDrawTriangle = function (context, vertices, uvs, index0, index1, index2) +{ var textureSource = this.texture.baseTexture.source; var textureWidth = this.texture.width; var textureHeight = this.texture.height; @@ -265,7 +287,8 @@ var u0 = uvs[index0] * textureWidth, u1 = uvs[index1] * textureWidth, u2 = uvs[index2] * textureWidth; var v0 = uvs[index0 + 1] * textureHeight, v1 = uvs[index1 + 1] * textureHeight, v2 = uvs[index2 + 1] * textureHeight; - if (this.canvasPadding > 0) { + if (this.canvasPadding > 0) + { var paddingX = this.canvasPadding / this.worldTransform.a; var paddingY = this.canvasPadding / this.worldTransform.d; var centerX = (x0 + x1 + x2) / 3; @@ -332,7 +355,8 @@ * @param strip {Strip} The Strip to render * @private */ -Strip.prototype.renderStripFlat = function (strip) { +Strip.prototype.renderStripFlat = function (strip) +{ var context = this.context; var vertices = strip.vertices; @@ -340,7 +364,8 @@ // this.count++; context.beginPath(); - for (var i=1; i < length-2; i++) { + for (var i=1; i < length-2; i++) + { // draw some triangles! var index = i*2; @@ -358,7 +383,8 @@ }; /* -Strip.prototype.setTexture = function (texture) { +Strip.prototype.setTexture = function (texture) +{ //TODO SET THE TEXTURES //TODO VISIBILITY @@ -377,7 +403,8 @@ * @private */ -Strip.prototype.onTextureUpdate = function () { +Strip.prototype.onTextureUpdate = function () +{ this.updateFrame = true; }; @@ -387,7 +414,8 @@ * @param matrix {Matrix} the transformation matrix of the sprite * @return {Rectangle} the framing rectangle */ -Strip.prototype.getBounds = function (matrix) { +Strip.prototype.getBounds = function (matrix) +{ var worldTransform = matrix || this.worldTransform; var a = worldTransform.a; @@ -404,7 +432,8 @@ var minY = Infinity; var vertices = this.vertices; - for (var i = 0, n = vertices.length; i < n; i += 2) { + for (var i = 0, n = vertices.length; i < n; i += 2) + { var rawX = vertices[i], rawY = vertices[i + 1]; var x = (a * rawX) + (c * rawY) + tx; var y = (d * rawY) + (b * rawX) + ty; @@ -416,7 +445,8 @@ maxY = y > maxY ? y : maxY; } - if (minX === -Infinity || maxY === Infinity) { + if (minX === -Infinity || maxY === Infinity) + { return core.math.Rectangle.EMPTY; } diff --git a/src/extras/TilingSprite.js b/src/extras/TilingSprite.js index 3ac22df..31da393 100644 --- a/src/extras/TilingSprite.js +++ b/src/extras/TilingSprite.js @@ -10,7 +10,8 @@ * @param width {number} the width of the tiling sprite * @param height {number} the height of the tiling sprite */ -function TilingSprite(texture, width, height) { +function TilingSprite(texture, width, height) +{ core.Sprite.call( this, texture); /** @@ -86,10 +87,12 @@ * @memberof TilingSprite# */ width: { - get: function () { + get: function () + { return this._width; }, - set: function (value) { + set: function (value) + { this._width = value; } }, @@ -101,20 +104,25 @@ * @memberof TilingSprite# */ height: { - get: function () { + get: function () + { return this._height; }, - set: function (value) { + set: function (value) + { this._height = value; } }, texture: { - get: function () { + get: function () + { return this._texture; }, - set: function (value) { - if (this._texture === value) { + set: function (value) + { + if (this._texture === value) + { return; } @@ -130,51 +138,61 @@ * * @param renderer {WebGLRenderer} */ -TilingSprite.prototype.renderWebGL = function (renderer) { - if (!this.visible || this.alpha <= 0) { +TilingSprite.prototype.renderWebGL = function (renderer) +{ + if (!this.visible || this.alpha <= 0) + { return; } var i, j; - if (this._mask) { + if (this._mask) + { renderer.spriteBatch.stop(); renderer.maskManager.pushMask(this.mask, renderer); renderer.spriteBatch.start(); } - if (this._filters) { + if (this._filters) + { renderer.spriteBatch.flush(); renderer.filterManager.pushFilter(this._filterBlock); } - if (!this.tilingTexture || this.refreshTexture) { + if (!this.tilingTexture || this.refreshTexture) + { this.generateTilingTexture(true); - if (this.tilingTexture && this.tilingTexture.needsUpdate) { + if (this.tilingTexture && this.tilingTexture.needsUpdate) + { //TODO - tweaking renderer.updateTexture(this.tilingTexture.baseTexture); this.tilingTexture.needsUpdate = false; // this.tilingTexture._uvs = null; } } - else { + else + { renderer.spriteBatch.renderTilingSprite(this); } // simple render children! - for (i=0,j=this.children.length; i= 0 && index <= this.children.length) { - if (child.parent) { + if (index >= 0 && index <= this.children.length) + { + if (child.parent) + { child.parent.removeChild(child); } @@ -154,7 +173,8 @@ return child; } - else { + else + { throw new Error(child + 'addChildAt: The index '+ index +' supplied is out of bounds ' + this.children.length); } }; @@ -165,15 +185,18 @@ * @param child {DisplayObject} * @param child2 {DisplayObject} */ -DisplayObjectContainer.prototype.swapChildren = function (child, child2) { - if (child === child2) { +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) { + if (index1 < 0 || index2 < 0) + { throw new Error('swapChildren: Both the supplied DisplayObjects must be a child of the caller.'); } @@ -187,10 +210,12 @@ * @param child {DisplayObject} The DisplayObject instance to identify * @return {Number} The index position of the child display object to identify */ -DisplayObjectContainer.prototype.getChildIndex = function (child) { +DisplayObjectContainer.prototype.getChildIndex = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { throw new Error('The supplied DisplayObject must be a child of the caller'); } @@ -203,8 +228,10 @@ * @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 */ -DisplayObjectContainer.prototype.setChildIndex = function (child, index) { - if (index < 0 || index >= this.children.length) { +DisplayObjectContainer.prototype.setChildIndex = function (child, index) +{ + if (index < 0 || index >= this.children.length) + { throw new Error('The supplied index is out of bounds'); } @@ -220,8 +247,10 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child at the given index, if any. */ -DisplayObjectContainer.prototype.getChildAt = function (index) { - if (index < 0 || index >= this.children.length) { +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'); } @@ -234,10 +263,12 @@ * @param child {DisplayObject} The DisplayObject to remove * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChild = function (child) { +DisplayObjectContainer.prototype.removeChild = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { return; } @@ -250,7 +281,8 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChildAt = function (index) { +DisplayObjectContainer.prototype.removeChildAt = function (index) +{ var child = this.getChildAt(index); child.parent = null; @@ -265,24 +297,29 @@ * @param beginIndex {Number} The beginning position. Default value is 0. * @param endIndex {Number} The ending position. Default value is size of the container. */ -DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) { +DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) +{ var begin = beginIndex || 0; var end = typeof endIndex === 'number' ? endIndex : this.children.length; var range = end - begin; - if (range > 0 && range <= end) { + if (range > 0 && range <= end) + { var removed = this.children.splice(begin, range); - for (var i = 0; i < removed.length; ++i) { + for (var i = 0; i < removed.length; ++i) + { removed[i].parent = null; } return removed; } - else if (range === 0 && this.children.length === 0) { + else if (range === 0 && this.children.length === 0) + { return []; } - else { + else + { throw new RangeError('removeChildren: numeric values are outside the acceptable range.'); } }; @@ -291,7 +328,8 @@ * Generates and updates the cached sprite for this object. * */ -DisplayObjectContainer.prototype.updateCachedSprite = function () { +DisplayObjectContainer.prototype.updateCachedSprite = function () +{ this._generateCachedSprite(); }; @@ -304,7 +342,8 @@ * @param renderer {CanvasRenderer|WebGLRenderer} The renderer used to generate the texture. * @return {Texture} a texture of the graphics object */ -DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) { +DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) +{ var bounds = this.getLocalBounds(); var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0, renderer, scaleMode, resolution); @@ -322,18 +361,22 @@ * * @private */ -DisplayObjectContainer.prototype.updateTransform = function () { - if (!this.visible) { +DisplayObjectContainer.prototype.updateTransform = function () +{ + if (!this.visible) + { return; } this.displayObjectUpdateTransform(); - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { return; } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } }; @@ -346,8 +389,10 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getBounds = function () { - if (this.children.length === 0) { +DisplayObjectContainer.prototype.getBounds = function () +{ + if (this.children.length === 0) + { return math.Rectangle.EMPTY; } @@ -365,10 +410,12 @@ var childVisible = false; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -386,7 +433,8 @@ maxY = maxY > childMaxY ? maxY : childMaxY; } - if (!childVisible) { + if (!childVisible) + { return math.Rectangle.EMPTY; } @@ -407,12 +455,14 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getLocalBounds = function () { +DisplayObjectContainer.prototype.getLocalBounds = function () +{ var matrixCache = this.worldTransform; this.worldTransform = math.Matrix.IDENTITY; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } @@ -428,13 +478,16 @@ * * @param renderer {WebGLRenderer} The renderer */ -DisplayObjectContainer.prototype.renderWebGL = function (renderer) { +DisplayObjectContainer.prototype.renderWebGL = function (renderer) +{ // if the object is not visible or the alpha is 0 then no need to render this element - if (!this.visible || this.alpha <= 0) { + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } @@ -442,14 +495,17 @@ var i, j; // do a quick check to see if this element has a mask or a filter. - if (this._mask || this._filters) { + if (this._mask || this._filters) + { // push filter first as we need to ensure the stencil buffer is correct for any masking - if (this._filters) { + if (this._filters) + { renderer.spriteBatch.flush(); renderer.filterManager.pushFilter(this._filterBlock); } - if (this._mask) { + if (this._mask) + { renderer.spriteBatch.stop(); renderer.maskManager.pushMask(this.mask, renderer); renderer.spriteBatch.start(); @@ -459,36 +515,42 @@ this._renderWebGL(renderer); // now loop through the children and make sure they get rendered - for (i = 0, j = this.children.length; i < j; i++) { + for (i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderWebGL(renderer); } // time to stop the sprite batch as either a mask element or a filter draw will happen next renderer.spriteBatch.stop(); - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(this._mask, renderer); } - if (this._filters) { + if (this._filters) + { renderer.filterManager.popFilter(); } renderer.spriteBatch.start(); } - else { + else + { this._renderWebGL(renderer); // simple render children! - for (i = 0, j = this.children.length; i < j; ++i) { + for (i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderWebGL(renderer); } } }; -DisplayObjectContainer.prototype._renderWebGL = function (renderer) { +DisplayObjectContainer.prototype._renderWebGL = function (renderer) +{ // this is where content itself gets renderd.. @@ -499,25 +561,31 @@ * * @param renderer {CanvasRenderer} The renderer */ -DisplayObjectContainer.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0) { +DisplayObjectContainer.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -528,13 +596,16 @@ * @param renderer {WebGLRenderer|CanvasRenderer} The renderer * @private */ -DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) { +DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) +{ this._cachedSprite.worldAlpha = this.worldAlpha; - if (renderer.gl) { + if (renderer.gl) + { this._cachedSprite.renderWebGL(renderer); } - else { + else + { this._cachedSprite.renderCanvas(renderer); } }; @@ -544,10 +615,12 @@ * * @private */ -DisplayObjectContainer.prototype._generateCachedSprite = function () { +DisplayObjectContainer.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { // TODO - RenderTexture now *requires* a renderer instance, so this is like broken // because `renderer` isn't actually in scope here :P var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0); @@ -555,7 +628,8 @@ this._cachedSprite = new Sprite(renderTexture); this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.texture.resize(bounds.width | 0, bounds.height | 0); } @@ -580,8 +654,10 @@ * * @private */ -DisplayObjectContainer.prototype._destroyCachedSprite = function () { - if (!this._cachedSprite) { +DisplayObjectContainer.prototype._destroyCachedSprite = function () +{ + if (!this._cachedSprite) + { return; } diff --git a/src/core/display/Sprite.js b/src/core/display/Sprite.js index 707da24..5862aef 100644 --- a/src/core/display/Sprite.js +++ b/src/core/display/Sprite.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param texture {Texture} The texture for this sprite */ -function Sprite(texture) { +function Sprite(texture) +{ DisplayObjectContainer.call(this); /** @@ -85,12 +86,14 @@ this.texture = texture || Texture.EMPTY; } -Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) { +Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) +{ DisplayObjectContainer.prototype.destroy.call(this); this.anchor = null; - if (destroyTexture) { + if (destroyTexture) + { this._texture.destroy(destroyBaseTexture); } @@ -111,10 +114,12 @@ * @memberof Sprite# */ width: { - get: function () { + get: function () + { return this.scale.x * this.texture.frame.width; }, - set: function (value) { + set: function (value) + { this.scale.x = value / this.texture.frame.width; this._width = value; } @@ -127,10 +132,12 @@ * @memberof Sprite# */ height: { - get: function () { + get: function () + { return this.scale.y * this.texture.frame.height; }, - set: function (value) { + set: function (value) + { this.scale.y = value / this.texture.frame.height; this._height = value; } @@ -143,23 +150,29 @@ * @memberof Sprite# */ texture: { - get: function () { + get: function () + { return this._texture; }, - set: function (value) { - if (this._texture === value) { + set: function (value) + { + if (this._texture === value) + { return; } this._texture = value; this.cachedTint = 0xFFFFFF; - if (value) { + if (value) + { // wait for the texture to load - if (value.baseTexture.hasLoaded) { + if (value.baseTexture.hasLoaded) + { this._onTextureUpdate(); } - else { + else + { value.once('update', this._onTextureUpdate.bind(this)); } } @@ -172,18 +185,22 @@ * * @private */ -Sprite.prototype._onTextureUpdate = function () { +Sprite.prototype._onTextureUpdate = function () +{ // so if _width is 0 then width was not set.. - if (this._width) { + if (this._width) + { this.scale.x = this._width / this.texture.frame.width; } - if (this._height) { + if (this._height) + { this.scale.y = this._height / this.texture.frame.height; } }; -Sprite.prototype._renderWebGL = function (renderer) { +Sprite.prototype._renderWebGL = function (renderer) +{ // this is where content gets renderd.. // watch this space for a little render state manager.. @@ -197,7 +214,8 @@ * @param matrix {Matrix} the transformation matrix of the sprite * @return {Rectangle} the framing rectangle */ -Sprite.prototype.getBounds = function (matrix) { +Sprite.prototype.getBounds = function (matrix) +{ var width = this.texture.frame.width; var height = this.texture.frame.height; @@ -224,11 +242,13 @@ if(b === 0 && c === 0) { // scale may be negative! - if (a < 0) { + if (a < 0) + { a *= -1; } - if (d < 0) { + if (d < 0) + { d *= -1; } @@ -293,28 +313,34 @@ * * @param renderer {CanvasRenderer} The renderer */ -Sprite.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) { +Sprite.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) + { return; } - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; renderer.context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } // Ignore null sources - if (this.texture.valid) { + if (this.texture.valid) + { var resolution = this.texture.baseTexture.resolution / renderer.resolution; renderer.context.globalAlpha = this.worldAlpha; // If smoothingEnabled is supported and we need to change the smoothing property for this texture - if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) { + if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) + { renderer.scaleMode = this.texture.baseTexture.scaleMode; renderer.context[renderer.smoothProperty] = (renderer.scaleMode === CONST.scaleModes.LINEAR); } @@ -324,7 +350,8 @@ var dy = (this.texture.trim ? this.texture.trim.y : 0) - (this.anchor.y * this.texture.trim.height); // Allow for pixel rounding - if (renderer.roundPixels) { + if (renderer.roundPixels) + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -337,7 +364,8 @@ dx = dx | 0; dy = dy | 0; } - else { + else + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -348,8 +376,10 @@ ); } - if (this.tint !== 0xFFFFFF) { - if (this.cachedTint !== this.tint) { + if (this.tint !== 0xFFFFFF) + { + if (this.cachedTint !== this.tint) + { this.cachedTint = this.tint; // TODO clean up caching - how to clean up the caches? @@ -368,7 +398,8 @@ this.texture.crop.height / resolution ); } - else { + else + { renderer.context.drawImage( this.texture.baseTexture.source, this.texture.crop.x, @@ -383,11 +414,13 @@ } } - for (var i = 0, j = this.children.length; i < j; i++) { + for (var i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -402,10 +435,12 @@ * @param frameId {String} The frame Id of the texture in the cache * @return {Sprite} A new Sprite using a texture from the texture cache matching the frameId */ -Sprite.fromFrame = function (frameId) { +Sprite.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache' + this); } @@ -420,6 +455,7 @@ * @param imageId {String} The image url of the texture * @return {Sprite} A new Sprite using a texture from the texture cache matching the image id */ -Sprite.fromImage = function (imageId, crossorigin, scaleMode) { +Sprite.fromImage = function (imageId, crossorigin, scaleMode) +{ return new Sprite(Texture.fromImage(imageId, crossorigin, scaleMode)); }; diff --git a/src/core/display/SpriteBatch.js b/src/core/display/SpriteBatch.js index 3187777..c196fef 100644 --- a/src/core/display/SpriteBatch.js +++ b/src/core/display/SpriteBatch.js @@ -12,7 +12,8 @@ * ```js * var container = new SpriteBatch(); * - * for(var i = 0; i < 100; ++i) { + * for(var i = 0; i < 100; ++i) + * { * var sprite = new PIXI.Sprite.fromImage("myImage.png"); * container.addChild(sprite); * } @@ -25,7 +26,8 @@ */ //TODO RENAME to PARTICLE CONTAINER? -function SpriteBatch() { +function SpriteBatch() +{ DisplayObjectContainer.call(this); } @@ -38,7 +40,8 @@ * * @private */ -SpriteBatch.prototype.updateTransform = function () { +SpriteBatch.prototype.updateTransform = function () +{ // TODO don't need to! this.displayObjectUpdateTransform(); // PIXI.DisplayObjectContainer.prototype.updateTransform.call( this ); @@ -50,8 +53,10 @@ * @param renderer {WebGLRenderer} The webgl renderer * @private */ -SpriteBatch.prototype.renderWebGL = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderWebGL = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -71,8 +76,10 @@ * @param renderer {CanvasRenderer} The canvas renderer * @private */ -SpriteBatch.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -84,10 +91,12 @@ this.displayObjectUpdateTransform(); - for (var i = 0; i < this.children.length; ++i) { + for (var i = 0; i < this.children.length; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -95,9 +104,11 @@ context.globalAlpha = this.worldAlpha * child.alpha; - if (child.rotation % (Math.PI * 2) === 0) { + if (child.rotation % (Math.PI * 2) === 0) + { // this is the fastest way to optimise! - if rotation is 0 then we can avoid any kind of setTransform call - if (isRotated) { + if (isRotated) + { context.setTransform( transform.a, transform.b, @@ -122,8 +133,10 @@ frame.height * child.scale.y ); } - else { - if (!isRotated) { + else + { + if (!isRotated) + { isRotated = true; } @@ -131,7 +144,8 @@ var childTransform = child.worldTransform; - if (renderer.roundPixels) { + if (renderer.roundPixels) + { context.setTransform( childTransform.a, childTransform.b, @@ -141,7 +155,8 @@ childTransform.ty | 0 ); } - else { + else + { context.setTransform( childTransform.a, childTransform.b, diff --git a/src/core/index.js b/src/core/index.js index 3954b6f..eb4a82b 100644 --- a/src/core/index.js +++ b/src/core/index.js @@ -58,11 +58,13 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRenderer: function (width, height, options, noWebGL) { + autoDetectRenderer: function (width, height, options, noWebGL) + { width = width || 800; height = height || 600; - if (!noWebGL && require('webgl-enabled')()) { + if (!noWebGL && require('webgl-enabled')()) + { return new core.WebGLRenderer(width, height, options); } @@ -87,7 +89,8 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRecommendedRenderer: function (width, height, options) { + autoDetectRecommendedRenderer: function (width, height, options) + { var isAndroid = /Android/i.test(navigator.userAgent); return core.autoDetectRenderer(width, height, options, isAndroid); diff --git a/src/core/math/Matrix.js b/src/core/math/Matrix.js index c2f87e2..2ff4848 100644 --- a/src/core/math/Matrix.js +++ b/src/core/math/Matrix.js @@ -10,7 +10,8 @@ * @class * @namespace PIXI */ -function Matrix() { +function Matrix() +{ /** * @member {number} * @default 1 @@ -63,7 +64,8 @@ * * @param array {number[]} The array that the matrix will be populated from. */ -Matrix.prototype.fromArray = function (array) { +Matrix.prototype.fromArray = function (array) +{ this.a = array[0]; this.b = array[1]; this.c = array[3]; @@ -78,14 +80,17 @@ * @param transpose {boolean} Whether we need to transpose the matrix or not * @return {number[]} the newly created array which contains the matrix */ -Matrix.prototype.toArray = function (transpose) { - if (!this.array) { +Matrix.prototype.toArray = function (transpose) +{ + if (!this.array) + { this.array = new Float32Array(9); } var array = this.array; - if (transpose) { + if (transpose) + { array[0] = this.a; array[1] = this.b; array[2] = 0; @@ -96,7 +101,8 @@ array[7] = this.ty; array[8] = 1; } - else { + else + { array[0] = this.a; array[1] = this.c; array[2] = this.tx; @@ -119,7 +125,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, transformed through this matrix */ -Matrix.prototype.apply = function (pos, newPos) { +Matrix.prototype.apply = function (pos, newPos) +{ newPos = newPos || new Point(); newPos.x = this.a * pos.x + this.c * pos.y + this.tx; @@ -136,7 +143,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, inverse-transformed through this matrix */ -Matrix.prototype.applyInverse = function (pos, newPos) { +Matrix.prototype.applyInverse = function (pos, newPos) +{ newPos = newPos || new Point(); var id = 1 / (this.a * this.d + this.c * -this.b); @@ -154,7 +162,8 @@ * @param {number} y * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.translate = function (x, y) { +Matrix.prototype.translate = function (x, y) +{ this.tx += x; this.ty += y; @@ -168,7 +177,8 @@ * @param {number} y The amount to scale vertically * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.scale = function (x, y) { +Matrix.prototype.scale = function (x, y) +{ this.a *= x; this.d *= y; this.c *= x; @@ -186,7 +196,8 @@ * @param {number} angle - The angle in radians. * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.rotate = function (angle) { +Matrix.prototype.rotate = function (angle) +{ var cos = Math.cos( angle ); var sin = Math.sin( angle ); @@ -210,7 +221,8 @@ * @param {Matrix} matrix * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.append = function (matrix) { +Matrix.prototype.append = function (matrix) +{ var a1 = this.a; var b1 = this.b; var c1 = this.c; @@ -232,7 +244,8 @@ * * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.identity = function () { +Matrix.prototype.identity = function () +{ this.a = 1; this.b = 0; this.c = 0; diff --git a/src/core/math/Point.js b/src/core/math/Point.js index 7565b2d..632f346 100644 --- a/src/core/math/Point.js +++ b/src/core/math/Point.js @@ -7,7 +7,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -function Point(x, y) { +function Point(x, y) +{ /** * @member {number} * @default 0 @@ -29,7 +30,8 @@ * * @return {Point} a copy of the point */ -Point.prototype.clone = function () { +Point.prototype.clone = function () +{ return new Point(this.x, this.y); }; @@ -40,7 +42,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -Point.prototype.set = function (x, y) { +Point.prototype.set = function (x, y) +{ this.x = x || 0; this.y = y || ( (y !== 0) ? this.x : 0 ) ; }; diff --git a/src/core/math/shapes/Circle.js b/src/core/math/shapes/Circle.js index 69cfdc9..4d76efc 100644 --- a/src/core/math/shapes/Circle.js +++ b/src/core/math/shapes/Circle.js @@ -10,7 +10,8 @@ * @param y {number} The Y coordinate of the center of this circle * @param radius {number} The radius of the circle */ -function Circle(x, y, radius) { +function Circle(x, y, radius) +{ /** * @member {number} * @default 0 @@ -46,7 +47,8 @@ * @method clone * @return {Circle} a copy of the Circle */ -Circle.prototype.clone = function () { +Circle.prototype.clone = function () +{ return new Circle(this.x, this.y, this.radius); }; @@ -58,8 +60,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Circle */ -Circle.prototype.contains = function (x, y) { - if (this.radius <= 0) { +Circle.prototype.contains = function (x, y) +{ + if (this.radius <= 0) + { return false; } @@ -79,6 +83,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Circle.prototype.getBounds = function () { +Circle.prototype.getBounds = function () +{ return new Rectangle(this.x - this.radius, this.y - this.radius, this.radius * 2, this.radius * 2); }; diff --git a/src/core/math/shapes/Ellipse.js b/src/core/math/shapes/Ellipse.js index 4f2d066..fefd01a 100644 --- a/src/core/math/shapes/Ellipse.js +++ b/src/core/math/shapes/Ellipse.js @@ -11,7 +11,8 @@ * @param width {number} The half width of this ellipse * @param height {number} The half height of this ellipse */ -function Ellipse(x, y, width, height) { +function Ellipse(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -53,7 +54,8 @@ * @method clone * @return {Ellipse} a copy of the ellipse */ -Ellipse.prototype.clone = function () { +Ellipse.prototype.clone = function () +{ return new Ellipse(this.x, this.y, this.width, this.height); }; @@ -65,8 +67,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coords are within this ellipse */ -Ellipse.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Ellipse.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } @@ -86,6 +90,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Ellipse.prototype.getBounds = function () { +Ellipse.prototype.getBounds = function () +{ return new Rectangle(this.x - this.width, this.y - this.height, this.width, this.height); }; diff --git a/src/core/math/shapes/Polygon.js b/src/core/math/shapes/Polygon.js index ae89148..fea6d37 100644 --- a/src/core/math/shapes/Polygon.js +++ b/src/core/math/shapes/Polygon.js @@ -10,16 +10,20 @@ * arguments passed can be flat x,y values e.g. `new Polygon(x,y, x,y, x,y, ...)` where `x` and `y` are * Numbers. */ -function Polygon(points) { +function Polygon(points) +{ //if points isn't an array, use arguments as the array - if (!(points instanceof Array)) { + if (!(points instanceof Array)) + { points = Array.prototype.slice.call(arguments); } //if this is a flat array of numbers, convert it to points - if (points[0] instanceof Point) { + if (points[0] instanceof Point) + { var p = []; - for (var i = 0, il = points.length; i < il; i++) { + for (var i = 0, il = points.length; i < il; i++) + { p.push(points[i].x, points[i].y); } @@ -51,7 +55,8 @@ * * @return {Polygon} a copy of the polygon */ -Polygon.prototype.clone = function () { +Polygon.prototype.clone = function () +{ return new Polygon(this.points.slice()); }; @@ -62,19 +67,22 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this polygon */ -Polygon.prototype.contains = function (x, y) { +Polygon.prototype.contains = function (x, y) +{ var inside = false; // use some raycasting to test hits // https://github.com/substack/point-in-polygon/blob/master/index.js var length = this.points.length / 2; - for (var i = 0, j = length - 1; i < length; j = i++) { + for (var i = 0, j = length - 1; i < length; j = i++) + { var xi = this.points[i * 2], yi = this.points[i * 2 + 1], xj = this.points[j * 2], yj = this.points[j * 2 + 1], intersect = ((yi > y) !== (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi); - if (intersect) { + if (intersect) + { inside = !inside; } } diff --git a/src/core/math/shapes/Rectangle.js b/src/core/math/shapes/Rectangle.js index 16ac62a..4008b68 100644 --- a/src/core/math/shapes/Rectangle.js +++ b/src/core/math/shapes/Rectangle.js @@ -10,7 +10,8 @@ * @param width {number} The overall width of this rectangle * @param height {number} The overall height of this rectangle */ -function Rectangle(x, y, width, height) { +function Rectangle(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -60,7 +61,8 @@ * * @return {Rectangle} a copy of the rectangle */ -Rectangle.prototype.clone = function () { +Rectangle.prototype.clone = function () +{ return new Rectangle(this.x, this.y, this.width, this.height); }; @@ -71,13 +73,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rectangle */ -Rectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Rectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/math/shapes/RoundedRectangle.js b/src/core/math/shapes/RoundedRectangle.js index 27d286e..7bf6411 100644 --- a/src/core/math/shapes/RoundedRectangle.js +++ b/src/core/math/shapes/RoundedRectangle.js @@ -11,7 +11,8 @@ * @param height {number} The overall height of this rounded rectangle * @param radius {number} Controls the radius of the rounded corners */ -function RoundedRectangle(x, y, width, height, radius) { +function RoundedRectangle(x, y, width, height, radius) +{ /** * @member {number} * @default 0 @@ -58,7 +59,8 @@ * * @return {RoundedRectangle} a copy of the rounded rectangle */ -RoundedRectangle.prototype.clone = function () { +RoundedRectangle.prototype.clone = function () +{ return new RoundedRectangle(this.x, this.y, this.width, this.height, this.radius); }; @@ -69,13 +71,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rounded Rectangle */ -RoundedRectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +RoundedRectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/primitives/Graphics.js b/src/core/primitives/Graphics.js index 261c534..e902d2a 100644 --- a/src/core/primitives/Graphics.js +++ b/src/core/primitives/Graphics.js @@ -16,7 +16,8 @@ * @extends DisplayObjectContainer * @namespace PIXI */ -function Graphics() { +function Graphics() +{ DisplayObjectContainer.call(this); this.renderable = true; @@ -154,16 +155,20 @@ * @private */ cacheAsBitmap: { - get: function () { + get: function () + { return this._cacheAsBitmap; }, - set: function (value) { + set: function (value) + { this._cacheAsBitmap = value; - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._generateCachedSprite(); } - else { + else + { this.destroyCachedSprite(); this.dirty = true; } @@ -176,7 +181,8 @@ * * @return {Graphics} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ var clone = new Graphics(); clone.renderable = this.renderable; @@ -192,7 +198,8 @@ clone.cachedSpriteDirty = this.cachedSpriteDirty; // copy graphics data - for (var i = 0; i < this.graphicsData.length; ++i) { + for (var i = 0; i < this.graphicsData.length; ++i) + { clone.graphicsData.push(this.graphicsData.clone()); } @@ -211,17 +218,21 @@ * @param alpha {number} alpha of the line to draw, will update the objects stored style * @return {Graphics} */ -Graphics.prototype.lineStyle = function (lineWidth, color, alpha) { +Graphics.prototype.lineStyle = function (lineWidth, color, alpha) +{ this.lineWidth = lineWidth || 0; this.lineColor = color || 0; this.lineAlpha = (arguments.length < 3) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length) + { // halfway through a line? start a new one! this.drawShape( new math.Polygon( this.currentPath.shape.points.slice(-2) )); } - else { + else + { // otherwise its empty so lets just set the line properties this.currentPath.lineWidth = this.lineWidth; this.currentPath.lineColor = this.lineColor; @@ -239,7 +250,8 @@ * @param y {number} the Y coordinate to move to * @return {Graphics} */ -Graphics.prototype.moveTo = function (x, y) { +Graphics.prototype.moveTo = function (x, y) +{ this.drawShape(new math.Polygon([x,y])); return this; @@ -253,7 +265,8 @@ * @param y {number} the Y coordinate to draw to * @return {Graphics} */ -Graphics.prototype.lineTo = function (x, y) { +Graphics.prototype.lineTo = function (x, y) +{ this.currentPath.shape.points.push(x, y); this.dirty = true; @@ -270,13 +283,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -285,7 +302,8 @@ n = 20, points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { this.moveTo(0, 0); } @@ -293,7 +311,8 @@ var fromY = points[points.length-1]; var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; xa = fromX + ( (cpX - fromX) * j ); @@ -319,13 +338,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -342,7 +365,8 @@ var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; dt = (1 - j); @@ -373,13 +397,17 @@ * @param radius {number} The radius of the arc * @return {Graphics} */ -Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points.push(x1, y1); } } - else { + else + { this.moveTo(x1, y1); } @@ -392,12 +420,15 @@ b2 = x2 - x1, mm = Math.abs(a1 * b2 - b1 * a2); - if (mm < 1.0e-8 || radius === 0) { - if (points[points.length-2] !== x1 || points[points.length-1] !== y1) { + if (mm < 1.0e-8 || radius === 0) + { + if (points[points.length-2] !== x1 || points[points.length-1] !== y1) + { points.push(x1, y1); } } - else { + else + { var dd = a1 * a1 + b1 * b1, cc = a2 * a2 + b2 * b2, tt = a1 * a2 + b1 * b2, @@ -433,42 +464,51 @@ * @param anticlockwise {boolean} Optional. Specifies whether the drawing should be counterclockwise or clockwise. False is default, and indicates clockwise, while true indicates counter-clockwise. * @return {Graphics} */ -Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) { +Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) +{ var startX = cx + Math.cos(startAngle) * radius; var startY = cy + Math.sin(startAngle) * radius; var points; // TODO - This if-else makes no sense. It uses currentPath in the else where it doesn't exist... - if (this.currentPath) { + if (this.currentPath) + { points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { points.push(startX, startY); } - else if (points[points.length-2] !== startX || points[points.length-1] !== startY) { + else if (points[points.length-2] !== startX || points[points.length-1] !== startY) + { points.push(startX, startY); } } - else { + else + { this.moveTo(startX, startY); points = this.currentPath.shape.points; } - if (startAngle === endAngle) { + if (startAngle === endAngle) + { return this; } - if (!anticlockwise && endAngle <= startAngle) { + if (!anticlockwise && endAngle <= startAngle) + { endAngle += Math.PI * 2; } - else if (anticlockwise && startAngle <= endAngle) { + else if (anticlockwise && startAngle <= endAngle) + { startAngle += Math.PI * 2; } var sweep = anticlockwise ? (startAngle - endAngle) *-1 : (endAngle - startAngle); var segs = (Math.abs(sweep)/ (Math.PI * 2)) * 40; - if (sweep === 0) { + if (sweep === 0) + { return this; } @@ -482,7 +522,8 @@ var remainder = ( segMinus % 1 ) / segMinus; - for (var i = 0; i <= segMinus; ++i) { + for (var i = 0; i <= segMinus; ++i) + { var real = i + remainder * i; var angle = ((theta) + startAngle + (theta2 * real)); @@ -506,13 +547,16 @@ * @param alpha {number} the alpha of the fill * @return {Graphics} */ -Graphics.prototype.beginFill = function (color, alpha) { +Graphics.prototype.beginFill = function (color, alpha) +{ this.filling = true; this.fillColor = color || 0; this.fillAlpha = (alpha === undefined) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length <= 2) + { this.currentPath.fill = this.filling; this.currentPath.fillColor = this.fillColor; this.currentPath.fillAlpha = this.fillAlpha; @@ -526,7 +570,8 @@ * * @return {Graphics} */ -Graphics.prototype.endFill = function () { +Graphics.prototype.endFill = function () +{ this.filling = false; this.fillColor = null; this.fillAlpha = 1; @@ -542,7 +587,8 @@ * @param height {number} The height of the rectangle * @return {Graphics} */ -Graphics.prototype.drawRect = function ( x, y, width, height ) { +Graphics.prototype.drawRect = function ( x, y, width, height ) +{ this.drawShape(new math.Rectangle(x,y, width, height)); return this; @@ -556,7 +602,8 @@ * @param height {number} The height of the rectangle * @param radius {number} Radius of the rectangle corners */ -Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) { +Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) +{ this.drawShape(new math.RoundedRectangle(x, y, width, height, radius)); return this; @@ -570,7 +617,8 @@ * @param radius {number} The radius of the circle * @return {Graphics} */ -Graphics.prototype.drawCircle = function (x, y, radius) { +Graphics.prototype.drawCircle = function (x, y, radius) +{ this.drawShape(new math.Circle(x,y, radius)); return this; @@ -585,7 +633,8 @@ * @param height {number} The half height of the ellipse * @return {Graphics} */ -Graphics.prototype.drawEllipse = function (x, y, width, height) { +Graphics.prototype.drawEllipse = function (x, y, width, height) +{ this.drawShape(new math.Ellipse(x, y, width, height)); return this; @@ -597,8 +646,10 @@ * @param path {Array} The path data used to construct the polygon. * @return {Graphics} */ -Graphics.prototype.drawPolygon = function (path) { - if (!(path instanceof Array)) { +Graphics.prototype.drawPolygon = function (path) +{ + if (!(path instanceof Array)) + { path = Array.prototype.slice.call(arguments); } @@ -612,7 +663,8 @@ * * @return {Graphics} */ -Graphics.prototype.clear = function () { +Graphics.prototype.clear = function () +{ this.lineWidth = 0; this.filling = false; @@ -631,7 +683,8 @@ * @param scaleMode {number} Should be one of the scaleMode consts * @return {Texture} a texture of the graphics object */ -Graphics.prototype.generateTexture = function (resolution, scaleMode) { +Graphics.prototype.generateTexture = function (resolution, scaleMode) +{ resolution = resolution || 1; var bounds = this.getBounds(); @@ -655,17 +708,21 @@ * * @param renderer {WebGLRenderer} */ -Graphics.prototype._renderWebGL = function (renderer) { +Graphics.prototype._renderWebGL = function (renderer) +{ // if the sprite is not visible or the alpha is 0 then no need to render this element - if (this.isMask === true) { + if (this.isMask === true) + { return; } // this code may still be needed so leaving for now.. - // + // /* - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture on the gpu too! @@ -681,17 +738,24 @@ return; } - */ - - // check if the webgl graphic needs to be updated - if (this.glDirty) { - this.dirty = true; - this.glDirty = false; - } + else */ - renderer.setObjectRendererer(renderer.graphicsRenderer); - renderer.graphicsRenderer.render(this); + renderer.spriteBatch.stop(); + renderer.blendModeManager.setBlendMode(this.blendMode); + // check blend mode + renderer.blendModeManager.setBlendMode( this.blendMode ); + + // check if the webgl graphic needs to be updated + if (this.glDirty) + { + this.dirty = true; + this.glDirty = false; + } + + WebGLGraphics.renderGraphics(this, renderer); + + renderer.spriteBatch.start(); }; /** @@ -700,14 +764,18 @@ * @param renderer {CanvasRenderer} * @private */ -Graphics.prototype.renderCanvas = function (renderer) { +Graphics.prototype.renderCanvas = function (renderer) +{ // 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.isMask === true) { + if (!this.visible || this.alpha <= 0 || this.isMask === true) + { return; } - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture @@ -723,16 +791,19 @@ return; } - else { + else + { var context = renderer.context; var transform = this.worldTransform; - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } @@ -748,11 +819,13 @@ CanvasGraphics.renderGraphics(this, context); - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } } @@ -763,13 +836,16 @@ * * @return {Rectangle} the rectangular bounding area */ -Graphics.prototype.getBounds = function (matrix) { +Graphics.prototype.getBounds = function (matrix) +{ // return an empty object if the item is a mask! - if (this.isMask) { + if (this.isMask) + { return math.Rectangle.EMPTY; } - if (this.dirty) { + if (this.dirty) + { this.updateLocalBounds(); this.glDirty = true; @@ -841,23 +917,27 @@ * Update the bounds of the object * */ -Graphics.prototype.updateLocalBounds = function () { +Graphics.prototype.updateLocalBounds = function () +{ var minX = Infinity; var maxX = -Infinity; var minY = Infinity; var maxY = -Infinity; - if (this.graphicsData.length) { + if (this.graphicsData.length) + { var shape, points, x, y, w, h; - for (var i = 0; i < this.graphicsData.length; i++) { + for (var i = 0; i < this.graphicsData.length; i++) + { var data = this.graphicsData[i]; var type = data.type; var lineWidth = data.lineWidth; shape = data.shape; - if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) { + if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) + { x = shape.x - lineWidth/2; y = shape.y - lineWidth/2; w = shape.width + lineWidth; @@ -869,7 +949,8 @@ minY = y < minY ? y : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.CIRC) { + else if (type === CONST.SHAPES.CIRC) + { x = shape.x; y = shape.y; w = shape.radius + lineWidth/2; @@ -881,7 +962,8 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.ELIP) { + else if (type === CONST.SHAPES.ELIP) + { x = shape.x; y = shape.y; w = shape.width + lineWidth/2; @@ -893,11 +975,13 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else { + else + { // POLY points = shape.points; - for (var j = 0; j < points.length; j += 2) { + for (var j = 0; j < points.length; j += 2) + { x = points[j]; y = points[j+1]; @@ -910,7 +994,8 @@ } } } - else { + else + { minX = 0; maxX = 0; minY = 0; @@ -931,10 +1016,12 @@ * * @private */ -Graphics.prototype._generateCachedSprite = function () { +Graphics.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { var canvasBuffer = new CanvasBuffer(bounds.width, bounds.height); var texture = Texture.fromCanvas(canvasBuffer.canvas); @@ -943,7 +1030,8 @@ this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.buffer.resize(bounds.width, bounds.height); } @@ -968,7 +1056,8 @@ * * @private */ -Graphics.prototype.updateCachedSpriteTexture = function () { +Graphics.prototype.updateCachedSpriteTexture = function () +{ var cachedSprite = this._cachedSprite; var texture = cachedSprite.texture; var canvas = cachedSprite.buffer.canvas; @@ -989,7 +1078,8 @@ * Destroys a previous cached sprite. * */ -Graphics.prototype.destroyCachedSprite = function () { +Graphics.prototype.destroyCachedSprite = function () +{ this._cachedSprite.texture.destroy(true); // let the gc collect the unused sprite @@ -1003,10 +1093,13 @@ * @param {Circle|Rectangle|Ellipse|Line|Polygon} shape The Shape object to draw. * @return {GraphicsData} The generated GraphicsData object. */ -Graphics.prototype.drawShape = function (shape) { - if (this.currentPath) { +Graphics.prototype.drawShape = function (shape) +{ + if (this.currentPath) + { // check current path! - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath.shape.points.length <= 2) + { this.graphicsData.pop(); } } @@ -1017,7 +1110,8 @@ this.graphicsData.push(data); - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { data.shape.closed = this.filling; this.currentPath = data; } diff --git a/src/core/primitives/GraphicsData.js b/src/core/primitives/GraphicsData.js index 99decbe..788f6f2 100644 --- a/src/core/primitives/GraphicsData.js +++ b/src/core/primitives/GraphicsData.js @@ -4,7 +4,8 @@ * @class * @namespace PIXI */ -function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) { +function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) +{ this.lineWidth = lineWidth; this.lineColor = lineColor; this.lineAlpha = lineAlpha; @@ -27,7 +28,8 @@ * * @return {GraphicsData} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ return new GraphicsData( this.lineWidth, this.lineColor, diff --git a/src/core/renderers/canvas/CanvasRenderer.js b/src/core/renderers/canvas/CanvasRenderer.js index 15a0978..7aebd44 100644 --- a/src/core/renderers/canvas/CanvasRenderer.js +++ b/src/core/renderers/canvas/CanvasRenderer.js @@ -17,17 +17,22 @@ * @param [options.resolution=1] {number} the resolution of the renderer retina would be 2 * @param [options.clearBeforeRender=true] {boolean} This sets if the CanvasRenderer will clear the canvas or not before the new render pass. */ -function CanvasRenderer(width, height, options) { +function CanvasRenderer(width, height, options) +{ utils.sayHello('Canvas'); - if (options) { - for (var i in CONST.defaultRenderOptions) { - if (typeof options[i] === 'undefined') { + if (options) + { + for (var i in CONST.defaultRenderOptions) + { + if (typeof options[i] === 'undefined') + { options[i] = CONST.defaultRenderOptions[i]; } } } - else { + else + { options = CONST.defaultRenderOptions; } @@ -156,19 +161,24 @@ this.smoothProperty = null; - if (this.context.imageSmoothingEnabled) { + if (this.context.imageSmoothingEnabled) + { this.smoothProperty = 'imageSmoothingEnabled'; } - else if (this.context.webkitImageSmoothingEnabled) { + else if (this.context.webkitImageSmoothingEnabled) + { this.smoothProperty = 'webkitImageSmoothingEnabled'; } - else if (this.context.mozImageSmoothingEnabled) { + else if (this.context.mozImageSmoothingEnabled) + { this.smoothProperty = 'mozImageSmoothingEnabled'; } - else if (this.context.oImageSmoothingEnabled) { + else if (this.context.oImageSmoothingEnabled) + { this.smoothProperty = 'oImageSmoothingEnabled'; } - else if (this.context.msImageSmoothingEnabled) { + else if (this.context.msImageSmoothingEnabled) + { this.smoothProperty = 'msImageSmoothingEnabled'; } @@ -193,10 +203,12 @@ * @memberof CanvasRenderer# */ backgroundColor: { - get: function () { + get: function () + { return this._backgroundColor; }, - set: function (val) { + set: function (val) + { this._backgroundColor = val; this._backgroundColorString = utils.hex2string(val); } @@ -208,7 +220,8 @@ * * @param object {DisplayObject} the object to be rendered */ -CanvasRenderer.prototype.render = function (object) { +CanvasRenderer.prototype.render = function (object) +{ object.updateTransform(); this.context.setTransform(1,0,0,1,0,0); @@ -218,16 +231,20 @@ this.currentBlendMode = CONST.blendModes.NORMAL; this.context.globalCompositeOperation = this.blendModes[CONST.blendModes.NORMAL]; - if (navigator.isCocoonJS && this.view.screencanvas) { + if (navigator.isCocoonJS && this.view.screencanvas) + { this.context.fillStyle = 'black'; this.context.clear(); } - if (this.clearBeforeRender) { - if (this.transparent) { + if (this.clearBeforeRender) + { + if (this.transparent) + { this.context.clearRect(0, 0, this.width, this.height); } - else { + else + { this.context.fillStyle = this._backgroundColorString; this.context.fillRect(0, 0, this.width , this.height); } @@ -241,8 +258,10 @@ * * @param [removeView=false] {boolean} Removes the Canvas element from the DOM. */ -CanvasRenderer.prototype.destroy = function (removeView) { - if (removeView && this.view.parent) { +CanvasRenderer.prototype.destroy = function (removeView) +{ + if (removeView && this.view.parent) + { this.view.parent.removeChild(this.view); } @@ -257,14 +276,16 @@ * @param width {number} the new width of the canvas view * @param height {number} the new height of the canvas view */ -CanvasRenderer.prototype.resize = function (width, height) { +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) { + if (this.autoResize) + { this.view.style.width = this.width / this.resolution + 'px'; this.view.style.height = this.height / this.resolution + 'px'; } @@ -276,7 +297,8 @@ * @param displayObject {DisplayObject} The displayObject to render * @private */ -CanvasRenderer.prototype.renderDisplayObject = function (displayObject) { +CanvasRenderer.prototype.renderDisplayObject = function (displayObject) +{ displayObject.renderCanvas(this); }; @@ -285,11 +307,14 @@ * * @private */ -CanvasRenderer.prototype._mapBlendModes = function () { - if (!this.blendModes) { +CanvasRenderer.prototype._mapBlendModes = function () +{ + if (!this.blendModes) + { this.blendModes = {}; - if (utils.canUseNewCanvasBlendModes()) { + if (utils.canUseNewCanvasBlendModes()) + { this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? this.blendModes[CONST.blendModes.MULTIPLY] = 'multiply'; @@ -308,7 +333,8 @@ this.blendModes[CONST.blendModes.COLOR] = 'color'; this.blendModes[CONST.blendModes.LUMINOSITY] = 'luminosity'; } - else { + else + { // this means that the browser does not support the cool new blend modes in canvas 'cough' ie 'cough' this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? diff --git a/src/core/renderers/canvas/utils/CanvasBuffer.js b/src/core/renderers/canvas/utils/CanvasBuffer.js index ebe5d47..b183a66 100644 --- a/src/core/renderers/canvas/utils/CanvasBuffer.js +++ b/src/core/renderers/canvas/utils/CanvasBuffer.js @@ -6,7 +6,8 @@ * @param width {number} the width for the newly created canvas * @param height {number} the height for the newly created canvas */ -function CanvasBuffer(width, height) { +function CanvasBuffer(width, height) +{ /** * The Canvas object that belongs to this CanvasBuffer. * @@ -36,10 +37,12 @@ * @memberof CanvasBuffer# */ width: { - get: function () { + get: function () + { return this.canvas.width; }, - set: function (val) { + set: function (val) + { this.canvas.width = val; } }, @@ -50,10 +53,12 @@ * @memberof CanvasBuffer# */ height: { - get: function () { + get: function () + { return this.canvas.height; }, - set: function (val) { + set: function (val) + { this.canvas.height = val; } } @@ -64,7 +69,8 @@ * * @private */ -CanvasBuffer.prototype.clear = function () { +CanvasBuffer.prototype.clear = function () +{ this.context.setTransform(1, 0, 0, 1, 0, 0); this.context.clearRect(0,0, this.canvas.width, this.canvas.height); }; @@ -75,7 +81,8 @@ * @param width {number} the new width of the canvas * @param height {number} the new height of the canvas */ -CanvasBuffer.prototype.resize = function (width, height) { +CanvasBuffer.prototype.resize = function (width, height) +{ this.canvas.width = width; this.canvas.height = height; }; diff --git a/src/core/renderers/canvas/utils/CanvasGraphics.js b/src/core/renderers/canvas/utils/CanvasGraphics.js index c7eaa2a..3f2a91f 100644 --- a/src/core/renderers/canvas/utils/CanvasGraphics.js +++ b/src/core/renderers/canvas/utils/CanvasGraphics.js @@ -13,15 +13,18 @@ * @param graphics {Graphics} the actual graphics object to render * @param context {CanvasRenderingContext2D} the 2d drawing method of the canvas */ -CanvasGraphics.renderGraphics = function (graphics, context) { +CanvasGraphics.renderGraphics = function (graphics, context) +{ var worldAlpha = graphics.worldAlpha; - if (graphics.dirty) { + if (graphics.dirty) + { this.updateGraphicsTint(graphics); graphics.dirty = false; } - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; @@ -30,69 +33,82 @@ context.lineWidth = data.lineWidth; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { context.beginPath(); var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } - if (shape.closed) { + if (shape.closed) + { context.lineTo(points[0], points[1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fillRect(shape.x, shape.y, shape.width, shape.height); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.strokeRect(shape.x, shape.y, shape.width, shape.height); } } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.beginPath(); context.arc(shape.x, shape.y, shape.radius,0,2*Math.PI); context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas var w = shape.width * 2; @@ -119,18 +135,21 @@ context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; var width = shape.width; @@ -152,13 +171,15 @@ context.quadraticCurveTo(rx, ry, rx, ry + radius); context.closePath(); - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); @@ -174,45 +195,54 @@ * @param graphics {Graphics} the graphics which will be used as a mask * @param context {CanvasRenderingContext2D} the context 2d method of the canvas */ -CanvasGraphics.renderGraphicsMask = function (graphics, context) { +CanvasGraphics.renderGraphicsMask = function (graphics, context) +{ var len = graphics.graphicsData.length; - if (len === 0) { + if (len === 0) + { return; } context.beginPath(); - for (var i = 0; i < len; i++) { + for (var i = 0; i < len; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { context.rect(shape.x, shape.y, shape.width, shape.height); context.closePath(); } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.arc(shape.x, shape.y, shape.radius, 0, 2 * Math.PI); context.closePath(); } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas @@ -237,7 +267,8 @@ context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); context.closePath(); } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; @@ -262,8 +293,10 @@ } }; -CanvasGraphics.updateGraphicsTint = function (graphics) { - if (graphics.tint === 0xFFFFFF) { +CanvasGraphics.updateGraphicsTint = function (graphics) +{ + if (graphics.tint === 0xFFFFFF) + { return; } @@ -271,7 +304,8 @@ var tintG = (graphics.tint >> 8 & 0xFF) / 255; var tintB = (graphics.tint & 0xFF)/ 255; - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var fillColor = data.fillColor | 0; diff --git a/src/core/renderers/canvas/utils/CanvasMaskManager.js b/src/core/renderers/canvas/utils/CanvasMaskManager.js index e04a733..9827d36 100644 --- a/src/core/renderers/canvas/utils/CanvasMaskManager.js +++ b/src/core/renderers/canvas/utils/CanvasMaskManager.js @@ -6,7 +6,8 @@ * @class * @namespace PIXI */ -function CanvasMaskManager() {} +function CanvasMaskManager() +{} CanvasMaskManager.prototype.constructor = CanvasMaskManager; module.exports = CanvasMaskManager; @@ -17,7 +18,8 @@ * @param maskData {object} the maskData that will be pushed * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.pushMask = function (maskData, renderer) { +CanvasMaskManager.prototype.pushMask = function (maskData, renderer) +{ renderer.context.save(); var cacheAlpha = maskData.alpha; @@ -45,6 +47,7 @@ * * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.popMask = function (renderer) { +CanvasMaskManager.prototype.popMask = function (renderer) +{ renderer.context.restore(); }; diff --git a/src/core/renderers/canvas/utils/CanvasTinter.js b/src/core/renderers/canvas/utils/CanvasTinter.js index 17e0529..d2fb1bc 100644 --- a/src/core/renderers/canvas/utils/CanvasTinter.js +++ b/src/core/renderers/canvas/utils/CanvasTinter.js @@ -14,7 +14,8 @@ * @param color {number} the color to use to tint the sprite with * @return {HTMLCanvasElement} The tinted canvas */ -CanvasTinter.getTintedTexture = function (sprite, color) { +CanvasTinter.getTintedTexture = function (sprite, color) +{ var texture = sprite.texture; color = CanvasTinter.roundColor(color); @@ -23,7 +24,8 @@ texture.tintCache = texture.tintCache || {}; - if (texture.tintCache[stringColor]) { + if (texture.tintCache[stringColor]) + { return texture.tintCache[stringColor]; } @@ -33,14 +35,16 @@ //CanvasTinter.tintWithPerPixel(texture, stringColor, canvas); CanvasTinter.tintMethod(texture, color, canvas); - if (CanvasTinter.convertTintToImage) { + if (CanvasTinter.convertTintToImage) + { // is this better? var tintImage = new Image(); tintImage.src = canvas.toDataURL(); texture.tintCache[stringColor] = tintImage; } - else { + else + { texture.tintCache[stringColor] = canvas; // if we are not converting the texture to an image then we need to lose the reference to the canvas CanvasTinter.canvas = null; @@ -56,7 +60,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithMultiply = function (texture, color, canvas) { +CanvasTinter.tintWithMultiply = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -104,7 +109,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithOverlay = function (texture, color, canvas) { +CanvasTinter.tintWithOverlay = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -139,7 +145,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithPerPixel = function (texture, color, canvas) { +CanvasTinter.tintWithPerPixel = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -167,7 +174,8 @@ var pixels = pixelData.data; - for (var i = 0; i < pixels.length; i += 4) { + for (var i = 0; i < pixels.length; i += 4) + { pixels[i+0] *= r; pixels[i+1] *= g; pixels[i+2] *= b; @@ -181,7 +189,8 @@ * * @param color {number} the color to round, should be a hex color */ -CanvasTinter.roundColor = function (color) { +CanvasTinter.roundColor = function (color) +{ var step = CanvasTinter.cacheStepsPerColorChannel; var rgbValues = utils.hex2rgb(color); diff --git a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js index 9f2f89a..35edbaf 100644 --- a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js +++ b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLBlendModeManager(renderer) { +function WebGLBlendModeManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -23,8 +24,10 @@ * * @param blendMode {number} the blendMode, should be a Pixi const, such as BlendModes.ADD */ -WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) { - if (this.currentBlendMode === blendMode) { +WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) +{ + if (this.currentBlendMode === blendMode) + { return false; } diff --git a/src/core/renderers/webgl/managers/WebGLFilterManager.js b/src/core/renderers/webgl/managers/WebGLFilterManager.js index 1179258..2dac048 100644 --- a/src/core/renderers/webgl/managers/WebGLFilterManager.js +++ b/src/core/renderers/webgl/managers/WebGLFilterManager.js @@ -7,7 +7,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLFilterManager(renderer) { +function WebGLFilterManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -32,7 +33,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.texturePool.length = 0; self.initShaderBuffers(); }); @@ -46,7 +48,8 @@ * @param renderer {WebGLRenderer} * @param buffer {ArrayBuffer} */ -WebGLFilterManager.prototype.begin = function (buffer) { +WebGLFilterManager.prototype.begin = function (buffer) +{ this.defaultShader = this.renderer.shaderManager.defaultShader; this.width = this.renderer.projection.x * 2; @@ -60,7 +63,8 @@ * * @param filterBlock {object} the filter that will be pushed to the current filter stack */ -WebGLFilterManager.prototype.pushFilter = function (filterBlock) { +WebGLFilterManager.prototype.pushFilter = function (filterBlock) +{ var gl = this.renderer.gl; var projection = this.renderer.projection; @@ -78,10 +82,12 @@ this.offsetY += filterBlock._filterArea.y; var texture = this.texturePool.pop(); - if (!texture) { + if (!texture) + { texture = new FilterTexture(this.renderer.gl, this.width, this.height); } - else { + else + { texture.resize(this.width, this.height); } @@ -98,29 +104,35 @@ var localX = filterArea.x, localY = filterArea.y; - if (filterArea.x < 0) { + if (filterArea.x < 0) + { filterArea.width += filterArea.x; filterArea.x = 0; } - if (filterArea.y < 0) { + if (filterArea.y < 0) + { filterArea.height += filterArea.y; filterArea.y = 0; } - if (localX + filterArea.width > this.width) { + if (localX + filterArea.width > this.width) + { filterArea.width = this.width - localX; } - if (localY + filterArea.height > this.height) { + if (localY + filterArea.height > this.height) + { filterArea.height = this.height - localY; } - if (filterArea.width < 0) { + if (filterArea.width < 0) + { filterArea.width = 0; } - if (filterArea.height < 0) { + if (filterArea.height < 0) + { filterArea.height = 0; } @@ -154,7 +166,8 @@ * Removes the last filter from the filter stack and doesn't return it. * */ -WebGLFilterManager.prototype.popFilter = function () { +WebGLFilterManager.prototype.popFilter = function () +{ var gl = this.renderer.gl; var filterBlock = this.filterStack.pop(); @@ -163,7 +176,8 @@ var projection = this.renderer.projection; var offset = this.renderer.offset; - if (filterBlock.filterPasses.length > 1) { + if (filterBlock.filterPasses.length > 1) + { gl.viewport(0, 0, filterArea.width, filterArea.height); gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); @@ -193,7 +207,8 @@ var inputTexture = texture; var outputTexture = this.texturePool.pop(); - if (!outputTexture) { + if (!outputTexture) + { outputTexture = new FilterTexture(this.renderer.gl, this.width, this.height); } outputTexture.resize(this.width, this.height); @@ -204,7 +219,8 @@ gl.disable(gl.BLEND); - for (var i = 0; i < filterBlock.filterPasses.length-1; i++) { + for (var i = 0; i < filterBlock.filterPasses.length-1; i++) + { var filterPass = filterBlock.filterPasses[i]; gl.bindFramebuffer(gl.FRAMEBUFFER, outputTexture.frameBuffer ); @@ -243,10 +259,12 @@ var buffer = this.buffer; // time to render the filters texture to the previous scene - if (this.filterStack.length === 0) { + if (this.filterStack.length === 0) + { gl.colorMask(true, true, true, true);//this.transparent); } - else { + else + { var currentFilter = this.filterStack[this.filterStack.length-1]; filterArea = currentFilter._filterArea; @@ -332,13 +350,15 @@ * @param width {number} the horizontal range of the filter * @param height {number} the vertical range of the filter */ -WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) { +WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) +{ // use program var gl = this.renderer.gl; var shader = filter.shaders[gl.id]; - if (!shader) { + if (!shader) + { shader = new Shader(gl); shader.fragmentSrc = filter.fragmentSrc; @@ -356,7 +376,8 @@ gl.uniform2f(shader.projectionVector, width/2, -height/2); gl.uniform2f(shader.offsetVector, 0,0); - if (filter.uniforms.dimensions) { + 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]; @@ -386,7 +407,8 @@ * Initialises the shader buffers. * */ -WebGLFilterManager.prototype.initShaderBuffers = function () { +WebGLFilterManager.prototype.initShaderBuffers = function () +{ var gl = this.renderer.gl; // create some buffers @@ -432,7 +454,8 @@ * Destroys the filter and removes it from the filter stack. * */ -WebGLFilterManager.prototype.destroy = function () { +WebGLFilterManager.prototype.destroy = function () +{ var gl = this.renderer.gl; this.filterStack = null; @@ -441,7 +464,8 @@ this.offsetY = 0; // destroy textures - for (var i = 0; i < this.texturePool.length; i++) { + for (var i = 0; i < this.texturePool.length; i++) + { this.texturePool[i].destroy(); } diff --git a/src/core/renderers/webgl/managers/WebGLManager.js b/src/core/renderers/webgl/managers/WebGLManager.js index 9d47b5c..c30cd51 100644 --- a/src/core/renderers/webgl/managers/WebGLManager.js +++ b/src/core/renderers/webgl/managers/WebGLManager.js @@ -3,7 +3,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLManager(renderer) { +function WebGLManager(renderer) +{ /** * The renderer this manager works for. * @@ -15,6 +16,7 @@ WebGLManager.prototype.constructor = WebGLManager; module.exports = WebGLManager; -WebGLManager.prototype.destroy = function () { +WebGLManager.prototype.destroy = function () +{ this.renderer = null; }; diff --git a/src/core/renderers/webgl/managers/WebGLMaskManager.js b/src/core/renderers/webgl/managers/WebGLMaskManager.js index 2f90b64..e568812 100644 --- a/src/core/renderers/webgl/managers/WebGLMaskManager.js +++ b/src/core/renderers/webgl/managers/WebGLMaskManager.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLMaskManager(renderer) { +function WebGLMaskManager(renderer) +{ WebGLManager.call(this, renderer); } @@ -19,12 +20,15 @@ * * @param maskData {any[]} */ -WebGLMaskManager.prototype.pushMask = function (maskData) { - if (maskData.dirty) { +WebGLMaskManager.prototype.pushMask = function (maskData) +{ + if (maskData.dirty) + { WebGLGraphics.updateGraphics(maskData, this.renderer.gl); } - if (!maskData._webGL[this.renderer.gl.id].data.length) { + if (!maskData._webGL[this.renderer.gl.id].data.length) + { return; } @@ -36,6 +40,7 @@ * * @param maskData {any[]} */ -WebGLMaskManager.prototype.popMask = function (maskData) { +WebGLMaskManager.prototype.popMask = function (maskData) +{ this.renderer.stencilManager.popStencil(maskData, maskData._webGL[this.renderer.gl.id].data[0], this.renderer); }; diff --git a/src/core/renderers/webgl/managers/WebGLShaderManager.js b/src/core/renderers/webgl/managers/WebGLShaderManager.js index fef071c..90c6477 100644 --- a/src/core/renderers/webgl/managers/WebGLShaderManager.js +++ b/src/core/renderers/webgl/managers/WebGLShaderManager.js @@ -10,7 +10,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLShaderManager(renderer) { +function WebGLShaderManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -28,7 +29,8 @@ */ this.tempAttribState = []; - for (var i = 0; i < this.maxAttibs; i++) { + for (var i = 0; i < this.maxAttibs; i++) + { this.attribState[i] = false; } @@ -66,7 +68,8 @@ // listen for context and update necessary shaders var self = this; - this.renderer.on('context', function (event) { + this.renderer.on('context', function (event) + { var gl = event.data; // this shader is used for rendering primitives @@ -97,29 +100,36 @@ * * @param attribs {Array} attribs */ -WebGLShaderManager.prototype.setAttribs = function (attribs) { +WebGLShaderManager.prototype.setAttribs = function (attribs) +{ // reset temp state var i; - for (i = 0; i < this.tempAttribState.length; i++) { + for (i = 0; i < this.tempAttribState.length; i++) + { this.tempAttribState[i] = false; } // set the new attribs - for (var a in attribs) { + for (var a in attribs) + { this.tempAttribState[attribs[a]] = true; } var gl = this.renderer.gl; - for (i = 0; i < this.attribState.length; i++) { - if (this.attribState[i] !== this.tempAttribState[i]) { + for (i = 0; i < this.attribState.length; i++) + { + if (this.attribState[i] !== this.tempAttribState[i]) + { this.attribState[i] = this.tempAttribState[i]; - if (this.attribState[i]) { + if (this.attribState[i]) + { gl.enableVertexAttribArray(i); } - else { + else + { gl.disableVertexAttribArray(i); } } @@ -131,8 +141,10 @@ * * @param shader {Any} */ -WebGLShaderManager.prototype.setShader = function (shader) { - if (this._currentId === shader.uuid) { +WebGLShaderManager.prototype.setShader = function (shader) +{ + if (this._currentId === shader.uuid) + { return false; } @@ -150,7 +162,8 @@ * Destroys this object. * */ -WebGLShaderManager.prototype.destroy = function () { +WebGLShaderManager.prototype.destroy = function () +{ this.attribState = null; this.tempAttribState = null; diff --git a/src/core/renderers/webgl/managers/WebGLStencilManager.js b/src/core/renderers/webgl/managers/WebGLStencilManager.js index 9ec6398..4cb0134 100644 --- a/src/core/renderers/webgl/managers/WebGLStencilManager.js +++ b/src/core/renderers/webgl/managers/WebGLStencilManager.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLStencilManager(renderer) { +function WebGLStencilManager(renderer) +{ WebGLManager.call(this, renderer); this.stencilStack = []; @@ -24,12 +25,14 @@ * @param graphics {Graphics} * @param webGLData {any[]} */ -WebGLStencilManager.prototype.pushStencil = function (graphics, webGLData) { +WebGLStencilManager.prototype.pushStencil = function (graphics, webGLData) +{ var gl = this.renderer.gl; this.bindGraphics(graphics, webGLData, this.renderer); - if (this.stencilStack.length === 0) { + if (this.stencilStack.length === 0) + { gl.enable(gl.STENCIL_TEST); gl.clear(gl.STENCIL_BUFFER_BIT); this.reverse = true; @@ -47,14 +50,17 @@ // draw the triangle strip! - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } @@ -62,31 +68,38 @@ // draw a quad to increment.. gl.drawElements(gl.TRIANGLE_FAN, 4, gl.UNSIGNED_SHORT, ( webGLData.indices.length - 4 ) * 2 ); - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); } this.reverse = !this.reverse; } - else { - if (!this.reverse) { + else + { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } - else { + 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) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); } } @@ -103,7 +116,8 @@ * @param graphics {Graphics} * @param webGLData {Array} */ -WebGLStencilManager.prototype.bindGraphics = function (graphics, webGLData) { +WebGLStencilManager.prototype.bindGraphics = function (graphics, webGLData) +{ //if (this._currentGraphics === graphics)return; this._currentGraphics = graphics; @@ -114,7 +128,8 @@ offset = this.renderer.offset, shader;// = this.renderer.shaderManager.primitiveShader; - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { shader = this.renderer.shaderManager.complexPrimitiveShader; this.renderer.shaderManager.setShader(shader); @@ -141,7 +156,8 @@ // set the index buffer! gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, webGLData.indexBuffer); } - else { + else + { //this.renderer.shaderManager.activatePrimitiveShader(); shader = this.renderer.shaderManager.primitiveShader; this.renderer.shaderManager.setShader( shader ); @@ -154,7 +170,7 @@ gl.uniform2f(shader.uniforms.offsetVector._location, -offset.x, -offset.y); gl.uniform3fv(shader.uniforms.tint._location, utils.hex2rgb(graphics.tint)); - + gl.uniform1f(shader.uniforms.alpha._location, graphics.worldAlpha); @@ -172,19 +188,22 @@ * @param graphics {Graphics} * @param webGLData {Array} */ -WebGLStencilManager.prototype.popStencil = function (graphics, webGLData) { +WebGLStencilManager.prototype.popStencil = function (graphics, webGLData) +{ var gl = this.renderer.gl; this.stencilStack.pop(); this.count--; - if (this.stencilStack.length === 0) { + if (this.stencilStack.length === 0) + { // the stack is empty! gl.disable(gl.STENCIL_TEST); } - else { + else + { var level = this.count; @@ -192,14 +211,17 @@ gl.colorMask(false, false, false, false); - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { this.reverse = !this.reverse; - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } @@ -213,31 +235,38 @@ // draw the triangle strip! gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); - if (!this.reverse) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); } } - else { + else + { // console.log("<<>>") - if (!this.reverse) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } - else { + 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) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); } } @@ -253,7 +282,8 @@ * Destroys the mask stack. * */ -WebGLStencilManager.prototype.destroy = function () { +WebGLStencilManager.prototype.destroy = function () +{ this.renderer = null; this.stencilStack = null; }; diff --git a/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js b/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js index 913ba5e..1ea7d19 100644 --- a/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js +++ b/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function ComplexPrimitiveShader(gl) { +function ComplexPrimitiveShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -24,7 +25,8 @@ 'uniform float flipY;', 'varying vec4 vColor;', - 'void main(void) {', + '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);', @@ -37,7 +39,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = vColor;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/FastShader.js b/src/core/renderers/webgl/shaders/FastShader.js index bd2e29a..2e5e060 100644 --- a/src/core/renderers/webgl/shaders/FastShader.js +++ b/src/core/renderers/webgl/shaders/FastShader.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function FastShader(gl) { +function FastShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -28,7 +29,8 @@ 'const vec2 center = vec2(-1.0, 1.0);', - 'void main(void) {', + 'void main(void) + {', ' vec2 v;', ' vec2 sv = aVertexPosition * aScale;', ' v.x = (sv.x) * cos(aRotation) - (sv.y) * sin(aRotation);', @@ -49,7 +51,8 @@ 'uniform sampler2D uSampler;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/PrimitiveShader.js b/src/core/renderers/webgl/shaders/PrimitiveShader.js index 6f25409..a25f54f 100644 --- a/src/core/renderers/webgl/shaders/PrimitiveShader.js +++ b/src/core/renderers/webgl/shaders/PrimitiveShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function PrimitiveShader(gl) { +function PrimitiveShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -23,7 +24,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + '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);', @@ -36,7 +38,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = vColor;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/Shader.js b/src/core/renderers/webgl/shaders/Shader.js index f8964f5..fd75ef5 100644 --- a/src/core/renderers/webgl/shaders/Shader.js +++ b/src/core/renderers/webgl/shaders/Shader.js @@ -6,7 +6,8 @@ * @param [fragmentSrc] {string} The source of the fragment shader. * @param [vertexSrc] {string} The source of the vertex shader. */ -function Shader(gl, vertexSrc, fragmentSrc, customUniforms, customAttributes) { +function Shader(gl, vertexSrc, fragmentSrc, customUniforms, customAttributes) +{ /** * @member {number} * @readonly @@ -33,7 +34,8 @@ dimensions: { type: '4f', value: new Float32Array(4) } }; - for (var u in customUniforms) { + for (var u in customUniforms) + { this.uniforms[u] = customUniforms[u]; } @@ -43,7 +45,8 @@ aColor: 0 }; - for (var a in customAttributes) { + for (var a in customAttributes) + { this.attributes[a] = customAttributes[a]; } @@ -66,7 +69,8 @@ 'const vec2 center = vec2(-1.0, 1.0);', - 'void main(void) {', + 'void main(void) + {', ' gl_Position = vec4( ((aVertexPosition + offsetVector) / projectionVector) + center , 0.0, 1.0);', ' vTextureCoord = aTextureCoord;', ' vColor = vec4(aColor.rgb * aColor.a, aColor.a);', @@ -85,7 +89,8 @@ 'uniform sampler2D uSampler;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;', '}' ].join('\n'); @@ -96,7 +101,8 @@ Shader.prototype.constructor = Shader; module.exports = Shader; -Shader.prototype.init = function () { +Shader.prototype.init = function () +{ this.compile(); this.gl.useProgram(this.program); @@ -105,14 +111,18 @@ this.cacheAttributeLocations(Object.keys(this.attributes)); }; -Shader.prototype.cacheUniformLocations = function (keys) { - for (var i = 0; i < keys.length; ++i) { +Shader.prototype.cacheUniformLocations = function (keys) +{ + for (var i = 0; i < keys.length; ++i) + { this.uniforms[keys[i]]._location = this.gl.getUniformLocation(this.program, keys[i]); } }; -Shader.prototype.cacheAttributeLocations = function (keys) { - for (var i = 0; i < keys.length; ++i) { +Shader.prototype.cacheAttributeLocations = function (keys) +{ + for (var i = 0; i < keys.length; ++i) + { this.attributes[keys[i]] = this.gl.getAttribLocation(this.program, keys[i]); } @@ -124,14 +134,16 @@ // 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.attributes.aColor === -1) { + // if (this.attributes.aColor === -1) + { // this.attributes.aColor = 2; // } // End worst hack eva // }; -Shader.prototype.compile = function () { +Shader.prototype.compile = function () +{ var gl = this.gl; var glVertShader = this._glCompile(gl.VERTEX_SHADER, this.vertexSrc); @@ -144,13 +156,15 @@ gl.linkProgram(program); // if linking fails, then log and cleanup - if (!gl.getProgramParameter(program, gl.LINK_STATUS)) { + if (!gl.getProgramParameter(program, gl.LINK_STATUS)) + { window.console.error('Pixi.js Error: Could not initialize shader.'); window.console.error('gl.VALIDATE_STATUS', gl.getProgramParameter(program, gl.VALIDATE_STATUS)); window.console.error('gl.getError()', gl.getError()); // if there is a program info log, log it - if (gl.getProgramInfoLog(program) !== '') { + if (gl.getProgramInfoLog(program) !== '') + { window.console.warn('Pixi.js Warning: gl.getProgramInfoLog()', gl.getProgramInfoLog(program)); } @@ -165,18 +179,21 @@ return (this.program = program); }; -Shader.prototype.syncUniforms = function () { +Shader.prototype.syncUniforms = function () +{ var gl = this.gl; this.textureCount = 1; - for (var key in this.uniforms) { + for (var key in this.uniforms) + { var uniform = this.uniforms[key], location = uniform._location, value = uniform.value, i, il; - switch (uniform.type) { + switch (uniform.type) + { // single int value case 'i': case '1i': @@ -282,7 +299,8 @@ // a Color Value case 'c': - if (typeof value === 'number') { + if (typeof value === 'number') + { value = utils.hex2rgb(value); } @@ -311,11 +329,13 @@ // array of 2D Point objects case 'v2v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(2 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 2] = value[i].x; uniform._array[i * 2 + 1] = value[i].y; } @@ -325,11 +345,13 @@ // array of 3D Point objects case 'v3v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(3 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 3] = value[i].x; uniform._array[i * 3 + 1] = value[i].y; uniform._array[i * 3 + 2] = value[i].z; @@ -341,11 +363,13 @@ // array of 4D Point objects case 'v4v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(4 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 4] = value[i].x; uniform._array[i * 4 + 1] = value[i].y; uniform._array[i * 4 + 2] = value[i].z; @@ -359,7 +383,8 @@ // PIXI.Texture case 't': case 'sampler2D': - if (!uniform.value || !uniform.value.baseTexture || !uniform.value.baseTexture.hasLoaded) { + if (!uniform.value || !uniform.value.baseTexture || !uniform.value.baseTexture.hasLoaded) + { break; } @@ -376,7 +401,8 @@ this.textureCount++; // initialize the texture if we haven't yet - if (!uniform._init) { + if (!uniform._init) + { this.initSampler2D(uniform); uniform._init = true; @@ -394,11 +420,13 @@ * Initialises a Sampler2D uniform (which may only be available later on after initUniforms once the texture has loaded) * */ -Shader.prototype.initSampler2D = function (uniform) { +Shader.prototype.initSampler2D = function (uniform) +{ var gl = this.gl; // Extended texture data - if (uniform.textureData) { + if (uniform.textureData) + { var data = uniform.textureData; // GLTexture = mag linear, min linear_mipmap_linear, wrap repeat + gl.generateMipmap(gl.TEXTURE_2D); @@ -417,14 +445,16 @@ var wrapT = (data.wrapT) ? data.wrapT : gl.CLAMP_TO_EDGE; var format = (data.luminance) ? gl.LUMINANCE : gl.RGBA; - if (data.repeat) { + if (data.repeat) + { wrapS = gl.REPEAT; wrapT = gl.REPEAT; } gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, !!data.flipY); - if (data.width) { + if (data.width) + { var width = (data.width) ? data.width : 512; var height = (data.height) ? data.height : 2; var border = (data.border) ? data.border : 0; @@ -432,7 +462,8 @@ // 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 { + 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); } @@ -448,7 +479,8 @@ * Destroys the shader. * */ -Shader.prototype.destroy = function () { +Shader.prototype.destroy = function () +{ this.gl.deleteProgram(this.program); this.gl = null; @@ -459,13 +491,15 @@ this.fragmentSrc = null; }; -Shader.prototype._glCompile = function (type, src) { +Shader.prototype._glCompile = function (type, src) +{ var shader = this.gl.createShader(type); this.gl.shaderSource(shader, src); this.gl.compileShader(shader); - if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) { + if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) + { window.console.log(this.gl.getShaderInfoLog(shader)); return null; } diff --git a/src/core/renderers/webgl/shaders/StripShader.js b/src/core/renderers/webgl/shaders/StripShader.js index 193f6e1..a7abcc6 100644 --- a/src/core/renderers/webgl/shaders/StripShader.js +++ b/src/core/renderers/webgl/shaders/StripShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function StripShader(gl) { +function StripShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -20,7 +21,8 @@ 'varying vec2 vTextureCoord;', - 'void main(void) {', + '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);', @@ -36,7 +38,8 @@ 'varying vec2 vTextureCoord;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vec2(vTextureCoord.x, vTextureCoord.y)) * alpha;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/utils/FilterTexture.js b/src/core/renderers/webgl/utils/FilterTexture.js index d2c8423..4433d44 100644 --- a/src/core/renderers/webgl/utils/FilterTexture.js +++ b/src/core/renderers/webgl/utils/FilterTexture.js @@ -8,7 +8,8 @@ * @param height {number} the vertical range of the filter * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values */ -function FilterTexture(gl, width, height, scaleMode) { +function FilterTexture(gl, width, height, scaleMode) +{ /** * @member {WebGLContext} */ @@ -59,7 +60,8 @@ * Clears the filter texture. * */ -FilterTexture.prototype.clear = function () { +FilterTexture.prototype.clear = function () +{ var gl = this.gl; gl.clearColor(0,0,0, 0); @@ -72,8 +74,10 @@ * @param width {number} the new width of the texture * @param height {number} the new height of the texture */ -FilterTexture.prototype.resize = function (width, height) { - if (this.width === width && this.height === height) { +FilterTexture.prototype.resize = function (width, height) +{ + if (this.width === width && this.height === height) + { return; } @@ -96,7 +100,8 @@ * Destroys the filter texture. * */ -FilterTexture.prototype.destroy = function () { +FilterTexture.prototype.destroy = function () +{ var gl = this.gl; gl.deleteFramebuffer( this.frameBuffer ); gl.deleteTexture( this.texture ); diff --git a/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js b/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js index c4721e9..a63f4d7 100644 --- a/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js +++ b/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js @@ -14,7 +14,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this sprite batch works for. */ -function WebGLFastSpriteBatch(renderer) { +function WebGLFastSpriteBatch(renderer) +{ /** * The renderer instance this sprite batch operates on. * @@ -91,7 +92,8 @@ */ this.lastIndexCount = 0; - for (var i=0, j=0; i < numIndices; i += 6, j += 4) { + 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; @@ -144,7 +146,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.setupContext(); }); } @@ -157,7 +160,8 @@ * * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLFastSpriteBatch.prototype.setupContext = function () { +WebGLFastSpriteBatch.prototype.setupContext = function () +{ var gl = this.renderer.gl; // create a couple of buffers @@ -177,7 +181,8 @@ /** * @param spriteBatch {SpriteBatch} The SpriteBatch container to prepare for. */ -WebGLFastSpriteBatch.prototype.begin = function (spriteBatch) { +WebGLFastSpriteBatch.prototype.begin = function (spriteBatch) +{ this.shader = this.renderer.shaderManager.fastShader; this.matrix = spriteBatch.worldTransform.toArray(true); @@ -187,33 +192,38 @@ /** */ -WebGLFastSpriteBatch.prototype.end = function () { +WebGLFastSpriteBatch.prototype.end = function () +{ this.flush(); }; /** * @param spriteBatch {SpriteBatch} The SpriteBatch container to render. */ -WebGLFastSpriteBatch.prototype.render = function (spriteBatch) { +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) { + if (!sprite.texture._uvs) + { return; } this.currentBaseTexture = sprite.texture.baseTexture; // check blend mode - if (sprite.blendMode !== this.renderer.blendModeManager.currentBlendMode) { + if (sprite.blendMode !== this.renderer.blendModeManager.currentBlendMode) + { this.flush(); this.renderer.blendModeManager.setBlendMode(sprite.blendMode); } - for (var i=0,j= children.length; i= this.size) { + if (this.currentBatchSize >= this.size) + { this.flush(); } }; @@ -362,29 +379,35 @@ /** * */ -WebGLFastSpriteBatch.prototype.flush = function () { +WebGLFastSpriteBatch.prototype.flush = function () +{ // If the batch is length 0 then return as there is nothing to draw - if (this.currentBatchSize === 0) { + if (this.currentBatchSize === 0) + { return; } var gl = this.renderer.gl; // bind the current texture - if (!this.currentBaseTexture._glTextures[gl.id]) { + if (!this.currentBaseTexture._glTextures[gl.id]) + { this.renderer.updateTexture(this.currentBaseTexture, gl); } //TODO-SHOUD THIS BE ELSE??!?!?! - else { + else + { gl.bindTexture(gl.TEXTURE_2D, this.currentBaseTexture._glTextures[gl.id]); } // upload the verts to the buffer - if (this.currentBatchSize > ( this.size * 0.5 ) ) { + if (this.currentBatchSize > ( this.size * 0.5 ) ) + { gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); } - else { + else + { var view = this.vertices.subarray(0, this.currentBatchSize * this.vertByteSize); gl.bufferSubData(gl.ARRAY_BUFFER, 0, view); @@ -405,14 +428,16 @@ * Ends the batch and flushes * */ -WebGLFastSpriteBatch.prototype.stop = function () { +WebGLFastSpriteBatch.prototype.stop = function () +{ this.flush(); }; /** * */ -WebGLFastSpriteBatch.prototype.start = function () { +WebGLFastSpriteBatch.prototype.start = function () +{ var gl = this.renderer.gl; // bind the main texture diff --git a/src/core/renderers/webgl/utils/WebGLGraphics.js b/src/core/renderers/webgl/utils/WebGLGraphics.js index 55f4911..ab8f46e 100644 --- a/src/core/renderers/webgl/utils/WebGLGraphics.js +++ b/src/core/renderers/webgl/utils/WebGLGraphics.js @@ -19,7 +19,8 @@ * @param graphics {Graphics} * @param renderer {WebGLRenderer} */ -WebGLGraphics.renderGraphics = function (graphics, renderer) {//projection, offset) { +WebGLGraphics.renderGraphics = function (graphics, renderer) {//projection, offset) +{ var gl = renderer.gl; var projection = renderer.projection, @@ -27,7 +28,8 @@ shader = renderer.shaderManager.primitiveShader, webGLData; - if (graphics.dirty) { + if (graphics.dirty) + { WebGLGraphics.updateGraphics(graphics, gl); } @@ -35,8 +37,10 @@ // This could be speeded up for sure! - for (var i = 0; i < webGL.data.length; i++) { - if (webGL.data[i].mode === 1) { + for (var i = 0; i < webGL.data.length; i++) + { + if (webGL.data[i].mode === 1) + { webGLData = webGL.data[i]; renderer.stencilManager.pushStencil(graphics, webGLData, renderer); @@ -46,7 +50,8 @@ renderer.stencilManager.popStencil(graphics, webGLData, renderer); } - else { + else + { webGLData = webGL.data[i]; @@ -84,12 +89,14 @@ * @param graphicsData {Graphics} The graphics object to update * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLGraphics.updateGraphics = function (graphics, gl) { +WebGLGraphics.updateGraphics = function (graphics, gl) +{ // get the contexts graphics object var webGL = graphics._webGL[gl.id]; // if the graphics object does not exist in the webGL context time to create it! - if (!webGL) { + if (!webGL) + { webGL = graphics._webGL[gl.id] = {lastIndex:0, data:[], gl:gl}; } @@ -99,11 +106,13 @@ var i; // if the user cleared the graphics object we will need to clear every object - if (graphics.clearDirty) { + if (graphics.clearDirty) + { graphics.clearDirty = false; // lop through and return all the webGLDatas to the object pool so than can be reused later on - for (i = 0; i < webGL.data.length; i++) { + for (i = 0; i < webGL.data.length; i++) + { var graphicsData = webGL.data[i]; graphicsData.reset(); WebGLGraphics.graphicsDataPool.push( graphicsData ); @@ -119,58 +128,72 @@ // loop through the graphics datas and construct each one.. // if the object is a complex fill then the new stencil buffer technique will be used // other wise graphics objects will be pushed into a batch.. - for (i = webGL.lastIndex; i < graphics.graphicsData.length; i++) { + for (i = webGL.lastIndex; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { // need to add the points the the graphics object.. data.points = data.shape.points.slice(); - if (data.shape.closed) { + if (data.shape.closed) + { // close the poly if the value is true! - if (data.points[0] !== data.points[data.points.length-2] || data.points[1] !== data.points[data.points.length-1]) { + if (data.points[0] !== data.points[data.points.length-2] || data.points[1] !== data.points[data.points.length-1]) + { data.points.push(data.points[0], data.points[1]); } } // MAKE SURE WE HAVE THE CORRECT TYPE.. - if (data.fill) { - if (data.points.length >= 6) { - if (data.points.length < 6 * 2) { + if (data.fill) + { + if (data.points.length >= 6) + { + if (data.points.length < 6 * 2) + { webGLData = WebGLGraphics.switchMode(webGL, 0); var canDrawUsingSimple = WebGLGraphics.buildPoly(data, webGLData); // console.log(canDrawUsingSimple); - if (!canDrawUsingSimple) { + if (!canDrawUsingSimple) + { // console.log("<>>>") webGLData = WebGLGraphics.switchMode(webGL, 1); WebGLGraphics.buildComplexPoly(data, webGLData); } } - else { + else + { webGLData = WebGLGraphics.switchMode(webGL, 1); WebGLGraphics.buildComplexPoly(data, webGLData); } } } - if (data.lineWidth > 0) { + if (data.lineWidth > 0) + { webGLData = WebGLGraphics.switchMode(webGL, 0); WebGLGraphics.buildLine(data, webGLData); } } - else { + else + { webGLData = WebGLGraphics.switchMode(webGL, 0); - if (data.type === CONST.SHAPES.RECT) { + if (data.type === CONST.SHAPES.RECT) + { WebGLGraphics.buildRectangle(data, webGLData); } - else if (data.type === CONST.SHAPES.CIRC || data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.CIRC || data.type === CONST.SHAPES.ELIP) + { WebGLGraphics.buildCircle(data, webGLData); } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { WebGLGraphics.buildRoundedRectangle(data, webGLData); } } @@ -179,10 +202,12 @@ } // upload all the dirty data... - for (i = 0; i < webGL.data.length; i++) { + for (i = 0; i < webGL.data.length; i++) + { webGLData = webGL.data[i]; - if (webGLData.dirty) { + if (webGLData.dirty) + { webGLData.upload(); } } @@ -194,18 +219,22 @@ * @param webGL {WebGLContext} * @param type {number} */ -WebGLGraphics.switchMode = function (webGL, type) { +WebGLGraphics.switchMode = function (webGL, type) +{ var webGLData; - if (!webGL.data.length) { + if (!webGL.data.length) + { webGLData = WebGLGraphics.graphicsDataPool.pop() || new WebGLGraphicsData(webGL.gl); webGLData.mode = type; webGL.data.push(webGLData); } - else { + else + { webGLData = webGL.data[webGL.data.length-1]; - if (webGLData.mode !== type || type === 1) { + if (webGLData.mode !== type || type === 1) + { webGLData = WebGLGraphics.graphicsDataPool.pop() || new WebGLGraphicsData(webGL.gl); webGLData.mode = type; webGL.data.push(webGLData); @@ -225,7 +254,8 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildRectangle = function (graphicsData, webGLData) { +WebGLGraphics.buildRectangle = function (graphicsData, webGLData) +{ // --- // // need to convert points to a nice regular data // @@ -235,7 +265,8 @@ var width = rectData.width; var height = rectData.height; - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -265,7 +296,8 @@ indices.push(vertPos, vertPos, vertPos+1, vertPos+2, vertPos+3, vertPos+3); } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = [x, y, @@ -289,7 +321,8 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildRoundedRectangle = function (graphicsData, webGLData) { +WebGLGraphics.buildRoundedRectangle = function (graphicsData, webGLData) +{ var rrectData = graphicsData.shape; var x = rrectData.x; var y = rrectData.y; @@ -305,7 +338,8 @@ recPoints = recPoints.concat(WebGLGraphics.quadraticBezierCurve(x + width, y + radius, x + width, y, x + width - radius, y)); recPoints = recPoints.concat(WebGLGraphics.quadraticBezierCurve(x + radius, y, x, y, x, y + radius)); - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -323,7 +357,8 @@ // var i = 0; - for (i = 0; i < triangles.length; i+=3) { + for (i = 0; i < triangles.length; i+=3) + { indices.push(triangles[i] + vecPos); indices.push(triangles[i] + vecPos); indices.push(triangles[i+1] + vecPos); @@ -332,12 +367,14 @@ } - for (i = 0; i < recPoints.length; i++) { + for (i = 0; i < recPoints.length; i++) + { verts.push(recPoints[i], recPoints[++i], r, g, b, alpha); } } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = recPoints; @@ -362,7 +399,8 @@ * @param toY {number} Destination point y * @return {number[]} */ -WebGLGraphics.quadraticBezierCurve = function (fromX, fromY, cpX, cpY, toX, toY) { +WebGLGraphics.quadraticBezierCurve = function (fromX, fromY, cpX, cpY, toX, toY) +{ var xa, ya, @@ -373,14 +411,16 @@ n = 20, points = []; - function getPt(n1 , n2, perc) { + function getPt(n1 , n2, perc) + { var diff = n2 - n1; return n1 + ( diff * perc ); } var j = 0; - for (var i = 0; i <= n; i++ ) { + for (var i = 0; i <= n; i++ ) + { j = i / n; // The Green Line @@ -406,7 +446,8 @@ * @param graphicsData {Graphics} The graphics object to draw * @param webGLData {object} */ -WebGLGraphics.buildCircle = function (graphicsData, webGLData) { +WebGLGraphics.buildCircle = function (graphicsData, webGLData) +{ // need to convert points to a nice regular data var circleData = graphicsData.shape; var x = circleData.x; @@ -415,11 +456,13 @@ var height; // TODO - bit hacky?? - if (graphicsData.type === CONST.SHAPES.CIRC) { + if (graphicsData.type === CONST.SHAPES.CIRC) + { width = circleData.radius; height = circleData.radius; } - else { + else + { width = circleData.width; height = circleData.height; } @@ -429,7 +472,8 @@ var i = 0; - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -444,7 +488,8 @@ indices.push(vecPos); - for (i = 0; i < totalSegs + 1 ; i++) { + for (i = 0; i < totalSegs + 1 ; i++) + { verts.push(x,y, r, g, b, alpha); verts.push(x + Math.sin(seg * i) * width, @@ -457,12 +502,14 @@ indices.push(vecPos-1); } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = []; - for (i = 0; i < totalSegs + 1; i++) { + for (i = 0; i < totalSegs + 1; i++) + { graphicsData.points.push(x + Math.sin(seg * i) * width, y + Math.cos(seg * i) * height); } @@ -481,18 +528,22 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildLine = function (graphicsData, webGLData) { +WebGLGraphics.buildLine = function (graphicsData, webGLData) +{ // TODO OPTIMISE! var i = 0; var points = graphicsData.points; - if (points.length === 0) { + if (points.length === 0) + { return; } // if the line width is an odd number add 0.5 to align to a whole pixel - if (graphicsData.lineWidth%2) { - for (i = 0; i < points.length; i++) { + if (graphicsData.lineWidth%2) + { + for (i = 0; i < points.length; i++) + { points[i] += 0.5; } } @@ -502,7 +553,8 @@ var lastPoint = new math.Point(points[points.length - 2], points[points.length - 1]); // if the first point is the last point - gonna have issues :) - if (firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) { + if (firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) + { // need to clone as we are going to slightly modify the shape.. points = points.slice(); @@ -562,7 +614,8 @@ verts.push(p1x + perpx , p1y + perpy, r, g, b, alpha); - for (i = 1; i < length-1; i++) { + for (i = 1; i < length-1; i++) + { p1x = points[(i-1)*2]; p1y = points[(i-1)*2 + 1]; @@ -599,7 +652,8 @@ denom = a1*b2 - a2*b1; - if (Math.abs(denom) < 0.1 ) { + if (Math.abs(denom) < 0.1 ) + { denom+=10.1; verts.push(p2x - perpx , p2y - perpy, @@ -618,7 +672,8 @@ pdist = (px -p2x) * (px -p2x) + (py -p2y) + (py -p2y); - if (pdist > 140 * 140) { + if (pdist > 140 * 140) + { perp3x = perpx - perp2x; perp3y = perpy - perp2y; @@ -639,7 +694,8 @@ indexCount++; } - else { + else + { verts.push(px , py); verts.push(r, g, b, alpha); @@ -672,7 +728,8 @@ indices.push(indexStart); - for (i = 0; i < indexCount; i++) { + for (i = 0; i < indexCount; i++) + { indices.push(indexStart++); } @@ -687,11 +744,13 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildComplexPoly = function (graphicsData, webGLData) { +WebGLGraphics.buildComplexPoly = function (graphicsData, webGLData) +{ //TODO - no need to copy this as it gets turned into a FLoat32Array anyways.. var points = graphicsData.points.slice(); - if (points.length < 6) { + if (points.length < 6) + { return; } @@ -711,7 +770,8 @@ var x,y; // get size.. - for (var i = 0; i < points.length; i+=2) { + for (var i = 0; i < points.length; i+=2) + { x = points[i]; y = points[i+1]; @@ -732,7 +792,8 @@ //TODO - this aint needed! var length = points.length / 2; - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { indices.push( i ); } @@ -746,10 +807,12 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildPoly = function (graphicsData, webGLData) { +WebGLGraphics.buildPoly = function (graphicsData, webGLData) +{ var points = graphicsData.points; - if (points.length < 6) { + if (points.length < 6) + { return; } // get first and last point.. figure out the middle! @@ -767,7 +830,8 @@ var triangles = utils.PolyK.Triangulate(points); - if (!triangles) { + if (!triangles) + { return false; } @@ -775,7 +839,8 @@ var i = 0; - for (i = 0; i < triangles.length; i+=3) { + for (i = 0; i < triangles.length; i+=3) + { indices.push(triangles[i] + vertPos); indices.push(triangles[i] + vertPos); indices.push(triangles[i+1] + vertPos); @@ -783,7 +848,8 @@ indices.push(triangles[i+2] + vertPos); } - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { verts.push(points[i * 2], points[i * 2 + 1], r, g, b, alpha); } diff --git a/src/core/renderers/webgl/utils/WebGLGraphicsData.js b/src/core/renderers/webgl/utils/WebGLGraphicsData.js index c56d05e..c739ba7 100644 --- a/src/core/renderers/webgl/utils/WebGLGraphicsData.js +++ b/src/core/renderers/webgl/utils/WebGLGraphicsData.js @@ -2,7 +2,8 @@ * @class * @private */ -function WebGLGraphicsData(gl) { +function WebGLGraphicsData(gl) +{ this.gl = gl; //TODO does this need to be split before uploding?? @@ -22,7 +23,8 @@ /** * */ -WebGLGraphicsData.prototype.reset = function () { +WebGLGraphicsData.prototype.reset = function () +{ this.points.length = 0; this.indices.length = 0; }; @@ -30,7 +32,8 @@ /** * */ -WebGLGraphicsData.prototype.upload = function () { +WebGLGraphicsData.prototype.upload = function () +{ var gl = this.gl; // this.lastIndex = graphics.graphicsData.length; diff --git a/src/core/renderers/webgl/utils/WebGLSpriteBatch.js b/src/core/renderers/webgl/utils/WebGLSpriteBatch.js index 96eaa52..55befbb 100644 --- a/src/core/renderers/webgl/utils/WebGLSpriteBatch.js +++ b/src/core/renderers/webgl/utils/WebGLSpriteBatch.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this sprite batch works for. */ -function WebGLSpriteBatch(renderer) { +function WebGLSpriteBatch(renderer) +{ /** * * @@ -88,7 +89,8 @@ */ this.lastIndexCount = 0; - for (var i=0, j=0; i < numIndices; i += 6, j += 4) { + 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; @@ -162,7 +164,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.setupContext(); }); } @@ -173,7 +176,8 @@ /** * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLSpriteBatch.prototype.setupContext = function () { +WebGLSpriteBatch.prototype.setupContext = function () +{ var gl = this.renderer.gl; // setup default shader @@ -198,7 +202,8 @@ /** * */ -WebGLSpriteBatch.prototype.begin = function () { +WebGLSpriteBatch.prototype.begin = function () +{ // this.shader = this.renderer.shaderManager.defaultShader; this.start(); @@ -206,19 +211,22 @@ /** */ -WebGLSpriteBatch.prototype.end = function () { +WebGLSpriteBatch.prototype.end = function () +{ this.flush(); }; /** * @param sprite {Sprite} the sprite to render when using this spritebatch */ -WebGLSpriteBatch.prototype.render = function (sprite) { +WebGLSpriteBatch.prototype.render = function (sprite) +{ var texture = sprite.texture; //TODO set blend modes.. // check texture.. - if (this.currentBatchSize >= this.size) { + if (this.currentBatchSize >= this.size) + { this.flush(); this.currentBaseTexture = texture.baseTexture; } @@ -227,7 +235,8 @@ var uvs = texture._uvs; // if the uvs have not updated then no point rendering just yet! - if (!uvs) { + if (!uvs) + { return; } @@ -237,7 +246,8 @@ var w0, w1, h0, h1; - if (texture.trim) { + 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; @@ -248,7 +258,8 @@ h0 = h1 + texture.crop.height; } - else { + else + { w0 = (texture.frame.width ) * (1-aX); w1 = (texture.frame.width ) * -aX; @@ -272,7 +283,8 @@ var colors = this.colors; var positions = this.positions; - if (this.renderer.roundPixels) { + if (this.renderer.roundPixels) + { // xy positions[index] = a * w1 + c * h1 + tx | 0; positions[index+1] = d * h1 + b * w1 + ty | 0; @@ -289,7 +301,8 @@ positions[index+15] = a * w1 + c * h0 + tx | 0; positions[index+16] = d * h0 + b * w1 + ty | 0; } - else { + else + { // xy positions[index] = a * w1 + c * h1 + tx; positions[index+1] = d * h1 + b * w1 + ty; @@ -338,11 +351,13 @@ * * @param sprite {TilingSprite} the tilingSprite to render */ -WebGLSpriteBatch.prototype.renderTilingSprite = function (tilingSprite) { +WebGLSpriteBatch.prototype.renderTilingSprite = function (tilingSprite) +{ var texture = tilingSprite.tilingTexture; // check texture.. - if (this.currentBatchSize >= this.size) { + if (this.currentBatchSize >= this.size) + { //return; this.flush(); this.currentBaseTexture = texture.baseTexture; @@ -351,7 +366,8 @@ // set the textures uvs temporarily // TODO create a separate texture so that we can tile part of a texture - if (!tilingSprite._uvs) { + if (!tilingSprite._uvs) + { tilingSprite._uvs = new TextureUvs(); } @@ -454,16 +470,19 @@ * Renders the content and empties the current batch. * */ -WebGLSpriteBatch.prototype.flush = function () { +WebGLSpriteBatch.prototype.flush = function () +{ // If the batch is length 0 then return as there is nothing to draw - if (this.currentBatchSize === 0) { + if (this.currentBatchSize === 0) + { return; } var gl = this.renderer.gl; var shader; - if (this.dirty) { + if (this.dirty) + { this.dirty = false; // bind the main texture gl.activeTexture(gl.TEXTURE0); @@ -482,10 +501,12 @@ } // upload the verts to the buffer - if (this.currentBatchSize > ( this.size * 0.5 ) ) { + if (this.currentBatchSize > ( this.size * 0.5 ) ) + { gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); } - else { + else + { var view = this.positions.subarray(0, this.currentBatchSize * this.vertByteSize); gl.bufferSubData(gl.ARRAY_BUFFER, 0, view); } @@ -502,7 +523,8 @@ var shaderSwap = false; var sprite; - for (var i = 0, j = this.currentBatchSize; i < j; i++) { + for (var i = 0, j = this.currentBatchSize; i < j; i++) + { sprite = this.sprites[i]; @@ -513,24 +535,28 @@ blendSwap = currentBlendMode !== nextBlendMode; shaderSwap = currentShader !== nextShader; // should I use uuidS??? - if (currentBaseTexture !== nextTexture || blendSwap || shaderSwap) { + if (currentBaseTexture !== nextTexture || blendSwap || shaderSwap) + { this.renderBatch(currentBaseTexture, batchSize, start); start = i; batchSize = 0; currentBaseTexture = nextTexture; - if (blendSwap) { + if (blendSwap) + { currentBlendMode = nextBlendMode; this.renderer.blendModeManager.setBlendMode( currentBlendMode ); } - if (shaderSwap) { + if (shaderSwap) + { currentShader = nextShader; shader = currentShader.shaders ? currentShader.shaders[gl.id] : currentShader; - if (!shader) { + if (!shader) + { shader = new Shader(gl, null, currentShader.fragmentSrc, currentShader.uniforms); currentShader.shaders[gl.id] = shader; } @@ -538,7 +564,8 @@ // set shader function??? this.renderer.shaderManager.setShader(shader); - if (shader.dirty) { + if (shader.dirty) + { shader.syncUniforms(); } @@ -569,17 +596,21 @@ * @param size {number} * @param startIndex {number} */ -WebGLSpriteBatch.prototype.renderBatch = function (texture, size, startIndex) { - if (size === 0) { +WebGLSpriteBatch.prototype.renderBatch = function (texture, size, startIndex) +{ + if (size === 0) + { return; } var gl = this.renderer.gl; - if (!texture._glTextures[gl.id]) { + if (!texture._glTextures[gl.id]) + { this.renderer.updateTexture(texture); } - else { + else + { // bind the current texture gl.bindTexture(gl.TEXTURE_2D, texture._glTextures[gl.id]); } @@ -594,7 +625,8 @@ /** * */ -WebGLSpriteBatch.prototype.stop = function () { +WebGLSpriteBatch.prototype.stop = function () +{ this.flush(); this.dirty = true; }; @@ -602,7 +634,8 @@ /** * */ -WebGLSpriteBatch.prototype.start = function () { +WebGLSpriteBatch.prototype.start = function () +{ this.dirty = true; }; @@ -610,7 +643,8 @@ * Destroys the SpriteBatch. * */ -WebGLSpriteBatch.prototype.destroy = function () { +WebGLSpriteBatch.prototype.destroy = function () +{ this.renderer.gl.deleteBuffer(this.vertexBuffer); this.renderer.gl.deleteBuffer(this.indexBuffer); diff --git a/src/core/textures/BaseTexture.js b/src/core/textures/BaseTexture.js index 2bf77d4..513d358 100644 --- a/src/core/textures/BaseTexture.js +++ b/src/core/textures/BaseTexture.js @@ -10,7 +10,8 @@ * @param source {Image|Canvas} the source object of the texture. * @param [scaleMode=scaleModes.DEFAULT] {number} See {@link scaleModes} for possible values */ -function BaseTexture(source, scaleMode) { +function BaseTexture(source, scaleMode) +{ this.uuid = utils.uuid(); /** @@ -123,7 +124,8 @@ this._needsUpdate = false; // if no source passed don't try to load - if (source) { + if (source) + { this.loadSource(source); } @@ -149,13 +151,16 @@ Object.defineProperties(BaseTexture.prototype, { needsUpdate: { - get: function () { + get: function () + { return this._needsUpdate; }, - set: function (val) { + set: function (val) + { this._needsUpdate = val; - if (val) { + if (val) + { this.emit('update', this); } } @@ -171,9 +176,11 @@ * * The logic state after calling `loadSource` directly or indirectly (eg. `fromImage`, `new BaseTexture`) is: * - * if (texture.hasLoaded) { + * if (texture.hasLoaded) + { * // texture ready for use - * } else if (texture.isLoading) { + * } else if (texture.isLoading) + { * // listen to 'loaded' and/or 'error' events on texture * } else { * // not loading, not going to load UNLESS the source is reloaded @@ -183,12 +190,14 @@ * @protected * @param source {Image|Canvas} the source object of the texture. */ -BaseTexture.prototype.loadSource = function (source) { +BaseTexture.prototype.loadSource = function (source) +{ var wasLoading = this.isLoading; this.hasLoaded = false; this.isLoading = false; - if (wasLoading && this.source) { + if (wasLoading && this.source) + { this.source.onload = null; this.source.onerror = null; } @@ -196,20 +205,24 @@ this.source = source; // Apply source if loaded. Otherwise setup appropriate loading monitors. - if ((this.source.complete || this.source.getContext) && this.source.width && this.source.height) { + if ((this.source.complete || this.source.getContext) && this.source.width && this.source.height) + { this._sourceLoaded(); } - else if(!source.getContext) { + else if(!source.getContext) + { // Image fail / not ready this.isLoading = true; var scope = this; - source.onload = function () { + source.onload = function () + { source.onload = null; source.onerror = null; - if(!scope.isLoading) { + if(!scope.isLoading) + { return; } @@ -219,11 +232,13 @@ scope.emit('loaded', scope); }; - source.onerror = function () { + source.onerror = function () + { source.onload = null; source.onerror = null; - if(!scope.isLoading) { + if(!scope.isLoading) + { return; } @@ -234,24 +249,29 @@ // Per http://www.w3.org/TR/html5/embedded-content-0.html#the-img-element // "The value of `complete` can thus change while a script is executing." // So complete needs to be re-checked after the callbacks have been added.. - if (source.complete) { + if (source.complete) + { this.isLoading = false; // ..and if we're complete now, no need for callbacks source.onload = null; source.onerror = null; - if (source.width && source.height) { + if (source.width && source.height) + { this._sourceLoaded(); // If any previous subscribers possible - if (wasLoading) { + if (wasLoading) + { this.emit('loaded', this); } } - else { + else + { // If any previous subscribers possible - if (wasLoading) { + if (wasLoading) + { this.emit('error', this); } } @@ -265,7 +285,8 @@ * * @private */ -BaseTexture.prototype._sourceLoaded = function () { +BaseTexture.prototype._sourceLoaded = function () +{ this.hasLoaded = true; this.width = this.source.naturalWidth || this.source.width; @@ -278,16 +299,20 @@ * Destroys this base texture * */ -BaseTexture.prototype.destroy = function () { - if (this.imageUrl) { +BaseTexture.prototype.destroy = function () +{ + if (this.imageUrl) + { delete utils.BaseTextureCache[this.imageUrl]; delete utils.TextureCache[this.imageUrl]; this.imageUrl = null; - if (!navigator.isCocoonJS) { + if (!navigator.isCocoonJS) + { this.source.src = ''; } } - else if (this.source && this.source._pixiId) { + else if (this.source && this.source._pixiId) + { delete utils.BaseTextureCache[this.source._pixiId]; } this.source = null; @@ -301,7 +326,8 @@ * memory again. * */ -BaseTexture.prototype.dispose = function () { +BaseTexture.prototype.dispose = function () +{ this.emit('dispose', this); }; @@ -311,7 +337,8 @@ * * @param newSrc {string} the path of the image */ -BaseTexture.prototype.updateSourceImage = function (newSrc) { +BaseTexture.prototype.updateSourceImage = function (newSrc) +{ this.source.src = newSrc; this.loadSource(this.source); }; @@ -326,18 +353,22 @@ * @param [scaleMode=scaleModes.DEFAULT] {number} See {@link scaleModes} for possible values * @return BaseTexture */ -BaseTexture.fromImage = function (imageUrl, crossorigin, scaleMode) { +BaseTexture.fromImage = function (imageUrl, crossorigin, scaleMode) +{ var baseTexture = utils.BaseTextureCache[imageUrl]; - if (crossorigin === undefined && imageUrl.indexOf('data:') !== 0) { + if (crossorigin === undefined && imageUrl.indexOf('data:') !== 0) + { crossorigin = true; } - if (!baseTexture) { + if (!baseTexture) + { // new Image() breaks tex loading in some versions of Chrome. // See https://code.google.com/p/chromium/issues/detail?id=238071 var image = new Image();//document.createElement('img'); - if (crossorigin) { + if (crossorigin) + { image.crossOrigin = ''; } @@ -347,7 +378,8 @@ utils.BaseTextureCache[imageUrl] = baseTexture; // if there is an @2x at the end of the url we are going to assume its a highres image - if ( imageUrl.indexOf(CONST.RETINA_PREFIX + '.') !== -1) { + if ( imageUrl.indexOf(CONST.RETINA_PREFIX + '.') !== -1) + { baseTexture.resolution = 2; } } @@ -363,14 +395,17 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return BaseTexture */ -BaseTexture.fromCanvas = function (canvas, scaleMode) { - if (!canvas._pixiId) { +BaseTexture.fromCanvas = function (canvas, scaleMode) +{ + if (!canvas._pixiId) + { canvas._pixiId = 'canvas_' + utils.uuid(); } var baseTexture = utils.BaseTextureCache[canvas._pixiId]; - if (!baseTexture) { + if (!baseTexture) + { baseTexture = new BaseTexture(canvas, scaleMode); utils.BaseTextureCache[canvas._pixiId] = baseTexture; } diff --git a/src/core/textures/RenderTexture.js b/src/core/textures/RenderTexture.js index 6dad20f..53ae796 100644 --- a/src/core/textures/RenderTexture.js +++ b/src/core/textures/RenderTexture.js @@ -46,8 +46,10 @@ * @param [scaleMode] {number} See {@link scaleModes} for possible values * @param [resolution=1] {number} The resolution of the texture being generated */ -function RenderTexture(renderer, width, height, scaleMode, resolution) { - if (!renderer) { +function RenderTexture(renderer, width, height, scaleMode, resolution) +{ + if (!renderer) + { throw new Error('Unable to create RenderTexture, you must pass a renderer into the constructor.'); } @@ -133,7 +135,8 @@ */ this.renderer = renderer; - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { var gl = this.renderer.gl; this.textureBuffer = new FilterTexture(gl, this.width * this.resolution, this.height * this.resolution, this.baseTexture.scaleMode); @@ -142,7 +145,8 @@ this.render = this.renderWebGL; this.projection = new math.Point(this.width*0.5, -this.height*0.5); } - else { + else + { this.render = this.renderCanvas; this.textureBuffer = new CanvasBuffer(this.width* this.resolution, this.height* this.resolution); this.baseTexture.source = this.textureBuffer.canvas; @@ -167,8 +171,10 @@ * @param height {number} The height to resize to. * @param updateBase {boolean} Should the baseTexture.width and height values be resized as well? */ -RenderTexture.prototype.resize = function (width, height, updateBase) { - if (width === this.width && height === this.height) { +RenderTexture.prototype.resize = function (width, height, updateBase) +{ + if (width === this.width && height === this.height) + { return; } @@ -177,17 +183,20 @@ this.width = this.frame.width = this.crop.width = width; this.height = this.frame.height = this.crop.height = height; - if (updateBase) { + if (updateBase) + { this.baseTexture.width = this.width; this.baseTexture.height = this.height; } - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { this.projection.x = this.width / 2; this.projection.y = -this.height / 2; } - if (!this.valid) { + if (!this.valid) + { return; } @@ -198,12 +207,15 @@ * Clears the RenderTexture. * */ -RenderTexture.prototype.clear = function () { - if (!this.valid) { +RenderTexture.prototype.clear = function () +{ + if (!this.valid) + { return; } - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { this.renderer.gl.bindFramebuffer(this.renderer.gl.FRAMEBUFFER, this.textureBuffer.frameBuffer); } @@ -220,19 +232,23 @@ * @param [restoreWorldTransform=true] {boolean} If true the displayObject's worldTransform/worldAlpha and all children * transformations will be restored. Not restoring this information will be a little faster. */ -RenderTexture.prototype.renderWebGL = function (displayObject, matrix, clear, restoreWorldTransform) { - if (!this.valid) { +RenderTexture.prototype.renderWebGL = function (displayObject, matrix, clear, restoreWorldTransform) +{ + if (!this.valid) + { return; } - if (typeof restoreWorldTransform === 'undefined') { + if (typeof restoreWorldTransform === 'undefined') + { restoreWorldTransform = true; } var tempAlpha, tempTransform; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { tempAlpha = displayObject.worldAlpha; tempTransform = displayObject.worldTransform.toArray(); } @@ -245,7 +261,8 @@ wt.identity(); wt.translate(0, this.projection.y * 2); - if (matrix) { + if (matrix) + { wt.append(matrix); } @@ -258,7 +275,8 @@ var children = displayObject.children; var i, j; - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } @@ -269,7 +287,8 @@ gl.bindFramebuffer(gl.FRAMEBUFFER, this.textureBuffer.frameBuffer ); - if (clear) { + if (clear) + { this.textureBuffer.clear(); } @@ -279,11 +298,13 @@ this.renderer.spriteBatch.dirty = true; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { displayObject.worldAlpha = tempAlpha; displayObject.worldTransform.fromArray(tempTransform); - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } } @@ -300,26 +321,31 @@ * @param [restoreWorldTransform=true] {boolean} If true the displayObject's worldTransform/worldAlpha and all children * transformations will be restored. Not restoring this information will be a little faster. */ -RenderTexture.prototype.renderCanvas = function (displayObject, matrix, clear, restoreWorldTransform) { - if (!this.valid) { +RenderTexture.prototype.renderCanvas = function (displayObject, matrix, clear, restoreWorldTransform) +{ + if (!this.valid) + { return; } - if (typeof restoreWorldTransform === 'undefined') { + if (typeof restoreWorldTransform === 'undefined') + { restoreWorldTransform = true; } var tempAlpha, tempTransform; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { tempAlpha = displayObject.worldAlpha; tempTransform = displayObject.worldTransform.toArray(); } var wt = displayObject.worldTransform; wt.identity(); - if (matrix) { + if (matrix) + { wt.append(matrix); } @@ -330,11 +356,13 @@ var children = displayObject.children; var i, j; - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } - if (clear) { + if (clear) + { this.textureBuffer.clear(); } @@ -348,11 +376,13 @@ this.renderer.resolution = realResolution; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { displayObject.worldAlpha = tempAlpha; displayObject.worldTransform.fromArray(tempTransform); - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } } @@ -363,7 +393,8 @@ * * @return {Image} */ -RenderTexture.prototype.getImage = function () { +RenderTexture.prototype.getImage = function () +{ var image = new Image(); image.src = this.getBase64(); return image; @@ -374,7 +405,8 @@ * * @return {string} A base64 encoded string of the texture. */ -RenderTexture.prototype.getBase64 = function () { +RenderTexture.prototype.getBase64 = function () +{ return this.getCanvas().toDataURL(); }; @@ -383,8 +415,10 @@ * * @return {HTMLCanvasElement} A Canvas element with the texture rendered on. */ -RenderTexture.prototype.getCanvas = function () { - if (this.renderer.type === CONST.WEBGL_RENDERER) { +RenderTexture.prototype.getCanvas = function () +{ + if (this.renderer.type === CONST.WEBGL_RENDERER) + { var gl = this.renderer.gl; var width = this.textureBuffer.width; var height = this.textureBuffer.height; @@ -403,7 +437,8 @@ return tempCanvas.canvas; } - else { + else + { return this.textureBuffer.canvas; } }; diff --git a/src/core/textures/Texture.js b/src/core/textures/Texture.js index 3c65909..e97f0aa 100644 --- a/src/core/textures/Texture.js +++ b/src/core/textures/Texture.js @@ -17,7 +17,8 @@ * @param [crop] {Rectangle} The area of original texture * @param [trim] {Rectangle} Trimmed texture rectangle */ -function Texture(baseTexture, frame, crop, trim) { +function Texture(baseTexture, frame, crop, trim) +{ /** * Does this Texture have any frame data assigned to it? * @@ -25,12 +26,14 @@ */ this.noFrame = false; - if (!frame) { + if (!frame) + { this.noFrame = true; frame = new math.Rectangle(0, 0, 1, 1); } - if (baseTexture instanceof Texture) { + if (baseTexture instanceof Texture) + { baseTexture = baseTexture.baseTexture; } @@ -100,13 +103,16 @@ */ this.crop = crop || new math.Rectangle(0, 0, 1, 1); - if (baseTexture.hasLoaded) { - if (this.noFrame) { + if (baseTexture.hasLoaded) + { + if (this.noFrame) + { frame = new math.Rectangle(0, 0, baseTexture.width, baseTexture.height); } this.frame = frame; } - else { + else + { baseTexture.addEventListener('loaded', this.onBaseTextureLoaded.bind(this)); } } @@ -118,19 +124,23 @@ Object.defineProperties(Texture.prototype, { needsUpdate: { - get: function () { + get: function () + { return this.baseTexture.needsUpdate; }, - set: function (val) { + set: function (val) + { this.baseTexture.needsUpdate = val; } }, frame: { - get: function () { + get: function () + { return this._frame; }, - set: function (frame) { + set: function (frame) + { this._frame = frame; this.noFrame = false; @@ -143,20 +153,23 @@ 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 (!this.trim && (frame.x + frame.width > this.baseTexture.width || frame.y + frame.height > this.baseTexture.height)) + { throw new Error('Texture Error: frame does not fit inside the base Texture dimensions ' + this); } this.valid = frame && frame.width && frame.height && this.baseTexture.source && this.baseTexture.hasLoaded; - if (this.trim) { + 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) { + if (this.valid) + { this._updateUvs(); } } @@ -168,11 +181,13 @@ * * @private */ -Texture.prototype.onBaseTextureLoaded = function () { +Texture.prototype.onBaseTextureLoaded = function () +{ var baseTexture = this.baseTexture; baseTexture.removeEventListener('loaded', this.onLoaded); - if (this.noFrame) { + if (this.noFrame) + { this.frame = new math.Rectangle(0, 0, baseTexture.width, baseTexture.height); } @@ -184,8 +199,10 @@ * * @param destroyBase {boolean} Whether to destroy the base texture as well */ -Texture.prototype.destroy = function (destroyBase) { - if (destroyBase) { +Texture.prototype.destroy = function (destroyBase) +{ + if (destroyBase) + { this.baseTexture.destroy(); } @@ -197,8 +214,10 @@ * * @private */ -Texture.prototype._updateUvs = function () { - if (!this._uvs) { +Texture.prototype._updateUvs = function () +{ + if (!this._uvs) + { this._uvs = new TextureUvs(); } @@ -229,10 +248,12 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return Texture */ -Texture.fromImage = function (imageUrl, crossorigin, scaleMode) { +Texture.fromImage = function (imageUrl, crossorigin, scaleMode) +{ var texture = utils.TextureCache[imageUrl]; - if (!texture) { + if (!texture) + { texture = new Texture(BaseTexture.fromImage(imageUrl, crossorigin, scaleMode)); utils.TextureCache[imageUrl] = texture; } @@ -248,9 +269,11 @@ * @param frameId {string} The frame id of the texture * @return Texture */ -Texture.fromFrame = function (frameId) { +Texture.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache '); } return texture; @@ -264,7 +287,8 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return {Texture} */ -Texture.fromCanvas = function (canvas, scaleMode) { +Texture.fromCanvas = function (canvas, scaleMode) +{ return new Texture(BaseTexture.fromCanvas(canvas, scaleMode)); }; @@ -276,7 +300,8 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return {Texture} A Texture */ -Texture.fromVideo = function (video, scaleMode) { +Texture.fromVideo = function (video, scaleMode) +{ return new Texture(VideoBaseTexture.baseTextureFromVideo(video, scaleMode)); }; @@ -287,7 +312,8 @@ * @param texture {Texture} The Texture to add to the cache. * @param id {string} The id that the texture will be stored against. */ -Texture.addTextureToCache = function (texture, id) { +Texture.addTextureToCache = function (texture, id) +{ utils.TextureCache[id] = texture; }; @@ -298,7 +324,8 @@ * @param id {string} The id of the texture to be removed * @return {Texture} The texture that was removed */ -Texture.removeTextureFromCache = function (id) { +Texture.removeTextureFromCache = function (id) +{ var texture = utils.TextureCache[id]; delete utils.TextureCache[id]; diff --git a/src/core/textures/TextureUvs.js b/src/core/textures/TextureUvs.js index b9bbb58..5424d52 100644 --- a/src/core/textures/TextureUvs.js +++ b/src/core/textures/TextureUvs.js @@ -1,4 +1,5 @@ -function TextureUvs() { +function TextureUvs() +{ this.x0 = 0; this.y0 = 0; diff --git a/src/core/textures/VideoBaseTexture.js b/src/core/textures/VideoBaseTexture.js index e3e0c5a..1a826a9 100644 --- a/src/core/textures/VideoBaseTexture.js +++ b/src/core/textures/VideoBaseTexture.js @@ -12,15 +12,18 @@ * @param source {HTMLVideoElement} * @param [scaleMode] {number} See {@link scaleModes} for possible values */ -function VideoBaseTexture(source, scaleMode) { - if (!source){ +function VideoBaseTexture(source, scaleMode) +{ + if (!source) + { throw new Error('No video source element specified.'); } // hook in here to check if video is already available. // BaseTexture looks for a source.complete boolean, plus width & height. - if ((source.readyState === source.HAVE_ENOUGH_DATA || source.readyState === source.HAVE_FUTURE_DATA) && source.width && source.height) { + if ((source.readyState === source.HAVE_ENOUGH_DATA || source.readyState === source.HAVE_FUTURE_DATA) && source.width && source.height) + { source.complete = true; } @@ -31,7 +34,8 @@ this._boundOnUpdate = this._onUpdate.bind(this); this._boundOnCanPlay = this._onCanPlay.bind(this); - if (!source.complete) { + if (!source.complete) + { source.addEventListener('canplay', this._boundOnCanPlay); source.addEventListener('canplaythrough', this._boundOnCanPlay); @@ -47,28 +51,35 @@ VideoBaseTexture.prototype.constructor = VideoBaseTexture; module.exports = VideoBaseTexture; -VideoBaseTexture.prototype._onUpdate = function () { - if (this.autoUpdate) { +VideoBaseTexture.prototype._onUpdate = function () +{ + if (this.autoUpdate) + { window.requestAnimationFrame(this._boundOnUpdate); this.needsUpdate = true; } }; -VideoBaseTexture.prototype._onPlayStart = function () { - if (!this.autoUpdate) { +VideoBaseTexture.prototype._onPlayStart = function () +{ + if (!this.autoUpdate) + { window.requestAnimationFrame(this._boundOnUpdate); this.autoUpdate = true; } }; -VideoBaseTexture.prototype._onPlayStop = function () { +VideoBaseTexture.prototype._onPlayStop = function () +{ this.autoUpdate = false; }; -VideoBaseTexture.prototype._onCanPlay = function () { +VideoBaseTexture.prototype._onCanPlay = function () +{ this.hasLoaded = true; - if (this.source) { + if (this.source) + { this.source.removeEventListener('canplay', this._boundOnCanPlay); this.source.removeEventListener('canplaythrough', this._boundOnCanPlay); @@ -78,15 +89,18 @@ this.source.play(); // prevent multiple loaded dispatches.. - if(!this.__loaded){ + if(!this.__loaded) + { this.__loaded = true; this.emit('loaded', this); } } }; -VideoBaseTexture.prototype.destroy = function () { - if (this.source && this.source._pixiId) { +VideoBaseTexture.prototype.destroy = function () +{ + if (this.source && this.source._pixiId) + { utils.BaseTextureCache[ this.source._pixiId ] = null; delete utils.BaseTextureCache[ this.source._pixiId ]; @@ -105,14 +119,17 @@ * @param scaleMode {number} See {@link scaleModes} for possible values * @return {VideoBaseTexture} */ -VideoBaseTexture.fromVideo = function (video, scaleMode) { - if (!video._pixiId) { +VideoBaseTexture.fromVideo = function (video, scaleMode) +{ + if (!video._pixiId) + { video._pixiId = 'video_' + utils.uuid(); } var baseTexture = utils.BaseTextureCache[video._pixiId]; - if (!baseTexture) { + if (!baseTexture) + { baseTexture = new VideoBaseTexture(video, scaleMode); utils.BaseTextureCache[ video._pixiId ] = baseTexture; } @@ -147,17 +164,21 @@ * @param scaleMode {number} See {@link scaleModes} for possible values * @return {VideoBaseTexture} */ -VideoBaseTexture.fromUrl = function (videoSrc, scaleMode) { +VideoBaseTexture.fromUrl = function (videoSrc, scaleMode) +{ var video = document.createElement('video'); // array of objects or strings - if (Array.isArray(videoSrc)) { - for (var i = 0; i < videoSrc.length; ++i) { + if (Array.isArray(videoSrc)) + { + for (var i = 0; i < videoSrc.length; ++i) + { video.appendChild(createSource(videoSrc.src || videoSrc, videoSrc.mime)); } } // single object or string - else { + else + { video.appendChild(createSource(videoSrc.src || videoSrc, videoSrc.mime)); } @@ -169,8 +190,10 @@ VideoBaseTexture.fromUrls = VideoBaseTexture.fromUrl; -function createSource(path, type) { - if (!type) { +function createSource(path, type) +{ + if (!type) + { type = 'video/' + path.substr(path.lastIndexOf('.') + 1); } diff --git a/src/core/utils/EventData.js b/src/core/utils/EventData.js index 5d55a22..8cdf701 100644 --- a/src/core/utils/EventData.js +++ b/src/core/utils/EventData.js @@ -7,7 +7,8 @@ * @param name {string} The string name of the event that was triggered * @param data {object} Arbitrary event data to pass along */ -function EventData(target, name, data) { +function EventData(target, name, data) +{ // for duck typing in the ".on()" function this.__isEventObject = true; @@ -71,7 +72,8 @@ * Stops the propagation of events up the scene graph (prevents bubbling). * */ -EventData.prototype.stopPropagation = function stopPropagation() { +EventData.prototype.stopPropagation = function stopPropagation() +{ this.stopped = true; }; @@ -79,6 +81,7 @@ * Stops the propagation of events to sibling listeners (no longer calls any listeners). * */ -EventData.prototype.stopImmediatePropagation = function stopImmediatePropagation() { +EventData.prototype.stopImmediatePropagation = function stopImmediatePropagation() +{ this.stoppedImmediate = true; }; diff --git a/src/core/utils/EventTarget.js b/src/core/utils/EventTarget.js index 7ae8820..671a151 100644 --- a/src/core/utils/EventTarget.js +++ b/src/core/utils/EventTarget.js @@ -13,14 +13,16 @@ * var em = new MyEmitter(); * em.emit('eventName', 'some data', 'some more data', {}, null, ...); */ -function eventTarget(obj) { +function eventTarget(obj) +{ /** * Return a list of assigned event listeners. * * @param eventName {string} The events that should be listed. * @return {Array} An array of listener functions */ - obj.listeners = function listeners(eventName) { + obj.listeners = function listeners(eventName) + { this._listeners = this._listeners || {}; return this._listeners[eventName] ? this._listeners[eventName].slice() : []; @@ -33,22 +35,26 @@ * @param eventName {string} The name of the event. * @return {boolean} Indication if we've emitted an event. */ - obj.emit = obj.dispatchEvent = function emit(eventName, data) { + obj.emit = obj.dispatchEvent = function emit(eventName, data) + { this._listeners = this._listeners || {}; // fast return when there are no listeners - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return; } //backwards compat with old method ".emit({ type: 'something' })" - if (typeof eventName === 'object') { + if (typeof eventName === 'object') + { data = eventName; eventName = eventName.type; } //ensure we are using a real pixi event - if (!data || data.__isEventObject !== true) { + if (!data || data.__isEventObject !== true) + { data = new EventData(this, eventName, data); } @@ -58,23 +64,27 @@ fn = listeners[0], i; - for (i = 0; i < length; fn = listeners[++i]) { + for (i = 0; i < length; fn = listeners[++i]) + { //call the event listener fn.call(this, data); //if "stopImmediatePropagation" is called, stop calling sibling events - if (data.stoppedImmediate) { + if (data.stoppedImmediate) + { return this; } } //if "stopPropagation" is called then don't bubble the event - if (data.stopped) { + if (data.stopped) + { return this; } //bubble this event up the scene graph - if (this.parent && this.parent.emit) { + if (this.parent && this.parent.emit) + { this.parent.emit.call(this.parent, eventName, data); } @@ -88,7 +98,8 @@ * @param eventName {string} Name of the event. * @param callback {Functon} fn Callback function. */ - obj.on = obj.addEventListener = function on(eventName, fn) { + obj.on = obj.addEventListener = function on(eventName, fn) + { this._listeners = this._listeners || {}; (this._listeners[eventName] = this._listeners[eventName] || []) @@ -103,11 +114,13 @@ * @param eventName {string} Name of the event. * @param callback {Function} Callback function. */ - obj.once = function once(eventName, fn) { + obj.once = function once(eventName, fn) + { this._listeners = this._listeners || {}; var self = this; - function onceHandlerWrapper() { + function onceHandlerWrapper() + { fn.apply(self.off(eventName, onceHandlerWrapper), arguments); } onceHandlerWrapper._originalHandler = fn; @@ -122,23 +135,28 @@ * @param eventName {string} The event we want to remove. * @param callback {Function} The listener that we need to find. */ - obj.off = obj.removeEventListener = function off(eventName, fn) { + obj.off = obj.removeEventListener = function off(eventName, fn) + { this._listeners = this._listeners || {}; - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return this; } var list = this._listeners[eventName], i = fn ? list.length : 0; - while(i-- > 0) { - if (list[i] === fn || list[i]._originalHandler === fn) { + while(i-- > 0) + { + if (list[i] === fn || list[i]._originalHandler === fn) + { list.splice(i, 1); } } - if (list.length === 0) { + if (list.length === 0) + { delete this._listeners[eventName]; } @@ -150,10 +168,12 @@ * * @param eventName {string} The event you want to remove all listeners for. */ - obj.removeAllListeners = function removeAllListeners(eventName) { + obj.removeAllListeners = function removeAllListeners(eventName) + { this._listeners = this._listeners || {}; - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return this; } @@ -169,7 +189,8 @@ * * @param object {object} The obj to mix into */ - mixin: function mixin(obj) { + mixin: function mixin(obj) + { eventTarget(obj); } }; diff --git a/src/core/utils/PolyK.js b/src/core/utils/PolyK.js index 7325141..5e20c2b 100644 --- a/src/core/utils/PolyK.js +++ b/src/core/utils/PolyK.js @@ -47,7 +47,8 @@ * Triangulates shapes for webGL graphic fills. * */ -PolyK.Triangulate = function (p) { +PolyK.Triangulate = function (p) +{ var sign = true; var n = p.length >> 1; @@ -59,7 +60,8 @@ i = 0; var al = n; - while(al > 3) { + while(al > 3) + { var i0 = avl[(i+0)%al]; var i1 = avl[(i+1)%al]; var i2 = avl[(i+2)%al]; @@ -69,29 +71,35 @@ var cx = p[2*i2], cy = p[2*i2+1]; var earFound = false; - if (PolyK._convex(ax, ay, bx, by, cx, cy, sign)) { + if (PolyK._convex(ax, ay, bx, by, cx, cy, sign)) + { earFound = true; - for (var j = 0; j < al; j++) { + for (var j = 0; j < al; j++) + { var vi = avl[j]; if (vi === i0 || vi === i1 || vi === i2) continue; - if (PolyK._PointInTriangle(p[2*vi], p[2*vi+1], ax, ay, bx, by, cx, cy)) { + if (PolyK._PointInTriangle(p[2*vi], p[2*vi+1], ax, ay, bx, by, cx, cy)) + { earFound = false; break; } } } - if (earFound) { + if (earFound) + { tgs.push(i0, i1, i2); avl.splice((i+1)%al, 1); al--; i = 0; } - else if (i++ > 3*al) { + else if (i++ > 3*al) + { // need to flip flip reverse it! // reset! - if (sign) { + if (sign) + { tgs = []; avl = []; for (i = 0; i < n; i++) avl.push(i); @@ -101,7 +109,8 @@ sign = false; } - else { + else + { // window.console.log("PIXI Warning: shape too complex to fill"); return null; } @@ -126,7 +135,8 @@ * @private * @return {boolean} */ -PolyK._PointInTriangle = function (px, py, ax, ay, bx, by, cx, cy) { +PolyK._PointInTriangle = function (px, py, ax, ay, bx, by, cx, cy) +{ var v0x = cx-ax; var v0y = cy-ay; var v1x = bx-ax; @@ -154,6 +164,7 @@ * @private * @return {boolean} */ -PolyK._convex = function (ax, ay, bx, by, cx, cy, sign) { +PolyK._convex = function (ax, ay, bx, by, cx, cy, sign) +{ return ((ay-by)*(cx-bx) + (bx-ax)*(cy-by) >= 0) === sign; }; diff --git a/src/core/utils/index.js b/src/core/utils/index.js index ade9831..bfae7ae 100644 --- a/src/core/utils/index.js +++ b/src/core/utils/index.js @@ -16,7 +16,8 @@ * * @return {number} The next uuid to use. */ - uuid: function () { + uuid: function () + { return ++utils._uid; }, @@ -26,7 +27,8 @@ * @param hex {number} * @return {number[]} An array representing the [R, G, B] of the color. */ - hex2rgb: function (hex, out) { + hex2rgb: function (hex, out) + { out = out || []; out[0] = (hex >> 16 & 0xFF) / 255; @@ -42,7 +44,8 @@ * @param hex {number} * @return {string} The string color. */ - hex2string: function (hex) { + hex2string: function (hex) + { hex = hex.toString(16); hex = '000000'.substr(0, 6 - hex.length) + hex; @@ -55,7 +58,8 @@ * @param rgb {number[]} * @return {number} The color number */ - rgb2hex: function (rgb) { + rgb2hex: function (rgb) + { return ((rgb[0]*255 << 16) + (rgb[1]*255 << 8) + rgb[2]*255); }, @@ -64,8 +68,10 @@ * * @return {boolean} whether they are supported */ - canUseNewCanvasBlendModes: function () { - if (typeof document === 'undefined') { + canUseNewCanvasBlendModes: function () + { + if (typeof document === 'undefined') + { return false; } @@ -93,15 +99,19 @@ * @param number {number} * @return {number} the closest number that is a power of two */ - getNextPowerOfTwo: function (number) { + getNextPowerOfTwo: function (number) + { // see: http://en.wikipedia.org/wiki/Power_of_two#Fast_algorithm_to_check_if_a_positive_number_is_a_power_of_two - if (number > 0 && (number & (number - 1)) === 0) { + if (number > 0 && (number & (number - 1)) === 0) + { return number; } - else { + else + { var result = 1; - while (result < number) { + while (result < number) + { result <<= 1; } @@ -116,7 +126,8 @@ * @param height {number} * @return {boolean} */ - isPowerOfTwo: function (width, height) { + isPowerOfTwo: function (width, height) + { return (width > 0 && (width & (width - 1)) === 0 && height > 0 && (height & (height - 1)) === 0); }, @@ -130,12 +141,15 @@ * @constant * @static */ - sayHello: function (type) { - if (utils._saidHello) { + sayHello: function (type) + { + if (utils._saidHello) + { return; } - if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) { + if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) + { var args = [ '%c %c %c Pixi.js ' + CONST.VERSION + ' - ' + type + ' %c ' + ' %c ' + ' http://www.pixijs.com/ %c %c ♥%c♥%c♥ ', 'background: #ff66a5', @@ -151,7 +165,8 @@ console.log.apply(console, args); //jshint ignore:line } - else if (window.console) { + else if (window.console) + { console.log('Pixi.js ' + CONST.VERSION + ' - ' + type + ' - http://www.pixijs.com/'); //jshint ignore:line } @@ -166,15 +181,19 @@ * @class * @namespace PIXI */ - AjaxRequest: function () { + AjaxRequest: function () + { var activexmodes = ['Msxml2.XMLHTTP.6.0', 'Msxml2.XMLHTTP.3.0', 'Microsoft.XMLHTTP']; //activeX versions to check for in IE - if (window.ActiveXObject) { //Test for support for ActiveXObject in IE first (as XMLHttpRequest in IE7 is broken) - for (var i=0; i= this.textures.length) { + else if (round >= this.textures.length) + { this.gotoAndStop(this.textures.length - 1); - if (this.onComplete) { + if (this.onComplete) + { this.onComplete(); } } @@ -167,10 +182,12 @@ * @static * @param frames {string[]} the array of frames ids the movieclip will use as its texture frames */ -MovieClip.fromFrames = function (frames) { +MovieClip.fromFrames = function (frames) +{ var textures = []; - for (var i = 0; i < frames.length; ++i) { + for (var i = 0; i < frames.length; ++i) + { textures.push(new core.Texture.fromFrame(frames[i])); } @@ -183,10 +200,12 @@ * @static * @param images {string[]} the array of image urls the movieclip will use as its texture frames */ -MovieClip.fromImages = function (images) { +MovieClip.fromImages = function (images) +{ var textures = []; - for (var i = 0; i < images.length; ++i) { + for (var i = 0; i < images.length; ++i) + { textures.push(new core.Texture.fromImage(images[i])); } diff --git a/src/extras/Rope.js b/src/extras/Rope.js index c157ec4..9c87bc0 100644 --- a/src/extras/Rope.js +++ b/src/extras/Rope.js @@ -9,7 +9,8 @@ * @param {Array} points - An array of {Point}. * */ -function Rope(texture, points) { +function Rope(texture, points) +{ Strip.call(this, texture); this.points = points; @@ -31,10 +32,12 @@ * Refreshes * */ -Rope.prototype.refresh = function () { +Rope.prototype.refresh = function () +{ var points = this.points; - if (points.length < 1) { + if (points.length < 1) + { return; } @@ -59,20 +62,23 @@ var total = points.length, point, index, amount; - for (var i = 1; i < total; i++) { + for (var i = 1; i < total; i++) + { point = points[i]; index = i * 4; // time to do some smart drawing! amount = i / (total-1); - if (i%2) { + if (i%2) + { uvs[index] = amount; uvs[index+1] = 0; uvs[index+2] = amount; uvs[index+3] = 1; } - else { + else + { uvs[index] = amount; uvs[index+1] = 0; @@ -95,10 +101,12 @@ * * @private */ -Rope.prototype.updateTransform = function () { +Rope.prototype.updateTransform = function () +{ var points = this.points; - if (points.length < 1) { + if (points.length < 1) + { return; } @@ -113,14 +121,17 @@ var total = points.length, point, index, ratio, perpLength, num; - for (var i = 0; i < total; i++) { + for (var i = 0; i < total; i++) + { point = points[i]; index = i * 4; - if (i < points.length-1) { + if (i < points.length-1) + { nextPoint = points[i+1]; } - else { + else + { nextPoint = point; } @@ -129,7 +140,8 @@ ratio = (1 - (i / (total-1))) * 10; - if (ratio > 1) { + if (ratio > 1) + { ratio = 1; } @@ -157,7 +169,8 @@ * * @param texture {Texture} the texture that will be used */ -Rope.prototype.setTexture = function (texture) { +Rope.prototype.setTexture = function (texture) +{ // stop current texture this.texture = texture; //this.updateFrame = true; diff --git a/src/extras/Strip.js b/src/extras/Strip.js index c5e378f..57691b5 100644 --- a/src/extras/Strip.js +++ b/src/extras/Strip.js @@ -10,7 +10,8 @@ * @param height {number} the height * */ -function Strip(texture) { +function Strip(texture) +{ core.DisplayObjectContainer.call(this); /** @@ -70,9 +71,11 @@ * * @param renderer {WebGLRenderer} */ -Strip.prototype.renderWebGL = function (renderer) { +Strip.prototype.renderWebGL = function (renderer) +{ // if the sprite is not visible or the alpha is 0 then no need to render this element - if (!this.visible || this.alpha <= 0) { + if (!this.visible || this.alpha <= 0) + { return; } @@ -81,7 +84,8 @@ renderer.spriteBatch.stop(); // init! init! - if (!this._vertexBuffer) { + if (!this._vertexBuffer) + { this._initWebGL(renderer); } @@ -96,7 +100,8 @@ //TODO check culling }; -Strip.prototype._initWebGL = function (renderer) { +Strip.prototype._initWebGL = function (renderer) +{ // build the strip! var gl = renderer.gl; @@ -118,7 +123,8 @@ gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this.indices, gl.STATIC_DRAW); }; -Strip.prototype._renderStrip = function (renderer) { +Strip.prototype._renderStrip = function (renderer) +{ var gl = renderer.gl; var projection = renderer.projection, offset = renderer.offset, @@ -137,7 +143,8 @@ gl.uniform2f(shader.offsetVector, -offset.x, -offset.y); gl.uniform1f(shader.alpha, this.worldAlpha); - if (!this.dirty) { + if (!this.dirty) + { gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexBuffer); gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); @@ -150,10 +157,12 @@ gl.activeTexture(gl.TEXTURE0); // check if a texture is dirty.. - if (this.texture.baseTexture._dirty[gl.id]) { + if (this.texture.baseTexture._dirty[gl.id]) + { renderer.updateTexture(this.texture.baseTexture); } - else { + else + { // bind the current texture gl.bindTexture(gl.TEXTURE_2D, this.texture.baseTexture._glTextures[gl.id]); } @@ -163,7 +172,8 @@ } - else { + else + { this.dirty = false; gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexBuffer); @@ -178,10 +188,12 @@ gl.activeTexture(gl.TEXTURE0); // check if a texture is dirty.. - if (this.texture.baseTexture._dirty[gl.id]) { + if (this.texture.baseTexture._dirty[gl.id]) + { renderer.updateTexture(this.texture.baseTexture); } - else { + else + { gl.bindTexture(gl.TEXTURE_2D, this.texture.baseTexture._glTextures[gl.id]); } @@ -203,27 +215,33 @@ * * @param renderer {CanvasRenderer} */ -Strip.prototype.renderCanvas = function (renderer) { +Strip.prototype.renderCanvas = function (renderer) +{ var context = renderer.context; var transform = this.worldTransform; - if (renderer.roundPixels) { + if (renderer.roundPixels) + { context.setTransform(transform.a, transform.b, transform.c, transform.d, transform.tx | 0, transform.ty | 0); } - else { + else + { context.setTransform(transform.a, transform.b, transform.c, transform.d, transform.tx, transform.ty); } - if (this.drawMode === Strip.DrawModes.TRIANGLE_STRIP) { + if (this.drawMode === Strip.DrawModes.TRIANGLE_STRIP) + { this._renderCanvasTriangleStrip(context); } - else { + else + { this._renderCanvasTriangles(context); } }; -Strip.prototype._renderCanvasTriangleStrip = function (context) { +Strip.prototype._renderCanvasTriangleStrip = function (context) +{ // draw triangles!! var vertices = this.vertices; var uvs = this.uvs; @@ -231,14 +249,16 @@ var length = vertices.length / 2; // this.count++; - for (var i = 0; i < length - 2; i++) { + for (var i = 0; i < length - 2; i++) + { // draw some triangles! var index = i * 2; this._renderCanvasDrawTriangle(context, vertices, uvs, index, (index + 2), (index + 4)); } }; -Strip.prototype._renderCanvasTriangles = function (context) { +Strip.prototype._renderCanvasTriangles = function (context) +{ // draw triangles!! var vertices = this.vertices; var uvs = this.uvs; @@ -247,14 +267,16 @@ var length = indices.length; // this.count++; - for (var i = 0; i < length; i += 3) { + for (var i = 0; i < length; i += 3) + { // draw some triangles! var index0 = indices[i] * 2, index1 = indices[i + 1] * 2, index2 = indices[i + 2] * 2; this._renderCanvasDrawTriangle(context, vertices, uvs, index0, index1, index2); } }; -Strip.prototype._renderCanvasDrawTriangle = function (context, vertices, uvs, index0, index1, index2) { +Strip.prototype._renderCanvasDrawTriangle = function (context, vertices, uvs, index0, index1, index2) +{ var textureSource = this.texture.baseTexture.source; var textureWidth = this.texture.width; var textureHeight = this.texture.height; @@ -265,7 +287,8 @@ var u0 = uvs[index0] * textureWidth, u1 = uvs[index1] * textureWidth, u2 = uvs[index2] * textureWidth; var v0 = uvs[index0 + 1] * textureHeight, v1 = uvs[index1 + 1] * textureHeight, v2 = uvs[index2 + 1] * textureHeight; - if (this.canvasPadding > 0) { + if (this.canvasPadding > 0) + { var paddingX = this.canvasPadding / this.worldTransform.a; var paddingY = this.canvasPadding / this.worldTransform.d; var centerX = (x0 + x1 + x2) / 3; @@ -332,7 +355,8 @@ * @param strip {Strip} The Strip to render * @private */ -Strip.prototype.renderStripFlat = function (strip) { +Strip.prototype.renderStripFlat = function (strip) +{ var context = this.context; var vertices = strip.vertices; @@ -340,7 +364,8 @@ // this.count++; context.beginPath(); - for (var i=1; i < length-2; i++) { + for (var i=1; i < length-2; i++) + { // draw some triangles! var index = i*2; @@ -358,7 +383,8 @@ }; /* -Strip.prototype.setTexture = function (texture) { +Strip.prototype.setTexture = function (texture) +{ //TODO SET THE TEXTURES //TODO VISIBILITY @@ -377,7 +403,8 @@ * @private */ -Strip.prototype.onTextureUpdate = function () { +Strip.prototype.onTextureUpdate = function () +{ this.updateFrame = true; }; @@ -387,7 +414,8 @@ * @param matrix {Matrix} the transformation matrix of the sprite * @return {Rectangle} the framing rectangle */ -Strip.prototype.getBounds = function (matrix) { +Strip.prototype.getBounds = function (matrix) +{ var worldTransform = matrix || this.worldTransform; var a = worldTransform.a; @@ -404,7 +432,8 @@ var minY = Infinity; var vertices = this.vertices; - for (var i = 0, n = vertices.length; i < n; i += 2) { + for (var i = 0, n = vertices.length; i < n; i += 2) + { var rawX = vertices[i], rawY = vertices[i + 1]; var x = (a * rawX) + (c * rawY) + tx; var y = (d * rawY) + (b * rawX) + ty; @@ -416,7 +445,8 @@ maxY = y > maxY ? y : maxY; } - if (minX === -Infinity || maxY === Infinity) { + if (minX === -Infinity || maxY === Infinity) + { return core.math.Rectangle.EMPTY; } diff --git a/src/extras/TilingSprite.js b/src/extras/TilingSprite.js index 3ac22df..31da393 100644 --- a/src/extras/TilingSprite.js +++ b/src/extras/TilingSprite.js @@ -10,7 +10,8 @@ * @param width {number} the width of the tiling sprite * @param height {number} the height of the tiling sprite */ -function TilingSprite(texture, width, height) { +function TilingSprite(texture, width, height) +{ core.Sprite.call( this, texture); /** @@ -86,10 +87,12 @@ * @memberof TilingSprite# */ width: { - get: function () { + get: function () + { return this._width; }, - set: function (value) { + set: function (value) + { this._width = value; } }, @@ -101,20 +104,25 @@ * @memberof TilingSprite# */ height: { - get: function () { + get: function () + { return this._height; }, - set: function (value) { + set: function (value) + { this._height = value; } }, texture: { - get: function () { + get: function () + { return this._texture; }, - set: function (value) { - if (this._texture === value) { + set: function (value) + { + if (this._texture === value) + { return; } @@ -130,51 +138,61 @@ * * @param renderer {WebGLRenderer} */ -TilingSprite.prototype.renderWebGL = function (renderer) { - if (!this.visible || this.alpha <= 0) { +TilingSprite.prototype.renderWebGL = function (renderer) +{ + if (!this.visible || this.alpha <= 0) + { return; } var i, j; - if (this._mask) { + if (this._mask) + { renderer.spriteBatch.stop(); renderer.maskManager.pushMask(this.mask, renderer); renderer.spriteBatch.start(); } - if (this._filters) { + if (this._filters) + { renderer.spriteBatch.flush(); renderer.filterManager.pushFilter(this._filterBlock); } - if (!this.tilingTexture || this.refreshTexture) { + if (!this.tilingTexture || this.refreshTexture) + { this.generateTilingTexture(true); - if (this.tilingTexture && this.tilingTexture.needsUpdate) { + if (this.tilingTexture && this.tilingTexture.needsUpdate) + { //TODO - tweaking renderer.updateTexture(this.tilingTexture.baseTexture); this.tilingTexture.needsUpdate = false; // this.tilingTexture._uvs = null; } } - else { + else + { renderer.spriteBatch.renderTilingSprite(this); } // simple render children! - for (i=0,j=this.children.length; i= 0 && index <= this.children.length) { - if (child.parent) { + if (index >= 0 && index <= this.children.length) + { + if (child.parent) + { child.parent.removeChild(child); } @@ -154,7 +173,8 @@ return child; } - else { + else + { throw new Error(child + 'addChildAt: The index '+ index +' supplied is out of bounds ' + this.children.length); } }; @@ -165,15 +185,18 @@ * @param child {DisplayObject} * @param child2 {DisplayObject} */ -DisplayObjectContainer.prototype.swapChildren = function (child, child2) { - if (child === child2) { +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) { + if (index1 < 0 || index2 < 0) + { throw new Error('swapChildren: Both the supplied DisplayObjects must be a child of the caller.'); } @@ -187,10 +210,12 @@ * @param child {DisplayObject} The DisplayObject instance to identify * @return {Number} The index position of the child display object to identify */ -DisplayObjectContainer.prototype.getChildIndex = function (child) { +DisplayObjectContainer.prototype.getChildIndex = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { throw new Error('The supplied DisplayObject must be a child of the caller'); } @@ -203,8 +228,10 @@ * @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 */ -DisplayObjectContainer.prototype.setChildIndex = function (child, index) { - if (index < 0 || index >= this.children.length) { +DisplayObjectContainer.prototype.setChildIndex = function (child, index) +{ + if (index < 0 || index >= this.children.length) + { throw new Error('The supplied index is out of bounds'); } @@ -220,8 +247,10 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child at the given index, if any. */ -DisplayObjectContainer.prototype.getChildAt = function (index) { - if (index < 0 || index >= this.children.length) { +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'); } @@ -234,10 +263,12 @@ * @param child {DisplayObject} The DisplayObject to remove * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChild = function (child) { +DisplayObjectContainer.prototype.removeChild = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { return; } @@ -250,7 +281,8 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChildAt = function (index) { +DisplayObjectContainer.prototype.removeChildAt = function (index) +{ var child = this.getChildAt(index); child.parent = null; @@ -265,24 +297,29 @@ * @param beginIndex {Number} The beginning position. Default value is 0. * @param endIndex {Number} The ending position. Default value is size of the container. */ -DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) { +DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) +{ var begin = beginIndex || 0; var end = typeof endIndex === 'number' ? endIndex : this.children.length; var range = end - begin; - if (range > 0 && range <= end) { + if (range > 0 && range <= end) + { var removed = this.children.splice(begin, range); - for (var i = 0; i < removed.length; ++i) { + for (var i = 0; i < removed.length; ++i) + { removed[i].parent = null; } return removed; } - else if (range === 0 && this.children.length === 0) { + else if (range === 0 && this.children.length === 0) + { return []; } - else { + else + { throw new RangeError('removeChildren: numeric values are outside the acceptable range.'); } }; @@ -291,7 +328,8 @@ * Generates and updates the cached sprite for this object. * */ -DisplayObjectContainer.prototype.updateCachedSprite = function () { +DisplayObjectContainer.prototype.updateCachedSprite = function () +{ this._generateCachedSprite(); }; @@ -304,7 +342,8 @@ * @param renderer {CanvasRenderer|WebGLRenderer} The renderer used to generate the texture. * @return {Texture} a texture of the graphics object */ -DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) { +DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) +{ var bounds = this.getLocalBounds(); var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0, renderer, scaleMode, resolution); @@ -322,18 +361,22 @@ * * @private */ -DisplayObjectContainer.prototype.updateTransform = function () { - if (!this.visible) { +DisplayObjectContainer.prototype.updateTransform = function () +{ + if (!this.visible) + { return; } this.displayObjectUpdateTransform(); - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { return; } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } }; @@ -346,8 +389,10 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getBounds = function () { - if (this.children.length === 0) { +DisplayObjectContainer.prototype.getBounds = function () +{ + if (this.children.length === 0) + { return math.Rectangle.EMPTY; } @@ -365,10 +410,12 @@ var childVisible = false; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -386,7 +433,8 @@ maxY = maxY > childMaxY ? maxY : childMaxY; } - if (!childVisible) { + if (!childVisible) + { return math.Rectangle.EMPTY; } @@ -407,12 +455,14 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getLocalBounds = function () { +DisplayObjectContainer.prototype.getLocalBounds = function () +{ var matrixCache = this.worldTransform; this.worldTransform = math.Matrix.IDENTITY; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } @@ -428,13 +478,16 @@ * * @param renderer {WebGLRenderer} The renderer */ -DisplayObjectContainer.prototype.renderWebGL = function (renderer) { +DisplayObjectContainer.prototype.renderWebGL = function (renderer) +{ // if the object is not visible or the alpha is 0 then no need to render this element - if (!this.visible || this.alpha <= 0) { + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } @@ -442,14 +495,17 @@ var i, j; // do a quick check to see if this element has a mask or a filter. - if (this._mask || this._filters) { + if (this._mask || this._filters) + { // push filter first as we need to ensure the stencil buffer is correct for any masking - if (this._filters) { + if (this._filters) + { renderer.spriteBatch.flush(); renderer.filterManager.pushFilter(this._filterBlock); } - if (this._mask) { + if (this._mask) + { renderer.spriteBatch.stop(); renderer.maskManager.pushMask(this.mask, renderer); renderer.spriteBatch.start(); @@ -459,36 +515,42 @@ this._renderWebGL(renderer); // now loop through the children and make sure they get rendered - for (i = 0, j = this.children.length; i < j; i++) { + for (i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderWebGL(renderer); } // time to stop the sprite batch as either a mask element or a filter draw will happen next renderer.spriteBatch.stop(); - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(this._mask, renderer); } - if (this._filters) { + if (this._filters) + { renderer.filterManager.popFilter(); } renderer.spriteBatch.start(); } - else { + else + { this._renderWebGL(renderer); // simple render children! - for (i = 0, j = this.children.length; i < j; ++i) { + for (i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderWebGL(renderer); } } }; -DisplayObjectContainer.prototype._renderWebGL = function (renderer) { +DisplayObjectContainer.prototype._renderWebGL = function (renderer) +{ // this is where content itself gets renderd.. @@ -499,25 +561,31 @@ * * @param renderer {CanvasRenderer} The renderer */ -DisplayObjectContainer.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0) { +DisplayObjectContainer.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -528,13 +596,16 @@ * @param renderer {WebGLRenderer|CanvasRenderer} The renderer * @private */ -DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) { +DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) +{ this._cachedSprite.worldAlpha = this.worldAlpha; - if (renderer.gl) { + if (renderer.gl) + { this._cachedSprite.renderWebGL(renderer); } - else { + else + { this._cachedSprite.renderCanvas(renderer); } }; @@ -544,10 +615,12 @@ * * @private */ -DisplayObjectContainer.prototype._generateCachedSprite = function () { +DisplayObjectContainer.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { // TODO - RenderTexture now *requires* a renderer instance, so this is like broken // because `renderer` isn't actually in scope here :P var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0); @@ -555,7 +628,8 @@ this._cachedSprite = new Sprite(renderTexture); this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.texture.resize(bounds.width | 0, bounds.height | 0); } @@ -580,8 +654,10 @@ * * @private */ -DisplayObjectContainer.prototype._destroyCachedSprite = function () { - if (!this._cachedSprite) { +DisplayObjectContainer.prototype._destroyCachedSprite = function () +{ + if (!this._cachedSprite) + { return; } diff --git a/src/core/display/Sprite.js b/src/core/display/Sprite.js index 707da24..5862aef 100644 --- a/src/core/display/Sprite.js +++ b/src/core/display/Sprite.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param texture {Texture} The texture for this sprite */ -function Sprite(texture) { +function Sprite(texture) +{ DisplayObjectContainer.call(this); /** @@ -85,12 +86,14 @@ this.texture = texture || Texture.EMPTY; } -Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) { +Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) +{ DisplayObjectContainer.prototype.destroy.call(this); this.anchor = null; - if (destroyTexture) { + if (destroyTexture) + { this._texture.destroy(destroyBaseTexture); } @@ -111,10 +114,12 @@ * @memberof Sprite# */ width: { - get: function () { + get: function () + { return this.scale.x * this.texture.frame.width; }, - set: function (value) { + set: function (value) + { this.scale.x = value / this.texture.frame.width; this._width = value; } @@ -127,10 +132,12 @@ * @memberof Sprite# */ height: { - get: function () { + get: function () + { return this.scale.y * this.texture.frame.height; }, - set: function (value) { + set: function (value) + { this.scale.y = value / this.texture.frame.height; this._height = value; } @@ -143,23 +150,29 @@ * @memberof Sprite# */ texture: { - get: function () { + get: function () + { return this._texture; }, - set: function (value) { - if (this._texture === value) { + set: function (value) + { + if (this._texture === value) + { return; } this._texture = value; this.cachedTint = 0xFFFFFF; - if (value) { + if (value) + { // wait for the texture to load - if (value.baseTexture.hasLoaded) { + if (value.baseTexture.hasLoaded) + { this._onTextureUpdate(); } - else { + else + { value.once('update', this._onTextureUpdate.bind(this)); } } @@ -172,18 +185,22 @@ * * @private */ -Sprite.prototype._onTextureUpdate = function () { +Sprite.prototype._onTextureUpdate = function () +{ // so if _width is 0 then width was not set.. - if (this._width) { + if (this._width) + { this.scale.x = this._width / this.texture.frame.width; } - if (this._height) { + if (this._height) + { this.scale.y = this._height / this.texture.frame.height; } }; -Sprite.prototype._renderWebGL = function (renderer) { +Sprite.prototype._renderWebGL = function (renderer) +{ // this is where content gets renderd.. // watch this space for a little render state manager.. @@ -197,7 +214,8 @@ * @param matrix {Matrix} the transformation matrix of the sprite * @return {Rectangle} the framing rectangle */ -Sprite.prototype.getBounds = function (matrix) { +Sprite.prototype.getBounds = function (matrix) +{ var width = this.texture.frame.width; var height = this.texture.frame.height; @@ -224,11 +242,13 @@ if(b === 0 && c === 0) { // scale may be negative! - if (a < 0) { + if (a < 0) + { a *= -1; } - if (d < 0) { + if (d < 0) + { d *= -1; } @@ -293,28 +313,34 @@ * * @param renderer {CanvasRenderer} The renderer */ -Sprite.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) { +Sprite.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) + { return; } - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; renderer.context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } // Ignore null sources - if (this.texture.valid) { + if (this.texture.valid) + { var resolution = this.texture.baseTexture.resolution / renderer.resolution; renderer.context.globalAlpha = this.worldAlpha; // If smoothingEnabled is supported and we need to change the smoothing property for this texture - if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) { + if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) + { renderer.scaleMode = this.texture.baseTexture.scaleMode; renderer.context[renderer.smoothProperty] = (renderer.scaleMode === CONST.scaleModes.LINEAR); } @@ -324,7 +350,8 @@ var dy = (this.texture.trim ? this.texture.trim.y : 0) - (this.anchor.y * this.texture.trim.height); // Allow for pixel rounding - if (renderer.roundPixels) { + if (renderer.roundPixels) + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -337,7 +364,8 @@ dx = dx | 0; dy = dy | 0; } - else { + else + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -348,8 +376,10 @@ ); } - if (this.tint !== 0xFFFFFF) { - if (this.cachedTint !== this.tint) { + if (this.tint !== 0xFFFFFF) + { + if (this.cachedTint !== this.tint) + { this.cachedTint = this.tint; // TODO clean up caching - how to clean up the caches? @@ -368,7 +398,8 @@ this.texture.crop.height / resolution ); } - else { + else + { renderer.context.drawImage( this.texture.baseTexture.source, this.texture.crop.x, @@ -383,11 +414,13 @@ } } - for (var i = 0, j = this.children.length; i < j; i++) { + for (var i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -402,10 +435,12 @@ * @param frameId {String} The frame Id of the texture in the cache * @return {Sprite} A new Sprite using a texture from the texture cache matching the frameId */ -Sprite.fromFrame = function (frameId) { +Sprite.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache' + this); } @@ -420,6 +455,7 @@ * @param imageId {String} The image url of the texture * @return {Sprite} A new Sprite using a texture from the texture cache matching the image id */ -Sprite.fromImage = function (imageId, crossorigin, scaleMode) { +Sprite.fromImage = function (imageId, crossorigin, scaleMode) +{ return new Sprite(Texture.fromImage(imageId, crossorigin, scaleMode)); }; diff --git a/src/core/display/SpriteBatch.js b/src/core/display/SpriteBatch.js index 3187777..c196fef 100644 --- a/src/core/display/SpriteBatch.js +++ b/src/core/display/SpriteBatch.js @@ -12,7 +12,8 @@ * ```js * var container = new SpriteBatch(); * - * for(var i = 0; i < 100; ++i) { + * for(var i = 0; i < 100; ++i) + * { * var sprite = new PIXI.Sprite.fromImage("myImage.png"); * container.addChild(sprite); * } @@ -25,7 +26,8 @@ */ //TODO RENAME to PARTICLE CONTAINER? -function SpriteBatch() { +function SpriteBatch() +{ DisplayObjectContainer.call(this); } @@ -38,7 +40,8 @@ * * @private */ -SpriteBatch.prototype.updateTransform = function () { +SpriteBatch.prototype.updateTransform = function () +{ // TODO don't need to! this.displayObjectUpdateTransform(); // PIXI.DisplayObjectContainer.prototype.updateTransform.call( this ); @@ -50,8 +53,10 @@ * @param renderer {WebGLRenderer} The webgl renderer * @private */ -SpriteBatch.prototype.renderWebGL = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderWebGL = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -71,8 +76,10 @@ * @param renderer {CanvasRenderer} The canvas renderer * @private */ -SpriteBatch.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -84,10 +91,12 @@ this.displayObjectUpdateTransform(); - for (var i = 0; i < this.children.length; ++i) { + for (var i = 0; i < this.children.length; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -95,9 +104,11 @@ context.globalAlpha = this.worldAlpha * child.alpha; - if (child.rotation % (Math.PI * 2) === 0) { + if (child.rotation % (Math.PI * 2) === 0) + { // this is the fastest way to optimise! - if rotation is 0 then we can avoid any kind of setTransform call - if (isRotated) { + if (isRotated) + { context.setTransform( transform.a, transform.b, @@ -122,8 +133,10 @@ frame.height * child.scale.y ); } - else { - if (!isRotated) { + else + { + if (!isRotated) + { isRotated = true; } @@ -131,7 +144,8 @@ var childTransform = child.worldTransform; - if (renderer.roundPixels) { + if (renderer.roundPixels) + { context.setTransform( childTransform.a, childTransform.b, @@ -141,7 +155,8 @@ childTransform.ty | 0 ); } - else { + else + { context.setTransform( childTransform.a, childTransform.b, diff --git a/src/core/index.js b/src/core/index.js index 3954b6f..eb4a82b 100644 --- a/src/core/index.js +++ b/src/core/index.js @@ -58,11 +58,13 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRenderer: function (width, height, options, noWebGL) { + autoDetectRenderer: function (width, height, options, noWebGL) + { width = width || 800; height = height || 600; - if (!noWebGL && require('webgl-enabled')()) { + if (!noWebGL && require('webgl-enabled')()) + { return new core.WebGLRenderer(width, height, options); } @@ -87,7 +89,8 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRecommendedRenderer: function (width, height, options) { + autoDetectRecommendedRenderer: function (width, height, options) + { var isAndroid = /Android/i.test(navigator.userAgent); return core.autoDetectRenderer(width, height, options, isAndroid); diff --git a/src/core/math/Matrix.js b/src/core/math/Matrix.js index c2f87e2..2ff4848 100644 --- a/src/core/math/Matrix.js +++ b/src/core/math/Matrix.js @@ -10,7 +10,8 @@ * @class * @namespace PIXI */ -function Matrix() { +function Matrix() +{ /** * @member {number} * @default 1 @@ -63,7 +64,8 @@ * * @param array {number[]} The array that the matrix will be populated from. */ -Matrix.prototype.fromArray = function (array) { +Matrix.prototype.fromArray = function (array) +{ this.a = array[0]; this.b = array[1]; this.c = array[3]; @@ -78,14 +80,17 @@ * @param transpose {boolean} Whether we need to transpose the matrix or not * @return {number[]} the newly created array which contains the matrix */ -Matrix.prototype.toArray = function (transpose) { - if (!this.array) { +Matrix.prototype.toArray = function (transpose) +{ + if (!this.array) + { this.array = new Float32Array(9); } var array = this.array; - if (transpose) { + if (transpose) + { array[0] = this.a; array[1] = this.b; array[2] = 0; @@ -96,7 +101,8 @@ array[7] = this.ty; array[8] = 1; } - else { + else + { array[0] = this.a; array[1] = this.c; array[2] = this.tx; @@ -119,7 +125,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, transformed through this matrix */ -Matrix.prototype.apply = function (pos, newPos) { +Matrix.prototype.apply = function (pos, newPos) +{ newPos = newPos || new Point(); newPos.x = this.a * pos.x + this.c * pos.y + this.tx; @@ -136,7 +143,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, inverse-transformed through this matrix */ -Matrix.prototype.applyInverse = function (pos, newPos) { +Matrix.prototype.applyInverse = function (pos, newPos) +{ newPos = newPos || new Point(); var id = 1 / (this.a * this.d + this.c * -this.b); @@ -154,7 +162,8 @@ * @param {number} y * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.translate = function (x, y) { +Matrix.prototype.translate = function (x, y) +{ this.tx += x; this.ty += y; @@ -168,7 +177,8 @@ * @param {number} y The amount to scale vertically * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.scale = function (x, y) { +Matrix.prototype.scale = function (x, y) +{ this.a *= x; this.d *= y; this.c *= x; @@ -186,7 +196,8 @@ * @param {number} angle - The angle in radians. * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.rotate = function (angle) { +Matrix.prototype.rotate = function (angle) +{ var cos = Math.cos( angle ); var sin = Math.sin( angle ); @@ -210,7 +221,8 @@ * @param {Matrix} matrix * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.append = function (matrix) { +Matrix.prototype.append = function (matrix) +{ var a1 = this.a; var b1 = this.b; var c1 = this.c; @@ -232,7 +244,8 @@ * * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.identity = function () { +Matrix.prototype.identity = function () +{ this.a = 1; this.b = 0; this.c = 0; diff --git a/src/core/math/Point.js b/src/core/math/Point.js index 7565b2d..632f346 100644 --- a/src/core/math/Point.js +++ b/src/core/math/Point.js @@ -7,7 +7,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -function Point(x, y) { +function Point(x, y) +{ /** * @member {number} * @default 0 @@ -29,7 +30,8 @@ * * @return {Point} a copy of the point */ -Point.prototype.clone = function () { +Point.prototype.clone = function () +{ return new Point(this.x, this.y); }; @@ -40,7 +42,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -Point.prototype.set = function (x, y) { +Point.prototype.set = function (x, y) +{ this.x = x || 0; this.y = y || ( (y !== 0) ? this.x : 0 ) ; }; diff --git a/src/core/math/shapes/Circle.js b/src/core/math/shapes/Circle.js index 69cfdc9..4d76efc 100644 --- a/src/core/math/shapes/Circle.js +++ b/src/core/math/shapes/Circle.js @@ -10,7 +10,8 @@ * @param y {number} The Y coordinate of the center of this circle * @param radius {number} The radius of the circle */ -function Circle(x, y, radius) { +function Circle(x, y, radius) +{ /** * @member {number} * @default 0 @@ -46,7 +47,8 @@ * @method clone * @return {Circle} a copy of the Circle */ -Circle.prototype.clone = function () { +Circle.prototype.clone = function () +{ return new Circle(this.x, this.y, this.radius); }; @@ -58,8 +60,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Circle */ -Circle.prototype.contains = function (x, y) { - if (this.radius <= 0) { +Circle.prototype.contains = function (x, y) +{ + if (this.radius <= 0) + { return false; } @@ -79,6 +83,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Circle.prototype.getBounds = function () { +Circle.prototype.getBounds = function () +{ return new Rectangle(this.x - this.radius, this.y - this.radius, this.radius * 2, this.radius * 2); }; diff --git a/src/core/math/shapes/Ellipse.js b/src/core/math/shapes/Ellipse.js index 4f2d066..fefd01a 100644 --- a/src/core/math/shapes/Ellipse.js +++ b/src/core/math/shapes/Ellipse.js @@ -11,7 +11,8 @@ * @param width {number} The half width of this ellipse * @param height {number} The half height of this ellipse */ -function Ellipse(x, y, width, height) { +function Ellipse(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -53,7 +54,8 @@ * @method clone * @return {Ellipse} a copy of the ellipse */ -Ellipse.prototype.clone = function () { +Ellipse.prototype.clone = function () +{ return new Ellipse(this.x, this.y, this.width, this.height); }; @@ -65,8 +67,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coords are within this ellipse */ -Ellipse.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Ellipse.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } @@ -86,6 +90,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Ellipse.prototype.getBounds = function () { +Ellipse.prototype.getBounds = function () +{ return new Rectangle(this.x - this.width, this.y - this.height, this.width, this.height); }; diff --git a/src/core/math/shapes/Polygon.js b/src/core/math/shapes/Polygon.js index ae89148..fea6d37 100644 --- a/src/core/math/shapes/Polygon.js +++ b/src/core/math/shapes/Polygon.js @@ -10,16 +10,20 @@ * arguments passed can be flat x,y values e.g. `new Polygon(x,y, x,y, x,y, ...)` where `x` and `y` are * Numbers. */ -function Polygon(points) { +function Polygon(points) +{ //if points isn't an array, use arguments as the array - if (!(points instanceof Array)) { + if (!(points instanceof Array)) + { points = Array.prototype.slice.call(arguments); } //if this is a flat array of numbers, convert it to points - if (points[0] instanceof Point) { + if (points[0] instanceof Point) + { var p = []; - for (var i = 0, il = points.length; i < il; i++) { + for (var i = 0, il = points.length; i < il; i++) + { p.push(points[i].x, points[i].y); } @@ -51,7 +55,8 @@ * * @return {Polygon} a copy of the polygon */ -Polygon.prototype.clone = function () { +Polygon.prototype.clone = function () +{ return new Polygon(this.points.slice()); }; @@ -62,19 +67,22 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this polygon */ -Polygon.prototype.contains = function (x, y) { +Polygon.prototype.contains = function (x, y) +{ var inside = false; // use some raycasting to test hits // https://github.com/substack/point-in-polygon/blob/master/index.js var length = this.points.length / 2; - for (var i = 0, j = length - 1; i < length; j = i++) { + for (var i = 0, j = length - 1; i < length; j = i++) + { var xi = this.points[i * 2], yi = this.points[i * 2 + 1], xj = this.points[j * 2], yj = this.points[j * 2 + 1], intersect = ((yi > y) !== (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi); - if (intersect) { + if (intersect) + { inside = !inside; } } diff --git a/src/core/math/shapes/Rectangle.js b/src/core/math/shapes/Rectangle.js index 16ac62a..4008b68 100644 --- a/src/core/math/shapes/Rectangle.js +++ b/src/core/math/shapes/Rectangle.js @@ -10,7 +10,8 @@ * @param width {number} The overall width of this rectangle * @param height {number} The overall height of this rectangle */ -function Rectangle(x, y, width, height) { +function Rectangle(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -60,7 +61,8 @@ * * @return {Rectangle} a copy of the rectangle */ -Rectangle.prototype.clone = function () { +Rectangle.prototype.clone = function () +{ return new Rectangle(this.x, this.y, this.width, this.height); }; @@ -71,13 +73,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rectangle */ -Rectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Rectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/math/shapes/RoundedRectangle.js b/src/core/math/shapes/RoundedRectangle.js index 27d286e..7bf6411 100644 --- a/src/core/math/shapes/RoundedRectangle.js +++ b/src/core/math/shapes/RoundedRectangle.js @@ -11,7 +11,8 @@ * @param height {number} The overall height of this rounded rectangle * @param radius {number} Controls the radius of the rounded corners */ -function RoundedRectangle(x, y, width, height, radius) { +function RoundedRectangle(x, y, width, height, radius) +{ /** * @member {number} * @default 0 @@ -58,7 +59,8 @@ * * @return {RoundedRectangle} a copy of the rounded rectangle */ -RoundedRectangle.prototype.clone = function () { +RoundedRectangle.prototype.clone = function () +{ return new RoundedRectangle(this.x, this.y, this.width, this.height, this.radius); }; @@ -69,13 +71,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rounded Rectangle */ -RoundedRectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +RoundedRectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/primitives/Graphics.js b/src/core/primitives/Graphics.js index 261c534..e902d2a 100644 --- a/src/core/primitives/Graphics.js +++ b/src/core/primitives/Graphics.js @@ -16,7 +16,8 @@ * @extends DisplayObjectContainer * @namespace PIXI */ -function Graphics() { +function Graphics() +{ DisplayObjectContainer.call(this); this.renderable = true; @@ -154,16 +155,20 @@ * @private */ cacheAsBitmap: { - get: function () { + get: function () + { return this._cacheAsBitmap; }, - set: function (value) { + set: function (value) + { this._cacheAsBitmap = value; - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._generateCachedSprite(); } - else { + else + { this.destroyCachedSprite(); this.dirty = true; } @@ -176,7 +181,8 @@ * * @return {Graphics} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ var clone = new Graphics(); clone.renderable = this.renderable; @@ -192,7 +198,8 @@ clone.cachedSpriteDirty = this.cachedSpriteDirty; // copy graphics data - for (var i = 0; i < this.graphicsData.length; ++i) { + for (var i = 0; i < this.graphicsData.length; ++i) + { clone.graphicsData.push(this.graphicsData.clone()); } @@ -211,17 +218,21 @@ * @param alpha {number} alpha of the line to draw, will update the objects stored style * @return {Graphics} */ -Graphics.prototype.lineStyle = function (lineWidth, color, alpha) { +Graphics.prototype.lineStyle = function (lineWidth, color, alpha) +{ this.lineWidth = lineWidth || 0; this.lineColor = color || 0; this.lineAlpha = (arguments.length < 3) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length) + { // halfway through a line? start a new one! this.drawShape( new math.Polygon( this.currentPath.shape.points.slice(-2) )); } - else { + else + { // otherwise its empty so lets just set the line properties this.currentPath.lineWidth = this.lineWidth; this.currentPath.lineColor = this.lineColor; @@ -239,7 +250,8 @@ * @param y {number} the Y coordinate to move to * @return {Graphics} */ -Graphics.prototype.moveTo = function (x, y) { +Graphics.prototype.moveTo = function (x, y) +{ this.drawShape(new math.Polygon([x,y])); return this; @@ -253,7 +265,8 @@ * @param y {number} the Y coordinate to draw to * @return {Graphics} */ -Graphics.prototype.lineTo = function (x, y) { +Graphics.prototype.lineTo = function (x, y) +{ this.currentPath.shape.points.push(x, y); this.dirty = true; @@ -270,13 +283,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -285,7 +302,8 @@ n = 20, points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { this.moveTo(0, 0); } @@ -293,7 +311,8 @@ var fromY = points[points.length-1]; var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; xa = fromX + ( (cpX - fromX) * j ); @@ -319,13 +338,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -342,7 +365,8 @@ var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; dt = (1 - j); @@ -373,13 +397,17 @@ * @param radius {number} The radius of the arc * @return {Graphics} */ -Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points.push(x1, y1); } } - else { + else + { this.moveTo(x1, y1); } @@ -392,12 +420,15 @@ b2 = x2 - x1, mm = Math.abs(a1 * b2 - b1 * a2); - if (mm < 1.0e-8 || radius === 0) { - if (points[points.length-2] !== x1 || points[points.length-1] !== y1) { + if (mm < 1.0e-8 || radius === 0) + { + if (points[points.length-2] !== x1 || points[points.length-1] !== y1) + { points.push(x1, y1); } } - else { + else + { var dd = a1 * a1 + b1 * b1, cc = a2 * a2 + b2 * b2, tt = a1 * a2 + b1 * b2, @@ -433,42 +464,51 @@ * @param anticlockwise {boolean} Optional. Specifies whether the drawing should be counterclockwise or clockwise. False is default, and indicates clockwise, while true indicates counter-clockwise. * @return {Graphics} */ -Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) { +Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) +{ var startX = cx + Math.cos(startAngle) * radius; var startY = cy + Math.sin(startAngle) * radius; var points; // TODO - This if-else makes no sense. It uses currentPath in the else where it doesn't exist... - if (this.currentPath) { + if (this.currentPath) + { points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { points.push(startX, startY); } - else if (points[points.length-2] !== startX || points[points.length-1] !== startY) { + else if (points[points.length-2] !== startX || points[points.length-1] !== startY) + { points.push(startX, startY); } } - else { + else + { this.moveTo(startX, startY); points = this.currentPath.shape.points; } - if (startAngle === endAngle) { + if (startAngle === endAngle) + { return this; } - if (!anticlockwise && endAngle <= startAngle) { + if (!anticlockwise && endAngle <= startAngle) + { endAngle += Math.PI * 2; } - else if (anticlockwise && startAngle <= endAngle) { + else if (anticlockwise && startAngle <= endAngle) + { startAngle += Math.PI * 2; } var sweep = anticlockwise ? (startAngle - endAngle) *-1 : (endAngle - startAngle); var segs = (Math.abs(sweep)/ (Math.PI * 2)) * 40; - if (sweep === 0) { + if (sweep === 0) + { return this; } @@ -482,7 +522,8 @@ var remainder = ( segMinus % 1 ) / segMinus; - for (var i = 0; i <= segMinus; ++i) { + for (var i = 0; i <= segMinus; ++i) + { var real = i + remainder * i; var angle = ((theta) + startAngle + (theta2 * real)); @@ -506,13 +547,16 @@ * @param alpha {number} the alpha of the fill * @return {Graphics} */ -Graphics.prototype.beginFill = function (color, alpha) { +Graphics.prototype.beginFill = function (color, alpha) +{ this.filling = true; this.fillColor = color || 0; this.fillAlpha = (alpha === undefined) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length <= 2) + { this.currentPath.fill = this.filling; this.currentPath.fillColor = this.fillColor; this.currentPath.fillAlpha = this.fillAlpha; @@ -526,7 +570,8 @@ * * @return {Graphics} */ -Graphics.prototype.endFill = function () { +Graphics.prototype.endFill = function () +{ this.filling = false; this.fillColor = null; this.fillAlpha = 1; @@ -542,7 +587,8 @@ * @param height {number} The height of the rectangle * @return {Graphics} */ -Graphics.prototype.drawRect = function ( x, y, width, height ) { +Graphics.prototype.drawRect = function ( x, y, width, height ) +{ this.drawShape(new math.Rectangle(x,y, width, height)); return this; @@ -556,7 +602,8 @@ * @param height {number} The height of the rectangle * @param radius {number} Radius of the rectangle corners */ -Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) { +Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) +{ this.drawShape(new math.RoundedRectangle(x, y, width, height, radius)); return this; @@ -570,7 +617,8 @@ * @param radius {number} The radius of the circle * @return {Graphics} */ -Graphics.prototype.drawCircle = function (x, y, radius) { +Graphics.prototype.drawCircle = function (x, y, radius) +{ this.drawShape(new math.Circle(x,y, radius)); return this; @@ -585,7 +633,8 @@ * @param height {number} The half height of the ellipse * @return {Graphics} */ -Graphics.prototype.drawEllipse = function (x, y, width, height) { +Graphics.prototype.drawEllipse = function (x, y, width, height) +{ this.drawShape(new math.Ellipse(x, y, width, height)); return this; @@ -597,8 +646,10 @@ * @param path {Array} The path data used to construct the polygon. * @return {Graphics} */ -Graphics.prototype.drawPolygon = function (path) { - if (!(path instanceof Array)) { +Graphics.prototype.drawPolygon = function (path) +{ + if (!(path instanceof Array)) + { path = Array.prototype.slice.call(arguments); } @@ -612,7 +663,8 @@ * * @return {Graphics} */ -Graphics.prototype.clear = function () { +Graphics.prototype.clear = function () +{ this.lineWidth = 0; this.filling = false; @@ -631,7 +683,8 @@ * @param scaleMode {number} Should be one of the scaleMode consts * @return {Texture} a texture of the graphics object */ -Graphics.prototype.generateTexture = function (resolution, scaleMode) { +Graphics.prototype.generateTexture = function (resolution, scaleMode) +{ resolution = resolution || 1; var bounds = this.getBounds(); @@ -655,17 +708,21 @@ * * @param renderer {WebGLRenderer} */ -Graphics.prototype._renderWebGL = function (renderer) { +Graphics.prototype._renderWebGL = function (renderer) +{ // if the sprite is not visible or the alpha is 0 then no need to render this element - if (this.isMask === true) { + if (this.isMask === true) + { return; } // this code may still be needed so leaving for now.. - // + // /* - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture on the gpu too! @@ -681,17 +738,24 @@ return; } - */ - - // check if the webgl graphic needs to be updated - if (this.glDirty) { - this.dirty = true; - this.glDirty = false; - } + else */ - renderer.setObjectRendererer(renderer.graphicsRenderer); - renderer.graphicsRenderer.render(this); + renderer.spriteBatch.stop(); + renderer.blendModeManager.setBlendMode(this.blendMode); + // check blend mode + renderer.blendModeManager.setBlendMode( this.blendMode ); + + // check if the webgl graphic needs to be updated + if (this.glDirty) + { + this.dirty = true; + this.glDirty = false; + } + + WebGLGraphics.renderGraphics(this, renderer); + + renderer.spriteBatch.start(); }; /** @@ -700,14 +764,18 @@ * @param renderer {CanvasRenderer} * @private */ -Graphics.prototype.renderCanvas = function (renderer) { +Graphics.prototype.renderCanvas = function (renderer) +{ // 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.isMask === true) { + if (!this.visible || this.alpha <= 0 || this.isMask === true) + { return; } - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture @@ -723,16 +791,19 @@ return; } - else { + else + { var context = renderer.context; var transform = this.worldTransform; - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } @@ -748,11 +819,13 @@ CanvasGraphics.renderGraphics(this, context); - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } } @@ -763,13 +836,16 @@ * * @return {Rectangle} the rectangular bounding area */ -Graphics.prototype.getBounds = function (matrix) { +Graphics.prototype.getBounds = function (matrix) +{ // return an empty object if the item is a mask! - if (this.isMask) { + if (this.isMask) + { return math.Rectangle.EMPTY; } - if (this.dirty) { + if (this.dirty) + { this.updateLocalBounds(); this.glDirty = true; @@ -841,23 +917,27 @@ * Update the bounds of the object * */ -Graphics.prototype.updateLocalBounds = function () { +Graphics.prototype.updateLocalBounds = function () +{ var minX = Infinity; var maxX = -Infinity; var minY = Infinity; var maxY = -Infinity; - if (this.graphicsData.length) { + if (this.graphicsData.length) + { var shape, points, x, y, w, h; - for (var i = 0; i < this.graphicsData.length; i++) { + for (var i = 0; i < this.graphicsData.length; i++) + { var data = this.graphicsData[i]; var type = data.type; var lineWidth = data.lineWidth; shape = data.shape; - if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) { + if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) + { x = shape.x - lineWidth/2; y = shape.y - lineWidth/2; w = shape.width + lineWidth; @@ -869,7 +949,8 @@ minY = y < minY ? y : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.CIRC) { + else if (type === CONST.SHAPES.CIRC) + { x = shape.x; y = shape.y; w = shape.radius + lineWidth/2; @@ -881,7 +962,8 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.ELIP) { + else if (type === CONST.SHAPES.ELIP) + { x = shape.x; y = shape.y; w = shape.width + lineWidth/2; @@ -893,11 +975,13 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else { + else + { // POLY points = shape.points; - for (var j = 0; j < points.length; j += 2) { + for (var j = 0; j < points.length; j += 2) + { x = points[j]; y = points[j+1]; @@ -910,7 +994,8 @@ } } } - else { + else + { minX = 0; maxX = 0; minY = 0; @@ -931,10 +1016,12 @@ * * @private */ -Graphics.prototype._generateCachedSprite = function () { +Graphics.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { var canvasBuffer = new CanvasBuffer(bounds.width, bounds.height); var texture = Texture.fromCanvas(canvasBuffer.canvas); @@ -943,7 +1030,8 @@ this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.buffer.resize(bounds.width, bounds.height); } @@ -968,7 +1056,8 @@ * * @private */ -Graphics.prototype.updateCachedSpriteTexture = function () { +Graphics.prototype.updateCachedSpriteTexture = function () +{ var cachedSprite = this._cachedSprite; var texture = cachedSprite.texture; var canvas = cachedSprite.buffer.canvas; @@ -989,7 +1078,8 @@ * Destroys a previous cached sprite. * */ -Graphics.prototype.destroyCachedSprite = function () { +Graphics.prototype.destroyCachedSprite = function () +{ this._cachedSprite.texture.destroy(true); // let the gc collect the unused sprite @@ -1003,10 +1093,13 @@ * @param {Circle|Rectangle|Ellipse|Line|Polygon} shape The Shape object to draw. * @return {GraphicsData} The generated GraphicsData object. */ -Graphics.prototype.drawShape = function (shape) { - if (this.currentPath) { +Graphics.prototype.drawShape = function (shape) +{ + if (this.currentPath) + { // check current path! - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath.shape.points.length <= 2) + { this.graphicsData.pop(); } } @@ -1017,7 +1110,8 @@ this.graphicsData.push(data); - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { data.shape.closed = this.filling; this.currentPath = data; } diff --git a/src/core/primitives/GraphicsData.js b/src/core/primitives/GraphicsData.js index 99decbe..788f6f2 100644 --- a/src/core/primitives/GraphicsData.js +++ b/src/core/primitives/GraphicsData.js @@ -4,7 +4,8 @@ * @class * @namespace PIXI */ -function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) { +function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) +{ this.lineWidth = lineWidth; this.lineColor = lineColor; this.lineAlpha = lineAlpha; @@ -27,7 +28,8 @@ * * @return {GraphicsData} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ return new GraphicsData( this.lineWidth, this.lineColor, diff --git a/src/core/renderers/canvas/CanvasRenderer.js b/src/core/renderers/canvas/CanvasRenderer.js index 15a0978..7aebd44 100644 --- a/src/core/renderers/canvas/CanvasRenderer.js +++ b/src/core/renderers/canvas/CanvasRenderer.js @@ -17,17 +17,22 @@ * @param [options.resolution=1] {number} the resolution of the renderer retina would be 2 * @param [options.clearBeforeRender=true] {boolean} This sets if the CanvasRenderer will clear the canvas or not before the new render pass. */ -function CanvasRenderer(width, height, options) { +function CanvasRenderer(width, height, options) +{ utils.sayHello('Canvas'); - if (options) { - for (var i in CONST.defaultRenderOptions) { - if (typeof options[i] === 'undefined') { + if (options) + { + for (var i in CONST.defaultRenderOptions) + { + if (typeof options[i] === 'undefined') + { options[i] = CONST.defaultRenderOptions[i]; } } } - else { + else + { options = CONST.defaultRenderOptions; } @@ -156,19 +161,24 @@ this.smoothProperty = null; - if (this.context.imageSmoothingEnabled) { + if (this.context.imageSmoothingEnabled) + { this.smoothProperty = 'imageSmoothingEnabled'; } - else if (this.context.webkitImageSmoothingEnabled) { + else if (this.context.webkitImageSmoothingEnabled) + { this.smoothProperty = 'webkitImageSmoothingEnabled'; } - else if (this.context.mozImageSmoothingEnabled) { + else if (this.context.mozImageSmoothingEnabled) + { this.smoothProperty = 'mozImageSmoothingEnabled'; } - else if (this.context.oImageSmoothingEnabled) { + else if (this.context.oImageSmoothingEnabled) + { this.smoothProperty = 'oImageSmoothingEnabled'; } - else if (this.context.msImageSmoothingEnabled) { + else if (this.context.msImageSmoothingEnabled) + { this.smoothProperty = 'msImageSmoothingEnabled'; } @@ -193,10 +203,12 @@ * @memberof CanvasRenderer# */ backgroundColor: { - get: function () { + get: function () + { return this._backgroundColor; }, - set: function (val) { + set: function (val) + { this._backgroundColor = val; this._backgroundColorString = utils.hex2string(val); } @@ -208,7 +220,8 @@ * * @param object {DisplayObject} the object to be rendered */ -CanvasRenderer.prototype.render = function (object) { +CanvasRenderer.prototype.render = function (object) +{ object.updateTransform(); this.context.setTransform(1,0,0,1,0,0); @@ -218,16 +231,20 @@ this.currentBlendMode = CONST.blendModes.NORMAL; this.context.globalCompositeOperation = this.blendModes[CONST.blendModes.NORMAL]; - if (navigator.isCocoonJS && this.view.screencanvas) { + if (navigator.isCocoonJS && this.view.screencanvas) + { this.context.fillStyle = 'black'; this.context.clear(); } - if (this.clearBeforeRender) { - if (this.transparent) { + if (this.clearBeforeRender) + { + if (this.transparent) + { this.context.clearRect(0, 0, this.width, this.height); } - else { + else + { this.context.fillStyle = this._backgroundColorString; this.context.fillRect(0, 0, this.width , this.height); } @@ -241,8 +258,10 @@ * * @param [removeView=false] {boolean} Removes the Canvas element from the DOM. */ -CanvasRenderer.prototype.destroy = function (removeView) { - if (removeView && this.view.parent) { +CanvasRenderer.prototype.destroy = function (removeView) +{ + if (removeView && this.view.parent) + { this.view.parent.removeChild(this.view); } @@ -257,14 +276,16 @@ * @param width {number} the new width of the canvas view * @param height {number} the new height of the canvas view */ -CanvasRenderer.prototype.resize = function (width, height) { +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) { + if (this.autoResize) + { this.view.style.width = this.width / this.resolution + 'px'; this.view.style.height = this.height / this.resolution + 'px'; } @@ -276,7 +297,8 @@ * @param displayObject {DisplayObject} The displayObject to render * @private */ -CanvasRenderer.prototype.renderDisplayObject = function (displayObject) { +CanvasRenderer.prototype.renderDisplayObject = function (displayObject) +{ displayObject.renderCanvas(this); }; @@ -285,11 +307,14 @@ * * @private */ -CanvasRenderer.prototype._mapBlendModes = function () { - if (!this.blendModes) { +CanvasRenderer.prototype._mapBlendModes = function () +{ + if (!this.blendModes) + { this.blendModes = {}; - if (utils.canUseNewCanvasBlendModes()) { + if (utils.canUseNewCanvasBlendModes()) + { this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? this.blendModes[CONST.blendModes.MULTIPLY] = 'multiply'; @@ -308,7 +333,8 @@ this.blendModes[CONST.blendModes.COLOR] = 'color'; this.blendModes[CONST.blendModes.LUMINOSITY] = 'luminosity'; } - else { + else + { // this means that the browser does not support the cool new blend modes in canvas 'cough' ie 'cough' this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? diff --git a/src/core/renderers/canvas/utils/CanvasBuffer.js b/src/core/renderers/canvas/utils/CanvasBuffer.js index ebe5d47..b183a66 100644 --- a/src/core/renderers/canvas/utils/CanvasBuffer.js +++ b/src/core/renderers/canvas/utils/CanvasBuffer.js @@ -6,7 +6,8 @@ * @param width {number} the width for the newly created canvas * @param height {number} the height for the newly created canvas */ -function CanvasBuffer(width, height) { +function CanvasBuffer(width, height) +{ /** * The Canvas object that belongs to this CanvasBuffer. * @@ -36,10 +37,12 @@ * @memberof CanvasBuffer# */ width: { - get: function () { + get: function () + { return this.canvas.width; }, - set: function (val) { + set: function (val) + { this.canvas.width = val; } }, @@ -50,10 +53,12 @@ * @memberof CanvasBuffer# */ height: { - get: function () { + get: function () + { return this.canvas.height; }, - set: function (val) { + set: function (val) + { this.canvas.height = val; } } @@ -64,7 +69,8 @@ * * @private */ -CanvasBuffer.prototype.clear = function () { +CanvasBuffer.prototype.clear = function () +{ this.context.setTransform(1, 0, 0, 1, 0, 0); this.context.clearRect(0,0, this.canvas.width, this.canvas.height); }; @@ -75,7 +81,8 @@ * @param width {number} the new width of the canvas * @param height {number} the new height of the canvas */ -CanvasBuffer.prototype.resize = function (width, height) { +CanvasBuffer.prototype.resize = function (width, height) +{ this.canvas.width = width; this.canvas.height = height; }; diff --git a/src/core/renderers/canvas/utils/CanvasGraphics.js b/src/core/renderers/canvas/utils/CanvasGraphics.js index c7eaa2a..3f2a91f 100644 --- a/src/core/renderers/canvas/utils/CanvasGraphics.js +++ b/src/core/renderers/canvas/utils/CanvasGraphics.js @@ -13,15 +13,18 @@ * @param graphics {Graphics} the actual graphics object to render * @param context {CanvasRenderingContext2D} the 2d drawing method of the canvas */ -CanvasGraphics.renderGraphics = function (graphics, context) { +CanvasGraphics.renderGraphics = function (graphics, context) +{ var worldAlpha = graphics.worldAlpha; - if (graphics.dirty) { + if (graphics.dirty) + { this.updateGraphicsTint(graphics); graphics.dirty = false; } - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; @@ -30,69 +33,82 @@ context.lineWidth = data.lineWidth; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { context.beginPath(); var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } - if (shape.closed) { + if (shape.closed) + { context.lineTo(points[0], points[1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fillRect(shape.x, shape.y, shape.width, shape.height); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.strokeRect(shape.x, shape.y, shape.width, shape.height); } } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.beginPath(); context.arc(shape.x, shape.y, shape.radius,0,2*Math.PI); context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas var w = shape.width * 2; @@ -119,18 +135,21 @@ context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; var width = shape.width; @@ -152,13 +171,15 @@ context.quadraticCurveTo(rx, ry, rx, ry + radius); context.closePath(); - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); @@ -174,45 +195,54 @@ * @param graphics {Graphics} the graphics which will be used as a mask * @param context {CanvasRenderingContext2D} the context 2d method of the canvas */ -CanvasGraphics.renderGraphicsMask = function (graphics, context) { +CanvasGraphics.renderGraphicsMask = function (graphics, context) +{ var len = graphics.graphicsData.length; - if (len === 0) { + if (len === 0) + { return; } context.beginPath(); - for (var i = 0; i < len; i++) { + for (var i = 0; i < len; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { context.rect(shape.x, shape.y, shape.width, shape.height); context.closePath(); } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.arc(shape.x, shape.y, shape.radius, 0, 2 * Math.PI); context.closePath(); } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas @@ -237,7 +267,8 @@ context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); context.closePath(); } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; @@ -262,8 +293,10 @@ } }; -CanvasGraphics.updateGraphicsTint = function (graphics) { - if (graphics.tint === 0xFFFFFF) { +CanvasGraphics.updateGraphicsTint = function (graphics) +{ + if (graphics.tint === 0xFFFFFF) + { return; } @@ -271,7 +304,8 @@ var tintG = (graphics.tint >> 8 & 0xFF) / 255; var tintB = (graphics.tint & 0xFF)/ 255; - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var fillColor = data.fillColor | 0; diff --git a/src/core/renderers/canvas/utils/CanvasMaskManager.js b/src/core/renderers/canvas/utils/CanvasMaskManager.js index e04a733..9827d36 100644 --- a/src/core/renderers/canvas/utils/CanvasMaskManager.js +++ b/src/core/renderers/canvas/utils/CanvasMaskManager.js @@ -6,7 +6,8 @@ * @class * @namespace PIXI */ -function CanvasMaskManager() {} +function CanvasMaskManager() +{} CanvasMaskManager.prototype.constructor = CanvasMaskManager; module.exports = CanvasMaskManager; @@ -17,7 +18,8 @@ * @param maskData {object} the maskData that will be pushed * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.pushMask = function (maskData, renderer) { +CanvasMaskManager.prototype.pushMask = function (maskData, renderer) +{ renderer.context.save(); var cacheAlpha = maskData.alpha; @@ -45,6 +47,7 @@ * * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.popMask = function (renderer) { +CanvasMaskManager.prototype.popMask = function (renderer) +{ renderer.context.restore(); }; diff --git a/src/core/renderers/canvas/utils/CanvasTinter.js b/src/core/renderers/canvas/utils/CanvasTinter.js index 17e0529..d2fb1bc 100644 --- a/src/core/renderers/canvas/utils/CanvasTinter.js +++ b/src/core/renderers/canvas/utils/CanvasTinter.js @@ -14,7 +14,8 @@ * @param color {number} the color to use to tint the sprite with * @return {HTMLCanvasElement} The tinted canvas */ -CanvasTinter.getTintedTexture = function (sprite, color) { +CanvasTinter.getTintedTexture = function (sprite, color) +{ var texture = sprite.texture; color = CanvasTinter.roundColor(color); @@ -23,7 +24,8 @@ texture.tintCache = texture.tintCache || {}; - if (texture.tintCache[stringColor]) { + if (texture.tintCache[stringColor]) + { return texture.tintCache[stringColor]; } @@ -33,14 +35,16 @@ //CanvasTinter.tintWithPerPixel(texture, stringColor, canvas); CanvasTinter.tintMethod(texture, color, canvas); - if (CanvasTinter.convertTintToImage) { + if (CanvasTinter.convertTintToImage) + { // is this better? var tintImage = new Image(); tintImage.src = canvas.toDataURL(); texture.tintCache[stringColor] = tintImage; } - else { + else + { texture.tintCache[stringColor] = canvas; // if we are not converting the texture to an image then we need to lose the reference to the canvas CanvasTinter.canvas = null; @@ -56,7 +60,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithMultiply = function (texture, color, canvas) { +CanvasTinter.tintWithMultiply = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -104,7 +109,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithOverlay = function (texture, color, canvas) { +CanvasTinter.tintWithOverlay = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -139,7 +145,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithPerPixel = function (texture, color, canvas) { +CanvasTinter.tintWithPerPixel = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -167,7 +174,8 @@ var pixels = pixelData.data; - for (var i = 0; i < pixels.length; i += 4) { + for (var i = 0; i < pixels.length; i += 4) + { pixels[i+0] *= r; pixels[i+1] *= g; pixels[i+2] *= b; @@ -181,7 +189,8 @@ * * @param color {number} the color to round, should be a hex color */ -CanvasTinter.roundColor = function (color) { +CanvasTinter.roundColor = function (color) +{ var step = CanvasTinter.cacheStepsPerColorChannel; var rgbValues = utils.hex2rgb(color); diff --git a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js index 9f2f89a..35edbaf 100644 --- a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js +++ b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLBlendModeManager(renderer) { +function WebGLBlendModeManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -23,8 +24,10 @@ * * @param blendMode {number} the blendMode, should be a Pixi const, such as BlendModes.ADD */ -WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) { - if (this.currentBlendMode === blendMode) { +WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) +{ + if (this.currentBlendMode === blendMode) + { return false; } diff --git a/src/core/renderers/webgl/managers/WebGLFilterManager.js b/src/core/renderers/webgl/managers/WebGLFilterManager.js index 1179258..2dac048 100644 --- a/src/core/renderers/webgl/managers/WebGLFilterManager.js +++ b/src/core/renderers/webgl/managers/WebGLFilterManager.js @@ -7,7 +7,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLFilterManager(renderer) { +function WebGLFilterManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -32,7 +33,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.texturePool.length = 0; self.initShaderBuffers(); }); @@ -46,7 +48,8 @@ * @param renderer {WebGLRenderer} * @param buffer {ArrayBuffer} */ -WebGLFilterManager.prototype.begin = function (buffer) { +WebGLFilterManager.prototype.begin = function (buffer) +{ this.defaultShader = this.renderer.shaderManager.defaultShader; this.width = this.renderer.projection.x * 2; @@ -60,7 +63,8 @@ * * @param filterBlock {object} the filter that will be pushed to the current filter stack */ -WebGLFilterManager.prototype.pushFilter = function (filterBlock) { +WebGLFilterManager.prototype.pushFilter = function (filterBlock) +{ var gl = this.renderer.gl; var projection = this.renderer.projection; @@ -78,10 +82,12 @@ this.offsetY += filterBlock._filterArea.y; var texture = this.texturePool.pop(); - if (!texture) { + if (!texture) + { texture = new FilterTexture(this.renderer.gl, this.width, this.height); } - else { + else + { texture.resize(this.width, this.height); } @@ -98,29 +104,35 @@ var localX = filterArea.x, localY = filterArea.y; - if (filterArea.x < 0) { + if (filterArea.x < 0) + { filterArea.width += filterArea.x; filterArea.x = 0; } - if (filterArea.y < 0) { + if (filterArea.y < 0) + { filterArea.height += filterArea.y; filterArea.y = 0; } - if (localX + filterArea.width > this.width) { + if (localX + filterArea.width > this.width) + { filterArea.width = this.width - localX; } - if (localY + filterArea.height > this.height) { + if (localY + filterArea.height > this.height) + { filterArea.height = this.height - localY; } - if (filterArea.width < 0) { + if (filterArea.width < 0) + { filterArea.width = 0; } - if (filterArea.height < 0) { + if (filterArea.height < 0) + { filterArea.height = 0; } @@ -154,7 +166,8 @@ * Removes the last filter from the filter stack and doesn't return it. * */ -WebGLFilterManager.prototype.popFilter = function () { +WebGLFilterManager.prototype.popFilter = function () +{ var gl = this.renderer.gl; var filterBlock = this.filterStack.pop(); @@ -163,7 +176,8 @@ var projection = this.renderer.projection; var offset = this.renderer.offset; - if (filterBlock.filterPasses.length > 1) { + if (filterBlock.filterPasses.length > 1) + { gl.viewport(0, 0, filterArea.width, filterArea.height); gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); @@ -193,7 +207,8 @@ var inputTexture = texture; var outputTexture = this.texturePool.pop(); - if (!outputTexture) { + if (!outputTexture) + { outputTexture = new FilterTexture(this.renderer.gl, this.width, this.height); } outputTexture.resize(this.width, this.height); @@ -204,7 +219,8 @@ gl.disable(gl.BLEND); - for (var i = 0; i < filterBlock.filterPasses.length-1; i++) { + for (var i = 0; i < filterBlock.filterPasses.length-1; i++) + { var filterPass = filterBlock.filterPasses[i]; gl.bindFramebuffer(gl.FRAMEBUFFER, outputTexture.frameBuffer ); @@ -243,10 +259,12 @@ var buffer = this.buffer; // time to render the filters texture to the previous scene - if (this.filterStack.length === 0) { + if (this.filterStack.length === 0) + { gl.colorMask(true, true, true, true);//this.transparent); } - else { + else + { var currentFilter = this.filterStack[this.filterStack.length-1]; filterArea = currentFilter._filterArea; @@ -332,13 +350,15 @@ * @param width {number} the horizontal range of the filter * @param height {number} the vertical range of the filter */ -WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) { +WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) +{ // use program var gl = this.renderer.gl; var shader = filter.shaders[gl.id]; - if (!shader) { + if (!shader) + { shader = new Shader(gl); shader.fragmentSrc = filter.fragmentSrc; @@ -356,7 +376,8 @@ gl.uniform2f(shader.projectionVector, width/2, -height/2); gl.uniform2f(shader.offsetVector, 0,0); - if (filter.uniforms.dimensions) { + 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]; @@ -386,7 +407,8 @@ * Initialises the shader buffers. * */ -WebGLFilterManager.prototype.initShaderBuffers = function () { +WebGLFilterManager.prototype.initShaderBuffers = function () +{ var gl = this.renderer.gl; // create some buffers @@ -432,7 +454,8 @@ * Destroys the filter and removes it from the filter stack. * */ -WebGLFilterManager.prototype.destroy = function () { +WebGLFilterManager.prototype.destroy = function () +{ var gl = this.renderer.gl; this.filterStack = null; @@ -441,7 +464,8 @@ this.offsetY = 0; // destroy textures - for (var i = 0; i < this.texturePool.length; i++) { + for (var i = 0; i < this.texturePool.length; i++) + { this.texturePool[i].destroy(); } diff --git a/src/core/renderers/webgl/managers/WebGLManager.js b/src/core/renderers/webgl/managers/WebGLManager.js index 9d47b5c..c30cd51 100644 --- a/src/core/renderers/webgl/managers/WebGLManager.js +++ b/src/core/renderers/webgl/managers/WebGLManager.js @@ -3,7 +3,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLManager(renderer) { +function WebGLManager(renderer) +{ /** * The renderer this manager works for. * @@ -15,6 +16,7 @@ WebGLManager.prototype.constructor = WebGLManager; module.exports = WebGLManager; -WebGLManager.prototype.destroy = function () { +WebGLManager.prototype.destroy = function () +{ this.renderer = null; }; diff --git a/src/core/renderers/webgl/managers/WebGLMaskManager.js b/src/core/renderers/webgl/managers/WebGLMaskManager.js index 2f90b64..e568812 100644 --- a/src/core/renderers/webgl/managers/WebGLMaskManager.js +++ b/src/core/renderers/webgl/managers/WebGLMaskManager.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLMaskManager(renderer) { +function WebGLMaskManager(renderer) +{ WebGLManager.call(this, renderer); } @@ -19,12 +20,15 @@ * * @param maskData {any[]} */ -WebGLMaskManager.prototype.pushMask = function (maskData) { - if (maskData.dirty) { +WebGLMaskManager.prototype.pushMask = function (maskData) +{ + if (maskData.dirty) + { WebGLGraphics.updateGraphics(maskData, this.renderer.gl); } - if (!maskData._webGL[this.renderer.gl.id].data.length) { + if (!maskData._webGL[this.renderer.gl.id].data.length) + { return; } @@ -36,6 +40,7 @@ * * @param maskData {any[]} */ -WebGLMaskManager.prototype.popMask = function (maskData) { +WebGLMaskManager.prototype.popMask = function (maskData) +{ this.renderer.stencilManager.popStencil(maskData, maskData._webGL[this.renderer.gl.id].data[0], this.renderer); }; diff --git a/src/core/renderers/webgl/managers/WebGLShaderManager.js b/src/core/renderers/webgl/managers/WebGLShaderManager.js index fef071c..90c6477 100644 --- a/src/core/renderers/webgl/managers/WebGLShaderManager.js +++ b/src/core/renderers/webgl/managers/WebGLShaderManager.js @@ -10,7 +10,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLShaderManager(renderer) { +function WebGLShaderManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -28,7 +29,8 @@ */ this.tempAttribState = []; - for (var i = 0; i < this.maxAttibs; i++) { + for (var i = 0; i < this.maxAttibs; i++) + { this.attribState[i] = false; } @@ -66,7 +68,8 @@ // listen for context and update necessary shaders var self = this; - this.renderer.on('context', function (event) { + this.renderer.on('context', function (event) + { var gl = event.data; // this shader is used for rendering primitives @@ -97,29 +100,36 @@ * * @param attribs {Array} attribs */ -WebGLShaderManager.prototype.setAttribs = function (attribs) { +WebGLShaderManager.prototype.setAttribs = function (attribs) +{ // reset temp state var i; - for (i = 0; i < this.tempAttribState.length; i++) { + for (i = 0; i < this.tempAttribState.length; i++) + { this.tempAttribState[i] = false; } // set the new attribs - for (var a in attribs) { + for (var a in attribs) + { this.tempAttribState[attribs[a]] = true; } var gl = this.renderer.gl; - for (i = 0; i < this.attribState.length; i++) { - if (this.attribState[i] !== this.tempAttribState[i]) { + for (i = 0; i < this.attribState.length; i++) + { + if (this.attribState[i] !== this.tempAttribState[i]) + { this.attribState[i] = this.tempAttribState[i]; - if (this.attribState[i]) { + if (this.attribState[i]) + { gl.enableVertexAttribArray(i); } - else { + else + { gl.disableVertexAttribArray(i); } } @@ -131,8 +141,10 @@ * * @param shader {Any} */ -WebGLShaderManager.prototype.setShader = function (shader) { - if (this._currentId === shader.uuid) { +WebGLShaderManager.prototype.setShader = function (shader) +{ + if (this._currentId === shader.uuid) + { return false; } @@ -150,7 +162,8 @@ * Destroys this object. * */ -WebGLShaderManager.prototype.destroy = function () { +WebGLShaderManager.prototype.destroy = function () +{ this.attribState = null; this.tempAttribState = null; diff --git a/src/core/renderers/webgl/managers/WebGLStencilManager.js b/src/core/renderers/webgl/managers/WebGLStencilManager.js index 9ec6398..4cb0134 100644 --- a/src/core/renderers/webgl/managers/WebGLStencilManager.js +++ b/src/core/renderers/webgl/managers/WebGLStencilManager.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLStencilManager(renderer) { +function WebGLStencilManager(renderer) +{ WebGLManager.call(this, renderer); this.stencilStack = []; @@ -24,12 +25,14 @@ * @param graphics {Graphics} * @param webGLData {any[]} */ -WebGLStencilManager.prototype.pushStencil = function (graphics, webGLData) { +WebGLStencilManager.prototype.pushStencil = function (graphics, webGLData) +{ var gl = this.renderer.gl; this.bindGraphics(graphics, webGLData, this.renderer); - if (this.stencilStack.length === 0) { + if (this.stencilStack.length === 0) + { gl.enable(gl.STENCIL_TEST); gl.clear(gl.STENCIL_BUFFER_BIT); this.reverse = true; @@ -47,14 +50,17 @@ // draw the triangle strip! - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } @@ -62,31 +68,38 @@ // draw a quad to increment.. gl.drawElements(gl.TRIANGLE_FAN, 4, gl.UNSIGNED_SHORT, ( webGLData.indices.length - 4 ) * 2 ); - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); } this.reverse = !this.reverse; } - else { - if (!this.reverse) { + else + { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } - else { + 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) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); } } @@ -103,7 +116,8 @@ * @param graphics {Graphics} * @param webGLData {Array} */ -WebGLStencilManager.prototype.bindGraphics = function (graphics, webGLData) { +WebGLStencilManager.prototype.bindGraphics = function (graphics, webGLData) +{ //if (this._currentGraphics === graphics)return; this._currentGraphics = graphics; @@ -114,7 +128,8 @@ offset = this.renderer.offset, shader;// = this.renderer.shaderManager.primitiveShader; - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { shader = this.renderer.shaderManager.complexPrimitiveShader; this.renderer.shaderManager.setShader(shader); @@ -141,7 +156,8 @@ // set the index buffer! gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, webGLData.indexBuffer); } - else { + else + { //this.renderer.shaderManager.activatePrimitiveShader(); shader = this.renderer.shaderManager.primitiveShader; this.renderer.shaderManager.setShader( shader ); @@ -154,7 +170,7 @@ gl.uniform2f(shader.uniforms.offsetVector._location, -offset.x, -offset.y); gl.uniform3fv(shader.uniforms.tint._location, utils.hex2rgb(graphics.tint)); - + gl.uniform1f(shader.uniforms.alpha._location, graphics.worldAlpha); @@ -172,19 +188,22 @@ * @param graphics {Graphics} * @param webGLData {Array} */ -WebGLStencilManager.prototype.popStencil = function (graphics, webGLData) { +WebGLStencilManager.prototype.popStencil = function (graphics, webGLData) +{ var gl = this.renderer.gl; this.stencilStack.pop(); this.count--; - if (this.stencilStack.length === 0) { + if (this.stencilStack.length === 0) + { // the stack is empty! gl.disable(gl.STENCIL_TEST); } - else { + else + { var level = this.count; @@ -192,14 +211,17 @@ gl.colorMask(false, false, false, false); - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { this.reverse = !this.reverse; - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } @@ -213,31 +235,38 @@ // draw the triangle strip! gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); - if (!this.reverse) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); } } - else { + else + { // console.log("<<>>") - if (!this.reverse) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } - else { + 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) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); } } @@ -253,7 +282,8 @@ * Destroys the mask stack. * */ -WebGLStencilManager.prototype.destroy = function () { +WebGLStencilManager.prototype.destroy = function () +{ this.renderer = null; this.stencilStack = null; }; diff --git a/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js b/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js index 913ba5e..1ea7d19 100644 --- a/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js +++ b/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function ComplexPrimitiveShader(gl) { +function ComplexPrimitiveShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -24,7 +25,8 @@ 'uniform float flipY;', 'varying vec4 vColor;', - 'void main(void) {', + '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);', @@ -37,7 +39,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = vColor;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/FastShader.js b/src/core/renderers/webgl/shaders/FastShader.js index bd2e29a..2e5e060 100644 --- a/src/core/renderers/webgl/shaders/FastShader.js +++ b/src/core/renderers/webgl/shaders/FastShader.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function FastShader(gl) { +function FastShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -28,7 +29,8 @@ 'const vec2 center = vec2(-1.0, 1.0);', - 'void main(void) {', + 'void main(void) + {', ' vec2 v;', ' vec2 sv = aVertexPosition * aScale;', ' v.x = (sv.x) * cos(aRotation) - (sv.y) * sin(aRotation);', @@ -49,7 +51,8 @@ 'uniform sampler2D uSampler;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/PrimitiveShader.js b/src/core/renderers/webgl/shaders/PrimitiveShader.js index 6f25409..a25f54f 100644 --- a/src/core/renderers/webgl/shaders/PrimitiveShader.js +++ b/src/core/renderers/webgl/shaders/PrimitiveShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function PrimitiveShader(gl) { +function PrimitiveShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -23,7 +24,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + '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);', @@ -36,7 +38,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = vColor;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/Shader.js b/src/core/renderers/webgl/shaders/Shader.js index f8964f5..fd75ef5 100644 --- a/src/core/renderers/webgl/shaders/Shader.js +++ b/src/core/renderers/webgl/shaders/Shader.js @@ -6,7 +6,8 @@ * @param [fragmentSrc] {string} The source of the fragment shader. * @param [vertexSrc] {string} The source of the vertex shader. */ -function Shader(gl, vertexSrc, fragmentSrc, customUniforms, customAttributes) { +function Shader(gl, vertexSrc, fragmentSrc, customUniforms, customAttributes) +{ /** * @member {number} * @readonly @@ -33,7 +34,8 @@ dimensions: { type: '4f', value: new Float32Array(4) } }; - for (var u in customUniforms) { + for (var u in customUniforms) + { this.uniforms[u] = customUniforms[u]; } @@ -43,7 +45,8 @@ aColor: 0 }; - for (var a in customAttributes) { + for (var a in customAttributes) + { this.attributes[a] = customAttributes[a]; } @@ -66,7 +69,8 @@ 'const vec2 center = vec2(-1.0, 1.0);', - 'void main(void) {', + 'void main(void) + {', ' gl_Position = vec4( ((aVertexPosition + offsetVector) / projectionVector) + center , 0.0, 1.0);', ' vTextureCoord = aTextureCoord;', ' vColor = vec4(aColor.rgb * aColor.a, aColor.a);', @@ -85,7 +89,8 @@ 'uniform sampler2D uSampler;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;', '}' ].join('\n'); @@ -96,7 +101,8 @@ Shader.prototype.constructor = Shader; module.exports = Shader; -Shader.prototype.init = function () { +Shader.prototype.init = function () +{ this.compile(); this.gl.useProgram(this.program); @@ -105,14 +111,18 @@ this.cacheAttributeLocations(Object.keys(this.attributes)); }; -Shader.prototype.cacheUniformLocations = function (keys) { - for (var i = 0; i < keys.length; ++i) { +Shader.prototype.cacheUniformLocations = function (keys) +{ + for (var i = 0; i < keys.length; ++i) + { this.uniforms[keys[i]]._location = this.gl.getUniformLocation(this.program, keys[i]); } }; -Shader.prototype.cacheAttributeLocations = function (keys) { - for (var i = 0; i < keys.length; ++i) { +Shader.prototype.cacheAttributeLocations = function (keys) +{ + for (var i = 0; i < keys.length; ++i) + { this.attributes[keys[i]] = this.gl.getAttribLocation(this.program, keys[i]); } @@ -124,14 +134,16 @@ // 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.attributes.aColor === -1) { + // if (this.attributes.aColor === -1) + { // this.attributes.aColor = 2; // } // End worst hack eva // }; -Shader.prototype.compile = function () { +Shader.prototype.compile = function () +{ var gl = this.gl; var glVertShader = this._glCompile(gl.VERTEX_SHADER, this.vertexSrc); @@ -144,13 +156,15 @@ gl.linkProgram(program); // if linking fails, then log and cleanup - if (!gl.getProgramParameter(program, gl.LINK_STATUS)) { + if (!gl.getProgramParameter(program, gl.LINK_STATUS)) + { window.console.error('Pixi.js Error: Could not initialize shader.'); window.console.error('gl.VALIDATE_STATUS', gl.getProgramParameter(program, gl.VALIDATE_STATUS)); window.console.error('gl.getError()', gl.getError()); // if there is a program info log, log it - if (gl.getProgramInfoLog(program) !== '') { + if (gl.getProgramInfoLog(program) !== '') + { window.console.warn('Pixi.js Warning: gl.getProgramInfoLog()', gl.getProgramInfoLog(program)); } @@ -165,18 +179,21 @@ return (this.program = program); }; -Shader.prototype.syncUniforms = function () { +Shader.prototype.syncUniforms = function () +{ var gl = this.gl; this.textureCount = 1; - for (var key in this.uniforms) { + for (var key in this.uniforms) + { var uniform = this.uniforms[key], location = uniform._location, value = uniform.value, i, il; - switch (uniform.type) { + switch (uniform.type) + { // single int value case 'i': case '1i': @@ -282,7 +299,8 @@ // a Color Value case 'c': - if (typeof value === 'number') { + if (typeof value === 'number') + { value = utils.hex2rgb(value); } @@ -311,11 +329,13 @@ // array of 2D Point objects case 'v2v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(2 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 2] = value[i].x; uniform._array[i * 2 + 1] = value[i].y; } @@ -325,11 +345,13 @@ // array of 3D Point objects case 'v3v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(3 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 3] = value[i].x; uniform._array[i * 3 + 1] = value[i].y; uniform._array[i * 3 + 2] = value[i].z; @@ -341,11 +363,13 @@ // array of 4D Point objects case 'v4v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(4 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 4] = value[i].x; uniform._array[i * 4 + 1] = value[i].y; uniform._array[i * 4 + 2] = value[i].z; @@ -359,7 +383,8 @@ // PIXI.Texture case 't': case 'sampler2D': - if (!uniform.value || !uniform.value.baseTexture || !uniform.value.baseTexture.hasLoaded) { + if (!uniform.value || !uniform.value.baseTexture || !uniform.value.baseTexture.hasLoaded) + { break; } @@ -376,7 +401,8 @@ this.textureCount++; // initialize the texture if we haven't yet - if (!uniform._init) { + if (!uniform._init) + { this.initSampler2D(uniform); uniform._init = true; @@ -394,11 +420,13 @@ * Initialises a Sampler2D uniform (which may only be available later on after initUniforms once the texture has loaded) * */ -Shader.prototype.initSampler2D = function (uniform) { +Shader.prototype.initSampler2D = function (uniform) +{ var gl = this.gl; // Extended texture data - if (uniform.textureData) { + if (uniform.textureData) + { var data = uniform.textureData; // GLTexture = mag linear, min linear_mipmap_linear, wrap repeat + gl.generateMipmap(gl.TEXTURE_2D); @@ -417,14 +445,16 @@ var wrapT = (data.wrapT) ? data.wrapT : gl.CLAMP_TO_EDGE; var format = (data.luminance) ? gl.LUMINANCE : gl.RGBA; - if (data.repeat) { + if (data.repeat) + { wrapS = gl.REPEAT; wrapT = gl.REPEAT; } gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, !!data.flipY); - if (data.width) { + if (data.width) + { var width = (data.width) ? data.width : 512; var height = (data.height) ? data.height : 2; var border = (data.border) ? data.border : 0; @@ -432,7 +462,8 @@ // 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 { + 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); } @@ -448,7 +479,8 @@ * Destroys the shader. * */ -Shader.prototype.destroy = function () { +Shader.prototype.destroy = function () +{ this.gl.deleteProgram(this.program); this.gl = null; @@ -459,13 +491,15 @@ this.fragmentSrc = null; }; -Shader.prototype._glCompile = function (type, src) { +Shader.prototype._glCompile = function (type, src) +{ var shader = this.gl.createShader(type); this.gl.shaderSource(shader, src); this.gl.compileShader(shader); - if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) { + if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) + { window.console.log(this.gl.getShaderInfoLog(shader)); return null; } diff --git a/src/core/renderers/webgl/shaders/StripShader.js b/src/core/renderers/webgl/shaders/StripShader.js index 193f6e1..a7abcc6 100644 --- a/src/core/renderers/webgl/shaders/StripShader.js +++ b/src/core/renderers/webgl/shaders/StripShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function StripShader(gl) { +function StripShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -20,7 +21,8 @@ 'varying vec2 vTextureCoord;', - 'void main(void) {', + '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);', @@ -36,7 +38,8 @@ 'varying vec2 vTextureCoord;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vec2(vTextureCoord.x, vTextureCoord.y)) * alpha;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/utils/FilterTexture.js b/src/core/renderers/webgl/utils/FilterTexture.js index d2c8423..4433d44 100644 --- a/src/core/renderers/webgl/utils/FilterTexture.js +++ b/src/core/renderers/webgl/utils/FilterTexture.js @@ -8,7 +8,8 @@ * @param height {number} the vertical range of the filter * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values */ -function FilterTexture(gl, width, height, scaleMode) { +function FilterTexture(gl, width, height, scaleMode) +{ /** * @member {WebGLContext} */ @@ -59,7 +60,8 @@ * Clears the filter texture. * */ -FilterTexture.prototype.clear = function () { +FilterTexture.prototype.clear = function () +{ var gl = this.gl; gl.clearColor(0,0,0, 0); @@ -72,8 +74,10 @@ * @param width {number} the new width of the texture * @param height {number} the new height of the texture */ -FilterTexture.prototype.resize = function (width, height) { - if (this.width === width && this.height === height) { +FilterTexture.prototype.resize = function (width, height) +{ + if (this.width === width && this.height === height) + { return; } @@ -96,7 +100,8 @@ * Destroys the filter texture. * */ -FilterTexture.prototype.destroy = function () { +FilterTexture.prototype.destroy = function () +{ var gl = this.gl; gl.deleteFramebuffer( this.frameBuffer ); gl.deleteTexture( this.texture ); diff --git a/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js b/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js index c4721e9..a63f4d7 100644 --- a/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js +++ b/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js @@ -14,7 +14,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this sprite batch works for. */ -function WebGLFastSpriteBatch(renderer) { +function WebGLFastSpriteBatch(renderer) +{ /** * The renderer instance this sprite batch operates on. * @@ -91,7 +92,8 @@ */ this.lastIndexCount = 0; - for (var i=0, j=0; i < numIndices; i += 6, j += 4) { + 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; @@ -144,7 +146,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.setupContext(); }); } @@ -157,7 +160,8 @@ * * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLFastSpriteBatch.prototype.setupContext = function () { +WebGLFastSpriteBatch.prototype.setupContext = function () +{ var gl = this.renderer.gl; // create a couple of buffers @@ -177,7 +181,8 @@ /** * @param spriteBatch {SpriteBatch} The SpriteBatch container to prepare for. */ -WebGLFastSpriteBatch.prototype.begin = function (spriteBatch) { +WebGLFastSpriteBatch.prototype.begin = function (spriteBatch) +{ this.shader = this.renderer.shaderManager.fastShader; this.matrix = spriteBatch.worldTransform.toArray(true); @@ -187,33 +192,38 @@ /** */ -WebGLFastSpriteBatch.prototype.end = function () { +WebGLFastSpriteBatch.prototype.end = function () +{ this.flush(); }; /** * @param spriteBatch {SpriteBatch} The SpriteBatch container to render. */ -WebGLFastSpriteBatch.prototype.render = function (spriteBatch) { +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) { + if (!sprite.texture._uvs) + { return; } this.currentBaseTexture = sprite.texture.baseTexture; // check blend mode - if (sprite.blendMode !== this.renderer.blendModeManager.currentBlendMode) { + if (sprite.blendMode !== this.renderer.blendModeManager.currentBlendMode) + { this.flush(); this.renderer.blendModeManager.setBlendMode(sprite.blendMode); } - for (var i=0,j= children.length; i= this.size) { + if (this.currentBatchSize >= this.size) + { this.flush(); } }; @@ -362,29 +379,35 @@ /** * */ -WebGLFastSpriteBatch.prototype.flush = function () { +WebGLFastSpriteBatch.prototype.flush = function () +{ // If the batch is length 0 then return as there is nothing to draw - if (this.currentBatchSize === 0) { + if (this.currentBatchSize === 0) + { return; } var gl = this.renderer.gl; // bind the current texture - if (!this.currentBaseTexture._glTextures[gl.id]) { + if (!this.currentBaseTexture._glTextures[gl.id]) + { this.renderer.updateTexture(this.currentBaseTexture, gl); } //TODO-SHOUD THIS BE ELSE??!?!?! - else { + else + { gl.bindTexture(gl.TEXTURE_2D, this.currentBaseTexture._glTextures[gl.id]); } // upload the verts to the buffer - if (this.currentBatchSize > ( this.size * 0.5 ) ) { + if (this.currentBatchSize > ( this.size * 0.5 ) ) + { gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); } - else { + else + { var view = this.vertices.subarray(0, this.currentBatchSize * this.vertByteSize); gl.bufferSubData(gl.ARRAY_BUFFER, 0, view); @@ -405,14 +428,16 @@ * Ends the batch and flushes * */ -WebGLFastSpriteBatch.prototype.stop = function () { +WebGLFastSpriteBatch.prototype.stop = function () +{ this.flush(); }; /** * */ -WebGLFastSpriteBatch.prototype.start = function () { +WebGLFastSpriteBatch.prototype.start = function () +{ var gl = this.renderer.gl; // bind the main texture diff --git a/src/core/renderers/webgl/utils/WebGLGraphics.js b/src/core/renderers/webgl/utils/WebGLGraphics.js index 55f4911..ab8f46e 100644 --- a/src/core/renderers/webgl/utils/WebGLGraphics.js +++ b/src/core/renderers/webgl/utils/WebGLGraphics.js @@ -19,7 +19,8 @@ * @param graphics {Graphics} * @param renderer {WebGLRenderer} */ -WebGLGraphics.renderGraphics = function (graphics, renderer) {//projection, offset) { +WebGLGraphics.renderGraphics = function (graphics, renderer) {//projection, offset) +{ var gl = renderer.gl; var projection = renderer.projection, @@ -27,7 +28,8 @@ shader = renderer.shaderManager.primitiveShader, webGLData; - if (graphics.dirty) { + if (graphics.dirty) + { WebGLGraphics.updateGraphics(graphics, gl); } @@ -35,8 +37,10 @@ // This could be speeded up for sure! - for (var i = 0; i < webGL.data.length; i++) { - if (webGL.data[i].mode === 1) { + for (var i = 0; i < webGL.data.length; i++) + { + if (webGL.data[i].mode === 1) + { webGLData = webGL.data[i]; renderer.stencilManager.pushStencil(graphics, webGLData, renderer); @@ -46,7 +50,8 @@ renderer.stencilManager.popStencil(graphics, webGLData, renderer); } - else { + else + { webGLData = webGL.data[i]; @@ -84,12 +89,14 @@ * @param graphicsData {Graphics} The graphics object to update * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLGraphics.updateGraphics = function (graphics, gl) { +WebGLGraphics.updateGraphics = function (graphics, gl) +{ // get the contexts graphics object var webGL = graphics._webGL[gl.id]; // if the graphics object does not exist in the webGL context time to create it! - if (!webGL) { + if (!webGL) + { webGL = graphics._webGL[gl.id] = {lastIndex:0, data:[], gl:gl}; } @@ -99,11 +106,13 @@ var i; // if the user cleared the graphics object we will need to clear every object - if (graphics.clearDirty) { + if (graphics.clearDirty) + { graphics.clearDirty = false; // lop through and return all the webGLDatas to the object pool so than can be reused later on - for (i = 0; i < webGL.data.length; i++) { + for (i = 0; i < webGL.data.length; i++) + { var graphicsData = webGL.data[i]; graphicsData.reset(); WebGLGraphics.graphicsDataPool.push( graphicsData ); @@ -119,58 +128,72 @@ // loop through the graphics datas and construct each one.. // if the object is a complex fill then the new stencil buffer technique will be used // other wise graphics objects will be pushed into a batch.. - for (i = webGL.lastIndex; i < graphics.graphicsData.length; i++) { + for (i = webGL.lastIndex; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { // need to add the points the the graphics object.. data.points = data.shape.points.slice(); - if (data.shape.closed) { + if (data.shape.closed) + { // close the poly if the value is true! - if (data.points[0] !== data.points[data.points.length-2] || data.points[1] !== data.points[data.points.length-1]) { + if (data.points[0] !== data.points[data.points.length-2] || data.points[1] !== data.points[data.points.length-1]) + { data.points.push(data.points[0], data.points[1]); } } // MAKE SURE WE HAVE THE CORRECT TYPE.. - if (data.fill) { - if (data.points.length >= 6) { - if (data.points.length < 6 * 2) { + if (data.fill) + { + if (data.points.length >= 6) + { + if (data.points.length < 6 * 2) + { webGLData = WebGLGraphics.switchMode(webGL, 0); var canDrawUsingSimple = WebGLGraphics.buildPoly(data, webGLData); // console.log(canDrawUsingSimple); - if (!canDrawUsingSimple) { + if (!canDrawUsingSimple) + { // console.log("<>>>") webGLData = WebGLGraphics.switchMode(webGL, 1); WebGLGraphics.buildComplexPoly(data, webGLData); } } - else { + else + { webGLData = WebGLGraphics.switchMode(webGL, 1); WebGLGraphics.buildComplexPoly(data, webGLData); } } } - if (data.lineWidth > 0) { + if (data.lineWidth > 0) + { webGLData = WebGLGraphics.switchMode(webGL, 0); WebGLGraphics.buildLine(data, webGLData); } } - else { + else + { webGLData = WebGLGraphics.switchMode(webGL, 0); - if (data.type === CONST.SHAPES.RECT) { + if (data.type === CONST.SHAPES.RECT) + { WebGLGraphics.buildRectangle(data, webGLData); } - else if (data.type === CONST.SHAPES.CIRC || data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.CIRC || data.type === CONST.SHAPES.ELIP) + { WebGLGraphics.buildCircle(data, webGLData); } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { WebGLGraphics.buildRoundedRectangle(data, webGLData); } } @@ -179,10 +202,12 @@ } // upload all the dirty data... - for (i = 0; i < webGL.data.length; i++) { + for (i = 0; i < webGL.data.length; i++) + { webGLData = webGL.data[i]; - if (webGLData.dirty) { + if (webGLData.dirty) + { webGLData.upload(); } } @@ -194,18 +219,22 @@ * @param webGL {WebGLContext} * @param type {number} */ -WebGLGraphics.switchMode = function (webGL, type) { +WebGLGraphics.switchMode = function (webGL, type) +{ var webGLData; - if (!webGL.data.length) { + if (!webGL.data.length) + { webGLData = WebGLGraphics.graphicsDataPool.pop() || new WebGLGraphicsData(webGL.gl); webGLData.mode = type; webGL.data.push(webGLData); } - else { + else + { webGLData = webGL.data[webGL.data.length-1]; - if (webGLData.mode !== type || type === 1) { + if (webGLData.mode !== type || type === 1) + { webGLData = WebGLGraphics.graphicsDataPool.pop() || new WebGLGraphicsData(webGL.gl); webGLData.mode = type; webGL.data.push(webGLData); @@ -225,7 +254,8 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildRectangle = function (graphicsData, webGLData) { +WebGLGraphics.buildRectangle = function (graphicsData, webGLData) +{ // --- // // need to convert points to a nice regular data // @@ -235,7 +265,8 @@ var width = rectData.width; var height = rectData.height; - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -265,7 +296,8 @@ indices.push(vertPos, vertPos, vertPos+1, vertPos+2, vertPos+3, vertPos+3); } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = [x, y, @@ -289,7 +321,8 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildRoundedRectangle = function (graphicsData, webGLData) { +WebGLGraphics.buildRoundedRectangle = function (graphicsData, webGLData) +{ var rrectData = graphicsData.shape; var x = rrectData.x; var y = rrectData.y; @@ -305,7 +338,8 @@ recPoints = recPoints.concat(WebGLGraphics.quadraticBezierCurve(x + width, y + radius, x + width, y, x + width - radius, y)); recPoints = recPoints.concat(WebGLGraphics.quadraticBezierCurve(x + radius, y, x, y, x, y + radius)); - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -323,7 +357,8 @@ // var i = 0; - for (i = 0; i < triangles.length; i+=3) { + for (i = 0; i < triangles.length; i+=3) + { indices.push(triangles[i] + vecPos); indices.push(triangles[i] + vecPos); indices.push(triangles[i+1] + vecPos); @@ -332,12 +367,14 @@ } - for (i = 0; i < recPoints.length; i++) { + for (i = 0; i < recPoints.length; i++) + { verts.push(recPoints[i], recPoints[++i], r, g, b, alpha); } } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = recPoints; @@ -362,7 +399,8 @@ * @param toY {number} Destination point y * @return {number[]} */ -WebGLGraphics.quadraticBezierCurve = function (fromX, fromY, cpX, cpY, toX, toY) { +WebGLGraphics.quadraticBezierCurve = function (fromX, fromY, cpX, cpY, toX, toY) +{ var xa, ya, @@ -373,14 +411,16 @@ n = 20, points = []; - function getPt(n1 , n2, perc) { + function getPt(n1 , n2, perc) + { var diff = n2 - n1; return n1 + ( diff * perc ); } var j = 0; - for (var i = 0; i <= n; i++ ) { + for (var i = 0; i <= n; i++ ) + { j = i / n; // The Green Line @@ -406,7 +446,8 @@ * @param graphicsData {Graphics} The graphics object to draw * @param webGLData {object} */ -WebGLGraphics.buildCircle = function (graphicsData, webGLData) { +WebGLGraphics.buildCircle = function (graphicsData, webGLData) +{ // need to convert points to a nice regular data var circleData = graphicsData.shape; var x = circleData.x; @@ -415,11 +456,13 @@ var height; // TODO - bit hacky?? - if (graphicsData.type === CONST.SHAPES.CIRC) { + if (graphicsData.type === CONST.SHAPES.CIRC) + { width = circleData.radius; height = circleData.radius; } - else { + else + { width = circleData.width; height = circleData.height; } @@ -429,7 +472,8 @@ var i = 0; - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -444,7 +488,8 @@ indices.push(vecPos); - for (i = 0; i < totalSegs + 1 ; i++) { + for (i = 0; i < totalSegs + 1 ; i++) + { verts.push(x,y, r, g, b, alpha); verts.push(x + Math.sin(seg * i) * width, @@ -457,12 +502,14 @@ indices.push(vecPos-1); } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = []; - for (i = 0; i < totalSegs + 1; i++) { + for (i = 0; i < totalSegs + 1; i++) + { graphicsData.points.push(x + Math.sin(seg * i) * width, y + Math.cos(seg * i) * height); } @@ -481,18 +528,22 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildLine = function (graphicsData, webGLData) { +WebGLGraphics.buildLine = function (graphicsData, webGLData) +{ // TODO OPTIMISE! var i = 0; var points = graphicsData.points; - if (points.length === 0) { + if (points.length === 0) + { return; } // if the line width is an odd number add 0.5 to align to a whole pixel - if (graphicsData.lineWidth%2) { - for (i = 0; i < points.length; i++) { + if (graphicsData.lineWidth%2) + { + for (i = 0; i < points.length; i++) + { points[i] += 0.5; } } @@ -502,7 +553,8 @@ var lastPoint = new math.Point(points[points.length - 2], points[points.length - 1]); // if the first point is the last point - gonna have issues :) - if (firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) { + if (firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) + { // need to clone as we are going to slightly modify the shape.. points = points.slice(); @@ -562,7 +614,8 @@ verts.push(p1x + perpx , p1y + perpy, r, g, b, alpha); - for (i = 1; i < length-1; i++) { + for (i = 1; i < length-1; i++) + { p1x = points[(i-1)*2]; p1y = points[(i-1)*2 + 1]; @@ -599,7 +652,8 @@ denom = a1*b2 - a2*b1; - if (Math.abs(denom) < 0.1 ) { + if (Math.abs(denom) < 0.1 ) + { denom+=10.1; verts.push(p2x - perpx , p2y - perpy, @@ -618,7 +672,8 @@ pdist = (px -p2x) * (px -p2x) + (py -p2y) + (py -p2y); - if (pdist > 140 * 140) { + if (pdist > 140 * 140) + { perp3x = perpx - perp2x; perp3y = perpy - perp2y; @@ -639,7 +694,8 @@ indexCount++; } - else { + else + { verts.push(px , py); verts.push(r, g, b, alpha); @@ -672,7 +728,8 @@ indices.push(indexStart); - for (i = 0; i < indexCount; i++) { + for (i = 0; i < indexCount; i++) + { indices.push(indexStart++); } @@ -687,11 +744,13 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildComplexPoly = function (graphicsData, webGLData) { +WebGLGraphics.buildComplexPoly = function (graphicsData, webGLData) +{ //TODO - no need to copy this as it gets turned into a FLoat32Array anyways.. var points = graphicsData.points.slice(); - if (points.length < 6) { + if (points.length < 6) + { return; } @@ -711,7 +770,8 @@ var x,y; // get size.. - for (var i = 0; i < points.length; i+=2) { + for (var i = 0; i < points.length; i+=2) + { x = points[i]; y = points[i+1]; @@ -732,7 +792,8 @@ //TODO - this aint needed! var length = points.length / 2; - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { indices.push( i ); } @@ -746,10 +807,12 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildPoly = function (graphicsData, webGLData) { +WebGLGraphics.buildPoly = function (graphicsData, webGLData) +{ var points = graphicsData.points; - if (points.length < 6) { + if (points.length < 6) + { return; } // get first and last point.. figure out the middle! @@ -767,7 +830,8 @@ var triangles = utils.PolyK.Triangulate(points); - if (!triangles) { + if (!triangles) + { return false; } @@ -775,7 +839,8 @@ var i = 0; - for (i = 0; i < triangles.length; i+=3) { + for (i = 0; i < triangles.length; i+=3) + { indices.push(triangles[i] + vertPos); indices.push(triangles[i] + vertPos); indices.push(triangles[i+1] + vertPos); @@ -783,7 +848,8 @@ indices.push(triangles[i+2] + vertPos); } - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { verts.push(points[i * 2], points[i * 2 + 1], r, g, b, alpha); } diff --git a/src/core/renderers/webgl/utils/WebGLGraphicsData.js b/src/core/renderers/webgl/utils/WebGLGraphicsData.js index c56d05e..c739ba7 100644 --- a/src/core/renderers/webgl/utils/WebGLGraphicsData.js +++ b/src/core/renderers/webgl/utils/WebGLGraphicsData.js @@ -2,7 +2,8 @@ * @class * @private */ -function WebGLGraphicsData(gl) { +function WebGLGraphicsData(gl) +{ this.gl = gl; //TODO does this need to be split before uploding?? @@ -22,7 +23,8 @@ /** * */ -WebGLGraphicsData.prototype.reset = function () { +WebGLGraphicsData.prototype.reset = function () +{ this.points.length = 0; this.indices.length = 0; }; @@ -30,7 +32,8 @@ /** * */ -WebGLGraphicsData.prototype.upload = function () { +WebGLGraphicsData.prototype.upload = function () +{ var gl = this.gl; // this.lastIndex = graphics.graphicsData.length; diff --git a/src/core/renderers/webgl/utils/WebGLSpriteBatch.js b/src/core/renderers/webgl/utils/WebGLSpriteBatch.js index 96eaa52..55befbb 100644 --- a/src/core/renderers/webgl/utils/WebGLSpriteBatch.js +++ b/src/core/renderers/webgl/utils/WebGLSpriteBatch.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this sprite batch works for. */ -function WebGLSpriteBatch(renderer) { +function WebGLSpriteBatch(renderer) +{ /** * * @@ -88,7 +89,8 @@ */ this.lastIndexCount = 0; - for (var i=0, j=0; i < numIndices; i += 6, j += 4) { + 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; @@ -162,7 +164,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.setupContext(); }); } @@ -173,7 +176,8 @@ /** * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLSpriteBatch.prototype.setupContext = function () { +WebGLSpriteBatch.prototype.setupContext = function () +{ var gl = this.renderer.gl; // setup default shader @@ -198,7 +202,8 @@ /** * */ -WebGLSpriteBatch.prototype.begin = function () { +WebGLSpriteBatch.prototype.begin = function () +{ // this.shader = this.renderer.shaderManager.defaultShader; this.start(); @@ -206,19 +211,22 @@ /** */ -WebGLSpriteBatch.prototype.end = function () { +WebGLSpriteBatch.prototype.end = function () +{ this.flush(); }; /** * @param sprite {Sprite} the sprite to render when using this spritebatch */ -WebGLSpriteBatch.prototype.render = function (sprite) { +WebGLSpriteBatch.prototype.render = function (sprite) +{ var texture = sprite.texture; //TODO set blend modes.. // check texture.. - if (this.currentBatchSize >= this.size) { + if (this.currentBatchSize >= this.size) + { this.flush(); this.currentBaseTexture = texture.baseTexture; } @@ -227,7 +235,8 @@ var uvs = texture._uvs; // if the uvs have not updated then no point rendering just yet! - if (!uvs) { + if (!uvs) + { return; } @@ -237,7 +246,8 @@ var w0, w1, h0, h1; - if (texture.trim) { + 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; @@ -248,7 +258,8 @@ h0 = h1 + texture.crop.height; } - else { + else + { w0 = (texture.frame.width ) * (1-aX); w1 = (texture.frame.width ) * -aX; @@ -272,7 +283,8 @@ var colors = this.colors; var positions = this.positions; - if (this.renderer.roundPixels) { + if (this.renderer.roundPixels) + { // xy positions[index] = a * w1 + c * h1 + tx | 0; positions[index+1] = d * h1 + b * w1 + ty | 0; @@ -289,7 +301,8 @@ positions[index+15] = a * w1 + c * h0 + tx | 0; positions[index+16] = d * h0 + b * w1 + ty | 0; } - else { + else + { // xy positions[index] = a * w1 + c * h1 + tx; positions[index+1] = d * h1 + b * w1 + ty; @@ -338,11 +351,13 @@ * * @param sprite {TilingSprite} the tilingSprite to render */ -WebGLSpriteBatch.prototype.renderTilingSprite = function (tilingSprite) { +WebGLSpriteBatch.prototype.renderTilingSprite = function (tilingSprite) +{ var texture = tilingSprite.tilingTexture; // check texture.. - if (this.currentBatchSize >= this.size) { + if (this.currentBatchSize >= this.size) + { //return; this.flush(); this.currentBaseTexture = texture.baseTexture; @@ -351,7 +366,8 @@ // set the textures uvs temporarily // TODO create a separate texture so that we can tile part of a texture - if (!tilingSprite._uvs) { + if (!tilingSprite._uvs) + { tilingSprite._uvs = new TextureUvs(); } @@ -454,16 +470,19 @@ * Renders the content and empties the current batch. * */ -WebGLSpriteBatch.prototype.flush = function () { +WebGLSpriteBatch.prototype.flush = function () +{ // If the batch is length 0 then return as there is nothing to draw - if (this.currentBatchSize === 0) { + if (this.currentBatchSize === 0) + { return; } var gl = this.renderer.gl; var shader; - if (this.dirty) { + if (this.dirty) + { this.dirty = false; // bind the main texture gl.activeTexture(gl.TEXTURE0); @@ -482,10 +501,12 @@ } // upload the verts to the buffer - if (this.currentBatchSize > ( this.size * 0.5 ) ) { + if (this.currentBatchSize > ( this.size * 0.5 ) ) + { gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); } - else { + else + { var view = this.positions.subarray(0, this.currentBatchSize * this.vertByteSize); gl.bufferSubData(gl.ARRAY_BUFFER, 0, view); } @@ -502,7 +523,8 @@ var shaderSwap = false; var sprite; - for (var i = 0, j = this.currentBatchSize; i < j; i++) { + for (var i = 0, j = this.currentBatchSize; i < j; i++) + { sprite = this.sprites[i]; @@ -513,24 +535,28 @@ blendSwap = currentBlendMode !== nextBlendMode; shaderSwap = currentShader !== nextShader; // should I use uuidS??? - if (currentBaseTexture !== nextTexture || blendSwap || shaderSwap) { + if (currentBaseTexture !== nextTexture || blendSwap || shaderSwap) + { this.renderBatch(currentBaseTexture, batchSize, start); start = i; batchSize = 0; currentBaseTexture = nextTexture; - if (blendSwap) { + if (blendSwap) + { currentBlendMode = nextBlendMode; this.renderer.blendModeManager.setBlendMode( currentBlendMode ); } - if (shaderSwap) { + if (shaderSwap) + { currentShader = nextShader; shader = currentShader.shaders ? currentShader.shaders[gl.id] : currentShader; - if (!shader) { + if (!shader) + { shader = new Shader(gl, null, currentShader.fragmentSrc, currentShader.uniforms); currentShader.shaders[gl.id] = shader; } @@ -538,7 +564,8 @@ // set shader function??? this.renderer.shaderManager.setShader(shader); - if (shader.dirty) { + if (shader.dirty) + { shader.syncUniforms(); } @@ -569,17 +596,21 @@ * @param size {number} * @param startIndex {number} */ -WebGLSpriteBatch.prototype.renderBatch = function (texture, size, startIndex) { - if (size === 0) { +WebGLSpriteBatch.prototype.renderBatch = function (texture, size, startIndex) +{ + if (size === 0) + { return; } var gl = this.renderer.gl; - if (!texture._glTextures[gl.id]) { + if (!texture._glTextures[gl.id]) + { this.renderer.updateTexture(texture); } - else { + else + { // bind the current texture gl.bindTexture(gl.TEXTURE_2D, texture._glTextures[gl.id]); } @@ -594,7 +625,8 @@ /** * */ -WebGLSpriteBatch.prototype.stop = function () { +WebGLSpriteBatch.prototype.stop = function () +{ this.flush(); this.dirty = true; }; @@ -602,7 +634,8 @@ /** * */ -WebGLSpriteBatch.prototype.start = function () { +WebGLSpriteBatch.prototype.start = function () +{ this.dirty = true; }; @@ -610,7 +643,8 @@ * Destroys the SpriteBatch. * */ -WebGLSpriteBatch.prototype.destroy = function () { +WebGLSpriteBatch.prototype.destroy = function () +{ this.renderer.gl.deleteBuffer(this.vertexBuffer); this.renderer.gl.deleteBuffer(this.indexBuffer); diff --git a/src/core/textures/BaseTexture.js b/src/core/textures/BaseTexture.js index 2bf77d4..513d358 100644 --- a/src/core/textures/BaseTexture.js +++ b/src/core/textures/BaseTexture.js @@ -10,7 +10,8 @@ * @param source {Image|Canvas} the source object of the texture. * @param [scaleMode=scaleModes.DEFAULT] {number} See {@link scaleModes} for possible values */ -function BaseTexture(source, scaleMode) { +function BaseTexture(source, scaleMode) +{ this.uuid = utils.uuid(); /** @@ -123,7 +124,8 @@ this._needsUpdate = false; // if no source passed don't try to load - if (source) { + if (source) + { this.loadSource(source); } @@ -149,13 +151,16 @@ Object.defineProperties(BaseTexture.prototype, { needsUpdate: { - get: function () { + get: function () + { return this._needsUpdate; }, - set: function (val) { + set: function (val) + { this._needsUpdate = val; - if (val) { + if (val) + { this.emit('update', this); } } @@ -171,9 +176,11 @@ * * The logic state after calling `loadSource` directly or indirectly (eg. `fromImage`, `new BaseTexture`) is: * - * if (texture.hasLoaded) { + * if (texture.hasLoaded) + { * // texture ready for use - * } else if (texture.isLoading) { + * } else if (texture.isLoading) + { * // listen to 'loaded' and/or 'error' events on texture * } else { * // not loading, not going to load UNLESS the source is reloaded @@ -183,12 +190,14 @@ * @protected * @param source {Image|Canvas} the source object of the texture. */ -BaseTexture.prototype.loadSource = function (source) { +BaseTexture.prototype.loadSource = function (source) +{ var wasLoading = this.isLoading; this.hasLoaded = false; this.isLoading = false; - if (wasLoading && this.source) { + if (wasLoading && this.source) + { this.source.onload = null; this.source.onerror = null; } @@ -196,20 +205,24 @@ this.source = source; // Apply source if loaded. Otherwise setup appropriate loading monitors. - if ((this.source.complete || this.source.getContext) && this.source.width && this.source.height) { + if ((this.source.complete || this.source.getContext) && this.source.width && this.source.height) + { this._sourceLoaded(); } - else if(!source.getContext) { + else if(!source.getContext) + { // Image fail / not ready this.isLoading = true; var scope = this; - source.onload = function () { + source.onload = function () + { source.onload = null; source.onerror = null; - if(!scope.isLoading) { + if(!scope.isLoading) + { return; } @@ -219,11 +232,13 @@ scope.emit('loaded', scope); }; - source.onerror = function () { + source.onerror = function () + { source.onload = null; source.onerror = null; - if(!scope.isLoading) { + if(!scope.isLoading) + { return; } @@ -234,24 +249,29 @@ // Per http://www.w3.org/TR/html5/embedded-content-0.html#the-img-element // "The value of `complete` can thus change while a script is executing." // So complete needs to be re-checked after the callbacks have been added.. - if (source.complete) { + if (source.complete) + { this.isLoading = false; // ..and if we're complete now, no need for callbacks source.onload = null; source.onerror = null; - if (source.width && source.height) { + if (source.width && source.height) + { this._sourceLoaded(); // If any previous subscribers possible - if (wasLoading) { + if (wasLoading) + { this.emit('loaded', this); } } - else { + else + { // If any previous subscribers possible - if (wasLoading) { + if (wasLoading) + { this.emit('error', this); } } @@ -265,7 +285,8 @@ * * @private */ -BaseTexture.prototype._sourceLoaded = function () { +BaseTexture.prototype._sourceLoaded = function () +{ this.hasLoaded = true; this.width = this.source.naturalWidth || this.source.width; @@ -278,16 +299,20 @@ * Destroys this base texture * */ -BaseTexture.prototype.destroy = function () { - if (this.imageUrl) { +BaseTexture.prototype.destroy = function () +{ + if (this.imageUrl) + { delete utils.BaseTextureCache[this.imageUrl]; delete utils.TextureCache[this.imageUrl]; this.imageUrl = null; - if (!navigator.isCocoonJS) { + if (!navigator.isCocoonJS) + { this.source.src = ''; } } - else if (this.source && this.source._pixiId) { + else if (this.source && this.source._pixiId) + { delete utils.BaseTextureCache[this.source._pixiId]; } this.source = null; @@ -301,7 +326,8 @@ * memory again. * */ -BaseTexture.prototype.dispose = function () { +BaseTexture.prototype.dispose = function () +{ this.emit('dispose', this); }; @@ -311,7 +337,8 @@ * * @param newSrc {string} the path of the image */ -BaseTexture.prototype.updateSourceImage = function (newSrc) { +BaseTexture.prototype.updateSourceImage = function (newSrc) +{ this.source.src = newSrc; this.loadSource(this.source); }; @@ -326,18 +353,22 @@ * @param [scaleMode=scaleModes.DEFAULT] {number} See {@link scaleModes} for possible values * @return BaseTexture */ -BaseTexture.fromImage = function (imageUrl, crossorigin, scaleMode) { +BaseTexture.fromImage = function (imageUrl, crossorigin, scaleMode) +{ var baseTexture = utils.BaseTextureCache[imageUrl]; - if (crossorigin === undefined && imageUrl.indexOf('data:') !== 0) { + if (crossorigin === undefined && imageUrl.indexOf('data:') !== 0) + { crossorigin = true; } - if (!baseTexture) { + if (!baseTexture) + { // new Image() breaks tex loading in some versions of Chrome. // See https://code.google.com/p/chromium/issues/detail?id=238071 var image = new Image();//document.createElement('img'); - if (crossorigin) { + if (crossorigin) + { image.crossOrigin = ''; } @@ -347,7 +378,8 @@ utils.BaseTextureCache[imageUrl] = baseTexture; // if there is an @2x at the end of the url we are going to assume its a highres image - if ( imageUrl.indexOf(CONST.RETINA_PREFIX + '.') !== -1) { + if ( imageUrl.indexOf(CONST.RETINA_PREFIX + '.') !== -1) + { baseTexture.resolution = 2; } } @@ -363,14 +395,17 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return BaseTexture */ -BaseTexture.fromCanvas = function (canvas, scaleMode) { - if (!canvas._pixiId) { +BaseTexture.fromCanvas = function (canvas, scaleMode) +{ + if (!canvas._pixiId) + { canvas._pixiId = 'canvas_' + utils.uuid(); } var baseTexture = utils.BaseTextureCache[canvas._pixiId]; - if (!baseTexture) { + if (!baseTexture) + { baseTexture = new BaseTexture(canvas, scaleMode); utils.BaseTextureCache[canvas._pixiId] = baseTexture; } diff --git a/src/core/textures/RenderTexture.js b/src/core/textures/RenderTexture.js index 6dad20f..53ae796 100644 --- a/src/core/textures/RenderTexture.js +++ b/src/core/textures/RenderTexture.js @@ -46,8 +46,10 @@ * @param [scaleMode] {number} See {@link scaleModes} for possible values * @param [resolution=1] {number} The resolution of the texture being generated */ -function RenderTexture(renderer, width, height, scaleMode, resolution) { - if (!renderer) { +function RenderTexture(renderer, width, height, scaleMode, resolution) +{ + if (!renderer) + { throw new Error('Unable to create RenderTexture, you must pass a renderer into the constructor.'); } @@ -133,7 +135,8 @@ */ this.renderer = renderer; - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { var gl = this.renderer.gl; this.textureBuffer = new FilterTexture(gl, this.width * this.resolution, this.height * this.resolution, this.baseTexture.scaleMode); @@ -142,7 +145,8 @@ this.render = this.renderWebGL; this.projection = new math.Point(this.width*0.5, -this.height*0.5); } - else { + else + { this.render = this.renderCanvas; this.textureBuffer = new CanvasBuffer(this.width* this.resolution, this.height* this.resolution); this.baseTexture.source = this.textureBuffer.canvas; @@ -167,8 +171,10 @@ * @param height {number} The height to resize to. * @param updateBase {boolean} Should the baseTexture.width and height values be resized as well? */ -RenderTexture.prototype.resize = function (width, height, updateBase) { - if (width === this.width && height === this.height) { +RenderTexture.prototype.resize = function (width, height, updateBase) +{ + if (width === this.width && height === this.height) + { return; } @@ -177,17 +183,20 @@ this.width = this.frame.width = this.crop.width = width; this.height = this.frame.height = this.crop.height = height; - if (updateBase) { + if (updateBase) + { this.baseTexture.width = this.width; this.baseTexture.height = this.height; } - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { this.projection.x = this.width / 2; this.projection.y = -this.height / 2; } - if (!this.valid) { + if (!this.valid) + { return; } @@ -198,12 +207,15 @@ * Clears the RenderTexture. * */ -RenderTexture.prototype.clear = function () { - if (!this.valid) { +RenderTexture.prototype.clear = function () +{ + if (!this.valid) + { return; } - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { this.renderer.gl.bindFramebuffer(this.renderer.gl.FRAMEBUFFER, this.textureBuffer.frameBuffer); } @@ -220,19 +232,23 @@ * @param [restoreWorldTransform=true] {boolean} If true the displayObject's worldTransform/worldAlpha and all children * transformations will be restored. Not restoring this information will be a little faster. */ -RenderTexture.prototype.renderWebGL = function (displayObject, matrix, clear, restoreWorldTransform) { - if (!this.valid) { +RenderTexture.prototype.renderWebGL = function (displayObject, matrix, clear, restoreWorldTransform) +{ + if (!this.valid) + { return; } - if (typeof restoreWorldTransform === 'undefined') { + if (typeof restoreWorldTransform === 'undefined') + { restoreWorldTransform = true; } var tempAlpha, tempTransform; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { tempAlpha = displayObject.worldAlpha; tempTransform = displayObject.worldTransform.toArray(); } @@ -245,7 +261,8 @@ wt.identity(); wt.translate(0, this.projection.y * 2); - if (matrix) { + if (matrix) + { wt.append(matrix); } @@ -258,7 +275,8 @@ var children = displayObject.children; var i, j; - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } @@ -269,7 +287,8 @@ gl.bindFramebuffer(gl.FRAMEBUFFER, this.textureBuffer.frameBuffer ); - if (clear) { + if (clear) + { this.textureBuffer.clear(); } @@ -279,11 +298,13 @@ this.renderer.spriteBatch.dirty = true; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { displayObject.worldAlpha = tempAlpha; displayObject.worldTransform.fromArray(tempTransform); - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } } @@ -300,26 +321,31 @@ * @param [restoreWorldTransform=true] {boolean} If true the displayObject's worldTransform/worldAlpha and all children * transformations will be restored. Not restoring this information will be a little faster. */ -RenderTexture.prototype.renderCanvas = function (displayObject, matrix, clear, restoreWorldTransform) { - if (!this.valid) { +RenderTexture.prototype.renderCanvas = function (displayObject, matrix, clear, restoreWorldTransform) +{ + if (!this.valid) + { return; } - if (typeof restoreWorldTransform === 'undefined') { + if (typeof restoreWorldTransform === 'undefined') + { restoreWorldTransform = true; } var tempAlpha, tempTransform; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { tempAlpha = displayObject.worldAlpha; tempTransform = displayObject.worldTransform.toArray(); } var wt = displayObject.worldTransform; wt.identity(); - if (matrix) { + if (matrix) + { wt.append(matrix); } @@ -330,11 +356,13 @@ var children = displayObject.children; var i, j; - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } - if (clear) { + if (clear) + { this.textureBuffer.clear(); } @@ -348,11 +376,13 @@ this.renderer.resolution = realResolution; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { displayObject.worldAlpha = tempAlpha; displayObject.worldTransform.fromArray(tempTransform); - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } } @@ -363,7 +393,8 @@ * * @return {Image} */ -RenderTexture.prototype.getImage = function () { +RenderTexture.prototype.getImage = function () +{ var image = new Image(); image.src = this.getBase64(); return image; @@ -374,7 +405,8 @@ * * @return {string} A base64 encoded string of the texture. */ -RenderTexture.prototype.getBase64 = function () { +RenderTexture.prototype.getBase64 = function () +{ return this.getCanvas().toDataURL(); }; @@ -383,8 +415,10 @@ * * @return {HTMLCanvasElement} A Canvas element with the texture rendered on. */ -RenderTexture.prototype.getCanvas = function () { - if (this.renderer.type === CONST.WEBGL_RENDERER) { +RenderTexture.prototype.getCanvas = function () +{ + if (this.renderer.type === CONST.WEBGL_RENDERER) + { var gl = this.renderer.gl; var width = this.textureBuffer.width; var height = this.textureBuffer.height; @@ -403,7 +437,8 @@ return tempCanvas.canvas; } - else { + else + { return this.textureBuffer.canvas; } }; diff --git a/src/core/textures/Texture.js b/src/core/textures/Texture.js index 3c65909..e97f0aa 100644 --- a/src/core/textures/Texture.js +++ b/src/core/textures/Texture.js @@ -17,7 +17,8 @@ * @param [crop] {Rectangle} The area of original texture * @param [trim] {Rectangle} Trimmed texture rectangle */ -function Texture(baseTexture, frame, crop, trim) { +function Texture(baseTexture, frame, crop, trim) +{ /** * Does this Texture have any frame data assigned to it? * @@ -25,12 +26,14 @@ */ this.noFrame = false; - if (!frame) { + if (!frame) + { this.noFrame = true; frame = new math.Rectangle(0, 0, 1, 1); } - if (baseTexture instanceof Texture) { + if (baseTexture instanceof Texture) + { baseTexture = baseTexture.baseTexture; } @@ -100,13 +103,16 @@ */ this.crop = crop || new math.Rectangle(0, 0, 1, 1); - if (baseTexture.hasLoaded) { - if (this.noFrame) { + if (baseTexture.hasLoaded) + { + if (this.noFrame) + { frame = new math.Rectangle(0, 0, baseTexture.width, baseTexture.height); } this.frame = frame; } - else { + else + { baseTexture.addEventListener('loaded', this.onBaseTextureLoaded.bind(this)); } } @@ -118,19 +124,23 @@ Object.defineProperties(Texture.prototype, { needsUpdate: { - get: function () { + get: function () + { return this.baseTexture.needsUpdate; }, - set: function (val) { + set: function (val) + { this.baseTexture.needsUpdate = val; } }, frame: { - get: function () { + get: function () + { return this._frame; }, - set: function (frame) { + set: function (frame) + { this._frame = frame; this.noFrame = false; @@ -143,20 +153,23 @@ 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 (!this.trim && (frame.x + frame.width > this.baseTexture.width || frame.y + frame.height > this.baseTexture.height)) + { throw new Error('Texture Error: frame does not fit inside the base Texture dimensions ' + this); } this.valid = frame && frame.width && frame.height && this.baseTexture.source && this.baseTexture.hasLoaded; - if (this.trim) { + 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) { + if (this.valid) + { this._updateUvs(); } } @@ -168,11 +181,13 @@ * * @private */ -Texture.prototype.onBaseTextureLoaded = function () { +Texture.prototype.onBaseTextureLoaded = function () +{ var baseTexture = this.baseTexture; baseTexture.removeEventListener('loaded', this.onLoaded); - if (this.noFrame) { + if (this.noFrame) + { this.frame = new math.Rectangle(0, 0, baseTexture.width, baseTexture.height); } @@ -184,8 +199,10 @@ * * @param destroyBase {boolean} Whether to destroy the base texture as well */ -Texture.prototype.destroy = function (destroyBase) { - if (destroyBase) { +Texture.prototype.destroy = function (destroyBase) +{ + if (destroyBase) + { this.baseTexture.destroy(); } @@ -197,8 +214,10 @@ * * @private */ -Texture.prototype._updateUvs = function () { - if (!this._uvs) { +Texture.prototype._updateUvs = function () +{ + if (!this._uvs) + { this._uvs = new TextureUvs(); } @@ -229,10 +248,12 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return Texture */ -Texture.fromImage = function (imageUrl, crossorigin, scaleMode) { +Texture.fromImage = function (imageUrl, crossorigin, scaleMode) +{ var texture = utils.TextureCache[imageUrl]; - if (!texture) { + if (!texture) + { texture = new Texture(BaseTexture.fromImage(imageUrl, crossorigin, scaleMode)); utils.TextureCache[imageUrl] = texture; } @@ -248,9 +269,11 @@ * @param frameId {string} The frame id of the texture * @return Texture */ -Texture.fromFrame = function (frameId) { +Texture.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache '); } return texture; @@ -264,7 +287,8 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return {Texture} */ -Texture.fromCanvas = function (canvas, scaleMode) { +Texture.fromCanvas = function (canvas, scaleMode) +{ return new Texture(BaseTexture.fromCanvas(canvas, scaleMode)); }; @@ -276,7 +300,8 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return {Texture} A Texture */ -Texture.fromVideo = function (video, scaleMode) { +Texture.fromVideo = function (video, scaleMode) +{ return new Texture(VideoBaseTexture.baseTextureFromVideo(video, scaleMode)); }; @@ -287,7 +312,8 @@ * @param texture {Texture} The Texture to add to the cache. * @param id {string} The id that the texture will be stored against. */ -Texture.addTextureToCache = function (texture, id) { +Texture.addTextureToCache = function (texture, id) +{ utils.TextureCache[id] = texture; }; @@ -298,7 +324,8 @@ * @param id {string} The id of the texture to be removed * @return {Texture} The texture that was removed */ -Texture.removeTextureFromCache = function (id) { +Texture.removeTextureFromCache = function (id) +{ var texture = utils.TextureCache[id]; delete utils.TextureCache[id]; diff --git a/src/core/textures/TextureUvs.js b/src/core/textures/TextureUvs.js index b9bbb58..5424d52 100644 --- a/src/core/textures/TextureUvs.js +++ b/src/core/textures/TextureUvs.js @@ -1,4 +1,5 @@ -function TextureUvs() { +function TextureUvs() +{ this.x0 = 0; this.y0 = 0; diff --git a/src/core/textures/VideoBaseTexture.js b/src/core/textures/VideoBaseTexture.js index e3e0c5a..1a826a9 100644 --- a/src/core/textures/VideoBaseTexture.js +++ b/src/core/textures/VideoBaseTexture.js @@ -12,15 +12,18 @@ * @param source {HTMLVideoElement} * @param [scaleMode] {number} See {@link scaleModes} for possible values */ -function VideoBaseTexture(source, scaleMode) { - if (!source){ +function VideoBaseTexture(source, scaleMode) +{ + if (!source) + { throw new Error('No video source element specified.'); } // hook in here to check if video is already available. // BaseTexture looks for a source.complete boolean, plus width & height. - if ((source.readyState === source.HAVE_ENOUGH_DATA || source.readyState === source.HAVE_FUTURE_DATA) && source.width && source.height) { + if ((source.readyState === source.HAVE_ENOUGH_DATA || source.readyState === source.HAVE_FUTURE_DATA) && source.width && source.height) + { source.complete = true; } @@ -31,7 +34,8 @@ this._boundOnUpdate = this._onUpdate.bind(this); this._boundOnCanPlay = this._onCanPlay.bind(this); - if (!source.complete) { + if (!source.complete) + { source.addEventListener('canplay', this._boundOnCanPlay); source.addEventListener('canplaythrough', this._boundOnCanPlay); @@ -47,28 +51,35 @@ VideoBaseTexture.prototype.constructor = VideoBaseTexture; module.exports = VideoBaseTexture; -VideoBaseTexture.prototype._onUpdate = function () { - if (this.autoUpdate) { +VideoBaseTexture.prototype._onUpdate = function () +{ + if (this.autoUpdate) + { window.requestAnimationFrame(this._boundOnUpdate); this.needsUpdate = true; } }; -VideoBaseTexture.prototype._onPlayStart = function () { - if (!this.autoUpdate) { +VideoBaseTexture.prototype._onPlayStart = function () +{ + if (!this.autoUpdate) + { window.requestAnimationFrame(this._boundOnUpdate); this.autoUpdate = true; } }; -VideoBaseTexture.prototype._onPlayStop = function () { +VideoBaseTexture.prototype._onPlayStop = function () +{ this.autoUpdate = false; }; -VideoBaseTexture.prototype._onCanPlay = function () { +VideoBaseTexture.prototype._onCanPlay = function () +{ this.hasLoaded = true; - if (this.source) { + if (this.source) + { this.source.removeEventListener('canplay', this._boundOnCanPlay); this.source.removeEventListener('canplaythrough', this._boundOnCanPlay); @@ -78,15 +89,18 @@ this.source.play(); // prevent multiple loaded dispatches.. - if(!this.__loaded){ + if(!this.__loaded) + { this.__loaded = true; this.emit('loaded', this); } } }; -VideoBaseTexture.prototype.destroy = function () { - if (this.source && this.source._pixiId) { +VideoBaseTexture.prototype.destroy = function () +{ + if (this.source && this.source._pixiId) + { utils.BaseTextureCache[ this.source._pixiId ] = null; delete utils.BaseTextureCache[ this.source._pixiId ]; @@ -105,14 +119,17 @@ * @param scaleMode {number} See {@link scaleModes} for possible values * @return {VideoBaseTexture} */ -VideoBaseTexture.fromVideo = function (video, scaleMode) { - if (!video._pixiId) { +VideoBaseTexture.fromVideo = function (video, scaleMode) +{ + if (!video._pixiId) + { video._pixiId = 'video_' + utils.uuid(); } var baseTexture = utils.BaseTextureCache[video._pixiId]; - if (!baseTexture) { + if (!baseTexture) + { baseTexture = new VideoBaseTexture(video, scaleMode); utils.BaseTextureCache[ video._pixiId ] = baseTexture; } @@ -147,17 +164,21 @@ * @param scaleMode {number} See {@link scaleModes} for possible values * @return {VideoBaseTexture} */ -VideoBaseTexture.fromUrl = function (videoSrc, scaleMode) { +VideoBaseTexture.fromUrl = function (videoSrc, scaleMode) +{ var video = document.createElement('video'); // array of objects or strings - if (Array.isArray(videoSrc)) { - for (var i = 0; i < videoSrc.length; ++i) { + if (Array.isArray(videoSrc)) + { + for (var i = 0; i < videoSrc.length; ++i) + { video.appendChild(createSource(videoSrc.src || videoSrc, videoSrc.mime)); } } // single object or string - else { + else + { video.appendChild(createSource(videoSrc.src || videoSrc, videoSrc.mime)); } @@ -169,8 +190,10 @@ VideoBaseTexture.fromUrls = VideoBaseTexture.fromUrl; -function createSource(path, type) { - if (!type) { +function createSource(path, type) +{ + if (!type) + { type = 'video/' + path.substr(path.lastIndexOf('.') + 1); } diff --git a/src/core/utils/EventData.js b/src/core/utils/EventData.js index 5d55a22..8cdf701 100644 --- a/src/core/utils/EventData.js +++ b/src/core/utils/EventData.js @@ -7,7 +7,8 @@ * @param name {string} The string name of the event that was triggered * @param data {object} Arbitrary event data to pass along */ -function EventData(target, name, data) { +function EventData(target, name, data) +{ // for duck typing in the ".on()" function this.__isEventObject = true; @@ -71,7 +72,8 @@ * Stops the propagation of events up the scene graph (prevents bubbling). * */ -EventData.prototype.stopPropagation = function stopPropagation() { +EventData.prototype.stopPropagation = function stopPropagation() +{ this.stopped = true; }; @@ -79,6 +81,7 @@ * Stops the propagation of events to sibling listeners (no longer calls any listeners). * */ -EventData.prototype.stopImmediatePropagation = function stopImmediatePropagation() { +EventData.prototype.stopImmediatePropagation = function stopImmediatePropagation() +{ this.stoppedImmediate = true; }; diff --git a/src/core/utils/EventTarget.js b/src/core/utils/EventTarget.js index 7ae8820..671a151 100644 --- a/src/core/utils/EventTarget.js +++ b/src/core/utils/EventTarget.js @@ -13,14 +13,16 @@ * var em = new MyEmitter(); * em.emit('eventName', 'some data', 'some more data', {}, null, ...); */ -function eventTarget(obj) { +function eventTarget(obj) +{ /** * Return a list of assigned event listeners. * * @param eventName {string} The events that should be listed. * @return {Array} An array of listener functions */ - obj.listeners = function listeners(eventName) { + obj.listeners = function listeners(eventName) + { this._listeners = this._listeners || {}; return this._listeners[eventName] ? this._listeners[eventName].slice() : []; @@ -33,22 +35,26 @@ * @param eventName {string} The name of the event. * @return {boolean} Indication if we've emitted an event. */ - obj.emit = obj.dispatchEvent = function emit(eventName, data) { + obj.emit = obj.dispatchEvent = function emit(eventName, data) + { this._listeners = this._listeners || {}; // fast return when there are no listeners - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return; } //backwards compat with old method ".emit({ type: 'something' })" - if (typeof eventName === 'object') { + if (typeof eventName === 'object') + { data = eventName; eventName = eventName.type; } //ensure we are using a real pixi event - if (!data || data.__isEventObject !== true) { + if (!data || data.__isEventObject !== true) + { data = new EventData(this, eventName, data); } @@ -58,23 +64,27 @@ fn = listeners[0], i; - for (i = 0; i < length; fn = listeners[++i]) { + for (i = 0; i < length; fn = listeners[++i]) + { //call the event listener fn.call(this, data); //if "stopImmediatePropagation" is called, stop calling sibling events - if (data.stoppedImmediate) { + if (data.stoppedImmediate) + { return this; } } //if "stopPropagation" is called then don't bubble the event - if (data.stopped) { + if (data.stopped) + { return this; } //bubble this event up the scene graph - if (this.parent && this.parent.emit) { + if (this.parent && this.parent.emit) + { this.parent.emit.call(this.parent, eventName, data); } @@ -88,7 +98,8 @@ * @param eventName {string} Name of the event. * @param callback {Functon} fn Callback function. */ - obj.on = obj.addEventListener = function on(eventName, fn) { + obj.on = obj.addEventListener = function on(eventName, fn) + { this._listeners = this._listeners || {}; (this._listeners[eventName] = this._listeners[eventName] || []) @@ -103,11 +114,13 @@ * @param eventName {string} Name of the event. * @param callback {Function} Callback function. */ - obj.once = function once(eventName, fn) { + obj.once = function once(eventName, fn) + { this._listeners = this._listeners || {}; var self = this; - function onceHandlerWrapper() { + function onceHandlerWrapper() + { fn.apply(self.off(eventName, onceHandlerWrapper), arguments); } onceHandlerWrapper._originalHandler = fn; @@ -122,23 +135,28 @@ * @param eventName {string} The event we want to remove. * @param callback {Function} The listener that we need to find. */ - obj.off = obj.removeEventListener = function off(eventName, fn) { + obj.off = obj.removeEventListener = function off(eventName, fn) + { this._listeners = this._listeners || {}; - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return this; } var list = this._listeners[eventName], i = fn ? list.length : 0; - while(i-- > 0) { - if (list[i] === fn || list[i]._originalHandler === fn) { + while(i-- > 0) + { + if (list[i] === fn || list[i]._originalHandler === fn) + { list.splice(i, 1); } } - if (list.length === 0) { + if (list.length === 0) + { delete this._listeners[eventName]; } @@ -150,10 +168,12 @@ * * @param eventName {string} The event you want to remove all listeners for. */ - obj.removeAllListeners = function removeAllListeners(eventName) { + obj.removeAllListeners = function removeAllListeners(eventName) + { this._listeners = this._listeners || {}; - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return this; } @@ -169,7 +189,8 @@ * * @param object {object} The obj to mix into */ - mixin: function mixin(obj) { + mixin: function mixin(obj) + { eventTarget(obj); } }; diff --git a/src/core/utils/PolyK.js b/src/core/utils/PolyK.js index 7325141..5e20c2b 100644 --- a/src/core/utils/PolyK.js +++ b/src/core/utils/PolyK.js @@ -47,7 +47,8 @@ * Triangulates shapes for webGL graphic fills. * */ -PolyK.Triangulate = function (p) { +PolyK.Triangulate = function (p) +{ var sign = true; var n = p.length >> 1; @@ -59,7 +60,8 @@ i = 0; var al = n; - while(al > 3) { + while(al > 3) + { var i0 = avl[(i+0)%al]; var i1 = avl[(i+1)%al]; var i2 = avl[(i+2)%al]; @@ -69,29 +71,35 @@ var cx = p[2*i2], cy = p[2*i2+1]; var earFound = false; - if (PolyK._convex(ax, ay, bx, by, cx, cy, sign)) { + if (PolyK._convex(ax, ay, bx, by, cx, cy, sign)) + { earFound = true; - for (var j = 0; j < al; j++) { + for (var j = 0; j < al; j++) + { var vi = avl[j]; if (vi === i0 || vi === i1 || vi === i2) continue; - if (PolyK._PointInTriangle(p[2*vi], p[2*vi+1], ax, ay, bx, by, cx, cy)) { + if (PolyK._PointInTriangle(p[2*vi], p[2*vi+1], ax, ay, bx, by, cx, cy)) + { earFound = false; break; } } } - if (earFound) { + if (earFound) + { tgs.push(i0, i1, i2); avl.splice((i+1)%al, 1); al--; i = 0; } - else if (i++ > 3*al) { + else if (i++ > 3*al) + { // need to flip flip reverse it! // reset! - if (sign) { + if (sign) + { tgs = []; avl = []; for (i = 0; i < n; i++) avl.push(i); @@ -101,7 +109,8 @@ sign = false; } - else { + else + { // window.console.log("PIXI Warning: shape too complex to fill"); return null; } @@ -126,7 +135,8 @@ * @private * @return {boolean} */ -PolyK._PointInTriangle = function (px, py, ax, ay, bx, by, cx, cy) { +PolyK._PointInTriangle = function (px, py, ax, ay, bx, by, cx, cy) +{ var v0x = cx-ax; var v0y = cy-ay; var v1x = bx-ax; @@ -154,6 +164,7 @@ * @private * @return {boolean} */ -PolyK._convex = function (ax, ay, bx, by, cx, cy, sign) { +PolyK._convex = function (ax, ay, bx, by, cx, cy, sign) +{ return ((ay-by)*(cx-bx) + (bx-ax)*(cy-by) >= 0) === sign; }; diff --git a/src/core/utils/index.js b/src/core/utils/index.js index ade9831..bfae7ae 100644 --- a/src/core/utils/index.js +++ b/src/core/utils/index.js @@ -16,7 +16,8 @@ * * @return {number} The next uuid to use. */ - uuid: function () { + uuid: function () + { return ++utils._uid; }, @@ -26,7 +27,8 @@ * @param hex {number} * @return {number[]} An array representing the [R, G, B] of the color. */ - hex2rgb: function (hex, out) { + hex2rgb: function (hex, out) + { out = out || []; out[0] = (hex >> 16 & 0xFF) / 255; @@ -42,7 +44,8 @@ * @param hex {number} * @return {string} The string color. */ - hex2string: function (hex) { + hex2string: function (hex) + { hex = hex.toString(16); hex = '000000'.substr(0, 6 - hex.length) + hex; @@ -55,7 +58,8 @@ * @param rgb {number[]} * @return {number} The color number */ - rgb2hex: function (rgb) { + rgb2hex: function (rgb) + { return ((rgb[0]*255 << 16) + (rgb[1]*255 << 8) + rgb[2]*255); }, @@ -64,8 +68,10 @@ * * @return {boolean} whether they are supported */ - canUseNewCanvasBlendModes: function () { - if (typeof document === 'undefined') { + canUseNewCanvasBlendModes: function () + { + if (typeof document === 'undefined') + { return false; } @@ -93,15 +99,19 @@ * @param number {number} * @return {number} the closest number that is a power of two */ - getNextPowerOfTwo: function (number) { + getNextPowerOfTwo: function (number) + { // see: http://en.wikipedia.org/wiki/Power_of_two#Fast_algorithm_to_check_if_a_positive_number_is_a_power_of_two - if (number > 0 && (number & (number - 1)) === 0) { + if (number > 0 && (number & (number - 1)) === 0) + { return number; } - else { + else + { var result = 1; - while (result < number) { + while (result < number) + { result <<= 1; } @@ -116,7 +126,8 @@ * @param height {number} * @return {boolean} */ - isPowerOfTwo: function (width, height) { + isPowerOfTwo: function (width, height) + { return (width > 0 && (width & (width - 1)) === 0 && height > 0 && (height & (height - 1)) === 0); }, @@ -130,12 +141,15 @@ * @constant * @static */ - sayHello: function (type) { - if (utils._saidHello) { + sayHello: function (type) + { + if (utils._saidHello) + { return; } - if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) { + if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) + { var args = [ '%c %c %c Pixi.js ' + CONST.VERSION + ' - ' + type + ' %c ' + ' %c ' + ' http://www.pixijs.com/ %c %c ♥%c♥%c♥ ', 'background: #ff66a5', @@ -151,7 +165,8 @@ console.log.apply(console, args); //jshint ignore:line } - else if (window.console) { + else if (window.console) + { console.log('Pixi.js ' + CONST.VERSION + ' - ' + type + ' - http://www.pixijs.com/'); //jshint ignore:line } @@ -166,15 +181,19 @@ * @class * @namespace PIXI */ - AjaxRequest: function () { + AjaxRequest: function () + { var activexmodes = ['Msxml2.XMLHTTP.6.0', 'Msxml2.XMLHTTP.3.0', 'Microsoft.XMLHTTP']; //activeX versions to check for in IE - if (window.ActiveXObject) { //Test for support for ActiveXObject in IE first (as XMLHttpRequest in IE7 is broken) - for (var i=0; i= this.textures.length) { + else if (round >= this.textures.length) + { this.gotoAndStop(this.textures.length - 1); - if (this.onComplete) { + if (this.onComplete) + { this.onComplete(); } } @@ -167,10 +182,12 @@ * @static * @param frames {string[]} the array of frames ids the movieclip will use as its texture frames */ -MovieClip.fromFrames = function (frames) { +MovieClip.fromFrames = function (frames) +{ var textures = []; - for (var i = 0; i < frames.length; ++i) { + for (var i = 0; i < frames.length; ++i) + { textures.push(new core.Texture.fromFrame(frames[i])); } @@ -183,10 +200,12 @@ * @static * @param images {string[]} the array of image urls the movieclip will use as its texture frames */ -MovieClip.fromImages = function (images) { +MovieClip.fromImages = function (images) +{ var textures = []; - for (var i = 0; i < images.length; ++i) { + for (var i = 0; i < images.length; ++i) + { textures.push(new core.Texture.fromImage(images[i])); } diff --git a/src/extras/Rope.js b/src/extras/Rope.js index c157ec4..9c87bc0 100644 --- a/src/extras/Rope.js +++ b/src/extras/Rope.js @@ -9,7 +9,8 @@ * @param {Array} points - An array of {Point}. * */ -function Rope(texture, points) { +function Rope(texture, points) +{ Strip.call(this, texture); this.points = points; @@ -31,10 +32,12 @@ * Refreshes * */ -Rope.prototype.refresh = function () { +Rope.prototype.refresh = function () +{ var points = this.points; - if (points.length < 1) { + if (points.length < 1) + { return; } @@ -59,20 +62,23 @@ var total = points.length, point, index, amount; - for (var i = 1; i < total; i++) { + for (var i = 1; i < total; i++) + { point = points[i]; index = i * 4; // time to do some smart drawing! amount = i / (total-1); - if (i%2) { + if (i%2) + { uvs[index] = amount; uvs[index+1] = 0; uvs[index+2] = amount; uvs[index+3] = 1; } - else { + else + { uvs[index] = amount; uvs[index+1] = 0; @@ -95,10 +101,12 @@ * * @private */ -Rope.prototype.updateTransform = function () { +Rope.prototype.updateTransform = function () +{ var points = this.points; - if (points.length < 1) { + if (points.length < 1) + { return; } @@ -113,14 +121,17 @@ var total = points.length, point, index, ratio, perpLength, num; - for (var i = 0; i < total; i++) { + for (var i = 0; i < total; i++) + { point = points[i]; index = i * 4; - if (i < points.length-1) { + if (i < points.length-1) + { nextPoint = points[i+1]; } - else { + else + { nextPoint = point; } @@ -129,7 +140,8 @@ ratio = (1 - (i / (total-1))) * 10; - if (ratio > 1) { + if (ratio > 1) + { ratio = 1; } @@ -157,7 +169,8 @@ * * @param texture {Texture} the texture that will be used */ -Rope.prototype.setTexture = function (texture) { +Rope.prototype.setTexture = function (texture) +{ // stop current texture this.texture = texture; //this.updateFrame = true; diff --git a/src/extras/Strip.js b/src/extras/Strip.js index c5e378f..57691b5 100644 --- a/src/extras/Strip.js +++ b/src/extras/Strip.js @@ -10,7 +10,8 @@ * @param height {number} the height * */ -function Strip(texture) { +function Strip(texture) +{ core.DisplayObjectContainer.call(this); /** @@ -70,9 +71,11 @@ * * @param renderer {WebGLRenderer} */ -Strip.prototype.renderWebGL = function (renderer) { +Strip.prototype.renderWebGL = function (renderer) +{ // if the sprite is not visible or the alpha is 0 then no need to render this element - if (!this.visible || this.alpha <= 0) { + if (!this.visible || this.alpha <= 0) + { return; } @@ -81,7 +84,8 @@ renderer.spriteBatch.stop(); // init! init! - if (!this._vertexBuffer) { + if (!this._vertexBuffer) + { this._initWebGL(renderer); } @@ -96,7 +100,8 @@ //TODO check culling }; -Strip.prototype._initWebGL = function (renderer) { +Strip.prototype._initWebGL = function (renderer) +{ // build the strip! var gl = renderer.gl; @@ -118,7 +123,8 @@ gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this.indices, gl.STATIC_DRAW); }; -Strip.prototype._renderStrip = function (renderer) { +Strip.prototype._renderStrip = function (renderer) +{ var gl = renderer.gl; var projection = renderer.projection, offset = renderer.offset, @@ -137,7 +143,8 @@ gl.uniform2f(shader.offsetVector, -offset.x, -offset.y); gl.uniform1f(shader.alpha, this.worldAlpha); - if (!this.dirty) { + if (!this.dirty) + { gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexBuffer); gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); @@ -150,10 +157,12 @@ gl.activeTexture(gl.TEXTURE0); // check if a texture is dirty.. - if (this.texture.baseTexture._dirty[gl.id]) { + if (this.texture.baseTexture._dirty[gl.id]) + { renderer.updateTexture(this.texture.baseTexture); } - else { + else + { // bind the current texture gl.bindTexture(gl.TEXTURE_2D, this.texture.baseTexture._glTextures[gl.id]); } @@ -163,7 +172,8 @@ } - else { + else + { this.dirty = false; gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexBuffer); @@ -178,10 +188,12 @@ gl.activeTexture(gl.TEXTURE0); // check if a texture is dirty.. - if (this.texture.baseTexture._dirty[gl.id]) { + if (this.texture.baseTexture._dirty[gl.id]) + { renderer.updateTexture(this.texture.baseTexture); } - else { + else + { gl.bindTexture(gl.TEXTURE_2D, this.texture.baseTexture._glTextures[gl.id]); } @@ -203,27 +215,33 @@ * * @param renderer {CanvasRenderer} */ -Strip.prototype.renderCanvas = function (renderer) { +Strip.prototype.renderCanvas = function (renderer) +{ var context = renderer.context; var transform = this.worldTransform; - if (renderer.roundPixels) { + if (renderer.roundPixels) + { context.setTransform(transform.a, transform.b, transform.c, transform.d, transform.tx | 0, transform.ty | 0); } - else { + else + { context.setTransform(transform.a, transform.b, transform.c, transform.d, transform.tx, transform.ty); } - if (this.drawMode === Strip.DrawModes.TRIANGLE_STRIP) { + if (this.drawMode === Strip.DrawModes.TRIANGLE_STRIP) + { this._renderCanvasTriangleStrip(context); } - else { + else + { this._renderCanvasTriangles(context); } }; -Strip.prototype._renderCanvasTriangleStrip = function (context) { +Strip.prototype._renderCanvasTriangleStrip = function (context) +{ // draw triangles!! var vertices = this.vertices; var uvs = this.uvs; @@ -231,14 +249,16 @@ var length = vertices.length / 2; // this.count++; - for (var i = 0; i < length - 2; i++) { + for (var i = 0; i < length - 2; i++) + { // draw some triangles! var index = i * 2; this._renderCanvasDrawTriangle(context, vertices, uvs, index, (index + 2), (index + 4)); } }; -Strip.prototype._renderCanvasTriangles = function (context) { +Strip.prototype._renderCanvasTriangles = function (context) +{ // draw triangles!! var vertices = this.vertices; var uvs = this.uvs; @@ -247,14 +267,16 @@ var length = indices.length; // this.count++; - for (var i = 0; i < length; i += 3) { + for (var i = 0; i < length; i += 3) + { // draw some triangles! var index0 = indices[i] * 2, index1 = indices[i + 1] * 2, index2 = indices[i + 2] * 2; this._renderCanvasDrawTriangle(context, vertices, uvs, index0, index1, index2); } }; -Strip.prototype._renderCanvasDrawTriangle = function (context, vertices, uvs, index0, index1, index2) { +Strip.prototype._renderCanvasDrawTriangle = function (context, vertices, uvs, index0, index1, index2) +{ var textureSource = this.texture.baseTexture.source; var textureWidth = this.texture.width; var textureHeight = this.texture.height; @@ -265,7 +287,8 @@ var u0 = uvs[index0] * textureWidth, u1 = uvs[index1] * textureWidth, u2 = uvs[index2] * textureWidth; var v0 = uvs[index0 + 1] * textureHeight, v1 = uvs[index1 + 1] * textureHeight, v2 = uvs[index2 + 1] * textureHeight; - if (this.canvasPadding > 0) { + if (this.canvasPadding > 0) + { var paddingX = this.canvasPadding / this.worldTransform.a; var paddingY = this.canvasPadding / this.worldTransform.d; var centerX = (x0 + x1 + x2) / 3; @@ -332,7 +355,8 @@ * @param strip {Strip} The Strip to render * @private */ -Strip.prototype.renderStripFlat = function (strip) { +Strip.prototype.renderStripFlat = function (strip) +{ var context = this.context; var vertices = strip.vertices; @@ -340,7 +364,8 @@ // this.count++; context.beginPath(); - for (var i=1; i < length-2; i++) { + for (var i=1; i < length-2; i++) + { // draw some triangles! var index = i*2; @@ -358,7 +383,8 @@ }; /* -Strip.prototype.setTexture = function (texture) { +Strip.prototype.setTexture = function (texture) +{ //TODO SET THE TEXTURES //TODO VISIBILITY @@ -377,7 +403,8 @@ * @private */ -Strip.prototype.onTextureUpdate = function () { +Strip.prototype.onTextureUpdate = function () +{ this.updateFrame = true; }; @@ -387,7 +414,8 @@ * @param matrix {Matrix} the transformation matrix of the sprite * @return {Rectangle} the framing rectangle */ -Strip.prototype.getBounds = function (matrix) { +Strip.prototype.getBounds = function (matrix) +{ var worldTransform = matrix || this.worldTransform; var a = worldTransform.a; @@ -404,7 +432,8 @@ var minY = Infinity; var vertices = this.vertices; - for (var i = 0, n = vertices.length; i < n; i += 2) { + for (var i = 0, n = vertices.length; i < n; i += 2) + { var rawX = vertices[i], rawY = vertices[i + 1]; var x = (a * rawX) + (c * rawY) + tx; var y = (d * rawY) + (b * rawX) + ty; @@ -416,7 +445,8 @@ maxY = y > maxY ? y : maxY; } - if (minX === -Infinity || maxY === Infinity) { + if (minX === -Infinity || maxY === Infinity) + { return core.math.Rectangle.EMPTY; } diff --git a/src/extras/TilingSprite.js b/src/extras/TilingSprite.js index 3ac22df..31da393 100644 --- a/src/extras/TilingSprite.js +++ b/src/extras/TilingSprite.js @@ -10,7 +10,8 @@ * @param width {number} the width of the tiling sprite * @param height {number} the height of the tiling sprite */ -function TilingSprite(texture, width, height) { +function TilingSprite(texture, width, height) +{ core.Sprite.call( this, texture); /** @@ -86,10 +87,12 @@ * @memberof TilingSprite# */ width: { - get: function () { + get: function () + { return this._width; }, - set: function (value) { + set: function (value) + { this._width = value; } }, @@ -101,20 +104,25 @@ * @memberof TilingSprite# */ height: { - get: function () { + get: function () + { return this._height; }, - set: function (value) { + set: function (value) + { this._height = value; } }, texture: { - get: function () { + get: function () + { return this._texture; }, - set: function (value) { - if (this._texture === value) { + set: function (value) + { + if (this._texture === value) + { return; } @@ -130,51 +138,61 @@ * * @param renderer {WebGLRenderer} */ -TilingSprite.prototype.renderWebGL = function (renderer) { - if (!this.visible || this.alpha <= 0) { +TilingSprite.prototype.renderWebGL = function (renderer) +{ + if (!this.visible || this.alpha <= 0) + { return; } var i, j; - if (this._mask) { + if (this._mask) + { renderer.spriteBatch.stop(); renderer.maskManager.pushMask(this.mask, renderer); renderer.spriteBatch.start(); } - if (this._filters) { + if (this._filters) + { renderer.spriteBatch.flush(); renderer.filterManager.pushFilter(this._filterBlock); } - if (!this.tilingTexture || this.refreshTexture) { + if (!this.tilingTexture || this.refreshTexture) + { this.generateTilingTexture(true); - if (this.tilingTexture && this.tilingTexture.needsUpdate) { + if (this.tilingTexture && this.tilingTexture.needsUpdate) + { //TODO - tweaking renderer.updateTexture(this.tilingTexture.baseTexture); this.tilingTexture.needsUpdate = false; // this.tilingTexture._uvs = null; } } - else { + else + { renderer.spriteBatch.renderTilingSprite(this); } // simple render children! - for (i=0,j=this.children.length; i= 0 && index <= this.children.length) { - if (child.parent) { + if (index >= 0 && index <= this.children.length) + { + if (child.parent) + { child.parent.removeChild(child); } @@ -154,7 +173,8 @@ return child; } - else { + else + { throw new Error(child + 'addChildAt: The index '+ index +' supplied is out of bounds ' + this.children.length); } }; @@ -165,15 +185,18 @@ * @param child {DisplayObject} * @param child2 {DisplayObject} */ -DisplayObjectContainer.prototype.swapChildren = function (child, child2) { - if (child === child2) { +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) { + if (index1 < 0 || index2 < 0) + { throw new Error('swapChildren: Both the supplied DisplayObjects must be a child of the caller.'); } @@ -187,10 +210,12 @@ * @param child {DisplayObject} The DisplayObject instance to identify * @return {Number} The index position of the child display object to identify */ -DisplayObjectContainer.prototype.getChildIndex = function (child) { +DisplayObjectContainer.prototype.getChildIndex = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { throw new Error('The supplied DisplayObject must be a child of the caller'); } @@ -203,8 +228,10 @@ * @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 */ -DisplayObjectContainer.prototype.setChildIndex = function (child, index) { - if (index < 0 || index >= this.children.length) { +DisplayObjectContainer.prototype.setChildIndex = function (child, index) +{ + if (index < 0 || index >= this.children.length) + { throw new Error('The supplied index is out of bounds'); } @@ -220,8 +247,10 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child at the given index, if any. */ -DisplayObjectContainer.prototype.getChildAt = function (index) { - if (index < 0 || index >= this.children.length) { +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'); } @@ -234,10 +263,12 @@ * @param child {DisplayObject} The DisplayObject to remove * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChild = function (child) { +DisplayObjectContainer.prototype.removeChild = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { return; } @@ -250,7 +281,8 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChildAt = function (index) { +DisplayObjectContainer.prototype.removeChildAt = function (index) +{ var child = this.getChildAt(index); child.parent = null; @@ -265,24 +297,29 @@ * @param beginIndex {Number} The beginning position. Default value is 0. * @param endIndex {Number} The ending position. Default value is size of the container. */ -DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) { +DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) +{ var begin = beginIndex || 0; var end = typeof endIndex === 'number' ? endIndex : this.children.length; var range = end - begin; - if (range > 0 && range <= end) { + if (range > 0 && range <= end) + { var removed = this.children.splice(begin, range); - for (var i = 0; i < removed.length; ++i) { + for (var i = 0; i < removed.length; ++i) + { removed[i].parent = null; } return removed; } - else if (range === 0 && this.children.length === 0) { + else if (range === 0 && this.children.length === 0) + { return []; } - else { + else + { throw new RangeError('removeChildren: numeric values are outside the acceptable range.'); } }; @@ -291,7 +328,8 @@ * Generates and updates the cached sprite for this object. * */ -DisplayObjectContainer.prototype.updateCachedSprite = function () { +DisplayObjectContainer.prototype.updateCachedSprite = function () +{ this._generateCachedSprite(); }; @@ -304,7 +342,8 @@ * @param renderer {CanvasRenderer|WebGLRenderer} The renderer used to generate the texture. * @return {Texture} a texture of the graphics object */ -DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) { +DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) +{ var bounds = this.getLocalBounds(); var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0, renderer, scaleMode, resolution); @@ -322,18 +361,22 @@ * * @private */ -DisplayObjectContainer.prototype.updateTransform = function () { - if (!this.visible) { +DisplayObjectContainer.prototype.updateTransform = function () +{ + if (!this.visible) + { return; } this.displayObjectUpdateTransform(); - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { return; } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } }; @@ -346,8 +389,10 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getBounds = function () { - if (this.children.length === 0) { +DisplayObjectContainer.prototype.getBounds = function () +{ + if (this.children.length === 0) + { return math.Rectangle.EMPTY; } @@ -365,10 +410,12 @@ var childVisible = false; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -386,7 +433,8 @@ maxY = maxY > childMaxY ? maxY : childMaxY; } - if (!childVisible) { + if (!childVisible) + { return math.Rectangle.EMPTY; } @@ -407,12 +455,14 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getLocalBounds = function () { +DisplayObjectContainer.prototype.getLocalBounds = function () +{ var matrixCache = this.worldTransform; this.worldTransform = math.Matrix.IDENTITY; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } @@ -428,13 +478,16 @@ * * @param renderer {WebGLRenderer} The renderer */ -DisplayObjectContainer.prototype.renderWebGL = function (renderer) { +DisplayObjectContainer.prototype.renderWebGL = function (renderer) +{ // if the object is not visible or the alpha is 0 then no need to render this element - if (!this.visible || this.alpha <= 0) { + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } @@ -442,14 +495,17 @@ var i, j; // do a quick check to see if this element has a mask or a filter. - if (this._mask || this._filters) { + if (this._mask || this._filters) + { // push filter first as we need to ensure the stencil buffer is correct for any masking - if (this._filters) { + if (this._filters) + { renderer.spriteBatch.flush(); renderer.filterManager.pushFilter(this._filterBlock); } - if (this._mask) { + if (this._mask) + { renderer.spriteBatch.stop(); renderer.maskManager.pushMask(this.mask, renderer); renderer.spriteBatch.start(); @@ -459,36 +515,42 @@ this._renderWebGL(renderer); // now loop through the children and make sure they get rendered - for (i = 0, j = this.children.length; i < j; i++) { + for (i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderWebGL(renderer); } // time to stop the sprite batch as either a mask element or a filter draw will happen next renderer.spriteBatch.stop(); - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(this._mask, renderer); } - if (this._filters) { + if (this._filters) + { renderer.filterManager.popFilter(); } renderer.spriteBatch.start(); } - else { + else + { this._renderWebGL(renderer); // simple render children! - for (i = 0, j = this.children.length; i < j; ++i) { + for (i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderWebGL(renderer); } } }; -DisplayObjectContainer.prototype._renderWebGL = function (renderer) { +DisplayObjectContainer.prototype._renderWebGL = function (renderer) +{ // this is where content itself gets renderd.. @@ -499,25 +561,31 @@ * * @param renderer {CanvasRenderer} The renderer */ -DisplayObjectContainer.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0) { +DisplayObjectContainer.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -528,13 +596,16 @@ * @param renderer {WebGLRenderer|CanvasRenderer} The renderer * @private */ -DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) { +DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) +{ this._cachedSprite.worldAlpha = this.worldAlpha; - if (renderer.gl) { + if (renderer.gl) + { this._cachedSprite.renderWebGL(renderer); } - else { + else + { this._cachedSprite.renderCanvas(renderer); } }; @@ -544,10 +615,12 @@ * * @private */ -DisplayObjectContainer.prototype._generateCachedSprite = function () { +DisplayObjectContainer.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { // TODO - RenderTexture now *requires* a renderer instance, so this is like broken // because `renderer` isn't actually in scope here :P var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0); @@ -555,7 +628,8 @@ this._cachedSprite = new Sprite(renderTexture); this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.texture.resize(bounds.width | 0, bounds.height | 0); } @@ -580,8 +654,10 @@ * * @private */ -DisplayObjectContainer.prototype._destroyCachedSprite = function () { - if (!this._cachedSprite) { +DisplayObjectContainer.prototype._destroyCachedSprite = function () +{ + if (!this._cachedSprite) + { return; } diff --git a/src/core/display/Sprite.js b/src/core/display/Sprite.js index 707da24..5862aef 100644 --- a/src/core/display/Sprite.js +++ b/src/core/display/Sprite.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param texture {Texture} The texture for this sprite */ -function Sprite(texture) { +function Sprite(texture) +{ DisplayObjectContainer.call(this); /** @@ -85,12 +86,14 @@ this.texture = texture || Texture.EMPTY; } -Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) { +Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) +{ DisplayObjectContainer.prototype.destroy.call(this); this.anchor = null; - if (destroyTexture) { + if (destroyTexture) + { this._texture.destroy(destroyBaseTexture); } @@ -111,10 +114,12 @@ * @memberof Sprite# */ width: { - get: function () { + get: function () + { return this.scale.x * this.texture.frame.width; }, - set: function (value) { + set: function (value) + { this.scale.x = value / this.texture.frame.width; this._width = value; } @@ -127,10 +132,12 @@ * @memberof Sprite# */ height: { - get: function () { + get: function () + { return this.scale.y * this.texture.frame.height; }, - set: function (value) { + set: function (value) + { this.scale.y = value / this.texture.frame.height; this._height = value; } @@ -143,23 +150,29 @@ * @memberof Sprite# */ texture: { - get: function () { + get: function () + { return this._texture; }, - set: function (value) { - if (this._texture === value) { + set: function (value) + { + if (this._texture === value) + { return; } this._texture = value; this.cachedTint = 0xFFFFFF; - if (value) { + if (value) + { // wait for the texture to load - if (value.baseTexture.hasLoaded) { + if (value.baseTexture.hasLoaded) + { this._onTextureUpdate(); } - else { + else + { value.once('update', this._onTextureUpdate.bind(this)); } } @@ -172,18 +185,22 @@ * * @private */ -Sprite.prototype._onTextureUpdate = function () { +Sprite.prototype._onTextureUpdate = function () +{ // so if _width is 0 then width was not set.. - if (this._width) { + if (this._width) + { this.scale.x = this._width / this.texture.frame.width; } - if (this._height) { + if (this._height) + { this.scale.y = this._height / this.texture.frame.height; } }; -Sprite.prototype._renderWebGL = function (renderer) { +Sprite.prototype._renderWebGL = function (renderer) +{ // this is where content gets renderd.. // watch this space for a little render state manager.. @@ -197,7 +214,8 @@ * @param matrix {Matrix} the transformation matrix of the sprite * @return {Rectangle} the framing rectangle */ -Sprite.prototype.getBounds = function (matrix) { +Sprite.prototype.getBounds = function (matrix) +{ var width = this.texture.frame.width; var height = this.texture.frame.height; @@ -224,11 +242,13 @@ if(b === 0 && c === 0) { // scale may be negative! - if (a < 0) { + if (a < 0) + { a *= -1; } - if (d < 0) { + if (d < 0) + { d *= -1; } @@ -293,28 +313,34 @@ * * @param renderer {CanvasRenderer} The renderer */ -Sprite.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) { +Sprite.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) + { return; } - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; renderer.context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } // Ignore null sources - if (this.texture.valid) { + if (this.texture.valid) + { var resolution = this.texture.baseTexture.resolution / renderer.resolution; renderer.context.globalAlpha = this.worldAlpha; // If smoothingEnabled is supported and we need to change the smoothing property for this texture - if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) { + if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) + { renderer.scaleMode = this.texture.baseTexture.scaleMode; renderer.context[renderer.smoothProperty] = (renderer.scaleMode === CONST.scaleModes.LINEAR); } @@ -324,7 +350,8 @@ var dy = (this.texture.trim ? this.texture.trim.y : 0) - (this.anchor.y * this.texture.trim.height); // Allow for pixel rounding - if (renderer.roundPixels) { + if (renderer.roundPixels) + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -337,7 +364,8 @@ dx = dx | 0; dy = dy | 0; } - else { + else + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -348,8 +376,10 @@ ); } - if (this.tint !== 0xFFFFFF) { - if (this.cachedTint !== this.tint) { + if (this.tint !== 0xFFFFFF) + { + if (this.cachedTint !== this.tint) + { this.cachedTint = this.tint; // TODO clean up caching - how to clean up the caches? @@ -368,7 +398,8 @@ this.texture.crop.height / resolution ); } - else { + else + { renderer.context.drawImage( this.texture.baseTexture.source, this.texture.crop.x, @@ -383,11 +414,13 @@ } } - for (var i = 0, j = this.children.length; i < j; i++) { + for (var i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -402,10 +435,12 @@ * @param frameId {String} The frame Id of the texture in the cache * @return {Sprite} A new Sprite using a texture from the texture cache matching the frameId */ -Sprite.fromFrame = function (frameId) { +Sprite.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache' + this); } @@ -420,6 +455,7 @@ * @param imageId {String} The image url of the texture * @return {Sprite} A new Sprite using a texture from the texture cache matching the image id */ -Sprite.fromImage = function (imageId, crossorigin, scaleMode) { +Sprite.fromImage = function (imageId, crossorigin, scaleMode) +{ return new Sprite(Texture.fromImage(imageId, crossorigin, scaleMode)); }; diff --git a/src/core/display/SpriteBatch.js b/src/core/display/SpriteBatch.js index 3187777..c196fef 100644 --- a/src/core/display/SpriteBatch.js +++ b/src/core/display/SpriteBatch.js @@ -12,7 +12,8 @@ * ```js * var container = new SpriteBatch(); * - * for(var i = 0; i < 100; ++i) { + * for(var i = 0; i < 100; ++i) + * { * var sprite = new PIXI.Sprite.fromImage("myImage.png"); * container.addChild(sprite); * } @@ -25,7 +26,8 @@ */ //TODO RENAME to PARTICLE CONTAINER? -function SpriteBatch() { +function SpriteBatch() +{ DisplayObjectContainer.call(this); } @@ -38,7 +40,8 @@ * * @private */ -SpriteBatch.prototype.updateTransform = function () { +SpriteBatch.prototype.updateTransform = function () +{ // TODO don't need to! this.displayObjectUpdateTransform(); // PIXI.DisplayObjectContainer.prototype.updateTransform.call( this ); @@ -50,8 +53,10 @@ * @param renderer {WebGLRenderer} The webgl renderer * @private */ -SpriteBatch.prototype.renderWebGL = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderWebGL = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -71,8 +76,10 @@ * @param renderer {CanvasRenderer} The canvas renderer * @private */ -SpriteBatch.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -84,10 +91,12 @@ this.displayObjectUpdateTransform(); - for (var i = 0; i < this.children.length; ++i) { + for (var i = 0; i < this.children.length; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -95,9 +104,11 @@ context.globalAlpha = this.worldAlpha * child.alpha; - if (child.rotation % (Math.PI * 2) === 0) { + if (child.rotation % (Math.PI * 2) === 0) + { // this is the fastest way to optimise! - if rotation is 0 then we can avoid any kind of setTransform call - if (isRotated) { + if (isRotated) + { context.setTransform( transform.a, transform.b, @@ -122,8 +133,10 @@ frame.height * child.scale.y ); } - else { - if (!isRotated) { + else + { + if (!isRotated) + { isRotated = true; } @@ -131,7 +144,8 @@ var childTransform = child.worldTransform; - if (renderer.roundPixels) { + if (renderer.roundPixels) + { context.setTransform( childTransform.a, childTransform.b, @@ -141,7 +155,8 @@ childTransform.ty | 0 ); } - else { + else + { context.setTransform( childTransform.a, childTransform.b, diff --git a/src/core/index.js b/src/core/index.js index 3954b6f..eb4a82b 100644 --- a/src/core/index.js +++ b/src/core/index.js @@ -58,11 +58,13 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRenderer: function (width, height, options, noWebGL) { + autoDetectRenderer: function (width, height, options, noWebGL) + { width = width || 800; height = height || 600; - if (!noWebGL && require('webgl-enabled')()) { + if (!noWebGL && require('webgl-enabled')()) + { return new core.WebGLRenderer(width, height, options); } @@ -87,7 +89,8 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRecommendedRenderer: function (width, height, options) { + autoDetectRecommendedRenderer: function (width, height, options) + { var isAndroid = /Android/i.test(navigator.userAgent); return core.autoDetectRenderer(width, height, options, isAndroid); diff --git a/src/core/math/Matrix.js b/src/core/math/Matrix.js index c2f87e2..2ff4848 100644 --- a/src/core/math/Matrix.js +++ b/src/core/math/Matrix.js @@ -10,7 +10,8 @@ * @class * @namespace PIXI */ -function Matrix() { +function Matrix() +{ /** * @member {number} * @default 1 @@ -63,7 +64,8 @@ * * @param array {number[]} The array that the matrix will be populated from. */ -Matrix.prototype.fromArray = function (array) { +Matrix.prototype.fromArray = function (array) +{ this.a = array[0]; this.b = array[1]; this.c = array[3]; @@ -78,14 +80,17 @@ * @param transpose {boolean} Whether we need to transpose the matrix or not * @return {number[]} the newly created array which contains the matrix */ -Matrix.prototype.toArray = function (transpose) { - if (!this.array) { +Matrix.prototype.toArray = function (transpose) +{ + if (!this.array) + { this.array = new Float32Array(9); } var array = this.array; - if (transpose) { + if (transpose) + { array[0] = this.a; array[1] = this.b; array[2] = 0; @@ -96,7 +101,8 @@ array[7] = this.ty; array[8] = 1; } - else { + else + { array[0] = this.a; array[1] = this.c; array[2] = this.tx; @@ -119,7 +125,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, transformed through this matrix */ -Matrix.prototype.apply = function (pos, newPos) { +Matrix.prototype.apply = function (pos, newPos) +{ newPos = newPos || new Point(); newPos.x = this.a * pos.x + this.c * pos.y + this.tx; @@ -136,7 +143,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, inverse-transformed through this matrix */ -Matrix.prototype.applyInverse = function (pos, newPos) { +Matrix.prototype.applyInverse = function (pos, newPos) +{ newPos = newPos || new Point(); var id = 1 / (this.a * this.d + this.c * -this.b); @@ -154,7 +162,8 @@ * @param {number} y * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.translate = function (x, y) { +Matrix.prototype.translate = function (x, y) +{ this.tx += x; this.ty += y; @@ -168,7 +177,8 @@ * @param {number} y The amount to scale vertically * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.scale = function (x, y) { +Matrix.prototype.scale = function (x, y) +{ this.a *= x; this.d *= y; this.c *= x; @@ -186,7 +196,8 @@ * @param {number} angle - The angle in radians. * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.rotate = function (angle) { +Matrix.prototype.rotate = function (angle) +{ var cos = Math.cos( angle ); var sin = Math.sin( angle ); @@ -210,7 +221,8 @@ * @param {Matrix} matrix * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.append = function (matrix) { +Matrix.prototype.append = function (matrix) +{ var a1 = this.a; var b1 = this.b; var c1 = this.c; @@ -232,7 +244,8 @@ * * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.identity = function () { +Matrix.prototype.identity = function () +{ this.a = 1; this.b = 0; this.c = 0; diff --git a/src/core/math/Point.js b/src/core/math/Point.js index 7565b2d..632f346 100644 --- a/src/core/math/Point.js +++ b/src/core/math/Point.js @@ -7,7 +7,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -function Point(x, y) { +function Point(x, y) +{ /** * @member {number} * @default 0 @@ -29,7 +30,8 @@ * * @return {Point} a copy of the point */ -Point.prototype.clone = function () { +Point.prototype.clone = function () +{ return new Point(this.x, this.y); }; @@ -40,7 +42,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -Point.prototype.set = function (x, y) { +Point.prototype.set = function (x, y) +{ this.x = x || 0; this.y = y || ( (y !== 0) ? this.x : 0 ) ; }; diff --git a/src/core/math/shapes/Circle.js b/src/core/math/shapes/Circle.js index 69cfdc9..4d76efc 100644 --- a/src/core/math/shapes/Circle.js +++ b/src/core/math/shapes/Circle.js @@ -10,7 +10,8 @@ * @param y {number} The Y coordinate of the center of this circle * @param radius {number} The radius of the circle */ -function Circle(x, y, radius) { +function Circle(x, y, radius) +{ /** * @member {number} * @default 0 @@ -46,7 +47,8 @@ * @method clone * @return {Circle} a copy of the Circle */ -Circle.prototype.clone = function () { +Circle.prototype.clone = function () +{ return new Circle(this.x, this.y, this.radius); }; @@ -58,8 +60,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Circle */ -Circle.prototype.contains = function (x, y) { - if (this.radius <= 0) { +Circle.prototype.contains = function (x, y) +{ + if (this.radius <= 0) + { return false; } @@ -79,6 +83,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Circle.prototype.getBounds = function () { +Circle.prototype.getBounds = function () +{ return new Rectangle(this.x - this.radius, this.y - this.radius, this.radius * 2, this.radius * 2); }; diff --git a/src/core/math/shapes/Ellipse.js b/src/core/math/shapes/Ellipse.js index 4f2d066..fefd01a 100644 --- a/src/core/math/shapes/Ellipse.js +++ b/src/core/math/shapes/Ellipse.js @@ -11,7 +11,8 @@ * @param width {number} The half width of this ellipse * @param height {number} The half height of this ellipse */ -function Ellipse(x, y, width, height) { +function Ellipse(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -53,7 +54,8 @@ * @method clone * @return {Ellipse} a copy of the ellipse */ -Ellipse.prototype.clone = function () { +Ellipse.prototype.clone = function () +{ return new Ellipse(this.x, this.y, this.width, this.height); }; @@ -65,8 +67,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coords are within this ellipse */ -Ellipse.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Ellipse.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } @@ -86,6 +90,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Ellipse.prototype.getBounds = function () { +Ellipse.prototype.getBounds = function () +{ return new Rectangle(this.x - this.width, this.y - this.height, this.width, this.height); }; diff --git a/src/core/math/shapes/Polygon.js b/src/core/math/shapes/Polygon.js index ae89148..fea6d37 100644 --- a/src/core/math/shapes/Polygon.js +++ b/src/core/math/shapes/Polygon.js @@ -10,16 +10,20 @@ * arguments passed can be flat x,y values e.g. `new Polygon(x,y, x,y, x,y, ...)` where `x` and `y` are * Numbers. */ -function Polygon(points) { +function Polygon(points) +{ //if points isn't an array, use arguments as the array - if (!(points instanceof Array)) { + if (!(points instanceof Array)) + { points = Array.prototype.slice.call(arguments); } //if this is a flat array of numbers, convert it to points - if (points[0] instanceof Point) { + if (points[0] instanceof Point) + { var p = []; - for (var i = 0, il = points.length; i < il; i++) { + for (var i = 0, il = points.length; i < il; i++) + { p.push(points[i].x, points[i].y); } @@ -51,7 +55,8 @@ * * @return {Polygon} a copy of the polygon */ -Polygon.prototype.clone = function () { +Polygon.prototype.clone = function () +{ return new Polygon(this.points.slice()); }; @@ -62,19 +67,22 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this polygon */ -Polygon.prototype.contains = function (x, y) { +Polygon.prototype.contains = function (x, y) +{ var inside = false; // use some raycasting to test hits // https://github.com/substack/point-in-polygon/blob/master/index.js var length = this.points.length / 2; - for (var i = 0, j = length - 1; i < length; j = i++) { + for (var i = 0, j = length - 1; i < length; j = i++) + { var xi = this.points[i * 2], yi = this.points[i * 2 + 1], xj = this.points[j * 2], yj = this.points[j * 2 + 1], intersect = ((yi > y) !== (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi); - if (intersect) { + if (intersect) + { inside = !inside; } } diff --git a/src/core/math/shapes/Rectangle.js b/src/core/math/shapes/Rectangle.js index 16ac62a..4008b68 100644 --- a/src/core/math/shapes/Rectangle.js +++ b/src/core/math/shapes/Rectangle.js @@ -10,7 +10,8 @@ * @param width {number} The overall width of this rectangle * @param height {number} The overall height of this rectangle */ -function Rectangle(x, y, width, height) { +function Rectangle(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -60,7 +61,8 @@ * * @return {Rectangle} a copy of the rectangle */ -Rectangle.prototype.clone = function () { +Rectangle.prototype.clone = function () +{ return new Rectangle(this.x, this.y, this.width, this.height); }; @@ -71,13 +73,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rectangle */ -Rectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Rectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/math/shapes/RoundedRectangle.js b/src/core/math/shapes/RoundedRectangle.js index 27d286e..7bf6411 100644 --- a/src/core/math/shapes/RoundedRectangle.js +++ b/src/core/math/shapes/RoundedRectangle.js @@ -11,7 +11,8 @@ * @param height {number} The overall height of this rounded rectangle * @param radius {number} Controls the radius of the rounded corners */ -function RoundedRectangle(x, y, width, height, radius) { +function RoundedRectangle(x, y, width, height, radius) +{ /** * @member {number} * @default 0 @@ -58,7 +59,8 @@ * * @return {RoundedRectangle} a copy of the rounded rectangle */ -RoundedRectangle.prototype.clone = function () { +RoundedRectangle.prototype.clone = function () +{ return new RoundedRectangle(this.x, this.y, this.width, this.height, this.radius); }; @@ -69,13 +71,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rounded Rectangle */ -RoundedRectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +RoundedRectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/primitives/Graphics.js b/src/core/primitives/Graphics.js index 261c534..e902d2a 100644 --- a/src/core/primitives/Graphics.js +++ b/src/core/primitives/Graphics.js @@ -16,7 +16,8 @@ * @extends DisplayObjectContainer * @namespace PIXI */ -function Graphics() { +function Graphics() +{ DisplayObjectContainer.call(this); this.renderable = true; @@ -154,16 +155,20 @@ * @private */ cacheAsBitmap: { - get: function () { + get: function () + { return this._cacheAsBitmap; }, - set: function (value) { + set: function (value) + { this._cacheAsBitmap = value; - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._generateCachedSprite(); } - else { + else + { this.destroyCachedSprite(); this.dirty = true; } @@ -176,7 +181,8 @@ * * @return {Graphics} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ var clone = new Graphics(); clone.renderable = this.renderable; @@ -192,7 +198,8 @@ clone.cachedSpriteDirty = this.cachedSpriteDirty; // copy graphics data - for (var i = 0; i < this.graphicsData.length; ++i) { + for (var i = 0; i < this.graphicsData.length; ++i) + { clone.graphicsData.push(this.graphicsData.clone()); } @@ -211,17 +218,21 @@ * @param alpha {number} alpha of the line to draw, will update the objects stored style * @return {Graphics} */ -Graphics.prototype.lineStyle = function (lineWidth, color, alpha) { +Graphics.prototype.lineStyle = function (lineWidth, color, alpha) +{ this.lineWidth = lineWidth || 0; this.lineColor = color || 0; this.lineAlpha = (arguments.length < 3) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length) + { // halfway through a line? start a new one! this.drawShape( new math.Polygon( this.currentPath.shape.points.slice(-2) )); } - else { + else + { // otherwise its empty so lets just set the line properties this.currentPath.lineWidth = this.lineWidth; this.currentPath.lineColor = this.lineColor; @@ -239,7 +250,8 @@ * @param y {number} the Y coordinate to move to * @return {Graphics} */ -Graphics.prototype.moveTo = function (x, y) { +Graphics.prototype.moveTo = function (x, y) +{ this.drawShape(new math.Polygon([x,y])); return this; @@ -253,7 +265,8 @@ * @param y {number} the Y coordinate to draw to * @return {Graphics} */ -Graphics.prototype.lineTo = function (x, y) { +Graphics.prototype.lineTo = function (x, y) +{ this.currentPath.shape.points.push(x, y); this.dirty = true; @@ -270,13 +283,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -285,7 +302,8 @@ n = 20, points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { this.moveTo(0, 0); } @@ -293,7 +311,8 @@ var fromY = points[points.length-1]; var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; xa = fromX + ( (cpX - fromX) * j ); @@ -319,13 +338,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -342,7 +365,8 @@ var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; dt = (1 - j); @@ -373,13 +397,17 @@ * @param radius {number} The radius of the arc * @return {Graphics} */ -Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points.push(x1, y1); } } - else { + else + { this.moveTo(x1, y1); } @@ -392,12 +420,15 @@ b2 = x2 - x1, mm = Math.abs(a1 * b2 - b1 * a2); - if (mm < 1.0e-8 || radius === 0) { - if (points[points.length-2] !== x1 || points[points.length-1] !== y1) { + if (mm < 1.0e-8 || radius === 0) + { + if (points[points.length-2] !== x1 || points[points.length-1] !== y1) + { points.push(x1, y1); } } - else { + else + { var dd = a1 * a1 + b1 * b1, cc = a2 * a2 + b2 * b2, tt = a1 * a2 + b1 * b2, @@ -433,42 +464,51 @@ * @param anticlockwise {boolean} Optional. Specifies whether the drawing should be counterclockwise or clockwise. False is default, and indicates clockwise, while true indicates counter-clockwise. * @return {Graphics} */ -Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) { +Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) +{ var startX = cx + Math.cos(startAngle) * radius; var startY = cy + Math.sin(startAngle) * radius; var points; // TODO - This if-else makes no sense. It uses currentPath in the else where it doesn't exist... - if (this.currentPath) { + if (this.currentPath) + { points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { points.push(startX, startY); } - else if (points[points.length-2] !== startX || points[points.length-1] !== startY) { + else if (points[points.length-2] !== startX || points[points.length-1] !== startY) + { points.push(startX, startY); } } - else { + else + { this.moveTo(startX, startY); points = this.currentPath.shape.points; } - if (startAngle === endAngle) { + if (startAngle === endAngle) + { return this; } - if (!anticlockwise && endAngle <= startAngle) { + if (!anticlockwise && endAngle <= startAngle) + { endAngle += Math.PI * 2; } - else if (anticlockwise && startAngle <= endAngle) { + else if (anticlockwise && startAngle <= endAngle) + { startAngle += Math.PI * 2; } var sweep = anticlockwise ? (startAngle - endAngle) *-1 : (endAngle - startAngle); var segs = (Math.abs(sweep)/ (Math.PI * 2)) * 40; - if (sweep === 0) { + if (sweep === 0) + { return this; } @@ -482,7 +522,8 @@ var remainder = ( segMinus % 1 ) / segMinus; - for (var i = 0; i <= segMinus; ++i) { + for (var i = 0; i <= segMinus; ++i) + { var real = i + remainder * i; var angle = ((theta) + startAngle + (theta2 * real)); @@ -506,13 +547,16 @@ * @param alpha {number} the alpha of the fill * @return {Graphics} */ -Graphics.prototype.beginFill = function (color, alpha) { +Graphics.prototype.beginFill = function (color, alpha) +{ this.filling = true; this.fillColor = color || 0; this.fillAlpha = (alpha === undefined) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length <= 2) + { this.currentPath.fill = this.filling; this.currentPath.fillColor = this.fillColor; this.currentPath.fillAlpha = this.fillAlpha; @@ -526,7 +570,8 @@ * * @return {Graphics} */ -Graphics.prototype.endFill = function () { +Graphics.prototype.endFill = function () +{ this.filling = false; this.fillColor = null; this.fillAlpha = 1; @@ -542,7 +587,8 @@ * @param height {number} The height of the rectangle * @return {Graphics} */ -Graphics.prototype.drawRect = function ( x, y, width, height ) { +Graphics.prototype.drawRect = function ( x, y, width, height ) +{ this.drawShape(new math.Rectangle(x,y, width, height)); return this; @@ -556,7 +602,8 @@ * @param height {number} The height of the rectangle * @param radius {number} Radius of the rectangle corners */ -Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) { +Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) +{ this.drawShape(new math.RoundedRectangle(x, y, width, height, radius)); return this; @@ -570,7 +617,8 @@ * @param radius {number} The radius of the circle * @return {Graphics} */ -Graphics.prototype.drawCircle = function (x, y, radius) { +Graphics.prototype.drawCircle = function (x, y, radius) +{ this.drawShape(new math.Circle(x,y, radius)); return this; @@ -585,7 +633,8 @@ * @param height {number} The half height of the ellipse * @return {Graphics} */ -Graphics.prototype.drawEllipse = function (x, y, width, height) { +Graphics.prototype.drawEllipse = function (x, y, width, height) +{ this.drawShape(new math.Ellipse(x, y, width, height)); return this; @@ -597,8 +646,10 @@ * @param path {Array} The path data used to construct the polygon. * @return {Graphics} */ -Graphics.prototype.drawPolygon = function (path) { - if (!(path instanceof Array)) { +Graphics.prototype.drawPolygon = function (path) +{ + if (!(path instanceof Array)) + { path = Array.prototype.slice.call(arguments); } @@ -612,7 +663,8 @@ * * @return {Graphics} */ -Graphics.prototype.clear = function () { +Graphics.prototype.clear = function () +{ this.lineWidth = 0; this.filling = false; @@ -631,7 +683,8 @@ * @param scaleMode {number} Should be one of the scaleMode consts * @return {Texture} a texture of the graphics object */ -Graphics.prototype.generateTexture = function (resolution, scaleMode) { +Graphics.prototype.generateTexture = function (resolution, scaleMode) +{ resolution = resolution || 1; var bounds = this.getBounds(); @@ -655,17 +708,21 @@ * * @param renderer {WebGLRenderer} */ -Graphics.prototype._renderWebGL = function (renderer) { +Graphics.prototype._renderWebGL = function (renderer) +{ // if the sprite is not visible or the alpha is 0 then no need to render this element - if (this.isMask === true) { + if (this.isMask === true) + { return; } // this code may still be needed so leaving for now.. - // + // /* - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture on the gpu too! @@ -681,17 +738,24 @@ return; } - */ - - // check if the webgl graphic needs to be updated - if (this.glDirty) { - this.dirty = true; - this.glDirty = false; - } + else */ - renderer.setObjectRendererer(renderer.graphicsRenderer); - renderer.graphicsRenderer.render(this); + renderer.spriteBatch.stop(); + renderer.blendModeManager.setBlendMode(this.blendMode); + // check blend mode + renderer.blendModeManager.setBlendMode( this.blendMode ); + + // check if the webgl graphic needs to be updated + if (this.glDirty) + { + this.dirty = true; + this.glDirty = false; + } + + WebGLGraphics.renderGraphics(this, renderer); + + renderer.spriteBatch.start(); }; /** @@ -700,14 +764,18 @@ * @param renderer {CanvasRenderer} * @private */ -Graphics.prototype.renderCanvas = function (renderer) { +Graphics.prototype.renderCanvas = function (renderer) +{ // 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.isMask === true) { + if (!this.visible || this.alpha <= 0 || this.isMask === true) + { return; } - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture @@ -723,16 +791,19 @@ return; } - else { + else + { var context = renderer.context; var transform = this.worldTransform; - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } @@ -748,11 +819,13 @@ CanvasGraphics.renderGraphics(this, context); - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } } @@ -763,13 +836,16 @@ * * @return {Rectangle} the rectangular bounding area */ -Graphics.prototype.getBounds = function (matrix) { +Graphics.prototype.getBounds = function (matrix) +{ // return an empty object if the item is a mask! - if (this.isMask) { + if (this.isMask) + { return math.Rectangle.EMPTY; } - if (this.dirty) { + if (this.dirty) + { this.updateLocalBounds(); this.glDirty = true; @@ -841,23 +917,27 @@ * Update the bounds of the object * */ -Graphics.prototype.updateLocalBounds = function () { +Graphics.prototype.updateLocalBounds = function () +{ var minX = Infinity; var maxX = -Infinity; var minY = Infinity; var maxY = -Infinity; - if (this.graphicsData.length) { + if (this.graphicsData.length) + { var shape, points, x, y, w, h; - for (var i = 0; i < this.graphicsData.length; i++) { + for (var i = 0; i < this.graphicsData.length; i++) + { var data = this.graphicsData[i]; var type = data.type; var lineWidth = data.lineWidth; shape = data.shape; - if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) { + if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) + { x = shape.x - lineWidth/2; y = shape.y - lineWidth/2; w = shape.width + lineWidth; @@ -869,7 +949,8 @@ minY = y < minY ? y : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.CIRC) { + else if (type === CONST.SHAPES.CIRC) + { x = shape.x; y = shape.y; w = shape.radius + lineWidth/2; @@ -881,7 +962,8 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.ELIP) { + else if (type === CONST.SHAPES.ELIP) + { x = shape.x; y = shape.y; w = shape.width + lineWidth/2; @@ -893,11 +975,13 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else { + else + { // POLY points = shape.points; - for (var j = 0; j < points.length; j += 2) { + for (var j = 0; j < points.length; j += 2) + { x = points[j]; y = points[j+1]; @@ -910,7 +994,8 @@ } } } - else { + else + { minX = 0; maxX = 0; minY = 0; @@ -931,10 +1016,12 @@ * * @private */ -Graphics.prototype._generateCachedSprite = function () { +Graphics.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { var canvasBuffer = new CanvasBuffer(bounds.width, bounds.height); var texture = Texture.fromCanvas(canvasBuffer.canvas); @@ -943,7 +1030,8 @@ this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.buffer.resize(bounds.width, bounds.height); } @@ -968,7 +1056,8 @@ * * @private */ -Graphics.prototype.updateCachedSpriteTexture = function () { +Graphics.prototype.updateCachedSpriteTexture = function () +{ var cachedSprite = this._cachedSprite; var texture = cachedSprite.texture; var canvas = cachedSprite.buffer.canvas; @@ -989,7 +1078,8 @@ * Destroys a previous cached sprite. * */ -Graphics.prototype.destroyCachedSprite = function () { +Graphics.prototype.destroyCachedSprite = function () +{ this._cachedSprite.texture.destroy(true); // let the gc collect the unused sprite @@ -1003,10 +1093,13 @@ * @param {Circle|Rectangle|Ellipse|Line|Polygon} shape The Shape object to draw. * @return {GraphicsData} The generated GraphicsData object. */ -Graphics.prototype.drawShape = function (shape) { - if (this.currentPath) { +Graphics.prototype.drawShape = function (shape) +{ + if (this.currentPath) + { // check current path! - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath.shape.points.length <= 2) + { this.graphicsData.pop(); } } @@ -1017,7 +1110,8 @@ this.graphicsData.push(data); - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { data.shape.closed = this.filling; this.currentPath = data; } diff --git a/src/core/primitives/GraphicsData.js b/src/core/primitives/GraphicsData.js index 99decbe..788f6f2 100644 --- a/src/core/primitives/GraphicsData.js +++ b/src/core/primitives/GraphicsData.js @@ -4,7 +4,8 @@ * @class * @namespace PIXI */ -function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) { +function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) +{ this.lineWidth = lineWidth; this.lineColor = lineColor; this.lineAlpha = lineAlpha; @@ -27,7 +28,8 @@ * * @return {GraphicsData} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ return new GraphicsData( this.lineWidth, this.lineColor, diff --git a/src/core/renderers/canvas/CanvasRenderer.js b/src/core/renderers/canvas/CanvasRenderer.js index 15a0978..7aebd44 100644 --- a/src/core/renderers/canvas/CanvasRenderer.js +++ b/src/core/renderers/canvas/CanvasRenderer.js @@ -17,17 +17,22 @@ * @param [options.resolution=1] {number} the resolution of the renderer retina would be 2 * @param [options.clearBeforeRender=true] {boolean} This sets if the CanvasRenderer will clear the canvas or not before the new render pass. */ -function CanvasRenderer(width, height, options) { +function CanvasRenderer(width, height, options) +{ utils.sayHello('Canvas'); - if (options) { - for (var i in CONST.defaultRenderOptions) { - if (typeof options[i] === 'undefined') { + if (options) + { + for (var i in CONST.defaultRenderOptions) + { + if (typeof options[i] === 'undefined') + { options[i] = CONST.defaultRenderOptions[i]; } } } - else { + else + { options = CONST.defaultRenderOptions; } @@ -156,19 +161,24 @@ this.smoothProperty = null; - if (this.context.imageSmoothingEnabled) { + if (this.context.imageSmoothingEnabled) + { this.smoothProperty = 'imageSmoothingEnabled'; } - else if (this.context.webkitImageSmoothingEnabled) { + else if (this.context.webkitImageSmoothingEnabled) + { this.smoothProperty = 'webkitImageSmoothingEnabled'; } - else if (this.context.mozImageSmoothingEnabled) { + else if (this.context.mozImageSmoothingEnabled) + { this.smoothProperty = 'mozImageSmoothingEnabled'; } - else if (this.context.oImageSmoothingEnabled) { + else if (this.context.oImageSmoothingEnabled) + { this.smoothProperty = 'oImageSmoothingEnabled'; } - else if (this.context.msImageSmoothingEnabled) { + else if (this.context.msImageSmoothingEnabled) + { this.smoothProperty = 'msImageSmoothingEnabled'; } @@ -193,10 +203,12 @@ * @memberof CanvasRenderer# */ backgroundColor: { - get: function () { + get: function () + { return this._backgroundColor; }, - set: function (val) { + set: function (val) + { this._backgroundColor = val; this._backgroundColorString = utils.hex2string(val); } @@ -208,7 +220,8 @@ * * @param object {DisplayObject} the object to be rendered */ -CanvasRenderer.prototype.render = function (object) { +CanvasRenderer.prototype.render = function (object) +{ object.updateTransform(); this.context.setTransform(1,0,0,1,0,0); @@ -218,16 +231,20 @@ this.currentBlendMode = CONST.blendModes.NORMAL; this.context.globalCompositeOperation = this.blendModes[CONST.blendModes.NORMAL]; - if (navigator.isCocoonJS && this.view.screencanvas) { + if (navigator.isCocoonJS && this.view.screencanvas) + { this.context.fillStyle = 'black'; this.context.clear(); } - if (this.clearBeforeRender) { - if (this.transparent) { + if (this.clearBeforeRender) + { + if (this.transparent) + { this.context.clearRect(0, 0, this.width, this.height); } - else { + else + { this.context.fillStyle = this._backgroundColorString; this.context.fillRect(0, 0, this.width , this.height); } @@ -241,8 +258,10 @@ * * @param [removeView=false] {boolean} Removes the Canvas element from the DOM. */ -CanvasRenderer.prototype.destroy = function (removeView) { - if (removeView && this.view.parent) { +CanvasRenderer.prototype.destroy = function (removeView) +{ + if (removeView && this.view.parent) + { this.view.parent.removeChild(this.view); } @@ -257,14 +276,16 @@ * @param width {number} the new width of the canvas view * @param height {number} the new height of the canvas view */ -CanvasRenderer.prototype.resize = function (width, height) { +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) { + if (this.autoResize) + { this.view.style.width = this.width / this.resolution + 'px'; this.view.style.height = this.height / this.resolution + 'px'; } @@ -276,7 +297,8 @@ * @param displayObject {DisplayObject} The displayObject to render * @private */ -CanvasRenderer.prototype.renderDisplayObject = function (displayObject) { +CanvasRenderer.prototype.renderDisplayObject = function (displayObject) +{ displayObject.renderCanvas(this); }; @@ -285,11 +307,14 @@ * * @private */ -CanvasRenderer.prototype._mapBlendModes = function () { - if (!this.blendModes) { +CanvasRenderer.prototype._mapBlendModes = function () +{ + if (!this.blendModes) + { this.blendModes = {}; - if (utils.canUseNewCanvasBlendModes()) { + if (utils.canUseNewCanvasBlendModes()) + { this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? this.blendModes[CONST.blendModes.MULTIPLY] = 'multiply'; @@ -308,7 +333,8 @@ this.blendModes[CONST.blendModes.COLOR] = 'color'; this.blendModes[CONST.blendModes.LUMINOSITY] = 'luminosity'; } - else { + else + { // this means that the browser does not support the cool new blend modes in canvas 'cough' ie 'cough' this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? diff --git a/src/core/renderers/canvas/utils/CanvasBuffer.js b/src/core/renderers/canvas/utils/CanvasBuffer.js index ebe5d47..b183a66 100644 --- a/src/core/renderers/canvas/utils/CanvasBuffer.js +++ b/src/core/renderers/canvas/utils/CanvasBuffer.js @@ -6,7 +6,8 @@ * @param width {number} the width for the newly created canvas * @param height {number} the height for the newly created canvas */ -function CanvasBuffer(width, height) { +function CanvasBuffer(width, height) +{ /** * The Canvas object that belongs to this CanvasBuffer. * @@ -36,10 +37,12 @@ * @memberof CanvasBuffer# */ width: { - get: function () { + get: function () + { return this.canvas.width; }, - set: function (val) { + set: function (val) + { this.canvas.width = val; } }, @@ -50,10 +53,12 @@ * @memberof CanvasBuffer# */ height: { - get: function () { + get: function () + { return this.canvas.height; }, - set: function (val) { + set: function (val) + { this.canvas.height = val; } } @@ -64,7 +69,8 @@ * * @private */ -CanvasBuffer.prototype.clear = function () { +CanvasBuffer.prototype.clear = function () +{ this.context.setTransform(1, 0, 0, 1, 0, 0); this.context.clearRect(0,0, this.canvas.width, this.canvas.height); }; @@ -75,7 +81,8 @@ * @param width {number} the new width of the canvas * @param height {number} the new height of the canvas */ -CanvasBuffer.prototype.resize = function (width, height) { +CanvasBuffer.prototype.resize = function (width, height) +{ this.canvas.width = width; this.canvas.height = height; }; diff --git a/src/core/renderers/canvas/utils/CanvasGraphics.js b/src/core/renderers/canvas/utils/CanvasGraphics.js index c7eaa2a..3f2a91f 100644 --- a/src/core/renderers/canvas/utils/CanvasGraphics.js +++ b/src/core/renderers/canvas/utils/CanvasGraphics.js @@ -13,15 +13,18 @@ * @param graphics {Graphics} the actual graphics object to render * @param context {CanvasRenderingContext2D} the 2d drawing method of the canvas */ -CanvasGraphics.renderGraphics = function (graphics, context) { +CanvasGraphics.renderGraphics = function (graphics, context) +{ var worldAlpha = graphics.worldAlpha; - if (graphics.dirty) { + if (graphics.dirty) + { this.updateGraphicsTint(graphics); graphics.dirty = false; } - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; @@ -30,69 +33,82 @@ context.lineWidth = data.lineWidth; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { context.beginPath(); var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } - if (shape.closed) { + if (shape.closed) + { context.lineTo(points[0], points[1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fillRect(shape.x, shape.y, shape.width, shape.height); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.strokeRect(shape.x, shape.y, shape.width, shape.height); } } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.beginPath(); context.arc(shape.x, shape.y, shape.radius,0,2*Math.PI); context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas var w = shape.width * 2; @@ -119,18 +135,21 @@ context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; var width = shape.width; @@ -152,13 +171,15 @@ context.quadraticCurveTo(rx, ry, rx, ry + radius); context.closePath(); - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); @@ -174,45 +195,54 @@ * @param graphics {Graphics} the graphics which will be used as a mask * @param context {CanvasRenderingContext2D} the context 2d method of the canvas */ -CanvasGraphics.renderGraphicsMask = function (graphics, context) { +CanvasGraphics.renderGraphicsMask = function (graphics, context) +{ var len = graphics.graphicsData.length; - if (len === 0) { + if (len === 0) + { return; } context.beginPath(); - for (var i = 0; i < len; i++) { + for (var i = 0; i < len; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { context.rect(shape.x, shape.y, shape.width, shape.height); context.closePath(); } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.arc(shape.x, shape.y, shape.radius, 0, 2 * Math.PI); context.closePath(); } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas @@ -237,7 +267,8 @@ context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); context.closePath(); } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; @@ -262,8 +293,10 @@ } }; -CanvasGraphics.updateGraphicsTint = function (graphics) { - if (graphics.tint === 0xFFFFFF) { +CanvasGraphics.updateGraphicsTint = function (graphics) +{ + if (graphics.tint === 0xFFFFFF) + { return; } @@ -271,7 +304,8 @@ var tintG = (graphics.tint >> 8 & 0xFF) / 255; var tintB = (graphics.tint & 0xFF)/ 255; - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var fillColor = data.fillColor | 0; diff --git a/src/core/renderers/canvas/utils/CanvasMaskManager.js b/src/core/renderers/canvas/utils/CanvasMaskManager.js index e04a733..9827d36 100644 --- a/src/core/renderers/canvas/utils/CanvasMaskManager.js +++ b/src/core/renderers/canvas/utils/CanvasMaskManager.js @@ -6,7 +6,8 @@ * @class * @namespace PIXI */ -function CanvasMaskManager() {} +function CanvasMaskManager() +{} CanvasMaskManager.prototype.constructor = CanvasMaskManager; module.exports = CanvasMaskManager; @@ -17,7 +18,8 @@ * @param maskData {object} the maskData that will be pushed * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.pushMask = function (maskData, renderer) { +CanvasMaskManager.prototype.pushMask = function (maskData, renderer) +{ renderer.context.save(); var cacheAlpha = maskData.alpha; @@ -45,6 +47,7 @@ * * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.popMask = function (renderer) { +CanvasMaskManager.prototype.popMask = function (renderer) +{ renderer.context.restore(); }; diff --git a/src/core/renderers/canvas/utils/CanvasTinter.js b/src/core/renderers/canvas/utils/CanvasTinter.js index 17e0529..d2fb1bc 100644 --- a/src/core/renderers/canvas/utils/CanvasTinter.js +++ b/src/core/renderers/canvas/utils/CanvasTinter.js @@ -14,7 +14,8 @@ * @param color {number} the color to use to tint the sprite with * @return {HTMLCanvasElement} The tinted canvas */ -CanvasTinter.getTintedTexture = function (sprite, color) { +CanvasTinter.getTintedTexture = function (sprite, color) +{ var texture = sprite.texture; color = CanvasTinter.roundColor(color); @@ -23,7 +24,8 @@ texture.tintCache = texture.tintCache || {}; - if (texture.tintCache[stringColor]) { + if (texture.tintCache[stringColor]) + { return texture.tintCache[stringColor]; } @@ -33,14 +35,16 @@ //CanvasTinter.tintWithPerPixel(texture, stringColor, canvas); CanvasTinter.tintMethod(texture, color, canvas); - if (CanvasTinter.convertTintToImage) { + if (CanvasTinter.convertTintToImage) + { // is this better? var tintImage = new Image(); tintImage.src = canvas.toDataURL(); texture.tintCache[stringColor] = tintImage; } - else { + else + { texture.tintCache[stringColor] = canvas; // if we are not converting the texture to an image then we need to lose the reference to the canvas CanvasTinter.canvas = null; @@ -56,7 +60,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithMultiply = function (texture, color, canvas) { +CanvasTinter.tintWithMultiply = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -104,7 +109,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithOverlay = function (texture, color, canvas) { +CanvasTinter.tintWithOverlay = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -139,7 +145,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithPerPixel = function (texture, color, canvas) { +CanvasTinter.tintWithPerPixel = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -167,7 +174,8 @@ var pixels = pixelData.data; - for (var i = 0; i < pixels.length; i += 4) { + for (var i = 0; i < pixels.length; i += 4) + { pixels[i+0] *= r; pixels[i+1] *= g; pixels[i+2] *= b; @@ -181,7 +189,8 @@ * * @param color {number} the color to round, should be a hex color */ -CanvasTinter.roundColor = function (color) { +CanvasTinter.roundColor = function (color) +{ var step = CanvasTinter.cacheStepsPerColorChannel; var rgbValues = utils.hex2rgb(color); diff --git a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js index 9f2f89a..35edbaf 100644 --- a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js +++ b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLBlendModeManager(renderer) { +function WebGLBlendModeManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -23,8 +24,10 @@ * * @param blendMode {number} the blendMode, should be a Pixi const, such as BlendModes.ADD */ -WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) { - if (this.currentBlendMode === blendMode) { +WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) +{ + if (this.currentBlendMode === blendMode) + { return false; } diff --git a/src/core/renderers/webgl/managers/WebGLFilterManager.js b/src/core/renderers/webgl/managers/WebGLFilterManager.js index 1179258..2dac048 100644 --- a/src/core/renderers/webgl/managers/WebGLFilterManager.js +++ b/src/core/renderers/webgl/managers/WebGLFilterManager.js @@ -7,7 +7,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLFilterManager(renderer) { +function WebGLFilterManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -32,7 +33,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.texturePool.length = 0; self.initShaderBuffers(); }); @@ -46,7 +48,8 @@ * @param renderer {WebGLRenderer} * @param buffer {ArrayBuffer} */ -WebGLFilterManager.prototype.begin = function (buffer) { +WebGLFilterManager.prototype.begin = function (buffer) +{ this.defaultShader = this.renderer.shaderManager.defaultShader; this.width = this.renderer.projection.x * 2; @@ -60,7 +63,8 @@ * * @param filterBlock {object} the filter that will be pushed to the current filter stack */ -WebGLFilterManager.prototype.pushFilter = function (filterBlock) { +WebGLFilterManager.prototype.pushFilter = function (filterBlock) +{ var gl = this.renderer.gl; var projection = this.renderer.projection; @@ -78,10 +82,12 @@ this.offsetY += filterBlock._filterArea.y; var texture = this.texturePool.pop(); - if (!texture) { + if (!texture) + { texture = new FilterTexture(this.renderer.gl, this.width, this.height); } - else { + else + { texture.resize(this.width, this.height); } @@ -98,29 +104,35 @@ var localX = filterArea.x, localY = filterArea.y; - if (filterArea.x < 0) { + if (filterArea.x < 0) + { filterArea.width += filterArea.x; filterArea.x = 0; } - if (filterArea.y < 0) { + if (filterArea.y < 0) + { filterArea.height += filterArea.y; filterArea.y = 0; } - if (localX + filterArea.width > this.width) { + if (localX + filterArea.width > this.width) + { filterArea.width = this.width - localX; } - if (localY + filterArea.height > this.height) { + if (localY + filterArea.height > this.height) + { filterArea.height = this.height - localY; } - if (filterArea.width < 0) { + if (filterArea.width < 0) + { filterArea.width = 0; } - if (filterArea.height < 0) { + if (filterArea.height < 0) + { filterArea.height = 0; } @@ -154,7 +166,8 @@ * Removes the last filter from the filter stack and doesn't return it. * */ -WebGLFilterManager.prototype.popFilter = function () { +WebGLFilterManager.prototype.popFilter = function () +{ var gl = this.renderer.gl; var filterBlock = this.filterStack.pop(); @@ -163,7 +176,8 @@ var projection = this.renderer.projection; var offset = this.renderer.offset; - if (filterBlock.filterPasses.length > 1) { + if (filterBlock.filterPasses.length > 1) + { gl.viewport(0, 0, filterArea.width, filterArea.height); gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); @@ -193,7 +207,8 @@ var inputTexture = texture; var outputTexture = this.texturePool.pop(); - if (!outputTexture) { + if (!outputTexture) + { outputTexture = new FilterTexture(this.renderer.gl, this.width, this.height); } outputTexture.resize(this.width, this.height); @@ -204,7 +219,8 @@ gl.disable(gl.BLEND); - for (var i = 0; i < filterBlock.filterPasses.length-1; i++) { + for (var i = 0; i < filterBlock.filterPasses.length-1; i++) + { var filterPass = filterBlock.filterPasses[i]; gl.bindFramebuffer(gl.FRAMEBUFFER, outputTexture.frameBuffer ); @@ -243,10 +259,12 @@ var buffer = this.buffer; // time to render the filters texture to the previous scene - if (this.filterStack.length === 0) { + if (this.filterStack.length === 0) + { gl.colorMask(true, true, true, true);//this.transparent); } - else { + else + { var currentFilter = this.filterStack[this.filterStack.length-1]; filterArea = currentFilter._filterArea; @@ -332,13 +350,15 @@ * @param width {number} the horizontal range of the filter * @param height {number} the vertical range of the filter */ -WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) { +WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) +{ // use program var gl = this.renderer.gl; var shader = filter.shaders[gl.id]; - if (!shader) { + if (!shader) + { shader = new Shader(gl); shader.fragmentSrc = filter.fragmentSrc; @@ -356,7 +376,8 @@ gl.uniform2f(shader.projectionVector, width/2, -height/2); gl.uniform2f(shader.offsetVector, 0,0); - if (filter.uniforms.dimensions) { + 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]; @@ -386,7 +407,8 @@ * Initialises the shader buffers. * */ -WebGLFilterManager.prototype.initShaderBuffers = function () { +WebGLFilterManager.prototype.initShaderBuffers = function () +{ var gl = this.renderer.gl; // create some buffers @@ -432,7 +454,8 @@ * Destroys the filter and removes it from the filter stack. * */ -WebGLFilterManager.prototype.destroy = function () { +WebGLFilterManager.prototype.destroy = function () +{ var gl = this.renderer.gl; this.filterStack = null; @@ -441,7 +464,8 @@ this.offsetY = 0; // destroy textures - for (var i = 0; i < this.texturePool.length; i++) { + for (var i = 0; i < this.texturePool.length; i++) + { this.texturePool[i].destroy(); } diff --git a/src/core/renderers/webgl/managers/WebGLManager.js b/src/core/renderers/webgl/managers/WebGLManager.js index 9d47b5c..c30cd51 100644 --- a/src/core/renderers/webgl/managers/WebGLManager.js +++ b/src/core/renderers/webgl/managers/WebGLManager.js @@ -3,7 +3,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLManager(renderer) { +function WebGLManager(renderer) +{ /** * The renderer this manager works for. * @@ -15,6 +16,7 @@ WebGLManager.prototype.constructor = WebGLManager; module.exports = WebGLManager; -WebGLManager.prototype.destroy = function () { +WebGLManager.prototype.destroy = function () +{ this.renderer = null; }; diff --git a/src/core/renderers/webgl/managers/WebGLMaskManager.js b/src/core/renderers/webgl/managers/WebGLMaskManager.js index 2f90b64..e568812 100644 --- a/src/core/renderers/webgl/managers/WebGLMaskManager.js +++ b/src/core/renderers/webgl/managers/WebGLMaskManager.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLMaskManager(renderer) { +function WebGLMaskManager(renderer) +{ WebGLManager.call(this, renderer); } @@ -19,12 +20,15 @@ * * @param maskData {any[]} */ -WebGLMaskManager.prototype.pushMask = function (maskData) { - if (maskData.dirty) { +WebGLMaskManager.prototype.pushMask = function (maskData) +{ + if (maskData.dirty) + { WebGLGraphics.updateGraphics(maskData, this.renderer.gl); } - if (!maskData._webGL[this.renderer.gl.id].data.length) { + if (!maskData._webGL[this.renderer.gl.id].data.length) + { return; } @@ -36,6 +40,7 @@ * * @param maskData {any[]} */ -WebGLMaskManager.prototype.popMask = function (maskData) { +WebGLMaskManager.prototype.popMask = function (maskData) +{ this.renderer.stencilManager.popStencil(maskData, maskData._webGL[this.renderer.gl.id].data[0], this.renderer); }; diff --git a/src/core/renderers/webgl/managers/WebGLShaderManager.js b/src/core/renderers/webgl/managers/WebGLShaderManager.js index fef071c..90c6477 100644 --- a/src/core/renderers/webgl/managers/WebGLShaderManager.js +++ b/src/core/renderers/webgl/managers/WebGLShaderManager.js @@ -10,7 +10,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLShaderManager(renderer) { +function WebGLShaderManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -28,7 +29,8 @@ */ this.tempAttribState = []; - for (var i = 0; i < this.maxAttibs; i++) { + for (var i = 0; i < this.maxAttibs; i++) + { this.attribState[i] = false; } @@ -66,7 +68,8 @@ // listen for context and update necessary shaders var self = this; - this.renderer.on('context', function (event) { + this.renderer.on('context', function (event) + { var gl = event.data; // this shader is used for rendering primitives @@ -97,29 +100,36 @@ * * @param attribs {Array} attribs */ -WebGLShaderManager.prototype.setAttribs = function (attribs) { +WebGLShaderManager.prototype.setAttribs = function (attribs) +{ // reset temp state var i; - for (i = 0; i < this.tempAttribState.length; i++) { + for (i = 0; i < this.tempAttribState.length; i++) + { this.tempAttribState[i] = false; } // set the new attribs - for (var a in attribs) { + for (var a in attribs) + { this.tempAttribState[attribs[a]] = true; } var gl = this.renderer.gl; - for (i = 0; i < this.attribState.length; i++) { - if (this.attribState[i] !== this.tempAttribState[i]) { + for (i = 0; i < this.attribState.length; i++) + { + if (this.attribState[i] !== this.tempAttribState[i]) + { this.attribState[i] = this.tempAttribState[i]; - if (this.attribState[i]) { + if (this.attribState[i]) + { gl.enableVertexAttribArray(i); } - else { + else + { gl.disableVertexAttribArray(i); } } @@ -131,8 +141,10 @@ * * @param shader {Any} */ -WebGLShaderManager.prototype.setShader = function (shader) { - if (this._currentId === shader.uuid) { +WebGLShaderManager.prototype.setShader = function (shader) +{ + if (this._currentId === shader.uuid) + { return false; } @@ -150,7 +162,8 @@ * Destroys this object. * */ -WebGLShaderManager.prototype.destroy = function () { +WebGLShaderManager.prototype.destroy = function () +{ this.attribState = null; this.tempAttribState = null; diff --git a/src/core/renderers/webgl/managers/WebGLStencilManager.js b/src/core/renderers/webgl/managers/WebGLStencilManager.js index 9ec6398..4cb0134 100644 --- a/src/core/renderers/webgl/managers/WebGLStencilManager.js +++ b/src/core/renderers/webgl/managers/WebGLStencilManager.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLStencilManager(renderer) { +function WebGLStencilManager(renderer) +{ WebGLManager.call(this, renderer); this.stencilStack = []; @@ -24,12 +25,14 @@ * @param graphics {Graphics} * @param webGLData {any[]} */ -WebGLStencilManager.prototype.pushStencil = function (graphics, webGLData) { +WebGLStencilManager.prototype.pushStencil = function (graphics, webGLData) +{ var gl = this.renderer.gl; this.bindGraphics(graphics, webGLData, this.renderer); - if (this.stencilStack.length === 0) { + if (this.stencilStack.length === 0) + { gl.enable(gl.STENCIL_TEST); gl.clear(gl.STENCIL_BUFFER_BIT); this.reverse = true; @@ -47,14 +50,17 @@ // draw the triangle strip! - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } @@ -62,31 +68,38 @@ // draw a quad to increment.. gl.drawElements(gl.TRIANGLE_FAN, 4, gl.UNSIGNED_SHORT, ( webGLData.indices.length - 4 ) * 2 ); - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); } this.reverse = !this.reverse; } - else { - if (!this.reverse) { + else + { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } - else { + 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) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); } } @@ -103,7 +116,8 @@ * @param graphics {Graphics} * @param webGLData {Array} */ -WebGLStencilManager.prototype.bindGraphics = function (graphics, webGLData) { +WebGLStencilManager.prototype.bindGraphics = function (graphics, webGLData) +{ //if (this._currentGraphics === graphics)return; this._currentGraphics = graphics; @@ -114,7 +128,8 @@ offset = this.renderer.offset, shader;// = this.renderer.shaderManager.primitiveShader; - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { shader = this.renderer.shaderManager.complexPrimitiveShader; this.renderer.shaderManager.setShader(shader); @@ -141,7 +156,8 @@ // set the index buffer! gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, webGLData.indexBuffer); } - else { + else + { //this.renderer.shaderManager.activatePrimitiveShader(); shader = this.renderer.shaderManager.primitiveShader; this.renderer.shaderManager.setShader( shader ); @@ -154,7 +170,7 @@ gl.uniform2f(shader.uniforms.offsetVector._location, -offset.x, -offset.y); gl.uniform3fv(shader.uniforms.tint._location, utils.hex2rgb(graphics.tint)); - + gl.uniform1f(shader.uniforms.alpha._location, graphics.worldAlpha); @@ -172,19 +188,22 @@ * @param graphics {Graphics} * @param webGLData {Array} */ -WebGLStencilManager.prototype.popStencil = function (graphics, webGLData) { +WebGLStencilManager.prototype.popStencil = function (graphics, webGLData) +{ var gl = this.renderer.gl; this.stencilStack.pop(); this.count--; - if (this.stencilStack.length === 0) { + if (this.stencilStack.length === 0) + { // the stack is empty! gl.disable(gl.STENCIL_TEST); } - else { + else + { var level = this.count; @@ -192,14 +211,17 @@ gl.colorMask(false, false, false, false); - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { this.reverse = !this.reverse; - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } @@ -213,31 +235,38 @@ // draw the triangle strip! gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); - if (!this.reverse) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); } } - else { + else + { // console.log("<<>>") - if (!this.reverse) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } - else { + 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) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); } } @@ -253,7 +282,8 @@ * Destroys the mask stack. * */ -WebGLStencilManager.prototype.destroy = function () { +WebGLStencilManager.prototype.destroy = function () +{ this.renderer = null; this.stencilStack = null; }; diff --git a/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js b/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js index 913ba5e..1ea7d19 100644 --- a/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js +++ b/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function ComplexPrimitiveShader(gl) { +function ComplexPrimitiveShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -24,7 +25,8 @@ 'uniform float flipY;', 'varying vec4 vColor;', - 'void main(void) {', + '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);', @@ -37,7 +39,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = vColor;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/FastShader.js b/src/core/renderers/webgl/shaders/FastShader.js index bd2e29a..2e5e060 100644 --- a/src/core/renderers/webgl/shaders/FastShader.js +++ b/src/core/renderers/webgl/shaders/FastShader.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function FastShader(gl) { +function FastShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -28,7 +29,8 @@ 'const vec2 center = vec2(-1.0, 1.0);', - 'void main(void) {', + 'void main(void) + {', ' vec2 v;', ' vec2 sv = aVertexPosition * aScale;', ' v.x = (sv.x) * cos(aRotation) - (sv.y) * sin(aRotation);', @@ -49,7 +51,8 @@ 'uniform sampler2D uSampler;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/PrimitiveShader.js b/src/core/renderers/webgl/shaders/PrimitiveShader.js index 6f25409..a25f54f 100644 --- a/src/core/renderers/webgl/shaders/PrimitiveShader.js +++ b/src/core/renderers/webgl/shaders/PrimitiveShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function PrimitiveShader(gl) { +function PrimitiveShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -23,7 +24,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + '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);', @@ -36,7 +38,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = vColor;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/Shader.js b/src/core/renderers/webgl/shaders/Shader.js index f8964f5..fd75ef5 100644 --- a/src/core/renderers/webgl/shaders/Shader.js +++ b/src/core/renderers/webgl/shaders/Shader.js @@ -6,7 +6,8 @@ * @param [fragmentSrc] {string} The source of the fragment shader. * @param [vertexSrc] {string} The source of the vertex shader. */ -function Shader(gl, vertexSrc, fragmentSrc, customUniforms, customAttributes) { +function Shader(gl, vertexSrc, fragmentSrc, customUniforms, customAttributes) +{ /** * @member {number} * @readonly @@ -33,7 +34,8 @@ dimensions: { type: '4f', value: new Float32Array(4) } }; - for (var u in customUniforms) { + for (var u in customUniforms) + { this.uniforms[u] = customUniforms[u]; } @@ -43,7 +45,8 @@ aColor: 0 }; - for (var a in customAttributes) { + for (var a in customAttributes) + { this.attributes[a] = customAttributes[a]; } @@ -66,7 +69,8 @@ 'const vec2 center = vec2(-1.0, 1.0);', - 'void main(void) {', + 'void main(void) + {', ' gl_Position = vec4( ((aVertexPosition + offsetVector) / projectionVector) + center , 0.0, 1.0);', ' vTextureCoord = aTextureCoord;', ' vColor = vec4(aColor.rgb * aColor.a, aColor.a);', @@ -85,7 +89,8 @@ 'uniform sampler2D uSampler;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;', '}' ].join('\n'); @@ -96,7 +101,8 @@ Shader.prototype.constructor = Shader; module.exports = Shader; -Shader.prototype.init = function () { +Shader.prototype.init = function () +{ this.compile(); this.gl.useProgram(this.program); @@ -105,14 +111,18 @@ this.cacheAttributeLocations(Object.keys(this.attributes)); }; -Shader.prototype.cacheUniformLocations = function (keys) { - for (var i = 0; i < keys.length; ++i) { +Shader.prototype.cacheUniformLocations = function (keys) +{ + for (var i = 0; i < keys.length; ++i) + { this.uniforms[keys[i]]._location = this.gl.getUniformLocation(this.program, keys[i]); } }; -Shader.prototype.cacheAttributeLocations = function (keys) { - for (var i = 0; i < keys.length; ++i) { +Shader.prototype.cacheAttributeLocations = function (keys) +{ + for (var i = 0; i < keys.length; ++i) + { this.attributes[keys[i]] = this.gl.getAttribLocation(this.program, keys[i]); } @@ -124,14 +134,16 @@ // 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.attributes.aColor === -1) { + // if (this.attributes.aColor === -1) + { // this.attributes.aColor = 2; // } // End worst hack eva // }; -Shader.prototype.compile = function () { +Shader.prototype.compile = function () +{ var gl = this.gl; var glVertShader = this._glCompile(gl.VERTEX_SHADER, this.vertexSrc); @@ -144,13 +156,15 @@ gl.linkProgram(program); // if linking fails, then log and cleanup - if (!gl.getProgramParameter(program, gl.LINK_STATUS)) { + if (!gl.getProgramParameter(program, gl.LINK_STATUS)) + { window.console.error('Pixi.js Error: Could not initialize shader.'); window.console.error('gl.VALIDATE_STATUS', gl.getProgramParameter(program, gl.VALIDATE_STATUS)); window.console.error('gl.getError()', gl.getError()); // if there is a program info log, log it - if (gl.getProgramInfoLog(program) !== '') { + if (gl.getProgramInfoLog(program) !== '') + { window.console.warn('Pixi.js Warning: gl.getProgramInfoLog()', gl.getProgramInfoLog(program)); } @@ -165,18 +179,21 @@ return (this.program = program); }; -Shader.prototype.syncUniforms = function () { +Shader.prototype.syncUniforms = function () +{ var gl = this.gl; this.textureCount = 1; - for (var key in this.uniforms) { + for (var key in this.uniforms) + { var uniform = this.uniforms[key], location = uniform._location, value = uniform.value, i, il; - switch (uniform.type) { + switch (uniform.type) + { // single int value case 'i': case '1i': @@ -282,7 +299,8 @@ // a Color Value case 'c': - if (typeof value === 'number') { + if (typeof value === 'number') + { value = utils.hex2rgb(value); } @@ -311,11 +329,13 @@ // array of 2D Point objects case 'v2v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(2 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 2] = value[i].x; uniform._array[i * 2 + 1] = value[i].y; } @@ -325,11 +345,13 @@ // array of 3D Point objects case 'v3v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(3 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 3] = value[i].x; uniform._array[i * 3 + 1] = value[i].y; uniform._array[i * 3 + 2] = value[i].z; @@ -341,11 +363,13 @@ // array of 4D Point objects case 'v4v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(4 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 4] = value[i].x; uniform._array[i * 4 + 1] = value[i].y; uniform._array[i * 4 + 2] = value[i].z; @@ -359,7 +383,8 @@ // PIXI.Texture case 't': case 'sampler2D': - if (!uniform.value || !uniform.value.baseTexture || !uniform.value.baseTexture.hasLoaded) { + if (!uniform.value || !uniform.value.baseTexture || !uniform.value.baseTexture.hasLoaded) + { break; } @@ -376,7 +401,8 @@ this.textureCount++; // initialize the texture if we haven't yet - if (!uniform._init) { + if (!uniform._init) + { this.initSampler2D(uniform); uniform._init = true; @@ -394,11 +420,13 @@ * Initialises a Sampler2D uniform (which may only be available later on after initUniforms once the texture has loaded) * */ -Shader.prototype.initSampler2D = function (uniform) { +Shader.prototype.initSampler2D = function (uniform) +{ var gl = this.gl; // Extended texture data - if (uniform.textureData) { + if (uniform.textureData) + { var data = uniform.textureData; // GLTexture = mag linear, min linear_mipmap_linear, wrap repeat + gl.generateMipmap(gl.TEXTURE_2D); @@ -417,14 +445,16 @@ var wrapT = (data.wrapT) ? data.wrapT : gl.CLAMP_TO_EDGE; var format = (data.luminance) ? gl.LUMINANCE : gl.RGBA; - if (data.repeat) { + if (data.repeat) + { wrapS = gl.REPEAT; wrapT = gl.REPEAT; } gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, !!data.flipY); - if (data.width) { + if (data.width) + { var width = (data.width) ? data.width : 512; var height = (data.height) ? data.height : 2; var border = (data.border) ? data.border : 0; @@ -432,7 +462,8 @@ // 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 { + 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); } @@ -448,7 +479,8 @@ * Destroys the shader. * */ -Shader.prototype.destroy = function () { +Shader.prototype.destroy = function () +{ this.gl.deleteProgram(this.program); this.gl = null; @@ -459,13 +491,15 @@ this.fragmentSrc = null; }; -Shader.prototype._glCompile = function (type, src) { +Shader.prototype._glCompile = function (type, src) +{ var shader = this.gl.createShader(type); this.gl.shaderSource(shader, src); this.gl.compileShader(shader); - if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) { + if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) + { window.console.log(this.gl.getShaderInfoLog(shader)); return null; } diff --git a/src/core/renderers/webgl/shaders/StripShader.js b/src/core/renderers/webgl/shaders/StripShader.js index 193f6e1..a7abcc6 100644 --- a/src/core/renderers/webgl/shaders/StripShader.js +++ b/src/core/renderers/webgl/shaders/StripShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function StripShader(gl) { +function StripShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -20,7 +21,8 @@ 'varying vec2 vTextureCoord;', - 'void main(void) {', + '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);', @@ -36,7 +38,8 @@ 'varying vec2 vTextureCoord;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vec2(vTextureCoord.x, vTextureCoord.y)) * alpha;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/utils/FilterTexture.js b/src/core/renderers/webgl/utils/FilterTexture.js index d2c8423..4433d44 100644 --- a/src/core/renderers/webgl/utils/FilterTexture.js +++ b/src/core/renderers/webgl/utils/FilterTexture.js @@ -8,7 +8,8 @@ * @param height {number} the vertical range of the filter * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values */ -function FilterTexture(gl, width, height, scaleMode) { +function FilterTexture(gl, width, height, scaleMode) +{ /** * @member {WebGLContext} */ @@ -59,7 +60,8 @@ * Clears the filter texture. * */ -FilterTexture.prototype.clear = function () { +FilterTexture.prototype.clear = function () +{ var gl = this.gl; gl.clearColor(0,0,0, 0); @@ -72,8 +74,10 @@ * @param width {number} the new width of the texture * @param height {number} the new height of the texture */ -FilterTexture.prototype.resize = function (width, height) { - if (this.width === width && this.height === height) { +FilterTexture.prototype.resize = function (width, height) +{ + if (this.width === width && this.height === height) + { return; } @@ -96,7 +100,8 @@ * Destroys the filter texture. * */ -FilterTexture.prototype.destroy = function () { +FilterTexture.prototype.destroy = function () +{ var gl = this.gl; gl.deleteFramebuffer( this.frameBuffer ); gl.deleteTexture( this.texture ); diff --git a/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js b/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js index c4721e9..a63f4d7 100644 --- a/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js +++ b/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js @@ -14,7 +14,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this sprite batch works for. */ -function WebGLFastSpriteBatch(renderer) { +function WebGLFastSpriteBatch(renderer) +{ /** * The renderer instance this sprite batch operates on. * @@ -91,7 +92,8 @@ */ this.lastIndexCount = 0; - for (var i=0, j=0; i < numIndices; i += 6, j += 4) { + 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; @@ -144,7 +146,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.setupContext(); }); } @@ -157,7 +160,8 @@ * * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLFastSpriteBatch.prototype.setupContext = function () { +WebGLFastSpriteBatch.prototype.setupContext = function () +{ var gl = this.renderer.gl; // create a couple of buffers @@ -177,7 +181,8 @@ /** * @param spriteBatch {SpriteBatch} The SpriteBatch container to prepare for. */ -WebGLFastSpriteBatch.prototype.begin = function (spriteBatch) { +WebGLFastSpriteBatch.prototype.begin = function (spriteBatch) +{ this.shader = this.renderer.shaderManager.fastShader; this.matrix = spriteBatch.worldTransform.toArray(true); @@ -187,33 +192,38 @@ /** */ -WebGLFastSpriteBatch.prototype.end = function () { +WebGLFastSpriteBatch.prototype.end = function () +{ this.flush(); }; /** * @param spriteBatch {SpriteBatch} The SpriteBatch container to render. */ -WebGLFastSpriteBatch.prototype.render = function (spriteBatch) { +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) { + if (!sprite.texture._uvs) + { return; } this.currentBaseTexture = sprite.texture.baseTexture; // check blend mode - if (sprite.blendMode !== this.renderer.blendModeManager.currentBlendMode) { + if (sprite.blendMode !== this.renderer.blendModeManager.currentBlendMode) + { this.flush(); this.renderer.blendModeManager.setBlendMode(sprite.blendMode); } - for (var i=0,j= children.length; i= this.size) { + if (this.currentBatchSize >= this.size) + { this.flush(); } }; @@ -362,29 +379,35 @@ /** * */ -WebGLFastSpriteBatch.prototype.flush = function () { +WebGLFastSpriteBatch.prototype.flush = function () +{ // If the batch is length 0 then return as there is nothing to draw - if (this.currentBatchSize === 0) { + if (this.currentBatchSize === 0) + { return; } var gl = this.renderer.gl; // bind the current texture - if (!this.currentBaseTexture._glTextures[gl.id]) { + if (!this.currentBaseTexture._glTextures[gl.id]) + { this.renderer.updateTexture(this.currentBaseTexture, gl); } //TODO-SHOUD THIS BE ELSE??!?!?! - else { + else + { gl.bindTexture(gl.TEXTURE_2D, this.currentBaseTexture._glTextures[gl.id]); } // upload the verts to the buffer - if (this.currentBatchSize > ( this.size * 0.5 ) ) { + if (this.currentBatchSize > ( this.size * 0.5 ) ) + { gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); } - else { + else + { var view = this.vertices.subarray(0, this.currentBatchSize * this.vertByteSize); gl.bufferSubData(gl.ARRAY_BUFFER, 0, view); @@ -405,14 +428,16 @@ * Ends the batch and flushes * */ -WebGLFastSpriteBatch.prototype.stop = function () { +WebGLFastSpriteBatch.prototype.stop = function () +{ this.flush(); }; /** * */ -WebGLFastSpriteBatch.prototype.start = function () { +WebGLFastSpriteBatch.prototype.start = function () +{ var gl = this.renderer.gl; // bind the main texture diff --git a/src/core/renderers/webgl/utils/WebGLGraphics.js b/src/core/renderers/webgl/utils/WebGLGraphics.js index 55f4911..ab8f46e 100644 --- a/src/core/renderers/webgl/utils/WebGLGraphics.js +++ b/src/core/renderers/webgl/utils/WebGLGraphics.js @@ -19,7 +19,8 @@ * @param graphics {Graphics} * @param renderer {WebGLRenderer} */ -WebGLGraphics.renderGraphics = function (graphics, renderer) {//projection, offset) { +WebGLGraphics.renderGraphics = function (graphics, renderer) {//projection, offset) +{ var gl = renderer.gl; var projection = renderer.projection, @@ -27,7 +28,8 @@ shader = renderer.shaderManager.primitiveShader, webGLData; - if (graphics.dirty) { + if (graphics.dirty) + { WebGLGraphics.updateGraphics(graphics, gl); } @@ -35,8 +37,10 @@ // This could be speeded up for sure! - for (var i = 0; i < webGL.data.length; i++) { - if (webGL.data[i].mode === 1) { + for (var i = 0; i < webGL.data.length; i++) + { + if (webGL.data[i].mode === 1) + { webGLData = webGL.data[i]; renderer.stencilManager.pushStencil(graphics, webGLData, renderer); @@ -46,7 +50,8 @@ renderer.stencilManager.popStencil(graphics, webGLData, renderer); } - else { + else + { webGLData = webGL.data[i]; @@ -84,12 +89,14 @@ * @param graphicsData {Graphics} The graphics object to update * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLGraphics.updateGraphics = function (graphics, gl) { +WebGLGraphics.updateGraphics = function (graphics, gl) +{ // get the contexts graphics object var webGL = graphics._webGL[gl.id]; // if the graphics object does not exist in the webGL context time to create it! - if (!webGL) { + if (!webGL) + { webGL = graphics._webGL[gl.id] = {lastIndex:0, data:[], gl:gl}; } @@ -99,11 +106,13 @@ var i; // if the user cleared the graphics object we will need to clear every object - if (graphics.clearDirty) { + if (graphics.clearDirty) + { graphics.clearDirty = false; // lop through and return all the webGLDatas to the object pool so than can be reused later on - for (i = 0; i < webGL.data.length; i++) { + for (i = 0; i < webGL.data.length; i++) + { var graphicsData = webGL.data[i]; graphicsData.reset(); WebGLGraphics.graphicsDataPool.push( graphicsData ); @@ -119,58 +128,72 @@ // loop through the graphics datas and construct each one.. // if the object is a complex fill then the new stencil buffer technique will be used // other wise graphics objects will be pushed into a batch.. - for (i = webGL.lastIndex; i < graphics.graphicsData.length; i++) { + for (i = webGL.lastIndex; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { // need to add the points the the graphics object.. data.points = data.shape.points.slice(); - if (data.shape.closed) { + if (data.shape.closed) + { // close the poly if the value is true! - if (data.points[0] !== data.points[data.points.length-2] || data.points[1] !== data.points[data.points.length-1]) { + if (data.points[0] !== data.points[data.points.length-2] || data.points[1] !== data.points[data.points.length-1]) + { data.points.push(data.points[0], data.points[1]); } } // MAKE SURE WE HAVE THE CORRECT TYPE.. - if (data.fill) { - if (data.points.length >= 6) { - if (data.points.length < 6 * 2) { + if (data.fill) + { + if (data.points.length >= 6) + { + if (data.points.length < 6 * 2) + { webGLData = WebGLGraphics.switchMode(webGL, 0); var canDrawUsingSimple = WebGLGraphics.buildPoly(data, webGLData); // console.log(canDrawUsingSimple); - if (!canDrawUsingSimple) { + if (!canDrawUsingSimple) + { // console.log("<>>>") webGLData = WebGLGraphics.switchMode(webGL, 1); WebGLGraphics.buildComplexPoly(data, webGLData); } } - else { + else + { webGLData = WebGLGraphics.switchMode(webGL, 1); WebGLGraphics.buildComplexPoly(data, webGLData); } } } - if (data.lineWidth > 0) { + if (data.lineWidth > 0) + { webGLData = WebGLGraphics.switchMode(webGL, 0); WebGLGraphics.buildLine(data, webGLData); } } - else { + else + { webGLData = WebGLGraphics.switchMode(webGL, 0); - if (data.type === CONST.SHAPES.RECT) { + if (data.type === CONST.SHAPES.RECT) + { WebGLGraphics.buildRectangle(data, webGLData); } - else if (data.type === CONST.SHAPES.CIRC || data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.CIRC || data.type === CONST.SHAPES.ELIP) + { WebGLGraphics.buildCircle(data, webGLData); } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { WebGLGraphics.buildRoundedRectangle(data, webGLData); } } @@ -179,10 +202,12 @@ } // upload all the dirty data... - for (i = 0; i < webGL.data.length; i++) { + for (i = 0; i < webGL.data.length; i++) + { webGLData = webGL.data[i]; - if (webGLData.dirty) { + if (webGLData.dirty) + { webGLData.upload(); } } @@ -194,18 +219,22 @@ * @param webGL {WebGLContext} * @param type {number} */ -WebGLGraphics.switchMode = function (webGL, type) { +WebGLGraphics.switchMode = function (webGL, type) +{ var webGLData; - if (!webGL.data.length) { + if (!webGL.data.length) + { webGLData = WebGLGraphics.graphicsDataPool.pop() || new WebGLGraphicsData(webGL.gl); webGLData.mode = type; webGL.data.push(webGLData); } - else { + else + { webGLData = webGL.data[webGL.data.length-1]; - if (webGLData.mode !== type || type === 1) { + if (webGLData.mode !== type || type === 1) + { webGLData = WebGLGraphics.graphicsDataPool.pop() || new WebGLGraphicsData(webGL.gl); webGLData.mode = type; webGL.data.push(webGLData); @@ -225,7 +254,8 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildRectangle = function (graphicsData, webGLData) { +WebGLGraphics.buildRectangle = function (graphicsData, webGLData) +{ // --- // // need to convert points to a nice regular data // @@ -235,7 +265,8 @@ var width = rectData.width; var height = rectData.height; - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -265,7 +296,8 @@ indices.push(vertPos, vertPos, vertPos+1, vertPos+2, vertPos+3, vertPos+3); } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = [x, y, @@ -289,7 +321,8 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildRoundedRectangle = function (graphicsData, webGLData) { +WebGLGraphics.buildRoundedRectangle = function (graphicsData, webGLData) +{ var rrectData = graphicsData.shape; var x = rrectData.x; var y = rrectData.y; @@ -305,7 +338,8 @@ recPoints = recPoints.concat(WebGLGraphics.quadraticBezierCurve(x + width, y + radius, x + width, y, x + width - radius, y)); recPoints = recPoints.concat(WebGLGraphics.quadraticBezierCurve(x + radius, y, x, y, x, y + radius)); - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -323,7 +357,8 @@ // var i = 0; - for (i = 0; i < triangles.length; i+=3) { + for (i = 0; i < triangles.length; i+=3) + { indices.push(triangles[i] + vecPos); indices.push(triangles[i] + vecPos); indices.push(triangles[i+1] + vecPos); @@ -332,12 +367,14 @@ } - for (i = 0; i < recPoints.length; i++) { + for (i = 0; i < recPoints.length; i++) + { verts.push(recPoints[i], recPoints[++i], r, g, b, alpha); } } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = recPoints; @@ -362,7 +399,8 @@ * @param toY {number} Destination point y * @return {number[]} */ -WebGLGraphics.quadraticBezierCurve = function (fromX, fromY, cpX, cpY, toX, toY) { +WebGLGraphics.quadraticBezierCurve = function (fromX, fromY, cpX, cpY, toX, toY) +{ var xa, ya, @@ -373,14 +411,16 @@ n = 20, points = []; - function getPt(n1 , n2, perc) { + function getPt(n1 , n2, perc) + { var diff = n2 - n1; return n1 + ( diff * perc ); } var j = 0; - for (var i = 0; i <= n; i++ ) { + for (var i = 0; i <= n; i++ ) + { j = i / n; // The Green Line @@ -406,7 +446,8 @@ * @param graphicsData {Graphics} The graphics object to draw * @param webGLData {object} */ -WebGLGraphics.buildCircle = function (graphicsData, webGLData) { +WebGLGraphics.buildCircle = function (graphicsData, webGLData) +{ // need to convert points to a nice regular data var circleData = graphicsData.shape; var x = circleData.x; @@ -415,11 +456,13 @@ var height; // TODO - bit hacky?? - if (graphicsData.type === CONST.SHAPES.CIRC) { + if (graphicsData.type === CONST.SHAPES.CIRC) + { width = circleData.radius; height = circleData.radius; } - else { + else + { width = circleData.width; height = circleData.height; } @@ -429,7 +472,8 @@ var i = 0; - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -444,7 +488,8 @@ indices.push(vecPos); - for (i = 0; i < totalSegs + 1 ; i++) { + for (i = 0; i < totalSegs + 1 ; i++) + { verts.push(x,y, r, g, b, alpha); verts.push(x + Math.sin(seg * i) * width, @@ -457,12 +502,14 @@ indices.push(vecPos-1); } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = []; - for (i = 0; i < totalSegs + 1; i++) { + for (i = 0; i < totalSegs + 1; i++) + { graphicsData.points.push(x + Math.sin(seg * i) * width, y + Math.cos(seg * i) * height); } @@ -481,18 +528,22 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildLine = function (graphicsData, webGLData) { +WebGLGraphics.buildLine = function (graphicsData, webGLData) +{ // TODO OPTIMISE! var i = 0; var points = graphicsData.points; - if (points.length === 0) { + if (points.length === 0) + { return; } // if the line width is an odd number add 0.5 to align to a whole pixel - if (graphicsData.lineWidth%2) { - for (i = 0; i < points.length; i++) { + if (graphicsData.lineWidth%2) + { + for (i = 0; i < points.length; i++) + { points[i] += 0.5; } } @@ -502,7 +553,8 @@ var lastPoint = new math.Point(points[points.length - 2], points[points.length - 1]); // if the first point is the last point - gonna have issues :) - if (firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) { + if (firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) + { // need to clone as we are going to slightly modify the shape.. points = points.slice(); @@ -562,7 +614,8 @@ verts.push(p1x + perpx , p1y + perpy, r, g, b, alpha); - for (i = 1; i < length-1; i++) { + for (i = 1; i < length-1; i++) + { p1x = points[(i-1)*2]; p1y = points[(i-1)*2 + 1]; @@ -599,7 +652,8 @@ denom = a1*b2 - a2*b1; - if (Math.abs(denom) < 0.1 ) { + if (Math.abs(denom) < 0.1 ) + { denom+=10.1; verts.push(p2x - perpx , p2y - perpy, @@ -618,7 +672,8 @@ pdist = (px -p2x) * (px -p2x) + (py -p2y) + (py -p2y); - if (pdist > 140 * 140) { + if (pdist > 140 * 140) + { perp3x = perpx - perp2x; perp3y = perpy - perp2y; @@ -639,7 +694,8 @@ indexCount++; } - else { + else + { verts.push(px , py); verts.push(r, g, b, alpha); @@ -672,7 +728,8 @@ indices.push(indexStart); - for (i = 0; i < indexCount; i++) { + for (i = 0; i < indexCount; i++) + { indices.push(indexStart++); } @@ -687,11 +744,13 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildComplexPoly = function (graphicsData, webGLData) { +WebGLGraphics.buildComplexPoly = function (graphicsData, webGLData) +{ //TODO - no need to copy this as it gets turned into a FLoat32Array anyways.. var points = graphicsData.points.slice(); - if (points.length < 6) { + if (points.length < 6) + { return; } @@ -711,7 +770,8 @@ var x,y; // get size.. - for (var i = 0; i < points.length; i+=2) { + for (var i = 0; i < points.length; i+=2) + { x = points[i]; y = points[i+1]; @@ -732,7 +792,8 @@ //TODO - this aint needed! var length = points.length / 2; - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { indices.push( i ); } @@ -746,10 +807,12 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildPoly = function (graphicsData, webGLData) { +WebGLGraphics.buildPoly = function (graphicsData, webGLData) +{ var points = graphicsData.points; - if (points.length < 6) { + if (points.length < 6) + { return; } // get first and last point.. figure out the middle! @@ -767,7 +830,8 @@ var triangles = utils.PolyK.Triangulate(points); - if (!triangles) { + if (!triangles) + { return false; } @@ -775,7 +839,8 @@ var i = 0; - for (i = 0; i < triangles.length; i+=3) { + for (i = 0; i < triangles.length; i+=3) + { indices.push(triangles[i] + vertPos); indices.push(triangles[i] + vertPos); indices.push(triangles[i+1] + vertPos); @@ -783,7 +848,8 @@ indices.push(triangles[i+2] + vertPos); } - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { verts.push(points[i * 2], points[i * 2 + 1], r, g, b, alpha); } diff --git a/src/core/renderers/webgl/utils/WebGLGraphicsData.js b/src/core/renderers/webgl/utils/WebGLGraphicsData.js index c56d05e..c739ba7 100644 --- a/src/core/renderers/webgl/utils/WebGLGraphicsData.js +++ b/src/core/renderers/webgl/utils/WebGLGraphicsData.js @@ -2,7 +2,8 @@ * @class * @private */ -function WebGLGraphicsData(gl) { +function WebGLGraphicsData(gl) +{ this.gl = gl; //TODO does this need to be split before uploding?? @@ -22,7 +23,8 @@ /** * */ -WebGLGraphicsData.prototype.reset = function () { +WebGLGraphicsData.prototype.reset = function () +{ this.points.length = 0; this.indices.length = 0; }; @@ -30,7 +32,8 @@ /** * */ -WebGLGraphicsData.prototype.upload = function () { +WebGLGraphicsData.prototype.upload = function () +{ var gl = this.gl; // this.lastIndex = graphics.graphicsData.length; diff --git a/src/core/renderers/webgl/utils/WebGLSpriteBatch.js b/src/core/renderers/webgl/utils/WebGLSpriteBatch.js index 96eaa52..55befbb 100644 --- a/src/core/renderers/webgl/utils/WebGLSpriteBatch.js +++ b/src/core/renderers/webgl/utils/WebGLSpriteBatch.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this sprite batch works for. */ -function WebGLSpriteBatch(renderer) { +function WebGLSpriteBatch(renderer) +{ /** * * @@ -88,7 +89,8 @@ */ this.lastIndexCount = 0; - for (var i=0, j=0; i < numIndices; i += 6, j += 4) { + 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; @@ -162,7 +164,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.setupContext(); }); } @@ -173,7 +176,8 @@ /** * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLSpriteBatch.prototype.setupContext = function () { +WebGLSpriteBatch.prototype.setupContext = function () +{ var gl = this.renderer.gl; // setup default shader @@ -198,7 +202,8 @@ /** * */ -WebGLSpriteBatch.prototype.begin = function () { +WebGLSpriteBatch.prototype.begin = function () +{ // this.shader = this.renderer.shaderManager.defaultShader; this.start(); @@ -206,19 +211,22 @@ /** */ -WebGLSpriteBatch.prototype.end = function () { +WebGLSpriteBatch.prototype.end = function () +{ this.flush(); }; /** * @param sprite {Sprite} the sprite to render when using this spritebatch */ -WebGLSpriteBatch.prototype.render = function (sprite) { +WebGLSpriteBatch.prototype.render = function (sprite) +{ var texture = sprite.texture; //TODO set blend modes.. // check texture.. - if (this.currentBatchSize >= this.size) { + if (this.currentBatchSize >= this.size) + { this.flush(); this.currentBaseTexture = texture.baseTexture; } @@ -227,7 +235,8 @@ var uvs = texture._uvs; // if the uvs have not updated then no point rendering just yet! - if (!uvs) { + if (!uvs) + { return; } @@ -237,7 +246,8 @@ var w0, w1, h0, h1; - if (texture.trim) { + 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; @@ -248,7 +258,8 @@ h0 = h1 + texture.crop.height; } - else { + else + { w0 = (texture.frame.width ) * (1-aX); w1 = (texture.frame.width ) * -aX; @@ -272,7 +283,8 @@ var colors = this.colors; var positions = this.positions; - if (this.renderer.roundPixels) { + if (this.renderer.roundPixels) + { // xy positions[index] = a * w1 + c * h1 + tx | 0; positions[index+1] = d * h1 + b * w1 + ty | 0; @@ -289,7 +301,8 @@ positions[index+15] = a * w1 + c * h0 + tx | 0; positions[index+16] = d * h0 + b * w1 + ty | 0; } - else { + else + { // xy positions[index] = a * w1 + c * h1 + tx; positions[index+1] = d * h1 + b * w1 + ty; @@ -338,11 +351,13 @@ * * @param sprite {TilingSprite} the tilingSprite to render */ -WebGLSpriteBatch.prototype.renderTilingSprite = function (tilingSprite) { +WebGLSpriteBatch.prototype.renderTilingSprite = function (tilingSprite) +{ var texture = tilingSprite.tilingTexture; // check texture.. - if (this.currentBatchSize >= this.size) { + if (this.currentBatchSize >= this.size) + { //return; this.flush(); this.currentBaseTexture = texture.baseTexture; @@ -351,7 +366,8 @@ // set the textures uvs temporarily // TODO create a separate texture so that we can tile part of a texture - if (!tilingSprite._uvs) { + if (!tilingSprite._uvs) + { tilingSprite._uvs = new TextureUvs(); } @@ -454,16 +470,19 @@ * Renders the content and empties the current batch. * */ -WebGLSpriteBatch.prototype.flush = function () { +WebGLSpriteBatch.prototype.flush = function () +{ // If the batch is length 0 then return as there is nothing to draw - if (this.currentBatchSize === 0) { + if (this.currentBatchSize === 0) + { return; } var gl = this.renderer.gl; var shader; - if (this.dirty) { + if (this.dirty) + { this.dirty = false; // bind the main texture gl.activeTexture(gl.TEXTURE0); @@ -482,10 +501,12 @@ } // upload the verts to the buffer - if (this.currentBatchSize > ( this.size * 0.5 ) ) { + if (this.currentBatchSize > ( this.size * 0.5 ) ) + { gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); } - else { + else + { var view = this.positions.subarray(0, this.currentBatchSize * this.vertByteSize); gl.bufferSubData(gl.ARRAY_BUFFER, 0, view); } @@ -502,7 +523,8 @@ var shaderSwap = false; var sprite; - for (var i = 0, j = this.currentBatchSize; i < j; i++) { + for (var i = 0, j = this.currentBatchSize; i < j; i++) + { sprite = this.sprites[i]; @@ -513,24 +535,28 @@ blendSwap = currentBlendMode !== nextBlendMode; shaderSwap = currentShader !== nextShader; // should I use uuidS??? - if (currentBaseTexture !== nextTexture || blendSwap || shaderSwap) { + if (currentBaseTexture !== nextTexture || blendSwap || shaderSwap) + { this.renderBatch(currentBaseTexture, batchSize, start); start = i; batchSize = 0; currentBaseTexture = nextTexture; - if (blendSwap) { + if (blendSwap) + { currentBlendMode = nextBlendMode; this.renderer.blendModeManager.setBlendMode( currentBlendMode ); } - if (shaderSwap) { + if (shaderSwap) + { currentShader = nextShader; shader = currentShader.shaders ? currentShader.shaders[gl.id] : currentShader; - if (!shader) { + if (!shader) + { shader = new Shader(gl, null, currentShader.fragmentSrc, currentShader.uniforms); currentShader.shaders[gl.id] = shader; } @@ -538,7 +564,8 @@ // set shader function??? this.renderer.shaderManager.setShader(shader); - if (shader.dirty) { + if (shader.dirty) + { shader.syncUniforms(); } @@ -569,17 +596,21 @@ * @param size {number} * @param startIndex {number} */ -WebGLSpriteBatch.prototype.renderBatch = function (texture, size, startIndex) { - if (size === 0) { +WebGLSpriteBatch.prototype.renderBatch = function (texture, size, startIndex) +{ + if (size === 0) + { return; } var gl = this.renderer.gl; - if (!texture._glTextures[gl.id]) { + if (!texture._glTextures[gl.id]) + { this.renderer.updateTexture(texture); } - else { + else + { // bind the current texture gl.bindTexture(gl.TEXTURE_2D, texture._glTextures[gl.id]); } @@ -594,7 +625,8 @@ /** * */ -WebGLSpriteBatch.prototype.stop = function () { +WebGLSpriteBatch.prototype.stop = function () +{ this.flush(); this.dirty = true; }; @@ -602,7 +634,8 @@ /** * */ -WebGLSpriteBatch.prototype.start = function () { +WebGLSpriteBatch.prototype.start = function () +{ this.dirty = true; }; @@ -610,7 +643,8 @@ * Destroys the SpriteBatch. * */ -WebGLSpriteBatch.prototype.destroy = function () { +WebGLSpriteBatch.prototype.destroy = function () +{ this.renderer.gl.deleteBuffer(this.vertexBuffer); this.renderer.gl.deleteBuffer(this.indexBuffer); diff --git a/src/core/textures/BaseTexture.js b/src/core/textures/BaseTexture.js index 2bf77d4..513d358 100644 --- a/src/core/textures/BaseTexture.js +++ b/src/core/textures/BaseTexture.js @@ -10,7 +10,8 @@ * @param source {Image|Canvas} the source object of the texture. * @param [scaleMode=scaleModes.DEFAULT] {number} See {@link scaleModes} for possible values */ -function BaseTexture(source, scaleMode) { +function BaseTexture(source, scaleMode) +{ this.uuid = utils.uuid(); /** @@ -123,7 +124,8 @@ this._needsUpdate = false; // if no source passed don't try to load - if (source) { + if (source) + { this.loadSource(source); } @@ -149,13 +151,16 @@ Object.defineProperties(BaseTexture.prototype, { needsUpdate: { - get: function () { + get: function () + { return this._needsUpdate; }, - set: function (val) { + set: function (val) + { this._needsUpdate = val; - if (val) { + if (val) + { this.emit('update', this); } } @@ -171,9 +176,11 @@ * * The logic state after calling `loadSource` directly or indirectly (eg. `fromImage`, `new BaseTexture`) is: * - * if (texture.hasLoaded) { + * if (texture.hasLoaded) + { * // texture ready for use - * } else if (texture.isLoading) { + * } else if (texture.isLoading) + { * // listen to 'loaded' and/or 'error' events on texture * } else { * // not loading, not going to load UNLESS the source is reloaded @@ -183,12 +190,14 @@ * @protected * @param source {Image|Canvas} the source object of the texture. */ -BaseTexture.prototype.loadSource = function (source) { +BaseTexture.prototype.loadSource = function (source) +{ var wasLoading = this.isLoading; this.hasLoaded = false; this.isLoading = false; - if (wasLoading && this.source) { + if (wasLoading && this.source) + { this.source.onload = null; this.source.onerror = null; } @@ -196,20 +205,24 @@ this.source = source; // Apply source if loaded. Otherwise setup appropriate loading monitors. - if ((this.source.complete || this.source.getContext) && this.source.width && this.source.height) { + if ((this.source.complete || this.source.getContext) && this.source.width && this.source.height) + { this._sourceLoaded(); } - else if(!source.getContext) { + else if(!source.getContext) + { // Image fail / not ready this.isLoading = true; var scope = this; - source.onload = function () { + source.onload = function () + { source.onload = null; source.onerror = null; - if(!scope.isLoading) { + if(!scope.isLoading) + { return; } @@ -219,11 +232,13 @@ scope.emit('loaded', scope); }; - source.onerror = function () { + source.onerror = function () + { source.onload = null; source.onerror = null; - if(!scope.isLoading) { + if(!scope.isLoading) + { return; } @@ -234,24 +249,29 @@ // Per http://www.w3.org/TR/html5/embedded-content-0.html#the-img-element // "The value of `complete` can thus change while a script is executing." // So complete needs to be re-checked after the callbacks have been added.. - if (source.complete) { + if (source.complete) + { this.isLoading = false; // ..and if we're complete now, no need for callbacks source.onload = null; source.onerror = null; - if (source.width && source.height) { + if (source.width && source.height) + { this._sourceLoaded(); // If any previous subscribers possible - if (wasLoading) { + if (wasLoading) + { this.emit('loaded', this); } } - else { + else + { // If any previous subscribers possible - if (wasLoading) { + if (wasLoading) + { this.emit('error', this); } } @@ -265,7 +285,8 @@ * * @private */ -BaseTexture.prototype._sourceLoaded = function () { +BaseTexture.prototype._sourceLoaded = function () +{ this.hasLoaded = true; this.width = this.source.naturalWidth || this.source.width; @@ -278,16 +299,20 @@ * Destroys this base texture * */ -BaseTexture.prototype.destroy = function () { - if (this.imageUrl) { +BaseTexture.prototype.destroy = function () +{ + if (this.imageUrl) + { delete utils.BaseTextureCache[this.imageUrl]; delete utils.TextureCache[this.imageUrl]; this.imageUrl = null; - if (!navigator.isCocoonJS) { + if (!navigator.isCocoonJS) + { this.source.src = ''; } } - else if (this.source && this.source._pixiId) { + else if (this.source && this.source._pixiId) + { delete utils.BaseTextureCache[this.source._pixiId]; } this.source = null; @@ -301,7 +326,8 @@ * memory again. * */ -BaseTexture.prototype.dispose = function () { +BaseTexture.prototype.dispose = function () +{ this.emit('dispose', this); }; @@ -311,7 +337,8 @@ * * @param newSrc {string} the path of the image */ -BaseTexture.prototype.updateSourceImage = function (newSrc) { +BaseTexture.prototype.updateSourceImage = function (newSrc) +{ this.source.src = newSrc; this.loadSource(this.source); }; @@ -326,18 +353,22 @@ * @param [scaleMode=scaleModes.DEFAULT] {number} See {@link scaleModes} for possible values * @return BaseTexture */ -BaseTexture.fromImage = function (imageUrl, crossorigin, scaleMode) { +BaseTexture.fromImage = function (imageUrl, crossorigin, scaleMode) +{ var baseTexture = utils.BaseTextureCache[imageUrl]; - if (crossorigin === undefined && imageUrl.indexOf('data:') !== 0) { + if (crossorigin === undefined && imageUrl.indexOf('data:') !== 0) + { crossorigin = true; } - if (!baseTexture) { + if (!baseTexture) + { // new Image() breaks tex loading in some versions of Chrome. // See https://code.google.com/p/chromium/issues/detail?id=238071 var image = new Image();//document.createElement('img'); - if (crossorigin) { + if (crossorigin) + { image.crossOrigin = ''; } @@ -347,7 +378,8 @@ utils.BaseTextureCache[imageUrl] = baseTexture; // if there is an @2x at the end of the url we are going to assume its a highres image - if ( imageUrl.indexOf(CONST.RETINA_PREFIX + '.') !== -1) { + if ( imageUrl.indexOf(CONST.RETINA_PREFIX + '.') !== -1) + { baseTexture.resolution = 2; } } @@ -363,14 +395,17 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return BaseTexture */ -BaseTexture.fromCanvas = function (canvas, scaleMode) { - if (!canvas._pixiId) { +BaseTexture.fromCanvas = function (canvas, scaleMode) +{ + if (!canvas._pixiId) + { canvas._pixiId = 'canvas_' + utils.uuid(); } var baseTexture = utils.BaseTextureCache[canvas._pixiId]; - if (!baseTexture) { + if (!baseTexture) + { baseTexture = new BaseTexture(canvas, scaleMode); utils.BaseTextureCache[canvas._pixiId] = baseTexture; } diff --git a/src/core/textures/RenderTexture.js b/src/core/textures/RenderTexture.js index 6dad20f..53ae796 100644 --- a/src/core/textures/RenderTexture.js +++ b/src/core/textures/RenderTexture.js @@ -46,8 +46,10 @@ * @param [scaleMode] {number} See {@link scaleModes} for possible values * @param [resolution=1] {number} The resolution of the texture being generated */ -function RenderTexture(renderer, width, height, scaleMode, resolution) { - if (!renderer) { +function RenderTexture(renderer, width, height, scaleMode, resolution) +{ + if (!renderer) + { throw new Error('Unable to create RenderTexture, you must pass a renderer into the constructor.'); } @@ -133,7 +135,8 @@ */ this.renderer = renderer; - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { var gl = this.renderer.gl; this.textureBuffer = new FilterTexture(gl, this.width * this.resolution, this.height * this.resolution, this.baseTexture.scaleMode); @@ -142,7 +145,8 @@ this.render = this.renderWebGL; this.projection = new math.Point(this.width*0.5, -this.height*0.5); } - else { + else + { this.render = this.renderCanvas; this.textureBuffer = new CanvasBuffer(this.width* this.resolution, this.height* this.resolution); this.baseTexture.source = this.textureBuffer.canvas; @@ -167,8 +171,10 @@ * @param height {number} The height to resize to. * @param updateBase {boolean} Should the baseTexture.width and height values be resized as well? */ -RenderTexture.prototype.resize = function (width, height, updateBase) { - if (width === this.width && height === this.height) { +RenderTexture.prototype.resize = function (width, height, updateBase) +{ + if (width === this.width && height === this.height) + { return; } @@ -177,17 +183,20 @@ this.width = this.frame.width = this.crop.width = width; this.height = this.frame.height = this.crop.height = height; - if (updateBase) { + if (updateBase) + { this.baseTexture.width = this.width; this.baseTexture.height = this.height; } - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { this.projection.x = this.width / 2; this.projection.y = -this.height / 2; } - if (!this.valid) { + if (!this.valid) + { return; } @@ -198,12 +207,15 @@ * Clears the RenderTexture. * */ -RenderTexture.prototype.clear = function () { - if (!this.valid) { +RenderTexture.prototype.clear = function () +{ + if (!this.valid) + { return; } - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { this.renderer.gl.bindFramebuffer(this.renderer.gl.FRAMEBUFFER, this.textureBuffer.frameBuffer); } @@ -220,19 +232,23 @@ * @param [restoreWorldTransform=true] {boolean} If true the displayObject's worldTransform/worldAlpha and all children * transformations will be restored. Not restoring this information will be a little faster. */ -RenderTexture.prototype.renderWebGL = function (displayObject, matrix, clear, restoreWorldTransform) { - if (!this.valid) { +RenderTexture.prototype.renderWebGL = function (displayObject, matrix, clear, restoreWorldTransform) +{ + if (!this.valid) + { return; } - if (typeof restoreWorldTransform === 'undefined') { + if (typeof restoreWorldTransform === 'undefined') + { restoreWorldTransform = true; } var tempAlpha, tempTransform; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { tempAlpha = displayObject.worldAlpha; tempTransform = displayObject.worldTransform.toArray(); } @@ -245,7 +261,8 @@ wt.identity(); wt.translate(0, this.projection.y * 2); - if (matrix) { + if (matrix) + { wt.append(matrix); } @@ -258,7 +275,8 @@ var children = displayObject.children; var i, j; - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } @@ -269,7 +287,8 @@ gl.bindFramebuffer(gl.FRAMEBUFFER, this.textureBuffer.frameBuffer ); - if (clear) { + if (clear) + { this.textureBuffer.clear(); } @@ -279,11 +298,13 @@ this.renderer.spriteBatch.dirty = true; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { displayObject.worldAlpha = tempAlpha; displayObject.worldTransform.fromArray(tempTransform); - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } } @@ -300,26 +321,31 @@ * @param [restoreWorldTransform=true] {boolean} If true the displayObject's worldTransform/worldAlpha and all children * transformations will be restored. Not restoring this information will be a little faster. */ -RenderTexture.prototype.renderCanvas = function (displayObject, matrix, clear, restoreWorldTransform) { - if (!this.valid) { +RenderTexture.prototype.renderCanvas = function (displayObject, matrix, clear, restoreWorldTransform) +{ + if (!this.valid) + { return; } - if (typeof restoreWorldTransform === 'undefined') { + if (typeof restoreWorldTransform === 'undefined') + { restoreWorldTransform = true; } var tempAlpha, tempTransform; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { tempAlpha = displayObject.worldAlpha; tempTransform = displayObject.worldTransform.toArray(); } var wt = displayObject.worldTransform; wt.identity(); - if (matrix) { + if (matrix) + { wt.append(matrix); } @@ -330,11 +356,13 @@ var children = displayObject.children; var i, j; - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } - if (clear) { + if (clear) + { this.textureBuffer.clear(); } @@ -348,11 +376,13 @@ this.renderer.resolution = realResolution; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { displayObject.worldAlpha = tempAlpha; displayObject.worldTransform.fromArray(tempTransform); - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } } @@ -363,7 +393,8 @@ * * @return {Image} */ -RenderTexture.prototype.getImage = function () { +RenderTexture.prototype.getImage = function () +{ var image = new Image(); image.src = this.getBase64(); return image; @@ -374,7 +405,8 @@ * * @return {string} A base64 encoded string of the texture. */ -RenderTexture.prototype.getBase64 = function () { +RenderTexture.prototype.getBase64 = function () +{ return this.getCanvas().toDataURL(); }; @@ -383,8 +415,10 @@ * * @return {HTMLCanvasElement} A Canvas element with the texture rendered on. */ -RenderTexture.prototype.getCanvas = function () { - if (this.renderer.type === CONST.WEBGL_RENDERER) { +RenderTexture.prototype.getCanvas = function () +{ + if (this.renderer.type === CONST.WEBGL_RENDERER) + { var gl = this.renderer.gl; var width = this.textureBuffer.width; var height = this.textureBuffer.height; @@ -403,7 +437,8 @@ return tempCanvas.canvas; } - else { + else + { return this.textureBuffer.canvas; } }; diff --git a/src/core/textures/Texture.js b/src/core/textures/Texture.js index 3c65909..e97f0aa 100644 --- a/src/core/textures/Texture.js +++ b/src/core/textures/Texture.js @@ -17,7 +17,8 @@ * @param [crop] {Rectangle} The area of original texture * @param [trim] {Rectangle} Trimmed texture rectangle */ -function Texture(baseTexture, frame, crop, trim) { +function Texture(baseTexture, frame, crop, trim) +{ /** * Does this Texture have any frame data assigned to it? * @@ -25,12 +26,14 @@ */ this.noFrame = false; - if (!frame) { + if (!frame) + { this.noFrame = true; frame = new math.Rectangle(0, 0, 1, 1); } - if (baseTexture instanceof Texture) { + if (baseTexture instanceof Texture) + { baseTexture = baseTexture.baseTexture; } @@ -100,13 +103,16 @@ */ this.crop = crop || new math.Rectangle(0, 0, 1, 1); - if (baseTexture.hasLoaded) { - if (this.noFrame) { + if (baseTexture.hasLoaded) + { + if (this.noFrame) + { frame = new math.Rectangle(0, 0, baseTexture.width, baseTexture.height); } this.frame = frame; } - else { + else + { baseTexture.addEventListener('loaded', this.onBaseTextureLoaded.bind(this)); } } @@ -118,19 +124,23 @@ Object.defineProperties(Texture.prototype, { needsUpdate: { - get: function () { + get: function () + { return this.baseTexture.needsUpdate; }, - set: function (val) { + set: function (val) + { this.baseTexture.needsUpdate = val; } }, frame: { - get: function () { + get: function () + { return this._frame; }, - set: function (frame) { + set: function (frame) + { this._frame = frame; this.noFrame = false; @@ -143,20 +153,23 @@ 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 (!this.trim && (frame.x + frame.width > this.baseTexture.width || frame.y + frame.height > this.baseTexture.height)) + { throw new Error('Texture Error: frame does not fit inside the base Texture dimensions ' + this); } this.valid = frame && frame.width && frame.height && this.baseTexture.source && this.baseTexture.hasLoaded; - if (this.trim) { + 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) { + if (this.valid) + { this._updateUvs(); } } @@ -168,11 +181,13 @@ * * @private */ -Texture.prototype.onBaseTextureLoaded = function () { +Texture.prototype.onBaseTextureLoaded = function () +{ var baseTexture = this.baseTexture; baseTexture.removeEventListener('loaded', this.onLoaded); - if (this.noFrame) { + if (this.noFrame) + { this.frame = new math.Rectangle(0, 0, baseTexture.width, baseTexture.height); } @@ -184,8 +199,10 @@ * * @param destroyBase {boolean} Whether to destroy the base texture as well */ -Texture.prototype.destroy = function (destroyBase) { - if (destroyBase) { +Texture.prototype.destroy = function (destroyBase) +{ + if (destroyBase) + { this.baseTexture.destroy(); } @@ -197,8 +214,10 @@ * * @private */ -Texture.prototype._updateUvs = function () { - if (!this._uvs) { +Texture.prototype._updateUvs = function () +{ + if (!this._uvs) + { this._uvs = new TextureUvs(); } @@ -229,10 +248,12 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return Texture */ -Texture.fromImage = function (imageUrl, crossorigin, scaleMode) { +Texture.fromImage = function (imageUrl, crossorigin, scaleMode) +{ var texture = utils.TextureCache[imageUrl]; - if (!texture) { + if (!texture) + { texture = new Texture(BaseTexture.fromImage(imageUrl, crossorigin, scaleMode)); utils.TextureCache[imageUrl] = texture; } @@ -248,9 +269,11 @@ * @param frameId {string} The frame id of the texture * @return Texture */ -Texture.fromFrame = function (frameId) { +Texture.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache '); } return texture; @@ -264,7 +287,8 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return {Texture} */ -Texture.fromCanvas = function (canvas, scaleMode) { +Texture.fromCanvas = function (canvas, scaleMode) +{ return new Texture(BaseTexture.fromCanvas(canvas, scaleMode)); }; @@ -276,7 +300,8 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return {Texture} A Texture */ -Texture.fromVideo = function (video, scaleMode) { +Texture.fromVideo = function (video, scaleMode) +{ return new Texture(VideoBaseTexture.baseTextureFromVideo(video, scaleMode)); }; @@ -287,7 +312,8 @@ * @param texture {Texture} The Texture to add to the cache. * @param id {string} The id that the texture will be stored against. */ -Texture.addTextureToCache = function (texture, id) { +Texture.addTextureToCache = function (texture, id) +{ utils.TextureCache[id] = texture; }; @@ -298,7 +324,8 @@ * @param id {string} The id of the texture to be removed * @return {Texture} The texture that was removed */ -Texture.removeTextureFromCache = function (id) { +Texture.removeTextureFromCache = function (id) +{ var texture = utils.TextureCache[id]; delete utils.TextureCache[id]; diff --git a/src/core/textures/TextureUvs.js b/src/core/textures/TextureUvs.js index b9bbb58..5424d52 100644 --- a/src/core/textures/TextureUvs.js +++ b/src/core/textures/TextureUvs.js @@ -1,4 +1,5 @@ -function TextureUvs() { +function TextureUvs() +{ this.x0 = 0; this.y0 = 0; diff --git a/src/core/textures/VideoBaseTexture.js b/src/core/textures/VideoBaseTexture.js index e3e0c5a..1a826a9 100644 --- a/src/core/textures/VideoBaseTexture.js +++ b/src/core/textures/VideoBaseTexture.js @@ -12,15 +12,18 @@ * @param source {HTMLVideoElement} * @param [scaleMode] {number} See {@link scaleModes} for possible values */ -function VideoBaseTexture(source, scaleMode) { - if (!source){ +function VideoBaseTexture(source, scaleMode) +{ + if (!source) + { throw new Error('No video source element specified.'); } // hook in here to check if video is already available. // BaseTexture looks for a source.complete boolean, plus width & height. - if ((source.readyState === source.HAVE_ENOUGH_DATA || source.readyState === source.HAVE_FUTURE_DATA) && source.width && source.height) { + if ((source.readyState === source.HAVE_ENOUGH_DATA || source.readyState === source.HAVE_FUTURE_DATA) && source.width && source.height) + { source.complete = true; } @@ -31,7 +34,8 @@ this._boundOnUpdate = this._onUpdate.bind(this); this._boundOnCanPlay = this._onCanPlay.bind(this); - if (!source.complete) { + if (!source.complete) + { source.addEventListener('canplay', this._boundOnCanPlay); source.addEventListener('canplaythrough', this._boundOnCanPlay); @@ -47,28 +51,35 @@ VideoBaseTexture.prototype.constructor = VideoBaseTexture; module.exports = VideoBaseTexture; -VideoBaseTexture.prototype._onUpdate = function () { - if (this.autoUpdate) { +VideoBaseTexture.prototype._onUpdate = function () +{ + if (this.autoUpdate) + { window.requestAnimationFrame(this._boundOnUpdate); this.needsUpdate = true; } }; -VideoBaseTexture.prototype._onPlayStart = function () { - if (!this.autoUpdate) { +VideoBaseTexture.prototype._onPlayStart = function () +{ + if (!this.autoUpdate) + { window.requestAnimationFrame(this._boundOnUpdate); this.autoUpdate = true; } }; -VideoBaseTexture.prototype._onPlayStop = function () { +VideoBaseTexture.prototype._onPlayStop = function () +{ this.autoUpdate = false; }; -VideoBaseTexture.prototype._onCanPlay = function () { +VideoBaseTexture.prototype._onCanPlay = function () +{ this.hasLoaded = true; - if (this.source) { + if (this.source) + { this.source.removeEventListener('canplay', this._boundOnCanPlay); this.source.removeEventListener('canplaythrough', this._boundOnCanPlay); @@ -78,15 +89,18 @@ this.source.play(); // prevent multiple loaded dispatches.. - if(!this.__loaded){ + if(!this.__loaded) + { this.__loaded = true; this.emit('loaded', this); } } }; -VideoBaseTexture.prototype.destroy = function () { - if (this.source && this.source._pixiId) { +VideoBaseTexture.prototype.destroy = function () +{ + if (this.source && this.source._pixiId) + { utils.BaseTextureCache[ this.source._pixiId ] = null; delete utils.BaseTextureCache[ this.source._pixiId ]; @@ -105,14 +119,17 @@ * @param scaleMode {number} See {@link scaleModes} for possible values * @return {VideoBaseTexture} */ -VideoBaseTexture.fromVideo = function (video, scaleMode) { - if (!video._pixiId) { +VideoBaseTexture.fromVideo = function (video, scaleMode) +{ + if (!video._pixiId) + { video._pixiId = 'video_' + utils.uuid(); } var baseTexture = utils.BaseTextureCache[video._pixiId]; - if (!baseTexture) { + if (!baseTexture) + { baseTexture = new VideoBaseTexture(video, scaleMode); utils.BaseTextureCache[ video._pixiId ] = baseTexture; } @@ -147,17 +164,21 @@ * @param scaleMode {number} See {@link scaleModes} for possible values * @return {VideoBaseTexture} */ -VideoBaseTexture.fromUrl = function (videoSrc, scaleMode) { +VideoBaseTexture.fromUrl = function (videoSrc, scaleMode) +{ var video = document.createElement('video'); // array of objects or strings - if (Array.isArray(videoSrc)) { - for (var i = 0; i < videoSrc.length; ++i) { + if (Array.isArray(videoSrc)) + { + for (var i = 0; i < videoSrc.length; ++i) + { video.appendChild(createSource(videoSrc.src || videoSrc, videoSrc.mime)); } } // single object or string - else { + else + { video.appendChild(createSource(videoSrc.src || videoSrc, videoSrc.mime)); } @@ -169,8 +190,10 @@ VideoBaseTexture.fromUrls = VideoBaseTexture.fromUrl; -function createSource(path, type) { - if (!type) { +function createSource(path, type) +{ + if (!type) + { type = 'video/' + path.substr(path.lastIndexOf('.') + 1); } diff --git a/src/core/utils/EventData.js b/src/core/utils/EventData.js index 5d55a22..8cdf701 100644 --- a/src/core/utils/EventData.js +++ b/src/core/utils/EventData.js @@ -7,7 +7,8 @@ * @param name {string} The string name of the event that was triggered * @param data {object} Arbitrary event data to pass along */ -function EventData(target, name, data) { +function EventData(target, name, data) +{ // for duck typing in the ".on()" function this.__isEventObject = true; @@ -71,7 +72,8 @@ * Stops the propagation of events up the scene graph (prevents bubbling). * */ -EventData.prototype.stopPropagation = function stopPropagation() { +EventData.prototype.stopPropagation = function stopPropagation() +{ this.stopped = true; }; @@ -79,6 +81,7 @@ * Stops the propagation of events to sibling listeners (no longer calls any listeners). * */ -EventData.prototype.stopImmediatePropagation = function stopImmediatePropagation() { +EventData.prototype.stopImmediatePropagation = function stopImmediatePropagation() +{ this.stoppedImmediate = true; }; diff --git a/src/core/utils/EventTarget.js b/src/core/utils/EventTarget.js index 7ae8820..671a151 100644 --- a/src/core/utils/EventTarget.js +++ b/src/core/utils/EventTarget.js @@ -13,14 +13,16 @@ * var em = new MyEmitter(); * em.emit('eventName', 'some data', 'some more data', {}, null, ...); */ -function eventTarget(obj) { +function eventTarget(obj) +{ /** * Return a list of assigned event listeners. * * @param eventName {string} The events that should be listed. * @return {Array} An array of listener functions */ - obj.listeners = function listeners(eventName) { + obj.listeners = function listeners(eventName) + { this._listeners = this._listeners || {}; return this._listeners[eventName] ? this._listeners[eventName].slice() : []; @@ -33,22 +35,26 @@ * @param eventName {string} The name of the event. * @return {boolean} Indication if we've emitted an event. */ - obj.emit = obj.dispatchEvent = function emit(eventName, data) { + obj.emit = obj.dispatchEvent = function emit(eventName, data) + { this._listeners = this._listeners || {}; // fast return when there are no listeners - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return; } //backwards compat with old method ".emit({ type: 'something' })" - if (typeof eventName === 'object') { + if (typeof eventName === 'object') + { data = eventName; eventName = eventName.type; } //ensure we are using a real pixi event - if (!data || data.__isEventObject !== true) { + if (!data || data.__isEventObject !== true) + { data = new EventData(this, eventName, data); } @@ -58,23 +64,27 @@ fn = listeners[0], i; - for (i = 0; i < length; fn = listeners[++i]) { + for (i = 0; i < length; fn = listeners[++i]) + { //call the event listener fn.call(this, data); //if "stopImmediatePropagation" is called, stop calling sibling events - if (data.stoppedImmediate) { + if (data.stoppedImmediate) + { return this; } } //if "stopPropagation" is called then don't bubble the event - if (data.stopped) { + if (data.stopped) + { return this; } //bubble this event up the scene graph - if (this.parent && this.parent.emit) { + if (this.parent && this.parent.emit) + { this.parent.emit.call(this.parent, eventName, data); } @@ -88,7 +98,8 @@ * @param eventName {string} Name of the event. * @param callback {Functon} fn Callback function. */ - obj.on = obj.addEventListener = function on(eventName, fn) { + obj.on = obj.addEventListener = function on(eventName, fn) + { this._listeners = this._listeners || {}; (this._listeners[eventName] = this._listeners[eventName] || []) @@ -103,11 +114,13 @@ * @param eventName {string} Name of the event. * @param callback {Function} Callback function. */ - obj.once = function once(eventName, fn) { + obj.once = function once(eventName, fn) + { this._listeners = this._listeners || {}; var self = this; - function onceHandlerWrapper() { + function onceHandlerWrapper() + { fn.apply(self.off(eventName, onceHandlerWrapper), arguments); } onceHandlerWrapper._originalHandler = fn; @@ -122,23 +135,28 @@ * @param eventName {string} The event we want to remove. * @param callback {Function} The listener that we need to find. */ - obj.off = obj.removeEventListener = function off(eventName, fn) { + obj.off = obj.removeEventListener = function off(eventName, fn) + { this._listeners = this._listeners || {}; - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return this; } var list = this._listeners[eventName], i = fn ? list.length : 0; - while(i-- > 0) { - if (list[i] === fn || list[i]._originalHandler === fn) { + while(i-- > 0) + { + if (list[i] === fn || list[i]._originalHandler === fn) + { list.splice(i, 1); } } - if (list.length === 0) { + if (list.length === 0) + { delete this._listeners[eventName]; } @@ -150,10 +168,12 @@ * * @param eventName {string} The event you want to remove all listeners for. */ - obj.removeAllListeners = function removeAllListeners(eventName) { + obj.removeAllListeners = function removeAllListeners(eventName) + { this._listeners = this._listeners || {}; - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return this; } @@ -169,7 +189,8 @@ * * @param object {object} The obj to mix into */ - mixin: function mixin(obj) { + mixin: function mixin(obj) + { eventTarget(obj); } }; diff --git a/src/core/utils/PolyK.js b/src/core/utils/PolyK.js index 7325141..5e20c2b 100644 --- a/src/core/utils/PolyK.js +++ b/src/core/utils/PolyK.js @@ -47,7 +47,8 @@ * Triangulates shapes for webGL graphic fills. * */ -PolyK.Triangulate = function (p) { +PolyK.Triangulate = function (p) +{ var sign = true; var n = p.length >> 1; @@ -59,7 +60,8 @@ i = 0; var al = n; - while(al > 3) { + while(al > 3) + { var i0 = avl[(i+0)%al]; var i1 = avl[(i+1)%al]; var i2 = avl[(i+2)%al]; @@ -69,29 +71,35 @@ var cx = p[2*i2], cy = p[2*i2+1]; var earFound = false; - if (PolyK._convex(ax, ay, bx, by, cx, cy, sign)) { + if (PolyK._convex(ax, ay, bx, by, cx, cy, sign)) + { earFound = true; - for (var j = 0; j < al; j++) { + for (var j = 0; j < al; j++) + { var vi = avl[j]; if (vi === i0 || vi === i1 || vi === i2) continue; - if (PolyK._PointInTriangle(p[2*vi], p[2*vi+1], ax, ay, bx, by, cx, cy)) { + if (PolyK._PointInTriangle(p[2*vi], p[2*vi+1], ax, ay, bx, by, cx, cy)) + { earFound = false; break; } } } - if (earFound) { + if (earFound) + { tgs.push(i0, i1, i2); avl.splice((i+1)%al, 1); al--; i = 0; } - else if (i++ > 3*al) { + else if (i++ > 3*al) + { // need to flip flip reverse it! // reset! - if (sign) { + if (sign) + { tgs = []; avl = []; for (i = 0; i < n; i++) avl.push(i); @@ -101,7 +109,8 @@ sign = false; } - else { + else + { // window.console.log("PIXI Warning: shape too complex to fill"); return null; } @@ -126,7 +135,8 @@ * @private * @return {boolean} */ -PolyK._PointInTriangle = function (px, py, ax, ay, bx, by, cx, cy) { +PolyK._PointInTriangle = function (px, py, ax, ay, bx, by, cx, cy) +{ var v0x = cx-ax; var v0y = cy-ay; var v1x = bx-ax; @@ -154,6 +164,7 @@ * @private * @return {boolean} */ -PolyK._convex = function (ax, ay, bx, by, cx, cy, sign) { +PolyK._convex = function (ax, ay, bx, by, cx, cy, sign) +{ return ((ay-by)*(cx-bx) + (bx-ax)*(cy-by) >= 0) === sign; }; diff --git a/src/core/utils/index.js b/src/core/utils/index.js index ade9831..bfae7ae 100644 --- a/src/core/utils/index.js +++ b/src/core/utils/index.js @@ -16,7 +16,8 @@ * * @return {number} The next uuid to use. */ - uuid: function () { + uuid: function () + { return ++utils._uid; }, @@ -26,7 +27,8 @@ * @param hex {number} * @return {number[]} An array representing the [R, G, B] of the color. */ - hex2rgb: function (hex, out) { + hex2rgb: function (hex, out) + { out = out || []; out[0] = (hex >> 16 & 0xFF) / 255; @@ -42,7 +44,8 @@ * @param hex {number} * @return {string} The string color. */ - hex2string: function (hex) { + hex2string: function (hex) + { hex = hex.toString(16); hex = '000000'.substr(0, 6 - hex.length) + hex; @@ -55,7 +58,8 @@ * @param rgb {number[]} * @return {number} The color number */ - rgb2hex: function (rgb) { + rgb2hex: function (rgb) + { return ((rgb[0]*255 << 16) + (rgb[1]*255 << 8) + rgb[2]*255); }, @@ -64,8 +68,10 @@ * * @return {boolean} whether they are supported */ - canUseNewCanvasBlendModes: function () { - if (typeof document === 'undefined') { + canUseNewCanvasBlendModes: function () + { + if (typeof document === 'undefined') + { return false; } @@ -93,15 +99,19 @@ * @param number {number} * @return {number} the closest number that is a power of two */ - getNextPowerOfTwo: function (number) { + getNextPowerOfTwo: function (number) + { // see: http://en.wikipedia.org/wiki/Power_of_two#Fast_algorithm_to_check_if_a_positive_number_is_a_power_of_two - if (number > 0 && (number & (number - 1)) === 0) { + if (number > 0 && (number & (number - 1)) === 0) + { return number; } - else { + else + { var result = 1; - while (result < number) { + while (result < number) + { result <<= 1; } @@ -116,7 +126,8 @@ * @param height {number} * @return {boolean} */ - isPowerOfTwo: function (width, height) { + isPowerOfTwo: function (width, height) + { return (width > 0 && (width & (width - 1)) === 0 && height > 0 && (height & (height - 1)) === 0); }, @@ -130,12 +141,15 @@ * @constant * @static */ - sayHello: function (type) { - if (utils._saidHello) { + sayHello: function (type) + { + if (utils._saidHello) + { return; } - if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) { + if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) + { var args = [ '%c %c %c Pixi.js ' + CONST.VERSION + ' - ' + type + ' %c ' + ' %c ' + ' http://www.pixijs.com/ %c %c ♥%c♥%c♥ ', 'background: #ff66a5', @@ -151,7 +165,8 @@ console.log.apply(console, args); //jshint ignore:line } - else if (window.console) { + else if (window.console) + { console.log('Pixi.js ' + CONST.VERSION + ' - ' + type + ' - http://www.pixijs.com/'); //jshint ignore:line } @@ -166,15 +181,19 @@ * @class * @namespace PIXI */ - AjaxRequest: function () { + AjaxRequest: function () + { var activexmodes = ['Msxml2.XMLHTTP.6.0', 'Msxml2.XMLHTTP.3.0', 'Microsoft.XMLHTTP']; //activeX versions to check for in IE - if (window.ActiveXObject) { //Test for support for ActiveXObject in IE first (as XMLHttpRequest in IE7 is broken) - for (var i=0; i= this.textures.length) { + else if (round >= this.textures.length) + { this.gotoAndStop(this.textures.length - 1); - if (this.onComplete) { + if (this.onComplete) + { this.onComplete(); } } @@ -167,10 +182,12 @@ * @static * @param frames {string[]} the array of frames ids the movieclip will use as its texture frames */ -MovieClip.fromFrames = function (frames) { +MovieClip.fromFrames = function (frames) +{ var textures = []; - for (var i = 0; i < frames.length; ++i) { + for (var i = 0; i < frames.length; ++i) + { textures.push(new core.Texture.fromFrame(frames[i])); } @@ -183,10 +200,12 @@ * @static * @param images {string[]} the array of image urls the movieclip will use as its texture frames */ -MovieClip.fromImages = function (images) { +MovieClip.fromImages = function (images) +{ var textures = []; - for (var i = 0; i < images.length; ++i) { + for (var i = 0; i < images.length; ++i) + { textures.push(new core.Texture.fromImage(images[i])); } diff --git a/src/extras/Rope.js b/src/extras/Rope.js index c157ec4..9c87bc0 100644 --- a/src/extras/Rope.js +++ b/src/extras/Rope.js @@ -9,7 +9,8 @@ * @param {Array} points - An array of {Point}. * */ -function Rope(texture, points) { +function Rope(texture, points) +{ Strip.call(this, texture); this.points = points; @@ -31,10 +32,12 @@ * Refreshes * */ -Rope.prototype.refresh = function () { +Rope.prototype.refresh = function () +{ var points = this.points; - if (points.length < 1) { + if (points.length < 1) + { return; } @@ -59,20 +62,23 @@ var total = points.length, point, index, amount; - for (var i = 1; i < total; i++) { + for (var i = 1; i < total; i++) + { point = points[i]; index = i * 4; // time to do some smart drawing! amount = i / (total-1); - if (i%2) { + if (i%2) + { uvs[index] = amount; uvs[index+1] = 0; uvs[index+2] = amount; uvs[index+3] = 1; } - else { + else + { uvs[index] = amount; uvs[index+1] = 0; @@ -95,10 +101,12 @@ * * @private */ -Rope.prototype.updateTransform = function () { +Rope.prototype.updateTransform = function () +{ var points = this.points; - if (points.length < 1) { + if (points.length < 1) + { return; } @@ -113,14 +121,17 @@ var total = points.length, point, index, ratio, perpLength, num; - for (var i = 0; i < total; i++) { + for (var i = 0; i < total; i++) + { point = points[i]; index = i * 4; - if (i < points.length-1) { + if (i < points.length-1) + { nextPoint = points[i+1]; } - else { + else + { nextPoint = point; } @@ -129,7 +140,8 @@ ratio = (1 - (i / (total-1))) * 10; - if (ratio > 1) { + if (ratio > 1) + { ratio = 1; } @@ -157,7 +169,8 @@ * * @param texture {Texture} the texture that will be used */ -Rope.prototype.setTexture = function (texture) { +Rope.prototype.setTexture = function (texture) +{ // stop current texture this.texture = texture; //this.updateFrame = true; diff --git a/src/extras/Strip.js b/src/extras/Strip.js index c5e378f..57691b5 100644 --- a/src/extras/Strip.js +++ b/src/extras/Strip.js @@ -10,7 +10,8 @@ * @param height {number} the height * */ -function Strip(texture) { +function Strip(texture) +{ core.DisplayObjectContainer.call(this); /** @@ -70,9 +71,11 @@ * * @param renderer {WebGLRenderer} */ -Strip.prototype.renderWebGL = function (renderer) { +Strip.prototype.renderWebGL = function (renderer) +{ // if the sprite is not visible or the alpha is 0 then no need to render this element - if (!this.visible || this.alpha <= 0) { + if (!this.visible || this.alpha <= 0) + { return; } @@ -81,7 +84,8 @@ renderer.spriteBatch.stop(); // init! init! - if (!this._vertexBuffer) { + if (!this._vertexBuffer) + { this._initWebGL(renderer); } @@ -96,7 +100,8 @@ //TODO check culling }; -Strip.prototype._initWebGL = function (renderer) { +Strip.prototype._initWebGL = function (renderer) +{ // build the strip! var gl = renderer.gl; @@ -118,7 +123,8 @@ gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this.indices, gl.STATIC_DRAW); }; -Strip.prototype._renderStrip = function (renderer) { +Strip.prototype._renderStrip = function (renderer) +{ var gl = renderer.gl; var projection = renderer.projection, offset = renderer.offset, @@ -137,7 +143,8 @@ gl.uniform2f(shader.offsetVector, -offset.x, -offset.y); gl.uniform1f(shader.alpha, this.worldAlpha); - if (!this.dirty) { + if (!this.dirty) + { gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexBuffer); gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); @@ -150,10 +157,12 @@ gl.activeTexture(gl.TEXTURE0); // check if a texture is dirty.. - if (this.texture.baseTexture._dirty[gl.id]) { + if (this.texture.baseTexture._dirty[gl.id]) + { renderer.updateTexture(this.texture.baseTexture); } - else { + else + { // bind the current texture gl.bindTexture(gl.TEXTURE_2D, this.texture.baseTexture._glTextures[gl.id]); } @@ -163,7 +172,8 @@ } - else { + else + { this.dirty = false; gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexBuffer); @@ -178,10 +188,12 @@ gl.activeTexture(gl.TEXTURE0); // check if a texture is dirty.. - if (this.texture.baseTexture._dirty[gl.id]) { + if (this.texture.baseTexture._dirty[gl.id]) + { renderer.updateTexture(this.texture.baseTexture); } - else { + else + { gl.bindTexture(gl.TEXTURE_2D, this.texture.baseTexture._glTextures[gl.id]); } @@ -203,27 +215,33 @@ * * @param renderer {CanvasRenderer} */ -Strip.prototype.renderCanvas = function (renderer) { +Strip.prototype.renderCanvas = function (renderer) +{ var context = renderer.context; var transform = this.worldTransform; - if (renderer.roundPixels) { + if (renderer.roundPixels) + { context.setTransform(transform.a, transform.b, transform.c, transform.d, transform.tx | 0, transform.ty | 0); } - else { + else + { context.setTransform(transform.a, transform.b, transform.c, transform.d, transform.tx, transform.ty); } - if (this.drawMode === Strip.DrawModes.TRIANGLE_STRIP) { + if (this.drawMode === Strip.DrawModes.TRIANGLE_STRIP) + { this._renderCanvasTriangleStrip(context); } - else { + else + { this._renderCanvasTriangles(context); } }; -Strip.prototype._renderCanvasTriangleStrip = function (context) { +Strip.prototype._renderCanvasTriangleStrip = function (context) +{ // draw triangles!! var vertices = this.vertices; var uvs = this.uvs; @@ -231,14 +249,16 @@ var length = vertices.length / 2; // this.count++; - for (var i = 0; i < length - 2; i++) { + for (var i = 0; i < length - 2; i++) + { // draw some triangles! var index = i * 2; this._renderCanvasDrawTriangle(context, vertices, uvs, index, (index + 2), (index + 4)); } }; -Strip.prototype._renderCanvasTriangles = function (context) { +Strip.prototype._renderCanvasTriangles = function (context) +{ // draw triangles!! var vertices = this.vertices; var uvs = this.uvs; @@ -247,14 +267,16 @@ var length = indices.length; // this.count++; - for (var i = 0; i < length; i += 3) { + for (var i = 0; i < length; i += 3) + { // draw some triangles! var index0 = indices[i] * 2, index1 = indices[i + 1] * 2, index2 = indices[i + 2] * 2; this._renderCanvasDrawTriangle(context, vertices, uvs, index0, index1, index2); } }; -Strip.prototype._renderCanvasDrawTriangle = function (context, vertices, uvs, index0, index1, index2) { +Strip.prototype._renderCanvasDrawTriangle = function (context, vertices, uvs, index0, index1, index2) +{ var textureSource = this.texture.baseTexture.source; var textureWidth = this.texture.width; var textureHeight = this.texture.height; @@ -265,7 +287,8 @@ var u0 = uvs[index0] * textureWidth, u1 = uvs[index1] * textureWidth, u2 = uvs[index2] * textureWidth; var v0 = uvs[index0 + 1] * textureHeight, v1 = uvs[index1 + 1] * textureHeight, v2 = uvs[index2 + 1] * textureHeight; - if (this.canvasPadding > 0) { + if (this.canvasPadding > 0) + { var paddingX = this.canvasPadding / this.worldTransform.a; var paddingY = this.canvasPadding / this.worldTransform.d; var centerX = (x0 + x1 + x2) / 3; @@ -332,7 +355,8 @@ * @param strip {Strip} The Strip to render * @private */ -Strip.prototype.renderStripFlat = function (strip) { +Strip.prototype.renderStripFlat = function (strip) +{ var context = this.context; var vertices = strip.vertices; @@ -340,7 +364,8 @@ // this.count++; context.beginPath(); - for (var i=1; i < length-2; i++) { + for (var i=1; i < length-2; i++) + { // draw some triangles! var index = i*2; @@ -358,7 +383,8 @@ }; /* -Strip.prototype.setTexture = function (texture) { +Strip.prototype.setTexture = function (texture) +{ //TODO SET THE TEXTURES //TODO VISIBILITY @@ -377,7 +403,8 @@ * @private */ -Strip.prototype.onTextureUpdate = function () { +Strip.prototype.onTextureUpdate = function () +{ this.updateFrame = true; }; @@ -387,7 +414,8 @@ * @param matrix {Matrix} the transformation matrix of the sprite * @return {Rectangle} the framing rectangle */ -Strip.prototype.getBounds = function (matrix) { +Strip.prototype.getBounds = function (matrix) +{ var worldTransform = matrix || this.worldTransform; var a = worldTransform.a; @@ -404,7 +432,8 @@ var minY = Infinity; var vertices = this.vertices; - for (var i = 0, n = vertices.length; i < n; i += 2) { + for (var i = 0, n = vertices.length; i < n; i += 2) + { var rawX = vertices[i], rawY = vertices[i + 1]; var x = (a * rawX) + (c * rawY) + tx; var y = (d * rawY) + (b * rawX) + ty; @@ -416,7 +445,8 @@ maxY = y > maxY ? y : maxY; } - if (minX === -Infinity || maxY === Infinity) { + if (minX === -Infinity || maxY === Infinity) + { return core.math.Rectangle.EMPTY; } diff --git a/src/extras/TilingSprite.js b/src/extras/TilingSprite.js index 3ac22df..31da393 100644 --- a/src/extras/TilingSprite.js +++ b/src/extras/TilingSprite.js @@ -10,7 +10,8 @@ * @param width {number} the width of the tiling sprite * @param height {number} the height of the tiling sprite */ -function TilingSprite(texture, width, height) { +function TilingSprite(texture, width, height) +{ core.Sprite.call( this, texture); /** @@ -86,10 +87,12 @@ * @memberof TilingSprite# */ width: { - get: function () { + get: function () + { return this._width; }, - set: function (value) { + set: function (value) + { this._width = value; } }, @@ -101,20 +104,25 @@ * @memberof TilingSprite# */ height: { - get: function () { + get: function () + { return this._height; }, - set: function (value) { + set: function (value) + { this._height = value; } }, texture: { - get: function () { + get: function () + { return this._texture; }, - set: function (value) { - if (this._texture === value) { + set: function (value) + { + if (this._texture === value) + { return; } @@ -130,51 +138,61 @@ * * @param renderer {WebGLRenderer} */ -TilingSprite.prototype.renderWebGL = function (renderer) { - if (!this.visible || this.alpha <= 0) { +TilingSprite.prototype.renderWebGL = function (renderer) +{ + if (!this.visible || this.alpha <= 0) + { return; } var i, j; - if (this._mask) { + if (this._mask) + { renderer.spriteBatch.stop(); renderer.maskManager.pushMask(this.mask, renderer); renderer.spriteBatch.start(); } - if (this._filters) { + if (this._filters) + { renderer.spriteBatch.flush(); renderer.filterManager.pushFilter(this._filterBlock); } - if (!this.tilingTexture || this.refreshTexture) { + if (!this.tilingTexture || this.refreshTexture) + { this.generateTilingTexture(true); - if (this.tilingTexture && this.tilingTexture.needsUpdate) { + if (this.tilingTexture && this.tilingTexture.needsUpdate) + { //TODO - tweaking renderer.updateTexture(this.tilingTexture.baseTexture); this.tilingTexture.needsUpdate = false; // this.tilingTexture._uvs = null; } } - else { + else + { renderer.spriteBatch.renderTilingSprite(this); } // simple render children! - for (i=0,j=this.children.length; i= 0 && index <= this.children.length) { - if (child.parent) { + if (index >= 0 && index <= this.children.length) + { + if (child.parent) + { child.parent.removeChild(child); } @@ -154,7 +173,8 @@ return child; } - else { + else + { throw new Error(child + 'addChildAt: The index '+ index +' supplied is out of bounds ' + this.children.length); } }; @@ -165,15 +185,18 @@ * @param child {DisplayObject} * @param child2 {DisplayObject} */ -DisplayObjectContainer.prototype.swapChildren = function (child, child2) { - if (child === child2) { +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) { + if (index1 < 0 || index2 < 0) + { throw new Error('swapChildren: Both the supplied DisplayObjects must be a child of the caller.'); } @@ -187,10 +210,12 @@ * @param child {DisplayObject} The DisplayObject instance to identify * @return {Number} The index position of the child display object to identify */ -DisplayObjectContainer.prototype.getChildIndex = function (child) { +DisplayObjectContainer.prototype.getChildIndex = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { throw new Error('The supplied DisplayObject must be a child of the caller'); } @@ -203,8 +228,10 @@ * @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 */ -DisplayObjectContainer.prototype.setChildIndex = function (child, index) { - if (index < 0 || index >= this.children.length) { +DisplayObjectContainer.prototype.setChildIndex = function (child, index) +{ + if (index < 0 || index >= this.children.length) + { throw new Error('The supplied index is out of bounds'); } @@ -220,8 +247,10 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child at the given index, if any. */ -DisplayObjectContainer.prototype.getChildAt = function (index) { - if (index < 0 || index >= this.children.length) { +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'); } @@ -234,10 +263,12 @@ * @param child {DisplayObject} The DisplayObject to remove * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChild = function (child) { +DisplayObjectContainer.prototype.removeChild = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { return; } @@ -250,7 +281,8 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChildAt = function (index) { +DisplayObjectContainer.prototype.removeChildAt = function (index) +{ var child = this.getChildAt(index); child.parent = null; @@ -265,24 +297,29 @@ * @param beginIndex {Number} The beginning position. Default value is 0. * @param endIndex {Number} The ending position. Default value is size of the container. */ -DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) { +DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) +{ var begin = beginIndex || 0; var end = typeof endIndex === 'number' ? endIndex : this.children.length; var range = end - begin; - if (range > 0 && range <= end) { + if (range > 0 && range <= end) + { var removed = this.children.splice(begin, range); - for (var i = 0; i < removed.length; ++i) { + for (var i = 0; i < removed.length; ++i) + { removed[i].parent = null; } return removed; } - else if (range === 0 && this.children.length === 0) { + else if (range === 0 && this.children.length === 0) + { return []; } - else { + else + { throw new RangeError('removeChildren: numeric values are outside the acceptable range.'); } }; @@ -291,7 +328,8 @@ * Generates and updates the cached sprite for this object. * */ -DisplayObjectContainer.prototype.updateCachedSprite = function () { +DisplayObjectContainer.prototype.updateCachedSprite = function () +{ this._generateCachedSprite(); }; @@ -304,7 +342,8 @@ * @param renderer {CanvasRenderer|WebGLRenderer} The renderer used to generate the texture. * @return {Texture} a texture of the graphics object */ -DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) { +DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) +{ var bounds = this.getLocalBounds(); var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0, renderer, scaleMode, resolution); @@ -322,18 +361,22 @@ * * @private */ -DisplayObjectContainer.prototype.updateTransform = function () { - if (!this.visible) { +DisplayObjectContainer.prototype.updateTransform = function () +{ + if (!this.visible) + { return; } this.displayObjectUpdateTransform(); - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { return; } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } }; @@ -346,8 +389,10 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getBounds = function () { - if (this.children.length === 0) { +DisplayObjectContainer.prototype.getBounds = function () +{ + if (this.children.length === 0) + { return math.Rectangle.EMPTY; } @@ -365,10 +410,12 @@ var childVisible = false; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -386,7 +433,8 @@ maxY = maxY > childMaxY ? maxY : childMaxY; } - if (!childVisible) { + if (!childVisible) + { return math.Rectangle.EMPTY; } @@ -407,12 +455,14 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getLocalBounds = function () { +DisplayObjectContainer.prototype.getLocalBounds = function () +{ var matrixCache = this.worldTransform; this.worldTransform = math.Matrix.IDENTITY; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } @@ -428,13 +478,16 @@ * * @param renderer {WebGLRenderer} The renderer */ -DisplayObjectContainer.prototype.renderWebGL = function (renderer) { +DisplayObjectContainer.prototype.renderWebGL = function (renderer) +{ // if the object is not visible or the alpha is 0 then no need to render this element - if (!this.visible || this.alpha <= 0) { + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } @@ -442,14 +495,17 @@ var i, j; // do a quick check to see if this element has a mask or a filter. - if (this._mask || this._filters) { + if (this._mask || this._filters) + { // push filter first as we need to ensure the stencil buffer is correct for any masking - if (this._filters) { + if (this._filters) + { renderer.spriteBatch.flush(); renderer.filterManager.pushFilter(this._filterBlock); } - if (this._mask) { + if (this._mask) + { renderer.spriteBatch.stop(); renderer.maskManager.pushMask(this.mask, renderer); renderer.spriteBatch.start(); @@ -459,36 +515,42 @@ this._renderWebGL(renderer); // now loop through the children and make sure they get rendered - for (i = 0, j = this.children.length; i < j; i++) { + for (i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderWebGL(renderer); } // time to stop the sprite batch as either a mask element or a filter draw will happen next renderer.spriteBatch.stop(); - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(this._mask, renderer); } - if (this._filters) { + if (this._filters) + { renderer.filterManager.popFilter(); } renderer.spriteBatch.start(); } - else { + else + { this._renderWebGL(renderer); // simple render children! - for (i = 0, j = this.children.length; i < j; ++i) { + for (i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderWebGL(renderer); } } }; -DisplayObjectContainer.prototype._renderWebGL = function (renderer) { +DisplayObjectContainer.prototype._renderWebGL = function (renderer) +{ // this is where content itself gets renderd.. @@ -499,25 +561,31 @@ * * @param renderer {CanvasRenderer} The renderer */ -DisplayObjectContainer.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0) { +DisplayObjectContainer.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -528,13 +596,16 @@ * @param renderer {WebGLRenderer|CanvasRenderer} The renderer * @private */ -DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) { +DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) +{ this._cachedSprite.worldAlpha = this.worldAlpha; - if (renderer.gl) { + if (renderer.gl) + { this._cachedSprite.renderWebGL(renderer); } - else { + else + { this._cachedSprite.renderCanvas(renderer); } }; @@ -544,10 +615,12 @@ * * @private */ -DisplayObjectContainer.prototype._generateCachedSprite = function () { +DisplayObjectContainer.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { // TODO - RenderTexture now *requires* a renderer instance, so this is like broken // because `renderer` isn't actually in scope here :P var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0); @@ -555,7 +628,8 @@ this._cachedSprite = new Sprite(renderTexture); this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.texture.resize(bounds.width | 0, bounds.height | 0); } @@ -580,8 +654,10 @@ * * @private */ -DisplayObjectContainer.prototype._destroyCachedSprite = function () { - if (!this._cachedSprite) { +DisplayObjectContainer.prototype._destroyCachedSprite = function () +{ + if (!this._cachedSprite) + { return; } diff --git a/src/core/display/Sprite.js b/src/core/display/Sprite.js index 707da24..5862aef 100644 --- a/src/core/display/Sprite.js +++ b/src/core/display/Sprite.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param texture {Texture} The texture for this sprite */ -function Sprite(texture) { +function Sprite(texture) +{ DisplayObjectContainer.call(this); /** @@ -85,12 +86,14 @@ this.texture = texture || Texture.EMPTY; } -Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) { +Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) +{ DisplayObjectContainer.prototype.destroy.call(this); this.anchor = null; - if (destroyTexture) { + if (destroyTexture) + { this._texture.destroy(destroyBaseTexture); } @@ -111,10 +114,12 @@ * @memberof Sprite# */ width: { - get: function () { + get: function () + { return this.scale.x * this.texture.frame.width; }, - set: function (value) { + set: function (value) + { this.scale.x = value / this.texture.frame.width; this._width = value; } @@ -127,10 +132,12 @@ * @memberof Sprite# */ height: { - get: function () { + get: function () + { return this.scale.y * this.texture.frame.height; }, - set: function (value) { + set: function (value) + { this.scale.y = value / this.texture.frame.height; this._height = value; } @@ -143,23 +150,29 @@ * @memberof Sprite# */ texture: { - get: function () { + get: function () + { return this._texture; }, - set: function (value) { - if (this._texture === value) { + set: function (value) + { + if (this._texture === value) + { return; } this._texture = value; this.cachedTint = 0xFFFFFF; - if (value) { + if (value) + { // wait for the texture to load - if (value.baseTexture.hasLoaded) { + if (value.baseTexture.hasLoaded) + { this._onTextureUpdate(); } - else { + else + { value.once('update', this._onTextureUpdate.bind(this)); } } @@ -172,18 +185,22 @@ * * @private */ -Sprite.prototype._onTextureUpdate = function () { +Sprite.prototype._onTextureUpdate = function () +{ // so if _width is 0 then width was not set.. - if (this._width) { + if (this._width) + { this.scale.x = this._width / this.texture.frame.width; } - if (this._height) { + if (this._height) + { this.scale.y = this._height / this.texture.frame.height; } }; -Sprite.prototype._renderWebGL = function (renderer) { +Sprite.prototype._renderWebGL = function (renderer) +{ // this is where content gets renderd.. // watch this space for a little render state manager.. @@ -197,7 +214,8 @@ * @param matrix {Matrix} the transformation matrix of the sprite * @return {Rectangle} the framing rectangle */ -Sprite.prototype.getBounds = function (matrix) { +Sprite.prototype.getBounds = function (matrix) +{ var width = this.texture.frame.width; var height = this.texture.frame.height; @@ -224,11 +242,13 @@ if(b === 0 && c === 0) { // scale may be negative! - if (a < 0) { + if (a < 0) + { a *= -1; } - if (d < 0) { + if (d < 0) + { d *= -1; } @@ -293,28 +313,34 @@ * * @param renderer {CanvasRenderer} The renderer */ -Sprite.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) { +Sprite.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) + { return; } - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; renderer.context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } // Ignore null sources - if (this.texture.valid) { + if (this.texture.valid) + { var resolution = this.texture.baseTexture.resolution / renderer.resolution; renderer.context.globalAlpha = this.worldAlpha; // If smoothingEnabled is supported and we need to change the smoothing property for this texture - if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) { + if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) + { renderer.scaleMode = this.texture.baseTexture.scaleMode; renderer.context[renderer.smoothProperty] = (renderer.scaleMode === CONST.scaleModes.LINEAR); } @@ -324,7 +350,8 @@ var dy = (this.texture.trim ? this.texture.trim.y : 0) - (this.anchor.y * this.texture.trim.height); // Allow for pixel rounding - if (renderer.roundPixels) { + if (renderer.roundPixels) + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -337,7 +364,8 @@ dx = dx | 0; dy = dy | 0; } - else { + else + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -348,8 +376,10 @@ ); } - if (this.tint !== 0xFFFFFF) { - if (this.cachedTint !== this.tint) { + if (this.tint !== 0xFFFFFF) + { + if (this.cachedTint !== this.tint) + { this.cachedTint = this.tint; // TODO clean up caching - how to clean up the caches? @@ -368,7 +398,8 @@ this.texture.crop.height / resolution ); } - else { + else + { renderer.context.drawImage( this.texture.baseTexture.source, this.texture.crop.x, @@ -383,11 +414,13 @@ } } - for (var i = 0, j = this.children.length; i < j; i++) { + for (var i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -402,10 +435,12 @@ * @param frameId {String} The frame Id of the texture in the cache * @return {Sprite} A new Sprite using a texture from the texture cache matching the frameId */ -Sprite.fromFrame = function (frameId) { +Sprite.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache' + this); } @@ -420,6 +455,7 @@ * @param imageId {String} The image url of the texture * @return {Sprite} A new Sprite using a texture from the texture cache matching the image id */ -Sprite.fromImage = function (imageId, crossorigin, scaleMode) { +Sprite.fromImage = function (imageId, crossorigin, scaleMode) +{ return new Sprite(Texture.fromImage(imageId, crossorigin, scaleMode)); }; diff --git a/src/core/display/SpriteBatch.js b/src/core/display/SpriteBatch.js index 3187777..c196fef 100644 --- a/src/core/display/SpriteBatch.js +++ b/src/core/display/SpriteBatch.js @@ -12,7 +12,8 @@ * ```js * var container = new SpriteBatch(); * - * for(var i = 0; i < 100; ++i) { + * for(var i = 0; i < 100; ++i) + * { * var sprite = new PIXI.Sprite.fromImage("myImage.png"); * container.addChild(sprite); * } @@ -25,7 +26,8 @@ */ //TODO RENAME to PARTICLE CONTAINER? -function SpriteBatch() { +function SpriteBatch() +{ DisplayObjectContainer.call(this); } @@ -38,7 +40,8 @@ * * @private */ -SpriteBatch.prototype.updateTransform = function () { +SpriteBatch.prototype.updateTransform = function () +{ // TODO don't need to! this.displayObjectUpdateTransform(); // PIXI.DisplayObjectContainer.prototype.updateTransform.call( this ); @@ -50,8 +53,10 @@ * @param renderer {WebGLRenderer} The webgl renderer * @private */ -SpriteBatch.prototype.renderWebGL = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderWebGL = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -71,8 +76,10 @@ * @param renderer {CanvasRenderer} The canvas renderer * @private */ -SpriteBatch.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -84,10 +91,12 @@ this.displayObjectUpdateTransform(); - for (var i = 0; i < this.children.length; ++i) { + for (var i = 0; i < this.children.length; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -95,9 +104,11 @@ context.globalAlpha = this.worldAlpha * child.alpha; - if (child.rotation % (Math.PI * 2) === 0) { + if (child.rotation % (Math.PI * 2) === 0) + { // this is the fastest way to optimise! - if rotation is 0 then we can avoid any kind of setTransform call - if (isRotated) { + if (isRotated) + { context.setTransform( transform.a, transform.b, @@ -122,8 +133,10 @@ frame.height * child.scale.y ); } - else { - if (!isRotated) { + else + { + if (!isRotated) + { isRotated = true; } @@ -131,7 +144,8 @@ var childTransform = child.worldTransform; - if (renderer.roundPixels) { + if (renderer.roundPixels) + { context.setTransform( childTransform.a, childTransform.b, @@ -141,7 +155,8 @@ childTransform.ty | 0 ); } - else { + else + { context.setTransform( childTransform.a, childTransform.b, diff --git a/src/core/index.js b/src/core/index.js index 3954b6f..eb4a82b 100644 --- a/src/core/index.js +++ b/src/core/index.js @@ -58,11 +58,13 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRenderer: function (width, height, options, noWebGL) { + autoDetectRenderer: function (width, height, options, noWebGL) + { width = width || 800; height = height || 600; - if (!noWebGL && require('webgl-enabled')()) { + if (!noWebGL && require('webgl-enabled')()) + { return new core.WebGLRenderer(width, height, options); } @@ -87,7 +89,8 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRecommendedRenderer: function (width, height, options) { + autoDetectRecommendedRenderer: function (width, height, options) + { var isAndroid = /Android/i.test(navigator.userAgent); return core.autoDetectRenderer(width, height, options, isAndroid); diff --git a/src/core/math/Matrix.js b/src/core/math/Matrix.js index c2f87e2..2ff4848 100644 --- a/src/core/math/Matrix.js +++ b/src/core/math/Matrix.js @@ -10,7 +10,8 @@ * @class * @namespace PIXI */ -function Matrix() { +function Matrix() +{ /** * @member {number} * @default 1 @@ -63,7 +64,8 @@ * * @param array {number[]} The array that the matrix will be populated from. */ -Matrix.prototype.fromArray = function (array) { +Matrix.prototype.fromArray = function (array) +{ this.a = array[0]; this.b = array[1]; this.c = array[3]; @@ -78,14 +80,17 @@ * @param transpose {boolean} Whether we need to transpose the matrix or not * @return {number[]} the newly created array which contains the matrix */ -Matrix.prototype.toArray = function (transpose) { - if (!this.array) { +Matrix.prototype.toArray = function (transpose) +{ + if (!this.array) + { this.array = new Float32Array(9); } var array = this.array; - if (transpose) { + if (transpose) + { array[0] = this.a; array[1] = this.b; array[2] = 0; @@ -96,7 +101,8 @@ array[7] = this.ty; array[8] = 1; } - else { + else + { array[0] = this.a; array[1] = this.c; array[2] = this.tx; @@ -119,7 +125,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, transformed through this matrix */ -Matrix.prototype.apply = function (pos, newPos) { +Matrix.prototype.apply = function (pos, newPos) +{ newPos = newPos || new Point(); newPos.x = this.a * pos.x + this.c * pos.y + this.tx; @@ -136,7 +143,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, inverse-transformed through this matrix */ -Matrix.prototype.applyInverse = function (pos, newPos) { +Matrix.prototype.applyInverse = function (pos, newPos) +{ newPos = newPos || new Point(); var id = 1 / (this.a * this.d + this.c * -this.b); @@ -154,7 +162,8 @@ * @param {number} y * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.translate = function (x, y) { +Matrix.prototype.translate = function (x, y) +{ this.tx += x; this.ty += y; @@ -168,7 +177,8 @@ * @param {number} y The amount to scale vertically * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.scale = function (x, y) { +Matrix.prototype.scale = function (x, y) +{ this.a *= x; this.d *= y; this.c *= x; @@ -186,7 +196,8 @@ * @param {number} angle - The angle in radians. * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.rotate = function (angle) { +Matrix.prototype.rotate = function (angle) +{ var cos = Math.cos( angle ); var sin = Math.sin( angle ); @@ -210,7 +221,8 @@ * @param {Matrix} matrix * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.append = function (matrix) { +Matrix.prototype.append = function (matrix) +{ var a1 = this.a; var b1 = this.b; var c1 = this.c; @@ -232,7 +244,8 @@ * * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.identity = function () { +Matrix.prototype.identity = function () +{ this.a = 1; this.b = 0; this.c = 0; diff --git a/src/core/math/Point.js b/src/core/math/Point.js index 7565b2d..632f346 100644 --- a/src/core/math/Point.js +++ b/src/core/math/Point.js @@ -7,7 +7,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -function Point(x, y) { +function Point(x, y) +{ /** * @member {number} * @default 0 @@ -29,7 +30,8 @@ * * @return {Point} a copy of the point */ -Point.prototype.clone = function () { +Point.prototype.clone = function () +{ return new Point(this.x, this.y); }; @@ -40,7 +42,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -Point.prototype.set = function (x, y) { +Point.prototype.set = function (x, y) +{ this.x = x || 0; this.y = y || ( (y !== 0) ? this.x : 0 ) ; }; diff --git a/src/core/math/shapes/Circle.js b/src/core/math/shapes/Circle.js index 69cfdc9..4d76efc 100644 --- a/src/core/math/shapes/Circle.js +++ b/src/core/math/shapes/Circle.js @@ -10,7 +10,8 @@ * @param y {number} The Y coordinate of the center of this circle * @param radius {number} The radius of the circle */ -function Circle(x, y, radius) { +function Circle(x, y, radius) +{ /** * @member {number} * @default 0 @@ -46,7 +47,8 @@ * @method clone * @return {Circle} a copy of the Circle */ -Circle.prototype.clone = function () { +Circle.prototype.clone = function () +{ return new Circle(this.x, this.y, this.radius); }; @@ -58,8 +60,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Circle */ -Circle.prototype.contains = function (x, y) { - if (this.radius <= 0) { +Circle.prototype.contains = function (x, y) +{ + if (this.radius <= 0) + { return false; } @@ -79,6 +83,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Circle.prototype.getBounds = function () { +Circle.prototype.getBounds = function () +{ return new Rectangle(this.x - this.radius, this.y - this.radius, this.radius * 2, this.radius * 2); }; diff --git a/src/core/math/shapes/Ellipse.js b/src/core/math/shapes/Ellipse.js index 4f2d066..fefd01a 100644 --- a/src/core/math/shapes/Ellipse.js +++ b/src/core/math/shapes/Ellipse.js @@ -11,7 +11,8 @@ * @param width {number} The half width of this ellipse * @param height {number} The half height of this ellipse */ -function Ellipse(x, y, width, height) { +function Ellipse(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -53,7 +54,8 @@ * @method clone * @return {Ellipse} a copy of the ellipse */ -Ellipse.prototype.clone = function () { +Ellipse.prototype.clone = function () +{ return new Ellipse(this.x, this.y, this.width, this.height); }; @@ -65,8 +67,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coords are within this ellipse */ -Ellipse.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Ellipse.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } @@ -86,6 +90,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Ellipse.prototype.getBounds = function () { +Ellipse.prototype.getBounds = function () +{ return new Rectangle(this.x - this.width, this.y - this.height, this.width, this.height); }; diff --git a/src/core/math/shapes/Polygon.js b/src/core/math/shapes/Polygon.js index ae89148..fea6d37 100644 --- a/src/core/math/shapes/Polygon.js +++ b/src/core/math/shapes/Polygon.js @@ -10,16 +10,20 @@ * arguments passed can be flat x,y values e.g. `new Polygon(x,y, x,y, x,y, ...)` where `x` and `y` are * Numbers. */ -function Polygon(points) { +function Polygon(points) +{ //if points isn't an array, use arguments as the array - if (!(points instanceof Array)) { + if (!(points instanceof Array)) + { points = Array.prototype.slice.call(arguments); } //if this is a flat array of numbers, convert it to points - if (points[0] instanceof Point) { + if (points[0] instanceof Point) + { var p = []; - for (var i = 0, il = points.length; i < il; i++) { + for (var i = 0, il = points.length; i < il; i++) + { p.push(points[i].x, points[i].y); } @@ -51,7 +55,8 @@ * * @return {Polygon} a copy of the polygon */ -Polygon.prototype.clone = function () { +Polygon.prototype.clone = function () +{ return new Polygon(this.points.slice()); }; @@ -62,19 +67,22 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this polygon */ -Polygon.prototype.contains = function (x, y) { +Polygon.prototype.contains = function (x, y) +{ var inside = false; // use some raycasting to test hits // https://github.com/substack/point-in-polygon/blob/master/index.js var length = this.points.length / 2; - for (var i = 0, j = length - 1; i < length; j = i++) { + for (var i = 0, j = length - 1; i < length; j = i++) + { var xi = this.points[i * 2], yi = this.points[i * 2 + 1], xj = this.points[j * 2], yj = this.points[j * 2 + 1], intersect = ((yi > y) !== (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi); - if (intersect) { + if (intersect) + { inside = !inside; } } diff --git a/src/core/math/shapes/Rectangle.js b/src/core/math/shapes/Rectangle.js index 16ac62a..4008b68 100644 --- a/src/core/math/shapes/Rectangle.js +++ b/src/core/math/shapes/Rectangle.js @@ -10,7 +10,8 @@ * @param width {number} The overall width of this rectangle * @param height {number} The overall height of this rectangle */ -function Rectangle(x, y, width, height) { +function Rectangle(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -60,7 +61,8 @@ * * @return {Rectangle} a copy of the rectangle */ -Rectangle.prototype.clone = function () { +Rectangle.prototype.clone = function () +{ return new Rectangle(this.x, this.y, this.width, this.height); }; @@ -71,13 +73,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rectangle */ -Rectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Rectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/math/shapes/RoundedRectangle.js b/src/core/math/shapes/RoundedRectangle.js index 27d286e..7bf6411 100644 --- a/src/core/math/shapes/RoundedRectangle.js +++ b/src/core/math/shapes/RoundedRectangle.js @@ -11,7 +11,8 @@ * @param height {number} The overall height of this rounded rectangle * @param radius {number} Controls the radius of the rounded corners */ -function RoundedRectangle(x, y, width, height, radius) { +function RoundedRectangle(x, y, width, height, radius) +{ /** * @member {number} * @default 0 @@ -58,7 +59,8 @@ * * @return {RoundedRectangle} a copy of the rounded rectangle */ -RoundedRectangle.prototype.clone = function () { +RoundedRectangle.prototype.clone = function () +{ return new RoundedRectangle(this.x, this.y, this.width, this.height, this.radius); }; @@ -69,13 +71,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rounded Rectangle */ -RoundedRectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +RoundedRectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/primitives/Graphics.js b/src/core/primitives/Graphics.js index 261c534..e902d2a 100644 --- a/src/core/primitives/Graphics.js +++ b/src/core/primitives/Graphics.js @@ -16,7 +16,8 @@ * @extends DisplayObjectContainer * @namespace PIXI */ -function Graphics() { +function Graphics() +{ DisplayObjectContainer.call(this); this.renderable = true; @@ -154,16 +155,20 @@ * @private */ cacheAsBitmap: { - get: function () { + get: function () + { return this._cacheAsBitmap; }, - set: function (value) { + set: function (value) + { this._cacheAsBitmap = value; - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._generateCachedSprite(); } - else { + else + { this.destroyCachedSprite(); this.dirty = true; } @@ -176,7 +181,8 @@ * * @return {Graphics} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ var clone = new Graphics(); clone.renderable = this.renderable; @@ -192,7 +198,8 @@ clone.cachedSpriteDirty = this.cachedSpriteDirty; // copy graphics data - for (var i = 0; i < this.graphicsData.length; ++i) { + for (var i = 0; i < this.graphicsData.length; ++i) + { clone.graphicsData.push(this.graphicsData.clone()); } @@ -211,17 +218,21 @@ * @param alpha {number} alpha of the line to draw, will update the objects stored style * @return {Graphics} */ -Graphics.prototype.lineStyle = function (lineWidth, color, alpha) { +Graphics.prototype.lineStyle = function (lineWidth, color, alpha) +{ this.lineWidth = lineWidth || 0; this.lineColor = color || 0; this.lineAlpha = (arguments.length < 3) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length) + { // halfway through a line? start a new one! this.drawShape( new math.Polygon( this.currentPath.shape.points.slice(-2) )); } - else { + else + { // otherwise its empty so lets just set the line properties this.currentPath.lineWidth = this.lineWidth; this.currentPath.lineColor = this.lineColor; @@ -239,7 +250,8 @@ * @param y {number} the Y coordinate to move to * @return {Graphics} */ -Graphics.prototype.moveTo = function (x, y) { +Graphics.prototype.moveTo = function (x, y) +{ this.drawShape(new math.Polygon([x,y])); return this; @@ -253,7 +265,8 @@ * @param y {number} the Y coordinate to draw to * @return {Graphics} */ -Graphics.prototype.lineTo = function (x, y) { +Graphics.prototype.lineTo = function (x, y) +{ this.currentPath.shape.points.push(x, y); this.dirty = true; @@ -270,13 +283,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -285,7 +302,8 @@ n = 20, points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { this.moveTo(0, 0); } @@ -293,7 +311,8 @@ var fromY = points[points.length-1]; var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; xa = fromX + ( (cpX - fromX) * j ); @@ -319,13 +338,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -342,7 +365,8 @@ var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; dt = (1 - j); @@ -373,13 +397,17 @@ * @param radius {number} The radius of the arc * @return {Graphics} */ -Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points.push(x1, y1); } } - else { + else + { this.moveTo(x1, y1); } @@ -392,12 +420,15 @@ b2 = x2 - x1, mm = Math.abs(a1 * b2 - b1 * a2); - if (mm < 1.0e-8 || radius === 0) { - if (points[points.length-2] !== x1 || points[points.length-1] !== y1) { + if (mm < 1.0e-8 || radius === 0) + { + if (points[points.length-2] !== x1 || points[points.length-1] !== y1) + { points.push(x1, y1); } } - else { + else + { var dd = a1 * a1 + b1 * b1, cc = a2 * a2 + b2 * b2, tt = a1 * a2 + b1 * b2, @@ -433,42 +464,51 @@ * @param anticlockwise {boolean} Optional. Specifies whether the drawing should be counterclockwise or clockwise. False is default, and indicates clockwise, while true indicates counter-clockwise. * @return {Graphics} */ -Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) { +Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) +{ var startX = cx + Math.cos(startAngle) * radius; var startY = cy + Math.sin(startAngle) * radius; var points; // TODO - This if-else makes no sense. It uses currentPath in the else where it doesn't exist... - if (this.currentPath) { + if (this.currentPath) + { points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { points.push(startX, startY); } - else if (points[points.length-2] !== startX || points[points.length-1] !== startY) { + else if (points[points.length-2] !== startX || points[points.length-1] !== startY) + { points.push(startX, startY); } } - else { + else + { this.moveTo(startX, startY); points = this.currentPath.shape.points; } - if (startAngle === endAngle) { + if (startAngle === endAngle) + { return this; } - if (!anticlockwise && endAngle <= startAngle) { + if (!anticlockwise && endAngle <= startAngle) + { endAngle += Math.PI * 2; } - else if (anticlockwise && startAngle <= endAngle) { + else if (anticlockwise && startAngle <= endAngle) + { startAngle += Math.PI * 2; } var sweep = anticlockwise ? (startAngle - endAngle) *-1 : (endAngle - startAngle); var segs = (Math.abs(sweep)/ (Math.PI * 2)) * 40; - if (sweep === 0) { + if (sweep === 0) + { return this; } @@ -482,7 +522,8 @@ var remainder = ( segMinus % 1 ) / segMinus; - for (var i = 0; i <= segMinus; ++i) { + for (var i = 0; i <= segMinus; ++i) + { var real = i + remainder * i; var angle = ((theta) + startAngle + (theta2 * real)); @@ -506,13 +547,16 @@ * @param alpha {number} the alpha of the fill * @return {Graphics} */ -Graphics.prototype.beginFill = function (color, alpha) { +Graphics.prototype.beginFill = function (color, alpha) +{ this.filling = true; this.fillColor = color || 0; this.fillAlpha = (alpha === undefined) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length <= 2) + { this.currentPath.fill = this.filling; this.currentPath.fillColor = this.fillColor; this.currentPath.fillAlpha = this.fillAlpha; @@ -526,7 +570,8 @@ * * @return {Graphics} */ -Graphics.prototype.endFill = function () { +Graphics.prototype.endFill = function () +{ this.filling = false; this.fillColor = null; this.fillAlpha = 1; @@ -542,7 +587,8 @@ * @param height {number} The height of the rectangle * @return {Graphics} */ -Graphics.prototype.drawRect = function ( x, y, width, height ) { +Graphics.prototype.drawRect = function ( x, y, width, height ) +{ this.drawShape(new math.Rectangle(x,y, width, height)); return this; @@ -556,7 +602,8 @@ * @param height {number} The height of the rectangle * @param radius {number} Radius of the rectangle corners */ -Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) { +Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) +{ this.drawShape(new math.RoundedRectangle(x, y, width, height, radius)); return this; @@ -570,7 +617,8 @@ * @param radius {number} The radius of the circle * @return {Graphics} */ -Graphics.prototype.drawCircle = function (x, y, radius) { +Graphics.prototype.drawCircle = function (x, y, radius) +{ this.drawShape(new math.Circle(x,y, radius)); return this; @@ -585,7 +633,8 @@ * @param height {number} The half height of the ellipse * @return {Graphics} */ -Graphics.prototype.drawEllipse = function (x, y, width, height) { +Graphics.prototype.drawEllipse = function (x, y, width, height) +{ this.drawShape(new math.Ellipse(x, y, width, height)); return this; @@ -597,8 +646,10 @@ * @param path {Array} The path data used to construct the polygon. * @return {Graphics} */ -Graphics.prototype.drawPolygon = function (path) { - if (!(path instanceof Array)) { +Graphics.prototype.drawPolygon = function (path) +{ + if (!(path instanceof Array)) + { path = Array.prototype.slice.call(arguments); } @@ -612,7 +663,8 @@ * * @return {Graphics} */ -Graphics.prototype.clear = function () { +Graphics.prototype.clear = function () +{ this.lineWidth = 0; this.filling = false; @@ -631,7 +683,8 @@ * @param scaleMode {number} Should be one of the scaleMode consts * @return {Texture} a texture of the graphics object */ -Graphics.prototype.generateTexture = function (resolution, scaleMode) { +Graphics.prototype.generateTexture = function (resolution, scaleMode) +{ resolution = resolution || 1; var bounds = this.getBounds(); @@ -655,17 +708,21 @@ * * @param renderer {WebGLRenderer} */ -Graphics.prototype._renderWebGL = function (renderer) { +Graphics.prototype._renderWebGL = function (renderer) +{ // if the sprite is not visible or the alpha is 0 then no need to render this element - if (this.isMask === true) { + if (this.isMask === true) + { return; } // this code may still be needed so leaving for now.. - // + // /* - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture on the gpu too! @@ -681,17 +738,24 @@ return; } - */ - - // check if the webgl graphic needs to be updated - if (this.glDirty) { - this.dirty = true; - this.glDirty = false; - } + else */ - renderer.setObjectRendererer(renderer.graphicsRenderer); - renderer.graphicsRenderer.render(this); + renderer.spriteBatch.stop(); + renderer.blendModeManager.setBlendMode(this.blendMode); + // check blend mode + renderer.blendModeManager.setBlendMode( this.blendMode ); + + // check if the webgl graphic needs to be updated + if (this.glDirty) + { + this.dirty = true; + this.glDirty = false; + } + + WebGLGraphics.renderGraphics(this, renderer); + + renderer.spriteBatch.start(); }; /** @@ -700,14 +764,18 @@ * @param renderer {CanvasRenderer} * @private */ -Graphics.prototype.renderCanvas = function (renderer) { +Graphics.prototype.renderCanvas = function (renderer) +{ // 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.isMask === true) { + if (!this.visible || this.alpha <= 0 || this.isMask === true) + { return; } - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture @@ -723,16 +791,19 @@ return; } - else { + else + { var context = renderer.context; var transform = this.worldTransform; - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } @@ -748,11 +819,13 @@ CanvasGraphics.renderGraphics(this, context); - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } } @@ -763,13 +836,16 @@ * * @return {Rectangle} the rectangular bounding area */ -Graphics.prototype.getBounds = function (matrix) { +Graphics.prototype.getBounds = function (matrix) +{ // return an empty object if the item is a mask! - if (this.isMask) { + if (this.isMask) + { return math.Rectangle.EMPTY; } - if (this.dirty) { + if (this.dirty) + { this.updateLocalBounds(); this.glDirty = true; @@ -841,23 +917,27 @@ * Update the bounds of the object * */ -Graphics.prototype.updateLocalBounds = function () { +Graphics.prototype.updateLocalBounds = function () +{ var minX = Infinity; var maxX = -Infinity; var minY = Infinity; var maxY = -Infinity; - if (this.graphicsData.length) { + if (this.graphicsData.length) + { var shape, points, x, y, w, h; - for (var i = 0; i < this.graphicsData.length; i++) { + for (var i = 0; i < this.graphicsData.length; i++) + { var data = this.graphicsData[i]; var type = data.type; var lineWidth = data.lineWidth; shape = data.shape; - if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) { + if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) + { x = shape.x - lineWidth/2; y = shape.y - lineWidth/2; w = shape.width + lineWidth; @@ -869,7 +949,8 @@ minY = y < minY ? y : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.CIRC) { + else if (type === CONST.SHAPES.CIRC) + { x = shape.x; y = shape.y; w = shape.radius + lineWidth/2; @@ -881,7 +962,8 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.ELIP) { + else if (type === CONST.SHAPES.ELIP) + { x = shape.x; y = shape.y; w = shape.width + lineWidth/2; @@ -893,11 +975,13 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else { + else + { // POLY points = shape.points; - for (var j = 0; j < points.length; j += 2) { + for (var j = 0; j < points.length; j += 2) + { x = points[j]; y = points[j+1]; @@ -910,7 +994,8 @@ } } } - else { + else + { minX = 0; maxX = 0; minY = 0; @@ -931,10 +1016,12 @@ * * @private */ -Graphics.prototype._generateCachedSprite = function () { +Graphics.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { var canvasBuffer = new CanvasBuffer(bounds.width, bounds.height); var texture = Texture.fromCanvas(canvasBuffer.canvas); @@ -943,7 +1030,8 @@ this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.buffer.resize(bounds.width, bounds.height); } @@ -968,7 +1056,8 @@ * * @private */ -Graphics.prototype.updateCachedSpriteTexture = function () { +Graphics.prototype.updateCachedSpriteTexture = function () +{ var cachedSprite = this._cachedSprite; var texture = cachedSprite.texture; var canvas = cachedSprite.buffer.canvas; @@ -989,7 +1078,8 @@ * Destroys a previous cached sprite. * */ -Graphics.prototype.destroyCachedSprite = function () { +Graphics.prototype.destroyCachedSprite = function () +{ this._cachedSprite.texture.destroy(true); // let the gc collect the unused sprite @@ -1003,10 +1093,13 @@ * @param {Circle|Rectangle|Ellipse|Line|Polygon} shape The Shape object to draw. * @return {GraphicsData} The generated GraphicsData object. */ -Graphics.prototype.drawShape = function (shape) { - if (this.currentPath) { +Graphics.prototype.drawShape = function (shape) +{ + if (this.currentPath) + { // check current path! - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath.shape.points.length <= 2) + { this.graphicsData.pop(); } } @@ -1017,7 +1110,8 @@ this.graphicsData.push(data); - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { data.shape.closed = this.filling; this.currentPath = data; } diff --git a/src/core/primitives/GraphicsData.js b/src/core/primitives/GraphicsData.js index 99decbe..788f6f2 100644 --- a/src/core/primitives/GraphicsData.js +++ b/src/core/primitives/GraphicsData.js @@ -4,7 +4,8 @@ * @class * @namespace PIXI */ -function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) { +function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) +{ this.lineWidth = lineWidth; this.lineColor = lineColor; this.lineAlpha = lineAlpha; @@ -27,7 +28,8 @@ * * @return {GraphicsData} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ return new GraphicsData( this.lineWidth, this.lineColor, diff --git a/src/core/renderers/canvas/CanvasRenderer.js b/src/core/renderers/canvas/CanvasRenderer.js index 15a0978..7aebd44 100644 --- a/src/core/renderers/canvas/CanvasRenderer.js +++ b/src/core/renderers/canvas/CanvasRenderer.js @@ -17,17 +17,22 @@ * @param [options.resolution=1] {number} the resolution of the renderer retina would be 2 * @param [options.clearBeforeRender=true] {boolean} This sets if the CanvasRenderer will clear the canvas or not before the new render pass. */ -function CanvasRenderer(width, height, options) { +function CanvasRenderer(width, height, options) +{ utils.sayHello('Canvas'); - if (options) { - for (var i in CONST.defaultRenderOptions) { - if (typeof options[i] === 'undefined') { + if (options) + { + for (var i in CONST.defaultRenderOptions) + { + if (typeof options[i] === 'undefined') + { options[i] = CONST.defaultRenderOptions[i]; } } } - else { + else + { options = CONST.defaultRenderOptions; } @@ -156,19 +161,24 @@ this.smoothProperty = null; - if (this.context.imageSmoothingEnabled) { + if (this.context.imageSmoothingEnabled) + { this.smoothProperty = 'imageSmoothingEnabled'; } - else if (this.context.webkitImageSmoothingEnabled) { + else if (this.context.webkitImageSmoothingEnabled) + { this.smoothProperty = 'webkitImageSmoothingEnabled'; } - else if (this.context.mozImageSmoothingEnabled) { + else if (this.context.mozImageSmoothingEnabled) + { this.smoothProperty = 'mozImageSmoothingEnabled'; } - else if (this.context.oImageSmoothingEnabled) { + else if (this.context.oImageSmoothingEnabled) + { this.smoothProperty = 'oImageSmoothingEnabled'; } - else if (this.context.msImageSmoothingEnabled) { + else if (this.context.msImageSmoothingEnabled) + { this.smoothProperty = 'msImageSmoothingEnabled'; } @@ -193,10 +203,12 @@ * @memberof CanvasRenderer# */ backgroundColor: { - get: function () { + get: function () + { return this._backgroundColor; }, - set: function (val) { + set: function (val) + { this._backgroundColor = val; this._backgroundColorString = utils.hex2string(val); } @@ -208,7 +220,8 @@ * * @param object {DisplayObject} the object to be rendered */ -CanvasRenderer.prototype.render = function (object) { +CanvasRenderer.prototype.render = function (object) +{ object.updateTransform(); this.context.setTransform(1,0,0,1,0,0); @@ -218,16 +231,20 @@ this.currentBlendMode = CONST.blendModes.NORMAL; this.context.globalCompositeOperation = this.blendModes[CONST.blendModes.NORMAL]; - if (navigator.isCocoonJS && this.view.screencanvas) { + if (navigator.isCocoonJS && this.view.screencanvas) + { this.context.fillStyle = 'black'; this.context.clear(); } - if (this.clearBeforeRender) { - if (this.transparent) { + if (this.clearBeforeRender) + { + if (this.transparent) + { this.context.clearRect(0, 0, this.width, this.height); } - else { + else + { this.context.fillStyle = this._backgroundColorString; this.context.fillRect(0, 0, this.width , this.height); } @@ -241,8 +258,10 @@ * * @param [removeView=false] {boolean} Removes the Canvas element from the DOM. */ -CanvasRenderer.prototype.destroy = function (removeView) { - if (removeView && this.view.parent) { +CanvasRenderer.prototype.destroy = function (removeView) +{ + if (removeView && this.view.parent) + { this.view.parent.removeChild(this.view); } @@ -257,14 +276,16 @@ * @param width {number} the new width of the canvas view * @param height {number} the new height of the canvas view */ -CanvasRenderer.prototype.resize = function (width, height) { +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) { + if (this.autoResize) + { this.view.style.width = this.width / this.resolution + 'px'; this.view.style.height = this.height / this.resolution + 'px'; } @@ -276,7 +297,8 @@ * @param displayObject {DisplayObject} The displayObject to render * @private */ -CanvasRenderer.prototype.renderDisplayObject = function (displayObject) { +CanvasRenderer.prototype.renderDisplayObject = function (displayObject) +{ displayObject.renderCanvas(this); }; @@ -285,11 +307,14 @@ * * @private */ -CanvasRenderer.prototype._mapBlendModes = function () { - if (!this.blendModes) { +CanvasRenderer.prototype._mapBlendModes = function () +{ + if (!this.blendModes) + { this.blendModes = {}; - if (utils.canUseNewCanvasBlendModes()) { + if (utils.canUseNewCanvasBlendModes()) + { this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? this.blendModes[CONST.blendModes.MULTIPLY] = 'multiply'; @@ -308,7 +333,8 @@ this.blendModes[CONST.blendModes.COLOR] = 'color'; this.blendModes[CONST.blendModes.LUMINOSITY] = 'luminosity'; } - else { + else + { // this means that the browser does not support the cool new blend modes in canvas 'cough' ie 'cough' this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? diff --git a/src/core/renderers/canvas/utils/CanvasBuffer.js b/src/core/renderers/canvas/utils/CanvasBuffer.js index ebe5d47..b183a66 100644 --- a/src/core/renderers/canvas/utils/CanvasBuffer.js +++ b/src/core/renderers/canvas/utils/CanvasBuffer.js @@ -6,7 +6,8 @@ * @param width {number} the width for the newly created canvas * @param height {number} the height for the newly created canvas */ -function CanvasBuffer(width, height) { +function CanvasBuffer(width, height) +{ /** * The Canvas object that belongs to this CanvasBuffer. * @@ -36,10 +37,12 @@ * @memberof CanvasBuffer# */ width: { - get: function () { + get: function () + { return this.canvas.width; }, - set: function (val) { + set: function (val) + { this.canvas.width = val; } }, @@ -50,10 +53,12 @@ * @memberof CanvasBuffer# */ height: { - get: function () { + get: function () + { return this.canvas.height; }, - set: function (val) { + set: function (val) + { this.canvas.height = val; } } @@ -64,7 +69,8 @@ * * @private */ -CanvasBuffer.prototype.clear = function () { +CanvasBuffer.prototype.clear = function () +{ this.context.setTransform(1, 0, 0, 1, 0, 0); this.context.clearRect(0,0, this.canvas.width, this.canvas.height); }; @@ -75,7 +81,8 @@ * @param width {number} the new width of the canvas * @param height {number} the new height of the canvas */ -CanvasBuffer.prototype.resize = function (width, height) { +CanvasBuffer.prototype.resize = function (width, height) +{ this.canvas.width = width; this.canvas.height = height; }; diff --git a/src/core/renderers/canvas/utils/CanvasGraphics.js b/src/core/renderers/canvas/utils/CanvasGraphics.js index c7eaa2a..3f2a91f 100644 --- a/src/core/renderers/canvas/utils/CanvasGraphics.js +++ b/src/core/renderers/canvas/utils/CanvasGraphics.js @@ -13,15 +13,18 @@ * @param graphics {Graphics} the actual graphics object to render * @param context {CanvasRenderingContext2D} the 2d drawing method of the canvas */ -CanvasGraphics.renderGraphics = function (graphics, context) { +CanvasGraphics.renderGraphics = function (graphics, context) +{ var worldAlpha = graphics.worldAlpha; - if (graphics.dirty) { + if (graphics.dirty) + { this.updateGraphicsTint(graphics); graphics.dirty = false; } - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; @@ -30,69 +33,82 @@ context.lineWidth = data.lineWidth; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { context.beginPath(); var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } - if (shape.closed) { + if (shape.closed) + { context.lineTo(points[0], points[1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fillRect(shape.x, shape.y, shape.width, shape.height); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.strokeRect(shape.x, shape.y, shape.width, shape.height); } } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.beginPath(); context.arc(shape.x, shape.y, shape.radius,0,2*Math.PI); context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas var w = shape.width * 2; @@ -119,18 +135,21 @@ context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; var width = shape.width; @@ -152,13 +171,15 @@ context.quadraticCurveTo(rx, ry, rx, ry + radius); context.closePath(); - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); @@ -174,45 +195,54 @@ * @param graphics {Graphics} the graphics which will be used as a mask * @param context {CanvasRenderingContext2D} the context 2d method of the canvas */ -CanvasGraphics.renderGraphicsMask = function (graphics, context) { +CanvasGraphics.renderGraphicsMask = function (graphics, context) +{ var len = graphics.graphicsData.length; - if (len === 0) { + if (len === 0) + { return; } context.beginPath(); - for (var i = 0; i < len; i++) { + for (var i = 0; i < len; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { context.rect(shape.x, shape.y, shape.width, shape.height); context.closePath(); } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.arc(shape.x, shape.y, shape.radius, 0, 2 * Math.PI); context.closePath(); } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas @@ -237,7 +267,8 @@ context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); context.closePath(); } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; @@ -262,8 +293,10 @@ } }; -CanvasGraphics.updateGraphicsTint = function (graphics) { - if (graphics.tint === 0xFFFFFF) { +CanvasGraphics.updateGraphicsTint = function (graphics) +{ + if (graphics.tint === 0xFFFFFF) + { return; } @@ -271,7 +304,8 @@ var tintG = (graphics.tint >> 8 & 0xFF) / 255; var tintB = (graphics.tint & 0xFF)/ 255; - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var fillColor = data.fillColor | 0; diff --git a/src/core/renderers/canvas/utils/CanvasMaskManager.js b/src/core/renderers/canvas/utils/CanvasMaskManager.js index e04a733..9827d36 100644 --- a/src/core/renderers/canvas/utils/CanvasMaskManager.js +++ b/src/core/renderers/canvas/utils/CanvasMaskManager.js @@ -6,7 +6,8 @@ * @class * @namespace PIXI */ -function CanvasMaskManager() {} +function CanvasMaskManager() +{} CanvasMaskManager.prototype.constructor = CanvasMaskManager; module.exports = CanvasMaskManager; @@ -17,7 +18,8 @@ * @param maskData {object} the maskData that will be pushed * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.pushMask = function (maskData, renderer) { +CanvasMaskManager.prototype.pushMask = function (maskData, renderer) +{ renderer.context.save(); var cacheAlpha = maskData.alpha; @@ -45,6 +47,7 @@ * * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.popMask = function (renderer) { +CanvasMaskManager.prototype.popMask = function (renderer) +{ renderer.context.restore(); }; diff --git a/src/core/renderers/canvas/utils/CanvasTinter.js b/src/core/renderers/canvas/utils/CanvasTinter.js index 17e0529..d2fb1bc 100644 --- a/src/core/renderers/canvas/utils/CanvasTinter.js +++ b/src/core/renderers/canvas/utils/CanvasTinter.js @@ -14,7 +14,8 @@ * @param color {number} the color to use to tint the sprite with * @return {HTMLCanvasElement} The tinted canvas */ -CanvasTinter.getTintedTexture = function (sprite, color) { +CanvasTinter.getTintedTexture = function (sprite, color) +{ var texture = sprite.texture; color = CanvasTinter.roundColor(color); @@ -23,7 +24,8 @@ texture.tintCache = texture.tintCache || {}; - if (texture.tintCache[stringColor]) { + if (texture.tintCache[stringColor]) + { return texture.tintCache[stringColor]; } @@ -33,14 +35,16 @@ //CanvasTinter.tintWithPerPixel(texture, stringColor, canvas); CanvasTinter.tintMethod(texture, color, canvas); - if (CanvasTinter.convertTintToImage) { + if (CanvasTinter.convertTintToImage) + { // is this better? var tintImage = new Image(); tintImage.src = canvas.toDataURL(); texture.tintCache[stringColor] = tintImage; } - else { + else + { texture.tintCache[stringColor] = canvas; // if we are not converting the texture to an image then we need to lose the reference to the canvas CanvasTinter.canvas = null; @@ -56,7 +60,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithMultiply = function (texture, color, canvas) { +CanvasTinter.tintWithMultiply = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -104,7 +109,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithOverlay = function (texture, color, canvas) { +CanvasTinter.tintWithOverlay = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -139,7 +145,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithPerPixel = function (texture, color, canvas) { +CanvasTinter.tintWithPerPixel = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -167,7 +174,8 @@ var pixels = pixelData.data; - for (var i = 0; i < pixels.length; i += 4) { + for (var i = 0; i < pixels.length; i += 4) + { pixels[i+0] *= r; pixels[i+1] *= g; pixels[i+2] *= b; @@ -181,7 +189,8 @@ * * @param color {number} the color to round, should be a hex color */ -CanvasTinter.roundColor = function (color) { +CanvasTinter.roundColor = function (color) +{ var step = CanvasTinter.cacheStepsPerColorChannel; var rgbValues = utils.hex2rgb(color); diff --git a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js index 9f2f89a..35edbaf 100644 --- a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js +++ b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLBlendModeManager(renderer) { +function WebGLBlendModeManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -23,8 +24,10 @@ * * @param blendMode {number} the blendMode, should be a Pixi const, such as BlendModes.ADD */ -WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) { - if (this.currentBlendMode === blendMode) { +WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) +{ + if (this.currentBlendMode === blendMode) + { return false; } diff --git a/src/core/renderers/webgl/managers/WebGLFilterManager.js b/src/core/renderers/webgl/managers/WebGLFilterManager.js index 1179258..2dac048 100644 --- a/src/core/renderers/webgl/managers/WebGLFilterManager.js +++ b/src/core/renderers/webgl/managers/WebGLFilterManager.js @@ -7,7 +7,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLFilterManager(renderer) { +function WebGLFilterManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -32,7 +33,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.texturePool.length = 0; self.initShaderBuffers(); }); @@ -46,7 +48,8 @@ * @param renderer {WebGLRenderer} * @param buffer {ArrayBuffer} */ -WebGLFilterManager.prototype.begin = function (buffer) { +WebGLFilterManager.prototype.begin = function (buffer) +{ this.defaultShader = this.renderer.shaderManager.defaultShader; this.width = this.renderer.projection.x * 2; @@ -60,7 +63,8 @@ * * @param filterBlock {object} the filter that will be pushed to the current filter stack */ -WebGLFilterManager.prototype.pushFilter = function (filterBlock) { +WebGLFilterManager.prototype.pushFilter = function (filterBlock) +{ var gl = this.renderer.gl; var projection = this.renderer.projection; @@ -78,10 +82,12 @@ this.offsetY += filterBlock._filterArea.y; var texture = this.texturePool.pop(); - if (!texture) { + if (!texture) + { texture = new FilterTexture(this.renderer.gl, this.width, this.height); } - else { + else + { texture.resize(this.width, this.height); } @@ -98,29 +104,35 @@ var localX = filterArea.x, localY = filterArea.y; - if (filterArea.x < 0) { + if (filterArea.x < 0) + { filterArea.width += filterArea.x; filterArea.x = 0; } - if (filterArea.y < 0) { + if (filterArea.y < 0) + { filterArea.height += filterArea.y; filterArea.y = 0; } - if (localX + filterArea.width > this.width) { + if (localX + filterArea.width > this.width) + { filterArea.width = this.width - localX; } - if (localY + filterArea.height > this.height) { + if (localY + filterArea.height > this.height) + { filterArea.height = this.height - localY; } - if (filterArea.width < 0) { + if (filterArea.width < 0) + { filterArea.width = 0; } - if (filterArea.height < 0) { + if (filterArea.height < 0) + { filterArea.height = 0; } @@ -154,7 +166,8 @@ * Removes the last filter from the filter stack and doesn't return it. * */ -WebGLFilterManager.prototype.popFilter = function () { +WebGLFilterManager.prototype.popFilter = function () +{ var gl = this.renderer.gl; var filterBlock = this.filterStack.pop(); @@ -163,7 +176,8 @@ var projection = this.renderer.projection; var offset = this.renderer.offset; - if (filterBlock.filterPasses.length > 1) { + if (filterBlock.filterPasses.length > 1) + { gl.viewport(0, 0, filterArea.width, filterArea.height); gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); @@ -193,7 +207,8 @@ var inputTexture = texture; var outputTexture = this.texturePool.pop(); - if (!outputTexture) { + if (!outputTexture) + { outputTexture = new FilterTexture(this.renderer.gl, this.width, this.height); } outputTexture.resize(this.width, this.height); @@ -204,7 +219,8 @@ gl.disable(gl.BLEND); - for (var i = 0; i < filterBlock.filterPasses.length-1; i++) { + for (var i = 0; i < filterBlock.filterPasses.length-1; i++) + { var filterPass = filterBlock.filterPasses[i]; gl.bindFramebuffer(gl.FRAMEBUFFER, outputTexture.frameBuffer ); @@ -243,10 +259,12 @@ var buffer = this.buffer; // time to render the filters texture to the previous scene - if (this.filterStack.length === 0) { + if (this.filterStack.length === 0) + { gl.colorMask(true, true, true, true);//this.transparent); } - else { + else + { var currentFilter = this.filterStack[this.filterStack.length-1]; filterArea = currentFilter._filterArea; @@ -332,13 +350,15 @@ * @param width {number} the horizontal range of the filter * @param height {number} the vertical range of the filter */ -WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) { +WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) +{ // use program var gl = this.renderer.gl; var shader = filter.shaders[gl.id]; - if (!shader) { + if (!shader) + { shader = new Shader(gl); shader.fragmentSrc = filter.fragmentSrc; @@ -356,7 +376,8 @@ gl.uniform2f(shader.projectionVector, width/2, -height/2); gl.uniform2f(shader.offsetVector, 0,0); - if (filter.uniforms.dimensions) { + 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]; @@ -386,7 +407,8 @@ * Initialises the shader buffers. * */ -WebGLFilterManager.prototype.initShaderBuffers = function () { +WebGLFilterManager.prototype.initShaderBuffers = function () +{ var gl = this.renderer.gl; // create some buffers @@ -432,7 +454,8 @@ * Destroys the filter and removes it from the filter stack. * */ -WebGLFilterManager.prototype.destroy = function () { +WebGLFilterManager.prototype.destroy = function () +{ var gl = this.renderer.gl; this.filterStack = null; @@ -441,7 +464,8 @@ this.offsetY = 0; // destroy textures - for (var i = 0; i < this.texturePool.length; i++) { + for (var i = 0; i < this.texturePool.length; i++) + { this.texturePool[i].destroy(); } diff --git a/src/core/renderers/webgl/managers/WebGLManager.js b/src/core/renderers/webgl/managers/WebGLManager.js index 9d47b5c..c30cd51 100644 --- a/src/core/renderers/webgl/managers/WebGLManager.js +++ b/src/core/renderers/webgl/managers/WebGLManager.js @@ -3,7 +3,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLManager(renderer) { +function WebGLManager(renderer) +{ /** * The renderer this manager works for. * @@ -15,6 +16,7 @@ WebGLManager.prototype.constructor = WebGLManager; module.exports = WebGLManager; -WebGLManager.prototype.destroy = function () { +WebGLManager.prototype.destroy = function () +{ this.renderer = null; }; diff --git a/src/core/renderers/webgl/managers/WebGLMaskManager.js b/src/core/renderers/webgl/managers/WebGLMaskManager.js index 2f90b64..e568812 100644 --- a/src/core/renderers/webgl/managers/WebGLMaskManager.js +++ b/src/core/renderers/webgl/managers/WebGLMaskManager.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLMaskManager(renderer) { +function WebGLMaskManager(renderer) +{ WebGLManager.call(this, renderer); } @@ -19,12 +20,15 @@ * * @param maskData {any[]} */ -WebGLMaskManager.prototype.pushMask = function (maskData) { - if (maskData.dirty) { +WebGLMaskManager.prototype.pushMask = function (maskData) +{ + if (maskData.dirty) + { WebGLGraphics.updateGraphics(maskData, this.renderer.gl); } - if (!maskData._webGL[this.renderer.gl.id].data.length) { + if (!maskData._webGL[this.renderer.gl.id].data.length) + { return; } @@ -36,6 +40,7 @@ * * @param maskData {any[]} */ -WebGLMaskManager.prototype.popMask = function (maskData) { +WebGLMaskManager.prototype.popMask = function (maskData) +{ this.renderer.stencilManager.popStencil(maskData, maskData._webGL[this.renderer.gl.id].data[0], this.renderer); }; diff --git a/src/core/renderers/webgl/managers/WebGLShaderManager.js b/src/core/renderers/webgl/managers/WebGLShaderManager.js index fef071c..90c6477 100644 --- a/src/core/renderers/webgl/managers/WebGLShaderManager.js +++ b/src/core/renderers/webgl/managers/WebGLShaderManager.js @@ -10,7 +10,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLShaderManager(renderer) { +function WebGLShaderManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -28,7 +29,8 @@ */ this.tempAttribState = []; - for (var i = 0; i < this.maxAttibs; i++) { + for (var i = 0; i < this.maxAttibs; i++) + { this.attribState[i] = false; } @@ -66,7 +68,8 @@ // listen for context and update necessary shaders var self = this; - this.renderer.on('context', function (event) { + this.renderer.on('context', function (event) + { var gl = event.data; // this shader is used for rendering primitives @@ -97,29 +100,36 @@ * * @param attribs {Array} attribs */ -WebGLShaderManager.prototype.setAttribs = function (attribs) { +WebGLShaderManager.prototype.setAttribs = function (attribs) +{ // reset temp state var i; - for (i = 0; i < this.tempAttribState.length; i++) { + for (i = 0; i < this.tempAttribState.length; i++) + { this.tempAttribState[i] = false; } // set the new attribs - for (var a in attribs) { + for (var a in attribs) + { this.tempAttribState[attribs[a]] = true; } var gl = this.renderer.gl; - for (i = 0; i < this.attribState.length; i++) { - if (this.attribState[i] !== this.tempAttribState[i]) { + for (i = 0; i < this.attribState.length; i++) + { + if (this.attribState[i] !== this.tempAttribState[i]) + { this.attribState[i] = this.tempAttribState[i]; - if (this.attribState[i]) { + if (this.attribState[i]) + { gl.enableVertexAttribArray(i); } - else { + else + { gl.disableVertexAttribArray(i); } } @@ -131,8 +141,10 @@ * * @param shader {Any} */ -WebGLShaderManager.prototype.setShader = function (shader) { - if (this._currentId === shader.uuid) { +WebGLShaderManager.prototype.setShader = function (shader) +{ + if (this._currentId === shader.uuid) + { return false; } @@ -150,7 +162,8 @@ * Destroys this object. * */ -WebGLShaderManager.prototype.destroy = function () { +WebGLShaderManager.prototype.destroy = function () +{ this.attribState = null; this.tempAttribState = null; diff --git a/src/core/renderers/webgl/managers/WebGLStencilManager.js b/src/core/renderers/webgl/managers/WebGLStencilManager.js index 9ec6398..4cb0134 100644 --- a/src/core/renderers/webgl/managers/WebGLStencilManager.js +++ b/src/core/renderers/webgl/managers/WebGLStencilManager.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLStencilManager(renderer) { +function WebGLStencilManager(renderer) +{ WebGLManager.call(this, renderer); this.stencilStack = []; @@ -24,12 +25,14 @@ * @param graphics {Graphics} * @param webGLData {any[]} */ -WebGLStencilManager.prototype.pushStencil = function (graphics, webGLData) { +WebGLStencilManager.prototype.pushStencil = function (graphics, webGLData) +{ var gl = this.renderer.gl; this.bindGraphics(graphics, webGLData, this.renderer); - if (this.stencilStack.length === 0) { + if (this.stencilStack.length === 0) + { gl.enable(gl.STENCIL_TEST); gl.clear(gl.STENCIL_BUFFER_BIT); this.reverse = true; @@ -47,14 +50,17 @@ // draw the triangle strip! - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } @@ -62,31 +68,38 @@ // draw a quad to increment.. gl.drawElements(gl.TRIANGLE_FAN, 4, gl.UNSIGNED_SHORT, ( webGLData.indices.length - 4 ) * 2 ); - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); } this.reverse = !this.reverse; } - else { - if (!this.reverse) { + else + { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } - else { + 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) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); } } @@ -103,7 +116,8 @@ * @param graphics {Graphics} * @param webGLData {Array} */ -WebGLStencilManager.prototype.bindGraphics = function (graphics, webGLData) { +WebGLStencilManager.prototype.bindGraphics = function (graphics, webGLData) +{ //if (this._currentGraphics === graphics)return; this._currentGraphics = graphics; @@ -114,7 +128,8 @@ offset = this.renderer.offset, shader;// = this.renderer.shaderManager.primitiveShader; - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { shader = this.renderer.shaderManager.complexPrimitiveShader; this.renderer.shaderManager.setShader(shader); @@ -141,7 +156,8 @@ // set the index buffer! gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, webGLData.indexBuffer); } - else { + else + { //this.renderer.shaderManager.activatePrimitiveShader(); shader = this.renderer.shaderManager.primitiveShader; this.renderer.shaderManager.setShader( shader ); @@ -154,7 +170,7 @@ gl.uniform2f(shader.uniforms.offsetVector._location, -offset.x, -offset.y); gl.uniform3fv(shader.uniforms.tint._location, utils.hex2rgb(graphics.tint)); - + gl.uniform1f(shader.uniforms.alpha._location, graphics.worldAlpha); @@ -172,19 +188,22 @@ * @param graphics {Graphics} * @param webGLData {Array} */ -WebGLStencilManager.prototype.popStencil = function (graphics, webGLData) { +WebGLStencilManager.prototype.popStencil = function (graphics, webGLData) +{ var gl = this.renderer.gl; this.stencilStack.pop(); this.count--; - if (this.stencilStack.length === 0) { + if (this.stencilStack.length === 0) + { // the stack is empty! gl.disable(gl.STENCIL_TEST); } - else { + else + { var level = this.count; @@ -192,14 +211,17 @@ gl.colorMask(false, false, false, false); - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { this.reverse = !this.reverse; - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } @@ -213,31 +235,38 @@ // draw the triangle strip! gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); - if (!this.reverse) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); } } - else { + else + { // console.log("<<>>") - if (!this.reverse) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } - else { + 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) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); } } @@ -253,7 +282,8 @@ * Destroys the mask stack. * */ -WebGLStencilManager.prototype.destroy = function () { +WebGLStencilManager.prototype.destroy = function () +{ this.renderer = null; this.stencilStack = null; }; diff --git a/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js b/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js index 913ba5e..1ea7d19 100644 --- a/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js +++ b/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function ComplexPrimitiveShader(gl) { +function ComplexPrimitiveShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -24,7 +25,8 @@ 'uniform float flipY;', 'varying vec4 vColor;', - 'void main(void) {', + '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);', @@ -37,7 +39,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = vColor;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/FastShader.js b/src/core/renderers/webgl/shaders/FastShader.js index bd2e29a..2e5e060 100644 --- a/src/core/renderers/webgl/shaders/FastShader.js +++ b/src/core/renderers/webgl/shaders/FastShader.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function FastShader(gl) { +function FastShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -28,7 +29,8 @@ 'const vec2 center = vec2(-1.0, 1.0);', - 'void main(void) {', + 'void main(void) + {', ' vec2 v;', ' vec2 sv = aVertexPosition * aScale;', ' v.x = (sv.x) * cos(aRotation) - (sv.y) * sin(aRotation);', @@ -49,7 +51,8 @@ 'uniform sampler2D uSampler;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/PrimitiveShader.js b/src/core/renderers/webgl/shaders/PrimitiveShader.js index 6f25409..a25f54f 100644 --- a/src/core/renderers/webgl/shaders/PrimitiveShader.js +++ b/src/core/renderers/webgl/shaders/PrimitiveShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function PrimitiveShader(gl) { +function PrimitiveShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -23,7 +24,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + '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);', @@ -36,7 +38,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = vColor;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/Shader.js b/src/core/renderers/webgl/shaders/Shader.js index f8964f5..fd75ef5 100644 --- a/src/core/renderers/webgl/shaders/Shader.js +++ b/src/core/renderers/webgl/shaders/Shader.js @@ -6,7 +6,8 @@ * @param [fragmentSrc] {string} The source of the fragment shader. * @param [vertexSrc] {string} The source of the vertex shader. */ -function Shader(gl, vertexSrc, fragmentSrc, customUniforms, customAttributes) { +function Shader(gl, vertexSrc, fragmentSrc, customUniforms, customAttributes) +{ /** * @member {number} * @readonly @@ -33,7 +34,8 @@ dimensions: { type: '4f', value: new Float32Array(4) } }; - for (var u in customUniforms) { + for (var u in customUniforms) + { this.uniforms[u] = customUniforms[u]; } @@ -43,7 +45,8 @@ aColor: 0 }; - for (var a in customAttributes) { + for (var a in customAttributes) + { this.attributes[a] = customAttributes[a]; } @@ -66,7 +69,8 @@ 'const vec2 center = vec2(-1.0, 1.0);', - 'void main(void) {', + 'void main(void) + {', ' gl_Position = vec4( ((aVertexPosition + offsetVector) / projectionVector) + center , 0.0, 1.0);', ' vTextureCoord = aTextureCoord;', ' vColor = vec4(aColor.rgb * aColor.a, aColor.a);', @@ -85,7 +89,8 @@ 'uniform sampler2D uSampler;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;', '}' ].join('\n'); @@ -96,7 +101,8 @@ Shader.prototype.constructor = Shader; module.exports = Shader; -Shader.prototype.init = function () { +Shader.prototype.init = function () +{ this.compile(); this.gl.useProgram(this.program); @@ -105,14 +111,18 @@ this.cacheAttributeLocations(Object.keys(this.attributes)); }; -Shader.prototype.cacheUniformLocations = function (keys) { - for (var i = 0; i < keys.length; ++i) { +Shader.prototype.cacheUniformLocations = function (keys) +{ + for (var i = 0; i < keys.length; ++i) + { this.uniforms[keys[i]]._location = this.gl.getUniformLocation(this.program, keys[i]); } }; -Shader.prototype.cacheAttributeLocations = function (keys) { - for (var i = 0; i < keys.length; ++i) { +Shader.prototype.cacheAttributeLocations = function (keys) +{ + for (var i = 0; i < keys.length; ++i) + { this.attributes[keys[i]] = this.gl.getAttribLocation(this.program, keys[i]); } @@ -124,14 +134,16 @@ // 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.attributes.aColor === -1) { + // if (this.attributes.aColor === -1) + { // this.attributes.aColor = 2; // } // End worst hack eva // }; -Shader.prototype.compile = function () { +Shader.prototype.compile = function () +{ var gl = this.gl; var glVertShader = this._glCompile(gl.VERTEX_SHADER, this.vertexSrc); @@ -144,13 +156,15 @@ gl.linkProgram(program); // if linking fails, then log and cleanup - if (!gl.getProgramParameter(program, gl.LINK_STATUS)) { + if (!gl.getProgramParameter(program, gl.LINK_STATUS)) + { window.console.error('Pixi.js Error: Could not initialize shader.'); window.console.error('gl.VALIDATE_STATUS', gl.getProgramParameter(program, gl.VALIDATE_STATUS)); window.console.error('gl.getError()', gl.getError()); // if there is a program info log, log it - if (gl.getProgramInfoLog(program) !== '') { + if (gl.getProgramInfoLog(program) !== '') + { window.console.warn('Pixi.js Warning: gl.getProgramInfoLog()', gl.getProgramInfoLog(program)); } @@ -165,18 +179,21 @@ return (this.program = program); }; -Shader.prototype.syncUniforms = function () { +Shader.prototype.syncUniforms = function () +{ var gl = this.gl; this.textureCount = 1; - for (var key in this.uniforms) { + for (var key in this.uniforms) + { var uniform = this.uniforms[key], location = uniform._location, value = uniform.value, i, il; - switch (uniform.type) { + switch (uniform.type) + { // single int value case 'i': case '1i': @@ -282,7 +299,8 @@ // a Color Value case 'c': - if (typeof value === 'number') { + if (typeof value === 'number') + { value = utils.hex2rgb(value); } @@ -311,11 +329,13 @@ // array of 2D Point objects case 'v2v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(2 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 2] = value[i].x; uniform._array[i * 2 + 1] = value[i].y; } @@ -325,11 +345,13 @@ // array of 3D Point objects case 'v3v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(3 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 3] = value[i].x; uniform._array[i * 3 + 1] = value[i].y; uniform._array[i * 3 + 2] = value[i].z; @@ -341,11 +363,13 @@ // array of 4D Point objects case 'v4v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(4 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 4] = value[i].x; uniform._array[i * 4 + 1] = value[i].y; uniform._array[i * 4 + 2] = value[i].z; @@ -359,7 +383,8 @@ // PIXI.Texture case 't': case 'sampler2D': - if (!uniform.value || !uniform.value.baseTexture || !uniform.value.baseTexture.hasLoaded) { + if (!uniform.value || !uniform.value.baseTexture || !uniform.value.baseTexture.hasLoaded) + { break; } @@ -376,7 +401,8 @@ this.textureCount++; // initialize the texture if we haven't yet - if (!uniform._init) { + if (!uniform._init) + { this.initSampler2D(uniform); uniform._init = true; @@ -394,11 +420,13 @@ * Initialises a Sampler2D uniform (which may only be available later on after initUniforms once the texture has loaded) * */ -Shader.prototype.initSampler2D = function (uniform) { +Shader.prototype.initSampler2D = function (uniform) +{ var gl = this.gl; // Extended texture data - if (uniform.textureData) { + if (uniform.textureData) + { var data = uniform.textureData; // GLTexture = mag linear, min linear_mipmap_linear, wrap repeat + gl.generateMipmap(gl.TEXTURE_2D); @@ -417,14 +445,16 @@ var wrapT = (data.wrapT) ? data.wrapT : gl.CLAMP_TO_EDGE; var format = (data.luminance) ? gl.LUMINANCE : gl.RGBA; - if (data.repeat) { + if (data.repeat) + { wrapS = gl.REPEAT; wrapT = gl.REPEAT; } gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, !!data.flipY); - if (data.width) { + if (data.width) + { var width = (data.width) ? data.width : 512; var height = (data.height) ? data.height : 2; var border = (data.border) ? data.border : 0; @@ -432,7 +462,8 @@ // 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 { + 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); } @@ -448,7 +479,8 @@ * Destroys the shader. * */ -Shader.prototype.destroy = function () { +Shader.prototype.destroy = function () +{ this.gl.deleteProgram(this.program); this.gl = null; @@ -459,13 +491,15 @@ this.fragmentSrc = null; }; -Shader.prototype._glCompile = function (type, src) { +Shader.prototype._glCompile = function (type, src) +{ var shader = this.gl.createShader(type); this.gl.shaderSource(shader, src); this.gl.compileShader(shader); - if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) { + if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) + { window.console.log(this.gl.getShaderInfoLog(shader)); return null; } diff --git a/src/core/renderers/webgl/shaders/StripShader.js b/src/core/renderers/webgl/shaders/StripShader.js index 193f6e1..a7abcc6 100644 --- a/src/core/renderers/webgl/shaders/StripShader.js +++ b/src/core/renderers/webgl/shaders/StripShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function StripShader(gl) { +function StripShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -20,7 +21,8 @@ 'varying vec2 vTextureCoord;', - 'void main(void) {', + '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);', @@ -36,7 +38,8 @@ 'varying vec2 vTextureCoord;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vec2(vTextureCoord.x, vTextureCoord.y)) * alpha;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/utils/FilterTexture.js b/src/core/renderers/webgl/utils/FilterTexture.js index d2c8423..4433d44 100644 --- a/src/core/renderers/webgl/utils/FilterTexture.js +++ b/src/core/renderers/webgl/utils/FilterTexture.js @@ -8,7 +8,8 @@ * @param height {number} the vertical range of the filter * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values */ -function FilterTexture(gl, width, height, scaleMode) { +function FilterTexture(gl, width, height, scaleMode) +{ /** * @member {WebGLContext} */ @@ -59,7 +60,8 @@ * Clears the filter texture. * */ -FilterTexture.prototype.clear = function () { +FilterTexture.prototype.clear = function () +{ var gl = this.gl; gl.clearColor(0,0,0, 0); @@ -72,8 +74,10 @@ * @param width {number} the new width of the texture * @param height {number} the new height of the texture */ -FilterTexture.prototype.resize = function (width, height) { - if (this.width === width && this.height === height) { +FilterTexture.prototype.resize = function (width, height) +{ + if (this.width === width && this.height === height) + { return; } @@ -96,7 +100,8 @@ * Destroys the filter texture. * */ -FilterTexture.prototype.destroy = function () { +FilterTexture.prototype.destroy = function () +{ var gl = this.gl; gl.deleteFramebuffer( this.frameBuffer ); gl.deleteTexture( this.texture ); diff --git a/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js b/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js index c4721e9..a63f4d7 100644 --- a/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js +++ b/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js @@ -14,7 +14,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this sprite batch works for. */ -function WebGLFastSpriteBatch(renderer) { +function WebGLFastSpriteBatch(renderer) +{ /** * The renderer instance this sprite batch operates on. * @@ -91,7 +92,8 @@ */ this.lastIndexCount = 0; - for (var i=0, j=0; i < numIndices; i += 6, j += 4) { + 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; @@ -144,7 +146,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.setupContext(); }); } @@ -157,7 +160,8 @@ * * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLFastSpriteBatch.prototype.setupContext = function () { +WebGLFastSpriteBatch.prototype.setupContext = function () +{ var gl = this.renderer.gl; // create a couple of buffers @@ -177,7 +181,8 @@ /** * @param spriteBatch {SpriteBatch} The SpriteBatch container to prepare for. */ -WebGLFastSpriteBatch.prototype.begin = function (spriteBatch) { +WebGLFastSpriteBatch.prototype.begin = function (spriteBatch) +{ this.shader = this.renderer.shaderManager.fastShader; this.matrix = spriteBatch.worldTransform.toArray(true); @@ -187,33 +192,38 @@ /** */ -WebGLFastSpriteBatch.prototype.end = function () { +WebGLFastSpriteBatch.prototype.end = function () +{ this.flush(); }; /** * @param spriteBatch {SpriteBatch} The SpriteBatch container to render. */ -WebGLFastSpriteBatch.prototype.render = function (spriteBatch) { +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) { + if (!sprite.texture._uvs) + { return; } this.currentBaseTexture = sprite.texture.baseTexture; // check blend mode - if (sprite.blendMode !== this.renderer.blendModeManager.currentBlendMode) { + if (sprite.blendMode !== this.renderer.blendModeManager.currentBlendMode) + { this.flush(); this.renderer.blendModeManager.setBlendMode(sprite.blendMode); } - for (var i=0,j= children.length; i= this.size) { + if (this.currentBatchSize >= this.size) + { this.flush(); } }; @@ -362,29 +379,35 @@ /** * */ -WebGLFastSpriteBatch.prototype.flush = function () { +WebGLFastSpriteBatch.prototype.flush = function () +{ // If the batch is length 0 then return as there is nothing to draw - if (this.currentBatchSize === 0) { + if (this.currentBatchSize === 0) + { return; } var gl = this.renderer.gl; // bind the current texture - if (!this.currentBaseTexture._glTextures[gl.id]) { + if (!this.currentBaseTexture._glTextures[gl.id]) + { this.renderer.updateTexture(this.currentBaseTexture, gl); } //TODO-SHOUD THIS BE ELSE??!?!?! - else { + else + { gl.bindTexture(gl.TEXTURE_2D, this.currentBaseTexture._glTextures[gl.id]); } // upload the verts to the buffer - if (this.currentBatchSize > ( this.size * 0.5 ) ) { + if (this.currentBatchSize > ( this.size * 0.5 ) ) + { gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); } - else { + else + { var view = this.vertices.subarray(0, this.currentBatchSize * this.vertByteSize); gl.bufferSubData(gl.ARRAY_BUFFER, 0, view); @@ -405,14 +428,16 @@ * Ends the batch and flushes * */ -WebGLFastSpriteBatch.prototype.stop = function () { +WebGLFastSpriteBatch.prototype.stop = function () +{ this.flush(); }; /** * */ -WebGLFastSpriteBatch.prototype.start = function () { +WebGLFastSpriteBatch.prototype.start = function () +{ var gl = this.renderer.gl; // bind the main texture diff --git a/src/core/renderers/webgl/utils/WebGLGraphics.js b/src/core/renderers/webgl/utils/WebGLGraphics.js index 55f4911..ab8f46e 100644 --- a/src/core/renderers/webgl/utils/WebGLGraphics.js +++ b/src/core/renderers/webgl/utils/WebGLGraphics.js @@ -19,7 +19,8 @@ * @param graphics {Graphics} * @param renderer {WebGLRenderer} */ -WebGLGraphics.renderGraphics = function (graphics, renderer) {//projection, offset) { +WebGLGraphics.renderGraphics = function (graphics, renderer) {//projection, offset) +{ var gl = renderer.gl; var projection = renderer.projection, @@ -27,7 +28,8 @@ shader = renderer.shaderManager.primitiveShader, webGLData; - if (graphics.dirty) { + if (graphics.dirty) + { WebGLGraphics.updateGraphics(graphics, gl); } @@ -35,8 +37,10 @@ // This could be speeded up for sure! - for (var i = 0; i < webGL.data.length; i++) { - if (webGL.data[i].mode === 1) { + for (var i = 0; i < webGL.data.length; i++) + { + if (webGL.data[i].mode === 1) + { webGLData = webGL.data[i]; renderer.stencilManager.pushStencil(graphics, webGLData, renderer); @@ -46,7 +50,8 @@ renderer.stencilManager.popStencil(graphics, webGLData, renderer); } - else { + else + { webGLData = webGL.data[i]; @@ -84,12 +89,14 @@ * @param graphicsData {Graphics} The graphics object to update * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLGraphics.updateGraphics = function (graphics, gl) { +WebGLGraphics.updateGraphics = function (graphics, gl) +{ // get the contexts graphics object var webGL = graphics._webGL[gl.id]; // if the graphics object does not exist in the webGL context time to create it! - if (!webGL) { + if (!webGL) + { webGL = graphics._webGL[gl.id] = {lastIndex:0, data:[], gl:gl}; } @@ -99,11 +106,13 @@ var i; // if the user cleared the graphics object we will need to clear every object - if (graphics.clearDirty) { + if (graphics.clearDirty) + { graphics.clearDirty = false; // lop through and return all the webGLDatas to the object pool so than can be reused later on - for (i = 0; i < webGL.data.length; i++) { + for (i = 0; i < webGL.data.length; i++) + { var graphicsData = webGL.data[i]; graphicsData.reset(); WebGLGraphics.graphicsDataPool.push( graphicsData ); @@ -119,58 +128,72 @@ // loop through the graphics datas and construct each one.. // if the object is a complex fill then the new stencil buffer technique will be used // other wise graphics objects will be pushed into a batch.. - for (i = webGL.lastIndex; i < graphics.graphicsData.length; i++) { + for (i = webGL.lastIndex; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { // need to add the points the the graphics object.. data.points = data.shape.points.slice(); - if (data.shape.closed) { + if (data.shape.closed) + { // close the poly if the value is true! - if (data.points[0] !== data.points[data.points.length-2] || data.points[1] !== data.points[data.points.length-1]) { + if (data.points[0] !== data.points[data.points.length-2] || data.points[1] !== data.points[data.points.length-1]) + { data.points.push(data.points[0], data.points[1]); } } // MAKE SURE WE HAVE THE CORRECT TYPE.. - if (data.fill) { - if (data.points.length >= 6) { - if (data.points.length < 6 * 2) { + if (data.fill) + { + if (data.points.length >= 6) + { + if (data.points.length < 6 * 2) + { webGLData = WebGLGraphics.switchMode(webGL, 0); var canDrawUsingSimple = WebGLGraphics.buildPoly(data, webGLData); // console.log(canDrawUsingSimple); - if (!canDrawUsingSimple) { + if (!canDrawUsingSimple) + { // console.log("<>>>") webGLData = WebGLGraphics.switchMode(webGL, 1); WebGLGraphics.buildComplexPoly(data, webGLData); } } - else { + else + { webGLData = WebGLGraphics.switchMode(webGL, 1); WebGLGraphics.buildComplexPoly(data, webGLData); } } } - if (data.lineWidth > 0) { + if (data.lineWidth > 0) + { webGLData = WebGLGraphics.switchMode(webGL, 0); WebGLGraphics.buildLine(data, webGLData); } } - else { + else + { webGLData = WebGLGraphics.switchMode(webGL, 0); - if (data.type === CONST.SHAPES.RECT) { + if (data.type === CONST.SHAPES.RECT) + { WebGLGraphics.buildRectangle(data, webGLData); } - else if (data.type === CONST.SHAPES.CIRC || data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.CIRC || data.type === CONST.SHAPES.ELIP) + { WebGLGraphics.buildCircle(data, webGLData); } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { WebGLGraphics.buildRoundedRectangle(data, webGLData); } } @@ -179,10 +202,12 @@ } // upload all the dirty data... - for (i = 0; i < webGL.data.length; i++) { + for (i = 0; i < webGL.data.length; i++) + { webGLData = webGL.data[i]; - if (webGLData.dirty) { + if (webGLData.dirty) + { webGLData.upload(); } } @@ -194,18 +219,22 @@ * @param webGL {WebGLContext} * @param type {number} */ -WebGLGraphics.switchMode = function (webGL, type) { +WebGLGraphics.switchMode = function (webGL, type) +{ var webGLData; - if (!webGL.data.length) { + if (!webGL.data.length) + { webGLData = WebGLGraphics.graphicsDataPool.pop() || new WebGLGraphicsData(webGL.gl); webGLData.mode = type; webGL.data.push(webGLData); } - else { + else + { webGLData = webGL.data[webGL.data.length-1]; - if (webGLData.mode !== type || type === 1) { + if (webGLData.mode !== type || type === 1) + { webGLData = WebGLGraphics.graphicsDataPool.pop() || new WebGLGraphicsData(webGL.gl); webGLData.mode = type; webGL.data.push(webGLData); @@ -225,7 +254,8 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildRectangle = function (graphicsData, webGLData) { +WebGLGraphics.buildRectangle = function (graphicsData, webGLData) +{ // --- // // need to convert points to a nice regular data // @@ -235,7 +265,8 @@ var width = rectData.width; var height = rectData.height; - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -265,7 +296,8 @@ indices.push(vertPos, vertPos, vertPos+1, vertPos+2, vertPos+3, vertPos+3); } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = [x, y, @@ -289,7 +321,8 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildRoundedRectangle = function (graphicsData, webGLData) { +WebGLGraphics.buildRoundedRectangle = function (graphicsData, webGLData) +{ var rrectData = graphicsData.shape; var x = rrectData.x; var y = rrectData.y; @@ -305,7 +338,8 @@ recPoints = recPoints.concat(WebGLGraphics.quadraticBezierCurve(x + width, y + radius, x + width, y, x + width - radius, y)); recPoints = recPoints.concat(WebGLGraphics.quadraticBezierCurve(x + radius, y, x, y, x, y + radius)); - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -323,7 +357,8 @@ // var i = 0; - for (i = 0; i < triangles.length; i+=3) { + for (i = 0; i < triangles.length; i+=3) + { indices.push(triangles[i] + vecPos); indices.push(triangles[i] + vecPos); indices.push(triangles[i+1] + vecPos); @@ -332,12 +367,14 @@ } - for (i = 0; i < recPoints.length; i++) { + for (i = 0; i < recPoints.length; i++) + { verts.push(recPoints[i], recPoints[++i], r, g, b, alpha); } } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = recPoints; @@ -362,7 +399,8 @@ * @param toY {number} Destination point y * @return {number[]} */ -WebGLGraphics.quadraticBezierCurve = function (fromX, fromY, cpX, cpY, toX, toY) { +WebGLGraphics.quadraticBezierCurve = function (fromX, fromY, cpX, cpY, toX, toY) +{ var xa, ya, @@ -373,14 +411,16 @@ n = 20, points = []; - function getPt(n1 , n2, perc) { + function getPt(n1 , n2, perc) + { var diff = n2 - n1; return n1 + ( diff * perc ); } var j = 0; - for (var i = 0; i <= n; i++ ) { + for (var i = 0; i <= n; i++ ) + { j = i / n; // The Green Line @@ -406,7 +446,8 @@ * @param graphicsData {Graphics} The graphics object to draw * @param webGLData {object} */ -WebGLGraphics.buildCircle = function (graphicsData, webGLData) { +WebGLGraphics.buildCircle = function (graphicsData, webGLData) +{ // need to convert points to a nice regular data var circleData = graphicsData.shape; var x = circleData.x; @@ -415,11 +456,13 @@ var height; // TODO - bit hacky?? - if (graphicsData.type === CONST.SHAPES.CIRC) { + if (graphicsData.type === CONST.SHAPES.CIRC) + { width = circleData.radius; height = circleData.radius; } - else { + else + { width = circleData.width; height = circleData.height; } @@ -429,7 +472,8 @@ var i = 0; - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -444,7 +488,8 @@ indices.push(vecPos); - for (i = 0; i < totalSegs + 1 ; i++) { + for (i = 0; i < totalSegs + 1 ; i++) + { verts.push(x,y, r, g, b, alpha); verts.push(x + Math.sin(seg * i) * width, @@ -457,12 +502,14 @@ indices.push(vecPos-1); } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = []; - for (i = 0; i < totalSegs + 1; i++) { + for (i = 0; i < totalSegs + 1; i++) + { graphicsData.points.push(x + Math.sin(seg * i) * width, y + Math.cos(seg * i) * height); } @@ -481,18 +528,22 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildLine = function (graphicsData, webGLData) { +WebGLGraphics.buildLine = function (graphicsData, webGLData) +{ // TODO OPTIMISE! var i = 0; var points = graphicsData.points; - if (points.length === 0) { + if (points.length === 0) + { return; } // if the line width is an odd number add 0.5 to align to a whole pixel - if (graphicsData.lineWidth%2) { - for (i = 0; i < points.length; i++) { + if (graphicsData.lineWidth%2) + { + for (i = 0; i < points.length; i++) + { points[i] += 0.5; } } @@ -502,7 +553,8 @@ var lastPoint = new math.Point(points[points.length - 2], points[points.length - 1]); // if the first point is the last point - gonna have issues :) - if (firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) { + if (firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) + { // need to clone as we are going to slightly modify the shape.. points = points.slice(); @@ -562,7 +614,8 @@ verts.push(p1x + perpx , p1y + perpy, r, g, b, alpha); - for (i = 1; i < length-1; i++) { + for (i = 1; i < length-1; i++) + { p1x = points[(i-1)*2]; p1y = points[(i-1)*2 + 1]; @@ -599,7 +652,8 @@ denom = a1*b2 - a2*b1; - if (Math.abs(denom) < 0.1 ) { + if (Math.abs(denom) < 0.1 ) + { denom+=10.1; verts.push(p2x - perpx , p2y - perpy, @@ -618,7 +672,8 @@ pdist = (px -p2x) * (px -p2x) + (py -p2y) + (py -p2y); - if (pdist > 140 * 140) { + if (pdist > 140 * 140) + { perp3x = perpx - perp2x; perp3y = perpy - perp2y; @@ -639,7 +694,8 @@ indexCount++; } - else { + else + { verts.push(px , py); verts.push(r, g, b, alpha); @@ -672,7 +728,8 @@ indices.push(indexStart); - for (i = 0; i < indexCount; i++) { + for (i = 0; i < indexCount; i++) + { indices.push(indexStart++); } @@ -687,11 +744,13 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildComplexPoly = function (graphicsData, webGLData) { +WebGLGraphics.buildComplexPoly = function (graphicsData, webGLData) +{ //TODO - no need to copy this as it gets turned into a FLoat32Array anyways.. var points = graphicsData.points.slice(); - if (points.length < 6) { + if (points.length < 6) + { return; } @@ -711,7 +770,8 @@ var x,y; // get size.. - for (var i = 0; i < points.length; i+=2) { + for (var i = 0; i < points.length; i+=2) + { x = points[i]; y = points[i+1]; @@ -732,7 +792,8 @@ //TODO - this aint needed! var length = points.length / 2; - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { indices.push( i ); } @@ -746,10 +807,12 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildPoly = function (graphicsData, webGLData) { +WebGLGraphics.buildPoly = function (graphicsData, webGLData) +{ var points = graphicsData.points; - if (points.length < 6) { + if (points.length < 6) + { return; } // get first and last point.. figure out the middle! @@ -767,7 +830,8 @@ var triangles = utils.PolyK.Triangulate(points); - if (!triangles) { + if (!triangles) + { return false; } @@ -775,7 +839,8 @@ var i = 0; - for (i = 0; i < triangles.length; i+=3) { + for (i = 0; i < triangles.length; i+=3) + { indices.push(triangles[i] + vertPos); indices.push(triangles[i] + vertPos); indices.push(triangles[i+1] + vertPos); @@ -783,7 +848,8 @@ indices.push(triangles[i+2] + vertPos); } - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { verts.push(points[i * 2], points[i * 2 + 1], r, g, b, alpha); } diff --git a/src/core/renderers/webgl/utils/WebGLGraphicsData.js b/src/core/renderers/webgl/utils/WebGLGraphicsData.js index c56d05e..c739ba7 100644 --- a/src/core/renderers/webgl/utils/WebGLGraphicsData.js +++ b/src/core/renderers/webgl/utils/WebGLGraphicsData.js @@ -2,7 +2,8 @@ * @class * @private */ -function WebGLGraphicsData(gl) { +function WebGLGraphicsData(gl) +{ this.gl = gl; //TODO does this need to be split before uploding?? @@ -22,7 +23,8 @@ /** * */ -WebGLGraphicsData.prototype.reset = function () { +WebGLGraphicsData.prototype.reset = function () +{ this.points.length = 0; this.indices.length = 0; }; @@ -30,7 +32,8 @@ /** * */ -WebGLGraphicsData.prototype.upload = function () { +WebGLGraphicsData.prototype.upload = function () +{ var gl = this.gl; // this.lastIndex = graphics.graphicsData.length; diff --git a/src/core/renderers/webgl/utils/WebGLSpriteBatch.js b/src/core/renderers/webgl/utils/WebGLSpriteBatch.js index 96eaa52..55befbb 100644 --- a/src/core/renderers/webgl/utils/WebGLSpriteBatch.js +++ b/src/core/renderers/webgl/utils/WebGLSpriteBatch.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this sprite batch works for. */ -function WebGLSpriteBatch(renderer) { +function WebGLSpriteBatch(renderer) +{ /** * * @@ -88,7 +89,8 @@ */ this.lastIndexCount = 0; - for (var i=0, j=0; i < numIndices; i += 6, j += 4) { + 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; @@ -162,7 +164,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.setupContext(); }); } @@ -173,7 +176,8 @@ /** * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLSpriteBatch.prototype.setupContext = function () { +WebGLSpriteBatch.prototype.setupContext = function () +{ var gl = this.renderer.gl; // setup default shader @@ -198,7 +202,8 @@ /** * */ -WebGLSpriteBatch.prototype.begin = function () { +WebGLSpriteBatch.prototype.begin = function () +{ // this.shader = this.renderer.shaderManager.defaultShader; this.start(); @@ -206,19 +211,22 @@ /** */ -WebGLSpriteBatch.prototype.end = function () { +WebGLSpriteBatch.prototype.end = function () +{ this.flush(); }; /** * @param sprite {Sprite} the sprite to render when using this spritebatch */ -WebGLSpriteBatch.prototype.render = function (sprite) { +WebGLSpriteBatch.prototype.render = function (sprite) +{ var texture = sprite.texture; //TODO set blend modes.. // check texture.. - if (this.currentBatchSize >= this.size) { + if (this.currentBatchSize >= this.size) + { this.flush(); this.currentBaseTexture = texture.baseTexture; } @@ -227,7 +235,8 @@ var uvs = texture._uvs; // if the uvs have not updated then no point rendering just yet! - if (!uvs) { + if (!uvs) + { return; } @@ -237,7 +246,8 @@ var w0, w1, h0, h1; - if (texture.trim) { + 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; @@ -248,7 +258,8 @@ h0 = h1 + texture.crop.height; } - else { + else + { w0 = (texture.frame.width ) * (1-aX); w1 = (texture.frame.width ) * -aX; @@ -272,7 +283,8 @@ var colors = this.colors; var positions = this.positions; - if (this.renderer.roundPixels) { + if (this.renderer.roundPixels) + { // xy positions[index] = a * w1 + c * h1 + tx | 0; positions[index+1] = d * h1 + b * w1 + ty | 0; @@ -289,7 +301,8 @@ positions[index+15] = a * w1 + c * h0 + tx | 0; positions[index+16] = d * h0 + b * w1 + ty | 0; } - else { + else + { // xy positions[index] = a * w1 + c * h1 + tx; positions[index+1] = d * h1 + b * w1 + ty; @@ -338,11 +351,13 @@ * * @param sprite {TilingSprite} the tilingSprite to render */ -WebGLSpriteBatch.prototype.renderTilingSprite = function (tilingSprite) { +WebGLSpriteBatch.prototype.renderTilingSprite = function (tilingSprite) +{ var texture = tilingSprite.tilingTexture; // check texture.. - if (this.currentBatchSize >= this.size) { + if (this.currentBatchSize >= this.size) + { //return; this.flush(); this.currentBaseTexture = texture.baseTexture; @@ -351,7 +366,8 @@ // set the textures uvs temporarily // TODO create a separate texture so that we can tile part of a texture - if (!tilingSprite._uvs) { + if (!tilingSprite._uvs) + { tilingSprite._uvs = new TextureUvs(); } @@ -454,16 +470,19 @@ * Renders the content and empties the current batch. * */ -WebGLSpriteBatch.prototype.flush = function () { +WebGLSpriteBatch.prototype.flush = function () +{ // If the batch is length 0 then return as there is nothing to draw - if (this.currentBatchSize === 0) { + if (this.currentBatchSize === 0) + { return; } var gl = this.renderer.gl; var shader; - if (this.dirty) { + if (this.dirty) + { this.dirty = false; // bind the main texture gl.activeTexture(gl.TEXTURE0); @@ -482,10 +501,12 @@ } // upload the verts to the buffer - if (this.currentBatchSize > ( this.size * 0.5 ) ) { + if (this.currentBatchSize > ( this.size * 0.5 ) ) + { gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); } - else { + else + { var view = this.positions.subarray(0, this.currentBatchSize * this.vertByteSize); gl.bufferSubData(gl.ARRAY_BUFFER, 0, view); } @@ -502,7 +523,8 @@ var shaderSwap = false; var sprite; - for (var i = 0, j = this.currentBatchSize; i < j; i++) { + for (var i = 0, j = this.currentBatchSize; i < j; i++) + { sprite = this.sprites[i]; @@ -513,24 +535,28 @@ blendSwap = currentBlendMode !== nextBlendMode; shaderSwap = currentShader !== nextShader; // should I use uuidS??? - if (currentBaseTexture !== nextTexture || blendSwap || shaderSwap) { + if (currentBaseTexture !== nextTexture || blendSwap || shaderSwap) + { this.renderBatch(currentBaseTexture, batchSize, start); start = i; batchSize = 0; currentBaseTexture = nextTexture; - if (blendSwap) { + if (blendSwap) + { currentBlendMode = nextBlendMode; this.renderer.blendModeManager.setBlendMode( currentBlendMode ); } - if (shaderSwap) { + if (shaderSwap) + { currentShader = nextShader; shader = currentShader.shaders ? currentShader.shaders[gl.id] : currentShader; - if (!shader) { + if (!shader) + { shader = new Shader(gl, null, currentShader.fragmentSrc, currentShader.uniforms); currentShader.shaders[gl.id] = shader; } @@ -538,7 +564,8 @@ // set shader function??? this.renderer.shaderManager.setShader(shader); - if (shader.dirty) { + if (shader.dirty) + { shader.syncUniforms(); } @@ -569,17 +596,21 @@ * @param size {number} * @param startIndex {number} */ -WebGLSpriteBatch.prototype.renderBatch = function (texture, size, startIndex) { - if (size === 0) { +WebGLSpriteBatch.prototype.renderBatch = function (texture, size, startIndex) +{ + if (size === 0) + { return; } var gl = this.renderer.gl; - if (!texture._glTextures[gl.id]) { + if (!texture._glTextures[gl.id]) + { this.renderer.updateTexture(texture); } - else { + else + { // bind the current texture gl.bindTexture(gl.TEXTURE_2D, texture._glTextures[gl.id]); } @@ -594,7 +625,8 @@ /** * */ -WebGLSpriteBatch.prototype.stop = function () { +WebGLSpriteBatch.prototype.stop = function () +{ this.flush(); this.dirty = true; }; @@ -602,7 +634,8 @@ /** * */ -WebGLSpriteBatch.prototype.start = function () { +WebGLSpriteBatch.prototype.start = function () +{ this.dirty = true; }; @@ -610,7 +643,8 @@ * Destroys the SpriteBatch. * */ -WebGLSpriteBatch.prototype.destroy = function () { +WebGLSpriteBatch.prototype.destroy = function () +{ this.renderer.gl.deleteBuffer(this.vertexBuffer); this.renderer.gl.deleteBuffer(this.indexBuffer); diff --git a/src/core/textures/BaseTexture.js b/src/core/textures/BaseTexture.js index 2bf77d4..513d358 100644 --- a/src/core/textures/BaseTexture.js +++ b/src/core/textures/BaseTexture.js @@ -10,7 +10,8 @@ * @param source {Image|Canvas} the source object of the texture. * @param [scaleMode=scaleModes.DEFAULT] {number} See {@link scaleModes} for possible values */ -function BaseTexture(source, scaleMode) { +function BaseTexture(source, scaleMode) +{ this.uuid = utils.uuid(); /** @@ -123,7 +124,8 @@ this._needsUpdate = false; // if no source passed don't try to load - if (source) { + if (source) + { this.loadSource(source); } @@ -149,13 +151,16 @@ Object.defineProperties(BaseTexture.prototype, { needsUpdate: { - get: function () { + get: function () + { return this._needsUpdate; }, - set: function (val) { + set: function (val) + { this._needsUpdate = val; - if (val) { + if (val) + { this.emit('update', this); } } @@ -171,9 +176,11 @@ * * The logic state after calling `loadSource` directly or indirectly (eg. `fromImage`, `new BaseTexture`) is: * - * if (texture.hasLoaded) { + * if (texture.hasLoaded) + { * // texture ready for use - * } else if (texture.isLoading) { + * } else if (texture.isLoading) + { * // listen to 'loaded' and/or 'error' events on texture * } else { * // not loading, not going to load UNLESS the source is reloaded @@ -183,12 +190,14 @@ * @protected * @param source {Image|Canvas} the source object of the texture. */ -BaseTexture.prototype.loadSource = function (source) { +BaseTexture.prototype.loadSource = function (source) +{ var wasLoading = this.isLoading; this.hasLoaded = false; this.isLoading = false; - if (wasLoading && this.source) { + if (wasLoading && this.source) + { this.source.onload = null; this.source.onerror = null; } @@ -196,20 +205,24 @@ this.source = source; // Apply source if loaded. Otherwise setup appropriate loading monitors. - if ((this.source.complete || this.source.getContext) && this.source.width && this.source.height) { + if ((this.source.complete || this.source.getContext) && this.source.width && this.source.height) + { this._sourceLoaded(); } - else if(!source.getContext) { + else if(!source.getContext) + { // Image fail / not ready this.isLoading = true; var scope = this; - source.onload = function () { + source.onload = function () + { source.onload = null; source.onerror = null; - if(!scope.isLoading) { + if(!scope.isLoading) + { return; } @@ -219,11 +232,13 @@ scope.emit('loaded', scope); }; - source.onerror = function () { + source.onerror = function () + { source.onload = null; source.onerror = null; - if(!scope.isLoading) { + if(!scope.isLoading) + { return; } @@ -234,24 +249,29 @@ // Per http://www.w3.org/TR/html5/embedded-content-0.html#the-img-element // "The value of `complete` can thus change while a script is executing." // So complete needs to be re-checked after the callbacks have been added.. - if (source.complete) { + if (source.complete) + { this.isLoading = false; // ..and if we're complete now, no need for callbacks source.onload = null; source.onerror = null; - if (source.width && source.height) { + if (source.width && source.height) + { this._sourceLoaded(); // If any previous subscribers possible - if (wasLoading) { + if (wasLoading) + { this.emit('loaded', this); } } - else { + else + { // If any previous subscribers possible - if (wasLoading) { + if (wasLoading) + { this.emit('error', this); } } @@ -265,7 +285,8 @@ * * @private */ -BaseTexture.prototype._sourceLoaded = function () { +BaseTexture.prototype._sourceLoaded = function () +{ this.hasLoaded = true; this.width = this.source.naturalWidth || this.source.width; @@ -278,16 +299,20 @@ * Destroys this base texture * */ -BaseTexture.prototype.destroy = function () { - if (this.imageUrl) { +BaseTexture.prototype.destroy = function () +{ + if (this.imageUrl) + { delete utils.BaseTextureCache[this.imageUrl]; delete utils.TextureCache[this.imageUrl]; this.imageUrl = null; - if (!navigator.isCocoonJS) { + if (!navigator.isCocoonJS) + { this.source.src = ''; } } - else if (this.source && this.source._pixiId) { + else if (this.source && this.source._pixiId) + { delete utils.BaseTextureCache[this.source._pixiId]; } this.source = null; @@ -301,7 +326,8 @@ * memory again. * */ -BaseTexture.prototype.dispose = function () { +BaseTexture.prototype.dispose = function () +{ this.emit('dispose', this); }; @@ -311,7 +337,8 @@ * * @param newSrc {string} the path of the image */ -BaseTexture.prototype.updateSourceImage = function (newSrc) { +BaseTexture.prototype.updateSourceImage = function (newSrc) +{ this.source.src = newSrc; this.loadSource(this.source); }; @@ -326,18 +353,22 @@ * @param [scaleMode=scaleModes.DEFAULT] {number} See {@link scaleModes} for possible values * @return BaseTexture */ -BaseTexture.fromImage = function (imageUrl, crossorigin, scaleMode) { +BaseTexture.fromImage = function (imageUrl, crossorigin, scaleMode) +{ var baseTexture = utils.BaseTextureCache[imageUrl]; - if (crossorigin === undefined && imageUrl.indexOf('data:') !== 0) { + if (crossorigin === undefined && imageUrl.indexOf('data:') !== 0) + { crossorigin = true; } - if (!baseTexture) { + if (!baseTexture) + { // new Image() breaks tex loading in some versions of Chrome. // See https://code.google.com/p/chromium/issues/detail?id=238071 var image = new Image();//document.createElement('img'); - if (crossorigin) { + if (crossorigin) + { image.crossOrigin = ''; } @@ -347,7 +378,8 @@ utils.BaseTextureCache[imageUrl] = baseTexture; // if there is an @2x at the end of the url we are going to assume its a highres image - if ( imageUrl.indexOf(CONST.RETINA_PREFIX + '.') !== -1) { + if ( imageUrl.indexOf(CONST.RETINA_PREFIX + '.') !== -1) + { baseTexture.resolution = 2; } } @@ -363,14 +395,17 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return BaseTexture */ -BaseTexture.fromCanvas = function (canvas, scaleMode) { - if (!canvas._pixiId) { +BaseTexture.fromCanvas = function (canvas, scaleMode) +{ + if (!canvas._pixiId) + { canvas._pixiId = 'canvas_' + utils.uuid(); } var baseTexture = utils.BaseTextureCache[canvas._pixiId]; - if (!baseTexture) { + if (!baseTexture) + { baseTexture = new BaseTexture(canvas, scaleMode); utils.BaseTextureCache[canvas._pixiId] = baseTexture; } diff --git a/src/core/textures/RenderTexture.js b/src/core/textures/RenderTexture.js index 6dad20f..53ae796 100644 --- a/src/core/textures/RenderTexture.js +++ b/src/core/textures/RenderTexture.js @@ -46,8 +46,10 @@ * @param [scaleMode] {number} See {@link scaleModes} for possible values * @param [resolution=1] {number} The resolution of the texture being generated */ -function RenderTexture(renderer, width, height, scaleMode, resolution) { - if (!renderer) { +function RenderTexture(renderer, width, height, scaleMode, resolution) +{ + if (!renderer) + { throw new Error('Unable to create RenderTexture, you must pass a renderer into the constructor.'); } @@ -133,7 +135,8 @@ */ this.renderer = renderer; - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { var gl = this.renderer.gl; this.textureBuffer = new FilterTexture(gl, this.width * this.resolution, this.height * this.resolution, this.baseTexture.scaleMode); @@ -142,7 +145,8 @@ this.render = this.renderWebGL; this.projection = new math.Point(this.width*0.5, -this.height*0.5); } - else { + else + { this.render = this.renderCanvas; this.textureBuffer = new CanvasBuffer(this.width* this.resolution, this.height* this.resolution); this.baseTexture.source = this.textureBuffer.canvas; @@ -167,8 +171,10 @@ * @param height {number} The height to resize to. * @param updateBase {boolean} Should the baseTexture.width and height values be resized as well? */ -RenderTexture.prototype.resize = function (width, height, updateBase) { - if (width === this.width && height === this.height) { +RenderTexture.prototype.resize = function (width, height, updateBase) +{ + if (width === this.width && height === this.height) + { return; } @@ -177,17 +183,20 @@ this.width = this.frame.width = this.crop.width = width; this.height = this.frame.height = this.crop.height = height; - if (updateBase) { + if (updateBase) + { this.baseTexture.width = this.width; this.baseTexture.height = this.height; } - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { this.projection.x = this.width / 2; this.projection.y = -this.height / 2; } - if (!this.valid) { + if (!this.valid) + { return; } @@ -198,12 +207,15 @@ * Clears the RenderTexture. * */ -RenderTexture.prototype.clear = function () { - if (!this.valid) { +RenderTexture.prototype.clear = function () +{ + if (!this.valid) + { return; } - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { this.renderer.gl.bindFramebuffer(this.renderer.gl.FRAMEBUFFER, this.textureBuffer.frameBuffer); } @@ -220,19 +232,23 @@ * @param [restoreWorldTransform=true] {boolean} If true the displayObject's worldTransform/worldAlpha and all children * transformations will be restored. Not restoring this information will be a little faster. */ -RenderTexture.prototype.renderWebGL = function (displayObject, matrix, clear, restoreWorldTransform) { - if (!this.valid) { +RenderTexture.prototype.renderWebGL = function (displayObject, matrix, clear, restoreWorldTransform) +{ + if (!this.valid) + { return; } - if (typeof restoreWorldTransform === 'undefined') { + if (typeof restoreWorldTransform === 'undefined') + { restoreWorldTransform = true; } var tempAlpha, tempTransform; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { tempAlpha = displayObject.worldAlpha; tempTransform = displayObject.worldTransform.toArray(); } @@ -245,7 +261,8 @@ wt.identity(); wt.translate(0, this.projection.y * 2); - if (matrix) { + if (matrix) + { wt.append(matrix); } @@ -258,7 +275,8 @@ var children = displayObject.children; var i, j; - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } @@ -269,7 +287,8 @@ gl.bindFramebuffer(gl.FRAMEBUFFER, this.textureBuffer.frameBuffer ); - if (clear) { + if (clear) + { this.textureBuffer.clear(); } @@ -279,11 +298,13 @@ this.renderer.spriteBatch.dirty = true; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { displayObject.worldAlpha = tempAlpha; displayObject.worldTransform.fromArray(tempTransform); - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } } @@ -300,26 +321,31 @@ * @param [restoreWorldTransform=true] {boolean} If true the displayObject's worldTransform/worldAlpha and all children * transformations will be restored. Not restoring this information will be a little faster. */ -RenderTexture.prototype.renderCanvas = function (displayObject, matrix, clear, restoreWorldTransform) { - if (!this.valid) { +RenderTexture.prototype.renderCanvas = function (displayObject, matrix, clear, restoreWorldTransform) +{ + if (!this.valid) + { return; } - if (typeof restoreWorldTransform === 'undefined') { + if (typeof restoreWorldTransform === 'undefined') + { restoreWorldTransform = true; } var tempAlpha, tempTransform; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { tempAlpha = displayObject.worldAlpha; tempTransform = displayObject.worldTransform.toArray(); } var wt = displayObject.worldTransform; wt.identity(); - if (matrix) { + if (matrix) + { wt.append(matrix); } @@ -330,11 +356,13 @@ var children = displayObject.children; var i, j; - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } - if (clear) { + if (clear) + { this.textureBuffer.clear(); } @@ -348,11 +376,13 @@ this.renderer.resolution = realResolution; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { displayObject.worldAlpha = tempAlpha; displayObject.worldTransform.fromArray(tempTransform); - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } } @@ -363,7 +393,8 @@ * * @return {Image} */ -RenderTexture.prototype.getImage = function () { +RenderTexture.prototype.getImage = function () +{ var image = new Image(); image.src = this.getBase64(); return image; @@ -374,7 +405,8 @@ * * @return {string} A base64 encoded string of the texture. */ -RenderTexture.prototype.getBase64 = function () { +RenderTexture.prototype.getBase64 = function () +{ return this.getCanvas().toDataURL(); }; @@ -383,8 +415,10 @@ * * @return {HTMLCanvasElement} A Canvas element with the texture rendered on. */ -RenderTexture.prototype.getCanvas = function () { - if (this.renderer.type === CONST.WEBGL_RENDERER) { +RenderTexture.prototype.getCanvas = function () +{ + if (this.renderer.type === CONST.WEBGL_RENDERER) + { var gl = this.renderer.gl; var width = this.textureBuffer.width; var height = this.textureBuffer.height; @@ -403,7 +437,8 @@ return tempCanvas.canvas; } - else { + else + { return this.textureBuffer.canvas; } }; diff --git a/src/core/textures/Texture.js b/src/core/textures/Texture.js index 3c65909..e97f0aa 100644 --- a/src/core/textures/Texture.js +++ b/src/core/textures/Texture.js @@ -17,7 +17,8 @@ * @param [crop] {Rectangle} The area of original texture * @param [trim] {Rectangle} Trimmed texture rectangle */ -function Texture(baseTexture, frame, crop, trim) { +function Texture(baseTexture, frame, crop, trim) +{ /** * Does this Texture have any frame data assigned to it? * @@ -25,12 +26,14 @@ */ this.noFrame = false; - if (!frame) { + if (!frame) + { this.noFrame = true; frame = new math.Rectangle(0, 0, 1, 1); } - if (baseTexture instanceof Texture) { + if (baseTexture instanceof Texture) + { baseTexture = baseTexture.baseTexture; } @@ -100,13 +103,16 @@ */ this.crop = crop || new math.Rectangle(0, 0, 1, 1); - if (baseTexture.hasLoaded) { - if (this.noFrame) { + if (baseTexture.hasLoaded) + { + if (this.noFrame) + { frame = new math.Rectangle(0, 0, baseTexture.width, baseTexture.height); } this.frame = frame; } - else { + else + { baseTexture.addEventListener('loaded', this.onBaseTextureLoaded.bind(this)); } } @@ -118,19 +124,23 @@ Object.defineProperties(Texture.prototype, { needsUpdate: { - get: function () { + get: function () + { return this.baseTexture.needsUpdate; }, - set: function (val) { + set: function (val) + { this.baseTexture.needsUpdate = val; } }, frame: { - get: function () { + get: function () + { return this._frame; }, - set: function (frame) { + set: function (frame) + { this._frame = frame; this.noFrame = false; @@ -143,20 +153,23 @@ 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 (!this.trim && (frame.x + frame.width > this.baseTexture.width || frame.y + frame.height > this.baseTexture.height)) + { throw new Error('Texture Error: frame does not fit inside the base Texture dimensions ' + this); } this.valid = frame && frame.width && frame.height && this.baseTexture.source && this.baseTexture.hasLoaded; - if (this.trim) { + 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) { + if (this.valid) + { this._updateUvs(); } } @@ -168,11 +181,13 @@ * * @private */ -Texture.prototype.onBaseTextureLoaded = function () { +Texture.prototype.onBaseTextureLoaded = function () +{ var baseTexture = this.baseTexture; baseTexture.removeEventListener('loaded', this.onLoaded); - if (this.noFrame) { + if (this.noFrame) + { this.frame = new math.Rectangle(0, 0, baseTexture.width, baseTexture.height); } @@ -184,8 +199,10 @@ * * @param destroyBase {boolean} Whether to destroy the base texture as well */ -Texture.prototype.destroy = function (destroyBase) { - if (destroyBase) { +Texture.prototype.destroy = function (destroyBase) +{ + if (destroyBase) + { this.baseTexture.destroy(); } @@ -197,8 +214,10 @@ * * @private */ -Texture.prototype._updateUvs = function () { - if (!this._uvs) { +Texture.prototype._updateUvs = function () +{ + if (!this._uvs) + { this._uvs = new TextureUvs(); } @@ -229,10 +248,12 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return Texture */ -Texture.fromImage = function (imageUrl, crossorigin, scaleMode) { +Texture.fromImage = function (imageUrl, crossorigin, scaleMode) +{ var texture = utils.TextureCache[imageUrl]; - if (!texture) { + if (!texture) + { texture = new Texture(BaseTexture.fromImage(imageUrl, crossorigin, scaleMode)); utils.TextureCache[imageUrl] = texture; } @@ -248,9 +269,11 @@ * @param frameId {string} The frame id of the texture * @return Texture */ -Texture.fromFrame = function (frameId) { +Texture.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache '); } return texture; @@ -264,7 +287,8 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return {Texture} */ -Texture.fromCanvas = function (canvas, scaleMode) { +Texture.fromCanvas = function (canvas, scaleMode) +{ return new Texture(BaseTexture.fromCanvas(canvas, scaleMode)); }; @@ -276,7 +300,8 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return {Texture} A Texture */ -Texture.fromVideo = function (video, scaleMode) { +Texture.fromVideo = function (video, scaleMode) +{ return new Texture(VideoBaseTexture.baseTextureFromVideo(video, scaleMode)); }; @@ -287,7 +312,8 @@ * @param texture {Texture} The Texture to add to the cache. * @param id {string} The id that the texture will be stored against. */ -Texture.addTextureToCache = function (texture, id) { +Texture.addTextureToCache = function (texture, id) +{ utils.TextureCache[id] = texture; }; @@ -298,7 +324,8 @@ * @param id {string} The id of the texture to be removed * @return {Texture} The texture that was removed */ -Texture.removeTextureFromCache = function (id) { +Texture.removeTextureFromCache = function (id) +{ var texture = utils.TextureCache[id]; delete utils.TextureCache[id]; diff --git a/src/core/textures/TextureUvs.js b/src/core/textures/TextureUvs.js index b9bbb58..5424d52 100644 --- a/src/core/textures/TextureUvs.js +++ b/src/core/textures/TextureUvs.js @@ -1,4 +1,5 @@ -function TextureUvs() { +function TextureUvs() +{ this.x0 = 0; this.y0 = 0; diff --git a/src/core/textures/VideoBaseTexture.js b/src/core/textures/VideoBaseTexture.js index e3e0c5a..1a826a9 100644 --- a/src/core/textures/VideoBaseTexture.js +++ b/src/core/textures/VideoBaseTexture.js @@ -12,15 +12,18 @@ * @param source {HTMLVideoElement} * @param [scaleMode] {number} See {@link scaleModes} for possible values */ -function VideoBaseTexture(source, scaleMode) { - if (!source){ +function VideoBaseTexture(source, scaleMode) +{ + if (!source) + { throw new Error('No video source element specified.'); } // hook in here to check if video is already available. // BaseTexture looks for a source.complete boolean, plus width & height. - if ((source.readyState === source.HAVE_ENOUGH_DATA || source.readyState === source.HAVE_FUTURE_DATA) && source.width && source.height) { + if ((source.readyState === source.HAVE_ENOUGH_DATA || source.readyState === source.HAVE_FUTURE_DATA) && source.width && source.height) + { source.complete = true; } @@ -31,7 +34,8 @@ this._boundOnUpdate = this._onUpdate.bind(this); this._boundOnCanPlay = this._onCanPlay.bind(this); - if (!source.complete) { + if (!source.complete) + { source.addEventListener('canplay', this._boundOnCanPlay); source.addEventListener('canplaythrough', this._boundOnCanPlay); @@ -47,28 +51,35 @@ VideoBaseTexture.prototype.constructor = VideoBaseTexture; module.exports = VideoBaseTexture; -VideoBaseTexture.prototype._onUpdate = function () { - if (this.autoUpdate) { +VideoBaseTexture.prototype._onUpdate = function () +{ + if (this.autoUpdate) + { window.requestAnimationFrame(this._boundOnUpdate); this.needsUpdate = true; } }; -VideoBaseTexture.prototype._onPlayStart = function () { - if (!this.autoUpdate) { +VideoBaseTexture.prototype._onPlayStart = function () +{ + if (!this.autoUpdate) + { window.requestAnimationFrame(this._boundOnUpdate); this.autoUpdate = true; } }; -VideoBaseTexture.prototype._onPlayStop = function () { +VideoBaseTexture.prototype._onPlayStop = function () +{ this.autoUpdate = false; }; -VideoBaseTexture.prototype._onCanPlay = function () { +VideoBaseTexture.prototype._onCanPlay = function () +{ this.hasLoaded = true; - if (this.source) { + if (this.source) + { this.source.removeEventListener('canplay', this._boundOnCanPlay); this.source.removeEventListener('canplaythrough', this._boundOnCanPlay); @@ -78,15 +89,18 @@ this.source.play(); // prevent multiple loaded dispatches.. - if(!this.__loaded){ + if(!this.__loaded) + { this.__loaded = true; this.emit('loaded', this); } } }; -VideoBaseTexture.prototype.destroy = function () { - if (this.source && this.source._pixiId) { +VideoBaseTexture.prototype.destroy = function () +{ + if (this.source && this.source._pixiId) + { utils.BaseTextureCache[ this.source._pixiId ] = null; delete utils.BaseTextureCache[ this.source._pixiId ]; @@ -105,14 +119,17 @@ * @param scaleMode {number} See {@link scaleModes} for possible values * @return {VideoBaseTexture} */ -VideoBaseTexture.fromVideo = function (video, scaleMode) { - if (!video._pixiId) { +VideoBaseTexture.fromVideo = function (video, scaleMode) +{ + if (!video._pixiId) + { video._pixiId = 'video_' + utils.uuid(); } var baseTexture = utils.BaseTextureCache[video._pixiId]; - if (!baseTexture) { + if (!baseTexture) + { baseTexture = new VideoBaseTexture(video, scaleMode); utils.BaseTextureCache[ video._pixiId ] = baseTexture; } @@ -147,17 +164,21 @@ * @param scaleMode {number} See {@link scaleModes} for possible values * @return {VideoBaseTexture} */ -VideoBaseTexture.fromUrl = function (videoSrc, scaleMode) { +VideoBaseTexture.fromUrl = function (videoSrc, scaleMode) +{ var video = document.createElement('video'); // array of objects or strings - if (Array.isArray(videoSrc)) { - for (var i = 0; i < videoSrc.length; ++i) { + if (Array.isArray(videoSrc)) + { + for (var i = 0; i < videoSrc.length; ++i) + { video.appendChild(createSource(videoSrc.src || videoSrc, videoSrc.mime)); } } // single object or string - else { + else + { video.appendChild(createSource(videoSrc.src || videoSrc, videoSrc.mime)); } @@ -169,8 +190,10 @@ VideoBaseTexture.fromUrls = VideoBaseTexture.fromUrl; -function createSource(path, type) { - if (!type) { +function createSource(path, type) +{ + if (!type) + { type = 'video/' + path.substr(path.lastIndexOf('.') + 1); } diff --git a/src/core/utils/EventData.js b/src/core/utils/EventData.js index 5d55a22..8cdf701 100644 --- a/src/core/utils/EventData.js +++ b/src/core/utils/EventData.js @@ -7,7 +7,8 @@ * @param name {string} The string name of the event that was triggered * @param data {object} Arbitrary event data to pass along */ -function EventData(target, name, data) { +function EventData(target, name, data) +{ // for duck typing in the ".on()" function this.__isEventObject = true; @@ -71,7 +72,8 @@ * Stops the propagation of events up the scene graph (prevents bubbling). * */ -EventData.prototype.stopPropagation = function stopPropagation() { +EventData.prototype.stopPropagation = function stopPropagation() +{ this.stopped = true; }; @@ -79,6 +81,7 @@ * Stops the propagation of events to sibling listeners (no longer calls any listeners). * */ -EventData.prototype.stopImmediatePropagation = function stopImmediatePropagation() { +EventData.prototype.stopImmediatePropagation = function stopImmediatePropagation() +{ this.stoppedImmediate = true; }; diff --git a/src/core/utils/EventTarget.js b/src/core/utils/EventTarget.js index 7ae8820..671a151 100644 --- a/src/core/utils/EventTarget.js +++ b/src/core/utils/EventTarget.js @@ -13,14 +13,16 @@ * var em = new MyEmitter(); * em.emit('eventName', 'some data', 'some more data', {}, null, ...); */ -function eventTarget(obj) { +function eventTarget(obj) +{ /** * Return a list of assigned event listeners. * * @param eventName {string} The events that should be listed. * @return {Array} An array of listener functions */ - obj.listeners = function listeners(eventName) { + obj.listeners = function listeners(eventName) + { this._listeners = this._listeners || {}; return this._listeners[eventName] ? this._listeners[eventName].slice() : []; @@ -33,22 +35,26 @@ * @param eventName {string} The name of the event. * @return {boolean} Indication if we've emitted an event. */ - obj.emit = obj.dispatchEvent = function emit(eventName, data) { + obj.emit = obj.dispatchEvent = function emit(eventName, data) + { this._listeners = this._listeners || {}; // fast return when there are no listeners - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return; } //backwards compat with old method ".emit({ type: 'something' })" - if (typeof eventName === 'object') { + if (typeof eventName === 'object') + { data = eventName; eventName = eventName.type; } //ensure we are using a real pixi event - if (!data || data.__isEventObject !== true) { + if (!data || data.__isEventObject !== true) + { data = new EventData(this, eventName, data); } @@ -58,23 +64,27 @@ fn = listeners[0], i; - for (i = 0; i < length; fn = listeners[++i]) { + for (i = 0; i < length; fn = listeners[++i]) + { //call the event listener fn.call(this, data); //if "stopImmediatePropagation" is called, stop calling sibling events - if (data.stoppedImmediate) { + if (data.stoppedImmediate) + { return this; } } //if "stopPropagation" is called then don't bubble the event - if (data.stopped) { + if (data.stopped) + { return this; } //bubble this event up the scene graph - if (this.parent && this.parent.emit) { + if (this.parent && this.parent.emit) + { this.parent.emit.call(this.parent, eventName, data); } @@ -88,7 +98,8 @@ * @param eventName {string} Name of the event. * @param callback {Functon} fn Callback function. */ - obj.on = obj.addEventListener = function on(eventName, fn) { + obj.on = obj.addEventListener = function on(eventName, fn) + { this._listeners = this._listeners || {}; (this._listeners[eventName] = this._listeners[eventName] || []) @@ -103,11 +114,13 @@ * @param eventName {string} Name of the event. * @param callback {Function} Callback function. */ - obj.once = function once(eventName, fn) { + obj.once = function once(eventName, fn) + { this._listeners = this._listeners || {}; var self = this; - function onceHandlerWrapper() { + function onceHandlerWrapper() + { fn.apply(self.off(eventName, onceHandlerWrapper), arguments); } onceHandlerWrapper._originalHandler = fn; @@ -122,23 +135,28 @@ * @param eventName {string} The event we want to remove. * @param callback {Function} The listener that we need to find. */ - obj.off = obj.removeEventListener = function off(eventName, fn) { + obj.off = obj.removeEventListener = function off(eventName, fn) + { this._listeners = this._listeners || {}; - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return this; } var list = this._listeners[eventName], i = fn ? list.length : 0; - while(i-- > 0) { - if (list[i] === fn || list[i]._originalHandler === fn) { + while(i-- > 0) + { + if (list[i] === fn || list[i]._originalHandler === fn) + { list.splice(i, 1); } } - if (list.length === 0) { + if (list.length === 0) + { delete this._listeners[eventName]; } @@ -150,10 +168,12 @@ * * @param eventName {string} The event you want to remove all listeners for. */ - obj.removeAllListeners = function removeAllListeners(eventName) { + obj.removeAllListeners = function removeAllListeners(eventName) + { this._listeners = this._listeners || {}; - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return this; } @@ -169,7 +189,8 @@ * * @param object {object} The obj to mix into */ - mixin: function mixin(obj) { + mixin: function mixin(obj) + { eventTarget(obj); } }; diff --git a/src/core/utils/PolyK.js b/src/core/utils/PolyK.js index 7325141..5e20c2b 100644 --- a/src/core/utils/PolyK.js +++ b/src/core/utils/PolyK.js @@ -47,7 +47,8 @@ * Triangulates shapes for webGL graphic fills. * */ -PolyK.Triangulate = function (p) { +PolyK.Triangulate = function (p) +{ var sign = true; var n = p.length >> 1; @@ -59,7 +60,8 @@ i = 0; var al = n; - while(al > 3) { + while(al > 3) + { var i0 = avl[(i+0)%al]; var i1 = avl[(i+1)%al]; var i2 = avl[(i+2)%al]; @@ -69,29 +71,35 @@ var cx = p[2*i2], cy = p[2*i2+1]; var earFound = false; - if (PolyK._convex(ax, ay, bx, by, cx, cy, sign)) { + if (PolyK._convex(ax, ay, bx, by, cx, cy, sign)) + { earFound = true; - for (var j = 0; j < al; j++) { + for (var j = 0; j < al; j++) + { var vi = avl[j]; if (vi === i0 || vi === i1 || vi === i2) continue; - if (PolyK._PointInTriangle(p[2*vi], p[2*vi+1], ax, ay, bx, by, cx, cy)) { + if (PolyK._PointInTriangle(p[2*vi], p[2*vi+1], ax, ay, bx, by, cx, cy)) + { earFound = false; break; } } } - if (earFound) { + if (earFound) + { tgs.push(i0, i1, i2); avl.splice((i+1)%al, 1); al--; i = 0; } - else if (i++ > 3*al) { + else if (i++ > 3*al) + { // need to flip flip reverse it! // reset! - if (sign) { + if (sign) + { tgs = []; avl = []; for (i = 0; i < n; i++) avl.push(i); @@ -101,7 +109,8 @@ sign = false; } - else { + else + { // window.console.log("PIXI Warning: shape too complex to fill"); return null; } @@ -126,7 +135,8 @@ * @private * @return {boolean} */ -PolyK._PointInTriangle = function (px, py, ax, ay, bx, by, cx, cy) { +PolyK._PointInTriangle = function (px, py, ax, ay, bx, by, cx, cy) +{ var v0x = cx-ax; var v0y = cy-ay; var v1x = bx-ax; @@ -154,6 +164,7 @@ * @private * @return {boolean} */ -PolyK._convex = function (ax, ay, bx, by, cx, cy, sign) { +PolyK._convex = function (ax, ay, bx, by, cx, cy, sign) +{ return ((ay-by)*(cx-bx) + (bx-ax)*(cy-by) >= 0) === sign; }; diff --git a/src/core/utils/index.js b/src/core/utils/index.js index ade9831..bfae7ae 100644 --- a/src/core/utils/index.js +++ b/src/core/utils/index.js @@ -16,7 +16,8 @@ * * @return {number} The next uuid to use. */ - uuid: function () { + uuid: function () + { return ++utils._uid; }, @@ -26,7 +27,8 @@ * @param hex {number} * @return {number[]} An array representing the [R, G, B] of the color. */ - hex2rgb: function (hex, out) { + hex2rgb: function (hex, out) + { out = out || []; out[0] = (hex >> 16 & 0xFF) / 255; @@ -42,7 +44,8 @@ * @param hex {number} * @return {string} The string color. */ - hex2string: function (hex) { + hex2string: function (hex) + { hex = hex.toString(16); hex = '000000'.substr(0, 6 - hex.length) + hex; @@ -55,7 +58,8 @@ * @param rgb {number[]} * @return {number} The color number */ - rgb2hex: function (rgb) { + rgb2hex: function (rgb) + { return ((rgb[0]*255 << 16) + (rgb[1]*255 << 8) + rgb[2]*255); }, @@ -64,8 +68,10 @@ * * @return {boolean} whether they are supported */ - canUseNewCanvasBlendModes: function () { - if (typeof document === 'undefined') { + canUseNewCanvasBlendModes: function () + { + if (typeof document === 'undefined') + { return false; } @@ -93,15 +99,19 @@ * @param number {number} * @return {number} the closest number that is a power of two */ - getNextPowerOfTwo: function (number) { + getNextPowerOfTwo: function (number) + { // see: http://en.wikipedia.org/wiki/Power_of_two#Fast_algorithm_to_check_if_a_positive_number_is_a_power_of_two - if (number > 0 && (number & (number - 1)) === 0) { + if (number > 0 && (number & (number - 1)) === 0) + { return number; } - else { + else + { var result = 1; - while (result < number) { + while (result < number) + { result <<= 1; } @@ -116,7 +126,8 @@ * @param height {number} * @return {boolean} */ - isPowerOfTwo: function (width, height) { + isPowerOfTwo: function (width, height) + { return (width > 0 && (width & (width - 1)) === 0 && height > 0 && (height & (height - 1)) === 0); }, @@ -130,12 +141,15 @@ * @constant * @static */ - sayHello: function (type) { - if (utils._saidHello) { + sayHello: function (type) + { + if (utils._saidHello) + { return; } - if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) { + if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) + { var args = [ '%c %c %c Pixi.js ' + CONST.VERSION + ' - ' + type + ' %c ' + ' %c ' + ' http://www.pixijs.com/ %c %c ♥%c♥%c♥ ', 'background: #ff66a5', @@ -151,7 +165,8 @@ console.log.apply(console, args); //jshint ignore:line } - else if (window.console) { + else if (window.console) + { console.log('Pixi.js ' + CONST.VERSION + ' - ' + type + ' - http://www.pixijs.com/'); //jshint ignore:line } @@ -166,15 +181,19 @@ * @class * @namespace PIXI */ - AjaxRequest: function () { + AjaxRequest: function () + { var activexmodes = ['Msxml2.XMLHTTP.6.0', 'Msxml2.XMLHTTP.3.0', 'Microsoft.XMLHTTP']; //activeX versions to check for in IE - if (window.ActiveXObject) { //Test for support for ActiveXObject in IE first (as XMLHttpRequest in IE7 is broken) - for (var i=0; i= this.textures.length) { + else if (round >= this.textures.length) + { this.gotoAndStop(this.textures.length - 1); - if (this.onComplete) { + if (this.onComplete) + { this.onComplete(); } } @@ -167,10 +182,12 @@ * @static * @param frames {string[]} the array of frames ids the movieclip will use as its texture frames */ -MovieClip.fromFrames = function (frames) { +MovieClip.fromFrames = function (frames) +{ var textures = []; - for (var i = 0; i < frames.length; ++i) { + for (var i = 0; i < frames.length; ++i) + { textures.push(new core.Texture.fromFrame(frames[i])); } @@ -183,10 +200,12 @@ * @static * @param images {string[]} the array of image urls the movieclip will use as its texture frames */ -MovieClip.fromImages = function (images) { +MovieClip.fromImages = function (images) +{ var textures = []; - for (var i = 0; i < images.length; ++i) { + for (var i = 0; i < images.length; ++i) + { textures.push(new core.Texture.fromImage(images[i])); } diff --git a/src/extras/Rope.js b/src/extras/Rope.js index c157ec4..9c87bc0 100644 --- a/src/extras/Rope.js +++ b/src/extras/Rope.js @@ -9,7 +9,8 @@ * @param {Array} points - An array of {Point}. * */ -function Rope(texture, points) { +function Rope(texture, points) +{ Strip.call(this, texture); this.points = points; @@ -31,10 +32,12 @@ * Refreshes * */ -Rope.prototype.refresh = function () { +Rope.prototype.refresh = function () +{ var points = this.points; - if (points.length < 1) { + if (points.length < 1) + { return; } @@ -59,20 +62,23 @@ var total = points.length, point, index, amount; - for (var i = 1; i < total; i++) { + for (var i = 1; i < total; i++) + { point = points[i]; index = i * 4; // time to do some smart drawing! amount = i / (total-1); - if (i%2) { + if (i%2) + { uvs[index] = amount; uvs[index+1] = 0; uvs[index+2] = amount; uvs[index+3] = 1; } - else { + else + { uvs[index] = amount; uvs[index+1] = 0; @@ -95,10 +101,12 @@ * * @private */ -Rope.prototype.updateTransform = function () { +Rope.prototype.updateTransform = function () +{ var points = this.points; - if (points.length < 1) { + if (points.length < 1) + { return; } @@ -113,14 +121,17 @@ var total = points.length, point, index, ratio, perpLength, num; - for (var i = 0; i < total; i++) { + for (var i = 0; i < total; i++) + { point = points[i]; index = i * 4; - if (i < points.length-1) { + if (i < points.length-1) + { nextPoint = points[i+1]; } - else { + else + { nextPoint = point; } @@ -129,7 +140,8 @@ ratio = (1 - (i / (total-1))) * 10; - if (ratio > 1) { + if (ratio > 1) + { ratio = 1; } @@ -157,7 +169,8 @@ * * @param texture {Texture} the texture that will be used */ -Rope.prototype.setTexture = function (texture) { +Rope.prototype.setTexture = function (texture) +{ // stop current texture this.texture = texture; //this.updateFrame = true; diff --git a/src/extras/Strip.js b/src/extras/Strip.js index c5e378f..57691b5 100644 --- a/src/extras/Strip.js +++ b/src/extras/Strip.js @@ -10,7 +10,8 @@ * @param height {number} the height * */ -function Strip(texture) { +function Strip(texture) +{ core.DisplayObjectContainer.call(this); /** @@ -70,9 +71,11 @@ * * @param renderer {WebGLRenderer} */ -Strip.prototype.renderWebGL = function (renderer) { +Strip.prototype.renderWebGL = function (renderer) +{ // if the sprite is not visible or the alpha is 0 then no need to render this element - if (!this.visible || this.alpha <= 0) { + if (!this.visible || this.alpha <= 0) + { return; } @@ -81,7 +84,8 @@ renderer.spriteBatch.stop(); // init! init! - if (!this._vertexBuffer) { + if (!this._vertexBuffer) + { this._initWebGL(renderer); } @@ -96,7 +100,8 @@ //TODO check culling }; -Strip.prototype._initWebGL = function (renderer) { +Strip.prototype._initWebGL = function (renderer) +{ // build the strip! var gl = renderer.gl; @@ -118,7 +123,8 @@ gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this.indices, gl.STATIC_DRAW); }; -Strip.prototype._renderStrip = function (renderer) { +Strip.prototype._renderStrip = function (renderer) +{ var gl = renderer.gl; var projection = renderer.projection, offset = renderer.offset, @@ -137,7 +143,8 @@ gl.uniform2f(shader.offsetVector, -offset.x, -offset.y); gl.uniform1f(shader.alpha, this.worldAlpha); - if (!this.dirty) { + if (!this.dirty) + { gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexBuffer); gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); @@ -150,10 +157,12 @@ gl.activeTexture(gl.TEXTURE0); // check if a texture is dirty.. - if (this.texture.baseTexture._dirty[gl.id]) { + if (this.texture.baseTexture._dirty[gl.id]) + { renderer.updateTexture(this.texture.baseTexture); } - else { + else + { // bind the current texture gl.bindTexture(gl.TEXTURE_2D, this.texture.baseTexture._glTextures[gl.id]); } @@ -163,7 +172,8 @@ } - else { + else + { this.dirty = false; gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexBuffer); @@ -178,10 +188,12 @@ gl.activeTexture(gl.TEXTURE0); // check if a texture is dirty.. - if (this.texture.baseTexture._dirty[gl.id]) { + if (this.texture.baseTexture._dirty[gl.id]) + { renderer.updateTexture(this.texture.baseTexture); } - else { + else + { gl.bindTexture(gl.TEXTURE_2D, this.texture.baseTexture._glTextures[gl.id]); } @@ -203,27 +215,33 @@ * * @param renderer {CanvasRenderer} */ -Strip.prototype.renderCanvas = function (renderer) { +Strip.prototype.renderCanvas = function (renderer) +{ var context = renderer.context; var transform = this.worldTransform; - if (renderer.roundPixels) { + if (renderer.roundPixels) + { context.setTransform(transform.a, transform.b, transform.c, transform.d, transform.tx | 0, transform.ty | 0); } - else { + else + { context.setTransform(transform.a, transform.b, transform.c, transform.d, transform.tx, transform.ty); } - if (this.drawMode === Strip.DrawModes.TRIANGLE_STRIP) { + if (this.drawMode === Strip.DrawModes.TRIANGLE_STRIP) + { this._renderCanvasTriangleStrip(context); } - else { + else + { this._renderCanvasTriangles(context); } }; -Strip.prototype._renderCanvasTriangleStrip = function (context) { +Strip.prototype._renderCanvasTriangleStrip = function (context) +{ // draw triangles!! var vertices = this.vertices; var uvs = this.uvs; @@ -231,14 +249,16 @@ var length = vertices.length / 2; // this.count++; - for (var i = 0; i < length - 2; i++) { + for (var i = 0; i < length - 2; i++) + { // draw some triangles! var index = i * 2; this._renderCanvasDrawTriangle(context, vertices, uvs, index, (index + 2), (index + 4)); } }; -Strip.prototype._renderCanvasTriangles = function (context) { +Strip.prototype._renderCanvasTriangles = function (context) +{ // draw triangles!! var vertices = this.vertices; var uvs = this.uvs; @@ -247,14 +267,16 @@ var length = indices.length; // this.count++; - for (var i = 0; i < length; i += 3) { + for (var i = 0; i < length; i += 3) + { // draw some triangles! var index0 = indices[i] * 2, index1 = indices[i + 1] * 2, index2 = indices[i + 2] * 2; this._renderCanvasDrawTriangle(context, vertices, uvs, index0, index1, index2); } }; -Strip.prototype._renderCanvasDrawTriangle = function (context, vertices, uvs, index0, index1, index2) { +Strip.prototype._renderCanvasDrawTriangle = function (context, vertices, uvs, index0, index1, index2) +{ var textureSource = this.texture.baseTexture.source; var textureWidth = this.texture.width; var textureHeight = this.texture.height; @@ -265,7 +287,8 @@ var u0 = uvs[index0] * textureWidth, u1 = uvs[index1] * textureWidth, u2 = uvs[index2] * textureWidth; var v0 = uvs[index0 + 1] * textureHeight, v1 = uvs[index1 + 1] * textureHeight, v2 = uvs[index2 + 1] * textureHeight; - if (this.canvasPadding > 0) { + if (this.canvasPadding > 0) + { var paddingX = this.canvasPadding / this.worldTransform.a; var paddingY = this.canvasPadding / this.worldTransform.d; var centerX = (x0 + x1 + x2) / 3; @@ -332,7 +355,8 @@ * @param strip {Strip} The Strip to render * @private */ -Strip.prototype.renderStripFlat = function (strip) { +Strip.prototype.renderStripFlat = function (strip) +{ var context = this.context; var vertices = strip.vertices; @@ -340,7 +364,8 @@ // this.count++; context.beginPath(); - for (var i=1; i < length-2; i++) { + for (var i=1; i < length-2; i++) + { // draw some triangles! var index = i*2; @@ -358,7 +383,8 @@ }; /* -Strip.prototype.setTexture = function (texture) { +Strip.prototype.setTexture = function (texture) +{ //TODO SET THE TEXTURES //TODO VISIBILITY @@ -377,7 +403,8 @@ * @private */ -Strip.prototype.onTextureUpdate = function () { +Strip.prototype.onTextureUpdate = function () +{ this.updateFrame = true; }; @@ -387,7 +414,8 @@ * @param matrix {Matrix} the transformation matrix of the sprite * @return {Rectangle} the framing rectangle */ -Strip.prototype.getBounds = function (matrix) { +Strip.prototype.getBounds = function (matrix) +{ var worldTransform = matrix || this.worldTransform; var a = worldTransform.a; @@ -404,7 +432,8 @@ var minY = Infinity; var vertices = this.vertices; - for (var i = 0, n = vertices.length; i < n; i += 2) { + for (var i = 0, n = vertices.length; i < n; i += 2) + { var rawX = vertices[i], rawY = vertices[i + 1]; var x = (a * rawX) + (c * rawY) + tx; var y = (d * rawY) + (b * rawX) + ty; @@ -416,7 +445,8 @@ maxY = y > maxY ? y : maxY; } - if (minX === -Infinity || maxY === Infinity) { + if (minX === -Infinity || maxY === Infinity) + { return core.math.Rectangle.EMPTY; } diff --git a/src/extras/TilingSprite.js b/src/extras/TilingSprite.js index 3ac22df..31da393 100644 --- a/src/extras/TilingSprite.js +++ b/src/extras/TilingSprite.js @@ -10,7 +10,8 @@ * @param width {number} the width of the tiling sprite * @param height {number} the height of the tiling sprite */ -function TilingSprite(texture, width, height) { +function TilingSprite(texture, width, height) +{ core.Sprite.call( this, texture); /** @@ -86,10 +87,12 @@ * @memberof TilingSprite# */ width: { - get: function () { + get: function () + { return this._width; }, - set: function (value) { + set: function (value) + { this._width = value; } }, @@ -101,20 +104,25 @@ * @memberof TilingSprite# */ height: { - get: function () { + get: function () + { return this._height; }, - set: function (value) { + set: function (value) + { this._height = value; } }, texture: { - get: function () { + get: function () + { return this._texture; }, - set: function (value) { - if (this._texture === value) { + set: function (value) + { + if (this._texture === value) + { return; } @@ -130,51 +138,61 @@ * * @param renderer {WebGLRenderer} */ -TilingSprite.prototype.renderWebGL = function (renderer) { - if (!this.visible || this.alpha <= 0) { +TilingSprite.prototype.renderWebGL = function (renderer) +{ + if (!this.visible || this.alpha <= 0) + { return; } var i, j; - if (this._mask) { + if (this._mask) + { renderer.spriteBatch.stop(); renderer.maskManager.pushMask(this.mask, renderer); renderer.spriteBatch.start(); } - if (this._filters) { + if (this._filters) + { renderer.spriteBatch.flush(); renderer.filterManager.pushFilter(this._filterBlock); } - if (!this.tilingTexture || this.refreshTexture) { + if (!this.tilingTexture || this.refreshTexture) + { this.generateTilingTexture(true); - if (this.tilingTexture && this.tilingTexture.needsUpdate) { + if (this.tilingTexture && this.tilingTexture.needsUpdate) + { //TODO - tweaking renderer.updateTexture(this.tilingTexture.baseTexture); this.tilingTexture.needsUpdate = false; // this.tilingTexture._uvs = null; } } - else { + else + { renderer.spriteBatch.renderTilingSprite(this); } // simple render children! - for (i=0,j=this.children.length; i= 0 && index <= this.children.length) { - if (child.parent) { + if (index >= 0 && index <= this.children.length) + { + if (child.parent) + { child.parent.removeChild(child); } @@ -154,7 +173,8 @@ return child; } - else { + else + { throw new Error(child + 'addChildAt: The index '+ index +' supplied is out of bounds ' + this.children.length); } }; @@ -165,15 +185,18 @@ * @param child {DisplayObject} * @param child2 {DisplayObject} */ -DisplayObjectContainer.prototype.swapChildren = function (child, child2) { - if (child === child2) { +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) { + if (index1 < 0 || index2 < 0) + { throw new Error('swapChildren: Both the supplied DisplayObjects must be a child of the caller.'); } @@ -187,10 +210,12 @@ * @param child {DisplayObject} The DisplayObject instance to identify * @return {Number} The index position of the child display object to identify */ -DisplayObjectContainer.prototype.getChildIndex = function (child) { +DisplayObjectContainer.prototype.getChildIndex = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { throw new Error('The supplied DisplayObject must be a child of the caller'); } @@ -203,8 +228,10 @@ * @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 */ -DisplayObjectContainer.prototype.setChildIndex = function (child, index) { - if (index < 0 || index >= this.children.length) { +DisplayObjectContainer.prototype.setChildIndex = function (child, index) +{ + if (index < 0 || index >= this.children.length) + { throw new Error('The supplied index is out of bounds'); } @@ -220,8 +247,10 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child at the given index, if any. */ -DisplayObjectContainer.prototype.getChildAt = function (index) { - if (index < 0 || index >= this.children.length) { +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'); } @@ -234,10 +263,12 @@ * @param child {DisplayObject} The DisplayObject to remove * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChild = function (child) { +DisplayObjectContainer.prototype.removeChild = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { return; } @@ -250,7 +281,8 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChildAt = function (index) { +DisplayObjectContainer.prototype.removeChildAt = function (index) +{ var child = this.getChildAt(index); child.parent = null; @@ -265,24 +297,29 @@ * @param beginIndex {Number} The beginning position. Default value is 0. * @param endIndex {Number} The ending position. Default value is size of the container. */ -DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) { +DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) +{ var begin = beginIndex || 0; var end = typeof endIndex === 'number' ? endIndex : this.children.length; var range = end - begin; - if (range > 0 && range <= end) { + if (range > 0 && range <= end) + { var removed = this.children.splice(begin, range); - for (var i = 0; i < removed.length; ++i) { + for (var i = 0; i < removed.length; ++i) + { removed[i].parent = null; } return removed; } - else if (range === 0 && this.children.length === 0) { + else if (range === 0 && this.children.length === 0) + { return []; } - else { + else + { throw new RangeError('removeChildren: numeric values are outside the acceptable range.'); } }; @@ -291,7 +328,8 @@ * Generates and updates the cached sprite for this object. * */ -DisplayObjectContainer.prototype.updateCachedSprite = function () { +DisplayObjectContainer.prototype.updateCachedSprite = function () +{ this._generateCachedSprite(); }; @@ -304,7 +342,8 @@ * @param renderer {CanvasRenderer|WebGLRenderer} The renderer used to generate the texture. * @return {Texture} a texture of the graphics object */ -DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) { +DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) +{ var bounds = this.getLocalBounds(); var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0, renderer, scaleMode, resolution); @@ -322,18 +361,22 @@ * * @private */ -DisplayObjectContainer.prototype.updateTransform = function () { - if (!this.visible) { +DisplayObjectContainer.prototype.updateTransform = function () +{ + if (!this.visible) + { return; } this.displayObjectUpdateTransform(); - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { return; } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } }; @@ -346,8 +389,10 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getBounds = function () { - if (this.children.length === 0) { +DisplayObjectContainer.prototype.getBounds = function () +{ + if (this.children.length === 0) + { return math.Rectangle.EMPTY; } @@ -365,10 +410,12 @@ var childVisible = false; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -386,7 +433,8 @@ maxY = maxY > childMaxY ? maxY : childMaxY; } - if (!childVisible) { + if (!childVisible) + { return math.Rectangle.EMPTY; } @@ -407,12 +455,14 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getLocalBounds = function () { +DisplayObjectContainer.prototype.getLocalBounds = function () +{ var matrixCache = this.worldTransform; this.worldTransform = math.Matrix.IDENTITY; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } @@ -428,13 +478,16 @@ * * @param renderer {WebGLRenderer} The renderer */ -DisplayObjectContainer.prototype.renderWebGL = function (renderer) { +DisplayObjectContainer.prototype.renderWebGL = function (renderer) +{ // if the object is not visible or the alpha is 0 then no need to render this element - if (!this.visible || this.alpha <= 0) { + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } @@ -442,14 +495,17 @@ var i, j; // do a quick check to see if this element has a mask or a filter. - if (this._mask || this._filters) { + if (this._mask || this._filters) + { // push filter first as we need to ensure the stencil buffer is correct for any masking - if (this._filters) { + if (this._filters) + { renderer.spriteBatch.flush(); renderer.filterManager.pushFilter(this._filterBlock); } - if (this._mask) { + if (this._mask) + { renderer.spriteBatch.stop(); renderer.maskManager.pushMask(this.mask, renderer); renderer.spriteBatch.start(); @@ -459,36 +515,42 @@ this._renderWebGL(renderer); // now loop through the children and make sure they get rendered - for (i = 0, j = this.children.length; i < j; i++) { + for (i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderWebGL(renderer); } // time to stop the sprite batch as either a mask element or a filter draw will happen next renderer.spriteBatch.stop(); - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(this._mask, renderer); } - if (this._filters) { + if (this._filters) + { renderer.filterManager.popFilter(); } renderer.spriteBatch.start(); } - else { + else + { this._renderWebGL(renderer); // simple render children! - for (i = 0, j = this.children.length; i < j; ++i) { + for (i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderWebGL(renderer); } } }; -DisplayObjectContainer.prototype._renderWebGL = function (renderer) { +DisplayObjectContainer.prototype._renderWebGL = function (renderer) +{ // this is where content itself gets renderd.. @@ -499,25 +561,31 @@ * * @param renderer {CanvasRenderer} The renderer */ -DisplayObjectContainer.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0) { +DisplayObjectContainer.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -528,13 +596,16 @@ * @param renderer {WebGLRenderer|CanvasRenderer} The renderer * @private */ -DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) { +DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) +{ this._cachedSprite.worldAlpha = this.worldAlpha; - if (renderer.gl) { + if (renderer.gl) + { this._cachedSprite.renderWebGL(renderer); } - else { + else + { this._cachedSprite.renderCanvas(renderer); } }; @@ -544,10 +615,12 @@ * * @private */ -DisplayObjectContainer.prototype._generateCachedSprite = function () { +DisplayObjectContainer.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { // TODO - RenderTexture now *requires* a renderer instance, so this is like broken // because `renderer` isn't actually in scope here :P var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0); @@ -555,7 +628,8 @@ this._cachedSprite = new Sprite(renderTexture); this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.texture.resize(bounds.width | 0, bounds.height | 0); } @@ -580,8 +654,10 @@ * * @private */ -DisplayObjectContainer.prototype._destroyCachedSprite = function () { - if (!this._cachedSprite) { +DisplayObjectContainer.prototype._destroyCachedSprite = function () +{ + if (!this._cachedSprite) + { return; } diff --git a/src/core/display/Sprite.js b/src/core/display/Sprite.js index 707da24..5862aef 100644 --- a/src/core/display/Sprite.js +++ b/src/core/display/Sprite.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param texture {Texture} The texture for this sprite */ -function Sprite(texture) { +function Sprite(texture) +{ DisplayObjectContainer.call(this); /** @@ -85,12 +86,14 @@ this.texture = texture || Texture.EMPTY; } -Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) { +Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) +{ DisplayObjectContainer.prototype.destroy.call(this); this.anchor = null; - if (destroyTexture) { + if (destroyTexture) + { this._texture.destroy(destroyBaseTexture); } @@ -111,10 +114,12 @@ * @memberof Sprite# */ width: { - get: function () { + get: function () + { return this.scale.x * this.texture.frame.width; }, - set: function (value) { + set: function (value) + { this.scale.x = value / this.texture.frame.width; this._width = value; } @@ -127,10 +132,12 @@ * @memberof Sprite# */ height: { - get: function () { + get: function () + { return this.scale.y * this.texture.frame.height; }, - set: function (value) { + set: function (value) + { this.scale.y = value / this.texture.frame.height; this._height = value; } @@ -143,23 +150,29 @@ * @memberof Sprite# */ texture: { - get: function () { + get: function () + { return this._texture; }, - set: function (value) { - if (this._texture === value) { + set: function (value) + { + if (this._texture === value) + { return; } this._texture = value; this.cachedTint = 0xFFFFFF; - if (value) { + if (value) + { // wait for the texture to load - if (value.baseTexture.hasLoaded) { + if (value.baseTexture.hasLoaded) + { this._onTextureUpdate(); } - else { + else + { value.once('update', this._onTextureUpdate.bind(this)); } } @@ -172,18 +185,22 @@ * * @private */ -Sprite.prototype._onTextureUpdate = function () { +Sprite.prototype._onTextureUpdate = function () +{ // so if _width is 0 then width was not set.. - if (this._width) { + if (this._width) + { this.scale.x = this._width / this.texture.frame.width; } - if (this._height) { + if (this._height) + { this.scale.y = this._height / this.texture.frame.height; } }; -Sprite.prototype._renderWebGL = function (renderer) { +Sprite.prototype._renderWebGL = function (renderer) +{ // this is where content gets renderd.. // watch this space for a little render state manager.. @@ -197,7 +214,8 @@ * @param matrix {Matrix} the transformation matrix of the sprite * @return {Rectangle} the framing rectangle */ -Sprite.prototype.getBounds = function (matrix) { +Sprite.prototype.getBounds = function (matrix) +{ var width = this.texture.frame.width; var height = this.texture.frame.height; @@ -224,11 +242,13 @@ if(b === 0 && c === 0) { // scale may be negative! - if (a < 0) { + if (a < 0) + { a *= -1; } - if (d < 0) { + if (d < 0) + { d *= -1; } @@ -293,28 +313,34 @@ * * @param renderer {CanvasRenderer} The renderer */ -Sprite.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) { +Sprite.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) + { return; } - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; renderer.context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } // Ignore null sources - if (this.texture.valid) { + if (this.texture.valid) + { var resolution = this.texture.baseTexture.resolution / renderer.resolution; renderer.context.globalAlpha = this.worldAlpha; // If smoothingEnabled is supported and we need to change the smoothing property for this texture - if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) { + if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) + { renderer.scaleMode = this.texture.baseTexture.scaleMode; renderer.context[renderer.smoothProperty] = (renderer.scaleMode === CONST.scaleModes.LINEAR); } @@ -324,7 +350,8 @@ var dy = (this.texture.trim ? this.texture.trim.y : 0) - (this.anchor.y * this.texture.trim.height); // Allow for pixel rounding - if (renderer.roundPixels) { + if (renderer.roundPixels) + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -337,7 +364,8 @@ dx = dx | 0; dy = dy | 0; } - else { + else + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -348,8 +376,10 @@ ); } - if (this.tint !== 0xFFFFFF) { - if (this.cachedTint !== this.tint) { + if (this.tint !== 0xFFFFFF) + { + if (this.cachedTint !== this.tint) + { this.cachedTint = this.tint; // TODO clean up caching - how to clean up the caches? @@ -368,7 +398,8 @@ this.texture.crop.height / resolution ); } - else { + else + { renderer.context.drawImage( this.texture.baseTexture.source, this.texture.crop.x, @@ -383,11 +414,13 @@ } } - for (var i = 0, j = this.children.length; i < j; i++) { + for (var i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -402,10 +435,12 @@ * @param frameId {String} The frame Id of the texture in the cache * @return {Sprite} A new Sprite using a texture from the texture cache matching the frameId */ -Sprite.fromFrame = function (frameId) { +Sprite.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache' + this); } @@ -420,6 +455,7 @@ * @param imageId {String} The image url of the texture * @return {Sprite} A new Sprite using a texture from the texture cache matching the image id */ -Sprite.fromImage = function (imageId, crossorigin, scaleMode) { +Sprite.fromImage = function (imageId, crossorigin, scaleMode) +{ return new Sprite(Texture.fromImage(imageId, crossorigin, scaleMode)); }; diff --git a/src/core/display/SpriteBatch.js b/src/core/display/SpriteBatch.js index 3187777..c196fef 100644 --- a/src/core/display/SpriteBatch.js +++ b/src/core/display/SpriteBatch.js @@ -12,7 +12,8 @@ * ```js * var container = new SpriteBatch(); * - * for(var i = 0; i < 100; ++i) { + * for(var i = 0; i < 100; ++i) + * { * var sprite = new PIXI.Sprite.fromImage("myImage.png"); * container.addChild(sprite); * } @@ -25,7 +26,8 @@ */ //TODO RENAME to PARTICLE CONTAINER? -function SpriteBatch() { +function SpriteBatch() +{ DisplayObjectContainer.call(this); } @@ -38,7 +40,8 @@ * * @private */ -SpriteBatch.prototype.updateTransform = function () { +SpriteBatch.prototype.updateTransform = function () +{ // TODO don't need to! this.displayObjectUpdateTransform(); // PIXI.DisplayObjectContainer.prototype.updateTransform.call( this ); @@ -50,8 +53,10 @@ * @param renderer {WebGLRenderer} The webgl renderer * @private */ -SpriteBatch.prototype.renderWebGL = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderWebGL = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -71,8 +76,10 @@ * @param renderer {CanvasRenderer} The canvas renderer * @private */ -SpriteBatch.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -84,10 +91,12 @@ this.displayObjectUpdateTransform(); - for (var i = 0; i < this.children.length; ++i) { + for (var i = 0; i < this.children.length; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -95,9 +104,11 @@ context.globalAlpha = this.worldAlpha * child.alpha; - if (child.rotation % (Math.PI * 2) === 0) { + if (child.rotation % (Math.PI * 2) === 0) + { // this is the fastest way to optimise! - if rotation is 0 then we can avoid any kind of setTransform call - if (isRotated) { + if (isRotated) + { context.setTransform( transform.a, transform.b, @@ -122,8 +133,10 @@ frame.height * child.scale.y ); } - else { - if (!isRotated) { + else + { + if (!isRotated) + { isRotated = true; } @@ -131,7 +144,8 @@ var childTransform = child.worldTransform; - if (renderer.roundPixels) { + if (renderer.roundPixels) + { context.setTransform( childTransform.a, childTransform.b, @@ -141,7 +155,8 @@ childTransform.ty | 0 ); } - else { + else + { context.setTransform( childTransform.a, childTransform.b, diff --git a/src/core/index.js b/src/core/index.js index 3954b6f..eb4a82b 100644 --- a/src/core/index.js +++ b/src/core/index.js @@ -58,11 +58,13 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRenderer: function (width, height, options, noWebGL) { + autoDetectRenderer: function (width, height, options, noWebGL) + { width = width || 800; height = height || 600; - if (!noWebGL && require('webgl-enabled')()) { + if (!noWebGL && require('webgl-enabled')()) + { return new core.WebGLRenderer(width, height, options); } @@ -87,7 +89,8 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRecommendedRenderer: function (width, height, options) { + autoDetectRecommendedRenderer: function (width, height, options) + { var isAndroid = /Android/i.test(navigator.userAgent); return core.autoDetectRenderer(width, height, options, isAndroid); diff --git a/src/core/math/Matrix.js b/src/core/math/Matrix.js index c2f87e2..2ff4848 100644 --- a/src/core/math/Matrix.js +++ b/src/core/math/Matrix.js @@ -10,7 +10,8 @@ * @class * @namespace PIXI */ -function Matrix() { +function Matrix() +{ /** * @member {number} * @default 1 @@ -63,7 +64,8 @@ * * @param array {number[]} The array that the matrix will be populated from. */ -Matrix.prototype.fromArray = function (array) { +Matrix.prototype.fromArray = function (array) +{ this.a = array[0]; this.b = array[1]; this.c = array[3]; @@ -78,14 +80,17 @@ * @param transpose {boolean} Whether we need to transpose the matrix or not * @return {number[]} the newly created array which contains the matrix */ -Matrix.prototype.toArray = function (transpose) { - if (!this.array) { +Matrix.prototype.toArray = function (transpose) +{ + if (!this.array) + { this.array = new Float32Array(9); } var array = this.array; - if (transpose) { + if (transpose) + { array[0] = this.a; array[1] = this.b; array[2] = 0; @@ -96,7 +101,8 @@ array[7] = this.ty; array[8] = 1; } - else { + else + { array[0] = this.a; array[1] = this.c; array[2] = this.tx; @@ -119,7 +125,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, transformed through this matrix */ -Matrix.prototype.apply = function (pos, newPos) { +Matrix.prototype.apply = function (pos, newPos) +{ newPos = newPos || new Point(); newPos.x = this.a * pos.x + this.c * pos.y + this.tx; @@ -136,7 +143,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, inverse-transformed through this matrix */ -Matrix.prototype.applyInverse = function (pos, newPos) { +Matrix.prototype.applyInverse = function (pos, newPos) +{ newPos = newPos || new Point(); var id = 1 / (this.a * this.d + this.c * -this.b); @@ -154,7 +162,8 @@ * @param {number} y * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.translate = function (x, y) { +Matrix.prototype.translate = function (x, y) +{ this.tx += x; this.ty += y; @@ -168,7 +177,8 @@ * @param {number} y The amount to scale vertically * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.scale = function (x, y) { +Matrix.prototype.scale = function (x, y) +{ this.a *= x; this.d *= y; this.c *= x; @@ -186,7 +196,8 @@ * @param {number} angle - The angle in radians. * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.rotate = function (angle) { +Matrix.prototype.rotate = function (angle) +{ var cos = Math.cos( angle ); var sin = Math.sin( angle ); @@ -210,7 +221,8 @@ * @param {Matrix} matrix * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.append = function (matrix) { +Matrix.prototype.append = function (matrix) +{ var a1 = this.a; var b1 = this.b; var c1 = this.c; @@ -232,7 +244,8 @@ * * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.identity = function () { +Matrix.prototype.identity = function () +{ this.a = 1; this.b = 0; this.c = 0; diff --git a/src/core/math/Point.js b/src/core/math/Point.js index 7565b2d..632f346 100644 --- a/src/core/math/Point.js +++ b/src/core/math/Point.js @@ -7,7 +7,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -function Point(x, y) { +function Point(x, y) +{ /** * @member {number} * @default 0 @@ -29,7 +30,8 @@ * * @return {Point} a copy of the point */ -Point.prototype.clone = function () { +Point.prototype.clone = function () +{ return new Point(this.x, this.y); }; @@ -40,7 +42,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -Point.prototype.set = function (x, y) { +Point.prototype.set = function (x, y) +{ this.x = x || 0; this.y = y || ( (y !== 0) ? this.x : 0 ) ; }; diff --git a/src/core/math/shapes/Circle.js b/src/core/math/shapes/Circle.js index 69cfdc9..4d76efc 100644 --- a/src/core/math/shapes/Circle.js +++ b/src/core/math/shapes/Circle.js @@ -10,7 +10,8 @@ * @param y {number} The Y coordinate of the center of this circle * @param radius {number} The radius of the circle */ -function Circle(x, y, radius) { +function Circle(x, y, radius) +{ /** * @member {number} * @default 0 @@ -46,7 +47,8 @@ * @method clone * @return {Circle} a copy of the Circle */ -Circle.prototype.clone = function () { +Circle.prototype.clone = function () +{ return new Circle(this.x, this.y, this.radius); }; @@ -58,8 +60,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Circle */ -Circle.prototype.contains = function (x, y) { - if (this.radius <= 0) { +Circle.prototype.contains = function (x, y) +{ + if (this.radius <= 0) + { return false; } @@ -79,6 +83,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Circle.prototype.getBounds = function () { +Circle.prototype.getBounds = function () +{ return new Rectangle(this.x - this.radius, this.y - this.radius, this.radius * 2, this.radius * 2); }; diff --git a/src/core/math/shapes/Ellipse.js b/src/core/math/shapes/Ellipse.js index 4f2d066..fefd01a 100644 --- a/src/core/math/shapes/Ellipse.js +++ b/src/core/math/shapes/Ellipse.js @@ -11,7 +11,8 @@ * @param width {number} The half width of this ellipse * @param height {number} The half height of this ellipse */ -function Ellipse(x, y, width, height) { +function Ellipse(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -53,7 +54,8 @@ * @method clone * @return {Ellipse} a copy of the ellipse */ -Ellipse.prototype.clone = function () { +Ellipse.prototype.clone = function () +{ return new Ellipse(this.x, this.y, this.width, this.height); }; @@ -65,8 +67,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coords are within this ellipse */ -Ellipse.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Ellipse.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } @@ -86,6 +90,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Ellipse.prototype.getBounds = function () { +Ellipse.prototype.getBounds = function () +{ return new Rectangle(this.x - this.width, this.y - this.height, this.width, this.height); }; diff --git a/src/core/math/shapes/Polygon.js b/src/core/math/shapes/Polygon.js index ae89148..fea6d37 100644 --- a/src/core/math/shapes/Polygon.js +++ b/src/core/math/shapes/Polygon.js @@ -10,16 +10,20 @@ * arguments passed can be flat x,y values e.g. `new Polygon(x,y, x,y, x,y, ...)` where `x` and `y` are * Numbers. */ -function Polygon(points) { +function Polygon(points) +{ //if points isn't an array, use arguments as the array - if (!(points instanceof Array)) { + if (!(points instanceof Array)) + { points = Array.prototype.slice.call(arguments); } //if this is a flat array of numbers, convert it to points - if (points[0] instanceof Point) { + if (points[0] instanceof Point) + { var p = []; - for (var i = 0, il = points.length; i < il; i++) { + for (var i = 0, il = points.length; i < il; i++) + { p.push(points[i].x, points[i].y); } @@ -51,7 +55,8 @@ * * @return {Polygon} a copy of the polygon */ -Polygon.prototype.clone = function () { +Polygon.prototype.clone = function () +{ return new Polygon(this.points.slice()); }; @@ -62,19 +67,22 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this polygon */ -Polygon.prototype.contains = function (x, y) { +Polygon.prototype.contains = function (x, y) +{ var inside = false; // use some raycasting to test hits // https://github.com/substack/point-in-polygon/blob/master/index.js var length = this.points.length / 2; - for (var i = 0, j = length - 1; i < length; j = i++) { + for (var i = 0, j = length - 1; i < length; j = i++) + { var xi = this.points[i * 2], yi = this.points[i * 2 + 1], xj = this.points[j * 2], yj = this.points[j * 2 + 1], intersect = ((yi > y) !== (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi); - if (intersect) { + if (intersect) + { inside = !inside; } } diff --git a/src/core/math/shapes/Rectangle.js b/src/core/math/shapes/Rectangle.js index 16ac62a..4008b68 100644 --- a/src/core/math/shapes/Rectangle.js +++ b/src/core/math/shapes/Rectangle.js @@ -10,7 +10,8 @@ * @param width {number} The overall width of this rectangle * @param height {number} The overall height of this rectangle */ -function Rectangle(x, y, width, height) { +function Rectangle(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -60,7 +61,8 @@ * * @return {Rectangle} a copy of the rectangle */ -Rectangle.prototype.clone = function () { +Rectangle.prototype.clone = function () +{ return new Rectangle(this.x, this.y, this.width, this.height); }; @@ -71,13 +73,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rectangle */ -Rectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Rectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/math/shapes/RoundedRectangle.js b/src/core/math/shapes/RoundedRectangle.js index 27d286e..7bf6411 100644 --- a/src/core/math/shapes/RoundedRectangle.js +++ b/src/core/math/shapes/RoundedRectangle.js @@ -11,7 +11,8 @@ * @param height {number} The overall height of this rounded rectangle * @param radius {number} Controls the radius of the rounded corners */ -function RoundedRectangle(x, y, width, height, radius) { +function RoundedRectangle(x, y, width, height, radius) +{ /** * @member {number} * @default 0 @@ -58,7 +59,8 @@ * * @return {RoundedRectangle} a copy of the rounded rectangle */ -RoundedRectangle.prototype.clone = function () { +RoundedRectangle.prototype.clone = function () +{ return new RoundedRectangle(this.x, this.y, this.width, this.height, this.radius); }; @@ -69,13 +71,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rounded Rectangle */ -RoundedRectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +RoundedRectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/primitives/Graphics.js b/src/core/primitives/Graphics.js index 261c534..e902d2a 100644 --- a/src/core/primitives/Graphics.js +++ b/src/core/primitives/Graphics.js @@ -16,7 +16,8 @@ * @extends DisplayObjectContainer * @namespace PIXI */ -function Graphics() { +function Graphics() +{ DisplayObjectContainer.call(this); this.renderable = true; @@ -154,16 +155,20 @@ * @private */ cacheAsBitmap: { - get: function () { + get: function () + { return this._cacheAsBitmap; }, - set: function (value) { + set: function (value) + { this._cacheAsBitmap = value; - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._generateCachedSprite(); } - else { + else + { this.destroyCachedSprite(); this.dirty = true; } @@ -176,7 +181,8 @@ * * @return {Graphics} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ var clone = new Graphics(); clone.renderable = this.renderable; @@ -192,7 +198,8 @@ clone.cachedSpriteDirty = this.cachedSpriteDirty; // copy graphics data - for (var i = 0; i < this.graphicsData.length; ++i) { + for (var i = 0; i < this.graphicsData.length; ++i) + { clone.graphicsData.push(this.graphicsData.clone()); } @@ -211,17 +218,21 @@ * @param alpha {number} alpha of the line to draw, will update the objects stored style * @return {Graphics} */ -Graphics.prototype.lineStyle = function (lineWidth, color, alpha) { +Graphics.prototype.lineStyle = function (lineWidth, color, alpha) +{ this.lineWidth = lineWidth || 0; this.lineColor = color || 0; this.lineAlpha = (arguments.length < 3) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length) + { // halfway through a line? start a new one! this.drawShape( new math.Polygon( this.currentPath.shape.points.slice(-2) )); } - else { + else + { // otherwise its empty so lets just set the line properties this.currentPath.lineWidth = this.lineWidth; this.currentPath.lineColor = this.lineColor; @@ -239,7 +250,8 @@ * @param y {number} the Y coordinate to move to * @return {Graphics} */ -Graphics.prototype.moveTo = function (x, y) { +Graphics.prototype.moveTo = function (x, y) +{ this.drawShape(new math.Polygon([x,y])); return this; @@ -253,7 +265,8 @@ * @param y {number} the Y coordinate to draw to * @return {Graphics} */ -Graphics.prototype.lineTo = function (x, y) { +Graphics.prototype.lineTo = function (x, y) +{ this.currentPath.shape.points.push(x, y); this.dirty = true; @@ -270,13 +283,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -285,7 +302,8 @@ n = 20, points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { this.moveTo(0, 0); } @@ -293,7 +311,8 @@ var fromY = points[points.length-1]; var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; xa = fromX + ( (cpX - fromX) * j ); @@ -319,13 +338,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -342,7 +365,8 @@ var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; dt = (1 - j); @@ -373,13 +397,17 @@ * @param radius {number} The radius of the arc * @return {Graphics} */ -Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points.push(x1, y1); } } - else { + else + { this.moveTo(x1, y1); } @@ -392,12 +420,15 @@ b2 = x2 - x1, mm = Math.abs(a1 * b2 - b1 * a2); - if (mm < 1.0e-8 || radius === 0) { - if (points[points.length-2] !== x1 || points[points.length-1] !== y1) { + if (mm < 1.0e-8 || radius === 0) + { + if (points[points.length-2] !== x1 || points[points.length-1] !== y1) + { points.push(x1, y1); } } - else { + else + { var dd = a1 * a1 + b1 * b1, cc = a2 * a2 + b2 * b2, tt = a1 * a2 + b1 * b2, @@ -433,42 +464,51 @@ * @param anticlockwise {boolean} Optional. Specifies whether the drawing should be counterclockwise or clockwise. False is default, and indicates clockwise, while true indicates counter-clockwise. * @return {Graphics} */ -Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) { +Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) +{ var startX = cx + Math.cos(startAngle) * radius; var startY = cy + Math.sin(startAngle) * radius; var points; // TODO - This if-else makes no sense. It uses currentPath in the else where it doesn't exist... - if (this.currentPath) { + if (this.currentPath) + { points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { points.push(startX, startY); } - else if (points[points.length-2] !== startX || points[points.length-1] !== startY) { + else if (points[points.length-2] !== startX || points[points.length-1] !== startY) + { points.push(startX, startY); } } - else { + else + { this.moveTo(startX, startY); points = this.currentPath.shape.points; } - if (startAngle === endAngle) { + if (startAngle === endAngle) + { return this; } - if (!anticlockwise && endAngle <= startAngle) { + if (!anticlockwise && endAngle <= startAngle) + { endAngle += Math.PI * 2; } - else if (anticlockwise && startAngle <= endAngle) { + else if (anticlockwise && startAngle <= endAngle) + { startAngle += Math.PI * 2; } var sweep = anticlockwise ? (startAngle - endAngle) *-1 : (endAngle - startAngle); var segs = (Math.abs(sweep)/ (Math.PI * 2)) * 40; - if (sweep === 0) { + if (sweep === 0) + { return this; } @@ -482,7 +522,8 @@ var remainder = ( segMinus % 1 ) / segMinus; - for (var i = 0; i <= segMinus; ++i) { + for (var i = 0; i <= segMinus; ++i) + { var real = i + remainder * i; var angle = ((theta) + startAngle + (theta2 * real)); @@ -506,13 +547,16 @@ * @param alpha {number} the alpha of the fill * @return {Graphics} */ -Graphics.prototype.beginFill = function (color, alpha) { +Graphics.prototype.beginFill = function (color, alpha) +{ this.filling = true; this.fillColor = color || 0; this.fillAlpha = (alpha === undefined) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length <= 2) + { this.currentPath.fill = this.filling; this.currentPath.fillColor = this.fillColor; this.currentPath.fillAlpha = this.fillAlpha; @@ -526,7 +570,8 @@ * * @return {Graphics} */ -Graphics.prototype.endFill = function () { +Graphics.prototype.endFill = function () +{ this.filling = false; this.fillColor = null; this.fillAlpha = 1; @@ -542,7 +587,8 @@ * @param height {number} The height of the rectangle * @return {Graphics} */ -Graphics.prototype.drawRect = function ( x, y, width, height ) { +Graphics.prototype.drawRect = function ( x, y, width, height ) +{ this.drawShape(new math.Rectangle(x,y, width, height)); return this; @@ -556,7 +602,8 @@ * @param height {number} The height of the rectangle * @param radius {number} Radius of the rectangle corners */ -Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) { +Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) +{ this.drawShape(new math.RoundedRectangle(x, y, width, height, radius)); return this; @@ -570,7 +617,8 @@ * @param radius {number} The radius of the circle * @return {Graphics} */ -Graphics.prototype.drawCircle = function (x, y, radius) { +Graphics.prototype.drawCircle = function (x, y, radius) +{ this.drawShape(new math.Circle(x,y, radius)); return this; @@ -585,7 +633,8 @@ * @param height {number} The half height of the ellipse * @return {Graphics} */ -Graphics.prototype.drawEllipse = function (x, y, width, height) { +Graphics.prototype.drawEllipse = function (x, y, width, height) +{ this.drawShape(new math.Ellipse(x, y, width, height)); return this; @@ -597,8 +646,10 @@ * @param path {Array} The path data used to construct the polygon. * @return {Graphics} */ -Graphics.prototype.drawPolygon = function (path) { - if (!(path instanceof Array)) { +Graphics.prototype.drawPolygon = function (path) +{ + if (!(path instanceof Array)) + { path = Array.prototype.slice.call(arguments); } @@ -612,7 +663,8 @@ * * @return {Graphics} */ -Graphics.prototype.clear = function () { +Graphics.prototype.clear = function () +{ this.lineWidth = 0; this.filling = false; @@ -631,7 +683,8 @@ * @param scaleMode {number} Should be one of the scaleMode consts * @return {Texture} a texture of the graphics object */ -Graphics.prototype.generateTexture = function (resolution, scaleMode) { +Graphics.prototype.generateTexture = function (resolution, scaleMode) +{ resolution = resolution || 1; var bounds = this.getBounds(); @@ -655,17 +708,21 @@ * * @param renderer {WebGLRenderer} */ -Graphics.prototype._renderWebGL = function (renderer) { +Graphics.prototype._renderWebGL = function (renderer) +{ // if the sprite is not visible or the alpha is 0 then no need to render this element - if (this.isMask === true) { + if (this.isMask === true) + { return; } // this code may still be needed so leaving for now.. - // + // /* - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture on the gpu too! @@ -681,17 +738,24 @@ return; } - */ - - // check if the webgl graphic needs to be updated - if (this.glDirty) { - this.dirty = true; - this.glDirty = false; - } + else */ - renderer.setObjectRendererer(renderer.graphicsRenderer); - renderer.graphicsRenderer.render(this); + renderer.spriteBatch.stop(); + renderer.blendModeManager.setBlendMode(this.blendMode); + // check blend mode + renderer.blendModeManager.setBlendMode( this.blendMode ); + + // check if the webgl graphic needs to be updated + if (this.glDirty) + { + this.dirty = true; + this.glDirty = false; + } + + WebGLGraphics.renderGraphics(this, renderer); + + renderer.spriteBatch.start(); }; /** @@ -700,14 +764,18 @@ * @param renderer {CanvasRenderer} * @private */ -Graphics.prototype.renderCanvas = function (renderer) { +Graphics.prototype.renderCanvas = function (renderer) +{ // 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.isMask === true) { + if (!this.visible || this.alpha <= 0 || this.isMask === true) + { return; } - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture @@ -723,16 +791,19 @@ return; } - else { + else + { var context = renderer.context; var transform = this.worldTransform; - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } @@ -748,11 +819,13 @@ CanvasGraphics.renderGraphics(this, context); - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } } @@ -763,13 +836,16 @@ * * @return {Rectangle} the rectangular bounding area */ -Graphics.prototype.getBounds = function (matrix) { +Graphics.prototype.getBounds = function (matrix) +{ // return an empty object if the item is a mask! - if (this.isMask) { + if (this.isMask) + { return math.Rectangle.EMPTY; } - if (this.dirty) { + if (this.dirty) + { this.updateLocalBounds(); this.glDirty = true; @@ -841,23 +917,27 @@ * Update the bounds of the object * */ -Graphics.prototype.updateLocalBounds = function () { +Graphics.prototype.updateLocalBounds = function () +{ var minX = Infinity; var maxX = -Infinity; var minY = Infinity; var maxY = -Infinity; - if (this.graphicsData.length) { + if (this.graphicsData.length) + { var shape, points, x, y, w, h; - for (var i = 0; i < this.graphicsData.length; i++) { + for (var i = 0; i < this.graphicsData.length; i++) + { var data = this.graphicsData[i]; var type = data.type; var lineWidth = data.lineWidth; shape = data.shape; - if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) { + if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) + { x = shape.x - lineWidth/2; y = shape.y - lineWidth/2; w = shape.width + lineWidth; @@ -869,7 +949,8 @@ minY = y < minY ? y : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.CIRC) { + else if (type === CONST.SHAPES.CIRC) + { x = shape.x; y = shape.y; w = shape.radius + lineWidth/2; @@ -881,7 +962,8 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.ELIP) { + else if (type === CONST.SHAPES.ELIP) + { x = shape.x; y = shape.y; w = shape.width + lineWidth/2; @@ -893,11 +975,13 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else { + else + { // POLY points = shape.points; - for (var j = 0; j < points.length; j += 2) { + for (var j = 0; j < points.length; j += 2) + { x = points[j]; y = points[j+1]; @@ -910,7 +994,8 @@ } } } - else { + else + { minX = 0; maxX = 0; minY = 0; @@ -931,10 +1016,12 @@ * * @private */ -Graphics.prototype._generateCachedSprite = function () { +Graphics.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { var canvasBuffer = new CanvasBuffer(bounds.width, bounds.height); var texture = Texture.fromCanvas(canvasBuffer.canvas); @@ -943,7 +1030,8 @@ this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.buffer.resize(bounds.width, bounds.height); } @@ -968,7 +1056,8 @@ * * @private */ -Graphics.prototype.updateCachedSpriteTexture = function () { +Graphics.prototype.updateCachedSpriteTexture = function () +{ var cachedSprite = this._cachedSprite; var texture = cachedSprite.texture; var canvas = cachedSprite.buffer.canvas; @@ -989,7 +1078,8 @@ * Destroys a previous cached sprite. * */ -Graphics.prototype.destroyCachedSprite = function () { +Graphics.prototype.destroyCachedSprite = function () +{ this._cachedSprite.texture.destroy(true); // let the gc collect the unused sprite @@ -1003,10 +1093,13 @@ * @param {Circle|Rectangle|Ellipse|Line|Polygon} shape The Shape object to draw. * @return {GraphicsData} The generated GraphicsData object. */ -Graphics.prototype.drawShape = function (shape) { - if (this.currentPath) { +Graphics.prototype.drawShape = function (shape) +{ + if (this.currentPath) + { // check current path! - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath.shape.points.length <= 2) + { this.graphicsData.pop(); } } @@ -1017,7 +1110,8 @@ this.graphicsData.push(data); - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { data.shape.closed = this.filling; this.currentPath = data; } diff --git a/src/core/primitives/GraphicsData.js b/src/core/primitives/GraphicsData.js index 99decbe..788f6f2 100644 --- a/src/core/primitives/GraphicsData.js +++ b/src/core/primitives/GraphicsData.js @@ -4,7 +4,8 @@ * @class * @namespace PIXI */ -function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) { +function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) +{ this.lineWidth = lineWidth; this.lineColor = lineColor; this.lineAlpha = lineAlpha; @@ -27,7 +28,8 @@ * * @return {GraphicsData} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ return new GraphicsData( this.lineWidth, this.lineColor, diff --git a/src/core/renderers/canvas/CanvasRenderer.js b/src/core/renderers/canvas/CanvasRenderer.js index 15a0978..7aebd44 100644 --- a/src/core/renderers/canvas/CanvasRenderer.js +++ b/src/core/renderers/canvas/CanvasRenderer.js @@ -17,17 +17,22 @@ * @param [options.resolution=1] {number} the resolution of the renderer retina would be 2 * @param [options.clearBeforeRender=true] {boolean} This sets if the CanvasRenderer will clear the canvas or not before the new render pass. */ -function CanvasRenderer(width, height, options) { +function CanvasRenderer(width, height, options) +{ utils.sayHello('Canvas'); - if (options) { - for (var i in CONST.defaultRenderOptions) { - if (typeof options[i] === 'undefined') { + if (options) + { + for (var i in CONST.defaultRenderOptions) + { + if (typeof options[i] === 'undefined') + { options[i] = CONST.defaultRenderOptions[i]; } } } - else { + else + { options = CONST.defaultRenderOptions; } @@ -156,19 +161,24 @@ this.smoothProperty = null; - if (this.context.imageSmoothingEnabled) { + if (this.context.imageSmoothingEnabled) + { this.smoothProperty = 'imageSmoothingEnabled'; } - else if (this.context.webkitImageSmoothingEnabled) { + else if (this.context.webkitImageSmoothingEnabled) + { this.smoothProperty = 'webkitImageSmoothingEnabled'; } - else if (this.context.mozImageSmoothingEnabled) { + else if (this.context.mozImageSmoothingEnabled) + { this.smoothProperty = 'mozImageSmoothingEnabled'; } - else if (this.context.oImageSmoothingEnabled) { + else if (this.context.oImageSmoothingEnabled) + { this.smoothProperty = 'oImageSmoothingEnabled'; } - else if (this.context.msImageSmoothingEnabled) { + else if (this.context.msImageSmoothingEnabled) + { this.smoothProperty = 'msImageSmoothingEnabled'; } @@ -193,10 +203,12 @@ * @memberof CanvasRenderer# */ backgroundColor: { - get: function () { + get: function () + { return this._backgroundColor; }, - set: function (val) { + set: function (val) + { this._backgroundColor = val; this._backgroundColorString = utils.hex2string(val); } @@ -208,7 +220,8 @@ * * @param object {DisplayObject} the object to be rendered */ -CanvasRenderer.prototype.render = function (object) { +CanvasRenderer.prototype.render = function (object) +{ object.updateTransform(); this.context.setTransform(1,0,0,1,0,0); @@ -218,16 +231,20 @@ this.currentBlendMode = CONST.blendModes.NORMAL; this.context.globalCompositeOperation = this.blendModes[CONST.blendModes.NORMAL]; - if (navigator.isCocoonJS && this.view.screencanvas) { + if (navigator.isCocoonJS && this.view.screencanvas) + { this.context.fillStyle = 'black'; this.context.clear(); } - if (this.clearBeforeRender) { - if (this.transparent) { + if (this.clearBeforeRender) + { + if (this.transparent) + { this.context.clearRect(0, 0, this.width, this.height); } - else { + else + { this.context.fillStyle = this._backgroundColorString; this.context.fillRect(0, 0, this.width , this.height); } @@ -241,8 +258,10 @@ * * @param [removeView=false] {boolean} Removes the Canvas element from the DOM. */ -CanvasRenderer.prototype.destroy = function (removeView) { - if (removeView && this.view.parent) { +CanvasRenderer.prototype.destroy = function (removeView) +{ + if (removeView && this.view.parent) + { this.view.parent.removeChild(this.view); } @@ -257,14 +276,16 @@ * @param width {number} the new width of the canvas view * @param height {number} the new height of the canvas view */ -CanvasRenderer.prototype.resize = function (width, height) { +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) { + if (this.autoResize) + { this.view.style.width = this.width / this.resolution + 'px'; this.view.style.height = this.height / this.resolution + 'px'; } @@ -276,7 +297,8 @@ * @param displayObject {DisplayObject} The displayObject to render * @private */ -CanvasRenderer.prototype.renderDisplayObject = function (displayObject) { +CanvasRenderer.prototype.renderDisplayObject = function (displayObject) +{ displayObject.renderCanvas(this); }; @@ -285,11 +307,14 @@ * * @private */ -CanvasRenderer.prototype._mapBlendModes = function () { - if (!this.blendModes) { +CanvasRenderer.prototype._mapBlendModes = function () +{ + if (!this.blendModes) + { this.blendModes = {}; - if (utils.canUseNewCanvasBlendModes()) { + if (utils.canUseNewCanvasBlendModes()) + { this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? this.blendModes[CONST.blendModes.MULTIPLY] = 'multiply'; @@ -308,7 +333,8 @@ this.blendModes[CONST.blendModes.COLOR] = 'color'; this.blendModes[CONST.blendModes.LUMINOSITY] = 'luminosity'; } - else { + else + { // this means that the browser does not support the cool new blend modes in canvas 'cough' ie 'cough' this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? diff --git a/src/core/renderers/canvas/utils/CanvasBuffer.js b/src/core/renderers/canvas/utils/CanvasBuffer.js index ebe5d47..b183a66 100644 --- a/src/core/renderers/canvas/utils/CanvasBuffer.js +++ b/src/core/renderers/canvas/utils/CanvasBuffer.js @@ -6,7 +6,8 @@ * @param width {number} the width for the newly created canvas * @param height {number} the height for the newly created canvas */ -function CanvasBuffer(width, height) { +function CanvasBuffer(width, height) +{ /** * The Canvas object that belongs to this CanvasBuffer. * @@ -36,10 +37,12 @@ * @memberof CanvasBuffer# */ width: { - get: function () { + get: function () + { return this.canvas.width; }, - set: function (val) { + set: function (val) + { this.canvas.width = val; } }, @@ -50,10 +53,12 @@ * @memberof CanvasBuffer# */ height: { - get: function () { + get: function () + { return this.canvas.height; }, - set: function (val) { + set: function (val) + { this.canvas.height = val; } } @@ -64,7 +69,8 @@ * * @private */ -CanvasBuffer.prototype.clear = function () { +CanvasBuffer.prototype.clear = function () +{ this.context.setTransform(1, 0, 0, 1, 0, 0); this.context.clearRect(0,0, this.canvas.width, this.canvas.height); }; @@ -75,7 +81,8 @@ * @param width {number} the new width of the canvas * @param height {number} the new height of the canvas */ -CanvasBuffer.prototype.resize = function (width, height) { +CanvasBuffer.prototype.resize = function (width, height) +{ this.canvas.width = width; this.canvas.height = height; }; diff --git a/src/core/renderers/canvas/utils/CanvasGraphics.js b/src/core/renderers/canvas/utils/CanvasGraphics.js index c7eaa2a..3f2a91f 100644 --- a/src/core/renderers/canvas/utils/CanvasGraphics.js +++ b/src/core/renderers/canvas/utils/CanvasGraphics.js @@ -13,15 +13,18 @@ * @param graphics {Graphics} the actual graphics object to render * @param context {CanvasRenderingContext2D} the 2d drawing method of the canvas */ -CanvasGraphics.renderGraphics = function (graphics, context) { +CanvasGraphics.renderGraphics = function (graphics, context) +{ var worldAlpha = graphics.worldAlpha; - if (graphics.dirty) { + if (graphics.dirty) + { this.updateGraphicsTint(graphics); graphics.dirty = false; } - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; @@ -30,69 +33,82 @@ context.lineWidth = data.lineWidth; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { context.beginPath(); var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } - if (shape.closed) { + if (shape.closed) + { context.lineTo(points[0], points[1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fillRect(shape.x, shape.y, shape.width, shape.height); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.strokeRect(shape.x, shape.y, shape.width, shape.height); } } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.beginPath(); context.arc(shape.x, shape.y, shape.radius,0,2*Math.PI); context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas var w = shape.width * 2; @@ -119,18 +135,21 @@ context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; var width = shape.width; @@ -152,13 +171,15 @@ context.quadraticCurveTo(rx, ry, rx, ry + radius); context.closePath(); - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); @@ -174,45 +195,54 @@ * @param graphics {Graphics} the graphics which will be used as a mask * @param context {CanvasRenderingContext2D} the context 2d method of the canvas */ -CanvasGraphics.renderGraphicsMask = function (graphics, context) { +CanvasGraphics.renderGraphicsMask = function (graphics, context) +{ var len = graphics.graphicsData.length; - if (len === 0) { + if (len === 0) + { return; } context.beginPath(); - for (var i = 0; i < len; i++) { + for (var i = 0; i < len; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { context.rect(shape.x, shape.y, shape.width, shape.height); context.closePath(); } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.arc(shape.x, shape.y, shape.radius, 0, 2 * Math.PI); context.closePath(); } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas @@ -237,7 +267,8 @@ context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); context.closePath(); } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; @@ -262,8 +293,10 @@ } }; -CanvasGraphics.updateGraphicsTint = function (graphics) { - if (graphics.tint === 0xFFFFFF) { +CanvasGraphics.updateGraphicsTint = function (graphics) +{ + if (graphics.tint === 0xFFFFFF) + { return; } @@ -271,7 +304,8 @@ var tintG = (graphics.tint >> 8 & 0xFF) / 255; var tintB = (graphics.tint & 0xFF)/ 255; - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var fillColor = data.fillColor | 0; diff --git a/src/core/renderers/canvas/utils/CanvasMaskManager.js b/src/core/renderers/canvas/utils/CanvasMaskManager.js index e04a733..9827d36 100644 --- a/src/core/renderers/canvas/utils/CanvasMaskManager.js +++ b/src/core/renderers/canvas/utils/CanvasMaskManager.js @@ -6,7 +6,8 @@ * @class * @namespace PIXI */ -function CanvasMaskManager() {} +function CanvasMaskManager() +{} CanvasMaskManager.prototype.constructor = CanvasMaskManager; module.exports = CanvasMaskManager; @@ -17,7 +18,8 @@ * @param maskData {object} the maskData that will be pushed * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.pushMask = function (maskData, renderer) { +CanvasMaskManager.prototype.pushMask = function (maskData, renderer) +{ renderer.context.save(); var cacheAlpha = maskData.alpha; @@ -45,6 +47,7 @@ * * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.popMask = function (renderer) { +CanvasMaskManager.prototype.popMask = function (renderer) +{ renderer.context.restore(); }; diff --git a/src/core/renderers/canvas/utils/CanvasTinter.js b/src/core/renderers/canvas/utils/CanvasTinter.js index 17e0529..d2fb1bc 100644 --- a/src/core/renderers/canvas/utils/CanvasTinter.js +++ b/src/core/renderers/canvas/utils/CanvasTinter.js @@ -14,7 +14,8 @@ * @param color {number} the color to use to tint the sprite with * @return {HTMLCanvasElement} The tinted canvas */ -CanvasTinter.getTintedTexture = function (sprite, color) { +CanvasTinter.getTintedTexture = function (sprite, color) +{ var texture = sprite.texture; color = CanvasTinter.roundColor(color); @@ -23,7 +24,8 @@ texture.tintCache = texture.tintCache || {}; - if (texture.tintCache[stringColor]) { + if (texture.tintCache[stringColor]) + { return texture.tintCache[stringColor]; } @@ -33,14 +35,16 @@ //CanvasTinter.tintWithPerPixel(texture, stringColor, canvas); CanvasTinter.tintMethod(texture, color, canvas); - if (CanvasTinter.convertTintToImage) { + if (CanvasTinter.convertTintToImage) + { // is this better? var tintImage = new Image(); tintImage.src = canvas.toDataURL(); texture.tintCache[stringColor] = tintImage; } - else { + else + { texture.tintCache[stringColor] = canvas; // if we are not converting the texture to an image then we need to lose the reference to the canvas CanvasTinter.canvas = null; @@ -56,7 +60,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithMultiply = function (texture, color, canvas) { +CanvasTinter.tintWithMultiply = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -104,7 +109,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithOverlay = function (texture, color, canvas) { +CanvasTinter.tintWithOverlay = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -139,7 +145,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithPerPixel = function (texture, color, canvas) { +CanvasTinter.tintWithPerPixel = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -167,7 +174,8 @@ var pixels = pixelData.data; - for (var i = 0; i < pixels.length; i += 4) { + for (var i = 0; i < pixels.length; i += 4) + { pixels[i+0] *= r; pixels[i+1] *= g; pixels[i+2] *= b; @@ -181,7 +189,8 @@ * * @param color {number} the color to round, should be a hex color */ -CanvasTinter.roundColor = function (color) { +CanvasTinter.roundColor = function (color) +{ var step = CanvasTinter.cacheStepsPerColorChannel; var rgbValues = utils.hex2rgb(color); diff --git a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js index 9f2f89a..35edbaf 100644 --- a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js +++ b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLBlendModeManager(renderer) { +function WebGLBlendModeManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -23,8 +24,10 @@ * * @param blendMode {number} the blendMode, should be a Pixi const, such as BlendModes.ADD */ -WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) { - if (this.currentBlendMode === blendMode) { +WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) +{ + if (this.currentBlendMode === blendMode) + { return false; } diff --git a/src/core/renderers/webgl/managers/WebGLFilterManager.js b/src/core/renderers/webgl/managers/WebGLFilterManager.js index 1179258..2dac048 100644 --- a/src/core/renderers/webgl/managers/WebGLFilterManager.js +++ b/src/core/renderers/webgl/managers/WebGLFilterManager.js @@ -7,7 +7,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLFilterManager(renderer) { +function WebGLFilterManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -32,7 +33,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.texturePool.length = 0; self.initShaderBuffers(); }); @@ -46,7 +48,8 @@ * @param renderer {WebGLRenderer} * @param buffer {ArrayBuffer} */ -WebGLFilterManager.prototype.begin = function (buffer) { +WebGLFilterManager.prototype.begin = function (buffer) +{ this.defaultShader = this.renderer.shaderManager.defaultShader; this.width = this.renderer.projection.x * 2; @@ -60,7 +63,8 @@ * * @param filterBlock {object} the filter that will be pushed to the current filter stack */ -WebGLFilterManager.prototype.pushFilter = function (filterBlock) { +WebGLFilterManager.prototype.pushFilter = function (filterBlock) +{ var gl = this.renderer.gl; var projection = this.renderer.projection; @@ -78,10 +82,12 @@ this.offsetY += filterBlock._filterArea.y; var texture = this.texturePool.pop(); - if (!texture) { + if (!texture) + { texture = new FilterTexture(this.renderer.gl, this.width, this.height); } - else { + else + { texture.resize(this.width, this.height); } @@ -98,29 +104,35 @@ var localX = filterArea.x, localY = filterArea.y; - if (filterArea.x < 0) { + if (filterArea.x < 0) + { filterArea.width += filterArea.x; filterArea.x = 0; } - if (filterArea.y < 0) { + if (filterArea.y < 0) + { filterArea.height += filterArea.y; filterArea.y = 0; } - if (localX + filterArea.width > this.width) { + if (localX + filterArea.width > this.width) + { filterArea.width = this.width - localX; } - if (localY + filterArea.height > this.height) { + if (localY + filterArea.height > this.height) + { filterArea.height = this.height - localY; } - if (filterArea.width < 0) { + if (filterArea.width < 0) + { filterArea.width = 0; } - if (filterArea.height < 0) { + if (filterArea.height < 0) + { filterArea.height = 0; } @@ -154,7 +166,8 @@ * Removes the last filter from the filter stack and doesn't return it. * */ -WebGLFilterManager.prototype.popFilter = function () { +WebGLFilterManager.prototype.popFilter = function () +{ var gl = this.renderer.gl; var filterBlock = this.filterStack.pop(); @@ -163,7 +176,8 @@ var projection = this.renderer.projection; var offset = this.renderer.offset; - if (filterBlock.filterPasses.length > 1) { + if (filterBlock.filterPasses.length > 1) + { gl.viewport(0, 0, filterArea.width, filterArea.height); gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); @@ -193,7 +207,8 @@ var inputTexture = texture; var outputTexture = this.texturePool.pop(); - if (!outputTexture) { + if (!outputTexture) + { outputTexture = new FilterTexture(this.renderer.gl, this.width, this.height); } outputTexture.resize(this.width, this.height); @@ -204,7 +219,8 @@ gl.disable(gl.BLEND); - for (var i = 0; i < filterBlock.filterPasses.length-1; i++) { + for (var i = 0; i < filterBlock.filterPasses.length-1; i++) + { var filterPass = filterBlock.filterPasses[i]; gl.bindFramebuffer(gl.FRAMEBUFFER, outputTexture.frameBuffer ); @@ -243,10 +259,12 @@ var buffer = this.buffer; // time to render the filters texture to the previous scene - if (this.filterStack.length === 0) { + if (this.filterStack.length === 0) + { gl.colorMask(true, true, true, true);//this.transparent); } - else { + else + { var currentFilter = this.filterStack[this.filterStack.length-1]; filterArea = currentFilter._filterArea; @@ -332,13 +350,15 @@ * @param width {number} the horizontal range of the filter * @param height {number} the vertical range of the filter */ -WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) { +WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) +{ // use program var gl = this.renderer.gl; var shader = filter.shaders[gl.id]; - if (!shader) { + if (!shader) + { shader = new Shader(gl); shader.fragmentSrc = filter.fragmentSrc; @@ -356,7 +376,8 @@ gl.uniform2f(shader.projectionVector, width/2, -height/2); gl.uniform2f(shader.offsetVector, 0,0); - if (filter.uniforms.dimensions) { + 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]; @@ -386,7 +407,8 @@ * Initialises the shader buffers. * */ -WebGLFilterManager.prototype.initShaderBuffers = function () { +WebGLFilterManager.prototype.initShaderBuffers = function () +{ var gl = this.renderer.gl; // create some buffers @@ -432,7 +454,8 @@ * Destroys the filter and removes it from the filter stack. * */ -WebGLFilterManager.prototype.destroy = function () { +WebGLFilterManager.prototype.destroy = function () +{ var gl = this.renderer.gl; this.filterStack = null; @@ -441,7 +464,8 @@ this.offsetY = 0; // destroy textures - for (var i = 0; i < this.texturePool.length; i++) { + for (var i = 0; i < this.texturePool.length; i++) + { this.texturePool[i].destroy(); } diff --git a/src/core/renderers/webgl/managers/WebGLManager.js b/src/core/renderers/webgl/managers/WebGLManager.js index 9d47b5c..c30cd51 100644 --- a/src/core/renderers/webgl/managers/WebGLManager.js +++ b/src/core/renderers/webgl/managers/WebGLManager.js @@ -3,7 +3,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLManager(renderer) { +function WebGLManager(renderer) +{ /** * The renderer this manager works for. * @@ -15,6 +16,7 @@ WebGLManager.prototype.constructor = WebGLManager; module.exports = WebGLManager; -WebGLManager.prototype.destroy = function () { +WebGLManager.prototype.destroy = function () +{ this.renderer = null; }; diff --git a/src/core/renderers/webgl/managers/WebGLMaskManager.js b/src/core/renderers/webgl/managers/WebGLMaskManager.js index 2f90b64..e568812 100644 --- a/src/core/renderers/webgl/managers/WebGLMaskManager.js +++ b/src/core/renderers/webgl/managers/WebGLMaskManager.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLMaskManager(renderer) { +function WebGLMaskManager(renderer) +{ WebGLManager.call(this, renderer); } @@ -19,12 +20,15 @@ * * @param maskData {any[]} */ -WebGLMaskManager.prototype.pushMask = function (maskData) { - if (maskData.dirty) { +WebGLMaskManager.prototype.pushMask = function (maskData) +{ + if (maskData.dirty) + { WebGLGraphics.updateGraphics(maskData, this.renderer.gl); } - if (!maskData._webGL[this.renderer.gl.id].data.length) { + if (!maskData._webGL[this.renderer.gl.id].data.length) + { return; } @@ -36,6 +40,7 @@ * * @param maskData {any[]} */ -WebGLMaskManager.prototype.popMask = function (maskData) { +WebGLMaskManager.prototype.popMask = function (maskData) +{ this.renderer.stencilManager.popStencil(maskData, maskData._webGL[this.renderer.gl.id].data[0], this.renderer); }; diff --git a/src/core/renderers/webgl/managers/WebGLShaderManager.js b/src/core/renderers/webgl/managers/WebGLShaderManager.js index fef071c..90c6477 100644 --- a/src/core/renderers/webgl/managers/WebGLShaderManager.js +++ b/src/core/renderers/webgl/managers/WebGLShaderManager.js @@ -10,7 +10,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLShaderManager(renderer) { +function WebGLShaderManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -28,7 +29,8 @@ */ this.tempAttribState = []; - for (var i = 0; i < this.maxAttibs; i++) { + for (var i = 0; i < this.maxAttibs; i++) + { this.attribState[i] = false; } @@ -66,7 +68,8 @@ // listen for context and update necessary shaders var self = this; - this.renderer.on('context', function (event) { + this.renderer.on('context', function (event) + { var gl = event.data; // this shader is used for rendering primitives @@ -97,29 +100,36 @@ * * @param attribs {Array} attribs */ -WebGLShaderManager.prototype.setAttribs = function (attribs) { +WebGLShaderManager.prototype.setAttribs = function (attribs) +{ // reset temp state var i; - for (i = 0; i < this.tempAttribState.length; i++) { + for (i = 0; i < this.tempAttribState.length; i++) + { this.tempAttribState[i] = false; } // set the new attribs - for (var a in attribs) { + for (var a in attribs) + { this.tempAttribState[attribs[a]] = true; } var gl = this.renderer.gl; - for (i = 0; i < this.attribState.length; i++) { - if (this.attribState[i] !== this.tempAttribState[i]) { + for (i = 0; i < this.attribState.length; i++) + { + if (this.attribState[i] !== this.tempAttribState[i]) + { this.attribState[i] = this.tempAttribState[i]; - if (this.attribState[i]) { + if (this.attribState[i]) + { gl.enableVertexAttribArray(i); } - else { + else + { gl.disableVertexAttribArray(i); } } @@ -131,8 +141,10 @@ * * @param shader {Any} */ -WebGLShaderManager.prototype.setShader = function (shader) { - if (this._currentId === shader.uuid) { +WebGLShaderManager.prototype.setShader = function (shader) +{ + if (this._currentId === shader.uuid) + { return false; } @@ -150,7 +162,8 @@ * Destroys this object. * */ -WebGLShaderManager.prototype.destroy = function () { +WebGLShaderManager.prototype.destroy = function () +{ this.attribState = null; this.tempAttribState = null; diff --git a/src/core/renderers/webgl/managers/WebGLStencilManager.js b/src/core/renderers/webgl/managers/WebGLStencilManager.js index 9ec6398..4cb0134 100644 --- a/src/core/renderers/webgl/managers/WebGLStencilManager.js +++ b/src/core/renderers/webgl/managers/WebGLStencilManager.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLStencilManager(renderer) { +function WebGLStencilManager(renderer) +{ WebGLManager.call(this, renderer); this.stencilStack = []; @@ -24,12 +25,14 @@ * @param graphics {Graphics} * @param webGLData {any[]} */ -WebGLStencilManager.prototype.pushStencil = function (graphics, webGLData) { +WebGLStencilManager.prototype.pushStencil = function (graphics, webGLData) +{ var gl = this.renderer.gl; this.bindGraphics(graphics, webGLData, this.renderer); - if (this.stencilStack.length === 0) { + if (this.stencilStack.length === 0) + { gl.enable(gl.STENCIL_TEST); gl.clear(gl.STENCIL_BUFFER_BIT); this.reverse = true; @@ -47,14 +50,17 @@ // draw the triangle strip! - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } @@ -62,31 +68,38 @@ // draw a quad to increment.. gl.drawElements(gl.TRIANGLE_FAN, 4, gl.UNSIGNED_SHORT, ( webGLData.indices.length - 4 ) * 2 ); - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); } this.reverse = !this.reverse; } - else { - if (!this.reverse) { + else + { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } - else { + 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) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); } } @@ -103,7 +116,8 @@ * @param graphics {Graphics} * @param webGLData {Array} */ -WebGLStencilManager.prototype.bindGraphics = function (graphics, webGLData) { +WebGLStencilManager.prototype.bindGraphics = function (graphics, webGLData) +{ //if (this._currentGraphics === graphics)return; this._currentGraphics = graphics; @@ -114,7 +128,8 @@ offset = this.renderer.offset, shader;// = this.renderer.shaderManager.primitiveShader; - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { shader = this.renderer.shaderManager.complexPrimitiveShader; this.renderer.shaderManager.setShader(shader); @@ -141,7 +156,8 @@ // set the index buffer! gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, webGLData.indexBuffer); } - else { + else + { //this.renderer.shaderManager.activatePrimitiveShader(); shader = this.renderer.shaderManager.primitiveShader; this.renderer.shaderManager.setShader( shader ); @@ -154,7 +170,7 @@ gl.uniform2f(shader.uniforms.offsetVector._location, -offset.x, -offset.y); gl.uniform3fv(shader.uniforms.tint._location, utils.hex2rgb(graphics.tint)); - + gl.uniform1f(shader.uniforms.alpha._location, graphics.worldAlpha); @@ -172,19 +188,22 @@ * @param graphics {Graphics} * @param webGLData {Array} */ -WebGLStencilManager.prototype.popStencil = function (graphics, webGLData) { +WebGLStencilManager.prototype.popStencil = function (graphics, webGLData) +{ var gl = this.renderer.gl; this.stencilStack.pop(); this.count--; - if (this.stencilStack.length === 0) { + if (this.stencilStack.length === 0) + { // the stack is empty! gl.disable(gl.STENCIL_TEST); } - else { + else + { var level = this.count; @@ -192,14 +211,17 @@ gl.colorMask(false, false, false, false); - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { this.reverse = !this.reverse; - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } @@ -213,31 +235,38 @@ // draw the triangle strip! gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); - if (!this.reverse) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); } } - else { + else + { // console.log("<<>>") - if (!this.reverse) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } - else { + 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) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); } } @@ -253,7 +282,8 @@ * Destroys the mask stack. * */ -WebGLStencilManager.prototype.destroy = function () { +WebGLStencilManager.prototype.destroy = function () +{ this.renderer = null; this.stencilStack = null; }; diff --git a/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js b/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js index 913ba5e..1ea7d19 100644 --- a/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js +++ b/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function ComplexPrimitiveShader(gl) { +function ComplexPrimitiveShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -24,7 +25,8 @@ 'uniform float flipY;', 'varying vec4 vColor;', - 'void main(void) {', + '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);', @@ -37,7 +39,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = vColor;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/FastShader.js b/src/core/renderers/webgl/shaders/FastShader.js index bd2e29a..2e5e060 100644 --- a/src/core/renderers/webgl/shaders/FastShader.js +++ b/src/core/renderers/webgl/shaders/FastShader.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function FastShader(gl) { +function FastShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -28,7 +29,8 @@ 'const vec2 center = vec2(-1.0, 1.0);', - 'void main(void) {', + 'void main(void) + {', ' vec2 v;', ' vec2 sv = aVertexPosition * aScale;', ' v.x = (sv.x) * cos(aRotation) - (sv.y) * sin(aRotation);', @@ -49,7 +51,8 @@ 'uniform sampler2D uSampler;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/PrimitiveShader.js b/src/core/renderers/webgl/shaders/PrimitiveShader.js index 6f25409..a25f54f 100644 --- a/src/core/renderers/webgl/shaders/PrimitiveShader.js +++ b/src/core/renderers/webgl/shaders/PrimitiveShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function PrimitiveShader(gl) { +function PrimitiveShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -23,7 +24,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + '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);', @@ -36,7 +38,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = vColor;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/Shader.js b/src/core/renderers/webgl/shaders/Shader.js index f8964f5..fd75ef5 100644 --- a/src/core/renderers/webgl/shaders/Shader.js +++ b/src/core/renderers/webgl/shaders/Shader.js @@ -6,7 +6,8 @@ * @param [fragmentSrc] {string} The source of the fragment shader. * @param [vertexSrc] {string} The source of the vertex shader. */ -function Shader(gl, vertexSrc, fragmentSrc, customUniforms, customAttributes) { +function Shader(gl, vertexSrc, fragmentSrc, customUniforms, customAttributes) +{ /** * @member {number} * @readonly @@ -33,7 +34,8 @@ dimensions: { type: '4f', value: new Float32Array(4) } }; - for (var u in customUniforms) { + for (var u in customUniforms) + { this.uniforms[u] = customUniforms[u]; } @@ -43,7 +45,8 @@ aColor: 0 }; - for (var a in customAttributes) { + for (var a in customAttributes) + { this.attributes[a] = customAttributes[a]; } @@ -66,7 +69,8 @@ 'const vec2 center = vec2(-1.0, 1.0);', - 'void main(void) {', + 'void main(void) + {', ' gl_Position = vec4( ((aVertexPosition + offsetVector) / projectionVector) + center , 0.0, 1.0);', ' vTextureCoord = aTextureCoord;', ' vColor = vec4(aColor.rgb * aColor.a, aColor.a);', @@ -85,7 +89,8 @@ 'uniform sampler2D uSampler;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;', '}' ].join('\n'); @@ -96,7 +101,8 @@ Shader.prototype.constructor = Shader; module.exports = Shader; -Shader.prototype.init = function () { +Shader.prototype.init = function () +{ this.compile(); this.gl.useProgram(this.program); @@ -105,14 +111,18 @@ this.cacheAttributeLocations(Object.keys(this.attributes)); }; -Shader.prototype.cacheUniformLocations = function (keys) { - for (var i = 0; i < keys.length; ++i) { +Shader.prototype.cacheUniformLocations = function (keys) +{ + for (var i = 0; i < keys.length; ++i) + { this.uniforms[keys[i]]._location = this.gl.getUniformLocation(this.program, keys[i]); } }; -Shader.prototype.cacheAttributeLocations = function (keys) { - for (var i = 0; i < keys.length; ++i) { +Shader.prototype.cacheAttributeLocations = function (keys) +{ + for (var i = 0; i < keys.length; ++i) + { this.attributes[keys[i]] = this.gl.getAttribLocation(this.program, keys[i]); } @@ -124,14 +134,16 @@ // 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.attributes.aColor === -1) { + // if (this.attributes.aColor === -1) + { // this.attributes.aColor = 2; // } // End worst hack eva // }; -Shader.prototype.compile = function () { +Shader.prototype.compile = function () +{ var gl = this.gl; var glVertShader = this._glCompile(gl.VERTEX_SHADER, this.vertexSrc); @@ -144,13 +156,15 @@ gl.linkProgram(program); // if linking fails, then log and cleanup - if (!gl.getProgramParameter(program, gl.LINK_STATUS)) { + if (!gl.getProgramParameter(program, gl.LINK_STATUS)) + { window.console.error('Pixi.js Error: Could not initialize shader.'); window.console.error('gl.VALIDATE_STATUS', gl.getProgramParameter(program, gl.VALIDATE_STATUS)); window.console.error('gl.getError()', gl.getError()); // if there is a program info log, log it - if (gl.getProgramInfoLog(program) !== '') { + if (gl.getProgramInfoLog(program) !== '') + { window.console.warn('Pixi.js Warning: gl.getProgramInfoLog()', gl.getProgramInfoLog(program)); } @@ -165,18 +179,21 @@ return (this.program = program); }; -Shader.prototype.syncUniforms = function () { +Shader.prototype.syncUniforms = function () +{ var gl = this.gl; this.textureCount = 1; - for (var key in this.uniforms) { + for (var key in this.uniforms) + { var uniform = this.uniforms[key], location = uniform._location, value = uniform.value, i, il; - switch (uniform.type) { + switch (uniform.type) + { // single int value case 'i': case '1i': @@ -282,7 +299,8 @@ // a Color Value case 'c': - if (typeof value === 'number') { + if (typeof value === 'number') + { value = utils.hex2rgb(value); } @@ -311,11 +329,13 @@ // array of 2D Point objects case 'v2v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(2 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 2] = value[i].x; uniform._array[i * 2 + 1] = value[i].y; } @@ -325,11 +345,13 @@ // array of 3D Point objects case 'v3v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(3 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 3] = value[i].x; uniform._array[i * 3 + 1] = value[i].y; uniform._array[i * 3 + 2] = value[i].z; @@ -341,11 +363,13 @@ // array of 4D Point objects case 'v4v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(4 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 4] = value[i].x; uniform._array[i * 4 + 1] = value[i].y; uniform._array[i * 4 + 2] = value[i].z; @@ -359,7 +383,8 @@ // PIXI.Texture case 't': case 'sampler2D': - if (!uniform.value || !uniform.value.baseTexture || !uniform.value.baseTexture.hasLoaded) { + if (!uniform.value || !uniform.value.baseTexture || !uniform.value.baseTexture.hasLoaded) + { break; } @@ -376,7 +401,8 @@ this.textureCount++; // initialize the texture if we haven't yet - if (!uniform._init) { + if (!uniform._init) + { this.initSampler2D(uniform); uniform._init = true; @@ -394,11 +420,13 @@ * Initialises a Sampler2D uniform (which may only be available later on after initUniforms once the texture has loaded) * */ -Shader.prototype.initSampler2D = function (uniform) { +Shader.prototype.initSampler2D = function (uniform) +{ var gl = this.gl; // Extended texture data - if (uniform.textureData) { + if (uniform.textureData) + { var data = uniform.textureData; // GLTexture = mag linear, min linear_mipmap_linear, wrap repeat + gl.generateMipmap(gl.TEXTURE_2D); @@ -417,14 +445,16 @@ var wrapT = (data.wrapT) ? data.wrapT : gl.CLAMP_TO_EDGE; var format = (data.luminance) ? gl.LUMINANCE : gl.RGBA; - if (data.repeat) { + if (data.repeat) + { wrapS = gl.REPEAT; wrapT = gl.REPEAT; } gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, !!data.flipY); - if (data.width) { + if (data.width) + { var width = (data.width) ? data.width : 512; var height = (data.height) ? data.height : 2; var border = (data.border) ? data.border : 0; @@ -432,7 +462,8 @@ // 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 { + 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); } @@ -448,7 +479,8 @@ * Destroys the shader. * */ -Shader.prototype.destroy = function () { +Shader.prototype.destroy = function () +{ this.gl.deleteProgram(this.program); this.gl = null; @@ -459,13 +491,15 @@ this.fragmentSrc = null; }; -Shader.prototype._glCompile = function (type, src) { +Shader.prototype._glCompile = function (type, src) +{ var shader = this.gl.createShader(type); this.gl.shaderSource(shader, src); this.gl.compileShader(shader); - if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) { + if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) + { window.console.log(this.gl.getShaderInfoLog(shader)); return null; } diff --git a/src/core/renderers/webgl/shaders/StripShader.js b/src/core/renderers/webgl/shaders/StripShader.js index 193f6e1..a7abcc6 100644 --- a/src/core/renderers/webgl/shaders/StripShader.js +++ b/src/core/renderers/webgl/shaders/StripShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function StripShader(gl) { +function StripShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -20,7 +21,8 @@ 'varying vec2 vTextureCoord;', - 'void main(void) {', + '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);', @@ -36,7 +38,8 @@ 'varying vec2 vTextureCoord;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vec2(vTextureCoord.x, vTextureCoord.y)) * alpha;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/utils/FilterTexture.js b/src/core/renderers/webgl/utils/FilterTexture.js index d2c8423..4433d44 100644 --- a/src/core/renderers/webgl/utils/FilterTexture.js +++ b/src/core/renderers/webgl/utils/FilterTexture.js @@ -8,7 +8,8 @@ * @param height {number} the vertical range of the filter * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values */ -function FilterTexture(gl, width, height, scaleMode) { +function FilterTexture(gl, width, height, scaleMode) +{ /** * @member {WebGLContext} */ @@ -59,7 +60,8 @@ * Clears the filter texture. * */ -FilterTexture.prototype.clear = function () { +FilterTexture.prototype.clear = function () +{ var gl = this.gl; gl.clearColor(0,0,0, 0); @@ -72,8 +74,10 @@ * @param width {number} the new width of the texture * @param height {number} the new height of the texture */ -FilterTexture.prototype.resize = function (width, height) { - if (this.width === width && this.height === height) { +FilterTexture.prototype.resize = function (width, height) +{ + if (this.width === width && this.height === height) + { return; } @@ -96,7 +100,8 @@ * Destroys the filter texture. * */ -FilterTexture.prototype.destroy = function () { +FilterTexture.prototype.destroy = function () +{ var gl = this.gl; gl.deleteFramebuffer( this.frameBuffer ); gl.deleteTexture( this.texture ); diff --git a/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js b/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js index c4721e9..a63f4d7 100644 --- a/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js +++ b/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js @@ -14,7 +14,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this sprite batch works for. */ -function WebGLFastSpriteBatch(renderer) { +function WebGLFastSpriteBatch(renderer) +{ /** * The renderer instance this sprite batch operates on. * @@ -91,7 +92,8 @@ */ this.lastIndexCount = 0; - for (var i=0, j=0; i < numIndices; i += 6, j += 4) { + 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; @@ -144,7 +146,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.setupContext(); }); } @@ -157,7 +160,8 @@ * * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLFastSpriteBatch.prototype.setupContext = function () { +WebGLFastSpriteBatch.prototype.setupContext = function () +{ var gl = this.renderer.gl; // create a couple of buffers @@ -177,7 +181,8 @@ /** * @param spriteBatch {SpriteBatch} The SpriteBatch container to prepare for. */ -WebGLFastSpriteBatch.prototype.begin = function (spriteBatch) { +WebGLFastSpriteBatch.prototype.begin = function (spriteBatch) +{ this.shader = this.renderer.shaderManager.fastShader; this.matrix = spriteBatch.worldTransform.toArray(true); @@ -187,33 +192,38 @@ /** */ -WebGLFastSpriteBatch.prototype.end = function () { +WebGLFastSpriteBatch.prototype.end = function () +{ this.flush(); }; /** * @param spriteBatch {SpriteBatch} The SpriteBatch container to render. */ -WebGLFastSpriteBatch.prototype.render = function (spriteBatch) { +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) { + if (!sprite.texture._uvs) + { return; } this.currentBaseTexture = sprite.texture.baseTexture; // check blend mode - if (sprite.blendMode !== this.renderer.blendModeManager.currentBlendMode) { + if (sprite.blendMode !== this.renderer.blendModeManager.currentBlendMode) + { this.flush(); this.renderer.blendModeManager.setBlendMode(sprite.blendMode); } - for (var i=0,j= children.length; i= this.size) { + if (this.currentBatchSize >= this.size) + { this.flush(); } }; @@ -362,29 +379,35 @@ /** * */ -WebGLFastSpriteBatch.prototype.flush = function () { +WebGLFastSpriteBatch.prototype.flush = function () +{ // If the batch is length 0 then return as there is nothing to draw - if (this.currentBatchSize === 0) { + if (this.currentBatchSize === 0) + { return; } var gl = this.renderer.gl; // bind the current texture - if (!this.currentBaseTexture._glTextures[gl.id]) { + if (!this.currentBaseTexture._glTextures[gl.id]) + { this.renderer.updateTexture(this.currentBaseTexture, gl); } //TODO-SHOUD THIS BE ELSE??!?!?! - else { + else + { gl.bindTexture(gl.TEXTURE_2D, this.currentBaseTexture._glTextures[gl.id]); } // upload the verts to the buffer - if (this.currentBatchSize > ( this.size * 0.5 ) ) { + if (this.currentBatchSize > ( this.size * 0.5 ) ) + { gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); } - else { + else + { var view = this.vertices.subarray(0, this.currentBatchSize * this.vertByteSize); gl.bufferSubData(gl.ARRAY_BUFFER, 0, view); @@ -405,14 +428,16 @@ * Ends the batch and flushes * */ -WebGLFastSpriteBatch.prototype.stop = function () { +WebGLFastSpriteBatch.prototype.stop = function () +{ this.flush(); }; /** * */ -WebGLFastSpriteBatch.prototype.start = function () { +WebGLFastSpriteBatch.prototype.start = function () +{ var gl = this.renderer.gl; // bind the main texture diff --git a/src/core/renderers/webgl/utils/WebGLGraphics.js b/src/core/renderers/webgl/utils/WebGLGraphics.js index 55f4911..ab8f46e 100644 --- a/src/core/renderers/webgl/utils/WebGLGraphics.js +++ b/src/core/renderers/webgl/utils/WebGLGraphics.js @@ -19,7 +19,8 @@ * @param graphics {Graphics} * @param renderer {WebGLRenderer} */ -WebGLGraphics.renderGraphics = function (graphics, renderer) {//projection, offset) { +WebGLGraphics.renderGraphics = function (graphics, renderer) {//projection, offset) +{ var gl = renderer.gl; var projection = renderer.projection, @@ -27,7 +28,8 @@ shader = renderer.shaderManager.primitiveShader, webGLData; - if (graphics.dirty) { + if (graphics.dirty) + { WebGLGraphics.updateGraphics(graphics, gl); } @@ -35,8 +37,10 @@ // This could be speeded up for sure! - for (var i = 0; i < webGL.data.length; i++) { - if (webGL.data[i].mode === 1) { + for (var i = 0; i < webGL.data.length; i++) + { + if (webGL.data[i].mode === 1) + { webGLData = webGL.data[i]; renderer.stencilManager.pushStencil(graphics, webGLData, renderer); @@ -46,7 +50,8 @@ renderer.stencilManager.popStencil(graphics, webGLData, renderer); } - else { + else + { webGLData = webGL.data[i]; @@ -84,12 +89,14 @@ * @param graphicsData {Graphics} The graphics object to update * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLGraphics.updateGraphics = function (graphics, gl) { +WebGLGraphics.updateGraphics = function (graphics, gl) +{ // get the contexts graphics object var webGL = graphics._webGL[gl.id]; // if the graphics object does not exist in the webGL context time to create it! - if (!webGL) { + if (!webGL) + { webGL = graphics._webGL[gl.id] = {lastIndex:0, data:[], gl:gl}; } @@ -99,11 +106,13 @@ var i; // if the user cleared the graphics object we will need to clear every object - if (graphics.clearDirty) { + if (graphics.clearDirty) + { graphics.clearDirty = false; // lop through and return all the webGLDatas to the object pool so than can be reused later on - for (i = 0; i < webGL.data.length; i++) { + for (i = 0; i < webGL.data.length; i++) + { var graphicsData = webGL.data[i]; graphicsData.reset(); WebGLGraphics.graphicsDataPool.push( graphicsData ); @@ -119,58 +128,72 @@ // loop through the graphics datas and construct each one.. // if the object is a complex fill then the new stencil buffer technique will be used // other wise graphics objects will be pushed into a batch.. - for (i = webGL.lastIndex; i < graphics.graphicsData.length; i++) { + for (i = webGL.lastIndex; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { // need to add the points the the graphics object.. data.points = data.shape.points.slice(); - if (data.shape.closed) { + if (data.shape.closed) + { // close the poly if the value is true! - if (data.points[0] !== data.points[data.points.length-2] || data.points[1] !== data.points[data.points.length-1]) { + if (data.points[0] !== data.points[data.points.length-2] || data.points[1] !== data.points[data.points.length-1]) + { data.points.push(data.points[0], data.points[1]); } } // MAKE SURE WE HAVE THE CORRECT TYPE.. - if (data.fill) { - if (data.points.length >= 6) { - if (data.points.length < 6 * 2) { + if (data.fill) + { + if (data.points.length >= 6) + { + if (data.points.length < 6 * 2) + { webGLData = WebGLGraphics.switchMode(webGL, 0); var canDrawUsingSimple = WebGLGraphics.buildPoly(data, webGLData); // console.log(canDrawUsingSimple); - if (!canDrawUsingSimple) { + if (!canDrawUsingSimple) + { // console.log("<>>>") webGLData = WebGLGraphics.switchMode(webGL, 1); WebGLGraphics.buildComplexPoly(data, webGLData); } } - else { + else + { webGLData = WebGLGraphics.switchMode(webGL, 1); WebGLGraphics.buildComplexPoly(data, webGLData); } } } - if (data.lineWidth > 0) { + if (data.lineWidth > 0) + { webGLData = WebGLGraphics.switchMode(webGL, 0); WebGLGraphics.buildLine(data, webGLData); } } - else { + else + { webGLData = WebGLGraphics.switchMode(webGL, 0); - if (data.type === CONST.SHAPES.RECT) { + if (data.type === CONST.SHAPES.RECT) + { WebGLGraphics.buildRectangle(data, webGLData); } - else if (data.type === CONST.SHAPES.CIRC || data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.CIRC || data.type === CONST.SHAPES.ELIP) + { WebGLGraphics.buildCircle(data, webGLData); } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { WebGLGraphics.buildRoundedRectangle(data, webGLData); } } @@ -179,10 +202,12 @@ } // upload all the dirty data... - for (i = 0; i < webGL.data.length; i++) { + for (i = 0; i < webGL.data.length; i++) + { webGLData = webGL.data[i]; - if (webGLData.dirty) { + if (webGLData.dirty) + { webGLData.upload(); } } @@ -194,18 +219,22 @@ * @param webGL {WebGLContext} * @param type {number} */ -WebGLGraphics.switchMode = function (webGL, type) { +WebGLGraphics.switchMode = function (webGL, type) +{ var webGLData; - if (!webGL.data.length) { + if (!webGL.data.length) + { webGLData = WebGLGraphics.graphicsDataPool.pop() || new WebGLGraphicsData(webGL.gl); webGLData.mode = type; webGL.data.push(webGLData); } - else { + else + { webGLData = webGL.data[webGL.data.length-1]; - if (webGLData.mode !== type || type === 1) { + if (webGLData.mode !== type || type === 1) + { webGLData = WebGLGraphics.graphicsDataPool.pop() || new WebGLGraphicsData(webGL.gl); webGLData.mode = type; webGL.data.push(webGLData); @@ -225,7 +254,8 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildRectangle = function (graphicsData, webGLData) { +WebGLGraphics.buildRectangle = function (graphicsData, webGLData) +{ // --- // // need to convert points to a nice regular data // @@ -235,7 +265,8 @@ var width = rectData.width; var height = rectData.height; - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -265,7 +296,8 @@ indices.push(vertPos, vertPos, vertPos+1, vertPos+2, vertPos+3, vertPos+3); } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = [x, y, @@ -289,7 +321,8 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildRoundedRectangle = function (graphicsData, webGLData) { +WebGLGraphics.buildRoundedRectangle = function (graphicsData, webGLData) +{ var rrectData = graphicsData.shape; var x = rrectData.x; var y = rrectData.y; @@ -305,7 +338,8 @@ recPoints = recPoints.concat(WebGLGraphics.quadraticBezierCurve(x + width, y + radius, x + width, y, x + width - radius, y)); recPoints = recPoints.concat(WebGLGraphics.quadraticBezierCurve(x + radius, y, x, y, x, y + radius)); - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -323,7 +357,8 @@ // var i = 0; - for (i = 0; i < triangles.length; i+=3) { + for (i = 0; i < triangles.length; i+=3) + { indices.push(triangles[i] + vecPos); indices.push(triangles[i] + vecPos); indices.push(triangles[i+1] + vecPos); @@ -332,12 +367,14 @@ } - for (i = 0; i < recPoints.length; i++) { + for (i = 0; i < recPoints.length; i++) + { verts.push(recPoints[i], recPoints[++i], r, g, b, alpha); } } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = recPoints; @@ -362,7 +399,8 @@ * @param toY {number} Destination point y * @return {number[]} */ -WebGLGraphics.quadraticBezierCurve = function (fromX, fromY, cpX, cpY, toX, toY) { +WebGLGraphics.quadraticBezierCurve = function (fromX, fromY, cpX, cpY, toX, toY) +{ var xa, ya, @@ -373,14 +411,16 @@ n = 20, points = []; - function getPt(n1 , n2, perc) { + function getPt(n1 , n2, perc) + { var diff = n2 - n1; return n1 + ( diff * perc ); } var j = 0; - for (var i = 0; i <= n; i++ ) { + for (var i = 0; i <= n; i++ ) + { j = i / n; // The Green Line @@ -406,7 +446,8 @@ * @param graphicsData {Graphics} The graphics object to draw * @param webGLData {object} */ -WebGLGraphics.buildCircle = function (graphicsData, webGLData) { +WebGLGraphics.buildCircle = function (graphicsData, webGLData) +{ // need to convert points to a nice regular data var circleData = graphicsData.shape; var x = circleData.x; @@ -415,11 +456,13 @@ var height; // TODO - bit hacky?? - if (graphicsData.type === CONST.SHAPES.CIRC) { + if (graphicsData.type === CONST.SHAPES.CIRC) + { width = circleData.radius; height = circleData.radius; } - else { + else + { width = circleData.width; height = circleData.height; } @@ -429,7 +472,8 @@ var i = 0; - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -444,7 +488,8 @@ indices.push(vecPos); - for (i = 0; i < totalSegs + 1 ; i++) { + for (i = 0; i < totalSegs + 1 ; i++) + { verts.push(x,y, r, g, b, alpha); verts.push(x + Math.sin(seg * i) * width, @@ -457,12 +502,14 @@ indices.push(vecPos-1); } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = []; - for (i = 0; i < totalSegs + 1; i++) { + for (i = 0; i < totalSegs + 1; i++) + { graphicsData.points.push(x + Math.sin(seg * i) * width, y + Math.cos(seg * i) * height); } @@ -481,18 +528,22 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildLine = function (graphicsData, webGLData) { +WebGLGraphics.buildLine = function (graphicsData, webGLData) +{ // TODO OPTIMISE! var i = 0; var points = graphicsData.points; - if (points.length === 0) { + if (points.length === 0) + { return; } // if the line width is an odd number add 0.5 to align to a whole pixel - if (graphicsData.lineWidth%2) { - for (i = 0; i < points.length; i++) { + if (graphicsData.lineWidth%2) + { + for (i = 0; i < points.length; i++) + { points[i] += 0.5; } } @@ -502,7 +553,8 @@ var lastPoint = new math.Point(points[points.length - 2], points[points.length - 1]); // if the first point is the last point - gonna have issues :) - if (firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) { + if (firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) + { // need to clone as we are going to slightly modify the shape.. points = points.slice(); @@ -562,7 +614,8 @@ verts.push(p1x + perpx , p1y + perpy, r, g, b, alpha); - for (i = 1; i < length-1; i++) { + for (i = 1; i < length-1; i++) + { p1x = points[(i-1)*2]; p1y = points[(i-1)*2 + 1]; @@ -599,7 +652,8 @@ denom = a1*b2 - a2*b1; - if (Math.abs(denom) < 0.1 ) { + if (Math.abs(denom) < 0.1 ) + { denom+=10.1; verts.push(p2x - perpx , p2y - perpy, @@ -618,7 +672,8 @@ pdist = (px -p2x) * (px -p2x) + (py -p2y) + (py -p2y); - if (pdist > 140 * 140) { + if (pdist > 140 * 140) + { perp3x = perpx - perp2x; perp3y = perpy - perp2y; @@ -639,7 +694,8 @@ indexCount++; } - else { + else + { verts.push(px , py); verts.push(r, g, b, alpha); @@ -672,7 +728,8 @@ indices.push(indexStart); - for (i = 0; i < indexCount; i++) { + for (i = 0; i < indexCount; i++) + { indices.push(indexStart++); } @@ -687,11 +744,13 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildComplexPoly = function (graphicsData, webGLData) { +WebGLGraphics.buildComplexPoly = function (graphicsData, webGLData) +{ //TODO - no need to copy this as it gets turned into a FLoat32Array anyways.. var points = graphicsData.points.slice(); - if (points.length < 6) { + if (points.length < 6) + { return; } @@ -711,7 +770,8 @@ var x,y; // get size.. - for (var i = 0; i < points.length; i+=2) { + for (var i = 0; i < points.length; i+=2) + { x = points[i]; y = points[i+1]; @@ -732,7 +792,8 @@ //TODO - this aint needed! var length = points.length / 2; - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { indices.push( i ); } @@ -746,10 +807,12 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildPoly = function (graphicsData, webGLData) { +WebGLGraphics.buildPoly = function (graphicsData, webGLData) +{ var points = graphicsData.points; - if (points.length < 6) { + if (points.length < 6) + { return; } // get first and last point.. figure out the middle! @@ -767,7 +830,8 @@ var triangles = utils.PolyK.Triangulate(points); - if (!triangles) { + if (!triangles) + { return false; } @@ -775,7 +839,8 @@ var i = 0; - for (i = 0; i < triangles.length; i+=3) { + for (i = 0; i < triangles.length; i+=3) + { indices.push(triangles[i] + vertPos); indices.push(triangles[i] + vertPos); indices.push(triangles[i+1] + vertPos); @@ -783,7 +848,8 @@ indices.push(triangles[i+2] + vertPos); } - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { verts.push(points[i * 2], points[i * 2 + 1], r, g, b, alpha); } diff --git a/src/core/renderers/webgl/utils/WebGLGraphicsData.js b/src/core/renderers/webgl/utils/WebGLGraphicsData.js index c56d05e..c739ba7 100644 --- a/src/core/renderers/webgl/utils/WebGLGraphicsData.js +++ b/src/core/renderers/webgl/utils/WebGLGraphicsData.js @@ -2,7 +2,8 @@ * @class * @private */ -function WebGLGraphicsData(gl) { +function WebGLGraphicsData(gl) +{ this.gl = gl; //TODO does this need to be split before uploding?? @@ -22,7 +23,8 @@ /** * */ -WebGLGraphicsData.prototype.reset = function () { +WebGLGraphicsData.prototype.reset = function () +{ this.points.length = 0; this.indices.length = 0; }; @@ -30,7 +32,8 @@ /** * */ -WebGLGraphicsData.prototype.upload = function () { +WebGLGraphicsData.prototype.upload = function () +{ var gl = this.gl; // this.lastIndex = graphics.graphicsData.length; diff --git a/src/core/renderers/webgl/utils/WebGLSpriteBatch.js b/src/core/renderers/webgl/utils/WebGLSpriteBatch.js index 96eaa52..55befbb 100644 --- a/src/core/renderers/webgl/utils/WebGLSpriteBatch.js +++ b/src/core/renderers/webgl/utils/WebGLSpriteBatch.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this sprite batch works for. */ -function WebGLSpriteBatch(renderer) { +function WebGLSpriteBatch(renderer) +{ /** * * @@ -88,7 +89,8 @@ */ this.lastIndexCount = 0; - for (var i=0, j=0; i < numIndices; i += 6, j += 4) { + 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; @@ -162,7 +164,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.setupContext(); }); } @@ -173,7 +176,8 @@ /** * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLSpriteBatch.prototype.setupContext = function () { +WebGLSpriteBatch.prototype.setupContext = function () +{ var gl = this.renderer.gl; // setup default shader @@ -198,7 +202,8 @@ /** * */ -WebGLSpriteBatch.prototype.begin = function () { +WebGLSpriteBatch.prototype.begin = function () +{ // this.shader = this.renderer.shaderManager.defaultShader; this.start(); @@ -206,19 +211,22 @@ /** */ -WebGLSpriteBatch.prototype.end = function () { +WebGLSpriteBatch.prototype.end = function () +{ this.flush(); }; /** * @param sprite {Sprite} the sprite to render when using this spritebatch */ -WebGLSpriteBatch.prototype.render = function (sprite) { +WebGLSpriteBatch.prototype.render = function (sprite) +{ var texture = sprite.texture; //TODO set blend modes.. // check texture.. - if (this.currentBatchSize >= this.size) { + if (this.currentBatchSize >= this.size) + { this.flush(); this.currentBaseTexture = texture.baseTexture; } @@ -227,7 +235,8 @@ var uvs = texture._uvs; // if the uvs have not updated then no point rendering just yet! - if (!uvs) { + if (!uvs) + { return; } @@ -237,7 +246,8 @@ var w0, w1, h0, h1; - if (texture.trim) { + 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; @@ -248,7 +258,8 @@ h0 = h1 + texture.crop.height; } - else { + else + { w0 = (texture.frame.width ) * (1-aX); w1 = (texture.frame.width ) * -aX; @@ -272,7 +283,8 @@ var colors = this.colors; var positions = this.positions; - if (this.renderer.roundPixels) { + if (this.renderer.roundPixels) + { // xy positions[index] = a * w1 + c * h1 + tx | 0; positions[index+1] = d * h1 + b * w1 + ty | 0; @@ -289,7 +301,8 @@ positions[index+15] = a * w1 + c * h0 + tx | 0; positions[index+16] = d * h0 + b * w1 + ty | 0; } - else { + else + { // xy positions[index] = a * w1 + c * h1 + tx; positions[index+1] = d * h1 + b * w1 + ty; @@ -338,11 +351,13 @@ * * @param sprite {TilingSprite} the tilingSprite to render */ -WebGLSpriteBatch.prototype.renderTilingSprite = function (tilingSprite) { +WebGLSpriteBatch.prototype.renderTilingSprite = function (tilingSprite) +{ var texture = tilingSprite.tilingTexture; // check texture.. - if (this.currentBatchSize >= this.size) { + if (this.currentBatchSize >= this.size) + { //return; this.flush(); this.currentBaseTexture = texture.baseTexture; @@ -351,7 +366,8 @@ // set the textures uvs temporarily // TODO create a separate texture so that we can tile part of a texture - if (!tilingSprite._uvs) { + if (!tilingSprite._uvs) + { tilingSprite._uvs = new TextureUvs(); } @@ -454,16 +470,19 @@ * Renders the content and empties the current batch. * */ -WebGLSpriteBatch.prototype.flush = function () { +WebGLSpriteBatch.prototype.flush = function () +{ // If the batch is length 0 then return as there is nothing to draw - if (this.currentBatchSize === 0) { + if (this.currentBatchSize === 0) + { return; } var gl = this.renderer.gl; var shader; - if (this.dirty) { + if (this.dirty) + { this.dirty = false; // bind the main texture gl.activeTexture(gl.TEXTURE0); @@ -482,10 +501,12 @@ } // upload the verts to the buffer - if (this.currentBatchSize > ( this.size * 0.5 ) ) { + if (this.currentBatchSize > ( this.size * 0.5 ) ) + { gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); } - else { + else + { var view = this.positions.subarray(0, this.currentBatchSize * this.vertByteSize); gl.bufferSubData(gl.ARRAY_BUFFER, 0, view); } @@ -502,7 +523,8 @@ var shaderSwap = false; var sprite; - for (var i = 0, j = this.currentBatchSize; i < j; i++) { + for (var i = 0, j = this.currentBatchSize; i < j; i++) + { sprite = this.sprites[i]; @@ -513,24 +535,28 @@ blendSwap = currentBlendMode !== nextBlendMode; shaderSwap = currentShader !== nextShader; // should I use uuidS??? - if (currentBaseTexture !== nextTexture || blendSwap || shaderSwap) { + if (currentBaseTexture !== nextTexture || blendSwap || shaderSwap) + { this.renderBatch(currentBaseTexture, batchSize, start); start = i; batchSize = 0; currentBaseTexture = nextTexture; - if (blendSwap) { + if (blendSwap) + { currentBlendMode = nextBlendMode; this.renderer.blendModeManager.setBlendMode( currentBlendMode ); } - if (shaderSwap) { + if (shaderSwap) + { currentShader = nextShader; shader = currentShader.shaders ? currentShader.shaders[gl.id] : currentShader; - if (!shader) { + if (!shader) + { shader = new Shader(gl, null, currentShader.fragmentSrc, currentShader.uniforms); currentShader.shaders[gl.id] = shader; } @@ -538,7 +564,8 @@ // set shader function??? this.renderer.shaderManager.setShader(shader); - if (shader.dirty) { + if (shader.dirty) + { shader.syncUniforms(); } @@ -569,17 +596,21 @@ * @param size {number} * @param startIndex {number} */ -WebGLSpriteBatch.prototype.renderBatch = function (texture, size, startIndex) { - if (size === 0) { +WebGLSpriteBatch.prototype.renderBatch = function (texture, size, startIndex) +{ + if (size === 0) + { return; } var gl = this.renderer.gl; - if (!texture._glTextures[gl.id]) { + if (!texture._glTextures[gl.id]) + { this.renderer.updateTexture(texture); } - else { + else + { // bind the current texture gl.bindTexture(gl.TEXTURE_2D, texture._glTextures[gl.id]); } @@ -594,7 +625,8 @@ /** * */ -WebGLSpriteBatch.prototype.stop = function () { +WebGLSpriteBatch.prototype.stop = function () +{ this.flush(); this.dirty = true; }; @@ -602,7 +634,8 @@ /** * */ -WebGLSpriteBatch.prototype.start = function () { +WebGLSpriteBatch.prototype.start = function () +{ this.dirty = true; }; @@ -610,7 +643,8 @@ * Destroys the SpriteBatch. * */ -WebGLSpriteBatch.prototype.destroy = function () { +WebGLSpriteBatch.prototype.destroy = function () +{ this.renderer.gl.deleteBuffer(this.vertexBuffer); this.renderer.gl.deleteBuffer(this.indexBuffer); diff --git a/src/core/textures/BaseTexture.js b/src/core/textures/BaseTexture.js index 2bf77d4..513d358 100644 --- a/src/core/textures/BaseTexture.js +++ b/src/core/textures/BaseTexture.js @@ -10,7 +10,8 @@ * @param source {Image|Canvas} the source object of the texture. * @param [scaleMode=scaleModes.DEFAULT] {number} See {@link scaleModes} for possible values */ -function BaseTexture(source, scaleMode) { +function BaseTexture(source, scaleMode) +{ this.uuid = utils.uuid(); /** @@ -123,7 +124,8 @@ this._needsUpdate = false; // if no source passed don't try to load - if (source) { + if (source) + { this.loadSource(source); } @@ -149,13 +151,16 @@ Object.defineProperties(BaseTexture.prototype, { needsUpdate: { - get: function () { + get: function () + { return this._needsUpdate; }, - set: function (val) { + set: function (val) + { this._needsUpdate = val; - if (val) { + if (val) + { this.emit('update', this); } } @@ -171,9 +176,11 @@ * * The logic state after calling `loadSource` directly or indirectly (eg. `fromImage`, `new BaseTexture`) is: * - * if (texture.hasLoaded) { + * if (texture.hasLoaded) + { * // texture ready for use - * } else if (texture.isLoading) { + * } else if (texture.isLoading) + { * // listen to 'loaded' and/or 'error' events on texture * } else { * // not loading, not going to load UNLESS the source is reloaded @@ -183,12 +190,14 @@ * @protected * @param source {Image|Canvas} the source object of the texture. */ -BaseTexture.prototype.loadSource = function (source) { +BaseTexture.prototype.loadSource = function (source) +{ var wasLoading = this.isLoading; this.hasLoaded = false; this.isLoading = false; - if (wasLoading && this.source) { + if (wasLoading && this.source) + { this.source.onload = null; this.source.onerror = null; } @@ -196,20 +205,24 @@ this.source = source; // Apply source if loaded. Otherwise setup appropriate loading monitors. - if ((this.source.complete || this.source.getContext) && this.source.width && this.source.height) { + if ((this.source.complete || this.source.getContext) && this.source.width && this.source.height) + { this._sourceLoaded(); } - else if(!source.getContext) { + else if(!source.getContext) + { // Image fail / not ready this.isLoading = true; var scope = this; - source.onload = function () { + source.onload = function () + { source.onload = null; source.onerror = null; - if(!scope.isLoading) { + if(!scope.isLoading) + { return; } @@ -219,11 +232,13 @@ scope.emit('loaded', scope); }; - source.onerror = function () { + source.onerror = function () + { source.onload = null; source.onerror = null; - if(!scope.isLoading) { + if(!scope.isLoading) + { return; } @@ -234,24 +249,29 @@ // Per http://www.w3.org/TR/html5/embedded-content-0.html#the-img-element // "The value of `complete` can thus change while a script is executing." // So complete needs to be re-checked after the callbacks have been added.. - if (source.complete) { + if (source.complete) + { this.isLoading = false; // ..and if we're complete now, no need for callbacks source.onload = null; source.onerror = null; - if (source.width && source.height) { + if (source.width && source.height) + { this._sourceLoaded(); // If any previous subscribers possible - if (wasLoading) { + if (wasLoading) + { this.emit('loaded', this); } } - else { + else + { // If any previous subscribers possible - if (wasLoading) { + if (wasLoading) + { this.emit('error', this); } } @@ -265,7 +285,8 @@ * * @private */ -BaseTexture.prototype._sourceLoaded = function () { +BaseTexture.prototype._sourceLoaded = function () +{ this.hasLoaded = true; this.width = this.source.naturalWidth || this.source.width; @@ -278,16 +299,20 @@ * Destroys this base texture * */ -BaseTexture.prototype.destroy = function () { - if (this.imageUrl) { +BaseTexture.prototype.destroy = function () +{ + if (this.imageUrl) + { delete utils.BaseTextureCache[this.imageUrl]; delete utils.TextureCache[this.imageUrl]; this.imageUrl = null; - if (!navigator.isCocoonJS) { + if (!navigator.isCocoonJS) + { this.source.src = ''; } } - else if (this.source && this.source._pixiId) { + else if (this.source && this.source._pixiId) + { delete utils.BaseTextureCache[this.source._pixiId]; } this.source = null; @@ -301,7 +326,8 @@ * memory again. * */ -BaseTexture.prototype.dispose = function () { +BaseTexture.prototype.dispose = function () +{ this.emit('dispose', this); }; @@ -311,7 +337,8 @@ * * @param newSrc {string} the path of the image */ -BaseTexture.prototype.updateSourceImage = function (newSrc) { +BaseTexture.prototype.updateSourceImage = function (newSrc) +{ this.source.src = newSrc; this.loadSource(this.source); }; @@ -326,18 +353,22 @@ * @param [scaleMode=scaleModes.DEFAULT] {number} See {@link scaleModes} for possible values * @return BaseTexture */ -BaseTexture.fromImage = function (imageUrl, crossorigin, scaleMode) { +BaseTexture.fromImage = function (imageUrl, crossorigin, scaleMode) +{ var baseTexture = utils.BaseTextureCache[imageUrl]; - if (crossorigin === undefined && imageUrl.indexOf('data:') !== 0) { + if (crossorigin === undefined && imageUrl.indexOf('data:') !== 0) + { crossorigin = true; } - if (!baseTexture) { + if (!baseTexture) + { // new Image() breaks tex loading in some versions of Chrome. // See https://code.google.com/p/chromium/issues/detail?id=238071 var image = new Image();//document.createElement('img'); - if (crossorigin) { + if (crossorigin) + { image.crossOrigin = ''; } @@ -347,7 +378,8 @@ utils.BaseTextureCache[imageUrl] = baseTexture; // if there is an @2x at the end of the url we are going to assume its a highres image - if ( imageUrl.indexOf(CONST.RETINA_PREFIX + '.') !== -1) { + if ( imageUrl.indexOf(CONST.RETINA_PREFIX + '.') !== -1) + { baseTexture.resolution = 2; } } @@ -363,14 +395,17 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return BaseTexture */ -BaseTexture.fromCanvas = function (canvas, scaleMode) { - if (!canvas._pixiId) { +BaseTexture.fromCanvas = function (canvas, scaleMode) +{ + if (!canvas._pixiId) + { canvas._pixiId = 'canvas_' + utils.uuid(); } var baseTexture = utils.BaseTextureCache[canvas._pixiId]; - if (!baseTexture) { + if (!baseTexture) + { baseTexture = new BaseTexture(canvas, scaleMode); utils.BaseTextureCache[canvas._pixiId] = baseTexture; } diff --git a/src/core/textures/RenderTexture.js b/src/core/textures/RenderTexture.js index 6dad20f..53ae796 100644 --- a/src/core/textures/RenderTexture.js +++ b/src/core/textures/RenderTexture.js @@ -46,8 +46,10 @@ * @param [scaleMode] {number} See {@link scaleModes} for possible values * @param [resolution=1] {number} The resolution of the texture being generated */ -function RenderTexture(renderer, width, height, scaleMode, resolution) { - if (!renderer) { +function RenderTexture(renderer, width, height, scaleMode, resolution) +{ + if (!renderer) + { throw new Error('Unable to create RenderTexture, you must pass a renderer into the constructor.'); } @@ -133,7 +135,8 @@ */ this.renderer = renderer; - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { var gl = this.renderer.gl; this.textureBuffer = new FilterTexture(gl, this.width * this.resolution, this.height * this.resolution, this.baseTexture.scaleMode); @@ -142,7 +145,8 @@ this.render = this.renderWebGL; this.projection = new math.Point(this.width*0.5, -this.height*0.5); } - else { + else + { this.render = this.renderCanvas; this.textureBuffer = new CanvasBuffer(this.width* this.resolution, this.height* this.resolution); this.baseTexture.source = this.textureBuffer.canvas; @@ -167,8 +171,10 @@ * @param height {number} The height to resize to. * @param updateBase {boolean} Should the baseTexture.width and height values be resized as well? */ -RenderTexture.prototype.resize = function (width, height, updateBase) { - if (width === this.width && height === this.height) { +RenderTexture.prototype.resize = function (width, height, updateBase) +{ + if (width === this.width && height === this.height) + { return; } @@ -177,17 +183,20 @@ this.width = this.frame.width = this.crop.width = width; this.height = this.frame.height = this.crop.height = height; - if (updateBase) { + if (updateBase) + { this.baseTexture.width = this.width; this.baseTexture.height = this.height; } - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { this.projection.x = this.width / 2; this.projection.y = -this.height / 2; } - if (!this.valid) { + if (!this.valid) + { return; } @@ -198,12 +207,15 @@ * Clears the RenderTexture. * */ -RenderTexture.prototype.clear = function () { - if (!this.valid) { +RenderTexture.prototype.clear = function () +{ + if (!this.valid) + { return; } - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { this.renderer.gl.bindFramebuffer(this.renderer.gl.FRAMEBUFFER, this.textureBuffer.frameBuffer); } @@ -220,19 +232,23 @@ * @param [restoreWorldTransform=true] {boolean} If true the displayObject's worldTransform/worldAlpha and all children * transformations will be restored. Not restoring this information will be a little faster. */ -RenderTexture.prototype.renderWebGL = function (displayObject, matrix, clear, restoreWorldTransform) { - if (!this.valid) { +RenderTexture.prototype.renderWebGL = function (displayObject, matrix, clear, restoreWorldTransform) +{ + if (!this.valid) + { return; } - if (typeof restoreWorldTransform === 'undefined') { + if (typeof restoreWorldTransform === 'undefined') + { restoreWorldTransform = true; } var tempAlpha, tempTransform; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { tempAlpha = displayObject.worldAlpha; tempTransform = displayObject.worldTransform.toArray(); } @@ -245,7 +261,8 @@ wt.identity(); wt.translate(0, this.projection.y * 2); - if (matrix) { + if (matrix) + { wt.append(matrix); } @@ -258,7 +275,8 @@ var children = displayObject.children; var i, j; - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } @@ -269,7 +287,8 @@ gl.bindFramebuffer(gl.FRAMEBUFFER, this.textureBuffer.frameBuffer ); - if (clear) { + if (clear) + { this.textureBuffer.clear(); } @@ -279,11 +298,13 @@ this.renderer.spriteBatch.dirty = true; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { displayObject.worldAlpha = tempAlpha; displayObject.worldTransform.fromArray(tempTransform); - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } } @@ -300,26 +321,31 @@ * @param [restoreWorldTransform=true] {boolean} If true the displayObject's worldTransform/worldAlpha and all children * transformations will be restored. Not restoring this information will be a little faster. */ -RenderTexture.prototype.renderCanvas = function (displayObject, matrix, clear, restoreWorldTransform) { - if (!this.valid) { +RenderTexture.prototype.renderCanvas = function (displayObject, matrix, clear, restoreWorldTransform) +{ + if (!this.valid) + { return; } - if (typeof restoreWorldTransform === 'undefined') { + if (typeof restoreWorldTransform === 'undefined') + { restoreWorldTransform = true; } var tempAlpha, tempTransform; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { tempAlpha = displayObject.worldAlpha; tempTransform = displayObject.worldTransform.toArray(); } var wt = displayObject.worldTransform; wt.identity(); - if (matrix) { + if (matrix) + { wt.append(matrix); } @@ -330,11 +356,13 @@ var children = displayObject.children; var i, j; - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } - if (clear) { + if (clear) + { this.textureBuffer.clear(); } @@ -348,11 +376,13 @@ this.renderer.resolution = realResolution; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { displayObject.worldAlpha = tempAlpha; displayObject.worldTransform.fromArray(tempTransform); - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } } @@ -363,7 +393,8 @@ * * @return {Image} */ -RenderTexture.prototype.getImage = function () { +RenderTexture.prototype.getImage = function () +{ var image = new Image(); image.src = this.getBase64(); return image; @@ -374,7 +405,8 @@ * * @return {string} A base64 encoded string of the texture. */ -RenderTexture.prototype.getBase64 = function () { +RenderTexture.prototype.getBase64 = function () +{ return this.getCanvas().toDataURL(); }; @@ -383,8 +415,10 @@ * * @return {HTMLCanvasElement} A Canvas element with the texture rendered on. */ -RenderTexture.prototype.getCanvas = function () { - if (this.renderer.type === CONST.WEBGL_RENDERER) { +RenderTexture.prototype.getCanvas = function () +{ + if (this.renderer.type === CONST.WEBGL_RENDERER) + { var gl = this.renderer.gl; var width = this.textureBuffer.width; var height = this.textureBuffer.height; @@ -403,7 +437,8 @@ return tempCanvas.canvas; } - else { + else + { return this.textureBuffer.canvas; } }; diff --git a/src/core/textures/Texture.js b/src/core/textures/Texture.js index 3c65909..e97f0aa 100644 --- a/src/core/textures/Texture.js +++ b/src/core/textures/Texture.js @@ -17,7 +17,8 @@ * @param [crop] {Rectangle} The area of original texture * @param [trim] {Rectangle} Trimmed texture rectangle */ -function Texture(baseTexture, frame, crop, trim) { +function Texture(baseTexture, frame, crop, trim) +{ /** * Does this Texture have any frame data assigned to it? * @@ -25,12 +26,14 @@ */ this.noFrame = false; - if (!frame) { + if (!frame) + { this.noFrame = true; frame = new math.Rectangle(0, 0, 1, 1); } - if (baseTexture instanceof Texture) { + if (baseTexture instanceof Texture) + { baseTexture = baseTexture.baseTexture; } @@ -100,13 +103,16 @@ */ this.crop = crop || new math.Rectangle(0, 0, 1, 1); - if (baseTexture.hasLoaded) { - if (this.noFrame) { + if (baseTexture.hasLoaded) + { + if (this.noFrame) + { frame = new math.Rectangle(0, 0, baseTexture.width, baseTexture.height); } this.frame = frame; } - else { + else + { baseTexture.addEventListener('loaded', this.onBaseTextureLoaded.bind(this)); } } @@ -118,19 +124,23 @@ Object.defineProperties(Texture.prototype, { needsUpdate: { - get: function () { + get: function () + { return this.baseTexture.needsUpdate; }, - set: function (val) { + set: function (val) + { this.baseTexture.needsUpdate = val; } }, frame: { - get: function () { + get: function () + { return this._frame; }, - set: function (frame) { + set: function (frame) + { this._frame = frame; this.noFrame = false; @@ -143,20 +153,23 @@ 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 (!this.trim && (frame.x + frame.width > this.baseTexture.width || frame.y + frame.height > this.baseTexture.height)) + { throw new Error('Texture Error: frame does not fit inside the base Texture dimensions ' + this); } this.valid = frame && frame.width && frame.height && this.baseTexture.source && this.baseTexture.hasLoaded; - if (this.trim) { + 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) { + if (this.valid) + { this._updateUvs(); } } @@ -168,11 +181,13 @@ * * @private */ -Texture.prototype.onBaseTextureLoaded = function () { +Texture.prototype.onBaseTextureLoaded = function () +{ var baseTexture = this.baseTexture; baseTexture.removeEventListener('loaded', this.onLoaded); - if (this.noFrame) { + if (this.noFrame) + { this.frame = new math.Rectangle(0, 0, baseTexture.width, baseTexture.height); } @@ -184,8 +199,10 @@ * * @param destroyBase {boolean} Whether to destroy the base texture as well */ -Texture.prototype.destroy = function (destroyBase) { - if (destroyBase) { +Texture.prototype.destroy = function (destroyBase) +{ + if (destroyBase) + { this.baseTexture.destroy(); } @@ -197,8 +214,10 @@ * * @private */ -Texture.prototype._updateUvs = function () { - if (!this._uvs) { +Texture.prototype._updateUvs = function () +{ + if (!this._uvs) + { this._uvs = new TextureUvs(); } @@ -229,10 +248,12 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return Texture */ -Texture.fromImage = function (imageUrl, crossorigin, scaleMode) { +Texture.fromImage = function (imageUrl, crossorigin, scaleMode) +{ var texture = utils.TextureCache[imageUrl]; - if (!texture) { + if (!texture) + { texture = new Texture(BaseTexture.fromImage(imageUrl, crossorigin, scaleMode)); utils.TextureCache[imageUrl] = texture; } @@ -248,9 +269,11 @@ * @param frameId {string} The frame id of the texture * @return Texture */ -Texture.fromFrame = function (frameId) { +Texture.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache '); } return texture; @@ -264,7 +287,8 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return {Texture} */ -Texture.fromCanvas = function (canvas, scaleMode) { +Texture.fromCanvas = function (canvas, scaleMode) +{ return new Texture(BaseTexture.fromCanvas(canvas, scaleMode)); }; @@ -276,7 +300,8 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return {Texture} A Texture */ -Texture.fromVideo = function (video, scaleMode) { +Texture.fromVideo = function (video, scaleMode) +{ return new Texture(VideoBaseTexture.baseTextureFromVideo(video, scaleMode)); }; @@ -287,7 +312,8 @@ * @param texture {Texture} The Texture to add to the cache. * @param id {string} The id that the texture will be stored against. */ -Texture.addTextureToCache = function (texture, id) { +Texture.addTextureToCache = function (texture, id) +{ utils.TextureCache[id] = texture; }; @@ -298,7 +324,8 @@ * @param id {string} The id of the texture to be removed * @return {Texture} The texture that was removed */ -Texture.removeTextureFromCache = function (id) { +Texture.removeTextureFromCache = function (id) +{ var texture = utils.TextureCache[id]; delete utils.TextureCache[id]; diff --git a/src/core/textures/TextureUvs.js b/src/core/textures/TextureUvs.js index b9bbb58..5424d52 100644 --- a/src/core/textures/TextureUvs.js +++ b/src/core/textures/TextureUvs.js @@ -1,4 +1,5 @@ -function TextureUvs() { +function TextureUvs() +{ this.x0 = 0; this.y0 = 0; diff --git a/src/core/textures/VideoBaseTexture.js b/src/core/textures/VideoBaseTexture.js index e3e0c5a..1a826a9 100644 --- a/src/core/textures/VideoBaseTexture.js +++ b/src/core/textures/VideoBaseTexture.js @@ -12,15 +12,18 @@ * @param source {HTMLVideoElement} * @param [scaleMode] {number} See {@link scaleModes} for possible values */ -function VideoBaseTexture(source, scaleMode) { - if (!source){ +function VideoBaseTexture(source, scaleMode) +{ + if (!source) + { throw new Error('No video source element specified.'); } // hook in here to check if video is already available. // BaseTexture looks for a source.complete boolean, plus width & height. - if ((source.readyState === source.HAVE_ENOUGH_DATA || source.readyState === source.HAVE_FUTURE_DATA) && source.width && source.height) { + if ((source.readyState === source.HAVE_ENOUGH_DATA || source.readyState === source.HAVE_FUTURE_DATA) && source.width && source.height) + { source.complete = true; } @@ -31,7 +34,8 @@ this._boundOnUpdate = this._onUpdate.bind(this); this._boundOnCanPlay = this._onCanPlay.bind(this); - if (!source.complete) { + if (!source.complete) + { source.addEventListener('canplay', this._boundOnCanPlay); source.addEventListener('canplaythrough', this._boundOnCanPlay); @@ -47,28 +51,35 @@ VideoBaseTexture.prototype.constructor = VideoBaseTexture; module.exports = VideoBaseTexture; -VideoBaseTexture.prototype._onUpdate = function () { - if (this.autoUpdate) { +VideoBaseTexture.prototype._onUpdate = function () +{ + if (this.autoUpdate) + { window.requestAnimationFrame(this._boundOnUpdate); this.needsUpdate = true; } }; -VideoBaseTexture.prototype._onPlayStart = function () { - if (!this.autoUpdate) { +VideoBaseTexture.prototype._onPlayStart = function () +{ + if (!this.autoUpdate) + { window.requestAnimationFrame(this._boundOnUpdate); this.autoUpdate = true; } }; -VideoBaseTexture.prototype._onPlayStop = function () { +VideoBaseTexture.prototype._onPlayStop = function () +{ this.autoUpdate = false; }; -VideoBaseTexture.prototype._onCanPlay = function () { +VideoBaseTexture.prototype._onCanPlay = function () +{ this.hasLoaded = true; - if (this.source) { + if (this.source) + { this.source.removeEventListener('canplay', this._boundOnCanPlay); this.source.removeEventListener('canplaythrough', this._boundOnCanPlay); @@ -78,15 +89,18 @@ this.source.play(); // prevent multiple loaded dispatches.. - if(!this.__loaded){ + if(!this.__loaded) + { this.__loaded = true; this.emit('loaded', this); } } }; -VideoBaseTexture.prototype.destroy = function () { - if (this.source && this.source._pixiId) { +VideoBaseTexture.prototype.destroy = function () +{ + if (this.source && this.source._pixiId) + { utils.BaseTextureCache[ this.source._pixiId ] = null; delete utils.BaseTextureCache[ this.source._pixiId ]; @@ -105,14 +119,17 @@ * @param scaleMode {number} See {@link scaleModes} for possible values * @return {VideoBaseTexture} */ -VideoBaseTexture.fromVideo = function (video, scaleMode) { - if (!video._pixiId) { +VideoBaseTexture.fromVideo = function (video, scaleMode) +{ + if (!video._pixiId) + { video._pixiId = 'video_' + utils.uuid(); } var baseTexture = utils.BaseTextureCache[video._pixiId]; - if (!baseTexture) { + if (!baseTexture) + { baseTexture = new VideoBaseTexture(video, scaleMode); utils.BaseTextureCache[ video._pixiId ] = baseTexture; } @@ -147,17 +164,21 @@ * @param scaleMode {number} See {@link scaleModes} for possible values * @return {VideoBaseTexture} */ -VideoBaseTexture.fromUrl = function (videoSrc, scaleMode) { +VideoBaseTexture.fromUrl = function (videoSrc, scaleMode) +{ var video = document.createElement('video'); // array of objects or strings - if (Array.isArray(videoSrc)) { - for (var i = 0; i < videoSrc.length; ++i) { + if (Array.isArray(videoSrc)) + { + for (var i = 0; i < videoSrc.length; ++i) + { video.appendChild(createSource(videoSrc.src || videoSrc, videoSrc.mime)); } } // single object or string - else { + else + { video.appendChild(createSource(videoSrc.src || videoSrc, videoSrc.mime)); } @@ -169,8 +190,10 @@ VideoBaseTexture.fromUrls = VideoBaseTexture.fromUrl; -function createSource(path, type) { - if (!type) { +function createSource(path, type) +{ + if (!type) + { type = 'video/' + path.substr(path.lastIndexOf('.') + 1); } diff --git a/src/core/utils/EventData.js b/src/core/utils/EventData.js index 5d55a22..8cdf701 100644 --- a/src/core/utils/EventData.js +++ b/src/core/utils/EventData.js @@ -7,7 +7,8 @@ * @param name {string} The string name of the event that was triggered * @param data {object} Arbitrary event data to pass along */ -function EventData(target, name, data) { +function EventData(target, name, data) +{ // for duck typing in the ".on()" function this.__isEventObject = true; @@ -71,7 +72,8 @@ * Stops the propagation of events up the scene graph (prevents bubbling). * */ -EventData.prototype.stopPropagation = function stopPropagation() { +EventData.prototype.stopPropagation = function stopPropagation() +{ this.stopped = true; }; @@ -79,6 +81,7 @@ * Stops the propagation of events to sibling listeners (no longer calls any listeners). * */ -EventData.prototype.stopImmediatePropagation = function stopImmediatePropagation() { +EventData.prototype.stopImmediatePropagation = function stopImmediatePropagation() +{ this.stoppedImmediate = true; }; diff --git a/src/core/utils/EventTarget.js b/src/core/utils/EventTarget.js index 7ae8820..671a151 100644 --- a/src/core/utils/EventTarget.js +++ b/src/core/utils/EventTarget.js @@ -13,14 +13,16 @@ * var em = new MyEmitter(); * em.emit('eventName', 'some data', 'some more data', {}, null, ...); */ -function eventTarget(obj) { +function eventTarget(obj) +{ /** * Return a list of assigned event listeners. * * @param eventName {string} The events that should be listed. * @return {Array} An array of listener functions */ - obj.listeners = function listeners(eventName) { + obj.listeners = function listeners(eventName) + { this._listeners = this._listeners || {}; return this._listeners[eventName] ? this._listeners[eventName].slice() : []; @@ -33,22 +35,26 @@ * @param eventName {string} The name of the event. * @return {boolean} Indication if we've emitted an event. */ - obj.emit = obj.dispatchEvent = function emit(eventName, data) { + obj.emit = obj.dispatchEvent = function emit(eventName, data) + { this._listeners = this._listeners || {}; // fast return when there are no listeners - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return; } //backwards compat with old method ".emit({ type: 'something' })" - if (typeof eventName === 'object') { + if (typeof eventName === 'object') + { data = eventName; eventName = eventName.type; } //ensure we are using a real pixi event - if (!data || data.__isEventObject !== true) { + if (!data || data.__isEventObject !== true) + { data = new EventData(this, eventName, data); } @@ -58,23 +64,27 @@ fn = listeners[0], i; - for (i = 0; i < length; fn = listeners[++i]) { + for (i = 0; i < length; fn = listeners[++i]) + { //call the event listener fn.call(this, data); //if "stopImmediatePropagation" is called, stop calling sibling events - if (data.stoppedImmediate) { + if (data.stoppedImmediate) + { return this; } } //if "stopPropagation" is called then don't bubble the event - if (data.stopped) { + if (data.stopped) + { return this; } //bubble this event up the scene graph - if (this.parent && this.parent.emit) { + if (this.parent && this.parent.emit) + { this.parent.emit.call(this.parent, eventName, data); } @@ -88,7 +98,8 @@ * @param eventName {string} Name of the event. * @param callback {Functon} fn Callback function. */ - obj.on = obj.addEventListener = function on(eventName, fn) { + obj.on = obj.addEventListener = function on(eventName, fn) + { this._listeners = this._listeners || {}; (this._listeners[eventName] = this._listeners[eventName] || []) @@ -103,11 +114,13 @@ * @param eventName {string} Name of the event. * @param callback {Function} Callback function. */ - obj.once = function once(eventName, fn) { + obj.once = function once(eventName, fn) + { this._listeners = this._listeners || {}; var self = this; - function onceHandlerWrapper() { + function onceHandlerWrapper() + { fn.apply(self.off(eventName, onceHandlerWrapper), arguments); } onceHandlerWrapper._originalHandler = fn; @@ -122,23 +135,28 @@ * @param eventName {string} The event we want to remove. * @param callback {Function} The listener that we need to find. */ - obj.off = obj.removeEventListener = function off(eventName, fn) { + obj.off = obj.removeEventListener = function off(eventName, fn) + { this._listeners = this._listeners || {}; - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return this; } var list = this._listeners[eventName], i = fn ? list.length : 0; - while(i-- > 0) { - if (list[i] === fn || list[i]._originalHandler === fn) { + while(i-- > 0) + { + if (list[i] === fn || list[i]._originalHandler === fn) + { list.splice(i, 1); } } - if (list.length === 0) { + if (list.length === 0) + { delete this._listeners[eventName]; } @@ -150,10 +168,12 @@ * * @param eventName {string} The event you want to remove all listeners for. */ - obj.removeAllListeners = function removeAllListeners(eventName) { + obj.removeAllListeners = function removeAllListeners(eventName) + { this._listeners = this._listeners || {}; - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return this; } @@ -169,7 +189,8 @@ * * @param object {object} The obj to mix into */ - mixin: function mixin(obj) { + mixin: function mixin(obj) + { eventTarget(obj); } }; diff --git a/src/core/utils/PolyK.js b/src/core/utils/PolyK.js index 7325141..5e20c2b 100644 --- a/src/core/utils/PolyK.js +++ b/src/core/utils/PolyK.js @@ -47,7 +47,8 @@ * Triangulates shapes for webGL graphic fills. * */ -PolyK.Triangulate = function (p) { +PolyK.Triangulate = function (p) +{ var sign = true; var n = p.length >> 1; @@ -59,7 +60,8 @@ i = 0; var al = n; - while(al > 3) { + while(al > 3) + { var i0 = avl[(i+0)%al]; var i1 = avl[(i+1)%al]; var i2 = avl[(i+2)%al]; @@ -69,29 +71,35 @@ var cx = p[2*i2], cy = p[2*i2+1]; var earFound = false; - if (PolyK._convex(ax, ay, bx, by, cx, cy, sign)) { + if (PolyK._convex(ax, ay, bx, by, cx, cy, sign)) + { earFound = true; - for (var j = 0; j < al; j++) { + for (var j = 0; j < al; j++) + { var vi = avl[j]; if (vi === i0 || vi === i1 || vi === i2) continue; - if (PolyK._PointInTriangle(p[2*vi], p[2*vi+1], ax, ay, bx, by, cx, cy)) { + if (PolyK._PointInTriangle(p[2*vi], p[2*vi+1], ax, ay, bx, by, cx, cy)) + { earFound = false; break; } } } - if (earFound) { + if (earFound) + { tgs.push(i0, i1, i2); avl.splice((i+1)%al, 1); al--; i = 0; } - else if (i++ > 3*al) { + else if (i++ > 3*al) + { // need to flip flip reverse it! // reset! - if (sign) { + if (sign) + { tgs = []; avl = []; for (i = 0; i < n; i++) avl.push(i); @@ -101,7 +109,8 @@ sign = false; } - else { + else + { // window.console.log("PIXI Warning: shape too complex to fill"); return null; } @@ -126,7 +135,8 @@ * @private * @return {boolean} */ -PolyK._PointInTriangle = function (px, py, ax, ay, bx, by, cx, cy) { +PolyK._PointInTriangle = function (px, py, ax, ay, bx, by, cx, cy) +{ var v0x = cx-ax; var v0y = cy-ay; var v1x = bx-ax; @@ -154,6 +164,7 @@ * @private * @return {boolean} */ -PolyK._convex = function (ax, ay, bx, by, cx, cy, sign) { +PolyK._convex = function (ax, ay, bx, by, cx, cy, sign) +{ return ((ay-by)*(cx-bx) + (bx-ax)*(cy-by) >= 0) === sign; }; diff --git a/src/core/utils/index.js b/src/core/utils/index.js index ade9831..bfae7ae 100644 --- a/src/core/utils/index.js +++ b/src/core/utils/index.js @@ -16,7 +16,8 @@ * * @return {number} The next uuid to use. */ - uuid: function () { + uuid: function () + { return ++utils._uid; }, @@ -26,7 +27,8 @@ * @param hex {number} * @return {number[]} An array representing the [R, G, B] of the color. */ - hex2rgb: function (hex, out) { + hex2rgb: function (hex, out) + { out = out || []; out[0] = (hex >> 16 & 0xFF) / 255; @@ -42,7 +44,8 @@ * @param hex {number} * @return {string} The string color. */ - hex2string: function (hex) { + hex2string: function (hex) + { hex = hex.toString(16); hex = '000000'.substr(0, 6 - hex.length) + hex; @@ -55,7 +58,8 @@ * @param rgb {number[]} * @return {number} The color number */ - rgb2hex: function (rgb) { + rgb2hex: function (rgb) + { return ((rgb[0]*255 << 16) + (rgb[1]*255 << 8) + rgb[2]*255); }, @@ -64,8 +68,10 @@ * * @return {boolean} whether they are supported */ - canUseNewCanvasBlendModes: function () { - if (typeof document === 'undefined') { + canUseNewCanvasBlendModes: function () + { + if (typeof document === 'undefined') + { return false; } @@ -93,15 +99,19 @@ * @param number {number} * @return {number} the closest number that is a power of two */ - getNextPowerOfTwo: function (number) { + getNextPowerOfTwo: function (number) + { // see: http://en.wikipedia.org/wiki/Power_of_two#Fast_algorithm_to_check_if_a_positive_number_is_a_power_of_two - if (number > 0 && (number & (number - 1)) === 0) { + if (number > 0 && (number & (number - 1)) === 0) + { return number; } - else { + else + { var result = 1; - while (result < number) { + while (result < number) + { result <<= 1; } @@ -116,7 +126,8 @@ * @param height {number} * @return {boolean} */ - isPowerOfTwo: function (width, height) { + isPowerOfTwo: function (width, height) + { return (width > 0 && (width & (width - 1)) === 0 && height > 0 && (height & (height - 1)) === 0); }, @@ -130,12 +141,15 @@ * @constant * @static */ - sayHello: function (type) { - if (utils._saidHello) { + sayHello: function (type) + { + if (utils._saidHello) + { return; } - if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) { + if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) + { var args = [ '%c %c %c Pixi.js ' + CONST.VERSION + ' - ' + type + ' %c ' + ' %c ' + ' http://www.pixijs.com/ %c %c ♥%c♥%c♥ ', 'background: #ff66a5', @@ -151,7 +165,8 @@ console.log.apply(console, args); //jshint ignore:line } - else if (window.console) { + else if (window.console) + { console.log('Pixi.js ' + CONST.VERSION + ' - ' + type + ' - http://www.pixijs.com/'); //jshint ignore:line } @@ -166,15 +181,19 @@ * @class * @namespace PIXI */ - AjaxRequest: function () { + AjaxRequest: function () + { var activexmodes = ['Msxml2.XMLHTTP.6.0', 'Msxml2.XMLHTTP.3.0', 'Microsoft.XMLHTTP']; //activeX versions to check for in IE - if (window.ActiveXObject) { //Test for support for ActiveXObject in IE first (as XMLHttpRequest in IE7 is broken) - for (var i=0; i= this.textures.length) { + else if (round >= this.textures.length) + { this.gotoAndStop(this.textures.length - 1); - if (this.onComplete) { + if (this.onComplete) + { this.onComplete(); } } @@ -167,10 +182,12 @@ * @static * @param frames {string[]} the array of frames ids the movieclip will use as its texture frames */ -MovieClip.fromFrames = function (frames) { +MovieClip.fromFrames = function (frames) +{ var textures = []; - for (var i = 0; i < frames.length; ++i) { + for (var i = 0; i < frames.length; ++i) + { textures.push(new core.Texture.fromFrame(frames[i])); } @@ -183,10 +200,12 @@ * @static * @param images {string[]} the array of image urls the movieclip will use as its texture frames */ -MovieClip.fromImages = function (images) { +MovieClip.fromImages = function (images) +{ var textures = []; - for (var i = 0; i < images.length; ++i) { + for (var i = 0; i < images.length; ++i) + { textures.push(new core.Texture.fromImage(images[i])); } diff --git a/src/extras/Rope.js b/src/extras/Rope.js index c157ec4..9c87bc0 100644 --- a/src/extras/Rope.js +++ b/src/extras/Rope.js @@ -9,7 +9,8 @@ * @param {Array} points - An array of {Point}. * */ -function Rope(texture, points) { +function Rope(texture, points) +{ Strip.call(this, texture); this.points = points; @@ -31,10 +32,12 @@ * Refreshes * */ -Rope.prototype.refresh = function () { +Rope.prototype.refresh = function () +{ var points = this.points; - if (points.length < 1) { + if (points.length < 1) + { return; } @@ -59,20 +62,23 @@ var total = points.length, point, index, amount; - for (var i = 1; i < total; i++) { + for (var i = 1; i < total; i++) + { point = points[i]; index = i * 4; // time to do some smart drawing! amount = i / (total-1); - if (i%2) { + if (i%2) + { uvs[index] = amount; uvs[index+1] = 0; uvs[index+2] = amount; uvs[index+3] = 1; } - else { + else + { uvs[index] = amount; uvs[index+1] = 0; @@ -95,10 +101,12 @@ * * @private */ -Rope.prototype.updateTransform = function () { +Rope.prototype.updateTransform = function () +{ var points = this.points; - if (points.length < 1) { + if (points.length < 1) + { return; } @@ -113,14 +121,17 @@ var total = points.length, point, index, ratio, perpLength, num; - for (var i = 0; i < total; i++) { + for (var i = 0; i < total; i++) + { point = points[i]; index = i * 4; - if (i < points.length-1) { + if (i < points.length-1) + { nextPoint = points[i+1]; } - else { + else + { nextPoint = point; } @@ -129,7 +140,8 @@ ratio = (1 - (i / (total-1))) * 10; - if (ratio > 1) { + if (ratio > 1) + { ratio = 1; } @@ -157,7 +169,8 @@ * * @param texture {Texture} the texture that will be used */ -Rope.prototype.setTexture = function (texture) { +Rope.prototype.setTexture = function (texture) +{ // stop current texture this.texture = texture; //this.updateFrame = true; diff --git a/src/extras/Strip.js b/src/extras/Strip.js index c5e378f..57691b5 100644 --- a/src/extras/Strip.js +++ b/src/extras/Strip.js @@ -10,7 +10,8 @@ * @param height {number} the height * */ -function Strip(texture) { +function Strip(texture) +{ core.DisplayObjectContainer.call(this); /** @@ -70,9 +71,11 @@ * * @param renderer {WebGLRenderer} */ -Strip.prototype.renderWebGL = function (renderer) { +Strip.prototype.renderWebGL = function (renderer) +{ // if the sprite is not visible or the alpha is 0 then no need to render this element - if (!this.visible || this.alpha <= 0) { + if (!this.visible || this.alpha <= 0) + { return; } @@ -81,7 +84,8 @@ renderer.spriteBatch.stop(); // init! init! - if (!this._vertexBuffer) { + if (!this._vertexBuffer) + { this._initWebGL(renderer); } @@ -96,7 +100,8 @@ //TODO check culling }; -Strip.prototype._initWebGL = function (renderer) { +Strip.prototype._initWebGL = function (renderer) +{ // build the strip! var gl = renderer.gl; @@ -118,7 +123,8 @@ gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this.indices, gl.STATIC_DRAW); }; -Strip.prototype._renderStrip = function (renderer) { +Strip.prototype._renderStrip = function (renderer) +{ var gl = renderer.gl; var projection = renderer.projection, offset = renderer.offset, @@ -137,7 +143,8 @@ gl.uniform2f(shader.offsetVector, -offset.x, -offset.y); gl.uniform1f(shader.alpha, this.worldAlpha); - if (!this.dirty) { + if (!this.dirty) + { gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexBuffer); gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); @@ -150,10 +157,12 @@ gl.activeTexture(gl.TEXTURE0); // check if a texture is dirty.. - if (this.texture.baseTexture._dirty[gl.id]) { + if (this.texture.baseTexture._dirty[gl.id]) + { renderer.updateTexture(this.texture.baseTexture); } - else { + else + { // bind the current texture gl.bindTexture(gl.TEXTURE_2D, this.texture.baseTexture._glTextures[gl.id]); } @@ -163,7 +172,8 @@ } - else { + else + { this.dirty = false; gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexBuffer); @@ -178,10 +188,12 @@ gl.activeTexture(gl.TEXTURE0); // check if a texture is dirty.. - if (this.texture.baseTexture._dirty[gl.id]) { + if (this.texture.baseTexture._dirty[gl.id]) + { renderer.updateTexture(this.texture.baseTexture); } - else { + else + { gl.bindTexture(gl.TEXTURE_2D, this.texture.baseTexture._glTextures[gl.id]); } @@ -203,27 +215,33 @@ * * @param renderer {CanvasRenderer} */ -Strip.prototype.renderCanvas = function (renderer) { +Strip.prototype.renderCanvas = function (renderer) +{ var context = renderer.context; var transform = this.worldTransform; - if (renderer.roundPixels) { + if (renderer.roundPixels) + { context.setTransform(transform.a, transform.b, transform.c, transform.d, transform.tx | 0, transform.ty | 0); } - else { + else + { context.setTransform(transform.a, transform.b, transform.c, transform.d, transform.tx, transform.ty); } - if (this.drawMode === Strip.DrawModes.TRIANGLE_STRIP) { + if (this.drawMode === Strip.DrawModes.TRIANGLE_STRIP) + { this._renderCanvasTriangleStrip(context); } - else { + else + { this._renderCanvasTriangles(context); } }; -Strip.prototype._renderCanvasTriangleStrip = function (context) { +Strip.prototype._renderCanvasTriangleStrip = function (context) +{ // draw triangles!! var vertices = this.vertices; var uvs = this.uvs; @@ -231,14 +249,16 @@ var length = vertices.length / 2; // this.count++; - for (var i = 0; i < length - 2; i++) { + for (var i = 0; i < length - 2; i++) + { // draw some triangles! var index = i * 2; this._renderCanvasDrawTriangle(context, vertices, uvs, index, (index + 2), (index + 4)); } }; -Strip.prototype._renderCanvasTriangles = function (context) { +Strip.prototype._renderCanvasTriangles = function (context) +{ // draw triangles!! var vertices = this.vertices; var uvs = this.uvs; @@ -247,14 +267,16 @@ var length = indices.length; // this.count++; - for (var i = 0; i < length; i += 3) { + for (var i = 0; i < length; i += 3) + { // draw some triangles! var index0 = indices[i] * 2, index1 = indices[i + 1] * 2, index2 = indices[i + 2] * 2; this._renderCanvasDrawTriangle(context, vertices, uvs, index0, index1, index2); } }; -Strip.prototype._renderCanvasDrawTriangle = function (context, vertices, uvs, index0, index1, index2) { +Strip.prototype._renderCanvasDrawTriangle = function (context, vertices, uvs, index0, index1, index2) +{ var textureSource = this.texture.baseTexture.source; var textureWidth = this.texture.width; var textureHeight = this.texture.height; @@ -265,7 +287,8 @@ var u0 = uvs[index0] * textureWidth, u1 = uvs[index1] * textureWidth, u2 = uvs[index2] * textureWidth; var v0 = uvs[index0 + 1] * textureHeight, v1 = uvs[index1 + 1] * textureHeight, v2 = uvs[index2 + 1] * textureHeight; - if (this.canvasPadding > 0) { + if (this.canvasPadding > 0) + { var paddingX = this.canvasPadding / this.worldTransform.a; var paddingY = this.canvasPadding / this.worldTransform.d; var centerX = (x0 + x1 + x2) / 3; @@ -332,7 +355,8 @@ * @param strip {Strip} The Strip to render * @private */ -Strip.prototype.renderStripFlat = function (strip) { +Strip.prototype.renderStripFlat = function (strip) +{ var context = this.context; var vertices = strip.vertices; @@ -340,7 +364,8 @@ // this.count++; context.beginPath(); - for (var i=1; i < length-2; i++) { + for (var i=1; i < length-2; i++) + { // draw some triangles! var index = i*2; @@ -358,7 +383,8 @@ }; /* -Strip.prototype.setTexture = function (texture) { +Strip.prototype.setTexture = function (texture) +{ //TODO SET THE TEXTURES //TODO VISIBILITY @@ -377,7 +403,8 @@ * @private */ -Strip.prototype.onTextureUpdate = function () { +Strip.prototype.onTextureUpdate = function () +{ this.updateFrame = true; }; @@ -387,7 +414,8 @@ * @param matrix {Matrix} the transformation matrix of the sprite * @return {Rectangle} the framing rectangle */ -Strip.prototype.getBounds = function (matrix) { +Strip.prototype.getBounds = function (matrix) +{ var worldTransform = matrix || this.worldTransform; var a = worldTransform.a; @@ -404,7 +432,8 @@ var minY = Infinity; var vertices = this.vertices; - for (var i = 0, n = vertices.length; i < n; i += 2) { + for (var i = 0, n = vertices.length; i < n; i += 2) + { var rawX = vertices[i], rawY = vertices[i + 1]; var x = (a * rawX) + (c * rawY) + tx; var y = (d * rawY) + (b * rawX) + ty; @@ -416,7 +445,8 @@ maxY = y > maxY ? y : maxY; } - if (minX === -Infinity || maxY === Infinity) { + if (minX === -Infinity || maxY === Infinity) + { return core.math.Rectangle.EMPTY; } diff --git a/src/extras/TilingSprite.js b/src/extras/TilingSprite.js index 3ac22df..31da393 100644 --- a/src/extras/TilingSprite.js +++ b/src/extras/TilingSprite.js @@ -10,7 +10,8 @@ * @param width {number} the width of the tiling sprite * @param height {number} the height of the tiling sprite */ -function TilingSprite(texture, width, height) { +function TilingSprite(texture, width, height) +{ core.Sprite.call( this, texture); /** @@ -86,10 +87,12 @@ * @memberof TilingSprite# */ width: { - get: function () { + get: function () + { return this._width; }, - set: function (value) { + set: function (value) + { this._width = value; } }, @@ -101,20 +104,25 @@ * @memberof TilingSprite# */ height: { - get: function () { + get: function () + { return this._height; }, - set: function (value) { + set: function (value) + { this._height = value; } }, texture: { - get: function () { + get: function () + { return this._texture; }, - set: function (value) { - if (this._texture === value) { + set: function (value) + { + if (this._texture === value) + { return; } @@ -130,51 +138,61 @@ * * @param renderer {WebGLRenderer} */ -TilingSprite.prototype.renderWebGL = function (renderer) { - if (!this.visible || this.alpha <= 0) { +TilingSprite.prototype.renderWebGL = function (renderer) +{ + if (!this.visible || this.alpha <= 0) + { return; } var i, j; - if (this._mask) { + if (this._mask) + { renderer.spriteBatch.stop(); renderer.maskManager.pushMask(this.mask, renderer); renderer.spriteBatch.start(); } - if (this._filters) { + if (this._filters) + { renderer.spriteBatch.flush(); renderer.filterManager.pushFilter(this._filterBlock); } - if (!this.tilingTexture || this.refreshTexture) { + if (!this.tilingTexture || this.refreshTexture) + { this.generateTilingTexture(true); - if (this.tilingTexture && this.tilingTexture.needsUpdate) { + if (this.tilingTexture && this.tilingTexture.needsUpdate) + { //TODO - tweaking renderer.updateTexture(this.tilingTexture.baseTexture); this.tilingTexture.needsUpdate = false; // this.tilingTexture._uvs = null; } } - else { + else + { renderer.spriteBatch.renderTilingSprite(this); } // simple render children! - for (i=0,j=this.children.length; i= 0 && index <= this.children.length) { - if (child.parent) { + if (index >= 0 && index <= this.children.length) + { + if (child.parent) + { child.parent.removeChild(child); } @@ -154,7 +173,8 @@ return child; } - else { + else + { throw new Error(child + 'addChildAt: The index '+ index +' supplied is out of bounds ' + this.children.length); } }; @@ -165,15 +185,18 @@ * @param child {DisplayObject} * @param child2 {DisplayObject} */ -DisplayObjectContainer.prototype.swapChildren = function (child, child2) { - if (child === child2) { +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) { + if (index1 < 0 || index2 < 0) + { throw new Error('swapChildren: Both the supplied DisplayObjects must be a child of the caller.'); } @@ -187,10 +210,12 @@ * @param child {DisplayObject} The DisplayObject instance to identify * @return {Number} The index position of the child display object to identify */ -DisplayObjectContainer.prototype.getChildIndex = function (child) { +DisplayObjectContainer.prototype.getChildIndex = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { throw new Error('The supplied DisplayObject must be a child of the caller'); } @@ -203,8 +228,10 @@ * @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 */ -DisplayObjectContainer.prototype.setChildIndex = function (child, index) { - if (index < 0 || index >= this.children.length) { +DisplayObjectContainer.prototype.setChildIndex = function (child, index) +{ + if (index < 0 || index >= this.children.length) + { throw new Error('The supplied index is out of bounds'); } @@ -220,8 +247,10 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child at the given index, if any. */ -DisplayObjectContainer.prototype.getChildAt = function (index) { - if (index < 0 || index >= this.children.length) { +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'); } @@ -234,10 +263,12 @@ * @param child {DisplayObject} The DisplayObject to remove * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChild = function (child) { +DisplayObjectContainer.prototype.removeChild = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { return; } @@ -250,7 +281,8 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChildAt = function (index) { +DisplayObjectContainer.prototype.removeChildAt = function (index) +{ var child = this.getChildAt(index); child.parent = null; @@ -265,24 +297,29 @@ * @param beginIndex {Number} The beginning position. Default value is 0. * @param endIndex {Number} The ending position. Default value is size of the container. */ -DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) { +DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) +{ var begin = beginIndex || 0; var end = typeof endIndex === 'number' ? endIndex : this.children.length; var range = end - begin; - if (range > 0 && range <= end) { + if (range > 0 && range <= end) + { var removed = this.children.splice(begin, range); - for (var i = 0; i < removed.length; ++i) { + for (var i = 0; i < removed.length; ++i) + { removed[i].parent = null; } return removed; } - else if (range === 0 && this.children.length === 0) { + else if (range === 0 && this.children.length === 0) + { return []; } - else { + else + { throw new RangeError('removeChildren: numeric values are outside the acceptable range.'); } }; @@ -291,7 +328,8 @@ * Generates and updates the cached sprite for this object. * */ -DisplayObjectContainer.prototype.updateCachedSprite = function () { +DisplayObjectContainer.prototype.updateCachedSprite = function () +{ this._generateCachedSprite(); }; @@ -304,7 +342,8 @@ * @param renderer {CanvasRenderer|WebGLRenderer} The renderer used to generate the texture. * @return {Texture} a texture of the graphics object */ -DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) { +DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) +{ var bounds = this.getLocalBounds(); var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0, renderer, scaleMode, resolution); @@ -322,18 +361,22 @@ * * @private */ -DisplayObjectContainer.prototype.updateTransform = function () { - if (!this.visible) { +DisplayObjectContainer.prototype.updateTransform = function () +{ + if (!this.visible) + { return; } this.displayObjectUpdateTransform(); - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { return; } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } }; @@ -346,8 +389,10 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getBounds = function () { - if (this.children.length === 0) { +DisplayObjectContainer.prototype.getBounds = function () +{ + if (this.children.length === 0) + { return math.Rectangle.EMPTY; } @@ -365,10 +410,12 @@ var childVisible = false; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -386,7 +433,8 @@ maxY = maxY > childMaxY ? maxY : childMaxY; } - if (!childVisible) { + if (!childVisible) + { return math.Rectangle.EMPTY; } @@ -407,12 +455,14 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getLocalBounds = function () { +DisplayObjectContainer.prototype.getLocalBounds = function () +{ var matrixCache = this.worldTransform; this.worldTransform = math.Matrix.IDENTITY; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } @@ -428,13 +478,16 @@ * * @param renderer {WebGLRenderer} The renderer */ -DisplayObjectContainer.prototype.renderWebGL = function (renderer) { +DisplayObjectContainer.prototype.renderWebGL = function (renderer) +{ // if the object is not visible or the alpha is 0 then no need to render this element - if (!this.visible || this.alpha <= 0) { + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } @@ -442,14 +495,17 @@ var i, j; // do a quick check to see if this element has a mask or a filter. - if (this._mask || this._filters) { + if (this._mask || this._filters) + { // push filter first as we need to ensure the stencil buffer is correct for any masking - if (this._filters) { + if (this._filters) + { renderer.spriteBatch.flush(); renderer.filterManager.pushFilter(this._filterBlock); } - if (this._mask) { + if (this._mask) + { renderer.spriteBatch.stop(); renderer.maskManager.pushMask(this.mask, renderer); renderer.spriteBatch.start(); @@ -459,36 +515,42 @@ this._renderWebGL(renderer); // now loop through the children and make sure they get rendered - for (i = 0, j = this.children.length; i < j; i++) { + for (i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderWebGL(renderer); } // time to stop the sprite batch as either a mask element or a filter draw will happen next renderer.spriteBatch.stop(); - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(this._mask, renderer); } - if (this._filters) { + if (this._filters) + { renderer.filterManager.popFilter(); } renderer.spriteBatch.start(); } - else { + else + { this._renderWebGL(renderer); // simple render children! - for (i = 0, j = this.children.length; i < j; ++i) { + for (i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderWebGL(renderer); } } }; -DisplayObjectContainer.prototype._renderWebGL = function (renderer) { +DisplayObjectContainer.prototype._renderWebGL = function (renderer) +{ // this is where content itself gets renderd.. @@ -499,25 +561,31 @@ * * @param renderer {CanvasRenderer} The renderer */ -DisplayObjectContainer.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0) { +DisplayObjectContainer.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -528,13 +596,16 @@ * @param renderer {WebGLRenderer|CanvasRenderer} The renderer * @private */ -DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) { +DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) +{ this._cachedSprite.worldAlpha = this.worldAlpha; - if (renderer.gl) { + if (renderer.gl) + { this._cachedSprite.renderWebGL(renderer); } - else { + else + { this._cachedSprite.renderCanvas(renderer); } }; @@ -544,10 +615,12 @@ * * @private */ -DisplayObjectContainer.prototype._generateCachedSprite = function () { +DisplayObjectContainer.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { // TODO - RenderTexture now *requires* a renderer instance, so this is like broken // because `renderer` isn't actually in scope here :P var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0); @@ -555,7 +628,8 @@ this._cachedSprite = new Sprite(renderTexture); this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.texture.resize(bounds.width | 0, bounds.height | 0); } @@ -580,8 +654,10 @@ * * @private */ -DisplayObjectContainer.prototype._destroyCachedSprite = function () { - if (!this._cachedSprite) { +DisplayObjectContainer.prototype._destroyCachedSprite = function () +{ + if (!this._cachedSprite) + { return; } diff --git a/src/core/display/Sprite.js b/src/core/display/Sprite.js index 707da24..5862aef 100644 --- a/src/core/display/Sprite.js +++ b/src/core/display/Sprite.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param texture {Texture} The texture for this sprite */ -function Sprite(texture) { +function Sprite(texture) +{ DisplayObjectContainer.call(this); /** @@ -85,12 +86,14 @@ this.texture = texture || Texture.EMPTY; } -Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) { +Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) +{ DisplayObjectContainer.prototype.destroy.call(this); this.anchor = null; - if (destroyTexture) { + if (destroyTexture) + { this._texture.destroy(destroyBaseTexture); } @@ -111,10 +114,12 @@ * @memberof Sprite# */ width: { - get: function () { + get: function () + { return this.scale.x * this.texture.frame.width; }, - set: function (value) { + set: function (value) + { this.scale.x = value / this.texture.frame.width; this._width = value; } @@ -127,10 +132,12 @@ * @memberof Sprite# */ height: { - get: function () { + get: function () + { return this.scale.y * this.texture.frame.height; }, - set: function (value) { + set: function (value) + { this.scale.y = value / this.texture.frame.height; this._height = value; } @@ -143,23 +150,29 @@ * @memberof Sprite# */ texture: { - get: function () { + get: function () + { return this._texture; }, - set: function (value) { - if (this._texture === value) { + set: function (value) + { + if (this._texture === value) + { return; } this._texture = value; this.cachedTint = 0xFFFFFF; - if (value) { + if (value) + { // wait for the texture to load - if (value.baseTexture.hasLoaded) { + if (value.baseTexture.hasLoaded) + { this._onTextureUpdate(); } - else { + else + { value.once('update', this._onTextureUpdate.bind(this)); } } @@ -172,18 +185,22 @@ * * @private */ -Sprite.prototype._onTextureUpdate = function () { +Sprite.prototype._onTextureUpdate = function () +{ // so if _width is 0 then width was not set.. - if (this._width) { + if (this._width) + { this.scale.x = this._width / this.texture.frame.width; } - if (this._height) { + if (this._height) + { this.scale.y = this._height / this.texture.frame.height; } }; -Sprite.prototype._renderWebGL = function (renderer) { +Sprite.prototype._renderWebGL = function (renderer) +{ // this is where content gets renderd.. // watch this space for a little render state manager.. @@ -197,7 +214,8 @@ * @param matrix {Matrix} the transformation matrix of the sprite * @return {Rectangle} the framing rectangle */ -Sprite.prototype.getBounds = function (matrix) { +Sprite.prototype.getBounds = function (matrix) +{ var width = this.texture.frame.width; var height = this.texture.frame.height; @@ -224,11 +242,13 @@ if(b === 0 && c === 0) { // scale may be negative! - if (a < 0) { + if (a < 0) + { a *= -1; } - if (d < 0) { + if (d < 0) + { d *= -1; } @@ -293,28 +313,34 @@ * * @param renderer {CanvasRenderer} The renderer */ -Sprite.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) { +Sprite.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) + { return; } - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; renderer.context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } // Ignore null sources - if (this.texture.valid) { + if (this.texture.valid) + { var resolution = this.texture.baseTexture.resolution / renderer.resolution; renderer.context.globalAlpha = this.worldAlpha; // If smoothingEnabled is supported and we need to change the smoothing property for this texture - if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) { + if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) + { renderer.scaleMode = this.texture.baseTexture.scaleMode; renderer.context[renderer.smoothProperty] = (renderer.scaleMode === CONST.scaleModes.LINEAR); } @@ -324,7 +350,8 @@ var dy = (this.texture.trim ? this.texture.trim.y : 0) - (this.anchor.y * this.texture.trim.height); // Allow for pixel rounding - if (renderer.roundPixels) { + if (renderer.roundPixels) + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -337,7 +364,8 @@ dx = dx | 0; dy = dy | 0; } - else { + else + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -348,8 +376,10 @@ ); } - if (this.tint !== 0xFFFFFF) { - if (this.cachedTint !== this.tint) { + if (this.tint !== 0xFFFFFF) + { + if (this.cachedTint !== this.tint) + { this.cachedTint = this.tint; // TODO clean up caching - how to clean up the caches? @@ -368,7 +398,8 @@ this.texture.crop.height / resolution ); } - else { + else + { renderer.context.drawImage( this.texture.baseTexture.source, this.texture.crop.x, @@ -383,11 +414,13 @@ } } - for (var i = 0, j = this.children.length; i < j; i++) { + for (var i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -402,10 +435,12 @@ * @param frameId {String} The frame Id of the texture in the cache * @return {Sprite} A new Sprite using a texture from the texture cache matching the frameId */ -Sprite.fromFrame = function (frameId) { +Sprite.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache' + this); } @@ -420,6 +455,7 @@ * @param imageId {String} The image url of the texture * @return {Sprite} A new Sprite using a texture from the texture cache matching the image id */ -Sprite.fromImage = function (imageId, crossorigin, scaleMode) { +Sprite.fromImage = function (imageId, crossorigin, scaleMode) +{ return new Sprite(Texture.fromImage(imageId, crossorigin, scaleMode)); }; diff --git a/src/core/display/SpriteBatch.js b/src/core/display/SpriteBatch.js index 3187777..c196fef 100644 --- a/src/core/display/SpriteBatch.js +++ b/src/core/display/SpriteBatch.js @@ -12,7 +12,8 @@ * ```js * var container = new SpriteBatch(); * - * for(var i = 0; i < 100; ++i) { + * for(var i = 0; i < 100; ++i) + * { * var sprite = new PIXI.Sprite.fromImage("myImage.png"); * container.addChild(sprite); * } @@ -25,7 +26,8 @@ */ //TODO RENAME to PARTICLE CONTAINER? -function SpriteBatch() { +function SpriteBatch() +{ DisplayObjectContainer.call(this); } @@ -38,7 +40,8 @@ * * @private */ -SpriteBatch.prototype.updateTransform = function () { +SpriteBatch.prototype.updateTransform = function () +{ // TODO don't need to! this.displayObjectUpdateTransform(); // PIXI.DisplayObjectContainer.prototype.updateTransform.call( this ); @@ -50,8 +53,10 @@ * @param renderer {WebGLRenderer} The webgl renderer * @private */ -SpriteBatch.prototype.renderWebGL = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderWebGL = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -71,8 +76,10 @@ * @param renderer {CanvasRenderer} The canvas renderer * @private */ -SpriteBatch.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -84,10 +91,12 @@ this.displayObjectUpdateTransform(); - for (var i = 0; i < this.children.length; ++i) { + for (var i = 0; i < this.children.length; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -95,9 +104,11 @@ context.globalAlpha = this.worldAlpha * child.alpha; - if (child.rotation % (Math.PI * 2) === 0) { + if (child.rotation % (Math.PI * 2) === 0) + { // this is the fastest way to optimise! - if rotation is 0 then we can avoid any kind of setTransform call - if (isRotated) { + if (isRotated) + { context.setTransform( transform.a, transform.b, @@ -122,8 +133,10 @@ frame.height * child.scale.y ); } - else { - if (!isRotated) { + else + { + if (!isRotated) + { isRotated = true; } @@ -131,7 +144,8 @@ var childTransform = child.worldTransform; - if (renderer.roundPixels) { + if (renderer.roundPixels) + { context.setTransform( childTransform.a, childTransform.b, @@ -141,7 +155,8 @@ childTransform.ty | 0 ); } - else { + else + { context.setTransform( childTransform.a, childTransform.b, diff --git a/src/core/index.js b/src/core/index.js index 3954b6f..eb4a82b 100644 --- a/src/core/index.js +++ b/src/core/index.js @@ -58,11 +58,13 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRenderer: function (width, height, options, noWebGL) { + autoDetectRenderer: function (width, height, options, noWebGL) + { width = width || 800; height = height || 600; - if (!noWebGL && require('webgl-enabled')()) { + if (!noWebGL && require('webgl-enabled')()) + { return new core.WebGLRenderer(width, height, options); } @@ -87,7 +89,8 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRecommendedRenderer: function (width, height, options) { + autoDetectRecommendedRenderer: function (width, height, options) + { var isAndroid = /Android/i.test(navigator.userAgent); return core.autoDetectRenderer(width, height, options, isAndroid); diff --git a/src/core/math/Matrix.js b/src/core/math/Matrix.js index c2f87e2..2ff4848 100644 --- a/src/core/math/Matrix.js +++ b/src/core/math/Matrix.js @@ -10,7 +10,8 @@ * @class * @namespace PIXI */ -function Matrix() { +function Matrix() +{ /** * @member {number} * @default 1 @@ -63,7 +64,8 @@ * * @param array {number[]} The array that the matrix will be populated from. */ -Matrix.prototype.fromArray = function (array) { +Matrix.prototype.fromArray = function (array) +{ this.a = array[0]; this.b = array[1]; this.c = array[3]; @@ -78,14 +80,17 @@ * @param transpose {boolean} Whether we need to transpose the matrix or not * @return {number[]} the newly created array which contains the matrix */ -Matrix.prototype.toArray = function (transpose) { - if (!this.array) { +Matrix.prototype.toArray = function (transpose) +{ + if (!this.array) + { this.array = new Float32Array(9); } var array = this.array; - if (transpose) { + if (transpose) + { array[0] = this.a; array[1] = this.b; array[2] = 0; @@ -96,7 +101,8 @@ array[7] = this.ty; array[8] = 1; } - else { + else + { array[0] = this.a; array[1] = this.c; array[2] = this.tx; @@ -119,7 +125,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, transformed through this matrix */ -Matrix.prototype.apply = function (pos, newPos) { +Matrix.prototype.apply = function (pos, newPos) +{ newPos = newPos || new Point(); newPos.x = this.a * pos.x + this.c * pos.y + this.tx; @@ -136,7 +143,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, inverse-transformed through this matrix */ -Matrix.prototype.applyInverse = function (pos, newPos) { +Matrix.prototype.applyInverse = function (pos, newPos) +{ newPos = newPos || new Point(); var id = 1 / (this.a * this.d + this.c * -this.b); @@ -154,7 +162,8 @@ * @param {number} y * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.translate = function (x, y) { +Matrix.prototype.translate = function (x, y) +{ this.tx += x; this.ty += y; @@ -168,7 +177,8 @@ * @param {number} y The amount to scale vertically * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.scale = function (x, y) { +Matrix.prototype.scale = function (x, y) +{ this.a *= x; this.d *= y; this.c *= x; @@ -186,7 +196,8 @@ * @param {number} angle - The angle in radians. * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.rotate = function (angle) { +Matrix.prototype.rotate = function (angle) +{ var cos = Math.cos( angle ); var sin = Math.sin( angle ); @@ -210,7 +221,8 @@ * @param {Matrix} matrix * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.append = function (matrix) { +Matrix.prototype.append = function (matrix) +{ var a1 = this.a; var b1 = this.b; var c1 = this.c; @@ -232,7 +244,8 @@ * * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.identity = function () { +Matrix.prototype.identity = function () +{ this.a = 1; this.b = 0; this.c = 0; diff --git a/src/core/math/Point.js b/src/core/math/Point.js index 7565b2d..632f346 100644 --- a/src/core/math/Point.js +++ b/src/core/math/Point.js @@ -7,7 +7,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -function Point(x, y) { +function Point(x, y) +{ /** * @member {number} * @default 0 @@ -29,7 +30,8 @@ * * @return {Point} a copy of the point */ -Point.prototype.clone = function () { +Point.prototype.clone = function () +{ return new Point(this.x, this.y); }; @@ -40,7 +42,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -Point.prototype.set = function (x, y) { +Point.prototype.set = function (x, y) +{ this.x = x || 0; this.y = y || ( (y !== 0) ? this.x : 0 ) ; }; diff --git a/src/core/math/shapes/Circle.js b/src/core/math/shapes/Circle.js index 69cfdc9..4d76efc 100644 --- a/src/core/math/shapes/Circle.js +++ b/src/core/math/shapes/Circle.js @@ -10,7 +10,8 @@ * @param y {number} The Y coordinate of the center of this circle * @param radius {number} The radius of the circle */ -function Circle(x, y, radius) { +function Circle(x, y, radius) +{ /** * @member {number} * @default 0 @@ -46,7 +47,8 @@ * @method clone * @return {Circle} a copy of the Circle */ -Circle.prototype.clone = function () { +Circle.prototype.clone = function () +{ return new Circle(this.x, this.y, this.radius); }; @@ -58,8 +60,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Circle */ -Circle.prototype.contains = function (x, y) { - if (this.radius <= 0) { +Circle.prototype.contains = function (x, y) +{ + if (this.radius <= 0) + { return false; } @@ -79,6 +83,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Circle.prototype.getBounds = function () { +Circle.prototype.getBounds = function () +{ return new Rectangle(this.x - this.radius, this.y - this.radius, this.radius * 2, this.radius * 2); }; diff --git a/src/core/math/shapes/Ellipse.js b/src/core/math/shapes/Ellipse.js index 4f2d066..fefd01a 100644 --- a/src/core/math/shapes/Ellipse.js +++ b/src/core/math/shapes/Ellipse.js @@ -11,7 +11,8 @@ * @param width {number} The half width of this ellipse * @param height {number} The half height of this ellipse */ -function Ellipse(x, y, width, height) { +function Ellipse(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -53,7 +54,8 @@ * @method clone * @return {Ellipse} a copy of the ellipse */ -Ellipse.prototype.clone = function () { +Ellipse.prototype.clone = function () +{ return new Ellipse(this.x, this.y, this.width, this.height); }; @@ -65,8 +67,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coords are within this ellipse */ -Ellipse.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Ellipse.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } @@ -86,6 +90,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Ellipse.prototype.getBounds = function () { +Ellipse.prototype.getBounds = function () +{ return new Rectangle(this.x - this.width, this.y - this.height, this.width, this.height); }; diff --git a/src/core/math/shapes/Polygon.js b/src/core/math/shapes/Polygon.js index ae89148..fea6d37 100644 --- a/src/core/math/shapes/Polygon.js +++ b/src/core/math/shapes/Polygon.js @@ -10,16 +10,20 @@ * arguments passed can be flat x,y values e.g. `new Polygon(x,y, x,y, x,y, ...)` where `x` and `y` are * Numbers. */ -function Polygon(points) { +function Polygon(points) +{ //if points isn't an array, use arguments as the array - if (!(points instanceof Array)) { + if (!(points instanceof Array)) + { points = Array.prototype.slice.call(arguments); } //if this is a flat array of numbers, convert it to points - if (points[0] instanceof Point) { + if (points[0] instanceof Point) + { var p = []; - for (var i = 0, il = points.length; i < il; i++) { + for (var i = 0, il = points.length; i < il; i++) + { p.push(points[i].x, points[i].y); } @@ -51,7 +55,8 @@ * * @return {Polygon} a copy of the polygon */ -Polygon.prototype.clone = function () { +Polygon.prototype.clone = function () +{ return new Polygon(this.points.slice()); }; @@ -62,19 +67,22 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this polygon */ -Polygon.prototype.contains = function (x, y) { +Polygon.prototype.contains = function (x, y) +{ var inside = false; // use some raycasting to test hits // https://github.com/substack/point-in-polygon/blob/master/index.js var length = this.points.length / 2; - for (var i = 0, j = length - 1; i < length; j = i++) { + for (var i = 0, j = length - 1; i < length; j = i++) + { var xi = this.points[i * 2], yi = this.points[i * 2 + 1], xj = this.points[j * 2], yj = this.points[j * 2 + 1], intersect = ((yi > y) !== (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi); - if (intersect) { + if (intersect) + { inside = !inside; } } diff --git a/src/core/math/shapes/Rectangle.js b/src/core/math/shapes/Rectangle.js index 16ac62a..4008b68 100644 --- a/src/core/math/shapes/Rectangle.js +++ b/src/core/math/shapes/Rectangle.js @@ -10,7 +10,8 @@ * @param width {number} The overall width of this rectangle * @param height {number} The overall height of this rectangle */ -function Rectangle(x, y, width, height) { +function Rectangle(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -60,7 +61,8 @@ * * @return {Rectangle} a copy of the rectangle */ -Rectangle.prototype.clone = function () { +Rectangle.prototype.clone = function () +{ return new Rectangle(this.x, this.y, this.width, this.height); }; @@ -71,13 +73,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rectangle */ -Rectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Rectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/math/shapes/RoundedRectangle.js b/src/core/math/shapes/RoundedRectangle.js index 27d286e..7bf6411 100644 --- a/src/core/math/shapes/RoundedRectangle.js +++ b/src/core/math/shapes/RoundedRectangle.js @@ -11,7 +11,8 @@ * @param height {number} The overall height of this rounded rectangle * @param radius {number} Controls the radius of the rounded corners */ -function RoundedRectangle(x, y, width, height, radius) { +function RoundedRectangle(x, y, width, height, radius) +{ /** * @member {number} * @default 0 @@ -58,7 +59,8 @@ * * @return {RoundedRectangle} a copy of the rounded rectangle */ -RoundedRectangle.prototype.clone = function () { +RoundedRectangle.prototype.clone = function () +{ return new RoundedRectangle(this.x, this.y, this.width, this.height, this.radius); }; @@ -69,13 +71,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rounded Rectangle */ -RoundedRectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +RoundedRectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/primitives/Graphics.js b/src/core/primitives/Graphics.js index 261c534..e902d2a 100644 --- a/src/core/primitives/Graphics.js +++ b/src/core/primitives/Graphics.js @@ -16,7 +16,8 @@ * @extends DisplayObjectContainer * @namespace PIXI */ -function Graphics() { +function Graphics() +{ DisplayObjectContainer.call(this); this.renderable = true; @@ -154,16 +155,20 @@ * @private */ cacheAsBitmap: { - get: function () { + get: function () + { return this._cacheAsBitmap; }, - set: function (value) { + set: function (value) + { this._cacheAsBitmap = value; - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._generateCachedSprite(); } - else { + else + { this.destroyCachedSprite(); this.dirty = true; } @@ -176,7 +181,8 @@ * * @return {Graphics} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ var clone = new Graphics(); clone.renderable = this.renderable; @@ -192,7 +198,8 @@ clone.cachedSpriteDirty = this.cachedSpriteDirty; // copy graphics data - for (var i = 0; i < this.graphicsData.length; ++i) { + for (var i = 0; i < this.graphicsData.length; ++i) + { clone.graphicsData.push(this.graphicsData.clone()); } @@ -211,17 +218,21 @@ * @param alpha {number} alpha of the line to draw, will update the objects stored style * @return {Graphics} */ -Graphics.prototype.lineStyle = function (lineWidth, color, alpha) { +Graphics.prototype.lineStyle = function (lineWidth, color, alpha) +{ this.lineWidth = lineWidth || 0; this.lineColor = color || 0; this.lineAlpha = (arguments.length < 3) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length) + { // halfway through a line? start a new one! this.drawShape( new math.Polygon( this.currentPath.shape.points.slice(-2) )); } - else { + else + { // otherwise its empty so lets just set the line properties this.currentPath.lineWidth = this.lineWidth; this.currentPath.lineColor = this.lineColor; @@ -239,7 +250,8 @@ * @param y {number} the Y coordinate to move to * @return {Graphics} */ -Graphics.prototype.moveTo = function (x, y) { +Graphics.prototype.moveTo = function (x, y) +{ this.drawShape(new math.Polygon([x,y])); return this; @@ -253,7 +265,8 @@ * @param y {number} the Y coordinate to draw to * @return {Graphics} */ -Graphics.prototype.lineTo = function (x, y) { +Graphics.prototype.lineTo = function (x, y) +{ this.currentPath.shape.points.push(x, y); this.dirty = true; @@ -270,13 +283,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -285,7 +302,8 @@ n = 20, points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { this.moveTo(0, 0); } @@ -293,7 +311,8 @@ var fromY = points[points.length-1]; var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; xa = fromX + ( (cpX - fromX) * j ); @@ -319,13 +338,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -342,7 +365,8 @@ var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; dt = (1 - j); @@ -373,13 +397,17 @@ * @param radius {number} The radius of the arc * @return {Graphics} */ -Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points.push(x1, y1); } } - else { + else + { this.moveTo(x1, y1); } @@ -392,12 +420,15 @@ b2 = x2 - x1, mm = Math.abs(a1 * b2 - b1 * a2); - if (mm < 1.0e-8 || radius === 0) { - if (points[points.length-2] !== x1 || points[points.length-1] !== y1) { + if (mm < 1.0e-8 || radius === 0) + { + if (points[points.length-2] !== x1 || points[points.length-1] !== y1) + { points.push(x1, y1); } } - else { + else + { var dd = a1 * a1 + b1 * b1, cc = a2 * a2 + b2 * b2, tt = a1 * a2 + b1 * b2, @@ -433,42 +464,51 @@ * @param anticlockwise {boolean} Optional. Specifies whether the drawing should be counterclockwise or clockwise. False is default, and indicates clockwise, while true indicates counter-clockwise. * @return {Graphics} */ -Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) { +Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) +{ var startX = cx + Math.cos(startAngle) * radius; var startY = cy + Math.sin(startAngle) * radius; var points; // TODO - This if-else makes no sense. It uses currentPath in the else where it doesn't exist... - if (this.currentPath) { + if (this.currentPath) + { points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { points.push(startX, startY); } - else if (points[points.length-2] !== startX || points[points.length-1] !== startY) { + else if (points[points.length-2] !== startX || points[points.length-1] !== startY) + { points.push(startX, startY); } } - else { + else + { this.moveTo(startX, startY); points = this.currentPath.shape.points; } - if (startAngle === endAngle) { + if (startAngle === endAngle) + { return this; } - if (!anticlockwise && endAngle <= startAngle) { + if (!anticlockwise && endAngle <= startAngle) + { endAngle += Math.PI * 2; } - else if (anticlockwise && startAngle <= endAngle) { + else if (anticlockwise && startAngle <= endAngle) + { startAngle += Math.PI * 2; } var sweep = anticlockwise ? (startAngle - endAngle) *-1 : (endAngle - startAngle); var segs = (Math.abs(sweep)/ (Math.PI * 2)) * 40; - if (sweep === 0) { + if (sweep === 0) + { return this; } @@ -482,7 +522,8 @@ var remainder = ( segMinus % 1 ) / segMinus; - for (var i = 0; i <= segMinus; ++i) { + for (var i = 0; i <= segMinus; ++i) + { var real = i + remainder * i; var angle = ((theta) + startAngle + (theta2 * real)); @@ -506,13 +547,16 @@ * @param alpha {number} the alpha of the fill * @return {Graphics} */ -Graphics.prototype.beginFill = function (color, alpha) { +Graphics.prototype.beginFill = function (color, alpha) +{ this.filling = true; this.fillColor = color || 0; this.fillAlpha = (alpha === undefined) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length <= 2) + { this.currentPath.fill = this.filling; this.currentPath.fillColor = this.fillColor; this.currentPath.fillAlpha = this.fillAlpha; @@ -526,7 +570,8 @@ * * @return {Graphics} */ -Graphics.prototype.endFill = function () { +Graphics.prototype.endFill = function () +{ this.filling = false; this.fillColor = null; this.fillAlpha = 1; @@ -542,7 +587,8 @@ * @param height {number} The height of the rectangle * @return {Graphics} */ -Graphics.prototype.drawRect = function ( x, y, width, height ) { +Graphics.prototype.drawRect = function ( x, y, width, height ) +{ this.drawShape(new math.Rectangle(x,y, width, height)); return this; @@ -556,7 +602,8 @@ * @param height {number} The height of the rectangle * @param radius {number} Radius of the rectangle corners */ -Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) { +Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) +{ this.drawShape(new math.RoundedRectangle(x, y, width, height, radius)); return this; @@ -570,7 +617,8 @@ * @param radius {number} The radius of the circle * @return {Graphics} */ -Graphics.prototype.drawCircle = function (x, y, radius) { +Graphics.prototype.drawCircle = function (x, y, radius) +{ this.drawShape(new math.Circle(x,y, radius)); return this; @@ -585,7 +633,8 @@ * @param height {number} The half height of the ellipse * @return {Graphics} */ -Graphics.prototype.drawEllipse = function (x, y, width, height) { +Graphics.prototype.drawEllipse = function (x, y, width, height) +{ this.drawShape(new math.Ellipse(x, y, width, height)); return this; @@ -597,8 +646,10 @@ * @param path {Array} The path data used to construct the polygon. * @return {Graphics} */ -Graphics.prototype.drawPolygon = function (path) { - if (!(path instanceof Array)) { +Graphics.prototype.drawPolygon = function (path) +{ + if (!(path instanceof Array)) + { path = Array.prototype.slice.call(arguments); } @@ -612,7 +663,8 @@ * * @return {Graphics} */ -Graphics.prototype.clear = function () { +Graphics.prototype.clear = function () +{ this.lineWidth = 0; this.filling = false; @@ -631,7 +683,8 @@ * @param scaleMode {number} Should be one of the scaleMode consts * @return {Texture} a texture of the graphics object */ -Graphics.prototype.generateTexture = function (resolution, scaleMode) { +Graphics.prototype.generateTexture = function (resolution, scaleMode) +{ resolution = resolution || 1; var bounds = this.getBounds(); @@ -655,17 +708,21 @@ * * @param renderer {WebGLRenderer} */ -Graphics.prototype._renderWebGL = function (renderer) { +Graphics.prototype._renderWebGL = function (renderer) +{ // if the sprite is not visible or the alpha is 0 then no need to render this element - if (this.isMask === true) { + if (this.isMask === true) + { return; } // this code may still be needed so leaving for now.. - // + // /* - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture on the gpu too! @@ -681,17 +738,24 @@ return; } - */ - - // check if the webgl graphic needs to be updated - if (this.glDirty) { - this.dirty = true; - this.glDirty = false; - } + else */ - renderer.setObjectRendererer(renderer.graphicsRenderer); - renderer.graphicsRenderer.render(this); + renderer.spriteBatch.stop(); + renderer.blendModeManager.setBlendMode(this.blendMode); + // check blend mode + renderer.blendModeManager.setBlendMode( this.blendMode ); + + // check if the webgl graphic needs to be updated + if (this.glDirty) + { + this.dirty = true; + this.glDirty = false; + } + + WebGLGraphics.renderGraphics(this, renderer); + + renderer.spriteBatch.start(); }; /** @@ -700,14 +764,18 @@ * @param renderer {CanvasRenderer} * @private */ -Graphics.prototype.renderCanvas = function (renderer) { +Graphics.prototype.renderCanvas = function (renderer) +{ // 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.isMask === true) { + if (!this.visible || this.alpha <= 0 || this.isMask === true) + { return; } - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture @@ -723,16 +791,19 @@ return; } - else { + else + { var context = renderer.context; var transform = this.worldTransform; - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } @@ -748,11 +819,13 @@ CanvasGraphics.renderGraphics(this, context); - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } } @@ -763,13 +836,16 @@ * * @return {Rectangle} the rectangular bounding area */ -Graphics.prototype.getBounds = function (matrix) { +Graphics.prototype.getBounds = function (matrix) +{ // return an empty object if the item is a mask! - if (this.isMask) { + if (this.isMask) + { return math.Rectangle.EMPTY; } - if (this.dirty) { + if (this.dirty) + { this.updateLocalBounds(); this.glDirty = true; @@ -841,23 +917,27 @@ * Update the bounds of the object * */ -Graphics.prototype.updateLocalBounds = function () { +Graphics.prototype.updateLocalBounds = function () +{ var minX = Infinity; var maxX = -Infinity; var minY = Infinity; var maxY = -Infinity; - if (this.graphicsData.length) { + if (this.graphicsData.length) + { var shape, points, x, y, w, h; - for (var i = 0; i < this.graphicsData.length; i++) { + for (var i = 0; i < this.graphicsData.length; i++) + { var data = this.graphicsData[i]; var type = data.type; var lineWidth = data.lineWidth; shape = data.shape; - if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) { + if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) + { x = shape.x - lineWidth/2; y = shape.y - lineWidth/2; w = shape.width + lineWidth; @@ -869,7 +949,8 @@ minY = y < minY ? y : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.CIRC) { + else if (type === CONST.SHAPES.CIRC) + { x = shape.x; y = shape.y; w = shape.radius + lineWidth/2; @@ -881,7 +962,8 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.ELIP) { + else if (type === CONST.SHAPES.ELIP) + { x = shape.x; y = shape.y; w = shape.width + lineWidth/2; @@ -893,11 +975,13 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else { + else + { // POLY points = shape.points; - for (var j = 0; j < points.length; j += 2) { + for (var j = 0; j < points.length; j += 2) + { x = points[j]; y = points[j+1]; @@ -910,7 +994,8 @@ } } } - else { + else + { minX = 0; maxX = 0; minY = 0; @@ -931,10 +1016,12 @@ * * @private */ -Graphics.prototype._generateCachedSprite = function () { +Graphics.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { var canvasBuffer = new CanvasBuffer(bounds.width, bounds.height); var texture = Texture.fromCanvas(canvasBuffer.canvas); @@ -943,7 +1030,8 @@ this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.buffer.resize(bounds.width, bounds.height); } @@ -968,7 +1056,8 @@ * * @private */ -Graphics.prototype.updateCachedSpriteTexture = function () { +Graphics.prototype.updateCachedSpriteTexture = function () +{ var cachedSprite = this._cachedSprite; var texture = cachedSprite.texture; var canvas = cachedSprite.buffer.canvas; @@ -989,7 +1078,8 @@ * Destroys a previous cached sprite. * */ -Graphics.prototype.destroyCachedSprite = function () { +Graphics.prototype.destroyCachedSprite = function () +{ this._cachedSprite.texture.destroy(true); // let the gc collect the unused sprite @@ -1003,10 +1093,13 @@ * @param {Circle|Rectangle|Ellipse|Line|Polygon} shape The Shape object to draw. * @return {GraphicsData} The generated GraphicsData object. */ -Graphics.prototype.drawShape = function (shape) { - if (this.currentPath) { +Graphics.prototype.drawShape = function (shape) +{ + if (this.currentPath) + { // check current path! - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath.shape.points.length <= 2) + { this.graphicsData.pop(); } } @@ -1017,7 +1110,8 @@ this.graphicsData.push(data); - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { data.shape.closed = this.filling; this.currentPath = data; } diff --git a/src/core/primitives/GraphicsData.js b/src/core/primitives/GraphicsData.js index 99decbe..788f6f2 100644 --- a/src/core/primitives/GraphicsData.js +++ b/src/core/primitives/GraphicsData.js @@ -4,7 +4,8 @@ * @class * @namespace PIXI */ -function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) { +function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) +{ this.lineWidth = lineWidth; this.lineColor = lineColor; this.lineAlpha = lineAlpha; @@ -27,7 +28,8 @@ * * @return {GraphicsData} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ return new GraphicsData( this.lineWidth, this.lineColor, diff --git a/src/core/renderers/canvas/CanvasRenderer.js b/src/core/renderers/canvas/CanvasRenderer.js index 15a0978..7aebd44 100644 --- a/src/core/renderers/canvas/CanvasRenderer.js +++ b/src/core/renderers/canvas/CanvasRenderer.js @@ -17,17 +17,22 @@ * @param [options.resolution=1] {number} the resolution of the renderer retina would be 2 * @param [options.clearBeforeRender=true] {boolean} This sets if the CanvasRenderer will clear the canvas or not before the new render pass. */ -function CanvasRenderer(width, height, options) { +function CanvasRenderer(width, height, options) +{ utils.sayHello('Canvas'); - if (options) { - for (var i in CONST.defaultRenderOptions) { - if (typeof options[i] === 'undefined') { + if (options) + { + for (var i in CONST.defaultRenderOptions) + { + if (typeof options[i] === 'undefined') + { options[i] = CONST.defaultRenderOptions[i]; } } } - else { + else + { options = CONST.defaultRenderOptions; } @@ -156,19 +161,24 @@ this.smoothProperty = null; - if (this.context.imageSmoothingEnabled) { + if (this.context.imageSmoothingEnabled) + { this.smoothProperty = 'imageSmoothingEnabled'; } - else if (this.context.webkitImageSmoothingEnabled) { + else if (this.context.webkitImageSmoothingEnabled) + { this.smoothProperty = 'webkitImageSmoothingEnabled'; } - else if (this.context.mozImageSmoothingEnabled) { + else if (this.context.mozImageSmoothingEnabled) + { this.smoothProperty = 'mozImageSmoothingEnabled'; } - else if (this.context.oImageSmoothingEnabled) { + else if (this.context.oImageSmoothingEnabled) + { this.smoothProperty = 'oImageSmoothingEnabled'; } - else if (this.context.msImageSmoothingEnabled) { + else if (this.context.msImageSmoothingEnabled) + { this.smoothProperty = 'msImageSmoothingEnabled'; } @@ -193,10 +203,12 @@ * @memberof CanvasRenderer# */ backgroundColor: { - get: function () { + get: function () + { return this._backgroundColor; }, - set: function (val) { + set: function (val) + { this._backgroundColor = val; this._backgroundColorString = utils.hex2string(val); } @@ -208,7 +220,8 @@ * * @param object {DisplayObject} the object to be rendered */ -CanvasRenderer.prototype.render = function (object) { +CanvasRenderer.prototype.render = function (object) +{ object.updateTransform(); this.context.setTransform(1,0,0,1,0,0); @@ -218,16 +231,20 @@ this.currentBlendMode = CONST.blendModes.NORMAL; this.context.globalCompositeOperation = this.blendModes[CONST.blendModes.NORMAL]; - if (navigator.isCocoonJS && this.view.screencanvas) { + if (navigator.isCocoonJS && this.view.screencanvas) + { this.context.fillStyle = 'black'; this.context.clear(); } - if (this.clearBeforeRender) { - if (this.transparent) { + if (this.clearBeforeRender) + { + if (this.transparent) + { this.context.clearRect(0, 0, this.width, this.height); } - else { + else + { this.context.fillStyle = this._backgroundColorString; this.context.fillRect(0, 0, this.width , this.height); } @@ -241,8 +258,10 @@ * * @param [removeView=false] {boolean} Removes the Canvas element from the DOM. */ -CanvasRenderer.prototype.destroy = function (removeView) { - if (removeView && this.view.parent) { +CanvasRenderer.prototype.destroy = function (removeView) +{ + if (removeView && this.view.parent) + { this.view.parent.removeChild(this.view); } @@ -257,14 +276,16 @@ * @param width {number} the new width of the canvas view * @param height {number} the new height of the canvas view */ -CanvasRenderer.prototype.resize = function (width, height) { +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) { + if (this.autoResize) + { this.view.style.width = this.width / this.resolution + 'px'; this.view.style.height = this.height / this.resolution + 'px'; } @@ -276,7 +297,8 @@ * @param displayObject {DisplayObject} The displayObject to render * @private */ -CanvasRenderer.prototype.renderDisplayObject = function (displayObject) { +CanvasRenderer.prototype.renderDisplayObject = function (displayObject) +{ displayObject.renderCanvas(this); }; @@ -285,11 +307,14 @@ * * @private */ -CanvasRenderer.prototype._mapBlendModes = function () { - if (!this.blendModes) { +CanvasRenderer.prototype._mapBlendModes = function () +{ + if (!this.blendModes) + { this.blendModes = {}; - if (utils.canUseNewCanvasBlendModes()) { + if (utils.canUseNewCanvasBlendModes()) + { this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? this.blendModes[CONST.blendModes.MULTIPLY] = 'multiply'; @@ -308,7 +333,8 @@ this.blendModes[CONST.blendModes.COLOR] = 'color'; this.blendModes[CONST.blendModes.LUMINOSITY] = 'luminosity'; } - else { + else + { // this means that the browser does not support the cool new blend modes in canvas 'cough' ie 'cough' this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? diff --git a/src/core/renderers/canvas/utils/CanvasBuffer.js b/src/core/renderers/canvas/utils/CanvasBuffer.js index ebe5d47..b183a66 100644 --- a/src/core/renderers/canvas/utils/CanvasBuffer.js +++ b/src/core/renderers/canvas/utils/CanvasBuffer.js @@ -6,7 +6,8 @@ * @param width {number} the width for the newly created canvas * @param height {number} the height for the newly created canvas */ -function CanvasBuffer(width, height) { +function CanvasBuffer(width, height) +{ /** * The Canvas object that belongs to this CanvasBuffer. * @@ -36,10 +37,12 @@ * @memberof CanvasBuffer# */ width: { - get: function () { + get: function () + { return this.canvas.width; }, - set: function (val) { + set: function (val) + { this.canvas.width = val; } }, @@ -50,10 +53,12 @@ * @memberof CanvasBuffer# */ height: { - get: function () { + get: function () + { return this.canvas.height; }, - set: function (val) { + set: function (val) + { this.canvas.height = val; } } @@ -64,7 +69,8 @@ * * @private */ -CanvasBuffer.prototype.clear = function () { +CanvasBuffer.prototype.clear = function () +{ this.context.setTransform(1, 0, 0, 1, 0, 0); this.context.clearRect(0,0, this.canvas.width, this.canvas.height); }; @@ -75,7 +81,8 @@ * @param width {number} the new width of the canvas * @param height {number} the new height of the canvas */ -CanvasBuffer.prototype.resize = function (width, height) { +CanvasBuffer.prototype.resize = function (width, height) +{ this.canvas.width = width; this.canvas.height = height; }; diff --git a/src/core/renderers/canvas/utils/CanvasGraphics.js b/src/core/renderers/canvas/utils/CanvasGraphics.js index c7eaa2a..3f2a91f 100644 --- a/src/core/renderers/canvas/utils/CanvasGraphics.js +++ b/src/core/renderers/canvas/utils/CanvasGraphics.js @@ -13,15 +13,18 @@ * @param graphics {Graphics} the actual graphics object to render * @param context {CanvasRenderingContext2D} the 2d drawing method of the canvas */ -CanvasGraphics.renderGraphics = function (graphics, context) { +CanvasGraphics.renderGraphics = function (graphics, context) +{ var worldAlpha = graphics.worldAlpha; - if (graphics.dirty) { + if (graphics.dirty) + { this.updateGraphicsTint(graphics); graphics.dirty = false; } - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; @@ -30,69 +33,82 @@ context.lineWidth = data.lineWidth; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { context.beginPath(); var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } - if (shape.closed) { + if (shape.closed) + { context.lineTo(points[0], points[1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fillRect(shape.x, shape.y, shape.width, shape.height); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.strokeRect(shape.x, shape.y, shape.width, shape.height); } } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.beginPath(); context.arc(shape.x, shape.y, shape.radius,0,2*Math.PI); context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas var w = shape.width * 2; @@ -119,18 +135,21 @@ context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; var width = shape.width; @@ -152,13 +171,15 @@ context.quadraticCurveTo(rx, ry, rx, ry + radius); context.closePath(); - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); @@ -174,45 +195,54 @@ * @param graphics {Graphics} the graphics which will be used as a mask * @param context {CanvasRenderingContext2D} the context 2d method of the canvas */ -CanvasGraphics.renderGraphicsMask = function (graphics, context) { +CanvasGraphics.renderGraphicsMask = function (graphics, context) +{ var len = graphics.graphicsData.length; - if (len === 0) { + if (len === 0) + { return; } context.beginPath(); - for (var i = 0; i < len; i++) { + for (var i = 0; i < len; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { context.rect(shape.x, shape.y, shape.width, shape.height); context.closePath(); } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.arc(shape.x, shape.y, shape.radius, 0, 2 * Math.PI); context.closePath(); } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas @@ -237,7 +267,8 @@ context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); context.closePath(); } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; @@ -262,8 +293,10 @@ } }; -CanvasGraphics.updateGraphicsTint = function (graphics) { - if (graphics.tint === 0xFFFFFF) { +CanvasGraphics.updateGraphicsTint = function (graphics) +{ + if (graphics.tint === 0xFFFFFF) + { return; } @@ -271,7 +304,8 @@ var tintG = (graphics.tint >> 8 & 0xFF) / 255; var tintB = (graphics.tint & 0xFF)/ 255; - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var fillColor = data.fillColor | 0; diff --git a/src/core/renderers/canvas/utils/CanvasMaskManager.js b/src/core/renderers/canvas/utils/CanvasMaskManager.js index e04a733..9827d36 100644 --- a/src/core/renderers/canvas/utils/CanvasMaskManager.js +++ b/src/core/renderers/canvas/utils/CanvasMaskManager.js @@ -6,7 +6,8 @@ * @class * @namespace PIXI */ -function CanvasMaskManager() {} +function CanvasMaskManager() +{} CanvasMaskManager.prototype.constructor = CanvasMaskManager; module.exports = CanvasMaskManager; @@ -17,7 +18,8 @@ * @param maskData {object} the maskData that will be pushed * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.pushMask = function (maskData, renderer) { +CanvasMaskManager.prototype.pushMask = function (maskData, renderer) +{ renderer.context.save(); var cacheAlpha = maskData.alpha; @@ -45,6 +47,7 @@ * * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.popMask = function (renderer) { +CanvasMaskManager.prototype.popMask = function (renderer) +{ renderer.context.restore(); }; diff --git a/src/core/renderers/canvas/utils/CanvasTinter.js b/src/core/renderers/canvas/utils/CanvasTinter.js index 17e0529..d2fb1bc 100644 --- a/src/core/renderers/canvas/utils/CanvasTinter.js +++ b/src/core/renderers/canvas/utils/CanvasTinter.js @@ -14,7 +14,8 @@ * @param color {number} the color to use to tint the sprite with * @return {HTMLCanvasElement} The tinted canvas */ -CanvasTinter.getTintedTexture = function (sprite, color) { +CanvasTinter.getTintedTexture = function (sprite, color) +{ var texture = sprite.texture; color = CanvasTinter.roundColor(color); @@ -23,7 +24,8 @@ texture.tintCache = texture.tintCache || {}; - if (texture.tintCache[stringColor]) { + if (texture.tintCache[stringColor]) + { return texture.tintCache[stringColor]; } @@ -33,14 +35,16 @@ //CanvasTinter.tintWithPerPixel(texture, stringColor, canvas); CanvasTinter.tintMethod(texture, color, canvas); - if (CanvasTinter.convertTintToImage) { + if (CanvasTinter.convertTintToImage) + { // is this better? var tintImage = new Image(); tintImage.src = canvas.toDataURL(); texture.tintCache[stringColor] = tintImage; } - else { + else + { texture.tintCache[stringColor] = canvas; // if we are not converting the texture to an image then we need to lose the reference to the canvas CanvasTinter.canvas = null; @@ -56,7 +60,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithMultiply = function (texture, color, canvas) { +CanvasTinter.tintWithMultiply = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -104,7 +109,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithOverlay = function (texture, color, canvas) { +CanvasTinter.tintWithOverlay = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -139,7 +145,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithPerPixel = function (texture, color, canvas) { +CanvasTinter.tintWithPerPixel = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -167,7 +174,8 @@ var pixels = pixelData.data; - for (var i = 0; i < pixels.length; i += 4) { + for (var i = 0; i < pixels.length; i += 4) + { pixels[i+0] *= r; pixels[i+1] *= g; pixels[i+2] *= b; @@ -181,7 +189,8 @@ * * @param color {number} the color to round, should be a hex color */ -CanvasTinter.roundColor = function (color) { +CanvasTinter.roundColor = function (color) +{ var step = CanvasTinter.cacheStepsPerColorChannel; var rgbValues = utils.hex2rgb(color); diff --git a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js index 9f2f89a..35edbaf 100644 --- a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js +++ b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLBlendModeManager(renderer) { +function WebGLBlendModeManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -23,8 +24,10 @@ * * @param blendMode {number} the blendMode, should be a Pixi const, such as BlendModes.ADD */ -WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) { - if (this.currentBlendMode === blendMode) { +WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) +{ + if (this.currentBlendMode === blendMode) + { return false; } diff --git a/src/core/renderers/webgl/managers/WebGLFilterManager.js b/src/core/renderers/webgl/managers/WebGLFilterManager.js index 1179258..2dac048 100644 --- a/src/core/renderers/webgl/managers/WebGLFilterManager.js +++ b/src/core/renderers/webgl/managers/WebGLFilterManager.js @@ -7,7 +7,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLFilterManager(renderer) { +function WebGLFilterManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -32,7 +33,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.texturePool.length = 0; self.initShaderBuffers(); }); @@ -46,7 +48,8 @@ * @param renderer {WebGLRenderer} * @param buffer {ArrayBuffer} */ -WebGLFilterManager.prototype.begin = function (buffer) { +WebGLFilterManager.prototype.begin = function (buffer) +{ this.defaultShader = this.renderer.shaderManager.defaultShader; this.width = this.renderer.projection.x * 2; @@ -60,7 +63,8 @@ * * @param filterBlock {object} the filter that will be pushed to the current filter stack */ -WebGLFilterManager.prototype.pushFilter = function (filterBlock) { +WebGLFilterManager.prototype.pushFilter = function (filterBlock) +{ var gl = this.renderer.gl; var projection = this.renderer.projection; @@ -78,10 +82,12 @@ this.offsetY += filterBlock._filterArea.y; var texture = this.texturePool.pop(); - if (!texture) { + if (!texture) + { texture = new FilterTexture(this.renderer.gl, this.width, this.height); } - else { + else + { texture.resize(this.width, this.height); } @@ -98,29 +104,35 @@ var localX = filterArea.x, localY = filterArea.y; - if (filterArea.x < 0) { + if (filterArea.x < 0) + { filterArea.width += filterArea.x; filterArea.x = 0; } - if (filterArea.y < 0) { + if (filterArea.y < 0) + { filterArea.height += filterArea.y; filterArea.y = 0; } - if (localX + filterArea.width > this.width) { + if (localX + filterArea.width > this.width) + { filterArea.width = this.width - localX; } - if (localY + filterArea.height > this.height) { + if (localY + filterArea.height > this.height) + { filterArea.height = this.height - localY; } - if (filterArea.width < 0) { + if (filterArea.width < 0) + { filterArea.width = 0; } - if (filterArea.height < 0) { + if (filterArea.height < 0) + { filterArea.height = 0; } @@ -154,7 +166,8 @@ * Removes the last filter from the filter stack and doesn't return it. * */ -WebGLFilterManager.prototype.popFilter = function () { +WebGLFilterManager.prototype.popFilter = function () +{ var gl = this.renderer.gl; var filterBlock = this.filterStack.pop(); @@ -163,7 +176,8 @@ var projection = this.renderer.projection; var offset = this.renderer.offset; - if (filterBlock.filterPasses.length > 1) { + if (filterBlock.filterPasses.length > 1) + { gl.viewport(0, 0, filterArea.width, filterArea.height); gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); @@ -193,7 +207,8 @@ var inputTexture = texture; var outputTexture = this.texturePool.pop(); - if (!outputTexture) { + if (!outputTexture) + { outputTexture = new FilterTexture(this.renderer.gl, this.width, this.height); } outputTexture.resize(this.width, this.height); @@ -204,7 +219,8 @@ gl.disable(gl.BLEND); - for (var i = 0; i < filterBlock.filterPasses.length-1; i++) { + for (var i = 0; i < filterBlock.filterPasses.length-1; i++) + { var filterPass = filterBlock.filterPasses[i]; gl.bindFramebuffer(gl.FRAMEBUFFER, outputTexture.frameBuffer ); @@ -243,10 +259,12 @@ var buffer = this.buffer; // time to render the filters texture to the previous scene - if (this.filterStack.length === 0) { + if (this.filterStack.length === 0) + { gl.colorMask(true, true, true, true);//this.transparent); } - else { + else + { var currentFilter = this.filterStack[this.filterStack.length-1]; filterArea = currentFilter._filterArea; @@ -332,13 +350,15 @@ * @param width {number} the horizontal range of the filter * @param height {number} the vertical range of the filter */ -WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) { +WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) +{ // use program var gl = this.renderer.gl; var shader = filter.shaders[gl.id]; - if (!shader) { + if (!shader) + { shader = new Shader(gl); shader.fragmentSrc = filter.fragmentSrc; @@ -356,7 +376,8 @@ gl.uniform2f(shader.projectionVector, width/2, -height/2); gl.uniform2f(shader.offsetVector, 0,0); - if (filter.uniforms.dimensions) { + 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]; @@ -386,7 +407,8 @@ * Initialises the shader buffers. * */ -WebGLFilterManager.prototype.initShaderBuffers = function () { +WebGLFilterManager.prototype.initShaderBuffers = function () +{ var gl = this.renderer.gl; // create some buffers @@ -432,7 +454,8 @@ * Destroys the filter and removes it from the filter stack. * */ -WebGLFilterManager.prototype.destroy = function () { +WebGLFilterManager.prototype.destroy = function () +{ var gl = this.renderer.gl; this.filterStack = null; @@ -441,7 +464,8 @@ this.offsetY = 0; // destroy textures - for (var i = 0; i < this.texturePool.length; i++) { + for (var i = 0; i < this.texturePool.length; i++) + { this.texturePool[i].destroy(); } diff --git a/src/core/renderers/webgl/managers/WebGLManager.js b/src/core/renderers/webgl/managers/WebGLManager.js index 9d47b5c..c30cd51 100644 --- a/src/core/renderers/webgl/managers/WebGLManager.js +++ b/src/core/renderers/webgl/managers/WebGLManager.js @@ -3,7 +3,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLManager(renderer) { +function WebGLManager(renderer) +{ /** * The renderer this manager works for. * @@ -15,6 +16,7 @@ WebGLManager.prototype.constructor = WebGLManager; module.exports = WebGLManager; -WebGLManager.prototype.destroy = function () { +WebGLManager.prototype.destroy = function () +{ this.renderer = null; }; diff --git a/src/core/renderers/webgl/managers/WebGLMaskManager.js b/src/core/renderers/webgl/managers/WebGLMaskManager.js index 2f90b64..e568812 100644 --- a/src/core/renderers/webgl/managers/WebGLMaskManager.js +++ b/src/core/renderers/webgl/managers/WebGLMaskManager.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLMaskManager(renderer) { +function WebGLMaskManager(renderer) +{ WebGLManager.call(this, renderer); } @@ -19,12 +20,15 @@ * * @param maskData {any[]} */ -WebGLMaskManager.prototype.pushMask = function (maskData) { - if (maskData.dirty) { +WebGLMaskManager.prototype.pushMask = function (maskData) +{ + if (maskData.dirty) + { WebGLGraphics.updateGraphics(maskData, this.renderer.gl); } - if (!maskData._webGL[this.renderer.gl.id].data.length) { + if (!maskData._webGL[this.renderer.gl.id].data.length) + { return; } @@ -36,6 +40,7 @@ * * @param maskData {any[]} */ -WebGLMaskManager.prototype.popMask = function (maskData) { +WebGLMaskManager.prototype.popMask = function (maskData) +{ this.renderer.stencilManager.popStencil(maskData, maskData._webGL[this.renderer.gl.id].data[0], this.renderer); }; diff --git a/src/core/renderers/webgl/managers/WebGLShaderManager.js b/src/core/renderers/webgl/managers/WebGLShaderManager.js index fef071c..90c6477 100644 --- a/src/core/renderers/webgl/managers/WebGLShaderManager.js +++ b/src/core/renderers/webgl/managers/WebGLShaderManager.js @@ -10,7 +10,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLShaderManager(renderer) { +function WebGLShaderManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -28,7 +29,8 @@ */ this.tempAttribState = []; - for (var i = 0; i < this.maxAttibs; i++) { + for (var i = 0; i < this.maxAttibs; i++) + { this.attribState[i] = false; } @@ -66,7 +68,8 @@ // listen for context and update necessary shaders var self = this; - this.renderer.on('context', function (event) { + this.renderer.on('context', function (event) + { var gl = event.data; // this shader is used for rendering primitives @@ -97,29 +100,36 @@ * * @param attribs {Array} attribs */ -WebGLShaderManager.prototype.setAttribs = function (attribs) { +WebGLShaderManager.prototype.setAttribs = function (attribs) +{ // reset temp state var i; - for (i = 0; i < this.tempAttribState.length; i++) { + for (i = 0; i < this.tempAttribState.length; i++) + { this.tempAttribState[i] = false; } // set the new attribs - for (var a in attribs) { + for (var a in attribs) + { this.tempAttribState[attribs[a]] = true; } var gl = this.renderer.gl; - for (i = 0; i < this.attribState.length; i++) { - if (this.attribState[i] !== this.tempAttribState[i]) { + for (i = 0; i < this.attribState.length; i++) + { + if (this.attribState[i] !== this.tempAttribState[i]) + { this.attribState[i] = this.tempAttribState[i]; - if (this.attribState[i]) { + if (this.attribState[i]) + { gl.enableVertexAttribArray(i); } - else { + else + { gl.disableVertexAttribArray(i); } } @@ -131,8 +141,10 @@ * * @param shader {Any} */ -WebGLShaderManager.prototype.setShader = function (shader) { - if (this._currentId === shader.uuid) { +WebGLShaderManager.prototype.setShader = function (shader) +{ + if (this._currentId === shader.uuid) + { return false; } @@ -150,7 +162,8 @@ * Destroys this object. * */ -WebGLShaderManager.prototype.destroy = function () { +WebGLShaderManager.prototype.destroy = function () +{ this.attribState = null; this.tempAttribState = null; diff --git a/src/core/renderers/webgl/managers/WebGLStencilManager.js b/src/core/renderers/webgl/managers/WebGLStencilManager.js index 9ec6398..4cb0134 100644 --- a/src/core/renderers/webgl/managers/WebGLStencilManager.js +++ b/src/core/renderers/webgl/managers/WebGLStencilManager.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLStencilManager(renderer) { +function WebGLStencilManager(renderer) +{ WebGLManager.call(this, renderer); this.stencilStack = []; @@ -24,12 +25,14 @@ * @param graphics {Graphics} * @param webGLData {any[]} */ -WebGLStencilManager.prototype.pushStencil = function (graphics, webGLData) { +WebGLStencilManager.prototype.pushStencil = function (graphics, webGLData) +{ var gl = this.renderer.gl; this.bindGraphics(graphics, webGLData, this.renderer); - if (this.stencilStack.length === 0) { + if (this.stencilStack.length === 0) + { gl.enable(gl.STENCIL_TEST); gl.clear(gl.STENCIL_BUFFER_BIT); this.reverse = true; @@ -47,14 +50,17 @@ // draw the triangle strip! - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } @@ -62,31 +68,38 @@ // draw a quad to increment.. gl.drawElements(gl.TRIANGLE_FAN, 4, gl.UNSIGNED_SHORT, ( webGLData.indices.length - 4 ) * 2 ); - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); } this.reverse = !this.reverse; } - else { - if (!this.reverse) { + else + { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } - else { + 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) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); } } @@ -103,7 +116,8 @@ * @param graphics {Graphics} * @param webGLData {Array} */ -WebGLStencilManager.prototype.bindGraphics = function (graphics, webGLData) { +WebGLStencilManager.prototype.bindGraphics = function (graphics, webGLData) +{ //if (this._currentGraphics === graphics)return; this._currentGraphics = graphics; @@ -114,7 +128,8 @@ offset = this.renderer.offset, shader;// = this.renderer.shaderManager.primitiveShader; - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { shader = this.renderer.shaderManager.complexPrimitiveShader; this.renderer.shaderManager.setShader(shader); @@ -141,7 +156,8 @@ // set the index buffer! gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, webGLData.indexBuffer); } - else { + else + { //this.renderer.shaderManager.activatePrimitiveShader(); shader = this.renderer.shaderManager.primitiveShader; this.renderer.shaderManager.setShader( shader ); @@ -154,7 +170,7 @@ gl.uniform2f(shader.uniforms.offsetVector._location, -offset.x, -offset.y); gl.uniform3fv(shader.uniforms.tint._location, utils.hex2rgb(graphics.tint)); - + gl.uniform1f(shader.uniforms.alpha._location, graphics.worldAlpha); @@ -172,19 +188,22 @@ * @param graphics {Graphics} * @param webGLData {Array} */ -WebGLStencilManager.prototype.popStencil = function (graphics, webGLData) { +WebGLStencilManager.prototype.popStencil = function (graphics, webGLData) +{ var gl = this.renderer.gl; this.stencilStack.pop(); this.count--; - if (this.stencilStack.length === 0) { + if (this.stencilStack.length === 0) + { // the stack is empty! gl.disable(gl.STENCIL_TEST); } - else { + else + { var level = this.count; @@ -192,14 +211,17 @@ gl.colorMask(false, false, false, false); - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { this.reverse = !this.reverse; - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } @@ -213,31 +235,38 @@ // draw the triangle strip! gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); - if (!this.reverse) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); } } - else { + else + { // console.log("<<>>") - if (!this.reverse) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } - else { + 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) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); } } @@ -253,7 +282,8 @@ * Destroys the mask stack. * */ -WebGLStencilManager.prototype.destroy = function () { +WebGLStencilManager.prototype.destroy = function () +{ this.renderer = null; this.stencilStack = null; }; diff --git a/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js b/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js index 913ba5e..1ea7d19 100644 --- a/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js +++ b/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function ComplexPrimitiveShader(gl) { +function ComplexPrimitiveShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -24,7 +25,8 @@ 'uniform float flipY;', 'varying vec4 vColor;', - 'void main(void) {', + '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);', @@ -37,7 +39,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = vColor;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/FastShader.js b/src/core/renderers/webgl/shaders/FastShader.js index bd2e29a..2e5e060 100644 --- a/src/core/renderers/webgl/shaders/FastShader.js +++ b/src/core/renderers/webgl/shaders/FastShader.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function FastShader(gl) { +function FastShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -28,7 +29,8 @@ 'const vec2 center = vec2(-1.0, 1.0);', - 'void main(void) {', + 'void main(void) + {', ' vec2 v;', ' vec2 sv = aVertexPosition * aScale;', ' v.x = (sv.x) * cos(aRotation) - (sv.y) * sin(aRotation);', @@ -49,7 +51,8 @@ 'uniform sampler2D uSampler;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/PrimitiveShader.js b/src/core/renderers/webgl/shaders/PrimitiveShader.js index 6f25409..a25f54f 100644 --- a/src/core/renderers/webgl/shaders/PrimitiveShader.js +++ b/src/core/renderers/webgl/shaders/PrimitiveShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function PrimitiveShader(gl) { +function PrimitiveShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -23,7 +24,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + '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);', @@ -36,7 +38,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = vColor;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/Shader.js b/src/core/renderers/webgl/shaders/Shader.js index f8964f5..fd75ef5 100644 --- a/src/core/renderers/webgl/shaders/Shader.js +++ b/src/core/renderers/webgl/shaders/Shader.js @@ -6,7 +6,8 @@ * @param [fragmentSrc] {string} The source of the fragment shader. * @param [vertexSrc] {string} The source of the vertex shader. */ -function Shader(gl, vertexSrc, fragmentSrc, customUniforms, customAttributes) { +function Shader(gl, vertexSrc, fragmentSrc, customUniforms, customAttributes) +{ /** * @member {number} * @readonly @@ -33,7 +34,8 @@ dimensions: { type: '4f', value: new Float32Array(4) } }; - for (var u in customUniforms) { + for (var u in customUniforms) + { this.uniforms[u] = customUniforms[u]; } @@ -43,7 +45,8 @@ aColor: 0 }; - for (var a in customAttributes) { + for (var a in customAttributes) + { this.attributes[a] = customAttributes[a]; } @@ -66,7 +69,8 @@ 'const vec2 center = vec2(-1.0, 1.0);', - 'void main(void) {', + 'void main(void) + {', ' gl_Position = vec4( ((aVertexPosition + offsetVector) / projectionVector) + center , 0.0, 1.0);', ' vTextureCoord = aTextureCoord;', ' vColor = vec4(aColor.rgb * aColor.a, aColor.a);', @@ -85,7 +89,8 @@ 'uniform sampler2D uSampler;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;', '}' ].join('\n'); @@ -96,7 +101,8 @@ Shader.prototype.constructor = Shader; module.exports = Shader; -Shader.prototype.init = function () { +Shader.prototype.init = function () +{ this.compile(); this.gl.useProgram(this.program); @@ -105,14 +111,18 @@ this.cacheAttributeLocations(Object.keys(this.attributes)); }; -Shader.prototype.cacheUniformLocations = function (keys) { - for (var i = 0; i < keys.length; ++i) { +Shader.prototype.cacheUniformLocations = function (keys) +{ + for (var i = 0; i < keys.length; ++i) + { this.uniforms[keys[i]]._location = this.gl.getUniformLocation(this.program, keys[i]); } }; -Shader.prototype.cacheAttributeLocations = function (keys) { - for (var i = 0; i < keys.length; ++i) { +Shader.prototype.cacheAttributeLocations = function (keys) +{ + for (var i = 0; i < keys.length; ++i) + { this.attributes[keys[i]] = this.gl.getAttribLocation(this.program, keys[i]); } @@ -124,14 +134,16 @@ // 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.attributes.aColor === -1) { + // if (this.attributes.aColor === -1) + { // this.attributes.aColor = 2; // } // End worst hack eva // }; -Shader.prototype.compile = function () { +Shader.prototype.compile = function () +{ var gl = this.gl; var glVertShader = this._glCompile(gl.VERTEX_SHADER, this.vertexSrc); @@ -144,13 +156,15 @@ gl.linkProgram(program); // if linking fails, then log and cleanup - if (!gl.getProgramParameter(program, gl.LINK_STATUS)) { + if (!gl.getProgramParameter(program, gl.LINK_STATUS)) + { window.console.error('Pixi.js Error: Could not initialize shader.'); window.console.error('gl.VALIDATE_STATUS', gl.getProgramParameter(program, gl.VALIDATE_STATUS)); window.console.error('gl.getError()', gl.getError()); // if there is a program info log, log it - if (gl.getProgramInfoLog(program) !== '') { + if (gl.getProgramInfoLog(program) !== '') + { window.console.warn('Pixi.js Warning: gl.getProgramInfoLog()', gl.getProgramInfoLog(program)); } @@ -165,18 +179,21 @@ return (this.program = program); }; -Shader.prototype.syncUniforms = function () { +Shader.prototype.syncUniforms = function () +{ var gl = this.gl; this.textureCount = 1; - for (var key in this.uniforms) { + for (var key in this.uniforms) + { var uniform = this.uniforms[key], location = uniform._location, value = uniform.value, i, il; - switch (uniform.type) { + switch (uniform.type) + { // single int value case 'i': case '1i': @@ -282,7 +299,8 @@ // a Color Value case 'c': - if (typeof value === 'number') { + if (typeof value === 'number') + { value = utils.hex2rgb(value); } @@ -311,11 +329,13 @@ // array of 2D Point objects case 'v2v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(2 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 2] = value[i].x; uniform._array[i * 2 + 1] = value[i].y; } @@ -325,11 +345,13 @@ // array of 3D Point objects case 'v3v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(3 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 3] = value[i].x; uniform._array[i * 3 + 1] = value[i].y; uniform._array[i * 3 + 2] = value[i].z; @@ -341,11 +363,13 @@ // array of 4D Point objects case 'v4v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(4 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 4] = value[i].x; uniform._array[i * 4 + 1] = value[i].y; uniform._array[i * 4 + 2] = value[i].z; @@ -359,7 +383,8 @@ // PIXI.Texture case 't': case 'sampler2D': - if (!uniform.value || !uniform.value.baseTexture || !uniform.value.baseTexture.hasLoaded) { + if (!uniform.value || !uniform.value.baseTexture || !uniform.value.baseTexture.hasLoaded) + { break; } @@ -376,7 +401,8 @@ this.textureCount++; // initialize the texture if we haven't yet - if (!uniform._init) { + if (!uniform._init) + { this.initSampler2D(uniform); uniform._init = true; @@ -394,11 +420,13 @@ * Initialises a Sampler2D uniform (which may only be available later on after initUniforms once the texture has loaded) * */ -Shader.prototype.initSampler2D = function (uniform) { +Shader.prototype.initSampler2D = function (uniform) +{ var gl = this.gl; // Extended texture data - if (uniform.textureData) { + if (uniform.textureData) + { var data = uniform.textureData; // GLTexture = mag linear, min linear_mipmap_linear, wrap repeat + gl.generateMipmap(gl.TEXTURE_2D); @@ -417,14 +445,16 @@ var wrapT = (data.wrapT) ? data.wrapT : gl.CLAMP_TO_EDGE; var format = (data.luminance) ? gl.LUMINANCE : gl.RGBA; - if (data.repeat) { + if (data.repeat) + { wrapS = gl.REPEAT; wrapT = gl.REPEAT; } gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, !!data.flipY); - if (data.width) { + if (data.width) + { var width = (data.width) ? data.width : 512; var height = (data.height) ? data.height : 2; var border = (data.border) ? data.border : 0; @@ -432,7 +462,8 @@ // 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 { + 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); } @@ -448,7 +479,8 @@ * Destroys the shader. * */ -Shader.prototype.destroy = function () { +Shader.prototype.destroy = function () +{ this.gl.deleteProgram(this.program); this.gl = null; @@ -459,13 +491,15 @@ this.fragmentSrc = null; }; -Shader.prototype._glCompile = function (type, src) { +Shader.prototype._glCompile = function (type, src) +{ var shader = this.gl.createShader(type); this.gl.shaderSource(shader, src); this.gl.compileShader(shader); - if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) { + if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) + { window.console.log(this.gl.getShaderInfoLog(shader)); return null; } diff --git a/src/core/renderers/webgl/shaders/StripShader.js b/src/core/renderers/webgl/shaders/StripShader.js index 193f6e1..a7abcc6 100644 --- a/src/core/renderers/webgl/shaders/StripShader.js +++ b/src/core/renderers/webgl/shaders/StripShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function StripShader(gl) { +function StripShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -20,7 +21,8 @@ 'varying vec2 vTextureCoord;', - 'void main(void) {', + '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);', @@ -36,7 +38,8 @@ 'varying vec2 vTextureCoord;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vec2(vTextureCoord.x, vTextureCoord.y)) * alpha;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/utils/FilterTexture.js b/src/core/renderers/webgl/utils/FilterTexture.js index d2c8423..4433d44 100644 --- a/src/core/renderers/webgl/utils/FilterTexture.js +++ b/src/core/renderers/webgl/utils/FilterTexture.js @@ -8,7 +8,8 @@ * @param height {number} the vertical range of the filter * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values */ -function FilterTexture(gl, width, height, scaleMode) { +function FilterTexture(gl, width, height, scaleMode) +{ /** * @member {WebGLContext} */ @@ -59,7 +60,8 @@ * Clears the filter texture. * */ -FilterTexture.prototype.clear = function () { +FilterTexture.prototype.clear = function () +{ var gl = this.gl; gl.clearColor(0,0,0, 0); @@ -72,8 +74,10 @@ * @param width {number} the new width of the texture * @param height {number} the new height of the texture */ -FilterTexture.prototype.resize = function (width, height) { - if (this.width === width && this.height === height) { +FilterTexture.prototype.resize = function (width, height) +{ + if (this.width === width && this.height === height) + { return; } @@ -96,7 +100,8 @@ * Destroys the filter texture. * */ -FilterTexture.prototype.destroy = function () { +FilterTexture.prototype.destroy = function () +{ var gl = this.gl; gl.deleteFramebuffer( this.frameBuffer ); gl.deleteTexture( this.texture ); diff --git a/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js b/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js index c4721e9..a63f4d7 100644 --- a/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js +++ b/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js @@ -14,7 +14,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this sprite batch works for. */ -function WebGLFastSpriteBatch(renderer) { +function WebGLFastSpriteBatch(renderer) +{ /** * The renderer instance this sprite batch operates on. * @@ -91,7 +92,8 @@ */ this.lastIndexCount = 0; - for (var i=0, j=0; i < numIndices; i += 6, j += 4) { + 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; @@ -144,7 +146,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.setupContext(); }); } @@ -157,7 +160,8 @@ * * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLFastSpriteBatch.prototype.setupContext = function () { +WebGLFastSpriteBatch.prototype.setupContext = function () +{ var gl = this.renderer.gl; // create a couple of buffers @@ -177,7 +181,8 @@ /** * @param spriteBatch {SpriteBatch} The SpriteBatch container to prepare for. */ -WebGLFastSpriteBatch.prototype.begin = function (spriteBatch) { +WebGLFastSpriteBatch.prototype.begin = function (spriteBatch) +{ this.shader = this.renderer.shaderManager.fastShader; this.matrix = spriteBatch.worldTransform.toArray(true); @@ -187,33 +192,38 @@ /** */ -WebGLFastSpriteBatch.prototype.end = function () { +WebGLFastSpriteBatch.prototype.end = function () +{ this.flush(); }; /** * @param spriteBatch {SpriteBatch} The SpriteBatch container to render. */ -WebGLFastSpriteBatch.prototype.render = function (spriteBatch) { +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) { + if (!sprite.texture._uvs) + { return; } this.currentBaseTexture = sprite.texture.baseTexture; // check blend mode - if (sprite.blendMode !== this.renderer.blendModeManager.currentBlendMode) { + if (sprite.blendMode !== this.renderer.blendModeManager.currentBlendMode) + { this.flush(); this.renderer.blendModeManager.setBlendMode(sprite.blendMode); } - for (var i=0,j= children.length; i= this.size) { + if (this.currentBatchSize >= this.size) + { this.flush(); } }; @@ -362,29 +379,35 @@ /** * */ -WebGLFastSpriteBatch.prototype.flush = function () { +WebGLFastSpriteBatch.prototype.flush = function () +{ // If the batch is length 0 then return as there is nothing to draw - if (this.currentBatchSize === 0) { + if (this.currentBatchSize === 0) + { return; } var gl = this.renderer.gl; // bind the current texture - if (!this.currentBaseTexture._glTextures[gl.id]) { + if (!this.currentBaseTexture._glTextures[gl.id]) + { this.renderer.updateTexture(this.currentBaseTexture, gl); } //TODO-SHOUD THIS BE ELSE??!?!?! - else { + else + { gl.bindTexture(gl.TEXTURE_2D, this.currentBaseTexture._glTextures[gl.id]); } // upload the verts to the buffer - if (this.currentBatchSize > ( this.size * 0.5 ) ) { + if (this.currentBatchSize > ( this.size * 0.5 ) ) + { gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); } - else { + else + { var view = this.vertices.subarray(0, this.currentBatchSize * this.vertByteSize); gl.bufferSubData(gl.ARRAY_BUFFER, 0, view); @@ -405,14 +428,16 @@ * Ends the batch and flushes * */ -WebGLFastSpriteBatch.prototype.stop = function () { +WebGLFastSpriteBatch.prototype.stop = function () +{ this.flush(); }; /** * */ -WebGLFastSpriteBatch.prototype.start = function () { +WebGLFastSpriteBatch.prototype.start = function () +{ var gl = this.renderer.gl; // bind the main texture diff --git a/src/core/renderers/webgl/utils/WebGLGraphics.js b/src/core/renderers/webgl/utils/WebGLGraphics.js index 55f4911..ab8f46e 100644 --- a/src/core/renderers/webgl/utils/WebGLGraphics.js +++ b/src/core/renderers/webgl/utils/WebGLGraphics.js @@ -19,7 +19,8 @@ * @param graphics {Graphics} * @param renderer {WebGLRenderer} */ -WebGLGraphics.renderGraphics = function (graphics, renderer) {//projection, offset) { +WebGLGraphics.renderGraphics = function (graphics, renderer) {//projection, offset) +{ var gl = renderer.gl; var projection = renderer.projection, @@ -27,7 +28,8 @@ shader = renderer.shaderManager.primitiveShader, webGLData; - if (graphics.dirty) { + if (graphics.dirty) + { WebGLGraphics.updateGraphics(graphics, gl); } @@ -35,8 +37,10 @@ // This could be speeded up for sure! - for (var i = 0; i < webGL.data.length; i++) { - if (webGL.data[i].mode === 1) { + for (var i = 0; i < webGL.data.length; i++) + { + if (webGL.data[i].mode === 1) + { webGLData = webGL.data[i]; renderer.stencilManager.pushStencil(graphics, webGLData, renderer); @@ -46,7 +50,8 @@ renderer.stencilManager.popStencil(graphics, webGLData, renderer); } - else { + else + { webGLData = webGL.data[i]; @@ -84,12 +89,14 @@ * @param graphicsData {Graphics} The graphics object to update * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLGraphics.updateGraphics = function (graphics, gl) { +WebGLGraphics.updateGraphics = function (graphics, gl) +{ // get the contexts graphics object var webGL = graphics._webGL[gl.id]; // if the graphics object does not exist in the webGL context time to create it! - if (!webGL) { + if (!webGL) + { webGL = graphics._webGL[gl.id] = {lastIndex:0, data:[], gl:gl}; } @@ -99,11 +106,13 @@ var i; // if the user cleared the graphics object we will need to clear every object - if (graphics.clearDirty) { + if (graphics.clearDirty) + { graphics.clearDirty = false; // lop through and return all the webGLDatas to the object pool so than can be reused later on - for (i = 0; i < webGL.data.length; i++) { + for (i = 0; i < webGL.data.length; i++) + { var graphicsData = webGL.data[i]; graphicsData.reset(); WebGLGraphics.graphicsDataPool.push( graphicsData ); @@ -119,58 +128,72 @@ // loop through the graphics datas and construct each one.. // if the object is a complex fill then the new stencil buffer technique will be used // other wise graphics objects will be pushed into a batch.. - for (i = webGL.lastIndex; i < graphics.graphicsData.length; i++) { + for (i = webGL.lastIndex; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { // need to add the points the the graphics object.. data.points = data.shape.points.slice(); - if (data.shape.closed) { + if (data.shape.closed) + { // close the poly if the value is true! - if (data.points[0] !== data.points[data.points.length-2] || data.points[1] !== data.points[data.points.length-1]) { + if (data.points[0] !== data.points[data.points.length-2] || data.points[1] !== data.points[data.points.length-1]) + { data.points.push(data.points[0], data.points[1]); } } // MAKE SURE WE HAVE THE CORRECT TYPE.. - if (data.fill) { - if (data.points.length >= 6) { - if (data.points.length < 6 * 2) { + if (data.fill) + { + if (data.points.length >= 6) + { + if (data.points.length < 6 * 2) + { webGLData = WebGLGraphics.switchMode(webGL, 0); var canDrawUsingSimple = WebGLGraphics.buildPoly(data, webGLData); // console.log(canDrawUsingSimple); - if (!canDrawUsingSimple) { + if (!canDrawUsingSimple) + { // console.log("<>>>") webGLData = WebGLGraphics.switchMode(webGL, 1); WebGLGraphics.buildComplexPoly(data, webGLData); } } - else { + else + { webGLData = WebGLGraphics.switchMode(webGL, 1); WebGLGraphics.buildComplexPoly(data, webGLData); } } } - if (data.lineWidth > 0) { + if (data.lineWidth > 0) + { webGLData = WebGLGraphics.switchMode(webGL, 0); WebGLGraphics.buildLine(data, webGLData); } } - else { + else + { webGLData = WebGLGraphics.switchMode(webGL, 0); - if (data.type === CONST.SHAPES.RECT) { + if (data.type === CONST.SHAPES.RECT) + { WebGLGraphics.buildRectangle(data, webGLData); } - else if (data.type === CONST.SHAPES.CIRC || data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.CIRC || data.type === CONST.SHAPES.ELIP) + { WebGLGraphics.buildCircle(data, webGLData); } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { WebGLGraphics.buildRoundedRectangle(data, webGLData); } } @@ -179,10 +202,12 @@ } // upload all the dirty data... - for (i = 0; i < webGL.data.length; i++) { + for (i = 0; i < webGL.data.length; i++) + { webGLData = webGL.data[i]; - if (webGLData.dirty) { + if (webGLData.dirty) + { webGLData.upload(); } } @@ -194,18 +219,22 @@ * @param webGL {WebGLContext} * @param type {number} */ -WebGLGraphics.switchMode = function (webGL, type) { +WebGLGraphics.switchMode = function (webGL, type) +{ var webGLData; - if (!webGL.data.length) { + if (!webGL.data.length) + { webGLData = WebGLGraphics.graphicsDataPool.pop() || new WebGLGraphicsData(webGL.gl); webGLData.mode = type; webGL.data.push(webGLData); } - else { + else + { webGLData = webGL.data[webGL.data.length-1]; - if (webGLData.mode !== type || type === 1) { + if (webGLData.mode !== type || type === 1) + { webGLData = WebGLGraphics.graphicsDataPool.pop() || new WebGLGraphicsData(webGL.gl); webGLData.mode = type; webGL.data.push(webGLData); @@ -225,7 +254,8 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildRectangle = function (graphicsData, webGLData) { +WebGLGraphics.buildRectangle = function (graphicsData, webGLData) +{ // --- // // need to convert points to a nice regular data // @@ -235,7 +265,8 @@ var width = rectData.width; var height = rectData.height; - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -265,7 +296,8 @@ indices.push(vertPos, vertPos, vertPos+1, vertPos+2, vertPos+3, vertPos+3); } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = [x, y, @@ -289,7 +321,8 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildRoundedRectangle = function (graphicsData, webGLData) { +WebGLGraphics.buildRoundedRectangle = function (graphicsData, webGLData) +{ var rrectData = graphicsData.shape; var x = rrectData.x; var y = rrectData.y; @@ -305,7 +338,8 @@ recPoints = recPoints.concat(WebGLGraphics.quadraticBezierCurve(x + width, y + radius, x + width, y, x + width - radius, y)); recPoints = recPoints.concat(WebGLGraphics.quadraticBezierCurve(x + radius, y, x, y, x, y + radius)); - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -323,7 +357,8 @@ // var i = 0; - for (i = 0; i < triangles.length; i+=3) { + for (i = 0; i < triangles.length; i+=3) + { indices.push(triangles[i] + vecPos); indices.push(triangles[i] + vecPos); indices.push(triangles[i+1] + vecPos); @@ -332,12 +367,14 @@ } - for (i = 0; i < recPoints.length; i++) { + for (i = 0; i < recPoints.length; i++) + { verts.push(recPoints[i], recPoints[++i], r, g, b, alpha); } } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = recPoints; @@ -362,7 +399,8 @@ * @param toY {number} Destination point y * @return {number[]} */ -WebGLGraphics.quadraticBezierCurve = function (fromX, fromY, cpX, cpY, toX, toY) { +WebGLGraphics.quadraticBezierCurve = function (fromX, fromY, cpX, cpY, toX, toY) +{ var xa, ya, @@ -373,14 +411,16 @@ n = 20, points = []; - function getPt(n1 , n2, perc) { + function getPt(n1 , n2, perc) + { var diff = n2 - n1; return n1 + ( diff * perc ); } var j = 0; - for (var i = 0; i <= n; i++ ) { + for (var i = 0; i <= n; i++ ) + { j = i / n; // The Green Line @@ -406,7 +446,8 @@ * @param graphicsData {Graphics} The graphics object to draw * @param webGLData {object} */ -WebGLGraphics.buildCircle = function (graphicsData, webGLData) { +WebGLGraphics.buildCircle = function (graphicsData, webGLData) +{ // need to convert points to a nice regular data var circleData = graphicsData.shape; var x = circleData.x; @@ -415,11 +456,13 @@ var height; // TODO - bit hacky?? - if (graphicsData.type === CONST.SHAPES.CIRC) { + if (graphicsData.type === CONST.SHAPES.CIRC) + { width = circleData.radius; height = circleData.radius; } - else { + else + { width = circleData.width; height = circleData.height; } @@ -429,7 +472,8 @@ var i = 0; - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -444,7 +488,8 @@ indices.push(vecPos); - for (i = 0; i < totalSegs + 1 ; i++) { + for (i = 0; i < totalSegs + 1 ; i++) + { verts.push(x,y, r, g, b, alpha); verts.push(x + Math.sin(seg * i) * width, @@ -457,12 +502,14 @@ indices.push(vecPos-1); } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = []; - for (i = 0; i < totalSegs + 1; i++) { + for (i = 0; i < totalSegs + 1; i++) + { graphicsData.points.push(x + Math.sin(seg * i) * width, y + Math.cos(seg * i) * height); } @@ -481,18 +528,22 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildLine = function (graphicsData, webGLData) { +WebGLGraphics.buildLine = function (graphicsData, webGLData) +{ // TODO OPTIMISE! var i = 0; var points = graphicsData.points; - if (points.length === 0) { + if (points.length === 0) + { return; } // if the line width is an odd number add 0.5 to align to a whole pixel - if (graphicsData.lineWidth%2) { - for (i = 0; i < points.length; i++) { + if (graphicsData.lineWidth%2) + { + for (i = 0; i < points.length; i++) + { points[i] += 0.5; } } @@ -502,7 +553,8 @@ var lastPoint = new math.Point(points[points.length - 2], points[points.length - 1]); // if the first point is the last point - gonna have issues :) - if (firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) { + if (firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) + { // need to clone as we are going to slightly modify the shape.. points = points.slice(); @@ -562,7 +614,8 @@ verts.push(p1x + perpx , p1y + perpy, r, g, b, alpha); - for (i = 1; i < length-1; i++) { + for (i = 1; i < length-1; i++) + { p1x = points[(i-1)*2]; p1y = points[(i-1)*2 + 1]; @@ -599,7 +652,8 @@ denom = a1*b2 - a2*b1; - if (Math.abs(denom) < 0.1 ) { + if (Math.abs(denom) < 0.1 ) + { denom+=10.1; verts.push(p2x - perpx , p2y - perpy, @@ -618,7 +672,8 @@ pdist = (px -p2x) * (px -p2x) + (py -p2y) + (py -p2y); - if (pdist > 140 * 140) { + if (pdist > 140 * 140) + { perp3x = perpx - perp2x; perp3y = perpy - perp2y; @@ -639,7 +694,8 @@ indexCount++; } - else { + else + { verts.push(px , py); verts.push(r, g, b, alpha); @@ -672,7 +728,8 @@ indices.push(indexStart); - for (i = 0; i < indexCount; i++) { + for (i = 0; i < indexCount; i++) + { indices.push(indexStart++); } @@ -687,11 +744,13 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildComplexPoly = function (graphicsData, webGLData) { +WebGLGraphics.buildComplexPoly = function (graphicsData, webGLData) +{ //TODO - no need to copy this as it gets turned into a FLoat32Array anyways.. var points = graphicsData.points.slice(); - if (points.length < 6) { + if (points.length < 6) + { return; } @@ -711,7 +770,8 @@ var x,y; // get size.. - for (var i = 0; i < points.length; i+=2) { + for (var i = 0; i < points.length; i+=2) + { x = points[i]; y = points[i+1]; @@ -732,7 +792,8 @@ //TODO - this aint needed! var length = points.length / 2; - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { indices.push( i ); } @@ -746,10 +807,12 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildPoly = function (graphicsData, webGLData) { +WebGLGraphics.buildPoly = function (graphicsData, webGLData) +{ var points = graphicsData.points; - if (points.length < 6) { + if (points.length < 6) + { return; } // get first and last point.. figure out the middle! @@ -767,7 +830,8 @@ var triangles = utils.PolyK.Triangulate(points); - if (!triangles) { + if (!triangles) + { return false; } @@ -775,7 +839,8 @@ var i = 0; - for (i = 0; i < triangles.length; i+=3) { + for (i = 0; i < triangles.length; i+=3) + { indices.push(triangles[i] + vertPos); indices.push(triangles[i] + vertPos); indices.push(triangles[i+1] + vertPos); @@ -783,7 +848,8 @@ indices.push(triangles[i+2] + vertPos); } - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { verts.push(points[i * 2], points[i * 2 + 1], r, g, b, alpha); } diff --git a/src/core/renderers/webgl/utils/WebGLGraphicsData.js b/src/core/renderers/webgl/utils/WebGLGraphicsData.js index c56d05e..c739ba7 100644 --- a/src/core/renderers/webgl/utils/WebGLGraphicsData.js +++ b/src/core/renderers/webgl/utils/WebGLGraphicsData.js @@ -2,7 +2,8 @@ * @class * @private */ -function WebGLGraphicsData(gl) { +function WebGLGraphicsData(gl) +{ this.gl = gl; //TODO does this need to be split before uploding?? @@ -22,7 +23,8 @@ /** * */ -WebGLGraphicsData.prototype.reset = function () { +WebGLGraphicsData.prototype.reset = function () +{ this.points.length = 0; this.indices.length = 0; }; @@ -30,7 +32,8 @@ /** * */ -WebGLGraphicsData.prototype.upload = function () { +WebGLGraphicsData.prototype.upload = function () +{ var gl = this.gl; // this.lastIndex = graphics.graphicsData.length; diff --git a/src/core/renderers/webgl/utils/WebGLSpriteBatch.js b/src/core/renderers/webgl/utils/WebGLSpriteBatch.js index 96eaa52..55befbb 100644 --- a/src/core/renderers/webgl/utils/WebGLSpriteBatch.js +++ b/src/core/renderers/webgl/utils/WebGLSpriteBatch.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this sprite batch works for. */ -function WebGLSpriteBatch(renderer) { +function WebGLSpriteBatch(renderer) +{ /** * * @@ -88,7 +89,8 @@ */ this.lastIndexCount = 0; - for (var i=0, j=0; i < numIndices; i += 6, j += 4) { + 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; @@ -162,7 +164,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.setupContext(); }); } @@ -173,7 +176,8 @@ /** * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLSpriteBatch.prototype.setupContext = function () { +WebGLSpriteBatch.prototype.setupContext = function () +{ var gl = this.renderer.gl; // setup default shader @@ -198,7 +202,8 @@ /** * */ -WebGLSpriteBatch.prototype.begin = function () { +WebGLSpriteBatch.prototype.begin = function () +{ // this.shader = this.renderer.shaderManager.defaultShader; this.start(); @@ -206,19 +211,22 @@ /** */ -WebGLSpriteBatch.prototype.end = function () { +WebGLSpriteBatch.prototype.end = function () +{ this.flush(); }; /** * @param sprite {Sprite} the sprite to render when using this spritebatch */ -WebGLSpriteBatch.prototype.render = function (sprite) { +WebGLSpriteBatch.prototype.render = function (sprite) +{ var texture = sprite.texture; //TODO set blend modes.. // check texture.. - if (this.currentBatchSize >= this.size) { + if (this.currentBatchSize >= this.size) + { this.flush(); this.currentBaseTexture = texture.baseTexture; } @@ -227,7 +235,8 @@ var uvs = texture._uvs; // if the uvs have not updated then no point rendering just yet! - if (!uvs) { + if (!uvs) + { return; } @@ -237,7 +246,8 @@ var w0, w1, h0, h1; - if (texture.trim) { + 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; @@ -248,7 +258,8 @@ h0 = h1 + texture.crop.height; } - else { + else + { w0 = (texture.frame.width ) * (1-aX); w1 = (texture.frame.width ) * -aX; @@ -272,7 +283,8 @@ var colors = this.colors; var positions = this.positions; - if (this.renderer.roundPixels) { + if (this.renderer.roundPixels) + { // xy positions[index] = a * w1 + c * h1 + tx | 0; positions[index+1] = d * h1 + b * w1 + ty | 0; @@ -289,7 +301,8 @@ positions[index+15] = a * w1 + c * h0 + tx | 0; positions[index+16] = d * h0 + b * w1 + ty | 0; } - else { + else + { // xy positions[index] = a * w1 + c * h1 + tx; positions[index+1] = d * h1 + b * w1 + ty; @@ -338,11 +351,13 @@ * * @param sprite {TilingSprite} the tilingSprite to render */ -WebGLSpriteBatch.prototype.renderTilingSprite = function (tilingSprite) { +WebGLSpriteBatch.prototype.renderTilingSprite = function (tilingSprite) +{ var texture = tilingSprite.tilingTexture; // check texture.. - if (this.currentBatchSize >= this.size) { + if (this.currentBatchSize >= this.size) + { //return; this.flush(); this.currentBaseTexture = texture.baseTexture; @@ -351,7 +366,8 @@ // set the textures uvs temporarily // TODO create a separate texture so that we can tile part of a texture - if (!tilingSprite._uvs) { + if (!tilingSprite._uvs) + { tilingSprite._uvs = new TextureUvs(); } @@ -454,16 +470,19 @@ * Renders the content and empties the current batch. * */ -WebGLSpriteBatch.prototype.flush = function () { +WebGLSpriteBatch.prototype.flush = function () +{ // If the batch is length 0 then return as there is nothing to draw - if (this.currentBatchSize === 0) { + if (this.currentBatchSize === 0) + { return; } var gl = this.renderer.gl; var shader; - if (this.dirty) { + if (this.dirty) + { this.dirty = false; // bind the main texture gl.activeTexture(gl.TEXTURE0); @@ -482,10 +501,12 @@ } // upload the verts to the buffer - if (this.currentBatchSize > ( this.size * 0.5 ) ) { + if (this.currentBatchSize > ( this.size * 0.5 ) ) + { gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); } - else { + else + { var view = this.positions.subarray(0, this.currentBatchSize * this.vertByteSize); gl.bufferSubData(gl.ARRAY_BUFFER, 0, view); } @@ -502,7 +523,8 @@ var shaderSwap = false; var sprite; - for (var i = 0, j = this.currentBatchSize; i < j; i++) { + for (var i = 0, j = this.currentBatchSize; i < j; i++) + { sprite = this.sprites[i]; @@ -513,24 +535,28 @@ blendSwap = currentBlendMode !== nextBlendMode; shaderSwap = currentShader !== nextShader; // should I use uuidS??? - if (currentBaseTexture !== nextTexture || blendSwap || shaderSwap) { + if (currentBaseTexture !== nextTexture || blendSwap || shaderSwap) + { this.renderBatch(currentBaseTexture, batchSize, start); start = i; batchSize = 0; currentBaseTexture = nextTexture; - if (blendSwap) { + if (blendSwap) + { currentBlendMode = nextBlendMode; this.renderer.blendModeManager.setBlendMode( currentBlendMode ); } - if (shaderSwap) { + if (shaderSwap) + { currentShader = nextShader; shader = currentShader.shaders ? currentShader.shaders[gl.id] : currentShader; - if (!shader) { + if (!shader) + { shader = new Shader(gl, null, currentShader.fragmentSrc, currentShader.uniforms); currentShader.shaders[gl.id] = shader; } @@ -538,7 +564,8 @@ // set shader function??? this.renderer.shaderManager.setShader(shader); - if (shader.dirty) { + if (shader.dirty) + { shader.syncUniforms(); } @@ -569,17 +596,21 @@ * @param size {number} * @param startIndex {number} */ -WebGLSpriteBatch.prototype.renderBatch = function (texture, size, startIndex) { - if (size === 0) { +WebGLSpriteBatch.prototype.renderBatch = function (texture, size, startIndex) +{ + if (size === 0) + { return; } var gl = this.renderer.gl; - if (!texture._glTextures[gl.id]) { + if (!texture._glTextures[gl.id]) + { this.renderer.updateTexture(texture); } - else { + else + { // bind the current texture gl.bindTexture(gl.TEXTURE_2D, texture._glTextures[gl.id]); } @@ -594,7 +625,8 @@ /** * */ -WebGLSpriteBatch.prototype.stop = function () { +WebGLSpriteBatch.prototype.stop = function () +{ this.flush(); this.dirty = true; }; @@ -602,7 +634,8 @@ /** * */ -WebGLSpriteBatch.prototype.start = function () { +WebGLSpriteBatch.prototype.start = function () +{ this.dirty = true; }; @@ -610,7 +643,8 @@ * Destroys the SpriteBatch. * */ -WebGLSpriteBatch.prototype.destroy = function () { +WebGLSpriteBatch.prototype.destroy = function () +{ this.renderer.gl.deleteBuffer(this.vertexBuffer); this.renderer.gl.deleteBuffer(this.indexBuffer); diff --git a/src/core/textures/BaseTexture.js b/src/core/textures/BaseTexture.js index 2bf77d4..513d358 100644 --- a/src/core/textures/BaseTexture.js +++ b/src/core/textures/BaseTexture.js @@ -10,7 +10,8 @@ * @param source {Image|Canvas} the source object of the texture. * @param [scaleMode=scaleModes.DEFAULT] {number} See {@link scaleModes} for possible values */ -function BaseTexture(source, scaleMode) { +function BaseTexture(source, scaleMode) +{ this.uuid = utils.uuid(); /** @@ -123,7 +124,8 @@ this._needsUpdate = false; // if no source passed don't try to load - if (source) { + if (source) + { this.loadSource(source); } @@ -149,13 +151,16 @@ Object.defineProperties(BaseTexture.prototype, { needsUpdate: { - get: function () { + get: function () + { return this._needsUpdate; }, - set: function (val) { + set: function (val) + { this._needsUpdate = val; - if (val) { + if (val) + { this.emit('update', this); } } @@ -171,9 +176,11 @@ * * The logic state after calling `loadSource` directly or indirectly (eg. `fromImage`, `new BaseTexture`) is: * - * if (texture.hasLoaded) { + * if (texture.hasLoaded) + { * // texture ready for use - * } else if (texture.isLoading) { + * } else if (texture.isLoading) + { * // listen to 'loaded' and/or 'error' events on texture * } else { * // not loading, not going to load UNLESS the source is reloaded @@ -183,12 +190,14 @@ * @protected * @param source {Image|Canvas} the source object of the texture. */ -BaseTexture.prototype.loadSource = function (source) { +BaseTexture.prototype.loadSource = function (source) +{ var wasLoading = this.isLoading; this.hasLoaded = false; this.isLoading = false; - if (wasLoading && this.source) { + if (wasLoading && this.source) + { this.source.onload = null; this.source.onerror = null; } @@ -196,20 +205,24 @@ this.source = source; // Apply source if loaded. Otherwise setup appropriate loading monitors. - if ((this.source.complete || this.source.getContext) && this.source.width && this.source.height) { + if ((this.source.complete || this.source.getContext) && this.source.width && this.source.height) + { this._sourceLoaded(); } - else if(!source.getContext) { + else if(!source.getContext) + { // Image fail / not ready this.isLoading = true; var scope = this; - source.onload = function () { + source.onload = function () + { source.onload = null; source.onerror = null; - if(!scope.isLoading) { + if(!scope.isLoading) + { return; } @@ -219,11 +232,13 @@ scope.emit('loaded', scope); }; - source.onerror = function () { + source.onerror = function () + { source.onload = null; source.onerror = null; - if(!scope.isLoading) { + if(!scope.isLoading) + { return; } @@ -234,24 +249,29 @@ // Per http://www.w3.org/TR/html5/embedded-content-0.html#the-img-element // "The value of `complete` can thus change while a script is executing." // So complete needs to be re-checked after the callbacks have been added.. - if (source.complete) { + if (source.complete) + { this.isLoading = false; // ..and if we're complete now, no need for callbacks source.onload = null; source.onerror = null; - if (source.width && source.height) { + if (source.width && source.height) + { this._sourceLoaded(); // If any previous subscribers possible - if (wasLoading) { + if (wasLoading) + { this.emit('loaded', this); } } - else { + else + { // If any previous subscribers possible - if (wasLoading) { + if (wasLoading) + { this.emit('error', this); } } @@ -265,7 +285,8 @@ * * @private */ -BaseTexture.prototype._sourceLoaded = function () { +BaseTexture.prototype._sourceLoaded = function () +{ this.hasLoaded = true; this.width = this.source.naturalWidth || this.source.width; @@ -278,16 +299,20 @@ * Destroys this base texture * */ -BaseTexture.prototype.destroy = function () { - if (this.imageUrl) { +BaseTexture.prototype.destroy = function () +{ + if (this.imageUrl) + { delete utils.BaseTextureCache[this.imageUrl]; delete utils.TextureCache[this.imageUrl]; this.imageUrl = null; - if (!navigator.isCocoonJS) { + if (!navigator.isCocoonJS) + { this.source.src = ''; } } - else if (this.source && this.source._pixiId) { + else if (this.source && this.source._pixiId) + { delete utils.BaseTextureCache[this.source._pixiId]; } this.source = null; @@ -301,7 +326,8 @@ * memory again. * */ -BaseTexture.prototype.dispose = function () { +BaseTexture.prototype.dispose = function () +{ this.emit('dispose', this); }; @@ -311,7 +337,8 @@ * * @param newSrc {string} the path of the image */ -BaseTexture.prototype.updateSourceImage = function (newSrc) { +BaseTexture.prototype.updateSourceImage = function (newSrc) +{ this.source.src = newSrc; this.loadSource(this.source); }; @@ -326,18 +353,22 @@ * @param [scaleMode=scaleModes.DEFAULT] {number} See {@link scaleModes} for possible values * @return BaseTexture */ -BaseTexture.fromImage = function (imageUrl, crossorigin, scaleMode) { +BaseTexture.fromImage = function (imageUrl, crossorigin, scaleMode) +{ var baseTexture = utils.BaseTextureCache[imageUrl]; - if (crossorigin === undefined && imageUrl.indexOf('data:') !== 0) { + if (crossorigin === undefined && imageUrl.indexOf('data:') !== 0) + { crossorigin = true; } - if (!baseTexture) { + if (!baseTexture) + { // new Image() breaks tex loading in some versions of Chrome. // See https://code.google.com/p/chromium/issues/detail?id=238071 var image = new Image();//document.createElement('img'); - if (crossorigin) { + if (crossorigin) + { image.crossOrigin = ''; } @@ -347,7 +378,8 @@ utils.BaseTextureCache[imageUrl] = baseTexture; // if there is an @2x at the end of the url we are going to assume its a highres image - if ( imageUrl.indexOf(CONST.RETINA_PREFIX + '.') !== -1) { + if ( imageUrl.indexOf(CONST.RETINA_PREFIX + '.') !== -1) + { baseTexture.resolution = 2; } } @@ -363,14 +395,17 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return BaseTexture */ -BaseTexture.fromCanvas = function (canvas, scaleMode) { - if (!canvas._pixiId) { +BaseTexture.fromCanvas = function (canvas, scaleMode) +{ + if (!canvas._pixiId) + { canvas._pixiId = 'canvas_' + utils.uuid(); } var baseTexture = utils.BaseTextureCache[canvas._pixiId]; - if (!baseTexture) { + if (!baseTexture) + { baseTexture = new BaseTexture(canvas, scaleMode); utils.BaseTextureCache[canvas._pixiId] = baseTexture; } diff --git a/src/core/textures/RenderTexture.js b/src/core/textures/RenderTexture.js index 6dad20f..53ae796 100644 --- a/src/core/textures/RenderTexture.js +++ b/src/core/textures/RenderTexture.js @@ -46,8 +46,10 @@ * @param [scaleMode] {number} See {@link scaleModes} for possible values * @param [resolution=1] {number} The resolution of the texture being generated */ -function RenderTexture(renderer, width, height, scaleMode, resolution) { - if (!renderer) { +function RenderTexture(renderer, width, height, scaleMode, resolution) +{ + if (!renderer) + { throw new Error('Unable to create RenderTexture, you must pass a renderer into the constructor.'); } @@ -133,7 +135,8 @@ */ this.renderer = renderer; - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { var gl = this.renderer.gl; this.textureBuffer = new FilterTexture(gl, this.width * this.resolution, this.height * this.resolution, this.baseTexture.scaleMode); @@ -142,7 +145,8 @@ this.render = this.renderWebGL; this.projection = new math.Point(this.width*0.5, -this.height*0.5); } - else { + else + { this.render = this.renderCanvas; this.textureBuffer = new CanvasBuffer(this.width* this.resolution, this.height* this.resolution); this.baseTexture.source = this.textureBuffer.canvas; @@ -167,8 +171,10 @@ * @param height {number} The height to resize to. * @param updateBase {boolean} Should the baseTexture.width and height values be resized as well? */ -RenderTexture.prototype.resize = function (width, height, updateBase) { - if (width === this.width && height === this.height) { +RenderTexture.prototype.resize = function (width, height, updateBase) +{ + if (width === this.width && height === this.height) + { return; } @@ -177,17 +183,20 @@ this.width = this.frame.width = this.crop.width = width; this.height = this.frame.height = this.crop.height = height; - if (updateBase) { + if (updateBase) + { this.baseTexture.width = this.width; this.baseTexture.height = this.height; } - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { this.projection.x = this.width / 2; this.projection.y = -this.height / 2; } - if (!this.valid) { + if (!this.valid) + { return; } @@ -198,12 +207,15 @@ * Clears the RenderTexture. * */ -RenderTexture.prototype.clear = function () { - if (!this.valid) { +RenderTexture.prototype.clear = function () +{ + if (!this.valid) + { return; } - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { this.renderer.gl.bindFramebuffer(this.renderer.gl.FRAMEBUFFER, this.textureBuffer.frameBuffer); } @@ -220,19 +232,23 @@ * @param [restoreWorldTransform=true] {boolean} If true the displayObject's worldTransform/worldAlpha and all children * transformations will be restored. Not restoring this information will be a little faster. */ -RenderTexture.prototype.renderWebGL = function (displayObject, matrix, clear, restoreWorldTransform) { - if (!this.valid) { +RenderTexture.prototype.renderWebGL = function (displayObject, matrix, clear, restoreWorldTransform) +{ + if (!this.valid) + { return; } - if (typeof restoreWorldTransform === 'undefined') { + if (typeof restoreWorldTransform === 'undefined') + { restoreWorldTransform = true; } var tempAlpha, tempTransform; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { tempAlpha = displayObject.worldAlpha; tempTransform = displayObject.worldTransform.toArray(); } @@ -245,7 +261,8 @@ wt.identity(); wt.translate(0, this.projection.y * 2); - if (matrix) { + if (matrix) + { wt.append(matrix); } @@ -258,7 +275,8 @@ var children = displayObject.children; var i, j; - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } @@ -269,7 +287,8 @@ gl.bindFramebuffer(gl.FRAMEBUFFER, this.textureBuffer.frameBuffer ); - if (clear) { + if (clear) + { this.textureBuffer.clear(); } @@ -279,11 +298,13 @@ this.renderer.spriteBatch.dirty = true; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { displayObject.worldAlpha = tempAlpha; displayObject.worldTransform.fromArray(tempTransform); - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } } @@ -300,26 +321,31 @@ * @param [restoreWorldTransform=true] {boolean} If true the displayObject's worldTransform/worldAlpha and all children * transformations will be restored. Not restoring this information will be a little faster. */ -RenderTexture.prototype.renderCanvas = function (displayObject, matrix, clear, restoreWorldTransform) { - if (!this.valid) { +RenderTexture.prototype.renderCanvas = function (displayObject, matrix, clear, restoreWorldTransform) +{ + if (!this.valid) + { return; } - if (typeof restoreWorldTransform === 'undefined') { + if (typeof restoreWorldTransform === 'undefined') + { restoreWorldTransform = true; } var tempAlpha, tempTransform; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { tempAlpha = displayObject.worldAlpha; tempTransform = displayObject.worldTransform.toArray(); } var wt = displayObject.worldTransform; wt.identity(); - if (matrix) { + if (matrix) + { wt.append(matrix); } @@ -330,11 +356,13 @@ var children = displayObject.children; var i, j; - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } - if (clear) { + if (clear) + { this.textureBuffer.clear(); } @@ -348,11 +376,13 @@ this.renderer.resolution = realResolution; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { displayObject.worldAlpha = tempAlpha; displayObject.worldTransform.fromArray(tempTransform); - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } } @@ -363,7 +393,8 @@ * * @return {Image} */ -RenderTexture.prototype.getImage = function () { +RenderTexture.prototype.getImage = function () +{ var image = new Image(); image.src = this.getBase64(); return image; @@ -374,7 +405,8 @@ * * @return {string} A base64 encoded string of the texture. */ -RenderTexture.prototype.getBase64 = function () { +RenderTexture.prototype.getBase64 = function () +{ return this.getCanvas().toDataURL(); }; @@ -383,8 +415,10 @@ * * @return {HTMLCanvasElement} A Canvas element with the texture rendered on. */ -RenderTexture.prototype.getCanvas = function () { - if (this.renderer.type === CONST.WEBGL_RENDERER) { +RenderTexture.prototype.getCanvas = function () +{ + if (this.renderer.type === CONST.WEBGL_RENDERER) + { var gl = this.renderer.gl; var width = this.textureBuffer.width; var height = this.textureBuffer.height; @@ -403,7 +437,8 @@ return tempCanvas.canvas; } - else { + else + { return this.textureBuffer.canvas; } }; diff --git a/src/core/textures/Texture.js b/src/core/textures/Texture.js index 3c65909..e97f0aa 100644 --- a/src/core/textures/Texture.js +++ b/src/core/textures/Texture.js @@ -17,7 +17,8 @@ * @param [crop] {Rectangle} The area of original texture * @param [trim] {Rectangle} Trimmed texture rectangle */ -function Texture(baseTexture, frame, crop, trim) { +function Texture(baseTexture, frame, crop, trim) +{ /** * Does this Texture have any frame data assigned to it? * @@ -25,12 +26,14 @@ */ this.noFrame = false; - if (!frame) { + if (!frame) + { this.noFrame = true; frame = new math.Rectangle(0, 0, 1, 1); } - if (baseTexture instanceof Texture) { + if (baseTexture instanceof Texture) + { baseTexture = baseTexture.baseTexture; } @@ -100,13 +103,16 @@ */ this.crop = crop || new math.Rectangle(0, 0, 1, 1); - if (baseTexture.hasLoaded) { - if (this.noFrame) { + if (baseTexture.hasLoaded) + { + if (this.noFrame) + { frame = new math.Rectangle(0, 0, baseTexture.width, baseTexture.height); } this.frame = frame; } - else { + else + { baseTexture.addEventListener('loaded', this.onBaseTextureLoaded.bind(this)); } } @@ -118,19 +124,23 @@ Object.defineProperties(Texture.prototype, { needsUpdate: { - get: function () { + get: function () + { return this.baseTexture.needsUpdate; }, - set: function (val) { + set: function (val) + { this.baseTexture.needsUpdate = val; } }, frame: { - get: function () { + get: function () + { return this._frame; }, - set: function (frame) { + set: function (frame) + { this._frame = frame; this.noFrame = false; @@ -143,20 +153,23 @@ 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 (!this.trim && (frame.x + frame.width > this.baseTexture.width || frame.y + frame.height > this.baseTexture.height)) + { throw new Error('Texture Error: frame does not fit inside the base Texture dimensions ' + this); } this.valid = frame && frame.width && frame.height && this.baseTexture.source && this.baseTexture.hasLoaded; - if (this.trim) { + 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) { + if (this.valid) + { this._updateUvs(); } } @@ -168,11 +181,13 @@ * * @private */ -Texture.prototype.onBaseTextureLoaded = function () { +Texture.prototype.onBaseTextureLoaded = function () +{ var baseTexture = this.baseTexture; baseTexture.removeEventListener('loaded', this.onLoaded); - if (this.noFrame) { + if (this.noFrame) + { this.frame = new math.Rectangle(0, 0, baseTexture.width, baseTexture.height); } @@ -184,8 +199,10 @@ * * @param destroyBase {boolean} Whether to destroy the base texture as well */ -Texture.prototype.destroy = function (destroyBase) { - if (destroyBase) { +Texture.prototype.destroy = function (destroyBase) +{ + if (destroyBase) + { this.baseTexture.destroy(); } @@ -197,8 +214,10 @@ * * @private */ -Texture.prototype._updateUvs = function () { - if (!this._uvs) { +Texture.prototype._updateUvs = function () +{ + if (!this._uvs) + { this._uvs = new TextureUvs(); } @@ -229,10 +248,12 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return Texture */ -Texture.fromImage = function (imageUrl, crossorigin, scaleMode) { +Texture.fromImage = function (imageUrl, crossorigin, scaleMode) +{ var texture = utils.TextureCache[imageUrl]; - if (!texture) { + if (!texture) + { texture = new Texture(BaseTexture.fromImage(imageUrl, crossorigin, scaleMode)); utils.TextureCache[imageUrl] = texture; } @@ -248,9 +269,11 @@ * @param frameId {string} The frame id of the texture * @return Texture */ -Texture.fromFrame = function (frameId) { +Texture.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache '); } return texture; @@ -264,7 +287,8 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return {Texture} */ -Texture.fromCanvas = function (canvas, scaleMode) { +Texture.fromCanvas = function (canvas, scaleMode) +{ return new Texture(BaseTexture.fromCanvas(canvas, scaleMode)); }; @@ -276,7 +300,8 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return {Texture} A Texture */ -Texture.fromVideo = function (video, scaleMode) { +Texture.fromVideo = function (video, scaleMode) +{ return new Texture(VideoBaseTexture.baseTextureFromVideo(video, scaleMode)); }; @@ -287,7 +312,8 @@ * @param texture {Texture} The Texture to add to the cache. * @param id {string} The id that the texture will be stored against. */ -Texture.addTextureToCache = function (texture, id) { +Texture.addTextureToCache = function (texture, id) +{ utils.TextureCache[id] = texture; }; @@ -298,7 +324,8 @@ * @param id {string} The id of the texture to be removed * @return {Texture} The texture that was removed */ -Texture.removeTextureFromCache = function (id) { +Texture.removeTextureFromCache = function (id) +{ var texture = utils.TextureCache[id]; delete utils.TextureCache[id]; diff --git a/src/core/textures/TextureUvs.js b/src/core/textures/TextureUvs.js index b9bbb58..5424d52 100644 --- a/src/core/textures/TextureUvs.js +++ b/src/core/textures/TextureUvs.js @@ -1,4 +1,5 @@ -function TextureUvs() { +function TextureUvs() +{ this.x0 = 0; this.y0 = 0; diff --git a/src/core/textures/VideoBaseTexture.js b/src/core/textures/VideoBaseTexture.js index e3e0c5a..1a826a9 100644 --- a/src/core/textures/VideoBaseTexture.js +++ b/src/core/textures/VideoBaseTexture.js @@ -12,15 +12,18 @@ * @param source {HTMLVideoElement} * @param [scaleMode] {number} See {@link scaleModes} for possible values */ -function VideoBaseTexture(source, scaleMode) { - if (!source){ +function VideoBaseTexture(source, scaleMode) +{ + if (!source) + { throw new Error('No video source element specified.'); } // hook in here to check if video is already available. // BaseTexture looks for a source.complete boolean, plus width & height. - if ((source.readyState === source.HAVE_ENOUGH_DATA || source.readyState === source.HAVE_FUTURE_DATA) && source.width && source.height) { + if ((source.readyState === source.HAVE_ENOUGH_DATA || source.readyState === source.HAVE_FUTURE_DATA) && source.width && source.height) + { source.complete = true; } @@ -31,7 +34,8 @@ this._boundOnUpdate = this._onUpdate.bind(this); this._boundOnCanPlay = this._onCanPlay.bind(this); - if (!source.complete) { + if (!source.complete) + { source.addEventListener('canplay', this._boundOnCanPlay); source.addEventListener('canplaythrough', this._boundOnCanPlay); @@ -47,28 +51,35 @@ VideoBaseTexture.prototype.constructor = VideoBaseTexture; module.exports = VideoBaseTexture; -VideoBaseTexture.prototype._onUpdate = function () { - if (this.autoUpdate) { +VideoBaseTexture.prototype._onUpdate = function () +{ + if (this.autoUpdate) + { window.requestAnimationFrame(this._boundOnUpdate); this.needsUpdate = true; } }; -VideoBaseTexture.prototype._onPlayStart = function () { - if (!this.autoUpdate) { +VideoBaseTexture.prototype._onPlayStart = function () +{ + if (!this.autoUpdate) + { window.requestAnimationFrame(this._boundOnUpdate); this.autoUpdate = true; } }; -VideoBaseTexture.prototype._onPlayStop = function () { +VideoBaseTexture.prototype._onPlayStop = function () +{ this.autoUpdate = false; }; -VideoBaseTexture.prototype._onCanPlay = function () { +VideoBaseTexture.prototype._onCanPlay = function () +{ this.hasLoaded = true; - if (this.source) { + if (this.source) + { this.source.removeEventListener('canplay', this._boundOnCanPlay); this.source.removeEventListener('canplaythrough', this._boundOnCanPlay); @@ -78,15 +89,18 @@ this.source.play(); // prevent multiple loaded dispatches.. - if(!this.__loaded){ + if(!this.__loaded) + { this.__loaded = true; this.emit('loaded', this); } } }; -VideoBaseTexture.prototype.destroy = function () { - if (this.source && this.source._pixiId) { +VideoBaseTexture.prototype.destroy = function () +{ + if (this.source && this.source._pixiId) + { utils.BaseTextureCache[ this.source._pixiId ] = null; delete utils.BaseTextureCache[ this.source._pixiId ]; @@ -105,14 +119,17 @@ * @param scaleMode {number} See {@link scaleModes} for possible values * @return {VideoBaseTexture} */ -VideoBaseTexture.fromVideo = function (video, scaleMode) { - if (!video._pixiId) { +VideoBaseTexture.fromVideo = function (video, scaleMode) +{ + if (!video._pixiId) + { video._pixiId = 'video_' + utils.uuid(); } var baseTexture = utils.BaseTextureCache[video._pixiId]; - if (!baseTexture) { + if (!baseTexture) + { baseTexture = new VideoBaseTexture(video, scaleMode); utils.BaseTextureCache[ video._pixiId ] = baseTexture; } @@ -147,17 +164,21 @@ * @param scaleMode {number} See {@link scaleModes} for possible values * @return {VideoBaseTexture} */ -VideoBaseTexture.fromUrl = function (videoSrc, scaleMode) { +VideoBaseTexture.fromUrl = function (videoSrc, scaleMode) +{ var video = document.createElement('video'); // array of objects or strings - if (Array.isArray(videoSrc)) { - for (var i = 0; i < videoSrc.length; ++i) { + if (Array.isArray(videoSrc)) + { + for (var i = 0; i < videoSrc.length; ++i) + { video.appendChild(createSource(videoSrc.src || videoSrc, videoSrc.mime)); } } // single object or string - else { + else + { video.appendChild(createSource(videoSrc.src || videoSrc, videoSrc.mime)); } @@ -169,8 +190,10 @@ VideoBaseTexture.fromUrls = VideoBaseTexture.fromUrl; -function createSource(path, type) { - if (!type) { +function createSource(path, type) +{ + if (!type) + { type = 'video/' + path.substr(path.lastIndexOf('.') + 1); } diff --git a/src/core/utils/EventData.js b/src/core/utils/EventData.js index 5d55a22..8cdf701 100644 --- a/src/core/utils/EventData.js +++ b/src/core/utils/EventData.js @@ -7,7 +7,8 @@ * @param name {string} The string name of the event that was triggered * @param data {object} Arbitrary event data to pass along */ -function EventData(target, name, data) { +function EventData(target, name, data) +{ // for duck typing in the ".on()" function this.__isEventObject = true; @@ -71,7 +72,8 @@ * Stops the propagation of events up the scene graph (prevents bubbling). * */ -EventData.prototype.stopPropagation = function stopPropagation() { +EventData.prototype.stopPropagation = function stopPropagation() +{ this.stopped = true; }; @@ -79,6 +81,7 @@ * Stops the propagation of events to sibling listeners (no longer calls any listeners). * */ -EventData.prototype.stopImmediatePropagation = function stopImmediatePropagation() { +EventData.prototype.stopImmediatePropagation = function stopImmediatePropagation() +{ this.stoppedImmediate = true; }; diff --git a/src/core/utils/EventTarget.js b/src/core/utils/EventTarget.js index 7ae8820..671a151 100644 --- a/src/core/utils/EventTarget.js +++ b/src/core/utils/EventTarget.js @@ -13,14 +13,16 @@ * var em = new MyEmitter(); * em.emit('eventName', 'some data', 'some more data', {}, null, ...); */ -function eventTarget(obj) { +function eventTarget(obj) +{ /** * Return a list of assigned event listeners. * * @param eventName {string} The events that should be listed. * @return {Array} An array of listener functions */ - obj.listeners = function listeners(eventName) { + obj.listeners = function listeners(eventName) + { this._listeners = this._listeners || {}; return this._listeners[eventName] ? this._listeners[eventName].slice() : []; @@ -33,22 +35,26 @@ * @param eventName {string} The name of the event. * @return {boolean} Indication if we've emitted an event. */ - obj.emit = obj.dispatchEvent = function emit(eventName, data) { + obj.emit = obj.dispatchEvent = function emit(eventName, data) + { this._listeners = this._listeners || {}; // fast return when there are no listeners - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return; } //backwards compat with old method ".emit({ type: 'something' })" - if (typeof eventName === 'object') { + if (typeof eventName === 'object') + { data = eventName; eventName = eventName.type; } //ensure we are using a real pixi event - if (!data || data.__isEventObject !== true) { + if (!data || data.__isEventObject !== true) + { data = new EventData(this, eventName, data); } @@ -58,23 +64,27 @@ fn = listeners[0], i; - for (i = 0; i < length; fn = listeners[++i]) { + for (i = 0; i < length; fn = listeners[++i]) + { //call the event listener fn.call(this, data); //if "stopImmediatePropagation" is called, stop calling sibling events - if (data.stoppedImmediate) { + if (data.stoppedImmediate) + { return this; } } //if "stopPropagation" is called then don't bubble the event - if (data.stopped) { + if (data.stopped) + { return this; } //bubble this event up the scene graph - if (this.parent && this.parent.emit) { + if (this.parent && this.parent.emit) + { this.parent.emit.call(this.parent, eventName, data); } @@ -88,7 +98,8 @@ * @param eventName {string} Name of the event. * @param callback {Functon} fn Callback function. */ - obj.on = obj.addEventListener = function on(eventName, fn) { + obj.on = obj.addEventListener = function on(eventName, fn) + { this._listeners = this._listeners || {}; (this._listeners[eventName] = this._listeners[eventName] || []) @@ -103,11 +114,13 @@ * @param eventName {string} Name of the event. * @param callback {Function} Callback function. */ - obj.once = function once(eventName, fn) { + obj.once = function once(eventName, fn) + { this._listeners = this._listeners || {}; var self = this; - function onceHandlerWrapper() { + function onceHandlerWrapper() + { fn.apply(self.off(eventName, onceHandlerWrapper), arguments); } onceHandlerWrapper._originalHandler = fn; @@ -122,23 +135,28 @@ * @param eventName {string} The event we want to remove. * @param callback {Function} The listener that we need to find. */ - obj.off = obj.removeEventListener = function off(eventName, fn) { + obj.off = obj.removeEventListener = function off(eventName, fn) + { this._listeners = this._listeners || {}; - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return this; } var list = this._listeners[eventName], i = fn ? list.length : 0; - while(i-- > 0) { - if (list[i] === fn || list[i]._originalHandler === fn) { + while(i-- > 0) + { + if (list[i] === fn || list[i]._originalHandler === fn) + { list.splice(i, 1); } } - if (list.length === 0) { + if (list.length === 0) + { delete this._listeners[eventName]; } @@ -150,10 +168,12 @@ * * @param eventName {string} The event you want to remove all listeners for. */ - obj.removeAllListeners = function removeAllListeners(eventName) { + obj.removeAllListeners = function removeAllListeners(eventName) + { this._listeners = this._listeners || {}; - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return this; } @@ -169,7 +189,8 @@ * * @param object {object} The obj to mix into */ - mixin: function mixin(obj) { + mixin: function mixin(obj) + { eventTarget(obj); } }; diff --git a/src/core/utils/PolyK.js b/src/core/utils/PolyK.js index 7325141..5e20c2b 100644 --- a/src/core/utils/PolyK.js +++ b/src/core/utils/PolyK.js @@ -47,7 +47,8 @@ * Triangulates shapes for webGL graphic fills. * */ -PolyK.Triangulate = function (p) { +PolyK.Triangulate = function (p) +{ var sign = true; var n = p.length >> 1; @@ -59,7 +60,8 @@ i = 0; var al = n; - while(al > 3) { + while(al > 3) + { var i0 = avl[(i+0)%al]; var i1 = avl[(i+1)%al]; var i2 = avl[(i+2)%al]; @@ -69,29 +71,35 @@ var cx = p[2*i2], cy = p[2*i2+1]; var earFound = false; - if (PolyK._convex(ax, ay, bx, by, cx, cy, sign)) { + if (PolyK._convex(ax, ay, bx, by, cx, cy, sign)) + { earFound = true; - for (var j = 0; j < al; j++) { + for (var j = 0; j < al; j++) + { var vi = avl[j]; if (vi === i0 || vi === i1 || vi === i2) continue; - if (PolyK._PointInTriangle(p[2*vi], p[2*vi+1], ax, ay, bx, by, cx, cy)) { + if (PolyK._PointInTriangle(p[2*vi], p[2*vi+1], ax, ay, bx, by, cx, cy)) + { earFound = false; break; } } } - if (earFound) { + if (earFound) + { tgs.push(i0, i1, i2); avl.splice((i+1)%al, 1); al--; i = 0; } - else if (i++ > 3*al) { + else if (i++ > 3*al) + { // need to flip flip reverse it! // reset! - if (sign) { + if (sign) + { tgs = []; avl = []; for (i = 0; i < n; i++) avl.push(i); @@ -101,7 +109,8 @@ sign = false; } - else { + else + { // window.console.log("PIXI Warning: shape too complex to fill"); return null; } @@ -126,7 +135,8 @@ * @private * @return {boolean} */ -PolyK._PointInTriangle = function (px, py, ax, ay, bx, by, cx, cy) { +PolyK._PointInTriangle = function (px, py, ax, ay, bx, by, cx, cy) +{ var v0x = cx-ax; var v0y = cy-ay; var v1x = bx-ax; @@ -154,6 +164,7 @@ * @private * @return {boolean} */ -PolyK._convex = function (ax, ay, bx, by, cx, cy, sign) { +PolyK._convex = function (ax, ay, bx, by, cx, cy, sign) +{ return ((ay-by)*(cx-bx) + (bx-ax)*(cy-by) >= 0) === sign; }; diff --git a/src/core/utils/index.js b/src/core/utils/index.js index ade9831..bfae7ae 100644 --- a/src/core/utils/index.js +++ b/src/core/utils/index.js @@ -16,7 +16,8 @@ * * @return {number} The next uuid to use. */ - uuid: function () { + uuid: function () + { return ++utils._uid; }, @@ -26,7 +27,8 @@ * @param hex {number} * @return {number[]} An array representing the [R, G, B] of the color. */ - hex2rgb: function (hex, out) { + hex2rgb: function (hex, out) + { out = out || []; out[0] = (hex >> 16 & 0xFF) / 255; @@ -42,7 +44,8 @@ * @param hex {number} * @return {string} The string color. */ - hex2string: function (hex) { + hex2string: function (hex) + { hex = hex.toString(16); hex = '000000'.substr(0, 6 - hex.length) + hex; @@ -55,7 +58,8 @@ * @param rgb {number[]} * @return {number} The color number */ - rgb2hex: function (rgb) { + rgb2hex: function (rgb) + { return ((rgb[0]*255 << 16) + (rgb[1]*255 << 8) + rgb[2]*255); }, @@ -64,8 +68,10 @@ * * @return {boolean} whether they are supported */ - canUseNewCanvasBlendModes: function () { - if (typeof document === 'undefined') { + canUseNewCanvasBlendModes: function () + { + if (typeof document === 'undefined') + { return false; } @@ -93,15 +99,19 @@ * @param number {number} * @return {number} the closest number that is a power of two */ - getNextPowerOfTwo: function (number) { + getNextPowerOfTwo: function (number) + { // see: http://en.wikipedia.org/wiki/Power_of_two#Fast_algorithm_to_check_if_a_positive_number_is_a_power_of_two - if (number > 0 && (number & (number - 1)) === 0) { + if (number > 0 && (number & (number - 1)) === 0) + { return number; } - else { + else + { var result = 1; - while (result < number) { + while (result < number) + { result <<= 1; } @@ -116,7 +126,8 @@ * @param height {number} * @return {boolean} */ - isPowerOfTwo: function (width, height) { + isPowerOfTwo: function (width, height) + { return (width > 0 && (width & (width - 1)) === 0 && height > 0 && (height & (height - 1)) === 0); }, @@ -130,12 +141,15 @@ * @constant * @static */ - sayHello: function (type) { - if (utils._saidHello) { + sayHello: function (type) + { + if (utils._saidHello) + { return; } - if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) { + if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) + { var args = [ '%c %c %c Pixi.js ' + CONST.VERSION + ' - ' + type + ' %c ' + ' %c ' + ' http://www.pixijs.com/ %c %c ♥%c♥%c♥ ', 'background: #ff66a5', @@ -151,7 +165,8 @@ console.log.apply(console, args); //jshint ignore:line } - else if (window.console) { + else if (window.console) + { console.log('Pixi.js ' + CONST.VERSION + ' - ' + type + ' - http://www.pixijs.com/'); //jshint ignore:line } @@ -166,15 +181,19 @@ * @class * @namespace PIXI */ - AjaxRequest: function () { + AjaxRequest: function () + { var activexmodes = ['Msxml2.XMLHTTP.6.0', 'Msxml2.XMLHTTP.3.0', 'Microsoft.XMLHTTP']; //activeX versions to check for in IE - if (window.ActiveXObject) { //Test for support for ActiveXObject in IE first (as XMLHttpRequest in IE7 is broken) - for (var i=0; i= this.textures.length) { + else if (round >= this.textures.length) + { this.gotoAndStop(this.textures.length - 1); - if (this.onComplete) { + if (this.onComplete) + { this.onComplete(); } } @@ -167,10 +182,12 @@ * @static * @param frames {string[]} the array of frames ids the movieclip will use as its texture frames */ -MovieClip.fromFrames = function (frames) { +MovieClip.fromFrames = function (frames) +{ var textures = []; - for (var i = 0; i < frames.length; ++i) { + for (var i = 0; i < frames.length; ++i) + { textures.push(new core.Texture.fromFrame(frames[i])); } @@ -183,10 +200,12 @@ * @static * @param images {string[]} the array of image urls the movieclip will use as its texture frames */ -MovieClip.fromImages = function (images) { +MovieClip.fromImages = function (images) +{ var textures = []; - for (var i = 0; i < images.length; ++i) { + for (var i = 0; i < images.length; ++i) + { textures.push(new core.Texture.fromImage(images[i])); } diff --git a/src/extras/Rope.js b/src/extras/Rope.js index c157ec4..9c87bc0 100644 --- a/src/extras/Rope.js +++ b/src/extras/Rope.js @@ -9,7 +9,8 @@ * @param {Array} points - An array of {Point}. * */ -function Rope(texture, points) { +function Rope(texture, points) +{ Strip.call(this, texture); this.points = points; @@ -31,10 +32,12 @@ * Refreshes * */ -Rope.prototype.refresh = function () { +Rope.prototype.refresh = function () +{ var points = this.points; - if (points.length < 1) { + if (points.length < 1) + { return; } @@ -59,20 +62,23 @@ var total = points.length, point, index, amount; - for (var i = 1; i < total; i++) { + for (var i = 1; i < total; i++) + { point = points[i]; index = i * 4; // time to do some smart drawing! amount = i / (total-1); - if (i%2) { + if (i%2) + { uvs[index] = amount; uvs[index+1] = 0; uvs[index+2] = amount; uvs[index+3] = 1; } - else { + else + { uvs[index] = amount; uvs[index+1] = 0; @@ -95,10 +101,12 @@ * * @private */ -Rope.prototype.updateTransform = function () { +Rope.prototype.updateTransform = function () +{ var points = this.points; - if (points.length < 1) { + if (points.length < 1) + { return; } @@ -113,14 +121,17 @@ var total = points.length, point, index, ratio, perpLength, num; - for (var i = 0; i < total; i++) { + for (var i = 0; i < total; i++) + { point = points[i]; index = i * 4; - if (i < points.length-1) { + if (i < points.length-1) + { nextPoint = points[i+1]; } - else { + else + { nextPoint = point; } @@ -129,7 +140,8 @@ ratio = (1 - (i / (total-1))) * 10; - if (ratio > 1) { + if (ratio > 1) + { ratio = 1; } @@ -157,7 +169,8 @@ * * @param texture {Texture} the texture that will be used */ -Rope.prototype.setTexture = function (texture) { +Rope.prototype.setTexture = function (texture) +{ // stop current texture this.texture = texture; //this.updateFrame = true; diff --git a/src/extras/Strip.js b/src/extras/Strip.js index c5e378f..57691b5 100644 --- a/src/extras/Strip.js +++ b/src/extras/Strip.js @@ -10,7 +10,8 @@ * @param height {number} the height * */ -function Strip(texture) { +function Strip(texture) +{ core.DisplayObjectContainer.call(this); /** @@ -70,9 +71,11 @@ * * @param renderer {WebGLRenderer} */ -Strip.prototype.renderWebGL = function (renderer) { +Strip.prototype.renderWebGL = function (renderer) +{ // if the sprite is not visible or the alpha is 0 then no need to render this element - if (!this.visible || this.alpha <= 0) { + if (!this.visible || this.alpha <= 0) + { return; } @@ -81,7 +84,8 @@ renderer.spriteBatch.stop(); // init! init! - if (!this._vertexBuffer) { + if (!this._vertexBuffer) + { this._initWebGL(renderer); } @@ -96,7 +100,8 @@ //TODO check culling }; -Strip.prototype._initWebGL = function (renderer) { +Strip.prototype._initWebGL = function (renderer) +{ // build the strip! var gl = renderer.gl; @@ -118,7 +123,8 @@ gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this.indices, gl.STATIC_DRAW); }; -Strip.prototype._renderStrip = function (renderer) { +Strip.prototype._renderStrip = function (renderer) +{ var gl = renderer.gl; var projection = renderer.projection, offset = renderer.offset, @@ -137,7 +143,8 @@ gl.uniform2f(shader.offsetVector, -offset.x, -offset.y); gl.uniform1f(shader.alpha, this.worldAlpha); - if (!this.dirty) { + if (!this.dirty) + { gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexBuffer); gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); @@ -150,10 +157,12 @@ gl.activeTexture(gl.TEXTURE0); // check if a texture is dirty.. - if (this.texture.baseTexture._dirty[gl.id]) { + if (this.texture.baseTexture._dirty[gl.id]) + { renderer.updateTexture(this.texture.baseTexture); } - else { + else + { // bind the current texture gl.bindTexture(gl.TEXTURE_2D, this.texture.baseTexture._glTextures[gl.id]); } @@ -163,7 +172,8 @@ } - else { + else + { this.dirty = false; gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexBuffer); @@ -178,10 +188,12 @@ gl.activeTexture(gl.TEXTURE0); // check if a texture is dirty.. - if (this.texture.baseTexture._dirty[gl.id]) { + if (this.texture.baseTexture._dirty[gl.id]) + { renderer.updateTexture(this.texture.baseTexture); } - else { + else + { gl.bindTexture(gl.TEXTURE_2D, this.texture.baseTexture._glTextures[gl.id]); } @@ -203,27 +215,33 @@ * * @param renderer {CanvasRenderer} */ -Strip.prototype.renderCanvas = function (renderer) { +Strip.prototype.renderCanvas = function (renderer) +{ var context = renderer.context; var transform = this.worldTransform; - if (renderer.roundPixels) { + if (renderer.roundPixels) + { context.setTransform(transform.a, transform.b, transform.c, transform.d, transform.tx | 0, transform.ty | 0); } - else { + else + { context.setTransform(transform.a, transform.b, transform.c, transform.d, transform.tx, transform.ty); } - if (this.drawMode === Strip.DrawModes.TRIANGLE_STRIP) { + if (this.drawMode === Strip.DrawModes.TRIANGLE_STRIP) + { this._renderCanvasTriangleStrip(context); } - else { + else + { this._renderCanvasTriangles(context); } }; -Strip.prototype._renderCanvasTriangleStrip = function (context) { +Strip.prototype._renderCanvasTriangleStrip = function (context) +{ // draw triangles!! var vertices = this.vertices; var uvs = this.uvs; @@ -231,14 +249,16 @@ var length = vertices.length / 2; // this.count++; - for (var i = 0; i < length - 2; i++) { + for (var i = 0; i < length - 2; i++) + { // draw some triangles! var index = i * 2; this._renderCanvasDrawTriangle(context, vertices, uvs, index, (index + 2), (index + 4)); } }; -Strip.prototype._renderCanvasTriangles = function (context) { +Strip.prototype._renderCanvasTriangles = function (context) +{ // draw triangles!! var vertices = this.vertices; var uvs = this.uvs; @@ -247,14 +267,16 @@ var length = indices.length; // this.count++; - for (var i = 0; i < length; i += 3) { + for (var i = 0; i < length; i += 3) + { // draw some triangles! var index0 = indices[i] * 2, index1 = indices[i + 1] * 2, index2 = indices[i + 2] * 2; this._renderCanvasDrawTriangle(context, vertices, uvs, index0, index1, index2); } }; -Strip.prototype._renderCanvasDrawTriangle = function (context, vertices, uvs, index0, index1, index2) { +Strip.prototype._renderCanvasDrawTriangle = function (context, vertices, uvs, index0, index1, index2) +{ var textureSource = this.texture.baseTexture.source; var textureWidth = this.texture.width; var textureHeight = this.texture.height; @@ -265,7 +287,8 @@ var u0 = uvs[index0] * textureWidth, u1 = uvs[index1] * textureWidth, u2 = uvs[index2] * textureWidth; var v0 = uvs[index0 + 1] * textureHeight, v1 = uvs[index1 + 1] * textureHeight, v2 = uvs[index2 + 1] * textureHeight; - if (this.canvasPadding > 0) { + if (this.canvasPadding > 0) + { var paddingX = this.canvasPadding / this.worldTransform.a; var paddingY = this.canvasPadding / this.worldTransform.d; var centerX = (x0 + x1 + x2) / 3; @@ -332,7 +355,8 @@ * @param strip {Strip} The Strip to render * @private */ -Strip.prototype.renderStripFlat = function (strip) { +Strip.prototype.renderStripFlat = function (strip) +{ var context = this.context; var vertices = strip.vertices; @@ -340,7 +364,8 @@ // this.count++; context.beginPath(); - for (var i=1; i < length-2; i++) { + for (var i=1; i < length-2; i++) + { // draw some triangles! var index = i*2; @@ -358,7 +383,8 @@ }; /* -Strip.prototype.setTexture = function (texture) { +Strip.prototype.setTexture = function (texture) +{ //TODO SET THE TEXTURES //TODO VISIBILITY @@ -377,7 +403,8 @@ * @private */ -Strip.prototype.onTextureUpdate = function () { +Strip.prototype.onTextureUpdate = function () +{ this.updateFrame = true; }; @@ -387,7 +414,8 @@ * @param matrix {Matrix} the transformation matrix of the sprite * @return {Rectangle} the framing rectangle */ -Strip.prototype.getBounds = function (matrix) { +Strip.prototype.getBounds = function (matrix) +{ var worldTransform = matrix || this.worldTransform; var a = worldTransform.a; @@ -404,7 +432,8 @@ var minY = Infinity; var vertices = this.vertices; - for (var i = 0, n = vertices.length; i < n; i += 2) { + for (var i = 0, n = vertices.length; i < n; i += 2) + { var rawX = vertices[i], rawY = vertices[i + 1]; var x = (a * rawX) + (c * rawY) + tx; var y = (d * rawY) + (b * rawX) + ty; @@ -416,7 +445,8 @@ maxY = y > maxY ? y : maxY; } - if (minX === -Infinity || maxY === Infinity) { + if (minX === -Infinity || maxY === Infinity) + { return core.math.Rectangle.EMPTY; } diff --git a/src/extras/TilingSprite.js b/src/extras/TilingSprite.js index 3ac22df..31da393 100644 --- a/src/extras/TilingSprite.js +++ b/src/extras/TilingSprite.js @@ -10,7 +10,8 @@ * @param width {number} the width of the tiling sprite * @param height {number} the height of the tiling sprite */ -function TilingSprite(texture, width, height) { +function TilingSprite(texture, width, height) +{ core.Sprite.call( this, texture); /** @@ -86,10 +87,12 @@ * @memberof TilingSprite# */ width: { - get: function () { + get: function () + { return this._width; }, - set: function (value) { + set: function (value) + { this._width = value; } }, @@ -101,20 +104,25 @@ * @memberof TilingSprite# */ height: { - get: function () { + get: function () + { return this._height; }, - set: function (value) { + set: function (value) + { this._height = value; } }, texture: { - get: function () { + get: function () + { return this._texture; }, - set: function (value) { - if (this._texture === value) { + set: function (value) + { + if (this._texture === value) + { return; } @@ -130,51 +138,61 @@ * * @param renderer {WebGLRenderer} */ -TilingSprite.prototype.renderWebGL = function (renderer) { - if (!this.visible || this.alpha <= 0) { +TilingSprite.prototype.renderWebGL = function (renderer) +{ + if (!this.visible || this.alpha <= 0) + { return; } var i, j; - if (this._mask) { + if (this._mask) + { renderer.spriteBatch.stop(); renderer.maskManager.pushMask(this.mask, renderer); renderer.spriteBatch.start(); } - if (this._filters) { + if (this._filters) + { renderer.spriteBatch.flush(); renderer.filterManager.pushFilter(this._filterBlock); } - if (!this.tilingTexture || this.refreshTexture) { + if (!this.tilingTexture || this.refreshTexture) + { this.generateTilingTexture(true); - if (this.tilingTexture && this.tilingTexture.needsUpdate) { + if (this.tilingTexture && this.tilingTexture.needsUpdate) + { //TODO - tweaking renderer.updateTexture(this.tilingTexture.baseTexture); this.tilingTexture.needsUpdate = false; // this.tilingTexture._uvs = null; } } - else { + else + { renderer.spriteBatch.renderTilingSprite(this); } // simple render children! - for (i=0,j=this.children.length; i= 0 && index <= this.children.length) { - if (child.parent) { + if (index >= 0 && index <= this.children.length) + { + if (child.parent) + { child.parent.removeChild(child); } @@ -154,7 +173,8 @@ return child; } - else { + else + { throw new Error(child + 'addChildAt: The index '+ index +' supplied is out of bounds ' + this.children.length); } }; @@ -165,15 +185,18 @@ * @param child {DisplayObject} * @param child2 {DisplayObject} */ -DisplayObjectContainer.prototype.swapChildren = function (child, child2) { - if (child === child2) { +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) { + if (index1 < 0 || index2 < 0) + { throw new Error('swapChildren: Both the supplied DisplayObjects must be a child of the caller.'); } @@ -187,10 +210,12 @@ * @param child {DisplayObject} The DisplayObject instance to identify * @return {Number} The index position of the child display object to identify */ -DisplayObjectContainer.prototype.getChildIndex = function (child) { +DisplayObjectContainer.prototype.getChildIndex = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { throw new Error('The supplied DisplayObject must be a child of the caller'); } @@ -203,8 +228,10 @@ * @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 */ -DisplayObjectContainer.prototype.setChildIndex = function (child, index) { - if (index < 0 || index >= this.children.length) { +DisplayObjectContainer.prototype.setChildIndex = function (child, index) +{ + if (index < 0 || index >= this.children.length) + { throw new Error('The supplied index is out of bounds'); } @@ -220,8 +247,10 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child at the given index, if any. */ -DisplayObjectContainer.prototype.getChildAt = function (index) { - if (index < 0 || index >= this.children.length) { +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'); } @@ -234,10 +263,12 @@ * @param child {DisplayObject} The DisplayObject to remove * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChild = function (child) { +DisplayObjectContainer.prototype.removeChild = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { return; } @@ -250,7 +281,8 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChildAt = function (index) { +DisplayObjectContainer.prototype.removeChildAt = function (index) +{ var child = this.getChildAt(index); child.parent = null; @@ -265,24 +297,29 @@ * @param beginIndex {Number} The beginning position. Default value is 0. * @param endIndex {Number} The ending position. Default value is size of the container. */ -DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) { +DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) +{ var begin = beginIndex || 0; var end = typeof endIndex === 'number' ? endIndex : this.children.length; var range = end - begin; - if (range > 0 && range <= end) { + if (range > 0 && range <= end) + { var removed = this.children.splice(begin, range); - for (var i = 0; i < removed.length; ++i) { + for (var i = 0; i < removed.length; ++i) + { removed[i].parent = null; } return removed; } - else if (range === 0 && this.children.length === 0) { + else if (range === 0 && this.children.length === 0) + { return []; } - else { + else + { throw new RangeError('removeChildren: numeric values are outside the acceptable range.'); } }; @@ -291,7 +328,8 @@ * Generates and updates the cached sprite for this object. * */ -DisplayObjectContainer.prototype.updateCachedSprite = function () { +DisplayObjectContainer.prototype.updateCachedSprite = function () +{ this._generateCachedSprite(); }; @@ -304,7 +342,8 @@ * @param renderer {CanvasRenderer|WebGLRenderer} The renderer used to generate the texture. * @return {Texture} a texture of the graphics object */ -DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) { +DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) +{ var bounds = this.getLocalBounds(); var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0, renderer, scaleMode, resolution); @@ -322,18 +361,22 @@ * * @private */ -DisplayObjectContainer.prototype.updateTransform = function () { - if (!this.visible) { +DisplayObjectContainer.prototype.updateTransform = function () +{ + if (!this.visible) + { return; } this.displayObjectUpdateTransform(); - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { return; } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } }; @@ -346,8 +389,10 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getBounds = function () { - if (this.children.length === 0) { +DisplayObjectContainer.prototype.getBounds = function () +{ + if (this.children.length === 0) + { return math.Rectangle.EMPTY; } @@ -365,10 +410,12 @@ var childVisible = false; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -386,7 +433,8 @@ maxY = maxY > childMaxY ? maxY : childMaxY; } - if (!childVisible) { + if (!childVisible) + { return math.Rectangle.EMPTY; } @@ -407,12 +455,14 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getLocalBounds = function () { +DisplayObjectContainer.prototype.getLocalBounds = function () +{ var matrixCache = this.worldTransform; this.worldTransform = math.Matrix.IDENTITY; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } @@ -428,13 +478,16 @@ * * @param renderer {WebGLRenderer} The renderer */ -DisplayObjectContainer.prototype.renderWebGL = function (renderer) { +DisplayObjectContainer.prototype.renderWebGL = function (renderer) +{ // if the object is not visible or the alpha is 0 then no need to render this element - if (!this.visible || this.alpha <= 0) { + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } @@ -442,14 +495,17 @@ var i, j; // do a quick check to see if this element has a mask or a filter. - if (this._mask || this._filters) { + if (this._mask || this._filters) + { // push filter first as we need to ensure the stencil buffer is correct for any masking - if (this._filters) { + if (this._filters) + { renderer.spriteBatch.flush(); renderer.filterManager.pushFilter(this._filterBlock); } - if (this._mask) { + if (this._mask) + { renderer.spriteBatch.stop(); renderer.maskManager.pushMask(this.mask, renderer); renderer.spriteBatch.start(); @@ -459,36 +515,42 @@ this._renderWebGL(renderer); // now loop through the children and make sure they get rendered - for (i = 0, j = this.children.length; i < j; i++) { + for (i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderWebGL(renderer); } // time to stop the sprite batch as either a mask element or a filter draw will happen next renderer.spriteBatch.stop(); - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(this._mask, renderer); } - if (this._filters) { + if (this._filters) + { renderer.filterManager.popFilter(); } renderer.spriteBatch.start(); } - else { + else + { this._renderWebGL(renderer); // simple render children! - for (i = 0, j = this.children.length; i < j; ++i) { + for (i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderWebGL(renderer); } } }; -DisplayObjectContainer.prototype._renderWebGL = function (renderer) { +DisplayObjectContainer.prototype._renderWebGL = function (renderer) +{ // this is where content itself gets renderd.. @@ -499,25 +561,31 @@ * * @param renderer {CanvasRenderer} The renderer */ -DisplayObjectContainer.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0) { +DisplayObjectContainer.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -528,13 +596,16 @@ * @param renderer {WebGLRenderer|CanvasRenderer} The renderer * @private */ -DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) { +DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) +{ this._cachedSprite.worldAlpha = this.worldAlpha; - if (renderer.gl) { + if (renderer.gl) + { this._cachedSprite.renderWebGL(renderer); } - else { + else + { this._cachedSprite.renderCanvas(renderer); } }; @@ -544,10 +615,12 @@ * * @private */ -DisplayObjectContainer.prototype._generateCachedSprite = function () { +DisplayObjectContainer.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { // TODO - RenderTexture now *requires* a renderer instance, so this is like broken // because `renderer` isn't actually in scope here :P var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0); @@ -555,7 +628,8 @@ this._cachedSprite = new Sprite(renderTexture); this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.texture.resize(bounds.width | 0, bounds.height | 0); } @@ -580,8 +654,10 @@ * * @private */ -DisplayObjectContainer.prototype._destroyCachedSprite = function () { - if (!this._cachedSprite) { +DisplayObjectContainer.prototype._destroyCachedSprite = function () +{ + if (!this._cachedSprite) + { return; } diff --git a/src/core/display/Sprite.js b/src/core/display/Sprite.js index 707da24..5862aef 100644 --- a/src/core/display/Sprite.js +++ b/src/core/display/Sprite.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param texture {Texture} The texture for this sprite */ -function Sprite(texture) { +function Sprite(texture) +{ DisplayObjectContainer.call(this); /** @@ -85,12 +86,14 @@ this.texture = texture || Texture.EMPTY; } -Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) { +Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) +{ DisplayObjectContainer.prototype.destroy.call(this); this.anchor = null; - if (destroyTexture) { + if (destroyTexture) + { this._texture.destroy(destroyBaseTexture); } @@ -111,10 +114,12 @@ * @memberof Sprite# */ width: { - get: function () { + get: function () + { return this.scale.x * this.texture.frame.width; }, - set: function (value) { + set: function (value) + { this.scale.x = value / this.texture.frame.width; this._width = value; } @@ -127,10 +132,12 @@ * @memberof Sprite# */ height: { - get: function () { + get: function () + { return this.scale.y * this.texture.frame.height; }, - set: function (value) { + set: function (value) + { this.scale.y = value / this.texture.frame.height; this._height = value; } @@ -143,23 +150,29 @@ * @memberof Sprite# */ texture: { - get: function () { + get: function () + { return this._texture; }, - set: function (value) { - if (this._texture === value) { + set: function (value) + { + if (this._texture === value) + { return; } this._texture = value; this.cachedTint = 0xFFFFFF; - if (value) { + if (value) + { // wait for the texture to load - if (value.baseTexture.hasLoaded) { + if (value.baseTexture.hasLoaded) + { this._onTextureUpdate(); } - else { + else + { value.once('update', this._onTextureUpdate.bind(this)); } } @@ -172,18 +185,22 @@ * * @private */ -Sprite.prototype._onTextureUpdate = function () { +Sprite.prototype._onTextureUpdate = function () +{ // so if _width is 0 then width was not set.. - if (this._width) { + if (this._width) + { this.scale.x = this._width / this.texture.frame.width; } - if (this._height) { + if (this._height) + { this.scale.y = this._height / this.texture.frame.height; } }; -Sprite.prototype._renderWebGL = function (renderer) { +Sprite.prototype._renderWebGL = function (renderer) +{ // this is where content gets renderd.. // watch this space for a little render state manager.. @@ -197,7 +214,8 @@ * @param matrix {Matrix} the transformation matrix of the sprite * @return {Rectangle} the framing rectangle */ -Sprite.prototype.getBounds = function (matrix) { +Sprite.prototype.getBounds = function (matrix) +{ var width = this.texture.frame.width; var height = this.texture.frame.height; @@ -224,11 +242,13 @@ if(b === 0 && c === 0) { // scale may be negative! - if (a < 0) { + if (a < 0) + { a *= -1; } - if (d < 0) { + if (d < 0) + { d *= -1; } @@ -293,28 +313,34 @@ * * @param renderer {CanvasRenderer} The renderer */ -Sprite.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) { +Sprite.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) + { return; } - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; renderer.context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } // Ignore null sources - if (this.texture.valid) { + if (this.texture.valid) + { var resolution = this.texture.baseTexture.resolution / renderer.resolution; renderer.context.globalAlpha = this.worldAlpha; // If smoothingEnabled is supported and we need to change the smoothing property for this texture - if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) { + if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) + { renderer.scaleMode = this.texture.baseTexture.scaleMode; renderer.context[renderer.smoothProperty] = (renderer.scaleMode === CONST.scaleModes.LINEAR); } @@ -324,7 +350,8 @@ var dy = (this.texture.trim ? this.texture.trim.y : 0) - (this.anchor.y * this.texture.trim.height); // Allow for pixel rounding - if (renderer.roundPixels) { + if (renderer.roundPixels) + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -337,7 +364,8 @@ dx = dx | 0; dy = dy | 0; } - else { + else + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -348,8 +376,10 @@ ); } - if (this.tint !== 0xFFFFFF) { - if (this.cachedTint !== this.tint) { + if (this.tint !== 0xFFFFFF) + { + if (this.cachedTint !== this.tint) + { this.cachedTint = this.tint; // TODO clean up caching - how to clean up the caches? @@ -368,7 +398,8 @@ this.texture.crop.height / resolution ); } - else { + else + { renderer.context.drawImage( this.texture.baseTexture.source, this.texture.crop.x, @@ -383,11 +414,13 @@ } } - for (var i = 0, j = this.children.length; i < j; i++) { + for (var i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -402,10 +435,12 @@ * @param frameId {String} The frame Id of the texture in the cache * @return {Sprite} A new Sprite using a texture from the texture cache matching the frameId */ -Sprite.fromFrame = function (frameId) { +Sprite.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache' + this); } @@ -420,6 +455,7 @@ * @param imageId {String} The image url of the texture * @return {Sprite} A new Sprite using a texture from the texture cache matching the image id */ -Sprite.fromImage = function (imageId, crossorigin, scaleMode) { +Sprite.fromImage = function (imageId, crossorigin, scaleMode) +{ return new Sprite(Texture.fromImage(imageId, crossorigin, scaleMode)); }; diff --git a/src/core/display/SpriteBatch.js b/src/core/display/SpriteBatch.js index 3187777..c196fef 100644 --- a/src/core/display/SpriteBatch.js +++ b/src/core/display/SpriteBatch.js @@ -12,7 +12,8 @@ * ```js * var container = new SpriteBatch(); * - * for(var i = 0; i < 100; ++i) { + * for(var i = 0; i < 100; ++i) + * { * var sprite = new PIXI.Sprite.fromImage("myImage.png"); * container.addChild(sprite); * } @@ -25,7 +26,8 @@ */ //TODO RENAME to PARTICLE CONTAINER? -function SpriteBatch() { +function SpriteBatch() +{ DisplayObjectContainer.call(this); } @@ -38,7 +40,8 @@ * * @private */ -SpriteBatch.prototype.updateTransform = function () { +SpriteBatch.prototype.updateTransform = function () +{ // TODO don't need to! this.displayObjectUpdateTransform(); // PIXI.DisplayObjectContainer.prototype.updateTransform.call( this ); @@ -50,8 +53,10 @@ * @param renderer {WebGLRenderer} The webgl renderer * @private */ -SpriteBatch.prototype.renderWebGL = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderWebGL = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -71,8 +76,10 @@ * @param renderer {CanvasRenderer} The canvas renderer * @private */ -SpriteBatch.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -84,10 +91,12 @@ this.displayObjectUpdateTransform(); - for (var i = 0; i < this.children.length; ++i) { + for (var i = 0; i < this.children.length; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -95,9 +104,11 @@ context.globalAlpha = this.worldAlpha * child.alpha; - if (child.rotation % (Math.PI * 2) === 0) { + if (child.rotation % (Math.PI * 2) === 0) + { // this is the fastest way to optimise! - if rotation is 0 then we can avoid any kind of setTransform call - if (isRotated) { + if (isRotated) + { context.setTransform( transform.a, transform.b, @@ -122,8 +133,10 @@ frame.height * child.scale.y ); } - else { - if (!isRotated) { + else + { + if (!isRotated) + { isRotated = true; } @@ -131,7 +144,8 @@ var childTransform = child.worldTransform; - if (renderer.roundPixels) { + if (renderer.roundPixels) + { context.setTransform( childTransform.a, childTransform.b, @@ -141,7 +155,8 @@ childTransform.ty | 0 ); } - else { + else + { context.setTransform( childTransform.a, childTransform.b, diff --git a/src/core/index.js b/src/core/index.js index 3954b6f..eb4a82b 100644 --- a/src/core/index.js +++ b/src/core/index.js @@ -58,11 +58,13 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRenderer: function (width, height, options, noWebGL) { + autoDetectRenderer: function (width, height, options, noWebGL) + { width = width || 800; height = height || 600; - if (!noWebGL && require('webgl-enabled')()) { + if (!noWebGL && require('webgl-enabled')()) + { return new core.WebGLRenderer(width, height, options); } @@ -87,7 +89,8 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRecommendedRenderer: function (width, height, options) { + autoDetectRecommendedRenderer: function (width, height, options) + { var isAndroid = /Android/i.test(navigator.userAgent); return core.autoDetectRenderer(width, height, options, isAndroid); diff --git a/src/core/math/Matrix.js b/src/core/math/Matrix.js index c2f87e2..2ff4848 100644 --- a/src/core/math/Matrix.js +++ b/src/core/math/Matrix.js @@ -10,7 +10,8 @@ * @class * @namespace PIXI */ -function Matrix() { +function Matrix() +{ /** * @member {number} * @default 1 @@ -63,7 +64,8 @@ * * @param array {number[]} The array that the matrix will be populated from. */ -Matrix.prototype.fromArray = function (array) { +Matrix.prototype.fromArray = function (array) +{ this.a = array[0]; this.b = array[1]; this.c = array[3]; @@ -78,14 +80,17 @@ * @param transpose {boolean} Whether we need to transpose the matrix or not * @return {number[]} the newly created array which contains the matrix */ -Matrix.prototype.toArray = function (transpose) { - if (!this.array) { +Matrix.prototype.toArray = function (transpose) +{ + if (!this.array) + { this.array = new Float32Array(9); } var array = this.array; - if (transpose) { + if (transpose) + { array[0] = this.a; array[1] = this.b; array[2] = 0; @@ -96,7 +101,8 @@ array[7] = this.ty; array[8] = 1; } - else { + else + { array[0] = this.a; array[1] = this.c; array[2] = this.tx; @@ -119,7 +125,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, transformed through this matrix */ -Matrix.prototype.apply = function (pos, newPos) { +Matrix.prototype.apply = function (pos, newPos) +{ newPos = newPos || new Point(); newPos.x = this.a * pos.x + this.c * pos.y + this.tx; @@ -136,7 +143,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, inverse-transformed through this matrix */ -Matrix.prototype.applyInverse = function (pos, newPos) { +Matrix.prototype.applyInverse = function (pos, newPos) +{ newPos = newPos || new Point(); var id = 1 / (this.a * this.d + this.c * -this.b); @@ -154,7 +162,8 @@ * @param {number} y * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.translate = function (x, y) { +Matrix.prototype.translate = function (x, y) +{ this.tx += x; this.ty += y; @@ -168,7 +177,8 @@ * @param {number} y The amount to scale vertically * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.scale = function (x, y) { +Matrix.prototype.scale = function (x, y) +{ this.a *= x; this.d *= y; this.c *= x; @@ -186,7 +196,8 @@ * @param {number} angle - The angle in radians. * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.rotate = function (angle) { +Matrix.prototype.rotate = function (angle) +{ var cos = Math.cos( angle ); var sin = Math.sin( angle ); @@ -210,7 +221,8 @@ * @param {Matrix} matrix * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.append = function (matrix) { +Matrix.prototype.append = function (matrix) +{ var a1 = this.a; var b1 = this.b; var c1 = this.c; @@ -232,7 +244,8 @@ * * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.identity = function () { +Matrix.prototype.identity = function () +{ this.a = 1; this.b = 0; this.c = 0; diff --git a/src/core/math/Point.js b/src/core/math/Point.js index 7565b2d..632f346 100644 --- a/src/core/math/Point.js +++ b/src/core/math/Point.js @@ -7,7 +7,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -function Point(x, y) { +function Point(x, y) +{ /** * @member {number} * @default 0 @@ -29,7 +30,8 @@ * * @return {Point} a copy of the point */ -Point.prototype.clone = function () { +Point.prototype.clone = function () +{ return new Point(this.x, this.y); }; @@ -40,7 +42,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -Point.prototype.set = function (x, y) { +Point.prototype.set = function (x, y) +{ this.x = x || 0; this.y = y || ( (y !== 0) ? this.x : 0 ) ; }; diff --git a/src/core/math/shapes/Circle.js b/src/core/math/shapes/Circle.js index 69cfdc9..4d76efc 100644 --- a/src/core/math/shapes/Circle.js +++ b/src/core/math/shapes/Circle.js @@ -10,7 +10,8 @@ * @param y {number} The Y coordinate of the center of this circle * @param radius {number} The radius of the circle */ -function Circle(x, y, radius) { +function Circle(x, y, radius) +{ /** * @member {number} * @default 0 @@ -46,7 +47,8 @@ * @method clone * @return {Circle} a copy of the Circle */ -Circle.prototype.clone = function () { +Circle.prototype.clone = function () +{ return new Circle(this.x, this.y, this.radius); }; @@ -58,8 +60,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Circle */ -Circle.prototype.contains = function (x, y) { - if (this.radius <= 0) { +Circle.prototype.contains = function (x, y) +{ + if (this.radius <= 0) + { return false; } @@ -79,6 +83,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Circle.prototype.getBounds = function () { +Circle.prototype.getBounds = function () +{ return new Rectangle(this.x - this.radius, this.y - this.radius, this.radius * 2, this.radius * 2); }; diff --git a/src/core/math/shapes/Ellipse.js b/src/core/math/shapes/Ellipse.js index 4f2d066..fefd01a 100644 --- a/src/core/math/shapes/Ellipse.js +++ b/src/core/math/shapes/Ellipse.js @@ -11,7 +11,8 @@ * @param width {number} The half width of this ellipse * @param height {number} The half height of this ellipse */ -function Ellipse(x, y, width, height) { +function Ellipse(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -53,7 +54,8 @@ * @method clone * @return {Ellipse} a copy of the ellipse */ -Ellipse.prototype.clone = function () { +Ellipse.prototype.clone = function () +{ return new Ellipse(this.x, this.y, this.width, this.height); }; @@ -65,8 +67,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coords are within this ellipse */ -Ellipse.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Ellipse.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } @@ -86,6 +90,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Ellipse.prototype.getBounds = function () { +Ellipse.prototype.getBounds = function () +{ return new Rectangle(this.x - this.width, this.y - this.height, this.width, this.height); }; diff --git a/src/core/math/shapes/Polygon.js b/src/core/math/shapes/Polygon.js index ae89148..fea6d37 100644 --- a/src/core/math/shapes/Polygon.js +++ b/src/core/math/shapes/Polygon.js @@ -10,16 +10,20 @@ * arguments passed can be flat x,y values e.g. `new Polygon(x,y, x,y, x,y, ...)` where `x` and `y` are * Numbers. */ -function Polygon(points) { +function Polygon(points) +{ //if points isn't an array, use arguments as the array - if (!(points instanceof Array)) { + if (!(points instanceof Array)) + { points = Array.prototype.slice.call(arguments); } //if this is a flat array of numbers, convert it to points - if (points[0] instanceof Point) { + if (points[0] instanceof Point) + { var p = []; - for (var i = 0, il = points.length; i < il; i++) { + for (var i = 0, il = points.length; i < il; i++) + { p.push(points[i].x, points[i].y); } @@ -51,7 +55,8 @@ * * @return {Polygon} a copy of the polygon */ -Polygon.prototype.clone = function () { +Polygon.prototype.clone = function () +{ return new Polygon(this.points.slice()); }; @@ -62,19 +67,22 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this polygon */ -Polygon.prototype.contains = function (x, y) { +Polygon.prototype.contains = function (x, y) +{ var inside = false; // use some raycasting to test hits // https://github.com/substack/point-in-polygon/blob/master/index.js var length = this.points.length / 2; - for (var i = 0, j = length - 1; i < length; j = i++) { + for (var i = 0, j = length - 1; i < length; j = i++) + { var xi = this.points[i * 2], yi = this.points[i * 2 + 1], xj = this.points[j * 2], yj = this.points[j * 2 + 1], intersect = ((yi > y) !== (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi); - if (intersect) { + if (intersect) + { inside = !inside; } } diff --git a/src/core/math/shapes/Rectangle.js b/src/core/math/shapes/Rectangle.js index 16ac62a..4008b68 100644 --- a/src/core/math/shapes/Rectangle.js +++ b/src/core/math/shapes/Rectangle.js @@ -10,7 +10,8 @@ * @param width {number} The overall width of this rectangle * @param height {number} The overall height of this rectangle */ -function Rectangle(x, y, width, height) { +function Rectangle(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -60,7 +61,8 @@ * * @return {Rectangle} a copy of the rectangle */ -Rectangle.prototype.clone = function () { +Rectangle.prototype.clone = function () +{ return new Rectangle(this.x, this.y, this.width, this.height); }; @@ -71,13 +73,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rectangle */ -Rectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Rectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/math/shapes/RoundedRectangle.js b/src/core/math/shapes/RoundedRectangle.js index 27d286e..7bf6411 100644 --- a/src/core/math/shapes/RoundedRectangle.js +++ b/src/core/math/shapes/RoundedRectangle.js @@ -11,7 +11,8 @@ * @param height {number} The overall height of this rounded rectangle * @param radius {number} Controls the radius of the rounded corners */ -function RoundedRectangle(x, y, width, height, radius) { +function RoundedRectangle(x, y, width, height, radius) +{ /** * @member {number} * @default 0 @@ -58,7 +59,8 @@ * * @return {RoundedRectangle} a copy of the rounded rectangle */ -RoundedRectangle.prototype.clone = function () { +RoundedRectangle.prototype.clone = function () +{ return new RoundedRectangle(this.x, this.y, this.width, this.height, this.radius); }; @@ -69,13 +71,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rounded Rectangle */ -RoundedRectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +RoundedRectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/primitives/Graphics.js b/src/core/primitives/Graphics.js index 261c534..e902d2a 100644 --- a/src/core/primitives/Graphics.js +++ b/src/core/primitives/Graphics.js @@ -16,7 +16,8 @@ * @extends DisplayObjectContainer * @namespace PIXI */ -function Graphics() { +function Graphics() +{ DisplayObjectContainer.call(this); this.renderable = true; @@ -154,16 +155,20 @@ * @private */ cacheAsBitmap: { - get: function () { + get: function () + { return this._cacheAsBitmap; }, - set: function (value) { + set: function (value) + { this._cacheAsBitmap = value; - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._generateCachedSprite(); } - else { + else + { this.destroyCachedSprite(); this.dirty = true; } @@ -176,7 +181,8 @@ * * @return {Graphics} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ var clone = new Graphics(); clone.renderable = this.renderable; @@ -192,7 +198,8 @@ clone.cachedSpriteDirty = this.cachedSpriteDirty; // copy graphics data - for (var i = 0; i < this.graphicsData.length; ++i) { + for (var i = 0; i < this.graphicsData.length; ++i) + { clone.graphicsData.push(this.graphicsData.clone()); } @@ -211,17 +218,21 @@ * @param alpha {number} alpha of the line to draw, will update the objects stored style * @return {Graphics} */ -Graphics.prototype.lineStyle = function (lineWidth, color, alpha) { +Graphics.prototype.lineStyle = function (lineWidth, color, alpha) +{ this.lineWidth = lineWidth || 0; this.lineColor = color || 0; this.lineAlpha = (arguments.length < 3) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length) + { // halfway through a line? start a new one! this.drawShape( new math.Polygon( this.currentPath.shape.points.slice(-2) )); } - else { + else + { // otherwise its empty so lets just set the line properties this.currentPath.lineWidth = this.lineWidth; this.currentPath.lineColor = this.lineColor; @@ -239,7 +250,8 @@ * @param y {number} the Y coordinate to move to * @return {Graphics} */ -Graphics.prototype.moveTo = function (x, y) { +Graphics.prototype.moveTo = function (x, y) +{ this.drawShape(new math.Polygon([x,y])); return this; @@ -253,7 +265,8 @@ * @param y {number} the Y coordinate to draw to * @return {Graphics} */ -Graphics.prototype.lineTo = function (x, y) { +Graphics.prototype.lineTo = function (x, y) +{ this.currentPath.shape.points.push(x, y); this.dirty = true; @@ -270,13 +283,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -285,7 +302,8 @@ n = 20, points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { this.moveTo(0, 0); } @@ -293,7 +311,8 @@ var fromY = points[points.length-1]; var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; xa = fromX + ( (cpX - fromX) * j ); @@ -319,13 +338,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -342,7 +365,8 @@ var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; dt = (1 - j); @@ -373,13 +397,17 @@ * @param radius {number} The radius of the arc * @return {Graphics} */ -Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points.push(x1, y1); } } - else { + else + { this.moveTo(x1, y1); } @@ -392,12 +420,15 @@ b2 = x2 - x1, mm = Math.abs(a1 * b2 - b1 * a2); - if (mm < 1.0e-8 || radius === 0) { - if (points[points.length-2] !== x1 || points[points.length-1] !== y1) { + if (mm < 1.0e-8 || radius === 0) + { + if (points[points.length-2] !== x1 || points[points.length-1] !== y1) + { points.push(x1, y1); } } - else { + else + { var dd = a1 * a1 + b1 * b1, cc = a2 * a2 + b2 * b2, tt = a1 * a2 + b1 * b2, @@ -433,42 +464,51 @@ * @param anticlockwise {boolean} Optional. Specifies whether the drawing should be counterclockwise or clockwise. False is default, and indicates clockwise, while true indicates counter-clockwise. * @return {Graphics} */ -Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) { +Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) +{ var startX = cx + Math.cos(startAngle) * radius; var startY = cy + Math.sin(startAngle) * radius; var points; // TODO - This if-else makes no sense. It uses currentPath in the else where it doesn't exist... - if (this.currentPath) { + if (this.currentPath) + { points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { points.push(startX, startY); } - else if (points[points.length-2] !== startX || points[points.length-1] !== startY) { + else if (points[points.length-2] !== startX || points[points.length-1] !== startY) + { points.push(startX, startY); } } - else { + else + { this.moveTo(startX, startY); points = this.currentPath.shape.points; } - if (startAngle === endAngle) { + if (startAngle === endAngle) + { return this; } - if (!anticlockwise && endAngle <= startAngle) { + if (!anticlockwise && endAngle <= startAngle) + { endAngle += Math.PI * 2; } - else if (anticlockwise && startAngle <= endAngle) { + else if (anticlockwise && startAngle <= endAngle) + { startAngle += Math.PI * 2; } var sweep = anticlockwise ? (startAngle - endAngle) *-1 : (endAngle - startAngle); var segs = (Math.abs(sweep)/ (Math.PI * 2)) * 40; - if (sweep === 0) { + if (sweep === 0) + { return this; } @@ -482,7 +522,8 @@ var remainder = ( segMinus % 1 ) / segMinus; - for (var i = 0; i <= segMinus; ++i) { + for (var i = 0; i <= segMinus; ++i) + { var real = i + remainder * i; var angle = ((theta) + startAngle + (theta2 * real)); @@ -506,13 +547,16 @@ * @param alpha {number} the alpha of the fill * @return {Graphics} */ -Graphics.prototype.beginFill = function (color, alpha) { +Graphics.prototype.beginFill = function (color, alpha) +{ this.filling = true; this.fillColor = color || 0; this.fillAlpha = (alpha === undefined) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length <= 2) + { this.currentPath.fill = this.filling; this.currentPath.fillColor = this.fillColor; this.currentPath.fillAlpha = this.fillAlpha; @@ -526,7 +570,8 @@ * * @return {Graphics} */ -Graphics.prototype.endFill = function () { +Graphics.prototype.endFill = function () +{ this.filling = false; this.fillColor = null; this.fillAlpha = 1; @@ -542,7 +587,8 @@ * @param height {number} The height of the rectangle * @return {Graphics} */ -Graphics.prototype.drawRect = function ( x, y, width, height ) { +Graphics.prototype.drawRect = function ( x, y, width, height ) +{ this.drawShape(new math.Rectangle(x,y, width, height)); return this; @@ -556,7 +602,8 @@ * @param height {number} The height of the rectangle * @param radius {number} Radius of the rectangle corners */ -Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) { +Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) +{ this.drawShape(new math.RoundedRectangle(x, y, width, height, radius)); return this; @@ -570,7 +617,8 @@ * @param radius {number} The radius of the circle * @return {Graphics} */ -Graphics.prototype.drawCircle = function (x, y, radius) { +Graphics.prototype.drawCircle = function (x, y, radius) +{ this.drawShape(new math.Circle(x,y, radius)); return this; @@ -585,7 +633,8 @@ * @param height {number} The half height of the ellipse * @return {Graphics} */ -Graphics.prototype.drawEllipse = function (x, y, width, height) { +Graphics.prototype.drawEllipse = function (x, y, width, height) +{ this.drawShape(new math.Ellipse(x, y, width, height)); return this; @@ -597,8 +646,10 @@ * @param path {Array} The path data used to construct the polygon. * @return {Graphics} */ -Graphics.prototype.drawPolygon = function (path) { - if (!(path instanceof Array)) { +Graphics.prototype.drawPolygon = function (path) +{ + if (!(path instanceof Array)) + { path = Array.prototype.slice.call(arguments); } @@ -612,7 +663,8 @@ * * @return {Graphics} */ -Graphics.prototype.clear = function () { +Graphics.prototype.clear = function () +{ this.lineWidth = 0; this.filling = false; @@ -631,7 +683,8 @@ * @param scaleMode {number} Should be one of the scaleMode consts * @return {Texture} a texture of the graphics object */ -Graphics.prototype.generateTexture = function (resolution, scaleMode) { +Graphics.prototype.generateTexture = function (resolution, scaleMode) +{ resolution = resolution || 1; var bounds = this.getBounds(); @@ -655,17 +708,21 @@ * * @param renderer {WebGLRenderer} */ -Graphics.prototype._renderWebGL = function (renderer) { +Graphics.prototype._renderWebGL = function (renderer) +{ // if the sprite is not visible or the alpha is 0 then no need to render this element - if (this.isMask === true) { + if (this.isMask === true) + { return; } // this code may still be needed so leaving for now.. - // + // /* - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture on the gpu too! @@ -681,17 +738,24 @@ return; } - */ - - // check if the webgl graphic needs to be updated - if (this.glDirty) { - this.dirty = true; - this.glDirty = false; - } + else */ - renderer.setObjectRendererer(renderer.graphicsRenderer); - renderer.graphicsRenderer.render(this); + renderer.spriteBatch.stop(); + renderer.blendModeManager.setBlendMode(this.blendMode); + // check blend mode + renderer.blendModeManager.setBlendMode( this.blendMode ); + + // check if the webgl graphic needs to be updated + if (this.glDirty) + { + this.dirty = true; + this.glDirty = false; + } + + WebGLGraphics.renderGraphics(this, renderer); + + renderer.spriteBatch.start(); }; /** @@ -700,14 +764,18 @@ * @param renderer {CanvasRenderer} * @private */ -Graphics.prototype.renderCanvas = function (renderer) { +Graphics.prototype.renderCanvas = function (renderer) +{ // 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.isMask === true) { + if (!this.visible || this.alpha <= 0 || this.isMask === true) + { return; } - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture @@ -723,16 +791,19 @@ return; } - else { + else + { var context = renderer.context; var transform = this.worldTransform; - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } @@ -748,11 +819,13 @@ CanvasGraphics.renderGraphics(this, context); - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } } @@ -763,13 +836,16 @@ * * @return {Rectangle} the rectangular bounding area */ -Graphics.prototype.getBounds = function (matrix) { +Graphics.prototype.getBounds = function (matrix) +{ // return an empty object if the item is a mask! - if (this.isMask) { + if (this.isMask) + { return math.Rectangle.EMPTY; } - if (this.dirty) { + if (this.dirty) + { this.updateLocalBounds(); this.glDirty = true; @@ -841,23 +917,27 @@ * Update the bounds of the object * */ -Graphics.prototype.updateLocalBounds = function () { +Graphics.prototype.updateLocalBounds = function () +{ var minX = Infinity; var maxX = -Infinity; var minY = Infinity; var maxY = -Infinity; - if (this.graphicsData.length) { + if (this.graphicsData.length) + { var shape, points, x, y, w, h; - for (var i = 0; i < this.graphicsData.length; i++) { + for (var i = 0; i < this.graphicsData.length; i++) + { var data = this.graphicsData[i]; var type = data.type; var lineWidth = data.lineWidth; shape = data.shape; - if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) { + if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) + { x = shape.x - lineWidth/2; y = shape.y - lineWidth/2; w = shape.width + lineWidth; @@ -869,7 +949,8 @@ minY = y < minY ? y : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.CIRC) { + else if (type === CONST.SHAPES.CIRC) + { x = shape.x; y = shape.y; w = shape.radius + lineWidth/2; @@ -881,7 +962,8 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.ELIP) { + else if (type === CONST.SHAPES.ELIP) + { x = shape.x; y = shape.y; w = shape.width + lineWidth/2; @@ -893,11 +975,13 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else { + else + { // POLY points = shape.points; - for (var j = 0; j < points.length; j += 2) { + for (var j = 0; j < points.length; j += 2) + { x = points[j]; y = points[j+1]; @@ -910,7 +994,8 @@ } } } - else { + else + { minX = 0; maxX = 0; minY = 0; @@ -931,10 +1016,12 @@ * * @private */ -Graphics.prototype._generateCachedSprite = function () { +Graphics.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { var canvasBuffer = new CanvasBuffer(bounds.width, bounds.height); var texture = Texture.fromCanvas(canvasBuffer.canvas); @@ -943,7 +1030,8 @@ this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.buffer.resize(bounds.width, bounds.height); } @@ -968,7 +1056,8 @@ * * @private */ -Graphics.prototype.updateCachedSpriteTexture = function () { +Graphics.prototype.updateCachedSpriteTexture = function () +{ var cachedSprite = this._cachedSprite; var texture = cachedSprite.texture; var canvas = cachedSprite.buffer.canvas; @@ -989,7 +1078,8 @@ * Destroys a previous cached sprite. * */ -Graphics.prototype.destroyCachedSprite = function () { +Graphics.prototype.destroyCachedSprite = function () +{ this._cachedSprite.texture.destroy(true); // let the gc collect the unused sprite @@ -1003,10 +1093,13 @@ * @param {Circle|Rectangle|Ellipse|Line|Polygon} shape The Shape object to draw. * @return {GraphicsData} The generated GraphicsData object. */ -Graphics.prototype.drawShape = function (shape) { - if (this.currentPath) { +Graphics.prototype.drawShape = function (shape) +{ + if (this.currentPath) + { // check current path! - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath.shape.points.length <= 2) + { this.graphicsData.pop(); } } @@ -1017,7 +1110,8 @@ this.graphicsData.push(data); - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { data.shape.closed = this.filling; this.currentPath = data; } diff --git a/src/core/primitives/GraphicsData.js b/src/core/primitives/GraphicsData.js index 99decbe..788f6f2 100644 --- a/src/core/primitives/GraphicsData.js +++ b/src/core/primitives/GraphicsData.js @@ -4,7 +4,8 @@ * @class * @namespace PIXI */ -function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) { +function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) +{ this.lineWidth = lineWidth; this.lineColor = lineColor; this.lineAlpha = lineAlpha; @@ -27,7 +28,8 @@ * * @return {GraphicsData} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ return new GraphicsData( this.lineWidth, this.lineColor, diff --git a/src/core/renderers/canvas/CanvasRenderer.js b/src/core/renderers/canvas/CanvasRenderer.js index 15a0978..7aebd44 100644 --- a/src/core/renderers/canvas/CanvasRenderer.js +++ b/src/core/renderers/canvas/CanvasRenderer.js @@ -17,17 +17,22 @@ * @param [options.resolution=1] {number} the resolution of the renderer retina would be 2 * @param [options.clearBeforeRender=true] {boolean} This sets if the CanvasRenderer will clear the canvas or not before the new render pass. */ -function CanvasRenderer(width, height, options) { +function CanvasRenderer(width, height, options) +{ utils.sayHello('Canvas'); - if (options) { - for (var i in CONST.defaultRenderOptions) { - if (typeof options[i] === 'undefined') { + if (options) + { + for (var i in CONST.defaultRenderOptions) + { + if (typeof options[i] === 'undefined') + { options[i] = CONST.defaultRenderOptions[i]; } } } - else { + else + { options = CONST.defaultRenderOptions; } @@ -156,19 +161,24 @@ this.smoothProperty = null; - if (this.context.imageSmoothingEnabled) { + if (this.context.imageSmoothingEnabled) + { this.smoothProperty = 'imageSmoothingEnabled'; } - else if (this.context.webkitImageSmoothingEnabled) { + else if (this.context.webkitImageSmoothingEnabled) + { this.smoothProperty = 'webkitImageSmoothingEnabled'; } - else if (this.context.mozImageSmoothingEnabled) { + else if (this.context.mozImageSmoothingEnabled) + { this.smoothProperty = 'mozImageSmoothingEnabled'; } - else if (this.context.oImageSmoothingEnabled) { + else if (this.context.oImageSmoothingEnabled) + { this.smoothProperty = 'oImageSmoothingEnabled'; } - else if (this.context.msImageSmoothingEnabled) { + else if (this.context.msImageSmoothingEnabled) + { this.smoothProperty = 'msImageSmoothingEnabled'; } @@ -193,10 +203,12 @@ * @memberof CanvasRenderer# */ backgroundColor: { - get: function () { + get: function () + { return this._backgroundColor; }, - set: function (val) { + set: function (val) + { this._backgroundColor = val; this._backgroundColorString = utils.hex2string(val); } @@ -208,7 +220,8 @@ * * @param object {DisplayObject} the object to be rendered */ -CanvasRenderer.prototype.render = function (object) { +CanvasRenderer.prototype.render = function (object) +{ object.updateTransform(); this.context.setTransform(1,0,0,1,0,0); @@ -218,16 +231,20 @@ this.currentBlendMode = CONST.blendModes.NORMAL; this.context.globalCompositeOperation = this.blendModes[CONST.blendModes.NORMAL]; - if (navigator.isCocoonJS && this.view.screencanvas) { + if (navigator.isCocoonJS && this.view.screencanvas) + { this.context.fillStyle = 'black'; this.context.clear(); } - if (this.clearBeforeRender) { - if (this.transparent) { + if (this.clearBeforeRender) + { + if (this.transparent) + { this.context.clearRect(0, 0, this.width, this.height); } - else { + else + { this.context.fillStyle = this._backgroundColorString; this.context.fillRect(0, 0, this.width , this.height); } @@ -241,8 +258,10 @@ * * @param [removeView=false] {boolean} Removes the Canvas element from the DOM. */ -CanvasRenderer.prototype.destroy = function (removeView) { - if (removeView && this.view.parent) { +CanvasRenderer.prototype.destroy = function (removeView) +{ + if (removeView && this.view.parent) + { this.view.parent.removeChild(this.view); } @@ -257,14 +276,16 @@ * @param width {number} the new width of the canvas view * @param height {number} the new height of the canvas view */ -CanvasRenderer.prototype.resize = function (width, height) { +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) { + if (this.autoResize) + { this.view.style.width = this.width / this.resolution + 'px'; this.view.style.height = this.height / this.resolution + 'px'; } @@ -276,7 +297,8 @@ * @param displayObject {DisplayObject} The displayObject to render * @private */ -CanvasRenderer.prototype.renderDisplayObject = function (displayObject) { +CanvasRenderer.prototype.renderDisplayObject = function (displayObject) +{ displayObject.renderCanvas(this); }; @@ -285,11 +307,14 @@ * * @private */ -CanvasRenderer.prototype._mapBlendModes = function () { - if (!this.blendModes) { +CanvasRenderer.prototype._mapBlendModes = function () +{ + if (!this.blendModes) + { this.blendModes = {}; - if (utils.canUseNewCanvasBlendModes()) { + if (utils.canUseNewCanvasBlendModes()) + { this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? this.blendModes[CONST.blendModes.MULTIPLY] = 'multiply'; @@ -308,7 +333,8 @@ this.blendModes[CONST.blendModes.COLOR] = 'color'; this.blendModes[CONST.blendModes.LUMINOSITY] = 'luminosity'; } - else { + else + { // this means that the browser does not support the cool new blend modes in canvas 'cough' ie 'cough' this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? diff --git a/src/core/renderers/canvas/utils/CanvasBuffer.js b/src/core/renderers/canvas/utils/CanvasBuffer.js index ebe5d47..b183a66 100644 --- a/src/core/renderers/canvas/utils/CanvasBuffer.js +++ b/src/core/renderers/canvas/utils/CanvasBuffer.js @@ -6,7 +6,8 @@ * @param width {number} the width for the newly created canvas * @param height {number} the height for the newly created canvas */ -function CanvasBuffer(width, height) { +function CanvasBuffer(width, height) +{ /** * The Canvas object that belongs to this CanvasBuffer. * @@ -36,10 +37,12 @@ * @memberof CanvasBuffer# */ width: { - get: function () { + get: function () + { return this.canvas.width; }, - set: function (val) { + set: function (val) + { this.canvas.width = val; } }, @@ -50,10 +53,12 @@ * @memberof CanvasBuffer# */ height: { - get: function () { + get: function () + { return this.canvas.height; }, - set: function (val) { + set: function (val) + { this.canvas.height = val; } } @@ -64,7 +69,8 @@ * * @private */ -CanvasBuffer.prototype.clear = function () { +CanvasBuffer.prototype.clear = function () +{ this.context.setTransform(1, 0, 0, 1, 0, 0); this.context.clearRect(0,0, this.canvas.width, this.canvas.height); }; @@ -75,7 +81,8 @@ * @param width {number} the new width of the canvas * @param height {number} the new height of the canvas */ -CanvasBuffer.prototype.resize = function (width, height) { +CanvasBuffer.prototype.resize = function (width, height) +{ this.canvas.width = width; this.canvas.height = height; }; diff --git a/src/core/renderers/canvas/utils/CanvasGraphics.js b/src/core/renderers/canvas/utils/CanvasGraphics.js index c7eaa2a..3f2a91f 100644 --- a/src/core/renderers/canvas/utils/CanvasGraphics.js +++ b/src/core/renderers/canvas/utils/CanvasGraphics.js @@ -13,15 +13,18 @@ * @param graphics {Graphics} the actual graphics object to render * @param context {CanvasRenderingContext2D} the 2d drawing method of the canvas */ -CanvasGraphics.renderGraphics = function (graphics, context) { +CanvasGraphics.renderGraphics = function (graphics, context) +{ var worldAlpha = graphics.worldAlpha; - if (graphics.dirty) { + if (graphics.dirty) + { this.updateGraphicsTint(graphics); graphics.dirty = false; } - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; @@ -30,69 +33,82 @@ context.lineWidth = data.lineWidth; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { context.beginPath(); var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } - if (shape.closed) { + if (shape.closed) + { context.lineTo(points[0], points[1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fillRect(shape.x, shape.y, shape.width, shape.height); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.strokeRect(shape.x, shape.y, shape.width, shape.height); } } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.beginPath(); context.arc(shape.x, shape.y, shape.radius,0,2*Math.PI); context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas var w = shape.width * 2; @@ -119,18 +135,21 @@ context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; var width = shape.width; @@ -152,13 +171,15 @@ context.quadraticCurveTo(rx, ry, rx, ry + radius); context.closePath(); - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); @@ -174,45 +195,54 @@ * @param graphics {Graphics} the graphics which will be used as a mask * @param context {CanvasRenderingContext2D} the context 2d method of the canvas */ -CanvasGraphics.renderGraphicsMask = function (graphics, context) { +CanvasGraphics.renderGraphicsMask = function (graphics, context) +{ var len = graphics.graphicsData.length; - if (len === 0) { + if (len === 0) + { return; } context.beginPath(); - for (var i = 0; i < len; i++) { + for (var i = 0; i < len; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { context.rect(shape.x, shape.y, shape.width, shape.height); context.closePath(); } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.arc(shape.x, shape.y, shape.radius, 0, 2 * Math.PI); context.closePath(); } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas @@ -237,7 +267,8 @@ context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); context.closePath(); } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; @@ -262,8 +293,10 @@ } }; -CanvasGraphics.updateGraphicsTint = function (graphics) { - if (graphics.tint === 0xFFFFFF) { +CanvasGraphics.updateGraphicsTint = function (graphics) +{ + if (graphics.tint === 0xFFFFFF) + { return; } @@ -271,7 +304,8 @@ var tintG = (graphics.tint >> 8 & 0xFF) / 255; var tintB = (graphics.tint & 0xFF)/ 255; - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var fillColor = data.fillColor | 0; diff --git a/src/core/renderers/canvas/utils/CanvasMaskManager.js b/src/core/renderers/canvas/utils/CanvasMaskManager.js index e04a733..9827d36 100644 --- a/src/core/renderers/canvas/utils/CanvasMaskManager.js +++ b/src/core/renderers/canvas/utils/CanvasMaskManager.js @@ -6,7 +6,8 @@ * @class * @namespace PIXI */ -function CanvasMaskManager() {} +function CanvasMaskManager() +{} CanvasMaskManager.prototype.constructor = CanvasMaskManager; module.exports = CanvasMaskManager; @@ -17,7 +18,8 @@ * @param maskData {object} the maskData that will be pushed * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.pushMask = function (maskData, renderer) { +CanvasMaskManager.prototype.pushMask = function (maskData, renderer) +{ renderer.context.save(); var cacheAlpha = maskData.alpha; @@ -45,6 +47,7 @@ * * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.popMask = function (renderer) { +CanvasMaskManager.prototype.popMask = function (renderer) +{ renderer.context.restore(); }; diff --git a/src/core/renderers/canvas/utils/CanvasTinter.js b/src/core/renderers/canvas/utils/CanvasTinter.js index 17e0529..d2fb1bc 100644 --- a/src/core/renderers/canvas/utils/CanvasTinter.js +++ b/src/core/renderers/canvas/utils/CanvasTinter.js @@ -14,7 +14,8 @@ * @param color {number} the color to use to tint the sprite with * @return {HTMLCanvasElement} The tinted canvas */ -CanvasTinter.getTintedTexture = function (sprite, color) { +CanvasTinter.getTintedTexture = function (sprite, color) +{ var texture = sprite.texture; color = CanvasTinter.roundColor(color); @@ -23,7 +24,8 @@ texture.tintCache = texture.tintCache || {}; - if (texture.tintCache[stringColor]) { + if (texture.tintCache[stringColor]) + { return texture.tintCache[stringColor]; } @@ -33,14 +35,16 @@ //CanvasTinter.tintWithPerPixel(texture, stringColor, canvas); CanvasTinter.tintMethod(texture, color, canvas); - if (CanvasTinter.convertTintToImage) { + if (CanvasTinter.convertTintToImage) + { // is this better? var tintImage = new Image(); tintImage.src = canvas.toDataURL(); texture.tintCache[stringColor] = tintImage; } - else { + else + { texture.tintCache[stringColor] = canvas; // if we are not converting the texture to an image then we need to lose the reference to the canvas CanvasTinter.canvas = null; @@ -56,7 +60,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithMultiply = function (texture, color, canvas) { +CanvasTinter.tintWithMultiply = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -104,7 +109,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithOverlay = function (texture, color, canvas) { +CanvasTinter.tintWithOverlay = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -139,7 +145,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithPerPixel = function (texture, color, canvas) { +CanvasTinter.tintWithPerPixel = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -167,7 +174,8 @@ var pixels = pixelData.data; - for (var i = 0; i < pixels.length; i += 4) { + for (var i = 0; i < pixels.length; i += 4) + { pixels[i+0] *= r; pixels[i+1] *= g; pixels[i+2] *= b; @@ -181,7 +189,8 @@ * * @param color {number} the color to round, should be a hex color */ -CanvasTinter.roundColor = function (color) { +CanvasTinter.roundColor = function (color) +{ var step = CanvasTinter.cacheStepsPerColorChannel; var rgbValues = utils.hex2rgb(color); diff --git a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js index 9f2f89a..35edbaf 100644 --- a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js +++ b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLBlendModeManager(renderer) { +function WebGLBlendModeManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -23,8 +24,10 @@ * * @param blendMode {number} the blendMode, should be a Pixi const, such as BlendModes.ADD */ -WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) { - if (this.currentBlendMode === blendMode) { +WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) +{ + if (this.currentBlendMode === blendMode) + { return false; } diff --git a/src/core/renderers/webgl/managers/WebGLFilterManager.js b/src/core/renderers/webgl/managers/WebGLFilterManager.js index 1179258..2dac048 100644 --- a/src/core/renderers/webgl/managers/WebGLFilterManager.js +++ b/src/core/renderers/webgl/managers/WebGLFilterManager.js @@ -7,7 +7,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLFilterManager(renderer) { +function WebGLFilterManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -32,7 +33,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.texturePool.length = 0; self.initShaderBuffers(); }); @@ -46,7 +48,8 @@ * @param renderer {WebGLRenderer} * @param buffer {ArrayBuffer} */ -WebGLFilterManager.prototype.begin = function (buffer) { +WebGLFilterManager.prototype.begin = function (buffer) +{ this.defaultShader = this.renderer.shaderManager.defaultShader; this.width = this.renderer.projection.x * 2; @@ -60,7 +63,8 @@ * * @param filterBlock {object} the filter that will be pushed to the current filter stack */ -WebGLFilterManager.prototype.pushFilter = function (filterBlock) { +WebGLFilterManager.prototype.pushFilter = function (filterBlock) +{ var gl = this.renderer.gl; var projection = this.renderer.projection; @@ -78,10 +82,12 @@ this.offsetY += filterBlock._filterArea.y; var texture = this.texturePool.pop(); - if (!texture) { + if (!texture) + { texture = new FilterTexture(this.renderer.gl, this.width, this.height); } - else { + else + { texture.resize(this.width, this.height); } @@ -98,29 +104,35 @@ var localX = filterArea.x, localY = filterArea.y; - if (filterArea.x < 0) { + if (filterArea.x < 0) + { filterArea.width += filterArea.x; filterArea.x = 0; } - if (filterArea.y < 0) { + if (filterArea.y < 0) + { filterArea.height += filterArea.y; filterArea.y = 0; } - if (localX + filterArea.width > this.width) { + if (localX + filterArea.width > this.width) + { filterArea.width = this.width - localX; } - if (localY + filterArea.height > this.height) { + if (localY + filterArea.height > this.height) + { filterArea.height = this.height - localY; } - if (filterArea.width < 0) { + if (filterArea.width < 0) + { filterArea.width = 0; } - if (filterArea.height < 0) { + if (filterArea.height < 0) + { filterArea.height = 0; } @@ -154,7 +166,8 @@ * Removes the last filter from the filter stack and doesn't return it. * */ -WebGLFilterManager.prototype.popFilter = function () { +WebGLFilterManager.prototype.popFilter = function () +{ var gl = this.renderer.gl; var filterBlock = this.filterStack.pop(); @@ -163,7 +176,8 @@ var projection = this.renderer.projection; var offset = this.renderer.offset; - if (filterBlock.filterPasses.length > 1) { + if (filterBlock.filterPasses.length > 1) + { gl.viewport(0, 0, filterArea.width, filterArea.height); gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); @@ -193,7 +207,8 @@ var inputTexture = texture; var outputTexture = this.texturePool.pop(); - if (!outputTexture) { + if (!outputTexture) + { outputTexture = new FilterTexture(this.renderer.gl, this.width, this.height); } outputTexture.resize(this.width, this.height); @@ -204,7 +219,8 @@ gl.disable(gl.BLEND); - for (var i = 0; i < filterBlock.filterPasses.length-1; i++) { + for (var i = 0; i < filterBlock.filterPasses.length-1; i++) + { var filterPass = filterBlock.filterPasses[i]; gl.bindFramebuffer(gl.FRAMEBUFFER, outputTexture.frameBuffer ); @@ -243,10 +259,12 @@ var buffer = this.buffer; // time to render the filters texture to the previous scene - if (this.filterStack.length === 0) { + if (this.filterStack.length === 0) + { gl.colorMask(true, true, true, true);//this.transparent); } - else { + else + { var currentFilter = this.filterStack[this.filterStack.length-1]; filterArea = currentFilter._filterArea; @@ -332,13 +350,15 @@ * @param width {number} the horizontal range of the filter * @param height {number} the vertical range of the filter */ -WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) { +WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) +{ // use program var gl = this.renderer.gl; var shader = filter.shaders[gl.id]; - if (!shader) { + if (!shader) + { shader = new Shader(gl); shader.fragmentSrc = filter.fragmentSrc; @@ -356,7 +376,8 @@ gl.uniform2f(shader.projectionVector, width/2, -height/2); gl.uniform2f(shader.offsetVector, 0,0); - if (filter.uniforms.dimensions) { + 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]; @@ -386,7 +407,8 @@ * Initialises the shader buffers. * */ -WebGLFilterManager.prototype.initShaderBuffers = function () { +WebGLFilterManager.prototype.initShaderBuffers = function () +{ var gl = this.renderer.gl; // create some buffers @@ -432,7 +454,8 @@ * Destroys the filter and removes it from the filter stack. * */ -WebGLFilterManager.prototype.destroy = function () { +WebGLFilterManager.prototype.destroy = function () +{ var gl = this.renderer.gl; this.filterStack = null; @@ -441,7 +464,8 @@ this.offsetY = 0; // destroy textures - for (var i = 0; i < this.texturePool.length; i++) { + for (var i = 0; i < this.texturePool.length; i++) + { this.texturePool[i].destroy(); } diff --git a/src/core/renderers/webgl/managers/WebGLManager.js b/src/core/renderers/webgl/managers/WebGLManager.js index 9d47b5c..c30cd51 100644 --- a/src/core/renderers/webgl/managers/WebGLManager.js +++ b/src/core/renderers/webgl/managers/WebGLManager.js @@ -3,7 +3,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLManager(renderer) { +function WebGLManager(renderer) +{ /** * The renderer this manager works for. * @@ -15,6 +16,7 @@ WebGLManager.prototype.constructor = WebGLManager; module.exports = WebGLManager; -WebGLManager.prototype.destroy = function () { +WebGLManager.prototype.destroy = function () +{ this.renderer = null; }; diff --git a/src/core/renderers/webgl/managers/WebGLMaskManager.js b/src/core/renderers/webgl/managers/WebGLMaskManager.js index 2f90b64..e568812 100644 --- a/src/core/renderers/webgl/managers/WebGLMaskManager.js +++ b/src/core/renderers/webgl/managers/WebGLMaskManager.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLMaskManager(renderer) { +function WebGLMaskManager(renderer) +{ WebGLManager.call(this, renderer); } @@ -19,12 +20,15 @@ * * @param maskData {any[]} */ -WebGLMaskManager.prototype.pushMask = function (maskData) { - if (maskData.dirty) { +WebGLMaskManager.prototype.pushMask = function (maskData) +{ + if (maskData.dirty) + { WebGLGraphics.updateGraphics(maskData, this.renderer.gl); } - if (!maskData._webGL[this.renderer.gl.id].data.length) { + if (!maskData._webGL[this.renderer.gl.id].data.length) + { return; } @@ -36,6 +40,7 @@ * * @param maskData {any[]} */ -WebGLMaskManager.prototype.popMask = function (maskData) { +WebGLMaskManager.prototype.popMask = function (maskData) +{ this.renderer.stencilManager.popStencil(maskData, maskData._webGL[this.renderer.gl.id].data[0], this.renderer); }; diff --git a/src/core/renderers/webgl/managers/WebGLShaderManager.js b/src/core/renderers/webgl/managers/WebGLShaderManager.js index fef071c..90c6477 100644 --- a/src/core/renderers/webgl/managers/WebGLShaderManager.js +++ b/src/core/renderers/webgl/managers/WebGLShaderManager.js @@ -10,7 +10,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLShaderManager(renderer) { +function WebGLShaderManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -28,7 +29,8 @@ */ this.tempAttribState = []; - for (var i = 0; i < this.maxAttibs; i++) { + for (var i = 0; i < this.maxAttibs; i++) + { this.attribState[i] = false; } @@ -66,7 +68,8 @@ // listen for context and update necessary shaders var self = this; - this.renderer.on('context', function (event) { + this.renderer.on('context', function (event) + { var gl = event.data; // this shader is used for rendering primitives @@ -97,29 +100,36 @@ * * @param attribs {Array} attribs */ -WebGLShaderManager.prototype.setAttribs = function (attribs) { +WebGLShaderManager.prototype.setAttribs = function (attribs) +{ // reset temp state var i; - for (i = 0; i < this.tempAttribState.length; i++) { + for (i = 0; i < this.tempAttribState.length; i++) + { this.tempAttribState[i] = false; } // set the new attribs - for (var a in attribs) { + for (var a in attribs) + { this.tempAttribState[attribs[a]] = true; } var gl = this.renderer.gl; - for (i = 0; i < this.attribState.length; i++) { - if (this.attribState[i] !== this.tempAttribState[i]) { + for (i = 0; i < this.attribState.length; i++) + { + if (this.attribState[i] !== this.tempAttribState[i]) + { this.attribState[i] = this.tempAttribState[i]; - if (this.attribState[i]) { + if (this.attribState[i]) + { gl.enableVertexAttribArray(i); } - else { + else + { gl.disableVertexAttribArray(i); } } @@ -131,8 +141,10 @@ * * @param shader {Any} */ -WebGLShaderManager.prototype.setShader = function (shader) { - if (this._currentId === shader.uuid) { +WebGLShaderManager.prototype.setShader = function (shader) +{ + if (this._currentId === shader.uuid) + { return false; } @@ -150,7 +162,8 @@ * Destroys this object. * */ -WebGLShaderManager.prototype.destroy = function () { +WebGLShaderManager.prototype.destroy = function () +{ this.attribState = null; this.tempAttribState = null; diff --git a/src/core/renderers/webgl/managers/WebGLStencilManager.js b/src/core/renderers/webgl/managers/WebGLStencilManager.js index 9ec6398..4cb0134 100644 --- a/src/core/renderers/webgl/managers/WebGLStencilManager.js +++ b/src/core/renderers/webgl/managers/WebGLStencilManager.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLStencilManager(renderer) { +function WebGLStencilManager(renderer) +{ WebGLManager.call(this, renderer); this.stencilStack = []; @@ -24,12 +25,14 @@ * @param graphics {Graphics} * @param webGLData {any[]} */ -WebGLStencilManager.prototype.pushStencil = function (graphics, webGLData) { +WebGLStencilManager.prototype.pushStencil = function (graphics, webGLData) +{ var gl = this.renderer.gl; this.bindGraphics(graphics, webGLData, this.renderer); - if (this.stencilStack.length === 0) { + if (this.stencilStack.length === 0) + { gl.enable(gl.STENCIL_TEST); gl.clear(gl.STENCIL_BUFFER_BIT); this.reverse = true; @@ -47,14 +50,17 @@ // draw the triangle strip! - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } @@ -62,31 +68,38 @@ // draw a quad to increment.. gl.drawElements(gl.TRIANGLE_FAN, 4, gl.UNSIGNED_SHORT, ( webGLData.indices.length - 4 ) * 2 ); - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); } this.reverse = !this.reverse; } - else { - if (!this.reverse) { + else + { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } - else { + 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) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); } } @@ -103,7 +116,8 @@ * @param graphics {Graphics} * @param webGLData {Array} */ -WebGLStencilManager.prototype.bindGraphics = function (graphics, webGLData) { +WebGLStencilManager.prototype.bindGraphics = function (graphics, webGLData) +{ //if (this._currentGraphics === graphics)return; this._currentGraphics = graphics; @@ -114,7 +128,8 @@ offset = this.renderer.offset, shader;// = this.renderer.shaderManager.primitiveShader; - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { shader = this.renderer.shaderManager.complexPrimitiveShader; this.renderer.shaderManager.setShader(shader); @@ -141,7 +156,8 @@ // set the index buffer! gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, webGLData.indexBuffer); } - else { + else + { //this.renderer.shaderManager.activatePrimitiveShader(); shader = this.renderer.shaderManager.primitiveShader; this.renderer.shaderManager.setShader( shader ); @@ -154,7 +170,7 @@ gl.uniform2f(shader.uniforms.offsetVector._location, -offset.x, -offset.y); gl.uniform3fv(shader.uniforms.tint._location, utils.hex2rgb(graphics.tint)); - + gl.uniform1f(shader.uniforms.alpha._location, graphics.worldAlpha); @@ -172,19 +188,22 @@ * @param graphics {Graphics} * @param webGLData {Array} */ -WebGLStencilManager.prototype.popStencil = function (graphics, webGLData) { +WebGLStencilManager.prototype.popStencil = function (graphics, webGLData) +{ var gl = this.renderer.gl; this.stencilStack.pop(); this.count--; - if (this.stencilStack.length === 0) { + if (this.stencilStack.length === 0) + { // the stack is empty! gl.disable(gl.STENCIL_TEST); } - else { + else + { var level = this.count; @@ -192,14 +211,17 @@ gl.colorMask(false, false, false, false); - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { this.reverse = !this.reverse; - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } @@ -213,31 +235,38 @@ // draw the triangle strip! gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); - if (!this.reverse) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); } } - else { + else + { // console.log("<<>>") - if (!this.reverse) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } - else { + 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) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); } } @@ -253,7 +282,8 @@ * Destroys the mask stack. * */ -WebGLStencilManager.prototype.destroy = function () { +WebGLStencilManager.prototype.destroy = function () +{ this.renderer = null; this.stencilStack = null; }; diff --git a/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js b/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js index 913ba5e..1ea7d19 100644 --- a/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js +++ b/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function ComplexPrimitiveShader(gl) { +function ComplexPrimitiveShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -24,7 +25,8 @@ 'uniform float flipY;', 'varying vec4 vColor;', - 'void main(void) {', + '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);', @@ -37,7 +39,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = vColor;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/FastShader.js b/src/core/renderers/webgl/shaders/FastShader.js index bd2e29a..2e5e060 100644 --- a/src/core/renderers/webgl/shaders/FastShader.js +++ b/src/core/renderers/webgl/shaders/FastShader.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function FastShader(gl) { +function FastShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -28,7 +29,8 @@ 'const vec2 center = vec2(-1.0, 1.0);', - 'void main(void) {', + 'void main(void) + {', ' vec2 v;', ' vec2 sv = aVertexPosition * aScale;', ' v.x = (sv.x) * cos(aRotation) - (sv.y) * sin(aRotation);', @@ -49,7 +51,8 @@ 'uniform sampler2D uSampler;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/PrimitiveShader.js b/src/core/renderers/webgl/shaders/PrimitiveShader.js index 6f25409..a25f54f 100644 --- a/src/core/renderers/webgl/shaders/PrimitiveShader.js +++ b/src/core/renderers/webgl/shaders/PrimitiveShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function PrimitiveShader(gl) { +function PrimitiveShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -23,7 +24,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + '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);', @@ -36,7 +38,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = vColor;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/Shader.js b/src/core/renderers/webgl/shaders/Shader.js index f8964f5..fd75ef5 100644 --- a/src/core/renderers/webgl/shaders/Shader.js +++ b/src/core/renderers/webgl/shaders/Shader.js @@ -6,7 +6,8 @@ * @param [fragmentSrc] {string} The source of the fragment shader. * @param [vertexSrc] {string} The source of the vertex shader. */ -function Shader(gl, vertexSrc, fragmentSrc, customUniforms, customAttributes) { +function Shader(gl, vertexSrc, fragmentSrc, customUniforms, customAttributes) +{ /** * @member {number} * @readonly @@ -33,7 +34,8 @@ dimensions: { type: '4f', value: new Float32Array(4) } }; - for (var u in customUniforms) { + for (var u in customUniforms) + { this.uniforms[u] = customUniforms[u]; } @@ -43,7 +45,8 @@ aColor: 0 }; - for (var a in customAttributes) { + for (var a in customAttributes) + { this.attributes[a] = customAttributes[a]; } @@ -66,7 +69,8 @@ 'const vec2 center = vec2(-1.0, 1.0);', - 'void main(void) {', + 'void main(void) + {', ' gl_Position = vec4( ((aVertexPosition + offsetVector) / projectionVector) + center , 0.0, 1.0);', ' vTextureCoord = aTextureCoord;', ' vColor = vec4(aColor.rgb * aColor.a, aColor.a);', @@ -85,7 +89,8 @@ 'uniform sampler2D uSampler;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;', '}' ].join('\n'); @@ -96,7 +101,8 @@ Shader.prototype.constructor = Shader; module.exports = Shader; -Shader.prototype.init = function () { +Shader.prototype.init = function () +{ this.compile(); this.gl.useProgram(this.program); @@ -105,14 +111,18 @@ this.cacheAttributeLocations(Object.keys(this.attributes)); }; -Shader.prototype.cacheUniformLocations = function (keys) { - for (var i = 0; i < keys.length; ++i) { +Shader.prototype.cacheUniformLocations = function (keys) +{ + for (var i = 0; i < keys.length; ++i) + { this.uniforms[keys[i]]._location = this.gl.getUniformLocation(this.program, keys[i]); } }; -Shader.prototype.cacheAttributeLocations = function (keys) { - for (var i = 0; i < keys.length; ++i) { +Shader.prototype.cacheAttributeLocations = function (keys) +{ + for (var i = 0; i < keys.length; ++i) + { this.attributes[keys[i]] = this.gl.getAttribLocation(this.program, keys[i]); } @@ -124,14 +134,16 @@ // 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.attributes.aColor === -1) { + // if (this.attributes.aColor === -1) + { // this.attributes.aColor = 2; // } // End worst hack eva // }; -Shader.prototype.compile = function () { +Shader.prototype.compile = function () +{ var gl = this.gl; var glVertShader = this._glCompile(gl.VERTEX_SHADER, this.vertexSrc); @@ -144,13 +156,15 @@ gl.linkProgram(program); // if linking fails, then log and cleanup - if (!gl.getProgramParameter(program, gl.LINK_STATUS)) { + if (!gl.getProgramParameter(program, gl.LINK_STATUS)) + { window.console.error('Pixi.js Error: Could not initialize shader.'); window.console.error('gl.VALIDATE_STATUS', gl.getProgramParameter(program, gl.VALIDATE_STATUS)); window.console.error('gl.getError()', gl.getError()); // if there is a program info log, log it - if (gl.getProgramInfoLog(program) !== '') { + if (gl.getProgramInfoLog(program) !== '') + { window.console.warn('Pixi.js Warning: gl.getProgramInfoLog()', gl.getProgramInfoLog(program)); } @@ -165,18 +179,21 @@ return (this.program = program); }; -Shader.prototype.syncUniforms = function () { +Shader.prototype.syncUniforms = function () +{ var gl = this.gl; this.textureCount = 1; - for (var key in this.uniforms) { + for (var key in this.uniforms) + { var uniform = this.uniforms[key], location = uniform._location, value = uniform.value, i, il; - switch (uniform.type) { + switch (uniform.type) + { // single int value case 'i': case '1i': @@ -282,7 +299,8 @@ // a Color Value case 'c': - if (typeof value === 'number') { + if (typeof value === 'number') + { value = utils.hex2rgb(value); } @@ -311,11 +329,13 @@ // array of 2D Point objects case 'v2v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(2 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 2] = value[i].x; uniform._array[i * 2 + 1] = value[i].y; } @@ -325,11 +345,13 @@ // array of 3D Point objects case 'v3v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(3 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 3] = value[i].x; uniform._array[i * 3 + 1] = value[i].y; uniform._array[i * 3 + 2] = value[i].z; @@ -341,11 +363,13 @@ // array of 4D Point objects case 'v4v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(4 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 4] = value[i].x; uniform._array[i * 4 + 1] = value[i].y; uniform._array[i * 4 + 2] = value[i].z; @@ -359,7 +383,8 @@ // PIXI.Texture case 't': case 'sampler2D': - if (!uniform.value || !uniform.value.baseTexture || !uniform.value.baseTexture.hasLoaded) { + if (!uniform.value || !uniform.value.baseTexture || !uniform.value.baseTexture.hasLoaded) + { break; } @@ -376,7 +401,8 @@ this.textureCount++; // initialize the texture if we haven't yet - if (!uniform._init) { + if (!uniform._init) + { this.initSampler2D(uniform); uniform._init = true; @@ -394,11 +420,13 @@ * Initialises a Sampler2D uniform (which may only be available later on after initUniforms once the texture has loaded) * */ -Shader.prototype.initSampler2D = function (uniform) { +Shader.prototype.initSampler2D = function (uniform) +{ var gl = this.gl; // Extended texture data - if (uniform.textureData) { + if (uniform.textureData) + { var data = uniform.textureData; // GLTexture = mag linear, min linear_mipmap_linear, wrap repeat + gl.generateMipmap(gl.TEXTURE_2D); @@ -417,14 +445,16 @@ var wrapT = (data.wrapT) ? data.wrapT : gl.CLAMP_TO_EDGE; var format = (data.luminance) ? gl.LUMINANCE : gl.RGBA; - if (data.repeat) { + if (data.repeat) + { wrapS = gl.REPEAT; wrapT = gl.REPEAT; } gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, !!data.flipY); - if (data.width) { + if (data.width) + { var width = (data.width) ? data.width : 512; var height = (data.height) ? data.height : 2; var border = (data.border) ? data.border : 0; @@ -432,7 +462,8 @@ // 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 { + 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); } @@ -448,7 +479,8 @@ * Destroys the shader. * */ -Shader.prototype.destroy = function () { +Shader.prototype.destroy = function () +{ this.gl.deleteProgram(this.program); this.gl = null; @@ -459,13 +491,15 @@ this.fragmentSrc = null; }; -Shader.prototype._glCompile = function (type, src) { +Shader.prototype._glCompile = function (type, src) +{ var shader = this.gl.createShader(type); this.gl.shaderSource(shader, src); this.gl.compileShader(shader); - if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) { + if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) + { window.console.log(this.gl.getShaderInfoLog(shader)); return null; } diff --git a/src/core/renderers/webgl/shaders/StripShader.js b/src/core/renderers/webgl/shaders/StripShader.js index 193f6e1..a7abcc6 100644 --- a/src/core/renderers/webgl/shaders/StripShader.js +++ b/src/core/renderers/webgl/shaders/StripShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function StripShader(gl) { +function StripShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -20,7 +21,8 @@ 'varying vec2 vTextureCoord;', - 'void main(void) {', + '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);', @@ -36,7 +38,8 @@ 'varying vec2 vTextureCoord;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vec2(vTextureCoord.x, vTextureCoord.y)) * alpha;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/utils/FilterTexture.js b/src/core/renderers/webgl/utils/FilterTexture.js index d2c8423..4433d44 100644 --- a/src/core/renderers/webgl/utils/FilterTexture.js +++ b/src/core/renderers/webgl/utils/FilterTexture.js @@ -8,7 +8,8 @@ * @param height {number} the vertical range of the filter * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values */ -function FilterTexture(gl, width, height, scaleMode) { +function FilterTexture(gl, width, height, scaleMode) +{ /** * @member {WebGLContext} */ @@ -59,7 +60,8 @@ * Clears the filter texture. * */ -FilterTexture.prototype.clear = function () { +FilterTexture.prototype.clear = function () +{ var gl = this.gl; gl.clearColor(0,0,0, 0); @@ -72,8 +74,10 @@ * @param width {number} the new width of the texture * @param height {number} the new height of the texture */ -FilterTexture.prototype.resize = function (width, height) { - if (this.width === width && this.height === height) { +FilterTexture.prototype.resize = function (width, height) +{ + if (this.width === width && this.height === height) + { return; } @@ -96,7 +100,8 @@ * Destroys the filter texture. * */ -FilterTexture.prototype.destroy = function () { +FilterTexture.prototype.destroy = function () +{ var gl = this.gl; gl.deleteFramebuffer( this.frameBuffer ); gl.deleteTexture( this.texture ); diff --git a/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js b/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js index c4721e9..a63f4d7 100644 --- a/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js +++ b/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js @@ -14,7 +14,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this sprite batch works for. */ -function WebGLFastSpriteBatch(renderer) { +function WebGLFastSpriteBatch(renderer) +{ /** * The renderer instance this sprite batch operates on. * @@ -91,7 +92,8 @@ */ this.lastIndexCount = 0; - for (var i=0, j=0; i < numIndices; i += 6, j += 4) { + 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; @@ -144,7 +146,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.setupContext(); }); } @@ -157,7 +160,8 @@ * * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLFastSpriteBatch.prototype.setupContext = function () { +WebGLFastSpriteBatch.prototype.setupContext = function () +{ var gl = this.renderer.gl; // create a couple of buffers @@ -177,7 +181,8 @@ /** * @param spriteBatch {SpriteBatch} The SpriteBatch container to prepare for. */ -WebGLFastSpriteBatch.prototype.begin = function (spriteBatch) { +WebGLFastSpriteBatch.prototype.begin = function (spriteBatch) +{ this.shader = this.renderer.shaderManager.fastShader; this.matrix = spriteBatch.worldTransform.toArray(true); @@ -187,33 +192,38 @@ /** */ -WebGLFastSpriteBatch.prototype.end = function () { +WebGLFastSpriteBatch.prototype.end = function () +{ this.flush(); }; /** * @param spriteBatch {SpriteBatch} The SpriteBatch container to render. */ -WebGLFastSpriteBatch.prototype.render = function (spriteBatch) { +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) { + if (!sprite.texture._uvs) + { return; } this.currentBaseTexture = sprite.texture.baseTexture; // check blend mode - if (sprite.blendMode !== this.renderer.blendModeManager.currentBlendMode) { + if (sprite.blendMode !== this.renderer.blendModeManager.currentBlendMode) + { this.flush(); this.renderer.blendModeManager.setBlendMode(sprite.blendMode); } - for (var i=0,j= children.length; i= this.size) { + if (this.currentBatchSize >= this.size) + { this.flush(); } }; @@ -362,29 +379,35 @@ /** * */ -WebGLFastSpriteBatch.prototype.flush = function () { +WebGLFastSpriteBatch.prototype.flush = function () +{ // If the batch is length 0 then return as there is nothing to draw - if (this.currentBatchSize === 0) { + if (this.currentBatchSize === 0) + { return; } var gl = this.renderer.gl; // bind the current texture - if (!this.currentBaseTexture._glTextures[gl.id]) { + if (!this.currentBaseTexture._glTextures[gl.id]) + { this.renderer.updateTexture(this.currentBaseTexture, gl); } //TODO-SHOUD THIS BE ELSE??!?!?! - else { + else + { gl.bindTexture(gl.TEXTURE_2D, this.currentBaseTexture._glTextures[gl.id]); } // upload the verts to the buffer - if (this.currentBatchSize > ( this.size * 0.5 ) ) { + if (this.currentBatchSize > ( this.size * 0.5 ) ) + { gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); } - else { + else + { var view = this.vertices.subarray(0, this.currentBatchSize * this.vertByteSize); gl.bufferSubData(gl.ARRAY_BUFFER, 0, view); @@ -405,14 +428,16 @@ * Ends the batch and flushes * */ -WebGLFastSpriteBatch.prototype.stop = function () { +WebGLFastSpriteBatch.prototype.stop = function () +{ this.flush(); }; /** * */ -WebGLFastSpriteBatch.prototype.start = function () { +WebGLFastSpriteBatch.prototype.start = function () +{ var gl = this.renderer.gl; // bind the main texture diff --git a/src/core/renderers/webgl/utils/WebGLGraphics.js b/src/core/renderers/webgl/utils/WebGLGraphics.js index 55f4911..ab8f46e 100644 --- a/src/core/renderers/webgl/utils/WebGLGraphics.js +++ b/src/core/renderers/webgl/utils/WebGLGraphics.js @@ -19,7 +19,8 @@ * @param graphics {Graphics} * @param renderer {WebGLRenderer} */ -WebGLGraphics.renderGraphics = function (graphics, renderer) {//projection, offset) { +WebGLGraphics.renderGraphics = function (graphics, renderer) {//projection, offset) +{ var gl = renderer.gl; var projection = renderer.projection, @@ -27,7 +28,8 @@ shader = renderer.shaderManager.primitiveShader, webGLData; - if (graphics.dirty) { + if (graphics.dirty) + { WebGLGraphics.updateGraphics(graphics, gl); } @@ -35,8 +37,10 @@ // This could be speeded up for sure! - for (var i = 0; i < webGL.data.length; i++) { - if (webGL.data[i].mode === 1) { + for (var i = 0; i < webGL.data.length; i++) + { + if (webGL.data[i].mode === 1) + { webGLData = webGL.data[i]; renderer.stencilManager.pushStencil(graphics, webGLData, renderer); @@ -46,7 +50,8 @@ renderer.stencilManager.popStencil(graphics, webGLData, renderer); } - else { + else + { webGLData = webGL.data[i]; @@ -84,12 +89,14 @@ * @param graphicsData {Graphics} The graphics object to update * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLGraphics.updateGraphics = function (graphics, gl) { +WebGLGraphics.updateGraphics = function (graphics, gl) +{ // get the contexts graphics object var webGL = graphics._webGL[gl.id]; // if the graphics object does not exist in the webGL context time to create it! - if (!webGL) { + if (!webGL) + { webGL = graphics._webGL[gl.id] = {lastIndex:0, data:[], gl:gl}; } @@ -99,11 +106,13 @@ var i; // if the user cleared the graphics object we will need to clear every object - if (graphics.clearDirty) { + if (graphics.clearDirty) + { graphics.clearDirty = false; // lop through and return all the webGLDatas to the object pool so than can be reused later on - for (i = 0; i < webGL.data.length; i++) { + for (i = 0; i < webGL.data.length; i++) + { var graphicsData = webGL.data[i]; graphicsData.reset(); WebGLGraphics.graphicsDataPool.push( graphicsData ); @@ -119,58 +128,72 @@ // loop through the graphics datas and construct each one.. // if the object is a complex fill then the new stencil buffer technique will be used // other wise graphics objects will be pushed into a batch.. - for (i = webGL.lastIndex; i < graphics.graphicsData.length; i++) { + for (i = webGL.lastIndex; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { // need to add the points the the graphics object.. data.points = data.shape.points.slice(); - if (data.shape.closed) { + if (data.shape.closed) + { // close the poly if the value is true! - if (data.points[0] !== data.points[data.points.length-2] || data.points[1] !== data.points[data.points.length-1]) { + if (data.points[0] !== data.points[data.points.length-2] || data.points[1] !== data.points[data.points.length-1]) + { data.points.push(data.points[0], data.points[1]); } } // MAKE SURE WE HAVE THE CORRECT TYPE.. - if (data.fill) { - if (data.points.length >= 6) { - if (data.points.length < 6 * 2) { + if (data.fill) + { + if (data.points.length >= 6) + { + if (data.points.length < 6 * 2) + { webGLData = WebGLGraphics.switchMode(webGL, 0); var canDrawUsingSimple = WebGLGraphics.buildPoly(data, webGLData); // console.log(canDrawUsingSimple); - if (!canDrawUsingSimple) { + if (!canDrawUsingSimple) + { // console.log("<>>>") webGLData = WebGLGraphics.switchMode(webGL, 1); WebGLGraphics.buildComplexPoly(data, webGLData); } } - else { + else + { webGLData = WebGLGraphics.switchMode(webGL, 1); WebGLGraphics.buildComplexPoly(data, webGLData); } } } - if (data.lineWidth > 0) { + if (data.lineWidth > 0) + { webGLData = WebGLGraphics.switchMode(webGL, 0); WebGLGraphics.buildLine(data, webGLData); } } - else { + else + { webGLData = WebGLGraphics.switchMode(webGL, 0); - if (data.type === CONST.SHAPES.RECT) { + if (data.type === CONST.SHAPES.RECT) + { WebGLGraphics.buildRectangle(data, webGLData); } - else if (data.type === CONST.SHAPES.CIRC || data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.CIRC || data.type === CONST.SHAPES.ELIP) + { WebGLGraphics.buildCircle(data, webGLData); } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { WebGLGraphics.buildRoundedRectangle(data, webGLData); } } @@ -179,10 +202,12 @@ } // upload all the dirty data... - for (i = 0; i < webGL.data.length; i++) { + for (i = 0; i < webGL.data.length; i++) + { webGLData = webGL.data[i]; - if (webGLData.dirty) { + if (webGLData.dirty) + { webGLData.upload(); } } @@ -194,18 +219,22 @@ * @param webGL {WebGLContext} * @param type {number} */ -WebGLGraphics.switchMode = function (webGL, type) { +WebGLGraphics.switchMode = function (webGL, type) +{ var webGLData; - if (!webGL.data.length) { + if (!webGL.data.length) + { webGLData = WebGLGraphics.graphicsDataPool.pop() || new WebGLGraphicsData(webGL.gl); webGLData.mode = type; webGL.data.push(webGLData); } - else { + else + { webGLData = webGL.data[webGL.data.length-1]; - if (webGLData.mode !== type || type === 1) { + if (webGLData.mode !== type || type === 1) + { webGLData = WebGLGraphics.graphicsDataPool.pop() || new WebGLGraphicsData(webGL.gl); webGLData.mode = type; webGL.data.push(webGLData); @@ -225,7 +254,8 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildRectangle = function (graphicsData, webGLData) { +WebGLGraphics.buildRectangle = function (graphicsData, webGLData) +{ // --- // // need to convert points to a nice regular data // @@ -235,7 +265,8 @@ var width = rectData.width; var height = rectData.height; - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -265,7 +296,8 @@ indices.push(vertPos, vertPos, vertPos+1, vertPos+2, vertPos+3, vertPos+3); } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = [x, y, @@ -289,7 +321,8 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildRoundedRectangle = function (graphicsData, webGLData) { +WebGLGraphics.buildRoundedRectangle = function (graphicsData, webGLData) +{ var rrectData = graphicsData.shape; var x = rrectData.x; var y = rrectData.y; @@ -305,7 +338,8 @@ recPoints = recPoints.concat(WebGLGraphics.quadraticBezierCurve(x + width, y + radius, x + width, y, x + width - radius, y)); recPoints = recPoints.concat(WebGLGraphics.quadraticBezierCurve(x + radius, y, x, y, x, y + radius)); - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -323,7 +357,8 @@ // var i = 0; - for (i = 0; i < triangles.length; i+=3) { + for (i = 0; i < triangles.length; i+=3) + { indices.push(triangles[i] + vecPos); indices.push(triangles[i] + vecPos); indices.push(triangles[i+1] + vecPos); @@ -332,12 +367,14 @@ } - for (i = 0; i < recPoints.length; i++) { + for (i = 0; i < recPoints.length; i++) + { verts.push(recPoints[i], recPoints[++i], r, g, b, alpha); } } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = recPoints; @@ -362,7 +399,8 @@ * @param toY {number} Destination point y * @return {number[]} */ -WebGLGraphics.quadraticBezierCurve = function (fromX, fromY, cpX, cpY, toX, toY) { +WebGLGraphics.quadraticBezierCurve = function (fromX, fromY, cpX, cpY, toX, toY) +{ var xa, ya, @@ -373,14 +411,16 @@ n = 20, points = []; - function getPt(n1 , n2, perc) { + function getPt(n1 , n2, perc) + { var diff = n2 - n1; return n1 + ( diff * perc ); } var j = 0; - for (var i = 0; i <= n; i++ ) { + for (var i = 0; i <= n; i++ ) + { j = i / n; // The Green Line @@ -406,7 +446,8 @@ * @param graphicsData {Graphics} The graphics object to draw * @param webGLData {object} */ -WebGLGraphics.buildCircle = function (graphicsData, webGLData) { +WebGLGraphics.buildCircle = function (graphicsData, webGLData) +{ // need to convert points to a nice regular data var circleData = graphicsData.shape; var x = circleData.x; @@ -415,11 +456,13 @@ var height; // TODO - bit hacky?? - if (graphicsData.type === CONST.SHAPES.CIRC) { + if (graphicsData.type === CONST.SHAPES.CIRC) + { width = circleData.radius; height = circleData.radius; } - else { + else + { width = circleData.width; height = circleData.height; } @@ -429,7 +472,8 @@ var i = 0; - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -444,7 +488,8 @@ indices.push(vecPos); - for (i = 0; i < totalSegs + 1 ; i++) { + for (i = 0; i < totalSegs + 1 ; i++) + { verts.push(x,y, r, g, b, alpha); verts.push(x + Math.sin(seg * i) * width, @@ -457,12 +502,14 @@ indices.push(vecPos-1); } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = []; - for (i = 0; i < totalSegs + 1; i++) { + for (i = 0; i < totalSegs + 1; i++) + { graphicsData.points.push(x + Math.sin(seg * i) * width, y + Math.cos(seg * i) * height); } @@ -481,18 +528,22 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildLine = function (graphicsData, webGLData) { +WebGLGraphics.buildLine = function (graphicsData, webGLData) +{ // TODO OPTIMISE! var i = 0; var points = graphicsData.points; - if (points.length === 0) { + if (points.length === 0) + { return; } // if the line width is an odd number add 0.5 to align to a whole pixel - if (graphicsData.lineWidth%2) { - for (i = 0; i < points.length; i++) { + if (graphicsData.lineWidth%2) + { + for (i = 0; i < points.length; i++) + { points[i] += 0.5; } } @@ -502,7 +553,8 @@ var lastPoint = new math.Point(points[points.length - 2], points[points.length - 1]); // if the first point is the last point - gonna have issues :) - if (firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) { + if (firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) + { // need to clone as we are going to slightly modify the shape.. points = points.slice(); @@ -562,7 +614,8 @@ verts.push(p1x + perpx , p1y + perpy, r, g, b, alpha); - for (i = 1; i < length-1; i++) { + for (i = 1; i < length-1; i++) + { p1x = points[(i-1)*2]; p1y = points[(i-1)*2 + 1]; @@ -599,7 +652,8 @@ denom = a1*b2 - a2*b1; - if (Math.abs(denom) < 0.1 ) { + if (Math.abs(denom) < 0.1 ) + { denom+=10.1; verts.push(p2x - perpx , p2y - perpy, @@ -618,7 +672,8 @@ pdist = (px -p2x) * (px -p2x) + (py -p2y) + (py -p2y); - if (pdist > 140 * 140) { + if (pdist > 140 * 140) + { perp3x = perpx - perp2x; perp3y = perpy - perp2y; @@ -639,7 +694,8 @@ indexCount++; } - else { + else + { verts.push(px , py); verts.push(r, g, b, alpha); @@ -672,7 +728,8 @@ indices.push(indexStart); - for (i = 0; i < indexCount; i++) { + for (i = 0; i < indexCount; i++) + { indices.push(indexStart++); } @@ -687,11 +744,13 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildComplexPoly = function (graphicsData, webGLData) { +WebGLGraphics.buildComplexPoly = function (graphicsData, webGLData) +{ //TODO - no need to copy this as it gets turned into a FLoat32Array anyways.. var points = graphicsData.points.slice(); - if (points.length < 6) { + if (points.length < 6) + { return; } @@ -711,7 +770,8 @@ var x,y; // get size.. - for (var i = 0; i < points.length; i+=2) { + for (var i = 0; i < points.length; i+=2) + { x = points[i]; y = points[i+1]; @@ -732,7 +792,8 @@ //TODO - this aint needed! var length = points.length / 2; - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { indices.push( i ); } @@ -746,10 +807,12 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildPoly = function (graphicsData, webGLData) { +WebGLGraphics.buildPoly = function (graphicsData, webGLData) +{ var points = graphicsData.points; - if (points.length < 6) { + if (points.length < 6) + { return; } // get first and last point.. figure out the middle! @@ -767,7 +830,8 @@ var triangles = utils.PolyK.Triangulate(points); - if (!triangles) { + if (!triangles) + { return false; } @@ -775,7 +839,8 @@ var i = 0; - for (i = 0; i < triangles.length; i+=3) { + for (i = 0; i < triangles.length; i+=3) + { indices.push(triangles[i] + vertPos); indices.push(triangles[i] + vertPos); indices.push(triangles[i+1] + vertPos); @@ -783,7 +848,8 @@ indices.push(triangles[i+2] + vertPos); } - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { verts.push(points[i * 2], points[i * 2 + 1], r, g, b, alpha); } diff --git a/src/core/renderers/webgl/utils/WebGLGraphicsData.js b/src/core/renderers/webgl/utils/WebGLGraphicsData.js index c56d05e..c739ba7 100644 --- a/src/core/renderers/webgl/utils/WebGLGraphicsData.js +++ b/src/core/renderers/webgl/utils/WebGLGraphicsData.js @@ -2,7 +2,8 @@ * @class * @private */ -function WebGLGraphicsData(gl) { +function WebGLGraphicsData(gl) +{ this.gl = gl; //TODO does this need to be split before uploding?? @@ -22,7 +23,8 @@ /** * */ -WebGLGraphicsData.prototype.reset = function () { +WebGLGraphicsData.prototype.reset = function () +{ this.points.length = 0; this.indices.length = 0; }; @@ -30,7 +32,8 @@ /** * */ -WebGLGraphicsData.prototype.upload = function () { +WebGLGraphicsData.prototype.upload = function () +{ var gl = this.gl; // this.lastIndex = graphics.graphicsData.length; diff --git a/src/core/renderers/webgl/utils/WebGLSpriteBatch.js b/src/core/renderers/webgl/utils/WebGLSpriteBatch.js index 96eaa52..55befbb 100644 --- a/src/core/renderers/webgl/utils/WebGLSpriteBatch.js +++ b/src/core/renderers/webgl/utils/WebGLSpriteBatch.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this sprite batch works for. */ -function WebGLSpriteBatch(renderer) { +function WebGLSpriteBatch(renderer) +{ /** * * @@ -88,7 +89,8 @@ */ this.lastIndexCount = 0; - for (var i=0, j=0; i < numIndices; i += 6, j += 4) { + 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; @@ -162,7 +164,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.setupContext(); }); } @@ -173,7 +176,8 @@ /** * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLSpriteBatch.prototype.setupContext = function () { +WebGLSpriteBatch.prototype.setupContext = function () +{ var gl = this.renderer.gl; // setup default shader @@ -198,7 +202,8 @@ /** * */ -WebGLSpriteBatch.prototype.begin = function () { +WebGLSpriteBatch.prototype.begin = function () +{ // this.shader = this.renderer.shaderManager.defaultShader; this.start(); @@ -206,19 +211,22 @@ /** */ -WebGLSpriteBatch.prototype.end = function () { +WebGLSpriteBatch.prototype.end = function () +{ this.flush(); }; /** * @param sprite {Sprite} the sprite to render when using this spritebatch */ -WebGLSpriteBatch.prototype.render = function (sprite) { +WebGLSpriteBatch.prototype.render = function (sprite) +{ var texture = sprite.texture; //TODO set blend modes.. // check texture.. - if (this.currentBatchSize >= this.size) { + if (this.currentBatchSize >= this.size) + { this.flush(); this.currentBaseTexture = texture.baseTexture; } @@ -227,7 +235,8 @@ var uvs = texture._uvs; // if the uvs have not updated then no point rendering just yet! - if (!uvs) { + if (!uvs) + { return; } @@ -237,7 +246,8 @@ var w0, w1, h0, h1; - if (texture.trim) { + 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; @@ -248,7 +258,8 @@ h0 = h1 + texture.crop.height; } - else { + else + { w0 = (texture.frame.width ) * (1-aX); w1 = (texture.frame.width ) * -aX; @@ -272,7 +283,8 @@ var colors = this.colors; var positions = this.positions; - if (this.renderer.roundPixels) { + if (this.renderer.roundPixels) + { // xy positions[index] = a * w1 + c * h1 + tx | 0; positions[index+1] = d * h1 + b * w1 + ty | 0; @@ -289,7 +301,8 @@ positions[index+15] = a * w1 + c * h0 + tx | 0; positions[index+16] = d * h0 + b * w1 + ty | 0; } - else { + else + { // xy positions[index] = a * w1 + c * h1 + tx; positions[index+1] = d * h1 + b * w1 + ty; @@ -338,11 +351,13 @@ * * @param sprite {TilingSprite} the tilingSprite to render */ -WebGLSpriteBatch.prototype.renderTilingSprite = function (tilingSprite) { +WebGLSpriteBatch.prototype.renderTilingSprite = function (tilingSprite) +{ var texture = tilingSprite.tilingTexture; // check texture.. - if (this.currentBatchSize >= this.size) { + if (this.currentBatchSize >= this.size) + { //return; this.flush(); this.currentBaseTexture = texture.baseTexture; @@ -351,7 +366,8 @@ // set the textures uvs temporarily // TODO create a separate texture so that we can tile part of a texture - if (!tilingSprite._uvs) { + if (!tilingSprite._uvs) + { tilingSprite._uvs = new TextureUvs(); } @@ -454,16 +470,19 @@ * Renders the content and empties the current batch. * */ -WebGLSpriteBatch.prototype.flush = function () { +WebGLSpriteBatch.prototype.flush = function () +{ // If the batch is length 0 then return as there is nothing to draw - if (this.currentBatchSize === 0) { + if (this.currentBatchSize === 0) + { return; } var gl = this.renderer.gl; var shader; - if (this.dirty) { + if (this.dirty) + { this.dirty = false; // bind the main texture gl.activeTexture(gl.TEXTURE0); @@ -482,10 +501,12 @@ } // upload the verts to the buffer - if (this.currentBatchSize > ( this.size * 0.5 ) ) { + if (this.currentBatchSize > ( this.size * 0.5 ) ) + { gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); } - else { + else + { var view = this.positions.subarray(0, this.currentBatchSize * this.vertByteSize); gl.bufferSubData(gl.ARRAY_BUFFER, 0, view); } @@ -502,7 +523,8 @@ var shaderSwap = false; var sprite; - for (var i = 0, j = this.currentBatchSize; i < j; i++) { + for (var i = 0, j = this.currentBatchSize; i < j; i++) + { sprite = this.sprites[i]; @@ -513,24 +535,28 @@ blendSwap = currentBlendMode !== nextBlendMode; shaderSwap = currentShader !== nextShader; // should I use uuidS??? - if (currentBaseTexture !== nextTexture || blendSwap || shaderSwap) { + if (currentBaseTexture !== nextTexture || blendSwap || shaderSwap) + { this.renderBatch(currentBaseTexture, batchSize, start); start = i; batchSize = 0; currentBaseTexture = nextTexture; - if (blendSwap) { + if (blendSwap) + { currentBlendMode = nextBlendMode; this.renderer.blendModeManager.setBlendMode( currentBlendMode ); } - if (shaderSwap) { + if (shaderSwap) + { currentShader = nextShader; shader = currentShader.shaders ? currentShader.shaders[gl.id] : currentShader; - if (!shader) { + if (!shader) + { shader = new Shader(gl, null, currentShader.fragmentSrc, currentShader.uniforms); currentShader.shaders[gl.id] = shader; } @@ -538,7 +564,8 @@ // set shader function??? this.renderer.shaderManager.setShader(shader); - if (shader.dirty) { + if (shader.dirty) + { shader.syncUniforms(); } @@ -569,17 +596,21 @@ * @param size {number} * @param startIndex {number} */ -WebGLSpriteBatch.prototype.renderBatch = function (texture, size, startIndex) { - if (size === 0) { +WebGLSpriteBatch.prototype.renderBatch = function (texture, size, startIndex) +{ + if (size === 0) + { return; } var gl = this.renderer.gl; - if (!texture._glTextures[gl.id]) { + if (!texture._glTextures[gl.id]) + { this.renderer.updateTexture(texture); } - else { + else + { // bind the current texture gl.bindTexture(gl.TEXTURE_2D, texture._glTextures[gl.id]); } @@ -594,7 +625,8 @@ /** * */ -WebGLSpriteBatch.prototype.stop = function () { +WebGLSpriteBatch.prototype.stop = function () +{ this.flush(); this.dirty = true; }; @@ -602,7 +634,8 @@ /** * */ -WebGLSpriteBatch.prototype.start = function () { +WebGLSpriteBatch.prototype.start = function () +{ this.dirty = true; }; @@ -610,7 +643,8 @@ * Destroys the SpriteBatch. * */ -WebGLSpriteBatch.prototype.destroy = function () { +WebGLSpriteBatch.prototype.destroy = function () +{ this.renderer.gl.deleteBuffer(this.vertexBuffer); this.renderer.gl.deleteBuffer(this.indexBuffer); diff --git a/src/core/textures/BaseTexture.js b/src/core/textures/BaseTexture.js index 2bf77d4..513d358 100644 --- a/src/core/textures/BaseTexture.js +++ b/src/core/textures/BaseTexture.js @@ -10,7 +10,8 @@ * @param source {Image|Canvas} the source object of the texture. * @param [scaleMode=scaleModes.DEFAULT] {number} See {@link scaleModes} for possible values */ -function BaseTexture(source, scaleMode) { +function BaseTexture(source, scaleMode) +{ this.uuid = utils.uuid(); /** @@ -123,7 +124,8 @@ this._needsUpdate = false; // if no source passed don't try to load - if (source) { + if (source) + { this.loadSource(source); } @@ -149,13 +151,16 @@ Object.defineProperties(BaseTexture.prototype, { needsUpdate: { - get: function () { + get: function () + { return this._needsUpdate; }, - set: function (val) { + set: function (val) + { this._needsUpdate = val; - if (val) { + if (val) + { this.emit('update', this); } } @@ -171,9 +176,11 @@ * * The logic state after calling `loadSource` directly or indirectly (eg. `fromImage`, `new BaseTexture`) is: * - * if (texture.hasLoaded) { + * if (texture.hasLoaded) + { * // texture ready for use - * } else if (texture.isLoading) { + * } else if (texture.isLoading) + { * // listen to 'loaded' and/or 'error' events on texture * } else { * // not loading, not going to load UNLESS the source is reloaded @@ -183,12 +190,14 @@ * @protected * @param source {Image|Canvas} the source object of the texture. */ -BaseTexture.prototype.loadSource = function (source) { +BaseTexture.prototype.loadSource = function (source) +{ var wasLoading = this.isLoading; this.hasLoaded = false; this.isLoading = false; - if (wasLoading && this.source) { + if (wasLoading && this.source) + { this.source.onload = null; this.source.onerror = null; } @@ -196,20 +205,24 @@ this.source = source; // Apply source if loaded. Otherwise setup appropriate loading monitors. - if ((this.source.complete || this.source.getContext) && this.source.width && this.source.height) { + if ((this.source.complete || this.source.getContext) && this.source.width && this.source.height) + { this._sourceLoaded(); } - else if(!source.getContext) { + else if(!source.getContext) + { // Image fail / not ready this.isLoading = true; var scope = this; - source.onload = function () { + source.onload = function () + { source.onload = null; source.onerror = null; - if(!scope.isLoading) { + if(!scope.isLoading) + { return; } @@ -219,11 +232,13 @@ scope.emit('loaded', scope); }; - source.onerror = function () { + source.onerror = function () + { source.onload = null; source.onerror = null; - if(!scope.isLoading) { + if(!scope.isLoading) + { return; } @@ -234,24 +249,29 @@ // Per http://www.w3.org/TR/html5/embedded-content-0.html#the-img-element // "The value of `complete` can thus change while a script is executing." // So complete needs to be re-checked after the callbacks have been added.. - if (source.complete) { + if (source.complete) + { this.isLoading = false; // ..and if we're complete now, no need for callbacks source.onload = null; source.onerror = null; - if (source.width && source.height) { + if (source.width && source.height) + { this._sourceLoaded(); // If any previous subscribers possible - if (wasLoading) { + if (wasLoading) + { this.emit('loaded', this); } } - else { + else + { // If any previous subscribers possible - if (wasLoading) { + if (wasLoading) + { this.emit('error', this); } } @@ -265,7 +285,8 @@ * * @private */ -BaseTexture.prototype._sourceLoaded = function () { +BaseTexture.prototype._sourceLoaded = function () +{ this.hasLoaded = true; this.width = this.source.naturalWidth || this.source.width; @@ -278,16 +299,20 @@ * Destroys this base texture * */ -BaseTexture.prototype.destroy = function () { - if (this.imageUrl) { +BaseTexture.prototype.destroy = function () +{ + if (this.imageUrl) + { delete utils.BaseTextureCache[this.imageUrl]; delete utils.TextureCache[this.imageUrl]; this.imageUrl = null; - if (!navigator.isCocoonJS) { + if (!navigator.isCocoonJS) + { this.source.src = ''; } } - else if (this.source && this.source._pixiId) { + else if (this.source && this.source._pixiId) + { delete utils.BaseTextureCache[this.source._pixiId]; } this.source = null; @@ -301,7 +326,8 @@ * memory again. * */ -BaseTexture.prototype.dispose = function () { +BaseTexture.prototype.dispose = function () +{ this.emit('dispose', this); }; @@ -311,7 +337,8 @@ * * @param newSrc {string} the path of the image */ -BaseTexture.prototype.updateSourceImage = function (newSrc) { +BaseTexture.prototype.updateSourceImage = function (newSrc) +{ this.source.src = newSrc; this.loadSource(this.source); }; @@ -326,18 +353,22 @@ * @param [scaleMode=scaleModes.DEFAULT] {number} See {@link scaleModes} for possible values * @return BaseTexture */ -BaseTexture.fromImage = function (imageUrl, crossorigin, scaleMode) { +BaseTexture.fromImage = function (imageUrl, crossorigin, scaleMode) +{ var baseTexture = utils.BaseTextureCache[imageUrl]; - if (crossorigin === undefined && imageUrl.indexOf('data:') !== 0) { + if (crossorigin === undefined && imageUrl.indexOf('data:') !== 0) + { crossorigin = true; } - if (!baseTexture) { + if (!baseTexture) + { // new Image() breaks tex loading in some versions of Chrome. // See https://code.google.com/p/chromium/issues/detail?id=238071 var image = new Image();//document.createElement('img'); - if (crossorigin) { + if (crossorigin) + { image.crossOrigin = ''; } @@ -347,7 +378,8 @@ utils.BaseTextureCache[imageUrl] = baseTexture; // if there is an @2x at the end of the url we are going to assume its a highres image - if ( imageUrl.indexOf(CONST.RETINA_PREFIX + '.') !== -1) { + if ( imageUrl.indexOf(CONST.RETINA_PREFIX + '.') !== -1) + { baseTexture.resolution = 2; } } @@ -363,14 +395,17 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return BaseTexture */ -BaseTexture.fromCanvas = function (canvas, scaleMode) { - if (!canvas._pixiId) { +BaseTexture.fromCanvas = function (canvas, scaleMode) +{ + if (!canvas._pixiId) + { canvas._pixiId = 'canvas_' + utils.uuid(); } var baseTexture = utils.BaseTextureCache[canvas._pixiId]; - if (!baseTexture) { + if (!baseTexture) + { baseTexture = new BaseTexture(canvas, scaleMode); utils.BaseTextureCache[canvas._pixiId] = baseTexture; } diff --git a/src/core/textures/RenderTexture.js b/src/core/textures/RenderTexture.js index 6dad20f..53ae796 100644 --- a/src/core/textures/RenderTexture.js +++ b/src/core/textures/RenderTexture.js @@ -46,8 +46,10 @@ * @param [scaleMode] {number} See {@link scaleModes} for possible values * @param [resolution=1] {number} The resolution of the texture being generated */ -function RenderTexture(renderer, width, height, scaleMode, resolution) { - if (!renderer) { +function RenderTexture(renderer, width, height, scaleMode, resolution) +{ + if (!renderer) + { throw new Error('Unable to create RenderTexture, you must pass a renderer into the constructor.'); } @@ -133,7 +135,8 @@ */ this.renderer = renderer; - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { var gl = this.renderer.gl; this.textureBuffer = new FilterTexture(gl, this.width * this.resolution, this.height * this.resolution, this.baseTexture.scaleMode); @@ -142,7 +145,8 @@ this.render = this.renderWebGL; this.projection = new math.Point(this.width*0.5, -this.height*0.5); } - else { + else + { this.render = this.renderCanvas; this.textureBuffer = new CanvasBuffer(this.width* this.resolution, this.height* this.resolution); this.baseTexture.source = this.textureBuffer.canvas; @@ -167,8 +171,10 @@ * @param height {number} The height to resize to. * @param updateBase {boolean} Should the baseTexture.width and height values be resized as well? */ -RenderTexture.prototype.resize = function (width, height, updateBase) { - if (width === this.width && height === this.height) { +RenderTexture.prototype.resize = function (width, height, updateBase) +{ + if (width === this.width && height === this.height) + { return; } @@ -177,17 +183,20 @@ this.width = this.frame.width = this.crop.width = width; this.height = this.frame.height = this.crop.height = height; - if (updateBase) { + if (updateBase) + { this.baseTexture.width = this.width; this.baseTexture.height = this.height; } - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { this.projection.x = this.width / 2; this.projection.y = -this.height / 2; } - if (!this.valid) { + if (!this.valid) + { return; } @@ -198,12 +207,15 @@ * Clears the RenderTexture. * */ -RenderTexture.prototype.clear = function () { - if (!this.valid) { +RenderTexture.prototype.clear = function () +{ + if (!this.valid) + { return; } - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { this.renderer.gl.bindFramebuffer(this.renderer.gl.FRAMEBUFFER, this.textureBuffer.frameBuffer); } @@ -220,19 +232,23 @@ * @param [restoreWorldTransform=true] {boolean} If true the displayObject's worldTransform/worldAlpha and all children * transformations will be restored. Not restoring this information will be a little faster. */ -RenderTexture.prototype.renderWebGL = function (displayObject, matrix, clear, restoreWorldTransform) { - if (!this.valid) { +RenderTexture.prototype.renderWebGL = function (displayObject, matrix, clear, restoreWorldTransform) +{ + if (!this.valid) + { return; } - if (typeof restoreWorldTransform === 'undefined') { + if (typeof restoreWorldTransform === 'undefined') + { restoreWorldTransform = true; } var tempAlpha, tempTransform; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { tempAlpha = displayObject.worldAlpha; tempTransform = displayObject.worldTransform.toArray(); } @@ -245,7 +261,8 @@ wt.identity(); wt.translate(0, this.projection.y * 2); - if (matrix) { + if (matrix) + { wt.append(matrix); } @@ -258,7 +275,8 @@ var children = displayObject.children; var i, j; - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } @@ -269,7 +287,8 @@ gl.bindFramebuffer(gl.FRAMEBUFFER, this.textureBuffer.frameBuffer ); - if (clear) { + if (clear) + { this.textureBuffer.clear(); } @@ -279,11 +298,13 @@ this.renderer.spriteBatch.dirty = true; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { displayObject.worldAlpha = tempAlpha; displayObject.worldTransform.fromArray(tempTransform); - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } } @@ -300,26 +321,31 @@ * @param [restoreWorldTransform=true] {boolean} If true the displayObject's worldTransform/worldAlpha and all children * transformations will be restored. Not restoring this information will be a little faster. */ -RenderTexture.prototype.renderCanvas = function (displayObject, matrix, clear, restoreWorldTransform) { - if (!this.valid) { +RenderTexture.prototype.renderCanvas = function (displayObject, matrix, clear, restoreWorldTransform) +{ + if (!this.valid) + { return; } - if (typeof restoreWorldTransform === 'undefined') { + if (typeof restoreWorldTransform === 'undefined') + { restoreWorldTransform = true; } var tempAlpha, tempTransform; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { tempAlpha = displayObject.worldAlpha; tempTransform = displayObject.worldTransform.toArray(); } var wt = displayObject.worldTransform; wt.identity(); - if (matrix) { + if (matrix) + { wt.append(matrix); } @@ -330,11 +356,13 @@ var children = displayObject.children; var i, j; - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } - if (clear) { + if (clear) + { this.textureBuffer.clear(); } @@ -348,11 +376,13 @@ this.renderer.resolution = realResolution; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { displayObject.worldAlpha = tempAlpha; displayObject.worldTransform.fromArray(tempTransform); - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } } @@ -363,7 +393,8 @@ * * @return {Image} */ -RenderTexture.prototype.getImage = function () { +RenderTexture.prototype.getImage = function () +{ var image = new Image(); image.src = this.getBase64(); return image; @@ -374,7 +405,8 @@ * * @return {string} A base64 encoded string of the texture. */ -RenderTexture.prototype.getBase64 = function () { +RenderTexture.prototype.getBase64 = function () +{ return this.getCanvas().toDataURL(); }; @@ -383,8 +415,10 @@ * * @return {HTMLCanvasElement} A Canvas element with the texture rendered on. */ -RenderTexture.prototype.getCanvas = function () { - if (this.renderer.type === CONST.WEBGL_RENDERER) { +RenderTexture.prototype.getCanvas = function () +{ + if (this.renderer.type === CONST.WEBGL_RENDERER) + { var gl = this.renderer.gl; var width = this.textureBuffer.width; var height = this.textureBuffer.height; @@ -403,7 +437,8 @@ return tempCanvas.canvas; } - else { + else + { return this.textureBuffer.canvas; } }; diff --git a/src/core/textures/Texture.js b/src/core/textures/Texture.js index 3c65909..e97f0aa 100644 --- a/src/core/textures/Texture.js +++ b/src/core/textures/Texture.js @@ -17,7 +17,8 @@ * @param [crop] {Rectangle} The area of original texture * @param [trim] {Rectangle} Trimmed texture rectangle */ -function Texture(baseTexture, frame, crop, trim) { +function Texture(baseTexture, frame, crop, trim) +{ /** * Does this Texture have any frame data assigned to it? * @@ -25,12 +26,14 @@ */ this.noFrame = false; - if (!frame) { + if (!frame) + { this.noFrame = true; frame = new math.Rectangle(0, 0, 1, 1); } - if (baseTexture instanceof Texture) { + if (baseTexture instanceof Texture) + { baseTexture = baseTexture.baseTexture; } @@ -100,13 +103,16 @@ */ this.crop = crop || new math.Rectangle(0, 0, 1, 1); - if (baseTexture.hasLoaded) { - if (this.noFrame) { + if (baseTexture.hasLoaded) + { + if (this.noFrame) + { frame = new math.Rectangle(0, 0, baseTexture.width, baseTexture.height); } this.frame = frame; } - else { + else + { baseTexture.addEventListener('loaded', this.onBaseTextureLoaded.bind(this)); } } @@ -118,19 +124,23 @@ Object.defineProperties(Texture.prototype, { needsUpdate: { - get: function () { + get: function () + { return this.baseTexture.needsUpdate; }, - set: function (val) { + set: function (val) + { this.baseTexture.needsUpdate = val; } }, frame: { - get: function () { + get: function () + { return this._frame; }, - set: function (frame) { + set: function (frame) + { this._frame = frame; this.noFrame = false; @@ -143,20 +153,23 @@ 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 (!this.trim && (frame.x + frame.width > this.baseTexture.width || frame.y + frame.height > this.baseTexture.height)) + { throw new Error('Texture Error: frame does not fit inside the base Texture dimensions ' + this); } this.valid = frame && frame.width && frame.height && this.baseTexture.source && this.baseTexture.hasLoaded; - if (this.trim) { + 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) { + if (this.valid) + { this._updateUvs(); } } @@ -168,11 +181,13 @@ * * @private */ -Texture.prototype.onBaseTextureLoaded = function () { +Texture.prototype.onBaseTextureLoaded = function () +{ var baseTexture = this.baseTexture; baseTexture.removeEventListener('loaded', this.onLoaded); - if (this.noFrame) { + if (this.noFrame) + { this.frame = new math.Rectangle(0, 0, baseTexture.width, baseTexture.height); } @@ -184,8 +199,10 @@ * * @param destroyBase {boolean} Whether to destroy the base texture as well */ -Texture.prototype.destroy = function (destroyBase) { - if (destroyBase) { +Texture.prototype.destroy = function (destroyBase) +{ + if (destroyBase) + { this.baseTexture.destroy(); } @@ -197,8 +214,10 @@ * * @private */ -Texture.prototype._updateUvs = function () { - if (!this._uvs) { +Texture.prototype._updateUvs = function () +{ + if (!this._uvs) + { this._uvs = new TextureUvs(); } @@ -229,10 +248,12 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return Texture */ -Texture.fromImage = function (imageUrl, crossorigin, scaleMode) { +Texture.fromImage = function (imageUrl, crossorigin, scaleMode) +{ var texture = utils.TextureCache[imageUrl]; - if (!texture) { + if (!texture) + { texture = new Texture(BaseTexture.fromImage(imageUrl, crossorigin, scaleMode)); utils.TextureCache[imageUrl] = texture; } @@ -248,9 +269,11 @@ * @param frameId {string} The frame id of the texture * @return Texture */ -Texture.fromFrame = function (frameId) { +Texture.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache '); } return texture; @@ -264,7 +287,8 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return {Texture} */ -Texture.fromCanvas = function (canvas, scaleMode) { +Texture.fromCanvas = function (canvas, scaleMode) +{ return new Texture(BaseTexture.fromCanvas(canvas, scaleMode)); }; @@ -276,7 +300,8 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return {Texture} A Texture */ -Texture.fromVideo = function (video, scaleMode) { +Texture.fromVideo = function (video, scaleMode) +{ return new Texture(VideoBaseTexture.baseTextureFromVideo(video, scaleMode)); }; @@ -287,7 +312,8 @@ * @param texture {Texture} The Texture to add to the cache. * @param id {string} The id that the texture will be stored against. */ -Texture.addTextureToCache = function (texture, id) { +Texture.addTextureToCache = function (texture, id) +{ utils.TextureCache[id] = texture; }; @@ -298,7 +324,8 @@ * @param id {string} The id of the texture to be removed * @return {Texture} The texture that was removed */ -Texture.removeTextureFromCache = function (id) { +Texture.removeTextureFromCache = function (id) +{ var texture = utils.TextureCache[id]; delete utils.TextureCache[id]; diff --git a/src/core/textures/TextureUvs.js b/src/core/textures/TextureUvs.js index b9bbb58..5424d52 100644 --- a/src/core/textures/TextureUvs.js +++ b/src/core/textures/TextureUvs.js @@ -1,4 +1,5 @@ -function TextureUvs() { +function TextureUvs() +{ this.x0 = 0; this.y0 = 0; diff --git a/src/core/textures/VideoBaseTexture.js b/src/core/textures/VideoBaseTexture.js index e3e0c5a..1a826a9 100644 --- a/src/core/textures/VideoBaseTexture.js +++ b/src/core/textures/VideoBaseTexture.js @@ -12,15 +12,18 @@ * @param source {HTMLVideoElement} * @param [scaleMode] {number} See {@link scaleModes} for possible values */ -function VideoBaseTexture(source, scaleMode) { - if (!source){ +function VideoBaseTexture(source, scaleMode) +{ + if (!source) + { throw new Error('No video source element specified.'); } // hook in here to check if video is already available. // BaseTexture looks for a source.complete boolean, plus width & height. - if ((source.readyState === source.HAVE_ENOUGH_DATA || source.readyState === source.HAVE_FUTURE_DATA) && source.width && source.height) { + if ((source.readyState === source.HAVE_ENOUGH_DATA || source.readyState === source.HAVE_FUTURE_DATA) && source.width && source.height) + { source.complete = true; } @@ -31,7 +34,8 @@ this._boundOnUpdate = this._onUpdate.bind(this); this._boundOnCanPlay = this._onCanPlay.bind(this); - if (!source.complete) { + if (!source.complete) + { source.addEventListener('canplay', this._boundOnCanPlay); source.addEventListener('canplaythrough', this._boundOnCanPlay); @@ -47,28 +51,35 @@ VideoBaseTexture.prototype.constructor = VideoBaseTexture; module.exports = VideoBaseTexture; -VideoBaseTexture.prototype._onUpdate = function () { - if (this.autoUpdate) { +VideoBaseTexture.prototype._onUpdate = function () +{ + if (this.autoUpdate) + { window.requestAnimationFrame(this._boundOnUpdate); this.needsUpdate = true; } }; -VideoBaseTexture.prototype._onPlayStart = function () { - if (!this.autoUpdate) { +VideoBaseTexture.prototype._onPlayStart = function () +{ + if (!this.autoUpdate) + { window.requestAnimationFrame(this._boundOnUpdate); this.autoUpdate = true; } }; -VideoBaseTexture.prototype._onPlayStop = function () { +VideoBaseTexture.prototype._onPlayStop = function () +{ this.autoUpdate = false; }; -VideoBaseTexture.prototype._onCanPlay = function () { +VideoBaseTexture.prototype._onCanPlay = function () +{ this.hasLoaded = true; - if (this.source) { + if (this.source) + { this.source.removeEventListener('canplay', this._boundOnCanPlay); this.source.removeEventListener('canplaythrough', this._boundOnCanPlay); @@ -78,15 +89,18 @@ this.source.play(); // prevent multiple loaded dispatches.. - if(!this.__loaded){ + if(!this.__loaded) + { this.__loaded = true; this.emit('loaded', this); } } }; -VideoBaseTexture.prototype.destroy = function () { - if (this.source && this.source._pixiId) { +VideoBaseTexture.prototype.destroy = function () +{ + if (this.source && this.source._pixiId) + { utils.BaseTextureCache[ this.source._pixiId ] = null; delete utils.BaseTextureCache[ this.source._pixiId ]; @@ -105,14 +119,17 @@ * @param scaleMode {number} See {@link scaleModes} for possible values * @return {VideoBaseTexture} */ -VideoBaseTexture.fromVideo = function (video, scaleMode) { - if (!video._pixiId) { +VideoBaseTexture.fromVideo = function (video, scaleMode) +{ + if (!video._pixiId) + { video._pixiId = 'video_' + utils.uuid(); } var baseTexture = utils.BaseTextureCache[video._pixiId]; - if (!baseTexture) { + if (!baseTexture) + { baseTexture = new VideoBaseTexture(video, scaleMode); utils.BaseTextureCache[ video._pixiId ] = baseTexture; } @@ -147,17 +164,21 @@ * @param scaleMode {number} See {@link scaleModes} for possible values * @return {VideoBaseTexture} */ -VideoBaseTexture.fromUrl = function (videoSrc, scaleMode) { +VideoBaseTexture.fromUrl = function (videoSrc, scaleMode) +{ var video = document.createElement('video'); // array of objects or strings - if (Array.isArray(videoSrc)) { - for (var i = 0; i < videoSrc.length; ++i) { + if (Array.isArray(videoSrc)) + { + for (var i = 0; i < videoSrc.length; ++i) + { video.appendChild(createSource(videoSrc.src || videoSrc, videoSrc.mime)); } } // single object or string - else { + else + { video.appendChild(createSource(videoSrc.src || videoSrc, videoSrc.mime)); } @@ -169,8 +190,10 @@ VideoBaseTexture.fromUrls = VideoBaseTexture.fromUrl; -function createSource(path, type) { - if (!type) { +function createSource(path, type) +{ + if (!type) + { type = 'video/' + path.substr(path.lastIndexOf('.') + 1); } diff --git a/src/core/utils/EventData.js b/src/core/utils/EventData.js index 5d55a22..8cdf701 100644 --- a/src/core/utils/EventData.js +++ b/src/core/utils/EventData.js @@ -7,7 +7,8 @@ * @param name {string} The string name of the event that was triggered * @param data {object} Arbitrary event data to pass along */ -function EventData(target, name, data) { +function EventData(target, name, data) +{ // for duck typing in the ".on()" function this.__isEventObject = true; @@ -71,7 +72,8 @@ * Stops the propagation of events up the scene graph (prevents bubbling). * */ -EventData.prototype.stopPropagation = function stopPropagation() { +EventData.prototype.stopPropagation = function stopPropagation() +{ this.stopped = true; }; @@ -79,6 +81,7 @@ * Stops the propagation of events to sibling listeners (no longer calls any listeners). * */ -EventData.prototype.stopImmediatePropagation = function stopImmediatePropagation() { +EventData.prototype.stopImmediatePropagation = function stopImmediatePropagation() +{ this.stoppedImmediate = true; }; diff --git a/src/core/utils/EventTarget.js b/src/core/utils/EventTarget.js index 7ae8820..671a151 100644 --- a/src/core/utils/EventTarget.js +++ b/src/core/utils/EventTarget.js @@ -13,14 +13,16 @@ * var em = new MyEmitter(); * em.emit('eventName', 'some data', 'some more data', {}, null, ...); */ -function eventTarget(obj) { +function eventTarget(obj) +{ /** * Return a list of assigned event listeners. * * @param eventName {string} The events that should be listed. * @return {Array} An array of listener functions */ - obj.listeners = function listeners(eventName) { + obj.listeners = function listeners(eventName) + { this._listeners = this._listeners || {}; return this._listeners[eventName] ? this._listeners[eventName].slice() : []; @@ -33,22 +35,26 @@ * @param eventName {string} The name of the event. * @return {boolean} Indication if we've emitted an event. */ - obj.emit = obj.dispatchEvent = function emit(eventName, data) { + obj.emit = obj.dispatchEvent = function emit(eventName, data) + { this._listeners = this._listeners || {}; // fast return when there are no listeners - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return; } //backwards compat with old method ".emit({ type: 'something' })" - if (typeof eventName === 'object') { + if (typeof eventName === 'object') + { data = eventName; eventName = eventName.type; } //ensure we are using a real pixi event - if (!data || data.__isEventObject !== true) { + if (!data || data.__isEventObject !== true) + { data = new EventData(this, eventName, data); } @@ -58,23 +64,27 @@ fn = listeners[0], i; - for (i = 0; i < length; fn = listeners[++i]) { + for (i = 0; i < length; fn = listeners[++i]) + { //call the event listener fn.call(this, data); //if "stopImmediatePropagation" is called, stop calling sibling events - if (data.stoppedImmediate) { + if (data.stoppedImmediate) + { return this; } } //if "stopPropagation" is called then don't bubble the event - if (data.stopped) { + if (data.stopped) + { return this; } //bubble this event up the scene graph - if (this.parent && this.parent.emit) { + if (this.parent && this.parent.emit) + { this.parent.emit.call(this.parent, eventName, data); } @@ -88,7 +98,8 @@ * @param eventName {string} Name of the event. * @param callback {Functon} fn Callback function. */ - obj.on = obj.addEventListener = function on(eventName, fn) { + obj.on = obj.addEventListener = function on(eventName, fn) + { this._listeners = this._listeners || {}; (this._listeners[eventName] = this._listeners[eventName] || []) @@ -103,11 +114,13 @@ * @param eventName {string} Name of the event. * @param callback {Function} Callback function. */ - obj.once = function once(eventName, fn) { + obj.once = function once(eventName, fn) + { this._listeners = this._listeners || {}; var self = this; - function onceHandlerWrapper() { + function onceHandlerWrapper() + { fn.apply(self.off(eventName, onceHandlerWrapper), arguments); } onceHandlerWrapper._originalHandler = fn; @@ -122,23 +135,28 @@ * @param eventName {string} The event we want to remove. * @param callback {Function} The listener that we need to find. */ - obj.off = obj.removeEventListener = function off(eventName, fn) { + obj.off = obj.removeEventListener = function off(eventName, fn) + { this._listeners = this._listeners || {}; - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return this; } var list = this._listeners[eventName], i = fn ? list.length : 0; - while(i-- > 0) { - if (list[i] === fn || list[i]._originalHandler === fn) { + while(i-- > 0) + { + if (list[i] === fn || list[i]._originalHandler === fn) + { list.splice(i, 1); } } - if (list.length === 0) { + if (list.length === 0) + { delete this._listeners[eventName]; } @@ -150,10 +168,12 @@ * * @param eventName {string} The event you want to remove all listeners for. */ - obj.removeAllListeners = function removeAllListeners(eventName) { + obj.removeAllListeners = function removeAllListeners(eventName) + { this._listeners = this._listeners || {}; - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return this; } @@ -169,7 +189,8 @@ * * @param object {object} The obj to mix into */ - mixin: function mixin(obj) { + mixin: function mixin(obj) + { eventTarget(obj); } }; diff --git a/src/core/utils/PolyK.js b/src/core/utils/PolyK.js index 7325141..5e20c2b 100644 --- a/src/core/utils/PolyK.js +++ b/src/core/utils/PolyK.js @@ -47,7 +47,8 @@ * Triangulates shapes for webGL graphic fills. * */ -PolyK.Triangulate = function (p) { +PolyK.Triangulate = function (p) +{ var sign = true; var n = p.length >> 1; @@ -59,7 +60,8 @@ i = 0; var al = n; - while(al > 3) { + while(al > 3) + { var i0 = avl[(i+0)%al]; var i1 = avl[(i+1)%al]; var i2 = avl[(i+2)%al]; @@ -69,29 +71,35 @@ var cx = p[2*i2], cy = p[2*i2+1]; var earFound = false; - if (PolyK._convex(ax, ay, bx, by, cx, cy, sign)) { + if (PolyK._convex(ax, ay, bx, by, cx, cy, sign)) + { earFound = true; - for (var j = 0; j < al; j++) { + for (var j = 0; j < al; j++) + { var vi = avl[j]; if (vi === i0 || vi === i1 || vi === i2) continue; - if (PolyK._PointInTriangle(p[2*vi], p[2*vi+1], ax, ay, bx, by, cx, cy)) { + if (PolyK._PointInTriangle(p[2*vi], p[2*vi+1], ax, ay, bx, by, cx, cy)) + { earFound = false; break; } } } - if (earFound) { + if (earFound) + { tgs.push(i0, i1, i2); avl.splice((i+1)%al, 1); al--; i = 0; } - else if (i++ > 3*al) { + else if (i++ > 3*al) + { // need to flip flip reverse it! // reset! - if (sign) { + if (sign) + { tgs = []; avl = []; for (i = 0; i < n; i++) avl.push(i); @@ -101,7 +109,8 @@ sign = false; } - else { + else + { // window.console.log("PIXI Warning: shape too complex to fill"); return null; } @@ -126,7 +135,8 @@ * @private * @return {boolean} */ -PolyK._PointInTriangle = function (px, py, ax, ay, bx, by, cx, cy) { +PolyK._PointInTriangle = function (px, py, ax, ay, bx, by, cx, cy) +{ var v0x = cx-ax; var v0y = cy-ay; var v1x = bx-ax; @@ -154,6 +164,7 @@ * @private * @return {boolean} */ -PolyK._convex = function (ax, ay, bx, by, cx, cy, sign) { +PolyK._convex = function (ax, ay, bx, by, cx, cy, sign) +{ return ((ay-by)*(cx-bx) + (bx-ax)*(cy-by) >= 0) === sign; }; diff --git a/src/core/utils/index.js b/src/core/utils/index.js index ade9831..bfae7ae 100644 --- a/src/core/utils/index.js +++ b/src/core/utils/index.js @@ -16,7 +16,8 @@ * * @return {number} The next uuid to use. */ - uuid: function () { + uuid: function () + { return ++utils._uid; }, @@ -26,7 +27,8 @@ * @param hex {number} * @return {number[]} An array representing the [R, G, B] of the color. */ - hex2rgb: function (hex, out) { + hex2rgb: function (hex, out) + { out = out || []; out[0] = (hex >> 16 & 0xFF) / 255; @@ -42,7 +44,8 @@ * @param hex {number} * @return {string} The string color. */ - hex2string: function (hex) { + hex2string: function (hex) + { hex = hex.toString(16); hex = '000000'.substr(0, 6 - hex.length) + hex; @@ -55,7 +58,8 @@ * @param rgb {number[]} * @return {number} The color number */ - rgb2hex: function (rgb) { + rgb2hex: function (rgb) + { return ((rgb[0]*255 << 16) + (rgb[1]*255 << 8) + rgb[2]*255); }, @@ -64,8 +68,10 @@ * * @return {boolean} whether they are supported */ - canUseNewCanvasBlendModes: function () { - if (typeof document === 'undefined') { + canUseNewCanvasBlendModes: function () + { + if (typeof document === 'undefined') + { return false; } @@ -93,15 +99,19 @@ * @param number {number} * @return {number} the closest number that is a power of two */ - getNextPowerOfTwo: function (number) { + getNextPowerOfTwo: function (number) + { // see: http://en.wikipedia.org/wiki/Power_of_two#Fast_algorithm_to_check_if_a_positive_number_is_a_power_of_two - if (number > 0 && (number & (number - 1)) === 0) { + if (number > 0 && (number & (number - 1)) === 0) + { return number; } - else { + else + { var result = 1; - while (result < number) { + while (result < number) + { result <<= 1; } @@ -116,7 +126,8 @@ * @param height {number} * @return {boolean} */ - isPowerOfTwo: function (width, height) { + isPowerOfTwo: function (width, height) + { return (width > 0 && (width & (width - 1)) === 0 && height > 0 && (height & (height - 1)) === 0); }, @@ -130,12 +141,15 @@ * @constant * @static */ - sayHello: function (type) { - if (utils._saidHello) { + sayHello: function (type) + { + if (utils._saidHello) + { return; } - if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) { + if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) + { var args = [ '%c %c %c Pixi.js ' + CONST.VERSION + ' - ' + type + ' %c ' + ' %c ' + ' http://www.pixijs.com/ %c %c ♥%c♥%c♥ ', 'background: #ff66a5', @@ -151,7 +165,8 @@ console.log.apply(console, args); //jshint ignore:line } - else if (window.console) { + else if (window.console) + { console.log('Pixi.js ' + CONST.VERSION + ' - ' + type + ' - http://www.pixijs.com/'); //jshint ignore:line } @@ -166,15 +181,19 @@ * @class * @namespace PIXI */ - AjaxRequest: function () { + AjaxRequest: function () + { var activexmodes = ['Msxml2.XMLHTTP.6.0', 'Msxml2.XMLHTTP.3.0', 'Microsoft.XMLHTTP']; //activeX versions to check for in IE - if (window.ActiveXObject) { //Test for support for ActiveXObject in IE first (as XMLHttpRequest in IE7 is broken) - for (var i=0; i= this.textures.length) { + else if (round >= this.textures.length) + { this.gotoAndStop(this.textures.length - 1); - if (this.onComplete) { + if (this.onComplete) + { this.onComplete(); } } @@ -167,10 +182,12 @@ * @static * @param frames {string[]} the array of frames ids the movieclip will use as its texture frames */ -MovieClip.fromFrames = function (frames) { +MovieClip.fromFrames = function (frames) +{ var textures = []; - for (var i = 0; i < frames.length; ++i) { + for (var i = 0; i < frames.length; ++i) + { textures.push(new core.Texture.fromFrame(frames[i])); } @@ -183,10 +200,12 @@ * @static * @param images {string[]} the array of image urls the movieclip will use as its texture frames */ -MovieClip.fromImages = function (images) { +MovieClip.fromImages = function (images) +{ var textures = []; - for (var i = 0; i < images.length; ++i) { + for (var i = 0; i < images.length; ++i) + { textures.push(new core.Texture.fromImage(images[i])); } diff --git a/src/extras/Rope.js b/src/extras/Rope.js index c157ec4..9c87bc0 100644 --- a/src/extras/Rope.js +++ b/src/extras/Rope.js @@ -9,7 +9,8 @@ * @param {Array} points - An array of {Point}. * */ -function Rope(texture, points) { +function Rope(texture, points) +{ Strip.call(this, texture); this.points = points; @@ -31,10 +32,12 @@ * Refreshes * */ -Rope.prototype.refresh = function () { +Rope.prototype.refresh = function () +{ var points = this.points; - if (points.length < 1) { + if (points.length < 1) + { return; } @@ -59,20 +62,23 @@ var total = points.length, point, index, amount; - for (var i = 1; i < total; i++) { + for (var i = 1; i < total; i++) + { point = points[i]; index = i * 4; // time to do some smart drawing! amount = i / (total-1); - if (i%2) { + if (i%2) + { uvs[index] = amount; uvs[index+1] = 0; uvs[index+2] = amount; uvs[index+3] = 1; } - else { + else + { uvs[index] = amount; uvs[index+1] = 0; @@ -95,10 +101,12 @@ * * @private */ -Rope.prototype.updateTransform = function () { +Rope.prototype.updateTransform = function () +{ var points = this.points; - if (points.length < 1) { + if (points.length < 1) + { return; } @@ -113,14 +121,17 @@ var total = points.length, point, index, ratio, perpLength, num; - for (var i = 0; i < total; i++) { + for (var i = 0; i < total; i++) + { point = points[i]; index = i * 4; - if (i < points.length-1) { + if (i < points.length-1) + { nextPoint = points[i+1]; } - else { + else + { nextPoint = point; } @@ -129,7 +140,8 @@ ratio = (1 - (i / (total-1))) * 10; - if (ratio > 1) { + if (ratio > 1) + { ratio = 1; } @@ -157,7 +169,8 @@ * * @param texture {Texture} the texture that will be used */ -Rope.prototype.setTexture = function (texture) { +Rope.prototype.setTexture = function (texture) +{ // stop current texture this.texture = texture; //this.updateFrame = true; diff --git a/src/extras/Strip.js b/src/extras/Strip.js index c5e378f..57691b5 100644 --- a/src/extras/Strip.js +++ b/src/extras/Strip.js @@ -10,7 +10,8 @@ * @param height {number} the height * */ -function Strip(texture) { +function Strip(texture) +{ core.DisplayObjectContainer.call(this); /** @@ -70,9 +71,11 @@ * * @param renderer {WebGLRenderer} */ -Strip.prototype.renderWebGL = function (renderer) { +Strip.prototype.renderWebGL = function (renderer) +{ // if the sprite is not visible or the alpha is 0 then no need to render this element - if (!this.visible || this.alpha <= 0) { + if (!this.visible || this.alpha <= 0) + { return; } @@ -81,7 +84,8 @@ renderer.spriteBatch.stop(); // init! init! - if (!this._vertexBuffer) { + if (!this._vertexBuffer) + { this._initWebGL(renderer); } @@ -96,7 +100,8 @@ //TODO check culling }; -Strip.prototype._initWebGL = function (renderer) { +Strip.prototype._initWebGL = function (renderer) +{ // build the strip! var gl = renderer.gl; @@ -118,7 +123,8 @@ gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this.indices, gl.STATIC_DRAW); }; -Strip.prototype._renderStrip = function (renderer) { +Strip.prototype._renderStrip = function (renderer) +{ var gl = renderer.gl; var projection = renderer.projection, offset = renderer.offset, @@ -137,7 +143,8 @@ gl.uniform2f(shader.offsetVector, -offset.x, -offset.y); gl.uniform1f(shader.alpha, this.worldAlpha); - if (!this.dirty) { + if (!this.dirty) + { gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexBuffer); gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); @@ -150,10 +157,12 @@ gl.activeTexture(gl.TEXTURE0); // check if a texture is dirty.. - if (this.texture.baseTexture._dirty[gl.id]) { + if (this.texture.baseTexture._dirty[gl.id]) + { renderer.updateTexture(this.texture.baseTexture); } - else { + else + { // bind the current texture gl.bindTexture(gl.TEXTURE_2D, this.texture.baseTexture._glTextures[gl.id]); } @@ -163,7 +172,8 @@ } - else { + else + { this.dirty = false; gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexBuffer); @@ -178,10 +188,12 @@ gl.activeTexture(gl.TEXTURE0); // check if a texture is dirty.. - if (this.texture.baseTexture._dirty[gl.id]) { + if (this.texture.baseTexture._dirty[gl.id]) + { renderer.updateTexture(this.texture.baseTexture); } - else { + else + { gl.bindTexture(gl.TEXTURE_2D, this.texture.baseTexture._glTextures[gl.id]); } @@ -203,27 +215,33 @@ * * @param renderer {CanvasRenderer} */ -Strip.prototype.renderCanvas = function (renderer) { +Strip.prototype.renderCanvas = function (renderer) +{ var context = renderer.context; var transform = this.worldTransform; - if (renderer.roundPixels) { + if (renderer.roundPixels) + { context.setTransform(transform.a, transform.b, transform.c, transform.d, transform.tx | 0, transform.ty | 0); } - else { + else + { context.setTransform(transform.a, transform.b, transform.c, transform.d, transform.tx, transform.ty); } - if (this.drawMode === Strip.DrawModes.TRIANGLE_STRIP) { + if (this.drawMode === Strip.DrawModes.TRIANGLE_STRIP) + { this._renderCanvasTriangleStrip(context); } - else { + else + { this._renderCanvasTriangles(context); } }; -Strip.prototype._renderCanvasTriangleStrip = function (context) { +Strip.prototype._renderCanvasTriangleStrip = function (context) +{ // draw triangles!! var vertices = this.vertices; var uvs = this.uvs; @@ -231,14 +249,16 @@ var length = vertices.length / 2; // this.count++; - for (var i = 0; i < length - 2; i++) { + for (var i = 0; i < length - 2; i++) + { // draw some triangles! var index = i * 2; this._renderCanvasDrawTriangle(context, vertices, uvs, index, (index + 2), (index + 4)); } }; -Strip.prototype._renderCanvasTriangles = function (context) { +Strip.prototype._renderCanvasTriangles = function (context) +{ // draw triangles!! var vertices = this.vertices; var uvs = this.uvs; @@ -247,14 +267,16 @@ var length = indices.length; // this.count++; - for (var i = 0; i < length; i += 3) { + for (var i = 0; i < length; i += 3) + { // draw some triangles! var index0 = indices[i] * 2, index1 = indices[i + 1] * 2, index2 = indices[i + 2] * 2; this._renderCanvasDrawTriangle(context, vertices, uvs, index0, index1, index2); } }; -Strip.prototype._renderCanvasDrawTriangle = function (context, vertices, uvs, index0, index1, index2) { +Strip.prototype._renderCanvasDrawTriangle = function (context, vertices, uvs, index0, index1, index2) +{ var textureSource = this.texture.baseTexture.source; var textureWidth = this.texture.width; var textureHeight = this.texture.height; @@ -265,7 +287,8 @@ var u0 = uvs[index0] * textureWidth, u1 = uvs[index1] * textureWidth, u2 = uvs[index2] * textureWidth; var v0 = uvs[index0 + 1] * textureHeight, v1 = uvs[index1 + 1] * textureHeight, v2 = uvs[index2 + 1] * textureHeight; - if (this.canvasPadding > 0) { + if (this.canvasPadding > 0) + { var paddingX = this.canvasPadding / this.worldTransform.a; var paddingY = this.canvasPadding / this.worldTransform.d; var centerX = (x0 + x1 + x2) / 3; @@ -332,7 +355,8 @@ * @param strip {Strip} The Strip to render * @private */ -Strip.prototype.renderStripFlat = function (strip) { +Strip.prototype.renderStripFlat = function (strip) +{ var context = this.context; var vertices = strip.vertices; @@ -340,7 +364,8 @@ // this.count++; context.beginPath(); - for (var i=1; i < length-2; i++) { + for (var i=1; i < length-2; i++) + { // draw some triangles! var index = i*2; @@ -358,7 +383,8 @@ }; /* -Strip.prototype.setTexture = function (texture) { +Strip.prototype.setTexture = function (texture) +{ //TODO SET THE TEXTURES //TODO VISIBILITY @@ -377,7 +403,8 @@ * @private */ -Strip.prototype.onTextureUpdate = function () { +Strip.prototype.onTextureUpdate = function () +{ this.updateFrame = true; }; @@ -387,7 +414,8 @@ * @param matrix {Matrix} the transformation matrix of the sprite * @return {Rectangle} the framing rectangle */ -Strip.prototype.getBounds = function (matrix) { +Strip.prototype.getBounds = function (matrix) +{ var worldTransform = matrix || this.worldTransform; var a = worldTransform.a; @@ -404,7 +432,8 @@ var minY = Infinity; var vertices = this.vertices; - for (var i = 0, n = vertices.length; i < n; i += 2) { + for (var i = 0, n = vertices.length; i < n; i += 2) + { var rawX = vertices[i], rawY = vertices[i + 1]; var x = (a * rawX) + (c * rawY) + tx; var y = (d * rawY) + (b * rawX) + ty; @@ -416,7 +445,8 @@ maxY = y > maxY ? y : maxY; } - if (minX === -Infinity || maxY === Infinity) { + if (minX === -Infinity || maxY === Infinity) + { return core.math.Rectangle.EMPTY; } diff --git a/src/extras/TilingSprite.js b/src/extras/TilingSprite.js index 3ac22df..31da393 100644 --- a/src/extras/TilingSprite.js +++ b/src/extras/TilingSprite.js @@ -10,7 +10,8 @@ * @param width {number} the width of the tiling sprite * @param height {number} the height of the tiling sprite */ -function TilingSprite(texture, width, height) { +function TilingSprite(texture, width, height) +{ core.Sprite.call( this, texture); /** @@ -86,10 +87,12 @@ * @memberof TilingSprite# */ width: { - get: function () { + get: function () + { return this._width; }, - set: function (value) { + set: function (value) + { this._width = value; } }, @@ -101,20 +104,25 @@ * @memberof TilingSprite# */ height: { - get: function () { + get: function () + { return this._height; }, - set: function (value) { + set: function (value) + { this._height = value; } }, texture: { - get: function () { + get: function () + { return this._texture; }, - set: function (value) { - if (this._texture === value) { + set: function (value) + { + if (this._texture === value) + { return; } @@ -130,51 +138,61 @@ * * @param renderer {WebGLRenderer} */ -TilingSprite.prototype.renderWebGL = function (renderer) { - if (!this.visible || this.alpha <= 0) { +TilingSprite.prototype.renderWebGL = function (renderer) +{ + if (!this.visible || this.alpha <= 0) + { return; } var i, j; - if (this._mask) { + if (this._mask) + { renderer.spriteBatch.stop(); renderer.maskManager.pushMask(this.mask, renderer); renderer.spriteBatch.start(); } - if (this._filters) { + if (this._filters) + { renderer.spriteBatch.flush(); renderer.filterManager.pushFilter(this._filterBlock); } - if (!this.tilingTexture || this.refreshTexture) { + if (!this.tilingTexture || this.refreshTexture) + { this.generateTilingTexture(true); - if (this.tilingTexture && this.tilingTexture.needsUpdate) { + if (this.tilingTexture && this.tilingTexture.needsUpdate) + { //TODO - tweaking renderer.updateTexture(this.tilingTexture.baseTexture); this.tilingTexture.needsUpdate = false; // this.tilingTexture._uvs = null; } } - else { + else + { renderer.spriteBatch.renderTilingSprite(this); } // simple render children! - for (i=0,j=this.children.length; i= 0 && index <= this.children.length) { - if (child.parent) { + if (index >= 0 && index <= this.children.length) + { + if (child.parent) + { child.parent.removeChild(child); } @@ -154,7 +173,8 @@ return child; } - else { + else + { throw new Error(child + 'addChildAt: The index '+ index +' supplied is out of bounds ' + this.children.length); } }; @@ -165,15 +185,18 @@ * @param child {DisplayObject} * @param child2 {DisplayObject} */ -DisplayObjectContainer.prototype.swapChildren = function (child, child2) { - if (child === child2) { +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) { + if (index1 < 0 || index2 < 0) + { throw new Error('swapChildren: Both the supplied DisplayObjects must be a child of the caller.'); } @@ -187,10 +210,12 @@ * @param child {DisplayObject} The DisplayObject instance to identify * @return {Number} The index position of the child display object to identify */ -DisplayObjectContainer.prototype.getChildIndex = function (child) { +DisplayObjectContainer.prototype.getChildIndex = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { throw new Error('The supplied DisplayObject must be a child of the caller'); } @@ -203,8 +228,10 @@ * @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 */ -DisplayObjectContainer.prototype.setChildIndex = function (child, index) { - if (index < 0 || index >= this.children.length) { +DisplayObjectContainer.prototype.setChildIndex = function (child, index) +{ + if (index < 0 || index >= this.children.length) + { throw new Error('The supplied index is out of bounds'); } @@ -220,8 +247,10 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child at the given index, if any. */ -DisplayObjectContainer.prototype.getChildAt = function (index) { - if (index < 0 || index >= this.children.length) { +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'); } @@ -234,10 +263,12 @@ * @param child {DisplayObject} The DisplayObject to remove * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChild = function (child) { +DisplayObjectContainer.prototype.removeChild = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { return; } @@ -250,7 +281,8 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChildAt = function (index) { +DisplayObjectContainer.prototype.removeChildAt = function (index) +{ var child = this.getChildAt(index); child.parent = null; @@ -265,24 +297,29 @@ * @param beginIndex {Number} The beginning position. Default value is 0. * @param endIndex {Number} The ending position. Default value is size of the container. */ -DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) { +DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) +{ var begin = beginIndex || 0; var end = typeof endIndex === 'number' ? endIndex : this.children.length; var range = end - begin; - if (range > 0 && range <= end) { + if (range > 0 && range <= end) + { var removed = this.children.splice(begin, range); - for (var i = 0; i < removed.length; ++i) { + for (var i = 0; i < removed.length; ++i) + { removed[i].parent = null; } return removed; } - else if (range === 0 && this.children.length === 0) { + else if (range === 0 && this.children.length === 0) + { return []; } - else { + else + { throw new RangeError('removeChildren: numeric values are outside the acceptable range.'); } }; @@ -291,7 +328,8 @@ * Generates and updates the cached sprite for this object. * */ -DisplayObjectContainer.prototype.updateCachedSprite = function () { +DisplayObjectContainer.prototype.updateCachedSprite = function () +{ this._generateCachedSprite(); }; @@ -304,7 +342,8 @@ * @param renderer {CanvasRenderer|WebGLRenderer} The renderer used to generate the texture. * @return {Texture} a texture of the graphics object */ -DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) { +DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) +{ var bounds = this.getLocalBounds(); var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0, renderer, scaleMode, resolution); @@ -322,18 +361,22 @@ * * @private */ -DisplayObjectContainer.prototype.updateTransform = function () { - if (!this.visible) { +DisplayObjectContainer.prototype.updateTransform = function () +{ + if (!this.visible) + { return; } this.displayObjectUpdateTransform(); - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { return; } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } }; @@ -346,8 +389,10 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getBounds = function () { - if (this.children.length === 0) { +DisplayObjectContainer.prototype.getBounds = function () +{ + if (this.children.length === 0) + { return math.Rectangle.EMPTY; } @@ -365,10 +410,12 @@ var childVisible = false; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -386,7 +433,8 @@ maxY = maxY > childMaxY ? maxY : childMaxY; } - if (!childVisible) { + if (!childVisible) + { return math.Rectangle.EMPTY; } @@ -407,12 +455,14 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getLocalBounds = function () { +DisplayObjectContainer.prototype.getLocalBounds = function () +{ var matrixCache = this.worldTransform; this.worldTransform = math.Matrix.IDENTITY; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } @@ -428,13 +478,16 @@ * * @param renderer {WebGLRenderer} The renderer */ -DisplayObjectContainer.prototype.renderWebGL = function (renderer) { +DisplayObjectContainer.prototype.renderWebGL = function (renderer) +{ // if the object is not visible or the alpha is 0 then no need to render this element - if (!this.visible || this.alpha <= 0) { + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } @@ -442,14 +495,17 @@ var i, j; // do a quick check to see if this element has a mask or a filter. - if (this._mask || this._filters) { + if (this._mask || this._filters) + { // push filter first as we need to ensure the stencil buffer is correct for any masking - if (this._filters) { + if (this._filters) + { renderer.spriteBatch.flush(); renderer.filterManager.pushFilter(this._filterBlock); } - if (this._mask) { + if (this._mask) + { renderer.spriteBatch.stop(); renderer.maskManager.pushMask(this.mask, renderer); renderer.spriteBatch.start(); @@ -459,36 +515,42 @@ this._renderWebGL(renderer); // now loop through the children and make sure they get rendered - for (i = 0, j = this.children.length; i < j; i++) { + for (i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderWebGL(renderer); } // time to stop the sprite batch as either a mask element or a filter draw will happen next renderer.spriteBatch.stop(); - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(this._mask, renderer); } - if (this._filters) { + if (this._filters) + { renderer.filterManager.popFilter(); } renderer.spriteBatch.start(); } - else { + else + { this._renderWebGL(renderer); // simple render children! - for (i = 0, j = this.children.length; i < j; ++i) { + for (i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderWebGL(renderer); } } }; -DisplayObjectContainer.prototype._renderWebGL = function (renderer) { +DisplayObjectContainer.prototype._renderWebGL = function (renderer) +{ // this is where content itself gets renderd.. @@ -499,25 +561,31 @@ * * @param renderer {CanvasRenderer} The renderer */ -DisplayObjectContainer.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0) { +DisplayObjectContainer.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -528,13 +596,16 @@ * @param renderer {WebGLRenderer|CanvasRenderer} The renderer * @private */ -DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) { +DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) +{ this._cachedSprite.worldAlpha = this.worldAlpha; - if (renderer.gl) { + if (renderer.gl) + { this._cachedSprite.renderWebGL(renderer); } - else { + else + { this._cachedSprite.renderCanvas(renderer); } }; @@ -544,10 +615,12 @@ * * @private */ -DisplayObjectContainer.prototype._generateCachedSprite = function () { +DisplayObjectContainer.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { // TODO - RenderTexture now *requires* a renderer instance, so this is like broken // because `renderer` isn't actually in scope here :P var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0); @@ -555,7 +628,8 @@ this._cachedSprite = new Sprite(renderTexture); this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.texture.resize(bounds.width | 0, bounds.height | 0); } @@ -580,8 +654,10 @@ * * @private */ -DisplayObjectContainer.prototype._destroyCachedSprite = function () { - if (!this._cachedSprite) { +DisplayObjectContainer.prototype._destroyCachedSprite = function () +{ + if (!this._cachedSprite) + { return; } diff --git a/src/core/display/Sprite.js b/src/core/display/Sprite.js index 707da24..5862aef 100644 --- a/src/core/display/Sprite.js +++ b/src/core/display/Sprite.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param texture {Texture} The texture for this sprite */ -function Sprite(texture) { +function Sprite(texture) +{ DisplayObjectContainer.call(this); /** @@ -85,12 +86,14 @@ this.texture = texture || Texture.EMPTY; } -Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) { +Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) +{ DisplayObjectContainer.prototype.destroy.call(this); this.anchor = null; - if (destroyTexture) { + if (destroyTexture) + { this._texture.destroy(destroyBaseTexture); } @@ -111,10 +114,12 @@ * @memberof Sprite# */ width: { - get: function () { + get: function () + { return this.scale.x * this.texture.frame.width; }, - set: function (value) { + set: function (value) + { this.scale.x = value / this.texture.frame.width; this._width = value; } @@ -127,10 +132,12 @@ * @memberof Sprite# */ height: { - get: function () { + get: function () + { return this.scale.y * this.texture.frame.height; }, - set: function (value) { + set: function (value) + { this.scale.y = value / this.texture.frame.height; this._height = value; } @@ -143,23 +150,29 @@ * @memberof Sprite# */ texture: { - get: function () { + get: function () + { return this._texture; }, - set: function (value) { - if (this._texture === value) { + set: function (value) + { + if (this._texture === value) + { return; } this._texture = value; this.cachedTint = 0xFFFFFF; - if (value) { + if (value) + { // wait for the texture to load - if (value.baseTexture.hasLoaded) { + if (value.baseTexture.hasLoaded) + { this._onTextureUpdate(); } - else { + else + { value.once('update', this._onTextureUpdate.bind(this)); } } @@ -172,18 +185,22 @@ * * @private */ -Sprite.prototype._onTextureUpdate = function () { +Sprite.prototype._onTextureUpdate = function () +{ // so if _width is 0 then width was not set.. - if (this._width) { + if (this._width) + { this.scale.x = this._width / this.texture.frame.width; } - if (this._height) { + if (this._height) + { this.scale.y = this._height / this.texture.frame.height; } }; -Sprite.prototype._renderWebGL = function (renderer) { +Sprite.prototype._renderWebGL = function (renderer) +{ // this is where content gets renderd.. // watch this space for a little render state manager.. @@ -197,7 +214,8 @@ * @param matrix {Matrix} the transformation matrix of the sprite * @return {Rectangle} the framing rectangle */ -Sprite.prototype.getBounds = function (matrix) { +Sprite.prototype.getBounds = function (matrix) +{ var width = this.texture.frame.width; var height = this.texture.frame.height; @@ -224,11 +242,13 @@ if(b === 0 && c === 0) { // scale may be negative! - if (a < 0) { + if (a < 0) + { a *= -1; } - if (d < 0) { + if (d < 0) + { d *= -1; } @@ -293,28 +313,34 @@ * * @param renderer {CanvasRenderer} The renderer */ -Sprite.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) { +Sprite.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) + { return; } - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; renderer.context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } // Ignore null sources - if (this.texture.valid) { + if (this.texture.valid) + { var resolution = this.texture.baseTexture.resolution / renderer.resolution; renderer.context.globalAlpha = this.worldAlpha; // If smoothingEnabled is supported and we need to change the smoothing property for this texture - if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) { + if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) + { renderer.scaleMode = this.texture.baseTexture.scaleMode; renderer.context[renderer.smoothProperty] = (renderer.scaleMode === CONST.scaleModes.LINEAR); } @@ -324,7 +350,8 @@ var dy = (this.texture.trim ? this.texture.trim.y : 0) - (this.anchor.y * this.texture.trim.height); // Allow for pixel rounding - if (renderer.roundPixels) { + if (renderer.roundPixels) + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -337,7 +364,8 @@ dx = dx | 0; dy = dy | 0; } - else { + else + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -348,8 +376,10 @@ ); } - if (this.tint !== 0xFFFFFF) { - if (this.cachedTint !== this.tint) { + if (this.tint !== 0xFFFFFF) + { + if (this.cachedTint !== this.tint) + { this.cachedTint = this.tint; // TODO clean up caching - how to clean up the caches? @@ -368,7 +398,8 @@ this.texture.crop.height / resolution ); } - else { + else + { renderer.context.drawImage( this.texture.baseTexture.source, this.texture.crop.x, @@ -383,11 +414,13 @@ } } - for (var i = 0, j = this.children.length; i < j; i++) { + for (var i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -402,10 +435,12 @@ * @param frameId {String} The frame Id of the texture in the cache * @return {Sprite} A new Sprite using a texture from the texture cache matching the frameId */ -Sprite.fromFrame = function (frameId) { +Sprite.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache' + this); } @@ -420,6 +455,7 @@ * @param imageId {String} The image url of the texture * @return {Sprite} A new Sprite using a texture from the texture cache matching the image id */ -Sprite.fromImage = function (imageId, crossorigin, scaleMode) { +Sprite.fromImage = function (imageId, crossorigin, scaleMode) +{ return new Sprite(Texture.fromImage(imageId, crossorigin, scaleMode)); }; diff --git a/src/core/display/SpriteBatch.js b/src/core/display/SpriteBatch.js index 3187777..c196fef 100644 --- a/src/core/display/SpriteBatch.js +++ b/src/core/display/SpriteBatch.js @@ -12,7 +12,8 @@ * ```js * var container = new SpriteBatch(); * - * for(var i = 0; i < 100; ++i) { + * for(var i = 0; i < 100; ++i) + * { * var sprite = new PIXI.Sprite.fromImage("myImage.png"); * container.addChild(sprite); * } @@ -25,7 +26,8 @@ */ //TODO RENAME to PARTICLE CONTAINER? -function SpriteBatch() { +function SpriteBatch() +{ DisplayObjectContainer.call(this); } @@ -38,7 +40,8 @@ * * @private */ -SpriteBatch.prototype.updateTransform = function () { +SpriteBatch.prototype.updateTransform = function () +{ // TODO don't need to! this.displayObjectUpdateTransform(); // PIXI.DisplayObjectContainer.prototype.updateTransform.call( this ); @@ -50,8 +53,10 @@ * @param renderer {WebGLRenderer} The webgl renderer * @private */ -SpriteBatch.prototype.renderWebGL = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderWebGL = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -71,8 +76,10 @@ * @param renderer {CanvasRenderer} The canvas renderer * @private */ -SpriteBatch.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -84,10 +91,12 @@ this.displayObjectUpdateTransform(); - for (var i = 0; i < this.children.length; ++i) { + for (var i = 0; i < this.children.length; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -95,9 +104,11 @@ context.globalAlpha = this.worldAlpha * child.alpha; - if (child.rotation % (Math.PI * 2) === 0) { + if (child.rotation % (Math.PI * 2) === 0) + { // this is the fastest way to optimise! - if rotation is 0 then we can avoid any kind of setTransform call - if (isRotated) { + if (isRotated) + { context.setTransform( transform.a, transform.b, @@ -122,8 +133,10 @@ frame.height * child.scale.y ); } - else { - if (!isRotated) { + else + { + if (!isRotated) + { isRotated = true; } @@ -131,7 +144,8 @@ var childTransform = child.worldTransform; - if (renderer.roundPixels) { + if (renderer.roundPixels) + { context.setTransform( childTransform.a, childTransform.b, @@ -141,7 +155,8 @@ childTransform.ty | 0 ); } - else { + else + { context.setTransform( childTransform.a, childTransform.b, diff --git a/src/core/index.js b/src/core/index.js index 3954b6f..eb4a82b 100644 --- a/src/core/index.js +++ b/src/core/index.js @@ -58,11 +58,13 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRenderer: function (width, height, options, noWebGL) { + autoDetectRenderer: function (width, height, options, noWebGL) + { width = width || 800; height = height || 600; - if (!noWebGL && require('webgl-enabled')()) { + if (!noWebGL && require('webgl-enabled')()) + { return new core.WebGLRenderer(width, height, options); } @@ -87,7 +89,8 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRecommendedRenderer: function (width, height, options) { + autoDetectRecommendedRenderer: function (width, height, options) + { var isAndroid = /Android/i.test(navigator.userAgent); return core.autoDetectRenderer(width, height, options, isAndroid); diff --git a/src/core/math/Matrix.js b/src/core/math/Matrix.js index c2f87e2..2ff4848 100644 --- a/src/core/math/Matrix.js +++ b/src/core/math/Matrix.js @@ -10,7 +10,8 @@ * @class * @namespace PIXI */ -function Matrix() { +function Matrix() +{ /** * @member {number} * @default 1 @@ -63,7 +64,8 @@ * * @param array {number[]} The array that the matrix will be populated from. */ -Matrix.prototype.fromArray = function (array) { +Matrix.prototype.fromArray = function (array) +{ this.a = array[0]; this.b = array[1]; this.c = array[3]; @@ -78,14 +80,17 @@ * @param transpose {boolean} Whether we need to transpose the matrix or not * @return {number[]} the newly created array which contains the matrix */ -Matrix.prototype.toArray = function (transpose) { - if (!this.array) { +Matrix.prototype.toArray = function (transpose) +{ + if (!this.array) + { this.array = new Float32Array(9); } var array = this.array; - if (transpose) { + if (transpose) + { array[0] = this.a; array[1] = this.b; array[2] = 0; @@ -96,7 +101,8 @@ array[7] = this.ty; array[8] = 1; } - else { + else + { array[0] = this.a; array[1] = this.c; array[2] = this.tx; @@ -119,7 +125,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, transformed through this matrix */ -Matrix.prototype.apply = function (pos, newPos) { +Matrix.prototype.apply = function (pos, newPos) +{ newPos = newPos || new Point(); newPos.x = this.a * pos.x + this.c * pos.y + this.tx; @@ -136,7 +143,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, inverse-transformed through this matrix */ -Matrix.prototype.applyInverse = function (pos, newPos) { +Matrix.prototype.applyInverse = function (pos, newPos) +{ newPos = newPos || new Point(); var id = 1 / (this.a * this.d + this.c * -this.b); @@ -154,7 +162,8 @@ * @param {number} y * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.translate = function (x, y) { +Matrix.prototype.translate = function (x, y) +{ this.tx += x; this.ty += y; @@ -168,7 +177,8 @@ * @param {number} y The amount to scale vertically * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.scale = function (x, y) { +Matrix.prototype.scale = function (x, y) +{ this.a *= x; this.d *= y; this.c *= x; @@ -186,7 +196,8 @@ * @param {number} angle - The angle in radians. * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.rotate = function (angle) { +Matrix.prototype.rotate = function (angle) +{ var cos = Math.cos( angle ); var sin = Math.sin( angle ); @@ -210,7 +221,8 @@ * @param {Matrix} matrix * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.append = function (matrix) { +Matrix.prototype.append = function (matrix) +{ var a1 = this.a; var b1 = this.b; var c1 = this.c; @@ -232,7 +244,8 @@ * * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.identity = function () { +Matrix.prototype.identity = function () +{ this.a = 1; this.b = 0; this.c = 0; diff --git a/src/core/math/Point.js b/src/core/math/Point.js index 7565b2d..632f346 100644 --- a/src/core/math/Point.js +++ b/src/core/math/Point.js @@ -7,7 +7,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -function Point(x, y) { +function Point(x, y) +{ /** * @member {number} * @default 0 @@ -29,7 +30,8 @@ * * @return {Point} a copy of the point */ -Point.prototype.clone = function () { +Point.prototype.clone = function () +{ return new Point(this.x, this.y); }; @@ -40,7 +42,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -Point.prototype.set = function (x, y) { +Point.prototype.set = function (x, y) +{ this.x = x || 0; this.y = y || ( (y !== 0) ? this.x : 0 ) ; }; diff --git a/src/core/math/shapes/Circle.js b/src/core/math/shapes/Circle.js index 69cfdc9..4d76efc 100644 --- a/src/core/math/shapes/Circle.js +++ b/src/core/math/shapes/Circle.js @@ -10,7 +10,8 @@ * @param y {number} The Y coordinate of the center of this circle * @param radius {number} The radius of the circle */ -function Circle(x, y, radius) { +function Circle(x, y, radius) +{ /** * @member {number} * @default 0 @@ -46,7 +47,8 @@ * @method clone * @return {Circle} a copy of the Circle */ -Circle.prototype.clone = function () { +Circle.prototype.clone = function () +{ return new Circle(this.x, this.y, this.radius); }; @@ -58,8 +60,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Circle */ -Circle.prototype.contains = function (x, y) { - if (this.radius <= 0) { +Circle.prototype.contains = function (x, y) +{ + if (this.radius <= 0) + { return false; } @@ -79,6 +83,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Circle.prototype.getBounds = function () { +Circle.prototype.getBounds = function () +{ return new Rectangle(this.x - this.radius, this.y - this.radius, this.radius * 2, this.radius * 2); }; diff --git a/src/core/math/shapes/Ellipse.js b/src/core/math/shapes/Ellipse.js index 4f2d066..fefd01a 100644 --- a/src/core/math/shapes/Ellipse.js +++ b/src/core/math/shapes/Ellipse.js @@ -11,7 +11,8 @@ * @param width {number} The half width of this ellipse * @param height {number} The half height of this ellipse */ -function Ellipse(x, y, width, height) { +function Ellipse(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -53,7 +54,8 @@ * @method clone * @return {Ellipse} a copy of the ellipse */ -Ellipse.prototype.clone = function () { +Ellipse.prototype.clone = function () +{ return new Ellipse(this.x, this.y, this.width, this.height); }; @@ -65,8 +67,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coords are within this ellipse */ -Ellipse.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Ellipse.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } @@ -86,6 +90,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Ellipse.prototype.getBounds = function () { +Ellipse.prototype.getBounds = function () +{ return new Rectangle(this.x - this.width, this.y - this.height, this.width, this.height); }; diff --git a/src/core/math/shapes/Polygon.js b/src/core/math/shapes/Polygon.js index ae89148..fea6d37 100644 --- a/src/core/math/shapes/Polygon.js +++ b/src/core/math/shapes/Polygon.js @@ -10,16 +10,20 @@ * arguments passed can be flat x,y values e.g. `new Polygon(x,y, x,y, x,y, ...)` where `x` and `y` are * Numbers. */ -function Polygon(points) { +function Polygon(points) +{ //if points isn't an array, use arguments as the array - if (!(points instanceof Array)) { + if (!(points instanceof Array)) + { points = Array.prototype.slice.call(arguments); } //if this is a flat array of numbers, convert it to points - if (points[0] instanceof Point) { + if (points[0] instanceof Point) + { var p = []; - for (var i = 0, il = points.length; i < il; i++) { + for (var i = 0, il = points.length; i < il; i++) + { p.push(points[i].x, points[i].y); } @@ -51,7 +55,8 @@ * * @return {Polygon} a copy of the polygon */ -Polygon.prototype.clone = function () { +Polygon.prototype.clone = function () +{ return new Polygon(this.points.slice()); }; @@ -62,19 +67,22 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this polygon */ -Polygon.prototype.contains = function (x, y) { +Polygon.prototype.contains = function (x, y) +{ var inside = false; // use some raycasting to test hits // https://github.com/substack/point-in-polygon/blob/master/index.js var length = this.points.length / 2; - for (var i = 0, j = length - 1; i < length; j = i++) { + for (var i = 0, j = length - 1; i < length; j = i++) + { var xi = this.points[i * 2], yi = this.points[i * 2 + 1], xj = this.points[j * 2], yj = this.points[j * 2 + 1], intersect = ((yi > y) !== (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi); - if (intersect) { + if (intersect) + { inside = !inside; } } diff --git a/src/core/math/shapes/Rectangle.js b/src/core/math/shapes/Rectangle.js index 16ac62a..4008b68 100644 --- a/src/core/math/shapes/Rectangle.js +++ b/src/core/math/shapes/Rectangle.js @@ -10,7 +10,8 @@ * @param width {number} The overall width of this rectangle * @param height {number} The overall height of this rectangle */ -function Rectangle(x, y, width, height) { +function Rectangle(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -60,7 +61,8 @@ * * @return {Rectangle} a copy of the rectangle */ -Rectangle.prototype.clone = function () { +Rectangle.prototype.clone = function () +{ return new Rectangle(this.x, this.y, this.width, this.height); }; @@ -71,13 +73,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rectangle */ -Rectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Rectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/math/shapes/RoundedRectangle.js b/src/core/math/shapes/RoundedRectangle.js index 27d286e..7bf6411 100644 --- a/src/core/math/shapes/RoundedRectangle.js +++ b/src/core/math/shapes/RoundedRectangle.js @@ -11,7 +11,8 @@ * @param height {number} The overall height of this rounded rectangle * @param radius {number} Controls the radius of the rounded corners */ -function RoundedRectangle(x, y, width, height, radius) { +function RoundedRectangle(x, y, width, height, radius) +{ /** * @member {number} * @default 0 @@ -58,7 +59,8 @@ * * @return {RoundedRectangle} a copy of the rounded rectangle */ -RoundedRectangle.prototype.clone = function () { +RoundedRectangle.prototype.clone = function () +{ return new RoundedRectangle(this.x, this.y, this.width, this.height, this.radius); }; @@ -69,13 +71,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rounded Rectangle */ -RoundedRectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +RoundedRectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/primitives/Graphics.js b/src/core/primitives/Graphics.js index 261c534..e902d2a 100644 --- a/src/core/primitives/Graphics.js +++ b/src/core/primitives/Graphics.js @@ -16,7 +16,8 @@ * @extends DisplayObjectContainer * @namespace PIXI */ -function Graphics() { +function Graphics() +{ DisplayObjectContainer.call(this); this.renderable = true; @@ -154,16 +155,20 @@ * @private */ cacheAsBitmap: { - get: function () { + get: function () + { return this._cacheAsBitmap; }, - set: function (value) { + set: function (value) + { this._cacheAsBitmap = value; - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._generateCachedSprite(); } - else { + else + { this.destroyCachedSprite(); this.dirty = true; } @@ -176,7 +181,8 @@ * * @return {Graphics} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ var clone = new Graphics(); clone.renderable = this.renderable; @@ -192,7 +198,8 @@ clone.cachedSpriteDirty = this.cachedSpriteDirty; // copy graphics data - for (var i = 0; i < this.graphicsData.length; ++i) { + for (var i = 0; i < this.graphicsData.length; ++i) + { clone.graphicsData.push(this.graphicsData.clone()); } @@ -211,17 +218,21 @@ * @param alpha {number} alpha of the line to draw, will update the objects stored style * @return {Graphics} */ -Graphics.prototype.lineStyle = function (lineWidth, color, alpha) { +Graphics.prototype.lineStyle = function (lineWidth, color, alpha) +{ this.lineWidth = lineWidth || 0; this.lineColor = color || 0; this.lineAlpha = (arguments.length < 3) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length) + { // halfway through a line? start a new one! this.drawShape( new math.Polygon( this.currentPath.shape.points.slice(-2) )); } - else { + else + { // otherwise its empty so lets just set the line properties this.currentPath.lineWidth = this.lineWidth; this.currentPath.lineColor = this.lineColor; @@ -239,7 +250,8 @@ * @param y {number} the Y coordinate to move to * @return {Graphics} */ -Graphics.prototype.moveTo = function (x, y) { +Graphics.prototype.moveTo = function (x, y) +{ this.drawShape(new math.Polygon([x,y])); return this; @@ -253,7 +265,8 @@ * @param y {number} the Y coordinate to draw to * @return {Graphics} */ -Graphics.prototype.lineTo = function (x, y) { +Graphics.prototype.lineTo = function (x, y) +{ this.currentPath.shape.points.push(x, y); this.dirty = true; @@ -270,13 +283,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -285,7 +302,8 @@ n = 20, points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { this.moveTo(0, 0); } @@ -293,7 +311,8 @@ var fromY = points[points.length-1]; var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; xa = fromX + ( (cpX - fromX) * j ); @@ -319,13 +338,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -342,7 +365,8 @@ var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; dt = (1 - j); @@ -373,13 +397,17 @@ * @param radius {number} The radius of the arc * @return {Graphics} */ -Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points.push(x1, y1); } } - else { + else + { this.moveTo(x1, y1); } @@ -392,12 +420,15 @@ b2 = x2 - x1, mm = Math.abs(a1 * b2 - b1 * a2); - if (mm < 1.0e-8 || radius === 0) { - if (points[points.length-2] !== x1 || points[points.length-1] !== y1) { + if (mm < 1.0e-8 || radius === 0) + { + if (points[points.length-2] !== x1 || points[points.length-1] !== y1) + { points.push(x1, y1); } } - else { + else + { var dd = a1 * a1 + b1 * b1, cc = a2 * a2 + b2 * b2, tt = a1 * a2 + b1 * b2, @@ -433,42 +464,51 @@ * @param anticlockwise {boolean} Optional. Specifies whether the drawing should be counterclockwise or clockwise. False is default, and indicates clockwise, while true indicates counter-clockwise. * @return {Graphics} */ -Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) { +Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) +{ var startX = cx + Math.cos(startAngle) * radius; var startY = cy + Math.sin(startAngle) * radius; var points; // TODO - This if-else makes no sense. It uses currentPath in the else where it doesn't exist... - if (this.currentPath) { + if (this.currentPath) + { points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { points.push(startX, startY); } - else if (points[points.length-2] !== startX || points[points.length-1] !== startY) { + else if (points[points.length-2] !== startX || points[points.length-1] !== startY) + { points.push(startX, startY); } } - else { + else + { this.moveTo(startX, startY); points = this.currentPath.shape.points; } - if (startAngle === endAngle) { + if (startAngle === endAngle) + { return this; } - if (!anticlockwise && endAngle <= startAngle) { + if (!anticlockwise && endAngle <= startAngle) + { endAngle += Math.PI * 2; } - else if (anticlockwise && startAngle <= endAngle) { + else if (anticlockwise && startAngle <= endAngle) + { startAngle += Math.PI * 2; } var sweep = anticlockwise ? (startAngle - endAngle) *-1 : (endAngle - startAngle); var segs = (Math.abs(sweep)/ (Math.PI * 2)) * 40; - if (sweep === 0) { + if (sweep === 0) + { return this; } @@ -482,7 +522,8 @@ var remainder = ( segMinus % 1 ) / segMinus; - for (var i = 0; i <= segMinus; ++i) { + for (var i = 0; i <= segMinus; ++i) + { var real = i + remainder * i; var angle = ((theta) + startAngle + (theta2 * real)); @@ -506,13 +547,16 @@ * @param alpha {number} the alpha of the fill * @return {Graphics} */ -Graphics.prototype.beginFill = function (color, alpha) { +Graphics.prototype.beginFill = function (color, alpha) +{ this.filling = true; this.fillColor = color || 0; this.fillAlpha = (alpha === undefined) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length <= 2) + { this.currentPath.fill = this.filling; this.currentPath.fillColor = this.fillColor; this.currentPath.fillAlpha = this.fillAlpha; @@ -526,7 +570,8 @@ * * @return {Graphics} */ -Graphics.prototype.endFill = function () { +Graphics.prototype.endFill = function () +{ this.filling = false; this.fillColor = null; this.fillAlpha = 1; @@ -542,7 +587,8 @@ * @param height {number} The height of the rectangle * @return {Graphics} */ -Graphics.prototype.drawRect = function ( x, y, width, height ) { +Graphics.prototype.drawRect = function ( x, y, width, height ) +{ this.drawShape(new math.Rectangle(x,y, width, height)); return this; @@ -556,7 +602,8 @@ * @param height {number} The height of the rectangle * @param radius {number} Radius of the rectangle corners */ -Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) { +Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) +{ this.drawShape(new math.RoundedRectangle(x, y, width, height, radius)); return this; @@ -570,7 +617,8 @@ * @param radius {number} The radius of the circle * @return {Graphics} */ -Graphics.prototype.drawCircle = function (x, y, radius) { +Graphics.prototype.drawCircle = function (x, y, radius) +{ this.drawShape(new math.Circle(x,y, radius)); return this; @@ -585,7 +633,8 @@ * @param height {number} The half height of the ellipse * @return {Graphics} */ -Graphics.prototype.drawEllipse = function (x, y, width, height) { +Graphics.prototype.drawEllipse = function (x, y, width, height) +{ this.drawShape(new math.Ellipse(x, y, width, height)); return this; @@ -597,8 +646,10 @@ * @param path {Array} The path data used to construct the polygon. * @return {Graphics} */ -Graphics.prototype.drawPolygon = function (path) { - if (!(path instanceof Array)) { +Graphics.prototype.drawPolygon = function (path) +{ + if (!(path instanceof Array)) + { path = Array.prototype.slice.call(arguments); } @@ -612,7 +663,8 @@ * * @return {Graphics} */ -Graphics.prototype.clear = function () { +Graphics.prototype.clear = function () +{ this.lineWidth = 0; this.filling = false; @@ -631,7 +683,8 @@ * @param scaleMode {number} Should be one of the scaleMode consts * @return {Texture} a texture of the graphics object */ -Graphics.prototype.generateTexture = function (resolution, scaleMode) { +Graphics.prototype.generateTexture = function (resolution, scaleMode) +{ resolution = resolution || 1; var bounds = this.getBounds(); @@ -655,17 +708,21 @@ * * @param renderer {WebGLRenderer} */ -Graphics.prototype._renderWebGL = function (renderer) { +Graphics.prototype._renderWebGL = function (renderer) +{ // if the sprite is not visible or the alpha is 0 then no need to render this element - if (this.isMask === true) { + if (this.isMask === true) + { return; } // this code may still be needed so leaving for now.. - // + // /* - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture on the gpu too! @@ -681,17 +738,24 @@ return; } - */ - - // check if the webgl graphic needs to be updated - if (this.glDirty) { - this.dirty = true; - this.glDirty = false; - } + else */ - renderer.setObjectRendererer(renderer.graphicsRenderer); - renderer.graphicsRenderer.render(this); + renderer.spriteBatch.stop(); + renderer.blendModeManager.setBlendMode(this.blendMode); + // check blend mode + renderer.blendModeManager.setBlendMode( this.blendMode ); + + // check if the webgl graphic needs to be updated + if (this.glDirty) + { + this.dirty = true; + this.glDirty = false; + } + + WebGLGraphics.renderGraphics(this, renderer); + + renderer.spriteBatch.start(); }; /** @@ -700,14 +764,18 @@ * @param renderer {CanvasRenderer} * @private */ -Graphics.prototype.renderCanvas = function (renderer) { +Graphics.prototype.renderCanvas = function (renderer) +{ // 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.isMask === true) { + if (!this.visible || this.alpha <= 0 || this.isMask === true) + { return; } - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture @@ -723,16 +791,19 @@ return; } - else { + else + { var context = renderer.context; var transform = this.worldTransform; - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } @@ -748,11 +819,13 @@ CanvasGraphics.renderGraphics(this, context); - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } } @@ -763,13 +836,16 @@ * * @return {Rectangle} the rectangular bounding area */ -Graphics.prototype.getBounds = function (matrix) { +Graphics.prototype.getBounds = function (matrix) +{ // return an empty object if the item is a mask! - if (this.isMask) { + if (this.isMask) + { return math.Rectangle.EMPTY; } - if (this.dirty) { + if (this.dirty) + { this.updateLocalBounds(); this.glDirty = true; @@ -841,23 +917,27 @@ * Update the bounds of the object * */ -Graphics.prototype.updateLocalBounds = function () { +Graphics.prototype.updateLocalBounds = function () +{ var minX = Infinity; var maxX = -Infinity; var minY = Infinity; var maxY = -Infinity; - if (this.graphicsData.length) { + if (this.graphicsData.length) + { var shape, points, x, y, w, h; - for (var i = 0; i < this.graphicsData.length; i++) { + for (var i = 0; i < this.graphicsData.length; i++) + { var data = this.graphicsData[i]; var type = data.type; var lineWidth = data.lineWidth; shape = data.shape; - if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) { + if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) + { x = shape.x - lineWidth/2; y = shape.y - lineWidth/2; w = shape.width + lineWidth; @@ -869,7 +949,8 @@ minY = y < minY ? y : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.CIRC) { + else if (type === CONST.SHAPES.CIRC) + { x = shape.x; y = shape.y; w = shape.radius + lineWidth/2; @@ -881,7 +962,8 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.ELIP) { + else if (type === CONST.SHAPES.ELIP) + { x = shape.x; y = shape.y; w = shape.width + lineWidth/2; @@ -893,11 +975,13 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else { + else + { // POLY points = shape.points; - for (var j = 0; j < points.length; j += 2) { + for (var j = 0; j < points.length; j += 2) + { x = points[j]; y = points[j+1]; @@ -910,7 +994,8 @@ } } } - else { + else + { minX = 0; maxX = 0; minY = 0; @@ -931,10 +1016,12 @@ * * @private */ -Graphics.prototype._generateCachedSprite = function () { +Graphics.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { var canvasBuffer = new CanvasBuffer(bounds.width, bounds.height); var texture = Texture.fromCanvas(canvasBuffer.canvas); @@ -943,7 +1030,8 @@ this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.buffer.resize(bounds.width, bounds.height); } @@ -968,7 +1056,8 @@ * * @private */ -Graphics.prototype.updateCachedSpriteTexture = function () { +Graphics.prototype.updateCachedSpriteTexture = function () +{ var cachedSprite = this._cachedSprite; var texture = cachedSprite.texture; var canvas = cachedSprite.buffer.canvas; @@ -989,7 +1078,8 @@ * Destroys a previous cached sprite. * */ -Graphics.prototype.destroyCachedSprite = function () { +Graphics.prototype.destroyCachedSprite = function () +{ this._cachedSprite.texture.destroy(true); // let the gc collect the unused sprite @@ -1003,10 +1093,13 @@ * @param {Circle|Rectangle|Ellipse|Line|Polygon} shape The Shape object to draw. * @return {GraphicsData} The generated GraphicsData object. */ -Graphics.prototype.drawShape = function (shape) { - if (this.currentPath) { +Graphics.prototype.drawShape = function (shape) +{ + if (this.currentPath) + { // check current path! - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath.shape.points.length <= 2) + { this.graphicsData.pop(); } } @@ -1017,7 +1110,8 @@ this.graphicsData.push(data); - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { data.shape.closed = this.filling; this.currentPath = data; } diff --git a/src/core/primitives/GraphicsData.js b/src/core/primitives/GraphicsData.js index 99decbe..788f6f2 100644 --- a/src/core/primitives/GraphicsData.js +++ b/src/core/primitives/GraphicsData.js @@ -4,7 +4,8 @@ * @class * @namespace PIXI */ -function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) { +function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) +{ this.lineWidth = lineWidth; this.lineColor = lineColor; this.lineAlpha = lineAlpha; @@ -27,7 +28,8 @@ * * @return {GraphicsData} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ return new GraphicsData( this.lineWidth, this.lineColor, diff --git a/src/core/renderers/canvas/CanvasRenderer.js b/src/core/renderers/canvas/CanvasRenderer.js index 15a0978..7aebd44 100644 --- a/src/core/renderers/canvas/CanvasRenderer.js +++ b/src/core/renderers/canvas/CanvasRenderer.js @@ -17,17 +17,22 @@ * @param [options.resolution=1] {number} the resolution of the renderer retina would be 2 * @param [options.clearBeforeRender=true] {boolean} This sets if the CanvasRenderer will clear the canvas or not before the new render pass. */ -function CanvasRenderer(width, height, options) { +function CanvasRenderer(width, height, options) +{ utils.sayHello('Canvas'); - if (options) { - for (var i in CONST.defaultRenderOptions) { - if (typeof options[i] === 'undefined') { + if (options) + { + for (var i in CONST.defaultRenderOptions) + { + if (typeof options[i] === 'undefined') + { options[i] = CONST.defaultRenderOptions[i]; } } } - else { + else + { options = CONST.defaultRenderOptions; } @@ -156,19 +161,24 @@ this.smoothProperty = null; - if (this.context.imageSmoothingEnabled) { + if (this.context.imageSmoothingEnabled) + { this.smoothProperty = 'imageSmoothingEnabled'; } - else if (this.context.webkitImageSmoothingEnabled) { + else if (this.context.webkitImageSmoothingEnabled) + { this.smoothProperty = 'webkitImageSmoothingEnabled'; } - else if (this.context.mozImageSmoothingEnabled) { + else if (this.context.mozImageSmoothingEnabled) + { this.smoothProperty = 'mozImageSmoothingEnabled'; } - else if (this.context.oImageSmoothingEnabled) { + else if (this.context.oImageSmoothingEnabled) + { this.smoothProperty = 'oImageSmoothingEnabled'; } - else if (this.context.msImageSmoothingEnabled) { + else if (this.context.msImageSmoothingEnabled) + { this.smoothProperty = 'msImageSmoothingEnabled'; } @@ -193,10 +203,12 @@ * @memberof CanvasRenderer# */ backgroundColor: { - get: function () { + get: function () + { return this._backgroundColor; }, - set: function (val) { + set: function (val) + { this._backgroundColor = val; this._backgroundColorString = utils.hex2string(val); } @@ -208,7 +220,8 @@ * * @param object {DisplayObject} the object to be rendered */ -CanvasRenderer.prototype.render = function (object) { +CanvasRenderer.prototype.render = function (object) +{ object.updateTransform(); this.context.setTransform(1,0,0,1,0,0); @@ -218,16 +231,20 @@ this.currentBlendMode = CONST.blendModes.NORMAL; this.context.globalCompositeOperation = this.blendModes[CONST.blendModes.NORMAL]; - if (navigator.isCocoonJS && this.view.screencanvas) { + if (navigator.isCocoonJS && this.view.screencanvas) + { this.context.fillStyle = 'black'; this.context.clear(); } - if (this.clearBeforeRender) { - if (this.transparent) { + if (this.clearBeforeRender) + { + if (this.transparent) + { this.context.clearRect(0, 0, this.width, this.height); } - else { + else + { this.context.fillStyle = this._backgroundColorString; this.context.fillRect(0, 0, this.width , this.height); } @@ -241,8 +258,10 @@ * * @param [removeView=false] {boolean} Removes the Canvas element from the DOM. */ -CanvasRenderer.prototype.destroy = function (removeView) { - if (removeView && this.view.parent) { +CanvasRenderer.prototype.destroy = function (removeView) +{ + if (removeView && this.view.parent) + { this.view.parent.removeChild(this.view); } @@ -257,14 +276,16 @@ * @param width {number} the new width of the canvas view * @param height {number} the new height of the canvas view */ -CanvasRenderer.prototype.resize = function (width, height) { +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) { + if (this.autoResize) + { this.view.style.width = this.width / this.resolution + 'px'; this.view.style.height = this.height / this.resolution + 'px'; } @@ -276,7 +297,8 @@ * @param displayObject {DisplayObject} The displayObject to render * @private */ -CanvasRenderer.prototype.renderDisplayObject = function (displayObject) { +CanvasRenderer.prototype.renderDisplayObject = function (displayObject) +{ displayObject.renderCanvas(this); }; @@ -285,11 +307,14 @@ * * @private */ -CanvasRenderer.prototype._mapBlendModes = function () { - if (!this.blendModes) { +CanvasRenderer.prototype._mapBlendModes = function () +{ + if (!this.blendModes) + { this.blendModes = {}; - if (utils.canUseNewCanvasBlendModes()) { + if (utils.canUseNewCanvasBlendModes()) + { this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? this.blendModes[CONST.blendModes.MULTIPLY] = 'multiply'; @@ -308,7 +333,8 @@ this.blendModes[CONST.blendModes.COLOR] = 'color'; this.blendModes[CONST.blendModes.LUMINOSITY] = 'luminosity'; } - else { + else + { // this means that the browser does not support the cool new blend modes in canvas 'cough' ie 'cough' this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? diff --git a/src/core/renderers/canvas/utils/CanvasBuffer.js b/src/core/renderers/canvas/utils/CanvasBuffer.js index ebe5d47..b183a66 100644 --- a/src/core/renderers/canvas/utils/CanvasBuffer.js +++ b/src/core/renderers/canvas/utils/CanvasBuffer.js @@ -6,7 +6,8 @@ * @param width {number} the width for the newly created canvas * @param height {number} the height for the newly created canvas */ -function CanvasBuffer(width, height) { +function CanvasBuffer(width, height) +{ /** * The Canvas object that belongs to this CanvasBuffer. * @@ -36,10 +37,12 @@ * @memberof CanvasBuffer# */ width: { - get: function () { + get: function () + { return this.canvas.width; }, - set: function (val) { + set: function (val) + { this.canvas.width = val; } }, @@ -50,10 +53,12 @@ * @memberof CanvasBuffer# */ height: { - get: function () { + get: function () + { return this.canvas.height; }, - set: function (val) { + set: function (val) + { this.canvas.height = val; } } @@ -64,7 +69,8 @@ * * @private */ -CanvasBuffer.prototype.clear = function () { +CanvasBuffer.prototype.clear = function () +{ this.context.setTransform(1, 0, 0, 1, 0, 0); this.context.clearRect(0,0, this.canvas.width, this.canvas.height); }; @@ -75,7 +81,8 @@ * @param width {number} the new width of the canvas * @param height {number} the new height of the canvas */ -CanvasBuffer.prototype.resize = function (width, height) { +CanvasBuffer.prototype.resize = function (width, height) +{ this.canvas.width = width; this.canvas.height = height; }; diff --git a/src/core/renderers/canvas/utils/CanvasGraphics.js b/src/core/renderers/canvas/utils/CanvasGraphics.js index c7eaa2a..3f2a91f 100644 --- a/src/core/renderers/canvas/utils/CanvasGraphics.js +++ b/src/core/renderers/canvas/utils/CanvasGraphics.js @@ -13,15 +13,18 @@ * @param graphics {Graphics} the actual graphics object to render * @param context {CanvasRenderingContext2D} the 2d drawing method of the canvas */ -CanvasGraphics.renderGraphics = function (graphics, context) { +CanvasGraphics.renderGraphics = function (graphics, context) +{ var worldAlpha = graphics.worldAlpha; - if (graphics.dirty) { + if (graphics.dirty) + { this.updateGraphicsTint(graphics); graphics.dirty = false; } - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; @@ -30,69 +33,82 @@ context.lineWidth = data.lineWidth; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { context.beginPath(); var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } - if (shape.closed) { + if (shape.closed) + { context.lineTo(points[0], points[1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fillRect(shape.x, shape.y, shape.width, shape.height); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.strokeRect(shape.x, shape.y, shape.width, shape.height); } } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.beginPath(); context.arc(shape.x, shape.y, shape.radius,0,2*Math.PI); context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas var w = shape.width * 2; @@ -119,18 +135,21 @@ context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; var width = shape.width; @@ -152,13 +171,15 @@ context.quadraticCurveTo(rx, ry, rx, ry + radius); context.closePath(); - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); @@ -174,45 +195,54 @@ * @param graphics {Graphics} the graphics which will be used as a mask * @param context {CanvasRenderingContext2D} the context 2d method of the canvas */ -CanvasGraphics.renderGraphicsMask = function (graphics, context) { +CanvasGraphics.renderGraphicsMask = function (graphics, context) +{ var len = graphics.graphicsData.length; - if (len === 0) { + if (len === 0) + { return; } context.beginPath(); - for (var i = 0; i < len; i++) { + for (var i = 0; i < len; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { context.rect(shape.x, shape.y, shape.width, shape.height); context.closePath(); } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.arc(shape.x, shape.y, shape.radius, 0, 2 * Math.PI); context.closePath(); } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas @@ -237,7 +267,8 @@ context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); context.closePath(); } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; @@ -262,8 +293,10 @@ } }; -CanvasGraphics.updateGraphicsTint = function (graphics) { - if (graphics.tint === 0xFFFFFF) { +CanvasGraphics.updateGraphicsTint = function (graphics) +{ + if (graphics.tint === 0xFFFFFF) + { return; } @@ -271,7 +304,8 @@ var tintG = (graphics.tint >> 8 & 0xFF) / 255; var tintB = (graphics.tint & 0xFF)/ 255; - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var fillColor = data.fillColor | 0; diff --git a/src/core/renderers/canvas/utils/CanvasMaskManager.js b/src/core/renderers/canvas/utils/CanvasMaskManager.js index e04a733..9827d36 100644 --- a/src/core/renderers/canvas/utils/CanvasMaskManager.js +++ b/src/core/renderers/canvas/utils/CanvasMaskManager.js @@ -6,7 +6,8 @@ * @class * @namespace PIXI */ -function CanvasMaskManager() {} +function CanvasMaskManager() +{} CanvasMaskManager.prototype.constructor = CanvasMaskManager; module.exports = CanvasMaskManager; @@ -17,7 +18,8 @@ * @param maskData {object} the maskData that will be pushed * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.pushMask = function (maskData, renderer) { +CanvasMaskManager.prototype.pushMask = function (maskData, renderer) +{ renderer.context.save(); var cacheAlpha = maskData.alpha; @@ -45,6 +47,7 @@ * * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.popMask = function (renderer) { +CanvasMaskManager.prototype.popMask = function (renderer) +{ renderer.context.restore(); }; diff --git a/src/core/renderers/canvas/utils/CanvasTinter.js b/src/core/renderers/canvas/utils/CanvasTinter.js index 17e0529..d2fb1bc 100644 --- a/src/core/renderers/canvas/utils/CanvasTinter.js +++ b/src/core/renderers/canvas/utils/CanvasTinter.js @@ -14,7 +14,8 @@ * @param color {number} the color to use to tint the sprite with * @return {HTMLCanvasElement} The tinted canvas */ -CanvasTinter.getTintedTexture = function (sprite, color) { +CanvasTinter.getTintedTexture = function (sprite, color) +{ var texture = sprite.texture; color = CanvasTinter.roundColor(color); @@ -23,7 +24,8 @@ texture.tintCache = texture.tintCache || {}; - if (texture.tintCache[stringColor]) { + if (texture.tintCache[stringColor]) + { return texture.tintCache[stringColor]; } @@ -33,14 +35,16 @@ //CanvasTinter.tintWithPerPixel(texture, stringColor, canvas); CanvasTinter.tintMethod(texture, color, canvas); - if (CanvasTinter.convertTintToImage) { + if (CanvasTinter.convertTintToImage) + { // is this better? var tintImage = new Image(); tintImage.src = canvas.toDataURL(); texture.tintCache[stringColor] = tintImage; } - else { + else + { texture.tintCache[stringColor] = canvas; // if we are not converting the texture to an image then we need to lose the reference to the canvas CanvasTinter.canvas = null; @@ -56,7 +60,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithMultiply = function (texture, color, canvas) { +CanvasTinter.tintWithMultiply = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -104,7 +109,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithOverlay = function (texture, color, canvas) { +CanvasTinter.tintWithOverlay = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -139,7 +145,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithPerPixel = function (texture, color, canvas) { +CanvasTinter.tintWithPerPixel = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -167,7 +174,8 @@ var pixels = pixelData.data; - for (var i = 0; i < pixels.length; i += 4) { + for (var i = 0; i < pixels.length; i += 4) + { pixels[i+0] *= r; pixels[i+1] *= g; pixels[i+2] *= b; @@ -181,7 +189,8 @@ * * @param color {number} the color to round, should be a hex color */ -CanvasTinter.roundColor = function (color) { +CanvasTinter.roundColor = function (color) +{ var step = CanvasTinter.cacheStepsPerColorChannel; var rgbValues = utils.hex2rgb(color); diff --git a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js index 9f2f89a..35edbaf 100644 --- a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js +++ b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLBlendModeManager(renderer) { +function WebGLBlendModeManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -23,8 +24,10 @@ * * @param blendMode {number} the blendMode, should be a Pixi const, such as BlendModes.ADD */ -WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) { - if (this.currentBlendMode === blendMode) { +WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) +{ + if (this.currentBlendMode === blendMode) + { return false; } diff --git a/src/core/renderers/webgl/managers/WebGLFilterManager.js b/src/core/renderers/webgl/managers/WebGLFilterManager.js index 1179258..2dac048 100644 --- a/src/core/renderers/webgl/managers/WebGLFilterManager.js +++ b/src/core/renderers/webgl/managers/WebGLFilterManager.js @@ -7,7 +7,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLFilterManager(renderer) { +function WebGLFilterManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -32,7 +33,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.texturePool.length = 0; self.initShaderBuffers(); }); @@ -46,7 +48,8 @@ * @param renderer {WebGLRenderer} * @param buffer {ArrayBuffer} */ -WebGLFilterManager.prototype.begin = function (buffer) { +WebGLFilterManager.prototype.begin = function (buffer) +{ this.defaultShader = this.renderer.shaderManager.defaultShader; this.width = this.renderer.projection.x * 2; @@ -60,7 +63,8 @@ * * @param filterBlock {object} the filter that will be pushed to the current filter stack */ -WebGLFilterManager.prototype.pushFilter = function (filterBlock) { +WebGLFilterManager.prototype.pushFilter = function (filterBlock) +{ var gl = this.renderer.gl; var projection = this.renderer.projection; @@ -78,10 +82,12 @@ this.offsetY += filterBlock._filterArea.y; var texture = this.texturePool.pop(); - if (!texture) { + if (!texture) + { texture = new FilterTexture(this.renderer.gl, this.width, this.height); } - else { + else + { texture.resize(this.width, this.height); } @@ -98,29 +104,35 @@ var localX = filterArea.x, localY = filterArea.y; - if (filterArea.x < 0) { + if (filterArea.x < 0) + { filterArea.width += filterArea.x; filterArea.x = 0; } - if (filterArea.y < 0) { + if (filterArea.y < 0) + { filterArea.height += filterArea.y; filterArea.y = 0; } - if (localX + filterArea.width > this.width) { + if (localX + filterArea.width > this.width) + { filterArea.width = this.width - localX; } - if (localY + filterArea.height > this.height) { + if (localY + filterArea.height > this.height) + { filterArea.height = this.height - localY; } - if (filterArea.width < 0) { + if (filterArea.width < 0) + { filterArea.width = 0; } - if (filterArea.height < 0) { + if (filterArea.height < 0) + { filterArea.height = 0; } @@ -154,7 +166,8 @@ * Removes the last filter from the filter stack and doesn't return it. * */ -WebGLFilterManager.prototype.popFilter = function () { +WebGLFilterManager.prototype.popFilter = function () +{ var gl = this.renderer.gl; var filterBlock = this.filterStack.pop(); @@ -163,7 +176,8 @@ var projection = this.renderer.projection; var offset = this.renderer.offset; - if (filterBlock.filterPasses.length > 1) { + if (filterBlock.filterPasses.length > 1) + { gl.viewport(0, 0, filterArea.width, filterArea.height); gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); @@ -193,7 +207,8 @@ var inputTexture = texture; var outputTexture = this.texturePool.pop(); - if (!outputTexture) { + if (!outputTexture) + { outputTexture = new FilterTexture(this.renderer.gl, this.width, this.height); } outputTexture.resize(this.width, this.height); @@ -204,7 +219,8 @@ gl.disable(gl.BLEND); - for (var i = 0; i < filterBlock.filterPasses.length-1; i++) { + for (var i = 0; i < filterBlock.filterPasses.length-1; i++) + { var filterPass = filterBlock.filterPasses[i]; gl.bindFramebuffer(gl.FRAMEBUFFER, outputTexture.frameBuffer ); @@ -243,10 +259,12 @@ var buffer = this.buffer; // time to render the filters texture to the previous scene - if (this.filterStack.length === 0) { + if (this.filterStack.length === 0) + { gl.colorMask(true, true, true, true);//this.transparent); } - else { + else + { var currentFilter = this.filterStack[this.filterStack.length-1]; filterArea = currentFilter._filterArea; @@ -332,13 +350,15 @@ * @param width {number} the horizontal range of the filter * @param height {number} the vertical range of the filter */ -WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) { +WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) +{ // use program var gl = this.renderer.gl; var shader = filter.shaders[gl.id]; - if (!shader) { + if (!shader) + { shader = new Shader(gl); shader.fragmentSrc = filter.fragmentSrc; @@ -356,7 +376,8 @@ gl.uniform2f(shader.projectionVector, width/2, -height/2); gl.uniform2f(shader.offsetVector, 0,0); - if (filter.uniforms.dimensions) { + 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]; @@ -386,7 +407,8 @@ * Initialises the shader buffers. * */ -WebGLFilterManager.prototype.initShaderBuffers = function () { +WebGLFilterManager.prototype.initShaderBuffers = function () +{ var gl = this.renderer.gl; // create some buffers @@ -432,7 +454,8 @@ * Destroys the filter and removes it from the filter stack. * */ -WebGLFilterManager.prototype.destroy = function () { +WebGLFilterManager.prototype.destroy = function () +{ var gl = this.renderer.gl; this.filterStack = null; @@ -441,7 +464,8 @@ this.offsetY = 0; // destroy textures - for (var i = 0; i < this.texturePool.length; i++) { + for (var i = 0; i < this.texturePool.length; i++) + { this.texturePool[i].destroy(); } diff --git a/src/core/renderers/webgl/managers/WebGLManager.js b/src/core/renderers/webgl/managers/WebGLManager.js index 9d47b5c..c30cd51 100644 --- a/src/core/renderers/webgl/managers/WebGLManager.js +++ b/src/core/renderers/webgl/managers/WebGLManager.js @@ -3,7 +3,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLManager(renderer) { +function WebGLManager(renderer) +{ /** * The renderer this manager works for. * @@ -15,6 +16,7 @@ WebGLManager.prototype.constructor = WebGLManager; module.exports = WebGLManager; -WebGLManager.prototype.destroy = function () { +WebGLManager.prototype.destroy = function () +{ this.renderer = null; }; diff --git a/src/core/renderers/webgl/managers/WebGLMaskManager.js b/src/core/renderers/webgl/managers/WebGLMaskManager.js index 2f90b64..e568812 100644 --- a/src/core/renderers/webgl/managers/WebGLMaskManager.js +++ b/src/core/renderers/webgl/managers/WebGLMaskManager.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLMaskManager(renderer) { +function WebGLMaskManager(renderer) +{ WebGLManager.call(this, renderer); } @@ -19,12 +20,15 @@ * * @param maskData {any[]} */ -WebGLMaskManager.prototype.pushMask = function (maskData) { - if (maskData.dirty) { +WebGLMaskManager.prototype.pushMask = function (maskData) +{ + if (maskData.dirty) + { WebGLGraphics.updateGraphics(maskData, this.renderer.gl); } - if (!maskData._webGL[this.renderer.gl.id].data.length) { + if (!maskData._webGL[this.renderer.gl.id].data.length) + { return; } @@ -36,6 +40,7 @@ * * @param maskData {any[]} */ -WebGLMaskManager.prototype.popMask = function (maskData) { +WebGLMaskManager.prototype.popMask = function (maskData) +{ this.renderer.stencilManager.popStencil(maskData, maskData._webGL[this.renderer.gl.id].data[0], this.renderer); }; diff --git a/src/core/renderers/webgl/managers/WebGLShaderManager.js b/src/core/renderers/webgl/managers/WebGLShaderManager.js index fef071c..90c6477 100644 --- a/src/core/renderers/webgl/managers/WebGLShaderManager.js +++ b/src/core/renderers/webgl/managers/WebGLShaderManager.js @@ -10,7 +10,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLShaderManager(renderer) { +function WebGLShaderManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -28,7 +29,8 @@ */ this.tempAttribState = []; - for (var i = 0; i < this.maxAttibs; i++) { + for (var i = 0; i < this.maxAttibs; i++) + { this.attribState[i] = false; } @@ -66,7 +68,8 @@ // listen for context and update necessary shaders var self = this; - this.renderer.on('context', function (event) { + this.renderer.on('context', function (event) + { var gl = event.data; // this shader is used for rendering primitives @@ -97,29 +100,36 @@ * * @param attribs {Array} attribs */ -WebGLShaderManager.prototype.setAttribs = function (attribs) { +WebGLShaderManager.prototype.setAttribs = function (attribs) +{ // reset temp state var i; - for (i = 0; i < this.tempAttribState.length; i++) { + for (i = 0; i < this.tempAttribState.length; i++) + { this.tempAttribState[i] = false; } // set the new attribs - for (var a in attribs) { + for (var a in attribs) + { this.tempAttribState[attribs[a]] = true; } var gl = this.renderer.gl; - for (i = 0; i < this.attribState.length; i++) { - if (this.attribState[i] !== this.tempAttribState[i]) { + for (i = 0; i < this.attribState.length; i++) + { + if (this.attribState[i] !== this.tempAttribState[i]) + { this.attribState[i] = this.tempAttribState[i]; - if (this.attribState[i]) { + if (this.attribState[i]) + { gl.enableVertexAttribArray(i); } - else { + else + { gl.disableVertexAttribArray(i); } } @@ -131,8 +141,10 @@ * * @param shader {Any} */ -WebGLShaderManager.prototype.setShader = function (shader) { - if (this._currentId === shader.uuid) { +WebGLShaderManager.prototype.setShader = function (shader) +{ + if (this._currentId === shader.uuid) + { return false; } @@ -150,7 +162,8 @@ * Destroys this object. * */ -WebGLShaderManager.prototype.destroy = function () { +WebGLShaderManager.prototype.destroy = function () +{ this.attribState = null; this.tempAttribState = null; diff --git a/src/core/renderers/webgl/managers/WebGLStencilManager.js b/src/core/renderers/webgl/managers/WebGLStencilManager.js index 9ec6398..4cb0134 100644 --- a/src/core/renderers/webgl/managers/WebGLStencilManager.js +++ b/src/core/renderers/webgl/managers/WebGLStencilManager.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLStencilManager(renderer) { +function WebGLStencilManager(renderer) +{ WebGLManager.call(this, renderer); this.stencilStack = []; @@ -24,12 +25,14 @@ * @param graphics {Graphics} * @param webGLData {any[]} */ -WebGLStencilManager.prototype.pushStencil = function (graphics, webGLData) { +WebGLStencilManager.prototype.pushStencil = function (graphics, webGLData) +{ var gl = this.renderer.gl; this.bindGraphics(graphics, webGLData, this.renderer); - if (this.stencilStack.length === 0) { + if (this.stencilStack.length === 0) + { gl.enable(gl.STENCIL_TEST); gl.clear(gl.STENCIL_BUFFER_BIT); this.reverse = true; @@ -47,14 +50,17 @@ // draw the triangle strip! - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } @@ -62,31 +68,38 @@ // draw a quad to increment.. gl.drawElements(gl.TRIANGLE_FAN, 4, gl.UNSIGNED_SHORT, ( webGLData.indices.length - 4 ) * 2 ); - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); } this.reverse = !this.reverse; } - else { - if (!this.reverse) { + else + { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } - else { + 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) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); } } @@ -103,7 +116,8 @@ * @param graphics {Graphics} * @param webGLData {Array} */ -WebGLStencilManager.prototype.bindGraphics = function (graphics, webGLData) { +WebGLStencilManager.prototype.bindGraphics = function (graphics, webGLData) +{ //if (this._currentGraphics === graphics)return; this._currentGraphics = graphics; @@ -114,7 +128,8 @@ offset = this.renderer.offset, shader;// = this.renderer.shaderManager.primitiveShader; - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { shader = this.renderer.shaderManager.complexPrimitiveShader; this.renderer.shaderManager.setShader(shader); @@ -141,7 +156,8 @@ // set the index buffer! gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, webGLData.indexBuffer); } - else { + else + { //this.renderer.shaderManager.activatePrimitiveShader(); shader = this.renderer.shaderManager.primitiveShader; this.renderer.shaderManager.setShader( shader ); @@ -154,7 +170,7 @@ gl.uniform2f(shader.uniforms.offsetVector._location, -offset.x, -offset.y); gl.uniform3fv(shader.uniforms.tint._location, utils.hex2rgb(graphics.tint)); - + gl.uniform1f(shader.uniforms.alpha._location, graphics.worldAlpha); @@ -172,19 +188,22 @@ * @param graphics {Graphics} * @param webGLData {Array} */ -WebGLStencilManager.prototype.popStencil = function (graphics, webGLData) { +WebGLStencilManager.prototype.popStencil = function (graphics, webGLData) +{ var gl = this.renderer.gl; this.stencilStack.pop(); this.count--; - if (this.stencilStack.length === 0) { + if (this.stencilStack.length === 0) + { // the stack is empty! gl.disable(gl.STENCIL_TEST); } - else { + else + { var level = this.count; @@ -192,14 +211,17 @@ gl.colorMask(false, false, false, false); - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { this.reverse = !this.reverse; - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } @@ -213,31 +235,38 @@ // draw the triangle strip! gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); - if (!this.reverse) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); } } - else { + else + { // console.log("<<>>") - if (!this.reverse) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } - else { + 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) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); } } @@ -253,7 +282,8 @@ * Destroys the mask stack. * */ -WebGLStencilManager.prototype.destroy = function () { +WebGLStencilManager.prototype.destroy = function () +{ this.renderer = null; this.stencilStack = null; }; diff --git a/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js b/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js index 913ba5e..1ea7d19 100644 --- a/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js +++ b/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function ComplexPrimitiveShader(gl) { +function ComplexPrimitiveShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -24,7 +25,8 @@ 'uniform float flipY;', 'varying vec4 vColor;', - 'void main(void) {', + '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);', @@ -37,7 +39,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = vColor;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/FastShader.js b/src/core/renderers/webgl/shaders/FastShader.js index bd2e29a..2e5e060 100644 --- a/src/core/renderers/webgl/shaders/FastShader.js +++ b/src/core/renderers/webgl/shaders/FastShader.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function FastShader(gl) { +function FastShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -28,7 +29,8 @@ 'const vec2 center = vec2(-1.0, 1.0);', - 'void main(void) {', + 'void main(void) + {', ' vec2 v;', ' vec2 sv = aVertexPosition * aScale;', ' v.x = (sv.x) * cos(aRotation) - (sv.y) * sin(aRotation);', @@ -49,7 +51,8 @@ 'uniform sampler2D uSampler;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/PrimitiveShader.js b/src/core/renderers/webgl/shaders/PrimitiveShader.js index 6f25409..a25f54f 100644 --- a/src/core/renderers/webgl/shaders/PrimitiveShader.js +++ b/src/core/renderers/webgl/shaders/PrimitiveShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function PrimitiveShader(gl) { +function PrimitiveShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -23,7 +24,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + '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);', @@ -36,7 +38,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = vColor;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/Shader.js b/src/core/renderers/webgl/shaders/Shader.js index f8964f5..fd75ef5 100644 --- a/src/core/renderers/webgl/shaders/Shader.js +++ b/src/core/renderers/webgl/shaders/Shader.js @@ -6,7 +6,8 @@ * @param [fragmentSrc] {string} The source of the fragment shader. * @param [vertexSrc] {string} The source of the vertex shader. */ -function Shader(gl, vertexSrc, fragmentSrc, customUniforms, customAttributes) { +function Shader(gl, vertexSrc, fragmentSrc, customUniforms, customAttributes) +{ /** * @member {number} * @readonly @@ -33,7 +34,8 @@ dimensions: { type: '4f', value: new Float32Array(4) } }; - for (var u in customUniforms) { + for (var u in customUniforms) + { this.uniforms[u] = customUniforms[u]; } @@ -43,7 +45,8 @@ aColor: 0 }; - for (var a in customAttributes) { + for (var a in customAttributes) + { this.attributes[a] = customAttributes[a]; } @@ -66,7 +69,8 @@ 'const vec2 center = vec2(-1.0, 1.0);', - 'void main(void) {', + 'void main(void) + {', ' gl_Position = vec4( ((aVertexPosition + offsetVector) / projectionVector) + center , 0.0, 1.0);', ' vTextureCoord = aTextureCoord;', ' vColor = vec4(aColor.rgb * aColor.a, aColor.a);', @@ -85,7 +89,8 @@ 'uniform sampler2D uSampler;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;', '}' ].join('\n'); @@ -96,7 +101,8 @@ Shader.prototype.constructor = Shader; module.exports = Shader; -Shader.prototype.init = function () { +Shader.prototype.init = function () +{ this.compile(); this.gl.useProgram(this.program); @@ -105,14 +111,18 @@ this.cacheAttributeLocations(Object.keys(this.attributes)); }; -Shader.prototype.cacheUniformLocations = function (keys) { - for (var i = 0; i < keys.length; ++i) { +Shader.prototype.cacheUniformLocations = function (keys) +{ + for (var i = 0; i < keys.length; ++i) + { this.uniforms[keys[i]]._location = this.gl.getUniformLocation(this.program, keys[i]); } }; -Shader.prototype.cacheAttributeLocations = function (keys) { - for (var i = 0; i < keys.length; ++i) { +Shader.prototype.cacheAttributeLocations = function (keys) +{ + for (var i = 0; i < keys.length; ++i) + { this.attributes[keys[i]] = this.gl.getAttribLocation(this.program, keys[i]); } @@ -124,14 +134,16 @@ // 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.attributes.aColor === -1) { + // if (this.attributes.aColor === -1) + { // this.attributes.aColor = 2; // } // End worst hack eva // }; -Shader.prototype.compile = function () { +Shader.prototype.compile = function () +{ var gl = this.gl; var glVertShader = this._glCompile(gl.VERTEX_SHADER, this.vertexSrc); @@ -144,13 +156,15 @@ gl.linkProgram(program); // if linking fails, then log and cleanup - if (!gl.getProgramParameter(program, gl.LINK_STATUS)) { + if (!gl.getProgramParameter(program, gl.LINK_STATUS)) + { window.console.error('Pixi.js Error: Could not initialize shader.'); window.console.error('gl.VALIDATE_STATUS', gl.getProgramParameter(program, gl.VALIDATE_STATUS)); window.console.error('gl.getError()', gl.getError()); // if there is a program info log, log it - if (gl.getProgramInfoLog(program) !== '') { + if (gl.getProgramInfoLog(program) !== '') + { window.console.warn('Pixi.js Warning: gl.getProgramInfoLog()', gl.getProgramInfoLog(program)); } @@ -165,18 +179,21 @@ return (this.program = program); }; -Shader.prototype.syncUniforms = function () { +Shader.prototype.syncUniforms = function () +{ var gl = this.gl; this.textureCount = 1; - for (var key in this.uniforms) { + for (var key in this.uniforms) + { var uniform = this.uniforms[key], location = uniform._location, value = uniform.value, i, il; - switch (uniform.type) { + switch (uniform.type) + { // single int value case 'i': case '1i': @@ -282,7 +299,8 @@ // a Color Value case 'c': - if (typeof value === 'number') { + if (typeof value === 'number') + { value = utils.hex2rgb(value); } @@ -311,11 +329,13 @@ // array of 2D Point objects case 'v2v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(2 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 2] = value[i].x; uniform._array[i * 2 + 1] = value[i].y; } @@ -325,11 +345,13 @@ // array of 3D Point objects case 'v3v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(3 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 3] = value[i].x; uniform._array[i * 3 + 1] = value[i].y; uniform._array[i * 3 + 2] = value[i].z; @@ -341,11 +363,13 @@ // array of 4D Point objects case 'v4v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(4 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 4] = value[i].x; uniform._array[i * 4 + 1] = value[i].y; uniform._array[i * 4 + 2] = value[i].z; @@ -359,7 +383,8 @@ // PIXI.Texture case 't': case 'sampler2D': - if (!uniform.value || !uniform.value.baseTexture || !uniform.value.baseTexture.hasLoaded) { + if (!uniform.value || !uniform.value.baseTexture || !uniform.value.baseTexture.hasLoaded) + { break; } @@ -376,7 +401,8 @@ this.textureCount++; // initialize the texture if we haven't yet - if (!uniform._init) { + if (!uniform._init) + { this.initSampler2D(uniform); uniform._init = true; @@ -394,11 +420,13 @@ * Initialises a Sampler2D uniform (which may only be available later on after initUniforms once the texture has loaded) * */ -Shader.prototype.initSampler2D = function (uniform) { +Shader.prototype.initSampler2D = function (uniform) +{ var gl = this.gl; // Extended texture data - if (uniform.textureData) { + if (uniform.textureData) + { var data = uniform.textureData; // GLTexture = mag linear, min linear_mipmap_linear, wrap repeat + gl.generateMipmap(gl.TEXTURE_2D); @@ -417,14 +445,16 @@ var wrapT = (data.wrapT) ? data.wrapT : gl.CLAMP_TO_EDGE; var format = (data.luminance) ? gl.LUMINANCE : gl.RGBA; - if (data.repeat) { + if (data.repeat) + { wrapS = gl.REPEAT; wrapT = gl.REPEAT; } gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, !!data.flipY); - if (data.width) { + if (data.width) + { var width = (data.width) ? data.width : 512; var height = (data.height) ? data.height : 2; var border = (data.border) ? data.border : 0; @@ -432,7 +462,8 @@ // 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 { + 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); } @@ -448,7 +479,8 @@ * Destroys the shader. * */ -Shader.prototype.destroy = function () { +Shader.prototype.destroy = function () +{ this.gl.deleteProgram(this.program); this.gl = null; @@ -459,13 +491,15 @@ this.fragmentSrc = null; }; -Shader.prototype._glCompile = function (type, src) { +Shader.prototype._glCompile = function (type, src) +{ var shader = this.gl.createShader(type); this.gl.shaderSource(shader, src); this.gl.compileShader(shader); - if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) { + if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) + { window.console.log(this.gl.getShaderInfoLog(shader)); return null; } diff --git a/src/core/renderers/webgl/shaders/StripShader.js b/src/core/renderers/webgl/shaders/StripShader.js index 193f6e1..a7abcc6 100644 --- a/src/core/renderers/webgl/shaders/StripShader.js +++ b/src/core/renderers/webgl/shaders/StripShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function StripShader(gl) { +function StripShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -20,7 +21,8 @@ 'varying vec2 vTextureCoord;', - 'void main(void) {', + '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);', @@ -36,7 +38,8 @@ 'varying vec2 vTextureCoord;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vec2(vTextureCoord.x, vTextureCoord.y)) * alpha;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/utils/FilterTexture.js b/src/core/renderers/webgl/utils/FilterTexture.js index d2c8423..4433d44 100644 --- a/src/core/renderers/webgl/utils/FilterTexture.js +++ b/src/core/renderers/webgl/utils/FilterTexture.js @@ -8,7 +8,8 @@ * @param height {number} the vertical range of the filter * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values */ -function FilterTexture(gl, width, height, scaleMode) { +function FilterTexture(gl, width, height, scaleMode) +{ /** * @member {WebGLContext} */ @@ -59,7 +60,8 @@ * Clears the filter texture. * */ -FilterTexture.prototype.clear = function () { +FilterTexture.prototype.clear = function () +{ var gl = this.gl; gl.clearColor(0,0,0, 0); @@ -72,8 +74,10 @@ * @param width {number} the new width of the texture * @param height {number} the new height of the texture */ -FilterTexture.prototype.resize = function (width, height) { - if (this.width === width && this.height === height) { +FilterTexture.prototype.resize = function (width, height) +{ + if (this.width === width && this.height === height) + { return; } @@ -96,7 +100,8 @@ * Destroys the filter texture. * */ -FilterTexture.prototype.destroy = function () { +FilterTexture.prototype.destroy = function () +{ var gl = this.gl; gl.deleteFramebuffer( this.frameBuffer ); gl.deleteTexture( this.texture ); diff --git a/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js b/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js index c4721e9..a63f4d7 100644 --- a/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js +++ b/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js @@ -14,7 +14,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this sprite batch works for. */ -function WebGLFastSpriteBatch(renderer) { +function WebGLFastSpriteBatch(renderer) +{ /** * The renderer instance this sprite batch operates on. * @@ -91,7 +92,8 @@ */ this.lastIndexCount = 0; - for (var i=0, j=0; i < numIndices; i += 6, j += 4) { + 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; @@ -144,7 +146,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.setupContext(); }); } @@ -157,7 +160,8 @@ * * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLFastSpriteBatch.prototype.setupContext = function () { +WebGLFastSpriteBatch.prototype.setupContext = function () +{ var gl = this.renderer.gl; // create a couple of buffers @@ -177,7 +181,8 @@ /** * @param spriteBatch {SpriteBatch} The SpriteBatch container to prepare for. */ -WebGLFastSpriteBatch.prototype.begin = function (spriteBatch) { +WebGLFastSpriteBatch.prototype.begin = function (spriteBatch) +{ this.shader = this.renderer.shaderManager.fastShader; this.matrix = spriteBatch.worldTransform.toArray(true); @@ -187,33 +192,38 @@ /** */ -WebGLFastSpriteBatch.prototype.end = function () { +WebGLFastSpriteBatch.prototype.end = function () +{ this.flush(); }; /** * @param spriteBatch {SpriteBatch} The SpriteBatch container to render. */ -WebGLFastSpriteBatch.prototype.render = function (spriteBatch) { +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) { + if (!sprite.texture._uvs) + { return; } this.currentBaseTexture = sprite.texture.baseTexture; // check blend mode - if (sprite.blendMode !== this.renderer.blendModeManager.currentBlendMode) { + if (sprite.blendMode !== this.renderer.blendModeManager.currentBlendMode) + { this.flush(); this.renderer.blendModeManager.setBlendMode(sprite.blendMode); } - for (var i=0,j= children.length; i= this.size) { + if (this.currentBatchSize >= this.size) + { this.flush(); } }; @@ -362,29 +379,35 @@ /** * */ -WebGLFastSpriteBatch.prototype.flush = function () { +WebGLFastSpriteBatch.prototype.flush = function () +{ // If the batch is length 0 then return as there is nothing to draw - if (this.currentBatchSize === 0) { + if (this.currentBatchSize === 0) + { return; } var gl = this.renderer.gl; // bind the current texture - if (!this.currentBaseTexture._glTextures[gl.id]) { + if (!this.currentBaseTexture._glTextures[gl.id]) + { this.renderer.updateTexture(this.currentBaseTexture, gl); } //TODO-SHOUD THIS BE ELSE??!?!?! - else { + else + { gl.bindTexture(gl.TEXTURE_2D, this.currentBaseTexture._glTextures[gl.id]); } // upload the verts to the buffer - if (this.currentBatchSize > ( this.size * 0.5 ) ) { + if (this.currentBatchSize > ( this.size * 0.5 ) ) + { gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); } - else { + else + { var view = this.vertices.subarray(0, this.currentBatchSize * this.vertByteSize); gl.bufferSubData(gl.ARRAY_BUFFER, 0, view); @@ -405,14 +428,16 @@ * Ends the batch and flushes * */ -WebGLFastSpriteBatch.prototype.stop = function () { +WebGLFastSpriteBatch.prototype.stop = function () +{ this.flush(); }; /** * */ -WebGLFastSpriteBatch.prototype.start = function () { +WebGLFastSpriteBatch.prototype.start = function () +{ var gl = this.renderer.gl; // bind the main texture diff --git a/src/core/renderers/webgl/utils/WebGLGraphics.js b/src/core/renderers/webgl/utils/WebGLGraphics.js index 55f4911..ab8f46e 100644 --- a/src/core/renderers/webgl/utils/WebGLGraphics.js +++ b/src/core/renderers/webgl/utils/WebGLGraphics.js @@ -19,7 +19,8 @@ * @param graphics {Graphics} * @param renderer {WebGLRenderer} */ -WebGLGraphics.renderGraphics = function (graphics, renderer) {//projection, offset) { +WebGLGraphics.renderGraphics = function (graphics, renderer) {//projection, offset) +{ var gl = renderer.gl; var projection = renderer.projection, @@ -27,7 +28,8 @@ shader = renderer.shaderManager.primitiveShader, webGLData; - if (graphics.dirty) { + if (graphics.dirty) + { WebGLGraphics.updateGraphics(graphics, gl); } @@ -35,8 +37,10 @@ // This could be speeded up for sure! - for (var i = 0; i < webGL.data.length; i++) { - if (webGL.data[i].mode === 1) { + for (var i = 0; i < webGL.data.length; i++) + { + if (webGL.data[i].mode === 1) + { webGLData = webGL.data[i]; renderer.stencilManager.pushStencil(graphics, webGLData, renderer); @@ -46,7 +50,8 @@ renderer.stencilManager.popStencil(graphics, webGLData, renderer); } - else { + else + { webGLData = webGL.data[i]; @@ -84,12 +89,14 @@ * @param graphicsData {Graphics} The graphics object to update * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLGraphics.updateGraphics = function (graphics, gl) { +WebGLGraphics.updateGraphics = function (graphics, gl) +{ // get the contexts graphics object var webGL = graphics._webGL[gl.id]; // if the graphics object does not exist in the webGL context time to create it! - if (!webGL) { + if (!webGL) + { webGL = graphics._webGL[gl.id] = {lastIndex:0, data:[], gl:gl}; } @@ -99,11 +106,13 @@ var i; // if the user cleared the graphics object we will need to clear every object - if (graphics.clearDirty) { + if (graphics.clearDirty) + { graphics.clearDirty = false; // lop through and return all the webGLDatas to the object pool so than can be reused later on - for (i = 0; i < webGL.data.length; i++) { + for (i = 0; i < webGL.data.length; i++) + { var graphicsData = webGL.data[i]; graphicsData.reset(); WebGLGraphics.graphicsDataPool.push( graphicsData ); @@ -119,58 +128,72 @@ // loop through the graphics datas and construct each one.. // if the object is a complex fill then the new stencil buffer technique will be used // other wise graphics objects will be pushed into a batch.. - for (i = webGL.lastIndex; i < graphics.graphicsData.length; i++) { + for (i = webGL.lastIndex; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { // need to add the points the the graphics object.. data.points = data.shape.points.slice(); - if (data.shape.closed) { + if (data.shape.closed) + { // close the poly if the value is true! - if (data.points[0] !== data.points[data.points.length-2] || data.points[1] !== data.points[data.points.length-1]) { + if (data.points[0] !== data.points[data.points.length-2] || data.points[1] !== data.points[data.points.length-1]) + { data.points.push(data.points[0], data.points[1]); } } // MAKE SURE WE HAVE THE CORRECT TYPE.. - if (data.fill) { - if (data.points.length >= 6) { - if (data.points.length < 6 * 2) { + if (data.fill) + { + if (data.points.length >= 6) + { + if (data.points.length < 6 * 2) + { webGLData = WebGLGraphics.switchMode(webGL, 0); var canDrawUsingSimple = WebGLGraphics.buildPoly(data, webGLData); // console.log(canDrawUsingSimple); - if (!canDrawUsingSimple) { + if (!canDrawUsingSimple) + { // console.log("<>>>") webGLData = WebGLGraphics.switchMode(webGL, 1); WebGLGraphics.buildComplexPoly(data, webGLData); } } - else { + else + { webGLData = WebGLGraphics.switchMode(webGL, 1); WebGLGraphics.buildComplexPoly(data, webGLData); } } } - if (data.lineWidth > 0) { + if (data.lineWidth > 0) + { webGLData = WebGLGraphics.switchMode(webGL, 0); WebGLGraphics.buildLine(data, webGLData); } } - else { + else + { webGLData = WebGLGraphics.switchMode(webGL, 0); - if (data.type === CONST.SHAPES.RECT) { + if (data.type === CONST.SHAPES.RECT) + { WebGLGraphics.buildRectangle(data, webGLData); } - else if (data.type === CONST.SHAPES.CIRC || data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.CIRC || data.type === CONST.SHAPES.ELIP) + { WebGLGraphics.buildCircle(data, webGLData); } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { WebGLGraphics.buildRoundedRectangle(data, webGLData); } } @@ -179,10 +202,12 @@ } // upload all the dirty data... - for (i = 0; i < webGL.data.length; i++) { + for (i = 0; i < webGL.data.length; i++) + { webGLData = webGL.data[i]; - if (webGLData.dirty) { + if (webGLData.dirty) + { webGLData.upload(); } } @@ -194,18 +219,22 @@ * @param webGL {WebGLContext} * @param type {number} */ -WebGLGraphics.switchMode = function (webGL, type) { +WebGLGraphics.switchMode = function (webGL, type) +{ var webGLData; - if (!webGL.data.length) { + if (!webGL.data.length) + { webGLData = WebGLGraphics.graphicsDataPool.pop() || new WebGLGraphicsData(webGL.gl); webGLData.mode = type; webGL.data.push(webGLData); } - else { + else + { webGLData = webGL.data[webGL.data.length-1]; - if (webGLData.mode !== type || type === 1) { + if (webGLData.mode !== type || type === 1) + { webGLData = WebGLGraphics.graphicsDataPool.pop() || new WebGLGraphicsData(webGL.gl); webGLData.mode = type; webGL.data.push(webGLData); @@ -225,7 +254,8 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildRectangle = function (graphicsData, webGLData) { +WebGLGraphics.buildRectangle = function (graphicsData, webGLData) +{ // --- // // need to convert points to a nice regular data // @@ -235,7 +265,8 @@ var width = rectData.width; var height = rectData.height; - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -265,7 +296,8 @@ indices.push(vertPos, vertPos, vertPos+1, vertPos+2, vertPos+3, vertPos+3); } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = [x, y, @@ -289,7 +321,8 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildRoundedRectangle = function (graphicsData, webGLData) { +WebGLGraphics.buildRoundedRectangle = function (graphicsData, webGLData) +{ var rrectData = graphicsData.shape; var x = rrectData.x; var y = rrectData.y; @@ -305,7 +338,8 @@ recPoints = recPoints.concat(WebGLGraphics.quadraticBezierCurve(x + width, y + radius, x + width, y, x + width - radius, y)); recPoints = recPoints.concat(WebGLGraphics.quadraticBezierCurve(x + radius, y, x, y, x, y + radius)); - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -323,7 +357,8 @@ // var i = 0; - for (i = 0; i < triangles.length; i+=3) { + for (i = 0; i < triangles.length; i+=3) + { indices.push(triangles[i] + vecPos); indices.push(triangles[i] + vecPos); indices.push(triangles[i+1] + vecPos); @@ -332,12 +367,14 @@ } - for (i = 0; i < recPoints.length; i++) { + for (i = 0; i < recPoints.length; i++) + { verts.push(recPoints[i], recPoints[++i], r, g, b, alpha); } } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = recPoints; @@ -362,7 +399,8 @@ * @param toY {number} Destination point y * @return {number[]} */ -WebGLGraphics.quadraticBezierCurve = function (fromX, fromY, cpX, cpY, toX, toY) { +WebGLGraphics.quadraticBezierCurve = function (fromX, fromY, cpX, cpY, toX, toY) +{ var xa, ya, @@ -373,14 +411,16 @@ n = 20, points = []; - function getPt(n1 , n2, perc) { + function getPt(n1 , n2, perc) + { var diff = n2 - n1; return n1 + ( diff * perc ); } var j = 0; - for (var i = 0; i <= n; i++ ) { + for (var i = 0; i <= n; i++ ) + { j = i / n; // The Green Line @@ -406,7 +446,8 @@ * @param graphicsData {Graphics} The graphics object to draw * @param webGLData {object} */ -WebGLGraphics.buildCircle = function (graphicsData, webGLData) { +WebGLGraphics.buildCircle = function (graphicsData, webGLData) +{ // need to convert points to a nice regular data var circleData = graphicsData.shape; var x = circleData.x; @@ -415,11 +456,13 @@ var height; // TODO - bit hacky?? - if (graphicsData.type === CONST.SHAPES.CIRC) { + if (graphicsData.type === CONST.SHAPES.CIRC) + { width = circleData.radius; height = circleData.radius; } - else { + else + { width = circleData.width; height = circleData.height; } @@ -429,7 +472,8 @@ var i = 0; - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -444,7 +488,8 @@ indices.push(vecPos); - for (i = 0; i < totalSegs + 1 ; i++) { + for (i = 0; i < totalSegs + 1 ; i++) + { verts.push(x,y, r, g, b, alpha); verts.push(x + Math.sin(seg * i) * width, @@ -457,12 +502,14 @@ indices.push(vecPos-1); } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = []; - for (i = 0; i < totalSegs + 1; i++) { + for (i = 0; i < totalSegs + 1; i++) + { graphicsData.points.push(x + Math.sin(seg * i) * width, y + Math.cos(seg * i) * height); } @@ -481,18 +528,22 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildLine = function (graphicsData, webGLData) { +WebGLGraphics.buildLine = function (graphicsData, webGLData) +{ // TODO OPTIMISE! var i = 0; var points = graphicsData.points; - if (points.length === 0) { + if (points.length === 0) + { return; } // if the line width is an odd number add 0.5 to align to a whole pixel - if (graphicsData.lineWidth%2) { - for (i = 0; i < points.length; i++) { + if (graphicsData.lineWidth%2) + { + for (i = 0; i < points.length; i++) + { points[i] += 0.5; } } @@ -502,7 +553,8 @@ var lastPoint = new math.Point(points[points.length - 2], points[points.length - 1]); // if the first point is the last point - gonna have issues :) - if (firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) { + if (firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) + { // need to clone as we are going to slightly modify the shape.. points = points.slice(); @@ -562,7 +614,8 @@ verts.push(p1x + perpx , p1y + perpy, r, g, b, alpha); - for (i = 1; i < length-1; i++) { + for (i = 1; i < length-1; i++) + { p1x = points[(i-1)*2]; p1y = points[(i-1)*2 + 1]; @@ -599,7 +652,8 @@ denom = a1*b2 - a2*b1; - if (Math.abs(denom) < 0.1 ) { + if (Math.abs(denom) < 0.1 ) + { denom+=10.1; verts.push(p2x - perpx , p2y - perpy, @@ -618,7 +672,8 @@ pdist = (px -p2x) * (px -p2x) + (py -p2y) + (py -p2y); - if (pdist > 140 * 140) { + if (pdist > 140 * 140) + { perp3x = perpx - perp2x; perp3y = perpy - perp2y; @@ -639,7 +694,8 @@ indexCount++; } - else { + else + { verts.push(px , py); verts.push(r, g, b, alpha); @@ -672,7 +728,8 @@ indices.push(indexStart); - for (i = 0; i < indexCount; i++) { + for (i = 0; i < indexCount; i++) + { indices.push(indexStart++); } @@ -687,11 +744,13 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildComplexPoly = function (graphicsData, webGLData) { +WebGLGraphics.buildComplexPoly = function (graphicsData, webGLData) +{ //TODO - no need to copy this as it gets turned into a FLoat32Array anyways.. var points = graphicsData.points.slice(); - if (points.length < 6) { + if (points.length < 6) + { return; } @@ -711,7 +770,8 @@ var x,y; // get size.. - for (var i = 0; i < points.length; i+=2) { + for (var i = 0; i < points.length; i+=2) + { x = points[i]; y = points[i+1]; @@ -732,7 +792,8 @@ //TODO - this aint needed! var length = points.length / 2; - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { indices.push( i ); } @@ -746,10 +807,12 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildPoly = function (graphicsData, webGLData) { +WebGLGraphics.buildPoly = function (graphicsData, webGLData) +{ var points = graphicsData.points; - if (points.length < 6) { + if (points.length < 6) + { return; } // get first and last point.. figure out the middle! @@ -767,7 +830,8 @@ var triangles = utils.PolyK.Triangulate(points); - if (!triangles) { + if (!triangles) + { return false; } @@ -775,7 +839,8 @@ var i = 0; - for (i = 0; i < triangles.length; i+=3) { + for (i = 0; i < triangles.length; i+=3) + { indices.push(triangles[i] + vertPos); indices.push(triangles[i] + vertPos); indices.push(triangles[i+1] + vertPos); @@ -783,7 +848,8 @@ indices.push(triangles[i+2] + vertPos); } - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { verts.push(points[i * 2], points[i * 2 + 1], r, g, b, alpha); } diff --git a/src/core/renderers/webgl/utils/WebGLGraphicsData.js b/src/core/renderers/webgl/utils/WebGLGraphicsData.js index c56d05e..c739ba7 100644 --- a/src/core/renderers/webgl/utils/WebGLGraphicsData.js +++ b/src/core/renderers/webgl/utils/WebGLGraphicsData.js @@ -2,7 +2,8 @@ * @class * @private */ -function WebGLGraphicsData(gl) { +function WebGLGraphicsData(gl) +{ this.gl = gl; //TODO does this need to be split before uploding?? @@ -22,7 +23,8 @@ /** * */ -WebGLGraphicsData.prototype.reset = function () { +WebGLGraphicsData.prototype.reset = function () +{ this.points.length = 0; this.indices.length = 0; }; @@ -30,7 +32,8 @@ /** * */ -WebGLGraphicsData.prototype.upload = function () { +WebGLGraphicsData.prototype.upload = function () +{ var gl = this.gl; // this.lastIndex = graphics.graphicsData.length; diff --git a/src/core/renderers/webgl/utils/WebGLSpriteBatch.js b/src/core/renderers/webgl/utils/WebGLSpriteBatch.js index 96eaa52..55befbb 100644 --- a/src/core/renderers/webgl/utils/WebGLSpriteBatch.js +++ b/src/core/renderers/webgl/utils/WebGLSpriteBatch.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this sprite batch works for. */ -function WebGLSpriteBatch(renderer) { +function WebGLSpriteBatch(renderer) +{ /** * * @@ -88,7 +89,8 @@ */ this.lastIndexCount = 0; - for (var i=0, j=0; i < numIndices; i += 6, j += 4) { + 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; @@ -162,7 +164,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.setupContext(); }); } @@ -173,7 +176,8 @@ /** * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLSpriteBatch.prototype.setupContext = function () { +WebGLSpriteBatch.prototype.setupContext = function () +{ var gl = this.renderer.gl; // setup default shader @@ -198,7 +202,8 @@ /** * */ -WebGLSpriteBatch.prototype.begin = function () { +WebGLSpriteBatch.prototype.begin = function () +{ // this.shader = this.renderer.shaderManager.defaultShader; this.start(); @@ -206,19 +211,22 @@ /** */ -WebGLSpriteBatch.prototype.end = function () { +WebGLSpriteBatch.prototype.end = function () +{ this.flush(); }; /** * @param sprite {Sprite} the sprite to render when using this spritebatch */ -WebGLSpriteBatch.prototype.render = function (sprite) { +WebGLSpriteBatch.prototype.render = function (sprite) +{ var texture = sprite.texture; //TODO set blend modes.. // check texture.. - if (this.currentBatchSize >= this.size) { + if (this.currentBatchSize >= this.size) + { this.flush(); this.currentBaseTexture = texture.baseTexture; } @@ -227,7 +235,8 @@ var uvs = texture._uvs; // if the uvs have not updated then no point rendering just yet! - if (!uvs) { + if (!uvs) + { return; } @@ -237,7 +246,8 @@ var w0, w1, h0, h1; - if (texture.trim) { + 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; @@ -248,7 +258,8 @@ h0 = h1 + texture.crop.height; } - else { + else + { w0 = (texture.frame.width ) * (1-aX); w1 = (texture.frame.width ) * -aX; @@ -272,7 +283,8 @@ var colors = this.colors; var positions = this.positions; - if (this.renderer.roundPixels) { + if (this.renderer.roundPixels) + { // xy positions[index] = a * w1 + c * h1 + tx | 0; positions[index+1] = d * h1 + b * w1 + ty | 0; @@ -289,7 +301,8 @@ positions[index+15] = a * w1 + c * h0 + tx | 0; positions[index+16] = d * h0 + b * w1 + ty | 0; } - else { + else + { // xy positions[index] = a * w1 + c * h1 + tx; positions[index+1] = d * h1 + b * w1 + ty; @@ -338,11 +351,13 @@ * * @param sprite {TilingSprite} the tilingSprite to render */ -WebGLSpriteBatch.prototype.renderTilingSprite = function (tilingSprite) { +WebGLSpriteBatch.prototype.renderTilingSprite = function (tilingSprite) +{ var texture = tilingSprite.tilingTexture; // check texture.. - if (this.currentBatchSize >= this.size) { + if (this.currentBatchSize >= this.size) + { //return; this.flush(); this.currentBaseTexture = texture.baseTexture; @@ -351,7 +366,8 @@ // set the textures uvs temporarily // TODO create a separate texture so that we can tile part of a texture - if (!tilingSprite._uvs) { + if (!tilingSprite._uvs) + { tilingSprite._uvs = new TextureUvs(); } @@ -454,16 +470,19 @@ * Renders the content and empties the current batch. * */ -WebGLSpriteBatch.prototype.flush = function () { +WebGLSpriteBatch.prototype.flush = function () +{ // If the batch is length 0 then return as there is nothing to draw - if (this.currentBatchSize === 0) { + if (this.currentBatchSize === 0) + { return; } var gl = this.renderer.gl; var shader; - if (this.dirty) { + if (this.dirty) + { this.dirty = false; // bind the main texture gl.activeTexture(gl.TEXTURE0); @@ -482,10 +501,12 @@ } // upload the verts to the buffer - if (this.currentBatchSize > ( this.size * 0.5 ) ) { + if (this.currentBatchSize > ( this.size * 0.5 ) ) + { gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); } - else { + else + { var view = this.positions.subarray(0, this.currentBatchSize * this.vertByteSize); gl.bufferSubData(gl.ARRAY_BUFFER, 0, view); } @@ -502,7 +523,8 @@ var shaderSwap = false; var sprite; - for (var i = 0, j = this.currentBatchSize; i < j; i++) { + for (var i = 0, j = this.currentBatchSize; i < j; i++) + { sprite = this.sprites[i]; @@ -513,24 +535,28 @@ blendSwap = currentBlendMode !== nextBlendMode; shaderSwap = currentShader !== nextShader; // should I use uuidS??? - if (currentBaseTexture !== nextTexture || blendSwap || shaderSwap) { + if (currentBaseTexture !== nextTexture || blendSwap || shaderSwap) + { this.renderBatch(currentBaseTexture, batchSize, start); start = i; batchSize = 0; currentBaseTexture = nextTexture; - if (blendSwap) { + if (blendSwap) + { currentBlendMode = nextBlendMode; this.renderer.blendModeManager.setBlendMode( currentBlendMode ); } - if (shaderSwap) { + if (shaderSwap) + { currentShader = nextShader; shader = currentShader.shaders ? currentShader.shaders[gl.id] : currentShader; - if (!shader) { + if (!shader) + { shader = new Shader(gl, null, currentShader.fragmentSrc, currentShader.uniforms); currentShader.shaders[gl.id] = shader; } @@ -538,7 +564,8 @@ // set shader function??? this.renderer.shaderManager.setShader(shader); - if (shader.dirty) { + if (shader.dirty) + { shader.syncUniforms(); } @@ -569,17 +596,21 @@ * @param size {number} * @param startIndex {number} */ -WebGLSpriteBatch.prototype.renderBatch = function (texture, size, startIndex) { - if (size === 0) { +WebGLSpriteBatch.prototype.renderBatch = function (texture, size, startIndex) +{ + if (size === 0) + { return; } var gl = this.renderer.gl; - if (!texture._glTextures[gl.id]) { + if (!texture._glTextures[gl.id]) + { this.renderer.updateTexture(texture); } - else { + else + { // bind the current texture gl.bindTexture(gl.TEXTURE_2D, texture._glTextures[gl.id]); } @@ -594,7 +625,8 @@ /** * */ -WebGLSpriteBatch.prototype.stop = function () { +WebGLSpriteBatch.prototype.stop = function () +{ this.flush(); this.dirty = true; }; @@ -602,7 +634,8 @@ /** * */ -WebGLSpriteBatch.prototype.start = function () { +WebGLSpriteBatch.prototype.start = function () +{ this.dirty = true; }; @@ -610,7 +643,8 @@ * Destroys the SpriteBatch. * */ -WebGLSpriteBatch.prototype.destroy = function () { +WebGLSpriteBatch.prototype.destroy = function () +{ this.renderer.gl.deleteBuffer(this.vertexBuffer); this.renderer.gl.deleteBuffer(this.indexBuffer); diff --git a/src/core/textures/BaseTexture.js b/src/core/textures/BaseTexture.js index 2bf77d4..513d358 100644 --- a/src/core/textures/BaseTexture.js +++ b/src/core/textures/BaseTexture.js @@ -10,7 +10,8 @@ * @param source {Image|Canvas} the source object of the texture. * @param [scaleMode=scaleModes.DEFAULT] {number} See {@link scaleModes} for possible values */ -function BaseTexture(source, scaleMode) { +function BaseTexture(source, scaleMode) +{ this.uuid = utils.uuid(); /** @@ -123,7 +124,8 @@ this._needsUpdate = false; // if no source passed don't try to load - if (source) { + if (source) + { this.loadSource(source); } @@ -149,13 +151,16 @@ Object.defineProperties(BaseTexture.prototype, { needsUpdate: { - get: function () { + get: function () + { return this._needsUpdate; }, - set: function (val) { + set: function (val) + { this._needsUpdate = val; - if (val) { + if (val) + { this.emit('update', this); } } @@ -171,9 +176,11 @@ * * The logic state after calling `loadSource` directly or indirectly (eg. `fromImage`, `new BaseTexture`) is: * - * if (texture.hasLoaded) { + * if (texture.hasLoaded) + { * // texture ready for use - * } else if (texture.isLoading) { + * } else if (texture.isLoading) + { * // listen to 'loaded' and/or 'error' events on texture * } else { * // not loading, not going to load UNLESS the source is reloaded @@ -183,12 +190,14 @@ * @protected * @param source {Image|Canvas} the source object of the texture. */ -BaseTexture.prototype.loadSource = function (source) { +BaseTexture.prototype.loadSource = function (source) +{ var wasLoading = this.isLoading; this.hasLoaded = false; this.isLoading = false; - if (wasLoading && this.source) { + if (wasLoading && this.source) + { this.source.onload = null; this.source.onerror = null; } @@ -196,20 +205,24 @@ this.source = source; // Apply source if loaded. Otherwise setup appropriate loading monitors. - if ((this.source.complete || this.source.getContext) && this.source.width && this.source.height) { + if ((this.source.complete || this.source.getContext) && this.source.width && this.source.height) + { this._sourceLoaded(); } - else if(!source.getContext) { + else if(!source.getContext) + { // Image fail / not ready this.isLoading = true; var scope = this; - source.onload = function () { + source.onload = function () + { source.onload = null; source.onerror = null; - if(!scope.isLoading) { + if(!scope.isLoading) + { return; } @@ -219,11 +232,13 @@ scope.emit('loaded', scope); }; - source.onerror = function () { + source.onerror = function () + { source.onload = null; source.onerror = null; - if(!scope.isLoading) { + if(!scope.isLoading) + { return; } @@ -234,24 +249,29 @@ // Per http://www.w3.org/TR/html5/embedded-content-0.html#the-img-element // "The value of `complete` can thus change while a script is executing." // So complete needs to be re-checked after the callbacks have been added.. - if (source.complete) { + if (source.complete) + { this.isLoading = false; // ..and if we're complete now, no need for callbacks source.onload = null; source.onerror = null; - if (source.width && source.height) { + if (source.width && source.height) + { this._sourceLoaded(); // If any previous subscribers possible - if (wasLoading) { + if (wasLoading) + { this.emit('loaded', this); } } - else { + else + { // If any previous subscribers possible - if (wasLoading) { + if (wasLoading) + { this.emit('error', this); } } @@ -265,7 +285,8 @@ * * @private */ -BaseTexture.prototype._sourceLoaded = function () { +BaseTexture.prototype._sourceLoaded = function () +{ this.hasLoaded = true; this.width = this.source.naturalWidth || this.source.width; @@ -278,16 +299,20 @@ * Destroys this base texture * */ -BaseTexture.prototype.destroy = function () { - if (this.imageUrl) { +BaseTexture.prototype.destroy = function () +{ + if (this.imageUrl) + { delete utils.BaseTextureCache[this.imageUrl]; delete utils.TextureCache[this.imageUrl]; this.imageUrl = null; - if (!navigator.isCocoonJS) { + if (!navigator.isCocoonJS) + { this.source.src = ''; } } - else if (this.source && this.source._pixiId) { + else if (this.source && this.source._pixiId) + { delete utils.BaseTextureCache[this.source._pixiId]; } this.source = null; @@ -301,7 +326,8 @@ * memory again. * */ -BaseTexture.prototype.dispose = function () { +BaseTexture.prototype.dispose = function () +{ this.emit('dispose', this); }; @@ -311,7 +337,8 @@ * * @param newSrc {string} the path of the image */ -BaseTexture.prototype.updateSourceImage = function (newSrc) { +BaseTexture.prototype.updateSourceImage = function (newSrc) +{ this.source.src = newSrc; this.loadSource(this.source); }; @@ -326,18 +353,22 @@ * @param [scaleMode=scaleModes.DEFAULT] {number} See {@link scaleModes} for possible values * @return BaseTexture */ -BaseTexture.fromImage = function (imageUrl, crossorigin, scaleMode) { +BaseTexture.fromImage = function (imageUrl, crossorigin, scaleMode) +{ var baseTexture = utils.BaseTextureCache[imageUrl]; - if (crossorigin === undefined && imageUrl.indexOf('data:') !== 0) { + if (crossorigin === undefined && imageUrl.indexOf('data:') !== 0) + { crossorigin = true; } - if (!baseTexture) { + if (!baseTexture) + { // new Image() breaks tex loading in some versions of Chrome. // See https://code.google.com/p/chromium/issues/detail?id=238071 var image = new Image();//document.createElement('img'); - if (crossorigin) { + if (crossorigin) + { image.crossOrigin = ''; } @@ -347,7 +378,8 @@ utils.BaseTextureCache[imageUrl] = baseTexture; // if there is an @2x at the end of the url we are going to assume its a highres image - if ( imageUrl.indexOf(CONST.RETINA_PREFIX + '.') !== -1) { + if ( imageUrl.indexOf(CONST.RETINA_PREFIX + '.') !== -1) + { baseTexture.resolution = 2; } } @@ -363,14 +395,17 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return BaseTexture */ -BaseTexture.fromCanvas = function (canvas, scaleMode) { - if (!canvas._pixiId) { +BaseTexture.fromCanvas = function (canvas, scaleMode) +{ + if (!canvas._pixiId) + { canvas._pixiId = 'canvas_' + utils.uuid(); } var baseTexture = utils.BaseTextureCache[canvas._pixiId]; - if (!baseTexture) { + if (!baseTexture) + { baseTexture = new BaseTexture(canvas, scaleMode); utils.BaseTextureCache[canvas._pixiId] = baseTexture; } diff --git a/src/core/textures/RenderTexture.js b/src/core/textures/RenderTexture.js index 6dad20f..53ae796 100644 --- a/src/core/textures/RenderTexture.js +++ b/src/core/textures/RenderTexture.js @@ -46,8 +46,10 @@ * @param [scaleMode] {number} See {@link scaleModes} for possible values * @param [resolution=1] {number} The resolution of the texture being generated */ -function RenderTexture(renderer, width, height, scaleMode, resolution) { - if (!renderer) { +function RenderTexture(renderer, width, height, scaleMode, resolution) +{ + if (!renderer) + { throw new Error('Unable to create RenderTexture, you must pass a renderer into the constructor.'); } @@ -133,7 +135,8 @@ */ this.renderer = renderer; - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { var gl = this.renderer.gl; this.textureBuffer = new FilterTexture(gl, this.width * this.resolution, this.height * this.resolution, this.baseTexture.scaleMode); @@ -142,7 +145,8 @@ this.render = this.renderWebGL; this.projection = new math.Point(this.width*0.5, -this.height*0.5); } - else { + else + { this.render = this.renderCanvas; this.textureBuffer = new CanvasBuffer(this.width* this.resolution, this.height* this.resolution); this.baseTexture.source = this.textureBuffer.canvas; @@ -167,8 +171,10 @@ * @param height {number} The height to resize to. * @param updateBase {boolean} Should the baseTexture.width and height values be resized as well? */ -RenderTexture.prototype.resize = function (width, height, updateBase) { - if (width === this.width && height === this.height) { +RenderTexture.prototype.resize = function (width, height, updateBase) +{ + if (width === this.width && height === this.height) + { return; } @@ -177,17 +183,20 @@ this.width = this.frame.width = this.crop.width = width; this.height = this.frame.height = this.crop.height = height; - if (updateBase) { + if (updateBase) + { this.baseTexture.width = this.width; this.baseTexture.height = this.height; } - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { this.projection.x = this.width / 2; this.projection.y = -this.height / 2; } - if (!this.valid) { + if (!this.valid) + { return; } @@ -198,12 +207,15 @@ * Clears the RenderTexture. * */ -RenderTexture.prototype.clear = function () { - if (!this.valid) { +RenderTexture.prototype.clear = function () +{ + if (!this.valid) + { return; } - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { this.renderer.gl.bindFramebuffer(this.renderer.gl.FRAMEBUFFER, this.textureBuffer.frameBuffer); } @@ -220,19 +232,23 @@ * @param [restoreWorldTransform=true] {boolean} If true the displayObject's worldTransform/worldAlpha and all children * transformations will be restored. Not restoring this information will be a little faster. */ -RenderTexture.prototype.renderWebGL = function (displayObject, matrix, clear, restoreWorldTransform) { - if (!this.valid) { +RenderTexture.prototype.renderWebGL = function (displayObject, matrix, clear, restoreWorldTransform) +{ + if (!this.valid) + { return; } - if (typeof restoreWorldTransform === 'undefined') { + if (typeof restoreWorldTransform === 'undefined') + { restoreWorldTransform = true; } var tempAlpha, tempTransform; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { tempAlpha = displayObject.worldAlpha; tempTransform = displayObject.worldTransform.toArray(); } @@ -245,7 +261,8 @@ wt.identity(); wt.translate(0, this.projection.y * 2); - if (matrix) { + if (matrix) + { wt.append(matrix); } @@ -258,7 +275,8 @@ var children = displayObject.children; var i, j; - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } @@ -269,7 +287,8 @@ gl.bindFramebuffer(gl.FRAMEBUFFER, this.textureBuffer.frameBuffer ); - if (clear) { + if (clear) + { this.textureBuffer.clear(); } @@ -279,11 +298,13 @@ this.renderer.spriteBatch.dirty = true; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { displayObject.worldAlpha = tempAlpha; displayObject.worldTransform.fromArray(tempTransform); - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } } @@ -300,26 +321,31 @@ * @param [restoreWorldTransform=true] {boolean} If true the displayObject's worldTransform/worldAlpha and all children * transformations will be restored. Not restoring this information will be a little faster. */ -RenderTexture.prototype.renderCanvas = function (displayObject, matrix, clear, restoreWorldTransform) { - if (!this.valid) { +RenderTexture.prototype.renderCanvas = function (displayObject, matrix, clear, restoreWorldTransform) +{ + if (!this.valid) + { return; } - if (typeof restoreWorldTransform === 'undefined') { + if (typeof restoreWorldTransform === 'undefined') + { restoreWorldTransform = true; } var tempAlpha, tempTransform; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { tempAlpha = displayObject.worldAlpha; tempTransform = displayObject.worldTransform.toArray(); } var wt = displayObject.worldTransform; wt.identity(); - if (matrix) { + if (matrix) + { wt.append(matrix); } @@ -330,11 +356,13 @@ var children = displayObject.children; var i, j; - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } - if (clear) { + if (clear) + { this.textureBuffer.clear(); } @@ -348,11 +376,13 @@ this.renderer.resolution = realResolution; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { displayObject.worldAlpha = tempAlpha; displayObject.worldTransform.fromArray(tempTransform); - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } } @@ -363,7 +393,8 @@ * * @return {Image} */ -RenderTexture.prototype.getImage = function () { +RenderTexture.prototype.getImage = function () +{ var image = new Image(); image.src = this.getBase64(); return image; @@ -374,7 +405,8 @@ * * @return {string} A base64 encoded string of the texture. */ -RenderTexture.prototype.getBase64 = function () { +RenderTexture.prototype.getBase64 = function () +{ return this.getCanvas().toDataURL(); }; @@ -383,8 +415,10 @@ * * @return {HTMLCanvasElement} A Canvas element with the texture rendered on. */ -RenderTexture.prototype.getCanvas = function () { - if (this.renderer.type === CONST.WEBGL_RENDERER) { +RenderTexture.prototype.getCanvas = function () +{ + if (this.renderer.type === CONST.WEBGL_RENDERER) + { var gl = this.renderer.gl; var width = this.textureBuffer.width; var height = this.textureBuffer.height; @@ -403,7 +437,8 @@ return tempCanvas.canvas; } - else { + else + { return this.textureBuffer.canvas; } }; diff --git a/src/core/textures/Texture.js b/src/core/textures/Texture.js index 3c65909..e97f0aa 100644 --- a/src/core/textures/Texture.js +++ b/src/core/textures/Texture.js @@ -17,7 +17,8 @@ * @param [crop] {Rectangle} The area of original texture * @param [trim] {Rectangle} Trimmed texture rectangle */ -function Texture(baseTexture, frame, crop, trim) { +function Texture(baseTexture, frame, crop, trim) +{ /** * Does this Texture have any frame data assigned to it? * @@ -25,12 +26,14 @@ */ this.noFrame = false; - if (!frame) { + if (!frame) + { this.noFrame = true; frame = new math.Rectangle(0, 0, 1, 1); } - if (baseTexture instanceof Texture) { + if (baseTexture instanceof Texture) + { baseTexture = baseTexture.baseTexture; } @@ -100,13 +103,16 @@ */ this.crop = crop || new math.Rectangle(0, 0, 1, 1); - if (baseTexture.hasLoaded) { - if (this.noFrame) { + if (baseTexture.hasLoaded) + { + if (this.noFrame) + { frame = new math.Rectangle(0, 0, baseTexture.width, baseTexture.height); } this.frame = frame; } - else { + else + { baseTexture.addEventListener('loaded', this.onBaseTextureLoaded.bind(this)); } } @@ -118,19 +124,23 @@ Object.defineProperties(Texture.prototype, { needsUpdate: { - get: function () { + get: function () + { return this.baseTexture.needsUpdate; }, - set: function (val) { + set: function (val) + { this.baseTexture.needsUpdate = val; } }, frame: { - get: function () { + get: function () + { return this._frame; }, - set: function (frame) { + set: function (frame) + { this._frame = frame; this.noFrame = false; @@ -143,20 +153,23 @@ 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 (!this.trim && (frame.x + frame.width > this.baseTexture.width || frame.y + frame.height > this.baseTexture.height)) + { throw new Error('Texture Error: frame does not fit inside the base Texture dimensions ' + this); } this.valid = frame && frame.width && frame.height && this.baseTexture.source && this.baseTexture.hasLoaded; - if (this.trim) { + 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) { + if (this.valid) + { this._updateUvs(); } } @@ -168,11 +181,13 @@ * * @private */ -Texture.prototype.onBaseTextureLoaded = function () { +Texture.prototype.onBaseTextureLoaded = function () +{ var baseTexture = this.baseTexture; baseTexture.removeEventListener('loaded', this.onLoaded); - if (this.noFrame) { + if (this.noFrame) + { this.frame = new math.Rectangle(0, 0, baseTexture.width, baseTexture.height); } @@ -184,8 +199,10 @@ * * @param destroyBase {boolean} Whether to destroy the base texture as well */ -Texture.prototype.destroy = function (destroyBase) { - if (destroyBase) { +Texture.prototype.destroy = function (destroyBase) +{ + if (destroyBase) + { this.baseTexture.destroy(); } @@ -197,8 +214,10 @@ * * @private */ -Texture.prototype._updateUvs = function () { - if (!this._uvs) { +Texture.prototype._updateUvs = function () +{ + if (!this._uvs) + { this._uvs = new TextureUvs(); } @@ -229,10 +248,12 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return Texture */ -Texture.fromImage = function (imageUrl, crossorigin, scaleMode) { +Texture.fromImage = function (imageUrl, crossorigin, scaleMode) +{ var texture = utils.TextureCache[imageUrl]; - if (!texture) { + if (!texture) + { texture = new Texture(BaseTexture.fromImage(imageUrl, crossorigin, scaleMode)); utils.TextureCache[imageUrl] = texture; } @@ -248,9 +269,11 @@ * @param frameId {string} The frame id of the texture * @return Texture */ -Texture.fromFrame = function (frameId) { +Texture.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache '); } return texture; @@ -264,7 +287,8 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return {Texture} */ -Texture.fromCanvas = function (canvas, scaleMode) { +Texture.fromCanvas = function (canvas, scaleMode) +{ return new Texture(BaseTexture.fromCanvas(canvas, scaleMode)); }; @@ -276,7 +300,8 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return {Texture} A Texture */ -Texture.fromVideo = function (video, scaleMode) { +Texture.fromVideo = function (video, scaleMode) +{ return new Texture(VideoBaseTexture.baseTextureFromVideo(video, scaleMode)); }; @@ -287,7 +312,8 @@ * @param texture {Texture} The Texture to add to the cache. * @param id {string} The id that the texture will be stored against. */ -Texture.addTextureToCache = function (texture, id) { +Texture.addTextureToCache = function (texture, id) +{ utils.TextureCache[id] = texture; }; @@ -298,7 +324,8 @@ * @param id {string} The id of the texture to be removed * @return {Texture} The texture that was removed */ -Texture.removeTextureFromCache = function (id) { +Texture.removeTextureFromCache = function (id) +{ var texture = utils.TextureCache[id]; delete utils.TextureCache[id]; diff --git a/src/core/textures/TextureUvs.js b/src/core/textures/TextureUvs.js index b9bbb58..5424d52 100644 --- a/src/core/textures/TextureUvs.js +++ b/src/core/textures/TextureUvs.js @@ -1,4 +1,5 @@ -function TextureUvs() { +function TextureUvs() +{ this.x0 = 0; this.y0 = 0; diff --git a/src/core/textures/VideoBaseTexture.js b/src/core/textures/VideoBaseTexture.js index e3e0c5a..1a826a9 100644 --- a/src/core/textures/VideoBaseTexture.js +++ b/src/core/textures/VideoBaseTexture.js @@ -12,15 +12,18 @@ * @param source {HTMLVideoElement} * @param [scaleMode] {number} See {@link scaleModes} for possible values */ -function VideoBaseTexture(source, scaleMode) { - if (!source){ +function VideoBaseTexture(source, scaleMode) +{ + if (!source) + { throw new Error('No video source element specified.'); } // hook in here to check if video is already available. // BaseTexture looks for a source.complete boolean, plus width & height. - if ((source.readyState === source.HAVE_ENOUGH_DATA || source.readyState === source.HAVE_FUTURE_DATA) && source.width && source.height) { + if ((source.readyState === source.HAVE_ENOUGH_DATA || source.readyState === source.HAVE_FUTURE_DATA) && source.width && source.height) + { source.complete = true; } @@ -31,7 +34,8 @@ this._boundOnUpdate = this._onUpdate.bind(this); this._boundOnCanPlay = this._onCanPlay.bind(this); - if (!source.complete) { + if (!source.complete) + { source.addEventListener('canplay', this._boundOnCanPlay); source.addEventListener('canplaythrough', this._boundOnCanPlay); @@ -47,28 +51,35 @@ VideoBaseTexture.prototype.constructor = VideoBaseTexture; module.exports = VideoBaseTexture; -VideoBaseTexture.prototype._onUpdate = function () { - if (this.autoUpdate) { +VideoBaseTexture.prototype._onUpdate = function () +{ + if (this.autoUpdate) + { window.requestAnimationFrame(this._boundOnUpdate); this.needsUpdate = true; } }; -VideoBaseTexture.prototype._onPlayStart = function () { - if (!this.autoUpdate) { +VideoBaseTexture.prototype._onPlayStart = function () +{ + if (!this.autoUpdate) + { window.requestAnimationFrame(this._boundOnUpdate); this.autoUpdate = true; } }; -VideoBaseTexture.prototype._onPlayStop = function () { +VideoBaseTexture.prototype._onPlayStop = function () +{ this.autoUpdate = false; }; -VideoBaseTexture.prototype._onCanPlay = function () { +VideoBaseTexture.prototype._onCanPlay = function () +{ this.hasLoaded = true; - if (this.source) { + if (this.source) + { this.source.removeEventListener('canplay', this._boundOnCanPlay); this.source.removeEventListener('canplaythrough', this._boundOnCanPlay); @@ -78,15 +89,18 @@ this.source.play(); // prevent multiple loaded dispatches.. - if(!this.__loaded){ + if(!this.__loaded) + { this.__loaded = true; this.emit('loaded', this); } } }; -VideoBaseTexture.prototype.destroy = function () { - if (this.source && this.source._pixiId) { +VideoBaseTexture.prototype.destroy = function () +{ + if (this.source && this.source._pixiId) + { utils.BaseTextureCache[ this.source._pixiId ] = null; delete utils.BaseTextureCache[ this.source._pixiId ]; @@ -105,14 +119,17 @@ * @param scaleMode {number} See {@link scaleModes} for possible values * @return {VideoBaseTexture} */ -VideoBaseTexture.fromVideo = function (video, scaleMode) { - if (!video._pixiId) { +VideoBaseTexture.fromVideo = function (video, scaleMode) +{ + if (!video._pixiId) + { video._pixiId = 'video_' + utils.uuid(); } var baseTexture = utils.BaseTextureCache[video._pixiId]; - if (!baseTexture) { + if (!baseTexture) + { baseTexture = new VideoBaseTexture(video, scaleMode); utils.BaseTextureCache[ video._pixiId ] = baseTexture; } @@ -147,17 +164,21 @@ * @param scaleMode {number} See {@link scaleModes} for possible values * @return {VideoBaseTexture} */ -VideoBaseTexture.fromUrl = function (videoSrc, scaleMode) { +VideoBaseTexture.fromUrl = function (videoSrc, scaleMode) +{ var video = document.createElement('video'); // array of objects or strings - if (Array.isArray(videoSrc)) { - for (var i = 0; i < videoSrc.length; ++i) { + if (Array.isArray(videoSrc)) + { + for (var i = 0; i < videoSrc.length; ++i) + { video.appendChild(createSource(videoSrc.src || videoSrc, videoSrc.mime)); } } // single object or string - else { + else + { video.appendChild(createSource(videoSrc.src || videoSrc, videoSrc.mime)); } @@ -169,8 +190,10 @@ VideoBaseTexture.fromUrls = VideoBaseTexture.fromUrl; -function createSource(path, type) { - if (!type) { +function createSource(path, type) +{ + if (!type) + { type = 'video/' + path.substr(path.lastIndexOf('.') + 1); } diff --git a/src/core/utils/EventData.js b/src/core/utils/EventData.js index 5d55a22..8cdf701 100644 --- a/src/core/utils/EventData.js +++ b/src/core/utils/EventData.js @@ -7,7 +7,8 @@ * @param name {string} The string name of the event that was triggered * @param data {object} Arbitrary event data to pass along */ -function EventData(target, name, data) { +function EventData(target, name, data) +{ // for duck typing in the ".on()" function this.__isEventObject = true; @@ -71,7 +72,8 @@ * Stops the propagation of events up the scene graph (prevents bubbling). * */ -EventData.prototype.stopPropagation = function stopPropagation() { +EventData.prototype.stopPropagation = function stopPropagation() +{ this.stopped = true; }; @@ -79,6 +81,7 @@ * Stops the propagation of events to sibling listeners (no longer calls any listeners). * */ -EventData.prototype.stopImmediatePropagation = function stopImmediatePropagation() { +EventData.prototype.stopImmediatePropagation = function stopImmediatePropagation() +{ this.stoppedImmediate = true; }; diff --git a/src/core/utils/EventTarget.js b/src/core/utils/EventTarget.js index 7ae8820..671a151 100644 --- a/src/core/utils/EventTarget.js +++ b/src/core/utils/EventTarget.js @@ -13,14 +13,16 @@ * var em = new MyEmitter(); * em.emit('eventName', 'some data', 'some more data', {}, null, ...); */ -function eventTarget(obj) { +function eventTarget(obj) +{ /** * Return a list of assigned event listeners. * * @param eventName {string} The events that should be listed. * @return {Array} An array of listener functions */ - obj.listeners = function listeners(eventName) { + obj.listeners = function listeners(eventName) + { this._listeners = this._listeners || {}; return this._listeners[eventName] ? this._listeners[eventName].slice() : []; @@ -33,22 +35,26 @@ * @param eventName {string} The name of the event. * @return {boolean} Indication if we've emitted an event. */ - obj.emit = obj.dispatchEvent = function emit(eventName, data) { + obj.emit = obj.dispatchEvent = function emit(eventName, data) + { this._listeners = this._listeners || {}; // fast return when there are no listeners - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return; } //backwards compat with old method ".emit({ type: 'something' })" - if (typeof eventName === 'object') { + if (typeof eventName === 'object') + { data = eventName; eventName = eventName.type; } //ensure we are using a real pixi event - if (!data || data.__isEventObject !== true) { + if (!data || data.__isEventObject !== true) + { data = new EventData(this, eventName, data); } @@ -58,23 +64,27 @@ fn = listeners[0], i; - for (i = 0; i < length; fn = listeners[++i]) { + for (i = 0; i < length; fn = listeners[++i]) + { //call the event listener fn.call(this, data); //if "stopImmediatePropagation" is called, stop calling sibling events - if (data.stoppedImmediate) { + if (data.stoppedImmediate) + { return this; } } //if "stopPropagation" is called then don't bubble the event - if (data.stopped) { + if (data.stopped) + { return this; } //bubble this event up the scene graph - if (this.parent && this.parent.emit) { + if (this.parent && this.parent.emit) + { this.parent.emit.call(this.parent, eventName, data); } @@ -88,7 +98,8 @@ * @param eventName {string} Name of the event. * @param callback {Functon} fn Callback function. */ - obj.on = obj.addEventListener = function on(eventName, fn) { + obj.on = obj.addEventListener = function on(eventName, fn) + { this._listeners = this._listeners || {}; (this._listeners[eventName] = this._listeners[eventName] || []) @@ -103,11 +114,13 @@ * @param eventName {string} Name of the event. * @param callback {Function} Callback function. */ - obj.once = function once(eventName, fn) { + obj.once = function once(eventName, fn) + { this._listeners = this._listeners || {}; var self = this; - function onceHandlerWrapper() { + function onceHandlerWrapper() + { fn.apply(self.off(eventName, onceHandlerWrapper), arguments); } onceHandlerWrapper._originalHandler = fn; @@ -122,23 +135,28 @@ * @param eventName {string} The event we want to remove. * @param callback {Function} The listener that we need to find. */ - obj.off = obj.removeEventListener = function off(eventName, fn) { + obj.off = obj.removeEventListener = function off(eventName, fn) + { this._listeners = this._listeners || {}; - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return this; } var list = this._listeners[eventName], i = fn ? list.length : 0; - while(i-- > 0) { - if (list[i] === fn || list[i]._originalHandler === fn) { + while(i-- > 0) + { + if (list[i] === fn || list[i]._originalHandler === fn) + { list.splice(i, 1); } } - if (list.length === 0) { + if (list.length === 0) + { delete this._listeners[eventName]; } @@ -150,10 +168,12 @@ * * @param eventName {string} The event you want to remove all listeners for. */ - obj.removeAllListeners = function removeAllListeners(eventName) { + obj.removeAllListeners = function removeAllListeners(eventName) + { this._listeners = this._listeners || {}; - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return this; } @@ -169,7 +189,8 @@ * * @param object {object} The obj to mix into */ - mixin: function mixin(obj) { + mixin: function mixin(obj) + { eventTarget(obj); } }; diff --git a/src/core/utils/PolyK.js b/src/core/utils/PolyK.js index 7325141..5e20c2b 100644 --- a/src/core/utils/PolyK.js +++ b/src/core/utils/PolyK.js @@ -47,7 +47,8 @@ * Triangulates shapes for webGL graphic fills. * */ -PolyK.Triangulate = function (p) { +PolyK.Triangulate = function (p) +{ var sign = true; var n = p.length >> 1; @@ -59,7 +60,8 @@ i = 0; var al = n; - while(al > 3) { + while(al > 3) + { var i0 = avl[(i+0)%al]; var i1 = avl[(i+1)%al]; var i2 = avl[(i+2)%al]; @@ -69,29 +71,35 @@ var cx = p[2*i2], cy = p[2*i2+1]; var earFound = false; - if (PolyK._convex(ax, ay, bx, by, cx, cy, sign)) { + if (PolyK._convex(ax, ay, bx, by, cx, cy, sign)) + { earFound = true; - for (var j = 0; j < al; j++) { + for (var j = 0; j < al; j++) + { var vi = avl[j]; if (vi === i0 || vi === i1 || vi === i2) continue; - if (PolyK._PointInTriangle(p[2*vi], p[2*vi+1], ax, ay, bx, by, cx, cy)) { + if (PolyK._PointInTriangle(p[2*vi], p[2*vi+1], ax, ay, bx, by, cx, cy)) + { earFound = false; break; } } } - if (earFound) { + if (earFound) + { tgs.push(i0, i1, i2); avl.splice((i+1)%al, 1); al--; i = 0; } - else if (i++ > 3*al) { + else if (i++ > 3*al) + { // need to flip flip reverse it! // reset! - if (sign) { + if (sign) + { tgs = []; avl = []; for (i = 0; i < n; i++) avl.push(i); @@ -101,7 +109,8 @@ sign = false; } - else { + else + { // window.console.log("PIXI Warning: shape too complex to fill"); return null; } @@ -126,7 +135,8 @@ * @private * @return {boolean} */ -PolyK._PointInTriangle = function (px, py, ax, ay, bx, by, cx, cy) { +PolyK._PointInTriangle = function (px, py, ax, ay, bx, by, cx, cy) +{ var v0x = cx-ax; var v0y = cy-ay; var v1x = bx-ax; @@ -154,6 +164,7 @@ * @private * @return {boolean} */ -PolyK._convex = function (ax, ay, bx, by, cx, cy, sign) { +PolyK._convex = function (ax, ay, bx, by, cx, cy, sign) +{ return ((ay-by)*(cx-bx) + (bx-ax)*(cy-by) >= 0) === sign; }; diff --git a/src/core/utils/index.js b/src/core/utils/index.js index ade9831..bfae7ae 100644 --- a/src/core/utils/index.js +++ b/src/core/utils/index.js @@ -16,7 +16,8 @@ * * @return {number} The next uuid to use. */ - uuid: function () { + uuid: function () + { return ++utils._uid; }, @@ -26,7 +27,8 @@ * @param hex {number} * @return {number[]} An array representing the [R, G, B] of the color. */ - hex2rgb: function (hex, out) { + hex2rgb: function (hex, out) + { out = out || []; out[0] = (hex >> 16 & 0xFF) / 255; @@ -42,7 +44,8 @@ * @param hex {number} * @return {string} The string color. */ - hex2string: function (hex) { + hex2string: function (hex) + { hex = hex.toString(16); hex = '000000'.substr(0, 6 - hex.length) + hex; @@ -55,7 +58,8 @@ * @param rgb {number[]} * @return {number} The color number */ - rgb2hex: function (rgb) { + rgb2hex: function (rgb) + { return ((rgb[0]*255 << 16) + (rgb[1]*255 << 8) + rgb[2]*255); }, @@ -64,8 +68,10 @@ * * @return {boolean} whether they are supported */ - canUseNewCanvasBlendModes: function () { - if (typeof document === 'undefined') { + canUseNewCanvasBlendModes: function () + { + if (typeof document === 'undefined') + { return false; } @@ -93,15 +99,19 @@ * @param number {number} * @return {number} the closest number that is a power of two */ - getNextPowerOfTwo: function (number) { + getNextPowerOfTwo: function (number) + { // see: http://en.wikipedia.org/wiki/Power_of_two#Fast_algorithm_to_check_if_a_positive_number_is_a_power_of_two - if (number > 0 && (number & (number - 1)) === 0) { + if (number > 0 && (number & (number - 1)) === 0) + { return number; } - else { + else + { var result = 1; - while (result < number) { + while (result < number) + { result <<= 1; } @@ -116,7 +126,8 @@ * @param height {number} * @return {boolean} */ - isPowerOfTwo: function (width, height) { + isPowerOfTwo: function (width, height) + { return (width > 0 && (width & (width - 1)) === 0 && height > 0 && (height & (height - 1)) === 0); }, @@ -130,12 +141,15 @@ * @constant * @static */ - sayHello: function (type) { - if (utils._saidHello) { + sayHello: function (type) + { + if (utils._saidHello) + { return; } - if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) { + if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) + { var args = [ '%c %c %c Pixi.js ' + CONST.VERSION + ' - ' + type + ' %c ' + ' %c ' + ' http://www.pixijs.com/ %c %c ♥%c♥%c♥ ', 'background: #ff66a5', @@ -151,7 +165,8 @@ console.log.apply(console, args); //jshint ignore:line } - else if (window.console) { + else if (window.console) + { console.log('Pixi.js ' + CONST.VERSION + ' - ' + type + ' - http://www.pixijs.com/'); //jshint ignore:line } @@ -166,15 +181,19 @@ * @class * @namespace PIXI */ - AjaxRequest: function () { + AjaxRequest: function () + { var activexmodes = ['Msxml2.XMLHTTP.6.0', 'Msxml2.XMLHTTP.3.0', 'Microsoft.XMLHTTP']; //activeX versions to check for in IE - if (window.ActiveXObject) { //Test for support for ActiveXObject in IE first (as XMLHttpRequest in IE7 is broken) - for (var i=0; i= this.textures.length) { + else if (round >= this.textures.length) + { this.gotoAndStop(this.textures.length - 1); - if (this.onComplete) { + if (this.onComplete) + { this.onComplete(); } } @@ -167,10 +182,12 @@ * @static * @param frames {string[]} the array of frames ids the movieclip will use as its texture frames */ -MovieClip.fromFrames = function (frames) { +MovieClip.fromFrames = function (frames) +{ var textures = []; - for (var i = 0; i < frames.length; ++i) { + for (var i = 0; i < frames.length; ++i) + { textures.push(new core.Texture.fromFrame(frames[i])); } @@ -183,10 +200,12 @@ * @static * @param images {string[]} the array of image urls the movieclip will use as its texture frames */ -MovieClip.fromImages = function (images) { +MovieClip.fromImages = function (images) +{ var textures = []; - for (var i = 0; i < images.length; ++i) { + for (var i = 0; i < images.length; ++i) + { textures.push(new core.Texture.fromImage(images[i])); } diff --git a/src/extras/Rope.js b/src/extras/Rope.js index c157ec4..9c87bc0 100644 --- a/src/extras/Rope.js +++ b/src/extras/Rope.js @@ -9,7 +9,8 @@ * @param {Array} points - An array of {Point}. * */ -function Rope(texture, points) { +function Rope(texture, points) +{ Strip.call(this, texture); this.points = points; @@ -31,10 +32,12 @@ * Refreshes * */ -Rope.prototype.refresh = function () { +Rope.prototype.refresh = function () +{ var points = this.points; - if (points.length < 1) { + if (points.length < 1) + { return; } @@ -59,20 +62,23 @@ var total = points.length, point, index, amount; - for (var i = 1; i < total; i++) { + for (var i = 1; i < total; i++) + { point = points[i]; index = i * 4; // time to do some smart drawing! amount = i / (total-1); - if (i%2) { + if (i%2) + { uvs[index] = amount; uvs[index+1] = 0; uvs[index+2] = amount; uvs[index+3] = 1; } - else { + else + { uvs[index] = amount; uvs[index+1] = 0; @@ -95,10 +101,12 @@ * * @private */ -Rope.prototype.updateTransform = function () { +Rope.prototype.updateTransform = function () +{ var points = this.points; - if (points.length < 1) { + if (points.length < 1) + { return; } @@ -113,14 +121,17 @@ var total = points.length, point, index, ratio, perpLength, num; - for (var i = 0; i < total; i++) { + for (var i = 0; i < total; i++) + { point = points[i]; index = i * 4; - if (i < points.length-1) { + if (i < points.length-1) + { nextPoint = points[i+1]; } - else { + else + { nextPoint = point; } @@ -129,7 +140,8 @@ ratio = (1 - (i / (total-1))) * 10; - if (ratio > 1) { + if (ratio > 1) + { ratio = 1; } @@ -157,7 +169,8 @@ * * @param texture {Texture} the texture that will be used */ -Rope.prototype.setTexture = function (texture) { +Rope.prototype.setTexture = function (texture) +{ // stop current texture this.texture = texture; //this.updateFrame = true; diff --git a/src/extras/Strip.js b/src/extras/Strip.js index c5e378f..57691b5 100644 --- a/src/extras/Strip.js +++ b/src/extras/Strip.js @@ -10,7 +10,8 @@ * @param height {number} the height * */ -function Strip(texture) { +function Strip(texture) +{ core.DisplayObjectContainer.call(this); /** @@ -70,9 +71,11 @@ * * @param renderer {WebGLRenderer} */ -Strip.prototype.renderWebGL = function (renderer) { +Strip.prototype.renderWebGL = function (renderer) +{ // if the sprite is not visible or the alpha is 0 then no need to render this element - if (!this.visible || this.alpha <= 0) { + if (!this.visible || this.alpha <= 0) + { return; } @@ -81,7 +84,8 @@ renderer.spriteBatch.stop(); // init! init! - if (!this._vertexBuffer) { + if (!this._vertexBuffer) + { this._initWebGL(renderer); } @@ -96,7 +100,8 @@ //TODO check culling }; -Strip.prototype._initWebGL = function (renderer) { +Strip.prototype._initWebGL = function (renderer) +{ // build the strip! var gl = renderer.gl; @@ -118,7 +123,8 @@ gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this.indices, gl.STATIC_DRAW); }; -Strip.prototype._renderStrip = function (renderer) { +Strip.prototype._renderStrip = function (renderer) +{ var gl = renderer.gl; var projection = renderer.projection, offset = renderer.offset, @@ -137,7 +143,8 @@ gl.uniform2f(shader.offsetVector, -offset.x, -offset.y); gl.uniform1f(shader.alpha, this.worldAlpha); - if (!this.dirty) { + if (!this.dirty) + { gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexBuffer); gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); @@ -150,10 +157,12 @@ gl.activeTexture(gl.TEXTURE0); // check if a texture is dirty.. - if (this.texture.baseTexture._dirty[gl.id]) { + if (this.texture.baseTexture._dirty[gl.id]) + { renderer.updateTexture(this.texture.baseTexture); } - else { + else + { // bind the current texture gl.bindTexture(gl.TEXTURE_2D, this.texture.baseTexture._glTextures[gl.id]); } @@ -163,7 +172,8 @@ } - else { + else + { this.dirty = false; gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexBuffer); @@ -178,10 +188,12 @@ gl.activeTexture(gl.TEXTURE0); // check if a texture is dirty.. - if (this.texture.baseTexture._dirty[gl.id]) { + if (this.texture.baseTexture._dirty[gl.id]) + { renderer.updateTexture(this.texture.baseTexture); } - else { + else + { gl.bindTexture(gl.TEXTURE_2D, this.texture.baseTexture._glTextures[gl.id]); } @@ -203,27 +215,33 @@ * * @param renderer {CanvasRenderer} */ -Strip.prototype.renderCanvas = function (renderer) { +Strip.prototype.renderCanvas = function (renderer) +{ var context = renderer.context; var transform = this.worldTransform; - if (renderer.roundPixels) { + if (renderer.roundPixels) + { context.setTransform(transform.a, transform.b, transform.c, transform.d, transform.tx | 0, transform.ty | 0); } - else { + else + { context.setTransform(transform.a, transform.b, transform.c, transform.d, transform.tx, transform.ty); } - if (this.drawMode === Strip.DrawModes.TRIANGLE_STRIP) { + if (this.drawMode === Strip.DrawModes.TRIANGLE_STRIP) + { this._renderCanvasTriangleStrip(context); } - else { + else + { this._renderCanvasTriangles(context); } }; -Strip.prototype._renderCanvasTriangleStrip = function (context) { +Strip.prototype._renderCanvasTriangleStrip = function (context) +{ // draw triangles!! var vertices = this.vertices; var uvs = this.uvs; @@ -231,14 +249,16 @@ var length = vertices.length / 2; // this.count++; - for (var i = 0; i < length - 2; i++) { + for (var i = 0; i < length - 2; i++) + { // draw some triangles! var index = i * 2; this._renderCanvasDrawTriangle(context, vertices, uvs, index, (index + 2), (index + 4)); } }; -Strip.prototype._renderCanvasTriangles = function (context) { +Strip.prototype._renderCanvasTriangles = function (context) +{ // draw triangles!! var vertices = this.vertices; var uvs = this.uvs; @@ -247,14 +267,16 @@ var length = indices.length; // this.count++; - for (var i = 0; i < length; i += 3) { + for (var i = 0; i < length; i += 3) + { // draw some triangles! var index0 = indices[i] * 2, index1 = indices[i + 1] * 2, index2 = indices[i + 2] * 2; this._renderCanvasDrawTriangle(context, vertices, uvs, index0, index1, index2); } }; -Strip.prototype._renderCanvasDrawTriangle = function (context, vertices, uvs, index0, index1, index2) { +Strip.prototype._renderCanvasDrawTriangle = function (context, vertices, uvs, index0, index1, index2) +{ var textureSource = this.texture.baseTexture.source; var textureWidth = this.texture.width; var textureHeight = this.texture.height; @@ -265,7 +287,8 @@ var u0 = uvs[index0] * textureWidth, u1 = uvs[index1] * textureWidth, u2 = uvs[index2] * textureWidth; var v0 = uvs[index0 + 1] * textureHeight, v1 = uvs[index1 + 1] * textureHeight, v2 = uvs[index2 + 1] * textureHeight; - if (this.canvasPadding > 0) { + if (this.canvasPadding > 0) + { var paddingX = this.canvasPadding / this.worldTransform.a; var paddingY = this.canvasPadding / this.worldTransform.d; var centerX = (x0 + x1 + x2) / 3; @@ -332,7 +355,8 @@ * @param strip {Strip} The Strip to render * @private */ -Strip.prototype.renderStripFlat = function (strip) { +Strip.prototype.renderStripFlat = function (strip) +{ var context = this.context; var vertices = strip.vertices; @@ -340,7 +364,8 @@ // this.count++; context.beginPath(); - for (var i=1; i < length-2; i++) { + for (var i=1; i < length-2; i++) + { // draw some triangles! var index = i*2; @@ -358,7 +383,8 @@ }; /* -Strip.prototype.setTexture = function (texture) { +Strip.prototype.setTexture = function (texture) +{ //TODO SET THE TEXTURES //TODO VISIBILITY @@ -377,7 +403,8 @@ * @private */ -Strip.prototype.onTextureUpdate = function () { +Strip.prototype.onTextureUpdate = function () +{ this.updateFrame = true; }; @@ -387,7 +414,8 @@ * @param matrix {Matrix} the transformation matrix of the sprite * @return {Rectangle} the framing rectangle */ -Strip.prototype.getBounds = function (matrix) { +Strip.prototype.getBounds = function (matrix) +{ var worldTransform = matrix || this.worldTransform; var a = worldTransform.a; @@ -404,7 +432,8 @@ var minY = Infinity; var vertices = this.vertices; - for (var i = 0, n = vertices.length; i < n; i += 2) { + for (var i = 0, n = vertices.length; i < n; i += 2) + { var rawX = vertices[i], rawY = vertices[i + 1]; var x = (a * rawX) + (c * rawY) + tx; var y = (d * rawY) + (b * rawX) + ty; @@ -416,7 +445,8 @@ maxY = y > maxY ? y : maxY; } - if (minX === -Infinity || maxY === Infinity) { + if (minX === -Infinity || maxY === Infinity) + { return core.math.Rectangle.EMPTY; } diff --git a/src/extras/TilingSprite.js b/src/extras/TilingSprite.js index 3ac22df..31da393 100644 --- a/src/extras/TilingSprite.js +++ b/src/extras/TilingSprite.js @@ -10,7 +10,8 @@ * @param width {number} the width of the tiling sprite * @param height {number} the height of the tiling sprite */ -function TilingSprite(texture, width, height) { +function TilingSprite(texture, width, height) +{ core.Sprite.call( this, texture); /** @@ -86,10 +87,12 @@ * @memberof TilingSprite# */ width: { - get: function () { + get: function () + { return this._width; }, - set: function (value) { + set: function (value) + { this._width = value; } }, @@ -101,20 +104,25 @@ * @memberof TilingSprite# */ height: { - get: function () { + get: function () + { return this._height; }, - set: function (value) { + set: function (value) + { this._height = value; } }, texture: { - get: function () { + get: function () + { return this._texture; }, - set: function (value) { - if (this._texture === value) { + set: function (value) + { + if (this._texture === value) + { return; } @@ -130,51 +138,61 @@ * * @param renderer {WebGLRenderer} */ -TilingSprite.prototype.renderWebGL = function (renderer) { - if (!this.visible || this.alpha <= 0) { +TilingSprite.prototype.renderWebGL = function (renderer) +{ + if (!this.visible || this.alpha <= 0) + { return; } var i, j; - if (this._mask) { + if (this._mask) + { renderer.spriteBatch.stop(); renderer.maskManager.pushMask(this.mask, renderer); renderer.spriteBatch.start(); } - if (this._filters) { + if (this._filters) + { renderer.spriteBatch.flush(); renderer.filterManager.pushFilter(this._filterBlock); } - if (!this.tilingTexture || this.refreshTexture) { + if (!this.tilingTexture || this.refreshTexture) + { this.generateTilingTexture(true); - if (this.tilingTexture && this.tilingTexture.needsUpdate) { + if (this.tilingTexture && this.tilingTexture.needsUpdate) + { //TODO - tweaking renderer.updateTexture(this.tilingTexture.baseTexture); this.tilingTexture.needsUpdate = false; // this.tilingTexture._uvs = null; } } - else { + else + { renderer.spriteBatch.renderTilingSprite(this); } // simple render children! - for (i=0,j=this.children.length; i= 0 && index <= this.children.length) { - if (child.parent) { + if (index >= 0 && index <= this.children.length) + { + if (child.parent) + { child.parent.removeChild(child); } @@ -154,7 +173,8 @@ return child; } - else { + else + { throw new Error(child + 'addChildAt: The index '+ index +' supplied is out of bounds ' + this.children.length); } }; @@ -165,15 +185,18 @@ * @param child {DisplayObject} * @param child2 {DisplayObject} */ -DisplayObjectContainer.prototype.swapChildren = function (child, child2) { - if (child === child2) { +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) { + if (index1 < 0 || index2 < 0) + { throw new Error('swapChildren: Both the supplied DisplayObjects must be a child of the caller.'); } @@ -187,10 +210,12 @@ * @param child {DisplayObject} The DisplayObject instance to identify * @return {Number} The index position of the child display object to identify */ -DisplayObjectContainer.prototype.getChildIndex = function (child) { +DisplayObjectContainer.prototype.getChildIndex = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { throw new Error('The supplied DisplayObject must be a child of the caller'); } @@ -203,8 +228,10 @@ * @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 */ -DisplayObjectContainer.prototype.setChildIndex = function (child, index) { - if (index < 0 || index >= this.children.length) { +DisplayObjectContainer.prototype.setChildIndex = function (child, index) +{ + if (index < 0 || index >= this.children.length) + { throw new Error('The supplied index is out of bounds'); } @@ -220,8 +247,10 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child at the given index, if any. */ -DisplayObjectContainer.prototype.getChildAt = function (index) { - if (index < 0 || index >= this.children.length) { +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'); } @@ -234,10 +263,12 @@ * @param child {DisplayObject} The DisplayObject to remove * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChild = function (child) { +DisplayObjectContainer.prototype.removeChild = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { return; } @@ -250,7 +281,8 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChildAt = function (index) { +DisplayObjectContainer.prototype.removeChildAt = function (index) +{ var child = this.getChildAt(index); child.parent = null; @@ -265,24 +297,29 @@ * @param beginIndex {Number} The beginning position. Default value is 0. * @param endIndex {Number} The ending position. Default value is size of the container. */ -DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) { +DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) +{ var begin = beginIndex || 0; var end = typeof endIndex === 'number' ? endIndex : this.children.length; var range = end - begin; - if (range > 0 && range <= end) { + if (range > 0 && range <= end) + { var removed = this.children.splice(begin, range); - for (var i = 0; i < removed.length; ++i) { + for (var i = 0; i < removed.length; ++i) + { removed[i].parent = null; } return removed; } - else if (range === 0 && this.children.length === 0) { + else if (range === 0 && this.children.length === 0) + { return []; } - else { + else + { throw new RangeError('removeChildren: numeric values are outside the acceptable range.'); } }; @@ -291,7 +328,8 @@ * Generates and updates the cached sprite for this object. * */ -DisplayObjectContainer.prototype.updateCachedSprite = function () { +DisplayObjectContainer.prototype.updateCachedSprite = function () +{ this._generateCachedSprite(); }; @@ -304,7 +342,8 @@ * @param renderer {CanvasRenderer|WebGLRenderer} The renderer used to generate the texture. * @return {Texture} a texture of the graphics object */ -DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) { +DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) +{ var bounds = this.getLocalBounds(); var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0, renderer, scaleMode, resolution); @@ -322,18 +361,22 @@ * * @private */ -DisplayObjectContainer.prototype.updateTransform = function () { - if (!this.visible) { +DisplayObjectContainer.prototype.updateTransform = function () +{ + if (!this.visible) + { return; } this.displayObjectUpdateTransform(); - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { return; } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } }; @@ -346,8 +389,10 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getBounds = function () { - if (this.children.length === 0) { +DisplayObjectContainer.prototype.getBounds = function () +{ + if (this.children.length === 0) + { return math.Rectangle.EMPTY; } @@ -365,10 +410,12 @@ var childVisible = false; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -386,7 +433,8 @@ maxY = maxY > childMaxY ? maxY : childMaxY; } - if (!childVisible) { + if (!childVisible) + { return math.Rectangle.EMPTY; } @@ -407,12 +455,14 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getLocalBounds = function () { +DisplayObjectContainer.prototype.getLocalBounds = function () +{ var matrixCache = this.worldTransform; this.worldTransform = math.Matrix.IDENTITY; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } @@ -428,13 +478,16 @@ * * @param renderer {WebGLRenderer} The renderer */ -DisplayObjectContainer.prototype.renderWebGL = function (renderer) { +DisplayObjectContainer.prototype.renderWebGL = function (renderer) +{ // if the object is not visible or the alpha is 0 then no need to render this element - if (!this.visible || this.alpha <= 0) { + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } @@ -442,14 +495,17 @@ var i, j; // do a quick check to see if this element has a mask or a filter. - if (this._mask || this._filters) { + if (this._mask || this._filters) + { // push filter first as we need to ensure the stencil buffer is correct for any masking - if (this._filters) { + if (this._filters) + { renderer.spriteBatch.flush(); renderer.filterManager.pushFilter(this._filterBlock); } - if (this._mask) { + if (this._mask) + { renderer.spriteBatch.stop(); renderer.maskManager.pushMask(this.mask, renderer); renderer.spriteBatch.start(); @@ -459,36 +515,42 @@ this._renderWebGL(renderer); // now loop through the children and make sure they get rendered - for (i = 0, j = this.children.length; i < j; i++) { + for (i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderWebGL(renderer); } // time to stop the sprite batch as either a mask element or a filter draw will happen next renderer.spriteBatch.stop(); - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(this._mask, renderer); } - if (this._filters) { + if (this._filters) + { renderer.filterManager.popFilter(); } renderer.spriteBatch.start(); } - else { + else + { this._renderWebGL(renderer); // simple render children! - for (i = 0, j = this.children.length; i < j; ++i) { + for (i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderWebGL(renderer); } } }; -DisplayObjectContainer.prototype._renderWebGL = function (renderer) { +DisplayObjectContainer.prototype._renderWebGL = function (renderer) +{ // this is where content itself gets renderd.. @@ -499,25 +561,31 @@ * * @param renderer {CanvasRenderer} The renderer */ -DisplayObjectContainer.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0) { +DisplayObjectContainer.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -528,13 +596,16 @@ * @param renderer {WebGLRenderer|CanvasRenderer} The renderer * @private */ -DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) { +DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) +{ this._cachedSprite.worldAlpha = this.worldAlpha; - if (renderer.gl) { + if (renderer.gl) + { this._cachedSprite.renderWebGL(renderer); } - else { + else + { this._cachedSprite.renderCanvas(renderer); } }; @@ -544,10 +615,12 @@ * * @private */ -DisplayObjectContainer.prototype._generateCachedSprite = function () { +DisplayObjectContainer.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { // TODO - RenderTexture now *requires* a renderer instance, so this is like broken // because `renderer` isn't actually in scope here :P var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0); @@ -555,7 +628,8 @@ this._cachedSprite = new Sprite(renderTexture); this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.texture.resize(bounds.width | 0, bounds.height | 0); } @@ -580,8 +654,10 @@ * * @private */ -DisplayObjectContainer.prototype._destroyCachedSprite = function () { - if (!this._cachedSprite) { +DisplayObjectContainer.prototype._destroyCachedSprite = function () +{ + if (!this._cachedSprite) + { return; } diff --git a/src/core/display/Sprite.js b/src/core/display/Sprite.js index 707da24..5862aef 100644 --- a/src/core/display/Sprite.js +++ b/src/core/display/Sprite.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param texture {Texture} The texture for this sprite */ -function Sprite(texture) { +function Sprite(texture) +{ DisplayObjectContainer.call(this); /** @@ -85,12 +86,14 @@ this.texture = texture || Texture.EMPTY; } -Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) { +Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) +{ DisplayObjectContainer.prototype.destroy.call(this); this.anchor = null; - if (destroyTexture) { + if (destroyTexture) + { this._texture.destroy(destroyBaseTexture); } @@ -111,10 +114,12 @@ * @memberof Sprite# */ width: { - get: function () { + get: function () + { return this.scale.x * this.texture.frame.width; }, - set: function (value) { + set: function (value) + { this.scale.x = value / this.texture.frame.width; this._width = value; } @@ -127,10 +132,12 @@ * @memberof Sprite# */ height: { - get: function () { + get: function () + { return this.scale.y * this.texture.frame.height; }, - set: function (value) { + set: function (value) + { this.scale.y = value / this.texture.frame.height; this._height = value; } @@ -143,23 +150,29 @@ * @memberof Sprite# */ texture: { - get: function () { + get: function () + { return this._texture; }, - set: function (value) { - if (this._texture === value) { + set: function (value) + { + if (this._texture === value) + { return; } this._texture = value; this.cachedTint = 0xFFFFFF; - if (value) { + if (value) + { // wait for the texture to load - if (value.baseTexture.hasLoaded) { + if (value.baseTexture.hasLoaded) + { this._onTextureUpdate(); } - else { + else + { value.once('update', this._onTextureUpdate.bind(this)); } } @@ -172,18 +185,22 @@ * * @private */ -Sprite.prototype._onTextureUpdate = function () { +Sprite.prototype._onTextureUpdate = function () +{ // so if _width is 0 then width was not set.. - if (this._width) { + if (this._width) + { this.scale.x = this._width / this.texture.frame.width; } - if (this._height) { + if (this._height) + { this.scale.y = this._height / this.texture.frame.height; } }; -Sprite.prototype._renderWebGL = function (renderer) { +Sprite.prototype._renderWebGL = function (renderer) +{ // this is where content gets renderd.. // watch this space for a little render state manager.. @@ -197,7 +214,8 @@ * @param matrix {Matrix} the transformation matrix of the sprite * @return {Rectangle} the framing rectangle */ -Sprite.prototype.getBounds = function (matrix) { +Sprite.prototype.getBounds = function (matrix) +{ var width = this.texture.frame.width; var height = this.texture.frame.height; @@ -224,11 +242,13 @@ if(b === 0 && c === 0) { // scale may be negative! - if (a < 0) { + if (a < 0) + { a *= -1; } - if (d < 0) { + if (d < 0) + { d *= -1; } @@ -293,28 +313,34 @@ * * @param renderer {CanvasRenderer} The renderer */ -Sprite.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) { +Sprite.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) + { return; } - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; renderer.context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } // Ignore null sources - if (this.texture.valid) { + if (this.texture.valid) + { var resolution = this.texture.baseTexture.resolution / renderer.resolution; renderer.context.globalAlpha = this.worldAlpha; // If smoothingEnabled is supported and we need to change the smoothing property for this texture - if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) { + if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) + { renderer.scaleMode = this.texture.baseTexture.scaleMode; renderer.context[renderer.smoothProperty] = (renderer.scaleMode === CONST.scaleModes.LINEAR); } @@ -324,7 +350,8 @@ var dy = (this.texture.trim ? this.texture.trim.y : 0) - (this.anchor.y * this.texture.trim.height); // Allow for pixel rounding - if (renderer.roundPixels) { + if (renderer.roundPixels) + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -337,7 +364,8 @@ dx = dx | 0; dy = dy | 0; } - else { + else + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -348,8 +376,10 @@ ); } - if (this.tint !== 0xFFFFFF) { - if (this.cachedTint !== this.tint) { + if (this.tint !== 0xFFFFFF) + { + if (this.cachedTint !== this.tint) + { this.cachedTint = this.tint; // TODO clean up caching - how to clean up the caches? @@ -368,7 +398,8 @@ this.texture.crop.height / resolution ); } - else { + else + { renderer.context.drawImage( this.texture.baseTexture.source, this.texture.crop.x, @@ -383,11 +414,13 @@ } } - for (var i = 0, j = this.children.length; i < j; i++) { + for (var i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -402,10 +435,12 @@ * @param frameId {String} The frame Id of the texture in the cache * @return {Sprite} A new Sprite using a texture from the texture cache matching the frameId */ -Sprite.fromFrame = function (frameId) { +Sprite.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache' + this); } @@ -420,6 +455,7 @@ * @param imageId {String} The image url of the texture * @return {Sprite} A new Sprite using a texture from the texture cache matching the image id */ -Sprite.fromImage = function (imageId, crossorigin, scaleMode) { +Sprite.fromImage = function (imageId, crossorigin, scaleMode) +{ return new Sprite(Texture.fromImage(imageId, crossorigin, scaleMode)); }; diff --git a/src/core/display/SpriteBatch.js b/src/core/display/SpriteBatch.js index 3187777..c196fef 100644 --- a/src/core/display/SpriteBatch.js +++ b/src/core/display/SpriteBatch.js @@ -12,7 +12,8 @@ * ```js * var container = new SpriteBatch(); * - * for(var i = 0; i < 100; ++i) { + * for(var i = 0; i < 100; ++i) + * { * var sprite = new PIXI.Sprite.fromImage("myImage.png"); * container.addChild(sprite); * } @@ -25,7 +26,8 @@ */ //TODO RENAME to PARTICLE CONTAINER? -function SpriteBatch() { +function SpriteBatch() +{ DisplayObjectContainer.call(this); } @@ -38,7 +40,8 @@ * * @private */ -SpriteBatch.prototype.updateTransform = function () { +SpriteBatch.prototype.updateTransform = function () +{ // TODO don't need to! this.displayObjectUpdateTransform(); // PIXI.DisplayObjectContainer.prototype.updateTransform.call( this ); @@ -50,8 +53,10 @@ * @param renderer {WebGLRenderer} The webgl renderer * @private */ -SpriteBatch.prototype.renderWebGL = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderWebGL = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -71,8 +76,10 @@ * @param renderer {CanvasRenderer} The canvas renderer * @private */ -SpriteBatch.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -84,10 +91,12 @@ this.displayObjectUpdateTransform(); - for (var i = 0; i < this.children.length; ++i) { + for (var i = 0; i < this.children.length; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -95,9 +104,11 @@ context.globalAlpha = this.worldAlpha * child.alpha; - if (child.rotation % (Math.PI * 2) === 0) { + if (child.rotation % (Math.PI * 2) === 0) + { // this is the fastest way to optimise! - if rotation is 0 then we can avoid any kind of setTransform call - if (isRotated) { + if (isRotated) + { context.setTransform( transform.a, transform.b, @@ -122,8 +133,10 @@ frame.height * child.scale.y ); } - else { - if (!isRotated) { + else + { + if (!isRotated) + { isRotated = true; } @@ -131,7 +144,8 @@ var childTransform = child.worldTransform; - if (renderer.roundPixels) { + if (renderer.roundPixels) + { context.setTransform( childTransform.a, childTransform.b, @@ -141,7 +155,8 @@ childTransform.ty | 0 ); } - else { + else + { context.setTransform( childTransform.a, childTransform.b, diff --git a/src/core/index.js b/src/core/index.js index 3954b6f..eb4a82b 100644 --- a/src/core/index.js +++ b/src/core/index.js @@ -58,11 +58,13 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRenderer: function (width, height, options, noWebGL) { + autoDetectRenderer: function (width, height, options, noWebGL) + { width = width || 800; height = height || 600; - if (!noWebGL && require('webgl-enabled')()) { + if (!noWebGL && require('webgl-enabled')()) + { return new core.WebGLRenderer(width, height, options); } @@ -87,7 +89,8 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRecommendedRenderer: function (width, height, options) { + autoDetectRecommendedRenderer: function (width, height, options) + { var isAndroid = /Android/i.test(navigator.userAgent); return core.autoDetectRenderer(width, height, options, isAndroid); diff --git a/src/core/math/Matrix.js b/src/core/math/Matrix.js index c2f87e2..2ff4848 100644 --- a/src/core/math/Matrix.js +++ b/src/core/math/Matrix.js @@ -10,7 +10,8 @@ * @class * @namespace PIXI */ -function Matrix() { +function Matrix() +{ /** * @member {number} * @default 1 @@ -63,7 +64,8 @@ * * @param array {number[]} The array that the matrix will be populated from. */ -Matrix.prototype.fromArray = function (array) { +Matrix.prototype.fromArray = function (array) +{ this.a = array[0]; this.b = array[1]; this.c = array[3]; @@ -78,14 +80,17 @@ * @param transpose {boolean} Whether we need to transpose the matrix or not * @return {number[]} the newly created array which contains the matrix */ -Matrix.prototype.toArray = function (transpose) { - if (!this.array) { +Matrix.prototype.toArray = function (transpose) +{ + if (!this.array) + { this.array = new Float32Array(9); } var array = this.array; - if (transpose) { + if (transpose) + { array[0] = this.a; array[1] = this.b; array[2] = 0; @@ -96,7 +101,8 @@ array[7] = this.ty; array[8] = 1; } - else { + else + { array[0] = this.a; array[1] = this.c; array[2] = this.tx; @@ -119,7 +125,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, transformed through this matrix */ -Matrix.prototype.apply = function (pos, newPos) { +Matrix.prototype.apply = function (pos, newPos) +{ newPos = newPos || new Point(); newPos.x = this.a * pos.x + this.c * pos.y + this.tx; @@ -136,7 +143,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, inverse-transformed through this matrix */ -Matrix.prototype.applyInverse = function (pos, newPos) { +Matrix.prototype.applyInverse = function (pos, newPos) +{ newPos = newPos || new Point(); var id = 1 / (this.a * this.d + this.c * -this.b); @@ -154,7 +162,8 @@ * @param {number} y * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.translate = function (x, y) { +Matrix.prototype.translate = function (x, y) +{ this.tx += x; this.ty += y; @@ -168,7 +177,8 @@ * @param {number} y The amount to scale vertically * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.scale = function (x, y) { +Matrix.prototype.scale = function (x, y) +{ this.a *= x; this.d *= y; this.c *= x; @@ -186,7 +196,8 @@ * @param {number} angle - The angle in radians. * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.rotate = function (angle) { +Matrix.prototype.rotate = function (angle) +{ var cos = Math.cos( angle ); var sin = Math.sin( angle ); @@ -210,7 +221,8 @@ * @param {Matrix} matrix * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.append = function (matrix) { +Matrix.prototype.append = function (matrix) +{ var a1 = this.a; var b1 = this.b; var c1 = this.c; @@ -232,7 +244,8 @@ * * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.identity = function () { +Matrix.prototype.identity = function () +{ this.a = 1; this.b = 0; this.c = 0; diff --git a/src/core/math/Point.js b/src/core/math/Point.js index 7565b2d..632f346 100644 --- a/src/core/math/Point.js +++ b/src/core/math/Point.js @@ -7,7 +7,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -function Point(x, y) { +function Point(x, y) +{ /** * @member {number} * @default 0 @@ -29,7 +30,8 @@ * * @return {Point} a copy of the point */ -Point.prototype.clone = function () { +Point.prototype.clone = function () +{ return new Point(this.x, this.y); }; @@ -40,7 +42,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -Point.prototype.set = function (x, y) { +Point.prototype.set = function (x, y) +{ this.x = x || 0; this.y = y || ( (y !== 0) ? this.x : 0 ) ; }; diff --git a/src/core/math/shapes/Circle.js b/src/core/math/shapes/Circle.js index 69cfdc9..4d76efc 100644 --- a/src/core/math/shapes/Circle.js +++ b/src/core/math/shapes/Circle.js @@ -10,7 +10,8 @@ * @param y {number} The Y coordinate of the center of this circle * @param radius {number} The radius of the circle */ -function Circle(x, y, radius) { +function Circle(x, y, radius) +{ /** * @member {number} * @default 0 @@ -46,7 +47,8 @@ * @method clone * @return {Circle} a copy of the Circle */ -Circle.prototype.clone = function () { +Circle.prototype.clone = function () +{ return new Circle(this.x, this.y, this.radius); }; @@ -58,8 +60,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Circle */ -Circle.prototype.contains = function (x, y) { - if (this.radius <= 0) { +Circle.prototype.contains = function (x, y) +{ + if (this.radius <= 0) + { return false; } @@ -79,6 +83,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Circle.prototype.getBounds = function () { +Circle.prototype.getBounds = function () +{ return new Rectangle(this.x - this.radius, this.y - this.radius, this.radius * 2, this.radius * 2); }; diff --git a/src/core/math/shapes/Ellipse.js b/src/core/math/shapes/Ellipse.js index 4f2d066..fefd01a 100644 --- a/src/core/math/shapes/Ellipse.js +++ b/src/core/math/shapes/Ellipse.js @@ -11,7 +11,8 @@ * @param width {number} The half width of this ellipse * @param height {number} The half height of this ellipse */ -function Ellipse(x, y, width, height) { +function Ellipse(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -53,7 +54,8 @@ * @method clone * @return {Ellipse} a copy of the ellipse */ -Ellipse.prototype.clone = function () { +Ellipse.prototype.clone = function () +{ return new Ellipse(this.x, this.y, this.width, this.height); }; @@ -65,8 +67,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coords are within this ellipse */ -Ellipse.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Ellipse.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } @@ -86,6 +90,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Ellipse.prototype.getBounds = function () { +Ellipse.prototype.getBounds = function () +{ return new Rectangle(this.x - this.width, this.y - this.height, this.width, this.height); }; diff --git a/src/core/math/shapes/Polygon.js b/src/core/math/shapes/Polygon.js index ae89148..fea6d37 100644 --- a/src/core/math/shapes/Polygon.js +++ b/src/core/math/shapes/Polygon.js @@ -10,16 +10,20 @@ * arguments passed can be flat x,y values e.g. `new Polygon(x,y, x,y, x,y, ...)` where `x` and `y` are * Numbers. */ -function Polygon(points) { +function Polygon(points) +{ //if points isn't an array, use arguments as the array - if (!(points instanceof Array)) { + if (!(points instanceof Array)) + { points = Array.prototype.slice.call(arguments); } //if this is a flat array of numbers, convert it to points - if (points[0] instanceof Point) { + if (points[0] instanceof Point) + { var p = []; - for (var i = 0, il = points.length; i < il; i++) { + for (var i = 0, il = points.length; i < il; i++) + { p.push(points[i].x, points[i].y); } @@ -51,7 +55,8 @@ * * @return {Polygon} a copy of the polygon */ -Polygon.prototype.clone = function () { +Polygon.prototype.clone = function () +{ return new Polygon(this.points.slice()); }; @@ -62,19 +67,22 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this polygon */ -Polygon.prototype.contains = function (x, y) { +Polygon.prototype.contains = function (x, y) +{ var inside = false; // use some raycasting to test hits // https://github.com/substack/point-in-polygon/blob/master/index.js var length = this.points.length / 2; - for (var i = 0, j = length - 1; i < length; j = i++) { + for (var i = 0, j = length - 1; i < length; j = i++) + { var xi = this.points[i * 2], yi = this.points[i * 2 + 1], xj = this.points[j * 2], yj = this.points[j * 2 + 1], intersect = ((yi > y) !== (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi); - if (intersect) { + if (intersect) + { inside = !inside; } } diff --git a/src/core/math/shapes/Rectangle.js b/src/core/math/shapes/Rectangle.js index 16ac62a..4008b68 100644 --- a/src/core/math/shapes/Rectangle.js +++ b/src/core/math/shapes/Rectangle.js @@ -10,7 +10,8 @@ * @param width {number} The overall width of this rectangle * @param height {number} The overall height of this rectangle */ -function Rectangle(x, y, width, height) { +function Rectangle(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -60,7 +61,8 @@ * * @return {Rectangle} a copy of the rectangle */ -Rectangle.prototype.clone = function () { +Rectangle.prototype.clone = function () +{ return new Rectangle(this.x, this.y, this.width, this.height); }; @@ -71,13 +73,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rectangle */ -Rectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Rectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/math/shapes/RoundedRectangle.js b/src/core/math/shapes/RoundedRectangle.js index 27d286e..7bf6411 100644 --- a/src/core/math/shapes/RoundedRectangle.js +++ b/src/core/math/shapes/RoundedRectangle.js @@ -11,7 +11,8 @@ * @param height {number} The overall height of this rounded rectangle * @param radius {number} Controls the radius of the rounded corners */ -function RoundedRectangle(x, y, width, height, radius) { +function RoundedRectangle(x, y, width, height, radius) +{ /** * @member {number} * @default 0 @@ -58,7 +59,8 @@ * * @return {RoundedRectangle} a copy of the rounded rectangle */ -RoundedRectangle.prototype.clone = function () { +RoundedRectangle.prototype.clone = function () +{ return new RoundedRectangle(this.x, this.y, this.width, this.height, this.radius); }; @@ -69,13 +71,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rounded Rectangle */ -RoundedRectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +RoundedRectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/primitives/Graphics.js b/src/core/primitives/Graphics.js index 261c534..e902d2a 100644 --- a/src/core/primitives/Graphics.js +++ b/src/core/primitives/Graphics.js @@ -16,7 +16,8 @@ * @extends DisplayObjectContainer * @namespace PIXI */ -function Graphics() { +function Graphics() +{ DisplayObjectContainer.call(this); this.renderable = true; @@ -154,16 +155,20 @@ * @private */ cacheAsBitmap: { - get: function () { + get: function () + { return this._cacheAsBitmap; }, - set: function (value) { + set: function (value) + { this._cacheAsBitmap = value; - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._generateCachedSprite(); } - else { + else + { this.destroyCachedSprite(); this.dirty = true; } @@ -176,7 +181,8 @@ * * @return {Graphics} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ var clone = new Graphics(); clone.renderable = this.renderable; @@ -192,7 +198,8 @@ clone.cachedSpriteDirty = this.cachedSpriteDirty; // copy graphics data - for (var i = 0; i < this.graphicsData.length; ++i) { + for (var i = 0; i < this.graphicsData.length; ++i) + { clone.graphicsData.push(this.graphicsData.clone()); } @@ -211,17 +218,21 @@ * @param alpha {number} alpha of the line to draw, will update the objects stored style * @return {Graphics} */ -Graphics.prototype.lineStyle = function (lineWidth, color, alpha) { +Graphics.prototype.lineStyle = function (lineWidth, color, alpha) +{ this.lineWidth = lineWidth || 0; this.lineColor = color || 0; this.lineAlpha = (arguments.length < 3) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length) + { // halfway through a line? start a new one! this.drawShape( new math.Polygon( this.currentPath.shape.points.slice(-2) )); } - else { + else + { // otherwise its empty so lets just set the line properties this.currentPath.lineWidth = this.lineWidth; this.currentPath.lineColor = this.lineColor; @@ -239,7 +250,8 @@ * @param y {number} the Y coordinate to move to * @return {Graphics} */ -Graphics.prototype.moveTo = function (x, y) { +Graphics.prototype.moveTo = function (x, y) +{ this.drawShape(new math.Polygon([x,y])); return this; @@ -253,7 +265,8 @@ * @param y {number} the Y coordinate to draw to * @return {Graphics} */ -Graphics.prototype.lineTo = function (x, y) { +Graphics.prototype.lineTo = function (x, y) +{ this.currentPath.shape.points.push(x, y); this.dirty = true; @@ -270,13 +283,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -285,7 +302,8 @@ n = 20, points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { this.moveTo(0, 0); } @@ -293,7 +311,8 @@ var fromY = points[points.length-1]; var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; xa = fromX + ( (cpX - fromX) * j ); @@ -319,13 +338,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -342,7 +365,8 @@ var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; dt = (1 - j); @@ -373,13 +397,17 @@ * @param radius {number} The radius of the arc * @return {Graphics} */ -Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points.push(x1, y1); } } - else { + else + { this.moveTo(x1, y1); } @@ -392,12 +420,15 @@ b2 = x2 - x1, mm = Math.abs(a1 * b2 - b1 * a2); - if (mm < 1.0e-8 || radius === 0) { - if (points[points.length-2] !== x1 || points[points.length-1] !== y1) { + if (mm < 1.0e-8 || radius === 0) + { + if (points[points.length-2] !== x1 || points[points.length-1] !== y1) + { points.push(x1, y1); } } - else { + else + { var dd = a1 * a1 + b1 * b1, cc = a2 * a2 + b2 * b2, tt = a1 * a2 + b1 * b2, @@ -433,42 +464,51 @@ * @param anticlockwise {boolean} Optional. Specifies whether the drawing should be counterclockwise or clockwise. False is default, and indicates clockwise, while true indicates counter-clockwise. * @return {Graphics} */ -Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) { +Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) +{ var startX = cx + Math.cos(startAngle) * radius; var startY = cy + Math.sin(startAngle) * radius; var points; // TODO - This if-else makes no sense. It uses currentPath in the else where it doesn't exist... - if (this.currentPath) { + if (this.currentPath) + { points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { points.push(startX, startY); } - else if (points[points.length-2] !== startX || points[points.length-1] !== startY) { + else if (points[points.length-2] !== startX || points[points.length-1] !== startY) + { points.push(startX, startY); } } - else { + else + { this.moveTo(startX, startY); points = this.currentPath.shape.points; } - if (startAngle === endAngle) { + if (startAngle === endAngle) + { return this; } - if (!anticlockwise && endAngle <= startAngle) { + if (!anticlockwise && endAngle <= startAngle) + { endAngle += Math.PI * 2; } - else if (anticlockwise && startAngle <= endAngle) { + else if (anticlockwise && startAngle <= endAngle) + { startAngle += Math.PI * 2; } var sweep = anticlockwise ? (startAngle - endAngle) *-1 : (endAngle - startAngle); var segs = (Math.abs(sweep)/ (Math.PI * 2)) * 40; - if (sweep === 0) { + if (sweep === 0) + { return this; } @@ -482,7 +522,8 @@ var remainder = ( segMinus % 1 ) / segMinus; - for (var i = 0; i <= segMinus; ++i) { + for (var i = 0; i <= segMinus; ++i) + { var real = i + remainder * i; var angle = ((theta) + startAngle + (theta2 * real)); @@ -506,13 +547,16 @@ * @param alpha {number} the alpha of the fill * @return {Graphics} */ -Graphics.prototype.beginFill = function (color, alpha) { +Graphics.prototype.beginFill = function (color, alpha) +{ this.filling = true; this.fillColor = color || 0; this.fillAlpha = (alpha === undefined) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length <= 2) + { this.currentPath.fill = this.filling; this.currentPath.fillColor = this.fillColor; this.currentPath.fillAlpha = this.fillAlpha; @@ -526,7 +570,8 @@ * * @return {Graphics} */ -Graphics.prototype.endFill = function () { +Graphics.prototype.endFill = function () +{ this.filling = false; this.fillColor = null; this.fillAlpha = 1; @@ -542,7 +587,8 @@ * @param height {number} The height of the rectangle * @return {Graphics} */ -Graphics.prototype.drawRect = function ( x, y, width, height ) { +Graphics.prototype.drawRect = function ( x, y, width, height ) +{ this.drawShape(new math.Rectangle(x,y, width, height)); return this; @@ -556,7 +602,8 @@ * @param height {number} The height of the rectangle * @param radius {number} Radius of the rectangle corners */ -Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) { +Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) +{ this.drawShape(new math.RoundedRectangle(x, y, width, height, radius)); return this; @@ -570,7 +617,8 @@ * @param radius {number} The radius of the circle * @return {Graphics} */ -Graphics.prototype.drawCircle = function (x, y, radius) { +Graphics.prototype.drawCircle = function (x, y, radius) +{ this.drawShape(new math.Circle(x,y, radius)); return this; @@ -585,7 +633,8 @@ * @param height {number} The half height of the ellipse * @return {Graphics} */ -Graphics.prototype.drawEllipse = function (x, y, width, height) { +Graphics.prototype.drawEllipse = function (x, y, width, height) +{ this.drawShape(new math.Ellipse(x, y, width, height)); return this; @@ -597,8 +646,10 @@ * @param path {Array} The path data used to construct the polygon. * @return {Graphics} */ -Graphics.prototype.drawPolygon = function (path) { - if (!(path instanceof Array)) { +Graphics.prototype.drawPolygon = function (path) +{ + if (!(path instanceof Array)) + { path = Array.prototype.slice.call(arguments); } @@ -612,7 +663,8 @@ * * @return {Graphics} */ -Graphics.prototype.clear = function () { +Graphics.prototype.clear = function () +{ this.lineWidth = 0; this.filling = false; @@ -631,7 +683,8 @@ * @param scaleMode {number} Should be one of the scaleMode consts * @return {Texture} a texture of the graphics object */ -Graphics.prototype.generateTexture = function (resolution, scaleMode) { +Graphics.prototype.generateTexture = function (resolution, scaleMode) +{ resolution = resolution || 1; var bounds = this.getBounds(); @@ -655,17 +708,21 @@ * * @param renderer {WebGLRenderer} */ -Graphics.prototype._renderWebGL = function (renderer) { +Graphics.prototype._renderWebGL = function (renderer) +{ // if the sprite is not visible or the alpha is 0 then no need to render this element - if (this.isMask === true) { + if (this.isMask === true) + { return; } // this code may still be needed so leaving for now.. - // + // /* - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture on the gpu too! @@ -681,17 +738,24 @@ return; } - */ - - // check if the webgl graphic needs to be updated - if (this.glDirty) { - this.dirty = true; - this.glDirty = false; - } + else */ - renderer.setObjectRendererer(renderer.graphicsRenderer); - renderer.graphicsRenderer.render(this); + renderer.spriteBatch.stop(); + renderer.blendModeManager.setBlendMode(this.blendMode); + // check blend mode + renderer.blendModeManager.setBlendMode( this.blendMode ); + + // check if the webgl graphic needs to be updated + if (this.glDirty) + { + this.dirty = true; + this.glDirty = false; + } + + WebGLGraphics.renderGraphics(this, renderer); + + renderer.spriteBatch.start(); }; /** @@ -700,14 +764,18 @@ * @param renderer {CanvasRenderer} * @private */ -Graphics.prototype.renderCanvas = function (renderer) { +Graphics.prototype.renderCanvas = function (renderer) +{ // 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.isMask === true) { + if (!this.visible || this.alpha <= 0 || this.isMask === true) + { return; } - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture @@ -723,16 +791,19 @@ return; } - else { + else + { var context = renderer.context; var transform = this.worldTransform; - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } @@ -748,11 +819,13 @@ CanvasGraphics.renderGraphics(this, context); - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } } @@ -763,13 +836,16 @@ * * @return {Rectangle} the rectangular bounding area */ -Graphics.prototype.getBounds = function (matrix) { +Graphics.prototype.getBounds = function (matrix) +{ // return an empty object if the item is a mask! - if (this.isMask) { + if (this.isMask) + { return math.Rectangle.EMPTY; } - if (this.dirty) { + if (this.dirty) + { this.updateLocalBounds(); this.glDirty = true; @@ -841,23 +917,27 @@ * Update the bounds of the object * */ -Graphics.prototype.updateLocalBounds = function () { +Graphics.prototype.updateLocalBounds = function () +{ var minX = Infinity; var maxX = -Infinity; var minY = Infinity; var maxY = -Infinity; - if (this.graphicsData.length) { + if (this.graphicsData.length) + { var shape, points, x, y, w, h; - for (var i = 0; i < this.graphicsData.length; i++) { + for (var i = 0; i < this.graphicsData.length; i++) + { var data = this.graphicsData[i]; var type = data.type; var lineWidth = data.lineWidth; shape = data.shape; - if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) { + if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) + { x = shape.x - lineWidth/2; y = shape.y - lineWidth/2; w = shape.width + lineWidth; @@ -869,7 +949,8 @@ minY = y < minY ? y : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.CIRC) { + else if (type === CONST.SHAPES.CIRC) + { x = shape.x; y = shape.y; w = shape.radius + lineWidth/2; @@ -881,7 +962,8 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.ELIP) { + else if (type === CONST.SHAPES.ELIP) + { x = shape.x; y = shape.y; w = shape.width + lineWidth/2; @@ -893,11 +975,13 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else { + else + { // POLY points = shape.points; - for (var j = 0; j < points.length; j += 2) { + for (var j = 0; j < points.length; j += 2) + { x = points[j]; y = points[j+1]; @@ -910,7 +994,8 @@ } } } - else { + else + { minX = 0; maxX = 0; minY = 0; @@ -931,10 +1016,12 @@ * * @private */ -Graphics.prototype._generateCachedSprite = function () { +Graphics.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { var canvasBuffer = new CanvasBuffer(bounds.width, bounds.height); var texture = Texture.fromCanvas(canvasBuffer.canvas); @@ -943,7 +1030,8 @@ this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.buffer.resize(bounds.width, bounds.height); } @@ -968,7 +1056,8 @@ * * @private */ -Graphics.prototype.updateCachedSpriteTexture = function () { +Graphics.prototype.updateCachedSpriteTexture = function () +{ var cachedSprite = this._cachedSprite; var texture = cachedSprite.texture; var canvas = cachedSprite.buffer.canvas; @@ -989,7 +1078,8 @@ * Destroys a previous cached sprite. * */ -Graphics.prototype.destroyCachedSprite = function () { +Graphics.prototype.destroyCachedSprite = function () +{ this._cachedSprite.texture.destroy(true); // let the gc collect the unused sprite @@ -1003,10 +1093,13 @@ * @param {Circle|Rectangle|Ellipse|Line|Polygon} shape The Shape object to draw. * @return {GraphicsData} The generated GraphicsData object. */ -Graphics.prototype.drawShape = function (shape) { - if (this.currentPath) { +Graphics.prototype.drawShape = function (shape) +{ + if (this.currentPath) + { // check current path! - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath.shape.points.length <= 2) + { this.graphicsData.pop(); } } @@ -1017,7 +1110,8 @@ this.graphicsData.push(data); - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { data.shape.closed = this.filling; this.currentPath = data; } diff --git a/src/core/primitives/GraphicsData.js b/src/core/primitives/GraphicsData.js index 99decbe..788f6f2 100644 --- a/src/core/primitives/GraphicsData.js +++ b/src/core/primitives/GraphicsData.js @@ -4,7 +4,8 @@ * @class * @namespace PIXI */ -function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) { +function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) +{ this.lineWidth = lineWidth; this.lineColor = lineColor; this.lineAlpha = lineAlpha; @@ -27,7 +28,8 @@ * * @return {GraphicsData} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ return new GraphicsData( this.lineWidth, this.lineColor, diff --git a/src/core/renderers/canvas/CanvasRenderer.js b/src/core/renderers/canvas/CanvasRenderer.js index 15a0978..7aebd44 100644 --- a/src/core/renderers/canvas/CanvasRenderer.js +++ b/src/core/renderers/canvas/CanvasRenderer.js @@ -17,17 +17,22 @@ * @param [options.resolution=1] {number} the resolution of the renderer retina would be 2 * @param [options.clearBeforeRender=true] {boolean} This sets if the CanvasRenderer will clear the canvas or not before the new render pass. */ -function CanvasRenderer(width, height, options) { +function CanvasRenderer(width, height, options) +{ utils.sayHello('Canvas'); - if (options) { - for (var i in CONST.defaultRenderOptions) { - if (typeof options[i] === 'undefined') { + if (options) + { + for (var i in CONST.defaultRenderOptions) + { + if (typeof options[i] === 'undefined') + { options[i] = CONST.defaultRenderOptions[i]; } } } - else { + else + { options = CONST.defaultRenderOptions; } @@ -156,19 +161,24 @@ this.smoothProperty = null; - if (this.context.imageSmoothingEnabled) { + if (this.context.imageSmoothingEnabled) + { this.smoothProperty = 'imageSmoothingEnabled'; } - else if (this.context.webkitImageSmoothingEnabled) { + else if (this.context.webkitImageSmoothingEnabled) + { this.smoothProperty = 'webkitImageSmoothingEnabled'; } - else if (this.context.mozImageSmoothingEnabled) { + else if (this.context.mozImageSmoothingEnabled) + { this.smoothProperty = 'mozImageSmoothingEnabled'; } - else if (this.context.oImageSmoothingEnabled) { + else if (this.context.oImageSmoothingEnabled) + { this.smoothProperty = 'oImageSmoothingEnabled'; } - else if (this.context.msImageSmoothingEnabled) { + else if (this.context.msImageSmoothingEnabled) + { this.smoothProperty = 'msImageSmoothingEnabled'; } @@ -193,10 +203,12 @@ * @memberof CanvasRenderer# */ backgroundColor: { - get: function () { + get: function () + { return this._backgroundColor; }, - set: function (val) { + set: function (val) + { this._backgroundColor = val; this._backgroundColorString = utils.hex2string(val); } @@ -208,7 +220,8 @@ * * @param object {DisplayObject} the object to be rendered */ -CanvasRenderer.prototype.render = function (object) { +CanvasRenderer.prototype.render = function (object) +{ object.updateTransform(); this.context.setTransform(1,0,0,1,0,0); @@ -218,16 +231,20 @@ this.currentBlendMode = CONST.blendModes.NORMAL; this.context.globalCompositeOperation = this.blendModes[CONST.blendModes.NORMAL]; - if (navigator.isCocoonJS && this.view.screencanvas) { + if (navigator.isCocoonJS && this.view.screencanvas) + { this.context.fillStyle = 'black'; this.context.clear(); } - if (this.clearBeforeRender) { - if (this.transparent) { + if (this.clearBeforeRender) + { + if (this.transparent) + { this.context.clearRect(0, 0, this.width, this.height); } - else { + else + { this.context.fillStyle = this._backgroundColorString; this.context.fillRect(0, 0, this.width , this.height); } @@ -241,8 +258,10 @@ * * @param [removeView=false] {boolean} Removes the Canvas element from the DOM. */ -CanvasRenderer.prototype.destroy = function (removeView) { - if (removeView && this.view.parent) { +CanvasRenderer.prototype.destroy = function (removeView) +{ + if (removeView && this.view.parent) + { this.view.parent.removeChild(this.view); } @@ -257,14 +276,16 @@ * @param width {number} the new width of the canvas view * @param height {number} the new height of the canvas view */ -CanvasRenderer.prototype.resize = function (width, height) { +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) { + if (this.autoResize) + { this.view.style.width = this.width / this.resolution + 'px'; this.view.style.height = this.height / this.resolution + 'px'; } @@ -276,7 +297,8 @@ * @param displayObject {DisplayObject} The displayObject to render * @private */ -CanvasRenderer.prototype.renderDisplayObject = function (displayObject) { +CanvasRenderer.prototype.renderDisplayObject = function (displayObject) +{ displayObject.renderCanvas(this); }; @@ -285,11 +307,14 @@ * * @private */ -CanvasRenderer.prototype._mapBlendModes = function () { - if (!this.blendModes) { +CanvasRenderer.prototype._mapBlendModes = function () +{ + if (!this.blendModes) + { this.blendModes = {}; - if (utils.canUseNewCanvasBlendModes()) { + if (utils.canUseNewCanvasBlendModes()) + { this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? this.blendModes[CONST.blendModes.MULTIPLY] = 'multiply'; @@ -308,7 +333,8 @@ this.blendModes[CONST.blendModes.COLOR] = 'color'; this.blendModes[CONST.blendModes.LUMINOSITY] = 'luminosity'; } - else { + else + { // this means that the browser does not support the cool new blend modes in canvas 'cough' ie 'cough' this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? diff --git a/src/core/renderers/canvas/utils/CanvasBuffer.js b/src/core/renderers/canvas/utils/CanvasBuffer.js index ebe5d47..b183a66 100644 --- a/src/core/renderers/canvas/utils/CanvasBuffer.js +++ b/src/core/renderers/canvas/utils/CanvasBuffer.js @@ -6,7 +6,8 @@ * @param width {number} the width for the newly created canvas * @param height {number} the height for the newly created canvas */ -function CanvasBuffer(width, height) { +function CanvasBuffer(width, height) +{ /** * The Canvas object that belongs to this CanvasBuffer. * @@ -36,10 +37,12 @@ * @memberof CanvasBuffer# */ width: { - get: function () { + get: function () + { return this.canvas.width; }, - set: function (val) { + set: function (val) + { this.canvas.width = val; } }, @@ -50,10 +53,12 @@ * @memberof CanvasBuffer# */ height: { - get: function () { + get: function () + { return this.canvas.height; }, - set: function (val) { + set: function (val) + { this.canvas.height = val; } } @@ -64,7 +69,8 @@ * * @private */ -CanvasBuffer.prototype.clear = function () { +CanvasBuffer.prototype.clear = function () +{ this.context.setTransform(1, 0, 0, 1, 0, 0); this.context.clearRect(0,0, this.canvas.width, this.canvas.height); }; @@ -75,7 +81,8 @@ * @param width {number} the new width of the canvas * @param height {number} the new height of the canvas */ -CanvasBuffer.prototype.resize = function (width, height) { +CanvasBuffer.prototype.resize = function (width, height) +{ this.canvas.width = width; this.canvas.height = height; }; diff --git a/src/core/renderers/canvas/utils/CanvasGraphics.js b/src/core/renderers/canvas/utils/CanvasGraphics.js index c7eaa2a..3f2a91f 100644 --- a/src/core/renderers/canvas/utils/CanvasGraphics.js +++ b/src/core/renderers/canvas/utils/CanvasGraphics.js @@ -13,15 +13,18 @@ * @param graphics {Graphics} the actual graphics object to render * @param context {CanvasRenderingContext2D} the 2d drawing method of the canvas */ -CanvasGraphics.renderGraphics = function (graphics, context) { +CanvasGraphics.renderGraphics = function (graphics, context) +{ var worldAlpha = graphics.worldAlpha; - if (graphics.dirty) { + if (graphics.dirty) + { this.updateGraphicsTint(graphics); graphics.dirty = false; } - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; @@ -30,69 +33,82 @@ context.lineWidth = data.lineWidth; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { context.beginPath(); var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } - if (shape.closed) { + if (shape.closed) + { context.lineTo(points[0], points[1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fillRect(shape.x, shape.y, shape.width, shape.height); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.strokeRect(shape.x, shape.y, shape.width, shape.height); } } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.beginPath(); context.arc(shape.x, shape.y, shape.radius,0,2*Math.PI); context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas var w = shape.width * 2; @@ -119,18 +135,21 @@ context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; var width = shape.width; @@ -152,13 +171,15 @@ context.quadraticCurveTo(rx, ry, rx, ry + radius); context.closePath(); - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); @@ -174,45 +195,54 @@ * @param graphics {Graphics} the graphics which will be used as a mask * @param context {CanvasRenderingContext2D} the context 2d method of the canvas */ -CanvasGraphics.renderGraphicsMask = function (graphics, context) { +CanvasGraphics.renderGraphicsMask = function (graphics, context) +{ var len = graphics.graphicsData.length; - if (len === 0) { + if (len === 0) + { return; } context.beginPath(); - for (var i = 0; i < len; i++) { + for (var i = 0; i < len; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { context.rect(shape.x, shape.y, shape.width, shape.height); context.closePath(); } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.arc(shape.x, shape.y, shape.radius, 0, 2 * Math.PI); context.closePath(); } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas @@ -237,7 +267,8 @@ context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); context.closePath(); } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; @@ -262,8 +293,10 @@ } }; -CanvasGraphics.updateGraphicsTint = function (graphics) { - if (graphics.tint === 0xFFFFFF) { +CanvasGraphics.updateGraphicsTint = function (graphics) +{ + if (graphics.tint === 0xFFFFFF) + { return; } @@ -271,7 +304,8 @@ var tintG = (graphics.tint >> 8 & 0xFF) / 255; var tintB = (graphics.tint & 0xFF)/ 255; - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var fillColor = data.fillColor | 0; diff --git a/src/core/renderers/canvas/utils/CanvasMaskManager.js b/src/core/renderers/canvas/utils/CanvasMaskManager.js index e04a733..9827d36 100644 --- a/src/core/renderers/canvas/utils/CanvasMaskManager.js +++ b/src/core/renderers/canvas/utils/CanvasMaskManager.js @@ -6,7 +6,8 @@ * @class * @namespace PIXI */ -function CanvasMaskManager() {} +function CanvasMaskManager() +{} CanvasMaskManager.prototype.constructor = CanvasMaskManager; module.exports = CanvasMaskManager; @@ -17,7 +18,8 @@ * @param maskData {object} the maskData that will be pushed * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.pushMask = function (maskData, renderer) { +CanvasMaskManager.prototype.pushMask = function (maskData, renderer) +{ renderer.context.save(); var cacheAlpha = maskData.alpha; @@ -45,6 +47,7 @@ * * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.popMask = function (renderer) { +CanvasMaskManager.prototype.popMask = function (renderer) +{ renderer.context.restore(); }; diff --git a/src/core/renderers/canvas/utils/CanvasTinter.js b/src/core/renderers/canvas/utils/CanvasTinter.js index 17e0529..d2fb1bc 100644 --- a/src/core/renderers/canvas/utils/CanvasTinter.js +++ b/src/core/renderers/canvas/utils/CanvasTinter.js @@ -14,7 +14,8 @@ * @param color {number} the color to use to tint the sprite with * @return {HTMLCanvasElement} The tinted canvas */ -CanvasTinter.getTintedTexture = function (sprite, color) { +CanvasTinter.getTintedTexture = function (sprite, color) +{ var texture = sprite.texture; color = CanvasTinter.roundColor(color); @@ -23,7 +24,8 @@ texture.tintCache = texture.tintCache || {}; - if (texture.tintCache[stringColor]) { + if (texture.tintCache[stringColor]) + { return texture.tintCache[stringColor]; } @@ -33,14 +35,16 @@ //CanvasTinter.tintWithPerPixel(texture, stringColor, canvas); CanvasTinter.tintMethod(texture, color, canvas); - if (CanvasTinter.convertTintToImage) { + if (CanvasTinter.convertTintToImage) + { // is this better? var tintImage = new Image(); tintImage.src = canvas.toDataURL(); texture.tintCache[stringColor] = tintImage; } - else { + else + { texture.tintCache[stringColor] = canvas; // if we are not converting the texture to an image then we need to lose the reference to the canvas CanvasTinter.canvas = null; @@ -56,7 +60,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithMultiply = function (texture, color, canvas) { +CanvasTinter.tintWithMultiply = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -104,7 +109,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithOverlay = function (texture, color, canvas) { +CanvasTinter.tintWithOverlay = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -139,7 +145,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithPerPixel = function (texture, color, canvas) { +CanvasTinter.tintWithPerPixel = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -167,7 +174,8 @@ var pixels = pixelData.data; - for (var i = 0; i < pixels.length; i += 4) { + for (var i = 0; i < pixels.length; i += 4) + { pixels[i+0] *= r; pixels[i+1] *= g; pixels[i+2] *= b; @@ -181,7 +189,8 @@ * * @param color {number} the color to round, should be a hex color */ -CanvasTinter.roundColor = function (color) { +CanvasTinter.roundColor = function (color) +{ var step = CanvasTinter.cacheStepsPerColorChannel; var rgbValues = utils.hex2rgb(color); diff --git a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js index 9f2f89a..35edbaf 100644 --- a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js +++ b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLBlendModeManager(renderer) { +function WebGLBlendModeManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -23,8 +24,10 @@ * * @param blendMode {number} the blendMode, should be a Pixi const, such as BlendModes.ADD */ -WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) { - if (this.currentBlendMode === blendMode) { +WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) +{ + if (this.currentBlendMode === blendMode) + { return false; } diff --git a/src/core/renderers/webgl/managers/WebGLFilterManager.js b/src/core/renderers/webgl/managers/WebGLFilterManager.js index 1179258..2dac048 100644 --- a/src/core/renderers/webgl/managers/WebGLFilterManager.js +++ b/src/core/renderers/webgl/managers/WebGLFilterManager.js @@ -7,7 +7,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLFilterManager(renderer) { +function WebGLFilterManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -32,7 +33,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.texturePool.length = 0; self.initShaderBuffers(); }); @@ -46,7 +48,8 @@ * @param renderer {WebGLRenderer} * @param buffer {ArrayBuffer} */ -WebGLFilterManager.prototype.begin = function (buffer) { +WebGLFilterManager.prototype.begin = function (buffer) +{ this.defaultShader = this.renderer.shaderManager.defaultShader; this.width = this.renderer.projection.x * 2; @@ -60,7 +63,8 @@ * * @param filterBlock {object} the filter that will be pushed to the current filter stack */ -WebGLFilterManager.prototype.pushFilter = function (filterBlock) { +WebGLFilterManager.prototype.pushFilter = function (filterBlock) +{ var gl = this.renderer.gl; var projection = this.renderer.projection; @@ -78,10 +82,12 @@ this.offsetY += filterBlock._filterArea.y; var texture = this.texturePool.pop(); - if (!texture) { + if (!texture) + { texture = new FilterTexture(this.renderer.gl, this.width, this.height); } - else { + else + { texture.resize(this.width, this.height); } @@ -98,29 +104,35 @@ var localX = filterArea.x, localY = filterArea.y; - if (filterArea.x < 0) { + if (filterArea.x < 0) + { filterArea.width += filterArea.x; filterArea.x = 0; } - if (filterArea.y < 0) { + if (filterArea.y < 0) + { filterArea.height += filterArea.y; filterArea.y = 0; } - if (localX + filterArea.width > this.width) { + if (localX + filterArea.width > this.width) + { filterArea.width = this.width - localX; } - if (localY + filterArea.height > this.height) { + if (localY + filterArea.height > this.height) + { filterArea.height = this.height - localY; } - if (filterArea.width < 0) { + if (filterArea.width < 0) + { filterArea.width = 0; } - if (filterArea.height < 0) { + if (filterArea.height < 0) + { filterArea.height = 0; } @@ -154,7 +166,8 @@ * Removes the last filter from the filter stack and doesn't return it. * */ -WebGLFilterManager.prototype.popFilter = function () { +WebGLFilterManager.prototype.popFilter = function () +{ var gl = this.renderer.gl; var filterBlock = this.filterStack.pop(); @@ -163,7 +176,8 @@ var projection = this.renderer.projection; var offset = this.renderer.offset; - if (filterBlock.filterPasses.length > 1) { + if (filterBlock.filterPasses.length > 1) + { gl.viewport(0, 0, filterArea.width, filterArea.height); gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); @@ -193,7 +207,8 @@ var inputTexture = texture; var outputTexture = this.texturePool.pop(); - if (!outputTexture) { + if (!outputTexture) + { outputTexture = new FilterTexture(this.renderer.gl, this.width, this.height); } outputTexture.resize(this.width, this.height); @@ -204,7 +219,8 @@ gl.disable(gl.BLEND); - for (var i = 0; i < filterBlock.filterPasses.length-1; i++) { + for (var i = 0; i < filterBlock.filterPasses.length-1; i++) + { var filterPass = filterBlock.filterPasses[i]; gl.bindFramebuffer(gl.FRAMEBUFFER, outputTexture.frameBuffer ); @@ -243,10 +259,12 @@ var buffer = this.buffer; // time to render the filters texture to the previous scene - if (this.filterStack.length === 0) { + if (this.filterStack.length === 0) + { gl.colorMask(true, true, true, true);//this.transparent); } - else { + else + { var currentFilter = this.filterStack[this.filterStack.length-1]; filterArea = currentFilter._filterArea; @@ -332,13 +350,15 @@ * @param width {number} the horizontal range of the filter * @param height {number} the vertical range of the filter */ -WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) { +WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) +{ // use program var gl = this.renderer.gl; var shader = filter.shaders[gl.id]; - if (!shader) { + if (!shader) + { shader = new Shader(gl); shader.fragmentSrc = filter.fragmentSrc; @@ -356,7 +376,8 @@ gl.uniform2f(shader.projectionVector, width/2, -height/2); gl.uniform2f(shader.offsetVector, 0,0); - if (filter.uniforms.dimensions) { + 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]; @@ -386,7 +407,8 @@ * Initialises the shader buffers. * */ -WebGLFilterManager.prototype.initShaderBuffers = function () { +WebGLFilterManager.prototype.initShaderBuffers = function () +{ var gl = this.renderer.gl; // create some buffers @@ -432,7 +454,8 @@ * Destroys the filter and removes it from the filter stack. * */ -WebGLFilterManager.prototype.destroy = function () { +WebGLFilterManager.prototype.destroy = function () +{ var gl = this.renderer.gl; this.filterStack = null; @@ -441,7 +464,8 @@ this.offsetY = 0; // destroy textures - for (var i = 0; i < this.texturePool.length; i++) { + for (var i = 0; i < this.texturePool.length; i++) + { this.texturePool[i].destroy(); } diff --git a/src/core/renderers/webgl/managers/WebGLManager.js b/src/core/renderers/webgl/managers/WebGLManager.js index 9d47b5c..c30cd51 100644 --- a/src/core/renderers/webgl/managers/WebGLManager.js +++ b/src/core/renderers/webgl/managers/WebGLManager.js @@ -3,7 +3,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLManager(renderer) { +function WebGLManager(renderer) +{ /** * The renderer this manager works for. * @@ -15,6 +16,7 @@ WebGLManager.prototype.constructor = WebGLManager; module.exports = WebGLManager; -WebGLManager.prototype.destroy = function () { +WebGLManager.prototype.destroy = function () +{ this.renderer = null; }; diff --git a/src/core/renderers/webgl/managers/WebGLMaskManager.js b/src/core/renderers/webgl/managers/WebGLMaskManager.js index 2f90b64..e568812 100644 --- a/src/core/renderers/webgl/managers/WebGLMaskManager.js +++ b/src/core/renderers/webgl/managers/WebGLMaskManager.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLMaskManager(renderer) { +function WebGLMaskManager(renderer) +{ WebGLManager.call(this, renderer); } @@ -19,12 +20,15 @@ * * @param maskData {any[]} */ -WebGLMaskManager.prototype.pushMask = function (maskData) { - if (maskData.dirty) { +WebGLMaskManager.prototype.pushMask = function (maskData) +{ + if (maskData.dirty) + { WebGLGraphics.updateGraphics(maskData, this.renderer.gl); } - if (!maskData._webGL[this.renderer.gl.id].data.length) { + if (!maskData._webGL[this.renderer.gl.id].data.length) + { return; } @@ -36,6 +40,7 @@ * * @param maskData {any[]} */ -WebGLMaskManager.prototype.popMask = function (maskData) { +WebGLMaskManager.prototype.popMask = function (maskData) +{ this.renderer.stencilManager.popStencil(maskData, maskData._webGL[this.renderer.gl.id].data[0], this.renderer); }; diff --git a/src/core/renderers/webgl/managers/WebGLShaderManager.js b/src/core/renderers/webgl/managers/WebGLShaderManager.js index fef071c..90c6477 100644 --- a/src/core/renderers/webgl/managers/WebGLShaderManager.js +++ b/src/core/renderers/webgl/managers/WebGLShaderManager.js @@ -10,7 +10,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLShaderManager(renderer) { +function WebGLShaderManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -28,7 +29,8 @@ */ this.tempAttribState = []; - for (var i = 0; i < this.maxAttibs; i++) { + for (var i = 0; i < this.maxAttibs; i++) + { this.attribState[i] = false; } @@ -66,7 +68,8 @@ // listen for context and update necessary shaders var self = this; - this.renderer.on('context', function (event) { + this.renderer.on('context', function (event) + { var gl = event.data; // this shader is used for rendering primitives @@ -97,29 +100,36 @@ * * @param attribs {Array} attribs */ -WebGLShaderManager.prototype.setAttribs = function (attribs) { +WebGLShaderManager.prototype.setAttribs = function (attribs) +{ // reset temp state var i; - for (i = 0; i < this.tempAttribState.length; i++) { + for (i = 0; i < this.tempAttribState.length; i++) + { this.tempAttribState[i] = false; } // set the new attribs - for (var a in attribs) { + for (var a in attribs) + { this.tempAttribState[attribs[a]] = true; } var gl = this.renderer.gl; - for (i = 0; i < this.attribState.length; i++) { - if (this.attribState[i] !== this.tempAttribState[i]) { + for (i = 0; i < this.attribState.length; i++) + { + if (this.attribState[i] !== this.tempAttribState[i]) + { this.attribState[i] = this.tempAttribState[i]; - if (this.attribState[i]) { + if (this.attribState[i]) + { gl.enableVertexAttribArray(i); } - else { + else + { gl.disableVertexAttribArray(i); } } @@ -131,8 +141,10 @@ * * @param shader {Any} */ -WebGLShaderManager.prototype.setShader = function (shader) { - if (this._currentId === shader.uuid) { +WebGLShaderManager.prototype.setShader = function (shader) +{ + if (this._currentId === shader.uuid) + { return false; } @@ -150,7 +162,8 @@ * Destroys this object. * */ -WebGLShaderManager.prototype.destroy = function () { +WebGLShaderManager.prototype.destroy = function () +{ this.attribState = null; this.tempAttribState = null; diff --git a/src/core/renderers/webgl/managers/WebGLStencilManager.js b/src/core/renderers/webgl/managers/WebGLStencilManager.js index 9ec6398..4cb0134 100644 --- a/src/core/renderers/webgl/managers/WebGLStencilManager.js +++ b/src/core/renderers/webgl/managers/WebGLStencilManager.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLStencilManager(renderer) { +function WebGLStencilManager(renderer) +{ WebGLManager.call(this, renderer); this.stencilStack = []; @@ -24,12 +25,14 @@ * @param graphics {Graphics} * @param webGLData {any[]} */ -WebGLStencilManager.prototype.pushStencil = function (graphics, webGLData) { +WebGLStencilManager.prototype.pushStencil = function (graphics, webGLData) +{ var gl = this.renderer.gl; this.bindGraphics(graphics, webGLData, this.renderer); - if (this.stencilStack.length === 0) { + if (this.stencilStack.length === 0) + { gl.enable(gl.STENCIL_TEST); gl.clear(gl.STENCIL_BUFFER_BIT); this.reverse = true; @@ -47,14 +50,17 @@ // draw the triangle strip! - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } @@ -62,31 +68,38 @@ // draw a quad to increment.. gl.drawElements(gl.TRIANGLE_FAN, 4, gl.UNSIGNED_SHORT, ( webGLData.indices.length - 4 ) * 2 ); - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); } this.reverse = !this.reverse; } - else { - if (!this.reverse) { + else + { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } - else { + 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) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); } } @@ -103,7 +116,8 @@ * @param graphics {Graphics} * @param webGLData {Array} */ -WebGLStencilManager.prototype.bindGraphics = function (graphics, webGLData) { +WebGLStencilManager.prototype.bindGraphics = function (graphics, webGLData) +{ //if (this._currentGraphics === graphics)return; this._currentGraphics = graphics; @@ -114,7 +128,8 @@ offset = this.renderer.offset, shader;// = this.renderer.shaderManager.primitiveShader; - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { shader = this.renderer.shaderManager.complexPrimitiveShader; this.renderer.shaderManager.setShader(shader); @@ -141,7 +156,8 @@ // set the index buffer! gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, webGLData.indexBuffer); } - else { + else + { //this.renderer.shaderManager.activatePrimitiveShader(); shader = this.renderer.shaderManager.primitiveShader; this.renderer.shaderManager.setShader( shader ); @@ -154,7 +170,7 @@ gl.uniform2f(shader.uniforms.offsetVector._location, -offset.x, -offset.y); gl.uniform3fv(shader.uniforms.tint._location, utils.hex2rgb(graphics.tint)); - + gl.uniform1f(shader.uniforms.alpha._location, graphics.worldAlpha); @@ -172,19 +188,22 @@ * @param graphics {Graphics} * @param webGLData {Array} */ -WebGLStencilManager.prototype.popStencil = function (graphics, webGLData) { +WebGLStencilManager.prototype.popStencil = function (graphics, webGLData) +{ var gl = this.renderer.gl; this.stencilStack.pop(); this.count--; - if (this.stencilStack.length === 0) { + if (this.stencilStack.length === 0) + { // the stack is empty! gl.disable(gl.STENCIL_TEST); } - else { + else + { var level = this.count; @@ -192,14 +211,17 @@ gl.colorMask(false, false, false, false); - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { this.reverse = !this.reverse; - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } @@ -213,31 +235,38 @@ // draw the triangle strip! gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); - if (!this.reverse) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); } } - else { + else + { // console.log("<<>>") - if (!this.reverse) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } - else { + 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) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); } } @@ -253,7 +282,8 @@ * Destroys the mask stack. * */ -WebGLStencilManager.prototype.destroy = function () { +WebGLStencilManager.prototype.destroy = function () +{ this.renderer = null; this.stencilStack = null; }; diff --git a/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js b/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js index 913ba5e..1ea7d19 100644 --- a/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js +++ b/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function ComplexPrimitiveShader(gl) { +function ComplexPrimitiveShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -24,7 +25,8 @@ 'uniform float flipY;', 'varying vec4 vColor;', - 'void main(void) {', + '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);', @@ -37,7 +39,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = vColor;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/FastShader.js b/src/core/renderers/webgl/shaders/FastShader.js index bd2e29a..2e5e060 100644 --- a/src/core/renderers/webgl/shaders/FastShader.js +++ b/src/core/renderers/webgl/shaders/FastShader.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function FastShader(gl) { +function FastShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -28,7 +29,8 @@ 'const vec2 center = vec2(-1.0, 1.0);', - 'void main(void) {', + 'void main(void) + {', ' vec2 v;', ' vec2 sv = aVertexPosition * aScale;', ' v.x = (sv.x) * cos(aRotation) - (sv.y) * sin(aRotation);', @@ -49,7 +51,8 @@ 'uniform sampler2D uSampler;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/PrimitiveShader.js b/src/core/renderers/webgl/shaders/PrimitiveShader.js index 6f25409..a25f54f 100644 --- a/src/core/renderers/webgl/shaders/PrimitiveShader.js +++ b/src/core/renderers/webgl/shaders/PrimitiveShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function PrimitiveShader(gl) { +function PrimitiveShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -23,7 +24,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + '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);', @@ -36,7 +38,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = vColor;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/Shader.js b/src/core/renderers/webgl/shaders/Shader.js index f8964f5..fd75ef5 100644 --- a/src/core/renderers/webgl/shaders/Shader.js +++ b/src/core/renderers/webgl/shaders/Shader.js @@ -6,7 +6,8 @@ * @param [fragmentSrc] {string} The source of the fragment shader. * @param [vertexSrc] {string} The source of the vertex shader. */ -function Shader(gl, vertexSrc, fragmentSrc, customUniforms, customAttributes) { +function Shader(gl, vertexSrc, fragmentSrc, customUniforms, customAttributes) +{ /** * @member {number} * @readonly @@ -33,7 +34,8 @@ dimensions: { type: '4f', value: new Float32Array(4) } }; - for (var u in customUniforms) { + for (var u in customUniforms) + { this.uniforms[u] = customUniforms[u]; } @@ -43,7 +45,8 @@ aColor: 0 }; - for (var a in customAttributes) { + for (var a in customAttributes) + { this.attributes[a] = customAttributes[a]; } @@ -66,7 +69,8 @@ 'const vec2 center = vec2(-1.0, 1.0);', - 'void main(void) {', + 'void main(void) + {', ' gl_Position = vec4( ((aVertexPosition + offsetVector) / projectionVector) + center , 0.0, 1.0);', ' vTextureCoord = aTextureCoord;', ' vColor = vec4(aColor.rgb * aColor.a, aColor.a);', @@ -85,7 +89,8 @@ 'uniform sampler2D uSampler;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;', '}' ].join('\n'); @@ -96,7 +101,8 @@ Shader.prototype.constructor = Shader; module.exports = Shader; -Shader.prototype.init = function () { +Shader.prototype.init = function () +{ this.compile(); this.gl.useProgram(this.program); @@ -105,14 +111,18 @@ this.cacheAttributeLocations(Object.keys(this.attributes)); }; -Shader.prototype.cacheUniformLocations = function (keys) { - for (var i = 0; i < keys.length; ++i) { +Shader.prototype.cacheUniformLocations = function (keys) +{ + for (var i = 0; i < keys.length; ++i) + { this.uniforms[keys[i]]._location = this.gl.getUniformLocation(this.program, keys[i]); } }; -Shader.prototype.cacheAttributeLocations = function (keys) { - for (var i = 0; i < keys.length; ++i) { +Shader.prototype.cacheAttributeLocations = function (keys) +{ + for (var i = 0; i < keys.length; ++i) + { this.attributes[keys[i]] = this.gl.getAttribLocation(this.program, keys[i]); } @@ -124,14 +134,16 @@ // 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.attributes.aColor === -1) { + // if (this.attributes.aColor === -1) + { // this.attributes.aColor = 2; // } // End worst hack eva // }; -Shader.prototype.compile = function () { +Shader.prototype.compile = function () +{ var gl = this.gl; var glVertShader = this._glCompile(gl.VERTEX_SHADER, this.vertexSrc); @@ -144,13 +156,15 @@ gl.linkProgram(program); // if linking fails, then log and cleanup - if (!gl.getProgramParameter(program, gl.LINK_STATUS)) { + if (!gl.getProgramParameter(program, gl.LINK_STATUS)) + { window.console.error('Pixi.js Error: Could not initialize shader.'); window.console.error('gl.VALIDATE_STATUS', gl.getProgramParameter(program, gl.VALIDATE_STATUS)); window.console.error('gl.getError()', gl.getError()); // if there is a program info log, log it - if (gl.getProgramInfoLog(program) !== '') { + if (gl.getProgramInfoLog(program) !== '') + { window.console.warn('Pixi.js Warning: gl.getProgramInfoLog()', gl.getProgramInfoLog(program)); } @@ -165,18 +179,21 @@ return (this.program = program); }; -Shader.prototype.syncUniforms = function () { +Shader.prototype.syncUniforms = function () +{ var gl = this.gl; this.textureCount = 1; - for (var key in this.uniforms) { + for (var key in this.uniforms) + { var uniform = this.uniforms[key], location = uniform._location, value = uniform.value, i, il; - switch (uniform.type) { + switch (uniform.type) + { // single int value case 'i': case '1i': @@ -282,7 +299,8 @@ // a Color Value case 'c': - if (typeof value === 'number') { + if (typeof value === 'number') + { value = utils.hex2rgb(value); } @@ -311,11 +329,13 @@ // array of 2D Point objects case 'v2v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(2 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 2] = value[i].x; uniform._array[i * 2 + 1] = value[i].y; } @@ -325,11 +345,13 @@ // array of 3D Point objects case 'v3v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(3 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 3] = value[i].x; uniform._array[i * 3 + 1] = value[i].y; uniform._array[i * 3 + 2] = value[i].z; @@ -341,11 +363,13 @@ // array of 4D Point objects case 'v4v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(4 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 4] = value[i].x; uniform._array[i * 4 + 1] = value[i].y; uniform._array[i * 4 + 2] = value[i].z; @@ -359,7 +383,8 @@ // PIXI.Texture case 't': case 'sampler2D': - if (!uniform.value || !uniform.value.baseTexture || !uniform.value.baseTexture.hasLoaded) { + if (!uniform.value || !uniform.value.baseTexture || !uniform.value.baseTexture.hasLoaded) + { break; } @@ -376,7 +401,8 @@ this.textureCount++; // initialize the texture if we haven't yet - if (!uniform._init) { + if (!uniform._init) + { this.initSampler2D(uniform); uniform._init = true; @@ -394,11 +420,13 @@ * Initialises a Sampler2D uniform (which may only be available later on after initUniforms once the texture has loaded) * */ -Shader.prototype.initSampler2D = function (uniform) { +Shader.prototype.initSampler2D = function (uniform) +{ var gl = this.gl; // Extended texture data - if (uniform.textureData) { + if (uniform.textureData) + { var data = uniform.textureData; // GLTexture = mag linear, min linear_mipmap_linear, wrap repeat + gl.generateMipmap(gl.TEXTURE_2D); @@ -417,14 +445,16 @@ var wrapT = (data.wrapT) ? data.wrapT : gl.CLAMP_TO_EDGE; var format = (data.luminance) ? gl.LUMINANCE : gl.RGBA; - if (data.repeat) { + if (data.repeat) + { wrapS = gl.REPEAT; wrapT = gl.REPEAT; } gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, !!data.flipY); - if (data.width) { + if (data.width) + { var width = (data.width) ? data.width : 512; var height = (data.height) ? data.height : 2; var border = (data.border) ? data.border : 0; @@ -432,7 +462,8 @@ // 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 { + 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); } @@ -448,7 +479,8 @@ * Destroys the shader. * */ -Shader.prototype.destroy = function () { +Shader.prototype.destroy = function () +{ this.gl.deleteProgram(this.program); this.gl = null; @@ -459,13 +491,15 @@ this.fragmentSrc = null; }; -Shader.prototype._glCompile = function (type, src) { +Shader.prototype._glCompile = function (type, src) +{ var shader = this.gl.createShader(type); this.gl.shaderSource(shader, src); this.gl.compileShader(shader); - if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) { + if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) + { window.console.log(this.gl.getShaderInfoLog(shader)); return null; } diff --git a/src/core/renderers/webgl/shaders/StripShader.js b/src/core/renderers/webgl/shaders/StripShader.js index 193f6e1..a7abcc6 100644 --- a/src/core/renderers/webgl/shaders/StripShader.js +++ b/src/core/renderers/webgl/shaders/StripShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function StripShader(gl) { +function StripShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -20,7 +21,8 @@ 'varying vec2 vTextureCoord;', - 'void main(void) {', + '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);', @@ -36,7 +38,8 @@ 'varying vec2 vTextureCoord;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vec2(vTextureCoord.x, vTextureCoord.y)) * alpha;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/utils/FilterTexture.js b/src/core/renderers/webgl/utils/FilterTexture.js index d2c8423..4433d44 100644 --- a/src/core/renderers/webgl/utils/FilterTexture.js +++ b/src/core/renderers/webgl/utils/FilterTexture.js @@ -8,7 +8,8 @@ * @param height {number} the vertical range of the filter * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values */ -function FilterTexture(gl, width, height, scaleMode) { +function FilterTexture(gl, width, height, scaleMode) +{ /** * @member {WebGLContext} */ @@ -59,7 +60,8 @@ * Clears the filter texture. * */ -FilterTexture.prototype.clear = function () { +FilterTexture.prototype.clear = function () +{ var gl = this.gl; gl.clearColor(0,0,0, 0); @@ -72,8 +74,10 @@ * @param width {number} the new width of the texture * @param height {number} the new height of the texture */ -FilterTexture.prototype.resize = function (width, height) { - if (this.width === width && this.height === height) { +FilterTexture.prototype.resize = function (width, height) +{ + if (this.width === width && this.height === height) + { return; } @@ -96,7 +100,8 @@ * Destroys the filter texture. * */ -FilterTexture.prototype.destroy = function () { +FilterTexture.prototype.destroy = function () +{ var gl = this.gl; gl.deleteFramebuffer( this.frameBuffer ); gl.deleteTexture( this.texture ); diff --git a/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js b/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js index c4721e9..a63f4d7 100644 --- a/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js +++ b/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js @@ -14,7 +14,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this sprite batch works for. */ -function WebGLFastSpriteBatch(renderer) { +function WebGLFastSpriteBatch(renderer) +{ /** * The renderer instance this sprite batch operates on. * @@ -91,7 +92,8 @@ */ this.lastIndexCount = 0; - for (var i=0, j=0; i < numIndices; i += 6, j += 4) { + 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; @@ -144,7 +146,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.setupContext(); }); } @@ -157,7 +160,8 @@ * * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLFastSpriteBatch.prototype.setupContext = function () { +WebGLFastSpriteBatch.prototype.setupContext = function () +{ var gl = this.renderer.gl; // create a couple of buffers @@ -177,7 +181,8 @@ /** * @param spriteBatch {SpriteBatch} The SpriteBatch container to prepare for. */ -WebGLFastSpriteBatch.prototype.begin = function (spriteBatch) { +WebGLFastSpriteBatch.prototype.begin = function (spriteBatch) +{ this.shader = this.renderer.shaderManager.fastShader; this.matrix = spriteBatch.worldTransform.toArray(true); @@ -187,33 +192,38 @@ /** */ -WebGLFastSpriteBatch.prototype.end = function () { +WebGLFastSpriteBatch.prototype.end = function () +{ this.flush(); }; /** * @param spriteBatch {SpriteBatch} The SpriteBatch container to render. */ -WebGLFastSpriteBatch.prototype.render = function (spriteBatch) { +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) { + if (!sprite.texture._uvs) + { return; } this.currentBaseTexture = sprite.texture.baseTexture; // check blend mode - if (sprite.blendMode !== this.renderer.blendModeManager.currentBlendMode) { + if (sprite.blendMode !== this.renderer.blendModeManager.currentBlendMode) + { this.flush(); this.renderer.blendModeManager.setBlendMode(sprite.blendMode); } - for (var i=0,j= children.length; i= this.size) { + if (this.currentBatchSize >= this.size) + { this.flush(); } }; @@ -362,29 +379,35 @@ /** * */ -WebGLFastSpriteBatch.prototype.flush = function () { +WebGLFastSpriteBatch.prototype.flush = function () +{ // If the batch is length 0 then return as there is nothing to draw - if (this.currentBatchSize === 0) { + if (this.currentBatchSize === 0) + { return; } var gl = this.renderer.gl; // bind the current texture - if (!this.currentBaseTexture._glTextures[gl.id]) { + if (!this.currentBaseTexture._glTextures[gl.id]) + { this.renderer.updateTexture(this.currentBaseTexture, gl); } //TODO-SHOUD THIS BE ELSE??!?!?! - else { + else + { gl.bindTexture(gl.TEXTURE_2D, this.currentBaseTexture._glTextures[gl.id]); } // upload the verts to the buffer - if (this.currentBatchSize > ( this.size * 0.5 ) ) { + if (this.currentBatchSize > ( this.size * 0.5 ) ) + { gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); } - else { + else + { var view = this.vertices.subarray(0, this.currentBatchSize * this.vertByteSize); gl.bufferSubData(gl.ARRAY_BUFFER, 0, view); @@ -405,14 +428,16 @@ * Ends the batch and flushes * */ -WebGLFastSpriteBatch.prototype.stop = function () { +WebGLFastSpriteBatch.prototype.stop = function () +{ this.flush(); }; /** * */ -WebGLFastSpriteBatch.prototype.start = function () { +WebGLFastSpriteBatch.prototype.start = function () +{ var gl = this.renderer.gl; // bind the main texture diff --git a/src/core/renderers/webgl/utils/WebGLGraphics.js b/src/core/renderers/webgl/utils/WebGLGraphics.js index 55f4911..ab8f46e 100644 --- a/src/core/renderers/webgl/utils/WebGLGraphics.js +++ b/src/core/renderers/webgl/utils/WebGLGraphics.js @@ -19,7 +19,8 @@ * @param graphics {Graphics} * @param renderer {WebGLRenderer} */ -WebGLGraphics.renderGraphics = function (graphics, renderer) {//projection, offset) { +WebGLGraphics.renderGraphics = function (graphics, renderer) {//projection, offset) +{ var gl = renderer.gl; var projection = renderer.projection, @@ -27,7 +28,8 @@ shader = renderer.shaderManager.primitiveShader, webGLData; - if (graphics.dirty) { + if (graphics.dirty) + { WebGLGraphics.updateGraphics(graphics, gl); } @@ -35,8 +37,10 @@ // This could be speeded up for sure! - for (var i = 0; i < webGL.data.length; i++) { - if (webGL.data[i].mode === 1) { + for (var i = 0; i < webGL.data.length; i++) + { + if (webGL.data[i].mode === 1) + { webGLData = webGL.data[i]; renderer.stencilManager.pushStencil(graphics, webGLData, renderer); @@ -46,7 +50,8 @@ renderer.stencilManager.popStencil(graphics, webGLData, renderer); } - else { + else + { webGLData = webGL.data[i]; @@ -84,12 +89,14 @@ * @param graphicsData {Graphics} The graphics object to update * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLGraphics.updateGraphics = function (graphics, gl) { +WebGLGraphics.updateGraphics = function (graphics, gl) +{ // get the contexts graphics object var webGL = graphics._webGL[gl.id]; // if the graphics object does not exist in the webGL context time to create it! - if (!webGL) { + if (!webGL) + { webGL = graphics._webGL[gl.id] = {lastIndex:0, data:[], gl:gl}; } @@ -99,11 +106,13 @@ var i; // if the user cleared the graphics object we will need to clear every object - if (graphics.clearDirty) { + if (graphics.clearDirty) + { graphics.clearDirty = false; // lop through and return all the webGLDatas to the object pool so than can be reused later on - for (i = 0; i < webGL.data.length; i++) { + for (i = 0; i < webGL.data.length; i++) + { var graphicsData = webGL.data[i]; graphicsData.reset(); WebGLGraphics.graphicsDataPool.push( graphicsData ); @@ -119,58 +128,72 @@ // loop through the graphics datas and construct each one.. // if the object is a complex fill then the new stencil buffer technique will be used // other wise graphics objects will be pushed into a batch.. - for (i = webGL.lastIndex; i < graphics.graphicsData.length; i++) { + for (i = webGL.lastIndex; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { // need to add the points the the graphics object.. data.points = data.shape.points.slice(); - if (data.shape.closed) { + if (data.shape.closed) + { // close the poly if the value is true! - if (data.points[0] !== data.points[data.points.length-2] || data.points[1] !== data.points[data.points.length-1]) { + if (data.points[0] !== data.points[data.points.length-2] || data.points[1] !== data.points[data.points.length-1]) + { data.points.push(data.points[0], data.points[1]); } } // MAKE SURE WE HAVE THE CORRECT TYPE.. - if (data.fill) { - if (data.points.length >= 6) { - if (data.points.length < 6 * 2) { + if (data.fill) + { + if (data.points.length >= 6) + { + if (data.points.length < 6 * 2) + { webGLData = WebGLGraphics.switchMode(webGL, 0); var canDrawUsingSimple = WebGLGraphics.buildPoly(data, webGLData); // console.log(canDrawUsingSimple); - if (!canDrawUsingSimple) { + if (!canDrawUsingSimple) + { // console.log("<>>>") webGLData = WebGLGraphics.switchMode(webGL, 1); WebGLGraphics.buildComplexPoly(data, webGLData); } } - else { + else + { webGLData = WebGLGraphics.switchMode(webGL, 1); WebGLGraphics.buildComplexPoly(data, webGLData); } } } - if (data.lineWidth > 0) { + if (data.lineWidth > 0) + { webGLData = WebGLGraphics.switchMode(webGL, 0); WebGLGraphics.buildLine(data, webGLData); } } - else { + else + { webGLData = WebGLGraphics.switchMode(webGL, 0); - if (data.type === CONST.SHAPES.RECT) { + if (data.type === CONST.SHAPES.RECT) + { WebGLGraphics.buildRectangle(data, webGLData); } - else if (data.type === CONST.SHAPES.CIRC || data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.CIRC || data.type === CONST.SHAPES.ELIP) + { WebGLGraphics.buildCircle(data, webGLData); } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { WebGLGraphics.buildRoundedRectangle(data, webGLData); } } @@ -179,10 +202,12 @@ } // upload all the dirty data... - for (i = 0; i < webGL.data.length; i++) { + for (i = 0; i < webGL.data.length; i++) + { webGLData = webGL.data[i]; - if (webGLData.dirty) { + if (webGLData.dirty) + { webGLData.upload(); } } @@ -194,18 +219,22 @@ * @param webGL {WebGLContext} * @param type {number} */ -WebGLGraphics.switchMode = function (webGL, type) { +WebGLGraphics.switchMode = function (webGL, type) +{ var webGLData; - if (!webGL.data.length) { + if (!webGL.data.length) + { webGLData = WebGLGraphics.graphicsDataPool.pop() || new WebGLGraphicsData(webGL.gl); webGLData.mode = type; webGL.data.push(webGLData); } - else { + else + { webGLData = webGL.data[webGL.data.length-1]; - if (webGLData.mode !== type || type === 1) { + if (webGLData.mode !== type || type === 1) + { webGLData = WebGLGraphics.graphicsDataPool.pop() || new WebGLGraphicsData(webGL.gl); webGLData.mode = type; webGL.data.push(webGLData); @@ -225,7 +254,8 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildRectangle = function (graphicsData, webGLData) { +WebGLGraphics.buildRectangle = function (graphicsData, webGLData) +{ // --- // // need to convert points to a nice regular data // @@ -235,7 +265,8 @@ var width = rectData.width; var height = rectData.height; - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -265,7 +296,8 @@ indices.push(vertPos, vertPos, vertPos+1, vertPos+2, vertPos+3, vertPos+3); } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = [x, y, @@ -289,7 +321,8 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildRoundedRectangle = function (graphicsData, webGLData) { +WebGLGraphics.buildRoundedRectangle = function (graphicsData, webGLData) +{ var rrectData = graphicsData.shape; var x = rrectData.x; var y = rrectData.y; @@ -305,7 +338,8 @@ recPoints = recPoints.concat(WebGLGraphics.quadraticBezierCurve(x + width, y + radius, x + width, y, x + width - radius, y)); recPoints = recPoints.concat(WebGLGraphics.quadraticBezierCurve(x + radius, y, x, y, x, y + radius)); - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -323,7 +357,8 @@ // var i = 0; - for (i = 0; i < triangles.length; i+=3) { + for (i = 0; i < triangles.length; i+=3) + { indices.push(triangles[i] + vecPos); indices.push(triangles[i] + vecPos); indices.push(triangles[i+1] + vecPos); @@ -332,12 +367,14 @@ } - for (i = 0; i < recPoints.length; i++) { + for (i = 0; i < recPoints.length; i++) + { verts.push(recPoints[i], recPoints[++i], r, g, b, alpha); } } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = recPoints; @@ -362,7 +399,8 @@ * @param toY {number} Destination point y * @return {number[]} */ -WebGLGraphics.quadraticBezierCurve = function (fromX, fromY, cpX, cpY, toX, toY) { +WebGLGraphics.quadraticBezierCurve = function (fromX, fromY, cpX, cpY, toX, toY) +{ var xa, ya, @@ -373,14 +411,16 @@ n = 20, points = []; - function getPt(n1 , n2, perc) { + function getPt(n1 , n2, perc) + { var diff = n2 - n1; return n1 + ( diff * perc ); } var j = 0; - for (var i = 0; i <= n; i++ ) { + for (var i = 0; i <= n; i++ ) + { j = i / n; // The Green Line @@ -406,7 +446,8 @@ * @param graphicsData {Graphics} The graphics object to draw * @param webGLData {object} */ -WebGLGraphics.buildCircle = function (graphicsData, webGLData) { +WebGLGraphics.buildCircle = function (graphicsData, webGLData) +{ // need to convert points to a nice regular data var circleData = graphicsData.shape; var x = circleData.x; @@ -415,11 +456,13 @@ var height; // TODO - bit hacky?? - if (graphicsData.type === CONST.SHAPES.CIRC) { + if (graphicsData.type === CONST.SHAPES.CIRC) + { width = circleData.radius; height = circleData.radius; } - else { + else + { width = circleData.width; height = circleData.height; } @@ -429,7 +472,8 @@ var i = 0; - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -444,7 +488,8 @@ indices.push(vecPos); - for (i = 0; i < totalSegs + 1 ; i++) { + for (i = 0; i < totalSegs + 1 ; i++) + { verts.push(x,y, r, g, b, alpha); verts.push(x + Math.sin(seg * i) * width, @@ -457,12 +502,14 @@ indices.push(vecPos-1); } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = []; - for (i = 0; i < totalSegs + 1; i++) { + for (i = 0; i < totalSegs + 1; i++) + { graphicsData.points.push(x + Math.sin(seg * i) * width, y + Math.cos(seg * i) * height); } @@ -481,18 +528,22 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildLine = function (graphicsData, webGLData) { +WebGLGraphics.buildLine = function (graphicsData, webGLData) +{ // TODO OPTIMISE! var i = 0; var points = graphicsData.points; - if (points.length === 0) { + if (points.length === 0) + { return; } // if the line width is an odd number add 0.5 to align to a whole pixel - if (graphicsData.lineWidth%2) { - for (i = 0; i < points.length; i++) { + if (graphicsData.lineWidth%2) + { + for (i = 0; i < points.length; i++) + { points[i] += 0.5; } } @@ -502,7 +553,8 @@ var lastPoint = new math.Point(points[points.length - 2], points[points.length - 1]); // if the first point is the last point - gonna have issues :) - if (firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) { + if (firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) + { // need to clone as we are going to slightly modify the shape.. points = points.slice(); @@ -562,7 +614,8 @@ verts.push(p1x + perpx , p1y + perpy, r, g, b, alpha); - for (i = 1; i < length-1; i++) { + for (i = 1; i < length-1; i++) + { p1x = points[(i-1)*2]; p1y = points[(i-1)*2 + 1]; @@ -599,7 +652,8 @@ denom = a1*b2 - a2*b1; - if (Math.abs(denom) < 0.1 ) { + if (Math.abs(denom) < 0.1 ) + { denom+=10.1; verts.push(p2x - perpx , p2y - perpy, @@ -618,7 +672,8 @@ pdist = (px -p2x) * (px -p2x) + (py -p2y) + (py -p2y); - if (pdist > 140 * 140) { + if (pdist > 140 * 140) + { perp3x = perpx - perp2x; perp3y = perpy - perp2y; @@ -639,7 +694,8 @@ indexCount++; } - else { + else + { verts.push(px , py); verts.push(r, g, b, alpha); @@ -672,7 +728,8 @@ indices.push(indexStart); - for (i = 0; i < indexCount; i++) { + for (i = 0; i < indexCount; i++) + { indices.push(indexStart++); } @@ -687,11 +744,13 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildComplexPoly = function (graphicsData, webGLData) { +WebGLGraphics.buildComplexPoly = function (graphicsData, webGLData) +{ //TODO - no need to copy this as it gets turned into a FLoat32Array anyways.. var points = graphicsData.points.slice(); - if (points.length < 6) { + if (points.length < 6) + { return; } @@ -711,7 +770,8 @@ var x,y; // get size.. - for (var i = 0; i < points.length; i+=2) { + for (var i = 0; i < points.length; i+=2) + { x = points[i]; y = points[i+1]; @@ -732,7 +792,8 @@ //TODO - this aint needed! var length = points.length / 2; - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { indices.push( i ); } @@ -746,10 +807,12 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildPoly = function (graphicsData, webGLData) { +WebGLGraphics.buildPoly = function (graphicsData, webGLData) +{ var points = graphicsData.points; - if (points.length < 6) { + if (points.length < 6) + { return; } // get first and last point.. figure out the middle! @@ -767,7 +830,8 @@ var triangles = utils.PolyK.Triangulate(points); - if (!triangles) { + if (!triangles) + { return false; } @@ -775,7 +839,8 @@ var i = 0; - for (i = 0; i < triangles.length; i+=3) { + for (i = 0; i < triangles.length; i+=3) + { indices.push(triangles[i] + vertPos); indices.push(triangles[i] + vertPos); indices.push(triangles[i+1] + vertPos); @@ -783,7 +848,8 @@ indices.push(triangles[i+2] + vertPos); } - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { verts.push(points[i * 2], points[i * 2 + 1], r, g, b, alpha); } diff --git a/src/core/renderers/webgl/utils/WebGLGraphicsData.js b/src/core/renderers/webgl/utils/WebGLGraphicsData.js index c56d05e..c739ba7 100644 --- a/src/core/renderers/webgl/utils/WebGLGraphicsData.js +++ b/src/core/renderers/webgl/utils/WebGLGraphicsData.js @@ -2,7 +2,8 @@ * @class * @private */ -function WebGLGraphicsData(gl) { +function WebGLGraphicsData(gl) +{ this.gl = gl; //TODO does this need to be split before uploding?? @@ -22,7 +23,8 @@ /** * */ -WebGLGraphicsData.prototype.reset = function () { +WebGLGraphicsData.prototype.reset = function () +{ this.points.length = 0; this.indices.length = 0; }; @@ -30,7 +32,8 @@ /** * */ -WebGLGraphicsData.prototype.upload = function () { +WebGLGraphicsData.prototype.upload = function () +{ var gl = this.gl; // this.lastIndex = graphics.graphicsData.length; diff --git a/src/core/renderers/webgl/utils/WebGLSpriteBatch.js b/src/core/renderers/webgl/utils/WebGLSpriteBatch.js index 96eaa52..55befbb 100644 --- a/src/core/renderers/webgl/utils/WebGLSpriteBatch.js +++ b/src/core/renderers/webgl/utils/WebGLSpriteBatch.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this sprite batch works for. */ -function WebGLSpriteBatch(renderer) { +function WebGLSpriteBatch(renderer) +{ /** * * @@ -88,7 +89,8 @@ */ this.lastIndexCount = 0; - for (var i=0, j=0; i < numIndices; i += 6, j += 4) { + 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; @@ -162,7 +164,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.setupContext(); }); } @@ -173,7 +176,8 @@ /** * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLSpriteBatch.prototype.setupContext = function () { +WebGLSpriteBatch.prototype.setupContext = function () +{ var gl = this.renderer.gl; // setup default shader @@ -198,7 +202,8 @@ /** * */ -WebGLSpriteBatch.prototype.begin = function () { +WebGLSpriteBatch.prototype.begin = function () +{ // this.shader = this.renderer.shaderManager.defaultShader; this.start(); @@ -206,19 +211,22 @@ /** */ -WebGLSpriteBatch.prototype.end = function () { +WebGLSpriteBatch.prototype.end = function () +{ this.flush(); }; /** * @param sprite {Sprite} the sprite to render when using this spritebatch */ -WebGLSpriteBatch.prototype.render = function (sprite) { +WebGLSpriteBatch.prototype.render = function (sprite) +{ var texture = sprite.texture; //TODO set blend modes.. // check texture.. - if (this.currentBatchSize >= this.size) { + if (this.currentBatchSize >= this.size) + { this.flush(); this.currentBaseTexture = texture.baseTexture; } @@ -227,7 +235,8 @@ var uvs = texture._uvs; // if the uvs have not updated then no point rendering just yet! - if (!uvs) { + if (!uvs) + { return; } @@ -237,7 +246,8 @@ var w0, w1, h0, h1; - if (texture.trim) { + 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; @@ -248,7 +258,8 @@ h0 = h1 + texture.crop.height; } - else { + else + { w0 = (texture.frame.width ) * (1-aX); w1 = (texture.frame.width ) * -aX; @@ -272,7 +283,8 @@ var colors = this.colors; var positions = this.positions; - if (this.renderer.roundPixels) { + if (this.renderer.roundPixels) + { // xy positions[index] = a * w1 + c * h1 + tx | 0; positions[index+1] = d * h1 + b * w1 + ty | 0; @@ -289,7 +301,8 @@ positions[index+15] = a * w1 + c * h0 + tx | 0; positions[index+16] = d * h0 + b * w1 + ty | 0; } - else { + else + { // xy positions[index] = a * w1 + c * h1 + tx; positions[index+1] = d * h1 + b * w1 + ty; @@ -338,11 +351,13 @@ * * @param sprite {TilingSprite} the tilingSprite to render */ -WebGLSpriteBatch.prototype.renderTilingSprite = function (tilingSprite) { +WebGLSpriteBatch.prototype.renderTilingSprite = function (tilingSprite) +{ var texture = tilingSprite.tilingTexture; // check texture.. - if (this.currentBatchSize >= this.size) { + if (this.currentBatchSize >= this.size) + { //return; this.flush(); this.currentBaseTexture = texture.baseTexture; @@ -351,7 +366,8 @@ // set the textures uvs temporarily // TODO create a separate texture so that we can tile part of a texture - if (!tilingSprite._uvs) { + if (!tilingSprite._uvs) + { tilingSprite._uvs = new TextureUvs(); } @@ -454,16 +470,19 @@ * Renders the content and empties the current batch. * */ -WebGLSpriteBatch.prototype.flush = function () { +WebGLSpriteBatch.prototype.flush = function () +{ // If the batch is length 0 then return as there is nothing to draw - if (this.currentBatchSize === 0) { + if (this.currentBatchSize === 0) + { return; } var gl = this.renderer.gl; var shader; - if (this.dirty) { + if (this.dirty) + { this.dirty = false; // bind the main texture gl.activeTexture(gl.TEXTURE0); @@ -482,10 +501,12 @@ } // upload the verts to the buffer - if (this.currentBatchSize > ( this.size * 0.5 ) ) { + if (this.currentBatchSize > ( this.size * 0.5 ) ) + { gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); } - else { + else + { var view = this.positions.subarray(0, this.currentBatchSize * this.vertByteSize); gl.bufferSubData(gl.ARRAY_BUFFER, 0, view); } @@ -502,7 +523,8 @@ var shaderSwap = false; var sprite; - for (var i = 0, j = this.currentBatchSize; i < j; i++) { + for (var i = 0, j = this.currentBatchSize; i < j; i++) + { sprite = this.sprites[i]; @@ -513,24 +535,28 @@ blendSwap = currentBlendMode !== nextBlendMode; shaderSwap = currentShader !== nextShader; // should I use uuidS??? - if (currentBaseTexture !== nextTexture || blendSwap || shaderSwap) { + if (currentBaseTexture !== nextTexture || blendSwap || shaderSwap) + { this.renderBatch(currentBaseTexture, batchSize, start); start = i; batchSize = 0; currentBaseTexture = nextTexture; - if (blendSwap) { + if (blendSwap) + { currentBlendMode = nextBlendMode; this.renderer.blendModeManager.setBlendMode( currentBlendMode ); } - if (shaderSwap) { + if (shaderSwap) + { currentShader = nextShader; shader = currentShader.shaders ? currentShader.shaders[gl.id] : currentShader; - if (!shader) { + if (!shader) + { shader = new Shader(gl, null, currentShader.fragmentSrc, currentShader.uniforms); currentShader.shaders[gl.id] = shader; } @@ -538,7 +564,8 @@ // set shader function??? this.renderer.shaderManager.setShader(shader); - if (shader.dirty) { + if (shader.dirty) + { shader.syncUniforms(); } @@ -569,17 +596,21 @@ * @param size {number} * @param startIndex {number} */ -WebGLSpriteBatch.prototype.renderBatch = function (texture, size, startIndex) { - if (size === 0) { +WebGLSpriteBatch.prototype.renderBatch = function (texture, size, startIndex) +{ + if (size === 0) + { return; } var gl = this.renderer.gl; - if (!texture._glTextures[gl.id]) { + if (!texture._glTextures[gl.id]) + { this.renderer.updateTexture(texture); } - else { + else + { // bind the current texture gl.bindTexture(gl.TEXTURE_2D, texture._glTextures[gl.id]); } @@ -594,7 +625,8 @@ /** * */ -WebGLSpriteBatch.prototype.stop = function () { +WebGLSpriteBatch.prototype.stop = function () +{ this.flush(); this.dirty = true; }; @@ -602,7 +634,8 @@ /** * */ -WebGLSpriteBatch.prototype.start = function () { +WebGLSpriteBatch.prototype.start = function () +{ this.dirty = true; }; @@ -610,7 +643,8 @@ * Destroys the SpriteBatch. * */ -WebGLSpriteBatch.prototype.destroy = function () { +WebGLSpriteBatch.prototype.destroy = function () +{ this.renderer.gl.deleteBuffer(this.vertexBuffer); this.renderer.gl.deleteBuffer(this.indexBuffer); diff --git a/src/core/textures/BaseTexture.js b/src/core/textures/BaseTexture.js index 2bf77d4..513d358 100644 --- a/src/core/textures/BaseTexture.js +++ b/src/core/textures/BaseTexture.js @@ -10,7 +10,8 @@ * @param source {Image|Canvas} the source object of the texture. * @param [scaleMode=scaleModes.DEFAULT] {number} See {@link scaleModes} for possible values */ -function BaseTexture(source, scaleMode) { +function BaseTexture(source, scaleMode) +{ this.uuid = utils.uuid(); /** @@ -123,7 +124,8 @@ this._needsUpdate = false; // if no source passed don't try to load - if (source) { + if (source) + { this.loadSource(source); } @@ -149,13 +151,16 @@ Object.defineProperties(BaseTexture.prototype, { needsUpdate: { - get: function () { + get: function () + { return this._needsUpdate; }, - set: function (val) { + set: function (val) + { this._needsUpdate = val; - if (val) { + if (val) + { this.emit('update', this); } } @@ -171,9 +176,11 @@ * * The logic state after calling `loadSource` directly or indirectly (eg. `fromImage`, `new BaseTexture`) is: * - * if (texture.hasLoaded) { + * if (texture.hasLoaded) + { * // texture ready for use - * } else if (texture.isLoading) { + * } else if (texture.isLoading) + { * // listen to 'loaded' and/or 'error' events on texture * } else { * // not loading, not going to load UNLESS the source is reloaded @@ -183,12 +190,14 @@ * @protected * @param source {Image|Canvas} the source object of the texture. */ -BaseTexture.prototype.loadSource = function (source) { +BaseTexture.prototype.loadSource = function (source) +{ var wasLoading = this.isLoading; this.hasLoaded = false; this.isLoading = false; - if (wasLoading && this.source) { + if (wasLoading && this.source) + { this.source.onload = null; this.source.onerror = null; } @@ -196,20 +205,24 @@ this.source = source; // Apply source if loaded. Otherwise setup appropriate loading monitors. - if ((this.source.complete || this.source.getContext) && this.source.width && this.source.height) { + if ((this.source.complete || this.source.getContext) && this.source.width && this.source.height) + { this._sourceLoaded(); } - else if(!source.getContext) { + else if(!source.getContext) + { // Image fail / not ready this.isLoading = true; var scope = this; - source.onload = function () { + source.onload = function () + { source.onload = null; source.onerror = null; - if(!scope.isLoading) { + if(!scope.isLoading) + { return; } @@ -219,11 +232,13 @@ scope.emit('loaded', scope); }; - source.onerror = function () { + source.onerror = function () + { source.onload = null; source.onerror = null; - if(!scope.isLoading) { + if(!scope.isLoading) + { return; } @@ -234,24 +249,29 @@ // Per http://www.w3.org/TR/html5/embedded-content-0.html#the-img-element // "The value of `complete` can thus change while a script is executing." // So complete needs to be re-checked after the callbacks have been added.. - if (source.complete) { + if (source.complete) + { this.isLoading = false; // ..and if we're complete now, no need for callbacks source.onload = null; source.onerror = null; - if (source.width && source.height) { + if (source.width && source.height) + { this._sourceLoaded(); // If any previous subscribers possible - if (wasLoading) { + if (wasLoading) + { this.emit('loaded', this); } } - else { + else + { // If any previous subscribers possible - if (wasLoading) { + if (wasLoading) + { this.emit('error', this); } } @@ -265,7 +285,8 @@ * * @private */ -BaseTexture.prototype._sourceLoaded = function () { +BaseTexture.prototype._sourceLoaded = function () +{ this.hasLoaded = true; this.width = this.source.naturalWidth || this.source.width; @@ -278,16 +299,20 @@ * Destroys this base texture * */ -BaseTexture.prototype.destroy = function () { - if (this.imageUrl) { +BaseTexture.prototype.destroy = function () +{ + if (this.imageUrl) + { delete utils.BaseTextureCache[this.imageUrl]; delete utils.TextureCache[this.imageUrl]; this.imageUrl = null; - if (!navigator.isCocoonJS) { + if (!navigator.isCocoonJS) + { this.source.src = ''; } } - else if (this.source && this.source._pixiId) { + else if (this.source && this.source._pixiId) + { delete utils.BaseTextureCache[this.source._pixiId]; } this.source = null; @@ -301,7 +326,8 @@ * memory again. * */ -BaseTexture.prototype.dispose = function () { +BaseTexture.prototype.dispose = function () +{ this.emit('dispose', this); }; @@ -311,7 +337,8 @@ * * @param newSrc {string} the path of the image */ -BaseTexture.prototype.updateSourceImage = function (newSrc) { +BaseTexture.prototype.updateSourceImage = function (newSrc) +{ this.source.src = newSrc; this.loadSource(this.source); }; @@ -326,18 +353,22 @@ * @param [scaleMode=scaleModes.DEFAULT] {number} See {@link scaleModes} for possible values * @return BaseTexture */ -BaseTexture.fromImage = function (imageUrl, crossorigin, scaleMode) { +BaseTexture.fromImage = function (imageUrl, crossorigin, scaleMode) +{ var baseTexture = utils.BaseTextureCache[imageUrl]; - if (crossorigin === undefined && imageUrl.indexOf('data:') !== 0) { + if (crossorigin === undefined && imageUrl.indexOf('data:') !== 0) + { crossorigin = true; } - if (!baseTexture) { + if (!baseTexture) + { // new Image() breaks tex loading in some versions of Chrome. // See https://code.google.com/p/chromium/issues/detail?id=238071 var image = new Image();//document.createElement('img'); - if (crossorigin) { + if (crossorigin) + { image.crossOrigin = ''; } @@ -347,7 +378,8 @@ utils.BaseTextureCache[imageUrl] = baseTexture; // if there is an @2x at the end of the url we are going to assume its a highres image - if ( imageUrl.indexOf(CONST.RETINA_PREFIX + '.') !== -1) { + if ( imageUrl.indexOf(CONST.RETINA_PREFIX + '.') !== -1) + { baseTexture.resolution = 2; } } @@ -363,14 +395,17 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return BaseTexture */ -BaseTexture.fromCanvas = function (canvas, scaleMode) { - if (!canvas._pixiId) { +BaseTexture.fromCanvas = function (canvas, scaleMode) +{ + if (!canvas._pixiId) + { canvas._pixiId = 'canvas_' + utils.uuid(); } var baseTexture = utils.BaseTextureCache[canvas._pixiId]; - if (!baseTexture) { + if (!baseTexture) + { baseTexture = new BaseTexture(canvas, scaleMode); utils.BaseTextureCache[canvas._pixiId] = baseTexture; } diff --git a/src/core/textures/RenderTexture.js b/src/core/textures/RenderTexture.js index 6dad20f..53ae796 100644 --- a/src/core/textures/RenderTexture.js +++ b/src/core/textures/RenderTexture.js @@ -46,8 +46,10 @@ * @param [scaleMode] {number} See {@link scaleModes} for possible values * @param [resolution=1] {number} The resolution of the texture being generated */ -function RenderTexture(renderer, width, height, scaleMode, resolution) { - if (!renderer) { +function RenderTexture(renderer, width, height, scaleMode, resolution) +{ + if (!renderer) + { throw new Error('Unable to create RenderTexture, you must pass a renderer into the constructor.'); } @@ -133,7 +135,8 @@ */ this.renderer = renderer; - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { var gl = this.renderer.gl; this.textureBuffer = new FilterTexture(gl, this.width * this.resolution, this.height * this.resolution, this.baseTexture.scaleMode); @@ -142,7 +145,8 @@ this.render = this.renderWebGL; this.projection = new math.Point(this.width*0.5, -this.height*0.5); } - else { + else + { this.render = this.renderCanvas; this.textureBuffer = new CanvasBuffer(this.width* this.resolution, this.height* this.resolution); this.baseTexture.source = this.textureBuffer.canvas; @@ -167,8 +171,10 @@ * @param height {number} The height to resize to. * @param updateBase {boolean} Should the baseTexture.width and height values be resized as well? */ -RenderTexture.prototype.resize = function (width, height, updateBase) { - if (width === this.width && height === this.height) { +RenderTexture.prototype.resize = function (width, height, updateBase) +{ + if (width === this.width && height === this.height) + { return; } @@ -177,17 +183,20 @@ this.width = this.frame.width = this.crop.width = width; this.height = this.frame.height = this.crop.height = height; - if (updateBase) { + if (updateBase) + { this.baseTexture.width = this.width; this.baseTexture.height = this.height; } - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { this.projection.x = this.width / 2; this.projection.y = -this.height / 2; } - if (!this.valid) { + if (!this.valid) + { return; } @@ -198,12 +207,15 @@ * Clears the RenderTexture. * */ -RenderTexture.prototype.clear = function () { - if (!this.valid) { +RenderTexture.prototype.clear = function () +{ + if (!this.valid) + { return; } - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { this.renderer.gl.bindFramebuffer(this.renderer.gl.FRAMEBUFFER, this.textureBuffer.frameBuffer); } @@ -220,19 +232,23 @@ * @param [restoreWorldTransform=true] {boolean} If true the displayObject's worldTransform/worldAlpha and all children * transformations will be restored. Not restoring this information will be a little faster. */ -RenderTexture.prototype.renderWebGL = function (displayObject, matrix, clear, restoreWorldTransform) { - if (!this.valid) { +RenderTexture.prototype.renderWebGL = function (displayObject, matrix, clear, restoreWorldTransform) +{ + if (!this.valid) + { return; } - if (typeof restoreWorldTransform === 'undefined') { + if (typeof restoreWorldTransform === 'undefined') + { restoreWorldTransform = true; } var tempAlpha, tempTransform; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { tempAlpha = displayObject.worldAlpha; tempTransform = displayObject.worldTransform.toArray(); } @@ -245,7 +261,8 @@ wt.identity(); wt.translate(0, this.projection.y * 2); - if (matrix) { + if (matrix) + { wt.append(matrix); } @@ -258,7 +275,8 @@ var children = displayObject.children; var i, j; - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } @@ -269,7 +287,8 @@ gl.bindFramebuffer(gl.FRAMEBUFFER, this.textureBuffer.frameBuffer ); - if (clear) { + if (clear) + { this.textureBuffer.clear(); } @@ -279,11 +298,13 @@ this.renderer.spriteBatch.dirty = true; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { displayObject.worldAlpha = tempAlpha; displayObject.worldTransform.fromArray(tempTransform); - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } } @@ -300,26 +321,31 @@ * @param [restoreWorldTransform=true] {boolean} If true the displayObject's worldTransform/worldAlpha and all children * transformations will be restored. Not restoring this information will be a little faster. */ -RenderTexture.prototype.renderCanvas = function (displayObject, matrix, clear, restoreWorldTransform) { - if (!this.valid) { +RenderTexture.prototype.renderCanvas = function (displayObject, matrix, clear, restoreWorldTransform) +{ + if (!this.valid) + { return; } - if (typeof restoreWorldTransform === 'undefined') { + if (typeof restoreWorldTransform === 'undefined') + { restoreWorldTransform = true; } var tempAlpha, tempTransform; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { tempAlpha = displayObject.worldAlpha; tempTransform = displayObject.worldTransform.toArray(); } var wt = displayObject.worldTransform; wt.identity(); - if (matrix) { + if (matrix) + { wt.append(matrix); } @@ -330,11 +356,13 @@ var children = displayObject.children; var i, j; - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } - if (clear) { + if (clear) + { this.textureBuffer.clear(); } @@ -348,11 +376,13 @@ this.renderer.resolution = realResolution; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { displayObject.worldAlpha = tempAlpha; displayObject.worldTransform.fromArray(tempTransform); - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } } @@ -363,7 +393,8 @@ * * @return {Image} */ -RenderTexture.prototype.getImage = function () { +RenderTexture.prototype.getImage = function () +{ var image = new Image(); image.src = this.getBase64(); return image; @@ -374,7 +405,8 @@ * * @return {string} A base64 encoded string of the texture. */ -RenderTexture.prototype.getBase64 = function () { +RenderTexture.prototype.getBase64 = function () +{ return this.getCanvas().toDataURL(); }; @@ -383,8 +415,10 @@ * * @return {HTMLCanvasElement} A Canvas element with the texture rendered on. */ -RenderTexture.prototype.getCanvas = function () { - if (this.renderer.type === CONST.WEBGL_RENDERER) { +RenderTexture.prototype.getCanvas = function () +{ + if (this.renderer.type === CONST.WEBGL_RENDERER) + { var gl = this.renderer.gl; var width = this.textureBuffer.width; var height = this.textureBuffer.height; @@ -403,7 +437,8 @@ return tempCanvas.canvas; } - else { + else + { return this.textureBuffer.canvas; } }; diff --git a/src/core/textures/Texture.js b/src/core/textures/Texture.js index 3c65909..e97f0aa 100644 --- a/src/core/textures/Texture.js +++ b/src/core/textures/Texture.js @@ -17,7 +17,8 @@ * @param [crop] {Rectangle} The area of original texture * @param [trim] {Rectangle} Trimmed texture rectangle */ -function Texture(baseTexture, frame, crop, trim) { +function Texture(baseTexture, frame, crop, trim) +{ /** * Does this Texture have any frame data assigned to it? * @@ -25,12 +26,14 @@ */ this.noFrame = false; - if (!frame) { + if (!frame) + { this.noFrame = true; frame = new math.Rectangle(0, 0, 1, 1); } - if (baseTexture instanceof Texture) { + if (baseTexture instanceof Texture) + { baseTexture = baseTexture.baseTexture; } @@ -100,13 +103,16 @@ */ this.crop = crop || new math.Rectangle(0, 0, 1, 1); - if (baseTexture.hasLoaded) { - if (this.noFrame) { + if (baseTexture.hasLoaded) + { + if (this.noFrame) + { frame = new math.Rectangle(0, 0, baseTexture.width, baseTexture.height); } this.frame = frame; } - else { + else + { baseTexture.addEventListener('loaded', this.onBaseTextureLoaded.bind(this)); } } @@ -118,19 +124,23 @@ Object.defineProperties(Texture.prototype, { needsUpdate: { - get: function () { + get: function () + { return this.baseTexture.needsUpdate; }, - set: function (val) { + set: function (val) + { this.baseTexture.needsUpdate = val; } }, frame: { - get: function () { + get: function () + { return this._frame; }, - set: function (frame) { + set: function (frame) + { this._frame = frame; this.noFrame = false; @@ -143,20 +153,23 @@ 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 (!this.trim && (frame.x + frame.width > this.baseTexture.width || frame.y + frame.height > this.baseTexture.height)) + { throw new Error('Texture Error: frame does not fit inside the base Texture dimensions ' + this); } this.valid = frame && frame.width && frame.height && this.baseTexture.source && this.baseTexture.hasLoaded; - if (this.trim) { + 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) { + if (this.valid) + { this._updateUvs(); } } @@ -168,11 +181,13 @@ * * @private */ -Texture.prototype.onBaseTextureLoaded = function () { +Texture.prototype.onBaseTextureLoaded = function () +{ var baseTexture = this.baseTexture; baseTexture.removeEventListener('loaded', this.onLoaded); - if (this.noFrame) { + if (this.noFrame) + { this.frame = new math.Rectangle(0, 0, baseTexture.width, baseTexture.height); } @@ -184,8 +199,10 @@ * * @param destroyBase {boolean} Whether to destroy the base texture as well */ -Texture.prototype.destroy = function (destroyBase) { - if (destroyBase) { +Texture.prototype.destroy = function (destroyBase) +{ + if (destroyBase) + { this.baseTexture.destroy(); } @@ -197,8 +214,10 @@ * * @private */ -Texture.prototype._updateUvs = function () { - if (!this._uvs) { +Texture.prototype._updateUvs = function () +{ + if (!this._uvs) + { this._uvs = new TextureUvs(); } @@ -229,10 +248,12 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return Texture */ -Texture.fromImage = function (imageUrl, crossorigin, scaleMode) { +Texture.fromImage = function (imageUrl, crossorigin, scaleMode) +{ var texture = utils.TextureCache[imageUrl]; - if (!texture) { + if (!texture) + { texture = new Texture(BaseTexture.fromImage(imageUrl, crossorigin, scaleMode)); utils.TextureCache[imageUrl] = texture; } @@ -248,9 +269,11 @@ * @param frameId {string} The frame id of the texture * @return Texture */ -Texture.fromFrame = function (frameId) { +Texture.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache '); } return texture; @@ -264,7 +287,8 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return {Texture} */ -Texture.fromCanvas = function (canvas, scaleMode) { +Texture.fromCanvas = function (canvas, scaleMode) +{ return new Texture(BaseTexture.fromCanvas(canvas, scaleMode)); }; @@ -276,7 +300,8 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return {Texture} A Texture */ -Texture.fromVideo = function (video, scaleMode) { +Texture.fromVideo = function (video, scaleMode) +{ return new Texture(VideoBaseTexture.baseTextureFromVideo(video, scaleMode)); }; @@ -287,7 +312,8 @@ * @param texture {Texture} The Texture to add to the cache. * @param id {string} The id that the texture will be stored against. */ -Texture.addTextureToCache = function (texture, id) { +Texture.addTextureToCache = function (texture, id) +{ utils.TextureCache[id] = texture; }; @@ -298,7 +324,8 @@ * @param id {string} The id of the texture to be removed * @return {Texture} The texture that was removed */ -Texture.removeTextureFromCache = function (id) { +Texture.removeTextureFromCache = function (id) +{ var texture = utils.TextureCache[id]; delete utils.TextureCache[id]; diff --git a/src/core/textures/TextureUvs.js b/src/core/textures/TextureUvs.js index b9bbb58..5424d52 100644 --- a/src/core/textures/TextureUvs.js +++ b/src/core/textures/TextureUvs.js @@ -1,4 +1,5 @@ -function TextureUvs() { +function TextureUvs() +{ this.x0 = 0; this.y0 = 0; diff --git a/src/core/textures/VideoBaseTexture.js b/src/core/textures/VideoBaseTexture.js index e3e0c5a..1a826a9 100644 --- a/src/core/textures/VideoBaseTexture.js +++ b/src/core/textures/VideoBaseTexture.js @@ -12,15 +12,18 @@ * @param source {HTMLVideoElement} * @param [scaleMode] {number} See {@link scaleModes} for possible values */ -function VideoBaseTexture(source, scaleMode) { - if (!source){ +function VideoBaseTexture(source, scaleMode) +{ + if (!source) + { throw new Error('No video source element specified.'); } // hook in here to check if video is already available. // BaseTexture looks for a source.complete boolean, plus width & height. - if ((source.readyState === source.HAVE_ENOUGH_DATA || source.readyState === source.HAVE_FUTURE_DATA) && source.width && source.height) { + if ((source.readyState === source.HAVE_ENOUGH_DATA || source.readyState === source.HAVE_FUTURE_DATA) && source.width && source.height) + { source.complete = true; } @@ -31,7 +34,8 @@ this._boundOnUpdate = this._onUpdate.bind(this); this._boundOnCanPlay = this._onCanPlay.bind(this); - if (!source.complete) { + if (!source.complete) + { source.addEventListener('canplay', this._boundOnCanPlay); source.addEventListener('canplaythrough', this._boundOnCanPlay); @@ -47,28 +51,35 @@ VideoBaseTexture.prototype.constructor = VideoBaseTexture; module.exports = VideoBaseTexture; -VideoBaseTexture.prototype._onUpdate = function () { - if (this.autoUpdate) { +VideoBaseTexture.prototype._onUpdate = function () +{ + if (this.autoUpdate) + { window.requestAnimationFrame(this._boundOnUpdate); this.needsUpdate = true; } }; -VideoBaseTexture.prototype._onPlayStart = function () { - if (!this.autoUpdate) { +VideoBaseTexture.prototype._onPlayStart = function () +{ + if (!this.autoUpdate) + { window.requestAnimationFrame(this._boundOnUpdate); this.autoUpdate = true; } }; -VideoBaseTexture.prototype._onPlayStop = function () { +VideoBaseTexture.prototype._onPlayStop = function () +{ this.autoUpdate = false; }; -VideoBaseTexture.prototype._onCanPlay = function () { +VideoBaseTexture.prototype._onCanPlay = function () +{ this.hasLoaded = true; - if (this.source) { + if (this.source) + { this.source.removeEventListener('canplay', this._boundOnCanPlay); this.source.removeEventListener('canplaythrough', this._boundOnCanPlay); @@ -78,15 +89,18 @@ this.source.play(); // prevent multiple loaded dispatches.. - if(!this.__loaded){ + if(!this.__loaded) + { this.__loaded = true; this.emit('loaded', this); } } }; -VideoBaseTexture.prototype.destroy = function () { - if (this.source && this.source._pixiId) { +VideoBaseTexture.prototype.destroy = function () +{ + if (this.source && this.source._pixiId) + { utils.BaseTextureCache[ this.source._pixiId ] = null; delete utils.BaseTextureCache[ this.source._pixiId ]; @@ -105,14 +119,17 @@ * @param scaleMode {number} See {@link scaleModes} for possible values * @return {VideoBaseTexture} */ -VideoBaseTexture.fromVideo = function (video, scaleMode) { - if (!video._pixiId) { +VideoBaseTexture.fromVideo = function (video, scaleMode) +{ + if (!video._pixiId) + { video._pixiId = 'video_' + utils.uuid(); } var baseTexture = utils.BaseTextureCache[video._pixiId]; - if (!baseTexture) { + if (!baseTexture) + { baseTexture = new VideoBaseTexture(video, scaleMode); utils.BaseTextureCache[ video._pixiId ] = baseTexture; } @@ -147,17 +164,21 @@ * @param scaleMode {number} See {@link scaleModes} for possible values * @return {VideoBaseTexture} */ -VideoBaseTexture.fromUrl = function (videoSrc, scaleMode) { +VideoBaseTexture.fromUrl = function (videoSrc, scaleMode) +{ var video = document.createElement('video'); // array of objects or strings - if (Array.isArray(videoSrc)) { - for (var i = 0; i < videoSrc.length; ++i) { + if (Array.isArray(videoSrc)) + { + for (var i = 0; i < videoSrc.length; ++i) + { video.appendChild(createSource(videoSrc.src || videoSrc, videoSrc.mime)); } } // single object or string - else { + else + { video.appendChild(createSource(videoSrc.src || videoSrc, videoSrc.mime)); } @@ -169,8 +190,10 @@ VideoBaseTexture.fromUrls = VideoBaseTexture.fromUrl; -function createSource(path, type) { - if (!type) { +function createSource(path, type) +{ + if (!type) + { type = 'video/' + path.substr(path.lastIndexOf('.') + 1); } diff --git a/src/core/utils/EventData.js b/src/core/utils/EventData.js index 5d55a22..8cdf701 100644 --- a/src/core/utils/EventData.js +++ b/src/core/utils/EventData.js @@ -7,7 +7,8 @@ * @param name {string} The string name of the event that was triggered * @param data {object} Arbitrary event data to pass along */ -function EventData(target, name, data) { +function EventData(target, name, data) +{ // for duck typing in the ".on()" function this.__isEventObject = true; @@ -71,7 +72,8 @@ * Stops the propagation of events up the scene graph (prevents bubbling). * */ -EventData.prototype.stopPropagation = function stopPropagation() { +EventData.prototype.stopPropagation = function stopPropagation() +{ this.stopped = true; }; @@ -79,6 +81,7 @@ * Stops the propagation of events to sibling listeners (no longer calls any listeners). * */ -EventData.prototype.stopImmediatePropagation = function stopImmediatePropagation() { +EventData.prototype.stopImmediatePropagation = function stopImmediatePropagation() +{ this.stoppedImmediate = true; }; diff --git a/src/core/utils/EventTarget.js b/src/core/utils/EventTarget.js index 7ae8820..671a151 100644 --- a/src/core/utils/EventTarget.js +++ b/src/core/utils/EventTarget.js @@ -13,14 +13,16 @@ * var em = new MyEmitter(); * em.emit('eventName', 'some data', 'some more data', {}, null, ...); */ -function eventTarget(obj) { +function eventTarget(obj) +{ /** * Return a list of assigned event listeners. * * @param eventName {string} The events that should be listed. * @return {Array} An array of listener functions */ - obj.listeners = function listeners(eventName) { + obj.listeners = function listeners(eventName) + { this._listeners = this._listeners || {}; return this._listeners[eventName] ? this._listeners[eventName].slice() : []; @@ -33,22 +35,26 @@ * @param eventName {string} The name of the event. * @return {boolean} Indication if we've emitted an event. */ - obj.emit = obj.dispatchEvent = function emit(eventName, data) { + obj.emit = obj.dispatchEvent = function emit(eventName, data) + { this._listeners = this._listeners || {}; // fast return when there are no listeners - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return; } //backwards compat with old method ".emit({ type: 'something' })" - if (typeof eventName === 'object') { + if (typeof eventName === 'object') + { data = eventName; eventName = eventName.type; } //ensure we are using a real pixi event - if (!data || data.__isEventObject !== true) { + if (!data || data.__isEventObject !== true) + { data = new EventData(this, eventName, data); } @@ -58,23 +64,27 @@ fn = listeners[0], i; - for (i = 0; i < length; fn = listeners[++i]) { + for (i = 0; i < length; fn = listeners[++i]) + { //call the event listener fn.call(this, data); //if "stopImmediatePropagation" is called, stop calling sibling events - if (data.stoppedImmediate) { + if (data.stoppedImmediate) + { return this; } } //if "stopPropagation" is called then don't bubble the event - if (data.stopped) { + if (data.stopped) + { return this; } //bubble this event up the scene graph - if (this.parent && this.parent.emit) { + if (this.parent && this.parent.emit) + { this.parent.emit.call(this.parent, eventName, data); } @@ -88,7 +98,8 @@ * @param eventName {string} Name of the event. * @param callback {Functon} fn Callback function. */ - obj.on = obj.addEventListener = function on(eventName, fn) { + obj.on = obj.addEventListener = function on(eventName, fn) + { this._listeners = this._listeners || {}; (this._listeners[eventName] = this._listeners[eventName] || []) @@ -103,11 +114,13 @@ * @param eventName {string} Name of the event. * @param callback {Function} Callback function. */ - obj.once = function once(eventName, fn) { + obj.once = function once(eventName, fn) + { this._listeners = this._listeners || {}; var self = this; - function onceHandlerWrapper() { + function onceHandlerWrapper() + { fn.apply(self.off(eventName, onceHandlerWrapper), arguments); } onceHandlerWrapper._originalHandler = fn; @@ -122,23 +135,28 @@ * @param eventName {string} The event we want to remove. * @param callback {Function} The listener that we need to find. */ - obj.off = obj.removeEventListener = function off(eventName, fn) { + obj.off = obj.removeEventListener = function off(eventName, fn) + { this._listeners = this._listeners || {}; - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return this; } var list = this._listeners[eventName], i = fn ? list.length : 0; - while(i-- > 0) { - if (list[i] === fn || list[i]._originalHandler === fn) { + while(i-- > 0) + { + if (list[i] === fn || list[i]._originalHandler === fn) + { list.splice(i, 1); } } - if (list.length === 0) { + if (list.length === 0) + { delete this._listeners[eventName]; } @@ -150,10 +168,12 @@ * * @param eventName {string} The event you want to remove all listeners for. */ - obj.removeAllListeners = function removeAllListeners(eventName) { + obj.removeAllListeners = function removeAllListeners(eventName) + { this._listeners = this._listeners || {}; - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return this; } @@ -169,7 +189,8 @@ * * @param object {object} The obj to mix into */ - mixin: function mixin(obj) { + mixin: function mixin(obj) + { eventTarget(obj); } }; diff --git a/src/core/utils/PolyK.js b/src/core/utils/PolyK.js index 7325141..5e20c2b 100644 --- a/src/core/utils/PolyK.js +++ b/src/core/utils/PolyK.js @@ -47,7 +47,8 @@ * Triangulates shapes for webGL graphic fills. * */ -PolyK.Triangulate = function (p) { +PolyK.Triangulate = function (p) +{ var sign = true; var n = p.length >> 1; @@ -59,7 +60,8 @@ i = 0; var al = n; - while(al > 3) { + while(al > 3) + { var i0 = avl[(i+0)%al]; var i1 = avl[(i+1)%al]; var i2 = avl[(i+2)%al]; @@ -69,29 +71,35 @@ var cx = p[2*i2], cy = p[2*i2+1]; var earFound = false; - if (PolyK._convex(ax, ay, bx, by, cx, cy, sign)) { + if (PolyK._convex(ax, ay, bx, by, cx, cy, sign)) + { earFound = true; - for (var j = 0; j < al; j++) { + for (var j = 0; j < al; j++) + { var vi = avl[j]; if (vi === i0 || vi === i1 || vi === i2) continue; - if (PolyK._PointInTriangle(p[2*vi], p[2*vi+1], ax, ay, bx, by, cx, cy)) { + if (PolyK._PointInTriangle(p[2*vi], p[2*vi+1], ax, ay, bx, by, cx, cy)) + { earFound = false; break; } } } - if (earFound) { + if (earFound) + { tgs.push(i0, i1, i2); avl.splice((i+1)%al, 1); al--; i = 0; } - else if (i++ > 3*al) { + else if (i++ > 3*al) + { // need to flip flip reverse it! // reset! - if (sign) { + if (sign) + { tgs = []; avl = []; for (i = 0; i < n; i++) avl.push(i); @@ -101,7 +109,8 @@ sign = false; } - else { + else + { // window.console.log("PIXI Warning: shape too complex to fill"); return null; } @@ -126,7 +135,8 @@ * @private * @return {boolean} */ -PolyK._PointInTriangle = function (px, py, ax, ay, bx, by, cx, cy) { +PolyK._PointInTriangle = function (px, py, ax, ay, bx, by, cx, cy) +{ var v0x = cx-ax; var v0y = cy-ay; var v1x = bx-ax; @@ -154,6 +164,7 @@ * @private * @return {boolean} */ -PolyK._convex = function (ax, ay, bx, by, cx, cy, sign) { +PolyK._convex = function (ax, ay, bx, by, cx, cy, sign) +{ return ((ay-by)*(cx-bx) + (bx-ax)*(cy-by) >= 0) === sign; }; diff --git a/src/core/utils/index.js b/src/core/utils/index.js index ade9831..bfae7ae 100644 --- a/src/core/utils/index.js +++ b/src/core/utils/index.js @@ -16,7 +16,8 @@ * * @return {number} The next uuid to use. */ - uuid: function () { + uuid: function () + { return ++utils._uid; }, @@ -26,7 +27,8 @@ * @param hex {number} * @return {number[]} An array representing the [R, G, B] of the color. */ - hex2rgb: function (hex, out) { + hex2rgb: function (hex, out) + { out = out || []; out[0] = (hex >> 16 & 0xFF) / 255; @@ -42,7 +44,8 @@ * @param hex {number} * @return {string} The string color. */ - hex2string: function (hex) { + hex2string: function (hex) + { hex = hex.toString(16); hex = '000000'.substr(0, 6 - hex.length) + hex; @@ -55,7 +58,8 @@ * @param rgb {number[]} * @return {number} The color number */ - rgb2hex: function (rgb) { + rgb2hex: function (rgb) + { return ((rgb[0]*255 << 16) + (rgb[1]*255 << 8) + rgb[2]*255); }, @@ -64,8 +68,10 @@ * * @return {boolean} whether they are supported */ - canUseNewCanvasBlendModes: function () { - if (typeof document === 'undefined') { + canUseNewCanvasBlendModes: function () + { + if (typeof document === 'undefined') + { return false; } @@ -93,15 +99,19 @@ * @param number {number} * @return {number} the closest number that is a power of two */ - getNextPowerOfTwo: function (number) { + getNextPowerOfTwo: function (number) + { // see: http://en.wikipedia.org/wiki/Power_of_two#Fast_algorithm_to_check_if_a_positive_number_is_a_power_of_two - if (number > 0 && (number & (number - 1)) === 0) { + if (number > 0 && (number & (number - 1)) === 0) + { return number; } - else { + else + { var result = 1; - while (result < number) { + while (result < number) + { result <<= 1; } @@ -116,7 +126,8 @@ * @param height {number} * @return {boolean} */ - isPowerOfTwo: function (width, height) { + isPowerOfTwo: function (width, height) + { return (width > 0 && (width & (width - 1)) === 0 && height > 0 && (height & (height - 1)) === 0); }, @@ -130,12 +141,15 @@ * @constant * @static */ - sayHello: function (type) { - if (utils._saidHello) { + sayHello: function (type) + { + if (utils._saidHello) + { return; } - if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) { + if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) + { var args = [ '%c %c %c Pixi.js ' + CONST.VERSION + ' - ' + type + ' %c ' + ' %c ' + ' http://www.pixijs.com/ %c %c ♥%c♥%c♥ ', 'background: #ff66a5', @@ -151,7 +165,8 @@ console.log.apply(console, args); //jshint ignore:line } - else if (window.console) { + else if (window.console) + { console.log('Pixi.js ' + CONST.VERSION + ' - ' + type + ' - http://www.pixijs.com/'); //jshint ignore:line } @@ -166,15 +181,19 @@ * @class * @namespace PIXI */ - AjaxRequest: function () { + AjaxRequest: function () + { var activexmodes = ['Msxml2.XMLHTTP.6.0', 'Msxml2.XMLHTTP.3.0', 'Microsoft.XMLHTTP']; //activeX versions to check for in IE - if (window.ActiveXObject) { //Test for support for ActiveXObject in IE first (as XMLHttpRequest in IE7 is broken) - for (var i=0; i= this.textures.length) { + else if (round >= this.textures.length) + { this.gotoAndStop(this.textures.length - 1); - if (this.onComplete) { + if (this.onComplete) + { this.onComplete(); } } @@ -167,10 +182,12 @@ * @static * @param frames {string[]} the array of frames ids the movieclip will use as its texture frames */ -MovieClip.fromFrames = function (frames) { +MovieClip.fromFrames = function (frames) +{ var textures = []; - for (var i = 0; i < frames.length; ++i) { + for (var i = 0; i < frames.length; ++i) + { textures.push(new core.Texture.fromFrame(frames[i])); } @@ -183,10 +200,12 @@ * @static * @param images {string[]} the array of image urls the movieclip will use as its texture frames */ -MovieClip.fromImages = function (images) { +MovieClip.fromImages = function (images) +{ var textures = []; - for (var i = 0; i < images.length; ++i) { + for (var i = 0; i < images.length; ++i) + { textures.push(new core.Texture.fromImage(images[i])); } diff --git a/src/extras/Rope.js b/src/extras/Rope.js index c157ec4..9c87bc0 100644 --- a/src/extras/Rope.js +++ b/src/extras/Rope.js @@ -9,7 +9,8 @@ * @param {Array} points - An array of {Point}. * */ -function Rope(texture, points) { +function Rope(texture, points) +{ Strip.call(this, texture); this.points = points; @@ -31,10 +32,12 @@ * Refreshes * */ -Rope.prototype.refresh = function () { +Rope.prototype.refresh = function () +{ var points = this.points; - if (points.length < 1) { + if (points.length < 1) + { return; } @@ -59,20 +62,23 @@ var total = points.length, point, index, amount; - for (var i = 1; i < total; i++) { + for (var i = 1; i < total; i++) + { point = points[i]; index = i * 4; // time to do some smart drawing! amount = i / (total-1); - if (i%2) { + if (i%2) + { uvs[index] = amount; uvs[index+1] = 0; uvs[index+2] = amount; uvs[index+3] = 1; } - else { + else + { uvs[index] = amount; uvs[index+1] = 0; @@ -95,10 +101,12 @@ * * @private */ -Rope.prototype.updateTransform = function () { +Rope.prototype.updateTransform = function () +{ var points = this.points; - if (points.length < 1) { + if (points.length < 1) + { return; } @@ -113,14 +121,17 @@ var total = points.length, point, index, ratio, perpLength, num; - for (var i = 0; i < total; i++) { + for (var i = 0; i < total; i++) + { point = points[i]; index = i * 4; - if (i < points.length-1) { + if (i < points.length-1) + { nextPoint = points[i+1]; } - else { + else + { nextPoint = point; } @@ -129,7 +140,8 @@ ratio = (1 - (i / (total-1))) * 10; - if (ratio > 1) { + if (ratio > 1) + { ratio = 1; } @@ -157,7 +169,8 @@ * * @param texture {Texture} the texture that will be used */ -Rope.prototype.setTexture = function (texture) { +Rope.prototype.setTexture = function (texture) +{ // stop current texture this.texture = texture; //this.updateFrame = true; diff --git a/src/extras/Strip.js b/src/extras/Strip.js index c5e378f..57691b5 100644 --- a/src/extras/Strip.js +++ b/src/extras/Strip.js @@ -10,7 +10,8 @@ * @param height {number} the height * */ -function Strip(texture) { +function Strip(texture) +{ core.DisplayObjectContainer.call(this); /** @@ -70,9 +71,11 @@ * * @param renderer {WebGLRenderer} */ -Strip.prototype.renderWebGL = function (renderer) { +Strip.prototype.renderWebGL = function (renderer) +{ // if the sprite is not visible or the alpha is 0 then no need to render this element - if (!this.visible || this.alpha <= 0) { + if (!this.visible || this.alpha <= 0) + { return; } @@ -81,7 +84,8 @@ renderer.spriteBatch.stop(); // init! init! - if (!this._vertexBuffer) { + if (!this._vertexBuffer) + { this._initWebGL(renderer); } @@ -96,7 +100,8 @@ //TODO check culling }; -Strip.prototype._initWebGL = function (renderer) { +Strip.prototype._initWebGL = function (renderer) +{ // build the strip! var gl = renderer.gl; @@ -118,7 +123,8 @@ gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this.indices, gl.STATIC_DRAW); }; -Strip.prototype._renderStrip = function (renderer) { +Strip.prototype._renderStrip = function (renderer) +{ var gl = renderer.gl; var projection = renderer.projection, offset = renderer.offset, @@ -137,7 +143,8 @@ gl.uniform2f(shader.offsetVector, -offset.x, -offset.y); gl.uniform1f(shader.alpha, this.worldAlpha); - if (!this.dirty) { + if (!this.dirty) + { gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexBuffer); gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); @@ -150,10 +157,12 @@ gl.activeTexture(gl.TEXTURE0); // check if a texture is dirty.. - if (this.texture.baseTexture._dirty[gl.id]) { + if (this.texture.baseTexture._dirty[gl.id]) + { renderer.updateTexture(this.texture.baseTexture); } - else { + else + { // bind the current texture gl.bindTexture(gl.TEXTURE_2D, this.texture.baseTexture._glTextures[gl.id]); } @@ -163,7 +172,8 @@ } - else { + else + { this.dirty = false; gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexBuffer); @@ -178,10 +188,12 @@ gl.activeTexture(gl.TEXTURE0); // check if a texture is dirty.. - if (this.texture.baseTexture._dirty[gl.id]) { + if (this.texture.baseTexture._dirty[gl.id]) + { renderer.updateTexture(this.texture.baseTexture); } - else { + else + { gl.bindTexture(gl.TEXTURE_2D, this.texture.baseTexture._glTextures[gl.id]); } @@ -203,27 +215,33 @@ * * @param renderer {CanvasRenderer} */ -Strip.prototype.renderCanvas = function (renderer) { +Strip.prototype.renderCanvas = function (renderer) +{ var context = renderer.context; var transform = this.worldTransform; - if (renderer.roundPixels) { + if (renderer.roundPixels) + { context.setTransform(transform.a, transform.b, transform.c, transform.d, transform.tx | 0, transform.ty | 0); } - else { + else + { context.setTransform(transform.a, transform.b, transform.c, transform.d, transform.tx, transform.ty); } - if (this.drawMode === Strip.DrawModes.TRIANGLE_STRIP) { + if (this.drawMode === Strip.DrawModes.TRIANGLE_STRIP) + { this._renderCanvasTriangleStrip(context); } - else { + else + { this._renderCanvasTriangles(context); } }; -Strip.prototype._renderCanvasTriangleStrip = function (context) { +Strip.prototype._renderCanvasTriangleStrip = function (context) +{ // draw triangles!! var vertices = this.vertices; var uvs = this.uvs; @@ -231,14 +249,16 @@ var length = vertices.length / 2; // this.count++; - for (var i = 0; i < length - 2; i++) { + for (var i = 0; i < length - 2; i++) + { // draw some triangles! var index = i * 2; this._renderCanvasDrawTriangle(context, vertices, uvs, index, (index + 2), (index + 4)); } }; -Strip.prototype._renderCanvasTriangles = function (context) { +Strip.prototype._renderCanvasTriangles = function (context) +{ // draw triangles!! var vertices = this.vertices; var uvs = this.uvs; @@ -247,14 +267,16 @@ var length = indices.length; // this.count++; - for (var i = 0; i < length; i += 3) { + for (var i = 0; i < length; i += 3) + { // draw some triangles! var index0 = indices[i] * 2, index1 = indices[i + 1] * 2, index2 = indices[i + 2] * 2; this._renderCanvasDrawTriangle(context, vertices, uvs, index0, index1, index2); } }; -Strip.prototype._renderCanvasDrawTriangle = function (context, vertices, uvs, index0, index1, index2) { +Strip.prototype._renderCanvasDrawTriangle = function (context, vertices, uvs, index0, index1, index2) +{ var textureSource = this.texture.baseTexture.source; var textureWidth = this.texture.width; var textureHeight = this.texture.height; @@ -265,7 +287,8 @@ var u0 = uvs[index0] * textureWidth, u1 = uvs[index1] * textureWidth, u2 = uvs[index2] * textureWidth; var v0 = uvs[index0 + 1] * textureHeight, v1 = uvs[index1 + 1] * textureHeight, v2 = uvs[index2 + 1] * textureHeight; - if (this.canvasPadding > 0) { + if (this.canvasPadding > 0) + { var paddingX = this.canvasPadding / this.worldTransform.a; var paddingY = this.canvasPadding / this.worldTransform.d; var centerX = (x0 + x1 + x2) / 3; @@ -332,7 +355,8 @@ * @param strip {Strip} The Strip to render * @private */ -Strip.prototype.renderStripFlat = function (strip) { +Strip.prototype.renderStripFlat = function (strip) +{ var context = this.context; var vertices = strip.vertices; @@ -340,7 +364,8 @@ // this.count++; context.beginPath(); - for (var i=1; i < length-2; i++) { + for (var i=1; i < length-2; i++) + { // draw some triangles! var index = i*2; @@ -358,7 +383,8 @@ }; /* -Strip.prototype.setTexture = function (texture) { +Strip.prototype.setTexture = function (texture) +{ //TODO SET THE TEXTURES //TODO VISIBILITY @@ -377,7 +403,8 @@ * @private */ -Strip.prototype.onTextureUpdate = function () { +Strip.prototype.onTextureUpdate = function () +{ this.updateFrame = true; }; @@ -387,7 +414,8 @@ * @param matrix {Matrix} the transformation matrix of the sprite * @return {Rectangle} the framing rectangle */ -Strip.prototype.getBounds = function (matrix) { +Strip.prototype.getBounds = function (matrix) +{ var worldTransform = matrix || this.worldTransform; var a = worldTransform.a; @@ -404,7 +432,8 @@ var minY = Infinity; var vertices = this.vertices; - for (var i = 0, n = vertices.length; i < n; i += 2) { + for (var i = 0, n = vertices.length; i < n; i += 2) + { var rawX = vertices[i], rawY = vertices[i + 1]; var x = (a * rawX) + (c * rawY) + tx; var y = (d * rawY) + (b * rawX) + ty; @@ -416,7 +445,8 @@ maxY = y > maxY ? y : maxY; } - if (minX === -Infinity || maxY === Infinity) { + if (minX === -Infinity || maxY === Infinity) + { return core.math.Rectangle.EMPTY; } diff --git a/src/extras/TilingSprite.js b/src/extras/TilingSprite.js index 3ac22df..31da393 100644 --- a/src/extras/TilingSprite.js +++ b/src/extras/TilingSprite.js @@ -10,7 +10,8 @@ * @param width {number} the width of the tiling sprite * @param height {number} the height of the tiling sprite */ -function TilingSprite(texture, width, height) { +function TilingSprite(texture, width, height) +{ core.Sprite.call( this, texture); /** @@ -86,10 +87,12 @@ * @memberof TilingSprite# */ width: { - get: function () { + get: function () + { return this._width; }, - set: function (value) { + set: function (value) + { this._width = value; } }, @@ -101,20 +104,25 @@ * @memberof TilingSprite# */ height: { - get: function () { + get: function () + { return this._height; }, - set: function (value) { + set: function (value) + { this._height = value; } }, texture: { - get: function () { + get: function () + { return this._texture; }, - set: function (value) { - if (this._texture === value) { + set: function (value) + { + if (this._texture === value) + { return; } @@ -130,51 +138,61 @@ * * @param renderer {WebGLRenderer} */ -TilingSprite.prototype.renderWebGL = function (renderer) { - if (!this.visible || this.alpha <= 0) { +TilingSprite.prototype.renderWebGL = function (renderer) +{ + if (!this.visible || this.alpha <= 0) + { return; } var i, j; - if (this._mask) { + if (this._mask) + { renderer.spriteBatch.stop(); renderer.maskManager.pushMask(this.mask, renderer); renderer.spriteBatch.start(); } - if (this._filters) { + if (this._filters) + { renderer.spriteBatch.flush(); renderer.filterManager.pushFilter(this._filterBlock); } - if (!this.tilingTexture || this.refreshTexture) { + if (!this.tilingTexture || this.refreshTexture) + { this.generateTilingTexture(true); - if (this.tilingTexture && this.tilingTexture.needsUpdate) { + if (this.tilingTexture && this.tilingTexture.needsUpdate) + { //TODO - tweaking renderer.updateTexture(this.tilingTexture.baseTexture); this.tilingTexture.needsUpdate = false; // this.tilingTexture._uvs = null; } } - else { + else + { renderer.spriteBatch.renderTilingSprite(this); } // simple render children! - for (i=0,j=this.children.length; i= 0 && index <= this.children.length) { - if (child.parent) { + if (index >= 0 && index <= this.children.length) + { + if (child.parent) + { child.parent.removeChild(child); } @@ -154,7 +173,8 @@ return child; } - else { + else + { throw new Error(child + 'addChildAt: The index '+ index +' supplied is out of bounds ' + this.children.length); } }; @@ -165,15 +185,18 @@ * @param child {DisplayObject} * @param child2 {DisplayObject} */ -DisplayObjectContainer.prototype.swapChildren = function (child, child2) { - if (child === child2) { +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) { + if (index1 < 0 || index2 < 0) + { throw new Error('swapChildren: Both the supplied DisplayObjects must be a child of the caller.'); } @@ -187,10 +210,12 @@ * @param child {DisplayObject} The DisplayObject instance to identify * @return {Number} The index position of the child display object to identify */ -DisplayObjectContainer.prototype.getChildIndex = function (child) { +DisplayObjectContainer.prototype.getChildIndex = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { throw new Error('The supplied DisplayObject must be a child of the caller'); } @@ -203,8 +228,10 @@ * @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 */ -DisplayObjectContainer.prototype.setChildIndex = function (child, index) { - if (index < 0 || index >= this.children.length) { +DisplayObjectContainer.prototype.setChildIndex = function (child, index) +{ + if (index < 0 || index >= this.children.length) + { throw new Error('The supplied index is out of bounds'); } @@ -220,8 +247,10 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child at the given index, if any. */ -DisplayObjectContainer.prototype.getChildAt = function (index) { - if (index < 0 || index >= this.children.length) { +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'); } @@ -234,10 +263,12 @@ * @param child {DisplayObject} The DisplayObject to remove * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChild = function (child) { +DisplayObjectContainer.prototype.removeChild = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { return; } @@ -250,7 +281,8 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChildAt = function (index) { +DisplayObjectContainer.prototype.removeChildAt = function (index) +{ var child = this.getChildAt(index); child.parent = null; @@ -265,24 +297,29 @@ * @param beginIndex {Number} The beginning position. Default value is 0. * @param endIndex {Number} The ending position. Default value is size of the container. */ -DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) { +DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) +{ var begin = beginIndex || 0; var end = typeof endIndex === 'number' ? endIndex : this.children.length; var range = end - begin; - if (range > 0 && range <= end) { + if (range > 0 && range <= end) + { var removed = this.children.splice(begin, range); - for (var i = 0; i < removed.length; ++i) { + for (var i = 0; i < removed.length; ++i) + { removed[i].parent = null; } return removed; } - else if (range === 0 && this.children.length === 0) { + else if (range === 0 && this.children.length === 0) + { return []; } - else { + else + { throw new RangeError('removeChildren: numeric values are outside the acceptable range.'); } }; @@ -291,7 +328,8 @@ * Generates and updates the cached sprite for this object. * */ -DisplayObjectContainer.prototype.updateCachedSprite = function () { +DisplayObjectContainer.prototype.updateCachedSprite = function () +{ this._generateCachedSprite(); }; @@ -304,7 +342,8 @@ * @param renderer {CanvasRenderer|WebGLRenderer} The renderer used to generate the texture. * @return {Texture} a texture of the graphics object */ -DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) { +DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) +{ var bounds = this.getLocalBounds(); var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0, renderer, scaleMode, resolution); @@ -322,18 +361,22 @@ * * @private */ -DisplayObjectContainer.prototype.updateTransform = function () { - if (!this.visible) { +DisplayObjectContainer.prototype.updateTransform = function () +{ + if (!this.visible) + { return; } this.displayObjectUpdateTransform(); - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { return; } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } }; @@ -346,8 +389,10 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getBounds = function () { - if (this.children.length === 0) { +DisplayObjectContainer.prototype.getBounds = function () +{ + if (this.children.length === 0) + { return math.Rectangle.EMPTY; } @@ -365,10 +410,12 @@ var childVisible = false; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -386,7 +433,8 @@ maxY = maxY > childMaxY ? maxY : childMaxY; } - if (!childVisible) { + if (!childVisible) + { return math.Rectangle.EMPTY; } @@ -407,12 +455,14 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getLocalBounds = function () { +DisplayObjectContainer.prototype.getLocalBounds = function () +{ var matrixCache = this.worldTransform; this.worldTransform = math.Matrix.IDENTITY; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } @@ -428,13 +478,16 @@ * * @param renderer {WebGLRenderer} The renderer */ -DisplayObjectContainer.prototype.renderWebGL = function (renderer) { +DisplayObjectContainer.prototype.renderWebGL = function (renderer) +{ // if the object is not visible or the alpha is 0 then no need to render this element - if (!this.visible || this.alpha <= 0) { + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } @@ -442,14 +495,17 @@ var i, j; // do a quick check to see if this element has a mask or a filter. - if (this._mask || this._filters) { + if (this._mask || this._filters) + { // push filter first as we need to ensure the stencil buffer is correct for any masking - if (this._filters) { + if (this._filters) + { renderer.spriteBatch.flush(); renderer.filterManager.pushFilter(this._filterBlock); } - if (this._mask) { + if (this._mask) + { renderer.spriteBatch.stop(); renderer.maskManager.pushMask(this.mask, renderer); renderer.spriteBatch.start(); @@ -459,36 +515,42 @@ this._renderWebGL(renderer); // now loop through the children and make sure they get rendered - for (i = 0, j = this.children.length; i < j; i++) { + for (i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderWebGL(renderer); } // time to stop the sprite batch as either a mask element or a filter draw will happen next renderer.spriteBatch.stop(); - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(this._mask, renderer); } - if (this._filters) { + if (this._filters) + { renderer.filterManager.popFilter(); } renderer.spriteBatch.start(); } - else { + else + { this._renderWebGL(renderer); // simple render children! - for (i = 0, j = this.children.length; i < j; ++i) { + for (i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderWebGL(renderer); } } }; -DisplayObjectContainer.prototype._renderWebGL = function (renderer) { +DisplayObjectContainer.prototype._renderWebGL = function (renderer) +{ // this is where content itself gets renderd.. @@ -499,25 +561,31 @@ * * @param renderer {CanvasRenderer} The renderer */ -DisplayObjectContainer.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0) { +DisplayObjectContainer.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -528,13 +596,16 @@ * @param renderer {WebGLRenderer|CanvasRenderer} The renderer * @private */ -DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) { +DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) +{ this._cachedSprite.worldAlpha = this.worldAlpha; - if (renderer.gl) { + if (renderer.gl) + { this._cachedSprite.renderWebGL(renderer); } - else { + else + { this._cachedSprite.renderCanvas(renderer); } }; @@ -544,10 +615,12 @@ * * @private */ -DisplayObjectContainer.prototype._generateCachedSprite = function () { +DisplayObjectContainer.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { // TODO - RenderTexture now *requires* a renderer instance, so this is like broken // because `renderer` isn't actually in scope here :P var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0); @@ -555,7 +628,8 @@ this._cachedSprite = new Sprite(renderTexture); this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.texture.resize(bounds.width | 0, bounds.height | 0); } @@ -580,8 +654,10 @@ * * @private */ -DisplayObjectContainer.prototype._destroyCachedSprite = function () { - if (!this._cachedSprite) { +DisplayObjectContainer.prototype._destroyCachedSprite = function () +{ + if (!this._cachedSprite) + { return; } diff --git a/src/core/display/Sprite.js b/src/core/display/Sprite.js index 707da24..5862aef 100644 --- a/src/core/display/Sprite.js +++ b/src/core/display/Sprite.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param texture {Texture} The texture for this sprite */ -function Sprite(texture) { +function Sprite(texture) +{ DisplayObjectContainer.call(this); /** @@ -85,12 +86,14 @@ this.texture = texture || Texture.EMPTY; } -Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) { +Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) +{ DisplayObjectContainer.prototype.destroy.call(this); this.anchor = null; - if (destroyTexture) { + if (destroyTexture) + { this._texture.destroy(destroyBaseTexture); } @@ -111,10 +114,12 @@ * @memberof Sprite# */ width: { - get: function () { + get: function () + { return this.scale.x * this.texture.frame.width; }, - set: function (value) { + set: function (value) + { this.scale.x = value / this.texture.frame.width; this._width = value; } @@ -127,10 +132,12 @@ * @memberof Sprite# */ height: { - get: function () { + get: function () + { return this.scale.y * this.texture.frame.height; }, - set: function (value) { + set: function (value) + { this.scale.y = value / this.texture.frame.height; this._height = value; } @@ -143,23 +150,29 @@ * @memberof Sprite# */ texture: { - get: function () { + get: function () + { return this._texture; }, - set: function (value) { - if (this._texture === value) { + set: function (value) + { + if (this._texture === value) + { return; } this._texture = value; this.cachedTint = 0xFFFFFF; - if (value) { + if (value) + { // wait for the texture to load - if (value.baseTexture.hasLoaded) { + if (value.baseTexture.hasLoaded) + { this._onTextureUpdate(); } - else { + else + { value.once('update', this._onTextureUpdate.bind(this)); } } @@ -172,18 +185,22 @@ * * @private */ -Sprite.prototype._onTextureUpdate = function () { +Sprite.prototype._onTextureUpdate = function () +{ // so if _width is 0 then width was not set.. - if (this._width) { + if (this._width) + { this.scale.x = this._width / this.texture.frame.width; } - if (this._height) { + if (this._height) + { this.scale.y = this._height / this.texture.frame.height; } }; -Sprite.prototype._renderWebGL = function (renderer) { +Sprite.prototype._renderWebGL = function (renderer) +{ // this is where content gets renderd.. // watch this space for a little render state manager.. @@ -197,7 +214,8 @@ * @param matrix {Matrix} the transformation matrix of the sprite * @return {Rectangle} the framing rectangle */ -Sprite.prototype.getBounds = function (matrix) { +Sprite.prototype.getBounds = function (matrix) +{ var width = this.texture.frame.width; var height = this.texture.frame.height; @@ -224,11 +242,13 @@ if(b === 0 && c === 0) { // scale may be negative! - if (a < 0) { + if (a < 0) + { a *= -1; } - if (d < 0) { + if (d < 0) + { d *= -1; } @@ -293,28 +313,34 @@ * * @param renderer {CanvasRenderer} The renderer */ -Sprite.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) { +Sprite.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) + { return; } - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; renderer.context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } // Ignore null sources - if (this.texture.valid) { + if (this.texture.valid) + { var resolution = this.texture.baseTexture.resolution / renderer.resolution; renderer.context.globalAlpha = this.worldAlpha; // If smoothingEnabled is supported and we need to change the smoothing property for this texture - if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) { + if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) + { renderer.scaleMode = this.texture.baseTexture.scaleMode; renderer.context[renderer.smoothProperty] = (renderer.scaleMode === CONST.scaleModes.LINEAR); } @@ -324,7 +350,8 @@ var dy = (this.texture.trim ? this.texture.trim.y : 0) - (this.anchor.y * this.texture.trim.height); // Allow for pixel rounding - if (renderer.roundPixels) { + if (renderer.roundPixels) + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -337,7 +364,8 @@ dx = dx | 0; dy = dy | 0; } - else { + else + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -348,8 +376,10 @@ ); } - if (this.tint !== 0xFFFFFF) { - if (this.cachedTint !== this.tint) { + if (this.tint !== 0xFFFFFF) + { + if (this.cachedTint !== this.tint) + { this.cachedTint = this.tint; // TODO clean up caching - how to clean up the caches? @@ -368,7 +398,8 @@ this.texture.crop.height / resolution ); } - else { + else + { renderer.context.drawImage( this.texture.baseTexture.source, this.texture.crop.x, @@ -383,11 +414,13 @@ } } - for (var i = 0, j = this.children.length; i < j; i++) { + for (var i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -402,10 +435,12 @@ * @param frameId {String} The frame Id of the texture in the cache * @return {Sprite} A new Sprite using a texture from the texture cache matching the frameId */ -Sprite.fromFrame = function (frameId) { +Sprite.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache' + this); } @@ -420,6 +455,7 @@ * @param imageId {String} The image url of the texture * @return {Sprite} A new Sprite using a texture from the texture cache matching the image id */ -Sprite.fromImage = function (imageId, crossorigin, scaleMode) { +Sprite.fromImage = function (imageId, crossorigin, scaleMode) +{ return new Sprite(Texture.fromImage(imageId, crossorigin, scaleMode)); }; diff --git a/src/core/display/SpriteBatch.js b/src/core/display/SpriteBatch.js index 3187777..c196fef 100644 --- a/src/core/display/SpriteBatch.js +++ b/src/core/display/SpriteBatch.js @@ -12,7 +12,8 @@ * ```js * var container = new SpriteBatch(); * - * for(var i = 0; i < 100; ++i) { + * for(var i = 0; i < 100; ++i) + * { * var sprite = new PIXI.Sprite.fromImage("myImage.png"); * container.addChild(sprite); * } @@ -25,7 +26,8 @@ */ //TODO RENAME to PARTICLE CONTAINER? -function SpriteBatch() { +function SpriteBatch() +{ DisplayObjectContainer.call(this); } @@ -38,7 +40,8 @@ * * @private */ -SpriteBatch.prototype.updateTransform = function () { +SpriteBatch.prototype.updateTransform = function () +{ // TODO don't need to! this.displayObjectUpdateTransform(); // PIXI.DisplayObjectContainer.prototype.updateTransform.call( this ); @@ -50,8 +53,10 @@ * @param renderer {WebGLRenderer} The webgl renderer * @private */ -SpriteBatch.prototype.renderWebGL = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderWebGL = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -71,8 +76,10 @@ * @param renderer {CanvasRenderer} The canvas renderer * @private */ -SpriteBatch.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -84,10 +91,12 @@ this.displayObjectUpdateTransform(); - for (var i = 0; i < this.children.length; ++i) { + for (var i = 0; i < this.children.length; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -95,9 +104,11 @@ context.globalAlpha = this.worldAlpha * child.alpha; - if (child.rotation % (Math.PI * 2) === 0) { + if (child.rotation % (Math.PI * 2) === 0) + { // this is the fastest way to optimise! - if rotation is 0 then we can avoid any kind of setTransform call - if (isRotated) { + if (isRotated) + { context.setTransform( transform.a, transform.b, @@ -122,8 +133,10 @@ frame.height * child.scale.y ); } - else { - if (!isRotated) { + else + { + if (!isRotated) + { isRotated = true; } @@ -131,7 +144,8 @@ var childTransform = child.worldTransform; - if (renderer.roundPixels) { + if (renderer.roundPixels) + { context.setTransform( childTransform.a, childTransform.b, @@ -141,7 +155,8 @@ childTransform.ty | 0 ); } - else { + else + { context.setTransform( childTransform.a, childTransform.b, diff --git a/src/core/index.js b/src/core/index.js index 3954b6f..eb4a82b 100644 --- a/src/core/index.js +++ b/src/core/index.js @@ -58,11 +58,13 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRenderer: function (width, height, options, noWebGL) { + autoDetectRenderer: function (width, height, options, noWebGL) + { width = width || 800; height = height || 600; - if (!noWebGL && require('webgl-enabled')()) { + if (!noWebGL && require('webgl-enabled')()) + { return new core.WebGLRenderer(width, height, options); } @@ -87,7 +89,8 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRecommendedRenderer: function (width, height, options) { + autoDetectRecommendedRenderer: function (width, height, options) + { var isAndroid = /Android/i.test(navigator.userAgent); return core.autoDetectRenderer(width, height, options, isAndroid); diff --git a/src/core/math/Matrix.js b/src/core/math/Matrix.js index c2f87e2..2ff4848 100644 --- a/src/core/math/Matrix.js +++ b/src/core/math/Matrix.js @@ -10,7 +10,8 @@ * @class * @namespace PIXI */ -function Matrix() { +function Matrix() +{ /** * @member {number} * @default 1 @@ -63,7 +64,8 @@ * * @param array {number[]} The array that the matrix will be populated from. */ -Matrix.prototype.fromArray = function (array) { +Matrix.prototype.fromArray = function (array) +{ this.a = array[0]; this.b = array[1]; this.c = array[3]; @@ -78,14 +80,17 @@ * @param transpose {boolean} Whether we need to transpose the matrix or not * @return {number[]} the newly created array which contains the matrix */ -Matrix.prototype.toArray = function (transpose) { - if (!this.array) { +Matrix.prototype.toArray = function (transpose) +{ + if (!this.array) + { this.array = new Float32Array(9); } var array = this.array; - if (transpose) { + if (transpose) + { array[0] = this.a; array[1] = this.b; array[2] = 0; @@ -96,7 +101,8 @@ array[7] = this.ty; array[8] = 1; } - else { + else + { array[0] = this.a; array[1] = this.c; array[2] = this.tx; @@ -119,7 +125,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, transformed through this matrix */ -Matrix.prototype.apply = function (pos, newPos) { +Matrix.prototype.apply = function (pos, newPos) +{ newPos = newPos || new Point(); newPos.x = this.a * pos.x + this.c * pos.y + this.tx; @@ -136,7 +143,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, inverse-transformed through this matrix */ -Matrix.prototype.applyInverse = function (pos, newPos) { +Matrix.prototype.applyInverse = function (pos, newPos) +{ newPos = newPos || new Point(); var id = 1 / (this.a * this.d + this.c * -this.b); @@ -154,7 +162,8 @@ * @param {number} y * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.translate = function (x, y) { +Matrix.prototype.translate = function (x, y) +{ this.tx += x; this.ty += y; @@ -168,7 +177,8 @@ * @param {number} y The amount to scale vertically * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.scale = function (x, y) { +Matrix.prototype.scale = function (x, y) +{ this.a *= x; this.d *= y; this.c *= x; @@ -186,7 +196,8 @@ * @param {number} angle - The angle in radians. * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.rotate = function (angle) { +Matrix.prototype.rotate = function (angle) +{ var cos = Math.cos( angle ); var sin = Math.sin( angle ); @@ -210,7 +221,8 @@ * @param {Matrix} matrix * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.append = function (matrix) { +Matrix.prototype.append = function (matrix) +{ var a1 = this.a; var b1 = this.b; var c1 = this.c; @@ -232,7 +244,8 @@ * * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.identity = function () { +Matrix.prototype.identity = function () +{ this.a = 1; this.b = 0; this.c = 0; diff --git a/src/core/math/Point.js b/src/core/math/Point.js index 7565b2d..632f346 100644 --- a/src/core/math/Point.js +++ b/src/core/math/Point.js @@ -7,7 +7,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -function Point(x, y) { +function Point(x, y) +{ /** * @member {number} * @default 0 @@ -29,7 +30,8 @@ * * @return {Point} a copy of the point */ -Point.prototype.clone = function () { +Point.prototype.clone = function () +{ return new Point(this.x, this.y); }; @@ -40,7 +42,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -Point.prototype.set = function (x, y) { +Point.prototype.set = function (x, y) +{ this.x = x || 0; this.y = y || ( (y !== 0) ? this.x : 0 ) ; }; diff --git a/src/core/math/shapes/Circle.js b/src/core/math/shapes/Circle.js index 69cfdc9..4d76efc 100644 --- a/src/core/math/shapes/Circle.js +++ b/src/core/math/shapes/Circle.js @@ -10,7 +10,8 @@ * @param y {number} The Y coordinate of the center of this circle * @param radius {number} The radius of the circle */ -function Circle(x, y, radius) { +function Circle(x, y, radius) +{ /** * @member {number} * @default 0 @@ -46,7 +47,8 @@ * @method clone * @return {Circle} a copy of the Circle */ -Circle.prototype.clone = function () { +Circle.prototype.clone = function () +{ return new Circle(this.x, this.y, this.radius); }; @@ -58,8 +60,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Circle */ -Circle.prototype.contains = function (x, y) { - if (this.radius <= 0) { +Circle.prototype.contains = function (x, y) +{ + if (this.radius <= 0) + { return false; } @@ -79,6 +83,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Circle.prototype.getBounds = function () { +Circle.prototype.getBounds = function () +{ return new Rectangle(this.x - this.radius, this.y - this.radius, this.radius * 2, this.radius * 2); }; diff --git a/src/core/math/shapes/Ellipse.js b/src/core/math/shapes/Ellipse.js index 4f2d066..fefd01a 100644 --- a/src/core/math/shapes/Ellipse.js +++ b/src/core/math/shapes/Ellipse.js @@ -11,7 +11,8 @@ * @param width {number} The half width of this ellipse * @param height {number} The half height of this ellipse */ -function Ellipse(x, y, width, height) { +function Ellipse(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -53,7 +54,8 @@ * @method clone * @return {Ellipse} a copy of the ellipse */ -Ellipse.prototype.clone = function () { +Ellipse.prototype.clone = function () +{ return new Ellipse(this.x, this.y, this.width, this.height); }; @@ -65,8 +67,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coords are within this ellipse */ -Ellipse.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Ellipse.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } @@ -86,6 +90,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Ellipse.prototype.getBounds = function () { +Ellipse.prototype.getBounds = function () +{ return new Rectangle(this.x - this.width, this.y - this.height, this.width, this.height); }; diff --git a/src/core/math/shapes/Polygon.js b/src/core/math/shapes/Polygon.js index ae89148..fea6d37 100644 --- a/src/core/math/shapes/Polygon.js +++ b/src/core/math/shapes/Polygon.js @@ -10,16 +10,20 @@ * arguments passed can be flat x,y values e.g. `new Polygon(x,y, x,y, x,y, ...)` where `x` and `y` are * Numbers. */ -function Polygon(points) { +function Polygon(points) +{ //if points isn't an array, use arguments as the array - if (!(points instanceof Array)) { + if (!(points instanceof Array)) + { points = Array.prototype.slice.call(arguments); } //if this is a flat array of numbers, convert it to points - if (points[0] instanceof Point) { + if (points[0] instanceof Point) + { var p = []; - for (var i = 0, il = points.length; i < il; i++) { + for (var i = 0, il = points.length; i < il; i++) + { p.push(points[i].x, points[i].y); } @@ -51,7 +55,8 @@ * * @return {Polygon} a copy of the polygon */ -Polygon.prototype.clone = function () { +Polygon.prototype.clone = function () +{ return new Polygon(this.points.slice()); }; @@ -62,19 +67,22 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this polygon */ -Polygon.prototype.contains = function (x, y) { +Polygon.prototype.contains = function (x, y) +{ var inside = false; // use some raycasting to test hits // https://github.com/substack/point-in-polygon/blob/master/index.js var length = this.points.length / 2; - for (var i = 0, j = length - 1; i < length; j = i++) { + for (var i = 0, j = length - 1; i < length; j = i++) + { var xi = this.points[i * 2], yi = this.points[i * 2 + 1], xj = this.points[j * 2], yj = this.points[j * 2 + 1], intersect = ((yi > y) !== (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi); - if (intersect) { + if (intersect) + { inside = !inside; } } diff --git a/src/core/math/shapes/Rectangle.js b/src/core/math/shapes/Rectangle.js index 16ac62a..4008b68 100644 --- a/src/core/math/shapes/Rectangle.js +++ b/src/core/math/shapes/Rectangle.js @@ -10,7 +10,8 @@ * @param width {number} The overall width of this rectangle * @param height {number} The overall height of this rectangle */ -function Rectangle(x, y, width, height) { +function Rectangle(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -60,7 +61,8 @@ * * @return {Rectangle} a copy of the rectangle */ -Rectangle.prototype.clone = function () { +Rectangle.prototype.clone = function () +{ return new Rectangle(this.x, this.y, this.width, this.height); }; @@ -71,13 +73,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rectangle */ -Rectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Rectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/math/shapes/RoundedRectangle.js b/src/core/math/shapes/RoundedRectangle.js index 27d286e..7bf6411 100644 --- a/src/core/math/shapes/RoundedRectangle.js +++ b/src/core/math/shapes/RoundedRectangle.js @@ -11,7 +11,8 @@ * @param height {number} The overall height of this rounded rectangle * @param radius {number} Controls the radius of the rounded corners */ -function RoundedRectangle(x, y, width, height, radius) { +function RoundedRectangle(x, y, width, height, radius) +{ /** * @member {number} * @default 0 @@ -58,7 +59,8 @@ * * @return {RoundedRectangle} a copy of the rounded rectangle */ -RoundedRectangle.prototype.clone = function () { +RoundedRectangle.prototype.clone = function () +{ return new RoundedRectangle(this.x, this.y, this.width, this.height, this.radius); }; @@ -69,13 +71,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rounded Rectangle */ -RoundedRectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +RoundedRectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/primitives/Graphics.js b/src/core/primitives/Graphics.js index 261c534..e902d2a 100644 --- a/src/core/primitives/Graphics.js +++ b/src/core/primitives/Graphics.js @@ -16,7 +16,8 @@ * @extends DisplayObjectContainer * @namespace PIXI */ -function Graphics() { +function Graphics() +{ DisplayObjectContainer.call(this); this.renderable = true; @@ -154,16 +155,20 @@ * @private */ cacheAsBitmap: { - get: function () { + get: function () + { return this._cacheAsBitmap; }, - set: function (value) { + set: function (value) + { this._cacheAsBitmap = value; - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._generateCachedSprite(); } - else { + else + { this.destroyCachedSprite(); this.dirty = true; } @@ -176,7 +181,8 @@ * * @return {Graphics} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ var clone = new Graphics(); clone.renderable = this.renderable; @@ -192,7 +198,8 @@ clone.cachedSpriteDirty = this.cachedSpriteDirty; // copy graphics data - for (var i = 0; i < this.graphicsData.length; ++i) { + for (var i = 0; i < this.graphicsData.length; ++i) + { clone.graphicsData.push(this.graphicsData.clone()); } @@ -211,17 +218,21 @@ * @param alpha {number} alpha of the line to draw, will update the objects stored style * @return {Graphics} */ -Graphics.prototype.lineStyle = function (lineWidth, color, alpha) { +Graphics.prototype.lineStyle = function (lineWidth, color, alpha) +{ this.lineWidth = lineWidth || 0; this.lineColor = color || 0; this.lineAlpha = (arguments.length < 3) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length) + { // halfway through a line? start a new one! this.drawShape( new math.Polygon( this.currentPath.shape.points.slice(-2) )); } - else { + else + { // otherwise its empty so lets just set the line properties this.currentPath.lineWidth = this.lineWidth; this.currentPath.lineColor = this.lineColor; @@ -239,7 +250,8 @@ * @param y {number} the Y coordinate to move to * @return {Graphics} */ -Graphics.prototype.moveTo = function (x, y) { +Graphics.prototype.moveTo = function (x, y) +{ this.drawShape(new math.Polygon([x,y])); return this; @@ -253,7 +265,8 @@ * @param y {number} the Y coordinate to draw to * @return {Graphics} */ -Graphics.prototype.lineTo = function (x, y) { +Graphics.prototype.lineTo = function (x, y) +{ this.currentPath.shape.points.push(x, y); this.dirty = true; @@ -270,13 +283,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -285,7 +302,8 @@ n = 20, points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { this.moveTo(0, 0); } @@ -293,7 +311,8 @@ var fromY = points[points.length-1]; var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; xa = fromX + ( (cpX - fromX) * j ); @@ -319,13 +338,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -342,7 +365,8 @@ var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; dt = (1 - j); @@ -373,13 +397,17 @@ * @param radius {number} The radius of the arc * @return {Graphics} */ -Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points.push(x1, y1); } } - else { + else + { this.moveTo(x1, y1); } @@ -392,12 +420,15 @@ b2 = x2 - x1, mm = Math.abs(a1 * b2 - b1 * a2); - if (mm < 1.0e-8 || radius === 0) { - if (points[points.length-2] !== x1 || points[points.length-1] !== y1) { + if (mm < 1.0e-8 || radius === 0) + { + if (points[points.length-2] !== x1 || points[points.length-1] !== y1) + { points.push(x1, y1); } } - else { + else + { var dd = a1 * a1 + b1 * b1, cc = a2 * a2 + b2 * b2, tt = a1 * a2 + b1 * b2, @@ -433,42 +464,51 @@ * @param anticlockwise {boolean} Optional. Specifies whether the drawing should be counterclockwise or clockwise. False is default, and indicates clockwise, while true indicates counter-clockwise. * @return {Graphics} */ -Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) { +Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) +{ var startX = cx + Math.cos(startAngle) * radius; var startY = cy + Math.sin(startAngle) * radius; var points; // TODO - This if-else makes no sense. It uses currentPath in the else where it doesn't exist... - if (this.currentPath) { + if (this.currentPath) + { points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { points.push(startX, startY); } - else if (points[points.length-2] !== startX || points[points.length-1] !== startY) { + else if (points[points.length-2] !== startX || points[points.length-1] !== startY) + { points.push(startX, startY); } } - else { + else + { this.moveTo(startX, startY); points = this.currentPath.shape.points; } - if (startAngle === endAngle) { + if (startAngle === endAngle) + { return this; } - if (!anticlockwise && endAngle <= startAngle) { + if (!anticlockwise && endAngle <= startAngle) + { endAngle += Math.PI * 2; } - else if (anticlockwise && startAngle <= endAngle) { + else if (anticlockwise && startAngle <= endAngle) + { startAngle += Math.PI * 2; } var sweep = anticlockwise ? (startAngle - endAngle) *-1 : (endAngle - startAngle); var segs = (Math.abs(sweep)/ (Math.PI * 2)) * 40; - if (sweep === 0) { + if (sweep === 0) + { return this; } @@ -482,7 +522,8 @@ var remainder = ( segMinus % 1 ) / segMinus; - for (var i = 0; i <= segMinus; ++i) { + for (var i = 0; i <= segMinus; ++i) + { var real = i + remainder * i; var angle = ((theta) + startAngle + (theta2 * real)); @@ -506,13 +547,16 @@ * @param alpha {number} the alpha of the fill * @return {Graphics} */ -Graphics.prototype.beginFill = function (color, alpha) { +Graphics.prototype.beginFill = function (color, alpha) +{ this.filling = true; this.fillColor = color || 0; this.fillAlpha = (alpha === undefined) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length <= 2) + { this.currentPath.fill = this.filling; this.currentPath.fillColor = this.fillColor; this.currentPath.fillAlpha = this.fillAlpha; @@ -526,7 +570,8 @@ * * @return {Graphics} */ -Graphics.prototype.endFill = function () { +Graphics.prototype.endFill = function () +{ this.filling = false; this.fillColor = null; this.fillAlpha = 1; @@ -542,7 +587,8 @@ * @param height {number} The height of the rectangle * @return {Graphics} */ -Graphics.prototype.drawRect = function ( x, y, width, height ) { +Graphics.prototype.drawRect = function ( x, y, width, height ) +{ this.drawShape(new math.Rectangle(x,y, width, height)); return this; @@ -556,7 +602,8 @@ * @param height {number} The height of the rectangle * @param radius {number} Radius of the rectangle corners */ -Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) { +Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) +{ this.drawShape(new math.RoundedRectangle(x, y, width, height, radius)); return this; @@ -570,7 +617,8 @@ * @param radius {number} The radius of the circle * @return {Graphics} */ -Graphics.prototype.drawCircle = function (x, y, radius) { +Graphics.prototype.drawCircle = function (x, y, radius) +{ this.drawShape(new math.Circle(x,y, radius)); return this; @@ -585,7 +633,8 @@ * @param height {number} The half height of the ellipse * @return {Graphics} */ -Graphics.prototype.drawEllipse = function (x, y, width, height) { +Graphics.prototype.drawEllipse = function (x, y, width, height) +{ this.drawShape(new math.Ellipse(x, y, width, height)); return this; @@ -597,8 +646,10 @@ * @param path {Array} The path data used to construct the polygon. * @return {Graphics} */ -Graphics.prototype.drawPolygon = function (path) { - if (!(path instanceof Array)) { +Graphics.prototype.drawPolygon = function (path) +{ + if (!(path instanceof Array)) + { path = Array.prototype.slice.call(arguments); } @@ -612,7 +663,8 @@ * * @return {Graphics} */ -Graphics.prototype.clear = function () { +Graphics.prototype.clear = function () +{ this.lineWidth = 0; this.filling = false; @@ -631,7 +683,8 @@ * @param scaleMode {number} Should be one of the scaleMode consts * @return {Texture} a texture of the graphics object */ -Graphics.prototype.generateTexture = function (resolution, scaleMode) { +Graphics.prototype.generateTexture = function (resolution, scaleMode) +{ resolution = resolution || 1; var bounds = this.getBounds(); @@ -655,17 +708,21 @@ * * @param renderer {WebGLRenderer} */ -Graphics.prototype._renderWebGL = function (renderer) { +Graphics.prototype._renderWebGL = function (renderer) +{ // if the sprite is not visible or the alpha is 0 then no need to render this element - if (this.isMask === true) { + if (this.isMask === true) + { return; } // this code may still be needed so leaving for now.. - // + // /* - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture on the gpu too! @@ -681,17 +738,24 @@ return; } - */ - - // check if the webgl graphic needs to be updated - if (this.glDirty) { - this.dirty = true; - this.glDirty = false; - } + else */ - renderer.setObjectRendererer(renderer.graphicsRenderer); - renderer.graphicsRenderer.render(this); + renderer.spriteBatch.stop(); + renderer.blendModeManager.setBlendMode(this.blendMode); + // check blend mode + renderer.blendModeManager.setBlendMode( this.blendMode ); + + // check if the webgl graphic needs to be updated + if (this.glDirty) + { + this.dirty = true; + this.glDirty = false; + } + + WebGLGraphics.renderGraphics(this, renderer); + + renderer.spriteBatch.start(); }; /** @@ -700,14 +764,18 @@ * @param renderer {CanvasRenderer} * @private */ -Graphics.prototype.renderCanvas = function (renderer) { +Graphics.prototype.renderCanvas = function (renderer) +{ // 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.isMask === true) { + if (!this.visible || this.alpha <= 0 || this.isMask === true) + { return; } - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture @@ -723,16 +791,19 @@ return; } - else { + else + { var context = renderer.context; var transform = this.worldTransform; - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } @@ -748,11 +819,13 @@ CanvasGraphics.renderGraphics(this, context); - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } } @@ -763,13 +836,16 @@ * * @return {Rectangle} the rectangular bounding area */ -Graphics.prototype.getBounds = function (matrix) { +Graphics.prototype.getBounds = function (matrix) +{ // return an empty object if the item is a mask! - if (this.isMask) { + if (this.isMask) + { return math.Rectangle.EMPTY; } - if (this.dirty) { + if (this.dirty) + { this.updateLocalBounds(); this.glDirty = true; @@ -841,23 +917,27 @@ * Update the bounds of the object * */ -Graphics.prototype.updateLocalBounds = function () { +Graphics.prototype.updateLocalBounds = function () +{ var minX = Infinity; var maxX = -Infinity; var minY = Infinity; var maxY = -Infinity; - if (this.graphicsData.length) { + if (this.graphicsData.length) + { var shape, points, x, y, w, h; - for (var i = 0; i < this.graphicsData.length; i++) { + for (var i = 0; i < this.graphicsData.length; i++) + { var data = this.graphicsData[i]; var type = data.type; var lineWidth = data.lineWidth; shape = data.shape; - if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) { + if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) + { x = shape.x - lineWidth/2; y = shape.y - lineWidth/2; w = shape.width + lineWidth; @@ -869,7 +949,8 @@ minY = y < minY ? y : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.CIRC) { + else if (type === CONST.SHAPES.CIRC) + { x = shape.x; y = shape.y; w = shape.radius + lineWidth/2; @@ -881,7 +962,8 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.ELIP) { + else if (type === CONST.SHAPES.ELIP) + { x = shape.x; y = shape.y; w = shape.width + lineWidth/2; @@ -893,11 +975,13 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else { + else + { // POLY points = shape.points; - for (var j = 0; j < points.length; j += 2) { + for (var j = 0; j < points.length; j += 2) + { x = points[j]; y = points[j+1]; @@ -910,7 +994,8 @@ } } } - else { + else + { minX = 0; maxX = 0; minY = 0; @@ -931,10 +1016,12 @@ * * @private */ -Graphics.prototype._generateCachedSprite = function () { +Graphics.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { var canvasBuffer = new CanvasBuffer(bounds.width, bounds.height); var texture = Texture.fromCanvas(canvasBuffer.canvas); @@ -943,7 +1030,8 @@ this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.buffer.resize(bounds.width, bounds.height); } @@ -968,7 +1056,8 @@ * * @private */ -Graphics.prototype.updateCachedSpriteTexture = function () { +Graphics.prototype.updateCachedSpriteTexture = function () +{ var cachedSprite = this._cachedSprite; var texture = cachedSprite.texture; var canvas = cachedSprite.buffer.canvas; @@ -989,7 +1078,8 @@ * Destroys a previous cached sprite. * */ -Graphics.prototype.destroyCachedSprite = function () { +Graphics.prototype.destroyCachedSprite = function () +{ this._cachedSprite.texture.destroy(true); // let the gc collect the unused sprite @@ -1003,10 +1093,13 @@ * @param {Circle|Rectangle|Ellipse|Line|Polygon} shape The Shape object to draw. * @return {GraphicsData} The generated GraphicsData object. */ -Graphics.prototype.drawShape = function (shape) { - if (this.currentPath) { +Graphics.prototype.drawShape = function (shape) +{ + if (this.currentPath) + { // check current path! - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath.shape.points.length <= 2) + { this.graphicsData.pop(); } } @@ -1017,7 +1110,8 @@ this.graphicsData.push(data); - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { data.shape.closed = this.filling; this.currentPath = data; } diff --git a/src/core/primitives/GraphicsData.js b/src/core/primitives/GraphicsData.js index 99decbe..788f6f2 100644 --- a/src/core/primitives/GraphicsData.js +++ b/src/core/primitives/GraphicsData.js @@ -4,7 +4,8 @@ * @class * @namespace PIXI */ -function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) { +function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) +{ this.lineWidth = lineWidth; this.lineColor = lineColor; this.lineAlpha = lineAlpha; @@ -27,7 +28,8 @@ * * @return {GraphicsData} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ return new GraphicsData( this.lineWidth, this.lineColor, diff --git a/src/core/renderers/canvas/CanvasRenderer.js b/src/core/renderers/canvas/CanvasRenderer.js index 15a0978..7aebd44 100644 --- a/src/core/renderers/canvas/CanvasRenderer.js +++ b/src/core/renderers/canvas/CanvasRenderer.js @@ -17,17 +17,22 @@ * @param [options.resolution=1] {number} the resolution of the renderer retina would be 2 * @param [options.clearBeforeRender=true] {boolean} This sets if the CanvasRenderer will clear the canvas or not before the new render pass. */ -function CanvasRenderer(width, height, options) { +function CanvasRenderer(width, height, options) +{ utils.sayHello('Canvas'); - if (options) { - for (var i in CONST.defaultRenderOptions) { - if (typeof options[i] === 'undefined') { + if (options) + { + for (var i in CONST.defaultRenderOptions) + { + if (typeof options[i] === 'undefined') + { options[i] = CONST.defaultRenderOptions[i]; } } } - else { + else + { options = CONST.defaultRenderOptions; } @@ -156,19 +161,24 @@ this.smoothProperty = null; - if (this.context.imageSmoothingEnabled) { + if (this.context.imageSmoothingEnabled) + { this.smoothProperty = 'imageSmoothingEnabled'; } - else if (this.context.webkitImageSmoothingEnabled) { + else if (this.context.webkitImageSmoothingEnabled) + { this.smoothProperty = 'webkitImageSmoothingEnabled'; } - else if (this.context.mozImageSmoothingEnabled) { + else if (this.context.mozImageSmoothingEnabled) + { this.smoothProperty = 'mozImageSmoothingEnabled'; } - else if (this.context.oImageSmoothingEnabled) { + else if (this.context.oImageSmoothingEnabled) + { this.smoothProperty = 'oImageSmoothingEnabled'; } - else if (this.context.msImageSmoothingEnabled) { + else if (this.context.msImageSmoothingEnabled) + { this.smoothProperty = 'msImageSmoothingEnabled'; } @@ -193,10 +203,12 @@ * @memberof CanvasRenderer# */ backgroundColor: { - get: function () { + get: function () + { return this._backgroundColor; }, - set: function (val) { + set: function (val) + { this._backgroundColor = val; this._backgroundColorString = utils.hex2string(val); } @@ -208,7 +220,8 @@ * * @param object {DisplayObject} the object to be rendered */ -CanvasRenderer.prototype.render = function (object) { +CanvasRenderer.prototype.render = function (object) +{ object.updateTransform(); this.context.setTransform(1,0,0,1,0,0); @@ -218,16 +231,20 @@ this.currentBlendMode = CONST.blendModes.NORMAL; this.context.globalCompositeOperation = this.blendModes[CONST.blendModes.NORMAL]; - if (navigator.isCocoonJS && this.view.screencanvas) { + if (navigator.isCocoonJS && this.view.screencanvas) + { this.context.fillStyle = 'black'; this.context.clear(); } - if (this.clearBeforeRender) { - if (this.transparent) { + if (this.clearBeforeRender) + { + if (this.transparent) + { this.context.clearRect(0, 0, this.width, this.height); } - else { + else + { this.context.fillStyle = this._backgroundColorString; this.context.fillRect(0, 0, this.width , this.height); } @@ -241,8 +258,10 @@ * * @param [removeView=false] {boolean} Removes the Canvas element from the DOM. */ -CanvasRenderer.prototype.destroy = function (removeView) { - if (removeView && this.view.parent) { +CanvasRenderer.prototype.destroy = function (removeView) +{ + if (removeView && this.view.parent) + { this.view.parent.removeChild(this.view); } @@ -257,14 +276,16 @@ * @param width {number} the new width of the canvas view * @param height {number} the new height of the canvas view */ -CanvasRenderer.prototype.resize = function (width, height) { +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) { + if (this.autoResize) + { this.view.style.width = this.width / this.resolution + 'px'; this.view.style.height = this.height / this.resolution + 'px'; } @@ -276,7 +297,8 @@ * @param displayObject {DisplayObject} The displayObject to render * @private */ -CanvasRenderer.prototype.renderDisplayObject = function (displayObject) { +CanvasRenderer.prototype.renderDisplayObject = function (displayObject) +{ displayObject.renderCanvas(this); }; @@ -285,11 +307,14 @@ * * @private */ -CanvasRenderer.prototype._mapBlendModes = function () { - if (!this.blendModes) { +CanvasRenderer.prototype._mapBlendModes = function () +{ + if (!this.blendModes) + { this.blendModes = {}; - if (utils.canUseNewCanvasBlendModes()) { + if (utils.canUseNewCanvasBlendModes()) + { this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? this.blendModes[CONST.blendModes.MULTIPLY] = 'multiply'; @@ -308,7 +333,8 @@ this.blendModes[CONST.blendModes.COLOR] = 'color'; this.blendModes[CONST.blendModes.LUMINOSITY] = 'luminosity'; } - else { + else + { // this means that the browser does not support the cool new blend modes in canvas 'cough' ie 'cough' this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? diff --git a/src/core/renderers/canvas/utils/CanvasBuffer.js b/src/core/renderers/canvas/utils/CanvasBuffer.js index ebe5d47..b183a66 100644 --- a/src/core/renderers/canvas/utils/CanvasBuffer.js +++ b/src/core/renderers/canvas/utils/CanvasBuffer.js @@ -6,7 +6,8 @@ * @param width {number} the width for the newly created canvas * @param height {number} the height for the newly created canvas */ -function CanvasBuffer(width, height) { +function CanvasBuffer(width, height) +{ /** * The Canvas object that belongs to this CanvasBuffer. * @@ -36,10 +37,12 @@ * @memberof CanvasBuffer# */ width: { - get: function () { + get: function () + { return this.canvas.width; }, - set: function (val) { + set: function (val) + { this.canvas.width = val; } }, @@ -50,10 +53,12 @@ * @memberof CanvasBuffer# */ height: { - get: function () { + get: function () + { return this.canvas.height; }, - set: function (val) { + set: function (val) + { this.canvas.height = val; } } @@ -64,7 +69,8 @@ * * @private */ -CanvasBuffer.prototype.clear = function () { +CanvasBuffer.prototype.clear = function () +{ this.context.setTransform(1, 0, 0, 1, 0, 0); this.context.clearRect(0,0, this.canvas.width, this.canvas.height); }; @@ -75,7 +81,8 @@ * @param width {number} the new width of the canvas * @param height {number} the new height of the canvas */ -CanvasBuffer.prototype.resize = function (width, height) { +CanvasBuffer.prototype.resize = function (width, height) +{ this.canvas.width = width; this.canvas.height = height; }; diff --git a/src/core/renderers/canvas/utils/CanvasGraphics.js b/src/core/renderers/canvas/utils/CanvasGraphics.js index c7eaa2a..3f2a91f 100644 --- a/src/core/renderers/canvas/utils/CanvasGraphics.js +++ b/src/core/renderers/canvas/utils/CanvasGraphics.js @@ -13,15 +13,18 @@ * @param graphics {Graphics} the actual graphics object to render * @param context {CanvasRenderingContext2D} the 2d drawing method of the canvas */ -CanvasGraphics.renderGraphics = function (graphics, context) { +CanvasGraphics.renderGraphics = function (graphics, context) +{ var worldAlpha = graphics.worldAlpha; - if (graphics.dirty) { + if (graphics.dirty) + { this.updateGraphicsTint(graphics); graphics.dirty = false; } - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; @@ -30,69 +33,82 @@ context.lineWidth = data.lineWidth; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { context.beginPath(); var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } - if (shape.closed) { + if (shape.closed) + { context.lineTo(points[0], points[1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fillRect(shape.x, shape.y, shape.width, shape.height); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.strokeRect(shape.x, shape.y, shape.width, shape.height); } } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.beginPath(); context.arc(shape.x, shape.y, shape.radius,0,2*Math.PI); context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas var w = shape.width * 2; @@ -119,18 +135,21 @@ context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; var width = shape.width; @@ -152,13 +171,15 @@ context.quadraticCurveTo(rx, ry, rx, ry + radius); context.closePath(); - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); @@ -174,45 +195,54 @@ * @param graphics {Graphics} the graphics which will be used as a mask * @param context {CanvasRenderingContext2D} the context 2d method of the canvas */ -CanvasGraphics.renderGraphicsMask = function (graphics, context) { +CanvasGraphics.renderGraphicsMask = function (graphics, context) +{ var len = graphics.graphicsData.length; - if (len === 0) { + if (len === 0) + { return; } context.beginPath(); - for (var i = 0; i < len; i++) { + for (var i = 0; i < len; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { context.rect(shape.x, shape.y, shape.width, shape.height); context.closePath(); } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.arc(shape.x, shape.y, shape.radius, 0, 2 * Math.PI); context.closePath(); } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas @@ -237,7 +267,8 @@ context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); context.closePath(); } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; @@ -262,8 +293,10 @@ } }; -CanvasGraphics.updateGraphicsTint = function (graphics) { - if (graphics.tint === 0xFFFFFF) { +CanvasGraphics.updateGraphicsTint = function (graphics) +{ + if (graphics.tint === 0xFFFFFF) + { return; } @@ -271,7 +304,8 @@ var tintG = (graphics.tint >> 8 & 0xFF) / 255; var tintB = (graphics.tint & 0xFF)/ 255; - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var fillColor = data.fillColor | 0; diff --git a/src/core/renderers/canvas/utils/CanvasMaskManager.js b/src/core/renderers/canvas/utils/CanvasMaskManager.js index e04a733..9827d36 100644 --- a/src/core/renderers/canvas/utils/CanvasMaskManager.js +++ b/src/core/renderers/canvas/utils/CanvasMaskManager.js @@ -6,7 +6,8 @@ * @class * @namespace PIXI */ -function CanvasMaskManager() {} +function CanvasMaskManager() +{} CanvasMaskManager.prototype.constructor = CanvasMaskManager; module.exports = CanvasMaskManager; @@ -17,7 +18,8 @@ * @param maskData {object} the maskData that will be pushed * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.pushMask = function (maskData, renderer) { +CanvasMaskManager.prototype.pushMask = function (maskData, renderer) +{ renderer.context.save(); var cacheAlpha = maskData.alpha; @@ -45,6 +47,7 @@ * * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.popMask = function (renderer) { +CanvasMaskManager.prototype.popMask = function (renderer) +{ renderer.context.restore(); }; diff --git a/src/core/renderers/canvas/utils/CanvasTinter.js b/src/core/renderers/canvas/utils/CanvasTinter.js index 17e0529..d2fb1bc 100644 --- a/src/core/renderers/canvas/utils/CanvasTinter.js +++ b/src/core/renderers/canvas/utils/CanvasTinter.js @@ -14,7 +14,8 @@ * @param color {number} the color to use to tint the sprite with * @return {HTMLCanvasElement} The tinted canvas */ -CanvasTinter.getTintedTexture = function (sprite, color) { +CanvasTinter.getTintedTexture = function (sprite, color) +{ var texture = sprite.texture; color = CanvasTinter.roundColor(color); @@ -23,7 +24,8 @@ texture.tintCache = texture.tintCache || {}; - if (texture.tintCache[stringColor]) { + if (texture.tintCache[stringColor]) + { return texture.tintCache[stringColor]; } @@ -33,14 +35,16 @@ //CanvasTinter.tintWithPerPixel(texture, stringColor, canvas); CanvasTinter.tintMethod(texture, color, canvas); - if (CanvasTinter.convertTintToImage) { + if (CanvasTinter.convertTintToImage) + { // is this better? var tintImage = new Image(); tintImage.src = canvas.toDataURL(); texture.tintCache[stringColor] = tintImage; } - else { + else + { texture.tintCache[stringColor] = canvas; // if we are not converting the texture to an image then we need to lose the reference to the canvas CanvasTinter.canvas = null; @@ -56,7 +60,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithMultiply = function (texture, color, canvas) { +CanvasTinter.tintWithMultiply = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -104,7 +109,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithOverlay = function (texture, color, canvas) { +CanvasTinter.tintWithOverlay = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -139,7 +145,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithPerPixel = function (texture, color, canvas) { +CanvasTinter.tintWithPerPixel = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -167,7 +174,8 @@ var pixels = pixelData.data; - for (var i = 0; i < pixels.length; i += 4) { + for (var i = 0; i < pixels.length; i += 4) + { pixels[i+0] *= r; pixels[i+1] *= g; pixels[i+2] *= b; @@ -181,7 +189,8 @@ * * @param color {number} the color to round, should be a hex color */ -CanvasTinter.roundColor = function (color) { +CanvasTinter.roundColor = function (color) +{ var step = CanvasTinter.cacheStepsPerColorChannel; var rgbValues = utils.hex2rgb(color); diff --git a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js index 9f2f89a..35edbaf 100644 --- a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js +++ b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLBlendModeManager(renderer) { +function WebGLBlendModeManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -23,8 +24,10 @@ * * @param blendMode {number} the blendMode, should be a Pixi const, such as BlendModes.ADD */ -WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) { - if (this.currentBlendMode === blendMode) { +WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) +{ + if (this.currentBlendMode === blendMode) + { return false; } diff --git a/src/core/renderers/webgl/managers/WebGLFilterManager.js b/src/core/renderers/webgl/managers/WebGLFilterManager.js index 1179258..2dac048 100644 --- a/src/core/renderers/webgl/managers/WebGLFilterManager.js +++ b/src/core/renderers/webgl/managers/WebGLFilterManager.js @@ -7,7 +7,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLFilterManager(renderer) { +function WebGLFilterManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -32,7 +33,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.texturePool.length = 0; self.initShaderBuffers(); }); @@ -46,7 +48,8 @@ * @param renderer {WebGLRenderer} * @param buffer {ArrayBuffer} */ -WebGLFilterManager.prototype.begin = function (buffer) { +WebGLFilterManager.prototype.begin = function (buffer) +{ this.defaultShader = this.renderer.shaderManager.defaultShader; this.width = this.renderer.projection.x * 2; @@ -60,7 +63,8 @@ * * @param filterBlock {object} the filter that will be pushed to the current filter stack */ -WebGLFilterManager.prototype.pushFilter = function (filterBlock) { +WebGLFilterManager.prototype.pushFilter = function (filterBlock) +{ var gl = this.renderer.gl; var projection = this.renderer.projection; @@ -78,10 +82,12 @@ this.offsetY += filterBlock._filterArea.y; var texture = this.texturePool.pop(); - if (!texture) { + if (!texture) + { texture = new FilterTexture(this.renderer.gl, this.width, this.height); } - else { + else + { texture.resize(this.width, this.height); } @@ -98,29 +104,35 @@ var localX = filterArea.x, localY = filterArea.y; - if (filterArea.x < 0) { + if (filterArea.x < 0) + { filterArea.width += filterArea.x; filterArea.x = 0; } - if (filterArea.y < 0) { + if (filterArea.y < 0) + { filterArea.height += filterArea.y; filterArea.y = 0; } - if (localX + filterArea.width > this.width) { + if (localX + filterArea.width > this.width) + { filterArea.width = this.width - localX; } - if (localY + filterArea.height > this.height) { + if (localY + filterArea.height > this.height) + { filterArea.height = this.height - localY; } - if (filterArea.width < 0) { + if (filterArea.width < 0) + { filterArea.width = 0; } - if (filterArea.height < 0) { + if (filterArea.height < 0) + { filterArea.height = 0; } @@ -154,7 +166,8 @@ * Removes the last filter from the filter stack and doesn't return it. * */ -WebGLFilterManager.prototype.popFilter = function () { +WebGLFilterManager.prototype.popFilter = function () +{ var gl = this.renderer.gl; var filterBlock = this.filterStack.pop(); @@ -163,7 +176,8 @@ var projection = this.renderer.projection; var offset = this.renderer.offset; - if (filterBlock.filterPasses.length > 1) { + if (filterBlock.filterPasses.length > 1) + { gl.viewport(0, 0, filterArea.width, filterArea.height); gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); @@ -193,7 +207,8 @@ var inputTexture = texture; var outputTexture = this.texturePool.pop(); - if (!outputTexture) { + if (!outputTexture) + { outputTexture = new FilterTexture(this.renderer.gl, this.width, this.height); } outputTexture.resize(this.width, this.height); @@ -204,7 +219,8 @@ gl.disable(gl.BLEND); - for (var i = 0; i < filterBlock.filterPasses.length-1; i++) { + for (var i = 0; i < filterBlock.filterPasses.length-1; i++) + { var filterPass = filterBlock.filterPasses[i]; gl.bindFramebuffer(gl.FRAMEBUFFER, outputTexture.frameBuffer ); @@ -243,10 +259,12 @@ var buffer = this.buffer; // time to render the filters texture to the previous scene - if (this.filterStack.length === 0) { + if (this.filterStack.length === 0) + { gl.colorMask(true, true, true, true);//this.transparent); } - else { + else + { var currentFilter = this.filterStack[this.filterStack.length-1]; filterArea = currentFilter._filterArea; @@ -332,13 +350,15 @@ * @param width {number} the horizontal range of the filter * @param height {number} the vertical range of the filter */ -WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) { +WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) +{ // use program var gl = this.renderer.gl; var shader = filter.shaders[gl.id]; - if (!shader) { + if (!shader) + { shader = new Shader(gl); shader.fragmentSrc = filter.fragmentSrc; @@ -356,7 +376,8 @@ gl.uniform2f(shader.projectionVector, width/2, -height/2); gl.uniform2f(shader.offsetVector, 0,0); - if (filter.uniforms.dimensions) { + 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]; @@ -386,7 +407,8 @@ * Initialises the shader buffers. * */ -WebGLFilterManager.prototype.initShaderBuffers = function () { +WebGLFilterManager.prototype.initShaderBuffers = function () +{ var gl = this.renderer.gl; // create some buffers @@ -432,7 +454,8 @@ * Destroys the filter and removes it from the filter stack. * */ -WebGLFilterManager.prototype.destroy = function () { +WebGLFilterManager.prototype.destroy = function () +{ var gl = this.renderer.gl; this.filterStack = null; @@ -441,7 +464,8 @@ this.offsetY = 0; // destroy textures - for (var i = 0; i < this.texturePool.length; i++) { + for (var i = 0; i < this.texturePool.length; i++) + { this.texturePool[i].destroy(); } diff --git a/src/core/renderers/webgl/managers/WebGLManager.js b/src/core/renderers/webgl/managers/WebGLManager.js index 9d47b5c..c30cd51 100644 --- a/src/core/renderers/webgl/managers/WebGLManager.js +++ b/src/core/renderers/webgl/managers/WebGLManager.js @@ -3,7 +3,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLManager(renderer) { +function WebGLManager(renderer) +{ /** * The renderer this manager works for. * @@ -15,6 +16,7 @@ WebGLManager.prototype.constructor = WebGLManager; module.exports = WebGLManager; -WebGLManager.prototype.destroy = function () { +WebGLManager.prototype.destroy = function () +{ this.renderer = null; }; diff --git a/src/core/renderers/webgl/managers/WebGLMaskManager.js b/src/core/renderers/webgl/managers/WebGLMaskManager.js index 2f90b64..e568812 100644 --- a/src/core/renderers/webgl/managers/WebGLMaskManager.js +++ b/src/core/renderers/webgl/managers/WebGLMaskManager.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLMaskManager(renderer) { +function WebGLMaskManager(renderer) +{ WebGLManager.call(this, renderer); } @@ -19,12 +20,15 @@ * * @param maskData {any[]} */ -WebGLMaskManager.prototype.pushMask = function (maskData) { - if (maskData.dirty) { +WebGLMaskManager.prototype.pushMask = function (maskData) +{ + if (maskData.dirty) + { WebGLGraphics.updateGraphics(maskData, this.renderer.gl); } - if (!maskData._webGL[this.renderer.gl.id].data.length) { + if (!maskData._webGL[this.renderer.gl.id].data.length) + { return; } @@ -36,6 +40,7 @@ * * @param maskData {any[]} */ -WebGLMaskManager.prototype.popMask = function (maskData) { +WebGLMaskManager.prototype.popMask = function (maskData) +{ this.renderer.stencilManager.popStencil(maskData, maskData._webGL[this.renderer.gl.id].data[0], this.renderer); }; diff --git a/src/core/renderers/webgl/managers/WebGLShaderManager.js b/src/core/renderers/webgl/managers/WebGLShaderManager.js index fef071c..90c6477 100644 --- a/src/core/renderers/webgl/managers/WebGLShaderManager.js +++ b/src/core/renderers/webgl/managers/WebGLShaderManager.js @@ -10,7 +10,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLShaderManager(renderer) { +function WebGLShaderManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -28,7 +29,8 @@ */ this.tempAttribState = []; - for (var i = 0; i < this.maxAttibs; i++) { + for (var i = 0; i < this.maxAttibs; i++) + { this.attribState[i] = false; } @@ -66,7 +68,8 @@ // listen for context and update necessary shaders var self = this; - this.renderer.on('context', function (event) { + this.renderer.on('context', function (event) + { var gl = event.data; // this shader is used for rendering primitives @@ -97,29 +100,36 @@ * * @param attribs {Array} attribs */ -WebGLShaderManager.prototype.setAttribs = function (attribs) { +WebGLShaderManager.prototype.setAttribs = function (attribs) +{ // reset temp state var i; - for (i = 0; i < this.tempAttribState.length; i++) { + for (i = 0; i < this.tempAttribState.length; i++) + { this.tempAttribState[i] = false; } // set the new attribs - for (var a in attribs) { + for (var a in attribs) + { this.tempAttribState[attribs[a]] = true; } var gl = this.renderer.gl; - for (i = 0; i < this.attribState.length; i++) { - if (this.attribState[i] !== this.tempAttribState[i]) { + for (i = 0; i < this.attribState.length; i++) + { + if (this.attribState[i] !== this.tempAttribState[i]) + { this.attribState[i] = this.tempAttribState[i]; - if (this.attribState[i]) { + if (this.attribState[i]) + { gl.enableVertexAttribArray(i); } - else { + else + { gl.disableVertexAttribArray(i); } } @@ -131,8 +141,10 @@ * * @param shader {Any} */ -WebGLShaderManager.prototype.setShader = function (shader) { - if (this._currentId === shader.uuid) { +WebGLShaderManager.prototype.setShader = function (shader) +{ + if (this._currentId === shader.uuid) + { return false; } @@ -150,7 +162,8 @@ * Destroys this object. * */ -WebGLShaderManager.prototype.destroy = function () { +WebGLShaderManager.prototype.destroy = function () +{ this.attribState = null; this.tempAttribState = null; diff --git a/src/core/renderers/webgl/managers/WebGLStencilManager.js b/src/core/renderers/webgl/managers/WebGLStencilManager.js index 9ec6398..4cb0134 100644 --- a/src/core/renderers/webgl/managers/WebGLStencilManager.js +++ b/src/core/renderers/webgl/managers/WebGLStencilManager.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLStencilManager(renderer) { +function WebGLStencilManager(renderer) +{ WebGLManager.call(this, renderer); this.stencilStack = []; @@ -24,12 +25,14 @@ * @param graphics {Graphics} * @param webGLData {any[]} */ -WebGLStencilManager.prototype.pushStencil = function (graphics, webGLData) { +WebGLStencilManager.prototype.pushStencil = function (graphics, webGLData) +{ var gl = this.renderer.gl; this.bindGraphics(graphics, webGLData, this.renderer); - if (this.stencilStack.length === 0) { + if (this.stencilStack.length === 0) + { gl.enable(gl.STENCIL_TEST); gl.clear(gl.STENCIL_BUFFER_BIT); this.reverse = true; @@ -47,14 +50,17 @@ // draw the triangle strip! - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } @@ -62,31 +68,38 @@ // draw a quad to increment.. gl.drawElements(gl.TRIANGLE_FAN, 4, gl.UNSIGNED_SHORT, ( webGLData.indices.length - 4 ) * 2 ); - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); } this.reverse = !this.reverse; } - else { - if (!this.reverse) { + else + { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } - else { + 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) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); } } @@ -103,7 +116,8 @@ * @param graphics {Graphics} * @param webGLData {Array} */ -WebGLStencilManager.prototype.bindGraphics = function (graphics, webGLData) { +WebGLStencilManager.prototype.bindGraphics = function (graphics, webGLData) +{ //if (this._currentGraphics === graphics)return; this._currentGraphics = graphics; @@ -114,7 +128,8 @@ offset = this.renderer.offset, shader;// = this.renderer.shaderManager.primitiveShader; - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { shader = this.renderer.shaderManager.complexPrimitiveShader; this.renderer.shaderManager.setShader(shader); @@ -141,7 +156,8 @@ // set the index buffer! gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, webGLData.indexBuffer); } - else { + else + { //this.renderer.shaderManager.activatePrimitiveShader(); shader = this.renderer.shaderManager.primitiveShader; this.renderer.shaderManager.setShader( shader ); @@ -154,7 +170,7 @@ gl.uniform2f(shader.uniforms.offsetVector._location, -offset.x, -offset.y); gl.uniform3fv(shader.uniforms.tint._location, utils.hex2rgb(graphics.tint)); - + gl.uniform1f(shader.uniforms.alpha._location, graphics.worldAlpha); @@ -172,19 +188,22 @@ * @param graphics {Graphics} * @param webGLData {Array} */ -WebGLStencilManager.prototype.popStencil = function (graphics, webGLData) { +WebGLStencilManager.prototype.popStencil = function (graphics, webGLData) +{ var gl = this.renderer.gl; this.stencilStack.pop(); this.count--; - if (this.stencilStack.length === 0) { + if (this.stencilStack.length === 0) + { // the stack is empty! gl.disable(gl.STENCIL_TEST); } - else { + else + { var level = this.count; @@ -192,14 +211,17 @@ gl.colorMask(false, false, false, false); - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { this.reverse = !this.reverse; - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } @@ -213,31 +235,38 @@ // draw the triangle strip! gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); - if (!this.reverse) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); } } - else { + else + { // console.log("<<>>") - if (!this.reverse) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } - else { + 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) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); } } @@ -253,7 +282,8 @@ * Destroys the mask stack. * */ -WebGLStencilManager.prototype.destroy = function () { +WebGLStencilManager.prototype.destroy = function () +{ this.renderer = null; this.stencilStack = null; }; diff --git a/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js b/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js index 913ba5e..1ea7d19 100644 --- a/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js +++ b/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function ComplexPrimitiveShader(gl) { +function ComplexPrimitiveShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -24,7 +25,8 @@ 'uniform float flipY;', 'varying vec4 vColor;', - 'void main(void) {', + '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);', @@ -37,7 +39,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = vColor;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/FastShader.js b/src/core/renderers/webgl/shaders/FastShader.js index bd2e29a..2e5e060 100644 --- a/src/core/renderers/webgl/shaders/FastShader.js +++ b/src/core/renderers/webgl/shaders/FastShader.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function FastShader(gl) { +function FastShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -28,7 +29,8 @@ 'const vec2 center = vec2(-1.0, 1.0);', - 'void main(void) {', + 'void main(void) + {', ' vec2 v;', ' vec2 sv = aVertexPosition * aScale;', ' v.x = (sv.x) * cos(aRotation) - (sv.y) * sin(aRotation);', @@ -49,7 +51,8 @@ 'uniform sampler2D uSampler;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/PrimitiveShader.js b/src/core/renderers/webgl/shaders/PrimitiveShader.js index 6f25409..a25f54f 100644 --- a/src/core/renderers/webgl/shaders/PrimitiveShader.js +++ b/src/core/renderers/webgl/shaders/PrimitiveShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function PrimitiveShader(gl) { +function PrimitiveShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -23,7 +24,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + '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);', @@ -36,7 +38,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = vColor;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/Shader.js b/src/core/renderers/webgl/shaders/Shader.js index f8964f5..fd75ef5 100644 --- a/src/core/renderers/webgl/shaders/Shader.js +++ b/src/core/renderers/webgl/shaders/Shader.js @@ -6,7 +6,8 @@ * @param [fragmentSrc] {string} The source of the fragment shader. * @param [vertexSrc] {string} The source of the vertex shader. */ -function Shader(gl, vertexSrc, fragmentSrc, customUniforms, customAttributes) { +function Shader(gl, vertexSrc, fragmentSrc, customUniforms, customAttributes) +{ /** * @member {number} * @readonly @@ -33,7 +34,8 @@ dimensions: { type: '4f', value: new Float32Array(4) } }; - for (var u in customUniforms) { + for (var u in customUniforms) + { this.uniforms[u] = customUniforms[u]; } @@ -43,7 +45,8 @@ aColor: 0 }; - for (var a in customAttributes) { + for (var a in customAttributes) + { this.attributes[a] = customAttributes[a]; } @@ -66,7 +69,8 @@ 'const vec2 center = vec2(-1.0, 1.0);', - 'void main(void) {', + 'void main(void) + {', ' gl_Position = vec4( ((aVertexPosition + offsetVector) / projectionVector) + center , 0.0, 1.0);', ' vTextureCoord = aTextureCoord;', ' vColor = vec4(aColor.rgb * aColor.a, aColor.a);', @@ -85,7 +89,8 @@ 'uniform sampler2D uSampler;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;', '}' ].join('\n'); @@ -96,7 +101,8 @@ Shader.prototype.constructor = Shader; module.exports = Shader; -Shader.prototype.init = function () { +Shader.prototype.init = function () +{ this.compile(); this.gl.useProgram(this.program); @@ -105,14 +111,18 @@ this.cacheAttributeLocations(Object.keys(this.attributes)); }; -Shader.prototype.cacheUniformLocations = function (keys) { - for (var i = 0; i < keys.length; ++i) { +Shader.prototype.cacheUniformLocations = function (keys) +{ + for (var i = 0; i < keys.length; ++i) + { this.uniforms[keys[i]]._location = this.gl.getUniformLocation(this.program, keys[i]); } }; -Shader.prototype.cacheAttributeLocations = function (keys) { - for (var i = 0; i < keys.length; ++i) { +Shader.prototype.cacheAttributeLocations = function (keys) +{ + for (var i = 0; i < keys.length; ++i) + { this.attributes[keys[i]] = this.gl.getAttribLocation(this.program, keys[i]); } @@ -124,14 +134,16 @@ // 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.attributes.aColor === -1) { + // if (this.attributes.aColor === -1) + { // this.attributes.aColor = 2; // } // End worst hack eva // }; -Shader.prototype.compile = function () { +Shader.prototype.compile = function () +{ var gl = this.gl; var glVertShader = this._glCompile(gl.VERTEX_SHADER, this.vertexSrc); @@ -144,13 +156,15 @@ gl.linkProgram(program); // if linking fails, then log and cleanup - if (!gl.getProgramParameter(program, gl.LINK_STATUS)) { + if (!gl.getProgramParameter(program, gl.LINK_STATUS)) + { window.console.error('Pixi.js Error: Could not initialize shader.'); window.console.error('gl.VALIDATE_STATUS', gl.getProgramParameter(program, gl.VALIDATE_STATUS)); window.console.error('gl.getError()', gl.getError()); // if there is a program info log, log it - if (gl.getProgramInfoLog(program) !== '') { + if (gl.getProgramInfoLog(program) !== '') + { window.console.warn('Pixi.js Warning: gl.getProgramInfoLog()', gl.getProgramInfoLog(program)); } @@ -165,18 +179,21 @@ return (this.program = program); }; -Shader.prototype.syncUniforms = function () { +Shader.prototype.syncUniforms = function () +{ var gl = this.gl; this.textureCount = 1; - for (var key in this.uniforms) { + for (var key in this.uniforms) + { var uniform = this.uniforms[key], location = uniform._location, value = uniform.value, i, il; - switch (uniform.type) { + switch (uniform.type) + { // single int value case 'i': case '1i': @@ -282,7 +299,8 @@ // a Color Value case 'c': - if (typeof value === 'number') { + if (typeof value === 'number') + { value = utils.hex2rgb(value); } @@ -311,11 +329,13 @@ // array of 2D Point objects case 'v2v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(2 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 2] = value[i].x; uniform._array[i * 2 + 1] = value[i].y; } @@ -325,11 +345,13 @@ // array of 3D Point objects case 'v3v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(3 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 3] = value[i].x; uniform._array[i * 3 + 1] = value[i].y; uniform._array[i * 3 + 2] = value[i].z; @@ -341,11 +363,13 @@ // array of 4D Point objects case 'v4v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(4 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 4] = value[i].x; uniform._array[i * 4 + 1] = value[i].y; uniform._array[i * 4 + 2] = value[i].z; @@ -359,7 +383,8 @@ // PIXI.Texture case 't': case 'sampler2D': - if (!uniform.value || !uniform.value.baseTexture || !uniform.value.baseTexture.hasLoaded) { + if (!uniform.value || !uniform.value.baseTexture || !uniform.value.baseTexture.hasLoaded) + { break; } @@ -376,7 +401,8 @@ this.textureCount++; // initialize the texture if we haven't yet - if (!uniform._init) { + if (!uniform._init) + { this.initSampler2D(uniform); uniform._init = true; @@ -394,11 +420,13 @@ * Initialises a Sampler2D uniform (which may only be available later on after initUniforms once the texture has loaded) * */ -Shader.prototype.initSampler2D = function (uniform) { +Shader.prototype.initSampler2D = function (uniform) +{ var gl = this.gl; // Extended texture data - if (uniform.textureData) { + if (uniform.textureData) + { var data = uniform.textureData; // GLTexture = mag linear, min linear_mipmap_linear, wrap repeat + gl.generateMipmap(gl.TEXTURE_2D); @@ -417,14 +445,16 @@ var wrapT = (data.wrapT) ? data.wrapT : gl.CLAMP_TO_EDGE; var format = (data.luminance) ? gl.LUMINANCE : gl.RGBA; - if (data.repeat) { + if (data.repeat) + { wrapS = gl.REPEAT; wrapT = gl.REPEAT; } gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, !!data.flipY); - if (data.width) { + if (data.width) + { var width = (data.width) ? data.width : 512; var height = (data.height) ? data.height : 2; var border = (data.border) ? data.border : 0; @@ -432,7 +462,8 @@ // 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 { + 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); } @@ -448,7 +479,8 @@ * Destroys the shader. * */ -Shader.prototype.destroy = function () { +Shader.prototype.destroy = function () +{ this.gl.deleteProgram(this.program); this.gl = null; @@ -459,13 +491,15 @@ this.fragmentSrc = null; }; -Shader.prototype._glCompile = function (type, src) { +Shader.prototype._glCompile = function (type, src) +{ var shader = this.gl.createShader(type); this.gl.shaderSource(shader, src); this.gl.compileShader(shader); - if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) { + if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) + { window.console.log(this.gl.getShaderInfoLog(shader)); return null; } diff --git a/src/core/renderers/webgl/shaders/StripShader.js b/src/core/renderers/webgl/shaders/StripShader.js index 193f6e1..a7abcc6 100644 --- a/src/core/renderers/webgl/shaders/StripShader.js +++ b/src/core/renderers/webgl/shaders/StripShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function StripShader(gl) { +function StripShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -20,7 +21,8 @@ 'varying vec2 vTextureCoord;', - 'void main(void) {', + '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);', @@ -36,7 +38,8 @@ 'varying vec2 vTextureCoord;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vec2(vTextureCoord.x, vTextureCoord.y)) * alpha;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/utils/FilterTexture.js b/src/core/renderers/webgl/utils/FilterTexture.js index d2c8423..4433d44 100644 --- a/src/core/renderers/webgl/utils/FilterTexture.js +++ b/src/core/renderers/webgl/utils/FilterTexture.js @@ -8,7 +8,8 @@ * @param height {number} the vertical range of the filter * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values */ -function FilterTexture(gl, width, height, scaleMode) { +function FilterTexture(gl, width, height, scaleMode) +{ /** * @member {WebGLContext} */ @@ -59,7 +60,8 @@ * Clears the filter texture. * */ -FilterTexture.prototype.clear = function () { +FilterTexture.prototype.clear = function () +{ var gl = this.gl; gl.clearColor(0,0,0, 0); @@ -72,8 +74,10 @@ * @param width {number} the new width of the texture * @param height {number} the new height of the texture */ -FilterTexture.prototype.resize = function (width, height) { - if (this.width === width && this.height === height) { +FilterTexture.prototype.resize = function (width, height) +{ + if (this.width === width && this.height === height) + { return; } @@ -96,7 +100,8 @@ * Destroys the filter texture. * */ -FilterTexture.prototype.destroy = function () { +FilterTexture.prototype.destroy = function () +{ var gl = this.gl; gl.deleteFramebuffer( this.frameBuffer ); gl.deleteTexture( this.texture ); diff --git a/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js b/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js index c4721e9..a63f4d7 100644 --- a/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js +++ b/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js @@ -14,7 +14,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this sprite batch works for. */ -function WebGLFastSpriteBatch(renderer) { +function WebGLFastSpriteBatch(renderer) +{ /** * The renderer instance this sprite batch operates on. * @@ -91,7 +92,8 @@ */ this.lastIndexCount = 0; - for (var i=0, j=0; i < numIndices; i += 6, j += 4) { + 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; @@ -144,7 +146,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.setupContext(); }); } @@ -157,7 +160,8 @@ * * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLFastSpriteBatch.prototype.setupContext = function () { +WebGLFastSpriteBatch.prototype.setupContext = function () +{ var gl = this.renderer.gl; // create a couple of buffers @@ -177,7 +181,8 @@ /** * @param spriteBatch {SpriteBatch} The SpriteBatch container to prepare for. */ -WebGLFastSpriteBatch.prototype.begin = function (spriteBatch) { +WebGLFastSpriteBatch.prototype.begin = function (spriteBatch) +{ this.shader = this.renderer.shaderManager.fastShader; this.matrix = spriteBatch.worldTransform.toArray(true); @@ -187,33 +192,38 @@ /** */ -WebGLFastSpriteBatch.prototype.end = function () { +WebGLFastSpriteBatch.prototype.end = function () +{ this.flush(); }; /** * @param spriteBatch {SpriteBatch} The SpriteBatch container to render. */ -WebGLFastSpriteBatch.prototype.render = function (spriteBatch) { +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) { + if (!sprite.texture._uvs) + { return; } this.currentBaseTexture = sprite.texture.baseTexture; // check blend mode - if (sprite.blendMode !== this.renderer.blendModeManager.currentBlendMode) { + if (sprite.blendMode !== this.renderer.blendModeManager.currentBlendMode) + { this.flush(); this.renderer.blendModeManager.setBlendMode(sprite.blendMode); } - for (var i=0,j= children.length; i= this.size) { + if (this.currentBatchSize >= this.size) + { this.flush(); } }; @@ -362,29 +379,35 @@ /** * */ -WebGLFastSpriteBatch.prototype.flush = function () { +WebGLFastSpriteBatch.prototype.flush = function () +{ // If the batch is length 0 then return as there is nothing to draw - if (this.currentBatchSize === 0) { + if (this.currentBatchSize === 0) + { return; } var gl = this.renderer.gl; // bind the current texture - if (!this.currentBaseTexture._glTextures[gl.id]) { + if (!this.currentBaseTexture._glTextures[gl.id]) + { this.renderer.updateTexture(this.currentBaseTexture, gl); } //TODO-SHOUD THIS BE ELSE??!?!?! - else { + else + { gl.bindTexture(gl.TEXTURE_2D, this.currentBaseTexture._glTextures[gl.id]); } // upload the verts to the buffer - if (this.currentBatchSize > ( this.size * 0.5 ) ) { + if (this.currentBatchSize > ( this.size * 0.5 ) ) + { gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); } - else { + else + { var view = this.vertices.subarray(0, this.currentBatchSize * this.vertByteSize); gl.bufferSubData(gl.ARRAY_BUFFER, 0, view); @@ -405,14 +428,16 @@ * Ends the batch and flushes * */ -WebGLFastSpriteBatch.prototype.stop = function () { +WebGLFastSpriteBatch.prototype.stop = function () +{ this.flush(); }; /** * */ -WebGLFastSpriteBatch.prototype.start = function () { +WebGLFastSpriteBatch.prototype.start = function () +{ var gl = this.renderer.gl; // bind the main texture diff --git a/src/core/renderers/webgl/utils/WebGLGraphics.js b/src/core/renderers/webgl/utils/WebGLGraphics.js index 55f4911..ab8f46e 100644 --- a/src/core/renderers/webgl/utils/WebGLGraphics.js +++ b/src/core/renderers/webgl/utils/WebGLGraphics.js @@ -19,7 +19,8 @@ * @param graphics {Graphics} * @param renderer {WebGLRenderer} */ -WebGLGraphics.renderGraphics = function (graphics, renderer) {//projection, offset) { +WebGLGraphics.renderGraphics = function (graphics, renderer) {//projection, offset) +{ var gl = renderer.gl; var projection = renderer.projection, @@ -27,7 +28,8 @@ shader = renderer.shaderManager.primitiveShader, webGLData; - if (graphics.dirty) { + if (graphics.dirty) + { WebGLGraphics.updateGraphics(graphics, gl); } @@ -35,8 +37,10 @@ // This could be speeded up for sure! - for (var i = 0; i < webGL.data.length; i++) { - if (webGL.data[i].mode === 1) { + for (var i = 0; i < webGL.data.length; i++) + { + if (webGL.data[i].mode === 1) + { webGLData = webGL.data[i]; renderer.stencilManager.pushStencil(graphics, webGLData, renderer); @@ -46,7 +50,8 @@ renderer.stencilManager.popStencil(graphics, webGLData, renderer); } - else { + else + { webGLData = webGL.data[i]; @@ -84,12 +89,14 @@ * @param graphicsData {Graphics} The graphics object to update * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLGraphics.updateGraphics = function (graphics, gl) { +WebGLGraphics.updateGraphics = function (graphics, gl) +{ // get the contexts graphics object var webGL = graphics._webGL[gl.id]; // if the graphics object does not exist in the webGL context time to create it! - if (!webGL) { + if (!webGL) + { webGL = graphics._webGL[gl.id] = {lastIndex:0, data:[], gl:gl}; } @@ -99,11 +106,13 @@ var i; // if the user cleared the graphics object we will need to clear every object - if (graphics.clearDirty) { + if (graphics.clearDirty) + { graphics.clearDirty = false; // lop through and return all the webGLDatas to the object pool so than can be reused later on - for (i = 0; i < webGL.data.length; i++) { + for (i = 0; i < webGL.data.length; i++) + { var graphicsData = webGL.data[i]; graphicsData.reset(); WebGLGraphics.graphicsDataPool.push( graphicsData ); @@ -119,58 +128,72 @@ // loop through the graphics datas and construct each one.. // if the object is a complex fill then the new stencil buffer technique will be used // other wise graphics objects will be pushed into a batch.. - for (i = webGL.lastIndex; i < graphics.graphicsData.length; i++) { + for (i = webGL.lastIndex; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { // need to add the points the the graphics object.. data.points = data.shape.points.slice(); - if (data.shape.closed) { + if (data.shape.closed) + { // close the poly if the value is true! - if (data.points[0] !== data.points[data.points.length-2] || data.points[1] !== data.points[data.points.length-1]) { + if (data.points[0] !== data.points[data.points.length-2] || data.points[1] !== data.points[data.points.length-1]) + { data.points.push(data.points[0], data.points[1]); } } // MAKE SURE WE HAVE THE CORRECT TYPE.. - if (data.fill) { - if (data.points.length >= 6) { - if (data.points.length < 6 * 2) { + if (data.fill) + { + if (data.points.length >= 6) + { + if (data.points.length < 6 * 2) + { webGLData = WebGLGraphics.switchMode(webGL, 0); var canDrawUsingSimple = WebGLGraphics.buildPoly(data, webGLData); // console.log(canDrawUsingSimple); - if (!canDrawUsingSimple) { + if (!canDrawUsingSimple) + { // console.log("<>>>") webGLData = WebGLGraphics.switchMode(webGL, 1); WebGLGraphics.buildComplexPoly(data, webGLData); } } - else { + else + { webGLData = WebGLGraphics.switchMode(webGL, 1); WebGLGraphics.buildComplexPoly(data, webGLData); } } } - if (data.lineWidth > 0) { + if (data.lineWidth > 0) + { webGLData = WebGLGraphics.switchMode(webGL, 0); WebGLGraphics.buildLine(data, webGLData); } } - else { + else + { webGLData = WebGLGraphics.switchMode(webGL, 0); - if (data.type === CONST.SHAPES.RECT) { + if (data.type === CONST.SHAPES.RECT) + { WebGLGraphics.buildRectangle(data, webGLData); } - else if (data.type === CONST.SHAPES.CIRC || data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.CIRC || data.type === CONST.SHAPES.ELIP) + { WebGLGraphics.buildCircle(data, webGLData); } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { WebGLGraphics.buildRoundedRectangle(data, webGLData); } } @@ -179,10 +202,12 @@ } // upload all the dirty data... - for (i = 0; i < webGL.data.length; i++) { + for (i = 0; i < webGL.data.length; i++) + { webGLData = webGL.data[i]; - if (webGLData.dirty) { + if (webGLData.dirty) + { webGLData.upload(); } } @@ -194,18 +219,22 @@ * @param webGL {WebGLContext} * @param type {number} */ -WebGLGraphics.switchMode = function (webGL, type) { +WebGLGraphics.switchMode = function (webGL, type) +{ var webGLData; - if (!webGL.data.length) { + if (!webGL.data.length) + { webGLData = WebGLGraphics.graphicsDataPool.pop() || new WebGLGraphicsData(webGL.gl); webGLData.mode = type; webGL.data.push(webGLData); } - else { + else + { webGLData = webGL.data[webGL.data.length-1]; - if (webGLData.mode !== type || type === 1) { + if (webGLData.mode !== type || type === 1) + { webGLData = WebGLGraphics.graphicsDataPool.pop() || new WebGLGraphicsData(webGL.gl); webGLData.mode = type; webGL.data.push(webGLData); @@ -225,7 +254,8 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildRectangle = function (graphicsData, webGLData) { +WebGLGraphics.buildRectangle = function (graphicsData, webGLData) +{ // --- // // need to convert points to a nice regular data // @@ -235,7 +265,8 @@ var width = rectData.width; var height = rectData.height; - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -265,7 +296,8 @@ indices.push(vertPos, vertPos, vertPos+1, vertPos+2, vertPos+3, vertPos+3); } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = [x, y, @@ -289,7 +321,8 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildRoundedRectangle = function (graphicsData, webGLData) { +WebGLGraphics.buildRoundedRectangle = function (graphicsData, webGLData) +{ var rrectData = graphicsData.shape; var x = rrectData.x; var y = rrectData.y; @@ -305,7 +338,8 @@ recPoints = recPoints.concat(WebGLGraphics.quadraticBezierCurve(x + width, y + radius, x + width, y, x + width - radius, y)); recPoints = recPoints.concat(WebGLGraphics.quadraticBezierCurve(x + radius, y, x, y, x, y + radius)); - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -323,7 +357,8 @@ // var i = 0; - for (i = 0; i < triangles.length; i+=3) { + for (i = 0; i < triangles.length; i+=3) + { indices.push(triangles[i] + vecPos); indices.push(triangles[i] + vecPos); indices.push(triangles[i+1] + vecPos); @@ -332,12 +367,14 @@ } - for (i = 0; i < recPoints.length; i++) { + for (i = 0; i < recPoints.length; i++) + { verts.push(recPoints[i], recPoints[++i], r, g, b, alpha); } } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = recPoints; @@ -362,7 +399,8 @@ * @param toY {number} Destination point y * @return {number[]} */ -WebGLGraphics.quadraticBezierCurve = function (fromX, fromY, cpX, cpY, toX, toY) { +WebGLGraphics.quadraticBezierCurve = function (fromX, fromY, cpX, cpY, toX, toY) +{ var xa, ya, @@ -373,14 +411,16 @@ n = 20, points = []; - function getPt(n1 , n2, perc) { + function getPt(n1 , n2, perc) + { var diff = n2 - n1; return n1 + ( diff * perc ); } var j = 0; - for (var i = 0; i <= n; i++ ) { + for (var i = 0; i <= n; i++ ) + { j = i / n; // The Green Line @@ -406,7 +446,8 @@ * @param graphicsData {Graphics} The graphics object to draw * @param webGLData {object} */ -WebGLGraphics.buildCircle = function (graphicsData, webGLData) { +WebGLGraphics.buildCircle = function (graphicsData, webGLData) +{ // need to convert points to a nice regular data var circleData = graphicsData.shape; var x = circleData.x; @@ -415,11 +456,13 @@ var height; // TODO - bit hacky?? - if (graphicsData.type === CONST.SHAPES.CIRC) { + if (graphicsData.type === CONST.SHAPES.CIRC) + { width = circleData.radius; height = circleData.radius; } - else { + else + { width = circleData.width; height = circleData.height; } @@ -429,7 +472,8 @@ var i = 0; - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -444,7 +488,8 @@ indices.push(vecPos); - for (i = 0; i < totalSegs + 1 ; i++) { + for (i = 0; i < totalSegs + 1 ; i++) + { verts.push(x,y, r, g, b, alpha); verts.push(x + Math.sin(seg * i) * width, @@ -457,12 +502,14 @@ indices.push(vecPos-1); } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = []; - for (i = 0; i < totalSegs + 1; i++) { + for (i = 0; i < totalSegs + 1; i++) + { graphicsData.points.push(x + Math.sin(seg * i) * width, y + Math.cos(seg * i) * height); } @@ -481,18 +528,22 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildLine = function (graphicsData, webGLData) { +WebGLGraphics.buildLine = function (graphicsData, webGLData) +{ // TODO OPTIMISE! var i = 0; var points = graphicsData.points; - if (points.length === 0) { + if (points.length === 0) + { return; } // if the line width is an odd number add 0.5 to align to a whole pixel - if (graphicsData.lineWidth%2) { - for (i = 0; i < points.length; i++) { + if (graphicsData.lineWidth%2) + { + for (i = 0; i < points.length; i++) + { points[i] += 0.5; } } @@ -502,7 +553,8 @@ var lastPoint = new math.Point(points[points.length - 2], points[points.length - 1]); // if the first point is the last point - gonna have issues :) - if (firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) { + if (firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) + { // need to clone as we are going to slightly modify the shape.. points = points.slice(); @@ -562,7 +614,8 @@ verts.push(p1x + perpx , p1y + perpy, r, g, b, alpha); - for (i = 1; i < length-1; i++) { + for (i = 1; i < length-1; i++) + { p1x = points[(i-1)*2]; p1y = points[(i-1)*2 + 1]; @@ -599,7 +652,8 @@ denom = a1*b2 - a2*b1; - if (Math.abs(denom) < 0.1 ) { + if (Math.abs(denom) < 0.1 ) + { denom+=10.1; verts.push(p2x - perpx , p2y - perpy, @@ -618,7 +672,8 @@ pdist = (px -p2x) * (px -p2x) + (py -p2y) + (py -p2y); - if (pdist > 140 * 140) { + if (pdist > 140 * 140) + { perp3x = perpx - perp2x; perp3y = perpy - perp2y; @@ -639,7 +694,8 @@ indexCount++; } - else { + else + { verts.push(px , py); verts.push(r, g, b, alpha); @@ -672,7 +728,8 @@ indices.push(indexStart); - for (i = 0; i < indexCount; i++) { + for (i = 0; i < indexCount; i++) + { indices.push(indexStart++); } @@ -687,11 +744,13 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildComplexPoly = function (graphicsData, webGLData) { +WebGLGraphics.buildComplexPoly = function (graphicsData, webGLData) +{ //TODO - no need to copy this as it gets turned into a FLoat32Array anyways.. var points = graphicsData.points.slice(); - if (points.length < 6) { + if (points.length < 6) + { return; } @@ -711,7 +770,8 @@ var x,y; // get size.. - for (var i = 0; i < points.length; i+=2) { + for (var i = 0; i < points.length; i+=2) + { x = points[i]; y = points[i+1]; @@ -732,7 +792,8 @@ //TODO - this aint needed! var length = points.length / 2; - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { indices.push( i ); } @@ -746,10 +807,12 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildPoly = function (graphicsData, webGLData) { +WebGLGraphics.buildPoly = function (graphicsData, webGLData) +{ var points = graphicsData.points; - if (points.length < 6) { + if (points.length < 6) + { return; } // get first and last point.. figure out the middle! @@ -767,7 +830,8 @@ var triangles = utils.PolyK.Triangulate(points); - if (!triangles) { + if (!triangles) + { return false; } @@ -775,7 +839,8 @@ var i = 0; - for (i = 0; i < triangles.length; i+=3) { + for (i = 0; i < triangles.length; i+=3) + { indices.push(triangles[i] + vertPos); indices.push(triangles[i] + vertPos); indices.push(triangles[i+1] + vertPos); @@ -783,7 +848,8 @@ indices.push(triangles[i+2] + vertPos); } - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { verts.push(points[i * 2], points[i * 2 + 1], r, g, b, alpha); } diff --git a/src/core/renderers/webgl/utils/WebGLGraphicsData.js b/src/core/renderers/webgl/utils/WebGLGraphicsData.js index c56d05e..c739ba7 100644 --- a/src/core/renderers/webgl/utils/WebGLGraphicsData.js +++ b/src/core/renderers/webgl/utils/WebGLGraphicsData.js @@ -2,7 +2,8 @@ * @class * @private */ -function WebGLGraphicsData(gl) { +function WebGLGraphicsData(gl) +{ this.gl = gl; //TODO does this need to be split before uploding?? @@ -22,7 +23,8 @@ /** * */ -WebGLGraphicsData.prototype.reset = function () { +WebGLGraphicsData.prototype.reset = function () +{ this.points.length = 0; this.indices.length = 0; }; @@ -30,7 +32,8 @@ /** * */ -WebGLGraphicsData.prototype.upload = function () { +WebGLGraphicsData.prototype.upload = function () +{ var gl = this.gl; // this.lastIndex = graphics.graphicsData.length; diff --git a/src/core/renderers/webgl/utils/WebGLSpriteBatch.js b/src/core/renderers/webgl/utils/WebGLSpriteBatch.js index 96eaa52..55befbb 100644 --- a/src/core/renderers/webgl/utils/WebGLSpriteBatch.js +++ b/src/core/renderers/webgl/utils/WebGLSpriteBatch.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this sprite batch works for. */ -function WebGLSpriteBatch(renderer) { +function WebGLSpriteBatch(renderer) +{ /** * * @@ -88,7 +89,8 @@ */ this.lastIndexCount = 0; - for (var i=0, j=0; i < numIndices; i += 6, j += 4) { + 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; @@ -162,7 +164,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.setupContext(); }); } @@ -173,7 +176,8 @@ /** * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLSpriteBatch.prototype.setupContext = function () { +WebGLSpriteBatch.prototype.setupContext = function () +{ var gl = this.renderer.gl; // setup default shader @@ -198,7 +202,8 @@ /** * */ -WebGLSpriteBatch.prototype.begin = function () { +WebGLSpriteBatch.prototype.begin = function () +{ // this.shader = this.renderer.shaderManager.defaultShader; this.start(); @@ -206,19 +211,22 @@ /** */ -WebGLSpriteBatch.prototype.end = function () { +WebGLSpriteBatch.prototype.end = function () +{ this.flush(); }; /** * @param sprite {Sprite} the sprite to render when using this spritebatch */ -WebGLSpriteBatch.prototype.render = function (sprite) { +WebGLSpriteBatch.prototype.render = function (sprite) +{ var texture = sprite.texture; //TODO set blend modes.. // check texture.. - if (this.currentBatchSize >= this.size) { + if (this.currentBatchSize >= this.size) + { this.flush(); this.currentBaseTexture = texture.baseTexture; } @@ -227,7 +235,8 @@ var uvs = texture._uvs; // if the uvs have not updated then no point rendering just yet! - if (!uvs) { + if (!uvs) + { return; } @@ -237,7 +246,8 @@ var w0, w1, h0, h1; - if (texture.trim) { + 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; @@ -248,7 +258,8 @@ h0 = h1 + texture.crop.height; } - else { + else + { w0 = (texture.frame.width ) * (1-aX); w1 = (texture.frame.width ) * -aX; @@ -272,7 +283,8 @@ var colors = this.colors; var positions = this.positions; - if (this.renderer.roundPixels) { + if (this.renderer.roundPixels) + { // xy positions[index] = a * w1 + c * h1 + tx | 0; positions[index+1] = d * h1 + b * w1 + ty | 0; @@ -289,7 +301,8 @@ positions[index+15] = a * w1 + c * h0 + tx | 0; positions[index+16] = d * h0 + b * w1 + ty | 0; } - else { + else + { // xy positions[index] = a * w1 + c * h1 + tx; positions[index+1] = d * h1 + b * w1 + ty; @@ -338,11 +351,13 @@ * * @param sprite {TilingSprite} the tilingSprite to render */ -WebGLSpriteBatch.prototype.renderTilingSprite = function (tilingSprite) { +WebGLSpriteBatch.prototype.renderTilingSprite = function (tilingSprite) +{ var texture = tilingSprite.tilingTexture; // check texture.. - if (this.currentBatchSize >= this.size) { + if (this.currentBatchSize >= this.size) + { //return; this.flush(); this.currentBaseTexture = texture.baseTexture; @@ -351,7 +366,8 @@ // set the textures uvs temporarily // TODO create a separate texture so that we can tile part of a texture - if (!tilingSprite._uvs) { + if (!tilingSprite._uvs) + { tilingSprite._uvs = new TextureUvs(); } @@ -454,16 +470,19 @@ * Renders the content and empties the current batch. * */ -WebGLSpriteBatch.prototype.flush = function () { +WebGLSpriteBatch.prototype.flush = function () +{ // If the batch is length 0 then return as there is nothing to draw - if (this.currentBatchSize === 0) { + if (this.currentBatchSize === 0) + { return; } var gl = this.renderer.gl; var shader; - if (this.dirty) { + if (this.dirty) + { this.dirty = false; // bind the main texture gl.activeTexture(gl.TEXTURE0); @@ -482,10 +501,12 @@ } // upload the verts to the buffer - if (this.currentBatchSize > ( this.size * 0.5 ) ) { + if (this.currentBatchSize > ( this.size * 0.5 ) ) + { gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); } - else { + else + { var view = this.positions.subarray(0, this.currentBatchSize * this.vertByteSize); gl.bufferSubData(gl.ARRAY_BUFFER, 0, view); } @@ -502,7 +523,8 @@ var shaderSwap = false; var sprite; - for (var i = 0, j = this.currentBatchSize; i < j; i++) { + for (var i = 0, j = this.currentBatchSize; i < j; i++) + { sprite = this.sprites[i]; @@ -513,24 +535,28 @@ blendSwap = currentBlendMode !== nextBlendMode; shaderSwap = currentShader !== nextShader; // should I use uuidS??? - if (currentBaseTexture !== nextTexture || blendSwap || shaderSwap) { + if (currentBaseTexture !== nextTexture || blendSwap || shaderSwap) + { this.renderBatch(currentBaseTexture, batchSize, start); start = i; batchSize = 0; currentBaseTexture = nextTexture; - if (blendSwap) { + if (blendSwap) + { currentBlendMode = nextBlendMode; this.renderer.blendModeManager.setBlendMode( currentBlendMode ); } - if (shaderSwap) { + if (shaderSwap) + { currentShader = nextShader; shader = currentShader.shaders ? currentShader.shaders[gl.id] : currentShader; - if (!shader) { + if (!shader) + { shader = new Shader(gl, null, currentShader.fragmentSrc, currentShader.uniforms); currentShader.shaders[gl.id] = shader; } @@ -538,7 +564,8 @@ // set shader function??? this.renderer.shaderManager.setShader(shader); - if (shader.dirty) { + if (shader.dirty) + { shader.syncUniforms(); } @@ -569,17 +596,21 @@ * @param size {number} * @param startIndex {number} */ -WebGLSpriteBatch.prototype.renderBatch = function (texture, size, startIndex) { - if (size === 0) { +WebGLSpriteBatch.prototype.renderBatch = function (texture, size, startIndex) +{ + if (size === 0) + { return; } var gl = this.renderer.gl; - if (!texture._glTextures[gl.id]) { + if (!texture._glTextures[gl.id]) + { this.renderer.updateTexture(texture); } - else { + else + { // bind the current texture gl.bindTexture(gl.TEXTURE_2D, texture._glTextures[gl.id]); } @@ -594,7 +625,8 @@ /** * */ -WebGLSpriteBatch.prototype.stop = function () { +WebGLSpriteBatch.prototype.stop = function () +{ this.flush(); this.dirty = true; }; @@ -602,7 +634,8 @@ /** * */ -WebGLSpriteBatch.prototype.start = function () { +WebGLSpriteBatch.prototype.start = function () +{ this.dirty = true; }; @@ -610,7 +643,8 @@ * Destroys the SpriteBatch. * */ -WebGLSpriteBatch.prototype.destroy = function () { +WebGLSpriteBatch.prototype.destroy = function () +{ this.renderer.gl.deleteBuffer(this.vertexBuffer); this.renderer.gl.deleteBuffer(this.indexBuffer); diff --git a/src/core/textures/BaseTexture.js b/src/core/textures/BaseTexture.js index 2bf77d4..513d358 100644 --- a/src/core/textures/BaseTexture.js +++ b/src/core/textures/BaseTexture.js @@ -10,7 +10,8 @@ * @param source {Image|Canvas} the source object of the texture. * @param [scaleMode=scaleModes.DEFAULT] {number} See {@link scaleModes} for possible values */ -function BaseTexture(source, scaleMode) { +function BaseTexture(source, scaleMode) +{ this.uuid = utils.uuid(); /** @@ -123,7 +124,8 @@ this._needsUpdate = false; // if no source passed don't try to load - if (source) { + if (source) + { this.loadSource(source); } @@ -149,13 +151,16 @@ Object.defineProperties(BaseTexture.prototype, { needsUpdate: { - get: function () { + get: function () + { return this._needsUpdate; }, - set: function (val) { + set: function (val) + { this._needsUpdate = val; - if (val) { + if (val) + { this.emit('update', this); } } @@ -171,9 +176,11 @@ * * The logic state after calling `loadSource` directly or indirectly (eg. `fromImage`, `new BaseTexture`) is: * - * if (texture.hasLoaded) { + * if (texture.hasLoaded) + { * // texture ready for use - * } else if (texture.isLoading) { + * } else if (texture.isLoading) + { * // listen to 'loaded' and/or 'error' events on texture * } else { * // not loading, not going to load UNLESS the source is reloaded @@ -183,12 +190,14 @@ * @protected * @param source {Image|Canvas} the source object of the texture. */ -BaseTexture.prototype.loadSource = function (source) { +BaseTexture.prototype.loadSource = function (source) +{ var wasLoading = this.isLoading; this.hasLoaded = false; this.isLoading = false; - if (wasLoading && this.source) { + if (wasLoading && this.source) + { this.source.onload = null; this.source.onerror = null; } @@ -196,20 +205,24 @@ this.source = source; // Apply source if loaded. Otherwise setup appropriate loading monitors. - if ((this.source.complete || this.source.getContext) && this.source.width && this.source.height) { + if ((this.source.complete || this.source.getContext) && this.source.width && this.source.height) + { this._sourceLoaded(); } - else if(!source.getContext) { + else if(!source.getContext) + { // Image fail / not ready this.isLoading = true; var scope = this; - source.onload = function () { + source.onload = function () + { source.onload = null; source.onerror = null; - if(!scope.isLoading) { + if(!scope.isLoading) + { return; } @@ -219,11 +232,13 @@ scope.emit('loaded', scope); }; - source.onerror = function () { + source.onerror = function () + { source.onload = null; source.onerror = null; - if(!scope.isLoading) { + if(!scope.isLoading) + { return; } @@ -234,24 +249,29 @@ // Per http://www.w3.org/TR/html5/embedded-content-0.html#the-img-element // "The value of `complete` can thus change while a script is executing." // So complete needs to be re-checked after the callbacks have been added.. - if (source.complete) { + if (source.complete) + { this.isLoading = false; // ..and if we're complete now, no need for callbacks source.onload = null; source.onerror = null; - if (source.width && source.height) { + if (source.width && source.height) + { this._sourceLoaded(); // If any previous subscribers possible - if (wasLoading) { + if (wasLoading) + { this.emit('loaded', this); } } - else { + else + { // If any previous subscribers possible - if (wasLoading) { + if (wasLoading) + { this.emit('error', this); } } @@ -265,7 +285,8 @@ * * @private */ -BaseTexture.prototype._sourceLoaded = function () { +BaseTexture.prototype._sourceLoaded = function () +{ this.hasLoaded = true; this.width = this.source.naturalWidth || this.source.width; @@ -278,16 +299,20 @@ * Destroys this base texture * */ -BaseTexture.prototype.destroy = function () { - if (this.imageUrl) { +BaseTexture.prototype.destroy = function () +{ + if (this.imageUrl) + { delete utils.BaseTextureCache[this.imageUrl]; delete utils.TextureCache[this.imageUrl]; this.imageUrl = null; - if (!navigator.isCocoonJS) { + if (!navigator.isCocoonJS) + { this.source.src = ''; } } - else if (this.source && this.source._pixiId) { + else if (this.source && this.source._pixiId) + { delete utils.BaseTextureCache[this.source._pixiId]; } this.source = null; @@ -301,7 +326,8 @@ * memory again. * */ -BaseTexture.prototype.dispose = function () { +BaseTexture.prototype.dispose = function () +{ this.emit('dispose', this); }; @@ -311,7 +337,8 @@ * * @param newSrc {string} the path of the image */ -BaseTexture.prototype.updateSourceImage = function (newSrc) { +BaseTexture.prototype.updateSourceImage = function (newSrc) +{ this.source.src = newSrc; this.loadSource(this.source); }; @@ -326,18 +353,22 @@ * @param [scaleMode=scaleModes.DEFAULT] {number} See {@link scaleModes} for possible values * @return BaseTexture */ -BaseTexture.fromImage = function (imageUrl, crossorigin, scaleMode) { +BaseTexture.fromImage = function (imageUrl, crossorigin, scaleMode) +{ var baseTexture = utils.BaseTextureCache[imageUrl]; - if (crossorigin === undefined && imageUrl.indexOf('data:') !== 0) { + if (crossorigin === undefined && imageUrl.indexOf('data:') !== 0) + { crossorigin = true; } - if (!baseTexture) { + if (!baseTexture) + { // new Image() breaks tex loading in some versions of Chrome. // See https://code.google.com/p/chromium/issues/detail?id=238071 var image = new Image();//document.createElement('img'); - if (crossorigin) { + if (crossorigin) + { image.crossOrigin = ''; } @@ -347,7 +378,8 @@ utils.BaseTextureCache[imageUrl] = baseTexture; // if there is an @2x at the end of the url we are going to assume its a highres image - if ( imageUrl.indexOf(CONST.RETINA_PREFIX + '.') !== -1) { + if ( imageUrl.indexOf(CONST.RETINA_PREFIX + '.') !== -1) + { baseTexture.resolution = 2; } } @@ -363,14 +395,17 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return BaseTexture */ -BaseTexture.fromCanvas = function (canvas, scaleMode) { - if (!canvas._pixiId) { +BaseTexture.fromCanvas = function (canvas, scaleMode) +{ + if (!canvas._pixiId) + { canvas._pixiId = 'canvas_' + utils.uuid(); } var baseTexture = utils.BaseTextureCache[canvas._pixiId]; - if (!baseTexture) { + if (!baseTexture) + { baseTexture = new BaseTexture(canvas, scaleMode); utils.BaseTextureCache[canvas._pixiId] = baseTexture; } diff --git a/src/core/textures/RenderTexture.js b/src/core/textures/RenderTexture.js index 6dad20f..53ae796 100644 --- a/src/core/textures/RenderTexture.js +++ b/src/core/textures/RenderTexture.js @@ -46,8 +46,10 @@ * @param [scaleMode] {number} See {@link scaleModes} for possible values * @param [resolution=1] {number} The resolution of the texture being generated */ -function RenderTexture(renderer, width, height, scaleMode, resolution) { - if (!renderer) { +function RenderTexture(renderer, width, height, scaleMode, resolution) +{ + if (!renderer) + { throw new Error('Unable to create RenderTexture, you must pass a renderer into the constructor.'); } @@ -133,7 +135,8 @@ */ this.renderer = renderer; - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { var gl = this.renderer.gl; this.textureBuffer = new FilterTexture(gl, this.width * this.resolution, this.height * this.resolution, this.baseTexture.scaleMode); @@ -142,7 +145,8 @@ this.render = this.renderWebGL; this.projection = new math.Point(this.width*0.5, -this.height*0.5); } - else { + else + { this.render = this.renderCanvas; this.textureBuffer = new CanvasBuffer(this.width* this.resolution, this.height* this.resolution); this.baseTexture.source = this.textureBuffer.canvas; @@ -167,8 +171,10 @@ * @param height {number} The height to resize to. * @param updateBase {boolean} Should the baseTexture.width and height values be resized as well? */ -RenderTexture.prototype.resize = function (width, height, updateBase) { - if (width === this.width && height === this.height) { +RenderTexture.prototype.resize = function (width, height, updateBase) +{ + if (width === this.width && height === this.height) + { return; } @@ -177,17 +183,20 @@ this.width = this.frame.width = this.crop.width = width; this.height = this.frame.height = this.crop.height = height; - if (updateBase) { + if (updateBase) + { this.baseTexture.width = this.width; this.baseTexture.height = this.height; } - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { this.projection.x = this.width / 2; this.projection.y = -this.height / 2; } - if (!this.valid) { + if (!this.valid) + { return; } @@ -198,12 +207,15 @@ * Clears the RenderTexture. * */ -RenderTexture.prototype.clear = function () { - if (!this.valid) { +RenderTexture.prototype.clear = function () +{ + if (!this.valid) + { return; } - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { this.renderer.gl.bindFramebuffer(this.renderer.gl.FRAMEBUFFER, this.textureBuffer.frameBuffer); } @@ -220,19 +232,23 @@ * @param [restoreWorldTransform=true] {boolean} If true the displayObject's worldTransform/worldAlpha and all children * transformations will be restored. Not restoring this information will be a little faster. */ -RenderTexture.prototype.renderWebGL = function (displayObject, matrix, clear, restoreWorldTransform) { - if (!this.valid) { +RenderTexture.prototype.renderWebGL = function (displayObject, matrix, clear, restoreWorldTransform) +{ + if (!this.valid) + { return; } - if (typeof restoreWorldTransform === 'undefined') { + if (typeof restoreWorldTransform === 'undefined') + { restoreWorldTransform = true; } var tempAlpha, tempTransform; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { tempAlpha = displayObject.worldAlpha; tempTransform = displayObject.worldTransform.toArray(); } @@ -245,7 +261,8 @@ wt.identity(); wt.translate(0, this.projection.y * 2); - if (matrix) { + if (matrix) + { wt.append(matrix); } @@ -258,7 +275,8 @@ var children = displayObject.children; var i, j; - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } @@ -269,7 +287,8 @@ gl.bindFramebuffer(gl.FRAMEBUFFER, this.textureBuffer.frameBuffer ); - if (clear) { + if (clear) + { this.textureBuffer.clear(); } @@ -279,11 +298,13 @@ this.renderer.spriteBatch.dirty = true; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { displayObject.worldAlpha = tempAlpha; displayObject.worldTransform.fromArray(tempTransform); - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } } @@ -300,26 +321,31 @@ * @param [restoreWorldTransform=true] {boolean} If true the displayObject's worldTransform/worldAlpha and all children * transformations will be restored. Not restoring this information will be a little faster. */ -RenderTexture.prototype.renderCanvas = function (displayObject, matrix, clear, restoreWorldTransform) { - if (!this.valid) { +RenderTexture.prototype.renderCanvas = function (displayObject, matrix, clear, restoreWorldTransform) +{ + if (!this.valid) + { return; } - if (typeof restoreWorldTransform === 'undefined') { + if (typeof restoreWorldTransform === 'undefined') + { restoreWorldTransform = true; } var tempAlpha, tempTransform; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { tempAlpha = displayObject.worldAlpha; tempTransform = displayObject.worldTransform.toArray(); } var wt = displayObject.worldTransform; wt.identity(); - if (matrix) { + if (matrix) + { wt.append(matrix); } @@ -330,11 +356,13 @@ var children = displayObject.children; var i, j; - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } - if (clear) { + if (clear) + { this.textureBuffer.clear(); } @@ -348,11 +376,13 @@ this.renderer.resolution = realResolution; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { displayObject.worldAlpha = tempAlpha; displayObject.worldTransform.fromArray(tempTransform); - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } } @@ -363,7 +393,8 @@ * * @return {Image} */ -RenderTexture.prototype.getImage = function () { +RenderTexture.prototype.getImage = function () +{ var image = new Image(); image.src = this.getBase64(); return image; @@ -374,7 +405,8 @@ * * @return {string} A base64 encoded string of the texture. */ -RenderTexture.prototype.getBase64 = function () { +RenderTexture.prototype.getBase64 = function () +{ return this.getCanvas().toDataURL(); }; @@ -383,8 +415,10 @@ * * @return {HTMLCanvasElement} A Canvas element with the texture rendered on. */ -RenderTexture.prototype.getCanvas = function () { - if (this.renderer.type === CONST.WEBGL_RENDERER) { +RenderTexture.prototype.getCanvas = function () +{ + if (this.renderer.type === CONST.WEBGL_RENDERER) + { var gl = this.renderer.gl; var width = this.textureBuffer.width; var height = this.textureBuffer.height; @@ -403,7 +437,8 @@ return tempCanvas.canvas; } - else { + else + { return this.textureBuffer.canvas; } }; diff --git a/src/core/textures/Texture.js b/src/core/textures/Texture.js index 3c65909..e97f0aa 100644 --- a/src/core/textures/Texture.js +++ b/src/core/textures/Texture.js @@ -17,7 +17,8 @@ * @param [crop] {Rectangle} The area of original texture * @param [trim] {Rectangle} Trimmed texture rectangle */ -function Texture(baseTexture, frame, crop, trim) { +function Texture(baseTexture, frame, crop, trim) +{ /** * Does this Texture have any frame data assigned to it? * @@ -25,12 +26,14 @@ */ this.noFrame = false; - if (!frame) { + if (!frame) + { this.noFrame = true; frame = new math.Rectangle(0, 0, 1, 1); } - if (baseTexture instanceof Texture) { + if (baseTexture instanceof Texture) + { baseTexture = baseTexture.baseTexture; } @@ -100,13 +103,16 @@ */ this.crop = crop || new math.Rectangle(0, 0, 1, 1); - if (baseTexture.hasLoaded) { - if (this.noFrame) { + if (baseTexture.hasLoaded) + { + if (this.noFrame) + { frame = new math.Rectangle(0, 0, baseTexture.width, baseTexture.height); } this.frame = frame; } - else { + else + { baseTexture.addEventListener('loaded', this.onBaseTextureLoaded.bind(this)); } } @@ -118,19 +124,23 @@ Object.defineProperties(Texture.prototype, { needsUpdate: { - get: function () { + get: function () + { return this.baseTexture.needsUpdate; }, - set: function (val) { + set: function (val) + { this.baseTexture.needsUpdate = val; } }, frame: { - get: function () { + get: function () + { return this._frame; }, - set: function (frame) { + set: function (frame) + { this._frame = frame; this.noFrame = false; @@ -143,20 +153,23 @@ 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 (!this.trim && (frame.x + frame.width > this.baseTexture.width || frame.y + frame.height > this.baseTexture.height)) + { throw new Error('Texture Error: frame does not fit inside the base Texture dimensions ' + this); } this.valid = frame && frame.width && frame.height && this.baseTexture.source && this.baseTexture.hasLoaded; - if (this.trim) { + 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) { + if (this.valid) + { this._updateUvs(); } } @@ -168,11 +181,13 @@ * * @private */ -Texture.prototype.onBaseTextureLoaded = function () { +Texture.prototype.onBaseTextureLoaded = function () +{ var baseTexture = this.baseTexture; baseTexture.removeEventListener('loaded', this.onLoaded); - if (this.noFrame) { + if (this.noFrame) + { this.frame = new math.Rectangle(0, 0, baseTexture.width, baseTexture.height); } @@ -184,8 +199,10 @@ * * @param destroyBase {boolean} Whether to destroy the base texture as well */ -Texture.prototype.destroy = function (destroyBase) { - if (destroyBase) { +Texture.prototype.destroy = function (destroyBase) +{ + if (destroyBase) + { this.baseTexture.destroy(); } @@ -197,8 +214,10 @@ * * @private */ -Texture.prototype._updateUvs = function () { - if (!this._uvs) { +Texture.prototype._updateUvs = function () +{ + if (!this._uvs) + { this._uvs = new TextureUvs(); } @@ -229,10 +248,12 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return Texture */ -Texture.fromImage = function (imageUrl, crossorigin, scaleMode) { +Texture.fromImage = function (imageUrl, crossorigin, scaleMode) +{ var texture = utils.TextureCache[imageUrl]; - if (!texture) { + if (!texture) + { texture = new Texture(BaseTexture.fromImage(imageUrl, crossorigin, scaleMode)); utils.TextureCache[imageUrl] = texture; } @@ -248,9 +269,11 @@ * @param frameId {string} The frame id of the texture * @return Texture */ -Texture.fromFrame = function (frameId) { +Texture.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache '); } return texture; @@ -264,7 +287,8 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return {Texture} */ -Texture.fromCanvas = function (canvas, scaleMode) { +Texture.fromCanvas = function (canvas, scaleMode) +{ return new Texture(BaseTexture.fromCanvas(canvas, scaleMode)); }; @@ -276,7 +300,8 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return {Texture} A Texture */ -Texture.fromVideo = function (video, scaleMode) { +Texture.fromVideo = function (video, scaleMode) +{ return new Texture(VideoBaseTexture.baseTextureFromVideo(video, scaleMode)); }; @@ -287,7 +312,8 @@ * @param texture {Texture} The Texture to add to the cache. * @param id {string} The id that the texture will be stored against. */ -Texture.addTextureToCache = function (texture, id) { +Texture.addTextureToCache = function (texture, id) +{ utils.TextureCache[id] = texture; }; @@ -298,7 +324,8 @@ * @param id {string} The id of the texture to be removed * @return {Texture} The texture that was removed */ -Texture.removeTextureFromCache = function (id) { +Texture.removeTextureFromCache = function (id) +{ var texture = utils.TextureCache[id]; delete utils.TextureCache[id]; diff --git a/src/core/textures/TextureUvs.js b/src/core/textures/TextureUvs.js index b9bbb58..5424d52 100644 --- a/src/core/textures/TextureUvs.js +++ b/src/core/textures/TextureUvs.js @@ -1,4 +1,5 @@ -function TextureUvs() { +function TextureUvs() +{ this.x0 = 0; this.y0 = 0; diff --git a/src/core/textures/VideoBaseTexture.js b/src/core/textures/VideoBaseTexture.js index e3e0c5a..1a826a9 100644 --- a/src/core/textures/VideoBaseTexture.js +++ b/src/core/textures/VideoBaseTexture.js @@ -12,15 +12,18 @@ * @param source {HTMLVideoElement} * @param [scaleMode] {number} See {@link scaleModes} for possible values */ -function VideoBaseTexture(source, scaleMode) { - if (!source){ +function VideoBaseTexture(source, scaleMode) +{ + if (!source) + { throw new Error('No video source element specified.'); } // hook in here to check if video is already available. // BaseTexture looks for a source.complete boolean, plus width & height. - if ((source.readyState === source.HAVE_ENOUGH_DATA || source.readyState === source.HAVE_FUTURE_DATA) && source.width && source.height) { + if ((source.readyState === source.HAVE_ENOUGH_DATA || source.readyState === source.HAVE_FUTURE_DATA) && source.width && source.height) + { source.complete = true; } @@ -31,7 +34,8 @@ this._boundOnUpdate = this._onUpdate.bind(this); this._boundOnCanPlay = this._onCanPlay.bind(this); - if (!source.complete) { + if (!source.complete) + { source.addEventListener('canplay', this._boundOnCanPlay); source.addEventListener('canplaythrough', this._boundOnCanPlay); @@ -47,28 +51,35 @@ VideoBaseTexture.prototype.constructor = VideoBaseTexture; module.exports = VideoBaseTexture; -VideoBaseTexture.prototype._onUpdate = function () { - if (this.autoUpdate) { +VideoBaseTexture.prototype._onUpdate = function () +{ + if (this.autoUpdate) + { window.requestAnimationFrame(this._boundOnUpdate); this.needsUpdate = true; } }; -VideoBaseTexture.prototype._onPlayStart = function () { - if (!this.autoUpdate) { +VideoBaseTexture.prototype._onPlayStart = function () +{ + if (!this.autoUpdate) + { window.requestAnimationFrame(this._boundOnUpdate); this.autoUpdate = true; } }; -VideoBaseTexture.prototype._onPlayStop = function () { +VideoBaseTexture.prototype._onPlayStop = function () +{ this.autoUpdate = false; }; -VideoBaseTexture.prototype._onCanPlay = function () { +VideoBaseTexture.prototype._onCanPlay = function () +{ this.hasLoaded = true; - if (this.source) { + if (this.source) + { this.source.removeEventListener('canplay', this._boundOnCanPlay); this.source.removeEventListener('canplaythrough', this._boundOnCanPlay); @@ -78,15 +89,18 @@ this.source.play(); // prevent multiple loaded dispatches.. - if(!this.__loaded){ + if(!this.__loaded) + { this.__loaded = true; this.emit('loaded', this); } } }; -VideoBaseTexture.prototype.destroy = function () { - if (this.source && this.source._pixiId) { +VideoBaseTexture.prototype.destroy = function () +{ + if (this.source && this.source._pixiId) + { utils.BaseTextureCache[ this.source._pixiId ] = null; delete utils.BaseTextureCache[ this.source._pixiId ]; @@ -105,14 +119,17 @@ * @param scaleMode {number} See {@link scaleModes} for possible values * @return {VideoBaseTexture} */ -VideoBaseTexture.fromVideo = function (video, scaleMode) { - if (!video._pixiId) { +VideoBaseTexture.fromVideo = function (video, scaleMode) +{ + if (!video._pixiId) + { video._pixiId = 'video_' + utils.uuid(); } var baseTexture = utils.BaseTextureCache[video._pixiId]; - if (!baseTexture) { + if (!baseTexture) + { baseTexture = new VideoBaseTexture(video, scaleMode); utils.BaseTextureCache[ video._pixiId ] = baseTexture; } @@ -147,17 +164,21 @@ * @param scaleMode {number} See {@link scaleModes} for possible values * @return {VideoBaseTexture} */ -VideoBaseTexture.fromUrl = function (videoSrc, scaleMode) { +VideoBaseTexture.fromUrl = function (videoSrc, scaleMode) +{ var video = document.createElement('video'); // array of objects or strings - if (Array.isArray(videoSrc)) { - for (var i = 0; i < videoSrc.length; ++i) { + if (Array.isArray(videoSrc)) + { + for (var i = 0; i < videoSrc.length; ++i) + { video.appendChild(createSource(videoSrc.src || videoSrc, videoSrc.mime)); } } // single object or string - else { + else + { video.appendChild(createSource(videoSrc.src || videoSrc, videoSrc.mime)); } @@ -169,8 +190,10 @@ VideoBaseTexture.fromUrls = VideoBaseTexture.fromUrl; -function createSource(path, type) { - if (!type) { +function createSource(path, type) +{ + if (!type) + { type = 'video/' + path.substr(path.lastIndexOf('.') + 1); } diff --git a/src/core/utils/EventData.js b/src/core/utils/EventData.js index 5d55a22..8cdf701 100644 --- a/src/core/utils/EventData.js +++ b/src/core/utils/EventData.js @@ -7,7 +7,8 @@ * @param name {string} The string name of the event that was triggered * @param data {object} Arbitrary event data to pass along */ -function EventData(target, name, data) { +function EventData(target, name, data) +{ // for duck typing in the ".on()" function this.__isEventObject = true; @@ -71,7 +72,8 @@ * Stops the propagation of events up the scene graph (prevents bubbling). * */ -EventData.prototype.stopPropagation = function stopPropagation() { +EventData.prototype.stopPropagation = function stopPropagation() +{ this.stopped = true; }; @@ -79,6 +81,7 @@ * Stops the propagation of events to sibling listeners (no longer calls any listeners). * */ -EventData.prototype.stopImmediatePropagation = function stopImmediatePropagation() { +EventData.prototype.stopImmediatePropagation = function stopImmediatePropagation() +{ this.stoppedImmediate = true; }; diff --git a/src/core/utils/EventTarget.js b/src/core/utils/EventTarget.js index 7ae8820..671a151 100644 --- a/src/core/utils/EventTarget.js +++ b/src/core/utils/EventTarget.js @@ -13,14 +13,16 @@ * var em = new MyEmitter(); * em.emit('eventName', 'some data', 'some more data', {}, null, ...); */ -function eventTarget(obj) { +function eventTarget(obj) +{ /** * Return a list of assigned event listeners. * * @param eventName {string} The events that should be listed. * @return {Array} An array of listener functions */ - obj.listeners = function listeners(eventName) { + obj.listeners = function listeners(eventName) + { this._listeners = this._listeners || {}; return this._listeners[eventName] ? this._listeners[eventName].slice() : []; @@ -33,22 +35,26 @@ * @param eventName {string} The name of the event. * @return {boolean} Indication if we've emitted an event. */ - obj.emit = obj.dispatchEvent = function emit(eventName, data) { + obj.emit = obj.dispatchEvent = function emit(eventName, data) + { this._listeners = this._listeners || {}; // fast return when there are no listeners - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return; } //backwards compat with old method ".emit({ type: 'something' })" - if (typeof eventName === 'object') { + if (typeof eventName === 'object') + { data = eventName; eventName = eventName.type; } //ensure we are using a real pixi event - if (!data || data.__isEventObject !== true) { + if (!data || data.__isEventObject !== true) + { data = new EventData(this, eventName, data); } @@ -58,23 +64,27 @@ fn = listeners[0], i; - for (i = 0; i < length; fn = listeners[++i]) { + for (i = 0; i < length; fn = listeners[++i]) + { //call the event listener fn.call(this, data); //if "stopImmediatePropagation" is called, stop calling sibling events - if (data.stoppedImmediate) { + if (data.stoppedImmediate) + { return this; } } //if "stopPropagation" is called then don't bubble the event - if (data.stopped) { + if (data.stopped) + { return this; } //bubble this event up the scene graph - if (this.parent && this.parent.emit) { + if (this.parent && this.parent.emit) + { this.parent.emit.call(this.parent, eventName, data); } @@ -88,7 +98,8 @@ * @param eventName {string} Name of the event. * @param callback {Functon} fn Callback function. */ - obj.on = obj.addEventListener = function on(eventName, fn) { + obj.on = obj.addEventListener = function on(eventName, fn) + { this._listeners = this._listeners || {}; (this._listeners[eventName] = this._listeners[eventName] || []) @@ -103,11 +114,13 @@ * @param eventName {string} Name of the event. * @param callback {Function} Callback function. */ - obj.once = function once(eventName, fn) { + obj.once = function once(eventName, fn) + { this._listeners = this._listeners || {}; var self = this; - function onceHandlerWrapper() { + function onceHandlerWrapper() + { fn.apply(self.off(eventName, onceHandlerWrapper), arguments); } onceHandlerWrapper._originalHandler = fn; @@ -122,23 +135,28 @@ * @param eventName {string} The event we want to remove. * @param callback {Function} The listener that we need to find. */ - obj.off = obj.removeEventListener = function off(eventName, fn) { + obj.off = obj.removeEventListener = function off(eventName, fn) + { this._listeners = this._listeners || {}; - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return this; } var list = this._listeners[eventName], i = fn ? list.length : 0; - while(i-- > 0) { - if (list[i] === fn || list[i]._originalHandler === fn) { + while(i-- > 0) + { + if (list[i] === fn || list[i]._originalHandler === fn) + { list.splice(i, 1); } } - if (list.length === 0) { + if (list.length === 0) + { delete this._listeners[eventName]; } @@ -150,10 +168,12 @@ * * @param eventName {string} The event you want to remove all listeners for. */ - obj.removeAllListeners = function removeAllListeners(eventName) { + obj.removeAllListeners = function removeAllListeners(eventName) + { this._listeners = this._listeners || {}; - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return this; } @@ -169,7 +189,8 @@ * * @param object {object} The obj to mix into */ - mixin: function mixin(obj) { + mixin: function mixin(obj) + { eventTarget(obj); } }; diff --git a/src/core/utils/PolyK.js b/src/core/utils/PolyK.js index 7325141..5e20c2b 100644 --- a/src/core/utils/PolyK.js +++ b/src/core/utils/PolyK.js @@ -47,7 +47,8 @@ * Triangulates shapes for webGL graphic fills. * */ -PolyK.Triangulate = function (p) { +PolyK.Triangulate = function (p) +{ var sign = true; var n = p.length >> 1; @@ -59,7 +60,8 @@ i = 0; var al = n; - while(al > 3) { + while(al > 3) + { var i0 = avl[(i+0)%al]; var i1 = avl[(i+1)%al]; var i2 = avl[(i+2)%al]; @@ -69,29 +71,35 @@ var cx = p[2*i2], cy = p[2*i2+1]; var earFound = false; - if (PolyK._convex(ax, ay, bx, by, cx, cy, sign)) { + if (PolyK._convex(ax, ay, bx, by, cx, cy, sign)) + { earFound = true; - for (var j = 0; j < al; j++) { + for (var j = 0; j < al; j++) + { var vi = avl[j]; if (vi === i0 || vi === i1 || vi === i2) continue; - if (PolyK._PointInTriangle(p[2*vi], p[2*vi+1], ax, ay, bx, by, cx, cy)) { + if (PolyK._PointInTriangle(p[2*vi], p[2*vi+1], ax, ay, bx, by, cx, cy)) + { earFound = false; break; } } } - if (earFound) { + if (earFound) + { tgs.push(i0, i1, i2); avl.splice((i+1)%al, 1); al--; i = 0; } - else if (i++ > 3*al) { + else if (i++ > 3*al) + { // need to flip flip reverse it! // reset! - if (sign) { + if (sign) + { tgs = []; avl = []; for (i = 0; i < n; i++) avl.push(i); @@ -101,7 +109,8 @@ sign = false; } - else { + else + { // window.console.log("PIXI Warning: shape too complex to fill"); return null; } @@ -126,7 +135,8 @@ * @private * @return {boolean} */ -PolyK._PointInTriangle = function (px, py, ax, ay, bx, by, cx, cy) { +PolyK._PointInTriangle = function (px, py, ax, ay, bx, by, cx, cy) +{ var v0x = cx-ax; var v0y = cy-ay; var v1x = bx-ax; @@ -154,6 +164,7 @@ * @private * @return {boolean} */ -PolyK._convex = function (ax, ay, bx, by, cx, cy, sign) { +PolyK._convex = function (ax, ay, bx, by, cx, cy, sign) +{ return ((ay-by)*(cx-bx) + (bx-ax)*(cy-by) >= 0) === sign; }; diff --git a/src/core/utils/index.js b/src/core/utils/index.js index ade9831..bfae7ae 100644 --- a/src/core/utils/index.js +++ b/src/core/utils/index.js @@ -16,7 +16,8 @@ * * @return {number} The next uuid to use. */ - uuid: function () { + uuid: function () + { return ++utils._uid; }, @@ -26,7 +27,8 @@ * @param hex {number} * @return {number[]} An array representing the [R, G, B] of the color. */ - hex2rgb: function (hex, out) { + hex2rgb: function (hex, out) + { out = out || []; out[0] = (hex >> 16 & 0xFF) / 255; @@ -42,7 +44,8 @@ * @param hex {number} * @return {string} The string color. */ - hex2string: function (hex) { + hex2string: function (hex) + { hex = hex.toString(16); hex = '000000'.substr(0, 6 - hex.length) + hex; @@ -55,7 +58,8 @@ * @param rgb {number[]} * @return {number} The color number */ - rgb2hex: function (rgb) { + rgb2hex: function (rgb) + { return ((rgb[0]*255 << 16) + (rgb[1]*255 << 8) + rgb[2]*255); }, @@ -64,8 +68,10 @@ * * @return {boolean} whether they are supported */ - canUseNewCanvasBlendModes: function () { - if (typeof document === 'undefined') { + canUseNewCanvasBlendModes: function () + { + if (typeof document === 'undefined') + { return false; } @@ -93,15 +99,19 @@ * @param number {number} * @return {number} the closest number that is a power of two */ - getNextPowerOfTwo: function (number) { + getNextPowerOfTwo: function (number) + { // see: http://en.wikipedia.org/wiki/Power_of_two#Fast_algorithm_to_check_if_a_positive_number_is_a_power_of_two - if (number > 0 && (number & (number - 1)) === 0) { + if (number > 0 && (number & (number - 1)) === 0) + { return number; } - else { + else + { var result = 1; - while (result < number) { + while (result < number) + { result <<= 1; } @@ -116,7 +126,8 @@ * @param height {number} * @return {boolean} */ - isPowerOfTwo: function (width, height) { + isPowerOfTwo: function (width, height) + { return (width > 0 && (width & (width - 1)) === 0 && height > 0 && (height & (height - 1)) === 0); }, @@ -130,12 +141,15 @@ * @constant * @static */ - sayHello: function (type) { - if (utils._saidHello) { + sayHello: function (type) + { + if (utils._saidHello) + { return; } - if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) { + if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) + { var args = [ '%c %c %c Pixi.js ' + CONST.VERSION + ' - ' + type + ' %c ' + ' %c ' + ' http://www.pixijs.com/ %c %c ♥%c♥%c♥ ', 'background: #ff66a5', @@ -151,7 +165,8 @@ console.log.apply(console, args); //jshint ignore:line } - else if (window.console) { + else if (window.console) + { console.log('Pixi.js ' + CONST.VERSION + ' - ' + type + ' - http://www.pixijs.com/'); //jshint ignore:line } @@ -166,15 +181,19 @@ * @class * @namespace PIXI */ - AjaxRequest: function () { + AjaxRequest: function () + { var activexmodes = ['Msxml2.XMLHTTP.6.0', 'Msxml2.XMLHTTP.3.0', 'Microsoft.XMLHTTP']; //activeX versions to check for in IE - if (window.ActiveXObject) { //Test for support for ActiveXObject in IE first (as XMLHttpRequest in IE7 is broken) - for (var i=0; i= this.textures.length) { + else if (round >= this.textures.length) + { this.gotoAndStop(this.textures.length - 1); - if (this.onComplete) { + if (this.onComplete) + { this.onComplete(); } } @@ -167,10 +182,12 @@ * @static * @param frames {string[]} the array of frames ids the movieclip will use as its texture frames */ -MovieClip.fromFrames = function (frames) { +MovieClip.fromFrames = function (frames) +{ var textures = []; - for (var i = 0; i < frames.length; ++i) { + for (var i = 0; i < frames.length; ++i) + { textures.push(new core.Texture.fromFrame(frames[i])); } @@ -183,10 +200,12 @@ * @static * @param images {string[]} the array of image urls the movieclip will use as its texture frames */ -MovieClip.fromImages = function (images) { +MovieClip.fromImages = function (images) +{ var textures = []; - for (var i = 0; i < images.length; ++i) { + for (var i = 0; i < images.length; ++i) + { textures.push(new core.Texture.fromImage(images[i])); } diff --git a/src/extras/Rope.js b/src/extras/Rope.js index c157ec4..9c87bc0 100644 --- a/src/extras/Rope.js +++ b/src/extras/Rope.js @@ -9,7 +9,8 @@ * @param {Array} points - An array of {Point}. * */ -function Rope(texture, points) { +function Rope(texture, points) +{ Strip.call(this, texture); this.points = points; @@ -31,10 +32,12 @@ * Refreshes * */ -Rope.prototype.refresh = function () { +Rope.prototype.refresh = function () +{ var points = this.points; - if (points.length < 1) { + if (points.length < 1) + { return; } @@ -59,20 +62,23 @@ var total = points.length, point, index, amount; - for (var i = 1; i < total; i++) { + for (var i = 1; i < total; i++) + { point = points[i]; index = i * 4; // time to do some smart drawing! amount = i / (total-1); - if (i%2) { + if (i%2) + { uvs[index] = amount; uvs[index+1] = 0; uvs[index+2] = amount; uvs[index+3] = 1; } - else { + else + { uvs[index] = amount; uvs[index+1] = 0; @@ -95,10 +101,12 @@ * * @private */ -Rope.prototype.updateTransform = function () { +Rope.prototype.updateTransform = function () +{ var points = this.points; - if (points.length < 1) { + if (points.length < 1) + { return; } @@ -113,14 +121,17 @@ var total = points.length, point, index, ratio, perpLength, num; - for (var i = 0; i < total; i++) { + for (var i = 0; i < total; i++) + { point = points[i]; index = i * 4; - if (i < points.length-1) { + if (i < points.length-1) + { nextPoint = points[i+1]; } - else { + else + { nextPoint = point; } @@ -129,7 +140,8 @@ ratio = (1 - (i / (total-1))) * 10; - if (ratio > 1) { + if (ratio > 1) + { ratio = 1; } @@ -157,7 +169,8 @@ * * @param texture {Texture} the texture that will be used */ -Rope.prototype.setTexture = function (texture) { +Rope.prototype.setTexture = function (texture) +{ // stop current texture this.texture = texture; //this.updateFrame = true; diff --git a/src/extras/Strip.js b/src/extras/Strip.js index c5e378f..57691b5 100644 --- a/src/extras/Strip.js +++ b/src/extras/Strip.js @@ -10,7 +10,8 @@ * @param height {number} the height * */ -function Strip(texture) { +function Strip(texture) +{ core.DisplayObjectContainer.call(this); /** @@ -70,9 +71,11 @@ * * @param renderer {WebGLRenderer} */ -Strip.prototype.renderWebGL = function (renderer) { +Strip.prototype.renderWebGL = function (renderer) +{ // if the sprite is not visible or the alpha is 0 then no need to render this element - if (!this.visible || this.alpha <= 0) { + if (!this.visible || this.alpha <= 0) + { return; } @@ -81,7 +84,8 @@ renderer.spriteBatch.stop(); // init! init! - if (!this._vertexBuffer) { + if (!this._vertexBuffer) + { this._initWebGL(renderer); } @@ -96,7 +100,8 @@ //TODO check culling }; -Strip.prototype._initWebGL = function (renderer) { +Strip.prototype._initWebGL = function (renderer) +{ // build the strip! var gl = renderer.gl; @@ -118,7 +123,8 @@ gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this.indices, gl.STATIC_DRAW); }; -Strip.prototype._renderStrip = function (renderer) { +Strip.prototype._renderStrip = function (renderer) +{ var gl = renderer.gl; var projection = renderer.projection, offset = renderer.offset, @@ -137,7 +143,8 @@ gl.uniform2f(shader.offsetVector, -offset.x, -offset.y); gl.uniform1f(shader.alpha, this.worldAlpha); - if (!this.dirty) { + if (!this.dirty) + { gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexBuffer); gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); @@ -150,10 +157,12 @@ gl.activeTexture(gl.TEXTURE0); // check if a texture is dirty.. - if (this.texture.baseTexture._dirty[gl.id]) { + if (this.texture.baseTexture._dirty[gl.id]) + { renderer.updateTexture(this.texture.baseTexture); } - else { + else + { // bind the current texture gl.bindTexture(gl.TEXTURE_2D, this.texture.baseTexture._glTextures[gl.id]); } @@ -163,7 +172,8 @@ } - else { + else + { this.dirty = false; gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexBuffer); @@ -178,10 +188,12 @@ gl.activeTexture(gl.TEXTURE0); // check if a texture is dirty.. - if (this.texture.baseTexture._dirty[gl.id]) { + if (this.texture.baseTexture._dirty[gl.id]) + { renderer.updateTexture(this.texture.baseTexture); } - else { + else + { gl.bindTexture(gl.TEXTURE_2D, this.texture.baseTexture._glTextures[gl.id]); } @@ -203,27 +215,33 @@ * * @param renderer {CanvasRenderer} */ -Strip.prototype.renderCanvas = function (renderer) { +Strip.prototype.renderCanvas = function (renderer) +{ var context = renderer.context; var transform = this.worldTransform; - if (renderer.roundPixels) { + if (renderer.roundPixels) + { context.setTransform(transform.a, transform.b, transform.c, transform.d, transform.tx | 0, transform.ty | 0); } - else { + else + { context.setTransform(transform.a, transform.b, transform.c, transform.d, transform.tx, transform.ty); } - if (this.drawMode === Strip.DrawModes.TRIANGLE_STRIP) { + if (this.drawMode === Strip.DrawModes.TRIANGLE_STRIP) + { this._renderCanvasTriangleStrip(context); } - else { + else + { this._renderCanvasTriangles(context); } }; -Strip.prototype._renderCanvasTriangleStrip = function (context) { +Strip.prototype._renderCanvasTriangleStrip = function (context) +{ // draw triangles!! var vertices = this.vertices; var uvs = this.uvs; @@ -231,14 +249,16 @@ var length = vertices.length / 2; // this.count++; - for (var i = 0; i < length - 2; i++) { + for (var i = 0; i < length - 2; i++) + { // draw some triangles! var index = i * 2; this._renderCanvasDrawTriangle(context, vertices, uvs, index, (index + 2), (index + 4)); } }; -Strip.prototype._renderCanvasTriangles = function (context) { +Strip.prototype._renderCanvasTriangles = function (context) +{ // draw triangles!! var vertices = this.vertices; var uvs = this.uvs; @@ -247,14 +267,16 @@ var length = indices.length; // this.count++; - for (var i = 0; i < length; i += 3) { + for (var i = 0; i < length; i += 3) + { // draw some triangles! var index0 = indices[i] * 2, index1 = indices[i + 1] * 2, index2 = indices[i + 2] * 2; this._renderCanvasDrawTriangle(context, vertices, uvs, index0, index1, index2); } }; -Strip.prototype._renderCanvasDrawTriangle = function (context, vertices, uvs, index0, index1, index2) { +Strip.prototype._renderCanvasDrawTriangle = function (context, vertices, uvs, index0, index1, index2) +{ var textureSource = this.texture.baseTexture.source; var textureWidth = this.texture.width; var textureHeight = this.texture.height; @@ -265,7 +287,8 @@ var u0 = uvs[index0] * textureWidth, u1 = uvs[index1] * textureWidth, u2 = uvs[index2] * textureWidth; var v0 = uvs[index0 + 1] * textureHeight, v1 = uvs[index1 + 1] * textureHeight, v2 = uvs[index2 + 1] * textureHeight; - if (this.canvasPadding > 0) { + if (this.canvasPadding > 0) + { var paddingX = this.canvasPadding / this.worldTransform.a; var paddingY = this.canvasPadding / this.worldTransform.d; var centerX = (x0 + x1 + x2) / 3; @@ -332,7 +355,8 @@ * @param strip {Strip} The Strip to render * @private */ -Strip.prototype.renderStripFlat = function (strip) { +Strip.prototype.renderStripFlat = function (strip) +{ var context = this.context; var vertices = strip.vertices; @@ -340,7 +364,8 @@ // this.count++; context.beginPath(); - for (var i=1; i < length-2; i++) { + for (var i=1; i < length-2; i++) + { // draw some triangles! var index = i*2; @@ -358,7 +383,8 @@ }; /* -Strip.prototype.setTexture = function (texture) { +Strip.prototype.setTexture = function (texture) +{ //TODO SET THE TEXTURES //TODO VISIBILITY @@ -377,7 +403,8 @@ * @private */ -Strip.prototype.onTextureUpdate = function () { +Strip.prototype.onTextureUpdate = function () +{ this.updateFrame = true; }; @@ -387,7 +414,8 @@ * @param matrix {Matrix} the transformation matrix of the sprite * @return {Rectangle} the framing rectangle */ -Strip.prototype.getBounds = function (matrix) { +Strip.prototype.getBounds = function (matrix) +{ var worldTransform = matrix || this.worldTransform; var a = worldTransform.a; @@ -404,7 +432,8 @@ var minY = Infinity; var vertices = this.vertices; - for (var i = 0, n = vertices.length; i < n; i += 2) { + for (var i = 0, n = vertices.length; i < n; i += 2) + { var rawX = vertices[i], rawY = vertices[i + 1]; var x = (a * rawX) + (c * rawY) + tx; var y = (d * rawY) + (b * rawX) + ty; @@ -416,7 +445,8 @@ maxY = y > maxY ? y : maxY; } - if (minX === -Infinity || maxY === Infinity) { + if (minX === -Infinity || maxY === Infinity) + { return core.math.Rectangle.EMPTY; } diff --git a/src/extras/TilingSprite.js b/src/extras/TilingSprite.js index 3ac22df..31da393 100644 --- a/src/extras/TilingSprite.js +++ b/src/extras/TilingSprite.js @@ -10,7 +10,8 @@ * @param width {number} the width of the tiling sprite * @param height {number} the height of the tiling sprite */ -function TilingSprite(texture, width, height) { +function TilingSprite(texture, width, height) +{ core.Sprite.call( this, texture); /** @@ -86,10 +87,12 @@ * @memberof TilingSprite# */ width: { - get: function () { + get: function () + { return this._width; }, - set: function (value) { + set: function (value) + { this._width = value; } }, @@ -101,20 +104,25 @@ * @memberof TilingSprite# */ height: { - get: function () { + get: function () + { return this._height; }, - set: function (value) { + set: function (value) + { this._height = value; } }, texture: { - get: function () { + get: function () + { return this._texture; }, - set: function (value) { - if (this._texture === value) { + set: function (value) + { + if (this._texture === value) + { return; } @@ -130,51 +138,61 @@ * * @param renderer {WebGLRenderer} */ -TilingSprite.prototype.renderWebGL = function (renderer) { - if (!this.visible || this.alpha <= 0) { +TilingSprite.prototype.renderWebGL = function (renderer) +{ + if (!this.visible || this.alpha <= 0) + { return; } var i, j; - if (this._mask) { + if (this._mask) + { renderer.spriteBatch.stop(); renderer.maskManager.pushMask(this.mask, renderer); renderer.spriteBatch.start(); } - if (this._filters) { + if (this._filters) + { renderer.spriteBatch.flush(); renderer.filterManager.pushFilter(this._filterBlock); } - if (!this.tilingTexture || this.refreshTexture) { + if (!this.tilingTexture || this.refreshTexture) + { this.generateTilingTexture(true); - if (this.tilingTexture && this.tilingTexture.needsUpdate) { + if (this.tilingTexture && this.tilingTexture.needsUpdate) + { //TODO - tweaking renderer.updateTexture(this.tilingTexture.baseTexture); this.tilingTexture.needsUpdate = false; // this.tilingTexture._uvs = null; } } - else { + else + { renderer.spriteBatch.renderTilingSprite(this); } // simple render children! - for (i=0,j=this.children.length; i= 0; i--) { + for (var i = length - 1; i >= 0; i--) + { var child = children[i]; // push all interactive bits - if (child._interactive) { + if (child._interactive) + { iParent.interactiveChildren = true; //child.__iParent = iParent; this.interactiveItems.push(child); - if (child.children.length > 0) { + if (child.children.length > 0) + { this.collectInteractiveSprite(child, child); } } - else { + else + { child.__iParent = null; - if (child.children.length > 0) { + if (child.children.length > 0) + { this.collectInteractiveSprite(child, iParent); } } @@ -189,7 +196,8 @@ * @param [resolution=1] {number} THe resolution of the new element (relative to the canvas). * @private */ -InteractionManager.prototype.setTargetElement = function (element, resolution) { +InteractionManager.prototype.setTargetElement = function (element, resolution) +{ this.removeEvents(); this.interactionDOMElement = element; @@ -203,12 +211,15 @@ * * @private */ -InteractionManager.prototype.addEvents = function () { - if (!this.interactionDOMElement) { +InteractionManager.prototype.addEvents = function () +{ + if (!this.interactionDOMElement) + { return; } - if (window.navigator.msPointerEnabled) { + if (window.navigator.msPointerEnabled) + { this.interactionDOMElement.style['-ms-content-zooming'] = 'none'; this.interactionDOMElement.style['-ms-touch-action'] = 'none'; } @@ -230,12 +241,15 @@ * * @private */ -InteractionManager.prototype.removeEvents = function () { - if (!this.interactionDOMElement) { +InteractionManager.prototype.removeEvents = function () +{ + if (!this.interactionDOMElement) + { return; } - if (window.navigator.msPointerEnabled) { + if (window.navigator.msPointerEnabled) + { this.interactionDOMElement.style['-ms-content-zooming'] = ''; this.interactionDOMElement.style['-ms-touch-action'] = ''; } @@ -260,8 +274,10 @@ * * @private */ -InteractionManager.prototype.update = function () { - if (!this.interactionDOMElement) { +InteractionManager.prototype.update = function () +{ + if (!this.interactionDOMElement) + { return; } @@ -269,7 +285,8 @@ var now = Date.now(); var diff = now - this.last; diff = (diff * INTERACTION_FREQUENCY ) / 1000; - if (diff < 1) { + if (diff < 1) + { return; } @@ -280,7 +297,8 @@ // ok.. so mouse events?? // yes for now :) // OPTIMISE - how often to check?? - if (this.dirty) { + if (this.dirty) + { this.rebuildInteractiveGraph(); } @@ -289,7 +307,8 @@ var cursor = 'inherit'; var over = false; - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { var item = this.interactiveItems[i]; // OPTIMISATION - only calculate every time if the mousemove function exists.. @@ -302,26 +321,34 @@ this.mouse.target = item; // ok so deal with interactions.. // looks like there was a hit! - if (item.__hit && !over) { - if (item.buttonMode) { + if (item.__hit && !over) + { + if (item.buttonMode) + { cursor = item.defaultCursor; } - if (!item.interactiveChildren) { + if (!item.interactiveChildren) + { over = true; } - if (!item.__isOver) { - if (item.mouseover) { + if (!item.__isOver) + { + if (item.mouseover) + { item.mouseover (this.mouse); } item.__isOver = true; } } - else { - if (item.__isOver) { + else + { + if (item.__isOver) + { // roll out! - if (item.mouseout) { + if (item.mouseout) + { item.mouseout (this.mouse); } item.__isOver = false; @@ -329,7 +356,8 @@ } } - if (this.currentCursorStyle !== cursor) { + if (this.currentCursorStyle !== cursor) + { this.currentCursorStyle = cursor; this.interactionDOMElement.style.cursor = cursor; } @@ -338,18 +366,21 @@ /** * @private */ -InteractionManager.prototype.rebuildInteractiveGraph = function () { +InteractionManager.prototype.rebuildInteractiveGraph = function () +{ this.dirty = false; var len = this.interactiveItems.length; - for (var i = 0; i < len; i++) { + for (var i = 0; i < len; i++) + { this.interactiveItems[i].interactiveChildren = false; } this.interactiveItems.length = 0; - if (this.stage.interactive) { + if (this.stage.interactive) + { this.interactiveItems.push(this.stage); } @@ -363,8 +394,10 @@ * @param event {Event} The DOM event of the mouse moving * @private */ -InteractionManager.prototype.onMouseMove = function (event) { - if (this.dirty) { +InteractionManager.prototype.onMouseMove = function (event) +{ + if (this.dirty) + { this.rebuildInteractiveGraph(); } @@ -378,11 +411,13 @@ var length = this.interactiveItems.length; - for (var i = 0; i < length; i++) { + for (var i = 0; i < length; i++) + { var item = this.interactiveItems[i]; // Call the function! - if (item.mousemove) { + if (item.mousemove) + { item.mousemove(this.mouse); } } @@ -394,14 +429,17 @@ * @param event {Event} The DOM event of a mouse button being pressed down * @private */ -InteractionManager.prototype.onMouseDown = function (event) { - if (this.dirty) { +InteractionManager.prototype.onMouseDown = function (event) +{ + if (this.dirty) + { this.rebuildInteractiveGraph(); } this.mouse.originalEvent = event; - if (AUTO_PREVENT_DEFAULT) { + if (AUTO_PREVENT_DEFAULT) + { this.mouse.originalEvent.preventDefault(); } @@ -420,22 +458,27 @@ // while // hit test - for (var i = 0; i < length; i++) { + for (var i = 0; i < length; i++) + { var item = this.interactiveItems[i]; - if (item[downFunction] || item[clickFunction]) { + if (item[downFunction] || item[clickFunction]) + { item[buttonIsDown] = true; item.__hit = this.hitTest(item, this.mouse); - if (item.__hit) { + if (item.__hit) + { //call the function! - if (item[downFunction]) { + if (item[downFunction]) + { item[downFunction](this.mouse); } item[isDown] = true; // just the one! - if (!item.interactiveChildren) { + if (!item.interactiveChildren) + { break; } } @@ -449,8 +492,10 @@ * @param event {Event} The DOM event of a mouse being moved out * @private */ -InteractionManager.prototype.onMouseOut = function (event) { - if (this.dirty) { +InteractionManager.prototype.onMouseOut = function (event) +{ + if (this.dirty) + { this.rebuildInteractiveGraph(); } @@ -460,11 +505,14 @@ this.interactionDOMElement.style.cursor = 'inherit'; - for (var i = 0; i < length; i++) { + for (var i = 0; i < length; i++) + { var item = this.interactiveItems[i]; - if (item.__isOver) { + if (item.__isOver) + { this.mouse.target = item; - if (item.mouseout) { + if (item.mouseout) + { item.mouseout(this.mouse); } item.__isOver = false; @@ -484,8 +532,10 @@ * @param event {Event} The DOM event of a mouse button being released * @private */ -InteractionManager.prototype.onMouseUp = function (event) { - if (this.dirty) { +InteractionManager.prototype.onMouseUp = function (event) +{ + if (this.dirty) + { this.rebuildInteractiveGraph(); } @@ -502,30 +552,40 @@ var upOutsideFunction = isRightButton ? 'rightupoutside' : 'mouseupoutside'; var isDown = isRightButton ? '__isRightDown' : '__isDown'; - for (var i = 0; i < length; i++) { + for (var i = 0; i < length; i++) + { var item = this.interactiveItems[i]; - if (item[clickFunction] || item[upFunction] || item[upOutsideFunction]) { + if (item[clickFunction] || item[upFunction] || item[upOutsideFunction]) + { item.__hit = this.hitTest(item, this.mouse); - if (item.__hit && !up) { + if (item.__hit && !up) + { //call the function! - if (item[upFunction]) { + if (item[upFunction]) + { item[upFunction](this.mouse); } - if (item[isDown]) { - if (item[clickFunction]) { + if (item[isDown]) + { + if (item[clickFunction]) + { item[clickFunction](this.mouse); } } - if (!item.interactiveChildren) { + if (!item.interactiveChildren) + { up = true; } } - else { - if (item[isDown]) { - if (item[upOutsideFunction]) { + else + { + if (item[isDown]) + { + if (item[upOutsideFunction]) + { item[upOutsideFunction](this.mouse); } } @@ -543,10 +603,12 @@ * @param interactionData {InteractionData} The interactionData object to update in the case there is a hit * @private */ -InteractionManager.prototype.hitTest = function (item, interactionData) { +InteractionManager.prototype.hitTest = function (item, interactionData) +{ var global = interactionData.global; - if (!item.worldVisible) { + if (!item.worldVisible) + { return false; } @@ -560,37 +622,46 @@ interactionData.target = item; //a sprite or display object with a hit area defined - if (item.hitArea && item.hitArea.contains) { + if (item.hitArea && item.hitArea.contains) + { return item.hitArea.contains(x, y); } // a sprite with no hitarea defined - else if (item instanceof core.Sprite) { + else if (item instanceof core.Sprite) + { var width = item.texture.frame.width; var height = item.texture.frame.height; var x1 = -width * item.anchor.x; var y1; - if (x > x1 && x < x1 + width) { + if (x > x1 && x < x1 + width) + { y1 = -height * item.anchor.y; - if (y > y1 && y < y1 + height) { + if (y > y1 && y < y1 + height) + { // set the target property if a hit is true! return true; } } } - else if (item instanceof core.Graphics) { + else if (item instanceof core.Graphics) + { var graphicsData = item.graphicsData; - for (i = 0; i < graphicsData.length; i++) { + for (i = 0; i < graphicsData.length; i++) + { var data = graphicsData[i]; - if (!data.fill) { + if (!data.fill) + { continue; } // only deal with fills.. - if (data.shape) { - if (data.shape.contains(x, y)) { + if (data.shape) + { + if (data.shape.contains(x, y)) + { //interactionData.target = item; return true; } @@ -600,10 +671,12 @@ var length = item.children.length; - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { var tempItem = item.children[i]; var hit = this.hitTest(tempItem, interactionData); - if (hit) { + if (hit) + { // hmm.. TODO SET CORRECT TARGET? interactionData.target = item; return true; @@ -618,8 +691,10 @@ * @param event {Event} The DOM event of a touch moving across the renderer view * @private */ -InteractionManager.prototype.onTouchMove = function (event) { - if (this.dirty) { +InteractionManager.prototype.onTouchMove = function (event) +{ + if (this.dirty) + { this.rebuildInteractiveGraph(); } @@ -628,7 +703,8 @@ var touchData; var i = 0; - for (i = 0; i < changedTouches.length; i++) { + for (i = 0; i < changedTouches.length; i++) + { var touchEvent = changedTouches[i]; touchData = this.touches[touchEvent.identifier]; touchData.originalEvent = event; @@ -636,15 +712,18 @@ // update the touch position touchData.global.x = ( (touchEvent.clientX - rect.left) * (this.interactionDOMElement.width / rect.width) ) / this.resolution; touchData.global.y = ( (touchEvent.clientY - rect.top) * (this.interactionDOMElement.height / rect.height) ) / this.resolution; - if (navigator.isCocoonJS && !rect.left && !rect.top && !event.target.style.width && !event.target.style.height) { + if (navigator.isCocoonJS && !rect.left && !rect.top && !event.target.style.width && !event.target.style.height) + { //Support for CocoonJS fullscreen scale modes touchData.global.x = touchEvent.clientX; touchData.global.y = touchEvent.clientY; } - for (var j = 0; j < this.interactiveItems.length; j++) { + for (var j = 0; j < this.interactiveItems.length; j++) + { var item = this.interactiveItems[j]; - if (item.touchmove && item.__touchData && item.__touchData[touchEvent.identifier]) { + if (item.touchmove && item.__touchData && item.__touchData[touchEvent.identifier]) + { item.touchmove(touchData); } } @@ -657,23 +736,28 @@ * @param event {Event} The DOM event of a touch starting on the renderer view * @private */ -InteractionManager.prototype.onTouchStart = function (event) { - if (this.dirty) { +InteractionManager.prototype.onTouchStart = function (event) +{ + if (this.dirty) + { this.rebuildInteractiveGraph(); } var rect = this.interactionDOMElement.getBoundingClientRect(); - if (AUTO_PREVENT_DEFAULT) { + if (AUTO_PREVENT_DEFAULT) + { event.preventDefault(); } var changedTouches = event.changedTouches; - for (var i=0; i < changedTouches.length; i++) { + for (var i=0; i < changedTouches.length; i++) + { var touchEvent = changedTouches[i]; var touchData = this.pool.pop(); - if (!touchData) { + if (!touchData) + { touchData = new InteractionData(); } @@ -682,7 +766,8 @@ this.touches[touchEvent.identifier] = touchData; touchData.global.x = ( (touchEvent.clientX - rect.left) * (this.interactionDOMElement.width / rect.width) ) / this.resolution; touchData.global.y = ( (touchEvent.clientY - rect.top) * (this.interactionDOMElement.height / rect.height) ) / this.resolution; - if (navigator.isCocoonJS && !rect.left && !rect.top && !event.target.style.width && !event.target.style.height) { + if (navigator.isCocoonJS && !rect.left && !rect.top && !event.target.style.width && !event.target.style.height) + { //Support for CocoonJS fullscreen scale modes touchData.global.x = touchEvent.clientX; touchData.global.y = touchEvent.clientY; @@ -690,15 +775,19 @@ var length = this.interactiveItems.length; - for (var j = 0; j < length; j++) { + for (var j = 0; j < length; j++) + { var item = this.interactiveItems[j]; - if (item.touchstart || item.tap) { + if (item.touchstart || item.tap) + { item.__hit = this.hitTest(item, touchData); - if (item.__hit) { + if (item.__hit) + { //call the function! - if (item.touchstart) { + if (item.touchstart) + { item.touchstart(touchData); } @@ -706,7 +795,8 @@ item.__touchData = item.__touchData || {}; item.__touchData[touchEvent.identifier] = touchData; - if (!item.interactiveChildren) { + if (!item.interactiveChildren) + { break; } } @@ -721,31 +811,37 @@ * @param event {Event} The DOM event of a touch ending on the renderer view * @private */ -InteractionManager.prototype.onTouchEnd = function (event) { - if (this.dirty) { +InteractionManager.prototype.onTouchEnd = function (event) +{ + if (this.dirty) + { this.rebuildInteractiveGraph(); } var rect = this.interactionDOMElement.getBoundingClientRect(); var changedTouches = event.changedTouches; - for (var i=0; i < changedTouches.length; i++) { + for (var i=0; i < changedTouches.length; i++) + { var touchEvent = changedTouches[i]; var touchData = this.touches[touchEvent.identifier]; var up = false; touchData.global.x = ( (touchEvent.clientX - rect.left) * (this.interactionDOMElement.width / rect.width) ) / this.resolution; touchData.global.y = ( (touchEvent.clientY - rect.top) * (this.interactionDOMElement.height / rect.height) ) / this.resolution; - if (navigator.isCocoonJS && !rect.left && !rect.top && !event.target.style.width && !event.target.style.height) { + if (navigator.isCocoonJS && !rect.left && !rect.top && !event.target.style.width && !event.target.style.height) + { //Support for CocoonJS fullscreen scale modes touchData.global.x = touchEvent.clientX; touchData.global.y = touchEvent.clientY; } var length = this.interactiveItems.length; - for (var j = 0; j < length; j++) { + for (var j = 0; j < length; j++) + { var item = this.interactiveItems[j]; - if (item.__touchData && item.__touchData[touchEvent.identifier]) { + if (item.__touchData && item.__touchData[touchEvent.identifier]) + { item.__hit = this.hitTest(item, item.__touchData[touchEvent.identifier]); @@ -753,20 +849,27 @@ touchData.originalEvent = event; // hitTest?? - if (item.touchend || item.tap) { - if (item.__hit && !up) { - if (item.touchend) { + if (item.touchend || item.tap) + { + if (item.__hit && !up) + { + if (item.touchend) + { item.touchend(touchData); } - if (item.__isDown && item.tap) { + if (item.__isDown && item.tap) + { item.tap(touchData); } - if (!item.interactiveChildren) { + if (!item.interactiveChildren) + { up = true; } } - else { - if (item.__isDown && item.touchendoutside) { + else + { + if (item.__isDown && item.touchendoutside) + { item.touchendoutside(touchData); } } diff --git a/src/core/display/DisplayObject.js b/src/core/display/DisplayObject.js index 66ebc3c..20e778c 100644 --- a/src/core/display/DisplayObject.js +++ b/src/core/display/DisplayObject.js @@ -7,7 +7,8 @@ * @class * @namespace PIXI */ -function DisplayObject() { +function DisplayObject() +{ /** * The coordinate of the object relative to the local coordinates of the parent. * @@ -152,10 +153,12 @@ * @memberof DisplayObject# */ x: { - get: function () { + get: function () + { return this.position.x; }, - set: function (value) { + set: function (value) + { this.position.x = value; } }, @@ -167,10 +170,12 @@ * @memberof DisplayObject# */ y: { - get: function () { + get: function () + { return this.position.y; }, - set: function (value) { + set: function (value) + { this.position.y = value; } }, @@ -183,11 +188,13 @@ * @readonly */ worldVisible: { - get: function () { + get: function () + { var item = this; do { - if (!item.visible) { + if (!item.visible) + { return false; } @@ -207,17 +214,21 @@ * @memberof DisplayObject# */ mask: { - get: function () { + get: function () + { return this._mask; }, - set: function (value) { - if (this._mask) { + set: function (value) + { + if (this._mask) + { this._mask.isMask = false; } this._mask = value; - if (this._mask) { + if (this._mask) + { this._mask.isMask = true; } } @@ -232,18 +243,23 @@ * @memberof DisplayObject# */ filters: { - get: function () { + get: function () + { return this._filters; }, - set: function (value) { - if (value) { + set: function (value) + { + if (value) + { // now put all the passes in one place.. var passes = []; - for (var i = 0; i < value.length; i++) { + for (var i = 0; i < value.length; i++) + { var filterPasses = value[i].passes; - for (var j = 0; j < filterPasses.length; j++) { + for (var j = 0; j < filterPasses.length; j++) + { passes.push(filterPasses[j]); } } @@ -264,8 +280,9 @@ * * @private */ -DisplayObject.prototype.updateTransform = function () { - +DisplayObject.prototype.updateTransform = function () +{ + // create some matrix refs for easy access var pt = this.parent.worldTransform; var wt = this.worldTransform; @@ -274,9 +291,11 @@ var a, b, c, d, tx, ty; // so if rotation is between 0 then we can simplify the multiplication process.. - if (this.rotation % math.PI_2) { + if (this.rotation % math.PI_2) + { // 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) { + if (this.rotation !== this.rotationCache) + { this.rotationCache = this.rotation; this._sr = Math.sin(this.rotation); this._cr = Math.cos(this.rotation); @@ -291,7 +310,8 @@ ty = this.position.y; // check for pivot.. not often used so geared towards that fact! - if (this.pivot.x || this.pivot.y) { + 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; } @@ -304,7 +324,8 @@ wt.tx = tx * pt.a + ty * pt.c + pt.tx; wt.ty = tx * pt.b + ty * pt.d + pt.ty; } - else { + else + { // lets do the fast version as we know there is no rotation.. a = this.scale.x; d = this.scale.y; @@ -333,7 +354,8 @@ * @param matrix {Matrix} * @return {Rectangle} the rectangular bounding area */ -DisplayObject.prototype.getBounds = function (/* matrix */) { +DisplayObject.prototype.getBounds = function (/* matrix */) +{ return math.Rectangle.EMPTY; }; @@ -342,7 +364,8 @@ * * @return {Rectangle} the rectangular bounding area */ -DisplayObject.prototype.getLocalBounds = function () { +DisplayObject.prototype.getLocalBounds = function () +{ return this.getBounds(math.Matrix.IDENTITY); }; @@ -352,7 +375,8 @@ * @param position {Point} The world origin to calculate from * @return {Point} A point object representing the position of this object */ -DisplayObject.prototype.toGlobal = function (position) { +DisplayObject.prototype.toGlobal = function (position) +{ // don't need to u[date the lot this.displayObjectUpdateTransform(); return this.worldTransform.apply(position); @@ -365,8 +389,10 @@ * @param [from] {DisplayObject} The DisplayObject to calculate the global position from * @return {Point} A point object representing the position of this object */ -DisplayObject.prototype.toLocal = function (position, from) { - if (from) { +DisplayObject.prototype.toLocal = function (position, from) +{ + if (from) + { position = from.toGlobal(position); } @@ -381,7 +407,8 @@ * @param renderer {WebGLRenderer} The renderer * @private */ -DisplayObject.prototype.renderWebGL = function (/* renderer */) { +DisplayObject.prototype.renderWebGL = function (/* renderer */) +{ // OVERWRITE; }; @@ -391,6 +418,7 @@ * @param renderer {CanvasRenderer} The renderer * @private */ -DisplayObject.prototype.renderCanvas = function (/* renderer */) { +DisplayObject.prototype.renderCanvas = function (/* renderer */) +{ // OVERWRITE; }; diff --git a/src/core/display/DisplayObjectContainer.js b/src/core/display/DisplayObjectContainer.js index 689f40b..4625ee8 100644 --- a/src/core/display/DisplayObjectContainer.js +++ b/src/core/display/DisplayObjectContainer.js @@ -12,7 +12,8 @@ * @extends DisplayObject * @namespace PIXI */ -function DisplayObjectContainer() { +function DisplayObjectContainer() +{ DisplayObject.call(this); /** @@ -47,17 +48,21 @@ * @memberof DisplayObjectContainer# */ width: { - get: function () { + get: function () + { return this.scale.x * this.getLocalBounds().width; }, - set: function (value) { + set: function (value) + { var width = this.getLocalBounds().width; - if(width !== 0) { + if(width !== 0) + { this.scale.x = value / width; } - else { + else + { this.scale.x = 1; } @@ -73,17 +78,21 @@ * @memberof DisplayObjectContainer# */ height: { - get: function () { + get: function () + { return this.scale.y * this.getLocalBounds().height; }, - set: function (value) { + set: function (value) + { var height = this.getLocalBounds().height; - if (height !== 0) { + if (height !== 0) + { this.scale.y = value / height ; } - else { + else + { this.scale.y = 1; } @@ -100,18 +109,23 @@ * @memberof DisplayObject# */ cacheAsBitmap: { - get: function () { + get: function () + { return this._cacheAsBitmap; }, - set: function (value) { - if (this._cacheAsBitmap === value) { + set: function (value) + { + if (this._cacheAsBitmap === value) + { return; } - if (value) { + if (value) + { this._generateCachedSprite(); } - else { + else + { this._destroyCachedSprite(); } @@ -126,7 +140,8 @@ * @param child {DisplayObject} The DisplayObject to add to the container * @return {DisplayObject} The child that was added. */ -DisplayObjectContainer.prototype.addChild = function (child) { +DisplayObjectContainer.prototype.addChild = function (child) +{ return this.addChildAt(child, this.children.length); }; @@ -137,14 +152,18 @@ * @param index {Number} The index to place the child in * @return {DisplayObject} The child that was added. */ -DisplayObjectContainer.prototype.addChildAt = function (child, index) { +DisplayObjectContainer.prototype.addChildAt = function (child, index) +{ // prevent adding self as child - if (child === this) { + if (child === this) + { return; } - if (index >= 0 && index <= this.children.length) { - if (child.parent) { + if (index >= 0 && index <= this.children.length) + { + if (child.parent) + { child.parent.removeChild(child); } @@ -154,7 +173,8 @@ return child; } - else { + else + { throw new Error(child + 'addChildAt: The index '+ index +' supplied is out of bounds ' + this.children.length); } }; @@ -165,15 +185,18 @@ * @param child {DisplayObject} * @param child2 {DisplayObject} */ -DisplayObjectContainer.prototype.swapChildren = function (child, child2) { - if (child === child2) { +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) { + if (index1 < 0 || index2 < 0) + { throw new Error('swapChildren: Both the supplied DisplayObjects must be a child of the caller.'); } @@ -187,10 +210,12 @@ * @param child {DisplayObject} The DisplayObject instance to identify * @return {Number} The index position of the child display object to identify */ -DisplayObjectContainer.prototype.getChildIndex = function (child) { +DisplayObjectContainer.prototype.getChildIndex = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { throw new Error('The supplied DisplayObject must be a child of the caller'); } @@ -203,8 +228,10 @@ * @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 */ -DisplayObjectContainer.prototype.setChildIndex = function (child, index) { - if (index < 0 || index >= this.children.length) { +DisplayObjectContainer.prototype.setChildIndex = function (child, index) +{ + if (index < 0 || index >= this.children.length) + { throw new Error('The supplied index is out of bounds'); } @@ -220,8 +247,10 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child at the given index, if any. */ -DisplayObjectContainer.prototype.getChildAt = function (index) { - if (index < 0 || index >= this.children.length) { +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'); } @@ -234,10 +263,12 @@ * @param child {DisplayObject} The DisplayObject to remove * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChild = function (child) { +DisplayObjectContainer.prototype.removeChild = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { return; } @@ -250,7 +281,8 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChildAt = function (index) { +DisplayObjectContainer.prototype.removeChildAt = function (index) +{ var child = this.getChildAt(index); child.parent = null; @@ -265,24 +297,29 @@ * @param beginIndex {Number} The beginning position. Default value is 0. * @param endIndex {Number} The ending position. Default value is size of the container. */ -DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) { +DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) +{ var begin = beginIndex || 0; var end = typeof endIndex === 'number' ? endIndex : this.children.length; var range = end - begin; - if (range > 0 && range <= end) { + if (range > 0 && range <= end) + { var removed = this.children.splice(begin, range); - for (var i = 0; i < removed.length; ++i) { + for (var i = 0; i < removed.length; ++i) + { removed[i].parent = null; } return removed; } - else if (range === 0 && this.children.length === 0) { + else if (range === 0 && this.children.length === 0) + { return []; } - else { + else + { throw new RangeError('removeChildren: numeric values are outside the acceptable range.'); } }; @@ -291,7 +328,8 @@ * Generates and updates the cached sprite for this object. * */ -DisplayObjectContainer.prototype.updateCachedSprite = function () { +DisplayObjectContainer.prototype.updateCachedSprite = function () +{ this._generateCachedSprite(); }; @@ -304,7 +342,8 @@ * @param renderer {CanvasRenderer|WebGLRenderer} The renderer used to generate the texture. * @return {Texture} a texture of the graphics object */ -DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) { +DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) +{ var bounds = this.getLocalBounds(); var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0, renderer, scaleMode, resolution); @@ -322,18 +361,22 @@ * * @private */ -DisplayObjectContainer.prototype.updateTransform = function () { - if (!this.visible) { +DisplayObjectContainer.prototype.updateTransform = function () +{ + if (!this.visible) + { return; } this.displayObjectUpdateTransform(); - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { return; } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } }; @@ -346,8 +389,10 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getBounds = function () { - if (this.children.length === 0) { +DisplayObjectContainer.prototype.getBounds = function () +{ + if (this.children.length === 0) + { return math.Rectangle.EMPTY; } @@ -365,10 +410,12 @@ var childVisible = false; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -386,7 +433,8 @@ maxY = maxY > childMaxY ? maxY : childMaxY; } - if (!childVisible) { + if (!childVisible) + { return math.Rectangle.EMPTY; } @@ -407,12 +455,14 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getLocalBounds = function () { +DisplayObjectContainer.prototype.getLocalBounds = function () +{ var matrixCache = this.worldTransform; this.worldTransform = math.Matrix.IDENTITY; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } @@ -428,13 +478,16 @@ * * @param renderer {WebGLRenderer} The renderer */ -DisplayObjectContainer.prototype.renderWebGL = function (renderer) { +DisplayObjectContainer.prototype.renderWebGL = function (renderer) +{ // if the object is not visible or the alpha is 0 then no need to render this element - if (!this.visible || this.alpha <= 0) { + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } @@ -442,14 +495,17 @@ var i, j; // do a quick check to see if this element has a mask or a filter. - if (this._mask || this._filters) { + if (this._mask || this._filters) + { // push filter first as we need to ensure the stencil buffer is correct for any masking - if (this._filters) { + if (this._filters) + { renderer.spriteBatch.flush(); renderer.filterManager.pushFilter(this._filterBlock); } - if (this._mask) { + if (this._mask) + { renderer.spriteBatch.stop(); renderer.maskManager.pushMask(this.mask, renderer); renderer.spriteBatch.start(); @@ -459,36 +515,42 @@ this._renderWebGL(renderer); // now loop through the children and make sure they get rendered - for (i = 0, j = this.children.length; i < j; i++) { + for (i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderWebGL(renderer); } // time to stop the sprite batch as either a mask element or a filter draw will happen next renderer.spriteBatch.stop(); - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(this._mask, renderer); } - if (this._filters) { + if (this._filters) + { renderer.filterManager.popFilter(); } renderer.spriteBatch.start(); } - else { + else + { this._renderWebGL(renderer); // simple render children! - for (i = 0, j = this.children.length; i < j; ++i) { + for (i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderWebGL(renderer); } } }; -DisplayObjectContainer.prototype._renderWebGL = function (renderer) { +DisplayObjectContainer.prototype._renderWebGL = function (renderer) +{ // this is where content itself gets renderd.. @@ -499,25 +561,31 @@ * * @param renderer {CanvasRenderer} The renderer */ -DisplayObjectContainer.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0) { +DisplayObjectContainer.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -528,13 +596,16 @@ * @param renderer {WebGLRenderer|CanvasRenderer} The renderer * @private */ -DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) { +DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) +{ this._cachedSprite.worldAlpha = this.worldAlpha; - if (renderer.gl) { + if (renderer.gl) + { this._cachedSprite.renderWebGL(renderer); } - else { + else + { this._cachedSprite.renderCanvas(renderer); } }; @@ -544,10 +615,12 @@ * * @private */ -DisplayObjectContainer.prototype._generateCachedSprite = function () { +DisplayObjectContainer.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { // TODO - RenderTexture now *requires* a renderer instance, so this is like broken // because `renderer` isn't actually in scope here :P var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0); @@ -555,7 +628,8 @@ this._cachedSprite = new Sprite(renderTexture); this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.texture.resize(bounds.width | 0, bounds.height | 0); } @@ -580,8 +654,10 @@ * * @private */ -DisplayObjectContainer.prototype._destroyCachedSprite = function () { - if (!this._cachedSprite) { +DisplayObjectContainer.prototype._destroyCachedSprite = function () +{ + if (!this._cachedSprite) + { return; } diff --git a/src/core/display/Sprite.js b/src/core/display/Sprite.js index 707da24..5862aef 100644 --- a/src/core/display/Sprite.js +++ b/src/core/display/Sprite.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param texture {Texture} The texture for this sprite */ -function Sprite(texture) { +function Sprite(texture) +{ DisplayObjectContainer.call(this); /** @@ -85,12 +86,14 @@ this.texture = texture || Texture.EMPTY; } -Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) { +Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) +{ DisplayObjectContainer.prototype.destroy.call(this); this.anchor = null; - if (destroyTexture) { + if (destroyTexture) + { this._texture.destroy(destroyBaseTexture); } @@ -111,10 +114,12 @@ * @memberof Sprite# */ width: { - get: function () { + get: function () + { return this.scale.x * this.texture.frame.width; }, - set: function (value) { + set: function (value) + { this.scale.x = value / this.texture.frame.width; this._width = value; } @@ -127,10 +132,12 @@ * @memberof Sprite# */ height: { - get: function () { + get: function () + { return this.scale.y * this.texture.frame.height; }, - set: function (value) { + set: function (value) + { this.scale.y = value / this.texture.frame.height; this._height = value; } @@ -143,23 +150,29 @@ * @memberof Sprite# */ texture: { - get: function () { + get: function () + { return this._texture; }, - set: function (value) { - if (this._texture === value) { + set: function (value) + { + if (this._texture === value) + { return; } this._texture = value; this.cachedTint = 0xFFFFFF; - if (value) { + if (value) + { // wait for the texture to load - if (value.baseTexture.hasLoaded) { + if (value.baseTexture.hasLoaded) + { this._onTextureUpdate(); } - else { + else + { value.once('update', this._onTextureUpdate.bind(this)); } } @@ -172,18 +185,22 @@ * * @private */ -Sprite.prototype._onTextureUpdate = function () { +Sprite.prototype._onTextureUpdate = function () +{ // so if _width is 0 then width was not set.. - if (this._width) { + if (this._width) + { this.scale.x = this._width / this.texture.frame.width; } - if (this._height) { + if (this._height) + { this.scale.y = this._height / this.texture.frame.height; } }; -Sprite.prototype._renderWebGL = function (renderer) { +Sprite.prototype._renderWebGL = function (renderer) +{ // this is where content gets renderd.. // watch this space for a little render state manager.. @@ -197,7 +214,8 @@ * @param matrix {Matrix} the transformation matrix of the sprite * @return {Rectangle} the framing rectangle */ -Sprite.prototype.getBounds = function (matrix) { +Sprite.prototype.getBounds = function (matrix) +{ var width = this.texture.frame.width; var height = this.texture.frame.height; @@ -224,11 +242,13 @@ if(b === 0 && c === 0) { // scale may be negative! - if (a < 0) { + if (a < 0) + { a *= -1; } - if (d < 0) { + if (d < 0) + { d *= -1; } @@ -293,28 +313,34 @@ * * @param renderer {CanvasRenderer} The renderer */ -Sprite.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) { +Sprite.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) + { return; } - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; renderer.context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } // Ignore null sources - if (this.texture.valid) { + if (this.texture.valid) + { var resolution = this.texture.baseTexture.resolution / renderer.resolution; renderer.context.globalAlpha = this.worldAlpha; // If smoothingEnabled is supported and we need to change the smoothing property for this texture - if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) { + if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) + { renderer.scaleMode = this.texture.baseTexture.scaleMode; renderer.context[renderer.smoothProperty] = (renderer.scaleMode === CONST.scaleModes.LINEAR); } @@ -324,7 +350,8 @@ var dy = (this.texture.trim ? this.texture.trim.y : 0) - (this.anchor.y * this.texture.trim.height); // Allow for pixel rounding - if (renderer.roundPixels) { + if (renderer.roundPixels) + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -337,7 +364,8 @@ dx = dx | 0; dy = dy | 0; } - else { + else + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -348,8 +376,10 @@ ); } - if (this.tint !== 0xFFFFFF) { - if (this.cachedTint !== this.tint) { + if (this.tint !== 0xFFFFFF) + { + if (this.cachedTint !== this.tint) + { this.cachedTint = this.tint; // TODO clean up caching - how to clean up the caches? @@ -368,7 +398,8 @@ this.texture.crop.height / resolution ); } - else { + else + { renderer.context.drawImage( this.texture.baseTexture.source, this.texture.crop.x, @@ -383,11 +414,13 @@ } } - for (var i = 0, j = this.children.length; i < j; i++) { + for (var i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -402,10 +435,12 @@ * @param frameId {String} The frame Id of the texture in the cache * @return {Sprite} A new Sprite using a texture from the texture cache matching the frameId */ -Sprite.fromFrame = function (frameId) { +Sprite.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache' + this); } @@ -420,6 +455,7 @@ * @param imageId {String} The image url of the texture * @return {Sprite} A new Sprite using a texture from the texture cache matching the image id */ -Sprite.fromImage = function (imageId, crossorigin, scaleMode) { +Sprite.fromImage = function (imageId, crossorigin, scaleMode) +{ return new Sprite(Texture.fromImage(imageId, crossorigin, scaleMode)); }; diff --git a/src/core/display/SpriteBatch.js b/src/core/display/SpriteBatch.js index 3187777..c196fef 100644 --- a/src/core/display/SpriteBatch.js +++ b/src/core/display/SpriteBatch.js @@ -12,7 +12,8 @@ * ```js * var container = new SpriteBatch(); * - * for(var i = 0; i < 100; ++i) { + * for(var i = 0; i < 100; ++i) + * { * var sprite = new PIXI.Sprite.fromImage("myImage.png"); * container.addChild(sprite); * } @@ -25,7 +26,8 @@ */ //TODO RENAME to PARTICLE CONTAINER? -function SpriteBatch() { +function SpriteBatch() +{ DisplayObjectContainer.call(this); } @@ -38,7 +40,8 @@ * * @private */ -SpriteBatch.prototype.updateTransform = function () { +SpriteBatch.prototype.updateTransform = function () +{ // TODO don't need to! this.displayObjectUpdateTransform(); // PIXI.DisplayObjectContainer.prototype.updateTransform.call( this ); @@ -50,8 +53,10 @@ * @param renderer {WebGLRenderer} The webgl renderer * @private */ -SpriteBatch.prototype.renderWebGL = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderWebGL = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -71,8 +76,10 @@ * @param renderer {CanvasRenderer} The canvas renderer * @private */ -SpriteBatch.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -84,10 +91,12 @@ this.displayObjectUpdateTransform(); - for (var i = 0; i < this.children.length; ++i) { + for (var i = 0; i < this.children.length; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -95,9 +104,11 @@ context.globalAlpha = this.worldAlpha * child.alpha; - if (child.rotation % (Math.PI * 2) === 0) { + if (child.rotation % (Math.PI * 2) === 0) + { // this is the fastest way to optimise! - if rotation is 0 then we can avoid any kind of setTransform call - if (isRotated) { + if (isRotated) + { context.setTransform( transform.a, transform.b, @@ -122,8 +133,10 @@ frame.height * child.scale.y ); } - else { - if (!isRotated) { + else + { + if (!isRotated) + { isRotated = true; } @@ -131,7 +144,8 @@ var childTransform = child.worldTransform; - if (renderer.roundPixels) { + if (renderer.roundPixels) + { context.setTransform( childTransform.a, childTransform.b, @@ -141,7 +155,8 @@ childTransform.ty | 0 ); } - else { + else + { context.setTransform( childTransform.a, childTransform.b, diff --git a/src/core/index.js b/src/core/index.js index 3954b6f..eb4a82b 100644 --- a/src/core/index.js +++ b/src/core/index.js @@ -58,11 +58,13 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRenderer: function (width, height, options, noWebGL) { + autoDetectRenderer: function (width, height, options, noWebGL) + { width = width || 800; height = height || 600; - if (!noWebGL && require('webgl-enabled')()) { + if (!noWebGL && require('webgl-enabled')()) + { return new core.WebGLRenderer(width, height, options); } @@ -87,7 +89,8 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRecommendedRenderer: function (width, height, options) { + autoDetectRecommendedRenderer: function (width, height, options) + { var isAndroid = /Android/i.test(navigator.userAgent); return core.autoDetectRenderer(width, height, options, isAndroid); diff --git a/src/core/math/Matrix.js b/src/core/math/Matrix.js index c2f87e2..2ff4848 100644 --- a/src/core/math/Matrix.js +++ b/src/core/math/Matrix.js @@ -10,7 +10,8 @@ * @class * @namespace PIXI */ -function Matrix() { +function Matrix() +{ /** * @member {number} * @default 1 @@ -63,7 +64,8 @@ * * @param array {number[]} The array that the matrix will be populated from. */ -Matrix.prototype.fromArray = function (array) { +Matrix.prototype.fromArray = function (array) +{ this.a = array[0]; this.b = array[1]; this.c = array[3]; @@ -78,14 +80,17 @@ * @param transpose {boolean} Whether we need to transpose the matrix or not * @return {number[]} the newly created array which contains the matrix */ -Matrix.prototype.toArray = function (transpose) { - if (!this.array) { +Matrix.prototype.toArray = function (transpose) +{ + if (!this.array) + { this.array = new Float32Array(9); } var array = this.array; - if (transpose) { + if (transpose) + { array[0] = this.a; array[1] = this.b; array[2] = 0; @@ -96,7 +101,8 @@ array[7] = this.ty; array[8] = 1; } - else { + else + { array[0] = this.a; array[1] = this.c; array[2] = this.tx; @@ -119,7 +125,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, transformed through this matrix */ -Matrix.prototype.apply = function (pos, newPos) { +Matrix.prototype.apply = function (pos, newPos) +{ newPos = newPos || new Point(); newPos.x = this.a * pos.x + this.c * pos.y + this.tx; @@ -136,7 +143,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, inverse-transformed through this matrix */ -Matrix.prototype.applyInverse = function (pos, newPos) { +Matrix.prototype.applyInverse = function (pos, newPos) +{ newPos = newPos || new Point(); var id = 1 / (this.a * this.d + this.c * -this.b); @@ -154,7 +162,8 @@ * @param {number} y * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.translate = function (x, y) { +Matrix.prototype.translate = function (x, y) +{ this.tx += x; this.ty += y; @@ -168,7 +177,8 @@ * @param {number} y The amount to scale vertically * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.scale = function (x, y) { +Matrix.prototype.scale = function (x, y) +{ this.a *= x; this.d *= y; this.c *= x; @@ -186,7 +196,8 @@ * @param {number} angle - The angle in radians. * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.rotate = function (angle) { +Matrix.prototype.rotate = function (angle) +{ var cos = Math.cos( angle ); var sin = Math.sin( angle ); @@ -210,7 +221,8 @@ * @param {Matrix} matrix * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.append = function (matrix) { +Matrix.prototype.append = function (matrix) +{ var a1 = this.a; var b1 = this.b; var c1 = this.c; @@ -232,7 +244,8 @@ * * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.identity = function () { +Matrix.prototype.identity = function () +{ this.a = 1; this.b = 0; this.c = 0; diff --git a/src/core/math/Point.js b/src/core/math/Point.js index 7565b2d..632f346 100644 --- a/src/core/math/Point.js +++ b/src/core/math/Point.js @@ -7,7 +7,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -function Point(x, y) { +function Point(x, y) +{ /** * @member {number} * @default 0 @@ -29,7 +30,8 @@ * * @return {Point} a copy of the point */ -Point.prototype.clone = function () { +Point.prototype.clone = function () +{ return new Point(this.x, this.y); }; @@ -40,7 +42,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -Point.prototype.set = function (x, y) { +Point.prototype.set = function (x, y) +{ this.x = x || 0; this.y = y || ( (y !== 0) ? this.x : 0 ) ; }; diff --git a/src/core/math/shapes/Circle.js b/src/core/math/shapes/Circle.js index 69cfdc9..4d76efc 100644 --- a/src/core/math/shapes/Circle.js +++ b/src/core/math/shapes/Circle.js @@ -10,7 +10,8 @@ * @param y {number} The Y coordinate of the center of this circle * @param radius {number} The radius of the circle */ -function Circle(x, y, radius) { +function Circle(x, y, radius) +{ /** * @member {number} * @default 0 @@ -46,7 +47,8 @@ * @method clone * @return {Circle} a copy of the Circle */ -Circle.prototype.clone = function () { +Circle.prototype.clone = function () +{ return new Circle(this.x, this.y, this.radius); }; @@ -58,8 +60,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Circle */ -Circle.prototype.contains = function (x, y) { - if (this.radius <= 0) { +Circle.prototype.contains = function (x, y) +{ + if (this.radius <= 0) + { return false; } @@ -79,6 +83,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Circle.prototype.getBounds = function () { +Circle.prototype.getBounds = function () +{ return new Rectangle(this.x - this.radius, this.y - this.radius, this.radius * 2, this.radius * 2); }; diff --git a/src/core/math/shapes/Ellipse.js b/src/core/math/shapes/Ellipse.js index 4f2d066..fefd01a 100644 --- a/src/core/math/shapes/Ellipse.js +++ b/src/core/math/shapes/Ellipse.js @@ -11,7 +11,8 @@ * @param width {number} The half width of this ellipse * @param height {number} The half height of this ellipse */ -function Ellipse(x, y, width, height) { +function Ellipse(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -53,7 +54,8 @@ * @method clone * @return {Ellipse} a copy of the ellipse */ -Ellipse.prototype.clone = function () { +Ellipse.prototype.clone = function () +{ return new Ellipse(this.x, this.y, this.width, this.height); }; @@ -65,8 +67,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coords are within this ellipse */ -Ellipse.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Ellipse.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } @@ -86,6 +90,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Ellipse.prototype.getBounds = function () { +Ellipse.prototype.getBounds = function () +{ return new Rectangle(this.x - this.width, this.y - this.height, this.width, this.height); }; diff --git a/src/core/math/shapes/Polygon.js b/src/core/math/shapes/Polygon.js index ae89148..fea6d37 100644 --- a/src/core/math/shapes/Polygon.js +++ b/src/core/math/shapes/Polygon.js @@ -10,16 +10,20 @@ * arguments passed can be flat x,y values e.g. `new Polygon(x,y, x,y, x,y, ...)` where `x` and `y` are * Numbers. */ -function Polygon(points) { +function Polygon(points) +{ //if points isn't an array, use arguments as the array - if (!(points instanceof Array)) { + if (!(points instanceof Array)) + { points = Array.prototype.slice.call(arguments); } //if this is a flat array of numbers, convert it to points - if (points[0] instanceof Point) { + if (points[0] instanceof Point) + { var p = []; - for (var i = 0, il = points.length; i < il; i++) { + for (var i = 0, il = points.length; i < il; i++) + { p.push(points[i].x, points[i].y); } @@ -51,7 +55,8 @@ * * @return {Polygon} a copy of the polygon */ -Polygon.prototype.clone = function () { +Polygon.prototype.clone = function () +{ return new Polygon(this.points.slice()); }; @@ -62,19 +67,22 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this polygon */ -Polygon.prototype.contains = function (x, y) { +Polygon.prototype.contains = function (x, y) +{ var inside = false; // use some raycasting to test hits // https://github.com/substack/point-in-polygon/blob/master/index.js var length = this.points.length / 2; - for (var i = 0, j = length - 1; i < length; j = i++) { + for (var i = 0, j = length - 1; i < length; j = i++) + { var xi = this.points[i * 2], yi = this.points[i * 2 + 1], xj = this.points[j * 2], yj = this.points[j * 2 + 1], intersect = ((yi > y) !== (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi); - if (intersect) { + if (intersect) + { inside = !inside; } } diff --git a/src/core/math/shapes/Rectangle.js b/src/core/math/shapes/Rectangle.js index 16ac62a..4008b68 100644 --- a/src/core/math/shapes/Rectangle.js +++ b/src/core/math/shapes/Rectangle.js @@ -10,7 +10,8 @@ * @param width {number} The overall width of this rectangle * @param height {number} The overall height of this rectangle */ -function Rectangle(x, y, width, height) { +function Rectangle(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -60,7 +61,8 @@ * * @return {Rectangle} a copy of the rectangle */ -Rectangle.prototype.clone = function () { +Rectangle.prototype.clone = function () +{ return new Rectangle(this.x, this.y, this.width, this.height); }; @@ -71,13 +73,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rectangle */ -Rectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Rectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/math/shapes/RoundedRectangle.js b/src/core/math/shapes/RoundedRectangle.js index 27d286e..7bf6411 100644 --- a/src/core/math/shapes/RoundedRectangle.js +++ b/src/core/math/shapes/RoundedRectangle.js @@ -11,7 +11,8 @@ * @param height {number} The overall height of this rounded rectangle * @param radius {number} Controls the radius of the rounded corners */ -function RoundedRectangle(x, y, width, height, radius) { +function RoundedRectangle(x, y, width, height, radius) +{ /** * @member {number} * @default 0 @@ -58,7 +59,8 @@ * * @return {RoundedRectangle} a copy of the rounded rectangle */ -RoundedRectangle.prototype.clone = function () { +RoundedRectangle.prototype.clone = function () +{ return new RoundedRectangle(this.x, this.y, this.width, this.height, this.radius); }; @@ -69,13 +71,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rounded Rectangle */ -RoundedRectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +RoundedRectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/primitives/Graphics.js b/src/core/primitives/Graphics.js index 261c534..e902d2a 100644 --- a/src/core/primitives/Graphics.js +++ b/src/core/primitives/Graphics.js @@ -16,7 +16,8 @@ * @extends DisplayObjectContainer * @namespace PIXI */ -function Graphics() { +function Graphics() +{ DisplayObjectContainer.call(this); this.renderable = true; @@ -154,16 +155,20 @@ * @private */ cacheAsBitmap: { - get: function () { + get: function () + { return this._cacheAsBitmap; }, - set: function (value) { + set: function (value) + { this._cacheAsBitmap = value; - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._generateCachedSprite(); } - else { + else + { this.destroyCachedSprite(); this.dirty = true; } @@ -176,7 +181,8 @@ * * @return {Graphics} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ var clone = new Graphics(); clone.renderable = this.renderable; @@ -192,7 +198,8 @@ clone.cachedSpriteDirty = this.cachedSpriteDirty; // copy graphics data - for (var i = 0; i < this.graphicsData.length; ++i) { + for (var i = 0; i < this.graphicsData.length; ++i) + { clone.graphicsData.push(this.graphicsData.clone()); } @@ -211,17 +218,21 @@ * @param alpha {number} alpha of the line to draw, will update the objects stored style * @return {Graphics} */ -Graphics.prototype.lineStyle = function (lineWidth, color, alpha) { +Graphics.prototype.lineStyle = function (lineWidth, color, alpha) +{ this.lineWidth = lineWidth || 0; this.lineColor = color || 0; this.lineAlpha = (arguments.length < 3) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length) + { // halfway through a line? start a new one! this.drawShape( new math.Polygon( this.currentPath.shape.points.slice(-2) )); } - else { + else + { // otherwise its empty so lets just set the line properties this.currentPath.lineWidth = this.lineWidth; this.currentPath.lineColor = this.lineColor; @@ -239,7 +250,8 @@ * @param y {number} the Y coordinate to move to * @return {Graphics} */ -Graphics.prototype.moveTo = function (x, y) { +Graphics.prototype.moveTo = function (x, y) +{ this.drawShape(new math.Polygon([x,y])); return this; @@ -253,7 +265,8 @@ * @param y {number} the Y coordinate to draw to * @return {Graphics} */ -Graphics.prototype.lineTo = function (x, y) { +Graphics.prototype.lineTo = function (x, y) +{ this.currentPath.shape.points.push(x, y); this.dirty = true; @@ -270,13 +283,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -285,7 +302,8 @@ n = 20, points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { this.moveTo(0, 0); } @@ -293,7 +311,8 @@ var fromY = points[points.length-1]; var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; xa = fromX + ( (cpX - fromX) * j ); @@ -319,13 +338,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -342,7 +365,8 @@ var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; dt = (1 - j); @@ -373,13 +397,17 @@ * @param radius {number} The radius of the arc * @return {Graphics} */ -Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points.push(x1, y1); } } - else { + else + { this.moveTo(x1, y1); } @@ -392,12 +420,15 @@ b2 = x2 - x1, mm = Math.abs(a1 * b2 - b1 * a2); - if (mm < 1.0e-8 || radius === 0) { - if (points[points.length-2] !== x1 || points[points.length-1] !== y1) { + if (mm < 1.0e-8 || radius === 0) + { + if (points[points.length-2] !== x1 || points[points.length-1] !== y1) + { points.push(x1, y1); } } - else { + else + { var dd = a1 * a1 + b1 * b1, cc = a2 * a2 + b2 * b2, tt = a1 * a2 + b1 * b2, @@ -433,42 +464,51 @@ * @param anticlockwise {boolean} Optional. Specifies whether the drawing should be counterclockwise or clockwise. False is default, and indicates clockwise, while true indicates counter-clockwise. * @return {Graphics} */ -Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) { +Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) +{ var startX = cx + Math.cos(startAngle) * radius; var startY = cy + Math.sin(startAngle) * radius; var points; // TODO - This if-else makes no sense. It uses currentPath in the else where it doesn't exist... - if (this.currentPath) { + if (this.currentPath) + { points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { points.push(startX, startY); } - else if (points[points.length-2] !== startX || points[points.length-1] !== startY) { + else if (points[points.length-2] !== startX || points[points.length-1] !== startY) + { points.push(startX, startY); } } - else { + else + { this.moveTo(startX, startY); points = this.currentPath.shape.points; } - if (startAngle === endAngle) { + if (startAngle === endAngle) + { return this; } - if (!anticlockwise && endAngle <= startAngle) { + if (!anticlockwise && endAngle <= startAngle) + { endAngle += Math.PI * 2; } - else if (anticlockwise && startAngle <= endAngle) { + else if (anticlockwise && startAngle <= endAngle) + { startAngle += Math.PI * 2; } var sweep = anticlockwise ? (startAngle - endAngle) *-1 : (endAngle - startAngle); var segs = (Math.abs(sweep)/ (Math.PI * 2)) * 40; - if (sweep === 0) { + if (sweep === 0) + { return this; } @@ -482,7 +522,8 @@ var remainder = ( segMinus % 1 ) / segMinus; - for (var i = 0; i <= segMinus; ++i) { + for (var i = 0; i <= segMinus; ++i) + { var real = i + remainder * i; var angle = ((theta) + startAngle + (theta2 * real)); @@ -506,13 +547,16 @@ * @param alpha {number} the alpha of the fill * @return {Graphics} */ -Graphics.prototype.beginFill = function (color, alpha) { +Graphics.prototype.beginFill = function (color, alpha) +{ this.filling = true; this.fillColor = color || 0; this.fillAlpha = (alpha === undefined) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length <= 2) + { this.currentPath.fill = this.filling; this.currentPath.fillColor = this.fillColor; this.currentPath.fillAlpha = this.fillAlpha; @@ -526,7 +570,8 @@ * * @return {Graphics} */ -Graphics.prototype.endFill = function () { +Graphics.prototype.endFill = function () +{ this.filling = false; this.fillColor = null; this.fillAlpha = 1; @@ -542,7 +587,8 @@ * @param height {number} The height of the rectangle * @return {Graphics} */ -Graphics.prototype.drawRect = function ( x, y, width, height ) { +Graphics.prototype.drawRect = function ( x, y, width, height ) +{ this.drawShape(new math.Rectangle(x,y, width, height)); return this; @@ -556,7 +602,8 @@ * @param height {number} The height of the rectangle * @param radius {number} Radius of the rectangle corners */ -Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) { +Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) +{ this.drawShape(new math.RoundedRectangle(x, y, width, height, radius)); return this; @@ -570,7 +617,8 @@ * @param radius {number} The radius of the circle * @return {Graphics} */ -Graphics.prototype.drawCircle = function (x, y, radius) { +Graphics.prototype.drawCircle = function (x, y, radius) +{ this.drawShape(new math.Circle(x,y, radius)); return this; @@ -585,7 +633,8 @@ * @param height {number} The half height of the ellipse * @return {Graphics} */ -Graphics.prototype.drawEllipse = function (x, y, width, height) { +Graphics.prototype.drawEllipse = function (x, y, width, height) +{ this.drawShape(new math.Ellipse(x, y, width, height)); return this; @@ -597,8 +646,10 @@ * @param path {Array} The path data used to construct the polygon. * @return {Graphics} */ -Graphics.prototype.drawPolygon = function (path) { - if (!(path instanceof Array)) { +Graphics.prototype.drawPolygon = function (path) +{ + if (!(path instanceof Array)) + { path = Array.prototype.slice.call(arguments); } @@ -612,7 +663,8 @@ * * @return {Graphics} */ -Graphics.prototype.clear = function () { +Graphics.prototype.clear = function () +{ this.lineWidth = 0; this.filling = false; @@ -631,7 +683,8 @@ * @param scaleMode {number} Should be one of the scaleMode consts * @return {Texture} a texture of the graphics object */ -Graphics.prototype.generateTexture = function (resolution, scaleMode) { +Graphics.prototype.generateTexture = function (resolution, scaleMode) +{ resolution = resolution || 1; var bounds = this.getBounds(); @@ -655,17 +708,21 @@ * * @param renderer {WebGLRenderer} */ -Graphics.prototype._renderWebGL = function (renderer) { +Graphics.prototype._renderWebGL = function (renderer) +{ // if the sprite is not visible or the alpha is 0 then no need to render this element - if (this.isMask === true) { + if (this.isMask === true) + { return; } // this code may still be needed so leaving for now.. - // + // /* - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture on the gpu too! @@ -681,17 +738,24 @@ return; } - */ - - // check if the webgl graphic needs to be updated - if (this.glDirty) { - this.dirty = true; - this.glDirty = false; - } + else */ - renderer.setObjectRendererer(renderer.graphicsRenderer); - renderer.graphicsRenderer.render(this); + renderer.spriteBatch.stop(); + renderer.blendModeManager.setBlendMode(this.blendMode); + // check blend mode + renderer.blendModeManager.setBlendMode( this.blendMode ); + + // check if the webgl graphic needs to be updated + if (this.glDirty) + { + this.dirty = true; + this.glDirty = false; + } + + WebGLGraphics.renderGraphics(this, renderer); + + renderer.spriteBatch.start(); }; /** @@ -700,14 +764,18 @@ * @param renderer {CanvasRenderer} * @private */ -Graphics.prototype.renderCanvas = function (renderer) { +Graphics.prototype.renderCanvas = function (renderer) +{ // 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.isMask === true) { + if (!this.visible || this.alpha <= 0 || this.isMask === true) + { return; } - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture @@ -723,16 +791,19 @@ return; } - else { + else + { var context = renderer.context; var transform = this.worldTransform; - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } @@ -748,11 +819,13 @@ CanvasGraphics.renderGraphics(this, context); - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } } @@ -763,13 +836,16 @@ * * @return {Rectangle} the rectangular bounding area */ -Graphics.prototype.getBounds = function (matrix) { +Graphics.prototype.getBounds = function (matrix) +{ // return an empty object if the item is a mask! - if (this.isMask) { + if (this.isMask) + { return math.Rectangle.EMPTY; } - if (this.dirty) { + if (this.dirty) + { this.updateLocalBounds(); this.glDirty = true; @@ -841,23 +917,27 @@ * Update the bounds of the object * */ -Graphics.prototype.updateLocalBounds = function () { +Graphics.prototype.updateLocalBounds = function () +{ var minX = Infinity; var maxX = -Infinity; var minY = Infinity; var maxY = -Infinity; - if (this.graphicsData.length) { + if (this.graphicsData.length) + { var shape, points, x, y, w, h; - for (var i = 0; i < this.graphicsData.length; i++) { + for (var i = 0; i < this.graphicsData.length; i++) + { var data = this.graphicsData[i]; var type = data.type; var lineWidth = data.lineWidth; shape = data.shape; - if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) { + if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) + { x = shape.x - lineWidth/2; y = shape.y - lineWidth/2; w = shape.width + lineWidth; @@ -869,7 +949,8 @@ minY = y < minY ? y : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.CIRC) { + else if (type === CONST.SHAPES.CIRC) + { x = shape.x; y = shape.y; w = shape.radius + lineWidth/2; @@ -881,7 +962,8 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.ELIP) { + else if (type === CONST.SHAPES.ELIP) + { x = shape.x; y = shape.y; w = shape.width + lineWidth/2; @@ -893,11 +975,13 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else { + else + { // POLY points = shape.points; - for (var j = 0; j < points.length; j += 2) { + for (var j = 0; j < points.length; j += 2) + { x = points[j]; y = points[j+1]; @@ -910,7 +994,8 @@ } } } - else { + else + { minX = 0; maxX = 0; minY = 0; @@ -931,10 +1016,12 @@ * * @private */ -Graphics.prototype._generateCachedSprite = function () { +Graphics.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { var canvasBuffer = new CanvasBuffer(bounds.width, bounds.height); var texture = Texture.fromCanvas(canvasBuffer.canvas); @@ -943,7 +1030,8 @@ this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.buffer.resize(bounds.width, bounds.height); } @@ -968,7 +1056,8 @@ * * @private */ -Graphics.prototype.updateCachedSpriteTexture = function () { +Graphics.prototype.updateCachedSpriteTexture = function () +{ var cachedSprite = this._cachedSprite; var texture = cachedSprite.texture; var canvas = cachedSprite.buffer.canvas; @@ -989,7 +1078,8 @@ * Destroys a previous cached sprite. * */ -Graphics.prototype.destroyCachedSprite = function () { +Graphics.prototype.destroyCachedSprite = function () +{ this._cachedSprite.texture.destroy(true); // let the gc collect the unused sprite @@ -1003,10 +1093,13 @@ * @param {Circle|Rectangle|Ellipse|Line|Polygon} shape The Shape object to draw. * @return {GraphicsData} The generated GraphicsData object. */ -Graphics.prototype.drawShape = function (shape) { - if (this.currentPath) { +Graphics.prototype.drawShape = function (shape) +{ + if (this.currentPath) + { // check current path! - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath.shape.points.length <= 2) + { this.graphicsData.pop(); } } @@ -1017,7 +1110,8 @@ this.graphicsData.push(data); - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { data.shape.closed = this.filling; this.currentPath = data; } diff --git a/src/core/primitives/GraphicsData.js b/src/core/primitives/GraphicsData.js index 99decbe..788f6f2 100644 --- a/src/core/primitives/GraphicsData.js +++ b/src/core/primitives/GraphicsData.js @@ -4,7 +4,8 @@ * @class * @namespace PIXI */ -function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) { +function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) +{ this.lineWidth = lineWidth; this.lineColor = lineColor; this.lineAlpha = lineAlpha; @@ -27,7 +28,8 @@ * * @return {GraphicsData} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ return new GraphicsData( this.lineWidth, this.lineColor, diff --git a/src/core/renderers/canvas/CanvasRenderer.js b/src/core/renderers/canvas/CanvasRenderer.js index 15a0978..7aebd44 100644 --- a/src/core/renderers/canvas/CanvasRenderer.js +++ b/src/core/renderers/canvas/CanvasRenderer.js @@ -17,17 +17,22 @@ * @param [options.resolution=1] {number} the resolution of the renderer retina would be 2 * @param [options.clearBeforeRender=true] {boolean} This sets if the CanvasRenderer will clear the canvas or not before the new render pass. */ -function CanvasRenderer(width, height, options) { +function CanvasRenderer(width, height, options) +{ utils.sayHello('Canvas'); - if (options) { - for (var i in CONST.defaultRenderOptions) { - if (typeof options[i] === 'undefined') { + if (options) + { + for (var i in CONST.defaultRenderOptions) + { + if (typeof options[i] === 'undefined') + { options[i] = CONST.defaultRenderOptions[i]; } } } - else { + else + { options = CONST.defaultRenderOptions; } @@ -156,19 +161,24 @@ this.smoothProperty = null; - if (this.context.imageSmoothingEnabled) { + if (this.context.imageSmoothingEnabled) + { this.smoothProperty = 'imageSmoothingEnabled'; } - else if (this.context.webkitImageSmoothingEnabled) { + else if (this.context.webkitImageSmoothingEnabled) + { this.smoothProperty = 'webkitImageSmoothingEnabled'; } - else if (this.context.mozImageSmoothingEnabled) { + else if (this.context.mozImageSmoothingEnabled) + { this.smoothProperty = 'mozImageSmoothingEnabled'; } - else if (this.context.oImageSmoothingEnabled) { + else if (this.context.oImageSmoothingEnabled) + { this.smoothProperty = 'oImageSmoothingEnabled'; } - else if (this.context.msImageSmoothingEnabled) { + else if (this.context.msImageSmoothingEnabled) + { this.smoothProperty = 'msImageSmoothingEnabled'; } @@ -193,10 +203,12 @@ * @memberof CanvasRenderer# */ backgroundColor: { - get: function () { + get: function () + { return this._backgroundColor; }, - set: function (val) { + set: function (val) + { this._backgroundColor = val; this._backgroundColorString = utils.hex2string(val); } @@ -208,7 +220,8 @@ * * @param object {DisplayObject} the object to be rendered */ -CanvasRenderer.prototype.render = function (object) { +CanvasRenderer.prototype.render = function (object) +{ object.updateTransform(); this.context.setTransform(1,0,0,1,0,0); @@ -218,16 +231,20 @@ this.currentBlendMode = CONST.blendModes.NORMAL; this.context.globalCompositeOperation = this.blendModes[CONST.blendModes.NORMAL]; - if (navigator.isCocoonJS && this.view.screencanvas) { + if (navigator.isCocoonJS && this.view.screencanvas) + { this.context.fillStyle = 'black'; this.context.clear(); } - if (this.clearBeforeRender) { - if (this.transparent) { + if (this.clearBeforeRender) + { + if (this.transparent) + { this.context.clearRect(0, 0, this.width, this.height); } - else { + else + { this.context.fillStyle = this._backgroundColorString; this.context.fillRect(0, 0, this.width , this.height); } @@ -241,8 +258,10 @@ * * @param [removeView=false] {boolean} Removes the Canvas element from the DOM. */ -CanvasRenderer.prototype.destroy = function (removeView) { - if (removeView && this.view.parent) { +CanvasRenderer.prototype.destroy = function (removeView) +{ + if (removeView && this.view.parent) + { this.view.parent.removeChild(this.view); } @@ -257,14 +276,16 @@ * @param width {number} the new width of the canvas view * @param height {number} the new height of the canvas view */ -CanvasRenderer.prototype.resize = function (width, height) { +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) { + if (this.autoResize) + { this.view.style.width = this.width / this.resolution + 'px'; this.view.style.height = this.height / this.resolution + 'px'; } @@ -276,7 +297,8 @@ * @param displayObject {DisplayObject} The displayObject to render * @private */ -CanvasRenderer.prototype.renderDisplayObject = function (displayObject) { +CanvasRenderer.prototype.renderDisplayObject = function (displayObject) +{ displayObject.renderCanvas(this); }; @@ -285,11 +307,14 @@ * * @private */ -CanvasRenderer.prototype._mapBlendModes = function () { - if (!this.blendModes) { +CanvasRenderer.prototype._mapBlendModes = function () +{ + if (!this.blendModes) + { this.blendModes = {}; - if (utils.canUseNewCanvasBlendModes()) { + if (utils.canUseNewCanvasBlendModes()) + { this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? this.blendModes[CONST.blendModes.MULTIPLY] = 'multiply'; @@ -308,7 +333,8 @@ this.blendModes[CONST.blendModes.COLOR] = 'color'; this.blendModes[CONST.blendModes.LUMINOSITY] = 'luminosity'; } - else { + else + { // this means that the browser does not support the cool new blend modes in canvas 'cough' ie 'cough' this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? diff --git a/src/core/renderers/canvas/utils/CanvasBuffer.js b/src/core/renderers/canvas/utils/CanvasBuffer.js index ebe5d47..b183a66 100644 --- a/src/core/renderers/canvas/utils/CanvasBuffer.js +++ b/src/core/renderers/canvas/utils/CanvasBuffer.js @@ -6,7 +6,8 @@ * @param width {number} the width for the newly created canvas * @param height {number} the height for the newly created canvas */ -function CanvasBuffer(width, height) { +function CanvasBuffer(width, height) +{ /** * The Canvas object that belongs to this CanvasBuffer. * @@ -36,10 +37,12 @@ * @memberof CanvasBuffer# */ width: { - get: function () { + get: function () + { return this.canvas.width; }, - set: function (val) { + set: function (val) + { this.canvas.width = val; } }, @@ -50,10 +53,12 @@ * @memberof CanvasBuffer# */ height: { - get: function () { + get: function () + { return this.canvas.height; }, - set: function (val) { + set: function (val) + { this.canvas.height = val; } } @@ -64,7 +69,8 @@ * * @private */ -CanvasBuffer.prototype.clear = function () { +CanvasBuffer.prototype.clear = function () +{ this.context.setTransform(1, 0, 0, 1, 0, 0); this.context.clearRect(0,0, this.canvas.width, this.canvas.height); }; @@ -75,7 +81,8 @@ * @param width {number} the new width of the canvas * @param height {number} the new height of the canvas */ -CanvasBuffer.prototype.resize = function (width, height) { +CanvasBuffer.prototype.resize = function (width, height) +{ this.canvas.width = width; this.canvas.height = height; }; diff --git a/src/core/renderers/canvas/utils/CanvasGraphics.js b/src/core/renderers/canvas/utils/CanvasGraphics.js index c7eaa2a..3f2a91f 100644 --- a/src/core/renderers/canvas/utils/CanvasGraphics.js +++ b/src/core/renderers/canvas/utils/CanvasGraphics.js @@ -13,15 +13,18 @@ * @param graphics {Graphics} the actual graphics object to render * @param context {CanvasRenderingContext2D} the 2d drawing method of the canvas */ -CanvasGraphics.renderGraphics = function (graphics, context) { +CanvasGraphics.renderGraphics = function (graphics, context) +{ var worldAlpha = graphics.worldAlpha; - if (graphics.dirty) { + if (graphics.dirty) + { this.updateGraphicsTint(graphics); graphics.dirty = false; } - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; @@ -30,69 +33,82 @@ context.lineWidth = data.lineWidth; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { context.beginPath(); var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } - if (shape.closed) { + if (shape.closed) + { context.lineTo(points[0], points[1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fillRect(shape.x, shape.y, shape.width, shape.height); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.strokeRect(shape.x, shape.y, shape.width, shape.height); } } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.beginPath(); context.arc(shape.x, shape.y, shape.radius,0,2*Math.PI); context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas var w = shape.width * 2; @@ -119,18 +135,21 @@ context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; var width = shape.width; @@ -152,13 +171,15 @@ context.quadraticCurveTo(rx, ry, rx, ry + radius); context.closePath(); - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); @@ -174,45 +195,54 @@ * @param graphics {Graphics} the graphics which will be used as a mask * @param context {CanvasRenderingContext2D} the context 2d method of the canvas */ -CanvasGraphics.renderGraphicsMask = function (graphics, context) { +CanvasGraphics.renderGraphicsMask = function (graphics, context) +{ var len = graphics.graphicsData.length; - if (len === 0) { + if (len === 0) + { return; } context.beginPath(); - for (var i = 0; i < len; i++) { + for (var i = 0; i < len; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { context.rect(shape.x, shape.y, shape.width, shape.height); context.closePath(); } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.arc(shape.x, shape.y, shape.radius, 0, 2 * Math.PI); context.closePath(); } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas @@ -237,7 +267,8 @@ context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); context.closePath(); } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; @@ -262,8 +293,10 @@ } }; -CanvasGraphics.updateGraphicsTint = function (graphics) { - if (graphics.tint === 0xFFFFFF) { +CanvasGraphics.updateGraphicsTint = function (graphics) +{ + if (graphics.tint === 0xFFFFFF) + { return; } @@ -271,7 +304,8 @@ var tintG = (graphics.tint >> 8 & 0xFF) / 255; var tintB = (graphics.tint & 0xFF)/ 255; - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var fillColor = data.fillColor | 0; diff --git a/src/core/renderers/canvas/utils/CanvasMaskManager.js b/src/core/renderers/canvas/utils/CanvasMaskManager.js index e04a733..9827d36 100644 --- a/src/core/renderers/canvas/utils/CanvasMaskManager.js +++ b/src/core/renderers/canvas/utils/CanvasMaskManager.js @@ -6,7 +6,8 @@ * @class * @namespace PIXI */ -function CanvasMaskManager() {} +function CanvasMaskManager() +{} CanvasMaskManager.prototype.constructor = CanvasMaskManager; module.exports = CanvasMaskManager; @@ -17,7 +18,8 @@ * @param maskData {object} the maskData that will be pushed * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.pushMask = function (maskData, renderer) { +CanvasMaskManager.prototype.pushMask = function (maskData, renderer) +{ renderer.context.save(); var cacheAlpha = maskData.alpha; @@ -45,6 +47,7 @@ * * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.popMask = function (renderer) { +CanvasMaskManager.prototype.popMask = function (renderer) +{ renderer.context.restore(); }; diff --git a/src/core/renderers/canvas/utils/CanvasTinter.js b/src/core/renderers/canvas/utils/CanvasTinter.js index 17e0529..d2fb1bc 100644 --- a/src/core/renderers/canvas/utils/CanvasTinter.js +++ b/src/core/renderers/canvas/utils/CanvasTinter.js @@ -14,7 +14,8 @@ * @param color {number} the color to use to tint the sprite with * @return {HTMLCanvasElement} The tinted canvas */ -CanvasTinter.getTintedTexture = function (sprite, color) { +CanvasTinter.getTintedTexture = function (sprite, color) +{ var texture = sprite.texture; color = CanvasTinter.roundColor(color); @@ -23,7 +24,8 @@ texture.tintCache = texture.tintCache || {}; - if (texture.tintCache[stringColor]) { + if (texture.tintCache[stringColor]) + { return texture.tintCache[stringColor]; } @@ -33,14 +35,16 @@ //CanvasTinter.tintWithPerPixel(texture, stringColor, canvas); CanvasTinter.tintMethod(texture, color, canvas); - if (CanvasTinter.convertTintToImage) { + if (CanvasTinter.convertTintToImage) + { // is this better? var tintImage = new Image(); tintImage.src = canvas.toDataURL(); texture.tintCache[stringColor] = tintImage; } - else { + else + { texture.tintCache[stringColor] = canvas; // if we are not converting the texture to an image then we need to lose the reference to the canvas CanvasTinter.canvas = null; @@ -56,7 +60,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithMultiply = function (texture, color, canvas) { +CanvasTinter.tintWithMultiply = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -104,7 +109,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithOverlay = function (texture, color, canvas) { +CanvasTinter.tintWithOverlay = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -139,7 +145,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithPerPixel = function (texture, color, canvas) { +CanvasTinter.tintWithPerPixel = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -167,7 +174,8 @@ var pixels = pixelData.data; - for (var i = 0; i < pixels.length; i += 4) { + for (var i = 0; i < pixels.length; i += 4) + { pixels[i+0] *= r; pixels[i+1] *= g; pixels[i+2] *= b; @@ -181,7 +189,8 @@ * * @param color {number} the color to round, should be a hex color */ -CanvasTinter.roundColor = function (color) { +CanvasTinter.roundColor = function (color) +{ var step = CanvasTinter.cacheStepsPerColorChannel; var rgbValues = utils.hex2rgb(color); diff --git a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js index 9f2f89a..35edbaf 100644 --- a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js +++ b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLBlendModeManager(renderer) { +function WebGLBlendModeManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -23,8 +24,10 @@ * * @param blendMode {number} the blendMode, should be a Pixi const, such as BlendModes.ADD */ -WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) { - if (this.currentBlendMode === blendMode) { +WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) +{ + if (this.currentBlendMode === blendMode) + { return false; } diff --git a/src/core/renderers/webgl/managers/WebGLFilterManager.js b/src/core/renderers/webgl/managers/WebGLFilterManager.js index 1179258..2dac048 100644 --- a/src/core/renderers/webgl/managers/WebGLFilterManager.js +++ b/src/core/renderers/webgl/managers/WebGLFilterManager.js @@ -7,7 +7,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLFilterManager(renderer) { +function WebGLFilterManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -32,7 +33,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.texturePool.length = 0; self.initShaderBuffers(); }); @@ -46,7 +48,8 @@ * @param renderer {WebGLRenderer} * @param buffer {ArrayBuffer} */ -WebGLFilterManager.prototype.begin = function (buffer) { +WebGLFilterManager.prototype.begin = function (buffer) +{ this.defaultShader = this.renderer.shaderManager.defaultShader; this.width = this.renderer.projection.x * 2; @@ -60,7 +63,8 @@ * * @param filterBlock {object} the filter that will be pushed to the current filter stack */ -WebGLFilterManager.prototype.pushFilter = function (filterBlock) { +WebGLFilterManager.prototype.pushFilter = function (filterBlock) +{ var gl = this.renderer.gl; var projection = this.renderer.projection; @@ -78,10 +82,12 @@ this.offsetY += filterBlock._filterArea.y; var texture = this.texturePool.pop(); - if (!texture) { + if (!texture) + { texture = new FilterTexture(this.renderer.gl, this.width, this.height); } - else { + else + { texture.resize(this.width, this.height); } @@ -98,29 +104,35 @@ var localX = filterArea.x, localY = filterArea.y; - if (filterArea.x < 0) { + if (filterArea.x < 0) + { filterArea.width += filterArea.x; filterArea.x = 0; } - if (filterArea.y < 0) { + if (filterArea.y < 0) + { filterArea.height += filterArea.y; filterArea.y = 0; } - if (localX + filterArea.width > this.width) { + if (localX + filterArea.width > this.width) + { filterArea.width = this.width - localX; } - if (localY + filterArea.height > this.height) { + if (localY + filterArea.height > this.height) + { filterArea.height = this.height - localY; } - if (filterArea.width < 0) { + if (filterArea.width < 0) + { filterArea.width = 0; } - if (filterArea.height < 0) { + if (filterArea.height < 0) + { filterArea.height = 0; } @@ -154,7 +166,8 @@ * Removes the last filter from the filter stack and doesn't return it. * */ -WebGLFilterManager.prototype.popFilter = function () { +WebGLFilterManager.prototype.popFilter = function () +{ var gl = this.renderer.gl; var filterBlock = this.filterStack.pop(); @@ -163,7 +176,8 @@ var projection = this.renderer.projection; var offset = this.renderer.offset; - if (filterBlock.filterPasses.length > 1) { + if (filterBlock.filterPasses.length > 1) + { gl.viewport(0, 0, filterArea.width, filterArea.height); gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); @@ -193,7 +207,8 @@ var inputTexture = texture; var outputTexture = this.texturePool.pop(); - if (!outputTexture) { + if (!outputTexture) + { outputTexture = new FilterTexture(this.renderer.gl, this.width, this.height); } outputTexture.resize(this.width, this.height); @@ -204,7 +219,8 @@ gl.disable(gl.BLEND); - for (var i = 0; i < filterBlock.filterPasses.length-1; i++) { + for (var i = 0; i < filterBlock.filterPasses.length-1; i++) + { var filterPass = filterBlock.filterPasses[i]; gl.bindFramebuffer(gl.FRAMEBUFFER, outputTexture.frameBuffer ); @@ -243,10 +259,12 @@ var buffer = this.buffer; // time to render the filters texture to the previous scene - if (this.filterStack.length === 0) { + if (this.filterStack.length === 0) + { gl.colorMask(true, true, true, true);//this.transparent); } - else { + else + { var currentFilter = this.filterStack[this.filterStack.length-1]; filterArea = currentFilter._filterArea; @@ -332,13 +350,15 @@ * @param width {number} the horizontal range of the filter * @param height {number} the vertical range of the filter */ -WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) { +WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) +{ // use program var gl = this.renderer.gl; var shader = filter.shaders[gl.id]; - if (!shader) { + if (!shader) + { shader = new Shader(gl); shader.fragmentSrc = filter.fragmentSrc; @@ -356,7 +376,8 @@ gl.uniform2f(shader.projectionVector, width/2, -height/2); gl.uniform2f(shader.offsetVector, 0,0); - if (filter.uniforms.dimensions) { + 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]; @@ -386,7 +407,8 @@ * Initialises the shader buffers. * */ -WebGLFilterManager.prototype.initShaderBuffers = function () { +WebGLFilterManager.prototype.initShaderBuffers = function () +{ var gl = this.renderer.gl; // create some buffers @@ -432,7 +454,8 @@ * Destroys the filter and removes it from the filter stack. * */ -WebGLFilterManager.prototype.destroy = function () { +WebGLFilterManager.prototype.destroy = function () +{ var gl = this.renderer.gl; this.filterStack = null; @@ -441,7 +464,8 @@ this.offsetY = 0; // destroy textures - for (var i = 0; i < this.texturePool.length; i++) { + for (var i = 0; i < this.texturePool.length; i++) + { this.texturePool[i].destroy(); } diff --git a/src/core/renderers/webgl/managers/WebGLManager.js b/src/core/renderers/webgl/managers/WebGLManager.js index 9d47b5c..c30cd51 100644 --- a/src/core/renderers/webgl/managers/WebGLManager.js +++ b/src/core/renderers/webgl/managers/WebGLManager.js @@ -3,7 +3,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLManager(renderer) { +function WebGLManager(renderer) +{ /** * The renderer this manager works for. * @@ -15,6 +16,7 @@ WebGLManager.prototype.constructor = WebGLManager; module.exports = WebGLManager; -WebGLManager.prototype.destroy = function () { +WebGLManager.prototype.destroy = function () +{ this.renderer = null; }; diff --git a/src/core/renderers/webgl/managers/WebGLMaskManager.js b/src/core/renderers/webgl/managers/WebGLMaskManager.js index 2f90b64..e568812 100644 --- a/src/core/renderers/webgl/managers/WebGLMaskManager.js +++ b/src/core/renderers/webgl/managers/WebGLMaskManager.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLMaskManager(renderer) { +function WebGLMaskManager(renderer) +{ WebGLManager.call(this, renderer); } @@ -19,12 +20,15 @@ * * @param maskData {any[]} */ -WebGLMaskManager.prototype.pushMask = function (maskData) { - if (maskData.dirty) { +WebGLMaskManager.prototype.pushMask = function (maskData) +{ + if (maskData.dirty) + { WebGLGraphics.updateGraphics(maskData, this.renderer.gl); } - if (!maskData._webGL[this.renderer.gl.id].data.length) { + if (!maskData._webGL[this.renderer.gl.id].data.length) + { return; } @@ -36,6 +40,7 @@ * * @param maskData {any[]} */ -WebGLMaskManager.prototype.popMask = function (maskData) { +WebGLMaskManager.prototype.popMask = function (maskData) +{ this.renderer.stencilManager.popStencil(maskData, maskData._webGL[this.renderer.gl.id].data[0], this.renderer); }; diff --git a/src/core/renderers/webgl/managers/WebGLShaderManager.js b/src/core/renderers/webgl/managers/WebGLShaderManager.js index fef071c..90c6477 100644 --- a/src/core/renderers/webgl/managers/WebGLShaderManager.js +++ b/src/core/renderers/webgl/managers/WebGLShaderManager.js @@ -10,7 +10,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLShaderManager(renderer) { +function WebGLShaderManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -28,7 +29,8 @@ */ this.tempAttribState = []; - for (var i = 0; i < this.maxAttibs; i++) { + for (var i = 0; i < this.maxAttibs; i++) + { this.attribState[i] = false; } @@ -66,7 +68,8 @@ // listen for context and update necessary shaders var self = this; - this.renderer.on('context', function (event) { + this.renderer.on('context', function (event) + { var gl = event.data; // this shader is used for rendering primitives @@ -97,29 +100,36 @@ * * @param attribs {Array} attribs */ -WebGLShaderManager.prototype.setAttribs = function (attribs) { +WebGLShaderManager.prototype.setAttribs = function (attribs) +{ // reset temp state var i; - for (i = 0; i < this.tempAttribState.length; i++) { + for (i = 0; i < this.tempAttribState.length; i++) + { this.tempAttribState[i] = false; } // set the new attribs - for (var a in attribs) { + for (var a in attribs) + { this.tempAttribState[attribs[a]] = true; } var gl = this.renderer.gl; - for (i = 0; i < this.attribState.length; i++) { - if (this.attribState[i] !== this.tempAttribState[i]) { + for (i = 0; i < this.attribState.length; i++) + { + if (this.attribState[i] !== this.tempAttribState[i]) + { this.attribState[i] = this.tempAttribState[i]; - if (this.attribState[i]) { + if (this.attribState[i]) + { gl.enableVertexAttribArray(i); } - else { + else + { gl.disableVertexAttribArray(i); } } @@ -131,8 +141,10 @@ * * @param shader {Any} */ -WebGLShaderManager.prototype.setShader = function (shader) { - if (this._currentId === shader.uuid) { +WebGLShaderManager.prototype.setShader = function (shader) +{ + if (this._currentId === shader.uuid) + { return false; } @@ -150,7 +162,8 @@ * Destroys this object. * */ -WebGLShaderManager.prototype.destroy = function () { +WebGLShaderManager.prototype.destroy = function () +{ this.attribState = null; this.tempAttribState = null; diff --git a/src/core/renderers/webgl/managers/WebGLStencilManager.js b/src/core/renderers/webgl/managers/WebGLStencilManager.js index 9ec6398..4cb0134 100644 --- a/src/core/renderers/webgl/managers/WebGLStencilManager.js +++ b/src/core/renderers/webgl/managers/WebGLStencilManager.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLStencilManager(renderer) { +function WebGLStencilManager(renderer) +{ WebGLManager.call(this, renderer); this.stencilStack = []; @@ -24,12 +25,14 @@ * @param graphics {Graphics} * @param webGLData {any[]} */ -WebGLStencilManager.prototype.pushStencil = function (graphics, webGLData) { +WebGLStencilManager.prototype.pushStencil = function (graphics, webGLData) +{ var gl = this.renderer.gl; this.bindGraphics(graphics, webGLData, this.renderer); - if (this.stencilStack.length === 0) { + if (this.stencilStack.length === 0) + { gl.enable(gl.STENCIL_TEST); gl.clear(gl.STENCIL_BUFFER_BIT); this.reverse = true; @@ -47,14 +50,17 @@ // draw the triangle strip! - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } @@ -62,31 +68,38 @@ // draw a quad to increment.. gl.drawElements(gl.TRIANGLE_FAN, 4, gl.UNSIGNED_SHORT, ( webGLData.indices.length - 4 ) * 2 ); - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); } this.reverse = !this.reverse; } - else { - if (!this.reverse) { + else + { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } - else { + 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) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); } } @@ -103,7 +116,8 @@ * @param graphics {Graphics} * @param webGLData {Array} */ -WebGLStencilManager.prototype.bindGraphics = function (graphics, webGLData) { +WebGLStencilManager.prototype.bindGraphics = function (graphics, webGLData) +{ //if (this._currentGraphics === graphics)return; this._currentGraphics = graphics; @@ -114,7 +128,8 @@ offset = this.renderer.offset, shader;// = this.renderer.shaderManager.primitiveShader; - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { shader = this.renderer.shaderManager.complexPrimitiveShader; this.renderer.shaderManager.setShader(shader); @@ -141,7 +156,8 @@ // set the index buffer! gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, webGLData.indexBuffer); } - else { + else + { //this.renderer.shaderManager.activatePrimitiveShader(); shader = this.renderer.shaderManager.primitiveShader; this.renderer.shaderManager.setShader( shader ); @@ -154,7 +170,7 @@ gl.uniform2f(shader.uniforms.offsetVector._location, -offset.x, -offset.y); gl.uniform3fv(shader.uniforms.tint._location, utils.hex2rgb(graphics.tint)); - + gl.uniform1f(shader.uniforms.alpha._location, graphics.worldAlpha); @@ -172,19 +188,22 @@ * @param graphics {Graphics} * @param webGLData {Array} */ -WebGLStencilManager.prototype.popStencil = function (graphics, webGLData) { +WebGLStencilManager.prototype.popStencil = function (graphics, webGLData) +{ var gl = this.renderer.gl; this.stencilStack.pop(); this.count--; - if (this.stencilStack.length === 0) { + if (this.stencilStack.length === 0) + { // the stack is empty! gl.disable(gl.STENCIL_TEST); } - else { + else + { var level = this.count; @@ -192,14 +211,17 @@ gl.colorMask(false, false, false, false); - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { this.reverse = !this.reverse; - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } @@ -213,31 +235,38 @@ // draw the triangle strip! gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); - if (!this.reverse) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); } } - else { + else + { // console.log("<<>>") - if (!this.reverse) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } - else { + 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) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); } } @@ -253,7 +282,8 @@ * Destroys the mask stack. * */ -WebGLStencilManager.prototype.destroy = function () { +WebGLStencilManager.prototype.destroy = function () +{ this.renderer = null; this.stencilStack = null; }; diff --git a/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js b/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js index 913ba5e..1ea7d19 100644 --- a/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js +++ b/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function ComplexPrimitiveShader(gl) { +function ComplexPrimitiveShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -24,7 +25,8 @@ 'uniform float flipY;', 'varying vec4 vColor;', - 'void main(void) {', + '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);', @@ -37,7 +39,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = vColor;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/FastShader.js b/src/core/renderers/webgl/shaders/FastShader.js index bd2e29a..2e5e060 100644 --- a/src/core/renderers/webgl/shaders/FastShader.js +++ b/src/core/renderers/webgl/shaders/FastShader.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function FastShader(gl) { +function FastShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -28,7 +29,8 @@ 'const vec2 center = vec2(-1.0, 1.0);', - 'void main(void) {', + 'void main(void) + {', ' vec2 v;', ' vec2 sv = aVertexPosition * aScale;', ' v.x = (sv.x) * cos(aRotation) - (sv.y) * sin(aRotation);', @@ -49,7 +51,8 @@ 'uniform sampler2D uSampler;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/PrimitiveShader.js b/src/core/renderers/webgl/shaders/PrimitiveShader.js index 6f25409..a25f54f 100644 --- a/src/core/renderers/webgl/shaders/PrimitiveShader.js +++ b/src/core/renderers/webgl/shaders/PrimitiveShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function PrimitiveShader(gl) { +function PrimitiveShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -23,7 +24,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + '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);', @@ -36,7 +38,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = vColor;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/Shader.js b/src/core/renderers/webgl/shaders/Shader.js index f8964f5..fd75ef5 100644 --- a/src/core/renderers/webgl/shaders/Shader.js +++ b/src/core/renderers/webgl/shaders/Shader.js @@ -6,7 +6,8 @@ * @param [fragmentSrc] {string} The source of the fragment shader. * @param [vertexSrc] {string} The source of the vertex shader. */ -function Shader(gl, vertexSrc, fragmentSrc, customUniforms, customAttributes) { +function Shader(gl, vertexSrc, fragmentSrc, customUniforms, customAttributes) +{ /** * @member {number} * @readonly @@ -33,7 +34,8 @@ dimensions: { type: '4f', value: new Float32Array(4) } }; - for (var u in customUniforms) { + for (var u in customUniforms) + { this.uniforms[u] = customUniforms[u]; } @@ -43,7 +45,8 @@ aColor: 0 }; - for (var a in customAttributes) { + for (var a in customAttributes) + { this.attributes[a] = customAttributes[a]; } @@ -66,7 +69,8 @@ 'const vec2 center = vec2(-1.0, 1.0);', - 'void main(void) {', + 'void main(void) + {', ' gl_Position = vec4( ((aVertexPosition + offsetVector) / projectionVector) + center , 0.0, 1.0);', ' vTextureCoord = aTextureCoord;', ' vColor = vec4(aColor.rgb * aColor.a, aColor.a);', @@ -85,7 +89,8 @@ 'uniform sampler2D uSampler;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;', '}' ].join('\n'); @@ -96,7 +101,8 @@ Shader.prototype.constructor = Shader; module.exports = Shader; -Shader.prototype.init = function () { +Shader.prototype.init = function () +{ this.compile(); this.gl.useProgram(this.program); @@ -105,14 +111,18 @@ this.cacheAttributeLocations(Object.keys(this.attributes)); }; -Shader.prototype.cacheUniformLocations = function (keys) { - for (var i = 0; i < keys.length; ++i) { +Shader.prototype.cacheUniformLocations = function (keys) +{ + for (var i = 0; i < keys.length; ++i) + { this.uniforms[keys[i]]._location = this.gl.getUniformLocation(this.program, keys[i]); } }; -Shader.prototype.cacheAttributeLocations = function (keys) { - for (var i = 0; i < keys.length; ++i) { +Shader.prototype.cacheAttributeLocations = function (keys) +{ + for (var i = 0; i < keys.length; ++i) + { this.attributes[keys[i]] = this.gl.getAttribLocation(this.program, keys[i]); } @@ -124,14 +134,16 @@ // 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.attributes.aColor === -1) { + // if (this.attributes.aColor === -1) + { // this.attributes.aColor = 2; // } // End worst hack eva // }; -Shader.prototype.compile = function () { +Shader.prototype.compile = function () +{ var gl = this.gl; var glVertShader = this._glCompile(gl.VERTEX_SHADER, this.vertexSrc); @@ -144,13 +156,15 @@ gl.linkProgram(program); // if linking fails, then log and cleanup - if (!gl.getProgramParameter(program, gl.LINK_STATUS)) { + if (!gl.getProgramParameter(program, gl.LINK_STATUS)) + { window.console.error('Pixi.js Error: Could not initialize shader.'); window.console.error('gl.VALIDATE_STATUS', gl.getProgramParameter(program, gl.VALIDATE_STATUS)); window.console.error('gl.getError()', gl.getError()); // if there is a program info log, log it - if (gl.getProgramInfoLog(program) !== '') { + if (gl.getProgramInfoLog(program) !== '') + { window.console.warn('Pixi.js Warning: gl.getProgramInfoLog()', gl.getProgramInfoLog(program)); } @@ -165,18 +179,21 @@ return (this.program = program); }; -Shader.prototype.syncUniforms = function () { +Shader.prototype.syncUniforms = function () +{ var gl = this.gl; this.textureCount = 1; - for (var key in this.uniforms) { + for (var key in this.uniforms) + { var uniform = this.uniforms[key], location = uniform._location, value = uniform.value, i, il; - switch (uniform.type) { + switch (uniform.type) + { // single int value case 'i': case '1i': @@ -282,7 +299,8 @@ // a Color Value case 'c': - if (typeof value === 'number') { + if (typeof value === 'number') + { value = utils.hex2rgb(value); } @@ -311,11 +329,13 @@ // array of 2D Point objects case 'v2v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(2 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 2] = value[i].x; uniform._array[i * 2 + 1] = value[i].y; } @@ -325,11 +345,13 @@ // array of 3D Point objects case 'v3v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(3 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 3] = value[i].x; uniform._array[i * 3 + 1] = value[i].y; uniform._array[i * 3 + 2] = value[i].z; @@ -341,11 +363,13 @@ // array of 4D Point objects case 'v4v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(4 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 4] = value[i].x; uniform._array[i * 4 + 1] = value[i].y; uniform._array[i * 4 + 2] = value[i].z; @@ -359,7 +383,8 @@ // PIXI.Texture case 't': case 'sampler2D': - if (!uniform.value || !uniform.value.baseTexture || !uniform.value.baseTexture.hasLoaded) { + if (!uniform.value || !uniform.value.baseTexture || !uniform.value.baseTexture.hasLoaded) + { break; } @@ -376,7 +401,8 @@ this.textureCount++; // initialize the texture if we haven't yet - if (!uniform._init) { + if (!uniform._init) + { this.initSampler2D(uniform); uniform._init = true; @@ -394,11 +420,13 @@ * Initialises a Sampler2D uniform (which may only be available later on after initUniforms once the texture has loaded) * */ -Shader.prototype.initSampler2D = function (uniform) { +Shader.prototype.initSampler2D = function (uniform) +{ var gl = this.gl; // Extended texture data - if (uniform.textureData) { + if (uniform.textureData) + { var data = uniform.textureData; // GLTexture = mag linear, min linear_mipmap_linear, wrap repeat + gl.generateMipmap(gl.TEXTURE_2D); @@ -417,14 +445,16 @@ var wrapT = (data.wrapT) ? data.wrapT : gl.CLAMP_TO_EDGE; var format = (data.luminance) ? gl.LUMINANCE : gl.RGBA; - if (data.repeat) { + if (data.repeat) + { wrapS = gl.REPEAT; wrapT = gl.REPEAT; } gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, !!data.flipY); - if (data.width) { + if (data.width) + { var width = (data.width) ? data.width : 512; var height = (data.height) ? data.height : 2; var border = (data.border) ? data.border : 0; @@ -432,7 +462,8 @@ // 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 { + 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); } @@ -448,7 +479,8 @@ * Destroys the shader. * */ -Shader.prototype.destroy = function () { +Shader.prototype.destroy = function () +{ this.gl.deleteProgram(this.program); this.gl = null; @@ -459,13 +491,15 @@ this.fragmentSrc = null; }; -Shader.prototype._glCompile = function (type, src) { +Shader.prototype._glCompile = function (type, src) +{ var shader = this.gl.createShader(type); this.gl.shaderSource(shader, src); this.gl.compileShader(shader); - if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) { + if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) + { window.console.log(this.gl.getShaderInfoLog(shader)); return null; } diff --git a/src/core/renderers/webgl/shaders/StripShader.js b/src/core/renderers/webgl/shaders/StripShader.js index 193f6e1..a7abcc6 100644 --- a/src/core/renderers/webgl/shaders/StripShader.js +++ b/src/core/renderers/webgl/shaders/StripShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function StripShader(gl) { +function StripShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -20,7 +21,8 @@ 'varying vec2 vTextureCoord;', - 'void main(void) {', + '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);', @@ -36,7 +38,8 @@ 'varying vec2 vTextureCoord;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vec2(vTextureCoord.x, vTextureCoord.y)) * alpha;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/utils/FilterTexture.js b/src/core/renderers/webgl/utils/FilterTexture.js index d2c8423..4433d44 100644 --- a/src/core/renderers/webgl/utils/FilterTexture.js +++ b/src/core/renderers/webgl/utils/FilterTexture.js @@ -8,7 +8,8 @@ * @param height {number} the vertical range of the filter * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values */ -function FilterTexture(gl, width, height, scaleMode) { +function FilterTexture(gl, width, height, scaleMode) +{ /** * @member {WebGLContext} */ @@ -59,7 +60,8 @@ * Clears the filter texture. * */ -FilterTexture.prototype.clear = function () { +FilterTexture.prototype.clear = function () +{ var gl = this.gl; gl.clearColor(0,0,0, 0); @@ -72,8 +74,10 @@ * @param width {number} the new width of the texture * @param height {number} the new height of the texture */ -FilterTexture.prototype.resize = function (width, height) { - if (this.width === width && this.height === height) { +FilterTexture.prototype.resize = function (width, height) +{ + if (this.width === width && this.height === height) + { return; } @@ -96,7 +100,8 @@ * Destroys the filter texture. * */ -FilterTexture.prototype.destroy = function () { +FilterTexture.prototype.destroy = function () +{ var gl = this.gl; gl.deleteFramebuffer( this.frameBuffer ); gl.deleteTexture( this.texture ); diff --git a/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js b/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js index c4721e9..a63f4d7 100644 --- a/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js +++ b/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js @@ -14,7 +14,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this sprite batch works for. */ -function WebGLFastSpriteBatch(renderer) { +function WebGLFastSpriteBatch(renderer) +{ /** * The renderer instance this sprite batch operates on. * @@ -91,7 +92,8 @@ */ this.lastIndexCount = 0; - for (var i=0, j=0; i < numIndices; i += 6, j += 4) { + 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; @@ -144,7 +146,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.setupContext(); }); } @@ -157,7 +160,8 @@ * * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLFastSpriteBatch.prototype.setupContext = function () { +WebGLFastSpriteBatch.prototype.setupContext = function () +{ var gl = this.renderer.gl; // create a couple of buffers @@ -177,7 +181,8 @@ /** * @param spriteBatch {SpriteBatch} The SpriteBatch container to prepare for. */ -WebGLFastSpriteBatch.prototype.begin = function (spriteBatch) { +WebGLFastSpriteBatch.prototype.begin = function (spriteBatch) +{ this.shader = this.renderer.shaderManager.fastShader; this.matrix = spriteBatch.worldTransform.toArray(true); @@ -187,33 +192,38 @@ /** */ -WebGLFastSpriteBatch.prototype.end = function () { +WebGLFastSpriteBatch.prototype.end = function () +{ this.flush(); }; /** * @param spriteBatch {SpriteBatch} The SpriteBatch container to render. */ -WebGLFastSpriteBatch.prototype.render = function (spriteBatch) { +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) { + if (!sprite.texture._uvs) + { return; } this.currentBaseTexture = sprite.texture.baseTexture; // check blend mode - if (sprite.blendMode !== this.renderer.blendModeManager.currentBlendMode) { + if (sprite.blendMode !== this.renderer.blendModeManager.currentBlendMode) + { this.flush(); this.renderer.blendModeManager.setBlendMode(sprite.blendMode); } - for (var i=0,j= children.length; i= this.size) { + if (this.currentBatchSize >= this.size) + { this.flush(); } }; @@ -362,29 +379,35 @@ /** * */ -WebGLFastSpriteBatch.prototype.flush = function () { +WebGLFastSpriteBatch.prototype.flush = function () +{ // If the batch is length 0 then return as there is nothing to draw - if (this.currentBatchSize === 0) { + if (this.currentBatchSize === 0) + { return; } var gl = this.renderer.gl; // bind the current texture - if (!this.currentBaseTexture._glTextures[gl.id]) { + if (!this.currentBaseTexture._glTextures[gl.id]) + { this.renderer.updateTexture(this.currentBaseTexture, gl); } //TODO-SHOUD THIS BE ELSE??!?!?! - else { + else + { gl.bindTexture(gl.TEXTURE_2D, this.currentBaseTexture._glTextures[gl.id]); } // upload the verts to the buffer - if (this.currentBatchSize > ( this.size * 0.5 ) ) { + if (this.currentBatchSize > ( this.size * 0.5 ) ) + { gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); } - else { + else + { var view = this.vertices.subarray(0, this.currentBatchSize * this.vertByteSize); gl.bufferSubData(gl.ARRAY_BUFFER, 0, view); @@ -405,14 +428,16 @@ * Ends the batch and flushes * */ -WebGLFastSpriteBatch.prototype.stop = function () { +WebGLFastSpriteBatch.prototype.stop = function () +{ this.flush(); }; /** * */ -WebGLFastSpriteBatch.prototype.start = function () { +WebGLFastSpriteBatch.prototype.start = function () +{ var gl = this.renderer.gl; // bind the main texture diff --git a/src/core/renderers/webgl/utils/WebGLGraphics.js b/src/core/renderers/webgl/utils/WebGLGraphics.js index 55f4911..ab8f46e 100644 --- a/src/core/renderers/webgl/utils/WebGLGraphics.js +++ b/src/core/renderers/webgl/utils/WebGLGraphics.js @@ -19,7 +19,8 @@ * @param graphics {Graphics} * @param renderer {WebGLRenderer} */ -WebGLGraphics.renderGraphics = function (graphics, renderer) {//projection, offset) { +WebGLGraphics.renderGraphics = function (graphics, renderer) {//projection, offset) +{ var gl = renderer.gl; var projection = renderer.projection, @@ -27,7 +28,8 @@ shader = renderer.shaderManager.primitiveShader, webGLData; - if (graphics.dirty) { + if (graphics.dirty) + { WebGLGraphics.updateGraphics(graphics, gl); } @@ -35,8 +37,10 @@ // This could be speeded up for sure! - for (var i = 0; i < webGL.data.length; i++) { - if (webGL.data[i].mode === 1) { + for (var i = 0; i < webGL.data.length; i++) + { + if (webGL.data[i].mode === 1) + { webGLData = webGL.data[i]; renderer.stencilManager.pushStencil(graphics, webGLData, renderer); @@ -46,7 +50,8 @@ renderer.stencilManager.popStencil(graphics, webGLData, renderer); } - else { + else + { webGLData = webGL.data[i]; @@ -84,12 +89,14 @@ * @param graphicsData {Graphics} The graphics object to update * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLGraphics.updateGraphics = function (graphics, gl) { +WebGLGraphics.updateGraphics = function (graphics, gl) +{ // get the contexts graphics object var webGL = graphics._webGL[gl.id]; // if the graphics object does not exist in the webGL context time to create it! - if (!webGL) { + if (!webGL) + { webGL = graphics._webGL[gl.id] = {lastIndex:0, data:[], gl:gl}; } @@ -99,11 +106,13 @@ var i; // if the user cleared the graphics object we will need to clear every object - if (graphics.clearDirty) { + if (graphics.clearDirty) + { graphics.clearDirty = false; // lop through and return all the webGLDatas to the object pool so than can be reused later on - for (i = 0; i < webGL.data.length; i++) { + for (i = 0; i < webGL.data.length; i++) + { var graphicsData = webGL.data[i]; graphicsData.reset(); WebGLGraphics.graphicsDataPool.push( graphicsData ); @@ -119,58 +128,72 @@ // loop through the graphics datas and construct each one.. // if the object is a complex fill then the new stencil buffer technique will be used // other wise graphics objects will be pushed into a batch.. - for (i = webGL.lastIndex; i < graphics.graphicsData.length; i++) { + for (i = webGL.lastIndex; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { // need to add the points the the graphics object.. data.points = data.shape.points.slice(); - if (data.shape.closed) { + if (data.shape.closed) + { // close the poly if the value is true! - if (data.points[0] !== data.points[data.points.length-2] || data.points[1] !== data.points[data.points.length-1]) { + if (data.points[0] !== data.points[data.points.length-2] || data.points[1] !== data.points[data.points.length-1]) + { data.points.push(data.points[0], data.points[1]); } } // MAKE SURE WE HAVE THE CORRECT TYPE.. - if (data.fill) { - if (data.points.length >= 6) { - if (data.points.length < 6 * 2) { + if (data.fill) + { + if (data.points.length >= 6) + { + if (data.points.length < 6 * 2) + { webGLData = WebGLGraphics.switchMode(webGL, 0); var canDrawUsingSimple = WebGLGraphics.buildPoly(data, webGLData); // console.log(canDrawUsingSimple); - if (!canDrawUsingSimple) { + if (!canDrawUsingSimple) + { // console.log("<>>>") webGLData = WebGLGraphics.switchMode(webGL, 1); WebGLGraphics.buildComplexPoly(data, webGLData); } } - else { + else + { webGLData = WebGLGraphics.switchMode(webGL, 1); WebGLGraphics.buildComplexPoly(data, webGLData); } } } - if (data.lineWidth > 0) { + if (data.lineWidth > 0) + { webGLData = WebGLGraphics.switchMode(webGL, 0); WebGLGraphics.buildLine(data, webGLData); } } - else { + else + { webGLData = WebGLGraphics.switchMode(webGL, 0); - if (data.type === CONST.SHAPES.RECT) { + if (data.type === CONST.SHAPES.RECT) + { WebGLGraphics.buildRectangle(data, webGLData); } - else if (data.type === CONST.SHAPES.CIRC || data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.CIRC || data.type === CONST.SHAPES.ELIP) + { WebGLGraphics.buildCircle(data, webGLData); } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { WebGLGraphics.buildRoundedRectangle(data, webGLData); } } @@ -179,10 +202,12 @@ } // upload all the dirty data... - for (i = 0; i < webGL.data.length; i++) { + for (i = 0; i < webGL.data.length; i++) + { webGLData = webGL.data[i]; - if (webGLData.dirty) { + if (webGLData.dirty) + { webGLData.upload(); } } @@ -194,18 +219,22 @@ * @param webGL {WebGLContext} * @param type {number} */ -WebGLGraphics.switchMode = function (webGL, type) { +WebGLGraphics.switchMode = function (webGL, type) +{ var webGLData; - if (!webGL.data.length) { + if (!webGL.data.length) + { webGLData = WebGLGraphics.graphicsDataPool.pop() || new WebGLGraphicsData(webGL.gl); webGLData.mode = type; webGL.data.push(webGLData); } - else { + else + { webGLData = webGL.data[webGL.data.length-1]; - if (webGLData.mode !== type || type === 1) { + if (webGLData.mode !== type || type === 1) + { webGLData = WebGLGraphics.graphicsDataPool.pop() || new WebGLGraphicsData(webGL.gl); webGLData.mode = type; webGL.data.push(webGLData); @@ -225,7 +254,8 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildRectangle = function (graphicsData, webGLData) { +WebGLGraphics.buildRectangle = function (graphicsData, webGLData) +{ // --- // // need to convert points to a nice regular data // @@ -235,7 +265,8 @@ var width = rectData.width; var height = rectData.height; - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -265,7 +296,8 @@ indices.push(vertPos, vertPos, vertPos+1, vertPos+2, vertPos+3, vertPos+3); } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = [x, y, @@ -289,7 +321,8 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildRoundedRectangle = function (graphicsData, webGLData) { +WebGLGraphics.buildRoundedRectangle = function (graphicsData, webGLData) +{ var rrectData = graphicsData.shape; var x = rrectData.x; var y = rrectData.y; @@ -305,7 +338,8 @@ recPoints = recPoints.concat(WebGLGraphics.quadraticBezierCurve(x + width, y + radius, x + width, y, x + width - radius, y)); recPoints = recPoints.concat(WebGLGraphics.quadraticBezierCurve(x + radius, y, x, y, x, y + radius)); - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -323,7 +357,8 @@ // var i = 0; - for (i = 0; i < triangles.length; i+=3) { + for (i = 0; i < triangles.length; i+=3) + { indices.push(triangles[i] + vecPos); indices.push(triangles[i] + vecPos); indices.push(triangles[i+1] + vecPos); @@ -332,12 +367,14 @@ } - for (i = 0; i < recPoints.length; i++) { + for (i = 0; i < recPoints.length; i++) + { verts.push(recPoints[i], recPoints[++i], r, g, b, alpha); } } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = recPoints; @@ -362,7 +399,8 @@ * @param toY {number} Destination point y * @return {number[]} */ -WebGLGraphics.quadraticBezierCurve = function (fromX, fromY, cpX, cpY, toX, toY) { +WebGLGraphics.quadraticBezierCurve = function (fromX, fromY, cpX, cpY, toX, toY) +{ var xa, ya, @@ -373,14 +411,16 @@ n = 20, points = []; - function getPt(n1 , n2, perc) { + function getPt(n1 , n2, perc) + { var diff = n2 - n1; return n1 + ( diff * perc ); } var j = 0; - for (var i = 0; i <= n; i++ ) { + for (var i = 0; i <= n; i++ ) + { j = i / n; // The Green Line @@ -406,7 +446,8 @@ * @param graphicsData {Graphics} The graphics object to draw * @param webGLData {object} */ -WebGLGraphics.buildCircle = function (graphicsData, webGLData) { +WebGLGraphics.buildCircle = function (graphicsData, webGLData) +{ // need to convert points to a nice regular data var circleData = graphicsData.shape; var x = circleData.x; @@ -415,11 +456,13 @@ var height; // TODO - bit hacky?? - if (graphicsData.type === CONST.SHAPES.CIRC) { + if (graphicsData.type === CONST.SHAPES.CIRC) + { width = circleData.radius; height = circleData.radius; } - else { + else + { width = circleData.width; height = circleData.height; } @@ -429,7 +472,8 @@ var i = 0; - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -444,7 +488,8 @@ indices.push(vecPos); - for (i = 0; i < totalSegs + 1 ; i++) { + for (i = 0; i < totalSegs + 1 ; i++) + { verts.push(x,y, r, g, b, alpha); verts.push(x + Math.sin(seg * i) * width, @@ -457,12 +502,14 @@ indices.push(vecPos-1); } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = []; - for (i = 0; i < totalSegs + 1; i++) { + for (i = 0; i < totalSegs + 1; i++) + { graphicsData.points.push(x + Math.sin(seg * i) * width, y + Math.cos(seg * i) * height); } @@ -481,18 +528,22 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildLine = function (graphicsData, webGLData) { +WebGLGraphics.buildLine = function (graphicsData, webGLData) +{ // TODO OPTIMISE! var i = 0; var points = graphicsData.points; - if (points.length === 0) { + if (points.length === 0) + { return; } // if the line width is an odd number add 0.5 to align to a whole pixel - if (graphicsData.lineWidth%2) { - for (i = 0; i < points.length; i++) { + if (graphicsData.lineWidth%2) + { + for (i = 0; i < points.length; i++) + { points[i] += 0.5; } } @@ -502,7 +553,8 @@ var lastPoint = new math.Point(points[points.length - 2], points[points.length - 1]); // if the first point is the last point - gonna have issues :) - if (firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) { + if (firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) + { // need to clone as we are going to slightly modify the shape.. points = points.slice(); @@ -562,7 +614,8 @@ verts.push(p1x + perpx , p1y + perpy, r, g, b, alpha); - for (i = 1; i < length-1; i++) { + for (i = 1; i < length-1; i++) + { p1x = points[(i-1)*2]; p1y = points[(i-1)*2 + 1]; @@ -599,7 +652,8 @@ denom = a1*b2 - a2*b1; - if (Math.abs(denom) < 0.1 ) { + if (Math.abs(denom) < 0.1 ) + { denom+=10.1; verts.push(p2x - perpx , p2y - perpy, @@ -618,7 +672,8 @@ pdist = (px -p2x) * (px -p2x) + (py -p2y) + (py -p2y); - if (pdist > 140 * 140) { + if (pdist > 140 * 140) + { perp3x = perpx - perp2x; perp3y = perpy - perp2y; @@ -639,7 +694,8 @@ indexCount++; } - else { + else + { verts.push(px , py); verts.push(r, g, b, alpha); @@ -672,7 +728,8 @@ indices.push(indexStart); - for (i = 0; i < indexCount; i++) { + for (i = 0; i < indexCount; i++) + { indices.push(indexStart++); } @@ -687,11 +744,13 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildComplexPoly = function (graphicsData, webGLData) { +WebGLGraphics.buildComplexPoly = function (graphicsData, webGLData) +{ //TODO - no need to copy this as it gets turned into a FLoat32Array anyways.. var points = graphicsData.points.slice(); - if (points.length < 6) { + if (points.length < 6) + { return; } @@ -711,7 +770,8 @@ var x,y; // get size.. - for (var i = 0; i < points.length; i+=2) { + for (var i = 0; i < points.length; i+=2) + { x = points[i]; y = points[i+1]; @@ -732,7 +792,8 @@ //TODO - this aint needed! var length = points.length / 2; - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { indices.push( i ); } @@ -746,10 +807,12 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildPoly = function (graphicsData, webGLData) { +WebGLGraphics.buildPoly = function (graphicsData, webGLData) +{ var points = graphicsData.points; - if (points.length < 6) { + if (points.length < 6) + { return; } // get first and last point.. figure out the middle! @@ -767,7 +830,8 @@ var triangles = utils.PolyK.Triangulate(points); - if (!triangles) { + if (!triangles) + { return false; } @@ -775,7 +839,8 @@ var i = 0; - for (i = 0; i < triangles.length; i+=3) { + for (i = 0; i < triangles.length; i+=3) + { indices.push(triangles[i] + vertPos); indices.push(triangles[i] + vertPos); indices.push(triangles[i+1] + vertPos); @@ -783,7 +848,8 @@ indices.push(triangles[i+2] + vertPos); } - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { verts.push(points[i * 2], points[i * 2 + 1], r, g, b, alpha); } diff --git a/src/core/renderers/webgl/utils/WebGLGraphicsData.js b/src/core/renderers/webgl/utils/WebGLGraphicsData.js index c56d05e..c739ba7 100644 --- a/src/core/renderers/webgl/utils/WebGLGraphicsData.js +++ b/src/core/renderers/webgl/utils/WebGLGraphicsData.js @@ -2,7 +2,8 @@ * @class * @private */ -function WebGLGraphicsData(gl) { +function WebGLGraphicsData(gl) +{ this.gl = gl; //TODO does this need to be split before uploding?? @@ -22,7 +23,8 @@ /** * */ -WebGLGraphicsData.prototype.reset = function () { +WebGLGraphicsData.prototype.reset = function () +{ this.points.length = 0; this.indices.length = 0; }; @@ -30,7 +32,8 @@ /** * */ -WebGLGraphicsData.prototype.upload = function () { +WebGLGraphicsData.prototype.upload = function () +{ var gl = this.gl; // this.lastIndex = graphics.graphicsData.length; diff --git a/src/core/renderers/webgl/utils/WebGLSpriteBatch.js b/src/core/renderers/webgl/utils/WebGLSpriteBatch.js index 96eaa52..55befbb 100644 --- a/src/core/renderers/webgl/utils/WebGLSpriteBatch.js +++ b/src/core/renderers/webgl/utils/WebGLSpriteBatch.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this sprite batch works for. */ -function WebGLSpriteBatch(renderer) { +function WebGLSpriteBatch(renderer) +{ /** * * @@ -88,7 +89,8 @@ */ this.lastIndexCount = 0; - for (var i=0, j=0; i < numIndices; i += 6, j += 4) { + 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; @@ -162,7 +164,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.setupContext(); }); } @@ -173,7 +176,8 @@ /** * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLSpriteBatch.prototype.setupContext = function () { +WebGLSpriteBatch.prototype.setupContext = function () +{ var gl = this.renderer.gl; // setup default shader @@ -198,7 +202,8 @@ /** * */ -WebGLSpriteBatch.prototype.begin = function () { +WebGLSpriteBatch.prototype.begin = function () +{ // this.shader = this.renderer.shaderManager.defaultShader; this.start(); @@ -206,19 +211,22 @@ /** */ -WebGLSpriteBatch.prototype.end = function () { +WebGLSpriteBatch.prototype.end = function () +{ this.flush(); }; /** * @param sprite {Sprite} the sprite to render when using this spritebatch */ -WebGLSpriteBatch.prototype.render = function (sprite) { +WebGLSpriteBatch.prototype.render = function (sprite) +{ var texture = sprite.texture; //TODO set blend modes.. // check texture.. - if (this.currentBatchSize >= this.size) { + if (this.currentBatchSize >= this.size) + { this.flush(); this.currentBaseTexture = texture.baseTexture; } @@ -227,7 +235,8 @@ var uvs = texture._uvs; // if the uvs have not updated then no point rendering just yet! - if (!uvs) { + if (!uvs) + { return; } @@ -237,7 +246,8 @@ var w0, w1, h0, h1; - if (texture.trim) { + 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; @@ -248,7 +258,8 @@ h0 = h1 + texture.crop.height; } - else { + else + { w0 = (texture.frame.width ) * (1-aX); w1 = (texture.frame.width ) * -aX; @@ -272,7 +283,8 @@ var colors = this.colors; var positions = this.positions; - if (this.renderer.roundPixels) { + if (this.renderer.roundPixels) + { // xy positions[index] = a * w1 + c * h1 + tx | 0; positions[index+1] = d * h1 + b * w1 + ty | 0; @@ -289,7 +301,8 @@ positions[index+15] = a * w1 + c * h0 + tx | 0; positions[index+16] = d * h0 + b * w1 + ty | 0; } - else { + else + { // xy positions[index] = a * w1 + c * h1 + tx; positions[index+1] = d * h1 + b * w1 + ty; @@ -338,11 +351,13 @@ * * @param sprite {TilingSprite} the tilingSprite to render */ -WebGLSpriteBatch.prototype.renderTilingSprite = function (tilingSprite) { +WebGLSpriteBatch.prototype.renderTilingSprite = function (tilingSprite) +{ var texture = tilingSprite.tilingTexture; // check texture.. - if (this.currentBatchSize >= this.size) { + if (this.currentBatchSize >= this.size) + { //return; this.flush(); this.currentBaseTexture = texture.baseTexture; @@ -351,7 +366,8 @@ // set the textures uvs temporarily // TODO create a separate texture so that we can tile part of a texture - if (!tilingSprite._uvs) { + if (!tilingSprite._uvs) + { tilingSprite._uvs = new TextureUvs(); } @@ -454,16 +470,19 @@ * Renders the content and empties the current batch. * */ -WebGLSpriteBatch.prototype.flush = function () { +WebGLSpriteBatch.prototype.flush = function () +{ // If the batch is length 0 then return as there is nothing to draw - if (this.currentBatchSize === 0) { + if (this.currentBatchSize === 0) + { return; } var gl = this.renderer.gl; var shader; - if (this.dirty) { + if (this.dirty) + { this.dirty = false; // bind the main texture gl.activeTexture(gl.TEXTURE0); @@ -482,10 +501,12 @@ } // upload the verts to the buffer - if (this.currentBatchSize > ( this.size * 0.5 ) ) { + if (this.currentBatchSize > ( this.size * 0.5 ) ) + { gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); } - else { + else + { var view = this.positions.subarray(0, this.currentBatchSize * this.vertByteSize); gl.bufferSubData(gl.ARRAY_BUFFER, 0, view); } @@ -502,7 +523,8 @@ var shaderSwap = false; var sprite; - for (var i = 0, j = this.currentBatchSize; i < j; i++) { + for (var i = 0, j = this.currentBatchSize; i < j; i++) + { sprite = this.sprites[i]; @@ -513,24 +535,28 @@ blendSwap = currentBlendMode !== nextBlendMode; shaderSwap = currentShader !== nextShader; // should I use uuidS??? - if (currentBaseTexture !== nextTexture || blendSwap || shaderSwap) { + if (currentBaseTexture !== nextTexture || blendSwap || shaderSwap) + { this.renderBatch(currentBaseTexture, batchSize, start); start = i; batchSize = 0; currentBaseTexture = nextTexture; - if (blendSwap) { + if (blendSwap) + { currentBlendMode = nextBlendMode; this.renderer.blendModeManager.setBlendMode( currentBlendMode ); } - if (shaderSwap) { + if (shaderSwap) + { currentShader = nextShader; shader = currentShader.shaders ? currentShader.shaders[gl.id] : currentShader; - if (!shader) { + if (!shader) + { shader = new Shader(gl, null, currentShader.fragmentSrc, currentShader.uniforms); currentShader.shaders[gl.id] = shader; } @@ -538,7 +564,8 @@ // set shader function??? this.renderer.shaderManager.setShader(shader); - if (shader.dirty) { + if (shader.dirty) + { shader.syncUniforms(); } @@ -569,17 +596,21 @@ * @param size {number} * @param startIndex {number} */ -WebGLSpriteBatch.prototype.renderBatch = function (texture, size, startIndex) { - if (size === 0) { +WebGLSpriteBatch.prototype.renderBatch = function (texture, size, startIndex) +{ + if (size === 0) + { return; } var gl = this.renderer.gl; - if (!texture._glTextures[gl.id]) { + if (!texture._glTextures[gl.id]) + { this.renderer.updateTexture(texture); } - else { + else + { // bind the current texture gl.bindTexture(gl.TEXTURE_2D, texture._glTextures[gl.id]); } @@ -594,7 +625,8 @@ /** * */ -WebGLSpriteBatch.prototype.stop = function () { +WebGLSpriteBatch.prototype.stop = function () +{ this.flush(); this.dirty = true; }; @@ -602,7 +634,8 @@ /** * */ -WebGLSpriteBatch.prototype.start = function () { +WebGLSpriteBatch.prototype.start = function () +{ this.dirty = true; }; @@ -610,7 +643,8 @@ * Destroys the SpriteBatch. * */ -WebGLSpriteBatch.prototype.destroy = function () { +WebGLSpriteBatch.prototype.destroy = function () +{ this.renderer.gl.deleteBuffer(this.vertexBuffer); this.renderer.gl.deleteBuffer(this.indexBuffer); diff --git a/src/core/textures/BaseTexture.js b/src/core/textures/BaseTexture.js index 2bf77d4..513d358 100644 --- a/src/core/textures/BaseTexture.js +++ b/src/core/textures/BaseTexture.js @@ -10,7 +10,8 @@ * @param source {Image|Canvas} the source object of the texture. * @param [scaleMode=scaleModes.DEFAULT] {number} See {@link scaleModes} for possible values */ -function BaseTexture(source, scaleMode) { +function BaseTexture(source, scaleMode) +{ this.uuid = utils.uuid(); /** @@ -123,7 +124,8 @@ this._needsUpdate = false; // if no source passed don't try to load - if (source) { + if (source) + { this.loadSource(source); } @@ -149,13 +151,16 @@ Object.defineProperties(BaseTexture.prototype, { needsUpdate: { - get: function () { + get: function () + { return this._needsUpdate; }, - set: function (val) { + set: function (val) + { this._needsUpdate = val; - if (val) { + if (val) + { this.emit('update', this); } } @@ -171,9 +176,11 @@ * * The logic state after calling `loadSource` directly or indirectly (eg. `fromImage`, `new BaseTexture`) is: * - * if (texture.hasLoaded) { + * if (texture.hasLoaded) + { * // texture ready for use - * } else if (texture.isLoading) { + * } else if (texture.isLoading) + { * // listen to 'loaded' and/or 'error' events on texture * } else { * // not loading, not going to load UNLESS the source is reloaded @@ -183,12 +190,14 @@ * @protected * @param source {Image|Canvas} the source object of the texture. */ -BaseTexture.prototype.loadSource = function (source) { +BaseTexture.prototype.loadSource = function (source) +{ var wasLoading = this.isLoading; this.hasLoaded = false; this.isLoading = false; - if (wasLoading && this.source) { + if (wasLoading && this.source) + { this.source.onload = null; this.source.onerror = null; } @@ -196,20 +205,24 @@ this.source = source; // Apply source if loaded. Otherwise setup appropriate loading monitors. - if ((this.source.complete || this.source.getContext) && this.source.width && this.source.height) { + if ((this.source.complete || this.source.getContext) && this.source.width && this.source.height) + { this._sourceLoaded(); } - else if(!source.getContext) { + else if(!source.getContext) + { // Image fail / not ready this.isLoading = true; var scope = this; - source.onload = function () { + source.onload = function () + { source.onload = null; source.onerror = null; - if(!scope.isLoading) { + if(!scope.isLoading) + { return; } @@ -219,11 +232,13 @@ scope.emit('loaded', scope); }; - source.onerror = function () { + source.onerror = function () + { source.onload = null; source.onerror = null; - if(!scope.isLoading) { + if(!scope.isLoading) + { return; } @@ -234,24 +249,29 @@ // Per http://www.w3.org/TR/html5/embedded-content-0.html#the-img-element // "The value of `complete` can thus change while a script is executing." // So complete needs to be re-checked after the callbacks have been added.. - if (source.complete) { + if (source.complete) + { this.isLoading = false; // ..and if we're complete now, no need for callbacks source.onload = null; source.onerror = null; - if (source.width && source.height) { + if (source.width && source.height) + { this._sourceLoaded(); // If any previous subscribers possible - if (wasLoading) { + if (wasLoading) + { this.emit('loaded', this); } } - else { + else + { // If any previous subscribers possible - if (wasLoading) { + if (wasLoading) + { this.emit('error', this); } } @@ -265,7 +285,8 @@ * * @private */ -BaseTexture.prototype._sourceLoaded = function () { +BaseTexture.prototype._sourceLoaded = function () +{ this.hasLoaded = true; this.width = this.source.naturalWidth || this.source.width; @@ -278,16 +299,20 @@ * Destroys this base texture * */ -BaseTexture.prototype.destroy = function () { - if (this.imageUrl) { +BaseTexture.prototype.destroy = function () +{ + if (this.imageUrl) + { delete utils.BaseTextureCache[this.imageUrl]; delete utils.TextureCache[this.imageUrl]; this.imageUrl = null; - if (!navigator.isCocoonJS) { + if (!navigator.isCocoonJS) + { this.source.src = ''; } } - else if (this.source && this.source._pixiId) { + else if (this.source && this.source._pixiId) + { delete utils.BaseTextureCache[this.source._pixiId]; } this.source = null; @@ -301,7 +326,8 @@ * memory again. * */ -BaseTexture.prototype.dispose = function () { +BaseTexture.prototype.dispose = function () +{ this.emit('dispose', this); }; @@ -311,7 +337,8 @@ * * @param newSrc {string} the path of the image */ -BaseTexture.prototype.updateSourceImage = function (newSrc) { +BaseTexture.prototype.updateSourceImage = function (newSrc) +{ this.source.src = newSrc; this.loadSource(this.source); }; @@ -326,18 +353,22 @@ * @param [scaleMode=scaleModes.DEFAULT] {number} See {@link scaleModes} for possible values * @return BaseTexture */ -BaseTexture.fromImage = function (imageUrl, crossorigin, scaleMode) { +BaseTexture.fromImage = function (imageUrl, crossorigin, scaleMode) +{ var baseTexture = utils.BaseTextureCache[imageUrl]; - if (crossorigin === undefined && imageUrl.indexOf('data:') !== 0) { + if (crossorigin === undefined && imageUrl.indexOf('data:') !== 0) + { crossorigin = true; } - if (!baseTexture) { + if (!baseTexture) + { // new Image() breaks tex loading in some versions of Chrome. // See https://code.google.com/p/chromium/issues/detail?id=238071 var image = new Image();//document.createElement('img'); - if (crossorigin) { + if (crossorigin) + { image.crossOrigin = ''; } @@ -347,7 +378,8 @@ utils.BaseTextureCache[imageUrl] = baseTexture; // if there is an @2x at the end of the url we are going to assume its a highres image - if ( imageUrl.indexOf(CONST.RETINA_PREFIX + '.') !== -1) { + if ( imageUrl.indexOf(CONST.RETINA_PREFIX + '.') !== -1) + { baseTexture.resolution = 2; } } @@ -363,14 +395,17 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return BaseTexture */ -BaseTexture.fromCanvas = function (canvas, scaleMode) { - if (!canvas._pixiId) { +BaseTexture.fromCanvas = function (canvas, scaleMode) +{ + if (!canvas._pixiId) + { canvas._pixiId = 'canvas_' + utils.uuid(); } var baseTexture = utils.BaseTextureCache[canvas._pixiId]; - if (!baseTexture) { + if (!baseTexture) + { baseTexture = new BaseTexture(canvas, scaleMode); utils.BaseTextureCache[canvas._pixiId] = baseTexture; } diff --git a/src/core/textures/RenderTexture.js b/src/core/textures/RenderTexture.js index 6dad20f..53ae796 100644 --- a/src/core/textures/RenderTexture.js +++ b/src/core/textures/RenderTexture.js @@ -46,8 +46,10 @@ * @param [scaleMode] {number} See {@link scaleModes} for possible values * @param [resolution=1] {number} The resolution of the texture being generated */ -function RenderTexture(renderer, width, height, scaleMode, resolution) { - if (!renderer) { +function RenderTexture(renderer, width, height, scaleMode, resolution) +{ + if (!renderer) + { throw new Error('Unable to create RenderTexture, you must pass a renderer into the constructor.'); } @@ -133,7 +135,8 @@ */ this.renderer = renderer; - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { var gl = this.renderer.gl; this.textureBuffer = new FilterTexture(gl, this.width * this.resolution, this.height * this.resolution, this.baseTexture.scaleMode); @@ -142,7 +145,8 @@ this.render = this.renderWebGL; this.projection = new math.Point(this.width*0.5, -this.height*0.5); } - else { + else + { this.render = this.renderCanvas; this.textureBuffer = new CanvasBuffer(this.width* this.resolution, this.height* this.resolution); this.baseTexture.source = this.textureBuffer.canvas; @@ -167,8 +171,10 @@ * @param height {number} The height to resize to. * @param updateBase {boolean} Should the baseTexture.width and height values be resized as well? */ -RenderTexture.prototype.resize = function (width, height, updateBase) { - if (width === this.width && height === this.height) { +RenderTexture.prototype.resize = function (width, height, updateBase) +{ + if (width === this.width && height === this.height) + { return; } @@ -177,17 +183,20 @@ this.width = this.frame.width = this.crop.width = width; this.height = this.frame.height = this.crop.height = height; - if (updateBase) { + if (updateBase) + { this.baseTexture.width = this.width; this.baseTexture.height = this.height; } - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { this.projection.x = this.width / 2; this.projection.y = -this.height / 2; } - if (!this.valid) { + if (!this.valid) + { return; } @@ -198,12 +207,15 @@ * Clears the RenderTexture. * */ -RenderTexture.prototype.clear = function () { - if (!this.valid) { +RenderTexture.prototype.clear = function () +{ + if (!this.valid) + { return; } - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { this.renderer.gl.bindFramebuffer(this.renderer.gl.FRAMEBUFFER, this.textureBuffer.frameBuffer); } @@ -220,19 +232,23 @@ * @param [restoreWorldTransform=true] {boolean} If true the displayObject's worldTransform/worldAlpha and all children * transformations will be restored. Not restoring this information will be a little faster. */ -RenderTexture.prototype.renderWebGL = function (displayObject, matrix, clear, restoreWorldTransform) { - if (!this.valid) { +RenderTexture.prototype.renderWebGL = function (displayObject, matrix, clear, restoreWorldTransform) +{ + if (!this.valid) + { return; } - if (typeof restoreWorldTransform === 'undefined') { + if (typeof restoreWorldTransform === 'undefined') + { restoreWorldTransform = true; } var tempAlpha, tempTransform; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { tempAlpha = displayObject.worldAlpha; tempTransform = displayObject.worldTransform.toArray(); } @@ -245,7 +261,8 @@ wt.identity(); wt.translate(0, this.projection.y * 2); - if (matrix) { + if (matrix) + { wt.append(matrix); } @@ -258,7 +275,8 @@ var children = displayObject.children; var i, j; - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } @@ -269,7 +287,8 @@ gl.bindFramebuffer(gl.FRAMEBUFFER, this.textureBuffer.frameBuffer ); - if (clear) { + if (clear) + { this.textureBuffer.clear(); } @@ -279,11 +298,13 @@ this.renderer.spriteBatch.dirty = true; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { displayObject.worldAlpha = tempAlpha; displayObject.worldTransform.fromArray(tempTransform); - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } } @@ -300,26 +321,31 @@ * @param [restoreWorldTransform=true] {boolean} If true the displayObject's worldTransform/worldAlpha and all children * transformations will be restored. Not restoring this information will be a little faster. */ -RenderTexture.prototype.renderCanvas = function (displayObject, matrix, clear, restoreWorldTransform) { - if (!this.valid) { +RenderTexture.prototype.renderCanvas = function (displayObject, matrix, clear, restoreWorldTransform) +{ + if (!this.valid) + { return; } - if (typeof restoreWorldTransform === 'undefined') { + if (typeof restoreWorldTransform === 'undefined') + { restoreWorldTransform = true; } var tempAlpha, tempTransform; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { tempAlpha = displayObject.worldAlpha; tempTransform = displayObject.worldTransform.toArray(); } var wt = displayObject.worldTransform; wt.identity(); - if (matrix) { + if (matrix) + { wt.append(matrix); } @@ -330,11 +356,13 @@ var children = displayObject.children; var i, j; - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } - if (clear) { + if (clear) + { this.textureBuffer.clear(); } @@ -348,11 +376,13 @@ this.renderer.resolution = realResolution; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { displayObject.worldAlpha = tempAlpha; displayObject.worldTransform.fromArray(tempTransform); - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } } @@ -363,7 +393,8 @@ * * @return {Image} */ -RenderTexture.prototype.getImage = function () { +RenderTexture.prototype.getImage = function () +{ var image = new Image(); image.src = this.getBase64(); return image; @@ -374,7 +405,8 @@ * * @return {string} A base64 encoded string of the texture. */ -RenderTexture.prototype.getBase64 = function () { +RenderTexture.prototype.getBase64 = function () +{ return this.getCanvas().toDataURL(); }; @@ -383,8 +415,10 @@ * * @return {HTMLCanvasElement} A Canvas element with the texture rendered on. */ -RenderTexture.prototype.getCanvas = function () { - if (this.renderer.type === CONST.WEBGL_RENDERER) { +RenderTexture.prototype.getCanvas = function () +{ + if (this.renderer.type === CONST.WEBGL_RENDERER) + { var gl = this.renderer.gl; var width = this.textureBuffer.width; var height = this.textureBuffer.height; @@ -403,7 +437,8 @@ return tempCanvas.canvas; } - else { + else + { return this.textureBuffer.canvas; } }; diff --git a/src/core/textures/Texture.js b/src/core/textures/Texture.js index 3c65909..e97f0aa 100644 --- a/src/core/textures/Texture.js +++ b/src/core/textures/Texture.js @@ -17,7 +17,8 @@ * @param [crop] {Rectangle} The area of original texture * @param [trim] {Rectangle} Trimmed texture rectangle */ -function Texture(baseTexture, frame, crop, trim) { +function Texture(baseTexture, frame, crop, trim) +{ /** * Does this Texture have any frame data assigned to it? * @@ -25,12 +26,14 @@ */ this.noFrame = false; - if (!frame) { + if (!frame) + { this.noFrame = true; frame = new math.Rectangle(0, 0, 1, 1); } - if (baseTexture instanceof Texture) { + if (baseTexture instanceof Texture) + { baseTexture = baseTexture.baseTexture; } @@ -100,13 +103,16 @@ */ this.crop = crop || new math.Rectangle(0, 0, 1, 1); - if (baseTexture.hasLoaded) { - if (this.noFrame) { + if (baseTexture.hasLoaded) + { + if (this.noFrame) + { frame = new math.Rectangle(0, 0, baseTexture.width, baseTexture.height); } this.frame = frame; } - else { + else + { baseTexture.addEventListener('loaded', this.onBaseTextureLoaded.bind(this)); } } @@ -118,19 +124,23 @@ Object.defineProperties(Texture.prototype, { needsUpdate: { - get: function () { + get: function () + { return this.baseTexture.needsUpdate; }, - set: function (val) { + set: function (val) + { this.baseTexture.needsUpdate = val; } }, frame: { - get: function () { + get: function () + { return this._frame; }, - set: function (frame) { + set: function (frame) + { this._frame = frame; this.noFrame = false; @@ -143,20 +153,23 @@ 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 (!this.trim && (frame.x + frame.width > this.baseTexture.width || frame.y + frame.height > this.baseTexture.height)) + { throw new Error('Texture Error: frame does not fit inside the base Texture dimensions ' + this); } this.valid = frame && frame.width && frame.height && this.baseTexture.source && this.baseTexture.hasLoaded; - if (this.trim) { + 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) { + if (this.valid) + { this._updateUvs(); } } @@ -168,11 +181,13 @@ * * @private */ -Texture.prototype.onBaseTextureLoaded = function () { +Texture.prototype.onBaseTextureLoaded = function () +{ var baseTexture = this.baseTexture; baseTexture.removeEventListener('loaded', this.onLoaded); - if (this.noFrame) { + if (this.noFrame) + { this.frame = new math.Rectangle(0, 0, baseTexture.width, baseTexture.height); } @@ -184,8 +199,10 @@ * * @param destroyBase {boolean} Whether to destroy the base texture as well */ -Texture.prototype.destroy = function (destroyBase) { - if (destroyBase) { +Texture.prototype.destroy = function (destroyBase) +{ + if (destroyBase) + { this.baseTexture.destroy(); } @@ -197,8 +214,10 @@ * * @private */ -Texture.prototype._updateUvs = function () { - if (!this._uvs) { +Texture.prototype._updateUvs = function () +{ + if (!this._uvs) + { this._uvs = new TextureUvs(); } @@ -229,10 +248,12 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return Texture */ -Texture.fromImage = function (imageUrl, crossorigin, scaleMode) { +Texture.fromImage = function (imageUrl, crossorigin, scaleMode) +{ var texture = utils.TextureCache[imageUrl]; - if (!texture) { + if (!texture) + { texture = new Texture(BaseTexture.fromImage(imageUrl, crossorigin, scaleMode)); utils.TextureCache[imageUrl] = texture; } @@ -248,9 +269,11 @@ * @param frameId {string} The frame id of the texture * @return Texture */ -Texture.fromFrame = function (frameId) { +Texture.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache '); } return texture; @@ -264,7 +287,8 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return {Texture} */ -Texture.fromCanvas = function (canvas, scaleMode) { +Texture.fromCanvas = function (canvas, scaleMode) +{ return new Texture(BaseTexture.fromCanvas(canvas, scaleMode)); }; @@ -276,7 +300,8 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return {Texture} A Texture */ -Texture.fromVideo = function (video, scaleMode) { +Texture.fromVideo = function (video, scaleMode) +{ return new Texture(VideoBaseTexture.baseTextureFromVideo(video, scaleMode)); }; @@ -287,7 +312,8 @@ * @param texture {Texture} The Texture to add to the cache. * @param id {string} The id that the texture will be stored against. */ -Texture.addTextureToCache = function (texture, id) { +Texture.addTextureToCache = function (texture, id) +{ utils.TextureCache[id] = texture; }; @@ -298,7 +324,8 @@ * @param id {string} The id of the texture to be removed * @return {Texture} The texture that was removed */ -Texture.removeTextureFromCache = function (id) { +Texture.removeTextureFromCache = function (id) +{ var texture = utils.TextureCache[id]; delete utils.TextureCache[id]; diff --git a/src/core/textures/TextureUvs.js b/src/core/textures/TextureUvs.js index b9bbb58..5424d52 100644 --- a/src/core/textures/TextureUvs.js +++ b/src/core/textures/TextureUvs.js @@ -1,4 +1,5 @@ -function TextureUvs() { +function TextureUvs() +{ this.x0 = 0; this.y0 = 0; diff --git a/src/core/textures/VideoBaseTexture.js b/src/core/textures/VideoBaseTexture.js index e3e0c5a..1a826a9 100644 --- a/src/core/textures/VideoBaseTexture.js +++ b/src/core/textures/VideoBaseTexture.js @@ -12,15 +12,18 @@ * @param source {HTMLVideoElement} * @param [scaleMode] {number} See {@link scaleModes} for possible values */ -function VideoBaseTexture(source, scaleMode) { - if (!source){ +function VideoBaseTexture(source, scaleMode) +{ + if (!source) + { throw new Error('No video source element specified.'); } // hook in here to check if video is already available. // BaseTexture looks for a source.complete boolean, plus width & height. - if ((source.readyState === source.HAVE_ENOUGH_DATA || source.readyState === source.HAVE_FUTURE_DATA) && source.width && source.height) { + if ((source.readyState === source.HAVE_ENOUGH_DATA || source.readyState === source.HAVE_FUTURE_DATA) && source.width && source.height) + { source.complete = true; } @@ -31,7 +34,8 @@ this._boundOnUpdate = this._onUpdate.bind(this); this._boundOnCanPlay = this._onCanPlay.bind(this); - if (!source.complete) { + if (!source.complete) + { source.addEventListener('canplay', this._boundOnCanPlay); source.addEventListener('canplaythrough', this._boundOnCanPlay); @@ -47,28 +51,35 @@ VideoBaseTexture.prototype.constructor = VideoBaseTexture; module.exports = VideoBaseTexture; -VideoBaseTexture.prototype._onUpdate = function () { - if (this.autoUpdate) { +VideoBaseTexture.prototype._onUpdate = function () +{ + if (this.autoUpdate) + { window.requestAnimationFrame(this._boundOnUpdate); this.needsUpdate = true; } }; -VideoBaseTexture.prototype._onPlayStart = function () { - if (!this.autoUpdate) { +VideoBaseTexture.prototype._onPlayStart = function () +{ + if (!this.autoUpdate) + { window.requestAnimationFrame(this._boundOnUpdate); this.autoUpdate = true; } }; -VideoBaseTexture.prototype._onPlayStop = function () { +VideoBaseTexture.prototype._onPlayStop = function () +{ this.autoUpdate = false; }; -VideoBaseTexture.prototype._onCanPlay = function () { +VideoBaseTexture.prototype._onCanPlay = function () +{ this.hasLoaded = true; - if (this.source) { + if (this.source) + { this.source.removeEventListener('canplay', this._boundOnCanPlay); this.source.removeEventListener('canplaythrough', this._boundOnCanPlay); @@ -78,15 +89,18 @@ this.source.play(); // prevent multiple loaded dispatches.. - if(!this.__loaded){ + if(!this.__loaded) + { this.__loaded = true; this.emit('loaded', this); } } }; -VideoBaseTexture.prototype.destroy = function () { - if (this.source && this.source._pixiId) { +VideoBaseTexture.prototype.destroy = function () +{ + if (this.source && this.source._pixiId) + { utils.BaseTextureCache[ this.source._pixiId ] = null; delete utils.BaseTextureCache[ this.source._pixiId ]; @@ -105,14 +119,17 @@ * @param scaleMode {number} See {@link scaleModes} for possible values * @return {VideoBaseTexture} */ -VideoBaseTexture.fromVideo = function (video, scaleMode) { - if (!video._pixiId) { +VideoBaseTexture.fromVideo = function (video, scaleMode) +{ + if (!video._pixiId) + { video._pixiId = 'video_' + utils.uuid(); } var baseTexture = utils.BaseTextureCache[video._pixiId]; - if (!baseTexture) { + if (!baseTexture) + { baseTexture = new VideoBaseTexture(video, scaleMode); utils.BaseTextureCache[ video._pixiId ] = baseTexture; } @@ -147,17 +164,21 @@ * @param scaleMode {number} See {@link scaleModes} for possible values * @return {VideoBaseTexture} */ -VideoBaseTexture.fromUrl = function (videoSrc, scaleMode) { +VideoBaseTexture.fromUrl = function (videoSrc, scaleMode) +{ var video = document.createElement('video'); // array of objects or strings - if (Array.isArray(videoSrc)) { - for (var i = 0; i < videoSrc.length; ++i) { + if (Array.isArray(videoSrc)) + { + for (var i = 0; i < videoSrc.length; ++i) + { video.appendChild(createSource(videoSrc.src || videoSrc, videoSrc.mime)); } } // single object or string - else { + else + { video.appendChild(createSource(videoSrc.src || videoSrc, videoSrc.mime)); } @@ -169,8 +190,10 @@ VideoBaseTexture.fromUrls = VideoBaseTexture.fromUrl; -function createSource(path, type) { - if (!type) { +function createSource(path, type) +{ + if (!type) + { type = 'video/' + path.substr(path.lastIndexOf('.') + 1); } diff --git a/src/core/utils/EventData.js b/src/core/utils/EventData.js index 5d55a22..8cdf701 100644 --- a/src/core/utils/EventData.js +++ b/src/core/utils/EventData.js @@ -7,7 +7,8 @@ * @param name {string} The string name of the event that was triggered * @param data {object} Arbitrary event data to pass along */ -function EventData(target, name, data) { +function EventData(target, name, data) +{ // for duck typing in the ".on()" function this.__isEventObject = true; @@ -71,7 +72,8 @@ * Stops the propagation of events up the scene graph (prevents bubbling). * */ -EventData.prototype.stopPropagation = function stopPropagation() { +EventData.prototype.stopPropagation = function stopPropagation() +{ this.stopped = true; }; @@ -79,6 +81,7 @@ * Stops the propagation of events to sibling listeners (no longer calls any listeners). * */ -EventData.prototype.stopImmediatePropagation = function stopImmediatePropagation() { +EventData.prototype.stopImmediatePropagation = function stopImmediatePropagation() +{ this.stoppedImmediate = true; }; diff --git a/src/core/utils/EventTarget.js b/src/core/utils/EventTarget.js index 7ae8820..671a151 100644 --- a/src/core/utils/EventTarget.js +++ b/src/core/utils/EventTarget.js @@ -13,14 +13,16 @@ * var em = new MyEmitter(); * em.emit('eventName', 'some data', 'some more data', {}, null, ...); */ -function eventTarget(obj) { +function eventTarget(obj) +{ /** * Return a list of assigned event listeners. * * @param eventName {string} The events that should be listed. * @return {Array} An array of listener functions */ - obj.listeners = function listeners(eventName) { + obj.listeners = function listeners(eventName) + { this._listeners = this._listeners || {}; return this._listeners[eventName] ? this._listeners[eventName].slice() : []; @@ -33,22 +35,26 @@ * @param eventName {string} The name of the event. * @return {boolean} Indication if we've emitted an event. */ - obj.emit = obj.dispatchEvent = function emit(eventName, data) { + obj.emit = obj.dispatchEvent = function emit(eventName, data) + { this._listeners = this._listeners || {}; // fast return when there are no listeners - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return; } //backwards compat with old method ".emit({ type: 'something' })" - if (typeof eventName === 'object') { + if (typeof eventName === 'object') + { data = eventName; eventName = eventName.type; } //ensure we are using a real pixi event - if (!data || data.__isEventObject !== true) { + if (!data || data.__isEventObject !== true) + { data = new EventData(this, eventName, data); } @@ -58,23 +64,27 @@ fn = listeners[0], i; - for (i = 0; i < length; fn = listeners[++i]) { + for (i = 0; i < length; fn = listeners[++i]) + { //call the event listener fn.call(this, data); //if "stopImmediatePropagation" is called, stop calling sibling events - if (data.stoppedImmediate) { + if (data.stoppedImmediate) + { return this; } } //if "stopPropagation" is called then don't bubble the event - if (data.stopped) { + if (data.stopped) + { return this; } //bubble this event up the scene graph - if (this.parent && this.parent.emit) { + if (this.parent && this.parent.emit) + { this.parent.emit.call(this.parent, eventName, data); } @@ -88,7 +98,8 @@ * @param eventName {string} Name of the event. * @param callback {Functon} fn Callback function. */ - obj.on = obj.addEventListener = function on(eventName, fn) { + obj.on = obj.addEventListener = function on(eventName, fn) + { this._listeners = this._listeners || {}; (this._listeners[eventName] = this._listeners[eventName] || []) @@ -103,11 +114,13 @@ * @param eventName {string} Name of the event. * @param callback {Function} Callback function. */ - obj.once = function once(eventName, fn) { + obj.once = function once(eventName, fn) + { this._listeners = this._listeners || {}; var self = this; - function onceHandlerWrapper() { + function onceHandlerWrapper() + { fn.apply(self.off(eventName, onceHandlerWrapper), arguments); } onceHandlerWrapper._originalHandler = fn; @@ -122,23 +135,28 @@ * @param eventName {string} The event we want to remove. * @param callback {Function} The listener that we need to find. */ - obj.off = obj.removeEventListener = function off(eventName, fn) { + obj.off = obj.removeEventListener = function off(eventName, fn) + { this._listeners = this._listeners || {}; - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return this; } var list = this._listeners[eventName], i = fn ? list.length : 0; - while(i-- > 0) { - if (list[i] === fn || list[i]._originalHandler === fn) { + while(i-- > 0) + { + if (list[i] === fn || list[i]._originalHandler === fn) + { list.splice(i, 1); } } - if (list.length === 0) { + if (list.length === 0) + { delete this._listeners[eventName]; } @@ -150,10 +168,12 @@ * * @param eventName {string} The event you want to remove all listeners for. */ - obj.removeAllListeners = function removeAllListeners(eventName) { + obj.removeAllListeners = function removeAllListeners(eventName) + { this._listeners = this._listeners || {}; - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return this; } @@ -169,7 +189,8 @@ * * @param object {object} The obj to mix into */ - mixin: function mixin(obj) { + mixin: function mixin(obj) + { eventTarget(obj); } }; diff --git a/src/core/utils/PolyK.js b/src/core/utils/PolyK.js index 7325141..5e20c2b 100644 --- a/src/core/utils/PolyK.js +++ b/src/core/utils/PolyK.js @@ -47,7 +47,8 @@ * Triangulates shapes for webGL graphic fills. * */ -PolyK.Triangulate = function (p) { +PolyK.Triangulate = function (p) +{ var sign = true; var n = p.length >> 1; @@ -59,7 +60,8 @@ i = 0; var al = n; - while(al > 3) { + while(al > 3) + { var i0 = avl[(i+0)%al]; var i1 = avl[(i+1)%al]; var i2 = avl[(i+2)%al]; @@ -69,29 +71,35 @@ var cx = p[2*i2], cy = p[2*i2+1]; var earFound = false; - if (PolyK._convex(ax, ay, bx, by, cx, cy, sign)) { + if (PolyK._convex(ax, ay, bx, by, cx, cy, sign)) + { earFound = true; - for (var j = 0; j < al; j++) { + for (var j = 0; j < al; j++) + { var vi = avl[j]; if (vi === i0 || vi === i1 || vi === i2) continue; - if (PolyK._PointInTriangle(p[2*vi], p[2*vi+1], ax, ay, bx, by, cx, cy)) { + if (PolyK._PointInTriangle(p[2*vi], p[2*vi+1], ax, ay, bx, by, cx, cy)) + { earFound = false; break; } } } - if (earFound) { + if (earFound) + { tgs.push(i0, i1, i2); avl.splice((i+1)%al, 1); al--; i = 0; } - else if (i++ > 3*al) { + else if (i++ > 3*al) + { // need to flip flip reverse it! // reset! - if (sign) { + if (sign) + { tgs = []; avl = []; for (i = 0; i < n; i++) avl.push(i); @@ -101,7 +109,8 @@ sign = false; } - else { + else + { // window.console.log("PIXI Warning: shape too complex to fill"); return null; } @@ -126,7 +135,8 @@ * @private * @return {boolean} */ -PolyK._PointInTriangle = function (px, py, ax, ay, bx, by, cx, cy) { +PolyK._PointInTriangle = function (px, py, ax, ay, bx, by, cx, cy) +{ var v0x = cx-ax; var v0y = cy-ay; var v1x = bx-ax; @@ -154,6 +164,7 @@ * @private * @return {boolean} */ -PolyK._convex = function (ax, ay, bx, by, cx, cy, sign) { +PolyK._convex = function (ax, ay, bx, by, cx, cy, sign) +{ return ((ay-by)*(cx-bx) + (bx-ax)*(cy-by) >= 0) === sign; }; diff --git a/src/core/utils/index.js b/src/core/utils/index.js index ade9831..bfae7ae 100644 --- a/src/core/utils/index.js +++ b/src/core/utils/index.js @@ -16,7 +16,8 @@ * * @return {number} The next uuid to use. */ - uuid: function () { + uuid: function () + { return ++utils._uid; }, @@ -26,7 +27,8 @@ * @param hex {number} * @return {number[]} An array representing the [R, G, B] of the color. */ - hex2rgb: function (hex, out) { + hex2rgb: function (hex, out) + { out = out || []; out[0] = (hex >> 16 & 0xFF) / 255; @@ -42,7 +44,8 @@ * @param hex {number} * @return {string} The string color. */ - hex2string: function (hex) { + hex2string: function (hex) + { hex = hex.toString(16); hex = '000000'.substr(0, 6 - hex.length) + hex; @@ -55,7 +58,8 @@ * @param rgb {number[]} * @return {number} The color number */ - rgb2hex: function (rgb) { + rgb2hex: function (rgb) + { return ((rgb[0]*255 << 16) + (rgb[1]*255 << 8) + rgb[2]*255); }, @@ -64,8 +68,10 @@ * * @return {boolean} whether they are supported */ - canUseNewCanvasBlendModes: function () { - if (typeof document === 'undefined') { + canUseNewCanvasBlendModes: function () + { + if (typeof document === 'undefined') + { return false; } @@ -93,15 +99,19 @@ * @param number {number} * @return {number} the closest number that is a power of two */ - getNextPowerOfTwo: function (number) { + getNextPowerOfTwo: function (number) + { // see: http://en.wikipedia.org/wiki/Power_of_two#Fast_algorithm_to_check_if_a_positive_number_is_a_power_of_two - if (number > 0 && (number & (number - 1)) === 0) { + if (number > 0 && (number & (number - 1)) === 0) + { return number; } - else { + else + { var result = 1; - while (result < number) { + while (result < number) + { result <<= 1; } @@ -116,7 +126,8 @@ * @param height {number} * @return {boolean} */ - isPowerOfTwo: function (width, height) { + isPowerOfTwo: function (width, height) + { return (width > 0 && (width & (width - 1)) === 0 && height > 0 && (height & (height - 1)) === 0); }, @@ -130,12 +141,15 @@ * @constant * @static */ - sayHello: function (type) { - if (utils._saidHello) { + sayHello: function (type) + { + if (utils._saidHello) + { return; } - if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) { + if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) + { var args = [ '%c %c %c Pixi.js ' + CONST.VERSION + ' - ' + type + ' %c ' + ' %c ' + ' http://www.pixijs.com/ %c %c ♥%c♥%c♥ ', 'background: #ff66a5', @@ -151,7 +165,8 @@ console.log.apply(console, args); //jshint ignore:line } - else if (window.console) { + else if (window.console) + { console.log('Pixi.js ' + CONST.VERSION + ' - ' + type + ' - http://www.pixijs.com/'); //jshint ignore:line } @@ -166,15 +181,19 @@ * @class * @namespace PIXI */ - AjaxRequest: function () { + AjaxRequest: function () + { var activexmodes = ['Msxml2.XMLHTTP.6.0', 'Msxml2.XMLHTTP.3.0', 'Microsoft.XMLHTTP']; //activeX versions to check for in IE - if (window.ActiveXObject) { //Test for support for ActiveXObject in IE first (as XMLHttpRequest in IE7 is broken) - for (var i=0; i= this.textures.length) { + else if (round >= this.textures.length) + { this.gotoAndStop(this.textures.length - 1); - if (this.onComplete) { + if (this.onComplete) + { this.onComplete(); } } @@ -167,10 +182,12 @@ * @static * @param frames {string[]} the array of frames ids the movieclip will use as its texture frames */ -MovieClip.fromFrames = function (frames) { +MovieClip.fromFrames = function (frames) +{ var textures = []; - for (var i = 0; i < frames.length; ++i) { + for (var i = 0; i < frames.length; ++i) + { textures.push(new core.Texture.fromFrame(frames[i])); } @@ -183,10 +200,12 @@ * @static * @param images {string[]} the array of image urls the movieclip will use as its texture frames */ -MovieClip.fromImages = function (images) { +MovieClip.fromImages = function (images) +{ var textures = []; - for (var i = 0; i < images.length; ++i) { + for (var i = 0; i < images.length; ++i) + { textures.push(new core.Texture.fromImage(images[i])); } diff --git a/src/extras/Rope.js b/src/extras/Rope.js index c157ec4..9c87bc0 100644 --- a/src/extras/Rope.js +++ b/src/extras/Rope.js @@ -9,7 +9,8 @@ * @param {Array} points - An array of {Point}. * */ -function Rope(texture, points) { +function Rope(texture, points) +{ Strip.call(this, texture); this.points = points; @@ -31,10 +32,12 @@ * Refreshes * */ -Rope.prototype.refresh = function () { +Rope.prototype.refresh = function () +{ var points = this.points; - if (points.length < 1) { + if (points.length < 1) + { return; } @@ -59,20 +62,23 @@ var total = points.length, point, index, amount; - for (var i = 1; i < total; i++) { + for (var i = 1; i < total; i++) + { point = points[i]; index = i * 4; // time to do some smart drawing! amount = i / (total-1); - if (i%2) { + if (i%2) + { uvs[index] = amount; uvs[index+1] = 0; uvs[index+2] = amount; uvs[index+3] = 1; } - else { + else + { uvs[index] = amount; uvs[index+1] = 0; @@ -95,10 +101,12 @@ * * @private */ -Rope.prototype.updateTransform = function () { +Rope.prototype.updateTransform = function () +{ var points = this.points; - if (points.length < 1) { + if (points.length < 1) + { return; } @@ -113,14 +121,17 @@ var total = points.length, point, index, ratio, perpLength, num; - for (var i = 0; i < total; i++) { + for (var i = 0; i < total; i++) + { point = points[i]; index = i * 4; - if (i < points.length-1) { + if (i < points.length-1) + { nextPoint = points[i+1]; } - else { + else + { nextPoint = point; } @@ -129,7 +140,8 @@ ratio = (1 - (i / (total-1))) * 10; - if (ratio > 1) { + if (ratio > 1) + { ratio = 1; } @@ -157,7 +169,8 @@ * * @param texture {Texture} the texture that will be used */ -Rope.prototype.setTexture = function (texture) { +Rope.prototype.setTexture = function (texture) +{ // stop current texture this.texture = texture; //this.updateFrame = true; diff --git a/src/extras/Strip.js b/src/extras/Strip.js index c5e378f..57691b5 100644 --- a/src/extras/Strip.js +++ b/src/extras/Strip.js @@ -10,7 +10,8 @@ * @param height {number} the height * */ -function Strip(texture) { +function Strip(texture) +{ core.DisplayObjectContainer.call(this); /** @@ -70,9 +71,11 @@ * * @param renderer {WebGLRenderer} */ -Strip.prototype.renderWebGL = function (renderer) { +Strip.prototype.renderWebGL = function (renderer) +{ // if the sprite is not visible or the alpha is 0 then no need to render this element - if (!this.visible || this.alpha <= 0) { + if (!this.visible || this.alpha <= 0) + { return; } @@ -81,7 +84,8 @@ renderer.spriteBatch.stop(); // init! init! - if (!this._vertexBuffer) { + if (!this._vertexBuffer) + { this._initWebGL(renderer); } @@ -96,7 +100,8 @@ //TODO check culling }; -Strip.prototype._initWebGL = function (renderer) { +Strip.prototype._initWebGL = function (renderer) +{ // build the strip! var gl = renderer.gl; @@ -118,7 +123,8 @@ gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this.indices, gl.STATIC_DRAW); }; -Strip.prototype._renderStrip = function (renderer) { +Strip.prototype._renderStrip = function (renderer) +{ var gl = renderer.gl; var projection = renderer.projection, offset = renderer.offset, @@ -137,7 +143,8 @@ gl.uniform2f(shader.offsetVector, -offset.x, -offset.y); gl.uniform1f(shader.alpha, this.worldAlpha); - if (!this.dirty) { + if (!this.dirty) + { gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexBuffer); gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); @@ -150,10 +157,12 @@ gl.activeTexture(gl.TEXTURE0); // check if a texture is dirty.. - if (this.texture.baseTexture._dirty[gl.id]) { + if (this.texture.baseTexture._dirty[gl.id]) + { renderer.updateTexture(this.texture.baseTexture); } - else { + else + { // bind the current texture gl.bindTexture(gl.TEXTURE_2D, this.texture.baseTexture._glTextures[gl.id]); } @@ -163,7 +172,8 @@ } - else { + else + { this.dirty = false; gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexBuffer); @@ -178,10 +188,12 @@ gl.activeTexture(gl.TEXTURE0); // check if a texture is dirty.. - if (this.texture.baseTexture._dirty[gl.id]) { + if (this.texture.baseTexture._dirty[gl.id]) + { renderer.updateTexture(this.texture.baseTexture); } - else { + else + { gl.bindTexture(gl.TEXTURE_2D, this.texture.baseTexture._glTextures[gl.id]); } @@ -203,27 +215,33 @@ * * @param renderer {CanvasRenderer} */ -Strip.prototype.renderCanvas = function (renderer) { +Strip.prototype.renderCanvas = function (renderer) +{ var context = renderer.context; var transform = this.worldTransform; - if (renderer.roundPixels) { + if (renderer.roundPixels) + { context.setTransform(transform.a, transform.b, transform.c, transform.d, transform.tx | 0, transform.ty | 0); } - else { + else + { context.setTransform(transform.a, transform.b, transform.c, transform.d, transform.tx, transform.ty); } - if (this.drawMode === Strip.DrawModes.TRIANGLE_STRIP) { + if (this.drawMode === Strip.DrawModes.TRIANGLE_STRIP) + { this._renderCanvasTriangleStrip(context); } - else { + else + { this._renderCanvasTriangles(context); } }; -Strip.prototype._renderCanvasTriangleStrip = function (context) { +Strip.prototype._renderCanvasTriangleStrip = function (context) +{ // draw triangles!! var vertices = this.vertices; var uvs = this.uvs; @@ -231,14 +249,16 @@ var length = vertices.length / 2; // this.count++; - for (var i = 0; i < length - 2; i++) { + for (var i = 0; i < length - 2; i++) + { // draw some triangles! var index = i * 2; this._renderCanvasDrawTriangle(context, vertices, uvs, index, (index + 2), (index + 4)); } }; -Strip.prototype._renderCanvasTriangles = function (context) { +Strip.prototype._renderCanvasTriangles = function (context) +{ // draw triangles!! var vertices = this.vertices; var uvs = this.uvs; @@ -247,14 +267,16 @@ var length = indices.length; // this.count++; - for (var i = 0; i < length; i += 3) { + for (var i = 0; i < length; i += 3) + { // draw some triangles! var index0 = indices[i] * 2, index1 = indices[i + 1] * 2, index2 = indices[i + 2] * 2; this._renderCanvasDrawTriangle(context, vertices, uvs, index0, index1, index2); } }; -Strip.prototype._renderCanvasDrawTriangle = function (context, vertices, uvs, index0, index1, index2) { +Strip.prototype._renderCanvasDrawTriangle = function (context, vertices, uvs, index0, index1, index2) +{ var textureSource = this.texture.baseTexture.source; var textureWidth = this.texture.width; var textureHeight = this.texture.height; @@ -265,7 +287,8 @@ var u0 = uvs[index0] * textureWidth, u1 = uvs[index1] * textureWidth, u2 = uvs[index2] * textureWidth; var v0 = uvs[index0 + 1] * textureHeight, v1 = uvs[index1 + 1] * textureHeight, v2 = uvs[index2 + 1] * textureHeight; - if (this.canvasPadding > 0) { + if (this.canvasPadding > 0) + { var paddingX = this.canvasPadding / this.worldTransform.a; var paddingY = this.canvasPadding / this.worldTransform.d; var centerX = (x0 + x1 + x2) / 3; @@ -332,7 +355,8 @@ * @param strip {Strip} The Strip to render * @private */ -Strip.prototype.renderStripFlat = function (strip) { +Strip.prototype.renderStripFlat = function (strip) +{ var context = this.context; var vertices = strip.vertices; @@ -340,7 +364,8 @@ // this.count++; context.beginPath(); - for (var i=1; i < length-2; i++) { + for (var i=1; i < length-2; i++) + { // draw some triangles! var index = i*2; @@ -358,7 +383,8 @@ }; /* -Strip.prototype.setTexture = function (texture) { +Strip.prototype.setTexture = function (texture) +{ //TODO SET THE TEXTURES //TODO VISIBILITY @@ -377,7 +403,8 @@ * @private */ -Strip.prototype.onTextureUpdate = function () { +Strip.prototype.onTextureUpdate = function () +{ this.updateFrame = true; }; @@ -387,7 +414,8 @@ * @param matrix {Matrix} the transformation matrix of the sprite * @return {Rectangle} the framing rectangle */ -Strip.prototype.getBounds = function (matrix) { +Strip.prototype.getBounds = function (matrix) +{ var worldTransform = matrix || this.worldTransform; var a = worldTransform.a; @@ -404,7 +432,8 @@ var minY = Infinity; var vertices = this.vertices; - for (var i = 0, n = vertices.length; i < n; i += 2) { + for (var i = 0, n = vertices.length; i < n; i += 2) + { var rawX = vertices[i], rawY = vertices[i + 1]; var x = (a * rawX) + (c * rawY) + tx; var y = (d * rawY) + (b * rawX) + ty; @@ -416,7 +445,8 @@ maxY = y > maxY ? y : maxY; } - if (minX === -Infinity || maxY === Infinity) { + if (minX === -Infinity || maxY === Infinity) + { return core.math.Rectangle.EMPTY; } diff --git a/src/extras/TilingSprite.js b/src/extras/TilingSprite.js index 3ac22df..31da393 100644 --- a/src/extras/TilingSprite.js +++ b/src/extras/TilingSprite.js @@ -10,7 +10,8 @@ * @param width {number} the width of the tiling sprite * @param height {number} the height of the tiling sprite */ -function TilingSprite(texture, width, height) { +function TilingSprite(texture, width, height) +{ core.Sprite.call( this, texture); /** @@ -86,10 +87,12 @@ * @memberof TilingSprite# */ width: { - get: function () { + get: function () + { return this._width; }, - set: function (value) { + set: function (value) + { this._width = value; } }, @@ -101,20 +104,25 @@ * @memberof TilingSprite# */ height: { - get: function () { + get: function () + { return this._height; }, - set: function (value) { + set: function (value) + { this._height = value; } }, texture: { - get: function () { + get: function () + { return this._texture; }, - set: function (value) { - if (this._texture === value) { + set: function (value) + { + if (this._texture === value) + { return; } @@ -130,51 +138,61 @@ * * @param renderer {WebGLRenderer} */ -TilingSprite.prototype.renderWebGL = function (renderer) { - if (!this.visible || this.alpha <= 0) { +TilingSprite.prototype.renderWebGL = function (renderer) +{ + if (!this.visible || this.alpha <= 0) + { return; } var i, j; - if (this._mask) { + if (this._mask) + { renderer.spriteBatch.stop(); renderer.maskManager.pushMask(this.mask, renderer); renderer.spriteBatch.start(); } - if (this._filters) { + if (this._filters) + { renderer.spriteBatch.flush(); renderer.filterManager.pushFilter(this._filterBlock); } - if (!this.tilingTexture || this.refreshTexture) { + if (!this.tilingTexture || this.refreshTexture) + { this.generateTilingTexture(true); - if (this.tilingTexture && this.tilingTexture.needsUpdate) { + if (this.tilingTexture && this.tilingTexture.needsUpdate) + { //TODO - tweaking renderer.updateTexture(this.tilingTexture.baseTexture); this.tilingTexture.needsUpdate = false; // this.tilingTexture._uvs = null; } } - else { + else + { renderer.spriteBatch.renderTilingSprite(this); } // simple render children! - for (i=0,j=this.children.length; i= 0; i--) { + for (var i = length - 1; i >= 0; i--) + { var child = children[i]; // push all interactive bits - if (child._interactive) { + if (child._interactive) + { iParent.interactiveChildren = true; //child.__iParent = iParent; this.interactiveItems.push(child); - if (child.children.length > 0) { + if (child.children.length > 0) + { this.collectInteractiveSprite(child, child); } } - else { + else + { child.__iParent = null; - if (child.children.length > 0) { + if (child.children.length > 0) + { this.collectInteractiveSprite(child, iParent); } } @@ -189,7 +196,8 @@ * @param [resolution=1] {number} THe resolution of the new element (relative to the canvas). * @private */ -InteractionManager.prototype.setTargetElement = function (element, resolution) { +InteractionManager.prototype.setTargetElement = function (element, resolution) +{ this.removeEvents(); this.interactionDOMElement = element; @@ -203,12 +211,15 @@ * * @private */ -InteractionManager.prototype.addEvents = function () { - if (!this.interactionDOMElement) { +InteractionManager.prototype.addEvents = function () +{ + if (!this.interactionDOMElement) + { return; } - if (window.navigator.msPointerEnabled) { + if (window.navigator.msPointerEnabled) + { this.interactionDOMElement.style['-ms-content-zooming'] = 'none'; this.interactionDOMElement.style['-ms-touch-action'] = 'none'; } @@ -230,12 +241,15 @@ * * @private */ -InteractionManager.prototype.removeEvents = function () { - if (!this.interactionDOMElement) { +InteractionManager.prototype.removeEvents = function () +{ + if (!this.interactionDOMElement) + { return; } - if (window.navigator.msPointerEnabled) { + if (window.navigator.msPointerEnabled) + { this.interactionDOMElement.style['-ms-content-zooming'] = ''; this.interactionDOMElement.style['-ms-touch-action'] = ''; } @@ -260,8 +274,10 @@ * * @private */ -InteractionManager.prototype.update = function () { - if (!this.interactionDOMElement) { +InteractionManager.prototype.update = function () +{ + if (!this.interactionDOMElement) + { return; } @@ -269,7 +285,8 @@ var now = Date.now(); var diff = now - this.last; diff = (diff * INTERACTION_FREQUENCY ) / 1000; - if (diff < 1) { + if (diff < 1) + { return; } @@ -280,7 +297,8 @@ // ok.. so mouse events?? // yes for now :) // OPTIMISE - how often to check?? - if (this.dirty) { + if (this.dirty) + { this.rebuildInteractiveGraph(); } @@ -289,7 +307,8 @@ var cursor = 'inherit'; var over = false; - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { var item = this.interactiveItems[i]; // OPTIMISATION - only calculate every time if the mousemove function exists.. @@ -302,26 +321,34 @@ this.mouse.target = item; // ok so deal with interactions.. // looks like there was a hit! - if (item.__hit && !over) { - if (item.buttonMode) { + if (item.__hit && !over) + { + if (item.buttonMode) + { cursor = item.defaultCursor; } - if (!item.interactiveChildren) { + if (!item.interactiveChildren) + { over = true; } - if (!item.__isOver) { - if (item.mouseover) { + if (!item.__isOver) + { + if (item.mouseover) + { item.mouseover (this.mouse); } item.__isOver = true; } } - else { - if (item.__isOver) { + else + { + if (item.__isOver) + { // roll out! - if (item.mouseout) { + if (item.mouseout) + { item.mouseout (this.mouse); } item.__isOver = false; @@ -329,7 +356,8 @@ } } - if (this.currentCursorStyle !== cursor) { + if (this.currentCursorStyle !== cursor) + { this.currentCursorStyle = cursor; this.interactionDOMElement.style.cursor = cursor; } @@ -338,18 +366,21 @@ /** * @private */ -InteractionManager.prototype.rebuildInteractiveGraph = function () { +InteractionManager.prototype.rebuildInteractiveGraph = function () +{ this.dirty = false; var len = this.interactiveItems.length; - for (var i = 0; i < len; i++) { + for (var i = 0; i < len; i++) + { this.interactiveItems[i].interactiveChildren = false; } this.interactiveItems.length = 0; - if (this.stage.interactive) { + if (this.stage.interactive) + { this.interactiveItems.push(this.stage); } @@ -363,8 +394,10 @@ * @param event {Event} The DOM event of the mouse moving * @private */ -InteractionManager.prototype.onMouseMove = function (event) { - if (this.dirty) { +InteractionManager.prototype.onMouseMove = function (event) +{ + if (this.dirty) + { this.rebuildInteractiveGraph(); } @@ -378,11 +411,13 @@ var length = this.interactiveItems.length; - for (var i = 0; i < length; i++) { + for (var i = 0; i < length; i++) + { var item = this.interactiveItems[i]; // Call the function! - if (item.mousemove) { + if (item.mousemove) + { item.mousemove(this.mouse); } } @@ -394,14 +429,17 @@ * @param event {Event} The DOM event of a mouse button being pressed down * @private */ -InteractionManager.prototype.onMouseDown = function (event) { - if (this.dirty) { +InteractionManager.prototype.onMouseDown = function (event) +{ + if (this.dirty) + { this.rebuildInteractiveGraph(); } this.mouse.originalEvent = event; - if (AUTO_PREVENT_DEFAULT) { + if (AUTO_PREVENT_DEFAULT) + { this.mouse.originalEvent.preventDefault(); } @@ -420,22 +458,27 @@ // while // hit test - for (var i = 0; i < length; i++) { + for (var i = 0; i < length; i++) + { var item = this.interactiveItems[i]; - if (item[downFunction] || item[clickFunction]) { + if (item[downFunction] || item[clickFunction]) + { item[buttonIsDown] = true; item.__hit = this.hitTest(item, this.mouse); - if (item.__hit) { + if (item.__hit) + { //call the function! - if (item[downFunction]) { + if (item[downFunction]) + { item[downFunction](this.mouse); } item[isDown] = true; // just the one! - if (!item.interactiveChildren) { + if (!item.interactiveChildren) + { break; } } @@ -449,8 +492,10 @@ * @param event {Event} The DOM event of a mouse being moved out * @private */ -InteractionManager.prototype.onMouseOut = function (event) { - if (this.dirty) { +InteractionManager.prototype.onMouseOut = function (event) +{ + if (this.dirty) + { this.rebuildInteractiveGraph(); } @@ -460,11 +505,14 @@ this.interactionDOMElement.style.cursor = 'inherit'; - for (var i = 0; i < length; i++) { + for (var i = 0; i < length; i++) + { var item = this.interactiveItems[i]; - if (item.__isOver) { + if (item.__isOver) + { this.mouse.target = item; - if (item.mouseout) { + if (item.mouseout) + { item.mouseout(this.mouse); } item.__isOver = false; @@ -484,8 +532,10 @@ * @param event {Event} The DOM event of a mouse button being released * @private */ -InteractionManager.prototype.onMouseUp = function (event) { - if (this.dirty) { +InteractionManager.prototype.onMouseUp = function (event) +{ + if (this.dirty) + { this.rebuildInteractiveGraph(); } @@ -502,30 +552,40 @@ var upOutsideFunction = isRightButton ? 'rightupoutside' : 'mouseupoutside'; var isDown = isRightButton ? '__isRightDown' : '__isDown'; - for (var i = 0; i < length; i++) { + for (var i = 0; i < length; i++) + { var item = this.interactiveItems[i]; - if (item[clickFunction] || item[upFunction] || item[upOutsideFunction]) { + if (item[clickFunction] || item[upFunction] || item[upOutsideFunction]) + { item.__hit = this.hitTest(item, this.mouse); - if (item.__hit && !up) { + if (item.__hit && !up) + { //call the function! - if (item[upFunction]) { + if (item[upFunction]) + { item[upFunction](this.mouse); } - if (item[isDown]) { - if (item[clickFunction]) { + if (item[isDown]) + { + if (item[clickFunction]) + { item[clickFunction](this.mouse); } } - if (!item.interactiveChildren) { + if (!item.interactiveChildren) + { up = true; } } - else { - if (item[isDown]) { - if (item[upOutsideFunction]) { + else + { + if (item[isDown]) + { + if (item[upOutsideFunction]) + { item[upOutsideFunction](this.mouse); } } @@ -543,10 +603,12 @@ * @param interactionData {InteractionData} The interactionData object to update in the case there is a hit * @private */ -InteractionManager.prototype.hitTest = function (item, interactionData) { +InteractionManager.prototype.hitTest = function (item, interactionData) +{ var global = interactionData.global; - if (!item.worldVisible) { + if (!item.worldVisible) + { return false; } @@ -560,37 +622,46 @@ interactionData.target = item; //a sprite or display object with a hit area defined - if (item.hitArea && item.hitArea.contains) { + if (item.hitArea && item.hitArea.contains) + { return item.hitArea.contains(x, y); } // a sprite with no hitarea defined - else if (item instanceof core.Sprite) { + else if (item instanceof core.Sprite) + { var width = item.texture.frame.width; var height = item.texture.frame.height; var x1 = -width * item.anchor.x; var y1; - if (x > x1 && x < x1 + width) { + if (x > x1 && x < x1 + width) + { y1 = -height * item.anchor.y; - if (y > y1 && y < y1 + height) { + if (y > y1 && y < y1 + height) + { // set the target property if a hit is true! return true; } } } - else if (item instanceof core.Graphics) { + else if (item instanceof core.Graphics) + { var graphicsData = item.graphicsData; - for (i = 0; i < graphicsData.length; i++) { + for (i = 0; i < graphicsData.length; i++) + { var data = graphicsData[i]; - if (!data.fill) { + if (!data.fill) + { continue; } // only deal with fills.. - if (data.shape) { - if (data.shape.contains(x, y)) { + if (data.shape) + { + if (data.shape.contains(x, y)) + { //interactionData.target = item; return true; } @@ -600,10 +671,12 @@ var length = item.children.length; - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { var tempItem = item.children[i]; var hit = this.hitTest(tempItem, interactionData); - if (hit) { + if (hit) + { // hmm.. TODO SET CORRECT TARGET? interactionData.target = item; return true; @@ -618,8 +691,10 @@ * @param event {Event} The DOM event of a touch moving across the renderer view * @private */ -InteractionManager.prototype.onTouchMove = function (event) { - if (this.dirty) { +InteractionManager.prototype.onTouchMove = function (event) +{ + if (this.dirty) + { this.rebuildInteractiveGraph(); } @@ -628,7 +703,8 @@ var touchData; var i = 0; - for (i = 0; i < changedTouches.length; i++) { + for (i = 0; i < changedTouches.length; i++) + { var touchEvent = changedTouches[i]; touchData = this.touches[touchEvent.identifier]; touchData.originalEvent = event; @@ -636,15 +712,18 @@ // update the touch position touchData.global.x = ( (touchEvent.clientX - rect.left) * (this.interactionDOMElement.width / rect.width) ) / this.resolution; touchData.global.y = ( (touchEvent.clientY - rect.top) * (this.interactionDOMElement.height / rect.height) ) / this.resolution; - if (navigator.isCocoonJS && !rect.left && !rect.top && !event.target.style.width && !event.target.style.height) { + if (navigator.isCocoonJS && !rect.left && !rect.top && !event.target.style.width && !event.target.style.height) + { //Support for CocoonJS fullscreen scale modes touchData.global.x = touchEvent.clientX; touchData.global.y = touchEvent.clientY; } - for (var j = 0; j < this.interactiveItems.length; j++) { + for (var j = 0; j < this.interactiveItems.length; j++) + { var item = this.interactiveItems[j]; - if (item.touchmove && item.__touchData && item.__touchData[touchEvent.identifier]) { + if (item.touchmove && item.__touchData && item.__touchData[touchEvent.identifier]) + { item.touchmove(touchData); } } @@ -657,23 +736,28 @@ * @param event {Event} The DOM event of a touch starting on the renderer view * @private */ -InteractionManager.prototype.onTouchStart = function (event) { - if (this.dirty) { +InteractionManager.prototype.onTouchStart = function (event) +{ + if (this.dirty) + { this.rebuildInteractiveGraph(); } var rect = this.interactionDOMElement.getBoundingClientRect(); - if (AUTO_PREVENT_DEFAULT) { + if (AUTO_PREVENT_DEFAULT) + { event.preventDefault(); } var changedTouches = event.changedTouches; - for (var i=0; i < changedTouches.length; i++) { + for (var i=0; i < changedTouches.length; i++) + { var touchEvent = changedTouches[i]; var touchData = this.pool.pop(); - if (!touchData) { + if (!touchData) + { touchData = new InteractionData(); } @@ -682,7 +766,8 @@ this.touches[touchEvent.identifier] = touchData; touchData.global.x = ( (touchEvent.clientX - rect.left) * (this.interactionDOMElement.width / rect.width) ) / this.resolution; touchData.global.y = ( (touchEvent.clientY - rect.top) * (this.interactionDOMElement.height / rect.height) ) / this.resolution; - if (navigator.isCocoonJS && !rect.left && !rect.top && !event.target.style.width && !event.target.style.height) { + if (navigator.isCocoonJS && !rect.left && !rect.top && !event.target.style.width && !event.target.style.height) + { //Support for CocoonJS fullscreen scale modes touchData.global.x = touchEvent.clientX; touchData.global.y = touchEvent.clientY; @@ -690,15 +775,19 @@ var length = this.interactiveItems.length; - for (var j = 0; j < length; j++) { + for (var j = 0; j < length; j++) + { var item = this.interactiveItems[j]; - if (item.touchstart || item.tap) { + if (item.touchstart || item.tap) + { item.__hit = this.hitTest(item, touchData); - if (item.__hit) { + if (item.__hit) + { //call the function! - if (item.touchstart) { + if (item.touchstart) + { item.touchstart(touchData); } @@ -706,7 +795,8 @@ item.__touchData = item.__touchData || {}; item.__touchData[touchEvent.identifier] = touchData; - if (!item.interactiveChildren) { + if (!item.interactiveChildren) + { break; } } @@ -721,31 +811,37 @@ * @param event {Event} The DOM event of a touch ending on the renderer view * @private */ -InteractionManager.prototype.onTouchEnd = function (event) { - if (this.dirty) { +InteractionManager.prototype.onTouchEnd = function (event) +{ + if (this.dirty) + { this.rebuildInteractiveGraph(); } var rect = this.interactionDOMElement.getBoundingClientRect(); var changedTouches = event.changedTouches; - for (var i=0; i < changedTouches.length; i++) { + for (var i=0; i < changedTouches.length; i++) + { var touchEvent = changedTouches[i]; var touchData = this.touches[touchEvent.identifier]; var up = false; touchData.global.x = ( (touchEvent.clientX - rect.left) * (this.interactionDOMElement.width / rect.width) ) / this.resolution; touchData.global.y = ( (touchEvent.clientY - rect.top) * (this.interactionDOMElement.height / rect.height) ) / this.resolution; - if (navigator.isCocoonJS && !rect.left && !rect.top && !event.target.style.width && !event.target.style.height) { + if (navigator.isCocoonJS && !rect.left && !rect.top && !event.target.style.width && !event.target.style.height) + { //Support for CocoonJS fullscreen scale modes touchData.global.x = touchEvent.clientX; touchData.global.y = touchEvent.clientY; } var length = this.interactiveItems.length; - for (var j = 0; j < length; j++) { + for (var j = 0; j < length; j++) + { var item = this.interactiveItems[j]; - if (item.__touchData && item.__touchData[touchEvent.identifier]) { + if (item.__touchData && item.__touchData[touchEvent.identifier]) + { item.__hit = this.hitTest(item, item.__touchData[touchEvent.identifier]); @@ -753,20 +849,27 @@ touchData.originalEvent = event; // hitTest?? - if (item.touchend || item.tap) { - if (item.__hit && !up) { - if (item.touchend) { + if (item.touchend || item.tap) + { + if (item.__hit && !up) + { + if (item.touchend) + { item.touchend(touchData); } - if (item.__isDown && item.tap) { + if (item.__isDown && item.tap) + { item.tap(touchData); } - if (!item.interactiveChildren) { + if (!item.interactiveChildren) + { up = true; } } - else { - if (item.__isDown && item.touchendoutside) { + else + { + if (item.__isDown && item.touchendoutside) + { item.touchendoutside(touchData); } } diff --git a/src/loaders/AssetLoader.js b/src/loaders/AssetLoader.js index 20da0cf..c4dba1c 100644 --- a/src/loaders/AssetLoader.js +++ b/src/loaders/AssetLoader.js @@ -21,7 +21,8 @@ * data formats include 'xml' and 'fnt'. * @param crossorigin {boolean} Whether requests should be treated as crossorigin */ -function AssetLoader(assetURLs, crossorigin) { +function AssetLoader(assetURLs, crossorigin) +{ /** * The array of asset URLs that are going to be loaded * @@ -76,16 +77,19 @@ * * @param str {string} the name of the asset */ -AssetLoader.prototype._getDataType = function (str) { +AssetLoader.prototype._getDataType = function (str) +{ var test = 'data:'; var start = str.slice(0, test.length).toLowerCase(); - if (start === test) { + if (start === test) + { var data = str.slice(test.length); var sepIdx = data.indexOf(','); // check for malformed data URI scheme - if (sepIdx === -1) { + if (sepIdx === -1) + { return null; } @@ -94,7 +98,8 @@ //We might need to handle some special cases here... //standardize text/plain to 'txt' file extension - if (!info || info.toLowerCase() === 'text/plain') { + if (!info || info.toLowerCase() === 'text/plain') + { return 'txt'; } @@ -109,27 +114,32 @@ * Starts loading the assets sequentially * */ -AssetLoader.prototype.load = function () { +AssetLoader.prototype.load = function () +{ var scope = this; - function onLoad(evt) { + function onLoad(evt) + { scope.onAssetLoaded(evt.data.content); } this.loadCount = this.assetURLs.length; - for (var i=0; i < this.assetURLs.length; i++) { + for (var i=0; i < this.assetURLs.length; i++) + { var fileName = this.assetURLs[i]; //first see if we have a data URI scheme.. var fileType = this._getDataType(fileName); //if not, assume it's a file URI - if (!fileType) { + if (!fileType) + { fileType = fileName.split('?').shift().split('.').pop().toLowerCase(); } var Constructor = this.loadersByType[fileType]; - if (!Constructor) { + if (!Constructor) + { throw new Error(fileType + ' is an unsupported file type'); } @@ -145,18 +155,22 @@ * * @private */ -AssetLoader.prototype.onAssetLoaded = function (loader) { +AssetLoader.prototype.onAssetLoaded = function (loader) +{ this.loadCount--; this.emit('onProgress', { content: this, loader: loader }); - if (this.onProgress) { + if (this.onProgress) + { this.onProgress(loader); } - if (!this.loadCount) { + if (!this.loadCount) + { this.emit('onComplete', { content: this }); - if (this.onComplete) { + if (this.onComplete) + { this.onComplete(); } } diff --git a/src/core/display/DisplayObject.js b/src/core/display/DisplayObject.js index 66ebc3c..20e778c 100644 --- a/src/core/display/DisplayObject.js +++ b/src/core/display/DisplayObject.js @@ -7,7 +7,8 @@ * @class * @namespace PIXI */ -function DisplayObject() { +function DisplayObject() +{ /** * The coordinate of the object relative to the local coordinates of the parent. * @@ -152,10 +153,12 @@ * @memberof DisplayObject# */ x: { - get: function () { + get: function () + { return this.position.x; }, - set: function (value) { + set: function (value) + { this.position.x = value; } }, @@ -167,10 +170,12 @@ * @memberof DisplayObject# */ y: { - get: function () { + get: function () + { return this.position.y; }, - set: function (value) { + set: function (value) + { this.position.y = value; } }, @@ -183,11 +188,13 @@ * @readonly */ worldVisible: { - get: function () { + get: function () + { var item = this; do { - if (!item.visible) { + if (!item.visible) + { return false; } @@ -207,17 +214,21 @@ * @memberof DisplayObject# */ mask: { - get: function () { + get: function () + { return this._mask; }, - set: function (value) { - if (this._mask) { + set: function (value) + { + if (this._mask) + { this._mask.isMask = false; } this._mask = value; - if (this._mask) { + if (this._mask) + { this._mask.isMask = true; } } @@ -232,18 +243,23 @@ * @memberof DisplayObject# */ filters: { - get: function () { + get: function () + { return this._filters; }, - set: function (value) { - if (value) { + set: function (value) + { + if (value) + { // now put all the passes in one place.. var passes = []; - for (var i = 0; i < value.length; i++) { + for (var i = 0; i < value.length; i++) + { var filterPasses = value[i].passes; - for (var j = 0; j < filterPasses.length; j++) { + for (var j = 0; j < filterPasses.length; j++) + { passes.push(filterPasses[j]); } } @@ -264,8 +280,9 @@ * * @private */ -DisplayObject.prototype.updateTransform = function () { - +DisplayObject.prototype.updateTransform = function () +{ + // create some matrix refs for easy access var pt = this.parent.worldTransform; var wt = this.worldTransform; @@ -274,9 +291,11 @@ var a, b, c, d, tx, ty; // so if rotation is between 0 then we can simplify the multiplication process.. - if (this.rotation % math.PI_2) { + if (this.rotation % math.PI_2) + { // 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) { + if (this.rotation !== this.rotationCache) + { this.rotationCache = this.rotation; this._sr = Math.sin(this.rotation); this._cr = Math.cos(this.rotation); @@ -291,7 +310,8 @@ ty = this.position.y; // check for pivot.. not often used so geared towards that fact! - if (this.pivot.x || this.pivot.y) { + 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; } @@ -304,7 +324,8 @@ wt.tx = tx * pt.a + ty * pt.c + pt.tx; wt.ty = tx * pt.b + ty * pt.d + pt.ty; } - else { + else + { // lets do the fast version as we know there is no rotation.. a = this.scale.x; d = this.scale.y; @@ -333,7 +354,8 @@ * @param matrix {Matrix} * @return {Rectangle} the rectangular bounding area */ -DisplayObject.prototype.getBounds = function (/* matrix */) { +DisplayObject.prototype.getBounds = function (/* matrix */) +{ return math.Rectangle.EMPTY; }; @@ -342,7 +364,8 @@ * * @return {Rectangle} the rectangular bounding area */ -DisplayObject.prototype.getLocalBounds = function () { +DisplayObject.prototype.getLocalBounds = function () +{ return this.getBounds(math.Matrix.IDENTITY); }; @@ -352,7 +375,8 @@ * @param position {Point} The world origin to calculate from * @return {Point} A point object representing the position of this object */ -DisplayObject.prototype.toGlobal = function (position) { +DisplayObject.prototype.toGlobal = function (position) +{ // don't need to u[date the lot this.displayObjectUpdateTransform(); return this.worldTransform.apply(position); @@ -365,8 +389,10 @@ * @param [from] {DisplayObject} The DisplayObject to calculate the global position from * @return {Point} A point object representing the position of this object */ -DisplayObject.prototype.toLocal = function (position, from) { - if (from) { +DisplayObject.prototype.toLocal = function (position, from) +{ + if (from) + { position = from.toGlobal(position); } @@ -381,7 +407,8 @@ * @param renderer {WebGLRenderer} The renderer * @private */ -DisplayObject.prototype.renderWebGL = function (/* renderer */) { +DisplayObject.prototype.renderWebGL = function (/* renderer */) +{ // OVERWRITE; }; @@ -391,6 +418,7 @@ * @param renderer {CanvasRenderer} The renderer * @private */ -DisplayObject.prototype.renderCanvas = function (/* renderer */) { +DisplayObject.prototype.renderCanvas = function (/* renderer */) +{ // OVERWRITE; }; diff --git a/src/core/display/DisplayObjectContainer.js b/src/core/display/DisplayObjectContainer.js index 689f40b..4625ee8 100644 --- a/src/core/display/DisplayObjectContainer.js +++ b/src/core/display/DisplayObjectContainer.js @@ -12,7 +12,8 @@ * @extends DisplayObject * @namespace PIXI */ -function DisplayObjectContainer() { +function DisplayObjectContainer() +{ DisplayObject.call(this); /** @@ -47,17 +48,21 @@ * @memberof DisplayObjectContainer# */ width: { - get: function () { + get: function () + { return this.scale.x * this.getLocalBounds().width; }, - set: function (value) { + set: function (value) + { var width = this.getLocalBounds().width; - if(width !== 0) { + if(width !== 0) + { this.scale.x = value / width; } - else { + else + { this.scale.x = 1; } @@ -73,17 +78,21 @@ * @memberof DisplayObjectContainer# */ height: { - get: function () { + get: function () + { return this.scale.y * this.getLocalBounds().height; }, - set: function (value) { + set: function (value) + { var height = this.getLocalBounds().height; - if (height !== 0) { + if (height !== 0) + { this.scale.y = value / height ; } - else { + else + { this.scale.y = 1; } @@ -100,18 +109,23 @@ * @memberof DisplayObject# */ cacheAsBitmap: { - get: function () { + get: function () + { return this._cacheAsBitmap; }, - set: function (value) { - if (this._cacheAsBitmap === value) { + set: function (value) + { + if (this._cacheAsBitmap === value) + { return; } - if (value) { + if (value) + { this._generateCachedSprite(); } - else { + else + { this._destroyCachedSprite(); } @@ -126,7 +140,8 @@ * @param child {DisplayObject} The DisplayObject to add to the container * @return {DisplayObject} The child that was added. */ -DisplayObjectContainer.prototype.addChild = function (child) { +DisplayObjectContainer.prototype.addChild = function (child) +{ return this.addChildAt(child, this.children.length); }; @@ -137,14 +152,18 @@ * @param index {Number} The index to place the child in * @return {DisplayObject} The child that was added. */ -DisplayObjectContainer.prototype.addChildAt = function (child, index) { +DisplayObjectContainer.prototype.addChildAt = function (child, index) +{ // prevent adding self as child - if (child === this) { + if (child === this) + { return; } - if (index >= 0 && index <= this.children.length) { - if (child.parent) { + if (index >= 0 && index <= this.children.length) + { + if (child.parent) + { child.parent.removeChild(child); } @@ -154,7 +173,8 @@ return child; } - else { + else + { throw new Error(child + 'addChildAt: The index '+ index +' supplied is out of bounds ' + this.children.length); } }; @@ -165,15 +185,18 @@ * @param child {DisplayObject} * @param child2 {DisplayObject} */ -DisplayObjectContainer.prototype.swapChildren = function (child, child2) { - if (child === child2) { +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) { + if (index1 < 0 || index2 < 0) + { throw new Error('swapChildren: Both the supplied DisplayObjects must be a child of the caller.'); } @@ -187,10 +210,12 @@ * @param child {DisplayObject} The DisplayObject instance to identify * @return {Number} The index position of the child display object to identify */ -DisplayObjectContainer.prototype.getChildIndex = function (child) { +DisplayObjectContainer.prototype.getChildIndex = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { throw new Error('The supplied DisplayObject must be a child of the caller'); } @@ -203,8 +228,10 @@ * @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 */ -DisplayObjectContainer.prototype.setChildIndex = function (child, index) { - if (index < 0 || index >= this.children.length) { +DisplayObjectContainer.prototype.setChildIndex = function (child, index) +{ + if (index < 0 || index >= this.children.length) + { throw new Error('The supplied index is out of bounds'); } @@ -220,8 +247,10 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child at the given index, if any. */ -DisplayObjectContainer.prototype.getChildAt = function (index) { - if (index < 0 || index >= this.children.length) { +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'); } @@ -234,10 +263,12 @@ * @param child {DisplayObject} The DisplayObject to remove * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChild = function (child) { +DisplayObjectContainer.prototype.removeChild = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { return; } @@ -250,7 +281,8 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChildAt = function (index) { +DisplayObjectContainer.prototype.removeChildAt = function (index) +{ var child = this.getChildAt(index); child.parent = null; @@ -265,24 +297,29 @@ * @param beginIndex {Number} The beginning position. Default value is 0. * @param endIndex {Number} The ending position. Default value is size of the container. */ -DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) { +DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) +{ var begin = beginIndex || 0; var end = typeof endIndex === 'number' ? endIndex : this.children.length; var range = end - begin; - if (range > 0 && range <= end) { + if (range > 0 && range <= end) + { var removed = this.children.splice(begin, range); - for (var i = 0; i < removed.length; ++i) { + for (var i = 0; i < removed.length; ++i) + { removed[i].parent = null; } return removed; } - else if (range === 0 && this.children.length === 0) { + else if (range === 0 && this.children.length === 0) + { return []; } - else { + else + { throw new RangeError('removeChildren: numeric values are outside the acceptable range.'); } }; @@ -291,7 +328,8 @@ * Generates and updates the cached sprite for this object. * */ -DisplayObjectContainer.prototype.updateCachedSprite = function () { +DisplayObjectContainer.prototype.updateCachedSprite = function () +{ this._generateCachedSprite(); }; @@ -304,7 +342,8 @@ * @param renderer {CanvasRenderer|WebGLRenderer} The renderer used to generate the texture. * @return {Texture} a texture of the graphics object */ -DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) { +DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) +{ var bounds = this.getLocalBounds(); var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0, renderer, scaleMode, resolution); @@ -322,18 +361,22 @@ * * @private */ -DisplayObjectContainer.prototype.updateTransform = function () { - if (!this.visible) { +DisplayObjectContainer.prototype.updateTransform = function () +{ + if (!this.visible) + { return; } this.displayObjectUpdateTransform(); - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { return; } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } }; @@ -346,8 +389,10 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getBounds = function () { - if (this.children.length === 0) { +DisplayObjectContainer.prototype.getBounds = function () +{ + if (this.children.length === 0) + { return math.Rectangle.EMPTY; } @@ -365,10 +410,12 @@ var childVisible = false; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -386,7 +433,8 @@ maxY = maxY > childMaxY ? maxY : childMaxY; } - if (!childVisible) { + if (!childVisible) + { return math.Rectangle.EMPTY; } @@ -407,12 +455,14 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getLocalBounds = function () { +DisplayObjectContainer.prototype.getLocalBounds = function () +{ var matrixCache = this.worldTransform; this.worldTransform = math.Matrix.IDENTITY; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } @@ -428,13 +478,16 @@ * * @param renderer {WebGLRenderer} The renderer */ -DisplayObjectContainer.prototype.renderWebGL = function (renderer) { +DisplayObjectContainer.prototype.renderWebGL = function (renderer) +{ // if the object is not visible or the alpha is 0 then no need to render this element - if (!this.visible || this.alpha <= 0) { + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } @@ -442,14 +495,17 @@ var i, j; // do a quick check to see if this element has a mask or a filter. - if (this._mask || this._filters) { + if (this._mask || this._filters) + { // push filter first as we need to ensure the stencil buffer is correct for any masking - if (this._filters) { + if (this._filters) + { renderer.spriteBatch.flush(); renderer.filterManager.pushFilter(this._filterBlock); } - if (this._mask) { + if (this._mask) + { renderer.spriteBatch.stop(); renderer.maskManager.pushMask(this.mask, renderer); renderer.spriteBatch.start(); @@ -459,36 +515,42 @@ this._renderWebGL(renderer); // now loop through the children and make sure they get rendered - for (i = 0, j = this.children.length; i < j; i++) { + for (i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderWebGL(renderer); } // time to stop the sprite batch as either a mask element or a filter draw will happen next renderer.spriteBatch.stop(); - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(this._mask, renderer); } - if (this._filters) { + if (this._filters) + { renderer.filterManager.popFilter(); } renderer.spriteBatch.start(); } - else { + else + { this._renderWebGL(renderer); // simple render children! - for (i = 0, j = this.children.length; i < j; ++i) { + for (i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderWebGL(renderer); } } }; -DisplayObjectContainer.prototype._renderWebGL = function (renderer) { +DisplayObjectContainer.prototype._renderWebGL = function (renderer) +{ // this is where content itself gets renderd.. @@ -499,25 +561,31 @@ * * @param renderer {CanvasRenderer} The renderer */ -DisplayObjectContainer.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0) { +DisplayObjectContainer.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -528,13 +596,16 @@ * @param renderer {WebGLRenderer|CanvasRenderer} The renderer * @private */ -DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) { +DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) +{ this._cachedSprite.worldAlpha = this.worldAlpha; - if (renderer.gl) { + if (renderer.gl) + { this._cachedSprite.renderWebGL(renderer); } - else { + else + { this._cachedSprite.renderCanvas(renderer); } }; @@ -544,10 +615,12 @@ * * @private */ -DisplayObjectContainer.prototype._generateCachedSprite = function () { +DisplayObjectContainer.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { // TODO - RenderTexture now *requires* a renderer instance, so this is like broken // because `renderer` isn't actually in scope here :P var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0); @@ -555,7 +628,8 @@ this._cachedSprite = new Sprite(renderTexture); this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.texture.resize(bounds.width | 0, bounds.height | 0); } @@ -580,8 +654,10 @@ * * @private */ -DisplayObjectContainer.prototype._destroyCachedSprite = function () { - if (!this._cachedSprite) { +DisplayObjectContainer.prototype._destroyCachedSprite = function () +{ + if (!this._cachedSprite) + { return; } diff --git a/src/core/display/Sprite.js b/src/core/display/Sprite.js index 707da24..5862aef 100644 --- a/src/core/display/Sprite.js +++ b/src/core/display/Sprite.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param texture {Texture} The texture for this sprite */ -function Sprite(texture) { +function Sprite(texture) +{ DisplayObjectContainer.call(this); /** @@ -85,12 +86,14 @@ this.texture = texture || Texture.EMPTY; } -Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) { +Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) +{ DisplayObjectContainer.prototype.destroy.call(this); this.anchor = null; - if (destroyTexture) { + if (destroyTexture) + { this._texture.destroy(destroyBaseTexture); } @@ -111,10 +114,12 @@ * @memberof Sprite# */ width: { - get: function () { + get: function () + { return this.scale.x * this.texture.frame.width; }, - set: function (value) { + set: function (value) + { this.scale.x = value / this.texture.frame.width; this._width = value; } @@ -127,10 +132,12 @@ * @memberof Sprite# */ height: { - get: function () { + get: function () + { return this.scale.y * this.texture.frame.height; }, - set: function (value) { + set: function (value) + { this.scale.y = value / this.texture.frame.height; this._height = value; } @@ -143,23 +150,29 @@ * @memberof Sprite# */ texture: { - get: function () { + get: function () + { return this._texture; }, - set: function (value) { - if (this._texture === value) { + set: function (value) + { + if (this._texture === value) + { return; } this._texture = value; this.cachedTint = 0xFFFFFF; - if (value) { + if (value) + { // wait for the texture to load - if (value.baseTexture.hasLoaded) { + if (value.baseTexture.hasLoaded) + { this._onTextureUpdate(); } - else { + else + { value.once('update', this._onTextureUpdate.bind(this)); } } @@ -172,18 +185,22 @@ * * @private */ -Sprite.prototype._onTextureUpdate = function () { +Sprite.prototype._onTextureUpdate = function () +{ // so if _width is 0 then width was not set.. - if (this._width) { + if (this._width) + { this.scale.x = this._width / this.texture.frame.width; } - if (this._height) { + if (this._height) + { this.scale.y = this._height / this.texture.frame.height; } }; -Sprite.prototype._renderWebGL = function (renderer) { +Sprite.prototype._renderWebGL = function (renderer) +{ // this is where content gets renderd.. // watch this space for a little render state manager.. @@ -197,7 +214,8 @@ * @param matrix {Matrix} the transformation matrix of the sprite * @return {Rectangle} the framing rectangle */ -Sprite.prototype.getBounds = function (matrix) { +Sprite.prototype.getBounds = function (matrix) +{ var width = this.texture.frame.width; var height = this.texture.frame.height; @@ -224,11 +242,13 @@ if(b === 0 && c === 0) { // scale may be negative! - if (a < 0) { + if (a < 0) + { a *= -1; } - if (d < 0) { + if (d < 0) + { d *= -1; } @@ -293,28 +313,34 @@ * * @param renderer {CanvasRenderer} The renderer */ -Sprite.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) { +Sprite.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) + { return; } - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; renderer.context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } // Ignore null sources - if (this.texture.valid) { + if (this.texture.valid) + { var resolution = this.texture.baseTexture.resolution / renderer.resolution; renderer.context.globalAlpha = this.worldAlpha; // If smoothingEnabled is supported and we need to change the smoothing property for this texture - if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) { + if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) + { renderer.scaleMode = this.texture.baseTexture.scaleMode; renderer.context[renderer.smoothProperty] = (renderer.scaleMode === CONST.scaleModes.LINEAR); } @@ -324,7 +350,8 @@ var dy = (this.texture.trim ? this.texture.trim.y : 0) - (this.anchor.y * this.texture.trim.height); // Allow for pixel rounding - if (renderer.roundPixels) { + if (renderer.roundPixels) + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -337,7 +364,8 @@ dx = dx | 0; dy = dy | 0; } - else { + else + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -348,8 +376,10 @@ ); } - if (this.tint !== 0xFFFFFF) { - if (this.cachedTint !== this.tint) { + if (this.tint !== 0xFFFFFF) + { + if (this.cachedTint !== this.tint) + { this.cachedTint = this.tint; // TODO clean up caching - how to clean up the caches? @@ -368,7 +398,8 @@ this.texture.crop.height / resolution ); } - else { + else + { renderer.context.drawImage( this.texture.baseTexture.source, this.texture.crop.x, @@ -383,11 +414,13 @@ } } - for (var i = 0, j = this.children.length; i < j; i++) { + for (var i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -402,10 +435,12 @@ * @param frameId {String} The frame Id of the texture in the cache * @return {Sprite} A new Sprite using a texture from the texture cache matching the frameId */ -Sprite.fromFrame = function (frameId) { +Sprite.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache' + this); } @@ -420,6 +455,7 @@ * @param imageId {String} The image url of the texture * @return {Sprite} A new Sprite using a texture from the texture cache matching the image id */ -Sprite.fromImage = function (imageId, crossorigin, scaleMode) { +Sprite.fromImage = function (imageId, crossorigin, scaleMode) +{ return new Sprite(Texture.fromImage(imageId, crossorigin, scaleMode)); }; diff --git a/src/core/display/SpriteBatch.js b/src/core/display/SpriteBatch.js index 3187777..c196fef 100644 --- a/src/core/display/SpriteBatch.js +++ b/src/core/display/SpriteBatch.js @@ -12,7 +12,8 @@ * ```js * var container = new SpriteBatch(); * - * for(var i = 0; i < 100; ++i) { + * for(var i = 0; i < 100; ++i) + * { * var sprite = new PIXI.Sprite.fromImage("myImage.png"); * container.addChild(sprite); * } @@ -25,7 +26,8 @@ */ //TODO RENAME to PARTICLE CONTAINER? -function SpriteBatch() { +function SpriteBatch() +{ DisplayObjectContainer.call(this); } @@ -38,7 +40,8 @@ * * @private */ -SpriteBatch.prototype.updateTransform = function () { +SpriteBatch.prototype.updateTransform = function () +{ // TODO don't need to! this.displayObjectUpdateTransform(); // PIXI.DisplayObjectContainer.prototype.updateTransform.call( this ); @@ -50,8 +53,10 @@ * @param renderer {WebGLRenderer} The webgl renderer * @private */ -SpriteBatch.prototype.renderWebGL = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderWebGL = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -71,8 +76,10 @@ * @param renderer {CanvasRenderer} The canvas renderer * @private */ -SpriteBatch.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -84,10 +91,12 @@ this.displayObjectUpdateTransform(); - for (var i = 0; i < this.children.length; ++i) { + for (var i = 0; i < this.children.length; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -95,9 +104,11 @@ context.globalAlpha = this.worldAlpha * child.alpha; - if (child.rotation % (Math.PI * 2) === 0) { + if (child.rotation % (Math.PI * 2) === 0) + { // this is the fastest way to optimise! - if rotation is 0 then we can avoid any kind of setTransform call - if (isRotated) { + if (isRotated) + { context.setTransform( transform.a, transform.b, @@ -122,8 +133,10 @@ frame.height * child.scale.y ); } - else { - if (!isRotated) { + else + { + if (!isRotated) + { isRotated = true; } @@ -131,7 +144,8 @@ var childTransform = child.worldTransform; - if (renderer.roundPixels) { + if (renderer.roundPixels) + { context.setTransform( childTransform.a, childTransform.b, @@ -141,7 +155,8 @@ childTransform.ty | 0 ); } - else { + else + { context.setTransform( childTransform.a, childTransform.b, diff --git a/src/core/index.js b/src/core/index.js index 3954b6f..eb4a82b 100644 --- a/src/core/index.js +++ b/src/core/index.js @@ -58,11 +58,13 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRenderer: function (width, height, options, noWebGL) { + autoDetectRenderer: function (width, height, options, noWebGL) + { width = width || 800; height = height || 600; - if (!noWebGL && require('webgl-enabled')()) { + if (!noWebGL && require('webgl-enabled')()) + { return new core.WebGLRenderer(width, height, options); } @@ -87,7 +89,8 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRecommendedRenderer: function (width, height, options) { + autoDetectRecommendedRenderer: function (width, height, options) + { var isAndroid = /Android/i.test(navigator.userAgent); return core.autoDetectRenderer(width, height, options, isAndroid); diff --git a/src/core/math/Matrix.js b/src/core/math/Matrix.js index c2f87e2..2ff4848 100644 --- a/src/core/math/Matrix.js +++ b/src/core/math/Matrix.js @@ -10,7 +10,8 @@ * @class * @namespace PIXI */ -function Matrix() { +function Matrix() +{ /** * @member {number} * @default 1 @@ -63,7 +64,8 @@ * * @param array {number[]} The array that the matrix will be populated from. */ -Matrix.prototype.fromArray = function (array) { +Matrix.prototype.fromArray = function (array) +{ this.a = array[0]; this.b = array[1]; this.c = array[3]; @@ -78,14 +80,17 @@ * @param transpose {boolean} Whether we need to transpose the matrix or not * @return {number[]} the newly created array which contains the matrix */ -Matrix.prototype.toArray = function (transpose) { - if (!this.array) { +Matrix.prototype.toArray = function (transpose) +{ + if (!this.array) + { this.array = new Float32Array(9); } var array = this.array; - if (transpose) { + if (transpose) + { array[0] = this.a; array[1] = this.b; array[2] = 0; @@ -96,7 +101,8 @@ array[7] = this.ty; array[8] = 1; } - else { + else + { array[0] = this.a; array[1] = this.c; array[2] = this.tx; @@ -119,7 +125,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, transformed through this matrix */ -Matrix.prototype.apply = function (pos, newPos) { +Matrix.prototype.apply = function (pos, newPos) +{ newPos = newPos || new Point(); newPos.x = this.a * pos.x + this.c * pos.y + this.tx; @@ -136,7 +143,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, inverse-transformed through this matrix */ -Matrix.prototype.applyInverse = function (pos, newPos) { +Matrix.prototype.applyInverse = function (pos, newPos) +{ newPos = newPos || new Point(); var id = 1 / (this.a * this.d + this.c * -this.b); @@ -154,7 +162,8 @@ * @param {number} y * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.translate = function (x, y) { +Matrix.prototype.translate = function (x, y) +{ this.tx += x; this.ty += y; @@ -168,7 +177,8 @@ * @param {number} y The amount to scale vertically * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.scale = function (x, y) { +Matrix.prototype.scale = function (x, y) +{ this.a *= x; this.d *= y; this.c *= x; @@ -186,7 +196,8 @@ * @param {number} angle - The angle in radians. * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.rotate = function (angle) { +Matrix.prototype.rotate = function (angle) +{ var cos = Math.cos( angle ); var sin = Math.sin( angle ); @@ -210,7 +221,8 @@ * @param {Matrix} matrix * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.append = function (matrix) { +Matrix.prototype.append = function (matrix) +{ var a1 = this.a; var b1 = this.b; var c1 = this.c; @@ -232,7 +244,8 @@ * * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.identity = function () { +Matrix.prototype.identity = function () +{ this.a = 1; this.b = 0; this.c = 0; diff --git a/src/core/math/Point.js b/src/core/math/Point.js index 7565b2d..632f346 100644 --- a/src/core/math/Point.js +++ b/src/core/math/Point.js @@ -7,7 +7,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -function Point(x, y) { +function Point(x, y) +{ /** * @member {number} * @default 0 @@ -29,7 +30,8 @@ * * @return {Point} a copy of the point */ -Point.prototype.clone = function () { +Point.prototype.clone = function () +{ return new Point(this.x, this.y); }; @@ -40,7 +42,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -Point.prototype.set = function (x, y) { +Point.prototype.set = function (x, y) +{ this.x = x || 0; this.y = y || ( (y !== 0) ? this.x : 0 ) ; }; diff --git a/src/core/math/shapes/Circle.js b/src/core/math/shapes/Circle.js index 69cfdc9..4d76efc 100644 --- a/src/core/math/shapes/Circle.js +++ b/src/core/math/shapes/Circle.js @@ -10,7 +10,8 @@ * @param y {number} The Y coordinate of the center of this circle * @param radius {number} The radius of the circle */ -function Circle(x, y, radius) { +function Circle(x, y, radius) +{ /** * @member {number} * @default 0 @@ -46,7 +47,8 @@ * @method clone * @return {Circle} a copy of the Circle */ -Circle.prototype.clone = function () { +Circle.prototype.clone = function () +{ return new Circle(this.x, this.y, this.radius); }; @@ -58,8 +60,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Circle */ -Circle.prototype.contains = function (x, y) { - if (this.radius <= 0) { +Circle.prototype.contains = function (x, y) +{ + if (this.radius <= 0) + { return false; } @@ -79,6 +83,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Circle.prototype.getBounds = function () { +Circle.prototype.getBounds = function () +{ return new Rectangle(this.x - this.radius, this.y - this.radius, this.radius * 2, this.radius * 2); }; diff --git a/src/core/math/shapes/Ellipse.js b/src/core/math/shapes/Ellipse.js index 4f2d066..fefd01a 100644 --- a/src/core/math/shapes/Ellipse.js +++ b/src/core/math/shapes/Ellipse.js @@ -11,7 +11,8 @@ * @param width {number} The half width of this ellipse * @param height {number} The half height of this ellipse */ -function Ellipse(x, y, width, height) { +function Ellipse(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -53,7 +54,8 @@ * @method clone * @return {Ellipse} a copy of the ellipse */ -Ellipse.prototype.clone = function () { +Ellipse.prototype.clone = function () +{ return new Ellipse(this.x, this.y, this.width, this.height); }; @@ -65,8 +67,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coords are within this ellipse */ -Ellipse.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Ellipse.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } @@ -86,6 +90,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Ellipse.prototype.getBounds = function () { +Ellipse.prototype.getBounds = function () +{ return new Rectangle(this.x - this.width, this.y - this.height, this.width, this.height); }; diff --git a/src/core/math/shapes/Polygon.js b/src/core/math/shapes/Polygon.js index ae89148..fea6d37 100644 --- a/src/core/math/shapes/Polygon.js +++ b/src/core/math/shapes/Polygon.js @@ -10,16 +10,20 @@ * arguments passed can be flat x,y values e.g. `new Polygon(x,y, x,y, x,y, ...)` where `x` and `y` are * Numbers. */ -function Polygon(points) { +function Polygon(points) +{ //if points isn't an array, use arguments as the array - if (!(points instanceof Array)) { + if (!(points instanceof Array)) + { points = Array.prototype.slice.call(arguments); } //if this is a flat array of numbers, convert it to points - if (points[0] instanceof Point) { + if (points[0] instanceof Point) + { var p = []; - for (var i = 0, il = points.length; i < il; i++) { + for (var i = 0, il = points.length; i < il; i++) + { p.push(points[i].x, points[i].y); } @@ -51,7 +55,8 @@ * * @return {Polygon} a copy of the polygon */ -Polygon.prototype.clone = function () { +Polygon.prototype.clone = function () +{ return new Polygon(this.points.slice()); }; @@ -62,19 +67,22 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this polygon */ -Polygon.prototype.contains = function (x, y) { +Polygon.prototype.contains = function (x, y) +{ var inside = false; // use some raycasting to test hits // https://github.com/substack/point-in-polygon/blob/master/index.js var length = this.points.length / 2; - for (var i = 0, j = length - 1; i < length; j = i++) { + for (var i = 0, j = length - 1; i < length; j = i++) + { var xi = this.points[i * 2], yi = this.points[i * 2 + 1], xj = this.points[j * 2], yj = this.points[j * 2 + 1], intersect = ((yi > y) !== (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi); - if (intersect) { + if (intersect) + { inside = !inside; } } diff --git a/src/core/math/shapes/Rectangle.js b/src/core/math/shapes/Rectangle.js index 16ac62a..4008b68 100644 --- a/src/core/math/shapes/Rectangle.js +++ b/src/core/math/shapes/Rectangle.js @@ -10,7 +10,8 @@ * @param width {number} The overall width of this rectangle * @param height {number} The overall height of this rectangle */ -function Rectangle(x, y, width, height) { +function Rectangle(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -60,7 +61,8 @@ * * @return {Rectangle} a copy of the rectangle */ -Rectangle.prototype.clone = function () { +Rectangle.prototype.clone = function () +{ return new Rectangle(this.x, this.y, this.width, this.height); }; @@ -71,13 +73,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rectangle */ -Rectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Rectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/math/shapes/RoundedRectangle.js b/src/core/math/shapes/RoundedRectangle.js index 27d286e..7bf6411 100644 --- a/src/core/math/shapes/RoundedRectangle.js +++ b/src/core/math/shapes/RoundedRectangle.js @@ -11,7 +11,8 @@ * @param height {number} The overall height of this rounded rectangle * @param radius {number} Controls the radius of the rounded corners */ -function RoundedRectangle(x, y, width, height, radius) { +function RoundedRectangle(x, y, width, height, radius) +{ /** * @member {number} * @default 0 @@ -58,7 +59,8 @@ * * @return {RoundedRectangle} a copy of the rounded rectangle */ -RoundedRectangle.prototype.clone = function () { +RoundedRectangle.prototype.clone = function () +{ return new RoundedRectangle(this.x, this.y, this.width, this.height, this.radius); }; @@ -69,13 +71,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rounded Rectangle */ -RoundedRectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +RoundedRectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/primitives/Graphics.js b/src/core/primitives/Graphics.js index 261c534..e902d2a 100644 --- a/src/core/primitives/Graphics.js +++ b/src/core/primitives/Graphics.js @@ -16,7 +16,8 @@ * @extends DisplayObjectContainer * @namespace PIXI */ -function Graphics() { +function Graphics() +{ DisplayObjectContainer.call(this); this.renderable = true; @@ -154,16 +155,20 @@ * @private */ cacheAsBitmap: { - get: function () { + get: function () + { return this._cacheAsBitmap; }, - set: function (value) { + set: function (value) + { this._cacheAsBitmap = value; - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._generateCachedSprite(); } - else { + else + { this.destroyCachedSprite(); this.dirty = true; } @@ -176,7 +181,8 @@ * * @return {Graphics} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ var clone = new Graphics(); clone.renderable = this.renderable; @@ -192,7 +198,8 @@ clone.cachedSpriteDirty = this.cachedSpriteDirty; // copy graphics data - for (var i = 0; i < this.graphicsData.length; ++i) { + for (var i = 0; i < this.graphicsData.length; ++i) + { clone.graphicsData.push(this.graphicsData.clone()); } @@ -211,17 +218,21 @@ * @param alpha {number} alpha of the line to draw, will update the objects stored style * @return {Graphics} */ -Graphics.prototype.lineStyle = function (lineWidth, color, alpha) { +Graphics.prototype.lineStyle = function (lineWidth, color, alpha) +{ this.lineWidth = lineWidth || 0; this.lineColor = color || 0; this.lineAlpha = (arguments.length < 3) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length) + { // halfway through a line? start a new one! this.drawShape( new math.Polygon( this.currentPath.shape.points.slice(-2) )); } - else { + else + { // otherwise its empty so lets just set the line properties this.currentPath.lineWidth = this.lineWidth; this.currentPath.lineColor = this.lineColor; @@ -239,7 +250,8 @@ * @param y {number} the Y coordinate to move to * @return {Graphics} */ -Graphics.prototype.moveTo = function (x, y) { +Graphics.prototype.moveTo = function (x, y) +{ this.drawShape(new math.Polygon([x,y])); return this; @@ -253,7 +265,8 @@ * @param y {number} the Y coordinate to draw to * @return {Graphics} */ -Graphics.prototype.lineTo = function (x, y) { +Graphics.prototype.lineTo = function (x, y) +{ this.currentPath.shape.points.push(x, y); this.dirty = true; @@ -270,13 +283,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -285,7 +302,8 @@ n = 20, points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { this.moveTo(0, 0); } @@ -293,7 +311,8 @@ var fromY = points[points.length-1]; var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; xa = fromX + ( (cpX - fromX) * j ); @@ -319,13 +338,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -342,7 +365,8 @@ var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; dt = (1 - j); @@ -373,13 +397,17 @@ * @param radius {number} The radius of the arc * @return {Graphics} */ -Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points.push(x1, y1); } } - else { + else + { this.moveTo(x1, y1); } @@ -392,12 +420,15 @@ b2 = x2 - x1, mm = Math.abs(a1 * b2 - b1 * a2); - if (mm < 1.0e-8 || radius === 0) { - if (points[points.length-2] !== x1 || points[points.length-1] !== y1) { + if (mm < 1.0e-8 || radius === 0) + { + if (points[points.length-2] !== x1 || points[points.length-1] !== y1) + { points.push(x1, y1); } } - else { + else + { var dd = a1 * a1 + b1 * b1, cc = a2 * a2 + b2 * b2, tt = a1 * a2 + b1 * b2, @@ -433,42 +464,51 @@ * @param anticlockwise {boolean} Optional. Specifies whether the drawing should be counterclockwise or clockwise. False is default, and indicates clockwise, while true indicates counter-clockwise. * @return {Graphics} */ -Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) { +Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) +{ var startX = cx + Math.cos(startAngle) * radius; var startY = cy + Math.sin(startAngle) * radius; var points; // TODO - This if-else makes no sense. It uses currentPath in the else where it doesn't exist... - if (this.currentPath) { + if (this.currentPath) + { points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { points.push(startX, startY); } - else if (points[points.length-2] !== startX || points[points.length-1] !== startY) { + else if (points[points.length-2] !== startX || points[points.length-1] !== startY) + { points.push(startX, startY); } } - else { + else + { this.moveTo(startX, startY); points = this.currentPath.shape.points; } - if (startAngle === endAngle) { + if (startAngle === endAngle) + { return this; } - if (!anticlockwise && endAngle <= startAngle) { + if (!anticlockwise && endAngle <= startAngle) + { endAngle += Math.PI * 2; } - else if (anticlockwise && startAngle <= endAngle) { + else if (anticlockwise && startAngle <= endAngle) + { startAngle += Math.PI * 2; } var sweep = anticlockwise ? (startAngle - endAngle) *-1 : (endAngle - startAngle); var segs = (Math.abs(sweep)/ (Math.PI * 2)) * 40; - if (sweep === 0) { + if (sweep === 0) + { return this; } @@ -482,7 +522,8 @@ var remainder = ( segMinus % 1 ) / segMinus; - for (var i = 0; i <= segMinus; ++i) { + for (var i = 0; i <= segMinus; ++i) + { var real = i + remainder * i; var angle = ((theta) + startAngle + (theta2 * real)); @@ -506,13 +547,16 @@ * @param alpha {number} the alpha of the fill * @return {Graphics} */ -Graphics.prototype.beginFill = function (color, alpha) { +Graphics.prototype.beginFill = function (color, alpha) +{ this.filling = true; this.fillColor = color || 0; this.fillAlpha = (alpha === undefined) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length <= 2) + { this.currentPath.fill = this.filling; this.currentPath.fillColor = this.fillColor; this.currentPath.fillAlpha = this.fillAlpha; @@ -526,7 +570,8 @@ * * @return {Graphics} */ -Graphics.prototype.endFill = function () { +Graphics.prototype.endFill = function () +{ this.filling = false; this.fillColor = null; this.fillAlpha = 1; @@ -542,7 +587,8 @@ * @param height {number} The height of the rectangle * @return {Graphics} */ -Graphics.prototype.drawRect = function ( x, y, width, height ) { +Graphics.prototype.drawRect = function ( x, y, width, height ) +{ this.drawShape(new math.Rectangle(x,y, width, height)); return this; @@ -556,7 +602,8 @@ * @param height {number} The height of the rectangle * @param radius {number} Radius of the rectangle corners */ -Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) { +Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) +{ this.drawShape(new math.RoundedRectangle(x, y, width, height, radius)); return this; @@ -570,7 +617,8 @@ * @param radius {number} The radius of the circle * @return {Graphics} */ -Graphics.prototype.drawCircle = function (x, y, radius) { +Graphics.prototype.drawCircle = function (x, y, radius) +{ this.drawShape(new math.Circle(x,y, radius)); return this; @@ -585,7 +633,8 @@ * @param height {number} The half height of the ellipse * @return {Graphics} */ -Graphics.prototype.drawEllipse = function (x, y, width, height) { +Graphics.prototype.drawEllipse = function (x, y, width, height) +{ this.drawShape(new math.Ellipse(x, y, width, height)); return this; @@ -597,8 +646,10 @@ * @param path {Array} The path data used to construct the polygon. * @return {Graphics} */ -Graphics.prototype.drawPolygon = function (path) { - if (!(path instanceof Array)) { +Graphics.prototype.drawPolygon = function (path) +{ + if (!(path instanceof Array)) + { path = Array.prototype.slice.call(arguments); } @@ -612,7 +663,8 @@ * * @return {Graphics} */ -Graphics.prototype.clear = function () { +Graphics.prototype.clear = function () +{ this.lineWidth = 0; this.filling = false; @@ -631,7 +683,8 @@ * @param scaleMode {number} Should be one of the scaleMode consts * @return {Texture} a texture of the graphics object */ -Graphics.prototype.generateTexture = function (resolution, scaleMode) { +Graphics.prototype.generateTexture = function (resolution, scaleMode) +{ resolution = resolution || 1; var bounds = this.getBounds(); @@ -655,17 +708,21 @@ * * @param renderer {WebGLRenderer} */ -Graphics.prototype._renderWebGL = function (renderer) { +Graphics.prototype._renderWebGL = function (renderer) +{ // if the sprite is not visible or the alpha is 0 then no need to render this element - if (this.isMask === true) { + if (this.isMask === true) + { return; } // this code may still be needed so leaving for now.. - // + // /* - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture on the gpu too! @@ -681,17 +738,24 @@ return; } - */ - - // check if the webgl graphic needs to be updated - if (this.glDirty) { - this.dirty = true; - this.glDirty = false; - } + else */ - renderer.setObjectRendererer(renderer.graphicsRenderer); - renderer.graphicsRenderer.render(this); + renderer.spriteBatch.stop(); + renderer.blendModeManager.setBlendMode(this.blendMode); + // check blend mode + renderer.blendModeManager.setBlendMode( this.blendMode ); + + // check if the webgl graphic needs to be updated + if (this.glDirty) + { + this.dirty = true; + this.glDirty = false; + } + + WebGLGraphics.renderGraphics(this, renderer); + + renderer.spriteBatch.start(); }; /** @@ -700,14 +764,18 @@ * @param renderer {CanvasRenderer} * @private */ -Graphics.prototype.renderCanvas = function (renderer) { +Graphics.prototype.renderCanvas = function (renderer) +{ // 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.isMask === true) { + if (!this.visible || this.alpha <= 0 || this.isMask === true) + { return; } - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture @@ -723,16 +791,19 @@ return; } - else { + else + { var context = renderer.context; var transform = this.worldTransform; - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } @@ -748,11 +819,13 @@ CanvasGraphics.renderGraphics(this, context); - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } } @@ -763,13 +836,16 @@ * * @return {Rectangle} the rectangular bounding area */ -Graphics.prototype.getBounds = function (matrix) { +Graphics.prototype.getBounds = function (matrix) +{ // return an empty object if the item is a mask! - if (this.isMask) { + if (this.isMask) + { return math.Rectangle.EMPTY; } - if (this.dirty) { + if (this.dirty) + { this.updateLocalBounds(); this.glDirty = true; @@ -841,23 +917,27 @@ * Update the bounds of the object * */ -Graphics.prototype.updateLocalBounds = function () { +Graphics.prototype.updateLocalBounds = function () +{ var minX = Infinity; var maxX = -Infinity; var minY = Infinity; var maxY = -Infinity; - if (this.graphicsData.length) { + if (this.graphicsData.length) + { var shape, points, x, y, w, h; - for (var i = 0; i < this.graphicsData.length; i++) { + for (var i = 0; i < this.graphicsData.length; i++) + { var data = this.graphicsData[i]; var type = data.type; var lineWidth = data.lineWidth; shape = data.shape; - if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) { + if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) + { x = shape.x - lineWidth/2; y = shape.y - lineWidth/2; w = shape.width + lineWidth; @@ -869,7 +949,8 @@ minY = y < minY ? y : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.CIRC) { + else if (type === CONST.SHAPES.CIRC) + { x = shape.x; y = shape.y; w = shape.radius + lineWidth/2; @@ -881,7 +962,8 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.ELIP) { + else if (type === CONST.SHAPES.ELIP) + { x = shape.x; y = shape.y; w = shape.width + lineWidth/2; @@ -893,11 +975,13 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else { + else + { // POLY points = shape.points; - for (var j = 0; j < points.length; j += 2) { + for (var j = 0; j < points.length; j += 2) + { x = points[j]; y = points[j+1]; @@ -910,7 +994,8 @@ } } } - else { + else + { minX = 0; maxX = 0; minY = 0; @@ -931,10 +1016,12 @@ * * @private */ -Graphics.prototype._generateCachedSprite = function () { +Graphics.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { var canvasBuffer = new CanvasBuffer(bounds.width, bounds.height); var texture = Texture.fromCanvas(canvasBuffer.canvas); @@ -943,7 +1030,8 @@ this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.buffer.resize(bounds.width, bounds.height); } @@ -968,7 +1056,8 @@ * * @private */ -Graphics.prototype.updateCachedSpriteTexture = function () { +Graphics.prototype.updateCachedSpriteTexture = function () +{ var cachedSprite = this._cachedSprite; var texture = cachedSprite.texture; var canvas = cachedSprite.buffer.canvas; @@ -989,7 +1078,8 @@ * Destroys a previous cached sprite. * */ -Graphics.prototype.destroyCachedSprite = function () { +Graphics.prototype.destroyCachedSprite = function () +{ this._cachedSprite.texture.destroy(true); // let the gc collect the unused sprite @@ -1003,10 +1093,13 @@ * @param {Circle|Rectangle|Ellipse|Line|Polygon} shape The Shape object to draw. * @return {GraphicsData} The generated GraphicsData object. */ -Graphics.prototype.drawShape = function (shape) { - if (this.currentPath) { +Graphics.prototype.drawShape = function (shape) +{ + if (this.currentPath) + { // check current path! - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath.shape.points.length <= 2) + { this.graphicsData.pop(); } } @@ -1017,7 +1110,8 @@ this.graphicsData.push(data); - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { data.shape.closed = this.filling; this.currentPath = data; } diff --git a/src/core/primitives/GraphicsData.js b/src/core/primitives/GraphicsData.js index 99decbe..788f6f2 100644 --- a/src/core/primitives/GraphicsData.js +++ b/src/core/primitives/GraphicsData.js @@ -4,7 +4,8 @@ * @class * @namespace PIXI */ -function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) { +function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) +{ this.lineWidth = lineWidth; this.lineColor = lineColor; this.lineAlpha = lineAlpha; @@ -27,7 +28,8 @@ * * @return {GraphicsData} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ return new GraphicsData( this.lineWidth, this.lineColor, diff --git a/src/core/renderers/canvas/CanvasRenderer.js b/src/core/renderers/canvas/CanvasRenderer.js index 15a0978..7aebd44 100644 --- a/src/core/renderers/canvas/CanvasRenderer.js +++ b/src/core/renderers/canvas/CanvasRenderer.js @@ -17,17 +17,22 @@ * @param [options.resolution=1] {number} the resolution of the renderer retina would be 2 * @param [options.clearBeforeRender=true] {boolean} This sets if the CanvasRenderer will clear the canvas or not before the new render pass. */ -function CanvasRenderer(width, height, options) { +function CanvasRenderer(width, height, options) +{ utils.sayHello('Canvas'); - if (options) { - for (var i in CONST.defaultRenderOptions) { - if (typeof options[i] === 'undefined') { + if (options) + { + for (var i in CONST.defaultRenderOptions) + { + if (typeof options[i] === 'undefined') + { options[i] = CONST.defaultRenderOptions[i]; } } } - else { + else + { options = CONST.defaultRenderOptions; } @@ -156,19 +161,24 @@ this.smoothProperty = null; - if (this.context.imageSmoothingEnabled) { + if (this.context.imageSmoothingEnabled) + { this.smoothProperty = 'imageSmoothingEnabled'; } - else if (this.context.webkitImageSmoothingEnabled) { + else if (this.context.webkitImageSmoothingEnabled) + { this.smoothProperty = 'webkitImageSmoothingEnabled'; } - else if (this.context.mozImageSmoothingEnabled) { + else if (this.context.mozImageSmoothingEnabled) + { this.smoothProperty = 'mozImageSmoothingEnabled'; } - else if (this.context.oImageSmoothingEnabled) { + else if (this.context.oImageSmoothingEnabled) + { this.smoothProperty = 'oImageSmoothingEnabled'; } - else if (this.context.msImageSmoothingEnabled) { + else if (this.context.msImageSmoothingEnabled) + { this.smoothProperty = 'msImageSmoothingEnabled'; } @@ -193,10 +203,12 @@ * @memberof CanvasRenderer# */ backgroundColor: { - get: function () { + get: function () + { return this._backgroundColor; }, - set: function (val) { + set: function (val) + { this._backgroundColor = val; this._backgroundColorString = utils.hex2string(val); } @@ -208,7 +220,8 @@ * * @param object {DisplayObject} the object to be rendered */ -CanvasRenderer.prototype.render = function (object) { +CanvasRenderer.prototype.render = function (object) +{ object.updateTransform(); this.context.setTransform(1,0,0,1,0,0); @@ -218,16 +231,20 @@ this.currentBlendMode = CONST.blendModes.NORMAL; this.context.globalCompositeOperation = this.blendModes[CONST.blendModes.NORMAL]; - if (navigator.isCocoonJS && this.view.screencanvas) { + if (navigator.isCocoonJS && this.view.screencanvas) + { this.context.fillStyle = 'black'; this.context.clear(); } - if (this.clearBeforeRender) { - if (this.transparent) { + if (this.clearBeforeRender) + { + if (this.transparent) + { this.context.clearRect(0, 0, this.width, this.height); } - else { + else + { this.context.fillStyle = this._backgroundColorString; this.context.fillRect(0, 0, this.width , this.height); } @@ -241,8 +258,10 @@ * * @param [removeView=false] {boolean} Removes the Canvas element from the DOM. */ -CanvasRenderer.prototype.destroy = function (removeView) { - if (removeView && this.view.parent) { +CanvasRenderer.prototype.destroy = function (removeView) +{ + if (removeView && this.view.parent) + { this.view.parent.removeChild(this.view); } @@ -257,14 +276,16 @@ * @param width {number} the new width of the canvas view * @param height {number} the new height of the canvas view */ -CanvasRenderer.prototype.resize = function (width, height) { +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) { + if (this.autoResize) + { this.view.style.width = this.width / this.resolution + 'px'; this.view.style.height = this.height / this.resolution + 'px'; } @@ -276,7 +297,8 @@ * @param displayObject {DisplayObject} The displayObject to render * @private */ -CanvasRenderer.prototype.renderDisplayObject = function (displayObject) { +CanvasRenderer.prototype.renderDisplayObject = function (displayObject) +{ displayObject.renderCanvas(this); }; @@ -285,11 +307,14 @@ * * @private */ -CanvasRenderer.prototype._mapBlendModes = function () { - if (!this.blendModes) { +CanvasRenderer.prototype._mapBlendModes = function () +{ + if (!this.blendModes) + { this.blendModes = {}; - if (utils.canUseNewCanvasBlendModes()) { + if (utils.canUseNewCanvasBlendModes()) + { this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? this.blendModes[CONST.blendModes.MULTIPLY] = 'multiply'; @@ -308,7 +333,8 @@ this.blendModes[CONST.blendModes.COLOR] = 'color'; this.blendModes[CONST.blendModes.LUMINOSITY] = 'luminosity'; } - else { + else + { // this means that the browser does not support the cool new blend modes in canvas 'cough' ie 'cough' this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? diff --git a/src/core/renderers/canvas/utils/CanvasBuffer.js b/src/core/renderers/canvas/utils/CanvasBuffer.js index ebe5d47..b183a66 100644 --- a/src/core/renderers/canvas/utils/CanvasBuffer.js +++ b/src/core/renderers/canvas/utils/CanvasBuffer.js @@ -6,7 +6,8 @@ * @param width {number} the width for the newly created canvas * @param height {number} the height for the newly created canvas */ -function CanvasBuffer(width, height) { +function CanvasBuffer(width, height) +{ /** * The Canvas object that belongs to this CanvasBuffer. * @@ -36,10 +37,12 @@ * @memberof CanvasBuffer# */ width: { - get: function () { + get: function () + { return this.canvas.width; }, - set: function (val) { + set: function (val) + { this.canvas.width = val; } }, @@ -50,10 +53,12 @@ * @memberof CanvasBuffer# */ height: { - get: function () { + get: function () + { return this.canvas.height; }, - set: function (val) { + set: function (val) + { this.canvas.height = val; } } @@ -64,7 +69,8 @@ * * @private */ -CanvasBuffer.prototype.clear = function () { +CanvasBuffer.prototype.clear = function () +{ this.context.setTransform(1, 0, 0, 1, 0, 0); this.context.clearRect(0,0, this.canvas.width, this.canvas.height); }; @@ -75,7 +81,8 @@ * @param width {number} the new width of the canvas * @param height {number} the new height of the canvas */ -CanvasBuffer.prototype.resize = function (width, height) { +CanvasBuffer.prototype.resize = function (width, height) +{ this.canvas.width = width; this.canvas.height = height; }; diff --git a/src/core/renderers/canvas/utils/CanvasGraphics.js b/src/core/renderers/canvas/utils/CanvasGraphics.js index c7eaa2a..3f2a91f 100644 --- a/src/core/renderers/canvas/utils/CanvasGraphics.js +++ b/src/core/renderers/canvas/utils/CanvasGraphics.js @@ -13,15 +13,18 @@ * @param graphics {Graphics} the actual graphics object to render * @param context {CanvasRenderingContext2D} the 2d drawing method of the canvas */ -CanvasGraphics.renderGraphics = function (graphics, context) { +CanvasGraphics.renderGraphics = function (graphics, context) +{ var worldAlpha = graphics.worldAlpha; - if (graphics.dirty) { + if (graphics.dirty) + { this.updateGraphicsTint(graphics); graphics.dirty = false; } - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; @@ -30,69 +33,82 @@ context.lineWidth = data.lineWidth; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { context.beginPath(); var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } - if (shape.closed) { + if (shape.closed) + { context.lineTo(points[0], points[1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fillRect(shape.x, shape.y, shape.width, shape.height); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.strokeRect(shape.x, shape.y, shape.width, shape.height); } } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.beginPath(); context.arc(shape.x, shape.y, shape.radius,0,2*Math.PI); context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas var w = shape.width * 2; @@ -119,18 +135,21 @@ context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; var width = shape.width; @@ -152,13 +171,15 @@ context.quadraticCurveTo(rx, ry, rx, ry + radius); context.closePath(); - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); @@ -174,45 +195,54 @@ * @param graphics {Graphics} the graphics which will be used as a mask * @param context {CanvasRenderingContext2D} the context 2d method of the canvas */ -CanvasGraphics.renderGraphicsMask = function (graphics, context) { +CanvasGraphics.renderGraphicsMask = function (graphics, context) +{ var len = graphics.graphicsData.length; - if (len === 0) { + if (len === 0) + { return; } context.beginPath(); - for (var i = 0; i < len; i++) { + for (var i = 0; i < len; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { context.rect(shape.x, shape.y, shape.width, shape.height); context.closePath(); } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.arc(shape.x, shape.y, shape.radius, 0, 2 * Math.PI); context.closePath(); } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas @@ -237,7 +267,8 @@ context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); context.closePath(); } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; @@ -262,8 +293,10 @@ } }; -CanvasGraphics.updateGraphicsTint = function (graphics) { - if (graphics.tint === 0xFFFFFF) { +CanvasGraphics.updateGraphicsTint = function (graphics) +{ + if (graphics.tint === 0xFFFFFF) + { return; } @@ -271,7 +304,8 @@ var tintG = (graphics.tint >> 8 & 0xFF) / 255; var tintB = (graphics.tint & 0xFF)/ 255; - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var fillColor = data.fillColor | 0; diff --git a/src/core/renderers/canvas/utils/CanvasMaskManager.js b/src/core/renderers/canvas/utils/CanvasMaskManager.js index e04a733..9827d36 100644 --- a/src/core/renderers/canvas/utils/CanvasMaskManager.js +++ b/src/core/renderers/canvas/utils/CanvasMaskManager.js @@ -6,7 +6,8 @@ * @class * @namespace PIXI */ -function CanvasMaskManager() {} +function CanvasMaskManager() +{} CanvasMaskManager.prototype.constructor = CanvasMaskManager; module.exports = CanvasMaskManager; @@ -17,7 +18,8 @@ * @param maskData {object} the maskData that will be pushed * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.pushMask = function (maskData, renderer) { +CanvasMaskManager.prototype.pushMask = function (maskData, renderer) +{ renderer.context.save(); var cacheAlpha = maskData.alpha; @@ -45,6 +47,7 @@ * * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.popMask = function (renderer) { +CanvasMaskManager.prototype.popMask = function (renderer) +{ renderer.context.restore(); }; diff --git a/src/core/renderers/canvas/utils/CanvasTinter.js b/src/core/renderers/canvas/utils/CanvasTinter.js index 17e0529..d2fb1bc 100644 --- a/src/core/renderers/canvas/utils/CanvasTinter.js +++ b/src/core/renderers/canvas/utils/CanvasTinter.js @@ -14,7 +14,8 @@ * @param color {number} the color to use to tint the sprite with * @return {HTMLCanvasElement} The tinted canvas */ -CanvasTinter.getTintedTexture = function (sprite, color) { +CanvasTinter.getTintedTexture = function (sprite, color) +{ var texture = sprite.texture; color = CanvasTinter.roundColor(color); @@ -23,7 +24,8 @@ texture.tintCache = texture.tintCache || {}; - if (texture.tintCache[stringColor]) { + if (texture.tintCache[stringColor]) + { return texture.tintCache[stringColor]; } @@ -33,14 +35,16 @@ //CanvasTinter.tintWithPerPixel(texture, stringColor, canvas); CanvasTinter.tintMethod(texture, color, canvas); - if (CanvasTinter.convertTintToImage) { + if (CanvasTinter.convertTintToImage) + { // is this better? var tintImage = new Image(); tintImage.src = canvas.toDataURL(); texture.tintCache[stringColor] = tintImage; } - else { + else + { texture.tintCache[stringColor] = canvas; // if we are not converting the texture to an image then we need to lose the reference to the canvas CanvasTinter.canvas = null; @@ -56,7 +60,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithMultiply = function (texture, color, canvas) { +CanvasTinter.tintWithMultiply = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -104,7 +109,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithOverlay = function (texture, color, canvas) { +CanvasTinter.tintWithOverlay = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -139,7 +145,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithPerPixel = function (texture, color, canvas) { +CanvasTinter.tintWithPerPixel = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -167,7 +174,8 @@ var pixels = pixelData.data; - for (var i = 0; i < pixels.length; i += 4) { + for (var i = 0; i < pixels.length; i += 4) + { pixels[i+0] *= r; pixels[i+1] *= g; pixels[i+2] *= b; @@ -181,7 +189,8 @@ * * @param color {number} the color to round, should be a hex color */ -CanvasTinter.roundColor = function (color) { +CanvasTinter.roundColor = function (color) +{ var step = CanvasTinter.cacheStepsPerColorChannel; var rgbValues = utils.hex2rgb(color); diff --git a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js index 9f2f89a..35edbaf 100644 --- a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js +++ b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLBlendModeManager(renderer) { +function WebGLBlendModeManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -23,8 +24,10 @@ * * @param blendMode {number} the blendMode, should be a Pixi const, such as BlendModes.ADD */ -WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) { - if (this.currentBlendMode === blendMode) { +WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) +{ + if (this.currentBlendMode === blendMode) + { return false; } diff --git a/src/core/renderers/webgl/managers/WebGLFilterManager.js b/src/core/renderers/webgl/managers/WebGLFilterManager.js index 1179258..2dac048 100644 --- a/src/core/renderers/webgl/managers/WebGLFilterManager.js +++ b/src/core/renderers/webgl/managers/WebGLFilterManager.js @@ -7,7 +7,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLFilterManager(renderer) { +function WebGLFilterManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -32,7 +33,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.texturePool.length = 0; self.initShaderBuffers(); }); @@ -46,7 +48,8 @@ * @param renderer {WebGLRenderer} * @param buffer {ArrayBuffer} */ -WebGLFilterManager.prototype.begin = function (buffer) { +WebGLFilterManager.prototype.begin = function (buffer) +{ this.defaultShader = this.renderer.shaderManager.defaultShader; this.width = this.renderer.projection.x * 2; @@ -60,7 +63,8 @@ * * @param filterBlock {object} the filter that will be pushed to the current filter stack */ -WebGLFilterManager.prototype.pushFilter = function (filterBlock) { +WebGLFilterManager.prototype.pushFilter = function (filterBlock) +{ var gl = this.renderer.gl; var projection = this.renderer.projection; @@ -78,10 +82,12 @@ this.offsetY += filterBlock._filterArea.y; var texture = this.texturePool.pop(); - if (!texture) { + if (!texture) + { texture = new FilterTexture(this.renderer.gl, this.width, this.height); } - else { + else + { texture.resize(this.width, this.height); } @@ -98,29 +104,35 @@ var localX = filterArea.x, localY = filterArea.y; - if (filterArea.x < 0) { + if (filterArea.x < 0) + { filterArea.width += filterArea.x; filterArea.x = 0; } - if (filterArea.y < 0) { + if (filterArea.y < 0) + { filterArea.height += filterArea.y; filterArea.y = 0; } - if (localX + filterArea.width > this.width) { + if (localX + filterArea.width > this.width) + { filterArea.width = this.width - localX; } - if (localY + filterArea.height > this.height) { + if (localY + filterArea.height > this.height) + { filterArea.height = this.height - localY; } - if (filterArea.width < 0) { + if (filterArea.width < 0) + { filterArea.width = 0; } - if (filterArea.height < 0) { + if (filterArea.height < 0) + { filterArea.height = 0; } @@ -154,7 +166,8 @@ * Removes the last filter from the filter stack and doesn't return it. * */ -WebGLFilterManager.prototype.popFilter = function () { +WebGLFilterManager.prototype.popFilter = function () +{ var gl = this.renderer.gl; var filterBlock = this.filterStack.pop(); @@ -163,7 +176,8 @@ var projection = this.renderer.projection; var offset = this.renderer.offset; - if (filterBlock.filterPasses.length > 1) { + if (filterBlock.filterPasses.length > 1) + { gl.viewport(0, 0, filterArea.width, filterArea.height); gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); @@ -193,7 +207,8 @@ var inputTexture = texture; var outputTexture = this.texturePool.pop(); - if (!outputTexture) { + if (!outputTexture) + { outputTexture = new FilterTexture(this.renderer.gl, this.width, this.height); } outputTexture.resize(this.width, this.height); @@ -204,7 +219,8 @@ gl.disable(gl.BLEND); - for (var i = 0; i < filterBlock.filterPasses.length-1; i++) { + for (var i = 0; i < filterBlock.filterPasses.length-1; i++) + { var filterPass = filterBlock.filterPasses[i]; gl.bindFramebuffer(gl.FRAMEBUFFER, outputTexture.frameBuffer ); @@ -243,10 +259,12 @@ var buffer = this.buffer; // time to render the filters texture to the previous scene - if (this.filterStack.length === 0) { + if (this.filterStack.length === 0) + { gl.colorMask(true, true, true, true);//this.transparent); } - else { + else + { var currentFilter = this.filterStack[this.filterStack.length-1]; filterArea = currentFilter._filterArea; @@ -332,13 +350,15 @@ * @param width {number} the horizontal range of the filter * @param height {number} the vertical range of the filter */ -WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) { +WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) +{ // use program var gl = this.renderer.gl; var shader = filter.shaders[gl.id]; - if (!shader) { + if (!shader) + { shader = new Shader(gl); shader.fragmentSrc = filter.fragmentSrc; @@ -356,7 +376,8 @@ gl.uniform2f(shader.projectionVector, width/2, -height/2); gl.uniform2f(shader.offsetVector, 0,0); - if (filter.uniforms.dimensions) { + 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]; @@ -386,7 +407,8 @@ * Initialises the shader buffers. * */ -WebGLFilterManager.prototype.initShaderBuffers = function () { +WebGLFilterManager.prototype.initShaderBuffers = function () +{ var gl = this.renderer.gl; // create some buffers @@ -432,7 +454,8 @@ * Destroys the filter and removes it from the filter stack. * */ -WebGLFilterManager.prototype.destroy = function () { +WebGLFilterManager.prototype.destroy = function () +{ var gl = this.renderer.gl; this.filterStack = null; @@ -441,7 +464,8 @@ this.offsetY = 0; // destroy textures - for (var i = 0; i < this.texturePool.length; i++) { + for (var i = 0; i < this.texturePool.length; i++) + { this.texturePool[i].destroy(); } diff --git a/src/core/renderers/webgl/managers/WebGLManager.js b/src/core/renderers/webgl/managers/WebGLManager.js index 9d47b5c..c30cd51 100644 --- a/src/core/renderers/webgl/managers/WebGLManager.js +++ b/src/core/renderers/webgl/managers/WebGLManager.js @@ -3,7 +3,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLManager(renderer) { +function WebGLManager(renderer) +{ /** * The renderer this manager works for. * @@ -15,6 +16,7 @@ WebGLManager.prototype.constructor = WebGLManager; module.exports = WebGLManager; -WebGLManager.prototype.destroy = function () { +WebGLManager.prototype.destroy = function () +{ this.renderer = null; }; diff --git a/src/core/renderers/webgl/managers/WebGLMaskManager.js b/src/core/renderers/webgl/managers/WebGLMaskManager.js index 2f90b64..e568812 100644 --- a/src/core/renderers/webgl/managers/WebGLMaskManager.js +++ b/src/core/renderers/webgl/managers/WebGLMaskManager.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLMaskManager(renderer) { +function WebGLMaskManager(renderer) +{ WebGLManager.call(this, renderer); } @@ -19,12 +20,15 @@ * * @param maskData {any[]} */ -WebGLMaskManager.prototype.pushMask = function (maskData) { - if (maskData.dirty) { +WebGLMaskManager.prototype.pushMask = function (maskData) +{ + if (maskData.dirty) + { WebGLGraphics.updateGraphics(maskData, this.renderer.gl); } - if (!maskData._webGL[this.renderer.gl.id].data.length) { + if (!maskData._webGL[this.renderer.gl.id].data.length) + { return; } @@ -36,6 +40,7 @@ * * @param maskData {any[]} */ -WebGLMaskManager.prototype.popMask = function (maskData) { +WebGLMaskManager.prototype.popMask = function (maskData) +{ this.renderer.stencilManager.popStencil(maskData, maskData._webGL[this.renderer.gl.id].data[0], this.renderer); }; diff --git a/src/core/renderers/webgl/managers/WebGLShaderManager.js b/src/core/renderers/webgl/managers/WebGLShaderManager.js index fef071c..90c6477 100644 --- a/src/core/renderers/webgl/managers/WebGLShaderManager.js +++ b/src/core/renderers/webgl/managers/WebGLShaderManager.js @@ -10,7 +10,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLShaderManager(renderer) { +function WebGLShaderManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -28,7 +29,8 @@ */ this.tempAttribState = []; - for (var i = 0; i < this.maxAttibs; i++) { + for (var i = 0; i < this.maxAttibs; i++) + { this.attribState[i] = false; } @@ -66,7 +68,8 @@ // listen for context and update necessary shaders var self = this; - this.renderer.on('context', function (event) { + this.renderer.on('context', function (event) + { var gl = event.data; // this shader is used for rendering primitives @@ -97,29 +100,36 @@ * * @param attribs {Array} attribs */ -WebGLShaderManager.prototype.setAttribs = function (attribs) { +WebGLShaderManager.prototype.setAttribs = function (attribs) +{ // reset temp state var i; - for (i = 0; i < this.tempAttribState.length; i++) { + for (i = 0; i < this.tempAttribState.length; i++) + { this.tempAttribState[i] = false; } // set the new attribs - for (var a in attribs) { + for (var a in attribs) + { this.tempAttribState[attribs[a]] = true; } var gl = this.renderer.gl; - for (i = 0; i < this.attribState.length; i++) { - if (this.attribState[i] !== this.tempAttribState[i]) { + for (i = 0; i < this.attribState.length; i++) + { + if (this.attribState[i] !== this.tempAttribState[i]) + { this.attribState[i] = this.tempAttribState[i]; - if (this.attribState[i]) { + if (this.attribState[i]) + { gl.enableVertexAttribArray(i); } - else { + else + { gl.disableVertexAttribArray(i); } } @@ -131,8 +141,10 @@ * * @param shader {Any} */ -WebGLShaderManager.prototype.setShader = function (shader) { - if (this._currentId === shader.uuid) { +WebGLShaderManager.prototype.setShader = function (shader) +{ + if (this._currentId === shader.uuid) + { return false; } @@ -150,7 +162,8 @@ * Destroys this object. * */ -WebGLShaderManager.prototype.destroy = function () { +WebGLShaderManager.prototype.destroy = function () +{ this.attribState = null; this.tempAttribState = null; diff --git a/src/core/renderers/webgl/managers/WebGLStencilManager.js b/src/core/renderers/webgl/managers/WebGLStencilManager.js index 9ec6398..4cb0134 100644 --- a/src/core/renderers/webgl/managers/WebGLStencilManager.js +++ b/src/core/renderers/webgl/managers/WebGLStencilManager.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLStencilManager(renderer) { +function WebGLStencilManager(renderer) +{ WebGLManager.call(this, renderer); this.stencilStack = []; @@ -24,12 +25,14 @@ * @param graphics {Graphics} * @param webGLData {any[]} */ -WebGLStencilManager.prototype.pushStencil = function (graphics, webGLData) { +WebGLStencilManager.prototype.pushStencil = function (graphics, webGLData) +{ var gl = this.renderer.gl; this.bindGraphics(graphics, webGLData, this.renderer); - if (this.stencilStack.length === 0) { + if (this.stencilStack.length === 0) + { gl.enable(gl.STENCIL_TEST); gl.clear(gl.STENCIL_BUFFER_BIT); this.reverse = true; @@ -47,14 +50,17 @@ // draw the triangle strip! - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } @@ -62,31 +68,38 @@ // draw a quad to increment.. gl.drawElements(gl.TRIANGLE_FAN, 4, gl.UNSIGNED_SHORT, ( webGLData.indices.length - 4 ) * 2 ); - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); } this.reverse = !this.reverse; } - else { - if (!this.reverse) { + else + { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } - else { + 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) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); } } @@ -103,7 +116,8 @@ * @param graphics {Graphics} * @param webGLData {Array} */ -WebGLStencilManager.prototype.bindGraphics = function (graphics, webGLData) { +WebGLStencilManager.prototype.bindGraphics = function (graphics, webGLData) +{ //if (this._currentGraphics === graphics)return; this._currentGraphics = graphics; @@ -114,7 +128,8 @@ offset = this.renderer.offset, shader;// = this.renderer.shaderManager.primitiveShader; - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { shader = this.renderer.shaderManager.complexPrimitiveShader; this.renderer.shaderManager.setShader(shader); @@ -141,7 +156,8 @@ // set the index buffer! gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, webGLData.indexBuffer); } - else { + else + { //this.renderer.shaderManager.activatePrimitiveShader(); shader = this.renderer.shaderManager.primitiveShader; this.renderer.shaderManager.setShader( shader ); @@ -154,7 +170,7 @@ gl.uniform2f(shader.uniforms.offsetVector._location, -offset.x, -offset.y); gl.uniform3fv(shader.uniforms.tint._location, utils.hex2rgb(graphics.tint)); - + gl.uniform1f(shader.uniforms.alpha._location, graphics.worldAlpha); @@ -172,19 +188,22 @@ * @param graphics {Graphics} * @param webGLData {Array} */ -WebGLStencilManager.prototype.popStencil = function (graphics, webGLData) { +WebGLStencilManager.prototype.popStencil = function (graphics, webGLData) +{ var gl = this.renderer.gl; this.stencilStack.pop(); this.count--; - if (this.stencilStack.length === 0) { + if (this.stencilStack.length === 0) + { // the stack is empty! gl.disable(gl.STENCIL_TEST); } - else { + else + { var level = this.count; @@ -192,14 +211,17 @@ gl.colorMask(false, false, false, false); - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { this.reverse = !this.reverse; - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } @@ -213,31 +235,38 @@ // draw the triangle strip! gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); - if (!this.reverse) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); } } - else { + else + { // console.log("<<>>") - if (!this.reverse) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } - else { + 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) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); } } @@ -253,7 +282,8 @@ * Destroys the mask stack. * */ -WebGLStencilManager.prototype.destroy = function () { +WebGLStencilManager.prototype.destroy = function () +{ this.renderer = null; this.stencilStack = null; }; diff --git a/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js b/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js index 913ba5e..1ea7d19 100644 --- a/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js +++ b/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function ComplexPrimitiveShader(gl) { +function ComplexPrimitiveShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -24,7 +25,8 @@ 'uniform float flipY;', 'varying vec4 vColor;', - 'void main(void) {', + '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);', @@ -37,7 +39,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = vColor;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/FastShader.js b/src/core/renderers/webgl/shaders/FastShader.js index bd2e29a..2e5e060 100644 --- a/src/core/renderers/webgl/shaders/FastShader.js +++ b/src/core/renderers/webgl/shaders/FastShader.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function FastShader(gl) { +function FastShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -28,7 +29,8 @@ 'const vec2 center = vec2(-1.0, 1.0);', - 'void main(void) {', + 'void main(void) + {', ' vec2 v;', ' vec2 sv = aVertexPosition * aScale;', ' v.x = (sv.x) * cos(aRotation) - (sv.y) * sin(aRotation);', @@ -49,7 +51,8 @@ 'uniform sampler2D uSampler;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/PrimitiveShader.js b/src/core/renderers/webgl/shaders/PrimitiveShader.js index 6f25409..a25f54f 100644 --- a/src/core/renderers/webgl/shaders/PrimitiveShader.js +++ b/src/core/renderers/webgl/shaders/PrimitiveShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function PrimitiveShader(gl) { +function PrimitiveShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -23,7 +24,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + '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);', @@ -36,7 +38,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = vColor;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/Shader.js b/src/core/renderers/webgl/shaders/Shader.js index f8964f5..fd75ef5 100644 --- a/src/core/renderers/webgl/shaders/Shader.js +++ b/src/core/renderers/webgl/shaders/Shader.js @@ -6,7 +6,8 @@ * @param [fragmentSrc] {string} The source of the fragment shader. * @param [vertexSrc] {string} The source of the vertex shader. */ -function Shader(gl, vertexSrc, fragmentSrc, customUniforms, customAttributes) { +function Shader(gl, vertexSrc, fragmentSrc, customUniforms, customAttributes) +{ /** * @member {number} * @readonly @@ -33,7 +34,8 @@ dimensions: { type: '4f', value: new Float32Array(4) } }; - for (var u in customUniforms) { + for (var u in customUniforms) + { this.uniforms[u] = customUniforms[u]; } @@ -43,7 +45,8 @@ aColor: 0 }; - for (var a in customAttributes) { + for (var a in customAttributes) + { this.attributes[a] = customAttributes[a]; } @@ -66,7 +69,8 @@ 'const vec2 center = vec2(-1.0, 1.0);', - 'void main(void) {', + 'void main(void) + {', ' gl_Position = vec4( ((aVertexPosition + offsetVector) / projectionVector) + center , 0.0, 1.0);', ' vTextureCoord = aTextureCoord;', ' vColor = vec4(aColor.rgb * aColor.a, aColor.a);', @@ -85,7 +89,8 @@ 'uniform sampler2D uSampler;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;', '}' ].join('\n'); @@ -96,7 +101,8 @@ Shader.prototype.constructor = Shader; module.exports = Shader; -Shader.prototype.init = function () { +Shader.prototype.init = function () +{ this.compile(); this.gl.useProgram(this.program); @@ -105,14 +111,18 @@ this.cacheAttributeLocations(Object.keys(this.attributes)); }; -Shader.prototype.cacheUniformLocations = function (keys) { - for (var i = 0; i < keys.length; ++i) { +Shader.prototype.cacheUniformLocations = function (keys) +{ + for (var i = 0; i < keys.length; ++i) + { this.uniforms[keys[i]]._location = this.gl.getUniformLocation(this.program, keys[i]); } }; -Shader.prototype.cacheAttributeLocations = function (keys) { - for (var i = 0; i < keys.length; ++i) { +Shader.prototype.cacheAttributeLocations = function (keys) +{ + for (var i = 0; i < keys.length; ++i) + { this.attributes[keys[i]] = this.gl.getAttribLocation(this.program, keys[i]); } @@ -124,14 +134,16 @@ // 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.attributes.aColor === -1) { + // if (this.attributes.aColor === -1) + { // this.attributes.aColor = 2; // } // End worst hack eva // }; -Shader.prototype.compile = function () { +Shader.prototype.compile = function () +{ var gl = this.gl; var glVertShader = this._glCompile(gl.VERTEX_SHADER, this.vertexSrc); @@ -144,13 +156,15 @@ gl.linkProgram(program); // if linking fails, then log and cleanup - if (!gl.getProgramParameter(program, gl.LINK_STATUS)) { + if (!gl.getProgramParameter(program, gl.LINK_STATUS)) + { window.console.error('Pixi.js Error: Could not initialize shader.'); window.console.error('gl.VALIDATE_STATUS', gl.getProgramParameter(program, gl.VALIDATE_STATUS)); window.console.error('gl.getError()', gl.getError()); // if there is a program info log, log it - if (gl.getProgramInfoLog(program) !== '') { + if (gl.getProgramInfoLog(program) !== '') + { window.console.warn('Pixi.js Warning: gl.getProgramInfoLog()', gl.getProgramInfoLog(program)); } @@ -165,18 +179,21 @@ return (this.program = program); }; -Shader.prototype.syncUniforms = function () { +Shader.prototype.syncUniforms = function () +{ var gl = this.gl; this.textureCount = 1; - for (var key in this.uniforms) { + for (var key in this.uniforms) + { var uniform = this.uniforms[key], location = uniform._location, value = uniform.value, i, il; - switch (uniform.type) { + switch (uniform.type) + { // single int value case 'i': case '1i': @@ -282,7 +299,8 @@ // a Color Value case 'c': - if (typeof value === 'number') { + if (typeof value === 'number') + { value = utils.hex2rgb(value); } @@ -311,11 +329,13 @@ // array of 2D Point objects case 'v2v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(2 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 2] = value[i].x; uniform._array[i * 2 + 1] = value[i].y; } @@ -325,11 +345,13 @@ // array of 3D Point objects case 'v3v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(3 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 3] = value[i].x; uniform._array[i * 3 + 1] = value[i].y; uniform._array[i * 3 + 2] = value[i].z; @@ -341,11 +363,13 @@ // array of 4D Point objects case 'v4v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(4 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 4] = value[i].x; uniform._array[i * 4 + 1] = value[i].y; uniform._array[i * 4 + 2] = value[i].z; @@ -359,7 +383,8 @@ // PIXI.Texture case 't': case 'sampler2D': - if (!uniform.value || !uniform.value.baseTexture || !uniform.value.baseTexture.hasLoaded) { + if (!uniform.value || !uniform.value.baseTexture || !uniform.value.baseTexture.hasLoaded) + { break; } @@ -376,7 +401,8 @@ this.textureCount++; // initialize the texture if we haven't yet - if (!uniform._init) { + if (!uniform._init) + { this.initSampler2D(uniform); uniform._init = true; @@ -394,11 +420,13 @@ * Initialises a Sampler2D uniform (which may only be available later on after initUniforms once the texture has loaded) * */ -Shader.prototype.initSampler2D = function (uniform) { +Shader.prototype.initSampler2D = function (uniform) +{ var gl = this.gl; // Extended texture data - if (uniform.textureData) { + if (uniform.textureData) + { var data = uniform.textureData; // GLTexture = mag linear, min linear_mipmap_linear, wrap repeat + gl.generateMipmap(gl.TEXTURE_2D); @@ -417,14 +445,16 @@ var wrapT = (data.wrapT) ? data.wrapT : gl.CLAMP_TO_EDGE; var format = (data.luminance) ? gl.LUMINANCE : gl.RGBA; - if (data.repeat) { + if (data.repeat) + { wrapS = gl.REPEAT; wrapT = gl.REPEAT; } gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, !!data.flipY); - if (data.width) { + if (data.width) + { var width = (data.width) ? data.width : 512; var height = (data.height) ? data.height : 2; var border = (data.border) ? data.border : 0; @@ -432,7 +462,8 @@ // 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 { + 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); } @@ -448,7 +479,8 @@ * Destroys the shader. * */ -Shader.prototype.destroy = function () { +Shader.prototype.destroy = function () +{ this.gl.deleteProgram(this.program); this.gl = null; @@ -459,13 +491,15 @@ this.fragmentSrc = null; }; -Shader.prototype._glCompile = function (type, src) { +Shader.prototype._glCompile = function (type, src) +{ var shader = this.gl.createShader(type); this.gl.shaderSource(shader, src); this.gl.compileShader(shader); - if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) { + if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) + { window.console.log(this.gl.getShaderInfoLog(shader)); return null; } diff --git a/src/core/renderers/webgl/shaders/StripShader.js b/src/core/renderers/webgl/shaders/StripShader.js index 193f6e1..a7abcc6 100644 --- a/src/core/renderers/webgl/shaders/StripShader.js +++ b/src/core/renderers/webgl/shaders/StripShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function StripShader(gl) { +function StripShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -20,7 +21,8 @@ 'varying vec2 vTextureCoord;', - 'void main(void) {', + '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);', @@ -36,7 +38,8 @@ 'varying vec2 vTextureCoord;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vec2(vTextureCoord.x, vTextureCoord.y)) * alpha;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/utils/FilterTexture.js b/src/core/renderers/webgl/utils/FilterTexture.js index d2c8423..4433d44 100644 --- a/src/core/renderers/webgl/utils/FilterTexture.js +++ b/src/core/renderers/webgl/utils/FilterTexture.js @@ -8,7 +8,8 @@ * @param height {number} the vertical range of the filter * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values */ -function FilterTexture(gl, width, height, scaleMode) { +function FilterTexture(gl, width, height, scaleMode) +{ /** * @member {WebGLContext} */ @@ -59,7 +60,8 @@ * Clears the filter texture. * */ -FilterTexture.prototype.clear = function () { +FilterTexture.prototype.clear = function () +{ var gl = this.gl; gl.clearColor(0,0,0, 0); @@ -72,8 +74,10 @@ * @param width {number} the new width of the texture * @param height {number} the new height of the texture */ -FilterTexture.prototype.resize = function (width, height) { - if (this.width === width && this.height === height) { +FilterTexture.prototype.resize = function (width, height) +{ + if (this.width === width && this.height === height) + { return; } @@ -96,7 +100,8 @@ * Destroys the filter texture. * */ -FilterTexture.prototype.destroy = function () { +FilterTexture.prototype.destroy = function () +{ var gl = this.gl; gl.deleteFramebuffer( this.frameBuffer ); gl.deleteTexture( this.texture ); diff --git a/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js b/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js index c4721e9..a63f4d7 100644 --- a/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js +++ b/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js @@ -14,7 +14,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this sprite batch works for. */ -function WebGLFastSpriteBatch(renderer) { +function WebGLFastSpriteBatch(renderer) +{ /** * The renderer instance this sprite batch operates on. * @@ -91,7 +92,8 @@ */ this.lastIndexCount = 0; - for (var i=0, j=0; i < numIndices; i += 6, j += 4) { + 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; @@ -144,7 +146,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.setupContext(); }); } @@ -157,7 +160,8 @@ * * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLFastSpriteBatch.prototype.setupContext = function () { +WebGLFastSpriteBatch.prototype.setupContext = function () +{ var gl = this.renderer.gl; // create a couple of buffers @@ -177,7 +181,8 @@ /** * @param spriteBatch {SpriteBatch} The SpriteBatch container to prepare for. */ -WebGLFastSpriteBatch.prototype.begin = function (spriteBatch) { +WebGLFastSpriteBatch.prototype.begin = function (spriteBatch) +{ this.shader = this.renderer.shaderManager.fastShader; this.matrix = spriteBatch.worldTransform.toArray(true); @@ -187,33 +192,38 @@ /** */ -WebGLFastSpriteBatch.prototype.end = function () { +WebGLFastSpriteBatch.prototype.end = function () +{ this.flush(); }; /** * @param spriteBatch {SpriteBatch} The SpriteBatch container to render. */ -WebGLFastSpriteBatch.prototype.render = function (spriteBatch) { +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) { + if (!sprite.texture._uvs) + { return; } this.currentBaseTexture = sprite.texture.baseTexture; // check blend mode - if (sprite.blendMode !== this.renderer.blendModeManager.currentBlendMode) { + if (sprite.blendMode !== this.renderer.blendModeManager.currentBlendMode) + { this.flush(); this.renderer.blendModeManager.setBlendMode(sprite.blendMode); } - for (var i=0,j= children.length; i= this.size) { + if (this.currentBatchSize >= this.size) + { this.flush(); } }; @@ -362,29 +379,35 @@ /** * */ -WebGLFastSpriteBatch.prototype.flush = function () { +WebGLFastSpriteBatch.prototype.flush = function () +{ // If the batch is length 0 then return as there is nothing to draw - if (this.currentBatchSize === 0) { + if (this.currentBatchSize === 0) + { return; } var gl = this.renderer.gl; // bind the current texture - if (!this.currentBaseTexture._glTextures[gl.id]) { + if (!this.currentBaseTexture._glTextures[gl.id]) + { this.renderer.updateTexture(this.currentBaseTexture, gl); } //TODO-SHOUD THIS BE ELSE??!?!?! - else { + else + { gl.bindTexture(gl.TEXTURE_2D, this.currentBaseTexture._glTextures[gl.id]); } // upload the verts to the buffer - if (this.currentBatchSize > ( this.size * 0.5 ) ) { + if (this.currentBatchSize > ( this.size * 0.5 ) ) + { gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); } - else { + else + { var view = this.vertices.subarray(0, this.currentBatchSize * this.vertByteSize); gl.bufferSubData(gl.ARRAY_BUFFER, 0, view); @@ -405,14 +428,16 @@ * Ends the batch and flushes * */ -WebGLFastSpriteBatch.prototype.stop = function () { +WebGLFastSpriteBatch.prototype.stop = function () +{ this.flush(); }; /** * */ -WebGLFastSpriteBatch.prototype.start = function () { +WebGLFastSpriteBatch.prototype.start = function () +{ var gl = this.renderer.gl; // bind the main texture diff --git a/src/core/renderers/webgl/utils/WebGLGraphics.js b/src/core/renderers/webgl/utils/WebGLGraphics.js index 55f4911..ab8f46e 100644 --- a/src/core/renderers/webgl/utils/WebGLGraphics.js +++ b/src/core/renderers/webgl/utils/WebGLGraphics.js @@ -19,7 +19,8 @@ * @param graphics {Graphics} * @param renderer {WebGLRenderer} */ -WebGLGraphics.renderGraphics = function (graphics, renderer) {//projection, offset) { +WebGLGraphics.renderGraphics = function (graphics, renderer) {//projection, offset) +{ var gl = renderer.gl; var projection = renderer.projection, @@ -27,7 +28,8 @@ shader = renderer.shaderManager.primitiveShader, webGLData; - if (graphics.dirty) { + if (graphics.dirty) + { WebGLGraphics.updateGraphics(graphics, gl); } @@ -35,8 +37,10 @@ // This could be speeded up for sure! - for (var i = 0; i < webGL.data.length; i++) { - if (webGL.data[i].mode === 1) { + for (var i = 0; i < webGL.data.length; i++) + { + if (webGL.data[i].mode === 1) + { webGLData = webGL.data[i]; renderer.stencilManager.pushStencil(graphics, webGLData, renderer); @@ -46,7 +50,8 @@ renderer.stencilManager.popStencil(graphics, webGLData, renderer); } - else { + else + { webGLData = webGL.data[i]; @@ -84,12 +89,14 @@ * @param graphicsData {Graphics} The graphics object to update * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLGraphics.updateGraphics = function (graphics, gl) { +WebGLGraphics.updateGraphics = function (graphics, gl) +{ // get the contexts graphics object var webGL = graphics._webGL[gl.id]; // if the graphics object does not exist in the webGL context time to create it! - if (!webGL) { + if (!webGL) + { webGL = graphics._webGL[gl.id] = {lastIndex:0, data:[], gl:gl}; } @@ -99,11 +106,13 @@ var i; // if the user cleared the graphics object we will need to clear every object - if (graphics.clearDirty) { + if (graphics.clearDirty) + { graphics.clearDirty = false; // lop through and return all the webGLDatas to the object pool so than can be reused later on - for (i = 0; i < webGL.data.length; i++) { + for (i = 0; i < webGL.data.length; i++) + { var graphicsData = webGL.data[i]; graphicsData.reset(); WebGLGraphics.graphicsDataPool.push( graphicsData ); @@ -119,58 +128,72 @@ // loop through the graphics datas and construct each one.. // if the object is a complex fill then the new stencil buffer technique will be used // other wise graphics objects will be pushed into a batch.. - for (i = webGL.lastIndex; i < graphics.graphicsData.length; i++) { + for (i = webGL.lastIndex; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { // need to add the points the the graphics object.. data.points = data.shape.points.slice(); - if (data.shape.closed) { + if (data.shape.closed) + { // close the poly if the value is true! - if (data.points[0] !== data.points[data.points.length-2] || data.points[1] !== data.points[data.points.length-1]) { + if (data.points[0] !== data.points[data.points.length-2] || data.points[1] !== data.points[data.points.length-1]) + { data.points.push(data.points[0], data.points[1]); } } // MAKE SURE WE HAVE THE CORRECT TYPE.. - if (data.fill) { - if (data.points.length >= 6) { - if (data.points.length < 6 * 2) { + if (data.fill) + { + if (data.points.length >= 6) + { + if (data.points.length < 6 * 2) + { webGLData = WebGLGraphics.switchMode(webGL, 0); var canDrawUsingSimple = WebGLGraphics.buildPoly(data, webGLData); // console.log(canDrawUsingSimple); - if (!canDrawUsingSimple) { + if (!canDrawUsingSimple) + { // console.log("<>>>") webGLData = WebGLGraphics.switchMode(webGL, 1); WebGLGraphics.buildComplexPoly(data, webGLData); } } - else { + else + { webGLData = WebGLGraphics.switchMode(webGL, 1); WebGLGraphics.buildComplexPoly(data, webGLData); } } } - if (data.lineWidth > 0) { + if (data.lineWidth > 0) + { webGLData = WebGLGraphics.switchMode(webGL, 0); WebGLGraphics.buildLine(data, webGLData); } } - else { + else + { webGLData = WebGLGraphics.switchMode(webGL, 0); - if (data.type === CONST.SHAPES.RECT) { + if (data.type === CONST.SHAPES.RECT) + { WebGLGraphics.buildRectangle(data, webGLData); } - else if (data.type === CONST.SHAPES.CIRC || data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.CIRC || data.type === CONST.SHAPES.ELIP) + { WebGLGraphics.buildCircle(data, webGLData); } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { WebGLGraphics.buildRoundedRectangle(data, webGLData); } } @@ -179,10 +202,12 @@ } // upload all the dirty data... - for (i = 0; i < webGL.data.length; i++) { + for (i = 0; i < webGL.data.length; i++) + { webGLData = webGL.data[i]; - if (webGLData.dirty) { + if (webGLData.dirty) + { webGLData.upload(); } } @@ -194,18 +219,22 @@ * @param webGL {WebGLContext} * @param type {number} */ -WebGLGraphics.switchMode = function (webGL, type) { +WebGLGraphics.switchMode = function (webGL, type) +{ var webGLData; - if (!webGL.data.length) { + if (!webGL.data.length) + { webGLData = WebGLGraphics.graphicsDataPool.pop() || new WebGLGraphicsData(webGL.gl); webGLData.mode = type; webGL.data.push(webGLData); } - else { + else + { webGLData = webGL.data[webGL.data.length-1]; - if (webGLData.mode !== type || type === 1) { + if (webGLData.mode !== type || type === 1) + { webGLData = WebGLGraphics.graphicsDataPool.pop() || new WebGLGraphicsData(webGL.gl); webGLData.mode = type; webGL.data.push(webGLData); @@ -225,7 +254,8 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildRectangle = function (graphicsData, webGLData) { +WebGLGraphics.buildRectangle = function (graphicsData, webGLData) +{ // --- // // need to convert points to a nice regular data // @@ -235,7 +265,8 @@ var width = rectData.width; var height = rectData.height; - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -265,7 +296,8 @@ indices.push(vertPos, vertPos, vertPos+1, vertPos+2, vertPos+3, vertPos+3); } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = [x, y, @@ -289,7 +321,8 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildRoundedRectangle = function (graphicsData, webGLData) { +WebGLGraphics.buildRoundedRectangle = function (graphicsData, webGLData) +{ var rrectData = graphicsData.shape; var x = rrectData.x; var y = rrectData.y; @@ -305,7 +338,8 @@ recPoints = recPoints.concat(WebGLGraphics.quadraticBezierCurve(x + width, y + radius, x + width, y, x + width - radius, y)); recPoints = recPoints.concat(WebGLGraphics.quadraticBezierCurve(x + radius, y, x, y, x, y + radius)); - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -323,7 +357,8 @@ // var i = 0; - for (i = 0; i < triangles.length; i+=3) { + for (i = 0; i < triangles.length; i+=3) + { indices.push(triangles[i] + vecPos); indices.push(triangles[i] + vecPos); indices.push(triangles[i+1] + vecPos); @@ -332,12 +367,14 @@ } - for (i = 0; i < recPoints.length; i++) { + for (i = 0; i < recPoints.length; i++) + { verts.push(recPoints[i], recPoints[++i], r, g, b, alpha); } } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = recPoints; @@ -362,7 +399,8 @@ * @param toY {number} Destination point y * @return {number[]} */ -WebGLGraphics.quadraticBezierCurve = function (fromX, fromY, cpX, cpY, toX, toY) { +WebGLGraphics.quadraticBezierCurve = function (fromX, fromY, cpX, cpY, toX, toY) +{ var xa, ya, @@ -373,14 +411,16 @@ n = 20, points = []; - function getPt(n1 , n2, perc) { + function getPt(n1 , n2, perc) + { var diff = n2 - n1; return n1 + ( diff * perc ); } var j = 0; - for (var i = 0; i <= n; i++ ) { + for (var i = 0; i <= n; i++ ) + { j = i / n; // The Green Line @@ -406,7 +446,8 @@ * @param graphicsData {Graphics} The graphics object to draw * @param webGLData {object} */ -WebGLGraphics.buildCircle = function (graphicsData, webGLData) { +WebGLGraphics.buildCircle = function (graphicsData, webGLData) +{ // need to convert points to a nice regular data var circleData = graphicsData.shape; var x = circleData.x; @@ -415,11 +456,13 @@ var height; // TODO - bit hacky?? - if (graphicsData.type === CONST.SHAPES.CIRC) { + if (graphicsData.type === CONST.SHAPES.CIRC) + { width = circleData.radius; height = circleData.radius; } - else { + else + { width = circleData.width; height = circleData.height; } @@ -429,7 +472,8 @@ var i = 0; - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -444,7 +488,8 @@ indices.push(vecPos); - for (i = 0; i < totalSegs + 1 ; i++) { + for (i = 0; i < totalSegs + 1 ; i++) + { verts.push(x,y, r, g, b, alpha); verts.push(x + Math.sin(seg * i) * width, @@ -457,12 +502,14 @@ indices.push(vecPos-1); } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = []; - for (i = 0; i < totalSegs + 1; i++) { + for (i = 0; i < totalSegs + 1; i++) + { graphicsData.points.push(x + Math.sin(seg * i) * width, y + Math.cos(seg * i) * height); } @@ -481,18 +528,22 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildLine = function (graphicsData, webGLData) { +WebGLGraphics.buildLine = function (graphicsData, webGLData) +{ // TODO OPTIMISE! var i = 0; var points = graphicsData.points; - if (points.length === 0) { + if (points.length === 0) + { return; } // if the line width is an odd number add 0.5 to align to a whole pixel - if (graphicsData.lineWidth%2) { - for (i = 0; i < points.length; i++) { + if (graphicsData.lineWidth%2) + { + for (i = 0; i < points.length; i++) + { points[i] += 0.5; } } @@ -502,7 +553,8 @@ var lastPoint = new math.Point(points[points.length - 2], points[points.length - 1]); // if the first point is the last point - gonna have issues :) - if (firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) { + if (firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) + { // need to clone as we are going to slightly modify the shape.. points = points.slice(); @@ -562,7 +614,8 @@ verts.push(p1x + perpx , p1y + perpy, r, g, b, alpha); - for (i = 1; i < length-1; i++) { + for (i = 1; i < length-1; i++) + { p1x = points[(i-1)*2]; p1y = points[(i-1)*2 + 1]; @@ -599,7 +652,8 @@ denom = a1*b2 - a2*b1; - if (Math.abs(denom) < 0.1 ) { + if (Math.abs(denom) < 0.1 ) + { denom+=10.1; verts.push(p2x - perpx , p2y - perpy, @@ -618,7 +672,8 @@ pdist = (px -p2x) * (px -p2x) + (py -p2y) + (py -p2y); - if (pdist > 140 * 140) { + if (pdist > 140 * 140) + { perp3x = perpx - perp2x; perp3y = perpy - perp2y; @@ -639,7 +694,8 @@ indexCount++; } - else { + else + { verts.push(px , py); verts.push(r, g, b, alpha); @@ -672,7 +728,8 @@ indices.push(indexStart); - for (i = 0; i < indexCount; i++) { + for (i = 0; i < indexCount; i++) + { indices.push(indexStart++); } @@ -687,11 +744,13 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildComplexPoly = function (graphicsData, webGLData) { +WebGLGraphics.buildComplexPoly = function (graphicsData, webGLData) +{ //TODO - no need to copy this as it gets turned into a FLoat32Array anyways.. var points = graphicsData.points.slice(); - if (points.length < 6) { + if (points.length < 6) + { return; } @@ -711,7 +770,8 @@ var x,y; // get size.. - for (var i = 0; i < points.length; i+=2) { + for (var i = 0; i < points.length; i+=2) + { x = points[i]; y = points[i+1]; @@ -732,7 +792,8 @@ //TODO - this aint needed! var length = points.length / 2; - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { indices.push( i ); } @@ -746,10 +807,12 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildPoly = function (graphicsData, webGLData) { +WebGLGraphics.buildPoly = function (graphicsData, webGLData) +{ var points = graphicsData.points; - if (points.length < 6) { + if (points.length < 6) + { return; } // get first and last point.. figure out the middle! @@ -767,7 +830,8 @@ var triangles = utils.PolyK.Triangulate(points); - if (!triangles) { + if (!triangles) + { return false; } @@ -775,7 +839,8 @@ var i = 0; - for (i = 0; i < triangles.length; i+=3) { + for (i = 0; i < triangles.length; i+=3) + { indices.push(triangles[i] + vertPos); indices.push(triangles[i] + vertPos); indices.push(triangles[i+1] + vertPos); @@ -783,7 +848,8 @@ indices.push(triangles[i+2] + vertPos); } - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { verts.push(points[i * 2], points[i * 2 + 1], r, g, b, alpha); } diff --git a/src/core/renderers/webgl/utils/WebGLGraphicsData.js b/src/core/renderers/webgl/utils/WebGLGraphicsData.js index c56d05e..c739ba7 100644 --- a/src/core/renderers/webgl/utils/WebGLGraphicsData.js +++ b/src/core/renderers/webgl/utils/WebGLGraphicsData.js @@ -2,7 +2,8 @@ * @class * @private */ -function WebGLGraphicsData(gl) { +function WebGLGraphicsData(gl) +{ this.gl = gl; //TODO does this need to be split before uploding?? @@ -22,7 +23,8 @@ /** * */ -WebGLGraphicsData.prototype.reset = function () { +WebGLGraphicsData.prototype.reset = function () +{ this.points.length = 0; this.indices.length = 0; }; @@ -30,7 +32,8 @@ /** * */ -WebGLGraphicsData.prototype.upload = function () { +WebGLGraphicsData.prototype.upload = function () +{ var gl = this.gl; // this.lastIndex = graphics.graphicsData.length; diff --git a/src/core/renderers/webgl/utils/WebGLSpriteBatch.js b/src/core/renderers/webgl/utils/WebGLSpriteBatch.js index 96eaa52..55befbb 100644 --- a/src/core/renderers/webgl/utils/WebGLSpriteBatch.js +++ b/src/core/renderers/webgl/utils/WebGLSpriteBatch.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this sprite batch works for. */ -function WebGLSpriteBatch(renderer) { +function WebGLSpriteBatch(renderer) +{ /** * * @@ -88,7 +89,8 @@ */ this.lastIndexCount = 0; - for (var i=0, j=0; i < numIndices; i += 6, j += 4) { + 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; @@ -162,7 +164,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.setupContext(); }); } @@ -173,7 +176,8 @@ /** * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLSpriteBatch.prototype.setupContext = function () { +WebGLSpriteBatch.prototype.setupContext = function () +{ var gl = this.renderer.gl; // setup default shader @@ -198,7 +202,8 @@ /** * */ -WebGLSpriteBatch.prototype.begin = function () { +WebGLSpriteBatch.prototype.begin = function () +{ // this.shader = this.renderer.shaderManager.defaultShader; this.start(); @@ -206,19 +211,22 @@ /** */ -WebGLSpriteBatch.prototype.end = function () { +WebGLSpriteBatch.prototype.end = function () +{ this.flush(); }; /** * @param sprite {Sprite} the sprite to render when using this spritebatch */ -WebGLSpriteBatch.prototype.render = function (sprite) { +WebGLSpriteBatch.prototype.render = function (sprite) +{ var texture = sprite.texture; //TODO set blend modes.. // check texture.. - if (this.currentBatchSize >= this.size) { + if (this.currentBatchSize >= this.size) + { this.flush(); this.currentBaseTexture = texture.baseTexture; } @@ -227,7 +235,8 @@ var uvs = texture._uvs; // if the uvs have not updated then no point rendering just yet! - if (!uvs) { + if (!uvs) + { return; } @@ -237,7 +246,8 @@ var w0, w1, h0, h1; - if (texture.trim) { + 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; @@ -248,7 +258,8 @@ h0 = h1 + texture.crop.height; } - else { + else + { w0 = (texture.frame.width ) * (1-aX); w1 = (texture.frame.width ) * -aX; @@ -272,7 +283,8 @@ var colors = this.colors; var positions = this.positions; - if (this.renderer.roundPixels) { + if (this.renderer.roundPixels) + { // xy positions[index] = a * w1 + c * h1 + tx | 0; positions[index+1] = d * h1 + b * w1 + ty | 0; @@ -289,7 +301,8 @@ positions[index+15] = a * w1 + c * h0 + tx | 0; positions[index+16] = d * h0 + b * w1 + ty | 0; } - else { + else + { // xy positions[index] = a * w1 + c * h1 + tx; positions[index+1] = d * h1 + b * w1 + ty; @@ -338,11 +351,13 @@ * * @param sprite {TilingSprite} the tilingSprite to render */ -WebGLSpriteBatch.prototype.renderTilingSprite = function (tilingSprite) { +WebGLSpriteBatch.prototype.renderTilingSprite = function (tilingSprite) +{ var texture = tilingSprite.tilingTexture; // check texture.. - if (this.currentBatchSize >= this.size) { + if (this.currentBatchSize >= this.size) + { //return; this.flush(); this.currentBaseTexture = texture.baseTexture; @@ -351,7 +366,8 @@ // set the textures uvs temporarily // TODO create a separate texture so that we can tile part of a texture - if (!tilingSprite._uvs) { + if (!tilingSprite._uvs) + { tilingSprite._uvs = new TextureUvs(); } @@ -454,16 +470,19 @@ * Renders the content and empties the current batch. * */ -WebGLSpriteBatch.prototype.flush = function () { +WebGLSpriteBatch.prototype.flush = function () +{ // If the batch is length 0 then return as there is nothing to draw - if (this.currentBatchSize === 0) { + if (this.currentBatchSize === 0) + { return; } var gl = this.renderer.gl; var shader; - if (this.dirty) { + if (this.dirty) + { this.dirty = false; // bind the main texture gl.activeTexture(gl.TEXTURE0); @@ -482,10 +501,12 @@ } // upload the verts to the buffer - if (this.currentBatchSize > ( this.size * 0.5 ) ) { + if (this.currentBatchSize > ( this.size * 0.5 ) ) + { gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); } - else { + else + { var view = this.positions.subarray(0, this.currentBatchSize * this.vertByteSize); gl.bufferSubData(gl.ARRAY_BUFFER, 0, view); } @@ -502,7 +523,8 @@ var shaderSwap = false; var sprite; - for (var i = 0, j = this.currentBatchSize; i < j; i++) { + for (var i = 0, j = this.currentBatchSize; i < j; i++) + { sprite = this.sprites[i]; @@ -513,24 +535,28 @@ blendSwap = currentBlendMode !== nextBlendMode; shaderSwap = currentShader !== nextShader; // should I use uuidS??? - if (currentBaseTexture !== nextTexture || blendSwap || shaderSwap) { + if (currentBaseTexture !== nextTexture || blendSwap || shaderSwap) + { this.renderBatch(currentBaseTexture, batchSize, start); start = i; batchSize = 0; currentBaseTexture = nextTexture; - if (blendSwap) { + if (blendSwap) + { currentBlendMode = nextBlendMode; this.renderer.blendModeManager.setBlendMode( currentBlendMode ); } - if (shaderSwap) { + if (shaderSwap) + { currentShader = nextShader; shader = currentShader.shaders ? currentShader.shaders[gl.id] : currentShader; - if (!shader) { + if (!shader) + { shader = new Shader(gl, null, currentShader.fragmentSrc, currentShader.uniforms); currentShader.shaders[gl.id] = shader; } @@ -538,7 +564,8 @@ // set shader function??? this.renderer.shaderManager.setShader(shader); - if (shader.dirty) { + if (shader.dirty) + { shader.syncUniforms(); } @@ -569,17 +596,21 @@ * @param size {number} * @param startIndex {number} */ -WebGLSpriteBatch.prototype.renderBatch = function (texture, size, startIndex) { - if (size === 0) { +WebGLSpriteBatch.prototype.renderBatch = function (texture, size, startIndex) +{ + if (size === 0) + { return; } var gl = this.renderer.gl; - if (!texture._glTextures[gl.id]) { + if (!texture._glTextures[gl.id]) + { this.renderer.updateTexture(texture); } - else { + else + { // bind the current texture gl.bindTexture(gl.TEXTURE_2D, texture._glTextures[gl.id]); } @@ -594,7 +625,8 @@ /** * */ -WebGLSpriteBatch.prototype.stop = function () { +WebGLSpriteBatch.prototype.stop = function () +{ this.flush(); this.dirty = true; }; @@ -602,7 +634,8 @@ /** * */ -WebGLSpriteBatch.prototype.start = function () { +WebGLSpriteBatch.prototype.start = function () +{ this.dirty = true; }; @@ -610,7 +643,8 @@ * Destroys the SpriteBatch. * */ -WebGLSpriteBatch.prototype.destroy = function () { +WebGLSpriteBatch.prototype.destroy = function () +{ this.renderer.gl.deleteBuffer(this.vertexBuffer); this.renderer.gl.deleteBuffer(this.indexBuffer); diff --git a/src/core/textures/BaseTexture.js b/src/core/textures/BaseTexture.js index 2bf77d4..513d358 100644 --- a/src/core/textures/BaseTexture.js +++ b/src/core/textures/BaseTexture.js @@ -10,7 +10,8 @@ * @param source {Image|Canvas} the source object of the texture. * @param [scaleMode=scaleModes.DEFAULT] {number} See {@link scaleModes} for possible values */ -function BaseTexture(source, scaleMode) { +function BaseTexture(source, scaleMode) +{ this.uuid = utils.uuid(); /** @@ -123,7 +124,8 @@ this._needsUpdate = false; // if no source passed don't try to load - if (source) { + if (source) + { this.loadSource(source); } @@ -149,13 +151,16 @@ Object.defineProperties(BaseTexture.prototype, { needsUpdate: { - get: function () { + get: function () + { return this._needsUpdate; }, - set: function (val) { + set: function (val) + { this._needsUpdate = val; - if (val) { + if (val) + { this.emit('update', this); } } @@ -171,9 +176,11 @@ * * The logic state after calling `loadSource` directly or indirectly (eg. `fromImage`, `new BaseTexture`) is: * - * if (texture.hasLoaded) { + * if (texture.hasLoaded) + { * // texture ready for use - * } else if (texture.isLoading) { + * } else if (texture.isLoading) + { * // listen to 'loaded' and/or 'error' events on texture * } else { * // not loading, not going to load UNLESS the source is reloaded @@ -183,12 +190,14 @@ * @protected * @param source {Image|Canvas} the source object of the texture. */ -BaseTexture.prototype.loadSource = function (source) { +BaseTexture.prototype.loadSource = function (source) +{ var wasLoading = this.isLoading; this.hasLoaded = false; this.isLoading = false; - if (wasLoading && this.source) { + if (wasLoading && this.source) + { this.source.onload = null; this.source.onerror = null; } @@ -196,20 +205,24 @@ this.source = source; // Apply source if loaded. Otherwise setup appropriate loading monitors. - if ((this.source.complete || this.source.getContext) && this.source.width && this.source.height) { + if ((this.source.complete || this.source.getContext) && this.source.width && this.source.height) + { this._sourceLoaded(); } - else if(!source.getContext) { + else if(!source.getContext) + { // Image fail / not ready this.isLoading = true; var scope = this; - source.onload = function () { + source.onload = function () + { source.onload = null; source.onerror = null; - if(!scope.isLoading) { + if(!scope.isLoading) + { return; } @@ -219,11 +232,13 @@ scope.emit('loaded', scope); }; - source.onerror = function () { + source.onerror = function () + { source.onload = null; source.onerror = null; - if(!scope.isLoading) { + if(!scope.isLoading) + { return; } @@ -234,24 +249,29 @@ // Per http://www.w3.org/TR/html5/embedded-content-0.html#the-img-element // "The value of `complete` can thus change while a script is executing." // So complete needs to be re-checked after the callbacks have been added.. - if (source.complete) { + if (source.complete) + { this.isLoading = false; // ..and if we're complete now, no need for callbacks source.onload = null; source.onerror = null; - if (source.width && source.height) { + if (source.width && source.height) + { this._sourceLoaded(); // If any previous subscribers possible - if (wasLoading) { + if (wasLoading) + { this.emit('loaded', this); } } - else { + else + { // If any previous subscribers possible - if (wasLoading) { + if (wasLoading) + { this.emit('error', this); } } @@ -265,7 +285,8 @@ * * @private */ -BaseTexture.prototype._sourceLoaded = function () { +BaseTexture.prototype._sourceLoaded = function () +{ this.hasLoaded = true; this.width = this.source.naturalWidth || this.source.width; @@ -278,16 +299,20 @@ * Destroys this base texture * */ -BaseTexture.prototype.destroy = function () { - if (this.imageUrl) { +BaseTexture.prototype.destroy = function () +{ + if (this.imageUrl) + { delete utils.BaseTextureCache[this.imageUrl]; delete utils.TextureCache[this.imageUrl]; this.imageUrl = null; - if (!navigator.isCocoonJS) { + if (!navigator.isCocoonJS) + { this.source.src = ''; } } - else if (this.source && this.source._pixiId) { + else if (this.source && this.source._pixiId) + { delete utils.BaseTextureCache[this.source._pixiId]; } this.source = null; @@ -301,7 +326,8 @@ * memory again. * */ -BaseTexture.prototype.dispose = function () { +BaseTexture.prototype.dispose = function () +{ this.emit('dispose', this); }; @@ -311,7 +337,8 @@ * * @param newSrc {string} the path of the image */ -BaseTexture.prototype.updateSourceImage = function (newSrc) { +BaseTexture.prototype.updateSourceImage = function (newSrc) +{ this.source.src = newSrc; this.loadSource(this.source); }; @@ -326,18 +353,22 @@ * @param [scaleMode=scaleModes.DEFAULT] {number} See {@link scaleModes} for possible values * @return BaseTexture */ -BaseTexture.fromImage = function (imageUrl, crossorigin, scaleMode) { +BaseTexture.fromImage = function (imageUrl, crossorigin, scaleMode) +{ var baseTexture = utils.BaseTextureCache[imageUrl]; - if (crossorigin === undefined && imageUrl.indexOf('data:') !== 0) { + if (crossorigin === undefined && imageUrl.indexOf('data:') !== 0) + { crossorigin = true; } - if (!baseTexture) { + if (!baseTexture) + { // new Image() breaks tex loading in some versions of Chrome. // See https://code.google.com/p/chromium/issues/detail?id=238071 var image = new Image();//document.createElement('img'); - if (crossorigin) { + if (crossorigin) + { image.crossOrigin = ''; } @@ -347,7 +378,8 @@ utils.BaseTextureCache[imageUrl] = baseTexture; // if there is an @2x at the end of the url we are going to assume its a highres image - if ( imageUrl.indexOf(CONST.RETINA_PREFIX + '.') !== -1) { + if ( imageUrl.indexOf(CONST.RETINA_PREFIX + '.') !== -1) + { baseTexture.resolution = 2; } } @@ -363,14 +395,17 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return BaseTexture */ -BaseTexture.fromCanvas = function (canvas, scaleMode) { - if (!canvas._pixiId) { +BaseTexture.fromCanvas = function (canvas, scaleMode) +{ + if (!canvas._pixiId) + { canvas._pixiId = 'canvas_' + utils.uuid(); } var baseTexture = utils.BaseTextureCache[canvas._pixiId]; - if (!baseTexture) { + if (!baseTexture) + { baseTexture = new BaseTexture(canvas, scaleMode); utils.BaseTextureCache[canvas._pixiId] = baseTexture; } diff --git a/src/core/textures/RenderTexture.js b/src/core/textures/RenderTexture.js index 6dad20f..53ae796 100644 --- a/src/core/textures/RenderTexture.js +++ b/src/core/textures/RenderTexture.js @@ -46,8 +46,10 @@ * @param [scaleMode] {number} See {@link scaleModes} for possible values * @param [resolution=1] {number} The resolution of the texture being generated */ -function RenderTexture(renderer, width, height, scaleMode, resolution) { - if (!renderer) { +function RenderTexture(renderer, width, height, scaleMode, resolution) +{ + if (!renderer) + { throw new Error('Unable to create RenderTexture, you must pass a renderer into the constructor.'); } @@ -133,7 +135,8 @@ */ this.renderer = renderer; - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { var gl = this.renderer.gl; this.textureBuffer = new FilterTexture(gl, this.width * this.resolution, this.height * this.resolution, this.baseTexture.scaleMode); @@ -142,7 +145,8 @@ this.render = this.renderWebGL; this.projection = new math.Point(this.width*0.5, -this.height*0.5); } - else { + else + { this.render = this.renderCanvas; this.textureBuffer = new CanvasBuffer(this.width* this.resolution, this.height* this.resolution); this.baseTexture.source = this.textureBuffer.canvas; @@ -167,8 +171,10 @@ * @param height {number} The height to resize to. * @param updateBase {boolean} Should the baseTexture.width and height values be resized as well? */ -RenderTexture.prototype.resize = function (width, height, updateBase) { - if (width === this.width && height === this.height) { +RenderTexture.prototype.resize = function (width, height, updateBase) +{ + if (width === this.width && height === this.height) + { return; } @@ -177,17 +183,20 @@ this.width = this.frame.width = this.crop.width = width; this.height = this.frame.height = this.crop.height = height; - if (updateBase) { + if (updateBase) + { this.baseTexture.width = this.width; this.baseTexture.height = this.height; } - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { this.projection.x = this.width / 2; this.projection.y = -this.height / 2; } - if (!this.valid) { + if (!this.valid) + { return; } @@ -198,12 +207,15 @@ * Clears the RenderTexture. * */ -RenderTexture.prototype.clear = function () { - if (!this.valid) { +RenderTexture.prototype.clear = function () +{ + if (!this.valid) + { return; } - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { this.renderer.gl.bindFramebuffer(this.renderer.gl.FRAMEBUFFER, this.textureBuffer.frameBuffer); } @@ -220,19 +232,23 @@ * @param [restoreWorldTransform=true] {boolean} If true the displayObject's worldTransform/worldAlpha and all children * transformations will be restored. Not restoring this information will be a little faster. */ -RenderTexture.prototype.renderWebGL = function (displayObject, matrix, clear, restoreWorldTransform) { - if (!this.valid) { +RenderTexture.prototype.renderWebGL = function (displayObject, matrix, clear, restoreWorldTransform) +{ + if (!this.valid) + { return; } - if (typeof restoreWorldTransform === 'undefined') { + if (typeof restoreWorldTransform === 'undefined') + { restoreWorldTransform = true; } var tempAlpha, tempTransform; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { tempAlpha = displayObject.worldAlpha; tempTransform = displayObject.worldTransform.toArray(); } @@ -245,7 +261,8 @@ wt.identity(); wt.translate(0, this.projection.y * 2); - if (matrix) { + if (matrix) + { wt.append(matrix); } @@ -258,7 +275,8 @@ var children = displayObject.children; var i, j; - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } @@ -269,7 +287,8 @@ gl.bindFramebuffer(gl.FRAMEBUFFER, this.textureBuffer.frameBuffer ); - if (clear) { + if (clear) + { this.textureBuffer.clear(); } @@ -279,11 +298,13 @@ this.renderer.spriteBatch.dirty = true; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { displayObject.worldAlpha = tempAlpha; displayObject.worldTransform.fromArray(tempTransform); - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } } @@ -300,26 +321,31 @@ * @param [restoreWorldTransform=true] {boolean} If true the displayObject's worldTransform/worldAlpha and all children * transformations will be restored. Not restoring this information will be a little faster. */ -RenderTexture.prototype.renderCanvas = function (displayObject, matrix, clear, restoreWorldTransform) { - if (!this.valid) { +RenderTexture.prototype.renderCanvas = function (displayObject, matrix, clear, restoreWorldTransform) +{ + if (!this.valid) + { return; } - if (typeof restoreWorldTransform === 'undefined') { + if (typeof restoreWorldTransform === 'undefined') + { restoreWorldTransform = true; } var tempAlpha, tempTransform; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { tempAlpha = displayObject.worldAlpha; tempTransform = displayObject.worldTransform.toArray(); } var wt = displayObject.worldTransform; wt.identity(); - if (matrix) { + if (matrix) + { wt.append(matrix); } @@ -330,11 +356,13 @@ var children = displayObject.children; var i, j; - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } - if (clear) { + if (clear) + { this.textureBuffer.clear(); } @@ -348,11 +376,13 @@ this.renderer.resolution = realResolution; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { displayObject.worldAlpha = tempAlpha; displayObject.worldTransform.fromArray(tempTransform); - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } } @@ -363,7 +393,8 @@ * * @return {Image} */ -RenderTexture.prototype.getImage = function () { +RenderTexture.prototype.getImage = function () +{ var image = new Image(); image.src = this.getBase64(); return image; @@ -374,7 +405,8 @@ * * @return {string} A base64 encoded string of the texture. */ -RenderTexture.prototype.getBase64 = function () { +RenderTexture.prototype.getBase64 = function () +{ return this.getCanvas().toDataURL(); }; @@ -383,8 +415,10 @@ * * @return {HTMLCanvasElement} A Canvas element with the texture rendered on. */ -RenderTexture.prototype.getCanvas = function () { - if (this.renderer.type === CONST.WEBGL_RENDERER) { +RenderTexture.prototype.getCanvas = function () +{ + if (this.renderer.type === CONST.WEBGL_RENDERER) + { var gl = this.renderer.gl; var width = this.textureBuffer.width; var height = this.textureBuffer.height; @@ -403,7 +437,8 @@ return tempCanvas.canvas; } - else { + else + { return this.textureBuffer.canvas; } }; diff --git a/src/core/textures/Texture.js b/src/core/textures/Texture.js index 3c65909..e97f0aa 100644 --- a/src/core/textures/Texture.js +++ b/src/core/textures/Texture.js @@ -17,7 +17,8 @@ * @param [crop] {Rectangle} The area of original texture * @param [trim] {Rectangle} Trimmed texture rectangle */ -function Texture(baseTexture, frame, crop, trim) { +function Texture(baseTexture, frame, crop, trim) +{ /** * Does this Texture have any frame data assigned to it? * @@ -25,12 +26,14 @@ */ this.noFrame = false; - if (!frame) { + if (!frame) + { this.noFrame = true; frame = new math.Rectangle(0, 0, 1, 1); } - if (baseTexture instanceof Texture) { + if (baseTexture instanceof Texture) + { baseTexture = baseTexture.baseTexture; } @@ -100,13 +103,16 @@ */ this.crop = crop || new math.Rectangle(0, 0, 1, 1); - if (baseTexture.hasLoaded) { - if (this.noFrame) { + if (baseTexture.hasLoaded) + { + if (this.noFrame) + { frame = new math.Rectangle(0, 0, baseTexture.width, baseTexture.height); } this.frame = frame; } - else { + else + { baseTexture.addEventListener('loaded', this.onBaseTextureLoaded.bind(this)); } } @@ -118,19 +124,23 @@ Object.defineProperties(Texture.prototype, { needsUpdate: { - get: function () { + get: function () + { return this.baseTexture.needsUpdate; }, - set: function (val) { + set: function (val) + { this.baseTexture.needsUpdate = val; } }, frame: { - get: function () { + get: function () + { return this._frame; }, - set: function (frame) { + set: function (frame) + { this._frame = frame; this.noFrame = false; @@ -143,20 +153,23 @@ 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 (!this.trim && (frame.x + frame.width > this.baseTexture.width || frame.y + frame.height > this.baseTexture.height)) + { throw new Error('Texture Error: frame does not fit inside the base Texture dimensions ' + this); } this.valid = frame && frame.width && frame.height && this.baseTexture.source && this.baseTexture.hasLoaded; - if (this.trim) { + 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) { + if (this.valid) + { this._updateUvs(); } } @@ -168,11 +181,13 @@ * * @private */ -Texture.prototype.onBaseTextureLoaded = function () { +Texture.prototype.onBaseTextureLoaded = function () +{ var baseTexture = this.baseTexture; baseTexture.removeEventListener('loaded', this.onLoaded); - if (this.noFrame) { + if (this.noFrame) + { this.frame = new math.Rectangle(0, 0, baseTexture.width, baseTexture.height); } @@ -184,8 +199,10 @@ * * @param destroyBase {boolean} Whether to destroy the base texture as well */ -Texture.prototype.destroy = function (destroyBase) { - if (destroyBase) { +Texture.prototype.destroy = function (destroyBase) +{ + if (destroyBase) + { this.baseTexture.destroy(); } @@ -197,8 +214,10 @@ * * @private */ -Texture.prototype._updateUvs = function () { - if (!this._uvs) { +Texture.prototype._updateUvs = function () +{ + if (!this._uvs) + { this._uvs = new TextureUvs(); } @@ -229,10 +248,12 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return Texture */ -Texture.fromImage = function (imageUrl, crossorigin, scaleMode) { +Texture.fromImage = function (imageUrl, crossorigin, scaleMode) +{ var texture = utils.TextureCache[imageUrl]; - if (!texture) { + if (!texture) + { texture = new Texture(BaseTexture.fromImage(imageUrl, crossorigin, scaleMode)); utils.TextureCache[imageUrl] = texture; } @@ -248,9 +269,11 @@ * @param frameId {string} The frame id of the texture * @return Texture */ -Texture.fromFrame = function (frameId) { +Texture.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache '); } return texture; @@ -264,7 +287,8 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return {Texture} */ -Texture.fromCanvas = function (canvas, scaleMode) { +Texture.fromCanvas = function (canvas, scaleMode) +{ return new Texture(BaseTexture.fromCanvas(canvas, scaleMode)); }; @@ -276,7 +300,8 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return {Texture} A Texture */ -Texture.fromVideo = function (video, scaleMode) { +Texture.fromVideo = function (video, scaleMode) +{ return new Texture(VideoBaseTexture.baseTextureFromVideo(video, scaleMode)); }; @@ -287,7 +312,8 @@ * @param texture {Texture} The Texture to add to the cache. * @param id {string} The id that the texture will be stored against. */ -Texture.addTextureToCache = function (texture, id) { +Texture.addTextureToCache = function (texture, id) +{ utils.TextureCache[id] = texture; }; @@ -298,7 +324,8 @@ * @param id {string} The id of the texture to be removed * @return {Texture} The texture that was removed */ -Texture.removeTextureFromCache = function (id) { +Texture.removeTextureFromCache = function (id) +{ var texture = utils.TextureCache[id]; delete utils.TextureCache[id]; diff --git a/src/core/textures/TextureUvs.js b/src/core/textures/TextureUvs.js index b9bbb58..5424d52 100644 --- a/src/core/textures/TextureUvs.js +++ b/src/core/textures/TextureUvs.js @@ -1,4 +1,5 @@ -function TextureUvs() { +function TextureUvs() +{ this.x0 = 0; this.y0 = 0; diff --git a/src/core/textures/VideoBaseTexture.js b/src/core/textures/VideoBaseTexture.js index e3e0c5a..1a826a9 100644 --- a/src/core/textures/VideoBaseTexture.js +++ b/src/core/textures/VideoBaseTexture.js @@ -12,15 +12,18 @@ * @param source {HTMLVideoElement} * @param [scaleMode] {number} See {@link scaleModes} for possible values */ -function VideoBaseTexture(source, scaleMode) { - if (!source){ +function VideoBaseTexture(source, scaleMode) +{ + if (!source) + { throw new Error('No video source element specified.'); } // hook in here to check if video is already available. // BaseTexture looks for a source.complete boolean, plus width & height. - if ((source.readyState === source.HAVE_ENOUGH_DATA || source.readyState === source.HAVE_FUTURE_DATA) && source.width && source.height) { + if ((source.readyState === source.HAVE_ENOUGH_DATA || source.readyState === source.HAVE_FUTURE_DATA) && source.width && source.height) + { source.complete = true; } @@ -31,7 +34,8 @@ this._boundOnUpdate = this._onUpdate.bind(this); this._boundOnCanPlay = this._onCanPlay.bind(this); - if (!source.complete) { + if (!source.complete) + { source.addEventListener('canplay', this._boundOnCanPlay); source.addEventListener('canplaythrough', this._boundOnCanPlay); @@ -47,28 +51,35 @@ VideoBaseTexture.prototype.constructor = VideoBaseTexture; module.exports = VideoBaseTexture; -VideoBaseTexture.prototype._onUpdate = function () { - if (this.autoUpdate) { +VideoBaseTexture.prototype._onUpdate = function () +{ + if (this.autoUpdate) + { window.requestAnimationFrame(this._boundOnUpdate); this.needsUpdate = true; } }; -VideoBaseTexture.prototype._onPlayStart = function () { - if (!this.autoUpdate) { +VideoBaseTexture.prototype._onPlayStart = function () +{ + if (!this.autoUpdate) + { window.requestAnimationFrame(this._boundOnUpdate); this.autoUpdate = true; } }; -VideoBaseTexture.prototype._onPlayStop = function () { +VideoBaseTexture.prototype._onPlayStop = function () +{ this.autoUpdate = false; }; -VideoBaseTexture.prototype._onCanPlay = function () { +VideoBaseTexture.prototype._onCanPlay = function () +{ this.hasLoaded = true; - if (this.source) { + if (this.source) + { this.source.removeEventListener('canplay', this._boundOnCanPlay); this.source.removeEventListener('canplaythrough', this._boundOnCanPlay); @@ -78,15 +89,18 @@ this.source.play(); // prevent multiple loaded dispatches.. - if(!this.__loaded){ + if(!this.__loaded) + { this.__loaded = true; this.emit('loaded', this); } } }; -VideoBaseTexture.prototype.destroy = function () { - if (this.source && this.source._pixiId) { +VideoBaseTexture.prototype.destroy = function () +{ + if (this.source && this.source._pixiId) + { utils.BaseTextureCache[ this.source._pixiId ] = null; delete utils.BaseTextureCache[ this.source._pixiId ]; @@ -105,14 +119,17 @@ * @param scaleMode {number} See {@link scaleModes} for possible values * @return {VideoBaseTexture} */ -VideoBaseTexture.fromVideo = function (video, scaleMode) { - if (!video._pixiId) { +VideoBaseTexture.fromVideo = function (video, scaleMode) +{ + if (!video._pixiId) + { video._pixiId = 'video_' + utils.uuid(); } var baseTexture = utils.BaseTextureCache[video._pixiId]; - if (!baseTexture) { + if (!baseTexture) + { baseTexture = new VideoBaseTexture(video, scaleMode); utils.BaseTextureCache[ video._pixiId ] = baseTexture; } @@ -147,17 +164,21 @@ * @param scaleMode {number} See {@link scaleModes} for possible values * @return {VideoBaseTexture} */ -VideoBaseTexture.fromUrl = function (videoSrc, scaleMode) { +VideoBaseTexture.fromUrl = function (videoSrc, scaleMode) +{ var video = document.createElement('video'); // array of objects or strings - if (Array.isArray(videoSrc)) { - for (var i = 0; i < videoSrc.length; ++i) { + if (Array.isArray(videoSrc)) + { + for (var i = 0; i < videoSrc.length; ++i) + { video.appendChild(createSource(videoSrc.src || videoSrc, videoSrc.mime)); } } // single object or string - else { + else + { video.appendChild(createSource(videoSrc.src || videoSrc, videoSrc.mime)); } @@ -169,8 +190,10 @@ VideoBaseTexture.fromUrls = VideoBaseTexture.fromUrl; -function createSource(path, type) { - if (!type) { +function createSource(path, type) +{ + if (!type) + { type = 'video/' + path.substr(path.lastIndexOf('.') + 1); } diff --git a/src/core/utils/EventData.js b/src/core/utils/EventData.js index 5d55a22..8cdf701 100644 --- a/src/core/utils/EventData.js +++ b/src/core/utils/EventData.js @@ -7,7 +7,8 @@ * @param name {string} The string name of the event that was triggered * @param data {object} Arbitrary event data to pass along */ -function EventData(target, name, data) { +function EventData(target, name, data) +{ // for duck typing in the ".on()" function this.__isEventObject = true; @@ -71,7 +72,8 @@ * Stops the propagation of events up the scene graph (prevents bubbling). * */ -EventData.prototype.stopPropagation = function stopPropagation() { +EventData.prototype.stopPropagation = function stopPropagation() +{ this.stopped = true; }; @@ -79,6 +81,7 @@ * Stops the propagation of events to sibling listeners (no longer calls any listeners). * */ -EventData.prototype.stopImmediatePropagation = function stopImmediatePropagation() { +EventData.prototype.stopImmediatePropagation = function stopImmediatePropagation() +{ this.stoppedImmediate = true; }; diff --git a/src/core/utils/EventTarget.js b/src/core/utils/EventTarget.js index 7ae8820..671a151 100644 --- a/src/core/utils/EventTarget.js +++ b/src/core/utils/EventTarget.js @@ -13,14 +13,16 @@ * var em = new MyEmitter(); * em.emit('eventName', 'some data', 'some more data', {}, null, ...); */ -function eventTarget(obj) { +function eventTarget(obj) +{ /** * Return a list of assigned event listeners. * * @param eventName {string} The events that should be listed. * @return {Array} An array of listener functions */ - obj.listeners = function listeners(eventName) { + obj.listeners = function listeners(eventName) + { this._listeners = this._listeners || {}; return this._listeners[eventName] ? this._listeners[eventName].slice() : []; @@ -33,22 +35,26 @@ * @param eventName {string} The name of the event. * @return {boolean} Indication if we've emitted an event. */ - obj.emit = obj.dispatchEvent = function emit(eventName, data) { + obj.emit = obj.dispatchEvent = function emit(eventName, data) + { this._listeners = this._listeners || {}; // fast return when there are no listeners - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return; } //backwards compat with old method ".emit({ type: 'something' })" - if (typeof eventName === 'object') { + if (typeof eventName === 'object') + { data = eventName; eventName = eventName.type; } //ensure we are using a real pixi event - if (!data || data.__isEventObject !== true) { + if (!data || data.__isEventObject !== true) + { data = new EventData(this, eventName, data); } @@ -58,23 +64,27 @@ fn = listeners[0], i; - for (i = 0; i < length; fn = listeners[++i]) { + for (i = 0; i < length; fn = listeners[++i]) + { //call the event listener fn.call(this, data); //if "stopImmediatePropagation" is called, stop calling sibling events - if (data.stoppedImmediate) { + if (data.stoppedImmediate) + { return this; } } //if "stopPropagation" is called then don't bubble the event - if (data.stopped) { + if (data.stopped) + { return this; } //bubble this event up the scene graph - if (this.parent && this.parent.emit) { + if (this.parent && this.parent.emit) + { this.parent.emit.call(this.parent, eventName, data); } @@ -88,7 +98,8 @@ * @param eventName {string} Name of the event. * @param callback {Functon} fn Callback function. */ - obj.on = obj.addEventListener = function on(eventName, fn) { + obj.on = obj.addEventListener = function on(eventName, fn) + { this._listeners = this._listeners || {}; (this._listeners[eventName] = this._listeners[eventName] || []) @@ -103,11 +114,13 @@ * @param eventName {string} Name of the event. * @param callback {Function} Callback function. */ - obj.once = function once(eventName, fn) { + obj.once = function once(eventName, fn) + { this._listeners = this._listeners || {}; var self = this; - function onceHandlerWrapper() { + function onceHandlerWrapper() + { fn.apply(self.off(eventName, onceHandlerWrapper), arguments); } onceHandlerWrapper._originalHandler = fn; @@ -122,23 +135,28 @@ * @param eventName {string} The event we want to remove. * @param callback {Function} The listener that we need to find. */ - obj.off = obj.removeEventListener = function off(eventName, fn) { + obj.off = obj.removeEventListener = function off(eventName, fn) + { this._listeners = this._listeners || {}; - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return this; } var list = this._listeners[eventName], i = fn ? list.length : 0; - while(i-- > 0) { - if (list[i] === fn || list[i]._originalHandler === fn) { + while(i-- > 0) + { + if (list[i] === fn || list[i]._originalHandler === fn) + { list.splice(i, 1); } } - if (list.length === 0) { + if (list.length === 0) + { delete this._listeners[eventName]; } @@ -150,10 +168,12 @@ * * @param eventName {string} The event you want to remove all listeners for. */ - obj.removeAllListeners = function removeAllListeners(eventName) { + obj.removeAllListeners = function removeAllListeners(eventName) + { this._listeners = this._listeners || {}; - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return this; } @@ -169,7 +189,8 @@ * * @param object {object} The obj to mix into */ - mixin: function mixin(obj) { + mixin: function mixin(obj) + { eventTarget(obj); } }; diff --git a/src/core/utils/PolyK.js b/src/core/utils/PolyK.js index 7325141..5e20c2b 100644 --- a/src/core/utils/PolyK.js +++ b/src/core/utils/PolyK.js @@ -47,7 +47,8 @@ * Triangulates shapes for webGL graphic fills. * */ -PolyK.Triangulate = function (p) { +PolyK.Triangulate = function (p) +{ var sign = true; var n = p.length >> 1; @@ -59,7 +60,8 @@ i = 0; var al = n; - while(al > 3) { + while(al > 3) + { var i0 = avl[(i+0)%al]; var i1 = avl[(i+1)%al]; var i2 = avl[(i+2)%al]; @@ -69,29 +71,35 @@ var cx = p[2*i2], cy = p[2*i2+1]; var earFound = false; - if (PolyK._convex(ax, ay, bx, by, cx, cy, sign)) { + if (PolyK._convex(ax, ay, bx, by, cx, cy, sign)) + { earFound = true; - for (var j = 0; j < al; j++) { + for (var j = 0; j < al; j++) + { var vi = avl[j]; if (vi === i0 || vi === i1 || vi === i2) continue; - if (PolyK._PointInTriangle(p[2*vi], p[2*vi+1], ax, ay, bx, by, cx, cy)) { + if (PolyK._PointInTriangle(p[2*vi], p[2*vi+1], ax, ay, bx, by, cx, cy)) + { earFound = false; break; } } } - if (earFound) { + if (earFound) + { tgs.push(i0, i1, i2); avl.splice((i+1)%al, 1); al--; i = 0; } - else if (i++ > 3*al) { + else if (i++ > 3*al) + { // need to flip flip reverse it! // reset! - if (sign) { + if (sign) + { tgs = []; avl = []; for (i = 0; i < n; i++) avl.push(i); @@ -101,7 +109,8 @@ sign = false; } - else { + else + { // window.console.log("PIXI Warning: shape too complex to fill"); return null; } @@ -126,7 +135,8 @@ * @private * @return {boolean} */ -PolyK._PointInTriangle = function (px, py, ax, ay, bx, by, cx, cy) { +PolyK._PointInTriangle = function (px, py, ax, ay, bx, by, cx, cy) +{ var v0x = cx-ax; var v0y = cy-ay; var v1x = bx-ax; @@ -154,6 +164,7 @@ * @private * @return {boolean} */ -PolyK._convex = function (ax, ay, bx, by, cx, cy, sign) { +PolyK._convex = function (ax, ay, bx, by, cx, cy, sign) +{ return ((ay-by)*(cx-bx) + (bx-ax)*(cy-by) >= 0) === sign; }; diff --git a/src/core/utils/index.js b/src/core/utils/index.js index ade9831..bfae7ae 100644 --- a/src/core/utils/index.js +++ b/src/core/utils/index.js @@ -16,7 +16,8 @@ * * @return {number} The next uuid to use. */ - uuid: function () { + uuid: function () + { return ++utils._uid; }, @@ -26,7 +27,8 @@ * @param hex {number} * @return {number[]} An array representing the [R, G, B] of the color. */ - hex2rgb: function (hex, out) { + hex2rgb: function (hex, out) + { out = out || []; out[0] = (hex >> 16 & 0xFF) / 255; @@ -42,7 +44,8 @@ * @param hex {number} * @return {string} The string color. */ - hex2string: function (hex) { + hex2string: function (hex) + { hex = hex.toString(16); hex = '000000'.substr(0, 6 - hex.length) + hex; @@ -55,7 +58,8 @@ * @param rgb {number[]} * @return {number} The color number */ - rgb2hex: function (rgb) { + rgb2hex: function (rgb) + { return ((rgb[0]*255 << 16) + (rgb[1]*255 << 8) + rgb[2]*255); }, @@ -64,8 +68,10 @@ * * @return {boolean} whether they are supported */ - canUseNewCanvasBlendModes: function () { - if (typeof document === 'undefined') { + canUseNewCanvasBlendModes: function () + { + if (typeof document === 'undefined') + { return false; } @@ -93,15 +99,19 @@ * @param number {number} * @return {number} the closest number that is a power of two */ - getNextPowerOfTwo: function (number) { + getNextPowerOfTwo: function (number) + { // see: http://en.wikipedia.org/wiki/Power_of_two#Fast_algorithm_to_check_if_a_positive_number_is_a_power_of_two - if (number > 0 && (number & (number - 1)) === 0) { + if (number > 0 && (number & (number - 1)) === 0) + { return number; } - else { + else + { var result = 1; - while (result < number) { + while (result < number) + { result <<= 1; } @@ -116,7 +126,8 @@ * @param height {number} * @return {boolean} */ - isPowerOfTwo: function (width, height) { + isPowerOfTwo: function (width, height) + { return (width > 0 && (width & (width - 1)) === 0 && height > 0 && (height & (height - 1)) === 0); }, @@ -130,12 +141,15 @@ * @constant * @static */ - sayHello: function (type) { - if (utils._saidHello) { + sayHello: function (type) + { + if (utils._saidHello) + { return; } - if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) { + if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) + { var args = [ '%c %c %c Pixi.js ' + CONST.VERSION + ' - ' + type + ' %c ' + ' %c ' + ' http://www.pixijs.com/ %c %c ♥%c♥%c♥ ', 'background: #ff66a5', @@ -151,7 +165,8 @@ console.log.apply(console, args); //jshint ignore:line } - else if (window.console) { + else if (window.console) + { console.log('Pixi.js ' + CONST.VERSION + ' - ' + type + ' - http://www.pixijs.com/'); //jshint ignore:line } @@ -166,15 +181,19 @@ * @class * @namespace PIXI */ - AjaxRequest: function () { + AjaxRequest: function () + { var activexmodes = ['Msxml2.XMLHTTP.6.0', 'Msxml2.XMLHTTP.3.0', 'Microsoft.XMLHTTP']; //activeX versions to check for in IE - if (window.ActiveXObject) { //Test for support for ActiveXObject in IE first (as XMLHttpRequest in IE7 is broken) - for (var i=0; i= this.textures.length) { + else if (round >= this.textures.length) + { this.gotoAndStop(this.textures.length - 1); - if (this.onComplete) { + if (this.onComplete) + { this.onComplete(); } } @@ -167,10 +182,12 @@ * @static * @param frames {string[]} the array of frames ids the movieclip will use as its texture frames */ -MovieClip.fromFrames = function (frames) { +MovieClip.fromFrames = function (frames) +{ var textures = []; - for (var i = 0; i < frames.length; ++i) { + for (var i = 0; i < frames.length; ++i) + { textures.push(new core.Texture.fromFrame(frames[i])); } @@ -183,10 +200,12 @@ * @static * @param images {string[]} the array of image urls the movieclip will use as its texture frames */ -MovieClip.fromImages = function (images) { +MovieClip.fromImages = function (images) +{ var textures = []; - for (var i = 0; i < images.length; ++i) { + for (var i = 0; i < images.length; ++i) + { textures.push(new core.Texture.fromImage(images[i])); } diff --git a/src/extras/Rope.js b/src/extras/Rope.js index c157ec4..9c87bc0 100644 --- a/src/extras/Rope.js +++ b/src/extras/Rope.js @@ -9,7 +9,8 @@ * @param {Array} points - An array of {Point}. * */ -function Rope(texture, points) { +function Rope(texture, points) +{ Strip.call(this, texture); this.points = points; @@ -31,10 +32,12 @@ * Refreshes * */ -Rope.prototype.refresh = function () { +Rope.prototype.refresh = function () +{ var points = this.points; - if (points.length < 1) { + if (points.length < 1) + { return; } @@ -59,20 +62,23 @@ var total = points.length, point, index, amount; - for (var i = 1; i < total; i++) { + for (var i = 1; i < total; i++) + { point = points[i]; index = i * 4; // time to do some smart drawing! amount = i / (total-1); - if (i%2) { + if (i%2) + { uvs[index] = amount; uvs[index+1] = 0; uvs[index+2] = amount; uvs[index+3] = 1; } - else { + else + { uvs[index] = amount; uvs[index+1] = 0; @@ -95,10 +101,12 @@ * * @private */ -Rope.prototype.updateTransform = function () { +Rope.prototype.updateTransform = function () +{ var points = this.points; - if (points.length < 1) { + if (points.length < 1) + { return; } @@ -113,14 +121,17 @@ var total = points.length, point, index, ratio, perpLength, num; - for (var i = 0; i < total; i++) { + for (var i = 0; i < total; i++) + { point = points[i]; index = i * 4; - if (i < points.length-1) { + if (i < points.length-1) + { nextPoint = points[i+1]; } - else { + else + { nextPoint = point; } @@ -129,7 +140,8 @@ ratio = (1 - (i / (total-1))) * 10; - if (ratio > 1) { + if (ratio > 1) + { ratio = 1; } @@ -157,7 +169,8 @@ * * @param texture {Texture} the texture that will be used */ -Rope.prototype.setTexture = function (texture) { +Rope.prototype.setTexture = function (texture) +{ // stop current texture this.texture = texture; //this.updateFrame = true; diff --git a/src/extras/Strip.js b/src/extras/Strip.js index c5e378f..57691b5 100644 --- a/src/extras/Strip.js +++ b/src/extras/Strip.js @@ -10,7 +10,8 @@ * @param height {number} the height * */ -function Strip(texture) { +function Strip(texture) +{ core.DisplayObjectContainer.call(this); /** @@ -70,9 +71,11 @@ * * @param renderer {WebGLRenderer} */ -Strip.prototype.renderWebGL = function (renderer) { +Strip.prototype.renderWebGL = function (renderer) +{ // if the sprite is not visible or the alpha is 0 then no need to render this element - if (!this.visible || this.alpha <= 0) { + if (!this.visible || this.alpha <= 0) + { return; } @@ -81,7 +84,8 @@ renderer.spriteBatch.stop(); // init! init! - if (!this._vertexBuffer) { + if (!this._vertexBuffer) + { this._initWebGL(renderer); } @@ -96,7 +100,8 @@ //TODO check culling }; -Strip.prototype._initWebGL = function (renderer) { +Strip.prototype._initWebGL = function (renderer) +{ // build the strip! var gl = renderer.gl; @@ -118,7 +123,8 @@ gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this.indices, gl.STATIC_DRAW); }; -Strip.prototype._renderStrip = function (renderer) { +Strip.prototype._renderStrip = function (renderer) +{ var gl = renderer.gl; var projection = renderer.projection, offset = renderer.offset, @@ -137,7 +143,8 @@ gl.uniform2f(shader.offsetVector, -offset.x, -offset.y); gl.uniform1f(shader.alpha, this.worldAlpha); - if (!this.dirty) { + if (!this.dirty) + { gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexBuffer); gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); @@ -150,10 +157,12 @@ gl.activeTexture(gl.TEXTURE0); // check if a texture is dirty.. - if (this.texture.baseTexture._dirty[gl.id]) { + if (this.texture.baseTexture._dirty[gl.id]) + { renderer.updateTexture(this.texture.baseTexture); } - else { + else + { // bind the current texture gl.bindTexture(gl.TEXTURE_2D, this.texture.baseTexture._glTextures[gl.id]); } @@ -163,7 +172,8 @@ } - else { + else + { this.dirty = false; gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexBuffer); @@ -178,10 +188,12 @@ gl.activeTexture(gl.TEXTURE0); // check if a texture is dirty.. - if (this.texture.baseTexture._dirty[gl.id]) { + if (this.texture.baseTexture._dirty[gl.id]) + { renderer.updateTexture(this.texture.baseTexture); } - else { + else + { gl.bindTexture(gl.TEXTURE_2D, this.texture.baseTexture._glTextures[gl.id]); } @@ -203,27 +215,33 @@ * * @param renderer {CanvasRenderer} */ -Strip.prototype.renderCanvas = function (renderer) { +Strip.prototype.renderCanvas = function (renderer) +{ var context = renderer.context; var transform = this.worldTransform; - if (renderer.roundPixels) { + if (renderer.roundPixels) + { context.setTransform(transform.a, transform.b, transform.c, transform.d, transform.tx | 0, transform.ty | 0); } - else { + else + { context.setTransform(transform.a, transform.b, transform.c, transform.d, transform.tx, transform.ty); } - if (this.drawMode === Strip.DrawModes.TRIANGLE_STRIP) { + if (this.drawMode === Strip.DrawModes.TRIANGLE_STRIP) + { this._renderCanvasTriangleStrip(context); } - else { + else + { this._renderCanvasTriangles(context); } }; -Strip.prototype._renderCanvasTriangleStrip = function (context) { +Strip.prototype._renderCanvasTriangleStrip = function (context) +{ // draw triangles!! var vertices = this.vertices; var uvs = this.uvs; @@ -231,14 +249,16 @@ var length = vertices.length / 2; // this.count++; - for (var i = 0; i < length - 2; i++) { + for (var i = 0; i < length - 2; i++) + { // draw some triangles! var index = i * 2; this._renderCanvasDrawTriangle(context, vertices, uvs, index, (index + 2), (index + 4)); } }; -Strip.prototype._renderCanvasTriangles = function (context) { +Strip.prototype._renderCanvasTriangles = function (context) +{ // draw triangles!! var vertices = this.vertices; var uvs = this.uvs; @@ -247,14 +267,16 @@ var length = indices.length; // this.count++; - for (var i = 0; i < length; i += 3) { + for (var i = 0; i < length; i += 3) + { // draw some triangles! var index0 = indices[i] * 2, index1 = indices[i + 1] * 2, index2 = indices[i + 2] * 2; this._renderCanvasDrawTriangle(context, vertices, uvs, index0, index1, index2); } }; -Strip.prototype._renderCanvasDrawTriangle = function (context, vertices, uvs, index0, index1, index2) { +Strip.prototype._renderCanvasDrawTriangle = function (context, vertices, uvs, index0, index1, index2) +{ var textureSource = this.texture.baseTexture.source; var textureWidth = this.texture.width; var textureHeight = this.texture.height; @@ -265,7 +287,8 @@ var u0 = uvs[index0] * textureWidth, u1 = uvs[index1] * textureWidth, u2 = uvs[index2] * textureWidth; var v0 = uvs[index0 + 1] * textureHeight, v1 = uvs[index1 + 1] * textureHeight, v2 = uvs[index2 + 1] * textureHeight; - if (this.canvasPadding > 0) { + if (this.canvasPadding > 0) + { var paddingX = this.canvasPadding / this.worldTransform.a; var paddingY = this.canvasPadding / this.worldTransform.d; var centerX = (x0 + x1 + x2) / 3; @@ -332,7 +355,8 @@ * @param strip {Strip} The Strip to render * @private */ -Strip.prototype.renderStripFlat = function (strip) { +Strip.prototype.renderStripFlat = function (strip) +{ var context = this.context; var vertices = strip.vertices; @@ -340,7 +364,8 @@ // this.count++; context.beginPath(); - for (var i=1; i < length-2; i++) { + for (var i=1; i < length-2; i++) + { // draw some triangles! var index = i*2; @@ -358,7 +383,8 @@ }; /* -Strip.prototype.setTexture = function (texture) { +Strip.prototype.setTexture = function (texture) +{ //TODO SET THE TEXTURES //TODO VISIBILITY @@ -377,7 +403,8 @@ * @private */ -Strip.prototype.onTextureUpdate = function () { +Strip.prototype.onTextureUpdate = function () +{ this.updateFrame = true; }; @@ -387,7 +414,8 @@ * @param matrix {Matrix} the transformation matrix of the sprite * @return {Rectangle} the framing rectangle */ -Strip.prototype.getBounds = function (matrix) { +Strip.prototype.getBounds = function (matrix) +{ var worldTransform = matrix || this.worldTransform; var a = worldTransform.a; @@ -404,7 +432,8 @@ var minY = Infinity; var vertices = this.vertices; - for (var i = 0, n = vertices.length; i < n; i += 2) { + for (var i = 0, n = vertices.length; i < n; i += 2) + { var rawX = vertices[i], rawY = vertices[i + 1]; var x = (a * rawX) + (c * rawY) + tx; var y = (d * rawY) + (b * rawX) + ty; @@ -416,7 +445,8 @@ maxY = y > maxY ? y : maxY; } - if (minX === -Infinity || maxY === Infinity) { + if (minX === -Infinity || maxY === Infinity) + { return core.math.Rectangle.EMPTY; } diff --git a/src/extras/TilingSprite.js b/src/extras/TilingSprite.js index 3ac22df..31da393 100644 --- a/src/extras/TilingSprite.js +++ b/src/extras/TilingSprite.js @@ -10,7 +10,8 @@ * @param width {number} the width of the tiling sprite * @param height {number} the height of the tiling sprite */ -function TilingSprite(texture, width, height) { +function TilingSprite(texture, width, height) +{ core.Sprite.call( this, texture); /** @@ -86,10 +87,12 @@ * @memberof TilingSprite# */ width: { - get: function () { + get: function () + { return this._width; }, - set: function (value) { + set: function (value) + { this._width = value; } }, @@ -101,20 +104,25 @@ * @memberof TilingSprite# */ height: { - get: function () { + get: function () + { return this._height; }, - set: function (value) { + set: function (value) + { this._height = value; } }, texture: { - get: function () { + get: function () + { return this._texture; }, - set: function (value) { - if (this._texture === value) { + set: function (value) + { + if (this._texture === value) + { return; } @@ -130,51 +138,61 @@ * * @param renderer {WebGLRenderer} */ -TilingSprite.prototype.renderWebGL = function (renderer) { - if (!this.visible || this.alpha <= 0) { +TilingSprite.prototype.renderWebGL = function (renderer) +{ + if (!this.visible || this.alpha <= 0) + { return; } var i, j; - if (this._mask) { + if (this._mask) + { renderer.spriteBatch.stop(); renderer.maskManager.pushMask(this.mask, renderer); renderer.spriteBatch.start(); } - if (this._filters) { + if (this._filters) + { renderer.spriteBatch.flush(); renderer.filterManager.pushFilter(this._filterBlock); } - if (!this.tilingTexture || this.refreshTexture) { + if (!this.tilingTexture || this.refreshTexture) + { this.generateTilingTexture(true); - if (this.tilingTexture && this.tilingTexture.needsUpdate) { + if (this.tilingTexture && this.tilingTexture.needsUpdate) + { //TODO - tweaking renderer.updateTexture(this.tilingTexture.baseTexture); this.tilingTexture.needsUpdate = false; // this.tilingTexture._uvs = null; } } - else { + else + { renderer.spriteBatch.renderTilingSprite(this); } // simple render children! - for (i=0,j=this.children.length; i= 0; i--) { + for (var i = length - 1; i >= 0; i--) + { var child = children[i]; // push all interactive bits - if (child._interactive) { + if (child._interactive) + { iParent.interactiveChildren = true; //child.__iParent = iParent; this.interactiveItems.push(child); - if (child.children.length > 0) { + if (child.children.length > 0) + { this.collectInteractiveSprite(child, child); } } - else { + else + { child.__iParent = null; - if (child.children.length > 0) { + if (child.children.length > 0) + { this.collectInteractiveSprite(child, iParent); } } @@ -189,7 +196,8 @@ * @param [resolution=1] {number} THe resolution of the new element (relative to the canvas). * @private */ -InteractionManager.prototype.setTargetElement = function (element, resolution) { +InteractionManager.prototype.setTargetElement = function (element, resolution) +{ this.removeEvents(); this.interactionDOMElement = element; @@ -203,12 +211,15 @@ * * @private */ -InteractionManager.prototype.addEvents = function () { - if (!this.interactionDOMElement) { +InteractionManager.prototype.addEvents = function () +{ + if (!this.interactionDOMElement) + { return; } - if (window.navigator.msPointerEnabled) { + if (window.navigator.msPointerEnabled) + { this.interactionDOMElement.style['-ms-content-zooming'] = 'none'; this.interactionDOMElement.style['-ms-touch-action'] = 'none'; } @@ -230,12 +241,15 @@ * * @private */ -InteractionManager.prototype.removeEvents = function () { - if (!this.interactionDOMElement) { +InteractionManager.prototype.removeEvents = function () +{ + if (!this.interactionDOMElement) + { return; } - if (window.navigator.msPointerEnabled) { + if (window.navigator.msPointerEnabled) + { this.interactionDOMElement.style['-ms-content-zooming'] = ''; this.interactionDOMElement.style['-ms-touch-action'] = ''; } @@ -260,8 +274,10 @@ * * @private */ -InteractionManager.prototype.update = function () { - if (!this.interactionDOMElement) { +InteractionManager.prototype.update = function () +{ + if (!this.interactionDOMElement) + { return; } @@ -269,7 +285,8 @@ var now = Date.now(); var diff = now - this.last; diff = (diff * INTERACTION_FREQUENCY ) / 1000; - if (diff < 1) { + if (diff < 1) + { return; } @@ -280,7 +297,8 @@ // ok.. so mouse events?? // yes for now :) // OPTIMISE - how often to check?? - if (this.dirty) { + if (this.dirty) + { this.rebuildInteractiveGraph(); } @@ -289,7 +307,8 @@ var cursor = 'inherit'; var over = false; - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { var item = this.interactiveItems[i]; // OPTIMISATION - only calculate every time if the mousemove function exists.. @@ -302,26 +321,34 @@ this.mouse.target = item; // ok so deal with interactions.. // looks like there was a hit! - if (item.__hit && !over) { - if (item.buttonMode) { + if (item.__hit && !over) + { + if (item.buttonMode) + { cursor = item.defaultCursor; } - if (!item.interactiveChildren) { + if (!item.interactiveChildren) + { over = true; } - if (!item.__isOver) { - if (item.mouseover) { + if (!item.__isOver) + { + if (item.mouseover) + { item.mouseover (this.mouse); } item.__isOver = true; } } - else { - if (item.__isOver) { + else + { + if (item.__isOver) + { // roll out! - if (item.mouseout) { + if (item.mouseout) + { item.mouseout (this.mouse); } item.__isOver = false; @@ -329,7 +356,8 @@ } } - if (this.currentCursorStyle !== cursor) { + if (this.currentCursorStyle !== cursor) + { this.currentCursorStyle = cursor; this.interactionDOMElement.style.cursor = cursor; } @@ -338,18 +366,21 @@ /** * @private */ -InteractionManager.prototype.rebuildInteractiveGraph = function () { +InteractionManager.prototype.rebuildInteractiveGraph = function () +{ this.dirty = false; var len = this.interactiveItems.length; - for (var i = 0; i < len; i++) { + for (var i = 0; i < len; i++) + { this.interactiveItems[i].interactiveChildren = false; } this.interactiveItems.length = 0; - if (this.stage.interactive) { + if (this.stage.interactive) + { this.interactiveItems.push(this.stage); } @@ -363,8 +394,10 @@ * @param event {Event} The DOM event of the mouse moving * @private */ -InteractionManager.prototype.onMouseMove = function (event) { - if (this.dirty) { +InteractionManager.prototype.onMouseMove = function (event) +{ + if (this.dirty) + { this.rebuildInteractiveGraph(); } @@ -378,11 +411,13 @@ var length = this.interactiveItems.length; - for (var i = 0; i < length; i++) { + for (var i = 0; i < length; i++) + { var item = this.interactiveItems[i]; // Call the function! - if (item.mousemove) { + if (item.mousemove) + { item.mousemove(this.mouse); } } @@ -394,14 +429,17 @@ * @param event {Event} The DOM event of a mouse button being pressed down * @private */ -InteractionManager.prototype.onMouseDown = function (event) { - if (this.dirty) { +InteractionManager.prototype.onMouseDown = function (event) +{ + if (this.dirty) + { this.rebuildInteractiveGraph(); } this.mouse.originalEvent = event; - if (AUTO_PREVENT_DEFAULT) { + if (AUTO_PREVENT_DEFAULT) + { this.mouse.originalEvent.preventDefault(); } @@ -420,22 +458,27 @@ // while // hit test - for (var i = 0; i < length; i++) { + for (var i = 0; i < length; i++) + { var item = this.interactiveItems[i]; - if (item[downFunction] || item[clickFunction]) { + if (item[downFunction] || item[clickFunction]) + { item[buttonIsDown] = true; item.__hit = this.hitTest(item, this.mouse); - if (item.__hit) { + if (item.__hit) + { //call the function! - if (item[downFunction]) { + if (item[downFunction]) + { item[downFunction](this.mouse); } item[isDown] = true; // just the one! - if (!item.interactiveChildren) { + if (!item.interactiveChildren) + { break; } } @@ -449,8 +492,10 @@ * @param event {Event} The DOM event of a mouse being moved out * @private */ -InteractionManager.prototype.onMouseOut = function (event) { - if (this.dirty) { +InteractionManager.prototype.onMouseOut = function (event) +{ + if (this.dirty) + { this.rebuildInteractiveGraph(); } @@ -460,11 +505,14 @@ this.interactionDOMElement.style.cursor = 'inherit'; - for (var i = 0; i < length; i++) { + for (var i = 0; i < length; i++) + { var item = this.interactiveItems[i]; - if (item.__isOver) { + if (item.__isOver) + { this.mouse.target = item; - if (item.mouseout) { + if (item.mouseout) + { item.mouseout(this.mouse); } item.__isOver = false; @@ -484,8 +532,10 @@ * @param event {Event} The DOM event of a mouse button being released * @private */ -InteractionManager.prototype.onMouseUp = function (event) { - if (this.dirty) { +InteractionManager.prototype.onMouseUp = function (event) +{ + if (this.dirty) + { this.rebuildInteractiveGraph(); } @@ -502,30 +552,40 @@ var upOutsideFunction = isRightButton ? 'rightupoutside' : 'mouseupoutside'; var isDown = isRightButton ? '__isRightDown' : '__isDown'; - for (var i = 0; i < length; i++) { + for (var i = 0; i < length; i++) + { var item = this.interactiveItems[i]; - if (item[clickFunction] || item[upFunction] || item[upOutsideFunction]) { + if (item[clickFunction] || item[upFunction] || item[upOutsideFunction]) + { item.__hit = this.hitTest(item, this.mouse); - if (item.__hit && !up) { + if (item.__hit && !up) + { //call the function! - if (item[upFunction]) { + if (item[upFunction]) + { item[upFunction](this.mouse); } - if (item[isDown]) { - if (item[clickFunction]) { + if (item[isDown]) + { + if (item[clickFunction]) + { item[clickFunction](this.mouse); } } - if (!item.interactiveChildren) { + if (!item.interactiveChildren) + { up = true; } } - else { - if (item[isDown]) { - if (item[upOutsideFunction]) { + else + { + if (item[isDown]) + { + if (item[upOutsideFunction]) + { item[upOutsideFunction](this.mouse); } } @@ -543,10 +603,12 @@ * @param interactionData {InteractionData} The interactionData object to update in the case there is a hit * @private */ -InteractionManager.prototype.hitTest = function (item, interactionData) { +InteractionManager.prototype.hitTest = function (item, interactionData) +{ var global = interactionData.global; - if (!item.worldVisible) { + if (!item.worldVisible) + { return false; } @@ -560,37 +622,46 @@ interactionData.target = item; //a sprite or display object with a hit area defined - if (item.hitArea && item.hitArea.contains) { + if (item.hitArea && item.hitArea.contains) + { return item.hitArea.contains(x, y); } // a sprite with no hitarea defined - else if (item instanceof core.Sprite) { + else if (item instanceof core.Sprite) + { var width = item.texture.frame.width; var height = item.texture.frame.height; var x1 = -width * item.anchor.x; var y1; - if (x > x1 && x < x1 + width) { + if (x > x1 && x < x1 + width) + { y1 = -height * item.anchor.y; - if (y > y1 && y < y1 + height) { + if (y > y1 && y < y1 + height) + { // set the target property if a hit is true! return true; } } } - else if (item instanceof core.Graphics) { + else if (item instanceof core.Graphics) + { var graphicsData = item.graphicsData; - for (i = 0; i < graphicsData.length; i++) { + for (i = 0; i < graphicsData.length; i++) + { var data = graphicsData[i]; - if (!data.fill) { + if (!data.fill) + { continue; } // only deal with fills.. - if (data.shape) { - if (data.shape.contains(x, y)) { + if (data.shape) + { + if (data.shape.contains(x, y)) + { //interactionData.target = item; return true; } @@ -600,10 +671,12 @@ var length = item.children.length; - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { var tempItem = item.children[i]; var hit = this.hitTest(tempItem, interactionData); - if (hit) { + if (hit) + { // hmm.. TODO SET CORRECT TARGET? interactionData.target = item; return true; @@ -618,8 +691,10 @@ * @param event {Event} The DOM event of a touch moving across the renderer view * @private */ -InteractionManager.prototype.onTouchMove = function (event) { - if (this.dirty) { +InteractionManager.prototype.onTouchMove = function (event) +{ + if (this.dirty) + { this.rebuildInteractiveGraph(); } @@ -628,7 +703,8 @@ var touchData; var i = 0; - for (i = 0; i < changedTouches.length; i++) { + for (i = 0; i < changedTouches.length; i++) + { var touchEvent = changedTouches[i]; touchData = this.touches[touchEvent.identifier]; touchData.originalEvent = event; @@ -636,15 +712,18 @@ // update the touch position touchData.global.x = ( (touchEvent.clientX - rect.left) * (this.interactionDOMElement.width / rect.width) ) / this.resolution; touchData.global.y = ( (touchEvent.clientY - rect.top) * (this.interactionDOMElement.height / rect.height) ) / this.resolution; - if (navigator.isCocoonJS && !rect.left && !rect.top && !event.target.style.width && !event.target.style.height) { + if (navigator.isCocoonJS && !rect.left && !rect.top && !event.target.style.width && !event.target.style.height) + { //Support for CocoonJS fullscreen scale modes touchData.global.x = touchEvent.clientX; touchData.global.y = touchEvent.clientY; } - for (var j = 0; j < this.interactiveItems.length; j++) { + for (var j = 0; j < this.interactiveItems.length; j++) + { var item = this.interactiveItems[j]; - if (item.touchmove && item.__touchData && item.__touchData[touchEvent.identifier]) { + if (item.touchmove && item.__touchData && item.__touchData[touchEvent.identifier]) + { item.touchmove(touchData); } } @@ -657,23 +736,28 @@ * @param event {Event} The DOM event of a touch starting on the renderer view * @private */ -InteractionManager.prototype.onTouchStart = function (event) { - if (this.dirty) { +InteractionManager.prototype.onTouchStart = function (event) +{ + if (this.dirty) + { this.rebuildInteractiveGraph(); } var rect = this.interactionDOMElement.getBoundingClientRect(); - if (AUTO_PREVENT_DEFAULT) { + if (AUTO_PREVENT_DEFAULT) + { event.preventDefault(); } var changedTouches = event.changedTouches; - for (var i=0; i < changedTouches.length; i++) { + for (var i=0; i < changedTouches.length; i++) + { var touchEvent = changedTouches[i]; var touchData = this.pool.pop(); - if (!touchData) { + if (!touchData) + { touchData = new InteractionData(); } @@ -682,7 +766,8 @@ this.touches[touchEvent.identifier] = touchData; touchData.global.x = ( (touchEvent.clientX - rect.left) * (this.interactionDOMElement.width / rect.width) ) / this.resolution; touchData.global.y = ( (touchEvent.clientY - rect.top) * (this.interactionDOMElement.height / rect.height) ) / this.resolution; - if (navigator.isCocoonJS && !rect.left && !rect.top && !event.target.style.width && !event.target.style.height) { + if (navigator.isCocoonJS && !rect.left && !rect.top && !event.target.style.width && !event.target.style.height) + { //Support for CocoonJS fullscreen scale modes touchData.global.x = touchEvent.clientX; touchData.global.y = touchEvent.clientY; @@ -690,15 +775,19 @@ var length = this.interactiveItems.length; - for (var j = 0; j < length; j++) { + for (var j = 0; j < length; j++) + { var item = this.interactiveItems[j]; - if (item.touchstart || item.tap) { + if (item.touchstart || item.tap) + { item.__hit = this.hitTest(item, touchData); - if (item.__hit) { + if (item.__hit) + { //call the function! - if (item.touchstart) { + if (item.touchstart) + { item.touchstart(touchData); } @@ -706,7 +795,8 @@ item.__touchData = item.__touchData || {}; item.__touchData[touchEvent.identifier] = touchData; - if (!item.interactiveChildren) { + if (!item.interactiveChildren) + { break; } } @@ -721,31 +811,37 @@ * @param event {Event} The DOM event of a touch ending on the renderer view * @private */ -InteractionManager.prototype.onTouchEnd = function (event) { - if (this.dirty) { +InteractionManager.prototype.onTouchEnd = function (event) +{ + if (this.dirty) + { this.rebuildInteractiveGraph(); } var rect = this.interactionDOMElement.getBoundingClientRect(); var changedTouches = event.changedTouches; - for (var i=0; i < changedTouches.length; i++) { + for (var i=0; i < changedTouches.length; i++) + { var touchEvent = changedTouches[i]; var touchData = this.touches[touchEvent.identifier]; var up = false; touchData.global.x = ( (touchEvent.clientX - rect.left) * (this.interactionDOMElement.width / rect.width) ) / this.resolution; touchData.global.y = ( (touchEvent.clientY - rect.top) * (this.interactionDOMElement.height / rect.height) ) / this.resolution; - if (navigator.isCocoonJS && !rect.left && !rect.top && !event.target.style.width && !event.target.style.height) { + if (navigator.isCocoonJS && !rect.left && !rect.top && !event.target.style.width && !event.target.style.height) + { //Support for CocoonJS fullscreen scale modes touchData.global.x = touchEvent.clientX; touchData.global.y = touchEvent.clientY; } var length = this.interactiveItems.length; - for (var j = 0; j < length; j++) { + for (var j = 0; j < length; j++) + { var item = this.interactiveItems[j]; - if (item.__touchData && item.__touchData[touchEvent.identifier]) { + if (item.__touchData && item.__touchData[touchEvent.identifier]) + { item.__hit = this.hitTest(item, item.__touchData[touchEvent.identifier]); @@ -753,20 +849,27 @@ touchData.originalEvent = event; // hitTest?? - if (item.touchend || item.tap) { - if (item.__hit && !up) { - if (item.touchend) { + if (item.touchend || item.tap) + { + if (item.__hit && !up) + { + if (item.touchend) + { item.touchend(touchData); } - if (item.__isDown && item.tap) { + if (item.__isDown && item.tap) + { item.tap(touchData); } - if (!item.interactiveChildren) { + if (!item.interactiveChildren) + { up = true; } } - else { - if (item.__isDown && item.touchendoutside) { + else + { + if (item.__isDown && item.touchendoutside) + { item.touchendoutside(touchData); } } diff --git a/src/loaders/AssetLoader.js b/src/loaders/AssetLoader.js index 20da0cf..c4dba1c 100644 --- a/src/loaders/AssetLoader.js +++ b/src/loaders/AssetLoader.js @@ -21,7 +21,8 @@ * data formats include 'xml' and 'fnt'. * @param crossorigin {boolean} Whether requests should be treated as crossorigin */ -function AssetLoader(assetURLs, crossorigin) { +function AssetLoader(assetURLs, crossorigin) +{ /** * The array of asset URLs that are going to be loaded * @@ -76,16 +77,19 @@ * * @param str {string} the name of the asset */ -AssetLoader.prototype._getDataType = function (str) { +AssetLoader.prototype._getDataType = function (str) +{ var test = 'data:'; var start = str.slice(0, test.length).toLowerCase(); - if (start === test) { + if (start === test) + { var data = str.slice(test.length); var sepIdx = data.indexOf(','); // check for malformed data URI scheme - if (sepIdx === -1) { + if (sepIdx === -1) + { return null; } @@ -94,7 +98,8 @@ //We might need to handle some special cases here... //standardize text/plain to 'txt' file extension - if (!info || info.toLowerCase() === 'text/plain') { + if (!info || info.toLowerCase() === 'text/plain') + { return 'txt'; } @@ -109,27 +114,32 @@ * Starts loading the assets sequentially * */ -AssetLoader.prototype.load = function () { +AssetLoader.prototype.load = function () +{ var scope = this; - function onLoad(evt) { + function onLoad(evt) + { scope.onAssetLoaded(evt.data.content); } this.loadCount = this.assetURLs.length; - for (var i=0; i < this.assetURLs.length; i++) { + for (var i=0; i < this.assetURLs.length; i++) + { var fileName = this.assetURLs[i]; //first see if we have a data URI scheme.. var fileType = this._getDataType(fileName); //if not, assume it's a file URI - if (!fileType) { + if (!fileType) + { fileType = fileName.split('?').shift().split('.').pop().toLowerCase(); } var Constructor = this.loadersByType[fileType]; - if (!Constructor) { + if (!Constructor) + { throw new Error(fileType + ' is an unsupported file type'); } @@ -145,18 +155,22 @@ * * @private */ -AssetLoader.prototype.onAssetLoaded = function (loader) { +AssetLoader.prototype.onAssetLoaded = function (loader) +{ this.loadCount--; this.emit('onProgress', { content: this, loader: loader }); - if (this.onProgress) { + if (this.onProgress) + { this.onProgress(loader); } - if (!this.loadCount) { + if (!this.loadCount) + { this.emit('onComplete', { content: this }); - if (this.onComplete) { + if (this.onComplete) + { this.onComplete(); } } diff --git a/src/loaders/AtlasLoader.js b/src/loaders/AtlasLoader.js index 5eda286..3aec9e2 100644 --- a/src/loaders/AtlasLoader.js +++ b/src/loaders/AtlasLoader.js @@ -15,7 +15,8 @@ * @param url {String} The url of the JSON file * @param crossorigin {boolean} Whether requests should be treated as crossorigin */ -function AtlasLoader(url, crossorigin) { +function AtlasLoader(url, crossorigin) +{ this.url = url; this.baseUrl = url.replace(/[^\/]*$/, ''); this.crossorigin = crossorigin; @@ -31,13 +32,15 @@ * Starts loading the JSON file * */ -AtlasLoader.prototype.load = function () { +AtlasLoader.prototype.load = function () +{ this.ajaxRequest = new core.utils.AjaxRequest(); this.ajaxRequest.onreadystatechange = this.onAtlasLoaded.bind(this); this.ajaxRequest.open('GET', this.url, true); - if (this.ajaxRequest.overrideMimeType) { + if (this.ajaxRequest.overrideMimeType) + { this.ajaxRequest.overrideMimeType('application/json'); } @@ -49,9 +52,12 @@ * * @private */ -AtlasLoader.prototype.onAtlasLoaded = function () { - if (this.ajaxRequest.readyState === 4) { - if (this.ajaxRequest.status === 200 || window.location.href.indexOf('http') === -1) { +AtlasLoader.prototype.onAtlasLoaded = function () +{ + if (this.ajaxRequest.readyState === 4) + { + if (this.ajaxRequest.status === 200 || window.location.href.indexOf('http') === -1) + { this.atlas = { meta : { image : [] @@ -70,34 +76,44 @@ selfOnLoaded = this.onLoaded.bind(this); // parser without rotation support yet! - for (i = 0; i < result.length; i++) { + for (i = 0; i < result.length; i++) + { result[i] = result[i].replace(/^\s+|\s+$/g, ''); - if (result[i] === '') { + if (result[i] === '') + { nameInNextLine = i+1; } - if (result[i].length > 0) { - if (nameInNextLine === i) { + if (result[i].length > 0) + { + if (nameInNextLine === i) + { this.atlas.meta.image.push(result[i]); currentImageId = this.atlas.meta.image.length - 1; this.atlas.frames.push({}); lineCount = -3; - } else if (lineCount > 0) { - if (lineCount % 7 === 1) { // frame name - if (currentFrame != null) { //jshint ignore:line + } else if (lineCount > 0) + { + if (lineCount % 7 === 1) + { // frame name + if (currentFrame != null) + { //jshint ignore:line this.atlas.frames[currentImageId][currentFrame.name] = currentFrame; } currentFrame = { name: result[i], frame : {} }; } else { var text = result[i].split(' '); - if (lineCount % 7 === 3) { // position + if (lineCount % 7 === 3) + { // position currentFrame.frame.x = Number(text[1].replace(',', '')); currentFrame.frame.y = Number(text[2]); - } else if (lineCount % 7 === 4) { // size + } else if (lineCount % 7 === 4) + { // size currentFrame.frame.w = Number(text[1].replace(',', '')); currentFrame.frame.h = Number(text[2]); - } else if (lineCount % 7 === 5) { // real size + } else if (lineCount % 7 === 5) + { // real size var realSize = { x : 0, y : 0, @@ -105,7 +121,8 @@ h : Number(text[2]) }; - if (realSize.w > currentFrame.frame.w || realSize.h > currentFrame.frame.h) { + if (realSize.w > currentFrame.frame.w || realSize.h > currentFrame.frame.h) + { currentFrame.trimmed = true; currentFrame.realSize = realSize; } else { @@ -118,28 +135,34 @@ } } - if (currentFrame != null) { //jshint ignore:line + if (currentFrame != null) + { //jshint ignore:line this.atlas.frames[currentImageId][currentFrame.name] = currentFrame; } - if (this.atlas.meta.image.length > 0) { + if (this.atlas.meta.image.length > 0) + { this.images = []; - for (j = 0; j < this.atlas.meta.image.length; j++) { + for (j = 0; j < this.atlas.meta.image.length; j++) + { // sprite sheet var textureUrl = this.baseUrl + this.atlas.meta.image[j]; var frameData = this.atlas.frames[j]; this.images.push(new ImageLoader(textureUrl, this.crossorigin)); - for (i in frameData) { + for (i in frameData) + { var rect = frameData[i].frame; - if (rect) { + if (rect) + { core.utils.TextureCache[i] = new core.Texture(this.images[j].texture.baseTexture, { x: rect.x, y: rect.y, width: rect.w, height: rect.h }); - if (frameData[i].trimmed) { + if (frameData[i].trimmed) + { core.utils.TextureCache[i].realSize = frameData[i].realSize; // trim in pixi not supported yet, todo update trim properties if it is done ... core.utils.TextureCache[i].trim.x = 0; @@ -150,7 +173,8 @@ } this.currentImageId = 0; - for (j = 0; j < this.images.length; j++) { + for (j = 0; j < this.images.length; j++) + { this.images[j].on('loaded', selfOnLoaded); } this.images[this.currentImageId].load(); @@ -170,8 +194,10 @@ * * @private */ -AtlasLoader.prototype.onLoaded = function () { - if (this.images.length - 1 > this.currentImageId) { +AtlasLoader.prototype.onLoaded = function () +{ + if (this.images.length - 1 > this.currentImageId) + { this.currentImageId++; this.images[this.currentImageId].load(); } else { @@ -185,6 +211,7 @@ * * @private */ -AtlasLoader.prototype.onError = function () { +AtlasLoader.prototype.onError = function () +{ this.emit('error', { content: this }); }; diff --git a/src/core/display/DisplayObject.js b/src/core/display/DisplayObject.js index 66ebc3c..20e778c 100644 --- a/src/core/display/DisplayObject.js +++ b/src/core/display/DisplayObject.js @@ -7,7 +7,8 @@ * @class * @namespace PIXI */ -function DisplayObject() { +function DisplayObject() +{ /** * The coordinate of the object relative to the local coordinates of the parent. * @@ -152,10 +153,12 @@ * @memberof DisplayObject# */ x: { - get: function () { + get: function () + { return this.position.x; }, - set: function (value) { + set: function (value) + { this.position.x = value; } }, @@ -167,10 +170,12 @@ * @memberof DisplayObject# */ y: { - get: function () { + get: function () + { return this.position.y; }, - set: function (value) { + set: function (value) + { this.position.y = value; } }, @@ -183,11 +188,13 @@ * @readonly */ worldVisible: { - get: function () { + get: function () + { var item = this; do { - if (!item.visible) { + if (!item.visible) + { return false; } @@ -207,17 +214,21 @@ * @memberof DisplayObject# */ mask: { - get: function () { + get: function () + { return this._mask; }, - set: function (value) { - if (this._mask) { + set: function (value) + { + if (this._mask) + { this._mask.isMask = false; } this._mask = value; - if (this._mask) { + if (this._mask) + { this._mask.isMask = true; } } @@ -232,18 +243,23 @@ * @memberof DisplayObject# */ filters: { - get: function () { + get: function () + { return this._filters; }, - set: function (value) { - if (value) { + set: function (value) + { + if (value) + { // now put all the passes in one place.. var passes = []; - for (var i = 0; i < value.length; i++) { + for (var i = 0; i < value.length; i++) + { var filterPasses = value[i].passes; - for (var j = 0; j < filterPasses.length; j++) { + for (var j = 0; j < filterPasses.length; j++) + { passes.push(filterPasses[j]); } } @@ -264,8 +280,9 @@ * * @private */ -DisplayObject.prototype.updateTransform = function () { - +DisplayObject.prototype.updateTransform = function () +{ + // create some matrix refs for easy access var pt = this.parent.worldTransform; var wt = this.worldTransform; @@ -274,9 +291,11 @@ var a, b, c, d, tx, ty; // so if rotation is between 0 then we can simplify the multiplication process.. - if (this.rotation % math.PI_2) { + if (this.rotation % math.PI_2) + { // 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) { + if (this.rotation !== this.rotationCache) + { this.rotationCache = this.rotation; this._sr = Math.sin(this.rotation); this._cr = Math.cos(this.rotation); @@ -291,7 +310,8 @@ ty = this.position.y; // check for pivot.. not often used so geared towards that fact! - if (this.pivot.x || this.pivot.y) { + 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; } @@ -304,7 +324,8 @@ wt.tx = tx * pt.a + ty * pt.c + pt.tx; wt.ty = tx * pt.b + ty * pt.d + pt.ty; } - else { + else + { // lets do the fast version as we know there is no rotation.. a = this.scale.x; d = this.scale.y; @@ -333,7 +354,8 @@ * @param matrix {Matrix} * @return {Rectangle} the rectangular bounding area */ -DisplayObject.prototype.getBounds = function (/* matrix */) { +DisplayObject.prototype.getBounds = function (/* matrix */) +{ return math.Rectangle.EMPTY; }; @@ -342,7 +364,8 @@ * * @return {Rectangle} the rectangular bounding area */ -DisplayObject.prototype.getLocalBounds = function () { +DisplayObject.prototype.getLocalBounds = function () +{ return this.getBounds(math.Matrix.IDENTITY); }; @@ -352,7 +375,8 @@ * @param position {Point} The world origin to calculate from * @return {Point} A point object representing the position of this object */ -DisplayObject.prototype.toGlobal = function (position) { +DisplayObject.prototype.toGlobal = function (position) +{ // don't need to u[date the lot this.displayObjectUpdateTransform(); return this.worldTransform.apply(position); @@ -365,8 +389,10 @@ * @param [from] {DisplayObject} The DisplayObject to calculate the global position from * @return {Point} A point object representing the position of this object */ -DisplayObject.prototype.toLocal = function (position, from) { - if (from) { +DisplayObject.prototype.toLocal = function (position, from) +{ + if (from) + { position = from.toGlobal(position); } @@ -381,7 +407,8 @@ * @param renderer {WebGLRenderer} The renderer * @private */ -DisplayObject.prototype.renderWebGL = function (/* renderer */) { +DisplayObject.prototype.renderWebGL = function (/* renderer */) +{ // OVERWRITE; }; @@ -391,6 +418,7 @@ * @param renderer {CanvasRenderer} The renderer * @private */ -DisplayObject.prototype.renderCanvas = function (/* renderer */) { +DisplayObject.prototype.renderCanvas = function (/* renderer */) +{ // OVERWRITE; }; diff --git a/src/core/display/DisplayObjectContainer.js b/src/core/display/DisplayObjectContainer.js index 689f40b..4625ee8 100644 --- a/src/core/display/DisplayObjectContainer.js +++ b/src/core/display/DisplayObjectContainer.js @@ -12,7 +12,8 @@ * @extends DisplayObject * @namespace PIXI */ -function DisplayObjectContainer() { +function DisplayObjectContainer() +{ DisplayObject.call(this); /** @@ -47,17 +48,21 @@ * @memberof DisplayObjectContainer# */ width: { - get: function () { + get: function () + { return this.scale.x * this.getLocalBounds().width; }, - set: function (value) { + set: function (value) + { var width = this.getLocalBounds().width; - if(width !== 0) { + if(width !== 0) + { this.scale.x = value / width; } - else { + else + { this.scale.x = 1; } @@ -73,17 +78,21 @@ * @memberof DisplayObjectContainer# */ height: { - get: function () { + get: function () + { return this.scale.y * this.getLocalBounds().height; }, - set: function (value) { + set: function (value) + { var height = this.getLocalBounds().height; - if (height !== 0) { + if (height !== 0) + { this.scale.y = value / height ; } - else { + else + { this.scale.y = 1; } @@ -100,18 +109,23 @@ * @memberof DisplayObject# */ cacheAsBitmap: { - get: function () { + get: function () + { return this._cacheAsBitmap; }, - set: function (value) { - if (this._cacheAsBitmap === value) { + set: function (value) + { + if (this._cacheAsBitmap === value) + { return; } - if (value) { + if (value) + { this._generateCachedSprite(); } - else { + else + { this._destroyCachedSprite(); } @@ -126,7 +140,8 @@ * @param child {DisplayObject} The DisplayObject to add to the container * @return {DisplayObject} The child that was added. */ -DisplayObjectContainer.prototype.addChild = function (child) { +DisplayObjectContainer.prototype.addChild = function (child) +{ return this.addChildAt(child, this.children.length); }; @@ -137,14 +152,18 @@ * @param index {Number} The index to place the child in * @return {DisplayObject} The child that was added. */ -DisplayObjectContainer.prototype.addChildAt = function (child, index) { +DisplayObjectContainer.prototype.addChildAt = function (child, index) +{ // prevent adding self as child - if (child === this) { + if (child === this) + { return; } - if (index >= 0 && index <= this.children.length) { - if (child.parent) { + if (index >= 0 && index <= this.children.length) + { + if (child.parent) + { child.parent.removeChild(child); } @@ -154,7 +173,8 @@ return child; } - else { + else + { throw new Error(child + 'addChildAt: The index '+ index +' supplied is out of bounds ' + this.children.length); } }; @@ -165,15 +185,18 @@ * @param child {DisplayObject} * @param child2 {DisplayObject} */ -DisplayObjectContainer.prototype.swapChildren = function (child, child2) { - if (child === child2) { +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) { + if (index1 < 0 || index2 < 0) + { throw new Error('swapChildren: Both the supplied DisplayObjects must be a child of the caller.'); } @@ -187,10 +210,12 @@ * @param child {DisplayObject} The DisplayObject instance to identify * @return {Number} The index position of the child display object to identify */ -DisplayObjectContainer.prototype.getChildIndex = function (child) { +DisplayObjectContainer.prototype.getChildIndex = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { throw new Error('The supplied DisplayObject must be a child of the caller'); } @@ -203,8 +228,10 @@ * @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 */ -DisplayObjectContainer.prototype.setChildIndex = function (child, index) { - if (index < 0 || index >= this.children.length) { +DisplayObjectContainer.prototype.setChildIndex = function (child, index) +{ + if (index < 0 || index >= this.children.length) + { throw new Error('The supplied index is out of bounds'); } @@ -220,8 +247,10 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child at the given index, if any. */ -DisplayObjectContainer.prototype.getChildAt = function (index) { - if (index < 0 || index >= this.children.length) { +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'); } @@ -234,10 +263,12 @@ * @param child {DisplayObject} The DisplayObject to remove * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChild = function (child) { +DisplayObjectContainer.prototype.removeChild = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { return; } @@ -250,7 +281,8 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChildAt = function (index) { +DisplayObjectContainer.prototype.removeChildAt = function (index) +{ var child = this.getChildAt(index); child.parent = null; @@ -265,24 +297,29 @@ * @param beginIndex {Number} The beginning position. Default value is 0. * @param endIndex {Number} The ending position. Default value is size of the container. */ -DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) { +DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) +{ var begin = beginIndex || 0; var end = typeof endIndex === 'number' ? endIndex : this.children.length; var range = end - begin; - if (range > 0 && range <= end) { + if (range > 0 && range <= end) + { var removed = this.children.splice(begin, range); - for (var i = 0; i < removed.length; ++i) { + for (var i = 0; i < removed.length; ++i) + { removed[i].parent = null; } return removed; } - else if (range === 0 && this.children.length === 0) { + else if (range === 0 && this.children.length === 0) + { return []; } - else { + else + { throw new RangeError('removeChildren: numeric values are outside the acceptable range.'); } }; @@ -291,7 +328,8 @@ * Generates and updates the cached sprite for this object. * */ -DisplayObjectContainer.prototype.updateCachedSprite = function () { +DisplayObjectContainer.prototype.updateCachedSprite = function () +{ this._generateCachedSprite(); }; @@ -304,7 +342,8 @@ * @param renderer {CanvasRenderer|WebGLRenderer} The renderer used to generate the texture. * @return {Texture} a texture of the graphics object */ -DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) { +DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) +{ var bounds = this.getLocalBounds(); var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0, renderer, scaleMode, resolution); @@ -322,18 +361,22 @@ * * @private */ -DisplayObjectContainer.prototype.updateTransform = function () { - if (!this.visible) { +DisplayObjectContainer.prototype.updateTransform = function () +{ + if (!this.visible) + { return; } this.displayObjectUpdateTransform(); - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { return; } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } }; @@ -346,8 +389,10 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getBounds = function () { - if (this.children.length === 0) { +DisplayObjectContainer.prototype.getBounds = function () +{ + if (this.children.length === 0) + { return math.Rectangle.EMPTY; } @@ -365,10 +410,12 @@ var childVisible = false; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -386,7 +433,8 @@ maxY = maxY > childMaxY ? maxY : childMaxY; } - if (!childVisible) { + if (!childVisible) + { return math.Rectangle.EMPTY; } @@ -407,12 +455,14 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getLocalBounds = function () { +DisplayObjectContainer.prototype.getLocalBounds = function () +{ var matrixCache = this.worldTransform; this.worldTransform = math.Matrix.IDENTITY; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } @@ -428,13 +478,16 @@ * * @param renderer {WebGLRenderer} The renderer */ -DisplayObjectContainer.prototype.renderWebGL = function (renderer) { +DisplayObjectContainer.prototype.renderWebGL = function (renderer) +{ // if the object is not visible or the alpha is 0 then no need to render this element - if (!this.visible || this.alpha <= 0) { + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } @@ -442,14 +495,17 @@ var i, j; // do a quick check to see if this element has a mask or a filter. - if (this._mask || this._filters) { + if (this._mask || this._filters) + { // push filter first as we need to ensure the stencil buffer is correct for any masking - if (this._filters) { + if (this._filters) + { renderer.spriteBatch.flush(); renderer.filterManager.pushFilter(this._filterBlock); } - if (this._mask) { + if (this._mask) + { renderer.spriteBatch.stop(); renderer.maskManager.pushMask(this.mask, renderer); renderer.spriteBatch.start(); @@ -459,36 +515,42 @@ this._renderWebGL(renderer); // now loop through the children and make sure they get rendered - for (i = 0, j = this.children.length; i < j; i++) { + for (i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderWebGL(renderer); } // time to stop the sprite batch as either a mask element or a filter draw will happen next renderer.spriteBatch.stop(); - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(this._mask, renderer); } - if (this._filters) { + if (this._filters) + { renderer.filterManager.popFilter(); } renderer.spriteBatch.start(); } - else { + else + { this._renderWebGL(renderer); // simple render children! - for (i = 0, j = this.children.length; i < j; ++i) { + for (i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderWebGL(renderer); } } }; -DisplayObjectContainer.prototype._renderWebGL = function (renderer) { +DisplayObjectContainer.prototype._renderWebGL = function (renderer) +{ // this is where content itself gets renderd.. @@ -499,25 +561,31 @@ * * @param renderer {CanvasRenderer} The renderer */ -DisplayObjectContainer.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0) { +DisplayObjectContainer.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -528,13 +596,16 @@ * @param renderer {WebGLRenderer|CanvasRenderer} The renderer * @private */ -DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) { +DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) +{ this._cachedSprite.worldAlpha = this.worldAlpha; - if (renderer.gl) { + if (renderer.gl) + { this._cachedSprite.renderWebGL(renderer); } - else { + else + { this._cachedSprite.renderCanvas(renderer); } }; @@ -544,10 +615,12 @@ * * @private */ -DisplayObjectContainer.prototype._generateCachedSprite = function () { +DisplayObjectContainer.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { // TODO - RenderTexture now *requires* a renderer instance, so this is like broken // because `renderer` isn't actually in scope here :P var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0); @@ -555,7 +628,8 @@ this._cachedSprite = new Sprite(renderTexture); this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.texture.resize(bounds.width | 0, bounds.height | 0); } @@ -580,8 +654,10 @@ * * @private */ -DisplayObjectContainer.prototype._destroyCachedSprite = function () { - if (!this._cachedSprite) { +DisplayObjectContainer.prototype._destroyCachedSprite = function () +{ + if (!this._cachedSprite) + { return; } diff --git a/src/core/display/Sprite.js b/src/core/display/Sprite.js index 707da24..5862aef 100644 --- a/src/core/display/Sprite.js +++ b/src/core/display/Sprite.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param texture {Texture} The texture for this sprite */ -function Sprite(texture) { +function Sprite(texture) +{ DisplayObjectContainer.call(this); /** @@ -85,12 +86,14 @@ this.texture = texture || Texture.EMPTY; } -Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) { +Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) +{ DisplayObjectContainer.prototype.destroy.call(this); this.anchor = null; - if (destroyTexture) { + if (destroyTexture) + { this._texture.destroy(destroyBaseTexture); } @@ -111,10 +114,12 @@ * @memberof Sprite# */ width: { - get: function () { + get: function () + { return this.scale.x * this.texture.frame.width; }, - set: function (value) { + set: function (value) + { this.scale.x = value / this.texture.frame.width; this._width = value; } @@ -127,10 +132,12 @@ * @memberof Sprite# */ height: { - get: function () { + get: function () + { return this.scale.y * this.texture.frame.height; }, - set: function (value) { + set: function (value) + { this.scale.y = value / this.texture.frame.height; this._height = value; } @@ -143,23 +150,29 @@ * @memberof Sprite# */ texture: { - get: function () { + get: function () + { return this._texture; }, - set: function (value) { - if (this._texture === value) { + set: function (value) + { + if (this._texture === value) + { return; } this._texture = value; this.cachedTint = 0xFFFFFF; - if (value) { + if (value) + { // wait for the texture to load - if (value.baseTexture.hasLoaded) { + if (value.baseTexture.hasLoaded) + { this._onTextureUpdate(); } - else { + else + { value.once('update', this._onTextureUpdate.bind(this)); } } @@ -172,18 +185,22 @@ * * @private */ -Sprite.prototype._onTextureUpdate = function () { +Sprite.prototype._onTextureUpdate = function () +{ // so if _width is 0 then width was not set.. - if (this._width) { + if (this._width) + { this.scale.x = this._width / this.texture.frame.width; } - if (this._height) { + if (this._height) + { this.scale.y = this._height / this.texture.frame.height; } }; -Sprite.prototype._renderWebGL = function (renderer) { +Sprite.prototype._renderWebGL = function (renderer) +{ // this is where content gets renderd.. // watch this space for a little render state manager.. @@ -197,7 +214,8 @@ * @param matrix {Matrix} the transformation matrix of the sprite * @return {Rectangle} the framing rectangle */ -Sprite.prototype.getBounds = function (matrix) { +Sprite.prototype.getBounds = function (matrix) +{ var width = this.texture.frame.width; var height = this.texture.frame.height; @@ -224,11 +242,13 @@ if(b === 0 && c === 0) { // scale may be negative! - if (a < 0) { + if (a < 0) + { a *= -1; } - if (d < 0) { + if (d < 0) + { d *= -1; } @@ -293,28 +313,34 @@ * * @param renderer {CanvasRenderer} The renderer */ -Sprite.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) { +Sprite.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) + { return; } - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; renderer.context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } // Ignore null sources - if (this.texture.valid) { + if (this.texture.valid) + { var resolution = this.texture.baseTexture.resolution / renderer.resolution; renderer.context.globalAlpha = this.worldAlpha; // If smoothingEnabled is supported and we need to change the smoothing property for this texture - if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) { + if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) + { renderer.scaleMode = this.texture.baseTexture.scaleMode; renderer.context[renderer.smoothProperty] = (renderer.scaleMode === CONST.scaleModes.LINEAR); } @@ -324,7 +350,8 @@ var dy = (this.texture.trim ? this.texture.trim.y : 0) - (this.anchor.y * this.texture.trim.height); // Allow for pixel rounding - if (renderer.roundPixels) { + if (renderer.roundPixels) + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -337,7 +364,8 @@ dx = dx | 0; dy = dy | 0; } - else { + else + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -348,8 +376,10 @@ ); } - if (this.tint !== 0xFFFFFF) { - if (this.cachedTint !== this.tint) { + if (this.tint !== 0xFFFFFF) + { + if (this.cachedTint !== this.tint) + { this.cachedTint = this.tint; // TODO clean up caching - how to clean up the caches? @@ -368,7 +398,8 @@ this.texture.crop.height / resolution ); } - else { + else + { renderer.context.drawImage( this.texture.baseTexture.source, this.texture.crop.x, @@ -383,11 +414,13 @@ } } - for (var i = 0, j = this.children.length; i < j; i++) { + for (var i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -402,10 +435,12 @@ * @param frameId {String} The frame Id of the texture in the cache * @return {Sprite} A new Sprite using a texture from the texture cache matching the frameId */ -Sprite.fromFrame = function (frameId) { +Sprite.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache' + this); } @@ -420,6 +455,7 @@ * @param imageId {String} The image url of the texture * @return {Sprite} A new Sprite using a texture from the texture cache matching the image id */ -Sprite.fromImage = function (imageId, crossorigin, scaleMode) { +Sprite.fromImage = function (imageId, crossorigin, scaleMode) +{ return new Sprite(Texture.fromImage(imageId, crossorigin, scaleMode)); }; diff --git a/src/core/display/SpriteBatch.js b/src/core/display/SpriteBatch.js index 3187777..c196fef 100644 --- a/src/core/display/SpriteBatch.js +++ b/src/core/display/SpriteBatch.js @@ -12,7 +12,8 @@ * ```js * var container = new SpriteBatch(); * - * for(var i = 0; i < 100; ++i) { + * for(var i = 0; i < 100; ++i) + * { * var sprite = new PIXI.Sprite.fromImage("myImage.png"); * container.addChild(sprite); * } @@ -25,7 +26,8 @@ */ //TODO RENAME to PARTICLE CONTAINER? -function SpriteBatch() { +function SpriteBatch() +{ DisplayObjectContainer.call(this); } @@ -38,7 +40,8 @@ * * @private */ -SpriteBatch.prototype.updateTransform = function () { +SpriteBatch.prototype.updateTransform = function () +{ // TODO don't need to! this.displayObjectUpdateTransform(); // PIXI.DisplayObjectContainer.prototype.updateTransform.call( this ); @@ -50,8 +53,10 @@ * @param renderer {WebGLRenderer} The webgl renderer * @private */ -SpriteBatch.prototype.renderWebGL = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderWebGL = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -71,8 +76,10 @@ * @param renderer {CanvasRenderer} The canvas renderer * @private */ -SpriteBatch.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -84,10 +91,12 @@ this.displayObjectUpdateTransform(); - for (var i = 0; i < this.children.length; ++i) { + for (var i = 0; i < this.children.length; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -95,9 +104,11 @@ context.globalAlpha = this.worldAlpha * child.alpha; - if (child.rotation % (Math.PI * 2) === 0) { + if (child.rotation % (Math.PI * 2) === 0) + { // this is the fastest way to optimise! - if rotation is 0 then we can avoid any kind of setTransform call - if (isRotated) { + if (isRotated) + { context.setTransform( transform.a, transform.b, @@ -122,8 +133,10 @@ frame.height * child.scale.y ); } - else { - if (!isRotated) { + else + { + if (!isRotated) + { isRotated = true; } @@ -131,7 +144,8 @@ var childTransform = child.worldTransform; - if (renderer.roundPixels) { + if (renderer.roundPixels) + { context.setTransform( childTransform.a, childTransform.b, @@ -141,7 +155,8 @@ childTransform.ty | 0 ); } - else { + else + { context.setTransform( childTransform.a, childTransform.b, diff --git a/src/core/index.js b/src/core/index.js index 3954b6f..eb4a82b 100644 --- a/src/core/index.js +++ b/src/core/index.js @@ -58,11 +58,13 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRenderer: function (width, height, options, noWebGL) { + autoDetectRenderer: function (width, height, options, noWebGL) + { width = width || 800; height = height || 600; - if (!noWebGL && require('webgl-enabled')()) { + if (!noWebGL && require('webgl-enabled')()) + { return new core.WebGLRenderer(width, height, options); } @@ -87,7 +89,8 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRecommendedRenderer: function (width, height, options) { + autoDetectRecommendedRenderer: function (width, height, options) + { var isAndroid = /Android/i.test(navigator.userAgent); return core.autoDetectRenderer(width, height, options, isAndroid); diff --git a/src/core/math/Matrix.js b/src/core/math/Matrix.js index c2f87e2..2ff4848 100644 --- a/src/core/math/Matrix.js +++ b/src/core/math/Matrix.js @@ -10,7 +10,8 @@ * @class * @namespace PIXI */ -function Matrix() { +function Matrix() +{ /** * @member {number} * @default 1 @@ -63,7 +64,8 @@ * * @param array {number[]} The array that the matrix will be populated from. */ -Matrix.prototype.fromArray = function (array) { +Matrix.prototype.fromArray = function (array) +{ this.a = array[0]; this.b = array[1]; this.c = array[3]; @@ -78,14 +80,17 @@ * @param transpose {boolean} Whether we need to transpose the matrix or not * @return {number[]} the newly created array which contains the matrix */ -Matrix.prototype.toArray = function (transpose) { - if (!this.array) { +Matrix.prototype.toArray = function (transpose) +{ + if (!this.array) + { this.array = new Float32Array(9); } var array = this.array; - if (transpose) { + if (transpose) + { array[0] = this.a; array[1] = this.b; array[2] = 0; @@ -96,7 +101,8 @@ array[7] = this.ty; array[8] = 1; } - else { + else + { array[0] = this.a; array[1] = this.c; array[2] = this.tx; @@ -119,7 +125,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, transformed through this matrix */ -Matrix.prototype.apply = function (pos, newPos) { +Matrix.prototype.apply = function (pos, newPos) +{ newPos = newPos || new Point(); newPos.x = this.a * pos.x + this.c * pos.y + this.tx; @@ -136,7 +143,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, inverse-transformed through this matrix */ -Matrix.prototype.applyInverse = function (pos, newPos) { +Matrix.prototype.applyInverse = function (pos, newPos) +{ newPos = newPos || new Point(); var id = 1 / (this.a * this.d + this.c * -this.b); @@ -154,7 +162,8 @@ * @param {number} y * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.translate = function (x, y) { +Matrix.prototype.translate = function (x, y) +{ this.tx += x; this.ty += y; @@ -168,7 +177,8 @@ * @param {number} y The amount to scale vertically * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.scale = function (x, y) { +Matrix.prototype.scale = function (x, y) +{ this.a *= x; this.d *= y; this.c *= x; @@ -186,7 +196,8 @@ * @param {number} angle - The angle in radians. * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.rotate = function (angle) { +Matrix.prototype.rotate = function (angle) +{ var cos = Math.cos( angle ); var sin = Math.sin( angle ); @@ -210,7 +221,8 @@ * @param {Matrix} matrix * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.append = function (matrix) { +Matrix.prototype.append = function (matrix) +{ var a1 = this.a; var b1 = this.b; var c1 = this.c; @@ -232,7 +244,8 @@ * * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.identity = function () { +Matrix.prototype.identity = function () +{ this.a = 1; this.b = 0; this.c = 0; diff --git a/src/core/math/Point.js b/src/core/math/Point.js index 7565b2d..632f346 100644 --- a/src/core/math/Point.js +++ b/src/core/math/Point.js @@ -7,7 +7,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -function Point(x, y) { +function Point(x, y) +{ /** * @member {number} * @default 0 @@ -29,7 +30,8 @@ * * @return {Point} a copy of the point */ -Point.prototype.clone = function () { +Point.prototype.clone = function () +{ return new Point(this.x, this.y); }; @@ -40,7 +42,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -Point.prototype.set = function (x, y) { +Point.prototype.set = function (x, y) +{ this.x = x || 0; this.y = y || ( (y !== 0) ? this.x : 0 ) ; }; diff --git a/src/core/math/shapes/Circle.js b/src/core/math/shapes/Circle.js index 69cfdc9..4d76efc 100644 --- a/src/core/math/shapes/Circle.js +++ b/src/core/math/shapes/Circle.js @@ -10,7 +10,8 @@ * @param y {number} The Y coordinate of the center of this circle * @param radius {number} The radius of the circle */ -function Circle(x, y, radius) { +function Circle(x, y, radius) +{ /** * @member {number} * @default 0 @@ -46,7 +47,8 @@ * @method clone * @return {Circle} a copy of the Circle */ -Circle.prototype.clone = function () { +Circle.prototype.clone = function () +{ return new Circle(this.x, this.y, this.radius); }; @@ -58,8 +60,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Circle */ -Circle.prototype.contains = function (x, y) { - if (this.radius <= 0) { +Circle.prototype.contains = function (x, y) +{ + if (this.radius <= 0) + { return false; } @@ -79,6 +83,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Circle.prototype.getBounds = function () { +Circle.prototype.getBounds = function () +{ return new Rectangle(this.x - this.radius, this.y - this.radius, this.radius * 2, this.radius * 2); }; diff --git a/src/core/math/shapes/Ellipse.js b/src/core/math/shapes/Ellipse.js index 4f2d066..fefd01a 100644 --- a/src/core/math/shapes/Ellipse.js +++ b/src/core/math/shapes/Ellipse.js @@ -11,7 +11,8 @@ * @param width {number} The half width of this ellipse * @param height {number} The half height of this ellipse */ -function Ellipse(x, y, width, height) { +function Ellipse(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -53,7 +54,8 @@ * @method clone * @return {Ellipse} a copy of the ellipse */ -Ellipse.prototype.clone = function () { +Ellipse.prototype.clone = function () +{ return new Ellipse(this.x, this.y, this.width, this.height); }; @@ -65,8 +67,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coords are within this ellipse */ -Ellipse.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Ellipse.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } @@ -86,6 +90,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Ellipse.prototype.getBounds = function () { +Ellipse.prototype.getBounds = function () +{ return new Rectangle(this.x - this.width, this.y - this.height, this.width, this.height); }; diff --git a/src/core/math/shapes/Polygon.js b/src/core/math/shapes/Polygon.js index ae89148..fea6d37 100644 --- a/src/core/math/shapes/Polygon.js +++ b/src/core/math/shapes/Polygon.js @@ -10,16 +10,20 @@ * arguments passed can be flat x,y values e.g. `new Polygon(x,y, x,y, x,y, ...)` where `x` and `y` are * Numbers. */ -function Polygon(points) { +function Polygon(points) +{ //if points isn't an array, use arguments as the array - if (!(points instanceof Array)) { + if (!(points instanceof Array)) + { points = Array.prototype.slice.call(arguments); } //if this is a flat array of numbers, convert it to points - if (points[0] instanceof Point) { + if (points[0] instanceof Point) + { var p = []; - for (var i = 0, il = points.length; i < il; i++) { + for (var i = 0, il = points.length; i < il; i++) + { p.push(points[i].x, points[i].y); } @@ -51,7 +55,8 @@ * * @return {Polygon} a copy of the polygon */ -Polygon.prototype.clone = function () { +Polygon.prototype.clone = function () +{ return new Polygon(this.points.slice()); }; @@ -62,19 +67,22 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this polygon */ -Polygon.prototype.contains = function (x, y) { +Polygon.prototype.contains = function (x, y) +{ var inside = false; // use some raycasting to test hits // https://github.com/substack/point-in-polygon/blob/master/index.js var length = this.points.length / 2; - for (var i = 0, j = length - 1; i < length; j = i++) { + for (var i = 0, j = length - 1; i < length; j = i++) + { var xi = this.points[i * 2], yi = this.points[i * 2 + 1], xj = this.points[j * 2], yj = this.points[j * 2 + 1], intersect = ((yi > y) !== (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi); - if (intersect) { + if (intersect) + { inside = !inside; } } diff --git a/src/core/math/shapes/Rectangle.js b/src/core/math/shapes/Rectangle.js index 16ac62a..4008b68 100644 --- a/src/core/math/shapes/Rectangle.js +++ b/src/core/math/shapes/Rectangle.js @@ -10,7 +10,8 @@ * @param width {number} The overall width of this rectangle * @param height {number} The overall height of this rectangle */ -function Rectangle(x, y, width, height) { +function Rectangle(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -60,7 +61,8 @@ * * @return {Rectangle} a copy of the rectangle */ -Rectangle.prototype.clone = function () { +Rectangle.prototype.clone = function () +{ return new Rectangle(this.x, this.y, this.width, this.height); }; @@ -71,13 +73,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rectangle */ -Rectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Rectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/math/shapes/RoundedRectangle.js b/src/core/math/shapes/RoundedRectangle.js index 27d286e..7bf6411 100644 --- a/src/core/math/shapes/RoundedRectangle.js +++ b/src/core/math/shapes/RoundedRectangle.js @@ -11,7 +11,8 @@ * @param height {number} The overall height of this rounded rectangle * @param radius {number} Controls the radius of the rounded corners */ -function RoundedRectangle(x, y, width, height, radius) { +function RoundedRectangle(x, y, width, height, radius) +{ /** * @member {number} * @default 0 @@ -58,7 +59,8 @@ * * @return {RoundedRectangle} a copy of the rounded rectangle */ -RoundedRectangle.prototype.clone = function () { +RoundedRectangle.prototype.clone = function () +{ return new RoundedRectangle(this.x, this.y, this.width, this.height, this.radius); }; @@ -69,13 +71,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rounded Rectangle */ -RoundedRectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +RoundedRectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/primitives/Graphics.js b/src/core/primitives/Graphics.js index 261c534..e902d2a 100644 --- a/src/core/primitives/Graphics.js +++ b/src/core/primitives/Graphics.js @@ -16,7 +16,8 @@ * @extends DisplayObjectContainer * @namespace PIXI */ -function Graphics() { +function Graphics() +{ DisplayObjectContainer.call(this); this.renderable = true; @@ -154,16 +155,20 @@ * @private */ cacheAsBitmap: { - get: function () { + get: function () + { return this._cacheAsBitmap; }, - set: function (value) { + set: function (value) + { this._cacheAsBitmap = value; - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._generateCachedSprite(); } - else { + else + { this.destroyCachedSprite(); this.dirty = true; } @@ -176,7 +181,8 @@ * * @return {Graphics} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ var clone = new Graphics(); clone.renderable = this.renderable; @@ -192,7 +198,8 @@ clone.cachedSpriteDirty = this.cachedSpriteDirty; // copy graphics data - for (var i = 0; i < this.graphicsData.length; ++i) { + for (var i = 0; i < this.graphicsData.length; ++i) + { clone.graphicsData.push(this.graphicsData.clone()); } @@ -211,17 +218,21 @@ * @param alpha {number} alpha of the line to draw, will update the objects stored style * @return {Graphics} */ -Graphics.prototype.lineStyle = function (lineWidth, color, alpha) { +Graphics.prototype.lineStyle = function (lineWidth, color, alpha) +{ this.lineWidth = lineWidth || 0; this.lineColor = color || 0; this.lineAlpha = (arguments.length < 3) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length) + { // halfway through a line? start a new one! this.drawShape( new math.Polygon( this.currentPath.shape.points.slice(-2) )); } - else { + else + { // otherwise its empty so lets just set the line properties this.currentPath.lineWidth = this.lineWidth; this.currentPath.lineColor = this.lineColor; @@ -239,7 +250,8 @@ * @param y {number} the Y coordinate to move to * @return {Graphics} */ -Graphics.prototype.moveTo = function (x, y) { +Graphics.prototype.moveTo = function (x, y) +{ this.drawShape(new math.Polygon([x,y])); return this; @@ -253,7 +265,8 @@ * @param y {number} the Y coordinate to draw to * @return {Graphics} */ -Graphics.prototype.lineTo = function (x, y) { +Graphics.prototype.lineTo = function (x, y) +{ this.currentPath.shape.points.push(x, y); this.dirty = true; @@ -270,13 +283,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -285,7 +302,8 @@ n = 20, points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { this.moveTo(0, 0); } @@ -293,7 +311,8 @@ var fromY = points[points.length-1]; var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; xa = fromX + ( (cpX - fromX) * j ); @@ -319,13 +338,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -342,7 +365,8 @@ var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; dt = (1 - j); @@ -373,13 +397,17 @@ * @param radius {number} The radius of the arc * @return {Graphics} */ -Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points.push(x1, y1); } } - else { + else + { this.moveTo(x1, y1); } @@ -392,12 +420,15 @@ b2 = x2 - x1, mm = Math.abs(a1 * b2 - b1 * a2); - if (mm < 1.0e-8 || radius === 0) { - if (points[points.length-2] !== x1 || points[points.length-1] !== y1) { + if (mm < 1.0e-8 || radius === 0) + { + if (points[points.length-2] !== x1 || points[points.length-1] !== y1) + { points.push(x1, y1); } } - else { + else + { var dd = a1 * a1 + b1 * b1, cc = a2 * a2 + b2 * b2, tt = a1 * a2 + b1 * b2, @@ -433,42 +464,51 @@ * @param anticlockwise {boolean} Optional. Specifies whether the drawing should be counterclockwise or clockwise. False is default, and indicates clockwise, while true indicates counter-clockwise. * @return {Graphics} */ -Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) { +Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) +{ var startX = cx + Math.cos(startAngle) * radius; var startY = cy + Math.sin(startAngle) * radius; var points; // TODO - This if-else makes no sense. It uses currentPath in the else where it doesn't exist... - if (this.currentPath) { + if (this.currentPath) + { points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { points.push(startX, startY); } - else if (points[points.length-2] !== startX || points[points.length-1] !== startY) { + else if (points[points.length-2] !== startX || points[points.length-1] !== startY) + { points.push(startX, startY); } } - else { + else + { this.moveTo(startX, startY); points = this.currentPath.shape.points; } - if (startAngle === endAngle) { + if (startAngle === endAngle) + { return this; } - if (!anticlockwise && endAngle <= startAngle) { + if (!anticlockwise && endAngle <= startAngle) + { endAngle += Math.PI * 2; } - else if (anticlockwise && startAngle <= endAngle) { + else if (anticlockwise && startAngle <= endAngle) + { startAngle += Math.PI * 2; } var sweep = anticlockwise ? (startAngle - endAngle) *-1 : (endAngle - startAngle); var segs = (Math.abs(sweep)/ (Math.PI * 2)) * 40; - if (sweep === 0) { + if (sweep === 0) + { return this; } @@ -482,7 +522,8 @@ var remainder = ( segMinus % 1 ) / segMinus; - for (var i = 0; i <= segMinus; ++i) { + for (var i = 0; i <= segMinus; ++i) + { var real = i + remainder * i; var angle = ((theta) + startAngle + (theta2 * real)); @@ -506,13 +547,16 @@ * @param alpha {number} the alpha of the fill * @return {Graphics} */ -Graphics.prototype.beginFill = function (color, alpha) { +Graphics.prototype.beginFill = function (color, alpha) +{ this.filling = true; this.fillColor = color || 0; this.fillAlpha = (alpha === undefined) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length <= 2) + { this.currentPath.fill = this.filling; this.currentPath.fillColor = this.fillColor; this.currentPath.fillAlpha = this.fillAlpha; @@ -526,7 +570,8 @@ * * @return {Graphics} */ -Graphics.prototype.endFill = function () { +Graphics.prototype.endFill = function () +{ this.filling = false; this.fillColor = null; this.fillAlpha = 1; @@ -542,7 +587,8 @@ * @param height {number} The height of the rectangle * @return {Graphics} */ -Graphics.prototype.drawRect = function ( x, y, width, height ) { +Graphics.prototype.drawRect = function ( x, y, width, height ) +{ this.drawShape(new math.Rectangle(x,y, width, height)); return this; @@ -556,7 +602,8 @@ * @param height {number} The height of the rectangle * @param radius {number} Radius of the rectangle corners */ -Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) { +Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) +{ this.drawShape(new math.RoundedRectangle(x, y, width, height, radius)); return this; @@ -570,7 +617,8 @@ * @param radius {number} The radius of the circle * @return {Graphics} */ -Graphics.prototype.drawCircle = function (x, y, radius) { +Graphics.prototype.drawCircle = function (x, y, radius) +{ this.drawShape(new math.Circle(x,y, radius)); return this; @@ -585,7 +633,8 @@ * @param height {number} The half height of the ellipse * @return {Graphics} */ -Graphics.prototype.drawEllipse = function (x, y, width, height) { +Graphics.prototype.drawEllipse = function (x, y, width, height) +{ this.drawShape(new math.Ellipse(x, y, width, height)); return this; @@ -597,8 +646,10 @@ * @param path {Array} The path data used to construct the polygon. * @return {Graphics} */ -Graphics.prototype.drawPolygon = function (path) { - if (!(path instanceof Array)) { +Graphics.prototype.drawPolygon = function (path) +{ + if (!(path instanceof Array)) + { path = Array.prototype.slice.call(arguments); } @@ -612,7 +663,8 @@ * * @return {Graphics} */ -Graphics.prototype.clear = function () { +Graphics.prototype.clear = function () +{ this.lineWidth = 0; this.filling = false; @@ -631,7 +683,8 @@ * @param scaleMode {number} Should be one of the scaleMode consts * @return {Texture} a texture of the graphics object */ -Graphics.prototype.generateTexture = function (resolution, scaleMode) { +Graphics.prototype.generateTexture = function (resolution, scaleMode) +{ resolution = resolution || 1; var bounds = this.getBounds(); @@ -655,17 +708,21 @@ * * @param renderer {WebGLRenderer} */ -Graphics.prototype._renderWebGL = function (renderer) { +Graphics.prototype._renderWebGL = function (renderer) +{ // if the sprite is not visible or the alpha is 0 then no need to render this element - if (this.isMask === true) { + if (this.isMask === true) + { return; } // this code may still be needed so leaving for now.. - // + // /* - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture on the gpu too! @@ -681,17 +738,24 @@ return; } - */ - - // check if the webgl graphic needs to be updated - if (this.glDirty) { - this.dirty = true; - this.glDirty = false; - } + else */ - renderer.setObjectRendererer(renderer.graphicsRenderer); - renderer.graphicsRenderer.render(this); + renderer.spriteBatch.stop(); + renderer.blendModeManager.setBlendMode(this.blendMode); + // check blend mode + renderer.blendModeManager.setBlendMode( this.blendMode ); + + // check if the webgl graphic needs to be updated + if (this.glDirty) + { + this.dirty = true; + this.glDirty = false; + } + + WebGLGraphics.renderGraphics(this, renderer); + + renderer.spriteBatch.start(); }; /** @@ -700,14 +764,18 @@ * @param renderer {CanvasRenderer} * @private */ -Graphics.prototype.renderCanvas = function (renderer) { +Graphics.prototype.renderCanvas = function (renderer) +{ // 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.isMask === true) { + if (!this.visible || this.alpha <= 0 || this.isMask === true) + { return; } - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture @@ -723,16 +791,19 @@ return; } - else { + else + { var context = renderer.context; var transform = this.worldTransform; - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } @@ -748,11 +819,13 @@ CanvasGraphics.renderGraphics(this, context); - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } } @@ -763,13 +836,16 @@ * * @return {Rectangle} the rectangular bounding area */ -Graphics.prototype.getBounds = function (matrix) { +Graphics.prototype.getBounds = function (matrix) +{ // return an empty object if the item is a mask! - if (this.isMask) { + if (this.isMask) + { return math.Rectangle.EMPTY; } - if (this.dirty) { + if (this.dirty) + { this.updateLocalBounds(); this.glDirty = true; @@ -841,23 +917,27 @@ * Update the bounds of the object * */ -Graphics.prototype.updateLocalBounds = function () { +Graphics.prototype.updateLocalBounds = function () +{ var minX = Infinity; var maxX = -Infinity; var minY = Infinity; var maxY = -Infinity; - if (this.graphicsData.length) { + if (this.graphicsData.length) + { var shape, points, x, y, w, h; - for (var i = 0; i < this.graphicsData.length; i++) { + for (var i = 0; i < this.graphicsData.length; i++) + { var data = this.graphicsData[i]; var type = data.type; var lineWidth = data.lineWidth; shape = data.shape; - if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) { + if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) + { x = shape.x - lineWidth/2; y = shape.y - lineWidth/2; w = shape.width + lineWidth; @@ -869,7 +949,8 @@ minY = y < minY ? y : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.CIRC) { + else if (type === CONST.SHAPES.CIRC) + { x = shape.x; y = shape.y; w = shape.radius + lineWidth/2; @@ -881,7 +962,8 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.ELIP) { + else if (type === CONST.SHAPES.ELIP) + { x = shape.x; y = shape.y; w = shape.width + lineWidth/2; @@ -893,11 +975,13 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else { + else + { // POLY points = shape.points; - for (var j = 0; j < points.length; j += 2) { + for (var j = 0; j < points.length; j += 2) + { x = points[j]; y = points[j+1]; @@ -910,7 +994,8 @@ } } } - else { + else + { minX = 0; maxX = 0; minY = 0; @@ -931,10 +1016,12 @@ * * @private */ -Graphics.prototype._generateCachedSprite = function () { +Graphics.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { var canvasBuffer = new CanvasBuffer(bounds.width, bounds.height); var texture = Texture.fromCanvas(canvasBuffer.canvas); @@ -943,7 +1030,8 @@ this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.buffer.resize(bounds.width, bounds.height); } @@ -968,7 +1056,8 @@ * * @private */ -Graphics.prototype.updateCachedSpriteTexture = function () { +Graphics.prototype.updateCachedSpriteTexture = function () +{ var cachedSprite = this._cachedSprite; var texture = cachedSprite.texture; var canvas = cachedSprite.buffer.canvas; @@ -989,7 +1078,8 @@ * Destroys a previous cached sprite. * */ -Graphics.prototype.destroyCachedSprite = function () { +Graphics.prototype.destroyCachedSprite = function () +{ this._cachedSprite.texture.destroy(true); // let the gc collect the unused sprite @@ -1003,10 +1093,13 @@ * @param {Circle|Rectangle|Ellipse|Line|Polygon} shape The Shape object to draw. * @return {GraphicsData} The generated GraphicsData object. */ -Graphics.prototype.drawShape = function (shape) { - if (this.currentPath) { +Graphics.prototype.drawShape = function (shape) +{ + if (this.currentPath) + { // check current path! - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath.shape.points.length <= 2) + { this.graphicsData.pop(); } } @@ -1017,7 +1110,8 @@ this.graphicsData.push(data); - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { data.shape.closed = this.filling; this.currentPath = data; } diff --git a/src/core/primitives/GraphicsData.js b/src/core/primitives/GraphicsData.js index 99decbe..788f6f2 100644 --- a/src/core/primitives/GraphicsData.js +++ b/src/core/primitives/GraphicsData.js @@ -4,7 +4,8 @@ * @class * @namespace PIXI */ -function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) { +function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) +{ this.lineWidth = lineWidth; this.lineColor = lineColor; this.lineAlpha = lineAlpha; @@ -27,7 +28,8 @@ * * @return {GraphicsData} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ return new GraphicsData( this.lineWidth, this.lineColor, diff --git a/src/core/renderers/canvas/CanvasRenderer.js b/src/core/renderers/canvas/CanvasRenderer.js index 15a0978..7aebd44 100644 --- a/src/core/renderers/canvas/CanvasRenderer.js +++ b/src/core/renderers/canvas/CanvasRenderer.js @@ -17,17 +17,22 @@ * @param [options.resolution=1] {number} the resolution of the renderer retina would be 2 * @param [options.clearBeforeRender=true] {boolean} This sets if the CanvasRenderer will clear the canvas or not before the new render pass. */ -function CanvasRenderer(width, height, options) { +function CanvasRenderer(width, height, options) +{ utils.sayHello('Canvas'); - if (options) { - for (var i in CONST.defaultRenderOptions) { - if (typeof options[i] === 'undefined') { + if (options) + { + for (var i in CONST.defaultRenderOptions) + { + if (typeof options[i] === 'undefined') + { options[i] = CONST.defaultRenderOptions[i]; } } } - else { + else + { options = CONST.defaultRenderOptions; } @@ -156,19 +161,24 @@ this.smoothProperty = null; - if (this.context.imageSmoothingEnabled) { + if (this.context.imageSmoothingEnabled) + { this.smoothProperty = 'imageSmoothingEnabled'; } - else if (this.context.webkitImageSmoothingEnabled) { + else if (this.context.webkitImageSmoothingEnabled) + { this.smoothProperty = 'webkitImageSmoothingEnabled'; } - else if (this.context.mozImageSmoothingEnabled) { + else if (this.context.mozImageSmoothingEnabled) + { this.smoothProperty = 'mozImageSmoothingEnabled'; } - else if (this.context.oImageSmoothingEnabled) { + else if (this.context.oImageSmoothingEnabled) + { this.smoothProperty = 'oImageSmoothingEnabled'; } - else if (this.context.msImageSmoothingEnabled) { + else if (this.context.msImageSmoothingEnabled) + { this.smoothProperty = 'msImageSmoothingEnabled'; } @@ -193,10 +203,12 @@ * @memberof CanvasRenderer# */ backgroundColor: { - get: function () { + get: function () + { return this._backgroundColor; }, - set: function (val) { + set: function (val) + { this._backgroundColor = val; this._backgroundColorString = utils.hex2string(val); } @@ -208,7 +220,8 @@ * * @param object {DisplayObject} the object to be rendered */ -CanvasRenderer.prototype.render = function (object) { +CanvasRenderer.prototype.render = function (object) +{ object.updateTransform(); this.context.setTransform(1,0,0,1,0,0); @@ -218,16 +231,20 @@ this.currentBlendMode = CONST.blendModes.NORMAL; this.context.globalCompositeOperation = this.blendModes[CONST.blendModes.NORMAL]; - if (navigator.isCocoonJS && this.view.screencanvas) { + if (navigator.isCocoonJS && this.view.screencanvas) + { this.context.fillStyle = 'black'; this.context.clear(); } - if (this.clearBeforeRender) { - if (this.transparent) { + if (this.clearBeforeRender) + { + if (this.transparent) + { this.context.clearRect(0, 0, this.width, this.height); } - else { + else + { this.context.fillStyle = this._backgroundColorString; this.context.fillRect(0, 0, this.width , this.height); } @@ -241,8 +258,10 @@ * * @param [removeView=false] {boolean} Removes the Canvas element from the DOM. */ -CanvasRenderer.prototype.destroy = function (removeView) { - if (removeView && this.view.parent) { +CanvasRenderer.prototype.destroy = function (removeView) +{ + if (removeView && this.view.parent) + { this.view.parent.removeChild(this.view); } @@ -257,14 +276,16 @@ * @param width {number} the new width of the canvas view * @param height {number} the new height of the canvas view */ -CanvasRenderer.prototype.resize = function (width, height) { +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) { + if (this.autoResize) + { this.view.style.width = this.width / this.resolution + 'px'; this.view.style.height = this.height / this.resolution + 'px'; } @@ -276,7 +297,8 @@ * @param displayObject {DisplayObject} The displayObject to render * @private */ -CanvasRenderer.prototype.renderDisplayObject = function (displayObject) { +CanvasRenderer.prototype.renderDisplayObject = function (displayObject) +{ displayObject.renderCanvas(this); }; @@ -285,11 +307,14 @@ * * @private */ -CanvasRenderer.prototype._mapBlendModes = function () { - if (!this.blendModes) { +CanvasRenderer.prototype._mapBlendModes = function () +{ + if (!this.blendModes) + { this.blendModes = {}; - if (utils.canUseNewCanvasBlendModes()) { + if (utils.canUseNewCanvasBlendModes()) + { this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? this.blendModes[CONST.blendModes.MULTIPLY] = 'multiply'; @@ -308,7 +333,8 @@ this.blendModes[CONST.blendModes.COLOR] = 'color'; this.blendModes[CONST.blendModes.LUMINOSITY] = 'luminosity'; } - else { + else + { // this means that the browser does not support the cool new blend modes in canvas 'cough' ie 'cough' this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? diff --git a/src/core/renderers/canvas/utils/CanvasBuffer.js b/src/core/renderers/canvas/utils/CanvasBuffer.js index ebe5d47..b183a66 100644 --- a/src/core/renderers/canvas/utils/CanvasBuffer.js +++ b/src/core/renderers/canvas/utils/CanvasBuffer.js @@ -6,7 +6,8 @@ * @param width {number} the width for the newly created canvas * @param height {number} the height for the newly created canvas */ -function CanvasBuffer(width, height) { +function CanvasBuffer(width, height) +{ /** * The Canvas object that belongs to this CanvasBuffer. * @@ -36,10 +37,12 @@ * @memberof CanvasBuffer# */ width: { - get: function () { + get: function () + { return this.canvas.width; }, - set: function (val) { + set: function (val) + { this.canvas.width = val; } }, @@ -50,10 +53,12 @@ * @memberof CanvasBuffer# */ height: { - get: function () { + get: function () + { return this.canvas.height; }, - set: function (val) { + set: function (val) + { this.canvas.height = val; } } @@ -64,7 +69,8 @@ * * @private */ -CanvasBuffer.prototype.clear = function () { +CanvasBuffer.prototype.clear = function () +{ this.context.setTransform(1, 0, 0, 1, 0, 0); this.context.clearRect(0,0, this.canvas.width, this.canvas.height); }; @@ -75,7 +81,8 @@ * @param width {number} the new width of the canvas * @param height {number} the new height of the canvas */ -CanvasBuffer.prototype.resize = function (width, height) { +CanvasBuffer.prototype.resize = function (width, height) +{ this.canvas.width = width; this.canvas.height = height; }; diff --git a/src/core/renderers/canvas/utils/CanvasGraphics.js b/src/core/renderers/canvas/utils/CanvasGraphics.js index c7eaa2a..3f2a91f 100644 --- a/src/core/renderers/canvas/utils/CanvasGraphics.js +++ b/src/core/renderers/canvas/utils/CanvasGraphics.js @@ -13,15 +13,18 @@ * @param graphics {Graphics} the actual graphics object to render * @param context {CanvasRenderingContext2D} the 2d drawing method of the canvas */ -CanvasGraphics.renderGraphics = function (graphics, context) { +CanvasGraphics.renderGraphics = function (graphics, context) +{ var worldAlpha = graphics.worldAlpha; - if (graphics.dirty) { + if (graphics.dirty) + { this.updateGraphicsTint(graphics); graphics.dirty = false; } - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; @@ -30,69 +33,82 @@ context.lineWidth = data.lineWidth; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { context.beginPath(); var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } - if (shape.closed) { + if (shape.closed) + { context.lineTo(points[0], points[1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fillRect(shape.x, shape.y, shape.width, shape.height); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.strokeRect(shape.x, shape.y, shape.width, shape.height); } } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.beginPath(); context.arc(shape.x, shape.y, shape.radius,0,2*Math.PI); context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas var w = shape.width * 2; @@ -119,18 +135,21 @@ context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; var width = shape.width; @@ -152,13 +171,15 @@ context.quadraticCurveTo(rx, ry, rx, ry + radius); context.closePath(); - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); @@ -174,45 +195,54 @@ * @param graphics {Graphics} the graphics which will be used as a mask * @param context {CanvasRenderingContext2D} the context 2d method of the canvas */ -CanvasGraphics.renderGraphicsMask = function (graphics, context) { +CanvasGraphics.renderGraphicsMask = function (graphics, context) +{ var len = graphics.graphicsData.length; - if (len === 0) { + if (len === 0) + { return; } context.beginPath(); - for (var i = 0; i < len; i++) { + for (var i = 0; i < len; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { context.rect(shape.x, shape.y, shape.width, shape.height); context.closePath(); } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.arc(shape.x, shape.y, shape.radius, 0, 2 * Math.PI); context.closePath(); } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas @@ -237,7 +267,8 @@ context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); context.closePath(); } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; @@ -262,8 +293,10 @@ } }; -CanvasGraphics.updateGraphicsTint = function (graphics) { - if (graphics.tint === 0xFFFFFF) { +CanvasGraphics.updateGraphicsTint = function (graphics) +{ + if (graphics.tint === 0xFFFFFF) + { return; } @@ -271,7 +304,8 @@ var tintG = (graphics.tint >> 8 & 0xFF) / 255; var tintB = (graphics.tint & 0xFF)/ 255; - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var fillColor = data.fillColor | 0; diff --git a/src/core/renderers/canvas/utils/CanvasMaskManager.js b/src/core/renderers/canvas/utils/CanvasMaskManager.js index e04a733..9827d36 100644 --- a/src/core/renderers/canvas/utils/CanvasMaskManager.js +++ b/src/core/renderers/canvas/utils/CanvasMaskManager.js @@ -6,7 +6,8 @@ * @class * @namespace PIXI */ -function CanvasMaskManager() {} +function CanvasMaskManager() +{} CanvasMaskManager.prototype.constructor = CanvasMaskManager; module.exports = CanvasMaskManager; @@ -17,7 +18,8 @@ * @param maskData {object} the maskData that will be pushed * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.pushMask = function (maskData, renderer) { +CanvasMaskManager.prototype.pushMask = function (maskData, renderer) +{ renderer.context.save(); var cacheAlpha = maskData.alpha; @@ -45,6 +47,7 @@ * * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.popMask = function (renderer) { +CanvasMaskManager.prototype.popMask = function (renderer) +{ renderer.context.restore(); }; diff --git a/src/core/renderers/canvas/utils/CanvasTinter.js b/src/core/renderers/canvas/utils/CanvasTinter.js index 17e0529..d2fb1bc 100644 --- a/src/core/renderers/canvas/utils/CanvasTinter.js +++ b/src/core/renderers/canvas/utils/CanvasTinter.js @@ -14,7 +14,8 @@ * @param color {number} the color to use to tint the sprite with * @return {HTMLCanvasElement} The tinted canvas */ -CanvasTinter.getTintedTexture = function (sprite, color) { +CanvasTinter.getTintedTexture = function (sprite, color) +{ var texture = sprite.texture; color = CanvasTinter.roundColor(color); @@ -23,7 +24,8 @@ texture.tintCache = texture.tintCache || {}; - if (texture.tintCache[stringColor]) { + if (texture.tintCache[stringColor]) + { return texture.tintCache[stringColor]; } @@ -33,14 +35,16 @@ //CanvasTinter.tintWithPerPixel(texture, stringColor, canvas); CanvasTinter.tintMethod(texture, color, canvas); - if (CanvasTinter.convertTintToImage) { + if (CanvasTinter.convertTintToImage) + { // is this better? var tintImage = new Image(); tintImage.src = canvas.toDataURL(); texture.tintCache[stringColor] = tintImage; } - else { + else + { texture.tintCache[stringColor] = canvas; // if we are not converting the texture to an image then we need to lose the reference to the canvas CanvasTinter.canvas = null; @@ -56,7 +60,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithMultiply = function (texture, color, canvas) { +CanvasTinter.tintWithMultiply = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -104,7 +109,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithOverlay = function (texture, color, canvas) { +CanvasTinter.tintWithOverlay = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -139,7 +145,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithPerPixel = function (texture, color, canvas) { +CanvasTinter.tintWithPerPixel = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -167,7 +174,8 @@ var pixels = pixelData.data; - for (var i = 0; i < pixels.length; i += 4) { + for (var i = 0; i < pixels.length; i += 4) + { pixels[i+0] *= r; pixels[i+1] *= g; pixels[i+2] *= b; @@ -181,7 +189,8 @@ * * @param color {number} the color to round, should be a hex color */ -CanvasTinter.roundColor = function (color) { +CanvasTinter.roundColor = function (color) +{ var step = CanvasTinter.cacheStepsPerColorChannel; var rgbValues = utils.hex2rgb(color); diff --git a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js index 9f2f89a..35edbaf 100644 --- a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js +++ b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLBlendModeManager(renderer) { +function WebGLBlendModeManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -23,8 +24,10 @@ * * @param blendMode {number} the blendMode, should be a Pixi const, such as BlendModes.ADD */ -WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) { - if (this.currentBlendMode === blendMode) { +WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) +{ + if (this.currentBlendMode === blendMode) + { return false; } diff --git a/src/core/renderers/webgl/managers/WebGLFilterManager.js b/src/core/renderers/webgl/managers/WebGLFilterManager.js index 1179258..2dac048 100644 --- a/src/core/renderers/webgl/managers/WebGLFilterManager.js +++ b/src/core/renderers/webgl/managers/WebGLFilterManager.js @@ -7,7 +7,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLFilterManager(renderer) { +function WebGLFilterManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -32,7 +33,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.texturePool.length = 0; self.initShaderBuffers(); }); @@ -46,7 +48,8 @@ * @param renderer {WebGLRenderer} * @param buffer {ArrayBuffer} */ -WebGLFilterManager.prototype.begin = function (buffer) { +WebGLFilterManager.prototype.begin = function (buffer) +{ this.defaultShader = this.renderer.shaderManager.defaultShader; this.width = this.renderer.projection.x * 2; @@ -60,7 +63,8 @@ * * @param filterBlock {object} the filter that will be pushed to the current filter stack */ -WebGLFilterManager.prototype.pushFilter = function (filterBlock) { +WebGLFilterManager.prototype.pushFilter = function (filterBlock) +{ var gl = this.renderer.gl; var projection = this.renderer.projection; @@ -78,10 +82,12 @@ this.offsetY += filterBlock._filterArea.y; var texture = this.texturePool.pop(); - if (!texture) { + if (!texture) + { texture = new FilterTexture(this.renderer.gl, this.width, this.height); } - else { + else + { texture.resize(this.width, this.height); } @@ -98,29 +104,35 @@ var localX = filterArea.x, localY = filterArea.y; - if (filterArea.x < 0) { + if (filterArea.x < 0) + { filterArea.width += filterArea.x; filterArea.x = 0; } - if (filterArea.y < 0) { + if (filterArea.y < 0) + { filterArea.height += filterArea.y; filterArea.y = 0; } - if (localX + filterArea.width > this.width) { + if (localX + filterArea.width > this.width) + { filterArea.width = this.width - localX; } - if (localY + filterArea.height > this.height) { + if (localY + filterArea.height > this.height) + { filterArea.height = this.height - localY; } - if (filterArea.width < 0) { + if (filterArea.width < 0) + { filterArea.width = 0; } - if (filterArea.height < 0) { + if (filterArea.height < 0) + { filterArea.height = 0; } @@ -154,7 +166,8 @@ * Removes the last filter from the filter stack and doesn't return it. * */ -WebGLFilterManager.prototype.popFilter = function () { +WebGLFilterManager.prototype.popFilter = function () +{ var gl = this.renderer.gl; var filterBlock = this.filterStack.pop(); @@ -163,7 +176,8 @@ var projection = this.renderer.projection; var offset = this.renderer.offset; - if (filterBlock.filterPasses.length > 1) { + if (filterBlock.filterPasses.length > 1) + { gl.viewport(0, 0, filterArea.width, filterArea.height); gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); @@ -193,7 +207,8 @@ var inputTexture = texture; var outputTexture = this.texturePool.pop(); - if (!outputTexture) { + if (!outputTexture) + { outputTexture = new FilterTexture(this.renderer.gl, this.width, this.height); } outputTexture.resize(this.width, this.height); @@ -204,7 +219,8 @@ gl.disable(gl.BLEND); - for (var i = 0; i < filterBlock.filterPasses.length-1; i++) { + for (var i = 0; i < filterBlock.filterPasses.length-1; i++) + { var filterPass = filterBlock.filterPasses[i]; gl.bindFramebuffer(gl.FRAMEBUFFER, outputTexture.frameBuffer ); @@ -243,10 +259,12 @@ var buffer = this.buffer; // time to render the filters texture to the previous scene - if (this.filterStack.length === 0) { + if (this.filterStack.length === 0) + { gl.colorMask(true, true, true, true);//this.transparent); } - else { + else + { var currentFilter = this.filterStack[this.filterStack.length-1]; filterArea = currentFilter._filterArea; @@ -332,13 +350,15 @@ * @param width {number} the horizontal range of the filter * @param height {number} the vertical range of the filter */ -WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) { +WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) +{ // use program var gl = this.renderer.gl; var shader = filter.shaders[gl.id]; - if (!shader) { + if (!shader) + { shader = new Shader(gl); shader.fragmentSrc = filter.fragmentSrc; @@ -356,7 +376,8 @@ gl.uniform2f(shader.projectionVector, width/2, -height/2); gl.uniform2f(shader.offsetVector, 0,0); - if (filter.uniforms.dimensions) { + 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]; @@ -386,7 +407,8 @@ * Initialises the shader buffers. * */ -WebGLFilterManager.prototype.initShaderBuffers = function () { +WebGLFilterManager.prototype.initShaderBuffers = function () +{ var gl = this.renderer.gl; // create some buffers @@ -432,7 +454,8 @@ * Destroys the filter and removes it from the filter stack. * */ -WebGLFilterManager.prototype.destroy = function () { +WebGLFilterManager.prototype.destroy = function () +{ var gl = this.renderer.gl; this.filterStack = null; @@ -441,7 +464,8 @@ this.offsetY = 0; // destroy textures - for (var i = 0; i < this.texturePool.length; i++) { + for (var i = 0; i < this.texturePool.length; i++) + { this.texturePool[i].destroy(); } diff --git a/src/core/renderers/webgl/managers/WebGLManager.js b/src/core/renderers/webgl/managers/WebGLManager.js index 9d47b5c..c30cd51 100644 --- a/src/core/renderers/webgl/managers/WebGLManager.js +++ b/src/core/renderers/webgl/managers/WebGLManager.js @@ -3,7 +3,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLManager(renderer) { +function WebGLManager(renderer) +{ /** * The renderer this manager works for. * @@ -15,6 +16,7 @@ WebGLManager.prototype.constructor = WebGLManager; module.exports = WebGLManager; -WebGLManager.prototype.destroy = function () { +WebGLManager.prototype.destroy = function () +{ this.renderer = null; }; diff --git a/src/core/renderers/webgl/managers/WebGLMaskManager.js b/src/core/renderers/webgl/managers/WebGLMaskManager.js index 2f90b64..e568812 100644 --- a/src/core/renderers/webgl/managers/WebGLMaskManager.js +++ b/src/core/renderers/webgl/managers/WebGLMaskManager.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLMaskManager(renderer) { +function WebGLMaskManager(renderer) +{ WebGLManager.call(this, renderer); } @@ -19,12 +20,15 @@ * * @param maskData {any[]} */ -WebGLMaskManager.prototype.pushMask = function (maskData) { - if (maskData.dirty) { +WebGLMaskManager.prototype.pushMask = function (maskData) +{ + if (maskData.dirty) + { WebGLGraphics.updateGraphics(maskData, this.renderer.gl); } - if (!maskData._webGL[this.renderer.gl.id].data.length) { + if (!maskData._webGL[this.renderer.gl.id].data.length) + { return; } @@ -36,6 +40,7 @@ * * @param maskData {any[]} */ -WebGLMaskManager.prototype.popMask = function (maskData) { +WebGLMaskManager.prototype.popMask = function (maskData) +{ this.renderer.stencilManager.popStencil(maskData, maskData._webGL[this.renderer.gl.id].data[0], this.renderer); }; diff --git a/src/core/renderers/webgl/managers/WebGLShaderManager.js b/src/core/renderers/webgl/managers/WebGLShaderManager.js index fef071c..90c6477 100644 --- a/src/core/renderers/webgl/managers/WebGLShaderManager.js +++ b/src/core/renderers/webgl/managers/WebGLShaderManager.js @@ -10,7 +10,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLShaderManager(renderer) { +function WebGLShaderManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -28,7 +29,8 @@ */ this.tempAttribState = []; - for (var i = 0; i < this.maxAttibs; i++) { + for (var i = 0; i < this.maxAttibs; i++) + { this.attribState[i] = false; } @@ -66,7 +68,8 @@ // listen for context and update necessary shaders var self = this; - this.renderer.on('context', function (event) { + this.renderer.on('context', function (event) + { var gl = event.data; // this shader is used for rendering primitives @@ -97,29 +100,36 @@ * * @param attribs {Array} attribs */ -WebGLShaderManager.prototype.setAttribs = function (attribs) { +WebGLShaderManager.prototype.setAttribs = function (attribs) +{ // reset temp state var i; - for (i = 0; i < this.tempAttribState.length; i++) { + for (i = 0; i < this.tempAttribState.length; i++) + { this.tempAttribState[i] = false; } // set the new attribs - for (var a in attribs) { + for (var a in attribs) + { this.tempAttribState[attribs[a]] = true; } var gl = this.renderer.gl; - for (i = 0; i < this.attribState.length; i++) { - if (this.attribState[i] !== this.tempAttribState[i]) { + for (i = 0; i < this.attribState.length; i++) + { + if (this.attribState[i] !== this.tempAttribState[i]) + { this.attribState[i] = this.tempAttribState[i]; - if (this.attribState[i]) { + if (this.attribState[i]) + { gl.enableVertexAttribArray(i); } - else { + else + { gl.disableVertexAttribArray(i); } } @@ -131,8 +141,10 @@ * * @param shader {Any} */ -WebGLShaderManager.prototype.setShader = function (shader) { - if (this._currentId === shader.uuid) { +WebGLShaderManager.prototype.setShader = function (shader) +{ + if (this._currentId === shader.uuid) + { return false; } @@ -150,7 +162,8 @@ * Destroys this object. * */ -WebGLShaderManager.prototype.destroy = function () { +WebGLShaderManager.prototype.destroy = function () +{ this.attribState = null; this.tempAttribState = null; diff --git a/src/core/renderers/webgl/managers/WebGLStencilManager.js b/src/core/renderers/webgl/managers/WebGLStencilManager.js index 9ec6398..4cb0134 100644 --- a/src/core/renderers/webgl/managers/WebGLStencilManager.js +++ b/src/core/renderers/webgl/managers/WebGLStencilManager.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLStencilManager(renderer) { +function WebGLStencilManager(renderer) +{ WebGLManager.call(this, renderer); this.stencilStack = []; @@ -24,12 +25,14 @@ * @param graphics {Graphics} * @param webGLData {any[]} */ -WebGLStencilManager.prototype.pushStencil = function (graphics, webGLData) { +WebGLStencilManager.prototype.pushStencil = function (graphics, webGLData) +{ var gl = this.renderer.gl; this.bindGraphics(graphics, webGLData, this.renderer); - if (this.stencilStack.length === 0) { + if (this.stencilStack.length === 0) + { gl.enable(gl.STENCIL_TEST); gl.clear(gl.STENCIL_BUFFER_BIT); this.reverse = true; @@ -47,14 +50,17 @@ // draw the triangle strip! - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } @@ -62,31 +68,38 @@ // draw a quad to increment.. gl.drawElements(gl.TRIANGLE_FAN, 4, gl.UNSIGNED_SHORT, ( webGLData.indices.length - 4 ) * 2 ); - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); } this.reverse = !this.reverse; } - else { - if (!this.reverse) { + else + { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } - else { + 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) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); } } @@ -103,7 +116,8 @@ * @param graphics {Graphics} * @param webGLData {Array} */ -WebGLStencilManager.prototype.bindGraphics = function (graphics, webGLData) { +WebGLStencilManager.prototype.bindGraphics = function (graphics, webGLData) +{ //if (this._currentGraphics === graphics)return; this._currentGraphics = graphics; @@ -114,7 +128,8 @@ offset = this.renderer.offset, shader;// = this.renderer.shaderManager.primitiveShader; - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { shader = this.renderer.shaderManager.complexPrimitiveShader; this.renderer.shaderManager.setShader(shader); @@ -141,7 +156,8 @@ // set the index buffer! gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, webGLData.indexBuffer); } - else { + else + { //this.renderer.shaderManager.activatePrimitiveShader(); shader = this.renderer.shaderManager.primitiveShader; this.renderer.shaderManager.setShader( shader ); @@ -154,7 +170,7 @@ gl.uniform2f(shader.uniforms.offsetVector._location, -offset.x, -offset.y); gl.uniform3fv(shader.uniforms.tint._location, utils.hex2rgb(graphics.tint)); - + gl.uniform1f(shader.uniforms.alpha._location, graphics.worldAlpha); @@ -172,19 +188,22 @@ * @param graphics {Graphics} * @param webGLData {Array} */ -WebGLStencilManager.prototype.popStencil = function (graphics, webGLData) { +WebGLStencilManager.prototype.popStencil = function (graphics, webGLData) +{ var gl = this.renderer.gl; this.stencilStack.pop(); this.count--; - if (this.stencilStack.length === 0) { + if (this.stencilStack.length === 0) + { // the stack is empty! gl.disable(gl.STENCIL_TEST); } - else { + else + { var level = this.count; @@ -192,14 +211,17 @@ gl.colorMask(false, false, false, false); - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { this.reverse = !this.reverse; - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } @@ -213,31 +235,38 @@ // draw the triangle strip! gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); - if (!this.reverse) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); } } - else { + else + { // console.log("<<>>") - if (!this.reverse) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } - else { + 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) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); } } @@ -253,7 +282,8 @@ * Destroys the mask stack. * */ -WebGLStencilManager.prototype.destroy = function () { +WebGLStencilManager.prototype.destroy = function () +{ this.renderer = null; this.stencilStack = null; }; diff --git a/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js b/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js index 913ba5e..1ea7d19 100644 --- a/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js +++ b/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function ComplexPrimitiveShader(gl) { +function ComplexPrimitiveShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -24,7 +25,8 @@ 'uniform float flipY;', 'varying vec4 vColor;', - 'void main(void) {', + '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);', @@ -37,7 +39,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = vColor;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/FastShader.js b/src/core/renderers/webgl/shaders/FastShader.js index bd2e29a..2e5e060 100644 --- a/src/core/renderers/webgl/shaders/FastShader.js +++ b/src/core/renderers/webgl/shaders/FastShader.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function FastShader(gl) { +function FastShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -28,7 +29,8 @@ 'const vec2 center = vec2(-1.0, 1.0);', - 'void main(void) {', + 'void main(void) + {', ' vec2 v;', ' vec2 sv = aVertexPosition * aScale;', ' v.x = (sv.x) * cos(aRotation) - (sv.y) * sin(aRotation);', @@ -49,7 +51,8 @@ 'uniform sampler2D uSampler;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/PrimitiveShader.js b/src/core/renderers/webgl/shaders/PrimitiveShader.js index 6f25409..a25f54f 100644 --- a/src/core/renderers/webgl/shaders/PrimitiveShader.js +++ b/src/core/renderers/webgl/shaders/PrimitiveShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function PrimitiveShader(gl) { +function PrimitiveShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -23,7 +24,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + '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);', @@ -36,7 +38,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = vColor;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/Shader.js b/src/core/renderers/webgl/shaders/Shader.js index f8964f5..fd75ef5 100644 --- a/src/core/renderers/webgl/shaders/Shader.js +++ b/src/core/renderers/webgl/shaders/Shader.js @@ -6,7 +6,8 @@ * @param [fragmentSrc] {string} The source of the fragment shader. * @param [vertexSrc] {string} The source of the vertex shader. */ -function Shader(gl, vertexSrc, fragmentSrc, customUniforms, customAttributes) { +function Shader(gl, vertexSrc, fragmentSrc, customUniforms, customAttributes) +{ /** * @member {number} * @readonly @@ -33,7 +34,8 @@ dimensions: { type: '4f', value: new Float32Array(4) } }; - for (var u in customUniforms) { + for (var u in customUniforms) + { this.uniforms[u] = customUniforms[u]; } @@ -43,7 +45,8 @@ aColor: 0 }; - for (var a in customAttributes) { + for (var a in customAttributes) + { this.attributes[a] = customAttributes[a]; } @@ -66,7 +69,8 @@ 'const vec2 center = vec2(-1.0, 1.0);', - 'void main(void) {', + 'void main(void) + {', ' gl_Position = vec4( ((aVertexPosition + offsetVector) / projectionVector) + center , 0.0, 1.0);', ' vTextureCoord = aTextureCoord;', ' vColor = vec4(aColor.rgb * aColor.a, aColor.a);', @@ -85,7 +89,8 @@ 'uniform sampler2D uSampler;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;', '}' ].join('\n'); @@ -96,7 +101,8 @@ Shader.prototype.constructor = Shader; module.exports = Shader; -Shader.prototype.init = function () { +Shader.prototype.init = function () +{ this.compile(); this.gl.useProgram(this.program); @@ -105,14 +111,18 @@ this.cacheAttributeLocations(Object.keys(this.attributes)); }; -Shader.prototype.cacheUniformLocations = function (keys) { - for (var i = 0; i < keys.length; ++i) { +Shader.prototype.cacheUniformLocations = function (keys) +{ + for (var i = 0; i < keys.length; ++i) + { this.uniforms[keys[i]]._location = this.gl.getUniformLocation(this.program, keys[i]); } }; -Shader.prototype.cacheAttributeLocations = function (keys) { - for (var i = 0; i < keys.length; ++i) { +Shader.prototype.cacheAttributeLocations = function (keys) +{ + for (var i = 0; i < keys.length; ++i) + { this.attributes[keys[i]] = this.gl.getAttribLocation(this.program, keys[i]); } @@ -124,14 +134,16 @@ // 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.attributes.aColor === -1) { + // if (this.attributes.aColor === -1) + { // this.attributes.aColor = 2; // } // End worst hack eva // }; -Shader.prototype.compile = function () { +Shader.prototype.compile = function () +{ var gl = this.gl; var glVertShader = this._glCompile(gl.VERTEX_SHADER, this.vertexSrc); @@ -144,13 +156,15 @@ gl.linkProgram(program); // if linking fails, then log and cleanup - if (!gl.getProgramParameter(program, gl.LINK_STATUS)) { + if (!gl.getProgramParameter(program, gl.LINK_STATUS)) + { window.console.error('Pixi.js Error: Could not initialize shader.'); window.console.error('gl.VALIDATE_STATUS', gl.getProgramParameter(program, gl.VALIDATE_STATUS)); window.console.error('gl.getError()', gl.getError()); // if there is a program info log, log it - if (gl.getProgramInfoLog(program) !== '') { + if (gl.getProgramInfoLog(program) !== '') + { window.console.warn('Pixi.js Warning: gl.getProgramInfoLog()', gl.getProgramInfoLog(program)); } @@ -165,18 +179,21 @@ return (this.program = program); }; -Shader.prototype.syncUniforms = function () { +Shader.prototype.syncUniforms = function () +{ var gl = this.gl; this.textureCount = 1; - for (var key in this.uniforms) { + for (var key in this.uniforms) + { var uniform = this.uniforms[key], location = uniform._location, value = uniform.value, i, il; - switch (uniform.type) { + switch (uniform.type) + { // single int value case 'i': case '1i': @@ -282,7 +299,8 @@ // a Color Value case 'c': - if (typeof value === 'number') { + if (typeof value === 'number') + { value = utils.hex2rgb(value); } @@ -311,11 +329,13 @@ // array of 2D Point objects case 'v2v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(2 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 2] = value[i].x; uniform._array[i * 2 + 1] = value[i].y; } @@ -325,11 +345,13 @@ // array of 3D Point objects case 'v3v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(3 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 3] = value[i].x; uniform._array[i * 3 + 1] = value[i].y; uniform._array[i * 3 + 2] = value[i].z; @@ -341,11 +363,13 @@ // array of 4D Point objects case 'v4v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(4 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 4] = value[i].x; uniform._array[i * 4 + 1] = value[i].y; uniform._array[i * 4 + 2] = value[i].z; @@ -359,7 +383,8 @@ // PIXI.Texture case 't': case 'sampler2D': - if (!uniform.value || !uniform.value.baseTexture || !uniform.value.baseTexture.hasLoaded) { + if (!uniform.value || !uniform.value.baseTexture || !uniform.value.baseTexture.hasLoaded) + { break; } @@ -376,7 +401,8 @@ this.textureCount++; // initialize the texture if we haven't yet - if (!uniform._init) { + if (!uniform._init) + { this.initSampler2D(uniform); uniform._init = true; @@ -394,11 +420,13 @@ * Initialises a Sampler2D uniform (which may only be available later on after initUniforms once the texture has loaded) * */ -Shader.prototype.initSampler2D = function (uniform) { +Shader.prototype.initSampler2D = function (uniform) +{ var gl = this.gl; // Extended texture data - if (uniform.textureData) { + if (uniform.textureData) + { var data = uniform.textureData; // GLTexture = mag linear, min linear_mipmap_linear, wrap repeat + gl.generateMipmap(gl.TEXTURE_2D); @@ -417,14 +445,16 @@ var wrapT = (data.wrapT) ? data.wrapT : gl.CLAMP_TO_EDGE; var format = (data.luminance) ? gl.LUMINANCE : gl.RGBA; - if (data.repeat) { + if (data.repeat) + { wrapS = gl.REPEAT; wrapT = gl.REPEAT; } gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, !!data.flipY); - if (data.width) { + if (data.width) + { var width = (data.width) ? data.width : 512; var height = (data.height) ? data.height : 2; var border = (data.border) ? data.border : 0; @@ -432,7 +462,8 @@ // 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 { + 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); } @@ -448,7 +479,8 @@ * Destroys the shader. * */ -Shader.prototype.destroy = function () { +Shader.prototype.destroy = function () +{ this.gl.deleteProgram(this.program); this.gl = null; @@ -459,13 +491,15 @@ this.fragmentSrc = null; }; -Shader.prototype._glCompile = function (type, src) { +Shader.prototype._glCompile = function (type, src) +{ var shader = this.gl.createShader(type); this.gl.shaderSource(shader, src); this.gl.compileShader(shader); - if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) { + if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) + { window.console.log(this.gl.getShaderInfoLog(shader)); return null; } diff --git a/src/core/renderers/webgl/shaders/StripShader.js b/src/core/renderers/webgl/shaders/StripShader.js index 193f6e1..a7abcc6 100644 --- a/src/core/renderers/webgl/shaders/StripShader.js +++ b/src/core/renderers/webgl/shaders/StripShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function StripShader(gl) { +function StripShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -20,7 +21,8 @@ 'varying vec2 vTextureCoord;', - 'void main(void) {', + '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);', @@ -36,7 +38,8 @@ 'varying vec2 vTextureCoord;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vec2(vTextureCoord.x, vTextureCoord.y)) * alpha;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/utils/FilterTexture.js b/src/core/renderers/webgl/utils/FilterTexture.js index d2c8423..4433d44 100644 --- a/src/core/renderers/webgl/utils/FilterTexture.js +++ b/src/core/renderers/webgl/utils/FilterTexture.js @@ -8,7 +8,8 @@ * @param height {number} the vertical range of the filter * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values */ -function FilterTexture(gl, width, height, scaleMode) { +function FilterTexture(gl, width, height, scaleMode) +{ /** * @member {WebGLContext} */ @@ -59,7 +60,8 @@ * Clears the filter texture. * */ -FilterTexture.prototype.clear = function () { +FilterTexture.prototype.clear = function () +{ var gl = this.gl; gl.clearColor(0,0,0, 0); @@ -72,8 +74,10 @@ * @param width {number} the new width of the texture * @param height {number} the new height of the texture */ -FilterTexture.prototype.resize = function (width, height) { - if (this.width === width && this.height === height) { +FilterTexture.prototype.resize = function (width, height) +{ + if (this.width === width && this.height === height) + { return; } @@ -96,7 +100,8 @@ * Destroys the filter texture. * */ -FilterTexture.prototype.destroy = function () { +FilterTexture.prototype.destroy = function () +{ var gl = this.gl; gl.deleteFramebuffer( this.frameBuffer ); gl.deleteTexture( this.texture ); diff --git a/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js b/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js index c4721e9..a63f4d7 100644 --- a/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js +++ b/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js @@ -14,7 +14,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this sprite batch works for. */ -function WebGLFastSpriteBatch(renderer) { +function WebGLFastSpriteBatch(renderer) +{ /** * The renderer instance this sprite batch operates on. * @@ -91,7 +92,8 @@ */ this.lastIndexCount = 0; - for (var i=0, j=0; i < numIndices; i += 6, j += 4) { + 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; @@ -144,7 +146,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.setupContext(); }); } @@ -157,7 +160,8 @@ * * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLFastSpriteBatch.prototype.setupContext = function () { +WebGLFastSpriteBatch.prototype.setupContext = function () +{ var gl = this.renderer.gl; // create a couple of buffers @@ -177,7 +181,8 @@ /** * @param spriteBatch {SpriteBatch} The SpriteBatch container to prepare for. */ -WebGLFastSpriteBatch.prototype.begin = function (spriteBatch) { +WebGLFastSpriteBatch.prototype.begin = function (spriteBatch) +{ this.shader = this.renderer.shaderManager.fastShader; this.matrix = spriteBatch.worldTransform.toArray(true); @@ -187,33 +192,38 @@ /** */ -WebGLFastSpriteBatch.prototype.end = function () { +WebGLFastSpriteBatch.prototype.end = function () +{ this.flush(); }; /** * @param spriteBatch {SpriteBatch} The SpriteBatch container to render. */ -WebGLFastSpriteBatch.prototype.render = function (spriteBatch) { +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) { + if (!sprite.texture._uvs) + { return; } this.currentBaseTexture = sprite.texture.baseTexture; // check blend mode - if (sprite.blendMode !== this.renderer.blendModeManager.currentBlendMode) { + if (sprite.blendMode !== this.renderer.blendModeManager.currentBlendMode) + { this.flush(); this.renderer.blendModeManager.setBlendMode(sprite.blendMode); } - for (var i=0,j= children.length; i= this.size) { + if (this.currentBatchSize >= this.size) + { this.flush(); } }; @@ -362,29 +379,35 @@ /** * */ -WebGLFastSpriteBatch.prototype.flush = function () { +WebGLFastSpriteBatch.prototype.flush = function () +{ // If the batch is length 0 then return as there is nothing to draw - if (this.currentBatchSize === 0) { + if (this.currentBatchSize === 0) + { return; } var gl = this.renderer.gl; // bind the current texture - if (!this.currentBaseTexture._glTextures[gl.id]) { + if (!this.currentBaseTexture._glTextures[gl.id]) + { this.renderer.updateTexture(this.currentBaseTexture, gl); } //TODO-SHOUD THIS BE ELSE??!?!?! - else { + else + { gl.bindTexture(gl.TEXTURE_2D, this.currentBaseTexture._glTextures[gl.id]); } // upload the verts to the buffer - if (this.currentBatchSize > ( this.size * 0.5 ) ) { + if (this.currentBatchSize > ( this.size * 0.5 ) ) + { gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); } - else { + else + { var view = this.vertices.subarray(0, this.currentBatchSize * this.vertByteSize); gl.bufferSubData(gl.ARRAY_BUFFER, 0, view); @@ -405,14 +428,16 @@ * Ends the batch and flushes * */ -WebGLFastSpriteBatch.prototype.stop = function () { +WebGLFastSpriteBatch.prototype.stop = function () +{ this.flush(); }; /** * */ -WebGLFastSpriteBatch.prototype.start = function () { +WebGLFastSpriteBatch.prototype.start = function () +{ var gl = this.renderer.gl; // bind the main texture diff --git a/src/core/renderers/webgl/utils/WebGLGraphics.js b/src/core/renderers/webgl/utils/WebGLGraphics.js index 55f4911..ab8f46e 100644 --- a/src/core/renderers/webgl/utils/WebGLGraphics.js +++ b/src/core/renderers/webgl/utils/WebGLGraphics.js @@ -19,7 +19,8 @@ * @param graphics {Graphics} * @param renderer {WebGLRenderer} */ -WebGLGraphics.renderGraphics = function (graphics, renderer) {//projection, offset) { +WebGLGraphics.renderGraphics = function (graphics, renderer) {//projection, offset) +{ var gl = renderer.gl; var projection = renderer.projection, @@ -27,7 +28,8 @@ shader = renderer.shaderManager.primitiveShader, webGLData; - if (graphics.dirty) { + if (graphics.dirty) + { WebGLGraphics.updateGraphics(graphics, gl); } @@ -35,8 +37,10 @@ // This could be speeded up for sure! - for (var i = 0; i < webGL.data.length; i++) { - if (webGL.data[i].mode === 1) { + for (var i = 0; i < webGL.data.length; i++) + { + if (webGL.data[i].mode === 1) + { webGLData = webGL.data[i]; renderer.stencilManager.pushStencil(graphics, webGLData, renderer); @@ -46,7 +50,8 @@ renderer.stencilManager.popStencil(graphics, webGLData, renderer); } - else { + else + { webGLData = webGL.data[i]; @@ -84,12 +89,14 @@ * @param graphicsData {Graphics} The graphics object to update * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLGraphics.updateGraphics = function (graphics, gl) { +WebGLGraphics.updateGraphics = function (graphics, gl) +{ // get the contexts graphics object var webGL = graphics._webGL[gl.id]; // if the graphics object does not exist in the webGL context time to create it! - if (!webGL) { + if (!webGL) + { webGL = graphics._webGL[gl.id] = {lastIndex:0, data:[], gl:gl}; } @@ -99,11 +106,13 @@ var i; // if the user cleared the graphics object we will need to clear every object - if (graphics.clearDirty) { + if (graphics.clearDirty) + { graphics.clearDirty = false; // lop through and return all the webGLDatas to the object pool so than can be reused later on - for (i = 0; i < webGL.data.length; i++) { + for (i = 0; i < webGL.data.length; i++) + { var graphicsData = webGL.data[i]; graphicsData.reset(); WebGLGraphics.graphicsDataPool.push( graphicsData ); @@ -119,58 +128,72 @@ // loop through the graphics datas and construct each one.. // if the object is a complex fill then the new stencil buffer technique will be used // other wise graphics objects will be pushed into a batch.. - for (i = webGL.lastIndex; i < graphics.graphicsData.length; i++) { + for (i = webGL.lastIndex; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { // need to add the points the the graphics object.. data.points = data.shape.points.slice(); - if (data.shape.closed) { + if (data.shape.closed) + { // close the poly if the value is true! - if (data.points[0] !== data.points[data.points.length-2] || data.points[1] !== data.points[data.points.length-1]) { + if (data.points[0] !== data.points[data.points.length-2] || data.points[1] !== data.points[data.points.length-1]) + { data.points.push(data.points[0], data.points[1]); } } // MAKE SURE WE HAVE THE CORRECT TYPE.. - if (data.fill) { - if (data.points.length >= 6) { - if (data.points.length < 6 * 2) { + if (data.fill) + { + if (data.points.length >= 6) + { + if (data.points.length < 6 * 2) + { webGLData = WebGLGraphics.switchMode(webGL, 0); var canDrawUsingSimple = WebGLGraphics.buildPoly(data, webGLData); // console.log(canDrawUsingSimple); - if (!canDrawUsingSimple) { + if (!canDrawUsingSimple) + { // console.log("<>>>") webGLData = WebGLGraphics.switchMode(webGL, 1); WebGLGraphics.buildComplexPoly(data, webGLData); } } - else { + else + { webGLData = WebGLGraphics.switchMode(webGL, 1); WebGLGraphics.buildComplexPoly(data, webGLData); } } } - if (data.lineWidth > 0) { + if (data.lineWidth > 0) + { webGLData = WebGLGraphics.switchMode(webGL, 0); WebGLGraphics.buildLine(data, webGLData); } } - else { + else + { webGLData = WebGLGraphics.switchMode(webGL, 0); - if (data.type === CONST.SHAPES.RECT) { + if (data.type === CONST.SHAPES.RECT) + { WebGLGraphics.buildRectangle(data, webGLData); } - else if (data.type === CONST.SHAPES.CIRC || data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.CIRC || data.type === CONST.SHAPES.ELIP) + { WebGLGraphics.buildCircle(data, webGLData); } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { WebGLGraphics.buildRoundedRectangle(data, webGLData); } } @@ -179,10 +202,12 @@ } // upload all the dirty data... - for (i = 0; i < webGL.data.length; i++) { + for (i = 0; i < webGL.data.length; i++) + { webGLData = webGL.data[i]; - if (webGLData.dirty) { + if (webGLData.dirty) + { webGLData.upload(); } } @@ -194,18 +219,22 @@ * @param webGL {WebGLContext} * @param type {number} */ -WebGLGraphics.switchMode = function (webGL, type) { +WebGLGraphics.switchMode = function (webGL, type) +{ var webGLData; - if (!webGL.data.length) { + if (!webGL.data.length) + { webGLData = WebGLGraphics.graphicsDataPool.pop() || new WebGLGraphicsData(webGL.gl); webGLData.mode = type; webGL.data.push(webGLData); } - else { + else + { webGLData = webGL.data[webGL.data.length-1]; - if (webGLData.mode !== type || type === 1) { + if (webGLData.mode !== type || type === 1) + { webGLData = WebGLGraphics.graphicsDataPool.pop() || new WebGLGraphicsData(webGL.gl); webGLData.mode = type; webGL.data.push(webGLData); @@ -225,7 +254,8 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildRectangle = function (graphicsData, webGLData) { +WebGLGraphics.buildRectangle = function (graphicsData, webGLData) +{ // --- // // need to convert points to a nice regular data // @@ -235,7 +265,8 @@ var width = rectData.width; var height = rectData.height; - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -265,7 +296,8 @@ indices.push(vertPos, vertPos, vertPos+1, vertPos+2, vertPos+3, vertPos+3); } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = [x, y, @@ -289,7 +321,8 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildRoundedRectangle = function (graphicsData, webGLData) { +WebGLGraphics.buildRoundedRectangle = function (graphicsData, webGLData) +{ var rrectData = graphicsData.shape; var x = rrectData.x; var y = rrectData.y; @@ -305,7 +338,8 @@ recPoints = recPoints.concat(WebGLGraphics.quadraticBezierCurve(x + width, y + radius, x + width, y, x + width - radius, y)); recPoints = recPoints.concat(WebGLGraphics.quadraticBezierCurve(x + radius, y, x, y, x, y + radius)); - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -323,7 +357,8 @@ // var i = 0; - for (i = 0; i < triangles.length; i+=3) { + for (i = 0; i < triangles.length; i+=3) + { indices.push(triangles[i] + vecPos); indices.push(triangles[i] + vecPos); indices.push(triangles[i+1] + vecPos); @@ -332,12 +367,14 @@ } - for (i = 0; i < recPoints.length; i++) { + for (i = 0; i < recPoints.length; i++) + { verts.push(recPoints[i], recPoints[++i], r, g, b, alpha); } } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = recPoints; @@ -362,7 +399,8 @@ * @param toY {number} Destination point y * @return {number[]} */ -WebGLGraphics.quadraticBezierCurve = function (fromX, fromY, cpX, cpY, toX, toY) { +WebGLGraphics.quadraticBezierCurve = function (fromX, fromY, cpX, cpY, toX, toY) +{ var xa, ya, @@ -373,14 +411,16 @@ n = 20, points = []; - function getPt(n1 , n2, perc) { + function getPt(n1 , n2, perc) + { var diff = n2 - n1; return n1 + ( diff * perc ); } var j = 0; - for (var i = 0; i <= n; i++ ) { + for (var i = 0; i <= n; i++ ) + { j = i / n; // The Green Line @@ -406,7 +446,8 @@ * @param graphicsData {Graphics} The graphics object to draw * @param webGLData {object} */ -WebGLGraphics.buildCircle = function (graphicsData, webGLData) { +WebGLGraphics.buildCircle = function (graphicsData, webGLData) +{ // need to convert points to a nice regular data var circleData = graphicsData.shape; var x = circleData.x; @@ -415,11 +456,13 @@ var height; // TODO - bit hacky?? - if (graphicsData.type === CONST.SHAPES.CIRC) { + if (graphicsData.type === CONST.SHAPES.CIRC) + { width = circleData.radius; height = circleData.radius; } - else { + else + { width = circleData.width; height = circleData.height; } @@ -429,7 +472,8 @@ var i = 0; - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -444,7 +488,8 @@ indices.push(vecPos); - for (i = 0; i < totalSegs + 1 ; i++) { + for (i = 0; i < totalSegs + 1 ; i++) + { verts.push(x,y, r, g, b, alpha); verts.push(x + Math.sin(seg * i) * width, @@ -457,12 +502,14 @@ indices.push(vecPos-1); } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = []; - for (i = 0; i < totalSegs + 1; i++) { + for (i = 0; i < totalSegs + 1; i++) + { graphicsData.points.push(x + Math.sin(seg * i) * width, y + Math.cos(seg * i) * height); } @@ -481,18 +528,22 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildLine = function (graphicsData, webGLData) { +WebGLGraphics.buildLine = function (graphicsData, webGLData) +{ // TODO OPTIMISE! var i = 0; var points = graphicsData.points; - if (points.length === 0) { + if (points.length === 0) + { return; } // if the line width is an odd number add 0.5 to align to a whole pixel - if (graphicsData.lineWidth%2) { - for (i = 0; i < points.length; i++) { + if (graphicsData.lineWidth%2) + { + for (i = 0; i < points.length; i++) + { points[i] += 0.5; } } @@ -502,7 +553,8 @@ var lastPoint = new math.Point(points[points.length - 2], points[points.length - 1]); // if the first point is the last point - gonna have issues :) - if (firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) { + if (firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) + { // need to clone as we are going to slightly modify the shape.. points = points.slice(); @@ -562,7 +614,8 @@ verts.push(p1x + perpx , p1y + perpy, r, g, b, alpha); - for (i = 1; i < length-1; i++) { + for (i = 1; i < length-1; i++) + { p1x = points[(i-1)*2]; p1y = points[(i-1)*2 + 1]; @@ -599,7 +652,8 @@ denom = a1*b2 - a2*b1; - if (Math.abs(denom) < 0.1 ) { + if (Math.abs(denom) < 0.1 ) + { denom+=10.1; verts.push(p2x - perpx , p2y - perpy, @@ -618,7 +672,8 @@ pdist = (px -p2x) * (px -p2x) + (py -p2y) + (py -p2y); - if (pdist > 140 * 140) { + if (pdist > 140 * 140) + { perp3x = perpx - perp2x; perp3y = perpy - perp2y; @@ -639,7 +694,8 @@ indexCount++; } - else { + else + { verts.push(px , py); verts.push(r, g, b, alpha); @@ -672,7 +728,8 @@ indices.push(indexStart); - for (i = 0; i < indexCount; i++) { + for (i = 0; i < indexCount; i++) + { indices.push(indexStart++); } @@ -687,11 +744,13 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildComplexPoly = function (graphicsData, webGLData) { +WebGLGraphics.buildComplexPoly = function (graphicsData, webGLData) +{ //TODO - no need to copy this as it gets turned into a FLoat32Array anyways.. var points = graphicsData.points.slice(); - if (points.length < 6) { + if (points.length < 6) + { return; } @@ -711,7 +770,8 @@ var x,y; // get size.. - for (var i = 0; i < points.length; i+=2) { + for (var i = 0; i < points.length; i+=2) + { x = points[i]; y = points[i+1]; @@ -732,7 +792,8 @@ //TODO - this aint needed! var length = points.length / 2; - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { indices.push( i ); } @@ -746,10 +807,12 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildPoly = function (graphicsData, webGLData) { +WebGLGraphics.buildPoly = function (graphicsData, webGLData) +{ var points = graphicsData.points; - if (points.length < 6) { + if (points.length < 6) + { return; } // get first and last point.. figure out the middle! @@ -767,7 +830,8 @@ var triangles = utils.PolyK.Triangulate(points); - if (!triangles) { + if (!triangles) + { return false; } @@ -775,7 +839,8 @@ var i = 0; - for (i = 0; i < triangles.length; i+=3) { + for (i = 0; i < triangles.length; i+=3) + { indices.push(triangles[i] + vertPos); indices.push(triangles[i] + vertPos); indices.push(triangles[i+1] + vertPos); @@ -783,7 +848,8 @@ indices.push(triangles[i+2] + vertPos); } - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { verts.push(points[i * 2], points[i * 2 + 1], r, g, b, alpha); } diff --git a/src/core/renderers/webgl/utils/WebGLGraphicsData.js b/src/core/renderers/webgl/utils/WebGLGraphicsData.js index c56d05e..c739ba7 100644 --- a/src/core/renderers/webgl/utils/WebGLGraphicsData.js +++ b/src/core/renderers/webgl/utils/WebGLGraphicsData.js @@ -2,7 +2,8 @@ * @class * @private */ -function WebGLGraphicsData(gl) { +function WebGLGraphicsData(gl) +{ this.gl = gl; //TODO does this need to be split before uploding?? @@ -22,7 +23,8 @@ /** * */ -WebGLGraphicsData.prototype.reset = function () { +WebGLGraphicsData.prototype.reset = function () +{ this.points.length = 0; this.indices.length = 0; }; @@ -30,7 +32,8 @@ /** * */ -WebGLGraphicsData.prototype.upload = function () { +WebGLGraphicsData.prototype.upload = function () +{ var gl = this.gl; // this.lastIndex = graphics.graphicsData.length; diff --git a/src/core/renderers/webgl/utils/WebGLSpriteBatch.js b/src/core/renderers/webgl/utils/WebGLSpriteBatch.js index 96eaa52..55befbb 100644 --- a/src/core/renderers/webgl/utils/WebGLSpriteBatch.js +++ b/src/core/renderers/webgl/utils/WebGLSpriteBatch.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this sprite batch works for. */ -function WebGLSpriteBatch(renderer) { +function WebGLSpriteBatch(renderer) +{ /** * * @@ -88,7 +89,8 @@ */ this.lastIndexCount = 0; - for (var i=0, j=0; i < numIndices; i += 6, j += 4) { + 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; @@ -162,7 +164,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.setupContext(); }); } @@ -173,7 +176,8 @@ /** * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLSpriteBatch.prototype.setupContext = function () { +WebGLSpriteBatch.prototype.setupContext = function () +{ var gl = this.renderer.gl; // setup default shader @@ -198,7 +202,8 @@ /** * */ -WebGLSpriteBatch.prototype.begin = function () { +WebGLSpriteBatch.prototype.begin = function () +{ // this.shader = this.renderer.shaderManager.defaultShader; this.start(); @@ -206,19 +211,22 @@ /** */ -WebGLSpriteBatch.prototype.end = function () { +WebGLSpriteBatch.prototype.end = function () +{ this.flush(); }; /** * @param sprite {Sprite} the sprite to render when using this spritebatch */ -WebGLSpriteBatch.prototype.render = function (sprite) { +WebGLSpriteBatch.prototype.render = function (sprite) +{ var texture = sprite.texture; //TODO set blend modes.. // check texture.. - if (this.currentBatchSize >= this.size) { + if (this.currentBatchSize >= this.size) + { this.flush(); this.currentBaseTexture = texture.baseTexture; } @@ -227,7 +235,8 @@ var uvs = texture._uvs; // if the uvs have not updated then no point rendering just yet! - if (!uvs) { + if (!uvs) + { return; } @@ -237,7 +246,8 @@ var w0, w1, h0, h1; - if (texture.trim) { + 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; @@ -248,7 +258,8 @@ h0 = h1 + texture.crop.height; } - else { + else + { w0 = (texture.frame.width ) * (1-aX); w1 = (texture.frame.width ) * -aX; @@ -272,7 +283,8 @@ var colors = this.colors; var positions = this.positions; - if (this.renderer.roundPixels) { + if (this.renderer.roundPixels) + { // xy positions[index] = a * w1 + c * h1 + tx | 0; positions[index+1] = d * h1 + b * w1 + ty | 0; @@ -289,7 +301,8 @@ positions[index+15] = a * w1 + c * h0 + tx | 0; positions[index+16] = d * h0 + b * w1 + ty | 0; } - else { + else + { // xy positions[index] = a * w1 + c * h1 + tx; positions[index+1] = d * h1 + b * w1 + ty; @@ -338,11 +351,13 @@ * * @param sprite {TilingSprite} the tilingSprite to render */ -WebGLSpriteBatch.prototype.renderTilingSprite = function (tilingSprite) { +WebGLSpriteBatch.prototype.renderTilingSprite = function (tilingSprite) +{ var texture = tilingSprite.tilingTexture; // check texture.. - if (this.currentBatchSize >= this.size) { + if (this.currentBatchSize >= this.size) + { //return; this.flush(); this.currentBaseTexture = texture.baseTexture; @@ -351,7 +366,8 @@ // set the textures uvs temporarily // TODO create a separate texture so that we can tile part of a texture - if (!tilingSprite._uvs) { + if (!tilingSprite._uvs) + { tilingSprite._uvs = new TextureUvs(); } @@ -454,16 +470,19 @@ * Renders the content and empties the current batch. * */ -WebGLSpriteBatch.prototype.flush = function () { +WebGLSpriteBatch.prototype.flush = function () +{ // If the batch is length 0 then return as there is nothing to draw - if (this.currentBatchSize === 0) { + if (this.currentBatchSize === 0) + { return; } var gl = this.renderer.gl; var shader; - if (this.dirty) { + if (this.dirty) + { this.dirty = false; // bind the main texture gl.activeTexture(gl.TEXTURE0); @@ -482,10 +501,12 @@ } // upload the verts to the buffer - if (this.currentBatchSize > ( this.size * 0.5 ) ) { + if (this.currentBatchSize > ( this.size * 0.5 ) ) + { gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); } - else { + else + { var view = this.positions.subarray(0, this.currentBatchSize * this.vertByteSize); gl.bufferSubData(gl.ARRAY_BUFFER, 0, view); } @@ -502,7 +523,8 @@ var shaderSwap = false; var sprite; - for (var i = 0, j = this.currentBatchSize; i < j; i++) { + for (var i = 0, j = this.currentBatchSize; i < j; i++) + { sprite = this.sprites[i]; @@ -513,24 +535,28 @@ blendSwap = currentBlendMode !== nextBlendMode; shaderSwap = currentShader !== nextShader; // should I use uuidS??? - if (currentBaseTexture !== nextTexture || blendSwap || shaderSwap) { + if (currentBaseTexture !== nextTexture || blendSwap || shaderSwap) + { this.renderBatch(currentBaseTexture, batchSize, start); start = i; batchSize = 0; currentBaseTexture = nextTexture; - if (blendSwap) { + if (blendSwap) + { currentBlendMode = nextBlendMode; this.renderer.blendModeManager.setBlendMode( currentBlendMode ); } - if (shaderSwap) { + if (shaderSwap) + { currentShader = nextShader; shader = currentShader.shaders ? currentShader.shaders[gl.id] : currentShader; - if (!shader) { + if (!shader) + { shader = new Shader(gl, null, currentShader.fragmentSrc, currentShader.uniforms); currentShader.shaders[gl.id] = shader; } @@ -538,7 +564,8 @@ // set shader function??? this.renderer.shaderManager.setShader(shader); - if (shader.dirty) { + if (shader.dirty) + { shader.syncUniforms(); } @@ -569,17 +596,21 @@ * @param size {number} * @param startIndex {number} */ -WebGLSpriteBatch.prototype.renderBatch = function (texture, size, startIndex) { - if (size === 0) { +WebGLSpriteBatch.prototype.renderBatch = function (texture, size, startIndex) +{ + if (size === 0) + { return; } var gl = this.renderer.gl; - if (!texture._glTextures[gl.id]) { + if (!texture._glTextures[gl.id]) + { this.renderer.updateTexture(texture); } - else { + else + { // bind the current texture gl.bindTexture(gl.TEXTURE_2D, texture._glTextures[gl.id]); } @@ -594,7 +625,8 @@ /** * */ -WebGLSpriteBatch.prototype.stop = function () { +WebGLSpriteBatch.prototype.stop = function () +{ this.flush(); this.dirty = true; }; @@ -602,7 +634,8 @@ /** * */ -WebGLSpriteBatch.prototype.start = function () { +WebGLSpriteBatch.prototype.start = function () +{ this.dirty = true; }; @@ -610,7 +643,8 @@ * Destroys the SpriteBatch. * */ -WebGLSpriteBatch.prototype.destroy = function () { +WebGLSpriteBatch.prototype.destroy = function () +{ this.renderer.gl.deleteBuffer(this.vertexBuffer); this.renderer.gl.deleteBuffer(this.indexBuffer); diff --git a/src/core/textures/BaseTexture.js b/src/core/textures/BaseTexture.js index 2bf77d4..513d358 100644 --- a/src/core/textures/BaseTexture.js +++ b/src/core/textures/BaseTexture.js @@ -10,7 +10,8 @@ * @param source {Image|Canvas} the source object of the texture. * @param [scaleMode=scaleModes.DEFAULT] {number} See {@link scaleModes} for possible values */ -function BaseTexture(source, scaleMode) { +function BaseTexture(source, scaleMode) +{ this.uuid = utils.uuid(); /** @@ -123,7 +124,8 @@ this._needsUpdate = false; // if no source passed don't try to load - if (source) { + if (source) + { this.loadSource(source); } @@ -149,13 +151,16 @@ Object.defineProperties(BaseTexture.prototype, { needsUpdate: { - get: function () { + get: function () + { return this._needsUpdate; }, - set: function (val) { + set: function (val) + { this._needsUpdate = val; - if (val) { + if (val) + { this.emit('update', this); } } @@ -171,9 +176,11 @@ * * The logic state after calling `loadSource` directly or indirectly (eg. `fromImage`, `new BaseTexture`) is: * - * if (texture.hasLoaded) { + * if (texture.hasLoaded) + { * // texture ready for use - * } else if (texture.isLoading) { + * } else if (texture.isLoading) + { * // listen to 'loaded' and/or 'error' events on texture * } else { * // not loading, not going to load UNLESS the source is reloaded @@ -183,12 +190,14 @@ * @protected * @param source {Image|Canvas} the source object of the texture. */ -BaseTexture.prototype.loadSource = function (source) { +BaseTexture.prototype.loadSource = function (source) +{ var wasLoading = this.isLoading; this.hasLoaded = false; this.isLoading = false; - if (wasLoading && this.source) { + if (wasLoading && this.source) + { this.source.onload = null; this.source.onerror = null; } @@ -196,20 +205,24 @@ this.source = source; // Apply source if loaded. Otherwise setup appropriate loading monitors. - if ((this.source.complete || this.source.getContext) && this.source.width && this.source.height) { + if ((this.source.complete || this.source.getContext) && this.source.width && this.source.height) + { this._sourceLoaded(); } - else if(!source.getContext) { + else if(!source.getContext) + { // Image fail / not ready this.isLoading = true; var scope = this; - source.onload = function () { + source.onload = function () + { source.onload = null; source.onerror = null; - if(!scope.isLoading) { + if(!scope.isLoading) + { return; } @@ -219,11 +232,13 @@ scope.emit('loaded', scope); }; - source.onerror = function () { + source.onerror = function () + { source.onload = null; source.onerror = null; - if(!scope.isLoading) { + if(!scope.isLoading) + { return; } @@ -234,24 +249,29 @@ // Per http://www.w3.org/TR/html5/embedded-content-0.html#the-img-element // "The value of `complete` can thus change while a script is executing." // So complete needs to be re-checked after the callbacks have been added.. - if (source.complete) { + if (source.complete) + { this.isLoading = false; // ..and if we're complete now, no need for callbacks source.onload = null; source.onerror = null; - if (source.width && source.height) { + if (source.width && source.height) + { this._sourceLoaded(); // If any previous subscribers possible - if (wasLoading) { + if (wasLoading) + { this.emit('loaded', this); } } - else { + else + { // If any previous subscribers possible - if (wasLoading) { + if (wasLoading) + { this.emit('error', this); } } @@ -265,7 +285,8 @@ * * @private */ -BaseTexture.prototype._sourceLoaded = function () { +BaseTexture.prototype._sourceLoaded = function () +{ this.hasLoaded = true; this.width = this.source.naturalWidth || this.source.width; @@ -278,16 +299,20 @@ * Destroys this base texture * */ -BaseTexture.prototype.destroy = function () { - if (this.imageUrl) { +BaseTexture.prototype.destroy = function () +{ + if (this.imageUrl) + { delete utils.BaseTextureCache[this.imageUrl]; delete utils.TextureCache[this.imageUrl]; this.imageUrl = null; - if (!navigator.isCocoonJS) { + if (!navigator.isCocoonJS) + { this.source.src = ''; } } - else if (this.source && this.source._pixiId) { + else if (this.source && this.source._pixiId) + { delete utils.BaseTextureCache[this.source._pixiId]; } this.source = null; @@ -301,7 +326,8 @@ * memory again. * */ -BaseTexture.prototype.dispose = function () { +BaseTexture.prototype.dispose = function () +{ this.emit('dispose', this); }; @@ -311,7 +337,8 @@ * * @param newSrc {string} the path of the image */ -BaseTexture.prototype.updateSourceImage = function (newSrc) { +BaseTexture.prototype.updateSourceImage = function (newSrc) +{ this.source.src = newSrc; this.loadSource(this.source); }; @@ -326,18 +353,22 @@ * @param [scaleMode=scaleModes.DEFAULT] {number} See {@link scaleModes} for possible values * @return BaseTexture */ -BaseTexture.fromImage = function (imageUrl, crossorigin, scaleMode) { +BaseTexture.fromImage = function (imageUrl, crossorigin, scaleMode) +{ var baseTexture = utils.BaseTextureCache[imageUrl]; - if (crossorigin === undefined && imageUrl.indexOf('data:') !== 0) { + if (crossorigin === undefined && imageUrl.indexOf('data:') !== 0) + { crossorigin = true; } - if (!baseTexture) { + if (!baseTexture) + { // new Image() breaks tex loading in some versions of Chrome. // See https://code.google.com/p/chromium/issues/detail?id=238071 var image = new Image();//document.createElement('img'); - if (crossorigin) { + if (crossorigin) + { image.crossOrigin = ''; } @@ -347,7 +378,8 @@ utils.BaseTextureCache[imageUrl] = baseTexture; // if there is an @2x at the end of the url we are going to assume its a highres image - if ( imageUrl.indexOf(CONST.RETINA_PREFIX + '.') !== -1) { + if ( imageUrl.indexOf(CONST.RETINA_PREFIX + '.') !== -1) + { baseTexture.resolution = 2; } } @@ -363,14 +395,17 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return BaseTexture */ -BaseTexture.fromCanvas = function (canvas, scaleMode) { - if (!canvas._pixiId) { +BaseTexture.fromCanvas = function (canvas, scaleMode) +{ + if (!canvas._pixiId) + { canvas._pixiId = 'canvas_' + utils.uuid(); } var baseTexture = utils.BaseTextureCache[canvas._pixiId]; - if (!baseTexture) { + if (!baseTexture) + { baseTexture = new BaseTexture(canvas, scaleMode); utils.BaseTextureCache[canvas._pixiId] = baseTexture; } diff --git a/src/core/textures/RenderTexture.js b/src/core/textures/RenderTexture.js index 6dad20f..53ae796 100644 --- a/src/core/textures/RenderTexture.js +++ b/src/core/textures/RenderTexture.js @@ -46,8 +46,10 @@ * @param [scaleMode] {number} See {@link scaleModes} for possible values * @param [resolution=1] {number} The resolution of the texture being generated */ -function RenderTexture(renderer, width, height, scaleMode, resolution) { - if (!renderer) { +function RenderTexture(renderer, width, height, scaleMode, resolution) +{ + if (!renderer) + { throw new Error('Unable to create RenderTexture, you must pass a renderer into the constructor.'); } @@ -133,7 +135,8 @@ */ this.renderer = renderer; - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { var gl = this.renderer.gl; this.textureBuffer = new FilterTexture(gl, this.width * this.resolution, this.height * this.resolution, this.baseTexture.scaleMode); @@ -142,7 +145,8 @@ this.render = this.renderWebGL; this.projection = new math.Point(this.width*0.5, -this.height*0.5); } - else { + else + { this.render = this.renderCanvas; this.textureBuffer = new CanvasBuffer(this.width* this.resolution, this.height* this.resolution); this.baseTexture.source = this.textureBuffer.canvas; @@ -167,8 +171,10 @@ * @param height {number} The height to resize to. * @param updateBase {boolean} Should the baseTexture.width and height values be resized as well? */ -RenderTexture.prototype.resize = function (width, height, updateBase) { - if (width === this.width && height === this.height) { +RenderTexture.prototype.resize = function (width, height, updateBase) +{ + if (width === this.width && height === this.height) + { return; } @@ -177,17 +183,20 @@ this.width = this.frame.width = this.crop.width = width; this.height = this.frame.height = this.crop.height = height; - if (updateBase) { + if (updateBase) + { this.baseTexture.width = this.width; this.baseTexture.height = this.height; } - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { this.projection.x = this.width / 2; this.projection.y = -this.height / 2; } - if (!this.valid) { + if (!this.valid) + { return; } @@ -198,12 +207,15 @@ * Clears the RenderTexture. * */ -RenderTexture.prototype.clear = function () { - if (!this.valid) { +RenderTexture.prototype.clear = function () +{ + if (!this.valid) + { return; } - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { this.renderer.gl.bindFramebuffer(this.renderer.gl.FRAMEBUFFER, this.textureBuffer.frameBuffer); } @@ -220,19 +232,23 @@ * @param [restoreWorldTransform=true] {boolean} If true the displayObject's worldTransform/worldAlpha and all children * transformations will be restored. Not restoring this information will be a little faster. */ -RenderTexture.prototype.renderWebGL = function (displayObject, matrix, clear, restoreWorldTransform) { - if (!this.valid) { +RenderTexture.prototype.renderWebGL = function (displayObject, matrix, clear, restoreWorldTransform) +{ + if (!this.valid) + { return; } - if (typeof restoreWorldTransform === 'undefined') { + if (typeof restoreWorldTransform === 'undefined') + { restoreWorldTransform = true; } var tempAlpha, tempTransform; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { tempAlpha = displayObject.worldAlpha; tempTransform = displayObject.worldTransform.toArray(); } @@ -245,7 +261,8 @@ wt.identity(); wt.translate(0, this.projection.y * 2); - if (matrix) { + if (matrix) + { wt.append(matrix); } @@ -258,7 +275,8 @@ var children = displayObject.children; var i, j; - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } @@ -269,7 +287,8 @@ gl.bindFramebuffer(gl.FRAMEBUFFER, this.textureBuffer.frameBuffer ); - if (clear) { + if (clear) + { this.textureBuffer.clear(); } @@ -279,11 +298,13 @@ this.renderer.spriteBatch.dirty = true; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { displayObject.worldAlpha = tempAlpha; displayObject.worldTransform.fromArray(tempTransform); - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } } @@ -300,26 +321,31 @@ * @param [restoreWorldTransform=true] {boolean} If true the displayObject's worldTransform/worldAlpha and all children * transformations will be restored. Not restoring this information will be a little faster. */ -RenderTexture.prototype.renderCanvas = function (displayObject, matrix, clear, restoreWorldTransform) { - if (!this.valid) { +RenderTexture.prototype.renderCanvas = function (displayObject, matrix, clear, restoreWorldTransform) +{ + if (!this.valid) + { return; } - if (typeof restoreWorldTransform === 'undefined') { + if (typeof restoreWorldTransform === 'undefined') + { restoreWorldTransform = true; } var tempAlpha, tempTransform; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { tempAlpha = displayObject.worldAlpha; tempTransform = displayObject.worldTransform.toArray(); } var wt = displayObject.worldTransform; wt.identity(); - if (matrix) { + if (matrix) + { wt.append(matrix); } @@ -330,11 +356,13 @@ var children = displayObject.children; var i, j; - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } - if (clear) { + if (clear) + { this.textureBuffer.clear(); } @@ -348,11 +376,13 @@ this.renderer.resolution = realResolution; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { displayObject.worldAlpha = tempAlpha; displayObject.worldTransform.fromArray(tempTransform); - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } } @@ -363,7 +393,8 @@ * * @return {Image} */ -RenderTexture.prototype.getImage = function () { +RenderTexture.prototype.getImage = function () +{ var image = new Image(); image.src = this.getBase64(); return image; @@ -374,7 +405,8 @@ * * @return {string} A base64 encoded string of the texture. */ -RenderTexture.prototype.getBase64 = function () { +RenderTexture.prototype.getBase64 = function () +{ return this.getCanvas().toDataURL(); }; @@ -383,8 +415,10 @@ * * @return {HTMLCanvasElement} A Canvas element with the texture rendered on. */ -RenderTexture.prototype.getCanvas = function () { - if (this.renderer.type === CONST.WEBGL_RENDERER) { +RenderTexture.prototype.getCanvas = function () +{ + if (this.renderer.type === CONST.WEBGL_RENDERER) + { var gl = this.renderer.gl; var width = this.textureBuffer.width; var height = this.textureBuffer.height; @@ -403,7 +437,8 @@ return tempCanvas.canvas; } - else { + else + { return this.textureBuffer.canvas; } }; diff --git a/src/core/textures/Texture.js b/src/core/textures/Texture.js index 3c65909..e97f0aa 100644 --- a/src/core/textures/Texture.js +++ b/src/core/textures/Texture.js @@ -17,7 +17,8 @@ * @param [crop] {Rectangle} The area of original texture * @param [trim] {Rectangle} Trimmed texture rectangle */ -function Texture(baseTexture, frame, crop, trim) { +function Texture(baseTexture, frame, crop, trim) +{ /** * Does this Texture have any frame data assigned to it? * @@ -25,12 +26,14 @@ */ this.noFrame = false; - if (!frame) { + if (!frame) + { this.noFrame = true; frame = new math.Rectangle(0, 0, 1, 1); } - if (baseTexture instanceof Texture) { + if (baseTexture instanceof Texture) + { baseTexture = baseTexture.baseTexture; } @@ -100,13 +103,16 @@ */ this.crop = crop || new math.Rectangle(0, 0, 1, 1); - if (baseTexture.hasLoaded) { - if (this.noFrame) { + if (baseTexture.hasLoaded) + { + if (this.noFrame) + { frame = new math.Rectangle(0, 0, baseTexture.width, baseTexture.height); } this.frame = frame; } - else { + else + { baseTexture.addEventListener('loaded', this.onBaseTextureLoaded.bind(this)); } } @@ -118,19 +124,23 @@ Object.defineProperties(Texture.prototype, { needsUpdate: { - get: function () { + get: function () + { return this.baseTexture.needsUpdate; }, - set: function (val) { + set: function (val) + { this.baseTexture.needsUpdate = val; } }, frame: { - get: function () { + get: function () + { return this._frame; }, - set: function (frame) { + set: function (frame) + { this._frame = frame; this.noFrame = false; @@ -143,20 +153,23 @@ 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 (!this.trim && (frame.x + frame.width > this.baseTexture.width || frame.y + frame.height > this.baseTexture.height)) + { throw new Error('Texture Error: frame does not fit inside the base Texture dimensions ' + this); } this.valid = frame && frame.width && frame.height && this.baseTexture.source && this.baseTexture.hasLoaded; - if (this.trim) { + 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) { + if (this.valid) + { this._updateUvs(); } } @@ -168,11 +181,13 @@ * * @private */ -Texture.prototype.onBaseTextureLoaded = function () { +Texture.prototype.onBaseTextureLoaded = function () +{ var baseTexture = this.baseTexture; baseTexture.removeEventListener('loaded', this.onLoaded); - if (this.noFrame) { + if (this.noFrame) + { this.frame = new math.Rectangle(0, 0, baseTexture.width, baseTexture.height); } @@ -184,8 +199,10 @@ * * @param destroyBase {boolean} Whether to destroy the base texture as well */ -Texture.prototype.destroy = function (destroyBase) { - if (destroyBase) { +Texture.prototype.destroy = function (destroyBase) +{ + if (destroyBase) + { this.baseTexture.destroy(); } @@ -197,8 +214,10 @@ * * @private */ -Texture.prototype._updateUvs = function () { - if (!this._uvs) { +Texture.prototype._updateUvs = function () +{ + if (!this._uvs) + { this._uvs = new TextureUvs(); } @@ -229,10 +248,12 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return Texture */ -Texture.fromImage = function (imageUrl, crossorigin, scaleMode) { +Texture.fromImage = function (imageUrl, crossorigin, scaleMode) +{ var texture = utils.TextureCache[imageUrl]; - if (!texture) { + if (!texture) + { texture = new Texture(BaseTexture.fromImage(imageUrl, crossorigin, scaleMode)); utils.TextureCache[imageUrl] = texture; } @@ -248,9 +269,11 @@ * @param frameId {string} The frame id of the texture * @return Texture */ -Texture.fromFrame = function (frameId) { +Texture.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache '); } return texture; @@ -264,7 +287,8 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return {Texture} */ -Texture.fromCanvas = function (canvas, scaleMode) { +Texture.fromCanvas = function (canvas, scaleMode) +{ return new Texture(BaseTexture.fromCanvas(canvas, scaleMode)); }; @@ -276,7 +300,8 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return {Texture} A Texture */ -Texture.fromVideo = function (video, scaleMode) { +Texture.fromVideo = function (video, scaleMode) +{ return new Texture(VideoBaseTexture.baseTextureFromVideo(video, scaleMode)); }; @@ -287,7 +312,8 @@ * @param texture {Texture} The Texture to add to the cache. * @param id {string} The id that the texture will be stored against. */ -Texture.addTextureToCache = function (texture, id) { +Texture.addTextureToCache = function (texture, id) +{ utils.TextureCache[id] = texture; }; @@ -298,7 +324,8 @@ * @param id {string} The id of the texture to be removed * @return {Texture} The texture that was removed */ -Texture.removeTextureFromCache = function (id) { +Texture.removeTextureFromCache = function (id) +{ var texture = utils.TextureCache[id]; delete utils.TextureCache[id]; diff --git a/src/core/textures/TextureUvs.js b/src/core/textures/TextureUvs.js index b9bbb58..5424d52 100644 --- a/src/core/textures/TextureUvs.js +++ b/src/core/textures/TextureUvs.js @@ -1,4 +1,5 @@ -function TextureUvs() { +function TextureUvs() +{ this.x0 = 0; this.y0 = 0; diff --git a/src/core/textures/VideoBaseTexture.js b/src/core/textures/VideoBaseTexture.js index e3e0c5a..1a826a9 100644 --- a/src/core/textures/VideoBaseTexture.js +++ b/src/core/textures/VideoBaseTexture.js @@ -12,15 +12,18 @@ * @param source {HTMLVideoElement} * @param [scaleMode] {number} See {@link scaleModes} for possible values */ -function VideoBaseTexture(source, scaleMode) { - if (!source){ +function VideoBaseTexture(source, scaleMode) +{ + if (!source) + { throw new Error('No video source element specified.'); } // hook in here to check if video is already available. // BaseTexture looks for a source.complete boolean, plus width & height. - if ((source.readyState === source.HAVE_ENOUGH_DATA || source.readyState === source.HAVE_FUTURE_DATA) && source.width && source.height) { + if ((source.readyState === source.HAVE_ENOUGH_DATA || source.readyState === source.HAVE_FUTURE_DATA) && source.width && source.height) + { source.complete = true; } @@ -31,7 +34,8 @@ this._boundOnUpdate = this._onUpdate.bind(this); this._boundOnCanPlay = this._onCanPlay.bind(this); - if (!source.complete) { + if (!source.complete) + { source.addEventListener('canplay', this._boundOnCanPlay); source.addEventListener('canplaythrough', this._boundOnCanPlay); @@ -47,28 +51,35 @@ VideoBaseTexture.prototype.constructor = VideoBaseTexture; module.exports = VideoBaseTexture; -VideoBaseTexture.prototype._onUpdate = function () { - if (this.autoUpdate) { +VideoBaseTexture.prototype._onUpdate = function () +{ + if (this.autoUpdate) + { window.requestAnimationFrame(this._boundOnUpdate); this.needsUpdate = true; } }; -VideoBaseTexture.prototype._onPlayStart = function () { - if (!this.autoUpdate) { +VideoBaseTexture.prototype._onPlayStart = function () +{ + if (!this.autoUpdate) + { window.requestAnimationFrame(this._boundOnUpdate); this.autoUpdate = true; } }; -VideoBaseTexture.prototype._onPlayStop = function () { +VideoBaseTexture.prototype._onPlayStop = function () +{ this.autoUpdate = false; }; -VideoBaseTexture.prototype._onCanPlay = function () { +VideoBaseTexture.prototype._onCanPlay = function () +{ this.hasLoaded = true; - if (this.source) { + if (this.source) + { this.source.removeEventListener('canplay', this._boundOnCanPlay); this.source.removeEventListener('canplaythrough', this._boundOnCanPlay); @@ -78,15 +89,18 @@ this.source.play(); // prevent multiple loaded dispatches.. - if(!this.__loaded){ + if(!this.__loaded) + { this.__loaded = true; this.emit('loaded', this); } } }; -VideoBaseTexture.prototype.destroy = function () { - if (this.source && this.source._pixiId) { +VideoBaseTexture.prototype.destroy = function () +{ + if (this.source && this.source._pixiId) + { utils.BaseTextureCache[ this.source._pixiId ] = null; delete utils.BaseTextureCache[ this.source._pixiId ]; @@ -105,14 +119,17 @@ * @param scaleMode {number} See {@link scaleModes} for possible values * @return {VideoBaseTexture} */ -VideoBaseTexture.fromVideo = function (video, scaleMode) { - if (!video._pixiId) { +VideoBaseTexture.fromVideo = function (video, scaleMode) +{ + if (!video._pixiId) + { video._pixiId = 'video_' + utils.uuid(); } var baseTexture = utils.BaseTextureCache[video._pixiId]; - if (!baseTexture) { + if (!baseTexture) + { baseTexture = new VideoBaseTexture(video, scaleMode); utils.BaseTextureCache[ video._pixiId ] = baseTexture; } @@ -147,17 +164,21 @@ * @param scaleMode {number} See {@link scaleModes} for possible values * @return {VideoBaseTexture} */ -VideoBaseTexture.fromUrl = function (videoSrc, scaleMode) { +VideoBaseTexture.fromUrl = function (videoSrc, scaleMode) +{ var video = document.createElement('video'); // array of objects or strings - if (Array.isArray(videoSrc)) { - for (var i = 0; i < videoSrc.length; ++i) { + if (Array.isArray(videoSrc)) + { + for (var i = 0; i < videoSrc.length; ++i) + { video.appendChild(createSource(videoSrc.src || videoSrc, videoSrc.mime)); } } // single object or string - else { + else + { video.appendChild(createSource(videoSrc.src || videoSrc, videoSrc.mime)); } @@ -169,8 +190,10 @@ VideoBaseTexture.fromUrls = VideoBaseTexture.fromUrl; -function createSource(path, type) { - if (!type) { +function createSource(path, type) +{ + if (!type) + { type = 'video/' + path.substr(path.lastIndexOf('.') + 1); } diff --git a/src/core/utils/EventData.js b/src/core/utils/EventData.js index 5d55a22..8cdf701 100644 --- a/src/core/utils/EventData.js +++ b/src/core/utils/EventData.js @@ -7,7 +7,8 @@ * @param name {string} The string name of the event that was triggered * @param data {object} Arbitrary event data to pass along */ -function EventData(target, name, data) { +function EventData(target, name, data) +{ // for duck typing in the ".on()" function this.__isEventObject = true; @@ -71,7 +72,8 @@ * Stops the propagation of events up the scene graph (prevents bubbling). * */ -EventData.prototype.stopPropagation = function stopPropagation() { +EventData.prototype.stopPropagation = function stopPropagation() +{ this.stopped = true; }; @@ -79,6 +81,7 @@ * Stops the propagation of events to sibling listeners (no longer calls any listeners). * */ -EventData.prototype.stopImmediatePropagation = function stopImmediatePropagation() { +EventData.prototype.stopImmediatePropagation = function stopImmediatePropagation() +{ this.stoppedImmediate = true; }; diff --git a/src/core/utils/EventTarget.js b/src/core/utils/EventTarget.js index 7ae8820..671a151 100644 --- a/src/core/utils/EventTarget.js +++ b/src/core/utils/EventTarget.js @@ -13,14 +13,16 @@ * var em = new MyEmitter(); * em.emit('eventName', 'some data', 'some more data', {}, null, ...); */ -function eventTarget(obj) { +function eventTarget(obj) +{ /** * Return a list of assigned event listeners. * * @param eventName {string} The events that should be listed. * @return {Array} An array of listener functions */ - obj.listeners = function listeners(eventName) { + obj.listeners = function listeners(eventName) + { this._listeners = this._listeners || {}; return this._listeners[eventName] ? this._listeners[eventName].slice() : []; @@ -33,22 +35,26 @@ * @param eventName {string} The name of the event. * @return {boolean} Indication if we've emitted an event. */ - obj.emit = obj.dispatchEvent = function emit(eventName, data) { + obj.emit = obj.dispatchEvent = function emit(eventName, data) + { this._listeners = this._listeners || {}; // fast return when there are no listeners - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return; } //backwards compat with old method ".emit({ type: 'something' })" - if (typeof eventName === 'object') { + if (typeof eventName === 'object') + { data = eventName; eventName = eventName.type; } //ensure we are using a real pixi event - if (!data || data.__isEventObject !== true) { + if (!data || data.__isEventObject !== true) + { data = new EventData(this, eventName, data); } @@ -58,23 +64,27 @@ fn = listeners[0], i; - for (i = 0; i < length; fn = listeners[++i]) { + for (i = 0; i < length; fn = listeners[++i]) + { //call the event listener fn.call(this, data); //if "stopImmediatePropagation" is called, stop calling sibling events - if (data.stoppedImmediate) { + if (data.stoppedImmediate) + { return this; } } //if "stopPropagation" is called then don't bubble the event - if (data.stopped) { + if (data.stopped) + { return this; } //bubble this event up the scene graph - if (this.parent && this.parent.emit) { + if (this.parent && this.parent.emit) + { this.parent.emit.call(this.parent, eventName, data); } @@ -88,7 +98,8 @@ * @param eventName {string} Name of the event. * @param callback {Functon} fn Callback function. */ - obj.on = obj.addEventListener = function on(eventName, fn) { + obj.on = obj.addEventListener = function on(eventName, fn) + { this._listeners = this._listeners || {}; (this._listeners[eventName] = this._listeners[eventName] || []) @@ -103,11 +114,13 @@ * @param eventName {string} Name of the event. * @param callback {Function} Callback function. */ - obj.once = function once(eventName, fn) { + obj.once = function once(eventName, fn) + { this._listeners = this._listeners || {}; var self = this; - function onceHandlerWrapper() { + function onceHandlerWrapper() + { fn.apply(self.off(eventName, onceHandlerWrapper), arguments); } onceHandlerWrapper._originalHandler = fn; @@ -122,23 +135,28 @@ * @param eventName {string} The event we want to remove. * @param callback {Function} The listener that we need to find. */ - obj.off = obj.removeEventListener = function off(eventName, fn) { + obj.off = obj.removeEventListener = function off(eventName, fn) + { this._listeners = this._listeners || {}; - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return this; } var list = this._listeners[eventName], i = fn ? list.length : 0; - while(i-- > 0) { - if (list[i] === fn || list[i]._originalHandler === fn) { + while(i-- > 0) + { + if (list[i] === fn || list[i]._originalHandler === fn) + { list.splice(i, 1); } } - if (list.length === 0) { + if (list.length === 0) + { delete this._listeners[eventName]; } @@ -150,10 +168,12 @@ * * @param eventName {string} The event you want to remove all listeners for. */ - obj.removeAllListeners = function removeAllListeners(eventName) { + obj.removeAllListeners = function removeAllListeners(eventName) + { this._listeners = this._listeners || {}; - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return this; } @@ -169,7 +189,8 @@ * * @param object {object} The obj to mix into */ - mixin: function mixin(obj) { + mixin: function mixin(obj) + { eventTarget(obj); } }; diff --git a/src/core/utils/PolyK.js b/src/core/utils/PolyK.js index 7325141..5e20c2b 100644 --- a/src/core/utils/PolyK.js +++ b/src/core/utils/PolyK.js @@ -47,7 +47,8 @@ * Triangulates shapes for webGL graphic fills. * */ -PolyK.Triangulate = function (p) { +PolyK.Triangulate = function (p) +{ var sign = true; var n = p.length >> 1; @@ -59,7 +60,8 @@ i = 0; var al = n; - while(al > 3) { + while(al > 3) + { var i0 = avl[(i+0)%al]; var i1 = avl[(i+1)%al]; var i2 = avl[(i+2)%al]; @@ -69,29 +71,35 @@ var cx = p[2*i2], cy = p[2*i2+1]; var earFound = false; - if (PolyK._convex(ax, ay, bx, by, cx, cy, sign)) { + if (PolyK._convex(ax, ay, bx, by, cx, cy, sign)) + { earFound = true; - for (var j = 0; j < al; j++) { + for (var j = 0; j < al; j++) + { var vi = avl[j]; if (vi === i0 || vi === i1 || vi === i2) continue; - if (PolyK._PointInTriangle(p[2*vi], p[2*vi+1], ax, ay, bx, by, cx, cy)) { + if (PolyK._PointInTriangle(p[2*vi], p[2*vi+1], ax, ay, bx, by, cx, cy)) + { earFound = false; break; } } } - if (earFound) { + if (earFound) + { tgs.push(i0, i1, i2); avl.splice((i+1)%al, 1); al--; i = 0; } - else if (i++ > 3*al) { + else if (i++ > 3*al) + { // need to flip flip reverse it! // reset! - if (sign) { + if (sign) + { tgs = []; avl = []; for (i = 0; i < n; i++) avl.push(i); @@ -101,7 +109,8 @@ sign = false; } - else { + else + { // window.console.log("PIXI Warning: shape too complex to fill"); return null; } @@ -126,7 +135,8 @@ * @private * @return {boolean} */ -PolyK._PointInTriangle = function (px, py, ax, ay, bx, by, cx, cy) { +PolyK._PointInTriangle = function (px, py, ax, ay, bx, by, cx, cy) +{ var v0x = cx-ax; var v0y = cy-ay; var v1x = bx-ax; @@ -154,6 +164,7 @@ * @private * @return {boolean} */ -PolyK._convex = function (ax, ay, bx, by, cx, cy, sign) { +PolyK._convex = function (ax, ay, bx, by, cx, cy, sign) +{ return ((ay-by)*(cx-bx) + (bx-ax)*(cy-by) >= 0) === sign; }; diff --git a/src/core/utils/index.js b/src/core/utils/index.js index ade9831..bfae7ae 100644 --- a/src/core/utils/index.js +++ b/src/core/utils/index.js @@ -16,7 +16,8 @@ * * @return {number} The next uuid to use. */ - uuid: function () { + uuid: function () + { return ++utils._uid; }, @@ -26,7 +27,8 @@ * @param hex {number} * @return {number[]} An array representing the [R, G, B] of the color. */ - hex2rgb: function (hex, out) { + hex2rgb: function (hex, out) + { out = out || []; out[0] = (hex >> 16 & 0xFF) / 255; @@ -42,7 +44,8 @@ * @param hex {number} * @return {string} The string color. */ - hex2string: function (hex) { + hex2string: function (hex) + { hex = hex.toString(16); hex = '000000'.substr(0, 6 - hex.length) + hex; @@ -55,7 +58,8 @@ * @param rgb {number[]} * @return {number} The color number */ - rgb2hex: function (rgb) { + rgb2hex: function (rgb) + { return ((rgb[0]*255 << 16) + (rgb[1]*255 << 8) + rgb[2]*255); }, @@ -64,8 +68,10 @@ * * @return {boolean} whether they are supported */ - canUseNewCanvasBlendModes: function () { - if (typeof document === 'undefined') { + canUseNewCanvasBlendModes: function () + { + if (typeof document === 'undefined') + { return false; } @@ -93,15 +99,19 @@ * @param number {number} * @return {number} the closest number that is a power of two */ - getNextPowerOfTwo: function (number) { + getNextPowerOfTwo: function (number) + { // see: http://en.wikipedia.org/wiki/Power_of_two#Fast_algorithm_to_check_if_a_positive_number_is_a_power_of_two - if (number > 0 && (number & (number - 1)) === 0) { + if (number > 0 && (number & (number - 1)) === 0) + { return number; } - else { + else + { var result = 1; - while (result < number) { + while (result < number) + { result <<= 1; } @@ -116,7 +126,8 @@ * @param height {number} * @return {boolean} */ - isPowerOfTwo: function (width, height) { + isPowerOfTwo: function (width, height) + { return (width > 0 && (width & (width - 1)) === 0 && height > 0 && (height & (height - 1)) === 0); }, @@ -130,12 +141,15 @@ * @constant * @static */ - sayHello: function (type) { - if (utils._saidHello) { + sayHello: function (type) + { + if (utils._saidHello) + { return; } - if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) { + if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) + { var args = [ '%c %c %c Pixi.js ' + CONST.VERSION + ' - ' + type + ' %c ' + ' %c ' + ' http://www.pixijs.com/ %c %c ♥%c♥%c♥ ', 'background: #ff66a5', @@ -151,7 +165,8 @@ console.log.apply(console, args); //jshint ignore:line } - else if (window.console) { + else if (window.console) + { console.log('Pixi.js ' + CONST.VERSION + ' - ' + type + ' - http://www.pixijs.com/'); //jshint ignore:line } @@ -166,15 +181,19 @@ * @class * @namespace PIXI */ - AjaxRequest: function () { + AjaxRequest: function () + { var activexmodes = ['Msxml2.XMLHTTP.6.0', 'Msxml2.XMLHTTP.3.0', 'Microsoft.XMLHTTP']; //activeX versions to check for in IE - if (window.ActiveXObject) { //Test for support for ActiveXObject in IE first (as XMLHttpRequest in IE7 is broken) - for (var i=0; i= this.textures.length) { + else if (round >= this.textures.length) + { this.gotoAndStop(this.textures.length - 1); - if (this.onComplete) { + if (this.onComplete) + { this.onComplete(); } } @@ -167,10 +182,12 @@ * @static * @param frames {string[]} the array of frames ids the movieclip will use as its texture frames */ -MovieClip.fromFrames = function (frames) { +MovieClip.fromFrames = function (frames) +{ var textures = []; - for (var i = 0; i < frames.length; ++i) { + for (var i = 0; i < frames.length; ++i) + { textures.push(new core.Texture.fromFrame(frames[i])); } @@ -183,10 +200,12 @@ * @static * @param images {string[]} the array of image urls the movieclip will use as its texture frames */ -MovieClip.fromImages = function (images) { +MovieClip.fromImages = function (images) +{ var textures = []; - for (var i = 0; i < images.length; ++i) { + for (var i = 0; i < images.length; ++i) + { textures.push(new core.Texture.fromImage(images[i])); } diff --git a/src/extras/Rope.js b/src/extras/Rope.js index c157ec4..9c87bc0 100644 --- a/src/extras/Rope.js +++ b/src/extras/Rope.js @@ -9,7 +9,8 @@ * @param {Array} points - An array of {Point}. * */ -function Rope(texture, points) { +function Rope(texture, points) +{ Strip.call(this, texture); this.points = points; @@ -31,10 +32,12 @@ * Refreshes * */ -Rope.prototype.refresh = function () { +Rope.prototype.refresh = function () +{ var points = this.points; - if (points.length < 1) { + if (points.length < 1) + { return; } @@ -59,20 +62,23 @@ var total = points.length, point, index, amount; - for (var i = 1; i < total; i++) { + for (var i = 1; i < total; i++) + { point = points[i]; index = i * 4; // time to do some smart drawing! amount = i / (total-1); - if (i%2) { + if (i%2) + { uvs[index] = amount; uvs[index+1] = 0; uvs[index+2] = amount; uvs[index+3] = 1; } - else { + else + { uvs[index] = amount; uvs[index+1] = 0; @@ -95,10 +101,12 @@ * * @private */ -Rope.prototype.updateTransform = function () { +Rope.prototype.updateTransform = function () +{ var points = this.points; - if (points.length < 1) { + if (points.length < 1) + { return; } @@ -113,14 +121,17 @@ var total = points.length, point, index, ratio, perpLength, num; - for (var i = 0; i < total; i++) { + for (var i = 0; i < total; i++) + { point = points[i]; index = i * 4; - if (i < points.length-1) { + if (i < points.length-1) + { nextPoint = points[i+1]; } - else { + else + { nextPoint = point; } @@ -129,7 +140,8 @@ ratio = (1 - (i / (total-1))) * 10; - if (ratio > 1) { + if (ratio > 1) + { ratio = 1; } @@ -157,7 +169,8 @@ * * @param texture {Texture} the texture that will be used */ -Rope.prototype.setTexture = function (texture) { +Rope.prototype.setTexture = function (texture) +{ // stop current texture this.texture = texture; //this.updateFrame = true; diff --git a/src/extras/Strip.js b/src/extras/Strip.js index c5e378f..57691b5 100644 --- a/src/extras/Strip.js +++ b/src/extras/Strip.js @@ -10,7 +10,8 @@ * @param height {number} the height * */ -function Strip(texture) { +function Strip(texture) +{ core.DisplayObjectContainer.call(this); /** @@ -70,9 +71,11 @@ * * @param renderer {WebGLRenderer} */ -Strip.prototype.renderWebGL = function (renderer) { +Strip.prototype.renderWebGL = function (renderer) +{ // if the sprite is not visible or the alpha is 0 then no need to render this element - if (!this.visible || this.alpha <= 0) { + if (!this.visible || this.alpha <= 0) + { return; } @@ -81,7 +84,8 @@ renderer.spriteBatch.stop(); // init! init! - if (!this._vertexBuffer) { + if (!this._vertexBuffer) + { this._initWebGL(renderer); } @@ -96,7 +100,8 @@ //TODO check culling }; -Strip.prototype._initWebGL = function (renderer) { +Strip.prototype._initWebGL = function (renderer) +{ // build the strip! var gl = renderer.gl; @@ -118,7 +123,8 @@ gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this.indices, gl.STATIC_DRAW); }; -Strip.prototype._renderStrip = function (renderer) { +Strip.prototype._renderStrip = function (renderer) +{ var gl = renderer.gl; var projection = renderer.projection, offset = renderer.offset, @@ -137,7 +143,8 @@ gl.uniform2f(shader.offsetVector, -offset.x, -offset.y); gl.uniform1f(shader.alpha, this.worldAlpha); - if (!this.dirty) { + if (!this.dirty) + { gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexBuffer); gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); @@ -150,10 +157,12 @@ gl.activeTexture(gl.TEXTURE0); // check if a texture is dirty.. - if (this.texture.baseTexture._dirty[gl.id]) { + if (this.texture.baseTexture._dirty[gl.id]) + { renderer.updateTexture(this.texture.baseTexture); } - else { + else + { // bind the current texture gl.bindTexture(gl.TEXTURE_2D, this.texture.baseTexture._glTextures[gl.id]); } @@ -163,7 +172,8 @@ } - else { + else + { this.dirty = false; gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexBuffer); @@ -178,10 +188,12 @@ gl.activeTexture(gl.TEXTURE0); // check if a texture is dirty.. - if (this.texture.baseTexture._dirty[gl.id]) { + if (this.texture.baseTexture._dirty[gl.id]) + { renderer.updateTexture(this.texture.baseTexture); } - else { + else + { gl.bindTexture(gl.TEXTURE_2D, this.texture.baseTexture._glTextures[gl.id]); } @@ -203,27 +215,33 @@ * * @param renderer {CanvasRenderer} */ -Strip.prototype.renderCanvas = function (renderer) { +Strip.prototype.renderCanvas = function (renderer) +{ var context = renderer.context; var transform = this.worldTransform; - if (renderer.roundPixels) { + if (renderer.roundPixels) + { context.setTransform(transform.a, transform.b, transform.c, transform.d, transform.tx | 0, transform.ty | 0); } - else { + else + { context.setTransform(transform.a, transform.b, transform.c, transform.d, transform.tx, transform.ty); } - if (this.drawMode === Strip.DrawModes.TRIANGLE_STRIP) { + if (this.drawMode === Strip.DrawModes.TRIANGLE_STRIP) + { this._renderCanvasTriangleStrip(context); } - else { + else + { this._renderCanvasTriangles(context); } }; -Strip.prototype._renderCanvasTriangleStrip = function (context) { +Strip.prototype._renderCanvasTriangleStrip = function (context) +{ // draw triangles!! var vertices = this.vertices; var uvs = this.uvs; @@ -231,14 +249,16 @@ var length = vertices.length / 2; // this.count++; - for (var i = 0; i < length - 2; i++) { + for (var i = 0; i < length - 2; i++) + { // draw some triangles! var index = i * 2; this._renderCanvasDrawTriangle(context, vertices, uvs, index, (index + 2), (index + 4)); } }; -Strip.prototype._renderCanvasTriangles = function (context) { +Strip.prototype._renderCanvasTriangles = function (context) +{ // draw triangles!! var vertices = this.vertices; var uvs = this.uvs; @@ -247,14 +267,16 @@ var length = indices.length; // this.count++; - for (var i = 0; i < length; i += 3) { + for (var i = 0; i < length; i += 3) + { // draw some triangles! var index0 = indices[i] * 2, index1 = indices[i + 1] * 2, index2 = indices[i + 2] * 2; this._renderCanvasDrawTriangle(context, vertices, uvs, index0, index1, index2); } }; -Strip.prototype._renderCanvasDrawTriangle = function (context, vertices, uvs, index0, index1, index2) { +Strip.prototype._renderCanvasDrawTriangle = function (context, vertices, uvs, index0, index1, index2) +{ var textureSource = this.texture.baseTexture.source; var textureWidth = this.texture.width; var textureHeight = this.texture.height; @@ -265,7 +287,8 @@ var u0 = uvs[index0] * textureWidth, u1 = uvs[index1] * textureWidth, u2 = uvs[index2] * textureWidth; var v0 = uvs[index0 + 1] * textureHeight, v1 = uvs[index1 + 1] * textureHeight, v2 = uvs[index2 + 1] * textureHeight; - if (this.canvasPadding > 0) { + if (this.canvasPadding > 0) + { var paddingX = this.canvasPadding / this.worldTransform.a; var paddingY = this.canvasPadding / this.worldTransform.d; var centerX = (x0 + x1 + x2) / 3; @@ -332,7 +355,8 @@ * @param strip {Strip} The Strip to render * @private */ -Strip.prototype.renderStripFlat = function (strip) { +Strip.prototype.renderStripFlat = function (strip) +{ var context = this.context; var vertices = strip.vertices; @@ -340,7 +364,8 @@ // this.count++; context.beginPath(); - for (var i=1; i < length-2; i++) { + for (var i=1; i < length-2; i++) + { // draw some triangles! var index = i*2; @@ -358,7 +383,8 @@ }; /* -Strip.prototype.setTexture = function (texture) { +Strip.prototype.setTexture = function (texture) +{ //TODO SET THE TEXTURES //TODO VISIBILITY @@ -377,7 +403,8 @@ * @private */ -Strip.prototype.onTextureUpdate = function () { +Strip.prototype.onTextureUpdate = function () +{ this.updateFrame = true; }; @@ -387,7 +414,8 @@ * @param matrix {Matrix} the transformation matrix of the sprite * @return {Rectangle} the framing rectangle */ -Strip.prototype.getBounds = function (matrix) { +Strip.prototype.getBounds = function (matrix) +{ var worldTransform = matrix || this.worldTransform; var a = worldTransform.a; @@ -404,7 +432,8 @@ var minY = Infinity; var vertices = this.vertices; - for (var i = 0, n = vertices.length; i < n; i += 2) { + for (var i = 0, n = vertices.length; i < n; i += 2) + { var rawX = vertices[i], rawY = vertices[i + 1]; var x = (a * rawX) + (c * rawY) + tx; var y = (d * rawY) + (b * rawX) + ty; @@ -416,7 +445,8 @@ maxY = y > maxY ? y : maxY; } - if (minX === -Infinity || maxY === Infinity) { + if (minX === -Infinity || maxY === Infinity) + { return core.math.Rectangle.EMPTY; } diff --git a/src/extras/TilingSprite.js b/src/extras/TilingSprite.js index 3ac22df..31da393 100644 --- a/src/extras/TilingSprite.js +++ b/src/extras/TilingSprite.js @@ -10,7 +10,8 @@ * @param width {number} the width of the tiling sprite * @param height {number} the height of the tiling sprite */ -function TilingSprite(texture, width, height) { +function TilingSprite(texture, width, height) +{ core.Sprite.call( this, texture); /** @@ -86,10 +87,12 @@ * @memberof TilingSprite# */ width: { - get: function () { + get: function () + { return this._width; }, - set: function (value) { + set: function (value) + { this._width = value; } }, @@ -101,20 +104,25 @@ * @memberof TilingSprite# */ height: { - get: function () { + get: function () + { return this._height; }, - set: function (value) { + set: function (value) + { this._height = value; } }, texture: { - get: function () { + get: function () + { return this._texture; }, - set: function (value) { - if (this._texture === value) { + set: function (value) + { + if (this._texture === value) + { return; } @@ -130,51 +138,61 @@ * * @param renderer {WebGLRenderer} */ -TilingSprite.prototype.renderWebGL = function (renderer) { - if (!this.visible || this.alpha <= 0) { +TilingSprite.prototype.renderWebGL = function (renderer) +{ + if (!this.visible || this.alpha <= 0) + { return; } var i, j; - if (this._mask) { + if (this._mask) + { renderer.spriteBatch.stop(); renderer.maskManager.pushMask(this.mask, renderer); renderer.spriteBatch.start(); } - if (this._filters) { + if (this._filters) + { renderer.spriteBatch.flush(); renderer.filterManager.pushFilter(this._filterBlock); } - if (!this.tilingTexture || this.refreshTexture) { + if (!this.tilingTexture || this.refreshTexture) + { this.generateTilingTexture(true); - if (this.tilingTexture && this.tilingTexture.needsUpdate) { + if (this.tilingTexture && this.tilingTexture.needsUpdate) + { //TODO - tweaking renderer.updateTexture(this.tilingTexture.baseTexture); this.tilingTexture.needsUpdate = false; // this.tilingTexture._uvs = null; } } - else { + else + { renderer.spriteBatch.renderTilingSprite(this); } // simple render children! - for (i=0,j=this.children.length; i= 0; i--) { + for (var i = length - 1; i >= 0; i--) + { var child = children[i]; // push all interactive bits - if (child._interactive) { + if (child._interactive) + { iParent.interactiveChildren = true; //child.__iParent = iParent; this.interactiveItems.push(child); - if (child.children.length > 0) { + if (child.children.length > 0) + { this.collectInteractiveSprite(child, child); } } - else { + else + { child.__iParent = null; - if (child.children.length > 0) { + if (child.children.length > 0) + { this.collectInteractiveSprite(child, iParent); } } @@ -189,7 +196,8 @@ * @param [resolution=1] {number} THe resolution of the new element (relative to the canvas). * @private */ -InteractionManager.prototype.setTargetElement = function (element, resolution) { +InteractionManager.prototype.setTargetElement = function (element, resolution) +{ this.removeEvents(); this.interactionDOMElement = element; @@ -203,12 +211,15 @@ * * @private */ -InteractionManager.prototype.addEvents = function () { - if (!this.interactionDOMElement) { +InteractionManager.prototype.addEvents = function () +{ + if (!this.interactionDOMElement) + { return; } - if (window.navigator.msPointerEnabled) { + if (window.navigator.msPointerEnabled) + { this.interactionDOMElement.style['-ms-content-zooming'] = 'none'; this.interactionDOMElement.style['-ms-touch-action'] = 'none'; } @@ -230,12 +241,15 @@ * * @private */ -InteractionManager.prototype.removeEvents = function () { - if (!this.interactionDOMElement) { +InteractionManager.prototype.removeEvents = function () +{ + if (!this.interactionDOMElement) + { return; } - if (window.navigator.msPointerEnabled) { + if (window.navigator.msPointerEnabled) + { this.interactionDOMElement.style['-ms-content-zooming'] = ''; this.interactionDOMElement.style['-ms-touch-action'] = ''; } @@ -260,8 +274,10 @@ * * @private */ -InteractionManager.prototype.update = function () { - if (!this.interactionDOMElement) { +InteractionManager.prototype.update = function () +{ + if (!this.interactionDOMElement) + { return; } @@ -269,7 +285,8 @@ var now = Date.now(); var diff = now - this.last; diff = (diff * INTERACTION_FREQUENCY ) / 1000; - if (diff < 1) { + if (diff < 1) + { return; } @@ -280,7 +297,8 @@ // ok.. so mouse events?? // yes for now :) // OPTIMISE - how often to check?? - if (this.dirty) { + if (this.dirty) + { this.rebuildInteractiveGraph(); } @@ -289,7 +307,8 @@ var cursor = 'inherit'; var over = false; - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { var item = this.interactiveItems[i]; // OPTIMISATION - only calculate every time if the mousemove function exists.. @@ -302,26 +321,34 @@ this.mouse.target = item; // ok so deal with interactions.. // looks like there was a hit! - if (item.__hit && !over) { - if (item.buttonMode) { + if (item.__hit && !over) + { + if (item.buttonMode) + { cursor = item.defaultCursor; } - if (!item.interactiveChildren) { + if (!item.interactiveChildren) + { over = true; } - if (!item.__isOver) { - if (item.mouseover) { + if (!item.__isOver) + { + if (item.mouseover) + { item.mouseover (this.mouse); } item.__isOver = true; } } - else { - if (item.__isOver) { + else + { + if (item.__isOver) + { // roll out! - if (item.mouseout) { + if (item.mouseout) + { item.mouseout (this.mouse); } item.__isOver = false; @@ -329,7 +356,8 @@ } } - if (this.currentCursorStyle !== cursor) { + if (this.currentCursorStyle !== cursor) + { this.currentCursorStyle = cursor; this.interactionDOMElement.style.cursor = cursor; } @@ -338,18 +366,21 @@ /** * @private */ -InteractionManager.prototype.rebuildInteractiveGraph = function () { +InteractionManager.prototype.rebuildInteractiveGraph = function () +{ this.dirty = false; var len = this.interactiveItems.length; - for (var i = 0; i < len; i++) { + for (var i = 0; i < len; i++) + { this.interactiveItems[i].interactiveChildren = false; } this.interactiveItems.length = 0; - if (this.stage.interactive) { + if (this.stage.interactive) + { this.interactiveItems.push(this.stage); } @@ -363,8 +394,10 @@ * @param event {Event} The DOM event of the mouse moving * @private */ -InteractionManager.prototype.onMouseMove = function (event) { - if (this.dirty) { +InteractionManager.prototype.onMouseMove = function (event) +{ + if (this.dirty) + { this.rebuildInteractiveGraph(); } @@ -378,11 +411,13 @@ var length = this.interactiveItems.length; - for (var i = 0; i < length; i++) { + for (var i = 0; i < length; i++) + { var item = this.interactiveItems[i]; // Call the function! - if (item.mousemove) { + if (item.mousemove) + { item.mousemove(this.mouse); } } @@ -394,14 +429,17 @@ * @param event {Event} The DOM event of a mouse button being pressed down * @private */ -InteractionManager.prototype.onMouseDown = function (event) { - if (this.dirty) { +InteractionManager.prototype.onMouseDown = function (event) +{ + if (this.dirty) + { this.rebuildInteractiveGraph(); } this.mouse.originalEvent = event; - if (AUTO_PREVENT_DEFAULT) { + if (AUTO_PREVENT_DEFAULT) + { this.mouse.originalEvent.preventDefault(); } @@ -420,22 +458,27 @@ // while // hit test - for (var i = 0; i < length; i++) { + for (var i = 0; i < length; i++) + { var item = this.interactiveItems[i]; - if (item[downFunction] || item[clickFunction]) { + if (item[downFunction] || item[clickFunction]) + { item[buttonIsDown] = true; item.__hit = this.hitTest(item, this.mouse); - if (item.__hit) { + if (item.__hit) + { //call the function! - if (item[downFunction]) { + if (item[downFunction]) + { item[downFunction](this.mouse); } item[isDown] = true; // just the one! - if (!item.interactiveChildren) { + if (!item.interactiveChildren) + { break; } } @@ -449,8 +492,10 @@ * @param event {Event} The DOM event of a mouse being moved out * @private */ -InteractionManager.prototype.onMouseOut = function (event) { - if (this.dirty) { +InteractionManager.prototype.onMouseOut = function (event) +{ + if (this.dirty) + { this.rebuildInteractiveGraph(); } @@ -460,11 +505,14 @@ this.interactionDOMElement.style.cursor = 'inherit'; - for (var i = 0; i < length; i++) { + for (var i = 0; i < length; i++) + { var item = this.interactiveItems[i]; - if (item.__isOver) { + if (item.__isOver) + { this.mouse.target = item; - if (item.mouseout) { + if (item.mouseout) + { item.mouseout(this.mouse); } item.__isOver = false; @@ -484,8 +532,10 @@ * @param event {Event} The DOM event of a mouse button being released * @private */ -InteractionManager.prototype.onMouseUp = function (event) { - if (this.dirty) { +InteractionManager.prototype.onMouseUp = function (event) +{ + if (this.dirty) + { this.rebuildInteractiveGraph(); } @@ -502,30 +552,40 @@ var upOutsideFunction = isRightButton ? 'rightupoutside' : 'mouseupoutside'; var isDown = isRightButton ? '__isRightDown' : '__isDown'; - for (var i = 0; i < length; i++) { + for (var i = 0; i < length; i++) + { var item = this.interactiveItems[i]; - if (item[clickFunction] || item[upFunction] || item[upOutsideFunction]) { + if (item[clickFunction] || item[upFunction] || item[upOutsideFunction]) + { item.__hit = this.hitTest(item, this.mouse); - if (item.__hit && !up) { + if (item.__hit && !up) + { //call the function! - if (item[upFunction]) { + if (item[upFunction]) + { item[upFunction](this.mouse); } - if (item[isDown]) { - if (item[clickFunction]) { + if (item[isDown]) + { + if (item[clickFunction]) + { item[clickFunction](this.mouse); } } - if (!item.interactiveChildren) { + if (!item.interactiveChildren) + { up = true; } } - else { - if (item[isDown]) { - if (item[upOutsideFunction]) { + else + { + if (item[isDown]) + { + if (item[upOutsideFunction]) + { item[upOutsideFunction](this.mouse); } } @@ -543,10 +603,12 @@ * @param interactionData {InteractionData} The interactionData object to update in the case there is a hit * @private */ -InteractionManager.prototype.hitTest = function (item, interactionData) { +InteractionManager.prototype.hitTest = function (item, interactionData) +{ var global = interactionData.global; - if (!item.worldVisible) { + if (!item.worldVisible) + { return false; } @@ -560,37 +622,46 @@ interactionData.target = item; //a sprite or display object with a hit area defined - if (item.hitArea && item.hitArea.contains) { + if (item.hitArea && item.hitArea.contains) + { return item.hitArea.contains(x, y); } // a sprite with no hitarea defined - else if (item instanceof core.Sprite) { + else if (item instanceof core.Sprite) + { var width = item.texture.frame.width; var height = item.texture.frame.height; var x1 = -width * item.anchor.x; var y1; - if (x > x1 && x < x1 + width) { + if (x > x1 && x < x1 + width) + { y1 = -height * item.anchor.y; - if (y > y1 && y < y1 + height) { + if (y > y1 && y < y1 + height) + { // set the target property if a hit is true! return true; } } } - else if (item instanceof core.Graphics) { + else if (item instanceof core.Graphics) + { var graphicsData = item.graphicsData; - for (i = 0; i < graphicsData.length; i++) { + for (i = 0; i < graphicsData.length; i++) + { var data = graphicsData[i]; - if (!data.fill) { + if (!data.fill) + { continue; } // only deal with fills.. - if (data.shape) { - if (data.shape.contains(x, y)) { + if (data.shape) + { + if (data.shape.contains(x, y)) + { //interactionData.target = item; return true; } @@ -600,10 +671,12 @@ var length = item.children.length; - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { var tempItem = item.children[i]; var hit = this.hitTest(tempItem, interactionData); - if (hit) { + if (hit) + { // hmm.. TODO SET CORRECT TARGET? interactionData.target = item; return true; @@ -618,8 +691,10 @@ * @param event {Event} The DOM event of a touch moving across the renderer view * @private */ -InteractionManager.prototype.onTouchMove = function (event) { - if (this.dirty) { +InteractionManager.prototype.onTouchMove = function (event) +{ + if (this.dirty) + { this.rebuildInteractiveGraph(); } @@ -628,7 +703,8 @@ var touchData; var i = 0; - for (i = 0; i < changedTouches.length; i++) { + for (i = 0; i < changedTouches.length; i++) + { var touchEvent = changedTouches[i]; touchData = this.touches[touchEvent.identifier]; touchData.originalEvent = event; @@ -636,15 +712,18 @@ // update the touch position touchData.global.x = ( (touchEvent.clientX - rect.left) * (this.interactionDOMElement.width / rect.width) ) / this.resolution; touchData.global.y = ( (touchEvent.clientY - rect.top) * (this.interactionDOMElement.height / rect.height) ) / this.resolution; - if (navigator.isCocoonJS && !rect.left && !rect.top && !event.target.style.width && !event.target.style.height) { + if (navigator.isCocoonJS && !rect.left && !rect.top && !event.target.style.width && !event.target.style.height) + { //Support for CocoonJS fullscreen scale modes touchData.global.x = touchEvent.clientX; touchData.global.y = touchEvent.clientY; } - for (var j = 0; j < this.interactiveItems.length; j++) { + for (var j = 0; j < this.interactiveItems.length; j++) + { var item = this.interactiveItems[j]; - if (item.touchmove && item.__touchData && item.__touchData[touchEvent.identifier]) { + if (item.touchmove && item.__touchData && item.__touchData[touchEvent.identifier]) + { item.touchmove(touchData); } } @@ -657,23 +736,28 @@ * @param event {Event} The DOM event of a touch starting on the renderer view * @private */ -InteractionManager.prototype.onTouchStart = function (event) { - if (this.dirty) { +InteractionManager.prototype.onTouchStart = function (event) +{ + if (this.dirty) + { this.rebuildInteractiveGraph(); } var rect = this.interactionDOMElement.getBoundingClientRect(); - if (AUTO_PREVENT_DEFAULT) { + if (AUTO_PREVENT_DEFAULT) + { event.preventDefault(); } var changedTouches = event.changedTouches; - for (var i=0; i < changedTouches.length; i++) { + for (var i=0; i < changedTouches.length; i++) + { var touchEvent = changedTouches[i]; var touchData = this.pool.pop(); - if (!touchData) { + if (!touchData) + { touchData = new InteractionData(); } @@ -682,7 +766,8 @@ this.touches[touchEvent.identifier] = touchData; touchData.global.x = ( (touchEvent.clientX - rect.left) * (this.interactionDOMElement.width / rect.width) ) / this.resolution; touchData.global.y = ( (touchEvent.clientY - rect.top) * (this.interactionDOMElement.height / rect.height) ) / this.resolution; - if (navigator.isCocoonJS && !rect.left && !rect.top && !event.target.style.width && !event.target.style.height) { + if (navigator.isCocoonJS && !rect.left && !rect.top && !event.target.style.width && !event.target.style.height) + { //Support for CocoonJS fullscreen scale modes touchData.global.x = touchEvent.clientX; touchData.global.y = touchEvent.clientY; @@ -690,15 +775,19 @@ var length = this.interactiveItems.length; - for (var j = 0; j < length; j++) { + for (var j = 0; j < length; j++) + { var item = this.interactiveItems[j]; - if (item.touchstart || item.tap) { + if (item.touchstart || item.tap) + { item.__hit = this.hitTest(item, touchData); - if (item.__hit) { + if (item.__hit) + { //call the function! - if (item.touchstart) { + if (item.touchstart) + { item.touchstart(touchData); } @@ -706,7 +795,8 @@ item.__touchData = item.__touchData || {}; item.__touchData[touchEvent.identifier] = touchData; - if (!item.interactiveChildren) { + if (!item.interactiveChildren) + { break; } } @@ -721,31 +811,37 @@ * @param event {Event} The DOM event of a touch ending on the renderer view * @private */ -InteractionManager.prototype.onTouchEnd = function (event) { - if (this.dirty) { +InteractionManager.prototype.onTouchEnd = function (event) +{ + if (this.dirty) + { this.rebuildInteractiveGraph(); } var rect = this.interactionDOMElement.getBoundingClientRect(); var changedTouches = event.changedTouches; - for (var i=0; i < changedTouches.length; i++) { + for (var i=0; i < changedTouches.length; i++) + { var touchEvent = changedTouches[i]; var touchData = this.touches[touchEvent.identifier]; var up = false; touchData.global.x = ( (touchEvent.clientX - rect.left) * (this.interactionDOMElement.width / rect.width) ) / this.resolution; touchData.global.y = ( (touchEvent.clientY - rect.top) * (this.interactionDOMElement.height / rect.height) ) / this.resolution; - if (navigator.isCocoonJS && !rect.left && !rect.top && !event.target.style.width && !event.target.style.height) { + if (navigator.isCocoonJS && !rect.left && !rect.top && !event.target.style.width && !event.target.style.height) + { //Support for CocoonJS fullscreen scale modes touchData.global.x = touchEvent.clientX; touchData.global.y = touchEvent.clientY; } var length = this.interactiveItems.length; - for (var j = 0; j < length; j++) { + for (var j = 0; j < length; j++) + { var item = this.interactiveItems[j]; - if (item.__touchData && item.__touchData[touchEvent.identifier]) { + if (item.__touchData && item.__touchData[touchEvent.identifier]) + { item.__hit = this.hitTest(item, item.__touchData[touchEvent.identifier]); @@ -753,20 +849,27 @@ touchData.originalEvent = event; // hitTest?? - if (item.touchend || item.tap) { - if (item.__hit && !up) { - if (item.touchend) { + if (item.touchend || item.tap) + { + if (item.__hit && !up) + { + if (item.touchend) + { item.touchend(touchData); } - if (item.__isDown && item.tap) { + if (item.__isDown && item.tap) + { item.tap(touchData); } - if (!item.interactiveChildren) { + if (!item.interactiveChildren) + { up = true; } } - else { - if (item.__isDown && item.touchendoutside) { + else + { + if (item.__isDown && item.touchendoutside) + { item.touchendoutside(touchData); } } diff --git a/src/loaders/AssetLoader.js b/src/loaders/AssetLoader.js index 20da0cf..c4dba1c 100644 --- a/src/loaders/AssetLoader.js +++ b/src/loaders/AssetLoader.js @@ -21,7 +21,8 @@ * data formats include 'xml' and 'fnt'. * @param crossorigin {boolean} Whether requests should be treated as crossorigin */ -function AssetLoader(assetURLs, crossorigin) { +function AssetLoader(assetURLs, crossorigin) +{ /** * The array of asset URLs that are going to be loaded * @@ -76,16 +77,19 @@ * * @param str {string} the name of the asset */ -AssetLoader.prototype._getDataType = function (str) { +AssetLoader.prototype._getDataType = function (str) +{ var test = 'data:'; var start = str.slice(0, test.length).toLowerCase(); - if (start === test) { + if (start === test) + { var data = str.slice(test.length); var sepIdx = data.indexOf(','); // check for malformed data URI scheme - if (sepIdx === -1) { + if (sepIdx === -1) + { return null; } @@ -94,7 +98,8 @@ //We might need to handle some special cases here... //standardize text/plain to 'txt' file extension - if (!info || info.toLowerCase() === 'text/plain') { + if (!info || info.toLowerCase() === 'text/plain') + { return 'txt'; } @@ -109,27 +114,32 @@ * Starts loading the assets sequentially * */ -AssetLoader.prototype.load = function () { +AssetLoader.prototype.load = function () +{ var scope = this; - function onLoad(evt) { + function onLoad(evt) + { scope.onAssetLoaded(evt.data.content); } this.loadCount = this.assetURLs.length; - for (var i=0; i < this.assetURLs.length; i++) { + for (var i=0; i < this.assetURLs.length; i++) + { var fileName = this.assetURLs[i]; //first see if we have a data URI scheme.. var fileType = this._getDataType(fileName); //if not, assume it's a file URI - if (!fileType) { + if (!fileType) + { fileType = fileName.split('?').shift().split('.').pop().toLowerCase(); } var Constructor = this.loadersByType[fileType]; - if (!Constructor) { + if (!Constructor) + { throw new Error(fileType + ' is an unsupported file type'); } @@ -145,18 +155,22 @@ * * @private */ -AssetLoader.prototype.onAssetLoaded = function (loader) { +AssetLoader.prototype.onAssetLoaded = function (loader) +{ this.loadCount--; this.emit('onProgress', { content: this, loader: loader }); - if (this.onProgress) { + if (this.onProgress) + { this.onProgress(loader); } - if (!this.loadCount) { + if (!this.loadCount) + { this.emit('onComplete', { content: this }); - if (this.onComplete) { + if (this.onComplete) + { this.onComplete(); } } diff --git a/src/loaders/AtlasLoader.js b/src/loaders/AtlasLoader.js index 5eda286..3aec9e2 100644 --- a/src/loaders/AtlasLoader.js +++ b/src/loaders/AtlasLoader.js @@ -15,7 +15,8 @@ * @param url {String} The url of the JSON file * @param crossorigin {boolean} Whether requests should be treated as crossorigin */ -function AtlasLoader(url, crossorigin) { +function AtlasLoader(url, crossorigin) +{ this.url = url; this.baseUrl = url.replace(/[^\/]*$/, ''); this.crossorigin = crossorigin; @@ -31,13 +32,15 @@ * Starts loading the JSON file * */ -AtlasLoader.prototype.load = function () { +AtlasLoader.prototype.load = function () +{ this.ajaxRequest = new core.utils.AjaxRequest(); this.ajaxRequest.onreadystatechange = this.onAtlasLoaded.bind(this); this.ajaxRequest.open('GET', this.url, true); - if (this.ajaxRequest.overrideMimeType) { + if (this.ajaxRequest.overrideMimeType) + { this.ajaxRequest.overrideMimeType('application/json'); } @@ -49,9 +52,12 @@ * * @private */ -AtlasLoader.prototype.onAtlasLoaded = function () { - if (this.ajaxRequest.readyState === 4) { - if (this.ajaxRequest.status === 200 || window.location.href.indexOf('http') === -1) { +AtlasLoader.prototype.onAtlasLoaded = function () +{ + if (this.ajaxRequest.readyState === 4) + { + if (this.ajaxRequest.status === 200 || window.location.href.indexOf('http') === -1) + { this.atlas = { meta : { image : [] @@ -70,34 +76,44 @@ selfOnLoaded = this.onLoaded.bind(this); // parser without rotation support yet! - for (i = 0; i < result.length; i++) { + for (i = 0; i < result.length; i++) + { result[i] = result[i].replace(/^\s+|\s+$/g, ''); - if (result[i] === '') { + if (result[i] === '') + { nameInNextLine = i+1; } - if (result[i].length > 0) { - if (nameInNextLine === i) { + if (result[i].length > 0) + { + if (nameInNextLine === i) + { this.atlas.meta.image.push(result[i]); currentImageId = this.atlas.meta.image.length - 1; this.atlas.frames.push({}); lineCount = -3; - } else if (lineCount > 0) { - if (lineCount % 7 === 1) { // frame name - if (currentFrame != null) { //jshint ignore:line + } else if (lineCount > 0) + { + if (lineCount % 7 === 1) + { // frame name + if (currentFrame != null) + { //jshint ignore:line this.atlas.frames[currentImageId][currentFrame.name] = currentFrame; } currentFrame = { name: result[i], frame : {} }; } else { var text = result[i].split(' '); - if (lineCount % 7 === 3) { // position + if (lineCount % 7 === 3) + { // position currentFrame.frame.x = Number(text[1].replace(',', '')); currentFrame.frame.y = Number(text[2]); - } else if (lineCount % 7 === 4) { // size + } else if (lineCount % 7 === 4) + { // size currentFrame.frame.w = Number(text[1].replace(',', '')); currentFrame.frame.h = Number(text[2]); - } else if (lineCount % 7 === 5) { // real size + } else if (lineCount % 7 === 5) + { // real size var realSize = { x : 0, y : 0, @@ -105,7 +121,8 @@ h : Number(text[2]) }; - if (realSize.w > currentFrame.frame.w || realSize.h > currentFrame.frame.h) { + if (realSize.w > currentFrame.frame.w || realSize.h > currentFrame.frame.h) + { currentFrame.trimmed = true; currentFrame.realSize = realSize; } else { @@ -118,28 +135,34 @@ } } - if (currentFrame != null) { //jshint ignore:line + if (currentFrame != null) + { //jshint ignore:line this.atlas.frames[currentImageId][currentFrame.name] = currentFrame; } - if (this.atlas.meta.image.length > 0) { + if (this.atlas.meta.image.length > 0) + { this.images = []; - for (j = 0; j < this.atlas.meta.image.length; j++) { + for (j = 0; j < this.atlas.meta.image.length; j++) + { // sprite sheet var textureUrl = this.baseUrl + this.atlas.meta.image[j]; var frameData = this.atlas.frames[j]; this.images.push(new ImageLoader(textureUrl, this.crossorigin)); - for (i in frameData) { + for (i in frameData) + { var rect = frameData[i].frame; - if (rect) { + if (rect) + { core.utils.TextureCache[i] = new core.Texture(this.images[j].texture.baseTexture, { x: rect.x, y: rect.y, width: rect.w, height: rect.h }); - if (frameData[i].trimmed) { + if (frameData[i].trimmed) + { core.utils.TextureCache[i].realSize = frameData[i].realSize; // trim in pixi not supported yet, todo update trim properties if it is done ... core.utils.TextureCache[i].trim.x = 0; @@ -150,7 +173,8 @@ } this.currentImageId = 0; - for (j = 0; j < this.images.length; j++) { + for (j = 0; j < this.images.length; j++) + { this.images[j].on('loaded', selfOnLoaded); } this.images[this.currentImageId].load(); @@ -170,8 +194,10 @@ * * @private */ -AtlasLoader.prototype.onLoaded = function () { - if (this.images.length - 1 > this.currentImageId) { +AtlasLoader.prototype.onLoaded = function () +{ + if (this.images.length - 1 > this.currentImageId) + { this.currentImageId++; this.images[this.currentImageId].load(); } else { @@ -185,6 +211,7 @@ * * @private */ -AtlasLoader.prototype.onError = function () { +AtlasLoader.prototype.onError = function () +{ this.emit('error', { content: this }); }; diff --git a/src/loaders/BitmapFontLoader.js b/src/loaders/BitmapFontLoader.js index 8641760..13e5c1b 100644 --- a/src/loaders/BitmapFontLoader.js +++ b/src/loaders/BitmapFontLoader.js @@ -13,7 +13,8 @@ * @param url {String} The url of the sprite sheet JSON file * @param crossorigin {boolean} Whether requests should be treated as crossorigin */ -function BitmapFontLoader(url, crossorigin) { +function BitmapFontLoader(url, crossorigin) +{ /** * The url of the bitmap font data * @@ -54,13 +55,15 @@ * Loads the XML font data * */ -BitmapFontLoader.prototype.load = function () { +BitmapFontLoader.prototype.load = function () +{ this.ajaxRequest = new core.utils.AjaxRequest(); this.ajaxRequest.onreadystatechange = this.onXMLLoaded.bind(this); this.ajaxRequest.open('GET', this.url, true); - if (this.ajaxRequest.overrideMimeType) { + if (this.ajaxRequest.overrideMimeType) + { this.ajaxRequest.overrideMimeType('application/xml'); } @@ -72,12 +75,17 @@ * * @private */ -BitmapFontLoader.prototype.onXMLLoaded = function () { - if (this.ajaxRequest.readyState === 4) { - if (this.ajaxRequest.status === 200 || window.location.protocol.indexOf('http') === -1) { +BitmapFontLoader.prototype.onXMLLoaded = function () +{ + if (this.ajaxRequest.readyState === 4) + { + if (this.ajaxRequest.status === 200 || window.location.protocol.indexOf('http') === -1) + { var responseXML = this.ajaxRequest.responseXML; - if (!responseXML || /MSIE 9/i.test(navigator.userAgent) || navigator.isCocoonJS) { - if (typeof(window.DOMParser) === 'function') { + if (!responseXML || /MSIE 9/i.test(navigator.userAgent) || navigator.isCocoonJS) + { + if (typeof(window.DOMParser) === 'function') + { var domparser = new DOMParser(); responseXML = domparser.parseFromString(this.ajaxRequest.responseText, 'text/xml'); } else { @@ -102,7 +110,8 @@ //parse letters var letters = responseXML.getElementsByTagName('char'); - for (var i = 0; i < letters.length; i++) { + for (var i = 0; i < letters.length; i++) + { var charCode = parseInt(letters[i].getAttribute('id'), 10); var textureRect = new core.math.Rectangle( @@ -124,7 +133,8 @@ //parse kernings var kernings = responseXML.getElementsByTagName('kerning'); - for (i = 0; i < kernings.length; i++) { + for (i = 0; i < kernings.length; i++) + { var first = parseInt(kernings[i].getAttribute('first'), 10); var second = parseInt(kernings[i].getAttribute('second'), 10); var amount = parseInt(kernings[i].getAttribute('amount'), 10); @@ -146,6 +156,7 @@ * * @private */ -BitmapFontLoader.prototype.onLoaded = function () { +BitmapFontLoader.prototype.onLoaded = function () +{ this.emit('loaded', { content: this }); }; diff --git a/src/core/display/DisplayObject.js b/src/core/display/DisplayObject.js index 66ebc3c..20e778c 100644 --- a/src/core/display/DisplayObject.js +++ b/src/core/display/DisplayObject.js @@ -7,7 +7,8 @@ * @class * @namespace PIXI */ -function DisplayObject() { +function DisplayObject() +{ /** * The coordinate of the object relative to the local coordinates of the parent. * @@ -152,10 +153,12 @@ * @memberof DisplayObject# */ x: { - get: function () { + get: function () + { return this.position.x; }, - set: function (value) { + set: function (value) + { this.position.x = value; } }, @@ -167,10 +170,12 @@ * @memberof DisplayObject# */ y: { - get: function () { + get: function () + { return this.position.y; }, - set: function (value) { + set: function (value) + { this.position.y = value; } }, @@ -183,11 +188,13 @@ * @readonly */ worldVisible: { - get: function () { + get: function () + { var item = this; do { - if (!item.visible) { + if (!item.visible) + { return false; } @@ -207,17 +214,21 @@ * @memberof DisplayObject# */ mask: { - get: function () { + get: function () + { return this._mask; }, - set: function (value) { - if (this._mask) { + set: function (value) + { + if (this._mask) + { this._mask.isMask = false; } this._mask = value; - if (this._mask) { + if (this._mask) + { this._mask.isMask = true; } } @@ -232,18 +243,23 @@ * @memberof DisplayObject# */ filters: { - get: function () { + get: function () + { return this._filters; }, - set: function (value) { - if (value) { + set: function (value) + { + if (value) + { // now put all the passes in one place.. var passes = []; - for (var i = 0; i < value.length; i++) { + for (var i = 0; i < value.length; i++) + { var filterPasses = value[i].passes; - for (var j = 0; j < filterPasses.length; j++) { + for (var j = 0; j < filterPasses.length; j++) + { passes.push(filterPasses[j]); } } @@ -264,8 +280,9 @@ * * @private */ -DisplayObject.prototype.updateTransform = function () { - +DisplayObject.prototype.updateTransform = function () +{ + // create some matrix refs for easy access var pt = this.parent.worldTransform; var wt = this.worldTransform; @@ -274,9 +291,11 @@ var a, b, c, d, tx, ty; // so if rotation is between 0 then we can simplify the multiplication process.. - if (this.rotation % math.PI_2) { + if (this.rotation % math.PI_2) + { // 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) { + if (this.rotation !== this.rotationCache) + { this.rotationCache = this.rotation; this._sr = Math.sin(this.rotation); this._cr = Math.cos(this.rotation); @@ -291,7 +310,8 @@ ty = this.position.y; // check for pivot.. not often used so geared towards that fact! - if (this.pivot.x || this.pivot.y) { + 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; } @@ -304,7 +324,8 @@ wt.tx = tx * pt.a + ty * pt.c + pt.tx; wt.ty = tx * pt.b + ty * pt.d + pt.ty; } - else { + else + { // lets do the fast version as we know there is no rotation.. a = this.scale.x; d = this.scale.y; @@ -333,7 +354,8 @@ * @param matrix {Matrix} * @return {Rectangle} the rectangular bounding area */ -DisplayObject.prototype.getBounds = function (/* matrix */) { +DisplayObject.prototype.getBounds = function (/* matrix */) +{ return math.Rectangle.EMPTY; }; @@ -342,7 +364,8 @@ * * @return {Rectangle} the rectangular bounding area */ -DisplayObject.prototype.getLocalBounds = function () { +DisplayObject.prototype.getLocalBounds = function () +{ return this.getBounds(math.Matrix.IDENTITY); }; @@ -352,7 +375,8 @@ * @param position {Point} The world origin to calculate from * @return {Point} A point object representing the position of this object */ -DisplayObject.prototype.toGlobal = function (position) { +DisplayObject.prototype.toGlobal = function (position) +{ // don't need to u[date the lot this.displayObjectUpdateTransform(); return this.worldTransform.apply(position); @@ -365,8 +389,10 @@ * @param [from] {DisplayObject} The DisplayObject to calculate the global position from * @return {Point} A point object representing the position of this object */ -DisplayObject.prototype.toLocal = function (position, from) { - if (from) { +DisplayObject.prototype.toLocal = function (position, from) +{ + if (from) + { position = from.toGlobal(position); } @@ -381,7 +407,8 @@ * @param renderer {WebGLRenderer} The renderer * @private */ -DisplayObject.prototype.renderWebGL = function (/* renderer */) { +DisplayObject.prototype.renderWebGL = function (/* renderer */) +{ // OVERWRITE; }; @@ -391,6 +418,7 @@ * @param renderer {CanvasRenderer} The renderer * @private */ -DisplayObject.prototype.renderCanvas = function (/* renderer */) { +DisplayObject.prototype.renderCanvas = function (/* renderer */) +{ // OVERWRITE; }; diff --git a/src/core/display/DisplayObjectContainer.js b/src/core/display/DisplayObjectContainer.js index 689f40b..4625ee8 100644 --- a/src/core/display/DisplayObjectContainer.js +++ b/src/core/display/DisplayObjectContainer.js @@ -12,7 +12,8 @@ * @extends DisplayObject * @namespace PIXI */ -function DisplayObjectContainer() { +function DisplayObjectContainer() +{ DisplayObject.call(this); /** @@ -47,17 +48,21 @@ * @memberof DisplayObjectContainer# */ width: { - get: function () { + get: function () + { return this.scale.x * this.getLocalBounds().width; }, - set: function (value) { + set: function (value) + { var width = this.getLocalBounds().width; - if(width !== 0) { + if(width !== 0) + { this.scale.x = value / width; } - else { + else + { this.scale.x = 1; } @@ -73,17 +78,21 @@ * @memberof DisplayObjectContainer# */ height: { - get: function () { + get: function () + { return this.scale.y * this.getLocalBounds().height; }, - set: function (value) { + set: function (value) + { var height = this.getLocalBounds().height; - if (height !== 0) { + if (height !== 0) + { this.scale.y = value / height ; } - else { + else + { this.scale.y = 1; } @@ -100,18 +109,23 @@ * @memberof DisplayObject# */ cacheAsBitmap: { - get: function () { + get: function () + { return this._cacheAsBitmap; }, - set: function (value) { - if (this._cacheAsBitmap === value) { + set: function (value) + { + if (this._cacheAsBitmap === value) + { return; } - if (value) { + if (value) + { this._generateCachedSprite(); } - else { + else + { this._destroyCachedSprite(); } @@ -126,7 +140,8 @@ * @param child {DisplayObject} The DisplayObject to add to the container * @return {DisplayObject} The child that was added. */ -DisplayObjectContainer.prototype.addChild = function (child) { +DisplayObjectContainer.prototype.addChild = function (child) +{ return this.addChildAt(child, this.children.length); }; @@ -137,14 +152,18 @@ * @param index {Number} The index to place the child in * @return {DisplayObject} The child that was added. */ -DisplayObjectContainer.prototype.addChildAt = function (child, index) { +DisplayObjectContainer.prototype.addChildAt = function (child, index) +{ // prevent adding self as child - if (child === this) { + if (child === this) + { return; } - if (index >= 0 && index <= this.children.length) { - if (child.parent) { + if (index >= 0 && index <= this.children.length) + { + if (child.parent) + { child.parent.removeChild(child); } @@ -154,7 +173,8 @@ return child; } - else { + else + { throw new Error(child + 'addChildAt: The index '+ index +' supplied is out of bounds ' + this.children.length); } }; @@ -165,15 +185,18 @@ * @param child {DisplayObject} * @param child2 {DisplayObject} */ -DisplayObjectContainer.prototype.swapChildren = function (child, child2) { - if (child === child2) { +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) { + if (index1 < 0 || index2 < 0) + { throw new Error('swapChildren: Both the supplied DisplayObjects must be a child of the caller.'); } @@ -187,10 +210,12 @@ * @param child {DisplayObject} The DisplayObject instance to identify * @return {Number} The index position of the child display object to identify */ -DisplayObjectContainer.prototype.getChildIndex = function (child) { +DisplayObjectContainer.prototype.getChildIndex = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { throw new Error('The supplied DisplayObject must be a child of the caller'); } @@ -203,8 +228,10 @@ * @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 */ -DisplayObjectContainer.prototype.setChildIndex = function (child, index) { - if (index < 0 || index >= this.children.length) { +DisplayObjectContainer.prototype.setChildIndex = function (child, index) +{ + if (index < 0 || index >= this.children.length) + { throw new Error('The supplied index is out of bounds'); } @@ -220,8 +247,10 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child at the given index, if any. */ -DisplayObjectContainer.prototype.getChildAt = function (index) { - if (index < 0 || index >= this.children.length) { +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'); } @@ -234,10 +263,12 @@ * @param child {DisplayObject} The DisplayObject to remove * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChild = function (child) { +DisplayObjectContainer.prototype.removeChild = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { return; } @@ -250,7 +281,8 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChildAt = function (index) { +DisplayObjectContainer.prototype.removeChildAt = function (index) +{ var child = this.getChildAt(index); child.parent = null; @@ -265,24 +297,29 @@ * @param beginIndex {Number} The beginning position. Default value is 0. * @param endIndex {Number} The ending position. Default value is size of the container. */ -DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) { +DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) +{ var begin = beginIndex || 0; var end = typeof endIndex === 'number' ? endIndex : this.children.length; var range = end - begin; - if (range > 0 && range <= end) { + if (range > 0 && range <= end) + { var removed = this.children.splice(begin, range); - for (var i = 0; i < removed.length; ++i) { + for (var i = 0; i < removed.length; ++i) + { removed[i].parent = null; } return removed; } - else if (range === 0 && this.children.length === 0) { + else if (range === 0 && this.children.length === 0) + { return []; } - else { + else + { throw new RangeError('removeChildren: numeric values are outside the acceptable range.'); } }; @@ -291,7 +328,8 @@ * Generates and updates the cached sprite for this object. * */ -DisplayObjectContainer.prototype.updateCachedSprite = function () { +DisplayObjectContainer.prototype.updateCachedSprite = function () +{ this._generateCachedSprite(); }; @@ -304,7 +342,8 @@ * @param renderer {CanvasRenderer|WebGLRenderer} The renderer used to generate the texture. * @return {Texture} a texture of the graphics object */ -DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) { +DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) +{ var bounds = this.getLocalBounds(); var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0, renderer, scaleMode, resolution); @@ -322,18 +361,22 @@ * * @private */ -DisplayObjectContainer.prototype.updateTransform = function () { - if (!this.visible) { +DisplayObjectContainer.prototype.updateTransform = function () +{ + if (!this.visible) + { return; } this.displayObjectUpdateTransform(); - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { return; } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } }; @@ -346,8 +389,10 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getBounds = function () { - if (this.children.length === 0) { +DisplayObjectContainer.prototype.getBounds = function () +{ + if (this.children.length === 0) + { return math.Rectangle.EMPTY; } @@ -365,10 +410,12 @@ var childVisible = false; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -386,7 +433,8 @@ maxY = maxY > childMaxY ? maxY : childMaxY; } - if (!childVisible) { + if (!childVisible) + { return math.Rectangle.EMPTY; } @@ -407,12 +455,14 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getLocalBounds = function () { +DisplayObjectContainer.prototype.getLocalBounds = function () +{ var matrixCache = this.worldTransform; this.worldTransform = math.Matrix.IDENTITY; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } @@ -428,13 +478,16 @@ * * @param renderer {WebGLRenderer} The renderer */ -DisplayObjectContainer.prototype.renderWebGL = function (renderer) { +DisplayObjectContainer.prototype.renderWebGL = function (renderer) +{ // if the object is not visible or the alpha is 0 then no need to render this element - if (!this.visible || this.alpha <= 0) { + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } @@ -442,14 +495,17 @@ var i, j; // do a quick check to see if this element has a mask or a filter. - if (this._mask || this._filters) { + if (this._mask || this._filters) + { // push filter first as we need to ensure the stencil buffer is correct for any masking - if (this._filters) { + if (this._filters) + { renderer.spriteBatch.flush(); renderer.filterManager.pushFilter(this._filterBlock); } - if (this._mask) { + if (this._mask) + { renderer.spriteBatch.stop(); renderer.maskManager.pushMask(this.mask, renderer); renderer.spriteBatch.start(); @@ -459,36 +515,42 @@ this._renderWebGL(renderer); // now loop through the children and make sure they get rendered - for (i = 0, j = this.children.length; i < j; i++) { + for (i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderWebGL(renderer); } // time to stop the sprite batch as either a mask element or a filter draw will happen next renderer.spriteBatch.stop(); - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(this._mask, renderer); } - if (this._filters) { + if (this._filters) + { renderer.filterManager.popFilter(); } renderer.spriteBatch.start(); } - else { + else + { this._renderWebGL(renderer); // simple render children! - for (i = 0, j = this.children.length; i < j; ++i) { + for (i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderWebGL(renderer); } } }; -DisplayObjectContainer.prototype._renderWebGL = function (renderer) { +DisplayObjectContainer.prototype._renderWebGL = function (renderer) +{ // this is where content itself gets renderd.. @@ -499,25 +561,31 @@ * * @param renderer {CanvasRenderer} The renderer */ -DisplayObjectContainer.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0) { +DisplayObjectContainer.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -528,13 +596,16 @@ * @param renderer {WebGLRenderer|CanvasRenderer} The renderer * @private */ -DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) { +DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) +{ this._cachedSprite.worldAlpha = this.worldAlpha; - if (renderer.gl) { + if (renderer.gl) + { this._cachedSprite.renderWebGL(renderer); } - else { + else + { this._cachedSprite.renderCanvas(renderer); } }; @@ -544,10 +615,12 @@ * * @private */ -DisplayObjectContainer.prototype._generateCachedSprite = function () { +DisplayObjectContainer.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { // TODO - RenderTexture now *requires* a renderer instance, so this is like broken // because `renderer` isn't actually in scope here :P var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0); @@ -555,7 +628,8 @@ this._cachedSprite = new Sprite(renderTexture); this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.texture.resize(bounds.width | 0, bounds.height | 0); } @@ -580,8 +654,10 @@ * * @private */ -DisplayObjectContainer.prototype._destroyCachedSprite = function () { - if (!this._cachedSprite) { +DisplayObjectContainer.prototype._destroyCachedSprite = function () +{ + if (!this._cachedSprite) + { return; } diff --git a/src/core/display/Sprite.js b/src/core/display/Sprite.js index 707da24..5862aef 100644 --- a/src/core/display/Sprite.js +++ b/src/core/display/Sprite.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param texture {Texture} The texture for this sprite */ -function Sprite(texture) { +function Sprite(texture) +{ DisplayObjectContainer.call(this); /** @@ -85,12 +86,14 @@ this.texture = texture || Texture.EMPTY; } -Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) { +Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) +{ DisplayObjectContainer.prototype.destroy.call(this); this.anchor = null; - if (destroyTexture) { + if (destroyTexture) + { this._texture.destroy(destroyBaseTexture); } @@ -111,10 +114,12 @@ * @memberof Sprite# */ width: { - get: function () { + get: function () + { return this.scale.x * this.texture.frame.width; }, - set: function (value) { + set: function (value) + { this.scale.x = value / this.texture.frame.width; this._width = value; } @@ -127,10 +132,12 @@ * @memberof Sprite# */ height: { - get: function () { + get: function () + { return this.scale.y * this.texture.frame.height; }, - set: function (value) { + set: function (value) + { this.scale.y = value / this.texture.frame.height; this._height = value; } @@ -143,23 +150,29 @@ * @memberof Sprite# */ texture: { - get: function () { + get: function () + { return this._texture; }, - set: function (value) { - if (this._texture === value) { + set: function (value) + { + if (this._texture === value) + { return; } this._texture = value; this.cachedTint = 0xFFFFFF; - if (value) { + if (value) + { // wait for the texture to load - if (value.baseTexture.hasLoaded) { + if (value.baseTexture.hasLoaded) + { this._onTextureUpdate(); } - else { + else + { value.once('update', this._onTextureUpdate.bind(this)); } } @@ -172,18 +185,22 @@ * * @private */ -Sprite.prototype._onTextureUpdate = function () { +Sprite.prototype._onTextureUpdate = function () +{ // so if _width is 0 then width was not set.. - if (this._width) { + if (this._width) + { this.scale.x = this._width / this.texture.frame.width; } - if (this._height) { + if (this._height) + { this.scale.y = this._height / this.texture.frame.height; } }; -Sprite.prototype._renderWebGL = function (renderer) { +Sprite.prototype._renderWebGL = function (renderer) +{ // this is where content gets renderd.. // watch this space for a little render state manager.. @@ -197,7 +214,8 @@ * @param matrix {Matrix} the transformation matrix of the sprite * @return {Rectangle} the framing rectangle */ -Sprite.prototype.getBounds = function (matrix) { +Sprite.prototype.getBounds = function (matrix) +{ var width = this.texture.frame.width; var height = this.texture.frame.height; @@ -224,11 +242,13 @@ if(b === 0 && c === 0) { // scale may be negative! - if (a < 0) { + if (a < 0) + { a *= -1; } - if (d < 0) { + if (d < 0) + { d *= -1; } @@ -293,28 +313,34 @@ * * @param renderer {CanvasRenderer} The renderer */ -Sprite.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) { +Sprite.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) + { return; } - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; renderer.context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } // Ignore null sources - if (this.texture.valid) { + if (this.texture.valid) + { var resolution = this.texture.baseTexture.resolution / renderer.resolution; renderer.context.globalAlpha = this.worldAlpha; // If smoothingEnabled is supported and we need to change the smoothing property for this texture - if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) { + if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) + { renderer.scaleMode = this.texture.baseTexture.scaleMode; renderer.context[renderer.smoothProperty] = (renderer.scaleMode === CONST.scaleModes.LINEAR); } @@ -324,7 +350,8 @@ var dy = (this.texture.trim ? this.texture.trim.y : 0) - (this.anchor.y * this.texture.trim.height); // Allow for pixel rounding - if (renderer.roundPixels) { + if (renderer.roundPixels) + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -337,7 +364,8 @@ dx = dx | 0; dy = dy | 0; } - else { + else + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -348,8 +376,10 @@ ); } - if (this.tint !== 0xFFFFFF) { - if (this.cachedTint !== this.tint) { + if (this.tint !== 0xFFFFFF) + { + if (this.cachedTint !== this.tint) + { this.cachedTint = this.tint; // TODO clean up caching - how to clean up the caches? @@ -368,7 +398,8 @@ this.texture.crop.height / resolution ); } - else { + else + { renderer.context.drawImage( this.texture.baseTexture.source, this.texture.crop.x, @@ -383,11 +414,13 @@ } } - for (var i = 0, j = this.children.length; i < j; i++) { + for (var i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -402,10 +435,12 @@ * @param frameId {String} The frame Id of the texture in the cache * @return {Sprite} A new Sprite using a texture from the texture cache matching the frameId */ -Sprite.fromFrame = function (frameId) { +Sprite.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache' + this); } @@ -420,6 +455,7 @@ * @param imageId {String} The image url of the texture * @return {Sprite} A new Sprite using a texture from the texture cache matching the image id */ -Sprite.fromImage = function (imageId, crossorigin, scaleMode) { +Sprite.fromImage = function (imageId, crossorigin, scaleMode) +{ return new Sprite(Texture.fromImage(imageId, crossorigin, scaleMode)); }; diff --git a/src/core/display/SpriteBatch.js b/src/core/display/SpriteBatch.js index 3187777..c196fef 100644 --- a/src/core/display/SpriteBatch.js +++ b/src/core/display/SpriteBatch.js @@ -12,7 +12,8 @@ * ```js * var container = new SpriteBatch(); * - * for(var i = 0; i < 100; ++i) { + * for(var i = 0; i < 100; ++i) + * { * var sprite = new PIXI.Sprite.fromImage("myImage.png"); * container.addChild(sprite); * } @@ -25,7 +26,8 @@ */ //TODO RENAME to PARTICLE CONTAINER? -function SpriteBatch() { +function SpriteBatch() +{ DisplayObjectContainer.call(this); } @@ -38,7 +40,8 @@ * * @private */ -SpriteBatch.prototype.updateTransform = function () { +SpriteBatch.prototype.updateTransform = function () +{ // TODO don't need to! this.displayObjectUpdateTransform(); // PIXI.DisplayObjectContainer.prototype.updateTransform.call( this ); @@ -50,8 +53,10 @@ * @param renderer {WebGLRenderer} The webgl renderer * @private */ -SpriteBatch.prototype.renderWebGL = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderWebGL = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -71,8 +76,10 @@ * @param renderer {CanvasRenderer} The canvas renderer * @private */ -SpriteBatch.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -84,10 +91,12 @@ this.displayObjectUpdateTransform(); - for (var i = 0; i < this.children.length; ++i) { + for (var i = 0; i < this.children.length; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -95,9 +104,11 @@ context.globalAlpha = this.worldAlpha * child.alpha; - if (child.rotation % (Math.PI * 2) === 0) { + if (child.rotation % (Math.PI * 2) === 0) + { // this is the fastest way to optimise! - if rotation is 0 then we can avoid any kind of setTransform call - if (isRotated) { + if (isRotated) + { context.setTransform( transform.a, transform.b, @@ -122,8 +133,10 @@ frame.height * child.scale.y ); } - else { - if (!isRotated) { + else + { + if (!isRotated) + { isRotated = true; } @@ -131,7 +144,8 @@ var childTransform = child.worldTransform; - if (renderer.roundPixels) { + if (renderer.roundPixels) + { context.setTransform( childTransform.a, childTransform.b, @@ -141,7 +155,8 @@ childTransform.ty | 0 ); } - else { + else + { context.setTransform( childTransform.a, childTransform.b, diff --git a/src/core/index.js b/src/core/index.js index 3954b6f..eb4a82b 100644 --- a/src/core/index.js +++ b/src/core/index.js @@ -58,11 +58,13 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRenderer: function (width, height, options, noWebGL) { + autoDetectRenderer: function (width, height, options, noWebGL) + { width = width || 800; height = height || 600; - if (!noWebGL && require('webgl-enabled')()) { + if (!noWebGL && require('webgl-enabled')()) + { return new core.WebGLRenderer(width, height, options); } @@ -87,7 +89,8 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRecommendedRenderer: function (width, height, options) { + autoDetectRecommendedRenderer: function (width, height, options) + { var isAndroid = /Android/i.test(navigator.userAgent); return core.autoDetectRenderer(width, height, options, isAndroid); diff --git a/src/core/math/Matrix.js b/src/core/math/Matrix.js index c2f87e2..2ff4848 100644 --- a/src/core/math/Matrix.js +++ b/src/core/math/Matrix.js @@ -10,7 +10,8 @@ * @class * @namespace PIXI */ -function Matrix() { +function Matrix() +{ /** * @member {number} * @default 1 @@ -63,7 +64,8 @@ * * @param array {number[]} The array that the matrix will be populated from. */ -Matrix.prototype.fromArray = function (array) { +Matrix.prototype.fromArray = function (array) +{ this.a = array[0]; this.b = array[1]; this.c = array[3]; @@ -78,14 +80,17 @@ * @param transpose {boolean} Whether we need to transpose the matrix or not * @return {number[]} the newly created array which contains the matrix */ -Matrix.prototype.toArray = function (transpose) { - if (!this.array) { +Matrix.prototype.toArray = function (transpose) +{ + if (!this.array) + { this.array = new Float32Array(9); } var array = this.array; - if (transpose) { + if (transpose) + { array[0] = this.a; array[1] = this.b; array[2] = 0; @@ -96,7 +101,8 @@ array[7] = this.ty; array[8] = 1; } - else { + else + { array[0] = this.a; array[1] = this.c; array[2] = this.tx; @@ -119,7 +125,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, transformed through this matrix */ -Matrix.prototype.apply = function (pos, newPos) { +Matrix.prototype.apply = function (pos, newPos) +{ newPos = newPos || new Point(); newPos.x = this.a * pos.x + this.c * pos.y + this.tx; @@ -136,7 +143,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, inverse-transformed through this matrix */ -Matrix.prototype.applyInverse = function (pos, newPos) { +Matrix.prototype.applyInverse = function (pos, newPos) +{ newPos = newPos || new Point(); var id = 1 / (this.a * this.d + this.c * -this.b); @@ -154,7 +162,8 @@ * @param {number} y * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.translate = function (x, y) { +Matrix.prototype.translate = function (x, y) +{ this.tx += x; this.ty += y; @@ -168,7 +177,8 @@ * @param {number} y The amount to scale vertically * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.scale = function (x, y) { +Matrix.prototype.scale = function (x, y) +{ this.a *= x; this.d *= y; this.c *= x; @@ -186,7 +196,8 @@ * @param {number} angle - The angle in radians. * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.rotate = function (angle) { +Matrix.prototype.rotate = function (angle) +{ var cos = Math.cos( angle ); var sin = Math.sin( angle ); @@ -210,7 +221,8 @@ * @param {Matrix} matrix * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.append = function (matrix) { +Matrix.prototype.append = function (matrix) +{ var a1 = this.a; var b1 = this.b; var c1 = this.c; @@ -232,7 +244,8 @@ * * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.identity = function () { +Matrix.prototype.identity = function () +{ this.a = 1; this.b = 0; this.c = 0; diff --git a/src/core/math/Point.js b/src/core/math/Point.js index 7565b2d..632f346 100644 --- a/src/core/math/Point.js +++ b/src/core/math/Point.js @@ -7,7 +7,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -function Point(x, y) { +function Point(x, y) +{ /** * @member {number} * @default 0 @@ -29,7 +30,8 @@ * * @return {Point} a copy of the point */ -Point.prototype.clone = function () { +Point.prototype.clone = function () +{ return new Point(this.x, this.y); }; @@ -40,7 +42,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -Point.prototype.set = function (x, y) { +Point.prototype.set = function (x, y) +{ this.x = x || 0; this.y = y || ( (y !== 0) ? this.x : 0 ) ; }; diff --git a/src/core/math/shapes/Circle.js b/src/core/math/shapes/Circle.js index 69cfdc9..4d76efc 100644 --- a/src/core/math/shapes/Circle.js +++ b/src/core/math/shapes/Circle.js @@ -10,7 +10,8 @@ * @param y {number} The Y coordinate of the center of this circle * @param radius {number} The radius of the circle */ -function Circle(x, y, radius) { +function Circle(x, y, radius) +{ /** * @member {number} * @default 0 @@ -46,7 +47,8 @@ * @method clone * @return {Circle} a copy of the Circle */ -Circle.prototype.clone = function () { +Circle.prototype.clone = function () +{ return new Circle(this.x, this.y, this.radius); }; @@ -58,8 +60,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Circle */ -Circle.prototype.contains = function (x, y) { - if (this.radius <= 0) { +Circle.prototype.contains = function (x, y) +{ + if (this.radius <= 0) + { return false; } @@ -79,6 +83,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Circle.prototype.getBounds = function () { +Circle.prototype.getBounds = function () +{ return new Rectangle(this.x - this.radius, this.y - this.radius, this.radius * 2, this.radius * 2); }; diff --git a/src/core/math/shapes/Ellipse.js b/src/core/math/shapes/Ellipse.js index 4f2d066..fefd01a 100644 --- a/src/core/math/shapes/Ellipse.js +++ b/src/core/math/shapes/Ellipse.js @@ -11,7 +11,8 @@ * @param width {number} The half width of this ellipse * @param height {number} The half height of this ellipse */ -function Ellipse(x, y, width, height) { +function Ellipse(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -53,7 +54,8 @@ * @method clone * @return {Ellipse} a copy of the ellipse */ -Ellipse.prototype.clone = function () { +Ellipse.prototype.clone = function () +{ return new Ellipse(this.x, this.y, this.width, this.height); }; @@ -65,8 +67,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coords are within this ellipse */ -Ellipse.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Ellipse.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } @@ -86,6 +90,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Ellipse.prototype.getBounds = function () { +Ellipse.prototype.getBounds = function () +{ return new Rectangle(this.x - this.width, this.y - this.height, this.width, this.height); }; diff --git a/src/core/math/shapes/Polygon.js b/src/core/math/shapes/Polygon.js index ae89148..fea6d37 100644 --- a/src/core/math/shapes/Polygon.js +++ b/src/core/math/shapes/Polygon.js @@ -10,16 +10,20 @@ * arguments passed can be flat x,y values e.g. `new Polygon(x,y, x,y, x,y, ...)` where `x` and `y` are * Numbers. */ -function Polygon(points) { +function Polygon(points) +{ //if points isn't an array, use arguments as the array - if (!(points instanceof Array)) { + if (!(points instanceof Array)) + { points = Array.prototype.slice.call(arguments); } //if this is a flat array of numbers, convert it to points - if (points[0] instanceof Point) { + if (points[0] instanceof Point) + { var p = []; - for (var i = 0, il = points.length; i < il; i++) { + for (var i = 0, il = points.length; i < il; i++) + { p.push(points[i].x, points[i].y); } @@ -51,7 +55,8 @@ * * @return {Polygon} a copy of the polygon */ -Polygon.prototype.clone = function () { +Polygon.prototype.clone = function () +{ return new Polygon(this.points.slice()); }; @@ -62,19 +67,22 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this polygon */ -Polygon.prototype.contains = function (x, y) { +Polygon.prototype.contains = function (x, y) +{ var inside = false; // use some raycasting to test hits // https://github.com/substack/point-in-polygon/blob/master/index.js var length = this.points.length / 2; - for (var i = 0, j = length - 1; i < length; j = i++) { + for (var i = 0, j = length - 1; i < length; j = i++) + { var xi = this.points[i * 2], yi = this.points[i * 2 + 1], xj = this.points[j * 2], yj = this.points[j * 2 + 1], intersect = ((yi > y) !== (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi); - if (intersect) { + if (intersect) + { inside = !inside; } } diff --git a/src/core/math/shapes/Rectangle.js b/src/core/math/shapes/Rectangle.js index 16ac62a..4008b68 100644 --- a/src/core/math/shapes/Rectangle.js +++ b/src/core/math/shapes/Rectangle.js @@ -10,7 +10,8 @@ * @param width {number} The overall width of this rectangle * @param height {number} The overall height of this rectangle */ -function Rectangle(x, y, width, height) { +function Rectangle(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -60,7 +61,8 @@ * * @return {Rectangle} a copy of the rectangle */ -Rectangle.prototype.clone = function () { +Rectangle.prototype.clone = function () +{ return new Rectangle(this.x, this.y, this.width, this.height); }; @@ -71,13 +73,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rectangle */ -Rectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Rectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/math/shapes/RoundedRectangle.js b/src/core/math/shapes/RoundedRectangle.js index 27d286e..7bf6411 100644 --- a/src/core/math/shapes/RoundedRectangle.js +++ b/src/core/math/shapes/RoundedRectangle.js @@ -11,7 +11,8 @@ * @param height {number} The overall height of this rounded rectangle * @param radius {number} Controls the radius of the rounded corners */ -function RoundedRectangle(x, y, width, height, radius) { +function RoundedRectangle(x, y, width, height, radius) +{ /** * @member {number} * @default 0 @@ -58,7 +59,8 @@ * * @return {RoundedRectangle} a copy of the rounded rectangle */ -RoundedRectangle.prototype.clone = function () { +RoundedRectangle.prototype.clone = function () +{ return new RoundedRectangle(this.x, this.y, this.width, this.height, this.radius); }; @@ -69,13 +71,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rounded Rectangle */ -RoundedRectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +RoundedRectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/primitives/Graphics.js b/src/core/primitives/Graphics.js index 261c534..e902d2a 100644 --- a/src/core/primitives/Graphics.js +++ b/src/core/primitives/Graphics.js @@ -16,7 +16,8 @@ * @extends DisplayObjectContainer * @namespace PIXI */ -function Graphics() { +function Graphics() +{ DisplayObjectContainer.call(this); this.renderable = true; @@ -154,16 +155,20 @@ * @private */ cacheAsBitmap: { - get: function () { + get: function () + { return this._cacheAsBitmap; }, - set: function (value) { + set: function (value) + { this._cacheAsBitmap = value; - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._generateCachedSprite(); } - else { + else + { this.destroyCachedSprite(); this.dirty = true; } @@ -176,7 +181,8 @@ * * @return {Graphics} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ var clone = new Graphics(); clone.renderable = this.renderable; @@ -192,7 +198,8 @@ clone.cachedSpriteDirty = this.cachedSpriteDirty; // copy graphics data - for (var i = 0; i < this.graphicsData.length; ++i) { + for (var i = 0; i < this.graphicsData.length; ++i) + { clone.graphicsData.push(this.graphicsData.clone()); } @@ -211,17 +218,21 @@ * @param alpha {number} alpha of the line to draw, will update the objects stored style * @return {Graphics} */ -Graphics.prototype.lineStyle = function (lineWidth, color, alpha) { +Graphics.prototype.lineStyle = function (lineWidth, color, alpha) +{ this.lineWidth = lineWidth || 0; this.lineColor = color || 0; this.lineAlpha = (arguments.length < 3) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length) + { // halfway through a line? start a new one! this.drawShape( new math.Polygon( this.currentPath.shape.points.slice(-2) )); } - else { + else + { // otherwise its empty so lets just set the line properties this.currentPath.lineWidth = this.lineWidth; this.currentPath.lineColor = this.lineColor; @@ -239,7 +250,8 @@ * @param y {number} the Y coordinate to move to * @return {Graphics} */ -Graphics.prototype.moveTo = function (x, y) { +Graphics.prototype.moveTo = function (x, y) +{ this.drawShape(new math.Polygon([x,y])); return this; @@ -253,7 +265,8 @@ * @param y {number} the Y coordinate to draw to * @return {Graphics} */ -Graphics.prototype.lineTo = function (x, y) { +Graphics.prototype.lineTo = function (x, y) +{ this.currentPath.shape.points.push(x, y); this.dirty = true; @@ -270,13 +283,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -285,7 +302,8 @@ n = 20, points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { this.moveTo(0, 0); } @@ -293,7 +311,8 @@ var fromY = points[points.length-1]; var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; xa = fromX + ( (cpX - fromX) * j ); @@ -319,13 +338,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -342,7 +365,8 @@ var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; dt = (1 - j); @@ -373,13 +397,17 @@ * @param radius {number} The radius of the arc * @return {Graphics} */ -Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points.push(x1, y1); } } - else { + else + { this.moveTo(x1, y1); } @@ -392,12 +420,15 @@ b2 = x2 - x1, mm = Math.abs(a1 * b2 - b1 * a2); - if (mm < 1.0e-8 || radius === 0) { - if (points[points.length-2] !== x1 || points[points.length-1] !== y1) { + if (mm < 1.0e-8 || radius === 0) + { + if (points[points.length-2] !== x1 || points[points.length-1] !== y1) + { points.push(x1, y1); } } - else { + else + { var dd = a1 * a1 + b1 * b1, cc = a2 * a2 + b2 * b2, tt = a1 * a2 + b1 * b2, @@ -433,42 +464,51 @@ * @param anticlockwise {boolean} Optional. Specifies whether the drawing should be counterclockwise or clockwise. False is default, and indicates clockwise, while true indicates counter-clockwise. * @return {Graphics} */ -Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) { +Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) +{ var startX = cx + Math.cos(startAngle) * radius; var startY = cy + Math.sin(startAngle) * radius; var points; // TODO - This if-else makes no sense. It uses currentPath in the else where it doesn't exist... - if (this.currentPath) { + if (this.currentPath) + { points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { points.push(startX, startY); } - else if (points[points.length-2] !== startX || points[points.length-1] !== startY) { + else if (points[points.length-2] !== startX || points[points.length-1] !== startY) + { points.push(startX, startY); } } - else { + else + { this.moveTo(startX, startY); points = this.currentPath.shape.points; } - if (startAngle === endAngle) { + if (startAngle === endAngle) + { return this; } - if (!anticlockwise && endAngle <= startAngle) { + if (!anticlockwise && endAngle <= startAngle) + { endAngle += Math.PI * 2; } - else if (anticlockwise && startAngle <= endAngle) { + else if (anticlockwise && startAngle <= endAngle) + { startAngle += Math.PI * 2; } var sweep = anticlockwise ? (startAngle - endAngle) *-1 : (endAngle - startAngle); var segs = (Math.abs(sweep)/ (Math.PI * 2)) * 40; - if (sweep === 0) { + if (sweep === 0) + { return this; } @@ -482,7 +522,8 @@ var remainder = ( segMinus % 1 ) / segMinus; - for (var i = 0; i <= segMinus; ++i) { + for (var i = 0; i <= segMinus; ++i) + { var real = i + remainder * i; var angle = ((theta) + startAngle + (theta2 * real)); @@ -506,13 +547,16 @@ * @param alpha {number} the alpha of the fill * @return {Graphics} */ -Graphics.prototype.beginFill = function (color, alpha) { +Graphics.prototype.beginFill = function (color, alpha) +{ this.filling = true; this.fillColor = color || 0; this.fillAlpha = (alpha === undefined) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length <= 2) + { this.currentPath.fill = this.filling; this.currentPath.fillColor = this.fillColor; this.currentPath.fillAlpha = this.fillAlpha; @@ -526,7 +570,8 @@ * * @return {Graphics} */ -Graphics.prototype.endFill = function () { +Graphics.prototype.endFill = function () +{ this.filling = false; this.fillColor = null; this.fillAlpha = 1; @@ -542,7 +587,8 @@ * @param height {number} The height of the rectangle * @return {Graphics} */ -Graphics.prototype.drawRect = function ( x, y, width, height ) { +Graphics.prototype.drawRect = function ( x, y, width, height ) +{ this.drawShape(new math.Rectangle(x,y, width, height)); return this; @@ -556,7 +602,8 @@ * @param height {number} The height of the rectangle * @param radius {number} Radius of the rectangle corners */ -Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) { +Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) +{ this.drawShape(new math.RoundedRectangle(x, y, width, height, radius)); return this; @@ -570,7 +617,8 @@ * @param radius {number} The radius of the circle * @return {Graphics} */ -Graphics.prototype.drawCircle = function (x, y, radius) { +Graphics.prototype.drawCircle = function (x, y, radius) +{ this.drawShape(new math.Circle(x,y, radius)); return this; @@ -585,7 +633,8 @@ * @param height {number} The half height of the ellipse * @return {Graphics} */ -Graphics.prototype.drawEllipse = function (x, y, width, height) { +Graphics.prototype.drawEllipse = function (x, y, width, height) +{ this.drawShape(new math.Ellipse(x, y, width, height)); return this; @@ -597,8 +646,10 @@ * @param path {Array} The path data used to construct the polygon. * @return {Graphics} */ -Graphics.prototype.drawPolygon = function (path) { - if (!(path instanceof Array)) { +Graphics.prototype.drawPolygon = function (path) +{ + if (!(path instanceof Array)) + { path = Array.prototype.slice.call(arguments); } @@ -612,7 +663,8 @@ * * @return {Graphics} */ -Graphics.prototype.clear = function () { +Graphics.prototype.clear = function () +{ this.lineWidth = 0; this.filling = false; @@ -631,7 +683,8 @@ * @param scaleMode {number} Should be one of the scaleMode consts * @return {Texture} a texture of the graphics object */ -Graphics.prototype.generateTexture = function (resolution, scaleMode) { +Graphics.prototype.generateTexture = function (resolution, scaleMode) +{ resolution = resolution || 1; var bounds = this.getBounds(); @@ -655,17 +708,21 @@ * * @param renderer {WebGLRenderer} */ -Graphics.prototype._renderWebGL = function (renderer) { +Graphics.prototype._renderWebGL = function (renderer) +{ // if the sprite is not visible or the alpha is 0 then no need to render this element - if (this.isMask === true) { + if (this.isMask === true) + { return; } // this code may still be needed so leaving for now.. - // + // /* - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture on the gpu too! @@ -681,17 +738,24 @@ return; } - */ - - // check if the webgl graphic needs to be updated - if (this.glDirty) { - this.dirty = true; - this.glDirty = false; - } + else */ - renderer.setObjectRendererer(renderer.graphicsRenderer); - renderer.graphicsRenderer.render(this); + renderer.spriteBatch.stop(); + renderer.blendModeManager.setBlendMode(this.blendMode); + // check blend mode + renderer.blendModeManager.setBlendMode( this.blendMode ); + + // check if the webgl graphic needs to be updated + if (this.glDirty) + { + this.dirty = true; + this.glDirty = false; + } + + WebGLGraphics.renderGraphics(this, renderer); + + renderer.spriteBatch.start(); }; /** @@ -700,14 +764,18 @@ * @param renderer {CanvasRenderer} * @private */ -Graphics.prototype.renderCanvas = function (renderer) { +Graphics.prototype.renderCanvas = function (renderer) +{ // 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.isMask === true) { + if (!this.visible || this.alpha <= 0 || this.isMask === true) + { return; } - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture @@ -723,16 +791,19 @@ return; } - else { + else + { var context = renderer.context; var transform = this.worldTransform; - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } @@ -748,11 +819,13 @@ CanvasGraphics.renderGraphics(this, context); - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } } @@ -763,13 +836,16 @@ * * @return {Rectangle} the rectangular bounding area */ -Graphics.prototype.getBounds = function (matrix) { +Graphics.prototype.getBounds = function (matrix) +{ // return an empty object if the item is a mask! - if (this.isMask) { + if (this.isMask) + { return math.Rectangle.EMPTY; } - if (this.dirty) { + if (this.dirty) + { this.updateLocalBounds(); this.glDirty = true; @@ -841,23 +917,27 @@ * Update the bounds of the object * */ -Graphics.prototype.updateLocalBounds = function () { +Graphics.prototype.updateLocalBounds = function () +{ var minX = Infinity; var maxX = -Infinity; var minY = Infinity; var maxY = -Infinity; - if (this.graphicsData.length) { + if (this.graphicsData.length) + { var shape, points, x, y, w, h; - for (var i = 0; i < this.graphicsData.length; i++) { + for (var i = 0; i < this.graphicsData.length; i++) + { var data = this.graphicsData[i]; var type = data.type; var lineWidth = data.lineWidth; shape = data.shape; - if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) { + if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) + { x = shape.x - lineWidth/2; y = shape.y - lineWidth/2; w = shape.width + lineWidth; @@ -869,7 +949,8 @@ minY = y < minY ? y : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.CIRC) { + else if (type === CONST.SHAPES.CIRC) + { x = shape.x; y = shape.y; w = shape.radius + lineWidth/2; @@ -881,7 +962,8 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.ELIP) { + else if (type === CONST.SHAPES.ELIP) + { x = shape.x; y = shape.y; w = shape.width + lineWidth/2; @@ -893,11 +975,13 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else { + else + { // POLY points = shape.points; - for (var j = 0; j < points.length; j += 2) { + for (var j = 0; j < points.length; j += 2) + { x = points[j]; y = points[j+1]; @@ -910,7 +994,8 @@ } } } - else { + else + { minX = 0; maxX = 0; minY = 0; @@ -931,10 +1016,12 @@ * * @private */ -Graphics.prototype._generateCachedSprite = function () { +Graphics.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { var canvasBuffer = new CanvasBuffer(bounds.width, bounds.height); var texture = Texture.fromCanvas(canvasBuffer.canvas); @@ -943,7 +1030,8 @@ this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.buffer.resize(bounds.width, bounds.height); } @@ -968,7 +1056,8 @@ * * @private */ -Graphics.prototype.updateCachedSpriteTexture = function () { +Graphics.prototype.updateCachedSpriteTexture = function () +{ var cachedSprite = this._cachedSprite; var texture = cachedSprite.texture; var canvas = cachedSprite.buffer.canvas; @@ -989,7 +1078,8 @@ * Destroys a previous cached sprite. * */ -Graphics.prototype.destroyCachedSprite = function () { +Graphics.prototype.destroyCachedSprite = function () +{ this._cachedSprite.texture.destroy(true); // let the gc collect the unused sprite @@ -1003,10 +1093,13 @@ * @param {Circle|Rectangle|Ellipse|Line|Polygon} shape The Shape object to draw. * @return {GraphicsData} The generated GraphicsData object. */ -Graphics.prototype.drawShape = function (shape) { - if (this.currentPath) { +Graphics.prototype.drawShape = function (shape) +{ + if (this.currentPath) + { // check current path! - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath.shape.points.length <= 2) + { this.graphicsData.pop(); } } @@ -1017,7 +1110,8 @@ this.graphicsData.push(data); - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { data.shape.closed = this.filling; this.currentPath = data; } diff --git a/src/core/primitives/GraphicsData.js b/src/core/primitives/GraphicsData.js index 99decbe..788f6f2 100644 --- a/src/core/primitives/GraphicsData.js +++ b/src/core/primitives/GraphicsData.js @@ -4,7 +4,8 @@ * @class * @namespace PIXI */ -function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) { +function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) +{ this.lineWidth = lineWidth; this.lineColor = lineColor; this.lineAlpha = lineAlpha; @@ -27,7 +28,8 @@ * * @return {GraphicsData} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ return new GraphicsData( this.lineWidth, this.lineColor, diff --git a/src/core/renderers/canvas/CanvasRenderer.js b/src/core/renderers/canvas/CanvasRenderer.js index 15a0978..7aebd44 100644 --- a/src/core/renderers/canvas/CanvasRenderer.js +++ b/src/core/renderers/canvas/CanvasRenderer.js @@ -17,17 +17,22 @@ * @param [options.resolution=1] {number} the resolution of the renderer retina would be 2 * @param [options.clearBeforeRender=true] {boolean} This sets if the CanvasRenderer will clear the canvas or not before the new render pass. */ -function CanvasRenderer(width, height, options) { +function CanvasRenderer(width, height, options) +{ utils.sayHello('Canvas'); - if (options) { - for (var i in CONST.defaultRenderOptions) { - if (typeof options[i] === 'undefined') { + if (options) + { + for (var i in CONST.defaultRenderOptions) + { + if (typeof options[i] === 'undefined') + { options[i] = CONST.defaultRenderOptions[i]; } } } - else { + else + { options = CONST.defaultRenderOptions; } @@ -156,19 +161,24 @@ this.smoothProperty = null; - if (this.context.imageSmoothingEnabled) { + if (this.context.imageSmoothingEnabled) + { this.smoothProperty = 'imageSmoothingEnabled'; } - else if (this.context.webkitImageSmoothingEnabled) { + else if (this.context.webkitImageSmoothingEnabled) + { this.smoothProperty = 'webkitImageSmoothingEnabled'; } - else if (this.context.mozImageSmoothingEnabled) { + else if (this.context.mozImageSmoothingEnabled) + { this.smoothProperty = 'mozImageSmoothingEnabled'; } - else if (this.context.oImageSmoothingEnabled) { + else if (this.context.oImageSmoothingEnabled) + { this.smoothProperty = 'oImageSmoothingEnabled'; } - else if (this.context.msImageSmoothingEnabled) { + else if (this.context.msImageSmoothingEnabled) + { this.smoothProperty = 'msImageSmoothingEnabled'; } @@ -193,10 +203,12 @@ * @memberof CanvasRenderer# */ backgroundColor: { - get: function () { + get: function () + { return this._backgroundColor; }, - set: function (val) { + set: function (val) + { this._backgroundColor = val; this._backgroundColorString = utils.hex2string(val); } @@ -208,7 +220,8 @@ * * @param object {DisplayObject} the object to be rendered */ -CanvasRenderer.prototype.render = function (object) { +CanvasRenderer.prototype.render = function (object) +{ object.updateTransform(); this.context.setTransform(1,0,0,1,0,0); @@ -218,16 +231,20 @@ this.currentBlendMode = CONST.blendModes.NORMAL; this.context.globalCompositeOperation = this.blendModes[CONST.blendModes.NORMAL]; - if (navigator.isCocoonJS && this.view.screencanvas) { + if (navigator.isCocoonJS && this.view.screencanvas) + { this.context.fillStyle = 'black'; this.context.clear(); } - if (this.clearBeforeRender) { - if (this.transparent) { + if (this.clearBeforeRender) + { + if (this.transparent) + { this.context.clearRect(0, 0, this.width, this.height); } - else { + else + { this.context.fillStyle = this._backgroundColorString; this.context.fillRect(0, 0, this.width , this.height); } @@ -241,8 +258,10 @@ * * @param [removeView=false] {boolean} Removes the Canvas element from the DOM. */ -CanvasRenderer.prototype.destroy = function (removeView) { - if (removeView && this.view.parent) { +CanvasRenderer.prototype.destroy = function (removeView) +{ + if (removeView && this.view.parent) + { this.view.parent.removeChild(this.view); } @@ -257,14 +276,16 @@ * @param width {number} the new width of the canvas view * @param height {number} the new height of the canvas view */ -CanvasRenderer.prototype.resize = function (width, height) { +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) { + if (this.autoResize) + { this.view.style.width = this.width / this.resolution + 'px'; this.view.style.height = this.height / this.resolution + 'px'; } @@ -276,7 +297,8 @@ * @param displayObject {DisplayObject} The displayObject to render * @private */ -CanvasRenderer.prototype.renderDisplayObject = function (displayObject) { +CanvasRenderer.prototype.renderDisplayObject = function (displayObject) +{ displayObject.renderCanvas(this); }; @@ -285,11 +307,14 @@ * * @private */ -CanvasRenderer.prototype._mapBlendModes = function () { - if (!this.blendModes) { +CanvasRenderer.prototype._mapBlendModes = function () +{ + if (!this.blendModes) + { this.blendModes = {}; - if (utils.canUseNewCanvasBlendModes()) { + if (utils.canUseNewCanvasBlendModes()) + { this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? this.blendModes[CONST.blendModes.MULTIPLY] = 'multiply'; @@ -308,7 +333,8 @@ this.blendModes[CONST.blendModes.COLOR] = 'color'; this.blendModes[CONST.blendModes.LUMINOSITY] = 'luminosity'; } - else { + else + { // this means that the browser does not support the cool new blend modes in canvas 'cough' ie 'cough' this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? diff --git a/src/core/renderers/canvas/utils/CanvasBuffer.js b/src/core/renderers/canvas/utils/CanvasBuffer.js index ebe5d47..b183a66 100644 --- a/src/core/renderers/canvas/utils/CanvasBuffer.js +++ b/src/core/renderers/canvas/utils/CanvasBuffer.js @@ -6,7 +6,8 @@ * @param width {number} the width for the newly created canvas * @param height {number} the height for the newly created canvas */ -function CanvasBuffer(width, height) { +function CanvasBuffer(width, height) +{ /** * The Canvas object that belongs to this CanvasBuffer. * @@ -36,10 +37,12 @@ * @memberof CanvasBuffer# */ width: { - get: function () { + get: function () + { return this.canvas.width; }, - set: function (val) { + set: function (val) + { this.canvas.width = val; } }, @@ -50,10 +53,12 @@ * @memberof CanvasBuffer# */ height: { - get: function () { + get: function () + { return this.canvas.height; }, - set: function (val) { + set: function (val) + { this.canvas.height = val; } } @@ -64,7 +69,8 @@ * * @private */ -CanvasBuffer.prototype.clear = function () { +CanvasBuffer.prototype.clear = function () +{ this.context.setTransform(1, 0, 0, 1, 0, 0); this.context.clearRect(0,0, this.canvas.width, this.canvas.height); }; @@ -75,7 +81,8 @@ * @param width {number} the new width of the canvas * @param height {number} the new height of the canvas */ -CanvasBuffer.prototype.resize = function (width, height) { +CanvasBuffer.prototype.resize = function (width, height) +{ this.canvas.width = width; this.canvas.height = height; }; diff --git a/src/core/renderers/canvas/utils/CanvasGraphics.js b/src/core/renderers/canvas/utils/CanvasGraphics.js index c7eaa2a..3f2a91f 100644 --- a/src/core/renderers/canvas/utils/CanvasGraphics.js +++ b/src/core/renderers/canvas/utils/CanvasGraphics.js @@ -13,15 +13,18 @@ * @param graphics {Graphics} the actual graphics object to render * @param context {CanvasRenderingContext2D} the 2d drawing method of the canvas */ -CanvasGraphics.renderGraphics = function (graphics, context) { +CanvasGraphics.renderGraphics = function (graphics, context) +{ var worldAlpha = graphics.worldAlpha; - if (graphics.dirty) { + if (graphics.dirty) + { this.updateGraphicsTint(graphics); graphics.dirty = false; } - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; @@ -30,69 +33,82 @@ context.lineWidth = data.lineWidth; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { context.beginPath(); var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } - if (shape.closed) { + if (shape.closed) + { context.lineTo(points[0], points[1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fillRect(shape.x, shape.y, shape.width, shape.height); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.strokeRect(shape.x, shape.y, shape.width, shape.height); } } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.beginPath(); context.arc(shape.x, shape.y, shape.radius,0,2*Math.PI); context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas var w = shape.width * 2; @@ -119,18 +135,21 @@ context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; var width = shape.width; @@ -152,13 +171,15 @@ context.quadraticCurveTo(rx, ry, rx, ry + radius); context.closePath(); - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); @@ -174,45 +195,54 @@ * @param graphics {Graphics} the graphics which will be used as a mask * @param context {CanvasRenderingContext2D} the context 2d method of the canvas */ -CanvasGraphics.renderGraphicsMask = function (graphics, context) { +CanvasGraphics.renderGraphicsMask = function (graphics, context) +{ var len = graphics.graphicsData.length; - if (len === 0) { + if (len === 0) + { return; } context.beginPath(); - for (var i = 0; i < len; i++) { + for (var i = 0; i < len; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { context.rect(shape.x, shape.y, shape.width, shape.height); context.closePath(); } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.arc(shape.x, shape.y, shape.radius, 0, 2 * Math.PI); context.closePath(); } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas @@ -237,7 +267,8 @@ context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); context.closePath(); } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; @@ -262,8 +293,10 @@ } }; -CanvasGraphics.updateGraphicsTint = function (graphics) { - if (graphics.tint === 0xFFFFFF) { +CanvasGraphics.updateGraphicsTint = function (graphics) +{ + if (graphics.tint === 0xFFFFFF) + { return; } @@ -271,7 +304,8 @@ var tintG = (graphics.tint >> 8 & 0xFF) / 255; var tintB = (graphics.tint & 0xFF)/ 255; - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var fillColor = data.fillColor | 0; diff --git a/src/core/renderers/canvas/utils/CanvasMaskManager.js b/src/core/renderers/canvas/utils/CanvasMaskManager.js index e04a733..9827d36 100644 --- a/src/core/renderers/canvas/utils/CanvasMaskManager.js +++ b/src/core/renderers/canvas/utils/CanvasMaskManager.js @@ -6,7 +6,8 @@ * @class * @namespace PIXI */ -function CanvasMaskManager() {} +function CanvasMaskManager() +{} CanvasMaskManager.prototype.constructor = CanvasMaskManager; module.exports = CanvasMaskManager; @@ -17,7 +18,8 @@ * @param maskData {object} the maskData that will be pushed * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.pushMask = function (maskData, renderer) { +CanvasMaskManager.prototype.pushMask = function (maskData, renderer) +{ renderer.context.save(); var cacheAlpha = maskData.alpha; @@ -45,6 +47,7 @@ * * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.popMask = function (renderer) { +CanvasMaskManager.prototype.popMask = function (renderer) +{ renderer.context.restore(); }; diff --git a/src/core/renderers/canvas/utils/CanvasTinter.js b/src/core/renderers/canvas/utils/CanvasTinter.js index 17e0529..d2fb1bc 100644 --- a/src/core/renderers/canvas/utils/CanvasTinter.js +++ b/src/core/renderers/canvas/utils/CanvasTinter.js @@ -14,7 +14,8 @@ * @param color {number} the color to use to tint the sprite with * @return {HTMLCanvasElement} The tinted canvas */ -CanvasTinter.getTintedTexture = function (sprite, color) { +CanvasTinter.getTintedTexture = function (sprite, color) +{ var texture = sprite.texture; color = CanvasTinter.roundColor(color); @@ -23,7 +24,8 @@ texture.tintCache = texture.tintCache || {}; - if (texture.tintCache[stringColor]) { + if (texture.tintCache[stringColor]) + { return texture.tintCache[stringColor]; } @@ -33,14 +35,16 @@ //CanvasTinter.tintWithPerPixel(texture, stringColor, canvas); CanvasTinter.tintMethod(texture, color, canvas); - if (CanvasTinter.convertTintToImage) { + if (CanvasTinter.convertTintToImage) + { // is this better? var tintImage = new Image(); tintImage.src = canvas.toDataURL(); texture.tintCache[stringColor] = tintImage; } - else { + else + { texture.tintCache[stringColor] = canvas; // if we are not converting the texture to an image then we need to lose the reference to the canvas CanvasTinter.canvas = null; @@ -56,7 +60,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithMultiply = function (texture, color, canvas) { +CanvasTinter.tintWithMultiply = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -104,7 +109,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithOverlay = function (texture, color, canvas) { +CanvasTinter.tintWithOverlay = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -139,7 +145,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithPerPixel = function (texture, color, canvas) { +CanvasTinter.tintWithPerPixel = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -167,7 +174,8 @@ var pixels = pixelData.data; - for (var i = 0; i < pixels.length; i += 4) { + for (var i = 0; i < pixels.length; i += 4) + { pixels[i+0] *= r; pixels[i+1] *= g; pixels[i+2] *= b; @@ -181,7 +189,8 @@ * * @param color {number} the color to round, should be a hex color */ -CanvasTinter.roundColor = function (color) { +CanvasTinter.roundColor = function (color) +{ var step = CanvasTinter.cacheStepsPerColorChannel; var rgbValues = utils.hex2rgb(color); diff --git a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js index 9f2f89a..35edbaf 100644 --- a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js +++ b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLBlendModeManager(renderer) { +function WebGLBlendModeManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -23,8 +24,10 @@ * * @param blendMode {number} the blendMode, should be a Pixi const, such as BlendModes.ADD */ -WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) { - if (this.currentBlendMode === blendMode) { +WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) +{ + if (this.currentBlendMode === blendMode) + { return false; } diff --git a/src/core/renderers/webgl/managers/WebGLFilterManager.js b/src/core/renderers/webgl/managers/WebGLFilterManager.js index 1179258..2dac048 100644 --- a/src/core/renderers/webgl/managers/WebGLFilterManager.js +++ b/src/core/renderers/webgl/managers/WebGLFilterManager.js @@ -7,7 +7,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLFilterManager(renderer) { +function WebGLFilterManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -32,7 +33,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.texturePool.length = 0; self.initShaderBuffers(); }); @@ -46,7 +48,8 @@ * @param renderer {WebGLRenderer} * @param buffer {ArrayBuffer} */ -WebGLFilterManager.prototype.begin = function (buffer) { +WebGLFilterManager.prototype.begin = function (buffer) +{ this.defaultShader = this.renderer.shaderManager.defaultShader; this.width = this.renderer.projection.x * 2; @@ -60,7 +63,8 @@ * * @param filterBlock {object} the filter that will be pushed to the current filter stack */ -WebGLFilterManager.prototype.pushFilter = function (filterBlock) { +WebGLFilterManager.prototype.pushFilter = function (filterBlock) +{ var gl = this.renderer.gl; var projection = this.renderer.projection; @@ -78,10 +82,12 @@ this.offsetY += filterBlock._filterArea.y; var texture = this.texturePool.pop(); - if (!texture) { + if (!texture) + { texture = new FilterTexture(this.renderer.gl, this.width, this.height); } - else { + else + { texture.resize(this.width, this.height); } @@ -98,29 +104,35 @@ var localX = filterArea.x, localY = filterArea.y; - if (filterArea.x < 0) { + if (filterArea.x < 0) + { filterArea.width += filterArea.x; filterArea.x = 0; } - if (filterArea.y < 0) { + if (filterArea.y < 0) + { filterArea.height += filterArea.y; filterArea.y = 0; } - if (localX + filterArea.width > this.width) { + if (localX + filterArea.width > this.width) + { filterArea.width = this.width - localX; } - if (localY + filterArea.height > this.height) { + if (localY + filterArea.height > this.height) + { filterArea.height = this.height - localY; } - if (filterArea.width < 0) { + if (filterArea.width < 0) + { filterArea.width = 0; } - if (filterArea.height < 0) { + if (filterArea.height < 0) + { filterArea.height = 0; } @@ -154,7 +166,8 @@ * Removes the last filter from the filter stack and doesn't return it. * */ -WebGLFilterManager.prototype.popFilter = function () { +WebGLFilterManager.prototype.popFilter = function () +{ var gl = this.renderer.gl; var filterBlock = this.filterStack.pop(); @@ -163,7 +176,8 @@ var projection = this.renderer.projection; var offset = this.renderer.offset; - if (filterBlock.filterPasses.length > 1) { + if (filterBlock.filterPasses.length > 1) + { gl.viewport(0, 0, filterArea.width, filterArea.height); gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); @@ -193,7 +207,8 @@ var inputTexture = texture; var outputTexture = this.texturePool.pop(); - if (!outputTexture) { + if (!outputTexture) + { outputTexture = new FilterTexture(this.renderer.gl, this.width, this.height); } outputTexture.resize(this.width, this.height); @@ -204,7 +219,8 @@ gl.disable(gl.BLEND); - for (var i = 0; i < filterBlock.filterPasses.length-1; i++) { + for (var i = 0; i < filterBlock.filterPasses.length-1; i++) + { var filterPass = filterBlock.filterPasses[i]; gl.bindFramebuffer(gl.FRAMEBUFFER, outputTexture.frameBuffer ); @@ -243,10 +259,12 @@ var buffer = this.buffer; // time to render the filters texture to the previous scene - if (this.filterStack.length === 0) { + if (this.filterStack.length === 0) + { gl.colorMask(true, true, true, true);//this.transparent); } - else { + else + { var currentFilter = this.filterStack[this.filterStack.length-1]; filterArea = currentFilter._filterArea; @@ -332,13 +350,15 @@ * @param width {number} the horizontal range of the filter * @param height {number} the vertical range of the filter */ -WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) { +WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) +{ // use program var gl = this.renderer.gl; var shader = filter.shaders[gl.id]; - if (!shader) { + if (!shader) + { shader = new Shader(gl); shader.fragmentSrc = filter.fragmentSrc; @@ -356,7 +376,8 @@ gl.uniform2f(shader.projectionVector, width/2, -height/2); gl.uniform2f(shader.offsetVector, 0,0); - if (filter.uniforms.dimensions) { + 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]; @@ -386,7 +407,8 @@ * Initialises the shader buffers. * */ -WebGLFilterManager.prototype.initShaderBuffers = function () { +WebGLFilterManager.prototype.initShaderBuffers = function () +{ var gl = this.renderer.gl; // create some buffers @@ -432,7 +454,8 @@ * Destroys the filter and removes it from the filter stack. * */ -WebGLFilterManager.prototype.destroy = function () { +WebGLFilterManager.prototype.destroy = function () +{ var gl = this.renderer.gl; this.filterStack = null; @@ -441,7 +464,8 @@ this.offsetY = 0; // destroy textures - for (var i = 0; i < this.texturePool.length; i++) { + for (var i = 0; i < this.texturePool.length; i++) + { this.texturePool[i].destroy(); } diff --git a/src/core/renderers/webgl/managers/WebGLManager.js b/src/core/renderers/webgl/managers/WebGLManager.js index 9d47b5c..c30cd51 100644 --- a/src/core/renderers/webgl/managers/WebGLManager.js +++ b/src/core/renderers/webgl/managers/WebGLManager.js @@ -3,7 +3,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLManager(renderer) { +function WebGLManager(renderer) +{ /** * The renderer this manager works for. * @@ -15,6 +16,7 @@ WebGLManager.prototype.constructor = WebGLManager; module.exports = WebGLManager; -WebGLManager.prototype.destroy = function () { +WebGLManager.prototype.destroy = function () +{ this.renderer = null; }; diff --git a/src/core/renderers/webgl/managers/WebGLMaskManager.js b/src/core/renderers/webgl/managers/WebGLMaskManager.js index 2f90b64..e568812 100644 --- a/src/core/renderers/webgl/managers/WebGLMaskManager.js +++ b/src/core/renderers/webgl/managers/WebGLMaskManager.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLMaskManager(renderer) { +function WebGLMaskManager(renderer) +{ WebGLManager.call(this, renderer); } @@ -19,12 +20,15 @@ * * @param maskData {any[]} */ -WebGLMaskManager.prototype.pushMask = function (maskData) { - if (maskData.dirty) { +WebGLMaskManager.prototype.pushMask = function (maskData) +{ + if (maskData.dirty) + { WebGLGraphics.updateGraphics(maskData, this.renderer.gl); } - if (!maskData._webGL[this.renderer.gl.id].data.length) { + if (!maskData._webGL[this.renderer.gl.id].data.length) + { return; } @@ -36,6 +40,7 @@ * * @param maskData {any[]} */ -WebGLMaskManager.prototype.popMask = function (maskData) { +WebGLMaskManager.prototype.popMask = function (maskData) +{ this.renderer.stencilManager.popStencil(maskData, maskData._webGL[this.renderer.gl.id].data[0], this.renderer); }; diff --git a/src/core/renderers/webgl/managers/WebGLShaderManager.js b/src/core/renderers/webgl/managers/WebGLShaderManager.js index fef071c..90c6477 100644 --- a/src/core/renderers/webgl/managers/WebGLShaderManager.js +++ b/src/core/renderers/webgl/managers/WebGLShaderManager.js @@ -10,7 +10,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLShaderManager(renderer) { +function WebGLShaderManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -28,7 +29,8 @@ */ this.tempAttribState = []; - for (var i = 0; i < this.maxAttibs; i++) { + for (var i = 0; i < this.maxAttibs; i++) + { this.attribState[i] = false; } @@ -66,7 +68,8 @@ // listen for context and update necessary shaders var self = this; - this.renderer.on('context', function (event) { + this.renderer.on('context', function (event) + { var gl = event.data; // this shader is used for rendering primitives @@ -97,29 +100,36 @@ * * @param attribs {Array} attribs */ -WebGLShaderManager.prototype.setAttribs = function (attribs) { +WebGLShaderManager.prototype.setAttribs = function (attribs) +{ // reset temp state var i; - for (i = 0; i < this.tempAttribState.length; i++) { + for (i = 0; i < this.tempAttribState.length; i++) + { this.tempAttribState[i] = false; } // set the new attribs - for (var a in attribs) { + for (var a in attribs) + { this.tempAttribState[attribs[a]] = true; } var gl = this.renderer.gl; - for (i = 0; i < this.attribState.length; i++) { - if (this.attribState[i] !== this.tempAttribState[i]) { + for (i = 0; i < this.attribState.length; i++) + { + if (this.attribState[i] !== this.tempAttribState[i]) + { this.attribState[i] = this.tempAttribState[i]; - if (this.attribState[i]) { + if (this.attribState[i]) + { gl.enableVertexAttribArray(i); } - else { + else + { gl.disableVertexAttribArray(i); } } @@ -131,8 +141,10 @@ * * @param shader {Any} */ -WebGLShaderManager.prototype.setShader = function (shader) { - if (this._currentId === shader.uuid) { +WebGLShaderManager.prototype.setShader = function (shader) +{ + if (this._currentId === shader.uuid) + { return false; } @@ -150,7 +162,8 @@ * Destroys this object. * */ -WebGLShaderManager.prototype.destroy = function () { +WebGLShaderManager.prototype.destroy = function () +{ this.attribState = null; this.tempAttribState = null; diff --git a/src/core/renderers/webgl/managers/WebGLStencilManager.js b/src/core/renderers/webgl/managers/WebGLStencilManager.js index 9ec6398..4cb0134 100644 --- a/src/core/renderers/webgl/managers/WebGLStencilManager.js +++ b/src/core/renderers/webgl/managers/WebGLStencilManager.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLStencilManager(renderer) { +function WebGLStencilManager(renderer) +{ WebGLManager.call(this, renderer); this.stencilStack = []; @@ -24,12 +25,14 @@ * @param graphics {Graphics} * @param webGLData {any[]} */ -WebGLStencilManager.prototype.pushStencil = function (graphics, webGLData) { +WebGLStencilManager.prototype.pushStencil = function (graphics, webGLData) +{ var gl = this.renderer.gl; this.bindGraphics(graphics, webGLData, this.renderer); - if (this.stencilStack.length === 0) { + if (this.stencilStack.length === 0) + { gl.enable(gl.STENCIL_TEST); gl.clear(gl.STENCIL_BUFFER_BIT); this.reverse = true; @@ -47,14 +50,17 @@ // draw the triangle strip! - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } @@ -62,31 +68,38 @@ // draw a quad to increment.. gl.drawElements(gl.TRIANGLE_FAN, 4, gl.UNSIGNED_SHORT, ( webGLData.indices.length - 4 ) * 2 ); - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); } this.reverse = !this.reverse; } - else { - if (!this.reverse) { + else + { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } - else { + 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) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); } } @@ -103,7 +116,8 @@ * @param graphics {Graphics} * @param webGLData {Array} */ -WebGLStencilManager.prototype.bindGraphics = function (graphics, webGLData) { +WebGLStencilManager.prototype.bindGraphics = function (graphics, webGLData) +{ //if (this._currentGraphics === graphics)return; this._currentGraphics = graphics; @@ -114,7 +128,8 @@ offset = this.renderer.offset, shader;// = this.renderer.shaderManager.primitiveShader; - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { shader = this.renderer.shaderManager.complexPrimitiveShader; this.renderer.shaderManager.setShader(shader); @@ -141,7 +156,8 @@ // set the index buffer! gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, webGLData.indexBuffer); } - else { + else + { //this.renderer.shaderManager.activatePrimitiveShader(); shader = this.renderer.shaderManager.primitiveShader; this.renderer.shaderManager.setShader( shader ); @@ -154,7 +170,7 @@ gl.uniform2f(shader.uniforms.offsetVector._location, -offset.x, -offset.y); gl.uniform3fv(shader.uniforms.tint._location, utils.hex2rgb(graphics.tint)); - + gl.uniform1f(shader.uniforms.alpha._location, graphics.worldAlpha); @@ -172,19 +188,22 @@ * @param graphics {Graphics} * @param webGLData {Array} */ -WebGLStencilManager.prototype.popStencil = function (graphics, webGLData) { +WebGLStencilManager.prototype.popStencil = function (graphics, webGLData) +{ var gl = this.renderer.gl; this.stencilStack.pop(); this.count--; - if (this.stencilStack.length === 0) { + if (this.stencilStack.length === 0) + { // the stack is empty! gl.disable(gl.STENCIL_TEST); } - else { + else + { var level = this.count; @@ -192,14 +211,17 @@ gl.colorMask(false, false, false, false); - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { this.reverse = !this.reverse; - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } @@ -213,31 +235,38 @@ // draw the triangle strip! gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); - if (!this.reverse) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); } } - else { + else + { // console.log("<<>>") - if (!this.reverse) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } - else { + 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) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); } } @@ -253,7 +282,8 @@ * Destroys the mask stack. * */ -WebGLStencilManager.prototype.destroy = function () { +WebGLStencilManager.prototype.destroy = function () +{ this.renderer = null; this.stencilStack = null; }; diff --git a/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js b/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js index 913ba5e..1ea7d19 100644 --- a/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js +++ b/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function ComplexPrimitiveShader(gl) { +function ComplexPrimitiveShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -24,7 +25,8 @@ 'uniform float flipY;', 'varying vec4 vColor;', - 'void main(void) {', + '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);', @@ -37,7 +39,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = vColor;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/FastShader.js b/src/core/renderers/webgl/shaders/FastShader.js index bd2e29a..2e5e060 100644 --- a/src/core/renderers/webgl/shaders/FastShader.js +++ b/src/core/renderers/webgl/shaders/FastShader.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function FastShader(gl) { +function FastShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -28,7 +29,8 @@ 'const vec2 center = vec2(-1.0, 1.0);', - 'void main(void) {', + 'void main(void) + {', ' vec2 v;', ' vec2 sv = aVertexPosition * aScale;', ' v.x = (sv.x) * cos(aRotation) - (sv.y) * sin(aRotation);', @@ -49,7 +51,8 @@ 'uniform sampler2D uSampler;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/PrimitiveShader.js b/src/core/renderers/webgl/shaders/PrimitiveShader.js index 6f25409..a25f54f 100644 --- a/src/core/renderers/webgl/shaders/PrimitiveShader.js +++ b/src/core/renderers/webgl/shaders/PrimitiveShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function PrimitiveShader(gl) { +function PrimitiveShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -23,7 +24,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + '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);', @@ -36,7 +38,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = vColor;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/Shader.js b/src/core/renderers/webgl/shaders/Shader.js index f8964f5..fd75ef5 100644 --- a/src/core/renderers/webgl/shaders/Shader.js +++ b/src/core/renderers/webgl/shaders/Shader.js @@ -6,7 +6,8 @@ * @param [fragmentSrc] {string} The source of the fragment shader. * @param [vertexSrc] {string} The source of the vertex shader. */ -function Shader(gl, vertexSrc, fragmentSrc, customUniforms, customAttributes) { +function Shader(gl, vertexSrc, fragmentSrc, customUniforms, customAttributes) +{ /** * @member {number} * @readonly @@ -33,7 +34,8 @@ dimensions: { type: '4f', value: new Float32Array(4) } }; - for (var u in customUniforms) { + for (var u in customUniforms) + { this.uniforms[u] = customUniforms[u]; } @@ -43,7 +45,8 @@ aColor: 0 }; - for (var a in customAttributes) { + for (var a in customAttributes) + { this.attributes[a] = customAttributes[a]; } @@ -66,7 +69,8 @@ 'const vec2 center = vec2(-1.0, 1.0);', - 'void main(void) {', + 'void main(void) + {', ' gl_Position = vec4( ((aVertexPosition + offsetVector) / projectionVector) + center , 0.0, 1.0);', ' vTextureCoord = aTextureCoord;', ' vColor = vec4(aColor.rgb * aColor.a, aColor.a);', @@ -85,7 +89,8 @@ 'uniform sampler2D uSampler;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;', '}' ].join('\n'); @@ -96,7 +101,8 @@ Shader.prototype.constructor = Shader; module.exports = Shader; -Shader.prototype.init = function () { +Shader.prototype.init = function () +{ this.compile(); this.gl.useProgram(this.program); @@ -105,14 +111,18 @@ this.cacheAttributeLocations(Object.keys(this.attributes)); }; -Shader.prototype.cacheUniformLocations = function (keys) { - for (var i = 0; i < keys.length; ++i) { +Shader.prototype.cacheUniformLocations = function (keys) +{ + for (var i = 0; i < keys.length; ++i) + { this.uniforms[keys[i]]._location = this.gl.getUniformLocation(this.program, keys[i]); } }; -Shader.prototype.cacheAttributeLocations = function (keys) { - for (var i = 0; i < keys.length; ++i) { +Shader.prototype.cacheAttributeLocations = function (keys) +{ + for (var i = 0; i < keys.length; ++i) + { this.attributes[keys[i]] = this.gl.getAttribLocation(this.program, keys[i]); } @@ -124,14 +134,16 @@ // 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.attributes.aColor === -1) { + // if (this.attributes.aColor === -1) + { // this.attributes.aColor = 2; // } // End worst hack eva // }; -Shader.prototype.compile = function () { +Shader.prototype.compile = function () +{ var gl = this.gl; var glVertShader = this._glCompile(gl.VERTEX_SHADER, this.vertexSrc); @@ -144,13 +156,15 @@ gl.linkProgram(program); // if linking fails, then log and cleanup - if (!gl.getProgramParameter(program, gl.LINK_STATUS)) { + if (!gl.getProgramParameter(program, gl.LINK_STATUS)) + { window.console.error('Pixi.js Error: Could not initialize shader.'); window.console.error('gl.VALIDATE_STATUS', gl.getProgramParameter(program, gl.VALIDATE_STATUS)); window.console.error('gl.getError()', gl.getError()); // if there is a program info log, log it - if (gl.getProgramInfoLog(program) !== '') { + if (gl.getProgramInfoLog(program) !== '') + { window.console.warn('Pixi.js Warning: gl.getProgramInfoLog()', gl.getProgramInfoLog(program)); } @@ -165,18 +179,21 @@ return (this.program = program); }; -Shader.prototype.syncUniforms = function () { +Shader.prototype.syncUniforms = function () +{ var gl = this.gl; this.textureCount = 1; - for (var key in this.uniforms) { + for (var key in this.uniforms) + { var uniform = this.uniforms[key], location = uniform._location, value = uniform.value, i, il; - switch (uniform.type) { + switch (uniform.type) + { // single int value case 'i': case '1i': @@ -282,7 +299,8 @@ // a Color Value case 'c': - if (typeof value === 'number') { + if (typeof value === 'number') + { value = utils.hex2rgb(value); } @@ -311,11 +329,13 @@ // array of 2D Point objects case 'v2v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(2 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 2] = value[i].x; uniform._array[i * 2 + 1] = value[i].y; } @@ -325,11 +345,13 @@ // array of 3D Point objects case 'v3v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(3 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 3] = value[i].x; uniform._array[i * 3 + 1] = value[i].y; uniform._array[i * 3 + 2] = value[i].z; @@ -341,11 +363,13 @@ // array of 4D Point objects case 'v4v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(4 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 4] = value[i].x; uniform._array[i * 4 + 1] = value[i].y; uniform._array[i * 4 + 2] = value[i].z; @@ -359,7 +383,8 @@ // PIXI.Texture case 't': case 'sampler2D': - if (!uniform.value || !uniform.value.baseTexture || !uniform.value.baseTexture.hasLoaded) { + if (!uniform.value || !uniform.value.baseTexture || !uniform.value.baseTexture.hasLoaded) + { break; } @@ -376,7 +401,8 @@ this.textureCount++; // initialize the texture if we haven't yet - if (!uniform._init) { + if (!uniform._init) + { this.initSampler2D(uniform); uniform._init = true; @@ -394,11 +420,13 @@ * Initialises a Sampler2D uniform (which may only be available later on after initUniforms once the texture has loaded) * */ -Shader.prototype.initSampler2D = function (uniform) { +Shader.prototype.initSampler2D = function (uniform) +{ var gl = this.gl; // Extended texture data - if (uniform.textureData) { + if (uniform.textureData) + { var data = uniform.textureData; // GLTexture = mag linear, min linear_mipmap_linear, wrap repeat + gl.generateMipmap(gl.TEXTURE_2D); @@ -417,14 +445,16 @@ var wrapT = (data.wrapT) ? data.wrapT : gl.CLAMP_TO_EDGE; var format = (data.luminance) ? gl.LUMINANCE : gl.RGBA; - if (data.repeat) { + if (data.repeat) + { wrapS = gl.REPEAT; wrapT = gl.REPEAT; } gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, !!data.flipY); - if (data.width) { + if (data.width) + { var width = (data.width) ? data.width : 512; var height = (data.height) ? data.height : 2; var border = (data.border) ? data.border : 0; @@ -432,7 +462,8 @@ // 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 { + 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); } @@ -448,7 +479,8 @@ * Destroys the shader. * */ -Shader.prototype.destroy = function () { +Shader.prototype.destroy = function () +{ this.gl.deleteProgram(this.program); this.gl = null; @@ -459,13 +491,15 @@ this.fragmentSrc = null; }; -Shader.prototype._glCompile = function (type, src) { +Shader.prototype._glCompile = function (type, src) +{ var shader = this.gl.createShader(type); this.gl.shaderSource(shader, src); this.gl.compileShader(shader); - if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) { + if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) + { window.console.log(this.gl.getShaderInfoLog(shader)); return null; } diff --git a/src/core/renderers/webgl/shaders/StripShader.js b/src/core/renderers/webgl/shaders/StripShader.js index 193f6e1..a7abcc6 100644 --- a/src/core/renderers/webgl/shaders/StripShader.js +++ b/src/core/renderers/webgl/shaders/StripShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function StripShader(gl) { +function StripShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -20,7 +21,8 @@ 'varying vec2 vTextureCoord;', - 'void main(void) {', + '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);', @@ -36,7 +38,8 @@ 'varying vec2 vTextureCoord;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vec2(vTextureCoord.x, vTextureCoord.y)) * alpha;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/utils/FilterTexture.js b/src/core/renderers/webgl/utils/FilterTexture.js index d2c8423..4433d44 100644 --- a/src/core/renderers/webgl/utils/FilterTexture.js +++ b/src/core/renderers/webgl/utils/FilterTexture.js @@ -8,7 +8,8 @@ * @param height {number} the vertical range of the filter * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values */ -function FilterTexture(gl, width, height, scaleMode) { +function FilterTexture(gl, width, height, scaleMode) +{ /** * @member {WebGLContext} */ @@ -59,7 +60,8 @@ * Clears the filter texture. * */ -FilterTexture.prototype.clear = function () { +FilterTexture.prototype.clear = function () +{ var gl = this.gl; gl.clearColor(0,0,0, 0); @@ -72,8 +74,10 @@ * @param width {number} the new width of the texture * @param height {number} the new height of the texture */ -FilterTexture.prototype.resize = function (width, height) { - if (this.width === width && this.height === height) { +FilterTexture.prototype.resize = function (width, height) +{ + if (this.width === width && this.height === height) + { return; } @@ -96,7 +100,8 @@ * Destroys the filter texture. * */ -FilterTexture.prototype.destroy = function () { +FilterTexture.prototype.destroy = function () +{ var gl = this.gl; gl.deleteFramebuffer( this.frameBuffer ); gl.deleteTexture( this.texture ); diff --git a/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js b/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js index c4721e9..a63f4d7 100644 --- a/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js +++ b/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js @@ -14,7 +14,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this sprite batch works for. */ -function WebGLFastSpriteBatch(renderer) { +function WebGLFastSpriteBatch(renderer) +{ /** * The renderer instance this sprite batch operates on. * @@ -91,7 +92,8 @@ */ this.lastIndexCount = 0; - for (var i=0, j=0; i < numIndices; i += 6, j += 4) { + 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; @@ -144,7 +146,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.setupContext(); }); } @@ -157,7 +160,8 @@ * * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLFastSpriteBatch.prototype.setupContext = function () { +WebGLFastSpriteBatch.prototype.setupContext = function () +{ var gl = this.renderer.gl; // create a couple of buffers @@ -177,7 +181,8 @@ /** * @param spriteBatch {SpriteBatch} The SpriteBatch container to prepare for. */ -WebGLFastSpriteBatch.prototype.begin = function (spriteBatch) { +WebGLFastSpriteBatch.prototype.begin = function (spriteBatch) +{ this.shader = this.renderer.shaderManager.fastShader; this.matrix = spriteBatch.worldTransform.toArray(true); @@ -187,33 +192,38 @@ /** */ -WebGLFastSpriteBatch.prototype.end = function () { +WebGLFastSpriteBatch.prototype.end = function () +{ this.flush(); }; /** * @param spriteBatch {SpriteBatch} The SpriteBatch container to render. */ -WebGLFastSpriteBatch.prototype.render = function (spriteBatch) { +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) { + if (!sprite.texture._uvs) + { return; } this.currentBaseTexture = sprite.texture.baseTexture; // check blend mode - if (sprite.blendMode !== this.renderer.blendModeManager.currentBlendMode) { + if (sprite.blendMode !== this.renderer.blendModeManager.currentBlendMode) + { this.flush(); this.renderer.blendModeManager.setBlendMode(sprite.blendMode); } - for (var i=0,j= children.length; i= this.size) { + if (this.currentBatchSize >= this.size) + { this.flush(); } }; @@ -362,29 +379,35 @@ /** * */ -WebGLFastSpriteBatch.prototype.flush = function () { +WebGLFastSpriteBatch.prototype.flush = function () +{ // If the batch is length 0 then return as there is nothing to draw - if (this.currentBatchSize === 0) { + if (this.currentBatchSize === 0) + { return; } var gl = this.renderer.gl; // bind the current texture - if (!this.currentBaseTexture._glTextures[gl.id]) { + if (!this.currentBaseTexture._glTextures[gl.id]) + { this.renderer.updateTexture(this.currentBaseTexture, gl); } //TODO-SHOUD THIS BE ELSE??!?!?! - else { + else + { gl.bindTexture(gl.TEXTURE_2D, this.currentBaseTexture._glTextures[gl.id]); } // upload the verts to the buffer - if (this.currentBatchSize > ( this.size * 0.5 ) ) { + if (this.currentBatchSize > ( this.size * 0.5 ) ) + { gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); } - else { + else + { var view = this.vertices.subarray(0, this.currentBatchSize * this.vertByteSize); gl.bufferSubData(gl.ARRAY_BUFFER, 0, view); @@ -405,14 +428,16 @@ * Ends the batch and flushes * */ -WebGLFastSpriteBatch.prototype.stop = function () { +WebGLFastSpriteBatch.prototype.stop = function () +{ this.flush(); }; /** * */ -WebGLFastSpriteBatch.prototype.start = function () { +WebGLFastSpriteBatch.prototype.start = function () +{ var gl = this.renderer.gl; // bind the main texture diff --git a/src/core/renderers/webgl/utils/WebGLGraphics.js b/src/core/renderers/webgl/utils/WebGLGraphics.js index 55f4911..ab8f46e 100644 --- a/src/core/renderers/webgl/utils/WebGLGraphics.js +++ b/src/core/renderers/webgl/utils/WebGLGraphics.js @@ -19,7 +19,8 @@ * @param graphics {Graphics} * @param renderer {WebGLRenderer} */ -WebGLGraphics.renderGraphics = function (graphics, renderer) {//projection, offset) { +WebGLGraphics.renderGraphics = function (graphics, renderer) {//projection, offset) +{ var gl = renderer.gl; var projection = renderer.projection, @@ -27,7 +28,8 @@ shader = renderer.shaderManager.primitiveShader, webGLData; - if (graphics.dirty) { + if (graphics.dirty) + { WebGLGraphics.updateGraphics(graphics, gl); } @@ -35,8 +37,10 @@ // This could be speeded up for sure! - for (var i = 0; i < webGL.data.length; i++) { - if (webGL.data[i].mode === 1) { + for (var i = 0; i < webGL.data.length; i++) + { + if (webGL.data[i].mode === 1) + { webGLData = webGL.data[i]; renderer.stencilManager.pushStencil(graphics, webGLData, renderer); @@ -46,7 +50,8 @@ renderer.stencilManager.popStencil(graphics, webGLData, renderer); } - else { + else + { webGLData = webGL.data[i]; @@ -84,12 +89,14 @@ * @param graphicsData {Graphics} The graphics object to update * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLGraphics.updateGraphics = function (graphics, gl) { +WebGLGraphics.updateGraphics = function (graphics, gl) +{ // get the contexts graphics object var webGL = graphics._webGL[gl.id]; // if the graphics object does not exist in the webGL context time to create it! - if (!webGL) { + if (!webGL) + { webGL = graphics._webGL[gl.id] = {lastIndex:0, data:[], gl:gl}; } @@ -99,11 +106,13 @@ var i; // if the user cleared the graphics object we will need to clear every object - if (graphics.clearDirty) { + if (graphics.clearDirty) + { graphics.clearDirty = false; // lop through and return all the webGLDatas to the object pool so than can be reused later on - for (i = 0; i < webGL.data.length; i++) { + for (i = 0; i < webGL.data.length; i++) + { var graphicsData = webGL.data[i]; graphicsData.reset(); WebGLGraphics.graphicsDataPool.push( graphicsData ); @@ -119,58 +128,72 @@ // loop through the graphics datas and construct each one.. // if the object is a complex fill then the new stencil buffer technique will be used // other wise graphics objects will be pushed into a batch.. - for (i = webGL.lastIndex; i < graphics.graphicsData.length; i++) { + for (i = webGL.lastIndex; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { // need to add the points the the graphics object.. data.points = data.shape.points.slice(); - if (data.shape.closed) { + if (data.shape.closed) + { // close the poly if the value is true! - if (data.points[0] !== data.points[data.points.length-2] || data.points[1] !== data.points[data.points.length-1]) { + if (data.points[0] !== data.points[data.points.length-2] || data.points[1] !== data.points[data.points.length-1]) + { data.points.push(data.points[0], data.points[1]); } } // MAKE SURE WE HAVE THE CORRECT TYPE.. - if (data.fill) { - if (data.points.length >= 6) { - if (data.points.length < 6 * 2) { + if (data.fill) + { + if (data.points.length >= 6) + { + if (data.points.length < 6 * 2) + { webGLData = WebGLGraphics.switchMode(webGL, 0); var canDrawUsingSimple = WebGLGraphics.buildPoly(data, webGLData); // console.log(canDrawUsingSimple); - if (!canDrawUsingSimple) { + if (!canDrawUsingSimple) + { // console.log("<>>>") webGLData = WebGLGraphics.switchMode(webGL, 1); WebGLGraphics.buildComplexPoly(data, webGLData); } } - else { + else + { webGLData = WebGLGraphics.switchMode(webGL, 1); WebGLGraphics.buildComplexPoly(data, webGLData); } } } - if (data.lineWidth > 0) { + if (data.lineWidth > 0) + { webGLData = WebGLGraphics.switchMode(webGL, 0); WebGLGraphics.buildLine(data, webGLData); } } - else { + else + { webGLData = WebGLGraphics.switchMode(webGL, 0); - if (data.type === CONST.SHAPES.RECT) { + if (data.type === CONST.SHAPES.RECT) + { WebGLGraphics.buildRectangle(data, webGLData); } - else if (data.type === CONST.SHAPES.CIRC || data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.CIRC || data.type === CONST.SHAPES.ELIP) + { WebGLGraphics.buildCircle(data, webGLData); } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { WebGLGraphics.buildRoundedRectangle(data, webGLData); } } @@ -179,10 +202,12 @@ } // upload all the dirty data... - for (i = 0; i < webGL.data.length; i++) { + for (i = 0; i < webGL.data.length; i++) + { webGLData = webGL.data[i]; - if (webGLData.dirty) { + if (webGLData.dirty) + { webGLData.upload(); } } @@ -194,18 +219,22 @@ * @param webGL {WebGLContext} * @param type {number} */ -WebGLGraphics.switchMode = function (webGL, type) { +WebGLGraphics.switchMode = function (webGL, type) +{ var webGLData; - if (!webGL.data.length) { + if (!webGL.data.length) + { webGLData = WebGLGraphics.graphicsDataPool.pop() || new WebGLGraphicsData(webGL.gl); webGLData.mode = type; webGL.data.push(webGLData); } - else { + else + { webGLData = webGL.data[webGL.data.length-1]; - if (webGLData.mode !== type || type === 1) { + if (webGLData.mode !== type || type === 1) + { webGLData = WebGLGraphics.graphicsDataPool.pop() || new WebGLGraphicsData(webGL.gl); webGLData.mode = type; webGL.data.push(webGLData); @@ -225,7 +254,8 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildRectangle = function (graphicsData, webGLData) { +WebGLGraphics.buildRectangle = function (graphicsData, webGLData) +{ // --- // // need to convert points to a nice regular data // @@ -235,7 +265,8 @@ var width = rectData.width; var height = rectData.height; - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -265,7 +296,8 @@ indices.push(vertPos, vertPos, vertPos+1, vertPos+2, vertPos+3, vertPos+3); } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = [x, y, @@ -289,7 +321,8 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildRoundedRectangle = function (graphicsData, webGLData) { +WebGLGraphics.buildRoundedRectangle = function (graphicsData, webGLData) +{ var rrectData = graphicsData.shape; var x = rrectData.x; var y = rrectData.y; @@ -305,7 +338,8 @@ recPoints = recPoints.concat(WebGLGraphics.quadraticBezierCurve(x + width, y + radius, x + width, y, x + width - radius, y)); recPoints = recPoints.concat(WebGLGraphics.quadraticBezierCurve(x + radius, y, x, y, x, y + radius)); - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -323,7 +357,8 @@ // var i = 0; - for (i = 0; i < triangles.length; i+=3) { + for (i = 0; i < triangles.length; i+=3) + { indices.push(triangles[i] + vecPos); indices.push(triangles[i] + vecPos); indices.push(triangles[i+1] + vecPos); @@ -332,12 +367,14 @@ } - for (i = 0; i < recPoints.length; i++) { + for (i = 0; i < recPoints.length; i++) + { verts.push(recPoints[i], recPoints[++i], r, g, b, alpha); } } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = recPoints; @@ -362,7 +399,8 @@ * @param toY {number} Destination point y * @return {number[]} */ -WebGLGraphics.quadraticBezierCurve = function (fromX, fromY, cpX, cpY, toX, toY) { +WebGLGraphics.quadraticBezierCurve = function (fromX, fromY, cpX, cpY, toX, toY) +{ var xa, ya, @@ -373,14 +411,16 @@ n = 20, points = []; - function getPt(n1 , n2, perc) { + function getPt(n1 , n2, perc) + { var diff = n2 - n1; return n1 + ( diff * perc ); } var j = 0; - for (var i = 0; i <= n; i++ ) { + for (var i = 0; i <= n; i++ ) + { j = i / n; // The Green Line @@ -406,7 +446,8 @@ * @param graphicsData {Graphics} The graphics object to draw * @param webGLData {object} */ -WebGLGraphics.buildCircle = function (graphicsData, webGLData) { +WebGLGraphics.buildCircle = function (graphicsData, webGLData) +{ // need to convert points to a nice regular data var circleData = graphicsData.shape; var x = circleData.x; @@ -415,11 +456,13 @@ var height; // TODO - bit hacky?? - if (graphicsData.type === CONST.SHAPES.CIRC) { + if (graphicsData.type === CONST.SHAPES.CIRC) + { width = circleData.radius; height = circleData.radius; } - else { + else + { width = circleData.width; height = circleData.height; } @@ -429,7 +472,8 @@ var i = 0; - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -444,7 +488,8 @@ indices.push(vecPos); - for (i = 0; i < totalSegs + 1 ; i++) { + for (i = 0; i < totalSegs + 1 ; i++) + { verts.push(x,y, r, g, b, alpha); verts.push(x + Math.sin(seg * i) * width, @@ -457,12 +502,14 @@ indices.push(vecPos-1); } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = []; - for (i = 0; i < totalSegs + 1; i++) { + for (i = 0; i < totalSegs + 1; i++) + { graphicsData.points.push(x + Math.sin(seg * i) * width, y + Math.cos(seg * i) * height); } @@ -481,18 +528,22 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildLine = function (graphicsData, webGLData) { +WebGLGraphics.buildLine = function (graphicsData, webGLData) +{ // TODO OPTIMISE! var i = 0; var points = graphicsData.points; - if (points.length === 0) { + if (points.length === 0) + { return; } // if the line width is an odd number add 0.5 to align to a whole pixel - if (graphicsData.lineWidth%2) { - for (i = 0; i < points.length; i++) { + if (graphicsData.lineWidth%2) + { + for (i = 0; i < points.length; i++) + { points[i] += 0.5; } } @@ -502,7 +553,8 @@ var lastPoint = new math.Point(points[points.length - 2], points[points.length - 1]); // if the first point is the last point - gonna have issues :) - if (firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) { + if (firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) + { // need to clone as we are going to slightly modify the shape.. points = points.slice(); @@ -562,7 +614,8 @@ verts.push(p1x + perpx , p1y + perpy, r, g, b, alpha); - for (i = 1; i < length-1; i++) { + for (i = 1; i < length-1; i++) + { p1x = points[(i-1)*2]; p1y = points[(i-1)*2 + 1]; @@ -599,7 +652,8 @@ denom = a1*b2 - a2*b1; - if (Math.abs(denom) < 0.1 ) { + if (Math.abs(denom) < 0.1 ) + { denom+=10.1; verts.push(p2x - perpx , p2y - perpy, @@ -618,7 +672,8 @@ pdist = (px -p2x) * (px -p2x) + (py -p2y) + (py -p2y); - if (pdist > 140 * 140) { + if (pdist > 140 * 140) + { perp3x = perpx - perp2x; perp3y = perpy - perp2y; @@ -639,7 +694,8 @@ indexCount++; } - else { + else + { verts.push(px , py); verts.push(r, g, b, alpha); @@ -672,7 +728,8 @@ indices.push(indexStart); - for (i = 0; i < indexCount; i++) { + for (i = 0; i < indexCount; i++) + { indices.push(indexStart++); } @@ -687,11 +744,13 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildComplexPoly = function (graphicsData, webGLData) { +WebGLGraphics.buildComplexPoly = function (graphicsData, webGLData) +{ //TODO - no need to copy this as it gets turned into a FLoat32Array anyways.. var points = graphicsData.points.slice(); - if (points.length < 6) { + if (points.length < 6) + { return; } @@ -711,7 +770,8 @@ var x,y; // get size.. - for (var i = 0; i < points.length; i+=2) { + for (var i = 0; i < points.length; i+=2) + { x = points[i]; y = points[i+1]; @@ -732,7 +792,8 @@ //TODO - this aint needed! var length = points.length / 2; - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { indices.push( i ); } @@ -746,10 +807,12 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildPoly = function (graphicsData, webGLData) { +WebGLGraphics.buildPoly = function (graphicsData, webGLData) +{ var points = graphicsData.points; - if (points.length < 6) { + if (points.length < 6) + { return; } // get first and last point.. figure out the middle! @@ -767,7 +830,8 @@ var triangles = utils.PolyK.Triangulate(points); - if (!triangles) { + if (!triangles) + { return false; } @@ -775,7 +839,8 @@ var i = 0; - for (i = 0; i < triangles.length; i+=3) { + for (i = 0; i < triangles.length; i+=3) + { indices.push(triangles[i] + vertPos); indices.push(triangles[i] + vertPos); indices.push(triangles[i+1] + vertPos); @@ -783,7 +848,8 @@ indices.push(triangles[i+2] + vertPos); } - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { verts.push(points[i * 2], points[i * 2 + 1], r, g, b, alpha); } diff --git a/src/core/renderers/webgl/utils/WebGLGraphicsData.js b/src/core/renderers/webgl/utils/WebGLGraphicsData.js index c56d05e..c739ba7 100644 --- a/src/core/renderers/webgl/utils/WebGLGraphicsData.js +++ b/src/core/renderers/webgl/utils/WebGLGraphicsData.js @@ -2,7 +2,8 @@ * @class * @private */ -function WebGLGraphicsData(gl) { +function WebGLGraphicsData(gl) +{ this.gl = gl; //TODO does this need to be split before uploding?? @@ -22,7 +23,8 @@ /** * */ -WebGLGraphicsData.prototype.reset = function () { +WebGLGraphicsData.prototype.reset = function () +{ this.points.length = 0; this.indices.length = 0; }; @@ -30,7 +32,8 @@ /** * */ -WebGLGraphicsData.prototype.upload = function () { +WebGLGraphicsData.prototype.upload = function () +{ var gl = this.gl; // this.lastIndex = graphics.graphicsData.length; diff --git a/src/core/renderers/webgl/utils/WebGLSpriteBatch.js b/src/core/renderers/webgl/utils/WebGLSpriteBatch.js index 96eaa52..55befbb 100644 --- a/src/core/renderers/webgl/utils/WebGLSpriteBatch.js +++ b/src/core/renderers/webgl/utils/WebGLSpriteBatch.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this sprite batch works for. */ -function WebGLSpriteBatch(renderer) { +function WebGLSpriteBatch(renderer) +{ /** * * @@ -88,7 +89,8 @@ */ this.lastIndexCount = 0; - for (var i=0, j=0; i < numIndices; i += 6, j += 4) { + 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; @@ -162,7 +164,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.setupContext(); }); } @@ -173,7 +176,8 @@ /** * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLSpriteBatch.prototype.setupContext = function () { +WebGLSpriteBatch.prototype.setupContext = function () +{ var gl = this.renderer.gl; // setup default shader @@ -198,7 +202,8 @@ /** * */ -WebGLSpriteBatch.prototype.begin = function () { +WebGLSpriteBatch.prototype.begin = function () +{ // this.shader = this.renderer.shaderManager.defaultShader; this.start(); @@ -206,19 +211,22 @@ /** */ -WebGLSpriteBatch.prototype.end = function () { +WebGLSpriteBatch.prototype.end = function () +{ this.flush(); }; /** * @param sprite {Sprite} the sprite to render when using this spritebatch */ -WebGLSpriteBatch.prototype.render = function (sprite) { +WebGLSpriteBatch.prototype.render = function (sprite) +{ var texture = sprite.texture; //TODO set blend modes.. // check texture.. - if (this.currentBatchSize >= this.size) { + if (this.currentBatchSize >= this.size) + { this.flush(); this.currentBaseTexture = texture.baseTexture; } @@ -227,7 +235,8 @@ var uvs = texture._uvs; // if the uvs have not updated then no point rendering just yet! - if (!uvs) { + if (!uvs) + { return; } @@ -237,7 +246,8 @@ var w0, w1, h0, h1; - if (texture.trim) { + 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; @@ -248,7 +258,8 @@ h0 = h1 + texture.crop.height; } - else { + else + { w0 = (texture.frame.width ) * (1-aX); w1 = (texture.frame.width ) * -aX; @@ -272,7 +283,8 @@ var colors = this.colors; var positions = this.positions; - if (this.renderer.roundPixels) { + if (this.renderer.roundPixels) + { // xy positions[index] = a * w1 + c * h1 + tx | 0; positions[index+1] = d * h1 + b * w1 + ty | 0; @@ -289,7 +301,8 @@ positions[index+15] = a * w1 + c * h0 + tx | 0; positions[index+16] = d * h0 + b * w1 + ty | 0; } - else { + else + { // xy positions[index] = a * w1 + c * h1 + tx; positions[index+1] = d * h1 + b * w1 + ty; @@ -338,11 +351,13 @@ * * @param sprite {TilingSprite} the tilingSprite to render */ -WebGLSpriteBatch.prototype.renderTilingSprite = function (tilingSprite) { +WebGLSpriteBatch.prototype.renderTilingSprite = function (tilingSprite) +{ var texture = tilingSprite.tilingTexture; // check texture.. - if (this.currentBatchSize >= this.size) { + if (this.currentBatchSize >= this.size) + { //return; this.flush(); this.currentBaseTexture = texture.baseTexture; @@ -351,7 +366,8 @@ // set the textures uvs temporarily // TODO create a separate texture so that we can tile part of a texture - if (!tilingSprite._uvs) { + if (!tilingSprite._uvs) + { tilingSprite._uvs = new TextureUvs(); } @@ -454,16 +470,19 @@ * Renders the content and empties the current batch. * */ -WebGLSpriteBatch.prototype.flush = function () { +WebGLSpriteBatch.prototype.flush = function () +{ // If the batch is length 0 then return as there is nothing to draw - if (this.currentBatchSize === 0) { + if (this.currentBatchSize === 0) + { return; } var gl = this.renderer.gl; var shader; - if (this.dirty) { + if (this.dirty) + { this.dirty = false; // bind the main texture gl.activeTexture(gl.TEXTURE0); @@ -482,10 +501,12 @@ } // upload the verts to the buffer - if (this.currentBatchSize > ( this.size * 0.5 ) ) { + if (this.currentBatchSize > ( this.size * 0.5 ) ) + { gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); } - else { + else + { var view = this.positions.subarray(0, this.currentBatchSize * this.vertByteSize); gl.bufferSubData(gl.ARRAY_BUFFER, 0, view); } @@ -502,7 +523,8 @@ var shaderSwap = false; var sprite; - for (var i = 0, j = this.currentBatchSize; i < j; i++) { + for (var i = 0, j = this.currentBatchSize; i < j; i++) + { sprite = this.sprites[i]; @@ -513,24 +535,28 @@ blendSwap = currentBlendMode !== nextBlendMode; shaderSwap = currentShader !== nextShader; // should I use uuidS??? - if (currentBaseTexture !== nextTexture || blendSwap || shaderSwap) { + if (currentBaseTexture !== nextTexture || blendSwap || shaderSwap) + { this.renderBatch(currentBaseTexture, batchSize, start); start = i; batchSize = 0; currentBaseTexture = nextTexture; - if (blendSwap) { + if (blendSwap) + { currentBlendMode = nextBlendMode; this.renderer.blendModeManager.setBlendMode( currentBlendMode ); } - if (shaderSwap) { + if (shaderSwap) + { currentShader = nextShader; shader = currentShader.shaders ? currentShader.shaders[gl.id] : currentShader; - if (!shader) { + if (!shader) + { shader = new Shader(gl, null, currentShader.fragmentSrc, currentShader.uniforms); currentShader.shaders[gl.id] = shader; } @@ -538,7 +564,8 @@ // set shader function??? this.renderer.shaderManager.setShader(shader); - if (shader.dirty) { + if (shader.dirty) + { shader.syncUniforms(); } @@ -569,17 +596,21 @@ * @param size {number} * @param startIndex {number} */ -WebGLSpriteBatch.prototype.renderBatch = function (texture, size, startIndex) { - if (size === 0) { +WebGLSpriteBatch.prototype.renderBatch = function (texture, size, startIndex) +{ + if (size === 0) + { return; } var gl = this.renderer.gl; - if (!texture._glTextures[gl.id]) { + if (!texture._glTextures[gl.id]) + { this.renderer.updateTexture(texture); } - else { + else + { // bind the current texture gl.bindTexture(gl.TEXTURE_2D, texture._glTextures[gl.id]); } @@ -594,7 +625,8 @@ /** * */ -WebGLSpriteBatch.prototype.stop = function () { +WebGLSpriteBatch.prototype.stop = function () +{ this.flush(); this.dirty = true; }; @@ -602,7 +634,8 @@ /** * */ -WebGLSpriteBatch.prototype.start = function () { +WebGLSpriteBatch.prototype.start = function () +{ this.dirty = true; }; @@ -610,7 +643,8 @@ * Destroys the SpriteBatch. * */ -WebGLSpriteBatch.prototype.destroy = function () { +WebGLSpriteBatch.prototype.destroy = function () +{ this.renderer.gl.deleteBuffer(this.vertexBuffer); this.renderer.gl.deleteBuffer(this.indexBuffer); diff --git a/src/core/textures/BaseTexture.js b/src/core/textures/BaseTexture.js index 2bf77d4..513d358 100644 --- a/src/core/textures/BaseTexture.js +++ b/src/core/textures/BaseTexture.js @@ -10,7 +10,8 @@ * @param source {Image|Canvas} the source object of the texture. * @param [scaleMode=scaleModes.DEFAULT] {number} See {@link scaleModes} for possible values */ -function BaseTexture(source, scaleMode) { +function BaseTexture(source, scaleMode) +{ this.uuid = utils.uuid(); /** @@ -123,7 +124,8 @@ this._needsUpdate = false; // if no source passed don't try to load - if (source) { + if (source) + { this.loadSource(source); } @@ -149,13 +151,16 @@ Object.defineProperties(BaseTexture.prototype, { needsUpdate: { - get: function () { + get: function () + { return this._needsUpdate; }, - set: function (val) { + set: function (val) + { this._needsUpdate = val; - if (val) { + if (val) + { this.emit('update', this); } } @@ -171,9 +176,11 @@ * * The logic state after calling `loadSource` directly or indirectly (eg. `fromImage`, `new BaseTexture`) is: * - * if (texture.hasLoaded) { + * if (texture.hasLoaded) + { * // texture ready for use - * } else if (texture.isLoading) { + * } else if (texture.isLoading) + { * // listen to 'loaded' and/or 'error' events on texture * } else { * // not loading, not going to load UNLESS the source is reloaded @@ -183,12 +190,14 @@ * @protected * @param source {Image|Canvas} the source object of the texture. */ -BaseTexture.prototype.loadSource = function (source) { +BaseTexture.prototype.loadSource = function (source) +{ var wasLoading = this.isLoading; this.hasLoaded = false; this.isLoading = false; - if (wasLoading && this.source) { + if (wasLoading && this.source) + { this.source.onload = null; this.source.onerror = null; } @@ -196,20 +205,24 @@ this.source = source; // Apply source if loaded. Otherwise setup appropriate loading monitors. - if ((this.source.complete || this.source.getContext) && this.source.width && this.source.height) { + if ((this.source.complete || this.source.getContext) && this.source.width && this.source.height) + { this._sourceLoaded(); } - else if(!source.getContext) { + else if(!source.getContext) + { // Image fail / not ready this.isLoading = true; var scope = this; - source.onload = function () { + source.onload = function () + { source.onload = null; source.onerror = null; - if(!scope.isLoading) { + if(!scope.isLoading) + { return; } @@ -219,11 +232,13 @@ scope.emit('loaded', scope); }; - source.onerror = function () { + source.onerror = function () + { source.onload = null; source.onerror = null; - if(!scope.isLoading) { + if(!scope.isLoading) + { return; } @@ -234,24 +249,29 @@ // Per http://www.w3.org/TR/html5/embedded-content-0.html#the-img-element // "The value of `complete` can thus change while a script is executing." // So complete needs to be re-checked after the callbacks have been added.. - if (source.complete) { + if (source.complete) + { this.isLoading = false; // ..and if we're complete now, no need for callbacks source.onload = null; source.onerror = null; - if (source.width && source.height) { + if (source.width && source.height) + { this._sourceLoaded(); // If any previous subscribers possible - if (wasLoading) { + if (wasLoading) + { this.emit('loaded', this); } } - else { + else + { // If any previous subscribers possible - if (wasLoading) { + if (wasLoading) + { this.emit('error', this); } } @@ -265,7 +285,8 @@ * * @private */ -BaseTexture.prototype._sourceLoaded = function () { +BaseTexture.prototype._sourceLoaded = function () +{ this.hasLoaded = true; this.width = this.source.naturalWidth || this.source.width; @@ -278,16 +299,20 @@ * Destroys this base texture * */ -BaseTexture.prototype.destroy = function () { - if (this.imageUrl) { +BaseTexture.prototype.destroy = function () +{ + if (this.imageUrl) + { delete utils.BaseTextureCache[this.imageUrl]; delete utils.TextureCache[this.imageUrl]; this.imageUrl = null; - if (!navigator.isCocoonJS) { + if (!navigator.isCocoonJS) + { this.source.src = ''; } } - else if (this.source && this.source._pixiId) { + else if (this.source && this.source._pixiId) + { delete utils.BaseTextureCache[this.source._pixiId]; } this.source = null; @@ -301,7 +326,8 @@ * memory again. * */ -BaseTexture.prototype.dispose = function () { +BaseTexture.prototype.dispose = function () +{ this.emit('dispose', this); }; @@ -311,7 +337,8 @@ * * @param newSrc {string} the path of the image */ -BaseTexture.prototype.updateSourceImage = function (newSrc) { +BaseTexture.prototype.updateSourceImage = function (newSrc) +{ this.source.src = newSrc; this.loadSource(this.source); }; @@ -326,18 +353,22 @@ * @param [scaleMode=scaleModes.DEFAULT] {number} See {@link scaleModes} for possible values * @return BaseTexture */ -BaseTexture.fromImage = function (imageUrl, crossorigin, scaleMode) { +BaseTexture.fromImage = function (imageUrl, crossorigin, scaleMode) +{ var baseTexture = utils.BaseTextureCache[imageUrl]; - if (crossorigin === undefined && imageUrl.indexOf('data:') !== 0) { + if (crossorigin === undefined && imageUrl.indexOf('data:') !== 0) + { crossorigin = true; } - if (!baseTexture) { + if (!baseTexture) + { // new Image() breaks tex loading in some versions of Chrome. // See https://code.google.com/p/chromium/issues/detail?id=238071 var image = new Image();//document.createElement('img'); - if (crossorigin) { + if (crossorigin) + { image.crossOrigin = ''; } @@ -347,7 +378,8 @@ utils.BaseTextureCache[imageUrl] = baseTexture; // if there is an @2x at the end of the url we are going to assume its a highres image - if ( imageUrl.indexOf(CONST.RETINA_PREFIX + '.') !== -1) { + if ( imageUrl.indexOf(CONST.RETINA_PREFIX + '.') !== -1) + { baseTexture.resolution = 2; } } @@ -363,14 +395,17 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return BaseTexture */ -BaseTexture.fromCanvas = function (canvas, scaleMode) { - if (!canvas._pixiId) { +BaseTexture.fromCanvas = function (canvas, scaleMode) +{ + if (!canvas._pixiId) + { canvas._pixiId = 'canvas_' + utils.uuid(); } var baseTexture = utils.BaseTextureCache[canvas._pixiId]; - if (!baseTexture) { + if (!baseTexture) + { baseTexture = new BaseTexture(canvas, scaleMode); utils.BaseTextureCache[canvas._pixiId] = baseTexture; } diff --git a/src/core/textures/RenderTexture.js b/src/core/textures/RenderTexture.js index 6dad20f..53ae796 100644 --- a/src/core/textures/RenderTexture.js +++ b/src/core/textures/RenderTexture.js @@ -46,8 +46,10 @@ * @param [scaleMode] {number} See {@link scaleModes} for possible values * @param [resolution=1] {number} The resolution of the texture being generated */ -function RenderTexture(renderer, width, height, scaleMode, resolution) { - if (!renderer) { +function RenderTexture(renderer, width, height, scaleMode, resolution) +{ + if (!renderer) + { throw new Error('Unable to create RenderTexture, you must pass a renderer into the constructor.'); } @@ -133,7 +135,8 @@ */ this.renderer = renderer; - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { var gl = this.renderer.gl; this.textureBuffer = new FilterTexture(gl, this.width * this.resolution, this.height * this.resolution, this.baseTexture.scaleMode); @@ -142,7 +145,8 @@ this.render = this.renderWebGL; this.projection = new math.Point(this.width*0.5, -this.height*0.5); } - else { + else + { this.render = this.renderCanvas; this.textureBuffer = new CanvasBuffer(this.width* this.resolution, this.height* this.resolution); this.baseTexture.source = this.textureBuffer.canvas; @@ -167,8 +171,10 @@ * @param height {number} The height to resize to. * @param updateBase {boolean} Should the baseTexture.width and height values be resized as well? */ -RenderTexture.prototype.resize = function (width, height, updateBase) { - if (width === this.width && height === this.height) { +RenderTexture.prototype.resize = function (width, height, updateBase) +{ + if (width === this.width && height === this.height) + { return; } @@ -177,17 +183,20 @@ this.width = this.frame.width = this.crop.width = width; this.height = this.frame.height = this.crop.height = height; - if (updateBase) { + if (updateBase) + { this.baseTexture.width = this.width; this.baseTexture.height = this.height; } - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { this.projection.x = this.width / 2; this.projection.y = -this.height / 2; } - if (!this.valid) { + if (!this.valid) + { return; } @@ -198,12 +207,15 @@ * Clears the RenderTexture. * */ -RenderTexture.prototype.clear = function () { - if (!this.valid) { +RenderTexture.prototype.clear = function () +{ + if (!this.valid) + { return; } - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { this.renderer.gl.bindFramebuffer(this.renderer.gl.FRAMEBUFFER, this.textureBuffer.frameBuffer); } @@ -220,19 +232,23 @@ * @param [restoreWorldTransform=true] {boolean} If true the displayObject's worldTransform/worldAlpha and all children * transformations will be restored. Not restoring this information will be a little faster. */ -RenderTexture.prototype.renderWebGL = function (displayObject, matrix, clear, restoreWorldTransform) { - if (!this.valid) { +RenderTexture.prototype.renderWebGL = function (displayObject, matrix, clear, restoreWorldTransform) +{ + if (!this.valid) + { return; } - if (typeof restoreWorldTransform === 'undefined') { + if (typeof restoreWorldTransform === 'undefined') + { restoreWorldTransform = true; } var tempAlpha, tempTransform; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { tempAlpha = displayObject.worldAlpha; tempTransform = displayObject.worldTransform.toArray(); } @@ -245,7 +261,8 @@ wt.identity(); wt.translate(0, this.projection.y * 2); - if (matrix) { + if (matrix) + { wt.append(matrix); } @@ -258,7 +275,8 @@ var children = displayObject.children; var i, j; - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } @@ -269,7 +287,8 @@ gl.bindFramebuffer(gl.FRAMEBUFFER, this.textureBuffer.frameBuffer ); - if (clear) { + if (clear) + { this.textureBuffer.clear(); } @@ -279,11 +298,13 @@ this.renderer.spriteBatch.dirty = true; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { displayObject.worldAlpha = tempAlpha; displayObject.worldTransform.fromArray(tempTransform); - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } } @@ -300,26 +321,31 @@ * @param [restoreWorldTransform=true] {boolean} If true the displayObject's worldTransform/worldAlpha and all children * transformations will be restored. Not restoring this information will be a little faster. */ -RenderTexture.prototype.renderCanvas = function (displayObject, matrix, clear, restoreWorldTransform) { - if (!this.valid) { +RenderTexture.prototype.renderCanvas = function (displayObject, matrix, clear, restoreWorldTransform) +{ + if (!this.valid) + { return; } - if (typeof restoreWorldTransform === 'undefined') { + if (typeof restoreWorldTransform === 'undefined') + { restoreWorldTransform = true; } var tempAlpha, tempTransform; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { tempAlpha = displayObject.worldAlpha; tempTransform = displayObject.worldTransform.toArray(); } var wt = displayObject.worldTransform; wt.identity(); - if (matrix) { + if (matrix) + { wt.append(matrix); } @@ -330,11 +356,13 @@ var children = displayObject.children; var i, j; - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } - if (clear) { + if (clear) + { this.textureBuffer.clear(); } @@ -348,11 +376,13 @@ this.renderer.resolution = realResolution; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { displayObject.worldAlpha = tempAlpha; displayObject.worldTransform.fromArray(tempTransform); - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } } @@ -363,7 +393,8 @@ * * @return {Image} */ -RenderTexture.prototype.getImage = function () { +RenderTexture.prototype.getImage = function () +{ var image = new Image(); image.src = this.getBase64(); return image; @@ -374,7 +405,8 @@ * * @return {string} A base64 encoded string of the texture. */ -RenderTexture.prototype.getBase64 = function () { +RenderTexture.prototype.getBase64 = function () +{ return this.getCanvas().toDataURL(); }; @@ -383,8 +415,10 @@ * * @return {HTMLCanvasElement} A Canvas element with the texture rendered on. */ -RenderTexture.prototype.getCanvas = function () { - if (this.renderer.type === CONST.WEBGL_RENDERER) { +RenderTexture.prototype.getCanvas = function () +{ + if (this.renderer.type === CONST.WEBGL_RENDERER) + { var gl = this.renderer.gl; var width = this.textureBuffer.width; var height = this.textureBuffer.height; @@ -403,7 +437,8 @@ return tempCanvas.canvas; } - else { + else + { return this.textureBuffer.canvas; } }; diff --git a/src/core/textures/Texture.js b/src/core/textures/Texture.js index 3c65909..e97f0aa 100644 --- a/src/core/textures/Texture.js +++ b/src/core/textures/Texture.js @@ -17,7 +17,8 @@ * @param [crop] {Rectangle} The area of original texture * @param [trim] {Rectangle} Trimmed texture rectangle */ -function Texture(baseTexture, frame, crop, trim) { +function Texture(baseTexture, frame, crop, trim) +{ /** * Does this Texture have any frame data assigned to it? * @@ -25,12 +26,14 @@ */ this.noFrame = false; - if (!frame) { + if (!frame) + { this.noFrame = true; frame = new math.Rectangle(0, 0, 1, 1); } - if (baseTexture instanceof Texture) { + if (baseTexture instanceof Texture) + { baseTexture = baseTexture.baseTexture; } @@ -100,13 +103,16 @@ */ this.crop = crop || new math.Rectangle(0, 0, 1, 1); - if (baseTexture.hasLoaded) { - if (this.noFrame) { + if (baseTexture.hasLoaded) + { + if (this.noFrame) + { frame = new math.Rectangle(0, 0, baseTexture.width, baseTexture.height); } this.frame = frame; } - else { + else + { baseTexture.addEventListener('loaded', this.onBaseTextureLoaded.bind(this)); } } @@ -118,19 +124,23 @@ Object.defineProperties(Texture.prototype, { needsUpdate: { - get: function () { + get: function () + { return this.baseTexture.needsUpdate; }, - set: function (val) { + set: function (val) + { this.baseTexture.needsUpdate = val; } }, frame: { - get: function () { + get: function () + { return this._frame; }, - set: function (frame) { + set: function (frame) + { this._frame = frame; this.noFrame = false; @@ -143,20 +153,23 @@ 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 (!this.trim && (frame.x + frame.width > this.baseTexture.width || frame.y + frame.height > this.baseTexture.height)) + { throw new Error('Texture Error: frame does not fit inside the base Texture dimensions ' + this); } this.valid = frame && frame.width && frame.height && this.baseTexture.source && this.baseTexture.hasLoaded; - if (this.trim) { + 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) { + if (this.valid) + { this._updateUvs(); } } @@ -168,11 +181,13 @@ * * @private */ -Texture.prototype.onBaseTextureLoaded = function () { +Texture.prototype.onBaseTextureLoaded = function () +{ var baseTexture = this.baseTexture; baseTexture.removeEventListener('loaded', this.onLoaded); - if (this.noFrame) { + if (this.noFrame) + { this.frame = new math.Rectangle(0, 0, baseTexture.width, baseTexture.height); } @@ -184,8 +199,10 @@ * * @param destroyBase {boolean} Whether to destroy the base texture as well */ -Texture.prototype.destroy = function (destroyBase) { - if (destroyBase) { +Texture.prototype.destroy = function (destroyBase) +{ + if (destroyBase) + { this.baseTexture.destroy(); } @@ -197,8 +214,10 @@ * * @private */ -Texture.prototype._updateUvs = function () { - if (!this._uvs) { +Texture.prototype._updateUvs = function () +{ + if (!this._uvs) + { this._uvs = new TextureUvs(); } @@ -229,10 +248,12 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return Texture */ -Texture.fromImage = function (imageUrl, crossorigin, scaleMode) { +Texture.fromImage = function (imageUrl, crossorigin, scaleMode) +{ var texture = utils.TextureCache[imageUrl]; - if (!texture) { + if (!texture) + { texture = new Texture(BaseTexture.fromImage(imageUrl, crossorigin, scaleMode)); utils.TextureCache[imageUrl] = texture; } @@ -248,9 +269,11 @@ * @param frameId {string} The frame id of the texture * @return Texture */ -Texture.fromFrame = function (frameId) { +Texture.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache '); } return texture; @@ -264,7 +287,8 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return {Texture} */ -Texture.fromCanvas = function (canvas, scaleMode) { +Texture.fromCanvas = function (canvas, scaleMode) +{ return new Texture(BaseTexture.fromCanvas(canvas, scaleMode)); }; @@ -276,7 +300,8 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return {Texture} A Texture */ -Texture.fromVideo = function (video, scaleMode) { +Texture.fromVideo = function (video, scaleMode) +{ return new Texture(VideoBaseTexture.baseTextureFromVideo(video, scaleMode)); }; @@ -287,7 +312,8 @@ * @param texture {Texture} The Texture to add to the cache. * @param id {string} The id that the texture will be stored against. */ -Texture.addTextureToCache = function (texture, id) { +Texture.addTextureToCache = function (texture, id) +{ utils.TextureCache[id] = texture; }; @@ -298,7 +324,8 @@ * @param id {string} The id of the texture to be removed * @return {Texture} The texture that was removed */ -Texture.removeTextureFromCache = function (id) { +Texture.removeTextureFromCache = function (id) +{ var texture = utils.TextureCache[id]; delete utils.TextureCache[id]; diff --git a/src/core/textures/TextureUvs.js b/src/core/textures/TextureUvs.js index b9bbb58..5424d52 100644 --- a/src/core/textures/TextureUvs.js +++ b/src/core/textures/TextureUvs.js @@ -1,4 +1,5 @@ -function TextureUvs() { +function TextureUvs() +{ this.x0 = 0; this.y0 = 0; diff --git a/src/core/textures/VideoBaseTexture.js b/src/core/textures/VideoBaseTexture.js index e3e0c5a..1a826a9 100644 --- a/src/core/textures/VideoBaseTexture.js +++ b/src/core/textures/VideoBaseTexture.js @@ -12,15 +12,18 @@ * @param source {HTMLVideoElement} * @param [scaleMode] {number} See {@link scaleModes} for possible values */ -function VideoBaseTexture(source, scaleMode) { - if (!source){ +function VideoBaseTexture(source, scaleMode) +{ + if (!source) + { throw new Error('No video source element specified.'); } // hook in here to check if video is already available. // BaseTexture looks for a source.complete boolean, plus width & height. - if ((source.readyState === source.HAVE_ENOUGH_DATA || source.readyState === source.HAVE_FUTURE_DATA) && source.width && source.height) { + if ((source.readyState === source.HAVE_ENOUGH_DATA || source.readyState === source.HAVE_FUTURE_DATA) && source.width && source.height) + { source.complete = true; } @@ -31,7 +34,8 @@ this._boundOnUpdate = this._onUpdate.bind(this); this._boundOnCanPlay = this._onCanPlay.bind(this); - if (!source.complete) { + if (!source.complete) + { source.addEventListener('canplay', this._boundOnCanPlay); source.addEventListener('canplaythrough', this._boundOnCanPlay); @@ -47,28 +51,35 @@ VideoBaseTexture.prototype.constructor = VideoBaseTexture; module.exports = VideoBaseTexture; -VideoBaseTexture.prototype._onUpdate = function () { - if (this.autoUpdate) { +VideoBaseTexture.prototype._onUpdate = function () +{ + if (this.autoUpdate) + { window.requestAnimationFrame(this._boundOnUpdate); this.needsUpdate = true; } }; -VideoBaseTexture.prototype._onPlayStart = function () { - if (!this.autoUpdate) { +VideoBaseTexture.prototype._onPlayStart = function () +{ + if (!this.autoUpdate) + { window.requestAnimationFrame(this._boundOnUpdate); this.autoUpdate = true; } }; -VideoBaseTexture.prototype._onPlayStop = function () { +VideoBaseTexture.prototype._onPlayStop = function () +{ this.autoUpdate = false; }; -VideoBaseTexture.prototype._onCanPlay = function () { +VideoBaseTexture.prototype._onCanPlay = function () +{ this.hasLoaded = true; - if (this.source) { + if (this.source) + { this.source.removeEventListener('canplay', this._boundOnCanPlay); this.source.removeEventListener('canplaythrough', this._boundOnCanPlay); @@ -78,15 +89,18 @@ this.source.play(); // prevent multiple loaded dispatches.. - if(!this.__loaded){ + if(!this.__loaded) + { this.__loaded = true; this.emit('loaded', this); } } }; -VideoBaseTexture.prototype.destroy = function () { - if (this.source && this.source._pixiId) { +VideoBaseTexture.prototype.destroy = function () +{ + if (this.source && this.source._pixiId) + { utils.BaseTextureCache[ this.source._pixiId ] = null; delete utils.BaseTextureCache[ this.source._pixiId ]; @@ -105,14 +119,17 @@ * @param scaleMode {number} See {@link scaleModes} for possible values * @return {VideoBaseTexture} */ -VideoBaseTexture.fromVideo = function (video, scaleMode) { - if (!video._pixiId) { +VideoBaseTexture.fromVideo = function (video, scaleMode) +{ + if (!video._pixiId) + { video._pixiId = 'video_' + utils.uuid(); } var baseTexture = utils.BaseTextureCache[video._pixiId]; - if (!baseTexture) { + if (!baseTexture) + { baseTexture = new VideoBaseTexture(video, scaleMode); utils.BaseTextureCache[ video._pixiId ] = baseTexture; } @@ -147,17 +164,21 @@ * @param scaleMode {number} See {@link scaleModes} for possible values * @return {VideoBaseTexture} */ -VideoBaseTexture.fromUrl = function (videoSrc, scaleMode) { +VideoBaseTexture.fromUrl = function (videoSrc, scaleMode) +{ var video = document.createElement('video'); // array of objects or strings - if (Array.isArray(videoSrc)) { - for (var i = 0; i < videoSrc.length; ++i) { + if (Array.isArray(videoSrc)) + { + for (var i = 0; i < videoSrc.length; ++i) + { video.appendChild(createSource(videoSrc.src || videoSrc, videoSrc.mime)); } } // single object or string - else { + else + { video.appendChild(createSource(videoSrc.src || videoSrc, videoSrc.mime)); } @@ -169,8 +190,10 @@ VideoBaseTexture.fromUrls = VideoBaseTexture.fromUrl; -function createSource(path, type) { - if (!type) { +function createSource(path, type) +{ + if (!type) + { type = 'video/' + path.substr(path.lastIndexOf('.') + 1); } diff --git a/src/core/utils/EventData.js b/src/core/utils/EventData.js index 5d55a22..8cdf701 100644 --- a/src/core/utils/EventData.js +++ b/src/core/utils/EventData.js @@ -7,7 +7,8 @@ * @param name {string} The string name of the event that was triggered * @param data {object} Arbitrary event data to pass along */ -function EventData(target, name, data) { +function EventData(target, name, data) +{ // for duck typing in the ".on()" function this.__isEventObject = true; @@ -71,7 +72,8 @@ * Stops the propagation of events up the scene graph (prevents bubbling). * */ -EventData.prototype.stopPropagation = function stopPropagation() { +EventData.prototype.stopPropagation = function stopPropagation() +{ this.stopped = true; }; @@ -79,6 +81,7 @@ * Stops the propagation of events to sibling listeners (no longer calls any listeners). * */ -EventData.prototype.stopImmediatePropagation = function stopImmediatePropagation() { +EventData.prototype.stopImmediatePropagation = function stopImmediatePropagation() +{ this.stoppedImmediate = true; }; diff --git a/src/core/utils/EventTarget.js b/src/core/utils/EventTarget.js index 7ae8820..671a151 100644 --- a/src/core/utils/EventTarget.js +++ b/src/core/utils/EventTarget.js @@ -13,14 +13,16 @@ * var em = new MyEmitter(); * em.emit('eventName', 'some data', 'some more data', {}, null, ...); */ -function eventTarget(obj) { +function eventTarget(obj) +{ /** * Return a list of assigned event listeners. * * @param eventName {string} The events that should be listed. * @return {Array} An array of listener functions */ - obj.listeners = function listeners(eventName) { + obj.listeners = function listeners(eventName) + { this._listeners = this._listeners || {}; return this._listeners[eventName] ? this._listeners[eventName].slice() : []; @@ -33,22 +35,26 @@ * @param eventName {string} The name of the event. * @return {boolean} Indication if we've emitted an event. */ - obj.emit = obj.dispatchEvent = function emit(eventName, data) { + obj.emit = obj.dispatchEvent = function emit(eventName, data) + { this._listeners = this._listeners || {}; // fast return when there are no listeners - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return; } //backwards compat with old method ".emit({ type: 'something' })" - if (typeof eventName === 'object') { + if (typeof eventName === 'object') + { data = eventName; eventName = eventName.type; } //ensure we are using a real pixi event - if (!data || data.__isEventObject !== true) { + if (!data || data.__isEventObject !== true) + { data = new EventData(this, eventName, data); } @@ -58,23 +64,27 @@ fn = listeners[0], i; - for (i = 0; i < length; fn = listeners[++i]) { + for (i = 0; i < length; fn = listeners[++i]) + { //call the event listener fn.call(this, data); //if "stopImmediatePropagation" is called, stop calling sibling events - if (data.stoppedImmediate) { + if (data.stoppedImmediate) + { return this; } } //if "stopPropagation" is called then don't bubble the event - if (data.stopped) { + if (data.stopped) + { return this; } //bubble this event up the scene graph - if (this.parent && this.parent.emit) { + if (this.parent && this.parent.emit) + { this.parent.emit.call(this.parent, eventName, data); } @@ -88,7 +98,8 @@ * @param eventName {string} Name of the event. * @param callback {Functon} fn Callback function. */ - obj.on = obj.addEventListener = function on(eventName, fn) { + obj.on = obj.addEventListener = function on(eventName, fn) + { this._listeners = this._listeners || {}; (this._listeners[eventName] = this._listeners[eventName] || []) @@ -103,11 +114,13 @@ * @param eventName {string} Name of the event. * @param callback {Function} Callback function. */ - obj.once = function once(eventName, fn) { + obj.once = function once(eventName, fn) + { this._listeners = this._listeners || {}; var self = this; - function onceHandlerWrapper() { + function onceHandlerWrapper() + { fn.apply(self.off(eventName, onceHandlerWrapper), arguments); } onceHandlerWrapper._originalHandler = fn; @@ -122,23 +135,28 @@ * @param eventName {string} The event we want to remove. * @param callback {Function} The listener that we need to find. */ - obj.off = obj.removeEventListener = function off(eventName, fn) { + obj.off = obj.removeEventListener = function off(eventName, fn) + { this._listeners = this._listeners || {}; - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return this; } var list = this._listeners[eventName], i = fn ? list.length : 0; - while(i-- > 0) { - if (list[i] === fn || list[i]._originalHandler === fn) { + while(i-- > 0) + { + if (list[i] === fn || list[i]._originalHandler === fn) + { list.splice(i, 1); } } - if (list.length === 0) { + if (list.length === 0) + { delete this._listeners[eventName]; } @@ -150,10 +168,12 @@ * * @param eventName {string} The event you want to remove all listeners for. */ - obj.removeAllListeners = function removeAllListeners(eventName) { + obj.removeAllListeners = function removeAllListeners(eventName) + { this._listeners = this._listeners || {}; - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return this; } @@ -169,7 +189,8 @@ * * @param object {object} The obj to mix into */ - mixin: function mixin(obj) { + mixin: function mixin(obj) + { eventTarget(obj); } }; diff --git a/src/core/utils/PolyK.js b/src/core/utils/PolyK.js index 7325141..5e20c2b 100644 --- a/src/core/utils/PolyK.js +++ b/src/core/utils/PolyK.js @@ -47,7 +47,8 @@ * Triangulates shapes for webGL graphic fills. * */ -PolyK.Triangulate = function (p) { +PolyK.Triangulate = function (p) +{ var sign = true; var n = p.length >> 1; @@ -59,7 +60,8 @@ i = 0; var al = n; - while(al > 3) { + while(al > 3) + { var i0 = avl[(i+0)%al]; var i1 = avl[(i+1)%al]; var i2 = avl[(i+2)%al]; @@ -69,29 +71,35 @@ var cx = p[2*i2], cy = p[2*i2+1]; var earFound = false; - if (PolyK._convex(ax, ay, bx, by, cx, cy, sign)) { + if (PolyK._convex(ax, ay, bx, by, cx, cy, sign)) + { earFound = true; - for (var j = 0; j < al; j++) { + for (var j = 0; j < al; j++) + { var vi = avl[j]; if (vi === i0 || vi === i1 || vi === i2) continue; - if (PolyK._PointInTriangle(p[2*vi], p[2*vi+1], ax, ay, bx, by, cx, cy)) { + if (PolyK._PointInTriangle(p[2*vi], p[2*vi+1], ax, ay, bx, by, cx, cy)) + { earFound = false; break; } } } - if (earFound) { + if (earFound) + { tgs.push(i0, i1, i2); avl.splice((i+1)%al, 1); al--; i = 0; } - else if (i++ > 3*al) { + else if (i++ > 3*al) + { // need to flip flip reverse it! // reset! - if (sign) { + if (sign) + { tgs = []; avl = []; for (i = 0; i < n; i++) avl.push(i); @@ -101,7 +109,8 @@ sign = false; } - else { + else + { // window.console.log("PIXI Warning: shape too complex to fill"); return null; } @@ -126,7 +135,8 @@ * @private * @return {boolean} */ -PolyK._PointInTriangle = function (px, py, ax, ay, bx, by, cx, cy) { +PolyK._PointInTriangle = function (px, py, ax, ay, bx, by, cx, cy) +{ var v0x = cx-ax; var v0y = cy-ay; var v1x = bx-ax; @@ -154,6 +164,7 @@ * @private * @return {boolean} */ -PolyK._convex = function (ax, ay, bx, by, cx, cy, sign) { +PolyK._convex = function (ax, ay, bx, by, cx, cy, sign) +{ return ((ay-by)*(cx-bx) + (bx-ax)*(cy-by) >= 0) === sign; }; diff --git a/src/core/utils/index.js b/src/core/utils/index.js index ade9831..bfae7ae 100644 --- a/src/core/utils/index.js +++ b/src/core/utils/index.js @@ -16,7 +16,8 @@ * * @return {number} The next uuid to use. */ - uuid: function () { + uuid: function () + { return ++utils._uid; }, @@ -26,7 +27,8 @@ * @param hex {number} * @return {number[]} An array representing the [R, G, B] of the color. */ - hex2rgb: function (hex, out) { + hex2rgb: function (hex, out) + { out = out || []; out[0] = (hex >> 16 & 0xFF) / 255; @@ -42,7 +44,8 @@ * @param hex {number} * @return {string} The string color. */ - hex2string: function (hex) { + hex2string: function (hex) + { hex = hex.toString(16); hex = '000000'.substr(0, 6 - hex.length) + hex; @@ -55,7 +58,8 @@ * @param rgb {number[]} * @return {number} The color number */ - rgb2hex: function (rgb) { + rgb2hex: function (rgb) + { return ((rgb[0]*255 << 16) + (rgb[1]*255 << 8) + rgb[2]*255); }, @@ -64,8 +68,10 @@ * * @return {boolean} whether they are supported */ - canUseNewCanvasBlendModes: function () { - if (typeof document === 'undefined') { + canUseNewCanvasBlendModes: function () + { + if (typeof document === 'undefined') + { return false; } @@ -93,15 +99,19 @@ * @param number {number} * @return {number} the closest number that is a power of two */ - getNextPowerOfTwo: function (number) { + getNextPowerOfTwo: function (number) + { // see: http://en.wikipedia.org/wiki/Power_of_two#Fast_algorithm_to_check_if_a_positive_number_is_a_power_of_two - if (number > 0 && (number & (number - 1)) === 0) { + if (number > 0 && (number & (number - 1)) === 0) + { return number; } - else { + else + { var result = 1; - while (result < number) { + while (result < number) + { result <<= 1; } @@ -116,7 +126,8 @@ * @param height {number} * @return {boolean} */ - isPowerOfTwo: function (width, height) { + isPowerOfTwo: function (width, height) + { return (width > 0 && (width & (width - 1)) === 0 && height > 0 && (height & (height - 1)) === 0); }, @@ -130,12 +141,15 @@ * @constant * @static */ - sayHello: function (type) { - if (utils._saidHello) { + sayHello: function (type) + { + if (utils._saidHello) + { return; } - if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) { + if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) + { var args = [ '%c %c %c Pixi.js ' + CONST.VERSION + ' - ' + type + ' %c ' + ' %c ' + ' http://www.pixijs.com/ %c %c ♥%c♥%c♥ ', 'background: #ff66a5', @@ -151,7 +165,8 @@ console.log.apply(console, args); //jshint ignore:line } - else if (window.console) { + else if (window.console) + { console.log('Pixi.js ' + CONST.VERSION + ' - ' + type + ' - http://www.pixijs.com/'); //jshint ignore:line } @@ -166,15 +181,19 @@ * @class * @namespace PIXI */ - AjaxRequest: function () { + AjaxRequest: function () + { var activexmodes = ['Msxml2.XMLHTTP.6.0', 'Msxml2.XMLHTTP.3.0', 'Microsoft.XMLHTTP']; //activeX versions to check for in IE - if (window.ActiveXObject) { //Test for support for ActiveXObject in IE first (as XMLHttpRequest in IE7 is broken) - for (var i=0; i= this.textures.length) { + else if (round >= this.textures.length) + { this.gotoAndStop(this.textures.length - 1); - if (this.onComplete) { + if (this.onComplete) + { this.onComplete(); } } @@ -167,10 +182,12 @@ * @static * @param frames {string[]} the array of frames ids the movieclip will use as its texture frames */ -MovieClip.fromFrames = function (frames) { +MovieClip.fromFrames = function (frames) +{ var textures = []; - for (var i = 0; i < frames.length; ++i) { + for (var i = 0; i < frames.length; ++i) + { textures.push(new core.Texture.fromFrame(frames[i])); } @@ -183,10 +200,12 @@ * @static * @param images {string[]} the array of image urls the movieclip will use as its texture frames */ -MovieClip.fromImages = function (images) { +MovieClip.fromImages = function (images) +{ var textures = []; - for (var i = 0; i < images.length; ++i) { + for (var i = 0; i < images.length; ++i) + { textures.push(new core.Texture.fromImage(images[i])); } diff --git a/src/extras/Rope.js b/src/extras/Rope.js index c157ec4..9c87bc0 100644 --- a/src/extras/Rope.js +++ b/src/extras/Rope.js @@ -9,7 +9,8 @@ * @param {Array} points - An array of {Point}. * */ -function Rope(texture, points) { +function Rope(texture, points) +{ Strip.call(this, texture); this.points = points; @@ -31,10 +32,12 @@ * Refreshes * */ -Rope.prototype.refresh = function () { +Rope.prototype.refresh = function () +{ var points = this.points; - if (points.length < 1) { + if (points.length < 1) + { return; } @@ -59,20 +62,23 @@ var total = points.length, point, index, amount; - for (var i = 1; i < total; i++) { + for (var i = 1; i < total; i++) + { point = points[i]; index = i * 4; // time to do some smart drawing! amount = i / (total-1); - if (i%2) { + if (i%2) + { uvs[index] = amount; uvs[index+1] = 0; uvs[index+2] = amount; uvs[index+3] = 1; } - else { + else + { uvs[index] = amount; uvs[index+1] = 0; @@ -95,10 +101,12 @@ * * @private */ -Rope.prototype.updateTransform = function () { +Rope.prototype.updateTransform = function () +{ var points = this.points; - if (points.length < 1) { + if (points.length < 1) + { return; } @@ -113,14 +121,17 @@ var total = points.length, point, index, ratio, perpLength, num; - for (var i = 0; i < total; i++) { + for (var i = 0; i < total; i++) + { point = points[i]; index = i * 4; - if (i < points.length-1) { + if (i < points.length-1) + { nextPoint = points[i+1]; } - else { + else + { nextPoint = point; } @@ -129,7 +140,8 @@ ratio = (1 - (i / (total-1))) * 10; - if (ratio > 1) { + if (ratio > 1) + { ratio = 1; } @@ -157,7 +169,8 @@ * * @param texture {Texture} the texture that will be used */ -Rope.prototype.setTexture = function (texture) { +Rope.prototype.setTexture = function (texture) +{ // stop current texture this.texture = texture; //this.updateFrame = true; diff --git a/src/extras/Strip.js b/src/extras/Strip.js index c5e378f..57691b5 100644 --- a/src/extras/Strip.js +++ b/src/extras/Strip.js @@ -10,7 +10,8 @@ * @param height {number} the height * */ -function Strip(texture) { +function Strip(texture) +{ core.DisplayObjectContainer.call(this); /** @@ -70,9 +71,11 @@ * * @param renderer {WebGLRenderer} */ -Strip.prototype.renderWebGL = function (renderer) { +Strip.prototype.renderWebGL = function (renderer) +{ // if the sprite is not visible or the alpha is 0 then no need to render this element - if (!this.visible || this.alpha <= 0) { + if (!this.visible || this.alpha <= 0) + { return; } @@ -81,7 +84,8 @@ renderer.spriteBatch.stop(); // init! init! - if (!this._vertexBuffer) { + if (!this._vertexBuffer) + { this._initWebGL(renderer); } @@ -96,7 +100,8 @@ //TODO check culling }; -Strip.prototype._initWebGL = function (renderer) { +Strip.prototype._initWebGL = function (renderer) +{ // build the strip! var gl = renderer.gl; @@ -118,7 +123,8 @@ gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this.indices, gl.STATIC_DRAW); }; -Strip.prototype._renderStrip = function (renderer) { +Strip.prototype._renderStrip = function (renderer) +{ var gl = renderer.gl; var projection = renderer.projection, offset = renderer.offset, @@ -137,7 +143,8 @@ gl.uniform2f(shader.offsetVector, -offset.x, -offset.y); gl.uniform1f(shader.alpha, this.worldAlpha); - if (!this.dirty) { + if (!this.dirty) + { gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexBuffer); gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); @@ -150,10 +157,12 @@ gl.activeTexture(gl.TEXTURE0); // check if a texture is dirty.. - if (this.texture.baseTexture._dirty[gl.id]) { + if (this.texture.baseTexture._dirty[gl.id]) + { renderer.updateTexture(this.texture.baseTexture); } - else { + else + { // bind the current texture gl.bindTexture(gl.TEXTURE_2D, this.texture.baseTexture._glTextures[gl.id]); } @@ -163,7 +172,8 @@ } - else { + else + { this.dirty = false; gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexBuffer); @@ -178,10 +188,12 @@ gl.activeTexture(gl.TEXTURE0); // check if a texture is dirty.. - if (this.texture.baseTexture._dirty[gl.id]) { + if (this.texture.baseTexture._dirty[gl.id]) + { renderer.updateTexture(this.texture.baseTexture); } - else { + else + { gl.bindTexture(gl.TEXTURE_2D, this.texture.baseTexture._glTextures[gl.id]); } @@ -203,27 +215,33 @@ * * @param renderer {CanvasRenderer} */ -Strip.prototype.renderCanvas = function (renderer) { +Strip.prototype.renderCanvas = function (renderer) +{ var context = renderer.context; var transform = this.worldTransform; - if (renderer.roundPixels) { + if (renderer.roundPixels) + { context.setTransform(transform.a, transform.b, transform.c, transform.d, transform.tx | 0, transform.ty | 0); } - else { + else + { context.setTransform(transform.a, transform.b, transform.c, transform.d, transform.tx, transform.ty); } - if (this.drawMode === Strip.DrawModes.TRIANGLE_STRIP) { + if (this.drawMode === Strip.DrawModes.TRIANGLE_STRIP) + { this._renderCanvasTriangleStrip(context); } - else { + else + { this._renderCanvasTriangles(context); } }; -Strip.prototype._renderCanvasTriangleStrip = function (context) { +Strip.prototype._renderCanvasTriangleStrip = function (context) +{ // draw triangles!! var vertices = this.vertices; var uvs = this.uvs; @@ -231,14 +249,16 @@ var length = vertices.length / 2; // this.count++; - for (var i = 0; i < length - 2; i++) { + for (var i = 0; i < length - 2; i++) + { // draw some triangles! var index = i * 2; this._renderCanvasDrawTriangle(context, vertices, uvs, index, (index + 2), (index + 4)); } }; -Strip.prototype._renderCanvasTriangles = function (context) { +Strip.prototype._renderCanvasTriangles = function (context) +{ // draw triangles!! var vertices = this.vertices; var uvs = this.uvs; @@ -247,14 +267,16 @@ var length = indices.length; // this.count++; - for (var i = 0; i < length; i += 3) { + for (var i = 0; i < length; i += 3) + { // draw some triangles! var index0 = indices[i] * 2, index1 = indices[i + 1] * 2, index2 = indices[i + 2] * 2; this._renderCanvasDrawTriangle(context, vertices, uvs, index0, index1, index2); } }; -Strip.prototype._renderCanvasDrawTriangle = function (context, vertices, uvs, index0, index1, index2) { +Strip.prototype._renderCanvasDrawTriangle = function (context, vertices, uvs, index0, index1, index2) +{ var textureSource = this.texture.baseTexture.source; var textureWidth = this.texture.width; var textureHeight = this.texture.height; @@ -265,7 +287,8 @@ var u0 = uvs[index0] * textureWidth, u1 = uvs[index1] * textureWidth, u2 = uvs[index2] * textureWidth; var v0 = uvs[index0 + 1] * textureHeight, v1 = uvs[index1 + 1] * textureHeight, v2 = uvs[index2 + 1] * textureHeight; - if (this.canvasPadding > 0) { + if (this.canvasPadding > 0) + { var paddingX = this.canvasPadding / this.worldTransform.a; var paddingY = this.canvasPadding / this.worldTransform.d; var centerX = (x0 + x1 + x2) / 3; @@ -332,7 +355,8 @@ * @param strip {Strip} The Strip to render * @private */ -Strip.prototype.renderStripFlat = function (strip) { +Strip.prototype.renderStripFlat = function (strip) +{ var context = this.context; var vertices = strip.vertices; @@ -340,7 +364,8 @@ // this.count++; context.beginPath(); - for (var i=1; i < length-2; i++) { + for (var i=1; i < length-2; i++) + { // draw some triangles! var index = i*2; @@ -358,7 +383,8 @@ }; /* -Strip.prototype.setTexture = function (texture) { +Strip.prototype.setTexture = function (texture) +{ //TODO SET THE TEXTURES //TODO VISIBILITY @@ -377,7 +403,8 @@ * @private */ -Strip.prototype.onTextureUpdate = function () { +Strip.prototype.onTextureUpdate = function () +{ this.updateFrame = true; }; @@ -387,7 +414,8 @@ * @param matrix {Matrix} the transformation matrix of the sprite * @return {Rectangle} the framing rectangle */ -Strip.prototype.getBounds = function (matrix) { +Strip.prototype.getBounds = function (matrix) +{ var worldTransform = matrix || this.worldTransform; var a = worldTransform.a; @@ -404,7 +432,8 @@ var minY = Infinity; var vertices = this.vertices; - for (var i = 0, n = vertices.length; i < n; i += 2) { + for (var i = 0, n = vertices.length; i < n; i += 2) + { var rawX = vertices[i], rawY = vertices[i + 1]; var x = (a * rawX) + (c * rawY) + tx; var y = (d * rawY) + (b * rawX) + ty; @@ -416,7 +445,8 @@ maxY = y > maxY ? y : maxY; } - if (minX === -Infinity || maxY === Infinity) { + if (minX === -Infinity || maxY === Infinity) + { return core.math.Rectangle.EMPTY; } diff --git a/src/extras/TilingSprite.js b/src/extras/TilingSprite.js index 3ac22df..31da393 100644 --- a/src/extras/TilingSprite.js +++ b/src/extras/TilingSprite.js @@ -10,7 +10,8 @@ * @param width {number} the width of the tiling sprite * @param height {number} the height of the tiling sprite */ -function TilingSprite(texture, width, height) { +function TilingSprite(texture, width, height) +{ core.Sprite.call( this, texture); /** @@ -86,10 +87,12 @@ * @memberof TilingSprite# */ width: { - get: function () { + get: function () + { return this._width; }, - set: function (value) { + set: function (value) + { this._width = value; } }, @@ -101,20 +104,25 @@ * @memberof TilingSprite# */ height: { - get: function () { + get: function () + { return this._height; }, - set: function (value) { + set: function (value) + { this._height = value; } }, texture: { - get: function () { + get: function () + { return this._texture; }, - set: function (value) { - if (this._texture === value) { + set: function (value) + { + if (this._texture === value) + { return; } @@ -130,51 +138,61 @@ * * @param renderer {WebGLRenderer} */ -TilingSprite.prototype.renderWebGL = function (renderer) { - if (!this.visible || this.alpha <= 0) { +TilingSprite.prototype.renderWebGL = function (renderer) +{ + if (!this.visible || this.alpha <= 0) + { return; } var i, j; - if (this._mask) { + if (this._mask) + { renderer.spriteBatch.stop(); renderer.maskManager.pushMask(this.mask, renderer); renderer.spriteBatch.start(); } - if (this._filters) { + if (this._filters) + { renderer.spriteBatch.flush(); renderer.filterManager.pushFilter(this._filterBlock); } - if (!this.tilingTexture || this.refreshTexture) { + if (!this.tilingTexture || this.refreshTexture) + { this.generateTilingTexture(true); - if (this.tilingTexture && this.tilingTexture.needsUpdate) { + if (this.tilingTexture && this.tilingTexture.needsUpdate) + { //TODO - tweaking renderer.updateTexture(this.tilingTexture.baseTexture); this.tilingTexture.needsUpdate = false; // this.tilingTexture._uvs = null; } } - else { + else + { renderer.spriteBatch.renderTilingSprite(this); } // simple render children! - for (i=0,j=this.children.length; i= 0; i--) { + for (var i = length - 1; i >= 0; i--) + { var child = children[i]; // push all interactive bits - if (child._interactive) { + if (child._interactive) + { iParent.interactiveChildren = true; //child.__iParent = iParent; this.interactiveItems.push(child); - if (child.children.length > 0) { + if (child.children.length > 0) + { this.collectInteractiveSprite(child, child); } } - else { + else + { child.__iParent = null; - if (child.children.length > 0) { + if (child.children.length > 0) + { this.collectInteractiveSprite(child, iParent); } } @@ -189,7 +196,8 @@ * @param [resolution=1] {number} THe resolution of the new element (relative to the canvas). * @private */ -InteractionManager.prototype.setTargetElement = function (element, resolution) { +InteractionManager.prototype.setTargetElement = function (element, resolution) +{ this.removeEvents(); this.interactionDOMElement = element; @@ -203,12 +211,15 @@ * * @private */ -InteractionManager.prototype.addEvents = function () { - if (!this.interactionDOMElement) { +InteractionManager.prototype.addEvents = function () +{ + if (!this.interactionDOMElement) + { return; } - if (window.navigator.msPointerEnabled) { + if (window.navigator.msPointerEnabled) + { this.interactionDOMElement.style['-ms-content-zooming'] = 'none'; this.interactionDOMElement.style['-ms-touch-action'] = 'none'; } @@ -230,12 +241,15 @@ * * @private */ -InteractionManager.prototype.removeEvents = function () { - if (!this.interactionDOMElement) { +InteractionManager.prototype.removeEvents = function () +{ + if (!this.interactionDOMElement) + { return; } - if (window.navigator.msPointerEnabled) { + if (window.navigator.msPointerEnabled) + { this.interactionDOMElement.style['-ms-content-zooming'] = ''; this.interactionDOMElement.style['-ms-touch-action'] = ''; } @@ -260,8 +274,10 @@ * * @private */ -InteractionManager.prototype.update = function () { - if (!this.interactionDOMElement) { +InteractionManager.prototype.update = function () +{ + if (!this.interactionDOMElement) + { return; } @@ -269,7 +285,8 @@ var now = Date.now(); var diff = now - this.last; diff = (diff * INTERACTION_FREQUENCY ) / 1000; - if (diff < 1) { + if (diff < 1) + { return; } @@ -280,7 +297,8 @@ // ok.. so mouse events?? // yes for now :) // OPTIMISE - how often to check?? - if (this.dirty) { + if (this.dirty) + { this.rebuildInteractiveGraph(); } @@ -289,7 +307,8 @@ var cursor = 'inherit'; var over = false; - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { var item = this.interactiveItems[i]; // OPTIMISATION - only calculate every time if the mousemove function exists.. @@ -302,26 +321,34 @@ this.mouse.target = item; // ok so deal with interactions.. // looks like there was a hit! - if (item.__hit && !over) { - if (item.buttonMode) { + if (item.__hit && !over) + { + if (item.buttonMode) + { cursor = item.defaultCursor; } - if (!item.interactiveChildren) { + if (!item.interactiveChildren) + { over = true; } - if (!item.__isOver) { - if (item.mouseover) { + if (!item.__isOver) + { + if (item.mouseover) + { item.mouseover (this.mouse); } item.__isOver = true; } } - else { - if (item.__isOver) { + else + { + if (item.__isOver) + { // roll out! - if (item.mouseout) { + if (item.mouseout) + { item.mouseout (this.mouse); } item.__isOver = false; @@ -329,7 +356,8 @@ } } - if (this.currentCursorStyle !== cursor) { + if (this.currentCursorStyle !== cursor) + { this.currentCursorStyle = cursor; this.interactionDOMElement.style.cursor = cursor; } @@ -338,18 +366,21 @@ /** * @private */ -InteractionManager.prototype.rebuildInteractiveGraph = function () { +InteractionManager.prototype.rebuildInteractiveGraph = function () +{ this.dirty = false; var len = this.interactiveItems.length; - for (var i = 0; i < len; i++) { + for (var i = 0; i < len; i++) + { this.interactiveItems[i].interactiveChildren = false; } this.interactiveItems.length = 0; - if (this.stage.interactive) { + if (this.stage.interactive) + { this.interactiveItems.push(this.stage); } @@ -363,8 +394,10 @@ * @param event {Event} The DOM event of the mouse moving * @private */ -InteractionManager.prototype.onMouseMove = function (event) { - if (this.dirty) { +InteractionManager.prototype.onMouseMove = function (event) +{ + if (this.dirty) + { this.rebuildInteractiveGraph(); } @@ -378,11 +411,13 @@ var length = this.interactiveItems.length; - for (var i = 0; i < length; i++) { + for (var i = 0; i < length; i++) + { var item = this.interactiveItems[i]; // Call the function! - if (item.mousemove) { + if (item.mousemove) + { item.mousemove(this.mouse); } } @@ -394,14 +429,17 @@ * @param event {Event} The DOM event of a mouse button being pressed down * @private */ -InteractionManager.prototype.onMouseDown = function (event) { - if (this.dirty) { +InteractionManager.prototype.onMouseDown = function (event) +{ + if (this.dirty) + { this.rebuildInteractiveGraph(); } this.mouse.originalEvent = event; - if (AUTO_PREVENT_DEFAULT) { + if (AUTO_PREVENT_DEFAULT) + { this.mouse.originalEvent.preventDefault(); } @@ -420,22 +458,27 @@ // while // hit test - for (var i = 0; i < length; i++) { + for (var i = 0; i < length; i++) + { var item = this.interactiveItems[i]; - if (item[downFunction] || item[clickFunction]) { + if (item[downFunction] || item[clickFunction]) + { item[buttonIsDown] = true; item.__hit = this.hitTest(item, this.mouse); - if (item.__hit) { + if (item.__hit) + { //call the function! - if (item[downFunction]) { + if (item[downFunction]) + { item[downFunction](this.mouse); } item[isDown] = true; // just the one! - if (!item.interactiveChildren) { + if (!item.interactiveChildren) + { break; } } @@ -449,8 +492,10 @@ * @param event {Event} The DOM event of a mouse being moved out * @private */ -InteractionManager.prototype.onMouseOut = function (event) { - if (this.dirty) { +InteractionManager.prototype.onMouseOut = function (event) +{ + if (this.dirty) + { this.rebuildInteractiveGraph(); } @@ -460,11 +505,14 @@ this.interactionDOMElement.style.cursor = 'inherit'; - for (var i = 0; i < length; i++) { + for (var i = 0; i < length; i++) + { var item = this.interactiveItems[i]; - if (item.__isOver) { + if (item.__isOver) + { this.mouse.target = item; - if (item.mouseout) { + if (item.mouseout) + { item.mouseout(this.mouse); } item.__isOver = false; @@ -484,8 +532,10 @@ * @param event {Event} The DOM event of a mouse button being released * @private */ -InteractionManager.prototype.onMouseUp = function (event) { - if (this.dirty) { +InteractionManager.prototype.onMouseUp = function (event) +{ + if (this.dirty) + { this.rebuildInteractiveGraph(); } @@ -502,30 +552,40 @@ var upOutsideFunction = isRightButton ? 'rightupoutside' : 'mouseupoutside'; var isDown = isRightButton ? '__isRightDown' : '__isDown'; - for (var i = 0; i < length; i++) { + for (var i = 0; i < length; i++) + { var item = this.interactiveItems[i]; - if (item[clickFunction] || item[upFunction] || item[upOutsideFunction]) { + if (item[clickFunction] || item[upFunction] || item[upOutsideFunction]) + { item.__hit = this.hitTest(item, this.mouse); - if (item.__hit && !up) { + if (item.__hit && !up) + { //call the function! - if (item[upFunction]) { + if (item[upFunction]) + { item[upFunction](this.mouse); } - if (item[isDown]) { - if (item[clickFunction]) { + if (item[isDown]) + { + if (item[clickFunction]) + { item[clickFunction](this.mouse); } } - if (!item.interactiveChildren) { + if (!item.interactiveChildren) + { up = true; } } - else { - if (item[isDown]) { - if (item[upOutsideFunction]) { + else + { + if (item[isDown]) + { + if (item[upOutsideFunction]) + { item[upOutsideFunction](this.mouse); } } @@ -543,10 +603,12 @@ * @param interactionData {InteractionData} The interactionData object to update in the case there is a hit * @private */ -InteractionManager.prototype.hitTest = function (item, interactionData) { +InteractionManager.prototype.hitTest = function (item, interactionData) +{ var global = interactionData.global; - if (!item.worldVisible) { + if (!item.worldVisible) + { return false; } @@ -560,37 +622,46 @@ interactionData.target = item; //a sprite or display object with a hit area defined - if (item.hitArea && item.hitArea.contains) { + if (item.hitArea && item.hitArea.contains) + { return item.hitArea.contains(x, y); } // a sprite with no hitarea defined - else if (item instanceof core.Sprite) { + else if (item instanceof core.Sprite) + { var width = item.texture.frame.width; var height = item.texture.frame.height; var x1 = -width * item.anchor.x; var y1; - if (x > x1 && x < x1 + width) { + if (x > x1 && x < x1 + width) + { y1 = -height * item.anchor.y; - if (y > y1 && y < y1 + height) { + if (y > y1 && y < y1 + height) + { // set the target property if a hit is true! return true; } } } - else if (item instanceof core.Graphics) { + else if (item instanceof core.Graphics) + { var graphicsData = item.graphicsData; - for (i = 0; i < graphicsData.length; i++) { + for (i = 0; i < graphicsData.length; i++) + { var data = graphicsData[i]; - if (!data.fill) { + if (!data.fill) + { continue; } // only deal with fills.. - if (data.shape) { - if (data.shape.contains(x, y)) { + if (data.shape) + { + if (data.shape.contains(x, y)) + { //interactionData.target = item; return true; } @@ -600,10 +671,12 @@ var length = item.children.length; - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { var tempItem = item.children[i]; var hit = this.hitTest(tempItem, interactionData); - if (hit) { + if (hit) + { // hmm.. TODO SET CORRECT TARGET? interactionData.target = item; return true; @@ -618,8 +691,10 @@ * @param event {Event} The DOM event of a touch moving across the renderer view * @private */ -InteractionManager.prototype.onTouchMove = function (event) { - if (this.dirty) { +InteractionManager.prototype.onTouchMove = function (event) +{ + if (this.dirty) + { this.rebuildInteractiveGraph(); } @@ -628,7 +703,8 @@ var touchData; var i = 0; - for (i = 0; i < changedTouches.length; i++) { + for (i = 0; i < changedTouches.length; i++) + { var touchEvent = changedTouches[i]; touchData = this.touches[touchEvent.identifier]; touchData.originalEvent = event; @@ -636,15 +712,18 @@ // update the touch position touchData.global.x = ( (touchEvent.clientX - rect.left) * (this.interactionDOMElement.width / rect.width) ) / this.resolution; touchData.global.y = ( (touchEvent.clientY - rect.top) * (this.interactionDOMElement.height / rect.height) ) / this.resolution; - if (navigator.isCocoonJS && !rect.left && !rect.top && !event.target.style.width && !event.target.style.height) { + if (navigator.isCocoonJS && !rect.left && !rect.top && !event.target.style.width && !event.target.style.height) + { //Support for CocoonJS fullscreen scale modes touchData.global.x = touchEvent.clientX; touchData.global.y = touchEvent.clientY; } - for (var j = 0; j < this.interactiveItems.length; j++) { + for (var j = 0; j < this.interactiveItems.length; j++) + { var item = this.interactiveItems[j]; - if (item.touchmove && item.__touchData && item.__touchData[touchEvent.identifier]) { + if (item.touchmove && item.__touchData && item.__touchData[touchEvent.identifier]) + { item.touchmove(touchData); } } @@ -657,23 +736,28 @@ * @param event {Event} The DOM event of a touch starting on the renderer view * @private */ -InteractionManager.prototype.onTouchStart = function (event) { - if (this.dirty) { +InteractionManager.prototype.onTouchStart = function (event) +{ + if (this.dirty) + { this.rebuildInteractiveGraph(); } var rect = this.interactionDOMElement.getBoundingClientRect(); - if (AUTO_PREVENT_DEFAULT) { + if (AUTO_PREVENT_DEFAULT) + { event.preventDefault(); } var changedTouches = event.changedTouches; - for (var i=0; i < changedTouches.length; i++) { + for (var i=0; i < changedTouches.length; i++) + { var touchEvent = changedTouches[i]; var touchData = this.pool.pop(); - if (!touchData) { + if (!touchData) + { touchData = new InteractionData(); } @@ -682,7 +766,8 @@ this.touches[touchEvent.identifier] = touchData; touchData.global.x = ( (touchEvent.clientX - rect.left) * (this.interactionDOMElement.width / rect.width) ) / this.resolution; touchData.global.y = ( (touchEvent.clientY - rect.top) * (this.interactionDOMElement.height / rect.height) ) / this.resolution; - if (navigator.isCocoonJS && !rect.left && !rect.top && !event.target.style.width && !event.target.style.height) { + if (navigator.isCocoonJS && !rect.left && !rect.top && !event.target.style.width && !event.target.style.height) + { //Support for CocoonJS fullscreen scale modes touchData.global.x = touchEvent.clientX; touchData.global.y = touchEvent.clientY; @@ -690,15 +775,19 @@ var length = this.interactiveItems.length; - for (var j = 0; j < length; j++) { + for (var j = 0; j < length; j++) + { var item = this.interactiveItems[j]; - if (item.touchstart || item.tap) { + if (item.touchstart || item.tap) + { item.__hit = this.hitTest(item, touchData); - if (item.__hit) { + if (item.__hit) + { //call the function! - if (item.touchstart) { + if (item.touchstart) + { item.touchstart(touchData); } @@ -706,7 +795,8 @@ item.__touchData = item.__touchData || {}; item.__touchData[touchEvent.identifier] = touchData; - if (!item.interactiveChildren) { + if (!item.interactiveChildren) + { break; } } @@ -721,31 +811,37 @@ * @param event {Event} The DOM event of a touch ending on the renderer view * @private */ -InteractionManager.prototype.onTouchEnd = function (event) { - if (this.dirty) { +InteractionManager.prototype.onTouchEnd = function (event) +{ + if (this.dirty) + { this.rebuildInteractiveGraph(); } var rect = this.interactionDOMElement.getBoundingClientRect(); var changedTouches = event.changedTouches; - for (var i=0; i < changedTouches.length; i++) { + for (var i=0; i < changedTouches.length; i++) + { var touchEvent = changedTouches[i]; var touchData = this.touches[touchEvent.identifier]; var up = false; touchData.global.x = ( (touchEvent.clientX - rect.left) * (this.interactionDOMElement.width / rect.width) ) / this.resolution; touchData.global.y = ( (touchEvent.clientY - rect.top) * (this.interactionDOMElement.height / rect.height) ) / this.resolution; - if (navigator.isCocoonJS && !rect.left && !rect.top && !event.target.style.width && !event.target.style.height) { + if (navigator.isCocoonJS && !rect.left && !rect.top && !event.target.style.width && !event.target.style.height) + { //Support for CocoonJS fullscreen scale modes touchData.global.x = touchEvent.clientX; touchData.global.y = touchEvent.clientY; } var length = this.interactiveItems.length; - for (var j = 0; j < length; j++) { + for (var j = 0; j < length; j++) + { var item = this.interactiveItems[j]; - if (item.__touchData && item.__touchData[touchEvent.identifier]) { + if (item.__touchData && item.__touchData[touchEvent.identifier]) + { item.__hit = this.hitTest(item, item.__touchData[touchEvent.identifier]); @@ -753,20 +849,27 @@ touchData.originalEvent = event; // hitTest?? - if (item.touchend || item.tap) { - if (item.__hit && !up) { - if (item.touchend) { + if (item.touchend || item.tap) + { + if (item.__hit && !up) + { + if (item.touchend) + { item.touchend(touchData); } - if (item.__isDown && item.tap) { + if (item.__isDown && item.tap) + { item.tap(touchData); } - if (!item.interactiveChildren) { + if (!item.interactiveChildren) + { up = true; } } - else { - if (item.__isDown && item.touchendoutside) { + else + { + if (item.__isDown && item.touchendoutside) + { item.touchendoutside(touchData); } } diff --git a/src/loaders/AssetLoader.js b/src/loaders/AssetLoader.js index 20da0cf..c4dba1c 100644 --- a/src/loaders/AssetLoader.js +++ b/src/loaders/AssetLoader.js @@ -21,7 +21,8 @@ * data formats include 'xml' and 'fnt'. * @param crossorigin {boolean} Whether requests should be treated as crossorigin */ -function AssetLoader(assetURLs, crossorigin) { +function AssetLoader(assetURLs, crossorigin) +{ /** * The array of asset URLs that are going to be loaded * @@ -76,16 +77,19 @@ * * @param str {string} the name of the asset */ -AssetLoader.prototype._getDataType = function (str) { +AssetLoader.prototype._getDataType = function (str) +{ var test = 'data:'; var start = str.slice(0, test.length).toLowerCase(); - if (start === test) { + if (start === test) + { var data = str.slice(test.length); var sepIdx = data.indexOf(','); // check for malformed data URI scheme - if (sepIdx === -1) { + if (sepIdx === -1) + { return null; } @@ -94,7 +98,8 @@ //We might need to handle some special cases here... //standardize text/plain to 'txt' file extension - if (!info || info.toLowerCase() === 'text/plain') { + if (!info || info.toLowerCase() === 'text/plain') + { return 'txt'; } @@ -109,27 +114,32 @@ * Starts loading the assets sequentially * */ -AssetLoader.prototype.load = function () { +AssetLoader.prototype.load = function () +{ var scope = this; - function onLoad(evt) { + function onLoad(evt) + { scope.onAssetLoaded(evt.data.content); } this.loadCount = this.assetURLs.length; - for (var i=0; i < this.assetURLs.length; i++) { + for (var i=0; i < this.assetURLs.length; i++) + { var fileName = this.assetURLs[i]; //first see if we have a data URI scheme.. var fileType = this._getDataType(fileName); //if not, assume it's a file URI - if (!fileType) { + if (!fileType) + { fileType = fileName.split('?').shift().split('.').pop().toLowerCase(); } var Constructor = this.loadersByType[fileType]; - if (!Constructor) { + if (!Constructor) + { throw new Error(fileType + ' is an unsupported file type'); } @@ -145,18 +155,22 @@ * * @private */ -AssetLoader.prototype.onAssetLoaded = function (loader) { +AssetLoader.prototype.onAssetLoaded = function (loader) +{ this.loadCount--; this.emit('onProgress', { content: this, loader: loader }); - if (this.onProgress) { + if (this.onProgress) + { this.onProgress(loader); } - if (!this.loadCount) { + if (!this.loadCount) + { this.emit('onComplete', { content: this }); - if (this.onComplete) { + if (this.onComplete) + { this.onComplete(); } } diff --git a/src/loaders/AtlasLoader.js b/src/loaders/AtlasLoader.js index 5eda286..3aec9e2 100644 --- a/src/loaders/AtlasLoader.js +++ b/src/loaders/AtlasLoader.js @@ -15,7 +15,8 @@ * @param url {String} The url of the JSON file * @param crossorigin {boolean} Whether requests should be treated as crossorigin */ -function AtlasLoader(url, crossorigin) { +function AtlasLoader(url, crossorigin) +{ this.url = url; this.baseUrl = url.replace(/[^\/]*$/, ''); this.crossorigin = crossorigin; @@ -31,13 +32,15 @@ * Starts loading the JSON file * */ -AtlasLoader.prototype.load = function () { +AtlasLoader.prototype.load = function () +{ this.ajaxRequest = new core.utils.AjaxRequest(); this.ajaxRequest.onreadystatechange = this.onAtlasLoaded.bind(this); this.ajaxRequest.open('GET', this.url, true); - if (this.ajaxRequest.overrideMimeType) { + if (this.ajaxRequest.overrideMimeType) + { this.ajaxRequest.overrideMimeType('application/json'); } @@ -49,9 +52,12 @@ * * @private */ -AtlasLoader.prototype.onAtlasLoaded = function () { - if (this.ajaxRequest.readyState === 4) { - if (this.ajaxRequest.status === 200 || window.location.href.indexOf('http') === -1) { +AtlasLoader.prototype.onAtlasLoaded = function () +{ + if (this.ajaxRequest.readyState === 4) + { + if (this.ajaxRequest.status === 200 || window.location.href.indexOf('http') === -1) + { this.atlas = { meta : { image : [] @@ -70,34 +76,44 @@ selfOnLoaded = this.onLoaded.bind(this); // parser without rotation support yet! - for (i = 0; i < result.length; i++) { + for (i = 0; i < result.length; i++) + { result[i] = result[i].replace(/^\s+|\s+$/g, ''); - if (result[i] === '') { + if (result[i] === '') + { nameInNextLine = i+1; } - if (result[i].length > 0) { - if (nameInNextLine === i) { + if (result[i].length > 0) + { + if (nameInNextLine === i) + { this.atlas.meta.image.push(result[i]); currentImageId = this.atlas.meta.image.length - 1; this.atlas.frames.push({}); lineCount = -3; - } else if (lineCount > 0) { - if (lineCount % 7 === 1) { // frame name - if (currentFrame != null) { //jshint ignore:line + } else if (lineCount > 0) + { + if (lineCount % 7 === 1) + { // frame name + if (currentFrame != null) + { //jshint ignore:line this.atlas.frames[currentImageId][currentFrame.name] = currentFrame; } currentFrame = { name: result[i], frame : {} }; } else { var text = result[i].split(' '); - if (lineCount % 7 === 3) { // position + if (lineCount % 7 === 3) + { // position currentFrame.frame.x = Number(text[1].replace(',', '')); currentFrame.frame.y = Number(text[2]); - } else if (lineCount % 7 === 4) { // size + } else if (lineCount % 7 === 4) + { // size currentFrame.frame.w = Number(text[1].replace(',', '')); currentFrame.frame.h = Number(text[2]); - } else if (lineCount % 7 === 5) { // real size + } else if (lineCount % 7 === 5) + { // real size var realSize = { x : 0, y : 0, @@ -105,7 +121,8 @@ h : Number(text[2]) }; - if (realSize.w > currentFrame.frame.w || realSize.h > currentFrame.frame.h) { + if (realSize.w > currentFrame.frame.w || realSize.h > currentFrame.frame.h) + { currentFrame.trimmed = true; currentFrame.realSize = realSize; } else { @@ -118,28 +135,34 @@ } } - if (currentFrame != null) { //jshint ignore:line + if (currentFrame != null) + { //jshint ignore:line this.atlas.frames[currentImageId][currentFrame.name] = currentFrame; } - if (this.atlas.meta.image.length > 0) { + if (this.atlas.meta.image.length > 0) + { this.images = []; - for (j = 0; j < this.atlas.meta.image.length; j++) { + for (j = 0; j < this.atlas.meta.image.length; j++) + { // sprite sheet var textureUrl = this.baseUrl + this.atlas.meta.image[j]; var frameData = this.atlas.frames[j]; this.images.push(new ImageLoader(textureUrl, this.crossorigin)); - for (i in frameData) { + for (i in frameData) + { var rect = frameData[i].frame; - if (rect) { + if (rect) + { core.utils.TextureCache[i] = new core.Texture(this.images[j].texture.baseTexture, { x: rect.x, y: rect.y, width: rect.w, height: rect.h }); - if (frameData[i].trimmed) { + if (frameData[i].trimmed) + { core.utils.TextureCache[i].realSize = frameData[i].realSize; // trim in pixi not supported yet, todo update trim properties if it is done ... core.utils.TextureCache[i].trim.x = 0; @@ -150,7 +173,8 @@ } this.currentImageId = 0; - for (j = 0; j < this.images.length; j++) { + for (j = 0; j < this.images.length; j++) + { this.images[j].on('loaded', selfOnLoaded); } this.images[this.currentImageId].load(); @@ -170,8 +194,10 @@ * * @private */ -AtlasLoader.prototype.onLoaded = function () { - if (this.images.length - 1 > this.currentImageId) { +AtlasLoader.prototype.onLoaded = function () +{ + if (this.images.length - 1 > this.currentImageId) + { this.currentImageId++; this.images[this.currentImageId].load(); } else { @@ -185,6 +211,7 @@ * * @private */ -AtlasLoader.prototype.onError = function () { +AtlasLoader.prototype.onError = function () +{ this.emit('error', { content: this }); }; diff --git a/src/loaders/BitmapFontLoader.js b/src/loaders/BitmapFontLoader.js index 8641760..13e5c1b 100644 --- a/src/loaders/BitmapFontLoader.js +++ b/src/loaders/BitmapFontLoader.js @@ -13,7 +13,8 @@ * @param url {String} The url of the sprite sheet JSON file * @param crossorigin {boolean} Whether requests should be treated as crossorigin */ -function BitmapFontLoader(url, crossorigin) { +function BitmapFontLoader(url, crossorigin) +{ /** * The url of the bitmap font data * @@ -54,13 +55,15 @@ * Loads the XML font data * */ -BitmapFontLoader.prototype.load = function () { +BitmapFontLoader.prototype.load = function () +{ this.ajaxRequest = new core.utils.AjaxRequest(); this.ajaxRequest.onreadystatechange = this.onXMLLoaded.bind(this); this.ajaxRequest.open('GET', this.url, true); - if (this.ajaxRequest.overrideMimeType) { + if (this.ajaxRequest.overrideMimeType) + { this.ajaxRequest.overrideMimeType('application/xml'); } @@ -72,12 +75,17 @@ * * @private */ -BitmapFontLoader.prototype.onXMLLoaded = function () { - if (this.ajaxRequest.readyState === 4) { - if (this.ajaxRequest.status === 200 || window.location.protocol.indexOf('http') === -1) { +BitmapFontLoader.prototype.onXMLLoaded = function () +{ + if (this.ajaxRequest.readyState === 4) + { + if (this.ajaxRequest.status === 200 || window.location.protocol.indexOf('http') === -1) + { var responseXML = this.ajaxRequest.responseXML; - if (!responseXML || /MSIE 9/i.test(navigator.userAgent) || navigator.isCocoonJS) { - if (typeof(window.DOMParser) === 'function') { + if (!responseXML || /MSIE 9/i.test(navigator.userAgent) || navigator.isCocoonJS) + { + if (typeof(window.DOMParser) === 'function') + { var domparser = new DOMParser(); responseXML = domparser.parseFromString(this.ajaxRequest.responseText, 'text/xml'); } else { @@ -102,7 +110,8 @@ //parse letters var letters = responseXML.getElementsByTagName('char'); - for (var i = 0; i < letters.length; i++) { + for (var i = 0; i < letters.length; i++) + { var charCode = parseInt(letters[i].getAttribute('id'), 10); var textureRect = new core.math.Rectangle( @@ -124,7 +133,8 @@ //parse kernings var kernings = responseXML.getElementsByTagName('kerning'); - for (i = 0; i < kernings.length; i++) { + for (i = 0; i < kernings.length; i++) + { var first = parseInt(kernings[i].getAttribute('first'), 10); var second = parseInt(kernings[i].getAttribute('second'), 10); var amount = parseInt(kernings[i].getAttribute('amount'), 10); @@ -146,6 +156,7 @@ * * @private */ -BitmapFontLoader.prototype.onLoaded = function () { +BitmapFontLoader.prototype.onLoaded = function () +{ this.emit('loaded', { content: this }); }; diff --git a/src/loaders/ImageLoader.js b/src/loaders/ImageLoader.js index e3ff493..16ee7c8 100644 --- a/src/loaders/ImageLoader.js +++ b/src/loaders/ImageLoader.js @@ -11,7 +11,8 @@ * @param url {String} The url of the image * @param crossorigin {boolean} Whether requests should be treated as crossorigin */ -function ImageLoader(url, crossorigin) { +function ImageLoader(url, crossorigin) +{ /** * The texture being loaded * @@ -39,12 +40,15 @@ * Loads image or takes it from cache * */ -ImageLoader.prototype.load = function () { - if (!this.texture.baseTexture.hasLoaded) { +ImageLoader.prototype.load = function () +{ + if (!this.texture.baseTexture.hasLoaded) + { this.texture.baseTexture.on('loaded', this.onLoaded.bind(this)); this.texture.baseTexture.on('error', this.onError.bind(this)); } - else { + else + { this.onLoaded(); } }; @@ -54,7 +58,8 @@ * * @private */ -ImageLoader.prototype.onLoaded = function () { +ImageLoader.prototype.onLoaded = function () +{ this.emit('loaded', { content: this }); }; @@ -64,7 +69,8 @@ * @method onError * @private */ -ImageLoader.prototype.onError = function () { +ImageLoader.prototype.onError = function () +{ this.emit('error', { content: this }); }; @@ -75,15 +81,18 @@ * @param frameHeight {number} height of each frame * @param textureName {String} if given, the frames will be cached in - format */ -ImageLoader.prototype.loadFramedSpriteSheet = function (frameWidth, frameHeight, textureName) { +ImageLoader.prototype.loadFramedSpriteSheet = function (frameWidth, frameHeight, textureName) +{ this.frames = []; var cols = Math.floor(this.texture.width / frameWidth); var rows = Math.floor(this.texture.height / frameHeight); var i=0; - for (var y = 0; y < rows; ++y) { - for (var x = 0; x < cols; ++x, ++i) { + for (var y = 0; y < rows; ++y) + { + for (var x = 0; x < cols; ++x, ++i) + { var texture = new core.Texture( this.texture.baseTexture, new core.math.Rectangle( @@ -96,7 +105,8 @@ this.frames.push(texture); - if (textureName) { + if (textureName) + { core.utils.TextureCache[textureName + '-' + i] = texture; } } diff --git a/src/core/display/DisplayObject.js b/src/core/display/DisplayObject.js index 66ebc3c..20e778c 100644 --- a/src/core/display/DisplayObject.js +++ b/src/core/display/DisplayObject.js @@ -7,7 +7,8 @@ * @class * @namespace PIXI */ -function DisplayObject() { +function DisplayObject() +{ /** * The coordinate of the object relative to the local coordinates of the parent. * @@ -152,10 +153,12 @@ * @memberof DisplayObject# */ x: { - get: function () { + get: function () + { return this.position.x; }, - set: function (value) { + set: function (value) + { this.position.x = value; } }, @@ -167,10 +170,12 @@ * @memberof DisplayObject# */ y: { - get: function () { + get: function () + { return this.position.y; }, - set: function (value) { + set: function (value) + { this.position.y = value; } }, @@ -183,11 +188,13 @@ * @readonly */ worldVisible: { - get: function () { + get: function () + { var item = this; do { - if (!item.visible) { + if (!item.visible) + { return false; } @@ -207,17 +214,21 @@ * @memberof DisplayObject# */ mask: { - get: function () { + get: function () + { return this._mask; }, - set: function (value) { - if (this._mask) { + set: function (value) + { + if (this._mask) + { this._mask.isMask = false; } this._mask = value; - if (this._mask) { + if (this._mask) + { this._mask.isMask = true; } } @@ -232,18 +243,23 @@ * @memberof DisplayObject# */ filters: { - get: function () { + get: function () + { return this._filters; }, - set: function (value) { - if (value) { + set: function (value) + { + if (value) + { // now put all the passes in one place.. var passes = []; - for (var i = 0; i < value.length; i++) { + for (var i = 0; i < value.length; i++) + { var filterPasses = value[i].passes; - for (var j = 0; j < filterPasses.length; j++) { + for (var j = 0; j < filterPasses.length; j++) + { passes.push(filterPasses[j]); } } @@ -264,8 +280,9 @@ * * @private */ -DisplayObject.prototype.updateTransform = function () { - +DisplayObject.prototype.updateTransform = function () +{ + // create some matrix refs for easy access var pt = this.parent.worldTransform; var wt = this.worldTransform; @@ -274,9 +291,11 @@ var a, b, c, d, tx, ty; // so if rotation is between 0 then we can simplify the multiplication process.. - if (this.rotation % math.PI_2) { + if (this.rotation % math.PI_2) + { // 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) { + if (this.rotation !== this.rotationCache) + { this.rotationCache = this.rotation; this._sr = Math.sin(this.rotation); this._cr = Math.cos(this.rotation); @@ -291,7 +310,8 @@ ty = this.position.y; // check for pivot.. not often used so geared towards that fact! - if (this.pivot.x || this.pivot.y) { + 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; } @@ -304,7 +324,8 @@ wt.tx = tx * pt.a + ty * pt.c + pt.tx; wt.ty = tx * pt.b + ty * pt.d + pt.ty; } - else { + else + { // lets do the fast version as we know there is no rotation.. a = this.scale.x; d = this.scale.y; @@ -333,7 +354,8 @@ * @param matrix {Matrix} * @return {Rectangle} the rectangular bounding area */ -DisplayObject.prototype.getBounds = function (/* matrix */) { +DisplayObject.prototype.getBounds = function (/* matrix */) +{ return math.Rectangle.EMPTY; }; @@ -342,7 +364,8 @@ * * @return {Rectangle} the rectangular bounding area */ -DisplayObject.prototype.getLocalBounds = function () { +DisplayObject.prototype.getLocalBounds = function () +{ return this.getBounds(math.Matrix.IDENTITY); }; @@ -352,7 +375,8 @@ * @param position {Point} The world origin to calculate from * @return {Point} A point object representing the position of this object */ -DisplayObject.prototype.toGlobal = function (position) { +DisplayObject.prototype.toGlobal = function (position) +{ // don't need to u[date the lot this.displayObjectUpdateTransform(); return this.worldTransform.apply(position); @@ -365,8 +389,10 @@ * @param [from] {DisplayObject} The DisplayObject to calculate the global position from * @return {Point} A point object representing the position of this object */ -DisplayObject.prototype.toLocal = function (position, from) { - if (from) { +DisplayObject.prototype.toLocal = function (position, from) +{ + if (from) + { position = from.toGlobal(position); } @@ -381,7 +407,8 @@ * @param renderer {WebGLRenderer} The renderer * @private */ -DisplayObject.prototype.renderWebGL = function (/* renderer */) { +DisplayObject.prototype.renderWebGL = function (/* renderer */) +{ // OVERWRITE; }; @@ -391,6 +418,7 @@ * @param renderer {CanvasRenderer} The renderer * @private */ -DisplayObject.prototype.renderCanvas = function (/* renderer */) { +DisplayObject.prototype.renderCanvas = function (/* renderer */) +{ // OVERWRITE; }; diff --git a/src/core/display/DisplayObjectContainer.js b/src/core/display/DisplayObjectContainer.js index 689f40b..4625ee8 100644 --- a/src/core/display/DisplayObjectContainer.js +++ b/src/core/display/DisplayObjectContainer.js @@ -12,7 +12,8 @@ * @extends DisplayObject * @namespace PIXI */ -function DisplayObjectContainer() { +function DisplayObjectContainer() +{ DisplayObject.call(this); /** @@ -47,17 +48,21 @@ * @memberof DisplayObjectContainer# */ width: { - get: function () { + get: function () + { return this.scale.x * this.getLocalBounds().width; }, - set: function (value) { + set: function (value) + { var width = this.getLocalBounds().width; - if(width !== 0) { + if(width !== 0) + { this.scale.x = value / width; } - else { + else + { this.scale.x = 1; } @@ -73,17 +78,21 @@ * @memberof DisplayObjectContainer# */ height: { - get: function () { + get: function () + { return this.scale.y * this.getLocalBounds().height; }, - set: function (value) { + set: function (value) + { var height = this.getLocalBounds().height; - if (height !== 0) { + if (height !== 0) + { this.scale.y = value / height ; } - else { + else + { this.scale.y = 1; } @@ -100,18 +109,23 @@ * @memberof DisplayObject# */ cacheAsBitmap: { - get: function () { + get: function () + { return this._cacheAsBitmap; }, - set: function (value) { - if (this._cacheAsBitmap === value) { + set: function (value) + { + if (this._cacheAsBitmap === value) + { return; } - if (value) { + if (value) + { this._generateCachedSprite(); } - else { + else + { this._destroyCachedSprite(); } @@ -126,7 +140,8 @@ * @param child {DisplayObject} The DisplayObject to add to the container * @return {DisplayObject} The child that was added. */ -DisplayObjectContainer.prototype.addChild = function (child) { +DisplayObjectContainer.prototype.addChild = function (child) +{ return this.addChildAt(child, this.children.length); }; @@ -137,14 +152,18 @@ * @param index {Number} The index to place the child in * @return {DisplayObject} The child that was added. */ -DisplayObjectContainer.prototype.addChildAt = function (child, index) { +DisplayObjectContainer.prototype.addChildAt = function (child, index) +{ // prevent adding self as child - if (child === this) { + if (child === this) + { return; } - if (index >= 0 && index <= this.children.length) { - if (child.parent) { + if (index >= 0 && index <= this.children.length) + { + if (child.parent) + { child.parent.removeChild(child); } @@ -154,7 +173,8 @@ return child; } - else { + else + { throw new Error(child + 'addChildAt: The index '+ index +' supplied is out of bounds ' + this.children.length); } }; @@ -165,15 +185,18 @@ * @param child {DisplayObject} * @param child2 {DisplayObject} */ -DisplayObjectContainer.prototype.swapChildren = function (child, child2) { - if (child === child2) { +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) { + if (index1 < 0 || index2 < 0) + { throw new Error('swapChildren: Both the supplied DisplayObjects must be a child of the caller.'); } @@ -187,10 +210,12 @@ * @param child {DisplayObject} The DisplayObject instance to identify * @return {Number} The index position of the child display object to identify */ -DisplayObjectContainer.prototype.getChildIndex = function (child) { +DisplayObjectContainer.prototype.getChildIndex = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { throw new Error('The supplied DisplayObject must be a child of the caller'); } @@ -203,8 +228,10 @@ * @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 */ -DisplayObjectContainer.prototype.setChildIndex = function (child, index) { - if (index < 0 || index >= this.children.length) { +DisplayObjectContainer.prototype.setChildIndex = function (child, index) +{ + if (index < 0 || index >= this.children.length) + { throw new Error('The supplied index is out of bounds'); } @@ -220,8 +247,10 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child at the given index, if any. */ -DisplayObjectContainer.prototype.getChildAt = function (index) { - if (index < 0 || index >= this.children.length) { +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'); } @@ -234,10 +263,12 @@ * @param child {DisplayObject} The DisplayObject to remove * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChild = function (child) { +DisplayObjectContainer.prototype.removeChild = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { return; } @@ -250,7 +281,8 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChildAt = function (index) { +DisplayObjectContainer.prototype.removeChildAt = function (index) +{ var child = this.getChildAt(index); child.parent = null; @@ -265,24 +297,29 @@ * @param beginIndex {Number} The beginning position. Default value is 0. * @param endIndex {Number} The ending position. Default value is size of the container. */ -DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) { +DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) +{ var begin = beginIndex || 0; var end = typeof endIndex === 'number' ? endIndex : this.children.length; var range = end - begin; - if (range > 0 && range <= end) { + if (range > 0 && range <= end) + { var removed = this.children.splice(begin, range); - for (var i = 0; i < removed.length; ++i) { + for (var i = 0; i < removed.length; ++i) + { removed[i].parent = null; } return removed; } - else if (range === 0 && this.children.length === 0) { + else if (range === 0 && this.children.length === 0) + { return []; } - else { + else + { throw new RangeError('removeChildren: numeric values are outside the acceptable range.'); } }; @@ -291,7 +328,8 @@ * Generates and updates the cached sprite for this object. * */ -DisplayObjectContainer.prototype.updateCachedSprite = function () { +DisplayObjectContainer.prototype.updateCachedSprite = function () +{ this._generateCachedSprite(); }; @@ -304,7 +342,8 @@ * @param renderer {CanvasRenderer|WebGLRenderer} The renderer used to generate the texture. * @return {Texture} a texture of the graphics object */ -DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) { +DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) +{ var bounds = this.getLocalBounds(); var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0, renderer, scaleMode, resolution); @@ -322,18 +361,22 @@ * * @private */ -DisplayObjectContainer.prototype.updateTransform = function () { - if (!this.visible) { +DisplayObjectContainer.prototype.updateTransform = function () +{ + if (!this.visible) + { return; } this.displayObjectUpdateTransform(); - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { return; } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } }; @@ -346,8 +389,10 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getBounds = function () { - if (this.children.length === 0) { +DisplayObjectContainer.prototype.getBounds = function () +{ + if (this.children.length === 0) + { return math.Rectangle.EMPTY; } @@ -365,10 +410,12 @@ var childVisible = false; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -386,7 +433,8 @@ maxY = maxY > childMaxY ? maxY : childMaxY; } - if (!childVisible) { + if (!childVisible) + { return math.Rectangle.EMPTY; } @@ -407,12 +455,14 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getLocalBounds = function () { +DisplayObjectContainer.prototype.getLocalBounds = function () +{ var matrixCache = this.worldTransform; this.worldTransform = math.Matrix.IDENTITY; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } @@ -428,13 +478,16 @@ * * @param renderer {WebGLRenderer} The renderer */ -DisplayObjectContainer.prototype.renderWebGL = function (renderer) { +DisplayObjectContainer.prototype.renderWebGL = function (renderer) +{ // if the object is not visible or the alpha is 0 then no need to render this element - if (!this.visible || this.alpha <= 0) { + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } @@ -442,14 +495,17 @@ var i, j; // do a quick check to see if this element has a mask or a filter. - if (this._mask || this._filters) { + if (this._mask || this._filters) + { // push filter first as we need to ensure the stencil buffer is correct for any masking - if (this._filters) { + if (this._filters) + { renderer.spriteBatch.flush(); renderer.filterManager.pushFilter(this._filterBlock); } - if (this._mask) { + if (this._mask) + { renderer.spriteBatch.stop(); renderer.maskManager.pushMask(this.mask, renderer); renderer.spriteBatch.start(); @@ -459,36 +515,42 @@ this._renderWebGL(renderer); // now loop through the children and make sure they get rendered - for (i = 0, j = this.children.length; i < j; i++) { + for (i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderWebGL(renderer); } // time to stop the sprite batch as either a mask element or a filter draw will happen next renderer.spriteBatch.stop(); - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(this._mask, renderer); } - if (this._filters) { + if (this._filters) + { renderer.filterManager.popFilter(); } renderer.spriteBatch.start(); } - else { + else + { this._renderWebGL(renderer); // simple render children! - for (i = 0, j = this.children.length; i < j; ++i) { + for (i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderWebGL(renderer); } } }; -DisplayObjectContainer.prototype._renderWebGL = function (renderer) { +DisplayObjectContainer.prototype._renderWebGL = function (renderer) +{ // this is where content itself gets renderd.. @@ -499,25 +561,31 @@ * * @param renderer {CanvasRenderer} The renderer */ -DisplayObjectContainer.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0) { +DisplayObjectContainer.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -528,13 +596,16 @@ * @param renderer {WebGLRenderer|CanvasRenderer} The renderer * @private */ -DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) { +DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) +{ this._cachedSprite.worldAlpha = this.worldAlpha; - if (renderer.gl) { + if (renderer.gl) + { this._cachedSprite.renderWebGL(renderer); } - else { + else + { this._cachedSprite.renderCanvas(renderer); } }; @@ -544,10 +615,12 @@ * * @private */ -DisplayObjectContainer.prototype._generateCachedSprite = function () { +DisplayObjectContainer.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { // TODO - RenderTexture now *requires* a renderer instance, so this is like broken // because `renderer` isn't actually in scope here :P var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0); @@ -555,7 +628,8 @@ this._cachedSprite = new Sprite(renderTexture); this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.texture.resize(bounds.width | 0, bounds.height | 0); } @@ -580,8 +654,10 @@ * * @private */ -DisplayObjectContainer.prototype._destroyCachedSprite = function () { - if (!this._cachedSprite) { +DisplayObjectContainer.prototype._destroyCachedSprite = function () +{ + if (!this._cachedSprite) + { return; } diff --git a/src/core/display/Sprite.js b/src/core/display/Sprite.js index 707da24..5862aef 100644 --- a/src/core/display/Sprite.js +++ b/src/core/display/Sprite.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param texture {Texture} The texture for this sprite */ -function Sprite(texture) { +function Sprite(texture) +{ DisplayObjectContainer.call(this); /** @@ -85,12 +86,14 @@ this.texture = texture || Texture.EMPTY; } -Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) { +Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) +{ DisplayObjectContainer.prototype.destroy.call(this); this.anchor = null; - if (destroyTexture) { + if (destroyTexture) + { this._texture.destroy(destroyBaseTexture); } @@ -111,10 +114,12 @@ * @memberof Sprite# */ width: { - get: function () { + get: function () + { return this.scale.x * this.texture.frame.width; }, - set: function (value) { + set: function (value) + { this.scale.x = value / this.texture.frame.width; this._width = value; } @@ -127,10 +132,12 @@ * @memberof Sprite# */ height: { - get: function () { + get: function () + { return this.scale.y * this.texture.frame.height; }, - set: function (value) { + set: function (value) + { this.scale.y = value / this.texture.frame.height; this._height = value; } @@ -143,23 +150,29 @@ * @memberof Sprite# */ texture: { - get: function () { + get: function () + { return this._texture; }, - set: function (value) { - if (this._texture === value) { + set: function (value) + { + if (this._texture === value) + { return; } this._texture = value; this.cachedTint = 0xFFFFFF; - if (value) { + if (value) + { // wait for the texture to load - if (value.baseTexture.hasLoaded) { + if (value.baseTexture.hasLoaded) + { this._onTextureUpdate(); } - else { + else + { value.once('update', this._onTextureUpdate.bind(this)); } } @@ -172,18 +185,22 @@ * * @private */ -Sprite.prototype._onTextureUpdate = function () { +Sprite.prototype._onTextureUpdate = function () +{ // so if _width is 0 then width was not set.. - if (this._width) { + if (this._width) + { this.scale.x = this._width / this.texture.frame.width; } - if (this._height) { + if (this._height) + { this.scale.y = this._height / this.texture.frame.height; } }; -Sprite.prototype._renderWebGL = function (renderer) { +Sprite.prototype._renderWebGL = function (renderer) +{ // this is where content gets renderd.. // watch this space for a little render state manager.. @@ -197,7 +214,8 @@ * @param matrix {Matrix} the transformation matrix of the sprite * @return {Rectangle} the framing rectangle */ -Sprite.prototype.getBounds = function (matrix) { +Sprite.prototype.getBounds = function (matrix) +{ var width = this.texture.frame.width; var height = this.texture.frame.height; @@ -224,11 +242,13 @@ if(b === 0 && c === 0) { // scale may be negative! - if (a < 0) { + if (a < 0) + { a *= -1; } - if (d < 0) { + if (d < 0) + { d *= -1; } @@ -293,28 +313,34 @@ * * @param renderer {CanvasRenderer} The renderer */ -Sprite.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) { +Sprite.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) + { return; } - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; renderer.context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } // Ignore null sources - if (this.texture.valid) { + if (this.texture.valid) + { var resolution = this.texture.baseTexture.resolution / renderer.resolution; renderer.context.globalAlpha = this.worldAlpha; // If smoothingEnabled is supported and we need to change the smoothing property for this texture - if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) { + if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) + { renderer.scaleMode = this.texture.baseTexture.scaleMode; renderer.context[renderer.smoothProperty] = (renderer.scaleMode === CONST.scaleModes.LINEAR); } @@ -324,7 +350,8 @@ var dy = (this.texture.trim ? this.texture.trim.y : 0) - (this.anchor.y * this.texture.trim.height); // Allow for pixel rounding - if (renderer.roundPixels) { + if (renderer.roundPixels) + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -337,7 +364,8 @@ dx = dx | 0; dy = dy | 0; } - else { + else + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -348,8 +376,10 @@ ); } - if (this.tint !== 0xFFFFFF) { - if (this.cachedTint !== this.tint) { + if (this.tint !== 0xFFFFFF) + { + if (this.cachedTint !== this.tint) + { this.cachedTint = this.tint; // TODO clean up caching - how to clean up the caches? @@ -368,7 +398,8 @@ this.texture.crop.height / resolution ); } - else { + else + { renderer.context.drawImage( this.texture.baseTexture.source, this.texture.crop.x, @@ -383,11 +414,13 @@ } } - for (var i = 0, j = this.children.length; i < j; i++) { + for (var i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -402,10 +435,12 @@ * @param frameId {String} The frame Id of the texture in the cache * @return {Sprite} A new Sprite using a texture from the texture cache matching the frameId */ -Sprite.fromFrame = function (frameId) { +Sprite.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache' + this); } @@ -420,6 +455,7 @@ * @param imageId {String} The image url of the texture * @return {Sprite} A new Sprite using a texture from the texture cache matching the image id */ -Sprite.fromImage = function (imageId, crossorigin, scaleMode) { +Sprite.fromImage = function (imageId, crossorigin, scaleMode) +{ return new Sprite(Texture.fromImage(imageId, crossorigin, scaleMode)); }; diff --git a/src/core/display/SpriteBatch.js b/src/core/display/SpriteBatch.js index 3187777..c196fef 100644 --- a/src/core/display/SpriteBatch.js +++ b/src/core/display/SpriteBatch.js @@ -12,7 +12,8 @@ * ```js * var container = new SpriteBatch(); * - * for(var i = 0; i < 100; ++i) { + * for(var i = 0; i < 100; ++i) + * { * var sprite = new PIXI.Sprite.fromImage("myImage.png"); * container.addChild(sprite); * } @@ -25,7 +26,8 @@ */ //TODO RENAME to PARTICLE CONTAINER? -function SpriteBatch() { +function SpriteBatch() +{ DisplayObjectContainer.call(this); } @@ -38,7 +40,8 @@ * * @private */ -SpriteBatch.prototype.updateTransform = function () { +SpriteBatch.prototype.updateTransform = function () +{ // TODO don't need to! this.displayObjectUpdateTransform(); // PIXI.DisplayObjectContainer.prototype.updateTransform.call( this ); @@ -50,8 +53,10 @@ * @param renderer {WebGLRenderer} The webgl renderer * @private */ -SpriteBatch.prototype.renderWebGL = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderWebGL = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -71,8 +76,10 @@ * @param renderer {CanvasRenderer} The canvas renderer * @private */ -SpriteBatch.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -84,10 +91,12 @@ this.displayObjectUpdateTransform(); - for (var i = 0; i < this.children.length; ++i) { + for (var i = 0; i < this.children.length; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -95,9 +104,11 @@ context.globalAlpha = this.worldAlpha * child.alpha; - if (child.rotation % (Math.PI * 2) === 0) { + if (child.rotation % (Math.PI * 2) === 0) + { // this is the fastest way to optimise! - if rotation is 0 then we can avoid any kind of setTransform call - if (isRotated) { + if (isRotated) + { context.setTransform( transform.a, transform.b, @@ -122,8 +133,10 @@ frame.height * child.scale.y ); } - else { - if (!isRotated) { + else + { + if (!isRotated) + { isRotated = true; } @@ -131,7 +144,8 @@ var childTransform = child.worldTransform; - if (renderer.roundPixels) { + if (renderer.roundPixels) + { context.setTransform( childTransform.a, childTransform.b, @@ -141,7 +155,8 @@ childTransform.ty | 0 ); } - else { + else + { context.setTransform( childTransform.a, childTransform.b, diff --git a/src/core/index.js b/src/core/index.js index 3954b6f..eb4a82b 100644 --- a/src/core/index.js +++ b/src/core/index.js @@ -58,11 +58,13 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRenderer: function (width, height, options, noWebGL) { + autoDetectRenderer: function (width, height, options, noWebGL) + { width = width || 800; height = height || 600; - if (!noWebGL && require('webgl-enabled')()) { + if (!noWebGL && require('webgl-enabled')()) + { return new core.WebGLRenderer(width, height, options); } @@ -87,7 +89,8 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRecommendedRenderer: function (width, height, options) { + autoDetectRecommendedRenderer: function (width, height, options) + { var isAndroid = /Android/i.test(navigator.userAgent); return core.autoDetectRenderer(width, height, options, isAndroid); diff --git a/src/core/math/Matrix.js b/src/core/math/Matrix.js index c2f87e2..2ff4848 100644 --- a/src/core/math/Matrix.js +++ b/src/core/math/Matrix.js @@ -10,7 +10,8 @@ * @class * @namespace PIXI */ -function Matrix() { +function Matrix() +{ /** * @member {number} * @default 1 @@ -63,7 +64,8 @@ * * @param array {number[]} The array that the matrix will be populated from. */ -Matrix.prototype.fromArray = function (array) { +Matrix.prototype.fromArray = function (array) +{ this.a = array[0]; this.b = array[1]; this.c = array[3]; @@ -78,14 +80,17 @@ * @param transpose {boolean} Whether we need to transpose the matrix or not * @return {number[]} the newly created array which contains the matrix */ -Matrix.prototype.toArray = function (transpose) { - if (!this.array) { +Matrix.prototype.toArray = function (transpose) +{ + if (!this.array) + { this.array = new Float32Array(9); } var array = this.array; - if (transpose) { + if (transpose) + { array[0] = this.a; array[1] = this.b; array[2] = 0; @@ -96,7 +101,8 @@ array[7] = this.ty; array[8] = 1; } - else { + else + { array[0] = this.a; array[1] = this.c; array[2] = this.tx; @@ -119,7 +125,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, transformed through this matrix */ -Matrix.prototype.apply = function (pos, newPos) { +Matrix.prototype.apply = function (pos, newPos) +{ newPos = newPos || new Point(); newPos.x = this.a * pos.x + this.c * pos.y + this.tx; @@ -136,7 +143,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, inverse-transformed through this matrix */ -Matrix.prototype.applyInverse = function (pos, newPos) { +Matrix.prototype.applyInverse = function (pos, newPos) +{ newPos = newPos || new Point(); var id = 1 / (this.a * this.d + this.c * -this.b); @@ -154,7 +162,8 @@ * @param {number} y * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.translate = function (x, y) { +Matrix.prototype.translate = function (x, y) +{ this.tx += x; this.ty += y; @@ -168,7 +177,8 @@ * @param {number} y The amount to scale vertically * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.scale = function (x, y) { +Matrix.prototype.scale = function (x, y) +{ this.a *= x; this.d *= y; this.c *= x; @@ -186,7 +196,8 @@ * @param {number} angle - The angle in radians. * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.rotate = function (angle) { +Matrix.prototype.rotate = function (angle) +{ var cos = Math.cos( angle ); var sin = Math.sin( angle ); @@ -210,7 +221,8 @@ * @param {Matrix} matrix * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.append = function (matrix) { +Matrix.prototype.append = function (matrix) +{ var a1 = this.a; var b1 = this.b; var c1 = this.c; @@ -232,7 +244,8 @@ * * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.identity = function () { +Matrix.prototype.identity = function () +{ this.a = 1; this.b = 0; this.c = 0; diff --git a/src/core/math/Point.js b/src/core/math/Point.js index 7565b2d..632f346 100644 --- a/src/core/math/Point.js +++ b/src/core/math/Point.js @@ -7,7 +7,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -function Point(x, y) { +function Point(x, y) +{ /** * @member {number} * @default 0 @@ -29,7 +30,8 @@ * * @return {Point} a copy of the point */ -Point.prototype.clone = function () { +Point.prototype.clone = function () +{ return new Point(this.x, this.y); }; @@ -40,7 +42,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -Point.prototype.set = function (x, y) { +Point.prototype.set = function (x, y) +{ this.x = x || 0; this.y = y || ( (y !== 0) ? this.x : 0 ) ; }; diff --git a/src/core/math/shapes/Circle.js b/src/core/math/shapes/Circle.js index 69cfdc9..4d76efc 100644 --- a/src/core/math/shapes/Circle.js +++ b/src/core/math/shapes/Circle.js @@ -10,7 +10,8 @@ * @param y {number} The Y coordinate of the center of this circle * @param radius {number} The radius of the circle */ -function Circle(x, y, radius) { +function Circle(x, y, radius) +{ /** * @member {number} * @default 0 @@ -46,7 +47,8 @@ * @method clone * @return {Circle} a copy of the Circle */ -Circle.prototype.clone = function () { +Circle.prototype.clone = function () +{ return new Circle(this.x, this.y, this.radius); }; @@ -58,8 +60,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Circle */ -Circle.prototype.contains = function (x, y) { - if (this.radius <= 0) { +Circle.prototype.contains = function (x, y) +{ + if (this.radius <= 0) + { return false; } @@ -79,6 +83,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Circle.prototype.getBounds = function () { +Circle.prototype.getBounds = function () +{ return new Rectangle(this.x - this.radius, this.y - this.radius, this.radius * 2, this.radius * 2); }; diff --git a/src/core/math/shapes/Ellipse.js b/src/core/math/shapes/Ellipse.js index 4f2d066..fefd01a 100644 --- a/src/core/math/shapes/Ellipse.js +++ b/src/core/math/shapes/Ellipse.js @@ -11,7 +11,8 @@ * @param width {number} The half width of this ellipse * @param height {number} The half height of this ellipse */ -function Ellipse(x, y, width, height) { +function Ellipse(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -53,7 +54,8 @@ * @method clone * @return {Ellipse} a copy of the ellipse */ -Ellipse.prototype.clone = function () { +Ellipse.prototype.clone = function () +{ return new Ellipse(this.x, this.y, this.width, this.height); }; @@ -65,8 +67,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coords are within this ellipse */ -Ellipse.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Ellipse.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } @@ -86,6 +90,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Ellipse.prototype.getBounds = function () { +Ellipse.prototype.getBounds = function () +{ return new Rectangle(this.x - this.width, this.y - this.height, this.width, this.height); }; diff --git a/src/core/math/shapes/Polygon.js b/src/core/math/shapes/Polygon.js index ae89148..fea6d37 100644 --- a/src/core/math/shapes/Polygon.js +++ b/src/core/math/shapes/Polygon.js @@ -10,16 +10,20 @@ * arguments passed can be flat x,y values e.g. `new Polygon(x,y, x,y, x,y, ...)` where `x` and `y` are * Numbers. */ -function Polygon(points) { +function Polygon(points) +{ //if points isn't an array, use arguments as the array - if (!(points instanceof Array)) { + if (!(points instanceof Array)) + { points = Array.prototype.slice.call(arguments); } //if this is a flat array of numbers, convert it to points - if (points[0] instanceof Point) { + if (points[0] instanceof Point) + { var p = []; - for (var i = 0, il = points.length; i < il; i++) { + for (var i = 0, il = points.length; i < il; i++) + { p.push(points[i].x, points[i].y); } @@ -51,7 +55,8 @@ * * @return {Polygon} a copy of the polygon */ -Polygon.prototype.clone = function () { +Polygon.prototype.clone = function () +{ return new Polygon(this.points.slice()); }; @@ -62,19 +67,22 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this polygon */ -Polygon.prototype.contains = function (x, y) { +Polygon.prototype.contains = function (x, y) +{ var inside = false; // use some raycasting to test hits // https://github.com/substack/point-in-polygon/blob/master/index.js var length = this.points.length / 2; - for (var i = 0, j = length - 1; i < length; j = i++) { + for (var i = 0, j = length - 1; i < length; j = i++) + { var xi = this.points[i * 2], yi = this.points[i * 2 + 1], xj = this.points[j * 2], yj = this.points[j * 2 + 1], intersect = ((yi > y) !== (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi); - if (intersect) { + if (intersect) + { inside = !inside; } } diff --git a/src/core/math/shapes/Rectangle.js b/src/core/math/shapes/Rectangle.js index 16ac62a..4008b68 100644 --- a/src/core/math/shapes/Rectangle.js +++ b/src/core/math/shapes/Rectangle.js @@ -10,7 +10,8 @@ * @param width {number} The overall width of this rectangle * @param height {number} The overall height of this rectangle */ -function Rectangle(x, y, width, height) { +function Rectangle(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -60,7 +61,8 @@ * * @return {Rectangle} a copy of the rectangle */ -Rectangle.prototype.clone = function () { +Rectangle.prototype.clone = function () +{ return new Rectangle(this.x, this.y, this.width, this.height); }; @@ -71,13 +73,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rectangle */ -Rectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Rectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/math/shapes/RoundedRectangle.js b/src/core/math/shapes/RoundedRectangle.js index 27d286e..7bf6411 100644 --- a/src/core/math/shapes/RoundedRectangle.js +++ b/src/core/math/shapes/RoundedRectangle.js @@ -11,7 +11,8 @@ * @param height {number} The overall height of this rounded rectangle * @param radius {number} Controls the radius of the rounded corners */ -function RoundedRectangle(x, y, width, height, radius) { +function RoundedRectangle(x, y, width, height, radius) +{ /** * @member {number} * @default 0 @@ -58,7 +59,8 @@ * * @return {RoundedRectangle} a copy of the rounded rectangle */ -RoundedRectangle.prototype.clone = function () { +RoundedRectangle.prototype.clone = function () +{ return new RoundedRectangle(this.x, this.y, this.width, this.height, this.radius); }; @@ -69,13 +71,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rounded Rectangle */ -RoundedRectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +RoundedRectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/primitives/Graphics.js b/src/core/primitives/Graphics.js index 261c534..e902d2a 100644 --- a/src/core/primitives/Graphics.js +++ b/src/core/primitives/Graphics.js @@ -16,7 +16,8 @@ * @extends DisplayObjectContainer * @namespace PIXI */ -function Graphics() { +function Graphics() +{ DisplayObjectContainer.call(this); this.renderable = true; @@ -154,16 +155,20 @@ * @private */ cacheAsBitmap: { - get: function () { + get: function () + { return this._cacheAsBitmap; }, - set: function (value) { + set: function (value) + { this._cacheAsBitmap = value; - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._generateCachedSprite(); } - else { + else + { this.destroyCachedSprite(); this.dirty = true; } @@ -176,7 +181,8 @@ * * @return {Graphics} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ var clone = new Graphics(); clone.renderable = this.renderable; @@ -192,7 +198,8 @@ clone.cachedSpriteDirty = this.cachedSpriteDirty; // copy graphics data - for (var i = 0; i < this.graphicsData.length; ++i) { + for (var i = 0; i < this.graphicsData.length; ++i) + { clone.graphicsData.push(this.graphicsData.clone()); } @@ -211,17 +218,21 @@ * @param alpha {number} alpha of the line to draw, will update the objects stored style * @return {Graphics} */ -Graphics.prototype.lineStyle = function (lineWidth, color, alpha) { +Graphics.prototype.lineStyle = function (lineWidth, color, alpha) +{ this.lineWidth = lineWidth || 0; this.lineColor = color || 0; this.lineAlpha = (arguments.length < 3) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length) + { // halfway through a line? start a new one! this.drawShape( new math.Polygon( this.currentPath.shape.points.slice(-2) )); } - else { + else + { // otherwise its empty so lets just set the line properties this.currentPath.lineWidth = this.lineWidth; this.currentPath.lineColor = this.lineColor; @@ -239,7 +250,8 @@ * @param y {number} the Y coordinate to move to * @return {Graphics} */ -Graphics.prototype.moveTo = function (x, y) { +Graphics.prototype.moveTo = function (x, y) +{ this.drawShape(new math.Polygon([x,y])); return this; @@ -253,7 +265,8 @@ * @param y {number} the Y coordinate to draw to * @return {Graphics} */ -Graphics.prototype.lineTo = function (x, y) { +Graphics.prototype.lineTo = function (x, y) +{ this.currentPath.shape.points.push(x, y); this.dirty = true; @@ -270,13 +283,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -285,7 +302,8 @@ n = 20, points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { this.moveTo(0, 0); } @@ -293,7 +311,8 @@ var fromY = points[points.length-1]; var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; xa = fromX + ( (cpX - fromX) * j ); @@ -319,13 +338,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -342,7 +365,8 @@ var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; dt = (1 - j); @@ -373,13 +397,17 @@ * @param radius {number} The radius of the arc * @return {Graphics} */ -Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points.push(x1, y1); } } - else { + else + { this.moveTo(x1, y1); } @@ -392,12 +420,15 @@ b2 = x2 - x1, mm = Math.abs(a1 * b2 - b1 * a2); - if (mm < 1.0e-8 || radius === 0) { - if (points[points.length-2] !== x1 || points[points.length-1] !== y1) { + if (mm < 1.0e-8 || radius === 0) + { + if (points[points.length-2] !== x1 || points[points.length-1] !== y1) + { points.push(x1, y1); } } - else { + else + { var dd = a1 * a1 + b1 * b1, cc = a2 * a2 + b2 * b2, tt = a1 * a2 + b1 * b2, @@ -433,42 +464,51 @@ * @param anticlockwise {boolean} Optional. Specifies whether the drawing should be counterclockwise or clockwise. False is default, and indicates clockwise, while true indicates counter-clockwise. * @return {Graphics} */ -Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) { +Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) +{ var startX = cx + Math.cos(startAngle) * radius; var startY = cy + Math.sin(startAngle) * radius; var points; // TODO - This if-else makes no sense. It uses currentPath in the else where it doesn't exist... - if (this.currentPath) { + if (this.currentPath) + { points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { points.push(startX, startY); } - else if (points[points.length-2] !== startX || points[points.length-1] !== startY) { + else if (points[points.length-2] !== startX || points[points.length-1] !== startY) + { points.push(startX, startY); } } - else { + else + { this.moveTo(startX, startY); points = this.currentPath.shape.points; } - if (startAngle === endAngle) { + if (startAngle === endAngle) + { return this; } - if (!anticlockwise && endAngle <= startAngle) { + if (!anticlockwise && endAngle <= startAngle) + { endAngle += Math.PI * 2; } - else if (anticlockwise && startAngle <= endAngle) { + else if (anticlockwise && startAngle <= endAngle) + { startAngle += Math.PI * 2; } var sweep = anticlockwise ? (startAngle - endAngle) *-1 : (endAngle - startAngle); var segs = (Math.abs(sweep)/ (Math.PI * 2)) * 40; - if (sweep === 0) { + if (sweep === 0) + { return this; } @@ -482,7 +522,8 @@ var remainder = ( segMinus % 1 ) / segMinus; - for (var i = 0; i <= segMinus; ++i) { + for (var i = 0; i <= segMinus; ++i) + { var real = i + remainder * i; var angle = ((theta) + startAngle + (theta2 * real)); @@ -506,13 +547,16 @@ * @param alpha {number} the alpha of the fill * @return {Graphics} */ -Graphics.prototype.beginFill = function (color, alpha) { +Graphics.prototype.beginFill = function (color, alpha) +{ this.filling = true; this.fillColor = color || 0; this.fillAlpha = (alpha === undefined) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length <= 2) + { this.currentPath.fill = this.filling; this.currentPath.fillColor = this.fillColor; this.currentPath.fillAlpha = this.fillAlpha; @@ -526,7 +570,8 @@ * * @return {Graphics} */ -Graphics.prototype.endFill = function () { +Graphics.prototype.endFill = function () +{ this.filling = false; this.fillColor = null; this.fillAlpha = 1; @@ -542,7 +587,8 @@ * @param height {number} The height of the rectangle * @return {Graphics} */ -Graphics.prototype.drawRect = function ( x, y, width, height ) { +Graphics.prototype.drawRect = function ( x, y, width, height ) +{ this.drawShape(new math.Rectangle(x,y, width, height)); return this; @@ -556,7 +602,8 @@ * @param height {number} The height of the rectangle * @param radius {number} Radius of the rectangle corners */ -Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) { +Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) +{ this.drawShape(new math.RoundedRectangle(x, y, width, height, radius)); return this; @@ -570,7 +617,8 @@ * @param radius {number} The radius of the circle * @return {Graphics} */ -Graphics.prototype.drawCircle = function (x, y, radius) { +Graphics.prototype.drawCircle = function (x, y, radius) +{ this.drawShape(new math.Circle(x,y, radius)); return this; @@ -585,7 +633,8 @@ * @param height {number} The half height of the ellipse * @return {Graphics} */ -Graphics.prototype.drawEllipse = function (x, y, width, height) { +Graphics.prototype.drawEllipse = function (x, y, width, height) +{ this.drawShape(new math.Ellipse(x, y, width, height)); return this; @@ -597,8 +646,10 @@ * @param path {Array} The path data used to construct the polygon. * @return {Graphics} */ -Graphics.prototype.drawPolygon = function (path) { - if (!(path instanceof Array)) { +Graphics.prototype.drawPolygon = function (path) +{ + if (!(path instanceof Array)) + { path = Array.prototype.slice.call(arguments); } @@ -612,7 +663,8 @@ * * @return {Graphics} */ -Graphics.prototype.clear = function () { +Graphics.prototype.clear = function () +{ this.lineWidth = 0; this.filling = false; @@ -631,7 +683,8 @@ * @param scaleMode {number} Should be one of the scaleMode consts * @return {Texture} a texture of the graphics object */ -Graphics.prototype.generateTexture = function (resolution, scaleMode) { +Graphics.prototype.generateTexture = function (resolution, scaleMode) +{ resolution = resolution || 1; var bounds = this.getBounds(); @@ -655,17 +708,21 @@ * * @param renderer {WebGLRenderer} */ -Graphics.prototype._renderWebGL = function (renderer) { +Graphics.prototype._renderWebGL = function (renderer) +{ // if the sprite is not visible or the alpha is 0 then no need to render this element - if (this.isMask === true) { + if (this.isMask === true) + { return; } // this code may still be needed so leaving for now.. - // + // /* - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture on the gpu too! @@ -681,17 +738,24 @@ return; } - */ - - // check if the webgl graphic needs to be updated - if (this.glDirty) { - this.dirty = true; - this.glDirty = false; - } + else */ - renderer.setObjectRendererer(renderer.graphicsRenderer); - renderer.graphicsRenderer.render(this); + renderer.spriteBatch.stop(); + renderer.blendModeManager.setBlendMode(this.blendMode); + // check blend mode + renderer.blendModeManager.setBlendMode( this.blendMode ); + + // check if the webgl graphic needs to be updated + if (this.glDirty) + { + this.dirty = true; + this.glDirty = false; + } + + WebGLGraphics.renderGraphics(this, renderer); + + renderer.spriteBatch.start(); }; /** @@ -700,14 +764,18 @@ * @param renderer {CanvasRenderer} * @private */ -Graphics.prototype.renderCanvas = function (renderer) { +Graphics.prototype.renderCanvas = function (renderer) +{ // 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.isMask === true) { + if (!this.visible || this.alpha <= 0 || this.isMask === true) + { return; } - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture @@ -723,16 +791,19 @@ return; } - else { + else + { var context = renderer.context; var transform = this.worldTransform; - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } @@ -748,11 +819,13 @@ CanvasGraphics.renderGraphics(this, context); - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } } @@ -763,13 +836,16 @@ * * @return {Rectangle} the rectangular bounding area */ -Graphics.prototype.getBounds = function (matrix) { +Graphics.prototype.getBounds = function (matrix) +{ // return an empty object if the item is a mask! - if (this.isMask) { + if (this.isMask) + { return math.Rectangle.EMPTY; } - if (this.dirty) { + if (this.dirty) + { this.updateLocalBounds(); this.glDirty = true; @@ -841,23 +917,27 @@ * Update the bounds of the object * */ -Graphics.prototype.updateLocalBounds = function () { +Graphics.prototype.updateLocalBounds = function () +{ var minX = Infinity; var maxX = -Infinity; var minY = Infinity; var maxY = -Infinity; - if (this.graphicsData.length) { + if (this.graphicsData.length) + { var shape, points, x, y, w, h; - for (var i = 0; i < this.graphicsData.length; i++) { + for (var i = 0; i < this.graphicsData.length; i++) + { var data = this.graphicsData[i]; var type = data.type; var lineWidth = data.lineWidth; shape = data.shape; - if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) { + if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) + { x = shape.x - lineWidth/2; y = shape.y - lineWidth/2; w = shape.width + lineWidth; @@ -869,7 +949,8 @@ minY = y < minY ? y : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.CIRC) { + else if (type === CONST.SHAPES.CIRC) + { x = shape.x; y = shape.y; w = shape.radius + lineWidth/2; @@ -881,7 +962,8 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.ELIP) { + else if (type === CONST.SHAPES.ELIP) + { x = shape.x; y = shape.y; w = shape.width + lineWidth/2; @@ -893,11 +975,13 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else { + else + { // POLY points = shape.points; - for (var j = 0; j < points.length; j += 2) { + for (var j = 0; j < points.length; j += 2) + { x = points[j]; y = points[j+1]; @@ -910,7 +994,8 @@ } } } - else { + else + { minX = 0; maxX = 0; minY = 0; @@ -931,10 +1016,12 @@ * * @private */ -Graphics.prototype._generateCachedSprite = function () { +Graphics.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { var canvasBuffer = new CanvasBuffer(bounds.width, bounds.height); var texture = Texture.fromCanvas(canvasBuffer.canvas); @@ -943,7 +1030,8 @@ this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.buffer.resize(bounds.width, bounds.height); } @@ -968,7 +1056,8 @@ * * @private */ -Graphics.prototype.updateCachedSpriteTexture = function () { +Graphics.prototype.updateCachedSpriteTexture = function () +{ var cachedSprite = this._cachedSprite; var texture = cachedSprite.texture; var canvas = cachedSprite.buffer.canvas; @@ -989,7 +1078,8 @@ * Destroys a previous cached sprite. * */ -Graphics.prototype.destroyCachedSprite = function () { +Graphics.prototype.destroyCachedSprite = function () +{ this._cachedSprite.texture.destroy(true); // let the gc collect the unused sprite @@ -1003,10 +1093,13 @@ * @param {Circle|Rectangle|Ellipse|Line|Polygon} shape The Shape object to draw. * @return {GraphicsData} The generated GraphicsData object. */ -Graphics.prototype.drawShape = function (shape) { - if (this.currentPath) { +Graphics.prototype.drawShape = function (shape) +{ + if (this.currentPath) + { // check current path! - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath.shape.points.length <= 2) + { this.graphicsData.pop(); } } @@ -1017,7 +1110,8 @@ this.graphicsData.push(data); - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { data.shape.closed = this.filling; this.currentPath = data; } diff --git a/src/core/primitives/GraphicsData.js b/src/core/primitives/GraphicsData.js index 99decbe..788f6f2 100644 --- a/src/core/primitives/GraphicsData.js +++ b/src/core/primitives/GraphicsData.js @@ -4,7 +4,8 @@ * @class * @namespace PIXI */ -function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) { +function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) +{ this.lineWidth = lineWidth; this.lineColor = lineColor; this.lineAlpha = lineAlpha; @@ -27,7 +28,8 @@ * * @return {GraphicsData} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ return new GraphicsData( this.lineWidth, this.lineColor, diff --git a/src/core/renderers/canvas/CanvasRenderer.js b/src/core/renderers/canvas/CanvasRenderer.js index 15a0978..7aebd44 100644 --- a/src/core/renderers/canvas/CanvasRenderer.js +++ b/src/core/renderers/canvas/CanvasRenderer.js @@ -17,17 +17,22 @@ * @param [options.resolution=1] {number} the resolution of the renderer retina would be 2 * @param [options.clearBeforeRender=true] {boolean} This sets if the CanvasRenderer will clear the canvas or not before the new render pass. */ -function CanvasRenderer(width, height, options) { +function CanvasRenderer(width, height, options) +{ utils.sayHello('Canvas'); - if (options) { - for (var i in CONST.defaultRenderOptions) { - if (typeof options[i] === 'undefined') { + if (options) + { + for (var i in CONST.defaultRenderOptions) + { + if (typeof options[i] === 'undefined') + { options[i] = CONST.defaultRenderOptions[i]; } } } - else { + else + { options = CONST.defaultRenderOptions; } @@ -156,19 +161,24 @@ this.smoothProperty = null; - if (this.context.imageSmoothingEnabled) { + if (this.context.imageSmoothingEnabled) + { this.smoothProperty = 'imageSmoothingEnabled'; } - else if (this.context.webkitImageSmoothingEnabled) { + else if (this.context.webkitImageSmoothingEnabled) + { this.smoothProperty = 'webkitImageSmoothingEnabled'; } - else if (this.context.mozImageSmoothingEnabled) { + else if (this.context.mozImageSmoothingEnabled) + { this.smoothProperty = 'mozImageSmoothingEnabled'; } - else if (this.context.oImageSmoothingEnabled) { + else if (this.context.oImageSmoothingEnabled) + { this.smoothProperty = 'oImageSmoothingEnabled'; } - else if (this.context.msImageSmoothingEnabled) { + else if (this.context.msImageSmoothingEnabled) + { this.smoothProperty = 'msImageSmoothingEnabled'; } @@ -193,10 +203,12 @@ * @memberof CanvasRenderer# */ backgroundColor: { - get: function () { + get: function () + { return this._backgroundColor; }, - set: function (val) { + set: function (val) + { this._backgroundColor = val; this._backgroundColorString = utils.hex2string(val); } @@ -208,7 +220,8 @@ * * @param object {DisplayObject} the object to be rendered */ -CanvasRenderer.prototype.render = function (object) { +CanvasRenderer.prototype.render = function (object) +{ object.updateTransform(); this.context.setTransform(1,0,0,1,0,0); @@ -218,16 +231,20 @@ this.currentBlendMode = CONST.blendModes.NORMAL; this.context.globalCompositeOperation = this.blendModes[CONST.blendModes.NORMAL]; - if (navigator.isCocoonJS && this.view.screencanvas) { + if (navigator.isCocoonJS && this.view.screencanvas) + { this.context.fillStyle = 'black'; this.context.clear(); } - if (this.clearBeforeRender) { - if (this.transparent) { + if (this.clearBeforeRender) + { + if (this.transparent) + { this.context.clearRect(0, 0, this.width, this.height); } - else { + else + { this.context.fillStyle = this._backgroundColorString; this.context.fillRect(0, 0, this.width , this.height); } @@ -241,8 +258,10 @@ * * @param [removeView=false] {boolean} Removes the Canvas element from the DOM. */ -CanvasRenderer.prototype.destroy = function (removeView) { - if (removeView && this.view.parent) { +CanvasRenderer.prototype.destroy = function (removeView) +{ + if (removeView && this.view.parent) + { this.view.parent.removeChild(this.view); } @@ -257,14 +276,16 @@ * @param width {number} the new width of the canvas view * @param height {number} the new height of the canvas view */ -CanvasRenderer.prototype.resize = function (width, height) { +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) { + if (this.autoResize) + { this.view.style.width = this.width / this.resolution + 'px'; this.view.style.height = this.height / this.resolution + 'px'; } @@ -276,7 +297,8 @@ * @param displayObject {DisplayObject} The displayObject to render * @private */ -CanvasRenderer.prototype.renderDisplayObject = function (displayObject) { +CanvasRenderer.prototype.renderDisplayObject = function (displayObject) +{ displayObject.renderCanvas(this); }; @@ -285,11 +307,14 @@ * * @private */ -CanvasRenderer.prototype._mapBlendModes = function () { - if (!this.blendModes) { +CanvasRenderer.prototype._mapBlendModes = function () +{ + if (!this.blendModes) + { this.blendModes = {}; - if (utils.canUseNewCanvasBlendModes()) { + if (utils.canUseNewCanvasBlendModes()) + { this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? this.blendModes[CONST.blendModes.MULTIPLY] = 'multiply'; @@ -308,7 +333,8 @@ this.blendModes[CONST.blendModes.COLOR] = 'color'; this.blendModes[CONST.blendModes.LUMINOSITY] = 'luminosity'; } - else { + else + { // this means that the browser does not support the cool new blend modes in canvas 'cough' ie 'cough' this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? diff --git a/src/core/renderers/canvas/utils/CanvasBuffer.js b/src/core/renderers/canvas/utils/CanvasBuffer.js index ebe5d47..b183a66 100644 --- a/src/core/renderers/canvas/utils/CanvasBuffer.js +++ b/src/core/renderers/canvas/utils/CanvasBuffer.js @@ -6,7 +6,8 @@ * @param width {number} the width for the newly created canvas * @param height {number} the height for the newly created canvas */ -function CanvasBuffer(width, height) { +function CanvasBuffer(width, height) +{ /** * The Canvas object that belongs to this CanvasBuffer. * @@ -36,10 +37,12 @@ * @memberof CanvasBuffer# */ width: { - get: function () { + get: function () + { return this.canvas.width; }, - set: function (val) { + set: function (val) + { this.canvas.width = val; } }, @@ -50,10 +53,12 @@ * @memberof CanvasBuffer# */ height: { - get: function () { + get: function () + { return this.canvas.height; }, - set: function (val) { + set: function (val) + { this.canvas.height = val; } } @@ -64,7 +69,8 @@ * * @private */ -CanvasBuffer.prototype.clear = function () { +CanvasBuffer.prototype.clear = function () +{ this.context.setTransform(1, 0, 0, 1, 0, 0); this.context.clearRect(0,0, this.canvas.width, this.canvas.height); }; @@ -75,7 +81,8 @@ * @param width {number} the new width of the canvas * @param height {number} the new height of the canvas */ -CanvasBuffer.prototype.resize = function (width, height) { +CanvasBuffer.prototype.resize = function (width, height) +{ this.canvas.width = width; this.canvas.height = height; }; diff --git a/src/core/renderers/canvas/utils/CanvasGraphics.js b/src/core/renderers/canvas/utils/CanvasGraphics.js index c7eaa2a..3f2a91f 100644 --- a/src/core/renderers/canvas/utils/CanvasGraphics.js +++ b/src/core/renderers/canvas/utils/CanvasGraphics.js @@ -13,15 +13,18 @@ * @param graphics {Graphics} the actual graphics object to render * @param context {CanvasRenderingContext2D} the 2d drawing method of the canvas */ -CanvasGraphics.renderGraphics = function (graphics, context) { +CanvasGraphics.renderGraphics = function (graphics, context) +{ var worldAlpha = graphics.worldAlpha; - if (graphics.dirty) { + if (graphics.dirty) + { this.updateGraphicsTint(graphics); graphics.dirty = false; } - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; @@ -30,69 +33,82 @@ context.lineWidth = data.lineWidth; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { context.beginPath(); var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } - if (shape.closed) { + if (shape.closed) + { context.lineTo(points[0], points[1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fillRect(shape.x, shape.y, shape.width, shape.height); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.strokeRect(shape.x, shape.y, shape.width, shape.height); } } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.beginPath(); context.arc(shape.x, shape.y, shape.radius,0,2*Math.PI); context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas var w = shape.width * 2; @@ -119,18 +135,21 @@ context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; var width = shape.width; @@ -152,13 +171,15 @@ context.quadraticCurveTo(rx, ry, rx, ry + radius); context.closePath(); - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); @@ -174,45 +195,54 @@ * @param graphics {Graphics} the graphics which will be used as a mask * @param context {CanvasRenderingContext2D} the context 2d method of the canvas */ -CanvasGraphics.renderGraphicsMask = function (graphics, context) { +CanvasGraphics.renderGraphicsMask = function (graphics, context) +{ var len = graphics.graphicsData.length; - if (len === 0) { + if (len === 0) + { return; } context.beginPath(); - for (var i = 0; i < len; i++) { + for (var i = 0; i < len; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { context.rect(shape.x, shape.y, shape.width, shape.height); context.closePath(); } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.arc(shape.x, shape.y, shape.radius, 0, 2 * Math.PI); context.closePath(); } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas @@ -237,7 +267,8 @@ context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); context.closePath(); } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; @@ -262,8 +293,10 @@ } }; -CanvasGraphics.updateGraphicsTint = function (graphics) { - if (graphics.tint === 0xFFFFFF) { +CanvasGraphics.updateGraphicsTint = function (graphics) +{ + if (graphics.tint === 0xFFFFFF) + { return; } @@ -271,7 +304,8 @@ var tintG = (graphics.tint >> 8 & 0xFF) / 255; var tintB = (graphics.tint & 0xFF)/ 255; - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var fillColor = data.fillColor | 0; diff --git a/src/core/renderers/canvas/utils/CanvasMaskManager.js b/src/core/renderers/canvas/utils/CanvasMaskManager.js index e04a733..9827d36 100644 --- a/src/core/renderers/canvas/utils/CanvasMaskManager.js +++ b/src/core/renderers/canvas/utils/CanvasMaskManager.js @@ -6,7 +6,8 @@ * @class * @namespace PIXI */ -function CanvasMaskManager() {} +function CanvasMaskManager() +{} CanvasMaskManager.prototype.constructor = CanvasMaskManager; module.exports = CanvasMaskManager; @@ -17,7 +18,8 @@ * @param maskData {object} the maskData that will be pushed * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.pushMask = function (maskData, renderer) { +CanvasMaskManager.prototype.pushMask = function (maskData, renderer) +{ renderer.context.save(); var cacheAlpha = maskData.alpha; @@ -45,6 +47,7 @@ * * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.popMask = function (renderer) { +CanvasMaskManager.prototype.popMask = function (renderer) +{ renderer.context.restore(); }; diff --git a/src/core/renderers/canvas/utils/CanvasTinter.js b/src/core/renderers/canvas/utils/CanvasTinter.js index 17e0529..d2fb1bc 100644 --- a/src/core/renderers/canvas/utils/CanvasTinter.js +++ b/src/core/renderers/canvas/utils/CanvasTinter.js @@ -14,7 +14,8 @@ * @param color {number} the color to use to tint the sprite with * @return {HTMLCanvasElement} The tinted canvas */ -CanvasTinter.getTintedTexture = function (sprite, color) { +CanvasTinter.getTintedTexture = function (sprite, color) +{ var texture = sprite.texture; color = CanvasTinter.roundColor(color); @@ -23,7 +24,8 @@ texture.tintCache = texture.tintCache || {}; - if (texture.tintCache[stringColor]) { + if (texture.tintCache[stringColor]) + { return texture.tintCache[stringColor]; } @@ -33,14 +35,16 @@ //CanvasTinter.tintWithPerPixel(texture, stringColor, canvas); CanvasTinter.tintMethod(texture, color, canvas); - if (CanvasTinter.convertTintToImage) { + if (CanvasTinter.convertTintToImage) + { // is this better? var tintImage = new Image(); tintImage.src = canvas.toDataURL(); texture.tintCache[stringColor] = tintImage; } - else { + else + { texture.tintCache[stringColor] = canvas; // if we are not converting the texture to an image then we need to lose the reference to the canvas CanvasTinter.canvas = null; @@ -56,7 +60,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithMultiply = function (texture, color, canvas) { +CanvasTinter.tintWithMultiply = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -104,7 +109,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithOverlay = function (texture, color, canvas) { +CanvasTinter.tintWithOverlay = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -139,7 +145,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithPerPixel = function (texture, color, canvas) { +CanvasTinter.tintWithPerPixel = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -167,7 +174,8 @@ var pixels = pixelData.data; - for (var i = 0; i < pixels.length; i += 4) { + for (var i = 0; i < pixels.length; i += 4) + { pixels[i+0] *= r; pixels[i+1] *= g; pixels[i+2] *= b; @@ -181,7 +189,8 @@ * * @param color {number} the color to round, should be a hex color */ -CanvasTinter.roundColor = function (color) { +CanvasTinter.roundColor = function (color) +{ var step = CanvasTinter.cacheStepsPerColorChannel; var rgbValues = utils.hex2rgb(color); diff --git a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js index 9f2f89a..35edbaf 100644 --- a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js +++ b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLBlendModeManager(renderer) { +function WebGLBlendModeManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -23,8 +24,10 @@ * * @param blendMode {number} the blendMode, should be a Pixi const, such as BlendModes.ADD */ -WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) { - if (this.currentBlendMode === blendMode) { +WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) +{ + if (this.currentBlendMode === blendMode) + { return false; } diff --git a/src/core/renderers/webgl/managers/WebGLFilterManager.js b/src/core/renderers/webgl/managers/WebGLFilterManager.js index 1179258..2dac048 100644 --- a/src/core/renderers/webgl/managers/WebGLFilterManager.js +++ b/src/core/renderers/webgl/managers/WebGLFilterManager.js @@ -7,7 +7,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLFilterManager(renderer) { +function WebGLFilterManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -32,7 +33,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.texturePool.length = 0; self.initShaderBuffers(); }); @@ -46,7 +48,8 @@ * @param renderer {WebGLRenderer} * @param buffer {ArrayBuffer} */ -WebGLFilterManager.prototype.begin = function (buffer) { +WebGLFilterManager.prototype.begin = function (buffer) +{ this.defaultShader = this.renderer.shaderManager.defaultShader; this.width = this.renderer.projection.x * 2; @@ -60,7 +63,8 @@ * * @param filterBlock {object} the filter that will be pushed to the current filter stack */ -WebGLFilterManager.prototype.pushFilter = function (filterBlock) { +WebGLFilterManager.prototype.pushFilter = function (filterBlock) +{ var gl = this.renderer.gl; var projection = this.renderer.projection; @@ -78,10 +82,12 @@ this.offsetY += filterBlock._filterArea.y; var texture = this.texturePool.pop(); - if (!texture) { + if (!texture) + { texture = new FilterTexture(this.renderer.gl, this.width, this.height); } - else { + else + { texture.resize(this.width, this.height); } @@ -98,29 +104,35 @@ var localX = filterArea.x, localY = filterArea.y; - if (filterArea.x < 0) { + if (filterArea.x < 0) + { filterArea.width += filterArea.x; filterArea.x = 0; } - if (filterArea.y < 0) { + if (filterArea.y < 0) + { filterArea.height += filterArea.y; filterArea.y = 0; } - if (localX + filterArea.width > this.width) { + if (localX + filterArea.width > this.width) + { filterArea.width = this.width - localX; } - if (localY + filterArea.height > this.height) { + if (localY + filterArea.height > this.height) + { filterArea.height = this.height - localY; } - if (filterArea.width < 0) { + if (filterArea.width < 0) + { filterArea.width = 0; } - if (filterArea.height < 0) { + if (filterArea.height < 0) + { filterArea.height = 0; } @@ -154,7 +166,8 @@ * Removes the last filter from the filter stack and doesn't return it. * */ -WebGLFilterManager.prototype.popFilter = function () { +WebGLFilterManager.prototype.popFilter = function () +{ var gl = this.renderer.gl; var filterBlock = this.filterStack.pop(); @@ -163,7 +176,8 @@ var projection = this.renderer.projection; var offset = this.renderer.offset; - if (filterBlock.filterPasses.length > 1) { + if (filterBlock.filterPasses.length > 1) + { gl.viewport(0, 0, filterArea.width, filterArea.height); gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); @@ -193,7 +207,8 @@ var inputTexture = texture; var outputTexture = this.texturePool.pop(); - if (!outputTexture) { + if (!outputTexture) + { outputTexture = new FilterTexture(this.renderer.gl, this.width, this.height); } outputTexture.resize(this.width, this.height); @@ -204,7 +219,8 @@ gl.disable(gl.BLEND); - for (var i = 0; i < filterBlock.filterPasses.length-1; i++) { + for (var i = 0; i < filterBlock.filterPasses.length-1; i++) + { var filterPass = filterBlock.filterPasses[i]; gl.bindFramebuffer(gl.FRAMEBUFFER, outputTexture.frameBuffer ); @@ -243,10 +259,12 @@ var buffer = this.buffer; // time to render the filters texture to the previous scene - if (this.filterStack.length === 0) { + if (this.filterStack.length === 0) + { gl.colorMask(true, true, true, true);//this.transparent); } - else { + else + { var currentFilter = this.filterStack[this.filterStack.length-1]; filterArea = currentFilter._filterArea; @@ -332,13 +350,15 @@ * @param width {number} the horizontal range of the filter * @param height {number} the vertical range of the filter */ -WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) { +WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) +{ // use program var gl = this.renderer.gl; var shader = filter.shaders[gl.id]; - if (!shader) { + if (!shader) + { shader = new Shader(gl); shader.fragmentSrc = filter.fragmentSrc; @@ -356,7 +376,8 @@ gl.uniform2f(shader.projectionVector, width/2, -height/2); gl.uniform2f(shader.offsetVector, 0,0); - if (filter.uniforms.dimensions) { + 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]; @@ -386,7 +407,8 @@ * Initialises the shader buffers. * */ -WebGLFilterManager.prototype.initShaderBuffers = function () { +WebGLFilterManager.prototype.initShaderBuffers = function () +{ var gl = this.renderer.gl; // create some buffers @@ -432,7 +454,8 @@ * Destroys the filter and removes it from the filter stack. * */ -WebGLFilterManager.prototype.destroy = function () { +WebGLFilterManager.prototype.destroy = function () +{ var gl = this.renderer.gl; this.filterStack = null; @@ -441,7 +464,8 @@ this.offsetY = 0; // destroy textures - for (var i = 0; i < this.texturePool.length; i++) { + for (var i = 0; i < this.texturePool.length; i++) + { this.texturePool[i].destroy(); } diff --git a/src/core/renderers/webgl/managers/WebGLManager.js b/src/core/renderers/webgl/managers/WebGLManager.js index 9d47b5c..c30cd51 100644 --- a/src/core/renderers/webgl/managers/WebGLManager.js +++ b/src/core/renderers/webgl/managers/WebGLManager.js @@ -3,7 +3,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLManager(renderer) { +function WebGLManager(renderer) +{ /** * The renderer this manager works for. * @@ -15,6 +16,7 @@ WebGLManager.prototype.constructor = WebGLManager; module.exports = WebGLManager; -WebGLManager.prototype.destroy = function () { +WebGLManager.prototype.destroy = function () +{ this.renderer = null; }; diff --git a/src/core/renderers/webgl/managers/WebGLMaskManager.js b/src/core/renderers/webgl/managers/WebGLMaskManager.js index 2f90b64..e568812 100644 --- a/src/core/renderers/webgl/managers/WebGLMaskManager.js +++ b/src/core/renderers/webgl/managers/WebGLMaskManager.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLMaskManager(renderer) { +function WebGLMaskManager(renderer) +{ WebGLManager.call(this, renderer); } @@ -19,12 +20,15 @@ * * @param maskData {any[]} */ -WebGLMaskManager.prototype.pushMask = function (maskData) { - if (maskData.dirty) { +WebGLMaskManager.prototype.pushMask = function (maskData) +{ + if (maskData.dirty) + { WebGLGraphics.updateGraphics(maskData, this.renderer.gl); } - if (!maskData._webGL[this.renderer.gl.id].data.length) { + if (!maskData._webGL[this.renderer.gl.id].data.length) + { return; } @@ -36,6 +40,7 @@ * * @param maskData {any[]} */ -WebGLMaskManager.prototype.popMask = function (maskData) { +WebGLMaskManager.prototype.popMask = function (maskData) +{ this.renderer.stencilManager.popStencil(maskData, maskData._webGL[this.renderer.gl.id].data[0], this.renderer); }; diff --git a/src/core/renderers/webgl/managers/WebGLShaderManager.js b/src/core/renderers/webgl/managers/WebGLShaderManager.js index fef071c..90c6477 100644 --- a/src/core/renderers/webgl/managers/WebGLShaderManager.js +++ b/src/core/renderers/webgl/managers/WebGLShaderManager.js @@ -10,7 +10,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLShaderManager(renderer) { +function WebGLShaderManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -28,7 +29,8 @@ */ this.tempAttribState = []; - for (var i = 0; i < this.maxAttibs; i++) { + for (var i = 0; i < this.maxAttibs; i++) + { this.attribState[i] = false; } @@ -66,7 +68,8 @@ // listen for context and update necessary shaders var self = this; - this.renderer.on('context', function (event) { + this.renderer.on('context', function (event) + { var gl = event.data; // this shader is used for rendering primitives @@ -97,29 +100,36 @@ * * @param attribs {Array} attribs */ -WebGLShaderManager.prototype.setAttribs = function (attribs) { +WebGLShaderManager.prototype.setAttribs = function (attribs) +{ // reset temp state var i; - for (i = 0; i < this.tempAttribState.length; i++) { + for (i = 0; i < this.tempAttribState.length; i++) + { this.tempAttribState[i] = false; } // set the new attribs - for (var a in attribs) { + for (var a in attribs) + { this.tempAttribState[attribs[a]] = true; } var gl = this.renderer.gl; - for (i = 0; i < this.attribState.length; i++) { - if (this.attribState[i] !== this.tempAttribState[i]) { + for (i = 0; i < this.attribState.length; i++) + { + if (this.attribState[i] !== this.tempAttribState[i]) + { this.attribState[i] = this.tempAttribState[i]; - if (this.attribState[i]) { + if (this.attribState[i]) + { gl.enableVertexAttribArray(i); } - else { + else + { gl.disableVertexAttribArray(i); } } @@ -131,8 +141,10 @@ * * @param shader {Any} */ -WebGLShaderManager.prototype.setShader = function (shader) { - if (this._currentId === shader.uuid) { +WebGLShaderManager.prototype.setShader = function (shader) +{ + if (this._currentId === shader.uuid) + { return false; } @@ -150,7 +162,8 @@ * Destroys this object. * */ -WebGLShaderManager.prototype.destroy = function () { +WebGLShaderManager.prototype.destroy = function () +{ this.attribState = null; this.tempAttribState = null; diff --git a/src/core/renderers/webgl/managers/WebGLStencilManager.js b/src/core/renderers/webgl/managers/WebGLStencilManager.js index 9ec6398..4cb0134 100644 --- a/src/core/renderers/webgl/managers/WebGLStencilManager.js +++ b/src/core/renderers/webgl/managers/WebGLStencilManager.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLStencilManager(renderer) { +function WebGLStencilManager(renderer) +{ WebGLManager.call(this, renderer); this.stencilStack = []; @@ -24,12 +25,14 @@ * @param graphics {Graphics} * @param webGLData {any[]} */ -WebGLStencilManager.prototype.pushStencil = function (graphics, webGLData) { +WebGLStencilManager.prototype.pushStencil = function (graphics, webGLData) +{ var gl = this.renderer.gl; this.bindGraphics(graphics, webGLData, this.renderer); - if (this.stencilStack.length === 0) { + if (this.stencilStack.length === 0) + { gl.enable(gl.STENCIL_TEST); gl.clear(gl.STENCIL_BUFFER_BIT); this.reverse = true; @@ -47,14 +50,17 @@ // draw the triangle strip! - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } @@ -62,31 +68,38 @@ // draw a quad to increment.. gl.drawElements(gl.TRIANGLE_FAN, 4, gl.UNSIGNED_SHORT, ( webGLData.indices.length - 4 ) * 2 ); - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); } this.reverse = !this.reverse; } - else { - if (!this.reverse) { + else + { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } - else { + 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) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); } } @@ -103,7 +116,8 @@ * @param graphics {Graphics} * @param webGLData {Array} */ -WebGLStencilManager.prototype.bindGraphics = function (graphics, webGLData) { +WebGLStencilManager.prototype.bindGraphics = function (graphics, webGLData) +{ //if (this._currentGraphics === graphics)return; this._currentGraphics = graphics; @@ -114,7 +128,8 @@ offset = this.renderer.offset, shader;// = this.renderer.shaderManager.primitiveShader; - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { shader = this.renderer.shaderManager.complexPrimitiveShader; this.renderer.shaderManager.setShader(shader); @@ -141,7 +156,8 @@ // set the index buffer! gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, webGLData.indexBuffer); } - else { + else + { //this.renderer.shaderManager.activatePrimitiveShader(); shader = this.renderer.shaderManager.primitiveShader; this.renderer.shaderManager.setShader( shader ); @@ -154,7 +170,7 @@ gl.uniform2f(shader.uniforms.offsetVector._location, -offset.x, -offset.y); gl.uniform3fv(shader.uniforms.tint._location, utils.hex2rgb(graphics.tint)); - + gl.uniform1f(shader.uniforms.alpha._location, graphics.worldAlpha); @@ -172,19 +188,22 @@ * @param graphics {Graphics} * @param webGLData {Array} */ -WebGLStencilManager.prototype.popStencil = function (graphics, webGLData) { +WebGLStencilManager.prototype.popStencil = function (graphics, webGLData) +{ var gl = this.renderer.gl; this.stencilStack.pop(); this.count--; - if (this.stencilStack.length === 0) { + if (this.stencilStack.length === 0) + { // the stack is empty! gl.disable(gl.STENCIL_TEST); } - else { + else + { var level = this.count; @@ -192,14 +211,17 @@ gl.colorMask(false, false, false, false); - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { this.reverse = !this.reverse; - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } @@ -213,31 +235,38 @@ // draw the triangle strip! gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); - if (!this.reverse) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); } } - else { + else + { // console.log("<<>>") - if (!this.reverse) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } - else { + 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) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); } } @@ -253,7 +282,8 @@ * Destroys the mask stack. * */ -WebGLStencilManager.prototype.destroy = function () { +WebGLStencilManager.prototype.destroy = function () +{ this.renderer = null; this.stencilStack = null; }; diff --git a/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js b/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js index 913ba5e..1ea7d19 100644 --- a/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js +++ b/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function ComplexPrimitiveShader(gl) { +function ComplexPrimitiveShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -24,7 +25,8 @@ 'uniform float flipY;', 'varying vec4 vColor;', - 'void main(void) {', + '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);', @@ -37,7 +39,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = vColor;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/FastShader.js b/src/core/renderers/webgl/shaders/FastShader.js index bd2e29a..2e5e060 100644 --- a/src/core/renderers/webgl/shaders/FastShader.js +++ b/src/core/renderers/webgl/shaders/FastShader.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function FastShader(gl) { +function FastShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -28,7 +29,8 @@ 'const vec2 center = vec2(-1.0, 1.0);', - 'void main(void) {', + 'void main(void) + {', ' vec2 v;', ' vec2 sv = aVertexPosition * aScale;', ' v.x = (sv.x) * cos(aRotation) - (sv.y) * sin(aRotation);', @@ -49,7 +51,8 @@ 'uniform sampler2D uSampler;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/PrimitiveShader.js b/src/core/renderers/webgl/shaders/PrimitiveShader.js index 6f25409..a25f54f 100644 --- a/src/core/renderers/webgl/shaders/PrimitiveShader.js +++ b/src/core/renderers/webgl/shaders/PrimitiveShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function PrimitiveShader(gl) { +function PrimitiveShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -23,7 +24,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + '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);', @@ -36,7 +38,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = vColor;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/Shader.js b/src/core/renderers/webgl/shaders/Shader.js index f8964f5..fd75ef5 100644 --- a/src/core/renderers/webgl/shaders/Shader.js +++ b/src/core/renderers/webgl/shaders/Shader.js @@ -6,7 +6,8 @@ * @param [fragmentSrc] {string} The source of the fragment shader. * @param [vertexSrc] {string} The source of the vertex shader. */ -function Shader(gl, vertexSrc, fragmentSrc, customUniforms, customAttributes) { +function Shader(gl, vertexSrc, fragmentSrc, customUniforms, customAttributes) +{ /** * @member {number} * @readonly @@ -33,7 +34,8 @@ dimensions: { type: '4f', value: new Float32Array(4) } }; - for (var u in customUniforms) { + for (var u in customUniforms) + { this.uniforms[u] = customUniforms[u]; } @@ -43,7 +45,8 @@ aColor: 0 }; - for (var a in customAttributes) { + for (var a in customAttributes) + { this.attributes[a] = customAttributes[a]; } @@ -66,7 +69,8 @@ 'const vec2 center = vec2(-1.0, 1.0);', - 'void main(void) {', + 'void main(void) + {', ' gl_Position = vec4( ((aVertexPosition + offsetVector) / projectionVector) + center , 0.0, 1.0);', ' vTextureCoord = aTextureCoord;', ' vColor = vec4(aColor.rgb * aColor.a, aColor.a);', @@ -85,7 +89,8 @@ 'uniform sampler2D uSampler;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;', '}' ].join('\n'); @@ -96,7 +101,8 @@ Shader.prototype.constructor = Shader; module.exports = Shader; -Shader.prototype.init = function () { +Shader.prototype.init = function () +{ this.compile(); this.gl.useProgram(this.program); @@ -105,14 +111,18 @@ this.cacheAttributeLocations(Object.keys(this.attributes)); }; -Shader.prototype.cacheUniformLocations = function (keys) { - for (var i = 0; i < keys.length; ++i) { +Shader.prototype.cacheUniformLocations = function (keys) +{ + for (var i = 0; i < keys.length; ++i) + { this.uniforms[keys[i]]._location = this.gl.getUniformLocation(this.program, keys[i]); } }; -Shader.prototype.cacheAttributeLocations = function (keys) { - for (var i = 0; i < keys.length; ++i) { +Shader.prototype.cacheAttributeLocations = function (keys) +{ + for (var i = 0; i < keys.length; ++i) + { this.attributes[keys[i]] = this.gl.getAttribLocation(this.program, keys[i]); } @@ -124,14 +134,16 @@ // 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.attributes.aColor === -1) { + // if (this.attributes.aColor === -1) + { // this.attributes.aColor = 2; // } // End worst hack eva // }; -Shader.prototype.compile = function () { +Shader.prototype.compile = function () +{ var gl = this.gl; var glVertShader = this._glCompile(gl.VERTEX_SHADER, this.vertexSrc); @@ -144,13 +156,15 @@ gl.linkProgram(program); // if linking fails, then log and cleanup - if (!gl.getProgramParameter(program, gl.LINK_STATUS)) { + if (!gl.getProgramParameter(program, gl.LINK_STATUS)) + { window.console.error('Pixi.js Error: Could not initialize shader.'); window.console.error('gl.VALIDATE_STATUS', gl.getProgramParameter(program, gl.VALIDATE_STATUS)); window.console.error('gl.getError()', gl.getError()); // if there is a program info log, log it - if (gl.getProgramInfoLog(program) !== '') { + if (gl.getProgramInfoLog(program) !== '') + { window.console.warn('Pixi.js Warning: gl.getProgramInfoLog()', gl.getProgramInfoLog(program)); } @@ -165,18 +179,21 @@ return (this.program = program); }; -Shader.prototype.syncUniforms = function () { +Shader.prototype.syncUniforms = function () +{ var gl = this.gl; this.textureCount = 1; - for (var key in this.uniforms) { + for (var key in this.uniforms) + { var uniform = this.uniforms[key], location = uniform._location, value = uniform.value, i, il; - switch (uniform.type) { + switch (uniform.type) + { // single int value case 'i': case '1i': @@ -282,7 +299,8 @@ // a Color Value case 'c': - if (typeof value === 'number') { + if (typeof value === 'number') + { value = utils.hex2rgb(value); } @@ -311,11 +329,13 @@ // array of 2D Point objects case 'v2v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(2 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 2] = value[i].x; uniform._array[i * 2 + 1] = value[i].y; } @@ -325,11 +345,13 @@ // array of 3D Point objects case 'v3v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(3 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 3] = value[i].x; uniform._array[i * 3 + 1] = value[i].y; uniform._array[i * 3 + 2] = value[i].z; @@ -341,11 +363,13 @@ // array of 4D Point objects case 'v4v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(4 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 4] = value[i].x; uniform._array[i * 4 + 1] = value[i].y; uniform._array[i * 4 + 2] = value[i].z; @@ -359,7 +383,8 @@ // PIXI.Texture case 't': case 'sampler2D': - if (!uniform.value || !uniform.value.baseTexture || !uniform.value.baseTexture.hasLoaded) { + if (!uniform.value || !uniform.value.baseTexture || !uniform.value.baseTexture.hasLoaded) + { break; } @@ -376,7 +401,8 @@ this.textureCount++; // initialize the texture if we haven't yet - if (!uniform._init) { + if (!uniform._init) + { this.initSampler2D(uniform); uniform._init = true; @@ -394,11 +420,13 @@ * Initialises a Sampler2D uniform (which may only be available later on after initUniforms once the texture has loaded) * */ -Shader.prototype.initSampler2D = function (uniform) { +Shader.prototype.initSampler2D = function (uniform) +{ var gl = this.gl; // Extended texture data - if (uniform.textureData) { + if (uniform.textureData) + { var data = uniform.textureData; // GLTexture = mag linear, min linear_mipmap_linear, wrap repeat + gl.generateMipmap(gl.TEXTURE_2D); @@ -417,14 +445,16 @@ var wrapT = (data.wrapT) ? data.wrapT : gl.CLAMP_TO_EDGE; var format = (data.luminance) ? gl.LUMINANCE : gl.RGBA; - if (data.repeat) { + if (data.repeat) + { wrapS = gl.REPEAT; wrapT = gl.REPEAT; } gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, !!data.flipY); - if (data.width) { + if (data.width) + { var width = (data.width) ? data.width : 512; var height = (data.height) ? data.height : 2; var border = (data.border) ? data.border : 0; @@ -432,7 +462,8 @@ // 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 { + 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); } @@ -448,7 +479,8 @@ * Destroys the shader. * */ -Shader.prototype.destroy = function () { +Shader.prototype.destroy = function () +{ this.gl.deleteProgram(this.program); this.gl = null; @@ -459,13 +491,15 @@ this.fragmentSrc = null; }; -Shader.prototype._glCompile = function (type, src) { +Shader.prototype._glCompile = function (type, src) +{ var shader = this.gl.createShader(type); this.gl.shaderSource(shader, src); this.gl.compileShader(shader); - if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) { + if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) + { window.console.log(this.gl.getShaderInfoLog(shader)); return null; } diff --git a/src/core/renderers/webgl/shaders/StripShader.js b/src/core/renderers/webgl/shaders/StripShader.js index 193f6e1..a7abcc6 100644 --- a/src/core/renderers/webgl/shaders/StripShader.js +++ b/src/core/renderers/webgl/shaders/StripShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function StripShader(gl) { +function StripShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -20,7 +21,8 @@ 'varying vec2 vTextureCoord;', - 'void main(void) {', + '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);', @@ -36,7 +38,8 @@ 'varying vec2 vTextureCoord;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vec2(vTextureCoord.x, vTextureCoord.y)) * alpha;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/utils/FilterTexture.js b/src/core/renderers/webgl/utils/FilterTexture.js index d2c8423..4433d44 100644 --- a/src/core/renderers/webgl/utils/FilterTexture.js +++ b/src/core/renderers/webgl/utils/FilterTexture.js @@ -8,7 +8,8 @@ * @param height {number} the vertical range of the filter * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values */ -function FilterTexture(gl, width, height, scaleMode) { +function FilterTexture(gl, width, height, scaleMode) +{ /** * @member {WebGLContext} */ @@ -59,7 +60,8 @@ * Clears the filter texture. * */ -FilterTexture.prototype.clear = function () { +FilterTexture.prototype.clear = function () +{ var gl = this.gl; gl.clearColor(0,0,0, 0); @@ -72,8 +74,10 @@ * @param width {number} the new width of the texture * @param height {number} the new height of the texture */ -FilterTexture.prototype.resize = function (width, height) { - if (this.width === width && this.height === height) { +FilterTexture.prototype.resize = function (width, height) +{ + if (this.width === width && this.height === height) + { return; } @@ -96,7 +100,8 @@ * Destroys the filter texture. * */ -FilterTexture.prototype.destroy = function () { +FilterTexture.prototype.destroy = function () +{ var gl = this.gl; gl.deleteFramebuffer( this.frameBuffer ); gl.deleteTexture( this.texture ); diff --git a/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js b/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js index c4721e9..a63f4d7 100644 --- a/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js +++ b/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js @@ -14,7 +14,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this sprite batch works for. */ -function WebGLFastSpriteBatch(renderer) { +function WebGLFastSpriteBatch(renderer) +{ /** * The renderer instance this sprite batch operates on. * @@ -91,7 +92,8 @@ */ this.lastIndexCount = 0; - for (var i=0, j=0; i < numIndices; i += 6, j += 4) { + 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; @@ -144,7 +146,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.setupContext(); }); } @@ -157,7 +160,8 @@ * * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLFastSpriteBatch.prototype.setupContext = function () { +WebGLFastSpriteBatch.prototype.setupContext = function () +{ var gl = this.renderer.gl; // create a couple of buffers @@ -177,7 +181,8 @@ /** * @param spriteBatch {SpriteBatch} The SpriteBatch container to prepare for. */ -WebGLFastSpriteBatch.prototype.begin = function (spriteBatch) { +WebGLFastSpriteBatch.prototype.begin = function (spriteBatch) +{ this.shader = this.renderer.shaderManager.fastShader; this.matrix = spriteBatch.worldTransform.toArray(true); @@ -187,33 +192,38 @@ /** */ -WebGLFastSpriteBatch.prototype.end = function () { +WebGLFastSpriteBatch.prototype.end = function () +{ this.flush(); }; /** * @param spriteBatch {SpriteBatch} The SpriteBatch container to render. */ -WebGLFastSpriteBatch.prototype.render = function (spriteBatch) { +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) { + if (!sprite.texture._uvs) + { return; } this.currentBaseTexture = sprite.texture.baseTexture; // check blend mode - if (sprite.blendMode !== this.renderer.blendModeManager.currentBlendMode) { + if (sprite.blendMode !== this.renderer.blendModeManager.currentBlendMode) + { this.flush(); this.renderer.blendModeManager.setBlendMode(sprite.blendMode); } - for (var i=0,j= children.length; i= this.size) { + if (this.currentBatchSize >= this.size) + { this.flush(); } }; @@ -362,29 +379,35 @@ /** * */ -WebGLFastSpriteBatch.prototype.flush = function () { +WebGLFastSpriteBatch.prototype.flush = function () +{ // If the batch is length 0 then return as there is nothing to draw - if (this.currentBatchSize === 0) { + if (this.currentBatchSize === 0) + { return; } var gl = this.renderer.gl; // bind the current texture - if (!this.currentBaseTexture._glTextures[gl.id]) { + if (!this.currentBaseTexture._glTextures[gl.id]) + { this.renderer.updateTexture(this.currentBaseTexture, gl); } //TODO-SHOUD THIS BE ELSE??!?!?! - else { + else + { gl.bindTexture(gl.TEXTURE_2D, this.currentBaseTexture._glTextures[gl.id]); } // upload the verts to the buffer - if (this.currentBatchSize > ( this.size * 0.5 ) ) { + if (this.currentBatchSize > ( this.size * 0.5 ) ) + { gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); } - else { + else + { var view = this.vertices.subarray(0, this.currentBatchSize * this.vertByteSize); gl.bufferSubData(gl.ARRAY_BUFFER, 0, view); @@ -405,14 +428,16 @@ * Ends the batch and flushes * */ -WebGLFastSpriteBatch.prototype.stop = function () { +WebGLFastSpriteBatch.prototype.stop = function () +{ this.flush(); }; /** * */ -WebGLFastSpriteBatch.prototype.start = function () { +WebGLFastSpriteBatch.prototype.start = function () +{ var gl = this.renderer.gl; // bind the main texture diff --git a/src/core/renderers/webgl/utils/WebGLGraphics.js b/src/core/renderers/webgl/utils/WebGLGraphics.js index 55f4911..ab8f46e 100644 --- a/src/core/renderers/webgl/utils/WebGLGraphics.js +++ b/src/core/renderers/webgl/utils/WebGLGraphics.js @@ -19,7 +19,8 @@ * @param graphics {Graphics} * @param renderer {WebGLRenderer} */ -WebGLGraphics.renderGraphics = function (graphics, renderer) {//projection, offset) { +WebGLGraphics.renderGraphics = function (graphics, renderer) {//projection, offset) +{ var gl = renderer.gl; var projection = renderer.projection, @@ -27,7 +28,8 @@ shader = renderer.shaderManager.primitiveShader, webGLData; - if (graphics.dirty) { + if (graphics.dirty) + { WebGLGraphics.updateGraphics(graphics, gl); } @@ -35,8 +37,10 @@ // This could be speeded up for sure! - for (var i = 0; i < webGL.data.length; i++) { - if (webGL.data[i].mode === 1) { + for (var i = 0; i < webGL.data.length; i++) + { + if (webGL.data[i].mode === 1) + { webGLData = webGL.data[i]; renderer.stencilManager.pushStencil(graphics, webGLData, renderer); @@ -46,7 +50,8 @@ renderer.stencilManager.popStencil(graphics, webGLData, renderer); } - else { + else + { webGLData = webGL.data[i]; @@ -84,12 +89,14 @@ * @param graphicsData {Graphics} The graphics object to update * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLGraphics.updateGraphics = function (graphics, gl) { +WebGLGraphics.updateGraphics = function (graphics, gl) +{ // get the contexts graphics object var webGL = graphics._webGL[gl.id]; // if the graphics object does not exist in the webGL context time to create it! - if (!webGL) { + if (!webGL) + { webGL = graphics._webGL[gl.id] = {lastIndex:0, data:[], gl:gl}; } @@ -99,11 +106,13 @@ var i; // if the user cleared the graphics object we will need to clear every object - if (graphics.clearDirty) { + if (graphics.clearDirty) + { graphics.clearDirty = false; // lop through and return all the webGLDatas to the object pool so than can be reused later on - for (i = 0; i < webGL.data.length; i++) { + for (i = 0; i < webGL.data.length; i++) + { var graphicsData = webGL.data[i]; graphicsData.reset(); WebGLGraphics.graphicsDataPool.push( graphicsData ); @@ -119,58 +128,72 @@ // loop through the graphics datas and construct each one.. // if the object is a complex fill then the new stencil buffer technique will be used // other wise graphics objects will be pushed into a batch.. - for (i = webGL.lastIndex; i < graphics.graphicsData.length; i++) { + for (i = webGL.lastIndex; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { // need to add the points the the graphics object.. data.points = data.shape.points.slice(); - if (data.shape.closed) { + if (data.shape.closed) + { // close the poly if the value is true! - if (data.points[0] !== data.points[data.points.length-2] || data.points[1] !== data.points[data.points.length-1]) { + if (data.points[0] !== data.points[data.points.length-2] || data.points[1] !== data.points[data.points.length-1]) + { data.points.push(data.points[0], data.points[1]); } } // MAKE SURE WE HAVE THE CORRECT TYPE.. - if (data.fill) { - if (data.points.length >= 6) { - if (data.points.length < 6 * 2) { + if (data.fill) + { + if (data.points.length >= 6) + { + if (data.points.length < 6 * 2) + { webGLData = WebGLGraphics.switchMode(webGL, 0); var canDrawUsingSimple = WebGLGraphics.buildPoly(data, webGLData); // console.log(canDrawUsingSimple); - if (!canDrawUsingSimple) { + if (!canDrawUsingSimple) + { // console.log("<>>>") webGLData = WebGLGraphics.switchMode(webGL, 1); WebGLGraphics.buildComplexPoly(data, webGLData); } } - else { + else + { webGLData = WebGLGraphics.switchMode(webGL, 1); WebGLGraphics.buildComplexPoly(data, webGLData); } } } - if (data.lineWidth > 0) { + if (data.lineWidth > 0) + { webGLData = WebGLGraphics.switchMode(webGL, 0); WebGLGraphics.buildLine(data, webGLData); } } - else { + else + { webGLData = WebGLGraphics.switchMode(webGL, 0); - if (data.type === CONST.SHAPES.RECT) { + if (data.type === CONST.SHAPES.RECT) + { WebGLGraphics.buildRectangle(data, webGLData); } - else if (data.type === CONST.SHAPES.CIRC || data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.CIRC || data.type === CONST.SHAPES.ELIP) + { WebGLGraphics.buildCircle(data, webGLData); } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { WebGLGraphics.buildRoundedRectangle(data, webGLData); } } @@ -179,10 +202,12 @@ } // upload all the dirty data... - for (i = 0; i < webGL.data.length; i++) { + for (i = 0; i < webGL.data.length; i++) + { webGLData = webGL.data[i]; - if (webGLData.dirty) { + if (webGLData.dirty) + { webGLData.upload(); } } @@ -194,18 +219,22 @@ * @param webGL {WebGLContext} * @param type {number} */ -WebGLGraphics.switchMode = function (webGL, type) { +WebGLGraphics.switchMode = function (webGL, type) +{ var webGLData; - if (!webGL.data.length) { + if (!webGL.data.length) + { webGLData = WebGLGraphics.graphicsDataPool.pop() || new WebGLGraphicsData(webGL.gl); webGLData.mode = type; webGL.data.push(webGLData); } - else { + else + { webGLData = webGL.data[webGL.data.length-1]; - if (webGLData.mode !== type || type === 1) { + if (webGLData.mode !== type || type === 1) + { webGLData = WebGLGraphics.graphicsDataPool.pop() || new WebGLGraphicsData(webGL.gl); webGLData.mode = type; webGL.data.push(webGLData); @@ -225,7 +254,8 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildRectangle = function (graphicsData, webGLData) { +WebGLGraphics.buildRectangle = function (graphicsData, webGLData) +{ // --- // // need to convert points to a nice regular data // @@ -235,7 +265,8 @@ var width = rectData.width; var height = rectData.height; - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -265,7 +296,8 @@ indices.push(vertPos, vertPos, vertPos+1, vertPos+2, vertPos+3, vertPos+3); } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = [x, y, @@ -289,7 +321,8 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildRoundedRectangle = function (graphicsData, webGLData) { +WebGLGraphics.buildRoundedRectangle = function (graphicsData, webGLData) +{ var rrectData = graphicsData.shape; var x = rrectData.x; var y = rrectData.y; @@ -305,7 +338,8 @@ recPoints = recPoints.concat(WebGLGraphics.quadraticBezierCurve(x + width, y + radius, x + width, y, x + width - radius, y)); recPoints = recPoints.concat(WebGLGraphics.quadraticBezierCurve(x + radius, y, x, y, x, y + radius)); - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -323,7 +357,8 @@ // var i = 0; - for (i = 0; i < triangles.length; i+=3) { + for (i = 0; i < triangles.length; i+=3) + { indices.push(triangles[i] + vecPos); indices.push(triangles[i] + vecPos); indices.push(triangles[i+1] + vecPos); @@ -332,12 +367,14 @@ } - for (i = 0; i < recPoints.length; i++) { + for (i = 0; i < recPoints.length; i++) + { verts.push(recPoints[i], recPoints[++i], r, g, b, alpha); } } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = recPoints; @@ -362,7 +399,8 @@ * @param toY {number} Destination point y * @return {number[]} */ -WebGLGraphics.quadraticBezierCurve = function (fromX, fromY, cpX, cpY, toX, toY) { +WebGLGraphics.quadraticBezierCurve = function (fromX, fromY, cpX, cpY, toX, toY) +{ var xa, ya, @@ -373,14 +411,16 @@ n = 20, points = []; - function getPt(n1 , n2, perc) { + function getPt(n1 , n2, perc) + { var diff = n2 - n1; return n1 + ( diff * perc ); } var j = 0; - for (var i = 0; i <= n; i++ ) { + for (var i = 0; i <= n; i++ ) + { j = i / n; // The Green Line @@ -406,7 +446,8 @@ * @param graphicsData {Graphics} The graphics object to draw * @param webGLData {object} */ -WebGLGraphics.buildCircle = function (graphicsData, webGLData) { +WebGLGraphics.buildCircle = function (graphicsData, webGLData) +{ // need to convert points to a nice regular data var circleData = graphicsData.shape; var x = circleData.x; @@ -415,11 +456,13 @@ var height; // TODO - bit hacky?? - if (graphicsData.type === CONST.SHAPES.CIRC) { + if (graphicsData.type === CONST.SHAPES.CIRC) + { width = circleData.radius; height = circleData.radius; } - else { + else + { width = circleData.width; height = circleData.height; } @@ -429,7 +472,8 @@ var i = 0; - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -444,7 +488,8 @@ indices.push(vecPos); - for (i = 0; i < totalSegs + 1 ; i++) { + for (i = 0; i < totalSegs + 1 ; i++) + { verts.push(x,y, r, g, b, alpha); verts.push(x + Math.sin(seg * i) * width, @@ -457,12 +502,14 @@ indices.push(vecPos-1); } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = []; - for (i = 0; i < totalSegs + 1; i++) { + for (i = 0; i < totalSegs + 1; i++) + { graphicsData.points.push(x + Math.sin(seg * i) * width, y + Math.cos(seg * i) * height); } @@ -481,18 +528,22 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildLine = function (graphicsData, webGLData) { +WebGLGraphics.buildLine = function (graphicsData, webGLData) +{ // TODO OPTIMISE! var i = 0; var points = graphicsData.points; - if (points.length === 0) { + if (points.length === 0) + { return; } // if the line width is an odd number add 0.5 to align to a whole pixel - if (graphicsData.lineWidth%2) { - for (i = 0; i < points.length; i++) { + if (graphicsData.lineWidth%2) + { + for (i = 0; i < points.length; i++) + { points[i] += 0.5; } } @@ -502,7 +553,8 @@ var lastPoint = new math.Point(points[points.length - 2], points[points.length - 1]); // if the first point is the last point - gonna have issues :) - if (firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) { + if (firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) + { // need to clone as we are going to slightly modify the shape.. points = points.slice(); @@ -562,7 +614,8 @@ verts.push(p1x + perpx , p1y + perpy, r, g, b, alpha); - for (i = 1; i < length-1; i++) { + for (i = 1; i < length-1; i++) + { p1x = points[(i-1)*2]; p1y = points[(i-1)*2 + 1]; @@ -599,7 +652,8 @@ denom = a1*b2 - a2*b1; - if (Math.abs(denom) < 0.1 ) { + if (Math.abs(denom) < 0.1 ) + { denom+=10.1; verts.push(p2x - perpx , p2y - perpy, @@ -618,7 +672,8 @@ pdist = (px -p2x) * (px -p2x) + (py -p2y) + (py -p2y); - if (pdist > 140 * 140) { + if (pdist > 140 * 140) + { perp3x = perpx - perp2x; perp3y = perpy - perp2y; @@ -639,7 +694,8 @@ indexCount++; } - else { + else + { verts.push(px , py); verts.push(r, g, b, alpha); @@ -672,7 +728,8 @@ indices.push(indexStart); - for (i = 0; i < indexCount; i++) { + for (i = 0; i < indexCount; i++) + { indices.push(indexStart++); } @@ -687,11 +744,13 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildComplexPoly = function (graphicsData, webGLData) { +WebGLGraphics.buildComplexPoly = function (graphicsData, webGLData) +{ //TODO - no need to copy this as it gets turned into a FLoat32Array anyways.. var points = graphicsData.points.slice(); - if (points.length < 6) { + if (points.length < 6) + { return; } @@ -711,7 +770,8 @@ var x,y; // get size.. - for (var i = 0; i < points.length; i+=2) { + for (var i = 0; i < points.length; i+=2) + { x = points[i]; y = points[i+1]; @@ -732,7 +792,8 @@ //TODO - this aint needed! var length = points.length / 2; - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { indices.push( i ); } @@ -746,10 +807,12 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildPoly = function (graphicsData, webGLData) { +WebGLGraphics.buildPoly = function (graphicsData, webGLData) +{ var points = graphicsData.points; - if (points.length < 6) { + if (points.length < 6) + { return; } // get first and last point.. figure out the middle! @@ -767,7 +830,8 @@ var triangles = utils.PolyK.Triangulate(points); - if (!triangles) { + if (!triangles) + { return false; } @@ -775,7 +839,8 @@ var i = 0; - for (i = 0; i < triangles.length; i+=3) { + for (i = 0; i < triangles.length; i+=3) + { indices.push(triangles[i] + vertPos); indices.push(triangles[i] + vertPos); indices.push(triangles[i+1] + vertPos); @@ -783,7 +848,8 @@ indices.push(triangles[i+2] + vertPos); } - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { verts.push(points[i * 2], points[i * 2 + 1], r, g, b, alpha); } diff --git a/src/core/renderers/webgl/utils/WebGLGraphicsData.js b/src/core/renderers/webgl/utils/WebGLGraphicsData.js index c56d05e..c739ba7 100644 --- a/src/core/renderers/webgl/utils/WebGLGraphicsData.js +++ b/src/core/renderers/webgl/utils/WebGLGraphicsData.js @@ -2,7 +2,8 @@ * @class * @private */ -function WebGLGraphicsData(gl) { +function WebGLGraphicsData(gl) +{ this.gl = gl; //TODO does this need to be split before uploding?? @@ -22,7 +23,8 @@ /** * */ -WebGLGraphicsData.prototype.reset = function () { +WebGLGraphicsData.prototype.reset = function () +{ this.points.length = 0; this.indices.length = 0; }; @@ -30,7 +32,8 @@ /** * */ -WebGLGraphicsData.prototype.upload = function () { +WebGLGraphicsData.prototype.upload = function () +{ var gl = this.gl; // this.lastIndex = graphics.graphicsData.length; diff --git a/src/core/renderers/webgl/utils/WebGLSpriteBatch.js b/src/core/renderers/webgl/utils/WebGLSpriteBatch.js index 96eaa52..55befbb 100644 --- a/src/core/renderers/webgl/utils/WebGLSpriteBatch.js +++ b/src/core/renderers/webgl/utils/WebGLSpriteBatch.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this sprite batch works for. */ -function WebGLSpriteBatch(renderer) { +function WebGLSpriteBatch(renderer) +{ /** * * @@ -88,7 +89,8 @@ */ this.lastIndexCount = 0; - for (var i=0, j=0; i < numIndices; i += 6, j += 4) { + 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; @@ -162,7 +164,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.setupContext(); }); } @@ -173,7 +176,8 @@ /** * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLSpriteBatch.prototype.setupContext = function () { +WebGLSpriteBatch.prototype.setupContext = function () +{ var gl = this.renderer.gl; // setup default shader @@ -198,7 +202,8 @@ /** * */ -WebGLSpriteBatch.prototype.begin = function () { +WebGLSpriteBatch.prototype.begin = function () +{ // this.shader = this.renderer.shaderManager.defaultShader; this.start(); @@ -206,19 +211,22 @@ /** */ -WebGLSpriteBatch.prototype.end = function () { +WebGLSpriteBatch.prototype.end = function () +{ this.flush(); }; /** * @param sprite {Sprite} the sprite to render when using this spritebatch */ -WebGLSpriteBatch.prototype.render = function (sprite) { +WebGLSpriteBatch.prototype.render = function (sprite) +{ var texture = sprite.texture; //TODO set blend modes.. // check texture.. - if (this.currentBatchSize >= this.size) { + if (this.currentBatchSize >= this.size) + { this.flush(); this.currentBaseTexture = texture.baseTexture; } @@ -227,7 +235,8 @@ var uvs = texture._uvs; // if the uvs have not updated then no point rendering just yet! - if (!uvs) { + if (!uvs) + { return; } @@ -237,7 +246,8 @@ var w0, w1, h0, h1; - if (texture.trim) { + 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; @@ -248,7 +258,8 @@ h0 = h1 + texture.crop.height; } - else { + else + { w0 = (texture.frame.width ) * (1-aX); w1 = (texture.frame.width ) * -aX; @@ -272,7 +283,8 @@ var colors = this.colors; var positions = this.positions; - if (this.renderer.roundPixels) { + if (this.renderer.roundPixels) + { // xy positions[index] = a * w1 + c * h1 + tx | 0; positions[index+1] = d * h1 + b * w1 + ty | 0; @@ -289,7 +301,8 @@ positions[index+15] = a * w1 + c * h0 + tx | 0; positions[index+16] = d * h0 + b * w1 + ty | 0; } - else { + else + { // xy positions[index] = a * w1 + c * h1 + tx; positions[index+1] = d * h1 + b * w1 + ty; @@ -338,11 +351,13 @@ * * @param sprite {TilingSprite} the tilingSprite to render */ -WebGLSpriteBatch.prototype.renderTilingSprite = function (tilingSprite) { +WebGLSpriteBatch.prototype.renderTilingSprite = function (tilingSprite) +{ var texture = tilingSprite.tilingTexture; // check texture.. - if (this.currentBatchSize >= this.size) { + if (this.currentBatchSize >= this.size) + { //return; this.flush(); this.currentBaseTexture = texture.baseTexture; @@ -351,7 +366,8 @@ // set the textures uvs temporarily // TODO create a separate texture so that we can tile part of a texture - if (!tilingSprite._uvs) { + if (!tilingSprite._uvs) + { tilingSprite._uvs = new TextureUvs(); } @@ -454,16 +470,19 @@ * Renders the content and empties the current batch. * */ -WebGLSpriteBatch.prototype.flush = function () { +WebGLSpriteBatch.prototype.flush = function () +{ // If the batch is length 0 then return as there is nothing to draw - if (this.currentBatchSize === 0) { + if (this.currentBatchSize === 0) + { return; } var gl = this.renderer.gl; var shader; - if (this.dirty) { + if (this.dirty) + { this.dirty = false; // bind the main texture gl.activeTexture(gl.TEXTURE0); @@ -482,10 +501,12 @@ } // upload the verts to the buffer - if (this.currentBatchSize > ( this.size * 0.5 ) ) { + if (this.currentBatchSize > ( this.size * 0.5 ) ) + { gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); } - else { + else + { var view = this.positions.subarray(0, this.currentBatchSize * this.vertByteSize); gl.bufferSubData(gl.ARRAY_BUFFER, 0, view); } @@ -502,7 +523,8 @@ var shaderSwap = false; var sprite; - for (var i = 0, j = this.currentBatchSize; i < j; i++) { + for (var i = 0, j = this.currentBatchSize; i < j; i++) + { sprite = this.sprites[i]; @@ -513,24 +535,28 @@ blendSwap = currentBlendMode !== nextBlendMode; shaderSwap = currentShader !== nextShader; // should I use uuidS??? - if (currentBaseTexture !== nextTexture || blendSwap || shaderSwap) { + if (currentBaseTexture !== nextTexture || blendSwap || shaderSwap) + { this.renderBatch(currentBaseTexture, batchSize, start); start = i; batchSize = 0; currentBaseTexture = nextTexture; - if (blendSwap) { + if (blendSwap) + { currentBlendMode = nextBlendMode; this.renderer.blendModeManager.setBlendMode( currentBlendMode ); } - if (shaderSwap) { + if (shaderSwap) + { currentShader = nextShader; shader = currentShader.shaders ? currentShader.shaders[gl.id] : currentShader; - if (!shader) { + if (!shader) + { shader = new Shader(gl, null, currentShader.fragmentSrc, currentShader.uniforms); currentShader.shaders[gl.id] = shader; } @@ -538,7 +564,8 @@ // set shader function??? this.renderer.shaderManager.setShader(shader); - if (shader.dirty) { + if (shader.dirty) + { shader.syncUniforms(); } @@ -569,17 +596,21 @@ * @param size {number} * @param startIndex {number} */ -WebGLSpriteBatch.prototype.renderBatch = function (texture, size, startIndex) { - if (size === 0) { +WebGLSpriteBatch.prototype.renderBatch = function (texture, size, startIndex) +{ + if (size === 0) + { return; } var gl = this.renderer.gl; - if (!texture._glTextures[gl.id]) { + if (!texture._glTextures[gl.id]) + { this.renderer.updateTexture(texture); } - else { + else + { // bind the current texture gl.bindTexture(gl.TEXTURE_2D, texture._glTextures[gl.id]); } @@ -594,7 +625,8 @@ /** * */ -WebGLSpriteBatch.prototype.stop = function () { +WebGLSpriteBatch.prototype.stop = function () +{ this.flush(); this.dirty = true; }; @@ -602,7 +634,8 @@ /** * */ -WebGLSpriteBatch.prototype.start = function () { +WebGLSpriteBatch.prototype.start = function () +{ this.dirty = true; }; @@ -610,7 +643,8 @@ * Destroys the SpriteBatch. * */ -WebGLSpriteBatch.prototype.destroy = function () { +WebGLSpriteBatch.prototype.destroy = function () +{ this.renderer.gl.deleteBuffer(this.vertexBuffer); this.renderer.gl.deleteBuffer(this.indexBuffer); diff --git a/src/core/textures/BaseTexture.js b/src/core/textures/BaseTexture.js index 2bf77d4..513d358 100644 --- a/src/core/textures/BaseTexture.js +++ b/src/core/textures/BaseTexture.js @@ -10,7 +10,8 @@ * @param source {Image|Canvas} the source object of the texture. * @param [scaleMode=scaleModes.DEFAULT] {number} See {@link scaleModes} for possible values */ -function BaseTexture(source, scaleMode) { +function BaseTexture(source, scaleMode) +{ this.uuid = utils.uuid(); /** @@ -123,7 +124,8 @@ this._needsUpdate = false; // if no source passed don't try to load - if (source) { + if (source) + { this.loadSource(source); } @@ -149,13 +151,16 @@ Object.defineProperties(BaseTexture.prototype, { needsUpdate: { - get: function () { + get: function () + { return this._needsUpdate; }, - set: function (val) { + set: function (val) + { this._needsUpdate = val; - if (val) { + if (val) + { this.emit('update', this); } } @@ -171,9 +176,11 @@ * * The logic state after calling `loadSource` directly or indirectly (eg. `fromImage`, `new BaseTexture`) is: * - * if (texture.hasLoaded) { + * if (texture.hasLoaded) + { * // texture ready for use - * } else if (texture.isLoading) { + * } else if (texture.isLoading) + { * // listen to 'loaded' and/or 'error' events on texture * } else { * // not loading, not going to load UNLESS the source is reloaded @@ -183,12 +190,14 @@ * @protected * @param source {Image|Canvas} the source object of the texture. */ -BaseTexture.prototype.loadSource = function (source) { +BaseTexture.prototype.loadSource = function (source) +{ var wasLoading = this.isLoading; this.hasLoaded = false; this.isLoading = false; - if (wasLoading && this.source) { + if (wasLoading && this.source) + { this.source.onload = null; this.source.onerror = null; } @@ -196,20 +205,24 @@ this.source = source; // Apply source if loaded. Otherwise setup appropriate loading monitors. - if ((this.source.complete || this.source.getContext) && this.source.width && this.source.height) { + if ((this.source.complete || this.source.getContext) && this.source.width && this.source.height) + { this._sourceLoaded(); } - else if(!source.getContext) { + else if(!source.getContext) + { // Image fail / not ready this.isLoading = true; var scope = this; - source.onload = function () { + source.onload = function () + { source.onload = null; source.onerror = null; - if(!scope.isLoading) { + if(!scope.isLoading) + { return; } @@ -219,11 +232,13 @@ scope.emit('loaded', scope); }; - source.onerror = function () { + source.onerror = function () + { source.onload = null; source.onerror = null; - if(!scope.isLoading) { + if(!scope.isLoading) + { return; } @@ -234,24 +249,29 @@ // Per http://www.w3.org/TR/html5/embedded-content-0.html#the-img-element // "The value of `complete` can thus change while a script is executing." // So complete needs to be re-checked after the callbacks have been added.. - if (source.complete) { + if (source.complete) + { this.isLoading = false; // ..and if we're complete now, no need for callbacks source.onload = null; source.onerror = null; - if (source.width && source.height) { + if (source.width && source.height) + { this._sourceLoaded(); // If any previous subscribers possible - if (wasLoading) { + if (wasLoading) + { this.emit('loaded', this); } } - else { + else + { // If any previous subscribers possible - if (wasLoading) { + if (wasLoading) + { this.emit('error', this); } } @@ -265,7 +285,8 @@ * * @private */ -BaseTexture.prototype._sourceLoaded = function () { +BaseTexture.prototype._sourceLoaded = function () +{ this.hasLoaded = true; this.width = this.source.naturalWidth || this.source.width; @@ -278,16 +299,20 @@ * Destroys this base texture * */ -BaseTexture.prototype.destroy = function () { - if (this.imageUrl) { +BaseTexture.prototype.destroy = function () +{ + if (this.imageUrl) + { delete utils.BaseTextureCache[this.imageUrl]; delete utils.TextureCache[this.imageUrl]; this.imageUrl = null; - if (!navigator.isCocoonJS) { + if (!navigator.isCocoonJS) + { this.source.src = ''; } } - else if (this.source && this.source._pixiId) { + else if (this.source && this.source._pixiId) + { delete utils.BaseTextureCache[this.source._pixiId]; } this.source = null; @@ -301,7 +326,8 @@ * memory again. * */ -BaseTexture.prototype.dispose = function () { +BaseTexture.prototype.dispose = function () +{ this.emit('dispose', this); }; @@ -311,7 +337,8 @@ * * @param newSrc {string} the path of the image */ -BaseTexture.prototype.updateSourceImage = function (newSrc) { +BaseTexture.prototype.updateSourceImage = function (newSrc) +{ this.source.src = newSrc; this.loadSource(this.source); }; @@ -326,18 +353,22 @@ * @param [scaleMode=scaleModes.DEFAULT] {number} See {@link scaleModes} for possible values * @return BaseTexture */ -BaseTexture.fromImage = function (imageUrl, crossorigin, scaleMode) { +BaseTexture.fromImage = function (imageUrl, crossorigin, scaleMode) +{ var baseTexture = utils.BaseTextureCache[imageUrl]; - if (crossorigin === undefined && imageUrl.indexOf('data:') !== 0) { + if (crossorigin === undefined && imageUrl.indexOf('data:') !== 0) + { crossorigin = true; } - if (!baseTexture) { + if (!baseTexture) + { // new Image() breaks tex loading in some versions of Chrome. // See https://code.google.com/p/chromium/issues/detail?id=238071 var image = new Image();//document.createElement('img'); - if (crossorigin) { + if (crossorigin) + { image.crossOrigin = ''; } @@ -347,7 +378,8 @@ utils.BaseTextureCache[imageUrl] = baseTexture; // if there is an @2x at the end of the url we are going to assume its a highres image - if ( imageUrl.indexOf(CONST.RETINA_PREFIX + '.') !== -1) { + if ( imageUrl.indexOf(CONST.RETINA_PREFIX + '.') !== -1) + { baseTexture.resolution = 2; } } @@ -363,14 +395,17 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return BaseTexture */ -BaseTexture.fromCanvas = function (canvas, scaleMode) { - if (!canvas._pixiId) { +BaseTexture.fromCanvas = function (canvas, scaleMode) +{ + if (!canvas._pixiId) + { canvas._pixiId = 'canvas_' + utils.uuid(); } var baseTexture = utils.BaseTextureCache[canvas._pixiId]; - if (!baseTexture) { + if (!baseTexture) + { baseTexture = new BaseTexture(canvas, scaleMode); utils.BaseTextureCache[canvas._pixiId] = baseTexture; } diff --git a/src/core/textures/RenderTexture.js b/src/core/textures/RenderTexture.js index 6dad20f..53ae796 100644 --- a/src/core/textures/RenderTexture.js +++ b/src/core/textures/RenderTexture.js @@ -46,8 +46,10 @@ * @param [scaleMode] {number} See {@link scaleModes} for possible values * @param [resolution=1] {number} The resolution of the texture being generated */ -function RenderTexture(renderer, width, height, scaleMode, resolution) { - if (!renderer) { +function RenderTexture(renderer, width, height, scaleMode, resolution) +{ + if (!renderer) + { throw new Error('Unable to create RenderTexture, you must pass a renderer into the constructor.'); } @@ -133,7 +135,8 @@ */ this.renderer = renderer; - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { var gl = this.renderer.gl; this.textureBuffer = new FilterTexture(gl, this.width * this.resolution, this.height * this.resolution, this.baseTexture.scaleMode); @@ -142,7 +145,8 @@ this.render = this.renderWebGL; this.projection = new math.Point(this.width*0.5, -this.height*0.5); } - else { + else + { this.render = this.renderCanvas; this.textureBuffer = new CanvasBuffer(this.width* this.resolution, this.height* this.resolution); this.baseTexture.source = this.textureBuffer.canvas; @@ -167,8 +171,10 @@ * @param height {number} The height to resize to. * @param updateBase {boolean} Should the baseTexture.width and height values be resized as well? */ -RenderTexture.prototype.resize = function (width, height, updateBase) { - if (width === this.width && height === this.height) { +RenderTexture.prototype.resize = function (width, height, updateBase) +{ + if (width === this.width && height === this.height) + { return; } @@ -177,17 +183,20 @@ this.width = this.frame.width = this.crop.width = width; this.height = this.frame.height = this.crop.height = height; - if (updateBase) { + if (updateBase) + { this.baseTexture.width = this.width; this.baseTexture.height = this.height; } - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { this.projection.x = this.width / 2; this.projection.y = -this.height / 2; } - if (!this.valid) { + if (!this.valid) + { return; } @@ -198,12 +207,15 @@ * Clears the RenderTexture. * */ -RenderTexture.prototype.clear = function () { - if (!this.valid) { +RenderTexture.prototype.clear = function () +{ + if (!this.valid) + { return; } - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { this.renderer.gl.bindFramebuffer(this.renderer.gl.FRAMEBUFFER, this.textureBuffer.frameBuffer); } @@ -220,19 +232,23 @@ * @param [restoreWorldTransform=true] {boolean} If true the displayObject's worldTransform/worldAlpha and all children * transformations will be restored. Not restoring this information will be a little faster. */ -RenderTexture.prototype.renderWebGL = function (displayObject, matrix, clear, restoreWorldTransform) { - if (!this.valid) { +RenderTexture.prototype.renderWebGL = function (displayObject, matrix, clear, restoreWorldTransform) +{ + if (!this.valid) + { return; } - if (typeof restoreWorldTransform === 'undefined') { + if (typeof restoreWorldTransform === 'undefined') + { restoreWorldTransform = true; } var tempAlpha, tempTransform; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { tempAlpha = displayObject.worldAlpha; tempTransform = displayObject.worldTransform.toArray(); } @@ -245,7 +261,8 @@ wt.identity(); wt.translate(0, this.projection.y * 2); - if (matrix) { + if (matrix) + { wt.append(matrix); } @@ -258,7 +275,8 @@ var children = displayObject.children; var i, j; - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } @@ -269,7 +287,8 @@ gl.bindFramebuffer(gl.FRAMEBUFFER, this.textureBuffer.frameBuffer ); - if (clear) { + if (clear) + { this.textureBuffer.clear(); } @@ -279,11 +298,13 @@ this.renderer.spriteBatch.dirty = true; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { displayObject.worldAlpha = tempAlpha; displayObject.worldTransform.fromArray(tempTransform); - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } } @@ -300,26 +321,31 @@ * @param [restoreWorldTransform=true] {boolean} If true the displayObject's worldTransform/worldAlpha and all children * transformations will be restored. Not restoring this information will be a little faster. */ -RenderTexture.prototype.renderCanvas = function (displayObject, matrix, clear, restoreWorldTransform) { - if (!this.valid) { +RenderTexture.prototype.renderCanvas = function (displayObject, matrix, clear, restoreWorldTransform) +{ + if (!this.valid) + { return; } - if (typeof restoreWorldTransform === 'undefined') { + if (typeof restoreWorldTransform === 'undefined') + { restoreWorldTransform = true; } var tempAlpha, tempTransform; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { tempAlpha = displayObject.worldAlpha; tempTransform = displayObject.worldTransform.toArray(); } var wt = displayObject.worldTransform; wt.identity(); - if (matrix) { + if (matrix) + { wt.append(matrix); } @@ -330,11 +356,13 @@ var children = displayObject.children; var i, j; - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } - if (clear) { + if (clear) + { this.textureBuffer.clear(); } @@ -348,11 +376,13 @@ this.renderer.resolution = realResolution; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { displayObject.worldAlpha = tempAlpha; displayObject.worldTransform.fromArray(tempTransform); - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } } @@ -363,7 +393,8 @@ * * @return {Image} */ -RenderTexture.prototype.getImage = function () { +RenderTexture.prototype.getImage = function () +{ var image = new Image(); image.src = this.getBase64(); return image; @@ -374,7 +405,8 @@ * * @return {string} A base64 encoded string of the texture. */ -RenderTexture.prototype.getBase64 = function () { +RenderTexture.prototype.getBase64 = function () +{ return this.getCanvas().toDataURL(); }; @@ -383,8 +415,10 @@ * * @return {HTMLCanvasElement} A Canvas element with the texture rendered on. */ -RenderTexture.prototype.getCanvas = function () { - if (this.renderer.type === CONST.WEBGL_RENDERER) { +RenderTexture.prototype.getCanvas = function () +{ + if (this.renderer.type === CONST.WEBGL_RENDERER) + { var gl = this.renderer.gl; var width = this.textureBuffer.width; var height = this.textureBuffer.height; @@ -403,7 +437,8 @@ return tempCanvas.canvas; } - else { + else + { return this.textureBuffer.canvas; } }; diff --git a/src/core/textures/Texture.js b/src/core/textures/Texture.js index 3c65909..e97f0aa 100644 --- a/src/core/textures/Texture.js +++ b/src/core/textures/Texture.js @@ -17,7 +17,8 @@ * @param [crop] {Rectangle} The area of original texture * @param [trim] {Rectangle} Trimmed texture rectangle */ -function Texture(baseTexture, frame, crop, trim) { +function Texture(baseTexture, frame, crop, trim) +{ /** * Does this Texture have any frame data assigned to it? * @@ -25,12 +26,14 @@ */ this.noFrame = false; - if (!frame) { + if (!frame) + { this.noFrame = true; frame = new math.Rectangle(0, 0, 1, 1); } - if (baseTexture instanceof Texture) { + if (baseTexture instanceof Texture) + { baseTexture = baseTexture.baseTexture; } @@ -100,13 +103,16 @@ */ this.crop = crop || new math.Rectangle(0, 0, 1, 1); - if (baseTexture.hasLoaded) { - if (this.noFrame) { + if (baseTexture.hasLoaded) + { + if (this.noFrame) + { frame = new math.Rectangle(0, 0, baseTexture.width, baseTexture.height); } this.frame = frame; } - else { + else + { baseTexture.addEventListener('loaded', this.onBaseTextureLoaded.bind(this)); } } @@ -118,19 +124,23 @@ Object.defineProperties(Texture.prototype, { needsUpdate: { - get: function () { + get: function () + { return this.baseTexture.needsUpdate; }, - set: function (val) { + set: function (val) + { this.baseTexture.needsUpdate = val; } }, frame: { - get: function () { + get: function () + { return this._frame; }, - set: function (frame) { + set: function (frame) + { this._frame = frame; this.noFrame = false; @@ -143,20 +153,23 @@ 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 (!this.trim && (frame.x + frame.width > this.baseTexture.width || frame.y + frame.height > this.baseTexture.height)) + { throw new Error('Texture Error: frame does not fit inside the base Texture dimensions ' + this); } this.valid = frame && frame.width && frame.height && this.baseTexture.source && this.baseTexture.hasLoaded; - if (this.trim) { + 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) { + if (this.valid) + { this._updateUvs(); } } @@ -168,11 +181,13 @@ * * @private */ -Texture.prototype.onBaseTextureLoaded = function () { +Texture.prototype.onBaseTextureLoaded = function () +{ var baseTexture = this.baseTexture; baseTexture.removeEventListener('loaded', this.onLoaded); - if (this.noFrame) { + if (this.noFrame) + { this.frame = new math.Rectangle(0, 0, baseTexture.width, baseTexture.height); } @@ -184,8 +199,10 @@ * * @param destroyBase {boolean} Whether to destroy the base texture as well */ -Texture.prototype.destroy = function (destroyBase) { - if (destroyBase) { +Texture.prototype.destroy = function (destroyBase) +{ + if (destroyBase) + { this.baseTexture.destroy(); } @@ -197,8 +214,10 @@ * * @private */ -Texture.prototype._updateUvs = function () { - if (!this._uvs) { +Texture.prototype._updateUvs = function () +{ + if (!this._uvs) + { this._uvs = new TextureUvs(); } @@ -229,10 +248,12 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return Texture */ -Texture.fromImage = function (imageUrl, crossorigin, scaleMode) { +Texture.fromImage = function (imageUrl, crossorigin, scaleMode) +{ var texture = utils.TextureCache[imageUrl]; - if (!texture) { + if (!texture) + { texture = new Texture(BaseTexture.fromImage(imageUrl, crossorigin, scaleMode)); utils.TextureCache[imageUrl] = texture; } @@ -248,9 +269,11 @@ * @param frameId {string} The frame id of the texture * @return Texture */ -Texture.fromFrame = function (frameId) { +Texture.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache '); } return texture; @@ -264,7 +287,8 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return {Texture} */ -Texture.fromCanvas = function (canvas, scaleMode) { +Texture.fromCanvas = function (canvas, scaleMode) +{ return new Texture(BaseTexture.fromCanvas(canvas, scaleMode)); }; @@ -276,7 +300,8 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return {Texture} A Texture */ -Texture.fromVideo = function (video, scaleMode) { +Texture.fromVideo = function (video, scaleMode) +{ return new Texture(VideoBaseTexture.baseTextureFromVideo(video, scaleMode)); }; @@ -287,7 +312,8 @@ * @param texture {Texture} The Texture to add to the cache. * @param id {string} The id that the texture will be stored against. */ -Texture.addTextureToCache = function (texture, id) { +Texture.addTextureToCache = function (texture, id) +{ utils.TextureCache[id] = texture; }; @@ -298,7 +324,8 @@ * @param id {string} The id of the texture to be removed * @return {Texture} The texture that was removed */ -Texture.removeTextureFromCache = function (id) { +Texture.removeTextureFromCache = function (id) +{ var texture = utils.TextureCache[id]; delete utils.TextureCache[id]; diff --git a/src/core/textures/TextureUvs.js b/src/core/textures/TextureUvs.js index b9bbb58..5424d52 100644 --- a/src/core/textures/TextureUvs.js +++ b/src/core/textures/TextureUvs.js @@ -1,4 +1,5 @@ -function TextureUvs() { +function TextureUvs() +{ this.x0 = 0; this.y0 = 0; diff --git a/src/core/textures/VideoBaseTexture.js b/src/core/textures/VideoBaseTexture.js index e3e0c5a..1a826a9 100644 --- a/src/core/textures/VideoBaseTexture.js +++ b/src/core/textures/VideoBaseTexture.js @@ -12,15 +12,18 @@ * @param source {HTMLVideoElement} * @param [scaleMode] {number} See {@link scaleModes} for possible values */ -function VideoBaseTexture(source, scaleMode) { - if (!source){ +function VideoBaseTexture(source, scaleMode) +{ + if (!source) + { throw new Error('No video source element specified.'); } // hook in here to check if video is already available. // BaseTexture looks for a source.complete boolean, plus width & height. - if ((source.readyState === source.HAVE_ENOUGH_DATA || source.readyState === source.HAVE_FUTURE_DATA) && source.width && source.height) { + if ((source.readyState === source.HAVE_ENOUGH_DATA || source.readyState === source.HAVE_FUTURE_DATA) && source.width && source.height) + { source.complete = true; } @@ -31,7 +34,8 @@ this._boundOnUpdate = this._onUpdate.bind(this); this._boundOnCanPlay = this._onCanPlay.bind(this); - if (!source.complete) { + if (!source.complete) + { source.addEventListener('canplay', this._boundOnCanPlay); source.addEventListener('canplaythrough', this._boundOnCanPlay); @@ -47,28 +51,35 @@ VideoBaseTexture.prototype.constructor = VideoBaseTexture; module.exports = VideoBaseTexture; -VideoBaseTexture.prototype._onUpdate = function () { - if (this.autoUpdate) { +VideoBaseTexture.prototype._onUpdate = function () +{ + if (this.autoUpdate) + { window.requestAnimationFrame(this._boundOnUpdate); this.needsUpdate = true; } }; -VideoBaseTexture.prototype._onPlayStart = function () { - if (!this.autoUpdate) { +VideoBaseTexture.prototype._onPlayStart = function () +{ + if (!this.autoUpdate) + { window.requestAnimationFrame(this._boundOnUpdate); this.autoUpdate = true; } }; -VideoBaseTexture.prototype._onPlayStop = function () { +VideoBaseTexture.prototype._onPlayStop = function () +{ this.autoUpdate = false; }; -VideoBaseTexture.prototype._onCanPlay = function () { +VideoBaseTexture.prototype._onCanPlay = function () +{ this.hasLoaded = true; - if (this.source) { + if (this.source) + { this.source.removeEventListener('canplay', this._boundOnCanPlay); this.source.removeEventListener('canplaythrough', this._boundOnCanPlay); @@ -78,15 +89,18 @@ this.source.play(); // prevent multiple loaded dispatches.. - if(!this.__loaded){ + if(!this.__loaded) + { this.__loaded = true; this.emit('loaded', this); } } }; -VideoBaseTexture.prototype.destroy = function () { - if (this.source && this.source._pixiId) { +VideoBaseTexture.prototype.destroy = function () +{ + if (this.source && this.source._pixiId) + { utils.BaseTextureCache[ this.source._pixiId ] = null; delete utils.BaseTextureCache[ this.source._pixiId ]; @@ -105,14 +119,17 @@ * @param scaleMode {number} See {@link scaleModes} for possible values * @return {VideoBaseTexture} */ -VideoBaseTexture.fromVideo = function (video, scaleMode) { - if (!video._pixiId) { +VideoBaseTexture.fromVideo = function (video, scaleMode) +{ + if (!video._pixiId) + { video._pixiId = 'video_' + utils.uuid(); } var baseTexture = utils.BaseTextureCache[video._pixiId]; - if (!baseTexture) { + if (!baseTexture) + { baseTexture = new VideoBaseTexture(video, scaleMode); utils.BaseTextureCache[ video._pixiId ] = baseTexture; } @@ -147,17 +164,21 @@ * @param scaleMode {number} See {@link scaleModes} for possible values * @return {VideoBaseTexture} */ -VideoBaseTexture.fromUrl = function (videoSrc, scaleMode) { +VideoBaseTexture.fromUrl = function (videoSrc, scaleMode) +{ var video = document.createElement('video'); // array of objects or strings - if (Array.isArray(videoSrc)) { - for (var i = 0; i < videoSrc.length; ++i) { + if (Array.isArray(videoSrc)) + { + for (var i = 0; i < videoSrc.length; ++i) + { video.appendChild(createSource(videoSrc.src || videoSrc, videoSrc.mime)); } } // single object or string - else { + else + { video.appendChild(createSource(videoSrc.src || videoSrc, videoSrc.mime)); } @@ -169,8 +190,10 @@ VideoBaseTexture.fromUrls = VideoBaseTexture.fromUrl; -function createSource(path, type) { - if (!type) { +function createSource(path, type) +{ + if (!type) + { type = 'video/' + path.substr(path.lastIndexOf('.') + 1); } diff --git a/src/core/utils/EventData.js b/src/core/utils/EventData.js index 5d55a22..8cdf701 100644 --- a/src/core/utils/EventData.js +++ b/src/core/utils/EventData.js @@ -7,7 +7,8 @@ * @param name {string} The string name of the event that was triggered * @param data {object} Arbitrary event data to pass along */ -function EventData(target, name, data) { +function EventData(target, name, data) +{ // for duck typing in the ".on()" function this.__isEventObject = true; @@ -71,7 +72,8 @@ * Stops the propagation of events up the scene graph (prevents bubbling). * */ -EventData.prototype.stopPropagation = function stopPropagation() { +EventData.prototype.stopPropagation = function stopPropagation() +{ this.stopped = true; }; @@ -79,6 +81,7 @@ * Stops the propagation of events to sibling listeners (no longer calls any listeners). * */ -EventData.prototype.stopImmediatePropagation = function stopImmediatePropagation() { +EventData.prototype.stopImmediatePropagation = function stopImmediatePropagation() +{ this.stoppedImmediate = true; }; diff --git a/src/core/utils/EventTarget.js b/src/core/utils/EventTarget.js index 7ae8820..671a151 100644 --- a/src/core/utils/EventTarget.js +++ b/src/core/utils/EventTarget.js @@ -13,14 +13,16 @@ * var em = new MyEmitter(); * em.emit('eventName', 'some data', 'some more data', {}, null, ...); */ -function eventTarget(obj) { +function eventTarget(obj) +{ /** * Return a list of assigned event listeners. * * @param eventName {string} The events that should be listed. * @return {Array} An array of listener functions */ - obj.listeners = function listeners(eventName) { + obj.listeners = function listeners(eventName) + { this._listeners = this._listeners || {}; return this._listeners[eventName] ? this._listeners[eventName].slice() : []; @@ -33,22 +35,26 @@ * @param eventName {string} The name of the event. * @return {boolean} Indication if we've emitted an event. */ - obj.emit = obj.dispatchEvent = function emit(eventName, data) { + obj.emit = obj.dispatchEvent = function emit(eventName, data) + { this._listeners = this._listeners || {}; // fast return when there are no listeners - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return; } //backwards compat with old method ".emit({ type: 'something' })" - if (typeof eventName === 'object') { + if (typeof eventName === 'object') + { data = eventName; eventName = eventName.type; } //ensure we are using a real pixi event - if (!data || data.__isEventObject !== true) { + if (!data || data.__isEventObject !== true) + { data = new EventData(this, eventName, data); } @@ -58,23 +64,27 @@ fn = listeners[0], i; - for (i = 0; i < length; fn = listeners[++i]) { + for (i = 0; i < length; fn = listeners[++i]) + { //call the event listener fn.call(this, data); //if "stopImmediatePropagation" is called, stop calling sibling events - if (data.stoppedImmediate) { + if (data.stoppedImmediate) + { return this; } } //if "stopPropagation" is called then don't bubble the event - if (data.stopped) { + if (data.stopped) + { return this; } //bubble this event up the scene graph - if (this.parent && this.parent.emit) { + if (this.parent && this.parent.emit) + { this.parent.emit.call(this.parent, eventName, data); } @@ -88,7 +98,8 @@ * @param eventName {string} Name of the event. * @param callback {Functon} fn Callback function. */ - obj.on = obj.addEventListener = function on(eventName, fn) { + obj.on = obj.addEventListener = function on(eventName, fn) + { this._listeners = this._listeners || {}; (this._listeners[eventName] = this._listeners[eventName] || []) @@ -103,11 +114,13 @@ * @param eventName {string} Name of the event. * @param callback {Function} Callback function. */ - obj.once = function once(eventName, fn) { + obj.once = function once(eventName, fn) + { this._listeners = this._listeners || {}; var self = this; - function onceHandlerWrapper() { + function onceHandlerWrapper() + { fn.apply(self.off(eventName, onceHandlerWrapper), arguments); } onceHandlerWrapper._originalHandler = fn; @@ -122,23 +135,28 @@ * @param eventName {string} The event we want to remove. * @param callback {Function} The listener that we need to find. */ - obj.off = obj.removeEventListener = function off(eventName, fn) { + obj.off = obj.removeEventListener = function off(eventName, fn) + { this._listeners = this._listeners || {}; - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return this; } var list = this._listeners[eventName], i = fn ? list.length : 0; - while(i-- > 0) { - if (list[i] === fn || list[i]._originalHandler === fn) { + while(i-- > 0) + { + if (list[i] === fn || list[i]._originalHandler === fn) + { list.splice(i, 1); } } - if (list.length === 0) { + if (list.length === 0) + { delete this._listeners[eventName]; } @@ -150,10 +168,12 @@ * * @param eventName {string} The event you want to remove all listeners for. */ - obj.removeAllListeners = function removeAllListeners(eventName) { + obj.removeAllListeners = function removeAllListeners(eventName) + { this._listeners = this._listeners || {}; - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return this; } @@ -169,7 +189,8 @@ * * @param object {object} The obj to mix into */ - mixin: function mixin(obj) { + mixin: function mixin(obj) + { eventTarget(obj); } }; diff --git a/src/core/utils/PolyK.js b/src/core/utils/PolyK.js index 7325141..5e20c2b 100644 --- a/src/core/utils/PolyK.js +++ b/src/core/utils/PolyK.js @@ -47,7 +47,8 @@ * Triangulates shapes for webGL graphic fills. * */ -PolyK.Triangulate = function (p) { +PolyK.Triangulate = function (p) +{ var sign = true; var n = p.length >> 1; @@ -59,7 +60,8 @@ i = 0; var al = n; - while(al > 3) { + while(al > 3) + { var i0 = avl[(i+0)%al]; var i1 = avl[(i+1)%al]; var i2 = avl[(i+2)%al]; @@ -69,29 +71,35 @@ var cx = p[2*i2], cy = p[2*i2+1]; var earFound = false; - if (PolyK._convex(ax, ay, bx, by, cx, cy, sign)) { + if (PolyK._convex(ax, ay, bx, by, cx, cy, sign)) + { earFound = true; - for (var j = 0; j < al; j++) { + for (var j = 0; j < al; j++) + { var vi = avl[j]; if (vi === i0 || vi === i1 || vi === i2) continue; - if (PolyK._PointInTriangle(p[2*vi], p[2*vi+1], ax, ay, bx, by, cx, cy)) { + if (PolyK._PointInTriangle(p[2*vi], p[2*vi+1], ax, ay, bx, by, cx, cy)) + { earFound = false; break; } } } - if (earFound) { + if (earFound) + { tgs.push(i0, i1, i2); avl.splice((i+1)%al, 1); al--; i = 0; } - else if (i++ > 3*al) { + else if (i++ > 3*al) + { // need to flip flip reverse it! // reset! - if (sign) { + if (sign) + { tgs = []; avl = []; for (i = 0; i < n; i++) avl.push(i); @@ -101,7 +109,8 @@ sign = false; } - else { + else + { // window.console.log("PIXI Warning: shape too complex to fill"); return null; } @@ -126,7 +135,8 @@ * @private * @return {boolean} */ -PolyK._PointInTriangle = function (px, py, ax, ay, bx, by, cx, cy) { +PolyK._PointInTriangle = function (px, py, ax, ay, bx, by, cx, cy) +{ var v0x = cx-ax; var v0y = cy-ay; var v1x = bx-ax; @@ -154,6 +164,7 @@ * @private * @return {boolean} */ -PolyK._convex = function (ax, ay, bx, by, cx, cy, sign) { +PolyK._convex = function (ax, ay, bx, by, cx, cy, sign) +{ return ((ay-by)*(cx-bx) + (bx-ax)*(cy-by) >= 0) === sign; }; diff --git a/src/core/utils/index.js b/src/core/utils/index.js index ade9831..bfae7ae 100644 --- a/src/core/utils/index.js +++ b/src/core/utils/index.js @@ -16,7 +16,8 @@ * * @return {number} The next uuid to use. */ - uuid: function () { + uuid: function () + { return ++utils._uid; }, @@ -26,7 +27,8 @@ * @param hex {number} * @return {number[]} An array representing the [R, G, B] of the color. */ - hex2rgb: function (hex, out) { + hex2rgb: function (hex, out) + { out = out || []; out[0] = (hex >> 16 & 0xFF) / 255; @@ -42,7 +44,8 @@ * @param hex {number} * @return {string} The string color. */ - hex2string: function (hex) { + hex2string: function (hex) + { hex = hex.toString(16); hex = '000000'.substr(0, 6 - hex.length) + hex; @@ -55,7 +58,8 @@ * @param rgb {number[]} * @return {number} The color number */ - rgb2hex: function (rgb) { + rgb2hex: function (rgb) + { return ((rgb[0]*255 << 16) + (rgb[1]*255 << 8) + rgb[2]*255); }, @@ -64,8 +68,10 @@ * * @return {boolean} whether they are supported */ - canUseNewCanvasBlendModes: function () { - if (typeof document === 'undefined') { + canUseNewCanvasBlendModes: function () + { + if (typeof document === 'undefined') + { return false; } @@ -93,15 +99,19 @@ * @param number {number} * @return {number} the closest number that is a power of two */ - getNextPowerOfTwo: function (number) { + getNextPowerOfTwo: function (number) + { // see: http://en.wikipedia.org/wiki/Power_of_two#Fast_algorithm_to_check_if_a_positive_number_is_a_power_of_two - if (number > 0 && (number & (number - 1)) === 0) { + if (number > 0 && (number & (number - 1)) === 0) + { return number; } - else { + else + { var result = 1; - while (result < number) { + while (result < number) + { result <<= 1; } @@ -116,7 +126,8 @@ * @param height {number} * @return {boolean} */ - isPowerOfTwo: function (width, height) { + isPowerOfTwo: function (width, height) + { return (width > 0 && (width & (width - 1)) === 0 && height > 0 && (height & (height - 1)) === 0); }, @@ -130,12 +141,15 @@ * @constant * @static */ - sayHello: function (type) { - if (utils._saidHello) { + sayHello: function (type) + { + if (utils._saidHello) + { return; } - if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) { + if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) + { var args = [ '%c %c %c Pixi.js ' + CONST.VERSION + ' - ' + type + ' %c ' + ' %c ' + ' http://www.pixijs.com/ %c %c ♥%c♥%c♥ ', 'background: #ff66a5', @@ -151,7 +165,8 @@ console.log.apply(console, args); //jshint ignore:line } - else if (window.console) { + else if (window.console) + { console.log('Pixi.js ' + CONST.VERSION + ' - ' + type + ' - http://www.pixijs.com/'); //jshint ignore:line } @@ -166,15 +181,19 @@ * @class * @namespace PIXI */ - AjaxRequest: function () { + AjaxRequest: function () + { var activexmodes = ['Msxml2.XMLHTTP.6.0', 'Msxml2.XMLHTTP.3.0', 'Microsoft.XMLHTTP']; //activeX versions to check for in IE - if (window.ActiveXObject) { //Test for support for ActiveXObject in IE first (as XMLHttpRequest in IE7 is broken) - for (var i=0; i= this.textures.length) { + else if (round >= this.textures.length) + { this.gotoAndStop(this.textures.length - 1); - if (this.onComplete) { + if (this.onComplete) + { this.onComplete(); } } @@ -167,10 +182,12 @@ * @static * @param frames {string[]} the array of frames ids the movieclip will use as its texture frames */ -MovieClip.fromFrames = function (frames) { +MovieClip.fromFrames = function (frames) +{ var textures = []; - for (var i = 0; i < frames.length; ++i) { + for (var i = 0; i < frames.length; ++i) + { textures.push(new core.Texture.fromFrame(frames[i])); } @@ -183,10 +200,12 @@ * @static * @param images {string[]} the array of image urls the movieclip will use as its texture frames */ -MovieClip.fromImages = function (images) { +MovieClip.fromImages = function (images) +{ var textures = []; - for (var i = 0; i < images.length; ++i) { + for (var i = 0; i < images.length; ++i) + { textures.push(new core.Texture.fromImage(images[i])); } diff --git a/src/extras/Rope.js b/src/extras/Rope.js index c157ec4..9c87bc0 100644 --- a/src/extras/Rope.js +++ b/src/extras/Rope.js @@ -9,7 +9,8 @@ * @param {Array} points - An array of {Point}. * */ -function Rope(texture, points) { +function Rope(texture, points) +{ Strip.call(this, texture); this.points = points; @@ -31,10 +32,12 @@ * Refreshes * */ -Rope.prototype.refresh = function () { +Rope.prototype.refresh = function () +{ var points = this.points; - if (points.length < 1) { + if (points.length < 1) + { return; } @@ -59,20 +62,23 @@ var total = points.length, point, index, amount; - for (var i = 1; i < total; i++) { + for (var i = 1; i < total; i++) + { point = points[i]; index = i * 4; // time to do some smart drawing! amount = i / (total-1); - if (i%2) { + if (i%2) + { uvs[index] = amount; uvs[index+1] = 0; uvs[index+2] = amount; uvs[index+3] = 1; } - else { + else + { uvs[index] = amount; uvs[index+1] = 0; @@ -95,10 +101,12 @@ * * @private */ -Rope.prototype.updateTransform = function () { +Rope.prototype.updateTransform = function () +{ var points = this.points; - if (points.length < 1) { + if (points.length < 1) + { return; } @@ -113,14 +121,17 @@ var total = points.length, point, index, ratio, perpLength, num; - for (var i = 0; i < total; i++) { + for (var i = 0; i < total; i++) + { point = points[i]; index = i * 4; - if (i < points.length-1) { + if (i < points.length-1) + { nextPoint = points[i+1]; } - else { + else + { nextPoint = point; } @@ -129,7 +140,8 @@ ratio = (1 - (i / (total-1))) * 10; - if (ratio > 1) { + if (ratio > 1) + { ratio = 1; } @@ -157,7 +169,8 @@ * * @param texture {Texture} the texture that will be used */ -Rope.prototype.setTexture = function (texture) { +Rope.prototype.setTexture = function (texture) +{ // stop current texture this.texture = texture; //this.updateFrame = true; diff --git a/src/extras/Strip.js b/src/extras/Strip.js index c5e378f..57691b5 100644 --- a/src/extras/Strip.js +++ b/src/extras/Strip.js @@ -10,7 +10,8 @@ * @param height {number} the height * */ -function Strip(texture) { +function Strip(texture) +{ core.DisplayObjectContainer.call(this); /** @@ -70,9 +71,11 @@ * * @param renderer {WebGLRenderer} */ -Strip.prototype.renderWebGL = function (renderer) { +Strip.prototype.renderWebGL = function (renderer) +{ // if the sprite is not visible or the alpha is 0 then no need to render this element - if (!this.visible || this.alpha <= 0) { + if (!this.visible || this.alpha <= 0) + { return; } @@ -81,7 +84,8 @@ renderer.spriteBatch.stop(); // init! init! - if (!this._vertexBuffer) { + if (!this._vertexBuffer) + { this._initWebGL(renderer); } @@ -96,7 +100,8 @@ //TODO check culling }; -Strip.prototype._initWebGL = function (renderer) { +Strip.prototype._initWebGL = function (renderer) +{ // build the strip! var gl = renderer.gl; @@ -118,7 +123,8 @@ gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this.indices, gl.STATIC_DRAW); }; -Strip.prototype._renderStrip = function (renderer) { +Strip.prototype._renderStrip = function (renderer) +{ var gl = renderer.gl; var projection = renderer.projection, offset = renderer.offset, @@ -137,7 +143,8 @@ gl.uniform2f(shader.offsetVector, -offset.x, -offset.y); gl.uniform1f(shader.alpha, this.worldAlpha); - if (!this.dirty) { + if (!this.dirty) + { gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexBuffer); gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); @@ -150,10 +157,12 @@ gl.activeTexture(gl.TEXTURE0); // check if a texture is dirty.. - if (this.texture.baseTexture._dirty[gl.id]) { + if (this.texture.baseTexture._dirty[gl.id]) + { renderer.updateTexture(this.texture.baseTexture); } - else { + else + { // bind the current texture gl.bindTexture(gl.TEXTURE_2D, this.texture.baseTexture._glTextures[gl.id]); } @@ -163,7 +172,8 @@ } - else { + else + { this.dirty = false; gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexBuffer); @@ -178,10 +188,12 @@ gl.activeTexture(gl.TEXTURE0); // check if a texture is dirty.. - if (this.texture.baseTexture._dirty[gl.id]) { + if (this.texture.baseTexture._dirty[gl.id]) + { renderer.updateTexture(this.texture.baseTexture); } - else { + else + { gl.bindTexture(gl.TEXTURE_2D, this.texture.baseTexture._glTextures[gl.id]); } @@ -203,27 +215,33 @@ * * @param renderer {CanvasRenderer} */ -Strip.prototype.renderCanvas = function (renderer) { +Strip.prototype.renderCanvas = function (renderer) +{ var context = renderer.context; var transform = this.worldTransform; - if (renderer.roundPixels) { + if (renderer.roundPixels) + { context.setTransform(transform.a, transform.b, transform.c, transform.d, transform.tx | 0, transform.ty | 0); } - else { + else + { context.setTransform(transform.a, transform.b, transform.c, transform.d, transform.tx, transform.ty); } - if (this.drawMode === Strip.DrawModes.TRIANGLE_STRIP) { + if (this.drawMode === Strip.DrawModes.TRIANGLE_STRIP) + { this._renderCanvasTriangleStrip(context); } - else { + else + { this._renderCanvasTriangles(context); } }; -Strip.prototype._renderCanvasTriangleStrip = function (context) { +Strip.prototype._renderCanvasTriangleStrip = function (context) +{ // draw triangles!! var vertices = this.vertices; var uvs = this.uvs; @@ -231,14 +249,16 @@ var length = vertices.length / 2; // this.count++; - for (var i = 0; i < length - 2; i++) { + for (var i = 0; i < length - 2; i++) + { // draw some triangles! var index = i * 2; this._renderCanvasDrawTriangle(context, vertices, uvs, index, (index + 2), (index + 4)); } }; -Strip.prototype._renderCanvasTriangles = function (context) { +Strip.prototype._renderCanvasTriangles = function (context) +{ // draw triangles!! var vertices = this.vertices; var uvs = this.uvs; @@ -247,14 +267,16 @@ var length = indices.length; // this.count++; - for (var i = 0; i < length; i += 3) { + for (var i = 0; i < length; i += 3) + { // draw some triangles! var index0 = indices[i] * 2, index1 = indices[i + 1] * 2, index2 = indices[i + 2] * 2; this._renderCanvasDrawTriangle(context, vertices, uvs, index0, index1, index2); } }; -Strip.prototype._renderCanvasDrawTriangle = function (context, vertices, uvs, index0, index1, index2) { +Strip.prototype._renderCanvasDrawTriangle = function (context, vertices, uvs, index0, index1, index2) +{ var textureSource = this.texture.baseTexture.source; var textureWidth = this.texture.width; var textureHeight = this.texture.height; @@ -265,7 +287,8 @@ var u0 = uvs[index0] * textureWidth, u1 = uvs[index1] * textureWidth, u2 = uvs[index2] * textureWidth; var v0 = uvs[index0 + 1] * textureHeight, v1 = uvs[index1 + 1] * textureHeight, v2 = uvs[index2 + 1] * textureHeight; - if (this.canvasPadding > 0) { + if (this.canvasPadding > 0) + { var paddingX = this.canvasPadding / this.worldTransform.a; var paddingY = this.canvasPadding / this.worldTransform.d; var centerX = (x0 + x1 + x2) / 3; @@ -332,7 +355,8 @@ * @param strip {Strip} The Strip to render * @private */ -Strip.prototype.renderStripFlat = function (strip) { +Strip.prototype.renderStripFlat = function (strip) +{ var context = this.context; var vertices = strip.vertices; @@ -340,7 +364,8 @@ // this.count++; context.beginPath(); - for (var i=1; i < length-2; i++) { + for (var i=1; i < length-2; i++) + { // draw some triangles! var index = i*2; @@ -358,7 +383,8 @@ }; /* -Strip.prototype.setTexture = function (texture) { +Strip.prototype.setTexture = function (texture) +{ //TODO SET THE TEXTURES //TODO VISIBILITY @@ -377,7 +403,8 @@ * @private */ -Strip.prototype.onTextureUpdate = function () { +Strip.prototype.onTextureUpdate = function () +{ this.updateFrame = true; }; @@ -387,7 +414,8 @@ * @param matrix {Matrix} the transformation matrix of the sprite * @return {Rectangle} the framing rectangle */ -Strip.prototype.getBounds = function (matrix) { +Strip.prototype.getBounds = function (matrix) +{ var worldTransform = matrix || this.worldTransform; var a = worldTransform.a; @@ -404,7 +432,8 @@ var minY = Infinity; var vertices = this.vertices; - for (var i = 0, n = vertices.length; i < n; i += 2) { + for (var i = 0, n = vertices.length; i < n; i += 2) + { var rawX = vertices[i], rawY = vertices[i + 1]; var x = (a * rawX) + (c * rawY) + tx; var y = (d * rawY) + (b * rawX) + ty; @@ -416,7 +445,8 @@ maxY = y > maxY ? y : maxY; } - if (minX === -Infinity || maxY === Infinity) { + if (minX === -Infinity || maxY === Infinity) + { return core.math.Rectangle.EMPTY; } diff --git a/src/extras/TilingSprite.js b/src/extras/TilingSprite.js index 3ac22df..31da393 100644 --- a/src/extras/TilingSprite.js +++ b/src/extras/TilingSprite.js @@ -10,7 +10,8 @@ * @param width {number} the width of the tiling sprite * @param height {number} the height of the tiling sprite */ -function TilingSprite(texture, width, height) { +function TilingSprite(texture, width, height) +{ core.Sprite.call( this, texture); /** @@ -86,10 +87,12 @@ * @memberof TilingSprite# */ width: { - get: function () { + get: function () + { return this._width; }, - set: function (value) { + set: function (value) + { this._width = value; } }, @@ -101,20 +104,25 @@ * @memberof TilingSprite# */ height: { - get: function () { + get: function () + { return this._height; }, - set: function (value) { + set: function (value) + { this._height = value; } }, texture: { - get: function () { + get: function () + { return this._texture; }, - set: function (value) { - if (this._texture === value) { + set: function (value) + { + if (this._texture === value) + { return; } @@ -130,51 +138,61 @@ * * @param renderer {WebGLRenderer} */ -TilingSprite.prototype.renderWebGL = function (renderer) { - if (!this.visible || this.alpha <= 0) { +TilingSprite.prototype.renderWebGL = function (renderer) +{ + if (!this.visible || this.alpha <= 0) + { return; } var i, j; - if (this._mask) { + if (this._mask) + { renderer.spriteBatch.stop(); renderer.maskManager.pushMask(this.mask, renderer); renderer.spriteBatch.start(); } - if (this._filters) { + if (this._filters) + { renderer.spriteBatch.flush(); renderer.filterManager.pushFilter(this._filterBlock); } - if (!this.tilingTexture || this.refreshTexture) { + if (!this.tilingTexture || this.refreshTexture) + { this.generateTilingTexture(true); - if (this.tilingTexture && this.tilingTexture.needsUpdate) { + if (this.tilingTexture && this.tilingTexture.needsUpdate) + { //TODO - tweaking renderer.updateTexture(this.tilingTexture.baseTexture); this.tilingTexture.needsUpdate = false; // this.tilingTexture._uvs = null; } } - else { + else + { renderer.spriteBatch.renderTilingSprite(this); } // simple render children! - for (i=0,j=this.children.length; i= 0; i--) { + for (var i = length - 1; i >= 0; i--) + { var child = children[i]; // push all interactive bits - if (child._interactive) { + if (child._interactive) + { iParent.interactiveChildren = true; //child.__iParent = iParent; this.interactiveItems.push(child); - if (child.children.length > 0) { + if (child.children.length > 0) + { this.collectInteractiveSprite(child, child); } } - else { + else + { child.__iParent = null; - if (child.children.length > 0) { + if (child.children.length > 0) + { this.collectInteractiveSprite(child, iParent); } } @@ -189,7 +196,8 @@ * @param [resolution=1] {number} THe resolution of the new element (relative to the canvas). * @private */ -InteractionManager.prototype.setTargetElement = function (element, resolution) { +InteractionManager.prototype.setTargetElement = function (element, resolution) +{ this.removeEvents(); this.interactionDOMElement = element; @@ -203,12 +211,15 @@ * * @private */ -InteractionManager.prototype.addEvents = function () { - if (!this.interactionDOMElement) { +InteractionManager.prototype.addEvents = function () +{ + if (!this.interactionDOMElement) + { return; } - if (window.navigator.msPointerEnabled) { + if (window.navigator.msPointerEnabled) + { this.interactionDOMElement.style['-ms-content-zooming'] = 'none'; this.interactionDOMElement.style['-ms-touch-action'] = 'none'; } @@ -230,12 +241,15 @@ * * @private */ -InteractionManager.prototype.removeEvents = function () { - if (!this.interactionDOMElement) { +InteractionManager.prototype.removeEvents = function () +{ + if (!this.interactionDOMElement) + { return; } - if (window.navigator.msPointerEnabled) { + if (window.navigator.msPointerEnabled) + { this.interactionDOMElement.style['-ms-content-zooming'] = ''; this.interactionDOMElement.style['-ms-touch-action'] = ''; } @@ -260,8 +274,10 @@ * * @private */ -InteractionManager.prototype.update = function () { - if (!this.interactionDOMElement) { +InteractionManager.prototype.update = function () +{ + if (!this.interactionDOMElement) + { return; } @@ -269,7 +285,8 @@ var now = Date.now(); var diff = now - this.last; diff = (diff * INTERACTION_FREQUENCY ) / 1000; - if (diff < 1) { + if (diff < 1) + { return; } @@ -280,7 +297,8 @@ // ok.. so mouse events?? // yes for now :) // OPTIMISE - how often to check?? - if (this.dirty) { + if (this.dirty) + { this.rebuildInteractiveGraph(); } @@ -289,7 +307,8 @@ var cursor = 'inherit'; var over = false; - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { var item = this.interactiveItems[i]; // OPTIMISATION - only calculate every time if the mousemove function exists.. @@ -302,26 +321,34 @@ this.mouse.target = item; // ok so deal with interactions.. // looks like there was a hit! - if (item.__hit && !over) { - if (item.buttonMode) { + if (item.__hit && !over) + { + if (item.buttonMode) + { cursor = item.defaultCursor; } - if (!item.interactiveChildren) { + if (!item.interactiveChildren) + { over = true; } - if (!item.__isOver) { - if (item.mouseover) { + if (!item.__isOver) + { + if (item.mouseover) + { item.mouseover (this.mouse); } item.__isOver = true; } } - else { - if (item.__isOver) { + else + { + if (item.__isOver) + { // roll out! - if (item.mouseout) { + if (item.mouseout) + { item.mouseout (this.mouse); } item.__isOver = false; @@ -329,7 +356,8 @@ } } - if (this.currentCursorStyle !== cursor) { + if (this.currentCursorStyle !== cursor) + { this.currentCursorStyle = cursor; this.interactionDOMElement.style.cursor = cursor; } @@ -338,18 +366,21 @@ /** * @private */ -InteractionManager.prototype.rebuildInteractiveGraph = function () { +InteractionManager.prototype.rebuildInteractiveGraph = function () +{ this.dirty = false; var len = this.interactiveItems.length; - for (var i = 0; i < len; i++) { + for (var i = 0; i < len; i++) + { this.interactiveItems[i].interactiveChildren = false; } this.interactiveItems.length = 0; - if (this.stage.interactive) { + if (this.stage.interactive) + { this.interactiveItems.push(this.stage); } @@ -363,8 +394,10 @@ * @param event {Event} The DOM event of the mouse moving * @private */ -InteractionManager.prototype.onMouseMove = function (event) { - if (this.dirty) { +InteractionManager.prototype.onMouseMove = function (event) +{ + if (this.dirty) + { this.rebuildInteractiveGraph(); } @@ -378,11 +411,13 @@ var length = this.interactiveItems.length; - for (var i = 0; i < length; i++) { + for (var i = 0; i < length; i++) + { var item = this.interactiveItems[i]; // Call the function! - if (item.mousemove) { + if (item.mousemove) + { item.mousemove(this.mouse); } } @@ -394,14 +429,17 @@ * @param event {Event} The DOM event of a mouse button being pressed down * @private */ -InteractionManager.prototype.onMouseDown = function (event) { - if (this.dirty) { +InteractionManager.prototype.onMouseDown = function (event) +{ + if (this.dirty) + { this.rebuildInteractiveGraph(); } this.mouse.originalEvent = event; - if (AUTO_PREVENT_DEFAULT) { + if (AUTO_PREVENT_DEFAULT) + { this.mouse.originalEvent.preventDefault(); } @@ -420,22 +458,27 @@ // while // hit test - for (var i = 0; i < length; i++) { + for (var i = 0; i < length; i++) + { var item = this.interactiveItems[i]; - if (item[downFunction] || item[clickFunction]) { + if (item[downFunction] || item[clickFunction]) + { item[buttonIsDown] = true; item.__hit = this.hitTest(item, this.mouse); - if (item.__hit) { + if (item.__hit) + { //call the function! - if (item[downFunction]) { + if (item[downFunction]) + { item[downFunction](this.mouse); } item[isDown] = true; // just the one! - if (!item.interactiveChildren) { + if (!item.interactiveChildren) + { break; } } @@ -449,8 +492,10 @@ * @param event {Event} The DOM event of a mouse being moved out * @private */ -InteractionManager.prototype.onMouseOut = function (event) { - if (this.dirty) { +InteractionManager.prototype.onMouseOut = function (event) +{ + if (this.dirty) + { this.rebuildInteractiveGraph(); } @@ -460,11 +505,14 @@ this.interactionDOMElement.style.cursor = 'inherit'; - for (var i = 0; i < length; i++) { + for (var i = 0; i < length; i++) + { var item = this.interactiveItems[i]; - if (item.__isOver) { + if (item.__isOver) + { this.mouse.target = item; - if (item.mouseout) { + if (item.mouseout) + { item.mouseout(this.mouse); } item.__isOver = false; @@ -484,8 +532,10 @@ * @param event {Event} The DOM event of a mouse button being released * @private */ -InteractionManager.prototype.onMouseUp = function (event) { - if (this.dirty) { +InteractionManager.prototype.onMouseUp = function (event) +{ + if (this.dirty) + { this.rebuildInteractiveGraph(); } @@ -502,30 +552,40 @@ var upOutsideFunction = isRightButton ? 'rightupoutside' : 'mouseupoutside'; var isDown = isRightButton ? '__isRightDown' : '__isDown'; - for (var i = 0; i < length; i++) { + for (var i = 0; i < length; i++) + { var item = this.interactiveItems[i]; - if (item[clickFunction] || item[upFunction] || item[upOutsideFunction]) { + if (item[clickFunction] || item[upFunction] || item[upOutsideFunction]) + { item.__hit = this.hitTest(item, this.mouse); - if (item.__hit && !up) { + if (item.__hit && !up) + { //call the function! - if (item[upFunction]) { + if (item[upFunction]) + { item[upFunction](this.mouse); } - if (item[isDown]) { - if (item[clickFunction]) { + if (item[isDown]) + { + if (item[clickFunction]) + { item[clickFunction](this.mouse); } } - if (!item.interactiveChildren) { + if (!item.interactiveChildren) + { up = true; } } - else { - if (item[isDown]) { - if (item[upOutsideFunction]) { + else + { + if (item[isDown]) + { + if (item[upOutsideFunction]) + { item[upOutsideFunction](this.mouse); } } @@ -543,10 +603,12 @@ * @param interactionData {InteractionData} The interactionData object to update in the case there is a hit * @private */ -InteractionManager.prototype.hitTest = function (item, interactionData) { +InteractionManager.prototype.hitTest = function (item, interactionData) +{ var global = interactionData.global; - if (!item.worldVisible) { + if (!item.worldVisible) + { return false; } @@ -560,37 +622,46 @@ interactionData.target = item; //a sprite or display object with a hit area defined - if (item.hitArea && item.hitArea.contains) { + if (item.hitArea && item.hitArea.contains) + { return item.hitArea.contains(x, y); } // a sprite with no hitarea defined - else if (item instanceof core.Sprite) { + else if (item instanceof core.Sprite) + { var width = item.texture.frame.width; var height = item.texture.frame.height; var x1 = -width * item.anchor.x; var y1; - if (x > x1 && x < x1 + width) { + if (x > x1 && x < x1 + width) + { y1 = -height * item.anchor.y; - if (y > y1 && y < y1 + height) { + if (y > y1 && y < y1 + height) + { // set the target property if a hit is true! return true; } } } - else if (item instanceof core.Graphics) { + else if (item instanceof core.Graphics) + { var graphicsData = item.graphicsData; - for (i = 0; i < graphicsData.length; i++) { + for (i = 0; i < graphicsData.length; i++) + { var data = graphicsData[i]; - if (!data.fill) { + if (!data.fill) + { continue; } // only deal with fills.. - if (data.shape) { - if (data.shape.contains(x, y)) { + if (data.shape) + { + if (data.shape.contains(x, y)) + { //interactionData.target = item; return true; } @@ -600,10 +671,12 @@ var length = item.children.length; - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { var tempItem = item.children[i]; var hit = this.hitTest(tempItem, interactionData); - if (hit) { + if (hit) + { // hmm.. TODO SET CORRECT TARGET? interactionData.target = item; return true; @@ -618,8 +691,10 @@ * @param event {Event} The DOM event of a touch moving across the renderer view * @private */ -InteractionManager.prototype.onTouchMove = function (event) { - if (this.dirty) { +InteractionManager.prototype.onTouchMove = function (event) +{ + if (this.dirty) + { this.rebuildInteractiveGraph(); } @@ -628,7 +703,8 @@ var touchData; var i = 0; - for (i = 0; i < changedTouches.length; i++) { + for (i = 0; i < changedTouches.length; i++) + { var touchEvent = changedTouches[i]; touchData = this.touches[touchEvent.identifier]; touchData.originalEvent = event; @@ -636,15 +712,18 @@ // update the touch position touchData.global.x = ( (touchEvent.clientX - rect.left) * (this.interactionDOMElement.width / rect.width) ) / this.resolution; touchData.global.y = ( (touchEvent.clientY - rect.top) * (this.interactionDOMElement.height / rect.height) ) / this.resolution; - if (navigator.isCocoonJS && !rect.left && !rect.top && !event.target.style.width && !event.target.style.height) { + if (navigator.isCocoonJS && !rect.left && !rect.top && !event.target.style.width && !event.target.style.height) + { //Support for CocoonJS fullscreen scale modes touchData.global.x = touchEvent.clientX; touchData.global.y = touchEvent.clientY; } - for (var j = 0; j < this.interactiveItems.length; j++) { + for (var j = 0; j < this.interactiveItems.length; j++) + { var item = this.interactiveItems[j]; - if (item.touchmove && item.__touchData && item.__touchData[touchEvent.identifier]) { + if (item.touchmove && item.__touchData && item.__touchData[touchEvent.identifier]) + { item.touchmove(touchData); } } @@ -657,23 +736,28 @@ * @param event {Event} The DOM event of a touch starting on the renderer view * @private */ -InteractionManager.prototype.onTouchStart = function (event) { - if (this.dirty) { +InteractionManager.prototype.onTouchStart = function (event) +{ + if (this.dirty) + { this.rebuildInteractiveGraph(); } var rect = this.interactionDOMElement.getBoundingClientRect(); - if (AUTO_PREVENT_DEFAULT) { + if (AUTO_PREVENT_DEFAULT) + { event.preventDefault(); } var changedTouches = event.changedTouches; - for (var i=0; i < changedTouches.length; i++) { + for (var i=0; i < changedTouches.length; i++) + { var touchEvent = changedTouches[i]; var touchData = this.pool.pop(); - if (!touchData) { + if (!touchData) + { touchData = new InteractionData(); } @@ -682,7 +766,8 @@ this.touches[touchEvent.identifier] = touchData; touchData.global.x = ( (touchEvent.clientX - rect.left) * (this.interactionDOMElement.width / rect.width) ) / this.resolution; touchData.global.y = ( (touchEvent.clientY - rect.top) * (this.interactionDOMElement.height / rect.height) ) / this.resolution; - if (navigator.isCocoonJS && !rect.left && !rect.top && !event.target.style.width && !event.target.style.height) { + if (navigator.isCocoonJS && !rect.left && !rect.top && !event.target.style.width && !event.target.style.height) + { //Support for CocoonJS fullscreen scale modes touchData.global.x = touchEvent.clientX; touchData.global.y = touchEvent.clientY; @@ -690,15 +775,19 @@ var length = this.interactiveItems.length; - for (var j = 0; j < length; j++) { + for (var j = 0; j < length; j++) + { var item = this.interactiveItems[j]; - if (item.touchstart || item.tap) { + if (item.touchstart || item.tap) + { item.__hit = this.hitTest(item, touchData); - if (item.__hit) { + if (item.__hit) + { //call the function! - if (item.touchstart) { + if (item.touchstart) + { item.touchstart(touchData); } @@ -706,7 +795,8 @@ item.__touchData = item.__touchData || {}; item.__touchData[touchEvent.identifier] = touchData; - if (!item.interactiveChildren) { + if (!item.interactiveChildren) + { break; } } @@ -721,31 +811,37 @@ * @param event {Event} The DOM event of a touch ending on the renderer view * @private */ -InteractionManager.prototype.onTouchEnd = function (event) { - if (this.dirty) { +InteractionManager.prototype.onTouchEnd = function (event) +{ + if (this.dirty) + { this.rebuildInteractiveGraph(); } var rect = this.interactionDOMElement.getBoundingClientRect(); var changedTouches = event.changedTouches; - for (var i=0; i < changedTouches.length; i++) { + for (var i=0; i < changedTouches.length; i++) + { var touchEvent = changedTouches[i]; var touchData = this.touches[touchEvent.identifier]; var up = false; touchData.global.x = ( (touchEvent.clientX - rect.left) * (this.interactionDOMElement.width / rect.width) ) / this.resolution; touchData.global.y = ( (touchEvent.clientY - rect.top) * (this.interactionDOMElement.height / rect.height) ) / this.resolution; - if (navigator.isCocoonJS && !rect.left && !rect.top && !event.target.style.width && !event.target.style.height) { + if (navigator.isCocoonJS && !rect.left && !rect.top && !event.target.style.width && !event.target.style.height) + { //Support for CocoonJS fullscreen scale modes touchData.global.x = touchEvent.clientX; touchData.global.y = touchEvent.clientY; } var length = this.interactiveItems.length; - for (var j = 0; j < length; j++) { + for (var j = 0; j < length; j++) + { var item = this.interactiveItems[j]; - if (item.__touchData && item.__touchData[touchEvent.identifier]) { + if (item.__touchData && item.__touchData[touchEvent.identifier]) + { item.__hit = this.hitTest(item, item.__touchData[touchEvent.identifier]); @@ -753,20 +849,27 @@ touchData.originalEvent = event; // hitTest?? - if (item.touchend || item.tap) { - if (item.__hit && !up) { - if (item.touchend) { + if (item.touchend || item.tap) + { + if (item.__hit && !up) + { + if (item.touchend) + { item.touchend(touchData); } - if (item.__isDown && item.tap) { + if (item.__isDown && item.tap) + { item.tap(touchData); } - if (!item.interactiveChildren) { + if (!item.interactiveChildren) + { up = true; } } - else { - if (item.__isDown && item.touchendoutside) { + else + { + if (item.__isDown && item.touchendoutside) + { item.touchendoutside(touchData); } } diff --git a/src/loaders/AssetLoader.js b/src/loaders/AssetLoader.js index 20da0cf..c4dba1c 100644 --- a/src/loaders/AssetLoader.js +++ b/src/loaders/AssetLoader.js @@ -21,7 +21,8 @@ * data formats include 'xml' and 'fnt'. * @param crossorigin {boolean} Whether requests should be treated as crossorigin */ -function AssetLoader(assetURLs, crossorigin) { +function AssetLoader(assetURLs, crossorigin) +{ /** * The array of asset URLs that are going to be loaded * @@ -76,16 +77,19 @@ * * @param str {string} the name of the asset */ -AssetLoader.prototype._getDataType = function (str) { +AssetLoader.prototype._getDataType = function (str) +{ var test = 'data:'; var start = str.slice(0, test.length).toLowerCase(); - if (start === test) { + if (start === test) + { var data = str.slice(test.length); var sepIdx = data.indexOf(','); // check for malformed data URI scheme - if (sepIdx === -1) { + if (sepIdx === -1) + { return null; } @@ -94,7 +98,8 @@ //We might need to handle some special cases here... //standardize text/plain to 'txt' file extension - if (!info || info.toLowerCase() === 'text/plain') { + if (!info || info.toLowerCase() === 'text/plain') + { return 'txt'; } @@ -109,27 +114,32 @@ * Starts loading the assets sequentially * */ -AssetLoader.prototype.load = function () { +AssetLoader.prototype.load = function () +{ var scope = this; - function onLoad(evt) { + function onLoad(evt) + { scope.onAssetLoaded(evt.data.content); } this.loadCount = this.assetURLs.length; - for (var i=0; i < this.assetURLs.length; i++) { + for (var i=0; i < this.assetURLs.length; i++) + { var fileName = this.assetURLs[i]; //first see if we have a data URI scheme.. var fileType = this._getDataType(fileName); //if not, assume it's a file URI - if (!fileType) { + if (!fileType) + { fileType = fileName.split('?').shift().split('.').pop().toLowerCase(); } var Constructor = this.loadersByType[fileType]; - if (!Constructor) { + if (!Constructor) + { throw new Error(fileType + ' is an unsupported file type'); } @@ -145,18 +155,22 @@ * * @private */ -AssetLoader.prototype.onAssetLoaded = function (loader) { +AssetLoader.prototype.onAssetLoaded = function (loader) +{ this.loadCount--; this.emit('onProgress', { content: this, loader: loader }); - if (this.onProgress) { + if (this.onProgress) + { this.onProgress(loader); } - if (!this.loadCount) { + if (!this.loadCount) + { this.emit('onComplete', { content: this }); - if (this.onComplete) { + if (this.onComplete) + { this.onComplete(); } } diff --git a/src/loaders/AtlasLoader.js b/src/loaders/AtlasLoader.js index 5eda286..3aec9e2 100644 --- a/src/loaders/AtlasLoader.js +++ b/src/loaders/AtlasLoader.js @@ -15,7 +15,8 @@ * @param url {String} The url of the JSON file * @param crossorigin {boolean} Whether requests should be treated as crossorigin */ -function AtlasLoader(url, crossorigin) { +function AtlasLoader(url, crossorigin) +{ this.url = url; this.baseUrl = url.replace(/[^\/]*$/, ''); this.crossorigin = crossorigin; @@ -31,13 +32,15 @@ * Starts loading the JSON file * */ -AtlasLoader.prototype.load = function () { +AtlasLoader.prototype.load = function () +{ this.ajaxRequest = new core.utils.AjaxRequest(); this.ajaxRequest.onreadystatechange = this.onAtlasLoaded.bind(this); this.ajaxRequest.open('GET', this.url, true); - if (this.ajaxRequest.overrideMimeType) { + if (this.ajaxRequest.overrideMimeType) + { this.ajaxRequest.overrideMimeType('application/json'); } @@ -49,9 +52,12 @@ * * @private */ -AtlasLoader.prototype.onAtlasLoaded = function () { - if (this.ajaxRequest.readyState === 4) { - if (this.ajaxRequest.status === 200 || window.location.href.indexOf('http') === -1) { +AtlasLoader.prototype.onAtlasLoaded = function () +{ + if (this.ajaxRequest.readyState === 4) + { + if (this.ajaxRequest.status === 200 || window.location.href.indexOf('http') === -1) + { this.atlas = { meta : { image : [] @@ -70,34 +76,44 @@ selfOnLoaded = this.onLoaded.bind(this); // parser without rotation support yet! - for (i = 0; i < result.length; i++) { + for (i = 0; i < result.length; i++) + { result[i] = result[i].replace(/^\s+|\s+$/g, ''); - if (result[i] === '') { + if (result[i] === '') + { nameInNextLine = i+1; } - if (result[i].length > 0) { - if (nameInNextLine === i) { + if (result[i].length > 0) + { + if (nameInNextLine === i) + { this.atlas.meta.image.push(result[i]); currentImageId = this.atlas.meta.image.length - 1; this.atlas.frames.push({}); lineCount = -3; - } else if (lineCount > 0) { - if (lineCount % 7 === 1) { // frame name - if (currentFrame != null) { //jshint ignore:line + } else if (lineCount > 0) + { + if (lineCount % 7 === 1) + { // frame name + if (currentFrame != null) + { //jshint ignore:line this.atlas.frames[currentImageId][currentFrame.name] = currentFrame; } currentFrame = { name: result[i], frame : {} }; } else { var text = result[i].split(' '); - if (lineCount % 7 === 3) { // position + if (lineCount % 7 === 3) + { // position currentFrame.frame.x = Number(text[1].replace(',', '')); currentFrame.frame.y = Number(text[2]); - } else if (lineCount % 7 === 4) { // size + } else if (lineCount % 7 === 4) + { // size currentFrame.frame.w = Number(text[1].replace(',', '')); currentFrame.frame.h = Number(text[2]); - } else if (lineCount % 7 === 5) { // real size + } else if (lineCount % 7 === 5) + { // real size var realSize = { x : 0, y : 0, @@ -105,7 +121,8 @@ h : Number(text[2]) }; - if (realSize.w > currentFrame.frame.w || realSize.h > currentFrame.frame.h) { + if (realSize.w > currentFrame.frame.w || realSize.h > currentFrame.frame.h) + { currentFrame.trimmed = true; currentFrame.realSize = realSize; } else { @@ -118,28 +135,34 @@ } } - if (currentFrame != null) { //jshint ignore:line + if (currentFrame != null) + { //jshint ignore:line this.atlas.frames[currentImageId][currentFrame.name] = currentFrame; } - if (this.atlas.meta.image.length > 0) { + if (this.atlas.meta.image.length > 0) + { this.images = []; - for (j = 0; j < this.atlas.meta.image.length; j++) { + for (j = 0; j < this.atlas.meta.image.length; j++) + { // sprite sheet var textureUrl = this.baseUrl + this.atlas.meta.image[j]; var frameData = this.atlas.frames[j]; this.images.push(new ImageLoader(textureUrl, this.crossorigin)); - for (i in frameData) { + for (i in frameData) + { var rect = frameData[i].frame; - if (rect) { + if (rect) + { core.utils.TextureCache[i] = new core.Texture(this.images[j].texture.baseTexture, { x: rect.x, y: rect.y, width: rect.w, height: rect.h }); - if (frameData[i].trimmed) { + if (frameData[i].trimmed) + { core.utils.TextureCache[i].realSize = frameData[i].realSize; // trim in pixi not supported yet, todo update trim properties if it is done ... core.utils.TextureCache[i].trim.x = 0; @@ -150,7 +173,8 @@ } this.currentImageId = 0; - for (j = 0; j < this.images.length; j++) { + for (j = 0; j < this.images.length; j++) + { this.images[j].on('loaded', selfOnLoaded); } this.images[this.currentImageId].load(); @@ -170,8 +194,10 @@ * * @private */ -AtlasLoader.prototype.onLoaded = function () { - if (this.images.length - 1 > this.currentImageId) { +AtlasLoader.prototype.onLoaded = function () +{ + if (this.images.length - 1 > this.currentImageId) + { this.currentImageId++; this.images[this.currentImageId].load(); } else { @@ -185,6 +211,7 @@ * * @private */ -AtlasLoader.prototype.onError = function () { +AtlasLoader.prototype.onError = function () +{ this.emit('error', { content: this }); }; diff --git a/src/loaders/BitmapFontLoader.js b/src/loaders/BitmapFontLoader.js index 8641760..13e5c1b 100644 --- a/src/loaders/BitmapFontLoader.js +++ b/src/loaders/BitmapFontLoader.js @@ -13,7 +13,8 @@ * @param url {String} The url of the sprite sheet JSON file * @param crossorigin {boolean} Whether requests should be treated as crossorigin */ -function BitmapFontLoader(url, crossorigin) { +function BitmapFontLoader(url, crossorigin) +{ /** * The url of the bitmap font data * @@ -54,13 +55,15 @@ * Loads the XML font data * */ -BitmapFontLoader.prototype.load = function () { +BitmapFontLoader.prototype.load = function () +{ this.ajaxRequest = new core.utils.AjaxRequest(); this.ajaxRequest.onreadystatechange = this.onXMLLoaded.bind(this); this.ajaxRequest.open('GET', this.url, true); - if (this.ajaxRequest.overrideMimeType) { + if (this.ajaxRequest.overrideMimeType) + { this.ajaxRequest.overrideMimeType('application/xml'); } @@ -72,12 +75,17 @@ * * @private */ -BitmapFontLoader.prototype.onXMLLoaded = function () { - if (this.ajaxRequest.readyState === 4) { - if (this.ajaxRequest.status === 200 || window.location.protocol.indexOf('http') === -1) { +BitmapFontLoader.prototype.onXMLLoaded = function () +{ + if (this.ajaxRequest.readyState === 4) + { + if (this.ajaxRequest.status === 200 || window.location.protocol.indexOf('http') === -1) + { var responseXML = this.ajaxRequest.responseXML; - if (!responseXML || /MSIE 9/i.test(navigator.userAgent) || navigator.isCocoonJS) { - if (typeof(window.DOMParser) === 'function') { + if (!responseXML || /MSIE 9/i.test(navigator.userAgent) || navigator.isCocoonJS) + { + if (typeof(window.DOMParser) === 'function') + { var domparser = new DOMParser(); responseXML = domparser.parseFromString(this.ajaxRequest.responseText, 'text/xml'); } else { @@ -102,7 +110,8 @@ //parse letters var letters = responseXML.getElementsByTagName('char'); - for (var i = 0; i < letters.length; i++) { + for (var i = 0; i < letters.length; i++) + { var charCode = parseInt(letters[i].getAttribute('id'), 10); var textureRect = new core.math.Rectangle( @@ -124,7 +133,8 @@ //parse kernings var kernings = responseXML.getElementsByTagName('kerning'); - for (i = 0; i < kernings.length; i++) { + for (i = 0; i < kernings.length; i++) + { var first = parseInt(kernings[i].getAttribute('first'), 10); var second = parseInt(kernings[i].getAttribute('second'), 10); var amount = parseInt(kernings[i].getAttribute('amount'), 10); @@ -146,6 +156,7 @@ * * @private */ -BitmapFontLoader.prototype.onLoaded = function () { +BitmapFontLoader.prototype.onLoaded = function () +{ this.emit('loaded', { content: this }); }; diff --git a/src/loaders/ImageLoader.js b/src/loaders/ImageLoader.js index e3ff493..16ee7c8 100644 --- a/src/loaders/ImageLoader.js +++ b/src/loaders/ImageLoader.js @@ -11,7 +11,8 @@ * @param url {String} The url of the image * @param crossorigin {boolean} Whether requests should be treated as crossorigin */ -function ImageLoader(url, crossorigin) { +function ImageLoader(url, crossorigin) +{ /** * The texture being loaded * @@ -39,12 +40,15 @@ * Loads image or takes it from cache * */ -ImageLoader.prototype.load = function () { - if (!this.texture.baseTexture.hasLoaded) { +ImageLoader.prototype.load = function () +{ + if (!this.texture.baseTexture.hasLoaded) + { this.texture.baseTexture.on('loaded', this.onLoaded.bind(this)); this.texture.baseTexture.on('error', this.onError.bind(this)); } - else { + else + { this.onLoaded(); } }; @@ -54,7 +58,8 @@ * * @private */ -ImageLoader.prototype.onLoaded = function () { +ImageLoader.prototype.onLoaded = function () +{ this.emit('loaded', { content: this }); }; @@ -64,7 +69,8 @@ * @method onError * @private */ -ImageLoader.prototype.onError = function () { +ImageLoader.prototype.onError = function () +{ this.emit('error', { content: this }); }; @@ -75,15 +81,18 @@ * @param frameHeight {number} height of each frame * @param textureName {String} if given, the frames will be cached in - format */ -ImageLoader.prototype.loadFramedSpriteSheet = function (frameWidth, frameHeight, textureName) { +ImageLoader.prototype.loadFramedSpriteSheet = function (frameWidth, frameHeight, textureName) +{ this.frames = []; var cols = Math.floor(this.texture.width / frameWidth); var rows = Math.floor(this.texture.height / frameHeight); var i=0; - for (var y = 0; y < rows; ++y) { - for (var x = 0; x < cols; ++x, ++i) { + for (var y = 0; y < rows; ++y) + { + for (var x = 0; x < cols; ++x, ++i) + { var texture = new core.Texture( this.texture.baseTexture, new core.math.Rectangle( @@ -96,7 +105,8 @@ this.frames.push(texture); - if (textureName) { + if (textureName) + { core.utils.TextureCache[textureName + '-' + i] = texture; } } diff --git a/src/loaders/JsonLoader.js b/src/loaders/JsonLoader.js index 3279f40..7aabeb4 100644 --- a/src/loaders/JsonLoader.js +++ b/src/loaders/JsonLoader.js @@ -14,7 +14,8 @@ * @param url {String} The url of the JSON file * @param crossorigin {boolean} Whether requests should be treated as crossorigin */ -function JsonLoader(url, crossorigin) { +function JsonLoader(url, crossorigin) +{ /** * The url of the bitmap font data * @@ -56,8 +57,10 @@ * Loads the JSON data * */ -JsonLoader.prototype.load = function () { - if (window.XDomainRequest && this.crossorigin) { +JsonLoader.prototype.load = function () +{ + if (window.XDomainRequest && this.crossorigin) + { this.ajaxRequest = new window.XDomainRequest(); // XDomainRequest has a few quirks. Occasionally it will abort requests @@ -68,15 +71,19 @@ this.ajaxRequest.onerror = this.onError.bind(this); this.ajaxRequest.ontimeout = this.onError.bind(this); - this.ajaxRequest.onprogress = function () {}; + this.ajaxRequest.onprogress = function () + {}; this.ajaxRequest.onload = this.onJSONLoaded.bind(this); } - else { - if (window.XMLHttpRequest) { + else + { + if (window.XMLHttpRequest) + { this.ajaxRequest = new window.XMLHttpRequest(); } - else { + else + { this.ajaxRequest = new window.ActiveXObject('Microsoft.XMLHTTP'); } @@ -93,8 +100,10 @@ * * @private */ -JsonLoader.prototype.onReadyStateChanged = function () { - if (this.ajaxRequest.readyState === 4 && (this.ajaxRequest.status === 200 || window.location.href.indexOf('http') === -1)) { +JsonLoader.prototype.onReadyStateChanged = function () +{ + if (this.ajaxRequest.readyState === 4 && (this.ajaxRequest.status === 200 || window.location.href.indexOf('http') === -1)) + { this.onJSONLoaded(); } }; @@ -104,15 +113,18 @@ * * @private */ -JsonLoader.prototype.onJSONLoaded = function () { - if (!this.ajaxRequest.responseText) { +JsonLoader.prototype.onJSONLoaded = function () +{ + if (!this.ajaxRequest.responseText) + { this.onError(); return; } this.json = JSON.parse(this.ajaxRequest.responseText); - if (this.json.frames) { + if (this.json.frames) + { // sprite sheet var textureUrl = this.baseUrl + this.json.meta.image; var image = new ImageLoader(textureUrl, this.crossorigin); @@ -122,16 +134,19 @@ image.addEventListener('loaded', this.onLoaded.bind(this)); image.addEventListener('error', this.onError.bind(this)); - for (var i in frameData) { + for (var i in frameData) + { var rect = frameData[i].frame; - if (rect) { + if (rect) + { var textureSize = new core.math.Rectangle(rect.x, rect.y, rect.w, rect.h); var crop = textureSize.clone(); var trim = null; // Check to see if the sprite is trimmed - if (frameData[i].trimmed) { + if (frameData[i].trimmed) + { var actualSize = frameData[i].sourceSize; var realSize = frameData[i].spriteSourceSize; trim = new core.math.Rectangle(realSize.x, realSize.y, actualSize.w, actualSize.h); @@ -143,12 +158,15 @@ image.load(); } - else if (this.json.bones) { + else if (this.json.bones) + { // check if the json was loaded before - if (core.utils.AnimCache[this.url]) { + if (core.utils.AnimCache[this.url]) + { this.onLoaded(); } - else { + else + { /** * use a bit of hackery to load the atlas file, here we assume that the .json, .atlas and .png files * that correspond to the spine file are in the same base URL and that the .json and .atlas files @@ -159,9 +177,11 @@ // save a copy of the current object for future reference // var originalLoader = this; // before loading the file, replace the "onJSONLoaded" function for our own // - atlasLoader.onJSONLoaded = function () { + atlasLoader.onJSONLoaded = function () + { // at this point "this" points at the atlasLoader (JsonLoader) instance // - if (!this.ajaxRequest.responseText) { + if (!this.ajaxRequest.responseText) + { this.onError(); // FIXME: hmm, this is funny because we are not responding to errors yet return; } @@ -179,14 +199,18 @@ originalLoader.spineAtlas = spineAtlas; originalLoader.spineAtlasLoader = atlasLoader; // wait for textures to finish loading if needed - if (textureLoader.loadingCount > 0) { - textureLoader.addEventListener('loadedBaseTexture', function (evt){ - if (evt.content.content.loadingCount <= 0) { + if (textureLoader.loadingCount > 0) + { + textureLoader.addEventListener('loadedBaseTexture', function (evt) + { + if (evt.content.content.loadingCount <= 0) + { originalLoader.onLoaded(); } }); } - else { + else + { originalLoader.onLoaded(); } }; @@ -194,7 +218,8 @@ atlasLoader.load(); } } - else { + else + { this.onLoaded(); } }; @@ -204,7 +229,8 @@ * * @private */ -JsonLoader.prototype.onLoaded = function () { +JsonLoader.prototype.onLoaded = function () +{ this.loaded = true; this.dispatchEvent({ type: 'loaded', @@ -217,7 +243,8 @@ * * @private */ -JsonLoader.prototype.onError = function () { +JsonLoader.prototype.onError = function () +{ this.dispatchEvent({ type: 'error', diff --git a/src/core/display/DisplayObject.js b/src/core/display/DisplayObject.js index 66ebc3c..20e778c 100644 --- a/src/core/display/DisplayObject.js +++ b/src/core/display/DisplayObject.js @@ -7,7 +7,8 @@ * @class * @namespace PIXI */ -function DisplayObject() { +function DisplayObject() +{ /** * The coordinate of the object relative to the local coordinates of the parent. * @@ -152,10 +153,12 @@ * @memberof DisplayObject# */ x: { - get: function () { + get: function () + { return this.position.x; }, - set: function (value) { + set: function (value) + { this.position.x = value; } }, @@ -167,10 +170,12 @@ * @memberof DisplayObject# */ y: { - get: function () { + get: function () + { return this.position.y; }, - set: function (value) { + set: function (value) + { this.position.y = value; } }, @@ -183,11 +188,13 @@ * @readonly */ worldVisible: { - get: function () { + get: function () + { var item = this; do { - if (!item.visible) { + if (!item.visible) + { return false; } @@ -207,17 +214,21 @@ * @memberof DisplayObject# */ mask: { - get: function () { + get: function () + { return this._mask; }, - set: function (value) { - if (this._mask) { + set: function (value) + { + if (this._mask) + { this._mask.isMask = false; } this._mask = value; - if (this._mask) { + if (this._mask) + { this._mask.isMask = true; } } @@ -232,18 +243,23 @@ * @memberof DisplayObject# */ filters: { - get: function () { + get: function () + { return this._filters; }, - set: function (value) { - if (value) { + set: function (value) + { + if (value) + { // now put all the passes in one place.. var passes = []; - for (var i = 0; i < value.length; i++) { + for (var i = 0; i < value.length; i++) + { var filterPasses = value[i].passes; - for (var j = 0; j < filterPasses.length; j++) { + for (var j = 0; j < filterPasses.length; j++) + { passes.push(filterPasses[j]); } } @@ -264,8 +280,9 @@ * * @private */ -DisplayObject.prototype.updateTransform = function () { - +DisplayObject.prototype.updateTransform = function () +{ + // create some matrix refs for easy access var pt = this.parent.worldTransform; var wt = this.worldTransform; @@ -274,9 +291,11 @@ var a, b, c, d, tx, ty; // so if rotation is between 0 then we can simplify the multiplication process.. - if (this.rotation % math.PI_2) { + if (this.rotation % math.PI_2) + { // 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) { + if (this.rotation !== this.rotationCache) + { this.rotationCache = this.rotation; this._sr = Math.sin(this.rotation); this._cr = Math.cos(this.rotation); @@ -291,7 +310,8 @@ ty = this.position.y; // check for pivot.. not often used so geared towards that fact! - if (this.pivot.x || this.pivot.y) { + 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; } @@ -304,7 +324,8 @@ wt.tx = tx * pt.a + ty * pt.c + pt.tx; wt.ty = tx * pt.b + ty * pt.d + pt.ty; } - else { + else + { // lets do the fast version as we know there is no rotation.. a = this.scale.x; d = this.scale.y; @@ -333,7 +354,8 @@ * @param matrix {Matrix} * @return {Rectangle} the rectangular bounding area */ -DisplayObject.prototype.getBounds = function (/* matrix */) { +DisplayObject.prototype.getBounds = function (/* matrix */) +{ return math.Rectangle.EMPTY; }; @@ -342,7 +364,8 @@ * * @return {Rectangle} the rectangular bounding area */ -DisplayObject.prototype.getLocalBounds = function () { +DisplayObject.prototype.getLocalBounds = function () +{ return this.getBounds(math.Matrix.IDENTITY); }; @@ -352,7 +375,8 @@ * @param position {Point} The world origin to calculate from * @return {Point} A point object representing the position of this object */ -DisplayObject.prototype.toGlobal = function (position) { +DisplayObject.prototype.toGlobal = function (position) +{ // don't need to u[date the lot this.displayObjectUpdateTransform(); return this.worldTransform.apply(position); @@ -365,8 +389,10 @@ * @param [from] {DisplayObject} The DisplayObject to calculate the global position from * @return {Point} A point object representing the position of this object */ -DisplayObject.prototype.toLocal = function (position, from) { - if (from) { +DisplayObject.prototype.toLocal = function (position, from) +{ + if (from) + { position = from.toGlobal(position); } @@ -381,7 +407,8 @@ * @param renderer {WebGLRenderer} The renderer * @private */ -DisplayObject.prototype.renderWebGL = function (/* renderer */) { +DisplayObject.prototype.renderWebGL = function (/* renderer */) +{ // OVERWRITE; }; @@ -391,6 +418,7 @@ * @param renderer {CanvasRenderer} The renderer * @private */ -DisplayObject.prototype.renderCanvas = function (/* renderer */) { +DisplayObject.prototype.renderCanvas = function (/* renderer */) +{ // OVERWRITE; }; diff --git a/src/core/display/DisplayObjectContainer.js b/src/core/display/DisplayObjectContainer.js index 689f40b..4625ee8 100644 --- a/src/core/display/DisplayObjectContainer.js +++ b/src/core/display/DisplayObjectContainer.js @@ -12,7 +12,8 @@ * @extends DisplayObject * @namespace PIXI */ -function DisplayObjectContainer() { +function DisplayObjectContainer() +{ DisplayObject.call(this); /** @@ -47,17 +48,21 @@ * @memberof DisplayObjectContainer# */ width: { - get: function () { + get: function () + { return this.scale.x * this.getLocalBounds().width; }, - set: function (value) { + set: function (value) + { var width = this.getLocalBounds().width; - if(width !== 0) { + if(width !== 0) + { this.scale.x = value / width; } - else { + else + { this.scale.x = 1; } @@ -73,17 +78,21 @@ * @memberof DisplayObjectContainer# */ height: { - get: function () { + get: function () + { return this.scale.y * this.getLocalBounds().height; }, - set: function (value) { + set: function (value) + { var height = this.getLocalBounds().height; - if (height !== 0) { + if (height !== 0) + { this.scale.y = value / height ; } - else { + else + { this.scale.y = 1; } @@ -100,18 +109,23 @@ * @memberof DisplayObject# */ cacheAsBitmap: { - get: function () { + get: function () + { return this._cacheAsBitmap; }, - set: function (value) { - if (this._cacheAsBitmap === value) { + set: function (value) + { + if (this._cacheAsBitmap === value) + { return; } - if (value) { + if (value) + { this._generateCachedSprite(); } - else { + else + { this._destroyCachedSprite(); } @@ -126,7 +140,8 @@ * @param child {DisplayObject} The DisplayObject to add to the container * @return {DisplayObject} The child that was added. */ -DisplayObjectContainer.prototype.addChild = function (child) { +DisplayObjectContainer.prototype.addChild = function (child) +{ return this.addChildAt(child, this.children.length); }; @@ -137,14 +152,18 @@ * @param index {Number} The index to place the child in * @return {DisplayObject} The child that was added. */ -DisplayObjectContainer.prototype.addChildAt = function (child, index) { +DisplayObjectContainer.prototype.addChildAt = function (child, index) +{ // prevent adding self as child - if (child === this) { + if (child === this) + { return; } - if (index >= 0 && index <= this.children.length) { - if (child.parent) { + if (index >= 0 && index <= this.children.length) + { + if (child.parent) + { child.parent.removeChild(child); } @@ -154,7 +173,8 @@ return child; } - else { + else + { throw new Error(child + 'addChildAt: The index '+ index +' supplied is out of bounds ' + this.children.length); } }; @@ -165,15 +185,18 @@ * @param child {DisplayObject} * @param child2 {DisplayObject} */ -DisplayObjectContainer.prototype.swapChildren = function (child, child2) { - if (child === child2) { +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) { + if (index1 < 0 || index2 < 0) + { throw new Error('swapChildren: Both the supplied DisplayObjects must be a child of the caller.'); } @@ -187,10 +210,12 @@ * @param child {DisplayObject} The DisplayObject instance to identify * @return {Number} The index position of the child display object to identify */ -DisplayObjectContainer.prototype.getChildIndex = function (child) { +DisplayObjectContainer.prototype.getChildIndex = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { throw new Error('The supplied DisplayObject must be a child of the caller'); } @@ -203,8 +228,10 @@ * @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 */ -DisplayObjectContainer.prototype.setChildIndex = function (child, index) { - if (index < 0 || index >= this.children.length) { +DisplayObjectContainer.prototype.setChildIndex = function (child, index) +{ + if (index < 0 || index >= this.children.length) + { throw new Error('The supplied index is out of bounds'); } @@ -220,8 +247,10 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child at the given index, if any. */ -DisplayObjectContainer.prototype.getChildAt = function (index) { - if (index < 0 || index >= this.children.length) { +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'); } @@ -234,10 +263,12 @@ * @param child {DisplayObject} The DisplayObject to remove * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChild = function (child) { +DisplayObjectContainer.prototype.removeChild = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { return; } @@ -250,7 +281,8 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChildAt = function (index) { +DisplayObjectContainer.prototype.removeChildAt = function (index) +{ var child = this.getChildAt(index); child.parent = null; @@ -265,24 +297,29 @@ * @param beginIndex {Number} The beginning position. Default value is 0. * @param endIndex {Number} The ending position. Default value is size of the container. */ -DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) { +DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) +{ var begin = beginIndex || 0; var end = typeof endIndex === 'number' ? endIndex : this.children.length; var range = end - begin; - if (range > 0 && range <= end) { + if (range > 0 && range <= end) + { var removed = this.children.splice(begin, range); - for (var i = 0; i < removed.length; ++i) { + for (var i = 0; i < removed.length; ++i) + { removed[i].parent = null; } return removed; } - else if (range === 0 && this.children.length === 0) { + else if (range === 0 && this.children.length === 0) + { return []; } - else { + else + { throw new RangeError('removeChildren: numeric values are outside the acceptable range.'); } }; @@ -291,7 +328,8 @@ * Generates and updates the cached sprite for this object. * */ -DisplayObjectContainer.prototype.updateCachedSprite = function () { +DisplayObjectContainer.prototype.updateCachedSprite = function () +{ this._generateCachedSprite(); }; @@ -304,7 +342,8 @@ * @param renderer {CanvasRenderer|WebGLRenderer} The renderer used to generate the texture. * @return {Texture} a texture of the graphics object */ -DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) { +DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) +{ var bounds = this.getLocalBounds(); var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0, renderer, scaleMode, resolution); @@ -322,18 +361,22 @@ * * @private */ -DisplayObjectContainer.prototype.updateTransform = function () { - if (!this.visible) { +DisplayObjectContainer.prototype.updateTransform = function () +{ + if (!this.visible) + { return; } this.displayObjectUpdateTransform(); - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { return; } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } }; @@ -346,8 +389,10 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getBounds = function () { - if (this.children.length === 0) { +DisplayObjectContainer.prototype.getBounds = function () +{ + if (this.children.length === 0) + { return math.Rectangle.EMPTY; } @@ -365,10 +410,12 @@ var childVisible = false; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -386,7 +433,8 @@ maxY = maxY > childMaxY ? maxY : childMaxY; } - if (!childVisible) { + if (!childVisible) + { return math.Rectangle.EMPTY; } @@ -407,12 +455,14 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getLocalBounds = function () { +DisplayObjectContainer.prototype.getLocalBounds = function () +{ var matrixCache = this.worldTransform; this.worldTransform = math.Matrix.IDENTITY; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } @@ -428,13 +478,16 @@ * * @param renderer {WebGLRenderer} The renderer */ -DisplayObjectContainer.prototype.renderWebGL = function (renderer) { +DisplayObjectContainer.prototype.renderWebGL = function (renderer) +{ // if the object is not visible or the alpha is 0 then no need to render this element - if (!this.visible || this.alpha <= 0) { + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } @@ -442,14 +495,17 @@ var i, j; // do a quick check to see if this element has a mask or a filter. - if (this._mask || this._filters) { + if (this._mask || this._filters) + { // push filter first as we need to ensure the stencil buffer is correct for any masking - if (this._filters) { + if (this._filters) + { renderer.spriteBatch.flush(); renderer.filterManager.pushFilter(this._filterBlock); } - if (this._mask) { + if (this._mask) + { renderer.spriteBatch.stop(); renderer.maskManager.pushMask(this.mask, renderer); renderer.spriteBatch.start(); @@ -459,36 +515,42 @@ this._renderWebGL(renderer); // now loop through the children and make sure they get rendered - for (i = 0, j = this.children.length; i < j; i++) { + for (i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderWebGL(renderer); } // time to stop the sprite batch as either a mask element or a filter draw will happen next renderer.spriteBatch.stop(); - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(this._mask, renderer); } - if (this._filters) { + if (this._filters) + { renderer.filterManager.popFilter(); } renderer.spriteBatch.start(); } - else { + else + { this._renderWebGL(renderer); // simple render children! - for (i = 0, j = this.children.length; i < j; ++i) { + for (i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderWebGL(renderer); } } }; -DisplayObjectContainer.prototype._renderWebGL = function (renderer) { +DisplayObjectContainer.prototype._renderWebGL = function (renderer) +{ // this is where content itself gets renderd.. @@ -499,25 +561,31 @@ * * @param renderer {CanvasRenderer} The renderer */ -DisplayObjectContainer.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0) { +DisplayObjectContainer.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -528,13 +596,16 @@ * @param renderer {WebGLRenderer|CanvasRenderer} The renderer * @private */ -DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) { +DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) +{ this._cachedSprite.worldAlpha = this.worldAlpha; - if (renderer.gl) { + if (renderer.gl) + { this._cachedSprite.renderWebGL(renderer); } - else { + else + { this._cachedSprite.renderCanvas(renderer); } }; @@ -544,10 +615,12 @@ * * @private */ -DisplayObjectContainer.prototype._generateCachedSprite = function () { +DisplayObjectContainer.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { // TODO - RenderTexture now *requires* a renderer instance, so this is like broken // because `renderer` isn't actually in scope here :P var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0); @@ -555,7 +628,8 @@ this._cachedSprite = new Sprite(renderTexture); this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.texture.resize(bounds.width | 0, bounds.height | 0); } @@ -580,8 +654,10 @@ * * @private */ -DisplayObjectContainer.prototype._destroyCachedSprite = function () { - if (!this._cachedSprite) { +DisplayObjectContainer.prototype._destroyCachedSprite = function () +{ + if (!this._cachedSprite) + { return; } diff --git a/src/core/display/Sprite.js b/src/core/display/Sprite.js index 707da24..5862aef 100644 --- a/src/core/display/Sprite.js +++ b/src/core/display/Sprite.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param texture {Texture} The texture for this sprite */ -function Sprite(texture) { +function Sprite(texture) +{ DisplayObjectContainer.call(this); /** @@ -85,12 +86,14 @@ this.texture = texture || Texture.EMPTY; } -Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) { +Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) +{ DisplayObjectContainer.prototype.destroy.call(this); this.anchor = null; - if (destroyTexture) { + if (destroyTexture) + { this._texture.destroy(destroyBaseTexture); } @@ -111,10 +114,12 @@ * @memberof Sprite# */ width: { - get: function () { + get: function () + { return this.scale.x * this.texture.frame.width; }, - set: function (value) { + set: function (value) + { this.scale.x = value / this.texture.frame.width; this._width = value; } @@ -127,10 +132,12 @@ * @memberof Sprite# */ height: { - get: function () { + get: function () + { return this.scale.y * this.texture.frame.height; }, - set: function (value) { + set: function (value) + { this.scale.y = value / this.texture.frame.height; this._height = value; } @@ -143,23 +150,29 @@ * @memberof Sprite# */ texture: { - get: function () { + get: function () + { return this._texture; }, - set: function (value) { - if (this._texture === value) { + set: function (value) + { + if (this._texture === value) + { return; } this._texture = value; this.cachedTint = 0xFFFFFF; - if (value) { + if (value) + { // wait for the texture to load - if (value.baseTexture.hasLoaded) { + if (value.baseTexture.hasLoaded) + { this._onTextureUpdate(); } - else { + else + { value.once('update', this._onTextureUpdate.bind(this)); } } @@ -172,18 +185,22 @@ * * @private */ -Sprite.prototype._onTextureUpdate = function () { +Sprite.prototype._onTextureUpdate = function () +{ // so if _width is 0 then width was not set.. - if (this._width) { + if (this._width) + { this.scale.x = this._width / this.texture.frame.width; } - if (this._height) { + if (this._height) + { this.scale.y = this._height / this.texture.frame.height; } }; -Sprite.prototype._renderWebGL = function (renderer) { +Sprite.prototype._renderWebGL = function (renderer) +{ // this is where content gets renderd.. // watch this space for a little render state manager.. @@ -197,7 +214,8 @@ * @param matrix {Matrix} the transformation matrix of the sprite * @return {Rectangle} the framing rectangle */ -Sprite.prototype.getBounds = function (matrix) { +Sprite.prototype.getBounds = function (matrix) +{ var width = this.texture.frame.width; var height = this.texture.frame.height; @@ -224,11 +242,13 @@ if(b === 0 && c === 0) { // scale may be negative! - if (a < 0) { + if (a < 0) + { a *= -1; } - if (d < 0) { + if (d < 0) + { d *= -1; } @@ -293,28 +313,34 @@ * * @param renderer {CanvasRenderer} The renderer */ -Sprite.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) { +Sprite.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) + { return; } - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; renderer.context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } // Ignore null sources - if (this.texture.valid) { + if (this.texture.valid) + { var resolution = this.texture.baseTexture.resolution / renderer.resolution; renderer.context.globalAlpha = this.worldAlpha; // If smoothingEnabled is supported and we need to change the smoothing property for this texture - if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) { + if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) + { renderer.scaleMode = this.texture.baseTexture.scaleMode; renderer.context[renderer.smoothProperty] = (renderer.scaleMode === CONST.scaleModes.LINEAR); } @@ -324,7 +350,8 @@ var dy = (this.texture.trim ? this.texture.trim.y : 0) - (this.anchor.y * this.texture.trim.height); // Allow for pixel rounding - if (renderer.roundPixels) { + if (renderer.roundPixels) + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -337,7 +364,8 @@ dx = dx | 0; dy = dy | 0; } - else { + else + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -348,8 +376,10 @@ ); } - if (this.tint !== 0xFFFFFF) { - if (this.cachedTint !== this.tint) { + if (this.tint !== 0xFFFFFF) + { + if (this.cachedTint !== this.tint) + { this.cachedTint = this.tint; // TODO clean up caching - how to clean up the caches? @@ -368,7 +398,8 @@ this.texture.crop.height / resolution ); } - else { + else + { renderer.context.drawImage( this.texture.baseTexture.source, this.texture.crop.x, @@ -383,11 +414,13 @@ } } - for (var i = 0, j = this.children.length; i < j; i++) { + for (var i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -402,10 +435,12 @@ * @param frameId {String} The frame Id of the texture in the cache * @return {Sprite} A new Sprite using a texture from the texture cache matching the frameId */ -Sprite.fromFrame = function (frameId) { +Sprite.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache' + this); } @@ -420,6 +455,7 @@ * @param imageId {String} The image url of the texture * @return {Sprite} A new Sprite using a texture from the texture cache matching the image id */ -Sprite.fromImage = function (imageId, crossorigin, scaleMode) { +Sprite.fromImage = function (imageId, crossorigin, scaleMode) +{ return new Sprite(Texture.fromImage(imageId, crossorigin, scaleMode)); }; diff --git a/src/core/display/SpriteBatch.js b/src/core/display/SpriteBatch.js index 3187777..c196fef 100644 --- a/src/core/display/SpriteBatch.js +++ b/src/core/display/SpriteBatch.js @@ -12,7 +12,8 @@ * ```js * var container = new SpriteBatch(); * - * for(var i = 0; i < 100; ++i) { + * for(var i = 0; i < 100; ++i) + * { * var sprite = new PIXI.Sprite.fromImage("myImage.png"); * container.addChild(sprite); * } @@ -25,7 +26,8 @@ */ //TODO RENAME to PARTICLE CONTAINER? -function SpriteBatch() { +function SpriteBatch() +{ DisplayObjectContainer.call(this); } @@ -38,7 +40,8 @@ * * @private */ -SpriteBatch.prototype.updateTransform = function () { +SpriteBatch.prototype.updateTransform = function () +{ // TODO don't need to! this.displayObjectUpdateTransform(); // PIXI.DisplayObjectContainer.prototype.updateTransform.call( this ); @@ -50,8 +53,10 @@ * @param renderer {WebGLRenderer} The webgl renderer * @private */ -SpriteBatch.prototype.renderWebGL = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderWebGL = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -71,8 +76,10 @@ * @param renderer {CanvasRenderer} The canvas renderer * @private */ -SpriteBatch.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -84,10 +91,12 @@ this.displayObjectUpdateTransform(); - for (var i = 0; i < this.children.length; ++i) { + for (var i = 0; i < this.children.length; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -95,9 +104,11 @@ context.globalAlpha = this.worldAlpha * child.alpha; - if (child.rotation % (Math.PI * 2) === 0) { + if (child.rotation % (Math.PI * 2) === 0) + { // this is the fastest way to optimise! - if rotation is 0 then we can avoid any kind of setTransform call - if (isRotated) { + if (isRotated) + { context.setTransform( transform.a, transform.b, @@ -122,8 +133,10 @@ frame.height * child.scale.y ); } - else { - if (!isRotated) { + else + { + if (!isRotated) + { isRotated = true; } @@ -131,7 +144,8 @@ var childTransform = child.worldTransform; - if (renderer.roundPixels) { + if (renderer.roundPixels) + { context.setTransform( childTransform.a, childTransform.b, @@ -141,7 +155,8 @@ childTransform.ty | 0 ); } - else { + else + { context.setTransform( childTransform.a, childTransform.b, diff --git a/src/core/index.js b/src/core/index.js index 3954b6f..eb4a82b 100644 --- a/src/core/index.js +++ b/src/core/index.js @@ -58,11 +58,13 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRenderer: function (width, height, options, noWebGL) { + autoDetectRenderer: function (width, height, options, noWebGL) + { width = width || 800; height = height || 600; - if (!noWebGL && require('webgl-enabled')()) { + if (!noWebGL && require('webgl-enabled')()) + { return new core.WebGLRenderer(width, height, options); } @@ -87,7 +89,8 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRecommendedRenderer: function (width, height, options) { + autoDetectRecommendedRenderer: function (width, height, options) + { var isAndroid = /Android/i.test(navigator.userAgent); return core.autoDetectRenderer(width, height, options, isAndroid); diff --git a/src/core/math/Matrix.js b/src/core/math/Matrix.js index c2f87e2..2ff4848 100644 --- a/src/core/math/Matrix.js +++ b/src/core/math/Matrix.js @@ -10,7 +10,8 @@ * @class * @namespace PIXI */ -function Matrix() { +function Matrix() +{ /** * @member {number} * @default 1 @@ -63,7 +64,8 @@ * * @param array {number[]} The array that the matrix will be populated from. */ -Matrix.prototype.fromArray = function (array) { +Matrix.prototype.fromArray = function (array) +{ this.a = array[0]; this.b = array[1]; this.c = array[3]; @@ -78,14 +80,17 @@ * @param transpose {boolean} Whether we need to transpose the matrix or not * @return {number[]} the newly created array which contains the matrix */ -Matrix.prototype.toArray = function (transpose) { - if (!this.array) { +Matrix.prototype.toArray = function (transpose) +{ + if (!this.array) + { this.array = new Float32Array(9); } var array = this.array; - if (transpose) { + if (transpose) + { array[0] = this.a; array[1] = this.b; array[2] = 0; @@ -96,7 +101,8 @@ array[7] = this.ty; array[8] = 1; } - else { + else + { array[0] = this.a; array[1] = this.c; array[2] = this.tx; @@ -119,7 +125,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, transformed through this matrix */ -Matrix.prototype.apply = function (pos, newPos) { +Matrix.prototype.apply = function (pos, newPos) +{ newPos = newPos || new Point(); newPos.x = this.a * pos.x + this.c * pos.y + this.tx; @@ -136,7 +143,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, inverse-transformed through this matrix */ -Matrix.prototype.applyInverse = function (pos, newPos) { +Matrix.prototype.applyInverse = function (pos, newPos) +{ newPos = newPos || new Point(); var id = 1 / (this.a * this.d + this.c * -this.b); @@ -154,7 +162,8 @@ * @param {number} y * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.translate = function (x, y) { +Matrix.prototype.translate = function (x, y) +{ this.tx += x; this.ty += y; @@ -168,7 +177,8 @@ * @param {number} y The amount to scale vertically * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.scale = function (x, y) { +Matrix.prototype.scale = function (x, y) +{ this.a *= x; this.d *= y; this.c *= x; @@ -186,7 +196,8 @@ * @param {number} angle - The angle in radians. * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.rotate = function (angle) { +Matrix.prototype.rotate = function (angle) +{ var cos = Math.cos( angle ); var sin = Math.sin( angle ); @@ -210,7 +221,8 @@ * @param {Matrix} matrix * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.append = function (matrix) { +Matrix.prototype.append = function (matrix) +{ var a1 = this.a; var b1 = this.b; var c1 = this.c; @@ -232,7 +244,8 @@ * * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.identity = function () { +Matrix.prototype.identity = function () +{ this.a = 1; this.b = 0; this.c = 0; diff --git a/src/core/math/Point.js b/src/core/math/Point.js index 7565b2d..632f346 100644 --- a/src/core/math/Point.js +++ b/src/core/math/Point.js @@ -7,7 +7,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -function Point(x, y) { +function Point(x, y) +{ /** * @member {number} * @default 0 @@ -29,7 +30,8 @@ * * @return {Point} a copy of the point */ -Point.prototype.clone = function () { +Point.prototype.clone = function () +{ return new Point(this.x, this.y); }; @@ -40,7 +42,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -Point.prototype.set = function (x, y) { +Point.prototype.set = function (x, y) +{ this.x = x || 0; this.y = y || ( (y !== 0) ? this.x : 0 ) ; }; diff --git a/src/core/math/shapes/Circle.js b/src/core/math/shapes/Circle.js index 69cfdc9..4d76efc 100644 --- a/src/core/math/shapes/Circle.js +++ b/src/core/math/shapes/Circle.js @@ -10,7 +10,8 @@ * @param y {number} The Y coordinate of the center of this circle * @param radius {number} The radius of the circle */ -function Circle(x, y, radius) { +function Circle(x, y, radius) +{ /** * @member {number} * @default 0 @@ -46,7 +47,8 @@ * @method clone * @return {Circle} a copy of the Circle */ -Circle.prototype.clone = function () { +Circle.prototype.clone = function () +{ return new Circle(this.x, this.y, this.radius); }; @@ -58,8 +60,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Circle */ -Circle.prototype.contains = function (x, y) { - if (this.radius <= 0) { +Circle.prototype.contains = function (x, y) +{ + if (this.radius <= 0) + { return false; } @@ -79,6 +83,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Circle.prototype.getBounds = function () { +Circle.prototype.getBounds = function () +{ return new Rectangle(this.x - this.radius, this.y - this.radius, this.radius * 2, this.radius * 2); }; diff --git a/src/core/math/shapes/Ellipse.js b/src/core/math/shapes/Ellipse.js index 4f2d066..fefd01a 100644 --- a/src/core/math/shapes/Ellipse.js +++ b/src/core/math/shapes/Ellipse.js @@ -11,7 +11,8 @@ * @param width {number} The half width of this ellipse * @param height {number} The half height of this ellipse */ -function Ellipse(x, y, width, height) { +function Ellipse(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -53,7 +54,8 @@ * @method clone * @return {Ellipse} a copy of the ellipse */ -Ellipse.prototype.clone = function () { +Ellipse.prototype.clone = function () +{ return new Ellipse(this.x, this.y, this.width, this.height); }; @@ -65,8 +67,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coords are within this ellipse */ -Ellipse.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Ellipse.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } @@ -86,6 +90,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Ellipse.prototype.getBounds = function () { +Ellipse.prototype.getBounds = function () +{ return new Rectangle(this.x - this.width, this.y - this.height, this.width, this.height); }; diff --git a/src/core/math/shapes/Polygon.js b/src/core/math/shapes/Polygon.js index ae89148..fea6d37 100644 --- a/src/core/math/shapes/Polygon.js +++ b/src/core/math/shapes/Polygon.js @@ -10,16 +10,20 @@ * arguments passed can be flat x,y values e.g. `new Polygon(x,y, x,y, x,y, ...)` where `x` and `y` are * Numbers. */ -function Polygon(points) { +function Polygon(points) +{ //if points isn't an array, use arguments as the array - if (!(points instanceof Array)) { + if (!(points instanceof Array)) + { points = Array.prototype.slice.call(arguments); } //if this is a flat array of numbers, convert it to points - if (points[0] instanceof Point) { + if (points[0] instanceof Point) + { var p = []; - for (var i = 0, il = points.length; i < il; i++) { + for (var i = 0, il = points.length; i < il; i++) + { p.push(points[i].x, points[i].y); } @@ -51,7 +55,8 @@ * * @return {Polygon} a copy of the polygon */ -Polygon.prototype.clone = function () { +Polygon.prototype.clone = function () +{ return new Polygon(this.points.slice()); }; @@ -62,19 +67,22 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this polygon */ -Polygon.prototype.contains = function (x, y) { +Polygon.prototype.contains = function (x, y) +{ var inside = false; // use some raycasting to test hits // https://github.com/substack/point-in-polygon/blob/master/index.js var length = this.points.length / 2; - for (var i = 0, j = length - 1; i < length; j = i++) { + for (var i = 0, j = length - 1; i < length; j = i++) + { var xi = this.points[i * 2], yi = this.points[i * 2 + 1], xj = this.points[j * 2], yj = this.points[j * 2 + 1], intersect = ((yi > y) !== (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi); - if (intersect) { + if (intersect) + { inside = !inside; } } diff --git a/src/core/math/shapes/Rectangle.js b/src/core/math/shapes/Rectangle.js index 16ac62a..4008b68 100644 --- a/src/core/math/shapes/Rectangle.js +++ b/src/core/math/shapes/Rectangle.js @@ -10,7 +10,8 @@ * @param width {number} The overall width of this rectangle * @param height {number} The overall height of this rectangle */ -function Rectangle(x, y, width, height) { +function Rectangle(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -60,7 +61,8 @@ * * @return {Rectangle} a copy of the rectangle */ -Rectangle.prototype.clone = function () { +Rectangle.prototype.clone = function () +{ return new Rectangle(this.x, this.y, this.width, this.height); }; @@ -71,13 +73,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rectangle */ -Rectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Rectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/math/shapes/RoundedRectangle.js b/src/core/math/shapes/RoundedRectangle.js index 27d286e..7bf6411 100644 --- a/src/core/math/shapes/RoundedRectangle.js +++ b/src/core/math/shapes/RoundedRectangle.js @@ -11,7 +11,8 @@ * @param height {number} The overall height of this rounded rectangle * @param radius {number} Controls the radius of the rounded corners */ -function RoundedRectangle(x, y, width, height, radius) { +function RoundedRectangle(x, y, width, height, radius) +{ /** * @member {number} * @default 0 @@ -58,7 +59,8 @@ * * @return {RoundedRectangle} a copy of the rounded rectangle */ -RoundedRectangle.prototype.clone = function () { +RoundedRectangle.prototype.clone = function () +{ return new RoundedRectangle(this.x, this.y, this.width, this.height, this.radius); }; @@ -69,13 +71,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rounded Rectangle */ -RoundedRectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +RoundedRectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/primitives/Graphics.js b/src/core/primitives/Graphics.js index 261c534..e902d2a 100644 --- a/src/core/primitives/Graphics.js +++ b/src/core/primitives/Graphics.js @@ -16,7 +16,8 @@ * @extends DisplayObjectContainer * @namespace PIXI */ -function Graphics() { +function Graphics() +{ DisplayObjectContainer.call(this); this.renderable = true; @@ -154,16 +155,20 @@ * @private */ cacheAsBitmap: { - get: function () { + get: function () + { return this._cacheAsBitmap; }, - set: function (value) { + set: function (value) + { this._cacheAsBitmap = value; - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._generateCachedSprite(); } - else { + else + { this.destroyCachedSprite(); this.dirty = true; } @@ -176,7 +181,8 @@ * * @return {Graphics} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ var clone = new Graphics(); clone.renderable = this.renderable; @@ -192,7 +198,8 @@ clone.cachedSpriteDirty = this.cachedSpriteDirty; // copy graphics data - for (var i = 0; i < this.graphicsData.length; ++i) { + for (var i = 0; i < this.graphicsData.length; ++i) + { clone.graphicsData.push(this.graphicsData.clone()); } @@ -211,17 +218,21 @@ * @param alpha {number} alpha of the line to draw, will update the objects stored style * @return {Graphics} */ -Graphics.prototype.lineStyle = function (lineWidth, color, alpha) { +Graphics.prototype.lineStyle = function (lineWidth, color, alpha) +{ this.lineWidth = lineWidth || 0; this.lineColor = color || 0; this.lineAlpha = (arguments.length < 3) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length) + { // halfway through a line? start a new one! this.drawShape( new math.Polygon( this.currentPath.shape.points.slice(-2) )); } - else { + else + { // otherwise its empty so lets just set the line properties this.currentPath.lineWidth = this.lineWidth; this.currentPath.lineColor = this.lineColor; @@ -239,7 +250,8 @@ * @param y {number} the Y coordinate to move to * @return {Graphics} */ -Graphics.prototype.moveTo = function (x, y) { +Graphics.prototype.moveTo = function (x, y) +{ this.drawShape(new math.Polygon([x,y])); return this; @@ -253,7 +265,8 @@ * @param y {number} the Y coordinate to draw to * @return {Graphics} */ -Graphics.prototype.lineTo = function (x, y) { +Graphics.prototype.lineTo = function (x, y) +{ this.currentPath.shape.points.push(x, y); this.dirty = true; @@ -270,13 +283,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -285,7 +302,8 @@ n = 20, points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { this.moveTo(0, 0); } @@ -293,7 +311,8 @@ var fromY = points[points.length-1]; var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; xa = fromX + ( (cpX - fromX) * j ); @@ -319,13 +338,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -342,7 +365,8 @@ var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; dt = (1 - j); @@ -373,13 +397,17 @@ * @param radius {number} The radius of the arc * @return {Graphics} */ -Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points.push(x1, y1); } } - else { + else + { this.moveTo(x1, y1); } @@ -392,12 +420,15 @@ b2 = x2 - x1, mm = Math.abs(a1 * b2 - b1 * a2); - if (mm < 1.0e-8 || radius === 0) { - if (points[points.length-2] !== x1 || points[points.length-1] !== y1) { + if (mm < 1.0e-8 || radius === 0) + { + if (points[points.length-2] !== x1 || points[points.length-1] !== y1) + { points.push(x1, y1); } } - else { + else + { var dd = a1 * a1 + b1 * b1, cc = a2 * a2 + b2 * b2, tt = a1 * a2 + b1 * b2, @@ -433,42 +464,51 @@ * @param anticlockwise {boolean} Optional. Specifies whether the drawing should be counterclockwise or clockwise. False is default, and indicates clockwise, while true indicates counter-clockwise. * @return {Graphics} */ -Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) { +Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) +{ var startX = cx + Math.cos(startAngle) * radius; var startY = cy + Math.sin(startAngle) * radius; var points; // TODO - This if-else makes no sense. It uses currentPath in the else where it doesn't exist... - if (this.currentPath) { + if (this.currentPath) + { points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { points.push(startX, startY); } - else if (points[points.length-2] !== startX || points[points.length-1] !== startY) { + else if (points[points.length-2] !== startX || points[points.length-1] !== startY) + { points.push(startX, startY); } } - else { + else + { this.moveTo(startX, startY); points = this.currentPath.shape.points; } - if (startAngle === endAngle) { + if (startAngle === endAngle) + { return this; } - if (!anticlockwise && endAngle <= startAngle) { + if (!anticlockwise && endAngle <= startAngle) + { endAngle += Math.PI * 2; } - else if (anticlockwise && startAngle <= endAngle) { + else if (anticlockwise && startAngle <= endAngle) + { startAngle += Math.PI * 2; } var sweep = anticlockwise ? (startAngle - endAngle) *-1 : (endAngle - startAngle); var segs = (Math.abs(sweep)/ (Math.PI * 2)) * 40; - if (sweep === 0) { + if (sweep === 0) + { return this; } @@ -482,7 +522,8 @@ var remainder = ( segMinus % 1 ) / segMinus; - for (var i = 0; i <= segMinus; ++i) { + for (var i = 0; i <= segMinus; ++i) + { var real = i + remainder * i; var angle = ((theta) + startAngle + (theta2 * real)); @@ -506,13 +547,16 @@ * @param alpha {number} the alpha of the fill * @return {Graphics} */ -Graphics.prototype.beginFill = function (color, alpha) { +Graphics.prototype.beginFill = function (color, alpha) +{ this.filling = true; this.fillColor = color || 0; this.fillAlpha = (alpha === undefined) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length <= 2) + { this.currentPath.fill = this.filling; this.currentPath.fillColor = this.fillColor; this.currentPath.fillAlpha = this.fillAlpha; @@ -526,7 +570,8 @@ * * @return {Graphics} */ -Graphics.prototype.endFill = function () { +Graphics.prototype.endFill = function () +{ this.filling = false; this.fillColor = null; this.fillAlpha = 1; @@ -542,7 +587,8 @@ * @param height {number} The height of the rectangle * @return {Graphics} */ -Graphics.prototype.drawRect = function ( x, y, width, height ) { +Graphics.prototype.drawRect = function ( x, y, width, height ) +{ this.drawShape(new math.Rectangle(x,y, width, height)); return this; @@ -556,7 +602,8 @@ * @param height {number} The height of the rectangle * @param radius {number} Radius of the rectangle corners */ -Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) { +Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) +{ this.drawShape(new math.RoundedRectangle(x, y, width, height, radius)); return this; @@ -570,7 +617,8 @@ * @param radius {number} The radius of the circle * @return {Graphics} */ -Graphics.prototype.drawCircle = function (x, y, radius) { +Graphics.prototype.drawCircle = function (x, y, radius) +{ this.drawShape(new math.Circle(x,y, radius)); return this; @@ -585,7 +633,8 @@ * @param height {number} The half height of the ellipse * @return {Graphics} */ -Graphics.prototype.drawEllipse = function (x, y, width, height) { +Graphics.prototype.drawEllipse = function (x, y, width, height) +{ this.drawShape(new math.Ellipse(x, y, width, height)); return this; @@ -597,8 +646,10 @@ * @param path {Array} The path data used to construct the polygon. * @return {Graphics} */ -Graphics.prototype.drawPolygon = function (path) { - if (!(path instanceof Array)) { +Graphics.prototype.drawPolygon = function (path) +{ + if (!(path instanceof Array)) + { path = Array.prototype.slice.call(arguments); } @@ -612,7 +663,8 @@ * * @return {Graphics} */ -Graphics.prototype.clear = function () { +Graphics.prototype.clear = function () +{ this.lineWidth = 0; this.filling = false; @@ -631,7 +683,8 @@ * @param scaleMode {number} Should be one of the scaleMode consts * @return {Texture} a texture of the graphics object */ -Graphics.prototype.generateTexture = function (resolution, scaleMode) { +Graphics.prototype.generateTexture = function (resolution, scaleMode) +{ resolution = resolution || 1; var bounds = this.getBounds(); @@ -655,17 +708,21 @@ * * @param renderer {WebGLRenderer} */ -Graphics.prototype._renderWebGL = function (renderer) { +Graphics.prototype._renderWebGL = function (renderer) +{ // if the sprite is not visible or the alpha is 0 then no need to render this element - if (this.isMask === true) { + if (this.isMask === true) + { return; } // this code may still be needed so leaving for now.. - // + // /* - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture on the gpu too! @@ -681,17 +738,24 @@ return; } - */ - - // check if the webgl graphic needs to be updated - if (this.glDirty) { - this.dirty = true; - this.glDirty = false; - } + else */ - renderer.setObjectRendererer(renderer.graphicsRenderer); - renderer.graphicsRenderer.render(this); + renderer.spriteBatch.stop(); + renderer.blendModeManager.setBlendMode(this.blendMode); + // check blend mode + renderer.blendModeManager.setBlendMode( this.blendMode ); + + // check if the webgl graphic needs to be updated + if (this.glDirty) + { + this.dirty = true; + this.glDirty = false; + } + + WebGLGraphics.renderGraphics(this, renderer); + + renderer.spriteBatch.start(); }; /** @@ -700,14 +764,18 @@ * @param renderer {CanvasRenderer} * @private */ -Graphics.prototype.renderCanvas = function (renderer) { +Graphics.prototype.renderCanvas = function (renderer) +{ // 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.isMask === true) { + if (!this.visible || this.alpha <= 0 || this.isMask === true) + { return; } - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture @@ -723,16 +791,19 @@ return; } - else { + else + { var context = renderer.context; var transform = this.worldTransform; - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } @@ -748,11 +819,13 @@ CanvasGraphics.renderGraphics(this, context); - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } } @@ -763,13 +836,16 @@ * * @return {Rectangle} the rectangular bounding area */ -Graphics.prototype.getBounds = function (matrix) { +Graphics.prototype.getBounds = function (matrix) +{ // return an empty object if the item is a mask! - if (this.isMask) { + if (this.isMask) + { return math.Rectangle.EMPTY; } - if (this.dirty) { + if (this.dirty) + { this.updateLocalBounds(); this.glDirty = true; @@ -841,23 +917,27 @@ * Update the bounds of the object * */ -Graphics.prototype.updateLocalBounds = function () { +Graphics.prototype.updateLocalBounds = function () +{ var minX = Infinity; var maxX = -Infinity; var minY = Infinity; var maxY = -Infinity; - if (this.graphicsData.length) { + if (this.graphicsData.length) + { var shape, points, x, y, w, h; - for (var i = 0; i < this.graphicsData.length; i++) { + for (var i = 0; i < this.graphicsData.length; i++) + { var data = this.graphicsData[i]; var type = data.type; var lineWidth = data.lineWidth; shape = data.shape; - if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) { + if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) + { x = shape.x - lineWidth/2; y = shape.y - lineWidth/2; w = shape.width + lineWidth; @@ -869,7 +949,8 @@ minY = y < minY ? y : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.CIRC) { + else if (type === CONST.SHAPES.CIRC) + { x = shape.x; y = shape.y; w = shape.radius + lineWidth/2; @@ -881,7 +962,8 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.ELIP) { + else if (type === CONST.SHAPES.ELIP) + { x = shape.x; y = shape.y; w = shape.width + lineWidth/2; @@ -893,11 +975,13 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else { + else + { // POLY points = shape.points; - for (var j = 0; j < points.length; j += 2) { + for (var j = 0; j < points.length; j += 2) + { x = points[j]; y = points[j+1]; @@ -910,7 +994,8 @@ } } } - else { + else + { minX = 0; maxX = 0; minY = 0; @@ -931,10 +1016,12 @@ * * @private */ -Graphics.prototype._generateCachedSprite = function () { +Graphics.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { var canvasBuffer = new CanvasBuffer(bounds.width, bounds.height); var texture = Texture.fromCanvas(canvasBuffer.canvas); @@ -943,7 +1030,8 @@ this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.buffer.resize(bounds.width, bounds.height); } @@ -968,7 +1056,8 @@ * * @private */ -Graphics.prototype.updateCachedSpriteTexture = function () { +Graphics.prototype.updateCachedSpriteTexture = function () +{ var cachedSprite = this._cachedSprite; var texture = cachedSprite.texture; var canvas = cachedSprite.buffer.canvas; @@ -989,7 +1078,8 @@ * Destroys a previous cached sprite. * */ -Graphics.prototype.destroyCachedSprite = function () { +Graphics.prototype.destroyCachedSprite = function () +{ this._cachedSprite.texture.destroy(true); // let the gc collect the unused sprite @@ -1003,10 +1093,13 @@ * @param {Circle|Rectangle|Ellipse|Line|Polygon} shape The Shape object to draw. * @return {GraphicsData} The generated GraphicsData object. */ -Graphics.prototype.drawShape = function (shape) { - if (this.currentPath) { +Graphics.prototype.drawShape = function (shape) +{ + if (this.currentPath) + { // check current path! - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath.shape.points.length <= 2) + { this.graphicsData.pop(); } } @@ -1017,7 +1110,8 @@ this.graphicsData.push(data); - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { data.shape.closed = this.filling; this.currentPath = data; } diff --git a/src/core/primitives/GraphicsData.js b/src/core/primitives/GraphicsData.js index 99decbe..788f6f2 100644 --- a/src/core/primitives/GraphicsData.js +++ b/src/core/primitives/GraphicsData.js @@ -4,7 +4,8 @@ * @class * @namespace PIXI */ -function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) { +function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) +{ this.lineWidth = lineWidth; this.lineColor = lineColor; this.lineAlpha = lineAlpha; @@ -27,7 +28,8 @@ * * @return {GraphicsData} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ return new GraphicsData( this.lineWidth, this.lineColor, diff --git a/src/core/renderers/canvas/CanvasRenderer.js b/src/core/renderers/canvas/CanvasRenderer.js index 15a0978..7aebd44 100644 --- a/src/core/renderers/canvas/CanvasRenderer.js +++ b/src/core/renderers/canvas/CanvasRenderer.js @@ -17,17 +17,22 @@ * @param [options.resolution=1] {number} the resolution of the renderer retina would be 2 * @param [options.clearBeforeRender=true] {boolean} This sets if the CanvasRenderer will clear the canvas or not before the new render pass. */ -function CanvasRenderer(width, height, options) { +function CanvasRenderer(width, height, options) +{ utils.sayHello('Canvas'); - if (options) { - for (var i in CONST.defaultRenderOptions) { - if (typeof options[i] === 'undefined') { + if (options) + { + for (var i in CONST.defaultRenderOptions) + { + if (typeof options[i] === 'undefined') + { options[i] = CONST.defaultRenderOptions[i]; } } } - else { + else + { options = CONST.defaultRenderOptions; } @@ -156,19 +161,24 @@ this.smoothProperty = null; - if (this.context.imageSmoothingEnabled) { + if (this.context.imageSmoothingEnabled) + { this.smoothProperty = 'imageSmoothingEnabled'; } - else if (this.context.webkitImageSmoothingEnabled) { + else if (this.context.webkitImageSmoothingEnabled) + { this.smoothProperty = 'webkitImageSmoothingEnabled'; } - else if (this.context.mozImageSmoothingEnabled) { + else if (this.context.mozImageSmoothingEnabled) + { this.smoothProperty = 'mozImageSmoothingEnabled'; } - else if (this.context.oImageSmoothingEnabled) { + else if (this.context.oImageSmoothingEnabled) + { this.smoothProperty = 'oImageSmoothingEnabled'; } - else if (this.context.msImageSmoothingEnabled) { + else if (this.context.msImageSmoothingEnabled) + { this.smoothProperty = 'msImageSmoothingEnabled'; } @@ -193,10 +203,12 @@ * @memberof CanvasRenderer# */ backgroundColor: { - get: function () { + get: function () + { return this._backgroundColor; }, - set: function (val) { + set: function (val) + { this._backgroundColor = val; this._backgroundColorString = utils.hex2string(val); } @@ -208,7 +220,8 @@ * * @param object {DisplayObject} the object to be rendered */ -CanvasRenderer.prototype.render = function (object) { +CanvasRenderer.prototype.render = function (object) +{ object.updateTransform(); this.context.setTransform(1,0,0,1,0,0); @@ -218,16 +231,20 @@ this.currentBlendMode = CONST.blendModes.NORMAL; this.context.globalCompositeOperation = this.blendModes[CONST.blendModes.NORMAL]; - if (navigator.isCocoonJS && this.view.screencanvas) { + if (navigator.isCocoonJS && this.view.screencanvas) + { this.context.fillStyle = 'black'; this.context.clear(); } - if (this.clearBeforeRender) { - if (this.transparent) { + if (this.clearBeforeRender) + { + if (this.transparent) + { this.context.clearRect(0, 0, this.width, this.height); } - else { + else + { this.context.fillStyle = this._backgroundColorString; this.context.fillRect(0, 0, this.width , this.height); } @@ -241,8 +258,10 @@ * * @param [removeView=false] {boolean} Removes the Canvas element from the DOM. */ -CanvasRenderer.prototype.destroy = function (removeView) { - if (removeView && this.view.parent) { +CanvasRenderer.prototype.destroy = function (removeView) +{ + if (removeView && this.view.parent) + { this.view.parent.removeChild(this.view); } @@ -257,14 +276,16 @@ * @param width {number} the new width of the canvas view * @param height {number} the new height of the canvas view */ -CanvasRenderer.prototype.resize = function (width, height) { +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) { + if (this.autoResize) + { this.view.style.width = this.width / this.resolution + 'px'; this.view.style.height = this.height / this.resolution + 'px'; } @@ -276,7 +297,8 @@ * @param displayObject {DisplayObject} The displayObject to render * @private */ -CanvasRenderer.prototype.renderDisplayObject = function (displayObject) { +CanvasRenderer.prototype.renderDisplayObject = function (displayObject) +{ displayObject.renderCanvas(this); }; @@ -285,11 +307,14 @@ * * @private */ -CanvasRenderer.prototype._mapBlendModes = function () { - if (!this.blendModes) { +CanvasRenderer.prototype._mapBlendModes = function () +{ + if (!this.blendModes) + { this.blendModes = {}; - if (utils.canUseNewCanvasBlendModes()) { + if (utils.canUseNewCanvasBlendModes()) + { this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? this.blendModes[CONST.blendModes.MULTIPLY] = 'multiply'; @@ -308,7 +333,8 @@ this.blendModes[CONST.blendModes.COLOR] = 'color'; this.blendModes[CONST.blendModes.LUMINOSITY] = 'luminosity'; } - else { + else + { // this means that the browser does not support the cool new blend modes in canvas 'cough' ie 'cough' this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? diff --git a/src/core/renderers/canvas/utils/CanvasBuffer.js b/src/core/renderers/canvas/utils/CanvasBuffer.js index ebe5d47..b183a66 100644 --- a/src/core/renderers/canvas/utils/CanvasBuffer.js +++ b/src/core/renderers/canvas/utils/CanvasBuffer.js @@ -6,7 +6,8 @@ * @param width {number} the width for the newly created canvas * @param height {number} the height for the newly created canvas */ -function CanvasBuffer(width, height) { +function CanvasBuffer(width, height) +{ /** * The Canvas object that belongs to this CanvasBuffer. * @@ -36,10 +37,12 @@ * @memberof CanvasBuffer# */ width: { - get: function () { + get: function () + { return this.canvas.width; }, - set: function (val) { + set: function (val) + { this.canvas.width = val; } }, @@ -50,10 +53,12 @@ * @memberof CanvasBuffer# */ height: { - get: function () { + get: function () + { return this.canvas.height; }, - set: function (val) { + set: function (val) + { this.canvas.height = val; } } @@ -64,7 +69,8 @@ * * @private */ -CanvasBuffer.prototype.clear = function () { +CanvasBuffer.prototype.clear = function () +{ this.context.setTransform(1, 0, 0, 1, 0, 0); this.context.clearRect(0,0, this.canvas.width, this.canvas.height); }; @@ -75,7 +81,8 @@ * @param width {number} the new width of the canvas * @param height {number} the new height of the canvas */ -CanvasBuffer.prototype.resize = function (width, height) { +CanvasBuffer.prototype.resize = function (width, height) +{ this.canvas.width = width; this.canvas.height = height; }; diff --git a/src/core/renderers/canvas/utils/CanvasGraphics.js b/src/core/renderers/canvas/utils/CanvasGraphics.js index c7eaa2a..3f2a91f 100644 --- a/src/core/renderers/canvas/utils/CanvasGraphics.js +++ b/src/core/renderers/canvas/utils/CanvasGraphics.js @@ -13,15 +13,18 @@ * @param graphics {Graphics} the actual graphics object to render * @param context {CanvasRenderingContext2D} the 2d drawing method of the canvas */ -CanvasGraphics.renderGraphics = function (graphics, context) { +CanvasGraphics.renderGraphics = function (graphics, context) +{ var worldAlpha = graphics.worldAlpha; - if (graphics.dirty) { + if (graphics.dirty) + { this.updateGraphicsTint(graphics); graphics.dirty = false; } - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; @@ -30,69 +33,82 @@ context.lineWidth = data.lineWidth; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { context.beginPath(); var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } - if (shape.closed) { + if (shape.closed) + { context.lineTo(points[0], points[1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fillRect(shape.x, shape.y, shape.width, shape.height); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.strokeRect(shape.x, shape.y, shape.width, shape.height); } } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.beginPath(); context.arc(shape.x, shape.y, shape.radius,0,2*Math.PI); context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas var w = shape.width * 2; @@ -119,18 +135,21 @@ context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; var width = shape.width; @@ -152,13 +171,15 @@ context.quadraticCurveTo(rx, ry, rx, ry + radius); context.closePath(); - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); @@ -174,45 +195,54 @@ * @param graphics {Graphics} the graphics which will be used as a mask * @param context {CanvasRenderingContext2D} the context 2d method of the canvas */ -CanvasGraphics.renderGraphicsMask = function (graphics, context) { +CanvasGraphics.renderGraphicsMask = function (graphics, context) +{ var len = graphics.graphicsData.length; - if (len === 0) { + if (len === 0) + { return; } context.beginPath(); - for (var i = 0; i < len; i++) { + for (var i = 0; i < len; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { context.rect(shape.x, shape.y, shape.width, shape.height); context.closePath(); } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.arc(shape.x, shape.y, shape.radius, 0, 2 * Math.PI); context.closePath(); } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas @@ -237,7 +267,8 @@ context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); context.closePath(); } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; @@ -262,8 +293,10 @@ } }; -CanvasGraphics.updateGraphicsTint = function (graphics) { - if (graphics.tint === 0xFFFFFF) { +CanvasGraphics.updateGraphicsTint = function (graphics) +{ + if (graphics.tint === 0xFFFFFF) + { return; } @@ -271,7 +304,8 @@ var tintG = (graphics.tint >> 8 & 0xFF) / 255; var tintB = (graphics.tint & 0xFF)/ 255; - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var fillColor = data.fillColor | 0; diff --git a/src/core/renderers/canvas/utils/CanvasMaskManager.js b/src/core/renderers/canvas/utils/CanvasMaskManager.js index e04a733..9827d36 100644 --- a/src/core/renderers/canvas/utils/CanvasMaskManager.js +++ b/src/core/renderers/canvas/utils/CanvasMaskManager.js @@ -6,7 +6,8 @@ * @class * @namespace PIXI */ -function CanvasMaskManager() {} +function CanvasMaskManager() +{} CanvasMaskManager.prototype.constructor = CanvasMaskManager; module.exports = CanvasMaskManager; @@ -17,7 +18,8 @@ * @param maskData {object} the maskData that will be pushed * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.pushMask = function (maskData, renderer) { +CanvasMaskManager.prototype.pushMask = function (maskData, renderer) +{ renderer.context.save(); var cacheAlpha = maskData.alpha; @@ -45,6 +47,7 @@ * * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.popMask = function (renderer) { +CanvasMaskManager.prototype.popMask = function (renderer) +{ renderer.context.restore(); }; diff --git a/src/core/renderers/canvas/utils/CanvasTinter.js b/src/core/renderers/canvas/utils/CanvasTinter.js index 17e0529..d2fb1bc 100644 --- a/src/core/renderers/canvas/utils/CanvasTinter.js +++ b/src/core/renderers/canvas/utils/CanvasTinter.js @@ -14,7 +14,8 @@ * @param color {number} the color to use to tint the sprite with * @return {HTMLCanvasElement} The tinted canvas */ -CanvasTinter.getTintedTexture = function (sprite, color) { +CanvasTinter.getTintedTexture = function (sprite, color) +{ var texture = sprite.texture; color = CanvasTinter.roundColor(color); @@ -23,7 +24,8 @@ texture.tintCache = texture.tintCache || {}; - if (texture.tintCache[stringColor]) { + if (texture.tintCache[stringColor]) + { return texture.tintCache[stringColor]; } @@ -33,14 +35,16 @@ //CanvasTinter.tintWithPerPixel(texture, stringColor, canvas); CanvasTinter.tintMethod(texture, color, canvas); - if (CanvasTinter.convertTintToImage) { + if (CanvasTinter.convertTintToImage) + { // is this better? var tintImage = new Image(); tintImage.src = canvas.toDataURL(); texture.tintCache[stringColor] = tintImage; } - else { + else + { texture.tintCache[stringColor] = canvas; // if we are not converting the texture to an image then we need to lose the reference to the canvas CanvasTinter.canvas = null; @@ -56,7 +60,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithMultiply = function (texture, color, canvas) { +CanvasTinter.tintWithMultiply = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -104,7 +109,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithOverlay = function (texture, color, canvas) { +CanvasTinter.tintWithOverlay = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -139,7 +145,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithPerPixel = function (texture, color, canvas) { +CanvasTinter.tintWithPerPixel = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -167,7 +174,8 @@ var pixels = pixelData.data; - for (var i = 0; i < pixels.length; i += 4) { + for (var i = 0; i < pixels.length; i += 4) + { pixels[i+0] *= r; pixels[i+1] *= g; pixels[i+2] *= b; @@ -181,7 +189,8 @@ * * @param color {number} the color to round, should be a hex color */ -CanvasTinter.roundColor = function (color) { +CanvasTinter.roundColor = function (color) +{ var step = CanvasTinter.cacheStepsPerColorChannel; var rgbValues = utils.hex2rgb(color); diff --git a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js index 9f2f89a..35edbaf 100644 --- a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js +++ b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLBlendModeManager(renderer) { +function WebGLBlendModeManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -23,8 +24,10 @@ * * @param blendMode {number} the blendMode, should be a Pixi const, such as BlendModes.ADD */ -WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) { - if (this.currentBlendMode === blendMode) { +WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) +{ + if (this.currentBlendMode === blendMode) + { return false; } diff --git a/src/core/renderers/webgl/managers/WebGLFilterManager.js b/src/core/renderers/webgl/managers/WebGLFilterManager.js index 1179258..2dac048 100644 --- a/src/core/renderers/webgl/managers/WebGLFilterManager.js +++ b/src/core/renderers/webgl/managers/WebGLFilterManager.js @@ -7,7 +7,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLFilterManager(renderer) { +function WebGLFilterManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -32,7 +33,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.texturePool.length = 0; self.initShaderBuffers(); }); @@ -46,7 +48,8 @@ * @param renderer {WebGLRenderer} * @param buffer {ArrayBuffer} */ -WebGLFilterManager.prototype.begin = function (buffer) { +WebGLFilterManager.prototype.begin = function (buffer) +{ this.defaultShader = this.renderer.shaderManager.defaultShader; this.width = this.renderer.projection.x * 2; @@ -60,7 +63,8 @@ * * @param filterBlock {object} the filter that will be pushed to the current filter stack */ -WebGLFilterManager.prototype.pushFilter = function (filterBlock) { +WebGLFilterManager.prototype.pushFilter = function (filterBlock) +{ var gl = this.renderer.gl; var projection = this.renderer.projection; @@ -78,10 +82,12 @@ this.offsetY += filterBlock._filterArea.y; var texture = this.texturePool.pop(); - if (!texture) { + if (!texture) + { texture = new FilterTexture(this.renderer.gl, this.width, this.height); } - else { + else + { texture.resize(this.width, this.height); } @@ -98,29 +104,35 @@ var localX = filterArea.x, localY = filterArea.y; - if (filterArea.x < 0) { + if (filterArea.x < 0) + { filterArea.width += filterArea.x; filterArea.x = 0; } - if (filterArea.y < 0) { + if (filterArea.y < 0) + { filterArea.height += filterArea.y; filterArea.y = 0; } - if (localX + filterArea.width > this.width) { + if (localX + filterArea.width > this.width) + { filterArea.width = this.width - localX; } - if (localY + filterArea.height > this.height) { + if (localY + filterArea.height > this.height) + { filterArea.height = this.height - localY; } - if (filterArea.width < 0) { + if (filterArea.width < 0) + { filterArea.width = 0; } - if (filterArea.height < 0) { + if (filterArea.height < 0) + { filterArea.height = 0; } @@ -154,7 +166,8 @@ * Removes the last filter from the filter stack and doesn't return it. * */ -WebGLFilterManager.prototype.popFilter = function () { +WebGLFilterManager.prototype.popFilter = function () +{ var gl = this.renderer.gl; var filterBlock = this.filterStack.pop(); @@ -163,7 +176,8 @@ var projection = this.renderer.projection; var offset = this.renderer.offset; - if (filterBlock.filterPasses.length > 1) { + if (filterBlock.filterPasses.length > 1) + { gl.viewport(0, 0, filterArea.width, filterArea.height); gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); @@ -193,7 +207,8 @@ var inputTexture = texture; var outputTexture = this.texturePool.pop(); - if (!outputTexture) { + if (!outputTexture) + { outputTexture = new FilterTexture(this.renderer.gl, this.width, this.height); } outputTexture.resize(this.width, this.height); @@ -204,7 +219,8 @@ gl.disable(gl.BLEND); - for (var i = 0; i < filterBlock.filterPasses.length-1; i++) { + for (var i = 0; i < filterBlock.filterPasses.length-1; i++) + { var filterPass = filterBlock.filterPasses[i]; gl.bindFramebuffer(gl.FRAMEBUFFER, outputTexture.frameBuffer ); @@ -243,10 +259,12 @@ var buffer = this.buffer; // time to render the filters texture to the previous scene - if (this.filterStack.length === 0) { + if (this.filterStack.length === 0) + { gl.colorMask(true, true, true, true);//this.transparent); } - else { + else + { var currentFilter = this.filterStack[this.filterStack.length-1]; filterArea = currentFilter._filterArea; @@ -332,13 +350,15 @@ * @param width {number} the horizontal range of the filter * @param height {number} the vertical range of the filter */ -WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) { +WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) +{ // use program var gl = this.renderer.gl; var shader = filter.shaders[gl.id]; - if (!shader) { + if (!shader) + { shader = new Shader(gl); shader.fragmentSrc = filter.fragmentSrc; @@ -356,7 +376,8 @@ gl.uniform2f(shader.projectionVector, width/2, -height/2); gl.uniform2f(shader.offsetVector, 0,0); - if (filter.uniforms.dimensions) { + 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]; @@ -386,7 +407,8 @@ * Initialises the shader buffers. * */ -WebGLFilterManager.prototype.initShaderBuffers = function () { +WebGLFilterManager.prototype.initShaderBuffers = function () +{ var gl = this.renderer.gl; // create some buffers @@ -432,7 +454,8 @@ * Destroys the filter and removes it from the filter stack. * */ -WebGLFilterManager.prototype.destroy = function () { +WebGLFilterManager.prototype.destroy = function () +{ var gl = this.renderer.gl; this.filterStack = null; @@ -441,7 +464,8 @@ this.offsetY = 0; // destroy textures - for (var i = 0; i < this.texturePool.length; i++) { + for (var i = 0; i < this.texturePool.length; i++) + { this.texturePool[i].destroy(); } diff --git a/src/core/renderers/webgl/managers/WebGLManager.js b/src/core/renderers/webgl/managers/WebGLManager.js index 9d47b5c..c30cd51 100644 --- a/src/core/renderers/webgl/managers/WebGLManager.js +++ b/src/core/renderers/webgl/managers/WebGLManager.js @@ -3,7 +3,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLManager(renderer) { +function WebGLManager(renderer) +{ /** * The renderer this manager works for. * @@ -15,6 +16,7 @@ WebGLManager.prototype.constructor = WebGLManager; module.exports = WebGLManager; -WebGLManager.prototype.destroy = function () { +WebGLManager.prototype.destroy = function () +{ this.renderer = null; }; diff --git a/src/core/renderers/webgl/managers/WebGLMaskManager.js b/src/core/renderers/webgl/managers/WebGLMaskManager.js index 2f90b64..e568812 100644 --- a/src/core/renderers/webgl/managers/WebGLMaskManager.js +++ b/src/core/renderers/webgl/managers/WebGLMaskManager.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLMaskManager(renderer) { +function WebGLMaskManager(renderer) +{ WebGLManager.call(this, renderer); } @@ -19,12 +20,15 @@ * * @param maskData {any[]} */ -WebGLMaskManager.prototype.pushMask = function (maskData) { - if (maskData.dirty) { +WebGLMaskManager.prototype.pushMask = function (maskData) +{ + if (maskData.dirty) + { WebGLGraphics.updateGraphics(maskData, this.renderer.gl); } - if (!maskData._webGL[this.renderer.gl.id].data.length) { + if (!maskData._webGL[this.renderer.gl.id].data.length) + { return; } @@ -36,6 +40,7 @@ * * @param maskData {any[]} */ -WebGLMaskManager.prototype.popMask = function (maskData) { +WebGLMaskManager.prototype.popMask = function (maskData) +{ this.renderer.stencilManager.popStencil(maskData, maskData._webGL[this.renderer.gl.id].data[0], this.renderer); }; diff --git a/src/core/renderers/webgl/managers/WebGLShaderManager.js b/src/core/renderers/webgl/managers/WebGLShaderManager.js index fef071c..90c6477 100644 --- a/src/core/renderers/webgl/managers/WebGLShaderManager.js +++ b/src/core/renderers/webgl/managers/WebGLShaderManager.js @@ -10,7 +10,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLShaderManager(renderer) { +function WebGLShaderManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -28,7 +29,8 @@ */ this.tempAttribState = []; - for (var i = 0; i < this.maxAttibs; i++) { + for (var i = 0; i < this.maxAttibs; i++) + { this.attribState[i] = false; } @@ -66,7 +68,8 @@ // listen for context and update necessary shaders var self = this; - this.renderer.on('context', function (event) { + this.renderer.on('context', function (event) + { var gl = event.data; // this shader is used for rendering primitives @@ -97,29 +100,36 @@ * * @param attribs {Array} attribs */ -WebGLShaderManager.prototype.setAttribs = function (attribs) { +WebGLShaderManager.prototype.setAttribs = function (attribs) +{ // reset temp state var i; - for (i = 0; i < this.tempAttribState.length; i++) { + for (i = 0; i < this.tempAttribState.length; i++) + { this.tempAttribState[i] = false; } // set the new attribs - for (var a in attribs) { + for (var a in attribs) + { this.tempAttribState[attribs[a]] = true; } var gl = this.renderer.gl; - for (i = 0; i < this.attribState.length; i++) { - if (this.attribState[i] !== this.tempAttribState[i]) { + for (i = 0; i < this.attribState.length; i++) + { + if (this.attribState[i] !== this.tempAttribState[i]) + { this.attribState[i] = this.tempAttribState[i]; - if (this.attribState[i]) { + if (this.attribState[i]) + { gl.enableVertexAttribArray(i); } - else { + else + { gl.disableVertexAttribArray(i); } } @@ -131,8 +141,10 @@ * * @param shader {Any} */ -WebGLShaderManager.prototype.setShader = function (shader) { - if (this._currentId === shader.uuid) { +WebGLShaderManager.prototype.setShader = function (shader) +{ + if (this._currentId === shader.uuid) + { return false; } @@ -150,7 +162,8 @@ * Destroys this object. * */ -WebGLShaderManager.prototype.destroy = function () { +WebGLShaderManager.prototype.destroy = function () +{ this.attribState = null; this.tempAttribState = null; diff --git a/src/core/renderers/webgl/managers/WebGLStencilManager.js b/src/core/renderers/webgl/managers/WebGLStencilManager.js index 9ec6398..4cb0134 100644 --- a/src/core/renderers/webgl/managers/WebGLStencilManager.js +++ b/src/core/renderers/webgl/managers/WebGLStencilManager.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLStencilManager(renderer) { +function WebGLStencilManager(renderer) +{ WebGLManager.call(this, renderer); this.stencilStack = []; @@ -24,12 +25,14 @@ * @param graphics {Graphics} * @param webGLData {any[]} */ -WebGLStencilManager.prototype.pushStencil = function (graphics, webGLData) { +WebGLStencilManager.prototype.pushStencil = function (graphics, webGLData) +{ var gl = this.renderer.gl; this.bindGraphics(graphics, webGLData, this.renderer); - if (this.stencilStack.length === 0) { + if (this.stencilStack.length === 0) + { gl.enable(gl.STENCIL_TEST); gl.clear(gl.STENCIL_BUFFER_BIT); this.reverse = true; @@ -47,14 +50,17 @@ // draw the triangle strip! - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } @@ -62,31 +68,38 @@ // draw a quad to increment.. gl.drawElements(gl.TRIANGLE_FAN, 4, gl.UNSIGNED_SHORT, ( webGLData.indices.length - 4 ) * 2 ); - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); } this.reverse = !this.reverse; } - else { - if (!this.reverse) { + else + { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } - else { + 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) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); } } @@ -103,7 +116,8 @@ * @param graphics {Graphics} * @param webGLData {Array} */ -WebGLStencilManager.prototype.bindGraphics = function (graphics, webGLData) { +WebGLStencilManager.prototype.bindGraphics = function (graphics, webGLData) +{ //if (this._currentGraphics === graphics)return; this._currentGraphics = graphics; @@ -114,7 +128,8 @@ offset = this.renderer.offset, shader;// = this.renderer.shaderManager.primitiveShader; - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { shader = this.renderer.shaderManager.complexPrimitiveShader; this.renderer.shaderManager.setShader(shader); @@ -141,7 +156,8 @@ // set the index buffer! gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, webGLData.indexBuffer); } - else { + else + { //this.renderer.shaderManager.activatePrimitiveShader(); shader = this.renderer.shaderManager.primitiveShader; this.renderer.shaderManager.setShader( shader ); @@ -154,7 +170,7 @@ gl.uniform2f(shader.uniforms.offsetVector._location, -offset.x, -offset.y); gl.uniform3fv(shader.uniforms.tint._location, utils.hex2rgb(graphics.tint)); - + gl.uniform1f(shader.uniforms.alpha._location, graphics.worldAlpha); @@ -172,19 +188,22 @@ * @param graphics {Graphics} * @param webGLData {Array} */ -WebGLStencilManager.prototype.popStencil = function (graphics, webGLData) { +WebGLStencilManager.prototype.popStencil = function (graphics, webGLData) +{ var gl = this.renderer.gl; this.stencilStack.pop(); this.count--; - if (this.stencilStack.length === 0) { + if (this.stencilStack.length === 0) + { // the stack is empty! gl.disable(gl.STENCIL_TEST); } - else { + else + { var level = this.count; @@ -192,14 +211,17 @@ gl.colorMask(false, false, false, false); - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { this.reverse = !this.reverse; - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } @@ -213,31 +235,38 @@ // draw the triangle strip! gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); - if (!this.reverse) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); } } - else { + else + { // console.log("<<>>") - if (!this.reverse) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } - else { + 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) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); } } @@ -253,7 +282,8 @@ * Destroys the mask stack. * */ -WebGLStencilManager.prototype.destroy = function () { +WebGLStencilManager.prototype.destroy = function () +{ this.renderer = null; this.stencilStack = null; }; diff --git a/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js b/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js index 913ba5e..1ea7d19 100644 --- a/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js +++ b/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function ComplexPrimitiveShader(gl) { +function ComplexPrimitiveShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -24,7 +25,8 @@ 'uniform float flipY;', 'varying vec4 vColor;', - 'void main(void) {', + '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);', @@ -37,7 +39,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = vColor;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/FastShader.js b/src/core/renderers/webgl/shaders/FastShader.js index bd2e29a..2e5e060 100644 --- a/src/core/renderers/webgl/shaders/FastShader.js +++ b/src/core/renderers/webgl/shaders/FastShader.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function FastShader(gl) { +function FastShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -28,7 +29,8 @@ 'const vec2 center = vec2(-1.0, 1.0);', - 'void main(void) {', + 'void main(void) + {', ' vec2 v;', ' vec2 sv = aVertexPosition * aScale;', ' v.x = (sv.x) * cos(aRotation) - (sv.y) * sin(aRotation);', @@ -49,7 +51,8 @@ 'uniform sampler2D uSampler;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/PrimitiveShader.js b/src/core/renderers/webgl/shaders/PrimitiveShader.js index 6f25409..a25f54f 100644 --- a/src/core/renderers/webgl/shaders/PrimitiveShader.js +++ b/src/core/renderers/webgl/shaders/PrimitiveShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function PrimitiveShader(gl) { +function PrimitiveShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -23,7 +24,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + '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);', @@ -36,7 +38,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = vColor;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/Shader.js b/src/core/renderers/webgl/shaders/Shader.js index f8964f5..fd75ef5 100644 --- a/src/core/renderers/webgl/shaders/Shader.js +++ b/src/core/renderers/webgl/shaders/Shader.js @@ -6,7 +6,8 @@ * @param [fragmentSrc] {string} The source of the fragment shader. * @param [vertexSrc] {string} The source of the vertex shader. */ -function Shader(gl, vertexSrc, fragmentSrc, customUniforms, customAttributes) { +function Shader(gl, vertexSrc, fragmentSrc, customUniforms, customAttributes) +{ /** * @member {number} * @readonly @@ -33,7 +34,8 @@ dimensions: { type: '4f', value: new Float32Array(4) } }; - for (var u in customUniforms) { + for (var u in customUniforms) + { this.uniforms[u] = customUniforms[u]; } @@ -43,7 +45,8 @@ aColor: 0 }; - for (var a in customAttributes) { + for (var a in customAttributes) + { this.attributes[a] = customAttributes[a]; } @@ -66,7 +69,8 @@ 'const vec2 center = vec2(-1.0, 1.0);', - 'void main(void) {', + 'void main(void) + {', ' gl_Position = vec4( ((aVertexPosition + offsetVector) / projectionVector) + center , 0.0, 1.0);', ' vTextureCoord = aTextureCoord;', ' vColor = vec4(aColor.rgb * aColor.a, aColor.a);', @@ -85,7 +89,8 @@ 'uniform sampler2D uSampler;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;', '}' ].join('\n'); @@ -96,7 +101,8 @@ Shader.prototype.constructor = Shader; module.exports = Shader; -Shader.prototype.init = function () { +Shader.prototype.init = function () +{ this.compile(); this.gl.useProgram(this.program); @@ -105,14 +111,18 @@ this.cacheAttributeLocations(Object.keys(this.attributes)); }; -Shader.prototype.cacheUniformLocations = function (keys) { - for (var i = 0; i < keys.length; ++i) { +Shader.prototype.cacheUniformLocations = function (keys) +{ + for (var i = 0; i < keys.length; ++i) + { this.uniforms[keys[i]]._location = this.gl.getUniformLocation(this.program, keys[i]); } }; -Shader.prototype.cacheAttributeLocations = function (keys) { - for (var i = 0; i < keys.length; ++i) { +Shader.prototype.cacheAttributeLocations = function (keys) +{ + for (var i = 0; i < keys.length; ++i) + { this.attributes[keys[i]] = this.gl.getAttribLocation(this.program, keys[i]); } @@ -124,14 +134,16 @@ // 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.attributes.aColor === -1) { + // if (this.attributes.aColor === -1) + { // this.attributes.aColor = 2; // } // End worst hack eva // }; -Shader.prototype.compile = function () { +Shader.prototype.compile = function () +{ var gl = this.gl; var glVertShader = this._glCompile(gl.VERTEX_SHADER, this.vertexSrc); @@ -144,13 +156,15 @@ gl.linkProgram(program); // if linking fails, then log and cleanup - if (!gl.getProgramParameter(program, gl.LINK_STATUS)) { + if (!gl.getProgramParameter(program, gl.LINK_STATUS)) + { window.console.error('Pixi.js Error: Could not initialize shader.'); window.console.error('gl.VALIDATE_STATUS', gl.getProgramParameter(program, gl.VALIDATE_STATUS)); window.console.error('gl.getError()', gl.getError()); // if there is a program info log, log it - if (gl.getProgramInfoLog(program) !== '') { + if (gl.getProgramInfoLog(program) !== '') + { window.console.warn('Pixi.js Warning: gl.getProgramInfoLog()', gl.getProgramInfoLog(program)); } @@ -165,18 +179,21 @@ return (this.program = program); }; -Shader.prototype.syncUniforms = function () { +Shader.prototype.syncUniforms = function () +{ var gl = this.gl; this.textureCount = 1; - for (var key in this.uniforms) { + for (var key in this.uniforms) + { var uniform = this.uniforms[key], location = uniform._location, value = uniform.value, i, il; - switch (uniform.type) { + switch (uniform.type) + { // single int value case 'i': case '1i': @@ -282,7 +299,8 @@ // a Color Value case 'c': - if (typeof value === 'number') { + if (typeof value === 'number') + { value = utils.hex2rgb(value); } @@ -311,11 +329,13 @@ // array of 2D Point objects case 'v2v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(2 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 2] = value[i].x; uniform._array[i * 2 + 1] = value[i].y; } @@ -325,11 +345,13 @@ // array of 3D Point objects case 'v3v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(3 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 3] = value[i].x; uniform._array[i * 3 + 1] = value[i].y; uniform._array[i * 3 + 2] = value[i].z; @@ -341,11 +363,13 @@ // array of 4D Point objects case 'v4v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(4 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 4] = value[i].x; uniform._array[i * 4 + 1] = value[i].y; uniform._array[i * 4 + 2] = value[i].z; @@ -359,7 +383,8 @@ // PIXI.Texture case 't': case 'sampler2D': - if (!uniform.value || !uniform.value.baseTexture || !uniform.value.baseTexture.hasLoaded) { + if (!uniform.value || !uniform.value.baseTexture || !uniform.value.baseTexture.hasLoaded) + { break; } @@ -376,7 +401,8 @@ this.textureCount++; // initialize the texture if we haven't yet - if (!uniform._init) { + if (!uniform._init) + { this.initSampler2D(uniform); uniform._init = true; @@ -394,11 +420,13 @@ * Initialises a Sampler2D uniform (which may only be available later on after initUniforms once the texture has loaded) * */ -Shader.prototype.initSampler2D = function (uniform) { +Shader.prototype.initSampler2D = function (uniform) +{ var gl = this.gl; // Extended texture data - if (uniform.textureData) { + if (uniform.textureData) + { var data = uniform.textureData; // GLTexture = mag linear, min linear_mipmap_linear, wrap repeat + gl.generateMipmap(gl.TEXTURE_2D); @@ -417,14 +445,16 @@ var wrapT = (data.wrapT) ? data.wrapT : gl.CLAMP_TO_EDGE; var format = (data.luminance) ? gl.LUMINANCE : gl.RGBA; - if (data.repeat) { + if (data.repeat) + { wrapS = gl.REPEAT; wrapT = gl.REPEAT; } gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, !!data.flipY); - if (data.width) { + if (data.width) + { var width = (data.width) ? data.width : 512; var height = (data.height) ? data.height : 2; var border = (data.border) ? data.border : 0; @@ -432,7 +462,8 @@ // 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 { + 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); } @@ -448,7 +479,8 @@ * Destroys the shader. * */ -Shader.prototype.destroy = function () { +Shader.prototype.destroy = function () +{ this.gl.deleteProgram(this.program); this.gl = null; @@ -459,13 +491,15 @@ this.fragmentSrc = null; }; -Shader.prototype._glCompile = function (type, src) { +Shader.prototype._glCompile = function (type, src) +{ var shader = this.gl.createShader(type); this.gl.shaderSource(shader, src); this.gl.compileShader(shader); - if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) { + if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) + { window.console.log(this.gl.getShaderInfoLog(shader)); return null; } diff --git a/src/core/renderers/webgl/shaders/StripShader.js b/src/core/renderers/webgl/shaders/StripShader.js index 193f6e1..a7abcc6 100644 --- a/src/core/renderers/webgl/shaders/StripShader.js +++ b/src/core/renderers/webgl/shaders/StripShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function StripShader(gl) { +function StripShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -20,7 +21,8 @@ 'varying vec2 vTextureCoord;', - 'void main(void) {', + '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);', @@ -36,7 +38,8 @@ 'varying vec2 vTextureCoord;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vec2(vTextureCoord.x, vTextureCoord.y)) * alpha;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/utils/FilterTexture.js b/src/core/renderers/webgl/utils/FilterTexture.js index d2c8423..4433d44 100644 --- a/src/core/renderers/webgl/utils/FilterTexture.js +++ b/src/core/renderers/webgl/utils/FilterTexture.js @@ -8,7 +8,8 @@ * @param height {number} the vertical range of the filter * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values */ -function FilterTexture(gl, width, height, scaleMode) { +function FilterTexture(gl, width, height, scaleMode) +{ /** * @member {WebGLContext} */ @@ -59,7 +60,8 @@ * Clears the filter texture. * */ -FilterTexture.prototype.clear = function () { +FilterTexture.prototype.clear = function () +{ var gl = this.gl; gl.clearColor(0,0,0, 0); @@ -72,8 +74,10 @@ * @param width {number} the new width of the texture * @param height {number} the new height of the texture */ -FilterTexture.prototype.resize = function (width, height) { - if (this.width === width && this.height === height) { +FilterTexture.prototype.resize = function (width, height) +{ + if (this.width === width && this.height === height) + { return; } @@ -96,7 +100,8 @@ * Destroys the filter texture. * */ -FilterTexture.prototype.destroy = function () { +FilterTexture.prototype.destroy = function () +{ var gl = this.gl; gl.deleteFramebuffer( this.frameBuffer ); gl.deleteTexture( this.texture ); diff --git a/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js b/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js index c4721e9..a63f4d7 100644 --- a/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js +++ b/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js @@ -14,7 +14,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this sprite batch works for. */ -function WebGLFastSpriteBatch(renderer) { +function WebGLFastSpriteBatch(renderer) +{ /** * The renderer instance this sprite batch operates on. * @@ -91,7 +92,8 @@ */ this.lastIndexCount = 0; - for (var i=0, j=0; i < numIndices; i += 6, j += 4) { + 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; @@ -144,7 +146,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.setupContext(); }); } @@ -157,7 +160,8 @@ * * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLFastSpriteBatch.prototype.setupContext = function () { +WebGLFastSpriteBatch.prototype.setupContext = function () +{ var gl = this.renderer.gl; // create a couple of buffers @@ -177,7 +181,8 @@ /** * @param spriteBatch {SpriteBatch} The SpriteBatch container to prepare for. */ -WebGLFastSpriteBatch.prototype.begin = function (spriteBatch) { +WebGLFastSpriteBatch.prototype.begin = function (spriteBatch) +{ this.shader = this.renderer.shaderManager.fastShader; this.matrix = spriteBatch.worldTransform.toArray(true); @@ -187,33 +192,38 @@ /** */ -WebGLFastSpriteBatch.prototype.end = function () { +WebGLFastSpriteBatch.prototype.end = function () +{ this.flush(); }; /** * @param spriteBatch {SpriteBatch} The SpriteBatch container to render. */ -WebGLFastSpriteBatch.prototype.render = function (spriteBatch) { +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) { + if (!sprite.texture._uvs) + { return; } this.currentBaseTexture = sprite.texture.baseTexture; // check blend mode - if (sprite.blendMode !== this.renderer.blendModeManager.currentBlendMode) { + if (sprite.blendMode !== this.renderer.blendModeManager.currentBlendMode) + { this.flush(); this.renderer.blendModeManager.setBlendMode(sprite.blendMode); } - for (var i=0,j= children.length; i= this.size) { + if (this.currentBatchSize >= this.size) + { this.flush(); } }; @@ -362,29 +379,35 @@ /** * */ -WebGLFastSpriteBatch.prototype.flush = function () { +WebGLFastSpriteBatch.prototype.flush = function () +{ // If the batch is length 0 then return as there is nothing to draw - if (this.currentBatchSize === 0) { + if (this.currentBatchSize === 0) + { return; } var gl = this.renderer.gl; // bind the current texture - if (!this.currentBaseTexture._glTextures[gl.id]) { + if (!this.currentBaseTexture._glTextures[gl.id]) + { this.renderer.updateTexture(this.currentBaseTexture, gl); } //TODO-SHOUD THIS BE ELSE??!?!?! - else { + else + { gl.bindTexture(gl.TEXTURE_2D, this.currentBaseTexture._glTextures[gl.id]); } // upload the verts to the buffer - if (this.currentBatchSize > ( this.size * 0.5 ) ) { + if (this.currentBatchSize > ( this.size * 0.5 ) ) + { gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); } - else { + else + { var view = this.vertices.subarray(0, this.currentBatchSize * this.vertByteSize); gl.bufferSubData(gl.ARRAY_BUFFER, 0, view); @@ -405,14 +428,16 @@ * Ends the batch and flushes * */ -WebGLFastSpriteBatch.prototype.stop = function () { +WebGLFastSpriteBatch.prototype.stop = function () +{ this.flush(); }; /** * */ -WebGLFastSpriteBatch.prototype.start = function () { +WebGLFastSpriteBatch.prototype.start = function () +{ var gl = this.renderer.gl; // bind the main texture diff --git a/src/core/renderers/webgl/utils/WebGLGraphics.js b/src/core/renderers/webgl/utils/WebGLGraphics.js index 55f4911..ab8f46e 100644 --- a/src/core/renderers/webgl/utils/WebGLGraphics.js +++ b/src/core/renderers/webgl/utils/WebGLGraphics.js @@ -19,7 +19,8 @@ * @param graphics {Graphics} * @param renderer {WebGLRenderer} */ -WebGLGraphics.renderGraphics = function (graphics, renderer) {//projection, offset) { +WebGLGraphics.renderGraphics = function (graphics, renderer) {//projection, offset) +{ var gl = renderer.gl; var projection = renderer.projection, @@ -27,7 +28,8 @@ shader = renderer.shaderManager.primitiveShader, webGLData; - if (graphics.dirty) { + if (graphics.dirty) + { WebGLGraphics.updateGraphics(graphics, gl); } @@ -35,8 +37,10 @@ // This could be speeded up for sure! - for (var i = 0; i < webGL.data.length; i++) { - if (webGL.data[i].mode === 1) { + for (var i = 0; i < webGL.data.length; i++) + { + if (webGL.data[i].mode === 1) + { webGLData = webGL.data[i]; renderer.stencilManager.pushStencil(graphics, webGLData, renderer); @@ -46,7 +50,8 @@ renderer.stencilManager.popStencil(graphics, webGLData, renderer); } - else { + else + { webGLData = webGL.data[i]; @@ -84,12 +89,14 @@ * @param graphicsData {Graphics} The graphics object to update * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLGraphics.updateGraphics = function (graphics, gl) { +WebGLGraphics.updateGraphics = function (graphics, gl) +{ // get the contexts graphics object var webGL = graphics._webGL[gl.id]; // if the graphics object does not exist in the webGL context time to create it! - if (!webGL) { + if (!webGL) + { webGL = graphics._webGL[gl.id] = {lastIndex:0, data:[], gl:gl}; } @@ -99,11 +106,13 @@ var i; // if the user cleared the graphics object we will need to clear every object - if (graphics.clearDirty) { + if (graphics.clearDirty) + { graphics.clearDirty = false; // lop through and return all the webGLDatas to the object pool so than can be reused later on - for (i = 0; i < webGL.data.length; i++) { + for (i = 0; i < webGL.data.length; i++) + { var graphicsData = webGL.data[i]; graphicsData.reset(); WebGLGraphics.graphicsDataPool.push( graphicsData ); @@ -119,58 +128,72 @@ // loop through the graphics datas and construct each one.. // if the object is a complex fill then the new stencil buffer technique will be used // other wise graphics objects will be pushed into a batch.. - for (i = webGL.lastIndex; i < graphics.graphicsData.length; i++) { + for (i = webGL.lastIndex; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { // need to add the points the the graphics object.. data.points = data.shape.points.slice(); - if (data.shape.closed) { + if (data.shape.closed) + { // close the poly if the value is true! - if (data.points[0] !== data.points[data.points.length-2] || data.points[1] !== data.points[data.points.length-1]) { + if (data.points[0] !== data.points[data.points.length-2] || data.points[1] !== data.points[data.points.length-1]) + { data.points.push(data.points[0], data.points[1]); } } // MAKE SURE WE HAVE THE CORRECT TYPE.. - if (data.fill) { - if (data.points.length >= 6) { - if (data.points.length < 6 * 2) { + if (data.fill) + { + if (data.points.length >= 6) + { + if (data.points.length < 6 * 2) + { webGLData = WebGLGraphics.switchMode(webGL, 0); var canDrawUsingSimple = WebGLGraphics.buildPoly(data, webGLData); // console.log(canDrawUsingSimple); - if (!canDrawUsingSimple) { + if (!canDrawUsingSimple) + { // console.log("<>>>") webGLData = WebGLGraphics.switchMode(webGL, 1); WebGLGraphics.buildComplexPoly(data, webGLData); } } - else { + else + { webGLData = WebGLGraphics.switchMode(webGL, 1); WebGLGraphics.buildComplexPoly(data, webGLData); } } } - if (data.lineWidth > 0) { + if (data.lineWidth > 0) + { webGLData = WebGLGraphics.switchMode(webGL, 0); WebGLGraphics.buildLine(data, webGLData); } } - else { + else + { webGLData = WebGLGraphics.switchMode(webGL, 0); - if (data.type === CONST.SHAPES.RECT) { + if (data.type === CONST.SHAPES.RECT) + { WebGLGraphics.buildRectangle(data, webGLData); } - else if (data.type === CONST.SHAPES.CIRC || data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.CIRC || data.type === CONST.SHAPES.ELIP) + { WebGLGraphics.buildCircle(data, webGLData); } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { WebGLGraphics.buildRoundedRectangle(data, webGLData); } } @@ -179,10 +202,12 @@ } // upload all the dirty data... - for (i = 0; i < webGL.data.length; i++) { + for (i = 0; i < webGL.data.length; i++) + { webGLData = webGL.data[i]; - if (webGLData.dirty) { + if (webGLData.dirty) + { webGLData.upload(); } } @@ -194,18 +219,22 @@ * @param webGL {WebGLContext} * @param type {number} */ -WebGLGraphics.switchMode = function (webGL, type) { +WebGLGraphics.switchMode = function (webGL, type) +{ var webGLData; - if (!webGL.data.length) { + if (!webGL.data.length) + { webGLData = WebGLGraphics.graphicsDataPool.pop() || new WebGLGraphicsData(webGL.gl); webGLData.mode = type; webGL.data.push(webGLData); } - else { + else + { webGLData = webGL.data[webGL.data.length-1]; - if (webGLData.mode !== type || type === 1) { + if (webGLData.mode !== type || type === 1) + { webGLData = WebGLGraphics.graphicsDataPool.pop() || new WebGLGraphicsData(webGL.gl); webGLData.mode = type; webGL.data.push(webGLData); @@ -225,7 +254,8 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildRectangle = function (graphicsData, webGLData) { +WebGLGraphics.buildRectangle = function (graphicsData, webGLData) +{ // --- // // need to convert points to a nice regular data // @@ -235,7 +265,8 @@ var width = rectData.width; var height = rectData.height; - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -265,7 +296,8 @@ indices.push(vertPos, vertPos, vertPos+1, vertPos+2, vertPos+3, vertPos+3); } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = [x, y, @@ -289,7 +321,8 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildRoundedRectangle = function (graphicsData, webGLData) { +WebGLGraphics.buildRoundedRectangle = function (graphicsData, webGLData) +{ var rrectData = graphicsData.shape; var x = rrectData.x; var y = rrectData.y; @@ -305,7 +338,8 @@ recPoints = recPoints.concat(WebGLGraphics.quadraticBezierCurve(x + width, y + radius, x + width, y, x + width - radius, y)); recPoints = recPoints.concat(WebGLGraphics.quadraticBezierCurve(x + radius, y, x, y, x, y + radius)); - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -323,7 +357,8 @@ // var i = 0; - for (i = 0; i < triangles.length; i+=3) { + for (i = 0; i < triangles.length; i+=3) + { indices.push(triangles[i] + vecPos); indices.push(triangles[i] + vecPos); indices.push(triangles[i+1] + vecPos); @@ -332,12 +367,14 @@ } - for (i = 0; i < recPoints.length; i++) { + for (i = 0; i < recPoints.length; i++) + { verts.push(recPoints[i], recPoints[++i], r, g, b, alpha); } } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = recPoints; @@ -362,7 +399,8 @@ * @param toY {number} Destination point y * @return {number[]} */ -WebGLGraphics.quadraticBezierCurve = function (fromX, fromY, cpX, cpY, toX, toY) { +WebGLGraphics.quadraticBezierCurve = function (fromX, fromY, cpX, cpY, toX, toY) +{ var xa, ya, @@ -373,14 +411,16 @@ n = 20, points = []; - function getPt(n1 , n2, perc) { + function getPt(n1 , n2, perc) + { var diff = n2 - n1; return n1 + ( diff * perc ); } var j = 0; - for (var i = 0; i <= n; i++ ) { + for (var i = 0; i <= n; i++ ) + { j = i / n; // The Green Line @@ -406,7 +446,8 @@ * @param graphicsData {Graphics} The graphics object to draw * @param webGLData {object} */ -WebGLGraphics.buildCircle = function (graphicsData, webGLData) { +WebGLGraphics.buildCircle = function (graphicsData, webGLData) +{ // need to convert points to a nice regular data var circleData = graphicsData.shape; var x = circleData.x; @@ -415,11 +456,13 @@ var height; // TODO - bit hacky?? - if (graphicsData.type === CONST.SHAPES.CIRC) { + if (graphicsData.type === CONST.SHAPES.CIRC) + { width = circleData.radius; height = circleData.radius; } - else { + else + { width = circleData.width; height = circleData.height; } @@ -429,7 +472,8 @@ var i = 0; - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -444,7 +488,8 @@ indices.push(vecPos); - for (i = 0; i < totalSegs + 1 ; i++) { + for (i = 0; i < totalSegs + 1 ; i++) + { verts.push(x,y, r, g, b, alpha); verts.push(x + Math.sin(seg * i) * width, @@ -457,12 +502,14 @@ indices.push(vecPos-1); } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = []; - for (i = 0; i < totalSegs + 1; i++) { + for (i = 0; i < totalSegs + 1; i++) + { graphicsData.points.push(x + Math.sin(seg * i) * width, y + Math.cos(seg * i) * height); } @@ -481,18 +528,22 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildLine = function (graphicsData, webGLData) { +WebGLGraphics.buildLine = function (graphicsData, webGLData) +{ // TODO OPTIMISE! var i = 0; var points = graphicsData.points; - if (points.length === 0) { + if (points.length === 0) + { return; } // if the line width is an odd number add 0.5 to align to a whole pixel - if (graphicsData.lineWidth%2) { - for (i = 0; i < points.length; i++) { + if (graphicsData.lineWidth%2) + { + for (i = 0; i < points.length; i++) + { points[i] += 0.5; } } @@ -502,7 +553,8 @@ var lastPoint = new math.Point(points[points.length - 2], points[points.length - 1]); // if the first point is the last point - gonna have issues :) - if (firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) { + if (firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) + { // need to clone as we are going to slightly modify the shape.. points = points.slice(); @@ -562,7 +614,8 @@ verts.push(p1x + perpx , p1y + perpy, r, g, b, alpha); - for (i = 1; i < length-1; i++) { + for (i = 1; i < length-1; i++) + { p1x = points[(i-1)*2]; p1y = points[(i-1)*2 + 1]; @@ -599,7 +652,8 @@ denom = a1*b2 - a2*b1; - if (Math.abs(denom) < 0.1 ) { + if (Math.abs(denom) < 0.1 ) + { denom+=10.1; verts.push(p2x - perpx , p2y - perpy, @@ -618,7 +672,8 @@ pdist = (px -p2x) * (px -p2x) + (py -p2y) + (py -p2y); - if (pdist > 140 * 140) { + if (pdist > 140 * 140) + { perp3x = perpx - perp2x; perp3y = perpy - perp2y; @@ -639,7 +694,8 @@ indexCount++; } - else { + else + { verts.push(px , py); verts.push(r, g, b, alpha); @@ -672,7 +728,8 @@ indices.push(indexStart); - for (i = 0; i < indexCount; i++) { + for (i = 0; i < indexCount; i++) + { indices.push(indexStart++); } @@ -687,11 +744,13 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildComplexPoly = function (graphicsData, webGLData) { +WebGLGraphics.buildComplexPoly = function (graphicsData, webGLData) +{ //TODO - no need to copy this as it gets turned into a FLoat32Array anyways.. var points = graphicsData.points.slice(); - if (points.length < 6) { + if (points.length < 6) + { return; } @@ -711,7 +770,8 @@ var x,y; // get size.. - for (var i = 0; i < points.length; i+=2) { + for (var i = 0; i < points.length; i+=2) + { x = points[i]; y = points[i+1]; @@ -732,7 +792,8 @@ //TODO - this aint needed! var length = points.length / 2; - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { indices.push( i ); } @@ -746,10 +807,12 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildPoly = function (graphicsData, webGLData) { +WebGLGraphics.buildPoly = function (graphicsData, webGLData) +{ var points = graphicsData.points; - if (points.length < 6) { + if (points.length < 6) + { return; } // get first and last point.. figure out the middle! @@ -767,7 +830,8 @@ var triangles = utils.PolyK.Triangulate(points); - if (!triangles) { + if (!triangles) + { return false; } @@ -775,7 +839,8 @@ var i = 0; - for (i = 0; i < triangles.length; i+=3) { + for (i = 0; i < triangles.length; i+=3) + { indices.push(triangles[i] + vertPos); indices.push(triangles[i] + vertPos); indices.push(triangles[i+1] + vertPos); @@ -783,7 +848,8 @@ indices.push(triangles[i+2] + vertPos); } - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { verts.push(points[i * 2], points[i * 2 + 1], r, g, b, alpha); } diff --git a/src/core/renderers/webgl/utils/WebGLGraphicsData.js b/src/core/renderers/webgl/utils/WebGLGraphicsData.js index c56d05e..c739ba7 100644 --- a/src/core/renderers/webgl/utils/WebGLGraphicsData.js +++ b/src/core/renderers/webgl/utils/WebGLGraphicsData.js @@ -2,7 +2,8 @@ * @class * @private */ -function WebGLGraphicsData(gl) { +function WebGLGraphicsData(gl) +{ this.gl = gl; //TODO does this need to be split before uploding?? @@ -22,7 +23,8 @@ /** * */ -WebGLGraphicsData.prototype.reset = function () { +WebGLGraphicsData.prototype.reset = function () +{ this.points.length = 0; this.indices.length = 0; }; @@ -30,7 +32,8 @@ /** * */ -WebGLGraphicsData.prototype.upload = function () { +WebGLGraphicsData.prototype.upload = function () +{ var gl = this.gl; // this.lastIndex = graphics.graphicsData.length; diff --git a/src/core/renderers/webgl/utils/WebGLSpriteBatch.js b/src/core/renderers/webgl/utils/WebGLSpriteBatch.js index 96eaa52..55befbb 100644 --- a/src/core/renderers/webgl/utils/WebGLSpriteBatch.js +++ b/src/core/renderers/webgl/utils/WebGLSpriteBatch.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this sprite batch works for. */ -function WebGLSpriteBatch(renderer) { +function WebGLSpriteBatch(renderer) +{ /** * * @@ -88,7 +89,8 @@ */ this.lastIndexCount = 0; - for (var i=0, j=0; i < numIndices; i += 6, j += 4) { + 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; @@ -162,7 +164,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.setupContext(); }); } @@ -173,7 +176,8 @@ /** * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLSpriteBatch.prototype.setupContext = function () { +WebGLSpriteBatch.prototype.setupContext = function () +{ var gl = this.renderer.gl; // setup default shader @@ -198,7 +202,8 @@ /** * */ -WebGLSpriteBatch.prototype.begin = function () { +WebGLSpriteBatch.prototype.begin = function () +{ // this.shader = this.renderer.shaderManager.defaultShader; this.start(); @@ -206,19 +211,22 @@ /** */ -WebGLSpriteBatch.prototype.end = function () { +WebGLSpriteBatch.prototype.end = function () +{ this.flush(); }; /** * @param sprite {Sprite} the sprite to render when using this spritebatch */ -WebGLSpriteBatch.prototype.render = function (sprite) { +WebGLSpriteBatch.prototype.render = function (sprite) +{ var texture = sprite.texture; //TODO set blend modes.. // check texture.. - if (this.currentBatchSize >= this.size) { + if (this.currentBatchSize >= this.size) + { this.flush(); this.currentBaseTexture = texture.baseTexture; } @@ -227,7 +235,8 @@ var uvs = texture._uvs; // if the uvs have not updated then no point rendering just yet! - if (!uvs) { + if (!uvs) + { return; } @@ -237,7 +246,8 @@ var w0, w1, h0, h1; - if (texture.trim) { + 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; @@ -248,7 +258,8 @@ h0 = h1 + texture.crop.height; } - else { + else + { w0 = (texture.frame.width ) * (1-aX); w1 = (texture.frame.width ) * -aX; @@ -272,7 +283,8 @@ var colors = this.colors; var positions = this.positions; - if (this.renderer.roundPixels) { + if (this.renderer.roundPixels) + { // xy positions[index] = a * w1 + c * h1 + tx | 0; positions[index+1] = d * h1 + b * w1 + ty | 0; @@ -289,7 +301,8 @@ positions[index+15] = a * w1 + c * h0 + tx | 0; positions[index+16] = d * h0 + b * w1 + ty | 0; } - else { + else + { // xy positions[index] = a * w1 + c * h1 + tx; positions[index+1] = d * h1 + b * w1 + ty; @@ -338,11 +351,13 @@ * * @param sprite {TilingSprite} the tilingSprite to render */ -WebGLSpriteBatch.prototype.renderTilingSprite = function (tilingSprite) { +WebGLSpriteBatch.prototype.renderTilingSprite = function (tilingSprite) +{ var texture = tilingSprite.tilingTexture; // check texture.. - if (this.currentBatchSize >= this.size) { + if (this.currentBatchSize >= this.size) + { //return; this.flush(); this.currentBaseTexture = texture.baseTexture; @@ -351,7 +366,8 @@ // set the textures uvs temporarily // TODO create a separate texture so that we can tile part of a texture - if (!tilingSprite._uvs) { + if (!tilingSprite._uvs) + { tilingSprite._uvs = new TextureUvs(); } @@ -454,16 +470,19 @@ * Renders the content and empties the current batch. * */ -WebGLSpriteBatch.prototype.flush = function () { +WebGLSpriteBatch.prototype.flush = function () +{ // If the batch is length 0 then return as there is nothing to draw - if (this.currentBatchSize === 0) { + if (this.currentBatchSize === 0) + { return; } var gl = this.renderer.gl; var shader; - if (this.dirty) { + if (this.dirty) + { this.dirty = false; // bind the main texture gl.activeTexture(gl.TEXTURE0); @@ -482,10 +501,12 @@ } // upload the verts to the buffer - if (this.currentBatchSize > ( this.size * 0.5 ) ) { + if (this.currentBatchSize > ( this.size * 0.5 ) ) + { gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); } - else { + else + { var view = this.positions.subarray(0, this.currentBatchSize * this.vertByteSize); gl.bufferSubData(gl.ARRAY_BUFFER, 0, view); } @@ -502,7 +523,8 @@ var shaderSwap = false; var sprite; - for (var i = 0, j = this.currentBatchSize; i < j; i++) { + for (var i = 0, j = this.currentBatchSize; i < j; i++) + { sprite = this.sprites[i]; @@ -513,24 +535,28 @@ blendSwap = currentBlendMode !== nextBlendMode; shaderSwap = currentShader !== nextShader; // should I use uuidS??? - if (currentBaseTexture !== nextTexture || blendSwap || shaderSwap) { + if (currentBaseTexture !== nextTexture || blendSwap || shaderSwap) + { this.renderBatch(currentBaseTexture, batchSize, start); start = i; batchSize = 0; currentBaseTexture = nextTexture; - if (blendSwap) { + if (blendSwap) + { currentBlendMode = nextBlendMode; this.renderer.blendModeManager.setBlendMode( currentBlendMode ); } - if (shaderSwap) { + if (shaderSwap) + { currentShader = nextShader; shader = currentShader.shaders ? currentShader.shaders[gl.id] : currentShader; - if (!shader) { + if (!shader) + { shader = new Shader(gl, null, currentShader.fragmentSrc, currentShader.uniforms); currentShader.shaders[gl.id] = shader; } @@ -538,7 +564,8 @@ // set shader function??? this.renderer.shaderManager.setShader(shader); - if (shader.dirty) { + if (shader.dirty) + { shader.syncUniforms(); } @@ -569,17 +596,21 @@ * @param size {number} * @param startIndex {number} */ -WebGLSpriteBatch.prototype.renderBatch = function (texture, size, startIndex) { - if (size === 0) { +WebGLSpriteBatch.prototype.renderBatch = function (texture, size, startIndex) +{ + if (size === 0) + { return; } var gl = this.renderer.gl; - if (!texture._glTextures[gl.id]) { + if (!texture._glTextures[gl.id]) + { this.renderer.updateTexture(texture); } - else { + else + { // bind the current texture gl.bindTexture(gl.TEXTURE_2D, texture._glTextures[gl.id]); } @@ -594,7 +625,8 @@ /** * */ -WebGLSpriteBatch.prototype.stop = function () { +WebGLSpriteBatch.prototype.stop = function () +{ this.flush(); this.dirty = true; }; @@ -602,7 +634,8 @@ /** * */ -WebGLSpriteBatch.prototype.start = function () { +WebGLSpriteBatch.prototype.start = function () +{ this.dirty = true; }; @@ -610,7 +643,8 @@ * Destroys the SpriteBatch. * */ -WebGLSpriteBatch.prototype.destroy = function () { +WebGLSpriteBatch.prototype.destroy = function () +{ this.renderer.gl.deleteBuffer(this.vertexBuffer); this.renderer.gl.deleteBuffer(this.indexBuffer); diff --git a/src/core/textures/BaseTexture.js b/src/core/textures/BaseTexture.js index 2bf77d4..513d358 100644 --- a/src/core/textures/BaseTexture.js +++ b/src/core/textures/BaseTexture.js @@ -10,7 +10,8 @@ * @param source {Image|Canvas} the source object of the texture. * @param [scaleMode=scaleModes.DEFAULT] {number} See {@link scaleModes} for possible values */ -function BaseTexture(source, scaleMode) { +function BaseTexture(source, scaleMode) +{ this.uuid = utils.uuid(); /** @@ -123,7 +124,8 @@ this._needsUpdate = false; // if no source passed don't try to load - if (source) { + if (source) + { this.loadSource(source); } @@ -149,13 +151,16 @@ Object.defineProperties(BaseTexture.prototype, { needsUpdate: { - get: function () { + get: function () + { return this._needsUpdate; }, - set: function (val) { + set: function (val) + { this._needsUpdate = val; - if (val) { + if (val) + { this.emit('update', this); } } @@ -171,9 +176,11 @@ * * The logic state after calling `loadSource` directly or indirectly (eg. `fromImage`, `new BaseTexture`) is: * - * if (texture.hasLoaded) { + * if (texture.hasLoaded) + { * // texture ready for use - * } else if (texture.isLoading) { + * } else if (texture.isLoading) + { * // listen to 'loaded' and/or 'error' events on texture * } else { * // not loading, not going to load UNLESS the source is reloaded @@ -183,12 +190,14 @@ * @protected * @param source {Image|Canvas} the source object of the texture. */ -BaseTexture.prototype.loadSource = function (source) { +BaseTexture.prototype.loadSource = function (source) +{ var wasLoading = this.isLoading; this.hasLoaded = false; this.isLoading = false; - if (wasLoading && this.source) { + if (wasLoading && this.source) + { this.source.onload = null; this.source.onerror = null; } @@ -196,20 +205,24 @@ this.source = source; // Apply source if loaded. Otherwise setup appropriate loading monitors. - if ((this.source.complete || this.source.getContext) && this.source.width && this.source.height) { + if ((this.source.complete || this.source.getContext) && this.source.width && this.source.height) + { this._sourceLoaded(); } - else if(!source.getContext) { + else if(!source.getContext) + { // Image fail / not ready this.isLoading = true; var scope = this; - source.onload = function () { + source.onload = function () + { source.onload = null; source.onerror = null; - if(!scope.isLoading) { + if(!scope.isLoading) + { return; } @@ -219,11 +232,13 @@ scope.emit('loaded', scope); }; - source.onerror = function () { + source.onerror = function () + { source.onload = null; source.onerror = null; - if(!scope.isLoading) { + if(!scope.isLoading) + { return; } @@ -234,24 +249,29 @@ // Per http://www.w3.org/TR/html5/embedded-content-0.html#the-img-element // "The value of `complete` can thus change while a script is executing." // So complete needs to be re-checked after the callbacks have been added.. - if (source.complete) { + if (source.complete) + { this.isLoading = false; // ..and if we're complete now, no need for callbacks source.onload = null; source.onerror = null; - if (source.width && source.height) { + if (source.width && source.height) + { this._sourceLoaded(); // If any previous subscribers possible - if (wasLoading) { + if (wasLoading) + { this.emit('loaded', this); } } - else { + else + { // If any previous subscribers possible - if (wasLoading) { + if (wasLoading) + { this.emit('error', this); } } @@ -265,7 +285,8 @@ * * @private */ -BaseTexture.prototype._sourceLoaded = function () { +BaseTexture.prototype._sourceLoaded = function () +{ this.hasLoaded = true; this.width = this.source.naturalWidth || this.source.width; @@ -278,16 +299,20 @@ * Destroys this base texture * */ -BaseTexture.prototype.destroy = function () { - if (this.imageUrl) { +BaseTexture.prototype.destroy = function () +{ + if (this.imageUrl) + { delete utils.BaseTextureCache[this.imageUrl]; delete utils.TextureCache[this.imageUrl]; this.imageUrl = null; - if (!navigator.isCocoonJS) { + if (!navigator.isCocoonJS) + { this.source.src = ''; } } - else if (this.source && this.source._pixiId) { + else if (this.source && this.source._pixiId) + { delete utils.BaseTextureCache[this.source._pixiId]; } this.source = null; @@ -301,7 +326,8 @@ * memory again. * */ -BaseTexture.prototype.dispose = function () { +BaseTexture.prototype.dispose = function () +{ this.emit('dispose', this); }; @@ -311,7 +337,8 @@ * * @param newSrc {string} the path of the image */ -BaseTexture.prototype.updateSourceImage = function (newSrc) { +BaseTexture.prototype.updateSourceImage = function (newSrc) +{ this.source.src = newSrc; this.loadSource(this.source); }; @@ -326,18 +353,22 @@ * @param [scaleMode=scaleModes.DEFAULT] {number} See {@link scaleModes} for possible values * @return BaseTexture */ -BaseTexture.fromImage = function (imageUrl, crossorigin, scaleMode) { +BaseTexture.fromImage = function (imageUrl, crossorigin, scaleMode) +{ var baseTexture = utils.BaseTextureCache[imageUrl]; - if (crossorigin === undefined && imageUrl.indexOf('data:') !== 0) { + if (crossorigin === undefined && imageUrl.indexOf('data:') !== 0) + { crossorigin = true; } - if (!baseTexture) { + if (!baseTexture) + { // new Image() breaks tex loading in some versions of Chrome. // See https://code.google.com/p/chromium/issues/detail?id=238071 var image = new Image();//document.createElement('img'); - if (crossorigin) { + if (crossorigin) + { image.crossOrigin = ''; } @@ -347,7 +378,8 @@ utils.BaseTextureCache[imageUrl] = baseTexture; // if there is an @2x at the end of the url we are going to assume its a highres image - if ( imageUrl.indexOf(CONST.RETINA_PREFIX + '.') !== -1) { + if ( imageUrl.indexOf(CONST.RETINA_PREFIX + '.') !== -1) + { baseTexture.resolution = 2; } } @@ -363,14 +395,17 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return BaseTexture */ -BaseTexture.fromCanvas = function (canvas, scaleMode) { - if (!canvas._pixiId) { +BaseTexture.fromCanvas = function (canvas, scaleMode) +{ + if (!canvas._pixiId) + { canvas._pixiId = 'canvas_' + utils.uuid(); } var baseTexture = utils.BaseTextureCache[canvas._pixiId]; - if (!baseTexture) { + if (!baseTexture) + { baseTexture = new BaseTexture(canvas, scaleMode); utils.BaseTextureCache[canvas._pixiId] = baseTexture; } diff --git a/src/core/textures/RenderTexture.js b/src/core/textures/RenderTexture.js index 6dad20f..53ae796 100644 --- a/src/core/textures/RenderTexture.js +++ b/src/core/textures/RenderTexture.js @@ -46,8 +46,10 @@ * @param [scaleMode] {number} See {@link scaleModes} for possible values * @param [resolution=1] {number} The resolution of the texture being generated */ -function RenderTexture(renderer, width, height, scaleMode, resolution) { - if (!renderer) { +function RenderTexture(renderer, width, height, scaleMode, resolution) +{ + if (!renderer) + { throw new Error('Unable to create RenderTexture, you must pass a renderer into the constructor.'); } @@ -133,7 +135,8 @@ */ this.renderer = renderer; - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { var gl = this.renderer.gl; this.textureBuffer = new FilterTexture(gl, this.width * this.resolution, this.height * this.resolution, this.baseTexture.scaleMode); @@ -142,7 +145,8 @@ this.render = this.renderWebGL; this.projection = new math.Point(this.width*0.5, -this.height*0.5); } - else { + else + { this.render = this.renderCanvas; this.textureBuffer = new CanvasBuffer(this.width* this.resolution, this.height* this.resolution); this.baseTexture.source = this.textureBuffer.canvas; @@ -167,8 +171,10 @@ * @param height {number} The height to resize to. * @param updateBase {boolean} Should the baseTexture.width and height values be resized as well? */ -RenderTexture.prototype.resize = function (width, height, updateBase) { - if (width === this.width && height === this.height) { +RenderTexture.prototype.resize = function (width, height, updateBase) +{ + if (width === this.width && height === this.height) + { return; } @@ -177,17 +183,20 @@ this.width = this.frame.width = this.crop.width = width; this.height = this.frame.height = this.crop.height = height; - if (updateBase) { + if (updateBase) + { this.baseTexture.width = this.width; this.baseTexture.height = this.height; } - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { this.projection.x = this.width / 2; this.projection.y = -this.height / 2; } - if (!this.valid) { + if (!this.valid) + { return; } @@ -198,12 +207,15 @@ * Clears the RenderTexture. * */ -RenderTexture.prototype.clear = function () { - if (!this.valid) { +RenderTexture.prototype.clear = function () +{ + if (!this.valid) + { return; } - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { this.renderer.gl.bindFramebuffer(this.renderer.gl.FRAMEBUFFER, this.textureBuffer.frameBuffer); } @@ -220,19 +232,23 @@ * @param [restoreWorldTransform=true] {boolean} If true the displayObject's worldTransform/worldAlpha and all children * transformations will be restored. Not restoring this information will be a little faster. */ -RenderTexture.prototype.renderWebGL = function (displayObject, matrix, clear, restoreWorldTransform) { - if (!this.valid) { +RenderTexture.prototype.renderWebGL = function (displayObject, matrix, clear, restoreWorldTransform) +{ + if (!this.valid) + { return; } - if (typeof restoreWorldTransform === 'undefined') { + if (typeof restoreWorldTransform === 'undefined') + { restoreWorldTransform = true; } var tempAlpha, tempTransform; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { tempAlpha = displayObject.worldAlpha; tempTransform = displayObject.worldTransform.toArray(); } @@ -245,7 +261,8 @@ wt.identity(); wt.translate(0, this.projection.y * 2); - if (matrix) { + if (matrix) + { wt.append(matrix); } @@ -258,7 +275,8 @@ var children = displayObject.children; var i, j; - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } @@ -269,7 +287,8 @@ gl.bindFramebuffer(gl.FRAMEBUFFER, this.textureBuffer.frameBuffer ); - if (clear) { + if (clear) + { this.textureBuffer.clear(); } @@ -279,11 +298,13 @@ this.renderer.spriteBatch.dirty = true; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { displayObject.worldAlpha = tempAlpha; displayObject.worldTransform.fromArray(tempTransform); - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } } @@ -300,26 +321,31 @@ * @param [restoreWorldTransform=true] {boolean} If true the displayObject's worldTransform/worldAlpha and all children * transformations will be restored. Not restoring this information will be a little faster. */ -RenderTexture.prototype.renderCanvas = function (displayObject, matrix, clear, restoreWorldTransform) { - if (!this.valid) { +RenderTexture.prototype.renderCanvas = function (displayObject, matrix, clear, restoreWorldTransform) +{ + if (!this.valid) + { return; } - if (typeof restoreWorldTransform === 'undefined') { + if (typeof restoreWorldTransform === 'undefined') + { restoreWorldTransform = true; } var tempAlpha, tempTransform; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { tempAlpha = displayObject.worldAlpha; tempTransform = displayObject.worldTransform.toArray(); } var wt = displayObject.worldTransform; wt.identity(); - if (matrix) { + if (matrix) + { wt.append(matrix); } @@ -330,11 +356,13 @@ var children = displayObject.children; var i, j; - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } - if (clear) { + if (clear) + { this.textureBuffer.clear(); } @@ -348,11 +376,13 @@ this.renderer.resolution = realResolution; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { displayObject.worldAlpha = tempAlpha; displayObject.worldTransform.fromArray(tempTransform); - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } } @@ -363,7 +393,8 @@ * * @return {Image} */ -RenderTexture.prototype.getImage = function () { +RenderTexture.prototype.getImage = function () +{ var image = new Image(); image.src = this.getBase64(); return image; @@ -374,7 +405,8 @@ * * @return {string} A base64 encoded string of the texture. */ -RenderTexture.prototype.getBase64 = function () { +RenderTexture.prototype.getBase64 = function () +{ return this.getCanvas().toDataURL(); }; @@ -383,8 +415,10 @@ * * @return {HTMLCanvasElement} A Canvas element with the texture rendered on. */ -RenderTexture.prototype.getCanvas = function () { - if (this.renderer.type === CONST.WEBGL_RENDERER) { +RenderTexture.prototype.getCanvas = function () +{ + if (this.renderer.type === CONST.WEBGL_RENDERER) + { var gl = this.renderer.gl; var width = this.textureBuffer.width; var height = this.textureBuffer.height; @@ -403,7 +437,8 @@ return tempCanvas.canvas; } - else { + else + { return this.textureBuffer.canvas; } }; diff --git a/src/core/textures/Texture.js b/src/core/textures/Texture.js index 3c65909..e97f0aa 100644 --- a/src/core/textures/Texture.js +++ b/src/core/textures/Texture.js @@ -17,7 +17,8 @@ * @param [crop] {Rectangle} The area of original texture * @param [trim] {Rectangle} Trimmed texture rectangle */ -function Texture(baseTexture, frame, crop, trim) { +function Texture(baseTexture, frame, crop, trim) +{ /** * Does this Texture have any frame data assigned to it? * @@ -25,12 +26,14 @@ */ this.noFrame = false; - if (!frame) { + if (!frame) + { this.noFrame = true; frame = new math.Rectangle(0, 0, 1, 1); } - if (baseTexture instanceof Texture) { + if (baseTexture instanceof Texture) + { baseTexture = baseTexture.baseTexture; } @@ -100,13 +103,16 @@ */ this.crop = crop || new math.Rectangle(0, 0, 1, 1); - if (baseTexture.hasLoaded) { - if (this.noFrame) { + if (baseTexture.hasLoaded) + { + if (this.noFrame) + { frame = new math.Rectangle(0, 0, baseTexture.width, baseTexture.height); } this.frame = frame; } - else { + else + { baseTexture.addEventListener('loaded', this.onBaseTextureLoaded.bind(this)); } } @@ -118,19 +124,23 @@ Object.defineProperties(Texture.prototype, { needsUpdate: { - get: function () { + get: function () + { return this.baseTexture.needsUpdate; }, - set: function (val) { + set: function (val) + { this.baseTexture.needsUpdate = val; } }, frame: { - get: function () { + get: function () + { return this._frame; }, - set: function (frame) { + set: function (frame) + { this._frame = frame; this.noFrame = false; @@ -143,20 +153,23 @@ 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 (!this.trim && (frame.x + frame.width > this.baseTexture.width || frame.y + frame.height > this.baseTexture.height)) + { throw new Error('Texture Error: frame does not fit inside the base Texture dimensions ' + this); } this.valid = frame && frame.width && frame.height && this.baseTexture.source && this.baseTexture.hasLoaded; - if (this.trim) { + 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) { + if (this.valid) + { this._updateUvs(); } } @@ -168,11 +181,13 @@ * * @private */ -Texture.prototype.onBaseTextureLoaded = function () { +Texture.prototype.onBaseTextureLoaded = function () +{ var baseTexture = this.baseTexture; baseTexture.removeEventListener('loaded', this.onLoaded); - if (this.noFrame) { + if (this.noFrame) + { this.frame = new math.Rectangle(0, 0, baseTexture.width, baseTexture.height); } @@ -184,8 +199,10 @@ * * @param destroyBase {boolean} Whether to destroy the base texture as well */ -Texture.prototype.destroy = function (destroyBase) { - if (destroyBase) { +Texture.prototype.destroy = function (destroyBase) +{ + if (destroyBase) + { this.baseTexture.destroy(); } @@ -197,8 +214,10 @@ * * @private */ -Texture.prototype._updateUvs = function () { - if (!this._uvs) { +Texture.prototype._updateUvs = function () +{ + if (!this._uvs) + { this._uvs = new TextureUvs(); } @@ -229,10 +248,12 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return Texture */ -Texture.fromImage = function (imageUrl, crossorigin, scaleMode) { +Texture.fromImage = function (imageUrl, crossorigin, scaleMode) +{ var texture = utils.TextureCache[imageUrl]; - if (!texture) { + if (!texture) + { texture = new Texture(BaseTexture.fromImage(imageUrl, crossorigin, scaleMode)); utils.TextureCache[imageUrl] = texture; } @@ -248,9 +269,11 @@ * @param frameId {string} The frame id of the texture * @return Texture */ -Texture.fromFrame = function (frameId) { +Texture.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache '); } return texture; @@ -264,7 +287,8 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return {Texture} */ -Texture.fromCanvas = function (canvas, scaleMode) { +Texture.fromCanvas = function (canvas, scaleMode) +{ return new Texture(BaseTexture.fromCanvas(canvas, scaleMode)); }; @@ -276,7 +300,8 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return {Texture} A Texture */ -Texture.fromVideo = function (video, scaleMode) { +Texture.fromVideo = function (video, scaleMode) +{ return new Texture(VideoBaseTexture.baseTextureFromVideo(video, scaleMode)); }; @@ -287,7 +312,8 @@ * @param texture {Texture} The Texture to add to the cache. * @param id {string} The id that the texture will be stored against. */ -Texture.addTextureToCache = function (texture, id) { +Texture.addTextureToCache = function (texture, id) +{ utils.TextureCache[id] = texture; }; @@ -298,7 +324,8 @@ * @param id {string} The id of the texture to be removed * @return {Texture} The texture that was removed */ -Texture.removeTextureFromCache = function (id) { +Texture.removeTextureFromCache = function (id) +{ var texture = utils.TextureCache[id]; delete utils.TextureCache[id]; diff --git a/src/core/textures/TextureUvs.js b/src/core/textures/TextureUvs.js index b9bbb58..5424d52 100644 --- a/src/core/textures/TextureUvs.js +++ b/src/core/textures/TextureUvs.js @@ -1,4 +1,5 @@ -function TextureUvs() { +function TextureUvs() +{ this.x0 = 0; this.y0 = 0; diff --git a/src/core/textures/VideoBaseTexture.js b/src/core/textures/VideoBaseTexture.js index e3e0c5a..1a826a9 100644 --- a/src/core/textures/VideoBaseTexture.js +++ b/src/core/textures/VideoBaseTexture.js @@ -12,15 +12,18 @@ * @param source {HTMLVideoElement} * @param [scaleMode] {number} See {@link scaleModes} for possible values */ -function VideoBaseTexture(source, scaleMode) { - if (!source){ +function VideoBaseTexture(source, scaleMode) +{ + if (!source) + { throw new Error('No video source element specified.'); } // hook in here to check if video is already available. // BaseTexture looks for a source.complete boolean, plus width & height. - if ((source.readyState === source.HAVE_ENOUGH_DATA || source.readyState === source.HAVE_FUTURE_DATA) && source.width && source.height) { + if ((source.readyState === source.HAVE_ENOUGH_DATA || source.readyState === source.HAVE_FUTURE_DATA) && source.width && source.height) + { source.complete = true; } @@ -31,7 +34,8 @@ this._boundOnUpdate = this._onUpdate.bind(this); this._boundOnCanPlay = this._onCanPlay.bind(this); - if (!source.complete) { + if (!source.complete) + { source.addEventListener('canplay', this._boundOnCanPlay); source.addEventListener('canplaythrough', this._boundOnCanPlay); @@ -47,28 +51,35 @@ VideoBaseTexture.prototype.constructor = VideoBaseTexture; module.exports = VideoBaseTexture; -VideoBaseTexture.prototype._onUpdate = function () { - if (this.autoUpdate) { +VideoBaseTexture.prototype._onUpdate = function () +{ + if (this.autoUpdate) + { window.requestAnimationFrame(this._boundOnUpdate); this.needsUpdate = true; } }; -VideoBaseTexture.prototype._onPlayStart = function () { - if (!this.autoUpdate) { +VideoBaseTexture.prototype._onPlayStart = function () +{ + if (!this.autoUpdate) + { window.requestAnimationFrame(this._boundOnUpdate); this.autoUpdate = true; } }; -VideoBaseTexture.prototype._onPlayStop = function () { +VideoBaseTexture.prototype._onPlayStop = function () +{ this.autoUpdate = false; }; -VideoBaseTexture.prototype._onCanPlay = function () { +VideoBaseTexture.prototype._onCanPlay = function () +{ this.hasLoaded = true; - if (this.source) { + if (this.source) + { this.source.removeEventListener('canplay', this._boundOnCanPlay); this.source.removeEventListener('canplaythrough', this._boundOnCanPlay); @@ -78,15 +89,18 @@ this.source.play(); // prevent multiple loaded dispatches.. - if(!this.__loaded){ + if(!this.__loaded) + { this.__loaded = true; this.emit('loaded', this); } } }; -VideoBaseTexture.prototype.destroy = function () { - if (this.source && this.source._pixiId) { +VideoBaseTexture.prototype.destroy = function () +{ + if (this.source && this.source._pixiId) + { utils.BaseTextureCache[ this.source._pixiId ] = null; delete utils.BaseTextureCache[ this.source._pixiId ]; @@ -105,14 +119,17 @@ * @param scaleMode {number} See {@link scaleModes} for possible values * @return {VideoBaseTexture} */ -VideoBaseTexture.fromVideo = function (video, scaleMode) { - if (!video._pixiId) { +VideoBaseTexture.fromVideo = function (video, scaleMode) +{ + if (!video._pixiId) + { video._pixiId = 'video_' + utils.uuid(); } var baseTexture = utils.BaseTextureCache[video._pixiId]; - if (!baseTexture) { + if (!baseTexture) + { baseTexture = new VideoBaseTexture(video, scaleMode); utils.BaseTextureCache[ video._pixiId ] = baseTexture; } @@ -147,17 +164,21 @@ * @param scaleMode {number} See {@link scaleModes} for possible values * @return {VideoBaseTexture} */ -VideoBaseTexture.fromUrl = function (videoSrc, scaleMode) { +VideoBaseTexture.fromUrl = function (videoSrc, scaleMode) +{ var video = document.createElement('video'); // array of objects or strings - if (Array.isArray(videoSrc)) { - for (var i = 0; i < videoSrc.length; ++i) { + if (Array.isArray(videoSrc)) + { + for (var i = 0; i < videoSrc.length; ++i) + { video.appendChild(createSource(videoSrc.src || videoSrc, videoSrc.mime)); } } // single object or string - else { + else + { video.appendChild(createSource(videoSrc.src || videoSrc, videoSrc.mime)); } @@ -169,8 +190,10 @@ VideoBaseTexture.fromUrls = VideoBaseTexture.fromUrl; -function createSource(path, type) { - if (!type) { +function createSource(path, type) +{ + if (!type) + { type = 'video/' + path.substr(path.lastIndexOf('.') + 1); } diff --git a/src/core/utils/EventData.js b/src/core/utils/EventData.js index 5d55a22..8cdf701 100644 --- a/src/core/utils/EventData.js +++ b/src/core/utils/EventData.js @@ -7,7 +7,8 @@ * @param name {string} The string name of the event that was triggered * @param data {object} Arbitrary event data to pass along */ -function EventData(target, name, data) { +function EventData(target, name, data) +{ // for duck typing in the ".on()" function this.__isEventObject = true; @@ -71,7 +72,8 @@ * Stops the propagation of events up the scene graph (prevents bubbling). * */ -EventData.prototype.stopPropagation = function stopPropagation() { +EventData.prototype.stopPropagation = function stopPropagation() +{ this.stopped = true; }; @@ -79,6 +81,7 @@ * Stops the propagation of events to sibling listeners (no longer calls any listeners). * */ -EventData.prototype.stopImmediatePropagation = function stopImmediatePropagation() { +EventData.prototype.stopImmediatePropagation = function stopImmediatePropagation() +{ this.stoppedImmediate = true; }; diff --git a/src/core/utils/EventTarget.js b/src/core/utils/EventTarget.js index 7ae8820..671a151 100644 --- a/src/core/utils/EventTarget.js +++ b/src/core/utils/EventTarget.js @@ -13,14 +13,16 @@ * var em = new MyEmitter(); * em.emit('eventName', 'some data', 'some more data', {}, null, ...); */ -function eventTarget(obj) { +function eventTarget(obj) +{ /** * Return a list of assigned event listeners. * * @param eventName {string} The events that should be listed. * @return {Array} An array of listener functions */ - obj.listeners = function listeners(eventName) { + obj.listeners = function listeners(eventName) + { this._listeners = this._listeners || {}; return this._listeners[eventName] ? this._listeners[eventName].slice() : []; @@ -33,22 +35,26 @@ * @param eventName {string} The name of the event. * @return {boolean} Indication if we've emitted an event. */ - obj.emit = obj.dispatchEvent = function emit(eventName, data) { + obj.emit = obj.dispatchEvent = function emit(eventName, data) + { this._listeners = this._listeners || {}; // fast return when there are no listeners - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return; } //backwards compat with old method ".emit({ type: 'something' })" - if (typeof eventName === 'object') { + if (typeof eventName === 'object') + { data = eventName; eventName = eventName.type; } //ensure we are using a real pixi event - if (!data || data.__isEventObject !== true) { + if (!data || data.__isEventObject !== true) + { data = new EventData(this, eventName, data); } @@ -58,23 +64,27 @@ fn = listeners[0], i; - for (i = 0; i < length; fn = listeners[++i]) { + for (i = 0; i < length; fn = listeners[++i]) + { //call the event listener fn.call(this, data); //if "stopImmediatePropagation" is called, stop calling sibling events - if (data.stoppedImmediate) { + if (data.stoppedImmediate) + { return this; } } //if "stopPropagation" is called then don't bubble the event - if (data.stopped) { + if (data.stopped) + { return this; } //bubble this event up the scene graph - if (this.parent && this.parent.emit) { + if (this.parent && this.parent.emit) + { this.parent.emit.call(this.parent, eventName, data); } @@ -88,7 +98,8 @@ * @param eventName {string} Name of the event. * @param callback {Functon} fn Callback function. */ - obj.on = obj.addEventListener = function on(eventName, fn) { + obj.on = obj.addEventListener = function on(eventName, fn) + { this._listeners = this._listeners || {}; (this._listeners[eventName] = this._listeners[eventName] || []) @@ -103,11 +114,13 @@ * @param eventName {string} Name of the event. * @param callback {Function} Callback function. */ - obj.once = function once(eventName, fn) { + obj.once = function once(eventName, fn) + { this._listeners = this._listeners || {}; var self = this; - function onceHandlerWrapper() { + function onceHandlerWrapper() + { fn.apply(self.off(eventName, onceHandlerWrapper), arguments); } onceHandlerWrapper._originalHandler = fn; @@ -122,23 +135,28 @@ * @param eventName {string} The event we want to remove. * @param callback {Function} The listener that we need to find. */ - obj.off = obj.removeEventListener = function off(eventName, fn) { + obj.off = obj.removeEventListener = function off(eventName, fn) + { this._listeners = this._listeners || {}; - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return this; } var list = this._listeners[eventName], i = fn ? list.length : 0; - while(i-- > 0) { - if (list[i] === fn || list[i]._originalHandler === fn) { + while(i-- > 0) + { + if (list[i] === fn || list[i]._originalHandler === fn) + { list.splice(i, 1); } } - if (list.length === 0) { + if (list.length === 0) + { delete this._listeners[eventName]; } @@ -150,10 +168,12 @@ * * @param eventName {string} The event you want to remove all listeners for. */ - obj.removeAllListeners = function removeAllListeners(eventName) { + obj.removeAllListeners = function removeAllListeners(eventName) + { this._listeners = this._listeners || {}; - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return this; } @@ -169,7 +189,8 @@ * * @param object {object} The obj to mix into */ - mixin: function mixin(obj) { + mixin: function mixin(obj) + { eventTarget(obj); } }; diff --git a/src/core/utils/PolyK.js b/src/core/utils/PolyK.js index 7325141..5e20c2b 100644 --- a/src/core/utils/PolyK.js +++ b/src/core/utils/PolyK.js @@ -47,7 +47,8 @@ * Triangulates shapes for webGL graphic fills. * */ -PolyK.Triangulate = function (p) { +PolyK.Triangulate = function (p) +{ var sign = true; var n = p.length >> 1; @@ -59,7 +60,8 @@ i = 0; var al = n; - while(al > 3) { + while(al > 3) + { var i0 = avl[(i+0)%al]; var i1 = avl[(i+1)%al]; var i2 = avl[(i+2)%al]; @@ -69,29 +71,35 @@ var cx = p[2*i2], cy = p[2*i2+1]; var earFound = false; - if (PolyK._convex(ax, ay, bx, by, cx, cy, sign)) { + if (PolyK._convex(ax, ay, bx, by, cx, cy, sign)) + { earFound = true; - for (var j = 0; j < al; j++) { + for (var j = 0; j < al; j++) + { var vi = avl[j]; if (vi === i0 || vi === i1 || vi === i2) continue; - if (PolyK._PointInTriangle(p[2*vi], p[2*vi+1], ax, ay, bx, by, cx, cy)) { + if (PolyK._PointInTriangle(p[2*vi], p[2*vi+1], ax, ay, bx, by, cx, cy)) + { earFound = false; break; } } } - if (earFound) { + if (earFound) + { tgs.push(i0, i1, i2); avl.splice((i+1)%al, 1); al--; i = 0; } - else if (i++ > 3*al) { + else if (i++ > 3*al) + { // need to flip flip reverse it! // reset! - if (sign) { + if (sign) + { tgs = []; avl = []; for (i = 0; i < n; i++) avl.push(i); @@ -101,7 +109,8 @@ sign = false; } - else { + else + { // window.console.log("PIXI Warning: shape too complex to fill"); return null; } @@ -126,7 +135,8 @@ * @private * @return {boolean} */ -PolyK._PointInTriangle = function (px, py, ax, ay, bx, by, cx, cy) { +PolyK._PointInTriangle = function (px, py, ax, ay, bx, by, cx, cy) +{ var v0x = cx-ax; var v0y = cy-ay; var v1x = bx-ax; @@ -154,6 +164,7 @@ * @private * @return {boolean} */ -PolyK._convex = function (ax, ay, bx, by, cx, cy, sign) { +PolyK._convex = function (ax, ay, bx, by, cx, cy, sign) +{ return ((ay-by)*(cx-bx) + (bx-ax)*(cy-by) >= 0) === sign; }; diff --git a/src/core/utils/index.js b/src/core/utils/index.js index ade9831..bfae7ae 100644 --- a/src/core/utils/index.js +++ b/src/core/utils/index.js @@ -16,7 +16,8 @@ * * @return {number} The next uuid to use. */ - uuid: function () { + uuid: function () + { return ++utils._uid; }, @@ -26,7 +27,8 @@ * @param hex {number} * @return {number[]} An array representing the [R, G, B] of the color. */ - hex2rgb: function (hex, out) { + hex2rgb: function (hex, out) + { out = out || []; out[0] = (hex >> 16 & 0xFF) / 255; @@ -42,7 +44,8 @@ * @param hex {number} * @return {string} The string color. */ - hex2string: function (hex) { + hex2string: function (hex) + { hex = hex.toString(16); hex = '000000'.substr(0, 6 - hex.length) + hex; @@ -55,7 +58,8 @@ * @param rgb {number[]} * @return {number} The color number */ - rgb2hex: function (rgb) { + rgb2hex: function (rgb) + { return ((rgb[0]*255 << 16) + (rgb[1]*255 << 8) + rgb[2]*255); }, @@ -64,8 +68,10 @@ * * @return {boolean} whether they are supported */ - canUseNewCanvasBlendModes: function () { - if (typeof document === 'undefined') { + canUseNewCanvasBlendModes: function () + { + if (typeof document === 'undefined') + { return false; } @@ -93,15 +99,19 @@ * @param number {number} * @return {number} the closest number that is a power of two */ - getNextPowerOfTwo: function (number) { + getNextPowerOfTwo: function (number) + { // see: http://en.wikipedia.org/wiki/Power_of_two#Fast_algorithm_to_check_if_a_positive_number_is_a_power_of_two - if (number > 0 && (number & (number - 1)) === 0) { + if (number > 0 && (number & (number - 1)) === 0) + { return number; } - else { + else + { var result = 1; - while (result < number) { + while (result < number) + { result <<= 1; } @@ -116,7 +126,8 @@ * @param height {number} * @return {boolean} */ - isPowerOfTwo: function (width, height) { + isPowerOfTwo: function (width, height) + { return (width > 0 && (width & (width - 1)) === 0 && height > 0 && (height & (height - 1)) === 0); }, @@ -130,12 +141,15 @@ * @constant * @static */ - sayHello: function (type) { - if (utils._saidHello) { + sayHello: function (type) + { + if (utils._saidHello) + { return; } - if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) { + if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) + { var args = [ '%c %c %c Pixi.js ' + CONST.VERSION + ' - ' + type + ' %c ' + ' %c ' + ' http://www.pixijs.com/ %c %c ♥%c♥%c♥ ', 'background: #ff66a5', @@ -151,7 +165,8 @@ console.log.apply(console, args); //jshint ignore:line } - else if (window.console) { + else if (window.console) + { console.log('Pixi.js ' + CONST.VERSION + ' - ' + type + ' - http://www.pixijs.com/'); //jshint ignore:line } @@ -166,15 +181,19 @@ * @class * @namespace PIXI */ - AjaxRequest: function () { + AjaxRequest: function () + { var activexmodes = ['Msxml2.XMLHTTP.6.0', 'Msxml2.XMLHTTP.3.0', 'Microsoft.XMLHTTP']; //activeX versions to check for in IE - if (window.ActiveXObject) { //Test for support for ActiveXObject in IE first (as XMLHttpRequest in IE7 is broken) - for (var i=0; i= this.textures.length) { + else if (round >= this.textures.length) + { this.gotoAndStop(this.textures.length - 1); - if (this.onComplete) { + if (this.onComplete) + { this.onComplete(); } } @@ -167,10 +182,12 @@ * @static * @param frames {string[]} the array of frames ids the movieclip will use as its texture frames */ -MovieClip.fromFrames = function (frames) { +MovieClip.fromFrames = function (frames) +{ var textures = []; - for (var i = 0; i < frames.length; ++i) { + for (var i = 0; i < frames.length; ++i) + { textures.push(new core.Texture.fromFrame(frames[i])); } @@ -183,10 +200,12 @@ * @static * @param images {string[]} the array of image urls the movieclip will use as its texture frames */ -MovieClip.fromImages = function (images) { +MovieClip.fromImages = function (images) +{ var textures = []; - for (var i = 0; i < images.length; ++i) { + for (var i = 0; i < images.length; ++i) + { textures.push(new core.Texture.fromImage(images[i])); } diff --git a/src/extras/Rope.js b/src/extras/Rope.js index c157ec4..9c87bc0 100644 --- a/src/extras/Rope.js +++ b/src/extras/Rope.js @@ -9,7 +9,8 @@ * @param {Array} points - An array of {Point}. * */ -function Rope(texture, points) { +function Rope(texture, points) +{ Strip.call(this, texture); this.points = points; @@ -31,10 +32,12 @@ * Refreshes * */ -Rope.prototype.refresh = function () { +Rope.prototype.refresh = function () +{ var points = this.points; - if (points.length < 1) { + if (points.length < 1) + { return; } @@ -59,20 +62,23 @@ var total = points.length, point, index, amount; - for (var i = 1; i < total; i++) { + for (var i = 1; i < total; i++) + { point = points[i]; index = i * 4; // time to do some smart drawing! amount = i / (total-1); - if (i%2) { + if (i%2) + { uvs[index] = amount; uvs[index+1] = 0; uvs[index+2] = amount; uvs[index+3] = 1; } - else { + else + { uvs[index] = amount; uvs[index+1] = 0; @@ -95,10 +101,12 @@ * * @private */ -Rope.prototype.updateTransform = function () { +Rope.prototype.updateTransform = function () +{ var points = this.points; - if (points.length < 1) { + if (points.length < 1) + { return; } @@ -113,14 +121,17 @@ var total = points.length, point, index, ratio, perpLength, num; - for (var i = 0; i < total; i++) { + for (var i = 0; i < total; i++) + { point = points[i]; index = i * 4; - if (i < points.length-1) { + if (i < points.length-1) + { nextPoint = points[i+1]; } - else { + else + { nextPoint = point; } @@ -129,7 +140,8 @@ ratio = (1 - (i / (total-1))) * 10; - if (ratio > 1) { + if (ratio > 1) + { ratio = 1; } @@ -157,7 +169,8 @@ * * @param texture {Texture} the texture that will be used */ -Rope.prototype.setTexture = function (texture) { +Rope.prototype.setTexture = function (texture) +{ // stop current texture this.texture = texture; //this.updateFrame = true; diff --git a/src/extras/Strip.js b/src/extras/Strip.js index c5e378f..57691b5 100644 --- a/src/extras/Strip.js +++ b/src/extras/Strip.js @@ -10,7 +10,8 @@ * @param height {number} the height * */ -function Strip(texture) { +function Strip(texture) +{ core.DisplayObjectContainer.call(this); /** @@ -70,9 +71,11 @@ * * @param renderer {WebGLRenderer} */ -Strip.prototype.renderWebGL = function (renderer) { +Strip.prototype.renderWebGL = function (renderer) +{ // if the sprite is not visible or the alpha is 0 then no need to render this element - if (!this.visible || this.alpha <= 0) { + if (!this.visible || this.alpha <= 0) + { return; } @@ -81,7 +84,8 @@ renderer.spriteBatch.stop(); // init! init! - if (!this._vertexBuffer) { + if (!this._vertexBuffer) + { this._initWebGL(renderer); } @@ -96,7 +100,8 @@ //TODO check culling }; -Strip.prototype._initWebGL = function (renderer) { +Strip.prototype._initWebGL = function (renderer) +{ // build the strip! var gl = renderer.gl; @@ -118,7 +123,8 @@ gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this.indices, gl.STATIC_DRAW); }; -Strip.prototype._renderStrip = function (renderer) { +Strip.prototype._renderStrip = function (renderer) +{ var gl = renderer.gl; var projection = renderer.projection, offset = renderer.offset, @@ -137,7 +143,8 @@ gl.uniform2f(shader.offsetVector, -offset.x, -offset.y); gl.uniform1f(shader.alpha, this.worldAlpha); - if (!this.dirty) { + if (!this.dirty) + { gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexBuffer); gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); @@ -150,10 +157,12 @@ gl.activeTexture(gl.TEXTURE0); // check if a texture is dirty.. - if (this.texture.baseTexture._dirty[gl.id]) { + if (this.texture.baseTexture._dirty[gl.id]) + { renderer.updateTexture(this.texture.baseTexture); } - else { + else + { // bind the current texture gl.bindTexture(gl.TEXTURE_2D, this.texture.baseTexture._glTextures[gl.id]); } @@ -163,7 +172,8 @@ } - else { + else + { this.dirty = false; gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexBuffer); @@ -178,10 +188,12 @@ gl.activeTexture(gl.TEXTURE0); // check if a texture is dirty.. - if (this.texture.baseTexture._dirty[gl.id]) { + if (this.texture.baseTexture._dirty[gl.id]) + { renderer.updateTexture(this.texture.baseTexture); } - else { + else + { gl.bindTexture(gl.TEXTURE_2D, this.texture.baseTexture._glTextures[gl.id]); } @@ -203,27 +215,33 @@ * * @param renderer {CanvasRenderer} */ -Strip.prototype.renderCanvas = function (renderer) { +Strip.prototype.renderCanvas = function (renderer) +{ var context = renderer.context; var transform = this.worldTransform; - if (renderer.roundPixels) { + if (renderer.roundPixels) + { context.setTransform(transform.a, transform.b, transform.c, transform.d, transform.tx | 0, transform.ty | 0); } - else { + else + { context.setTransform(transform.a, transform.b, transform.c, transform.d, transform.tx, transform.ty); } - if (this.drawMode === Strip.DrawModes.TRIANGLE_STRIP) { + if (this.drawMode === Strip.DrawModes.TRIANGLE_STRIP) + { this._renderCanvasTriangleStrip(context); } - else { + else + { this._renderCanvasTriangles(context); } }; -Strip.prototype._renderCanvasTriangleStrip = function (context) { +Strip.prototype._renderCanvasTriangleStrip = function (context) +{ // draw triangles!! var vertices = this.vertices; var uvs = this.uvs; @@ -231,14 +249,16 @@ var length = vertices.length / 2; // this.count++; - for (var i = 0; i < length - 2; i++) { + for (var i = 0; i < length - 2; i++) + { // draw some triangles! var index = i * 2; this._renderCanvasDrawTriangle(context, vertices, uvs, index, (index + 2), (index + 4)); } }; -Strip.prototype._renderCanvasTriangles = function (context) { +Strip.prototype._renderCanvasTriangles = function (context) +{ // draw triangles!! var vertices = this.vertices; var uvs = this.uvs; @@ -247,14 +267,16 @@ var length = indices.length; // this.count++; - for (var i = 0; i < length; i += 3) { + for (var i = 0; i < length; i += 3) + { // draw some triangles! var index0 = indices[i] * 2, index1 = indices[i + 1] * 2, index2 = indices[i + 2] * 2; this._renderCanvasDrawTriangle(context, vertices, uvs, index0, index1, index2); } }; -Strip.prototype._renderCanvasDrawTriangle = function (context, vertices, uvs, index0, index1, index2) { +Strip.prototype._renderCanvasDrawTriangle = function (context, vertices, uvs, index0, index1, index2) +{ var textureSource = this.texture.baseTexture.source; var textureWidth = this.texture.width; var textureHeight = this.texture.height; @@ -265,7 +287,8 @@ var u0 = uvs[index0] * textureWidth, u1 = uvs[index1] * textureWidth, u2 = uvs[index2] * textureWidth; var v0 = uvs[index0 + 1] * textureHeight, v1 = uvs[index1 + 1] * textureHeight, v2 = uvs[index2 + 1] * textureHeight; - if (this.canvasPadding > 0) { + if (this.canvasPadding > 0) + { var paddingX = this.canvasPadding / this.worldTransform.a; var paddingY = this.canvasPadding / this.worldTransform.d; var centerX = (x0 + x1 + x2) / 3; @@ -332,7 +355,8 @@ * @param strip {Strip} The Strip to render * @private */ -Strip.prototype.renderStripFlat = function (strip) { +Strip.prototype.renderStripFlat = function (strip) +{ var context = this.context; var vertices = strip.vertices; @@ -340,7 +364,8 @@ // this.count++; context.beginPath(); - for (var i=1; i < length-2; i++) { + for (var i=1; i < length-2; i++) + { // draw some triangles! var index = i*2; @@ -358,7 +383,8 @@ }; /* -Strip.prototype.setTexture = function (texture) { +Strip.prototype.setTexture = function (texture) +{ //TODO SET THE TEXTURES //TODO VISIBILITY @@ -377,7 +403,8 @@ * @private */ -Strip.prototype.onTextureUpdate = function () { +Strip.prototype.onTextureUpdate = function () +{ this.updateFrame = true; }; @@ -387,7 +414,8 @@ * @param matrix {Matrix} the transformation matrix of the sprite * @return {Rectangle} the framing rectangle */ -Strip.prototype.getBounds = function (matrix) { +Strip.prototype.getBounds = function (matrix) +{ var worldTransform = matrix || this.worldTransform; var a = worldTransform.a; @@ -404,7 +432,8 @@ var minY = Infinity; var vertices = this.vertices; - for (var i = 0, n = vertices.length; i < n; i += 2) { + for (var i = 0, n = vertices.length; i < n; i += 2) + { var rawX = vertices[i], rawY = vertices[i + 1]; var x = (a * rawX) + (c * rawY) + tx; var y = (d * rawY) + (b * rawX) + ty; @@ -416,7 +445,8 @@ maxY = y > maxY ? y : maxY; } - if (minX === -Infinity || maxY === Infinity) { + if (minX === -Infinity || maxY === Infinity) + { return core.math.Rectangle.EMPTY; } diff --git a/src/extras/TilingSprite.js b/src/extras/TilingSprite.js index 3ac22df..31da393 100644 --- a/src/extras/TilingSprite.js +++ b/src/extras/TilingSprite.js @@ -10,7 +10,8 @@ * @param width {number} the width of the tiling sprite * @param height {number} the height of the tiling sprite */ -function TilingSprite(texture, width, height) { +function TilingSprite(texture, width, height) +{ core.Sprite.call( this, texture); /** @@ -86,10 +87,12 @@ * @memberof TilingSprite# */ width: { - get: function () { + get: function () + { return this._width; }, - set: function (value) { + set: function (value) + { this._width = value; } }, @@ -101,20 +104,25 @@ * @memberof TilingSprite# */ height: { - get: function () { + get: function () + { return this._height; }, - set: function (value) { + set: function (value) + { this._height = value; } }, texture: { - get: function () { + get: function () + { return this._texture; }, - set: function (value) { - if (this._texture === value) { + set: function (value) + { + if (this._texture === value) + { return; } @@ -130,51 +138,61 @@ * * @param renderer {WebGLRenderer} */ -TilingSprite.prototype.renderWebGL = function (renderer) { - if (!this.visible || this.alpha <= 0) { +TilingSprite.prototype.renderWebGL = function (renderer) +{ + if (!this.visible || this.alpha <= 0) + { return; } var i, j; - if (this._mask) { + if (this._mask) + { renderer.spriteBatch.stop(); renderer.maskManager.pushMask(this.mask, renderer); renderer.spriteBatch.start(); } - if (this._filters) { + if (this._filters) + { renderer.spriteBatch.flush(); renderer.filterManager.pushFilter(this._filterBlock); } - if (!this.tilingTexture || this.refreshTexture) { + if (!this.tilingTexture || this.refreshTexture) + { this.generateTilingTexture(true); - if (this.tilingTexture && this.tilingTexture.needsUpdate) { + if (this.tilingTexture && this.tilingTexture.needsUpdate) + { //TODO - tweaking renderer.updateTexture(this.tilingTexture.baseTexture); this.tilingTexture.needsUpdate = false; // this.tilingTexture._uvs = null; } } - else { + else + { renderer.spriteBatch.renderTilingSprite(this); } // simple render children! - for (i=0,j=this.children.length; i= 0; i--) { + for (var i = length - 1; i >= 0; i--) + { var child = children[i]; // push all interactive bits - if (child._interactive) { + if (child._interactive) + { iParent.interactiveChildren = true; //child.__iParent = iParent; this.interactiveItems.push(child); - if (child.children.length > 0) { + if (child.children.length > 0) + { this.collectInteractiveSprite(child, child); } } - else { + else + { child.__iParent = null; - if (child.children.length > 0) { + if (child.children.length > 0) + { this.collectInteractiveSprite(child, iParent); } } @@ -189,7 +196,8 @@ * @param [resolution=1] {number} THe resolution of the new element (relative to the canvas). * @private */ -InteractionManager.prototype.setTargetElement = function (element, resolution) { +InteractionManager.prototype.setTargetElement = function (element, resolution) +{ this.removeEvents(); this.interactionDOMElement = element; @@ -203,12 +211,15 @@ * * @private */ -InteractionManager.prototype.addEvents = function () { - if (!this.interactionDOMElement) { +InteractionManager.prototype.addEvents = function () +{ + if (!this.interactionDOMElement) + { return; } - if (window.navigator.msPointerEnabled) { + if (window.navigator.msPointerEnabled) + { this.interactionDOMElement.style['-ms-content-zooming'] = 'none'; this.interactionDOMElement.style['-ms-touch-action'] = 'none'; } @@ -230,12 +241,15 @@ * * @private */ -InteractionManager.prototype.removeEvents = function () { - if (!this.interactionDOMElement) { +InteractionManager.prototype.removeEvents = function () +{ + if (!this.interactionDOMElement) + { return; } - if (window.navigator.msPointerEnabled) { + if (window.navigator.msPointerEnabled) + { this.interactionDOMElement.style['-ms-content-zooming'] = ''; this.interactionDOMElement.style['-ms-touch-action'] = ''; } @@ -260,8 +274,10 @@ * * @private */ -InteractionManager.prototype.update = function () { - if (!this.interactionDOMElement) { +InteractionManager.prototype.update = function () +{ + if (!this.interactionDOMElement) + { return; } @@ -269,7 +285,8 @@ var now = Date.now(); var diff = now - this.last; diff = (diff * INTERACTION_FREQUENCY ) / 1000; - if (diff < 1) { + if (diff < 1) + { return; } @@ -280,7 +297,8 @@ // ok.. so mouse events?? // yes for now :) // OPTIMISE - how often to check?? - if (this.dirty) { + if (this.dirty) + { this.rebuildInteractiveGraph(); } @@ -289,7 +307,8 @@ var cursor = 'inherit'; var over = false; - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { var item = this.interactiveItems[i]; // OPTIMISATION - only calculate every time if the mousemove function exists.. @@ -302,26 +321,34 @@ this.mouse.target = item; // ok so deal with interactions.. // looks like there was a hit! - if (item.__hit && !over) { - if (item.buttonMode) { + if (item.__hit && !over) + { + if (item.buttonMode) + { cursor = item.defaultCursor; } - if (!item.interactiveChildren) { + if (!item.interactiveChildren) + { over = true; } - if (!item.__isOver) { - if (item.mouseover) { + if (!item.__isOver) + { + if (item.mouseover) + { item.mouseover (this.mouse); } item.__isOver = true; } } - else { - if (item.__isOver) { + else + { + if (item.__isOver) + { // roll out! - if (item.mouseout) { + if (item.mouseout) + { item.mouseout (this.mouse); } item.__isOver = false; @@ -329,7 +356,8 @@ } } - if (this.currentCursorStyle !== cursor) { + if (this.currentCursorStyle !== cursor) + { this.currentCursorStyle = cursor; this.interactionDOMElement.style.cursor = cursor; } @@ -338,18 +366,21 @@ /** * @private */ -InteractionManager.prototype.rebuildInteractiveGraph = function () { +InteractionManager.prototype.rebuildInteractiveGraph = function () +{ this.dirty = false; var len = this.interactiveItems.length; - for (var i = 0; i < len; i++) { + for (var i = 0; i < len; i++) + { this.interactiveItems[i].interactiveChildren = false; } this.interactiveItems.length = 0; - if (this.stage.interactive) { + if (this.stage.interactive) + { this.interactiveItems.push(this.stage); } @@ -363,8 +394,10 @@ * @param event {Event} The DOM event of the mouse moving * @private */ -InteractionManager.prototype.onMouseMove = function (event) { - if (this.dirty) { +InteractionManager.prototype.onMouseMove = function (event) +{ + if (this.dirty) + { this.rebuildInteractiveGraph(); } @@ -378,11 +411,13 @@ var length = this.interactiveItems.length; - for (var i = 0; i < length; i++) { + for (var i = 0; i < length; i++) + { var item = this.interactiveItems[i]; // Call the function! - if (item.mousemove) { + if (item.mousemove) + { item.mousemove(this.mouse); } } @@ -394,14 +429,17 @@ * @param event {Event} The DOM event of a mouse button being pressed down * @private */ -InteractionManager.prototype.onMouseDown = function (event) { - if (this.dirty) { +InteractionManager.prototype.onMouseDown = function (event) +{ + if (this.dirty) + { this.rebuildInteractiveGraph(); } this.mouse.originalEvent = event; - if (AUTO_PREVENT_DEFAULT) { + if (AUTO_PREVENT_DEFAULT) + { this.mouse.originalEvent.preventDefault(); } @@ -420,22 +458,27 @@ // while // hit test - for (var i = 0; i < length; i++) { + for (var i = 0; i < length; i++) + { var item = this.interactiveItems[i]; - if (item[downFunction] || item[clickFunction]) { + if (item[downFunction] || item[clickFunction]) + { item[buttonIsDown] = true; item.__hit = this.hitTest(item, this.mouse); - if (item.__hit) { + if (item.__hit) + { //call the function! - if (item[downFunction]) { + if (item[downFunction]) + { item[downFunction](this.mouse); } item[isDown] = true; // just the one! - if (!item.interactiveChildren) { + if (!item.interactiveChildren) + { break; } } @@ -449,8 +492,10 @@ * @param event {Event} The DOM event of a mouse being moved out * @private */ -InteractionManager.prototype.onMouseOut = function (event) { - if (this.dirty) { +InteractionManager.prototype.onMouseOut = function (event) +{ + if (this.dirty) + { this.rebuildInteractiveGraph(); } @@ -460,11 +505,14 @@ this.interactionDOMElement.style.cursor = 'inherit'; - for (var i = 0; i < length; i++) { + for (var i = 0; i < length; i++) + { var item = this.interactiveItems[i]; - if (item.__isOver) { + if (item.__isOver) + { this.mouse.target = item; - if (item.mouseout) { + if (item.mouseout) + { item.mouseout(this.mouse); } item.__isOver = false; @@ -484,8 +532,10 @@ * @param event {Event} The DOM event of a mouse button being released * @private */ -InteractionManager.prototype.onMouseUp = function (event) { - if (this.dirty) { +InteractionManager.prototype.onMouseUp = function (event) +{ + if (this.dirty) + { this.rebuildInteractiveGraph(); } @@ -502,30 +552,40 @@ var upOutsideFunction = isRightButton ? 'rightupoutside' : 'mouseupoutside'; var isDown = isRightButton ? '__isRightDown' : '__isDown'; - for (var i = 0; i < length; i++) { + for (var i = 0; i < length; i++) + { var item = this.interactiveItems[i]; - if (item[clickFunction] || item[upFunction] || item[upOutsideFunction]) { + if (item[clickFunction] || item[upFunction] || item[upOutsideFunction]) + { item.__hit = this.hitTest(item, this.mouse); - if (item.__hit && !up) { + if (item.__hit && !up) + { //call the function! - if (item[upFunction]) { + if (item[upFunction]) + { item[upFunction](this.mouse); } - if (item[isDown]) { - if (item[clickFunction]) { + if (item[isDown]) + { + if (item[clickFunction]) + { item[clickFunction](this.mouse); } } - if (!item.interactiveChildren) { + if (!item.interactiveChildren) + { up = true; } } - else { - if (item[isDown]) { - if (item[upOutsideFunction]) { + else + { + if (item[isDown]) + { + if (item[upOutsideFunction]) + { item[upOutsideFunction](this.mouse); } } @@ -543,10 +603,12 @@ * @param interactionData {InteractionData} The interactionData object to update in the case there is a hit * @private */ -InteractionManager.prototype.hitTest = function (item, interactionData) { +InteractionManager.prototype.hitTest = function (item, interactionData) +{ var global = interactionData.global; - if (!item.worldVisible) { + if (!item.worldVisible) + { return false; } @@ -560,37 +622,46 @@ interactionData.target = item; //a sprite or display object with a hit area defined - if (item.hitArea && item.hitArea.contains) { + if (item.hitArea && item.hitArea.contains) + { return item.hitArea.contains(x, y); } // a sprite with no hitarea defined - else if (item instanceof core.Sprite) { + else if (item instanceof core.Sprite) + { var width = item.texture.frame.width; var height = item.texture.frame.height; var x1 = -width * item.anchor.x; var y1; - if (x > x1 && x < x1 + width) { + if (x > x1 && x < x1 + width) + { y1 = -height * item.anchor.y; - if (y > y1 && y < y1 + height) { + if (y > y1 && y < y1 + height) + { // set the target property if a hit is true! return true; } } } - else if (item instanceof core.Graphics) { + else if (item instanceof core.Graphics) + { var graphicsData = item.graphicsData; - for (i = 0; i < graphicsData.length; i++) { + for (i = 0; i < graphicsData.length; i++) + { var data = graphicsData[i]; - if (!data.fill) { + if (!data.fill) + { continue; } // only deal with fills.. - if (data.shape) { - if (data.shape.contains(x, y)) { + if (data.shape) + { + if (data.shape.contains(x, y)) + { //interactionData.target = item; return true; } @@ -600,10 +671,12 @@ var length = item.children.length; - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { var tempItem = item.children[i]; var hit = this.hitTest(tempItem, interactionData); - if (hit) { + if (hit) + { // hmm.. TODO SET CORRECT TARGET? interactionData.target = item; return true; @@ -618,8 +691,10 @@ * @param event {Event} The DOM event of a touch moving across the renderer view * @private */ -InteractionManager.prototype.onTouchMove = function (event) { - if (this.dirty) { +InteractionManager.prototype.onTouchMove = function (event) +{ + if (this.dirty) + { this.rebuildInteractiveGraph(); } @@ -628,7 +703,8 @@ var touchData; var i = 0; - for (i = 0; i < changedTouches.length; i++) { + for (i = 0; i < changedTouches.length; i++) + { var touchEvent = changedTouches[i]; touchData = this.touches[touchEvent.identifier]; touchData.originalEvent = event; @@ -636,15 +712,18 @@ // update the touch position touchData.global.x = ( (touchEvent.clientX - rect.left) * (this.interactionDOMElement.width / rect.width) ) / this.resolution; touchData.global.y = ( (touchEvent.clientY - rect.top) * (this.interactionDOMElement.height / rect.height) ) / this.resolution; - if (navigator.isCocoonJS && !rect.left && !rect.top && !event.target.style.width && !event.target.style.height) { + if (navigator.isCocoonJS && !rect.left && !rect.top && !event.target.style.width && !event.target.style.height) + { //Support for CocoonJS fullscreen scale modes touchData.global.x = touchEvent.clientX; touchData.global.y = touchEvent.clientY; } - for (var j = 0; j < this.interactiveItems.length; j++) { + for (var j = 0; j < this.interactiveItems.length; j++) + { var item = this.interactiveItems[j]; - if (item.touchmove && item.__touchData && item.__touchData[touchEvent.identifier]) { + if (item.touchmove && item.__touchData && item.__touchData[touchEvent.identifier]) + { item.touchmove(touchData); } } @@ -657,23 +736,28 @@ * @param event {Event} The DOM event of a touch starting on the renderer view * @private */ -InteractionManager.prototype.onTouchStart = function (event) { - if (this.dirty) { +InteractionManager.prototype.onTouchStart = function (event) +{ + if (this.dirty) + { this.rebuildInteractiveGraph(); } var rect = this.interactionDOMElement.getBoundingClientRect(); - if (AUTO_PREVENT_DEFAULT) { + if (AUTO_PREVENT_DEFAULT) + { event.preventDefault(); } var changedTouches = event.changedTouches; - for (var i=0; i < changedTouches.length; i++) { + for (var i=0; i < changedTouches.length; i++) + { var touchEvent = changedTouches[i]; var touchData = this.pool.pop(); - if (!touchData) { + if (!touchData) + { touchData = new InteractionData(); } @@ -682,7 +766,8 @@ this.touches[touchEvent.identifier] = touchData; touchData.global.x = ( (touchEvent.clientX - rect.left) * (this.interactionDOMElement.width / rect.width) ) / this.resolution; touchData.global.y = ( (touchEvent.clientY - rect.top) * (this.interactionDOMElement.height / rect.height) ) / this.resolution; - if (navigator.isCocoonJS && !rect.left && !rect.top && !event.target.style.width && !event.target.style.height) { + if (navigator.isCocoonJS && !rect.left && !rect.top && !event.target.style.width && !event.target.style.height) + { //Support for CocoonJS fullscreen scale modes touchData.global.x = touchEvent.clientX; touchData.global.y = touchEvent.clientY; @@ -690,15 +775,19 @@ var length = this.interactiveItems.length; - for (var j = 0; j < length; j++) { + for (var j = 0; j < length; j++) + { var item = this.interactiveItems[j]; - if (item.touchstart || item.tap) { + if (item.touchstart || item.tap) + { item.__hit = this.hitTest(item, touchData); - if (item.__hit) { + if (item.__hit) + { //call the function! - if (item.touchstart) { + if (item.touchstart) + { item.touchstart(touchData); } @@ -706,7 +795,8 @@ item.__touchData = item.__touchData || {}; item.__touchData[touchEvent.identifier] = touchData; - if (!item.interactiveChildren) { + if (!item.interactiveChildren) + { break; } } @@ -721,31 +811,37 @@ * @param event {Event} The DOM event of a touch ending on the renderer view * @private */ -InteractionManager.prototype.onTouchEnd = function (event) { - if (this.dirty) { +InteractionManager.prototype.onTouchEnd = function (event) +{ + if (this.dirty) + { this.rebuildInteractiveGraph(); } var rect = this.interactionDOMElement.getBoundingClientRect(); var changedTouches = event.changedTouches; - for (var i=0; i < changedTouches.length; i++) { + for (var i=0; i < changedTouches.length; i++) + { var touchEvent = changedTouches[i]; var touchData = this.touches[touchEvent.identifier]; var up = false; touchData.global.x = ( (touchEvent.clientX - rect.left) * (this.interactionDOMElement.width / rect.width) ) / this.resolution; touchData.global.y = ( (touchEvent.clientY - rect.top) * (this.interactionDOMElement.height / rect.height) ) / this.resolution; - if (navigator.isCocoonJS && !rect.left && !rect.top && !event.target.style.width && !event.target.style.height) { + if (navigator.isCocoonJS && !rect.left && !rect.top && !event.target.style.width && !event.target.style.height) + { //Support for CocoonJS fullscreen scale modes touchData.global.x = touchEvent.clientX; touchData.global.y = touchEvent.clientY; } var length = this.interactiveItems.length; - for (var j = 0; j < length; j++) { + for (var j = 0; j < length; j++) + { var item = this.interactiveItems[j]; - if (item.__touchData && item.__touchData[touchEvent.identifier]) { + if (item.__touchData && item.__touchData[touchEvent.identifier]) + { item.__hit = this.hitTest(item, item.__touchData[touchEvent.identifier]); @@ -753,20 +849,27 @@ touchData.originalEvent = event; // hitTest?? - if (item.touchend || item.tap) { - if (item.__hit && !up) { - if (item.touchend) { + if (item.touchend || item.tap) + { + if (item.__hit && !up) + { + if (item.touchend) + { item.touchend(touchData); } - if (item.__isDown && item.tap) { + if (item.__isDown && item.tap) + { item.tap(touchData); } - if (!item.interactiveChildren) { + if (!item.interactiveChildren) + { up = true; } } - else { - if (item.__isDown && item.touchendoutside) { + else + { + if (item.__isDown && item.touchendoutside) + { item.touchendoutside(touchData); } } diff --git a/src/loaders/AssetLoader.js b/src/loaders/AssetLoader.js index 20da0cf..c4dba1c 100644 --- a/src/loaders/AssetLoader.js +++ b/src/loaders/AssetLoader.js @@ -21,7 +21,8 @@ * data formats include 'xml' and 'fnt'. * @param crossorigin {boolean} Whether requests should be treated as crossorigin */ -function AssetLoader(assetURLs, crossorigin) { +function AssetLoader(assetURLs, crossorigin) +{ /** * The array of asset URLs that are going to be loaded * @@ -76,16 +77,19 @@ * * @param str {string} the name of the asset */ -AssetLoader.prototype._getDataType = function (str) { +AssetLoader.prototype._getDataType = function (str) +{ var test = 'data:'; var start = str.slice(0, test.length).toLowerCase(); - if (start === test) { + if (start === test) + { var data = str.slice(test.length); var sepIdx = data.indexOf(','); // check for malformed data URI scheme - if (sepIdx === -1) { + if (sepIdx === -1) + { return null; } @@ -94,7 +98,8 @@ //We might need to handle some special cases here... //standardize text/plain to 'txt' file extension - if (!info || info.toLowerCase() === 'text/plain') { + if (!info || info.toLowerCase() === 'text/plain') + { return 'txt'; } @@ -109,27 +114,32 @@ * Starts loading the assets sequentially * */ -AssetLoader.prototype.load = function () { +AssetLoader.prototype.load = function () +{ var scope = this; - function onLoad(evt) { + function onLoad(evt) + { scope.onAssetLoaded(evt.data.content); } this.loadCount = this.assetURLs.length; - for (var i=0; i < this.assetURLs.length; i++) { + for (var i=0; i < this.assetURLs.length; i++) + { var fileName = this.assetURLs[i]; //first see if we have a data URI scheme.. var fileType = this._getDataType(fileName); //if not, assume it's a file URI - if (!fileType) { + if (!fileType) + { fileType = fileName.split('?').shift().split('.').pop().toLowerCase(); } var Constructor = this.loadersByType[fileType]; - if (!Constructor) { + if (!Constructor) + { throw new Error(fileType + ' is an unsupported file type'); } @@ -145,18 +155,22 @@ * * @private */ -AssetLoader.prototype.onAssetLoaded = function (loader) { +AssetLoader.prototype.onAssetLoaded = function (loader) +{ this.loadCount--; this.emit('onProgress', { content: this, loader: loader }); - if (this.onProgress) { + if (this.onProgress) + { this.onProgress(loader); } - if (!this.loadCount) { + if (!this.loadCount) + { this.emit('onComplete', { content: this }); - if (this.onComplete) { + if (this.onComplete) + { this.onComplete(); } } diff --git a/src/loaders/AtlasLoader.js b/src/loaders/AtlasLoader.js index 5eda286..3aec9e2 100644 --- a/src/loaders/AtlasLoader.js +++ b/src/loaders/AtlasLoader.js @@ -15,7 +15,8 @@ * @param url {String} The url of the JSON file * @param crossorigin {boolean} Whether requests should be treated as crossorigin */ -function AtlasLoader(url, crossorigin) { +function AtlasLoader(url, crossorigin) +{ this.url = url; this.baseUrl = url.replace(/[^\/]*$/, ''); this.crossorigin = crossorigin; @@ -31,13 +32,15 @@ * Starts loading the JSON file * */ -AtlasLoader.prototype.load = function () { +AtlasLoader.prototype.load = function () +{ this.ajaxRequest = new core.utils.AjaxRequest(); this.ajaxRequest.onreadystatechange = this.onAtlasLoaded.bind(this); this.ajaxRequest.open('GET', this.url, true); - if (this.ajaxRequest.overrideMimeType) { + if (this.ajaxRequest.overrideMimeType) + { this.ajaxRequest.overrideMimeType('application/json'); } @@ -49,9 +52,12 @@ * * @private */ -AtlasLoader.prototype.onAtlasLoaded = function () { - if (this.ajaxRequest.readyState === 4) { - if (this.ajaxRequest.status === 200 || window.location.href.indexOf('http') === -1) { +AtlasLoader.prototype.onAtlasLoaded = function () +{ + if (this.ajaxRequest.readyState === 4) + { + if (this.ajaxRequest.status === 200 || window.location.href.indexOf('http') === -1) + { this.atlas = { meta : { image : [] @@ -70,34 +76,44 @@ selfOnLoaded = this.onLoaded.bind(this); // parser without rotation support yet! - for (i = 0; i < result.length; i++) { + for (i = 0; i < result.length; i++) + { result[i] = result[i].replace(/^\s+|\s+$/g, ''); - if (result[i] === '') { + if (result[i] === '') + { nameInNextLine = i+1; } - if (result[i].length > 0) { - if (nameInNextLine === i) { + if (result[i].length > 0) + { + if (nameInNextLine === i) + { this.atlas.meta.image.push(result[i]); currentImageId = this.atlas.meta.image.length - 1; this.atlas.frames.push({}); lineCount = -3; - } else if (lineCount > 0) { - if (lineCount % 7 === 1) { // frame name - if (currentFrame != null) { //jshint ignore:line + } else if (lineCount > 0) + { + if (lineCount % 7 === 1) + { // frame name + if (currentFrame != null) + { //jshint ignore:line this.atlas.frames[currentImageId][currentFrame.name] = currentFrame; } currentFrame = { name: result[i], frame : {} }; } else { var text = result[i].split(' '); - if (lineCount % 7 === 3) { // position + if (lineCount % 7 === 3) + { // position currentFrame.frame.x = Number(text[1].replace(',', '')); currentFrame.frame.y = Number(text[2]); - } else if (lineCount % 7 === 4) { // size + } else if (lineCount % 7 === 4) + { // size currentFrame.frame.w = Number(text[1].replace(',', '')); currentFrame.frame.h = Number(text[2]); - } else if (lineCount % 7 === 5) { // real size + } else if (lineCount % 7 === 5) + { // real size var realSize = { x : 0, y : 0, @@ -105,7 +121,8 @@ h : Number(text[2]) }; - if (realSize.w > currentFrame.frame.w || realSize.h > currentFrame.frame.h) { + if (realSize.w > currentFrame.frame.w || realSize.h > currentFrame.frame.h) + { currentFrame.trimmed = true; currentFrame.realSize = realSize; } else { @@ -118,28 +135,34 @@ } } - if (currentFrame != null) { //jshint ignore:line + if (currentFrame != null) + { //jshint ignore:line this.atlas.frames[currentImageId][currentFrame.name] = currentFrame; } - if (this.atlas.meta.image.length > 0) { + if (this.atlas.meta.image.length > 0) + { this.images = []; - for (j = 0; j < this.atlas.meta.image.length; j++) { + for (j = 0; j < this.atlas.meta.image.length; j++) + { // sprite sheet var textureUrl = this.baseUrl + this.atlas.meta.image[j]; var frameData = this.atlas.frames[j]; this.images.push(new ImageLoader(textureUrl, this.crossorigin)); - for (i in frameData) { + for (i in frameData) + { var rect = frameData[i].frame; - if (rect) { + if (rect) + { core.utils.TextureCache[i] = new core.Texture(this.images[j].texture.baseTexture, { x: rect.x, y: rect.y, width: rect.w, height: rect.h }); - if (frameData[i].trimmed) { + if (frameData[i].trimmed) + { core.utils.TextureCache[i].realSize = frameData[i].realSize; // trim in pixi not supported yet, todo update trim properties if it is done ... core.utils.TextureCache[i].trim.x = 0; @@ -150,7 +173,8 @@ } this.currentImageId = 0; - for (j = 0; j < this.images.length; j++) { + for (j = 0; j < this.images.length; j++) + { this.images[j].on('loaded', selfOnLoaded); } this.images[this.currentImageId].load(); @@ -170,8 +194,10 @@ * * @private */ -AtlasLoader.prototype.onLoaded = function () { - if (this.images.length - 1 > this.currentImageId) { +AtlasLoader.prototype.onLoaded = function () +{ + if (this.images.length - 1 > this.currentImageId) + { this.currentImageId++; this.images[this.currentImageId].load(); } else { @@ -185,6 +211,7 @@ * * @private */ -AtlasLoader.prototype.onError = function () { +AtlasLoader.prototype.onError = function () +{ this.emit('error', { content: this }); }; diff --git a/src/loaders/BitmapFontLoader.js b/src/loaders/BitmapFontLoader.js index 8641760..13e5c1b 100644 --- a/src/loaders/BitmapFontLoader.js +++ b/src/loaders/BitmapFontLoader.js @@ -13,7 +13,8 @@ * @param url {String} The url of the sprite sheet JSON file * @param crossorigin {boolean} Whether requests should be treated as crossorigin */ -function BitmapFontLoader(url, crossorigin) { +function BitmapFontLoader(url, crossorigin) +{ /** * The url of the bitmap font data * @@ -54,13 +55,15 @@ * Loads the XML font data * */ -BitmapFontLoader.prototype.load = function () { +BitmapFontLoader.prototype.load = function () +{ this.ajaxRequest = new core.utils.AjaxRequest(); this.ajaxRequest.onreadystatechange = this.onXMLLoaded.bind(this); this.ajaxRequest.open('GET', this.url, true); - if (this.ajaxRequest.overrideMimeType) { + if (this.ajaxRequest.overrideMimeType) + { this.ajaxRequest.overrideMimeType('application/xml'); } @@ -72,12 +75,17 @@ * * @private */ -BitmapFontLoader.prototype.onXMLLoaded = function () { - if (this.ajaxRequest.readyState === 4) { - if (this.ajaxRequest.status === 200 || window.location.protocol.indexOf('http') === -1) { +BitmapFontLoader.prototype.onXMLLoaded = function () +{ + if (this.ajaxRequest.readyState === 4) + { + if (this.ajaxRequest.status === 200 || window.location.protocol.indexOf('http') === -1) + { var responseXML = this.ajaxRequest.responseXML; - if (!responseXML || /MSIE 9/i.test(navigator.userAgent) || navigator.isCocoonJS) { - if (typeof(window.DOMParser) === 'function') { + if (!responseXML || /MSIE 9/i.test(navigator.userAgent) || navigator.isCocoonJS) + { + if (typeof(window.DOMParser) === 'function') + { var domparser = new DOMParser(); responseXML = domparser.parseFromString(this.ajaxRequest.responseText, 'text/xml'); } else { @@ -102,7 +110,8 @@ //parse letters var letters = responseXML.getElementsByTagName('char'); - for (var i = 0; i < letters.length; i++) { + for (var i = 0; i < letters.length; i++) + { var charCode = parseInt(letters[i].getAttribute('id'), 10); var textureRect = new core.math.Rectangle( @@ -124,7 +133,8 @@ //parse kernings var kernings = responseXML.getElementsByTagName('kerning'); - for (i = 0; i < kernings.length; i++) { + for (i = 0; i < kernings.length; i++) + { var first = parseInt(kernings[i].getAttribute('first'), 10); var second = parseInt(kernings[i].getAttribute('second'), 10); var amount = parseInt(kernings[i].getAttribute('amount'), 10); @@ -146,6 +156,7 @@ * * @private */ -BitmapFontLoader.prototype.onLoaded = function () { +BitmapFontLoader.prototype.onLoaded = function () +{ this.emit('loaded', { content: this }); }; diff --git a/src/loaders/ImageLoader.js b/src/loaders/ImageLoader.js index e3ff493..16ee7c8 100644 --- a/src/loaders/ImageLoader.js +++ b/src/loaders/ImageLoader.js @@ -11,7 +11,8 @@ * @param url {String} The url of the image * @param crossorigin {boolean} Whether requests should be treated as crossorigin */ -function ImageLoader(url, crossorigin) { +function ImageLoader(url, crossorigin) +{ /** * The texture being loaded * @@ -39,12 +40,15 @@ * Loads image or takes it from cache * */ -ImageLoader.prototype.load = function () { - if (!this.texture.baseTexture.hasLoaded) { +ImageLoader.prototype.load = function () +{ + if (!this.texture.baseTexture.hasLoaded) + { this.texture.baseTexture.on('loaded', this.onLoaded.bind(this)); this.texture.baseTexture.on('error', this.onError.bind(this)); } - else { + else + { this.onLoaded(); } }; @@ -54,7 +58,8 @@ * * @private */ -ImageLoader.prototype.onLoaded = function () { +ImageLoader.prototype.onLoaded = function () +{ this.emit('loaded', { content: this }); }; @@ -64,7 +69,8 @@ * @method onError * @private */ -ImageLoader.prototype.onError = function () { +ImageLoader.prototype.onError = function () +{ this.emit('error', { content: this }); }; @@ -75,15 +81,18 @@ * @param frameHeight {number} height of each frame * @param textureName {String} if given, the frames will be cached in - format */ -ImageLoader.prototype.loadFramedSpriteSheet = function (frameWidth, frameHeight, textureName) { +ImageLoader.prototype.loadFramedSpriteSheet = function (frameWidth, frameHeight, textureName) +{ this.frames = []; var cols = Math.floor(this.texture.width / frameWidth); var rows = Math.floor(this.texture.height / frameHeight); var i=0; - for (var y = 0; y < rows; ++y) { - for (var x = 0; x < cols; ++x, ++i) { + for (var y = 0; y < rows; ++y) + { + for (var x = 0; x < cols; ++x, ++i) + { var texture = new core.Texture( this.texture.baseTexture, new core.math.Rectangle( @@ -96,7 +105,8 @@ this.frames.push(texture); - if (textureName) { + if (textureName) + { core.utils.TextureCache[textureName + '-' + i] = texture; } } diff --git a/src/loaders/JsonLoader.js b/src/loaders/JsonLoader.js index 3279f40..7aabeb4 100644 --- a/src/loaders/JsonLoader.js +++ b/src/loaders/JsonLoader.js @@ -14,7 +14,8 @@ * @param url {String} The url of the JSON file * @param crossorigin {boolean} Whether requests should be treated as crossorigin */ -function JsonLoader(url, crossorigin) { +function JsonLoader(url, crossorigin) +{ /** * The url of the bitmap font data * @@ -56,8 +57,10 @@ * Loads the JSON data * */ -JsonLoader.prototype.load = function () { - if (window.XDomainRequest && this.crossorigin) { +JsonLoader.prototype.load = function () +{ + if (window.XDomainRequest && this.crossorigin) + { this.ajaxRequest = new window.XDomainRequest(); // XDomainRequest has a few quirks. Occasionally it will abort requests @@ -68,15 +71,19 @@ this.ajaxRequest.onerror = this.onError.bind(this); this.ajaxRequest.ontimeout = this.onError.bind(this); - this.ajaxRequest.onprogress = function () {}; + this.ajaxRequest.onprogress = function () + {}; this.ajaxRequest.onload = this.onJSONLoaded.bind(this); } - else { - if (window.XMLHttpRequest) { + else + { + if (window.XMLHttpRequest) + { this.ajaxRequest = new window.XMLHttpRequest(); } - else { + else + { this.ajaxRequest = new window.ActiveXObject('Microsoft.XMLHTTP'); } @@ -93,8 +100,10 @@ * * @private */ -JsonLoader.prototype.onReadyStateChanged = function () { - if (this.ajaxRequest.readyState === 4 && (this.ajaxRequest.status === 200 || window.location.href.indexOf('http') === -1)) { +JsonLoader.prototype.onReadyStateChanged = function () +{ + if (this.ajaxRequest.readyState === 4 && (this.ajaxRequest.status === 200 || window.location.href.indexOf('http') === -1)) + { this.onJSONLoaded(); } }; @@ -104,15 +113,18 @@ * * @private */ -JsonLoader.prototype.onJSONLoaded = function () { - if (!this.ajaxRequest.responseText) { +JsonLoader.prototype.onJSONLoaded = function () +{ + if (!this.ajaxRequest.responseText) + { this.onError(); return; } this.json = JSON.parse(this.ajaxRequest.responseText); - if (this.json.frames) { + if (this.json.frames) + { // sprite sheet var textureUrl = this.baseUrl + this.json.meta.image; var image = new ImageLoader(textureUrl, this.crossorigin); @@ -122,16 +134,19 @@ image.addEventListener('loaded', this.onLoaded.bind(this)); image.addEventListener('error', this.onError.bind(this)); - for (var i in frameData) { + for (var i in frameData) + { var rect = frameData[i].frame; - if (rect) { + if (rect) + { var textureSize = new core.math.Rectangle(rect.x, rect.y, rect.w, rect.h); var crop = textureSize.clone(); var trim = null; // Check to see if the sprite is trimmed - if (frameData[i].trimmed) { + if (frameData[i].trimmed) + { var actualSize = frameData[i].sourceSize; var realSize = frameData[i].spriteSourceSize; trim = new core.math.Rectangle(realSize.x, realSize.y, actualSize.w, actualSize.h); @@ -143,12 +158,15 @@ image.load(); } - else if (this.json.bones) { + else if (this.json.bones) + { // check if the json was loaded before - if (core.utils.AnimCache[this.url]) { + if (core.utils.AnimCache[this.url]) + { this.onLoaded(); } - else { + else + { /** * use a bit of hackery to load the atlas file, here we assume that the .json, .atlas and .png files * that correspond to the spine file are in the same base URL and that the .json and .atlas files @@ -159,9 +177,11 @@ // save a copy of the current object for future reference // var originalLoader = this; // before loading the file, replace the "onJSONLoaded" function for our own // - atlasLoader.onJSONLoaded = function () { + atlasLoader.onJSONLoaded = function () + { // at this point "this" points at the atlasLoader (JsonLoader) instance // - if (!this.ajaxRequest.responseText) { + if (!this.ajaxRequest.responseText) + { this.onError(); // FIXME: hmm, this is funny because we are not responding to errors yet return; } @@ -179,14 +199,18 @@ originalLoader.spineAtlas = spineAtlas; originalLoader.spineAtlasLoader = atlasLoader; // wait for textures to finish loading if needed - if (textureLoader.loadingCount > 0) { - textureLoader.addEventListener('loadedBaseTexture', function (evt){ - if (evt.content.content.loadingCount <= 0) { + if (textureLoader.loadingCount > 0) + { + textureLoader.addEventListener('loadedBaseTexture', function (evt) + { + if (evt.content.content.loadingCount <= 0) + { originalLoader.onLoaded(); } }); } - else { + else + { originalLoader.onLoaded(); } }; @@ -194,7 +218,8 @@ atlasLoader.load(); } } - else { + else + { this.onLoaded(); } }; @@ -204,7 +229,8 @@ * * @private */ -JsonLoader.prototype.onLoaded = function () { +JsonLoader.prototype.onLoaded = function () +{ this.loaded = true; this.dispatchEvent({ type: 'loaded', @@ -217,7 +243,8 @@ * * @private */ -JsonLoader.prototype.onError = function () { +JsonLoader.prototype.onError = function () +{ this.dispatchEvent({ type: 'error', diff --git a/src/loaders/SpineLoader.js b/src/loaders/SpineLoader.js index 51aaddb..69bae21 100644 --- a/src/loaders/SpineLoader.js +++ b/src/loaders/SpineLoader.js @@ -24,7 +24,8 @@ * @param url {String} The url of the JSON file * @param crossorigin {boolean} Whether requests should be treated as crossorigin */ -function SpineLoader(url, crossorigin) { +function SpineLoader(url, crossorigin) +{ /** * The url of the bitmap font data * @@ -57,11 +58,13 @@ * Loads the JSON data * */ -SpineLoader.prototype.load = function () { +SpineLoader.prototype.load = function () +{ var scope = this; var jsonLoader = new JsonLoader(this.url, this.crossorigin); - jsonLoader.on('loaded', function (event) { + jsonLoader.on('loaded', function (event) + { scope.json = event.data.content.json; scope.onLoaded(); }); @@ -74,7 +77,8 @@ * * @private */ -SpineLoader.prototype.onLoaded = function () { +SpineLoader.prototype.onLoaded = function () +{ this.loaded = true; this.emit('loaded', { content: this }); }; diff --git a/src/core/display/DisplayObject.js b/src/core/display/DisplayObject.js index 66ebc3c..20e778c 100644 --- a/src/core/display/DisplayObject.js +++ b/src/core/display/DisplayObject.js @@ -7,7 +7,8 @@ * @class * @namespace PIXI */ -function DisplayObject() { +function DisplayObject() +{ /** * The coordinate of the object relative to the local coordinates of the parent. * @@ -152,10 +153,12 @@ * @memberof DisplayObject# */ x: { - get: function () { + get: function () + { return this.position.x; }, - set: function (value) { + set: function (value) + { this.position.x = value; } }, @@ -167,10 +170,12 @@ * @memberof DisplayObject# */ y: { - get: function () { + get: function () + { return this.position.y; }, - set: function (value) { + set: function (value) + { this.position.y = value; } }, @@ -183,11 +188,13 @@ * @readonly */ worldVisible: { - get: function () { + get: function () + { var item = this; do { - if (!item.visible) { + if (!item.visible) + { return false; } @@ -207,17 +214,21 @@ * @memberof DisplayObject# */ mask: { - get: function () { + get: function () + { return this._mask; }, - set: function (value) { - if (this._mask) { + set: function (value) + { + if (this._mask) + { this._mask.isMask = false; } this._mask = value; - if (this._mask) { + if (this._mask) + { this._mask.isMask = true; } } @@ -232,18 +243,23 @@ * @memberof DisplayObject# */ filters: { - get: function () { + get: function () + { return this._filters; }, - set: function (value) { - if (value) { + set: function (value) + { + if (value) + { // now put all the passes in one place.. var passes = []; - for (var i = 0; i < value.length; i++) { + for (var i = 0; i < value.length; i++) + { var filterPasses = value[i].passes; - for (var j = 0; j < filterPasses.length; j++) { + for (var j = 0; j < filterPasses.length; j++) + { passes.push(filterPasses[j]); } } @@ -264,8 +280,9 @@ * * @private */ -DisplayObject.prototype.updateTransform = function () { - +DisplayObject.prototype.updateTransform = function () +{ + // create some matrix refs for easy access var pt = this.parent.worldTransform; var wt = this.worldTransform; @@ -274,9 +291,11 @@ var a, b, c, d, tx, ty; // so if rotation is between 0 then we can simplify the multiplication process.. - if (this.rotation % math.PI_2) { + if (this.rotation % math.PI_2) + { // 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) { + if (this.rotation !== this.rotationCache) + { this.rotationCache = this.rotation; this._sr = Math.sin(this.rotation); this._cr = Math.cos(this.rotation); @@ -291,7 +310,8 @@ ty = this.position.y; // check for pivot.. not often used so geared towards that fact! - if (this.pivot.x || this.pivot.y) { + 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; } @@ -304,7 +324,8 @@ wt.tx = tx * pt.a + ty * pt.c + pt.tx; wt.ty = tx * pt.b + ty * pt.d + pt.ty; } - else { + else + { // lets do the fast version as we know there is no rotation.. a = this.scale.x; d = this.scale.y; @@ -333,7 +354,8 @@ * @param matrix {Matrix} * @return {Rectangle} the rectangular bounding area */ -DisplayObject.prototype.getBounds = function (/* matrix */) { +DisplayObject.prototype.getBounds = function (/* matrix */) +{ return math.Rectangle.EMPTY; }; @@ -342,7 +364,8 @@ * * @return {Rectangle} the rectangular bounding area */ -DisplayObject.prototype.getLocalBounds = function () { +DisplayObject.prototype.getLocalBounds = function () +{ return this.getBounds(math.Matrix.IDENTITY); }; @@ -352,7 +375,8 @@ * @param position {Point} The world origin to calculate from * @return {Point} A point object representing the position of this object */ -DisplayObject.prototype.toGlobal = function (position) { +DisplayObject.prototype.toGlobal = function (position) +{ // don't need to u[date the lot this.displayObjectUpdateTransform(); return this.worldTransform.apply(position); @@ -365,8 +389,10 @@ * @param [from] {DisplayObject} The DisplayObject to calculate the global position from * @return {Point} A point object representing the position of this object */ -DisplayObject.prototype.toLocal = function (position, from) { - if (from) { +DisplayObject.prototype.toLocal = function (position, from) +{ + if (from) + { position = from.toGlobal(position); } @@ -381,7 +407,8 @@ * @param renderer {WebGLRenderer} The renderer * @private */ -DisplayObject.prototype.renderWebGL = function (/* renderer */) { +DisplayObject.prototype.renderWebGL = function (/* renderer */) +{ // OVERWRITE; }; @@ -391,6 +418,7 @@ * @param renderer {CanvasRenderer} The renderer * @private */ -DisplayObject.prototype.renderCanvas = function (/* renderer */) { +DisplayObject.prototype.renderCanvas = function (/* renderer */) +{ // OVERWRITE; }; diff --git a/src/core/display/DisplayObjectContainer.js b/src/core/display/DisplayObjectContainer.js index 689f40b..4625ee8 100644 --- a/src/core/display/DisplayObjectContainer.js +++ b/src/core/display/DisplayObjectContainer.js @@ -12,7 +12,8 @@ * @extends DisplayObject * @namespace PIXI */ -function DisplayObjectContainer() { +function DisplayObjectContainer() +{ DisplayObject.call(this); /** @@ -47,17 +48,21 @@ * @memberof DisplayObjectContainer# */ width: { - get: function () { + get: function () + { return this.scale.x * this.getLocalBounds().width; }, - set: function (value) { + set: function (value) + { var width = this.getLocalBounds().width; - if(width !== 0) { + if(width !== 0) + { this.scale.x = value / width; } - else { + else + { this.scale.x = 1; } @@ -73,17 +78,21 @@ * @memberof DisplayObjectContainer# */ height: { - get: function () { + get: function () + { return this.scale.y * this.getLocalBounds().height; }, - set: function (value) { + set: function (value) + { var height = this.getLocalBounds().height; - if (height !== 0) { + if (height !== 0) + { this.scale.y = value / height ; } - else { + else + { this.scale.y = 1; } @@ -100,18 +109,23 @@ * @memberof DisplayObject# */ cacheAsBitmap: { - get: function () { + get: function () + { return this._cacheAsBitmap; }, - set: function (value) { - if (this._cacheAsBitmap === value) { + set: function (value) + { + if (this._cacheAsBitmap === value) + { return; } - if (value) { + if (value) + { this._generateCachedSprite(); } - else { + else + { this._destroyCachedSprite(); } @@ -126,7 +140,8 @@ * @param child {DisplayObject} The DisplayObject to add to the container * @return {DisplayObject} The child that was added. */ -DisplayObjectContainer.prototype.addChild = function (child) { +DisplayObjectContainer.prototype.addChild = function (child) +{ return this.addChildAt(child, this.children.length); }; @@ -137,14 +152,18 @@ * @param index {Number} The index to place the child in * @return {DisplayObject} The child that was added. */ -DisplayObjectContainer.prototype.addChildAt = function (child, index) { +DisplayObjectContainer.prototype.addChildAt = function (child, index) +{ // prevent adding self as child - if (child === this) { + if (child === this) + { return; } - if (index >= 0 && index <= this.children.length) { - if (child.parent) { + if (index >= 0 && index <= this.children.length) + { + if (child.parent) + { child.parent.removeChild(child); } @@ -154,7 +173,8 @@ return child; } - else { + else + { throw new Error(child + 'addChildAt: The index '+ index +' supplied is out of bounds ' + this.children.length); } }; @@ -165,15 +185,18 @@ * @param child {DisplayObject} * @param child2 {DisplayObject} */ -DisplayObjectContainer.prototype.swapChildren = function (child, child2) { - if (child === child2) { +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) { + if (index1 < 0 || index2 < 0) + { throw new Error('swapChildren: Both the supplied DisplayObjects must be a child of the caller.'); } @@ -187,10 +210,12 @@ * @param child {DisplayObject} The DisplayObject instance to identify * @return {Number} The index position of the child display object to identify */ -DisplayObjectContainer.prototype.getChildIndex = function (child) { +DisplayObjectContainer.prototype.getChildIndex = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { throw new Error('The supplied DisplayObject must be a child of the caller'); } @@ -203,8 +228,10 @@ * @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 */ -DisplayObjectContainer.prototype.setChildIndex = function (child, index) { - if (index < 0 || index >= this.children.length) { +DisplayObjectContainer.prototype.setChildIndex = function (child, index) +{ + if (index < 0 || index >= this.children.length) + { throw new Error('The supplied index is out of bounds'); } @@ -220,8 +247,10 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child at the given index, if any. */ -DisplayObjectContainer.prototype.getChildAt = function (index) { - if (index < 0 || index >= this.children.length) { +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'); } @@ -234,10 +263,12 @@ * @param child {DisplayObject} The DisplayObject to remove * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChild = function (child) { +DisplayObjectContainer.prototype.removeChild = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { return; } @@ -250,7 +281,8 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChildAt = function (index) { +DisplayObjectContainer.prototype.removeChildAt = function (index) +{ var child = this.getChildAt(index); child.parent = null; @@ -265,24 +297,29 @@ * @param beginIndex {Number} The beginning position. Default value is 0. * @param endIndex {Number} The ending position. Default value is size of the container. */ -DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) { +DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) +{ var begin = beginIndex || 0; var end = typeof endIndex === 'number' ? endIndex : this.children.length; var range = end - begin; - if (range > 0 && range <= end) { + if (range > 0 && range <= end) + { var removed = this.children.splice(begin, range); - for (var i = 0; i < removed.length; ++i) { + for (var i = 0; i < removed.length; ++i) + { removed[i].parent = null; } return removed; } - else if (range === 0 && this.children.length === 0) { + else if (range === 0 && this.children.length === 0) + { return []; } - else { + else + { throw new RangeError('removeChildren: numeric values are outside the acceptable range.'); } }; @@ -291,7 +328,8 @@ * Generates and updates the cached sprite for this object. * */ -DisplayObjectContainer.prototype.updateCachedSprite = function () { +DisplayObjectContainer.prototype.updateCachedSprite = function () +{ this._generateCachedSprite(); }; @@ -304,7 +342,8 @@ * @param renderer {CanvasRenderer|WebGLRenderer} The renderer used to generate the texture. * @return {Texture} a texture of the graphics object */ -DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) { +DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) +{ var bounds = this.getLocalBounds(); var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0, renderer, scaleMode, resolution); @@ -322,18 +361,22 @@ * * @private */ -DisplayObjectContainer.prototype.updateTransform = function () { - if (!this.visible) { +DisplayObjectContainer.prototype.updateTransform = function () +{ + if (!this.visible) + { return; } this.displayObjectUpdateTransform(); - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { return; } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } }; @@ -346,8 +389,10 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getBounds = function () { - if (this.children.length === 0) { +DisplayObjectContainer.prototype.getBounds = function () +{ + if (this.children.length === 0) + { return math.Rectangle.EMPTY; } @@ -365,10 +410,12 @@ var childVisible = false; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -386,7 +433,8 @@ maxY = maxY > childMaxY ? maxY : childMaxY; } - if (!childVisible) { + if (!childVisible) + { return math.Rectangle.EMPTY; } @@ -407,12 +455,14 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getLocalBounds = function () { +DisplayObjectContainer.prototype.getLocalBounds = function () +{ var matrixCache = this.worldTransform; this.worldTransform = math.Matrix.IDENTITY; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } @@ -428,13 +478,16 @@ * * @param renderer {WebGLRenderer} The renderer */ -DisplayObjectContainer.prototype.renderWebGL = function (renderer) { +DisplayObjectContainer.prototype.renderWebGL = function (renderer) +{ // if the object is not visible or the alpha is 0 then no need to render this element - if (!this.visible || this.alpha <= 0) { + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } @@ -442,14 +495,17 @@ var i, j; // do a quick check to see if this element has a mask or a filter. - if (this._mask || this._filters) { + if (this._mask || this._filters) + { // push filter first as we need to ensure the stencil buffer is correct for any masking - if (this._filters) { + if (this._filters) + { renderer.spriteBatch.flush(); renderer.filterManager.pushFilter(this._filterBlock); } - if (this._mask) { + if (this._mask) + { renderer.spriteBatch.stop(); renderer.maskManager.pushMask(this.mask, renderer); renderer.spriteBatch.start(); @@ -459,36 +515,42 @@ this._renderWebGL(renderer); // now loop through the children and make sure they get rendered - for (i = 0, j = this.children.length; i < j; i++) { + for (i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderWebGL(renderer); } // time to stop the sprite batch as either a mask element or a filter draw will happen next renderer.spriteBatch.stop(); - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(this._mask, renderer); } - if (this._filters) { + if (this._filters) + { renderer.filterManager.popFilter(); } renderer.spriteBatch.start(); } - else { + else + { this._renderWebGL(renderer); // simple render children! - for (i = 0, j = this.children.length; i < j; ++i) { + for (i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderWebGL(renderer); } } }; -DisplayObjectContainer.prototype._renderWebGL = function (renderer) { +DisplayObjectContainer.prototype._renderWebGL = function (renderer) +{ // this is where content itself gets renderd.. @@ -499,25 +561,31 @@ * * @param renderer {CanvasRenderer} The renderer */ -DisplayObjectContainer.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0) { +DisplayObjectContainer.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -528,13 +596,16 @@ * @param renderer {WebGLRenderer|CanvasRenderer} The renderer * @private */ -DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) { +DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) +{ this._cachedSprite.worldAlpha = this.worldAlpha; - if (renderer.gl) { + if (renderer.gl) + { this._cachedSprite.renderWebGL(renderer); } - else { + else + { this._cachedSprite.renderCanvas(renderer); } }; @@ -544,10 +615,12 @@ * * @private */ -DisplayObjectContainer.prototype._generateCachedSprite = function () { +DisplayObjectContainer.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { // TODO - RenderTexture now *requires* a renderer instance, so this is like broken // because `renderer` isn't actually in scope here :P var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0); @@ -555,7 +628,8 @@ this._cachedSprite = new Sprite(renderTexture); this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.texture.resize(bounds.width | 0, bounds.height | 0); } @@ -580,8 +654,10 @@ * * @private */ -DisplayObjectContainer.prototype._destroyCachedSprite = function () { - if (!this._cachedSprite) { +DisplayObjectContainer.prototype._destroyCachedSprite = function () +{ + if (!this._cachedSprite) + { return; } diff --git a/src/core/display/Sprite.js b/src/core/display/Sprite.js index 707da24..5862aef 100644 --- a/src/core/display/Sprite.js +++ b/src/core/display/Sprite.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param texture {Texture} The texture for this sprite */ -function Sprite(texture) { +function Sprite(texture) +{ DisplayObjectContainer.call(this); /** @@ -85,12 +86,14 @@ this.texture = texture || Texture.EMPTY; } -Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) { +Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) +{ DisplayObjectContainer.prototype.destroy.call(this); this.anchor = null; - if (destroyTexture) { + if (destroyTexture) + { this._texture.destroy(destroyBaseTexture); } @@ -111,10 +114,12 @@ * @memberof Sprite# */ width: { - get: function () { + get: function () + { return this.scale.x * this.texture.frame.width; }, - set: function (value) { + set: function (value) + { this.scale.x = value / this.texture.frame.width; this._width = value; } @@ -127,10 +132,12 @@ * @memberof Sprite# */ height: { - get: function () { + get: function () + { return this.scale.y * this.texture.frame.height; }, - set: function (value) { + set: function (value) + { this.scale.y = value / this.texture.frame.height; this._height = value; } @@ -143,23 +150,29 @@ * @memberof Sprite# */ texture: { - get: function () { + get: function () + { return this._texture; }, - set: function (value) { - if (this._texture === value) { + set: function (value) + { + if (this._texture === value) + { return; } this._texture = value; this.cachedTint = 0xFFFFFF; - if (value) { + if (value) + { // wait for the texture to load - if (value.baseTexture.hasLoaded) { + if (value.baseTexture.hasLoaded) + { this._onTextureUpdate(); } - else { + else + { value.once('update', this._onTextureUpdate.bind(this)); } } @@ -172,18 +185,22 @@ * * @private */ -Sprite.prototype._onTextureUpdate = function () { +Sprite.prototype._onTextureUpdate = function () +{ // so if _width is 0 then width was not set.. - if (this._width) { + if (this._width) + { this.scale.x = this._width / this.texture.frame.width; } - if (this._height) { + if (this._height) + { this.scale.y = this._height / this.texture.frame.height; } }; -Sprite.prototype._renderWebGL = function (renderer) { +Sprite.prototype._renderWebGL = function (renderer) +{ // this is where content gets renderd.. // watch this space for a little render state manager.. @@ -197,7 +214,8 @@ * @param matrix {Matrix} the transformation matrix of the sprite * @return {Rectangle} the framing rectangle */ -Sprite.prototype.getBounds = function (matrix) { +Sprite.prototype.getBounds = function (matrix) +{ var width = this.texture.frame.width; var height = this.texture.frame.height; @@ -224,11 +242,13 @@ if(b === 0 && c === 0) { // scale may be negative! - if (a < 0) { + if (a < 0) + { a *= -1; } - if (d < 0) { + if (d < 0) + { d *= -1; } @@ -293,28 +313,34 @@ * * @param renderer {CanvasRenderer} The renderer */ -Sprite.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) { +Sprite.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) + { return; } - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; renderer.context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } // Ignore null sources - if (this.texture.valid) { + if (this.texture.valid) + { var resolution = this.texture.baseTexture.resolution / renderer.resolution; renderer.context.globalAlpha = this.worldAlpha; // If smoothingEnabled is supported and we need to change the smoothing property for this texture - if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) { + if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) + { renderer.scaleMode = this.texture.baseTexture.scaleMode; renderer.context[renderer.smoothProperty] = (renderer.scaleMode === CONST.scaleModes.LINEAR); } @@ -324,7 +350,8 @@ var dy = (this.texture.trim ? this.texture.trim.y : 0) - (this.anchor.y * this.texture.trim.height); // Allow for pixel rounding - if (renderer.roundPixels) { + if (renderer.roundPixels) + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -337,7 +364,8 @@ dx = dx | 0; dy = dy | 0; } - else { + else + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -348,8 +376,10 @@ ); } - if (this.tint !== 0xFFFFFF) { - if (this.cachedTint !== this.tint) { + if (this.tint !== 0xFFFFFF) + { + if (this.cachedTint !== this.tint) + { this.cachedTint = this.tint; // TODO clean up caching - how to clean up the caches? @@ -368,7 +398,8 @@ this.texture.crop.height / resolution ); } - else { + else + { renderer.context.drawImage( this.texture.baseTexture.source, this.texture.crop.x, @@ -383,11 +414,13 @@ } } - for (var i = 0, j = this.children.length; i < j; i++) { + for (var i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -402,10 +435,12 @@ * @param frameId {String} The frame Id of the texture in the cache * @return {Sprite} A new Sprite using a texture from the texture cache matching the frameId */ -Sprite.fromFrame = function (frameId) { +Sprite.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache' + this); } @@ -420,6 +455,7 @@ * @param imageId {String} The image url of the texture * @return {Sprite} A new Sprite using a texture from the texture cache matching the image id */ -Sprite.fromImage = function (imageId, crossorigin, scaleMode) { +Sprite.fromImage = function (imageId, crossorigin, scaleMode) +{ return new Sprite(Texture.fromImage(imageId, crossorigin, scaleMode)); }; diff --git a/src/core/display/SpriteBatch.js b/src/core/display/SpriteBatch.js index 3187777..c196fef 100644 --- a/src/core/display/SpriteBatch.js +++ b/src/core/display/SpriteBatch.js @@ -12,7 +12,8 @@ * ```js * var container = new SpriteBatch(); * - * for(var i = 0; i < 100; ++i) { + * for(var i = 0; i < 100; ++i) + * { * var sprite = new PIXI.Sprite.fromImage("myImage.png"); * container.addChild(sprite); * } @@ -25,7 +26,8 @@ */ //TODO RENAME to PARTICLE CONTAINER? -function SpriteBatch() { +function SpriteBatch() +{ DisplayObjectContainer.call(this); } @@ -38,7 +40,8 @@ * * @private */ -SpriteBatch.prototype.updateTransform = function () { +SpriteBatch.prototype.updateTransform = function () +{ // TODO don't need to! this.displayObjectUpdateTransform(); // PIXI.DisplayObjectContainer.prototype.updateTransform.call( this ); @@ -50,8 +53,10 @@ * @param renderer {WebGLRenderer} The webgl renderer * @private */ -SpriteBatch.prototype.renderWebGL = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderWebGL = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -71,8 +76,10 @@ * @param renderer {CanvasRenderer} The canvas renderer * @private */ -SpriteBatch.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -84,10 +91,12 @@ this.displayObjectUpdateTransform(); - for (var i = 0; i < this.children.length; ++i) { + for (var i = 0; i < this.children.length; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -95,9 +104,11 @@ context.globalAlpha = this.worldAlpha * child.alpha; - if (child.rotation % (Math.PI * 2) === 0) { + if (child.rotation % (Math.PI * 2) === 0) + { // this is the fastest way to optimise! - if rotation is 0 then we can avoid any kind of setTransform call - if (isRotated) { + if (isRotated) + { context.setTransform( transform.a, transform.b, @@ -122,8 +133,10 @@ frame.height * child.scale.y ); } - else { - if (!isRotated) { + else + { + if (!isRotated) + { isRotated = true; } @@ -131,7 +144,8 @@ var childTransform = child.worldTransform; - if (renderer.roundPixels) { + if (renderer.roundPixels) + { context.setTransform( childTransform.a, childTransform.b, @@ -141,7 +155,8 @@ childTransform.ty | 0 ); } - else { + else + { context.setTransform( childTransform.a, childTransform.b, diff --git a/src/core/index.js b/src/core/index.js index 3954b6f..eb4a82b 100644 --- a/src/core/index.js +++ b/src/core/index.js @@ -58,11 +58,13 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRenderer: function (width, height, options, noWebGL) { + autoDetectRenderer: function (width, height, options, noWebGL) + { width = width || 800; height = height || 600; - if (!noWebGL && require('webgl-enabled')()) { + if (!noWebGL && require('webgl-enabled')()) + { return new core.WebGLRenderer(width, height, options); } @@ -87,7 +89,8 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRecommendedRenderer: function (width, height, options) { + autoDetectRecommendedRenderer: function (width, height, options) + { var isAndroid = /Android/i.test(navigator.userAgent); return core.autoDetectRenderer(width, height, options, isAndroid); diff --git a/src/core/math/Matrix.js b/src/core/math/Matrix.js index c2f87e2..2ff4848 100644 --- a/src/core/math/Matrix.js +++ b/src/core/math/Matrix.js @@ -10,7 +10,8 @@ * @class * @namespace PIXI */ -function Matrix() { +function Matrix() +{ /** * @member {number} * @default 1 @@ -63,7 +64,8 @@ * * @param array {number[]} The array that the matrix will be populated from. */ -Matrix.prototype.fromArray = function (array) { +Matrix.prototype.fromArray = function (array) +{ this.a = array[0]; this.b = array[1]; this.c = array[3]; @@ -78,14 +80,17 @@ * @param transpose {boolean} Whether we need to transpose the matrix or not * @return {number[]} the newly created array which contains the matrix */ -Matrix.prototype.toArray = function (transpose) { - if (!this.array) { +Matrix.prototype.toArray = function (transpose) +{ + if (!this.array) + { this.array = new Float32Array(9); } var array = this.array; - if (transpose) { + if (transpose) + { array[0] = this.a; array[1] = this.b; array[2] = 0; @@ -96,7 +101,8 @@ array[7] = this.ty; array[8] = 1; } - else { + else + { array[0] = this.a; array[1] = this.c; array[2] = this.tx; @@ -119,7 +125,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, transformed through this matrix */ -Matrix.prototype.apply = function (pos, newPos) { +Matrix.prototype.apply = function (pos, newPos) +{ newPos = newPos || new Point(); newPos.x = this.a * pos.x + this.c * pos.y + this.tx; @@ -136,7 +143,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, inverse-transformed through this matrix */ -Matrix.prototype.applyInverse = function (pos, newPos) { +Matrix.prototype.applyInverse = function (pos, newPos) +{ newPos = newPos || new Point(); var id = 1 / (this.a * this.d + this.c * -this.b); @@ -154,7 +162,8 @@ * @param {number} y * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.translate = function (x, y) { +Matrix.prototype.translate = function (x, y) +{ this.tx += x; this.ty += y; @@ -168,7 +177,8 @@ * @param {number} y The amount to scale vertically * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.scale = function (x, y) { +Matrix.prototype.scale = function (x, y) +{ this.a *= x; this.d *= y; this.c *= x; @@ -186,7 +196,8 @@ * @param {number} angle - The angle in radians. * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.rotate = function (angle) { +Matrix.prototype.rotate = function (angle) +{ var cos = Math.cos( angle ); var sin = Math.sin( angle ); @@ -210,7 +221,8 @@ * @param {Matrix} matrix * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.append = function (matrix) { +Matrix.prototype.append = function (matrix) +{ var a1 = this.a; var b1 = this.b; var c1 = this.c; @@ -232,7 +244,8 @@ * * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.identity = function () { +Matrix.prototype.identity = function () +{ this.a = 1; this.b = 0; this.c = 0; diff --git a/src/core/math/Point.js b/src/core/math/Point.js index 7565b2d..632f346 100644 --- a/src/core/math/Point.js +++ b/src/core/math/Point.js @@ -7,7 +7,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -function Point(x, y) { +function Point(x, y) +{ /** * @member {number} * @default 0 @@ -29,7 +30,8 @@ * * @return {Point} a copy of the point */ -Point.prototype.clone = function () { +Point.prototype.clone = function () +{ return new Point(this.x, this.y); }; @@ -40,7 +42,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -Point.prototype.set = function (x, y) { +Point.prototype.set = function (x, y) +{ this.x = x || 0; this.y = y || ( (y !== 0) ? this.x : 0 ) ; }; diff --git a/src/core/math/shapes/Circle.js b/src/core/math/shapes/Circle.js index 69cfdc9..4d76efc 100644 --- a/src/core/math/shapes/Circle.js +++ b/src/core/math/shapes/Circle.js @@ -10,7 +10,8 @@ * @param y {number} The Y coordinate of the center of this circle * @param radius {number} The radius of the circle */ -function Circle(x, y, radius) { +function Circle(x, y, radius) +{ /** * @member {number} * @default 0 @@ -46,7 +47,8 @@ * @method clone * @return {Circle} a copy of the Circle */ -Circle.prototype.clone = function () { +Circle.prototype.clone = function () +{ return new Circle(this.x, this.y, this.radius); }; @@ -58,8 +60,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Circle */ -Circle.prototype.contains = function (x, y) { - if (this.radius <= 0) { +Circle.prototype.contains = function (x, y) +{ + if (this.radius <= 0) + { return false; } @@ -79,6 +83,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Circle.prototype.getBounds = function () { +Circle.prototype.getBounds = function () +{ return new Rectangle(this.x - this.radius, this.y - this.radius, this.radius * 2, this.radius * 2); }; diff --git a/src/core/math/shapes/Ellipse.js b/src/core/math/shapes/Ellipse.js index 4f2d066..fefd01a 100644 --- a/src/core/math/shapes/Ellipse.js +++ b/src/core/math/shapes/Ellipse.js @@ -11,7 +11,8 @@ * @param width {number} The half width of this ellipse * @param height {number} The half height of this ellipse */ -function Ellipse(x, y, width, height) { +function Ellipse(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -53,7 +54,8 @@ * @method clone * @return {Ellipse} a copy of the ellipse */ -Ellipse.prototype.clone = function () { +Ellipse.prototype.clone = function () +{ return new Ellipse(this.x, this.y, this.width, this.height); }; @@ -65,8 +67,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coords are within this ellipse */ -Ellipse.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Ellipse.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } @@ -86,6 +90,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Ellipse.prototype.getBounds = function () { +Ellipse.prototype.getBounds = function () +{ return new Rectangle(this.x - this.width, this.y - this.height, this.width, this.height); }; diff --git a/src/core/math/shapes/Polygon.js b/src/core/math/shapes/Polygon.js index ae89148..fea6d37 100644 --- a/src/core/math/shapes/Polygon.js +++ b/src/core/math/shapes/Polygon.js @@ -10,16 +10,20 @@ * arguments passed can be flat x,y values e.g. `new Polygon(x,y, x,y, x,y, ...)` where `x` and `y` are * Numbers. */ -function Polygon(points) { +function Polygon(points) +{ //if points isn't an array, use arguments as the array - if (!(points instanceof Array)) { + if (!(points instanceof Array)) + { points = Array.prototype.slice.call(arguments); } //if this is a flat array of numbers, convert it to points - if (points[0] instanceof Point) { + if (points[0] instanceof Point) + { var p = []; - for (var i = 0, il = points.length; i < il; i++) { + for (var i = 0, il = points.length; i < il; i++) + { p.push(points[i].x, points[i].y); } @@ -51,7 +55,8 @@ * * @return {Polygon} a copy of the polygon */ -Polygon.prototype.clone = function () { +Polygon.prototype.clone = function () +{ return new Polygon(this.points.slice()); }; @@ -62,19 +67,22 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this polygon */ -Polygon.prototype.contains = function (x, y) { +Polygon.prototype.contains = function (x, y) +{ var inside = false; // use some raycasting to test hits // https://github.com/substack/point-in-polygon/blob/master/index.js var length = this.points.length / 2; - for (var i = 0, j = length - 1; i < length; j = i++) { + for (var i = 0, j = length - 1; i < length; j = i++) + { var xi = this.points[i * 2], yi = this.points[i * 2 + 1], xj = this.points[j * 2], yj = this.points[j * 2 + 1], intersect = ((yi > y) !== (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi); - if (intersect) { + if (intersect) + { inside = !inside; } } diff --git a/src/core/math/shapes/Rectangle.js b/src/core/math/shapes/Rectangle.js index 16ac62a..4008b68 100644 --- a/src/core/math/shapes/Rectangle.js +++ b/src/core/math/shapes/Rectangle.js @@ -10,7 +10,8 @@ * @param width {number} The overall width of this rectangle * @param height {number} The overall height of this rectangle */ -function Rectangle(x, y, width, height) { +function Rectangle(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -60,7 +61,8 @@ * * @return {Rectangle} a copy of the rectangle */ -Rectangle.prototype.clone = function () { +Rectangle.prototype.clone = function () +{ return new Rectangle(this.x, this.y, this.width, this.height); }; @@ -71,13 +73,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rectangle */ -Rectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Rectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/math/shapes/RoundedRectangle.js b/src/core/math/shapes/RoundedRectangle.js index 27d286e..7bf6411 100644 --- a/src/core/math/shapes/RoundedRectangle.js +++ b/src/core/math/shapes/RoundedRectangle.js @@ -11,7 +11,8 @@ * @param height {number} The overall height of this rounded rectangle * @param radius {number} Controls the radius of the rounded corners */ -function RoundedRectangle(x, y, width, height, radius) { +function RoundedRectangle(x, y, width, height, radius) +{ /** * @member {number} * @default 0 @@ -58,7 +59,8 @@ * * @return {RoundedRectangle} a copy of the rounded rectangle */ -RoundedRectangle.prototype.clone = function () { +RoundedRectangle.prototype.clone = function () +{ return new RoundedRectangle(this.x, this.y, this.width, this.height, this.radius); }; @@ -69,13 +71,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rounded Rectangle */ -RoundedRectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +RoundedRectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/primitives/Graphics.js b/src/core/primitives/Graphics.js index 261c534..e902d2a 100644 --- a/src/core/primitives/Graphics.js +++ b/src/core/primitives/Graphics.js @@ -16,7 +16,8 @@ * @extends DisplayObjectContainer * @namespace PIXI */ -function Graphics() { +function Graphics() +{ DisplayObjectContainer.call(this); this.renderable = true; @@ -154,16 +155,20 @@ * @private */ cacheAsBitmap: { - get: function () { + get: function () + { return this._cacheAsBitmap; }, - set: function (value) { + set: function (value) + { this._cacheAsBitmap = value; - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._generateCachedSprite(); } - else { + else + { this.destroyCachedSprite(); this.dirty = true; } @@ -176,7 +181,8 @@ * * @return {Graphics} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ var clone = new Graphics(); clone.renderable = this.renderable; @@ -192,7 +198,8 @@ clone.cachedSpriteDirty = this.cachedSpriteDirty; // copy graphics data - for (var i = 0; i < this.graphicsData.length; ++i) { + for (var i = 0; i < this.graphicsData.length; ++i) + { clone.graphicsData.push(this.graphicsData.clone()); } @@ -211,17 +218,21 @@ * @param alpha {number} alpha of the line to draw, will update the objects stored style * @return {Graphics} */ -Graphics.prototype.lineStyle = function (lineWidth, color, alpha) { +Graphics.prototype.lineStyle = function (lineWidth, color, alpha) +{ this.lineWidth = lineWidth || 0; this.lineColor = color || 0; this.lineAlpha = (arguments.length < 3) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length) + { // halfway through a line? start a new one! this.drawShape( new math.Polygon( this.currentPath.shape.points.slice(-2) )); } - else { + else + { // otherwise its empty so lets just set the line properties this.currentPath.lineWidth = this.lineWidth; this.currentPath.lineColor = this.lineColor; @@ -239,7 +250,8 @@ * @param y {number} the Y coordinate to move to * @return {Graphics} */ -Graphics.prototype.moveTo = function (x, y) { +Graphics.prototype.moveTo = function (x, y) +{ this.drawShape(new math.Polygon([x,y])); return this; @@ -253,7 +265,8 @@ * @param y {number} the Y coordinate to draw to * @return {Graphics} */ -Graphics.prototype.lineTo = function (x, y) { +Graphics.prototype.lineTo = function (x, y) +{ this.currentPath.shape.points.push(x, y); this.dirty = true; @@ -270,13 +283,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -285,7 +302,8 @@ n = 20, points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { this.moveTo(0, 0); } @@ -293,7 +311,8 @@ var fromY = points[points.length-1]; var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; xa = fromX + ( (cpX - fromX) * j ); @@ -319,13 +338,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -342,7 +365,8 @@ var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; dt = (1 - j); @@ -373,13 +397,17 @@ * @param radius {number} The radius of the arc * @return {Graphics} */ -Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points.push(x1, y1); } } - else { + else + { this.moveTo(x1, y1); } @@ -392,12 +420,15 @@ b2 = x2 - x1, mm = Math.abs(a1 * b2 - b1 * a2); - if (mm < 1.0e-8 || radius === 0) { - if (points[points.length-2] !== x1 || points[points.length-1] !== y1) { + if (mm < 1.0e-8 || radius === 0) + { + if (points[points.length-2] !== x1 || points[points.length-1] !== y1) + { points.push(x1, y1); } } - else { + else + { var dd = a1 * a1 + b1 * b1, cc = a2 * a2 + b2 * b2, tt = a1 * a2 + b1 * b2, @@ -433,42 +464,51 @@ * @param anticlockwise {boolean} Optional. Specifies whether the drawing should be counterclockwise or clockwise. False is default, and indicates clockwise, while true indicates counter-clockwise. * @return {Graphics} */ -Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) { +Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) +{ var startX = cx + Math.cos(startAngle) * radius; var startY = cy + Math.sin(startAngle) * radius; var points; // TODO - This if-else makes no sense. It uses currentPath in the else where it doesn't exist... - if (this.currentPath) { + if (this.currentPath) + { points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { points.push(startX, startY); } - else if (points[points.length-2] !== startX || points[points.length-1] !== startY) { + else if (points[points.length-2] !== startX || points[points.length-1] !== startY) + { points.push(startX, startY); } } - else { + else + { this.moveTo(startX, startY); points = this.currentPath.shape.points; } - if (startAngle === endAngle) { + if (startAngle === endAngle) + { return this; } - if (!anticlockwise && endAngle <= startAngle) { + if (!anticlockwise && endAngle <= startAngle) + { endAngle += Math.PI * 2; } - else if (anticlockwise && startAngle <= endAngle) { + else if (anticlockwise && startAngle <= endAngle) + { startAngle += Math.PI * 2; } var sweep = anticlockwise ? (startAngle - endAngle) *-1 : (endAngle - startAngle); var segs = (Math.abs(sweep)/ (Math.PI * 2)) * 40; - if (sweep === 0) { + if (sweep === 0) + { return this; } @@ -482,7 +522,8 @@ var remainder = ( segMinus % 1 ) / segMinus; - for (var i = 0; i <= segMinus; ++i) { + for (var i = 0; i <= segMinus; ++i) + { var real = i + remainder * i; var angle = ((theta) + startAngle + (theta2 * real)); @@ -506,13 +547,16 @@ * @param alpha {number} the alpha of the fill * @return {Graphics} */ -Graphics.prototype.beginFill = function (color, alpha) { +Graphics.prototype.beginFill = function (color, alpha) +{ this.filling = true; this.fillColor = color || 0; this.fillAlpha = (alpha === undefined) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length <= 2) + { this.currentPath.fill = this.filling; this.currentPath.fillColor = this.fillColor; this.currentPath.fillAlpha = this.fillAlpha; @@ -526,7 +570,8 @@ * * @return {Graphics} */ -Graphics.prototype.endFill = function () { +Graphics.prototype.endFill = function () +{ this.filling = false; this.fillColor = null; this.fillAlpha = 1; @@ -542,7 +587,8 @@ * @param height {number} The height of the rectangle * @return {Graphics} */ -Graphics.prototype.drawRect = function ( x, y, width, height ) { +Graphics.prototype.drawRect = function ( x, y, width, height ) +{ this.drawShape(new math.Rectangle(x,y, width, height)); return this; @@ -556,7 +602,8 @@ * @param height {number} The height of the rectangle * @param radius {number} Radius of the rectangle corners */ -Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) { +Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) +{ this.drawShape(new math.RoundedRectangle(x, y, width, height, radius)); return this; @@ -570,7 +617,8 @@ * @param radius {number} The radius of the circle * @return {Graphics} */ -Graphics.prototype.drawCircle = function (x, y, radius) { +Graphics.prototype.drawCircle = function (x, y, radius) +{ this.drawShape(new math.Circle(x,y, radius)); return this; @@ -585,7 +633,8 @@ * @param height {number} The half height of the ellipse * @return {Graphics} */ -Graphics.prototype.drawEllipse = function (x, y, width, height) { +Graphics.prototype.drawEllipse = function (x, y, width, height) +{ this.drawShape(new math.Ellipse(x, y, width, height)); return this; @@ -597,8 +646,10 @@ * @param path {Array} The path data used to construct the polygon. * @return {Graphics} */ -Graphics.prototype.drawPolygon = function (path) { - if (!(path instanceof Array)) { +Graphics.prototype.drawPolygon = function (path) +{ + if (!(path instanceof Array)) + { path = Array.prototype.slice.call(arguments); } @@ -612,7 +663,8 @@ * * @return {Graphics} */ -Graphics.prototype.clear = function () { +Graphics.prototype.clear = function () +{ this.lineWidth = 0; this.filling = false; @@ -631,7 +683,8 @@ * @param scaleMode {number} Should be one of the scaleMode consts * @return {Texture} a texture of the graphics object */ -Graphics.prototype.generateTexture = function (resolution, scaleMode) { +Graphics.prototype.generateTexture = function (resolution, scaleMode) +{ resolution = resolution || 1; var bounds = this.getBounds(); @@ -655,17 +708,21 @@ * * @param renderer {WebGLRenderer} */ -Graphics.prototype._renderWebGL = function (renderer) { +Graphics.prototype._renderWebGL = function (renderer) +{ // if the sprite is not visible or the alpha is 0 then no need to render this element - if (this.isMask === true) { + if (this.isMask === true) + { return; } // this code may still be needed so leaving for now.. - // + // /* - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture on the gpu too! @@ -681,17 +738,24 @@ return; } - */ - - // check if the webgl graphic needs to be updated - if (this.glDirty) { - this.dirty = true; - this.glDirty = false; - } + else */ - renderer.setObjectRendererer(renderer.graphicsRenderer); - renderer.graphicsRenderer.render(this); + renderer.spriteBatch.stop(); + renderer.blendModeManager.setBlendMode(this.blendMode); + // check blend mode + renderer.blendModeManager.setBlendMode( this.blendMode ); + + // check if the webgl graphic needs to be updated + if (this.glDirty) + { + this.dirty = true; + this.glDirty = false; + } + + WebGLGraphics.renderGraphics(this, renderer); + + renderer.spriteBatch.start(); }; /** @@ -700,14 +764,18 @@ * @param renderer {CanvasRenderer} * @private */ -Graphics.prototype.renderCanvas = function (renderer) { +Graphics.prototype.renderCanvas = function (renderer) +{ // 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.isMask === true) { + if (!this.visible || this.alpha <= 0 || this.isMask === true) + { return; } - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture @@ -723,16 +791,19 @@ return; } - else { + else + { var context = renderer.context; var transform = this.worldTransform; - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } @@ -748,11 +819,13 @@ CanvasGraphics.renderGraphics(this, context); - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } } @@ -763,13 +836,16 @@ * * @return {Rectangle} the rectangular bounding area */ -Graphics.prototype.getBounds = function (matrix) { +Graphics.prototype.getBounds = function (matrix) +{ // return an empty object if the item is a mask! - if (this.isMask) { + if (this.isMask) + { return math.Rectangle.EMPTY; } - if (this.dirty) { + if (this.dirty) + { this.updateLocalBounds(); this.glDirty = true; @@ -841,23 +917,27 @@ * Update the bounds of the object * */ -Graphics.prototype.updateLocalBounds = function () { +Graphics.prototype.updateLocalBounds = function () +{ var minX = Infinity; var maxX = -Infinity; var minY = Infinity; var maxY = -Infinity; - if (this.graphicsData.length) { + if (this.graphicsData.length) + { var shape, points, x, y, w, h; - for (var i = 0; i < this.graphicsData.length; i++) { + for (var i = 0; i < this.graphicsData.length; i++) + { var data = this.graphicsData[i]; var type = data.type; var lineWidth = data.lineWidth; shape = data.shape; - if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) { + if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) + { x = shape.x - lineWidth/2; y = shape.y - lineWidth/2; w = shape.width + lineWidth; @@ -869,7 +949,8 @@ minY = y < minY ? y : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.CIRC) { + else if (type === CONST.SHAPES.CIRC) + { x = shape.x; y = shape.y; w = shape.radius + lineWidth/2; @@ -881,7 +962,8 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.ELIP) { + else if (type === CONST.SHAPES.ELIP) + { x = shape.x; y = shape.y; w = shape.width + lineWidth/2; @@ -893,11 +975,13 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else { + else + { // POLY points = shape.points; - for (var j = 0; j < points.length; j += 2) { + for (var j = 0; j < points.length; j += 2) + { x = points[j]; y = points[j+1]; @@ -910,7 +994,8 @@ } } } - else { + else + { minX = 0; maxX = 0; minY = 0; @@ -931,10 +1016,12 @@ * * @private */ -Graphics.prototype._generateCachedSprite = function () { +Graphics.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { var canvasBuffer = new CanvasBuffer(bounds.width, bounds.height); var texture = Texture.fromCanvas(canvasBuffer.canvas); @@ -943,7 +1030,8 @@ this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.buffer.resize(bounds.width, bounds.height); } @@ -968,7 +1056,8 @@ * * @private */ -Graphics.prototype.updateCachedSpriteTexture = function () { +Graphics.prototype.updateCachedSpriteTexture = function () +{ var cachedSprite = this._cachedSprite; var texture = cachedSprite.texture; var canvas = cachedSprite.buffer.canvas; @@ -989,7 +1078,8 @@ * Destroys a previous cached sprite. * */ -Graphics.prototype.destroyCachedSprite = function () { +Graphics.prototype.destroyCachedSprite = function () +{ this._cachedSprite.texture.destroy(true); // let the gc collect the unused sprite @@ -1003,10 +1093,13 @@ * @param {Circle|Rectangle|Ellipse|Line|Polygon} shape The Shape object to draw. * @return {GraphicsData} The generated GraphicsData object. */ -Graphics.prototype.drawShape = function (shape) { - if (this.currentPath) { +Graphics.prototype.drawShape = function (shape) +{ + if (this.currentPath) + { // check current path! - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath.shape.points.length <= 2) + { this.graphicsData.pop(); } } @@ -1017,7 +1110,8 @@ this.graphicsData.push(data); - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { data.shape.closed = this.filling; this.currentPath = data; } diff --git a/src/core/primitives/GraphicsData.js b/src/core/primitives/GraphicsData.js index 99decbe..788f6f2 100644 --- a/src/core/primitives/GraphicsData.js +++ b/src/core/primitives/GraphicsData.js @@ -4,7 +4,8 @@ * @class * @namespace PIXI */ -function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) { +function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) +{ this.lineWidth = lineWidth; this.lineColor = lineColor; this.lineAlpha = lineAlpha; @@ -27,7 +28,8 @@ * * @return {GraphicsData} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ return new GraphicsData( this.lineWidth, this.lineColor, diff --git a/src/core/renderers/canvas/CanvasRenderer.js b/src/core/renderers/canvas/CanvasRenderer.js index 15a0978..7aebd44 100644 --- a/src/core/renderers/canvas/CanvasRenderer.js +++ b/src/core/renderers/canvas/CanvasRenderer.js @@ -17,17 +17,22 @@ * @param [options.resolution=1] {number} the resolution of the renderer retina would be 2 * @param [options.clearBeforeRender=true] {boolean} This sets if the CanvasRenderer will clear the canvas or not before the new render pass. */ -function CanvasRenderer(width, height, options) { +function CanvasRenderer(width, height, options) +{ utils.sayHello('Canvas'); - if (options) { - for (var i in CONST.defaultRenderOptions) { - if (typeof options[i] === 'undefined') { + if (options) + { + for (var i in CONST.defaultRenderOptions) + { + if (typeof options[i] === 'undefined') + { options[i] = CONST.defaultRenderOptions[i]; } } } - else { + else + { options = CONST.defaultRenderOptions; } @@ -156,19 +161,24 @@ this.smoothProperty = null; - if (this.context.imageSmoothingEnabled) { + if (this.context.imageSmoothingEnabled) + { this.smoothProperty = 'imageSmoothingEnabled'; } - else if (this.context.webkitImageSmoothingEnabled) { + else if (this.context.webkitImageSmoothingEnabled) + { this.smoothProperty = 'webkitImageSmoothingEnabled'; } - else if (this.context.mozImageSmoothingEnabled) { + else if (this.context.mozImageSmoothingEnabled) + { this.smoothProperty = 'mozImageSmoothingEnabled'; } - else if (this.context.oImageSmoothingEnabled) { + else if (this.context.oImageSmoothingEnabled) + { this.smoothProperty = 'oImageSmoothingEnabled'; } - else if (this.context.msImageSmoothingEnabled) { + else if (this.context.msImageSmoothingEnabled) + { this.smoothProperty = 'msImageSmoothingEnabled'; } @@ -193,10 +203,12 @@ * @memberof CanvasRenderer# */ backgroundColor: { - get: function () { + get: function () + { return this._backgroundColor; }, - set: function (val) { + set: function (val) + { this._backgroundColor = val; this._backgroundColorString = utils.hex2string(val); } @@ -208,7 +220,8 @@ * * @param object {DisplayObject} the object to be rendered */ -CanvasRenderer.prototype.render = function (object) { +CanvasRenderer.prototype.render = function (object) +{ object.updateTransform(); this.context.setTransform(1,0,0,1,0,0); @@ -218,16 +231,20 @@ this.currentBlendMode = CONST.blendModes.NORMAL; this.context.globalCompositeOperation = this.blendModes[CONST.blendModes.NORMAL]; - if (navigator.isCocoonJS && this.view.screencanvas) { + if (navigator.isCocoonJS && this.view.screencanvas) + { this.context.fillStyle = 'black'; this.context.clear(); } - if (this.clearBeforeRender) { - if (this.transparent) { + if (this.clearBeforeRender) + { + if (this.transparent) + { this.context.clearRect(0, 0, this.width, this.height); } - else { + else + { this.context.fillStyle = this._backgroundColorString; this.context.fillRect(0, 0, this.width , this.height); } @@ -241,8 +258,10 @@ * * @param [removeView=false] {boolean} Removes the Canvas element from the DOM. */ -CanvasRenderer.prototype.destroy = function (removeView) { - if (removeView && this.view.parent) { +CanvasRenderer.prototype.destroy = function (removeView) +{ + if (removeView && this.view.parent) + { this.view.parent.removeChild(this.view); } @@ -257,14 +276,16 @@ * @param width {number} the new width of the canvas view * @param height {number} the new height of the canvas view */ -CanvasRenderer.prototype.resize = function (width, height) { +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) { + if (this.autoResize) + { this.view.style.width = this.width / this.resolution + 'px'; this.view.style.height = this.height / this.resolution + 'px'; } @@ -276,7 +297,8 @@ * @param displayObject {DisplayObject} The displayObject to render * @private */ -CanvasRenderer.prototype.renderDisplayObject = function (displayObject) { +CanvasRenderer.prototype.renderDisplayObject = function (displayObject) +{ displayObject.renderCanvas(this); }; @@ -285,11 +307,14 @@ * * @private */ -CanvasRenderer.prototype._mapBlendModes = function () { - if (!this.blendModes) { +CanvasRenderer.prototype._mapBlendModes = function () +{ + if (!this.blendModes) + { this.blendModes = {}; - if (utils.canUseNewCanvasBlendModes()) { + if (utils.canUseNewCanvasBlendModes()) + { this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? this.blendModes[CONST.blendModes.MULTIPLY] = 'multiply'; @@ -308,7 +333,8 @@ this.blendModes[CONST.blendModes.COLOR] = 'color'; this.blendModes[CONST.blendModes.LUMINOSITY] = 'luminosity'; } - else { + else + { // this means that the browser does not support the cool new blend modes in canvas 'cough' ie 'cough' this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? diff --git a/src/core/renderers/canvas/utils/CanvasBuffer.js b/src/core/renderers/canvas/utils/CanvasBuffer.js index ebe5d47..b183a66 100644 --- a/src/core/renderers/canvas/utils/CanvasBuffer.js +++ b/src/core/renderers/canvas/utils/CanvasBuffer.js @@ -6,7 +6,8 @@ * @param width {number} the width for the newly created canvas * @param height {number} the height for the newly created canvas */ -function CanvasBuffer(width, height) { +function CanvasBuffer(width, height) +{ /** * The Canvas object that belongs to this CanvasBuffer. * @@ -36,10 +37,12 @@ * @memberof CanvasBuffer# */ width: { - get: function () { + get: function () + { return this.canvas.width; }, - set: function (val) { + set: function (val) + { this.canvas.width = val; } }, @@ -50,10 +53,12 @@ * @memberof CanvasBuffer# */ height: { - get: function () { + get: function () + { return this.canvas.height; }, - set: function (val) { + set: function (val) + { this.canvas.height = val; } } @@ -64,7 +69,8 @@ * * @private */ -CanvasBuffer.prototype.clear = function () { +CanvasBuffer.prototype.clear = function () +{ this.context.setTransform(1, 0, 0, 1, 0, 0); this.context.clearRect(0,0, this.canvas.width, this.canvas.height); }; @@ -75,7 +81,8 @@ * @param width {number} the new width of the canvas * @param height {number} the new height of the canvas */ -CanvasBuffer.prototype.resize = function (width, height) { +CanvasBuffer.prototype.resize = function (width, height) +{ this.canvas.width = width; this.canvas.height = height; }; diff --git a/src/core/renderers/canvas/utils/CanvasGraphics.js b/src/core/renderers/canvas/utils/CanvasGraphics.js index c7eaa2a..3f2a91f 100644 --- a/src/core/renderers/canvas/utils/CanvasGraphics.js +++ b/src/core/renderers/canvas/utils/CanvasGraphics.js @@ -13,15 +13,18 @@ * @param graphics {Graphics} the actual graphics object to render * @param context {CanvasRenderingContext2D} the 2d drawing method of the canvas */ -CanvasGraphics.renderGraphics = function (graphics, context) { +CanvasGraphics.renderGraphics = function (graphics, context) +{ var worldAlpha = graphics.worldAlpha; - if (graphics.dirty) { + if (graphics.dirty) + { this.updateGraphicsTint(graphics); graphics.dirty = false; } - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; @@ -30,69 +33,82 @@ context.lineWidth = data.lineWidth; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { context.beginPath(); var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } - if (shape.closed) { + if (shape.closed) + { context.lineTo(points[0], points[1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fillRect(shape.x, shape.y, shape.width, shape.height); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.strokeRect(shape.x, shape.y, shape.width, shape.height); } } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.beginPath(); context.arc(shape.x, shape.y, shape.radius,0,2*Math.PI); context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas var w = shape.width * 2; @@ -119,18 +135,21 @@ context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; var width = shape.width; @@ -152,13 +171,15 @@ context.quadraticCurveTo(rx, ry, rx, ry + radius); context.closePath(); - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); @@ -174,45 +195,54 @@ * @param graphics {Graphics} the graphics which will be used as a mask * @param context {CanvasRenderingContext2D} the context 2d method of the canvas */ -CanvasGraphics.renderGraphicsMask = function (graphics, context) { +CanvasGraphics.renderGraphicsMask = function (graphics, context) +{ var len = graphics.graphicsData.length; - if (len === 0) { + if (len === 0) + { return; } context.beginPath(); - for (var i = 0; i < len; i++) { + for (var i = 0; i < len; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { context.rect(shape.x, shape.y, shape.width, shape.height); context.closePath(); } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.arc(shape.x, shape.y, shape.radius, 0, 2 * Math.PI); context.closePath(); } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas @@ -237,7 +267,8 @@ context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); context.closePath(); } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; @@ -262,8 +293,10 @@ } }; -CanvasGraphics.updateGraphicsTint = function (graphics) { - if (graphics.tint === 0xFFFFFF) { +CanvasGraphics.updateGraphicsTint = function (graphics) +{ + if (graphics.tint === 0xFFFFFF) + { return; } @@ -271,7 +304,8 @@ var tintG = (graphics.tint >> 8 & 0xFF) / 255; var tintB = (graphics.tint & 0xFF)/ 255; - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var fillColor = data.fillColor | 0; diff --git a/src/core/renderers/canvas/utils/CanvasMaskManager.js b/src/core/renderers/canvas/utils/CanvasMaskManager.js index e04a733..9827d36 100644 --- a/src/core/renderers/canvas/utils/CanvasMaskManager.js +++ b/src/core/renderers/canvas/utils/CanvasMaskManager.js @@ -6,7 +6,8 @@ * @class * @namespace PIXI */ -function CanvasMaskManager() {} +function CanvasMaskManager() +{} CanvasMaskManager.prototype.constructor = CanvasMaskManager; module.exports = CanvasMaskManager; @@ -17,7 +18,8 @@ * @param maskData {object} the maskData that will be pushed * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.pushMask = function (maskData, renderer) { +CanvasMaskManager.prototype.pushMask = function (maskData, renderer) +{ renderer.context.save(); var cacheAlpha = maskData.alpha; @@ -45,6 +47,7 @@ * * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.popMask = function (renderer) { +CanvasMaskManager.prototype.popMask = function (renderer) +{ renderer.context.restore(); }; diff --git a/src/core/renderers/canvas/utils/CanvasTinter.js b/src/core/renderers/canvas/utils/CanvasTinter.js index 17e0529..d2fb1bc 100644 --- a/src/core/renderers/canvas/utils/CanvasTinter.js +++ b/src/core/renderers/canvas/utils/CanvasTinter.js @@ -14,7 +14,8 @@ * @param color {number} the color to use to tint the sprite with * @return {HTMLCanvasElement} The tinted canvas */ -CanvasTinter.getTintedTexture = function (sprite, color) { +CanvasTinter.getTintedTexture = function (sprite, color) +{ var texture = sprite.texture; color = CanvasTinter.roundColor(color); @@ -23,7 +24,8 @@ texture.tintCache = texture.tintCache || {}; - if (texture.tintCache[stringColor]) { + if (texture.tintCache[stringColor]) + { return texture.tintCache[stringColor]; } @@ -33,14 +35,16 @@ //CanvasTinter.tintWithPerPixel(texture, stringColor, canvas); CanvasTinter.tintMethod(texture, color, canvas); - if (CanvasTinter.convertTintToImage) { + if (CanvasTinter.convertTintToImage) + { // is this better? var tintImage = new Image(); tintImage.src = canvas.toDataURL(); texture.tintCache[stringColor] = tintImage; } - else { + else + { texture.tintCache[stringColor] = canvas; // if we are not converting the texture to an image then we need to lose the reference to the canvas CanvasTinter.canvas = null; @@ -56,7 +60,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithMultiply = function (texture, color, canvas) { +CanvasTinter.tintWithMultiply = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -104,7 +109,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithOverlay = function (texture, color, canvas) { +CanvasTinter.tintWithOverlay = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -139,7 +145,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithPerPixel = function (texture, color, canvas) { +CanvasTinter.tintWithPerPixel = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -167,7 +174,8 @@ var pixels = pixelData.data; - for (var i = 0; i < pixels.length; i += 4) { + for (var i = 0; i < pixels.length; i += 4) + { pixels[i+0] *= r; pixels[i+1] *= g; pixels[i+2] *= b; @@ -181,7 +189,8 @@ * * @param color {number} the color to round, should be a hex color */ -CanvasTinter.roundColor = function (color) { +CanvasTinter.roundColor = function (color) +{ var step = CanvasTinter.cacheStepsPerColorChannel; var rgbValues = utils.hex2rgb(color); diff --git a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js index 9f2f89a..35edbaf 100644 --- a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js +++ b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLBlendModeManager(renderer) { +function WebGLBlendModeManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -23,8 +24,10 @@ * * @param blendMode {number} the blendMode, should be a Pixi const, such as BlendModes.ADD */ -WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) { - if (this.currentBlendMode === blendMode) { +WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) +{ + if (this.currentBlendMode === blendMode) + { return false; } diff --git a/src/core/renderers/webgl/managers/WebGLFilterManager.js b/src/core/renderers/webgl/managers/WebGLFilterManager.js index 1179258..2dac048 100644 --- a/src/core/renderers/webgl/managers/WebGLFilterManager.js +++ b/src/core/renderers/webgl/managers/WebGLFilterManager.js @@ -7,7 +7,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLFilterManager(renderer) { +function WebGLFilterManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -32,7 +33,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.texturePool.length = 0; self.initShaderBuffers(); }); @@ -46,7 +48,8 @@ * @param renderer {WebGLRenderer} * @param buffer {ArrayBuffer} */ -WebGLFilterManager.prototype.begin = function (buffer) { +WebGLFilterManager.prototype.begin = function (buffer) +{ this.defaultShader = this.renderer.shaderManager.defaultShader; this.width = this.renderer.projection.x * 2; @@ -60,7 +63,8 @@ * * @param filterBlock {object} the filter that will be pushed to the current filter stack */ -WebGLFilterManager.prototype.pushFilter = function (filterBlock) { +WebGLFilterManager.prototype.pushFilter = function (filterBlock) +{ var gl = this.renderer.gl; var projection = this.renderer.projection; @@ -78,10 +82,12 @@ this.offsetY += filterBlock._filterArea.y; var texture = this.texturePool.pop(); - if (!texture) { + if (!texture) + { texture = new FilterTexture(this.renderer.gl, this.width, this.height); } - else { + else + { texture.resize(this.width, this.height); } @@ -98,29 +104,35 @@ var localX = filterArea.x, localY = filterArea.y; - if (filterArea.x < 0) { + if (filterArea.x < 0) + { filterArea.width += filterArea.x; filterArea.x = 0; } - if (filterArea.y < 0) { + if (filterArea.y < 0) + { filterArea.height += filterArea.y; filterArea.y = 0; } - if (localX + filterArea.width > this.width) { + if (localX + filterArea.width > this.width) + { filterArea.width = this.width - localX; } - if (localY + filterArea.height > this.height) { + if (localY + filterArea.height > this.height) + { filterArea.height = this.height - localY; } - if (filterArea.width < 0) { + if (filterArea.width < 0) + { filterArea.width = 0; } - if (filterArea.height < 0) { + if (filterArea.height < 0) + { filterArea.height = 0; } @@ -154,7 +166,8 @@ * Removes the last filter from the filter stack and doesn't return it. * */ -WebGLFilterManager.prototype.popFilter = function () { +WebGLFilterManager.prototype.popFilter = function () +{ var gl = this.renderer.gl; var filterBlock = this.filterStack.pop(); @@ -163,7 +176,8 @@ var projection = this.renderer.projection; var offset = this.renderer.offset; - if (filterBlock.filterPasses.length > 1) { + if (filterBlock.filterPasses.length > 1) + { gl.viewport(0, 0, filterArea.width, filterArea.height); gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); @@ -193,7 +207,8 @@ var inputTexture = texture; var outputTexture = this.texturePool.pop(); - if (!outputTexture) { + if (!outputTexture) + { outputTexture = new FilterTexture(this.renderer.gl, this.width, this.height); } outputTexture.resize(this.width, this.height); @@ -204,7 +219,8 @@ gl.disable(gl.BLEND); - for (var i = 0; i < filterBlock.filterPasses.length-1; i++) { + for (var i = 0; i < filterBlock.filterPasses.length-1; i++) + { var filterPass = filterBlock.filterPasses[i]; gl.bindFramebuffer(gl.FRAMEBUFFER, outputTexture.frameBuffer ); @@ -243,10 +259,12 @@ var buffer = this.buffer; // time to render the filters texture to the previous scene - if (this.filterStack.length === 0) { + if (this.filterStack.length === 0) + { gl.colorMask(true, true, true, true);//this.transparent); } - else { + else + { var currentFilter = this.filterStack[this.filterStack.length-1]; filterArea = currentFilter._filterArea; @@ -332,13 +350,15 @@ * @param width {number} the horizontal range of the filter * @param height {number} the vertical range of the filter */ -WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) { +WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) +{ // use program var gl = this.renderer.gl; var shader = filter.shaders[gl.id]; - if (!shader) { + if (!shader) + { shader = new Shader(gl); shader.fragmentSrc = filter.fragmentSrc; @@ -356,7 +376,8 @@ gl.uniform2f(shader.projectionVector, width/2, -height/2); gl.uniform2f(shader.offsetVector, 0,0); - if (filter.uniforms.dimensions) { + 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]; @@ -386,7 +407,8 @@ * Initialises the shader buffers. * */ -WebGLFilterManager.prototype.initShaderBuffers = function () { +WebGLFilterManager.prototype.initShaderBuffers = function () +{ var gl = this.renderer.gl; // create some buffers @@ -432,7 +454,8 @@ * Destroys the filter and removes it from the filter stack. * */ -WebGLFilterManager.prototype.destroy = function () { +WebGLFilterManager.prototype.destroy = function () +{ var gl = this.renderer.gl; this.filterStack = null; @@ -441,7 +464,8 @@ this.offsetY = 0; // destroy textures - for (var i = 0; i < this.texturePool.length; i++) { + for (var i = 0; i < this.texturePool.length; i++) + { this.texturePool[i].destroy(); } diff --git a/src/core/renderers/webgl/managers/WebGLManager.js b/src/core/renderers/webgl/managers/WebGLManager.js index 9d47b5c..c30cd51 100644 --- a/src/core/renderers/webgl/managers/WebGLManager.js +++ b/src/core/renderers/webgl/managers/WebGLManager.js @@ -3,7 +3,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLManager(renderer) { +function WebGLManager(renderer) +{ /** * The renderer this manager works for. * @@ -15,6 +16,7 @@ WebGLManager.prototype.constructor = WebGLManager; module.exports = WebGLManager; -WebGLManager.prototype.destroy = function () { +WebGLManager.prototype.destroy = function () +{ this.renderer = null; }; diff --git a/src/core/renderers/webgl/managers/WebGLMaskManager.js b/src/core/renderers/webgl/managers/WebGLMaskManager.js index 2f90b64..e568812 100644 --- a/src/core/renderers/webgl/managers/WebGLMaskManager.js +++ b/src/core/renderers/webgl/managers/WebGLMaskManager.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLMaskManager(renderer) { +function WebGLMaskManager(renderer) +{ WebGLManager.call(this, renderer); } @@ -19,12 +20,15 @@ * * @param maskData {any[]} */ -WebGLMaskManager.prototype.pushMask = function (maskData) { - if (maskData.dirty) { +WebGLMaskManager.prototype.pushMask = function (maskData) +{ + if (maskData.dirty) + { WebGLGraphics.updateGraphics(maskData, this.renderer.gl); } - if (!maskData._webGL[this.renderer.gl.id].data.length) { + if (!maskData._webGL[this.renderer.gl.id].data.length) + { return; } @@ -36,6 +40,7 @@ * * @param maskData {any[]} */ -WebGLMaskManager.prototype.popMask = function (maskData) { +WebGLMaskManager.prototype.popMask = function (maskData) +{ this.renderer.stencilManager.popStencil(maskData, maskData._webGL[this.renderer.gl.id].data[0], this.renderer); }; diff --git a/src/core/renderers/webgl/managers/WebGLShaderManager.js b/src/core/renderers/webgl/managers/WebGLShaderManager.js index fef071c..90c6477 100644 --- a/src/core/renderers/webgl/managers/WebGLShaderManager.js +++ b/src/core/renderers/webgl/managers/WebGLShaderManager.js @@ -10,7 +10,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLShaderManager(renderer) { +function WebGLShaderManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -28,7 +29,8 @@ */ this.tempAttribState = []; - for (var i = 0; i < this.maxAttibs; i++) { + for (var i = 0; i < this.maxAttibs; i++) + { this.attribState[i] = false; } @@ -66,7 +68,8 @@ // listen for context and update necessary shaders var self = this; - this.renderer.on('context', function (event) { + this.renderer.on('context', function (event) + { var gl = event.data; // this shader is used for rendering primitives @@ -97,29 +100,36 @@ * * @param attribs {Array} attribs */ -WebGLShaderManager.prototype.setAttribs = function (attribs) { +WebGLShaderManager.prototype.setAttribs = function (attribs) +{ // reset temp state var i; - for (i = 0; i < this.tempAttribState.length; i++) { + for (i = 0; i < this.tempAttribState.length; i++) + { this.tempAttribState[i] = false; } // set the new attribs - for (var a in attribs) { + for (var a in attribs) + { this.tempAttribState[attribs[a]] = true; } var gl = this.renderer.gl; - for (i = 0; i < this.attribState.length; i++) { - if (this.attribState[i] !== this.tempAttribState[i]) { + for (i = 0; i < this.attribState.length; i++) + { + if (this.attribState[i] !== this.tempAttribState[i]) + { this.attribState[i] = this.tempAttribState[i]; - if (this.attribState[i]) { + if (this.attribState[i]) + { gl.enableVertexAttribArray(i); } - else { + else + { gl.disableVertexAttribArray(i); } } @@ -131,8 +141,10 @@ * * @param shader {Any} */ -WebGLShaderManager.prototype.setShader = function (shader) { - if (this._currentId === shader.uuid) { +WebGLShaderManager.prototype.setShader = function (shader) +{ + if (this._currentId === shader.uuid) + { return false; } @@ -150,7 +162,8 @@ * Destroys this object. * */ -WebGLShaderManager.prototype.destroy = function () { +WebGLShaderManager.prototype.destroy = function () +{ this.attribState = null; this.tempAttribState = null; diff --git a/src/core/renderers/webgl/managers/WebGLStencilManager.js b/src/core/renderers/webgl/managers/WebGLStencilManager.js index 9ec6398..4cb0134 100644 --- a/src/core/renderers/webgl/managers/WebGLStencilManager.js +++ b/src/core/renderers/webgl/managers/WebGLStencilManager.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLStencilManager(renderer) { +function WebGLStencilManager(renderer) +{ WebGLManager.call(this, renderer); this.stencilStack = []; @@ -24,12 +25,14 @@ * @param graphics {Graphics} * @param webGLData {any[]} */ -WebGLStencilManager.prototype.pushStencil = function (graphics, webGLData) { +WebGLStencilManager.prototype.pushStencil = function (graphics, webGLData) +{ var gl = this.renderer.gl; this.bindGraphics(graphics, webGLData, this.renderer); - if (this.stencilStack.length === 0) { + if (this.stencilStack.length === 0) + { gl.enable(gl.STENCIL_TEST); gl.clear(gl.STENCIL_BUFFER_BIT); this.reverse = true; @@ -47,14 +50,17 @@ // draw the triangle strip! - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } @@ -62,31 +68,38 @@ // draw a quad to increment.. gl.drawElements(gl.TRIANGLE_FAN, 4, gl.UNSIGNED_SHORT, ( webGLData.indices.length - 4 ) * 2 ); - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); } this.reverse = !this.reverse; } - else { - if (!this.reverse) { + else + { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } - else { + 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) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); } } @@ -103,7 +116,8 @@ * @param graphics {Graphics} * @param webGLData {Array} */ -WebGLStencilManager.prototype.bindGraphics = function (graphics, webGLData) { +WebGLStencilManager.prototype.bindGraphics = function (graphics, webGLData) +{ //if (this._currentGraphics === graphics)return; this._currentGraphics = graphics; @@ -114,7 +128,8 @@ offset = this.renderer.offset, shader;// = this.renderer.shaderManager.primitiveShader; - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { shader = this.renderer.shaderManager.complexPrimitiveShader; this.renderer.shaderManager.setShader(shader); @@ -141,7 +156,8 @@ // set the index buffer! gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, webGLData.indexBuffer); } - else { + else + { //this.renderer.shaderManager.activatePrimitiveShader(); shader = this.renderer.shaderManager.primitiveShader; this.renderer.shaderManager.setShader( shader ); @@ -154,7 +170,7 @@ gl.uniform2f(shader.uniforms.offsetVector._location, -offset.x, -offset.y); gl.uniform3fv(shader.uniforms.tint._location, utils.hex2rgb(graphics.tint)); - + gl.uniform1f(shader.uniforms.alpha._location, graphics.worldAlpha); @@ -172,19 +188,22 @@ * @param graphics {Graphics} * @param webGLData {Array} */ -WebGLStencilManager.prototype.popStencil = function (graphics, webGLData) { +WebGLStencilManager.prototype.popStencil = function (graphics, webGLData) +{ var gl = this.renderer.gl; this.stencilStack.pop(); this.count--; - if (this.stencilStack.length === 0) { + if (this.stencilStack.length === 0) + { // the stack is empty! gl.disable(gl.STENCIL_TEST); } - else { + else + { var level = this.count; @@ -192,14 +211,17 @@ gl.colorMask(false, false, false, false); - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { this.reverse = !this.reverse; - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } @@ -213,31 +235,38 @@ // draw the triangle strip! gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); - if (!this.reverse) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); } } - else { + else + { // console.log("<<>>") - if (!this.reverse) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } - else { + 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) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); } } @@ -253,7 +282,8 @@ * Destroys the mask stack. * */ -WebGLStencilManager.prototype.destroy = function () { +WebGLStencilManager.prototype.destroy = function () +{ this.renderer = null; this.stencilStack = null; }; diff --git a/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js b/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js index 913ba5e..1ea7d19 100644 --- a/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js +++ b/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function ComplexPrimitiveShader(gl) { +function ComplexPrimitiveShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -24,7 +25,8 @@ 'uniform float flipY;', 'varying vec4 vColor;', - 'void main(void) {', + '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);', @@ -37,7 +39,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = vColor;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/FastShader.js b/src/core/renderers/webgl/shaders/FastShader.js index bd2e29a..2e5e060 100644 --- a/src/core/renderers/webgl/shaders/FastShader.js +++ b/src/core/renderers/webgl/shaders/FastShader.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function FastShader(gl) { +function FastShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -28,7 +29,8 @@ 'const vec2 center = vec2(-1.0, 1.0);', - 'void main(void) {', + 'void main(void) + {', ' vec2 v;', ' vec2 sv = aVertexPosition * aScale;', ' v.x = (sv.x) * cos(aRotation) - (sv.y) * sin(aRotation);', @@ -49,7 +51,8 @@ 'uniform sampler2D uSampler;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/PrimitiveShader.js b/src/core/renderers/webgl/shaders/PrimitiveShader.js index 6f25409..a25f54f 100644 --- a/src/core/renderers/webgl/shaders/PrimitiveShader.js +++ b/src/core/renderers/webgl/shaders/PrimitiveShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function PrimitiveShader(gl) { +function PrimitiveShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -23,7 +24,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + '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);', @@ -36,7 +38,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = vColor;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/Shader.js b/src/core/renderers/webgl/shaders/Shader.js index f8964f5..fd75ef5 100644 --- a/src/core/renderers/webgl/shaders/Shader.js +++ b/src/core/renderers/webgl/shaders/Shader.js @@ -6,7 +6,8 @@ * @param [fragmentSrc] {string} The source of the fragment shader. * @param [vertexSrc] {string} The source of the vertex shader. */ -function Shader(gl, vertexSrc, fragmentSrc, customUniforms, customAttributes) { +function Shader(gl, vertexSrc, fragmentSrc, customUniforms, customAttributes) +{ /** * @member {number} * @readonly @@ -33,7 +34,8 @@ dimensions: { type: '4f', value: new Float32Array(4) } }; - for (var u in customUniforms) { + for (var u in customUniforms) + { this.uniforms[u] = customUniforms[u]; } @@ -43,7 +45,8 @@ aColor: 0 }; - for (var a in customAttributes) { + for (var a in customAttributes) + { this.attributes[a] = customAttributes[a]; } @@ -66,7 +69,8 @@ 'const vec2 center = vec2(-1.0, 1.0);', - 'void main(void) {', + 'void main(void) + {', ' gl_Position = vec4( ((aVertexPosition + offsetVector) / projectionVector) + center , 0.0, 1.0);', ' vTextureCoord = aTextureCoord;', ' vColor = vec4(aColor.rgb * aColor.a, aColor.a);', @@ -85,7 +89,8 @@ 'uniform sampler2D uSampler;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;', '}' ].join('\n'); @@ -96,7 +101,8 @@ Shader.prototype.constructor = Shader; module.exports = Shader; -Shader.prototype.init = function () { +Shader.prototype.init = function () +{ this.compile(); this.gl.useProgram(this.program); @@ -105,14 +111,18 @@ this.cacheAttributeLocations(Object.keys(this.attributes)); }; -Shader.prototype.cacheUniformLocations = function (keys) { - for (var i = 0; i < keys.length; ++i) { +Shader.prototype.cacheUniformLocations = function (keys) +{ + for (var i = 0; i < keys.length; ++i) + { this.uniforms[keys[i]]._location = this.gl.getUniformLocation(this.program, keys[i]); } }; -Shader.prototype.cacheAttributeLocations = function (keys) { - for (var i = 0; i < keys.length; ++i) { +Shader.prototype.cacheAttributeLocations = function (keys) +{ + for (var i = 0; i < keys.length; ++i) + { this.attributes[keys[i]] = this.gl.getAttribLocation(this.program, keys[i]); } @@ -124,14 +134,16 @@ // 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.attributes.aColor === -1) { + // if (this.attributes.aColor === -1) + { // this.attributes.aColor = 2; // } // End worst hack eva // }; -Shader.prototype.compile = function () { +Shader.prototype.compile = function () +{ var gl = this.gl; var glVertShader = this._glCompile(gl.VERTEX_SHADER, this.vertexSrc); @@ -144,13 +156,15 @@ gl.linkProgram(program); // if linking fails, then log and cleanup - if (!gl.getProgramParameter(program, gl.LINK_STATUS)) { + if (!gl.getProgramParameter(program, gl.LINK_STATUS)) + { window.console.error('Pixi.js Error: Could not initialize shader.'); window.console.error('gl.VALIDATE_STATUS', gl.getProgramParameter(program, gl.VALIDATE_STATUS)); window.console.error('gl.getError()', gl.getError()); // if there is a program info log, log it - if (gl.getProgramInfoLog(program) !== '') { + if (gl.getProgramInfoLog(program) !== '') + { window.console.warn('Pixi.js Warning: gl.getProgramInfoLog()', gl.getProgramInfoLog(program)); } @@ -165,18 +179,21 @@ return (this.program = program); }; -Shader.prototype.syncUniforms = function () { +Shader.prototype.syncUniforms = function () +{ var gl = this.gl; this.textureCount = 1; - for (var key in this.uniforms) { + for (var key in this.uniforms) + { var uniform = this.uniforms[key], location = uniform._location, value = uniform.value, i, il; - switch (uniform.type) { + switch (uniform.type) + { // single int value case 'i': case '1i': @@ -282,7 +299,8 @@ // a Color Value case 'c': - if (typeof value === 'number') { + if (typeof value === 'number') + { value = utils.hex2rgb(value); } @@ -311,11 +329,13 @@ // array of 2D Point objects case 'v2v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(2 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 2] = value[i].x; uniform._array[i * 2 + 1] = value[i].y; } @@ -325,11 +345,13 @@ // array of 3D Point objects case 'v3v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(3 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 3] = value[i].x; uniform._array[i * 3 + 1] = value[i].y; uniform._array[i * 3 + 2] = value[i].z; @@ -341,11 +363,13 @@ // array of 4D Point objects case 'v4v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(4 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 4] = value[i].x; uniform._array[i * 4 + 1] = value[i].y; uniform._array[i * 4 + 2] = value[i].z; @@ -359,7 +383,8 @@ // PIXI.Texture case 't': case 'sampler2D': - if (!uniform.value || !uniform.value.baseTexture || !uniform.value.baseTexture.hasLoaded) { + if (!uniform.value || !uniform.value.baseTexture || !uniform.value.baseTexture.hasLoaded) + { break; } @@ -376,7 +401,8 @@ this.textureCount++; // initialize the texture if we haven't yet - if (!uniform._init) { + if (!uniform._init) + { this.initSampler2D(uniform); uniform._init = true; @@ -394,11 +420,13 @@ * Initialises a Sampler2D uniform (which may only be available later on after initUniforms once the texture has loaded) * */ -Shader.prototype.initSampler2D = function (uniform) { +Shader.prototype.initSampler2D = function (uniform) +{ var gl = this.gl; // Extended texture data - if (uniform.textureData) { + if (uniform.textureData) + { var data = uniform.textureData; // GLTexture = mag linear, min linear_mipmap_linear, wrap repeat + gl.generateMipmap(gl.TEXTURE_2D); @@ -417,14 +445,16 @@ var wrapT = (data.wrapT) ? data.wrapT : gl.CLAMP_TO_EDGE; var format = (data.luminance) ? gl.LUMINANCE : gl.RGBA; - if (data.repeat) { + if (data.repeat) + { wrapS = gl.REPEAT; wrapT = gl.REPEAT; } gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, !!data.flipY); - if (data.width) { + if (data.width) + { var width = (data.width) ? data.width : 512; var height = (data.height) ? data.height : 2; var border = (data.border) ? data.border : 0; @@ -432,7 +462,8 @@ // 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 { + 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); } @@ -448,7 +479,8 @@ * Destroys the shader. * */ -Shader.prototype.destroy = function () { +Shader.prototype.destroy = function () +{ this.gl.deleteProgram(this.program); this.gl = null; @@ -459,13 +491,15 @@ this.fragmentSrc = null; }; -Shader.prototype._glCompile = function (type, src) { +Shader.prototype._glCompile = function (type, src) +{ var shader = this.gl.createShader(type); this.gl.shaderSource(shader, src); this.gl.compileShader(shader); - if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) { + if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) + { window.console.log(this.gl.getShaderInfoLog(shader)); return null; } diff --git a/src/core/renderers/webgl/shaders/StripShader.js b/src/core/renderers/webgl/shaders/StripShader.js index 193f6e1..a7abcc6 100644 --- a/src/core/renderers/webgl/shaders/StripShader.js +++ b/src/core/renderers/webgl/shaders/StripShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function StripShader(gl) { +function StripShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -20,7 +21,8 @@ 'varying vec2 vTextureCoord;', - 'void main(void) {', + '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);', @@ -36,7 +38,8 @@ 'varying vec2 vTextureCoord;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vec2(vTextureCoord.x, vTextureCoord.y)) * alpha;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/utils/FilterTexture.js b/src/core/renderers/webgl/utils/FilterTexture.js index d2c8423..4433d44 100644 --- a/src/core/renderers/webgl/utils/FilterTexture.js +++ b/src/core/renderers/webgl/utils/FilterTexture.js @@ -8,7 +8,8 @@ * @param height {number} the vertical range of the filter * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values */ -function FilterTexture(gl, width, height, scaleMode) { +function FilterTexture(gl, width, height, scaleMode) +{ /** * @member {WebGLContext} */ @@ -59,7 +60,8 @@ * Clears the filter texture. * */ -FilterTexture.prototype.clear = function () { +FilterTexture.prototype.clear = function () +{ var gl = this.gl; gl.clearColor(0,0,0, 0); @@ -72,8 +74,10 @@ * @param width {number} the new width of the texture * @param height {number} the new height of the texture */ -FilterTexture.prototype.resize = function (width, height) { - if (this.width === width && this.height === height) { +FilterTexture.prototype.resize = function (width, height) +{ + if (this.width === width && this.height === height) + { return; } @@ -96,7 +100,8 @@ * Destroys the filter texture. * */ -FilterTexture.prototype.destroy = function () { +FilterTexture.prototype.destroy = function () +{ var gl = this.gl; gl.deleteFramebuffer( this.frameBuffer ); gl.deleteTexture( this.texture ); diff --git a/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js b/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js index c4721e9..a63f4d7 100644 --- a/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js +++ b/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js @@ -14,7 +14,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this sprite batch works for. */ -function WebGLFastSpriteBatch(renderer) { +function WebGLFastSpriteBatch(renderer) +{ /** * The renderer instance this sprite batch operates on. * @@ -91,7 +92,8 @@ */ this.lastIndexCount = 0; - for (var i=0, j=0; i < numIndices; i += 6, j += 4) { + 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; @@ -144,7 +146,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.setupContext(); }); } @@ -157,7 +160,8 @@ * * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLFastSpriteBatch.prototype.setupContext = function () { +WebGLFastSpriteBatch.prototype.setupContext = function () +{ var gl = this.renderer.gl; // create a couple of buffers @@ -177,7 +181,8 @@ /** * @param spriteBatch {SpriteBatch} The SpriteBatch container to prepare for. */ -WebGLFastSpriteBatch.prototype.begin = function (spriteBatch) { +WebGLFastSpriteBatch.prototype.begin = function (spriteBatch) +{ this.shader = this.renderer.shaderManager.fastShader; this.matrix = spriteBatch.worldTransform.toArray(true); @@ -187,33 +192,38 @@ /** */ -WebGLFastSpriteBatch.prototype.end = function () { +WebGLFastSpriteBatch.prototype.end = function () +{ this.flush(); }; /** * @param spriteBatch {SpriteBatch} The SpriteBatch container to render. */ -WebGLFastSpriteBatch.prototype.render = function (spriteBatch) { +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) { + if (!sprite.texture._uvs) + { return; } this.currentBaseTexture = sprite.texture.baseTexture; // check blend mode - if (sprite.blendMode !== this.renderer.blendModeManager.currentBlendMode) { + if (sprite.blendMode !== this.renderer.blendModeManager.currentBlendMode) + { this.flush(); this.renderer.blendModeManager.setBlendMode(sprite.blendMode); } - for (var i=0,j= children.length; i= this.size) { + if (this.currentBatchSize >= this.size) + { this.flush(); } }; @@ -362,29 +379,35 @@ /** * */ -WebGLFastSpriteBatch.prototype.flush = function () { +WebGLFastSpriteBatch.prototype.flush = function () +{ // If the batch is length 0 then return as there is nothing to draw - if (this.currentBatchSize === 0) { + if (this.currentBatchSize === 0) + { return; } var gl = this.renderer.gl; // bind the current texture - if (!this.currentBaseTexture._glTextures[gl.id]) { + if (!this.currentBaseTexture._glTextures[gl.id]) + { this.renderer.updateTexture(this.currentBaseTexture, gl); } //TODO-SHOUD THIS BE ELSE??!?!?! - else { + else + { gl.bindTexture(gl.TEXTURE_2D, this.currentBaseTexture._glTextures[gl.id]); } // upload the verts to the buffer - if (this.currentBatchSize > ( this.size * 0.5 ) ) { + if (this.currentBatchSize > ( this.size * 0.5 ) ) + { gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); } - else { + else + { var view = this.vertices.subarray(0, this.currentBatchSize * this.vertByteSize); gl.bufferSubData(gl.ARRAY_BUFFER, 0, view); @@ -405,14 +428,16 @@ * Ends the batch and flushes * */ -WebGLFastSpriteBatch.prototype.stop = function () { +WebGLFastSpriteBatch.prototype.stop = function () +{ this.flush(); }; /** * */ -WebGLFastSpriteBatch.prototype.start = function () { +WebGLFastSpriteBatch.prototype.start = function () +{ var gl = this.renderer.gl; // bind the main texture diff --git a/src/core/renderers/webgl/utils/WebGLGraphics.js b/src/core/renderers/webgl/utils/WebGLGraphics.js index 55f4911..ab8f46e 100644 --- a/src/core/renderers/webgl/utils/WebGLGraphics.js +++ b/src/core/renderers/webgl/utils/WebGLGraphics.js @@ -19,7 +19,8 @@ * @param graphics {Graphics} * @param renderer {WebGLRenderer} */ -WebGLGraphics.renderGraphics = function (graphics, renderer) {//projection, offset) { +WebGLGraphics.renderGraphics = function (graphics, renderer) {//projection, offset) +{ var gl = renderer.gl; var projection = renderer.projection, @@ -27,7 +28,8 @@ shader = renderer.shaderManager.primitiveShader, webGLData; - if (graphics.dirty) { + if (graphics.dirty) + { WebGLGraphics.updateGraphics(graphics, gl); } @@ -35,8 +37,10 @@ // This could be speeded up for sure! - for (var i = 0; i < webGL.data.length; i++) { - if (webGL.data[i].mode === 1) { + for (var i = 0; i < webGL.data.length; i++) + { + if (webGL.data[i].mode === 1) + { webGLData = webGL.data[i]; renderer.stencilManager.pushStencil(graphics, webGLData, renderer); @@ -46,7 +50,8 @@ renderer.stencilManager.popStencil(graphics, webGLData, renderer); } - else { + else + { webGLData = webGL.data[i]; @@ -84,12 +89,14 @@ * @param graphicsData {Graphics} The graphics object to update * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLGraphics.updateGraphics = function (graphics, gl) { +WebGLGraphics.updateGraphics = function (graphics, gl) +{ // get the contexts graphics object var webGL = graphics._webGL[gl.id]; // if the graphics object does not exist in the webGL context time to create it! - if (!webGL) { + if (!webGL) + { webGL = graphics._webGL[gl.id] = {lastIndex:0, data:[], gl:gl}; } @@ -99,11 +106,13 @@ var i; // if the user cleared the graphics object we will need to clear every object - if (graphics.clearDirty) { + if (graphics.clearDirty) + { graphics.clearDirty = false; // lop through and return all the webGLDatas to the object pool so than can be reused later on - for (i = 0; i < webGL.data.length; i++) { + for (i = 0; i < webGL.data.length; i++) + { var graphicsData = webGL.data[i]; graphicsData.reset(); WebGLGraphics.graphicsDataPool.push( graphicsData ); @@ -119,58 +128,72 @@ // loop through the graphics datas and construct each one.. // if the object is a complex fill then the new stencil buffer technique will be used // other wise graphics objects will be pushed into a batch.. - for (i = webGL.lastIndex; i < graphics.graphicsData.length; i++) { + for (i = webGL.lastIndex; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { // need to add the points the the graphics object.. data.points = data.shape.points.slice(); - if (data.shape.closed) { + if (data.shape.closed) + { // close the poly if the value is true! - if (data.points[0] !== data.points[data.points.length-2] || data.points[1] !== data.points[data.points.length-1]) { + if (data.points[0] !== data.points[data.points.length-2] || data.points[1] !== data.points[data.points.length-1]) + { data.points.push(data.points[0], data.points[1]); } } // MAKE SURE WE HAVE THE CORRECT TYPE.. - if (data.fill) { - if (data.points.length >= 6) { - if (data.points.length < 6 * 2) { + if (data.fill) + { + if (data.points.length >= 6) + { + if (data.points.length < 6 * 2) + { webGLData = WebGLGraphics.switchMode(webGL, 0); var canDrawUsingSimple = WebGLGraphics.buildPoly(data, webGLData); // console.log(canDrawUsingSimple); - if (!canDrawUsingSimple) { + if (!canDrawUsingSimple) + { // console.log("<>>>") webGLData = WebGLGraphics.switchMode(webGL, 1); WebGLGraphics.buildComplexPoly(data, webGLData); } } - else { + else + { webGLData = WebGLGraphics.switchMode(webGL, 1); WebGLGraphics.buildComplexPoly(data, webGLData); } } } - if (data.lineWidth > 0) { + if (data.lineWidth > 0) + { webGLData = WebGLGraphics.switchMode(webGL, 0); WebGLGraphics.buildLine(data, webGLData); } } - else { + else + { webGLData = WebGLGraphics.switchMode(webGL, 0); - if (data.type === CONST.SHAPES.RECT) { + if (data.type === CONST.SHAPES.RECT) + { WebGLGraphics.buildRectangle(data, webGLData); } - else if (data.type === CONST.SHAPES.CIRC || data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.CIRC || data.type === CONST.SHAPES.ELIP) + { WebGLGraphics.buildCircle(data, webGLData); } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { WebGLGraphics.buildRoundedRectangle(data, webGLData); } } @@ -179,10 +202,12 @@ } // upload all the dirty data... - for (i = 0; i < webGL.data.length; i++) { + for (i = 0; i < webGL.data.length; i++) + { webGLData = webGL.data[i]; - if (webGLData.dirty) { + if (webGLData.dirty) + { webGLData.upload(); } } @@ -194,18 +219,22 @@ * @param webGL {WebGLContext} * @param type {number} */ -WebGLGraphics.switchMode = function (webGL, type) { +WebGLGraphics.switchMode = function (webGL, type) +{ var webGLData; - if (!webGL.data.length) { + if (!webGL.data.length) + { webGLData = WebGLGraphics.graphicsDataPool.pop() || new WebGLGraphicsData(webGL.gl); webGLData.mode = type; webGL.data.push(webGLData); } - else { + else + { webGLData = webGL.data[webGL.data.length-1]; - if (webGLData.mode !== type || type === 1) { + if (webGLData.mode !== type || type === 1) + { webGLData = WebGLGraphics.graphicsDataPool.pop() || new WebGLGraphicsData(webGL.gl); webGLData.mode = type; webGL.data.push(webGLData); @@ -225,7 +254,8 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildRectangle = function (graphicsData, webGLData) { +WebGLGraphics.buildRectangle = function (graphicsData, webGLData) +{ // --- // // need to convert points to a nice regular data // @@ -235,7 +265,8 @@ var width = rectData.width; var height = rectData.height; - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -265,7 +296,8 @@ indices.push(vertPos, vertPos, vertPos+1, vertPos+2, vertPos+3, vertPos+3); } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = [x, y, @@ -289,7 +321,8 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildRoundedRectangle = function (graphicsData, webGLData) { +WebGLGraphics.buildRoundedRectangle = function (graphicsData, webGLData) +{ var rrectData = graphicsData.shape; var x = rrectData.x; var y = rrectData.y; @@ -305,7 +338,8 @@ recPoints = recPoints.concat(WebGLGraphics.quadraticBezierCurve(x + width, y + radius, x + width, y, x + width - radius, y)); recPoints = recPoints.concat(WebGLGraphics.quadraticBezierCurve(x + radius, y, x, y, x, y + radius)); - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -323,7 +357,8 @@ // var i = 0; - for (i = 0; i < triangles.length; i+=3) { + for (i = 0; i < triangles.length; i+=3) + { indices.push(triangles[i] + vecPos); indices.push(triangles[i] + vecPos); indices.push(triangles[i+1] + vecPos); @@ -332,12 +367,14 @@ } - for (i = 0; i < recPoints.length; i++) { + for (i = 0; i < recPoints.length; i++) + { verts.push(recPoints[i], recPoints[++i], r, g, b, alpha); } } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = recPoints; @@ -362,7 +399,8 @@ * @param toY {number} Destination point y * @return {number[]} */ -WebGLGraphics.quadraticBezierCurve = function (fromX, fromY, cpX, cpY, toX, toY) { +WebGLGraphics.quadraticBezierCurve = function (fromX, fromY, cpX, cpY, toX, toY) +{ var xa, ya, @@ -373,14 +411,16 @@ n = 20, points = []; - function getPt(n1 , n2, perc) { + function getPt(n1 , n2, perc) + { var diff = n2 - n1; return n1 + ( diff * perc ); } var j = 0; - for (var i = 0; i <= n; i++ ) { + for (var i = 0; i <= n; i++ ) + { j = i / n; // The Green Line @@ -406,7 +446,8 @@ * @param graphicsData {Graphics} The graphics object to draw * @param webGLData {object} */ -WebGLGraphics.buildCircle = function (graphicsData, webGLData) { +WebGLGraphics.buildCircle = function (graphicsData, webGLData) +{ // need to convert points to a nice regular data var circleData = graphicsData.shape; var x = circleData.x; @@ -415,11 +456,13 @@ var height; // TODO - bit hacky?? - if (graphicsData.type === CONST.SHAPES.CIRC) { + if (graphicsData.type === CONST.SHAPES.CIRC) + { width = circleData.radius; height = circleData.radius; } - else { + else + { width = circleData.width; height = circleData.height; } @@ -429,7 +472,8 @@ var i = 0; - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -444,7 +488,8 @@ indices.push(vecPos); - for (i = 0; i < totalSegs + 1 ; i++) { + for (i = 0; i < totalSegs + 1 ; i++) + { verts.push(x,y, r, g, b, alpha); verts.push(x + Math.sin(seg * i) * width, @@ -457,12 +502,14 @@ indices.push(vecPos-1); } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = []; - for (i = 0; i < totalSegs + 1; i++) { + for (i = 0; i < totalSegs + 1; i++) + { graphicsData.points.push(x + Math.sin(seg * i) * width, y + Math.cos(seg * i) * height); } @@ -481,18 +528,22 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildLine = function (graphicsData, webGLData) { +WebGLGraphics.buildLine = function (graphicsData, webGLData) +{ // TODO OPTIMISE! var i = 0; var points = graphicsData.points; - if (points.length === 0) { + if (points.length === 0) + { return; } // if the line width is an odd number add 0.5 to align to a whole pixel - if (graphicsData.lineWidth%2) { - for (i = 0; i < points.length; i++) { + if (graphicsData.lineWidth%2) + { + for (i = 0; i < points.length; i++) + { points[i] += 0.5; } } @@ -502,7 +553,8 @@ var lastPoint = new math.Point(points[points.length - 2], points[points.length - 1]); // if the first point is the last point - gonna have issues :) - if (firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) { + if (firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) + { // need to clone as we are going to slightly modify the shape.. points = points.slice(); @@ -562,7 +614,8 @@ verts.push(p1x + perpx , p1y + perpy, r, g, b, alpha); - for (i = 1; i < length-1; i++) { + for (i = 1; i < length-1; i++) + { p1x = points[(i-1)*2]; p1y = points[(i-1)*2 + 1]; @@ -599,7 +652,8 @@ denom = a1*b2 - a2*b1; - if (Math.abs(denom) < 0.1 ) { + if (Math.abs(denom) < 0.1 ) + { denom+=10.1; verts.push(p2x - perpx , p2y - perpy, @@ -618,7 +672,8 @@ pdist = (px -p2x) * (px -p2x) + (py -p2y) + (py -p2y); - if (pdist > 140 * 140) { + if (pdist > 140 * 140) + { perp3x = perpx - perp2x; perp3y = perpy - perp2y; @@ -639,7 +694,8 @@ indexCount++; } - else { + else + { verts.push(px , py); verts.push(r, g, b, alpha); @@ -672,7 +728,8 @@ indices.push(indexStart); - for (i = 0; i < indexCount; i++) { + for (i = 0; i < indexCount; i++) + { indices.push(indexStart++); } @@ -687,11 +744,13 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildComplexPoly = function (graphicsData, webGLData) { +WebGLGraphics.buildComplexPoly = function (graphicsData, webGLData) +{ //TODO - no need to copy this as it gets turned into a FLoat32Array anyways.. var points = graphicsData.points.slice(); - if (points.length < 6) { + if (points.length < 6) + { return; } @@ -711,7 +770,8 @@ var x,y; // get size.. - for (var i = 0; i < points.length; i+=2) { + for (var i = 0; i < points.length; i+=2) + { x = points[i]; y = points[i+1]; @@ -732,7 +792,8 @@ //TODO - this aint needed! var length = points.length / 2; - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { indices.push( i ); } @@ -746,10 +807,12 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildPoly = function (graphicsData, webGLData) { +WebGLGraphics.buildPoly = function (graphicsData, webGLData) +{ var points = graphicsData.points; - if (points.length < 6) { + if (points.length < 6) + { return; } // get first and last point.. figure out the middle! @@ -767,7 +830,8 @@ var triangles = utils.PolyK.Triangulate(points); - if (!triangles) { + if (!triangles) + { return false; } @@ -775,7 +839,8 @@ var i = 0; - for (i = 0; i < triangles.length; i+=3) { + for (i = 0; i < triangles.length; i+=3) + { indices.push(triangles[i] + vertPos); indices.push(triangles[i] + vertPos); indices.push(triangles[i+1] + vertPos); @@ -783,7 +848,8 @@ indices.push(triangles[i+2] + vertPos); } - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { verts.push(points[i * 2], points[i * 2 + 1], r, g, b, alpha); } diff --git a/src/core/renderers/webgl/utils/WebGLGraphicsData.js b/src/core/renderers/webgl/utils/WebGLGraphicsData.js index c56d05e..c739ba7 100644 --- a/src/core/renderers/webgl/utils/WebGLGraphicsData.js +++ b/src/core/renderers/webgl/utils/WebGLGraphicsData.js @@ -2,7 +2,8 @@ * @class * @private */ -function WebGLGraphicsData(gl) { +function WebGLGraphicsData(gl) +{ this.gl = gl; //TODO does this need to be split before uploding?? @@ -22,7 +23,8 @@ /** * */ -WebGLGraphicsData.prototype.reset = function () { +WebGLGraphicsData.prototype.reset = function () +{ this.points.length = 0; this.indices.length = 0; }; @@ -30,7 +32,8 @@ /** * */ -WebGLGraphicsData.prototype.upload = function () { +WebGLGraphicsData.prototype.upload = function () +{ var gl = this.gl; // this.lastIndex = graphics.graphicsData.length; diff --git a/src/core/renderers/webgl/utils/WebGLSpriteBatch.js b/src/core/renderers/webgl/utils/WebGLSpriteBatch.js index 96eaa52..55befbb 100644 --- a/src/core/renderers/webgl/utils/WebGLSpriteBatch.js +++ b/src/core/renderers/webgl/utils/WebGLSpriteBatch.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this sprite batch works for. */ -function WebGLSpriteBatch(renderer) { +function WebGLSpriteBatch(renderer) +{ /** * * @@ -88,7 +89,8 @@ */ this.lastIndexCount = 0; - for (var i=0, j=0; i < numIndices; i += 6, j += 4) { + 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; @@ -162,7 +164,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.setupContext(); }); } @@ -173,7 +176,8 @@ /** * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLSpriteBatch.prototype.setupContext = function () { +WebGLSpriteBatch.prototype.setupContext = function () +{ var gl = this.renderer.gl; // setup default shader @@ -198,7 +202,8 @@ /** * */ -WebGLSpriteBatch.prototype.begin = function () { +WebGLSpriteBatch.prototype.begin = function () +{ // this.shader = this.renderer.shaderManager.defaultShader; this.start(); @@ -206,19 +211,22 @@ /** */ -WebGLSpriteBatch.prototype.end = function () { +WebGLSpriteBatch.prototype.end = function () +{ this.flush(); }; /** * @param sprite {Sprite} the sprite to render when using this spritebatch */ -WebGLSpriteBatch.prototype.render = function (sprite) { +WebGLSpriteBatch.prototype.render = function (sprite) +{ var texture = sprite.texture; //TODO set blend modes.. // check texture.. - if (this.currentBatchSize >= this.size) { + if (this.currentBatchSize >= this.size) + { this.flush(); this.currentBaseTexture = texture.baseTexture; } @@ -227,7 +235,8 @@ var uvs = texture._uvs; // if the uvs have not updated then no point rendering just yet! - if (!uvs) { + if (!uvs) + { return; } @@ -237,7 +246,8 @@ var w0, w1, h0, h1; - if (texture.trim) { + 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; @@ -248,7 +258,8 @@ h0 = h1 + texture.crop.height; } - else { + else + { w0 = (texture.frame.width ) * (1-aX); w1 = (texture.frame.width ) * -aX; @@ -272,7 +283,8 @@ var colors = this.colors; var positions = this.positions; - if (this.renderer.roundPixels) { + if (this.renderer.roundPixels) + { // xy positions[index] = a * w1 + c * h1 + tx | 0; positions[index+1] = d * h1 + b * w1 + ty | 0; @@ -289,7 +301,8 @@ positions[index+15] = a * w1 + c * h0 + tx | 0; positions[index+16] = d * h0 + b * w1 + ty | 0; } - else { + else + { // xy positions[index] = a * w1 + c * h1 + tx; positions[index+1] = d * h1 + b * w1 + ty; @@ -338,11 +351,13 @@ * * @param sprite {TilingSprite} the tilingSprite to render */ -WebGLSpriteBatch.prototype.renderTilingSprite = function (tilingSprite) { +WebGLSpriteBatch.prototype.renderTilingSprite = function (tilingSprite) +{ var texture = tilingSprite.tilingTexture; // check texture.. - if (this.currentBatchSize >= this.size) { + if (this.currentBatchSize >= this.size) + { //return; this.flush(); this.currentBaseTexture = texture.baseTexture; @@ -351,7 +366,8 @@ // set the textures uvs temporarily // TODO create a separate texture so that we can tile part of a texture - if (!tilingSprite._uvs) { + if (!tilingSprite._uvs) + { tilingSprite._uvs = new TextureUvs(); } @@ -454,16 +470,19 @@ * Renders the content and empties the current batch. * */ -WebGLSpriteBatch.prototype.flush = function () { +WebGLSpriteBatch.prototype.flush = function () +{ // If the batch is length 0 then return as there is nothing to draw - if (this.currentBatchSize === 0) { + if (this.currentBatchSize === 0) + { return; } var gl = this.renderer.gl; var shader; - if (this.dirty) { + if (this.dirty) + { this.dirty = false; // bind the main texture gl.activeTexture(gl.TEXTURE0); @@ -482,10 +501,12 @@ } // upload the verts to the buffer - if (this.currentBatchSize > ( this.size * 0.5 ) ) { + if (this.currentBatchSize > ( this.size * 0.5 ) ) + { gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); } - else { + else + { var view = this.positions.subarray(0, this.currentBatchSize * this.vertByteSize); gl.bufferSubData(gl.ARRAY_BUFFER, 0, view); } @@ -502,7 +523,8 @@ var shaderSwap = false; var sprite; - for (var i = 0, j = this.currentBatchSize; i < j; i++) { + for (var i = 0, j = this.currentBatchSize; i < j; i++) + { sprite = this.sprites[i]; @@ -513,24 +535,28 @@ blendSwap = currentBlendMode !== nextBlendMode; shaderSwap = currentShader !== nextShader; // should I use uuidS??? - if (currentBaseTexture !== nextTexture || blendSwap || shaderSwap) { + if (currentBaseTexture !== nextTexture || blendSwap || shaderSwap) + { this.renderBatch(currentBaseTexture, batchSize, start); start = i; batchSize = 0; currentBaseTexture = nextTexture; - if (blendSwap) { + if (blendSwap) + { currentBlendMode = nextBlendMode; this.renderer.blendModeManager.setBlendMode( currentBlendMode ); } - if (shaderSwap) { + if (shaderSwap) + { currentShader = nextShader; shader = currentShader.shaders ? currentShader.shaders[gl.id] : currentShader; - if (!shader) { + if (!shader) + { shader = new Shader(gl, null, currentShader.fragmentSrc, currentShader.uniforms); currentShader.shaders[gl.id] = shader; } @@ -538,7 +564,8 @@ // set shader function??? this.renderer.shaderManager.setShader(shader); - if (shader.dirty) { + if (shader.dirty) + { shader.syncUniforms(); } @@ -569,17 +596,21 @@ * @param size {number} * @param startIndex {number} */ -WebGLSpriteBatch.prototype.renderBatch = function (texture, size, startIndex) { - if (size === 0) { +WebGLSpriteBatch.prototype.renderBatch = function (texture, size, startIndex) +{ + if (size === 0) + { return; } var gl = this.renderer.gl; - if (!texture._glTextures[gl.id]) { + if (!texture._glTextures[gl.id]) + { this.renderer.updateTexture(texture); } - else { + else + { // bind the current texture gl.bindTexture(gl.TEXTURE_2D, texture._glTextures[gl.id]); } @@ -594,7 +625,8 @@ /** * */ -WebGLSpriteBatch.prototype.stop = function () { +WebGLSpriteBatch.prototype.stop = function () +{ this.flush(); this.dirty = true; }; @@ -602,7 +634,8 @@ /** * */ -WebGLSpriteBatch.prototype.start = function () { +WebGLSpriteBatch.prototype.start = function () +{ this.dirty = true; }; @@ -610,7 +643,8 @@ * Destroys the SpriteBatch. * */ -WebGLSpriteBatch.prototype.destroy = function () { +WebGLSpriteBatch.prototype.destroy = function () +{ this.renderer.gl.deleteBuffer(this.vertexBuffer); this.renderer.gl.deleteBuffer(this.indexBuffer); diff --git a/src/core/textures/BaseTexture.js b/src/core/textures/BaseTexture.js index 2bf77d4..513d358 100644 --- a/src/core/textures/BaseTexture.js +++ b/src/core/textures/BaseTexture.js @@ -10,7 +10,8 @@ * @param source {Image|Canvas} the source object of the texture. * @param [scaleMode=scaleModes.DEFAULT] {number} See {@link scaleModes} for possible values */ -function BaseTexture(source, scaleMode) { +function BaseTexture(source, scaleMode) +{ this.uuid = utils.uuid(); /** @@ -123,7 +124,8 @@ this._needsUpdate = false; // if no source passed don't try to load - if (source) { + if (source) + { this.loadSource(source); } @@ -149,13 +151,16 @@ Object.defineProperties(BaseTexture.prototype, { needsUpdate: { - get: function () { + get: function () + { return this._needsUpdate; }, - set: function (val) { + set: function (val) + { this._needsUpdate = val; - if (val) { + if (val) + { this.emit('update', this); } } @@ -171,9 +176,11 @@ * * The logic state after calling `loadSource` directly or indirectly (eg. `fromImage`, `new BaseTexture`) is: * - * if (texture.hasLoaded) { + * if (texture.hasLoaded) + { * // texture ready for use - * } else if (texture.isLoading) { + * } else if (texture.isLoading) + { * // listen to 'loaded' and/or 'error' events on texture * } else { * // not loading, not going to load UNLESS the source is reloaded @@ -183,12 +190,14 @@ * @protected * @param source {Image|Canvas} the source object of the texture. */ -BaseTexture.prototype.loadSource = function (source) { +BaseTexture.prototype.loadSource = function (source) +{ var wasLoading = this.isLoading; this.hasLoaded = false; this.isLoading = false; - if (wasLoading && this.source) { + if (wasLoading && this.source) + { this.source.onload = null; this.source.onerror = null; } @@ -196,20 +205,24 @@ this.source = source; // Apply source if loaded. Otherwise setup appropriate loading monitors. - if ((this.source.complete || this.source.getContext) && this.source.width && this.source.height) { + if ((this.source.complete || this.source.getContext) && this.source.width && this.source.height) + { this._sourceLoaded(); } - else if(!source.getContext) { + else if(!source.getContext) + { // Image fail / not ready this.isLoading = true; var scope = this; - source.onload = function () { + source.onload = function () + { source.onload = null; source.onerror = null; - if(!scope.isLoading) { + if(!scope.isLoading) + { return; } @@ -219,11 +232,13 @@ scope.emit('loaded', scope); }; - source.onerror = function () { + source.onerror = function () + { source.onload = null; source.onerror = null; - if(!scope.isLoading) { + if(!scope.isLoading) + { return; } @@ -234,24 +249,29 @@ // Per http://www.w3.org/TR/html5/embedded-content-0.html#the-img-element // "The value of `complete` can thus change while a script is executing." // So complete needs to be re-checked after the callbacks have been added.. - if (source.complete) { + if (source.complete) + { this.isLoading = false; // ..and if we're complete now, no need for callbacks source.onload = null; source.onerror = null; - if (source.width && source.height) { + if (source.width && source.height) + { this._sourceLoaded(); // If any previous subscribers possible - if (wasLoading) { + if (wasLoading) + { this.emit('loaded', this); } } - else { + else + { // If any previous subscribers possible - if (wasLoading) { + if (wasLoading) + { this.emit('error', this); } } @@ -265,7 +285,8 @@ * * @private */ -BaseTexture.prototype._sourceLoaded = function () { +BaseTexture.prototype._sourceLoaded = function () +{ this.hasLoaded = true; this.width = this.source.naturalWidth || this.source.width; @@ -278,16 +299,20 @@ * Destroys this base texture * */ -BaseTexture.prototype.destroy = function () { - if (this.imageUrl) { +BaseTexture.prototype.destroy = function () +{ + if (this.imageUrl) + { delete utils.BaseTextureCache[this.imageUrl]; delete utils.TextureCache[this.imageUrl]; this.imageUrl = null; - if (!navigator.isCocoonJS) { + if (!navigator.isCocoonJS) + { this.source.src = ''; } } - else if (this.source && this.source._pixiId) { + else if (this.source && this.source._pixiId) + { delete utils.BaseTextureCache[this.source._pixiId]; } this.source = null; @@ -301,7 +326,8 @@ * memory again. * */ -BaseTexture.prototype.dispose = function () { +BaseTexture.prototype.dispose = function () +{ this.emit('dispose', this); }; @@ -311,7 +337,8 @@ * * @param newSrc {string} the path of the image */ -BaseTexture.prototype.updateSourceImage = function (newSrc) { +BaseTexture.prototype.updateSourceImage = function (newSrc) +{ this.source.src = newSrc; this.loadSource(this.source); }; @@ -326,18 +353,22 @@ * @param [scaleMode=scaleModes.DEFAULT] {number} See {@link scaleModes} for possible values * @return BaseTexture */ -BaseTexture.fromImage = function (imageUrl, crossorigin, scaleMode) { +BaseTexture.fromImage = function (imageUrl, crossorigin, scaleMode) +{ var baseTexture = utils.BaseTextureCache[imageUrl]; - if (crossorigin === undefined && imageUrl.indexOf('data:') !== 0) { + if (crossorigin === undefined && imageUrl.indexOf('data:') !== 0) + { crossorigin = true; } - if (!baseTexture) { + if (!baseTexture) + { // new Image() breaks tex loading in some versions of Chrome. // See https://code.google.com/p/chromium/issues/detail?id=238071 var image = new Image();//document.createElement('img'); - if (crossorigin) { + if (crossorigin) + { image.crossOrigin = ''; } @@ -347,7 +378,8 @@ utils.BaseTextureCache[imageUrl] = baseTexture; // if there is an @2x at the end of the url we are going to assume its a highres image - if ( imageUrl.indexOf(CONST.RETINA_PREFIX + '.') !== -1) { + if ( imageUrl.indexOf(CONST.RETINA_PREFIX + '.') !== -1) + { baseTexture.resolution = 2; } } @@ -363,14 +395,17 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return BaseTexture */ -BaseTexture.fromCanvas = function (canvas, scaleMode) { - if (!canvas._pixiId) { +BaseTexture.fromCanvas = function (canvas, scaleMode) +{ + if (!canvas._pixiId) + { canvas._pixiId = 'canvas_' + utils.uuid(); } var baseTexture = utils.BaseTextureCache[canvas._pixiId]; - if (!baseTexture) { + if (!baseTexture) + { baseTexture = new BaseTexture(canvas, scaleMode); utils.BaseTextureCache[canvas._pixiId] = baseTexture; } diff --git a/src/core/textures/RenderTexture.js b/src/core/textures/RenderTexture.js index 6dad20f..53ae796 100644 --- a/src/core/textures/RenderTexture.js +++ b/src/core/textures/RenderTexture.js @@ -46,8 +46,10 @@ * @param [scaleMode] {number} See {@link scaleModes} for possible values * @param [resolution=1] {number} The resolution of the texture being generated */ -function RenderTexture(renderer, width, height, scaleMode, resolution) { - if (!renderer) { +function RenderTexture(renderer, width, height, scaleMode, resolution) +{ + if (!renderer) + { throw new Error('Unable to create RenderTexture, you must pass a renderer into the constructor.'); } @@ -133,7 +135,8 @@ */ this.renderer = renderer; - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { var gl = this.renderer.gl; this.textureBuffer = new FilterTexture(gl, this.width * this.resolution, this.height * this.resolution, this.baseTexture.scaleMode); @@ -142,7 +145,8 @@ this.render = this.renderWebGL; this.projection = new math.Point(this.width*0.5, -this.height*0.5); } - else { + else + { this.render = this.renderCanvas; this.textureBuffer = new CanvasBuffer(this.width* this.resolution, this.height* this.resolution); this.baseTexture.source = this.textureBuffer.canvas; @@ -167,8 +171,10 @@ * @param height {number} The height to resize to. * @param updateBase {boolean} Should the baseTexture.width and height values be resized as well? */ -RenderTexture.prototype.resize = function (width, height, updateBase) { - if (width === this.width && height === this.height) { +RenderTexture.prototype.resize = function (width, height, updateBase) +{ + if (width === this.width && height === this.height) + { return; } @@ -177,17 +183,20 @@ this.width = this.frame.width = this.crop.width = width; this.height = this.frame.height = this.crop.height = height; - if (updateBase) { + if (updateBase) + { this.baseTexture.width = this.width; this.baseTexture.height = this.height; } - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { this.projection.x = this.width / 2; this.projection.y = -this.height / 2; } - if (!this.valid) { + if (!this.valid) + { return; } @@ -198,12 +207,15 @@ * Clears the RenderTexture. * */ -RenderTexture.prototype.clear = function () { - if (!this.valid) { +RenderTexture.prototype.clear = function () +{ + if (!this.valid) + { return; } - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { this.renderer.gl.bindFramebuffer(this.renderer.gl.FRAMEBUFFER, this.textureBuffer.frameBuffer); } @@ -220,19 +232,23 @@ * @param [restoreWorldTransform=true] {boolean} If true the displayObject's worldTransform/worldAlpha and all children * transformations will be restored. Not restoring this information will be a little faster. */ -RenderTexture.prototype.renderWebGL = function (displayObject, matrix, clear, restoreWorldTransform) { - if (!this.valid) { +RenderTexture.prototype.renderWebGL = function (displayObject, matrix, clear, restoreWorldTransform) +{ + if (!this.valid) + { return; } - if (typeof restoreWorldTransform === 'undefined') { + if (typeof restoreWorldTransform === 'undefined') + { restoreWorldTransform = true; } var tempAlpha, tempTransform; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { tempAlpha = displayObject.worldAlpha; tempTransform = displayObject.worldTransform.toArray(); } @@ -245,7 +261,8 @@ wt.identity(); wt.translate(0, this.projection.y * 2); - if (matrix) { + if (matrix) + { wt.append(matrix); } @@ -258,7 +275,8 @@ var children = displayObject.children; var i, j; - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } @@ -269,7 +287,8 @@ gl.bindFramebuffer(gl.FRAMEBUFFER, this.textureBuffer.frameBuffer ); - if (clear) { + if (clear) + { this.textureBuffer.clear(); } @@ -279,11 +298,13 @@ this.renderer.spriteBatch.dirty = true; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { displayObject.worldAlpha = tempAlpha; displayObject.worldTransform.fromArray(tempTransform); - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } } @@ -300,26 +321,31 @@ * @param [restoreWorldTransform=true] {boolean} If true the displayObject's worldTransform/worldAlpha and all children * transformations will be restored. Not restoring this information will be a little faster. */ -RenderTexture.prototype.renderCanvas = function (displayObject, matrix, clear, restoreWorldTransform) { - if (!this.valid) { +RenderTexture.prototype.renderCanvas = function (displayObject, matrix, clear, restoreWorldTransform) +{ + if (!this.valid) + { return; } - if (typeof restoreWorldTransform === 'undefined') { + if (typeof restoreWorldTransform === 'undefined') + { restoreWorldTransform = true; } var tempAlpha, tempTransform; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { tempAlpha = displayObject.worldAlpha; tempTransform = displayObject.worldTransform.toArray(); } var wt = displayObject.worldTransform; wt.identity(); - if (matrix) { + if (matrix) + { wt.append(matrix); } @@ -330,11 +356,13 @@ var children = displayObject.children; var i, j; - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } - if (clear) { + if (clear) + { this.textureBuffer.clear(); } @@ -348,11 +376,13 @@ this.renderer.resolution = realResolution; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { displayObject.worldAlpha = tempAlpha; displayObject.worldTransform.fromArray(tempTransform); - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } } @@ -363,7 +393,8 @@ * * @return {Image} */ -RenderTexture.prototype.getImage = function () { +RenderTexture.prototype.getImage = function () +{ var image = new Image(); image.src = this.getBase64(); return image; @@ -374,7 +405,8 @@ * * @return {string} A base64 encoded string of the texture. */ -RenderTexture.prototype.getBase64 = function () { +RenderTexture.prototype.getBase64 = function () +{ return this.getCanvas().toDataURL(); }; @@ -383,8 +415,10 @@ * * @return {HTMLCanvasElement} A Canvas element with the texture rendered on. */ -RenderTexture.prototype.getCanvas = function () { - if (this.renderer.type === CONST.WEBGL_RENDERER) { +RenderTexture.prototype.getCanvas = function () +{ + if (this.renderer.type === CONST.WEBGL_RENDERER) + { var gl = this.renderer.gl; var width = this.textureBuffer.width; var height = this.textureBuffer.height; @@ -403,7 +437,8 @@ return tempCanvas.canvas; } - else { + else + { return this.textureBuffer.canvas; } }; diff --git a/src/core/textures/Texture.js b/src/core/textures/Texture.js index 3c65909..e97f0aa 100644 --- a/src/core/textures/Texture.js +++ b/src/core/textures/Texture.js @@ -17,7 +17,8 @@ * @param [crop] {Rectangle} The area of original texture * @param [trim] {Rectangle} Trimmed texture rectangle */ -function Texture(baseTexture, frame, crop, trim) { +function Texture(baseTexture, frame, crop, trim) +{ /** * Does this Texture have any frame data assigned to it? * @@ -25,12 +26,14 @@ */ this.noFrame = false; - if (!frame) { + if (!frame) + { this.noFrame = true; frame = new math.Rectangle(0, 0, 1, 1); } - if (baseTexture instanceof Texture) { + if (baseTexture instanceof Texture) + { baseTexture = baseTexture.baseTexture; } @@ -100,13 +103,16 @@ */ this.crop = crop || new math.Rectangle(0, 0, 1, 1); - if (baseTexture.hasLoaded) { - if (this.noFrame) { + if (baseTexture.hasLoaded) + { + if (this.noFrame) + { frame = new math.Rectangle(0, 0, baseTexture.width, baseTexture.height); } this.frame = frame; } - else { + else + { baseTexture.addEventListener('loaded', this.onBaseTextureLoaded.bind(this)); } } @@ -118,19 +124,23 @@ Object.defineProperties(Texture.prototype, { needsUpdate: { - get: function () { + get: function () + { return this.baseTexture.needsUpdate; }, - set: function (val) { + set: function (val) + { this.baseTexture.needsUpdate = val; } }, frame: { - get: function () { + get: function () + { return this._frame; }, - set: function (frame) { + set: function (frame) + { this._frame = frame; this.noFrame = false; @@ -143,20 +153,23 @@ 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 (!this.trim && (frame.x + frame.width > this.baseTexture.width || frame.y + frame.height > this.baseTexture.height)) + { throw new Error('Texture Error: frame does not fit inside the base Texture dimensions ' + this); } this.valid = frame && frame.width && frame.height && this.baseTexture.source && this.baseTexture.hasLoaded; - if (this.trim) { + 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) { + if (this.valid) + { this._updateUvs(); } } @@ -168,11 +181,13 @@ * * @private */ -Texture.prototype.onBaseTextureLoaded = function () { +Texture.prototype.onBaseTextureLoaded = function () +{ var baseTexture = this.baseTexture; baseTexture.removeEventListener('loaded', this.onLoaded); - if (this.noFrame) { + if (this.noFrame) + { this.frame = new math.Rectangle(0, 0, baseTexture.width, baseTexture.height); } @@ -184,8 +199,10 @@ * * @param destroyBase {boolean} Whether to destroy the base texture as well */ -Texture.prototype.destroy = function (destroyBase) { - if (destroyBase) { +Texture.prototype.destroy = function (destroyBase) +{ + if (destroyBase) + { this.baseTexture.destroy(); } @@ -197,8 +214,10 @@ * * @private */ -Texture.prototype._updateUvs = function () { - if (!this._uvs) { +Texture.prototype._updateUvs = function () +{ + if (!this._uvs) + { this._uvs = new TextureUvs(); } @@ -229,10 +248,12 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return Texture */ -Texture.fromImage = function (imageUrl, crossorigin, scaleMode) { +Texture.fromImage = function (imageUrl, crossorigin, scaleMode) +{ var texture = utils.TextureCache[imageUrl]; - if (!texture) { + if (!texture) + { texture = new Texture(BaseTexture.fromImage(imageUrl, crossorigin, scaleMode)); utils.TextureCache[imageUrl] = texture; } @@ -248,9 +269,11 @@ * @param frameId {string} The frame id of the texture * @return Texture */ -Texture.fromFrame = function (frameId) { +Texture.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache '); } return texture; @@ -264,7 +287,8 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return {Texture} */ -Texture.fromCanvas = function (canvas, scaleMode) { +Texture.fromCanvas = function (canvas, scaleMode) +{ return new Texture(BaseTexture.fromCanvas(canvas, scaleMode)); }; @@ -276,7 +300,8 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return {Texture} A Texture */ -Texture.fromVideo = function (video, scaleMode) { +Texture.fromVideo = function (video, scaleMode) +{ return new Texture(VideoBaseTexture.baseTextureFromVideo(video, scaleMode)); }; @@ -287,7 +312,8 @@ * @param texture {Texture} The Texture to add to the cache. * @param id {string} The id that the texture will be stored against. */ -Texture.addTextureToCache = function (texture, id) { +Texture.addTextureToCache = function (texture, id) +{ utils.TextureCache[id] = texture; }; @@ -298,7 +324,8 @@ * @param id {string} The id of the texture to be removed * @return {Texture} The texture that was removed */ -Texture.removeTextureFromCache = function (id) { +Texture.removeTextureFromCache = function (id) +{ var texture = utils.TextureCache[id]; delete utils.TextureCache[id]; diff --git a/src/core/textures/TextureUvs.js b/src/core/textures/TextureUvs.js index b9bbb58..5424d52 100644 --- a/src/core/textures/TextureUvs.js +++ b/src/core/textures/TextureUvs.js @@ -1,4 +1,5 @@ -function TextureUvs() { +function TextureUvs() +{ this.x0 = 0; this.y0 = 0; diff --git a/src/core/textures/VideoBaseTexture.js b/src/core/textures/VideoBaseTexture.js index e3e0c5a..1a826a9 100644 --- a/src/core/textures/VideoBaseTexture.js +++ b/src/core/textures/VideoBaseTexture.js @@ -12,15 +12,18 @@ * @param source {HTMLVideoElement} * @param [scaleMode] {number} See {@link scaleModes} for possible values */ -function VideoBaseTexture(source, scaleMode) { - if (!source){ +function VideoBaseTexture(source, scaleMode) +{ + if (!source) + { throw new Error('No video source element specified.'); } // hook in here to check if video is already available. // BaseTexture looks for a source.complete boolean, plus width & height. - if ((source.readyState === source.HAVE_ENOUGH_DATA || source.readyState === source.HAVE_FUTURE_DATA) && source.width && source.height) { + if ((source.readyState === source.HAVE_ENOUGH_DATA || source.readyState === source.HAVE_FUTURE_DATA) && source.width && source.height) + { source.complete = true; } @@ -31,7 +34,8 @@ this._boundOnUpdate = this._onUpdate.bind(this); this._boundOnCanPlay = this._onCanPlay.bind(this); - if (!source.complete) { + if (!source.complete) + { source.addEventListener('canplay', this._boundOnCanPlay); source.addEventListener('canplaythrough', this._boundOnCanPlay); @@ -47,28 +51,35 @@ VideoBaseTexture.prototype.constructor = VideoBaseTexture; module.exports = VideoBaseTexture; -VideoBaseTexture.prototype._onUpdate = function () { - if (this.autoUpdate) { +VideoBaseTexture.prototype._onUpdate = function () +{ + if (this.autoUpdate) + { window.requestAnimationFrame(this._boundOnUpdate); this.needsUpdate = true; } }; -VideoBaseTexture.prototype._onPlayStart = function () { - if (!this.autoUpdate) { +VideoBaseTexture.prototype._onPlayStart = function () +{ + if (!this.autoUpdate) + { window.requestAnimationFrame(this._boundOnUpdate); this.autoUpdate = true; } }; -VideoBaseTexture.prototype._onPlayStop = function () { +VideoBaseTexture.prototype._onPlayStop = function () +{ this.autoUpdate = false; }; -VideoBaseTexture.prototype._onCanPlay = function () { +VideoBaseTexture.prototype._onCanPlay = function () +{ this.hasLoaded = true; - if (this.source) { + if (this.source) + { this.source.removeEventListener('canplay', this._boundOnCanPlay); this.source.removeEventListener('canplaythrough', this._boundOnCanPlay); @@ -78,15 +89,18 @@ this.source.play(); // prevent multiple loaded dispatches.. - if(!this.__loaded){ + if(!this.__loaded) + { this.__loaded = true; this.emit('loaded', this); } } }; -VideoBaseTexture.prototype.destroy = function () { - if (this.source && this.source._pixiId) { +VideoBaseTexture.prototype.destroy = function () +{ + if (this.source && this.source._pixiId) + { utils.BaseTextureCache[ this.source._pixiId ] = null; delete utils.BaseTextureCache[ this.source._pixiId ]; @@ -105,14 +119,17 @@ * @param scaleMode {number} See {@link scaleModes} for possible values * @return {VideoBaseTexture} */ -VideoBaseTexture.fromVideo = function (video, scaleMode) { - if (!video._pixiId) { +VideoBaseTexture.fromVideo = function (video, scaleMode) +{ + if (!video._pixiId) + { video._pixiId = 'video_' + utils.uuid(); } var baseTexture = utils.BaseTextureCache[video._pixiId]; - if (!baseTexture) { + if (!baseTexture) + { baseTexture = new VideoBaseTexture(video, scaleMode); utils.BaseTextureCache[ video._pixiId ] = baseTexture; } @@ -147,17 +164,21 @@ * @param scaleMode {number} See {@link scaleModes} for possible values * @return {VideoBaseTexture} */ -VideoBaseTexture.fromUrl = function (videoSrc, scaleMode) { +VideoBaseTexture.fromUrl = function (videoSrc, scaleMode) +{ var video = document.createElement('video'); // array of objects or strings - if (Array.isArray(videoSrc)) { - for (var i = 0; i < videoSrc.length; ++i) { + if (Array.isArray(videoSrc)) + { + for (var i = 0; i < videoSrc.length; ++i) + { video.appendChild(createSource(videoSrc.src || videoSrc, videoSrc.mime)); } } // single object or string - else { + else + { video.appendChild(createSource(videoSrc.src || videoSrc, videoSrc.mime)); } @@ -169,8 +190,10 @@ VideoBaseTexture.fromUrls = VideoBaseTexture.fromUrl; -function createSource(path, type) { - if (!type) { +function createSource(path, type) +{ + if (!type) + { type = 'video/' + path.substr(path.lastIndexOf('.') + 1); } diff --git a/src/core/utils/EventData.js b/src/core/utils/EventData.js index 5d55a22..8cdf701 100644 --- a/src/core/utils/EventData.js +++ b/src/core/utils/EventData.js @@ -7,7 +7,8 @@ * @param name {string} The string name of the event that was triggered * @param data {object} Arbitrary event data to pass along */ -function EventData(target, name, data) { +function EventData(target, name, data) +{ // for duck typing in the ".on()" function this.__isEventObject = true; @@ -71,7 +72,8 @@ * Stops the propagation of events up the scene graph (prevents bubbling). * */ -EventData.prototype.stopPropagation = function stopPropagation() { +EventData.prototype.stopPropagation = function stopPropagation() +{ this.stopped = true; }; @@ -79,6 +81,7 @@ * Stops the propagation of events to sibling listeners (no longer calls any listeners). * */ -EventData.prototype.stopImmediatePropagation = function stopImmediatePropagation() { +EventData.prototype.stopImmediatePropagation = function stopImmediatePropagation() +{ this.stoppedImmediate = true; }; diff --git a/src/core/utils/EventTarget.js b/src/core/utils/EventTarget.js index 7ae8820..671a151 100644 --- a/src/core/utils/EventTarget.js +++ b/src/core/utils/EventTarget.js @@ -13,14 +13,16 @@ * var em = new MyEmitter(); * em.emit('eventName', 'some data', 'some more data', {}, null, ...); */ -function eventTarget(obj) { +function eventTarget(obj) +{ /** * Return a list of assigned event listeners. * * @param eventName {string} The events that should be listed. * @return {Array} An array of listener functions */ - obj.listeners = function listeners(eventName) { + obj.listeners = function listeners(eventName) + { this._listeners = this._listeners || {}; return this._listeners[eventName] ? this._listeners[eventName].slice() : []; @@ -33,22 +35,26 @@ * @param eventName {string} The name of the event. * @return {boolean} Indication if we've emitted an event. */ - obj.emit = obj.dispatchEvent = function emit(eventName, data) { + obj.emit = obj.dispatchEvent = function emit(eventName, data) + { this._listeners = this._listeners || {}; // fast return when there are no listeners - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return; } //backwards compat with old method ".emit({ type: 'something' })" - if (typeof eventName === 'object') { + if (typeof eventName === 'object') + { data = eventName; eventName = eventName.type; } //ensure we are using a real pixi event - if (!data || data.__isEventObject !== true) { + if (!data || data.__isEventObject !== true) + { data = new EventData(this, eventName, data); } @@ -58,23 +64,27 @@ fn = listeners[0], i; - for (i = 0; i < length; fn = listeners[++i]) { + for (i = 0; i < length; fn = listeners[++i]) + { //call the event listener fn.call(this, data); //if "stopImmediatePropagation" is called, stop calling sibling events - if (data.stoppedImmediate) { + if (data.stoppedImmediate) + { return this; } } //if "stopPropagation" is called then don't bubble the event - if (data.stopped) { + if (data.stopped) + { return this; } //bubble this event up the scene graph - if (this.parent && this.parent.emit) { + if (this.parent && this.parent.emit) + { this.parent.emit.call(this.parent, eventName, data); } @@ -88,7 +98,8 @@ * @param eventName {string} Name of the event. * @param callback {Functon} fn Callback function. */ - obj.on = obj.addEventListener = function on(eventName, fn) { + obj.on = obj.addEventListener = function on(eventName, fn) + { this._listeners = this._listeners || {}; (this._listeners[eventName] = this._listeners[eventName] || []) @@ -103,11 +114,13 @@ * @param eventName {string} Name of the event. * @param callback {Function} Callback function. */ - obj.once = function once(eventName, fn) { + obj.once = function once(eventName, fn) + { this._listeners = this._listeners || {}; var self = this; - function onceHandlerWrapper() { + function onceHandlerWrapper() + { fn.apply(self.off(eventName, onceHandlerWrapper), arguments); } onceHandlerWrapper._originalHandler = fn; @@ -122,23 +135,28 @@ * @param eventName {string} The event we want to remove. * @param callback {Function} The listener that we need to find. */ - obj.off = obj.removeEventListener = function off(eventName, fn) { + obj.off = obj.removeEventListener = function off(eventName, fn) + { this._listeners = this._listeners || {}; - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return this; } var list = this._listeners[eventName], i = fn ? list.length : 0; - while(i-- > 0) { - if (list[i] === fn || list[i]._originalHandler === fn) { + while(i-- > 0) + { + if (list[i] === fn || list[i]._originalHandler === fn) + { list.splice(i, 1); } } - if (list.length === 0) { + if (list.length === 0) + { delete this._listeners[eventName]; } @@ -150,10 +168,12 @@ * * @param eventName {string} The event you want to remove all listeners for. */ - obj.removeAllListeners = function removeAllListeners(eventName) { + obj.removeAllListeners = function removeAllListeners(eventName) + { this._listeners = this._listeners || {}; - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return this; } @@ -169,7 +189,8 @@ * * @param object {object} The obj to mix into */ - mixin: function mixin(obj) { + mixin: function mixin(obj) + { eventTarget(obj); } }; diff --git a/src/core/utils/PolyK.js b/src/core/utils/PolyK.js index 7325141..5e20c2b 100644 --- a/src/core/utils/PolyK.js +++ b/src/core/utils/PolyK.js @@ -47,7 +47,8 @@ * Triangulates shapes for webGL graphic fills. * */ -PolyK.Triangulate = function (p) { +PolyK.Triangulate = function (p) +{ var sign = true; var n = p.length >> 1; @@ -59,7 +60,8 @@ i = 0; var al = n; - while(al > 3) { + while(al > 3) + { var i0 = avl[(i+0)%al]; var i1 = avl[(i+1)%al]; var i2 = avl[(i+2)%al]; @@ -69,29 +71,35 @@ var cx = p[2*i2], cy = p[2*i2+1]; var earFound = false; - if (PolyK._convex(ax, ay, bx, by, cx, cy, sign)) { + if (PolyK._convex(ax, ay, bx, by, cx, cy, sign)) + { earFound = true; - for (var j = 0; j < al; j++) { + for (var j = 0; j < al; j++) + { var vi = avl[j]; if (vi === i0 || vi === i1 || vi === i2) continue; - if (PolyK._PointInTriangle(p[2*vi], p[2*vi+1], ax, ay, bx, by, cx, cy)) { + if (PolyK._PointInTriangle(p[2*vi], p[2*vi+1], ax, ay, bx, by, cx, cy)) + { earFound = false; break; } } } - if (earFound) { + if (earFound) + { tgs.push(i0, i1, i2); avl.splice((i+1)%al, 1); al--; i = 0; } - else if (i++ > 3*al) { + else if (i++ > 3*al) + { // need to flip flip reverse it! // reset! - if (sign) { + if (sign) + { tgs = []; avl = []; for (i = 0; i < n; i++) avl.push(i); @@ -101,7 +109,8 @@ sign = false; } - else { + else + { // window.console.log("PIXI Warning: shape too complex to fill"); return null; } @@ -126,7 +135,8 @@ * @private * @return {boolean} */ -PolyK._PointInTriangle = function (px, py, ax, ay, bx, by, cx, cy) { +PolyK._PointInTriangle = function (px, py, ax, ay, bx, by, cx, cy) +{ var v0x = cx-ax; var v0y = cy-ay; var v1x = bx-ax; @@ -154,6 +164,7 @@ * @private * @return {boolean} */ -PolyK._convex = function (ax, ay, bx, by, cx, cy, sign) { +PolyK._convex = function (ax, ay, bx, by, cx, cy, sign) +{ return ((ay-by)*(cx-bx) + (bx-ax)*(cy-by) >= 0) === sign; }; diff --git a/src/core/utils/index.js b/src/core/utils/index.js index ade9831..bfae7ae 100644 --- a/src/core/utils/index.js +++ b/src/core/utils/index.js @@ -16,7 +16,8 @@ * * @return {number} The next uuid to use. */ - uuid: function () { + uuid: function () + { return ++utils._uid; }, @@ -26,7 +27,8 @@ * @param hex {number} * @return {number[]} An array representing the [R, G, B] of the color. */ - hex2rgb: function (hex, out) { + hex2rgb: function (hex, out) + { out = out || []; out[0] = (hex >> 16 & 0xFF) / 255; @@ -42,7 +44,8 @@ * @param hex {number} * @return {string} The string color. */ - hex2string: function (hex) { + hex2string: function (hex) + { hex = hex.toString(16); hex = '000000'.substr(0, 6 - hex.length) + hex; @@ -55,7 +58,8 @@ * @param rgb {number[]} * @return {number} The color number */ - rgb2hex: function (rgb) { + rgb2hex: function (rgb) + { return ((rgb[0]*255 << 16) + (rgb[1]*255 << 8) + rgb[2]*255); }, @@ -64,8 +68,10 @@ * * @return {boolean} whether they are supported */ - canUseNewCanvasBlendModes: function () { - if (typeof document === 'undefined') { + canUseNewCanvasBlendModes: function () + { + if (typeof document === 'undefined') + { return false; } @@ -93,15 +99,19 @@ * @param number {number} * @return {number} the closest number that is a power of two */ - getNextPowerOfTwo: function (number) { + getNextPowerOfTwo: function (number) + { // see: http://en.wikipedia.org/wiki/Power_of_two#Fast_algorithm_to_check_if_a_positive_number_is_a_power_of_two - if (number > 0 && (number & (number - 1)) === 0) { + if (number > 0 && (number & (number - 1)) === 0) + { return number; } - else { + else + { var result = 1; - while (result < number) { + while (result < number) + { result <<= 1; } @@ -116,7 +126,8 @@ * @param height {number} * @return {boolean} */ - isPowerOfTwo: function (width, height) { + isPowerOfTwo: function (width, height) + { return (width > 0 && (width & (width - 1)) === 0 && height > 0 && (height & (height - 1)) === 0); }, @@ -130,12 +141,15 @@ * @constant * @static */ - sayHello: function (type) { - if (utils._saidHello) { + sayHello: function (type) + { + if (utils._saidHello) + { return; } - if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) { + if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) + { var args = [ '%c %c %c Pixi.js ' + CONST.VERSION + ' - ' + type + ' %c ' + ' %c ' + ' http://www.pixijs.com/ %c %c ♥%c♥%c♥ ', 'background: #ff66a5', @@ -151,7 +165,8 @@ console.log.apply(console, args); //jshint ignore:line } - else if (window.console) { + else if (window.console) + { console.log('Pixi.js ' + CONST.VERSION + ' - ' + type + ' - http://www.pixijs.com/'); //jshint ignore:line } @@ -166,15 +181,19 @@ * @class * @namespace PIXI */ - AjaxRequest: function () { + AjaxRequest: function () + { var activexmodes = ['Msxml2.XMLHTTP.6.0', 'Msxml2.XMLHTTP.3.0', 'Microsoft.XMLHTTP']; //activeX versions to check for in IE - if (window.ActiveXObject) { //Test for support for ActiveXObject in IE first (as XMLHttpRequest in IE7 is broken) - for (var i=0; i= this.textures.length) { + else if (round >= this.textures.length) + { this.gotoAndStop(this.textures.length - 1); - if (this.onComplete) { + if (this.onComplete) + { this.onComplete(); } } @@ -167,10 +182,12 @@ * @static * @param frames {string[]} the array of frames ids the movieclip will use as its texture frames */ -MovieClip.fromFrames = function (frames) { +MovieClip.fromFrames = function (frames) +{ var textures = []; - for (var i = 0; i < frames.length; ++i) { + for (var i = 0; i < frames.length; ++i) + { textures.push(new core.Texture.fromFrame(frames[i])); } @@ -183,10 +200,12 @@ * @static * @param images {string[]} the array of image urls the movieclip will use as its texture frames */ -MovieClip.fromImages = function (images) { +MovieClip.fromImages = function (images) +{ var textures = []; - for (var i = 0; i < images.length; ++i) { + for (var i = 0; i < images.length; ++i) + { textures.push(new core.Texture.fromImage(images[i])); } diff --git a/src/extras/Rope.js b/src/extras/Rope.js index c157ec4..9c87bc0 100644 --- a/src/extras/Rope.js +++ b/src/extras/Rope.js @@ -9,7 +9,8 @@ * @param {Array} points - An array of {Point}. * */ -function Rope(texture, points) { +function Rope(texture, points) +{ Strip.call(this, texture); this.points = points; @@ -31,10 +32,12 @@ * Refreshes * */ -Rope.prototype.refresh = function () { +Rope.prototype.refresh = function () +{ var points = this.points; - if (points.length < 1) { + if (points.length < 1) + { return; } @@ -59,20 +62,23 @@ var total = points.length, point, index, amount; - for (var i = 1; i < total; i++) { + for (var i = 1; i < total; i++) + { point = points[i]; index = i * 4; // time to do some smart drawing! amount = i / (total-1); - if (i%2) { + if (i%2) + { uvs[index] = amount; uvs[index+1] = 0; uvs[index+2] = amount; uvs[index+3] = 1; } - else { + else + { uvs[index] = amount; uvs[index+1] = 0; @@ -95,10 +101,12 @@ * * @private */ -Rope.prototype.updateTransform = function () { +Rope.prototype.updateTransform = function () +{ var points = this.points; - if (points.length < 1) { + if (points.length < 1) + { return; } @@ -113,14 +121,17 @@ var total = points.length, point, index, ratio, perpLength, num; - for (var i = 0; i < total; i++) { + for (var i = 0; i < total; i++) + { point = points[i]; index = i * 4; - if (i < points.length-1) { + if (i < points.length-1) + { nextPoint = points[i+1]; } - else { + else + { nextPoint = point; } @@ -129,7 +140,8 @@ ratio = (1 - (i / (total-1))) * 10; - if (ratio > 1) { + if (ratio > 1) + { ratio = 1; } @@ -157,7 +169,8 @@ * * @param texture {Texture} the texture that will be used */ -Rope.prototype.setTexture = function (texture) { +Rope.prototype.setTexture = function (texture) +{ // stop current texture this.texture = texture; //this.updateFrame = true; diff --git a/src/extras/Strip.js b/src/extras/Strip.js index c5e378f..57691b5 100644 --- a/src/extras/Strip.js +++ b/src/extras/Strip.js @@ -10,7 +10,8 @@ * @param height {number} the height * */ -function Strip(texture) { +function Strip(texture) +{ core.DisplayObjectContainer.call(this); /** @@ -70,9 +71,11 @@ * * @param renderer {WebGLRenderer} */ -Strip.prototype.renderWebGL = function (renderer) { +Strip.prototype.renderWebGL = function (renderer) +{ // if the sprite is not visible or the alpha is 0 then no need to render this element - if (!this.visible || this.alpha <= 0) { + if (!this.visible || this.alpha <= 0) + { return; } @@ -81,7 +84,8 @@ renderer.spriteBatch.stop(); // init! init! - if (!this._vertexBuffer) { + if (!this._vertexBuffer) + { this._initWebGL(renderer); } @@ -96,7 +100,8 @@ //TODO check culling }; -Strip.prototype._initWebGL = function (renderer) { +Strip.prototype._initWebGL = function (renderer) +{ // build the strip! var gl = renderer.gl; @@ -118,7 +123,8 @@ gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this.indices, gl.STATIC_DRAW); }; -Strip.prototype._renderStrip = function (renderer) { +Strip.prototype._renderStrip = function (renderer) +{ var gl = renderer.gl; var projection = renderer.projection, offset = renderer.offset, @@ -137,7 +143,8 @@ gl.uniform2f(shader.offsetVector, -offset.x, -offset.y); gl.uniform1f(shader.alpha, this.worldAlpha); - if (!this.dirty) { + if (!this.dirty) + { gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexBuffer); gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); @@ -150,10 +157,12 @@ gl.activeTexture(gl.TEXTURE0); // check if a texture is dirty.. - if (this.texture.baseTexture._dirty[gl.id]) { + if (this.texture.baseTexture._dirty[gl.id]) + { renderer.updateTexture(this.texture.baseTexture); } - else { + else + { // bind the current texture gl.bindTexture(gl.TEXTURE_2D, this.texture.baseTexture._glTextures[gl.id]); } @@ -163,7 +172,8 @@ } - else { + else + { this.dirty = false; gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexBuffer); @@ -178,10 +188,12 @@ gl.activeTexture(gl.TEXTURE0); // check if a texture is dirty.. - if (this.texture.baseTexture._dirty[gl.id]) { + if (this.texture.baseTexture._dirty[gl.id]) + { renderer.updateTexture(this.texture.baseTexture); } - else { + else + { gl.bindTexture(gl.TEXTURE_2D, this.texture.baseTexture._glTextures[gl.id]); } @@ -203,27 +215,33 @@ * * @param renderer {CanvasRenderer} */ -Strip.prototype.renderCanvas = function (renderer) { +Strip.prototype.renderCanvas = function (renderer) +{ var context = renderer.context; var transform = this.worldTransform; - if (renderer.roundPixels) { + if (renderer.roundPixels) + { context.setTransform(transform.a, transform.b, transform.c, transform.d, transform.tx | 0, transform.ty | 0); } - else { + else + { context.setTransform(transform.a, transform.b, transform.c, transform.d, transform.tx, transform.ty); } - if (this.drawMode === Strip.DrawModes.TRIANGLE_STRIP) { + if (this.drawMode === Strip.DrawModes.TRIANGLE_STRIP) + { this._renderCanvasTriangleStrip(context); } - else { + else + { this._renderCanvasTriangles(context); } }; -Strip.prototype._renderCanvasTriangleStrip = function (context) { +Strip.prototype._renderCanvasTriangleStrip = function (context) +{ // draw triangles!! var vertices = this.vertices; var uvs = this.uvs; @@ -231,14 +249,16 @@ var length = vertices.length / 2; // this.count++; - for (var i = 0; i < length - 2; i++) { + for (var i = 0; i < length - 2; i++) + { // draw some triangles! var index = i * 2; this._renderCanvasDrawTriangle(context, vertices, uvs, index, (index + 2), (index + 4)); } }; -Strip.prototype._renderCanvasTriangles = function (context) { +Strip.prototype._renderCanvasTriangles = function (context) +{ // draw triangles!! var vertices = this.vertices; var uvs = this.uvs; @@ -247,14 +267,16 @@ var length = indices.length; // this.count++; - for (var i = 0; i < length; i += 3) { + for (var i = 0; i < length; i += 3) + { // draw some triangles! var index0 = indices[i] * 2, index1 = indices[i + 1] * 2, index2 = indices[i + 2] * 2; this._renderCanvasDrawTriangle(context, vertices, uvs, index0, index1, index2); } }; -Strip.prototype._renderCanvasDrawTriangle = function (context, vertices, uvs, index0, index1, index2) { +Strip.prototype._renderCanvasDrawTriangle = function (context, vertices, uvs, index0, index1, index2) +{ var textureSource = this.texture.baseTexture.source; var textureWidth = this.texture.width; var textureHeight = this.texture.height; @@ -265,7 +287,8 @@ var u0 = uvs[index0] * textureWidth, u1 = uvs[index1] * textureWidth, u2 = uvs[index2] * textureWidth; var v0 = uvs[index0 + 1] * textureHeight, v1 = uvs[index1 + 1] * textureHeight, v2 = uvs[index2 + 1] * textureHeight; - if (this.canvasPadding > 0) { + if (this.canvasPadding > 0) + { var paddingX = this.canvasPadding / this.worldTransform.a; var paddingY = this.canvasPadding / this.worldTransform.d; var centerX = (x0 + x1 + x2) / 3; @@ -332,7 +355,8 @@ * @param strip {Strip} The Strip to render * @private */ -Strip.prototype.renderStripFlat = function (strip) { +Strip.prototype.renderStripFlat = function (strip) +{ var context = this.context; var vertices = strip.vertices; @@ -340,7 +364,8 @@ // this.count++; context.beginPath(); - for (var i=1; i < length-2; i++) { + for (var i=1; i < length-2; i++) + { // draw some triangles! var index = i*2; @@ -358,7 +383,8 @@ }; /* -Strip.prototype.setTexture = function (texture) { +Strip.prototype.setTexture = function (texture) +{ //TODO SET THE TEXTURES //TODO VISIBILITY @@ -377,7 +403,8 @@ * @private */ -Strip.prototype.onTextureUpdate = function () { +Strip.prototype.onTextureUpdate = function () +{ this.updateFrame = true; }; @@ -387,7 +414,8 @@ * @param matrix {Matrix} the transformation matrix of the sprite * @return {Rectangle} the framing rectangle */ -Strip.prototype.getBounds = function (matrix) { +Strip.prototype.getBounds = function (matrix) +{ var worldTransform = matrix || this.worldTransform; var a = worldTransform.a; @@ -404,7 +432,8 @@ var minY = Infinity; var vertices = this.vertices; - for (var i = 0, n = vertices.length; i < n; i += 2) { + for (var i = 0, n = vertices.length; i < n; i += 2) + { var rawX = vertices[i], rawY = vertices[i + 1]; var x = (a * rawX) + (c * rawY) + tx; var y = (d * rawY) + (b * rawX) + ty; @@ -416,7 +445,8 @@ maxY = y > maxY ? y : maxY; } - if (minX === -Infinity || maxY === Infinity) { + if (minX === -Infinity || maxY === Infinity) + { return core.math.Rectangle.EMPTY; } diff --git a/src/extras/TilingSprite.js b/src/extras/TilingSprite.js index 3ac22df..31da393 100644 --- a/src/extras/TilingSprite.js +++ b/src/extras/TilingSprite.js @@ -10,7 +10,8 @@ * @param width {number} the width of the tiling sprite * @param height {number} the height of the tiling sprite */ -function TilingSprite(texture, width, height) { +function TilingSprite(texture, width, height) +{ core.Sprite.call( this, texture); /** @@ -86,10 +87,12 @@ * @memberof TilingSprite# */ width: { - get: function () { + get: function () + { return this._width; }, - set: function (value) { + set: function (value) + { this._width = value; } }, @@ -101,20 +104,25 @@ * @memberof TilingSprite# */ height: { - get: function () { + get: function () + { return this._height; }, - set: function (value) { + set: function (value) + { this._height = value; } }, texture: { - get: function () { + get: function () + { return this._texture; }, - set: function (value) { - if (this._texture === value) { + set: function (value) + { + if (this._texture === value) + { return; } @@ -130,51 +138,61 @@ * * @param renderer {WebGLRenderer} */ -TilingSprite.prototype.renderWebGL = function (renderer) { - if (!this.visible || this.alpha <= 0) { +TilingSprite.prototype.renderWebGL = function (renderer) +{ + if (!this.visible || this.alpha <= 0) + { return; } var i, j; - if (this._mask) { + if (this._mask) + { renderer.spriteBatch.stop(); renderer.maskManager.pushMask(this.mask, renderer); renderer.spriteBatch.start(); } - if (this._filters) { + if (this._filters) + { renderer.spriteBatch.flush(); renderer.filterManager.pushFilter(this._filterBlock); } - if (!this.tilingTexture || this.refreshTexture) { + if (!this.tilingTexture || this.refreshTexture) + { this.generateTilingTexture(true); - if (this.tilingTexture && this.tilingTexture.needsUpdate) { + if (this.tilingTexture && this.tilingTexture.needsUpdate) + { //TODO - tweaking renderer.updateTexture(this.tilingTexture.baseTexture); this.tilingTexture.needsUpdate = false; // this.tilingTexture._uvs = null; } } - else { + else + { renderer.spriteBatch.renderTilingSprite(this); } // simple render children! - for (i=0,j=this.children.length; i= 0; i--) { + for (var i = length - 1; i >= 0; i--) + { var child = children[i]; // push all interactive bits - if (child._interactive) { + if (child._interactive) + { iParent.interactiveChildren = true; //child.__iParent = iParent; this.interactiveItems.push(child); - if (child.children.length > 0) { + if (child.children.length > 0) + { this.collectInteractiveSprite(child, child); } } - else { + else + { child.__iParent = null; - if (child.children.length > 0) { + if (child.children.length > 0) + { this.collectInteractiveSprite(child, iParent); } } @@ -189,7 +196,8 @@ * @param [resolution=1] {number} THe resolution of the new element (relative to the canvas). * @private */ -InteractionManager.prototype.setTargetElement = function (element, resolution) { +InteractionManager.prototype.setTargetElement = function (element, resolution) +{ this.removeEvents(); this.interactionDOMElement = element; @@ -203,12 +211,15 @@ * * @private */ -InteractionManager.prototype.addEvents = function () { - if (!this.interactionDOMElement) { +InteractionManager.prototype.addEvents = function () +{ + if (!this.interactionDOMElement) + { return; } - if (window.navigator.msPointerEnabled) { + if (window.navigator.msPointerEnabled) + { this.interactionDOMElement.style['-ms-content-zooming'] = 'none'; this.interactionDOMElement.style['-ms-touch-action'] = 'none'; } @@ -230,12 +241,15 @@ * * @private */ -InteractionManager.prototype.removeEvents = function () { - if (!this.interactionDOMElement) { +InteractionManager.prototype.removeEvents = function () +{ + if (!this.interactionDOMElement) + { return; } - if (window.navigator.msPointerEnabled) { + if (window.navigator.msPointerEnabled) + { this.interactionDOMElement.style['-ms-content-zooming'] = ''; this.interactionDOMElement.style['-ms-touch-action'] = ''; } @@ -260,8 +274,10 @@ * * @private */ -InteractionManager.prototype.update = function () { - if (!this.interactionDOMElement) { +InteractionManager.prototype.update = function () +{ + if (!this.interactionDOMElement) + { return; } @@ -269,7 +285,8 @@ var now = Date.now(); var diff = now - this.last; diff = (diff * INTERACTION_FREQUENCY ) / 1000; - if (diff < 1) { + if (diff < 1) + { return; } @@ -280,7 +297,8 @@ // ok.. so mouse events?? // yes for now :) // OPTIMISE - how often to check?? - if (this.dirty) { + if (this.dirty) + { this.rebuildInteractiveGraph(); } @@ -289,7 +307,8 @@ var cursor = 'inherit'; var over = false; - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { var item = this.interactiveItems[i]; // OPTIMISATION - only calculate every time if the mousemove function exists.. @@ -302,26 +321,34 @@ this.mouse.target = item; // ok so deal with interactions.. // looks like there was a hit! - if (item.__hit && !over) { - if (item.buttonMode) { + if (item.__hit && !over) + { + if (item.buttonMode) + { cursor = item.defaultCursor; } - if (!item.interactiveChildren) { + if (!item.interactiveChildren) + { over = true; } - if (!item.__isOver) { - if (item.mouseover) { + if (!item.__isOver) + { + if (item.mouseover) + { item.mouseover (this.mouse); } item.__isOver = true; } } - else { - if (item.__isOver) { + else + { + if (item.__isOver) + { // roll out! - if (item.mouseout) { + if (item.mouseout) + { item.mouseout (this.mouse); } item.__isOver = false; @@ -329,7 +356,8 @@ } } - if (this.currentCursorStyle !== cursor) { + if (this.currentCursorStyle !== cursor) + { this.currentCursorStyle = cursor; this.interactionDOMElement.style.cursor = cursor; } @@ -338,18 +366,21 @@ /** * @private */ -InteractionManager.prototype.rebuildInteractiveGraph = function () { +InteractionManager.prototype.rebuildInteractiveGraph = function () +{ this.dirty = false; var len = this.interactiveItems.length; - for (var i = 0; i < len; i++) { + for (var i = 0; i < len; i++) + { this.interactiveItems[i].interactiveChildren = false; } this.interactiveItems.length = 0; - if (this.stage.interactive) { + if (this.stage.interactive) + { this.interactiveItems.push(this.stage); } @@ -363,8 +394,10 @@ * @param event {Event} The DOM event of the mouse moving * @private */ -InteractionManager.prototype.onMouseMove = function (event) { - if (this.dirty) { +InteractionManager.prototype.onMouseMove = function (event) +{ + if (this.dirty) + { this.rebuildInteractiveGraph(); } @@ -378,11 +411,13 @@ var length = this.interactiveItems.length; - for (var i = 0; i < length; i++) { + for (var i = 0; i < length; i++) + { var item = this.interactiveItems[i]; // Call the function! - if (item.mousemove) { + if (item.mousemove) + { item.mousemove(this.mouse); } } @@ -394,14 +429,17 @@ * @param event {Event} The DOM event of a mouse button being pressed down * @private */ -InteractionManager.prototype.onMouseDown = function (event) { - if (this.dirty) { +InteractionManager.prototype.onMouseDown = function (event) +{ + if (this.dirty) + { this.rebuildInteractiveGraph(); } this.mouse.originalEvent = event; - if (AUTO_PREVENT_DEFAULT) { + if (AUTO_PREVENT_DEFAULT) + { this.mouse.originalEvent.preventDefault(); } @@ -420,22 +458,27 @@ // while // hit test - for (var i = 0; i < length; i++) { + for (var i = 0; i < length; i++) + { var item = this.interactiveItems[i]; - if (item[downFunction] || item[clickFunction]) { + if (item[downFunction] || item[clickFunction]) + { item[buttonIsDown] = true; item.__hit = this.hitTest(item, this.mouse); - if (item.__hit) { + if (item.__hit) + { //call the function! - if (item[downFunction]) { + if (item[downFunction]) + { item[downFunction](this.mouse); } item[isDown] = true; // just the one! - if (!item.interactiveChildren) { + if (!item.interactiveChildren) + { break; } } @@ -449,8 +492,10 @@ * @param event {Event} The DOM event of a mouse being moved out * @private */ -InteractionManager.prototype.onMouseOut = function (event) { - if (this.dirty) { +InteractionManager.prototype.onMouseOut = function (event) +{ + if (this.dirty) + { this.rebuildInteractiveGraph(); } @@ -460,11 +505,14 @@ this.interactionDOMElement.style.cursor = 'inherit'; - for (var i = 0; i < length; i++) { + for (var i = 0; i < length; i++) + { var item = this.interactiveItems[i]; - if (item.__isOver) { + if (item.__isOver) + { this.mouse.target = item; - if (item.mouseout) { + if (item.mouseout) + { item.mouseout(this.mouse); } item.__isOver = false; @@ -484,8 +532,10 @@ * @param event {Event} The DOM event of a mouse button being released * @private */ -InteractionManager.prototype.onMouseUp = function (event) { - if (this.dirty) { +InteractionManager.prototype.onMouseUp = function (event) +{ + if (this.dirty) + { this.rebuildInteractiveGraph(); } @@ -502,30 +552,40 @@ var upOutsideFunction = isRightButton ? 'rightupoutside' : 'mouseupoutside'; var isDown = isRightButton ? '__isRightDown' : '__isDown'; - for (var i = 0; i < length; i++) { + for (var i = 0; i < length; i++) + { var item = this.interactiveItems[i]; - if (item[clickFunction] || item[upFunction] || item[upOutsideFunction]) { + if (item[clickFunction] || item[upFunction] || item[upOutsideFunction]) + { item.__hit = this.hitTest(item, this.mouse); - if (item.__hit && !up) { + if (item.__hit && !up) + { //call the function! - if (item[upFunction]) { + if (item[upFunction]) + { item[upFunction](this.mouse); } - if (item[isDown]) { - if (item[clickFunction]) { + if (item[isDown]) + { + if (item[clickFunction]) + { item[clickFunction](this.mouse); } } - if (!item.interactiveChildren) { + if (!item.interactiveChildren) + { up = true; } } - else { - if (item[isDown]) { - if (item[upOutsideFunction]) { + else + { + if (item[isDown]) + { + if (item[upOutsideFunction]) + { item[upOutsideFunction](this.mouse); } } @@ -543,10 +603,12 @@ * @param interactionData {InteractionData} The interactionData object to update in the case there is a hit * @private */ -InteractionManager.prototype.hitTest = function (item, interactionData) { +InteractionManager.prototype.hitTest = function (item, interactionData) +{ var global = interactionData.global; - if (!item.worldVisible) { + if (!item.worldVisible) + { return false; } @@ -560,37 +622,46 @@ interactionData.target = item; //a sprite or display object with a hit area defined - if (item.hitArea && item.hitArea.contains) { + if (item.hitArea && item.hitArea.contains) + { return item.hitArea.contains(x, y); } // a sprite with no hitarea defined - else if (item instanceof core.Sprite) { + else if (item instanceof core.Sprite) + { var width = item.texture.frame.width; var height = item.texture.frame.height; var x1 = -width * item.anchor.x; var y1; - if (x > x1 && x < x1 + width) { + if (x > x1 && x < x1 + width) + { y1 = -height * item.anchor.y; - if (y > y1 && y < y1 + height) { + if (y > y1 && y < y1 + height) + { // set the target property if a hit is true! return true; } } } - else if (item instanceof core.Graphics) { + else if (item instanceof core.Graphics) + { var graphicsData = item.graphicsData; - for (i = 0; i < graphicsData.length; i++) { + for (i = 0; i < graphicsData.length; i++) + { var data = graphicsData[i]; - if (!data.fill) { + if (!data.fill) + { continue; } // only deal with fills.. - if (data.shape) { - if (data.shape.contains(x, y)) { + if (data.shape) + { + if (data.shape.contains(x, y)) + { //interactionData.target = item; return true; } @@ -600,10 +671,12 @@ var length = item.children.length; - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { var tempItem = item.children[i]; var hit = this.hitTest(tempItem, interactionData); - if (hit) { + if (hit) + { // hmm.. TODO SET CORRECT TARGET? interactionData.target = item; return true; @@ -618,8 +691,10 @@ * @param event {Event} The DOM event of a touch moving across the renderer view * @private */ -InteractionManager.prototype.onTouchMove = function (event) { - if (this.dirty) { +InteractionManager.prototype.onTouchMove = function (event) +{ + if (this.dirty) + { this.rebuildInteractiveGraph(); } @@ -628,7 +703,8 @@ var touchData; var i = 0; - for (i = 0; i < changedTouches.length; i++) { + for (i = 0; i < changedTouches.length; i++) + { var touchEvent = changedTouches[i]; touchData = this.touches[touchEvent.identifier]; touchData.originalEvent = event; @@ -636,15 +712,18 @@ // update the touch position touchData.global.x = ( (touchEvent.clientX - rect.left) * (this.interactionDOMElement.width / rect.width) ) / this.resolution; touchData.global.y = ( (touchEvent.clientY - rect.top) * (this.interactionDOMElement.height / rect.height) ) / this.resolution; - if (navigator.isCocoonJS && !rect.left && !rect.top && !event.target.style.width && !event.target.style.height) { + if (navigator.isCocoonJS && !rect.left && !rect.top && !event.target.style.width && !event.target.style.height) + { //Support for CocoonJS fullscreen scale modes touchData.global.x = touchEvent.clientX; touchData.global.y = touchEvent.clientY; } - for (var j = 0; j < this.interactiveItems.length; j++) { + for (var j = 0; j < this.interactiveItems.length; j++) + { var item = this.interactiveItems[j]; - if (item.touchmove && item.__touchData && item.__touchData[touchEvent.identifier]) { + if (item.touchmove && item.__touchData && item.__touchData[touchEvent.identifier]) + { item.touchmove(touchData); } } @@ -657,23 +736,28 @@ * @param event {Event} The DOM event of a touch starting on the renderer view * @private */ -InteractionManager.prototype.onTouchStart = function (event) { - if (this.dirty) { +InteractionManager.prototype.onTouchStart = function (event) +{ + if (this.dirty) + { this.rebuildInteractiveGraph(); } var rect = this.interactionDOMElement.getBoundingClientRect(); - if (AUTO_PREVENT_DEFAULT) { + if (AUTO_PREVENT_DEFAULT) + { event.preventDefault(); } var changedTouches = event.changedTouches; - for (var i=0; i < changedTouches.length; i++) { + for (var i=0; i < changedTouches.length; i++) + { var touchEvent = changedTouches[i]; var touchData = this.pool.pop(); - if (!touchData) { + if (!touchData) + { touchData = new InteractionData(); } @@ -682,7 +766,8 @@ this.touches[touchEvent.identifier] = touchData; touchData.global.x = ( (touchEvent.clientX - rect.left) * (this.interactionDOMElement.width / rect.width) ) / this.resolution; touchData.global.y = ( (touchEvent.clientY - rect.top) * (this.interactionDOMElement.height / rect.height) ) / this.resolution; - if (navigator.isCocoonJS && !rect.left && !rect.top && !event.target.style.width && !event.target.style.height) { + if (navigator.isCocoonJS && !rect.left && !rect.top && !event.target.style.width && !event.target.style.height) + { //Support for CocoonJS fullscreen scale modes touchData.global.x = touchEvent.clientX; touchData.global.y = touchEvent.clientY; @@ -690,15 +775,19 @@ var length = this.interactiveItems.length; - for (var j = 0; j < length; j++) { + for (var j = 0; j < length; j++) + { var item = this.interactiveItems[j]; - if (item.touchstart || item.tap) { + if (item.touchstart || item.tap) + { item.__hit = this.hitTest(item, touchData); - if (item.__hit) { + if (item.__hit) + { //call the function! - if (item.touchstart) { + if (item.touchstart) + { item.touchstart(touchData); } @@ -706,7 +795,8 @@ item.__touchData = item.__touchData || {}; item.__touchData[touchEvent.identifier] = touchData; - if (!item.interactiveChildren) { + if (!item.interactiveChildren) + { break; } } @@ -721,31 +811,37 @@ * @param event {Event} The DOM event of a touch ending on the renderer view * @private */ -InteractionManager.prototype.onTouchEnd = function (event) { - if (this.dirty) { +InteractionManager.prototype.onTouchEnd = function (event) +{ + if (this.dirty) + { this.rebuildInteractiveGraph(); } var rect = this.interactionDOMElement.getBoundingClientRect(); var changedTouches = event.changedTouches; - for (var i=0; i < changedTouches.length; i++) { + for (var i=0; i < changedTouches.length; i++) + { var touchEvent = changedTouches[i]; var touchData = this.touches[touchEvent.identifier]; var up = false; touchData.global.x = ( (touchEvent.clientX - rect.left) * (this.interactionDOMElement.width / rect.width) ) / this.resolution; touchData.global.y = ( (touchEvent.clientY - rect.top) * (this.interactionDOMElement.height / rect.height) ) / this.resolution; - if (navigator.isCocoonJS && !rect.left && !rect.top && !event.target.style.width && !event.target.style.height) { + if (navigator.isCocoonJS && !rect.left && !rect.top && !event.target.style.width && !event.target.style.height) + { //Support for CocoonJS fullscreen scale modes touchData.global.x = touchEvent.clientX; touchData.global.y = touchEvent.clientY; } var length = this.interactiveItems.length; - for (var j = 0; j < length; j++) { + for (var j = 0; j < length; j++) + { var item = this.interactiveItems[j]; - if (item.__touchData && item.__touchData[touchEvent.identifier]) { + if (item.__touchData && item.__touchData[touchEvent.identifier]) + { item.__hit = this.hitTest(item, item.__touchData[touchEvent.identifier]); @@ -753,20 +849,27 @@ touchData.originalEvent = event; // hitTest?? - if (item.touchend || item.tap) { - if (item.__hit && !up) { - if (item.touchend) { + if (item.touchend || item.tap) + { + if (item.__hit && !up) + { + if (item.touchend) + { item.touchend(touchData); } - if (item.__isDown && item.tap) { + if (item.__isDown && item.tap) + { item.tap(touchData); } - if (!item.interactiveChildren) { + if (!item.interactiveChildren) + { up = true; } } - else { - if (item.__isDown && item.touchendoutside) { + else + { + if (item.__isDown && item.touchendoutside) + { item.touchendoutside(touchData); } } diff --git a/src/loaders/AssetLoader.js b/src/loaders/AssetLoader.js index 20da0cf..c4dba1c 100644 --- a/src/loaders/AssetLoader.js +++ b/src/loaders/AssetLoader.js @@ -21,7 +21,8 @@ * data formats include 'xml' and 'fnt'. * @param crossorigin {boolean} Whether requests should be treated as crossorigin */ -function AssetLoader(assetURLs, crossorigin) { +function AssetLoader(assetURLs, crossorigin) +{ /** * The array of asset URLs that are going to be loaded * @@ -76,16 +77,19 @@ * * @param str {string} the name of the asset */ -AssetLoader.prototype._getDataType = function (str) { +AssetLoader.prototype._getDataType = function (str) +{ var test = 'data:'; var start = str.slice(0, test.length).toLowerCase(); - if (start === test) { + if (start === test) + { var data = str.slice(test.length); var sepIdx = data.indexOf(','); // check for malformed data URI scheme - if (sepIdx === -1) { + if (sepIdx === -1) + { return null; } @@ -94,7 +98,8 @@ //We might need to handle some special cases here... //standardize text/plain to 'txt' file extension - if (!info || info.toLowerCase() === 'text/plain') { + if (!info || info.toLowerCase() === 'text/plain') + { return 'txt'; } @@ -109,27 +114,32 @@ * Starts loading the assets sequentially * */ -AssetLoader.prototype.load = function () { +AssetLoader.prototype.load = function () +{ var scope = this; - function onLoad(evt) { + function onLoad(evt) + { scope.onAssetLoaded(evt.data.content); } this.loadCount = this.assetURLs.length; - for (var i=0; i < this.assetURLs.length; i++) { + for (var i=0; i < this.assetURLs.length; i++) + { var fileName = this.assetURLs[i]; //first see if we have a data URI scheme.. var fileType = this._getDataType(fileName); //if not, assume it's a file URI - if (!fileType) { + if (!fileType) + { fileType = fileName.split('?').shift().split('.').pop().toLowerCase(); } var Constructor = this.loadersByType[fileType]; - if (!Constructor) { + if (!Constructor) + { throw new Error(fileType + ' is an unsupported file type'); } @@ -145,18 +155,22 @@ * * @private */ -AssetLoader.prototype.onAssetLoaded = function (loader) { +AssetLoader.prototype.onAssetLoaded = function (loader) +{ this.loadCount--; this.emit('onProgress', { content: this, loader: loader }); - if (this.onProgress) { + if (this.onProgress) + { this.onProgress(loader); } - if (!this.loadCount) { + if (!this.loadCount) + { this.emit('onComplete', { content: this }); - if (this.onComplete) { + if (this.onComplete) + { this.onComplete(); } } diff --git a/src/loaders/AtlasLoader.js b/src/loaders/AtlasLoader.js index 5eda286..3aec9e2 100644 --- a/src/loaders/AtlasLoader.js +++ b/src/loaders/AtlasLoader.js @@ -15,7 +15,8 @@ * @param url {String} The url of the JSON file * @param crossorigin {boolean} Whether requests should be treated as crossorigin */ -function AtlasLoader(url, crossorigin) { +function AtlasLoader(url, crossorigin) +{ this.url = url; this.baseUrl = url.replace(/[^\/]*$/, ''); this.crossorigin = crossorigin; @@ -31,13 +32,15 @@ * Starts loading the JSON file * */ -AtlasLoader.prototype.load = function () { +AtlasLoader.prototype.load = function () +{ this.ajaxRequest = new core.utils.AjaxRequest(); this.ajaxRequest.onreadystatechange = this.onAtlasLoaded.bind(this); this.ajaxRequest.open('GET', this.url, true); - if (this.ajaxRequest.overrideMimeType) { + if (this.ajaxRequest.overrideMimeType) + { this.ajaxRequest.overrideMimeType('application/json'); } @@ -49,9 +52,12 @@ * * @private */ -AtlasLoader.prototype.onAtlasLoaded = function () { - if (this.ajaxRequest.readyState === 4) { - if (this.ajaxRequest.status === 200 || window.location.href.indexOf('http') === -1) { +AtlasLoader.prototype.onAtlasLoaded = function () +{ + if (this.ajaxRequest.readyState === 4) + { + if (this.ajaxRequest.status === 200 || window.location.href.indexOf('http') === -1) + { this.atlas = { meta : { image : [] @@ -70,34 +76,44 @@ selfOnLoaded = this.onLoaded.bind(this); // parser without rotation support yet! - for (i = 0; i < result.length; i++) { + for (i = 0; i < result.length; i++) + { result[i] = result[i].replace(/^\s+|\s+$/g, ''); - if (result[i] === '') { + if (result[i] === '') + { nameInNextLine = i+1; } - if (result[i].length > 0) { - if (nameInNextLine === i) { + if (result[i].length > 0) + { + if (nameInNextLine === i) + { this.atlas.meta.image.push(result[i]); currentImageId = this.atlas.meta.image.length - 1; this.atlas.frames.push({}); lineCount = -3; - } else if (lineCount > 0) { - if (lineCount % 7 === 1) { // frame name - if (currentFrame != null) { //jshint ignore:line + } else if (lineCount > 0) + { + if (lineCount % 7 === 1) + { // frame name + if (currentFrame != null) + { //jshint ignore:line this.atlas.frames[currentImageId][currentFrame.name] = currentFrame; } currentFrame = { name: result[i], frame : {} }; } else { var text = result[i].split(' '); - if (lineCount % 7 === 3) { // position + if (lineCount % 7 === 3) + { // position currentFrame.frame.x = Number(text[1].replace(',', '')); currentFrame.frame.y = Number(text[2]); - } else if (lineCount % 7 === 4) { // size + } else if (lineCount % 7 === 4) + { // size currentFrame.frame.w = Number(text[1].replace(',', '')); currentFrame.frame.h = Number(text[2]); - } else if (lineCount % 7 === 5) { // real size + } else if (lineCount % 7 === 5) + { // real size var realSize = { x : 0, y : 0, @@ -105,7 +121,8 @@ h : Number(text[2]) }; - if (realSize.w > currentFrame.frame.w || realSize.h > currentFrame.frame.h) { + if (realSize.w > currentFrame.frame.w || realSize.h > currentFrame.frame.h) + { currentFrame.trimmed = true; currentFrame.realSize = realSize; } else { @@ -118,28 +135,34 @@ } } - if (currentFrame != null) { //jshint ignore:line + if (currentFrame != null) + { //jshint ignore:line this.atlas.frames[currentImageId][currentFrame.name] = currentFrame; } - if (this.atlas.meta.image.length > 0) { + if (this.atlas.meta.image.length > 0) + { this.images = []; - for (j = 0; j < this.atlas.meta.image.length; j++) { + for (j = 0; j < this.atlas.meta.image.length; j++) + { // sprite sheet var textureUrl = this.baseUrl + this.atlas.meta.image[j]; var frameData = this.atlas.frames[j]; this.images.push(new ImageLoader(textureUrl, this.crossorigin)); - for (i in frameData) { + for (i in frameData) + { var rect = frameData[i].frame; - if (rect) { + if (rect) + { core.utils.TextureCache[i] = new core.Texture(this.images[j].texture.baseTexture, { x: rect.x, y: rect.y, width: rect.w, height: rect.h }); - if (frameData[i].trimmed) { + if (frameData[i].trimmed) + { core.utils.TextureCache[i].realSize = frameData[i].realSize; // trim in pixi not supported yet, todo update trim properties if it is done ... core.utils.TextureCache[i].trim.x = 0; @@ -150,7 +173,8 @@ } this.currentImageId = 0; - for (j = 0; j < this.images.length; j++) { + for (j = 0; j < this.images.length; j++) + { this.images[j].on('loaded', selfOnLoaded); } this.images[this.currentImageId].load(); @@ -170,8 +194,10 @@ * * @private */ -AtlasLoader.prototype.onLoaded = function () { - if (this.images.length - 1 > this.currentImageId) { +AtlasLoader.prototype.onLoaded = function () +{ + if (this.images.length - 1 > this.currentImageId) + { this.currentImageId++; this.images[this.currentImageId].load(); } else { @@ -185,6 +211,7 @@ * * @private */ -AtlasLoader.prototype.onError = function () { +AtlasLoader.prototype.onError = function () +{ this.emit('error', { content: this }); }; diff --git a/src/loaders/BitmapFontLoader.js b/src/loaders/BitmapFontLoader.js index 8641760..13e5c1b 100644 --- a/src/loaders/BitmapFontLoader.js +++ b/src/loaders/BitmapFontLoader.js @@ -13,7 +13,8 @@ * @param url {String} The url of the sprite sheet JSON file * @param crossorigin {boolean} Whether requests should be treated as crossorigin */ -function BitmapFontLoader(url, crossorigin) { +function BitmapFontLoader(url, crossorigin) +{ /** * The url of the bitmap font data * @@ -54,13 +55,15 @@ * Loads the XML font data * */ -BitmapFontLoader.prototype.load = function () { +BitmapFontLoader.prototype.load = function () +{ this.ajaxRequest = new core.utils.AjaxRequest(); this.ajaxRequest.onreadystatechange = this.onXMLLoaded.bind(this); this.ajaxRequest.open('GET', this.url, true); - if (this.ajaxRequest.overrideMimeType) { + if (this.ajaxRequest.overrideMimeType) + { this.ajaxRequest.overrideMimeType('application/xml'); } @@ -72,12 +75,17 @@ * * @private */ -BitmapFontLoader.prototype.onXMLLoaded = function () { - if (this.ajaxRequest.readyState === 4) { - if (this.ajaxRequest.status === 200 || window.location.protocol.indexOf('http') === -1) { +BitmapFontLoader.prototype.onXMLLoaded = function () +{ + if (this.ajaxRequest.readyState === 4) + { + if (this.ajaxRequest.status === 200 || window.location.protocol.indexOf('http') === -1) + { var responseXML = this.ajaxRequest.responseXML; - if (!responseXML || /MSIE 9/i.test(navigator.userAgent) || navigator.isCocoonJS) { - if (typeof(window.DOMParser) === 'function') { + if (!responseXML || /MSIE 9/i.test(navigator.userAgent) || navigator.isCocoonJS) + { + if (typeof(window.DOMParser) === 'function') + { var domparser = new DOMParser(); responseXML = domparser.parseFromString(this.ajaxRequest.responseText, 'text/xml'); } else { @@ -102,7 +110,8 @@ //parse letters var letters = responseXML.getElementsByTagName('char'); - for (var i = 0; i < letters.length; i++) { + for (var i = 0; i < letters.length; i++) + { var charCode = parseInt(letters[i].getAttribute('id'), 10); var textureRect = new core.math.Rectangle( @@ -124,7 +133,8 @@ //parse kernings var kernings = responseXML.getElementsByTagName('kerning'); - for (i = 0; i < kernings.length; i++) { + for (i = 0; i < kernings.length; i++) + { var first = parseInt(kernings[i].getAttribute('first'), 10); var second = parseInt(kernings[i].getAttribute('second'), 10); var amount = parseInt(kernings[i].getAttribute('amount'), 10); @@ -146,6 +156,7 @@ * * @private */ -BitmapFontLoader.prototype.onLoaded = function () { +BitmapFontLoader.prototype.onLoaded = function () +{ this.emit('loaded', { content: this }); }; diff --git a/src/loaders/ImageLoader.js b/src/loaders/ImageLoader.js index e3ff493..16ee7c8 100644 --- a/src/loaders/ImageLoader.js +++ b/src/loaders/ImageLoader.js @@ -11,7 +11,8 @@ * @param url {String} The url of the image * @param crossorigin {boolean} Whether requests should be treated as crossorigin */ -function ImageLoader(url, crossorigin) { +function ImageLoader(url, crossorigin) +{ /** * The texture being loaded * @@ -39,12 +40,15 @@ * Loads image or takes it from cache * */ -ImageLoader.prototype.load = function () { - if (!this.texture.baseTexture.hasLoaded) { +ImageLoader.prototype.load = function () +{ + if (!this.texture.baseTexture.hasLoaded) + { this.texture.baseTexture.on('loaded', this.onLoaded.bind(this)); this.texture.baseTexture.on('error', this.onError.bind(this)); } - else { + else + { this.onLoaded(); } }; @@ -54,7 +58,8 @@ * * @private */ -ImageLoader.prototype.onLoaded = function () { +ImageLoader.prototype.onLoaded = function () +{ this.emit('loaded', { content: this }); }; @@ -64,7 +69,8 @@ * @method onError * @private */ -ImageLoader.prototype.onError = function () { +ImageLoader.prototype.onError = function () +{ this.emit('error', { content: this }); }; @@ -75,15 +81,18 @@ * @param frameHeight {number} height of each frame * @param textureName {String} if given, the frames will be cached in - format */ -ImageLoader.prototype.loadFramedSpriteSheet = function (frameWidth, frameHeight, textureName) { +ImageLoader.prototype.loadFramedSpriteSheet = function (frameWidth, frameHeight, textureName) +{ this.frames = []; var cols = Math.floor(this.texture.width / frameWidth); var rows = Math.floor(this.texture.height / frameHeight); var i=0; - for (var y = 0; y < rows; ++y) { - for (var x = 0; x < cols; ++x, ++i) { + for (var y = 0; y < rows; ++y) + { + for (var x = 0; x < cols; ++x, ++i) + { var texture = new core.Texture( this.texture.baseTexture, new core.math.Rectangle( @@ -96,7 +105,8 @@ this.frames.push(texture); - if (textureName) { + if (textureName) + { core.utils.TextureCache[textureName + '-' + i] = texture; } } diff --git a/src/loaders/JsonLoader.js b/src/loaders/JsonLoader.js index 3279f40..7aabeb4 100644 --- a/src/loaders/JsonLoader.js +++ b/src/loaders/JsonLoader.js @@ -14,7 +14,8 @@ * @param url {String} The url of the JSON file * @param crossorigin {boolean} Whether requests should be treated as crossorigin */ -function JsonLoader(url, crossorigin) { +function JsonLoader(url, crossorigin) +{ /** * The url of the bitmap font data * @@ -56,8 +57,10 @@ * Loads the JSON data * */ -JsonLoader.prototype.load = function () { - if (window.XDomainRequest && this.crossorigin) { +JsonLoader.prototype.load = function () +{ + if (window.XDomainRequest && this.crossorigin) + { this.ajaxRequest = new window.XDomainRequest(); // XDomainRequest has a few quirks. Occasionally it will abort requests @@ -68,15 +71,19 @@ this.ajaxRequest.onerror = this.onError.bind(this); this.ajaxRequest.ontimeout = this.onError.bind(this); - this.ajaxRequest.onprogress = function () {}; + this.ajaxRequest.onprogress = function () + {}; this.ajaxRequest.onload = this.onJSONLoaded.bind(this); } - else { - if (window.XMLHttpRequest) { + else + { + if (window.XMLHttpRequest) + { this.ajaxRequest = new window.XMLHttpRequest(); } - else { + else + { this.ajaxRequest = new window.ActiveXObject('Microsoft.XMLHTTP'); } @@ -93,8 +100,10 @@ * * @private */ -JsonLoader.prototype.onReadyStateChanged = function () { - if (this.ajaxRequest.readyState === 4 && (this.ajaxRequest.status === 200 || window.location.href.indexOf('http') === -1)) { +JsonLoader.prototype.onReadyStateChanged = function () +{ + if (this.ajaxRequest.readyState === 4 && (this.ajaxRequest.status === 200 || window.location.href.indexOf('http') === -1)) + { this.onJSONLoaded(); } }; @@ -104,15 +113,18 @@ * * @private */ -JsonLoader.prototype.onJSONLoaded = function () { - if (!this.ajaxRequest.responseText) { +JsonLoader.prototype.onJSONLoaded = function () +{ + if (!this.ajaxRequest.responseText) + { this.onError(); return; } this.json = JSON.parse(this.ajaxRequest.responseText); - if (this.json.frames) { + if (this.json.frames) + { // sprite sheet var textureUrl = this.baseUrl + this.json.meta.image; var image = new ImageLoader(textureUrl, this.crossorigin); @@ -122,16 +134,19 @@ image.addEventListener('loaded', this.onLoaded.bind(this)); image.addEventListener('error', this.onError.bind(this)); - for (var i in frameData) { + for (var i in frameData) + { var rect = frameData[i].frame; - if (rect) { + if (rect) + { var textureSize = new core.math.Rectangle(rect.x, rect.y, rect.w, rect.h); var crop = textureSize.clone(); var trim = null; // Check to see if the sprite is trimmed - if (frameData[i].trimmed) { + if (frameData[i].trimmed) + { var actualSize = frameData[i].sourceSize; var realSize = frameData[i].spriteSourceSize; trim = new core.math.Rectangle(realSize.x, realSize.y, actualSize.w, actualSize.h); @@ -143,12 +158,15 @@ image.load(); } - else if (this.json.bones) { + else if (this.json.bones) + { // check if the json was loaded before - if (core.utils.AnimCache[this.url]) { + if (core.utils.AnimCache[this.url]) + { this.onLoaded(); } - else { + else + { /** * use a bit of hackery to load the atlas file, here we assume that the .json, .atlas and .png files * that correspond to the spine file are in the same base URL and that the .json and .atlas files @@ -159,9 +177,11 @@ // save a copy of the current object for future reference // var originalLoader = this; // before loading the file, replace the "onJSONLoaded" function for our own // - atlasLoader.onJSONLoaded = function () { + atlasLoader.onJSONLoaded = function () + { // at this point "this" points at the atlasLoader (JsonLoader) instance // - if (!this.ajaxRequest.responseText) { + if (!this.ajaxRequest.responseText) + { this.onError(); // FIXME: hmm, this is funny because we are not responding to errors yet return; } @@ -179,14 +199,18 @@ originalLoader.spineAtlas = spineAtlas; originalLoader.spineAtlasLoader = atlasLoader; // wait for textures to finish loading if needed - if (textureLoader.loadingCount > 0) { - textureLoader.addEventListener('loadedBaseTexture', function (evt){ - if (evt.content.content.loadingCount <= 0) { + if (textureLoader.loadingCount > 0) + { + textureLoader.addEventListener('loadedBaseTexture', function (evt) + { + if (evt.content.content.loadingCount <= 0) + { originalLoader.onLoaded(); } }); } - else { + else + { originalLoader.onLoaded(); } }; @@ -194,7 +218,8 @@ atlasLoader.load(); } } - else { + else + { this.onLoaded(); } }; @@ -204,7 +229,8 @@ * * @private */ -JsonLoader.prototype.onLoaded = function () { +JsonLoader.prototype.onLoaded = function () +{ this.loaded = true; this.dispatchEvent({ type: 'loaded', @@ -217,7 +243,8 @@ * * @private */ -JsonLoader.prototype.onError = function () { +JsonLoader.prototype.onError = function () +{ this.dispatchEvent({ type: 'error', diff --git a/src/loaders/SpineLoader.js b/src/loaders/SpineLoader.js index 51aaddb..69bae21 100644 --- a/src/loaders/SpineLoader.js +++ b/src/loaders/SpineLoader.js @@ -24,7 +24,8 @@ * @param url {String} The url of the JSON file * @param crossorigin {boolean} Whether requests should be treated as crossorigin */ -function SpineLoader(url, crossorigin) { +function SpineLoader(url, crossorigin) +{ /** * The url of the bitmap font data * @@ -57,11 +58,13 @@ * Loads the JSON data * */ -SpineLoader.prototype.load = function () { +SpineLoader.prototype.load = function () +{ var scope = this; var jsonLoader = new JsonLoader(this.url, this.crossorigin); - jsonLoader.on('loaded', function (event) { + jsonLoader.on('loaded', function (event) + { scope.json = event.data.content.json; scope.onLoaded(); }); @@ -74,7 +77,8 @@ * * @private */ -SpineLoader.prototype.onLoaded = function () { +SpineLoader.prototype.onLoaded = function () +{ this.loaded = true; this.emit('loaded', { content: this }); }; diff --git a/src/loaders/SpineTextureLoader.js b/src/loaders/SpineTextureLoader.js index 61c51c0..c09a548 100644 --- a/src/loaders/SpineTextureLoader.js +++ b/src/loaders/SpineTextureLoader.js @@ -9,7 +9,8 @@ * @param basePath {string} Tha base path where to look for the images to be loaded * @param crossorigin {boolean} Whether requests should be treated as crossorigin */ -function SpineTextureLoader(basePath, crossorigin) { +function SpineTextureLoader(basePath, crossorigin) +{ this.basePath = basePath; this.crossorigin = crossorigin; this.loadingCount = 0; @@ -26,12 +27,15 @@ * @param page {spine.AtlasPage} Atlas page to which texture belongs * @param file {string} The file to load, this is just the file path relative to the base path configured in the constructor */ -SpineTextureLoader.prototype.load = function (page, file) { +SpineTextureLoader.prototype.load = function (page, file) +{ page.rendererObject = core.BaseTexture.fromImage(this.basePath + '/' + file, this.crossorigin); - if (!page.rendererObject.hasLoaded) { + if (!page.rendererObject.hasLoaded) + { var scope = this; ++scope.loadingCount; - page.rendererObject.addEventListener('loaded', function (){ + page.rendererObject.addEventListener('loaded', function () + { --scope.loadingCount; scope.dispatchEvent({ type: 'loadedBaseTexture', @@ -46,6 +50,7 @@ * * @param texture {BaseTexture} Texture object to destroy */ -SpineTextureLoader.prototype.unload = function (texture) { +SpineTextureLoader.prototype.unload = function (texture) +{ texture.destroy(true); }; diff --git a/src/core/display/DisplayObject.js b/src/core/display/DisplayObject.js index 66ebc3c..20e778c 100644 --- a/src/core/display/DisplayObject.js +++ b/src/core/display/DisplayObject.js @@ -7,7 +7,8 @@ * @class * @namespace PIXI */ -function DisplayObject() { +function DisplayObject() +{ /** * The coordinate of the object relative to the local coordinates of the parent. * @@ -152,10 +153,12 @@ * @memberof DisplayObject# */ x: { - get: function () { + get: function () + { return this.position.x; }, - set: function (value) { + set: function (value) + { this.position.x = value; } }, @@ -167,10 +170,12 @@ * @memberof DisplayObject# */ y: { - get: function () { + get: function () + { return this.position.y; }, - set: function (value) { + set: function (value) + { this.position.y = value; } }, @@ -183,11 +188,13 @@ * @readonly */ worldVisible: { - get: function () { + get: function () + { var item = this; do { - if (!item.visible) { + if (!item.visible) + { return false; } @@ -207,17 +214,21 @@ * @memberof DisplayObject# */ mask: { - get: function () { + get: function () + { return this._mask; }, - set: function (value) { - if (this._mask) { + set: function (value) + { + if (this._mask) + { this._mask.isMask = false; } this._mask = value; - if (this._mask) { + if (this._mask) + { this._mask.isMask = true; } } @@ -232,18 +243,23 @@ * @memberof DisplayObject# */ filters: { - get: function () { + get: function () + { return this._filters; }, - set: function (value) { - if (value) { + set: function (value) + { + if (value) + { // now put all the passes in one place.. var passes = []; - for (var i = 0; i < value.length; i++) { + for (var i = 0; i < value.length; i++) + { var filterPasses = value[i].passes; - for (var j = 0; j < filterPasses.length; j++) { + for (var j = 0; j < filterPasses.length; j++) + { passes.push(filterPasses[j]); } } @@ -264,8 +280,9 @@ * * @private */ -DisplayObject.prototype.updateTransform = function () { - +DisplayObject.prototype.updateTransform = function () +{ + // create some matrix refs for easy access var pt = this.parent.worldTransform; var wt = this.worldTransform; @@ -274,9 +291,11 @@ var a, b, c, d, tx, ty; // so if rotation is between 0 then we can simplify the multiplication process.. - if (this.rotation % math.PI_2) { + if (this.rotation % math.PI_2) + { // 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) { + if (this.rotation !== this.rotationCache) + { this.rotationCache = this.rotation; this._sr = Math.sin(this.rotation); this._cr = Math.cos(this.rotation); @@ -291,7 +310,8 @@ ty = this.position.y; // check for pivot.. not often used so geared towards that fact! - if (this.pivot.x || this.pivot.y) { + 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; } @@ -304,7 +324,8 @@ wt.tx = tx * pt.a + ty * pt.c + pt.tx; wt.ty = tx * pt.b + ty * pt.d + pt.ty; } - else { + else + { // lets do the fast version as we know there is no rotation.. a = this.scale.x; d = this.scale.y; @@ -333,7 +354,8 @@ * @param matrix {Matrix} * @return {Rectangle} the rectangular bounding area */ -DisplayObject.prototype.getBounds = function (/* matrix */) { +DisplayObject.prototype.getBounds = function (/* matrix */) +{ return math.Rectangle.EMPTY; }; @@ -342,7 +364,8 @@ * * @return {Rectangle} the rectangular bounding area */ -DisplayObject.prototype.getLocalBounds = function () { +DisplayObject.prototype.getLocalBounds = function () +{ return this.getBounds(math.Matrix.IDENTITY); }; @@ -352,7 +375,8 @@ * @param position {Point} The world origin to calculate from * @return {Point} A point object representing the position of this object */ -DisplayObject.prototype.toGlobal = function (position) { +DisplayObject.prototype.toGlobal = function (position) +{ // don't need to u[date the lot this.displayObjectUpdateTransform(); return this.worldTransform.apply(position); @@ -365,8 +389,10 @@ * @param [from] {DisplayObject} The DisplayObject to calculate the global position from * @return {Point} A point object representing the position of this object */ -DisplayObject.prototype.toLocal = function (position, from) { - if (from) { +DisplayObject.prototype.toLocal = function (position, from) +{ + if (from) + { position = from.toGlobal(position); } @@ -381,7 +407,8 @@ * @param renderer {WebGLRenderer} The renderer * @private */ -DisplayObject.prototype.renderWebGL = function (/* renderer */) { +DisplayObject.prototype.renderWebGL = function (/* renderer */) +{ // OVERWRITE; }; @@ -391,6 +418,7 @@ * @param renderer {CanvasRenderer} The renderer * @private */ -DisplayObject.prototype.renderCanvas = function (/* renderer */) { +DisplayObject.prototype.renderCanvas = function (/* renderer */) +{ // OVERWRITE; }; diff --git a/src/core/display/DisplayObjectContainer.js b/src/core/display/DisplayObjectContainer.js index 689f40b..4625ee8 100644 --- a/src/core/display/DisplayObjectContainer.js +++ b/src/core/display/DisplayObjectContainer.js @@ -12,7 +12,8 @@ * @extends DisplayObject * @namespace PIXI */ -function DisplayObjectContainer() { +function DisplayObjectContainer() +{ DisplayObject.call(this); /** @@ -47,17 +48,21 @@ * @memberof DisplayObjectContainer# */ width: { - get: function () { + get: function () + { return this.scale.x * this.getLocalBounds().width; }, - set: function (value) { + set: function (value) + { var width = this.getLocalBounds().width; - if(width !== 0) { + if(width !== 0) + { this.scale.x = value / width; } - else { + else + { this.scale.x = 1; } @@ -73,17 +78,21 @@ * @memberof DisplayObjectContainer# */ height: { - get: function () { + get: function () + { return this.scale.y * this.getLocalBounds().height; }, - set: function (value) { + set: function (value) + { var height = this.getLocalBounds().height; - if (height !== 0) { + if (height !== 0) + { this.scale.y = value / height ; } - else { + else + { this.scale.y = 1; } @@ -100,18 +109,23 @@ * @memberof DisplayObject# */ cacheAsBitmap: { - get: function () { + get: function () + { return this._cacheAsBitmap; }, - set: function (value) { - if (this._cacheAsBitmap === value) { + set: function (value) + { + if (this._cacheAsBitmap === value) + { return; } - if (value) { + if (value) + { this._generateCachedSprite(); } - else { + else + { this._destroyCachedSprite(); } @@ -126,7 +140,8 @@ * @param child {DisplayObject} The DisplayObject to add to the container * @return {DisplayObject} The child that was added. */ -DisplayObjectContainer.prototype.addChild = function (child) { +DisplayObjectContainer.prototype.addChild = function (child) +{ return this.addChildAt(child, this.children.length); }; @@ -137,14 +152,18 @@ * @param index {Number} The index to place the child in * @return {DisplayObject} The child that was added. */ -DisplayObjectContainer.prototype.addChildAt = function (child, index) { +DisplayObjectContainer.prototype.addChildAt = function (child, index) +{ // prevent adding self as child - if (child === this) { + if (child === this) + { return; } - if (index >= 0 && index <= this.children.length) { - if (child.parent) { + if (index >= 0 && index <= this.children.length) + { + if (child.parent) + { child.parent.removeChild(child); } @@ -154,7 +173,8 @@ return child; } - else { + else + { throw new Error(child + 'addChildAt: The index '+ index +' supplied is out of bounds ' + this.children.length); } }; @@ -165,15 +185,18 @@ * @param child {DisplayObject} * @param child2 {DisplayObject} */ -DisplayObjectContainer.prototype.swapChildren = function (child, child2) { - if (child === child2) { +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) { + if (index1 < 0 || index2 < 0) + { throw new Error('swapChildren: Both the supplied DisplayObjects must be a child of the caller.'); } @@ -187,10 +210,12 @@ * @param child {DisplayObject} The DisplayObject instance to identify * @return {Number} The index position of the child display object to identify */ -DisplayObjectContainer.prototype.getChildIndex = function (child) { +DisplayObjectContainer.prototype.getChildIndex = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { throw new Error('The supplied DisplayObject must be a child of the caller'); } @@ -203,8 +228,10 @@ * @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 */ -DisplayObjectContainer.prototype.setChildIndex = function (child, index) { - if (index < 0 || index >= this.children.length) { +DisplayObjectContainer.prototype.setChildIndex = function (child, index) +{ + if (index < 0 || index >= this.children.length) + { throw new Error('The supplied index is out of bounds'); } @@ -220,8 +247,10 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child at the given index, if any. */ -DisplayObjectContainer.prototype.getChildAt = function (index) { - if (index < 0 || index >= this.children.length) { +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'); } @@ -234,10 +263,12 @@ * @param child {DisplayObject} The DisplayObject to remove * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChild = function (child) { +DisplayObjectContainer.prototype.removeChild = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { return; } @@ -250,7 +281,8 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChildAt = function (index) { +DisplayObjectContainer.prototype.removeChildAt = function (index) +{ var child = this.getChildAt(index); child.parent = null; @@ -265,24 +297,29 @@ * @param beginIndex {Number} The beginning position. Default value is 0. * @param endIndex {Number} The ending position. Default value is size of the container. */ -DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) { +DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) +{ var begin = beginIndex || 0; var end = typeof endIndex === 'number' ? endIndex : this.children.length; var range = end - begin; - if (range > 0 && range <= end) { + if (range > 0 && range <= end) + { var removed = this.children.splice(begin, range); - for (var i = 0; i < removed.length; ++i) { + for (var i = 0; i < removed.length; ++i) + { removed[i].parent = null; } return removed; } - else if (range === 0 && this.children.length === 0) { + else if (range === 0 && this.children.length === 0) + { return []; } - else { + else + { throw new RangeError('removeChildren: numeric values are outside the acceptable range.'); } }; @@ -291,7 +328,8 @@ * Generates and updates the cached sprite for this object. * */ -DisplayObjectContainer.prototype.updateCachedSprite = function () { +DisplayObjectContainer.prototype.updateCachedSprite = function () +{ this._generateCachedSprite(); }; @@ -304,7 +342,8 @@ * @param renderer {CanvasRenderer|WebGLRenderer} The renderer used to generate the texture. * @return {Texture} a texture of the graphics object */ -DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) { +DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) +{ var bounds = this.getLocalBounds(); var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0, renderer, scaleMode, resolution); @@ -322,18 +361,22 @@ * * @private */ -DisplayObjectContainer.prototype.updateTransform = function () { - if (!this.visible) { +DisplayObjectContainer.prototype.updateTransform = function () +{ + if (!this.visible) + { return; } this.displayObjectUpdateTransform(); - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { return; } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } }; @@ -346,8 +389,10 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getBounds = function () { - if (this.children.length === 0) { +DisplayObjectContainer.prototype.getBounds = function () +{ + if (this.children.length === 0) + { return math.Rectangle.EMPTY; } @@ -365,10 +410,12 @@ var childVisible = false; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -386,7 +433,8 @@ maxY = maxY > childMaxY ? maxY : childMaxY; } - if (!childVisible) { + if (!childVisible) + { return math.Rectangle.EMPTY; } @@ -407,12 +455,14 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getLocalBounds = function () { +DisplayObjectContainer.prototype.getLocalBounds = function () +{ var matrixCache = this.worldTransform; this.worldTransform = math.Matrix.IDENTITY; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } @@ -428,13 +478,16 @@ * * @param renderer {WebGLRenderer} The renderer */ -DisplayObjectContainer.prototype.renderWebGL = function (renderer) { +DisplayObjectContainer.prototype.renderWebGL = function (renderer) +{ // if the object is not visible or the alpha is 0 then no need to render this element - if (!this.visible || this.alpha <= 0) { + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } @@ -442,14 +495,17 @@ var i, j; // do a quick check to see if this element has a mask or a filter. - if (this._mask || this._filters) { + if (this._mask || this._filters) + { // push filter first as we need to ensure the stencil buffer is correct for any masking - if (this._filters) { + if (this._filters) + { renderer.spriteBatch.flush(); renderer.filterManager.pushFilter(this._filterBlock); } - if (this._mask) { + if (this._mask) + { renderer.spriteBatch.stop(); renderer.maskManager.pushMask(this.mask, renderer); renderer.spriteBatch.start(); @@ -459,36 +515,42 @@ this._renderWebGL(renderer); // now loop through the children and make sure they get rendered - for (i = 0, j = this.children.length; i < j; i++) { + for (i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderWebGL(renderer); } // time to stop the sprite batch as either a mask element or a filter draw will happen next renderer.spriteBatch.stop(); - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(this._mask, renderer); } - if (this._filters) { + if (this._filters) + { renderer.filterManager.popFilter(); } renderer.spriteBatch.start(); } - else { + else + { this._renderWebGL(renderer); // simple render children! - for (i = 0, j = this.children.length; i < j; ++i) { + for (i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderWebGL(renderer); } } }; -DisplayObjectContainer.prototype._renderWebGL = function (renderer) { +DisplayObjectContainer.prototype._renderWebGL = function (renderer) +{ // this is where content itself gets renderd.. @@ -499,25 +561,31 @@ * * @param renderer {CanvasRenderer} The renderer */ -DisplayObjectContainer.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0) { +DisplayObjectContainer.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -528,13 +596,16 @@ * @param renderer {WebGLRenderer|CanvasRenderer} The renderer * @private */ -DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) { +DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) +{ this._cachedSprite.worldAlpha = this.worldAlpha; - if (renderer.gl) { + if (renderer.gl) + { this._cachedSprite.renderWebGL(renderer); } - else { + else + { this._cachedSprite.renderCanvas(renderer); } }; @@ -544,10 +615,12 @@ * * @private */ -DisplayObjectContainer.prototype._generateCachedSprite = function () { +DisplayObjectContainer.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { // TODO - RenderTexture now *requires* a renderer instance, so this is like broken // because `renderer` isn't actually in scope here :P var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0); @@ -555,7 +628,8 @@ this._cachedSprite = new Sprite(renderTexture); this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.texture.resize(bounds.width | 0, bounds.height | 0); } @@ -580,8 +654,10 @@ * * @private */ -DisplayObjectContainer.prototype._destroyCachedSprite = function () { - if (!this._cachedSprite) { +DisplayObjectContainer.prototype._destroyCachedSprite = function () +{ + if (!this._cachedSprite) + { return; } diff --git a/src/core/display/Sprite.js b/src/core/display/Sprite.js index 707da24..5862aef 100644 --- a/src/core/display/Sprite.js +++ b/src/core/display/Sprite.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param texture {Texture} The texture for this sprite */ -function Sprite(texture) { +function Sprite(texture) +{ DisplayObjectContainer.call(this); /** @@ -85,12 +86,14 @@ this.texture = texture || Texture.EMPTY; } -Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) { +Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) +{ DisplayObjectContainer.prototype.destroy.call(this); this.anchor = null; - if (destroyTexture) { + if (destroyTexture) + { this._texture.destroy(destroyBaseTexture); } @@ -111,10 +114,12 @@ * @memberof Sprite# */ width: { - get: function () { + get: function () + { return this.scale.x * this.texture.frame.width; }, - set: function (value) { + set: function (value) + { this.scale.x = value / this.texture.frame.width; this._width = value; } @@ -127,10 +132,12 @@ * @memberof Sprite# */ height: { - get: function () { + get: function () + { return this.scale.y * this.texture.frame.height; }, - set: function (value) { + set: function (value) + { this.scale.y = value / this.texture.frame.height; this._height = value; } @@ -143,23 +150,29 @@ * @memberof Sprite# */ texture: { - get: function () { + get: function () + { return this._texture; }, - set: function (value) { - if (this._texture === value) { + set: function (value) + { + if (this._texture === value) + { return; } this._texture = value; this.cachedTint = 0xFFFFFF; - if (value) { + if (value) + { // wait for the texture to load - if (value.baseTexture.hasLoaded) { + if (value.baseTexture.hasLoaded) + { this._onTextureUpdate(); } - else { + else + { value.once('update', this._onTextureUpdate.bind(this)); } } @@ -172,18 +185,22 @@ * * @private */ -Sprite.prototype._onTextureUpdate = function () { +Sprite.prototype._onTextureUpdate = function () +{ // so if _width is 0 then width was not set.. - if (this._width) { + if (this._width) + { this.scale.x = this._width / this.texture.frame.width; } - if (this._height) { + if (this._height) + { this.scale.y = this._height / this.texture.frame.height; } }; -Sprite.prototype._renderWebGL = function (renderer) { +Sprite.prototype._renderWebGL = function (renderer) +{ // this is where content gets renderd.. // watch this space for a little render state manager.. @@ -197,7 +214,8 @@ * @param matrix {Matrix} the transformation matrix of the sprite * @return {Rectangle} the framing rectangle */ -Sprite.prototype.getBounds = function (matrix) { +Sprite.prototype.getBounds = function (matrix) +{ var width = this.texture.frame.width; var height = this.texture.frame.height; @@ -224,11 +242,13 @@ if(b === 0 && c === 0) { // scale may be negative! - if (a < 0) { + if (a < 0) + { a *= -1; } - if (d < 0) { + if (d < 0) + { d *= -1; } @@ -293,28 +313,34 @@ * * @param renderer {CanvasRenderer} The renderer */ -Sprite.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) { +Sprite.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) + { return; } - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; renderer.context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } // Ignore null sources - if (this.texture.valid) { + if (this.texture.valid) + { var resolution = this.texture.baseTexture.resolution / renderer.resolution; renderer.context.globalAlpha = this.worldAlpha; // If smoothingEnabled is supported and we need to change the smoothing property for this texture - if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) { + if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) + { renderer.scaleMode = this.texture.baseTexture.scaleMode; renderer.context[renderer.smoothProperty] = (renderer.scaleMode === CONST.scaleModes.LINEAR); } @@ -324,7 +350,8 @@ var dy = (this.texture.trim ? this.texture.trim.y : 0) - (this.anchor.y * this.texture.trim.height); // Allow for pixel rounding - if (renderer.roundPixels) { + if (renderer.roundPixels) + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -337,7 +364,8 @@ dx = dx | 0; dy = dy | 0; } - else { + else + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -348,8 +376,10 @@ ); } - if (this.tint !== 0xFFFFFF) { - if (this.cachedTint !== this.tint) { + if (this.tint !== 0xFFFFFF) + { + if (this.cachedTint !== this.tint) + { this.cachedTint = this.tint; // TODO clean up caching - how to clean up the caches? @@ -368,7 +398,8 @@ this.texture.crop.height / resolution ); } - else { + else + { renderer.context.drawImage( this.texture.baseTexture.source, this.texture.crop.x, @@ -383,11 +414,13 @@ } } - for (var i = 0, j = this.children.length; i < j; i++) { + for (var i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -402,10 +435,12 @@ * @param frameId {String} The frame Id of the texture in the cache * @return {Sprite} A new Sprite using a texture from the texture cache matching the frameId */ -Sprite.fromFrame = function (frameId) { +Sprite.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache' + this); } @@ -420,6 +455,7 @@ * @param imageId {String} The image url of the texture * @return {Sprite} A new Sprite using a texture from the texture cache matching the image id */ -Sprite.fromImage = function (imageId, crossorigin, scaleMode) { +Sprite.fromImage = function (imageId, crossorigin, scaleMode) +{ return new Sprite(Texture.fromImage(imageId, crossorigin, scaleMode)); }; diff --git a/src/core/display/SpriteBatch.js b/src/core/display/SpriteBatch.js index 3187777..c196fef 100644 --- a/src/core/display/SpriteBatch.js +++ b/src/core/display/SpriteBatch.js @@ -12,7 +12,8 @@ * ```js * var container = new SpriteBatch(); * - * for(var i = 0; i < 100; ++i) { + * for(var i = 0; i < 100; ++i) + * { * var sprite = new PIXI.Sprite.fromImage("myImage.png"); * container.addChild(sprite); * } @@ -25,7 +26,8 @@ */ //TODO RENAME to PARTICLE CONTAINER? -function SpriteBatch() { +function SpriteBatch() +{ DisplayObjectContainer.call(this); } @@ -38,7 +40,8 @@ * * @private */ -SpriteBatch.prototype.updateTransform = function () { +SpriteBatch.prototype.updateTransform = function () +{ // TODO don't need to! this.displayObjectUpdateTransform(); // PIXI.DisplayObjectContainer.prototype.updateTransform.call( this ); @@ -50,8 +53,10 @@ * @param renderer {WebGLRenderer} The webgl renderer * @private */ -SpriteBatch.prototype.renderWebGL = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderWebGL = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -71,8 +76,10 @@ * @param renderer {CanvasRenderer} The canvas renderer * @private */ -SpriteBatch.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -84,10 +91,12 @@ this.displayObjectUpdateTransform(); - for (var i = 0; i < this.children.length; ++i) { + for (var i = 0; i < this.children.length; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -95,9 +104,11 @@ context.globalAlpha = this.worldAlpha * child.alpha; - if (child.rotation % (Math.PI * 2) === 0) { + if (child.rotation % (Math.PI * 2) === 0) + { // this is the fastest way to optimise! - if rotation is 0 then we can avoid any kind of setTransform call - if (isRotated) { + if (isRotated) + { context.setTransform( transform.a, transform.b, @@ -122,8 +133,10 @@ frame.height * child.scale.y ); } - else { - if (!isRotated) { + else + { + if (!isRotated) + { isRotated = true; } @@ -131,7 +144,8 @@ var childTransform = child.worldTransform; - if (renderer.roundPixels) { + if (renderer.roundPixels) + { context.setTransform( childTransform.a, childTransform.b, @@ -141,7 +155,8 @@ childTransform.ty | 0 ); } - else { + else + { context.setTransform( childTransform.a, childTransform.b, diff --git a/src/core/index.js b/src/core/index.js index 3954b6f..eb4a82b 100644 --- a/src/core/index.js +++ b/src/core/index.js @@ -58,11 +58,13 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRenderer: function (width, height, options, noWebGL) { + autoDetectRenderer: function (width, height, options, noWebGL) + { width = width || 800; height = height || 600; - if (!noWebGL && require('webgl-enabled')()) { + if (!noWebGL && require('webgl-enabled')()) + { return new core.WebGLRenderer(width, height, options); } @@ -87,7 +89,8 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRecommendedRenderer: function (width, height, options) { + autoDetectRecommendedRenderer: function (width, height, options) + { var isAndroid = /Android/i.test(navigator.userAgent); return core.autoDetectRenderer(width, height, options, isAndroid); diff --git a/src/core/math/Matrix.js b/src/core/math/Matrix.js index c2f87e2..2ff4848 100644 --- a/src/core/math/Matrix.js +++ b/src/core/math/Matrix.js @@ -10,7 +10,8 @@ * @class * @namespace PIXI */ -function Matrix() { +function Matrix() +{ /** * @member {number} * @default 1 @@ -63,7 +64,8 @@ * * @param array {number[]} The array that the matrix will be populated from. */ -Matrix.prototype.fromArray = function (array) { +Matrix.prototype.fromArray = function (array) +{ this.a = array[0]; this.b = array[1]; this.c = array[3]; @@ -78,14 +80,17 @@ * @param transpose {boolean} Whether we need to transpose the matrix or not * @return {number[]} the newly created array which contains the matrix */ -Matrix.prototype.toArray = function (transpose) { - if (!this.array) { +Matrix.prototype.toArray = function (transpose) +{ + if (!this.array) + { this.array = new Float32Array(9); } var array = this.array; - if (transpose) { + if (transpose) + { array[0] = this.a; array[1] = this.b; array[2] = 0; @@ -96,7 +101,8 @@ array[7] = this.ty; array[8] = 1; } - else { + else + { array[0] = this.a; array[1] = this.c; array[2] = this.tx; @@ -119,7 +125,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, transformed through this matrix */ -Matrix.prototype.apply = function (pos, newPos) { +Matrix.prototype.apply = function (pos, newPos) +{ newPos = newPos || new Point(); newPos.x = this.a * pos.x + this.c * pos.y + this.tx; @@ -136,7 +143,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, inverse-transformed through this matrix */ -Matrix.prototype.applyInverse = function (pos, newPos) { +Matrix.prototype.applyInverse = function (pos, newPos) +{ newPos = newPos || new Point(); var id = 1 / (this.a * this.d + this.c * -this.b); @@ -154,7 +162,8 @@ * @param {number} y * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.translate = function (x, y) { +Matrix.prototype.translate = function (x, y) +{ this.tx += x; this.ty += y; @@ -168,7 +177,8 @@ * @param {number} y The amount to scale vertically * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.scale = function (x, y) { +Matrix.prototype.scale = function (x, y) +{ this.a *= x; this.d *= y; this.c *= x; @@ -186,7 +196,8 @@ * @param {number} angle - The angle in radians. * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.rotate = function (angle) { +Matrix.prototype.rotate = function (angle) +{ var cos = Math.cos( angle ); var sin = Math.sin( angle ); @@ -210,7 +221,8 @@ * @param {Matrix} matrix * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.append = function (matrix) { +Matrix.prototype.append = function (matrix) +{ var a1 = this.a; var b1 = this.b; var c1 = this.c; @@ -232,7 +244,8 @@ * * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.identity = function () { +Matrix.prototype.identity = function () +{ this.a = 1; this.b = 0; this.c = 0; diff --git a/src/core/math/Point.js b/src/core/math/Point.js index 7565b2d..632f346 100644 --- a/src/core/math/Point.js +++ b/src/core/math/Point.js @@ -7,7 +7,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -function Point(x, y) { +function Point(x, y) +{ /** * @member {number} * @default 0 @@ -29,7 +30,8 @@ * * @return {Point} a copy of the point */ -Point.prototype.clone = function () { +Point.prototype.clone = function () +{ return new Point(this.x, this.y); }; @@ -40,7 +42,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -Point.prototype.set = function (x, y) { +Point.prototype.set = function (x, y) +{ this.x = x || 0; this.y = y || ( (y !== 0) ? this.x : 0 ) ; }; diff --git a/src/core/math/shapes/Circle.js b/src/core/math/shapes/Circle.js index 69cfdc9..4d76efc 100644 --- a/src/core/math/shapes/Circle.js +++ b/src/core/math/shapes/Circle.js @@ -10,7 +10,8 @@ * @param y {number} The Y coordinate of the center of this circle * @param radius {number} The radius of the circle */ -function Circle(x, y, radius) { +function Circle(x, y, radius) +{ /** * @member {number} * @default 0 @@ -46,7 +47,8 @@ * @method clone * @return {Circle} a copy of the Circle */ -Circle.prototype.clone = function () { +Circle.prototype.clone = function () +{ return new Circle(this.x, this.y, this.radius); }; @@ -58,8 +60,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Circle */ -Circle.prototype.contains = function (x, y) { - if (this.radius <= 0) { +Circle.prototype.contains = function (x, y) +{ + if (this.radius <= 0) + { return false; } @@ -79,6 +83,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Circle.prototype.getBounds = function () { +Circle.prototype.getBounds = function () +{ return new Rectangle(this.x - this.radius, this.y - this.radius, this.radius * 2, this.radius * 2); }; diff --git a/src/core/math/shapes/Ellipse.js b/src/core/math/shapes/Ellipse.js index 4f2d066..fefd01a 100644 --- a/src/core/math/shapes/Ellipse.js +++ b/src/core/math/shapes/Ellipse.js @@ -11,7 +11,8 @@ * @param width {number} The half width of this ellipse * @param height {number} The half height of this ellipse */ -function Ellipse(x, y, width, height) { +function Ellipse(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -53,7 +54,8 @@ * @method clone * @return {Ellipse} a copy of the ellipse */ -Ellipse.prototype.clone = function () { +Ellipse.prototype.clone = function () +{ return new Ellipse(this.x, this.y, this.width, this.height); }; @@ -65,8 +67,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coords are within this ellipse */ -Ellipse.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Ellipse.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } @@ -86,6 +90,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Ellipse.prototype.getBounds = function () { +Ellipse.prototype.getBounds = function () +{ return new Rectangle(this.x - this.width, this.y - this.height, this.width, this.height); }; diff --git a/src/core/math/shapes/Polygon.js b/src/core/math/shapes/Polygon.js index ae89148..fea6d37 100644 --- a/src/core/math/shapes/Polygon.js +++ b/src/core/math/shapes/Polygon.js @@ -10,16 +10,20 @@ * arguments passed can be flat x,y values e.g. `new Polygon(x,y, x,y, x,y, ...)` where `x` and `y` are * Numbers. */ -function Polygon(points) { +function Polygon(points) +{ //if points isn't an array, use arguments as the array - if (!(points instanceof Array)) { + if (!(points instanceof Array)) + { points = Array.prototype.slice.call(arguments); } //if this is a flat array of numbers, convert it to points - if (points[0] instanceof Point) { + if (points[0] instanceof Point) + { var p = []; - for (var i = 0, il = points.length; i < il; i++) { + for (var i = 0, il = points.length; i < il; i++) + { p.push(points[i].x, points[i].y); } @@ -51,7 +55,8 @@ * * @return {Polygon} a copy of the polygon */ -Polygon.prototype.clone = function () { +Polygon.prototype.clone = function () +{ return new Polygon(this.points.slice()); }; @@ -62,19 +67,22 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this polygon */ -Polygon.prototype.contains = function (x, y) { +Polygon.prototype.contains = function (x, y) +{ var inside = false; // use some raycasting to test hits // https://github.com/substack/point-in-polygon/blob/master/index.js var length = this.points.length / 2; - for (var i = 0, j = length - 1; i < length; j = i++) { + for (var i = 0, j = length - 1; i < length; j = i++) + { var xi = this.points[i * 2], yi = this.points[i * 2 + 1], xj = this.points[j * 2], yj = this.points[j * 2 + 1], intersect = ((yi > y) !== (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi); - if (intersect) { + if (intersect) + { inside = !inside; } } diff --git a/src/core/math/shapes/Rectangle.js b/src/core/math/shapes/Rectangle.js index 16ac62a..4008b68 100644 --- a/src/core/math/shapes/Rectangle.js +++ b/src/core/math/shapes/Rectangle.js @@ -10,7 +10,8 @@ * @param width {number} The overall width of this rectangle * @param height {number} The overall height of this rectangle */ -function Rectangle(x, y, width, height) { +function Rectangle(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -60,7 +61,8 @@ * * @return {Rectangle} a copy of the rectangle */ -Rectangle.prototype.clone = function () { +Rectangle.prototype.clone = function () +{ return new Rectangle(this.x, this.y, this.width, this.height); }; @@ -71,13 +73,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rectangle */ -Rectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Rectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/math/shapes/RoundedRectangle.js b/src/core/math/shapes/RoundedRectangle.js index 27d286e..7bf6411 100644 --- a/src/core/math/shapes/RoundedRectangle.js +++ b/src/core/math/shapes/RoundedRectangle.js @@ -11,7 +11,8 @@ * @param height {number} The overall height of this rounded rectangle * @param radius {number} Controls the radius of the rounded corners */ -function RoundedRectangle(x, y, width, height, radius) { +function RoundedRectangle(x, y, width, height, radius) +{ /** * @member {number} * @default 0 @@ -58,7 +59,8 @@ * * @return {RoundedRectangle} a copy of the rounded rectangle */ -RoundedRectangle.prototype.clone = function () { +RoundedRectangle.prototype.clone = function () +{ return new RoundedRectangle(this.x, this.y, this.width, this.height, this.radius); }; @@ -69,13 +71,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rounded Rectangle */ -RoundedRectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +RoundedRectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/primitives/Graphics.js b/src/core/primitives/Graphics.js index 261c534..e902d2a 100644 --- a/src/core/primitives/Graphics.js +++ b/src/core/primitives/Graphics.js @@ -16,7 +16,8 @@ * @extends DisplayObjectContainer * @namespace PIXI */ -function Graphics() { +function Graphics() +{ DisplayObjectContainer.call(this); this.renderable = true; @@ -154,16 +155,20 @@ * @private */ cacheAsBitmap: { - get: function () { + get: function () + { return this._cacheAsBitmap; }, - set: function (value) { + set: function (value) + { this._cacheAsBitmap = value; - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._generateCachedSprite(); } - else { + else + { this.destroyCachedSprite(); this.dirty = true; } @@ -176,7 +181,8 @@ * * @return {Graphics} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ var clone = new Graphics(); clone.renderable = this.renderable; @@ -192,7 +198,8 @@ clone.cachedSpriteDirty = this.cachedSpriteDirty; // copy graphics data - for (var i = 0; i < this.graphicsData.length; ++i) { + for (var i = 0; i < this.graphicsData.length; ++i) + { clone.graphicsData.push(this.graphicsData.clone()); } @@ -211,17 +218,21 @@ * @param alpha {number} alpha of the line to draw, will update the objects stored style * @return {Graphics} */ -Graphics.prototype.lineStyle = function (lineWidth, color, alpha) { +Graphics.prototype.lineStyle = function (lineWidth, color, alpha) +{ this.lineWidth = lineWidth || 0; this.lineColor = color || 0; this.lineAlpha = (arguments.length < 3) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length) + { // halfway through a line? start a new one! this.drawShape( new math.Polygon( this.currentPath.shape.points.slice(-2) )); } - else { + else + { // otherwise its empty so lets just set the line properties this.currentPath.lineWidth = this.lineWidth; this.currentPath.lineColor = this.lineColor; @@ -239,7 +250,8 @@ * @param y {number} the Y coordinate to move to * @return {Graphics} */ -Graphics.prototype.moveTo = function (x, y) { +Graphics.prototype.moveTo = function (x, y) +{ this.drawShape(new math.Polygon([x,y])); return this; @@ -253,7 +265,8 @@ * @param y {number} the Y coordinate to draw to * @return {Graphics} */ -Graphics.prototype.lineTo = function (x, y) { +Graphics.prototype.lineTo = function (x, y) +{ this.currentPath.shape.points.push(x, y); this.dirty = true; @@ -270,13 +283,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -285,7 +302,8 @@ n = 20, points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { this.moveTo(0, 0); } @@ -293,7 +311,8 @@ var fromY = points[points.length-1]; var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; xa = fromX + ( (cpX - fromX) * j ); @@ -319,13 +338,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -342,7 +365,8 @@ var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; dt = (1 - j); @@ -373,13 +397,17 @@ * @param radius {number} The radius of the arc * @return {Graphics} */ -Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points.push(x1, y1); } } - else { + else + { this.moveTo(x1, y1); } @@ -392,12 +420,15 @@ b2 = x2 - x1, mm = Math.abs(a1 * b2 - b1 * a2); - if (mm < 1.0e-8 || radius === 0) { - if (points[points.length-2] !== x1 || points[points.length-1] !== y1) { + if (mm < 1.0e-8 || radius === 0) + { + if (points[points.length-2] !== x1 || points[points.length-1] !== y1) + { points.push(x1, y1); } } - else { + else + { var dd = a1 * a1 + b1 * b1, cc = a2 * a2 + b2 * b2, tt = a1 * a2 + b1 * b2, @@ -433,42 +464,51 @@ * @param anticlockwise {boolean} Optional. Specifies whether the drawing should be counterclockwise or clockwise. False is default, and indicates clockwise, while true indicates counter-clockwise. * @return {Graphics} */ -Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) { +Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) +{ var startX = cx + Math.cos(startAngle) * radius; var startY = cy + Math.sin(startAngle) * radius; var points; // TODO - This if-else makes no sense. It uses currentPath in the else where it doesn't exist... - if (this.currentPath) { + if (this.currentPath) + { points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { points.push(startX, startY); } - else if (points[points.length-2] !== startX || points[points.length-1] !== startY) { + else if (points[points.length-2] !== startX || points[points.length-1] !== startY) + { points.push(startX, startY); } } - else { + else + { this.moveTo(startX, startY); points = this.currentPath.shape.points; } - if (startAngle === endAngle) { + if (startAngle === endAngle) + { return this; } - if (!anticlockwise && endAngle <= startAngle) { + if (!anticlockwise && endAngle <= startAngle) + { endAngle += Math.PI * 2; } - else if (anticlockwise && startAngle <= endAngle) { + else if (anticlockwise && startAngle <= endAngle) + { startAngle += Math.PI * 2; } var sweep = anticlockwise ? (startAngle - endAngle) *-1 : (endAngle - startAngle); var segs = (Math.abs(sweep)/ (Math.PI * 2)) * 40; - if (sweep === 0) { + if (sweep === 0) + { return this; } @@ -482,7 +522,8 @@ var remainder = ( segMinus % 1 ) / segMinus; - for (var i = 0; i <= segMinus; ++i) { + for (var i = 0; i <= segMinus; ++i) + { var real = i + remainder * i; var angle = ((theta) + startAngle + (theta2 * real)); @@ -506,13 +547,16 @@ * @param alpha {number} the alpha of the fill * @return {Graphics} */ -Graphics.prototype.beginFill = function (color, alpha) { +Graphics.prototype.beginFill = function (color, alpha) +{ this.filling = true; this.fillColor = color || 0; this.fillAlpha = (alpha === undefined) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length <= 2) + { this.currentPath.fill = this.filling; this.currentPath.fillColor = this.fillColor; this.currentPath.fillAlpha = this.fillAlpha; @@ -526,7 +570,8 @@ * * @return {Graphics} */ -Graphics.prototype.endFill = function () { +Graphics.prototype.endFill = function () +{ this.filling = false; this.fillColor = null; this.fillAlpha = 1; @@ -542,7 +587,8 @@ * @param height {number} The height of the rectangle * @return {Graphics} */ -Graphics.prototype.drawRect = function ( x, y, width, height ) { +Graphics.prototype.drawRect = function ( x, y, width, height ) +{ this.drawShape(new math.Rectangle(x,y, width, height)); return this; @@ -556,7 +602,8 @@ * @param height {number} The height of the rectangle * @param radius {number} Radius of the rectangle corners */ -Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) { +Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) +{ this.drawShape(new math.RoundedRectangle(x, y, width, height, radius)); return this; @@ -570,7 +617,8 @@ * @param radius {number} The radius of the circle * @return {Graphics} */ -Graphics.prototype.drawCircle = function (x, y, radius) { +Graphics.prototype.drawCircle = function (x, y, radius) +{ this.drawShape(new math.Circle(x,y, radius)); return this; @@ -585,7 +633,8 @@ * @param height {number} The half height of the ellipse * @return {Graphics} */ -Graphics.prototype.drawEllipse = function (x, y, width, height) { +Graphics.prototype.drawEllipse = function (x, y, width, height) +{ this.drawShape(new math.Ellipse(x, y, width, height)); return this; @@ -597,8 +646,10 @@ * @param path {Array} The path data used to construct the polygon. * @return {Graphics} */ -Graphics.prototype.drawPolygon = function (path) { - if (!(path instanceof Array)) { +Graphics.prototype.drawPolygon = function (path) +{ + if (!(path instanceof Array)) + { path = Array.prototype.slice.call(arguments); } @@ -612,7 +663,8 @@ * * @return {Graphics} */ -Graphics.prototype.clear = function () { +Graphics.prototype.clear = function () +{ this.lineWidth = 0; this.filling = false; @@ -631,7 +683,8 @@ * @param scaleMode {number} Should be one of the scaleMode consts * @return {Texture} a texture of the graphics object */ -Graphics.prototype.generateTexture = function (resolution, scaleMode) { +Graphics.prototype.generateTexture = function (resolution, scaleMode) +{ resolution = resolution || 1; var bounds = this.getBounds(); @@ -655,17 +708,21 @@ * * @param renderer {WebGLRenderer} */ -Graphics.prototype._renderWebGL = function (renderer) { +Graphics.prototype._renderWebGL = function (renderer) +{ // if the sprite is not visible or the alpha is 0 then no need to render this element - if (this.isMask === true) { + if (this.isMask === true) + { return; } // this code may still be needed so leaving for now.. - // + // /* - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture on the gpu too! @@ -681,17 +738,24 @@ return; } - */ - - // check if the webgl graphic needs to be updated - if (this.glDirty) { - this.dirty = true; - this.glDirty = false; - } + else */ - renderer.setObjectRendererer(renderer.graphicsRenderer); - renderer.graphicsRenderer.render(this); + renderer.spriteBatch.stop(); + renderer.blendModeManager.setBlendMode(this.blendMode); + // check blend mode + renderer.blendModeManager.setBlendMode( this.blendMode ); + + // check if the webgl graphic needs to be updated + if (this.glDirty) + { + this.dirty = true; + this.glDirty = false; + } + + WebGLGraphics.renderGraphics(this, renderer); + + renderer.spriteBatch.start(); }; /** @@ -700,14 +764,18 @@ * @param renderer {CanvasRenderer} * @private */ -Graphics.prototype.renderCanvas = function (renderer) { +Graphics.prototype.renderCanvas = function (renderer) +{ // 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.isMask === true) { + if (!this.visible || this.alpha <= 0 || this.isMask === true) + { return; } - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture @@ -723,16 +791,19 @@ return; } - else { + else + { var context = renderer.context; var transform = this.worldTransform; - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } @@ -748,11 +819,13 @@ CanvasGraphics.renderGraphics(this, context); - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } } @@ -763,13 +836,16 @@ * * @return {Rectangle} the rectangular bounding area */ -Graphics.prototype.getBounds = function (matrix) { +Graphics.prototype.getBounds = function (matrix) +{ // return an empty object if the item is a mask! - if (this.isMask) { + if (this.isMask) + { return math.Rectangle.EMPTY; } - if (this.dirty) { + if (this.dirty) + { this.updateLocalBounds(); this.glDirty = true; @@ -841,23 +917,27 @@ * Update the bounds of the object * */ -Graphics.prototype.updateLocalBounds = function () { +Graphics.prototype.updateLocalBounds = function () +{ var minX = Infinity; var maxX = -Infinity; var minY = Infinity; var maxY = -Infinity; - if (this.graphicsData.length) { + if (this.graphicsData.length) + { var shape, points, x, y, w, h; - for (var i = 0; i < this.graphicsData.length; i++) { + for (var i = 0; i < this.graphicsData.length; i++) + { var data = this.graphicsData[i]; var type = data.type; var lineWidth = data.lineWidth; shape = data.shape; - if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) { + if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) + { x = shape.x - lineWidth/2; y = shape.y - lineWidth/2; w = shape.width + lineWidth; @@ -869,7 +949,8 @@ minY = y < minY ? y : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.CIRC) { + else if (type === CONST.SHAPES.CIRC) + { x = shape.x; y = shape.y; w = shape.radius + lineWidth/2; @@ -881,7 +962,8 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.ELIP) { + else if (type === CONST.SHAPES.ELIP) + { x = shape.x; y = shape.y; w = shape.width + lineWidth/2; @@ -893,11 +975,13 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else { + else + { // POLY points = shape.points; - for (var j = 0; j < points.length; j += 2) { + for (var j = 0; j < points.length; j += 2) + { x = points[j]; y = points[j+1]; @@ -910,7 +994,8 @@ } } } - else { + else + { minX = 0; maxX = 0; minY = 0; @@ -931,10 +1016,12 @@ * * @private */ -Graphics.prototype._generateCachedSprite = function () { +Graphics.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { var canvasBuffer = new CanvasBuffer(bounds.width, bounds.height); var texture = Texture.fromCanvas(canvasBuffer.canvas); @@ -943,7 +1030,8 @@ this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.buffer.resize(bounds.width, bounds.height); } @@ -968,7 +1056,8 @@ * * @private */ -Graphics.prototype.updateCachedSpriteTexture = function () { +Graphics.prototype.updateCachedSpriteTexture = function () +{ var cachedSprite = this._cachedSprite; var texture = cachedSprite.texture; var canvas = cachedSprite.buffer.canvas; @@ -989,7 +1078,8 @@ * Destroys a previous cached sprite. * */ -Graphics.prototype.destroyCachedSprite = function () { +Graphics.prototype.destroyCachedSprite = function () +{ this._cachedSprite.texture.destroy(true); // let the gc collect the unused sprite @@ -1003,10 +1093,13 @@ * @param {Circle|Rectangle|Ellipse|Line|Polygon} shape The Shape object to draw. * @return {GraphicsData} The generated GraphicsData object. */ -Graphics.prototype.drawShape = function (shape) { - if (this.currentPath) { +Graphics.prototype.drawShape = function (shape) +{ + if (this.currentPath) + { // check current path! - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath.shape.points.length <= 2) + { this.graphicsData.pop(); } } @@ -1017,7 +1110,8 @@ this.graphicsData.push(data); - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { data.shape.closed = this.filling; this.currentPath = data; } diff --git a/src/core/primitives/GraphicsData.js b/src/core/primitives/GraphicsData.js index 99decbe..788f6f2 100644 --- a/src/core/primitives/GraphicsData.js +++ b/src/core/primitives/GraphicsData.js @@ -4,7 +4,8 @@ * @class * @namespace PIXI */ -function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) { +function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) +{ this.lineWidth = lineWidth; this.lineColor = lineColor; this.lineAlpha = lineAlpha; @@ -27,7 +28,8 @@ * * @return {GraphicsData} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ return new GraphicsData( this.lineWidth, this.lineColor, diff --git a/src/core/renderers/canvas/CanvasRenderer.js b/src/core/renderers/canvas/CanvasRenderer.js index 15a0978..7aebd44 100644 --- a/src/core/renderers/canvas/CanvasRenderer.js +++ b/src/core/renderers/canvas/CanvasRenderer.js @@ -17,17 +17,22 @@ * @param [options.resolution=1] {number} the resolution of the renderer retina would be 2 * @param [options.clearBeforeRender=true] {boolean} This sets if the CanvasRenderer will clear the canvas or not before the new render pass. */ -function CanvasRenderer(width, height, options) { +function CanvasRenderer(width, height, options) +{ utils.sayHello('Canvas'); - if (options) { - for (var i in CONST.defaultRenderOptions) { - if (typeof options[i] === 'undefined') { + if (options) + { + for (var i in CONST.defaultRenderOptions) + { + if (typeof options[i] === 'undefined') + { options[i] = CONST.defaultRenderOptions[i]; } } } - else { + else + { options = CONST.defaultRenderOptions; } @@ -156,19 +161,24 @@ this.smoothProperty = null; - if (this.context.imageSmoothingEnabled) { + if (this.context.imageSmoothingEnabled) + { this.smoothProperty = 'imageSmoothingEnabled'; } - else if (this.context.webkitImageSmoothingEnabled) { + else if (this.context.webkitImageSmoothingEnabled) + { this.smoothProperty = 'webkitImageSmoothingEnabled'; } - else if (this.context.mozImageSmoothingEnabled) { + else if (this.context.mozImageSmoothingEnabled) + { this.smoothProperty = 'mozImageSmoothingEnabled'; } - else if (this.context.oImageSmoothingEnabled) { + else if (this.context.oImageSmoothingEnabled) + { this.smoothProperty = 'oImageSmoothingEnabled'; } - else if (this.context.msImageSmoothingEnabled) { + else if (this.context.msImageSmoothingEnabled) + { this.smoothProperty = 'msImageSmoothingEnabled'; } @@ -193,10 +203,12 @@ * @memberof CanvasRenderer# */ backgroundColor: { - get: function () { + get: function () + { return this._backgroundColor; }, - set: function (val) { + set: function (val) + { this._backgroundColor = val; this._backgroundColorString = utils.hex2string(val); } @@ -208,7 +220,8 @@ * * @param object {DisplayObject} the object to be rendered */ -CanvasRenderer.prototype.render = function (object) { +CanvasRenderer.prototype.render = function (object) +{ object.updateTransform(); this.context.setTransform(1,0,0,1,0,0); @@ -218,16 +231,20 @@ this.currentBlendMode = CONST.blendModes.NORMAL; this.context.globalCompositeOperation = this.blendModes[CONST.blendModes.NORMAL]; - if (navigator.isCocoonJS && this.view.screencanvas) { + if (navigator.isCocoonJS && this.view.screencanvas) + { this.context.fillStyle = 'black'; this.context.clear(); } - if (this.clearBeforeRender) { - if (this.transparent) { + if (this.clearBeforeRender) + { + if (this.transparent) + { this.context.clearRect(0, 0, this.width, this.height); } - else { + else + { this.context.fillStyle = this._backgroundColorString; this.context.fillRect(0, 0, this.width , this.height); } @@ -241,8 +258,10 @@ * * @param [removeView=false] {boolean} Removes the Canvas element from the DOM. */ -CanvasRenderer.prototype.destroy = function (removeView) { - if (removeView && this.view.parent) { +CanvasRenderer.prototype.destroy = function (removeView) +{ + if (removeView && this.view.parent) + { this.view.parent.removeChild(this.view); } @@ -257,14 +276,16 @@ * @param width {number} the new width of the canvas view * @param height {number} the new height of the canvas view */ -CanvasRenderer.prototype.resize = function (width, height) { +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) { + if (this.autoResize) + { this.view.style.width = this.width / this.resolution + 'px'; this.view.style.height = this.height / this.resolution + 'px'; } @@ -276,7 +297,8 @@ * @param displayObject {DisplayObject} The displayObject to render * @private */ -CanvasRenderer.prototype.renderDisplayObject = function (displayObject) { +CanvasRenderer.prototype.renderDisplayObject = function (displayObject) +{ displayObject.renderCanvas(this); }; @@ -285,11 +307,14 @@ * * @private */ -CanvasRenderer.prototype._mapBlendModes = function () { - if (!this.blendModes) { +CanvasRenderer.prototype._mapBlendModes = function () +{ + if (!this.blendModes) + { this.blendModes = {}; - if (utils.canUseNewCanvasBlendModes()) { + if (utils.canUseNewCanvasBlendModes()) + { this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? this.blendModes[CONST.blendModes.MULTIPLY] = 'multiply'; @@ -308,7 +333,8 @@ this.blendModes[CONST.blendModes.COLOR] = 'color'; this.blendModes[CONST.blendModes.LUMINOSITY] = 'luminosity'; } - else { + else + { // this means that the browser does not support the cool new blend modes in canvas 'cough' ie 'cough' this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? diff --git a/src/core/renderers/canvas/utils/CanvasBuffer.js b/src/core/renderers/canvas/utils/CanvasBuffer.js index ebe5d47..b183a66 100644 --- a/src/core/renderers/canvas/utils/CanvasBuffer.js +++ b/src/core/renderers/canvas/utils/CanvasBuffer.js @@ -6,7 +6,8 @@ * @param width {number} the width for the newly created canvas * @param height {number} the height for the newly created canvas */ -function CanvasBuffer(width, height) { +function CanvasBuffer(width, height) +{ /** * The Canvas object that belongs to this CanvasBuffer. * @@ -36,10 +37,12 @@ * @memberof CanvasBuffer# */ width: { - get: function () { + get: function () + { return this.canvas.width; }, - set: function (val) { + set: function (val) + { this.canvas.width = val; } }, @@ -50,10 +53,12 @@ * @memberof CanvasBuffer# */ height: { - get: function () { + get: function () + { return this.canvas.height; }, - set: function (val) { + set: function (val) + { this.canvas.height = val; } } @@ -64,7 +69,8 @@ * * @private */ -CanvasBuffer.prototype.clear = function () { +CanvasBuffer.prototype.clear = function () +{ this.context.setTransform(1, 0, 0, 1, 0, 0); this.context.clearRect(0,0, this.canvas.width, this.canvas.height); }; @@ -75,7 +81,8 @@ * @param width {number} the new width of the canvas * @param height {number} the new height of the canvas */ -CanvasBuffer.prototype.resize = function (width, height) { +CanvasBuffer.prototype.resize = function (width, height) +{ this.canvas.width = width; this.canvas.height = height; }; diff --git a/src/core/renderers/canvas/utils/CanvasGraphics.js b/src/core/renderers/canvas/utils/CanvasGraphics.js index c7eaa2a..3f2a91f 100644 --- a/src/core/renderers/canvas/utils/CanvasGraphics.js +++ b/src/core/renderers/canvas/utils/CanvasGraphics.js @@ -13,15 +13,18 @@ * @param graphics {Graphics} the actual graphics object to render * @param context {CanvasRenderingContext2D} the 2d drawing method of the canvas */ -CanvasGraphics.renderGraphics = function (graphics, context) { +CanvasGraphics.renderGraphics = function (graphics, context) +{ var worldAlpha = graphics.worldAlpha; - if (graphics.dirty) { + if (graphics.dirty) + { this.updateGraphicsTint(graphics); graphics.dirty = false; } - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; @@ -30,69 +33,82 @@ context.lineWidth = data.lineWidth; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { context.beginPath(); var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } - if (shape.closed) { + if (shape.closed) + { context.lineTo(points[0], points[1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fillRect(shape.x, shape.y, shape.width, shape.height); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.strokeRect(shape.x, shape.y, shape.width, shape.height); } } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.beginPath(); context.arc(shape.x, shape.y, shape.radius,0,2*Math.PI); context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas var w = shape.width * 2; @@ -119,18 +135,21 @@ context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; var width = shape.width; @@ -152,13 +171,15 @@ context.quadraticCurveTo(rx, ry, rx, ry + radius); context.closePath(); - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); @@ -174,45 +195,54 @@ * @param graphics {Graphics} the graphics which will be used as a mask * @param context {CanvasRenderingContext2D} the context 2d method of the canvas */ -CanvasGraphics.renderGraphicsMask = function (graphics, context) { +CanvasGraphics.renderGraphicsMask = function (graphics, context) +{ var len = graphics.graphicsData.length; - if (len === 0) { + if (len === 0) + { return; } context.beginPath(); - for (var i = 0; i < len; i++) { + for (var i = 0; i < len; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { context.rect(shape.x, shape.y, shape.width, shape.height); context.closePath(); } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.arc(shape.x, shape.y, shape.radius, 0, 2 * Math.PI); context.closePath(); } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas @@ -237,7 +267,8 @@ context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); context.closePath(); } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; @@ -262,8 +293,10 @@ } }; -CanvasGraphics.updateGraphicsTint = function (graphics) { - if (graphics.tint === 0xFFFFFF) { +CanvasGraphics.updateGraphicsTint = function (graphics) +{ + if (graphics.tint === 0xFFFFFF) + { return; } @@ -271,7 +304,8 @@ var tintG = (graphics.tint >> 8 & 0xFF) / 255; var tintB = (graphics.tint & 0xFF)/ 255; - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var fillColor = data.fillColor | 0; diff --git a/src/core/renderers/canvas/utils/CanvasMaskManager.js b/src/core/renderers/canvas/utils/CanvasMaskManager.js index e04a733..9827d36 100644 --- a/src/core/renderers/canvas/utils/CanvasMaskManager.js +++ b/src/core/renderers/canvas/utils/CanvasMaskManager.js @@ -6,7 +6,8 @@ * @class * @namespace PIXI */ -function CanvasMaskManager() {} +function CanvasMaskManager() +{} CanvasMaskManager.prototype.constructor = CanvasMaskManager; module.exports = CanvasMaskManager; @@ -17,7 +18,8 @@ * @param maskData {object} the maskData that will be pushed * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.pushMask = function (maskData, renderer) { +CanvasMaskManager.prototype.pushMask = function (maskData, renderer) +{ renderer.context.save(); var cacheAlpha = maskData.alpha; @@ -45,6 +47,7 @@ * * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.popMask = function (renderer) { +CanvasMaskManager.prototype.popMask = function (renderer) +{ renderer.context.restore(); }; diff --git a/src/core/renderers/canvas/utils/CanvasTinter.js b/src/core/renderers/canvas/utils/CanvasTinter.js index 17e0529..d2fb1bc 100644 --- a/src/core/renderers/canvas/utils/CanvasTinter.js +++ b/src/core/renderers/canvas/utils/CanvasTinter.js @@ -14,7 +14,8 @@ * @param color {number} the color to use to tint the sprite with * @return {HTMLCanvasElement} The tinted canvas */ -CanvasTinter.getTintedTexture = function (sprite, color) { +CanvasTinter.getTintedTexture = function (sprite, color) +{ var texture = sprite.texture; color = CanvasTinter.roundColor(color); @@ -23,7 +24,8 @@ texture.tintCache = texture.tintCache || {}; - if (texture.tintCache[stringColor]) { + if (texture.tintCache[stringColor]) + { return texture.tintCache[stringColor]; } @@ -33,14 +35,16 @@ //CanvasTinter.tintWithPerPixel(texture, stringColor, canvas); CanvasTinter.tintMethod(texture, color, canvas); - if (CanvasTinter.convertTintToImage) { + if (CanvasTinter.convertTintToImage) + { // is this better? var tintImage = new Image(); tintImage.src = canvas.toDataURL(); texture.tintCache[stringColor] = tintImage; } - else { + else + { texture.tintCache[stringColor] = canvas; // if we are not converting the texture to an image then we need to lose the reference to the canvas CanvasTinter.canvas = null; @@ -56,7 +60,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithMultiply = function (texture, color, canvas) { +CanvasTinter.tintWithMultiply = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -104,7 +109,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithOverlay = function (texture, color, canvas) { +CanvasTinter.tintWithOverlay = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -139,7 +145,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithPerPixel = function (texture, color, canvas) { +CanvasTinter.tintWithPerPixel = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -167,7 +174,8 @@ var pixels = pixelData.data; - for (var i = 0; i < pixels.length; i += 4) { + for (var i = 0; i < pixels.length; i += 4) + { pixels[i+0] *= r; pixels[i+1] *= g; pixels[i+2] *= b; @@ -181,7 +189,8 @@ * * @param color {number} the color to round, should be a hex color */ -CanvasTinter.roundColor = function (color) { +CanvasTinter.roundColor = function (color) +{ var step = CanvasTinter.cacheStepsPerColorChannel; var rgbValues = utils.hex2rgb(color); diff --git a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js index 9f2f89a..35edbaf 100644 --- a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js +++ b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLBlendModeManager(renderer) { +function WebGLBlendModeManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -23,8 +24,10 @@ * * @param blendMode {number} the blendMode, should be a Pixi const, such as BlendModes.ADD */ -WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) { - if (this.currentBlendMode === blendMode) { +WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) +{ + if (this.currentBlendMode === blendMode) + { return false; } diff --git a/src/core/renderers/webgl/managers/WebGLFilterManager.js b/src/core/renderers/webgl/managers/WebGLFilterManager.js index 1179258..2dac048 100644 --- a/src/core/renderers/webgl/managers/WebGLFilterManager.js +++ b/src/core/renderers/webgl/managers/WebGLFilterManager.js @@ -7,7 +7,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLFilterManager(renderer) { +function WebGLFilterManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -32,7 +33,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.texturePool.length = 0; self.initShaderBuffers(); }); @@ -46,7 +48,8 @@ * @param renderer {WebGLRenderer} * @param buffer {ArrayBuffer} */ -WebGLFilterManager.prototype.begin = function (buffer) { +WebGLFilterManager.prototype.begin = function (buffer) +{ this.defaultShader = this.renderer.shaderManager.defaultShader; this.width = this.renderer.projection.x * 2; @@ -60,7 +63,8 @@ * * @param filterBlock {object} the filter that will be pushed to the current filter stack */ -WebGLFilterManager.prototype.pushFilter = function (filterBlock) { +WebGLFilterManager.prototype.pushFilter = function (filterBlock) +{ var gl = this.renderer.gl; var projection = this.renderer.projection; @@ -78,10 +82,12 @@ this.offsetY += filterBlock._filterArea.y; var texture = this.texturePool.pop(); - if (!texture) { + if (!texture) + { texture = new FilterTexture(this.renderer.gl, this.width, this.height); } - else { + else + { texture.resize(this.width, this.height); } @@ -98,29 +104,35 @@ var localX = filterArea.x, localY = filterArea.y; - if (filterArea.x < 0) { + if (filterArea.x < 0) + { filterArea.width += filterArea.x; filterArea.x = 0; } - if (filterArea.y < 0) { + if (filterArea.y < 0) + { filterArea.height += filterArea.y; filterArea.y = 0; } - if (localX + filterArea.width > this.width) { + if (localX + filterArea.width > this.width) + { filterArea.width = this.width - localX; } - if (localY + filterArea.height > this.height) { + if (localY + filterArea.height > this.height) + { filterArea.height = this.height - localY; } - if (filterArea.width < 0) { + if (filterArea.width < 0) + { filterArea.width = 0; } - if (filterArea.height < 0) { + if (filterArea.height < 0) + { filterArea.height = 0; } @@ -154,7 +166,8 @@ * Removes the last filter from the filter stack and doesn't return it. * */ -WebGLFilterManager.prototype.popFilter = function () { +WebGLFilterManager.prototype.popFilter = function () +{ var gl = this.renderer.gl; var filterBlock = this.filterStack.pop(); @@ -163,7 +176,8 @@ var projection = this.renderer.projection; var offset = this.renderer.offset; - if (filterBlock.filterPasses.length > 1) { + if (filterBlock.filterPasses.length > 1) + { gl.viewport(0, 0, filterArea.width, filterArea.height); gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); @@ -193,7 +207,8 @@ var inputTexture = texture; var outputTexture = this.texturePool.pop(); - if (!outputTexture) { + if (!outputTexture) + { outputTexture = new FilterTexture(this.renderer.gl, this.width, this.height); } outputTexture.resize(this.width, this.height); @@ -204,7 +219,8 @@ gl.disable(gl.BLEND); - for (var i = 0; i < filterBlock.filterPasses.length-1; i++) { + for (var i = 0; i < filterBlock.filterPasses.length-1; i++) + { var filterPass = filterBlock.filterPasses[i]; gl.bindFramebuffer(gl.FRAMEBUFFER, outputTexture.frameBuffer ); @@ -243,10 +259,12 @@ var buffer = this.buffer; // time to render the filters texture to the previous scene - if (this.filterStack.length === 0) { + if (this.filterStack.length === 0) + { gl.colorMask(true, true, true, true);//this.transparent); } - else { + else + { var currentFilter = this.filterStack[this.filterStack.length-1]; filterArea = currentFilter._filterArea; @@ -332,13 +350,15 @@ * @param width {number} the horizontal range of the filter * @param height {number} the vertical range of the filter */ -WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) { +WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) +{ // use program var gl = this.renderer.gl; var shader = filter.shaders[gl.id]; - if (!shader) { + if (!shader) + { shader = new Shader(gl); shader.fragmentSrc = filter.fragmentSrc; @@ -356,7 +376,8 @@ gl.uniform2f(shader.projectionVector, width/2, -height/2); gl.uniform2f(shader.offsetVector, 0,0); - if (filter.uniforms.dimensions) { + 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]; @@ -386,7 +407,8 @@ * Initialises the shader buffers. * */ -WebGLFilterManager.prototype.initShaderBuffers = function () { +WebGLFilterManager.prototype.initShaderBuffers = function () +{ var gl = this.renderer.gl; // create some buffers @@ -432,7 +454,8 @@ * Destroys the filter and removes it from the filter stack. * */ -WebGLFilterManager.prototype.destroy = function () { +WebGLFilterManager.prototype.destroy = function () +{ var gl = this.renderer.gl; this.filterStack = null; @@ -441,7 +464,8 @@ this.offsetY = 0; // destroy textures - for (var i = 0; i < this.texturePool.length; i++) { + for (var i = 0; i < this.texturePool.length; i++) + { this.texturePool[i].destroy(); } diff --git a/src/core/renderers/webgl/managers/WebGLManager.js b/src/core/renderers/webgl/managers/WebGLManager.js index 9d47b5c..c30cd51 100644 --- a/src/core/renderers/webgl/managers/WebGLManager.js +++ b/src/core/renderers/webgl/managers/WebGLManager.js @@ -3,7 +3,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLManager(renderer) { +function WebGLManager(renderer) +{ /** * The renderer this manager works for. * @@ -15,6 +16,7 @@ WebGLManager.prototype.constructor = WebGLManager; module.exports = WebGLManager; -WebGLManager.prototype.destroy = function () { +WebGLManager.prototype.destroy = function () +{ this.renderer = null; }; diff --git a/src/core/renderers/webgl/managers/WebGLMaskManager.js b/src/core/renderers/webgl/managers/WebGLMaskManager.js index 2f90b64..e568812 100644 --- a/src/core/renderers/webgl/managers/WebGLMaskManager.js +++ b/src/core/renderers/webgl/managers/WebGLMaskManager.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLMaskManager(renderer) { +function WebGLMaskManager(renderer) +{ WebGLManager.call(this, renderer); } @@ -19,12 +20,15 @@ * * @param maskData {any[]} */ -WebGLMaskManager.prototype.pushMask = function (maskData) { - if (maskData.dirty) { +WebGLMaskManager.prototype.pushMask = function (maskData) +{ + if (maskData.dirty) + { WebGLGraphics.updateGraphics(maskData, this.renderer.gl); } - if (!maskData._webGL[this.renderer.gl.id].data.length) { + if (!maskData._webGL[this.renderer.gl.id].data.length) + { return; } @@ -36,6 +40,7 @@ * * @param maskData {any[]} */ -WebGLMaskManager.prototype.popMask = function (maskData) { +WebGLMaskManager.prototype.popMask = function (maskData) +{ this.renderer.stencilManager.popStencil(maskData, maskData._webGL[this.renderer.gl.id].data[0], this.renderer); }; diff --git a/src/core/renderers/webgl/managers/WebGLShaderManager.js b/src/core/renderers/webgl/managers/WebGLShaderManager.js index fef071c..90c6477 100644 --- a/src/core/renderers/webgl/managers/WebGLShaderManager.js +++ b/src/core/renderers/webgl/managers/WebGLShaderManager.js @@ -10,7 +10,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLShaderManager(renderer) { +function WebGLShaderManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -28,7 +29,8 @@ */ this.tempAttribState = []; - for (var i = 0; i < this.maxAttibs; i++) { + for (var i = 0; i < this.maxAttibs; i++) + { this.attribState[i] = false; } @@ -66,7 +68,8 @@ // listen for context and update necessary shaders var self = this; - this.renderer.on('context', function (event) { + this.renderer.on('context', function (event) + { var gl = event.data; // this shader is used for rendering primitives @@ -97,29 +100,36 @@ * * @param attribs {Array} attribs */ -WebGLShaderManager.prototype.setAttribs = function (attribs) { +WebGLShaderManager.prototype.setAttribs = function (attribs) +{ // reset temp state var i; - for (i = 0; i < this.tempAttribState.length; i++) { + for (i = 0; i < this.tempAttribState.length; i++) + { this.tempAttribState[i] = false; } // set the new attribs - for (var a in attribs) { + for (var a in attribs) + { this.tempAttribState[attribs[a]] = true; } var gl = this.renderer.gl; - for (i = 0; i < this.attribState.length; i++) { - if (this.attribState[i] !== this.tempAttribState[i]) { + for (i = 0; i < this.attribState.length; i++) + { + if (this.attribState[i] !== this.tempAttribState[i]) + { this.attribState[i] = this.tempAttribState[i]; - if (this.attribState[i]) { + if (this.attribState[i]) + { gl.enableVertexAttribArray(i); } - else { + else + { gl.disableVertexAttribArray(i); } } @@ -131,8 +141,10 @@ * * @param shader {Any} */ -WebGLShaderManager.prototype.setShader = function (shader) { - if (this._currentId === shader.uuid) { +WebGLShaderManager.prototype.setShader = function (shader) +{ + if (this._currentId === shader.uuid) + { return false; } @@ -150,7 +162,8 @@ * Destroys this object. * */ -WebGLShaderManager.prototype.destroy = function () { +WebGLShaderManager.prototype.destroy = function () +{ this.attribState = null; this.tempAttribState = null; diff --git a/src/core/renderers/webgl/managers/WebGLStencilManager.js b/src/core/renderers/webgl/managers/WebGLStencilManager.js index 9ec6398..4cb0134 100644 --- a/src/core/renderers/webgl/managers/WebGLStencilManager.js +++ b/src/core/renderers/webgl/managers/WebGLStencilManager.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLStencilManager(renderer) { +function WebGLStencilManager(renderer) +{ WebGLManager.call(this, renderer); this.stencilStack = []; @@ -24,12 +25,14 @@ * @param graphics {Graphics} * @param webGLData {any[]} */ -WebGLStencilManager.prototype.pushStencil = function (graphics, webGLData) { +WebGLStencilManager.prototype.pushStencil = function (graphics, webGLData) +{ var gl = this.renderer.gl; this.bindGraphics(graphics, webGLData, this.renderer); - if (this.stencilStack.length === 0) { + if (this.stencilStack.length === 0) + { gl.enable(gl.STENCIL_TEST); gl.clear(gl.STENCIL_BUFFER_BIT); this.reverse = true; @@ -47,14 +50,17 @@ // draw the triangle strip! - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } @@ -62,31 +68,38 @@ // draw a quad to increment.. gl.drawElements(gl.TRIANGLE_FAN, 4, gl.UNSIGNED_SHORT, ( webGLData.indices.length - 4 ) * 2 ); - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); } this.reverse = !this.reverse; } - else { - if (!this.reverse) { + else + { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } - else { + 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) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); } } @@ -103,7 +116,8 @@ * @param graphics {Graphics} * @param webGLData {Array} */ -WebGLStencilManager.prototype.bindGraphics = function (graphics, webGLData) { +WebGLStencilManager.prototype.bindGraphics = function (graphics, webGLData) +{ //if (this._currentGraphics === graphics)return; this._currentGraphics = graphics; @@ -114,7 +128,8 @@ offset = this.renderer.offset, shader;// = this.renderer.shaderManager.primitiveShader; - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { shader = this.renderer.shaderManager.complexPrimitiveShader; this.renderer.shaderManager.setShader(shader); @@ -141,7 +156,8 @@ // set the index buffer! gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, webGLData.indexBuffer); } - else { + else + { //this.renderer.shaderManager.activatePrimitiveShader(); shader = this.renderer.shaderManager.primitiveShader; this.renderer.shaderManager.setShader( shader ); @@ -154,7 +170,7 @@ gl.uniform2f(shader.uniforms.offsetVector._location, -offset.x, -offset.y); gl.uniform3fv(shader.uniforms.tint._location, utils.hex2rgb(graphics.tint)); - + gl.uniform1f(shader.uniforms.alpha._location, graphics.worldAlpha); @@ -172,19 +188,22 @@ * @param graphics {Graphics} * @param webGLData {Array} */ -WebGLStencilManager.prototype.popStencil = function (graphics, webGLData) { +WebGLStencilManager.prototype.popStencil = function (graphics, webGLData) +{ var gl = this.renderer.gl; this.stencilStack.pop(); this.count--; - if (this.stencilStack.length === 0) { + if (this.stencilStack.length === 0) + { // the stack is empty! gl.disable(gl.STENCIL_TEST); } - else { + else + { var level = this.count; @@ -192,14 +211,17 @@ gl.colorMask(false, false, false, false); - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { this.reverse = !this.reverse; - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } @@ -213,31 +235,38 @@ // draw the triangle strip! gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); - if (!this.reverse) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); } } - else { + else + { // console.log("<<>>") - if (!this.reverse) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } - else { + 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) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); } } @@ -253,7 +282,8 @@ * Destroys the mask stack. * */ -WebGLStencilManager.prototype.destroy = function () { +WebGLStencilManager.prototype.destroy = function () +{ this.renderer = null; this.stencilStack = null; }; diff --git a/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js b/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js index 913ba5e..1ea7d19 100644 --- a/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js +++ b/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function ComplexPrimitiveShader(gl) { +function ComplexPrimitiveShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -24,7 +25,8 @@ 'uniform float flipY;', 'varying vec4 vColor;', - 'void main(void) {', + '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);', @@ -37,7 +39,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = vColor;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/FastShader.js b/src/core/renderers/webgl/shaders/FastShader.js index bd2e29a..2e5e060 100644 --- a/src/core/renderers/webgl/shaders/FastShader.js +++ b/src/core/renderers/webgl/shaders/FastShader.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function FastShader(gl) { +function FastShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -28,7 +29,8 @@ 'const vec2 center = vec2(-1.0, 1.0);', - 'void main(void) {', + 'void main(void) + {', ' vec2 v;', ' vec2 sv = aVertexPosition * aScale;', ' v.x = (sv.x) * cos(aRotation) - (sv.y) * sin(aRotation);', @@ -49,7 +51,8 @@ 'uniform sampler2D uSampler;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/PrimitiveShader.js b/src/core/renderers/webgl/shaders/PrimitiveShader.js index 6f25409..a25f54f 100644 --- a/src/core/renderers/webgl/shaders/PrimitiveShader.js +++ b/src/core/renderers/webgl/shaders/PrimitiveShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function PrimitiveShader(gl) { +function PrimitiveShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -23,7 +24,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + '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);', @@ -36,7 +38,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = vColor;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/Shader.js b/src/core/renderers/webgl/shaders/Shader.js index f8964f5..fd75ef5 100644 --- a/src/core/renderers/webgl/shaders/Shader.js +++ b/src/core/renderers/webgl/shaders/Shader.js @@ -6,7 +6,8 @@ * @param [fragmentSrc] {string} The source of the fragment shader. * @param [vertexSrc] {string} The source of the vertex shader. */ -function Shader(gl, vertexSrc, fragmentSrc, customUniforms, customAttributes) { +function Shader(gl, vertexSrc, fragmentSrc, customUniforms, customAttributes) +{ /** * @member {number} * @readonly @@ -33,7 +34,8 @@ dimensions: { type: '4f', value: new Float32Array(4) } }; - for (var u in customUniforms) { + for (var u in customUniforms) + { this.uniforms[u] = customUniforms[u]; } @@ -43,7 +45,8 @@ aColor: 0 }; - for (var a in customAttributes) { + for (var a in customAttributes) + { this.attributes[a] = customAttributes[a]; } @@ -66,7 +69,8 @@ 'const vec2 center = vec2(-1.0, 1.0);', - 'void main(void) {', + 'void main(void) + {', ' gl_Position = vec4( ((aVertexPosition + offsetVector) / projectionVector) + center , 0.0, 1.0);', ' vTextureCoord = aTextureCoord;', ' vColor = vec4(aColor.rgb * aColor.a, aColor.a);', @@ -85,7 +89,8 @@ 'uniform sampler2D uSampler;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;', '}' ].join('\n'); @@ -96,7 +101,8 @@ Shader.prototype.constructor = Shader; module.exports = Shader; -Shader.prototype.init = function () { +Shader.prototype.init = function () +{ this.compile(); this.gl.useProgram(this.program); @@ -105,14 +111,18 @@ this.cacheAttributeLocations(Object.keys(this.attributes)); }; -Shader.prototype.cacheUniformLocations = function (keys) { - for (var i = 0; i < keys.length; ++i) { +Shader.prototype.cacheUniformLocations = function (keys) +{ + for (var i = 0; i < keys.length; ++i) + { this.uniforms[keys[i]]._location = this.gl.getUniformLocation(this.program, keys[i]); } }; -Shader.prototype.cacheAttributeLocations = function (keys) { - for (var i = 0; i < keys.length; ++i) { +Shader.prototype.cacheAttributeLocations = function (keys) +{ + for (var i = 0; i < keys.length; ++i) + { this.attributes[keys[i]] = this.gl.getAttribLocation(this.program, keys[i]); } @@ -124,14 +134,16 @@ // 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.attributes.aColor === -1) { + // if (this.attributes.aColor === -1) + { // this.attributes.aColor = 2; // } // End worst hack eva // }; -Shader.prototype.compile = function () { +Shader.prototype.compile = function () +{ var gl = this.gl; var glVertShader = this._glCompile(gl.VERTEX_SHADER, this.vertexSrc); @@ -144,13 +156,15 @@ gl.linkProgram(program); // if linking fails, then log and cleanup - if (!gl.getProgramParameter(program, gl.LINK_STATUS)) { + if (!gl.getProgramParameter(program, gl.LINK_STATUS)) + { window.console.error('Pixi.js Error: Could not initialize shader.'); window.console.error('gl.VALIDATE_STATUS', gl.getProgramParameter(program, gl.VALIDATE_STATUS)); window.console.error('gl.getError()', gl.getError()); // if there is a program info log, log it - if (gl.getProgramInfoLog(program) !== '') { + if (gl.getProgramInfoLog(program) !== '') + { window.console.warn('Pixi.js Warning: gl.getProgramInfoLog()', gl.getProgramInfoLog(program)); } @@ -165,18 +179,21 @@ return (this.program = program); }; -Shader.prototype.syncUniforms = function () { +Shader.prototype.syncUniforms = function () +{ var gl = this.gl; this.textureCount = 1; - for (var key in this.uniforms) { + for (var key in this.uniforms) + { var uniform = this.uniforms[key], location = uniform._location, value = uniform.value, i, il; - switch (uniform.type) { + switch (uniform.type) + { // single int value case 'i': case '1i': @@ -282,7 +299,8 @@ // a Color Value case 'c': - if (typeof value === 'number') { + if (typeof value === 'number') + { value = utils.hex2rgb(value); } @@ -311,11 +329,13 @@ // array of 2D Point objects case 'v2v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(2 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 2] = value[i].x; uniform._array[i * 2 + 1] = value[i].y; } @@ -325,11 +345,13 @@ // array of 3D Point objects case 'v3v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(3 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 3] = value[i].x; uniform._array[i * 3 + 1] = value[i].y; uniform._array[i * 3 + 2] = value[i].z; @@ -341,11 +363,13 @@ // array of 4D Point objects case 'v4v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(4 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 4] = value[i].x; uniform._array[i * 4 + 1] = value[i].y; uniform._array[i * 4 + 2] = value[i].z; @@ -359,7 +383,8 @@ // PIXI.Texture case 't': case 'sampler2D': - if (!uniform.value || !uniform.value.baseTexture || !uniform.value.baseTexture.hasLoaded) { + if (!uniform.value || !uniform.value.baseTexture || !uniform.value.baseTexture.hasLoaded) + { break; } @@ -376,7 +401,8 @@ this.textureCount++; // initialize the texture if we haven't yet - if (!uniform._init) { + if (!uniform._init) + { this.initSampler2D(uniform); uniform._init = true; @@ -394,11 +420,13 @@ * Initialises a Sampler2D uniform (which may only be available later on after initUniforms once the texture has loaded) * */ -Shader.prototype.initSampler2D = function (uniform) { +Shader.prototype.initSampler2D = function (uniform) +{ var gl = this.gl; // Extended texture data - if (uniform.textureData) { + if (uniform.textureData) + { var data = uniform.textureData; // GLTexture = mag linear, min linear_mipmap_linear, wrap repeat + gl.generateMipmap(gl.TEXTURE_2D); @@ -417,14 +445,16 @@ var wrapT = (data.wrapT) ? data.wrapT : gl.CLAMP_TO_EDGE; var format = (data.luminance) ? gl.LUMINANCE : gl.RGBA; - if (data.repeat) { + if (data.repeat) + { wrapS = gl.REPEAT; wrapT = gl.REPEAT; } gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, !!data.flipY); - if (data.width) { + if (data.width) + { var width = (data.width) ? data.width : 512; var height = (data.height) ? data.height : 2; var border = (data.border) ? data.border : 0; @@ -432,7 +462,8 @@ // 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 { + 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); } @@ -448,7 +479,8 @@ * Destroys the shader. * */ -Shader.prototype.destroy = function () { +Shader.prototype.destroy = function () +{ this.gl.deleteProgram(this.program); this.gl = null; @@ -459,13 +491,15 @@ this.fragmentSrc = null; }; -Shader.prototype._glCompile = function (type, src) { +Shader.prototype._glCompile = function (type, src) +{ var shader = this.gl.createShader(type); this.gl.shaderSource(shader, src); this.gl.compileShader(shader); - if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) { + if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) + { window.console.log(this.gl.getShaderInfoLog(shader)); return null; } diff --git a/src/core/renderers/webgl/shaders/StripShader.js b/src/core/renderers/webgl/shaders/StripShader.js index 193f6e1..a7abcc6 100644 --- a/src/core/renderers/webgl/shaders/StripShader.js +++ b/src/core/renderers/webgl/shaders/StripShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function StripShader(gl) { +function StripShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -20,7 +21,8 @@ 'varying vec2 vTextureCoord;', - 'void main(void) {', + '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);', @@ -36,7 +38,8 @@ 'varying vec2 vTextureCoord;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vec2(vTextureCoord.x, vTextureCoord.y)) * alpha;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/utils/FilterTexture.js b/src/core/renderers/webgl/utils/FilterTexture.js index d2c8423..4433d44 100644 --- a/src/core/renderers/webgl/utils/FilterTexture.js +++ b/src/core/renderers/webgl/utils/FilterTexture.js @@ -8,7 +8,8 @@ * @param height {number} the vertical range of the filter * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values */ -function FilterTexture(gl, width, height, scaleMode) { +function FilterTexture(gl, width, height, scaleMode) +{ /** * @member {WebGLContext} */ @@ -59,7 +60,8 @@ * Clears the filter texture. * */ -FilterTexture.prototype.clear = function () { +FilterTexture.prototype.clear = function () +{ var gl = this.gl; gl.clearColor(0,0,0, 0); @@ -72,8 +74,10 @@ * @param width {number} the new width of the texture * @param height {number} the new height of the texture */ -FilterTexture.prototype.resize = function (width, height) { - if (this.width === width && this.height === height) { +FilterTexture.prototype.resize = function (width, height) +{ + if (this.width === width && this.height === height) + { return; } @@ -96,7 +100,8 @@ * Destroys the filter texture. * */ -FilterTexture.prototype.destroy = function () { +FilterTexture.prototype.destroy = function () +{ var gl = this.gl; gl.deleteFramebuffer( this.frameBuffer ); gl.deleteTexture( this.texture ); diff --git a/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js b/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js index c4721e9..a63f4d7 100644 --- a/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js +++ b/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js @@ -14,7 +14,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this sprite batch works for. */ -function WebGLFastSpriteBatch(renderer) { +function WebGLFastSpriteBatch(renderer) +{ /** * The renderer instance this sprite batch operates on. * @@ -91,7 +92,8 @@ */ this.lastIndexCount = 0; - for (var i=0, j=0; i < numIndices; i += 6, j += 4) { + 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; @@ -144,7 +146,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.setupContext(); }); } @@ -157,7 +160,8 @@ * * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLFastSpriteBatch.prototype.setupContext = function () { +WebGLFastSpriteBatch.prototype.setupContext = function () +{ var gl = this.renderer.gl; // create a couple of buffers @@ -177,7 +181,8 @@ /** * @param spriteBatch {SpriteBatch} The SpriteBatch container to prepare for. */ -WebGLFastSpriteBatch.prototype.begin = function (spriteBatch) { +WebGLFastSpriteBatch.prototype.begin = function (spriteBatch) +{ this.shader = this.renderer.shaderManager.fastShader; this.matrix = spriteBatch.worldTransform.toArray(true); @@ -187,33 +192,38 @@ /** */ -WebGLFastSpriteBatch.prototype.end = function () { +WebGLFastSpriteBatch.prototype.end = function () +{ this.flush(); }; /** * @param spriteBatch {SpriteBatch} The SpriteBatch container to render. */ -WebGLFastSpriteBatch.prototype.render = function (spriteBatch) { +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) { + if (!sprite.texture._uvs) + { return; } this.currentBaseTexture = sprite.texture.baseTexture; // check blend mode - if (sprite.blendMode !== this.renderer.blendModeManager.currentBlendMode) { + if (sprite.blendMode !== this.renderer.blendModeManager.currentBlendMode) + { this.flush(); this.renderer.blendModeManager.setBlendMode(sprite.blendMode); } - for (var i=0,j= children.length; i= this.size) { + if (this.currentBatchSize >= this.size) + { this.flush(); } }; @@ -362,29 +379,35 @@ /** * */ -WebGLFastSpriteBatch.prototype.flush = function () { +WebGLFastSpriteBatch.prototype.flush = function () +{ // If the batch is length 0 then return as there is nothing to draw - if (this.currentBatchSize === 0) { + if (this.currentBatchSize === 0) + { return; } var gl = this.renderer.gl; // bind the current texture - if (!this.currentBaseTexture._glTextures[gl.id]) { + if (!this.currentBaseTexture._glTextures[gl.id]) + { this.renderer.updateTexture(this.currentBaseTexture, gl); } //TODO-SHOUD THIS BE ELSE??!?!?! - else { + else + { gl.bindTexture(gl.TEXTURE_2D, this.currentBaseTexture._glTextures[gl.id]); } // upload the verts to the buffer - if (this.currentBatchSize > ( this.size * 0.5 ) ) { + if (this.currentBatchSize > ( this.size * 0.5 ) ) + { gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); } - else { + else + { var view = this.vertices.subarray(0, this.currentBatchSize * this.vertByteSize); gl.bufferSubData(gl.ARRAY_BUFFER, 0, view); @@ -405,14 +428,16 @@ * Ends the batch and flushes * */ -WebGLFastSpriteBatch.prototype.stop = function () { +WebGLFastSpriteBatch.prototype.stop = function () +{ this.flush(); }; /** * */ -WebGLFastSpriteBatch.prototype.start = function () { +WebGLFastSpriteBatch.prototype.start = function () +{ var gl = this.renderer.gl; // bind the main texture diff --git a/src/core/renderers/webgl/utils/WebGLGraphics.js b/src/core/renderers/webgl/utils/WebGLGraphics.js index 55f4911..ab8f46e 100644 --- a/src/core/renderers/webgl/utils/WebGLGraphics.js +++ b/src/core/renderers/webgl/utils/WebGLGraphics.js @@ -19,7 +19,8 @@ * @param graphics {Graphics} * @param renderer {WebGLRenderer} */ -WebGLGraphics.renderGraphics = function (graphics, renderer) {//projection, offset) { +WebGLGraphics.renderGraphics = function (graphics, renderer) {//projection, offset) +{ var gl = renderer.gl; var projection = renderer.projection, @@ -27,7 +28,8 @@ shader = renderer.shaderManager.primitiveShader, webGLData; - if (graphics.dirty) { + if (graphics.dirty) + { WebGLGraphics.updateGraphics(graphics, gl); } @@ -35,8 +37,10 @@ // This could be speeded up for sure! - for (var i = 0; i < webGL.data.length; i++) { - if (webGL.data[i].mode === 1) { + for (var i = 0; i < webGL.data.length; i++) + { + if (webGL.data[i].mode === 1) + { webGLData = webGL.data[i]; renderer.stencilManager.pushStencil(graphics, webGLData, renderer); @@ -46,7 +50,8 @@ renderer.stencilManager.popStencil(graphics, webGLData, renderer); } - else { + else + { webGLData = webGL.data[i]; @@ -84,12 +89,14 @@ * @param graphicsData {Graphics} The graphics object to update * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLGraphics.updateGraphics = function (graphics, gl) { +WebGLGraphics.updateGraphics = function (graphics, gl) +{ // get the contexts graphics object var webGL = graphics._webGL[gl.id]; // if the graphics object does not exist in the webGL context time to create it! - if (!webGL) { + if (!webGL) + { webGL = graphics._webGL[gl.id] = {lastIndex:0, data:[], gl:gl}; } @@ -99,11 +106,13 @@ var i; // if the user cleared the graphics object we will need to clear every object - if (graphics.clearDirty) { + if (graphics.clearDirty) + { graphics.clearDirty = false; // lop through and return all the webGLDatas to the object pool so than can be reused later on - for (i = 0; i < webGL.data.length; i++) { + for (i = 0; i < webGL.data.length; i++) + { var graphicsData = webGL.data[i]; graphicsData.reset(); WebGLGraphics.graphicsDataPool.push( graphicsData ); @@ -119,58 +128,72 @@ // loop through the graphics datas and construct each one.. // if the object is a complex fill then the new stencil buffer technique will be used // other wise graphics objects will be pushed into a batch.. - for (i = webGL.lastIndex; i < graphics.graphicsData.length; i++) { + for (i = webGL.lastIndex; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { // need to add the points the the graphics object.. data.points = data.shape.points.slice(); - if (data.shape.closed) { + if (data.shape.closed) + { // close the poly if the value is true! - if (data.points[0] !== data.points[data.points.length-2] || data.points[1] !== data.points[data.points.length-1]) { + if (data.points[0] !== data.points[data.points.length-2] || data.points[1] !== data.points[data.points.length-1]) + { data.points.push(data.points[0], data.points[1]); } } // MAKE SURE WE HAVE THE CORRECT TYPE.. - if (data.fill) { - if (data.points.length >= 6) { - if (data.points.length < 6 * 2) { + if (data.fill) + { + if (data.points.length >= 6) + { + if (data.points.length < 6 * 2) + { webGLData = WebGLGraphics.switchMode(webGL, 0); var canDrawUsingSimple = WebGLGraphics.buildPoly(data, webGLData); // console.log(canDrawUsingSimple); - if (!canDrawUsingSimple) { + if (!canDrawUsingSimple) + { // console.log("<>>>") webGLData = WebGLGraphics.switchMode(webGL, 1); WebGLGraphics.buildComplexPoly(data, webGLData); } } - else { + else + { webGLData = WebGLGraphics.switchMode(webGL, 1); WebGLGraphics.buildComplexPoly(data, webGLData); } } } - if (data.lineWidth > 0) { + if (data.lineWidth > 0) + { webGLData = WebGLGraphics.switchMode(webGL, 0); WebGLGraphics.buildLine(data, webGLData); } } - else { + else + { webGLData = WebGLGraphics.switchMode(webGL, 0); - if (data.type === CONST.SHAPES.RECT) { + if (data.type === CONST.SHAPES.RECT) + { WebGLGraphics.buildRectangle(data, webGLData); } - else if (data.type === CONST.SHAPES.CIRC || data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.CIRC || data.type === CONST.SHAPES.ELIP) + { WebGLGraphics.buildCircle(data, webGLData); } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { WebGLGraphics.buildRoundedRectangle(data, webGLData); } } @@ -179,10 +202,12 @@ } // upload all the dirty data... - for (i = 0; i < webGL.data.length; i++) { + for (i = 0; i < webGL.data.length; i++) + { webGLData = webGL.data[i]; - if (webGLData.dirty) { + if (webGLData.dirty) + { webGLData.upload(); } } @@ -194,18 +219,22 @@ * @param webGL {WebGLContext} * @param type {number} */ -WebGLGraphics.switchMode = function (webGL, type) { +WebGLGraphics.switchMode = function (webGL, type) +{ var webGLData; - if (!webGL.data.length) { + if (!webGL.data.length) + { webGLData = WebGLGraphics.graphicsDataPool.pop() || new WebGLGraphicsData(webGL.gl); webGLData.mode = type; webGL.data.push(webGLData); } - else { + else + { webGLData = webGL.data[webGL.data.length-1]; - if (webGLData.mode !== type || type === 1) { + if (webGLData.mode !== type || type === 1) + { webGLData = WebGLGraphics.graphicsDataPool.pop() || new WebGLGraphicsData(webGL.gl); webGLData.mode = type; webGL.data.push(webGLData); @@ -225,7 +254,8 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildRectangle = function (graphicsData, webGLData) { +WebGLGraphics.buildRectangle = function (graphicsData, webGLData) +{ // --- // // need to convert points to a nice regular data // @@ -235,7 +265,8 @@ var width = rectData.width; var height = rectData.height; - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -265,7 +296,8 @@ indices.push(vertPos, vertPos, vertPos+1, vertPos+2, vertPos+3, vertPos+3); } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = [x, y, @@ -289,7 +321,8 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildRoundedRectangle = function (graphicsData, webGLData) { +WebGLGraphics.buildRoundedRectangle = function (graphicsData, webGLData) +{ var rrectData = graphicsData.shape; var x = rrectData.x; var y = rrectData.y; @@ -305,7 +338,8 @@ recPoints = recPoints.concat(WebGLGraphics.quadraticBezierCurve(x + width, y + radius, x + width, y, x + width - radius, y)); recPoints = recPoints.concat(WebGLGraphics.quadraticBezierCurve(x + radius, y, x, y, x, y + radius)); - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -323,7 +357,8 @@ // var i = 0; - for (i = 0; i < triangles.length; i+=3) { + for (i = 0; i < triangles.length; i+=3) + { indices.push(triangles[i] + vecPos); indices.push(triangles[i] + vecPos); indices.push(triangles[i+1] + vecPos); @@ -332,12 +367,14 @@ } - for (i = 0; i < recPoints.length; i++) { + for (i = 0; i < recPoints.length; i++) + { verts.push(recPoints[i], recPoints[++i], r, g, b, alpha); } } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = recPoints; @@ -362,7 +399,8 @@ * @param toY {number} Destination point y * @return {number[]} */ -WebGLGraphics.quadraticBezierCurve = function (fromX, fromY, cpX, cpY, toX, toY) { +WebGLGraphics.quadraticBezierCurve = function (fromX, fromY, cpX, cpY, toX, toY) +{ var xa, ya, @@ -373,14 +411,16 @@ n = 20, points = []; - function getPt(n1 , n2, perc) { + function getPt(n1 , n2, perc) + { var diff = n2 - n1; return n1 + ( diff * perc ); } var j = 0; - for (var i = 0; i <= n; i++ ) { + for (var i = 0; i <= n; i++ ) + { j = i / n; // The Green Line @@ -406,7 +446,8 @@ * @param graphicsData {Graphics} The graphics object to draw * @param webGLData {object} */ -WebGLGraphics.buildCircle = function (graphicsData, webGLData) { +WebGLGraphics.buildCircle = function (graphicsData, webGLData) +{ // need to convert points to a nice regular data var circleData = graphicsData.shape; var x = circleData.x; @@ -415,11 +456,13 @@ var height; // TODO - bit hacky?? - if (graphicsData.type === CONST.SHAPES.CIRC) { + if (graphicsData.type === CONST.SHAPES.CIRC) + { width = circleData.radius; height = circleData.radius; } - else { + else + { width = circleData.width; height = circleData.height; } @@ -429,7 +472,8 @@ var i = 0; - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -444,7 +488,8 @@ indices.push(vecPos); - for (i = 0; i < totalSegs + 1 ; i++) { + for (i = 0; i < totalSegs + 1 ; i++) + { verts.push(x,y, r, g, b, alpha); verts.push(x + Math.sin(seg * i) * width, @@ -457,12 +502,14 @@ indices.push(vecPos-1); } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = []; - for (i = 0; i < totalSegs + 1; i++) { + for (i = 0; i < totalSegs + 1; i++) + { graphicsData.points.push(x + Math.sin(seg * i) * width, y + Math.cos(seg * i) * height); } @@ -481,18 +528,22 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildLine = function (graphicsData, webGLData) { +WebGLGraphics.buildLine = function (graphicsData, webGLData) +{ // TODO OPTIMISE! var i = 0; var points = graphicsData.points; - if (points.length === 0) { + if (points.length === 0) + { return; } // if the line width is an odd number add 0.5 to align to a whole pixel - if (graphicsData.lineWidth%2) { - for (i = 0; i < points.length; i++) { + if (graphicsData.lineWidth%2) + { + for (i = 0; i < points.length; i++) + { points[i] += 0.5; } } @@ -502,7 +553,8 @@ var lastPoint = new math.Point(points[points.length - 2], points[points.length - 1]); // if the first point is the last point - gonna have issues :) - if (firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) { + if (firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) + { // need to clone as we are going to slightly modify the shape.. points = points.slice(); @@ -562,7 +614,8 @@ verts.push(p1x + perpx , p1y + perpy, r, g, b, alpha); - for (i = 1; i < length-1; i++) { + for (i = 1; i < length-1; i++) + { p1x = points[(i-1)*2]; p1y = points[(i-1)*2 + 1]; @@ -599,7 +652,8 @@ denom = a1*b2 - a2*b1; - if (Math.abs(denom) < 0.1 ) { + if (Math.abs(denom) < 0.1 ) + { denom+=10.1; verts.push(p2x - perpx , p2y - perpy, @@ -618,7 +672,8 @@ pdist = (px -p2x) * (px -p2x) + (py -p2y) + (py -p2y); - if (pdist > 140 * 140) { + if (pdist > 140 * 140) + { perp3x = perpx - perp2x; perp3y = perpy - perp2y; @@ -639,7 +694,8 @@ indexCount++; } - else { + else + { verts.push(px , py); verts.push(r, g, b, alpha); @@ -672,7 +728,8 @@ indices.push(indexStart); - for (i = 0; i < indexCount; i++) { + for (i = 0; i < indexCount; i++) + { indices.push(indexStart++); } @@ -687,11 +744,13 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildComplexPoly = function (graphicsData, webGLData) { +WebGLGraphics.buildComplexPoly = function (graphicsData, webGLData) +{ //TODO - no need to copy this as it gets turned into a FLoat32Array anyways.. var points = graphicsData.points.slice(); - if (points.length < 6) { + if (points.length < 6) + { return; } @@ -711,7 +770,8 @@ var x,y; // get size.. - for (var i = 0; i < points.length; i+=2) { + for (var i = 0; i < points.length; i+=2) + { x = points[i]; y = points[i+1]; @@ -732,7 +792,8 @@ //TODO - this aint needed! var length = points.length / 2; - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { indices.push( i ); } @@ -746,10 +807,12 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildPoly = function (graphicsData, webGLData) { +WebGLGraphics.buildPoly = function (graphicsData, webGLData) +{ var points = graphicsData.points; - if (points.length < 6) { + if (points.length < 6) + { return; } // get first and last point.. figure out the middle! @@ -767,7 +830,8 @@ var triangles = utils.PolyK.Triangulate(points); - if (!triangles) { + if (!triangles) + { return false; } @@ -775,7 +839,8 @@ var i = 0; - for (i = 0; i < triangles.length; i+=3) { + for (i = 0; i < triangles.length; i+=3) + { indices.push(triangles[i] + vertPos); indices.push(triangles[i] + vertPos); indices.push(triangles[i+1] + vertPos); @@ -783,7 +848,8 @@ indices.push(triangles[i+2] + vertPos); } - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { verts.push(points[i * 2], points[i * 2 + 1], r, g, b, alpha); } diff --git a/src/core/renderers/webgl/utils/WebGLGraphicsData.js b/src/core/renderers/webgl/utils/WebGLGraphicsData.js index c56d05e..c739ba7 100644 --- a/src/core/renderers/webgl/utils/WebGLGraphicsData.js +++ b/src/core/renderers/webgl/utils/WebGLGraphicsData.js @@ -2,7 +2,8 @@ * @class * @private */ -function WebGLGraphicsData(gl) { +function WebGLGraphicsData(gl) +{ this.gl = gl; //TODO does this need to be split before uploding?? @@ -22,7 +23,8 @@ /** * */ -WebGLGraphicsData.prototype.reset = function () { +WebGLGraphicsData.prototype.reset = function () +{ this.points.length = 0; this.indices.length = 0; }; @@ -30,7 +32,8 @@ /** * */ -WebGLGraphicsData.prototype.upload = function () { +WebGLGraphicsData.prototype.upload = function () +{ var gl = this.gl; // this.lastIndex = graphics.graphicsData.length; diff --git a/src/core/renderers/webgl/utils/WebGLSpriteBatch.js b/src/core/renderers/webgl/utils/WebGLSpriteBatch.js index 96eaa52..55befbb 100644 --- a/src/core/renderers/webgl/utils/WebGLSpriteBatch.js +++ b/src/core/renderers/webgl/utils/WebGLSpriteBatch.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this sprite batch works for. */ -function WebGLSpriteBatch(renderer) { +function WebGLSpriteBatch(renderer) +{ /** * * @@ -88,7 +89,8 @@ */ this.lastIndexCount = 0; - for (var i=0, j=0; i < numIndices; i += 6, j += 4) { + 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; @@ -162,7 +164,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.setupContext(); }); } @@ -173,7 +176,8 @@ /** * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLSpriteBatch.prototype.setupContext = function () { +WebGLSpriteBatch.prototype.setupContext = function () +{ var gl = this.renderer.gl; // setup default shader @@ -198,7 +202,8 @@ /** * */ -WebGLSpriteBatch.prototype.begin = function () { +WebGLSpriteBatch.prototype.begin = function () +{ // this.shader = this.renderer.shaderManager.defaultShader; this.start(); @@ -206,19 +211,22 @@ /** */ -WebGLSpriteBatch.prototype.end = function () { +WebGLSpriteBatch.prototype.end = function () +{ this.flush(); }; /** * @param sprite {Sprite} the sprite to render when using this spritebatch */ -WebGLSpriteBatch.prototype.render = function (sprite) { +WebGLSpriteBatch.prototype.render = function (sprite) +{ var texture = sprite.texture; //TODO set blend modes.. // check texture.. - if (this.currentBatchSize >= this.size) { + if (this.currentBatchSize >= this.size) + { this.flush(); this.currentBaseTexture = texture.baseTexture; } @@ -227,7 +235,8 @@ var uvs = texture._uvs; // if the uvs have not updated then no point rendering just yet! - if (!uvs) { + if (!uvs) + { return; } @@ -237,7 +246,8 @@ var w0, w1, h0, h1; - if (texture.trim) { + 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; @@ -248,7 +258,8 @@ h0 = h1 + texture.crop.height; } - else { + else + { w0 = (texture.frame.width ) * (1-aX); w1 = (texture.frame.width ) * -aX; @@ -272,7 +283,8 @@ var colors = this.colors; var positions = this.positions; - if (this.renderer.roundPixels) { + if (this.renderer.roundPixels) + { // xy positions[index] = a * w1 + c * h1 + tx | 0; positions[index+1] = d * h1 + b * w1 + ty | 0; @@ -289,7 +301,8 @@ positions[index+15] = a * w1 + c * h0 + tx | 0; positions[index+16] = d * h0 + b * w1 + ty | 0; } - else { + else + { // xy positions[index] = a * w1 + c * h1 + tx; positions[index+1] = d * h1 + b * w1 + ty; @@ -338,11 +351,13 @@ * * @param sprite {TilingSprite} the tilingSprite to render */ -WebGLSpriteBatch.prototype.renderTilingSprite = function (tilingSprite) { +WebGLSpriteBatch.prototype.renderTilingSprite = function (tilingSprite) +{ var texture = tilingSprite.tilingTexture; // check texture.. - if (this.currentBatchSize >= this.size) { + if (this.currentBatchSize >= this.size) + { //return; this.flush(); this.currentBaseTexture = texture.baseTexture; @@ -351,7 +366,8 @@ // set the textures uvs temporarily // TODO create a separate texture so that we can tile part of a texture - if (!tilingSprite._uvs) { + if (!tilingSprite._uvs) + { tilingSprite._uvs = new TextureUvs(); } @@ -454,16 +470,19 @@ * Renders the content and empties the current batch. * */ -WebGLSpriteBatch.prototype.flush = function () { +WebGLSpriteBatch.prototype.flush = function () +{ // If the batch is length 0 then return as there is nothing to draw - if (this.currentBatchSize === 0) { + if (this.currentBatchSize === 0) + { return; } var gl = this.renderer.gl; var shader; - if (this.dirty) { + if (this.dirty) + { this.dirty = false; // bind the main texture gl.activeTexture(gl.TEXTURE0); @@ -482,10 +501,12 @@ } // upload the verts to the buffer - if (this.currentBatchSize > ( this.size * 0.5 ) ) { + if (this.currentBatchSize > ( this.size * 0.5 ) ) + { gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); } - else { + else + { var view = this.positions.subarray(0, this.currentBatchSize * this.vertByteSize); gl.bufferSubData(gl.ARRAY_BUFFER, 0, view); } @@ -502,7 +523,8 @@ var shaderSwap = false; var sprite; - for (var i = 0, j = this.currentBatchSize; i < j; i++) { + for (var i = 0, j = this.currentBatchSize; i < j; i++) + { sprite = this.sprites[i]; @@ -513,24 +535,28 @@ blendSwap = currentBlendMode !== nextBlendMode; shaderSwap = currentShader !== nextShader; // should I use uuidS??? - if (currentBaseTexture !== nextTexture || blendSwap || shaderSwap) { + if (currentBaseTexture !== nextTexture || blendSwap || shaderSwap) + { this.renderBatch(currentBaseTexture, batchSize, start); start = i; batchSize = 0; currentBaseTexture = nextTexture; - if (blendSwap) { + if (blendSwap) + { currentBlendMode = nextBlendMode; this.renderer.blendModeManager.setBlendMode( currentBlendMode ); } - if (shaderSwap) { + if (shaderSwap) + { currentShader = nextShader; shader = currentShader.shaders ? currentShader.shaders[gl.id] : currentShader; - if (!shader) { + if (!shader) + { shader = new Shader(gl, null, currentShader.fragmentSrc, currentShader.uniforms); currentShader.shaders[gl.id] = shader; } @@ -538,7 +564,8 @@ // set shader function??? this.renderer.shaderManager.setShader(shader); - if (shader.dirty) { + if (shader.dirty) + { shader.syncUniforms(); } @@ -569,17 +596,21 @@ * @param size {number} * @param startIndex {number} */ -WebGLSpriteBatch.prototype.renderBatch = function (texture, size, startIndex) { - if (size === 0) { +WebGLSpriteBatch.prototype.renderBatch = function (texture, size, startIndex) +{ + if (size === 0) + { return; } var gl = this.renderer.gl; - if (!texture._glTextures[gl.id]) { + if (!texture._glTextures[gl.id]) + { this.renderer.updateTexture(texture); } - else { + else + { // bind the current texture gl.bindTexture(gl.TEXTURE_2D, texture._glTextures[gl.id]); } @@ -594,7 +625,8 @@ /** * */ -WebGLSpriteBatch.prototype.stop = function () { +WebGLSpriteBatch.prototype.stop = function () +{ this.flush(); this.dirty = true; }; @@ -602,7 +634,8 @@ /** * */ -WebGLSpriteBatch.prototype.start = function () { +WebGLSpriteBatch.prototype.start = function () +{ this.dirty = true; }; @@ -610,7 +643,8 @@ * Destroys the SpriteBatch. * */ -WebGLSpriteBatch.prototype.destroy = function () { +WebGLSpriteBatch.prototype.destroy = function () +{ this.renderer.gl.deleteBuffer(this.vertexBuffer); this.renderer.gl.deleteBuffer(this.indexBuffer); diff --git a/src/core/textures/BaseTexture.js b/src/core/textures/BaseTexture.js index 2bf77d4..513d358 100644 --- a/src/core/textures/BaseTexture.js +++ b/src/core/textures/BaseTexture.js @@ -10,7 +10,8 @@ * @param source {Image|Canvas} the source object of the texture. * @param [scaleMode=scaleModes.DEFAULT] {number} See {@link scaleModes} for possible values */ -function BaseTexture(source, scaleMode) { +function BaseTexture(source, scaleMode) +{ this.uuid = utils.uuid(); /** @@ -123,7 +124,8 @@ this._needsUpdate = false; // if no source passed don't try to load - if (source) { + if (source) + { this.loadSource(source); } @@ -149,13 +151,16 @@ Object.defineProperties(BaseTexture.prototype, { needsUpdate: { - get: function () { + get: function () + { return this._needsUpdate; }, - set: function (val) { + set: function (val) + { this._needsUpdate = val; - if (val) { + if (val) + { this.emit('update', this); } } @@ -171,9 +176,11 @@ * * The logic state after calling `loadSource` directly or indirectly (eg. `fromImage`, `new BaseTexture`) is: * - * if (texture.hasLoaded) { + * if (texture.hasLoaded) + { * // texture ready for use - * } else if (texture.isLoading) { + * } else if (texture.isLoading) + { * // listen to 'loaded' and/or 'error' events on texture * } else { * // not loading, not going to load UNLESS the source is reloaded @@ -183,12 +190,14 @@ * @protected * @param source {Image|Canvas} the source object of the texture. */ -BaseTexture.prototype.loadSource = function (source) { +BaseTexture.prototype.loadSource = function (source) +{ var wasLoading = this.isLoading; this.hasLoaded = false; this.isLoading = false; - if (wasLoading && this.source) { + if (wasLoading && this.source) + { this.source.onload = null; this.source.onerror = null; } @@ -196,20 +205,24 @@ this.source = source; // Apply source if loaded. Otherwise setup appropriate loading monitors. - if ((this.source.complete || this.source.getContext) && this.source.width && this.source.height) { + if ((this.source.complete || this.source.getContext) && this.source.width && this.source.height) + { this._sourceLoaded(); } - else if(!source.getContext) { + else if(!source.getContext) + { // Image fail / not ready this.isLoading = true; var scope = this; - source.onload = function () { + source.onload = function () + { source.onload = null; source.onerror = null; - if(!scope.isLoading) { + if(!scope.isLoading) + { return; } @@ -219,11 +232,13 @@ scope.emit('loaded', scope); }; - source.onerror = function () { + source.onerror = function () + { source.onload = null; source.onerror = null; - if(!scope.isLoading) { + if(!scope.isLoading) + { return; } @@ -234,24 +249,29 @@ // Per http://www.w3.org/TR/html5/embedded-content-0.html#the-img-element // "The value of `complete` can thus change while a script is executing." // So complete needs to be re-checked after the callbacks have been added.. - if (source.complete) { + if (source.complete) + { this.isLoading = false; // ..and if we're complete now, no need for callbacks source.onload = null; source.onerror = null; - if (source.width && source.height) { + if (source.width && source.height) + { this._sourceLoaded(); // If any previous subscribers possible - if (wasLoading) { + if (wasLoading) + { this.emit('loaded', this); } } - else { + else + { // If any previous subscribers possible - if (wasLoading) { + if (wasLoading) + { this.emit('error', this); } } @@ -265,7 +285,8 @@ * * @private */ -BaseTexture.prototype._sourceLoaded = function () { +BaseTexture.prototype._sourceLoaded = function () +{ this.hasLoaded = true; this.width = this.source.naturalWidth || this.source.width; @@ -278,16 +299,20 @@ * Destroys this base texture * */ -BaseTexture.prototype.destroy = function () { - if (this.imageUrl) { +BaseTexture.prototype.destroy = function () +{ + if (this.imageUrl) + { delete utils.BaseTextureCache[this.imageUrl]; delete utils.TextureCache[this.imageUrl]; this.imageUrl = null; - if (!navigator.isCocoonJS) { + if (!navigator.isCocoonJS) + { this.source.src = ''; } } - else if (this.source && this.source._pixiId) { + else if (this.source && this.source._pixiId) + { delete utils.BaseTextureCache[this.source._pixiId]; } this.source = null; @@ -301,7 +326,8 @@ * memory again. * */ -BaseTexture.prototype.dispose = function () { +BaseTexture.prototype.dispose = function () +{ this.emit('dispose', this); }; @@ -311,7 +337,8 @@ * * @param newSrc {string} the path of the image */ -BaseTexture.prototype.updateSourceImage = function (newSrc) { +BaseTexture.prototype.updateSourceImage = function (newSrc) +{ this.source.src = newSrc; this.loadSource(this.source); }; @@ -326,18 +353,22 @@ * @param [scaleMode=scaleModes.DEFAULT] {number} See {@link scaleModes} for possible values * @return BaseTexture */ -BaseTexture.fromImage = function (imageUrl, crossorigin, scaleMode) { +BaseTexture.fromImage = function (imageUrl, crossorigin, scaleMode) +{ var baseTexture = utils.BaseTextureCache[imageUrl]; - if (crossorigin === undefined && imageUrl.indexOf('data:') !== 0) { + if (crossorigin === undefined && imageUrl.indexOf('data:') !== 0) + { crossorigin = true; } - if (!baseTexture) { + if (!baseTexture) + { // new Image() breaks tex loading in some versions of Chrome. // See https://code.google.com/p/chromium/issues/detail?id=238071 var image = new Image();//document.createElement('img'); - if (crossorigin) { + if (crossorigin) + { image.crossOrigin = ''; } @@ -347,7 +378,8 @@ utils.BaseTextureCache[imageUrl] = baseTexture; // if there is an @2x at the end of the url we are going to assume its a highres image - if ( imageUrl.indexOf(CONST.RETINA_PREFIX + '.') !== -1) { + if ( imageUrl.indexOf(CONST.RETINA_PREFIX + '.') !== -1) + { baseTexture.resolution = 2; } } @@ -363,14 +395,17 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return BaseTexture */ -BaseTexture.fromCanvas = function (canvas, scaleMode) { - if (!canvas._pixiId) { +BaseTexture.fromCanvas = function (canvas, scaleMode) +{ + if (!canvas._pixiId) + { canvas._pixiId = 'canvas_' + utils.uuid(); } var baseTexture = utils.BaseTextureCache[canvas._pixiId]; - if (!baseTexture) { + if (!baseTexture) + { baseTexture = new BaseTexture(canvas, scaleMode); utils.BaseTextureCache[canvas._pixiId] = baseTexture; } diff --git a/src/core/textures/RenderTexture.js b/src/core/textures/RenderTexture.js index 6dad20f..53ae796 100644 --- a/src/core/textures/RenderTexture.js +++ b/src/core/textures/RenderTexture.js @@ -46,8 +46,10 @@ * @param [scaleMode] {number} See {@link scaleModes} for possible values * @param [resolution=1] {number} The resolution of the texture being generated */ -function RenderTexture(renderer, width, height, scaleMode, resolution) { - if (!renderer) { +function RenderTexture(renderer, width, height, scaleMode, resolution) +{ + if (!renderer) + { throw new Error('Unable to create RenderTexture, you must pass a renderer into the constructor.'); } @@ -133,7 +135,8 @@ */ this.renderer = renderer; - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { var gl = this.renderer.gl; this.textureBuffer = new FilterTexture(gl, this.width * this.resolution, this.height * this.resolution, this.baseTexture.scaleMode); @@ -142,7 +145,8 @@ this.render = this.renderWebGL; this.projection = new math.Point(this.width*0.5, -this.height*0.5); } - else { + else + { this.render = this.renderCanvas; this.textureBuffer = new CanvasBuffer(this.width* this.resolution, this.height* this.resolution); this.baseTexture.source = this.textureBuffer.canvas; @@ -167,8 +171,10 @@ * @param height {number} The height to resize to. * @param updateBase {boolean} Should the baseTexture.width and height values be resized as well? */ -RenderTexture.prototype.resize = function (width, height, updateBase) { - if (width === this.width && height === this.height) { +RenderTexture.prototype.resize = function (width, height, updateBase) +{ + if (width === this.width && height === this.height) + { return; } @@ -177,17 +183,20 @@ this.width = this.frame.width = this.crop.width = width; this.height = this.frame.height = this.crop.height = height; - if (updateBase) { + if (updateBase) + { this.baseTexture.width = this.width; this.baseTexture.height = this.height; } - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { this.projection.x = this.width / 2; this.projection.y = -this.height / 2; } - if (!this.valid) { + if (!this.valid) + { return; } @@ -198,12 +207,15 @@ * Clears the RenderTexture. * */ -RenderTexture.prototype.clear = function () { - if (!this.valid) { +RenderTexture.prototype.clear = function () +{ + if (!this.valid) + { return; } - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { this.renderer.gl.bindFramebuffer(this.renderer.gl.FRAMEBUFFER, this.textureBuffer.frameBuffer); } @@ -220,19 +232,23 @@ * @param [restoreWorldTransform=true] {boolean} If true the displayObject's worldTransform/worldAlpha and all children * transformations will be restored. Not restoring this information will be a little faster. */ -RenderTexture.prototype.renderWebGL = function (displayObject, matrix, clear, restoreWorldTransform) { - if (!this.valid) { +RenderTexture.prototype.renderWebGL = function (displayObject, matrix, clear, restoreWorldTransform) +{ + if (!this.valid) + { return; } - if (typeof restoreWorldTransform === 'undefined') { + if (typeof restoreWorldTransform === 'undefined') + { restoreWorldTransform = true; } var tempAlpha, tempTransform; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { tempAlpha = displayObject.worldAlpha; tempTransform = displayObject.worldTransform.toArray(); } @@ -245,7 +261,8 @@ wt.identity(); wt.translate(0, this.projection.y * 2); - if (matrix) { + if (matrix) + { wt.append(matrix); } @@ -258,7 +275,8 @@ var children = displayObject.children; var i, j; - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } @@ -269,7 +287,8 @@ gl.bindFramebuffer(gl.FRAMEBUFFER, this.textureBuffer.frameBuffer ); - if (clear) { + if (clear) + { this.textureBuffer.clear(); } @@ -279,11 +298,13 @@ this.renderer.spriteBatch.dirty = true; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { displayObject.worldAlpha = tempAlpha; displayObject.worldTransform.fromArray(tempTransform); - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } } @@ -300,26 +321,31 @@ * @param [restoreWorldTransform=true] {boolean} If true the displayObject's worldTransform/worldAlpha and all children * transformations will be restored. Not restoring this information will be a little faster. */ -RenderTexture.prototype.renderCanvas = function (displayObject, matrix, clear, restoreWorldTransform) { - if (!this.valid) { +RenderTexture.prototype.renderCanvas = function (displayObject, matrix, clear, restoreWorldTransform) +{ + if (!this.valid) + { return; } - if (typeof restoreWorldTransform === 'undefined') { + if (typeof restoreWorldTransform === 'undefined') + { restoreWorldTransform = true; } var tempAlpha, tempTransform; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { tempAlpha = displayObject.worldAlpha; tempTransform = displayObject.worldTransform.toArray(); } var wt = displayObject.worldTransform; wt.identity(); - if (matrix) { + if (matrix) + { wt.append(matrix); } @@ -330,11 +356,13 @@ var children = displayObject.children; var i, j; - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } - if (clear) { + if (clear) + { this.textureBuffer.clear(); } @@ -348,11 +376,13 @@ this.renderer.resolution = realResolution; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { displayObject.worldAlpha = tempAlpha; displayObject.worldTransform.fromArray(tempTransform); - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } } @@ -363,7 +393,8 @@ * * @return {Image} */ -RenderTexture.prototype.getImage = function () { +RenderTexture.prototype.getImage = function () +{ var image = new Image(); image.src = this.getBase64(); return image; @@ -374,7 +405,8 @@ * * @return {string} A base64 encoded string of the texture. */ -RenderTexture.prototype.getBase64 = function () { +RenderTexture.prototype.getBase64 = function () +{ return this.getCanvas().toDataURL(); }; @@ -383,8 +415,10 @@ * * @return {HTMLCanvasElement} A Canvas element with the texture rendered on. */ -RenderTexture.prototype.getCanvas = function () { - if (this.renderer.type === CONST.WEBGL_RENDERER) { +RenderTexture.prototype.getCanvas = function () +{ + if (this.renderer.type === CONST.WEBGL_RENDERER) + { var gl = this.renderer.gl; var width = this.textureBuffer.width; var height = this.textureBuffer.height; @@ -403,7 +437,8 @@ return tempCanvas.canvas; } - else { + else + { return this.textureBuffer.canvas; } }; diff --git a/src/core/textures/Texture.js b/src/core/textures/Texture.js index 3c65909..e97f0aa 100644 --- a/src/core/textures/Texture.js +++ b/src/core/textures/Texture.js @@ -17,7 +17,8 @@ * @param [crop] {Rectangle} The area of original texture * @param [trim] {Rectangle} Trimmed texture rectangle */ -function Texture(baseTexture, frame, crop, trim) { +function Texture(baseTexture, frame, crop, trim) +{ /** * Does this Texture have any frame data assigned to it? * @@ -25,12 +26,14 @@ */ this.noFrame = false; - if (!frame) { + if (!frame) + { this.noFrame = true; frame = new math.Rectangle(0, 0, 1, 1); } - if (baseTexture instanceof Texture) { + if (baseTexture instanceof Texture) + { baseTexture = baseTexture.baseTexture; } @@ -100,13 +103,16 @@ */ this.crop = crop || new math.Rectangle(0, 0, 1, 1); - if (baseTexture.hasLoaded) { - if (this.noFrame) { + if (baseTexture.hasLoaded) + { + if (this.noFrame) + { frame = new math.Rectangle(0, 0, baseTexture.width, baseTexture.height); } this.frame = frame; } - else { + else + { baseTexture.addEventListener('loaded', this.onBaseTextureLoaded.bind(this)); } } @@ -118,19 +124,23 @@ Object.defineProperties(Texture.prototype, { needsUpdate: { - get: function () { + get: function () + { return this.baseTexture.needsUpdate; }, - set: function (val) { + set: function (val) + { this.baseTexture.needsUpdate = val; } }, frame: { - get: function () { + get: function () + { return this._frame; }, - set: function (frame) { + set: function (frame) + { this._frame = frame; this.noFrame = false; @@ -143,20 +153,23 @@ 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 (!this.trim && (frame.x + frame.width > this.baseTexture.width || frame.y + frame.height > this.baseTexture.height)) + { throw new Error('Texture Error: frame does not fit inside the base Texture dimensions ' + this); } this.valid = frame && frame.width && frame.height && this.baseTexture.source && this.baseTexture.hasLoaded; - if (this.trim) { + 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) { + if (this.valid) + { this._updateUvs(); } } @@ -168,11 +181,13 @@ * * @private */ -Texture.prototype.onBaseTextureLoaded = function () { +Texture.prototype.onBaseTextureLoaded = function () +{ var baseTexture = this.baseTexture; baseTexture.removeEventListener('loaded', this.onLoaded); - if (this.noFrame) { + if (this.noFrame) + { this.frame = new math.Rectangle(0, 0, baseTexture.width, baseTexture.height); } @@ -184,8 +199,10 @@ * * @param destroyBase {boolean} Whether to destroy the base texture as well */ -Texture.prototype.destroy = function (destroyBase) { - if (destroyBase) { +Texture.prototype.destroy = function (destroyBase) +{ + if (destroyBase) + { this.baseTexture.destroy(); } @@ -197,8 +214,10 @@ * * @private */ -Texture.prototype._updateUvs = function () { - if (!this._uvs) { +Texture.prototype._updateUvs = function () +{ + if (!this._uvs) + { this._uvs = new TextureUvs(); } @@ -229,10 +248,12 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return Texture */ -Texture.fromImage = function (imageUrl, crossorigin, scaleMode) { +Texture.fromImage = function (imageUrl, crossorigin, scaleMode) +{ var texture = utils.TextureCache[imageUrl]; - if (!texture) { + if (!texture) + { texture = new Texture(BaseTexture.fromImage(imageUrl, crossorigin, scaleMode)); utils.TextureCache[imageUrl] = texture; } @@ -248,9 +269,11 @@ * @param frameId {string} The frame id of the texture * @return Texture */ -Texture.fromFrame = function (frameId) { +Texture.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache '); } return texture; @@ -264,7 +287,8 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return {Texture} */ -Texture.fromCanvas = function (canvas, scaleMode) { +Texture.fromCanvas = function (canvas, scaleMode) +{ return new Texture(BaseTexture.fromCanvas(canvas, scaleMode)); }; @@ -276,7 +300,8 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return {Texture} A Texture */ -Texture.fromVideo = function (video, scaleMode) { +Texture.fromVideo = function (video, scaleMode) +{ return new Texture(VideoBaseTexture.baseTextureFromVideo(video, scaleMode)); }; @@ -287,7 +312,8 @@ * @param texture {Texture} The Texture to add to the cache. * @param id {string} The id that the texture will be stored against. */ -Texture.addTextureToCache = function (texture, id) { +Texture.addTextureToCache = function (texture, id) +{ utils.TextureCache[id] = texture; }; @@ -298,7 +324,8 @@ * @param id {string} The id of the texture to be removed * @return {Texture} The texture that was removed */ -Texture.removeTextureFromCache = function (id) { +Texture.removeTextureFromCache = function (id) +{ var texture = utils.TextureCache[id]; delete utils.TextureCache[id]; diff --git a/src/core/textures/TextureUvs.js b/src/core/textures/TextureUvs.js index b9bbb58..5424d52 100644 --- a/src/core/textures/TextureUvs.js +++ b/src/core/textures/TextureUvs.js @@ -1,4 +1,5 @@ -function TextureUvs() { +function TextureUvs() +{ this.x0 = 0; this.y0 = 0; diff --git a/src/core/textures/VideoBaseTexture.js b/src/core/textures/VideoBaseTexture.js index e3e0c5a..1a826a9 100644 --- a/src/core/textures/VideoBaseTexture.js +++ b/src/core/textures/VideoBaseTexture.js @@ -12,15 +12,18 @@ * @param source {HTMLVideoElement} * @param [scaleMode] {number} See {@link scaleModes} for possible values */ -function VideoBaseTexture(source, scaleMode) { - if (!source){ +function VideoBaseTexture(source, scaleMode) +{ + if (!source) + { throw new Error('No video source element specified.'); } // hook in here to check if video is already available. // BaseTexture looks for a source.complete boolean, plus width & height. - if ((source.readyState === source.HAVE_ENOUGH_DATA || source.readyState === source.HAVE_FUTURE_DATA) && source.width && source.height) { + if ((source.readyState === source.HAVE_ENOUGH_DATA || source.readyState === source.HAVE_FUTURE_DATA) && source.width && source.height) + { source.complete = true; } @@ -31,7 +34,8 @@ this._boundOnUpdate = this._onUpdate.bind(this); this._boundOnCanPlay = this._onCanPlay.bind(this); - if (!source.complete) { + if (!source.complete) + { source.addEventListener('canplay', this._boundOnCanPlay); source.addEventListener('canplaythrough', this._boundOnCanPlay); @@ -47,28 +51,35 @@ VideoBaseTexture.prototype.constructor = VideoBaseTexture; module.exports = VideoBaseTexture; -VideoBaseTexture.prototype._onUpdate = function () { - if (this.autoUpdate) { +VideoBaseTexture.prototype._onUpdate = function () +{ + if (this.autoUpdate) + { window.requestAnimationFrame(this._boundOnUpdate); this.needsUpdate = true; } }; -VideoBaseTexture.prototype._onPlayStart = function () { - if (!this.autoUpdate) { +VideoBaseTexture.prototype._onPlayStart = function () +{ + if (!this.autoUpdate) + { window.requestAnimationFrame(this._boundOnUpdate); this.autoUpdate = true; } }; -VideoBaseTexture.prototype._onPlayStop = function () { +VideoBaseTexture.prototype._onPlayStop = function () +{ this.autoUpdate = false; }; -VideoBaseTexture.prototype._onCanPlay = function () { +VideoBaseTexture.prototype._onCanPlay = function () +{ this.hasLoaded = true; - if (this.source) { + if (this.source) + { this.source.removeEventListener('canplay', this._boundOnCanPlay); this.source.removeEventListener('canplaythrough', this._boundOnCanPlay); @@ -78,15 +89,18 @@ this.source.play(); // prevent multiple loaded dispatches.. - if(!this.__loaded){ + if(!this.__loaded) + { this.__loaded = true; this.emit('loaded', this); } } }; -VideoBaseTexture.prototype.destroy = function () { - if (this.source && this.source._pixiId) { +VideoBaseTexture.prototype.destroy = function () +{ + if (this.source && this.source._pixiId) + { utils.BaseTextureCache[ this.source._pixiId ] = null; delete utils.BaseTextureCache[ this.source._pixiId ]; @@ -105,14 +119,17 @@ * @param scaleMode {number} See {@link scaleModes} for possible values * @return {VideoBaseTexture} */ -VideoBaseTexture.fromVideo = function (video, scaleMode) { - if (!video._pixiId) { +VideoBaseTexture.fromVideo = function (video, scaleMode) +{ + if (!video._pixiId) + { video._pixiId = 'video_' + utils.uuid(); } var baseTexture = utils.BaseTextureCache[video._pixiId]; - if (!baseTexture) { + if (!baseTexture) + { baseTexture = new VideoBaseTexture(video, scaleMode); utils.BaseTextureCache[ video._pixiId ] = baseTexture; } @@ -147,17 +164,21 @@ * @param scaleMode {number} See {@link scaleModes} for possible values * @return {VideoBaseTexture} */ -VideoBaseTexture.fromUrl = function (videoSrc, scaleMode) { +VideoBaseTexture.fromUrl = function (videoSrc, scaleMode) +{ var video = document.createElement('video'); // array of objects or strings - if (Array.isArray(videoSrc)) { - for (var i = 0; i < videoSrc.length; ++i) { + if (Array.isArray(videoSrc)) + { + for (var i = 0; i < videoSrc.length; ++i) + { video.appendChild(createSource(videoSrc.src || videoSrc, videoSrc.mime)); } } // single object or string - else { + else + { video.appendChild(createSource(videoSrc.src || videoSrc, videoSrc.mime)); } @@ -169,8 +190,10 @@ VideoBaseTexture.fromUrls = VideoBaseTexture.fromUrl; -function createSource(path, type) { - if (!type) { +function createSource(path, type) +{ + if (!type) + { type = 'video/' + path.substr(path.lastIndexOf('.') + 1); } diff --git a/src/core/utils/EventData.js b/src/core/utils/EventData.js index 5d55a22..8cdf701 100644 --- a/src/core/utils/EventData.js +++ b/src/core/utils/EventData.js @@ -7,7 +7,8 @@ * @param name {string} The string name of the event that was triggered * @param data {object} Arbitrary event data to pass along */ -function EventData(target, name, data) { +function EventData(target, name, data) +{ // for duck typing in the ".on()" function this.__isEventObject = true; @@ -71,7 +72,8 @@ * Stops the propagation of events up the scene graph (prevents bubbling). * */ -EventData.prototype.stopPropagation = function stopPropagation() { +EventData.prototype.stopPropagation = function stopPropagation() +{ this.stopped = true; }; @@ -79,6 +81,7 @@ * Stops the propagation of events to sibling listeners (no longer calls any listeners). * */ -EventData.prototype.stopImmediatePropagation = function stopImmediatePropagation() { +EventData.prototype.stopImmediatePropagation = function stopImmediatePropagation() +{ this.stoppedImmediate = true; }; diff --git a/src/core/utils/EventTarget.js b/src/core/utils/EventTarget.js index 7ae8820..671a151 100644 --- a/src/core/utils/EventTarget.js +++ b/src/core/utils/EventTarget.js @@ -13,14 +13,16 @@ * var em = new MyEmitter(); * em.emit('eventName', 'some data', 'some more data', {}, null, ...); */ -function eventTarget(obj) { +function eventTarget(obj) +{ /** * Return a list of assigned event listeners. * * @param eventName {string} The events that should be listed. * @return {Array} An array of listener functions */ - obj.listeners = function listeners(eventName) { + obj.listeners = function listeners(eventName) + { this._listeners = this._listeners || {}; return this._listeners[eventName] ? this._listeners[eventName].slice() : []; @@ -33,22 +35,26 @@ * @param eventName {string} The name of the event. * @return {boolean} Indication if we've emitted an event. */ - obj.emit = obj.dispatchEvent = function emit(eventName, data) { + obj.emit = obj.dispatchEvent = function emit(eventName, data) + { this._listeners = this._listeners || {}; // fast return when there are no listeners - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return; } //backwards compat with old method ".emit({ type: 'something' })" - if (typeof eventName === 'object') { + if (typeof eventName === 'object') + { data = eventName; eventName = eventName.type; } //ensure we are using a real pixi event - if (!data || data.__isEventObject !== true) { + if (!data || data.__isEventObject !== true) + { data = new EventData(this, eventName, data); } @@ -58,23 +64,27 @@ fn = listeners[0], i; - for (i = 0; i < length; fn = listeners[++i]) { + for (i = 0; i < length; fn = listeners[++i]) + { //call the event listener fn.call(this, data); //if "stopImmediatePropagation" is called, stop calling sibling events - if (data.stoppedImmediate) { + if (data.stoppedImmediate) + { return this; } } //if "stopPropagation" is called then don't bubble the event - if (data.stopped) { + if (data.stopped) + { return this; } //bubble this event up the scene graph - if (this.parent && this.parent.emit) { + if (this.parent && this.parent.emit) + { this.parent.emit.call(this.parent, eventName, data); } @@ -88,7 +98,8 @@ * @param eventName {string} Name of the event. * @param callback {Functon} fn Callback function. */ - obj.on = obj.addEventListener = function on(eventName, fn) { + obj.on = obj.addEventListener = function on(eventName, fn) + { this._listeners = this._listeners || {}; (this._listeners[eventName] = this._listeners[eventName] || []) @@ -103,11 +114,13 @@ * @param eventName {string} Name of the event. * @param callback {Function} Callback function. */ - obj.once = function once(eventName, fn) { + obj.once = function once(eventName, fn) + { this._listeners = this._listeners || {}; var self = this; - function onceHandlerWrapper() { + function onceHandlerWrapper() + { fn.apply(self.off(eventName, onceHandlerWrapper), arguments); } onceHandlerWrapper._originalHandler = fn; @@ -122,23 +135,28 @@ * @param eventName {string} The event we want to remove. * @param callback {Function} The listener that we need to find. */ - obj.off = obj.removeEventListener = function off(eventName, fn) { + obj.off = obj.removeEventListener = function off(eventName, fn) + { this._listeners = this._listeners || {}; - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return this; } var list = this._listeners[eventName], i = fn ? list.length : 0; - while(i-- > 0) { - if (list[i] === fn || list[i]._originalHandler === fn) { + while(i-- > 0) + { + if (list[i] === fn || list[i]._originalHandler === fn) + { list.splice(i, 1); } } - if (list.length === 0) { + if (list.length === 0) + { delete this._listeners[eventName]; } @@ -150,10 +168,12 @@ * * @param eventName {string} The event you want to remove all listeners for. */ - obj.removeAllListeners = function removeAllListeners(eventName) { + obj.removeAllListeners = function removeAllListeners(eventName) + { this._listeners = this._listeners || {}; - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return this; } @@ -169,7 +189,8 @@ * * @param object {object} The obj to mix into */ - mixin: function mixin(obj) { + mixin: function mixin(obj) + { eventTarget(obj); } }; diff --git a/src/core/utils/PolyK.js b/src/core/utils/PolyK.js index 7325141..5e20c2b 100644 --- a/src/core/utils/PolyK.js +++ b/src/core/utils/PolyK.js @@ -47,7 +47,8 @@ * Triangulates shapes for webGL graphic fills. * */ -PolyK.Triangulate = function (p) { +PolyK.Triangulate = function (p) +{ var sign = true; var n = p.length >> 1; @@ -59,7 +60,8 @@ i = 0; var al = n; - while(al > 3) { + while(al > 3) + { var i0 = avl[(i+0)%al]; var i1 = avl[(i+1)%al]; var i2 = avl[(i+2)%al]; @@ -69,29 +71,35 @@ var cx = p[2*i2], cy = p[2*i2+1]; var earFound = false; - if (PolyK._convex(ax, ay, bx, by, cx, cy, sign)) { + if (PolyK._convex(ax, ay, bx, by, cx, cy, sign)) + { earFound = true; - for (var j = 0; j < al; j++) { + for (var j = 0; j < al; j++) + { var vi = avl[j]; if (vi === i0 || vi === i1 || vi === i2) continue; - if (PolyK._PointInTriangle(p[2*vi], p[2*vi+1], ax, ay, bx, by, cx, cy)) { + if (PolyK._PointInTriangle(p[2*vi], p[2*vi+1], ax, ay, bx, by, cx, cy)) + { earFound = false; break; } } } - if (earFound) { + if (earFound) + { tgs.push(i0, i1, i2); avl.splice((i+1)%al, 1); al--; i = 0; } - else if (i++ > 3*al) { + else if (i++ > 3*al) + { // need to flip flip reverse it! // reset! - if (sign) { + if (sign) + { tgs = []; avl = []; for (i = 0; i < n; i++) avl.push(i); @@ -101,7 +109,8 @@ sign = false; } - else { + else + { // window.console.log("PIXI Warning: shape too complex to fill"); return null; } @@ -126,7 +135,8 @@ * @private * @return {boolean} */ -PolyK._PointInTriangle = function (px, py, ax, ay, bx, by, cx, cy) { +PolyK._PointInTriangle = function (px, py, ax, ay, bx, by, cx, cy) +{ var v0x = cx-ax; var v0y = cy-ay; var v1x = bx-ax; @@ -154,6 +164,7 @@ * @private * @return {boolean} */ -PolyK._convex = function (ax, ay, bx, by, cx, cy, sign) { +PolyK._convex = function (ax, ay, bx, by, cx, cy, sign) +{ return ((ay-by)*(cx-bx) + (bx-ax)*(cy-by) >= 0) === sign; }; diff --git a/src/core/utils/index.js b/src/core/utils/index.js index ade9831..bfae7ae 100644 --- a/src/core/utils/index.js +++ b/src/core/utils/index.js @@ -16,7 +16,8 @@ * * @return {number} The next uuid to use. */ - uuid: function () { + uuid: function () + { return ++utils._uid; }, @@ -26,7 +27,8 @@ * @param hex {number} * @return {number[]} An array representing the [R, G, B] of the color. */ - hex2rgb: function (hex, out) { + hex2rgb: function (hex, out) + { out = out || []; out[0] = (hex >> 16 & 0xFF) / 255; @@ -42,7 +44,8 @@ * @param hex {number} * @return {string} The string color. */ - hex2string: function (hex) { + hex2string: function (hex) + { hex = hex.toString(16); hex = '000000'.substr(0, 6 - hex.length) + hex; @@ -55,7 +58,8 @@ * @param rgb {number[]} * @return {number} The color number */ - rgb2hex: function (rgb) { + rgb2hex: function (rgb) + { return ((rgb[0]*255 << 16) + (rgb[1]*255 << 8) + rgb[2]*255); }, @@ -64,8 +68,10 @@ * * @return {boolean} whether they are supported */ - canUseNewCanvasBlendModes: function () { - if (typeof document === 'undefined') { + canUseNewCanvasBlendModes: function () + { + if (typeof document === 'undefined') + { return false; } @@ -93,15 +99,19 @@ * @param number {number} * @return {number} the closest number that is a power of two */ - getNextPowerOfTwo: function (number) { + getNextPowerOfTwo: function (number) + { // see: http://en.wikipedia.org/wiki/Power_of_two#Fast_algorithm_to_check_if_a_positive_number_is_a_power_of_two - if (number > 0 && (number & (number - 1)) === 0) { + if (number > 0 && (number & (number - 1)) === 0) + { return number; } - else { + else + { var result = 1; - while (result < number) { + while (result < number) + { result <<= 1; } @@ -116,7 +126,8 @@ * @param height {number} * @return {boolean} */ - isPowerOfTwo: function (width, height) { + isPowerOfTwo: function (width, height) + { return (width > 0 && (width & (width - 1)) === 0 && height > 0 && (height & (height - 1)) === 0); }, @@ -130,12 +141,15 @@ * @constant * @static */ - sayHello: function (type) { - if (utils._saidHello) { + sayHello: function (type) + { + if (utils._saidHello) + { return; } - if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) { + if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) + { var args = [ '%c %c %c Pixi.js ' + CONST.VERSION + ' - ' + type + ' %c ' + ' %c ' + ' http://www.pixijs.com/ %c %c ♥%c♥%c♥ ', 'background: #ff66a5', @@ -151,7 +165,8 @@ console.log.apply(console, args); //jshint ignore:line } - else if (window.console) { + else if (window.console) + { console.log('Pixi.js ' + CONST.VERSION + ' - ' + type + ' - http://www.pixijs.com/'); //jshint ignore:line } @@ -166,15 +181,19 @@ * @class * @namespace PIXI */ - AjaxRequest: function () { + AjaxRequest: function () + { var activexmodes = ['Msxml2.XMLHTTP.6.0', 'Msxml2.XMLHTTP.3.0', 'Microsoft.XMLHTTP']; //activeX versions to check for in IE - if (window.ActiveXObject) { //Test for support for ActiveXObject in IE first (as XMLHttpRequest in IE7 is broken) - for (var i=0; i= this.textures.length) { + else if (round >= this.textures.length) + { this.gotoAndStop(this.textures.length - 1); - if (this.onComplete) { + if (this.onComplete) + { this.onComplete(); } } @@ -167,10 +182,12 @@ * @static * @param frames {string[]} the array of frames ids the movieclip will use as its texture frames */ -MovieClip.fromFrames = function (frames) { +MovieClip.fromFrames = function (frames) +{ var textures = []; - for (var i = 0; i < frames.length; ++i) { + for (var i = 0; i < frames.length; ++i) + { textures.push(new core.Texture.fromFrame(frames[i])); } @@ -183,10 +200,12 @@ * @static * @param images {string[]} the array of image urls the movieclip will use as its texture frames */ -MovieClip.fromImages = function (images) { +MovieClip.fromImages = function (images) +{ var textures = []; - for (var i = 0; i < images.length; ++i) { + for (var i = 0; i < images.length; ++i) + { textures.push(new core.Texture.fromImage(images[i])); } diff --git a/src/extras/Rope.js b/src/extras/Rope.js index c157ec4..9c87bc0 100644 --- a/src/extras/Rope.js +++ b/src/extras/Rope.js @@ -9,7 +9,8 @@ * @param {Array} points - An array of {Point}. * */ -function Rope(texture, points) { +function Rope(texture, points) +{ Strip.call(this, texture); this.points = points; @@ -31,10 +32,12 @@ * Refreshes * */ -Rope.prototype.refresh = function () { +Rope.prototype.refresh = function () +{ var points = this.points; - if (points.length < 1) { + if (points.length < 1) + { return; } @@ -59,20 +62,23 @@ var total = points.length, point, index, amount; - for (var i = 1; i < total; i++) { + for (var i = 1; i < total; i++) + { point = points[i]; index = i * 4; // time to do some smart drawing! amount = i / (total-1); - if (i%2) { + if (i%2) + { uvs[index] = amount; uvs[index+1] = 0; uvs[index+2] = amount; uvs[index+3] = 1; } - else { + else + { uvs[index] = amount; uvs[index+1] = 0; @@ -95,10 +101,12 @@ * * @private */ -Rope.prototype.updateTransform = function () { +Rope.prototype.updateTransform = function () +{ var points = this.points; - if (points.length < 1) { + if (points.length < 1) + { return; } @@ -113,14 +121,17 @@ var total = points.length, point, index, ratio, perpLength, num; - for (var i = 0; i < total; i++) { + for (var i = 0; i < total; i++) + { point = points[i]; index = i * 4; - if (i < points.length-1) { + if (i < points.length-1) + { nextPoint = points[i+1]; } - else { + else + { nextPoint = point; } @@ -129,7 +140,8 @@ ratio = (1 - (i / (total-1))) * 10; - if (ratio > 1) { + if (ratio > 1) + { ratio = 1; } @@ -157,7 +169,8 @@ * * @param texture {Texture} the texture that will be used */ -Rope.prototype.setTexture = function (texture) { +Rope.prototype.setTexture = function (texture) +{ // stop current texture this.texture = texture; //this.updateFrame = true; diff --git a/src/extras/Strip.js b/src/extras/Strip.js index c5e378f..57691b5 100644 --- a/src/extras/Strip.js +++ b/src/extras/Strip.js @@ -10,7 +10,8 @@ * @param height {number} the height * */ -function Strip(texture) { +function Strip(texture) +{ core.DisplayObjectContainer.call(this); /** @@ -70,9 +71,11 @@ * * @param renderer {WebGLRenderer} */ -Strip.prototype.renderWebGL = function (renderer) { +Strip.prototype.renderWebGL = function (renderer) +{ // if the sprite is not visible or the alpha is 0 then no need to render this element - if (!this.visible || this.alpha <= 0) { + if (!this.visible || this.alpha <= 0) + { return; } @@ -81,7 +84,8 @@ renderer.spriteBatch.stop(); // init! init! - if (!this._vertexBuffer) { + if (!this._vertexBuffer) + { this._initWebGL(renderer); } @@ -96,7 +100,8 @@ //TODO check culling }; -Strip.prototype._initWebGL = function (renderer) { +Strip.prototype._initWebGL = function (renderer) +{ // build the strip! var gl = renderer.gl; @@ -118,7 +123,8 @@ gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this.indices, gl.STATIC_DRAW); }; -Strip.prototype._renderStrip = function (renderer) { +Strip.prototype._renderStrip = function (renderer) +{ var gl = renderer.gl; var projection = renderer.projection, offset = renderer.offset, @@ -137,7 +143,8 @@ gl.uniform2f(shader.offsetVector, -offset.x, -offset.y); gl.uniform1f(shader.alpha, this.worldAlpha); - if (!this.dirty) { + if (!this.dirty) + { gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexBuffer); gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); @@ -150,10 +157,12 @@ gl.activeTexture(gl.TEXTURE0); // check if a texture is dirty.. - if (this.texture.baseTexture._dirty[gl.id]) { + if (this.texture.baseTexture._dirty[gl.id]) + { renderer.updateTexture(this.texture.baseTexture); } - else { + else + { // bind the current texture gl.bindTexture(gl.TEXTURE_2D, this.texture.baseTexture._glTextures[gl.id]); } @@ -163,7 +172,8 @@ } - else { + else + { this.dirty = false; gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexBuffer); @@ -178,10 +188,12 @@ gl.activeTexture(gl.TEXTURE0); // check if a texture is dirty.. - if (this.texture.baseTexture._dirty[gl.id]) { + if (this.texture.baseTexture._dirty[gl.id]) + { renderer.updateTexture(this.texture.baseTexture); } - else { + else + { gl.bindTexture(gl.TEXTURE_2D, this.texture.baseTexture._glTextures[gl.id]); } @@ -203,27 +215,33 @@ * * @param renderer {CanvasRenderer} */ -Strip.prototype.renderCanvas = function (renderer) { +Strip.prototype.renderCanvas = function (renderer) +{ var context = renderer.context; var transform = this.worldTransform; - if (renderer.roundPixels) { + if (renderer.roundPixels) + { context.setTransform(transform.a, transform.b, transform.c, transform.d, transform.tx | 0, transform.ty | 0); } - else { + else + { context.setTransform(transform.a, transform.b, transform.c, transform.d, transform.tx, transform.ty); } - if (this.drawMode === Strip.DrawModes.TRIANGLE_STRIP) { + if (this.drawMode === Strip.DrawModes.TRIANGLE_STRIP) + { this._renderCanvasTriangleStrip(context); } - else { + else + { this._renderCanvasTriangles(context); } }; -Strip.prototype._renderCanvasTriangleStrip = function (context) { +Strip.prototype._renderCanvasTriangleStrip = function (context) +{ // draw triangles!! var vertices = this.vertices; var uvs = this.uvs; @@ -231,14 +249,16 @@ var length = vertices.length / 2; // this.count++; - for (var i = 0; i < length - 2; i++) { + for (var i = 0; i < length - 2; i++) + { // draw some triangles! var index = i * 2; this._renderCanvasDrawTriangle(context, vertices, uvs, index, (index + 2), (index + 4)); } }; -Strip.prototype._renderCanvasTriangles = function (context) { +Strip.prototype._renderCanvasTriangles = function (context) +{ // draw triangles!! var vertices = this.vertices; var uvs = this.uvs; @@ -247,14 +267,16 @@ var length = indices.length; // this.count++; - for (var i = 0; i < length; i += 3) { + for (var i = 0; i < length; i += 3) + { // draw some triangles! var index0 = indices[i] * 2, index1 = indices[i + 1] * 2, index2 = indices[i + 2] * 2; this._renderCanvasDrawTriangle(context, vertices, uvs, index0, index1, index2); } }; -Strip.prototype._renderCanvasDrawTriangle = function (context, vertices, uvs, index0, index1, index2) { +Strip.prototype._renderCanvasDrawTriangle = function (context, vertices, uvs, index0, index1, index2) +{ var textureSource = this.texture.baseTexture.source; var textureWidth = this.texture.width; var textureHeight = this.texture.height; @@ -265,7 +287,8 @@ var u0 = uvs[index0] * textureWidth, u1 = uvs[index1] * textureWidth, u2 = uvs[index2] * textureWidth; var v0 = uvs[index0 + 1] * textureHeight, v1 = uvs[index1 + 1] * textureHeight, v2 = uvs[index2 + 1] * textureHeight; - if (this.canvasPadding > 0) { + if (this.canvasPadding > 0) + { var paddingX = this.canvasPadding / this.worldTransform.a; var paddingY = this.canvasPadding / this.worldTransform.d; var centerX = (x0 + x1 + x2) / 3; @@ -332,7 +355,8 @@ * @param strip {Strip} The Strip to render * @private */ -Strip.prototype.renderStripFlat = function (strip) { +Strip.prototype.renderStripFlat = function (strip) +{ var context = this.context; var vertices = strip.vertices; @@ -340,7 +364,8 @@ // this.count++; context.beginPath(); - for (var i=1; i < length-2; i++) { + for (var i=1; i < length-2; i++) + { // draw some triangles! var index = i*2; @@ -358,7 +383,8 @@ }; /* -Strip.prototype.setTexture = function (texture) { +Strip.prototype.setTexture = function (texture) +{ //TODO SET THE TEXTURES //TODO VISIBILITY @@ -377,7 +403,8 @@ * @private */ -Strip.prototype.onTextureUpdate = function () { +Strip.prototype.onTextureUpdate = function () +{ this.updateFrame = true; }; @@ -387,7 +414,8 @@ * @param matrix {Matrix} the transformation matrix of the sprite * @return {Rectangle} the framing rectangle */ -Strip.prototype.getBounds = function (matrix) { +Strip.prototype.getBounds = function (matrix) +{ var worldTransform = matrix || this.worldTransform; var a = worldTransform.a; @@ -404,7 +432,8 @@ var minY = Infinity; var vertices = this.vertices; - for (var i = 0, n = vertices.length; i < n; i += 2) { + for (var i = 0, n = vertices.length; i < n; i += 2) + { var rawX = vertices[i], rawY = vertices[i + 1]; var x = (a * rawX) + (c * rawY) + tx; var y = (d * rawY) + (b * rawX) + ty; @@ -416,7 +445,8 @@ maxY = y > maxY ? y : maxY; } - if (minX === -Infinity || maxY === Infinity) { + if (minX === -Infinity || maxY === Infinity) + { return core.math.Rectangle.EMPTY; } diff --git a/src/extras/TilingSprite.js b/src/extras/TilingSprite.js index 3ac22df..31da393 100644 --- a/src/extras/TilingSprite.js +++ b/src/extras/TilingSprite.js @@ -10,7 +10,8 @@ * @param width {number} the width of the tiling sprite * @param height {number} the height of the tiling sprite */ -function TilingSprite(texture, width, height) { +function TilingSprite(texture, width, height) +{ core.Sprite.call( this, texture); /** @@ -86,10 +87,12 @@ * @memberof TilingSprite# */ width: { - get: function () { + get: function () + { return this._width; }, - set: function (value) { + set: function (value) + { this._width = value; } }, @@ -101,20 +104,25 @@ * @memberof TilingSprite# */ height: { - get: function () { + get: function () + { return this._height; }, - set: function (value) { + set: function (value) + { this._height = value; } }, texture: { - get: function () { + get: function () + { return this._texture; }, - set: function (value) { - if (this._texture === value) { + set: function (value) + { + if (this._texture === value) + { return; } @@ -130,51 +138,61 @@ * * @param renderer {WebGLRenderer} */ -TilingSprite.prototype.renderWebGL = function (renderer) { - if (!this.visible || this.alpha <= 0) { +TilingSprite.prototype.renderWebGL = function (renderer) +{ + if (!this.visible || this.alpha <= 0) + { return; } var i, j; - if (this._mask) { + if (this._mask) + { renderer.spriteBatch.stop(); renderer.maskManager.pushMask(this.mask, renderer); renderer.spriteBatch.start(); } - if (this._filters) { + if (this._filters) + { renderer.spriteBatch.flush(); renderer.filterManager.pushFilter(this._filterBlock); } - if (!this.tilingTexture || this.refreshTexture) { + if (!this.tilingTexture || this.refreshTexture) + { this.generateTilingTexture(true); - if (this.tilingTexture && this.tilingTexture.needsUpdate) { + if (this.tilingTexture && this.tilingTexture.needsUpdate) + { //TODO - tweaking renderer.updateTexture(this.tilingTexture.baseTexture); this.tilingTexture.needsUpdate = false; // this.tilingTexture._uvs = null; } } - else { + else + { renderer.spriteBatch.renderTilingSprite(this); } // simple render children! - for (i=0,j=this.children.length; i= 0; i--) { + for (var i = length - 1; i >= 0; i--) + { var child = children[i]; // push all interactive bits - if (child._interactive) { + if (child._interactive) + { iParent.interactiveChildren = true; //child.__iParent = iParent; this.interactiveItems.push(child); - if (child.children.length > 0) { + if (child.children.length > 0) + { this.collectInteractiveSprite(child, child); } } - else { + else + { child.__iParent = null; - if (child.children.length > 0) { + if (child.children.length > 0) + { this.collectInteractiveSprite(child, iParent); } } @@ -189,7 +196,8 @@ * @param [resolution=1] {number} THe resolution of the new element (relative to the canvas). * @private */ -InteractionManager.prototype.setTargetElement = function (element, resolution) { +InteractionManager.prototype.setTargetElement = function (element, resolution) +{ this.removeEvents(); this.interactionDOMElement = element; @@ -203,12 +211,15 @@ * * @private */ -InteractionManager.prototype.addEvents = function () { - if (!this.interactionDOMElement) { +InteractionManager.prototype.addEvents = function () +{ + if (!this.interactionDOMElement) + { return; } - if (window.navigator.msPointerEnabled) { + if (window.navigator.msPointerEnabled) + { this.interactionDOMElement.style['-ms-content-zooming'] = 'none'; this.interactionDOMElement.style['-ms-touch-action'] = 'none'; } @@ -230,12 +241,15 @@ * * @private */ -InteractionManager.prototype.removeEvents = function () { - if (!this.interactionDOMElement) { +InteractionManager.prototype.removeEvents = function () +{ + if (!this.interactionDOMElement) + { return; } - if (window.navigator.msPointerEnabled) { + if (window.navigator.msPointerEnabled) + { this.interactionDOMElement.style['-ms-content-zooming'] = ''; this.interactionDOMElement.style['-ms-touch-action'] = ''; } @@ -260,8 +274,10 @@ * * @private */ -InteractionManager.prototype.update = function () { - if (!this.interactionDOMElement) { +InteractionManager.prototype.update = function () +{ + if (!this.interactionDOMElement) + { return; } @@ -269,7 +285,8 @@ var now = Date.now(); var diff = now - this.last; diff = (diff * INTERACTION_FREQUENCY ) / 1000; - if (diff < 1) { + if (diff < 1) + { return; } @@ -280,7 +297,8 @@ // ok.. so mouse events?? // yes for now :) // OPTIMISE - how often to check?? - if (this.dirty) { + if (this.dirty) + { this.rebuildInteractiveGraph(); } @@ -289,7 +307,8 @@ var cursor = 'inherit'; var over = false; - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { var item = this.interactiveItems[i]; // OPTIMISATION - only calculate every time if the mousemove function exists.. @@ -302,26 +321,34 @@ this.mouse.target = item; // ok so deal with interactions.. // looks like there was a hit! - if (item.__hit && !over) { - if (item.buttonMode) { + if (item.__hit && !over) + { + if (item.buttonMode) + { cursor = item.defaultCursor; } - if (!item.interactiveChildren) { + if (!item.interactiveChildren) + { over = true; } - if (!item.__isOver) { - if (item.mouseover) { + if (!item.__isOver) + { + if (item.mouseover) + { item.mouseover (this.mouse); } item.__isOver = true; } } - else { - if (item.__isOver) { + else + { + if (item.__isOver) + { // roll out! - if (item.mouseout) { + if (item.mouseout) + { item.mouseout (this.mouse); } item.__isOver = false; @@ -329,7 +356,8 @@ } } - if (this.currentCursorStyle !== cursor) { + if (this.currentCursorStyle !== cursor) + { this.currentCursorStyle = cursor; this.interactionDOMElement.style.cursor = cursor; } @@ -338,18 +366,21 @@ /** * @private */ -InteractionManager.prototype.rebuildInteractiveGraph = function () { +InteractionManager.prototype.rebuildInteractiveGraph = function () +{ this.dirty = false; var len = this.interactiveItems.length; - for (var i = 0; i < len; i++) { + for (var i = 0; i < len; i++) + { this.interactiveItems[i].interactiveChildren = false; } this.interactiveItems.length = 0; - if (this.stage.interactive) { + if (this.stage.interactive) + { this.interactiveItems.push(this.stage); } @@ -363,8 +394,10 @@ * @param event {Event} The DOM event of the mouse moving * @private */ -InteractionManager.prototype.onMouseMove = function (event) { - if (this.dirty) { +InteractionManager.prototype.onMouseMove = function (event) +{ + if (this.dirty) + { this.rebuildInteractiveGraph(); } @@ -378,11 +411,13 @@ var length = this.interactiveItems.length; - for (var i = 0; i < length; i++) { + for (var i = 0; i < length; i++) + { var item = this.interactiveItems[i]; // Call the function! - if (item.mousemove) { + if (item.mousemove) + { item.mousemove(this.mouse); } } @@ -394,14 +429,17 @@ * @param event {Event} The DOM event of a mouse button being pressed down * @private */ -InteractionManager.prototype.onMouseDown = function (event) { - if (this.dirty) { +InteractionManager.prototype.onMouseDown = function (event) +{ + if (this.dirty) + { this.rebuildInteractiveGraph(); } this.mouse.originalEvent = event; - if (AUTO_PREVENT_DEFAULT) { + if (AUTO_PREVENT_DEFAULT) + { this.mouse.originalEvent.preventDefault(); } @@ -420,22 +458,27 @@ // while // hit test - for (var i = 0; i < length; i++) { + for (var i = 0; i < length; i++) + { var item = this.interactiveItems[i]; - if (item[downFunction] || item[clickFunction]) { + if (item[downFunction] || item[clickFunction]) + { item[buttonIsDown] = true; item.__hit = this.hitTest(item, this.mouse); - if (item.__hit) { + if (item.__hit) + { //call the function! - if (item[downFunction]) { + if (item[downFunction]) + { item[downFunction](this.mouse); } item[isDown] = true; // just the one! - if (!item.interactiveChildren) { + if (!item.interactiveChildren) + { break; } } @@ -449,8 +492,10 @@ * @param event {Event} The DOM event of a mouse being moved out * @private */ -InteractionManager.prototype.onMouseOut = function (event) { - if (this.dirty) { +InteractionManager.prototype.onMouseOut = function (event) +{ + if (this.dirty) + { this.rebuildInteractiveGraph(); } @@ -460,11 +505,14 @@ this.interactionDOMElement.style.cursor = 'inherit'; - for (var i = 0; i < length; i++) { + for (var i = 0; i < length; i++) + { var item = this.interactiveItems[i]; - if (item.__isOver) { + if (item.__isOver) + { this.mouse.target = item; - if (item.mouseout) { + if (item.mouseout) + { item.mouseout(this.mouse); } item.__isOver = false; @@ -484,8 +532,10 @@ * @param event {Event} The DOM event of a mouse button being released * @private */ -InteractionManager.prototype.onMouseUp = function (event) { - if (this.dirty) { +InteractionManager.prototype.onMouseUp = function (event) +{ + if (this.dirty) + { this.rebuildInteractiveGraph(); } @@ -502,30 +552,40 @@ var upOutsideFunction = isRightButton ? 'rightupoutside' : 'mouseupoutside'; var isDown = isRightButton ? '__isRightDown' : '__isDown'; - for (var i = 0; i < length; i++) { + for (var i = 0; i < length; i++) + { var item = this.interactiveItems[i]; - if (item[clickFunction] || item[upFunction] || item[upOutsideFunction]) { + if (item[clickFunction] || item[upFunction] || item[upOutsideFunction]) + { item.__hit = this.hitTest(item, this.mouse); - if (item.__hit && !up) { + if (item.__hit && !up) + { //call the function! - if (item[upFunction]) { + if (item[upFunction]) + { item[upFunction](this.mouse); } - if (item[isDown]) { - if (item[clickFunction]) { + if (item[isDown]) + { + if (item[clickFunction]) + { item[clickFunction](this.mouse); } } - if (!item.interactiveChildren) { + if (!item.interactiveChildren) + { up = true; } } - else { - if (item[isDown]) { - if (item[upOutsideFunction]) { + else + { + if (item[isDown]) + { + if (item[upOutsideFunction]) + { item[upOutsideFunction](this.mouse); } } @@ -543,10 +603,12 @@ * @param interactionData {InteractionData} The interactionData object to update in the case there is a hit * @private */ -InteractionManager.prototype.hitTest = function (item, interactionData) { +InteractionManager.prototype.hitTest = function (item, interactionData) +{ var global = interactionData.global; - if (!item.worldVisible) { + if (!item.worldVisible) + { return false; } @@ -560,37 +622,46 @@ interactionData.target = item; //a sprite or display object with a hit area defined - if (item.hitArea && item.hitArea.contains) { + if (item.hitArea && item.hitArea.contains) + { return item.hitArea.contains(x, y); } // a sprite with no hitarea defined - else if (item instanceof core.Sprite) { + else if (item instanceof core.Sprite) + { var width = item.texture.frame.width; var height = item.texture.frame.height; var x1 = -width * item.anchor.x; var y1; - if (x > x1 && x < x1 + width) { + if (x > x1 && x < x1 + width) + { y1 = -height * item.anchor.y; - if (y > y1 && y < y1 + height) { + if (y > y1 && y < y1 + height) + { // set the target property if a hit is true! return true; } } } - else if (item instanceof core.Graphics) { + else if (item instanceof core.Graphics) + { var graphicsData = item.graphicsData; - for (i = 0; i < graphicsData.length; i++) { + for (i = 0; i < graphicsData.length; i++) + { var data = graphicsData[i]; - if (!data.fill) { + if (!data.fill) + { continue; } // only deal with fills.. - if (data.shape) { - if (data.shape.contains(x, y)) { + if (data.shape) + { + if (data.shape.contains(x, y)) + { //interactionData.target = item; return true; } @@ -600,10 +671,12 @@ var length = item.children.length; - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { var tempItem = item.children[i]; var hit = this.hitTest(tempItem, interactionData); - if (hit) { + if (hit) + { // hmm.. TODO SET CORRECT TARGET? interactionData.target = item; return true; @@ -618,8 +691,10 @@ * @param event {Event} The DOM event of a touch moving across the renderer view * @private */ -InteractionManager.prototype.onTouchMove = function (event) { - if (this.dirty) { +InteractionManager.prototype.onTouchMove = function (event) +{ + if (this.dirty) + { this.rebuildInteractiveGraph(); } @@ -628,7 +703,8 @@ var touchData; var i = 0; - for (i = 0; i < changedTouches.length; i++) { + for (i = 0; i < changedTouches.length; i++) + { var touchEvent = changedTouches[i]; touchData = this.touches[touchEvent.identifier]; touchData.originalEvent = event; @@ -636,15 +712,18 @@ // update the touch position touchData.global.x = ( (touchEvent.clientX - rect.left) * (this.interactionDOMElement.width / rect.width) ) / this.resolution; touchData.global.y = ( (touchEvent.clientY - rect.top) * (this.interactionDOMElement.height / rect.height) ) / this.resolution; - if (navigator.isCocoonJS && !rect.left && !rect.top && !event.target.style.width && !event.target.style.height) { + if (navigator.isCocoonJS && !rect.left && !rect.top && !event.target.style.width && !event.target.style.height) + { //Support for CocoonJS fullscreen scale modes touchData.global.x = touchEvent.clientX; touchData.global.y = touchEvent.clientY; } - for (var j = 0; j < this.interactiveItems.length; j++) { + for (var j = 0; j < this.interactiveItems.length; j++) + { var item = this.interactiveItems[j]; - if (item.touchmove && item.__touchData && item.__touchData[touchEvent.identifier]) { + if (item.touchmove && item.__touchData && item.__touchData[touchEvent.identifier]) + { item.touchmove(touchData); } } @@ -657,23 +736,28 @@ * @param event {Event} The DOM event of a touch starting on the renderer view * @private */ -InteractionManager.prototype.onTouchStart = function (event) { - if (this.dirty) { +InteractionManager.prototype.onTouchStart = function (event) +{ + if (this.dirty) + { this.rebuildInteractiveGraph(); } var rect = this.interactionDOMElement.getBoundingClientRect(); - if (AUTO_PREVENT_DEFAULT) { + if (AUTO_PREVENT_DEFAULT) + { event.preventDefault(); } var changedTouches = event.changedTouches; - for (var i=0; i < changedTouches.length; i++) { + for (var i=0; i < changedTouches.length; i++) + { var touchEvent = changedTouches[i]; var touchData = this.pool.pop(); - if (!touchData) { + if (!touchData) + { touchData = new InteractionData(); } @@ -682,7 +766,8 @@ this.touches[touchEvent.identifier] = touchData; touchData.global.x = ( (touchEvent.clientX - rect.left) * (this.interactionDOMElement.width / rect.width) ) / this.resolution; touchData.global.y = ( (touchEvent.clientY - rect.top) * (this.interactionDOMElement.height / rect.height) ) / this.resolution; - if (navigator.isCocoonJS && !rect.left && !rect.top && !event.target.style.width && !event.target.style.height) { + if (navigator.isCocoonJS && !rect.left && !rect.top && !event.target.style.width && !event.target.style.height) + { //Support for CocoonJS fullscreen scale modes touchData.global.x = touchEvent.clientX; touchData.global.y = touchEvent.clientY; @@ -690,15 +775,19 @@ var length = this.interactiveItems.length; - for (var j = 0; j < length; j++) { + for (var j = 0; j < length; j++) + { var item = this.interactiveItems[j]; - if (item.touchstart || item.tap) { + if (item.touchstart || item.tap) + { item.__hit = this.hitTest(item, touchData); - if (item.__hit) { + if (item.__hit) + { //call the function! - if (item.touchstart) { + if (item.touchstart) + { item.touchstart(touchData); } @@ -706,7 +795,8 @@ item.__touchData = item.__touchData || {}; item.__touchData[touchEvent.identifier] = touchData; - if (!item.interactiveChildren) { + if (!item.interactiveChildren) + { break; } } @@ -721,31 +811,37 @@ * @param event {Event} The DOM event of a touch ending on the renderer view * @private */ -InteractionManager.prototype.onTouchEnd = function (event) { - if (this.dirty) { +InteractionManager.prototype.onTouchEnd = function (event) +{ + if (this.dirty) + { this.rebuildInteractiveGraph(); } var rect = this.interactionDOMElement.getBoundingClientRect(); var changedTouches = event.changedTouches; - for (var i=0; i < changedTouches.length; i++) { + for (var i=0; i < changedTouches.length; i++) + { var touchEvent = changedTouches[i]; var touchData = this.touches[touchEvent.identifier]; var up = false; touchData.global.x = ( (touchEvent.clientX - rect.left) * (this.interactionDOMElement.width / rect.width) ) / this.resolution; touchData.global.y = ( (touchEvent.clientY - rect.top) * (this.interactionDOMElement.height / rect.height) ) / this.resolution; - if (navigator.isCocoonJS && !rect.left && !rect.top && !event.target.style.width && !event.target.style.height) { + if (navigator.isCocoonJS && !rect.left && !rect.top && !event.target.style.width && !event.target.style.height) + { //Support for CocoonJS fullscreen scale modes touchData.global.x = touchEvent.clientX; touchData.global.y = touchEvent.clientY; } var length = this.interactiveItems.length; - for (var j = 0; j < length; j++) { + for (var j = 0; j < length; j++) + { var item = this.interactiveItems[j]; - if (item.__touchData && item.__touchData[touchEvent.identifier]) { + if (item.__touchData && item.__touchData[touchEvent.identifier]) + { item.__hit = this.hitTest(item, item.__touchData[touchEvent.identifier]); @@ -753,20 +849,27 @@ touchData.originalEvent = event; // hitTest?? - if (item.touchend || item.tap) { - if (item.__hit && !up) { - if (item.touchend) { + if (item.touchend || item.tap) + { + if (item.__hit && !up) + { + if (item.touchend) + { item.touchend(touchData); } - if (item.__isDown && item.tap) { + if (item.__isDown && item.tap) + { item.tap(touchData); } - if (!item.interactiveChildren) { + if (!item.interactiveChildren) + { up = true; } } - else { - if (item.__isDown && item.touchendoutside) { + else + { + if (item.__isDown && item.touchendoutside) + { item.touchendoutside(touchData); } } diff --git a/src/loaders/AssetLoader.js b/src/loaders/AssetLoader.js index 20da0cf..c4dba1c 100644 --- a/src/loaders/AssetLoader.js +++ b/src/loaders/AssetLoader.js @@ -21,7 +21,8 @@ * data formats include 'xml' and 'fnt'. * @param crossorigin {boolean} Whether requests should be treated as crossorigin */ -function AssetLoader(assetURLs, crossorigin) { +function AssetLoader(assetURLs, crossorigin) +{ /** * The array of asset URLs that are going to be loaded * @@ -76,16 +77,19 @@ * * @param str {string} the name of the asset */ -AssetLoader.prototype._getDataType = function (str) { +AssetLoader.prototype._getDataType = function (str) +{ var test = 'data:'; var start = str.slice(0, test.length).toLowerCase(); - if (start === test) { + if (start === test) + { var data = str.slice(test.length); var sepIdx = data.indexOf(','); // check for malformed data URI scheme - if (sepIdx === -1) { + if (sepIdx === -1) + { return null; } @@ -94,7 +98,8 @@ //We might need to handle some special cases here... //standardize text/plain to 'txt' file extension - if (!info || info.toLowerCase() === 'text/plain') { + if (!info || info.toLowerCase() === 'text/plain') + { return 'txt'; } @@ -109,27 +114,32 @@ * Starts loading the assets sequentially * */ -AssetLoader.prototype.load = function () { +AssetLoader.prototype.load = function () +{ var scope = this; - function onLoad(evt) { + function onLoad(evt) + { scope.onAssetLoaded(evt.data.content); } this.loadCount = this.assetURLs.length; - for (var i=0; i < this.assetURLs.length; i++) { + for (var i=0; i < this.assetURLs.length; i++) + { var fileName = this.assetURLs[i]; //first see if we have a data URI scheme.. var fileType = this._getDataType(fileName); //if not, assume it's a file URI - if (!fileType) { + if (!fileType) + { fileType = fileName.split('?').shift().split('.').pop().toLowerCase(); } var Constructor = this.loadersByType[fileType]; - if (!Constructor) { + if (!Constructor) + { throw new Error(fileType + ' is an unsupported file type'); } @@ -145,18 +155,22 @@ * * @private */ -AssetLoader.prototype.onAssetLoaded = function (loader) { +AssetLoader.prototype.onAssetLoaded = function (loader) +{ this.loadCount--; this.emit('onProgress', { content: this, loader: loader }); - if (this.onProgress) { + if (this.onProgress) + { this.onProgress(loader); } - if (!this.loadCount) { + if (!this.loadCount) + { this.emit('onComplete', { content: this }); - if (this.onComplete) { + if (this.onComplete) + { this.onComplete(); } } diff --git a/src/loaders/AtlasLoader.js b/src/loaders/AtlasLoader.js index 5eda286..3aec9e2 100644 --- a/src/loaders/AtlasLoader.js +++ b/src/loaders/AtlasLoader.js @@ -15,7 +15,8 @@ * @param url {String} The url of the JSON file * @param crossorigin {boolean} Whether requests should be treated as crossorigin */ -function AtlasLoader(url, crossorigin) { +function AtlasLoader(url, crossorigin) +{ this.url = url; this.baseUrl = url.replace(/[^\/]*$/, ''); this.crossorigin = crossorigin; @@ -31,13 +32,15 @@ * Starts loading the JSON file * */ -AtlasLoader.prototype.load = function () { +AtlasLoader.prototype.load = function () +{ this.ajaxRequest = new core.utils.AjaxRequest(); this.ajaxRequest.onreadystatechange = this.onAtlasLoaded.bind(this); this.ajaxRequest.open('GET', this.url, true); - if (this.ajaxRequest.overrideMimeType) { + if (this.ajaxRequest.overrideMimeType) + { this.ajaxRequest.overrideMimeType('application/json'); } @@ -49,9 +52,12 @@ * * @private */ -AtlasLoader.prototype.onAtlasLoaded = function () { - if (this.ajaxRequest.readyState === 4) { - if (this.ajaxRequest.status === 200 || window.location.href.indexOf('http') === -1) { +AtlasLoader.prototype.onAtlasLoaded = function () +{ + if (this.ajaxRequest.readyState === 4) + { + if (this.ajaxRequest.status === 200 || window.location.href.indexOf('http') === -1) + { this.atlas = { meta : { image : [] @@ -70,34 +76,44 @@ selfOnLoaded = this.onLoaded.bind(this); // parser without rotation support yet! - for (i = 0; i < result.length; i++) { + for (i = 0; i < result.length; i++) + { result[i] = result[i].replace(/^\s+|\s+$/g, ''); - if (result[i] === '') { + if (result[i] === '') + { nameInNextLine = i+1; } - if (result[i].length > 0) { - if (nameInNextLine === i) { + if (result[i].length > 0) + { + if (nameInNextLine === i) + { this.atlas.meta.image.push(result[i]); currentImageId = this.atlas.meta.image.length - 1; this.atlas.frames.push({}); lineCount = -3; - } else if (lineCount > 0) { - if (lineCount % 7 === 1) { // frame name - if (currentFrame != null) { //jshint ignore:line + } else if (lineCount > 0) + { + if (lineCount % 7 === 1) + { // frame name + if (currentFrame != null) + { //jshint ignore:line this.atlas.frames[currentImageId][currentFrame.name] = currentFrame; } currentFrame = { name: result[i], frame : {} }; } else { var text = result[i].split(' '); - if (lineCount % 7 === 3) { // position + if (lineCount % 7 === 3) + { // position currentFrame.frame.x = Number(text[1].replace(',', '')); currentFrame.frame.y = Number(text[2]); - } else if (lineCount % 7 === 4) { // size + } else if (lineCount % 7 === 4) + { // size currentFrame.frame.w = Number(text[1].replace(',', '')); currentFrame.frame.h = Number(text[2]); - } else if (lineCount % 7 === 5) { // real size + } else if (lineCount % 7 === 5) + { // real size var realSize = { x : 0, y : 0, @@ -105,7 +121,8 @@ h : Number(text[2]) }; - if (realSize.w > currentFrame.frame.w || realSize.h > currentFrame.frame.h) { + if (realSize.w > currentFrame.frame.w || realSize.h > currentFrame.frame.h) + { currentFrame.trimmed = true; currentFrame.realSize = realSize; } else { @@ -118,28 +135,34 @@ } } - if (currentFrame != null) { //jshint ignore:line + if (currentFrame != null) + { //jshint ignore:line this.atlas.frames[currentImageId][currentFrame.name] = currentFrame; } - if (this.atlas.meta.image.length > 0) { + if (this.atlas.meta.image.length > 0) + { this.images = []; - for (j = 0; j < this.atlas.meta.image.length; j++) { + for (j = 0; j < this.atlas.meta.image.length; j++) + { // sprite sheet var textureUrl = this.baseUrl + this.atlas.meta.image[j]; var frameData = this.atlas.frames[j]; this.images.push(new ImageLoader(textureUrl, this.crossorigin)); - for (i in frameData) { + for (i in frameData) + { var rect = frameData[i].frame; - if (rect) { + if (rect) + { core.utils.TextureCache[i] = new core.Texture(this.images[j].texture.baseTexture, { x: rect.x, y: rect.y, width: rect.w, height: rect.h }); - if (frameData[i].trimmed) { + if (frameData[i].trimmed) + { core.utils.TextureCache[i].realSize = frameData[i].realSize; // trim in pixi not supported yet, todo update trim properties if it is done ... core.utils.TextureCache[i].trim.x = 0; @@ -150,7 +173,8 @@ } this.currentImageId = 0; - for (j = 0; j < this.images.length; j++) { + for (j = 0; j < this.images.length; j++) + { this.images[j].on('loaded', selfOnLoaded); } this.images[this.currentImageId].load(); @@ -170,8 +194,10 @@ * * @private */ -AtlasLoader.prototype.onLoaded = function () { - if (this.images.length - 1 > this.currentImageId) { +AtlasLoader.prototype.onLoaded = function () +{ + if (this.images.length - 1 > this.currentImageId) + { this.currentImageId++; this.images[this.currentImageId].load(); } else { @@ -185,6 +211,7 @@ * * @private */ -AtlasLoader.prototype.onError = function () { +AtlasLoader.prototype.onError = function () +{ this.emit('error', { content: this }); }; diff --git a/src/loaders/BitmapFontLoader.js b/src/loaders/BitmapFontLoader.js index 8641760..13e5c1b 100644 --- a/src/loaders/BitmapFontLoader.js +++ b/src/loaders/BitmapFontLoader.js @@ -13,7 +13,8 @@ * @param url {String} The url of the sprite sheet JSON file * @param crossorigin {boolean} Whether requests should be treated as crossorigin */ -function BitmapFontLoader(url, crossorigin) { +function BitmapFontLoader(url, crossorigin) +{ /** * The url of the bitmap font data * @@ -54,13 +55,15 @@ * Loads the XML font data * */ -BitmapFontLoader.prototype.load = function () { +BitmapFontLoader.prototype.load = function () +{ this.ajaxRequest = new core.utils.AjaxRequest(); this.ajaxRequest.onreadystatechange = this.onXMLLoaded.bind(this); this.ajaxRequest.open('GET', this.url, true); - if (this.ajaxRequest.overrideMimeType) { + if (this.ajaxRequest.overrideMimeType) + { this.ajaxRequest.overrideMimeType('application/xml'); } @@ -72,12 +75,17 @@ * * @private */ -BitmapFontLoader.prototype.onXMLLoaded = function () { - if (this.ajaxRequest.readyState === 4) { - if (this.ajaxRequest.status === 200 || window.location.protocol.indexOf('http') === -1) { +BitmapFontLoader.prototype.onXMLLoaded = function () +{ + if (this.ajaxRequest.readyState === 4) + { + if (this.ajaxRequest.status === 200 || window.location.protocol.indexOf('http') === -1) + { var responseXML = this.ajaxRequest.responseXML; - if (!responseXML || /MSIE 9/i.test(navigator.userAgent) || navigator.isCocoonJS) { - if (typeof(window.DOMParser) === 'function') { + if (!responseXML || /MSIE 9/i.test(navigator.userAgent) || navigator.isCocoonJS) + { + if (typeof(window.DOMParser) === 'function') + { var domparser = new DOMParser(); responseXML = domparser.parseFromString(this.ajaxRequest.responseText, 'text/xml'); } else { @@ -102,7 +110,8 @@ //parse letters var letters = responseXML.getElementsByTagName('char'); - for (var i = 0; i < letters.length; i++) { + for (var i = 0; i < letters.length; i++) + { var charCode = parseInt(letters[i].getAttribute('id'), 10); var textureRect = new core.math.Rectangle( @@ -124,7 +133,8 @@ //parse kernings var kernings = responseXML.getElementsByTagName('kerning'); - for (i = 0; i < kernings.length; i++) { + for (i = 0; i < kernings.length; i++) + { var first = parseInt(kernings[i].getAttribute('first'), 10); var second = parseInt(kernings[i].getAttribute('second'), 10); var amount = parseInt(kernings[i].getAttribute('amount'), 10); @@ -146,6 +156,7 @@ * * @private */ -BitmapFontLoader.prototype.onLoaded = function () { +BitmapFontLoader.prototype.onLoaded = function () +{ this.emit('loaded', { content: this }); }; diff --git a/src/loaders/ImageLoader.js b/src/loaders/ImageLoader.js index e3ff493..16ee7c8 100644 --- a/src/loaders/ImageLoader.js +++ b/src/loaders/ImageLoader.js @@ -11,7 +11,8 @@ * @param url {String} The url of the image * @param crossorigin {boolean} Whether requests should be treated as crossorigin */ -function ImageLoader(url, crossorigin) { +function ImageLoader(url, crossorigin) +{ /** * The texture being loaded * @@ -39,12 +40,15 @@ * Loads image or takes it from cache * */ -ImageLoader.prototype.load = function () { - if (!this.texture.baseTexture.hasLoaded) { +ImageLoader.prototype.load = function () +{ + if (!this.texture.baseTexture.hasLoaded) + { this.texture.baseTexture.on('loaded', this.onLoaded.bind(this)); this.texture.baseTexture.on('error', this.onError.bind(this)); } - else { + else + { this.onLoaded(); } }; @@ -54,7 +58,8 @@ * * @private */ -ImageLoader.prototype.onLoaded = function () { +ImageLoader.prototype.onLoaded = function () +{ this.emit('loaded', { content: this }); }; @@ -64,7 +69,8 @@ * @method onError * @private */ -ImageLoader.prototype.onError = function () { +ImageLoader.prototype.onError = function () +{ this.emit('error', { content: this }); }; @@ -75,15 +81,18 @@ * @param frameHeight {number} height of each frame * @param textureName {String} if given, the frames will be cached in - format */ -ImageLoader.prototype.loadFramedSpriteSheet = function (frameWidth, frameHeight, textureName) { +ImageLoader.prototype.loadFramedSpriteSheet = function (frameWidth, frameHeight, textureName) +{ this.frames = []; var cols = Math.floor(this.texture.width / frameWidth); var rows = Math.floor(this.texture.height / frameHeight); var i=0; - for (var y = 0; y < rows; ++y) { - for (var x = 0; x < cols; ++x, ++i) { + for (var y = 0; y < rows; ++y) + { + for (var x = 0; x < cols; ++x, ++i) + { var texture = new core.Texture( this.texture.baseTexture, new core.math.Rectangle( @@ -96,7 +105,8 @@ this.frames.push(texture); - if (textureName) { + if (textureName) + { core.utils.TextureCache[textureName + '-' + i] = texture; } } diff --git a/src/loaders/JsonLoader.js b/src/loaders/JsonLoader.js index 3279f40..7aabeb4 100644 --- a/src/loaders/JsonLoader.js +++ b/src/loaders/JsonLoader.js @@ -14,7 +14,8 @@ * @param url {String} The url of the JSON file * @param crossorigin {boolean} Whether requests should be treated as crossorigin */ -function JsonLoader(url, crossorigin) { +function JsonLoader(url, crossorigin) +{ /** * The url of the bitmap font data * @@ -56,8 +57,10 @@ * Loads the JSON data * */ -JsonLoader.prototype.load = function () { - if (window.XDomainRequest && this.crossorigin) { +JsonLoader.prototype.load = function () +{ + if (window.XDomainRequest && this.crossorigin) + { this.ajaxRequest = new window.XDomainRequest(); // XDomainRequest has a few quirks. Occasionally it will abort requests @@ -68,15 +71,19 @@ this.ajaxRequest.onerror = this.onError.bind(this); this.ajaxRequest.ontimeout = this.onError.bind(this); - this.ajaxRequest.onprogress = function () {}; + this.ajaxRequest.onprogress = function () + {}; this.ajaxRequest.onload = this.onJSONLoaded.bind(this); } - else { - if (window.XMLHttpRequest) { + else + { + if (window.XMLHttpRequest) + { this.ajaxRequest = new window.XMLHttpRequest(); } - else { + else + { this.ajaxRequest = new window.ActiveXObject('Microsoft.XMLHTTP'); } @@ -93,8 +100,10 @@ * * @private */ -JsonLoader.prototype.onReadyStateChanged = function () { - if (this.ajaxRequest.readyState === 4 && (this.ajaxRequest.status === 200 || window.location.href.indexOf('http') === -1)) { +JsonLoader.prototype.onReadyStateChanged = function () +{ + if (this.ajaxRequest.readyState === 4 && (this.ajaxRequest.status === 200 || window.location.href.indexOf('http') === -1)) + { this.onJSONLoaded(); } }; @@ -104,15 +113,18 @@ * * @private */ -JsonLoader.prototype.onJSONLoaded = function () { - if (!this.ajaxRequest.responseText) { +JsonLoader.prototype.onJSONLoaded = function () +{ + if (!this.ajaxRequest.responseText) + { this.onError(); return; } this.json = JSON.parse(this.ajaxRequest.responseText); - if (this.json.frames) { + if (this.json.frames) + { // sprite sheet var textureUrl = this.baseUrl + this.json.meta.image; var image = new ImageLoader(textureUrl, this.crossorigin); @@ -122,16 +134,19 @@ image.addEventListener('loaded', this.onLoaded.bind(this)); image.addEventListener('error', this.onError.bind(this)); - for (var i in frameData) { + for (var i in frameData) + { var rect = frameData[i].frame; - if (rect) { + if (rect) + { var textureSize = new core.math.Rectangle(rect.x, rect.y, rect.w, rect.h); var crop = textureSize.clone(); var trim = null; // Check to see if the sprite is trimmed - if (frameData[i].trimmed) { + if (frameData[i].trimmed) + { var actualSize = frameData[i].sourceSize; var realSize = frameData[i].spriteSourceSize; trim = new core.math.Rectangle(realSize.x, realSize.y, actualSize.w, actualSize.h); @@ -143,12 +158,15 @@ image.load(); } - else if (this.json.bones) { + else if (this.json.bones) + { // check if the json was loaded before - if (core.utils.AnimCache[this.url]) { + if (core.utils.AnimCache[this.url]) + { this.onLoaded(); } - else { + else + { /** * use a bit of hackery to load the atlas file, here we assume that the .json, .atlas and .png files * that correspond to the spine file are in the same base URL and that the .json and .atlas files @@ -159,9 +177,11 @@ // save a copy of the current object for future reference // var originalLoader = this; // before loading the file, replace the "onJSONLoaded" function for our own // - atlasLoader.onJSONLoaded = function () { + atlasLoader.onJSONLoaded = function () + { // at this point "this" points at the atlasLoader (JsonLoader) instance // - if (!this.ajaxRequest.responseText) { + if (!this.ajaxRequest.responseText) + { this.onError(); // FIXME: hmm, this is funny because we are not responding to errors yet return; } @@ -179,14 +199,18 @@ originalLoader.spineAtlas = spineAtlas; originalLoader.spineAtlasLoader = atlasLoader; // wait for textures to finish loading if needed - if (textureLoader.loadingCount > 0) { - textureLoader.addEventListener('loadedBaseTexture', function (evt){ - if (evt.content.content.loadingCount <= 0) { + if (textureLoader.loadingCount > 0) + { + textureLoader.addEventListener('loadedBaseTexture', function (evt) + { + if (evt.content.content.loadingCount <= 0) + { originalLoader.onLoaded(); } }); } - else { + else + { originalLoader.onLoaded(); } }; @@ -194,7 +218,8 @@ atlasLoader.load(); } } - else { + else + { this.onLoaded(); } }; @@ -204,7 +229,8 @@ * * @private */ -JsonLoader.prototype.onLoaded = function () { +JsonLoader.prototype.onLoaded = function () +{ this.loaded = true; this.dispatchEvent({ type: 'loaded', @@ -217,7 +243,8 @@ * * @private */ -JsonLoader.prototype.onError = function () { +JsonLoader.prototype.onError = function () +{ this.dispatchEvent({ type: 'error', diff --git a/src/loaders/SpineLoader.js b/src/loaders/SpineLoader.js index 51aaddb..69bae21 100644 --- a/src/loaders/SpineLoader.js +++ b/src/loaders/SpineLoader.js @@ -24,7 +24,8 @@ * @param url {String} The url of the JSON file * @param crossorigin {boolean} Whether requests should be treated as crossorigin */ -function SpineLoader(url, crossorigin) { +function SpineLoader(url, crossorigin) +{ /** * The url of the bitmap font data * @@ -57,11 +58,13 @@ * Loads the JSON data * */ -SpineLoader.prototype.load = function () { +SpineLoader.prototype.load = function () +{ var scope = this; var jsonLoader = new JsonLoader(this.url, this.crossorigin); - jsonLoader.on('loaded', function (event) { + jsonLoader.on('loaded', function (event) + { scope.json = event.data.content.json; scope.onLoaded(); }); @@ -74,7 +77,8 @@ * * @private */ -SpineLoader.prototype.onLoaded = function () { +SpineLoader.prototype.onLoaded = function () +{ this.loaded = true; this.emit('loaded', { content: this }); }; diff --git a/src/loaders/SpineTextureLoader.js b/src/loaders/SpineTextureLoader.js index 61c51c0..c09a548 100644 --- a/src/loaders/SpineTextureLoader.js +++ b/src/loaders/SpineTextureLoader.js @@ -9,7 +9,8 @@ * @param basePath {string} Tha base path where to look for the images to be loaded * @param crossorigin {boolean} Whether requests should be treated as crossorigin */ -function SpineTextureLoader(basePath, crossorigin) { +function SpineTextureLoader(basePath, crossorigin) +{ this.basePath = basePath; this.crossorigin = crossorigin; this.loadingCount = 0; @@ -26,12 +27,15 @@ * @param page {spine.AtlasPage} Atlas page to which texture belongs * @param file {string} The file to load, this is just the file path relative to the base path configured in the constructor */ -SpineTextureLoader.prototype.load = function (page, file) { +SpineTextureLoader.prototype.load = function (page, file) +{ page.rendererObject = core.BaseTexture.fromImage(this.basePath + '/' + file, this.crossorigin); - if (!page.rendererObject.hasLoaded) { + if (!page.rendererObject.hasLoaded) + { var scope = this; ++scope.loadingCount; - page.rendererObject.addEventListener('loaded', function (){ + page.rendererObject.addEventListener('loaded', function () + { --scope.loadingCount; scope.dispatchEvent({ type: 'loadedBaseTexture', @@ -46,6 +50,7 @@ * * @param texture {BaseTexture} Texture object to destroy */ -SpineTextureLoader.prototype.unload = function (texture) { +SpineTextureLoader.prototype.unload = function (texture) +{ texture.destroy(true); }; diff --git a/src/loaders/SpriteSheetLoader.js b/src/loaders/SpriteSheetLoader.js index 5ee79df..a554e9d 100644 --- a/src/loaders/SpriteSheetLoader.js +++ b/src/loaders/SpriteSheetLoader.js @@ -16,7 +16,8 @@ * @param url {String} The url of the sprite sheet JSON file * @param crossorigin {boolean} Whether requests should be treated as crossorigin */ -function SpriteSheetLoader(url, crossorigin) { +function SpriteSheetLoader(url, crossorigin) +{ /** * The url of the atlas data @@ -65,11 +66,13 @@ * This will begin loading the JSON file * */ -SpriteSheetLoader.prototype.load = function () { +SpriteSheetLoader.prototype.load = function () +{ var scope = this; var jsonLoader = new JsonLoader(this.url, this.crossorigin); - jsonLoader.on('loaded', function (event) { + jsonLoader.on('loaded', function (event) + { scope.json = event.data.content.json; scope.onLoaded(); }); @@ -82,7 +85,8 @@ * * @private */ -SpriteSheetLoader.prototype.onLoaded = function () { +SpriteSheetLoader.prototype.onLoaded = function () +{ this.emit('loaded', { content: this }); diff --git a/src/core/display/DisplayObject.js b/src/core/display/DisplayObject.js index 66ebc3c..20e778c 100644 --- a/src/core/display/DisplayObject.js +++ b/src/core/display/DisplayObject.js @@ -7,7 +7,8 @@ * @class * @namespace PIXI */ -function DisplayObject() { +function DisplayObject() +{ /** * The coordinate of the object relative to the local coordinates of the parent. * @@ -152,10 +153,12 @@ * @memberof DisplayObject# */ x: { - get: function () { + get: function () + { return this.position.x; }, - set: function (value) { + set: function (value) + { this.position.x = value; } }, @@ -167,10 +170,12 @@ * @memberof DisplayObject# */ y: { - get: function () { + get: function () + { return this.position.y; }, - set: function (value) { + set: function (value) + { this.position.y = value; } }, @@ -183,11 +188,13 @@ * @readonly */ worldVisible: { - get: function () { + get: function () + { var item = this; do { - if (!item.visible) { + if (!item.visible) + { return false; } @@ -207,17 +214,21 @@ * @memberof DisplayObject# */ mask: { - get: function () { + get: function () + { return this._mask; }, - set: function (value) { - if (this._mask) { + set: function (value) + { + if (this._mask) + { this._mask.isMask = false; } this._mask = value; - if (this._mask) { + if (this._mask) + { this._mask.isMask = true; } } @@ -232,18 +243,23 @@ * @memberof DisplayObject# */ filters: { - get: function () { + get: function () + { return this._filters; }, - set: function (value) { - if (value) { + set: function (value) + { + if (value) + { // now put all the passes in one place.. var passes = []; - for (var i = 0; i < value.length; i++) { + for (var i = 0; i < value.length; i++) + { var filterPasses = value[i].passes; - for (var j = 0; j < filterPasses.length; j++) { + for (var j = 0; j < filterPasses.length; j++) + { passes.push(filterPasses[j]); } } @@ -264,8 +280,9 @@ * * @private */ -DisplayObject.prototype.updateTransform = function () { - +DisplayObject.prototype.updateTransform = function () +{ + // create some matrix refs for easy access var pt = this.parent.worldTransform; var wt = this.worldTransform; @@ -274,9 +291,11 @@ var a, b, c, d, tx, ty; // so if rotation is between 0 then we can simplify the multiplication process.. - if (this.rotation % math.PI_2) { + if (this.rotation % math.PI_2) + { // 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) { + if (this.rotation !== this.rotationCache) + { this.rotationCache = this.rotation; this._sr = Math.sin(this.rotation); this._cr = Math.cos(this.rotation); @@ -291,7 +310,8 @@ ty = this.position.y; // check for pivot.. not often used so geared towards that fact! - if (this.pivot.x || this.pivot.y) { + 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; } @@ -304,7 +324,8 @@ wt.tx = tx * pt.a + ty * pt.c + pt.tx; wt.ty = tx * pt.b + ty * pt.d + pt.ty; } - else { + else + { // lets do the fast version as we know there is no rotation.. a = this.scale.x; d = this.scale.y; @@ -333,7 +354,8 @@ * @param matrix {Matrix} * @return {Rectangle} the rectangular bounding area */ -DisplayObject.prototype.getBounds = function (/* matrix */) { +DisplayObject.prototype.getBounds = function (/* matrix */) +{ return math.Rectangle.EMPTY; }; @@ -342,7 +364,8 @@ * * @return {Rectangle} the rectangular bounding area */ -DisplayObject.prototype.getLocalBounds = function () { +DisplayObject.prototype.getLocalBounds = function () +{ return this.getBounds(math.Matrix.IDENTITY); }; @@ -352,7 +375,8 @@ * @param position {Point} The world origin to calculate from * @return {Point} A point object representing the position of this object */ -DisplayObject.prototype.toGlobal = function (position) { +DisplayObject.prototype.toGlobal = function (position) +{ // don't need to u[date the lot this.displayObjectUpdateTransform(); return this.worldTransform.apply(position); @@ -365,8 +389,10 @@ * @param [from] {DisplayObject} The DisplayObject to calculate the global position from * @return {Point} A point object representing the position of this object */ -DisplayObject.prototype.toLocal = function (position, from) { - if (from) { +DisplayObject.prototype.toLocal = function (position, from) +{ + if (from) + { position = from.toGlobal(position); } @@ -381,7 +407,8 @@ * @param renderer {WebGLRenderer} The renderer * @private */ -DisplayObject.prototype.renderWebGL = function (/* renderer */) { +DisplayObject.prototype.renderWebGL = function (/* renderer */) +{ // OVERWRITE; }; @@ -391,6 +418,7 @@ * @param renderer {CanvasRenderer} The renderer * @private */ -DisplayObject.prototype.renderCanvas = function (/* renderer */) { +DisplayObject.prototype.renderCanvas = function (/* renderer */) +{ // OVERWRITE; }; diff --git a/src/core/display/DisplayObjectContainer.js b/src/core/display/DisplayObjectContainer.js index 689f40b..4625ee8 100644 --- a/src/core/display/DisplayObjectContainer.js +++ b/src/core/display/DisplayObjectContainer.js @@ -12,7 +12,8 @@ * @extends DisplayObject * @namespace PIXI */ -function DisplayObjectContainer() { +function DisplayObjectContainer() +{ DisplayObject.call(this); /** @@ -47,17 +48,21 @@ * @memberof DisplayObjectContainer# */ width: { - get: function () { + get: function () + { return this.scale.x * this.getLocalBounds().width; }, - set: function (value) { + set: function (value) + { var width = this.getLocalBounds().width; - if(width !== 0) { + if(width !== 0) + { this.scale.x = value / width; } - else { + else + { this.scale.x = 1; } @@ -73,17 +78,21 @@ * @memberof DisplayObjectContainer# */ height: { - get: function () { + get: function () + { return this.scale.y * this.getLocalBounds().height; }, - set: function (value) { + set: function (value) + { var height = this.getLocalBounds().height; - if (height !== 0) { + if (height !== 0) + { this.scale.y = value / height ; } - else { + else + { this.scale.y = 1; } @@ -100,18 +109,23 @@ * @memberof DisplayObject# */ cacheAsBitmap: { - get: function () { + get: function () + { return this._cacheAsBitmap; }, - set: function (value) { - if (this._cacheAsBitmap === value) { + set: function (value) + { + if (this._cacheAsBitmap === value) + { return; } - if (value) { + if (value) + { this._generateCachedSprite(); } - else { + else + { this._destroyCachedSprite(); } @@ -126,7 +140,8 @@ * @param child {DisplayObject} The DisplayObject to add to the container * @return {DisplayObject} The child that was added. */ -DisplayObjectContainer.prototype.addChild = function (child) { +DisplayObjectContainer.prototype.addChild = function (child) +{ return this.addChildAt(child, this.children.length); }; @@ -137,14 +152,18 @@ * @param index {Number} The index to place the child in * @return {DisplayObject} The child that was added. */ -DisplayObjectContainer.prototype.addChildAt = function (child, index) { +DisplayObjectContainer.prototype.addChildAt = function (child, index) +{ // prevent adding self as child - if (child === this) { + if (child === this) + { return; } - if (index >= 0 && index <= this.children.length) { - if (child.parent) { + if (index >= 0 && index <= this.children.length) + { + if (child.parent) + { child.parent.removeChild(child); } @@ -154,7 +173,8 @@ return child; } - else { + else + { throw new Error(child + 'addChildAt: The index '+ index +' supplied is out of bounds ' + this.children.length); } }; @@ -165,15 +185,18 @@ * @param child {DisplayObject} * @param child2 {DisplayObject} */ -DisplayObjectContainer.prototype.swapChildren = function (child, child2) { - if (child === child2) { +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) { + if (index1 < 0 || index2 < 0) + { throw new Error('swapChildren: Both the supplied DisplayObjects must be a child of the caller.'); } @@ -187,10 +210,12 @@ * @param child {DisplayObject} The DisplayObject instance to identify * @return {Number} The index position of the child display object to identify */ -DisplayObjectContainer.prototype.getChildIndex = function (child) { +DisplayObjectContainer.prototype.getChildIndex = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { throw new Error('The supplied DisplayObject must be a child of the caller'); } @@ -203,8 +228,10 @@ * @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 */ -DisplayObjectContainer.prototype.setChildIndex = function (child, index) { - if (index < 0 || index >= this.children.length) { +DisplayObjectContainer.prototype.setChildIndex = function (child, index) +{ + if (index < 0 || index >= this.children.length) + { throw new Error('The supplied index is out of bounds'); } @@ -220,8 +247,10 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child at the given index, if any. */ -DisplayObjectContainer.prototype.getChildAt = function (index) { - if (index < 0 || index >= this.children.length) { +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'); } @@ -234,10 +263,12 @@ * @param child {DisplayObject} The DisplayObject to remove * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChild = function (child) { +DisplayObjectContainer.prototype.removeChild = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { return; } @@ -250,7 +281,8 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChildAt = function (index) { +DisplayObjectContainer.prototype.removeChildAt = function (index) +{ var child = this.getChildAt(index); child.parent = null; @@ -265,24 +297,29 @@ * @param beginIndex {Number} The beginning position. Default value is 0. * @param endIndex {Number} The ending position. Default value is size of the container. */ -DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) { +DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) +{ var begin = beginIndex || 0; var end = typeof endIndex === 'number' ? endIndex : this.children.length; var range = end - begin; - if (range > 0 && range <= end) { + if (range > 0 && range <= end) + { var removed = this.children.splice(begin, range); - for (var i = 0; i < removed.length; ++i) { + for (var i = 0; i < removed.length; ++i) + { removed[i].parent = null; } return removed; } - else if (range === 0 && this.children.length === 0) { + else if (range === 0 && this.children.length === 0) + { return []; } - else { + else + { throw new RangeError('removeChildren: numeric values are outside the acceptable range.'); } }; @@ -291,7 +328,8 @@ * Generates and updates the cached sprite for this object. * */ -DisplayObjectContainer.prototype.updateCachedSprite = function () { +DisplayObjectContainer.prototype.updateCachedSprite = function () +{ this._generateCachedSprite(); }; @@ -304,7 +342,8 @@ * @param renderer {CanvasRenderer|WebGLRenderer} The renderer used to generate the texture. * @return {Texture} a texture of the graphics object */ -DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) { +DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) +{ var bounds = this.getLocalBounds(); var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0, renderer, scaleMode, resolution); @@ -322,18 +361,22 @@ * * @private */ -DisplayObjectContainer.prototype.updateTransform = function () { - if (!this.visible) { +DisplayObjectContainer.prototype.updateTransform = function () +{ + if (!this.visible) + { return; } this.displayObjectUpdateTransform(); - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { return; } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } }; @@ -346,8 +389,10 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getBounds = function () { - if (this.children.length === 0) { +DisplayObjectContainer.prototype.getBounds = function () +{ + if (this.children.length === 0) + { return math.Rectangle.EMPTY; } @@ -365,10 +410,12 @@ var childVisible = false; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -386,7 +433,8 @@ maxY = maxY > childMaxY ? maxY : childMaxY; } - if (!childVisible) { + if (!childVisible) + { return math.Rectangle.EMPTY; } @@ -407,12 +455,14 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getLocalBounds = function () { +DisplayObjectContainer.prototype.getLocalBounds = function () +{ var matrixCache = this.worldTransform; this.worldTransform = math.Matrix.IDENTITY; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } @@ -428,13 +478,16 @@ * * @param renderer {WebGLRenderer} The renderer */ -DisplayObjectContainer.prototype.renderWebGL = function (renderer) { +DisplayObjectContainer.prototype.renderWebGL = function (renderer) +{ // if the object is not visible or the alpha is 0 then no need to render this element - if (!this.visible || this.alpha <= 0) { + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } @@ -442,14 +495,17 @@ var i, j; // do a quick check to see if this element has a mask or a filter. - if (this._mask || this._filters) { + if (this._mask || this._filters) + { // push filter first as we need to ensure the stencil buffer is correct for any masking - if (this._filters) { + if (this._filters) + { renderer.spriteBatch.flush(); renderer.filterManager.pushFilter(this._filterBlock); } - if (this._mask) { + if (this._mask) + { renderer.spriteBatch.stop(); renderer.maskManager.pushMask(this.mask, renderer); renderer.spriteBatch.start(); @@ -459,36 +515,42 @@ this._renderWebGL(renderer); // now loop through the children and make sure they get rendered - for (i = 0, j = this.children.length; i < j; i++) { + for (i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderWebGL(renderer); } // time to stop the sprite batch as either a mask element or a filter draw will happen next renderer.spriteBatch.stop(); - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(this._mask, renderer); } - if (this._filters) { + if (this._filters) + { renderer.filterManager.popFilter(); } renderer.spriteBatch.start(); } - else { + else + { this._renderWebGL(renderer); // simple render children! - for (i = 0, j = this.children.length; i < j; ++i) { + for (i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderWebGL(renderer); } } }; -DisplayObjectContainer.prototype._renderWebGL = function (renderer) { +DisplayObjectContainer.prototype._renderWebGL = function (renderer) +{ // this is where content itself gets renderd.. @@ -499,25 +561,31 @@ * * @param renderer {CanvasRenderer} The renderer */ -DisplayObjectContainer.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0) { +DisplayObjectContainer.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -528,13 +596,16 @@ * @param renderer {WebGLRenderer|CanvasRenderer} The renderer * @private */ -DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) { +DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) +{ this._cachedSprite.worldAlpha = this.worldAlpha; - if (renderer.gl) { + if (renderer.gl) + { this._cachedSprite.renderWebGL(renderer); } - else { + else + { this._cachedSprite.renderCanvas(renderer); } }; @@ -544,10 +615,12 @@ * * @private */ -DisplayObjectContainer.prototype._generateCachedSprite = function () { +DisplayObjectContainer.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { // TODO - RenderTexture now *requires* a renderer instance, so this is like broken // because `renderer` isn't actually in scope here :P var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0); @@ -555,7 +628,8 @@ this._cachedSprite = new Sprite(renderTexture); this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.texture.resize(bounds.width | 0, bounds.height | 0); } @@ -580,8 +654,10 @@ * * @private */ -DisplayObjectContainer.prototype._destroyCachedSprite = function () { - if (!this._cachedSprite) { +DisplayObjectContainer.prototype._destroyCachedSprite = function () +{ + if (!this._cachedSprite) + { return; } diff --git a/src/core/display/Sprite.js b/src/core/display/Sprite.js index 707da24..5862aef 100644 --- a/src/core/display/Sprite.js +++ b/src/core/display/Sprite.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param texture {Texture} The texture for this sprite */ -function Sprite(texture) { +function Sprite(texture) +{ DisplayObjectContainer.call(this); /** @@ -85,12 +86,14 @@ this.texture = texture || Texture.EMPTY; } -Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) { +Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) +{ DisplayObjectContainer.prototype.destroy.call(this); this.anchor = null; - if (destroyTexture) { + if (destroyTexture) + { this._texture.destroy(destroyBaseTexture); } @@ -111,10 +114,12 @@ * @memberof Sprite# */ width: { - get: function () { + get: function () + { return this.scale.x * this.texture.frame.width; }, - set: function (value) { + set: function (value) + { this.scale.x = value / this.texture.frame.width; this._width = value; } @@ -127,10 +132,12 @@ * @memberof Sprite# */ height: { - get: function () { + get: function () + { return this.scale.y * this.texture.frame.height; }, - set: function (value) { + set: function (value) + { this.scale.y = value / this.texture.frame.height; this._height = value; } @@ -143,23 +150,29 @@ * @memberof Sprite# */ texture: { - get: function () { + get: function () + { return this._texture; }, - set: function (value) { - if (this._texture === value) { + set: function (value) + { + if (this._texture === value) + { return; } this._texture = value; this.cachedTint = 0xFFFFFF; - if (value) { + if (value) + { // wait for the texture to load - if (value.baseTexture.hasLoaded) { + if (value.baseTexture.hasLoaded) + { this._onTextureUpdate(); } - else { + else + { value.once('update', this._onTextureUpdate.bind(this)); } } @@ -172,18 +185,22 @@ * * @private */ -Sprite.prototype._onTextureUpdate = function () { +Sprite.prototype._onTextureUpdate = function () +{ // so if _width is 0 then width was not set.. - if (this._width) { + if (this._width) + { this.scale.x = this._width / this.texture.frame.width; } - if (this._height) { + if (this._height) + { this.scale.y = this._height / this.texture.frame.height; } }; -Sprite.prototype._renderWebGL = function (renderer) { +Sprite.prototype._renderWebGL = function (renderer) +{ // this is where content gets renderd.. // watch this space for a little render state manager.. @@ -197,7 +214,8 @@ * @param matrix {Matrix} the transformation matrix of the sprite * @return {Rectangle} the framing rectangle */ -Sprite.prototype.getBounds = function (matrix) { +Sprite.prototype.getBounds = function (matrix) +{ var width = this.texture.frame.width; var height = this.texture.frame.height; @@ -224,11 +242,13 @@ if(b === 0 && c === 0) { // scale may be negative! - if (a < 0) { + if (a < 0) + { a *= -1; } - if (d < 0) { + if (d < 0) + { d *= -1; } @@ -293,28 +313,34 @@ * * @param renderer {CanvasRenderer} The renderer */ -Sprite.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) { +Sprite.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) + { return; } - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; renderer.context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } // Ignore null sources - if (this.texture.valid) { + if (this.texture.valid) + { var resolution = this.texture.baseTexture.resolution / renderer.resolution; renderer.context.globalAlpha = this.worldAlpha; // If smoothingEnabled is supported and we need to change the smoothing property for this texture - if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) { + if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) + { renderer.scaleMode = this.texture.baseTexture.scaleMode; renderer.context[renderer.smoothProperty] = (renderer.scaleMode === CONST.scaleModes.LINEAR); } @@ -324,7 +350,8 @@ var dy = (this.texture.trim ? this.texture.trim.y : 0) - (this.anchor.y * this.texture.trim.height); // Allow for pixel rounding - if (renderer.roundPixels) { + if (renderer.roundPixels) + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -337,7 +364,8 @@ dx = dx | 0; dy = dy | 0; } - else { + else + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -348,8 +376,10 @@ ); } - if (this.tint !== 0xFFFFFF) { - if (this.cachedTint !== this.tint) { + if (this.tint !== 0xFFFFFF) + { + if (this.cachedTint !== this.tint) + { this.cachedTint = this.tint; // TODO clean up caching - how to clean up the caches? @@ -368,7 +398,8 @@ this.texture.crop.height / resolution ); } - else { + else + { renderer.context.drawImage( this.texture.baseTexture.source, this.texture.crop.x, @@ -383,11 +414,13 @@ } } - for (var i = 0, j = this.children.length; i < j; i++) { + for (var i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -402,10 +435,12 @@ * @param frameId {String} The frame Id of the texture in the cache * @return {Sprite} A new Sprite using a texture from the texture cache matching the frameId */ -Sprite.fromFrame = function (frameId) { +Sprite.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache' + this); } @@ -420,6 +455,7 @@ * @param imageId {String} The image url of the texture * @return {Sprite} A new Sprite using a texture from the texture cache matching the image id */ -Sprite.fromImage = function (imageId, crossorigin, scaleMode) { +Sprite.fromImage = function (imageId, crossorigin, scaleMode) +{ return new Sprite(Texture.fromImage(imageId, crossorigin, scaleMode)); }; diff --git a/src/core/display/SpriteBatch.js b/src/core/display/SpriteBatch.js index 3187777..c196fef 100644 --- a/src/core/display/SpriteBatch.js +++ b/src/core/display/SpriteBatch.js @@ -12,7 +12,8 @@ * ```js * var container = new SpriteBatch(); * - * for(var i = 0; i < 100; ++i) { + * for(var i = 0; i < 100; ++i) + * { * var sprite = new PIXI.Sprite.fromImage("myImage.png"); * container.addChild(sprite); * } @@ -25,7 +26,8 @@ */ //TODO RENAME to PARTICLE CONTAINER? -function SpriteBatch() { +function SpriteBatch() +{ DisplayObjectContainer.call(this); } @@ -38,7 +40,8 @@ * * @private */ -SpriteBatch.prototype.updateTransform = function () { +SpriteBatch.prototype.updateTransform = function () +{ // TODO don't need to! this.displayObjectUpdateTransform(); // PIXI.DisplayObjectContainer.prototype.updateTransform.call( this ); @@ -50,8 +53,10 @@ * @param renderer {WebGLRenderer} The webgl renderer * @private */ -SpriteBatch.prototype.renderWebGL = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderWebGL = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -71,8 +76,10 @@ * @param renderer {CanvasRenderer} The canvas renderer * @private */ -SpriteBatch.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -84,10 +91,12 @@ this.displayObjectUpdateTransform(); - for (var i = 0; i < this.children.length; ++i) { + for (var i = 0; i < this.children.length; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -95,9 +104,11 @@ context.globalAlpha = this.worldAlpha * child.alpha; - if (child.rotation % (Math.PI * 2) === 0) { + if (child.rotation % (Math.PI * 2) === 0) + { // this is the fastest way to optimise! - if rotation is 0 then we can avoid any kind of setTransform call - if (isRotated) { + if (isRotated) + { context.setTransform( transform.a, transform.b, @@ -122,8 +133,10 @@ frame.height * child.scale.y ); } - else { - if (!isRotated) { + else + { + if (!isRotated) + { isRotated = true; } @@ -131,7 +144,8 @@ var childTransform = child.worldTransform; - if (renderer.roundPixels) { + if (renderer.roundPixels) + { context.setTransform( childTransform.a, childTransform.b, @@ -141,7 +155,8 @@ childTransform.ty | 0 ); } - else { + else + { context.setTransform( childTransform.a, childTransform.b, diff --git a/src/core/index.js b/src/core/index.js index 3954b6f..eb4a82b 100644 --- a/src/core/index.js +++ b/src/core/index.js @@ -58,11 +58,13 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRenderer: function (width, height, options, noWebGL) { + autoDetectRenderer: function (width, height, options, noWebGL) + { width = width || 800; height = height || 600; - if (!noWebGL && require('webgl-enabled')()) { + if (!noWebGL && require('webgl-enabled')()) + { return new core.WebGLRenderer(width, height, options); } @@ -87,7 +89,8 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRecommendedRenderer: function (width, height, options) { + autoDetectRecommendedRenderer: function (width, height, options) + { var isAndroid = /Android/i.test(navigator.userAgent); return core.autoDetectRenderer(width, height, options, isAndroid); diff --git a/src/core/math/Matrix.js b/src/core/math/Matrix.js index c2f87e2..2ff4848 100644 --- a/src/core/math/Matrix.js +++ b/src/core/math/Matrix.js @@ -10,7 +10,8 @@ * @class * @namespace PIXI */ -function Matrix() { +function Matrix() +{ /** * @member {number} * @default 1 @@ -63,7 +64,8 @@ * * @param array {number[]} The array that the matrix will be populated from. */ -Matrix.prototype.fromArray = function (array) { +Matrix.prototype.fromArray = function (array) +{ this.a = array[0]; this.b = array[1]; this.c = array[3]; @@ -78,14 +80,17 @@ * @param transpose {boolean} Whether we need to transpose the matrix or not * @return {number[]} the newly created array which contains the matrix */ -Matrix.prototype.toArray = function (transpose) { - if (!this.array) { +Matrix.prototype.toArray = function (transpose) +{ + if (!this.array) + { this.array = new Float32Array(9); } var array = this.array; - if (transpose) { + if (transpose) + { array[0] = this.a; array[1] = this.b; array[2] = 0; @@ -96,7 +101,8 @@ array[7] = this.ty; array[8] = 1; } - else { + else + { array[0] = this.a; array[1] = this.c; array[2] = this.tx; @@ -119,7 +125,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, transformed through this matrix */ -Matrix.prototype.apply = function (pos, newPos) { +Matrix.prototype.apply = function (pos, newPos) +{ newPos = newPos || new Point(); newPos.x = this.a * pos.x + this.c * pos.y + this.tx; @@ -136,7 +143,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, inverse-transformed through this matrix */ -Matrix.prototype.applyInverse = function (pos, newPos) { +Matrix.prototype.applyInverse = function (pos, newPos) +{ newPos = newPos || new Point(); var id = 1 / (this.a * this.d + this.c * -this.b); @@ -154,7 +162,8 @@ * @param {number} y * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.translate = function (x, y) { +Matrix.prototype.translate = function (x, y) +{ this.tx += x; this.ty += y; @@ -168,7 +177,8 @@ * @param {number} y The amount to scale vertically * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.scale = function (x, y) { +Matrix.prototype.scale = function (x, y) +{ this.a *= x; this.d *= y; this.c *= x; @@ -186,7 +196,8 @@ * @param {number} angle - The angle in radians. * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.rotate = function (angle) { +Matrix.prototype.rotate = function (angle) +{ var cos = Math.cos( angle ); var sin = Math.sin( angle ); @@ -210,7 +221,8 @@ * @param {Matrix} matrix * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.append = function (matrix) { +Matrix.prototype.append = function (matrix) +{ var a1 = this.a; var b1 = this.b; var c1 = this.c; @@ -232,7 +244,8 @@ * * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.identity = function () { +Matrix.prototype.identity = function () +{ this.a = 1; this.b = 0; this.c = 0; diff --git a/src/core/math/Point.js b/src/core/math/Point.js index 7565b2d..632f346 100644 --- a/src/core/math/Point.js +++ b/src/core/math/Point.js @@ -7,7 +7,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -function Point(x, y) { +function Point(x, y) +{ /** * @member {number} * @default 0 @@ -29,7 +30,8 @@ * * @return {Point} a copy of the point */ -Point.prototype.clone = function () { +Point.prototype.clone = function () +{ return new Point(this.x, this.y); }; @@ -40,7 +42,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -Point.prototype.set = function (x, y) { +Point.prototype.set = function (x, y) +{ this.x = x || 0; this.y = y || ( (y !== 0) ? this.x : 0 ) ; }; diff --git a/src/core/math/shapes/Circle.js b/src/core/math/shapes/Circle.js index 69cfdc9..4d76efc 100644 --- a/src/core/math/shapes/Circle.js +++ b/src/core/math/shapes/Circle.js @@ -10,7 +10,8 @@ * @param y {number} The Y coordinate of the center of this circle * @param radius {number} The radius of the circle */ -function Circle(x, y, radius) { +function Circle(x, y, radius) +{ /** * @member {number} * @default 0 @@ -46,7 +47,8 @@ * @method clone * @return {Circle} a copy of the Circle */ -Circle.prototype.clone = function () { +Circle.prototype.clone = function () +{ return new Circle(this.x, this.y, this.radius); }; @@ -58,8 +60,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Circle */ -Circle.prototype.contains = function (x, y) { - if (this.radius <= 0) { +Circle.prototype.contains = function (x, y) +{ + if (this.radius <= 0) + { return false; } @@ -79,6 +83,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Circle.prototype.getBounds = function () { +Circle.prototype.getBounds = function () +{ return new Rectangle(this.x - this.radius, this.y - this.radius, this.radius * 2, this.radius * 2); }; diff --git a/src/core/math/shapes/Ellipse.js b/src/core/math/shapes/Ellipse.js index 4f2d066..fefd01a 100644 --- a/src/core/math/shapes/Ellipse.js +++ b/src/core/math/shapes/Ellipse.js @@ -11,7 +11,8 @@ * @param width {number} The half width of this ellipse * @param height {number} The half height of this ellipse */ -function Ellipse(x, y, width, height) { +function Ellipse(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -53,7 +54,8 @@ * @method clone * @return {Ellipse} a copy of the ellipse */ -Ellipse.prototype.clone = function () { +Ellipse.prototype.clone = function () +{ return new Ellipse(this.x, this.y, this.width, this.height); }; @@ -65,8 +67,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coords are within this ellipse */ -Ellipse.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Ellipse.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } @@ -86,6 +90,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Ellipse.prototype.getBounds = function () { +Ellipse.prototype.getBounds = function () +{ return new Rectangle(this.x - this.width, this.y - this.height, this.width, this.height); }; diff --git a/src/core/math/shapes/Polygon.js b/src/core/math/shapes/Polygon.js index ae89148..fea6d37 100644 --- a/src/core/math/shapes/Polygon.js +++ b/src/core/math/shapes/Polygon.js @@ -10,16 +10,20 @@ * arguments passed can be flat x,y values e.g. `new Polygon(x,y, x,y, x,y, ...)` where `x` and `y` are * Numbers. */ -function Polygon(points) { +function Polygon(points) +{ //if points isn't an array, use arguments as the array - if (!(points instanceof Array)) { + if (!(points instanceof Array)) + { points = Array.prototype.slice.call(arguments); } //if this is a flat array of numbers, convert it to points - if (points[0] instanceof Point) { + if (points[0] instanceof Point) + { var p = []; - for (var i = 0, il = points.length; i < il; i++) { + for (var i = 0, il = points.length; i < il; i++) + { p.push(points[i].x, points[i].y); } @@ -51,7 +55,8 @@ * * @return {Polygon} a copy of the polygon */ -Polygon.prototype.clone = function () { +Polygon.prototype.clone = function () +{ return new Polygon(this.points.slice()); }; @@ -62,19 +67,22 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this polygon */ -Polygon.prototype.contains = function (x, y) { +Polygon.prototype.contains = function (x, y) +{ var inside = false; // use some raycasting to test hits // https://github.com/substack/point-in-polygon/blob/master/index.js var length = this.points.length / 2; - for (var i = 0, j = length - 1; i < length; j = i++) { + for (var i = 0, j = length - 1; i < length; j = i++) + { var xi = this.points[i * 2], yi = this.points[i * 2 + 1], xj = this.points[j * 2], yj = this.points[j * 2 + 1], intersect = ((yi > y) !== (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi); - if (intersect) { + if (intersect) + { inside = !inside; } } diff --git a/src/core/math/shapes/Rectangle.js b/src/core/math/shapes/Rectangle.js index 16ac62a..4008b68 100644 --- a/src/core/math/shapes/Rectangle.js +++ b/src/core/math/shapes/Rectangle.js @@ -10,7 +10,8 @@ * @param width {number} The overall width of this rectangle * @param height {number} The overall height of this rectangle */ -function Rectangle(x, y, width, height) { +function Rectangle(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -60,7 +61,8 @@ * * @return {Rectangle} a copy of the rectangle */ -Rectangle.prototype.clone = function () { +Rectangle.prototype.clone = function () +{ return new Rectangle(this.x, this.y, this.width, this.height); }; @@ -71,13 +73,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rectangle */ -Rectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Rectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/math/shapes/RoundedRectangle.js b/src/core/math/shapes/RoundedRectangle.js index 27d286e..7bf6411 100644 --- a/src/core/math/shapes/RoundedRectangle.js +++ b/src/core/math/shapes/RoundedRectangle.js @@ -11,7 +11,8 @@ * @param height {number} The overall height of this rounded rectangle * @param radius {number} Controls the radius of the rounded corners */ -function RoundedRectangle(x, y, width, height, radius) { +function RoundedRectangle(x, y, width, height, radius) +{ /** * @member {number} * @default 0 @@ -58,7 +59,8 @@ * * @return {RoundedRectangle} a copy of the rounded rectangle */ -RoundedRectangle.prototype.clone = function () { +RoundedRectangle.prototype.clone = function () +{ return new RoundedRectangle(this.x, this.y, this.width, this.height, this.radius); }; @@ -69,13 +71,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rounded Rectangle */ -RoundedRectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +RoundedRectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/primitives/Graphics.js b/src/core/primitives/Graphics.js index 261c534..e902d2a 100644 --- a/src/core/primitives/Graphics.js +++ b/src/core/primitives/Graphics.js @@ -16,7 +16,8 @@ * @extends DisplayObjectContainer * @namespace PIXI */ -function Graphics() { +function Graphics() +{ DisplayObjectContainer.call(this); this.renderable = true; @@ -154,16 +155,20 @@ * @private */ cacheAsBitmap: { - get: function () { + get: function () + { return this._cacheAsBitmap; }, - set: function (value) { + set: function (value) + { this._cacheAsBitmap = value; - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._generateCachedSprite(); } - else { + else + { this.destroyCachedSprite(); this.dirty = true; } @@ -176,7 +181,8 @@ * * @return {Graphics} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ var clone = new Graphics(); clone.renderable = this.renderable; @@ -192,7 +198,8 @@ clone.cachedSpriteDirty = this.cachedSpriteDirty; // copy graphics data - for (var i = 0; i < this.graphicsData.length; ++i) { + for (var i = 0; i < this.graphicsData.length; ++i) + { clone.graphicsData.push(this.graphicsData.clone()); } @@ -211,17 +218,21 @@ * @param alpha {number} alpha of the line to draw, will update the objects stored style * @return {Graphics} */ -Graphics.prototype.lineStyle = function (lineWidth, color, alpha) { +Graphics.prototype.lineStyle = function (lineWidth, color, alpha) +{ this.lineWidth = lineWidth || 0; this.lineColor = color || 0; this.lineAlpha = (arguments.length < 3) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length) + { // halfway through a line? start a new one! this.drawShape( new math.Polygon( this.currentPath.shape.points.slice(-2) )); } - else { + else + { // otherwise its empty so lets just set the line properties this.currentPath.lineWidth = this.lineWidth; this.currentPath.lineColor = this.lineColor; @@ -239,7 +250,8 @@ * @param y {number} the Y coordinate to move to * @return {Graphics} */ -Graphics.prototype.moveTo = function (x, y) { +Graphics.prototype.moveTo = function (x, y) +{ this.drawShape(new math.Polygon([x,y])); return this; @@ -253,7 +265,8 @@ * @param y {number} the Y coordinate to draw to * @return {Graphics} */ -Graphics.prototype.lineTo = function (x, y) { +Graphics.prototype.lineTo = function (x, y) +{ this.currentPath.shape.points.push(x, y); this.dirty = true; @@ -270,13 +283,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -285,7 +302,8 @@ n = 20, points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { this.moveTo(0, 0); } @@ -293,7 +311,8 @@ var fromY = points[points.length-1]; var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; xa = fromX + ( (cpX - fromX) * j ); @@ -319,13 +338,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -342,7 +365,8 @@ var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; dt = (1 - j); @@ -373,13 +397,17 @@ * @param radius {number} The radius of the arc * @return {Graphics} */ -Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points.push(x1, y1); } } - else { + else + { this.moveTo(x1, y1); } @@ -392,12 +420,15 @@ b2 = x2 - x1, mm = Math.abs(a1 * b2 - b1 * a2); - if (mm < 1.0e-8 || radius === 0) { - if (points[points.length-2] !== x1 || points[points.length-1] !== y1) { + if (mm < 1.0e-8 || radius === 0) + { + if (points[points.length-2] !== x1 || points[points.length-1] !== y1) + { points.push(x1, y1); } } - else { + else + { var dd = a1 * a1 + b1 * b1, cc = a2 * a2 + b2 * b2, tt = a1 * a2 + b1 * b2, @@ -433,42 +464,51 @@ * @param anticlockwise {boolean} Optional. Specifies whether the drawing should be counterclockwise or clockwise. False is default, and indicates clockwise, while true indicates counter-clockwise. * @return {Graphics} */ -Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) { +Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) +{ var startX = cx + Math.cos(startAngle) * radius; var startY = cy + Math.sin(startAngle) * radius; var points; // TODO - This if-else makes no sense. It uses currentPath in the else where it doesn't exist... - if (this.currentPath) { + if (this.currentPath) + { points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { points.push(startX, startY); } - else if (points[points.length-2] !== startX || points[points.length-1] !== startY) { + else if (points[points.length-2] !== startX || points[points.length-1] !== startY) + { points.push(startX, startY); } } - else { + else + { this.moveTo(startX, startY); points = this.currentPath.shape.points; } - if (startAngle === endAngle) { + if (startAngle === endAngle) + { return this; } - if (!anticlockwise && endAngle <= startAngle) { + if (!anticlockwise && endAngle <= startAngle) + { endAngle += Math.PI * 2; } - else if (anticlockwise && startAngle <= endAngle) { + else if (anticlockwise && startAngle <= endAngle) + { startAngle += Math.PI * 2; } var sweep = anticlockwise ? (startAngle - endAngle) *-1 : (endAngle - startAngle); var segs = (Math.abs(sweep)/ (Math.PI * 2)) * 40; - if (sweep === 0) { + if (sweep === 0) + { return this; } @@ -482,7 +522,8 @@ var remainder = ( segMinus % 1 ) / segMinus; - for (var i = 0; i <= segMinus; ++i) { + for (var i = 0; i <= segMinus; ++i) + { var real = i + remainder * i; var angle = ((theta) + startAngle + (theta2 * real)); @@ -506,13 +547,16 @@ * @param alpha {number} the alpha of the fill * @return {Graphics} */ -Graphics.prototype.beginFill = function (color, alpha) { +Graphics.prototype.beginFill = function (color, alpha) +{ this.filling = true; this.fillColor = color || 0; this.fillAlpha = (alpha === undefined) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length <= 2) + { this.currentPath.fill = this.filling; this.currentPath.fillColor = this.fillColor; this.currentPath.fillAlpha = this.fillAlpha; @@ -526,7 +570,8 @@ * * @return {Graphics} */ -Graphics.prototype.endFill = function () { +Graphics.prototype.endFill = function () +{ this.filling = false; this.fillColor = null; this.fillAlpha = 1; @@ -542,7 +587,8 @@ * @param height {number} The height of the rectangle * @return {Graphics} */ -Graphics.prototype.drawRect = function ( x, y, width, height ) { +Graphics.prototype.drawRect = function ( x, y, width, height ) +{ this.drawShape(new math.Rectangle(x,y, width, height)); return this; @@ -556,7 +602,8 @@ * @param height {number} The height of the rectangle * @param radius {number} Radius of the rectangle corners */ -Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) { +Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) +{ this.drawShape(new math.RoundedRectangle(x, y, width, height, radius)); return this; @@ -570,7 +617,8 @@ * @param radius {number} The radius of the circle * @return {Graphics} */ -Graphics.prototype.drawCircle = function (x, y, radius) { +Graphics.prototype.drawCircle = function (x, y, radius) +{ this.drawShape(new math.Circle(x,y, radius)); return this; @@ -585,7 +633,8 @@ * @param height {number} The half height of the ellipse * @return {Graphics} */ -Graphics.prototype.drawEllipse = function (x, y, width, height) { +Graphics.prototype.drawEllipse = function (x, y, width, height) +{ this.drawShape(new math.Ellipse(x, y, width, height)); return this; @@ -597,8 +646,10 @@ * @param path {Array} The path data used to construct the polygon. * @return {Graphics} */ -Graphics.prototype.drawPolygon = function (path) { - if (!(path instanceof Array)) { +Graphics.prototype.drawPolygon = function (path) +{ + if (!(path instanceof Array)) + { path = Array.prototype.slice.call(arguments); } @@ -612,7 +663,8 @@ * * @return {Graphics} */ -Graphics.prototype.clear = function () { +Graphics.prototype.clear = function () +{ this.lineWidth = 0; this.filling = false; @@ -631,7 +683,8 @@ * @param scaleMode {number} Should be one of the scaleMode consts * @return {Texture} a texture of the graphics object */ -Graphics.prototype.generateTexture = function (resolution, scaleMode) { +Graphics.prototype.generateTexture = function (resolution, scaleMode) +{ resolution = resolution || 1; var bounds = this.getBounds(); @@ -655,17 +708,21 @@ * * @param renderer {WebGLRenderer} */ -Graphics.prototype._renderWebGL = function (renderer) { +Graphics.prototype._renderWebGL = function (renderer) +{ // if the sprite is not visible or the alpha is 0 then no need to render this element - if (this.isMask === true) { + if (this.isMask === true) + { return; } // this code may still be needed so leaving for now.. - // + // /* - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture on the gpu too! @@ -681,17 +738,24 @@ return; } - */ - - // check if the webgl graphic needs to be updated - if (this.glDirty) { - this.dirty = true; - this.glDirty = false; - } + else */ - renderer.setObjectRendererer(renderer.graphicsRenderer); - renderer.graphicsRenderer.render(this); + renderer.spriteBatch.stop(); + renderer.blendModeManager.setBlendMode(this.blendMode); + // check blend mode + renderer.blendModeManager.setBlendMode( this.blendMode ); + + // check if the webgl graphic needs to be updated + if (this.glDirty) + { + this.dirty = true; + this.glDirty = false; + } + + WebGLGraphics.renderGraphics(this, renderer); + + renderer.spriteBatch.start(); }; /** @@ -700,14 +764,18 @@ * @param renderer {CanvasRenderer} * @private */ -Graphics.prototype.renderCanvas = function (renderer) { +Graphics.prototype.renderCanvas = function (renderer) +{ // 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.isMask === true) { + if (!this.visible || this.alpha <= 0 || this.isMask === true) + { return; } - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture @@ -723,16 +791,19 @@ return; } - else { + else + { var context = renderer.context; var transform = this.worldTransform; - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } @@ -748,11 +819,13 @@ CanvasGraphics.renderGraphics(this, context); - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } } @@ -763,13 +836,16 @@ * * @return {Rectangle} the rectangular bounding area */ -Graphics.prototype.getBounds = function (matrix) { +Graphics.prototype.getBounds = function (matrix) +{ // return an empty object if the item is a mask! - if (this.isMask) { + if (this.isMask) + { return math.Rectangle.EMPTY; } - if (this.dirty) { + if (this.dirty) + { this.updateLocalBounds(); this.glDirty = true; @@ -841,23 +917,27 @@ * Update the bounds of the object * */ -Graphics.prototype.updateLocalBounds = function () { +Graphics.prototype.updateLocalBounds = function () +{ var minX = Infinity; var maxX = -Infinity; var minY = Infinity; var maxY = -Infinity; - if (this.graphicsData.length) { + if (this.graphicsData.length) + { var shape, points, x, y, w, h; - for (var i = 0; i < this.graphicsData.length; i++) { + for (var i = 0; i < this.graphicsData.length; i++) + { var data = this.graphicsData[i]; var type = data.type; var lineWidth = data.lineWidth; shape = data.shape; - if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) { + if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) + { x = shape.x - lineWidth/2; y = shape.y - lineWidth/2; w = shape.width + lineWidth; @@ -869,7 +949,8 @@ minY = y < minY ? y : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.CIRC) { + else if (type === CONST.SHAPES.CIRC) + { x = shape.x; y = shape.y; w = shape.radius + lineWidth/2; @@ -881,7 +962,8 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.ELIP) { + else if (type === CONST.SHAPES.ELIP) + { x = shape.x; y = shape.y; w = shape.width + lineWidth/2; @@ -893,11 +975,13 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else { + else + { // POLY points = shape.points; - for (var j = 0; j < points.length; j += 2) { + for (var j = 0; j < points.length; j += 2) + { x = points[j]; y = points[j+1]; @@ -910,7 +994,8 @@ } } } - else { + else + { minX = 0; maxX = 0; minY = 0; @@ -931,10 +1016,12 @@ * * @private */ -Graphics.prototype._generateCachedSprite = function () { +Graphics.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { var canvasBuffer = new CanvasBuffer(bounds.width, bounds.height); var texture = Texture.fromCanvas(canvasBuffer.canvas); @@ -943,7 +1030,8 @@ this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.buffer.resize(bounds.width, bounds.height); } @@ -968,7 +1056,8 @@ * * @private */ -Graphics.prototype.updateCachedSpriteTexture = function () { +Graphics.prototype.updateCachedSpriteTexture = function () +{ var cachedSprite = this._cachedSprite; var texture = cachedSprite.texture; var canvas = cachedSprite.buffer.canvas; @@ -989,7 +1078,8 @@ * Destroys a previous cached sprite. * */ -Graphics.prototype.destroyCachedSprite = function () { +Graphics.prototype.destroyCachedSprite = function () +{ this._cachedSprite.texture.destroy(true); // let the gc collect the unused sprite @@ -1003,10 +1093,13 @@ * @param {Circle|Rectangle|Ellipse|Line|Polygon} shape The Shape object to draw. * @return {GraphicsData} The generated GraphicsData object. */ -Graphics.prototype.drawShape = function (shape) { - if (this.currentPath) { +Graphics.prototype.drawShape = function (shape) +{ + if (this.currentPath) + { // check current path! - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath.shape.points.length <= 2) + { this.graphicsData.pop(); } } @@ -1017,7 +1110,8 @@ this.graphicsData.push(data); - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { data.shape.closed = this.filling; this.currentPath = data; } diff --git a/src/core/primitives/GraphicsData.js b/src/core/primitives/GraphicsData.js index 99decbe..788f6f2 100644 --- a/src/core/primitives/GraphicsData.js +++ b/src/core/primitives/GraphicsData.js @@ -4,7 +4,8 @@ * @class * @namespace PIXI */ -function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) { +function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) +{ this.lineWidth = lineWidth; this.lineColor = lineColor; this.lineAlpha = lineAlpha; @@ -27,7 +28,8 @@ * * @return {GraphicsData} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ return new GraphicsData( this.lineWidth, this.lineColor, diff --git a/src/core/renderers/canvas/CanvasRenderer.js b/src/core/renderers/canvas/CanvasRenderer.js index 15a0978..7aebd44 100644 --- a/src/core/renderers/canvas/CanvasRenderer.js +++ b/src/core/renderers/canvas/CanvasRenderer.js @@ -17,17 +17,22 @@ * @param [options.resolution=1] {number} the resolution of the renderer retina would be 2 * @param [options.clearBeforeRender=true] {boolean} This sets if the CanvasRenderer will clear the canvas or not before the new render pass. */ -function CanvasRenderer(width, height, options) { +function CanvasRenderer(width, height, options) +{ utils.sayHello('Canvas'); - if (options) { - for (var i in CONST.defaultRenderOptions) { - if (typeof options[i] === 'undefined') { + if (options) + { + for (var i in CONST.defaultRenderOptions) + { + if (typeof options[i] === 'undefined') + { options[i] = CONST.defaultRenderOptions[i]; } } } - else { + else + { options = CONST.defaultRenderOptions; } @@ -156,19 +161,24 @@ this.smoothProperty = null; - if (this.context.imageSmoothingEnabled) { + if (this.context.imageSmoothingEnabled) + { this.smoothProperty = 'imageSmoothingEnabled'; } - else if (this.context.webkitImageSmoothingEnabled) { + else if (this.context.webkitImageSmoothingEnabled) + { this.smoothProperty = 'webkitImageSmoothingEnabled'; } - else if (this.context.mozImageSmoothingEnabled) { + else if (this.context.mozImageSmoothingEnabled) + { this.smoothProperty = 'mozImageSmoothingEnabled'; } - else if (this.context.oImageSmoothingEnabled) { + else if (this.context.oImageSmoothingEnabled) + { this.smoothProperty = 'oImageSmoothingEnabled'; } - else if (this.context.msImageSmoothingEnabled) { + else if (this.context.msImageSmoothingEnabled) + { this.smoothProperty = 'msImageSmoothingEnabled'; } @@ -193,10 +203,12 @@ * @memberof CanvasRenderer# */ backgroundColor: { - get: function () { + get: function () + { return this._backgroundColor; }, - set: function (val) { + set: function (val) + { this._backgroundColor = val; this._backgroundColorString = utils.hex2string(val); } @@ -208,7 +220,8 @@ * * @param object {DisplayObject} the object to be rendered */ -CanvasRenderer.prototype.render = function (object) { +CanvasRenderer.prototype.render = function (object) +{ object.updateTransform(); this.context.setTransform(1,0,0,1,0,0); @@ -218,16 +231,20 @@ this.currentBlendMode = CONST.blendModes.NORMAL; this.context.globalCompositeOperation = this.blendModes[CONST.blendModes.NORMAL]; - if (navigator.isCocoonJS && this.view.screencanvas) { + if (navigator.isCocoonJS && this.view.screencanvas) + { this.context.fillStyle = 'black'; this.context.clear(); } - if (this.clearBeforeRender) { - if (this.transparent) { + if (this.clearBeforeRender) + { + if (this.transparent) + { this.context.clearRect(0, 0, this.width, this.height); } - else { + else + { this.context.fillStyle = this._backgroundColorString; this.context.fillRect(0, 0, this.width , this.height); } @@ -241,8 +258,10 @@ * * @param [removeView=false] {boolean} Removes the Canvas element from the DOM. */ -CanvasRenderer.prototype.destroy = function (removeView) { - if (removeView && this.view.parent) { +CanvasRenderer.prototype.destroy = function (removeView) +{ + if (removeView && this.view.parent) + { this.view.parent.removeChild(this.view); } @@ -257,14 +276,16 @@ * @param width {number} the new width of the canvas view * @param height {number} the new height of the canvas view */ -CanvasRenderer.prototype.resize = function (width, height) { +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) { + if (this.autoResize) + { this.view.style.width = this.width / this.resolution + 'px'; this.view.style.height = this.height / this.resolution + 'px'; } @@ -276,7 +297,8 @@ * @param displayObject {DisplayObject} The displayObject to render * @private */ -CanvasRenderer.prototype.renderDisplayObject = function (displayObject) { +CanvasRenderer.prototype.renderDisplayObject = function (displayObject) +{ displayObject.renderCanvas(this); }; @@ -285,11 +307,14 @@ * * @private */ -CanvasRenderer.prototype._mapBlendModes = function () { - if (!this.blendModes) { +CanvasRenderer.prototype._mapBlendModes = function () +{ + if (!this.blendModes) + { this.blendModes = {}; - if (utils.canUseNewCanvasBlendModes()) { + if (utils.canUseNewCanvasBlendModes()) + { this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? this.blendModes[CONST.blendModes.MULTIPLY] = 'multiply'; @@ -308,7 +333,8 @@ this.blendModes[CONST.blendModes.COLOR] = 'color'; this.blendModes[CONST.blendModes.LUMINOSITY] = 'luminosity'; } - else { + else + { // this means that the browser does not support the cool new blend modes in canvas 'cough' ie 'cough' this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? diff --git a/src/core/renderers/canvas/utils/CanvasBuffer.js b/src/core/renderers/canvas/utils/CanvasBuffer.js index ebe5d47..b183a66 100644 --- a/src/core/renderers/canvas/utils/CanvasBuffer.js +++ b/src/core/renderers/canvas/utils/CanvasBuffer.js @@ -6,7 +6,8 @@ * @param width {number} the width for the newly created canvas * @param height {number} the height for the newly created canvas */ -function CanvasBuffer(width, height) { +function CanvasBuffer(width, height) +{ /** * The Canvas object that belongs to this CanvasBuffer. * @@ -36,10 +37,12 @@ * @memberof CanvasBuffer# */ width: { - get: function () { + get: function () + { return this.canvas.width; }, - set: function (val) { + set: function (val) + { this.canvas.width = val; } }, @@ -50,10 +53,12 @@ * @memberof CanvasBuffer# */ height: { - get: function () { + get: function () + { return this.canvas.height; }, - set: function (val) { + set: function (val) + { this.canvas.height = val; } } @@ -64,7 +69,8 @@ * * @private */ -CanvasBuffer.prototype.clear = function () { +CanvasBuffer.prototype.clear = function () +{ this.context.setTransform(1, 0, 0, 1, 0, 0); this.context.clearRect(0,0, this.canvas.width, this.canvas.height); }; @@ -75,7 +81,8 @@ * @param width {number} the new width of the canvas * @param height {number} the new height of the canvas */ -CanvasBuffer.prototype.resize = function (width, height) { +CanvasBuffer.prototype.resize = function (width, height) +{ this.canvas.width = width; this.canvas.height = height; }; diff --git a/src/core/renderers/canvas/utils/CanvasGraphics.js b/src/core/renderers/canvas/utils/CanvasGraphics.js index c7eaa2a..3f2a91f 100644 --- a/src/core/renderers/canvas/utils/CanvasGraphics.js +++ b/src/core/renderers/canvas/utils/CanvasGraphics.js @@ -13,15 +13,18 @@ * @param graphics {Graphics} the actual graphics object to render * @param context {CanvasRenderingContext2D} the 2d drawing method of the canvas */ -CanvasGraphics.renderGraphics = function (graphics, context) { +CanvasGraphics.renderGraphics = function (graphics, context) +{ var worldAlpha = graphics.worldAlpha; - if (graphics.dirty) { + if (graphics.dirty) + { this.updateGraphicsTint(graphics); graphics.dirty = false; } - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; @@ -30,69 +33,82 @@ context.lineWidth = data.lineWidth; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { context.beginPath(); var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } - if (shape.closed) { + if (shape.closed) + { context.lineTo(points[0], points[1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fillRect(shape.x, shape.y, shape.width, shape.height); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.strokeRect(shape.x, shape.y, shape.width, shape.height); } } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.beginPath(); context.arc(shape.x, shape.y, shape.radius,0,2*Math.PI); context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas var w = shape.width * 2; @@ -119,18 +135,21 @@ context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; var width = shape.width; @@ -152,13 +171,15 @@ context.quadraticCurveTo(rx, ry, rx, ry + radius); context.closePath(); - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); @@ -174,45 +195,54 @@ * @param graphics {Graphics} the graphics which will be used as a mask * @param context {CanvasRenderingContext2D} the context 2d method of the canvas */ -CanvasGraphics.renderGraphicsMask = function (graphics, context) { +CanvasGraphics.renderGraphicsMask = function (graphics, context) +{ var len = graphics.graphicsData.length; - if (len === 0) { + if (len === 0) + { return; } context.beginPath(); - for (var i = 0; i < len; i++) { + for (var i = 0; i < len; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { context.rect(shape.x, shape.y, shape.width, shape.height); context.closePath(); } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.arc(shape.x, shape.y, shape.radius, 0, 2 * Math.PI); context.closePath(); } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas @@ -237,7 +267,8 @@ context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); context.closePath(); } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; @@ -262,8 +293,10 @@ } }; -CanvasGraphics.updateGraphicsTint = function (graphics) { - if (graphics.tint === 0xFFFFFF) { +CanvasGraphics.updateGraphicsTint = function (graphics) +{ + if (graphics.tint === 0xFFFFFF) + { return; } @@ -271,7 +304,8 @@ var tintG = (graphics.tint >> 8 & 0xFF) / 255; var tintB = (graphics.tint & 0xFF)/ 255; - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var fillColor = data.fillColor | 0; diff --git a/src/core/renderers/canvas/utils/CanvasMaskManager.js b/src/core/renderers/canvas/utils/CanvasMaskManager.js index e04a733..9827d36 100644 --- a/src/core/renderers/canvas/utils/CanvasMaskManager.js +++ b/src/core/renderers/canvas/utils/CanvasMaskManager.js @@ -6,7 +6,8 @@ * @class * @namespace PIXI */ -function CanvasMaskManager() {} +function CanvasMaskManager() +{} CanvasMaskManager.prototype.constructor = CanvasMaskManager; module.exports = CanvasMaskManager; @@ -17,7 +18,8 @@ * @param maskData {object} the maskData that will be pushed * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.pushMask = function (maskData, renderer) { +CanvasMaskManager.prototype.pushMask = function (maskData, renderer) +{ renderer.context.save(); var cacheAlpha = maskData.alpha; @@ -45,6 +47,7 @@ * * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.popMask = function (renderer) { +CanvasMaskManager.prototype.popMask = function (renderer) +{ renderer.context.restore(); }; diff --git a/src/core/renderers/canvas/utils/CanvasTinter.js b/src/core/renderers/canvas/utils/CanvasTinter.js index 17e0529..d2fb1bc 100644 --- a/src/core/renderers/canvas/utils/CanvasTinter.js +++ b/src/core/renderers/canvas/utils/CanvasTinter.js @@ -14,7 +14,8 @@ * @param color {number} the color to use to tint the sprite with * @return {HTMLCanvasElement} The tinted canvas */ -CanvasTinter.getTintedTexture = function (sprite, color) { +CanvasTinter.getTintedTexture = function (sprite, color) +{ var texture = sprite.texture; color = CanvasTinter.roundColor(color); @@ -23,7 +24,8 @@ texture.tintCache = texture.tintCache || {}; - if (texture.tintCache[stringColor]) { + if (texture.tintCache[stringColor]) + { return texture.tintCache[stringColor]; } @@ -33,14 +35,16 @@ //CanvasTinter.tintWithPerPixel(texture, stringColor, canvas); CanvasTinter.tintMethod(texture, color, canvas); - if (CanvasTinter.convertTintToImage) { + if (CanvasTinter.convertTintToImage) + { // is this better? var tintImage = new Image(); tintImage.src = canvas.toDataURL(); texture.tintCache[stringColor] = tintImage; } - else { + else + { texture.tintCache[stringColor] = canvas; // if we are not converting the texture to an image then we need to lose the reference to the canvas CanvasTinter.canvas = null; @@ -56,7 +60,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithMultiply = function (texture, color, canvas) { +CanvasTinter.tintWithMultiply = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -104,7 +109,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithOverlay = function (texture, color, canvas) { +CanvasTinter.tintWithOverlay = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -139,7 +145,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithPerPixel = function (texture, color, canvas) { +CanvasTinter.tintWithPerPixel = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -167,7 +174,8 @@ var pixels = pixelData.data; - for (var i = 0; i < pixels.length; i += 4) { + for (var i = 0; i < pixels.length; i += 4) + { pixels[i+0] *= r; pixels[i+1] *= g; pixels[i+2] *= b; @@ -181,7 +189,8 @@ * * @param color {number} the color to round, should be a hex color */ -CanvasTinter.roundColor = function (color) { +CanvasTinter.roundColor = function (color) +{ var step = CanvasTinter.cacheStepsPerColorChannel; var rgbValues = utils.hex2rgb(color); diff --git a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js index 9f2f89a..35edbaf 100644 --- a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js +++ b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLBlendModeManager(renderer) { +function WebGLBlendModeManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -23,8 +24,10 @@ * * @param blendMode {number} the blendMode, should be a Pixi const, such as BlendModes.ADD */ -WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) { - if (this.currentBlendMode === blendMode) { +WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) +{ + if (this.currentBlendMode === blendMode) + { return false; } diff --git a/src/core/renderers/webgl/managers/WebGLFilterManager.js b/src/core/renderers/webgl/managers/WebGLFilterManager.js index 1179258..2dac048 100644 --- a/src/core/renderers/webgl/managers/WebGLFilterManager.js +++ b/src/core/renderers/webgl/managers/WebGLFilterManager.js @@ -7,7 +7,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLFilterManager(renderer) { +function WebGLFilterManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -32,7 +33,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.texturePool.length = 0; self.initShaderBuffers(); }); @@ -46,7 +48,8 @@ * @param renderer {WebGLRenderer} * @param buffer {ArrayBuffer} */ -WebGLFilterManager.prototype.begin = function (buffer) { +WebGLFilterManager.prototype.begin = function (buffer) +{ this.defaultShader = this.renderer.shaderManager.defaultShader; this.width = this.renderer.projection.x * 2; @@ -60,7 +63,8 @@ * * @param filterBlock {object} the filter that will be pushed to the current filter stack */ -WebGLFilterManager.prototype.pushFilter = function (filterBlock) { +WebGLFilterManager.prototype.pushFilter = function (filterBlock) +{ var gl = this.renderer.gl; var projection = this.renderer.projection; @@ -78,10 +82,12 @@ this.offsetY += filterBlock._filterArea.y; var texture = this.texturePool.pop(); - if (!texture) { + if (!texture) + { texture = new FilterTexture(this.renderer.gl, this.width, this.height); } - else { + else + { texture.resize(this.width, this.height); } @@ -98,29 +104,35 @@ var localX = filterArea.x, localY = filterArea.y; - if (filterArea.x < 0) { + if (filterArea.x < 0) + { filterArea.width += filterArea.x; filterArea.x = 0; } - if (filterArea.y < 0) { + if (filterArea.y < 0) + { filterArea.height += filterArea.y; filterArea.y = 0; } - if (localX + filterArea.width > this.width) { + if (localX + filterArea.width > this.width) + { filterArea.width = this.width - localX; } - if (localY + filterArea.height > this.height) { + if (localY + filterArea.height > this.height) + { filterArea.height = this.height - localY; } - if (filterArea.width < 0) { + if (filterArea.width < 0) + { filterArea.width = 0; } - if (filterArea.height < 0) { + if (filterArea.height < 0) + { filterArea.height = 0; } @@ -154,7 +166,8 @@ * Removes the last filter from the filter stack and doesn't return it. * */ -WebGLFilterManager.prototype.popFilter = function () { +WebGLFilterManager.prototype.popFilter = function () +{ var gl = this.renderer.gl; var filterBlock = this.filterStack.pop(); @@ -163,7 +176,8 @@ var projection = this.renderer.projection; var offset = this.renderer.offset; - if (filterBlock.filterPasses.length > 1) { + if (filterBlock.filterPasses.length > 1) + { gl.viewport(0, 0, filterArea.width, filterArea.height); gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); @@ -193,7 +207,8 @@ var inputTexture = texture; var outputTexture = this.texturePool.pop(); - if (!outputTexture) { + if (!outputTexture) + { outputTexture = new FilterTexture(this.renderer.gl, this.width, this.height); } outputTexture.resize(this.width, this.height); @@ -204,7 +219,8 @@ gl.disable(gl.BLEND); - for (var i = 0; i < filterBlock.filterPasses.length-1; i++) { + for (var i = 0; i < filterBlock.filterPasses.length-1; i++) + { var filterPass = filterBlock.filterPasses[i]; gl.bindFramebuffer(gl.FRAMEBUFFER, outputTexture.frameBuffer ); @@ -243,10 +259,12 @@ var buffer = this.buffer; // time to render the filters texture to the previous scene - if (this.filterStack.length === 0) { + if (this.filterStack.length === 0) + { gl.colorMask(true, true, true, true);//this.transparent); } - else { + else + { var currentFilter = this.filterStack[this.filterStack.length-1]; filterArea = currentFilter._filterArea; @@ -332,13 +350,15 @@ * @param width {number} the horizontal range of the filter * @param height {number} the vertical range of the filter */ -WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) { +WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) +{ // use program var gl = this.renderer.gl; var shader = filter.shaders[gl.id]; - if (!shader) { + if (!shader) + { shader = new Shader(gl); shader.fragmentSrc = filter.fragmentSrc; @@ -356,7 +376,8 @@ gl.uniform2f(shader.projectionVector, width/2, -height/2); gl.uniform2f(shader.offsetVector, 0,0); - if (filter.uniforms.dimensions) { + 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]; @@ -386,7 +407,8 @@ * Initialises the shader buffers. * */ -WebGLFilterManager.prototype.initShaderBuffers = function () { +WebGLFilterManager.prototype.initShaderBuffers = function () +{ var gl = this.renderer.gl; // create some buffers @@ -432,7 +454,8 @@ * Destroys the filter and removes it from the filter stack. * */ -WebGLFilterManager.prototype.destroy = function () { +WebGLFilterManager.prototype.destroy = function () +{ var gl = this.renderer.gl; this.filterStack = null; @@ -441,7 +464,8 @@ this.offsetY = 0; // destroy textures - for (var i = 0; i < this.texturePool.length; i++) { + for (var i = 0; i < this.texturePool.length; i++) + { this.texturePool[i].destroy(); } diff --git a/src/core/renderers/webgl/managers/WebGLManager.js b/src/core/renderers/webgl/managers/WebGLManager.js index 9d47b5c..c30cd51 100644 --- a/src/core/renderers/webgl/managers/WebGLManager.js +++ b/src/core/renderers/webgl/managers/WebGLManager.js @@ -3,7 +3,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLManager(renderer) { +function WebGLManager(renderer) +{ /** * The renderer this manager works for. * @@ -15,6 +16,7 @@ WebGLManager.prototype.constructor = WebGLManager; module.exports = WebGLManager; -WebGLManager.prototype.destroy = function () { +WebGLManager.prototype.destroy = function () +{ this.renderer = null; }; diff --git a/src/core/renderers/webgl/managers/WebGLMaskManager.js b/src/core/renderers/webgl/managers/WebGLMaskManager.js index 2f90b64..e568812 100644 --- a/src/core/renderers/webgl/managers/WebGLMaskManager.js +++ b/src/core/renderers/webgl/managers/WebGLMaskManager.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLMaskManager(renderer) { +function WebGLMaskManager(renderer) +{ WebGLManager.call(this, renderer); } @@ -19,12 +20,15 @@ * * @param maskData {any[]} */ -WebGLMaskManager.prototype.pushMask = function (maskData) { - if (maskData.dirty) { +WebGLMaskManager.prototype.pushMask = function (maskData) +{ + if (maskData.dirty) + { WebGLGraphics.updateGraphics(maskData, this.renderer.gl); } - if (!maskData._webGL[this.renderer.gl.id].data.length) { + if (!maskData._webGL[this.renderer.gl.id].data.length) + { return; } @@ -36,6 +40,7 @@ * * @param maskData {any[]} */ -WebGLMaskManager.prototype.popMask = function (maskData) { +WebGLMaskManager.prototype.popMask = function (maskData) +{ this.renderer.stencilManager.popStencil(maskData, maskData._webGL[this.renderer.gl.id].data[0], this.renderer); }; diff --git a/src/core/renderers/webgl/managers/WebGLShaderManager.js b/src/core/renderers/webgl/managers/WebGLShaderManager.js index fef071c..90c6477 100644 --- a/src/core/renderers/webgl/managers/WebGLShaderManager.js +++ b/src/core/renderers/webgl/managers/WebGLShaderManager.js @@ -10,7 +10,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLShaderManager(renderer) { +function WebGLShaderManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -28,7 +29,8 @@ */ this.tempAttribState = []; - for (var i = 0; i < this.maxAttibs; i++) { + for (var i = 0; i < this.maxAttibs; i++) + { this.attribState[i] = false; } @@ -66,7 +68,8 @@ // listen for context and update necessary shaders var self = this; - this.renderer.on('context', function (event) { + this.renderer.on('context', function (event) + { var gl = event.data; // this shader is used for rendering primitives @@ -97,29 +100,36 @@ * * @param attribs {Array} attribs */ -WebGLShaderManager.prototype.setAttribs = function (attribs) { +WebGLShaderManager.prototype.setAttribs = function (attribs) +{ // reset temp state var i; - for (i = 0; i < this.tempAttribState.length; i++) { + for (i = 0; i < this.tempAttribState.length; i++) + { this.tempAttribState[i] = false; } // set the new attribs - for (var a in attribs) { + for (var a in attribs) + { this.tempAttribState[attribs[a]] = true; } var gl = this.renderer.gl; - for (i = 0; i < this.attribState.length; i++) { - if (this.attribState[i] !== this.tempAttribState[i]) { + for (i = 0; i < this.attribState.length; i++) + { + if (this.attribState[i] !== this.tempAttribState[i]) + { this.attribState[i] = this.tempAttribState[i]; - if (this.attribState[i]) { + if (this.attribState[i]) + { gl.enableVertexAttribArray(i); } - else { + else + { gl.disableVertexAttribArray(i); } } @@ -131,8 +141,10 @@ * * @param shader {Any} */ -WebGLShaderManager.prototype.setShader = function (shader) { - if (this._currentId === shader.uuid) { +WebGLShaderManager.prototype.setShader = function (shader) +{ + if (this._currentId === shader.uuid) + { return false; } @@ -150,7 +162,8 @@ * Destroys this object. * */ -WebGLShaderManager.prototype.destroy = function () { +WebGLShaderManager.prototype.destroy = function () +{ this.attribState = null; this.tempAttribState = null; diff --git a/src/core/renderers/webgl/managers/WebGLStencilManager.js b/src/core/renderers/webgl/managers/WebGLStencilManager.js index 9ec6398..4cb0134 100644 --- a/src/core/renderers/webgl/managers/WebGLStencilManager.js +++ b/src/core/renderers/webgl/managers/WebGLStencilManager.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLStencilManager(renderer) { +function WebGLStencilManager(renderer) +{ WebGLManager.call(this, renderer); this.stencilStack = []; @@ -24,12 +25,14 @@ * @param graphics {Graphics} * @param webGLData {any[]} */ -WebGLStencilManager.prototype.pushStencil = function (graphics, webGLData) { +WebGLStencilManager.prototype.pushStencil = function (graphics, webGLData) +{ var gl = this.renderer.gl; this.bindGraphics(graphics, webGLData, this.renderer); - if (this.stencilStack.length === 0) { + if (this.stencilStack.length === 0) + { gl.enable(gl.STENCIL_TEST); gl.clear(gl.STENCIL_BUFFER_BIT); this.reverse = true; @@ -47,14 +50,17 @@ // draw the triangle strip! - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } @@ -62,31 +68,38 @@ // draw a quad to increment.. gl.drawElements(gl.TRIANGLE_FAN, 4, gl.UNSIGNED_SHORT, ( webGLData.indices.length - 4 ) * 2 ); - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); } this.reverse = !this.reverse; } - else { - if (!this.reverse) { + else + { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } - else { + 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) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); } } @@ -103,7 +116,8 @@ * @param graphics {Graphics} * @param webGLData {Array} */ -WebGLStencilManager.prototype.bindGraphics = function (graphics, webGLData) { +WebGLStencilManager.prototype.bindGraphics = function (graphics, webGLData) +{ //if (this._currentGraphics === graphics)return; this._currentGraphics = graphics; @@ -114,7 +128,8 @@ offset = this.renderer.offset, shader;// = this.renderer.shaderManager.primitiveShader; - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { shader = this.renderer.shaderManager.complexPrimitiveShader; this.renderer.shaderManager.setShader(shader); @@ -141,7 +156,8 @@ // set the index buffer! gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, webGLData.indexBuffer); } - else { + else + { //this.renderer.shaderManager.activatePrimitiveShader(); shader = this.renderer.shaderManager.primitiveShader; this.renderer.shaderManager.setShader( shader ); @@ -154,7 +170,7 @@ gl.uniform2f(shader.uniforms.offsetVector._location, -offset.x, -offset.y); gl.uniform3fv(shader.uniforms.tint._location, utils.hex2rgb(graphics.tint)); - + gl.uniform1f(shader.uniforms.alpha._location, graphics.worldAlpha); @@ -172,19 +188,22 @@ * @param graphics {Graphics} * @param webGLData {Array} */ -WebGLStencilManager.prototype.popStencil = function (graphics, webGLData) { +WebGLStencilManager.prototype.popStencil = function (graphics, webGLData) +{ var gl = this.renderer.gl; this.stencilStack.pop(); this.count--; - if (this.stencilStack.length === 0) { + if (this.stencilStack.length === 0) + { // the stack is empty! gl.disable(gl.STENCIL_TEST); } - else { + else + { var level = this.count; @@ -192,14 +211,17 @@ gl.colorMask(false, false, false, false); - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { this.reverse = !this.reverse; - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } @@ -213,31 +235,38 @@ // draw the triangle strip! gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); - if (!this.reverse) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); } } - else { + else + { // console.log("<<>>") - if (!this.reverse) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } - else { + 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) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); } } @@ -253,7 +282,8 @@ * Destroys the mask stack. * */ -WebGLStencilManager.prototype.destroy = function () { +WebGLStencilManager.prototype.destroy = function () +{ this.renderer = null; this.stencilStack = null; }; diff --git a/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js b/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js index 913ba5e..1ea7d19 100644 --- a/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js +++ b/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function ComplexPrimitiveShader(gl) { +function ComplexPrimitiveShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -24,7 +25,8 @@ 'uniform float flipY;', 'varying vec4 vColor;', - 'void main(void) {', + '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);', @@ -37,7 +39,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = vColor;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/FastShader.js b/src/core/renderers/webgl/shaders/FastShader.js index bd2e29a..2e5e060 100644 --- a/src/core/renderers/webgl/shaders/FastShader.js +++ b/src/core/renderers/webgl/shaders/FastShader.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function FastShader(gl) { +function FastShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -28,7 +29,8 @@ 'const vec2 center = vec2(-1.0, 1.0);', - 'void main(void) {', + 'void main(void) + {', ' vec2 v;', ' vec2 sv = aVertexPosition * aScale;', ' v.x = (sv.x) * cos(aRotation) - (sv.y) * sin(aRotation);', @@ -49,7 +51,8 @@ 'uniform sampler2D uSampler;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/PrimitiveShader.js b/src/core/renderers/webgl/shaders/PrimitiveShader.js index 6f25409..a25f54f 100644 --- a/src/core/renderers/webgl/shaders/PrimitiveShader.js +++ b/src/core/renderers/webgl/shaders/PrimitiveShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function PrimitiveShader(gl) { +function PrimitiveShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -23,7 +24,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + '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);', @@ -36,7 +38,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = vColor;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/Shader.js b/src/core/renderers/webgl/shaders/Shader.js index f8964f5..fd75ef5 100644 --- a/src/core/renderers/webgl/shaders/Shader.js +++ b/src/core/renderers/webgl/shaders/Shader.js @@ -6,7 +6,8 @@ * @param [fragmentSrc] {string} The source of the fragment shader. * @param [vertexSrc] {string} The source of the vertex shader. */ -function Shader(gl, vertexSrc, fragmentSrc, customUniforms, customAttributes) { +function Shader(gl, vertexSrc, fragmentSrc, customUniforms, customAttributes) +{ /** * @member {number} * @readonly @@ -33,7 +34,8 @@ dimensions: { type: '4f', value: new Float32Array(4) } }; - for (var u in customUniforms) { + for (var u in customUniforms) + { this.uniforms[u] = customUniforms[u]; } @@ -43,7 +45,8 @@ aColor: 0 }; - for (var a in customAttributes) { + for (var a in customAttributes) + { this.attributes[a] = customAttributes[a]; } @@ -66,7 +69,8 @@ 'const vec2 center = vec2(-1.0, 1.0);', - 'void main(void) {', + 'void main(void) + {', ' gl_Position = vec4( ((aVertexPosition + offsetVector) / projectionVector) + center , 0.0, 1.0);', ' vTextureCoord = aTextureCoord;', ' vColor = vec4(aColor.rgb * aColor.a, aColor.a);', @@ -85,7 +89,8 @@ 'uniform sampler2D uSampler;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;', '}' ].join('\n'); @@ -96,7 +101,8 @@ Shader.prototype.constructor = Shader; module.exports = Shader; -Shader.prototype.init = function () { +Shader.prototype.init = function () +{ this.compile(); this.gl.useProgram(this.program); @@ -105,14 +111,18 @@ this.cacheAttributeLocations(Object.keys(this.attributes)); }; -Shader.prototype.cacheUniformLocations = function (keys) { - for (var i = 0; i < keys.length; ++i) { +Shader.prototype.cacheUniformLocations = function (keys) +{ + for (var i = 0; i < keys.length; ++i) + { this.uniforms[keys[i]]._location = this.gl.getUniformLocation(this.program, keys[i]); } }; -Shader.prototype.cacheAttributeLocations = function (keys) { - for (var i = 0; i < keys.length; ++i) { +Shader.prototype.cacheAttributeLocations = function (keys) +{ + for (var i = 0; i < keys.length; ++i) + { this.attributes[keys[i]] = this.gl.getAttribLocation(this.program, keys[i]); } @@ -124,14 +134,16 @@ // 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.attributes.aColor === -1) { + // if (this.attributes.aColor === -1) + { // this.attributes.aColor = 2; // } // End worst hack eva // }; -Shader.prototype.compile = function () { +Shader.prototype.compile = function () +{ var gl = this.gl; var glVertShader = this._glCompile(gl.VERTEX_SHADER, this.vertexSrc); @@ -144,13 +156,15 @@ gl.linkProgram(program); // if linking fails, then log and cleanup - if (!gl.getProgramParameter(program, gl.LINK_STATUS)) { + if (!gl.getProgramParameter(program, gl.LINK_STATUS)) + { window.console.error('Pixi.js Error: Could not initialize shader.'); window.console.error('gl.VALIDATE_STATUS', gl.getProgramParameter(program, gl.VALIDATE_STATUS)); window.console.error('gl.getError()', gl.getError()); // if there is a program info log, log it - if (gl.getProgramInfoLog(program) !== '') { + if (gl.getProgramInfoLog(program) !== '') + { window.console.warn('Pixi.js Warning: gl.getProgramInfoLog()', gl.getProgramInfoLog(program)); } @@ -165,18 +179,21 @@ return (this.program = program); }; -Shader.prototype.syncUniforms = function () { +Shader.prototype.syncUniforms = function () +{ var gl = this.gl; this.textureCount = 1; - for (var key in this.uniforms) { + for (var key in this.uniforms) + { var uniform = this.uniforms[key], location = uniform._location, value = uniform.value, i, il; - switch (uniform.type) { + switch (uniform.type) + { // single int value case 'i': case '1i': @@ -282,7 +299,8 @@ // a Color Value case 'c': - if (typeof value === 'number') { + if (typeof value === 'number') + { value = utils.hex2rgb(value); } @@ -311,11 +329,13 @@ // array of 2D Point objects case 'v2v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(2 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 2] = value[i].x; uniform._array[i * 2 + 1] = value[i].y; } @@ -325,11 +345,13 @@ // array of 3D Point objects case 'v3v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(3 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 3] = value[i].x; uniform._array[i * 3 + 1] = value[i].y; uniform._array[i * 3 + 2] = value[i].z; @@ -341,11 +363,13 @@ // array of 4D Point objects case 'v4v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(4 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 4] = value[i].x; uniform._array[i * 4 + 1] = value[i].y; uniform._array[i * 4 + 2] = value[i].z; @@ -359,7 +383,8 @@ // PIXI.Texture case 't': case 'sampler2D': - if (!uniform.value || !uniform.value.baseTexture || !uniform.value.baseTexture.hasLoaded) { + if (!uniform.value || !uniform.value.baseTexture || !uniform.value.baseTexture.hasLoaded) + { break; } @@ -376,7 +401,8 @@ this.textureCount++; // initialize the texture if we haven't yet - if (!uniform._init) { + if (!uniform._init) + { this.initSampler2D(uniform); uniform._init = true; @@ -394,11 +420,13 @@ * Initialises a Sampler2D uniform (which may only be available later on after initUniforms once the texture has loaded) * */ -Shader.prototype.initSampler2D = function (uniform) { +Shader.prototype.initSampler2D = function (uniform) +{ var gl = this.gl; // Extended texture data - if (uniform.textureData) { + if (uniform.textureData) + { var data = uniform.textureData; // GLTexture = mag linear, min linear_mipmap_linear, wrap repeat + gl.generateMipmap(gl.TEXTURE_2D); @@ -417,14 +445,16 @@ var wrapT = (data.wrapT) ? data.wrapT : gl.CLAMP_TO_EDGE; var format = (data.luminance) ? gl.LUMINANCE : gl.RGBA; - if (data.repeat) { + if (data.repeat) + { wrapS = gl.REPEAT; wrapT = gl.REPEAT; } gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, !!data.flipY); - if (data.width) { + if (data.width) + { var width = (data.width) ? data.width : 512; var height = (data.height) ? data.height : 2; var border = (data.border) ? data.border : 0; @@ -432,7 +462,8 @@ // 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 { + 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); } @@ -448,7 +479,8 @@ * Destroys the shader. * */ -Shader.prototype.destroy = function () { +Shader.prototype.destroy = function () +{ this.gl.deleteProgram(this.program); this.gl = null; @@ -459,13 +491,15 @@ this.fragmentSrc = null; }; -Shader.prototype._glCompile = function (type, src) { +Shader.prototype._glCompile = function (type, src) +{ var shader = this.gl.createShader(type); this.gl.shaderSource(shader, src); this.gl.compileShader(shader); - if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) { + if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) + { window.console.log(this.gl.getShaderInfoLog(shader)); return null; } diff --git a/src/core/renderers/webgl/shaders/StripShader.js b/src/core/renderers/webgl/shaders/StripShader.js index 193f6e1..a7abcc6 100644 --- a/src/core/renderers/webgl/shaders/StripShader.js +++ b/src/core/renderers/webgl/shaders/StripShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function StripShader(gl) { +function StripShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -20,7 +21,8 @@ 'varying vec2 vTextureCoord;', - 'void main(void) {', + '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);', @@ -36,7 +38,8 @@ 'varying vec2 vTextureCoord;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vec2(vTextureCoord.x, vTextureCoord.y)) * alpha;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/utils/FilterTexture.js b/src/core/renderers/webgl/utils/FilterTexture.js index d2c8423..4433d44 100644 --- a/src/core/renderers/webgl/utils/FilterTexture.js +++ b/src/core/renderers/webgl/utils/FilterTexture.js @@ -8,7 +8,8 @@ * @param height {number} the vertical range of the filter * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values */ -function FilterTexture(gl, width, height, scaleMode) { +function FilterTexture(gl, width, height, scaleMode) +{ /** * @member {WebGLContext} */ @@ -59,7 +60,8 @@ * Clears the filter texture. * */ -FilterTexture.prototype.clear = function () { +FilterTexture.prototype.clear = function () +{ var gl = this.gl; gl.clearColor(0,0,0, 0); @@ -72,8 +74,10 @@ * @param width {number} the new width of the texture * @param height {number} the new height of the texture */ -FilterTexture.prototype.resize = function (width, height) { - if (this.width === width && this.height === height) { +FilterTexture.prototype.resize = function (width, height) +{ + if (this.width === width && this.height === height) + { return; } @@ -96,7 +100,8 @@ * Destroys the filter texture. * */ -FilterTexture.prototype.destroy = function () { +FilterTexture.prototype.destroy = function () +{ var gl = this.gl; gl.deleteFramebuffer( this.frameBuffer ); gl.deleteTexture( this.texture ); diff --git a/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js b/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js index c4721e9..a63f4d7 100644 --- a/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js +++ b/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js @@ -14,7 +14,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this sprite batch works for. */ -function WebGLFastSpriteBatch(renderer) { +function WebGLFastSpriteBatch(renderer) +{ /** * The renderer instance this sprite batch operates on. * @@ -91,7 +92,8 @@ */ this.lastIndexCount = 0; - for (var i=0, j=0; i < numIndices; i += 6, j += 4) { + 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; @@ -144,7 +146,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.setupContext(); }); } @@ -157,7 +160,8 @@ * * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLFastSpriteBatch.prototype.setupContext = function () { +WebGLFastSpriteBatch.prototype.setupContext = function () +{ var gl = this.renderer.gl; // create a couple of buffers @@ -177,7 +181,8 @@ /** * @param spriteBatch {SpriteBatch} The SpriteBatch container to prepare for. */ -WebGLFastSpriteBatch.prototype.begin = function (spriteBatch) { +WebGLFastSpriteBatch.prototype.begin = function (spriteBatch) +{ this.shader = this.renderer.shaderManager.fastShader; this.matrix = spriteBatch.worldTransform.toArray(true); @@ -187,33 +192,38 @@ /** */ -WebGLFastSpriteBatch.prototype.end = function () { +WebGLFastSpriteBatch.prototype.end = function () +{ this.flush(); }; /** * @param spriteBatch {SpriteBatch} The SpriteBatch container to render. */ -WebGLFastSpriteBatch.prototype.render = function (spriteBatch) { +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) { + if (!sprite.texture._uvs) + { return; } this.currentBaseTexture = sprite.texture.baseTexture; // check blend mode - if (sprite.blendMode !== this.renderer.blendModeManager.currentBlendMode) { + if (sprite.blendMode !== this.renderer.blendModeManager.currentBlendMode) + { this.flush(); this.renderer.blendModeManager.setBlendMode(sprite.blendMode); } - for (var i=0,j= children.length; i= this.size) { + if (this.currentBatchSize >= this.size) + { this.flush(); } }; @@ -362,29 +379,35 @@ /** * */ -WebGLFastSpriteBatch.prototype.flush = function () { +WebGLFastSpriteBatch.prototype.flush = function () +{ // If the batch is length 0 then return as there is nothing to draw - if (this.currentBatchSize === 0) { + if (this.currentBatchSize === 0) + { return; } var gl = this.renderer.gl; // bind the current texture - if (!this.currentBaseTexture._glTextures[gl.id]) { + if (!this.currentBaseTexture._glTextures[gl.id]) + { this.renderer.updateTexture(this.currentBaseTexture, gl); } //TODO-SHOUD THIS BE ELSE??!?!?! - else { + else + { gl.bindTexture(gl.TEXTURE_2D, this.currentBaseTexture._glTextures[gl.id]); } // upload the verts to the buffer - if (this.currentBatchSize > ( this.size * 0.5 ) ) { + if (this.currentBatchSize > ( this.size * 0.5 ) ) + { gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); } - else { + else + { var view = this.vertices.subarray(0, this.currentBatchSize * this.vertByteSize); gl.bufferSubData(gl.ARRAY_BUFFER, 0, view); @@ -405,14 +428,16 @@ * Ends the batch and flushes * */ -WebGLFastSpriteBatch.prototype.stop = function () { +WebGLFastSpriteBatch.prototype.stop = function () +{ this.flush(); }; /** * */ -WebGLFastSpriteBatch.prototype.start = function () { +WebGLFastSpriteBatch.prototype.start = function () +{ var gl = this.renderer.gl; // bind the main texture diff --git a/src/core/renderers/webgl/utils/WebGLGraphics.js b/src/core/renderers/webgl/utils/WebGLGraphics.js index 55f4911..ab8f46e 100644 --- a/src/core/renderers/webgl/utils/WebGLGraphics.js +++ b/src/core/renderers/webgl/utils/WebGLGraphics.js @@ -19,7 +19,8 @@ * @param graphics {Graphics} * @param renderer {WebGLRenderer} */ -WebGLGraphics.renderGraphics = function (graphics, renderer) {//projection, offset) { +WebGLGraphics.renderGraphics = function (graphics, renderer) {//projection, offset) +{ var gl = renderer.gl; var projection = renderer.projection, @@ -27,7 +28,8 @@ shader = renderer.shaderManager.primitiveShader, webGLData; - if (graphics.dirty) { + if (graphics.dirty) + { WebGLGraphics.updateGraphics(graphics, gl); } @@ -35,8 +37,10 @@ // This could be speeded up for sure! - for (var i = 0; i < webGL.data.length; i++) { - if (webGL.data[i].mode === 1) { + for (var i = 0; i < webGL.data.length; i++) + { + if (webGL.data[i].mode === 1) + { webGLData = webGL.data[i]; renderer.stencilManager.pushStencil(graphics, webGLData, renderer); @@ -46,7 +50,8 @@ renderer.stencilManager.popStencil(graphics, webGLData, renderer); } - else { + else + { webGLData = webGL.data[i]; @@ -84,12 +89,14 @@ * @param graphicsData {Graphics} The graphics object to update * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLGraphics.updateGraphics = function (graphics, gl) { +WebGLGraphics.updateGraphics = function (graphics, gl) +{ // get the contexts graphics object var webGL = graphics._webGL[gl.id]; // if the graphics object does not exist in the webGL context time to create it! - if (!webGL) { + if (!webGL) + { webGL = graphics._webGL[gl.id] = {lastIndex:0, data:[], gl:gl}; } @@ -99,11 +106,13 @@ var i; // if the user cleared the graphics object we will need to clear every object - if (graphics.clearDirty) { + if (graphics.clearDirty) + { graphics.clearDirty = false; // lop through and return all the webGLDatas to the object pool so than can be reused later on - for (i = 0; i < webGL.data.length; i++) { + for (i = 0; i < webGL.data.length; i++) + { var graphicsData = webGL.data[i]; graphicsData.reset(); WebGLGraphics.graphicsDataPool.push( graphicsData ); @@ -119,58 +128,72 @@ // loop through the graphics datas and construct each one.. // if the object is a complex fill then the new stencil buffer technique will be used // other wise graphics objects will be pushed into a batch.. - for (i = webGL.lastIndex; i < graphics.graphicsData.length; i++) { + for (i = webGL.lastIndex; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { // need to add the points the the graphics object.. data.points = data.shape.points.slice(); - if (data.shape.closed) { + if (data.shape.closed) + { // close the poly if the value is true! - if (data.points[0] !== data.points[data.points.length-2] || data.points[1] !== data.points[data.points.length-1]) { + if (data.points[0] !== data.points[data.points.length-2] || data.points[1] !== data.points[data.points.length-1]) + { data.points.push(data.points[0], data.points[1]); } } // MAKE SURE WE HAVE THE CORRECT TYPE.. - if (data.fill) { - if (data.points.length >= 6) { - if (data.points.length < 6 * 2) { + if (data.fill) + { + if (data.points.length >= 6) + { + if (data.points.length < 6 * 2) + { webGLData = WebGLGraphics.switchMode(webGL, 0); var canDrawUsingSimple = WebGLGraphics.buildPoly(data, webGLData); // console.log(canDrawUsingSimple); - if (!canDrawUsingSimple) { + if (!canDrawUsingSimple) + { // console.log("<>>>") webGLData = WebGLGraphics.switchMode(webGL, 1); WebGLGraphics.buildComplexPoly(data, webGLData); } } - else { + else + { webGLData = WebGLGraphics.switchMode(webGL, 1); WebGLGraphics.buildComplexPoly(data, webGLData); } } } - if (data.lineWidth > 0) { + if (data.lineWidth > 0) + { webGLData = WebGLGraphics.switchMode(webGL, 0); WebGLGraphics.buildLine(data, webGLData); } } - else { + else + { webGLData = WebGLGraphics.switchMode(webGL, 0); - if (data.type === CONST.SHAPES.RECT) { + if (data.type === CONST.SHAPES.RECT) + { WebGLGraphics.buildRectangle(data, webGLData); } - else if (data.type === CONST.SHAPES.CIRC || data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.CIRC || data.type === CONST.SHAPES.ELIP) + { WebGLGraphics.buildCircle(data, webGLData); } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { WebGLGraphics.buildRoundedRectangle(data, webGLData); } } @@ -179,10 +202,12 @@ } // upload all the dirty data... - for (i = 0; i < webGL.data.length; i++) { + for (i = 0; i < webGL.data.length; i++) + { webGLData = webGL.data[i]; - if (webGLData.dirty) { + if (webGLData.dirty) + { webGLData.upload(); } } @@ -194,18 +219,22 @@ * @param webGL {WebGLContext} * @param type {number} */ -WebGLGraphics.switchMode = function (webGL, type) { +WebGLGraphics.switchMode = function (webGL, type) +{ var webGLData; - if (!webGL.data.length) { + if (!webGL.data.length) + { webGLData = WebGLGraphics.graphicsDataPool.pop() || new WebGLGraphicsData(webGL.gl); webGLData.mode = type; webGL.data.push(webGLData); } - else { + else + { webGLData = webGL.data[webGL.data.length-1]; - if (webGLData.mode !== type || type === 1) { + if (webGLData.mode !== type || type === 1) + { webGLData = WebGLGraphics.graphicsDataPool.pop() || new WebGLGraphicsData(webGL.gl); webGLData.mode = type; webGL.data.push(webGLData); @@ -225,7 +254,8 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildRectangle = function (graphicsData, webGLData) { +WebGLGraphics.buildRectangle = function (graphicsData, webGLData) +{ // --- // // need to convert points to a nice regular data // @@ -235,7 +265,8 @@ var width = rectData.width; var height = rectData.height; - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -265,7 +296,8 @@ indices.push(vertPos, vertPos, vertPos+1, vertPos+2, vertPos+3, vertPos+3); } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = [x, y, @@ -289,7 +321,8 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildRoundedRectangle = function (graphicsData, webGLData) { +WebGLGraphics.buildRoundedRectangle = function (graphicsData, webGLData) +{ var rrectData = graphicsData.shape; var x = rrectData.x; var y = rrectData.y; @@ -305,7 +338,8 @@ recPoints = recPoints.concat(WebGLGraphics.quadraticBezierCurve(x + width, y + radius, x + width, y, x + width - radius, y)); recPoints = recPoints.concat(WebGLGraphics.quadraticBezierCurve(x + radius, y, x, y, x, y + radius)); - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -323,7 +357,8 @@ // var i = 0; - for (i = 0; i < triangles.length; i+=3) { + for (i = 0; i < triangles.length; i+=3) + { indices.push(triangles[i] + vecPos); indices.push(triangles[i] + vecPos); indices.push(triangles[i+1] + vecPos); @@ -332,12 +367,14 @@ } - for (i = 0; i < recPoints.length; i++) { + for (i = 0; i < recPoints.length; i++) + { verts.push(recPoints[i], recPoints[++i], r, g, b, alpha); } } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = recPoints; @@ -362,7 +399,8 @@ * @param toY {number} Destination point y * @return {number[]} */ -WebGLGraphics.quadraticBezierCurve = function (fromX, fromY, cpX, cpY, toX, toY) { +WebGLGraphics.quadraticBezierCurve = function (fromX, fromY, cpX, cpY, toX, toY) +{ var xa, ya, @@ -373,14 +411,16 @@ n = 20, points = []; - function getPt(n1 , n2, perc) { + function getPt(n1 , n2, perc) + { var diff = n2 - n1; return n1 + ( diff * perc ); } var j = 0; - for (var i = 0; i <= n; i++ ) { + for (var i = 0; i <= n; i++ ) + { j = i / n; // The Green Line @@ -406,7 +446,8 @@ * @param graphicsData {Graphics} The graphics object to draw * @param webGLData {object} */ -WebGLGraphics.buildCircle = function (graphicsData, webGLData) { +WebGLGraphics.buildCircle = function (graphicsData, webGLData) +{ // need to convert points to a nice regular data var circleData = graphicsData.shape; var x = circleData.x; @@ -415,11 +456,13 @@ var height; // TODO - bit hacky?? - if (graphicsData.type === CONST.SHAPES.CIRC) { + if (graphicsData.type === CONST.SHAPES.CIRC) + { width = circleData.radius; height = circleData.radius; } - else { + else + { width = circleData.width; height = circleData.height; } @@ -429,7 +472,8 @@ var i = 0; - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -444,7 +488,8 @@ indices.push(vecPos); - for (i = 0; i < totalSegs + 1 ; i++) { + for (i = 0; i < totalSegs + 1 ; i++) + { verts.push(x,y, r, g, b, alpha); verts.push(x + Math.sin(seg * i) * width, @@ -457,12 +502,14 @@ indices.push(vecPos-1); } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = []; - for (i = 0; i < totalSegs + 1; i++) { + for (i = 0; i < totalSegs + 1; i++) + { graphicsData.points.push(x + Math.sin(seg * i) * width, y + Math.cos(seg * i) * height); } @@ -481,18 +528,22 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildLine = function (graphicsData, webGLData) { +WebGLGraphics.buildLine = function (graphicsData, webGLData) +{ // TODO OPTIMISE! var i = 0; var points = graphicsData.points; - if (points.length === 0) { + if (points.length === 0) + { return; } // if the line width is an odd number add 0.5 to align to a whole pixel - if (graphicsData.lineWidth%2) { - for (i = 0; i < points.length; i++) { + if (graphicsData.lineWidth%2) + { + for (i = 0; i < points.length; i++) + { points[i] += 0.5; } } @@ -502,7 +553,8 @@ var lastPoint = new math.Point(points[points.length - 2], points[points.length - 1]); // if the first point is the last point - gonna have issues :) - if (firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) { + if (firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) + { // need to clone as we are going to slightly modify the shape.. points = points.slice(); @@ -562,7 +614,8 @@ verts.push(p1x + perpx , p1y + perpy, r, g, b, alpha); - for (i = 1; i < length-1; i++) { + for (i = 1; i < length-1; i++) + { p1x = points[(i-1)*2]; p1y = points[(i-1)*2 + 1]; @@ -599,7 +652,8 @@ denom = a1*b2 - a2*b1; - if (Math.abs(denom) < 0.1 ) { + if (Math.abs(denom) < 0.1 ) + { denom+=10.1; verts.push(p2x - perpx , p2y - perpy, @@ -618,7 +672,8 @@ pdist = (px -p2x) * (px -p2x) + (py -p2y) + (py -p2y); - if (pdist > 140 * 140) { + if (pdist > 140 * 140) + { perp3x = perpx - perp2x; perp3y = perpy - perp2y; @@ -639,7 +694,8 @@ indexCount++; } - else { + else + { verts.push(px , py); verts.push(r, g, b, alpha); @@ -672,7 +728,8 @@ indices.push(indexStart); - for (i = 0; i < indexCount; i++) { + for (i = 0; i < indexCount; i++) + { indices.push(indexStart++); } @@ -687,11 +744,13 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildComplexPoly = function (graphicsData, webGLData) { +WebGLGraphics.buildComplexPoly = function (graphicsData, webGLData) +{ //TODO - no need to copy this as it gets turned into a FLoat32Array anyways.. var points = graphicsData.points.slice(); - if (points.length < 6) { + if (points.length < 6) + { return; } @@ -711,7 +770,8 @@ var x,y; // get size.. - for (var i = 0; i < points.length; i+=2) { + for (var i = 0; i < points.length; i+=2) + { x = points[i]; y = points[i+1]; @@ -732,7 +792,8 @@ //TODO - this aint needed! var length = points.length / 2; - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { indices.push( i ); } @@ -746,10 +807,12 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildPoly = function (graphicsData, webGLData) { +WebGLGraphics.buildPoly = function (graphicsData, webGLData) +{ var points = graphicsData.points; - if (points.length < 6) { + if (points.length < 6) + { return; } // get first and last point.. figure out the middle! @@ -767,7 +830,8 @@ var triangles = utils.PolyK.Triangulate(points); - if (!triangles) { + if (!triangles) + { return false; } @@ -775,7 +839,8 @@ var i = 0; - for (i = 0; i < triangles.length; i+=3) { + for (i = 0; i < triangles.length; i+=3) + { indices.push(triangles[i] + vertPos); indices.push(triangles[i] + vertPos); indices.push(triangles[i+1] + vertPos); @@ -783,7 +848,8 @@ indices.push(triangles[i+2] + vertPos); } - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { verts.push(points[i * 2], points[i * 2 + 1], r, g, b, alpha); } diff --git a/src/core/renderers/webgl/utils/WebGLGraphicsData.js b/src/core/renderers/webgl/utils/WebGLGraphicsData.js index c56d05e..c739ba7 100644 --- a/src/core/renderers/webgl/utils/WebGLGraphicsData.js +++ b/src/core/renderers/webgl/utils/WebGLGraphicsData.js @@ -2,7 +2,8 @@ * @class * @private */ -function WebGLGraphicsData(gl) { +function WebGLGraphicsData(gl) +{ this.gl = gl; //TODO does this need to be split before uploding?? @@ -22,7 +23,8 @@ /** * */ -WebGLGraphicsData.prototype.reset = function () { +WebGLGraphicsData.prototype.reset = function () +{ this.points.length = 0; this.indices.length = 0; }; @@ -30,7 +32,8 @@ /** * */ -WebGLGraphicsData.prototype.upload = function () { +WebGLGraphicsData.prototype.upload = function () +{ var gl = this.gl; // this.lastIndex = graphics.graphicsData.length; diff --git a/src/core/renderers/webgl/utils/WebGLSpriteBatch.js b/src/core/renderers/webgl/utils/WebGLSpriteBatch.js index 96eaa52..55befbb 100644 --- a/src/core/renderers/webgl/utils/WebGLSpriteBatch.js +++ b/src/core/renderers/webgl/utils/WebGLSpriteBatch.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this sprite batch works for. */ -function WebGLSpriteBatch(renderer) { +function WebGLSpriteBatch(renderer) +{ /** * * @@ -88,7 +89,8 @@ */ this.lastIndexCount = 0; - for (var i=0, j=0; i < numIndices; i += 6, j += 4) { + 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; @@ -162,7 +164,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.setupContext(); }); } @@ -173,7 +176,8 @@ /** * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLSpriteBatch.prototype.setupContext = function () { +WebGLSpriteBatch.prototype.setupContext = function () +{ var gl = this.renderer.gl; // setup default shader @@ -198,7 +202,8 @@ /** * */ -WebGLSpriteBatch.prototype.begin = function () { +WebGLSpriteBatch.prototype.begin = function () +{ // this.shader = this.renderer.shaderManager.defaultShader; this.start(); @@ -206,19 +211,22 @@ /** */ -WebGLSpriteBatch.prototype.end = function () { +WebGLSpriteBatch.prototype.end = function () +{ this.flush(); }; /** * @param sprite {Sprite} the sprite to render when using this spritebatch */ -WebGLSpriteBatch.prototype.render = function (sprite) { +WebGLSpriteBatch.prototype.render = function (sprite) +{ var texture = sprite.texture; //TODO set blend modes.. // check texture.. - if (this.currentBatchSize >= this.size) { + if (this.currentBatchSize >= this.size) + { this.flush(); this.currentBaseTexture = texture.baseTexture; } @@ -227,7 +235,8 @@ var uvs = texture._uvs; // if the uvs have not updated then no point rendering just yet! - if (!uvs) { + if (!uvs) + { return; } @@ -237,7 +246,8 @@ var w0, w1, h0, h1; - if (texture.trim) { + 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; @@ -248,7 +258,8 @@ h0 = h1 + texture.crop.height; } - else { + else + { w0 = (texture.frame.width ) * (1-aX); w1 = (texture.frame.width ) * -aX; @@ -272,7 +283,8 @@ var colors = this.colors; var positions = this.positions; - if (this.renderer.roundPixels) { + if (this.renderer.roundPixels) + { // xy positions[index] = a * w1 + c * h1 + tx | 0; positions[index+1] = d * h1 + b * w1 + ty | 0; @@ -289,7 +301,8 @@ positions[index+15] = a * w1 + c * h0 + tx | 0; positions[index+16] = d * h0 + b * w1 + ty | 0; } - else { + else + { // xy positions[index] = a * w1 + c * h1 + tx; positions[index+1] = d * h1 + b * w1 + ty; @@ -338,11 +351,13 @@ * * @param sprite {TilingSprite} the tilingSprite to render */ -WebGLSpriteBatch.prototype.renderTilingSprite = function (tilingSprite) { +WebGLSpriteBatch.prototype.renderTilingSprite = function (tilingSprite) +{ var texture = tilingSprite.tilingTexture; // check texture.. - if (this.currentBatchSize >= this.size) { + if (this.currentBatchSize >= this.size) + { //return; this.flush(); this.currentBaseTexture = texture.baseTexture; @@ -351,7 +366,8 @@ // set the textures uvs temporarily // TODO create a separate texture so that we can tile part of a texture - if (!tilingSprite._uvs) { + if (!tilingSprite._uvs) + { tilingSprite._uvs = new TextureUvs(); } @@ -454,16 +470,19 @@ * Renders the content and empties the current batch. * */ -WebGLSpriteBatch.prototype.flush = function () { +WebGLSpriteBatch.prototype.flush = function () +{ // If the batch is length 0 then return as there is nothing to draw - if (this.currentBatchSize === 0) { + if (this.currentBatchSize === 0) + { return; } var gl = this.renderer.gl; var shader; - if (this.dirty) { + if (this.dirty) + { this.dirty = false; // bind the main texture gl.activeTexture(gl.TEXTURE0); @@ -482,10 +501,12 @@ } // upload the verts to the buffer - if (this.currentBatchSize > ( this.size * 0.5 ) ) { + if (this.currentBatchSize > ( this.size * 0.5 ) ) + { gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); } - else { + else + { var view = this.positions.subarray(0, this.currentBatchSize * this.vertByteSize); gl.bufferSubData(gl.ARRAY_BUFFER, 0, view); } @@ -502,7 +523,8 @@ var shaderSwap = false; var sprite; - for (var i = 0, j = this.currentBatchSize; i < j; i++) { + for (var i = 0, j = this.currentBatchSize; i < j; i++) + { sprite = this.sprites[i]; @@ -513,24 +535,28 @@ blendSwap = currentBlendMode !== nextBlendMode; shaderSwap = currentShader !== nextShader; // should I use uuidS??? - if (currentBaseTexture !== nextTexture || blendSwap || shaderSwap) { + if (currentBaseTexture !== nextTexture || blendSwap || shaderSwap) + { this.renderBatch(currentBaseTexture, batchSize, start); start = i; batchSize = 0; currentBaseTexture = nextTexture; - if (blendSwap) { + if (blendSwap) + { currentBlendMode = nextBlendMode; this.renderer.blendModeManager.setBlendMode( currentBlendMode ); } - if (shaderSwap) { + if (shaderSwap) + { currentShader = nextShader; shader = currentShader.shaders ? currentShader.shaders[gl.id] : currentShader; - if (!shader) { + if (!shader) + { shader = new Shader(gl, null, currentShader.fragmentSrc, currentShader.uniforms); currentShader.shaders[gl.id] = shader; } @@ -538,7 +564,8 @@ // set shader function??? this.renderer.shaderManager.setShader(shader); - if (shader.dirty) { + if (shader.dirty) + { shader.syncUniforms(); } @@ -569,17 +596,21 @@ * @param size {number} * @param startIndex {number} */ -WebGLSpriteBatch.prototype.renderBatch = function (texture, size, startIndex) { - if (size === 0) { +WebGLSpriteBatch.prototype.renderBatch = function (texture, size, startIndex) +{ + if (size === 0) + { return; } var gl = this.renderer.gl; - if (!texture._glTextures[gl.id]) { + if (!texture._glTextures[gl.id]) + { this.renderer.updateTexture(texture); } - else { + else + { // bind the current texture gl.bindTexture(gl.TEXTURE_2D, texture._glTextures[gl.id]); } @@ -594,7 +625,8 @@ /** * */ -WebGLSpriteBatch.prototype.stop = function () { +WebGLSpriteBatch.prototype.stop = function () +{ this.flush(); this.dirty = true; }; @@ -602,7 +634,8 @@ /** * */ -WebGLSpriteBatch.prototype.start = function () { +WebGLSpriteBatch.prototype.start = function () +{ this.dirty = true; }; @@ -610,7 +643,8 @@ * Destroys the SpriteBatch. * */ -WebGLSpriteBatch.prototype.destroy = function () { +WebGLSpriteBatch.prototype.destroy = function () +{ this.renderer.gl.deleteBuffer(this.vertexBuffer); this.renderer.gl.deleteBuffer(this.indexBuffer); diff --git a/src/core/textures/BaseTexture.js b/src/core/textures/BaseTexture.js index 2bf77d4..513d358 100644 --- a/src/core/textures/BaseTexture.js +++ b/src/core/textures/BaseTexture.js @@ -10,7 +10,8 @@ * @param source {Image|Canvas} the source object of the texture. * @param [scaleMode=scaleModes.DEFAULT] {number} See {@link scaleModes} for possible values */ -function BaseTexture(source, scaleMode) { +function BaseTexture(source, scaleMode) +{ this.uuid = utils.uuid(); /** @@ -123,7 +124,8 @@ this._needsUpdate = false; // if no source passed don't try to load - if (source) { + if (source) + { this.loadSource(source); } @@ -149,13 +151,16 @@ Object.defineProperties(BaseTexture.prototype, { needsUpdate: { - get: function () { + get: function () + { return this._needsUpdate; }, - set: function (val) { + set: function (val) + { this._needsUpdate = val; - if (val) { + if (val) + { this.emit('update', this); } } @@ -171,9 +176,11 @@ * * The logic state after calling `loadSource` directly or indirectly (eg. `fromImage`, `new BaseTexture`) is: * - * if (texture.hasLoaded) { + * if (texture.hasLoaded) + { * // texture ready for use - * } else if (texture.isLoading) { + * } else if (texture.isLoading) + { * // listen to 'loaded' and/or 'error' events on texture * } else { * // not loading, not going to load UNLESS the source is reloaded @@ -183,12 +190,14 @@ * @protected * @param source {Image|Canvas} the source object of the texture. */ -BaseTexture.prototype.loadSource = function (source) { +BaseTexture.prototype.loadSource = function (source) +{ var wasLoading = this.isLoading; this.hasLoaded = false; this.isLoading = false; - if (wasLoading && this.source) { + if (wasLoading && this.source) + { this.source.onload = null; this.source.onerror = null; } @@ -196,20 +205,24 @@ this.source = source; // Apply source if loaded. Otherwise setup appropriate loading monitors. - if ((this.source.complete || this.source.getContext) && this.source.width && this.source.height) { + if ((this.source.complete || this.source.getContext) && this.source.width && this.source.height) + { this._sourceLoaded(); } - else if(!source.getContext) { + else if(!source.getContext) + { // Image fail / not ready this.isLoading = true; var scope = this; - source.onload = function () { + source.onload = function () + { source.onload = null; source.onerror = null; - if(!scope.isLoading) { + if(!scope.isLoading) + { return; } @@ -219,11 +232,13 @@ scope.emit('loaded', scope); }; - source.onerror = function () { + source.onerror = function () + { source.onload = null; source.onerror = null; - if(!scope.isLoading) { + if(!scope.isLoading) + { return; } @@ -234,24 +249,29 @@ // Per http://www.w3.org/TR/html5/embedded-content-0.html#the-img-element // "The value of `complete` can thus change while a script is executing." // So complete needs to be re-checked after the callbacks have been added.. - if (source.complete) { + if (source.complete) + { this.isLoading = false; // ..and if we're complete now, no need for callbacks source.onload = null; source.onerror = null; - if (source.width && source.height) { + if (source.width && source.height) + { this._sourceLoaded(); // If any previous subscribers possible - if (wasLoading) { + if (wasLoading) + { this.emit('loaded', this); } } - else { + else + { // If any previous subscribers possible - if (wasLoading) { + if (wasLoading) + { this.emit('error', this); } } @@ -265,7 +285,8 @@ * * @private */ -BaseTexture.prototype._sourceLoaded = function () { +BaseTexture.prototype._sourceLoaded = function () +{ this.hasLoaded = true; this.width = this.source.naturalWidth || this.source.width; @@ -278,16 +299,20 @@ * Destroys this base texture * */ -BaseTexture.prototype.destroy = function () { - if (this.imageUrl) { +BaseTexture.prototype.destroy = function () +{ + if (this.imageUrl) + { delete utils.BaseTextureCache[this.imageUrl]; delete utils.TextureCache[this.imageUrl]; this.imageUrl = null; - if (!navigator.isCocoonJS) { + if (!navigator.isCocoonJS) + { this.source.src = ''; } } - else if (this.source && this.source._pixiId) { + else if (this.source && this.source._pixiId) + { delete utils.BaseTextureCache[this.source._pixiId]; } this.source = null; @@ -301,7 +326,8 @@ * memory again. * */ -BaseTexture.prototype.dispose = function () { +BaseTexture.prototype.dispose = function () +{ this.emit('dispose', this); }; @@ -311,7 +337,8 @@ * * @param newSrc {string} the path of the image */ -BaseTexture.prototype.updateSourceImage = function (newSrc) { +BaseTexture.prototype.updateSourceImage = function (newSrc) +{ this.source.src = newSrc; this.loadSource(this.source); }; @@ -326,18 +353,22 @@ * @param [scaleMode=scaleModes.DEFAULT] {number} See {@link scaleModes} for possible values * @return BaseTexture */ -BaseTexture.fromImage = function (imageUrl, crossorigin, scaleMode) { +BaseTexture.fromImage = function (imageUrl, crossorigin, scaleMode) +{ var baseTexture = utils.BaseTextureCache[imageUrl]; - if (crossorigin === undefined && imageUrl.indexOf('data:') !== 0) { + if (crossorigin === undefined && imageUrl.indexOf('data:') !== 0) + { crossorigin = true; } - if (!baseTexture) { + if (!baseTexture) + { // new Image() breaks tex loading in some versions of Chrome. // See https://code.google.com/p/chromium/issues/detail?id=238071 var image = new Image();//document.createElement('img'); - if (crossorigin) { + if (crossorigin) + { image.crossOrigin = ''; } @@ -347,7 +378,8 @@ utils.BaseTextureCache[imageUrl] = baseTexture; // if there is an @2x at the end of the url we are going to assume its a highres image - if ( imageUrl.indexOf(CONST.RETINA_PREFIX + '.') !== -1) { + if ( imageUrl.indexOf(CONST.RETINA_PREFIX + '.') !== -1) + { baseTexture.resolution = 2; } } @@ -363,14 +395,17 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return BaseTexture */ -BaseTexture.fromCanvas = function (canvas, scaleMode) { - if (!canvas._pixiId) { +BaseTexture.fromCanvas = function (canvas, scaleMode) +{ + if (!canvas._pixiId) + { canvas._pixiId = 'canvas_' + utils.uuid(); } var baseTexture = utils.BaseTextureCache[canvas._pixiId]; - if (!baseTexture) { + if (!baseTexture) + { baseTexture = new BaseTexture(canvas, scaleMode); utils.BaseTextureCache[canvas._pixiId] = baseTexture; } diff --git a/src/core/textures/RenderTexture.js b/src/core/textures/RenderTexture.js index 6dad20f..53ae796 100644 --- a/src/core/textures/RenderTexture.js +++ b/src/core/textures/RenderTexture.js @@ -46,8 +46,10 @@ * @param [scaleMode] {number} See {@link scaleModes} for possible values * @param [resolution=1] {number} The resolution of the texture being generated */ -function RenderTexture(renderer, width, height, scaleMode, resolution) { - if (!renderer) { +function RenderTexture(renderer, width, height, scaleMode, resolution) +{ + if (!renderer) + { throw new Error('Unable to create RenderTexture, you must pass a renderer into the constructor.'); } @@ -133,7 +135,8 @@ */ this.renderer = renderer; - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { var gl = this.renderer.gl; this.textureBuffer = new FilterTexture(gl, this.width * this.resolution, this.height * this.resolution, this.baseTexture.scaleMode); @@ -142,7 +145,8 @@ this.render = this.renderWebGL; this.projection = new math.Point(this.width*0.5, -this.height*0.5); } - else { + else + { this.render = this.renderCanvas; this.textureBuffer = new CanvasBuffer(this.width* this.resolution, this.height* this.resolution); this.baseTexture.source = this.textureBuffer.canvas; @@ -167,8 +171,10 @@ * @param height {number} The height to resize to. * @param updateBase {boolean} Should the baseTexture.width and height values be resized as well? */ -RenderTexture.prototype.resize = function (width, height, updateBase) { - if (width === this.width && height === this.height) { +RenderTexture.prototype.resize = function (width, height, updateBase) +{ + if (width === this.width && height === this.height) + { return; } @@ -177,17 +183,20 @@ this.width = this.frame.width = this.crop.width = width; this.height = this.frame.height = this.crop.height = height; - if (updateBase) { + if (updateBase) + { this.baseTexture.width = this.width; this.baseTexture.height = this.height; } - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { this.projection.x = this.width / 2; this.projection.y = -this.height / 2; } - if (!this.valid) { + if (!this.valid) + { return; } @@ -198,12 +207,15 @@ * Clears the RenderTexture. * */ -RenderTexture.prototype.clear = function () { - if (!this.valid) { +RenderTexture.prototype.clear = function () +{ + if (!this.valid) + { return; } - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { this.renderer.gl.bindFramebuffer(this.renderer.gl.FRAMEBUFFER, this.textureBuffer.frameBuffer); } @@ -220,19 +232,23 @@ * @param [restoreWorldTransform=true] {boolean} If true the displayObject's worldTransform/worldAlpha and all children * transformations will be restored. Not restoring this information will be a little faster. */ -RenderTexture.prototype.renderWebGL = function (displayObject, matrix, clear, restoreWorldTransform) { - if (!this.valid) { +RenderTexture.prototype.renderWebGL = function (displayObject, matrix, clear, restoreWorldTransform) +{ + if (!this.valid) + { return; } - if (typeof restoreWorldTransform === 'undefined') { + if (typeof restoreWorldTransform === 'undefined') + { restoreWorldTransform = true; } var tempAlpha, tempTransform; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { tempAlpha = displayObject.worldAlpha; tempTransform = displayObject.worldTransform.toArray(); } @@ -245,7 +261,8 @@ wt.identity(); wt.translate(0, this.projection.y * 2); - if (matrix) { + if (matrix) + { wt.append(matrix); } @@ -258,7 +275,8 @@ var children = displayObject.children; var i, j; - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } @@ -269,7 +287,8 @@ gl.bindFramebuffer(gl.FRAMEBUFFER, this.textureBuffer.frameBuffer ); - if (clear) { + if (clear) + { this.textureBuffer.clear(); } @@ -279,11 +298,13 @@ this.renderer.spriteBatch.dirty = true; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { displayObject.worldAlpha = tempAlpha; displayObject.worldTransform.fromArray(tempTransform); - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } } @@ -300,26 +321,31 @@ * @param [restoreWorldTransform=true] {boolean} If true the displayObject's worldTransform/worldAlpha and all children * transformations will be restored. Not restoring this information will be a little faster. */ -RenderTexture.prototype.renderCanvas = function (displayObject, matrix, clear, restoreWorldTransform) { - if (!this.valid) { +RenderTexture.prototype.renderCanvas = function (displayObject, matrix, clear, restoreWorldTransform) +{ + if (!this.valid) + { return; } - if (typeof restoreWorldTransform === 'undefined') { + if (typeof restoreWorldTransform === 'undefined') + { restoreWorldTransform = true; } var tempAlpha, tempTransform; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { tempAlpha = displayObject.worldAlpha; tempTransform = displayObject.worldTransform.toArray(); } var wt = displayObject.worldTransform; wt.identity(); - if (matrix) { + if (matrix) + { wt.append(matrix); } @@ -330,11 +356,13 @@ var children = displayObject.children; var i, j; - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } - if (clear) { + if (clear) + { this.textureBuffer.clear(); } @@ -348,11 +376,13 @@ this.renderer.resolution = realResolution; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { displayObject.worldAlpha = tempAlpha; displayObject.worldTransform.fromArray(tempTransform); - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } } @@ -363,7 +393,8 @@ * * @return {Image} */ -RenderTexture.prototype.getImage = function () { +RenderTexture.prototype.getImage = function () +{ var image = new Image(); image.src = this.getBase64(); return image; @@ -374,7 +405,8 @@ * * @return {string} A base64 encoded string of the texture. */ -RenderTexture.prototype.getBase64 = function () { +RenderTexture.prototype.getBase64 = function () +{ return this.getCanvas().toDataURL(); }; @@ -383,8 +415,10 @@ * * @return {HTMLCanvasElement} A Canvas element with the texture rendered on. */ -RenderTexture.prototype.getCanvas = function () { - if (this.renderer.type === CONST.WEBGL_RENDERER) { +RenderTexture.prototype.getCanvas = function () +{ + if (this.renderer.type === CONST.WEBGL_RENDERER) + { var gl = this.renderer.gl; var width = this.textureBuffer.width; var height = this.textureBuffer.height; @@ -403,7 +437,8 @@ return tempCanvas.canvas; } - else { + else + { return this.textureBuffer.canvas; } }; diff --git a/src/core/textures/Texture.js b/src/core/textures/Texture.js index 3c65909..e97f0aa 100644 --- a/src/core/textures/Texture.js +++ b/src/core/textures/Texture.js @@ -17,7 +17,8 @@ * @param [crop] {Rectangle} The area of original texture * @param [trim] {Rectangle} Trimmed texture rectangle */ -function Texture(baseTexture, frame, crop, trim) { +function Texture(baseTexture, frame, crop, trim) +{ /** * Does this Texture have any frame data assigned to it? * @@ -25,12 +26,14 @@ */ this.noFrame = false; - if (!frame) { + if (!frame) + { this.noFrame = true; frame = new math.Rectangle(0, 0, 1, 1); } - if (baseTexture instanceof Texture) { + if (baseTexture instanceof Texture) + { baseTexture = baseTexture.baseTexture; } @@ -100,13 +103,16 @@ */ this.crop = crop || new math.Rectangle(0, 0, 1, 1); - if (baseTexture.hasLoaded) { - if (this.noFrame) { + if (baseTexture.hasLoaded) + { + if (this.noFrame) + { frame = new math.Rectangle(0, 0, baseTexture.width, baseTexture.height); } this.frame = frame; } - else { + else + { baseTexture.addEventListener('loaded', this.onBaseTextureLoaded.bind(this)); } } @@ -118,19 +124,23 @@ Object.defineProperties(Texture.prototype, { needsUpdate: { - get: function () { + get: function () + { return this.baseTexture.needsUpdate; }, - set: function (val) { + set: function (val) + { this.baseTexture.needsUpdate = val; } }, frame: { - get: function () { + get: function () + { return this._frame; }, - set: function (frame) { + set: function (frame) + { this._frame = frame; this.noFrame = false; @@ -143,20 +153,23 @@ 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 (!this.trim && (frame.x + frame.width > this.baseTexture.width || frame.y + frame.height > this.baseTexture.height)) + { throw new Error('Texture Error: frame does not fit inside the base Texture dimensions ' + this); } this.valid = frame && frame.width && frame.height && this.baseTexture.source && this.baseTexture.hasLoaded; - if (this.trim) { + 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) { + if (this.valid) + { this._updateUvs(); } } @@ -168,11 +181,13 @@ * * @private */ -Texture.prototype.onBaseTextureLoaded = function () { +Texture.prototype.onBaseTextureLoaded = function () +{ var baseTexture = this.baseTexture; baseTexture.removeEventListener('loaded', this.onLoaded); - if (this.noFrame) { + if (this.noFrame) + { this.frame = new math.Rectangle(0, 0, baseTexture.width, baseTexture.height); } @@ -184,8 +199,10 @@ * * @param destroyBase {boolean} Whether to destroy the base texture as well */ -Texture.prototype.destroy = function (destroyBase) { - if (destroyBase) { +Texture.prototype.destroy = function (destroyBase) +{ + if (destroyBase) + { this.baseTexture.destroy(); } @@ -197,8 +214,10 @@ * * @private */ -Texture.prototype._updateUvs = function () { - if (!this._uvs) { +Texture.prototype._updateUvs = function () +{ + if (!this._uvs) + { this._uvs = new TextureUvs(); } @@ -229,10 +248,12 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return Texture */ -Texture.fromImage = function (imageUrl, crossorigin, scaleMode) { +Texture.fromImage = function (imageUrl, crossorigin, scaleMode) +{ var texture = utils.TextureCache[imageUrl]; - if (!texture) { + if (!texture) + { texture = new Texture(BaseTexture.fromImage(imageUrl, crossorigin, scaleMode)); utils.TextureCache[imageUrl] = texture; } @@ -248,9 +269,11 @@ * @param frameId {string} The frame id of the texture * @return Texture */ -Texture.fromFrame = function (frameId) { +Texture.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache '); } return texture; @@ -264,7 +287,8 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return {Texture} */ -Texture.fromCanvas = function (canvas, scaleMode) { +Texture.fromCanvas = function (canvas, scaleMode) +{ return new Texture(BaseTexture.fromCanvas(canvas, scaleMode)); }; @@ -276,7 +300,8 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return {Texture} A Texture */ -Texture.fromVideo = function (video, scaleMode) { +Texture.fromVideo = function (video, scaleMode) +{ return new Texture(VideoBaseTexture.baseTextureFromVideo(video, scaleMode)); }; @@ -287,7 +312,8 @@ * @param texture {Texture} The Texture to add to the cache. * @param id {string} The id that the texture will be stored against. */ -Texture.addTextureToCache = function (texture, id) { +Texture.addTextureToCache = function (texture, id) +{ utils.TextureCache[id] = texture; }; @@ -298,7 +324,8 @@ * @param id {string} The id of the texture to be removed * @return {Texture} The texture that was removed */ -Texture.removeTextureFromCache = function (id) { +Texture.removeTextureFromCache = function (id) +{ var texture = utils.TextureCache[id]; delete utils.TextureCache[id]; diff --git a/src/core/textures/TextureUvs.js b/src/core/textures/TextureUvs.js index b9bbb58..5424d52 100644 --- a/src/core/textures/TextureUvs.js +++ b/src/core/textures/TextureUvs.js @@ -1,4 +1,5 @@ -function TextureUvs() { +function TextureUvs() +{ this.x0 = 0; this.y0 = 0; diff --git a/src/core/textures/VideoBaseTexture.js b/src/core/textures/VideoBaseTexture.js index e3e0c5a..1a826a9 100644 --- a/src/core/textures/VideoBaseTexture.js +++ b/src/core/textures/VideoBaseTexture.js @@ -12,15 +12,18 @@ * @param source {HTMLVideoElement} * @param [scaleMode] {number} See {@link scaleModes} for possible values */ -function VideoBaseTexture(source, scaleMode) { - if (!source){ +function VideoBaseTexture(source, scaleMode) +{ + if (!source) + { throw new Error('No video source element specified.'); } // hook in here to check if video is already available. // BaseTexture looks for a source.complete boolean, plus width & height. - if ((source.readyState === source.HAVE_ENOUGH_DATA || source.readyState === source.HAVE_FUTURE_DATA) && source.width && source.height) { + if ((source.readyState === source.HAVE_ENOUGH_DATA || source.readyState === source.HAVE_FUTURE_DATA) && source.width && source.height) + { source.complete = true; } @@ -31,7 +34,8 @@ this._boundOnUpdate = this._onUpdate.bind(this); this._boundOnCanPlay = this._onCanPlay.bind(this); - if (!source.complete) { + if (!source.complete) + { source.addEventListener('canplay', this._boundOnCanPlay); source.addEventListener('canplaythrough', this._boundOnCanPlay); @@ -47,28 +51,35 @@ VideoBaseTexture.prototype.constructor = VideoBaseTexture; module.exports = VideoBaseTexture; -VideoBaseTexture.prototype._onUpdate = function () { - if (this.autoUpdate) { +VideoBaseTexture.prototype._onUpdate = function () +{ + if (this.autoUpdate) + { window.requestAnimationFrame(this._boundOnUpdate); this.needsUpdate = true; } }; -VideoBaseTexture.prototype._onPlayStart = function () { - if (!this.autoUpdate) { +VideoBaseTexture.prototype._onPlayStart = function () +{ + if (!this.autoUpdate) + { window.requestAnimationFrame(this._boundOnUpdate); this.autoUpdate = true; } }; -VideoBaseTexture.prototype._onPlayStop = function () { +VideoBaseTexture.prototype._onPlayStop = function () +{ this.autoUpdate = false; }; -VideoBaseTexture.prototype._onCanPlay = function () { +VideoBaseTexture.prototype._onCanPlay = function () +{ this.hasLoaded = true; - if (this.source) { + if (this.source) + { this.source.removeEventListener('canplay', this._boundOnCanPlay); this.source.removeEventListener('canplaythrough', this._boundOnCanPlay); @@ -78,15 +89,18 @@ this.source.play(); // prevent multiple loaded dispatches.. - if(!this.__loaded){ + if(!this.__loaded) + { this.__loaded = true; this.emit('loaded', this); } } }; -VideoBaseTexture.prototype.destroy = function () { - if (this.source && this.source._pixiId) { +VideoBaseTexture.prototype.destroy = function () +{ + if (this.source && this.source._pixiId) + { utils.BaseTextureCache[ this.source._pixiId ] = null; delete utils.BaseTextureCache[ this.source._pixiId ]; @@ -105,14 +119,17 @@ * @param scaleMode {number} See {@link scaleModes} for possible values * @return {VideoBaseTexture} */ -VideoBaseTexture.fromVideo = function (video, scaleMode) { - if (!video._pixiId) { +VideoBaseTexture.fromVideo = function (video, scaleMode) +{ + if (!video._pixiId) + { video._pixiId = 'video_' + utils.uuid(); } var baseTexture = utils.BaseTextureCache[video._pixiId]; - if (!baseTexture) { + if (!baseTexture) + { baseTexture = new VideoBaseTexture(video, scaleMode); utils.BaseTextureCache[ video._pixiId ] = baseTexture; } @@ -147,17 +164,21 @@ * @param scaleMode {number} See {@link scaleModes} for possible values * @return {VideoBaseTexture} */ -VideoBaseTexture.fromUrl = function (videoSrc, scaleMode) { +VideoBaseTexture.fromUrl = function (videoSrc, scaleMode) +{ var video = document.createElement('video'); // array of objects or strings - if (Array.isArray(videoSrc)) { - for (var i = 0; i < videoSrc.length; ++i) { + if (Array.isArray(videoSrc)) + { + for (var i = 0; i < videoSrc.length; ++i) + { video.appendChild(createSource(videoSrc.src || videoSrc, videoSrc.mime)); } } // single object or string - else { + else + { video.appendChild(createSource(videoSrc.src || videoSrc, videoSrc.mime)); } @@ -169,8 +190,10 @@ VideoBaseTexture.fromUrls = VideoBaseTexture.fromUrl; -function createSource(path, type) { - if (!type) { +function createSource(path, type) +{ + if (!type) + { type = 'video/' + path.substr(path.lastIndexOf('.') + 1); } diff --git a/src/core/utils/EventData.js b/src/core/utils/EventData.js index 5d55a22..8cdf701 100644 --- a/src/core/utils/EventData.js +++ b/src/core/utils/EventData.js @@ -7,7 +7,8 @@ * @param name {string} The string name of the event that was triggered * @param data {object} Arbitrary event data to pass along */ -function EventData(target, name, data) { +function EventData(target, name, data) +{ // for duck typing in the ".on()" function this.__isEventObject = true; @@ -71,7 +72,8 @@ * Stops the propagation of events up the scene graph (prevents bubbling). * */ -EventData.prototype.stopPropagation = function stopPropagation() { +EventData.prototype.stopPropagation = function stopPropagation() +{ this.stopped = true; }; @@ -79,6 +81,7 @@ * Stops the propagation of events to sibling listeners (no longer calls any listeners). * */ -EventData.prototype.stopImmediatePropagation = function stopImmediatePropagation() { +EventData.prototype.stopImmediatePropagation = function stopImmediatePropagation() +{ this.stoppedImmediate = true; }; diff --git a/src/core/utils/EventTarget.js b/src/core/utils/EventTarget.js index 7ae8820..671a151 100644 --- a/src/core/utils/EventTarget.js +++ b/src/core/utils/EventTarget.js @@ -13,14 +13,16 @@ * var em = new MyEmitter(); * em.emit('eventName', 'some data', 'some more data', {}, null, ...); */ -function eventTarget(obj) { +function eventTarget(obj) +{ /** * Return a list of assigned event listeners. * * @param eventName {string} The events that should be listed. * @return {Array} An array of listener functions */ - obj.listeners = function listeners(eventName) { + obj.listeners = function listeners(eventName) + { this._listeners = this._listeners || {}; return this._listeners[eventName] ? this._listeners[eventName].slice() : []; @@ -33,22 +35,26 @@ * @param eventName {string} The name of the event. * @return {boolean} Indication if we've emitted an event. */ - obj.emit = obj.dispatchEvent = function emit(eventName, data) { + obj.emit = obj.dispatchEvent = function emit(eventName, data) + { this._listeners = this._listeners || {}; // fast return when there are no listeners - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return; } //backwards compat with old method ".emit({ type: 'something' })" - if (typeof eventName === 'object') { + if (typeof eventName === 'object') + { data = eventName; eventName = eventName.type; } //ensure we are using a real pixi event - if (!data || data.__isEventObject !== true) { + if (!data || data.__isEventObject !== true) + { data = new EventData(this, eventName, data); } @@ -58,23 +64,27 @@ fn = listeners[0], i; - for (i = 0; i < length; fn = listeners[++i]) { + for (i = 0; i < length; fn = listeners[++i]) + { //call the event listener fn.call(this, data); //if "stopImmediatePropagation" is called, stop calling sibling events - if (data.stoppedImmediate) { + if (data.stoppedImmediate) + { return this; } } //if "stopPropagation" is called then don't bubble the event - if (data.stopped) { + if (data.stopped) + { return this; } //bubble this event up the scene graph - if (this.parent && this.parent.emit) { + if (this.parent && this.parent.emit) + { this.parent.emit.call(this.parent, eventName, data); } @@ -88,7 +98,8 @@ * @param eventName {string} Name of the event. * @param callback {Functon} fn Callback function. */ - obj.on = obj.addEventListener = function on(eventName, fn) { + obj.on = obj.addEventListener = function on(eventName, fn) + { this._listeners = this._listeners || {}; (this._listeners[eventName] = this._listeners[eventName] || []) @@ -103,11 +114,13 @@ * @param eventName {string} Name of the event. * @param callback {Function} Callback function. */ - obj.once = function once(eventName, fn) { + obj.once = function once(eventName, fn) + { this._listeners = this._listeners || {}; var self = this; - function onceHandlerWrapper() { + function onceHandlerWrapper() + { fn.apply(self.off(eventName, onceHandlerWrapper), arguments); } onceHandlerWrapper._originalHandler = fn; @@ -122,23 +135,28 @@ * @param eventName {string} The event we want to remove. * @param callback {Function} The listener that we need to find. */ - obj.off = obj.removeEventListener = function off(eventName, fn) { + obj.off = obj.removeEventListener = function off(eventName, fn) + { this._listeners = this._listeners || {}; - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return this; } var list = this._listeners[eventName], i = fn ? list.length : 0; - while(i-- > 0) { - if (list[i] === fn || list[i]._originalHandler === fn) { + while(i-- > 0) + { + if (list[i] === fn || list[i]._originalHandler === fn) + { list.splice(i, 1); } } - if (list.length === 0) { + if (list.length === 0) + { delete this._listeners[eventName]; } @@ -150,10 +168,12 @@ * * @param eventName {string} The event you want to remove all listeners for. */ - obj.removeAllListeners = function removeAllListeners(eventName) { + obj.removeAllListeners = function removeAllListeners(eventName) + { this._listeners = this._listeners || {}; - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return this; } @@ -169,7 +189,8 @@ * * @param object {object} The obj to mix into */ - mixin: function mixin(obj) { + mixin: function mixin(obj) + { eventTarget(obj); } }; diff --git a/src/core/utils/PolyK.js b/src/core/utils/PolyK.js index 7325141..5e20c2b 100644 --- a/src/core/utils/PolyK.js +++ b/src/core/utils/PolyK.js @@ -47,7 +47,8 @@ * Triangulates shapes for webGL graphic fills. * */ -PolyK.Triangulate = function (p) { +PolyK.Triangulate = function (p) +{ var sign = true; var n = p.length >> 1; @@ -59,7 +60,8 @@ i = 0; var al = n; - while(al > 3) { + while(al > 3) + { var i0 = avl[(i+0)%al]; var i1 = avl[(i+1)%al]; var i2 = avl[(i+2)%al]; @@ -69,29 +71,35 @@ var cx = p[2*i2], cy = p[2*i2+1]; var earFound = false; - if (PolyK._convex(ax, ay, bx, by, cx, cy, sign)) { + if (PolyK._convex(ax, ay, bx, by, cx, cy, sign)) + { earFound = true; - for (var j = 0; j < al; j++) { + for (var j = 0; j < al; j++) + { var vi = avl[j]; if (vi === i0 || vi === i1 || vi === i2) continue; - if (PolyK._PointInTriangle(p[2*vi], p[2*vi+1], ax, ay, bx, by, cx, cy)) { + if (PolyK._PointInTriangle(p[2*vi], p[2*vi+1], ax, ay, bx, by, cx, cy)) + { earFound = false; break; } } } - if (earFound) { + if (earFound) + { tgs.push(i0, i1, i2); avl.splice((i+1)%al, 1); al--; i = 0; } - else if (i++ > 3*al) { + else if (i++ > 3*al) + { // need to flip flip reverse it! // reset! - if (sign) { + if (sign) + { tgs = []; avl = []; for (i = 0; i < n; i++) avl.push(i); @@ -101,7 +109,8 @@ sign = false; } - else { + else + { // window.console.log("PIXI Warning: shape too complex to fill"); return null; } @@ -126,7 +135,8 @@ * @private * @return {boolean} */ -PolyK._PointInTriangle = function (px, py, ax, ay, bx, by, cx, cy) { +PolyK._PointInTriangle = function (px, py, ax, ay, bx, by, cx, cy) +{ var v0x = cx-ax; var v0y = cy-ay; var v1x = bx-ax; @@ -154,6 +164,7 @@ * @private * @return {boolean} */ -PolyK._convex = function (ax, ay, bx, by, cx, cy, sign) { +PolyK._convex = function (ax, ay, bx, by, cx, cy, sign) +{ return ((ay-by)*(cx-bx) + (bx-ax)*(cy-by) >= 0) === sign; }; diff --git a/src/core/utils/index.js b/src/core/utils/index.js index ade9831..bfae7ae 100644 --- a/src/core/utils/index.js +++ b/src/core/utils/index.js @@ -16,7 +16,8 @@ * * @return {number} The next uuid to use. */ - uuid: function () { + uuid: function () + { return ++utils._uid; }, @@ -26,7 +27,8 @@ * @param hex {number} * @return {number[]} An array representing the [R, G, B] of the color. */ - hex2rgb: function (hex, out) { + hex2rgb: function (hex, out) + { out = out || []; out[0] = (hex >> 16 & 0xFF) / 255; @@ -42,7 +44,8 @@ * @param hex {number} * @return {string} The string color. */ - hex2string: function (hex) { + hex2string: function (hex) + { hex = hex.toString(16); hex = '000000'.substr(0, 6 - hex.length) + hex; @@ -55,7 +58,8 @@ * @param rgb {number[]} * @return {number} The color number */ - rgb2hex: function (rgb) { + rgb2hex: function (rgb) + { return ((rgb[0]*255 << 16) + (rgb[1]*255 << 8) + rgb[2]*255); }, @@ -64,8 +68,10 @@ * * @return {boolean} whether they are supported */ - canUseNewCanvasBlendModes: function () { - if (typeof document === 'undefined') { + canUseNewCanvasBlendModes: function () + { + if (typeof document === 'undefined') + { return false; } @@ -93,15 +99,19 @@ * @param number {number} * @return {number} the closest number that is a power of two */ - getNextPowerOfTwo: function (number) { + getNextPowerOfTwo: function (number) + { // see: http://en.wikipedia.org/wiki/Power_of_two#Fast_algorithm_to_check_if_a_positive_number_is_a_power_of_two - if (number > 0 && (number & (number - 1)) === 0) { + if (number > 0 && (number & (number - 1)) === 0) + { return number; } - else { + else + { var result = 1; - while (result < number) { + while (result < number) + { result <<= 1; } @@ -116,7 +126,8 @@ * @param height {number} * @return {boolean} */ - isPowerOfTwo: function (width, height) { + isPowerOfTwo: function (width, height) + { return (width > 0 && (width & (width - 1)) === 0 && height > 0 && (height & (height - 1)) === 0); }, @@ -130,12 +141,15 @@ * @constant * @static */ - sayHello: function (type) { - if (utils._saidHello) { + sayHello: function (type) + { + if (utils._saidHello) + { return; } - if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) { + if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) + { var args = [ '%c %c %c Pixi.js ' + CONST.VERSION + ' - ' + type + ' %c ' + ' %c ' + ' http://www.pixijs.com/ %c %c ♥%c♥%c♥ ', 'background: #ff66a5', @@ -151,7 +165,8 @@ console.log.apply(console, args); //jshint ignore:line } - else if (window.console) { + else if (window.console) + { console.log('Pixi.js ' + CONST.VERSION + ' - ' + type + ' - http://www.pixijs.com/'); //jshint ignore:line } @@ -166,15 +181,19 @@ * @class * @namespace PIXI */ - AjaxRequest: function () { + AjaxRequest: function () + { var activexmodes = ['Msxml2.XMLHTTP.6.0', 'Msxml2.XMLHTTP.3.0', 'Microsoft.XMLHTTP']; //activeX versions to check for in IE - if (window.ActiveXObject) { //Test for support for ActiveXObject in IE first (as XMLHttpRequest in IE7 is broken) - for (var i=0; i= this.textures.length) { + else if (round >= this.textures.length) + { this.gotoAndStop(this.textures.length - 1); - if (this.onComplete) { + if (this.onComplete) + { this.onComplete(); } } @@ -167,10 +182,12 @@ * @static * @param frames {string[]} the array of frames ids the movieclip will use as its texture frames */ -MovieClip.fromFrames = function (frames) { +MovieClip.fromFrames = function (frames) +{ var textures = []; - for (var i = 0; i < frames.length; ++i) { + for (var i = 0; i < frames.length; ++i) + { textures.push(new core.Texture.fromFrame(frames[i])); } @@ -183,10 +200,12 @@ * @static * @param images {string[]} the array of image urls the movieclip will use as its texture frames */ -MovieClip.fromImages = function (images) { +MovieClip.fromImages = function (images) +{ var textures = []; - for (var i = 0; i < images.length; ++i) { + for (var i = 0; i < images.length; ++i) + { textures.push(new core.Texture.fromImage(images[i])); } diff --git a/src/extras/Rope.js b/src/extras/Rope.js index c157ec4..9c87bc0 100644 --- a/src/extras/Rope.js +++ b/src/extras/Rope.js @@ -9,7 +9,8 @@ * @param {Array} points - An array of {Point}. * */ -function Rope(texture, points) { +function Rope(texture, points) +{ Strip.call(this, texture); this.points = points; @@ -31,10 +32,12 @@ * Refreshes * */ -Rope.prototype.refresh = function () { +Rope.prototype.refresh = function () +{ var points = this.points; - if (points.length < 1) { + if (points.length < 1) + { return; } @@ -59,20 +62,23 @@ var total = points.length, point, index, amount; - for (var i = 1; i < total; i++) { + for (var i = 1; i < total; i++) + { point = points[i]; index = i * 4; // time to do some smart drawing! amount = i / (total-1); - if (i%2) { + if (i%2) + { uvs[index] = amount; uvs[index+1] = 0; uvs[index+2] = amount; uvs[index+3] = 1; } - else { + else + { uvs[index] = amount; uvs[index+1] = 0; @@ -95,10 +101,12 @@ * * @private */ -Rope.prototype.updateTransform = function () { +Rope.prototype.updateTransform = function () +{ var points = this.points; - if (points.length < 1) { + if (points.length < 1) + { return; } @@ -113,14 +121,17 @@ var total = points.length, point, index, ratio, perpLength, num; - for (var i = 0; i < total; i++) { + for (var i = 0; i < total; i++) + { point = points[i]; index = i * 4; - if (i < points.length-1) { + if (i < points.length-1) + { nextPoint = points[i+1]; } - else { + else + { nextPoint = point; } @@ -129,7 +140,8 @@ ratio = (1 - (i / (total-1))) * 10; - if (ratio > 1) { + if (ratio > 1) + { ratio = 1; } @@ -157,7 +169,8 @@ * * @param texture {Texture} the texture that will be used */ -Rope.prototype.setTexture = function (texture) { +Rope.prototype.setTexture = function (texture) +{ // stop current texture this.texture = texture; //this.updateFrame = true; diff --git a/src/extras/Strip.js b/src/extras/Strip.js index c5e378f..57691b5 100644 --- a/src/extras/Strip.js +++ b/src/extras/Strip.js @@ -10,7 +10,8 @@ * @param height {number} the height * */ -function Strip(texture) { +function Strip(texture) +{ core.DisplayObjectContainer.call(this); /** @@ -70,9 +71,11 @@ * * @param renderer {WebGLRenderer} */ -Strip.prototype.renderWebGL = function (renderer) { +Strip.prototype.renderWebGL = function (renderer) +{ // if the sprite is not visible or the alpha is 0 then no need to render this element - if (!this.visible || this.alpha <= 0) { + if (!this.visible || this.alpha <= 0) + { return; } @@ -81,7 +84,8 @@ renderer.spriteBatch.stop(); // init! init! - if (!this._vertexBuffer) { + if (!this._vertexBuffer) + { this._initWebGL(renderer); } @@ -96,7 +100,8 @@ //TODO check culling }; -Strip.prototype._initWebGL = function (renderer) { +Strip.prototype._initWebGL = function (renderer) +{ // build the strip! var gl = renderer.gl; @@ -118,7 +123,8 @@ gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this.indices, gl.STATIC_DRAW); }; -Strip.prototype._renderStrip = function (renderer) { +Strip.prototype._renderStrip = function (renderer) +{ var gl = renderer.gl; var projection = renderer.projection, offset = renderer.offset, @@ -137,7 +143,8 @@ gl.uniform2f(shader.offsetVector, -offset.x, -offset.y); gl.uniform1f(shader.alpha, this.worldAlpha); - if (!this.dirty) { + if (!this.dirty) + { gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexBuffer); gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); @@ -150,10 +157,12 @@ gl.activeTexture(gl.TEXTURE0); // check if a texture is dirty.. - if (this.texture.baseTexture._dirty[gl.id]) { + if (this.texture.baseTexture._dirty[gl.id]) + { renderer.updateTexture(this.texture.baseTexture); } - else { + else + { // bind the current texture gl.bindTexture(gl.TEXTURE_2D, this.texture.baseTexture._glTextures[gl.id]); } @@ -163,7 +172,8 @@ } - else { + else + { this.dirty = false; gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexBuffer); @@ -178,10 +188,12 @@ gl.activeTexture(gl.TEXTURE0); // check if a texture is dirty.. - if (this.texture.baseTexture._dirty[gl.id]) { + if (this.texture.baseTexture._dirty[gl.id]) + { renderer.updateTexture(this.texture.baseTexture); } - else { + else + { gl.bindTexture(gl.TEXTURE_2D, this.texture.baseTexture._glTextures[gl.id]); } @@ -203,27 +215,33 @@ * * @param renderer {CanvasRenderer} */ -Strip.prototype.renderCanvas = function (renderer) { +Strip.prototype.renderCanvas = function (renderer) +{ var context = renderer.context; var transform = this.worldTransform; - if (renderer.roundPixels) { + if (renderer.roundPixels) + { context.setTransform(transform.a, transform.b, transform.c, transform.d, transform.tx | 0, transform.ty | 0); } - else { + else + { context.setTransform(transform.a, transform.b, transform.c, transform.d, transform.tx, transform.ty); } - if (this.drawMode === Strip.DrawModes.TRIANGLE_STRIP) { + if (this.drawMode === Strip.DrawModes.TRIANGLE_STRIP) + { this._renderCanvasTriangleStrip(context); } - else { + else + { this._renderCanvasTriangles(context); } }; -Strip.prototype._renderCanvasTriangleStrip = function (context) { +Strip.prototype._renderCanvasTriangleStrip = function (context) +{ // draw triangles!! var vertices = this.vertices; var uvs = this.uvs; @@ -231,14 +249,16 @@ var length = vertices.length / 2; // this.count++; - for (var i = 0; i < length - 2; i++) { + for (var i = 0; i < length - 2; i++) + { // draw some triangles! var index = i * 2; this._renderCanvasDrawTriangle(context, vertices, uvs, index, (index + 2), (index + 4)); } }; -Strip.prototype._renderCanvasTriangles = function (context) { +Strip.prototype._renderCanvasTriangles = function (context) +{ // draw triangles!! var vertices = this.vertices; var uvs = this.uvs; @@ -247,14 +267,16 @@ var length = indices.length; // this.count++; - for (var i = 0; i < length; i += 3) { + for (var i = 0; i < length; i += 3) + { // draw some triangles! var index0 = indices[i] * 2, index1 = indices[i + 1] * 2, index2 = indices[i + 2] * 2; this._renderCanvasDrawTriangle(context, vertices, uvs, index0, index1, index2); } }; -Strip.prototype._renderCanvasDrawTriangle = function (context, vertices, uvs, index0, index1, index2) { +Strip.prototype._renderCanvasDrawTriangle = function (context, vertices, uvs, index0, index1, index2) +{ var textureSource = this.texture.baseTexture.source; var textureWidth = this.texture.width; var textureHeight = this.texture.height; @@ -265,7 +287,8 @@ var u0 = uvs[index0] * textureWidth, u1 = uvs[index1] * textureWidth, u2 = uvs[index2] * textureWidth; var v0 = uvs[index0 + 1] * textureHeight, v1 = uvs[index1 + 1] * textureHeight, v2 = uvs[index2 + 1] * textureHeight; - if (this.canvasPadding > 0) { + if (this.canvasPadding > 0) + { var paddingX = this.canvasPadding / this.worldTransform.a; var paddingY = this.canvasPadding / this.worldTransform.d; var centerX = (x0 + x1 + x2) / 3; @@ -332,7 +355,8 @@ * @param strip {Strip} The Strip to render * @private */ -Strip.prototype.renderStripFlat = function (strip) { +Strip.prototype.renderStripFlat = function (strip) +{ var context = this.context; var vertices = strip.vertices; @@ -340,7 +364,8 @@ // this.count++; context.beginPath(); - for (var i=1; i < length-2; i++) { + for (var i=1; i < length-2; i++) + { // draw some triangles! var index = i*2; @@ -358,7 +383,8 @@ }; /* -Strip.prototype.setTexture = function (texture) { +Strip.prototype.setTexture = function (texture) +{ //TODO SET THE TEXTURES //TODO VISIBILITY @@ -377,7 +403,8 @@ * @private */ -Strip.prototype.onTextureUpdate = function () { +Strip.prototype.onTextureUpdate = function () +{ this.updateFrame = true; }; @@ -387,7 +414,8 @@ * @param matrix {Matrix} the transformation matrix of the sprite * @return {Rectangle} the framing rectangle */ -Strip.prototype.getBounds = function (matrix) { +Strip.prototype.getBounds = function (matrix) +{ var worldTransform = matrix || this.worldTransform; var a = worldTransform.a; @@ -404,7 +432,8 @@ var minY = Infinity; var vertices = this.vertices; - for (var i = 0, n = vertices.length; i < n; i += 2) { + for (var i = 0, n = vertices.length; i < n; i += 2) + { var rawX = vertices[i], rawY = vertices[i + 1]; var x = (a * rawX) + (c * rawY) + tx; var y = (d * rawY) + (b * rawX) + ty; @@ -416,7 +445,8 @@ maxY = y > maxY ? y : maxY; } - if (minX === -Infinity || maxY === Infinity) { + if (minX === -Infinity || maxY === Infinity) + { return core.math.Rectangle.EMPTY; } diff --git a/src/extras/TilingSprite.js b/src/extras/TilingSprite.js index 3ac22df..31da393 100644 --- a/src/extras/TilingSprite.js +++ b/src/extras/TilingSprite.js @@ -10,7 +10,8 @@ * @param width {number} the width of the tiling sprite * @param height {number} the height of the tiling sprite */ -function TilingSprite(texture, width, height) { +function TilingSprite(texture, width, height) +{ core.Sprite.call( this, texture); /** @@ -86,10 +87,12 @@ * @memberof TilingSprite# */ width: { - get: function () { + get: function () + { return this._width; }, - set: function (value) { + set: function (value) + { this._width = value; } }, @@ -101,20 +104,25 @@ * @memberof TilingSprite# */ height: { - get: function () { + get: function () + { return this._height; }, - set: function (value) { + set: function (value) + { this._height = value; } }, texture: { - get: function () { + get: function () + { return this._texture; }, - set: function (value) { - if (this._texture === value) { + set: function (value) + { + if (this._texture === value) + { return; } @@ -130,51 +138,61 @@ * * @param renderer {WebGLRenderer} */ -TilingSprite.prototype.renderWebGL = function (renderer) { - if (!this.visible || this.alpha <= 0) { +TilingSprite.prototype.renderWebGL = function (renderer) +{ + if (!this.visible || this.alpha <= 0) + { return; } var i, j; - if (this._mask) { + if (this._mask) + { renderer.spriteBatch.stop(); renderer.maskManager.pushMask(this.mask, renderer); renderer.spriteBatch.start(); } - if (this._filters) { + if (this._filters) + { renderer.spriteBatch.flush(); renderer.filterManager.pushFilter(this._filterBlock); } - if (!this.tilingTexture || this.refreshTexture) { + if (!this.tilingTexture || this.refreshTexture) + { this.generateTilingTexture(true); - if (this.tilingTexture && this.tilingTexture.needsUpdate) { + if (this.tilingTexture && this.tilingTexture.needsUpdate) + { //TODO - tweaking renderer.updateTexture(this.tilingTexture.baseTexture); this.tilingTexture.needsUpdate = false; // this.tilingTexture._uvs = null; } } - else { + else + { renderer.spriteBatch.renderTilingSprite(this); } // simple render children! - for (i=0,j=this.children.length; i= 0; i--) { + for (var i = length - 1; i >= 0; i--) + { var child = children[i]; // push all interactive bits - if (child._interactive) { + if (child._interactive) + { iParent.interactiveChildren = true; //child.__iParent = iParent; this.interactiveItems.push(child); - if (child.children.length > 0) { + if (child.children.length > 0) + { this.collectInteractiveSprite(child, child); } } - else { + else + { child.__iParent = null; - if (child.children.length > 0) { + if (child.children.length > 0) + { this.collectInteractiveSprite(child, iParent); } } @@ -189,7 +196,8 @@ * @param [resolution=1] {number} THe resolution of the new element (relative to the canvas). * @private */ -InteractionManager.prototype.setTargetElement = function (element, resolution) { +InteractionManager.prototype.setTargetElement = function (element, resolution) +{ this.removeEvents(); this.interactionDOMElement = element; @@ -203,12 +211,15 @@ * * @private */ -InteractionManager.prototype.addEvents = function () { - if (!this.interactionDOMElement) { +InteractionManager.prototype.addEvents = function () +{ + if (!this.interactionDOMElement) + { return; } - if (window.navigator.msPointerEnabled) { + if (window.navigator.msPointerEnabled) + { this.interactionDOMElement.style['-ms-content-zooming'] = 'none'; this.interactionDOMElement.style['-ms-touch-action'] = 'none'; } @@ -230,12 +241,15 @@ * * @private */ -InteractionManager.prototype.removeEvents = function () { - if (!this.interactionDOMElement) { +InteractionManager.prototype.removeEvents = function () +{ + if (!this.interactionDOMElement) + { return; } - if (window.navigator.msPointerEnabled) { + if (window.navigator.msPointerEnabled) + { this.interactionDOMElement.style['-ms-content-zooming'] = ''; this.interactionDOMElement.style['-ms-touch-action'] = ''; } @@ -260,8 +274,10 @@ * * @private */ -InteractionManager.prototype.update = function () { - if (!this.interactionDOMElement) { +InteractionManager.prototype.update = function () +{ + if (!this.interactionDOMElement) + { return; } @@ -269,7 +285,8 @@ var now = Date.now(); var diff = now - this.last; diff = (diff * INTERACTION_FREQUENCY ) / 1000; - if (diff < 1) { + if (diff < 1) + { return; } @@ -280,7 +297,8 @@ // ok.. so mouse events?? // yes for now :) // OPTIMISE - how often to check?? - if (this.dirty) { + if (this.dirty) + { this.rebuildInteractiveGraph(); } @@ -289,7 +307,8 @@ var cursor = 'inherit'; var over = false; - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { var item = this.interactiveItems[i]; // OPTIMISATION - only calculate every time if the mousemove function exists.. @@ -302,26 +321,34 @@ this.mouse.target = item; // ok so deal with interactions.. // looks like there was a hit! - if (item.__hit && !over) { - if (item.buttonMode) { + if (item.__hit && !over) + { + if (item.buttonMode) + { cursor = item.defaultCursor; } - if (!item.interactiveChildren) { + if (!item.interactiveChildren) + { over = true; } - if (!item.__isOver) { - if (item.mouseover) { + if (!item.__isOver) + { + if (item.mouseover) + { item.mouseover (this.mouse); } item.__isOver = true; } } - else { - if (item.__isOver) { + else + { + if (item.__isOver) + { // roll out! - if (item.mouseout) { + if (item.mouseout) + { item.mouseout (this.mouse); } item.__isOver = false; @@ -329,7 +356,8 @@ } } - if (this.currentCursorStyle !== cursor) { + if (this.currentCursorStyle !== cursor) + { this.currentCursorStyle = cursor; this.interactionDOMElement.style.cursor = cursor; } @@ -338,18 +366,21 @@ /** * @private */ -InteractionManager.prototype.rebuildInteractiveGraph = function () { +InteractionManager.prototype.rebuildInteractiveGraph = function () +{ this.dirty = false; var len = this.interactiveItems.length; - for (var i = 0; i < len; i++) { + for (var i = 0; i < len; i++) + { this.interactiveItems[i].interactiveChildren = false; } this.interactiveItems.length = 0; - if (this.stage.interactive) { + if (this.stage.interactive) + { this.interactiveItems.push(this.stage); } @@ -363,8 +394,10 @@ * @param event {Event} The DOM event of the mouse moving * @private */ -InteractionManager.prototype.onMouseMove = function (event) { - if (this.dirty) { +InteractionManager.prototype.onMouseMove = function (event) +{ + if (this.dirty) + { this.rebuildInteractiveGraph(); } @@ -378,11 +411,13 @@ var length = this.interactiveItems.length; - for (var i = 0; i < length; i++) { + for (var i = 0; i < length; i++) + { var item = this.interactiveItems[i]; // Call the function! - if (item.mousemove) { + if (item.mousemove) + { item.mousemove(this.mouse); } } @@ -394,14 +429,17 @@ * @param event {Event} The DOM event of a mouse button being pressed down * @private */ -InteractionManager.prototype.onMouseDown = function (event) { - if (this.dirty) { +InteractionManager.prototype.onMouseDown = function (event) +{ + if (this.dirty) + { this.rebuildInteractiveGraph(); } this.mouse.originalEvent = event; - if (AUTO_PREVENT_DEFAULT) { + if (AUTO_PREVENT_DEFAULT) + { this.mouse.originalEvent.preventDefault(); } @@ -420,22 +458,27 @@ // while // hit test - for (var i = 0; i < length; i++) { + for (var i = 0; i < length; i++) + { var item = this.interactiveItems[i]; - if (item[downFunction] || item[clickFunction]) { + if (item[downFunction] || item[clickFunction]) + { item[buttonIsDown] = true; item.__hit = this.hitTest(item, this.mouse); - if (item.__hit) { + if (item.__hit) + { //call the function! - if (item[downFunction]) { + if (item[downFunction]) + { item[downFunction](this.mouse); } item[isDown] = true; // just the one! - if (!item.interactiveChildren) { + if (!item.interactiveChildren) + { break; } } @@ -449,8 +492,10 @@ * @param event {Event} The DOM event of a mouse being moved out * @private */ -InteractionManager.prototype.onMouseOut = function (event) { - if (this.dirty) { +InteractionManager.prototype.onMouseOut = function (event) +{ + if (this.dirty) + { this.rebuildInteractiveGraph(); } @@ -460,11 +505,14 @@ this.interactionDOMElement.style.cursor = 'inherit'; - for (var i = 0; i < length; i++) { + for (var i = 0; i < length; i++) + { var item = this.interactiveItems[i]; - if (item.__isOver) { + if (item.__isOver) + { this.mouse.target = item; - if (item.mouseout) { + if (item.mouseout) + { item.mouseout(this.mouse); } item.__isOver = false; @@ -484,8 +532,10 @@ * @param event {Event} The DOM event of a mouse button being released * @private */ -InteractionManager.prototype.onMouseUp = function (event) { - if (this.dirty) { +InteractionManager.prototype.onMouseUp = function (event) +{ + if (this.dirty) + { this.rebuildInteractiveGraph(); } @@ -502,30 +552,40 @@ var upOutsideFunction = isRightButton ? 'rightupoutside' : 'mouseupoutside'; var isDown = isRightButton ? '__isRightDown' : '__isDown'; - for (var i = 0; i < length; i++) { + for (var i = 0; i < length; i++) + { var item = this.interactiveItems[i]; - if (item[clickFunction] || item[upFunction] || item[upOutsideFunction]) { + if (item[clickFunction] || item[upFunction] || item[upOutsideFunction]) + { item.__hit = this.hitTest(item, this.mouse); - if (item.__hit && !up) { + if (item.__hit && !up) + { //call the function! - if (item[upFunction]) { + if (item[upFunction]) + { item[upFunction](this.mouse); } - if (item[isDown]) { - if (item[clickFunction]) { + if (item[isDown]) + { + if (item[clickFunction]) + { item[clickFunction](this.mouse); } } - if (!item.interactiveChildren) { + if (!item.interactiveChildren) + { up = true; } } - else { - if (item[isDown]) { - if (item[upOutsideFunction]) { + else + { + if (item[isDown]) + { + if (item[upOutsideFunction]) + { item[upOutsideFunction](this.mouse); } } @@ -543,10 +603,12 @@ * @param interactionData {InteractionData} The interactionData object to update in the case there is a hit * @private */ -InteractionManager.prototype.hitTest = function (item, interactionData) { +InteractionManager.prototype.hitTest = function (item, interactionData) +{ var global = interactionData.global; - if (!item.worldVisible) { + if (!item.worldVisible) + { return false; } @@ -560,37 +622,46 @@ interactionData.target = item; //a sprite or display object with a hit area defined - if (item.hitArea && item.hitArea.contains) { + if (item.hitArea && item.hitArea.contains) + { return item.hitArea.contains(x, y); } // a sprite with no hitarea defined - else if (item instanceof core.Sprite) { + else if (item instanceof core.Sprite) + { var width = item.texture.frame.width; var height = item.texture.frame.height; var x1 = -width * item.anchor.x; var y1; - if (x > x1 && x < x1 + width) { + if (x > x1 && x < x1 + width) + { y1 = -height * item.anchor.y; - if (y > y1 && y < y1 + height) { + if (y > y1 && y < y1 + height) + { // set the target property if a hit is true! return true; } } } - else if (item instanceof core.Graphics) { + else if (item instanceof core.Graphics) + { var graphicsData = item.graphicsData; - for (i = 0; i < graphicsData.length; i++) { + for (i = 0; i < graphicsData.length; i++) + { var data = graphicsData[i]; - if (!data.fill) { + if (!data.fill) + { continue; } // only deal with fills.. - if (data.shape) { - if (data.shape.contains(x, y)) { + if (data.shape) + { + if (data.shape.contains(x, y)) + { //interactionData.target = item; return true; } @@ -600,10 +671,12 @@ var length = item.children.length; - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { var tempItem = item.children[i]; var hit = this.hitTest(tempItem, interactionData); - if (hit) { + if (hit) + { // hmm.. TODO SET CORRECT TARGET? interactionData.target = item; return true; @@ -618,8 +691,10 @@ * @param event {Event} The DOM event of a touch moving across the renderer view * @private */ -InteractionManager.prototype.onTouchMove = function (event) { - if (this.dirty) { +InteractionManager.prototype.onTouchMove = function (event) +{ + if (this.dirty) + { this.rebuildInteractiveGraph(); } @@ -628,7 +703,8 @@ var touchData; var i = 0; - for (i = 0; i < changedTouches.length; i++) { + for (i = 0; i < changedTouches.length; i++) + { var touchEvent = changedTouches[i]; touchData = this.touches[touchEvent.identifier]; touchData.originalEvent = event; @@ -636,15 +712,18 @@ // update the touch position touchData.global.x = ( (touchEvent.clientX - rect.left) * (this.interactionDOMElement.width / rect.width) ) / this.resolution; touchData.global.y = ( (touchEvent.clientY - rect.top) * (this.interactionDOMElement.height / rect.height) ) / this.resolution; - if (navigator.isCocoonJS && !rect.left && !rect.top && !event.target.style.width && !event.target.style.height) { + if (navigator.isCocoonJS && !rect.left && !rect.top && !event.target.style.width && !event.target.style.height) + { //Support for CocoonJS fullscreen scale modes touchData.global.x = touchEvent.clientX; touchData.global.y = touchEvent.clientY; } - for (var j = 0; j < this.interactiveItems.length; j++) { + for (var j = 0; j < this.interactiveItems.length; j++) + { var item = this.interactiveItems[j]; - if (item.touchmove && item.__touchData && item.__touchData[touchEvent.identifier]) { + if (item.touchmove && item.__touchData && item.__touchData[touchEvent.identifier]) + { item.touchmove(touchData); } } @@ -657,23 +736,28 @@ * @param event {Event} The DOM event of a touch starting on the renderer view * @private */ -InteractionManager.prototype.onTouchStart = function (event) { - if (this.dirty) { +InteractionManager.prototype.onTouchStart = function (event) +{ + if (this.dirty) + { this.rebuildInteractiveGraph(); } var rect = this.interactionDOMElement.getBoundingClientRect(); - if (AUTO_PREVENT_DEFAULT) { + if (AUTO_PREVENT_DEFAULT) + { event.preventDefault(); } var changedTouches = event.changedTouches; - for (var i=0; i < changedTouches.length; i++) { + for (var i=0; i < changedTouches.length; i++) + { var touchEvent = changedTouches[i]; var touchData = this.pool.pop(); - if (!touchData) { + if (!touchData) + { touchData = new InteractionData(); } @@ -682,7 +766,8 @@ this.touches[touchEvent.identifier] = touchData; touchData.global.x = ( (touchEvent.clientX - rect.left) * (this.interactionDOMElement.width / rect.width) ) / this.resolution; touchData.global.y = ( (touchEvent.clientY - rect.top) * (this.interactionDOMElement.height / rect.height) ) / this.resolution; - if (navigator.isCocoonJS && !rect.left && !rect.top && !event.target.style.width && !event.target.style.height) { + if (navigator.isCocoonJS && !rect.left && !rect.top && !event.target.style.width && !event.target.style.height) + { //Support for CocoonJS fullscreen scale modes touchData.global.x = touchEvent.clientX; touchData.global.y = touchEvent.clientY; @@ -690,15 +775,19 @@ var length = this.interactiveItems.length; - for (var j = 0; j < length; j++) { + for (var j = 0; j < length; j++) + { var item = this.interactiveItems[j]; - if (item.touchstart || item.tap) { + if (item.touchstart || item.tap) + { item.__hit = this.hitTest(item, touchData); - if (item.__hit) { + if (item.__hit) + { //call the function! - if (item.touchstart) { + if (item.touchstart) + { item.touchstart(touchData); } @@ -706,7 +795,8 @@ item.__touchData = item.__touchData || {}; item.__touchData[touchEvent.identifier] = touchData; - if (!item.interactiveChildren) { + if (!item.interactiveChildren) + { break; } } @@ -721,31 +811,37 @@ * @param event {Event} The DOM event of a touch ending on the renderer view * @private */ -InteractionManager.prototype.onTouchEnd = function (event) { - if (this.dirty) { +InteractionManager.prototype.onTouchEnd = function (event) +{ + if (this.dirty) + { this.rebuildInteractiveGraph(); } var rect = this.interactionDOMElement.getBoundingClientRect(); var changedTouches = event.changedTouches; - for (var i=0; i < changedTouches.length; i++) { + for (var i=0; i < changedTouches.length; i++) + { var touchEvent = changedTouches[i]; var touchData = this.touches[touchEvent.identifier]; var up = false; touchData.global.x = ( (touchEvent.clientX - rect.left) * (this.interactionDOMElement.width / rect.width) ) / this.resolution; touchData.global.y = ( (touchEvent.clientY - rect.top) * (this.interactionDOMElement.height / rect.height) ) / this.resolution; - if (navigator.isCocoonJS && !rect.left && !rect.top && !event.target.style.width && !event.target.style.height) { + if (navigator.isCocoonJS && !rect.left && !rect.top && !event.target.style.width && !event.target.style.height) + { //Support for CocoonJS fullscreen scale modes touchData.global.x = touchEvent.clientX; touchData.global.y = touchEvent.clientY; } var length = this.interactiveItems.length; - for (var j = 0; j < length; j++) { + for (var j = 0; j < length; j++) + { var item = this.interactiveItems[j]; - if (item.__touchData && item.__touchData[touchEvent.identifier]) { + if (item.__touchData && item.__touchData[touchEvent.identifier]) + { item.__hit = this.hitTest(item, item.__touchData[touchEvent.identifier]); @@ -753,20 +849,27 @@ touchData.originalEvent = event; // hitTest?? - if (item.touchend || item.tap) { - if (item.__hit && !up) { - if (item.touchend) { + if (item.touchend || item.tap) + { + if (item.__hit && !up) + { + if (item.touchend) + { item.touchend(touchData); } - if (item.__isDown && item.tap) { + if (item.__isDown && item.tap) + { item.tap(touchData); } - if (!item.interactiveChildren) { + if (!item.interactiveChildren) + { up = true; } } - else { - if (item.__isDown && item.touchendoutside) { + else + { + if (item.__isDown && item.touchendoutside) + { item.touchendoutside(touchData); } } diff --git a/src/loaders/AssetLoader.js b/src/loaders/AssetLoader.js index 20da0cf..c4dba1c 100644 --- a/src/loaders/AssetLoader.js +++ b/src/loaders/AssetLoader.js @@ -21,7 +21,8 @@ * data formats include 'xml' and 'fnt'. * @param crossorigin {boolean} Whether requests should be treated as crossorigin */ -function AssetLoader(assetURLs, crossorigin) { +function AssetLoader(assetURLs, crossorigin) +{ /** * The array of asset URLs that are going to be loaded * @@ -76,16 +77,19 @@ * * @param str {string} the name of the asset */ -AssetLoader.prototype._getDataType = function (str) { +AssetLoader.prototype._getDataType = function (str) +{ var test = 'data:'; var start = str.slice(0, test.length).toLowerCase(); - if (start === test) { + if (start === test) + { var data = str.slice(test.length); var sepIdx = data.indexOf(','); // check for malformed data URI scheme - if (sepIdx === -1) { + if (sepIdx === -1) + { return null; } @@ -94,7 +98,8 @@ //We might need to handle some special cases here... //standardize text/plain to 'txt' file extension - if (!info || info.toLowerCase() === 'text/plain') { + if (!info || info.toLowerCase() === 'text/plain') + { return 'txt'; } @@ -109,27 +114,32 @@ * Starts loading the assets sequentially * */ -AssetLoader.prototype.load = function () { +AssetLoader.prototype.load = function () +{ var scope = this; - function onLoad(evt) { + function onLoad(evt) + { scope.onAssetLoaded(evt.data.content); } this.loadCount = this.assetURLs.length; - for (var i=0; i < this.assetURLs.length; i++) { + for (var i=0; i < this.assetURLs.length; i++) + { var fileName = this.assetURLs[i]; //first see if we have a data URI scheme.. var fileType = this._getDataType(fileName); //if not, assume it's a file URI - if (!fileType) { + if (!fileType) + { fileType = fileName.split('?').shift().split('.').pop().toLowerCase(); } var Constructor = this.loadersByType[fileType]; - if (!Constructor) { + if (!Constructor) + { throw new Error(fileType + ' is an unsupported file type'); } @@ -145,18 +155,22 @@ * * @private */ -AssetLoader.prototype.onAssetLoaded = function (loader) { +AssetLoader.prototype.onAssetLoaded = function (loader) +{ this.loadCount--; this.emit('onProgress', { content: this, loader: loader }); - if (this.onProgress) { + if (this.onProgress) + { this.onProgress(loader); } - if (!this.loadCount) { + if (!this.loadCount) + { this.emit('onComplete', { content: this }); - if (this.onComplete) { + if (this.onComplete) + { this.onComplete(); } } diff --git a/src/loaders/AtlasLoader.js b/src/loaders/AtlasLoader.js index 5eda286..3aec9e2 100644 --- a/src/loaders/AtlasLoader.js +++ b/src/loaders/AtlasLoader.js @@ -15,7 +15,8 @@ * @param url {String} The url of the JSON file * @param crossorigin {boolean} Whether requests should be treated as crossorigin */ -function AtlasLoader(url, crossorigin) { +function AtlasLoader(url, crossorigin) +{ this.url = url; this.baseUrl = url.replace(/[^\/]*$/, ''); this.crossorigin = crossorigin; @@ -31,13 +32,15 @@ * Starts loading the JSON file * */ -AtlasLoader.prototype.load = function () { +AtlasLoader.prototype.load = function () +{ this.ajaxRequest = new core.utils.AjaxRequest(); this.ajaxRequest.onreadystatechange = this.onAtlasLoaded.bind(this); this.ajaxRequest.open('GET', this.url, true); - if (this.ajaxRequest.overrideMimeType) { + if (this.ajaxRequest.overrideMimeType) + { this.ajaxRequest.overrideMimeType('application/json'); } @@ -49,9 +52,12 @@ * * @private */ -AtlasLoader.prototype.onAtlasLoaded = function () { - if (this.ajaxRequest.readyState === 4) { - if (this.ajaxRequest.status === 200 || window.location.href.indexOf('http') === -1) { +AtlasLoader.prototype.onAtlasLoaded = function () +{ + if (this.ajaxRequest.readyState === 4) + { + if (this.ajaxRequest.status === 200 || window.location.href.indexOf('http') === -1) + { this.atlas = { meta : { image : [] @@ -70,34 +76,44 @@ selfOnLoaded = this.onLoaded.bind(this); // parser without rotation support yet! - for (i = 0; i < result.length; i++) { + for (i = 0; i < result.length; i++) + { result[i] = result[i].replace(/^\s+|\s+$/g, ''); - if (result[i] === '') { + if (result[i] === '') + { nameInNextLine = i+1; } - if (result[i].length > 0) { - if (nameInNextLine === i) { + if (result[i].length > 0) + { + if (nameInNextLine === i) + { this.atlas.meta.image.push(result[i]); currentImageId = this.atlas.meta.image.length - 1; this.atlas.frames.push({}); lineCount = -3; - } else if (lineCount > 0) { - if (lineCount % 7 === 1) { // frame name - if (currentFrame != null) { //jshint ignore:line + } else if (lineCount > 0) + { + if (lineCount % 7 === 1) + { // frame name + if (currentFrame != null) + { //jshint ignore:line this.atlas.frames[currentImageId][currentFrame.name] = currentFrame; } currentFrame = { name: result[i], frame : {} }; } else { var text = result[i].split(' '); - if (lineCount % 7 === 3) { // position + if (lineCount % 7 === 3) + { // position currentFrame.frame.x = Number(text[1].replace(',', '')); currentFrame.frame.y = Number(text[2]); - } else if (lineCount % 7 === 4) { // size + } else if (lineCount % 7 === 4) + { // size currentFrame.frame.w = Number(text[1].replace(',', '')); currentFrame.frame.h = Number(text[2]); - } else if (lineCount % 7 === 5) { // real size + } else if (lineCount % 7 === 5) + { // real size var realSize = { x : 0, y : 0, @@ -105,7 +121,8 @@ h : Number(text[2]) }; - if (realSize.w > currentFrame.frame.w || realSize.h > currentFrame.frame.h) { + if (realSize.w > currentFrame.frame.w || realSize.h > currentFrame.frame.h) + { currentFrame.trimmed = true; currentFrame.realSize = realSize; } else { @@ -118,28 +135,34 @@ } } - if (currentFrame != null) { //jshint ignore:line + if (currentFrame != null) + { //jshint ignore:line this.atlas.frames[currentImageId][currentFrame.name] = currentFrame; } - if (this.atlas.meta.image.length > 0) { + if (this.atlas.meta.image.length > 0) + { this.images = []; - for (j = 0; j < this.atlas.meta.image.length; j++) { + for (j = 0; j < this.atlas.meta.image.length; j++) + { // sprite sheet var textureUrl = this.baseUrl + this.atlas.meta.image[j]; var frameData = this.atlas.frames[j]; this.images.push(new ImageLoader(textureUrl, this.crossorigin)); - for (i in frameData) { + for (i in frameData) + { var rect = frameData[i].frame; - if (rect) { + if (rect) + { core.utils.TextureCache[i] = new core.Texture(this.images[j].texture.baseTexture, { x: rect.x, y: rect.y, width: rect.w, height: rect.h }); - if (frameData[i].trimmed) { + if (frameData[i].trimmed) + { core.utils.TextureCache[i].realSize = frameData[i].realSize; // trim in pixi not supported yet, todo update trim properties if it is done ... core.utils.TextureCache[i].trim.x = 0; @@ -150,7 +173,8 @@ } this.currentImageId = 0; - for (j = 0; j < this.images.length; j++) { + for (j = 0; j < this.images.length; j++) + { this.images[j].on('loaded', selfOnLoaded); } this.images[this.currentImageId].load(); @@ -170,8 +194,10 @@ * * @private */ -AtlasLoader.prototype.onLoaded = function () { - if (this.images.length - 1 > this.currentImageId) { +AtlasLoader.prototype.onLoaded = function () +{ + if (this.images.length - 1 > this.currentImageId) + { this.currentImageId++; this.images[this.currentImageId].load(); } else { @@ -185,6 +211,7 @@ * * @private */ -AtlasLoader.prototype.onError = function () { +AtlasLoader.prototype.onError = function () +{ this.emit('error', { content: this }); }; diff --git a/src/loaders/BitmapFontLoader.js b/src/loaders/BitmapFontLoader.js index 8641760..13e5c1b 100644 --- a/src/loaders/BitmapFontLoader.js +++ b/src/loaders/BitmapFontLoader.js @@ -13,7 +13,8 @@ * @param url {String} The url of the sprite sheet JSON file * @param crossorigin {boolean} Whether requests should be treated as crossorigin */ -function BitmapFontLoader(url, crossorigin) { +function BitmapFontLoader(url, crossorigin) +{ /** * The url of the bitmap font data * @@ -54,13 +55,15 @@ * Loads the XML font data * */ -BitmapFontLoader.prototype.load = function () { +BitmapFontLoader.prototype.load = function () +{ this.ajaxRequest = new core.utils.AjaxRequest(); this.ajaxRequest.onreadystatechange = this.onXMLLoaded.bind(this); this.ajaxRequest.open('GET', this.url, true); - if (this.ajaxRequest.overrideMimeType) { + if (this.ajaxRequest.overrideMimeType) + { this.ajaxRequest.overrideMimeType('application/xml'); } @@ -72,12 +75,17 @@ * * @private */ -BitmapFontLoader.prototype.onXMLLoaded = function () { - if (this.ajaxRequest.readyState === 4) { - if (this.ajaxRequest.status === 200 || window.location.protocol.indexOf('http') === -1) { +BitmapFontLoader.prototype.onXMLLoaded = function () +{ + if (this.ajaxRequest.readyState === 4) + { + if (this.ajaxRequest.status === 200 || window.location.protocol.indexOf('http') === -1) + { var responseXML = this.ajaxRequest.responseXML; - if (!responseXML || /MSIE 9/i.test(navigator.userAgent) || navigator.isCocoonJS) { - if (typeof(window.DOMParser) === 'function') { + if (!responseXML || /MSIE 9/i.test(navigator.userAgent) || navigator.isCocoonJS) + { + if (typeof(window.DOMParser) === 'function') + { var domparser = new DOMParser(); responseXML = domparser.parseFromString(this.ajaxRequest.responseText, 'text/xml'); } else { @@ -102,7 +110,8 @@ //parse letters var letters = responseXML.getElementsByTagName('char'); - for (var i = 0; i < letters.length; i++) { + for (var i = 0; i < letters.length; i++) + { var charCode = parseInt(letters[i].getAttribute('id'), 10); var textureRect = new core.math.Rectangle( @@ -124,7 +133,8 @@ //parse kernings var kernings = responseXML.getElementsByTagName('kerning'); - for (i = 0; i < kernings.length; i++) { + for (i = 0; i < kernings.length; i++) + { var first = parseInt(kernings[i].getAttribute('first'), 10); var second = parseInt(kernings[i].getAttribute('second'), 10); var amount = parseInt(kernings[i].getAttribute('amount'), 10); @@ -146,6 +156,7 @@ * * @private */ -BitmapFontLoader.prototype.onLoaded = function () { +BitmapFontLoader.prototype.onLoaded = function () +{ this.emit('loaded', { content: this }); }; diff --git a/src/loaders/ImageLoader.js b/src/loaders/ImageLoader.js index e3ff493..16ee7c8 100644 --- a/src/loaders/ImageLoader.js +++ b/src/loaders/ImageLoader.js @@ -11,7 +11,8 @@ * @param url {String} The url of the image * @param crossorigin {boolean} Whether requests should be treated as crossorigin */ -function ImageLoader(url, crossorigin) { +function ImageLoader(url, crossorigin) +{ /** * The texture being loaded * @@ -39,12 +40,15 @@ * Loads image or takes it from cache * */ -ImageLoader.prototype.load = function () { - if (!this.texture.baseTexture.hasLoaded) { +ImageLoader.prototype.load = function () +{ + if (!this.texture.baseTexture.hasLoaded) + { this.texture.baseTexture.on('loaded', this.onLoaded.bind(this)); this.texture.baseTexture.on('error', this.onError.bind(this)); } - else { + else + { this.onLoaded(); } }; @@ -54,7 +58,8 @@ * * @private */ -ImageLoader.prototype.onLoaded = function () { +ImageLoader.prototype.onLoaded = function () +{ this.emit('loaded', { content: this }); }; @@ -64,7 +69,8 @@ * @method onError * @private */ -ImageLoader.prototype.onError = function () { +ImageLoader.prototype.onError = function () +{ this.emit('error', { content: this }); }; @@ -75,15 +81,18 @@ * @param frameHeight {number} height of each frame * @param textureName {String} if given, the frames will be cached in - format */ -ImageLoader.prototype.loadFramedSpriteSheet = function (frameWidth, frameHeight, textureName) { +ImageLoader.prototype.loadFramedSpriteSheet = function (frameWidth, frameHeight, textureName) +{ this.frames = []; var cols = Math.floor(this.texture.width / frameWidth); var rows = Math.floor(this.texture.height / frameHeight); var i=0; - for (var y = 0; y < rows; ++y) { - for (var x = 0; x < cols; ++x, ++i) { + for (var y = 0; y < rows; ++y) + { + for (var x = 0; x < cols; ++x, ++i) + { var texture = new core.Texture( this.texture.baseTexture, new core.math.Rectangle( @@ -96,7 +105,8 @@ this.frames.push(texture); - if (textureName) { + if (textureName) + { core.utils.TextureCache[textureName + '-' + i] = texture; } } diff --git a/src/loaders/JsonLoader.js b/src/loaders/JsonLoader.js index 3279f40..7aabeb4 100644 --- a/src/loaders/JsonLoader.js +++ b/src/loaders/JsonLoader.js @@ -14,7 +14,8 @@ * @param url {String} The url of the JSON file * @param crossorigin {boolean} Whether requests should be treated as crossorigin */ -function JsonLoader(url, crossorigin) { +function JsonLoader(url, crossorigin) +{ /** * The url of the bitmap font data * @@ -56,8 +57,10 @@ * Loads the JSON data * */ -JsonLoader.prototype.load = function () { - if (window.XDomainRequest && this.crossorigin) { +JsonLoader.prototype.load = function () +{ + if (window.XDomainRequest && this.crossorigin) + { this.ajaxRequest = new window.XDomainRequest(); // XDomainRequest has a few quirks. Occasionally it will abort requests @@ -68,15 +71,19 @@ this.ajaxRequest.onerror = this.onError.bind(this); this.ajaxRequest.ontimeout = this.onError.bind(this); - this.ajaxRequest.onprogress = function () {}; + this.ajaxRequest.onprogress = function () + {}; this.ajaxRequest.onload = this.onJSONLoaded.bind(this); } - else { - if (window.XMLHttpRequest) { + else + { + if (window.XMLHttpRequest) + { this.ajaxRequest = new window.XMLHttpRequest(); } - else { + else + { this.ajaxRequest = new window.ActiveXObject('Microsoft.XMLHTTP'); } @@ -93,8 +100,10 @@ * * @private */ -JsonLoader.prototype.onReadyStateChanged = function () { - if (this.ajaxRequest.readyState === 4 && (this.ajaxRequest.status === 200 || window.location.href.indexOf('http') === -1)) { +JsonLoader.prototype.onReadyStateChanged = function () +{ + if (this.ajaxRequest.readyState === 4 && (this.ajaxRequest.status === 200 || window.location.href.indexOf('http') === -1)) + { this.onJSONLoaded(); } }; @@ -104,15 +113,18 @@ * * @private */ -JsonLoader.prototype.onJSONLoaded = function () { - if (!this.ajaxRequest.responseText) { +JsonLoader.prototype.onJSONLoaded = function () +{ + if (!this.ajaxRequest.responseText) + { this.onError(); return; } this.json = JSON.parse(this.ajaxRequest.responseText); - if (this.json.frames) { + if (this.json.frames) + { // sprite sheet var textureUrl = this.baseUrl + this.json.meta.image; var image = new ImageLoader(textureUrl, this.crossorigin); @@ -122,16 +134,19 @@ image.addEventListener('loaded', this.onLoaded.bind(this)); image.addEventListener('error', this.onError.bind(this)); - for (var i in frameData) { + for (var i in frameData) + { var rect = frameData[i].frame; - if (rect) { + if (rect) + { var textureSize = new core.math.Rectangle(rect.x, rect.y, rect.w, rect.h); var crop = textureSize.clone(); var trim = null; // Check to see if the sprite is trimmed - if (frameData[i].trimmed) { + if (frameData[i].trimmed) + { var actualSize = frameData[i].sourceSize; var realSize = frameData[i].spriteSourceSize; trim = new core.math.Rectangle(realSize.x, realSize.y, actualSize.w, actualSize.h); @@ -143,12 +158,15 @@ image.load(); } - else if (this.json.bones) { + else if (this.json.bones) + { // check if the json was loaded before - if (core.utils.AnimCache[this.url]) { + if (core.utils.AnimCache[this.url]) + { this.onLoaded(); } - else { + else + { /** * use a bit of hackery to load the atlas file, here we assume that the .json, .atlas and .png files * that correspond to the spine file are in the same base URL and that the .json and .atlas files @@ -159,9 +177,11 @@ // save a copy of the current object for future reference // var originalLoader = this; // before loading the file, replace the "onJSONLoaded" function for our own // - atlasLoader.onJSONLoaded = function () { + atlasLoader.onJSONLoaded = function () + { // at this point "this" points at the atlasLoader (JsonLoader) instance // - if (!this.ajaxRequest.responseText) { + if (!this.ajaxRequest.responseText) + { this.onError(); // FIXME: hmm, this is funny because we are not responding to errors yet return; } @@ -179,14 +199,18 @@ originalLoader.spineAtlas = spineAtlas; originalLoader.spineAtlasLoader = atlasLoader; // wait for textures to finish loading if needed - if (textureLoader.loadingCount > 0) { - textureLoader.addEventListener('loadedBaseTexture', function (evt){ - if (evt.content.content.loadingCount <= 0) { + if (textureLoader.loadingCount > 0) + { + textureLoader.addEventListener('loadedBaseTexture', function (evt) + { + if (evt.content.content.loadingCount <= 0) + { originalLoader.onLoaded(); } }); } - else { + else + { originalLoader.onLoaded(); } }; @@ -194,7 +218,8 @@ atlasLoader.load(); } } - else { + else + { this.onLoaded(); } }; @@ -204,7 +229,8 @@ * * @private */ -JsonLoader.prototype.onLoaded = function () { +JsonLoader.prototype.onLoaded = function () +{ this.loaded = true; this.dispatchEvent({ type: 'loaded', @@ -217,7 +243,8 @@ * * @private */ -JsonLoader.prototype.onError = function () { +JsonLoader.prototype.onError = function () +{ this.dispatchEvent({ type: 'error', diff --git a/src/loaders/SpineLoader.js b/src/loaders/SpineLoader.js index 51aaddb..69bae21 100644 --- a/src/loaders/SpineLoader.js +++ b/src/loaders/SpineLoader.js @@ -24,7 +24,8 @@ * @param url {String} The url of the JSON file * @param crossorigin {boolean} Whether requests should be treated as crossorigin */ -function SpineLoader(url, crossorigin) { +function SpineLoader(url, crossorigin) +{ /** * The url of the bitmap font data * @@ -57,11 +58,13 @@ * Loads the JSON data * */ -SpineLoader.prototype.load = function () { +SpineLoader.prototype.load = function () +{ var scope = this; var jsonLoader = new JsonLoader(this.url, this.crossorigin); - jsonLoader.on('loaded', function (event) { + jsonLoader.on('loaded', function (event) + { scope.json = event.data.content.json; scope.onLoaded(); }); @@ -74,7 +77,8 @@ * * @private */ -SpineLoader.prototype.onLoaded = function () { +SpineLoader.prototype.onLoaded = function () +{ this.loaded = true; this.emit('loaded', { content: this }); }; diff --git a/src/loaders/SpineTextureLoader.js b/src/loaders/SpineTextureLoader.js index 61c51c0..c09a548 100644 --- a/src/loaders/SpineTextureLoader.js +++ b/src/loaders/SpineTextureLoader.js @@ -9,7 +9,8 @@ * @param basePath {string} Tha base path where to look for the images to be loaded * @param crossorigin {boolean} Whether requests should be treated as crossorigin */ -function SpineTextureLoader(basePath, crossorigin) { +function SpineTextureLoader(basePath, crossorigin) +{ this.basePath = basePath; this.crossorigin = crossorigin; this.loadingCount = 0; @@ -26,12 +27,15 @@ * @param page {spine.AtlasPage} Atlas page to which texture belongs * @param file {string} The file to load, this is just the file path relative to the base path configured in the constructor */ -SpineTextureLoader.prototype.load = function (page, file) { +SpineTextureLoader.prototype.load = function (page, file) +{ page.rendererObject = core.BaseTexture.fromImage(this.basePath + '/' + file, this.crossorigin); - if (!page.rendererObject.hasLoaded) { + if (!page.rendererObject.hasLoaded) + { var scope = this; ++scope.loadingCount; - page.rendererObject.addEventListener('loaded', function (){ + page.rendererObject.addEventListener('loaded', function () + { --scope.loadingCount; scope.dispatchEvent({ type: 'loadedBaseTexture', @@ -46,6 +50,7 @@ * * @param texture {BaseTexture} Texture object to destroy */ -SpineTextureLoader.prototype.unload = function (texture) { +SpineTextureLoader.prototype.unload = function (texture) +{ texture.destroy(true); }; diff --git a/src/loaders/SpriteSheetLoader.js b/src/loaders/SpriteSheetLoader.js index 5ee79df..a554e9d 100644 --- a/src/loaders/SpriteSheetLoader.js +++ b/src/loaders/SpriteSheetLoader.js @@ -16,7 +16,8 @@ * @param url {String} The url of the sprite sheet JSON file * @param crossorigin {boolean} Whether requests should be treated as crossorigin */ -function SpriteSheetLoader(url, crossorigin) { +function SpriteSheetLoader(url, crossorigin) +{ /** * The url of the atlas data @@ -65,11 +66,13 @@ * This will begin loading the JSON file * */ -SpriteSheetLoader.prototype.load = function () { +SpriteSheetLoader.prototype.load = function () +{ var scope = this; var jsonLoader = new JsonLoader(this.url, this.crossorigin); - jsonLoader.on('loaded', function (event) { + jsonLoader.on('loaded', function (event) + { scope.json = event.data.content.json; scope.onLoaded(); }); @@ -82,7 +85,8 @@ * * @private */ -SpriteSheetLoader.prototype.onLoaded = function () { +SpriteSheetLoader.prototype.onLoaded = function () +{ this.emit('loaded', { content: this }); diff --git a/src/spine/Spine.js b/src/spine/Spine.js index be7ad18..ce425cc 100644 --- a/src/spine/Spine.js +++ b/src/spine/Spine.js @@ -15,12 +15,14 @@ * @namespace PIXI * @param url {string} The url of the spine anim file to be used */ -function Spine(url) { +function Spine(url) +{ core.DisplayObjectContainer.call(this); this.spineData = core.utils.AnimCache[url]; - if (!this.spineData) { + if (!this.spineData) + { throw new Error('Spine data must be preloaded using SpineLoader or AssetLoader: ' + url); } @@ -32,27 +34,31 @@ this.slotContainers = []; - for (var i = 0, n = this.skeleton.drawOrder.length; i < n; i++) { + for (var i = 0, n = this.skeleton.drawOrder.length; i < n; i++) + { var slot = this.skeleton.drawOrder[i]; var attachment = slot.attachment; var slotContainer = new core.DisplayObjectContainer(); this.slotContainers.push(slotContainer); this.addChild(slotContainer); - if (attachment instanceof spine.RegionAttachment) { + if (attachment instanceof spine.RegionAttachment) + { var spriteName = attachment.rendererObject.name; var sprite = this.createSprite(slot, attachment); slot.currentSprite = sprite; slot.currentSpriteName = spriteName; slotContainer.addChild(sprite); } - else if (attachment instanceof spine.MeshAttachment) { + else if (attachment instanceof spine.MeshAttachment) + { var mesh = this.createMesh(slot, attachment); slot.currentMesh = mesh; slot.currentMeshName = attachment.name; slotContainer.addChild(mesh); } - else { + else + { continue; } @@ -78,11 +84,13 @@ * @default true */ autoUpdate: { - get: function () { + get: function () + { return (this.updateTransform === Spine.prototype.autoUpdateTransform); }, - set: function (value) { + set: function (value) + { this.updateTransform = value ? Spine.prototype.autoUpdateTransform : core.DisplayObjectContainer.prototype.updateTransform; } } @@ -93,35 +101,44 @@ * * @param dt {number} Delta time. Time by which the animation should be updated */ -Spine.prototype.update = function (dt) { +Spine.prototype.update = function (dt) +{ this.state.update(dt); this.state.apply(this.skeleton); this.skeleton.updateWorldTransform(); var drawOrder = this.skeleton.drawOrder; - for (var i = 0, n = drawOrder.length; i < n; i++) { + for (var i = 0, n = drawOrder.length; i < n; i++) + { var slot = drawOrder[i]; var attachment = slot.attachment; var slotContainer = this.slotContainers[i]; - if (!attachment) { + if (!attachment) + { slotContainer.visible = false; continue; } var type = attachment.type; - if (type === spine.AttachmentType.region) { - if (attachment.rendererObject) { - if (!slot.currentSpriteName || slot.currentSpriteName !== attachment.rendererObject.name) { + if (type === spine.AttachmentType.region) + { + if (attachment.rendererObject) + { + if (!slot.currentSpriteName || slot.currentSpriteName !== attachment.rendererObject.name) + { var spriteName = attachment.rendererObject.name; - if (slot.currentSprite !== undefined) { + if (slot.currentSprite !== undefined) + { slot.currentSprite.visible = false; } slot.sprites = slot.sprites || {}; - if (slot.sprites[spriteName] !== undefined) { + if (slot.sprites[spriteName] !== undefined) + { slot.sprites[spriteName].visible = true; } - else { + else + { var sprite = this.createSprite(slot, attachment); slotContainer.addChild(sprite); } @@ -141,19 +158,24 @@ slot.currentSprite.tint = core.utils.rgb2hex([slot.r,slot.g,slot.b]); } - else if (type === spine.AttachmentType.skinnedmesh) { - if (!slot.currentMeshName || slot.currentMeshName !== attachment.name) { + else if (type === spine.AttachmentType.skinnedmesh) + { + if (!slot.currentMeshName || slot.currentMeshName !== attachment.name) + { var meshName = attachment.name; - if (slot.currentMesh !== undefined) { + if (slot.currentMesh !== undefined) + { slot.currentMesh.visible = false; } slot.meshes = slot.meshes || {}; - if (slot.meshes[meshName] !== undefined) { + if (slot.meshes[meshName] !== undefined) + { slot.meshes[meshName].visible = true; } - else { + else + { var mesh = this.createMesh(slot, attachment); slotContainer.addChild(mesh); } @@ -165,7 +187,8 @@ attachment.computeWorldVertices(slot.bone.skeleton.x, slot.bone.skeleton.y, slot, slot.currentMesh.vertices); } - else { + else + { slotContainer.visible = false; continue; } @@ -180,7 +203,8 @@ * * @private */ -Spine.prototype.autoUpdateTransform = function () { +Spine.prototype.autoUpdateTransform = function () +{ this.lastTime = this.lastTime || Date.now(); var timeDelta = (Date.now() - this.lastTime) * 0.001; this.lastTime = Date.now(); @@ -197,7 +221,8 @@ * @param attachment {spine.RegionAttachment} The attachment that the sprite will represent * @private */ -Spine.prototype.createSprite = function (slot, attachment) { +Spine.prototype.createSprite = function (slot, attachment) +{ var descriptor = attachment.rendererObject; var baseTexture = descriptor.page.rendererObject; var spriteRect = new core.math.Rectangle(descriptor.x, @@ -223,7 +248,8 @@ * @param attachment {spine.RegionAttachment} The attachment that the sprite will represent * @private */ -Spine.prototype.createMesh = function (slot, attachment) { +Spine.prototype.createMesh = function (slot, attachment) +{ var descriptor = attachment.rendererObject; var baseTexture = descriptor.page.rendererObject; var texture = new core.Texture(baseTexture); diff --git a/src/core/display/DisplayObject.js b/src/core/display/DisplayObject.js index 66ebc3c..20e778c 100644 --- a/src/core/display/DisplayObject.js +++ b/src/core/display/DisplayObject.js @@ -7,7 +7,8 @@ * @class * @namespace PIXI */ -function DisplayObject() { +function DisplayObject() +{ /** * The coordinate of the object relative to the local coordinates of the parent. * @@ -152,10 +153,12 @@ * @memberof DisplayObject# */ x: { - get: function () { + get: function () + { return this.position.x; }, - set: function (value) { + set: function (value) + { this.position.x = value; } }, @@ -167,10 +170,12 @@ * @memberof DisplayObject# */ y: { - get: function () { + get: function () + { return this.position.y; }, - set: function (value) { + set: function (value) + { this.position.y = value; } }, @@ -183,11 +188,13 @@ * @readonly */ worldVisible: { - get: function () { + get: function () + { var item = this; do { - if (!item.visible) { + if (!item.visible) + { return false; } @@ -207,17 +214,21 @@ * @memberof DisplayObject# */ mask: { - get: function () { + get: function () + { return this._mask; }, - set: function (value) { - if (this._mask) { + set: function (value) + { + if (this._mask) + { this._mask.isMask = false; } this._mask = value; - if (this._mask) { + if (this._mask) + { this._mask.isMask = true; } } @@ -232,18 +243,23 @@ * @memberof DisplayObject# */ filters: { - get: function () { + get: function () + { return this._filters; }, - set: function (value) { - if (value) { + set: function (value) + { + if (value) + { // now put all the passes in one place.. var passes = []; - for (var i = 0; i < value.length; i++) { + for (var i = 0; i < value.length; i++) + { var filterPasses = value[i].passes; - for (var j = 0; j < filterPasses.length; j++) { + for (var j = 0; j < filterPasses.length; j++) + { passes.push(filterPasses[j]); } } @@ -264,8 +280,9 @@ * * @private */ -DisplayObject.prototype.updateTransform = function () { - +DisplayObject.prototype.updateTransform = function () +{ + // create some matrix refs for easy access var pt = this.parent.worldTransform; var wt = this.worldTransform; @@ -274,9 +291,11 @@ var a, b, c, d, tx, ty; // so if rotation is between 0 then we can simplify the multiplication process.. - if (this.rotation % math.PI_2) { + if (this.rotation % math.PI_2) + { // 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) { + if (this.rotation !== this.rotationCache) + { this.rotationCache = this.rotation; this._sr = Math.sin(this.rotation); this._cr = Math.cos(this.rotation); @@ -291,7 +310,8 @@ ty = this.position.y; // check for pivot.. not often used so geared towards that fact! - if (this.pivot.x || this.pivot.y) { + 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; } @@ -304,7 +324,8 @@ wt.tx = tx * pt.a + ty * pt.c + pt.tx; wt.ty = tx * pt.b + ty * pt.d + pt.ty; } - else { + else + { // lets do the fast version as we know there is no rotation.. a = this.scale.x; d = this.scale.y; @@ -333,7 +354,8 @@ * @param matrix {Matrix} * @return {Rectangle} the rectangular bounding area */ -DisplayObject.prototype.getBounds = function (/* matrix */) { +DisplayObject.prototype.getBounds = function (/* matrix */) +{ return math.Rectangle.EMPTY; }; @@ -342,7 +364,8 @@ * * @return {Rectangle} the rectangular bounding area */ -DisplayObject.prototype.getLocalBounds = function () { +DisplayObject.prototype.getLocalBounds = function () +{ return this.getBounds(math.Matrix.IDENTITY); }; @@ -352,7 +375,8 @@ * @param position {Point} The world origin to calculate from * @return {Point} A point object representing the position of this object */ -DisplayObject.prototype.toGlobal = function (position) { +DisplayObject.prototype.toGlobal = function (position) +{ // don't need to u[date the lot this.displayObjectUpdateTransform(); return this.worldTransform.apply(position); @@ -365,8 +389,10 @@ * @param [from] {DisplayObject} The DisplayObject to calculate the global position from * @return {Point} A point object representing the position of this object */ -DisplayObject.prototype.toLocal = function (position, from) { - if (from) { +DisplayObject.prototype.toLocal = function (position, from) +{ + if (from) + { position = from.toGlobal(position); } @@ -381,7 +407,8 @@ * @param renderer {WebGLRenderer} The renderer * @private */ -DisplayObject.prototype.renderWebGL = function (/* renderer */) { +DisplayObject.prototype.renderWebGL = function (/* renderer */) +{ // OVERWRITE; }; @@ -391,6 +418,7 @@ * @param renderer {CanvasRenderer} The renderer * @private */ -DisplayObject.prototype.renderCanvas = function (/* renderer */) { +DisplayObject.prototype.renderCanvas = function (/* renderer */) +{ // OVERWRITE; }; diff --git a/src/core/display/DisplayObjectContainer.js b/src/core/display/DisplayObjectContainer.js index 689f40b..4625ee8 100644 --- a/src/core/display/DisplayObjectContainer.js +++ b/src/core/display/DisplayObjectContainer.js @@ -12,7 +12,8 @@ * @extends DisplayObject * @namespace PIXI */ -function DisplayObjectContainer() { +function DisplayObjectContainer() +{ DisplayObject.call(this); /** @@ -47,17 +48,21 @@ * @memberof DisplayObjectContainer# */ width: { - get: function () { + get: function () + { return this.scale.x * this.getLocalBounds().width; }, - set: function (value) { + set: function (value) + { var width = this.getLocalBounds().width; - if(width !== 0) { + if(width !== 0) + { this.scale.x = value / width; } - else { + else + { this.scale.x = 1; } @@ -73,17 +78,21 @@ * @memberof DisplayObjectContainer# */ height: { - get: function () { + get: function () + { return this.scale.y * this.getLocalBounds().height; }, - set: function (value) { + set: function (value) + { var height = this.getLocalBounds().height; - if (height !== 0) { + if (height !== 0) + { this.scale.y = value / height ; } - else { + else + { this.scale.y = 1; } @@ -100,18 +109,23 @@ * @memberof DisplayObject# */ cacheAsBitmap: { - get: function () { + get: function () + { return this._cacheAsBitmap; }, - set: function (value) { - if (this._cacheAsBitmap === value) { + set: function (value) + { + if (this._cacheAsBitmap === value) + { return; } - if (value) { + if (value) + { this._generateCachedSprite(); } - else { + else + { this._destroyCachedSprite(); } @@ -126,7 +140,8 @@ * @param child {DisplayObject} The DisplayObject to add to the container * @return {DisplayObject} The child that was added. */ -DisplayObjectContainer.prototype.addChild = function (child) { +DisplayObjectContainer.prototype.addChild = function (child) +{ return this.addChildAt(child, this.children.length); }; @@ -137,14 +152,18 @@ * @param index {Number} The index to place the child in * @return {DisplayObject} The child that was added. */ -DisplayObjectContainer.prototype.addChildAt = function (child, index) { +DisplayObjectContainer.prototype.addChildAt = function (child, index) +{ // prevent adding self as child - if (child === this) { + if (child === this) + { return; } - if (index >= 0 && index <= this.children.length) { - if (child.parent) { + if (index >= 0 && index <= this.children.length) + { + if (child.parent) + { child.parent.removeChild(child); } @@ -154,7 +173,8 @@ return child; } - else { + else + { throw new Error(child + 'addChildAt: The index '+ index +' supplied is out of bounds ' + this.children.length); } }; @@ -165,15 +185,18 @@ * @param child {DisplayObject} * @param child2 {DisplayObject} */ -DisplayObjectContainer.prototype.swapChildren = function (child, child2) { - if (child === child2) { +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) { + if (index1 < 0 || index2 < 0) + { throw new Error('swapChildren: Both the supplied DisplayObjects must be a child of the caller.'); } @@ -187,10 +210,12 @@ * @param child {DisplayObject} The DisplayObject instance to identify * @return {Number} The index position of the child display object to identify */ -DisplayObjectContainer.prototype.getChildIndex = function (child) { +DisplayObjectContainer.prototype.getChildIndex = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { throw new Error('The supplied DisplayObject must be a child of the caller'); } @@ -203,8 +228,10 @@ * @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 */ -DisplayObjectContainer.prototype.setChildIndex = function (child, index) { - if (index < 0 || index >= this.children.length) { +DisplayObjectContainer.prototype.setChildIndex = function (child, index) +{ + if (index < 0 || index >= this.children.length) + { throw new Error('The supplied index is out of bounds'); } @@ -220,8 +247,10 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child at the given index, if any. */ -DisplayObjectContainer.prototype.getChildAt = function (index) { - if (index < 0 || index >= this.children.length) { +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'); } @@ -234,10 +263,12 @@ * @param child {DisplayObject} The DisplayObject to remove * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChild = function (child) { +DisplayObjectContainer.prototype.removeChild = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { return; } @@ -250,7 +281,8 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChildAt = function (index) { +DisplayObjectContainer.prototype.removeChildAt = function (index) +{ var child = this.getChildAt(index); child.parent = null; @@ -265,24 +297,29 @@ * @param beginIndex {Number} The beginning position. Default value is 0. * @param endIndex {Number} The ending position. Default value is size of the container. */ -DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) { +DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) +{ var begin = beginIndex || 0; var end = typeof endIndex === 'number' ? endIndex : this.children.length; var range = end - begin; - if (range > 0 && range <= end) { + if (range > 0 && range <= end) + { var removed = this.children.splice(begin, range); - for (var i = 0; i < removed.length; ++i) { + for (var i = 0; i < removed.length; ++i) + { removed[i].parent = null; } return removed; } - else if (range === 0 && this.children.length === 0) { + else if (range === 0 && this.children.length === 0) + { return []; } - else { + else + { throw new RangeError('removeChildren: numeric values are outside the acceptable range.'); } }; @@ -291,7 +328,8 @@ * Generates and updates the cached sprite for this object. * */ -DisplayObjectContainer.prototype.updateCachedSprite = function () { +DisplayObjectContainer.prototype.updateCachedSprite = function () +{ this._generateCachedSprite(); }; @@ -304,7 +342,8 @@ * @param renderer {CanvasRenderer|WebGLRenderer} The renderer used to generate the texture. * @return {Texture} a texture of the graphics object */ -DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) { +DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) +{ var bounds = this.getLocalBounds(); var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0, renderer, scaleMode, resolution); @@ -322,18 +361,22 @@ * * @private */ -DisplayObjectContainer.prototype.updateTransform = function () { - if (!this.visible) { +DisplayObjectContainer.prototype.updateTransform = function () +{ + if (!this.visible) + { return; } this.displayObjectUpdateTransform(); - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { return; } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } }; @@ -346,8 +389,10 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getBounds = function () { - if (this.children.length === 0) { +DisplayObjectContainer.prototype.getBounds = function () +{ + if (this.children.length === 0) + { return math.Rectangle.EMPTY; } @@ -365,10 +410,12 @@ var childVisible = false; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -386,7 +433,8 @@ maxY = maxY > childMaxY ? maxY : childMaxY; } - if (!childVisible) { + if (!childVisible) + { return math.Rectangle.EMPTY; } @@ -407,12 +455,14 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getLocalBounds = function () { +DisplayObjectContainer.prototype.getLocalBounds = function () +{ var matrixCache = this.worldTransform; this.worldTransform = math.Matrix.IDENTITY; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } @@ -428,13 +478,16 @@ * * @param renderer {WebGLRenderer} The renderer */ -DisplayObjectContainer.prototype.renderWebGL = function (renderer) { +DisplayObjectContainer.prototype.renderWebGL = function (renderer) +{ // if the object is not visible or the alpha is 0 then no need to render this element - if (!this.visible || this.alpha <= 0) { + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } @@ -442,14 +495,17 @@ var i, j; // do a quick check to see if this element has a mask or a filter. - if (this._mask || this._filters) { + if (this._mask || this._filters) + { // push filter first as we need to ensure the stencil buffer is correct for any masking - if (this._filters) { + if (this._filters) + { renderer.spriteBatch.flush(); renderer.filterManager.pushFilter(this._filterBlock); } - if (this._mask) { + if (this._mask) + { renderer.spriteBatch.stop(); renderer.maskManager.pushMask(this.mask, renderer); renderer.spriteBatch.start(); @@ -459,36 +515,42 @@ this._renderWebGL(renderer); // now loop through the children and make sure they get rendered - for (i = 0, j = this.children.length; i < j; i++) { + for (i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderWebGL(renderer); } // time to stop the sprite batch as either a mask element or a filter draw will happen next renderer.spriteBatch.stop(); - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(this._mask, renderer); } - if (this._filters) { + if (this._filters) + { renderer.filterManager.popFilter(); } renderer.spriteBatch.start(); } - else { + else + { this._renderWebGL(renderer); // simple render children! - for (i = 0, j = this.children.length; i < j; ++i) { + for (i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderWebGL(renderer); } } }; -DisplayObjectContainer.prototype._renderWebGL = function (renderer) { +DisplayObjectContainer.prototype._renderWebGL = function (renderer) +{ // this is where content itself gets renderd.. @@ -499,25 +561,31 @@ * * @param renderer {CanvasRenderer} The renderer */ -DisplayObjectContainer.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0) { +DisplayObjectContainer.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -528,13 +596,16 @@ * @param renderer {WebGLRenderer|CanvasRenderer} The renderer * @private */ -DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) { +DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) +{ this._cachedSprite.worldAlpha = this.worldAlpha; - if (renderer.gl) { + if (renderer.gl) + { this._cachedSprite.renderWebGL(renderer); } - else { + else + { this._cachedSprite.renderCanvas(renderer); } }; @@ -544,10 +615,12 @@ * * @private */ -DisplayObjectContainer.prototype._generateCachedSprite = function () { +DisplayObjectContainer.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { // TODO - RenderTexture now *requires* a renderer instance, so this is like broken // because `renderer` isn't actually in scope here :P var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0); @@ -555,7 +628,8 @@ this._cachedSprite = new Sprite(renderTexture); this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.texture.resize(bounds.width | 0, bounds.height | 0); } @@ -580,8 +654,10 @@ * * @private */ -DisplayObjectContainer.prototype._destroyCachedSprite = function () { - if (!this._cachedSprite) { +DisplayObjectContainer.prototype._destroyCachedSprite = function () +{ + if (!this._cachedSprite) + { return; } diff --git a/src/core/display/Sprite.js b/src/core/display/Sprite.js index 707da24..5862aef 100644 --- a/src/core/display/Sprite.js +++ b/src/core/display/Sprite.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param texture {Texture} The texture for this sprite */ -function Sprite(texture) { +function Sprite(texture) +{ DisplayObjectContainer.call(this); /** @@ -85,12 +86,14 @@ this.texture = texture || Texture.EMPTY; } -Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) { +Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) +{ DisplayObjectContainer.prototype.destroy.call(this); this.anchor = null; - if (destroyTexture) { + if (destroyTexture) + { this._texture.destroy(destroyBaseTexture); } @@ -111,10 +114,12 @@ * @memberof Sprite# */ width: { - get: function () { + get: function () + { return this.scale.x * this.texture.frame.width; }, - set: function (value) { + set: function (value) + { this.scale.x = value / this.texture.frame.width; this._width = value; } @@ -127,10 +132,12 @@ * @memberof Sprite# */ height: { - get: function () { + get: function () + { return this.scale.y * this.texture.frame.height; }, - set: function (value) { + set: function (value) + { this.scale.y = value / this.texture.frame.height; this._height = value; } @@ -143,23 +150,29 @@ * @memberof Sprite# */ texture: { - get: function () { + get: function () + { return this._texture; }, - set: function (value) { - if (this._texture === value) { + set: function (value) + { + if (this._texture === value) + { return; } this._texture = value; this.cachedTint = 0xFFFFFF; - if (value) { + if (value) + { // wait for the texture to load - if (value.baseTexture.hasLoaded) { + if (value.baseTexture.hasLoaded) + { this._onTextureUpdate(); } - else { + else + { value.once('update', this._onTextureUpdate.bind(this)); } } @@ -172,18 +185,22 @@ * * @private */ -Sprite.prototype._onTextureUpdate = function () { +Sprite.prototype._onTextureUpdate = function () +{ // so if _width is 0 then width was not set.. - if (this._width) { + if (this._width) + { this.scale.x = this._width / this.texture.frame.width; } - if (this._height) { + if (this._height) + { this.scale.y = this._height / this.texture.frame.height; } }; -Sprite.prototype._renderWebGL = function (renderer) { +Sprite.prototype._renderWebGL = function (renderer) +{ // this is where content gets renderd.. // watch this space for a little render state manager.. @@ -197,7 +214,8 @@ * @param matrix {Matrix} the transformation matrix of the sprite * @return {Rectangle} the framing rectangle */ -Sprite.prototype.getBounds = function (matrix) { +Sprite.prototype.getBounds = function (matrix) +{ var width = this.texture.frame.width; var height = this.texture.frame.height; @@ -224,11 +242,13 @@ if(b === 0 && c === 0) { // scale may be negative! - if (a < 0) { + if (a < 0) + { a *= -1; } - if (d < 0) { + if (d < 0) + { d *= -1; } @@ -293,28 +313,34 @@ * * @param renderer {CanvasRenderer} The renderer */ -Sprite.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) { +Sprite.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) + { return; } - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; renderer.context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } // Ignore null sources - if (this.texture.valid) { + if (this.texture.valid) + { var resolution = this.texture.baseTexture.resolution / renderer.resolution; renderer.context.globalAlpha = this.worldAlpha; // If smoothingEnabled is supported and we need to change the smoothing property for this texture - if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) { + if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) + { renderer.scaleMode = this.texture.baseTexture.scaleMode; renderer.context[renderer.smoothProperty] = (renderer.scaleMode === CONST.scaleModes.LINEAR); } @@ -324,7 +350,8 @@ var dy = (this.texture.trim ? this.texture.trim.y : 0) - (this.anchor.y * this.texture.trim.height); // Allow for pixel rounding - if (renderer.roundPixels) { + if (renderer.roundPixels) + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -337,7 +364,8 @@ dx = dx | 0; dy = dy | 0; } - else { + else + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -348,8 +376,10 @@ ); } - if (this.tint !== 0xFFFFFF) { - if (this.cachedTint !== this.tint) { + if (this.tint !== 0xFFFFFF) + { + if (this.cachedTint !== this.tint) + { this.cachedTint = this.tint; // TODO clean up caching - how to clean up the caches? @@ -368,7 +398,8 @@ this.texture.crop.height / resolution ); } - else { + else + { renderer.context.drawImage( this.texture.baseTexture.source, this.texture.crop.x, @@ -383,11 +414,13 @@ } } - for (var i = 0, j = this.children.length; i < j; i++) { + for (var i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -402,10 +435,12 @@ * @param frameId {String} The frame Id of the texture in the cache * @return {Sprite} A new Sprite using a texture from the texture cache matching the frameId */ -Sprite.fromFrame = function (frameId) { +Sprite.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache' + this); } @@ -420,6 +455,7 @@ * @param imageId {String} The image url of the texture * @return {Sprite} A new Sprite using a texture from the texture cache matching the image id */ -Sprite.fromImage = function (imageId, crossorigin, scaleMode) { +Sprite.fromImage = function (imageId, crossorigin, scaleMode) +{ return new Sprite(Texture.fromImage(imageId, crossorigin, scaleMode)); }; diff --git a/src/core/display/SpriteBatch.js b/src/core/display/SpriteBatch.js index 3187777..c196fef 100644 --- a/src/core/display/SpriteBatch.js +++ b/src/core/display/SpriteBatch.js @@ -12,7 +12,8 @@ * ```js * var container = new SpriteBatch(); * - * for(var i = 0; i < 100; ++i) { + * for(var i = 0; i < 100; ++i) + * { * var sprite = new PIXI.Sprite.fromImage("myImage.png"); * container.addChild(sprite); * } @@ -25,7 +26,8 @@ */ //TODO RENAME to PARTICLE CONTAINER? -function SpriteBatch() { +function SpriteBatch() +{ DisplayObjectContainer.call(this); } @@ -38,7 +40,8 @@ * * @private */ -SpriteBatch.prototype.updateTransform = function () { +SpriteBatch.prototype.updateTransform = function () +{ // TODO don't need to! this.displayObjectUpdateTransform(); // PIXI.DisplayObjectContainer.prototype.updateTransform.call( this ); @@ -50,8 +53,10 @@ * @param renderer {WebGLRenderer} The webgl renderer * @private */ -SpriteBatch.prototype.renderWebGL = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderWebGL = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -71,8 +76,10 @@ * @param renderer {CanvasRenderer} The canvas renderer * @private */ -SpriteBatch.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -84,10 +91,12 @@ this.displayObjectUpdateTransform(); - for (var i = 0; i < this.children.length; ++i) { + for (var i = 0; i < this.children.length; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -95,9 +104,11 @@ context.globalAlpha = this.worldAlpha * child.alpha; - if (child.rotation % (Math.PI * 2) === 0) { + if (child.rotation % (Math.PI * 2) === 0) + { // this is the fastest way to optimise! - if rotation is 0 then we can avoid any kind of setTransform call - if (isRotated) { + if (isRotated) + { context.setTransform( transform.a, transform.b, @@ -122,8 +133,10 @@ frame.height * child.scale.y ); } - else { - if (!isRotated) { + else + { + if (!isRotated) + { isRotated = true; } @@ -131,7 +144,8 @@ var childTransform = child.worldTransform; - if (renderer.roundPixels) { + if (renderer.roundPixels) + { context.setTransform( childTransform.a, childTransform.b, @@ -141,7 +155,8 @@ childTransform.ty | 0 ); } - else { + else + { context.setTransform( childTransform.a, childTransform.b, diff --git a/src/core/index.js b/src/core/index.js index 3954b6f..eb4a82b 100644 --- a/src/core/index.js +++ b/src/core/index.js @@ -58,11 +58,13 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRenderer: function (width, height, options, noWebGL) { + autoDetectRenderer: function (width, height, options, noWebGL) + { width = width || 800; height = height || 600; - if (!noWebGL && require('webgl-enabled')()) { + if (!noWebGL && require('webgl-enabled')()) + { return new core.WebGLRenderer(width, height, options); } @@ -87,7 +89,8 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRecommendedRenderer: function (width, height, options) { + autoDetectRecommendedRenderer: function (width, height, options) + { var isAndroid = /Android/i.test(navigator.userAgent); return core.autoDetectRenderer(width, height, options, isAndroid); diff --git a/src/core/math/Matrix.js b/src/core/math/Matrix.js index c2f87e2..2ff4848 100644 --- a/src/core/math/Matrix.js +++ b/src/core/math/Matrix.js @@ -10,7 +10,8 @@ * @class * @namespace PIXI */ -function Matrix() { +function Matrix() +{ /** * @member {number} * @default 1 @@ -63,7 +64,8 @@ * * @param array {number[]} The array that the matrix will be populated from. */ -Matrix.prototype.fromArray = function (array) { +Matrix.prototype.fromArray = function (array) +{ this.a = array[0]; this.b = array[1]; this.c = array[3]; @@ -78,14 +80,17 @@ * @param transpose {boolean} Whether we need to transpose the matrix or not * @return {number[]} the newly created array which contains the matrix */ -Matrix.prototype.toArray = function (transpose) { - if (!this.array) { +Matrix.prototype.toArray = function (transpose) +{ + if (!this.array) + { this.array = new Float32Array(9); } var array = this.array; - if (transpose) { + if (transpose) + { array[0] = this.a; array[1] = this.b; array[2] = 0; @@ -96,7 +101,8 @@ array[7] = this.ty; array[8] = 1; } - else { + else + { array[0] = this.a; array[1] = this.c; array[2] = this.tx; @@ -119,7 +125,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, transformed through this matrix */ -Matrix.prototype.apply = function (pos, newPos) { +Matrix.prototype.apply = function (pos, newPos) +{ newPos = newPos || new Point(); newPos.x = this.a * pos.x + this.c * pos.y + this.tx; @@ -136,7 +143,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, inverse-transformed through this matrix */ -Matrix.prototype.applyInverse = function (pos, newPos) { +Matrix.prototype.applyInverse = function (pos, newPos) +{ newPos = newPos || new Point(); var id = 1 / (this.a * this.d + this.c * -this.b); @@ -154,7 +162,8 @@ * @param {number} y * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.translate = function (x, y) { +Matrix.prototype.translate = function (x, y) +{ this.tx += x; this.ty += y; @@ -168,7 +177,8 @@ * @param {number} y The amount to scale vertically * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.scale = function (x, y) { +Matrix.prototype.scale = function (x, y) +{ this.a *= x; this.d *= y; this.c *= x; @@ -186,7 +196,8 @@ * @param {number} angle - The angle in radians. * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.rotate = function (angle) { +Matrix.prototype.rotate = function (angle) +{ var cos = Math.cos( angle ); var sin = Math.sin( angle ); @@ -210,7 +221,8 @@ * @param {Matrix} matrix * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.append = function (matrix) { +Matrix.prototype.append = function (matrix) +{ var a1 = this.a; var b1 = this.b; var c1 = this.c; @@ -232,7 +244,8 @@ * * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.identity = function () { +Matrix.prototype.identity = function () +{ this.a = 1; this.b = 0; this.c = 0; diff --git a/src/core/math/Point.js b/src/core/math/Point.js index 7565b2d..632f346 100644 --- a/src/core/math/Point.js +++ b/src/core/math/Point.js @@ -7,7 +7,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -function Point(x, y) { +function Point(x, y) +{ /** * @member {number} * @default 0 @@ -29,7 +30,8 @@ * * @return {Point} a copy of the point */ -Point.prototype.clone = function () { +Point.prototype.clone = function () +{ return new Point(this.x, this.y); }; @@ -40,7 +42,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -Point.prototype.set = function (x, y) { +Point.prototype.set = function (x, y) +{ this.x = x || 0; this.y = y || ( (y !== 0) ? this.x : 0 ) ; }; diff --git a/src/core/math/shapes/Circle.js b/src/core/math/shapes/Circle.js index 69cfdc9..4d76efc 100644 --- a/src/core/math/shapes/Circle.js +++ b/src/core/math/shapes/Circle.js @@ -10,7 +10,8 @@ * @param y {number} The Y coordinate of the center of this circle * @param radius {number} The radius of the circle */ -function Circle(x, y, radius) { +function Circle(x, y, radius) +{ /** * @member {number} * @default 0 @@ -46,7 +47,8 @@ * @method clone * @return {Circle} a copy of the Circle */ -Circle.prototype.clone = function () { +Circle.prototype.clone = function () +{ return new Circle(this.x, this.y, this.radius); }; @@ -58,8 +60,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Circle */ -Circle.prototype.contains = function (x, y) { - if (this.radius <= 0) { +Circle.prototype.contains = function (x, y) +{ + if (this.radius <= 0) + { return false; } @@ -79,6 +83,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Circle.prototype.getBounds = function () { +Circle.prototype.getBounds = function () +{ return new Rectangle(this.x - this.radius, this.y - this.radius, this.radius * 2, this.radius * 2); }; diff --git a/src/core/math/shapes/Ellipse.js b/src/core/math/shapes/Ellipse.js index 4f2d066..fefd01a 100644 --- a/src/core/math/shapes/Ellipse.js +++ b/src/core/math/shapes/Ellipse.js @@ -11,7 +11,8 @@ * @param width {number} The half width of this ellipse * @param height {number} The half height of this ellipse */ -function Ellipse(x, y, width, height) { +function Ellipse(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -53,7 +54,8 @@ * @method clone * @return {Ellipse} a copy of the ellipse */ -Ellipse.prototype.clone = function () { +Ellipse.prototype.clone = function () +{ return new Ellipse(this.x, this.y, this.width, this.height); }; @@ -65,8 +67,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coords are within this ellipse */ -Ellipse.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Ellipse.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } @@ -86,6 +90,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Ellipse.prototype.getBounds = function () { +Ellipse.prototype.getBounds = function () +{ return new Rectangle(this.x - this.width, this.y - this.height, this.width, this.height); }; diff --git a/src/core/math/shapes/Polygon.js b/src/core/math/shapes/Polygon.js index ae89148..fea6d37 100644 --- a/src/core/math/shapes/Polygon.js +++ b/src/core/math/shapes/Polygon.js @@ -10,16 +10,20 @@ * arguments passed can be flat x,y values e.g. `new Polygon(x,y, x,y, x,y, ...)` where `x` and `y` are * Numbers. */ -function Polygon(points) { +function Polygon(points) +{ //if points isn't an array, use arguments as the array - if (!(points instanceof Array)) { + if (!(points instanceof Array)) + { points = Array.prototype.slice.call(arguments); } //if this is a flat array of numbers, convert it to points - if (points[0] instanceof Point) { + if (points[0] instanceof Point) + { var p = []; - for (var i = 0, il = points.length; i < il; i++) { + for (var i = 0, il = points.length; i < il; i++) + { p.push(points[i].x, points[i].y); } @@ -51,7 +55,8 @@ * * @return {Polygon} a copy of the polygon */ -Polygon.prototype.clone = function () { +Polygon.prototype.clone = function () +{ return new Polygon(this.points.slice()); }; @@ -62,19 +67,22 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this polygon */ -Polygon.prototype.contains = function (x, y) { +Polygon.prototype.contains = function (x, y) +{ var inside = false; // use some raycasting to test hits // https://github.com/substack/point-in-polygon/blob/master/index.js var length = this.points.length / 2; - for (var i = 0, j = length - 1; i < length; j = i++) { + for (var i = 0, j = length - 1; i < length; j = i++) + { var xi = this.points[i * 2], yi = this.points[i * 2 + 1], xj = this.points[j * 2], yj = this.points[j * 2 + 1], intersect = ((yi > y) !== (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi); - if (intersect) { + if (intersect) + { inside = !inside; } } diff --git a/src/core/math/shapes/Rectangle.js b/src/core/math/shapes/Rectangle.js index 16ac62a..4008b68 100644 --- a/src/core/math/shapes/Rectangle.js +++ b/src/core/math/shapes/Rectangle.js @@ -10,7 +10,8 @@ * @param width {number} The overall width of this rectangle * @param height {number} The overall height of this rectangle */ -function Rectangle(x, y, width, height) { +function Rectangle(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -60,7 +61,8 @@ * * @return {Rectangle} a copy of the rectangle */ -Rectangle.prototype.clone = function () { +Rectangle.prototype.clone = function () +{ return new Rectangle(this.x, this.y, this.width, this.height); }; @@ -71,13 +73,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rectangle */ -Rectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Rectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/math/shapes/RoundedRectangle.js b/src/core/math/shapes/RoundedRectangle.js index 27d286e..7bf6411 100644 --- a/src/core/math/shapes/RoundedRectangle.js +++ b/src/core/math/shapes/RoundedRectangle.js @@ -11,7 +11,8 @@ * @param height {number} The overall height of this rounded rectangle * @param radius {number} Controls the radius of the rounded corners */ -function RoundedRectangle(x, y, width, height, radius) { +function RoundedRectangle(x, y, width, height, radius) +{ /** * @member {number} * @default 0 @@ -58,7 +59,8 @@ * * @return {RoundedRectangle} a copy of the rounded rectangle */ -RoundedRectangle.prototype.clone = function () { +RoundedRectangle.prototype.clone = function () +{ return new RoundedRectangle(this.x, this.y, this.width, this.height, this.radius); }; @@ -69,13 +71,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rounded Rectangle */ -RoundedRectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +RoundedRectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/primitives/Graphics.js b/src/core/primitives/Graphics.js index 261c534..e902d2a 100644 --- a/src/core/primitives/Graphics.js +++ b/src/core/primitives/Graphics.js @@ -16,7 +16,8 @@ * @extends DisplayObjectContainer * @namespace PIXI */ -function Graphics() { +function Graphics() +{ DisplayObjectContainer.call(this); this.renderable = true; @@ -154,16 +155,20 @@ * @private */ cacheAsBitmap: { - get: function () { + get: function () + { return this._cacheAsBitmap; }, - set: function (value) { + set: function (value) + { this._cacheAsBitmap = value; - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._generateCachedSprite(); } - else { + else + { this.destroyCachedSprite(); this.dirty = true; } @@ -176,7 +181,8 @@ * * @return {Graphics} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ var clone = new Graphics(); clone.renderable = this.renderable; @@ -192,7 +198,8 @@ clone.cachedSpriteDirty = this.cachedSpriteDirty; // copy graphics data - for (var i = 0; i < this.graphicsData.length; ++i) { + for (var i = 0; i < this.graphicsData.length; ++i) + { clone.graphicsData.push(this.graphicsData.clone()); } @@ -211,17 +218,21 @@ * @param alpha {number} alpha of the line to draw, will update the objects stored style * @return {Graphics} */ -Graphics.prototype.lineStyle = function (lineWidth, color, alpha) { +Graphics.prototype.lineStyle = function (lineWidth, color, alpha) +{ this.lineWidth = lineWidth || 0; this.lineColor = color || 0; this.lineAlpha = (arguments.length < 3) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length) + { // halfway through a line? start a new one! this.drawShape( new math.Polygon( this.currentPath.shape.points.slice(-2) )); } - else { + else + { // otherwise its empty so lets just set the line properties this.currentPath.lineWidth = this.lineWidth; this.currentPath.lineColor = this.lineColor; @@ -239,7 +250,8 @@ * @param y {number} the Y coordinate to move to * @return {Graphics} */ -Graphics.prototype.moveTo = function (x, y) { +Graphics.prototype.moveTo = function (x, y) +{ this.drawShape(new math.Polygon([x,y])); return this; @@ -253,7 +265,8 @@ * @param y {number} the Y coordinate to draw to * @return {Graphics} */ -Graphics.prototype.lineTo = function (x, y) { +Graphics.prototype.lineTo = function (x, y) +{ this.currentPath.shape.points.push(x, y); this.dirty = true; @@ -270,13 +283,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -285,7 +302,8 @@ n = 20, points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { this.moveTo(0, 0); } @@ -293,7 +311,8 @@ var fromY = points[points.length-1]; var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; xa = fromX + ( (cpX - fromX) * j ); @@ -319,13 +338,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -342,7 +365,8 @@ var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; dt = (1 - j); @@ -373,13 +397,17 @@ * @param radius {number} The radius of the arc * @return {Graphics} */ -Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points.push(x1, y1); } } - else { + else + { this.moveTo(x1, y1); } @@ -392,12 +420,15 @@ b2 = x2 - x1, mm = Math.abs(a1 * b2 - b1 * a2); - if (mm < 1.0e-8 || radius === 0) { - if (points[points.length-2] !== x1 || points[points.length-1] !== y1) { + if (mm < 1.0e-8 || radius === 0) + { + if (points[points.length-2] !== x1 || points[points.length-1] !== y1) + { points.push(x1, y1); } } - else { + else + { var dd = a1 * a1 + b1 * b1, cc = a2 * a2 + b2 * b2, tt = a1 * a2 + b1 * b2, @@ -433,42 +464,51 @@ * @param anticlockwise {boolean} Optional. Specifies whether the drawing should be counterclockwise or clockwise. False is default, and indicates clockwise, while true indicates counter-clockwise. * @return {Graphics} */ -Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) { +Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) +{ var startX = cx + Math.cos(startAngle) * radius; var startY = cy + Math.sin(startAngle) * radius; var points; // TODO - This if-else makes no sense. It uses currentPath in the else where it doesn't exist... - if (this.currentPath) { + if (this.currentPath) + { points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { points.push(startX, startY); } - else if (points[points.length-2] !== startX || points[points.length-1] !== startY) { + else if (points[points.length-2] !== startX || points[points.length-1] !== startY) + { points.push(startX, startY); } } - else { + else + { this.moveTo(startX, startY); points = this.currentPath.shape.points; } - if (startAngle === endAngle) { + if (startAngle === endAngle) + { return this; } - if (!anticlockwise && endAngle <= startAngle) { + if (!anticlockwise && endAngle <= startAngle) + { endAngle += Math.PI * 2; } - else if (anticlockwise && startAngle <= endAngle) { + else if (anticlockwise && startAngle <= endAngle) + { startAngle += Math.PI * 2; } var sweep = anticlockwise ? (startAngle - endAngle) *-1 : (endAngle - startAngle); var segs = (Math.abs(sweep)/ (Math.PI * 2)) * 40; - if (sweep === 0) { + if (sweep === 0) + { return this; } @@ -482,7 +522,8 @@ var remainder = ( segMinus % 1 ) / segMinus; - for (var i = 0; i <= segMinus; ++i) { + for (var i = 0; i <= segMinus; ++i) + { var real = i + remainder * i; var angle = ((theta) + startAngle + (theta2 * real)); @@ -506,13 +547,16 @@ * @param alpha {number} the alpha of the fill * @return {Graphics} */ -Graphics.prototype.beginFill = function (color, alpha) { +Graphics.prototype.beginFill = function (color, alpha) +{ this.filling = true; this.fillColor = color || 0; this.fillAlpha = (alpha === undefined) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length <= 2) + { this.currentPath.fill = this.filling; this.currentPath.fillColor = this.fillColor; this.currentPath.fillAlpha = this.fillAlpha; @@ -526,7 +570,8 @@ * * @return {Graphics} */ -Graphics.prototype.endFill = function () { +Graphics.prototype.endFill = function () +{ this.filling = false; this.fillColor = null; this.fillAlpha = 1; @@ -542,7 +587,8 @@ * @param height {number} The height of the rectangle * @return {Graphics} */ -Graphics.prototype.drawRect = function ( x, y, width, height ) { +Graphics.prototype.drawRect = function ( x, y, width, height ) +{ this.drawShape(new math.Rectangle(x,y, width, height)); return this; @@ -556,7 +602,8 @@ * @param height {number} The height of the rectangle * @param radius {number} Radius of the rectangle corners */ -Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) { +Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) +{ this.drawShape(new math.RoundedRectangle(x, y, width, height, radius)); return this; @@ -570,7 +617,8 @@ * @param radius {number} The radius of the circle * @return {Graphics} */ -Graphics.prototype.drawCircle = function (x, y, radius) { +Graphics.prototype.drawCircle = function (x, y, radius) +{ this.drawShape(new math.Circle(x,y, radius)); return this; @@ -585,7 +633,8 @@ * @param height {number} The half height of the ellipse * @return {Graphics} */ -Graphics.prototype.drawEllipse = function (x, y, width, height) { +Graphics.prototype.drawEllipse = function (x, y, width, height) +{ this.drawShape(new math.Ellipse(x, y, width, height)); return this; @@ -597,8 +646,10 @@ * @param path {Array} The path data used to construct the polygon. * @return {Graphics} */ -Graphics.prototype.drawPolygon = function (path) { - if (!(path instanceof Array)) { +Graphics.prototype.drawPolygon = function (path) +{ + if (!(path instanceof Array)) + { path = Array.prototype.slice.call(arguments); } @@ -612,7 +663,8 @@ * * @return {Graphics} */ -Graphics.prototype.clear = function () { +Graphics.prototype.clear = function () +{ this.lineWidth = 0; this.filling = false; @@ -631,7 +683,8 @@ * @param scaleMode {number} Should be one of the scaleMode consts * @return {Texture} a texture of the graphics object */ -Graphics.prototype.generateTexture = function (resolution, scaleMode) { +Graphics.prototype.generateTexture = function (resolution, scaleMode) +{ resolution = resolution || 1; var bounds = this.getBounds(); @@ -655,17 +708,21 @@ * * @param renderer {WebGLRenderer} */ -Graphics.prototype._renderWebGL = function (renderer) { +Graphics.prototype._renderWebGL = function (renderer) +{ // if the sprite is not visible or the alpha is 0 then no need to render this element - if (this.isMask === true) { + if (this.isMask === true) + { return; } // this code may still be needed so leaving for now.. - // + // /* - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture on the gpu too! @@ -681,17 +738,24 @@ return; } - */ - - // check if the webgl graphic needs to be updated - if (this.glDirty) { - this.dirty = true; - this.glDirty = false; - } + else */ - renderer.setObjectRendererer(renderer.graphicsRenderer); - renderer.graphicsRenderer.render(this); + renderer.spriteBatch.stop(); + renderer.blendModeManager.setBlendMode(this.blendMode); + // check blend mode + renderer.blendModeManager.setBlendMode( this.blendMode ); + + // check if the webgl graphic needs to be updated + if (this.glDirty) + { + this.dirty = true; + this.glDirty = false; + } + + WebGLGraphics.renderGraphics(this, renderer); + + renderer.spriteBatch.start(); }; /** @@ -700,14 +764,18 @@ * @param renderer {CanvasRenderer} * @private */ -Graphics.prototype.renderCanvas = function (renderer) { +Graphics.prototype.renderCanvas = function (renderer) +{ // 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.isMask === true) { + if (!this.visible || this.alpha <= 0 || this.isMask === true) + { return; } - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture @@ -723,16 +791,19 @@ return; } - else { + else + { var context = renderer.context; var transform = this.worldTransform; - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } @@ -748,11 +819,13 @@ CanvasGraphics.renderGraphics(this, context); - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } } @@ -763,13 +836,16 @@ * * @return {Rectangle} the rectangular bounding area */ -Graphics.prototype.getBounds = function (matrix) { +Graphics.prototype.getBounds = function (matrix) +{ // return an empty object if the item is a mask! - if (this.isMask) { + if (this.isMask) + { return math.Rectangle.EMPTY; } - if (this.dirty) { + if (this.dirty) + { this.updateLocalBounds(); this.glDirty = true; @@ -841,23 +917,27 @@ * Update the bounds of the object * */ -Graphics.prototype.updateLocalBounds = function () { +Graphics.prototype.updateLocalBounds = function () +{ var minX = Infinity; var maxX = -Infinity; var minY = Infinity; var maxY = -Infinity; - if (this.graphicsData.length) { + if (this.graphicsData.length) + { var shape, points, x, y, w, h; - for (var i = 0; i < this.graphicsData.length; i++) { + for (var i = 0; i < this.graphicsData.length; i++) + { var data = this.graphicsData[i]; var type = data.type; var lineWidth = data.lineWidth; shape = data.shape; - if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) { + if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) + { x = shape.x - lineWidth/2; y = shape.y - lineWidth/2; w = shape.width + lineWidth; @@ -869,7 +949,8 @@ minY = y < minY ? y : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.CIRC) { + else if (type === CONST.SHAPES.CIRC) + { x = shape.x; y = shape.y; w = shape.radius + lineWidth/2; @@ -881,7 +962,8 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.ELIP) { + else if (type === CONST.SHAPES.ELIP) + { x = shape.x; y = shape.y; w = shape.width + lineWidth/2; @@ -893,11 +975,13 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else { + else + { // POLY points = shape.points; - for (var j = 0; j < points.length; j += 2) { + for (var j = 0; j < points.length; j += 2) + { x = points[j]; y = points[j+1]; @@ -910,7 +994,8 @@ } } } - else { + else + { minX = 0; maxX = 0; minY = 0; @@ -931,10 +1016,12 @@ * * @private */ -Graphics.prototype._generateCachedSprite = function () { +Graphics.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { var canvasBuffer = new CanvasBuffer(bounds.width, bounds.height); var texture = Texture.fromCanvas(canvasBuffer.canvas); @@ -943,7 +1030,8 @@ this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.buffer.resize(bounds.width, bounds.height); } @@ -968,7 +1056,8 @@ * * @private */ -Graphics.prototype.updateCachedSpriteTexture = function () { +Graphics.prototype.updateCachedSpriteTexture = function () +{ var cachedSprite = this._cachedSprite; var texture = cachedSprite.texture; var canvas = cachedSprite.buffer.canvas; @@ -989,7 +1078,8 @@ * Destroys a previous cached sprite. * */ -Graphics.prototype.destroyCachedSprite = function () { +Graphics.prototype.destroyCachedSprite = function () +{ this._cachedSprite.texture.destroy(true); // let the gc collect the unused sprite @@ -1003,10 +1093,13 @@ * @param {Circle|Rectangle|Ellipse|Line|Polygon} shape The Shape object to draw. * @return {GraphicsData} The generated GraphicsData object. */ -Graphics.prototype.drawShape = function (shape) { - if (this.currentPath) { +Graphics.prototype.drawShape = function (shape) +{ + if (this.currentPath) + { // check current path! - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath.shape.points.length <= 2) + { this.graphicsData.pop(); } } @@ -1017,7 +1110,8 @@ this.graphicsData.push(data); - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { data.shape.closed = this.filling; this.currentPath = data; } diff --git a/src/core/primitives/GraphicsData.js b/src/core/primitives/GraphicsData.js index 99decbe..788f6f2 100644 --- a/src/core/primitives/GraphicsData.js +++ b/src/core/primitives/GraphicsData.js @@ -4,7 +4,8 @@ * @class * @namespace PIXI */ -function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) { +function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) +{ this.lineWidth = lineWidth; this.lineColor = lineColor; this.lineAlpha = lineAlpha; @@ -27,7 +28,8 @@ * * @return {GraphicsData} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ return new GraphicsData( this.lineWidth, this.lineColor, diff --git a/src/core/renderers/canvas/CanvasRenderer.js b/src/core/renderers/canvas/CanvasRenderer.js index 15a0978..7aebd44 100644 --- a/src/core/renderers/canvas/CanvasRenderer.js +++ b/src/core/renderers/canvas/CanvasRenderer.js @@ -17,17 +17,22 @@ * @param [options.resolution=1] {number} the resolution of the renderer retina would be 2 * @param [options.clearBeforeRender=true] {boolean} This sets if the CanvasRenderer will clear the canvas or not before the new render pass. */ -function CanvasRenderer(width, height, options) { +function CanvasRenderer(width, height, options) +{ utils.sayHello('Canvas'); - if (options) { - for (var i in CONST.defaultRenderOptions) { - if (typeof options[i] === 'undefined') { + if (options) + { + for (var i in CONST.defaultRenderOptions) + { + if (typeof options[i] === 'undefined') + { options[i] = CONST.defaultRenderOptions[i]; } } } - else { + else + { options = CONST.defaultRenderOptions; } @@ -156,19 +161,24 @@ this.smoothProperty = null; - if (this.context.imageSmoothingEnabled) { + if (this.context.imageSmoothingEnabled) + { this.smoothProperty = 'imageSmoothingEnabled'; } - else if (this.context.webkitImageSmoothingEnabled) { + else if (this.context.webkitImageSmoothingEnabled) + { this.smoothProperty = 'webkitImageSmoothingEnabled'; } - else if (this.context.mozImageSmoothingEnabled) { + else if (this.context.mozImageSmoothingEnabled) + { this.smoothProperty = 'mozImageSmoothingEnabled'; } - else if (this.context.oImageSmoothingEnabled) { + else if (this.context.oImageSmoothingEnabled) + { this.smoothProperty = 'oImageSmoothingEnabled'; } - else if (this.context.msImageSmoothingEnabled) { + else if (this.context.msImageSmoothingEnabled) + { this.smoothProperty = 'msImageSmoothingEnabled'; } @@ -193,10 +203,12 @@ * @memberof CanvasRenderer# */ backgroundColor: { - get: function () { + get: function () + { return this._backgroundColor; }, - set: function (val) { + set: function (val) + { this._backgroundColor = val; this._backgroundColorString = utils.hex2string(val); } @@ -208,7 +220,8 @@ * * @param object {DisplayObject} the object to be rendered */ -CanvasRenderer.prototype.render = function (object) { +CanvasRenderer.prototype.render = function (object) +{ object.updateTransform(); this.context.setTransform(1,0,0,1,0,0); @@ -218,16 +231,20 @@ this.currentBlendMode = CONST.blendModes.NORMAL; this.context.globalCompositeOperation = this.blendModes[CONST.blendModes.NORMAL]; - if (navigator.isCocoonJS && this.view.screencanvas) { + if (navigator.isCocoonJS && this.view.screencanvas) + { this.context.fillStyle = 'black'; this.context.clear(); } - if (this.clearBeforeRender) { - if (this.transparent) { + if (this.clearBeforeRender) + { + if (this.transparent) + { this.context.clearRect(0, 0, this.width, this.height); } - else { + else + { this.context.fillStyle = this._backgroundColorString; this.context.fillRect(0, 0, this.width , this.height); } @@ -241,8 +258,10 @@ * * @param [removeView=false] {boolean} Removes the Canvas element from the DOM. */ -CanvasRenderer.prototype.destroy = function (removeView) { - if (removeView && this.view.parent) { +CanvasRenderer.prototype.destroy = function (removeView) +{ + if (removeView && this.view.parent) + { this.view.parent.removeChild(this.view); } @@ -257,14 +276,16 @@ * @param width {number} the new width of the canvas view * @param height {number} the new height of the canvas view */ -CanvasRenderer.prototype.resize = function (width, height) { +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) { + if (this.autoResize) + { this.view.style.width = this.width / this.resolution + 'px'; this.view.style.height = this.height / this.resolution + 'px'; } @@ -276,7 +297,8 @@ * @param displayObject {DisplayObject} The displayObject to render * @private */ -CanvasRenderer.prototype.renderDisplayObject = function (displayObject) { +CanvasRenderer.prototype.renderDisplayObject = function (displayObject) +{ displayObject.renderCanvas(this); }; @@ -285,11 +307,14 @@ * * @private */ -CanvasRenderer.prototype._mapBlendModes = function () { - if (!this.blendModes) { +CanvasRenderer.prototype._mapBlendModes = function () +{ + if (!this.blendModes) + { this.blendModes = {}; - if (utils.canUseNewCanvasBlendModes()) { + if (utils.canUseNewCanvasBlendModes()) + { this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? this.blendModes[CONST.blendModes.MULTIPLY] = 'multiply'; @@ -308,7 +333,8 @@ this.blendModes[CONST.blendModes.COLOR] = 'color'; this.blendModes[CONST.blendModes.LUMINOSITY] = 'luminosity'; } - else { + else + { // this means that the browser does not support the cool new blend modes in canvas 'cough' ie 'cough' this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? diff --git a/src/core/renderers/canvas/utils/CanvasBuffer.js b/src/core/renderers/canvas/utils/CanvasBuffer.js index ebe5d47..b183a66 100644 --- a/src/core/renderers/canvas/utils/CanvasBuffer.js +++ b/src/core/renderers/canvas/utils/CanvasBuffer.js @@ -6,7 +6,8 @@ * @param width {number} the width for the newly created canvas * @param height {number} the height for the newly created canvas */ -function CanvasBuffer(width, height) { +function CanvasBuffer(width, height) +{ /** * The Canvas object that belongs to this CanvasBuffer. * @@ -36,10 +37,12 @@ * @memberof CanvasBuffer# */ width: { - get: function () { + get: function () + { return this.canvas.width; }, - set: function (val) { + set: function (val) + { this.canvas.width = val; } }, @@ -50,10 +53,12 @@ * @memberof CanvasBuffer# */ height: { - get: function () { + get: function () + { return this.canvas.height; }, - set: function (val) { + set: function (val) + { this.canvas.height = val; } } @@ -64,7 +69,8 @@ * * @private */ -CanvasBuffer.prototype.clear = function () { +CanvasBuffer.prototype.clear = function () +{ this.context.setTransform(1, 0, 0, 1, 0, 0); this.context.clearRect(0,0, this.canvas.width, this.canvas.height); }; @@ -75,7 +81,8 @@ * @param width {number} the new width of the canvas * @param height {number} the new height of the canvas */ -CanvasBuffer.prototype.resize = function (width, height) { +CanvasBuffer.prototype.resize = function (width, height) +{ this.canvas.width = width; this.canvas.height = height; }; diff --git a/src/core/renderers/canvas/utils/CanvasGraphics.js b/src/core/renderers/canvas/utils/CanvasGraphics.js index c7eaa2a..3f2a91f 100644 --- a/src/core/renderers/canvas/utils/CanvasGraphics.js +++ b/src/core/renderers/canvas/utils/CanvasGraphics.js @@ -13,15 +13,18 @@ * @param graphics {Graphics} the actual graphics object to render * @param context {CanvasRenderingContext2D} the 2d drawing method of the canvas */ -CanvasGraphics.renderGraphics = function (graphics, context) { +CanvasGraphics.renderGraphics = function (graphics, context) +{ var worldAlpha = graphics.worldAlpha; - if (graphics.dirty) { + if (graphics.dirty) + { this.updateGraphicsTint(graphics); graphics.dirty = false; } - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; @@ -30,69 +33,82 @@ context.lineWidth = data.lineWidth; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { context.beginPath(); var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } - if (shape.closed) { + if (shape.closed) + { context.lineTo(points[0], points[1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fillRect(shape.x, shape.y, shape.width, shape.height); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.strokeRect(shape.x, shape.y, shape.width, shape.height); } } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.beginPath(); context.arc(shape.x, shape.y, shape.radius,0,2*Math.PI); context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas var w = shape.width * 2; @@ -119,18 +135,21 @@ context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; var width = shape.width; @@ -152,13 +171,15 @@ context.quadraticCurveTo(rx, ry, rx, ry + radius); context.closePath(); - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); @@ -174,45 +195,54 @@ * @param graphics {Graphics} the graphics which will be used as a mask * @param context {CanvasRenderingContext2D} the context 2d method of the canvas */ -CanvasGraphics.renderGraphicsMask = function (graphics, context) { +CanvasGraphics.renderGraphicsMask = function (graphics, context) +{ var len = graphics.graphicsData.length; - if (len === 0) { + if (len === 0) + { return; } context.beginPath(); - for (var i = 0; i < len; i++) { + for (var i = 0; i < len; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { context.rect(shape.x, shape.y, shape.width, shape.height); context.closePath(); } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.arc(shape.x, shape.y, shape.radius, 0, 2 * Math.PI); context.closePath(); } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas @@ -237,7 +267,8 @@ context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); context.closePath(); } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; @@ -262,8 +293,10 @@ } }; -CanvasGraphics.updateGraphicsTint = function (graphics) { - if (graphics.tint === 0xFFFFFF) { +CanvasGraphics.updateGraphicsTint = function (graphics) +{ + if (graphics.tint === 0xFFFFFF) + { return; } @@ -271,7 +304,8 @@ var tintG = (graphics.tint >> 8 & 0xFF) / 255; var tintB = (graphics.tint & 0xFF)/ 255; - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var fillColor = data.fillColor | 0; diff --git a/src/core/renderers/canvas/utils/CanvasMaskManager.js b/src/core/renderers/canvas/utils/CanvasMaskManager.js index e04a733..9827d36 100644 --- a/src/core/renderers/canvas/utils/CanvasMaskManager.js +++ b/src/core/renderers/canvas/utils/CanvasMaskManager.js @@ -6,7 +6,8 @@ * @class * @namespace PIXI */ -function CanvasMaskManager() {} +function CanvasMaskManager() +{} CanvasMaskManager.prototype.constructor = CanvasMaskManager; module.exports = CanvasMaskManager; @@ -17,7 +18,8 @@ * @param maskData {object} the maskData that will be pushed * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.pushMask = function (maskData, renderer) { +CanvasMaskManager.prototype.pushMask = function (maskData, renderer) +{ renderer.context.save(); var cacheAlpha = maskData.alpha; @@ -45,6 +47,7 @@ * * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.popMask = function (renderer) { +CanvasMaskManager.prototype.popMask = function (renderer) +{ renderer.context.restore(); }; diff --git a/src/core/renderers/canvas/utils/CanvasTinter.js b/src/core/renderers/canvas/utils/CanvasTinter.js index 17e0529..d2fb1bc 100644 --- a/src/core/renderers/canvas/utils/CanvasTinter.js +++ b/src/core/renderers/canvas/utils/CanvasTinter.js @@ -14,7 +14,8 @@ * @param color {number} the color to use to tint the sprite with * @return {HTMLCanvasElement} The tinted canvas */ -CanvasTinter.getTintedTexture = function (sprite, color) { +CanvasTinter.getTintedTexture = function (sprite, color) +{ var texture = sprite.texture; color = CanvasTinter.roundColor(color); @@ -23,7 +24,8 @@ texture.tintCache = texture.tintCache || {}; - if (texture.tintCache[stringColor]) { + if (texture.tintCache[stringColor]) + { return texture.tintCache[stringColor]; } @@ -33,14 +35,16 @@ //CanvasTinter.tintWithPerPixel(texture, stringColor, canvas); CanvasTinter.tintMethod(texture, color, canvas); - if (CanvasTinter.convertTintToImage) { + if (CanvasTinter.convertTintToImage) + { // is this better? var tintImage = new Image(); tintImage.src = canvas.toDataURL(); texture.tintCache[stringColor] = tintImage; } - else { + else + { texture.tintCache[stringColor] = canvas; // if we are not converting the texture to an image then we need to lose the reference to the canvas CanvasTinter.canvas = null; @@ -56,7 +60,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithMultiply = function (texture, color, canvas) { +CanvasTinter.tintWithMultiply = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -104,7 +109,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithOverlay = function (texture, color, canvas) { +CanvasTinter.tintWithOverlay = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -139,7 +145,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithPerPixel = function (texture, color, canvas) { +CanvasTinter.tintWithPerPixel = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -167,7 +174,8 @@ var pixels = pixelData.data; - for (var i = 0; i < pixels.length; i += 4) { + for (var i = 0; i < pixels.length; i += 4) + { pixels[i+0] *= r; pixels[i+1] *= g; pixels[i+2] *= b; @@ -181,7 +189,8 @@ * * @param color {number} the color to round, should be a hex color */ -CanvasTinter.roundColor = function (color) { +CanvasTinter.roundColor = function (color) +{ var step = CanvasTinter.cacheStepsPerColorChannel; var rgbValues = utils.hex2rgb(color); diff --git a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js index 9f2f89a..35edbaf 100644 --- a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js +++ b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLBlendModeManager(renderer) { +function WebGLBlendModeManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -23,8 +24,10 @@ * * @param blendMode {number} the blendMode, should be a Pixi const, such as BlendModes.ADD */ -WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) { - if (this.currentBlendMode === blendMode) { +WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) +{ + if (this.currentBlendMode === blendMode) + { return false; } diff --git a/src/core/renderers/webgl/managers/WebGLFilterManager.js b/src/core/renderers/webgl/managers/WebGLFilterManager.js index 1179258..2dac048 100644 --- a/src/core/renderers/webgl/managers/WebGLFilterManager.js +++ b/src/core/renderers/webgl/managers/WebGLFilterManager.js @@ -7,7 +7,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLFilterManager(renderer) { +function WebGLFilterManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -32,7 +33,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.texturePool.length = 0; self.initShaderBuffers(); }); @@ -46,7 +48,8 @@ * @param renderer {WebGLRenderer} * @param buffer {ArrayBuffer} */ -WebGLFilterManager.prototype.begin = function (buffer) { +WebGLFilterManager.prototype.begin = function (buffer) +{ this.defaultShader = this.renderer.shaderManager.defaultShader; this.width = this.renderer.projection.x * 2; @@ -60,7 +63,8 @@ * * @param filterBlock {object} the filter that will be pushed to the current filter stack */ -WebGLFilterManager.prototype.pushFilter = function (filterBlock) { +WebGLFilterManager.prototype.pushFilter = function (filterBlock) +{ var gl = this.renderer.gl; var projection = this.renderer.projection; @@ -78,10 +82,12 @@ this.offsetY += filterBlock._filterArea.y; var texture = this.texturePool.pop(); - if (!texture) { + if (!texture) + { texture = new FilterTexture(this.renderer.gl, this.width, this.height); } - else { + else + { texture.resize(this.width, this.height); } @@ -98,29 +104,35 @@ var localX = filterArea.x, localY = filterArea.y; - if (filterArea.x < 0) { + if (filterArea.x < 0) + { filterArea.width += filterArea.x; filterArea.x = 0; } - if (filterArea.y < 0) { + if (filterArea.y < 0) + { filterArea.height += filterArea.y; filterArea.y = 0; } - if (localX + filterArea.width > this.width) { + if (localX + filterArea.width > this.width) + { filterArea.width = this.width - localX; } - if (localY + filterArea.height > this.height) { + if (localY + filterArea.height > this.height) + { filterArea.height = this.height - localY; } - if (filterArea.width < 0) { + if (filterArea.width < 0) + { filterArea.width = 0; } - if (filterArea.height < 0) { + if (filterArea.height < 0) + { filterArea.height = 0; } @@ -154,7 +166,8 @@ * Removes the last filter from the filter stack and doesn't return it. * */ -WebGLFilterManager.prototype.popFilter = function () { +WebGLFilterManager.prototype.popFilter = function () +{ var gl = this.renderer.gl; var filterBlock = this.filterStack.pop(); @@ -163,7 +176,8 @@ var projection = this.renderer.projection; var offset = this.renderer.offset; - if (filterBlock.filterPasses.length > 1) { + if (filterBlock.filterPasses.length > 1) + { gl.viewport(0, 0, filterArea.width, filterArea.height); gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); @@ -193,7 +207,8 @@ var inputTexture = texture; var outputTexture = this.texturePool.pop(); - if (!outputTexture) { + if (!outputTexture) + { outputTexture = new FilterTexture(this.renderer.gl, this.width, this.height); } outputTexture.resize(this.width, this.height); @@ -204,7 +219,8 @@ gl.disable(gl.BLEND); - for (var i = 0; i < filterBlock.filterPasses.length-1; i++) { + for (var i = 0; i < filterBlock.filterPasses.length-1; i++) + { var filterPass = filterBlock.filterPasses[i]; gl.bindFramebuffer(gl.FRAMEBUFFER, outputTexture.frameBuffer ); @@ -243,10 +259,12 @@ var buffer = this.buffer; // time to render the filters texture to the previous scene - if (this.filterStack.length === 0) { + if (this.filterStack.length === 0) + { gl.colorMask(true, true, true, true);//this.transparent); } - else { + else + { var currentFilter = this.filterStack[this.filterStack.length-1]; filterArea = currentFilter._filterArea; @@ -332,13 +350,15 @@ * @param width {number} the horizontal range of the filter * @param height {number} the vertical range of the filter */ -WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) { +WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) +{ // use program var gl = this.renderer.gl; var shader = filter.shaders[gl.id]; - if (!shader) { + if (!shader) + { shader = new Shader(gl); shader.fragmentSrc = filter.fragmentSrc; @@ -356,7 +376,8 @@ gl.uniform2f(shader.projectionVector, width/2, -height/2); gl.uniform2f(shader.offsetVector, 0,0); - if (filter.uniforms.dimensions) { + 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]; @@ -386,7 +407,8 @@ * Initialises the shader buffers. * */ -WebGLFilterManager.prototype.initShaderBuffers = function () { +WebGLFilterManager.prototype.initShaderBuffers = function () +{ var gl = this.renderer.gl; // create some buffers @@ -432,7 +454,8 @@ * Destroys the filter and removes it from the filter stack. * */ -WebGLFilterManager.prototype.destroy = function () { +WebGLFilterManager.prototype.destroy = function () +{ var gl = this.renderer.gl; this.filterStack = null; @@ -441,7 +464,8 @@ this.offsetY = 0; // destroy textures - for (var i = 0; i < this.texturePool.length; i++) { + for (var i = 0; i < this.texturePool.length; i++) + { this.texturePool[i].destroy(); } diff --git a/src/core/renderers/webgl/managers/WebGLManager.js b/src/core/renderers/webgl/managers/WebGLManager.js index 9d47b5c..c30cd51 100644 --- a/src/core/renderers/webgl/managers/WebGLManager.js +++ b/src/core/renderers/webgl/managers/WebGLManager.js @@ -3,7 +3,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLManager(renderer) { +function WebGLManager(renderer) +{ /** * The renderer this manager works for. * @@ -15,6 +16,7 @@ WebGLManager.prototype.constructor = WebGLManager; module.exports = WebGLManager; -WebGLManager.prototype.destroy = function () { +WebGLManager.prototype.destroy = function () +{ this.renderer = null; }; diff --git a/src/core/renderers/webgl/managers/WebGLMaskManager.js b/src/core/renderers/webgl/managers/WebGLMaskManager.js index 2f90b64..e568812 100644 --- a/src/core/renderers/webgl/managers/WebGLMaskManager.js +++ b/src/core/renderers/webgl/managers/WebGLMaskManager.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLMaskManager(renderer) { +function WebGLMaskManager(renderer) +{ WebGLManager.call(this, renderer); } @@ -19,12 +20,15 @@ * * @param maskData {any[]} */ -WebGLMaskManager.prototype.pushMask = function (maskData) { - if (maskData.dirty) { +WebGLMaskManager.prototype.pushMask = function (maskData) +{ + if (maskData.dirty) + { WebGLGraphics.updateGraphics(maskData, this.renderer.gl); } - if (!maskData._webGL[this.renderer.gl.id].data.length) { + if (!maskData._webGL[this.renderer.gl.id].data.length) + { return; } @@ -36,6 +40,7 @@ * * @param maskData {any[]} */ -WebGLMaskManager.prototype.popMask = function (maskData) { +WebGLMaskManager.prototype.popMask = function (maskData) +{ this.renderer.stencilManager.popStencil(maskData, maskData._webGL[this.renderer.gl.id].data[0], this.renderer); }; diff --git a/src/core/renderers/webgl/managers/WebGLShaderManager.js b/src/core/renderers/webgl/managers/WebGLShaderManager.js index fef071c..90c6477 100644 --- a/src/core/renderers/webgl/managers/WebGLShaderManager.js +++ b/src/core/renderers/webgl/managers/WebGLShaderManager.js @@ -10,7 +10,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLShaderManager(renderer) { +function WebGLShaderManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -28,7 +29,8 @@ */ this.tempAttribState = []; - for (var i = 0; i < this.maxAttibs; i++) { + for (var i = 0; i < this.maxAttibs; i++) + { this.attribState[i] = false; } @@ -66,7 +68,8 @@ // listen for context and update necessary shaders var self = this; - this.renderer.on('context', function (event) { + this.renderer.on('context', function (event) + { var gl = event.data; // this shader is used for rendering primitives @@ -97,29 +100,36 @@ * * @param attribs {Array} attribs */ -WebGLShaderManager.prototype.setAttribs = function (attribs) { +WebGLShaderManager.prototype.setAttribs = function (attribs) +{ // reset temp state var i; - for (i = 0; i < this.tempAttribState.length; i++) { + for (i = 0; i < this.tempAttribState.length; i++) + { this.tempAttribState[i] = false; } // set the new attribs - for (var a in attribs) { + for (var a in attribs) + { this.tempAttribState[attribs[a]] = true; } var gl = this.renderer.gl; - for (i = 0; i < this.attribState.length; i++) { - if (this.attribState[i] !== this.tempAttribState[i]) { + for (i = 0; i < this.attribState.length; i++) + { + if (this.attribState[i] !== this.tempAttribState[i]) + { this.attribState[i] = this.tempAttribState[i]; - if (this.attribState[i]) { + if (this.attribState[i]) + { gl.enableVertexAttribArray(i); } - else { + else + { gl.disableVertexAttribArray(i); } } @@ -131,8 +141,10 @@ * * @param shader {Any} */ -WebGLShaderManager.prototype.setShader = function (shader) { - if (this._currentId === shader.uuid) { +WebGLShaderManager.prototype.setShader = function (shader) +{ + if (this._currentId === shader.uuid) + { return false; } @@ -150,7 +162,8 @@ * Destroys this object. * */ -WebGLShaderManager.prototype.destroy = function () { +WebGLShaderManager.prototype.destroy = function () +{ this.attribState = null; this.tempAttribState = null; diff --git a/src/core/renderers/webgl/managers/WebGLStencilManager.js b/src/core/renderers/webgl/managers/WebGLStencilManager.js index 9ec6398..4cb0134 100644 --- a/src/core/renderers/webgl/managers/WebGLStencilManager.js +++ b/src/core/renderers/webgl/managers/WebGLStencilManager.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLStencilManager(renderer) { +function WebGLStencilManager(renderer) +{ WebGLManager.call(this, renderer); this.stencilStack = []; @@ -24,12 +25,14 @@ * @param graphics {Graphics} * @param webGLData {any[]} */ -WebGLStencilManager.prototype.pushStencil = function (graphics, webGLData) { +WebGLStencilManager.prototype.pushStencil = function (graphics, webGLData) +{ var gl = this.renderer.gl; this.bindGraphics(graphics, webGLData, this.renderer); - if (this.stencilStack.length === 0) { + if (this.stencilStack.length === 0) + { gl.enable(gl.STENCIL_TEST); gl.clear(gl.STENCIL_BUFFER_BIT); this.reverse = true; @@ -47,14 +50,17 @@ // draw the triangle strip! - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } @@ -62,31 +68,38 @@ // draw a quad to increment.. gl.drawElements(gl.TRIANGLE_FAN, 4, gl.UNSIGNED_SHORT, ( webGLData.indices.length - 4 ) * 2 ); - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); } this.reverse = !this.reverse; } - else { - if (!this.reverse) { + else + { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } - else { + 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) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); } } @@ -103,7 +116,8 @@ * @param graphics {Graphics} * @param webGLData {Array} */ -WebGLStencilManager.prototype.bindGraphics = function (graphics, webGLData) { +WebGLStencilManager.prototype.bindGraphics = function (graphics, webGLData) +{ //if (this._currentGraphics === graphics)return; this._currentGraphics = graphics; @@ -114,7 +128,8 @@ offset = this.renderer.offset, shader;// = this.renderer.shaderManager.primitiveShader; - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { shader = this.renderer.shaderManager.complexPrimitiveShader; this.renderer.shaderManager.setShader(shader); @@ -141,7 +156,8 @@ // set the index buffer! gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, webGLData.indexBuffer); } - else { + else + { //this.renderer.shaderManager.activatePrimitiveShader(); shader = this.renderer.shaderManager.primitiveShader; this.renderer.shaderManager.setShader( shader ); @@ -154,7 +170,7 @@ gl.uniform2f(shader.uniforms.offsetVector._location, -offset.x, -offset.y); gl.uniform3fv(shader.uniforms.tint._location, utils.hex2rgb(graphics.tint)); - + gl.uniform1f(shader.uniforms.alpha._location, graphics.worldAlpha); @@ -172,19 +188,22 @@ * @param graphics {Graphics} * @param webGLData {Array} */ -WebGLStencilManager.prototype.popStencil = function (graphics, webGLData) { +WebGLStencilManager.prototype.popStencil = function (graphics, webGLData) +{ var gl = this.renderer.gl; this.stencilStack.pop(); this.count--; - if (this.stencilStack.length === 0) { + if (this.stencilStack.length === 0) + { // the stack is empty! gl.disable(gl.STENCIL_TEST); } - else { + else + { var level = this.count; @@ -192,14 +211,17 @@ gl.colorMask(false, false, false, false); - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { this.reverse = !this.reverse; - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } @@ -213,31 +235,38 @@ // draw the triangle strip! gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); - if (!this.reverse) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); } } - else { + else + { // console.log("<<>>") - if (!this.reverse) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } - else { + 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) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); } } @@ -253,7 +282,8 @@ * Destroys the mask stack. * */ -WebGLStencilManager.prototype.destroy = function () { +WebGLStencilManager.prototype.destroy = function () +{ this.renderer = null; this.stencilStack = null; }; diff --git a/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js b/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js index 913ba5e..1ea7d19 100644 --- a/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js +++ b/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function ComplexPrimitiveShader(gl) { +function ComplexPrimitiveShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -24,7 +25,8 @@ 'uniform float flipY;', 'varying vec4 vColor;', - 'void main(void) {', + '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);', @@ -37,7 +39,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = vColor;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/FastShader.js b/src/core/renderers/webgl/shaders/FastShader.js index bd2e29a..2e5e060 100644 --- a/src/core/renderers/webgl/shaders/FastShader.js +++ b/src/core/renderers/webgl/shaders/FastShader.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function FastShader(gl) { +function FastShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -28,7 +29,8 @@ 'const vec2 center = vec2(-1.0, 1.0);', - 'void main(void) {', + 'void main(void) + {', ' vec2 v;', ' vec2 sv = aVertexPosition * aScale;', ' v.x = (sv.x) * cos(aRotation) - (sv.y) * sin(aRotation);', @@ -49,7 +51,8 @@ 'uniform sampler2D uSampler;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/PrimitiveShader.js b/src/core/renderers/webgl/shaders/PrimitiveShader.js index 6f25409..a25f54f 100644 --- a/src/core/renderers/webgl/shaders/PrimitiveShader.js +++ b/src/core/renderers/webgl/shaders/PrimitiveShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function PrimitiveShader(gl) { +function PrimitiveShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -23,7 +24,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + '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);', @@ -36,7 +38,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = vColor;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/Shader.js b/src/core/renderers/webgl/shaders/Shader.js index f8964f5..fd75ef5 100644 --- a/src/core/renderers/webgl/shaders/Shader.js +++ b/src/core/renderers/webgl/shaders/Shader.js @@ -6,7 +6,8 @@ * @param [fragmentSrc] {string} The source of the fragment shader. * @param [vertexSrc] {string} The source of the vertex shader. */ -function Shader(gl, vertexSrc, fragmentSrc, customUniforms, customAttributes) { +function Shader(gl, vertexSrc, fragmentSrc, customUniforms, customAttributes) +{ /** * @member {number} * @readonly @@ -33,7 +34,8 @@ dimensions: { type: '4f', value: new Float32Array(4) } }; - for (var u in customUniforms) { + for (var u in customUniforms) + { this.uniforms[u] = customUniforms[u]; } @@ -43,7 +45,8 @@ aColor: 0 }; - for (var a in customAttributes) { + for (var a in customAttributes) + { this.attributes[a] = customAttributes[a]; } @@ -66,7 +69,8 @@ 'const vec2 center = vec2(-1.0, 1.0);', - 'void main(void) {', + 'void main(void) + {', ' gl_Position = vec4( ((aVertexPosition + offsetVector) / projectionVector) + center , 0.0, 1.0);', ' vTextureCoord = aTextureCoord;', ' vColor = vec4(aColor.rgb * aColor.a, aColor.a);', @@ -85,7 +89,8 @@ 'uniform sampler2D uSampler;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;', '}' ].join('\n'); @@ -96,7 +101,8 @@ Shader.prototype.constructor = Shader; module.exports = Shader; -Shader.prototype.init = function () { +Shader.prototype.init = function () +{ this.compile(); this.gl.useProgram(this.program); @@ -105,14 +111,18 @@ this.cacheAttributeLocations(Object.keys(this.attributes)); }; -Shader.prototype.cacheUniformLocations = function (keys) { - for (var i = 0; i < keys.length; ++i) { +Shader.prototype.cacheUniformLocations = function (keys) +{ + for (var i = 0; i < keys.length; ++i) + { this.uniforms[keys[i]]._location = this.gl.getUniformLocation(this.program, keys[i]); } }; -Shader.prototype.cacheAttributeLocations = function (keys) { - for (var i = 0; i < keys.length; ++i) { +Shader.prototype.cacheAttributeLocations = function (keys) +{ + for (var i = 0; i < keys.length; ++i) + { this.attributes[keys[i]] = this.gl.getAttribLocation(this.program, keys[i]); } @@ -124,14 +134,16 @@ // 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.attributes.aColor === -1) { + // if (this.attributes.aColor === -1) + { // this.attributes.aColor = 2; // } // End worst hack eva // }; -Shader.prototype.compile = function () { +Shader.prototype.compile = function () +{ var gl = this.gl; var glVertShader = this._glCompile(gl.VERTEX_SHADER, this.vertexSrc); @@ -144,13 +156,15 @@ gl.linkProgram(program); // if linking fails, then log and cleanup - if (!gl.getProgramParameter(program, gl.LINK_STATUS)) { + if (!gl.getProgramParameter(program, gl.LINK_STATUS)) + { window.console.error('Pixi.js Error: Could not initialize shader.'); window.console.error('gl.VALIDATE_STATUS', gl.getProgramParameter(program, gl.VALIDATE_STATUS)); window.console.error('gl.getError()', gl.getError()); // if there is a program info log, log it - if (gl.getProgramInfoLog(program) !== '') { + if (gl.getProgramInfoLog(program) !== '') + { window.console.warn('Pixi.js Warning: gl.getProgramInfoLog()', gl.getProgramInfoLog(program)); } @@ -165,18 +179,21 @@ return (this.program = program); }; -Shader.prototype.syncUniforms = function () { +Shader.prototype.syncUniforms = function () +{ var gl = this.gl; this.textureCount = 1; - for (var key in this.uniforms) { + for (var key in this.uniforms) + { var uniform = this.uniforms[key], location = uniform._location, value = uniform.value, i, il; - switch (uniform.type) { + switch (uniform.type) + { // single int value case 'i': case '1i': @@ -282,7 +299,8 @@ // a Color Value case 'c': - if (typeof value === 'number') { + if (typeof value === 'number') + { value = utils.hex2rgb(value); } @@ -311,11 +329,13 @@ // array of 2D Point objects case 'v2v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(2 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 2] = value[i].x; uniform._array[i * 2 + 1] = value[i].y; } @@ -325,11 +345,13 @@ // array of 3D Point objects case 'v3v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(3 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 3] = value[i].x; uniform._array[i * 3 + 1] = value[i].y; uniform._array[i * 3 + 2] = value[i].z; @@ -341,11 +363,13 @@ // array of 4D Point objects case 'v4v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(4 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 4] = value[i].x; uniform._array[i * 4 + 1] = value[i].y; uniform._array[i * 4 + 2] = value[i].z; @@ -359,7 +383,8 @@ // PIXI.Texture case 't': case 'sampler2D': - if (!uniform.value || !uniform.value.baseTexture || !uniform.value.baseTexture.hasLoaded) { + if (!uniform.value || !uniform.value.baseTexture || !uniform.value.baseTexture.hasLoaded) + { break; } @@ -376,7 +401,8 @@ this.textureCount++; // initialize the texture if we haven't yet - if (!uniform._init) { + if (!uniform._init) + { this.initSampler2D(uniform); uniform._init = true; @@ -394,11 +420,13 @@ * Initialises a Sampler2D uniform (which may only be available later on after initUniforms once the texture has loaded) * */ -Shader.prototype.initSampler2D = function (uniform) { +Shader.prototype.initSampler2D = function (uniform) +{ var gl = this.gl; // Extended texture data - if (uniform.textureData) { + if (uniform.textureData) + { var data = uniform.textureData; // GLTexture = mag linear, min linear_mipmap_linear, wrap repeat + gl.generateMipmap(gl.TEXTURE_2D); @@ -417,14 +445,16 @@ var wrapT = (data.wrapT) ? data.wrapT : gl.CLAMP_TO_EDGE; var format = (data.luminance) ? gl.LUMINANCE : gl.RGBA; - if (data.repeat) { + if (data.repeat) + { wrapS = gl.REPEAT; wrapT = gl.REPEAT; } gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, !!data.flipY); - if (data.width) { + if (data.width) + { var width = (data.width) ? data.width : 512; var height = (data.height) ? data.height : 2; var border = (data.border) ? data.border : 0; @@ -432,7 +462,8 @@ // 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 { + 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); } @@ -448,7 +479,8 @@ * Destroys the shader. * */ -Shader.prototype.destroy = function () { +Shader.prototype.destroy = function () +{ this.gl.deleteProgram(this.program); this.gl = null; @@ -459,13 +491,15 @@ this.fragmentSrc = null; }; -Shader.prototype._glCompile = function (type, src) { +Shader.prototype._glCompile = function (type, src) +{ var shader = this.gl.createShader(type); this.gl.shaderSource(shader, src); this.gl.compileShader(shader); - if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) { + if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) + { window.console.log(this.gl.getShaderInfoLog(shader)); return null; } diff --git a/src/core/renderers/webgl/shaders/StripShader.js b/src/core/renderers/webgl/shaders/StripShader.js index 193f6e1..a7abcc6 100644 --- a/src/core/renderers/webgl/shaders/StripShader.js +++ b/src/core/renderers/webgl/shaders/StripShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function StripShader(gl) { +function StripShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -20,7 +21,8 @@ 'varying vec2 vTextureCoord;', - 'void main(void) {', + '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);', @@ -36,7 +38,8 @@ 'varying vec2 vTextureCoord;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vec2(vTextureCoord.x, vTextureCoord.y)) * alpha;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/utils/FilterTexture.js b/src/core/renderers/webgl/utils/FilterTexture.js index d2c8423..4433d44 100644 --- a/src/core/renderers/webgl/utils/FilterTexture.js +++ b/src/core/renderers/webgl/utils/FilterTexture.js @@ -8,7 +8,8 @@ * @param height {number} the vertical range of the filter * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values */ -function FilterTexture(gl, width, height, scaleMode) { +function FilterTexture(gl, width, height, scaleMode) +{ /** * @member {WebGLContext} */ @@ -59,7 +60,8 @@ * Clears the filter texture. * */ -FilterTexture.prototype.clear = function () { +FilterTexture.prototype.clear = function () +{ var gl = this.gl; gl.clearColor(0,0,0, 0); @@ -72,8 +74,10 @@ * @param width {number} the new width of the texture * @param height {number} the new height of the texture */ -FilterTexture.prototype.resize = function (width, height) { - if (this.width === width && this.height === height) { +FilterTexture.prototype.resize = function (width, height) +{ + if (this.width === width && this.height === height) + { return; } @@ -96,7 +100,8 @@ * Destroys the filter texture. * */ -FilterTexture.prototype.destroy = function () { +FilterTexture.prototype.destroy = function () +{ var gl = this.gl; gl.deleteFramebuffer( this.frameBuffer ); gl.deleteTexture( this.texture ); diff --git a/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js b/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js index c4721e9..a63f4d7 100644 --- a/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js +++ b/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js @@ -14,7 +14,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this sprite batch works for. */ -function WebGLFastSpriteBatch(renderer) { +function WebGLFastSpriteBatch(renderer) +{ /** * The renderer instance this sprite batch operates on. * @@ -91,7 +92,8 @@ */ this.lastIndexCount = 0; - for (var i=0, j=0; i < numIndices; i += 6, j += 4) { + 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; @@ -144,7 +146,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.setupContext(); }); } @@ -157,7 +160,8 @@ * * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLFastSpriteBatch.prototype.setupContext = function () { +WebGLFastSpriteBatch.prototype.setupContext = function () +{ var gl = this.renderer.gl; // create a couple of buffers @@ -177,7 +181,8 @@ /** * @param spriteBatch {SpriteBatch} The SpriteBatch container to prepare for. */ -WebGLFastSpriteBatch.prototype.begin = function (spriteBatch) { +WebGLFastSpriteBatch.prototype.begin = function (spriteBatch) +{ this.shader = this.renderer.shaderManager.fastShader; this.matrix = spriteBatch.worldTransform.toArray(true); @@ -187,33 +192,38 @@ /** */ -WebGLFastSpriteBatch.prototype.end = function () { +WebGLFastSpriteBatch.prototype.end = function () +{ this.flush(); }; /** * @param spriteBatch {SpriteBatch} The SpriteBatch container to render. */ -WebGLFastSpriteBatch.prototype.render = function (spriteBatch) { +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) { + if (!sprite.texture._uvs) + { return; } this.currentBaseTexture = sprite.texture.baseTexture; // check blend mode - if (sprite.blendMode !== this.renderer.blendModeManager.currentBlendMode) { + if (sprite.blendMode !== this.renderer.blendModeManager.currentBlendMode) + { this.flush(); this.renderer.blendModeManager.setBlendMode(sprite.blendMode); } - for (var i=0,j= children.length; i= this.size) { + if (this.currentBatchSize >= this.size) + { this.flush(); } }; @@ -362,29 +379,35 @@ /** * */ -WebGLFastSpriteBatch.prototype.flush = function () { +WebGLFastSpriteBatch.prototype.flush = function () +{ // If the batch is length 0 then return as there is nothing to draw - if (this.currentBatchSize === 0) { + if (this.currentBatchSize === 0) + { return; } var gl = this.renderer.gl; // bind the current texture - if (!this.currentBaseTexture._glTextures[gl.id]) { + if (!this.currentBaseTexture._glTextures[gl.id]) + { this.renderer.updateTexture(this.currentBaseTexture, gl); } //TODO-SHOUD THIS BE ELSE??!?!?! - else { + else + { gl.bindTexture(gl.TEXTURE_2D, this.currentBaseTexture._glTextures[gl.id]); } // upload the verts to the buffer - if (this.currentBatchSize > ( this.size * 0.5 ) ) { + if (this.currentBatchSize > ( this.size * 0.5 ) ) + { gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); } - else { + else + { var view = this.vertices.subarray(0, this.currentBatchSize * this.vertByteSize); gl.bufferSubData(gl.ARRAY_BUFFER, 0, view); @@ -405,14 +428,16 @@ * Ends the batch and flushes * */ -WebGLFastSpriteBatch.prototype.stop = function () { +WebGLFastSpriteBatch.prototype.stop = function () +{ this.flush(); }; /** * */ -WebGLFastSpriteBatch.prototype.start = function () { +WebGLFastSpriteBatch.prototype.start = function () +{ var gl = this.renderer.gl; // bind the main texture diff --git a/src/core/renderers/webgl/utils/WebGLGraphics.js b/src/core/renderers/webgl/utils/WebGLGraphics.js index 55f4911..ab8f46e 100644 --- a/src/core/renderers/webgl/utils/WebGLGraphics.js +++ b/src/core/renderers/webgl/utils/WebGLGraphics.js @@ -19,7 +19,8 @@ * @param graphics {Graphics} * @param renderer {WebGLRenderer} */ -WebGLGraphics.renderGraphics = function (graphics, renderer) {//projection, offset) { +WebGLGraphics.renderGraphics = function (graphics, renderer) {//projection, offset) +{ var gl = renderer.gl; var projection = renderer.projection, @@ -27,7 +28,8 @@ shader = renderer.shaderManager.primitiveShader, webGLData; - if (graphics.dirty) { + if (graphics.dirty) + { WebGLGraphics.updateGraphics(graphics, gl); } @@ -35,8 +37,10 @@ // This could be speeded up for sure! - for (var i = 0; i < webGL.data.length; i++) { - if (webGL.data[i].mode === 1) { + for (var i = 0; i < webGL.data.length; i++) + { + if (webGL.data[i].mode === 1) + { webGLData = webGL.data[i]; renderer.stencilManager.pushStencil(graphics, webGLData, renderer); @@ -46,7 +50,8 @@ renderer.stencilManager.popStencil(graphics, webGLData, renderer); } - else { + else + { webGLData = webGL.data[i]; @@ -84,12 +89,14 @@ * @param graphicsData {Graphics} The graphics object to update * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLGraphics.updateGraphics = function (graphics, gl) { +WebGLGraphics.updateGraphics = function (graphics, gl) +{ // get the contexts graphics object var webGL = graphics._webGL[gl.id]; // if the graphics object does not exist in the webGL context time to create it! - if (!webGL) { + if (!webGL) + { webGL = graphics._webGL[gl.id] = {lastIndex:0, data:[], gl:gl}; } @@ -99,11 +106,13 @@ var i; // if the user cleared the graphics object we will need to clear every object - if (graphics.clearDirty) { + if (graphics.clearDirty) + { graphics.clearDirty = false; // lop through and return all the webGLDatas to the object pool so than can be reused later on - for (i = 0; i < webGL.data.length; i++) { + for (i = 0; i < webGL.data.length; i++) + { var graphicsData = webGL.data[i]; graphicsData.reset(); WebGLGraphics.graphicsDataPool.push( graphicsData ); @@ -119,58 +128,72 @@ // loop through the graphics datas and construct each one.. // if the object is a complex fill then the new stencil buffer technique will be used // other wise graphics objects will be pushed into a batch.. - for (i = webGL.lastIndex; i < graphics.graphicsData.length; i++) { + for (i = webGL.lastIndex; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { // need to add the points the the graphics object.. data.points = data.shape.points.slice(); - if (data.shape.closed) { + if (data.shape.closed) + { // close the poly if the value is true! - if (data.points[0] !== data.points[data.points.length-2] || data.points[1] !== data.points[data.points.length-1]) { + if (data.points[0] !== data.points[data.points.length-2] || data.points[1] !== data.points[data.points.length-1]) + { data.points.push(data.points[0], data.points[1]); } } // MAKE SURE WE HAVE THE CORRECT TYPE.. - if (data.fill) { - if (data.points.length >= 6) { - if (data.points.length < 6 * 2) { + if (data.fill) + { + if (data.points.length >= 6) + { + if (data.points.length < 6 * 2) + { webGLData = WebGLGraphics.switchMode(webGL, 0); var canDrawUsingSimple = WebGLGraphics.buildPoly(data, webGLData); // console.log(canDrawUsingSimple); - if (!canDrawUsingSimple) { + if (!canDrawUsingSimple) + { // console.log("<>>>") webGLData = WebGLGraphics.switchMode(webGL, 1); WebGLGraphics.buildComplexPoly(data, webGLData); } } - else { + else + { webGLData = WebGLGraphics.switchMode(webGL, 1); WebGLGraphics.buildComplexPoly(data, webGLData); } } } - if (data.lineWidth > 0) { + if (data.lineWidth > 0) + { webGLData = WebGLGraphics.switchMode(webGL, 0); WebGLGraphics.buildLine(data, webGLData); } } - else { + else + { webGLData = WebGLGraphics.switchMode(webGL, 0); - if (data.type === CONST.SHAPES.RECT) { + if (data.type === CONST.SHAPES.RECT) + { WebGLGraphics.buildRectangle(data, webGLData); } - else if (data.type === CONST.SHAPES.CIRC || data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.CIRC || data.type === CONST.SHAPES.ELIP) + { WebGLGraphics.buildCircle(data, webGLData); } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { WebGLGraphics.buildRoundedRectangle(data, webGLData); } } @@ -179,10 +202,12 @@ } // upload all the dirty data... - for (i = 0; i < webGL.data.length; i++) { + for (i = 0; i < webGL.data.length; i++) + { webGLData = webGL.data[i]; - if (webGLData.dirty) { + if (webGLData.dirty) + { webGLData.upload(); } } @@ -194,18 +219,22 @@ * @param webGL {WebGLContext} * @param type {number} */ -WebGLGraphics.switchMode = function (webGL, type) { +WebGLGraphics.switchMode = function (webGL, type) +{ var webGLData; - if (!webGL.data.length) { + if (!webGL.data.length) + { webGLData = WebGLGraphics.graphicsDataPool.pop() || new WebGLGraphicsData(webGL.gl); webGLData.mode = type; webGL.data.push(webGLData); } - else { + else + { webGLData = webGL.data[webGL.data.length-1]; - if (webGLData.mode !== type || type === 1) { + if (webGLData.mode !== type || type === 1) + { webGLData = WebGLGraphics.graphicsDataPool.pop() || new WebGLGraphicsData(webGL.gl); webGLData.mode = type; webGL.data.push(webGLData); @@ -225,7 +254,8 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildRectangle = function (graphicsData, webGLData) { +WebGLGraphics.buildRectangle = function (graphicsData, webGLData) +{ // --- // // need to convert points to a nice regular data // @@ -235,7 +265,8 @@ var width = rectData.width; var height = rectData.height; - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -265,7 +296,8 @@ indices.push(vertPos, vertPos, vertPos+1, vertPos+2, vertPos+3, vertPos+3); } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = [x, y, @@ -289,7 +321,8 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildRoundedRectangle = function (graphicsData, webGLData) { +WebGLGraphics.buildRoundedRectangle = function (graphicsData, webGLData) +{ var rrectData = graphicsData.shape; var x = rrectData.x; var y = rrectData.y; @@ -305,7 +338,8 @@ recPoints = recPoints.concat(WebGLGraphics.quadraticBezierCurve(x + width, y + radius, x + width, y, x + width - radius, y)); recPoints = recPoints.concat(WebGLGraphics.quadraticBezierCurve(x + radius, y, x, y, x, y + radius)); - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -323,7 +357,8 @@ // var i = 0; - for (i = 0; i < triangles.length; i+=3) { + for (i = 0; i < triangles.length; i+=3) + { indices.push(triangles[i] + vecPos); indices.push(triangles[i] + vecPos); indices.push(triangles[i+1] + vecPos); @@ -332,12 +367,14 @@ } - for (i = 0; i < recPoints.length; i++) { + for (i = 0; i < recPoints.length; i++) + { verts.push(recPoints[i], recPoints[++i], r, g, b, alpha); } } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = recPoints; @@ -362,7 +399,8 @@ * @param toY {number} Destination point y * @return {number[]} */ -WebGLGraphics.quadraticBezierCurve = function (fromX, fromY, cpX, cpY, toX, toY) { +WebGLGraphics.quadraticBezierCurve = function (fromX, fromY, cpX, cpY, toX, toY) +{ var xa, ya, @@ -373,14 +411,16 @@ n = 20, points = []; - function getPt(n1 , n2, perc) { + function getPt(n1 , n2, perc) + { var diff = n2 - n1; return n1 + ( diff * perc ); } var j = 0; - for (var i = 0; i <= n; i++ ) { + for (var i = 0; i <= n; i++ ) + { j = i / n; // The Green Line @@ -406,7 +446,8 @@ * @param graphicsData {Graphics} The graphics object to draw * @param webGLData {object} */ -WebGLGraphics.buildCircle = function (graphicsData, webGLData) { +WebGLGraphics.buildCircle = function (graphicsData, webGLData) +{ // need to convert points to a nice regular data var circleData = graphicsData.shape; var x = circleData.x; @@ -415,11 +456,13 @@ var height; // TODO - bit hacky?? - if (graphicsData.type === CONST.SHAPES.CIRC) { + if (graphicsData.type === CONST.SHAPES.CIRC) + { width = circleData.radius; height = circleData.radius; } - else { + else + { width = circleData.width; height = circleData.height; } @@ -429,7 +472,8 @@ var i = 0; - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -444,7 +488,8 @@ indices.push(vecPos); - for (i = 0; i < totalSegs + 1 ; i++) { + for (i = 0; i < totalSegs + 1 ; i++) + { verts.push(x,y, r, g, b, alpha); verts.push(x + Math.sin(seg * i) * width, @@ -457,12 +502,14 @@ indices.push(vecPos-1); } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = []; - for (i = 0; i < totalSegs + 1; i++) { + for (i = 0; i < totalSegs + 1; i++) + { graphicsData.points.push(x + Math.sin(seg * i) * width, y + Math.cos(seg * i) * height); } @@ -481,18 +528,22 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildLine = function (graphicsData, webGLData) { +WebGLGraphics.buildLine = function (graphicsData, webGLData) +{ // TODO OPTIMISE! var i = 0; var points = graphicsData.points; - if (points.length === 0) { + if (points.length === 0) + { return; } // if the line width is an odd number add 0.5 to align to a whole pixel - if (graphicsData.lineWidth%2) { - for (i = 0; i < points.length; i++) { + if (graphicsData.lineWidth%2) + { + for (i = 0; i < points.length; i++) + { points[i] += 0.5; } } @@ -502,7 +553,8 @@ var lastPoint = new math.Point(points[points.length - 2], points[points.length - 1]); // if the first point is the last point - gonna have issues :) - if (firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) { + if (firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) + { // need to clone as we are going to slightly modify the shape.. points = points.slice(); @@ -562,7 +614,8 @@ verts.push(p1x + perpx , p1y + perpy, r, g, b, alpha); - for (i = 1; i < length-1; i++) { + for (i = 1; i < length-1; i++) + { p1x = points[(i-1)*2]; p1y = points[(i-1)*2 + 1]; @@ -599,7 +652,8 @@ denom = a1*b2 - a2*b1; - if (Math.abs(denom) < 0.1 ) { + if (Math.abs(denom) < 0.1 ) + { denom+=10.1; verts.push(p2x - perpx , p2y - perpy, @@ -618,7 +672,8 @@ pdist = (px -p2x) * (px -p2x) + (py -p2y) + (py -p2y); - if (pdist > 140 * 140) { + if (pdist > 140 * 140) + { perp3x = perpx - perp2x; perp3y = perpy - perp2y; @@ -639,7 +694,8 @@ indexCount++; } - else { + else + { verts.push(px , py); verts.push(r, g, b, alpha); @@ -672,7 +728,8 @@ indices.push(indexStart); - for (i = 0; i < indexCount; i++) { + for (i = 0; i < indexCount; i++) + { indices.push(indexStart++); } @@ -687,11 +744,13 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildComplexPoly = function (graphicsData, webGLData) { +WebGLGraphics.buildComplexPoly = function (graphicsData, webGLData) +{ //TODO - no need to copy this as it gets turned into a FLoat32Array anyways.. var points = graphicsData.points.slice(); - if (points.length < 6) { + if (points.length < 6) + { return; } @@ -711,7 +770,8 @@ var x,y; // get size.. - for (var i = 0; i < points.length; i+=2) { + for (var i = 0; i < points.length; i+=2) + { x = points[i]; y = points[i+1]; @@ -732,7 +792,8 @@ //TODO - this aint needed! var length = points.length / 2; - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { indices.push( i ); } @@ -746,10 +807,12 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildPoly = function (graphicsData, webGLData) { +WebGLGraphics.buildPoly = function (graphicsData, webGLData) +{ var points = graphicsData.points; - if (points.length < 6) { + if (points.length < 6) + { return; } // get first and last point.. figure out the middle! @@ -767,7 +830,8 @@ var triangles = utils.PolyK.Triangulate(points); - if (!triangles) { + if (!triangles) + { return false; } @@ -775,7 +839,8 @@ var i = 0; - for (i = 0; i < triangles.length; i+=3) { + for (i = 0; i < triangles.length; i+=3) + { indices.push(triangles[i] + vertPos); indices.push(triangles[i] + vertPos); indices.push(triangles[i+1] + vertPos); @@ -783,7 +848,8 @@ indices.push(triangles[i+2] + vertPos); } - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { verts.push(points[i * 2], points[i * 2 + 1], r, g, b, alpha); } diff --git a/src/core/renderers/webgl/utils/WebGLGraphicsData.js b/src/core/renderers/webgl/utils/WebGLGraphicsData.js index c56d05e..c739ba7 100644 --- a/src/core/renderers/webgl/utils/WebGLGraphicsData.js +++ b/src/core/renderers/webgl/utils/WebGLGraphicsData.js @@ -2,7 +2,8 @@ * @class * @private */ -function WebGLGraphicsData(gl) { +function WebGLGraphicsData(gl) +{ this.gl = gl; //TODO does this need to be split before uploding?? @@ -22,7 +23,8 @@ /** * */ -WebGLGraphicsData.prototype.reset = function () { +WebGLGraphicsData.prototype.reset = function () +{ this.points.length = 0; this.indices.length = 0; }; @@ -30,7 +32,8 @@ /** * */ -WebGLGraphicsData.prototype.upload = function () { +WebGLGraphicsData.prototype.upload = function () +{ var gl = this.gl; // this.lastIndex = graphics.graphicsData.length; diff --git a/src/core/renderers/webgl/utils/WebGLSpriteBatch.js b/src/core/renderers/webgl/utils/WebGLSpriteBatch.js index 96eaa52..55befbb 100644 --- a/src/core/renderers/webgl/utils/WebGLSpriteBatch.js +++ b/src/core/renderers/webgl/utils/WebGLSpriteBatch.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this sprite batch works for. */ -function WebGLSpriteBatch(renderer) { +function WebGLSpriteBatch(renderer) +{ /** * * @@ -88,7 +89,8 @@ */ this.lastIndexCount = 0; - for (var i=0, j=0; i < numIndices; i += 6, j += 4) { + 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; @@ -162,7 +164,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.setupContext(); }); } @@ -173,7 +176,8 @@ /** * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLSpriteBatch.prototype.setupContext = function () { +WebGLSpriteBatch.prototype.setupContext = function () +{ var gl = this.renderer.gl; // setup default shader @@ -198,7 +202,8 @@ /** * */ -WebGLSpriteBatch.prototype.begin = function () { +WebGLSpriteBatch.prototype.begin = function () +{ // this.shader = this.renderer.shaderManager.defaultShader; this.start(); @@ -206,19 +211,22 @@ /** */ -WebGLSpriteBatch.prototype.end = function () { +WebGLSpriteBatch.prototype.end = function () +{ this.flush(); }; /** * @param sprite {Sprite} the sprite to render when using this spritebatch */ -WebGLSpriteBatch.prototype.render = function (sprite) { +WebGLSpriteBatch.prototype.render = function (sprite) +{ var texture = sprite.texture; //TODO set blend modes.. // check texture.. - if (this.currentBatchSize >= this.size) { + if (this.currentBatchSize >= this.size) + { this.flush(); this.currentBaseTexture = texture.baseTexture; } @@ -227,7 +235,8 @@ var uvs = texture._uvs; // if the uvs have not updated then no point rendering just yet! - if (!uvs) { + if (!uvs) + { return; } @@ -237,7 +246,8 @@ var w0, w1, h0, h1; - if (texture.trim) { + 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; @@ -248,7 +258,8 @@ h0 = h1 + texture.crop.height; } - else { + else + { w0 = (texture.frame.width ) * (1-aX); w1 = (texture.frame.width ) * -aX; @@ -272,7 +283,8 @@ var colors = this.colors; var positions = this.positions; - if (this.renderer.roundPixels) { + if (this.renderer.roundPixels) + { // xy positions[index] = a * w1 + c * h1 + tx | 0; positions[index+1] = d * h1 + b * w1 + ty | 0; @@ -289,7 +301,8 @@ positions[index+15] = a * w1 + c * h0 + tx | 0; positions[index+16] = d * h0 + b * w1 + ty | 0; } - else { + else + { // xy positions[index] = a * w1 + c * h1 + tx; positions[index+1] = d * h1 + b * w1 + ty; @@ -338,11 +351,13 @@ * * @param sprite {TilingSprite} the tilingSprite to render */ -WebGLSpriteBatch.prototype.renderTilingSprite = function (tilingSprite) { +WebGLSpriteBatch.prototype.renderTilingSprite = function (tilingSprite) +{ var texture = tilingSprite.tilingTexture; // check texture.. - if (this.currentBatchSize >= this.size) { + if (this.currentBatchSize >= this.size) + { //return; this.flush(); this.currentBaseTexture = texture.baseTexture; @@ -351,7 +366,8 @@ // set the textures uvs temporarily // TODO create a separate texture so that we can tile part of a texture - if (!tilingSprite._uvs) { + if (!tilingSprite._uvs) + { tilingSprite._uvs = new TextureUvs(); } @@ -454,16 +470,19 @@ * Renders the content and empties the current batch. * */ -WebGLSpriteBatch.prototype.flush = function () { +WebGLSpriteBatch.prototype.flush = function () +{ // If the batch is length 0 then return as there is nothing to draw - if (this.currentBatchSize === 0) { + if (this.currentBatchSize === 0) + { return; } var gl = this.renderer.gl; var shader; - if (this.dirty) { + if (this.dirty) + { this.dirty = false; // bind the main texture gl.activeTexture(gl.TEXTURE0); @@ -482,10 +501,12 @@ } // upload the verts to the buffer - if (this.currentBatchSize > ( this.size * 0.5 ) ) { + if (this.currentBatchSize > ( this.size * 0.5 ) ) + { gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); } - else { + else + { var view = this.positions.subarray(0, this.currentBatchSize * this.vertByteSize); gl.bufferSubData(gl.ARRAY_BUFFER, 0, view); } @@ -502,7 +523,8 @@ var shaderSwap = false; var sprite; - for (var i = 0, j = this.currentBatchSize; i < j; i++) { + for (var i = 0, j = this.currentBatchSize; i < j; i++) + { sprite = this.sprites[i]; @@ -513,24 +535,28 @@ blendSwap = currentBlendMode !== nextBlendMode; shaderSwap = currentShader !== nextShader; // should I use uuidS??? - if (currentBaseTexture !== nextTexture || blendSwap || shaderSwap) { + if (currentBaseTexture !== nextTexture || blendSwap || shaderSwap) + { this.renderBatch(currentBaseTexture, batchSize, start); start = i; batchSize = 0; currentBaseTexture = nextTexture; - if (blendSwap) { + if (blendSwap) + { currentBlendMode = nextBlendMode; this.renderer.blendModeManager.setBlendMode( currentBlendMode ); } - if (shaderSwap) { + if (shaderSwap) + { currentShader = nextShader; shader = currentShader.shaders ? currentShader.shaders[gl.id] : currentShader; - if (!shader) { + if (!shader) + { shader = new Shader(gl, null, currentShader.fragmentSrc, currentShader.uniforms); currentShader.shaders[gl.id] = shader; } @@ -538,7 +564,8 @@ // set shader function??? this.renderer.shaderManager.setShader(shader); - if (shader.dirty) { + if (shader.dirty) + { shader.syncUniforms(); } @@ -569,17 +596,21 @@ * @param size {number} * @param startIndex {number} */ -WebGLSpriteBatch.prototype.renderBatch = function (texture, size, startIndex) { - if (size === 0) { +WebGLSpriteBatch.prototype.renderBatch = function (texture, size, startIndex) +{ + if (size === 0) + { return; } var gl = this.renderer.gl; - if (!texture._glTextures[gl.id]) { + if (!texture._glTextures[gl.id]) + { this.renderer.updateTexture(texture); } - else { + else + { // bind the current texture gl.bindTexture(gl.TEXTURE_2D, texture._glTextures[gl.id]); } @@ -594,7 +625,8 @@ /** * */ -WebGLSpriteBatch.prototype.stop = function () { +WebGLSpriteBatch.prototype.stop = function () +{ this.flush(); this.dirty = true; }; @@ -602,7 +634,8 @@ /** * */ -WebGLSpriteBatch.prototype.start = function () { +WebGLSpriteBatch.prototype.start = function () +{ this.dirty = true; }; @@ -610,7 +643,8 @@ * Destroys the SpriteBatch. * */ -WebGLSpriteBatch.prototype.destroy = function () { +WebGLSpriteBatch.prototype.destroy = function () +{ this.renderer.gl.deleteBuffer(this.vertexBuffer); this.renderer.gl.deleteBuffer(this.indexBuffer); diff --git a/src/core/textures/BaseTexture.js b/src/core/textures/BaseTexture.js index 2bf77d4..513d358 100644 --- a/src/core/textures/BaseTexture.js +++ b/src/core/textures/BaseTexture.js @@ -10,7 +10,8 @@ * @param source {Image|Canvas} the source object of the texture. * @param [scaleMode=scaleModes.DEFAULT] {number} See {@link scaleModes} for possible values */ -function BaseTexture(source, scaleMode) { +function BaseTexture(source, scaleMode) +{ this.uuid = utils.uuid(); /** @@ -123,7 +124,8 @@ this._needsUpdate = false; // if no source passed don't try to load - if (source) { + if (source) + { this.loadSource(source); } @@ -149,13 +151,16 @@ Object.defineProperties(BaseTexture.prototype, { needsUpdate: { - get: function () { + get: function () + { return this._needsUpdate; }, - set: function (val) { + set: function (val) + { this._needsUpdate = val; - if (val) { + if (val) + { this.emit('update', this); } } @@ -171,9 +176,11 @@ * * The logic state after calling `loadSource` directly or indirectly (eg. `fromImage`, `new BaseTexture`) is: * - * if (texture.hasLoaded) { + * if (texture.hasLoaded) + { * // texture ready for use - * } else if (texture.isLoading) { + * } else if (texture.isLoading) + { * // listen to 'loaded' and/or 'error' events on texture * } else { * // not loading, not going to load UNLESS the source is reloaded @@ -183,12 +190,14 @@ * @protected * @param source {Image|Canvas} the source object of the texture. */ -BaseTexture.prototype.loadSource = function (source) { +BaseTexture.prototype.loadSource = function (source) +{ var wasLoading = this.isLoading; this.hasLoaded = false; this.isLoading = false; - if (wasLoading && this.source) { + if (wasLoading && this.source) + { this.source.onload = null; this.source.onerror = null; } @@ -196,20 +205,24 @@ this.source = source; // Apply source if loaded. Otherwise setup appropriate loading monitors. - if ((this.source.complete || this.source.getContext) && this.source.width && this.source.height) { + if ((this.source.complete || this.source.getContext) && this.source.width && this.source.height) + { this._sourceLoaded(); } - else if(!source.getContext) { + else if(!source.getContext) + { // Image fail / not ready this.isLoading = true; var scope = this; - source.onload = function () { + source.onload = function () + { source.onload = null; source.onerror = null; - if(!scope.isLoading) { + if(!scope.isLoading) + { return; } @@ -219,11 +232,13 @@ scope.emit('loaded', scope); }; - source.onerror = function () { + source.onerror = function () + { source.onload = null; source.onerror = null; - if(!scope.isLoading) { + if(!scope.isLoading) + { return; } @@ -234,24 +249,29 @@ // Per http://www.w3.org/TR/html5/embedded-content-0.html#the-img-element // "The value of `complete` can thus change while a script is executing." // So complete needs to be re-checked after the callbacks have been added.. - if (source.complete) { + if (source.complete) + { this.isLoading = false; // ..and if we're complete now, no need for callbacks source.onload = null; source.onerror = null; - if (source.width && source.height) { + if (source.width && source.height) + { this._sourceLoaded(); // If any previous subscribers possible - if (wasLoading) { + if (wasLoading) + { this.emit('loaded', this); } } - else { + else + { // If any previous subscribers possible - if (wasLoading) { + if (wasLoading) + { this.emit('error', this); } } @@ -265,7 +285,8 @@ * * @private */ -BaseTexture.prototype._sourceLoaded = function () { +BaseTexture.prototype._sourceLoaded = function () +{ this.hasLoaded = true; this.width = this.source.naturalWidth || this.source.width; @@ -278,16 +299,20 @@ * Destroys this base texture * */ -BaseTexture.prototype.destroy = function () { - if (this.imageUrl) { +BaseTexture.prototype.destroy = function () +{ + if (this.imageUrl) + { delete utils.BaseTextureCache[this.imageUrl]; delete utils.TextureCache[this.imageUrl]; this.imageUrl = null; - if (!navigator.isCocoonJS) { + if (!navigator.isCocoonJS) + { this.source.src = ''; } } - else if (this.source && this.source._pixiId) { + else if (this.source && this.source._pixiId) + { delete utils.BaseTextureCache[this.source._pixiId]; } this.source = null; @@ -301,7 +326,8 @@ * memory again. * */ -BaseTexture.prototype.dispose = function () { +BaseTexture.prototype.dispose = function () +{ this.emit('dispose', this); }; @@ -311,7 +337,8 @@ * * @param newSrc {string} the path of the image */ -BaseTexture.prototype.updateSourceImage = function (newSrc) { +BaseTexture.prototype.updateSourceImage = function (newSrc) +{ this.source.src = newSrc; this.loadSource(this.source); }; @@ -326,18 +353,22 @@ * @param [scaleMode=scaleModes.DEFAULT] {number} See {@link scaleModes} for possible values * @return BaseTexture */ -BaseTexture.fromImage = function (imageUrl, crossorigin, scaleMode) { +BaseTexture.fromImage = function (imageUrl, crossorigin, scaleMode) +{ var baseTexture = utils.BaseTextureCache[imageUrl]; - if (crossorigin === undefined && imageUrl.indexOf('data:') !== 0) { + if (crossorigin === undefined && imageUrl.indexOf('data:') !== 0) + { crossorigin = true; } - if (!baseTexture) { + if (!baseTexture) + { // new Image() breaks tex loading in some versions of Chrome. // See https://code.google.com/p/chromium/issues/detail?id=238071 var image = new Image();//document.createElement('img'); - if (crossorigin) { + if (crossorigin) + { image.crossOrigin = ''; } @@ -347,7 +378,8 @@ utils.BaseTextureCache[imageUrl] = baseTexture; // if there is an @2x at the end of the url we are going to assume its a highres image - if ( imageUrl.indexOf(CONST.RETINA_PREFIX + '.') !== -1) { + if ( imageUrl.indexOf(CONST.RETINA_PREFIX + '.') !== -1) + { baseTexture.resolution = 2; } } @@ -363,14 +395,17 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return BaseTexture */ -BaseTexture.fromCanvas = function (canvas, scaleMode) { - if (!canvas._pixiId) { +BaseTexture.fromCanvas = function (canvas, scaleMode) +{ + if (!canvas._pixiId) + { canvas._pixiId = 'canvas_' + utils.uuid(); } var baseTexture = utils.BaseTextureCache[canvas._pixiId]; - if (!baseTexture) { + if (!baseTexture) + { baseTexture = new BaseTexture(canvas, scaleMode); utils.BaseTextureCache[canvas._pixiId] = baseTexture; } diff --git a/src/core/textures/RenderTexture.js b/src/core/textures/RenderTexture.js index 6dad20f..53ae796 100644 --- a/src/core/textures/RenderTexture.js +++ b/src/core/textures/RenderTexture.js @@ -46,8 +46,10 @@ * @param [scaleMode] {number} See {@link scaleModes} for possible values * @param [resolution=1] {number} The resolution of the texture being generated */ -function RenderTexture(renderer, width, height, scaleMode, resolution) { - if (!renderer) { +function RenderTexture(renderer, width, height, scaleMode, resolution) +{ + if (!renderer) + { throw new Error('Unable to create RenderTexture, you must pass a renderer into the constructor.'); } @@ -133,7 +135,8 @@ */ this.renderer = renderer; - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { var gl = this.renderer.gl; this.textureBuffer = new FilterTexture(gl, this.width * this.resolution, this.height * this.resolution, this.baseTexture.scaleMode); @@ -142,7 +145,8 @@ this.render = this.renderWebGL; this.projection = new math.Point(this.width*0.5, -this.height*0.5); } - else { + else + { this.render = this.renderCanvas; this.textureBuffer = new CanvasBuffer(this.width* this.resolution, this.height* this.resolution); this.baseTexture.source = this.textureBuffer.canvas; @@ -167,8 +171,10 @@ * @param height {number} The height to resize to. * @param updateBase {boolean} Should the baseTexture.width and height values be resized as well? */ -RenderTexture.prototype.resize = function (width, height, updateBase) { - if (width === this.width && height === this.height) { +RenderTexture.prototype.resize = function (width, height, updateBase) +{ + if (width === this.width && height === this.height) + { return; } @@ -177,17 +183,20 @@ this.width = this.frame.width = this.crop.width = width; this.height = this.frame.height = this.crop.height = height; - if (updateBase) { + if (updateBase) + { this.baseTexture.width = this.width; this.baseTexture.height = this.height; } - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { this.projection.x = this.width / 2; this.projection.y = -this.height / 2; } - if (!this.valid) { + if (!this.valid) + { return; } @@ -198,12 +207,15 @@ * Clears the RenderTexture. * */ -RenderTexture.prototype.clear = function () { - if (!this.valid) { +RenderTexture.prototype.clear = function () +{ + if (!this.valid) + { return; } - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { this.renderer.gl.bindFramebuffer(this.renderer.gl.FRAMEBUFFER, this.textureBuffer.frameBuffer); } @@ -220,19 +232,23 @@ * @param [restoreWorldTransform=true] {boolean} If true the displayObject's worldTransform/worldAlpha and all children * transformations will be restored. Not restoring this information will be a little faster. */ -RenderTexture.prototype.renderWebGL = function (displayObject, matrix, clear, restoreWorldTransform) { - if (!this.valid) { +RenderTexture.prototype.renderWebGL = function (displayObject, matrix, clear, restoreWorldTransform) +{ + if (!this.valid) + { return; } - if (typeof restoreWorldTransform === 'undefined') { + if (typeof restoreWorldTransform === 'undefined') + { restoreWorldTransform = true; } var tempAlpha, tempTransform; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { tempAlpha = displayObject.worldAlpha; tempTransform = displayObject.worldTransform.toArray(); } @@ -245,7 +261,8 @@ wt.identity(); wt.translate(0, this.projection.y * 2); - if (matrix) { + if (matrix) + { wt.append(matrix); } @@ -258,7 +275,8 @@ var children = displayObject.children; var i, j; - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } @@ -269,7 +287,8 @@ gl.bindFramebuffer(gl.FRAMEBUFFER, this.textureBuffer.frameBuffer ); - if (clear) { + if (clear) + { this.textureBuffer.clear(); } @@ -279,11 +298,13 @@ this.renderer.spriteBatch.dirty = true; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { displayObject.worldAlpha = tempAlpha; displayObject.worldTransform.fromArray(tempTransform); - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } } @@ -300,26 +321,31 @@ * @param [restoreWorldTransform=true] {boolean} If true the displayObject's worldTransform/worldAlpha and all children * transformations will be restored. Not restoring this information will be a little faster. */ -RenderTexture.prototype.renderCanvas = function (displayObject, matrix, clear, restoreWorldTransform) { - if (!this.valid) { +RenderTexture.prototype.renderCanvas = function (displayObject, matrix, clear, restoreWorldTransform) +{ + if (!this.valid) + { return; } - if (typeof restoreWorldTransform === 'undefined') { + if (typeof restoreWorldTransform === 'undefined') + { restoreWorldTransform = true; } var tempAlpha, tempTransform; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { tempAlpha = displayObject.worldAlpha; tempTransform = displayObject.worldTransform.toArray(); } var wt = displayObject.worldTransform; wt.identity(); - if (matrix) { + if (matrix) + { wt.append(matrix); } @@ -330,11 +356,13 @@ var children = displayObject.children; var i, j; - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } - if (clear) { + if (clear) + { this.textureBuffer.clear(); } @@ -348,11 +376,13 @@ this.renderer.resolution = realResolution; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { displayObject.worldAlpha = tempAlpha; displayObject.worldTransform.fromArray(tempTransform); - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } } @@ -363,7 +393,8 @@ * * @return {Image} */ -RenderTexture.prototype.getImage = function () { +RenderTexture.prototype.getImage = function () +{ var image = new Image(); image.src = this.getBase64(); return image; @@ -374,7 +405,8 @@ * * @return {string} A base64 encoded string of the texture. */ -RenderTexture.prototype.getBase64 = function () { +RenderTexture.prototype.getBase64 = function () +{ return this.getCanvas().toDataURL(); }; @@ -383,8 +415,10 @@ * * @return {HTMLCanvasElement} A Canvas element with the texture rendered on. */ -RenderTexture.prototype.getCanvas = function () { - if (this.renderer.type === CONST.WEBGL_RENDERER) { +RenderTexture.prototype.getCanvas = function () +{ + if (this.renderer.type === CONST.WEBGL_RENDERER) + { var gl = this.renderer.gl; var width = this.textureBuffer.width; var height = this.textureBuffer.height; @@ -403,7 +437,8 @@ return tempCanvas.canvas; } - else { + else + { return this.textureBuffer.canvas; } }; diff --git a/src/core/textures/Texture.js b/src/core/textures/Texture.js index 3c65909..e97f0aa 100644 --- a/src/core/textures/Texture.js +++ b/src/core/textures/Texture.js @@ -17,7 +17,8 @@ * @param [crop] {Rectangle} The area of original texture * @param [trim] {Rectangle} Trimmed texture rectangle */ -function Texture(baseTexture, frame, crop, trim) { +function Texture(baseTexture, frame, crop, trim) +{ /** * Does this Texture have any frame data assigned to it? * @@ -25,12 +26,14 @@ */ this.noFrame = false; - if (!frame) { + if (!frame) + { this.noFrame = true; frame = new math.Rectangle(0, 0, 1, 1); } - if (baseTexture instanceof Texture) { + if (baseTexture instanceof Texture) + { baseTexture = baseTexture.baseTexture; } @@ -100,13 +103,16 @@ */ this.crop = crop || new math.Rectangle(0, 0, 1, 1); - if (baseTexture.hasLoaded) { - if (this.noFrame) { + if (baseTexture.hasLoaded) + { + if (this.noFrame) + { frame = new math.Rectangle(0, 0, baseTexture.width, baseTexture.height); } this.frame = frame; } - else { + else + { baseTexture.addEventListener('loaded', this.onBaseTextureLoaded.bind(this)); } } @@ -118,19 +124,23 @@ Object.defineProperties(Texture.prototype, { needsUpdate: { - get: function () { + get: function () + { return this.baseTexture.needsUpdate; }, - set: function (val) { + set: function (val) + { this.baseTexture.needsUpdate = val; } }, frame: { - get: function () { + get: function () + { return this._frame; }, - set: function (frame) { + set: function (frame) + { this._frame = frame; this.noFrame = false; @@ -143,20 +153,23 @@ 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 (!this.trim && (frame.x + frame.width > this.baseTexture.width || frame.y + frame.height > this.baseTexture.height)) + { throw new Error('Texture Error: frame does not fit inside the base Texture dimensions ' + this); } this.valid = frame && frame.width && frame.height && this.baseTexture.source && this.baseTexture.hasLoaded; - if (this.trim) { + 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) { + if (this.valid) + { this._updateUvs(); } } @@ -168,11 +181,13 @@ * * @private */ -Texture.prototype.onBaseTextureLoaded = function () { +Texture.prototype.onBaseTextureLoaded = function () +{ var baseTexture = this.baseTexture; baseTexture.removeEventListener('loaded', this.onLoaded); - if (this.noFrame) { + if (this.noFrame) + { this.frame = new math.Rectangle(0, 0, baseTexture.width, baseTexture.height); } @@ -184,8 +199,10 @@ * * @param destroyBase {boolean} Whether to destroy the base texture as well */ -Texture.prototype.destroy = function (destroyBase) { - if (destroyBase) { +Texture.prototype.destroy = function (destroyBase) +{ + if (destroyBase) + { this.baseTexture.destroy(); } @@ -197,8 +214,10 @@ * * @private */ -Texture.prototype._updateUvs = function () { - if (!this._uvs) { +Texture.prototype._updateUvs = function () +{ + if (!this._uvs) + { this._uvs = new TextureUvs(); } @@ -229,10 +248,12 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return Texture */ -Texture.fromImage = function (imageUrl, crossorigin, scaleMode) { +Texture.fromImage = function (imageUrl, crossorigin, scaleMode) +{ var texture = utils.TextureCache[imageUrl]; - if (!texture) { + if (!texture) + { texture = new Texture(BaseTexture.fromImage(imageUrl, crossorigin, scaleMode)); utils.TextureCache[imageUrl] = texture; } @@ -248,9 +269,11 @@ * @param frameId {string} The frame id of the texture * @return Texture */ -Texture.fromFrame = function (frameId) { +Texture.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache '); } return texture; @@ -264,7 +287,8 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return {Texture} */ -Texture.fromCanvas = function (canvas, scaleMode) { +Texture.fromCanvas = function (canvas, scaleMode) +{ return new Texture(BaseTexture.fromCanvas(canvas, scaleMode)); }; @@ -276,7 +300,8 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return {Texture} A Texture */ -Texture.fromVideo = function (video, scaleMode) { +Texture.fromVideo = function (video, scaleMode) +{ return new Texture(VideoBaseTexture.baseTextureFromVideo(video, scaleMode)); }; @@ -287,7 +312,8 @@ * @param texture {Texture} The Texture to add to the cache. * @param id {string} The id that the texture will be stored against. */ -Texture.addTextureToCache = function (texture, id) { +Texture.addTextureToCache = function (texture, id) +{ utils.TextureCache[id] = texture; }; @@ -298,7 +324,8 @@ * @param id {string} The id of the texture to be removed * @return {Texture} The texture that was removed */ -Texture.removeTextureFromCache = function (id) { +Texture.removeTextureFromCache = function (id) +{ var texture = utils.TextureCache[id]; delete utils.TextureCache[id]; diff --git a/src/core/textures/TextureUvs.js b/src/core/textures/TextureUvs.js index b9bbb58..5424d52 100644 --- a/src/core/textures/TextureUvs.js +++ b/src/core/textures/TextureUvs.js @@ -1,4 +1,5 @@ -function TextureUvs() { +function TextureUvs() +{ this.x0 = 0; this.y0 = 0; diff --git a/src/core/textures/VideoBaseTexture.js b/src/core/textures/VideoBaseTexture.js index e3e0c5a..1a826a9 100644 --- a/src/core/textures/VideoBaseTexture.js +++ b/src/core/textures/VideoBaseTexture.js @@ -12,15 +12,18 @@ * @param source {HTMLVideoElement} * @param [scaleMode] {number} See {@link scaleModes} for possible values */ -function VideoBaseTexture(source, scaleMode) { - if (!source){ +function VideoBaseTexture(source, scaleMode) +{ + if (!source) + { throw new Error('No video source element specified.'); } // hook in here to check if video is already available. // BaseTexture looks for a source.complete boolean, plus width & height. - if ((source.readyState === source.HAVE_ENOUGH_DATA || source.readyState === source.HAVE_FUTURE_DATA) && source.width && source.height) { + if ((source.readyState === source.HAVE_ENOUGH_DATA || source.readyState === source.HAVE_FUTURE_DATA) && source.width && source.height) + { source.complete = true; } @@ -31,7 +34,8 @@ this._boundOnUpdate = this._onUpdate.bind(this); this._boundOnCanPlay = this._onCanPlay.bind(this); - if (!source.complete) { + if (!source.complete) + { source.addEventListener('canplay', this._boundOnCanPlay); source.addEventListener('canplaythrough', this._boundOnCanPlay); @@ -47,28 +51,35 @@ VideoBaseTexture.prototype.constructor = VideoBaseTexture; module.exports = VideoBaseTexture; -VideoBaseTexture.prototype._onUpdate = function () { - if (this.autoUpdate) { +VideoBaseTexture.prototype._onUpdate = function () +{ + if (this.autoUpdate) + { window.requestAnimationFrame(this._boundOnUpdate); this.needsUpdate = true; } }; -VideoBaseTexture.prototype._onPlayStart = function () { - if (!this.autoUpdate) { +VideoBaseTexture.prototype._onPlayStart = function () +{ + if (!this.autoUpdate) + { window.requestAnimationFrame(this._boundOnUpdate); this.autoUpdate = true; } }; -VideoBaseTexture.prototype._onPlayStop = function () { +VideoBaseTexture.prototype._onPlayStop = function () +{ this.autoUpdate = false; }; -VideoBaseTexture.prototype._onCanPlay = function () { +VideoBaseTexture.prototype._onCanPlay = function () +{ this.hasLoaded = true; - if (this.source) { + if (this.source) + { this.source.removeEventListener('canplay', this._boundOnCanPlay); this.source.removeEventListener('canplaythrough', this._boundOnCanPlay); @@ -78,15 +89,18 @@ this.source.play(); // prevent multiple loaded dispatches.. - if(!this.__loaded){ + if(!this.__loaded) + { this.__loaded = true; this.emit('loaded', this); } } }; -VideoBaseTexture.prototype.destroy = function () { - if (this.source && this.source._pixiId) { +VideoBaseTexture.prototype.destroy = function () +{ + if (this.source && this.source._pixiId) + { utils.BaseTextureCache[ this.source._pixiId ] = null; delete utils.BaseTextureCache[ this.source._pixiId ]; @@ -105,14 +119,17 @@ * @param scaleMode {number} See {@link scaleModes} for possible values * @return {VideoBaseTexture} */ -VideoBaseTexture.fromVideo = function (video, scaleMode) { - if (!video._pixiId) { +VideoBaseTexture.fromVideo = function (video, scaleMode) +{ + if (!video._pixiId) + { video._pixiId = 'video_' + utils.uuid(); } var baseTexture = utils.BaseTextureCache[video._pixiId]; - if (!baseTexture) { + if (!baseTexture) + { baseTexture = new VideoBaseTexture(video, scaleMode); utils.BaseTextureCache[ video._pixiId ] = baseTexture; } @@ -147,17 +164,21 @@ * @param scaleMode {number} See {@link scaleModes} for possible values * @return {VideoBaseTexture} */ -VideoBaseTexture.fromUrl = function (videoSrc, scaleMode) { +VideoBaseTexture.fromUrl = function (videoSrc, scaleMode) +{ var video = document.createElement('video'); // array of objects or strings - if (Array.isArray(videoSrc)) { - for (var i = 0; i < videoSrc.length; ++i) { + if (Array.isArray(videoSrc)) + { + for (var i = 0; i < videoSrc.length; ++i) + { video.appendChild(createSource(videoSrc.src || videoSrc, videoSrc.mime)); } } // single object or string - else { + else + { video.appendChild(createSource(videoSrc.src || videoSrc, videoSrc.mime)); } @@ -169,8 +190,10 @@ VideoBaseTexture.fromUrls = VideoBaseTexture.fromUrl; -function createSource(path, type) { - if (!type) { +function createSource(path, type) +{ + if (!type) + { type = 'video/' + path.substr(path.lastIndexOf('.') + 1); } diff --git a/src/core/utils/EventData.js b/src/core/utils/EventData.js index 5d55a22..8cdf701 100644 --- a/src/core/utils/EventData.js +++ b/src/core/utils/EventData.js @@ -7,7 +7,8 @@ * @param name {string} The string name of the event that was triggered * @param data {object} Arbitrary event data to pass along */ -function EventData(target, name, data) { +function EventData(target, name, data) +{ // for duck typing in the ".on()" function this.__isEventObject = true; @@ -71,7 +72,8 @@ * Stops the propagation of events up the scene graph (prevents bubbling). * */ -EventData.prototype.stopPropagation = function stopPropagation() { +EventData.prototype.stopPropagation = function stopPropagation() +{ this.stopped = true; }; @@ -79,6 +81,7 @@ * Stops the propagation of events to sibling listeners (no longer calls any listeners). * */ -EventData.prototype.stopImmediatePropagation = function stopImmediatePropagation() { +EventData.prototype.stopImmediatePropagation = function stopImmediatePropagation() +{ this.stoppedImmediate = true; }; diff --git a/src/core/utils/EventTarget.js b/src/core/utils/EventTarget.js index 7ae8820..671a151 100644 --- a/src/core/utils/EventTarget.js +++ b/src/core/utils/EventTarget.js @@ -13,14 +13,16 @@ * var em = new MyEmitter(); * em.emit('eventName', 'some data', 'some more data', {}, null, ...); */ -function eventTarget(obj) { +function eventTarget(obj) +{ /** * Return a list of assigned event listeners. * * @param eventName {string} The events that should be listed. * @return {Array} An array of listener functions */ - obj.listeners = function listeners(eventName) { + obj.listeners = function listeners(eventName) + { this._listeners = this._listeners || {}; return this._listeners[eventName] ? this._listeners[eventName].slice() : []; @@ -33,22 +35,26 @@ * @param eventName {string} The name of the event. * @return {boolean} Indication if we've emitted an event. */ - obj.emit = obj.dispatchEvent = function emit(eventName, data) { + obj.emit = obj.dispatchEvent = function emit(eventName, data) + { this._listeners = this._listeners || {}; // fast return when there are no listeners - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return; } //backwards compat with old method ".emit({ type: 'something' })" - if (typeof eventName === 'object') { + if (typeof eventName === 'object') + { data = eventName; eventName = eventName.type; } //ensure we are using a real pixi event - if (!data || data.__isEventObject !== true) { + if (!data || data.__isEventObject !== true) + { data = new EventData(this, eventName, data); } @@ -58,23 +64,27 @@ fn = listeners[0], i; - for (i = 0; i < length; fn = listeners[++i]) { + for (i = 0; i < length; fn = listeners[++i]) + { //call the event listener fn.call(this, data); //if "stopImmediatePropagation" is called, stop calling sibling events - if (data.stoppedImmediate) { + if (data.stoppedImmediate) + { return this; } } //if "stopPropagation" is called then don't bubble the event - if (data.stopped) { + if (data.stopped) + { return this; } //bubble this event up the scene graph - if (this.parent && this.parent.emit) { + if (this.parent && this.parent.emit) + { this.parent.emit.call(this.parent, eventName, data); } @@ -88,7 +98,8 @@ * @param eventName {string} Name of the event. * @param callback {Functon} fn Callback function. */ - obj.on = obj.addEventListener = function on(eventName, fn) { + obj.on = obj.addEventListener = function on(eventName, fn) + { this._listeners = this._listeners || {}; (this._listeners[eventName] = this._listeners[eventName] || []) @@ -103,11 +114,13 @@ * @param eventName {string} Name of the event. * @param callback {Function} Callback function. */ - obj.once = function once(eventName, fn) { + obj.once = function once(eventName, fn) + { this._listeners = this._listeners || {}; var self = this; - function onceHandlerWrapper() { + function onceHandlerWrapper() + { fn.apply(self.off(eventName, onceHandlerWrapper), arguments); } onceHandlerWrapper._originalHandler = fn; @@ -122,23 +135,28 @@ * @param eventName {string} The event we want to remove. * @param callback {Function} The listener that we need to find. */ - obj.off = obj.removeEventListener = function off(eventName, fn) { + obj.off = obj.removeEventListener = function off(eventName, fn) + { this._listeners = this._listeners || {}; - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return this; } var list = this._listeners[eventName], i = fn ? list.length : 0; - while(i-- > 0) { - if (list[i] === fn || list[i]._originalHandler === fn) { + while(i-- > 0) + { + if (list[i] === fn || list[i]._originalHandler === fn) + { list.splice(i, 1); } } - if (list.length === 0) { + if (list.length === 0) + { delete this._listeners[eventName]; } @@ -150,10 +168,12 @@ * * @param eventName {string} The event you want to remove all listeners for. */ - obj.removeAllListeners = function removeAllListeners(eventName) { + obj.removeAllListeners = function removeAllListeners(eventName) + { this._listeners = this._listeners || {}; - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return this; } @@ -169,7 +189,8 @@ * * @param object {object} The obj to mix into */ - mixin: function mixin(obj) { + mixin: function mixin(obj) + { eventTarget(obj); } }; diff --git a/src/core/utils/PolyK.js b/src/core/utils/PolyK.js index 7325141..5e20c2b 100644 --- a/src/core/utils/PolyK.js +++ b/src/core/utils/PolyK.js @@ -47,7 +47,8 @@ * Triangulates shapes for webGL graphic fills. * */ -PolyK.Triangulate = function (p) { +PolyK.Triangulate = function (p) +{ var sign = true; var n = p.length >> 1; @@ -59,7 +60,8 @@ i = 0; var al = n; - while(al > 3) { + while(al > 3) + { var i0 = avl[(i+0)%al]; var i1 = avl[(i+1)%al]; var i2 = avl[(i+2)%al]; @@ -69,29 +71,35 @@ var cx = p[2*i2], cy = p[2*i2+1]; var earFound = false; - if (PolyK._convex(ax, ay, bx, by, cx, cy, sign)) { + if (PolyK._convex(ax, ay, bx, by, cx, cy, sign)) + { earFound = true; - for (var j = 0; j < al; j++) { + for (var j = 0; j < al; j++) + { var vi = avl[j]; if (vi === i0 || vi === i1 || vi === i2) continue; - if (PolyK._PointInTriangle(p[2*vi], p[2*vi+1], ax, ay, bx, by, cx, cy)) { + if (PolyK._PointInTriangle(p[2*vi], p[2*vi+1], ax, ay, bx, by, cx, cy)) + { earFound = false; break; } } } - if (earFound) { + if (earFound) + { tgs.push(i0, i1, i2); avl.splice((i+1)%al, 1); al--; i = 0; } - else if (i++ > 3*al) { + else if (i++ > 3*al) + { // need to flip flip reverse it! // reset! - if (sign) { + if (sign) + { tgs = []; avl = []; for (i = 0; i < n; i++) avl.push(i); @@ -101,7 +109,8 @@ sign = false; } - else { + else + { // window.console.log("PIXI Warning: shape too complex to fill"); return null; } @@ -126,7 +135,8 @@ * @private * @return {boolean} */ -PolyK._PointInTriangle = function (px, py, ax, ay, bx, by, cx, cy) { +PolyK._PointInTriangle = function (px, py, ax, ay, bx, by, cx, cy) +{ var v0x = cx-ax; var v0y = cy-ay; var v1x = bx-ax; @@ -154,6 +164,7 @@ * @private * @return {boolean} */ -PolyK._convex = function (ax, ay, bx, by, cx, cy, sign) { +PolyK._convex = function (ax, ay, bx, by, cx, cy, sign) +{ return ((ay-by)*(cx-bx) + (bx-ax)*(cy-by) >= 0) === sign; }; diff --git a/src/core/utils/index.js b/src/core/utils/index.js index ade9831..bfae7ae 100644 --- a/src/core/utils/index.js +++ b/src/core/utils/index.js @@ -16,7 +16,8 @@ * * @return {number} The next uuid to use. */ - uuid: function () { + uuid: function () + { return ++utils._uid; }, @@ -26,7 +27,8 @@ * @param hex {number} * @return {number[]} An array representing the [R, G, B] of the color. */ - hex2rgb: function (hex, out) { + hex2rgb: function (hex, out) + { out = out || []; out[0] = (hex >> 16 & 0xFF) / 255; @@ -42,7 +44,8 @@ * @param hex {number} * @return {string} The string color. */ - hex2string: function (hex) { + hex2string: function (hex) + { hex = hex.toString(16); hex = '000000'.substr(0, 6 - hex.length) + hex; @@ -55,7 +58,8 @@ * @param rgb {number[]} * @return {number} The color number */ - rgb2hex: function (rgb) { + rgb2hex: function (rgb) + { return ((rgb[0]*255 << 16) + (rgb[1]*255 << 8) + rgb[2]*255); }, @@ -64,8 +68,10 @@ * * @return {boolean} whether they are supported */ - canUseNewCanvasBlendModes: function () { - if (typeof document === 'undefined') { + canUseNewCanvasBlendModes: function () + { + if (typeof document === 'undefined') + { return false; } @@ -93,15 +99,19 @@ * @param number {number} * @return {number} the closest number that is a power of two */ - getNextPowerOfTwo: function (number) { + getNextPowerOfTwo: function (number) + { // see: http://en.wikipedia.org/wiki/Power_of_two#Fast_algorithm_to_check_if_a_positive_number_is_a_power_of_two - if (number > 0 && (number & (number - 1)) === 0) { + if (number > 0 && (number & (number - 1)) === 0) + { return number; } - else { + else + { var result = 1; - while (result < number) { + while (result < number) + { result <<= 1; } @@ -116,7 +126,8 @@ * @param height {number} * @return {boolean} */ - isPowerOfTwo: function (width, height) { + isPowerOfTwo: function (width, height) + { return (width > 0 && (width & (width - 1)) === 0 && height > 0 && (height & (height - 1)) === 0); }, @@ -130,12 +141,15 @@ * @constant * @static */ - sayHello: function (type) { - if (utils._saidHello) { + sayHello: function (type) + { + if (utils._saidHello) + { return; } - if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) { + if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) + { var args = [ '%c %c %c Pixi.js ' + CONST.VERSION + ' - ' + type + ' %c ' + ' %c ' + ' http://www.pixijs.com/ %c %c ♥%c♥%c♥ ', 'background: #ff66a5', @@ -151,7 +165,8 @@ console.log.apply(console, args); //jshint ignore:line } - else if (window.console) { + else if (window.console) + { console.log('Pixi.js ' + CONST.VERSION + ' - ' + type + ' - http://www.pixijs.com/'); //jshint ignore:line } @@ -166,15 +181,19 @@ * @class * @namespace PIXI */ - AjaxRequest: function () { + AjaxRequest: function () + { var activexmodes = ['Msxml2.XMLHTTP.6.0', 'Msxml2.XMLHTTP.3.0', 'Microsoft.XMLHTTP']; //activeX versions to check for in IE - if (window.ActiveXObject) { //Test for support for ActiveXObject in IE first (as XMLHttpRequest in IE7 is broken) - for (var i=0; i= this.textures.length) { + else if (round >= this.textures.length) + { this.gotoAndStop(this.textures.length - 1); - if (this.onComplete) { + if (this.onComplete) + { this.onComplete(); } } @@ -167,10 +182,12 @@ * @static * @param frames {string[]} the array of frames ids the movieclip will use as its texture frames */ -MovieClip.fromFrames = function (frames) { +MovieClip.fromFrames = function (frames) +{ var textures = []; - for (var i = 0; i < frames.length; ++i) { + for (var i = 0; i < frames.length; ++i) + { textures.push(new core.Texture.fromFrame(frames[i])); } @@ -183,10 +200,12 @@ * @static * @param images {string[]} the array of image urls the movieclip will use as its texture frames */ -MovieClip.fromImages = function (images) { +MovieClip.fromImages = function (images) +{ var textures = []; - for (var i = 0; i < images.length; ++i) { + for (var i = 0; i < images.length; ++i) + { textures.push(new core.Texture.fromImage(images[i])); } diff --git a/src/extras/Rope.js b/src/extras/Rope.js index c157ec4..9c87bc0 100644 --- a/src/extras/Rope.js +++ b/src/extras/Rope.js @@ -9,7 +9,8 @@ * @param {Array} points - An array of {Point}. * */ -function Rope(texture, points) { +function Rope(texture, points) +{ Strip.call(this, texture); this.points = points; @@ -31,10 +32,12 @@ * Refreshes * */ -Rope.prototype.refresh = function () { +Rope.prototype.refresh = function () +{ var points = this.points; - if (points.length < 1) { + if (points.length < 1) + { return; } @@ -59,20 +62,23 @@ var total = points.length, point, index, amount; - for (var i = 1; i < total; i++) { + for (var i = 1; i < total; i++) + { point = points[i]; index = i * 4; // time to do some smart drawing! amount = i / (total-1); - if (i%2) { + if (i%2) + { uvs[index] = amount; uvs[index+1] = 0; uvs[index+2] = amount; uvs[index+3] = 1; } - else { + else + { uvs[index] = amount; uvs[index+1] = 0; @@ -95,10 +101,12 @@ * * @private */ -Rope.prototype.updateTransform = function () { +Rope.prototype.updateTransform = function () +{ var points = this.points; - if (points.length < 1) { + if (points.length < 1) + { return; } @@ -113,14 +121,17 @@ var total = points.length, point, index, ratio, perpLength, num; - for (var i = 0; i < total; i++) { + for (var i = 0; i < total; i++) + { point = points[i]; index = i * 4; - if (i < points.length-1) { + if (i < points.length-1) + { nextPoint = points[i+1]; } - else { + else + { nextPoint = point; } @@ -129,7 +140,8 @@ ratio = (1 - (i / (total-1))) * 10; - if (ratio > 1) { + if (ratio > 1) + { ratio = 1; } @@ -157,7 +169,8 @@ * * @param texture {Texture} the texture that will be used */ -Rope.prototype.setTexture = function (texture) { +Rope.prototype.setTexture = function (texture) +{ // stop current texture this.texture = texture; //this.updateFrame = true; diff --git a/src/extras/Strip.js b/src/extras/Strip.js index c5e378f..57691b5 100644 --- a/src/extras/Strip.js +++ b/src/extras/Strip.js @@ -10,7 +10,8 @@ * @param height {number} the height * */ -function Strip(texture) { +function Strip(texture) +{ core.DisplayObjectContainer.call(this); /** @@ -70,9 +71,11 @@ * * @param renderer {WebGLRenderer} */ -Strip.prototype.renderWebGL = function (renderer) { +Strip.prototype.renderWebGL = function (renderer) +{ // if the sprite is not visible or the alpha is 0 then no need to render this element - if (!this.visible || this.alpha <= 0) { + if (!this.visible || this.alpha <= 0) + { return; } @@ -81,7 +84,8 @@ renderer.spriteBatch.stop(); // init! init! - if (!this._vertexBuffer) { + if (!this._vertexBuffer) + { this._initWebGL(renderer); } @@ -96,7 +100,8 @@ //TODO check culling }; -Strip.prototype._initWebGL = function (renderer) { +Strip.prototype._initWebGL = function (renderer) +{ // build the strip! var gl = renderer.gl; @@ -118,7 +123,8 @@ gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this.indices, gl.STATIC_DRAW); }; -Strip.prototype._renderStrip = function (renderer) { +Strip.prototype._renderStrip = function (renderer) +{ var gl = renderer.gl; var projection = renderer.projection, offset = renderer.offset, @@ -137,7 +143,8 @@ gl.uniform2f(shader.offsetVector, -offset.x, -offset.y); gl.uniform1f(shader.alpha, this.worldAlpha); - if (!this.dirty) { + if (!this.dirty) + { gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexBuffer); gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); @@ -150,10 +157,12 @@ gl.activeTexture(gl.TEXTURE0); // check if a texture is dirty.. - if (this.texture.baseTexture._dirty[gl.id]) { + if (this.texture.baseTexture._dirty[gl.id]) + { renderer.updateTexture(this.texture.baseTexture); } - else { + else + { // bind the current texture gl.bindTexture(gl.TEXTURE_2D, this.texture.baseTexture._glTextures[gl.id]); } @@ -163,7 +172,8 @@ } - else { + else + { this.dirty = false; gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexBuffer); @@ -178,10 +188,12 @@ gl.activeTexture(gl.TEXTURE0); // check if a texture is dirty.. - if (this.texture.baseTexture._dirty[gl.id]) { + if (this.texture.baseTexture._dirty[gl.id]) + { renderer.updateTexture(this.texture.baseTexture); } - else { + else + { gl.bindTexture(gl.TEXTURE_2D, this.texture.baseTexture._glTextures[gl.id]); } @@ -203,27 +215,33 @@ * * @param renderer {CanvasRenderer} */ -Strip.prototype.renderCanvas = function (renderer) { +Strip.prototype.renderCanvas = function (renderer) +{ var context = renderer.context; var transform = this.worldTransform; - if (renderer.roundPixels) { + if (renderer.roundPixels) + { context.setTransform(transform.a, transform.b, transform.c, transform.d, transform.tx | 0, transform.ty | 0); } - else { + else + { context.setTransform(transform.a, transform.b, transform.c, transform.d, transform.tx, transform.ty); } - if (this.drawMode === Strip.DrawModes.TRIANGLE_STRIP) { + if (this.drawMode === Strip.DrawModes.TRIANGLE_STRIP) + { this._renderCanvasTriangleStrip(context); } - else { + else + { this._renderCanvasTriangles(context); } }; -Strip.prototype._renderCanvasTriangleStrip = function (context) { +Strip.prototype._renderCanvasTriangleStrip = function (context) +{ // draw triangles!! var vertices = this.vertices; var uvs = this.uvs; @@ -231,14 +249,16 @@ var length = vertices.length / 2; // this.count++; - for (var i = 0; i < length - 2; i++) { + for (var i = 0; i < length - 2; i++) + { // draw some triangles! var index = i * 2; this._renderCanvasDrawTriangle(context, vertices, uvs, index, (index + 2), (index + 4)); } }; -Strip.prototype._renderCanvasTriangles = function (context) { +Strip.prototype._renderCanvasTriangles = function (context) +{ // draw triangles!! var vertices = this.vertices; var uvs = this.uvs; @@ -247,14 +267,16 @@ var length = indices.length; // this.count++; - for (var i = 0; i < length; i += 3) { + for (var i = 0; i < length; i += 3) + { // draw some triangles! var index0 = indices[i] * 2, index1 = indices[i + 1] * 2, index2 = indices[i + 2] * 2; this._renderCanvasDrawTriangle(context, vertices, uvs, index0, index1, index2); } }; -Strip.prototype._renderCanvasDrawTriangle = function (context, vertices, uvs, index0, index1, index2) { +Strip.prototype._renderCanvasDrawTriangle = function (context, vertices, uvs, index0, index1, index2) +{ var textureSource = this.texture.baseTexture.source; var textureWidth = this.texture.width; var textureHeight = this.texture.height; @@ -265,7 +287,8 @@ var u0 = uvs[index0] * textureWidth, u1 = uvs[index1] * textureWidth, u2 = uvs[index2] * textureWidth; var v0 = uvs[index0 + 1] * textureHeight, v1 = uvs[index1 + 1] * textureHeight, v2 = uvs[index2 + 1] * textureHeight; - if (this.canvasPadding > 0) { + if (this.canvasPadding > 0) + { var paddingX = this.canvasPadding / this.worldTransform.a; var paddingY = this.canvasPadding / this.worldTransform.d; var centerX = (x0 + x1 + x2) / 3; @@ -332,7 +355,8 @@ * @param strip {Strip} The Strip to render * @private */ -Strip.prototype.renderStripFlat = function (strip) { +Strip.prototype.renderStripFlat = function (strip) +{ var context = this.context; var vertices = strip.vertices; @@ -340,7 +364,8 @@ // this.count++; context.beginPath(); - for (var i=1; i < length-2; i++) { + for (var i=1; i < length-2; i++) + { // draw some triangles! var index = i*2; @@ -358,7 +383,8 @@ }; /* -Strip.prototype.setTexture = function (texture) { +Strip.prototype.setTexture = function (texture) +{ //TODO SET THE TEXTURES //TODO VISIBILITY @@ -377,7 +403,8 @@ * @private */ -Strip.prototype.onTextureUpdate = function () { +Strip.prototype.onTextureUpdate = function () +{ this.updateFrame = true; }; @@ -387,7 +414,8 @@ * @param matrix {Matrix} the transformation matrix of the sprite * @return {Rectangle} the framing rectangle */ -Strip.prototype.getBounds = function (matrix) { +Strip.prototype.getBounds = function (matrix) +{ var worldTransform = matrix || this.worldTransform; var a = worldTransform.a; @@ -404,7 +432,8 @@ var minY = Infinity; var vertices = this.vertices; - for (var i = 0, n = vertices.length; i < n; i += 2) { + for (var i = 0, n = vertices.length; i < n; i += 2) + { var rawX = vertices[i], rawY = vertices[i + 1]; var x = (a * rawX) + (c * rawY) + tx; var y = (d * rawY) + (b * rawX) + ty; @@ -416,7 +445,8 @@ maxY = y > maxY ? y : maxY; } - if (minX === -Infinity || maxY === Infinity) { + if (minX === -Infinity || maxY === Infinity) + { return core.math.Rectangle.EMPTY; } diff --git a/src/extras/TilingSprite.js b/src/extras/TilingSprite.js index 3ac22df..31da393 100644 --- a/src/extras/TilingSprite.js +++ b/src/extras/TilingSprite.js @@ -10,7 +10,8 @@ * @param width {number} the width of the tiling sprite * @param height {number} the height of the tiling sprite */ -function TilingSprite(texture, width, height) { +function TilingSprite(texture, width, height) +{ core.Sprite.call( this, texture); /** @@ -86,10 +87,12 @@ * @memberof TilingSprite# */ width: { - get: function () { + get: function () + { return this._width; }, - set: function (value) { + set: function (value) + { this._width = value; } }, @@ -101,20 +104,25 @@ * @memberof TilingSprite# */ height: { - get: function () { + get: function () + { return this._height; }, - set: function (value) { + set: function (value) + { this._height = value; } }, texture: { - get: function () { + get: function () + { return this._texture; }, - set: function (value) { - if (this._texture === value) { + set: function (value) + { + if (this._texture === value) + { return; } @@ -130,51 +138,61 @@ * * @param renderer {WebGLRenderer} */ -TilingSprite.prototype.renderWebGL = function (renderer) { - if (!this.visible || this.alpha <= 0) { +TilingSprite.prototype.renderWebGL = function (renderer) +{ + if (!this.visible || this.alpha <= 0) + { return; } var i, j; - if (this._mask) { + if (this._mask) + { renderer.spriteBatch.stop(); renderer.maskManager.pushMask(this.mask, renderer); renderer.spriteBatch.start(); } - if (this._filters) { + if (this._filters) + { renderer.spriteBatch.flush(); renderer.filterManager.pushFilter(this._filterBlock); } - if (!this.tilingTexture || this.refreshTexture) { + if (!this.tilingTexture || this.refreshTexture) + { this.generateTilingTexture(true); - if (this.tilingTexture && this.tilingTexture.needsUpdate) { + if (this.tilingTexture && this.tilingTexture.needsUpdate) + { //TODO - tweaking renderer.updateTexture(this.tilingTexture.baseTexture); this.tilingTexture.needsUpdate = false; // this.tilingTexture._uvs = null; } } - else { + else + { renderer.spriteBatch.renderTilingSprite(this); } // simple render children! - for (i=0,j=this.children.length; i= 0; i--) { + for (var i = length - 1; i >= 0; i--) + { var child = children[i]; // push all interactive bits - if (child._interactive) { + if (child._interactive) + { iParent.interactiveChildren = true; //child.__iParent = iParent; this.interactiveItems.push(child); - if (child.children.length > 0) { + if (child.children.length > 0) + { this.collectInteractiveSprite(child, child); } } - else { + else + { child.__iParent = null; - if (child.children.length > 0) { + if (child.children.length > 0) + { this.collectInteractiveSprite(child, iParent); } } @@ -189,7 +196,8 @@ * @param [resolution=1] {number} THe resolution of the new element (relative to the canvas). * @private */ -InteractionManager.prototype.setTargetElement = function (element, resolution) { +InteractionManager.prototype.setTargetElement = function (element, resolution) +{ this.removeEvents(); this.interactionDOMElement = element; @@ -203,12 +211,15 @@ * * @private */ -InteractionManager.prototype.addEvents = function () { - if (!this.interactionDOMElement) { +InteractionManager.prototype.addEvents = function () +{ + if (!this.interactionDOMElement) + { return; } - if (window.navigator.msPointerEnabled) { + if (window.navigator.msPointerEnabled) + { this.interactionDOMElement.style['-ms-content-zooming'] = 'none'; this.interactionDOMElement.style['-ms-touch-action'] = 'none'; } @@ -230,12 +241,15 @@ * * @private */ -InteractionManager.prototype.removeEvents = function () { - if (!this.interactionDOMElement) { +InteractionManager.prototype.removeEvents = function () +{ + if (!this.interactionDOMElement) + { return; } - if (window.navigator.msPointerEnabled) { + if (window.navigator.msPointerEnabled) + { this.interactionDOMElement.style['-ms-content-zooming'] = ''; this.interactionDOMElement.style['-ms-touch-action'] = ''; } @@ -260,8 +274,10 @@ * * @private */ -InteractionManager.prototype.update = function () { - if (!this.interactionDOMElement) { +InteractionManager.prototype.update = function () +{ + if (!this.interactionDOMElement) + { return; } @@ -269,7 +285,8 @@ var now = Date.now(); var diff = now - this.last; diff = (diff * INTERACTION_FREQUENCY ) / 1000; - if (diff < 1) { + if (diff < 1) + { return; } @@ -280,7 +297,8 @@ // ok.. so mouse events?? // yes for now :) // OPTIMISE - how often to check?? - if (this.dirty) { + if (this.dirty) + { this.rebuildInteractiveGraph(); } @@ -289,7 +307,8 @@ var cursor = 'inherit'; var over = false; - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { var item = this.interactiveItems[i]; // OPTIMISATION - only calculate every time if the mousemove function exists.. @@ -302,26 +321,34 @@ this.mouse.target = item; // ok so deal with interactions.. // looks like there was a hit! - if (item.__hit && !over) { - if (item.buttonMode) { + if (item.__hit && !over) + { + if (item.buttonMode) + { cursor = item.defaultCursor; } - if (!item.interactiveChildren) { + if (!item.interactiveChildren) + { over = true; } - if (!item.__isOver) { - if (item.mouseover) { + if (!item.__isOver) + { + if (item.mouseover) + { item.mouseover (this.mouse); } item.__isOver = true; } } - else { - if (item.__isOver) { + else + { + if (item.__isOver) + { // roll out! - if (item.mouseout) { + if (item.mouseout) + { item.mouseout (this.mouse); } item.__isOver = false; @@ -329,7 +356,8 @@ } } - if (this.currentCursorStyle !== cursor) { + if (this.currentCursorStyle !== cursor) + { this.currentCursorStyle = cursor; this.interactionDOMElement.style.cursor = cursor; } @@ -338,18 +366,21 @@ /** * @private */ -InteractionManager.prototype.rebuildInteractiveGraph = function () { +InteractionManager.prototype.rebuildInteractiveGraph = function () +{ this.dirty = false; var len = this.interactiveItems.length; - for (var i = 0; i < len; i++) { + for (var i = 0; i < len; i++) + { this.interactiveItems[i].interactiveChildren = false; } this.interactiveItems.length = 0; - if (this.stage.interactive) { + if (this.stage.interactive) + { this.interactiveItems.push(this.stage); } @@ -363,8 +394,10 @@ * @param event {Event} The DOM event of the mouse moving * @private */ -InteractionManager.prototype.onMouseMove = function (event) { - if (this.dirty) { +InteractionManager.prototype.onMouseMove = function (event) +{ + if (this.dirty) + { this.rebuildInteractiveGraph(); } @@ -378,11 +411,13 @@ var length = this.interactiveItems.length; - for (var i = 0; i < length; i++) { + for (var i = 0; i < length; i++) + { var item = this.interactiveItems[i]; // Call the function! - if (item.mousemove) { + if (item.mousemove) + { item.mousemove(this.mouse); } } @@ -394,14 +429,17 @@ * @param event {Event} The DOM event of a mouse button being pressed down * @private */ -InteractionManager.prototype.onMouseDown = function (event) { - if (this.dirty) { +InteractionManager.prototype.onMouseDown = function (event) +{ + if (this.dirty) + { this.rebuildInteractiveGraph(); } this.mouse.originalEvent = event; - if (AUTO_PREVENT_DEFAULT) { + if (AUTO_PREVENT_DEFAULT) + { this.mouse.originalEvent.preventDefault(); } @@ -420,22 +458,27 @@ // while // hit test - for (var i = 0; i < length; i++) { + for (var i = 0; i < length; i++) + { var item = this.interactiveItems[i]; - if (item[downFunction] || item[clickFunction]) { + if (item[downFunction] || item[clickFunction]) + { item[buttonIsDown] = true; item.__hit = this.hitTest(item, this.mouse); - if (item.__hit) { + if (item.__hit) + { //call the function! - if (item[downFunction]) { + if (item[downFunction]) + { item[downFunction](this.mouse); } item[isDown] = true; // just the one! - if (!item.interactiveChildren) { + if (!item.interactiveChildren) + { break; } } @@ -449,8 +492,10 @@ * @param event {Event} The DOM event of a mouse being moved out * @private */ -InteractionManager.prototype.onMouseOut = function (event) { - if (this.dirty) { +InteractionManager.prototype.onMouseOut = function (event) +{ + if (this.dirty) + { this.rebuildInteractiveGraph(); } @@ -460,11 +505,14 @@ this.interactionDOMElement.style.cursor = 'inherit'; - for (var i = 0; i < length; i++) { + for (var i = 0; i < length; i++) + { var item = this.interactiveItems[i]; - if (item.__isOver) { + if (item.__isOver) + { this.mouse.target = item; - if (item.mouseout) { + if (item.mouseout) + { item.mouseout(this.mouse); } item.__isOver = false; @@ -484,8 +532,10 @@ * @param event {Event} The DOM event of a mouse button being released * @private */ -InteractionManager.prototype.onMouseUp = function (event) { - if (this.dirty) { +InteractionManager.prototype.onMouseUp = function (event) +{ + if (this.dirty) + { this.rebuildInteractiveGraph(); } @@ -502,30 +552,40 @@ var upOutsideFunction = isRightButton ? 'rightupoutside' : 'mouseupoutside'; var isDown = isRightButton ? '__isRightDown' : '__isDown'; - for (var i = 0; i < length; i++) { + for (var i = 0; i < length; i++) + { var item = this.interactiveItems[i]; - if (item[clickFunction] || item[upFunction] || item[upOutsideFunction]) { + if (item[clickFunction] || item[upFunction] || item[upOutsideFunction]) + { item.__hit = this.hitTest(item, this.mouse); - if (item.__hit && !up) { + if (item.__hit && !up) + { //call the function! - if (item[upFunction]) { + if (item[upFunction]) + { item[upFunction](this.mouse); } - if (item[isDown]) { - if (item[clickFunction]) { + if (item[isDown]) + { + if (item[clickFunction]) + { item[clickFunction](this.mouse); } } - if (!item.interactiveChildren) { + if (!item.interactiveChildren) + { up = true; } } - else { - if (item[isDown]) { - if (item[upOutsideFunction]) { + else + { + if (item[isDown]) + { + if (item[upOutsideFunction]) + { item[upOutsideFunction](this.mouse); } } @@ -543,10 +603,12 @@ * @param interactionData {InteractionData} The interactionData object to update in the case there is a hit * @private */ -InteractionManager.prototype.hitTest = function (item, interactionData) { +InteractionManager.prototype.hitTest = function (item, interactionData) +{ var global = interactionData.global; - if (!item.worldVisible) { + if (!item.worldVisible) + { return false; } @@ -560,37 +622,46 @@ interactionData.target = item; //a sprite or display object with a hit area defined - if (item.hitArea && item.hitArea.contains) { + if (item.hitArea && item.hitArea.contains) + { return item.hitArea.contains(x, y); } // a sprite with no hitarea defined - else if (item instanceof core.Sprite) { + else if (item instanceof core.Sprite) + { var width = item.texture.frame.width; var height = item.texture.frame.height; var x1 = -width * item.anchor.x; var y1; - if (x > x1 && x < x1 + width) { + if (x > x1 && x < x1 + width) + { y1 = -height * item.anchor.y; - if (y > y1 && y < y1 + height) { + if (y > y1 && y < y1 + height) + { // set the target property if a hit is true! return true; } } } - else if (item instanceof core.Graphics) { + else if (item instanceof core.Graphics) + { var graphicsData = item.graphicsData; - for (i = 0; i < graphicsData.length; i++) { + for (i = 0; i < graphicsData.length; i++) + { var data = graphicsData[i]; - if (!data.fill) { + if (!data.fill) + { continue; } // only deal with fills.. - if (data.shape) { - if (data.shape.contains(x, y)) { + if (data.shape) + { + if (data.shape.contains(x, y)) + { //interactionData.target = item; return true; } @@ -600,10 +671,12 @@ var length = item.children.length; - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { var tempItem = item.children[i]; var hit = this.hitTest(tempItem, interactionData); - if (hit) { + if (hit) + { // hmm.. TODO SET CORRECT TARGET? interactionData.target = item; return true; @@ -618,8 +691,10 @@ * @param event {Event} The DOM event of a touch moving across the renderer view * @private */ -InteractionManager.prototype.onTouchMove = function (event) { - if (this.dirty) { +InteractionManager.prototype.onTouchMove = function (event) +{ + if (this.dirty) + { this.rebuildInteractiveGraph(); } @@ -628,7 +703,8 @@ var touchData; var i = 0; - for (i = 0; i < changedTouches.length; i++) { + for (i = 0; i < changedTouches.length; i++) + { var touchEvent = changedTouches[i]; touchData = this.touches[touchEvent.identifier]; touchData.originalEvent = event; @@ -636,15 +712,18 @@ // update the touch position touchData.global.x = ( (touchEvent.clientX - rect.left) * (this.interactionDOMElement.width / rect.width) ) / this.resolution; touchData.global.y = ( (touchEvent.clientY - rect.top) * (this.interactionDOMElement.height / rect.height) ) / this.resolution; - if (navigator.isCocoonJS && !rect.left && !rect.top && !event.target.style.width && !event.target.style.height) { + if (navigator.isCocoonJS && !rect.left && !rect.top && !event.target.style.width && !event.target.style.height) + { //Support for CocoonJS fullscreen scale modes touchData.global.x = touchEvent.clientX; touchData.global.y = touchEvent.clientY; } - for (var j = 0; j < this.interactiveItems.length; j++) { + for (var j = 0; j < this.interactiveItems.length; j++) + { var item = this.interactiveItems[j]; - if (item.touchmove && item.__touchData && item.__touchData[touchEvent.identifier]) { + if (item.touchmove && item.__touchData && item.__touchData[touchEvent.identifier]) + { item.touchmove(touchData); } } @@ -657,23 +736,28 @@ * @param event {Event} The DOM event of a touch starting on the renderer view * @private */ -InteractionManager.prototype.onTouchStart = function (event) { - if (this.dirty) { +InteractionManager.prototype.onTouchStart = function (event) +{ + if (this.dirty) + { this.rebuildInteractiveGraph(); } var rect = this.interactionDOMElement.getBoundingClientRect(); - if (AUTO_PREVENT_DEFAULT) { + if (AUTO_PREVENT_DEFAULT) + { event.preventDefault(); } var changedTouches = event.changedTouches; - for (var i=0; i < changedTouches.length; i++) { + for (var i=0; i < changedTouches.length; i++) + { var touchEvent = changedTouches[i]; var touchData = this.pool.pop(); - if (!touchData) { + if (!touchData) + { touchData = new InteractionData(); } @@ -682,7 +766,8 @@ this.touches[touchEvent.identifier] = touchData; touchData.global.x = ( (touchEvent.clientX - rect.left) * (this.interactionDOMElement.width / rect.width) ) / this.resolution; touchData.global.y = ( (touchEvent.clientY - rect.top) * (this.interactionDOMElement.height / rect.height) ) / this.resolution; - if (navigator.isCocoonJS && !rect.left && !rect.top && !event.target.style.width && !event.target.style.height) { + if (navigator.isCocoonJS && !rect.left && !rect.top && !event.target.style.width && !event.target.style.height) + { //Support for CocoonJS fullscreen scale modes touchData.global.x = touchEvent.clientX; touchData.global.y = touchEvent.clientY; @@ -690,15 +775,19 @@ var length = this.interactiveItems.length; - for (var j = 0; j < length; j++) { + for (var j = 0; j < length; j++) + { var item = this.interactiveItems[j]; - if (item.touchstart || item.tap) { + if (item.touchstart || item.tap) + { item.__hit = this.hitTest(item, touchData); - if (item.__hit) { + if (item.__hit) + { //call the function! - if (item.touchstart) { + if (item.touchstart) + { item.touchstart(touchData); } @@ -706,7 +795,8 @@ item.__touchData = item.__touchData || {}; item.__touchData[touchEvent.identifier] = touchData; - if (!item.interactiveChildren) { + if (!item.interactiveChildren) + { break; } } @@ -721,31 +811,37 @@ * @param event {Event} The DOM event of a touch ending on the renderer view * @private */ -InteractionManager.prototype.onTouchEnd = function (event) { - if (this.dirty) { +InteractionManager.prototype.onTouchEnd = function (event) +{ + if (this.dirty) + { this.rebuildInteractiveGraph(); } var rect = this.interactionDOMElement.getBoundingClientRect(); var changedTouches = event.changedTouches; - for (var i=0; i < changedTouches.length; i++) { + for (var i=0; i < changedTouches.length; i++) + { var touchEvent = changedTouches[i]; var touchData = this.touches[touchEvent.identifier]; var up = false; touchData.global.x = ( (touchEvent.clientX - rect.left) * (this.interactionDOMElement.width / rect.width) ) / this.resolution; touchData.global.y = ( (touchEvent.clientY - rect.top) * (this.interactionDOMElement.height / rect.height) ) / this.resolution; - if (navigator.isCocoonJS && !rect.left && !rect.top && !event.target.style.width && !event.target.style.height) { + if (navigator.isCocoonJS && !rect.left && !rect.top && !event.target.style.width && !event.target.style.height) + { //Support for CocoonJS fullscreen scale modes touchData.global.x = touchEvent.clientX; touchData.global.y = touchEvent.clientY; } var length = this.interactiveItems.length; - for (var j = 0; j < length; j++) { + for (var j = 0; j < length; j++) + { var item = this.interactiveItems[j]; - if (item.__touchData && item.__touchData[touchEvent.identifier]) { + if (item.__touchData && item.__touchData[touchEvent.identifier]) + { item.__hit = this.hitTest(item, item.__touchData[touchEvent.identifier]); @@ -753,20 +849,27 @@ touchData.originalEvent = event; // hitTest?? - if (item.touchend || item.tap) { - if (item.__hit && !up) { - if (item.touchend) { + if (item.touchend || item.tap) + { + if (item.__hit && !up) + { + if (item.touchend) + { item.touchend(touchData); } - if (item.__isDown && item.tap) { + if (item.__isDown && item.tap) + { item.tap(touchData); } - if (!item.interactiveChildren) { + if (!item.interactiveChildren) + { up = true; } } - else { - if (item.__isDown && item.touchendoutside) { + else + { + if (item.__isDown && item.touchendoutside) + { item.touchendoutside(touchData); } } diff --git a/src/loaders/AssetLoader.js b/src/loaders/AssetLoader.js index 20da0cf..c4dba1c 100644 --- a/src/loaders/AssetLoader.js +++ b/src/loaders/AssetLoader.js @@ -21,7 +21,8 @@ * data formats include 'xml' and 'fnt'. * @param crossorigin {boolean} Whether requests should be treated as crossorigin */ -function AssetLoader(assetURLs, crossorigin) { +function AssetLoader(assetURLs, crossorigin) +{ /** * The array of asset URLs that are going to be loaded * @@ -76,16 +77,19 @@ * * @param str {string} the name of the asset */ -AssetLoader.prototype._getDataType = function (str) { +AssetLoader.prototype._getDataType = function (str) +{ var test = 'data:'; var start = str.slice(0, test.length).toLowerCase(); - if (start === test) { + if (start === test) + { var data = str.slice(test.length); var sepIdx = data.indexOf(','); // check for malformed data URI scheme - if (sepIdx === -1) { + if (sepIdx === -1) + { return null; } @@ -94,7 +98,8 @@ //We might need to handle some special cases here... //standardize text/plain to 'txt' file extension - if (!info || info.toLowerCase() === 'text/plain') { + if (!info || info.toLowerCase() === 'text/plain') + { return 'txt'; } @@ -109,27 +114,32 @@ * Starts loading the assets sequentially * */ -AssetLoader.prototype.load = function () { +AssetLoader.prototype.load = function () +{ var scope = this; - function onLoad(evt) { + function onLoad(evt) + { scope.onAssetLoaded(evt.data.content); } this.loadCount = this.assetURLs.length; - for (var i=0; i < this.assetURLs.length; i++) { + for (var i=0; i < this.assetURLs.length; i++) + { var fileName = this.assetURLs[i]; //first see if we have a data URI scheme.. var fileType = this._getDataType(fileName); //if not, assume it's a file URI - if (!fileType) { + if (!fileType) + { fileType = fileName.split('?').shift().split('.').pop().toLowerCase(); } var Constructor = this.loadersByType[fileType]; - if (!Constructor) { + if (!Constructor) + { throw new Error(fileType + ' is an unsupported file type'); } @@ -145,18 +155,22 @@ * * @private */ -AssetLoader.prototype.onAssetLoaded = function (loader) { +AssetLoader.prototype.onAssetLoaded = function (loader) +{ this.loadCount--; this.emit('onProgress', { content: this, loader: loader }); - if (this.onProgress) { + if (this.onProgress) + { this.onProgress(loader); } - if (!this.loadCount) { + if (!this.loadCount) + { this.emit('onComplete', { content: this }); - if (this.onComplete) { + if (this.onComplete) + { this.onComplete(); } } diff --git a/src/loaders/AtlasLoader.js b/src/loaders/AtlasLoader.js index 5eda286..3aec9e2 100644 --- a/src/loaders/AtlasLoader.js +++ b/src/loaders/AtlasLoader.js @@ -15,7 +15,8 @@ * @param url {String} The url of the JSON file * @param crossorigin {boolean} Whether requests should be treated as crossorigin */ -function AtlasLoader(url, crossorigin) { +function AtlasLoader(url, crossorigin) +{ this.url = url; this.baseUrl = url.replace(/[^\/]*$/, ''); this.crossorigin = crossorigin; @@ -31,13 +32,15 @@ * Starts loading the JSON file * */ -AtlasLoader.prototype.load = function () { +AtlasLoader.prototype.load = function () +{ this.ajaxRequest = new core.utils.AjaxRequest(); this.ajaxRequest.onreadystatechange = this.onAtlasLoaded.bind(this); this.ajaxRequest.open('GET', this.url, true); - if (this.ajaxRequest.overrideMimeType) { + if (this.ajaxRequest.overrideMimeType) + { this.ajaxRequest.overrideMimeType('application/json'); } @@ -49,9 +52,12 @@ * * @private */ -AtlasLoader.prototype.onAtlasLoaded = function () { - if (this.ajaxRequest.readyState === 4) { - if (this.ajaxRequest.status === 200 || window.location.href.indexOf('http') === -1) { +AtlasLoader.prototype.onAtlasLoaded = function () +{ + if (this.ajaxRequest.readyState === 4) + { + if (this.ajaxRequest.status === 200 || window.location.href.indexOf('http') === -1) + { this.atlas = { meta : { image : [] @@ -70,34 +76,44 @@ selfOnLoaded = this.onLoaded.bind(this); // parser without rotation support yet! - for (i = 0; i < result.length; i++) { + for (i = 0; i < result.length; i++) + { result[i] = result[i].replace(/^\s+|\s+$/g, ''); - if (result[i] === '') { + if (result[i] === '') + { nameInNextLine = i+1; } - if (result[i].length > 0) { - if (nameInNextLine === i) { + if (result[i].length > 0) + { + if (nameInNextLine === i) + { this.atlas.meta.image.push(result[i]); currentImageId = this.atlas.meta.image.length - 1; this.atlas.frames.push({}); lineCount = -3; - } else if (lineCount > 0) { - if (lineCount % 7 === 1) { // frame name - if (currentFrame != null) { //jshint ignore:line + } else if (lineCount > 0) + { + if (lineCount % 7 === 1) + { // frame name + if (currentFrame != null) + { //jshint ignore:line this.atlas.frames[currentImageId][currentFrame.name] = currentFrame; } currentFrame = { name: result[i], frame : {} }; } else { var text = result[i].split(' '); - if (lineCount % 7 === 3) { // position + if (lineCount % 7 === 3) + { // position currentFrame.frame.x = Number(text[1].replace(',', '')); currentFrame.frame.y = Number(text[2]); - } else if (lineCount % 7 === 4) { // size + } else if (lineCount % 7 === 4) + { // size currentFrame.frame.w = Number(text[1].replace(',', '')); currentFrame.frame.h = Number(text[2]); - } else if (lineCount % 7 === 5) { // real size + } else if (lineCount % 7 === 5) + { // real size var realSize = { x : 0, y : 0, @@ -105,7 +121,8 @@ h : Number(text[2]) }; - if (realSize.w > currentFrame.frame.w || realSize.h > currentFrame.frame.h) { + if (realSize.w > currentFrame.frame.w || realSize.h > currentFrame.frame.h) + { currentFrame.trimmed = true; currentFrame.realSize = realSize; } else { @@ -118,28 +135,34 @@ } } - if (currentFrame != null) { //jshint ignore:line + if (currentFrame != null) + { //jshint ignore:line this.atlas.frames[currentImageId][currentFrame.name] = currentFrame; } - if (this.atlas.meta.image.length > 0) { + if (this.atlas.meta.image.length > 0) + { this.images = []; - for (j = 0; j < this.atlas.meta.image.length; j++) { + for (j = 0; j < this.atlas.meta.image.length; j++) + { // sprite sheet var textureUrl = this.baseUrl + this.atlas.meta.image[j]; var frameData = this.atlas.frames[j]; this.images.push(new ImageLoader(textureUrl, this.crossorigin)); - for (i in frameData) { + for (i in frameData) + { var rect = frameData[i].frame; - if (rect) { + if (rect) + { core.utils.TextureCache[i] = new core.Texture(this.images[j].texture.baseTexture, { x: rect.x, y: rect.y, width: rect.w, height: rect.h }); - if (frameData[i].trimmed) { + if (frameData[i].trimmed) + { core.utils.TextureCache[i].realSize = frameData[i].realSize; // trim in pixi not supported yet, todo update trim properties if it is done ... core.utils.TextureCache[i].trim.x = 0; @@ -150,7 +173,8 @@ } this.currentImageId = 0; - for (j = 0; j < this.images.length; j++) { + for (j = 0; j < this.images.length; j++) + { this.images[j].on('loaded', selfOnLoaded); } this.images[this.currentImageId].load(); @@ -170,8 +194,10 @@ * * @private */ -AtlasLoader.prototype.onLoaded = function () { - if (this.images.length - 1 > this.currentImageId) { +AtlasLoader.prototype.onLoaded = function () +{ + if (this.images.length - 1 > this.currentImageId) + { this.currentImageId++; this.images[this.currentImageId].load(); } else { @@ -185,6 +211,7 @@ * * @private */ -AtlasLoader.prototype.onError = function () { +AtlasLoader.prototype.onError = function () +{ this.emit('error', { content: this }); }; diff --git a/src/loaders/BitmapFontLoader.js b/src/loaders/BitmapFontLoader.js index 8641760..13e5c1b 100644 --- a/src/loaders/BitmapFontLoader.js +++ b/src/loaders/BitmapFontLoader.js @@ -13,7 +13,8 @@ * @param url {String} The url of the sprite sheet JSON file * @param crossorigin {boolean} Whether requests should be treated as crossorigin */ -function BitmapFontLoader(url, crossorigin) { +function BitmapFontLoader(url, crossorigin) +{ /** * The url of the bitmap font data * @@ -54,13 +55,15 @@ * Loads the XML font data * */ -BitmapFontLoader.prototype.load = function () { +BitmapFontLoader.prototype.load = function () +{ this.ajaxRequest = new core.utils.AjaxRequest(); this.ajaxRequest.onreadystatechange = this.onXMLLoaded.bind(this); this.ajaxRequest.open('GET', this.url, true); - if (this.ajaxRequest.overrideMimeType) { + if (this.ajaxRequest.overrideMimeType) + { this.ajaxRequest.overrideMimeType('application/xml'); } @@ -72,12 +75,17 @@ * * @private */ -BitmapFontLoader.prototype.onXMLLoaded = function () { - if (this.ajaxRequest.readyState === 4) { - if (this.ajaxRequest.status === 200 || window.location.protocol.indexOf('http') === -1) { +BitmapFontLoader.prototype.onXMLLoaded = function () +{ + if (this.ajaxRequest.readyState === 4) + { + if (this.ajaxRequest.status === 200 || window.location.protocol.indexOf('http') === -1) + { var responseXML = this.ajaxRequest.responseXML; - if (!responseXML || /MSIE 9/i.test(navigator.userAgent) || navigator.isCocoonJS) { - if (typeof(window.DOMParser) === 'function') { + if (!responseXML || /MSIE 9/i.test(navigator.userAgent) || navigator.isCocoonJS) + { + if (typeof(window.DOMParser) === 'function') + { var domparser = new DOMParser(); responseXML = domparser.parseFromString(this.ajaxRequest.responseText, 'text/xml'); } else { @@ -102,7 +110,8 @@ //parse letters var letters = responseXML.getElementsByTagName('char'); - for (var i = 0; i < letters.length; i++) { + for (var i = 0; i < letters.length; i++) + { var charCode = parseInt(letters[i].getAttribute('id'), 10); var textureRect = new core.math.Rectangle( @@ -124,7 +133,8 @@ //parse kernings var kernings = responseXML.getElementsByTagName('kerning'); - for (i = 0; i < kernings.length; i++) { + for (i = 0; i < kernings.length; i++) + { var first = parseInt(kernings[i].getAttribute('first'), 10); var second = parseInt(kernings[i].getAttribute('second'), 10); var amount = parseInt(kernings[i].getAttribute('amount'), 10); @@ -146,6 +156,7 @@ * * @private */ -BitmapFontLoader.prototype.onLoaded = function () { +BitmapFontLoader.prototype.onLoaded = function () +{ this.emit('loaded', { content: this }); }; diff --git a/src/loaders/ImageLoader.js b/src/loaders/ImageLoader.js index e3ff493..16ee7c8 100644 --- a/src/loaders/ImageLoader.js +++ b/src/loaders/ImageLoader.js @@ -11,7 +11,8 @@ * @param url {String} The url of the image * @param crossorigin {boolean} Whether requests should be treated as crossorigin */ -function ImageLoader(url, crossorigin) { +function ImageLoader(url, crossorigin) +{ /** * The texture being loaded * @@ -39,12 +40,15 @@ * Loads image or takes it from cache * */ -ImageLoader.prototype.load = function () { - if (!this.texture.baseTexture.hasLoaded) { +ImageLoader.prototype.load = function () +{ + if (!this.texture.baseTexture.hasLoaded) + { this.texture.baseTexture.on('loaded', this.onLoaded.bind(this)); this.texture.baseTexture.on('error', this.onError.bind(this)); } - else { + else + { this.onLoaded(); } }; @@ -54,7 +58,8 @@ * * @private */ -ImageLoader.prototype.onLoaded = function () { +ImageLoader.prototype.onLoaded = function () +{ this.emit('loaded', { content: this }); }; @@ -64,7 +69,8 @@ * @method onError * @private */ -ImageLoader.prototype.onError = function () { +ImageLoader.prototype.onError = function () +{ this.emit('error', { content: this }); }; @@ -75,15 +81,18 @@ * @param frameHeight {number} height of each frame * @param textureName {String} if given, the frames will be cached in - format */ -ImageLoader.prototype.loadFramedSpriteSheet = function (frameWidth, frameHeight, textureName) { +ImageLoader.prototype.loadFramedSpriteSheet = function (frameWidth, frameHeight, textureName) +{ this.frames = []; var cols = Math.floor(this.texture.width / frameWidth); var rows = Math.floor(this.texture.height / frameHeight); var i=0; - for (var y = 0; y < rows; ++y) { - for (var x = 0; x < cols; ++x, ++i) { + for (var y = 0; y < rows; ++y) + { + for (var x = 0; x < cols; ++x, ++i) + { var texture = new core.Texture( this.texture.baseTexture, new core.math.Rectangle( @@ -96,7 +105,8 @@ this.frames.push(texture); - if (textureName) { + if (textureName) + { core.utils.TextureCache[textureName + '-' + i] = texture; } } diff --git a/src/loaders/JsonLoader.js b/src/loaders/JsonLoader.js index 3279f40..7aabeb4 100644 --- a/src/loaders/JsonLoader.js +++ b/src/loaders/JsonLoader.js @@ -14,7 +14,8 @@ * @param url {String} The url of the JSON file * @param crossorigin {boolean} Whether requests should be treated as crossorigin */ -function JsonLoader(url, crossorigin) { +function JsonLoader(url, crossorigin) +{ /** * The url of the bitmap font data * @@ -56,8 +57,10 @@ * Loads the JSON data * */ -JsonLoader.prototype.load = function () { - if (window.XDomainRequest && this.crossorigin) { +JsonLoader.prototype.load = function () +{ + if (window.XDomainRequest && this.crossorigin) + { this.ajaxRequest = new window.XDomainRequest(); // XDomainRequest has a few quirks. Occasionally it will abort requests @@ -68,15 +71,19 @@ this.ajaxRequest.onerror = this.onError.bind(this); this.ajaxRequest.ontimeout = this.onError.bind(this); - this.ajaxRequest.onprogress = function () {}; + this.ajaxRequest.onprogress = function () + {}; this.ajaxRequest.onload = this.onJSONLoaded.bind(this); } - else { - if (window.XMLHttpRequest) { + else + { + if (window.XMLHttpRequest) + { this.ajaxRequest = new window.XMLHttpRequest(); } - else { + else + { this.ajaxRequest = new window.ActiveXObject('Microsoft.XMLHTTP'); } @@ -93,8 +100,10 @@ * * @private */ -JsonLoader.prototype.onReadyStateChanged = function () { - if (this.ajaxRequest.readyState === 4 && (this.ajaxRequest.status === 200 || window.location.href.indexOf('http') === -1)) { +JsonLoader.prototype.onReadyStateChanged = function () +{ + if (this.ajaxRequest.readyState === 4 && (this.ajaxRequest.status === 200 || window.location.href.indexOf('http') === -1)) + { this.onJSONLoaded(); } }; @@ -104,15 +113,18 @@ * * @private */ -JsonLoader.prototype.onJSONLoaded = function () { - if (!this.ajaxRequest.responseText) { +JsonLoader.prototype.onJSONLoaded = function () +{ + if (!this.ajaxRequest.responseText) + { this.onError(); return; } this.json = JSON.parse(this.ajaxRequest.responseText); - if (this.json.frames) { + if (this.json.frames) + { // sprite sheet var textureUrl = this.baseUrl + this.json.meta.image; var image = new ImageLoader(textureUrl, this.crossorigin); @@ -122,16 +134,19 @@ image.addEventListener('loaded', this.onLoaded.bind(this)); image.addEventListener('error', this.onError.bind(this)); - for (var i in frameData) { + for (var i in frameData) + { var rect = frameData[i].frame; - if (rect) { + if (rect) + { var textureSize = new core.math.Rectangle(rect.x, rect.y, rect.w, rect.h); var crop = textureSize.clone(); var trim = null; // Check to see if the sprite is trimmed - if (frameData[i].trimmed) { + if (frameData[i].trimmed) + { var actualSize = frameData[i].sourceSize; var realSize = frameData[i].spriteSourceSize; trim = new core.math.Rectangle(realSize.x, realSize.y, actualSize.w, actualSize.h); @@ -143,12 +158,15 @@ image.load(); } - else if (this.json.bones) { + else if (this.json.bones) + { // check if the json was loaded before - if (core.utils.AnimCache[this.url]) { + if (core.utils.AnimCache[this.url]) + { this.onLoaded(); } - else { + else + { /** * use a bit of hackery to load the atlas file, here we assume that the .json, .atlas and .png files * that correspond to the spine file are in the same base URL and that the .json and .atlas files @@ -159,9 +177,11 @@ // save a copy of the current object for future reference // var originalLoader = this; // before loading the file, replace the "onJSONLoaded" function for our own // - atlasLoader.onJSONLoaded = function () { + atlasLoader.onJSONLoaded = function () + { // at this point "this" points at the atlasLoader (JsonLoader) instance // - if (!this.ajaxRequest.responseText) { + if (!this.ajaxRequest.responseText) + { this.onError(); // FIXME: hmm, this is funny because we are not responding to errors yet return; } @@ -179,14 +199,18 @@ originalLoader.spineAtlas = spineAtlas; originalLoader.spineAtlasLoader = atlasLoader; // wait for textures to finish loading if needed - if (textureLoader.loadingCount > 0) { - textureLoader.addEventListener('loadedBaseTexture', function (evt){ - if (evt.content.content.loadingCount <= 0) { + if (textureLoader.loadingCount > 0) + { + textureLoader.addEventListener('loadedBaseTexture', function (evt) + { + if (evt.content.content.loadingCount <= 0) + { originalLoader.onLoaded(); } }); } - else { + else + { originalLoader.onLoaded(); } }; @@ -194,7 +218,8 @@ atlasLoader.load(); } } - else { + else + { this.onLoaded(); } }; @@ -204,7 +229,8 @@ * * @private */ -JsonLoader.prototype.onLoaded = function () { +JsonLoader.prototype.onLoaded = function () +{ this.loaded = true; this.dispatchEvent({ type: 'loaded', @@ -217,7 +243,8 @@ * * @private */ -JsonLoader.prototype.onError = function () { +JsonLoader.prototype.onError = function () +{ this.dispatchEvent({ type: 'error', diff --git a/src/loaders/SpineLoader.js b/src/loaders/SpineLoader.js index 51aaddb..69bae21 100644 --- a/src/loaders/SpineLoader.js +++ b/src/loaders/SpineLoader.js @@ -24,7 +24,8 @@ * @param url {String} The url of the JSON file * @param crossorigin {boolean} Whether requests should be treated as crossorigin */ -function SpineLoader(url, crossorigin) { +function SpineLoader(url, crossorigin) +{ /** * The url of the bitmap font data * @@ -57,11 +58,13 @@ * Loads the JSON data * */ -SpineLoader.prototype.load = function () { +SpineLoader.prototype.load = function () +{ var scope = this; var jsonLoader = new JsonLoader(this.url, this.crossorigin); - jsonLoader.on('loaded', function (event) { + jsonLoader.on('loaded', function (event) + { scope.json = event.data.content.json; scope.onLoaded(); }); @@ -74,7 +77,8 @@ * * @private */ -SpineLoader.prototype.onLoaded = function () { +SpineLoader.prototype.onLoaded = function () +{ this.loaded = true; this.emit('loaded', { content: this }); }; diff --git a/src/loaders/SpineTextureLoader.js b/src/loaders/SpineTextureLoader.js index 61c51c0..c09a548 100644 --- a/src/loaders/SpineTextureLoader.js +++ b/src/loaders/SpineTextureLoader.js @@ -9,7 +9,8 @@ * @param basePath {string} Tha base path where to look for the images to be loaded * @param crossorigin {boolean} Whether requests should be treated as crossorigin */ -function SpineTextureLoader(basePath, crossorigin) { +function SpineTextureLoader(basePath, crossorigin) +{ this.basePath = basePath; this.crossorigin = crossorigin; this.loadingCount = 0; @@ -26,12 +27,15 @@ * @param page {spine.AtlasPage} Atlas page to which texture belongs * @param file {string} The file to load, this is just the file path relative to the base path configured in the constructor */ -SpineTextureLoader.prototype.load = function (page, file) { +SpineTextureLoader.prototype.load = function (page, file) +{ page.rendererObject = core.BaseTexture.fromImage(this.basePath + '/' + file, this.crossorigin); - if (!page.rendererObject.hasLoaded) { + if (!page.rendererObject.hasLoaded) + { var scope = this; ++scope.loadingCount; - page.rendererObject.addEventListener('loaded', function (){ + page.rendererObject.addEventListener('loaded', function () + { --scope.loadingCount; scope.dispatchEvent({ type: 'loadedBaseTexture', @@ -46,6 +50,7 @@ * * @param texture {BaseTexture} Texture object to destroy */ -SpineTextureLoader.prototype.unload = function (texture) { +SpineTextureLoader.prototype.unload = function (texture) +{ texture.destroy(true); }; diff --git a/src/loaders/SpriteSheetLoader.js b/src/loaders/SpriteSheetLoader.js index 5ee79df..a554e9d 100644 --- a/src/loaders/SpriteSheetLoader.js +++ b/src/loaders/SpriteSheetLoader.js @@ -16,7 +16,8 @@ * @param url {String} The url of the sprite sheet JSON file * @param crossorigin {boolean} Whether requests should be treated as crossorigin */ -function SpriteSheetLoader(url, crossorigin) { +function SpriteSheetLoader(url, crossorigin) +{ /** * The url of the atlas data @@ -65,11 +66,13 @@ * This will begin loading the JSON file * */ -SpriteSheetLoader.prototype.load = function () { +SpriteSheetLoader.prototype.load = function () +{ var scope = this; var jsonLoader = new JsonLoader(this.url, this.crossorigin); - jsonLoader.on('loaded', function (event) { + jsonLoader.on('loaded', function (event) + { scope.json = event.data.content.json; scope.onLoaded(); }); @@ -82,7 +85,8 @@ * * @private */ -SpriteSheetLoader.prototype.onLoaded = function () { +SpriteSheetLoader.prototype.onLoaded = function () +{ this.emit('loaded', { content: this }); diff --git a/src/spine/Spine.js b/src/spine/Spine.js index be7ad18..ce425cc 100644 --- a/src/spine/Spine.js +++ b/src/spine/Spine.js @@ -15,12 +15,14 @@ * @namespace PIXI * @param url {string} The url of the spine anim file to be used */ -function Spine(url) { +function Spine(url) +{ core.DisplayObjectContainer.call(this); this.spineData = core.utils.AnimCache[url]; - if (!this.spineData) { + if (!this.spineData) + { throw new Error('Spine data must be preloaded using SpineLoader or AssetLoader: ' + url); } @@ -32,27 +34,31 @@ this.slotContainers = []; - for (var i = 0, n = this.skeleton.drawOrder.length; i < n; i++) { + for (var i = 0, n = this.skeleton.drawOrder.length; i < n; i++) + { var slot = this.skeleton.drawOrder[i]; var attachment = slot.attachment; var slotContainer = new core.DisplayObjectContainer(); this.slotContainers.push(slotContainer); this.addChild(slotContainer); - if (attachment instanceof spine.RegionAttachment) { + if (attachment instanceof spine.RegionAttachment) + { var spriteName = attachment.rendererObject.name; var sprite = this.createSprite(slot, attachment); slot.currentSprite = sprite; slot.currentSpriteName = spriteName; slotContainer.addChild(sprite); } - else if (attachment instanceof spine.MeshAttachment) { + else if (attachment instanceof spine.MeshAttachment) + { var mesh = this.createMesh(slot, attachment); slot.currentMesh = mesh; slot.currentMeshName = attachment.name; slotContainer.addChild(mesh); } - else { + else + { continue; } @@ -78,11 +84,13 @@ * @default true */ autoUpdate: { - get: function () { + get: function () + { return (this.updateTransform === Spine.prototype.autoUpdateTransform); }, - set: function (value) { + set: function (value) + { this.updateTransform = value ? Spine.prototype.autoUpdateTransform : core.DisplayObjectContainer.prototype.updateTransform; } } @@ -93,35 +101,44 @@ * * @param dt {number} Delta time. Time by which the animation should be updated */ -Spine.prototype.update = function (dt) { +Spine.prototype.update = function (dt) +{ this.state.update(dt); this.state.apply(this.skeleton); this.skeleton.updateWorldTransform(); var drawOrder = this.skeleton.drawOrder; - for (var i = 0, n = drawOrder.length; i < n; i++) { + for (var i = 0, n = drawOrder.length; i < n; i++) + { var slot = drawOrder[i]; var attachment = slot.attachment; var slotContainer = this.slotContainers[i]; - if (!attachment) { + if (!attachment) + { slotContainer.visible = false; continue; } var type = attachment.type; - if (type === spine.AttachmentType.region) { - if (attachment.rendererObject) { - if (!slot.currentSpriteName || slot.currentSpriteName !== attachment.rendererObject.name) { + if (type === spine.AttachmentType.region) + { + if (attachment.rendererObject) + { + if (!slot.currentSpriteName || slot.currentSpriteName !== attachment.rendererObject.name) + { var spriteName = attachment.rendererObject.name; - if (slot.currentSprite !== undefined) { + if (slot.currentSprite !== undefined) + { slot.currentSprite.visible = false; } slot.sprites = slot.sprites || {}; - if (slot.sprites[spriteName] !== undefined) { + if (slot.sprites[spriteName] !== undefined) + { slot.sprites[spriteName].visible = true; } - else { + else + { var sprite = this.createSprite(slot, attachment); slotContainer.addChild(sprite); } @@ -141,19 +158,24 @@ slot.currentSprite.tint = core.utils.rgb2hex([slot.r,slot.g,slot.b]); } - else if (type === spine.AttachmentType.skinnedmesh) { - if (!slot.currentMeshName || slot.currentMeshName !== attachment.name) { + else if (type === spine.AttachmentType.skinnedmesh) + { + if (!slot.currentMeshName || slot.currentMeshName !== attachment.name) + { var meshName = attachment.name; - if (slot.currentMesh !== undefined) { + if (slot.currentMesh !== undefined) + { slot.currentMesh.visible = false; } slot.meshes = slot.meshes || {}; - if (slot.meshes[meshName] !== undefined) { + if (slot.meshes[meshName] !== undefined) + { slot.meshes[meshName].visible = true; } - else { + else + { var mesh = this.createMesh(slot, attachment); slotContainer.addChild(mesh); } @@ -165,7 +187,8 @@ attachment.computeWorldVertices(slot.bone.skeleton.x, slot.bone.skeleton.y, slot, slot.currentMesh.vertices); } - else { + else + { slotContainer.visible = false; continue; } @@ -180,7 +203,8 @@ * * @private */ -Spine.prototype.autoUpdateTransform = function () { +Spine.prototype.autoUpdateTransform = function () +{ this.lastTime = this.lastTime || Date.now(); var timeDelta = (Date.now() - this.lastTime) * 0.001; this.lastTime = Date.now(); @@ -197,7 +221,8 @@ * @param attachment {spine.RegionAttachment} The attachment that the sprite will represent * @private */ -Spine.prototype.createSprite = function (slot, attachment) { +Spine.prototype.createSprite = function (slot, attachment) +{ var descriptor = attachment.rendererObject; var baseTexture = descriptor.page.rendererObject; var spriteRect = new core.math.Rectangle(descriptor.x, @@ -223,7 +248,8 @@ * @param attachment {spine.RegionAttachment} The attachment that the sprite will represent * @private */ -Spine.prototype.createMesh = function (slot, attachment) { +Spine.prototype.createMesh = function (slot, attachment) +{ var descriptor = attachment.rendererObject; var baseTexture = descriptor.page.rendererObject; var texture = new core.Texture(baseTexture); diff --git a/src/spine/SpineRuntime.js b/src/spine/SpineRuntime.js index 392a878..fadd1b5 100644 --- a/src/spine/SpineRuntime.js +++ b/src/spine/SpineRuntime.js @@ -36,7 +36,8 @@ Uint16Array: (typeof(Uint16Array) === 'undefined') ? Array : Uint16Array }; -spine.BoneData = function (name, parent) { +spine.BoneData = function (name, parent) +{ this.name = name; this.parent = parent; }; @@ -50,7 +51,8 @@ flipX: false, flipY: false }; -spine.SlotData = function (name, boneData) { +spine.SlotData = function (name, boneData) +{ this.name = name; this.boneData = boneData; }; @@ -60,7 +62,8 @@ additiveBlending: false }; -spine.IkConstraintData = function (name) { +spine.IkConstraintData = function (name) +{ this.name = name; this.bones = []; }; @@ -70,7 +73,8 @@ mix: 1 }; -spine.Bone = function (boneData, skeleton, parent) { +spine.Bone = function (boneData, skeleton, parent) +{ this.data = boneData; this.skeleton = skeleton; this.parent = parent; @@ -87,12 +91,15 @@ worldRotation: 0, worldScaleX: 1, worldScaleY: 1, worldFlipX: false, worldFlipY: false, - updateWorldTransform: function () { + updateWorldTransform: function () + { var parent = this.parent; - if (parent) { + if (parent) + { this.worldX = this.x * parent.m00 + this.y * parent.m01 + parent.worldX; this.worldY = this.x * parent.m10 + this.y * parent.m11 + parent.worldY; - if (this.data.inheritScale) { + if (this.data.inheritScale) + { this.worldScaleX = parent.worldScaleX * this.scaleX; this.worldScaleY = parent.worldScaleY * this.scaleY; } else { @@ -115,14 +122,16 @@ var radians = this.worldRotation * spine.degRad; var cos = Math.cos(radians); var sin = Math.sin(radians); - if (this.worldFlipX) { + if (this.worldFlipX) + { this.m00 = -cos * this.worldScaleX; this.m01 = sin * this.worldScaleY; } else { this.m00 = cos * this.worldScaleX; this.m01 = -sin * this.worldScaleY; } - if (this.worldFlipY != spine.Bone.yDown) { + if (this.worldFlipY != spine.Bone.yDown) + { this.m10 = -sin * this.worldScaleX; this.m11 = -cos * this.worldScaleY; } else { @@ -130,7 +139,8 @@ this.m11 = cos * this.worldScaleY; } }, - setToSetupPose: function () { + setToSetupPose: function () + { var data = this.data; this.x = data.x; this.y = data.y; @@ -141,10 +151,12 @@ this.flipX = data.flipX; this.flipY = data.flipY; }, - worldToLocal: function (world) { + worldToLocal: function (world) + { var dx = world[0] - this.worldX, dy = world[1] - this.worldY; var m00 = this.m00, m10 = this.m10, m01 = this.m01, m11 = this.m11; - if (this.worldFlipX != (this.worldFlipY != spine.Bone.yDown)) { + if (this.worldFlipX != (this.worldFlipY != spine.Bone.yDown)) + { m00 = -m00; m11 = -m11; } @@ -152,14 +164,16 @@ world[0] = dx * m00 * invDet - dy * m01 * invDet; world[1] = dy * m11 * invDet - dx * m10 * invDet; }, - localToWorld: function (local) { + localToWorld: function (local) + { var localX = local[0], localY = local[1]; local[0] = localX * this.m00 + localY * this.m01 + this.worldX; local[1] = localX * this.m10 + localY * this.m11 + this.worldY; } }; -spine.Slot = function (slotData, bone) { +spine.Slot = function (slotData, bone) +{ this.data = slotData; this.bone = bone; this.setToSetupPose(); @@ -169,18 +183,22 @@ _attachmentTime: 0, attachment: null, attachmentVertices: [], - setAttachment: function (attachment) { + setAttachment: function (attachment) + { this.attachment = attachment; this._attachmentTime = this.bone.skeleton.time; this.attachmentVertices.length = 0; }, - setAttachmentTime: function (time) { + setAttachmentTime: function (time) + { this._attachmentTime = this.bone.skeleton.time - time; }, - getAttachmentTime: function () { + getAttachmentTime: function () + { return this.bone.skeleton.time - this._attachmentTime; }, - setToSetupPose: function () { + setToSetupPose: function () + { var data = this.data; this.r = data.r; this.g = data.g; @@ -188,8 +206,10 @@ this.a = data.a; var slotDatas = this.bone.skeleton.data.slots; - for (var i = 0, n = slotDatas.length; i < n; i++) { - if (slotDatas[i] == data) { + for (var i = 0, n = slotDatas.length; i < n; i++) + { + if (slotDatas[i] == data) + { this.setAttachment(!data.attachmentName ? null : this.bone.skeleton.getAttachmentBySlotIndex(i, data.attachmentName)); break; } @@ -197,7 +217,8 @@ } }; -spine.IkConstraint = function (data, skeleton) { +spine.IkConstraint = function (data, skeleton) +{ this.data = data; this.mix = data.mix; this.bendDirection = data.bendDirection; @@ -208,10 +229,12 @@ this.target = skeleton.findBone(data.target.name); }; spine.IkConstraint.prototype = { - apply: function () { + apply: function () + { var target = this.target; var bones = this.bones; - switch (bones.length) { + switch (bones.length) + { case 1: spine.IkConstraint.apply1(bones[0], target.worldX, target.worldY, this.mix); break; @@ -223,7 +246,8 @@ }; /** Adjusts the bone rotation so the tip is as close to the target position as possible. The target is specified in the world * coordinate system. */ -spine.IkConstraint.apply1 = function (bone, targetX, targetY, alpha) { +spine.IkConstraint.apply1 = function (bone, targetX, targetY, alpha) +{ var parentRotation = (!bone.data.inheritRotation || !bone.parent) ? 0 : bone.parent.worldRotation; var rotation = bone.rotation; var rotationIK = Math.atan2(targetY - bone.worldY, targetX - bone.worldX) * spine.radDeg - parentRotation; @@ -232,16 +256,19 @@ /** Adjusts the parent and child bone rotations so the tip of the child is as close to the target position as possible. The * target is specified in the world coordinate system. * @param child Any descendant bone of the parent. */ -spine.IkConstraint.apply2 = function (parent, child, targetX, targetY, bendDirection, alpha) { +spine.IkConstraint.apply2 = function (parent, child, targetX, targetY, bendDirection, alpha) +{ var childRotation = child.rotation, parentRotation = parent.rotation; - if (!alpha) { + if (!alpha) + { child.rotationIK = childRotation; parent.rotationIK = parentRotation; return; } var positionX, positionY, tempPosition = spine.temp; var parentParent = parent.parent; - if (parentParent) { + if (parentParent) + { tempPosition[0] = targetX; tempPosition[1] = targetY; parentParent.worldToLocal(tempPosition); @@ -251,7 +278,8 @@ targetX -= parent.x; targetY -= parent.y; } - if (child.parent == parent) { + if (child.parent == parent) + { positionX = child.x; positionY = child.y; } else { @@ -267,7 +295,8 @@ var len1 = Math.sqrt(childX * childX + childY * childY), len2 = child.data.length * child.worldScaleX; // Based on code by Ryan Juckett with permission: Copyright (c) 2008-2009 Ryan Juckett, http://www.ryanjuckett.com/ var cosDenom = 2 * len1 * len2; - if (cosDenom < 0.0001) { + if (cosDenom < 0.0001) + { child.rotationIK = childRotation + (Math.atan2(targetY, targetX) * spine.radDeg - parentRotation - childRotation) * alpha; return; } @@ -293,24 +322,30 @@ child.rotationIK = childRotation + (rotation + parent.worldRotation - child.parent.worldRotation) * alpha; }; -spine.Skin = function (name) { +spine.Skin = function (name) +{ this.name = name; this.attachments = {}; }; spine.Skin.prototype = { - addAttachment: function (slotIndex, name, attachment) { + addAttachment: function (slotIndex, name, attachment) + { this.attachments[slotIndex + ":" + name] = attachment; }, - getAttachment: function (slotIndex, name) { + getAttachment: function (slotIndex, name) + { return this.attachments[slotIndex + ":" + name]; }, - _attachAll: function (skeleton, oldSkin) { - for (var key in oldSkin.attachments) { + _attachAll: function (skeleton, oldSkin) + { + for (var key in oldSkin.attachments) + { var colon = key.indexOf(":"); var slotIndex = parseInt(key.substring(0, colon)); var name = key.substring(colon + 1); var slot = skeleton.slots[slotIndex]; - if (slot.attachment && slot.attachment.name == name) { + if (slot.attachment && slot.attachment.name == name) + { var attachment = this.getAttachment(slotIndex, name); if (attachment) slot.setAttachment(attachment); } @@ -318,14 +353,17 @@ } }; -spine.Animation = function (name, timelines, duration) { +spine.Animation = function (name, timelines, duration) +{ this.name = name; this.timelines = timelines; this.duration = duration; }; spine.Animation.prototype = { - apply: function (skeleton, lastTime, time, loop, events) { - if (loop && this.duration != 0) { + apply: function (skeleton, lastTime, time, loop, events) + { + if (loop && this.duration != 0) + { time %= this.duration; lastTime %= this.duration; } @@ -333,8 +371,10 @@ for (var i = 0, n = timelines.length; i < n; i++) timelines[i].apply(skeleton, lastTime, time, events, 1); }, - mix: function (skeleton, lastTime, time, loop, events, alpha) { - if (loop && this.duration != 0) { + mix: function (skeleton, lastTime, time, loop, events, alpha) + { + if (loop && this.duration != 0) + { time %= this.duration; lastTime %= this.duration; } @@ -343,12 +383,14 @@ timelines[i].apply(skeleton, lastTime, time, events, alpha); } }; -spine.Animation.binarySearch = function (values, target, step) { +spine.Animation.binarySearch = function (values, target, step) +{ var low = 0; var high = Math.floor(values.length / step) - 2; if (!high) return step; var current = high >>> 1; - while (true) { + while (true) + { if (values[(current + 1) * step] <= target) low = current + 1; else @@ -357,12 +399,14 @@ current = (low + high) >>> 1; } }; -spine.Animation.binarySearch1 = function (values, target) { +spine.Animation.binarySearch1 = function (values, target) +{ var low = 0; var high = values.length - 2; if (!high) return 1; var current = high >>> 1; - while (true) { + while (true) + { if (values[current + 1] <= target) low = current + 1; else @@ -371,27 +415,32 @@ current = (low + high) >>> 1; } }; -spine.Animation.linearSearch = function (values, target, step) { +spine.Animation.linearSearch = function (values, target, step) +{ for (var i = 0, last = values.length - step; i <= last; i += step) if (values[i] > target) return i; return -1; }; -spine.Curves = function (frameCount) { +spine.Curves = function (frameCount) +{ this.curves = []; // type, x, y, ... //this.curves.length = (frameCount - 1) * 19/*BEZIER_SIZE*/; }; spine.Curves.prototype = { - setLinear: function (frameIndex) { + setLinear: function (frameIndex) + { this.curves[frameIndex * 19/*BEZIER_SIZE*/] = 0/*LINEAR*/; }, - setStepped: function (frameIndex) { + setStepped: function (frameIndex) + { this.curves[frameIndex * 19/*BEZIER_SIZE*/] = 1/*STEPPED*/; }, /** Sets the control handle positions for an interpolation bezier curve used to transition from this keyframe to the next. * cx1 and cx2 are from 0 to 1, representing the percent of time between the two keyframes. cy1 and cy2 are the percent of * the difference between the keyframe's values. */ - setCurve: function (frameIndex, cx1, cy1, cx2, cy2) { + setCurve: function (frameIndex, cx1, cy1, cx2, cy2) + { var subdiv1 = 1 / 10/*BEZIER_SEGMENTS*/, subdiv2 = subdiv1 * subdiv1, subdiv3 = subdiv2 * subdiv1; var pre1 = 3 * subdiv1, pre2 = 3 * subdiv2, pre4 = 6 * subdiv2, pre5 = 6 * subdiv3; var tmp1x = -cx1 * 2 + cx2, tmp1y = -cy1 * 2 + cy2, tmp2x = (cx1 - cx2) * 3 + 1, tmp2y = (cy1 - cy2) * 3 + 1; @@ -404,7 +453,8 @@ curves[i++] = 2/*BEZIER*/; var x = dfx, y = dfy; - for (var n = i + 19/*BEZIER_SIZE*/ - 1; i < n; i += 2) { + for (var n = i + 19/*BEZIER_SIZE*/ - 1; i < n; i += 2) + { curves[i] = x; curves[i + 1] = y; dfx += ddfx; @@ -415,7 +465,8 @@ y += dfy; } }, - getCurvePercent: function (frameIndex, percent) { + getCurvePercent: function (frameIndex, percent) + { percent = percent < 0 ? 0 : (percent > 1 ? 1 : percent); var curves = this.curves; var i = frameIndex * 19/*BEZIER_SIZE*/; @@ -424,11 +475,14 @@ if (type == 1/*STEPPED*/) return 0; i++; var x = 0; - for (var start = i, n = i + 19/*BEZIER_SIZE*/ - 1; i < n; i += 2) { + for (var start = i, n = i + 19/*BEZIER_SIZE*/ - 1; i < n; i += 2) + { x = curves[i]; - if (x >= percent) { + if (x >= percent) + { var prevX, prevY; - if (i == start) { + if (i == start) + { prevX = 0; prevY = 0; } else { @@ -443,28 +497,33 @@ } }; -spine.RotateTimeline = function (frameCount) { +spine.RotateTimeline = function (frameCount) +{ this.curves = new spine.Curves(frameCount); this.frames = []; // time, angle, ... this.frames.length = frameCount * 2; }; spine.RotateTimeline.prototype = { boneIndex: 0, - getFrameCount: function () { + getFrameCount: function () + { return this.frames.length / 2; }, - setFrame: function (frameIndex, time, angle) { + setFrame: function (frameIndex, time, angle) + { frameIndex *= 2; this.frames[frameIndex] = time; this.frames[frameIndex + 1] = angle; }, - apply: function (skeleton, lastTime, time, firedEvents, alpha) { + apply: function (skeleton, lastTime, time, firedEvents, alpha) + { var frames = this.frames; if (time < frames[0]) return; // Time is before first frame. var bone = skeleton.bones[this.boneIndex]; - if (time >= frames[frames.length - 2]) { // Time is after last frame. + if (time >= frames[frames.length - 2]) + { // Time is after last frame. var amount = bone.data.rotation + frames[frames.length - 1] - bone.rotation; while (amount > 180) amount -= 360; @@ -495,29 +554,34 @@ } }; -spine.TranslateTimeline = function (frameCount) { +spine.TranslateTimeline = function (frameCount) +{ this.curves = new spine.Curves(frameCount); this.frames = []; // time, x, y, ... this.frames.length = frameCount * 3; }; spine.TranslateTimeline.prototype = { boneIndex: 0, - getFrameCount: function () { + getFrameCount: function () + { return this.frames.length / 3; }, - setFrame: function (frameIndex, time, x, y) { + setFrame: function (frameIndex, time, x, y) + { frameIndex *= 3; this.frames[frameIndex] = time; this.frames[frameIndex + 1] = x; this.frames[frameIndex + 2] = y; }, - apply: function (skeleton, lastTime, time, firedEvents, alpha) { + apply: function (skeleton, lastTime, time, firedEvents, alpha) + { var frames = this.frames; if (time < frames[0]) return; // Time is before first frame. var bone = skeleton.bones[this.boneIndex]; - if (time >= frames[frames.length - 3]) { // Time is after last frame. + if (time >= frames[frames.length - 3]) + { // Time is after last frame. bone.x += (bone.data.x + frames[frames.length - 2] - bone.x) * alpha; bone.y += (bone.data.y + frames[frames.length - 1] - bone.y) * alpha; return; @@ -536,29 +600,34 @@ } }; -spine.ScaleTimeline = function (frameCount) { +spine.ScaleTimeline = function (frameCount) +{ this.curves = new spine.Curves(frameCount); this.frames = []; // time, x, y, ... this.frames.length = frameCount * 3; }; spine.ScaleTimeline.prototype = { boneIndex: 0, - getFrameCount: function () { + getFrameCount: function () + { return this.frames.length / 3; }, - setFrame: function (frameIndex, time, x, y) { + setFrame: function (frameIndex, time, x, y) + { frameIndex *= 3; this.frames[frameIndex] = time; this.frames[frameIndex + 1] = x; this.frames[frameIndex + 2] = y; }, - apply: function (skeleton, lastTime, time, firedEvents, alpha) { + apply: function (skeleton, lastTime, time, firedEvents, alpha) + { var frames = this.frames; if (time < frames[0]) return; // Time is before first frame. var bone = skeleton.bones[this.boneIndex]; - if (time >= frames[frames.length - 3]) { // Time is after last frame. + if (time >= frames[frames.length - 3]) + { // Time is after last frame. bone.scaleX += (bone.data.scaleX * frames[frames.length - 2] - bone.scaleX) * alpha; bone.scaleY += (bone.data.scaleY * frames[frames.length - 1] - bone.scaleY) * alpha; return; @@ -577,17 +646,20 @@ } }; -spine.ColorTimeline = function (frameCount) { +spine.ColorTimeline = function (frameCount) +{ this.curves = new spine.Curves(frameCount); this.frames = []; // time, r, g, b, a, ... this.frames.length = frameCount * 5; }; spine.ColorTimeline.prototype = { slotIndex: 0, - getFrameCount: function () { + getFrameCount: function () + { return this.frames.length / 5; }, - setFrame: function (frameIndex, time, r, g, b, a) { + setFrame: function (frameIndex, time, r, g, b, a) + { frameIndex *= 5; this.frames[frameIndex] = time; this.frames[frameIndex + 1] = r; @@ -595,12 +667,14 @@ this.frames[frameIndex + 3] = b; this.frames[frameIndex + 4] = a; }, - apply: function (skeleton, lastTime, time, firedEvents, alpha) { + apply: function (skeleton, lastTime, time, firedEvents, alpha) + { var frames = this.frames; if (time < frames[0]) return; // Time is before first frame. var r, g, b, a; - if (time >= frames[frames.length - 5]) { + if (time >= frames[frames.length - 5]) + { // Time is after last frame. var i = frames.length - 1; r = frames[i - 3]; @@ -624,7 +698,8 @@ a = prevFrameA + (frames[frameIndex + 4/*FRAME_A*/] - prevFrameA) * percent; } var slot = skeleton.slots[this.slotIndex]; - if (alpha < 1) { + if (alpha < 1) + { slot.r += (r - slot.r) * alpha; slot.g += (g - slot.g) * alpha; slot.b += (b - slot.b) * alpha; @@ -638,7 +713,8 @@ } }; -spine.AttachmentTimeline = function (frameCount) { +spine.AttachmentTimeline = function (frameCount) +{ this.curves = new spine.Curves(frameCount); this.frames = []; // time, ... this.frames.length = frameCount; @@ -647,16 +723,20 @@ }; spine.AttachmentTimeline.prototype = { slotIndex: 0, - getFrameCount: function () { + getFrameCount: function () + { return this.frames.length; }, - setFrame: function (frameIndex, time, attachmentName) { + setFrame: function (frameIndex, time, attachmentName) + { this.frames[frameIndex] = time; this.attachmentNames[frameIndex] = attachmentName; }, - apply: function (skeleton, lastTime, time, firedEvents, alpha) { + apply: function (skeleton, lastTime, time, firedEvents, alpha) + { var frames = this.frames; - if (time < frames[0]) { + if (time < frames[0]) + { if (lastTime > time) this.apply(skeleton, lastTime, Number.MAX_VALUE, null, 0); return; } else if (lastTime > time) // @@ -671,28 +751,33 @@ } }; -spine.EventTimeline = function (frameCount) { +spine.EventTimeline = function (frameCount) +{ this.frames = []; // time, ... this.frames.length = frameCount; this.events = []; this.events.length = frameCount; }; spine.EventTimeline.prototype = { - getFrameCount: function () { + getFrameCount: function () + { return this.frames.length; }, - setFrame: function (frameIndex, time, event) { + setFrame: function (frameIndex, time, event) + { this.frames[frameIndex] = time; this.events[frameIndex] = event; }, /** Fires events for frames > lastTime and <= time. */ - apply: function (skeleton, lastTime, time, firedEvents, alpha) { + apply: function (skeleton, lastTime, time, firedEvents, alpha) + { if (!firedEvents) return; var frames = this.frames; var frameCount = frames.length; - if (lastTime > time) { // Fire events after last time for looped animations. + if (lastTime > time) + { // Fire events after last time for looped animations. this.apply(skeleton, lastTime, Number.MAX_VALUE, firedEvents, alpha); lastTime = -1; } else if (lastTime >= frames[frameCount - 1]) // Last time is after last frame. @@ -702,10 +787,12 @@ var frameIndex; if (lastTime < frames[0]) frameIndex = 0; - else { + else + { frameIndex = spine.Animation.binarySearch1(frames, lastTime); var frame = frames[frameIndex]; - while (frameIndex > 0) { // Fire multiple events with the same frame. + while (frameIndex > 0) + { // Fire multiple events with the same frame. if (frames[frameIndex - 1] != frame) break; frameIndex--; } @@ -716,21 +803,25 @@ } }; -spine.DrawOrderTimeline = function (frameCount) { +spine.DrawOrderTimeline = function (frameCount) +{ this.frames = []; // time, ... this.frames.length = frameCount; this.drawOrders = []; this.drawOrders.length = frameCount; }; spine.DrawOrderTimeline.prototype = { - getFrameCount: function () { + getFrameCount: function () + { return this.frames.length; }, - setFrame: function (frameIndex, time, drawOrder) { + setFrame: function (frameIndex, time, drawOrder) + { this.frames[frameIndex] = time; this.drawOrders[frameIndex] = drawOrder; }, - apply: function (skeleton, lastTime, time, firedEvents, alpha) { + apply: function (skeleton, lastTime, time, firedEvents, alpha) + { var frames = this.frames; if (time < frames[0]) return; // Time is before first frame. @@ -743,7 +834,8 @@ var drawOrder = skeleton.drawOrder; var slots = skeleton.slots; var drawOrderToSetupIndex = this.drawOrders[frameIndex]; - if (!drawOrderToSetupIndex) { + if (!drawOrderToSetupIndex) + { for (var i = 0, n = slots.length; i < n; i++) drawOrder[i] = slots[i]; } else { @@ -754,7 +846,8 @@ } }; -spine.FfdTimeline = function (frameCount) { +spine.FfdTimeline = function (frameCount) +{ this.curves = new spine.Curves(frameCount); this.frames = []; this.frames.length = frameCount; @@ -764,14 +857,17 @@ spine.FfdTimeline.prototype = { slotIndex: 0, attachment: 0, - getFrameCount: function () { + getFrameCount: function () + { return this.frames.length; }, - setFrame: function (frameIndex, time, vertices) { + setFrame: function (frameIndex, time, vertices) + { this.frames[frameIndex] = time; this.frameVertices[frameIndex] = vertices; }, - apply: function (skeleton, lastTime, time, firedEvents, alpha) { + apply: function (skeleton, lastTime, time, firedEvents, alpha) + { var slot = skeleton.slots[this.slotIndex]; if (slot.attachment != this.attachment) return; @@ -785,9 +881,11 @@ if (vertices.length != vertexCount) alpha = 1; vertices.length = vertexCount; - if (time >= frames[frames.length - 1]) { // Time is after last frame. + if (time >= frames[frames.length - 1]) + { // Time is after last frame. var lastVertices = frameVertices[frames.length - 1]; - if (alpha < 1) { + if (alpha < 1) + { for (var i = 0; i < vertexCount; i++) vertices[i] += (lastVertices[i] - vertices[i]) * alpha; } else { @@ -806,13 +904,16 @@ var prevVertices = frameVertices[frameIndex - 1]; var nextVertices = frameVertices[frameIndex]; - if (alpha < 1) { - for (var i = 0; i < vertexCount; i++) { + if (alpha < 1) + { + for (var i = 0; i < vertexCount; i++) + { var prev = prevVertices[i]; vertices[i] += (prev + (nextVertices[i] - prev) * percent - vertices[i]) * alpha; } } else { - for (var i = 0; i < vertexCount; i++) { + for (var i = 0; i < vertexCount; i++) + { var prev = prevVertices[i]; vertices[i] = prev + (nextVertices[i] - prev) * percent; } @@ -820,29 +921,34 @@ } }; -spine.IkConstraintTimeline = function (frameCount) { +spine.IkConstraintTimeline = function (frameCount) +{ this.curves = new spine.Curves(frameCount); this.frames = []; // time, mix, bendDirection, ... this.frames.length = frameCount * 3; }; spine.IkConstraintTimeline.prototype = { ikConstraintIndex: 0, - getFrameCount: function () { + getFrameCount: function () + { return this.frames.length / 3; }, - setFrame: function (frameIndex, time, mix, bendDirection) { + setFrame: function (frameIndex, time, mix, bendDirection) + { frameIndex *= 3; this.frames[frameIndex] = time; this.frames[frameIndex + 1] = mix; this.frames[frameIndex + 2] = bendDirection; }, - apply: function (skeleton, lastTime, time, firedEvents, alpha) { + apply: function (skeleton, lastTime, time, firedEvents, alpha) + { var frames = this.frames; if (time < frames[0]) return; // Time is before first frame. var ikConstraint = skeleton.ikConstraints[this.ikConstraintIndex]; - if (time >= frames[frames.length - 3]) { // Time is after last frame. + if (time >= frames[frames.length - 3]) + { // Time is after last frame. ikConstraint.mix += (frames[frames.length - 2] - ikConstraint.mix) * alpha; ikConstraint.bendDirection = frames[frames.length - 1]; return; @@ -861,24 +967,29 @@ } }; -spine.FlipXTimeline = function (frameCount) { +spine.FlipXTimeline = function (frameCount) +{ this.curves = new spine.Curves(frameCount); this.frames = []; // time, flip, ... this.frames.length = frameCount * 2; }; spine.FlipXTimeline.prototype = { boneIndex: 0, - getFrameCount: function () { + getFrameCount: function () + { return this.frames.length / 2; }, - setFrame: function (frameIndex, time, flip) { + setFrame: function (frameIndex, time, flip) + { frameIndex *= 2; this.frames[frameIndex] = time; this.frames[frameIndex + 1] = flip ? 1 : 0; }, - apply: function (skeleton, lastTime, time, firedEvents, alpha) { + apply: function (skeleton, lastTime, time, firedEvents, alpha) + { var frames = this.frames; - if (time < frames[0]) { + if (time < frames[0]) + { if (lastTime > time) this.apply(skeleton, lastTime, Number.MAX_VALUE, null, 0); return; } else if (lastTime > time) // @@ -889,24 +1000,29 @@ } }; -spine.FlipYTimeline = function (frameCount) { +spine.FlipYTimeline = function (frameCount) +{ this.curves = new spine.Curves(frameCount); this.frames = []; // time, flip, ... this.frames.length = frameCount * 2; }; spine.FlipYTimeline.prototype = { boneIndex: 0, - getFrameCount: function () { + getFrameCount: function () + { return this.frames.length / 2; }, - setFrame: function (frameIndex, time, flip) { + setFrame: function (frameIndex, time, flip) + { frameIndex *= 2; this.frames[frameIndex] = time; this.frames[frameIndex + 1] = flip ? 1 : 0; }, - apply: function (skeleton, lastTime, time, firedEvents, alpha) { + apply: function (skeleton, lastTime, time, firedEvents, alpha) + { var frames = this.frames; - if (time < frames[0]) { + if (time < frames[0]) + { if (lastTime > time) this.apply(skeleton, lastTime, Number.MAX_VALUE, null, 0); return; } else if (lastTime > time) // @@ -917,7 +1033,8 @@ } }; -spine.SkeletonData = function () { +spine.SkeletonData = function () +{ this.bones = []; this.slots = []; this.skins = []; @@ -931,57 +1048,66 @@ width: 0, height: 0, version: null, hash: null, /** @return May be null. */ - findBone: function (boneName) { + findBone: function (boneName) + { var bones = this.bones; for (var i = 0, n = bones.length; i < n; i++) if (bones[i].name == boneName) return bones[i]; return null; }, /** @return -1 if the bone was not found. */ - findBoneIndex: function (boneName) { + findBoneIndex: function (boneName) + { var bones = this.bones; for (var i = 0, n = bones.length; i < n; i++) if (bones[i].name == boneName) return i; return -1; }, /** @return May be null. */ - findSlot: function (slotName) { + findSlot: function (slotName) + { var slots = this.slots; - for (var i = 0, n = slots.length; i < n; i++) { + for (var i = 0, n = slots.length; i < n; i++) + { if (slots[i].name == slotName) return slot[i]; } return null; }, /** @return -1 if the bone was not found. */ - findSlotIndex: function (slotName) { + findSlotIndex: function (slotName) + { var slots = this.slots; for (var i = 0, n = slots.length; i < n; i++) if (slots[i].name == slotName) return i; return -1; }, /** @return May be null. */ - findSkin: function (skinName) { + findSkin: function (skinName) + { var skins = this.skins; for (var i = 0, n = skins.length; i < n; i++) if (skins[i].name == skinName) return skins[i]; return null; }, /** @return May be null. */ - findEvent: function (eventName) { + findEvent: function (eventName) + { var events = this.events; for (var i = 0, n = events.length; i < n; i++) if (events[i].name == eventName) return events[i]; return null; }, /** @return May be null. */ - findAnimation: function (animationName) { + findAnimation: function (animationName) + { var animations = this.animations; for (var i = 0, n = animations.length; i < n; i++) if (animations[i].name == animationName) return animations[i]; return null; }, /** @return May be null. */ - findIkConstraint: function (ikConstraintName) { + findIkConstraint: function (ikConstraintName) + { var ikConstraints = this.ikConstraints; for (var i = 0, n = ikConstraints.length; i < n; i++) if (ikConstraints[i].name == ikConstraintName) return ikConstraints[i]; @@ -989,11 +1115,13 @@ } }; -spine.Skeleton = function (skeletonData) { +spine.Skeleton = function (skeletonData) +{ this.data = skeletonData; this.bones = []; - for (var i = 0, n = skeletonData.bones.length; i < n; i++) { + for (var i = 0, n = skeletonData.bones.length; i < n; i++) + { var boneData = skeletonData.bones[i]; var parent = !boneData.parent ? null : this.bones[skeletonData.bones.indexOf(boneData.parent)]; this.bones.push(new spine.Bone(boneData, this, parent)); @@ -1001,7 +1129,8 @@ this.slots = []; this.drawOrder = []; - for (var i = 0, n = skeletonData.slots.length; i < n; i++) { + for (var i = 0, n = skeletonData.slots.length; i < n; i++) + { var slotData = skeletonData.slots[i]; var bone = this.bones[skeletonData.bones.indexOf(slotData.boneData)]; var slot = new spine.Slot(slotData, bone); @@ -1023,7 +1152,8 @@ time: 0, flipX: false, flipY: false, /** Caches information about bones and IK constraints. Must be called if bones or IK constraints are added or removed. */ - updateCache: function () { + updateCache: function () + { var ikConstraints = this.ikConstraints; var ikConstraintsCount = ikConstraints.length; @@ -1039,16 +1169,20 @@ var bones = this.bones; outer: - for (var i = 0, n = bones.length; i < n; i++) { + for (var i = 0, n = bones.length; i < n; i++) + { var bone = bones[i]; var current = bone; do { - for (var ii = 0; ii < ikConstraintsCount; ii++) { + for (var ii = 0; ii < ikConstraintsCount; ii++) + { var ikConstraint = ikConstraints[ii]; var parent = ikConstraint.bones[0]; var child= ikConstraint.bones[ikConstraint.bones.length - 1]; - while (true) { - if (current == child) { + while (true) + { + if (current == child) + { boneCache[ii].push(bone); boneCache[ii + 1].push(bone); continue outer; @@ -1063,14 +1197,17 @@ } }, /** Updates the world transform for each bone. */ - updateWorldTransform: function () { + updateWorldTransform: function () + { var bones = this.bones; - for (var i = 0, n = bones.length; i < n; i++) { + for (var i = 0, n = bones.length; i < n; i++) + { var bone = bones[i]; bone.rotationIK = bone.rotation; } var i = 0, last = this.boneCache.length - 1; - while (true) { + while (true) + { var cacheBones = this.boneCache[i]; for (var ii = 0, nn = cacheBones.length; ii < nn; ii++) cacheBones[ii].updateWorldTransform(); @@ -1080,63 +1217,74 @@ } }, /** Sets the bones and slots to their setup pose values. */ - setToSetupPose: function () { + setToSetupPose: function () + { this.setBonesToSetupPose(); this.setSlotsToSetupPose(); }, - setBonesToSetupPose: function () { + setBonesToSetupPose: function () + { var bones = this.bones; for (var i = 0, n = bones.length; i < n; i++) bones[i].setToSetupPose(); var ikConstraints = this.ikConstraints; - for (var i = 0, n = ikConstraints.length; i < n; i++) { + for (var i = 0, n = ikConstraints.length; i < n; i++) + { var ikConstraint = ikConstraints[i]; ikConstraint.bendDirection = ikConstraint.data.bendDirection; ikConstraint.mix = ikConstraint.data.mix; } }, - setSlotsToSetupPose: function () { + setSlotsToSetupPose: function () + { var slots = this.slots; var drawOrder = this.drawOrder; - for (var i = 0, n = slots.length; i < n; i++) { + for (var i = 0, n = slots.length; i < n; i++) + { drawOrder[i] = slots[i]; slots[i].setToSetupPose(i); } }, /** @return May return null. */ - getRootBone: function () { + getRootBone: function () + { return this.bones.length ? this.bones[0] : null; }, /** @return May be null. */ - findBone: function (boneName) { + findBone: function (boneName) + { var bones = this.bones; for (var i = 0, n = bones.length; i < n; i++) if (bones[i].data.name == boneName) return bones[i]; return null; }, /** @return -1 if the bone was not found. */ - findBoneIndex: function (boneName) { + findBoneIndex: function (boneName) + { var bones = this.bones; for (var i = 0, n = bones.length; i < n; i++) if (bones[i].data.name == boneName) return i; return -1; }, /** @return May be null. */ - findSlot: function (slotName) { + findSlot: function (slotName) + { var slots = this.slots; for (var i = 0, n = slots.length; i < n; i++) if (slots[i].data.name == slotName) return slots[i]; return null; }, /** @return -1 if the bone was not found. */ - findSlotIndex: function (slotName) { + findSlotIndex: function (slotName) + { var slots = this.slots; for (var i = 0, n = slots.length; i < n; i++) if (slots[i].data.name == slotName) return i; return -1; }, - setSkinByName: function (skinName) { + setSkinByName: function (skinName) + { var skin = this.data.findSkin(skinName); if (!skin) throw "Skin not found: " + skinName; this.setSkin(skin); @@ -1145,16 +1293,21 @@ * Attachments from the new skin are attached if the corresponding attachment from the old skin was attached. If there was * no old skin, each slot's setup mode attachment is attached from the new skin. * @param newSkin May be null. */ - setSkin: function (newSkin) { - if (newSkin) { + setSkin: function (newSkin) + { + if (newSkin) + { if (this.skin) newSkin._attachAll(this, this.skin); - else { + else + { var slots = this.slots; - for (var i = 0, n = slots.length; i < n; i++) { + for (var i = 0, n = slots.length; i < n; i++) + { var slot = slots[i]; var name = slot.data.attachmentName; - if (name) { + if (name) + { var attachment = newSkin.getAttachment(i, name); if (attachment) slot.setAttachment(attachment); } @@ -1164,12 +1317,15 @@ this.skin = newSkin; }, /** @return May be null. */ - getAttachmentBySlotName: function (slotName, attachmentName) { + getAttachmentBySlotName: function (slotName, attachmentName) + { return this.getAttachmentBySlotIndex(this.data.findSlotIndex(slotName), attachmentName); }, /** @return May be null. */ - getAttachmentBySlotIndex: function (slotIndex, attachmentName) { - if (this.skin) { + getAttachmentBySlotIndex: function (slotIndex, attachmentName) + { + if (this.skin) + { var attachment = this.skin.getAttachment(slotIndex, attachmentName); if (attachment) return attachment; } @@ -1177,13 +1333,17 @@ return null; }, /** @param attachmentName May be null. */ - setAttachment: function (slotName, attachmentName) { + setAttachment: function (slotName, attachmentName) + { var slots = this.slots; - for (var i = 0, n = slots.length; i < n; i++) { + for (var i = 0, n = slots.length; i < n; i++) + { var slot = slots[i]; - if (slot.data.name == slotName) { + if (slot.data.name == slotName) + { var attachment = null; - if (attachmentName) { + if (attachmentName) + { attachment = this.getAttachmentBySlotIndex(i, attachmentName); if (!attachment) throw "Attachment not found: " + attachmentName + ", for slot: " + slotName; } @@ -1194,18 +1354,21 @@ throw "Slot not found: " + slotName; }, /** @return May be null. */ - findIkConstraint: function (ikConstraintName) { + findIkConstraint: function (ikConstraintName) + { var ikConstraints = this.ikConstraints; for (var i = 0, n = ikConstraints.length; i < n; i++) if (ikConstraints[i].data.name == ikConstraintName) return ikConstraints[i]; return null; }, - update: function (delta) { + update: function (delta) + { this.time += delta; } }; -spine.EventData = function (name) { +spine.EventData = function (name) +{ this.name = name; }; spine.EventData.prototype = { @@ -1214,7 +1377,8 @@ stringValue: null }; -spine.Event = function (data) { +spine.Event = function (data) +{ this.data = data; }; spine.Event.prototype = { @@ -1230,7 +1394,8 @@ skinnedmesh: 3 }; -spine.RegionAttachment = function (name) { +spine.RegionAttachment = function (name) +{ this.name = name; this.offset = []; this.offset.length = 8; @@ -1249,9 +1414,11 @@ regionOffsetX: 0, regionOffsetY: 0, regionWidth: 0, regionHeight: 0, regionOriginalWidth: 0, regionOriginalHeight: 0, - setUVs: function (u, v, u2, v2, rotate) { + setUVs: function (u, v, u2, v2, rotate) + { var uvs = this.uvs; - if (rotate) { + if (rotate) + { uvs[2/*X2*/] = u; uvs[3/*Y2*/] = v2; uvs[4/*X3*/] = u; @@ -1271,7 +1438,8 @@ uvs[7/*Y4*/] = v2; } }, - updateOffset: function () { + updateOffset: function () + { var regionScaleX = this.width / this.regionOriginalWidth * this.scaleX; var regionScaleY = this.height / this.regionOriginalHeight * this.scaleY; var localX = -this.width / 2 * this.scaleX + this.regionOffsetX * regionScaleX; @@ -1299,7 +1467,8 @@ offset[6/*X4*/] = localX2Cos - localYSin; offset[7/*Y4*/] = localYCos + localX2Sin; }, - computeVertices: function (x, y, bone, vertices) { + computeVertices: function (x, y, bone, vertices) + { x += bone.worldX; y += bone.worldY; var m00 = bone.m00, m01 = bone.m01, m10 = bone.m10, m11 = bone.m11; @@ -1315,7 +1484,8 @@ } }; -spine.MeshAttachment = function (name) { +spine.MeshAttachment = function (name) +{ this.name = name; }; spine.MeshAttachment.prototype = { @@ -1334,25 +1504,31 @@ regionOriginalWidth: 0, regionOriginalHeight: 0, edges: null, width: 0, height: 0, - updateUVs: function () { + updateUVs: function () + { var width = this.regionU2 - this.regionU, height = this.regionV2 - this.regionV; var n = this.regionUVs.length; - if (!this.uvs || this.uvs.length != n) { + if (!this.uvs || this.uvs.length != n) + { this.uvs = new spine.Float32Array(n); } - if (this.regionRotate) { - for (var i = 0; i < n; i += 2) { + if (this.regionRotate) + { + for (var i = 0; i < n; i += 2) + { this.uvs[i] = this.regionU + this.regionUVs[i + 1] * width; this.uvs[i + 1] = this.regionV + height - this.regionUVs[i] * height; } } else { - for (var i = 0; i < n; i += 2) { + for (var i = 0; i < n; i += 2) + { this.uvs[i] = this.regionU + this.regionUVs[i] * width; this.uvs[i + 1] = this.regionV + this.regionUVs[i + 1] * height; } } }, - computeWorldVertices: function (x, y, slot, worldVertices) { + computeWorldVertices: function (x, y, slot, worldVertices) + { var bone = slot.bone; x += bone.worldX; y += bone.worldY; @@ -1360,7 +1536,8 @@ var vertices = this.vertices; var verticesCount = vertices.length; if (slot.attachmentVertices.length == verticesCount) vertices = slot.attachmentVertices; - for (var i = 0; i < verticesCount; i += 2) { + for (var i = 0; i < verticesCount; i += 2) + { var vx = vertices[i]; var vy = vertices[i + 1]; worldVertices[i] = vx * m00 + vy * m01 + x; @@ -1369,7 +1546,8 @@ } }; -spine.SkinnedMeshAttachment = function (name) { +spine.SkinnedMeshAttachment = function (name) +{ this.name = name; }; spine.SkinnedMeshAttachment.prototype = { @@ -1389,37 +1567,46 @@ regionOriginalWidth: 0, regionOriginalHeight: 0, edges: null, width: 0, height: 0, - updateUVs: function (u, v, u2, v2, rotate) { + updateUVs: function (u, v, u2, v2, rotate) + { var width = this.regionU2 - this.regionU, height = this.regionV2 - this.regionV; var n = this.regionUVs.length; - if (!this.uvs || this.uvs.length != n) { + if (!this.uvs || this.uvs.length != n) + { this.uvs = new spine.Float32Array(n); } - if (this.regionRotate) { - for (var i = 0; i < n; i += 2) { + if (this.regionRotate) + { + for (var i = 0; i < n; i += 2) + { this.uvs[i] = this.regionU + this.regionUVs[i + 1] * width; this.uvs[i + 1] = this.regionV + height - this.regionUVs[i] * height; } } else { - for (var i = 0; i < n; i += 2) { + for (var i = 0; i < n; i += 2) + { this.uvs[i] = this.regionU + this.regionUVs[i] * width; this.uvs[i + 1] = this.regionV + this.regionUVs[i + 1] * height; } } }, - computeWorldVertices: function (x, y, slot, worldVertices) { + computeWorldVertices: function (x, y, slot, worldVertices) + { var skeletonBones = slot.bone.skeleton.bones; var weights = this.weights; var bones = this.bones; var w = 0, v = 0, b = 0, f = 0, n = bones.length, nn; var wx, wy, bone, vx, vy, weight; - if (!slot.attachmentVertices.length) { - for (; v < n; w += 2) { + if (!slot.attachmentVertices.length) + { + for (; v < n; w += 2) + { wx = 0; wy = 0; nn = bones[v++] + v; - for (; v < nn; v++, b += 3) { + for (; v < nn; v++, b += 3) + { bone = skeletonBones[bones[v]]; vx = weights[b]; vy = weights[b + 1]; @@ -1432,11 +1619,13 @@ } } else { var ffd = slot.attachmentVertices; - for (; v < n; w += 2) { + for (; v < n; w += 2) + { wx = 0; wy = 0; nn = bones[v++] + v; - for (; v < nn; v++, b += 3, f += 2) { + for (; v < nn; v++, b += 3, f += 2) + { bone = skeletonBones[bones[v]]; vx = weights[b] + ffd[f]; vy = weights[b + 1] + ffd[f + 1]; @@ -1451,18 +1640,21 @@ } }; -spine.BoundingBoxAttachment = function (name) { +spine.BoundingBoxAttachment = function (name) +{ this.name = name; this.vertices = []; }; spine.BoundingBoxAttachment.prototype = { type: spine.AttachmentType.boundingbox, - computeWorldVertices: function (x, y, bone, worldVertices) { + computeWorldVertices: function (x, y, bone, worldVertices) + { x += bone.worldX; y += bone.worldY; var m00 = bone.m00, m01 = bone.m01, m10 = bone.m10, m11 = bone.m11; var vertices = this.vertices; - for (var i = 0, n = vertices.length; i < n; i += 2) { + for (var i = 0, n = vertices.length; i < n; i += 2) + { var px = vertices[i]; var py = vertices[i + 1]; worldVertices[i] = px * m00 + py * m01 + x; @@ -1471,29 +1663,34 @@ } }; -spine.AnimationStateData = function (skeletonData) { +spine.AnimationStateData = function (skeletonData) +{ this.skeletonData = skeletonData; this.animationToMixTime = {}; }; spine.AnimationStateData.prototype = { defaultMix: 0, - setMixByName: function (fromName, toName, duration) { + setMixByName: function (fromName, toName, duration) + { var from = this.skeletonData.findAnimation(fromName); if (!from) throw "Animation not found: " + fromName; var to = this.skeletonData.findAnimation(toName); if (!to) throw "Animation not found: " + toName; this.setMix(from, to, duration); }, - setMix: function (from, to, duration) { + setMix: function (from, to, duration) + { this.animationToMixTime[from.name + ":" + to.name] = duration; }, - getMix: function (from, to) { + getMix: function (from, to) + { var key = from.name + ":" + to.name; return this.animationToMixTime.hasOwnProperty(key) ? this.animationToMixTime[key] : this.defaultMix; } }; -spine.TrackEntry = function () {}; +spine.TrackEntry = function () +{}; spine.TrackEntry.prototype = { next: null, previous: null, animation: null, @@ -1504,7 +1701,8 @@ onStart: null, onEnd: null, onComplete: null, onEvent: null }; -spine.AnimationState = function (stateData) { +spine.AnimationState = function (stateData) +{ this.data = stateData; this.tracks = []; this.events = []; @@ -1515,21 +1713,25 @@ onComplete: null, onEvent: null, timeScale: 1, - update: function (delta) { + update: function (delta) + { delta *= this.timeScale; - for (var i = 0; i < this.tracks.length; i++) { + for (var i = 0; i < this.tracks.length; i++) + { var current = this.tracks[i]; if (!current) continue; current.time += delta * current.timeScale; - if (current.previous) { + if (current.previous) + { var previousDelta = delta * current.previous.timeScale; current.previous.time += previousDelta; current.mixTime += previousDelta; } var next = current.next; - if (next) { + if (next) + { next.time = current.lastTime - next.delay; if (next.time >= 0) this.setCurrent(i, next); } else { @@ -1538,8 +1740,10 @@ } } }, - apply: function (skeleton) { - for (var i = 0; i < this.tracks.length; i++) { + apply: function (skeleton) + { + for (var i = 0; i < this.tracks.length; i++) + { var current = this.tracks[i]; if (!current) continue; @@ -1552,7 +1756,8 @@ if (!loop && time > endTime) time = endTime; var previous = current.previous; - if (!previous) { + if (!previous) + { if (current.mix == 1) current.animation.apply(skeleton, current.lastTime, time, loop, this.events); else @@ -1563,21 +1768,24 @@ previous.animation.apply(skeleton, previousTime, previousTime, previous.loop, null); var alpha = current.mixTime / current.mixDuration * current.mix; - if (alpha >= 1) { + if (alpha >= 1) + { alpha = 1; current.previous = null; } current.animation.mix(skeleton, current.lastTime, time, loop, this.events, alpha); } - for (var ii = 0, nn = this.events.length; ii < nn; ii++) { + for (var ii = 0, nn = this.events.length; ii < nn; ii++) + { var event = this.events[ii]; if (current.onEvent) current.onEvent(i, event); if (this.onEvent) this.onEvent(i, event); } // Check if completed the animation or a loop iteration. - if (loop ? (lastTime % endTime > time % endTime) : (lastTime < endTime && time >= endTime)) { + if (loop ? (lastTime % endTime > time % endTime) : (lastTime < endTime && time >= endTime)) + { var count = Math.floor(time / endTime); if (current.onComplete) current.onComplete(i, count); if (this.onComplete) this.onComplete(i, count); @@ -1586,12 +1794,14 @@ current.lastTime = current.time; } }, - clearTracks: function () { + clearTracks: function () + { for (var i = 0, n = this.tracks.length; i < n; i++) this.clearTrack(i); this.tracks.length = 0; }, - clearTrack: function (trackIndex) { + clearTrack: function (trackIndex) + { if (trackIndex >= this.tracks.length) return; var current = this.tracks[trackIndex]; if (!current) return; @@ -1601,15 +1811,18 @@ this.tracks[trackIndex] = null; }, - _expandToIndex: function (index) { + _expandToIndex: function (index) + { if (index < this.tracks.length) return this.tracks[index]; while (index >= this.tracks.length) this.tracks.push(null); return null; }, - setCurrent: function (index, entry) { + setCurrent: function (index, entry) + { var current = this._expandToIndex(index); - if (current) { + if (current) + { var previous = current.previous; current.previous = null; @@ -1617,7 +1830,8 @@ if (this.onEnd) this.onEnd(index); entry.mixDuration = this.data.getMix(current.animation, entry.animation); - if (entry.mixDuration > 0) { + if (entry.mixDuration > 0) + { entry.mixTime = 0; // If a mix is in progress, mix from the closest animation. if (previous && current.mixTime / current.mixDuration < 0.5) @@ -1632,13 +1846,15 @@ if (entry.onStart) entry.onStart(index); if (this.onStart) this.onStart(index); }, - setAnimationByName: function (trackIndex, animationName, loop) { + setAnimationByName: function (trackIndex, animationName, loop) + { var animation = this.data.skeletonData.findAnimation(animationName); if (!animation) throw "Animation not found: " + animationName; return this.setAnimation(trackIndex, animation, loop); }, /** Set the current animation. Any queued animations are cleared. */ - setAnimation: function (trackIndex, animation, loop) { + setAnimation: function (trackIndex, animation, loop) + { var entry = new spine.TrackEntry(); entry.animation = animation; entry.loop = loop; @@ -1646,28 +1862,32 @@ this.setCurrent(trackIndex, entry); return entry; }, - addAnimationByName: function (trackIndex, animationName, loop, delay) { + addAnimationByName: function (trackIndex, animationName, loop, delay) + { var animation = this.data.skeletonData.findAnimation(animationName); if (!animation) throw "Animation not found: " + animationName; return this.addAnimation(trackIndex, animation, loop, delay); }, /** Adds an animation to be played delay seconds after the current or last queued animation. * @param delay May be <= 0 to use duration of previous animation minus any mix duration plus the negative delay. */ - addAnimation: function (trackIndex, animation, loop, delay) { + addAnimation: function (trackIndex, animation, loop, delay) + { var entry = new spine.TrackEntry(); entry.animation = animation; entry.loop = loop; entry.endTime = animation.duration; var last = this._expandToIndex(trackIndex); - if (last) { + if (last) + { while (last.next) last = last.next; last.next = entry; } else this.tracks[trackIndex] = entry; - if (delay <= 0) { + if (delay <= 0) + { if (last) delay += last.endTime - this.data.getMix(last.animation, animation); else @@ -1678,24 +1898,28 @@ return entry; }, /** May be null. */ - getCurrent: function (trackIndex) { + getCurrent: function (trackIndex) + { if (trackIndex >= this.tracks.length) return null; return this.tracks[trackIndex]; } }; -spine.SkeletonJson = function (attachmentLoader) { +spine.SkeletonJson = function (attachmentLoader) +{ this.attachmentLoader = attachmentLoader; }; spine.SkeletonJson.prototype = { scale: 1, - readSkeletonData: function (root, name) { + readSkeletonData: function (root, name) + { var skeletonData = new spine.SkeletonData(); skeletonData.name = name; // Skeleton. var skeletonMap = root["skeleton"]; - if (skeletonMap) { + if (skeletonMap) + { skeletonData.hash = skeletonMap["hash"]; skeletonData.version = skeletonMap["spine"]; skeletonData.width = skeletonMap["width"] || 0; @@ -1704,10 +1928,12 @@ // Bones. var bones = root["bones"]; - for (var i = 0, n = bones.length; i < n; i++) { + for (var i = 0, n = bones.length; i < n; i++) + { var boneMap = bones[i]; var parent = null; - if (boneMap["parent"]) { + if (boneMap["parent"]) + { parent = skeletonData.findBone(boneMap["parent"]); if (!parent) throw "Parent bone not found: " + boneMap["parent"]; } @@ -1725,13 +1951,16 @@ // IK constraints. var ik = root["ik"]; - if (ik) { - for (var i = 0, n = ik.length; i < n; i++) { + if (ik) + { + for (var i = 0, n = ik.length; i < n; i++) + { var ikMap = ik[i]; var ikConstraintData = new spine.IkConstraintData(ikMap["name"]); var bones = ikMap["bones"]; - for (var ii = 0, nn = bones.length; ii < nn; ii++) { + for (var ii = 0, nn = bones.length; ii < nn; ii++) + { var bone = skeletonData.findBone(bones[ii]); if (!bone) throw "IK bone not found: " + bones[ii]; ikConstraintData.bones.push(bone); @@ -1749,14 +1978,16 @@ // Slots. var slots = root["slots"]; - for (var i = 0, n = slots.length; i < n; i++) { + for (var i = 0, n = slots.length; i < n; i++) + { var slotMap = slots[i]; var boneData = skeletonData.findBone(slotMap["bone"]); if (!boneData) throw "Slot bone not found: " + slotMap["bone"]; var slotData = new spine.SlotData(slotMap["name"], boneData); var color = slotMap["color"]; - if (color) { + if (color) + { slotData.r = this.toColor(color, 0); slotData.g = this.toColor(color, 1); slotData.b = this.toColor(color, 2); @@ -1771,15 +2002,18 @@ // Skins. var skins = root["skins"]; - for (var skinName in skins) { + for (var skinName in skins) + { if (!skins.hasOwnProperty(skinName)) continue; var skinMap = skins[skinName]; var skin = new spine.Skin(skinName); - for (var slotName in skinMap) { + for (var slotName in skinMap) + { if (!skinMap.hasOwnProperty(slotName)) continue; var slotIndex = skeletonData.findSlotIndex(slotName); var slotEntry = skinMap[slotName]; - for (var attachmentName in slotEntry) { + for (var attachmentName in slotEntry) + { if (!slotEntry.hasOwnProperty(attachmentName)) continue; var attachment = this.readAttachment(skin, attachmentName, slotEntry[attachmentName]); if (attachment) skin.addAttachment(slotIndex, attachmentName, attachment); @@ -1791,7 +2025,8 @@ // Events. var events = root["events"]; - for (var eventName in events) { + for (var eventName in events) + { if (!events.hasOwnProperty(eventName)) continue; var eventMap = events[eventName]; var eventData = new spine.EventData(eventName); @@ -1803,21 +2038,24 @@ // Animations. var animations = root["animations"]; - for (var animationName in animations) { + for (var animationName in animations) + { if (!animations.hasOwnProperty(animationName)) continue; this.readAnimation(animationName, animations[animationName], skeletonData); } return skeletonData; }, - readAttachment: function (skin, name, map) { + readAttachment: function (skin, name, map) + { name = map["name"] || name; var type = spine.AttachmentType[map["type"] || "region"]; var path = map["path"] || name; var scale = this.scale; - if (type == spine.AttachmentType.region) { + if (type == spine.AttachmentType.region) + { var region = this.attachmentLoader.newRegionAttachment(skin, name, path); if (!region) return null; region.path = path; @@ -1830,7 +2068,8 @@ region.height = (map["height"] || 0) * scale; var color = map["color"]; - if (color) { + if (color) + { region.r = this.toColor(color, 0); region.g = this.toColor(color, 1); region.b = this.toColor(color, 2); @@ -1839,7 +2078,8 @@ region.updateOffset(); return region; - } else if (type == spine.AttachmentType.mesh) { + } else if (type == spine.AttachmentType.mesh) + { var mesh = this.attachmentLoader.newMeshAttachment(skin, name, path); if (!mesh) return null; mesh.path = path; @@ -1849,7 +2089,8 @@ mesh.updateUVs(); color = map["color"]; - if (color) { + if (color) + { mesh.r = this.toColor(color, 0); mesh.g = this.toColor(color, 1); mesh.b = this.toColor(color, 2); @@ -1861,7 +2102,8 @@ mesh.width = (map["width"] || 0) * scale; mesh.height = (map["height"] || 0) * scale; return mesh; - } else if (type == spine.AttachmentType.skinnedmesh) { + } else if (type == spine.AttachmentType.skinnedmesh) + { var mesh = this.attachmentLoader.newSkinnedMeshAttachment(skin, name, path); if (!mesh) return null; mesh.path = path; @@ -1870,10 +2112,12 @@ var vertices = this.getFloatArray(map, "vertices", 1); var weights = []; var bones = []; - for (var i = 0, n = vertices.length; i < n; ) { + for (var i = 0, n = vertices.length; i < n; ) + { var boneCount = vertices[i++] | 0; bones[bones.length] = boneCount; - for (var nn = i + boneCount * 4; i < nn; ) { + for (var nn = i + boneCount * 4; i < nn; ) + { bones[bones.length] = vertices[i]; weights[weights.length] = vertices[i + 1] * scale; weights[weights.length] = vertices[i + 2] * scale; @@ -1888,7 +2132,8 @@ mesh.updateUVs(); color = map["color"]; - if (color) { + if (color) + { mesh.r = this.toColor(color, 0); mesh.g = this.toColor(color, 1); mesh.b = this.toColor(color, 2); @@ -1900,7 +2145,8 @@ mesh.width = (map["width"] || 0) * scale; mesh.height = (map["height"] || 0) * scale; return mesh; - } else if (type == spine.AttachmentType.boundingbox) { + } else if (type == spine.AttachmentType.boundingbox) + { var attachment = this.attachmentLoader.newBoundingBoxAttachment(skin, name); var vertices = map["vertices"]; for (var i = 0, n = vertices.length; i < n; i++) @@ -1909,25 +2155,30 @@ } throw "Unknown attachment type: " + type; }, - readAnimation: function (name, map, skeletonData) { + readAnimation: function (name, map, skeletonData) + { var timelines = []; var duration = 0; var slots = map["slots"]; - for (var slotName in slots) { + for (var slotName in slots) + { if (!slots.hasOwnProperty(slotName)) continue; var slotMap = slots[slotName]; var slotIndex = skeletonData.findSlotIndex(slotName); - for (var timelineName in slotMap) { + for (var timelineName in slotMap) + { if (!slotMap.hasOwnProperty(timelineName)) continue; var values = slotMap[timelineName]; - if (timelineName == "color") { + if (timelineName == "color") + { var timeline = new spine.ColorTimeline(values.length); timeline.slotIndex = slotIndex; var frameIndex = 0; - for (var i = 0, n = values.length; i < n; i++) { + for (var i = 0, n = values.length; i < n; i++) + { var valueMap = values[i]; var color = valueMap["color"]; var r = this.toColor(color, 0); @@ -1941,12 +2192,14 @@ timelines.push(timeline); duration = Math.max(duration, timeline.frames[timeline.getFrameCount() * 5 - 5]); - } else if (timelineName == "attachment") { + } else if (timelineName == "attachment") + { var timeline = new spine.AttachmentTimeline(values.length); timeline.slotIndex = slotIndex; var frameIndex = 0; - for (var i = 0, n = values.length; i < n; i++) { + for (var i = 0, n = values.length; i < n; i++) + { var valueMap = values[i]; timeline.setFrame(frameIndex++, valueMap["time"], valueMap["name"]); } @@ -1959,21 +2212,25 @@ } var bones = map["bones"]; - for (var boneName in bones) { + for (var boneName in bones) + { if (!bones.hasOwnProperty(boneName)) continue; var boneIndex = skeletonData.findBoneIndex(boneName); if (boneIndex == -1) throw "Bone not found: " + boneName; var boneMap = bones[boneName]; - for (var timelineName in boneMap) { + for (var timelineName in boneMap) + { if (!boneMap.hasOwnProperty(timelineName)) continue; var values = boneMap[timelineName]; - if (timelineName == "rotate") { + if (timelineName == "rotate") + { var timeline = new spine.RotateTimeline(values.length); timeline.boneIndex = boneIndex; var frameIndex = 0; - for (var i = 0, n = values.length; i < n; i++) { + for (var i = 0, n = values.length; i < n; i++) + { var valueMap = values[i]; timeline.setFrame(frameIndex, valueMap["time"], valueMap["angle"]); this.readCurve(timeline, frameIndex, valueMap); @@ -1982,19 +2239,22 @@ timelines.push(timeline); duration = Math.max(duration, timeline.frames[timeline.getFrameCount() * 2 - 2]); - } else if (timelineName == "translate" || timelineName == "scale") { + } else if (timelineName == "translate" || timelineName == "scale") + { var timeline; var timelineScale = 1; if (timelineName == "scale") timeline = new spine.ScaleTimeline(values.length); - else { + else + { timeline = new spine.TranslateTimeline(values.length); timelineScale = this.scale; } timeline.boneIndex = boneIndex; var frameIndex = 0; - for (var i = 0, n = values.length; i < n; i++) { + for (var i = 0, n = values.length; i < n; i++) + { var valueMap = values[i]; var x = (valueMap["x"] || 0) * timelineScale; var y = (valueMap["y"] || 0) * timelineScale; @@ -2005,14 +2265,16 @@ timelines.push(timeline); duration = Math.max(duration, timeline.frames[timeline.getFrameCount() * 3 - 3]); - } else if (timelineName == "flipX" || timelineName == "flipY") { + } else if (timelineName == "flipX" || timelineName == "flipY") + { var x = timelineName == "flipX"; var timeline = x ? new spine.FlipXTimeline(values.length) : new spine.FlipYTimeline(values.length); timeline.boneIndex = boneIndex; var field = x ? "x" : "y"; var frameIndex = 0; - for (var i = 0, n = values.length; i < n; i++) { + for (var i = 0, n = values.length; i < n; i++) + { var valueMap = values[i]; timeline.setFrame(frameIndex, valueMap["time"], valueMap[field] || false); frameIndex++; @@ -2025,14 +2287,16 @@ } var ikMap = map["ik"]; - for (var ikConstraintName in ikMap) { + for (var ikConstraintName in ikMap) + { if (!ikMap.hasOwnProperty(ikConstraintName)) continue; var ikConstraint = skeletonData.findIkConstraint(ikConstraintName); var values = ikMap[ikConstraintName]; var timeline = new spine.IkConstraintTimeline(values.length); timeline.ikConstraintIndex = skeletonData.ikConstraints.indexOf(ikConstraint); var frameIndex = 0; - for (var i = 0, n = values.length; i < n; i++) { + for (var i = 0, n = values.length; i < n; i++) + { var valueMap = values[i]; var mix = valueMap.hasOwnProperty("mix") ? valueMap["mix"] : 1; var bendDirection = (!valueMap.hasOwnProperty("bendPositive") || valueMap["bendPositive"]) ? 1 : -1; @@ -2045,13 +2309,16 @@ } var ffd = map["ffd"]; - for (var skinName in ffd) { + for (var skinName in ffd) + { var skin = skeletonData.findSkin(skinName); var slotMap = ffd[skinName]; - for (slotName in slotMap) { + for (slotName in slotMap) + { var slotIndex = skeletonData.findSlotIndex(slotName); var meshMap = slotMap[slotName]; - for (var meshName in meshMap) { + for (var meshName in meshMap) + { var values = meshMap[meshName]; var timeline = new spine.FfdTimeline(values.length); var attachment = skin.getAttachment(slotIndex, meshName); @@ -2067,13 +2334,16 @@ vertexCount = attachment.weights.length / 3 * 2; var frameIndex = 0; - for (var i = 0, n = values.length; i < n; i++) { + for (var i = 0, n = values.length; i < n; i++) + { var valueMap = values[i]; var vertices; - if (!valueMap["vertices"]) { + if (!valueMap["vertices"]) + { if (isMesh) vertices = attachment.vertices; - else { + else + { vertices = []; vertices.length = vertexCount; } @@ -2083,14 +2353,16 @@ vertices.length = vertexCount; var start = valueMap["offset"] || 0; var nn = verticesValue.length; - if (this.scale == 1) { + if (this.scale == 1) + { for (var ii = 0; ii < nn; ii++) vertices[ii + start] = verticesValue[ii]; } else { for (var ii = 0; ii < nn; ii++) vertices[ii + start] = verticesValue[ii] * this.scale; } - if (isMesh) { + if (isMesh) + { var meshVertices = attachment.vertices; for (var ii = 0, nn = vertices.length; ii < nn; ii++) vertices[ii] += meshVertices[ii]; @@ -2109,14 +2381,17 @@ var drawOrderValues = map["drawOrder"]; if (!drawOrderValues) drawOrderValues = map["draworder"]; - if (drawOrderValues) { + if (drawOrderValues) + { var timeline = new spine.DrawOrderTimeline(drawOrderValues.length); var slotCount = skeletonData.slots.length; var frameIndex = 0; - for (var i = 0, n = drawOrderValues.length; i < n; i++) { + for (var i = 0, n = drawOrderValues.length; i < n; i++) + { var drawOrderMap = drawOrderValues[i]; var drawOrder = null; - if (drawOrderMap["offsets"]) { + if (drawOrderMap["offsets"]) + { drawOrder = []; drawOrder.length = slotCount; for (var ii = slotCount - 1; ii >= 0; ii--) @@ -2125,7 +2400,8 @@ var unchanged = []; unchanged.length = slotCount - offsets.length; var originalIndex = 0, unchangedIndex = 0; - for (var ii = 0, nn = offsets.length; ii < nn; ii++) { + for (var ii = 0, nn = offsets.length; ii < nn; ii++) + { var offsetMap = offsets[ii]; var slotIndex = skeletonData.findSlotIndex(offsetMap["slot"]); if (slotIndex == -1) throw "Slot not found: " + offsetMap["slot"]; @@ -2149,10 +2425,12 @@ } var events = map["events"]; - if (events) { + if (events) + { var timeline = new spine.EventTimeline(events.length); var frameIndex = 0; - for (var i = 0, n = events.length; i < n; i++) { + for (var i = 0, n = events.length; i < n; i++) + { var eventMap = events[i]; var eventData = skeletonData.findEvent(eventMap["name"]); if (!eventData) throw "Event not found: " + eventMap["name"]; @@ -2168,7 +2446,8 @@ skeletonData.animations.push(new spine.Animation(name, timelines, duration)); }, - readCurve: function (timeline, frameIndex, valueMap) { + readCurve: function (timeline, frameIndex, valueMap) + { var curve = valueMap["curve"]; if (!curve) timeline.curves.setLinear(frameIndex); @@ -2177,15 +2456,18 @@ else if (curve instanceof Array) timeline.curves.setCurve(frameIndex, curve[0], curve[1], curve[2], curve[3]); }, - toColor: function (hexString, colorIndex) { + toColor: function (hexString, colorIndex) + { if (hexString.length != 8) throw "Color hexidecimal length must be 8, recieved: " + hexString; return parseInt(hexString.substring(colorIndex * 2, (colorIndex * 2) + 2), 16) / 255; }, - getFloatArray: function (map, name, scale) { + getFloatArray: function (map, name, scale) + { var list = map[name]; var values = new spine.Float32Array(list.length); var i = 0, n = list.length; - if (scale == 1) { + if (scale == 1) + { for (; i < n; i++) values[i] = list[i]; } else { @@ -2194,7 +2476,8 @@ } return values; }, - getIntArray: function (map, name) { + getIntArray: function (map, name) + { var list = map[name]; var values = new spine.Uint16Array(list.length); for (var i = 0, n = list.length; i < n; i++) @@ -2203,7 +2486,8 @@ } }; -spine.Atlas = function (atlasText, textureLoader) { +spine.Atlas = function (atlasText, textureLoader) +{ this.textureLoader = textureLoader; this.pages = []; this.regions = []; @@ -2212,17 +2496,20 @@ var tuple = []; tuple.length = 4; var page = null; - while (true) { + while (true) + { var line = reader.readLine(); if (line === null) break; line = reader.trim(line); if (!line.length) page = null; - else if (!page) { + else if (!page) + { page = new spine.AtlasPage(); page.name = line; - if (reader.readTuple(tuple) == 2) { // size is only optional for an atlas packed with an old TexturePacker. + if (reader.readTuple(tuple) == 2) + { // size is only optional for an atlas packed with an old TexturePacker. page.width = parseInt(tuple[0]); page.height = parseInt(tuple[1]); reader.readTuple(tuple); @@ -2264,7 +2551,8 @@ region.u = x / page.width; region.v = y / page.height; - if (region.rotate) { + if (region.rotate) + { region.u2 = (x + height) / page.width; region.v2 = (y + width) / page.height; } else { @@ -2276,10 +2564,12 @@ region.width = Math.abs(width); region.height = Math.abs(height); - if (reader.readTuple(tuple) == 4) { // split is optional + if (reader.readTuple(tuple) == 4) + { // split is optional region.splits = [parseInt(tuple[0]), parseInt(tuple[1]), parseInt(tuple[2]), parseInt(tuple[3])]; - if (reader.readTuple(tuple) == 4) { // pad is optional, but only present with splits + if (reader.readTuple(tuple) == 4) + { // pad is optional, but only present with splits region.pads = [parseInt(tuple[0]), parseInt(tuple[1]), parseInt(tuple[2]), parseInt(tuple[3])]; reader.readTuple(tuple); @@ -2300,25 +2590,30 @@ } }; spine.Atlas.prototype = { - findRegion: function (name) { + findRegion: function (name) + { var regions = this.regions; for (var i = 0, n = regions.length; i < n; i++) if (regions[i].name == name) return regions[i]; return null; }, - dispose: function () { + dispose: function () + { var pages = this.pages; for (var i = 0, n = pages.length; i < n; i++) this.textureLoader.unload(pages[i].rendererObject); }, - updateUVs: function (page) { + updateUVs: function (page) + { var regions = this.regions; - for (var i = 0, n = regions.length; i < n; i++) { + for (var i = 0, n = regions.length; i < n; i++) + { var region = regions[i]; if (region.page != page) continue; region.u = region.x / page.width; region.v = region.y / page.height; - if (region.rotate) { + if (region.rotate) + { region.u2 = (region.x + region.height) / page.width; region.v2 = (region.y + region.width) / page.height; } else { @@ -2355,7 +2650,8 @@ repeat: 2 }; -spine.AtlasPage = function () {}; +spine.AtlasPage = function () +{}; spine.AtlasPage.prototype = { name: null, format: null, @@ -2368,7 +2664,8 @@ height: 0 }; -spine.AtlasRegion = function () {}; +spine.AtlasRegion = function () +{}; spine.AtlasRegion.prototype = { page: null, name: null, @@ -2383,31 +2680,37 @@ pads: null }; -spine.AtlasReader = function (text) { +spine.AtlasReader = function (text) +{ this.lines = text.split(/\r\n|\r|\n/); }; spine.AtlasReader.prototype = { index: 0, - trim: function (value) { + trim: function (value) + { return value.replace(/^\s+|\s+$/g, ""); }, - readLine: function () { + readLine: function () + { if (this.index >= this.lines.length) return null; return this.lines[this.index++]; }, - readValue: function () { + readValue: function () + { var line = this.readLine(); var colon = line.indexOf(":"); if (colon == -1) throw "Invalid line: " + line; return this.trim(line.substring(colon + 1)); }, /** Returns the number of tuple values read (1, 2 or 4). */ - readTuple: function (tuple) { + readTuple: function (tuple) + { var line = this.readLine(); var colon = line.indexOf(":"); if (colon == -1) throw "Invalid line: " + line; var i = 0, lastMatch = colon + 1; - for (; i < 3; i++) { + for (; i < 3; i++) + { var comma = line.indexOf(",", lastMatch); if (comma == -1) break; tuple[i] = this.trim(line.substr(lastMatch, comma - lastMatch)); @@ -2418,11 +2721,13 @@ } }; -spine.AtlasAttachmentLoader = function (atlas) { +spine.AtlasAttachmentLoader = function (atlas) +{ this.atlas = atlas; }; spine.AtlasAttachmentLoader.prototype = { - newRegionAttachment: function (skin, name, path) { + newRegionAttachment: function (skin, name, path) + { var region = this.atlas.findRegion(path); if (!region) throw "Region not found in atlas: " + path + " (region attachment: " + name + ")"; var attachment = new spine.RegionAttachment(name); @@ -2436,7 +2741,8 @@ attachment.regionOriginalHeight = region.originalHeight; return attachment; }, - newMeshAttachment: function (skin, name, path) { + newMeshAttachment: function (skin, name, path) + { var region = this.atlas.findRegion(path); if (!region) throw "Region not found in atlas: " + path + " (mesh attachment: " + name + ")"; var attachment = new spine.MeshAttachment(name); @@ -2454,7 +2760,8 @@ attachment.regionOriginalHeight = region.originalHeight; return attachment; }, - newSkinnedMeshAttachment: function (skin, name, path) { + newSkinnedMeshAttachment: function (skin, name, path) + { var region = this.atlas.findRegion(path); if (!region) throw "Region not found in atlas: " + path + " (skinned mesh attachment: " + name + ")"; var attachment = new spine.SkinnedMeshAttachment(name); @@ -2472,19 +2779,22 @@ attachment.regionOriginalHeight = region.originalHeight; return attachment; }, - newBoundingBoxAttachment: function (skin, name) { + newBoundingBoxAttachment: function (skin, name) + { return new spine.BoundingBoxAttachment(name); } }; -spine.SkeletonBounds = function () { +spine.SkeletonBounds = function () +{ this.polygonPool = []; this.polygons = []; this.boundingBoxes = []; }; spine.SkeletonBounds.prototype = { minX: 0, minY: 0, maxX: 0, maxY: 0, - update: function (skeleton, updateAabb) { + update: function (skeleton, updateAabb) + { var slots = skeleton.slots; var slotCount = slots.length; var x = skeleton.x, y = skeleton.y; @@ -2497,14 +2807,16 @@ polygonPool.push(polygons[i]); polygons.length = 0; - for (var i = 0; i < slotCount; i++) { + for (var i = 0; i < slotCount; i++) + { var slot = slots[i]; var boundingBox = slot.attachment; if (boundingBox.type != spine.AttachmentType.boundingbox) continue; boundingBoxes.push(boundingBox); var poolCount = polygonPool.length, polygon; - if (poolCount > 0) { + if (poolCount > 0) + { polygon = polygonPool[poolCount - 1]; polygonPool.splice(poolCount - 1, 1); } else @@ -2517,12 +2829,15 @@ if (updateAabb) this.aabbCompute(); }, - aabbCompute: function () { + aabbCompute: function () + { var polygons = this.polygons; var minX = Number.MAX_VALUE, minY = Number.MAX_VALUE, maxX = Number.MIN_VALUE, maxY = Number.MIN_VALUE; - for (var i = 0, n = polygons.length; i < n; i++) { + for (var i = 0, n = polygons.length; i < n; i++) + { var vertices = polygons[i]; - for (var ii = 0, nn = vertices.length; ii < nn; ii += 2) { + for (var ii = 0, nn = vertices.length; ii < nn; ii += 2) + { var x = vertices[ii]; var y = vertices[ii + 1]; minX = Math.min(minX, x); @@ -2537,11 +2852,13 @@ this.maxY = maxY; }, /** Returns true if the axis aligned bounding box contains the point. */ - aabbContainsPoint: function (x, y) { + aabbContainsPoint: function (x, y) + { return x >= this.minX && x <= this.maxX && y >= this.minY && y <= this.maxY; }, /** Returns true if the axis aligned bounding box intersects the line segment. */ - aabbIntersectsSegment: function (x1, y1, x2, y2) { + aabbIntersectsSegment: function (x1, y1, x2, y2) + { var minX = this.minX, minY = this.minY, maxX = this.maxX, maxY = this.maxY; if ((x1 <= minX && x2 <= minX) || (y1 <= minY && y2 <= minY) || (x1 >= maxX && x2 >= maxX) || (y1 >= maxY && y2 >= maxY)) return false; @@ -2557,12 +2874,14 @@ return false; }, /** Returns true if the axis aligned bounding box intersects the axis aligned bounding box of the specified bounds. */ - aabbIntersectsSkeleton: function (bounds) { + aabbIntersectsSkeleton: function (bounds) + { return this.minX < bounds.maxX && this.maxX > bounds.minX && this.minY < bounds.maxY && this.maxY > bounds.minY; }, /** Returns the first bounding box attachment that contains the point, or null. When doing many checks, it is usually more * efficient to only call this method if {@link #aabbContainsPoint(float, float)} returns true. */ - containsPoint: function (x, y) { + containsPoint: function (x, y) + { var polygons = this.polygons; for (var i = 0, n = polygons.length; i < n; i++) if (this.polygonContainsPoint(polygons[i], x, y)) return this.boundingBoxes[i]; @@ -2570,21 +2889,25 @@ }, /** Returns the first bounding box attachment that contains the line segment, or null. When doing many checks, it is usually * more efficient to only call this method if {@link #aabbIntersectsSegment(float, float, float, float)} returns true. */ - intersectsSegment: function (x1, y1, x2, y2) { + intersectsSegment: function (x1, y1, x2, y2) + { var polygons = this.polygons; for (var i = 0, n = polygons.length; i < n; i++) if (polygons[i].intersectsSegment(x1, y1, x2, y2)) return this.boundingBoxes[i]; return null; }, /** Returns true if the polygon contains the point. */ - polygonContainsPoint: function (polygon, x, y) { + polygonContainsPoint: function (polygon, x, y) + { var nn = polygon.length; var prevIndex = nn - 2; var inside = false; - for (var ii = 0; ii < nn; ii += 2) { + for (var ii = 0; ii < nn; ii += 2) + { var vertexY = polygon[ii + 1]; var prevY = polygon[prevIndex + 1]; - if ((vertexY < y && prevY >= y) || (prevY < y && vertexY >= y)) { + if ((vertexY < y && prevY >= y) || (prevY < y && vertexY >= y)) + { var vertexX = polygon[ii]; if (vertexX + (y - vertexY) / (prevY - vertexY) * (polygon[prevIndex] - vertexX) < x) inside = !inside; } @@ -2593,18 +2916,21 @@ return inside; }, /** Returns true if the polygon contains the line segment. */ - polygonIntersectsSegment: function (polygon, x1, y1, x2, y2) { + polygonIntersectsSegment: function (polygon, x1, y1, x2, y2) + { var nn = polygon.length; var width12 = x1 - x2, height12 = y1 - y2; var det1 = x1 * y2 - y1 * x2; var x3 = polygon[nn - 2], y3 = polygon[nn - 1]; - for (var ii = 0; ii < nn; ii += 2) { + for (var ii = 0; ii < nn; ii += 2) + { var x4 = polygon[ii], y4 = polygon[ii + 1]; var det2 = x3 * y4 - y3 * x4; var width34 = x3 - x4, height34 = y3 - y4; var det3 = width12 * height34 - height12 * width34; var x = (det1 * width34 - width12 * det2) / det3; - if (((x >= x3 && x <= x4) || (x >= x4 && x <= x3)) && ((x >= x1 && x <= x2) || (x >= x2 && x <= x1))) { + if (((x >= x3 && x <= x4) || (x >= x4 && x <= x3)) && ((x >= x1 && x <= x2) || (x >= x2 && x <= x1))) + { var y = (det1 * height34 - height12 * det2) / det3; if (((y >= y3 && y <= y4) || (y >= y4 && y <= y3)) && ((y >= y1 && y <= y2) || (y >= y2 && y <= y1))) return true; } @@ -2613,14 +2939,17 @@ } return false; }, - getPolygon: function (attachment) { + getPolygon: function (attachment) + { var index = this.boundingBoxes.indexOf(attachment); return index == -1 ? null : this.polygons[index]; }, - getWidth: function () { + getWidth: function () + { return this.maxX - this.minX; }, - getHeight: function () { + getHeight: function () + { return this.maxY - this.minY; } }; diff --git a/src/core/display/DisplayObject.js b/src/core/display/DisplayObject.js index 66ebc3c..20e778c 100644 --- a/src/core/display/DisplayObject.js +++ b/src/core/display/DisplayObject.js @@ -7,7 +7,8 @@ * @class * @namespace PIXI */ -function DisplayObject() { +function DisplayObject() +{ /** * The coordinate of the object relative to the local coordinates of the parent. * @@ -152,10 +153,12 @@ * @memberof DisplayObject# */ x: { - get: function () { + get: function () + { return this.position.x; }, - set: function (value) { + set: function (value) + { this.position.x = value; } }, @@ -167,10 +170,12 @@ * @memberof DisplayObject# */ y: { - get: function () { + get: function () + { return this.position.y; }, - set: function (value) { + set: function (value) + { this.position.y = value; } }, @@ -183,11 +188,13 @@ * @readonly */ worldVisible: { - get: function () { + get: function () + { var item = this; do { - if (!item.visible) { + if (!item.visible) + { return false; } @@ -207,17 +214,21 @@ * @memberof DisplayObject# */ mask: { - get: function () { + get: function () + { return this._mask; }, - set: function (value) { - if (this._mask) { + set: function (value) + { + if (this._mask) + { this._mask.isMask = false; } this._mask = value; - if (this._mask) { + if (this._mask) + { this._mask.isMask = true; } } @@ -232,18 +243,23 @@ * @memberof DisplayObject# */ filters: { - get: function () { + get: function () + { return this._filters; }, - set: function (value) { - if (value) { + set: function (value) + { + if (value) + { // now put all the passes in one place.. var passes = []; - for (var i = 0; i < value.length; i++) { + for (var i = 0; i < value.length; i++) + { var filterPasses = value[i].passes; - for (var j = 0; j < filterPasses.length; j++) { + for (var j = 0; j < filterPasses.length; j++) + { passes.push(filterPasses[j]); } } @@ -264,8 +280,9 @@ * * @private */ -DisplayObject.prototype.updateTransform = function () { - +DisplayObject.prototype.updateTransform = function () +{ + // create some matrix refs for easy access var pt = this.parent.worldTransform; var wt = this.worldTransform; @@ -274,9 +291,11 @@ var a, b, c, d, tx, ty; // so if rotation is between 0 then we can simplify the multiplication process.. - if (this.rotation % math.PI_2) { + if (this.rotation % math.PI_2) + { // 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) { + if (this.rotation !== this.rotationCache) + { this.rotationCache = this.rotation; this._sr = Math.sin(this.rotation); this._cr = Math.cos(this.rotation); @@ -291,7 +310,8 @@ ty = this.position.y; // check for pivot.. not often used so geared towards that fact! - if (this.pivot.x || this.pivot.y) { + 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; } @@ -304,7 +324,8 @@ wt.tx = tx * pt.a + ty * pt.c + pt.tx; wt.ty = tx * pt.b + ty * pt.d + pt.ty; } - else { + else + { // lets do the fast version as we know there is no rotation.. a = this.scale.x; d = this.scale.y; @@ -333,7 +354,8 @@ * @param matrix {Matrix} * @return {Rectangle} the rectangular bounding area */ -DisplayObject.prototype.getBounds = function (/* matrix */) { +DisplayObject.prototype.getBounds = function (/* matrix */) +{ return math.Rectangle.EMPTY; }; @@ -342,7 +364,8 @@ * * @return {Rectangle} the rectangular bounding area */ -DisplayObject.prototype.getLocalBounds = function () { +DisplayObject.prototype.getLocalBounds = function () +{ return this.getBounds(math.Matrix.IDENTITY); }; @@ -352,7 +375,8 @@ * @param position {Point} The world origin to calculate from * @return {Point} A point object representing the position of this object */ -DisplayObject.prototype.toGlobal = function (position) { +DisplayObject.prototype.toGlobal = function (position) +{ // don't need to u[date the lot this.displayObjectUpdateTransform(); return this.worldTransform.apply(position); @@ -365,8 +389,10 @@ * @param [from] {DisplayObject} The DisplayObject to calculate the global position from * @return {Point} A point object representing the position of this object */ -DisplayObject.prototype.toLocal = function (position, from) { - if (from) { +DisplayObject.prototype.toLocal = function (position, from) +{ + if (from) + { position = from.toGlobal(position); } @@ -381,7 +407,8 @@ * @param renderer {WebGLRenderer} The renderer * @private */ -DisplayObject.prototype.renderWebGL = function (/* renderer */) { +DisplayObject.prototype.renderWebGL = function (/* renderer */) +{ // OVERWRITE; }; @@ -391,6 +418,7 @@ * @param renderer {CanvasRenderer} The renderer * @private */ -DisplayObject.prototype.renderCanvas = function (/* renderer */) { +DisplayObject.prototype.renderCanvas = function (/* renderer */) +{ // OVERWRITE; }; diff --git a/src/core/display/DisplayObjectContainer.js b/src/core/display/DisplayObjectContainer.js index 689f40b..4625ee8 100644 --- a/src/core/display/DisplayObjectContainer.js +++ b/src/core/display/DisplayObjectContainer.js @@ -12,7 +12,8 @@ * @extends DisplayObject * @namespace PIXI */ -function DisplayObjectContainer() { +function DisplayObjectContainer() +{ DisplayObject.call(this); /** @@ -47,17 +48,21 @@ * @memberof DisplayObjectContainer# */ width: { - get: function () { + get: function () + { return this.scale.x * this.getLocalBounds().width; }, - set: function (value) { + set: function (value) + { var width = this.getLocalBounds().width; - if(width !== 0) { + if(width !== 0) + { this.scale.x = value / width; } - else { + else + { this.scale.x = 1; } @@ -73,17 +78,21 @@ * @memberof DisplayObjectContainer# */ height: { - get: function () { + get: function () + { return this.scale.y * this.getLocalBounds().height; }, - set: function (value) { + set: function (value) + { var height = this.getLocalBounds().height; - if (height !== 0) { + if (height !== 0) + { this.scale.y = value / height ; } - else { + else + { this.scale.y = 1; } @@ -100,18 +109,23 @@ * @memberof DisplayObject# */ cacheAsBitmap: { - get: function () { + get: function () + { return this._cacheAsBitmap; }, - set: function (value) { - if (this._cacheAsBitmap === value) { + set: function (value) + { + if (this._cacheAsBitmap === value) + { return; } - if (value) { + if (value) + { this._generateCachedSprite(); } - else { + else + { this._destroyCachedSprite(); } @@ -126,7 +140,8 @@ * @param child {DisplayObject} The DisplayObject to add to the container * @return {DisplayObject} The child that was added. */ -DisplayObjectContainer.prototype.addChild = function (child) { +DisplayObjectContainer.prototype.addChild = function (child) +{ return this.addChildAt(child, this.children.length); }; @@ -137,14 +152,18 @@ * @param index {Number} The index to place the child in * @return {DisplayObject} The child that was added. */ -DisplayObjectContainer.prototype.addChildAt = function (child, index) { +DisplayObjectContainer.prototype.addChildAt = function (child, index) +{ // prevent adding self as child - if (child === this) { + if (child === this) + { return; } - if (index >= 0 && index <= this.children.length) { - if (child.parent) { + if (index >= 0 && index <= this.children.length) + { + if (child.parent) + { child.parent.removeChild(child); } @@ -154,7 +173,8 @@ return child; } - else { + else + { throw new Error(child + 'addChildAt: The index '+ index +' supplied is out of bounds ' + this.children.length); } }; @@ -165,15 +185,18 @@ * @param child {DisplayObject} * @param child2 {DisplayObject} */ -DisplayObjectContainer.prototype.swapChildren = function (child, child2) { - if (child === child2) { +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) { + if (index1 < 0 || index2 < 0) + { throw new Error('swapChildren: Both the supplied DisplayObjects must be a child of the caller.'); } @@ -187,10 +210,12 @@ * @param child {DisplayObject} The DisplayObject instance to identify * @return {Number} The index position of the child display object to identify */ -DisplayObjectContainer.prototype.getChildIndex = function (child) { +DisplayObjectContainer.prototype.getChildIndex = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { throw new Error('The supplied DisplayObject must be a child of the caller'); } @@ -203,8 +228,10 @@ * @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 */ -DisplayObjectContainer.prototype.setChildIndex = function (child, index) { - if (index < 0 || index >= this.children.length) { +DisplayObjectContainer.prototype.setChildIndex = function (child, index) +{ + if (index < 0 || index >= this.children.length) + { throw new Error('The supplied index is out of bounds'); } @@ -220,8 +247,10 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child at the given index, if any. */ -DisplayObjectContainer.prototype.getChildAt = function (index) { - if (index < 0 || index >= this.children.length) { +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'); } @@ -234,10 +263,12 @@ * @param child {DisplayObject} The DisplayObject to remove * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChild = function (child) { +DisplayObjectContainer.prototype.removeChild = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { return; } @@ -250,7 +281,8 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChildAt = function (index) { +DisplayObjectContainer.prototype.removeChildAt = function (index) +{ var child = this.getChildAt(index); child.parent = null; @@ -265,24 +297,29 @@ * @param beginIndex {Number} The beginning position. Default value is 0. * @param endIndex {Number} The ending position. Default value is size of the container. */ -DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) { +DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) +{ var begin = beginIndex || 0; var end = typeof endIndex === 'number' ? endIndex : this.children.length; var range = end - begin; - if (range > 0 && range <= end) { + if (range > 0 && range <= end) + { var removed = this.children.splice(begin, range); - for (var i = 0; i < removed.length; ++i) { + for (var i = 0; i < removed.length; ++i) + { removed[i].parent = null; } return removed; } - else if (range === 0 && this.children.length === 0) { + else if (range === 0 && this.children.length === 0) + { return []; } - else { + else + { throw new RangeError('removeChildren: numeric values are outside the acceptable range.'); } }; @@ -291,7 +328,8 @@ * Generates and updates the cached sprite for this object. * */ -DisplayObjectContainer.prototype.updateCachedSprite = function () { +DisplayObjectContainer.prototype.updateCachedSprite = function () +{ this._generateCachedSprite(); }; @@ -304,7 +342,8 @@ * @param renderer {CanvasRenderer|WebGLRenderer} The renderer used to generate the texture. * @return {Texture} a texture of the graphics object */ -DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) { +DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) +{ var bounds = this.getLocalBounds(); var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0, renderer, scaleMode, resolution); @@ -322,18 +361,22 @@ * * @private */ -DisplayObjectContainer.prototype.updateTransform = function () { - if (!this.visible) { +DisplayObjectContainer.prototype.updateTransform = function () +{ + if (!this.visible) + { return; } this.displayObjectUpdateTransform(); - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { return; } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } }; @@ -346,8 +389,10 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getBounds = function () { - if (this.children.length === 0) { +DisplayObjectContainer.prototype.getBounds = function () +{ + if (this.children.length === 0) + { return math.Rectangle.EMPTY; } @@ -365,10 +410,12 @@ var childVisible = false; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -386,7 +433,8 @@ maxY = maxY > childMaxY ? maxY : childMaxY; } - if (!childVisible) { + if (!childVisible) + { return math.Rectangle.EMPTY; } @@ -407,12 +455,14 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getLocalBounds = function () { +DisplayObjectContainer.prototype.getLocalBounds = function () +{ var matrixCache = this.worldTransform; this.worldTransform = math.Matrix.IDENTITY; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } @@ -428,13 +478,16 @@ * * @param renderer {WebGLRenderer} The renderer */ -DisplayObjectContainer.prototype.renderWebGL = function (renderer) { +DisplayObjectContainer.prototype.renderWebGL = function (renderer) +{ // if the object is not visible or the alpha is 0 then no need to render this element - if (!this.visible || this.alpha <= 0) { + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } @@ -442,14 +495,17 @@ var i, j; // do a quick check to see if this element has a mask or a filter. - if (this._mask || this._filters) { + if (this._mask || this._filters) + { // push filter first as we need to ensure the stencil buffer is correct for any masking - if (this._filters) { + if (this._filters) + { renderer.spriteBatch.flush(); renderer.filterManager.pushFilter(this._filterBlock); } - if (this._mask) { + if (this._mask) + { renderer.spriteBatch.stop(); renderer.maskManager.pushMask(this.mask, renderer); renderer.spriteBatch.start(); @@ -459,36 +515,42 @@ this._renderWebGL(renderer); // now loop through the children and make sure they get rendered - for (i = 0, j = this.children.length; i < j; i++) { + for (i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderWebGL(renderer); } // time to stop the sprite batch as either a mask element or a filter draw will happen next renderer.spriteBatch.stop(); - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(this._mask, renderer); } - if (this._filters) { + if (this._filters) + { renderer.filterManager.popFilter(); } renderer.spriteBatch.start(); } - else { + else + { this._renderWebGL(renderer); // simple render children! - for (i = 0, j = this.children.length; i < j; ++i) { + for (i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderWebGL(renderer); } } }; -DisplayObjectContainer.prototype._renderWebGL = function (renderer) { +DisplayObjectContainer.prototype._renderWebGL = function (renderer) +{ // this is where content itself gets renderd.. @@ -499,25 +561,31 @@ * * @param renderer {CanvasRenderer} The renderer */ -DisplayObjectContainer.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0) { +DisplayObjectContainer.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -528,13 +596,16 @@ * @param renderer {WebGLRenderer|CanvasRenderer} The renderer * @private */ -DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) { +DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) +{ this._cachedSprite.worldAlpha = this.worldAlpha; - if (renderer.gl) { + if (renderer.gl) + { this._cachedSprite.renderWebGL(renderer); } - else { + else + { this._cachedSprite.renderCanvas(renderer); } }; @@ -544,10 +615,12 @@ * * @private */ -DisplayObjectContainer.prototype._generateCachedSprite = function () { +DisplayObjectContainer.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { // TODO - RenderTexture now *requires* a renderer instance, so this is like broken // because `renderer` isn't actually in scope here :P var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0); @@ -555,7 +628,8 @@ this._cachedSprite = new Sprite(renderTexture); this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.texture.resize(bounds.width | 0, bounds.height | 0); } @@ -580,8 +654,10 @@ * * @private */ -DisplayObjectContainer.prototype._destroyCachedSprite = function () { - if (!this._cachedSprite) { +DisplayObjectContainer.prototype._destroyCachedSprite = function () +{ + if (!this._cachedSprite) + { return; } diff --git a/src/core/display/Sprite.js b/src/core/display/Sprite.js index 707da24..5862aef 100644 --- a/src/core/display/Sprite.js +++ b/src/core/display/Sprite.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param texture {Texture} The texture for this sprite */ -function Sprite(texture) { +function Sprite(texture) +{ DisplayObjectContainer.call(this); /** @@ -85,12 +86,14 @@ this.texture = texture || Texture.EMPTY; } -Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) { +Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) +{ DisplayObjectContainer.prototype.destroy.call(this); this.anchor = null; - if (destroyTexture) { + if (destroyTexture) + { this._texture.destroy(destroyBaseTexture); } @@ -111,10 +114,12 @@ * @memberof Sprite# */ width: { - get: function () { + get: function () + { return this.scale.x * this.texture.frame.width; }, - set: function (value) { + set: function (value) + { this.scale.x = value / this.texture.frame.width; this._width = value; } @@ -127,10 +132,12 @@ * @memberof Sprite# */ height: { - get: function () { + get: function () + { return this.scale.y * this.texture.frame.height; }, - set: function (value) { + set: function (value) + { this.scale.y = value / this.texture.frame.height; this._height = value; } @@ -143,23 +150,29 @@ * @memberof Sprite# */ texture: { - get: function () { + get: function () + { return this._texture; }, - set: function (value) { - if (this._texture === value) { + set: function (value) + { + if (this._texture === value) + { return; } this._texture = value; this.cachedTint = 0xFFFFFF; - if (value) { + if (value) + { // wait for the texture to load - if (value.baseTexture.hasLoaded) { + if (value.baseTexture.hasLoaded) + { this._onTextureUpdate(); } - else { + else + { value.once('update', this._onTextureUpdate.bind(this)); } } @@ -172,18 +185,22 @@ * * @private */ -Sprite.prototype._onTextureUpdate = function () { +Sprite.prototype._onTextureUpdate = function () +{ // so if _width is 0 then width was not set.. - if (this._width) { + if (this._width) + { this.scale.x = this._width / this.texture.frame.width; } - if (this._height) { + if (this._height) + { this.scale.y = this._height / this.texture.frame.height; } }; -Sprite.prototype._renderWebGL = function (renderer) { +Sprite.prototype._renderWebGL = function (renderer) +{ // this is where content gets renderd.. // watch this space for a little render state manager.. @@ -197,7 +214,8 @@ * @param matrix {Matrix} the transformation matrix of the sprite * @return {Rectangle} the framing rectangle */ -Sprite.prototype.getBounds = function (matrix) { +Sprite.prototype.getBounds = function (matrix) +{ var width = this.texture.frame.width; var height = this.texture.frame.height; @@ -224,11 +242,13 @@ if(b === 0 && c === 0) { // scale may be negative! - if (a < 0) { + if (a < 0) + { a *= -1; } - if (d < 0) { + if (d < 0) + { d *= -1; } @@ -293,28 +313,34 @@ * * @param renderer {CanvasRenderer} The renderer */ -Sprite.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) { +Sprite.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) + { return; } - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; renderer.context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } // Ignore null sources - if (this.texture.valid) { + if (this.texture.valid) + { var resolution = this.texture.baseTexture.resolution / renderer.resolution; renderer.context.globalAlpha = this.worldAlpha; // If smoothingEnabled is supported and we need to change the smoothing property for this texture - if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) { + if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) + { renderer.scaleMode = this.texture.baseTexture.scaleMode; renderer.context[renderer.smoothProperty] = (renderer.scaleMode === CONST.scaleModes.LINEAR); } @@ -324,7 +350,8 @@ var dy = (this.texture.trim ? this.texture.trim.y : 0) - (this.anchor.y * this.texture.trim.height); // Allow for pixel rounding - if (renderer.roundPixels) { + if (renderer.roundPixels) + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -337,7 +364,8 @@ dx = dx | 0; dy = dy | 0; } - else { + else + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -348,8 +376,10 @@ ); } - if (this.tint !== 0xFFFFFF) { - if (this.cachedTint !== this.tint) { + if (this.tint !== 0xFFFFFF) + { + if (this.cachedTint !== this.tint) + { this.cachedTint = this.tint; // TODO clean up caching - how to clean up the caches? @@ -368,7 +398,8 @@ this.texture.crop.height / resolution ); } - else { + else + { renderer.context.drawImage( this.texture.baseTexture.source, this.texture.crop.x, @@ -383,11 +414,13 @@ } } - for (var i = 0, j = this.children.length; i < j; i++) { + for (var i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -402,10 +435,12 @@ * @param frameId {String} The frame Id of the texture in the cache * @return {Sprite} A new Sprite using a texture from the texture cache matching the frameId */ -Sprite.fromFrame = function (frameId) { +Sprite.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache' + this); } @@ -420,6 +455,7 @@ * @param imageId {String} The image url of the texture * @return {Sprite} A new Sprite using a texture from the texture cache matching the image id */ -Sprite.fromImage = function (imageId, crossorigin, scaleMode) { +Sprite.fromImage = function (imageId, crossorigin, scaleMode) +{ return new Sprite(Texture.fromImage(imageId, crossorigin, scaleMode)); }; diff --git a/src/core/display/SpriteBatch.js b/src/core/display/SpriteBatch.js index 3187777..c196fef 100644 --- a/src/core/display/SpriteBatch.js +++ b/src/core/display/SpriteBatch.js @@ -12,7 +12,8 @@ * ```js * var container = new SpriteBatch(); * - * for(var i = 0; i < 100; ++i) { + * for(var i = 0; i < 100; ++i) + * { * var sprite = new PIXI.Sprite.fromImage("myImage.png"); * container.addChild(sprite); * } @@ -25,7 +26,8 @@ */ //TODO RENAME to PARTICLE CONTAINER? -function SpriteBatch() { +function SpriteBatch() +{ DisplayObjectContainer.call(this); } @@ -38,7 +40,8 @@ * * @private */ -SpriteBatch.prototype.updateTransform = function () { +SpriteBatch.prototype.updateTransform = function () +{ // TODO don't need to! this.displayObjectUpdateTransform(); // PIXI.DisplayObjectContainer.prototype.updateTransform.call( this ); @@ -50,8 +53,10 @@ * @param renderer {WebGLRenderer} The webgl renderer * @private */ -SpriteBatch.prototype.renderWebGL = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderWebGL = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -71,8 +76,10 @@ * @param renderer {CanvasRenderer} The canvas renderer * @private */ -SpriteBatch.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -84,10 +91,12 @@ this.displayObjectUpdateTransform(); - for (var i = 0; i < this.children.length; ++i) { + for (var i = 0; i < this.children.length; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -95,9 +104,11 @@ context.globalAlpha = this.worldAlpha * child.alpha; - if (child.rotation % (Math.PI * 2) === 0) { + if (child.rotation % (Math.PI * 2) === 0) + { // this is the fastest way to optimise! - if rotation is 0 then we can avoid any kind of setTransform call - if (isRotated) { + if (isRotated) + { context.setTransform( transform.a, transform.b, @@ -122,8 +133,10 @@ frame.height * child.scale.y ); } - else { - if (!isRotated) { + else + { + if (!isRotated) + { isRotated = true; } @@ -131,7 +144,8 @@ var childTransform = child.worldTransform; - if (renderer.roundPixels) { + if (renderer.roundPixels) + { context.setTransform( childTransform.a, childTransform.b, @@ -141,7 +155,8 @@ childTransform.ty | 0 ); } - else { + else + { context.setTransform( childTransform.a, childTransform.b, diff --git a/src/core/index.js b/src/core/index.js index 3954b6f..eb4a82b 100644 --- a/src/core/index.js +++ b/src/core/index.js @@ -58,11 +58,13 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRenderer: function (width, height, options, noWebGL) { + autoDetectRenderer: function (width, height, options, noWebGL) + { width = width || 800; height = height || 600; - if (!noWebGL && require('webgl-enabled')()) { + if (!noWebGL && require('webgl-enabled')()) + { return new core.WebGLRenderer(width, height, options); } @@ -87,7 +89,8 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRecommendedRenderer: function (width, height, options) { + autoDetectRecommendedRenderer: function (width, height, options) + { var isAndroid = /Android/i.test(navigator.userAgent); return core.autoDetectRenderer(width, height, options, isAndroid); diff --git a/src/core/math/Matrix.js b/src/core/math/Matrix.js index c2f87e2..2ff4848 100644 --- a/src/core/math/Matrix.js +++ b/src/core/math/Matrix.js @@ -10,7 +10,8 @@ * @class * @namespace PIXI */ -function Matrix() { +function Matrix() +{ /** * @member {number} * @default 1 @@ -63,7 +64,8 @@ * * @param array {number[]} The array that the matrix will be populated from. */ -Matrix.prototype.fromArray = function (array) { +Matrix.prototype.fromArray = function (array) +{ this.a = array[0]; this.b = array[1]; this.c = array[3]; @@ -78,14 +80,17 @@ * @param transpose {boolean} Whether we need to transpose the matrix or not * @return {number[]} the newly created array which contains the matrix */ -Matrix.prototype.toArray = function (transpose) { - if (!this.array) { +Matrix.prototype.toArray = function (transpose) +{ + if (!this.array) + { this.array = new Float32Array(9); } var array = this.array; - if (transpose) { + if (transpose) + { array[0] = this.a; array[1] = this.b; array[2] = 0; @@ -96,7 +101,8 @@ array[7] = this.ty; array[8] = 1; } - else { + else + { array[0] = this.a; array[1] = this.c; array[2] = this.tx; @@ -119,7 +125,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, transformed through this matrix */ -Matrix.prototype.apply = function (pos, newPos) { +Matrix.prototype.apply = function (pos, newPos) +{ newPos = newPos || new Point(); newPos.x = this.a * pos.x + this.c * pos.y + this.tx; @@ -136,7 +143,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, inverse-transformed through this matrix */ -Matrix.prototype.applyInverse = function (pos, newPos) { +Matrix.prototype.applyInverse = function (pos, newPos) +{ newPos = newPos || new Point(); var id = 1 / (this.a * this.d + this.c * -this.b); @@ -154,7 +162,8 @@ * @param {number} y * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.translate = function (x, y) { +Matrix.prototype.translate = function (x, y) +{ this.tx += x; this.ty += y; @@ -168,7 +177,8 @@ * @param {number} y The amount to scale vertically * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.scale = function (x, y) { +Matrix.prototype.scale = function (x, y) +{ this.a *= x; this.d *= y; this.c *= x; @@ -186,7 +196,8 @@ * @param {number} angle - The angle in radians. * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.rotate = function (angle) { +Matrix.prototype.rotate = function (angle) +{ var cos = Math.cos( angle ); var sin = Math.sin( angle ); @@ -210,7 +221,8 @@ * @param {Matrix} matrix * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.append = function (matrix) { +Matrix.prototype.append = function (matrix) +{ var a1 = this.a; var b1 = this.b; var c1 = this.c; @@ -232,7 +244,8 @@ * * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.identity = function () { +Matrix.prototype.identity = function () +{ this.a = 1; this.b = 0; this.c = 0; diff --git a/src/core/math/Point.js b/src/core/math/Point.js index 7565b2d..632f346 100644 --- a/src/core/math/Point.js +++ b/src/core/math/Point.js @@ -7,7 +7,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -function Point(x, y) { +function Point(x, y) +{ /** * @member {number} * @default 0 @@ -29,7 +30,8 @@ * * @return {Point} a copy of the point */ -Point.prototype.clone = function () { +Point.prototype.clone = function () +{ return new Point(this.x, this.y); }; @@ -40,7 +42,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -Point.prototype.set = function (x, y) { +Point.prototype.set = function (x, y) +{ this.x = x || 0; this.y = y || ( (y !== 0) ? this.x : 0 ) ; }; diff --git a/src/core/math/shapes/Circle.js b/src/core/math/shapes/Circle.js index 69cfdc9..4d76efc 100644 --- a/src/core/math/shapes/Circle.js +++ b/src/core/math/shapes/Circle.js @@ -10,7 +10,8 @@ * @param y {number} The Y coordinate of the center of this circle * @param radius {number} The radius of the circle */ -function Circle(x, y, radius) { +function Circle(x, y, radius) +{ /** * @member {number} * @default 0 @@ -46,7 +47,8 @@ * @method clone * @return {Circle} a copy of the Circle */ -Circle.prototype.clone = function () { +Circle.prototype.clone = function () +{ return new Circle(this.x, this.y, this.radius); }; @@ -58,8 +60,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Circle */ -Circle.prototype.contains = function (x, y) { - if (this.radius <= 0) { +Circle.prototype.contains = function (x, y) +{ + if (this.radius <= 0) + { return false; } @@ -79,6 +83,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Circle.prototype.getBounds = function () { +Circle.prototype.getBounds = function () +{ return new Rectangle(this.x - this.radius, this.y - this.radius, this.radius * 2, this.radius * 2); }; diff --git a/src/core/math/shapes/Ellipse.js b/src/core/math/shapes/Ellipse.js index 4f2d066..fefd01a 100644 --- a/src/core/math/shapes/Ellipse.js +++ b/src/core/math/shapes/Ellipse.js @@ -11,7 +11,8 @@ * @param width {number} The half width of this ellipse * @param height {number} The half height of this ellipse */ -function Ellipse(x, y, width, height) { +function Ellipse(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -53,7 +54,8 @@ * @method clone * @return {Ellipse} a copy of the ellipse */ -Ellipse.prototype.clone = function () { +Ellipse.prototype.clone = function () +{ return new Ellipse(this.x, this.y, this.width, this.height); }; @@ -65,8 +67,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coords are within this ellipse */ -Ellipse.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Ellipse.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } @@ -86,6 +90,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Ellipse.prototype.getBounds = function () { +Ellipse.prototype.getBounds = function () +{ return new Rectangle(this.x - this.width, this.y - this.height, this.width, this.height); }; diff --git a/src/core/math/shapes/Polygon.js b/src/core/math/shapes/Polygon.js index ae89148..fea6d37 100644 --- a/src/core/math/shapes/Polygon.js +++ b/src/core/math/shapes/Polygon.js @@ -10,16 +10,20 @@ * arguments passed can be flat x,y values e.g. `new Polygon(x,y, x,y, x,y, ...)` where `x` and `y` are * Numbers. */ -function Polygon(points) { +function Polygon(points) +{ //if points isn't an array, use arguments as the array - if (!(points instanceof Array)) { + if (!(points instanceof Array)) + { points = Array.prototype.slice.call(arguments); } //if this is a flat array of numbers, convert it to points - if (points[0] instanceof Point) { + if (points[0] instanceof Point) + { var p = []; - for (var i = 0, il = points.length; i < il; i++) { + for (var i = 0, il = points.length; i < il; i++) + { p.push(points[i].x, points[i].y); } @@ -51,7 +55,8 @@ * * @return {Polygon} a copy of the polygon */ -Polygon.prototype.clone = function () { +Polygon.prototype.clone = function () +{ return new Polygon(this.points.slice()); }; @@ -62,19 +67,22 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this polygon */ -Polygon.prototype.contains = function (x, y) { +Polygon.prototype.contains = function (x, y) +{ var inside = false; // use some raycasting to test hits // https://github.com/substack/point-in-polygon/blob/master/index.js var length = this.points.length / 2; - for (var i = 0, j = length - 1; i < length; j = i++) { + for (var i = 0, j = length - 1; i < length; j = i++) + { var xi = this.points[i * 2], yi = this.points[i * 2 + 1], xj = this.points[j * 2], yj = this.points[j * 2 + 1], intersect = ((yi > y) !== (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi); - if (intersect) { + if (intersect) + { inside = !inside; } } diff --git a/src/core/math/shapes/Rectangle.js b/src/core/math/shapes/Rectangle.js index 16ac62a..4008b68 100644 --- a/src/core/math/shapes/Rectangle.js +++ b/src/core/math/shapes/Rectangle.js @@ -10,7 +10,8 @@ * @param width {number} The overall width of this rectangle * @param height {number} The overall height of this rectangle */ -function Rectangle(x, y, width, height) { +function Rectangle(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -60,7 +61,8 @@ * * @return {Rectangle} a copy of the rectangle */ -Rectangle.prototype.clone = function () { +Rectangle.prototype.clone = function () +{ return new Rectangle(this.x, this.y, this.width, this.height); }; @@ -71,13 +73,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rectangle */ -Rectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Rectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/math/shapes/RoundedRectangle.js b/src/core/math/shapes/RoundedRectangle.js index 27d286e..7bf6411 100644 --- a/src/core/math/shapes/RoundedRectangle.js +++ b/src/core/math/shapes/RoundedRectangle.js @@ -11,7 +11,8 @@ * @param height {number} The overall height of this rounded rectangle * @param radius {number} Controls the radius of the rounded corners */ -function RoundedRectangle(x, y, width, height, radius) { +function RoundedRectangle(x, y, width, height, radius) +{ /** * @member {number} * @default 0 @@ -58,7 +59,8 @@ * * @return {RoundedRectangle} a copy of the rounded rectangle */ -RoundedRectangle.prototype.clone = function () { +RoundedRectangle.prototype.clone = function () +{ return new RoundedRectangle(this.x, this.y, this.width, this.height, this.radius); }; @@ -69,13 +71,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rounded Rectangle */ -RoundedRectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +RoundedRectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/primitives/Graphics.js b/src/core/primitives/Graphics.js index 261c534..e902d2a 100644 --- a/src/core/primitives/Graphics.js +++ b/src/core/primitives/Graphics.js @@ -16,7 +16,8 @@ * @extends DisplayObjectContainer * @namespace PIXI */ -function Graphics() { +function Graphics() +{ DisplayObjectContainer.call(this); this.renderable = true; @@ -154,16 +155,20 @@ * @private */ cacheAsBitmap: { - get: function () { + get: function () + { return this._cacheAsBitmap; }, - set: function (value) { + set: function (value) + { this._cacheAsBitmap = value; - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._generateCachedSprite(); } - else { + else + { this.destroyCachedSprite(); this.dirty = true; } @@ -176,7 +181,8 @@ * * @return {Graphics} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ var clone = new Graphics(); clone.renderable = this.renderable; @@ -192,7 +198,8 @@ clone.cachedSpriteDirty = this.cachedSpriteDirty; // copy graphics data - for (var i = 0; i < this.graphicsData.length; ++i) { + for (var i = 0; i < this.graphicsData.length; ++i) + { clone.graphicsData.push(this.graphicsData.clone()); } @@ -211,17 +218,21 @@ * @param alpha {number} alpha of the line to draw, will update the objects stored style * @return {Graphics} */ -Graphics.prototype.lineStyle = function (lineWidth, color, alpha) { +Graphics.prototype.lineStyle = function (lineWidth, color, alpha) +{ this.lineWidth = lineWidth || 0; this.lineColor = color || 0; this.lineAlpha = (arguments.length < 3) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length) + { // halfway through a line? start a new one! this.drawShape( new math.Polygon( this.currentPath.shape.points.slice(-2) )); } - else { + else + { // otherwise its empty so lets just set the line properties this.currentPath.lineWidth = this.lineWidth; this.currentPath.lineColor = this.lineColor; @@ -239,7 +250,8 @@ * @param y {number} the Y coordinate to move to * @return {Graphics} */ -Graphics.prototype.moveTo = function (x, y) { +Graphics.prototype.moveTo = function (x, y) +{ this.drawShape(new math.Polygon([x,y])); return this; @@ -253,7 +265,8 @@ * @param y {number} the Y coordinate to draw to * @return {Graphics} */ -Graphics.prototype.lineTo = function (x, y) { +Graphics.prototype.lineTo = function (x, y) +{ this.currentPath.shape.points.push(x, y); this.dirty = true; @@ -270,13 +283,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -285,7 +302,8 @@ n = 20, points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { this.moveTo(0, 0); } @@ -293,7 +311,8 @@ var fromY = points[points.length-1]; var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; xa = fromX + ( (cpX - fromX) * j ); @@ -319,13 +338,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -342,7 +365,8 @@ var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; dt = (1 - j); @@ -373,13 +397,17 @@ * @param radius {number} The radius of the arc * @return {Graphics} */ -Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points.push(x1, y1); } } - else { + else + { this.moveTo(x1, y1); } @@ -392,12 +420,15 @@ b2 = x2 - x1, mm = Math.abs(a1 * b2 - b1 * a2); - if (mm < 1.0e-8 || radius === 0) { - if (points[points.length-2] !== x1 || points[points.length-1] !== y1) { + if (mm < 1.0e-8 || radius === 0) + { + if (points[points.length-2] !== x1 || points[points.length-1] !== y1) + { points.push(x1, y1); } } - else { + else + { var dd = a1 * a1 + b1 * b1, cc = a2 * a2 + b2 * b2, tt = a1 * a2 + b1 * b2, @@ -433,42 +464,51 @@ * @param anticlockwise {boolean} Optional. Specifies whether the drawing should be counterclockwise or clockwise. False is default, and indicates clockwise, while true indicates counter-clockwise. * @return {Graphics} */ -Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) { +Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) +{ var startX = cx + Math.cos(startAngle) * radius; var startY = cy + Math.sin(startAngle) * radius; var points; // TODO - This if-else makes no sense. It uses currentPath in the else where it doesn't exist... - if (this.currentPath) { + if (this.currentPath) + { points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { points.push(startX, startY); } - else if (points[points.length-2] !== startX || points[points.length-1] !== startY) { + else if (points[points.length-2] !== startX || points[points.length-1] !== startY) + { points.push(startX, startY); } } - else { + else + { this.moveTo(startX, startY); points = this.currentPath.shape.points; } - if (startAngle === endAngle) { + if (startAngle === endAngle) + { return this; } - if (!anticlockwise && endAngle <= startAngle) { + if (!anticlockwise && endAngle <= startAngle) + { endAngle += Math.PI * 2; } - else if (anticlockwise && startAngle <= endAngle) { + else if (anticlockwise && startAngle <= endAngle) + { startAngle += Math.PI * 2; } var sweep = anticlockwise ? (startAngle - endAngle) *-1 : (endAngle - startAngle); var segs = (Math.abs(sweep)/ (Math.PI * 2)) * 40; - if (sweep === 0) { + if (sweep === 0) + { return this; } @@ -482,7 +522,8 @@ var remainder = ( segMinus % 1 ) / segMinus; - for (var i = 0; i <= segMinus; ++i) { + for (var i = 0; i <= segMinus; ++i) + { var real = i + remainder * i; var angle = ((theta) + startAngle + (theta2 * real)); @@ -506,13 +547,16 @@ * @param alpha {number} the alpha of the fill * @return {Graphics} */ -Graphics.prototype.beginFill = function (color, alpha) { +Graphics.prototype.beginFill = function (color, alpha) +{ this.filling = true; this.fillColor = color || 0; this.fillAlpha = (alpha === undefined) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length <= 2) + { this.currentPath.fill = this.filling; this.currentPath.fillColor = this.fillColor; this.currentPath.fillAlpha = this.fillAlpha; @@ -526,7 +570,8 @@ * * @return {Graphics} */ -Graphics.prototype.endFill = function () { +Graphics.prototype.endFill = function () +{ this.filling = false; this.fillColor = null; this.fillAlpha = 1; @@ -542,7 +587,8 @@ * @param height {number} The height of the rectangle * @return {Graphics} */ -Graphics.prototype.drawRect = function ( x, y, width, height ) { +Graphics.prototype.drawRect = function ( x, y, width, height ) +{ this.drawShape(new math.Rectangle(x,y, width, height)); return this; @@ -556,7 +602,8 @@ * @param height {number} The height of the rectangle * @param radius {number} Radius of the rectangle corners */ -Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) { +Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) +{ this.drawShape(new math.RoundedRectangle(x, y, width, height, radius)); return this; @@ -570,7 +617,8 @@ * @param radius {number} The radius of the circle * @return {Graphics} */ -Graphics.prototype.drawCircle = function (x, y, radius) { +Graphics.prototype.drawCircle = function (x, y, radius) +{ this.drawShape(new math.Circle(x,y, radius)); return this; @@ -585,7 +633,8 @@ * @param height {number} The half height of the ellipse * @return {Graphics} */ -Graphics.prototype.drawEllipse = function (x, y, width, height) { +Graphics.prototype.drawEllipse = function (x, y, width, height) +{ this.drawShape(new math.Ellipse(x, y, width, height)); return this; @@ -597,8 +646,10 @@ * @param path {Array} The path data used to construct the polygon. * @return {Graphics} */ -Graphics.prototype.drawPolygon = function (path) { - if (!(path instanceof Array)) { +Graphics.prototype.drawPolygon = function (path) +{ + if (!(path instanceof Array)) + { path = Array.prototype.slice.call(arguments); } @@ -612,7 +663,8 @@ * * @return {Graphics} */ -Graphics.prototype.clear = function () { +Graphics.prototype.clear = function () +{ this.lineWidth = 0; this.filling = false; @@ -631,7 +683,8 @@ * @param scaleMode {number} Should be one of the scaleMode consts * @return {Texture} a texture of the graphics object */ -Graphics.prototype.generateTexture = function (resolution, scaleMode) { +Graphics.prototype.generateTexture = function (resolution, scaleMode) +{ resolution = resolution || 1; var bounds = this.getBounds(); @@ -655,17 +708,21 @@ * * @param renderer {WebGLRenderer} */ -Graphics.prototype._renderWebGL = function (renderer) { +Graphics.prototype._renderWebGL = function (renderer) +{ // if the sprite is not visible or the alpha is 0 then no need to render this element - if (this.isMask === true) { + if (this.isMask === true) + { return; } // this code may still be needed so leaving for now.. - // + // /* - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture on the gpu too! @@ -681,17 +738,24 @@ return; } - */ - - // check if the webgl graphic needs to be updated - if (this.glDirty) { - this.dirty = true; - this.glDirty = false; - } + else */ - renderer.setObjectRendererer(renderer.graphicsRenderer); - renderer.graphicsRenderer.render(this); + renderer.spriteBatch.stop(); + renderer.blendModeManager.setBlendMode(this.blendMode); + // check blend mode + renderer.blendModeManager.setBlendMode( this.blendMode ); + + // check if the webgl graphic needs to be updated + if (this.glDirty) + { + this.dirty = true; + this.glDirty = false; + } + + WebGLGraphics.renderGraphics(this, renderer); + + renderer.spriteBatch.start(); }; /** @@ -700,14 +764,18 @@ * @param renderer {CanvasRenderer} * @private */ -Graphics.prototype.renderCanvas = function (renderer) { +Graphics.prototype.renderCanvas = function (renderer) +{ // 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.isMask === true) { + if (!this.visible || this.alpha <= 0 || this.isMask === true) + { return; } - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture @@ -723,16 +791,19 @@ return; } - else { + else + { var context = renderer.context; var transform = this.worldTransform; - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } @@ -748,11 +819,13 @@ CanvasGraphics.renderGraphics(this, context); - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } } @@ -763,13 +836,16 @@ * * @return {Rectangle} the rectangular bounding area */ -Graphics.prototype.getBounds = function (matrix) { +Graphics.prototype.getBounds = function (matrix) +{ // return an empty object if the item is a mask! - if (this.isMask) { + if (this.isMask) + { return math.Rectangle.EMPTY; } - if (this.dirty) { + if (this.dirty) + { this.updateLocalBounds(); this.glDirty = true; @@ -841,23 +917,27 @@ * Update the bounds of the object * */ -Graphics.prototype.updateLocalBounds = function () { +Graphics.prototype.updateLocalBounds = function () +{ var minX = Infinity; var maxX = -Infinity; var minY = Infinity; var maxY = -Infinity; - if (this.graphicsData.length) { + if (this.graphicsData.length) + { var shape, points, x, y, w, h; - for (var i = 0; i < this.graphicsData.length; i++) { + for (var i = 0; i < this.graphicsData.length; i++) + { var data = this.graphicsData[i]; var type = data.type; var lineWidth = data.lineWidth; shape = data.shape; - if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) { + if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) + { x = shape.x - lineWidth/2; y = shape.y - lineWidth/2; w = shape.width + lineWidth; @@ -869,7 +949,8 @@ minY = y < minY ? y : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.CIRC) { + else if (type === CONST.SHAPES.CIRC) + { x = shape.x; y = shape.y; w = shape.radius + lineWidth/2; @@ -881,7 +962,8 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.ELIP) { + else if (type === CONST.SHAPES.ELIP) + { x = shape.x; y = shape.y; w = shape.width + lineWidth/2; @@ -893,11 +975,13 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else { + else + { // POLY points = shape.points; - for (var j = 0; j < points.length; j += 2) { + for (var j = 0; j < points.length; j += 2) + { x = points[j]; y = points[j+1]; @@ -910,7 +994,8 @@ } } } - else { + else + { minX = 0; maxX = 0; minY = 0; @@ -931,10 +1016,12 @@ * * @private */ -Graphics.prototype._generateCachedSprite = function () { +Graphics.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { var canvasBuffer = new CanvasBuffer(bounds.width, bounds.height); var texture = Texture.fromCanvas(canvasBuffer.canvas); @@ -943,7 +1030,8 @@ this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.buffer.resize(bounds.width, bounds.height); } @@ -968,7 +1056,8 @@ * * @private */ -Graphics.prototype.updateCachedSpriteTexture = function () { +Graphics.prototype.updateCachedSpriteTexture = function () +{ var cachedSprite = this._cachedSprite; var texture = cachedSprite.texture; var canvas = cachedSprite.buffer.canvas; @@ -989,7 +1078,8 @@ * Destroys a previous cached sprite. * */ -Graphics.prototype.destroyCachedSprite = function () { +Graphics.prototype.destroyCachedSprite = function () +{ this._cachedSprite.texture.destroy(true); // let the gc collect the unused sprite @@ -1003,10 +1093,13 @@ * @param {Circle|Rectangle|Ellipse|Line|Polygon} shape The Shape object to draw. * @return {GraphicsData} The generated GraphicsData object. */ -Graphics.prototype.drawShape = function (shape) { - if (this.currentPath) { +Graphics.prototype.drawShape = function (shape) +{ + if (this.currentPath) + { // check current path! - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath.shape.points.length <= 2) + { this.graphicsData.pop(); } } @@ -1017,7 +1110,8 @@ this.graphicsData.push(data); - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { data.shape.closed = this.filling; this.currentPath = data; } diff --git a/src/core/primitives/GraphicsData.js b/src/core/primitives/GraphicsData.js index 99decbe..788f6f2 100644 --- a/src/core/primitives/GraphicsData.js +++ b/src/core/primitives/GraphicsData.js @@ -4,7 +4,8 @@ * @class * @namespace PIXI */ -function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) { +function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) +{ this.lineWidth = lineWidth; this.lineColor = lineColor; this.lineAlpha = lineAlpha; @@ -27,7 +28,8 @@ * * @return {GraphicsData} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ return new GraphicsData( this.lineWidth, this.lineColor, diff --git a/src/core/renderers/canvas/CanvasRenderer.js b/src/core/renderers/canvas/CanvasRenderer.js index 15a0978..7aebd44 100644 --- a/src/core/renderers/canvas/CanvasRenderer.js +++ b/src/core/renderers/canvas/CanvasRenderer.js @@ -17,17 +17,22 @@ * @param [options.resolution=1] {number} the resolution of the renderer retina would be 2 * @param [options.clearBeforeRender=true] {boolean} This sets if the CanvasRenderer will clear the canvas or not before the new render pass. */ -function CanvasRenderer(width, height, options) { +function CanvasRenderer(width, height, options) +{ utils.sayHello('Canvas'); - if (options) { - for (var i in CONST.defaultRenderOptions) { - if (typeof options[i] === 'undefined') { + if (options) + { + for (var i in CONST.defaultRenderOptions) + { + if (typeof options[i] === 'undefined') + { options[i] = CONST.defaultRenderOptions[i]; } } } - else { + else + { options = CONST.defaultRenderOptions; } @@ -156,19 +161,24 @@ this.smoothProperty = null; - if (this.context.imageSmoothingEnabled) { + if (this.context.imageSmoothingEnabled) + { this.smoothProperty = 'imageSmoothingEnabled'; } - else if (this.context.webkitImageSmoothingEnabled) { + else if (this.context.webkitImageSmoothingEnabled) + { this.smoothProperty = 'webkitImageSmoothingEnabled'; } - else if (this.context.mozImageSmoothingEnabled) { + else if (this.context.mozImageSmoothingEnabled) + { this.smoothProperty = 'mozImageSmoothingEnabled'; } - else if (this.context.oImageSmoothingEnabled) { + else if (this.context.oImageSmoothingEnabled) + { this.smoothProperty = 'oImageSmoothingEnabled'; } - else if (this.context.msImageSmoothingEnabled) { + else if (this.context.msImageSmoothingEnabled) + { this.smoothProperty = 'msImageSmoothingEnabled'; } @@ -193,10 +203,12 @@ * @memberof CanvasRenderer# */ backgroundColor: { - get: function () { + get: function () + { return this._backgroundColor; }, - set: function (val) { + set: function (val) + { this._backgroundColor = val; this._backgroundColorString = utils.hex2string(val); } @@ -208,7 +220,8 @@ * * @param object {DisplayObject} the object to be rendered */ -CanvasRenderer.prototype.render = function (object) { +CanvasRenderer.prototype.render = function (object) +{ object.updateTransform(); this.context.setTransform(1,0,0,1,0,0); @@ -218,16 +231,20 @@ this.currentBlendMode = CONST.blendModes.NORMAL; this.context.globalCompositeOperation = this.blendModes[CONST.blendModes.NORMAL]; - if (navigator.isCocoonJS && this.view.screencanvas) { + if (navigator.isCocoonJS && this.view.screencanvas) + { this.context.fillStyle = 'black'; this.context.clear(); } - if (this.clearBeforeRender) { - if (this.transparent) { + if (this.clearBeforeRender) + { + if (this.transparent) + { this.context.clearRect(0, 0, this.width, this.height); } - else { + else + { this.context.fillStyle = this._backgroundColorString; this.context.fillRect(0, 0, this.width , this.height); } @@ -241,8 +258,10 @@ * * @param [removeView=false] {boolean} Removes the Canvas element from the DOM. */ -CanvasRenderer.prototype.destroy = function (removeView) { - if (removeView && this.view.parent) { +CanvasRenderer.prototype.destroy = function (removeView) +{ + if (removeView && this.view.parent) + { this.view.parent.removeChild(this.view); } @@ -257,14 +276,16 @@ * @param width {number} the new width of the canvas view * @param height {number} the new height of the canvas view */ -CanvasRenderer.prototype.resize = function (width, height) { +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) { + if (this.autoResize) + { this.view.style.width = this.width / this.resolution + 'px'; this.view.style.height = this.height / this.resolution + 'px'; } @@ -276,7 +297,8 @@ * @param displayObject {DisplayObject} The displayObject to render * @private */ -CanvasRenderer.prototype.renderDisplayObject = function (displayObject) { +CanvasRenderer.prototype.renderDisplayObject = function (displayObject) +{ displayObject.renderCanvas(this); }; @@ -285,11 +307,14 @@ * * @private */ -CanvasRenderer.prototype._mapBlendModes = function () { - if (!this.blendModes) { +CanvasRenderer.prototype._mapBlendModes = function () +{ + if (!this.blendModes) + { this.blendModes = {}; - if (utils.canUseNewCanvasBlendModes()) { + if (utils.canUseNewCanvasBlendModes()) + { this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? this.blendModes[CONST.blendModes.MULTIPLY] = 'multiply'; @@ -308,7 +333,8 @@ this.blendModes[CONST.blendModes.COLOR] = 'color'; this.blendModes[CONST.blendModes.LUMINOSITY] = 'luminosity'; } - else { + else + { // this means that the browser does not support the cool new blend modes in canvas 'cough' ie 'cough' this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? diff --git a/src/core/renderers/canvas/utils/CanvasBuffer.js b/src/core/renderers/canvas/utils/CanvasBuffer.js index ebe5d47..b183a66 100644 --- a/src/core/renderers/canvas/utils/CanvasBuffer.js +++ b/src/core/renderers/canvas/utils/CanvasBuffer.js @@ -6,7 +6,8 @@ * @param width {number} the width for the newly created canvas * @param height {number} the height for the newly created canvas */ -function CanvasBuffer(width, height) { +function CanvasBuffer(width, height) +{ /** * The Canvas object that belongs to this CanvasBuffer. * @@ -36,10 +37,12 @@ * @memberof CanvasBuffer# */ width: { - get: function () { + get: function () + { return this.canvas.width; }, - set: function (val) { + set: function (val) + { this.canvas.width = val; } }, @@ -50,10 +53,12 @@ * @memberof CanvasBuffer# */ height: { - get: function () { + get: function () + { return this.canvas.height; }, - set: function (val) { + set: function (val) + { this.canvas.height = val; } } @@ -64,7 +69,8 @@ * * @private */ -CanvasBuffer.prototype.clear = function () { +CanvasBuffer.prototype.clear = function () +{ this.context.setTransform(1, 0, 0, 1, 0, 0); this.context.clearRect(0,0, this.canvas.width, this.canvas.height); }; @@ -75,7 +81,8 @@ * @param width {number} the new width of the canvas * @param height {number} the new height of the canvas */ -CanvasBuffer.prototype.resize = function (width, height) { +CanvasBuffer.prototype.resize = function (width, height) +{ this.canvas.width = width; this.canvas.height = height; }; diff --git a/src/core/renderers/canvas/utils/CanvasGraphics.js b/src/core/renderers/canvas/utils/CanvasGraphics.js index c7eaa2a..3f2a91f 100644 --- a/src/core/renderers/canvas/utils/CanvasGraphics.js +++ b/src/core/renderers/canvas/utils/CanvasGraphics.js @@ -13,15 +13,18 @@ * @param graphics {Graphics} the actual graphics object to render * @param context {CanvasRenderingContext2D} the 2d drawing method of the canvas */ -CanvasGraphics.renderGraphics = function (graphics, context) { +CanvasGraphics.renderGraphics = function (graphics, context) +{ var worldAlpha = graphics.worldAlpha; - if (graphics.dirty) { + if (graphics.dirty) + { this.updateGraphicsTint(graphics); graphics.dirty = false; } - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; @@ -30,69 +33,82 @@ context.lineWidth = data.lineWidth; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { context.beginPath(); var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } - if (shape.closed) { + if (shape.closed) + { context.lineTo(points[0], points[1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fillRect(shape.x, shape.y, shape.width, shape.height); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.strokeRect(shape.x, shape.y, shape.width, shape.height); } } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.beginPath(); context.arc(shape.x, shape.y, shape.radius,0,2*Math.PI); context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas var w = shape.width * 2; @@ -119,18 +135,21 @@ context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; var width = shape.width; @@ -152,13 +171,15 @@ context.quadraticCurveTo(rx, ry, rx, ry + radius); context.closePath(); - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); @@ -174,45 +195,54 @@ * @param graphics {Graphics} the graphics which will be used as a mask * @param context {CanvasRenderingContext2D} the context 2d method of the canvas */ -CanvasGraphics.renderGraphicsMask = function (graphics, context) { +CanvasGraphics.renderGraphicsMask = function (graphics, context) +{ var len = graphics.graphicsData.length; - if (len === 0) { + if (len === 0) + { return; } context.beginPath(); - for (var i = 0; i < len; i++) { + for (var i = 0; i < len; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { context.rect(shape.x, shape.y, shape.width, shape.height); context.closePath(); } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.arc(shape.x, shape.y, shape.radius, 0, 2 * Math.PI); context.closePath(); } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas @@ -237,7 +267,8 @@ context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); context.closePath(); } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; @@ -262,8 +293,10 @@ } }; -CanvasGraphics.updateGraphicsTint = function (graphics) { - if (graphics.tint === 0xFFFFFF) { +CanvasGraphics.updateGraphicsTint = function (graphics) +{ + if (graphics.tint === 0xFFFFFF) + { return; } @@ -271,7 +304,8 @@ var tintG = (graphics.tint >> 8 & 0xFF) / 255; var tintB = (graphics.tint & 0xFF)/ 255; - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var fillColor = data.fillColor | 0; diff --git a/src/core/renderers/canvas/utils/CanvasMaskManager.js b/src/core/renderers/canvas/utils/CanvasMaskManager.js index e04a733..9827d36 100644 --- a/src/core/renderers/canvas/utils/CanvasMaskManager.js +++ b/src/core/renderers/canvas/utils/CanvasMaskManager.js @@ -6,7 +6,8 @@ * @class * @namespace PIXI */ -function CanvasMaskManager() {} +function CanvasMaskManager() +{} CanvasMaskManager.prototype.constructor = CanvasMaskManager; module.exports = CanvasMaskManager; @@ -17,7 +18,8 @@ * @param maskData {object} the maskData that will be pushed * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.pushMask = function (maskData, renderer) { +CanvasMaskManager.prototype.pushMask = function (maskData, renderer) +{ renderer.context.save(); var cacheAlpha = maskData.alpha; @@ -45,6 +47,7 @@ * * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.popMask = function (renderer) { +CanvasMaskManager.prototype.popMask = function (renderer) +{ renderer.context.restore(); }; diff --git a/src/core/renderers/canvas/utils/CanvasTinter.js b/src/core/renderers/canvas/utils/CanvasTinter.js index 17e0529..d2fb1bc 100644 --- a/src/core/renderers/canvas/utils/CanvasTinter.js +++ b/src/core/renderers/canvas/utils/CanvasTinter.js @@ -14,7 +14,8 @@ * @param color {number} the color to use to tint the sprite with * @return {HTMLCanvasElement} The tinted canvas */ -CanvasTinter.getTintedTexture = function (sprite, color) { +CanvasTinter.getTintedTexture = function (sprite, color) +{ var texture = sprite.texture; color = CanvasTinter.roundColor(color); @@ -23,7 +24,8 @@ texture.tintCache = texture.tintCache || {}; - if (texture.tintCache[stringColor]) { + if (texture.tintCache[stringColor]) + { return texture.tintCache[stringColor]; } @@ -33,14 +35,16 @@ //CanvasTinter.tintWithPerPixel(texture, stringColor, canvas); CanvasTinter.tintMethod(texture, color, canvas); - if (CanvasTinter.convertTintToImage) { + if (CanvasTinter.convertTintToImage) + { // is this better? var tintImage = new Image(); tintImage.src = canvas.toDataURL(); texture.tintCache[stringColor] = tintImage; } - else { + else + { texture.tintCache[stringColor] = canvas; // if we are not converting the texture to an image then we need to lose the reference to the canvas CanvasTinter.canvas = null; @@ -56,7 +60,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithMultiply = function (texture, color, canvas) { +CanvasTinter.tintWithMultiply = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -104,7 +109,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithOverlay = function (texture, color, canvas) { +CanvasTinter.tintWithOverlay = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -139,7 +145,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithPerPixel = function (texture, color, canvas) { +CanvasTinter.tintWithPerPixel = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -167,7 +174,8 @@ var pixels = pixelData.data; - for (var i = 0; i < pixels.length; i += 4) { + for (var i = 0; i < pixels.length; i += 4) + { pixels[i+0] *= r; pixels[i+1] *= g; pixels[i+2] *= b; @@ -181,7 +189,8 @@ * * @param color {number} the color to round, should be a hex color */ -CanvasTinter.roundColor = function (color) { +CanvasTinter.roundColor = function (color) +{ var step = CanvasTinter.cacheStepsPerColorChannel; var rgbValues = utils.hex2rgb(color); diff --git a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js index 9f2f89a..35edbaf 100644 --- a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js +++ b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLBlendModeManager(renderer) { +function WebGLBlendModeManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -23,8 +24,10 @@ * * @param blendMode {number} the blendMode, should be a Pixi const, such as BlendModes.ADD */ -WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) { - if (this.currentBlendMode === blendMode) { +WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) +{ + if (this.currentBlendMode === blendMode) + { return false; } diff --git a/src/core/renderers/webgl/managers/WebGLFilterManager.js b/src/core/renderers/webgl/managers/WebGLFilterManager.js index 1179258..2dac048 100644 --- a/src/core/renderers/webgl/managers/WebGLFilterManager.js +++ b/src/core/renderers/webgl/managers/WebGLFilterManager.js @@ -7,7 +7,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLFilterManager(renderer) { +function WebGLFilterManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -32,7 +33,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.texturePool.length = 0; self.initShaderBuffers(); }); @@ -46,7 +48,8 @@ * @param renderer {WebGLRenderer} * @param buffer {ArrayBuffer} */ -WebGLFilterManager.prototype.begin = function (buffer) { +WebGLFilterManager.prototype.begin = function (buffer) +{ this.defaultShader = this.renderer.shaderManager.defaultShader; this.width = this.renderer.projection.x * 2; @@ -60,7 +63,8 @@ * * @param filterBlock {object} the filter that will be pushed to the current filter stack */ -WebGLFilterManager.prototype.pushFilter = function (filterBlock) { +WebGLFilterManager.prototype.pushFilter = function (filterBlock) +{ var gl = this.renderer.gl; var projection = this.renderer.projection; @@ -78,10 +82,12 @@ this.offsetY += filterBlock._filterArea.y; var texture = this.texturePool.pop(); - if (!texture) { + if (!texture) + { texture = new FilterTexture(this.renderer.gl, this.width, this.height); } - else { + else + { texture.resize(this.width, this.height); } @@ -98,29 +104,35 @@ var localX = filterArea.x, localY = filterArea.y; - if (filterArea.x < 0) { + if (filterArea.x < 0) + { filterArea.width += filterArea.x; filterArea.x = 0; } - if (filterArea.y < 0) { + if (filterArea.y < 0) + { filterArea.height += filterArea.y; filterArea.y = 0; } - if (localX + filterArea.width > this.width) { + if (localX + filterArea.width > this.width) + { filterArea.width = this.width - localX; } - if (localY + filterArea.height > this.height) { + if (localY + filterArea.height > this.height) + { filterArea.height = this.height - localY; } - if (filterArea.width < 0) { + if (filterArea.width < 0) + { filterArea.width = 0; } - if (filterArea.height < 0) { + if (filterArea.height < 0) + { filterArea.height = 0; } @@ -154,7 +166,8 @@ * Removes the last filter from the filter stack and doesn't return it. * */ -WebGLFilterManager.prototype.popFilter = function () { +WebGLFilterManager.prototype.popFilter = function () +{ var gl = this.renderer.gl; var filterBlock = this.filterStack.pop(); @@ -163,7 +176,8 @@ var projection = this.renderer.projection; var offset = this.renderer.offset; - if (filterBlock.filterPasses.length > 1) { + if (filterBlock.filterPasses.length > 1) + { gl.viewport(0, 0, filterArea.width, filterArea.height); gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); @@ -193,7 +207,8 @@ var inputTexture = texture; var outputTexture = this.texturePool.pop(); - if (!outputTexture) { + if (!outputTexture) + { outputTexture = new FilterTexture(this.renderer.gl, this.width, this.height); } outputTexture.resize(this.width, this.height); @@ -204,7 +219,8 @@ gl.disable(gl.BLEND); - for (var i = 0; i < filterBlock.filterPasses.length-1; i++) { + for (var i = 0; i < filterBlock.filterPasses.length-1; i++) + { var filterPass = filterBlock.filterPasses[i]; gl.bindFramebuffer(gl.FRAMEBUFFER, outputTexture.frameBuffer ); @@ -243,10 +259,12 @@ var buffer = this.buffer; // time to render the filters texture to the previous scene - if (this.filterStack.length === 0) { + if (this.filterStack.length === 0) + { gl.colorMask(true, true, true, true);//this.transparent); } - else { + else + { var currentFilter = this.filterStack[this.filterStack.length-1]; filterArea = currentFilter._filterArea; @@ -332,13 +350,15 @@ * @param width {number} the horizontal range of the filter * @param height {number} the vertical range of the filter */ -WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) { +WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) +{ // use program var gl = this.renderer.gl; var shader = filter.shaders[gl.id]; - if (!shader) { + if (!shader) + { shader = new Shader(gl); shader.fragmentSrc = filter.fragmentSrc; @@ -356,7 +376,8 @@ gl.uniform2f(shader.projectionVector, width/2, -height/2); gl.uniform2f(shader.offsetVector, 0,0); - if (filter.uniforms.dimensions) { + 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]; @@ -386,7 +407,8 @@ * Initialises the shader buffers. * */ -WebGLFilterManager.prototype.initShaderBuffers = function () { +WebGLFilterManager.prototype.initShaderBuffers = function () +{ var gl = this.renderer.gl; // create some buffers @@ -432,7 +454,8 @@ * Destroys the filter and removes it from the filter stack. * */ -WebGLFilterManager.prototype.destroy = function () { +WebGLFilterManager.prototype.destroy = function () +{ var gl = this.renderer.gl; this.filterStack = null; @@ -441,7 +464,8 @@ this.offsetY = 0; // destroy textures - for (var i = 0; i < this.texturePool.length; i++) { + for (var i = 0; i < this.texturePool.length; i++) + { this.texturePool[i].destroy(); } diff --git a/src/core/renderers/webgl/managers/WebGLManager.js b/src/core/renderers/webgl/managers/WebGLManager.js index 9d47b5c..c30cd51 100644 --- a/src/core/renderers/webgl/managers/WebGLManager.js +++ b/src/core/renderers/webgl/managers/WebGLManager.js @@ -3,7 +3,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLManager(renderer) { +function WebGLManager(renderer) +{ /** * The renderer this manager works for. * @@ -15,6 +16,7 @@ WebGLManager.prototype.constructor = WebGLManager; module.exports = WebGLManager; -WebGLManager.prototype.destroy = function () { +WebGLManager.prototype.destroy = function () +{ this.renderer = null; }; diff --git a/src/core/renderers/webgl/managers/WebGLMaskManager.js b/src/core/renderers/webgl/managers/WebGLMaskManager.js index 2f90b64..e568812 100644 --- a/src/core/renderers/webgl/managers/WebGLMaskManager.js +++ b/src/core/renderers/webgl/managers/WebGLMaskManager.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLMaskManager(renderer) { +function WebGLMaskManager(renderer) +{ WebGLManager.call(this, renderer); } @@ -19,12 +20,15 @@ * * @param maskData {any[]} */ -WebGLMaskManager.prototype.pushMask = function (maskData) { - if (maskData.dirty) { +WebGLMaskManager.prototype.pushMask = function (maskData) +{ + if (maskData.dirty) + { WebGLGraphics.updateGraphics(maskData, this.renderer.gl); } - if (!maskData._webGL[this.renderer.gl.id].data.length) { + if (!maskData._webGL[this.renderer.gl.id].data.length) + { return; } @@ -36,6 +40,7 @@ * * @param maskData {any[]} */ -WebGLMaskManager.prototype.popMask = function (maskData) { +WebGLMaskManager.prototype.popMask = function (maskData) +{ this.renderer.stencilManager.popStencil(maskData, maskData._webGL[this.renderer.gl.id].data[0], this.renderer); }; diff --git a/src/core/renderers/webgl/managers/WebGLShaderManager.js b/src/core/renderers/webgl/managers/WebGLShaderManager.js index fef071c..90c6477 100644 --- a/src/core/renderers/webgl/managers/WebGLShaderManager.js +++ b/src/core/renderers/webgl/managers/WebGLShaderManager.js @@ -10,7 +10,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLShaderManager(renderer) { +function WebGLShaderManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -28,7 +29,8 @@ */ this.tempAttribState = []; - for (var i = 0; i < this.maxAttibs; i++) { + for (var i = 0; i < this.maxAttibs; i++) + { this.attribState[i] = false; } @@ -66,7 +68,8 @@ // listen for context and update necessary shaders var self = this; - this.renderer.on('context', function (event) { + this.renderer.on('context', function (event) + { var gl = event.data; // this shader is used for rendering primitives @@ -97,29 +100,36 @@ * * @param attribs {Array} attribs */ -WebGLShaderManager.prototype.setAttribs = function (attribs) { +WebGLShaderManager.prototype.setAttribs = function (attribs) +{ // reset temp state var i; - for (i = 0; i < this.tempAttribState.length; i++) { + for (i = 0; i < this.tempAttribState.length; i++) + { this.tempAttribState[i] = false; } // set the new attribs - for (var a in attribs) { + for (var a in attribs) + { this.tempAttribState[attribs[a]] = true; } var gl = this.renderer.gl; - for (i = 0; i < this.attribState.length; i++) { - if (this.attribState[i] !== this.tempAttribState[i]) { + for (i = 0; i < this.attribState.length; i++) + { + if (this.attribState[i] !== this.tempAttribState[i]) + { this.attribState[i] = this.tempAttribState[i]; - if (this.attribState[i]) { + if (this.attribState[i]) + { gl.enableVertexAttribArray(i); } - else { + else + { gl.disableVertexAttribArray(i); } } @@ -131,8 +141,10 @@ * * @param shader {Any} */ -WebGLShaderManager.prototype.setShader = function (shader) { - if (this._currentId === shader.uuid) { +WebGLShaderManager.prototype.setShader = function (shader) +{ + if (this._currentId === shader.uuid) + { return false; } @@ -150,7 +162,8 @@ * Destroys this object. * */ -WebGLShaderManager.prototype.destroy = function () { +WebGLShaderManager.prototype.destroy = function () +{ this.attribState = null; this.tempAttribState = null; diff --git a/src/core/renderers/webgl/managers/WebGLStencilManager.js b/src/core/renderers/webgl/managers/WebGLStencilManager.js index 9ec6398..4cb0134 100644 --- a/src/core/renderers/webgl/managers/WebGLStencilManager.js +++ b/src/core/renderers/webgl/managers/WebGLStencilManager.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLStencilManager(renderer) { +function WebGLStencilManager(renderer) +{ WebGLManager.call(this, renderer); this.stencilStack = []; @@ -24,12 +25,14 @@ * @param graphics {Graphics} * @param webGLData {any[]} */ -WebGLStencilManager.prototype.pushStencil = function (graphics, webGLData) { +WebGLStencilManager.prototype.pushStencil = function (graphics, webGLData) +{ var gl = this.renderer.gl; this.bindGraphics(graphics, webGLData, this.renderer); - if (this.stencilStack.length === 0) { + if (this.stencilStack.length === 0) + { gl.enable(gl.STENCIL_TEST); gl.clear(gl.STENCIL_BUFFER_BIT); this.reverse = true; @@ -47,14 +50,17 @@ // draw the triangle strip! - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } @@ -62,31 +68,38 @@ // draw a quad to increment.. gl.drawElements(gl.TRIANGLE_FAN, 4, gl.UNSIGNED_SHORT, ( webGLData.indices.length - 4 ) * 2 ); - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); } this.reverse = !this.reverse; } - else { - if (!this.reverse) { + else + { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } - else { + 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) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); } } @@ -103,7 +116,8 @@ * @param graphics {Graphics} * @param webGLData {Array} */ -WebGLStencilManager.prototype.bindGraphics = function (graphics, webGLData) { +WebGLStencilManager.prototype.bindGraphics = function (graphics, webGLData) +{ //if (this._currentGraphics === graphics)return; this._currentGraphics = graphics; @@ -114,7 +128,8 @@ offset = this.renderer.offset, shader;// = this.renderer.shaderManager.primitiveShader; - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { shader = this.renderer.shaderManager.complexPrimitiveShader; this.renderer.shaderManager.setShader(shader); @@ -141,7 +156,8 @@ // set the index buffer! gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, webGLData.indexBuffer); } - else { + else + { //this.renderer.shaderManager.activatePrimitiveShader(); shader = this.renderer.shaderManager.primitiveShader; this.renderer.shaderManager.setShader( shader ); @@ -154,7 +170,7 @@ gl.uniform2f(shader.uniforms.offsetVector._location, -offset.x, -offset.y); gl.uniform3fv(shader.uniforms.tint._location, utils.hex2rgb(graphics.tint)); - + gl.uniform1f(shader.uniforms.alpha._location, graphics.worldAlpha); @@ -172,19 +188,22 @@ * @param graphics {Graphics} * @param webGLData {Array} */ -WebGLStencilManager.prototype.popStencil = function (graphics, webGLData) { +WebGLStencilManager.prototype.popStencil = function (graphics, webGLData) +{ var gl = this.renderer.gl; this.stencilStack.pop(); this.count--; - if (this.stencilStack.length === 0) { + if (this.stencilStack.length === 0) + { // the stack is empty! gl.disable(gl.STENCIL_TEST); } - else { + else + { var level = this.count; @@ -192,14 +211,17 @@ gl.colorMask(false, false, false, false); - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { this.reverse = !this.reverse; - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } @@ -213,31 +235,38 @@ // draw the triangle strip! gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); - if (!this.reverse) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); } } - else { + else + { // console.log("<<>>") - if (!this.reverse) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } - else { + 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) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); } } @@ -253,7 +282,8 @@ * Destroys the mask stack. * */ -WebGLStencilManager.prototype.destroy = function () { +WebGLStencilManager.prototype.destroy = function () +{ this.renderer = null; this.stencilStack = null; }; diff --git a/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js b/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js index 913ba5e..1ea7d19 100644 --- a/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js +++ b/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function ComplexPrimitiveShader(gl) { +function ComplexPrimitiveShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -24,7 +25,8 @@ 'uniform float flipY;', 'varying vec4 vColor;', - 'void main(void) {', + '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);', @@ -37,7 +39,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = vColor;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/FastShader.js b/src/core/renderers/webgl/shaders/FastShader.js index bd2e29a..2e5e060 100644 --- a/src/core/renderers/webgl/shaders/FastShader.js +++ b/src/core/renderers/webgl/shaders/FastShader.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function FastShader(gl) { +function FastShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -28,7 +29,8 @@ 'const vec2 center = vec2(-1.0, 1.0);', - 'void main(void) {', + 'void main(void) + {', ' vec2 v;', ' vec2 sv = aVertexPosition * aScale;', ' v.x = (sv.x) * cos(aRotation) - (sv.y) * sin(aRotation);', @@ -49,7 +51,8 @@ 'uniform sampler2D uSampler;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/PrimitiveShader.js b/src/core/renderers/webgl/shaders/PrimitiveShader.js index 6f25409..a25f54f 100644 --- a/src/core/renderers/webgl/shaders/PrimitiveShader.js +++ b/src/core/renderers/webgl/shaders/PrimitiveShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function PrimitiveShader(gl) { +function PrimitiveShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -23,7 +24,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + '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);', @@ -36,7 +38,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = vColor;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/Shader.js b/src/core/renderers/webgl/shaders/Shader.js index f8964f5..fd75ef5 100644 --- a/src/core/renderers/webgl/shaders/Shader.js +++ b/src/core/renderers/webgl/shaders/Shader.js @@ -6,7 +6,8 @@ * @param [fragmentSrc] {string} The source of the fragment shader. * @param [vertexSrc] {string} The source of the vertex shader. */ -function Shader(gl, vertexSrc, fragmentSrc, customUniforms, customAttributes) { +function Shader(gl, vertexSrc, fragmentSrc, customUniforms, customAttributes) +{ /** * @member {number} * @readonly @@ -33,7 +34,8 @@ dimensions: { type: '4f', value: new Float32Array(4) } }; - for (var u in customUniforms) { + for (var u in customUniforms) + { this.uniforms[u] = customUniforms[u]; } @@ -43,7 +45,8 @@ aColor: 0 }; - for (var a in customAttributes) { + for (var a in customAttributes) + { this.attributes[a] = customAttributes[a]; } @@ -66,7 +69,8 @@ 'const vec2 center = vec2(-1.0, 1.0);', - 'void main(void) {', + 'void main(void) + {', ' gl_Position = vec4( ((aVertexPosition + offsetVector) / projectionVector) + center , 0.0, 1.0);', ' vTextureCoord = aTextureCoord;', ' vColor = vec4(aColor.rgb * aColor.a, aColor.a);', @@ -85,7 +89,8 @@ 'uniform sampler2D uSampler;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;', '}' ].join('\n'); @@ -96,7 +101,8 @@ Shader.prototype.constructor = Shader; module.exports = Shader; -Shader.prototype.init = function () { +Shader.prototype.init = function () +{ this.compile(); this.gl.useProgram(this.program); @@ -105,14 +111,18 @@ this.cacheAttributeLocations(Object.keys(this.attributes)); }; -Shader.prototype.cacheUniformLocations = function (keys) { - for (var i = 0; i < keys.length; ++i) { +Shader.prototype.cacheUniformLocations = function (keys) +{ + for (var i = 0; i < keys.length; ++i) + { this.uniforms[keys[i]]._location = this.gl.getUniformLocation(this.program, keys[i]); } }; -Shader.prototype.cacheAttributeLocations = function (keys) { - for (var i = 0; i < keys.length; ++i) { +Shader.prototype.cacheAttributeLocations = function (keys) +{ + for (var i = 0; i < keys.length; ++i) + { this.attributes[keys[i]] = this.gl.getAttribLocation(this.program, keys[i]); } @@ -124,14 +134,16 @@ // 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.attributes.aColor === -1) { + // if (this.attributes.aColor === -1) + { // this.attributes.aColor = 2; // } // End worst hack eva // }; -Shader.prototype.compile = function () { +Shader.prototype.compile = function () +{ var gl = this.gl; var glVertShader = this._glCompile(gl.VERTEX_SHADER, this.vertexSrc); @@ -144,13 +156,15 @@ gl.linkProgram(program); // if linking fails, then log and cleanup - if (!gl.getProgramParameter(program, gl.LINK_STATUS)) { + if (!gl.getProgramParameter(program, gl.LINK_STATUS)) + { window.console.error('Pixi.js Error: Could not initialize shader.'); window.console.error('gl.VALIDATE_STATUS', gl.getProgramParameter(program, gl.VALIDATE_STATUS)); window.console.error('gl.getError()', gl.getError()); // if there is a program info log, log it - if (gl.getProgramInfoLog(program) !== '') { + if (gl.getProgramInfoLog(program) !== '') + { window.console.warn('Pixi.js Warning: gl.getProgramInfoLog()', gl.getProgramInfoLog(program)); } @@ -165,18 +179,21 @@ return (this.program = program); }; -Shader.prototype.syncUniforms = function () { +Shader.prototype.syncUniforms = function () +{ var gl = this.gl; this.textureCount = 1; - for (var key in this.uniforms) { + for (var key in this.uniforms) + { var uniform = this.uniforms[key], location = uniform._location, value = uniform.value, i, il; - switch (uniform.type) { + switch (uniform.type) + { // single int value case 'i': case '1i': @@ -282,7 +299,8 @@ // a Color Value case 'c': - if (typeof value === 'number') { + if (typeof value === 'number') + { value = utils.hex2rgb(value); } @@ -311,11 +329,13 @@ // array of 2D Point objects case 'v2v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(2 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 2] = value[i].x; uniform._array[i * 2 + 1] = value[i].y; } @@ -325,11 +345,13 @@ // array of 3D Point objects case 'v3v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(3 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 3] = value[i].x; uniform._array[i * 3 + 1] = value[i].y; uniform._array[i * 3 + 2] = value[i].z; @@ -341,11 +363,13 @@ // array of 4D Point objects case 'v4v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(4 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 4] = value[i].x; uniform._array[i * 4 + 1] = value[i].y; uniform._array[i * 4 + 2] = value[i].z; @@ -359,7 +383,8 @@ // PIXI.Texture case 't': case 'sampler2D': - if (!uniform.value || !uniform.value.baseTexture || !uniform.value.baseTexture.hasLoaded) { + if (!uniform.value || !uniform.value.baseTexture || !uniform.value.baseTexture.hasLoaded) + { break; } @@ -376,7 +401,8 @@ this.textureCount++; // initialize the texture if we haven't yet - if (!uniform._init) { + if (!uniform._init) + { this.initSampler2D(uniform); uniform._init = true; @@ -394,11 +420,13 @@ * Initialises a Sampler2D uniform (which may only be available later on after initUniforms once the texture has loaded) * */ -Shader.prototype.initSampler2D = function (uniform) { +Shader.prototype.initSampler2D = function (uniform) +{ var gl = this.gl; // Extended texture data - if (uniform.textureData) { + if (uniform.textureData) + { var data = uniform.textureData; // GLTexture = mag linear, min linear_mipmap_linear, wrap repeat + gl.generateMipmap(gl.TEXTURE_2D); @@ -417,14 +445,16 @@ var wrapT = (data.wrapT) ? data.wrapT : gl.CLAMP_TO_EDGE; var format = (data.luminance) ? gl.LUMINANCE : gl.RGBA; - if (data.repeat) { + if (data.repeat) + { wrapS = gl.REPEAT; wrapT = gl.REPEAT; } gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, !!data.flipY); - if (data.width) { + if (data.width) + { var width = (data.width) ? data.width : 512; var height = (data.height) ? data.height : 2; var border = (data.border) ? data.border : 0; @@ -432,7 +462,8 @@ // 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 { + 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); } @@ -448,7 +479,8 @@ * Destroys the shader. * */ -Shader.prototype.destroy = function () { +Shader.prototype.destroy = function () +{ this.gl.deleteProgram(this.program); this.gl = null; @@ -459,13 +491,15 @@ this.fragmentSrc = null; }; -Shader.prototype._glCompile = function (type, src) { +Shader.prototype._glCompile = function (type, src) +{ var shader = this.gl.createShader(type); this.gl.shaderSource(shader, src); this.gl.compileShader(shader); - if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) { + if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) + { window.console.log(this.gl.getShaderInfoLog(shader)); return null; } diff --git a/src/core/renderers/webgl/shaders/StripShader.js b/src/core/renderers/webgl/shaders/StripShader.js index 193f6e1..a7abcc6 100644 --- a/src/core/renderers/webgl/shaders/StripShader.js +++ b/src/core/renderers/webgl/shaders/StripShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function StripShader(gl) { +function StripShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -20,7 +21,8 @@ 'varying vec2 vTextureCoord;', - 'void main(void) {', + '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);', @@ -36,7 +38,8 @@ 'varying vec2 vTextureCoord;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vec2(vTextureCoord.x, vTextureCoord.y)) * alpha;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/utils/FilterTexture.js b/src/core/renderers/webgl/utils/FilterTexture.js index d2c8423..4433d44 100644 --- a/src/core/renderers/webgl/utils/FilterTexture.js +++ b/src/core/renderers/webgl/utils/FilterTexture.js @@ -8,7 +8,8 @@ * @param height {number} the vertical range of the filter * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values */ -function FilterTexture(gl, width, height, scaleMode) { +function FilterTexture(gl, width, height, scaleMode) +{ /** * @member {WebGLContext} */ @@ -59,7 +60,8 @@ * Clears the filter texture. * */ -FilterTexture.prototype.clear = function () { +FilterTexture.prototype.clear = function () +{ var gl = this.gl; gl.clearColor(0,0,0, 0); @@ -72,8 +74,10 @@ * @param width {number} the new width of the texture * @param height {number} the new height of the texture */ -FilterTexture.prototype.resize = function (width, height) { - if (this.width === width && this.height === height) { +FilterTexture.prototype.resize = function (width, height) +{ + if (this.width === width && this.height === height) + { return; } @@ -96,7 +100,8 @@ * Destroys the filter texture. * */ -FilterTexture.prototype.destroy = function () { +FilterTexture.prototype.destroy = function () +{ var gl = this.gl; gl.deleteFramebuffer( this.frameBuffer ); gl.deleteTexture( this.texture ); diff --git a/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js b/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js index c4721e9..a63f4d7 100644 --- a/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js +++ b/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js @@ -14,7 +14,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this sprite batch works for. */ -function WebGLFastSpriteBatch(renderer) { +function WebGLFastSpriteBatch(renderer) +{ /** * The renderer instance this sprite batch operates on. * @@ -91,7 +92,8 @@ */ this.lastIndexCount = 0; - for (var i=0, j=0; i < numIndices; i += 6, j += 4) { + 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; @@ -144,7 +146,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.setupContext(); }); } @@ -157,7 +160,8 @@ * * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLFastSpriteBatch.prototype.setupContext = function () { +WebGLFastSpriteBatch.prototype.setupContext = function () +{ var gl = this.renderer.gl; // create a couple of buffers @@ -177,7 +181,8 @@ /** * @param spriteBatch {SpriteBatch} The SpriteBatch container to prepare for. */ -WebGLFastSpriteBatch.prototype.begin = function (spriteBatch) { +WebGLFastSpriteBatch.prototype.begin = function (spriteBatch) +{ this.shader = this.renderer.shaderManager.fastShader; this.matrix = spriteBatch.worldTransform.toArray(true); @@ -187,33 +192,38 @@ /** */ -WebGLFastSpriteBatch.prototype.end = function () { +WebGLFastSpriteBatch.prototype.end = function () +{ this.flush(); }; /** * @param spriteBatch {SpriteBatch} The SpriteBatch container to render. */ -WebGLFastSpriteBatch.prototype.render = function (spriteBatch) { +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) { + if (!sprite.texture._uvs) + { return; } this.currentBaseTexture = sprite.texture.baseTexture; // check blend mode - if (sprite.blendMode !== this.renderer.blendModeManager.currentBlendMode) { + if (sprite.blendMode !== this.renderer.blendModeManager.currentBlendMode) + { this.flush(); this.renderer.blendModeManager.setBlendMode(sprite.blendMode); } - for (var i=0,j= children.length; i= this.size) { + if (this.currentBatchSize >= this.size) + { this.flush(); } }; @@ -362,29 +379,35 @@ /** * */ -WebGLFastSpriteBatch.prototype.flush = function () { +WebGLFastSpriteBatch.prototype.flush = function () +{ // If the batch is length 0 then return as there is nothing to draw - if (this.currentBatchSize === 0) { + if (this.currentBatchSize === 0) + { return; } var gl = this.renderer.gl; // bind the current texture - if (!this.currentBaseTexture._glTextures[gl.id]) { + if (!this.currentBaseTexture._glTextures[gl.id]) + { this.renderer.updateTexture(this.currentBaseTexture, gl); } //TODO-SHOUD THIS BE ELSE??!?!?! - else { + else + { gl.bindTexture(gl.TEXTURE_2D, this.currentBaseTexture._glTextures[gl.id]); } // upload the verts to the buffer - if (this.currentBatchSize > ( this.size * 0.5 ) ) { + if (this.currentBatchSize > ( this.size * 0.5 ) ) + { gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); } - else { + else + { var view = this.vertices.subarray(0, this.currentBatchSize * this.vertByteSize); gl.bufferSubData(gl.ARRAY_BUFFER, 0, view); @@ -405,14 +428,16 @@ * Ends the batch and flushes * */ -WebGLFastSpriteBatch.prototype.stop = function () { +WebGLFastSpriteBatch.prototype.stop = function () +{ this.flush(); }; /** * */ -WebGLFastSpriteBatch.prototype.start = function () { +WebGLFastSpriteBatch.prototype.start = function () +{ var gl = this.renderer.gl; // bind the main texture diff --git a/src/core/renderers/webgl/utils/WebGLGraphics.js b/src/core/renderers/webgl/utils/WebGLGraphics.js index 55f4911..ab8f46e 100644 --- a/src/core/renderers/webgl/utils/WebGLGraphics.js +++ b/src/core/renderers/webgl/utils/WebGLGraphics.js @@ -19,7 +19,8 @@ * @param graphics {Graphics} * @param renderer {WebGLRenderer} */ -WebGLGraphics.renderGraphics = function (graphics, renderer) {//projection, offset) { +WebGLGraphics.renderGraphics = function (graphics, renderer) {//projection, offset) +{ var gl = renderer.gl; var projection = renderer.projection, @@ -27,7 +28,8 @@ shader = renderer.shaderManager.primitiveShader, webGLData; - if (graphics.dirty) { + if (graphics.dirty) + { WebGLGraphics.updateGraphics(graphics, gl); } @@ -35,8 +37,10 @@ // This could be speeded up for sure! - for (var i = 0; i < webGL.data.length; i++) { - if (webGL.data[i].mode === 1) { + for (var i = 0; i < webGL.data.length; i++) + { + if (webGL.data[i].mode === 1) + { webGLData = webGL.data[i]; renderer.stencilManager.pushStencil(graphics, webGLData, renderer); @@ -46,7 +50,8 @@ renderer.stencilManager.popStencil(graphics, webGLData, renderer); } - else { + else + { webGLData = webGL.data[i]; @@ -84,12 +89,14 @@ * @param graphicsData {Graphics} The graphics object to update * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLGraphics.updateGraphics = function (graphics, gl) { +WebGLGraphics.updateGraphics = function (graphics, gl) +{ // get the contexts graphics object var webGL = graphics._webGL[gl.id]; // if the graphics object does not exist in the webGL context time to create it! - if (!webGL) { + if (!webGL) + { webGL = graphics._webGL[gl.id] = {lastIndex:0, data:[], gl:gl}; } @@ -99,11 +106,13 @@ var i; // if the user cleared the graphics object we will need to clear every object - if (graphics.clearDirty) { + if (graphics.clearDirty) + { graphics.clearDirty = false; // lop through and return all the webGLDatas to the object pool so than can be reused later on - for (i = 0; i < webGL.data.length; i++) { + for (i = 0; i < webGL.data.length; i++) + { var graphicsData = webGL.data[i]; graphicsData.reset(); WebGLGraphics.graphicsDataPool.push( graphicsData ); @@ -119,58 +128,72 @@ // loop through the graphics datas and construct each one.. // if the object is a complex fill then the new stencil buffer technique will be used // other wise graphics objects will be pushed into a batch.. - for (i = webGL.lastIndex; i < graphics.graphicsData.length; i++) { + for (i = webGL.lastIndex; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { // need to add the points the the graphics object.. data.points = data.shape.points.slice(); - if (data.shape.closed) { + if (data.shape.closed) + { // close the poly if the value is true! - if (data.points[0] !== data.points[data.points.length-2] || data.points[1] !== data.points[data.points.length-1]) { + if (data.points[0] !== data.points[data.points.length-2] || data.points[1] !== data.points[data.points.length-1]) + { data.points.push(data.points[0], data.points[1]); } } // MAKE SURE WE HAVE THE CORRECT TYPE.. - if (data.fill) { - if (data.points.length >= 6) { - if (data.points.length < 6 * 2) { + if (data.fill) + { + if (data.points.length >= 6) + { + if (data.points.length < 6 * 2) + { webGLData = WebGLGraphics.switchMode(webGL, 0); var canDrawUsingSimple = WebGLGraphics.buildPoly(data, webGLData); // console.log(canDrawUsingSimple); - if (!canDrawUsingSimple) { + if (!canDrawUsingSimple) + { // console.log("<>>>") webGLData = WebGLGraphics.switchMode(webGL, 1); WebGLGraphics.buildComplexPoly(data, webGLData); } } - else { + else + { webGLData = WebGLGraphics.switchMode(webGL, 1); WebGLGraphics.buildComplexPoly(data, webGLData); } } } - if (data.lineWidth > 0) { + if (data.lineWidth > 0) + { webGLData = WebGLGraphics.switchMode(webGL, 0); WebGLGraphics.buildLine(data, webGLData); } } - else { + else + { webGLData = WebGLGraphics.switchMode(webGL, 0); - if (data.type === CONST.SHAPES.RECT) { + if (data.type === CONST.SHAPES.RECT) + { WebGLGraphics.buildRectangle(data, webGLData); } - else if (data.type === CONST.SHAPES.CIRC || data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.CIRC || data.type === CONST.SHAPES.ELIP) + { WebGLGraphics.buildCircle(data, webGLData); } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { WebGLGraphics.buildRoundedRectangle(data, webGLData); } } @@ -179,10 +202,12 @@ } // upload all the dirty data... - for (i = 0; i < webGL.data.length; i++) { + for (i = 0; i < webGL.data.length; i++) + { webGLData = webGL.data[i]; - if (webGLData.dirty) { + if (webGLData.dirty) + { webGLData.upload(); } } @@ -194,18 +219,22 @@ * @param webGL {WebGLContext} * @param type {number} */ -WebGLGraphics.switchMode = function (webGL, type) { +WebGLGraphics.switchMode = function (webGL, type) +{ var webGLData; - if (!webGL.data.length) { + if (!webGL.data.length) + { webGLData = WebGLGraphics.graphicsDataPool.pop() || new WebGLGraphicsData(webGL.gl); webGLData.mode = type; webGL.data.push(webGLData); } - else { + else + { webGLData = webGL.data[webGL.data.length-1]; - if (webGLData.mode !== type || type === 1) { + if (webGLData.mode !== type || type === 1) + { webGLData = WebGLGraphics.graphicsDataPool.pop() || new WebGLGraphicsData(webGL.gl); webGLData.mode = type; webGL.data.push(webGLData); @@ -225,7 +254,8 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildRectangle = function (graphicsData, webGLData) { +WebGLGraphics.buildRectangle = function (graphicsData, webGLData) +{ // --- // // need to convert points to a nice regular data // @@ -235,7 +265,8 @@ var width = rectData.width; var height = rectData.height; - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -265,7 +296,8 @@ indices.push(vertPos, vertPos, vertPos+1, vertPos+2, vertPos+3, vertPos+3); } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = [x, y, @@ -289,7 +321,8 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildRoundedRectangle = function (graphicsData, webGLData) { +WebGLGraphics.buildRoundedRectangle = function (graphicsData, webGLData) +{ var rrectData = graphicsData.shape; var x = rrectData.x; var y = rrectData.y; @@ -305,7 +338,8 @@ recPoints = recPoints.concat(WebGLGraphics.quadraticBezierCurve(x + width, y + radius, x + width, y, x + width - radius, y)); recPoints = recPoints.concat(WebGLGraphics.quadraticBezierCurve(x + radius, y, x, y, x, y + radius)); - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -323,7 +357,8 @@ // var i = 0; - for (i = 0; i < triangles.length; i+=3) { + for (i = 0; i < triangles.length; i+=3) + { indices.push(triangles[i] + vecPos); indices.push(triangles[i] + vecPos); indices.push(triangles[i+1] + vecPos); @@ -332,12 +367,14 @@ } - for (i = 0; i < recPoints.length; i++) { + for (i = 0; i < recPoints.length; i++) + { verts.push(recPoints[i], recPoints[++i], r, g, b, alpha); } } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = recPoints; @@ -362,7 +399,8 @@ * @param toY {number} Destination point y * @return {number[]} */ -WebGLGraphics.quadraticBezierCurve = function (fromX, fromY, cpX, cpY, toX, toY) { +WebGLGraphics.quadraticBezierCurve = function (fromX, fromY, cpX, cpY, toX, toY) +{ var xa, ya, @@ -373,14 +411,16 @@ n = 20, points = []; - function getPt(n1 , n2, perc) { + function getPt(n1 , n2, perc) + { var diff = n2 - n1; return n1 + ( diff * perc ); } var j = 0; - for (var i = 0; i <= n; i++ ) { + for (var i = 0; i <= n; i++ ) + { j = i / n; // The Green Line @@ -406,7 +446,8 @@ * @param graphicsData {Graphics} The graphics object to draw * @param webGLData {object} */ -WebGLGraphics.buildCircle = function (graphicsData, webGLData) { +WebGLGraphics.buildCircle = function (graphicsData, webGLData) +{ // need to convert points to a nice regular data var circleData = graphicsData.shape; var x = circleData.x; @@ -415,11 +456,13 @@ var height; // TODO - bit hacky?? - if (graphicsData.type === CONST.SHAPES.CIRC) { + if (graphicsData.type === CONST.SHAPES.CIRC) + { width = circleData.radius; height = circleData.radius; } - else { + else + { width = circleData.width; height = circleData.height; } @@ -429,7 +472,8 @@ var i = 0; - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -444,7 +488,8 @@ indices.push(vecPos); - for (i = 0; i < totalSegs + 1 ; i++) { + for (i = 0; i < totalSegs + 1 ; i++) + { verts.push(x,y, r, g, b, alpha); verts.push(x + Math.sin(seg * i) * width, @@ -457,12 +502,14 @@ indices.push(vecPos-1); } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = []; - for (i = 0; i < totalSegs + 1; i++) { + for (i = 0; i < totalSegs + 1; i++) + { graphicsData.points.push(x + Math.sin(seg * i) * width, y + Math.cos(seg * i) * height); } @@ -481,18 +528,22 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildLine = function (graphicsData, webGLData) { +WebGLGraphics.buildLine = function (graphicsData, webGLData) +{ // TODO OPTIMISE! var i = 0; var points = graphicsData.points; - if (points.length === 0) { + if (points.length === 0) + { return; } // if the line width is an odd number add 0.5 to align to a whole pixel - if (graphicsData.lineWidth%2) { - for (i = 0; i < points.length; i++) { + if (graphicsData.lineWidth%2) + { + for (i = 0; i < points.length; i++) + { points[i] += 0.5; } } @@ -502,7 +553,8 @@ var lastPoint = new math.Point(points[points.length - 2], points[points.length - 1]); // if the first point is the last point - gonna have issues :) - if (firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) { + if (firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) + { // need to clone as we are going to slightly modify the shape.. points = points.slice(); @@ -562,7 +614,8 @@ verts.push(p1x + perpx , p1y + perpy, r, g, b, alpha); - for (i = 1; i < length-1; i++) { + for (i = 1; i < length-1; i++) + { p1x = points[(i-1)*2]; p1y = points[(i-1)*2 + 1]; @@ -599,7 +652,8 @@ denom = a1*b2 - a2*b1; - if (Math.abs(denom) < 0.1 ) { + if (Math.abs(denom) < 0.1 ) + { denom+=10.1; verts.push(p2x - perpx , p2y - perpy, @@ -618,7 +672,8 @@ pdist = (px -p2x) * (px -p2x) + (py -p2y) + (py -p2y); - if (pdist > 140 * 140) { + if (pdist > 140 * 140) + { perp3x = perpx - perp2x; perp3y = perpy - perp2y; @@ -639,7 +694,8 @@ indexCount++; } - else { + else + { verts.push(px , py); verts.push(r, g, b, alpha); @@ -672,7 +728,8 @@ indices.push(indexStart); - for (i = 0; i < indexCount; i++) { + for (i = 0; i < indexCount; i++) + { indices.push(indexStart++); } @@ -687,11 +744,13 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildComplexPoly = function (graphicsData, webGLData) { +WebGLGraphics.buildComplexPoly = function (graphicsData, webGLData) +{ //TODO - no need to copy this as it gets turned into a FLoat32Array anyways.. var points = graphicsData.points.slice(); - if (points.length < 6) { + if (points.length < 6) + { return; } @@ -711,7 +770,8 @@ var x,y; // get size.. - for (var i = 0; i < points.length; i+=2) { + for (var i = 0; i < points.length; i+=2) + { x = points[i]; y = points[i+1]; @@ -732,7 +792,8 @@ //TODO - this aint needed! var length = points.length / 2; - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { indices.push( i ); } @@ -746,10 +807,12 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildPoly = function (graphicsData, webGLData) { +WebGLGraphics.buildPoly = function (graphicsData, webGLData) +{ var points = graphicsData.points; - if (points.length < 6) { + if (points.length < 6) + { return; } // get first and last point.. figure out the middle! @@ -767,7 +830,8 @@ var triangles = utils.PolyK.Triangulate(points); - if (!triangles) { + if (!triangles) + { return false; } @@ -775,7 +839,8 @@ var i = 0; - for (i = 0; i < triangles.length; i+=3) { + for (i = 0; i < triangles.length; i+=3) + { indices.push(triangles[i] + vertPos); indices.push(triangles[i] + vertPos); indices.push(triangles[i+1] + vertPos); @@ -783,7 +848,8 @@ indices.push(triangles[i+2] + vertPos); } - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { verts.push(points[i * 2], points[i * 2 + 1], r, g, b, alpha); } diff --git a/src/core/renderers/webgl/utils/WebGLGraphicsData.js b/src/core/renderers/webgl/utils/WebGLGraphicsData.js index c56d05e..c739ba7 100644 --- a/src/core/renderers/webgl/utils/WebGLGraphicsData.js +++ b/src/core/renderers/webgl/utils/WebGLGraphicsData.js @@ -2,7 +2,8 @@ * @class * @private */ -function WebGLGraphicsData(gl) { +function WebGLGraphicsData(gl) +{ this.gl = gl; //TODO does this need to be split before uploding?? @@ -22,7 +23,8 @@ /** * */ -WebGLGraphicsData.prototype.reset = function () { +WebGLGraphicsData.prototype.reset = function () +{ this.points.length = 0; this.indices.length = 0; }; @@ -30,7 +32,8 @@ /** * */ -WebGLGraphicsData.prototype.upload = function () { +WebGLGraphicsData.prototype.upload = function () +{ var gl = this.gl; // this.lastIndex = graphics.graphicsData.length; diff --git a/src/core/renderers/webgl/utils/WebGLSpriteBatch.js b/src/core/renderers/webgl/utils/WebGLSpriteBatch.js index 96eaa52..55befbb 100644 --- a/src/core/renderers/webgl/utils/WebGLSpriteBatch.js +++ b/src/core/renderers/webgl/utils/WebGLSpriteBatch.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this sprite batch works for. */ -function WebGLSpriteBatch(renderer) { +function WebGLSpriteBatch(renderer) +{ /** * * @@ -88,7 +89,8 @@ */ this.lastIndexCount = 0; - for (var i=0, j=0; i < numIndices; i += 6, j += 4) { + 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; @@ -162,7 +164,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.setupContext(); }); } @@ -173,7 +176,8 @@ /** * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLSpriteBatch.prototype.setupContext = function () { +WebGLSpriteBatch.prototype.setupContext = function () +{ var gl = this.renderer.gl; // setup default shader @@ -198,7 +202,8 @@ /** * */ -WebGLSpriteBatch.prototype.begin = function () { +WebGLSpriteBatch.prototype.begin = function () +{ // this.shader = this.renderer.shaderManager.defaultShader; this.start(); @@ -206,19 +211,22 @@ /** */ -WebGLSpriteBatch.prototype.end = function () { +WebGLSpriteBatch.prototype.end = function () +{ this.flush(); }; /** * @param sprite {Sprite} the sprite to render when using this spritebatch */ -WebGLSpriteBatch.prototype.render = function (sprite) { +WebGLSpriteBatch.prototype.render = function (sprite) +{ var texture = sprite.texture; //TODO set blend modes.. // check texture.. - if (this.currentBatchSize >= this.size) { + if (this.currentBatchSize >= this.size) + { this.flush(); this.currentBaseTexture = texture.baseTexture; } @@ -227,7 +235,8 @@ var uvs = texture._uvs; // if the uvs have not updated then no point rendering just yet! - if (!uvs) { + if (!uvs) + { return; } @@ -237,7 +246,8 @@ var w0, w1, h0, h1; - if (texture.trim) { + 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; @@ -248,7 +258,8 @@ h0 = h1 + texture.crop.height; } - else { + else + { w0 = (texture.frame.width ) * (1-aX); w1 = (texture.frame.width ) * -aX; @@ -272,7 +283,8 @@ var colors = this.colors; var positions = this.positions; - if (this.renderer.roundPixels) { + if (this.renderer.roundPixels) + { // xy positions[index] = a * w1 + c * h1 + tx | 0; positions[index+1] = d * h1 + b * w1 + ty | 0; @@ -289,7 +301,8 @@ positions[index+15] = a * w1 + c * h0 + tx | 0; positions[index+16] = d * h0 + b * w1 + ty | 0; } - else { + else + { // xy positions[index] = a * w1 + c * h1 + tx; positions[index+1] = d * h1 + b * w1 + ty; @@ -338,11 +351,13 @@ * * @param sprite {TilingSprite} the tilingSprite to render */ -WebGLSpriteBatch.prototype.renderTilingSprite = function (tilingSprite) { +WebGLSpriteBatch.prototype.renderTilingSprite = function (tilingSprite) +{ var texture = tilingSprite.tilingTexture; // check texture.. - if (this.currentBatchSize >= this.size) { + if (this.currentBatchSize >= this.size) + { //return; this.flush(); this.currentBaseTexture = texture.baseTexture; @@ -351,7 +366,8 @@ // set the textures uvs temporarily // TODO create a separate texture so that we can tile part of a texture - if (!tilingSprite._uvs) { + if (!tilingSprite._uvs) + { tilingSprite._uvs = new TextureUvs(); } @@ -454,16 +470,19 @@ * Renders the content and empties the current batch. * */ -WebGLSpriteBatch.prototype.flush = function () { +WebGLSpriteBatch.prototype.flush = function () +{ // If the batch is length 0 then return as there is nothing to draw - if (this.currentBatchSize === 0) { + if (this.currentBatchSize === 0) + { return; } var gl = this.renderer.gl; var shader; - if (this.dirty) { + if (this.dirty) + { this.dirty = false; // bind the main texture gl.activeTexture(gl.TEXTURE0); @@ -482,10 +501,12 @@ } // upload the verts to the buffer - if (this.currentBatchSize > ( this.size * 0.5 ) ) { + if (this.currentBatchSize > ( this.size * 0.5 ) ) + { gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); } - else { + else + { var view = this.positions.subarray(0, this.currentBatchSize * this.vertByteSize); gl.bufferSubData(gl.ARRAY_BUFFER, 0, view); } @@ -502,7 +523,8 @@ var shaderSwap = false; var sprite; - for (var i = 0, j = this.currentBatchSize; i < j; i++) { + for (var i = 0, j = this.currentBatchSize; i < j; i++) + { sprite = this.sprites[i]; @@ -513,24 +535,28 @@ blendSwap = currentBlendMode !== nextBlendMode; shaderSwap = currentShader !== nextShader; // should I use uuidS??? - if (currentBaseTexture !== nextTexture || blendSwap || shaderSwap) { + if (currentBaseTexture !== nextTexture || blendSwap || shaderSwap) + { this.renderBatch(currentBaseTexture, batchSize, start); start = i; batchSize = 0; currentBaseTexture = nextTexture; - if (blendSwap) { + if (blendSwap) + { currentBlendMode = nextBlendMode; this.renderer.blendModeManager.setBlendMode( currentBlendMode ); } - if (shaderSwap) { + if (shaderSwap) + { currentShader = nextShader; shader = currentShader.shaders ? currentShader.shaders[gl.id] : currentShader; - if (!shader) { + if (!shader) + { shader = new Shader(gl, null, currentShader.fragmentSrc, currentShader.uniforms); currentShader.shaders[gl.id] = shader; } @@ -538,7 +564,8 @@ // set shader function??? this.renderer.shaderManager.setShader(shader); - if (shader.dirty) { + if (shader.dirty) + { shader.syncUniforms(); } @@ -569,17 +596,21 @@ * @param size {number} * @param startIndex {number} */ -WebGLSpriteBatch.prototype.renderBatch = function (texture, size, startIndex) { - if (size === 0) { +WebGLSpriteBatch.prototype.renderBatch = function (texture, size, startIndex) +{ + if (size === 0) + { return; } var gl = this.renderer.gl; - if (!texture._glTextures[gl.id]) { + if (!texture._glTextures[gl.id]) + { this.renderer.updateTexture(texture); } - else { + else + { // bind the current texture gl.bindTexture(gl.TEXTURE_2D, texture._glTextures[gl.id]); } @@ -594,7 +625,8 @@ /** * */ -WebGLSpriteBatch.prototype.stop = function () { +WebGLSpriteBatch.prototype.stop = function () +{ this.flush(); this.dirty = true; }; @@ -602,7 +634,8 @@ /** * */ -WebGLSpriteBatch.prototype.start = function () { +WebGLSpriteBatch.prototype.start = function () +{ this.dirty = true; }; @@ -610,7 +643,8 @@ * Destroys the SpriteBatch. * */ -WebGLSpriteBatch.prototype.destroy = function () { +WebGLSpriteBatch.prototype.destroy = function () +{ this.renderer.gl.deleteBuffer(this.vertexBuffer); this.renderer.gl.deleteBuffer(this.indexBuffer); diff --git a/src/core/textures/BaseTexture.js b/src/core/textures/BaseTexture.js index 2bf77d4..513d358 100644 --- a/src/core/textures/BaseTexture.js +++ b/src/core/textures/BaseTexture.js @@ -10,7 +10,8 @@ * @param source {Image|Canvas} the source object of the texture. * @param [scaleMode=scaleModes.DEFAULT] {number} See {@link scaleModes} for possible values */ -function BaseTexture(source, scaleMode) { +function BaseTexture(source, scaleMode) +{ this.uuid = utils.uuid(); /** @@ -123,7 +124,8 @@ this._needsUpdate = false; // if no source passed don't try to load - if (source) { + if (source) + { this.loadSource(source); } @@ -149,13 +151,16 @@ Object.defineProperties(BaseTexture.prototype, { needsUpdate: { - get: function () { + get: function () + { return this._needsUpdate; }, - set: function (val) { + set: function (val) + { this._needsUpdate = val; - if (val) { + if (val) + { this.emit('update', this); } } @@ -171,9 +176,11 @@ * * The logic state after calling `loadSource` directly or indirectly (eg. `fromImage`, `new BaseTexture`) is: * - * if (texture.hasLoaded) { + * if (texture.hasLoaded) + { * // texture ready for use - * } else if (texture.isLoading) { + * } else if (texture.isLoading) + { * // listen to 'loaded' and/or 'error' events on texture * } else { * // not loading, not going to load UNLESS the source is reloaded @@ -183,12 +190,14 @@ * @protected * @param source {Image|Canvas} the source object of the texture. */ -BaseTexture.prototype.loadSource = function (source) { +BaseTexture.prototype.loadSource = function (source) +{ var wasLoading = this.isLoading; this.hasLoaded = false; this.isLoading = false; - if (wasLoading && this.source) { + if (wasLoading && this.source) + { this.source.onload = null; this.source.onerror = null; } @@ -196,20 +205,24 @@ this.source = source; // Apply source if loaded. Otherwise setup appropriate loading monitors. - if ((this.source.complete || this.source.getContext) && this.source.width && this.source.height) { + if ((this.source.complete || this.source.getContext) && this.source.width && this.source.height) + { this._sourceLoaded(); } - else if(!source.getContext) { + else if(!source.getContext) + { // Image fail / not ready this.isLoading = true; var scope = this; - source.onload = function () { + source.onload = function () + { source.onload = null; source.onerror = null; - if(!scope.isLoading) { + if(!scope.isLoading) + { return; } @@ -219,11 +232,13 @@ scope.emit('loaded', scope); }; - source.onerror = function () { + source.onerror = function () + { source.onload = null; source.onerror = null; - if(!scope.isLoading) { + if(!scope.isLoading) + { return; } @@ -234,24 +249,29 @@ // Per http://www.w3.org/TR/html5/embedded-content-0.html#the-img-element // "The value of `complete` can thus change while a script is executing." // So complete needs to be re-checked after the callbacks have been added.. - if (source.complete) { + if (source.complete) + { this.isLoading = false; // ..and if we're complete now, no need for callbacks source.onload = null; source.onerror = null; - if (source.width && source.height) { + if (source.width && source.height) + { this._sourceLoaded(); // If any previous subscribers possible - if (wasLoading) { + if (wasLoading) + { this.emit('loaded', this); } } - else { + else + { // If any previous subscribers possible - if (wasLoading) { + if (wasLoading) + { this.emit('error', this); } } @@ -265,7 +285,8 @@ * * @private */ -BaseTexture.prototype._sourceLoaded = function () { +BaseTexture.prototype._sourceLoaded = function () +{ this.hasLoaded = true; this.width = this.source.naturalWidth || this.source.width; @@ -278,16 +299,20 @@ * Destroys this base texture * */ -BaseTexture.prototype.destroy = function () { - if (this.imageUrl) { +BaseTexture.prototype.destroy = function () +{ + if (this.imageUrl) + { delete utils.BaseTextureCache[this.imageUrl]; delete utils.TextureCache[this.imageUrl]; this.imageUrl = null; - if (!navigator.isCocoonJS) { + if (!navigator.isCocoonJS) + { this.source.src = ''; } } - else if (this.source && this.source._pixiId) { + else if (this.source && this.source._pixiId) + { delete utils.BaseTextureCache[this.source._pixiId]; } this.source = null; @@ -301,7 +326,8 @@ * memory again. * */ -BaseTexture.prototype.dispose = function () { +BaseTexture.prototype.dispose = function () +{ this.emit('dispose', this); }; @@ -311,7 +337,8 @@ * * @param newSrc {string} the path of the image */ -BaseTexture.prototype.updateSourceImage = function (newSrc) { +BaseTexture.prototype.updateSourceImage = function (newSrc) +{ this.source.src = newSrc; this.loadSource(this.source); }; @@ -326,18 +353,22 @@ * @param [scaleMode=scaleModes.DEFAULT] {number} See {@link scaleModes} for possible values * @return BaseTexture */ -BaseTexture.fromImage = function (imageUrl, crossorigin, scaleMode) { +BaseTexture.fromImage = function (imageUrl, crossorigin, scaleMode) +{ var baseTexture = utils.BaseTextureCache[imageUrl]; - if (crossorigin === undefined && imageUrl.indexOf('data:') !== 0) { + if (crossorigin === undefined && imageUrl.indexOf('data:') !== 0) + { crossorigin = true; } - if (!baseTexture) { + if (!baseTexture) + { // new Image() breaks tex loading in some versions of Chrome. // See https://code.google.com/p/chromium/issues/detail?id=238071 var image = new Image();//document.createElement('img'); - if (crossorigin) { + if (crossorigin) + { image.crossOrigin = ''; } @@ -347,7 +378,8 @@ utils.BaseTextureCache[imageUrl] = baseTexture; // if there is an @2x at the end of the url we are going to assume its a highres image - if ( imageUrl.indexOf(CONST.RETINA_PREFIX + '.') !== -1) { + if ( imageUrl.indexOf(CONST.RETINA_PREFIX + '.') !== -1) + { baseTexture.resolution = 2; } } @@ -363,14 +395,17 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return BaseTexture */ -BaseTexture.fromCanvas = function (canvas, scaleMode) { - if (!canvas._pixiId) { +BaseTexture.fromCanvas = function (canvas, scaleMode) +{ + if (!canvas._pixiId) + { canvas._pixiId = 'canvas_' + utils.uuid(); } var baseTexture = utils.BaseTextureCache[canvas._pixiId]; - if (!baseTexture) { + if (!baseTexture) + { baseTexture = new BaseTexture(canvas, scaleMode); utils.BaseTextureCache[canvas._pixiId] = baseTexture; } diff --git a/src/core/textures/RenderTexture.js b/src/core/textures/RenderTexture.js index 6dad20f..53ae796 100644 --- a/src/core/textures/RenderTexture.js +++ b/src/core/textures/RenderTexture.js @@ -46,8 +46,10 @@ * @param [scaleMode] {number} See {@link scaleModes} for possible values * @param [resolution=1] {number} The resolution of the texture being generated */ -function RenderTexture(renderer, width, height, scaleMode, resolution) { - if (!renderer) { +function RenderTexture(renderer, width, height, scaleMode, resolution) +{ + if (!renderer) + { throw new Error('Unable to create RenderTexture, you must pass a renderer into the constructor.'); } @@ -133,7 +135,8 @@ */ this.renderer = renderer; - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { var gl = this.renderer.gl; this.textureBuffer = new FilterTexture(gl, this.width * this.resolution, this.height * this.resolution, this.baseTexture.scaleMode); @@ -142,7 +145,8 @@ this.render = this.renderWebGL; this.projection = new math.Point(this.width*0.5, -this.height*0.5); } - else { + else + { this.render = this.renderCanvas; this.textureBuffer = new CanvasBuffer(this.width* this.resolution, this.height* this.resolution); this.baseTexture.source = this.textureBuffer.canvas; @@ -167,8 +171,10 @@ * @param height {number} The height to resize to. * @param updateBase {boolean} Should the baseTexture.width and height values be resized as well? */ -RenderTexture.prototype.resize = function (width, height, updateBase) { - if (width === this.width && height === this.height) { +RenderTexture.prototype.resize = function (width, height, updateBase) +{ + if (width === this.width && height === this.height) + { return; } @@ -177,17 +183,20 @@ this.width = this.frame.width = this.crop.width = width; this.height = this.frame.height = this.crop.height = height; - if (updateBase) { + if (updateBase) + { this.baseTexture.width = this.width; this.baseTexture.height = this.height; } - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { this.projection.x = this.width / 2; this.projection.y = -this.height / 2; } - if (!this.valid) { + if (!this.valid) + { return; } @@ -198,12 +207,15 @@ * Clears the RenderTexture. * */ -RenderTexture.prototype.clear = function () { - if (!this.valid) { +RenderTexture.prototype.clear = function () +{ + if (!this.valid) + { return; } - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { this.renderer.gl.bindFramebuffer(this.renderer.gl.FRAMEBUFFER, this.textureBuffer.frameBuffer); } @@ -220,19 +232,23 @@ * @param [restoreWorldTransform=true] {boolean} If true the displayObject's worldTransform/worldAlpha and all children * transformations will be restored. Not restoring this information will be a little faster. */ -RenderTexture.prototype.renderWebGL = function (displayObject, matrix, clear, restoreWorldTransform) { - if (!this.valid) { +RenderTexture.prototype.renderWebGL = function (displayObject, matrix, clear, restoreWorldTransform) +{ + if (!this.valid) + { return; } - if (typeof restoreWorldTransform === 'undefined') { + if (typeof restoreWorldTransform === 'undefined') + { restoreWorldTransform = true; } var tempAlpha, tempTransform; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { tempAlpha = displayObject.worldAlpha; tempTransform = displayObject.worldTransform.toArray(); } @@ -245,7 +261,8 @@ wt.identity(); wt.translate(0, this.projection.y * 2); - if (matrix) { + if (matrix) + { wt.append(matrix); } @@ -258,7 +275,8 @@ var children = displayObject.children; var i, j; - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } @@ -269,7 +287,8 @@ gl.bindFramebuffer(gl.FRAMEBUFFER, this.textureBuffer.frameBuffer ); - if (clear) { + if (clear) + { this.textureBuffer.clear(); } @@ -279,11 +298,13 @@ this.renderer.spriteBatch.dirty = true; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { displayObject.worldAlpha = tempAlpha; displayObject.worldTransform.fromArray(tempTransform); - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } } @@ -300,26 +321,31 @@ * @param [restoreWorldTransform=true] {boolean} If true the displayObject's worldTransform/worldAlpha and all children * transformations will be restored. Not restoring this information will be a little faster. */ -RenderTexture.prototype.renderCanvas = function (displayObject, matrix, clear, restoreWorldTransform) { - if (!this.valid) { +RenderTexture.prototype.renderCanvas = function (displayObject, matrix, clear, restoreWorldTransform) +{ + if (!this.valid) + { return; } - if (typeof restoreWorldTransform === 'undefined') { + if (typeof restoreWorldTransform === 'undefined') + { restoreWorldTransform = true; } var tempAlpha, tempTransform; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { tempAlpha = displayObject.worldAlpha; tempTransform = displayObject.worldTransform.toArray(); } var wt = displayObject.worldTransform; wt.identity(); - if (matrix) { + if (matrix) + { wt.append(matrix); } @@ -330,11 +356,13 @@ var children = displayObject.children; var i, j; - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } - if (clear) { + if (clear) + { this.textureBuffer.clear(); } @@ -348,11 +376,13 @@ this.renderer.resolution = realResolution; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { displayObject.worldAlpha = tempAlpha; displayObject.worldTransform.fromArray(tempTransform); - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } } @@ -363,7 +393,8 @@ * * @return {Image} */ -RenderTexture.prototype.getImage = function () { +RenderTexture.prototype.getImage = function () +{ var image = new Image(); image.src = this.getBase64(); return image; @@ -374,7 +405,8 @@ * * @return {string} A base64 encoded string of the texture. */ -RenderTexture.prototype.getBase64 = function () { +RenderTexture.prototype.getBase64 = function () +{ return this.getCanvas().toDataURL(); }; @@ -383,8 +415,10 @@ * * @return {HTMLCanvasElement} A Canvas element with the texture rendered on. */ -RenderTexture.prototype.getCanvas = function () { - if (this.renderer.type === CONST.WEBGL_RENDERER) { +RenderTexture.prototype.getCanvas = function () +{ + if (this.renderer.type === CONST.WEBGL_RENDERER) + { var gl = this.renderer.gl; var width = this.textureBuffer.width; var height = this.textureBuffer.height; @@ -403,7 +437,8 @@ return tempCanvas.canvas; } - else { + else + { return this.textureBuffer.canvas; } }; diff --git a/src/core/textures/Texture.js b/src/core/textures/Texture.js index 3c65909..e97f0aa 100644 --- a/src/core/textures/Texture.js +++ b/src/core/textures/Texture.js @@ -17,7 +17,8 @@ * @param [crop] {Rectangle} The area of original texture * @param [trim] {Rectangle} Trimmed texture rectangle */ -function Texture(baseTexture, frame, crop, trim) { +function Texture(baseTexture, frame, crop, trim) +{ /** * Does this Texture have any frame data assigned to it? * @@ -25,12 +26,14 @@ */ this.noFrame = false; - if (!frame) { + if (!frame) + { this.noFrame = true; frame = new math.Rectangle(0, 0, 1, 1); } - if (baseTexture instanceof Texture) { + if (baseTexture instanceof Texture) + { baseTexture = baseTexture.baseTexture; } @@ -100,13 +103,16 @@ */ this.crop = crop || new math.Rectangle(0, 0, 1, 1); - if (baseTexture.hasLoaded) { - if (this.noFrame) { + if (baseTexture.hasLoaded) + { + if (this.noFrame) + { frame = new math.Rectangle(0, 0, baseTexture.width, baseTexture.height); } this.frame = frame; } - else { + else + { baseTexture.addEventListener('loaded', this.onBaseTextureLoaded.bind(this)); } } @@ -118,19 +124,23 @@ Object.defineProperties(Texture.prototype, { needsUpdate: { - get: function () { + get: function () + { return this.baseTexture.needsUpdate; }, - set: function (val) { + set: function (val) + { this.baseTexture.needsUpdate = val; } }, frame: { - get: function () { + get: function () + { return this._frame; }, - set: function (frame) { + set: function (frame) + { this._frame = frame; this.noFrame = false; @@ -143,20 +153,23 @@ 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 (!this.trim && (frame.x + frame.width > this.baseTexture.width || frame.y + frame.height > this.baseTexture.height)) + { throw new Error('Texture Error: frame does not fit inside the base Texture dimensions ' + this); } this.valid = frame && frame.width && frame.height && this.baseTexture.source && this.baseTexture.hasLoaded; - if (this.trim) { + 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) { + if (this.valid) + { this._updateUvs(); } } @@ -168,11 +181,13 @@ * * @private */ -Texture.prototype.onBaseTextureLoaded = function () { +Texture.prototype.onBaseTextureLoaded = function () +{ var baseTexture = this.baseTexture; baseTexture.removeEventListener('loaded', this.onLoaded); - if (this.noFrame) { + if (this.noFrame) + { this.frame = new math.Rectangle(0, 0, baseTexture.width, baseTexture.height); } @@ -184,8 +199,10 @@ * * @param destroyBase {boolean} Whether to destroy the base texture as well */ -Texture.prototype.destroy = function (destroyBase) { - if (destroyBase) { +Texture.prototype.destroy = function (destroyBase) +{ + if (destroyBase) + { this.baseTexture.destroy(); } @@ -197,8 +214,10 @@ * * @private */ -Texture.prototype._updateUvs = function () { - if (!this._uvs) { +Texture.prototype._updateUvs = function () +{ + if (!this._uvs) + { this._uvs = new TextureUvs(); } @@ -229,10 +248,12 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return Texture */ -Texture.fromImage = function (imageUrl, crossorigin, scaleMode) { +Texture.fromImage = function (imageUrl, crossorigin, scaleMode) +{ var texture = utils.TextureCache[imageUrl]; - if (!texture) { + if (!texture) + { texture = new Texture(BaseTexture.fromImage(imageUrl, crossorigin, scaleMode)); utils.TextureCache[imageUrl] = texture; } @@ -248,9 +269,11 @@ * @param frameId {string} The frame id of the texture * @return Texture */ -Texture.fromFrame = function (frameId) { +Texture.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache '); } return texture; @@ -264,7 +287,8 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return {Texture} */ -Texture.fromCanvas = function (canvas, scaleMode) { +Texture.fromCanvas = function (canvas, scaleMode) +{ return new Texture(BaseTexture.fromCanvas(canvas, scaleMode)); }; @@ -276,7 +300,8 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return {Texture} A Texture */ -Texture.fromVideo = function (video, scaleMode) { +Texture.fromVideo = function (video, scaleMode) +{ return new Texture(VideoBaseTexture.baseTextureFromVideo(video, scaleMode)); }; @@ -287,7 +312,8 @@ * @param texture {Texture} The Texture to add to the cache. * @param id {string} The id that the texture will be stored against. */ -Texture.addTextureToCache = function (texture, id) { +Texture.addTextureToCache = function (texture, id) +{ utils.TextureCache[id] = texture; }; @@ -298,7 +324,8 @@ * @param id {string} The id of the texture to be removed * @return {Texture} The texture that was removed */ -Texture.removeTextureFromCache = function (id) { +Texture.removeTextureFromCache = function (id) +{ var texture = utils.TextureCache[id]; delete utils.TextureCache[id]; diff --git a/src/core/textures/TextureUvs.js b/src/core/textures/TextureUvs.js index b9bbb58..5424d52 100644 --- a/src/core/textures/TextureUvs.js +++ b/src/core/textures/TextureUvs.js @@ -1,4 +1,5 @@ -function TextureUvs() { +function TextureUvs() +{ this.x0 = 0; this.y0 = 0; diff --git a/src/core/textures/VideoBaseTexture.js b/src/core/textures/VideoBaseTexture.js index e3e0c5a..1a826a9 100644 --- a/src/core/textures/VideoBaseTexture.js +++ b/src/core/textures/VideoBaseTexture.js @@ -12,15 +12,18 @@ * @param source {HTMLVideoElement} * @param [scaleMode] {number} See {@link scaleModes} for possible values */ -function VideoBaseTexture(source, scaleMode) { - if (!source){ +function VideoBaseTexture(source, scaleMode) +{ + if (!source) + { throw new Error('No video source element specified.'); } // hook in here to check if video is already available. // BaseTexture looks for a source.complete boolean, plus width & height. - if ((source.readyState === source.HAVE_ENOUGH_DATA || source.readyState === source.HAVE_FUTURE_DATA) && source.width && source.height) { + if ((source.readyState === source.HAVE_ENOUGH_DATA || source.readyState === source.HAVE_FUTURE_DATA) && source.width && source.height) + { source.complete = true; } @@ -31,7 +34,8 @@ this._boundOnUpdate = this._onUpdate.bind(this); this._boundOnCanPlay = this._onCanPlay.bind(this); - if (!source.complete) { + if (!source.complete) + { source.addEventListener('canplay', this._boundOnCanPlay); source.addEventListener('canplaythrough', this._boundOnCanPlay); @@ -47,28 +51,35 @@ VideoBaseTexture.prototype.constructor = VideoBaseTexture; module.exports = VideoBaseTexture; -VideoBaseTexture.prototype._onUpdate = function () { - if (this.autoUpdate) { +VideoBaseTexture.prototype._onUpdate = function () +{ + if (this.autoUpdate) + { window.requestAnimationFrame(this._boundOnUpdate); this.needsUpdate = true; } }; -VideoBaseTexture.prototype._onPlayStart = function () { - if (!this.autoUpdate) { +VideoBaseTexture.prototype._onPlayStart = function () +{ + if (!this.autoUpdate) + { window.requestAnimationFrame(this._boundOnUpdate); this.autoUpdate = true; } }; -VideoBaseTexture.prototype._onPlayStop = function () { +VideoBaseTexture.prototype._onPlayStop = function () +{ this.autoUpdate = false; }; -VideoBaseTexture.prototype._onCanPlay = function () { +VideoBaseTexture.prototype._onCanPlay = function () +{ this.hasLoaded = true; - if (this.source) { + if (this.source) + { this.source.removeEventListener('canplay', this._boundOnCanPlay); this.source.removeEventListener('canplaythrough', this._boundOnCanPlay); @@ -78,15 +89,18 @@ this.source.play(); // prevent multiple loaded dispatches.. - if(!this.__loaded){ + if(!this.__loaded) + { this.__loaded = true; this.emit('loaded', this); } } }; -VideoBaseTexture.prototype.destroy = function () { - if (this.source && this.source._pixiId) { +VideoBaseTexture.prototype.destroy = function () +{ + if (this.source && this.source._pixiId) + { utils.BaseTextureCache[ this.source._pixiId ] = null; delete utils.BaseTextureCache[ this.source._pixiId ]; @@ -105,14 +119,17 @@ * @param scaleMode {number} See {@link scaleModes} for possible values * @return {VideoBaseTexture} */ -VideoBaseTexture.fromVideo = function (video, scaleMode) { - if (!video._pixiId) { +VideoBaseTexture.fromVideo = function (video, scaleMode) +{ + if (!video._pixiId) + { video._pixiId = 'video_' + utils.uuid(); } var baseTexture = utils.BaseTextureCache[video._pixiId]; - if (!baseTexture) { + if (!baseTexture) + { baseTexture = new VideoBaseTexture(video, scaleMode); utils.BaseTextureCache[ video._pixiId ] = baseTexture; } @@ -147,17 +164,21 @@ * @param scaleMode {number} See {@link scaleModes} for possible values * @return {VideoBaseTexture} */ -VideoBaseTexture.fromUrl = function (videoSrc, scaleMode) { +VideoBaseTexture.fromUrl = function (videoSrc, scaleMode) +{ var video = document.createElement('video'); // array of objects or strings - if (Array.isArray(videoSrc)) { - for (var i = 0; i < videoSrc.length; ++i) { + if (Array.isArray(videoSrc)) + { + for (var i = 0; i < videoSrc.length; ++i) + { video.appendChild(createSource(videoSrc.src || videoSrc, videoSrc.mime)); } } // single object or string - else { + else + { video.appendChild(createSource(videoSrc.src || videoSrc, videoSrc.mime)); } @@ -169,8 +190,10 @@ VideoBaseTexture.fromUrls = VideoBaseTexture.fromUrl; -function createSource(path, type) { - if (!type) { +function createSource(path, type) +{ + if (!type) + { type = 'video/' + path.substr(path.lastIndexOf('.') + 1); } diff --git a/src/core/utils/EventData.js b/src/core/utils/EventData.js index 5d55a22..8cdf701 100644 --- a/src/core/utils/EventData.js +++ b/src/core/utils/EventData.js @@ -7,7 +7,8 @@ * @param name {string} The string name of the event that was triggered * @param data {object} Arbitrary event data to pass along */ -function EventData(target, name, data) { +function EventData(target, name, data) +{ // for duck typing in the ".on()" function this.__isEventObject = true; @@ -71,7 +72,8 @@ * Stops the propagation of events up the scene graph (prevents bubbling). * */ -EventData.prototype.stopPropagation = function stopPropagation() { +EventData.prototype.stopPropagation = function stopPropagation() +{ this.stopped = true; }; @@ -79,6 +81,7 @@ * Stops the propagation of events to sibling listeners (no longer calls any listeners). * */ -EventData.prototype.stopImmediatePropagation = function stopImmediatePropagation() { +EventData.prototype.stopImmediatePropagation = function stopImmediatePropagation() +{ this.stoppedImmediate = true; }; diff --git a/src/core/utils/EventTarget.js b/src/core/utils/EventTarget.js index 7ae8820..671a151 100644 --- a/src/core/utils/EventTarget.js +++ b/src/core/utils/EventTarget.js @@ -13,14 +13,16 @@ * var em = new MyEmitter(); * em.emit('eventName', 'some data', 'some more data', {}, null, ...); */ -function eventTarget(obj) { +function eventTarget(obj) +{ /** * Return a list of assigned event listeners. * * @param eventName {string} The events that should be listed. * @return {Array} An array of listener functions */ - obj.listeners = function listeners(eventName) { + obj.listeners = function listeners(eventName) + { this._listeners = this._listeners || {}; return this._listeners[eventName] ? this._listeners[eventName].slice() : []; @@ -33,22 +35,26 @@ * @param eventName {string} The name of the event. * @return {boolean} Indication if we've emitted an event. */ - obj.emit = obj.dispatchEvent = function emit(eventName, data) { + obj.emit = obj.dispatchEvent = function emit(eventName, data) + { this._listeners = this._listeners || {}; // fast return when there are no listeners - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return; } //backwards compat with old method ".emit({ type: 'something' })" - if (typeof eventName === 'object') { + if (typeof eventName === 'object') + { data = eventName; eventName = eventName.type; } //ensure we are using a real pixi event - if (!data || data.__isEventObject !== true) { + if (!data || data.__isEventObject !== true) + { data = new EventData(this, eventName, data); } @@ -58,23 +64,27 @@ fn = listeners[0], i; - for (i = 0; i < length; fn = listeners[++i]) { + for (i = 0; i < length; fn = listeners[++i]) + { //call the event listener fn.call(this, data); //if "stopImmediatePropagation" is called, stop calling sibling events - if (data.stoppedImmediate) { + if (data.stoppedImmediate) + { return this; } } //if "stopPropagation" is called then don't bubble the event - if (data.stopped) { + if (data.stopped) + { return this; } //bubble this event up the scene graph - if (this.parent && this.parent.emit) { + if (this.parent && this.parent.emit) + { this.parent.emit.call(this.parent, eventName, data); } @@ -88,7 +98,8 @@ * @param eventName {string} Name of the event. * @param callback {Functon} fn Callback function. */ - obj.on = obj.addEventListener = function on(eventName, fn) { + obj.on = obj.addEventListener = function on(eventName, fn) + { this._listeners = this._listeners || {}; (this._listeners[eventName] = this._listeners[eventName] || []) @@ -103,11 +114,13 @@ * @param eventName {string} Name of the event. * @param callback {Function} Callback function. */ - obj.once = function once(eventName, fn) { + obj.once = function once(eventName, fn) + { this._listeners = this._listeners || {}; var self = this; - function onceHandlerWrapper() { + function onceHandlerWrapper() + { fn.apply(self.off(eventName, onceHandlerWrapper), arguments); } onceHandlerWrapper._originalHandler = fn; @@ -122,23 +135,28 @@ * @param eventName {string} The event we want to remove. * @param callback {Function} The listener that we need to find. */ - obj.off = obj.removeEventListener = function off(eventName, fn) { + obj.off = obj.removeEventListener = function off(eventName, fn) + { this._listeners = this._listeners || {}; - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return this; } var list = this._listeners[eventName], i = fn ? list.length : 0; - while(i-- > 0) { - if (list[i] === fn || list[i]._originalHandler === fn) { + while(i-- > 0) + { + if (list[i] === fn || list[i]._originalHandler === fn) + { list.splice(i, 1); } } - if (list.length === 0) { + if (list.length === 0) + { delete this._listeners[eventName]; } @@ -150,10 +168,12 @@ * * @param eventName {string} The event you want to remove all listeners for. */ - obj.removeAllListeners = function removeAllListeners(eventName) { + obj.removeAllListeners = function removeAllListeners(eventName) + { this._listeners = this._listeners || {}; - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return this; } @@ -169,7 +189,8 @@ * * @param object {object} The obj to mix into */ - mixin: function mixin(obj) { + mixin: function mixin(obj) + { eventTarget(obj); } }; diff --git a/src/core/utils/PolyK.js b/src/core/utils/PolyK.js index 7325141..5e20c2b 100644 --- a/src/core/utils/PolyK.js +++ b/src/core/utils/PolyK.js @@ -47,7 +47,8 @@ * Triangulates shapes for webGL graphic fills. * */ -PolyK.Triangulate = function (p) { +PolyK.Triangulate = function (p) +{ var sign = true; var n = p.length >> 1; @@ -59,7 +60,8 @@ i = 0; var al = n; - while(al > 3) { + while(al > 3) + { var i0 = avl[(i+0)%al]; var i1 = avl[(i+1)%al]; var i2 = avl[(i+2)%al]; @@ -69,29 +71,35 @@ var cx = p[2*i2], cy = p[2*i2+1]; var earFound = false; - if (PolyK._convex(ax, ay, bx, by, cx, cy, sign)) { + if (PolyK._convex(ax, ay, bx, by, cx, cy, sign)) + { earFound = true; - for (var j = 0; j < al; j++) { + for (var j = 0; j < al; j++) + { var vi = avl[j]; if (vi === i0 || vi === i1 || vi === i2) continue; - if (PolyK._PointInTriangle(p[2*vi], p[2*vi+1], ax, ay, bx, by, cx, cy)) { + if (PolyK._PointInTriangle(p[2*vi], p[2*vi+1], ax, ay, bx, by, cx, cy)) + { earFound = false; break; } } } - if (earFound) { + if (earFound) + { tgs.push(i0, i1, i2); avl.splice((i+1)%al, 1); al--; i = 0; } - else if (i++ > 3*al) { + else if (i++ > 3*al) + { // need to flip flip reverse it! // reset! - if (sign) { + if (sign) + { tgs = []; avl = []; for (i = 0; i < n; i++) avl.push(i); @@ -101,7 +109,8 @@ sign = false; } - else { + else + { // window.console.log("PIXI Warning: shape too complex to fill"); return null; } @@ -126,7 +135,8 @@ * @private * @return {boolean} */ -PolyK._PointInTriangle = function (px, py, ax, ay, bx, by, cx, cy) { +PolyK._PointInTriangle = function (px, py, ax, ay, bx, by, cx, cy) +{ var v0x = cx-ax; var v0y = cy-ay; var v1x = bx-ax; @@ -154,6 +164,7 @@ * @private * @return {boolean} */ -PolyK._convex = function (ax, ay, bx, by, cx, cy, sign) { +PolyK._convex = function (ax, ay, bx, by, cx, cy, sign) +{ return ((ay-by)*(cx-bx) + (bx-ax)*(cy-by) >= 0) === sign; }; diff --git a/src/core/utils/index.js b/src/core/utils/index.js index ade9831..bfae7ae 100644 --- a/src/core/utils/index.js +++ b/src/core/utils/index.js @@ -16,7 +16,8 @@ * * @return {number} The next uuid to use. */ - uuid: function () { + uuid: function () + { return ++utils._uid; }, @@ -26,7 +27,8 @@ * @param hex {number} * @return {number[]} An array representing the [R, G, B] of the color. */ - hex2rgb: function (hex, out) { + hex2rgb: function (hex, out) + { out = out || []; out[0] = (hex >> 16 & 0xFF) / 255; @@ -42,7 +44,8 @@ * @param hex {number} * @return {string} The string color. */ - hex2string: function (hex) { + hex2string: function (hex) + { hex = hex.toString(16); hex = '000000'.substr(0, 6 - hex.length) + hex; @@ -55,7 +58,8 @@ * @param rgb {number[]} * @return {number} The color number */ - rgb2hex: function (rgb) { + rgb2hex: function (rgb) + { return ((rgb[0]*255 << 16) + (rgb[1]*255 << 8) + rgb[2]*255); }, @@ -64,8 +68,10 @@ * * @return {boolean} whether they are supported */ - canUseNewCanvasBlendModes: function () { - if (typeof document === 'undefined') { + canUseNewCanvasBlendModes: function () + { + if (typeof document === 'undefined') + { return false; } @@ -93,15 +99,19 @@ * @param number {number} * @return {number} the closest number that is a power of two */ - getNextPowerOfTwo: function (number) { + getNextPowerOfTwo: function (number) + { // see: http://en.wikipedia.org/wiki/Power_of_two#Fast_algorithm_to_check_if_a_positive_number_is_a_power_of_two - if (number > 0 && (number & (number - 1)) === 0) { + if (number > 0 && (number & (number - 1)) === 0) + { return number; } - else { + else + { var result = 1; - while (result < number) { + while (result < number) + { result <<= 1; } @@ -116,7 +126,8 @@ * @param height {number} * @return {boolean} */ - isPowerOfTwo: function (width, height) { + isPowerOfTwo: function (width, height) + { return (width > 0 && (width & (width - 1)) === 0 && height > 0 && (height & (height - 1)) === 0); }, @@ -130,12 +141,15 @@ * @constant * @static */ - sayHello: function (type) { - if (utils._saidHello) { + sayHello: function (type) + { + if (utils._saidHello) + { return; } - if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) { + if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) + { var args = [ '%c %c %c Pixi.js ' + CONST.VERSION + ' - ' + type + ' %c ' + ' %c ' + ' http://www.pixijs.com/ %c %c ♥%c♥%c♥ ', 'background: #ff66a5', @@ -151,7 +165,8 @@ console.log.apply(console, args); //jshint ignore:line } - else if (window.console) { + else if (window.console) + { console.log('Pixi.js ' + CONST.VERSION + ' - ' + type + ' - http://www.pixijs.com/'); //jshint ignore:line } @@ -166,15 +181,19 @@ * @class * @namespace PIXI */ - AjaxRequest: function () { + AjaxRequest: function () + { var activexmodes = ['Msxml2.XMLHTTP.6.0', 'Msxml2.XMLHTTP.3.0', 'Microsoft.XMLHTTP']; //activeX versions to check for in IE - if (window.ActiveXObject) { //Test for support for ActiveXObject in IE first (as XMLHttpRequest in IE7 is broken) - for (var i=0; i= this.textures.length) { + else if (round >= this.textures.length) + { this.gotoAndStop(this.textures.length - 1); - if (this.onComplete) { + if (this.onComplete) + { this.onComplete(); } } @@ -167,10 +182,12 @@ * @static * @param frames {string[]} the array of frames ids the movieclip will use as its texture frames */ -MovieClip.fromFrames = function (frames) { +MovieClip.fromFrames = function (frames) +{ var textures = []; - for (var i = 0; i < frames.length; ++i) { + for (var i = 0; i < frames.length; ++i) + { textures.push(new core.Texture.fromFrame(frames[i])); } @@ -183,10 +200,12 @@ * @static * @param images {string[]} the array of image urls the movieclip will use as its texture frames */ -MovieClip.fromImages = function (images) { +MovieClip.fromImages = function (images) +{ var textures = []; - for (var i = 0; i < images.length; ++i) { + for (var i = 0; i < images.length; ++i) + { textures.push(new core.Texture.fromImage(images[i])); } diff --git a/src/extras/Rope.js b/src/extras/Rope.js index c157ec4..9c87bc0 100644 --- a/src/extras/Rope.js +++ b/src/extras/Rope.js @@ -9,7 +9,8 @@ * @param {Array} points - An array of {Point}. * */ -function Rope(texture, points) { +function Rope(texture, points) +{ Strip.call(this, texture); this.points = points; @@ -31,10 +32,12 @@ * Refreshes * */ -Rope.prototype.refresh = function () { +Rope.prototype.refresh = function () +{ var points = this.points; - if (points.length < 1) { + if (points.length < 1) + { return; } @@ -59,20 +62,23 @@ var total = points.length, point, index, amount; - for (var i = 1; i < total; i++) { + for (var i = 1; i < total; i++) + { point = points[i]; index = i * 4; // time to do some smart drawing! amount = i / (total-1); - if (i%2) { + if (i%2) + { uvs[index] = amount; uvs[index+1] = 0; uvs[index+2] = amount; uvs[index+3] = 1; } - else { + else + { uvs[index] = amount; uvs[index+1] = 0; @@ -95,10 +101,12 @@ * * @private */ -Rope.prototype.updateTransform = function () { +Rope.prototype.updateTransform = function () +{ var points = this.points; - if (points.length < 1) { + if (points.length < 1) + { return; } @@ -113,14 +121,17 @@ var total = points.length, point, index, ratio, perpLength, num; - for (var i = 0; i < total; i++) { + for (var i = 0; i < total; i++) + { point = points[i]; index = i * 4; - if (i < points.length-1) { + if (i < points.length-1) + { nextPoint = points[i+1]; } - else { + else + { nextPoint = point; } @@ -129,7 +140,8 @@ ratio = (1 - (i / (total-1))) * 10; - if (ratio > 1) { + if (ratio > 1) + { ratio = 1; } @@ -157,7 +169,8 @@ * * @param texture {Texture} the texture that will be used */ -Rope.prototype.setTexture = function (texture) { +Rope.prototype.setTexture = function (texture) +{ // stop current texture this.texture = texture; //this.updateFrame = true; diff --git a/src/extras/Strip.js b/src/extras/Strip.js index c5e378f..57691b5 100644 --- a/src/extras/Strip.js +++ b/src/extras/Strip.js @@ -10,7 +10,8 @@ * @param height {number} the height * */ -function Strip(texture) { +function Strip(texture) +{ core.DisplayObjectContainer.call(this); /** @@ -70,9 +71,11 @@ * * @param renderer {WebGLRenderer} */ -Strip.prototype.renderWebGL = function (renderer) { +Strip.prototype.renderWebGL = function (renderer) +{ // if the sprite is not visible or the alpha is 0 then no need to render this element - if (!this.visible || this.alpha <= 0) { + if (!this.visible || this.alpha <= 0) + { return; } @@ -81,7 +84,8 @@ renderer.spriteBatch.stop(); // init! init! - if (!this._vertexBuffer) { + if (!this._vertexBuffer) + { this._initWebGL(renderer); } @@ -96,7 +100,8 @@ //TODO check culling }; -Strip.prototype._initWebGL = function (renderer) { +Strip.prototype._initWebGL = function (renderer) +{ // build the strip! var gl = renderer.gl; @@ -118,7 +123,8 @@ gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this.indices, gl.STATIC_DRAW); }; -Strip.prototype._renderStrip = function (renderer) { +Strip.prototype._renderStrip = function (renderer) +{ var gl = renderer.gl; var projection = renderer.projection, offset = renderer.offset, @@ -137,7 +143,8 @@ gl.uniform2f(shader.offsetVector, -offset.x, -offset.y); gl.uniform1f(shader.alpha, this.worldAlpha); - if (!this.dirty) { + if (!this.dirty) + { gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexBuffer); gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); @@ -150,10 +157,12 @@ gl.activeTexture(gl.TEXTURE0); // check if a texture is dirty.. - if (this.texture.baseTexture._dirty[gl.id]) { + if (this.texture.baseTexture._dirty[gl.id]) + { renderer.updateTexture(this.texture.baseTexture); } - else { + else + { // bind the current texture gl.bindTexture(gl.TEXTURE_2D, this.texture.baseTexture._glTextures[gl.id]); } @@ -163,7 +172,8 @@ } - else { + else + { this.dirty = false; gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexBuffer); @@ -178,10 +188,12 @@ gl.activeTexture(gl.TEXTURE0); // check if a texture is dirty.. - if (this.texture.baseTexture._dirty[gl.id]) { + if (this.texture.baseTexture._dirty[gl.id]) + { renderer.updateTexture(this.texture.baseTexture); } - else { + else + { gl.bindTexture(gl.TEXTURE_2D, this.texture.baseTexture._glTextures[gl.id]); } @@ -203,27 +215,33 @@ * * @param renderer {CanvasRenderer} */ -Strip.prototype.renderCanvas = function (renderer) { +Strip.prototype.renderCanvas = function (renderer) +{ var context = renderer.context; var transform = this.worldTransform; - if (renderer.roundPixels) { + if (renderer.roundPixels) + { context.setTransform(transform.a, transform.b, transform.c, transform.d, transform.tx | 0, transform.ty | 0); } - else { + else + { context.setTransform(transform.a, transform.b, transform.c, transform.d, transform.tx, transform.ty); } - if (this.drawMode === Strip.DrawModes.TRIANGLE_STRIP) { + if (this.drawMode === Strip.DrawModes.TRIANGLE_STRIP) + { this._renderCanvasTriangleStrip(context); } - else { + else + { this._renderCanvasTriangles(context); } }; -Strip.prototype._renderCanvasTriangleStrip = function (context) { +Strip.prototype._renderCanvasTriangleStrip = function (context) +{ // draw triangles!! var vertices = this.vertices; var uvs = this.uvs; @@ -231,14 +249,16 @@ var length = vertices.length / 2; // this.count++; - for (var i = 0; i < length - 2; i++) { + for (var i = 0; i < length - 2; i++) + { // draw some triangles! var index = i * 2; this._renderCanvasDrawTriangle(context, vertices, uvs, index, (index + 2), (index + 4)); } }; -Strip.prototype._renderCanvasTriangles = function (context) { +Strip.prototype._renderCanvasTriangles = function (context) +{ // draw triangles!! var vertices = this.vertices; var uvs = this.uvs; @@ -247,14 +267,16 @@ var length = indices.length; // this.count++; - for (var i = 0; i < length; i += 3) { + for (var i = 0; i < length; i += 3) + { // draw some triangles! var index0 = indices[i] * 2, index1 = indices[i + 1] * 2, index2 = indices[i + 2] * 2; this._renderCanvasDrawTriangle(context, vertices, uvs, index0, index1, index2); } }; -Strip.prototype._renderCanvasDrawTriangle = function (context, vertices, uvs, index0, index1, index2) { +Strip.prototype._renderCanvasDrawTriangle = function (context, vertices, uvs, index0, index1, index2) +{ var textureSource = this.texture.baseTexture.source; var textureWidth = this.texture.width; var textureHeight = this.texture.height; @@ -265,7 +287,8 @@ var u0 = uvs[index0] * textureWidth, u1 = uvs[index1] * textureWidth, u2 = uvs[index2] * textureWidth; var v0 = uvs[index0 + 1] * textureHeight, v1 = uvs[index1 + 1] * textureHeight, v2 = uvs[index2 + 1] * textureHeight; - if (this.canvasPadding > 0) { + if (this.canvasPadding > 0) + { var paddingX = this.canvasPadding / this.worldTransform.a; var paddingY = this.canvasPadding / this.worldTransform.d; var centerX = (x0 + x1 + x2) / 3; @@ -332,7 +355,8 @@ * @param strip {Strip} The Strip to render * @private */ -Strip.prototype.renderStripFlat = function (strip) { +Strip.prototype.renderStripFlat = function (strip) +{ var context = this.context; var vertices = strip.vertices; @@ -340,7 +364,8 @@ // this.count++; context.beginPath(); - for (var i=1; i < length-2; i++) { + for (var i=1; i < length-2; i++) + { // draw some triangles! var index = i*2; @@ -358,7 +383,8 @@ }; /* -Strip.prototype.setTexture = function (texture) { +Strip.prototype.setTexture = function (texture) +{ //TODO SET THE TEXTURES //TODO VISIBILITY @@ -377,7 +403,8 @@ * @private */ -Strip.prototype.onTextureUpdate = function () { +Strip.prototype.onTextureUpdate = function () +{ this.updateFrame = true; }; @@ -387,7 +414,8 @@ * @param matrix {Matrix} the transformation matrix of the sprite * @return {Rectangle} the framing rectangle */ -Strip.prototype.getBounds = function (matrix) { +Strip.prototype.getBounds = function (matrix) +{ var worldTransform = matrix || this.worldTransform; var a = worldTransform.a; @@ -404,7 +432,8 @@ var minY = Infinity; var vertices = this.vertices; - for (var i = 0, n = vertices.length; i < n; i += 2) { + for (var i = 0, n = vertices.length; i < n; i += 2) + { var rawX = vertices[i], rawY = vertices[i + 1]; var x = (a * rawX) + (c * rawY) + tx; var y = (d * rawY) + (b * rawX) + ty; @@ -416,7 +445,8 @@ maxY = y > maxY ? y : maxY; } - if (minX === -Infinity || maxY === Infinity) { + if (minX === -Infinity || maxY === Infinity) + { return core.math.Rectangle.EMPTY; } diff --git a/src/extras/TilingSprite.js b/src/extras/TilingSprite.js index 3ac22df..31da393 100644 --- a/src/extras/TilingSprite.js +++ b/src/extras/TilingSprite.js @@ -10,7 +10,8 @@ * @param width {number} the width of the tiling sprite * @param height {number} the height of the tiling sprite */ -function TilingSprite(texture, width, height) { +function TilingSprite(texture, width, height) +{ core.Sprite.call( this, texture); /** @@ -86,10 +87,12 @@ * @memberof TilingSprite# */ width: { - get: function () { + get: function () + { return this._width; }, - set: function (value) { + set: function (value) + { this._width = value; } }, @@ -101,20 +104,25 @@ * @memberof TilingSprite# */ height: { - get: function () { + get: function () + { return this._height; }, - set: function (value) { + set: function (value) + { this._height = value; } }, texture: { - get: function () { + get: function () + { return this._texture; }, - set: function (value) { - if (this._texture === value) { + set: function (value) + { + if (this._texture === value) + { return; } @@ -130,51 +138,61 @@ * * @param renderer {WebGLRenderer} */ -TilingSprite.prototype.renderWebGL = function (renderer) { - if (!this.visible || this.alpha <= 0) { +TilingSprite.prototype.renderWebGL = function (renderer) +{ + if (!this.visible || this.alpha <= 0) + { return; } var i, j; - if (this._mask) { + if (this._mask) + { renderer.spriteBatch.stop(); renderer.maskManager.pushMask(this.mask, renderer); renderer.spriteBatch.start(); } - if (this._filters) { + if (this._filters) + { renderer.spriteBatch.flush(); renderer.filterManager.pushFilter(this._filterBlock); } - if (!this.tilingTexture || this.refreshTexture) { + if (!this.tilingTexture || this.refreshTexture) + { this.generateTilingTexture(true); - if (this.tilingTexture && this.tilingTexture.needsUpdate) { + if (this.tilingTexture && this.tilingTexture.needsUpdate) + { //TODO - tweaking renderer.updateTexture(this.tilingTexture.baseTexture); this.tilingTexture.needsUpdate = false; // this.tilingTexture._uvs = null; } } - else { + else + { renderer.spriteBatch.renderTilingSprite(this); } // simple render children! - for (i=0,j=this.children.length; i= 0; i--) { + for (var i = length - 1; i >= 0; i--) + { var child = children[i]; // push all interactive bits - if (child._interactive) { + if (child._interactive) + { iParent.interactiveChildren = true; //child.__iParent = iParent; this.interactiveItems.push(child); - if (child.children.length > 0) { + if (child.children.length > 0) + { this.collectInteractiveSprite(child, child); } } - else { + else + { child.__iParent = null; - if (child.children.length > 0) { + if (child.children.length > 0) + { this.collectInteractiveSprite(child, iParent); } } @@ -189,7 +196,8 @@ * @param [resolution=1] {number} THe resolution of the new element (relative to the canvas). * @private */ -InteractionManager.prototype.setTargetElement = function (element, resolution) { +InteractionManager.prototype.setTargetElement = function (element, resolution) +{ this.removeEvents(); this.interactionDOMElement = element; @@ -203,12 +211,15 @@ * * @private */ -InteractionManager.prototype.addEvents = function () { - if (!this.interactionDOMElement) { +InteractionManager.prototype.addEvents = function () +{ + if (!this.interactionDOMElement) + { return; } - if (window.navigator.msPointerEnabled) { + if (window.navigator.msPointerEnabled) + { this.interactionDOMElement.style['-ms-content-zooming'] = 'none'; this.interactionDOMElement.style['-ms-touch-action'] = 'none'; } @@ -230,12 +241,15 @@ * * @private */ -InteractionManager.prototype.removeEvents = function () { - if (!this.interactionDOMElement) { +InteractionManager.prototype.removeEvents = function () +{ + if (!this.interactionDOMElement) + { return; } - if (window.navigator.msPointerEnabled) { + if (window.navigator.msPointerEnabled) + { this.interactionDOMElement.style['-ms-content-zooming'] = ''; this.interactionDOMElement.style['-ms-touch-action'] = ''; } @@ -260,8 +274,10 @@ * * @private */ -InteractionManager.prototype.update = function () { - if (!this.interactionDOMElement) { +InteractionManager.prototype.update = function () +{ + if (!this.interactionDOMElement) + { return; } @@ -269,7 +285,8 @@ var now = Date.now(); var diff = now - this.last; diff = (diff * INTERACTION_FREQUENCY ) / 1000; - if (diff < 1) { + if (diff < 1) + { return; } @@ -280,7 +297,8 @@ // ok.. so mouse events?? // yes for now :) // OPTIMISE - how often to check?? - if (this.dirty) { + if (this.dirty) + { this.rebuildInteractiveGraph(); } @@ -289,7 +307,8 @@ var cursor = 'inherit'; var over = false; - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { var item = this.interactiveItems[i]; // OPTIMISATION - only calculate every time if the mousemove function exists.. @@ -302,26 +321,34 @@ this.mouse.target = item; // ok so deal with interactions.. // looks like there was a hit! - if (item.__hit && !over) { - if (item.buttonMode) { + if (item.__hit && !over) + { + if (item.buttonMode) + { cursor = item.defaultCursor; } - if (!item.interactiveChildren) { + if (!item.interactiveChildren) + { over = true; } - if (!item.__isOver) { - if (item.mouseover) { + if (!item.__isOver) + { + if (item.mouseover) + { item.mouseover (this.mouse); } item.__isOver = true; } } - else { - if (item.__isOver) { + else + { + if (item.__isOver) + { // roll out! - if (item.mouseout) { + if (item.mouseout) + { item.mouseout (this.mouse); } item.__isOver = false; @@ -329,7 +356,8 @@ } } - if (this.currentCursorStyle !== cursor) { + if (this.currentCursorStyle !== cursor) + { this.currentCursorStyle = cursor; this.interactionDOMElement.style.cursor = cursor; } @@ -338,18 +366,21 @@ /** * @private */ -InteractionManager.prototype.rebuildInteractiveGraph = function () { +InteractionManager.prototype.rebuildInteractiveGraph = function () +{ this.dirty = false; var len = this.interactiveItems.length; - for (var i = 0; i < len; i++) { + for (var i = 0; i < len; i++) + { this.interactiveItems[i].interactiveChildren = false; } this.interactiveItems.length = 0; - if (this.stage.interactive) { + if (this.stage.interactive) + { this.interactiveItems.push(this.stage); } @@ -363,8 +394,10 @@ * @param event {Event} The DOM event of the mouse moving * @private */ -InteractionManager.prototype.onMouseMove = function (event) { - if (this.dirty) { +InteractionManager.prototype.onMouseMove = function (event) +{ + if (this.dirty) + { this.rebuildInteractiveGraph(); } @@ -378,11 +411,13 @@ var length = this.interactiveItems.length; - for (var i = 0; i < length; i++) { + for (var i = 0; i < length; i++) + { var item = this.interactiveItems[i]; // Call the function! - if (item.mousemove) { + if (item.mousemove) + { item.mousemove(this.mouse); } } @@ -394,14 +429,17 @@ * @param event {Event} The DOM event of a mouse button being pressed down * @private */ -InteractionManager.prototype.onMouseDown = function (event) { - if (this.dirty) { +InteractionManager.prototype.onMouseDown = function (event) +{ + if (this.dirty) + { this.rebuildInteractiveGraph(); } this.mouse.originalEvent = event; - if (AUTO_PREVENT_DEFAULT) { + if (AUTO_PREVENT_DEFAULT) + { this.mouse.originalEvent.preventDefault(); } @@ -420,22 +458,27 @@ // while // hit test - for (var i = 0; i < length; i++) { + for (var i = 0; i < length; i++) + { var item = this.interactiveItems[i]; - if (item[downFunction] || item[clickFunction]) { + if (item[downFunction] || item[clickFunction]) + { item[buttonIsDown] = true; item.__hit = this.hitTest(item, this.mouse); - if (item.__hit) { + if (item.__hit) + { //call the function! - if (item[downFunction]) { + if (item[downFunction]) + { item[downFunction](this.mouse); } item[isDown] = true; // just the one! - if (!item.interactiveChildren) { + if (!item.interactiveChildren) + { break; } } @@ -449,8 +492,10 @@ * @param event {Event} The DOM event of a mouse being moved out * @private */ -InteractionManager.prototype.onMouseOut = function (event) { - if (this.dirty) { +InteractionManager.prototype.onMouseOut = function (event) +{ + if (this.dirty) + { this.rebuildInteractiveGraph(); } @@ -460,11 +505,14 @@ this.interactionDOMElement.style.cursor = 'inherit'; - for (var i = 0; i < length; i++) { + for (var i = 0; i < length; i++) + { var item = this.interactiveItems[i]; - if (item.__isOver) { + if (item.__isOver) + { this.mouse.target = item; - if (item.mouseout) { + if (item.mouseout) + { item.mouseout(this.mouse); } item.__isOver = false; @@ -484,8 +532,10 @@ * @param event {Event} The DOM event of a mouse button being released * @private */ -InteractionManager.prototype.onMouseUp = function (event) { - if (this.dirty) { +InteractionManager.prototype.onMouseUp = function (event) +{ + if (this.dirty) + { this.rebuildInteractiveGraph(); } @@ -502,30 +552,40 @@ var upOutsideFunction = isRightButton ? 'rightupoutside' : 'mouseupoutside'; var isDown = isRightButton ? '__isRightDown' : '__isDown'; - for (var i = 0; i < length; i++) { + for (var i = 0; i < length; i++) + { var item = this.interactiveItems[i]; - if (item[clickFunction] || item[upFunction] || item[upOutsideFunction]) { + if (item[clickFunction] || item[upFunction] || item[upOutsideFunction]) + { item.__hit = this.hitTest(item, this.mouse); - if (item.__hit && !up) { + if (item.__hit && !up) + { //call the function! - if (item[upFunction]) { + if (item[upFunction]) + { item[upFunction](this.mouse); } - if (item[isDown]) { - if (item[clickFunction]) { + if (item[isDown]) + { + if (item[clickFunction]) + { item[clickFunction](this.mouse); } } - if (!item.interactiveChildren) { + if (!item.interactiveChildren) + { up = true; } } - else { - if (item[isDown]) { - if (item[upOutsideFunction]) { + else + { + if (item[isDown]) + { + if (item[upOutsideFunction]) + { item[upOutsideFunction](this.mouse); } } @@ -543,10 +603,12 @@ * @param interactionData {InteractionData} The interactionData object to update in the case there is a hit * @private */ -InteractionManager.prototype.hitTest = function (item, interactionData) { +InteractionManager.prototype.hitTest = function (item, interactionData) +{ var global = interactionData.global; - if (!item.worldVisible) { + if (!item.worldVisible) + { return false; } @@ -560,37 +622,46 @@ interactionData.target = item; //a sprite or display object with a hit area defined - if (item.hitArea && item.hitArea.contains) { + if (item.hitArea && item.hitArea.contains) + { return item.hitArea.contains(x, y); } // a sprite with no hitarea defined - else if (item instanceof core.Sprite) { + else if (item instanceof core.Sprite) + { var width = item.texture.frame.width; var height = item.texture.frame.height; var x1 = -width * item.anchor.x; var y1; - if (x > x1 && x < x1 + width) { + if (x > x1 && x < x1 + width) + { y1 = -height * item.anchor.y; - if (y > y1 && y < y1 + height) { + if (y > y1 && y < y1 + height) + { // set the target property if a hit is true! return true; } } } - else if (item instanceof core.Graphics) { + else if (item instanceof core.Graphics) + { var graphicsData = item.graphicsData; - for (i = 0; i < graphicsData.length; i++) { + for (i = 0; i < graphicsData.length; i++) + { var data = graphicsData[i]; - if (!data.fill) { + if (!data.fill) + { continue; } // only deal with fills.. - if (data.shape) { - if (data.shape.contains(x, y)) { + if (data.shape) + { + if (data.shape.contains(x, y)) + { //interactionData.target = item; return true; } @@ -600,10 +671,12 @@ var length = item.children.length; - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { var tempItem = item.children[i]; var hit = this.hitTest(tempItem, interactionData); - if (hit) { + if (hit) + { // hmm.. TODO SET CORRECT TARGET? interactionData.target = item; return true; @@ -618,8 +691,10 @@ * @param event {Event} The DOM event of a touch moving across the renderer view * @private */ -InteractionManager.prototype.onTouchMove = function (event) { - if (this.dirty) { +InteractionManager.prototype.onTouchMove = function (event) +{ + if (this.dirty) + { this.rebuildInteractiveGraph(); } @@ -628,7 +703,8 @@ var touchData; var i = 0; - for (i = 0; i < changedTouches.length; i++) { + for (i = 0; i < changedTouches.length; i++) + { var touchEvent = changedTouches[i]; touchData = this.touches[touchEvent.identifier]; touchData.originalEvent = event; @@ -636,15 +712,18 @@ // update the touch position touchData.global.x = ( (touchEvent.clientX - rect.left) * (this.interactionDOMElement.width / rect.width) ) / this.resolution; touchData.global.y = ( (touchEvent.clientY - rect.top) * (this.interactionDOMElement.height / rect.height) ) / this.resolution; - if (navigator.isCocoonJS && !rect.left && !rect.top && !event.target.style.width && !event.target.style.height) { + if (navigator.isCocoonJS && !rect.left && !rect.top && !event.target.style.width && !event.target.style.height) + { //Support for CocoonJS fullscreen scale modes touchData.global.x = touchEvent.clientX; touchData.global.y = touchEvent.clientY; } - for (var j = 0; j < this.interactiveItems.length; j++) { + for (var j = 0; j < this.interactiveItems.length; j++) + { var item = this.interactiveItems[j]; - if (item.touchmove && item.__touchData && item.__touchData[touchEvent.identifier]) { + if (item.touchmove && item.__touchData && item.__touchData[touchEvent.identifier]) + { item.touchmove(touchData); } } @@ -657,23 +736,28 @@ * @param event {Event} The DOM event of a touch starting on the renderer view * @private */ -InteractionManager.prototype.onTouchStart = function (event) { - if (this.dirty) { +InteractionManager.prototype.onTouchStart = function (event) +{ + if (this.dirty) + { this.rebuildInteractiveGraph(); } var rect = this.interactionDOMElement.getBoundingClientRect(); - if (AUTO_PREVENT_DEFAULT) { + if (AUTO_PREVENT_DEFAULT) + { event.preventDefault(); } var changedTouches = event.changedTouches; - for (var i=0; i < changedTouches.length; i++) { + for (var i=0; i < changedTouches.length; i++) + { var touchEvent = changedTouches[i]; var touchData = this.pool.pop(); - if (!touchData) { + if (!touchData) + { touchData = new InteractionData(); } @@ -682,7 +766,8 @@ this.touches[touchEvent.identifier] = touchData; touchData.global.x = ( (touchEvent.clientX - rect.left) * (this.interactionDOMElement.width / rect.width) ) / this.resolution; touchData.global.y = ( (touchEvent.clientY - rect.top) * (this.interactionDOMElement.height / rect.height) ) / this.resolution; - if (navigator.isCocoonJS && !rect.left && !rect.top && !event.target.style.width && !event.target.style.height) { + if (navigator.isCocoonJS && !rect.left && !rect.top && !event.target.style.width && !event.target.style.height) + { //Support for CocoonJS fullscreen scale modes touchData.global.x = touchEvent.clientX; touchData.global.y = touchEvent.clientY; @@ -690,15 +775,19 @@ var length = this.interactiveItems.length; - for (var j = 0; j < length; j++) { + for (var j = 0; j < length; j++) + { var item = this.interactiveItems[j]; - if (item.touchstart || item.tap) { + if (item.touchstart || item.tap) + { item.__hit = this.hitTest(item, touchData); - if (item.__hit) { + if (item.__hit) + { //call the function! - if (item.touchstart) { + if (item.touchstart) + { item.touchstart(touchData); } @@ -706,7 +795,8 @@ item.__touchData = item.__touchData || {}; item.__touchData[touchEvent.identifier] = touchData; - if (!item.interactiveChildren) { + if (!item.interactiveChildren) + { break; } } @@ -721,31 +811,37 @@ * @param event {Event} The DOM event of a touch ending on the renderer view * @private */ -InteractionManager.prototype.onTouchEnd = function (event) { - if (this.dirty) { +InteractionManager.prototype.onTouchEnd = function (event) +{ + if (this.dirty) + { this.rebuildInteractiveGraph(); } var rect = this.interactionDOMElement.getBoundingClientRect(); var changedTouches = event.changedTouches; - for (var i=0; i < changedTouches.length; i++) { + for (var i=0; i < changedTouches.length; i++) + { var touchEvent = changedTouches[i]; var touchData = this.touches[touchEvent.identifier]; var up = false; touchData.global.x = ( (touchEvent.clientX - rect.left) * (this.interactionDOMElement.width / rect.width) ) / this.resolution; touchData.global.y = ( (touchEvent.clientY - rect.top) * (this.interactionDOMElement.height / rect.height) ) / this.resolution; - if (navigator.isCocoonJS && !rect.left && !rect.top && !event.target.style.width && !event.target.style.height) { + if (navigator.isCocoonJS && !rect.left && !rect.top && !event.target.style.width && !event.target.style.height) + { //Support for CocoonJS fullscreen scale modes touchData.global.x = touchEvent.clientX; touchData.global.y = touchEvent.clientY; } var length = this.interactiveItems.length; - for (var j = 0; j < length; j++) { + for (var j = 0; j < length; j++) + { var item = this.interactiveItems[j]; - if (item.__touchData && item.__touchData[touchEvent.identifier]) { + if (item.__touchData && item.__touchData[touchEvent.identifier]) + { item.__hit = this.hitTest(item, item.__touchData[touchEvent.identifier]); @@ -753,20 +849,27 @@ touchData.originalEvent = event; // hitTest?? - if (item.touchend || item.tap) { - if (item.__hit && !up) { - if (item.touchend) { + if (item.touchend || item.tap) + { + if (item.__hit && !up) + { + if (item.touchend) + { item.touchend(touchData); } - if (item.__isDown && item.tap) { + if (item.__isDown && item.tap) + { item.tap(touchData); } - if (!item.interactiveChildren) { + if (!item.interactiveChildren) + { up = true; } } - else { - if (item.__isDown && item.touchendoutside) { + else + { + if (item.__isDown && item.touchendoutside) + { item.touchendoutside(touchData); } } diff --git a/src/loaders/AssetLoader.js b/src/loaders/AssetLoader.js index 20da0cf..c4dba1c 100644 --- a/src/loaders/AssetLoader.js +++ b/src/loaders/AssetLoader.js @@ -21,7 +21,8 @@ * data formats include 'xml' and 'fnt'. * @param crossorigin {boolean} Whether requests should be treated as crossorigin */ -function AssetLoader(assetURLs, crossorigin) { +function AssetLoader(assetURLs, crossorigin) +{ /** * The array of asset URLs that are going to be loaded * @@ -76,16 +77,19 @@ * * @param str {string} the name of the asset */ -AssetLoader.prototype._getDataType = function (str) { +AssetLoader.prototype._getDataType = function (str) +{ var test = 'data:'; var start = str.slice(0, test.length).toLowerCase(); - if (start === test) { + if (start === test) + { var data = str.slice(test.length); var sepIdx = data.indexOf(','); // check for malformed data URI scheme - if (sepIdx === -1) { + if (sepIdx === -1) + { return null; } @@ -94,7 +98,8 @@ //We might need to handle some special cases here... //standardize text/plain to 'txt' file extension - if (!info || info.toLowerCase() === 'text/plain') { + if (!info || info.toLowerCase() === 'text/plain') + { return 'txt'; } @@ -109,27 +114,32 @@ * Starts loading the assets sequentially * */ -AssetLoader.prototype.load = function () { +AssetLoader.prototype.load = function () +{ var scope = this; - function onLoad(evt) { + function onLoad(evt) + { scope.onAssetLoaded(evt.data.content); } this.loadCount = this.assetURLs.length; - for (var i=0; i < this.assetURLs.length; i++) { + for (var i=0; i < this.assetURLs.length; i++) + { var fileName = this.assetURLs[i]; //first see if we have a data URI scheme.. var fileType = this._getDataType(fileName); //if not, assume it's a file URI - if (!fileType) { + if (!fileType) + { fileType = fileName.split('?').shift().split('.').pop().toLowerCase(); } var Constructor = this.loadersByType[fileType]; - if (!Constructor) { + if (!Constructor) + { throw new Error(fileType + ' is an unsupported file type'); } @@ -145,18 +155,22 @@ * * @private */ -AssetLoader.prototype.onAssetLoaded = function (loader) { +AssetLoader.prototype.onAssetLoaded = function (loader) +{ this.loadCount--; this.emit('onProgress', { content: this, loader: loader }); - if (this.onProgress) { + if (this.onProgress) + { this.onProgress(loader); } - if (!this.loadCount) { + if (!this.loadCount) + { this.emit('onComplete', { content: this }); - if (this.onComplete) { + if (this.onComplete) + { this.onComplete(); } } diff --git a/src/loaders/AtlasLoader.js b/src/loaders/AtlasLoader.js index 5eda286..3aec9e2 100644 --- a/src/loaders/AtlasLoader.js +++ b/src/loaders/AtlasLoader.js @@ -15,7 +15,8 @@ * @param url {String} The url of the JSON file * @param crossorigin {boolean} Whether requests should be treated as crossorigin */ -function AtlasLoader(url, crossorigin) { +function AtlasLoader(url, crossorigin) +{ this.url = url; this.baseUrl = url.replace(/[^\/]*$/, ''); this.crossorigin = crossorigin; @@ -31,13 +32,15 @@ * Starts loading the JSON file * */ -AtlasLoader.prototype.load = function () { +AtlasLoader.prototype.load = function () +{ this.ajaxRequest = new core.utils.AjaxRequest(); this.ajaxRequest.onreadystatechange = this.onAtlasLoaded.bind(this); this.ajaxRequest.open('GET', this.url, true); - if (this.ajaxRequest.overrideMimeType) { + if (this.ajaxRequest.overrideMimeType) + { this.ajaxRequest.overrideMimeType('application/json'); } @@ -49,9 +52,12 @@ * * @private */ -AtlasLoader.prototype.onAtlasLoaded = function () { - if (this.ajaxRequest.readyState === 4) { - if (this.ajaxRequest.status === 200 || window.location.href.indexOf('http') === -1) { +AtlasLoader.prototype.onAtlasLoaded = function () +{ + if (this.ajaxRequest.readyState === 4) + { + if (this.ajaxRequest.status === 200 || window.location.href.indexOf('http') === -1) + { this.atlas = { meta : { image : [] @@ -70,34 +76,44 @@ selfOnLoaded = this.onLoaded.bind(this); // parser without rotation support yet! - for (i = 0; i < result.length; i++) { + for (i = 0; i < result.length; i++) + { result[i] = result[i].replace(/^\s+|\s+$/g, ''); - if (result[i] === '') { + if (result[i] === '') + { nameInNextLine = i+1; } - if (result[i].length > 0) { - if (nameInNextLine === i) { + if (result[i].length > 0) + { + if (nameInNextLine === i) + { this.atlas.meta.image.push(result[i]); currentImageId = this.atlas.meta.image.length - 1; this.atlas.frames.push({}); lineCount = -3; - } else if (lineCount > 0) { - if (lineCount % 7 === 1) { // frame name - if (currentFrame != null) { //jshint ignore:line + } else if (lineCount > 0) + { + if (lineCount % 7 === 1) + { // frame name + if (currentFrame != null) + { //jshint ignore:line this.atlas.frames[currentImageId][currentFrame.name] = currentFrame; } currentFrame = { name: result[i], frame : {} }; } else { var text = result[i].split(' '); - if (lineCount % 7 === 3) { // position + if (lineCount % 7 === 3) + { // position currentFrame.frame.x = Number(text[1].replace(',', '')); currentFrame.frame.y = Number(text[2]); - } else if (lineCount % 7 === 4) { // size + } else if (lineCount % 7 === 4) + { // size currentFrame.frame.w = Number(text[1].replace(',', '')); currentFrame.frame.h = Number(text[2]); - } else if (lineCount % 7 === 5) { // real size + } else if (lineCount % 7 === 5) + { // real size var realSize = { x : 0, y : 0, @@ -105,7 +121,8 @@ h : Number(text[2]) }; - if (realSize.w > currentFrame.frame.w || realSize.h > currentFrame.frame.h) { + if (realSize.w > currentFrame.frame.w || realSize.h > currentFrame.frame.h) + { currentFrame.trimmed = true; currentFrame.realSize = realSize; } else { @@ -118,28 +135,34 @@ } } - if (currentFrame != null) { //jshint ignore:line + if (currentFrame != null) + { //jshint ignore:line this.atlas.frames[currentImageId][currentFrame.name] = currentFrame; } - if (this.atlas.meta.image.length > 0) { + if (this.atlas.meta.image.length > 0) + { this.images = []; - for (j = 0; j < this.atlas.meta.image.length; j++) { + for (j = 0; j < this.atlas.meta.image.length; j++) + { // sprite sheet var textureUrl = this.baseUrl + this.atlas.meta.image[j]; var frameData = this.atlas.frames[j]; this.images.push(new ImageLoader(textureUrl, this.crossorigin)); - for (i in frameData) { + for (i in frameData) + { var rect = frameData[i].frame; - if (rect) { + if (rect) + { core.utils.TextureCache[i] = new core.Texture(this.images[j].texture.baseTexture, { x: rect.x, y: rect.y, width: rect.w, height: rect.h }); - if (frameData[i].trimmed) { + if (frameData[i].trimmed) + { core.utils.TextureCache[i].realSize = frameData[i].realSize; // trim in pixi not supported yet, todo update trim properties if it is done ... core.utils.TextureCache[i].trim.x = 0; @@ -150,7 +173,8 @@ } this.currentImageId = 0; - for (j = 0; j < this.images.length; j++) { + for (j = 0; j < this.images.length; j++) + { this.images[j].on('loaded', selfOnLoaded); } this.images[this.currentImageId].load(); @@ -170,8 +194,10 @@ * * @private */ -AtlasLoader.prototype.onLoaded = function () { - if (this.images.length - 1 > this.currentImageId) { +AtlasLoader.prototype.onLoaded = function () +{ + if (this.images.length - 1 > this.currentImageId) + { this.currentImageId++; this.images[this.currentImageId].load(); } else { @@ -185,6 +211,7 @@ * * @private */ -AtlasLoader.prototype.onError = function () { +AtlasLoader.prototype.onError = function () +{ this.emit('error', { content: this }); }; diff --git a/src/loaders/BitmapFontLoader.js b/src/loaders/BitmapFontLoader.js index 8641760..13e5c1b 100644 --- a/src/loaders/BitmapFontLoader.js +++ b/src/loaders/BitmapFontLoader.js @@ -13,7 +13,8 @@ * @param url {String} The url of the sprite sheet JSON file * @param crossorigin {boolean} Whether requests should be treated as crossorigin */ -function BitmapFontLoader(url, crossorigin) { +function BitmapFontLoader(url, crossorigin) +{ /** * The url of the bitmap font data * @@ -54,13 +55,15 @@ * Loads the XML font data * */ -BitmapFontLoader.prototype.load = function () { +BitmapFontLoader.prototype.load = function () +{ this.ajaxRequest = new core.utils.AjaxRequest(); this.ajaxRequest.onreadystatechange = this.onXMLLoaded.bind(this); this.ajaxRequest.open('GET', this.url, true); - if (this.ajaxRequest.overrideMimeType) { + if (this.ajaxRequest.overrideMimeType) + { this.ajaxRequest.overrideMimeType('application/xml'); } @@ -72,12 +75,17 @@ * * @private */ -BitmapFontLoader.prototype.onXMLLoaded = function () { - if (this.ajaxRequest.readyState === 4) { - if (this.ajaxRequest.status === 200 || window.location.protocol.indexOf('http') === -1) { +BitmapFontLoader.prototype.onXMLLoaded = function () +{ + if (this.ajaxRequest.readyState === 4) + { + if (this.ajaxRequest.status === 200 || window.location.protocol.indexOf('http') === -1) + { var responseXML = this.ajaxRequest.responseXML; - if (!responseXML || /MSIE 9/i.test(navigator.userAgent) || navigator.isCocoonJS) { - if (typeof(window.DOMParser) === 'function') { + if (!responseXML || /MSIE 9/i.test(navigator.userAgent) || navigator.isCocoonJS) + { + if (typeof(window.DOMParser) === 'function') + { var domparser = new DOMParser(); responseXML = domparser.parseFromString(this.ajaxRequest.responseText, 'text/xml'); } else { @@ -102,7 +110,8 @@ //parse letters var letters = responseXML.getElementsByTagName('char'); - for (var i = 0; i < letters.length; i++) { + for (var i = 0; i < letters.length; i++) + { var charCode = parseInt(letters[i].getAttribute('id'), 10); var textureRect = new core.math.Rectangle( @@ -124,7 +133,8 @@ //parse kernings var kernings = responseXML.getElementsByTagName('kerning'); - for (i = 0; i < kernings.length; i++) { + for (i = 0; i < kernings.length; i++) + { var first = parseInt(kernings[i].getAttribute('first'), 10); var second = parseInt(kernings[i].getAttribute('second'), 10); var amount = parseInt(kernings[i].getAttribute('amount'), 10); @@ -146,6 +156,7 @@ * * @private */ -BitmapFontLoader.prototype.onLoaded = function () { +BitmapFontLoader.prototype.onLoaded = function () +{ this.emit('loaded', { content: this }); }; diff --git a/src/loaders/ImageLoader.js b/src/loaders/ImageLoader.js index e3ff493..16ee7c8 100644 --- a/src/loaders/ImageLoader.js +++ b/src/loaders/ImageLoader.js @@ -11,7 +11,8 @@ * @param url {String} The url of the image * @param crossorigin {boolean} Whether requests should be treated as crossorigin */ -function ImageLoader(url, crossorigin) { +function ImageLoader(url, crossorigin) +{ /** * The texture being loaded * @@ -39,12 +40,15 @@ * Loads image or takes it from cache * */ -ImageLoader.prototype.load = function () { - if (!this.texture.baseTexture.hasLoaded) { +ImageLoader.prototype.load = function () +{ + if (!this.texture.baseTexture.hasLoaded) + { this.texture.baseTexture.on('loaded', this.onLoaded.bind(this)); this.texture.baseTexture.on('error', this.onError.bind(this)); } - else { + else + { this.onLoaded(); } }; @@ -54,7 +58,8 @@ * * @private */ -ImageLoader.prototype.onLoaded = function () { +ImageLoader.prototype.onLoaded = function () +{ this.emit('loaded', { content: this }); }; @@ -64,7 +69,8 @@ * @method onError * @private */ -ImageLoader.prototype.onError = function () { +ImageLoader.prototype.onError = function () +{ this.emit('error', { content: this }); }; @@ -75,15 +81,18 @@ * @param frameHeight {number} height of each frame * @param textureName {String} if given, the frames will be cached in - format */ -ImageLoader.prototype.loadFramedSpriteSheet = function (frameWidth, frameHeight, textureName) { +ImageLoader.prototype.loadFramedSpriteSheet = function (frameWidth, frameHeight, textureName) +{ this.frames = []; var cols = Math.floor(this.texture.width / frameWidth); var rows = Math.floor(this.texture.height / frameHeight); var i=0; - for (var y = 0; y < rows; ++y) { - for (var x = 0; x < cols; ++x, ++i) { + for (var y = 0; y < rows; ++y) + { + for (var x = 0; x < cols; ++x, ++i) + { var texture = new core.Texture( this.texture.baseTexture, new core.math.Rectangle( @@ -96,7 +105,8 @@ this.frames.push(texture); - if (textureName) { + if (textureName) + { core.utils.TextureCache[textureName + '-' + i] = texture; } } diff --git a/src/loaders/JsonLoader.js b/src/loaders/JsonLoader.js index 3279f40..7aabeb4 100644 --- a/src/loaders/JsonLoader.js +++ b/src/loaders/JsonLoader.js @@ -14,7 +14,8 @@ * @param url {String} The url of the JSON file * @param crossorigin {boolean} Whether requests should be treated as crossorigin */ -function JsonLoader(url, crossorigin) { +function JsonLoader(url, crossorigin) +{ /** * The url of the bitmap font data * @@ -56,8 +57,10 @@ * Loads the JSON data * */ -JsonLoader.prototype.load = function () { - if (window.XDomainRequest && this.crossorigin) { +JsonLoader.prototype.load = function () +{ + if (window.XDomainRequest && this.crossorigin) + { this.ajaxRequest = new window.XDomainRequest(); // XDomainRequest has a few quirks. Occasionally it will abort requests @@ -68,15 +71,19 @@ this.ajaxRequest.onerror = this.onError.bind(this); this.ajaxRequest.ontimeout = this.onError.bind(this); - this.ajaxRequest.onprogress = function () {}; + this.ajaxRequest.onprogress = function () + {}; this.ajaxRequest.onload = this.onJSONLoaded.bind(this); } - else { - if (window.XMLHttpRequest) { + else + { + if (window.XMLHttpRequest) + { this.ajaxRequest = new window.XMLHttpRequest(); } - else { + else + { this.ajaxRequest = new window.ActiveXObject('Microsoft.XMLHTTP'); } @@ -93,8 +100,10 @@ * * @private */ -JsonLoader.prototype.onReadyStateChanged = function () { - if (this.ajaxRequest.readyState === 4 && (this.ajaxRequest.status === 200 || window.location.href.indexOf('http') === -1)) { +JsonLoader.prototype.onReadyStateChanged = function () +{ + if (this.ajaxRequest.readyState === 4 && (this.ajaxRequest.status === 200 || window.location.href.indexOf('http') === -1)) + { this.onJSONLoaded(); } }; @@ -104,15 +113,18 @@ * * @private */ -JsonLoader.prototype.onJSONLoaded = function () { - if (!this.ajaxRequest.responseText) { +JsonLoader.prototype.onJSONLoaded = function () +{ + if (!this.ajaxRequest.responseText) + { this.onError(); return; } this.json = JSON.parse(this.ajaxRequest.responseText); - if (this.json.frames) { + if (this.json.frames) + { // sprite sheet var textureUrl = this.baseUrl + this.json.meta.image; var image = new ImageLoader(textureUrl, this.crossorigin); @@ -122,16 +134,19 @@ image.addEventListener('loaded', this.onLoaded.bind(this)); image.addEventListener('error', this.onError.bind(this)); - for (var i in frameData) { + for (var i in frameData) + { var rect = frameData[i].frame; - if (rect) { + if (rect) + { var textureSize = new core.math.Rectangle(rect.x, rect.y, rect.w, rect.h); var crop = textureSize.clone(); var trim = null; // Check to see if the sprite is trimmed - if (frameData[i].trimmed) { + if (frameData[i].trimmed) + { var actualSize = frameData[i].sourceSize; var realSize = frameData[i].spriteSourceSize; trim = new core.math.Rectangle(realSize.x, realSize.y, actualSize.w, actualSize.h); @@ -143,12 +158,15 @@ image.load(); } - else if (this.json.bones) { + else if (this.json.bones) + { // check if the json was loaded before - if (core.utils.AnimCache[this.url]) { + if (core.utils.AnimCache[this.url]) + { this.onLoaded(); } - else { + else + { /** * use a bit of hackery to load the atlas file, here we assume that the .json, .atlas and .png files * that correspond to the spine file are in the same base URL and that the .json and .atlas files @@ -159,9 +177,11 @@ // save a copy of the current object for future reference // var originalLoader = this; // before loading the file, replace the "onJSONLoaded" function for our own // - atlasLoader.onJSONLoaded = function () { + atlasLoader.onJSONLoaded = function () + { // at this point "this" points at the atlasLoader (JsonLoader) instance // - if (!this.ajaxRequest.responseText) { + if (!this.ajaxRequest.responseText) + { this.onError(); // FIXME: hmm, this is funny because we are not responding to errors yet return; } @@ -179,14 +199,18 @@ originalLoader.spineAtlas = spineAtlas; originalLoader.spineAtlasLoader = atlasLoader; // wait for textures to finish loading if needed - if (textureLoader.loadingCount > 0) { - textureLoader.addEventListener('loadedBaseTexture', function (evt){ - if (evt.content.content.loadingCount <= 0) { + if (textureLoader.loadingCount > 0) + { + textureLoader.addEventListener('loadedBaseTexture', function (evt) + { + if (evt.content.content.loadingCount <= 0) + { originalLoader.onLoaded(); } }); } - else { + else + { originalLoader.onLoaded(); } }; @@ -194,7 +218,8 @@ atlasLoader.load(); } } - else { + else + { this.onLoaded(); } }; @@ -204,7 +229,8 @@ * * @private */ -JsonLoader.prototype.onLoaded = function () { +JsonLoader.prototype.onLoaded = function () +{ this.loaded = true; this.dispatchEvent({ type: 'loaded', @@ -217,7 +243,8 @@ * * @private */ -JsonLoader.prototype.onError = function () { +JsonLoader.prototype.onError = function () +{ this.dispatchEvent({ type: 'error', diff --git a/src/loaders/SpineLoader.js b/src/loaders/SpineLoader.js index 51aaddb..69bae21 100644 --- a/src/loaders/SpineLoader.js +++ b/src/loaders/SpineLoader.js @@ -24,7 +24,8 @@ * @param url {String} The url of the JSON file * @param crossorigin {boolean} Whether requests should be treated as crossorigin */ -function SpineLoader(url, crossorigin) { +function SpineLoader(url, crossorigin) +{ /** * The url of the bitmap font data * @@ -57,11 +58,13 @@ * Loads the JSON data * */ -SpineLoader.prototype.load = function () { +SpineLoader.prototype.load = function () +{ var scope = this; var jsonLoader = new JsonLoader(this.url, this.crossorigin); - jsonLoader.on('loaded', function (event) { + jsonLoader.on('loaded', function (event) + { scope.json = event.data.content.json; scope.onLoaded(); }); @@ -74,7 +77,8 @@ * * @private */ -SpineLoader.prototype.onLoaded = function () { +SpineLoader.prototype.onLoaded = function () +{ this.loaded = true; this.emit('loaded', { content: this }); }; diff --git a/src/loaders/SpineTextureLoader.js b/src/loaders/SpineTextureLoader.js index 61c51c0..c09a548 100644 --- a/src/loaders/SpineTextureLoader.js +++ b/src/loaders/SpineTextureLoader.js @@ -9,7 +9,8 @@ * @param basePath {string} Tha base path where to look for the images to be loaded * @param crossorigin {boolean} Whether requests should be treated as crossorigin */ -function SpineTextureLoader(basePath, crossorigin) { +function SpineTextureLoader(basePath, crossorigin) +{ this.basePath = basePath; this.crossorigin = crossorigin; this.loadingCount = 0; @@ -26,12 +27,15 @@ * @param page {spine.AtlasPage} Atlas page to which texture belongs * @param file {string} The file to load, this is just the file path relative to the base path configured in the constructor */ -SpineTextureLoader.prototype.load = function (page, file) { +SpineTextureLoader.prototype.load = function (page, file) +{ page.rendererObject = core.BaseTexture.fromImage(this.basePath + '/' + file, this.crossorigin); - if (!page.rendererObject.hasLoaded) { + if (!page.rendererObject.hasLoaded) + { var scope = this; ++scope.loadingCount; - page.rendererObject.addEventListener('loaded', function (){ + page.rendererObject.addEventListener('loaded', function () + { --scope.loadingCount; scope.dispatchEvent({ type: 'loadedBaseTexture', @@ -46,6 +50,7 @@ * * @param texture {BaseTexture} Texture object to destroy */ -SpineTextureLoader.prototype.unload = function (texture) { +SpineTextureLoader.prototype.unload = function (texture) +{ texture.destroy(true); }; diff --git a/src/loaders/SpriteSheetLoader.js b/src/loaders/SpriteSheetLoader.js index 5ee79df..a554e9d 100644 --- a/src/loaders/SpriteSheetLoader.js +++ b/src/loaders/SpriteSheetLoader.js @@ -16,7 +16,8 @@ * @param url {String} The url of the sprite sheet JSON file * @param crossorigin {boolean} Whether requests should be treated as crossorigin */ -function SpriteSheetLoader(url, crossorigin) { +function SpriteSheetLoader(url, crossorigin) +{ /** * The url of the atlas data @@ -65,11 +66,13 @@ * This will begin loading the JSON file * */ -SpriteSheetLoader.prototype.load = function () { +SpriteSheetLoader.prototype.load = function () +{ var scope = this; var jsonLoader = new JsonLoader(this.url, this.crossorigin); - jsonLoader.on('loaded', function (event) { + jsonLoader.on('loaded', function (event) + { scope.json = event.data.content.json; scope.onLoaded(); }); @@ -82,7 +85,8 @@ * * @private */ -SpriteSheetLoader.prototype.onLoaded = function () { +SpriteSheetLoader.prototype.onLoaded = function () +{ this.emit('loaded', { content: this }); diff --git a/src/spine/Spine.js b/src/spine/Spine.js index be7ad18..ce425cc 100644 --- a/src/spine/Spine.js +++ b/src/spine/Spine.js @@ -15,12 +15,14 @@ * @namespace PIXI * @param url {string} The url of the spine anim file to be used */ -function Spine(url) { +function Spine(url) +{ core.DisplayObjectContainer.call(this); this.spineData = core.utils.AnimCache[url]; - if (!this.spineData) { + if (!this.spineData) + { throw new Error('Spine data must be preloaded using SpineLoader or AssetLoader: ' + url); } @@ -32,27 +34,31 @@ this.slotContainers = []; - for (var i = 0, n = this.skeleton.drawOrder.length; i < n; i++) { + for (var i = 0, n = this.skeleton.drawOrder.length; i < n; i++) + { var slot = this.skeleton.drawOrder[i]; var attachment = slot.attachment; var slotContainer = new core.DisplayObjectContainer(); this.slotContainers.push(slotContainer); this.addChild(slotContainer); - if (attachment instanceof spine.RegionAttachment) { + if (attachment instanceof spine.RegionAttachment) + { var spriteName = attachment.rendererObject.name; var sprite = this.createSprite(slot, attachment); slot.currentSprite = sprite; slot.currentSpriteName = spriteName; slotContainer.addChild(sprite); } - else if (attachment instanceof spine.MeshAttachment) { + else if (attachment instanceof spine.MeshAttachment) + { var mesh = this.createMesh(slot, attachment); slot.currentMesh = mesh; slot.currentMeshName = attachment.name; slotContainer.addChild(mesh); } - else { + else + { continue; } @@ -78,11 +84,13 @@ * @default true */ autoUpdate: { - get: function () { + get: function () + { return (this.updateTransform === Spine.prototype.autoUpdateTransform); }, - set: function (value) { + set: function (value) + { this.updateTransform = value ? Spine.prototype.autoUpdateTransform : core.DisplayObjectContainer.prototype.updateTransform; } } @@ -93,35 +101,44 @@ * * @param dt {number} Delta time. Time by which the animation should be updated */ -Spine.prototype.update = function (dt) { +Spine.prototype.update = function (dt) +{ this.state.update(dt); this.state.apply(this.skeleton); this.skeleton.updateWorldTransform(); var drawOrder = this.skeleton.drawOrder; - for (var i = 0, n = drawOrder.length; i < n; i++) { + for (var i = 0, n = drawOrder.length; i < n; i++) + { var slot = drawOrder[i]; var attachment = slot.attachment; var slotContainer = this.slotContainers[i]; - if (!attachment) { + if (!attachment) + { slotContainer.visible = false; continue; } var type = attachment.type; - if (type === spine.AttachmentType.region) { - if (attachment.rendererObject) { - if (!slot.currentSpriteName || slot.currentSpriteName !== attachment.rendererObject.name) { + if (type === spine.AttachmentType.region) + { + if (attachment.rendererObject) + { + if (!slot.currentSpriteName || slot.currentSpriteName !== attachment.rendererObject.name) + { var spriteName = attachment.rendererObject.name; - if (slot.currentSprite !== undefined) { + if (slot.currentSprite !== undefined) + { slot.currentSprite.visible = false; } slot.sprites = slot.sprites || {}; - if (slot.sprites[spriteName] !== undefined) { + if (slot.sprites[spriteName] !== undefined) + { slot.sprites[spriteName].visible = true; } - else { + else + { var sprite = this.createSprite(slot, attachment); slotContainer.addChild(sprite); } @@ -141,19 +158,24 @@ slot.currentSprite.tint = core.utils.rgb2hex([slot.r,slot.g,slot.b]); } - else if (type === spine.AttachmentType.skinnedmesh) { - if (!slot.currentMeshName || slot.currentMeshName !== attachment.name) { + else if (type === spine.AttachmentType.skinnedmesh) + { + if (!slot.currentMeshName || slot.currentMeshName !== attachment.name) + { var meshName = attachment.name; - if (slot.currentMesh !== undefined) { + if (slot.currentMesh !== undefined) + { slot.currentMesh.visible = false; } slot.meshes = slot.meshes || {}; - if (slot.meshes[meshName] !== undefined) { + if (slot.meshes[meshName] !== undefined) + { slot.meshes[meshName].visible = true; } - else { + else + { var mesh = this.createMesh(slot, attachment); slotContainer.addChild(mesh); } @@ -165,7 +187,8 @@ attachment.computeWorldVertices(slot.bone.skeleton.x, slot.bone.skeleton.y, slot, slot.currentMesh.vertices); } - else { + else + { slotContainer.visible = false; continue; } @@ -180,7 +203,8 @@ * * @private */ -Spine.prototype.autoUpdateTransform = function () { +Spine.prototype.autoUpdateTransform = function () +{ this.lastTime = this.lastTime || Date.now(); var timeDelta = (Date.now() - this.lastTime) * 0.001; this.lastTime = Date.now(); @@ -197,7 +221,8 @@ * @param attachment {spine.RegionAttachment} The attachment that the sprite will represent * @private */ -Spine.prototype.createSprite = function (slot, attachment) { +Spine.prototype.createSprite = function (slot, attachment) +{ var descriptor = attachment.rendererObject; var baseTexture = descriptor.page.rendererObject; var spriteRect = new core.math.Rectangle(descriptor.x, @@ -223,7 +248,8 @@ * @param attachment {spine.RegionAttachment} The attachment that the sprite will represent * @private */ -Spine.prototype.createMesh = function (slot, attachment) { +Spine.prototype.createMesh = function (slot, attachment) +{ var descriptor = attachment.rendererObject; var baseTexture = descriptor.page.rendererObject; var texture = new core.Texture(baseTexture); diff --git a/src/spine/SpineRuntime.js b/src/spine/SpineRuntime.js index 392a878..fadd1b5 100644 --- a/src/spine/SpineRuntime.js +++ b/src/spine/SpineRuntime.js @@ -36,7 +36,8 @@ Uint16Array: (typeof(Uint16Array) === 'undefined') ? Array : Uint16Array }; -spine.BoneData = function (name, parent) { +spine.BoneData = function (name, parent) +{ this.name = name; this.parent = parent; }; @@ -50,7 +51,8 @@ flipX: false, flipY: false }; -spine.SlotData = function (name, boneData) { +spine.SlotData = function (name, boneData) +{ this.name = name; this.boneData = boneData; }; @@ -60,7 +62,8 @@ additiveBlending: false }; -spine.IkConstraintData = function (name) { +spine.IkConstraintData = function (name) +{ this.name = name; this.bones = []; }; @@ -70,7 +73,8 @@ mix: 1 }; -spine.Bone = function (boneData, skeleton, parent) { +spine.Bone = function (boneData, skeleton, parent) +{ this.data = boneData; this.skeleton = skeleton; this.parent = parent; @@ -87,12 +91,15 @@ worldRotation: 0, worldScaleX: 1, worldScaleY: 1, worldFlipX: false, worldFlipY: false, - updateWorldTransform: function () { + updateWorldTransform: function () + { var parent = this.parent; - if (parent) { + if (parent) + { this.worldX = this.x * parent.m00 + this.y * parent.m01 + parent.worldX; this.worldY = this.x * parent.m10 + this.y * parent.m11 + parent.worldY; - if (this.data.inheritScale) { + if (this.data.inheritScale) + { this.worldScaleX = parent.worldScaleX * this.scaleX; this.worldScaleY = parent.worldScaleY * this.scaleY; } else { @@ -115,14 +122,16 @@ var radians = this.worldRotation * spine.degRad; var cos = Math.cos(radians); var sin = Math.sin(radians); - if (this.worldFlipX) { + if (this.worldFlipX) + { this.m00 = -cos * this.worldScaleX; this.m01 = sin * this.worldScaleY; } else { this.m00 = cos * this.worldScaleX; this.m01 = -sin * this.worldScaleY; } - if (this.worldFlipY != spine.Bone.yDown) { + if (this.worldFlipY != spine.Bone.yDown) + { this.m10 = -sin * this.worldScaleX; this.m11 = -cos * this.worldScaleY; } else { @@ -130,7 +139,8 @@ this.m11 = cos * this.worldScaleY; } }, - setToSetupPose: function () { + setToSetupPose: function () + { var data = this.data; this.x = data.x; this.y = data.y; @@ -141,10 +151,12 @@ this.flipX = data.flipX; this.flipY = data.flipY; }, - worldToLocal: function (world) { + worldToLocal: function (world) + { var dx = world[0] - this.worldX, dy = world[1] - this.worldY; var m00 = this.m00, m10 = this.m10, m01 = this.m01, m11 = this.m11; - if (this.worldFlipX != (this.worldFlipY != spine.Bone.yDown)) { + if (this.worldFlipX != (this.worldFlipY != spine.Bone.yDown)) + { m00 = -m00; m11 = -m11; } @@ -152,14 +164,16 @@ world[0] = dx * m00 * invDet - dy * m01 * invDet; world[1] = dy * m11 * invDet - dx * m10 * invDet; }, - localToWorld: function (local) { + localToWorld: function (local) + { var localX = local[0], localY = local[1]; local[0] = localX * this.m00 + localY * this.m01 + this.worldX; local[1] = localX * this.m10 + localY * this.m11 + this.worldY; } }; -spine.Slot = function (slotData, bone) { +spine.Slot = function (slotData, bone) +{ this.data = slotData; this.bone = bone; this.setToSetupPose(); @@ -169,18 +183,22 @@ _attachmentTime: 0, attachment: null, attachmentVertices: [], - setAttachment: function (attachment) { + setAttachment: function (attachment) + { this.attachment = attachment; this._attachmentTime = this.bone.skeleton.time; this.attachmentVertices.length = 0; }, - setAttachmentTime: function (time) { + setAttachmentTime: function (time) + { this._attachmentTime = this.bone.skeleton.time - time; }, - getAttachmentTime: function () { + getAttachmentTime: function () + { return this.bone.skeleton.time - this._attachmentTime; }, - setToSetupPose: function () { + setToSetupPose: function () + { var data = this.data; this.r = data.r; this.g = data.g; @@ -188,8 +206,10 @@ this.a = data.a; var slotDatas = this.bone.skeleton.data.slots; - for (var i = 0, n = slotDatas.length; i < n; i++) { - if (slotDatas[i] == data) { + for (var i = 0, n = slotDatas.length; i < n; i++) + { + if (slotDatas[i] == data) + { this.setAttachment(!data.attachmentName ? null : this.bone.skeleton.getAttachmentBySlotIndex(i, data.attachmentName)); break; } @@ -197,7 +217,8 @@ } }; -spine.IkConstraint = function (data, skeleton) { +spine.IkConstraint = function (data, skeleton) +{ this.data = data; this.mix = data.mix; this.bendDirection = data.bendDirection; @@ -208,10 +229,12 @@ this.target = skeleton.findBone(data.target.name); }; spine.IkConstraint.prototype = { - apply: function () { + apply: function () + { var target = this.target; var bones = this.bones; - switch (bones.length) { + switch (bones.length) + { case 1: spine.IkConstraint.apply1(bones[0], target.worldX, target.worldY, this.mix); break; @@ -223,7 +246,8 @@ }; /** Adjusts the bone rotation so the tip is as close to the target position as possible. The target is specified in the world * coordinate system. */ -spine.IkConstraint.apply1 = function (bone, targetX, targetY, alpha) { +spine.IkConstraint.apply1 = function (bone, targetX, targetY, alpha) +{ var parentRotation = (!bone.data.inheritRotation || !bone.parent) ? 0 : bone.parent.worldRotation; var rotation = bone.rotation; var rotationIK = Math.atan2(targetY - bone.worldY, targetX - bone.worldX) * spine.radDeg - parentRotation; @@ -232,16 +256,19 @@ /** Adjusts the parent and child bone rotations so the tip of the child is as close to the target position as possible. The * target is specified in the world coordinate system. * @param child Any descendant bone of the parent. */ -spine.IkConstraint.apply2 = function (parent, child, targetX, targetY, bendDirection, alpha) { +spine.IkConstraint.apply2 = function (parent, child, targetX, targetY, bendDirection, alpha) +{ var childRotation = child.rotation, parentRotation = parent.rotation; - if (!alpha) { + if (!alpha) + { child.rotationIK = childRotation; parent.rotationIK = parentRotation; return; } var positionX, positionY, tempPosition = spine.temp; var parentParent = parent.parent; - if (parentParent) { + if (parentParent) + { tempPosition[0] = targetX; tempPosition[1] = targetY; parentParent.worldToLocal(tempPosition); @@ -251,7 +278,8 @@ targetX -= parent.x; targetY -= parent.y; } - if (child.parent == parent) { + if (child.parent == parent) + { positionX = child.x; positionY = child.y; } else { @@ -267,7 +295,8 @@ var len1 = Math.sqrt(childX * childX + childY * childY), len2 = child.data.length * child.worldScaleX; // Based on code by Ryan Juckett with permission: Copyright (c) 2008-2009 Ryan Juckett, http://www.ryanjuckett.com/ var cosDenom = 2 * len1 * len2; - if (cosDenom < 0.0001) { + if (cosDenom < 0.0001) + { child.rotationIK = childRotation + (Math.atan2(targetY, targetX) * spine.radDeg - parentRotation - childRotation) * alpha; return; } @@ -293,24 +322,30 @@ child.rotationIK = childRotation + (rotation + parent.worldRotation - child.parent.worldRotation) * alpha; }; -spine.Skin = function (name) { +spine.Skin = function (name) +{ this.name = name; this.attachments = {}; }; spine.Skin.prototype = { - addAttachment: function (slotIndex, name, attachment) { + addAttachment: function (slotIndex, name, attachment) + { this.attachments[slotIndex + ":" + name] = attachment; }, - getAttachment: function (slotIndex, name) { + getAttachment: function (slotIndex, name) + { return this.attachments[slotIndex + ":" + name]; }, - _attachAll: function (skeleton, oldSkin) { - for (var key in oldSkin.attachments) { + _attachAll: function (skeleton, oldSkin) + { + for (var key in oldSkin.attachments) + { var colon = key.indexOf(":"); var slotIndex = parseInt(key.substring(0, colon)); var name = key.substring(colon + 1); var slot = skeleton.slots[slotIndex]; - if (slot.attachment && slot.attachment.name == name) { + if (slot.attachment && slot.attachment.name == name) + { var attachment = this.getAttachment(slotIndex, name); if (attachment) slot.setAttachment(attachment); } @@ -318,14 +353,17 @@ } }; -spine.Animation = function (name, timelines, duration) { +spine.Animation = function (name, timelines, duration) +{ this.name = name; this.timelines = timelines; this.duration = duration; }; spine.Animation.prototype = { - apply: function (skeleton, lastTime, time, loop, events) { - if (loop && this.duration != 0) { + apply: function (skeleton, lastTime, time, loop, events) + { + if (loop && this.duration != 0) + { time %= this.duration; lastTime %= this.duration; } @@ -333,8 +371,10 @@ for (var i = 0, n = timelines.length; i < n; i++) timelines[i].apply(skeleton, lastTime, time, events, 1); }, - mix: function (skeleton, lastTime, time, loop, events, alpha) { - if (loop && this.duration != 0) { + mix: function (skeleton, lastTime, time, loop, events, alpha) + { + if (loop && this.duration != 0) + { time %= this.duration; lastTime %= this.duration; } @@ -343,12 +383,14 @@ timelines[i].apply(skeleton, lastTime, time, events, alpha); } }; -spine.Animation.binarySearch = function (values, target, step) { +spine.Animation.binarySearch = function (values, target, step) +{ var low = 0; var high = Math.floor(values.length / step) - 2; if (!high) return step; var current = high >>> 1; - while (true) { + while (true) + { if (values[(current + 1) * step] <= target) low = current + 1; else @@ -357,12 +399,14 @@ current = (low + high) >>> 1; } }; -spine.Animation.binarySearch1 = function (values, target) { +spine.Animation.binarySearch1 = function (values, target) +{ var low = 0; var high = values.length - 2; if (!high) return 1; var current = high >>> 1; - while (true) { + while (true) + { if (values[current + 1] <= target) low = current + 1; else @@ -371,27 +415,32 @@ current = (low + high) >>> 1; } }; -spine.Animation.linearSearch = function (values, target, step) { +spine.Animation.linearSearch = function (values, target, step) +{ for (var i = 0, last = values.length - step; i <= last; i += step) if (values[i] > target) return i; return -1; }; -spine.Curves = function (frameCount) { +spine.Curves = function (frameCount) +{ this.curves = []; // type, x, y, ... //this.curves.length = (frameCount - 1) * 19/*BEZIER_SIZE*/; }; spine.Curves.prototype = { - setLinear: function (frameIndex) { + setLinear: function (frameIndex) + { this.curves[frameIndex * 19/*BEZIER_SIZE*/] = 0/*LINEAR*/; }, - setStepped: function (frameIndex) { + setStepped: function (frameIndex) + { this.curves[frameIndex * 19/*BEZIER_SIZE*/] = 1/*STEPPED*/; }, /** Sets the control handle positions for an interpolation bezier curve used to transition from this keyframe to the next. * cx1 and cx2 are from 0 to 1, representing the percent of time between the two keyframes. cy1 and cy2 are the percent of * the difference between the keyframe's values. */ - setCurve: function (frameIndex, cx1, cy1, cx2, cy2) { + setCurve: function (frameIndex, cx1, cy1, cx2, cy2) + { var subdiv1 = 1 / 10/*BEZIER_SEGMENTS*/, subdiv2 = subdiv1 * subdiv1, subdiv3 = subdiv2 * subdiv1; var pre1 = 3 * subdiv1, pre2 = 3 * subdiv2, pre4 = 6 * subdiv2, pre5 = 6 * subdiv3; var tmp1x = -cx1 * 2 + cx2, tmp1y = -cy1 * 2 + cy2, tmp2x = (cx1 - cx2) * 3 + 1, tmp2y = (cy1 - cy2) * 3 + 1; @@ -404,7 +453,8 @@ curves[i++] = 2/*BEZIER*/; var x = dfx, y = dfy; - for (var n = i + 19/*BEZIER_SIZE*/ - 1; i < n; i += 2) { + for (var n = i + 19/*BEZIER_SIZE*/ - 1; i < n; i += 2) + { curves[i] = x; curves[i + 1] = y; dfx += ddfx; @@ -415,7 +465,8 @@ y += dfy; } }, - getCurvePercent: function (frameIndex, percent) { + getCurvePercent: function (frameIndex, percent) + { percent = percent < 0 ? 0 : (percent > 1 ? 1 : percent); var curves = this.curves; var i = frameIndex * 19/*BEZIER_SIZE*/; @@ -424,11 +475,14 @@ if (type == 1/*STEPPED*/) return 0; i++; var x = 0; - for (var start = i, n = i + 19/*BEZIER_SIZE*/ - 1; i < n; i += 2) { + for (var start = i, n = i + 19/*BEZIER_SIZE*/ - 1; i < n; i += 2) + { x = curves[i]; - if (x >= percent) { + if (x >= percent) + { var prevX, prevY; - if (i == start) { + if (i == start) + { prevX = 0; prevY = 0; } else { @@ -443,28 +497,33 @@ } }; -spine.RotateTimeline = function (frameCount) { +spine.RotateTimeline = function (frameCount) +{ this.curves = new spine.Curves(frameCount); this.frames = []; // time, angle, ... this.frames.length = frameCount * 2; }; spine.RotateTimeline.prototype = { boneIndex: 0, - getFrameCount: function () { + getFrameCount: function () + { return this.frames.length / 2; }, - setFrame: function (frameIndex, time, angle) { + setFrame: function (frameIndex, time, angle) + { frameIndex *= 2; this.frames[frameIndex] = time; this.frames[frameIndex + 1] = angle; }, - apply: function (skeleton, lastTime, time, firedEvents, alpha) { + apply: function (skeleton, lastTime, time, firedEvents, alpha) + { var frames = this.frames; if (time < frames[0]) return; // Time is before first frame. var bone = skeleton.bones[this.boneIndex]; - if (time >= frames[frames.length - 2]) { // Time is after last frame. + if (time >= frames[frames.length - 2]) + { // Time is after last frame. var amount = bone.data.rotation + frames[frames.length - 1] - bone.rotation; while (amount > 180) amount -= 360; @@ -495,29 +554,34 @@ } }; -spine.TranslateTimeline = function (frameCount) { +spine.TranslateTimeline = function (frameCount) +{ this.curves = new spine.Curves(frameCount); this.frames = []; // time, x, y, ... this.frames.length = frameCount * 3; }; spine.TranslateTimeline.prototype = { boneIndex: 0, - getFrameCount: function () { + getFrameCount: function () + { return this.frames.length / 3; }, - setFrame: function (frameIndex, time, x, y) { + setFrame: function (frameIndex, time, x, y) + { frameIndex *= 3; this.frames[frameIndex] = time; this.frames[frameIndex + 1] = x; this.frames[frameIndex + 2] = y; }, - apply: function (skeleton, lastTime, time, firedEvents, alpha) { + apply: function (skeleton, lastTime, time, firedEvents, alpha) + { var frames = this.frames; if (time < frames[0]) return; // Time is before first frame. var bone = skeleton.bones[this.boneIndex]; - if (time >= frames[frames.length - 3]) { // Time is after last frame. + if (time >= frames[frames.length - 3]) + { // Time is after last frame. bone.x += (bone.data.x + frames[frames.length - 2] - bone.x) * alpha; bone.y += (bone.data.y + frames[frames.length - 1] - bone.y) * alpha; return; @@ -536,29 +600,34 @@ } }; -spine.ScaleTimeline = function (frameCount) { +spine.ScaleTimeline = function (frameCount) +{ this.curves = new spine.Curves(frameCount); this.frames = []; // time, x, y, ... this.frames.length = frameCount * 3; }; spine.ScaleTimeline.prototype = { boneIndex: 0, - getFrameCount: function () { + getFrameCount: function () + { return this.frames.length / 3; }, - setFrame: function (frameIndex, time, x, y) { + setFrame: function (frameIndex, time, x, y) + { frameIndex *= 3; this.frames[frameIndex] = time; this.frames[frameIndex + 1] = x; this.frames[frameIndex + 2] = y; }, - apply: function (skeleton, lastTime, time, firedEvents, alpha) { + apply: function (skeleton, lastTime, time, firedEvents, alpha) + { var frames = this.frames; if (time < frames[0]) return; // Time is before first frame. var bone = skeleton.bones[this.boneIndex]; - if (time >= frames[frames.length - 3]) { // Time is after last frame. + if (time >= frames[frames.length - 3]) + { // Time is after last frame. bone.scaleX += (bone.data.scaleX * frames[frames.length - 2] - bone.scaleX) * alpha; bone.scaleY += (bone.data.scaleY * frames[frames.length - 1] - bone.scaleY) * alpha; return; @@ -577,17 +646,20 @@ } }; -spine.ColorTimeline = function (frameCount) { +spine.ColorTimeline = function (frameCount) +{ this.curves = new spine.Curves(frameCount); this.frames = []; // time, r, g, b, a, ... this.frames.length = frameCount * 5; }; spine.ColorTimeline.prototype = { slotIndex: 0, - getFrameCount: function () { + getFrameCount: function () + { return this.frames.length / 5; }, - setFrame: function (frameIndex, time, r, g, b, a) { + setFrame: function (frameIndex, time, r, g, b, a) + { frameIndex *= 5; this.frames[frameIndex] = time; this.frames[frameIndex + 1] = r; @@ -595,12 +667,14 @@ this.frames[frameIndex + 3] = b; this.frames[frameIndex + 4] = a; }, - apply: function (skeleton, lastTime, time, firedEvents, alpha) { + apply: function (skeleton, lastTime, time, firedEvents, alpha) + { var frames = this.frames; if (time < frames[0]) return; // Time is before first frame. var r, g, b, a; - if (time >= frames[frames.length - 5]) { + if (time >= frames[frames.length - 5]) + { // Time is after last frame. var i = frames.length - 1; r = frames[i - 3]; @@ -624,7 +698,8 @@ a = prevFrameA + (frames[frameIndex + 4/*FRAME_A*/] - prevFrameA) * percent; } var slot = skeleton.slots[this.slotIndex]; - if (alpha < 1) { + if (alpha < 1) + { slot.r += (r - slot.r) * alpha; slot.g += (g - slot.g) * alpha; slot.b += (b - slot.b) * alpha; @@ -638,7 +713,8 @@ } }; -spine.AttachmentTimeline = function (frameCount) { +spine.AttachmentTimeline = function (frameCount) +{ this.curves = new spine.Curves(frameCount); this.frames = []; // time, ... this.frames.length = frameCount; @@ -647,16 +723,20 @@ }; spine.AttachmentTimeline.prototype = { slotIndex: 0, - getFrameCount: function () { + getFrameCount: function () + { return this.frames.length; }, - setFrame: function (frameIndex, time, attachmentName) { + setFrame: function (frameIndex, time, attachmentName) + { this.frames[frameIndex] = time; this.attachmentNames[frameIndex] = attachmentName; }, - apply: function (skeleton, lastTime, time, firedEvents, alpha) { + apply: function (skeleton, lastTime, time, firedEvents, alpha) + { var frames = this.frames; - if (time < frames[0]) { + if (time < frames[0]) + { if (lastTime > time) this.apply(skeleton, lastTime, Number.MAX_VALUE, null, 0); return; } else if (lastTime > time) // @@ -671,28 +751,33 @@ } }; -spine.EventTimeline = function (frameCount) { +spine.EventTimeline = function (frameCount) +{ this.frames = []; // time, ... this.frames.length = frameCount; this.events = []; this.events.length = frameCount; }; spine.EventTimeline.prototype = { - getFrameCount: function () { + getFrameCount: function () + { return this.frames.length; }, - setFrame: function (frameIndex, time, event) { + setFrame: function (frameIndex, time, event) + { this.frames[frameIndex] = time; this.events[frameIndex] = event; }, /** Fires events for frames > lastTime and <= time. */ - apply: function (skeleton, lastTime, time, firedEvents, alpha) { + apply: function (skeleton, lastTime, time, firedEvents, alpha) + { if (!firedEvents) return; var frames = this.frames; var frameCount = frames.length; - if (lastTime > time) { // Fire events after last time for looped animations. + if (lastTime > time) + { // Fire events after last time for looped animations. this.apply(skeleton, lastTime, Number.MAX_VALUE, firedEvents, alpha); lastTime = -1; } else if (lastTime >= frames[frameCount - 1]) // Last time is after last frame. @@ -702,10 +787,12 @@ var frameIndex; if (lastTime < frames[0]) frameIndex = 0; - else { + else + { frameIndex = spine.Animation.binarySearch1(frames, lastTime); var frame = frames[frameIndex]; - while (frameIndex > 0) { // Fire multiple events with the same frame. + while (frameIndex > 0) + { // Fire multiple events with the same frame. if (frames[frameIndex - 1] != frame) break; frameIndex--; } @@ -716,21 +803,25 @@ } }; -spine.DrawOrderTimeline = function (frameCount) { +spine.DrawOrderTimeline = function (frameCount) +{ this.frames = []; // time, ... this.frames.length = frameCount; this.drawOrders = []; this.drawOrders.length = frameCount; }; spine.DrawOrderTimeline.prototype = { - getFrameCount: function () { + getFrameCount: function () + { return this.frames.length; }, - setFrame: function (frameIndex, time, drawOrder) { + setFrame: function (frameIndex, time, drawOrder) + { this.frames[frameIndex] = time; this.drawOrders[frameIndex] = drawOrder; }, - apply: function (skeleton, lastTime, time, firedEvents, alpha) { + apply: function (skeleton, lastTime, time, firedEvents, alpha) + { var frames = this.frames; if (time < frames[0]) return; // Time is before first frame. @@ -743,7 +834,8 @@ var drawOrder = skeleton.drawOrder; var slots = skeleton.slots; var drawOrderToSetupIndex = this.drawOrders[frameIndex]; - if (!drawOrderToSetupIndex) { + if (!drawOrderToSetupIndex) + { for (var i = 0, n = slots.length; i < n; i++) drawOrder[i] = slots[i]; } else { @@ -754,7 +846,8 @@ } }; -spine.FfdTimeline = function (frameCount) { +spine.FfdTimeline = function (frameCount) +{ this.curves = new spine.Curves(frameCount); this.frames = []; this.frames.length = frameCount; @@ -764,14 +857,17 @@ spine.FfdTimeline.prototype = { slotIndex: 0, attachment: 0, - getFrameCount: function () { + getFrameCount: function () + { return this.frames.length; }, - setFrame: function (frameIndex, time, vertices) { + setFrame: function (frameIndex, time, vertices) + { this.frames[frameIndex] = time; this.frameVertices[frameIndex] = vertices; }, - apply: function (skeleton, lastTime, time, firedEvents, alpha) { + apply: function (skeleton, lastTime, time, firedEvents, alpha) + { var slot = skeleton.slots[this.slotIndex]; if (slot.attachment != this.attachment) return; @@ -785,9 +881,11 @@ if (vertices.length != vertexCount) alpha = 1; vertices.length = vertexCount; - if (time >= frames[frames.length - 1]) { // Time is after last frame. + if (time >= frames[frames.length - 1]) + { // Time is after last frame. var lastVertices = frameVertices[frames.length - 1]; - if (alpha < 1) { + if (alpha < 1) + { for (var i = 0; i < vertexCount; i++) vertices[i] += (lastVertices[i] - vertices[i]) * alpha; } else { @@ -806,13 +904,16 @@ var prevVertices = frameVertices[frameIndex - 1]; var nextVertices = frameVertices[frameIndex]; - if (alpha < 1) { - for (var i = 0; i < vertexCount; i++) { + if (alpha < 1) + { + for (var i = 0; i < vertexCount; i++) + { var prev = prevVertices[i]; vertices[i] += (prev + (nextVertices[i] - prev) * percent - vertices[i]) * alpha; } } else { - for (var i = 0; i < vertexCount; i++) { + for (var i = 0; i < vertexCount; i++) + { var prev = prevVertices[i]; vertices[i] = prev + (nextVertices[i] - prev) * percent; } @@ -820,29 +921,34 @@ } }; -spine.IkConstraintTimeline = function (frameCount) { +spine.IkConstraintTimeline = function (frameCount) +{ this.curves = new spine.Curves(frameCount); this.frames = []; // time, mix, bendDirection, ... this.frames.length = frameCount * 3; }; spine.IkConstraintTimeline.prototype = { ikConstraintIndex: 0, - getFrameCount: function () { + getFrameCount: function () + { return this.frames.length / 3; }, - setFrame: function (frameIndex, time, mix, bendDirection) { + setFrame: function (frameIndex, time, mix, bendDirection) + { frameIndex *= 3; this.frames[frameIndex] = time; this.frames[frameIndex + 1] = mix; this.frames[frameIndex + 2] = bendDirection; }, - apply: function (skeleton, lastTime, time, firedEvents, alpha) { + apply: function (skeleton, lastTime, time, firedEvents, alpha) + { var frames = this.frames; if (time < frames[0]) return; // Time is before first frame. var ikConstraint = skeleton.ikConstraints[this.ikConstraintIndex]; - if (time >= frames[frames.length - 3]) { // Time is after last frame. + if (time >= frames[frames.length - 3]) + { // Time is after last frame. ikConstraint.mix += (frames[frames.length - 2] - ikConstraint.mix) * alpha; ikConstraint.bendDirection = frames[frames.length - 1]; return; @@ -861,24 +967,29 @@ } }; -spine.FlipXTimeline = function (frameCount) { +spine.FlipXTimeline = function (frameCount) +{ this.curves = new spine.Curves(frameCount); this.frames = []; // time, flip, ... this.frames.length = frameCount * 2; }; spine.FlipXTimeline.prototype = { boneIndex: 0, - getFrameCount: function () { + getFrameCount: function () + { return this.frames.length / 2; }, - setFrame: function (frameIndex, time, flip) { + setFrame: function (frameIndex, time, flip) + { frameIndex *= 2; this.frames[frameIndex] = time; this.frames[frameIndex + 1] = flip ? 1 : 0; }, - apply: function (skeleton, lastTime, time, firedEvents, alpha) { + apply: function (skeleton, lastTime, time, firedEvents, alpha) + { var frames = this.frames; - if (time < frames[0]) { + if (time < frames[0]) + { if (lastTime > time) this.apply(skeleton, lastTime, Number.MAX_VALUE, null, 0); return; } else if (lastTime > time) // @@ -889,24 +1000,29 @@ } }; -spine.FlipYTimeline = function (frameCount) { +spine.FlipYTimeline = function (frameCount) +{ this.curves = new spine.Curves(frameCount); this.frames = []; // time, flip, ... this.frames.length = frameCount * 2; }; spine.FlipYTimeline.prototype = { boneIndex: 0, - getFrameCount: function () { + getFrameCount: function () + { return this.frames.length / 2; }, - setFrame: function (frameIndex, time, flip) { + setFrame: function (frameIndex, time, flip) + { frameIndex *= 2; this.frames[frameIndex] = time; this.frames[frameIndex + 1] = flip ? 1 : 0; }, - apply: function (skeleton, lastTime, time, firedEvents, alpha) { + apply: function (skeleton, lastTime, time, firedEvents, alpha) + { var frames = this.frames; - if (time < frames[0]) { + if (time < frames[0]) + { if (lastTime > time) this.apply(skeleton, lastTime, Number.MAX_VALUE, null, 0); return; } else if (lastTime > time) // @@ -917,7 +1033,8 @@ } }; -spine.SkeletonData = function () { +spine.SkeletonData = function () +{ this.bones = []; this.slots = []; this.skins = []; @@ -931,57 +1048,66 @@ width: 0, height: 0, version: null, hash: null, /** @return May be null. */ - findBone: function (boneName) { + findBone: function (boneName) + { var bones = this.bones; for (var i = 0, n = bones.length; i < n; i++) if (bones[i].name == boneName) return bones[i]; return null; }, /** @return -1 if the bone was not found. */ - findBoneIndex: function (boneName) { + findBoneIndex: function (boneName) + { var bones = this.bones; for (var i = 0, n = bones.length; i < n; i++) if (bones[i].name == boneName) return i; return -1; }, /** @return May be null. */ - findSlot: function (slotName) { + findSlot: function (slotName) + { var slots = this.slots; - for (var i = 0, n = slots.length; i < n; i++) { + for (var i = 0, n = slots.length; i < n; i++) + { if (slots[i].name == slotName) return slot[i]; } return null; }, /** @return -1 if the bone was not found. */ - findSlotIndex: function (slotName) { + findSlotIndex: function (slotName) + { var slots = this.slots; for (var i = 0, n = slots.length; i < n; i++) if (slots[i].name == slotName) return i; return -1; }, /** @return May be null. */ - findSkin: function (skinName) { + findSkin: function (skinName) + { var skins = this.skins; for (var i = 0, n = skins.length; i < n; i++) if (skins[i].name == skinName) return skins[i]; return null; }, /** @return May be null. */ - findEvent: function (eventName) { + findEvent: function (eventName) + { var events = this.events; for (var i = 0, n = events.length; i < n; i++) if (events[i].name == eventName) return events[i]; return null; }, /** @return May be null. */ - findAnimation: function (animationName) { + findAnimation: function (animationName) + { var animations = this.animations; for (var i = 0, n = animations.length; i < n; i++) if (animations[i].name == animationName) return animations[i]; return null; }, /** @return May be null. */ - findIkConstraint: function (ikConstraintName) { + findIkConstraint: function (ikConstraintName) + { var ikConstraints = this.ikConstraints; for (var i = 0, n = ikConstraints.length; i < n; i++) if (ikConstraints[i].name == ikConstraintName) return ikConstraints[i]; @@ -989,11 +1115,13 @@ } }; -spine.Skeleton = function (skeletonData) { +spine.Skeleton = function (skeletonData) +{ this.data = skeletonData; this.bones = []; - for (var i = 0, n = skeletonData.bones.length; i < n; i++) { + for (var i = 0, n = skeletonData.bones.length; i < n; i++) + { var boneData = skeletonData.bones[i]; var parent = !boneData.parent ? null : this.bones[skeletonData.bones.indexOf(boneData.parent)]; this.bones.push(new spine.Bone(boneData, this, parent)); @@ -1001,7 +1129,8 @@ this.slots = []; this.drawOrder = []; - for (var i = 0, n = skeletonData.slots.length; i < n; i++) { + for (var i = 0, n = skeletonData.slots.length; i < n; i++) + { var slotData = skeletonData.slots[i]; var bone = this.bones[skeletonData.bones.indexOf(slotData.boneData)]; var slot = new spine.Slot(slotData, bone); @@ -1023,7 +1152,8 @@ time: 0, flipX: false, flipY: false, /** Caches information about bones and IK constraints. Must be called if bones or IK constraints are added or removed. */ - updateCache: function () { + updateCache: function () + { var ikConstraints = this.ikConstraints; var ikConstraintsCount = ikConstraints.length; @@ -1039,16 +1169,20 @@ var bones = this.bones; outer: - for (var i = 0, n = bones.length; i < n; i++) { + for (var i = 0, n = bones.length; i < n; i++) + { var bone = bones[i]; var current = bone; do { - for (var ii = 0; ii < ikConstraintsCount; ii++) { + for (var ii = 0; ii < ikConstraintsCount; ii++) + { var ikConstraint = ikConstraints[ii]; var parent = ikConstraint.bones[0]; var child= ikConstraint.bones[ikConstraint.bones.length - 1]; - while (true) { - if (current == child) { + while (true) + { + if (current == child) + { boneCache[ii].push(bone); boneCache[ii + 1].push(bone); continue outer; @@ -1063,14 +1197,17 @@ } }, /** Updates the world transform for each bone. */ - updateWorldTransform: function () { + updateWorldTransform: function () + { var bones = this.bones; - for (var i = 0, n = bones.length; i < n; i++) { + for (var i = 0, n = bones.length; i < n; i++) + { var bone = bones[i]; bone.rotationIK = bone.rotation; } var i = 0, last = this.boneCache.length - 1; - while (true) { + while (true) + { var cacheBones = this.boneCache[i]; for (var ii = 0, nn = cacheBones.length; ii < nn; ii++) cacheBones[ii].updateWorldTransform(); @@ -1080,63 +1217,74 @@ } }, /** Sets the bones and slots to their setup pose values. */ - setToSetupPose: function () { + setToSetupPose: function () + { this.setBonesToSetupPose(); this.setSlotsToSetupPose(); }, - setBonesToSetupPose: function () { + setBonesToSetupPose: function () + { var bones = this.bones; for (var i = 0, n = bones.length; i < n; i++) bones[i].setToSetupPose(); var ikConstraints = this.ikConstraints; - for (var i = 0, n = ikConstraints.length; i < n; i++) { + for (var i = 0, n = ikConstraints.length; i < n; i++) + { var ikConstraint = ikConstraints[i]; ikConstraint.bendDirection = ikConstraint.data.bendDirection; ikConstraint.mix = ikConstraint.data.mix; } }, - setSlotsToSetupPose: function () { + setSlotsToSetupPose: function () + { var slots = this.slots; var drawOrder = this.drawOrder; - for (var i = 0, n = slots.length; i < n; i++) { + for (var i = 0, n = slots.length; i < n; i++) + { drawOrder[i] = slots[i]; slots[i].setToSetupPose(i); } }, /** @return May return null. */ - getRootBone: function () { + getRootBone: function () + { return this.bones.length ? this.bones[0] : null; }, /** @return May be null. */ - findBone: function (boneName) { + findBone: function (boneName) + { var bones = this.bones; for (var i = 0, n = bones.length; i < n; i++) if (bones[i].data.name == boneName) return bones[i]; return null; }, /** @return -1 if the bone was not found. */ - findBoneIndex: function (boneName) { + findBoneIndex: function (boneName) + { var bones = this.bones; for (var i = 0, n = bones.length; i < n; i++) if (bones[i].data.name == boneName) return i; return -1; }, /** @return May be null. */ - findSlot: function (slotName) { + findSlot: function (slotName) + { var slots = this.slots; for (var i = 0, n = slots.length; i < n; i++) if (slots[i].data.name == slotName) return slots[i]; return null; }, /** @return -1 if the bone was not found. */ - findSlotIndex: function (slotName) { + findSlotIndex: function (slotName) + { var slots = this.slots; for (var i = 0, n = slots.length; i < n; i++) if (slots[i].data.name == slotName) return i; return -1; }, - setSkinByName: function (skinName) { + setSkinByName: function (skinName) + { var skin = this.data.findSkin(skinName); if (!skin) throw "Skin not found: " + skinName; this.setSkin(skin); @@ -1145,16 +1293,21 @@ * Attachments from the new skin are attached if the corresponding attachment from the old skin was attached. If there was * no old skin, each slot's setup mode attachment is attached from the new skin. * @param newSkin May be null. */ - setSkin: function (newSkin) { - if (newSkin) { + setSkin: function (newSkin) + { + if (newSkin) + { if (this.skin) newSkin._attachAll(this, this.skin); - else { + else + { var slots = this.slots; - for (var i = 0, n = slots.length; i < n; i++) { + for (var i = 0, n = slots.length; i < n; i++) + { var slot = slots[i]; var name = slot.data.attachmentName; - if (name) { + if (name) + { var attachment = newSkin.getAttachment(i, name); if (attachment) slot.setAttachment(attachment); } @@ -1164,12 +1317,15 @@ this.skin = newSkin; }, /** @return May be null. */ - getAttachmentBySlotName: function (slotName, attachmentName) { + getAttachmentBySlotName: function (slotName, attachmentName) + { return this.getAttachmentBySlotIndex(this.data.findSlotIndex(slotName), attachmentName); }, /** @return May be null. */ - getAttachmentBySlotIndex: function (slotIndex, attachmentName) { - if (this.skin) { + getAttachmentBySlotIndex: function (slotIndex, attachmentName) + { + if (this.skin) + { var attachment = this.skin.getAttachment(slotIndex, attachmentName); if (attachment) return attachment; } @@ -1177,13 +1333,17 @@ return null; }, /** @param attachmentName May be null. */ - setAttachment: function (slotName, attachmentName) { + setAttachment: function (slotName, attachmentName) + { var slots = this.slots; - for (var i = 0, n = slots.length; i < n; i++) { + for (var i = 0, n = slots.length; i < n; i++) + { var slot = slots[i]; - if (slot.data.name == slotName) { + if (slot.data.name == slotName) + { var attachment = null; - if (attachmentName) { + if (attachmentName) + { attachment = this.getAttachmentBySlotIndex(i, attachmentName); if (!attachment) throw "Attachment not found: " + attachmentName + ", for slot: " + slotName; } @@ -1194,18 +1354,21 @@ throw "Slot not found: " + slotName; }, /** @return May be null. */ - findIkConstraint: function (ikConstraintName) { + findIkConstraint: function (ikConstraintName) + { var ikConstraints = this.ikConstraints; for (var i = 0, n = ikConstraints.length; i < n; i++) if (ikConstraints[i].data.name == ikConstraintName) return ikConstraints[i]; return null; }, - update: function (delta) { + update: function (delta) + { this.time += delta; } }; -spine.EventData = function (name) { +spine.EventData = function (name) +{ this.name = name; }; spine.EventData.prototype = { @@ -1214,7 +1377,8 @@ stringValue: null }; -spine.Event = function (data) { +spine.Event = function (data) +{ this.data = data; }; spine.Event.prototype = { @@ -1230,7 +1394,8 @@ skinnedmesh: 3 }; -spine.RegionAttachment = function (name) { +spine.RegionAttachment = function (name) +{ this.name = name; this.offset = []; this.offset.length = 8; @@ -1249,9 +1414,11 @@ regionOffsetX: 0, regionOffsetY: 0, regionWidth: 0, regionHeight: 0, regionOriginalWidth: 0, regionOriginalHeight: 0, - setUVs: function (u, v, u2, v2, rotate) { + setUVs: function (u, v, u2, v2, rotate) + { var uvs = this.uvs; - if (rotate) { + if (rotate) + { uvs[2/*X2*/] = u; uvs[3/*Y2*/] = v2; uvs[4/*X3*/] = u; @@ -1271,7 +1438,8 @@ uvs[7/*Y4*/] = v2; } }, - updateOffset: function () { + updateOffset: function () + { var regionScaleX = this.width / this.regionOriginalWidth * this.scaleX; var regionScaleY = this.height / this.regionOriginalHeight * this.scaleY; var localX = -this.width / 2 * this.scaleX + this.regionOffsetX * regionScaleX; @@ -1299,7 +1467,8 @@ offset[6/*X4*/] = localX2Cos - localYSin; offset[7/*Y4*/] = localYCos + localX2Sin; }, - computeVertices: function (x, y, bone, vertices) { + computeVertices: function (x, y, bone, vertices) + { x += bone.worldX; y += bone.worldY; var m00 = bone.m00, m01 = bone.m01, m10 = bone.m10, m11 = bone.m11; @@ -1315,7 +1484,8 @@ } }; -spine.MeshAttachment = function (name) { +spine.MeshAttachment = function (name) +{ this.name = name; }; spine.MeshAttachment.prototype = { @@ -1334,25 +1504,31 @@ regionOriginalWidth: 0, regionOriginalHeight: 0, edges: null, width: 0, height: 0, - updateUVs: function () { + updateUVs: function () + { var width = this.regionU2 - this.regionU, height = this.regionV2 - this.regionV; var n = this.regionUVs.length; - if (!this.uvs || this.uvs.length != n) { + if (!this.uvs || this.uvs.length != n) + { this.uvs = new spine.Float32Array(n); } - if (this.regionRotate) { - for (var i = 0; i < n; i += 2) { + if (this.regionRotate) + { + for (var i = 0; i < n; i += 2) + { this.uvs[i] = this.regionU + this.regionUVs[i + 1] * width; this.uvs[i + 1] = this.regionV + height - this.regionUVs[i] * height; } } else { - for (var i = 0; i < n; i += 2) { + for (var i = 0; i < n; i += 2) + { this.uvs[i] = this.regionU + this.regionUVs[i] * width; this.uvs[i + 1] = this.regionV + this.regionUVs[i + 1] * height; } } }, - computeWorldVertices: function (x, y, slot, worldVertices) { + computeWorldVertices: function (x, y, slot, worldVertices) + { var bone = slot.bone; x += bone.worldX; y += bone.worldY; @@ -1360,7 +1536,8 @@ var vertices = this.vertices; var verticesCount = vertices.length; if (slot.attachmentVertices.length == verticesCount) vertices = slot.attachmentVertices; - for (var i = 0; i < verticesCount; i += 2) { + for (var i = 0; i < verticesCount; i += 2) + { var vx = vertices[i]; var vy = vertices[i + 1]; worldVertices[i] = vx * m00 + vy * m01 + x; @@ -1369,7 +1546,8 @@ } }; -spine.SkinnedMeshAttachment = function (name) { +spine.SkinnedMeshAttachment = function (name) +{ this.name = name; }; spine.SkinnedMeshAttachment.prototype = { @@ -1389,37 +1567,46 @@ regionOriginalWidth: 0, regionOriginalHeight: 0, edges: null, width: 0, height: 0, - updateUVs: function (u, v, u2, v2, rotate) { + updateUVs: function (u, v, u2, v2, rotate) + { var width = this.regionU2 - this.regionU, height = this.regionV2 - this.regionV; var n = this.regionUVs.length; - if (!this.uvs || this.uvs.length != n) { + if (!this.uvs || this.uvs.length != n) + { this.uvs = new spine.Float32Array(n); } - if (this.regionRotate) { - for (var i = 0; i < n; i += 2) { + if (this.regionRotate) + { + for (var i = 0; i < n; i += 2) + { this.uvs[i] = this.regionU + this.regionUVs[i + 1] * width; this.uvs[i + 1] = this.regionV + height - this.regionUVs[i] * height; } } else { - for (var i = 0; i < n; i += 2) { + for (var i = 0; i < n; i += 2) + { this.uvs[i] = this.regionU + this.regionUVs[i] * width; this.uvs[i + 1] = this.regionV + this.regionUVs[i + 1] * height; } } }, - computeWorldVertices: function (x, y, slot, worldVertices) { + computeWorldVertices: function (x, y, slot, worldVertices) + { var skeletonBones = slot.bone.skeleton.bones; var weights = this.weights; var bones = this.bones; var w = 0, v = 0, b = 0, f = 0, n = bones.length, nn; var wx, wy, bone, vx, vy, weight; - if (!slot.attachmentVertices.length) { - for (; v < n; w += 2) { + if (!slot.attachmentVertices.length) + { + for (; v < n; w += 2) + { wx = 0; wy = 0; nn = bones[v++] + v; - for (; v < nn; v++, b += 3) { + for (; v < nn; v++, b += 3) + { bone = skeletonBones[bones[v]]; vx = weights[b]; vy = weights[b + 1]; @@ -1432,11 +1619,13 @@ } } else { var ffd = slot.attachmentVertices; - for (; v < n; w += 2) { + for (; v < n; w += 2) + { wx = 0; wy = 0; nn = bones[v++] + v; - for (; v < nn; v++, b += 3, f += 2) { + for (; v < nn; v++, b += 3, f += 2) + { bone = skeletonBones[bones[v]]; vx = weights[b] + ffd[f]; vy = weights[b + 1] + ffd[f + 1]; @@ -1451,18 +1640,21 @@ } }; -spine.BoundingBoxAttachment = function (name) { +spine.BoundingBoxAttachment = function (name) +{ this.name = name; this.vertices = []; }; spine.BoundingBoxAttachment.prototype = { type: spine.AttachmentType.boundingbox, - computeWorldVertices: function (x, y, bone, worldVertices) { + computeWorldVertices: function (x, y, bone, worldVertices) + { x += bone.worldX; y += bone.worldY; var m00 = bone.m00, m01 = bone.m01, m10 = bone.m10, m11 = bone.m11; var vertices = this.vertices; - for (var i = 0, n = vertices.length; i < n; i += 2) { + for (var i = 0, n = vertices.length; i < n; i += 2) + { var px = vertices[i]; var py = vertices[i + 1]; worldVertices[i] = px * m00 + py * m01 + x; @@ -1471,29 +1663,34 @@ } }; -spine.AnimationStateData = function (skeletonData) { +spine.AnimationStateData = function (skeletonData) +{ this.skeletonData = skeletonData; this.animationToMixTime = {}; }; spine.AnimationStateData.prototype = { defaultMix: 0, - setMixByName: function (fromName, toName, duration) { + setMixByName: function (fromName, toName, duration) + { var from = this.skeletonData.findAnimation(fromName); if (!from) throw "Animation not found: " + fromName; var to = this.skeletonData.findAnimation(toName); if (!to) throw "Animation not found: " + toName; this.setMix(from, to, duration); }, - setMix: function (from, to, duration) { + setMix: function (from, to, duration) + { this.animationToMixTime[from.name + ":" + to.name] = duration; }, - getMix: function (from, to) { + getMix: function (from, to) + { var key = from.name + ":" + to.name; return this.animationToMixTime.hasOwnProperty(key) ? this.animationToMixTime[key] : this.defaultMix; } }; -spine.TrackEntry = function () {}; +spine.TrackEntry = function () +{}; spine.TrackEntry.prototype = { next: null, previous: null, animation: null, @@ -1504,7 +1701,8 @@ onStart: null, onEnd: null, onComplete: null, onEvent: null }; -spine.AnimationState = function (stateData) { +spine.AnimationState = function (stateData) +{ this.data = stateData; this.tracks = []; this.events = []; @@ -1515,21 +1713,25 @@ onComplete: null, onEvent: null, timeScale: 1, - update: function (delta) { + update: function (delta) + { delta *= this.timeScale; - for (var i = 0; i < this.tracks.length; i++) { + for (var i = 0; i < this.tracks.length; i++) + { var current = this.tracks[i]; if (!current) continue; current.time += delta * current.timeScale; - if (current.previous) { + if (current.previous) + { var previousDelta = delta * current.previous.timeScale; current.previous.time += previousDelta; current.mixTime += previousDelta; } var next = current.next; - if (next) { + if (next) + { next.time = current.lastTime - next.delay; if (next.time >= 0) this.setCurrent(i, next); } else { @@ -1538,8 +1740,10 @@ } } }, - apply: function (skeleton) { - for (var i = 0; i < this.tracks.length; i++) { + apply: function (skeleton) + { + for (var i = 0; i < this.tracks.length; i++) + { var current = this.tracks[i]; if (!current) continue; @@ -1552,7 +1756,8 @@ if (!loop && time > endTime) time = endTime; var previous = current.previous; - if (!previous) { + if (!previous) + { if (current.mix == 1) current.animation.apply(skeleton, current.lastTime, time, loop, this.events); else @@ -1563,21 +1768,24 @@ previous.animation.apply(skeleton, previousTime, previousTime, previous.loop, null); var alpha = current.mixTime / current.mixDuration * current.mix; - if (alpha >= 1) { + if (alpha >= 1) + { alpha = 1; current.previous = null; } current.animation.mix(skeleton, current.lastTime, time, loop, this.events, alpha); } - for (var ii = 0, nn = this.events.length; ii < nn; ii++) { + for (var ii = 0, nn = this.events.length; ii < nn; ii++) + { var event = this.events[ii]; if (current.onEvent) current.onEvent(i, event); if (this.onEvent) this.onEvent(i, event); } // Check if completed the animation or a loop iteration. - if (loop ? (lastTime % endTime > time % endTime) : (lastTime < endTime && time >= endTime)) { + if (loop ? (lastTime % endTime > time % endTime) : (lastTime < endTime && time >= endTime)) + { var count = Math.floor(time / endTime); if (current.onComplete) current.onComplete(i, count); if (this.onComplete) this.onComplete(i, count); @@ -1586,12 +1794,14 @@ current.lastTime = current.time; } }, - clearTracks: function () { + clearTracks: function () + { for (var i = 0, n = this.tracks.length; i < n; i++) this.clearTrack(i); this.tracks.length = 0; }, - clearTrack: function (trackIndex) { + clearTrack: function (trackIndex) + { if (trackIndex >= this.tracks.length) return; var current = this.tracks[trackIndex]; if (!current) return; @@ -1601,15 +1811,18 @@ this.tracks[trackIndex] = null; }, - _expandToIndex: function (index) { + _expandToIndex: function (index) + { if (index < this.tracks.length) return this.tracks[index]; while (index >= this.tracks.length) this.tracks.push(null); return null; }, - setCurrent: function (index, entry) { + setCurrent: function (index, entry) + { var current = this._expandToIndex(index); - if (current) { + if (current) + { var previous = current.previous; current.previous = null; @@ -1617,7 +1830,8 @@ if (this.onEnd) this.onEnd(index); entry.mixDuration = this.data.getMix(current.animation, entry.animation); - if (entry.mixDuration > 0) { + if (entry.mixDuration > 0) + { entry.mixTime = 0; // If a mix is in progress, mix from the closest animation. if (previous && current.mixTime / current.mixDuration < 0.5) @@ -1632,13 +1846,15 @@ if (entry.onStart) entry.onStart(index); if (this.onStart) this.onStart(index); }, - setAnimationByName: function (trackIndex, animationName, loop) { + setAnimationByName: function (trackIndex, animationName, loop) + { var animation = this.data.skeletonData.findAnimation(animationName); if (!animation) throw "Animation not found: " + animationName; return this.setAnimation(trackIndex, animation, loop); }, /** Set the current animation. Any queued animations are cleared. */ - setAnimation: function (trackIndex, animation, loop) { + setAnimation: function (trackIndex, animation, loop) + { var entry = new spine.TrackEntry(); entry.animation = animation; entry.loop = loop; @@ -1646,28 +1862,32 @@ this.setCurrent(trackIndex, entry); return entry; }, - addAnimationByName: function (trackIndex, animationName, loop, delay) { + addAnimationByName: function (trackIndex, animationName, loop, delay) + { var animation = this.data.skeletonData.findAnimation(animationName); if (!animation) throw "Animation not found: " + animationName; return this.addAnimation(trackIndex, animation, loop, delay); }, /** Adds an animation to be played delay seconds after the current or last queued animation. * @param delay May be <= 0 to use duration of previous animation minus any mix duration plus the negative delay. */ - addAnimation: function (trackIndex, animation, loop, delay) { + addAnimation: function (trackIndex, animation, loop, delay) + { var entry = new spine.TrackEntry(); entry.animation = animation; entry.loop = loop; entry.endTime = animation.duration; var last = this._expandToIndex(trackIndex); - if (last) { + if (last) + { while (last.next) last = last.next; last.next = entry; } else this.tracks[trackIndex] = entry; - if (delay <= 0) { + if (delay <= 0) + { if (last) delay += last.endTime - this.data.getMix(last.animation, animation); else @@ -1678,24 +1898,28 @@ return entry; }, /** May be null. */ - getCurrent: function (trackIndex) { + getCurrent: function (trackIndex) + { if (trackIndex >= this.tracks.length) return null; return this.tracks[trackIndex]; } }; -spine.SkeletonJson = function (attachmentLoader) { +spine.SkeletonJson = function (attachmentLoader) +{ this.attachmentLoader = attachmentLoader; }; spine.SkeletonJson.prototype = { scale: 1, - readSkeletonData: function (root, name) { + readSkeletonData: function (root, name) + { var skeletonData = new spine.SkeletonData(); skeletonData.name = name; // Skeleton. var skeletonMap = root["skeleton"]; - if (skeletonMap) { + if (skeletonMap) + { skeletonData.hash = skeletonMap["hash"]; skeletonData.version = skeletonMap["spine"]; skeletonData.width = skeletonMap["width"] || 0; @@ -1704,10 +1928,12 @@ // Bones. var bones = root["bones"]; - for (var i = 0, n = bones.length; i < n; i++) { + for (var i = 0, n = bones.length; i < n; i++) + { var boneMap = bones[i]; var parent = null; - if (boneMap["parent"]) { + if (boneMap["parent"]) + { parent = skeletonData.findBone(boneMap["parent"]); if (!parent) throw "Parent bone not found: " + boneMap["parent"]; } @@ -1725,13 +1951,16 @@ // IK constraints. var ik = root["ik"]; - if (ik) { - for (var i = 0, n = ik.length; i < n; i++) { + if (ik) + { + for (var i = 0, n = ik.length; i < n; i++) + { var ikMap = ik[i]; var ikConstraintData = new spine.IkConstraintData(ikMap["name"]); var bones = ikMap["bones"]; - for (var ii = 0, nn = bones.length; ii < nn; ii++) { + for (var ii = 0, nn = bones.length; ii < nn; ii++) + { var bone = skeletonData.findBone(bones[ii]); if (!bone) throw "IK bone not found: " + bones[ii]; ikConstraintData.bones.push(bone); @@ -1749,14 +1978,16 @@ // Slots. var slots = root["slots"]; - for (var i = 0, n = slots.length; i < n; i++) { + for (var i = 0, n = slots.length; i < n; i++) + { var slotMap = slots[i]; var boneData = skeletonData.findBone(slotMap["bone"]); if (!boneData) throw "Slot bone not found: " + slotMap["bone"]; var slotData = new spine.SlotData(slotMap["name"], boneData); var color = slotMap["color"]; - if (color) { + if (color) + { slotData.r = this.toColor(color, 0); slotData.g = this.toColor(color, 1); slotData.b = this.toColor(color, 2); @@ -1771,15 +2002,18 @@ // Skins. var skins = root["skins"]; - for (var skinName in skins) { + for (var skinName in skins) + { if (!skins.hasOwnProperty(skinName)) continue; var skinMap = skins[skinName]; var skin = new spine.Skin(skinName); - for (var slotName in skinMap) { + for (var slotName in skinMap) + { if (!skinMap.hasOwnProperty(slotName)) continue; var slotIndex = skeletonData.findSlotIndex(slotName); var slotEntry = skinMap[slotName]; - for (var attachmentName in slotEntry) { + for (var attachmentName in slotEntry) + { if (!slotEntry.hasOwnProperty(attachmentName)) continue; var attachment = this.readAttachment(skin, attachmentName, slotEntry[attachmentName]); if (attachment) skin.addAttachment(slotIndex, attachmentName, attachment); @@ -1791,7 +2025,8 @@ // Events. var events = root["events"]; - for (var eventName in events) { + for (var eventName in events) + { if (!events.hasOwnProperty(eventName)) continue; var eventMap = events[eventName]; var eventData = new spine.EventData(eventName); @@ -1803,21 +2038,24 @@ // Animations. var animations = root["animations"]; - for (var animationName in animations) { + for (var animationName in animations) + { if (!animations.hasOwnProperty(animationName)) continue; this.readAnimation(animationName, animations[animationName], skeletonData); } return skeletonData; }, - readAttachment: function (skin, name, map) { + readAttachment: function (skin, name, map) + { name = map["name"] || name; var type = spine.AttachmentType[map["type"] || "region"]; var path = map["path"] || name; var scale = this.scale; - if (type == spine.AttachmentType.region) { + if (type == spine.AttachmentType.region) + { var region = this.attachmentLoader.newRegionAttachment(skin, name, path); if (!region) return null; region.path = path; @@ -1830,7 +2068,8 @@ region.height = (map["height"] || 0) * scale; var color = map["color"]; - if (color) { + if (color) + { region.r = this.toColor(color, 0); region.g = this.toColor(color, 1); region.b = this.toColor(color, 2); @@ -1839,7 +2078,8 @@ region.updateOffset(); return region; - } else if (type == spine.AttachmentType.mesh) { + } else if (type == spine.AttachmentType.mesh) + { var mesh = this.attachmentLoader.newMeshAttachment(skin, name, path); if (!mesh) return null; mesh.path = path; @@ -1849,7 +2089,8 @@ mesh.updateUVs(); color = map["color"]; - if (color) { + if (color) + { mesh.r = this.toColor(color, 0); mesh.g = this.toColor(color, 1); mesh.b = this.toColor(color, 2); @@ -1861,7 +2102,8 @@ mesh.width = (map["width"] || 0) * scale; mesh.height = (map["height"] || 0) * scale; return mesh; - } else if (type == spine.AttachmentType.skinnedmesh) { + } else if (type == spine.AttachmentType.skinnedmesh) + { var mesh = this.attachmentLoader.newSkinnedMeshAttachment(skin, name, path); if (!mesh) return null; mesh.path = path; @@ -1870,10 +2112,12 @@ var vertices = this.getFloatArray(map, "vertices", 1); var weights = []; var bones = []; - for (var i = 0, n = vertices.length; i < n; ) { + for (var i = 0, n = vertices.length; i < n; ) + { var boneCount = vertices[i++] | 0; bones[bones.length] = boneCount; - for (var nn = i + boneCount * 4; i < nn; ) { + for (var nn = i + boneCount * 4; i < nn; ) + { bones[bones.length] = vertices[i]; weights[weights.length] = vertices[i + 1] * scale; weights[weights.length] = vertices[i + 2] * scale; @@ -1888,7 +2132,8 @@ mesh.updateUVs(); color = map["color"]; - if (color) { + if (color) + { mesh.r = this.toColor(color, 0); mesh.g = this.toColor(color, 1); mesh.b = this.toColor(color, 2); @@ -1900,7 +2145,8 @@ mesh.width = (map["width"] || 0) * scale; mesh.height = (map["height"] || 0) * scale; return mesh; - } else if (type == spine.AttachmentType.boundingbox) { + } else if (type == spine.AttachmentType.boundingbox) + { var attachment = this.attachmentLoader.newBoundingBoxAttachment(skin, name); var vertices = map["vertices"]; for (var i = 0, n = vertices.length; i < n; i++) @@ -1909,25 +2155,30 @@ } throw "Unknown attachment type: " + type; }, - readAnimation: function (name, map, skeletonData) { + readAnimation: function (name, map, skeletonData) + { var timelines = []; var duration = 0; var slots = map["slots"]; - for (var slotName in slots) { + for (var slotName in slots) + { if (!slots.hasOwnProperty(slotName)) continue; var slotMap = slots[slotName]; var slotIndex = skeletonData.findSlotIndex(slotName); - for (var timelineName in slotMap) { + for (var timelineName in slotMap) + { if (!slotMap.hasOwnProperty(timelineName)) continue; var values = slotMap[timelineName]; - if (timelineName == "color") { + if (timelineName == "color") + { var timeline = new spine.ColorTimeline(values.length); timeline.slotIndex = slotIndex; var frameIndex = 0; - for (var i = 0, n = values.length; i < n; i++) { + for (var i = 0, n = values.length; i < n; i++) + { var valueMap = values[i]; var color = valueMap["color"]; var r = this.toColor(color, 0); @@ -1941,12 +2192,14 @@ timelines.push(timeline); duration = Math.max(duration, timeline.frames[timeline.getFrameCount() * 5 - 5]); - } else if (timelineName == "attachment") { + } else if (timelineName == "attachment") + { var timeline = new spine.AttachmentTimeline(values.length); timeline.slotIndex = slotIndex; var frameIndex = 0; - for (var i = 0, n = values.length; i < n; i++) { + for (var i = 0, n = values.length; i < n; i++) + { var valueMap = values[i]; timeline.setFrame(frameIndex++, valueMap["time"], valueMap["name"]); } @@ -1959,21 +2212,25 @@ } var bones = map["bones"]; - for (var boneName in bones) { + for (var boneName in bones) + { if (!bones.hasOwnProperty(boneName)) continue; var boneIndex = skeletonData.findBoneIndex(boneName); if (boneIndex == -1) throw "Bone not found: " + boneName; var boneMap = bones[boneName]; - for (var timelineName in boneMap) { + for (var timelineName in boneMap) + { if (!boneMap.hasOwnProperty(timelineName)) continue; var values = boneMap[timelineName]; - if (timelineName == "rotate") { + if (timelineName == "rotate") + { var timeline = new spine.RotateTimeline(values.length); timeline.boneIndex = boneIndex; var frameIndex = 0; - for (var i = 0, n = values.length; i < n; i++) { + for (var i = 0, n = values.length; i < n; i++) + { var valueMap = values[i]; timeline.setFrame(frameIndex, valueMap["time"], valueMap["angle"]); this.readCurve(timeline, frameIndex, valueMap); @@ -1982,19 +2239,22 @@ timelines.push(timeline); duration = Math.max(duration, timeline.frames[timeline.getFrameCount() * 2 - 2]); - } else if (timelineName == "translate" || timelineName == "scale") { + } else if (timelineName == "translate" || timelineName == "scale") + { var timeline; var timelineScale = 1; if (timelineName == "scale") timeline = new spine.ScaleTimeline(values.length); - else { + else + { timeline = new spine.TranslateTimeline(values.length); timelineScale = this.scale; } timeline.boneIndex = boneIndex; var frameIndex = 0; - for (var i = 0, n = values.length; i < n; i++) { + for (var i = 0, n = values.length; i < n; i++) + { var valueMap = values[i]; var x = (valueMap["x"] || 0) * timelineScale; var y = (valueMap["y"] || 0) * timelineScale; @@ -2005,14 +2265,16 @@ timelines.push(timeline); duration = Math.max(duration, timeline.frames[timeline.getFrameCount() * 3 - 3]); - } else if (timelineName == "flipX" || timelineName == "flipY") { + } else if (timelineName == "flipX" || timelineName == "flipY") + { var x = timelineName == "flipX"; var timeline = x ? new spine.FlipXTimeline(values.length) : new spine.FlipYTimeline(values.length); timeline.boneIndex = boneIndex; var field = x ? "x" : "y"; var frameIndex = 0; - for (var i = 0, n = values.length; i < n; i++) { + for (var i = 0, n = values.length; i < n; i++) + { var valueMap = values[i]; timeline.setFrame(frameIndex, valueMap["time"], valueMap[field] || false); frameIndex++; @@ -2025,14 +2287,16 @@ } var ikMap = map["ik"]; - for (var ikConstraintName in ikMap) { + for (var ikConstraintName in ikMap) + { if (!ikMap.hasOwnProperty(ikConstraintName)) continue; var ikConstraint = skeletonData.findIkConstraint(ikConstraintName); var values = ikMap[ikConstraintName]; var timeline = new spine.IkConstraintTimeline(values.length); timeline.ikConstraintIndex = skeletonData.ikConstraints.indexOf(ikConstraint); var frameIndex = 0; - for (var i = 0, n = values.length; i < n; i++) { + for (var i = 0, n = values.length; i < n; i++) + { var valueMap = values[i]; var mix = valueMap.hasOwnProperty("mix") ? valueMap["mix"] : 1; var bendDirection = (!valueMap.hasOwnProperty("bendPositive") || valueMap["bendPositive"]) ? 1 : -1; @@ -2045,13 +2309,16 @@ } var ffd = map["ffd"]; - for (var skinName in ffd) { + for (var skinName in ffd) + { var skin = skeletonData.findSkin(skinName); var slotMap = ffd[skinName]; - for (slotName in slotMap) { + for (slotName in slotMap) + { var slotIndex = skeletonData.findSlotIndex(slotName); var meshMap = slotMap[slotName]; - for (var meshName in meshMap) { + for (var meshName in meshMap) + { var values = meshMap[meshName]; var timeline = new spine.FfdTimeline(values.length); var attachment = skin.getAttachment(slotIndex, meshName); @@ -2067,13 +2334,16 @@ vertexCount = attachment.weights.length / 3 * 2; var frameIndex = 0; - for (var i = 0, n = values.length; i < n; i++) { + for (var i = 0, n = values.length; i < n; i++) + { var valueMap = values[i]; var vertices; - if (!valueMap["vertices"]) { + if (!valueMap["vertices"]) + { if (isMesh) vertices = attachment.vertices; - else { + else + { vertices = []; vertices.length = vertexCount; } @@ -2083,14 +2353,16 @@ vertices.length = vertexCount; var start = valueMap["offset"] || 0; var nn = verticesValue.length; - if (this.scale == 1) { + if (this.scale == 1) + { for (var ii = 0; ii < nn; ii++) vertices[ii + start] = verticesValue[ii]; } else { for (var ii = 0; ii < nn; ii++) vertices[ii + start] = verticesValue[ii] * this.scale; } - if (isMesh) { + if (isMesh) + { var meshVertices = attachment.vertices; for (var ii = 0, nn = vertices.length; ii < nn; ii++) vertices[ii] += meshVertices[ii]; @@ -2109,14 +2381,17 @@ var drawOrderValues = map["drawOrder"]; if (!drawOrderValues) drawOrderValues = map["draworder"]; - if (drawOrderValues) { + if (drawOrderValues) + { var timeline = new spine.DrawOrderTimeline(drawOrderValues.length); var slotCount = skeletonData.slots.length; var frameIndex = 0; - for (var i = 0, n = drawOrderValues.length; i < n; i++) { + for (var i = 0, n = drawOrderValues.length; i < n; i++) + { var drawOrderMap = drawOrderValues[i]; var drawOrder = null; - if (drawOrderMap["offsets"]) { + if (drawOrderMap["offsets"]) + { drawOrder = []; drawOrder.length = slotCount; for (var ii = slotCount - 1; ii >= 0; ii--) @@ -2125,7 +2400,8 @@ var unchanged = []; unchanged.length = slotCount - offsets.length; var originalIndex = 0, unchangedIndex = 0; - for (var ii = 0, nn = offsets.length; ii < nn; ii++) { + for (var ii = 0, nn = offsets.length; ii < nn; ii++) + { var offsetMap = offsets[ii]; var slotIndex = skeletonData.findSlotIndex(offsetMap["slot"]); if (slotIndex == -1) throw "Slot not found: " + offsetMap["slot"]; @@ -2149,10 +2425,12 @@ } var events = map["events"]; - if (events) { + if (events) + { var timeline = new spine.EventTimeline(events.length); var frameIndex = 0; - for (var i = 0, n = events.length; i < n; i++) { + for (var i = 0, n = events.length; i < n; i++) + { var eventMap = events[i]; var eventData = skeletonData.findEvent(eventMap["name"]); if (!eventData) throw "Event not found: " + eventMap["name"]; @@ -2168,7 +2446,8 @@ skeletonData.animations.push(new spine.Animation(name, timelines, duration)); }, - readCurve: function (timeline, frameIndex, valueMap) { + readCurve: function (timeline, frameIndex, valueMap) + { var curve = valueMap["curve"]; if (!curve) timeline.curves.setLinear(frameIndex); @@ -2177,15 +2456,18 @@ else if (curve instanceof Array) timeline.curves.setCurve(frameIndex, curve[0], curve[1], curve[2], curve[3]); }, - toColor: function (hexString, colorIndex) { + toColor: function (hexString, colorIndex) + { if (hexString.length != 8) throw "Color hexidecimal length must be 8, recieved: " + hexString; return parseInt(hexString.substring(colorIndex * 2, (colorIndex * 2) + 2), 16) / 255; }, - getFloatArray: function (map, name, scale) { + getFloatArray: function (map, name, scale) + { var list = map[name]; var values = new spine.Float32Array(list.length); var i = 0, n = list.length; - if (scale == 1) { + if (scale == 1) + { for (; i < n; i++) values[i] = list[i]; } else { @@ -2194,7 +2476,8 @@ } return values; }, - getIntArray: function (map, name) { + getIntArray: function (map, name) + { var list = map[name]; var values = new spine.Uint16Array(list.length); for (var i = 0, n = list.length; i < n; i++) @@ -2203,7 +2486,8 @@ } }; -spine.Atlas = function (atlasText, textureLoader) { +spine.Atlas = function (atlasText, textureLoader) +{ this.textureLoader = textureLoader; this.pages = []; this.regions = []; @@ -2212,17 +2496,20 @@ var tuple = []; tuple.length = 4; var page = null; - while (true) { + while (true) + { var line = reader.readLine(); if (line === null) break; line = reader.trim(line); if (!line.length) page = null; - else if (!page) { + else if (!page) + { page = new spine.AtlasPage(); page.name = line; - if (reader.readTuple(tuple) == 2) { // size is only optional for an atlas packed with an old TexturePacker. + if (reader.readTuple(tuple) == 2) + { // size is only optional for an atlas packed with an old TexturePacker. page.width = parseInt(tuple[0]); page.height = parseInt(tuple[1]); reader.readTuple(tuple); @@ -2264,7 +2551,8 @@ region.u = x / page.width; region.v = y / page.height; - if (region.rotate) { + if (region.rotate) + { region.u2 = (x + height) / page.width; region.v2 = (y + width) / page.height; } else { @@ -2276,10 +2564,12 @@ region.width = Math.abs(width); region.height = Math.abs(height); - if (reader.readTuple(tuple) == 4) { // split is optional + if (reader.readTuple(tuple) == 4) + { // split is optional region.splits = [parseInt(tuple[0]), parseInt(tuple[1]), parseInt(tuple[2]), parseInt(tuple[3])]; - if (reader.readTuple(tuple) == 4) { // pad is optional, but only present with splits + if (reader.readTuple(tuple) == 4) + { // pad is optional, but only present with splits region.pads = [parseInt(tuple[0]), parseInt(tuple[1]), parseInt(tuple[2]), parseInt(tuple[3])]; reader.readTuple(tuple); @@ -2300,25 +2590,30 @@ } }; spine.Atlas.prototype = { - findRegion: function (name) { + findRegion: function (name) + { var regions = this.regions; for (var i = 0, n = regions.length; i < n; i++) if (regions[i].name == name) return regions[i]; return null; }, - dispose: function () { + dispose: function () + { var pages = this.pages; for (var i = 0, n = pages.length; i < n; i++) this.textureLoader.unload(pages[i].rendererObject); }, - updateUVs: function (page) { + updateUVs: function (page) + { var regions = this.regions; - for (var i = 0, n = regions.length; i < n; i++) { + for (var i = 0, n = regions.length; i < n; i++) + { var region = regions[i]; if (region.page != page) continue; region.u = region.x / page.width; region.v = region.y / page.height; - if (region.rotate) { + if (region.rotate) + { region.u2 = (region.x + region.height) / page.width; region.v2 = (region.y + region.width) / page.height; } else { @@ -2355,7 +2650,8 @@ repeat: 2 }; -spine.AtlasPage = function () {}; +spine.AtlasPage = function () +{}; spine.AtlasPage.prototype = { name: null, format: null, @@ -2368,7 +2664,8 @@ height: 0 }; -spine.AtlasRegion = function () {}; +spine.AtlasRegion = function () +{}; spine.AtlasRegion.prototype = { page: null, name: null, @@ -2383,31 +2680,37 @@ pads: null }; -spine.AtlasReader = function (text) { +spine.AtlasReader = function (text) +{ this.lines = text.split(/\r\n|\r|\n/); }; spine.AtlasReader.prototype = { index: 0, - trim: function (value) { + trim: function (value) + { return value.replace(/^\s+|\s+$/g, ""); }, - readLine: function () { + readLine: function () + { if (this.index >= this.lines.length) return null; return this.lines[this.index++]; }, - readValue: function () { + readValue: function () + { var line = this.readLine(); var colon = line.indexOf(":"); if (colon == -1) throw "Invalid line: " + line; return this.trim(line.substring(colon + 1)); }, /** Returns the number of tuple values read (1, 2 or 4). */ - readTuple: function (tuple) { + readTuple: function (tuple) + { var line = this.readLine(); var colon = line.indexOf(":"); if (colon == -1) throw "Invalid line: " + line; var i = 0, lastMatch = colon + 1; - for (; i < 3; i++) { + for (; i < 3; i++) + { var comma = line.indexOf(",", lastMatch); if (comma == -1) break; tuple[i] = this.trim(line.substr(lastMatch, comma - lastMatch)); @@ -2418,11 +2721,13 @@ } }; -spine.AtlasAttachmentLoader = function (atlas) { +spine.AtlasAttachmentLoader = function (atlas) +{ this.atlas = atlas; }; spine.AtlasAttachmentLoader.prototype = { - newRegionAttachment: function (skin, name, path) { + newRegionAttachment: function (skin, name, path) + { var region = this.atlas.findRegion(path); if (!region) throw "Region not found in atlas: " + path + " (region attachment: " + name + ")"; var attachment = new spine.RegionAttachment(name); @@ -2436,7 +2741,8 @@ attachment.regionOriginalHeight = region.originalHeight; return attachment; }, - newMeshAttachment: function (skin, name, path) { + newMeshAttachment: function (skin, name, path) + { var region = this.atlas.findRegion(path); if (!region) throw "Region not found in atlas: " + path + " (mesh attachment: " + name + ")"; var attachment = new spine.MeshAttachment(name); @@ -2454,7 +2760,8 @@ attachment.regionOriginalHeight = region.originalHeight; return attachment; }, - newSkinnedMeshAttachment: function (skin, name, path) { + newSkinnedMeshAttachment: function (skin, name, path) + { var region = this.atlas.findRegion(path); if (!region) throw "Region not found in atlas: " + path + " (skinned mesh attachment: " + name + ")"; var attachment = new spine.SkinnedMeshAttachment(name); @@ -2472,19 +2779,22 @@ attachment.regionOriginalHeight = region.originalHeight; return attachment; }, - newBoundingBoxAttachment: function (skin, name) { + newBoundingBoxAttachment: function (skin, name) + { return new spine.BoundingBoxAttachment(name); } }; -spine.SkeletonBounds = function () { +spine.SkeletonBounds = function () +{ this.polygonPool = []; this.polygons = []; this.boundingBoxes = []; }; spine.SkeletonBounds.prototype = { minX: 0, minY: 0, maxX: 0, maxY: 0, - update: function (skeleton, updateAabb) { + update: function (skeleton, updateAabb) + { var slots = skeleton.slots; var slotCount = slots.length; var x = skeleton.x, y = skeleton.y; @@ -2497,14 +2807,16 @@ polygonPool.push(polygons[i]); polygons.length = 0; - for (var i = 0; i < slotCount; i++) { + for (var i = 0; i < slotCount; i++) + { var slot = slots[i]; var boundingBox = slot.attachment; if (boundingBox.type != spine.AttachmentType.boundingbox) continue; boundingBoxes.push(boundingBox); var poolCount = polygonPool.length, polygon; - if (poolCount > 0) { + if (poolCount > 0) + { polygon = polygonPool[poolCount - 1]; polygonPool.splice(poolCount - 1, 1); } else @@ -2517,12 +2829,15 @@ if (updateAabb) this.aabbCompute(); }, - aabbCompute: function () { + aabbCompute: function () + { var polygons = this.polygons; var minX = Number.MAX_VALUE, minY = Number.MAX_VALUE, maxX = Number.MIN_VALUE, maxY = Number.MIN_VALUE; - for (var i = 0, n = polygons.length; i < n; i++) { + for (var i = 0, n = polygons.length; i < n; i++) + { var vertices = polygons[i]; - for (var ii = 0, nn = vertices.length; ii < nn; ii += 2) { + for (var ii = 0, nn = vertices.length; ii < nn; ii += 2) + { var x = vertices[ii]; var y = vertices[ii + 1]; minX = Math.min(minX, x); @@ -2537,11 +2852,13 @@ this.maxY = maxY; }, /** Returns true if the axis aligned bounding box contains the point. */ - aabbContainsPoint: function (x, y) { + aabbContainsPoint: function (x, y) + { return x >= this.minX && x <= this.maxX && y >= this.minY && y <= this.maxY; }, /** Returns true if the axis aligned bounding box intersects the line segment. */ - aabbIntersectsSegment: function (x1, y1, x2, y2) { + aabbIntersectsSegment: function (x1, y1, x2, y2) + { var minX = this.minX, minY = this.minY, maxX = this.maxX, maxY = this.maxY; if ((x1 <= minX && x2 <= minX) || (y1 <= minY && y2 <= minY) || (x1 >= maxX && x2 >= maxX) || (y1 >= maxY && y2 >= maxY)) return false; @@ -2557,12 +2874,14 @@ return false; }, /** Returns true if the axis aligned bounding box intersects the axis aligned bounding box of the specified bounds. */ - aabbIntersectsSkeleton: function (bounds) { + aabbIntersectsSkeleton: function (bounds) + { return this.minX < bounds.maxX && this.maxX > bounds.minX && this.minY < bounds.maxY && this.maxY > bounds.minY; }, /** Returns the first bounding box attachment that contains the point, or null. When doing many checks, it is usually more * efficient to only call this method if {@link #aabbContainsPoint(float, float)} returns true. */ - containsPoint: function (x, y) { + containsPoint: function (x, y) + { var polygons = this.polygons; for (var i = 0, n = polygons.length; i < n; i++) if (this.polygonContainsPoint(polygons[i], x, y)) return this.boundingBoxes[i]; @@ -2570,21 +2889,25 @@ }, /** Returns the first bounding box attachment that contains the line segment, or null. When doing many checks, it is usually * more efficient to only call this method if {@link #aabbIntersectsSegment(float, float, float, float)} returns true. */ - intersectsSegment: function (x1, y1, x2, y2) { + intersectsSegment: function (x1, y1, x2, y2) + { var polygons = this.polygons; for (var i = 0, n = polygons.length; i < n; i++) if (polygons[i].intersectsSegment(x1, y1, x2, y2)) return this.boundingBoxes[i]; return null; }, /** Returns true if the polygon contains the point. */ - polygonContainsPoint: function (polygon, x, y) { + polygonContainsPoint: function (polygon, x, y) + { var nn = polygon.length; var prevIndex = nn - 2; var inside = false; - for (var ii = 0; ii < nn; ii += 2) { + for (var ii = 0; ii < nn; ii += 2) + { var vertexY = polygon[ii + 1]; var prevY = polygon[prevIndex + 1]; - if ((vertexY < y && prevY >= y) || (prevY < y && vertexY >= y)) { + if ((vertexY < y && prevY >= y) || (prevY < y && vertexY >= y)) + { var vertexX = polygon[ii]; if (vertexX + (y - vertexY) / (prevY - vertexY) * (polygon[prevIndex] - vertexX) < x) inside = !inside; } @@ -2593,18 +2916,21 @@ return inside; }, /** Returns true if the polygon contains the line segment. */ - polygonIntersectsSegment: function (polygon, x1, y1, x2, y2) { + polygonIntersectsSegment: function (polygon, x1, y1, x2, y2) + { var nn = polygon.length; var width12 = x1 - x2, height12 = y1 - y2; var det1 = x1 * y2 - y1 * x2; var x3 = polygon[nn - 2], y3 = polygon[nn - 1]; - for (var ii = 0; ii < nn; ii += 2) { + for (var ii = 0; ii < nn; ii += 2) + { var x4 = polygon[ii], y4 = polygon[ii + 1]; var det2 = x3 * y4 - y3 * x4; var width34 = x3 - x4, height34 = y3 - y4; var det3 = width12 * height34 - height12 * width34; var x = (det1 * width34 - width12 * det2) / det3; - if (((x >= x3 && x <= x4) || (x >= x4 && x <= x3)) && ((x >= x1 && x <= x2) || (x >= x2 && x <= x1))) { + if (((x >= x3 && x <= x4) || (x >= x4 && x <= x3)) && ((x >= x1 && x <= x2) || (x >= x2 && x <= x1))) + { var y = (det1 * height34 - height12 * det2) / det3; if (((y >= y3 && y <= y4) || (y >= y4 && y <= y3)) && ((y >= y1 && y <= y2) || (y >= y2 && y <= y1))) return true; } @@ -2613,14 +2939,17 @@ } return false; }, - getPolygon: function (attachment) { + getPolygon: function (attachment) + { var index = this.boundingBoxes.indexOf(attachment); return index == -1 ? null : this.polygons[index]; }, - getWidth: function () { + getWidth: function () + { return this.maxX - this.minX; }, - getHeight: function () { + getHeight: function () + { return this.maxY - this.minY; } }; diff --git a/src/text/BitmapText.js b/src/text/BitmapText.js index e973630..d25f2cb 100644 --- a/src/text/BitmapText.js +++ b/src/text/BitmapText.js @@ -15,7 +15,8 @@ * @param style.font {string} The size (optional) and bitmap font id (required) eq 'Arial' or '20px Arial' (must have loaded previously) * @param [style.align='left'] {string} Alignment for multiline text ('left', 'center' or 'right'), does not affect single line text */ -function BitmapText(text, style) { +function BitmapText(text, style) +{ core.DisplayObjectContainer.call(this); /** @@ -89,10 +90,12 @@ * @memberof BitmapText# */ tint: { - get: function () { + get: function () + { return this._style.tint; }, - set: function (value) { + set: function (value) + { this._style.tint = (typeof value === 'number' && value >= 0) ? value : 0xFFFFFF; this.dirty = true; @@ -107,10 +110,12 @@ * @memberof BitmapText# */ align: { - get: function () { + get: function () + { return this._style.align; }, - set: function (value) { + set: function (value) + { this._style.align = value; this.dirty = true; @@ -124,10 +129,12 @@ * @memberof BitmapText# */ font: { - get: function () { + get: function () + { return this._style.font; }, - set: function (value) { + set: function (value) + { value = value.split(' '); // TODO - This should be object-based not string based like it has been. @@ -145,10 +152,12 @@ * @memberof BitmapText# */ text: { - get: function () { + get: function () + { return this._text; }, - set: function (value) { + set: function (value) + { this._text = value; this.dirty = true; @@ -161,7 +170,8 @@ * * @private */ -BitmapText.prototype.updateText = function () { +BitmapText.prototype.updateText = function () +{ var data = BitmapText.fonts[this.fontName]; var pos = new core.math.Point(); var prevCharCode = null; @@ -171,10 +181,12 @@ var line = 0; var scale = this.fontSize / data.size; - for (var i = 0; i < this.text.length; i++) { + for (var i = 0; i < this.text.length; i++) + { var charCode = this.text.charCodeAt(i); - if (/(?:\r\n|\r|\n)/.test(this.text.charAt(i))) { + if (/(?:\r\n|\r|\n)/.test(this.text.charAt(i))) + { lineWidths.push(pos.x); maxLineWidth = Math.max(maxLineWidth, pos.x); line++; @@ -187,11 +199,13 @@ var charData = data.chars[charCode]; - if (!charData) { + if (!charData) + { continue; } - if (prevCharCode && charData.kerning[prevCharCode]) { + if (prevCharCode && charData.kerning[prevCharCode]) + { pos.x += charData.kerning[prevCharCode]; } @@ -206,13 +220,16 @@ var lineAlignOffsets = []; - for (i = 0; i <= line; i++) { + for (i = 0; i <= line; i++) + { var alignOffset = 0; - if (this.style.align === 'right') { + if (this.style.align === 'right') + { alignOffset = maxLineWidth - lineWidths[i]; } - else if (this.style.align === 'center') { + else if (this.style.align === 'center') + { alignOffset = (maxLineWidth - lineWidths[i]) / 2; } @@ -223,13 +240,16 @@ var lenChars = chars.length; var tint = this.tint; - for (i = 0; i < lenChars; i++) { + for (i = 0; i < lenChars; i++) + { var c = i < lenChildren ? this.children[i] : this._pool.pop(); // get old child if have. if not - take from pool. - if (c) { + if (c) + { c.setTexture(chars[i].texture); // check if got one before. } - else { + else + { c = new core.Sprite(chars[i].texture); // if no create new one. } @@ -238,14 +258,16 @@ c.scale.x = c.scale.y = scale; c.tint = tint; - if (!c.parent) { + if (!c.parent) + { this.addChild(c); } } // remove unnecessary children. // and put their into the pool. - while(this.children.length > lenChars) { + while(this.children.length > lenChars) + { var child = this.getChildAt(this.children.length - 1); this._pool.push(child); this.removeChild(child); @@ -260,8 +282,10 @@ * * @private */ -BitmapText.prototype.updateTransform = function () { - if (this.dirty) { +BitmapText.prototype.updateTransform = function () +{ + if (this.dirty) + { this.updateText(); this.dirty = false; } diff --git a/src/core/display/DisplayObject.js b/src/core/display/DisplayObject.js index 66ebc3c..20e778c 100644 --- a/src/core/display/DisplayObject.js +++ b/src/core/display/DisplayObject.js @@ -7,7 +7,8 @@ * @class * @namespace PIXI */ -function DisplayObject() { +function DisplayObject() +{ /** * The coordinate of the object relative to the local coordinates of the parent. * @@ -152,10 +153,12 @@ * @memberof DisplayObject# */ x: { - get: function () { + get: function () + { return this.position.x; }, - set: function (value) { + set: function (value) + { this.position.x = value; } }, @@ -167,10 +170,12 @@ * @memberof DisplayObject# */ y: { - get: function () { + get: function () + { return this.position.y; }, - set: function (value) { + set: function (value) + { this.position.y = value; } }, @@ -183,11 +188,13 @@ * @readonly */ worldVisible: { - get: function () { + get: function () + { var item = this; do { - if (!item.visible) { + if (!item.visible) + { return false; } @@ -207,17 +214,21 @@ * @memberof DisplayObject# */ mask: { - get: function () { + get: function () + { return this._mask; }, - set: function (value) { - if (this._mask) { + set: function (value) + { + if (this._mask) + { this._mask.isMask = false; } this._mask = value; - if (this._mask) { + if (this._mask) + { this._mask.isMask = true; } } @@ -232,18 +243,23 @@ * @memberof DisplayObject# */ filters: { - get: function () { + get: function () + { return this._filters; }, - set: function (value) { - if (value) { + set: function (value) + { + if (value) + { // now put all the passes in one place.. var passes = []; - for (var i = 0; i < value.length; i++) { + for (var i = 0; i < value.length; i++) + { var filterPasses = value[i].passes; - for (var j = 0; j < filterPasses.length; j++) { + for (var j = 0; j < filterPasses.length; j++) + { passes.push(filterPasses[j]); } } @@ -264,8 +280,9 @@ * * @private */ -DisplayObject.prototype.updateTransform = function () { - +DisplayObject.prototype.updateTransform = function () +{ + // create some matrix refs for easy access var pt = this.parent.worldTransform; var wt = this.worldTransform; @@ -274,9 +291,11 @@ var a, b, c, d, tx, ty; // so if rotation is between 0 then we can simplify the multiplication process.. - if (this.rotation % math.PI_2) { + if (this.rotation % math.PI_2) + { // 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) { + if (this.rotation !== this.rotationCache) + { this.rotationCache = this.rotation; this._sr = Math.sin(this.rotation); this._cr = Math.cos(this.rotation); @@ -291,7 +310,8 @@ ty = this.position.y; // check for pivot.. not often used so geared towards that fact! - if (this.pivot.x || this.pivot.y) { + 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; } @@ -304,7 +324,8 @@ wt.tx = tx * pt.a + ty * pt.c + pt.tx; wt.ty = tx * pt.b + ty * pt.d + pt.ty; } - else { + else + { // lets do the fast version as we know there is no rotation.. a = this.scale.x; d = this.scale.y; @@ -333,7 +354,8 @@ * @param matrix {Matrix} * @return {Rectangle} the rectangular bounding area */ -DisplayObject.prototype.getBounds = function (/* matrix */) { +DisplayObject.prototype.getBounds = function (/* matrix */) +{ return math.Rectangle.EMPTY; }; @@ -342,7 +364,8 @@ * * @return {Rectangle} the rectangular bounding area */ -DisplayObject.prototype.getLocalBounds = function () { +DisplayObject.prototype.getLocalBounds = function () +{ return this.getBounds(math.Matrix.IDENTITY); }; @@ -352,7 +375,8 @@ * @param position {Point} The world origin to calculate from * @return {Point} A point object representing the position of this object */ -DisplayObject.prototype.toGlobal = function (position) { +DisplayObject.prototype.toGlobal = function (position) +{ // don't need to u[date the lot this.displayObjectUpdateTransform(); return this.worldTransform.apply(position); @@ -365,8 +389,10 @@ * @param [from] {DisplayObject} The DisplayObject to calculate the global position from * @return {Point} A point object representing the position of this object */ -DisplayObject.prototype.toLocal = function (position, from) { - if (from) { +DisplayObject.prototype.toLocal = function (position, from) +{ + if (from) + { position = from.toGlobal(position); } @@ -381,7 +407,8 @@ * @param renderer {WebGLRenderer} The renderer * @private */ -DisplayObject.prototype.renderWebGL = function (/* renderer */) { +DisplayObject.prototype.renderWebGL = function (/* renderer */) +{ // OVERWRITE; }; @@ -391,6 +418,7 @@ * @param renderer {CanvasRenderer} The renderer * @private */ -DisplayObject.prototype.renderCanvas = function (/* renderer */) { +DisplayObject.prototype.renderCanvas = function (/* renderer */) +{ // OVERWRITE; }; diff --git a/src/core/display/DisplayObjectContainer.js b/src/core/display/DisplayObjectContainer.js index 689f40b..4625ee8 100644 --- a/src/core/display/DisplayObjectContainer.js +++ b/src/core/display/DisplayObjectContainer.js @@ -12,7 +12,8 @@ * @extends DisplayObject * @namespace PIXI */ -function DisplayObjectContainer() { +function DisplayObjectContainer() +{ DisplayObject.call(this); /** @@ -47,17 +48,21 @@ * @memberof DisplayObjectContainer# */ width: { - get: function () { + get: function () + { return this.scale.x * this.getLocalBounds().width; }, - set: function (value) { + set: function (value) + { var width = this.getLocalBounds().width; - if(width !== 0) { + if(width !== 0) + { this.scale.x = value / width; } - else { + else + { this.scale.x = 1; } @@ -73,17 +78,21 @@ * @memberof DisplayObjectContainer# */ height: { - get: function () { + get: function () + { return this.scale.y * this.getLocalBounds().height; }, - set: function (value) { + set: function (value) + { var height = this.getLocalBounds().height; - if (height !== 0) { + if (height !== 0) + { this.scale.y = value / height ; } - else { + else + { this.scale.y = 1; } @@ -100,18 +109,23 @@ * @memberof DisplayObject# */ cacheAsBitmap: { - get: function () { + get: function () + { return this._cacheAsBitmap; }, - set: function (value) { - if (this._cacheAsBitmap === value) { + set: function (value) + { + if (this._cacheAsBitmap === value) + { return; } - if (value) { + if (value) + { this._generateCachedSprite(); } - else { + else + { this._destroyCachedSprite(); } @@ -126,7 +140,8 @@ * @param child {DisplayObject} The DisplayObject to add to the container * @return {DisplayObject} The child that was added. */ -DisplayObjectContainer.prototype.addChild = function (child) { +DisplayObjectContainer.prototype.addChild = function (child) +{ return this.addChildAt(child, this.children.length); }; @@ -137,14 +152,18 @@ * @param index {Number} The index to place the child in * @return {DisplayObject} The child that was added. */ -DisplayObjectContainer.prototype.addChildAt = function (child, index) { +DisplayObjectContainer.prototype.addChildAt = function (child, index) +{ // prevent adding self as child - if (child === this) { + if (child === this) + { return; } - if (index >= 0 && index <= this.children.length) { - if (child.parent) { + if (index >= 0 && index <= this.children.length) + { + if (child.parent) + { child.parent.removeChild(child); } @@ -154,7 +173,8 @@ return child; } - else { + else + { throw new Error(child + 'addChildAt: The index '+ index +' supplied is out of bounds ' + this.children.length); } }; @@ -165,15 +185,18 @@ * @param child {DisplayObject} * @param child2 {DisplayObject} */ -DisplayObjectContainer.prototype.swapChildren = function (child, child2) { - if (child === child2) { +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) { + if (index1 < 0 || index2 < 0) + { throw new Error('swapChildren: Both the supplied DisplayObjects must be a child of the caller.'); } @@ -187,10 +210,12 @@ * @param child {DisplayObject} The DisplayObject instance to identify * @return {Number} The index position of the child display object to identify */ -DisplayObjectContainer.prototype.getChildIndex = function (child) { +DisplayObjectContainer.prototype.getChildIndex = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { throw new Error('The supplied DisplayObject must be a child of the caller'); } @@ -203,8 +228,10 @@ * @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 */ -DisplayObjectContainer.prototype.setChildIndex = function (child, index) { - if (index < 0 || index >= this.children.length) { +DisplayObjectContainer.prototype.setChildIndex = function (child, index) +{ + if (index < 0 || index >= this.children.length) + { throw new Error('The supplied index is out of bounds'); } @@ -220,8 +247,10 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child at the given index, if any. */ -DisplayObjectContainer.prototype.getChildAt = function (index) { - if (index < 0 || index >= this.children.length) { +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'); } @@ -234,10 +263,12 @@ * @param child {DisplayObject} The DisplayObject to remove * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChild = function (child) { +DisplayObjectContainer.prototype.removeChild = function (child) +{ var index = this.children.indexOf(child); - if (index === -1) { + if (index === -1) + { return; } @@ -250,7 +281,8 @@ * @param index {Number} The index to get the child from * @return {DisplayObject} The child that was removed. */ -DisplayObjectContainer.prototype.removeChildAt = function (index) { +DisplayObjectContainer.prototype.removeChildAt = function (index) +{ var child = this.getChildAt(index); child.parent = null; @@ -265,24 +297,29 @@ * @param beginIndex {Number} The beginning position. Default value is 0. * @param endIndex {Number} The ending position. Default value is size of the container. */ -DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) { +DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) +{ var begin = beginIndex || 0; var end = typeof endIndex === 'number' ? endIndex : this.children.length; var range = end - begin; - if (range > 0 && range <= end) { + if (range > 0 && range <= end) + { var removed = this.children.splice(begin, range); - for (var i = 0; i < removed.length; ++i) { + for (var i = 0; i < removed.length; ++i) + { removed[i].parent = null; } return removed; } - else if (range === 0 && this.children.length === 0) { + else if (range === 0 && this.children.length === 0) + { return []; } - else { + else + { throw new RangeError('removeChildren: numeric values are outside the acceptable range.'); } }; @@ -291,7 +328,8 @@ * Generates and updates the cached sprite for this object. * */ -DisplayObjectContainer.prototype.updateCachedSprite = function () { +DisplayObjectContainer.prototype.updateCachedSprite = function () +{ this._generateCachedSprite(); }; @@ -304,7 +342,8 @@ * @param renderer {CanvasRenderer|WebGLRenderer} The renderer used to generate the texture. * @return {Texture} a texture of the graphics object */ -DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) { +DisplayObjectContainer.prototype.generateTexture = function (resolution, scaleMode, renderer) +{ var bounds = this.getLocalBounds(); var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0, renderer, scaleMode, resolution); @@ -322,18 +361,22 @@ * * @private */ -DisplayObjectContainer.prototype.updateTransform = function () { - if (!this.visible) { +DisplayObjectContainer.prototype.updateTransform = function () +{ + if (!this.visible) + { return; } this.displayObjectUpdateTransform(); - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { return; } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } }; @@ -346,8 +389,10 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getBounds = function () { - if (this.children.length === 0) { +DisplayObjectContainer.prototype.getBounds = function () +{ + if (this.children.length === 0) + { return math.Rectangle.EMPTY; } @@ -365,10 +410,12 @@ var childVisible = false; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -386,7 +433,8 @@ maxY = maxY > childMaxY ? maxY : childMaxY; } - if (!childVisible) { + if (!childVisible) + { return math.Rectangle.EMPTY; } @@ -407,12 +455,14 @@ * * @return {Rectangle} The rectangular bounding area */ -DisplayObjectContainer.prototype.getLocalBounds = function () { +DisplayObjectContainer.prototype.getLocalBounds = function () +{ var matrixCache = this.worldTransform; this.worldTransform = math.Matrix.IDENTITY; - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].updateTransform(); } @@ -428,13 +478,16 @@ * * @param renderer {WebGLRenderer} The renderer */ -DisplayObjectContainer.prototype.renderWebGL = function (renderer) { +DisplayObjectContainer.prototype.renderWebGL = function (renderer) +{ // if the object is not visible or the alpha is 0 then no need to render this element - if (!this.visible || this.alpha <= 0) { + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } @@ -442,14 +495,17 @@ var i, j; // do a quick check to see if this element has a mask or a filter. - if (this._mask || this._filters) { + if (this._mask || this._filters) + { // push filter first as we need to ensure the stencil buffer is correct for any masking - if (this._filters) { + if (this._filters) + { renderer.spriteBatch.flush(); renderer.filterManager.pushFilter(this._filterBlock); } - if (this._mask) { + if (this._mask) + { renderer.spriteBatch.stop(); renderer.maskManager.pushMask(this.mask, renderer); renderer.spriteBatch.start(); @@ -459,36 +515,42 @@ this._renderWebGL(renderer); // now loop through the children and make sure they get rendered - for (i = 0, j = this.children.length; i < j; i++) { + for (i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderWebGL(renderer); } // time to stop the sprite batch as either a mask element or a filter draw will happen next renderer.spriteBatch.stop(); - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(this._mask, renderer); } - if (this._filters) { + if (this._filters) + { renderer.filterManager.popFilter(); } renderer.spriteBatch.start(); } - else { + else + { this._renderWebGL(renderer); // simple render children! - for (i = 0, j = this.children.length; i < j; ++i) { + for (i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderWebGL(renderer); } } }; -DisplayObjectContainer.prototype._renderWebGL = function (renderer) { +DisplayObjectContainer.prototype._renderWebGL = function (renderer) +{ // this is where content itself gets renderd.. @@ -499,25 +561,31 @@ * * @param renderer {CanvasRenderer} The renderer */ -DisplayObjectContainer.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0) { +DisplayObjectContainer.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0) + { return; } - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._renderCachedSprite(renderer); return; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -528,13 +596,16 @@ * @param renderer {WebGLRenderer|CanvasRenderer} The renderer * @private */ -DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) { +DisplayObjectContainer.prototype._renderCachedSprite = function (renderer) +{ this._cachedSprite.worldAlpha = this.worldAlpha; - if (renderer.gl) { + if (renderer.gl) + { this._cachedSprite.renderWebGL(renderer); } - else { + else + { this._cachedSprite.renderCanvas(renderer); } }; @@ -544,10 +615,12 @@ * * @private */ -DisplayObjectContainer.prototype._generateCachedSprite = function () { +DisplayObjectContainer.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { // TODO - RenderTexture now *requires* a renderer instance, so this is like broken // because `renderer` isn't actually in scope here :P var renderTexture = new RenderTexture(renderer, bounds.width | 0, bounds.height | 0); @@ -555,7 +628,8 @@ this._cachedSprite = new Sprite(renderTexture); this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.texture.resize(bounds.width | 0, bounds.height | 0); } @@ -580,8 +654,10 @@ * * @private */ -DisplayObjectContainer.prototype._destroyCachedSprite = function () { - if (!this._cachedSprite) { +DisplayObjectContainer.prototype._destroyCachedSprite = function () +{ + if (!this._cachedSprite) + { return; } diff --git a/src/core/display/Sprite.js b/src/core/display/Sprite.js index 707da24..5862aef 100644 --- a/src/core/display/Sprite.js +++ b/src/core/display/Sprite.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param texture {Texture} The texture for this sprite */ -function Sprite(texture) { +function Sprite(texture) +{ DisplayObjectContainer.call(this); /** @@ -85,12 +86,14 @@ this.texture = texture || Texture.EMPTY; } -Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) { +Sprite.prototype.destroy = function (destroyTexture, destroyBaseTexture) +{ DisplayObjectContainer.prototype.destroy.call(this); this.anchor = null; - if (destroyTexture) { + if (destroyTexture) + { this._texture.destroy(destroyBaseTexture); } @@ -111,10 +114,12 @@ * @memberof Sprite# */ width: { - get: function () { + get: function () + { return this.scale.x * this.texture.frame.width; }, - set: function (value) { + set: function (value) + { this.scale.x = value / this.texture.frame.width; this._width = value; } @@ -127,10 +132,12 @@ * @memberof Sprite# */ height: { - get: function () { + get: function () + { return this.scale.y * this.texture.frame.height; }, - set: function (value) { + set: function (value) + { this.scale.y = value / this.texture.frame.height; this._height = value; } @@ -143,23 +150,29 @@ * @memberof Sprite# */ texture: { - get: function () { + get: function () + { return this._texture; }, - set: function (value) { - if (this._texture === value) { + set: function (value) + { + if (this._texture === value) + { return; } this._texture = value; this.cachedTint = 0xFFFFFF; - if (value) { + if (value) + { // wait for the texture to load - if (value.baseTexture.hasLoaded) { + if (value.baseTexture.hasLoaded) + { this._onTextureUpdate(); } - else { + else + { value.once('update', this._onTextureUpdate.bind(this)); } } @@ -172,18 +185,22 @@ * * @private */ -Sprite.prototype._onTextureUpdate = function () { +Sprite.prototype._onTextureUpdate = function () +{ // so if _width is 0 then width was not set.. - if (this._width) { + if (this._width) + { this.scale.x = this._width / this.texture.frame.width; } - if (this._height) { + if (this._height) + { this.scale.y = this._height / this.texture.frame.height; } }; -Sprite.prototype._renderWebGL = function (renderer) { +Sprite.prototype._renderWebGL = function (renderer) +{ // this is where content gets renderd.. // watch this space for a little render state manager.. @@ -197,7 +214,8 @@ * @param matrix {Matrix} the transformation matrix of the sprite * @return {Rectangle} the framing rectangle */ -Sprite.prototype.getBounds = function (matrix) { +Sprite.prototype.getBounds = function (matrix) +{ var width = this.texture.frame.width; var height = this.texture.frame.height; @@ -224,11 +242,13 @@ if(b === 0 && c === 0) { // scale may be negative! - if (a < 0) { + if (a < 0) + { a *= -1; } - if (d < 0) { + if (d < 0) + { d *= -1; } @@ -293,28 +313,34 @@ * * @param renderer {CanvasRenderer} The renderer */ -Sprite.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) { +Sprite.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) + { return; } - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; renderer.context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } // Ignore null sources - if (this.texture.valid) { + if (this.texture.valid) + { var resolution = this.texture.baseTexture.resolution / renderer.resolution; renderer.context.globalAlpha = this.worldAlpha; // If smoothingEnabled is supported and we need to change the smoothing property for this texture - if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) { + if (renderer.smoothProperty && renderer.scaleMode !== this.texture.baseTexture.scaleMode) + { renderer.scaleMode = this.texture.baseTexture.scaleMode; renderer.context[renderer.smoothProperty] = (renderer.scaleMode === CONST.scaleModes.LINEAR); } @@ -324,7 +350,8 @@ var dy = (this.texture.trim ? this.texture.trim.y : 0) - (this.anchor.y * this.texture.trim.height); // Allow for pixel rounding - if (renderer.roundPixels) { + if (renderer.roundPixels) + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -337,7 +364,8 @@ dx = dx | 0; dy = dy | 0; } - else { + else + { renderer.context.setTransform( this.worldTransform.a, this.worldTransform.b, @@ -348,8 +376,10 @@ ); } - if (this.tint !== 0xFFFFFF) { - if (this.cachedTint !== this.tint) { + if (this.tint !== 0xFFFFFF) + { + if (this.cachedTint !== this.tint) + { this.cachedTint = this.tint; // TODO clean up caching - how to clean up the caches? @@ -368,7 +398,8 @@ this.texture.crop.height / resolution ); } - else { + else + { renderer.context.drawImage( this.texture.baseTexture.source, this.texture.crop.x, @@ -383,11 +414,13 @@ } } - for (var i = 0, j = this.children.length; i < j; i++) { + for (var i = 0, j = this.children.length; i < j; i++) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } }; @@ -402,10 +435,12 @@ * @param frameId {String} The frame Id of the texture in the cache * @return {Sprite} A new Sprite using a texture from the texture cache matching the frameId */ -Sprite.fromFrame = function (frameId) { +Sprite.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache' + this); } @@ -420,6 +455,7 @@ * @param imageId {String} The image url of the texture * @return {Sprite} A new Sprite using a texture from the texture cache matching the image id */ -Sprite.fromImage = function (imageId, crossorigin, scaleMode) { +Sprite.fromImage = function (imageId, crossorigin, scaleMode) +{ return new Sprite(Texture.fromImage(imageId, crossorigin, scaleMode)); }; diff --git a/src/core/display/SpriteBatch.js b/src/core/display/SpriteBatch.js index 3187777..c196fef 100644 --- a/src/core/display/SpriteBatch.js +++ b/src/core/display/SpriteBatch.js @@ -12,7 +12,8 @@ * ```js * var container = new SpriteBatch(); * - * for(var i = 0; i < 100; ++i) { + * for(var i = 0; i < 100; ++i) + * { * var sprite = new PIXI.Sprite.fromImage("myImage.png"); * container.addChild(sprite); * } @@ -25,7 +26,8 @@ */ //TODO RENAME to PARTICLE CONTAINER? -function SpriteBatch() { +function SpriteBatch() +{ DisplayObjectContainer.call(this); } @@ -38,7 +40,8 @@ * * @private */ -SpriteBatch.prototype.updateTransform = function () { +SpriteBatch.prototype.updateTransform = function () +{ // TODO don't need to! this.displayObjectUpdateTransform(); // PIXI.DisplayObjectContainer.prototype.updateTransform.call( this ); @@ -50,8 +53,10 @@ * @param renderer {WebGLRenderer} The webgl renderer * @private */ -SpriteBatch.prototype.renderWebGL = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderWebGL = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -71,8 +76,10 @@ * @param renderer {CanvasRenderer} The canvas renderer * @private */ -SpriteBatch.prototype.renderCanvas = function (renderer) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { +SpriteBatch.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.alpha <= 0 || !this.children.length) + { return; } @@ -84,10 +91,12 @@ this.displayObjectUpdateTransform(); - for (var i = 0; i < this.children.length; ++i) { + for (var i = 0; i < this.children.length; ++i) + { var child = this.children[i]; - if (!child.visible) { + if (!child.visible) + { continue; } @@ -95,9 +104,11 @@ context.globalAlpha = this.worldAlpha * child.alpha; - if (child.rotation % (Math.PI * 2) === 0) { + if (child.rotation % (Math.PI * 2) === 0) + { // this is the fastest way to optimise! - if rotation is 0 then we can avoid any kind of setTransform call - if (isRotated) { + if (isRotated) + { context.setTransform( transform.a, transform.b, @@ -122,8 +133,10 @@ frame.height * child.scale.y ); } - else { - if (!isRotated) { + else + { + if (!isRotated) + { isRotated = true; } @@ -131,7 +144,8 @@ var childTransform = child.worldTransform; - if (renderer.roundPixels) { + if (renderer.roundPixels) + { context.setTransform( childTransform.a, childTransform.b, @@ -141,7 +155,8 @@ childTransform.ty | 0 ); } - else { + else + { context.setTransform( childTransform.a, childTransform.b, diff --git a/src/core/index.js b/src/core/index.js index 3954b6f..eb4a82b 100644 --- a/src/core/index.js +++ b/src/core/index.js @@ -58,11 +58,13 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRenderer: function (width, height, options, noWebGL) { + autoDetectRenderer: function (width, height, options, noWebGL) + { width = width || 800; height = height || 600; - if (!noWebGL && require('webgl-enabled')()) { + if (!noWebGL && require('webgl-enabled')()) + { return new core.WebGLRenderer(width, height, options); } @@ -87,7 +89,8 @@ * * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ - autoDetectRecommendedRenderer: function (width, height, options) { + autoDetectRecommendedRenderer: function (width, height, options) + { var isAndroid = /Android/i.test(navigator.userAgent); return core.autoDetectRenderer(width, height, options, isAndroid); diff --git a/src/core/math/Matrix.js b/src/core/math/Matrix.js index c2f87e2..2ff4848 100644 --- a/src/core/math/Matrix.js +++ b/src/core/math/Matrix.js @@ -10,7 +10,8 @@ * @class * @namespace PIXI */ -function Matrix() { +function Matrix() +{ /** * @member {number} * @default 1 @@ -63,7 +64,8 @@ * * @param array {number[]} The array that the matrix will be populated from. */ -Matrix.prototype.fromArray = function (array) { +Matrix.prototype.fromArray = function (array) +{ this.a = array[0]; this.b = array[1]; this.c = array[3]; @@ -78,14 +80,17 @@ * @param transpose {boolean} Whether we need to transpose the matrix or not * @return {number[]} the newly created array which contains the matrix */ -Matrix.prototype.toArray = function (transpose) { - if (!this.array) { +Matrix.prototype.toArray = function (transpose) +{ + if (!this.array) + { this.array = new Float32Array(9); } var array = this.array; - if (transpose) { + if (transpose) + { array[0] = this.a; array[1] = this.b; array[2] = 0; @@ -96,7 +101,8 @@ array[7] = this.ty; array[8] = 1; } - else { + else + { array[0] = this.a; array[1] = this.c; array[2] = this.tx; @@ -119,7 +125,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, transformed through this matrix */ -Matrix.prototype.apply = function (pos, newPos) { +Matrix.prototype.apply = function (pos, newPos) +{ newPos = newPos || new Point(); newPos.x = this.a * pos.x + this.c * pos.y + this.tx; @@ -136,7 +143,8 @@ * @param [newPos] {Point} The point that the new position is assigned to (allowed to be same as input) * @return {Point} The new point, inverse-transformed through this matrix */ -Matrix.prototype.applyInverse = function (pos, newPos) { +Matrix.prototype.applyInverse = function (pos, newPos) +{ newPos = newPos || new Point(); var id = 1 / (this.a * this.d + this.c * -this.b); @@ -154,7 +162,8 @@ * @param {number} y * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.translate = function (x, y) { +Matrix.prototype.translate = function (x, y) +{ this.tx += x; this.ty += y; @@ -168,7 +177,8 @@ * @param {number} y The amount to scale vertically * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.scale = function (x, y) { +Matrix.prototype.scale = function (x, y) +{ this.a *= x; this.d *= y; this.c *= x; @@ -186,7 +196,8 @@ * @param {number} angle - The angle in radians. * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.rotate = function (angle) { +Matrix.prototype.rotate = function (angle) +{ var cos = Math.cos( angle ); var sin = Math.sin( angle ); @@ -210,7 +221,8 @@ * @param {Matrix} matrix * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.append = function (matrix) { +Matrix.prototype.append = function (matrix) +{ var a1 = this.a; var b1 = this.b; var c1 = this.c; @@ -232,7 +244,8 @@ * * @return {Matrix} This matrix. Good for chaining method calls. */ -Matrix.prototype.identity = function () { +Matrix.prototype.identity = function () +{ this.a = 1; this.b = 0; this.c = 0; diff --git a/src/core/math/Point.js b/src/core/math/Point.js index 7565b2d..632f346 100644 --- a/src/core/math/Point.js +++ b/src/core/math/Point.js @@ -7,7 +7,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -function Point(x, y) { +function Point(x, y) +{ /** * @member {number} * @default 0 @@ -29,7 +30,8 @@ * * @return {Point} a copy of the point */ -Point.prototype.clone = function () { +Point.prototype.clone = function () +{ return new Point(this.x, this.y); }; @@ -40,7 +42,8 @@ * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ -Point.prototype.set = function (x, y) { +Point.prototype.set = function (x, y) +{ this.x = x || 0; this.y = y || ( (y !== 0) ? this.x : 0 ) ; }; diff --git a/src/core/math/shapes/Circle.js b/src/core/math/shapes/Circle.js index 69cfdc9..4d76efc 100644 --- a/src/core/math/shapes/Circle.js +++ b/src/core/math/shapes/Circle.js @@ -10,7 +10,8 @@ * @param y {number} The Y coordinate of the center of this circle * @param radius {number} The radius of the circle */ -function Circle(x, y, radius) { +function Circle(x, y, radius) +{ /** * @member {number} * @default 0 @@ -46,7 +47,8 @@ * @method clone * @return {Circle} a copy of the Circle */ -Circle.prototype.clone = function () { +Circle.prototype.clone = function () +{ return new Circle(this.x, this.y, this.radius); }; @@ -58,8 +60,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Circle */ -Circle.prototype.contains = function (x, y) { - if (this.radius <= 0) { +Circle.prototype.contains = function (x, y) +{ + if (this.radius <= 0) + { return false; } @@ -79,6 +83,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Circle.prototype.getBounds = function () { +Circle.prototype.getBounds = function () +{ return new Rectangle(this.x - this.radius, this.y - this.radius, this.radius * 2, this.radius * 2); }; diff --git a/src/core/math/shapes/Ellipse.js b/src/core/math/shapes/Ellipse.js index 4f2d066..fefd01a 100644 --- a/src/core/math/shapes/Ellipse.js +++ b/src/core/math/shapes/Ellipse.js @@ -11,7 +11,8 @@ * @param width {number} The half width of this ellipse * @param height {number} The half height of this ellipse */ -function Ellipse(x, y, width, height) { +function Ellipse(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -53,7 +54,8 @@ * @method clone * @return {Ellipse} a copy of the ellipse */ -Ellipse.prototype.clone = function () { +Ellipse.prototype.clone = function () +{ return new Ellipse(this.x, this.y, this.width, this.height); }; @@ -65,8 +67,10 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coords are within this ellipse */ -Ellipse.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Ellipse.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } @@ -86,6 +90,7 @@ * @method getBounds * @return {Rectangle} the framing rectangle */ -Ellipse.prototype.getBounds = function () { +Ellipse.prototype.getBounds = function () +{ return new Rectangle(this.x - this.width, this.y - this.height, this.width, this.height); }; diff --git a/src/core/math/shapes/Polygon.js b/src/core/math/shapes/Polygon.js index ae89148..fea6d37 100644 --- a/src/core/math/shapes/Polygon.js +++ b/src/core/math/shapes/Polygon.js @@ -10,16 +10,20 @@ * arguments passed can be flat x,y values e.g. `new Polygon(x,y, x,y, x,y, ...)` where `x` and `y` are * Numbers. */ -function Polygon(points) { +function Polygon(points) +{ //if points isn't an array, use arguments as the array - if (!(points instanceof Array)) { + if (!(points instanceof Array)) + { points = Array.prototype.slice.call(arguments); } //if this is a flat array of numbers, convert it to points - if (points[0] instanceof Point) { + if (points[0] instanceof Point) + { var p = []; - for (var i = 0, il = points.length; i < il; i++) { + for (var i = 0, il = points.length; i < il; i++) + { p.push(points[i].x, points[i].y); } @@ -51,7 +55,8 @@ * * @return {Polygon} a copy of the polygon */ -Polygon.prototype.clone = function () { +Polygon.prototype.clone = function () +{ return new Polygon(this.points.slice()); }; @@ -62,19 +67,22 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this polygon */ -Polygon.prototype.contains = function (x, y) { +Polygon.prototype.contains = function (x, y) +{ var inside = false; // use some raycasting to test hits // https://github.com/substack/point-in-polygon/blob/master/index.js var length = this.points.length / 2; - for (var i = 0, j = length - 1; i < length; j = i++) { + for (var i = 0, j = length - 1; i < length; j = i++) + { var xi = this.points[i * 2], yi = this.points[i * 2 + 1], xj = this.points[j * 2], yj = this.points[j * 2 + 1], intersect = ((yi > y) !== (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi); - if (intersect) { + if (intersect) + { inside = !inside; } } diff --git a/src/core/math/shapes/Rectangle.js b/src/core/math/shapes/Rectangle.js index 16ac62a..4008b68 100644 --- a/src/core/math/shapes/Rectangle.js +++ b/src/core/math/shapes/Rectangle.js @@ -10,7 +10,8 @@ * @param width {number} The overall width of this rectangle * @param height {number} The overall height of this rectangle */ -function Rectangle(x, y, width, height) { +function Rectangle(x, y, width, height) +{ /** * @member {number} * @default 0 @@ -60,7 +61,8 @@ * * @return {Rectangle} a copy of the rectangle */ -Rectangle.prototype.clone = function () { +Rectangle.prototype.clone = function () +{ return new Rectangle(this.x, this.y, this.width, this.height); }; @@ -71,13 +73,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rectangle */ -Rectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +Rectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/math/shapes/RoundedRectangle.js b/src/core/math/shapes/RoundedRectangle.js index 27d286e..7bf6411 100644 --- a/src/core/math/shapes/RoundedRectangle.js +++ b/src/core/math/shapes/RoundedRectangle.js @@ -11,7 +11,8 @@ * @param height {number} The overall height of this rounded rectangle * @param radius {number} Controls the radius of the rounded corners */ -function RoundedRectangle(x, y, width, height, radius) { +function RoundedRectangle(x, y, width, height, radius) +{ /** * @member {number} * @default 0 @@ -58,7 +59,8 @@ * * @return {RoundedRectangle} a copy of the rounded rectangle */ -RoundedRectangle.prototype.clone = function () { +RoundedRectangle.prototype.clone = function () +{ return new RoundedRectangle(this.x, this.y, this.width, this.height, this.radius); }; @@ -69,13 +71,17 @@ * @param y {number} The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rounded Rectangle */ -RoundedRectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { +RoundedRectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { return false; } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { return true; } } diff --git a/src/core/primitives/Graphics.js b/src/core/primitives/Graphics.js index 261c534..e902d2a 100644 --- a/src/core/primitives/Graphics.js +++ b/src/core/primitives/Graphics.js @@ -16,7 +16,8 @@ * @extends DisplayObjectContainer * @namespace PIXI */ -function Graphics() { +function Graphics() +{ DisplayObjectContainer.call(this); this.renderable = true; @@ -154,16 +155,20 @@ * @private */ cacheAsBitmap: { - get: function () { + get: function () + { return this._cacheAsBitmap; }, - set: function (value) { + set: function (value) + { this._cacheAsBitmap = value; - if (this._cacheAsBitmap) { + if (this._cacheAsBitmap) + { this._generateCachedSprite(); } - else { + else + { this.destroyCachedSprite(); this.dirty = true; } @@ -176,7 +181,8 @@ * * @return {Graphics} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ var clone = new Graphics(); clone.renderable = this.renderable; @@ -192,7 +198,8 @@ clone.cachedSpriteDirty = this.cachedSpriteDirty; // copy graphics data - for (var i = 0; i < this.graphicsData.length; ++i) { + for (var i = 0; i < this.graphicsData.length; ++i) + { clone.graphicsData.push(this.graphicsData.clone()); } @@ -211,17 +218,21 @@ * @param alpha {number} alpha of the line to draw, will update the objects stored style * @return {Graphics} */ -Graphics.prototype.lineStyle = function (lineWidth, color, alpha) { +Graphics.prototype.lineStyle = function (lineWidth, color, alpha) +{ this.lineWidth = lineWidth || 0; this.lineColor = color || 0; this.lineAlpha = (arguments.length < 3) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length) + { // halfway through a line? start a new one! this.drawShape( new math.Polygon( this.currentPath.shape.points.slice(-2) )); } - else { + else + { // otherwise its empty so lets just set the line properties this.currentPath.lineWidth = this.lineWidth; this.currentPath.lineColor = this.lineColor; @@ -239,7 +250,8 @@ * @param y {number} the Y coordinate to move to * @return {Graphics} */ -Graphics.prototype.moveTo = function (x, y) { +Graphics.prototype.moveTo = function (x, y) +{ this.drawShape(new math.Polygon([x,y])); return this; @@ -253,7 +265,8 @@ * @param y {number} the Y coordinate to draw to * @return {Graphics} */ -Graphics.prototype.lineTo = function (x, y) { +Graphics.prototype.lineTo = function (x, y) +{ this.currentPath.shape.points.push(x, y); this.dirty = true; @@ -270,13 +283,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -285,7 +302,8 @@ n = 20, points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { this.moveTo(0, 0); } @@ -293,7 +311,8 @@ var fromY = points[points.length-1]; var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; xa = fromX + ( (cpX - fromX) * j ); @@ -319,13 +338,17 @@ * @param toY {number} Destination point y * @return {Graphics} */ -Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points = [0, 0]; } } - else { + else + { this.moveTo(0,0); } @@ -342,7 +365,8 @@ var j = 0; - for (var i = 1; i <= n; ++i) { + for (var i = 1; i <= n; ++i) + { j = i / n; dt = (1 - j); @@ -373,13 +397,17 @@ * @param radius {number} The radius of the arc * @return {Graphics} */ -Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) { - if (this.currentPath) { - if (this.currentPath.shape.points.length === 0) { +Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { this.currentPath.shape.points.push(x1, y1); } } - else { + else + { this.moveTo(x1, y1); } @@ -392,12 +420,15 @@ b2 = x2 - x1, mm = Math.abs(a1 * b2 - b1 * a2); - if (mm < 1.0e-8 || radius === 0) { - if (points[points.length-2] !== x1 || points[points.length-1] !== y1) { + if (mm < 1.0e-8 || radius === 0) + { + if (points[points.length-2] !== x1 || points[points.length-1] !== y1) + { points.push(x1, y1); } } - else { + else + { var dd = a1 * a1 + b1 * b1, cc = a2 * a2 + b2 * b2, tt = a1 * a2 + b1 * b2, @@ -433,42 +464,51 @@ * @param anticlockwise {boolean} Optional. Specifies whether the drawing should be counterclockwise or clockwise. False is default, and indicates clockwise, while true indicates counter-clockwise. * @return {Graphics} */ -Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) { +Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) +{ var startX = cx + Math.cos(startAngle) * radius; var startY = cy + Math.sin(startAngle) * radius; var points; // TODO - This if-else makes no sense. It uses currentPath in the else where it doesn't exist... - if (this.currentPath) { + if (this.currentPath) + { points = this.currentPath.shape.points; - if (points.length === 0) { + if (points.length === 0) + { points.push(startX, startY); } - else if (points[points.length-2] !== startX || points[points.length-1] !== startY) { + else if (points[points.length-2] !== startX || points[points.length-1] !== startY) + { points.push(startX, startY); } } - else { + else + { this.moveTo(startX, startY); points = this.currentPath.shape.points; } - if (startAngle === endAngle) { + if (startAngle === endAngle) + { return this; } - if (!anticlockwise && endAngle <= startAngle) { + if (!anticlockwise && endAngle <= startAngle) + { endAngle += Math.PI * 2; } - else if (anticlockwise && startAngle <= endAngle) { + else if (anticlockwise && startAngle <= endAngle) + { startAngle += Math.PI * 2; } var sweep = anticlockwise ? (startAngle - endAngle) *-1 : (endAngle - startAngle); var segs = (Math.abs(sweep)/ (Math.PI * 2)) * 40; - if (sweep === 0) { + if (sweep === 0) + { return this; } @@ -482,7 +522,8 @@ var remainder = ( segMinus % 1 ) / segMinus; - for (var i = 0; i <= segMinus; ++i) { + for (var i = 0; i <= segMinus; ++i) + { var real = i + remainder * i; var angle = ((theta) + startAngle + (theta2 * real)); @@ -506,13 +547,16 @@ * @param alpha {number} the alpha of the fill * @return {Graphics} */ -Graphics.prototype.beginFill = function (color, alpha) { +Graphics.prototype.beginFill = function (color, alpha) +{ this.filling = true; this.fillColor = color || 0; this.fillAlpha = (alpha === undefined) ? 1 : alpha; - if (this.currentPath) { - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath) + { + if (this.currentPath.shape.points.length <= 2) + { this.currentPath.fill = this.filling; this.currentPath.fillColor = this.fillColor; this.currentPath.fillAlpha = this.fillAlpha; @@ -526,7 +570,8 @@ * * @return {Graphics} */ -Graphics.prototype.endFill = function () { +Graphics.prototype.endFill = function () +{ this.filling = false; this.fillColor = null; this.fillAlpha = 1; @@ -542,7 +587,8 @@ * @param height {number} The height of the rectangle * @return {Graphics} */ -Graphics.prototype.drawRect = function ( x, y, width, height ) { +Graphics.prototype.drawRect = function ( x, y, width, height ) +{ this.drawShape(new math.Rectangle(x,y, width, height)); return this; @@ -556,7 +602,8 @@ * @param height {number} The height of the rectangle * @param radius {number} Radius of the rectangle corners */ -Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) { +Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) +{ this.drawShape(new math.RoundedRectangle(x, y, width, height, radius)); return this; @@ -570,7 +617,8 @@ * @param radius {number} The radius of the circle * @return {Graphics} */ -Graphics.prototype.drawCircle = function (x, y, radius) { +Graphics.prototype.drawCircle = function (x, y, radius) +{ this.drawShape(new math.Circle(x,y, radius)); return this; @@ -585,7 +633,8 @@ * @param height {number} The half height of the ellipse * @return {Graphics} */ -Graphics.prototype.drawEllipse = function (x, y, width, height) { +Graphics.prototype.drawEllipse = function (x, y, width, height) +{ this.drawShape(new math.Ellipse(x, y, width, height)); return this; @@ -597,8 +646,10 @@ * @param path {Array} The path data used to construct the polygon. * @return {Graphics} */ -Graphics.prototype.drawPolygon = function (path) { - if (!(path instanceof Array)) { +Graphics.prototype.drawPolygon = function (path) +{ + if (!(path instanceof Array)) + { path = Array.prototype.slice.call(arguments); } @@ -612,7 +663,8 @@ * * @return {Graphics} */ -Graphics.prototype.clear = function () { +Graphics.prototype.clear = function () +{ this.lineWidth = 0; this.filling = false; @@ -631,7 +683,8 @@ * @param scaleMode {number} Should be one of the scaleMode consts * @return {Texture} a texture of the graphics object */ -Graphics.prototype.generateTexture = function (resolution, scaleMode) { +Graphics.prototype.generateTexture = function (resolution, scaleMode) +{ resolution = resolution || 1; var bounds = this.getBounds(); @@ -655,17 +708,21 @@ * * @param renderer {WebGLRenderer} */ -Graphics.prototype._renderWebGL = function (renderer) { +Graphics.prototype._renderWebGL = function (renderer) +{ // if the sprite is not visible or the alpha is 0 then no need to render this element - if (this.isMask === true) { + if (this.isMask === true) + { return; } // this code may still be needed so leaving for now.. - // + // /* - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture on the gpu too! @@ -681,17 +738,24 @@ return; } - */ - - // check if the webgl graphic needs to be updated - if (this.glDirty) { - this.dirty = true; - this.glDirty = false; - } + else */ - renderer.setObjectRendererer(renderer.graphicsRenderer); - renderer.graphicsRenderer.render(this); + renderer.spriteBatch.stop(); + renderer.blendModeManager.setBlendMode(this.blendMode); + // check blend mode + renderer.blendModeManager.setBlendMode( this.blendMode ); + + // check if the webgl graphic needs to be updated + if (this.glDirty) + { + this.dirty = true; + this.glDirty = false; + } + + WebGLGraphics.renderGraphics(this, renderer); + + renderer.spriteBatch.start(); }; /** @@ -700,14 +764,18 @@ * @param renderer {CanvasRenderer} * @private */ -Graphics.prototype.renderCanvas = function (renderer) { +Graphics.prototype.renderCanvas = function (renderer) +{ // 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.isMask === true) { + if (!this.visible || this.alpha <= 0 || this.isMask === true) + { return; } - if (this._cacheAsBitmap) { - if (this.dirty || this.cachedSpriteDirty) { + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { this._generateCachedSprite(); // we will also need to update the texture @@ -723,16 +791,19 @@ return; } - else { + else + { var context = renderer.context; var transform = this.worldTransform; - if (this.blendMode !== renderer.currentBlendMode) { + if (this.blendMode !== renderer.currentBlendMode) + { renderer.currentBlendMode = this.blendMode; context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode]; } - if (this._mask) { + if (this._mask) + { renderer.maskManager.pushMask(this._mask, renderer); } @@ -748,11 +819,13 @@ CanvasGraphics.renderGraphics(this, context); - for (var i = 0, j = this.children.length; i < j; ++i) { + for (var i = 0, j = this.children.length; i < j; ++i) + { this.children[i].renderCanvas(renderer); } - if (this._mask) { + if (this._mask) + { renderer.maskManager.popMask(renderer); } } @@ -763,13 +836,16 @@ * * @return {Rectangle} the rectangular bounding area */ -Graphics.prototype.getBounds = function (matrix) { +Graphics.prototype.getBounds = function (matrix) +{ // return an empty object if the item is a mask! - if (this.isMask) { + if (this.isMask) + { return math.Rectangle.EMPTY; } - if (this.dirty) { + if (this.dirty) + { this.updateLocalBounds(); this.glDirty = true; @@ -841,23 +917,27 @@ * Update the bounds of the object * */ -Graphics.prototype.updateLocalBounds = function () { +Graphics.prototype.updateLocalBounds = function () +{ var minX = Infinity; var maxX = -Infinity; var minY = Infinity; var maxY = -Infinity; - if (this.graphicsData.length) { + if (this.graphicsData.length) + { var shape, points, x, y, w, h; - for (var i = 0; i < this.graphicsData.length; i++) { + for (var i = 0; i < this.graphicsData.length; i++) + { var data = this.graphicsData[i]; var type = data.type; var lineWidth = data.lineWidth; shape = data.shape; - if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) { + if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) + { x = shape.x - lineWidth/2; y = shape.y - lineWidth/2; w = shape.width + lineWidth; @@ -869,7 +949,8 @@ minY = y < minY ? y : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.CIRC) { + else if (type === CONST.SHAPES.CIRC) + { x = shape.x; y = shape.y; w = shape.radius + lineWidth/2; @@ -881,7 +962,8 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else if (type === CONST.SHAPES.ELIP) { + else if (type === CONST.SHAPES.ELIP) + { x = shape.x; y = shape.y; w = shape.width + lineWidth/2; @@ -893,11 +975,13 @@ minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } - else { + else + { // POLY points = shape.points; - for (var j = 0; j < points.length; j += 2) { + for (var j = 0; j < points.length; j += 2) + { x = points[j]; y = points[j+1]; @@ -910,7 +994,8 @@ } } } - else { + else + { minX = 0; maxX = 0; minY = 0; @@ -931,10 +1016,12 @@ * * @private */ -Graphics.prototype._generateCachedSprite = function () { +Graphics.prototype._generateCachedSprite = function () +{ var bounds = this.getLocalBounds(); - if (!this._cachedSprite) { + if (!this._cachedSprite) + { var canvasBuffer = new CanvasBuffer(bounds.width, bounds.height); var texture = Texture.fromCanvas(canvasBuffer.canvas); @@ -943,7 +1030,8 @@ this._cachedSprite.worldTransform = this.worldTransform; } - else { + else + { this._cachedSprite.buffer.resize(bounds.width, bounds.height); } @@ -968,7 +1056,8 @@ * * @private */ -Graphics.prototype.updateCachedSpriteTexture = function () { +Graphics.prototype.updateCachedSpriteTexture = function () +{ var cachedSprite = this._cachedSprite; var texture = cachedSprite.texture; var canvas = cachedSprite.buffer.canvas; @@ -989,7 +1078,8 @@ * Destroys a previous cached sprite. * */ -Graphics.prototype.destroyCachedSprite = function () { +Graphics.prototype.destroyCachedSprite = function () +{ this._cachedSprite.texture.destroy(true); // let the gc collect the unused sprite @@ -1003,10 +1093,13 @@ * @param {Circle|Rectangle|Ellipse|Line|Polygon} shape The Shape object to draw. * @return {GraphicsData} The generated GraphicsData object. */ -Graphics.prototype.drawShape = function (shape) { - if (this.currentPath) { +Graphics.prototype.drawShape = function (shape) +{ + if (this.currentPath) + { // check current path! - if (this.currentPath.shape.points.length <= 2) { + if (this.currentPath.shape.points.length <= 2) + { this.graphicsData.pop(); } } @@ -1017,7 +1110,8 @@ this.graphicsData.push(data); - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { data.shape.closed = this.filling; this.currentPath = data; } diff --git a/src/core/primitives/GraphicsData.js b/src/core/primitives/GraphicsData.js index 99decbe..788f6f2 100644 --- a/src/core/primitives/GraphicsData.js +++ b/src/core/primitives/GraphicsData.js @@ -4,7 +4,8 @@ * @class * @namespace PIXI */ -function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) { +function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) +{ this.lineWidth = lineWidth; this.lineColor = lineColor; this.lineAlpha = lineAlpha; @@ -27,7 +28,8 @@ * * @return {GraphicsData} */ -GraphicsData.prototype.clone = function () { +GraphicsData.prototype.clone = function () +{ return new GraphicsData( this.lineWidth, this.lineColor, diff --git a/src/core/renderers/canvas/CanvasRenderer.js b/src/core/renderers/canvas/CanvasRenderer.js index 15a0978..7aebd44 100644 --- a/src/core/renderers/canvas/CanvasRenderer.js +++ b/src/core/renderers/canvas/CanvasRenderer.js @@ -17,17 +17,22 @@ * @param [options.resolution=1] {number} the resolution of the renderer retina would be 2 * @param [options.clearBeforeRender=true] {boolean} This sets if the CanvasRenderer will clear the canvas or not before the new render pass. */ -function CanvasRenderer(width, height, options) { +function CanvasRenderer(width, height, options) +{ utils.sayHello('Canvas'); - if (options) { - for (var i in CONST.defaultRenderOptions) { - if (typeof options[i] === 'undefined') { + if (options) + { + for (var i in CONST.defaultRenderOptions) + { + if (typeof options[i] === 'undefined') + { options[i] = CONST.defaultRenderOptions[i]; } } } - else { + else + { options = CONST.defaultRenderOptions; } @@ -156,19 +161,24 @@ this.smoothProperty = null; - if (this.context.imageSmoothingEnabled) { + if (this.context.imageSmoothingEnabled) + { this.smoothProperty = 'imageSmoothingEnabled'; } - else if (this.context.webkitImageSmoothingEnabled) { + else if (this.context.webkitImageSmoothingEnabled) + { this.smoothProperty = 'webkitImageSmoothingEnabled'; } - else if (this.context.mozImageSmoothingEnabled) { + else if (this.context.mozImageSmoothingEnabled) + { this.smoothProperty = 'mozImageSmoothingEnabled'; } - else if (this.context.oImageSmoothingEnabled) { + else if (this.context.oImageSmoothingEnabled) + { this.smoothProperty = 'oImageSmoothingEnabled'; } - else if (this.context.msImageSmoothingEnabled) { + else if (this.context.msImageSmoothingEnabled) + { this.smoothProperty = 'msImageSmoothingEnabled'; } @@ -193,10 +203,12 @@ * @memberof CanvasRenderer# */ backgroundColor: { - get: function () { + get: function () + { return this._backgroundColor; }, - set: function (val) { + set: function (val) + { this._backgroundColor = val; this._backgroundColorString = utils.hex2string(val); } @@ -208,7 +220,8 @@ * * @param object {DisplayObject} the object to be rendered */ -CanvasRenderer.prototype.render = function (object) { +CanvasRenderer.prototype.render = function (object) +{ object.updateTransform(); this.context.setTransform(1,0,0,1,0,0); @@ -218,16 +231,20 @@ this.currentBlendMode = CONST.blendModes.NORMAL; this.context.globalCompositeOperation = this.blendModes[CONST.blendModes.NORMAL]; - if (navigator.isCocoonJS && this.view.screencanvas) { + if (navigator.isCocoonJS && this.view.screencanvas) + { this.context.fillStyle = 'black'; this.context.clear(); } - if (this.clearBeforeRender) { - if (this.transparent) { + if (this.clearBeforeRender) + { + if (this.transparent) + { this.context.clearRect(0, 0, this.width, this.height); } - else { + else + { this.context.fillStyle = this._backgroundColorString; this.context.fillRect(0, 0, this.width , this.height); } @@ -241,8 +258,10 @@ * * @param [removeView=false] {boolean} Removes the Canvas element from the DOM. */ -CanvasRenderer.prototype.destroy = function (removeView) { - if (removeView && this.view.parent) { +CanvasRenderer.prototype.destroy = function (removeView) +{ + if (removeView && this.view.parent) + { this.view.parent.removeChild(this.view); } @@ -257,14 +276,16 @@ * @param width {number} the new width of the canvas view * @param height {number} the new height of the canvas view */ -CanvasRenderer.prototype.resize = function (width, height) { +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) { + if (this.autoResize) + { this.view.style.width = this.width / this.resolution + 'px'; this.view.style.height = this.height / this.resolution + 'px'; } @@ -276,7 +297,8 @@ * @param displayObject {DisplayObject} The displayObject to render * @private */ -CanvasRenderer.prototype.renderDisplayObject = function (displayObject) { +CanvasRenderer.prototype.renderDisplayObject = function (displayObject) +{ displayObject.renderCanvas(this); }; @@ -285,11 +307,14 @@ * * @private */ -CanvasRenderer.prototype._mapBlendModes = function () { - if (!this.blendModes) { +CanvasRenderer.prototype._mapBlendModes = function () +{ + if (!this.blendModes) + { this.blendModes = {}; - if (utils.canUseNewCanvasBlendModes()) { + if (utils.canUseNewCanvasBlendModes()) + { this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? this.blendModes[CONST.blendModes.MULTIPLY] = 'multiply'; @@ -308,7 +333,8 @@ this.blendModes[CONST.blendModes.COLOR] = 'color'; this.blendModes[CONST.blendModes.LUMINOSITY] = 'luminosity'; } - else { + else + { // this means that the browser does not support the cool new blend modes in canvas 'cough' ie 'cough' this.blendModes[CONST.blendModes.NORMAL] = 'source-over'; this.blendModes[CONST.blendModes.ADD] = 'lighter'; //IS THIS OK??? diff --git a/src/core/renderers/canvas/utils/CanvasBuffer.js b/src/core/renderers/canvas/utils/CanvasBuffer.js index ebe5d47..b183a66 100644 --- a/src/core/renderers/canvas/utils/CanvasBuffer.js +++ b/src/core/renderers/canvas/utils/CanvasBuffer.js @@ -6,7 +6,8 @@ * @param width {number} the width for the newly created canvas * @param height {number} the height for the newly created canvas */ -function CanvasBuffer(width, height) { +function CanvasBuffer(width, height) +{ /** * The Canvas object that belongs to this CanvasBuffer. * @@ -36,10 +37,12 @@ * @memberof CanvasBuffer# */ width: { - get: function () { + get: function () + { return this.canvas.width; }, - set: function (val) { + set: function (val) + { this.canvas.width = val; } }, @@ -50,10 +53,12 @@ * @memberof CanvasBuffer# */ height: { - get: function () { + get: function () + { return this.canvas.height; }, - set: function (val) { + set: function (val) + { this.canvas.height = val; } } @@ -64,7 +69,8 @@ * * @private */ -CanvasBuffer.prototype.clear = function () { +CanvasBuffer.prototype.clear = function () +{ this.context.setTransform(1, 0, 0, 1, 0, 0); this.context.clearRect(0,0, this.canvas.width, this.canvas.height); }; @@ -75,7 +81,8 @@ * @param width {number} the new width of the canvas * @param height {number} the new height of the canvas */ -CanvasBuffer.prototype.resize = function (width, height) { +CanvasBuffer.prototype.resize = function (width, height) +{ this.canvas.width = width; this.canvas.height = height; }; diff --git a/src/core/renderers/canvas/utils/CanvasGraphics.js b/src/core/renderers/canvas/utils/CanvasGraphics.js index c7eaa2a..3f2a91f 100644 --- a/src/core/renderers/canvas/utils/CanvasGraphics.js +++ b/src/core/renderers/canvas/utils/CanvasGraphics.js @@ -13,15 +13,18 @@ * @param graphics {Graphics} the actual graphics object to render * @param context {CanvasRenderingContext2D} the 2d drawing method of the canvas */ -CanvasGraphics.renderGraphics = function (graphics, context) { +CanvasGraphics.renderGraphics = function (graphics, context) +{ var worldAlpha = graphics.worldAlpha; - if (graphics.dirty) { + if (graphics.dirty) + { this.updateGraphicsTint(graphics); graphics.dirty = false; } - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; @@ -30,69 +33,82 @@ context.lineWidth = data.lineWidth; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { context.beginPath(); var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } - if (shape.closed) { + if (shape.closed) + { context.lineTo(points[0], points[1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fillRect(shape.x, shape.y, shape.width, shape.height); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.strokeRect(shape.x, shape.y, shape.width, shape.height); } } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.beginPath(); context.arc(shape.x, shape.y, shape.radius,0,2*Math.PI); context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas var w = shape.width * 2; @@ -119,18 +135,21 @@ context.closePath(); - if (data.fill) { + if (data.fill) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); } } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; var width = shape.width; @@ -152,13 +171,15 @@ context.quadraticCurveTo(rx, ry, rx, ry + radius); context.closePath(); - if (data.fillColor || data.fillColor === 0) { + if (data.fillColor || data.fillColor === 0) + { context.globalAlpha = data.fillAlpha * worldAlpha; context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); context.fill(); } - if (data.lineWidth) { + if (data.lineWidth) + { context.globalAlpha = data.lineAlpha * worldAlpha; context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); context.stroke(); @@ -174,45 +195,54 @@ * @param graphics {Graphics} the graphics which will be used as a mask * @param context {CanvasRenderingContext2D} the context 2d method of the canvas */ -CanvasGraphics.renderGraphicsMask = function (graphics, context) { +CanvasGraphics.renderGraphicsMask = function (graphics, context) +{ var len = graphics.graphicsData.length; - if (len === 0) { + if (len === 0) + { return; } context.beginPath(); - for (var i = 0; i < len; i++) { + for (var i = 0; i < len; i++) + { var data = graphics.graphicsData[i]; var shape = data.shape; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { var points = shape.points; context.moveTo(points[0], points[1]); - for (var j=1; j < points.length/2; j++) { + for (var j=1; j < points.length/2; j++) + { context.lineTo(points[j * 2], points[j * 2 + 1]); } // if the first and last point are the same close the path - much neater :) - if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) { + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { context.closePath(); } } - else if (data.type === CONST.SHAPES.RECT) { + else if (data.type === CONST.SHAPES.RECT) + { context.rect(shape.x, shape.y, shape.width, shape.height); context.closePath(); } - else if (data.type === CONST.SHAPES.CIRC) { + else if (data.type === CONST.SHAPES.CIRC) + { // TODO - need to be Undefined! context.arc(shape.x, shape.y, shape.radius, 0, 2 * Math.PI); context.closePath(); } - else if (data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.ELIP) + { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas @@ -237,7 +267,8 @@ context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); context.closePath(); } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { var rx = shape.x; var ry = shape.y; @@ -262,8 +293,10 @@ } }; -CanvasGraphics.updateGraphicsTint = function (graphics) { - if (graphics.tint === 0xFFFFFF) { +CanvasGraphics.updateGraphicsTint = function (graphics) +{ + if (graphics.tint === 0xFFFFFF) + { return; } @@ -271,7 +304,8 @@ var tintG = (graphics.tint >> 8 & 0xFF) / 255; var tintB = (graphics.tint & 0xFF)/ 255; - for (var i = 0; i < graphics.graphicsData.length; i++) { + for (var i = 0; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; var fillColor = data.fillColor | 0; diff --git a/src/core/renderers/canvas/utils/CanvasMaskManager.js b/src/core/renderers/canvas/utils/CanvasMaskManager.js index e04a733..9827d36 100644 --- a/src/core/renderers/canvas/utils/CanvasMaskManager.js +++ b/src/core/renderers/canvas/utils/CanvasMaskManager.js @@ -6,7 +6,8 @@ * @class * @namespace PIXI */ -function CanvasMaskManager() {} +function CanvasMaskManager() +{} CanvasMaskManager.prototype.constructor = CanvasMaskManager; module.exports = CanvasMaskManager; @@ -17,7 +18,8 @@ * @param maskData {object} the maskData that will be pushed * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.pushMask = function (maskData, renderer) { +CanvasMaskManager.prototype.pushMask = function (maskData, renderer) +{ renderer.context.save(); var cacheAlpha = maskData.alpha; @@ -45,6 +47,7 @@ * * @param renderer {WebGLRenderer|CanvasRenderer} The renderer context to use. */ -CanvasMaskManager.prototype.popMask = function (renderer) { +CanvasMaskManager.prototype.popMask = function (renderer) +{ renderer.context.restore(); }; diff --git a/src/core/renderers/canvas/utils/CanvasTinter.js b/src/core/renderers/canvas/utils/CanvasTinter.js index 17e0529..d2fb1bc 100644 --- a/src/core/renderers/canvas/utils/CanvasTinter.js +++ b/src/core/renderers/canvas/utils/CanvasTinter.js @@ -14,7 +14,8 @@ * @param color {number} the color to use to tint the sprite with * @return {HTMLCanvasElement} The tinted canvas */ -CanvasTinter.getTintedTexture = function (sprite, color) { +CanvasTinter.getTintedTexture = function (sprite, color) +{ var texture = sprite.texture; color = CanvasTinter.roundColor(color); @@ -23,7 +24,8 @@ texture.tintCache = texture.tintCache || {}; - if (texture.tintCache[stringColor]) { + if (texture.tintCache[stringColor]) + { return texture.tintCache[stringColor]; } @@ -33,14 +35,16 @@ //CanvasTinter.tintWithPerPixel(texture, stringColor, canvas); CanvasTinter.tintMethod(texture, color, canvas); - if (CanvasTinter.convertTintToImage) { + if (CanvasTinter.convertTintToImage) + { // is this better? var tintImage = new Image(); tintImage.src = canvas.toDataURL(); texture.tintCache[stringColor] = tintImage; } - else { + else + { texture.tintCache[stringColor] = canvas; // if we are not converting the texture to an image then we need to lose the reference to the canvas CanvasTinter.canvas = null; @@ -56,7 +60,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithMultiply = function (texture, color, canvas) { +CanvasTinter.tintWithMultiply = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -104,7 +109,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithOverlay = function (texture, color, canvas) { +CanvasTinter.tintWithOverlay = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -139,7 +145,8 @@ * @param color {number} the color to use to tint the sprite with * @param canvas {HTMLCanvasElement} the current canvas */ -CanvasTinter.tintWithPerPixel = function (texture, color, canvas) { +CanvasTinter.tintWithPerPixel = function (texture, color, canvas) +{ var context = canvas.getContext( '2d' ); var crop = texture.crop; @@ -167,7 +174,8 @@ var pixels = pixelData.data; - for (var i = 0; i < pixels.length; i += 4) { + for (var i = 0; i < pixels.length; i += 4) + { pixels[i+0] *= r; pixels[i+1] *= g; pixels[i+2] *= b; @@ -181,7 +189,8 @@ * * @param color {number} the color to round, should be a hex color */ -CanvasTinter.roundColor = function (color) { +CanvasTinter.roundColor = function (color) +{ var step = CanvasTinter.cacheStepsPerColorChannel; var rgbValues = utils.hex2rgb(color); diff --git a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js index 9f2f89a..35edbaf 100644 --- a/src/core/renderers/webgl/managers/WebGLBlendModeManager.js +++ b/src/core/renderers/webgl/managers/WebGLBlendModeManager.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLBlendModeManager(renderer) { +function WebGLBlendModeManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -23,8 +24,10 @@ * * @param blendMode {number} the blendMode, should be a Pixi const, such as BlendModes.ADD */ -WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) { - if (this.currentBlendMode === blendMode) { +WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) +{ + if (this.currentBlendMode === blendMode) + { return false; } diff --git a/src/core/renderers/webgl/managers/WebGLFilterManager.js b/src/core/renderers/webgl/managers/WebGLFilterManager.js index 1179258..2dac048 100644 --- a/src/core/renderers/webgl/managers/WebGLFilterManager.js +++ b/src/core/renderers/webgl/managers/WebGLFilterManager.js @@ -7,7 +7,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLFilterManager(renderer) { +function WebGLFilterManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -32,7 +33,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.texturePool.length = 0; self.initShaderBuffers(); }); @@ -46,7 +48,8 @@ * @param renderer {WebGLRenderer} * @param buffer {ArrayBuffer} */ -WebGLFilterManager.prototype.begin = function (buffer) { +WebGLFilterManager.prototype.begin = function (buffer) +{ this.defaultShader = this.renderer.shaderManager.defaultShader; this.width = this.renderer.projection.x * 2; @@ -60,7 +63,8 @@ * * @param filterBlock {object} the filter that will be pushed to the current filter stack */ -WebGLFilterManager.prototype.pushFilter = function (filterBlock) { +WebGLFilterManager.prototype.pushFilter = function (filterBlock) +{ var gl = this.renderer.gl; var projection = this.renderer.projection; @@ -78,10 +82,12 @@ this.offsetY += filterBlock._filterArea.y; var texture = this.texturePool.pop(); - if (!texture) { + if (!texture) + { texture = new FilterTexture(this.renderer.gl, this.width, this.height); } - else { + else + { texture.resize(this.width, this.height); } @@ -98,29 +104,35 @@ var localX = filterArea.x, localY = filterArea.y; - if (filterArea.x < 0) { + if (filterArea.x < 0) + { filterArea.width += filterArea.x; filterArea.x = 0; } - if (filterArea.y < 0) { + if (filterArea.y < 0) + { filterArea.height += filterArea.y; filterArea.y = 0; } - if (localX + filterArea.width > this.width) { + if (localX + filterArea.width > this.width) + { filterArea.width = this.width - localX; } - if (localY + filterArea.height > this.height) { + if (localY + filterArea.height > this.height) + { filterArea.height = this.height - localY; } - if (filterArea.width < 0) { + if (filterArea.width < 0) + { filterArea.width = 0; } - if (filterArea.height < 0) { + if (filterArea.height < 0) + { filterArea.height = 0; } @@ -154,7 +166,8 @@ * Removes the last filter from the filter stack and doesn't return it. * */ -WebGLFilterManager.prototype.popFilter = function () { +WebGLFilterManager.prototype.popFilter = function () +{ var gl = this.renderer.gl; var filterBlock = this.filterStack.pop(); @@ -163,7 +176,8 @@ var projection = this.renderer.projection; var offset = this.renderer.offset; - if (filterBlock.filterPasses.length > 1) { + if (filterBlock.filterPasses.length > 1) + { gl.viewport(0, 0, filterArea.width, filterArea.height); gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); @@ -193,7 +207,8 @@ var inputTexture = texture; var outputTexture = this.texturePool.pop(); - if (!outputTexture) { + if (!outputTexture) + { outputTexture = new FilterTexture(this.renderer.gl, this.width, this.height); } outputTexture.resize(this.width, this.height); @@ -204,7 +219,8 @@ gl.disable(gl.BLEND); - for (var i = 0; i < filterBlock.filterPasses.length-1; i++) { + for (var i = 0; i < filterBlock.filterPasses.length-1; i++) + { var filterPass = filterBlock.filterPasses[i]; gl.bindFramebuffer(gl.FRAMEBUFFER, outputTexture.frameBuffer ); @@ -243,10 +259,12 @@ var buffer = this.buffer; // time to render the filters texture to the previous scene - if (this.filterStack.length === 0) { + if (this.filterStack.length === 0) + { gl.colorMask(true, true, true, true);//this.transparent); } - else { + else + { var currentFilter = this.filterStack[this.filterStack.length-1]; filterArea = currentFilter._filterArea; @@ -332,13 +350,15 @@ * @param width {number} the horizontal range of the filter * @param height {number} the vertical range of the filter */ -WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) { +WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) +{ // use program var gl = this.renderer.gl; var shader = filter.shaders[gl.id]; - if (!shader) { + if (!shader) + { shader = new Shader(gl); shader.fragmentSrc = filter.fragmentSrc; @@ -356,7 +376,8 @@ gl.uniform2f(shader.projectionVector, width/2, -height/2); gl.uniform2f(shader.offsetVector, 0,0); - if (filter.uniforms.dimensions) { + 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]; @@ -386,7 +407,8 @@ * Initialises the shader buffers. * */ -WebGLFilterManager.prototype.initShaderBuffers = function () { +WebGLFilterManager.prototype.initShaderBuffers = function () +{ var gl = this.renderer.gl; // create some buffers @@ -432,7 +454,8 @@ * Destroys the filter and removes it from the filter stack. * */ -WebGLFilterManager.prototype.destroy = function () { +WebGLFilterManager.prototype.destroy = function () +{ var gl = this.renderer.gl; this.filterStack = null; @@ -441,7 +464,8 @@ this.offsetY = 0; // destroy textures - for (var i = 0; i < this.texturePool.length; i++) { + for (var i = 0; i < this.texturePool.length; i++) + { this.texturePool[i].destroy(); } diff --git a/src/core/renderers/webgl/managers/WebGLManager.js b/src/core/renderers/webgl/managers/WebGLManager.js index 9d47b5c..c30cd51 100644 --- a/src/core/renderers/webgl/managers/WebGLManager.js +++ b/src/core/renderers/webgl/managers/WebGLManager.js @@ -3,7 +3,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLManager(renderer) { +function WebGLManager(renderer) +{ /** * The renderer this manager works for. * @@ -15,6 +16,7 @@ WebGLManager.prototype.constructor = WebGLManager; module.exports = WebGLManager; -WebGLManager.prototype.destroy = function () { +WebGLManager.prototype.destroy = function () +{ this.renderer = null; }; diff --git a/src/core/renderers/webgl/managers/WebGLMaskManager.js b/src/core/renderers/webgl/managers/WebGLMaskManager.js index 2f90b64..e568812 100644 --- a/src/core/renderers/webgl/managers/WebGLMaskManager.js +++ b/src/core/renderers/webgl/managers/WebGLMaskManager.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLMaskManager(renderer) { +function WebGLMaskManager(renderer) +{ WebGLManager.call(this, renderer); } @@ -19,12 +20,15 @@ * * @param maskData {any[]} */ -WebGLMaskManager.prototype.pushMask = function (maskData) { - if (maskData.dirty) { +WebGLMaskManager.prototype.pushMask = function (maskData) +{ + if (maskData.dirty) + { WebGLGraphics.updateGraphics(maskData, this.renderer.gl); } - if (!maskData._webGL[this.renderer.gl.id].data.length) { + if (!maskData._webGL[this.renderer.gl.id].data.length) + { return; } @@ -36,6 +40,7 @@ * * @param maskData {any[]} */ -WebGLMaskManager.prototype.popMask = function (maskData) { +WebGLMaskManager.prototype.popMask = function (maskData) +{ this.renderer.stencilManager.popStencil(maskData, maskData._webGL[this.renderer.gl.id].data[0], this.renderer); }; diff --git a/src/core/renderers/webgl/managers/WebGLShaderManager.js b/src/core/renderers/webgl/managers/WebGLShaderManager.js index fef071c..90c6477 100644 --- a/src/core/renderers/webgl/managers/WebGLShaderManager.js +++ b/src/core/renderers/webgl/managers/WebGLShaderManager.js @@ -10,7 +10,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLShaderManager(renderer) { +function WebGLShaderManager(renderer) +{ WebGLManager.call(this, renderer); /** @@ -28,7 +29,8 @@ */ this.tempAttribState = []; - for (var i = 0; i < this.maxAttibs; i++) { + for (var i = 0; i < this.maxAttibs; i++) + { this.attribState[i] = false; } @@ -66,7 +68,8 @@ // listen for context and update necessary shaders var self = this; - this.renderer.on('context', function (event) { + this.renderer.on('context', function (event) + { var gl = event.data; // this shader is used for rendering primitives @@ -97,29 +100,36 @@ * * @param attribs {Array} attribs */ -WebGLShaderManager.prototype.setAttribs = function (attribs) { +WebGLShaderManager.prototype.setAttribs = function (attribs) +{ // reset temp state var i; - for (i = 0; i < this.tempAttribState.length; i++) { + for (i = 0; i < this.tempAttribState.length; i++) + { this.tempAttribState[i] = false; } // set the new attribs - for (var a in attribs) { + for (var a in attribs) + { this.tempAttribState[attribs[a]] = true; } var gl = this.renderer.gl; - for (i = 0; i < this.attribState.length; i++) { - if (this.attribState[i] !== this.tempAttribState[i]) { + for (i = 0; i < this.attribState.length; i++) + { + if (this.attribState[i] !== this.tempAttribState[i]) + { this.attribState[i] = this.tempAttribState[i]; - if (this.attribState[i]) { + if (this.attribState[i]) + { gl.enableVertexAttribArray(i); } - else { + else + { gl.disableVertexAttribArray(i); } } @@ -131,8 +141,10 @@ * * @param shader {Any} */ -WebGLShaderManager.prototype.setShader = function (shader) { - if (this._currentId === shader.uuid) { +WebGLShaderManager.prototype.setShader = function (shader) +{ + if (this._currentId === shader.uuid) + { return false; } @@ -150,7 +162,8 @@ * Destroys this object. * */ -WebGLShaderManager.prototype.destroy = function () { +WebGLShaderManager.prototype.destroy = function () +{ this.attribState = null; this.tempAttribState = null; diff --git a/src/core/renderers/webgl/managers/WebGLStencilManager.js b/src/core/renderers/webgl/managers/WebGLStencilManager.js index 9ec6398..4cb0134 100644 --- a/src/core/renderers/webgl/managers/WebGLStencilManager.js +++ b/src/core/renderers/webgl/managers/WebGLStencilManager.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this manager works for. */ -function WebGLStencilManager(renderer) { +function WebGLStencilManager(renderer) +{ WebGLManager.call(this, renderer); this.stencilStack = []; @@ -24,12 +25,14 @@ * @param graphics {Graphics} * @param webGLData {any[]} */ -WebGLStencilManager.prototype.pushStencil = function (graphics, webGLData) { +WebGLStencilManager.prototype.pushStencil = function (graphics, webGLData) +{ var gl = this.renderer.gl; this.bindGraphics(graphics, webGLData, this.renderer); - if (this.stencilStack.length === 0) { + if (this.stencilStack.length === 0) + { gl.enable(gl.STENCIL_TEST); gl.clear(gl.STENCIL_BUFFER_BIT); this.reverse = true; @@ -47,14 +50,17 @@ // draw the triangle strip! - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } @@ -62,31 +68,38 @@ // draw a quad to increment.. gl.drawElements(gl.TRIANGLE_FAN, 4, gl.UNSIGNED_SHORT, ( webGLData.indices.length - 4 ) * 2 ); - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); } this.reverse = !this.reverse; } - else { - if (!this.reverse) { + else + { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } - else { + 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) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); } } @@ -103,7 +116,8 @@ * @param graphics {Graphics} * @param webGLData {Array} */ -WebGLStencilManager.prototype.bindGraphics = function (graphics, webGLData) { +WebGLStencilManager.prototype.bindGraphics = function (graphics, webGLData) +{ //if (this._currentGraphics === graphics)return; this._currentGraphics = graphics; @@ -114,7 +128,8 @@ offset = this.renderer.offset, shader;// = this.renderer.shaderManager.primitiveShader; - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { shader = this.renderer.shaderManager.complexPrimitiveShader; this.renderer.shaderManager.setShader(shader); @@ -141,7 +156,8 @@ // set the index buffer! gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, webGLData.indexBuffer); } - else { + else + { //this.renderer.shaderManager.activatePrimitiveShader(); shader = this.renderer.shaderManager.primitiveShader; this.renderer.shaderManager.setShader( shader ); @@ -154,7 +170,7 @@ gl.uniform2f(shader.uniforms.offsetVector._location, -offset.x, -offset.y); gl.uniform3fv(shader.uniforms.tint._location, utils.hex2rgb(graphics.tint)); - + gl.uniform1f(shader.uniforms.alpha._location, graphics.worldAlpha); @@ -172,19 +188,22 @@ * @param graphics {Graphics} * @param webGLData {Array} */ -WebGLStencilManager.prototype.popStencil = function (graphics, webGLData) { +WebGLStencilManager.prototype.popStencil = function (graphics, webGLData) +{ var gl = this.renderer.gl; this.stencilStack.pop(); this.count--; - if (this.stencilStack.length === 0) { + if (this.stencilStack.length === 0) + { // the stack is empty! gl.disable(gl.STENCIL_TEST); } - else { + else + { var level = this.count; @@ -192,14 +211,17 @@ gl.colorMask(false, false, false, false); - if (webGLData.mode === 1) { + if (webGLData.mode === 1) + { this.reverse = !this.reverse; - if (this.reverse) { + if (this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } - else { + else + { gl.stencilFunc(gl.EQUAL,level+1, 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); } @@ -213,31 +235,38 @@ // draw the triangle strip! gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); - if (!this.reverse) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); } } - else { + else + { // console.log("<<>>") - if (!this.reverse) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); } - else { + 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) { + if (!this.reverse) + { gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); } - else { + else + { gl.stencilFunc(gl.EQUAL,level, 0xFF); } } @@ -253,7 +282,8 @@ * Destroys the mask stack. * */ -WebGLStencilManager.prototype.destroy = function () { +WebGLStencilManager.prototype.destroy = function () +{ this.renderer = null; this.stencilStack = null; }; diff --git a/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js b/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js index 913ba5e..1ea7d19 100644 --- a/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js +++ b/src/core/renderers/webgl/shaders/ComplexPrimitiveShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function ComplexPrimitiveShader(gl) { +function ComplexPrimitiveShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -24,7 +25,8 @@ 'uniform float flipY;', 'varying vec4 vColor;', - 'void main(void) {', + '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);', @@ -37,7 +39,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = vColor;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/FastShader.js b/src/core/renderers/webgl/shaders/FastShader.js index bd2e29a..2e5e060 100644 --- a/src/core/renderers/webgl/shaders/FastShader.js +++ b/src/core/renderers/webgl/shaders/FastShader.js @@ -6,7 +6,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function FastShader(gl) { +function FastShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -28,7 +29,8 @@ 'const vec2 center = vec2(-1.0, 1.0);', - 'void main(void) {', + 'void main(void) + {', ' vec2 v;', ' vec2 sv = aVertexPosition * aScale;', ' v.x = (sv.x) * cos(aRotation) - (sv.y) * sin(aRotation);', @@ -49,7 +51,8 @@ 'uniform sampler2D uSampler;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/PrimitiveShader.js b/src/core/renderers/webgl/shaders/PrimitiveShader.js index 6f25409..a25f54f 100644 --- a/src/core/renderers/webgl/shaders/PrimitiveShader.js +++ b/src/core/renderers/webgl/shaders/PrimitiveShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function PrimitiveShader(gl) { +function PrimitiveShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -23,7 +24,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + '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);', @@ -36,7 +38,8 @@ 'varying vec4 vColor;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = vColor;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/shaders/Shader.js b/src/core/renderers/webgl/shaders/Shader.js index f8964f5..fd75ef5 100644 --- a/src/core/renderers/webgl/shaders/Shader.js +++ b/src/core/renderers/webgl/shaders/Shader.js @@ -6,7 +6,8 @@ * @param [fragmentSrc] {string} The source of the fragment shader. * @param [vertexSrc] {string} The source of the vertex shader. */ -function Shader(gl, vertexSrc, fragmentSrc, customUniforms, customAttributes) { +function Shader(gl, vertexSrc, fragmentSrc, customUniforms, customAttributes) +{ /** * @member {number} * @readonly @@ -33,7 +34,8 @@ dimensions: { type: '4f', value: new Float32Array(4) } }; - for (var u in customUniforms) { + for (var u in customUniforms) + { this.uniforms[u] = customUniforms[u]; } @@ -43,7 +45,8 @@ aColor: 0 }; - for (var a in customAttributes) { + for (var a in customAttributes) + { this.attributes[a] = customAttributes[a]; } @@ -66,7 +69,8 @@ 'const vec2 center = vec2(-1.0, 1.0);', - 'void main(void) {', + 'void main(void) + {', ' gl_Position = vec4( ((aVertexPosition + offsetVector) / projectionVector) + center , 0.0, 1.0);', ' vTextureCoord = aTextureCoord;', ' vColor = vec4(aColor.rgb * aColor.a, aColor.a);', @@ -85,7 +89,8 @@ 'uniform sampler2D uSampler;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;', '}' ].join('\n'); @@ -96,7 +101,8 @@ Shader.prototype.constructor = Shader; module.exports = Shader; -Shader.prototype.init = function () { +Shader.prototype.init = function () +{ this.compile(); this.gl.useProgram(this.program); @@ -105,14 +111,18 @@ this.cacheAttributeLocations(Object.keys(this.attributes)); }; -Shader.prototype.cacheUniformLocations = function (keys) { - for (var i = 0; i < keys.length; ++i) { +Shader.prototype.cacheUniformLocations = function (keys) +{ + for (var i = 0; i < keys.length; ++i) + { this.uniforms[keys[i]]._location = this.gl.getUniformLocation(this.program, keys[i]); } }; -Shader.prototype.cacheAttributeLocations = function (keys) { - for (var i = 0; i < keys.length; ++i) { +Shader.prototype.cacheAttributeLocations = function (keys) +{ + for (var i = 0; i < keys.length; ++i) + { this.attributes[keys[i]] = this.gl.getAttribLocation(this.program, keys[i]); } @@ -124,14 +134,16 @@ // 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.attributes.aColor === -1) { + // if (this.attributes.aColor === -1) + { // this.attributes.aColor = 2; // } // End worst hack eva // }; -Shader.prototype.compile = function () { +Shader.prototype.compile = function () +{ var gl = this.gl; var glVertShader = this._glCompile(gl.VERTEX_SHADER, this.vertexSrc); @@ -144,13 +156,15 @@ gl.linkProgram(program); // if linking fails, then log and cleanup - if (!gl.getProgramParameter(program, gl.LINK_STATUS)) { + if (!gl.getProgramParameter(program, gl.LINK_STATUS)) + { window.console.error('Pixi.js Error: Could not initialize shader.'); window.console.error('gl.VALIDATE_STATUS', gl.getProgramParameter(program, gl.VALIDATE_STATUS)); window.console.error('gl.getError()', gl.getError()); // if there is a program info log, log it - if (gl.getProgramInfoLog(program) !== '') { + if (gl.getProgramInfoLog(program) !== '') + { window.console.warn('Pixi.js Warning: gl.getProgramInfoLog()', gl.getProgramInfoLog(program)); } @@ -165,18 +179,21 @@ return (this.program = program); }; -Shader.prototype.syncUniforms = function () { +Shader.prototype.syncUniforms = function () +{ var gl = this.gl; this.textureCount = 1; - for (var key in this.uniforms) { + for (var key in this.uniforms) + { var uniform = this.uniforms[key], location = uniform._location, value = uniform.value, i, il; - switch (uniform.type) { + switch (uniform.type) + { // single int value case 'i': case '1i': @@ -282,7 +299,8 @@ // a Color Value case 'c': - if (typeof value === 'number') { + if (typeof value === 'number') + { value = utils.hex2rgb(value); } @@ -311,11 +329,13 @@ // array of 2D Point objects case 'v2v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(2 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 2] = value[i].x; uniform._array[i * 2 + 1] = value[i].y; } @@ -325,11 +345,13 @@ // array of 3D Point objects case 'v3v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(3 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 3] = value[i].x; uniform._array[i * 3 + 1] = value[i].y; uniform._array[i * 3 + 2] = value[i].z; @@ -341,11 +363,13 @@ // array of 4D Point objects case 'v4v': - if (!uniform._array) { + if (!uniform._array) + { uniform._array = new Float32Array(4 * value.length); } - for (i = 0, il = value.length; i < il; ++i) { + for (i = 0, il = value.length; i < il; ++i) + { uniform._array[i * 4] = value[i].x; uniform._array[i * 4 + 1] = value[i].y; uniform._array[i * 4 + 2] = value[i].z; @@ -359,7 +383,8 @@ // PIXI.Texture case 't': case 'sampler2D': - if (!uniform.value || !uniform.value.baseTexture || !uniform.value.baseTexture.hasLoaded) { + if (!uniform.value || !uniform.value.baseTexture || !uniform.value.baseTexture.hasLoaded) + { break; } @@ -376,7 +401,8 @@ this.textureCount++; // initialize the texture if we haven't yet - if (!uniform._init) { + if (!uniform._init) + { this.initSampler2D(uniform); uniform._init = true; @@ -394,11 +420,13 @@ * Initialises a Sampler2D uniform (which may only be available later on after initUniforms once the texture has loaded) * */ -Shader.prototype.initSampler2D = function (uniform) { +Shader.prototype.initSampler2D = function (uniform) +{ var gl = this.gl; // Extended texture data - if (uniform.textureData) { + if (uniform.textureData) + { var data = uniform.textureData; // GLTexture = mag linear, min linear_mipmap_linear, wrap repeat + gl.generateMipmap(gl.TEXTURE_2D); @@ -417,14 +445,16 @@ var wrapT = (data.wrapT) ? data.wrapT : gl.CLAMP_TO_EDGE; var format = (data.luminance) ? gl.LUMINANCE : gl.RGBA; - if (data.repeat) { + if (data.repeat) + { wrapS = gl.REPEAT; wrapT = gl.REPEAT; } gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, !!data.flipY); - if (data.width) { + if (data.width) + { var width = (data.width) ? data.width : 512; var height = (data.height) ? data.height : 2; var border = (data.border) ? data.border : 0; @@ -432,7 +462,8 @@ // 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 { + 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); } @@ -448,7 +479,8 @@ * Destroys the shader. * */ -Shader.prototype.destroy = function () { +Shader.prototype.destroy = function () +{ this.gl.deleteProgram(this.program); this.gl = null; @@ -459,13 +491,15 @@ this.fragmentSrc = null; }; -Shader.prototype._glCompile = function (type, src) { +Shader.prototype._glCompile = function (type, src) +{ var shader = this.gl.createShader(type); this.gl.shaderSource(shader, src); this.gl.compileShader(shader); - if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) { + if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) + { window.console.log(this.gl.getShaderInfoLog(shader)); return null; } diff --git a/src/core/renderers/webgl/shaders/StripShader.js b/src/core/renderers/webgl/shaders/StripShader.js index 193f6e1..a7abcc6 100644 --- a/src/core/renderers/webgl/shaders/StripShader.js +++ b/src/core/renderers/webgl/shaders/StripShader.js @@ -5,7 +5,8 @@ * @namespace PIXI * @param gl {WebGLContext} the current WebGL drawing context */ -function StripShader(gl) { +function StripShader(gl) +{ Shader.call(this, gl, // vertex shader @@ -20,7 +21,8 @@ 'varying vec2 vTextureCoord;', - 'void main(void) {', + '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);', @@ -36,7 +38,8 @@ 'varying vec2 vTextureCoord;', - 'void main(void) {', + 'void main(void) + {', ' gl_FragColor = texture2D(uSampler, vec2(vTextureCoord.x, vTextureCoord.y)) * alpha;', '}' ].join('\n'), diff --git a/src/core/renderers/webgl/utils/FilterTexture.js b/src/core/renderers/webgl/utils/FilterTexture.js index d2c8423..4433d44 100644 --- a/src/core/renderers/webgl/utils/FilterTexture.js +++ b/src/core/renderers/webgl/utils/FilterTexture.js @@ -8,7 +8,8 @@ * @param height {number} the vertical range of the filter * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values */ -function FilterTexture(gl, width, height, scaleMode) { +function FilterTexture(gl, width, height, scaleMode) +{ /** * @member {WebGLContext} */ @@ -59,7 +60,8 @@ * Clears the filter texture. * */ -FilterTexture.prototype.clear = function () { +FilterTexture.prototype.clear = function () +{ var gl = this.gl; gl.clearColor(0,0,0, 0); @@ -72,8 +74,10 @@ * @param width {number} the new width of the texture * @param height {number} the new height of the texture */ -FilterTexture.prototype.resize = function (width, height) { - if (this.width === width && this.height === height) { +FilterTexture.prototype.resize = function (width, height) +{ + if (this.width === width && this.height === height) + { return; } @@ -96,7 +100,8 @@ * Destroys the filter texture. * */ -FilterTexture.prototype.destroy = function () { +FilterTexture.prototype.destroy = function () +{ var gl = this.gl; gl.deleteFramebuffer( this.frameBuffer ); gl.deleteTexture( this.texture ); diff --git a/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js b/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js index c4721e9..a63f4d7 100644 --- a/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js +++ b/src/core/renderers/webgl/utils/WebGLFastSpriteBatch.js @@ -14,7 +14,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this sprite batch works for. */ -function WebGLFastSpriteBatch(renderer) { +function WebGLFastSpriteBatch(renderer) +{ /** * The renderer instance this sprite batch operates on. * @@ -91,7 +92,8 @@ */ this.lastIndexCount = 0; - for (var i=0, j=0; i < numIndices; i += 6, j += 4) { + 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; @@ -144,7 +146,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.setupContext(); }); } @@ -157,7 +160,8 @@ * * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLFastSpriteBatch.prototype.setupContext = function () { +WebGLFastSpriteBatch.prototype.setupContext = function () +{ var gl = this.renderer.gl; // create a couple of buffers @@ -177,7 +181,8 @@ /** * @param spriteBatch {SpriteBatch} The SpriteBatch container to prepare for. */ -WebGLFastSpriteBatch.prototype.begin = function (spriteBatch) { +WebGLFastSpriteBatch.prototype.begin = function (spriteBatch) +{ this.shader = this.renderer.shaderManager.fastShader; this.matrix = spriteBatch.worldTransform.toArray(true); @@ -187,33 +192,38 @@ /** */ -WebGLFastSpriteBatch.prototype.end = function () { +WebGLFastSpriteBatch.prototype.end = function () +{ this.flush(); }; /** * @param spriteBatch {SpriteBatch} The SpriteBatch container to render. */ -WebGLFastSpriteBatch.prototype.render = function (spriteBatch) { +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) { + if (!sprite.texture._uvs) + { return; } this.currentBaseTexture = sprite.texture.baseTexture; // check blend mode - if (sprite.blendMode !== this.renderer.blendModeManager.currentBlendMode) { + if (sprite.blendMode !== this.renderer.blendModeManager.currentBlendMode) + { this.flush(); this.renderer.blendModeManager.setBlendMode(sprite.blendMode); } - for (var i=0,j= children.length; i= this.size) { + if (this.currentBatchSize >= this.size) + { this.flush(); } }; @@ -362,29 +379,35 @@ /** * */ -WebGLFastSpriteBatch.prototype.flush = function () { +WebGLFastSpriteBatch.prototype.flush = function () +{ // If the batch is length 0 then return as there is nothing to draw - if (this.currentBatchSize === 0) { + if (this.currentBatchSize === 0) + { return; } var gl = this.renderer.gl; // bind the current texture - if (!this.currentBaseTexture._glTextures[gl.id]) { + if (!this.currentBaseTexture._glTextures[gl.id]) + { this.renderer.updateTexture(this.currentBaseTexture, gl); } //TODO-SHOUD THIS BE ELSE??!?!?! - else { + else + { gl.bindTexture(gl.TEXTURE_2D, this.currentBaseTexture._glTextures[gl.id]); } // upload the verts to the buffer - if (this.currentBatchSize > ( this.size * 0.5 ) ) { + if (this.currentBatchSize > ( this.size * 0.5 ) ) + { gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); } - else { + else + { var view = this.vertices.subarray(0, this.currentBatchSize * this.vertByteSize); gl.bufferSubData(gl.ARRAY_BUFFER, 0, view); @@ -405,14 +428,16 @@ * Ends the batch and flushes * */ -WebGLFastSpriteBatch.prototype.stop = function () { +WebGLFastSpriteBatch.prototype.stop = function () +{ this.flush(); }; /** * */ -WebGLFastSpriteBatch.prototype.start = function () { +WebGLFastSpriteBatch.prototype.start = function () +{ var gl = this.renderer.gl; // bind the main texture diff --git a/src/core/renderers/webgl/utils/WebGLGraphics.js b/src/core/renderers/webgl/utils/WebGLGraphics.js index 55f4911..ab8f46e 100644 --- a/src/core/renderers/webgl/utils/WebGLGraphics.js +++ b/src/core/renderers/webgl/utils/WebGLGraphics.js @@ -19,7 +19,8 @@ * @param graphics {Graphics} * @param renderer {WebGLRenderer} */ -WebGLGraphics.renderGraphics = function (graphics, renderer) {//projection, offset) { +WebGLGraphics.renderGraphics = function (graphics, renderer) {//projection, offset) +{ var gl = renderer.gl; var projection = renderer.projection, @@ -27,7 +28,8 @@ shader = renderer.shaderManager.primitiveShader, webGLData; - if (graphics.dirty) { + if (graphics.dirty) + { WebGLGraphics.updateGraphics(graphics, gl); } @@ -35,8 +37,10 @@ // This could be speeded up for sure! - for (var i = 0; i < webGL.data.length; i++) { - if (webGL.data[i].mode === 1) { + for (var i = 0; i < webGL.data.length; i++) + { + if (webGL.data[i].mode === 1) + { webGLData = webGL.data[i]; renderer.stencilManager.pushStencil(graphics, webGLData, renderer); @@ -46,7 +50,8 @@ renderer.stencilManager.popStencil(graphics, webGLData, renderer); } - else { + else + { webGLData = webGL.data[i]; @@ -84,12 +89,14 @@ * @param graphicsData {Graphics} The graphics object to update * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLGraphics.updateGraphics = function (graphics, gl) { +WebGLGraphics.updateGraphics = function (graphics, gl) +{ // get the contexts graphics object var webGL = graphics._webGL[gl.id]; // if the graphics object does not exist in the webGL context time to create it! - if (!webGL) { + if (!webGL) + { webGL = graphics._webGL[gl.id] = {lastIndex:0, data:[], gl:gl}; } @@ -99,11 +106,13 @@ var i; // if the user cleared the graphics object we will need to clear every object - if (graphics.clearDirty) { + if (graphics.clearDirty) + { graphics.clearDirty = false; // lop through and return all the webGLDatas to the object pool so than can be reused later on - for (i = 0; i < webGL.data.length; i++) { + for (i = 0; i < webGL.data.length; i++) + { var graphicsData = webGL.data[i]; graphicsData.reset(); WebGLGraphics.graphicsDataPool.push( graphicsData ); @@ -119,58 +128,72 @@ // loop through the graphics datas and construct each one.. // if the object is a complex fill then the new stencil buffer technique will be used // other wise graphics objects will be pushed into a batch.. - for (i = webGL.lastIndex; i < graphics.graphicsData.length; i++) { + for (i = webGL.lastIndex; i < graphics.graphicsData.length; i++) + { var data = graphics.graphicsData[i]; - if (data.type === CONST.SHAPES.POLY) { + if (data.type === CONST.SHAPES.POLY) + { // need to add the points the the graphics object.. data.points = data.shape.points.slice(); - if (data.shape.closed) { + if (data.shape.closed) + { // close the poly if the value is true! - if (data.points[0] !== data.points[data.points.length-2] || data.points[1] !== data.points[data.points.length-1]) { + if (data.points[0] !== data.points[data.points.length-2] || data.points[1] !== data.points[data.points.length-1]) + { data.points.push(data.points[0], data.points[1]); } } // MAKE SURE WE HAVE THE CORRECT TYPE.. - if (data.fill) { - if (data.points.length >= 6) { - if (data.points.length < 6 * 2) { + if (data.fill) + { + if (data.points.length >= 6) + { + if (data.points.length < 6 * 2) + { webGLData = WebGLGraphics.switchMode(webGL, 0); var canDrawUsingSimple = WebGLGraphics.buildPoly(data, webGLData); // console.log(canDrawUsingSimple); - if (!canDrawUsingSimple) { + if (!canDrawUsingSimple) + { // console.log("<>>>") webGLData = WebGLGraphics.switchMode(webGL, 1); WebGLGraphics.buildComplexPoly(data, webGLData); } } - else { + else + { webGLData = WebGLGraphics.switchMode(webGL, 1); WebGLGraphics.buildComplexPoly(data, webGLData); } } } - if (data.lineWidth > 0) { + if (data.lineWidth > 0) + { webGLData = WebGLGraphics.switchMode(webGL, 0); WebGLGraphics.buildLine(data, webGLData); } } - else { + else + { webGLData = WebGLGraphics.switchMode(webGL, 0); - if (data.type === CONST.SHAPES.RECT) { + if (data.type === CONST.SHAPES.RECT) + { WebGLGraphics.buildRectangle(data, webGLData); } - else if (data.type === CONST.SHAPES.CIRC || data.type === CONST.SHAPES.ELIP) { + else if (data.type === CONST.SHAPES.CIRC || data.type === CONST.SHAPES.ELIP) + { WebGLGraphics.buildCircle(data, webGLData); } - else if (data.type === CONST.SHAPES.RREC) { + else if (data.type === CONST.SHAPES.RREC) + { WebGLGraphics.buildRoundedRectangle(data, webGLData); } } @@ -179,10 +202,12 @@ } // upload all the dirty data... - for (i = 0; i < webGL.data.length; i++) { + for (i = 0; i < webGL.data.length; i++) + { webGLData = webGL.data[i]; - if (webGLData.dirty) { + if (webGLData.dirty) + { webGLData.upload(); } } @@ -194,18 +219,22 @@ * @param webGL {WebGLContext} * @param type {number} */ -WebGLGraphics.switchMode = function (webGL, type) { +WebGLGraphics.switchMode = function (webGL, type) +{ var webGLData; - if (!webGL.data.length) { + if (!webGL.data.length) + { webGLData = WebGLGraphics.graphicsDataPool.pop() || new WebGLGraphicsData(webGL.gl); webGLData.mode = type; webGL.data.push(webGLData); } - else { + else + { webGLData = webGL.data[webGL.data.length-1]; - if (webGLData.mode !== type || type === 1) { + if (webGLData.mode !== type || type === 1) + { webGLData = WebGLGraphics.graphicsDataPool.pop() || new WebGLGraphicsData(webGL.gl); webGLData.mode = type; webGL.data.push(webGLData); @@ -225,7 +254,8 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildRectangle = function (graphicsData, webGLData) { +WebGLGraphics.buildRectangle = function (graphicsData, webGLData) +{ // --- // // need to convert points to a nice regular data // @@ -235,7 +265,8 @@ var width = rectData.width; var height = rectData.height; - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -265,7 +296,8 @@ indices.push(vertPos, vertPos, vertPos+1, vertPos+2, vertPos+3, vertPos+3); } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = [x, y, @@ -289,7 +321,8 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildRoundedRectangle = function (graphicsData, webGLData) { +WebGLGraphics.buildRoundedRectangle = function (graphicsData, webGLData) +{ var rrectData = graphicsData.shape; var x = rrectData.x; var y = rrectData.y; @@ -305,7 +338,8 @@ recPoints = recPoints.concat(WebGLGraphics.quadraticBezierCurve(x + width, y + radius, x + width, y, x + width - radius, y)); recPoints = recPoints.concat(WebGLGraphics.quadraticBezierCurve(x + radius, y, x, y, x, y + radius)); - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -323,7 +357,8 @@ // var i = 0; - for (i = 0; i < triangles.length; i+=3) { + for (i = 0; i < triangles.length; i+=3) + { indices.push(triangles[i] + vecPos); indices.push(triangles[i] + vecPos); indices.push(triangles[i+1] + vecPos); @@ -332,12 +367,14 @@ } - for (i = 0; i < recPoints.length; i++) { + for (i = 0; i < recPoints.length; i++) + { verts.push(recPoints[i], recPoints[++i], r, g, b, alpha); } } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = recPoints; @@ -362,7 +399,8 @@ * @param toY {number} Destination point y * @return {number[]} */ -WebGLGraphics.quadraticBezierCurve = function (fromX, fromY, cpX, cpY, toX, toY) { +WebGLGraphics.quadraticBezierCurve = function (fromX, fromY, cpX, cpY, toX, toY) +{ var xa, ya, @@ -373,14 +411,16 @@ n = 20, points = []; - function getPt(n1 , n2, perc) { + function getPt(n1 , n2, perc) + { var diff = n2 - n1; return n1 + ( diff * perc ); } var j = 0; - for (var i = 0; i <= n; i++ ) { + for (var i = 0; i <= n; i++ ) + { j = i / n; // The Green Line @@ -406,7 +446,8 @@ * @param graphicsData {Graphics} The graphics object to draw * @param webGLData {object} */ -WebGLGraphics.buildCircle = function (graphicsData, webGLData) { +WebGLGraphics.buildCircle = function (graphicsData, webGLData) +{ // need to convert points to a nice regular data var circleData = graphicsData.shape; var x = circleData.x; @@ -415,11 +456,13 @@ var height; // TODO - bit hacky?? - if (graphicsData.type === CONST.SHAPES.CIRC) { + if (graphicsData.type === CONST.SHAPES.CIRC) + { width = circleData.radius; height = circleData.radius; } - else { + else + { width = circleData.width; height = circleData.height; } @@ -429,7 +472,8 @@ var i = 0; - if (graphicsData.fill) { + if (graphicsData.fill) + { var color = utils.hex2rgb(graphicsData.fillColor); var alpha = graphicsData.fillAlpha; @@ -444,7 +488,8 @@ indices.push(vecPos); - for (i = 0; i < totalSegs + 1 ; i++) { + for (i = 0; i < totalSegs + 1 ; i++) + { verts.push(x,y, r, g, b, alpha); verts.push(x + Math.sin(seg * i) * width, @@ -457,12 +502,14 @@ indices.push(vecPos-1); } - if (graphicsData.lineWidth) { + if (graphicsData.lineWidth) + { var tempPoints = graphicsData.points; graphicsData.points = []; - for (i = 0; i < totalSegs + 1; i++) { + for (i = 0; i < totalSegs + 1; i++) + { graphicsData.points.push(x + Math.sin(seg * i) * width, y + Math.cos(seg * i) * height); } @@ -481,18 +528,22 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildLine = function (graphicsData, webGLData) { +WebGLGraphics.buildLine = function (graphicsData, webGLData) +{ // TODO OPTIMISE! var i = 0; var points = graphicsData.points; - if (points.length === 0) { + if (points.length === 0) + { return; } // if the line width is an odd number add 0.5 to align to a whole pixel - if (graphicsData.lineWidth%2) { - for (i = 0; i < points.length; i++) { + if (graphicsData.lineWidth%2) + { + for (i = 0; i < points.length; i++) + { points[i] += 0.5; } } @@ -502,7 +553,8 @@ var lastPoint = new math.Point(points[points.length - 2], points[points.length - 1]); // if the first point is the last point - gonna have issues :) - if (firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) { + if (firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) + { // need to clone as we are going to slightly modify the shape.. points = points.slice(); @@ -562,7 +614,8 @@ verts.push(p1x + perpx , p1y + perpy, r, g, b, alpha); - for (i = 1; i < length-1; i++) { + for (i = 1; i < length-1; i++) + { p1x = points[(i-1)*2]; p1y = points[(i-1)*2 + 1]; @@ -599,7 +652,8 @@ denom = a1*b2 - a2*b1; - if (Math.abs(denom) < 0.1 ) { + if (Math.abs(denom) < 0.1 ) + { denom+=10.1; verts.push(p2x - perpx , p2y - perpy, @@ -618,7 +672,8 @@ pdist = (px -p2x) * (px -p2x) + (py -p2y) + (py -p2y); - if (pdist > 140 * 140) { + if (pdist > 140 * 140) + { perp3x = perpx - perp2x; perp3y = perpy - perp2y; @@ -639,7 +694,8 @@ indexCount++; } - else { + else + { verts.push(px , py); verts.push(r, g, b, alpha); @@ -672,7 +728,8 @@ indices.push(indexStart); - for (i = 0; i < indexCount; i++) { + for (i = 0; i < indexCount; i++) + { indices.push(indexStart++); } @@ -687,11 +744,13 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildComplexPoly = function (graphicsData, webGLData) { +WebGLGraphics.buildComplexPoly = function (graphicsData, webGLData) +{ //TODO - no need to copy this as it gets turned into a FLoat32Array anyways.. var points = graphicsData.points.slice(); - if (points.length < 6) { + if (points.length < 6) + { return; } @@ -711,7 +770,8 @@ var x,y; // get size.. - for (var i = 0; i < points.length; i+=2) { + for (var i = 0; i < points.length; i+=2) + { x = points[i]; y = points[i+1]; @@ -732,7 +792,8 @@ //TODO - this aint needed! var length = points.length / 2; - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { indices.push( i ); } @@ -746,10 +807,12 @@ * @param graphicsData {Graphics} The graphics object containing all the necessary properties * @param webGLData {object} */ -WebGLGraphics.buildPoly = function (graphicsData, webGLData) { +WebGLGraphics.buildPoly = function (graphicsData, webGLData) +{ var points = graphicsData.points; - if (points.length < 6) { + if (points.length < 6) + { return; } // get first and last point.. figure out the middle! @@ -767,7 +830,8 @@ var triangles = utils.PolyK.Triangulate(points); - if (!triangles) { + if (!triangles) + { return false; } @@ -775,7 +839,8 @@ var i = 0; - for (i = 0; i < triangles.length; i+=3) { + for (i = 0; i < triangles.length; i+=3) + { indices.push(triangles[i] + vertPos); indices.push(triangles[i] + vertPos); indices.push(triangles[i+1] + vertPos); @@ -783,7 +848,8 @@ indices.push(triangles[i+2] + vertPos); } - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { verts.push(points[i * 2], points[i * 2 + 1], r, g, b, alpha); } diff --git a/src/core/renderers/webgl/utils/WebGLGraphicsData.js b/src/core/renderers/webgl/utils/WebGLGraphicsData.js index c56d05e..c739ba7 100644 --- a/src/core/renderers/webgl/utils/WebGLGraphicsData.js +++ b/src/core/renderers/webgl/utils/WebGLGraphicsData.js @@ -2,7 +2,8 @@ * @class * @private */ -function WebGLGraphicsData(gl) { +function WebGLGraphicsData(gl) +{ this.gl = gl; //TODO does this need to be split before uploding?? @@ -22,7 +23,8 @@ /** * */ -WebGLGraphicsData.prototype.reset = function () { +WebGLGraphicsData.prototype.reset = function () +{ this.points.length = 0; this.indices.length = 0; }; @@ -30,7 +32,8 @@ /** * */ -WebGLGraphicsData.prototype.upload = function () { +WebGLGraphicsData.prototype.upload = function () +{ var gl = this.gl; // this.lastIndex = graphics.graphicsData.length; diff --git a/src/core/renderers/webgl/utils/WebGLSpriteBatch.js b/src/core/renderers/webgl/utils/WebGLSpriteBatch.js index 96eaa52..55befbb 100644 --- a/src/core/renderers/webgl/utils/WebGLSpriteBatch.js +++ b/src/core/renderers/webgl/utils/WebGLSpriteBatch.js @@ -19,7 +19,8 @@ * @namespace PIXI * @param renderer {WebGLRenderer} The renderer this sprite batch works for. */ -function WebGLSpriteBatch(renderer) { +function WebGLSpriteBatch(renderer) +{ /** * * @@ -88,7 +89,8 @@ */ this.lastIndexCount = 0; - for (var i=0, j=0; i < numIndices; i += 6, j += 4) { + 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; @@ -162,7 +164,8 @@ // listen for context and update necessary buffers var self = this; - this.renderer.on('context', function () { + this.renderer.on('context', function () + { self.setupContext(); }); } @@ -173,7 +176,8 @@ /** * @param gl {WebGLContext} the current WebGL drawing context */ -WebGLSpriteBatch.prototype.setupContext = function () { +WebGLSpriteBatch.prototype.setupContext = function () +{ var gl = this.renderer.gl; // setup default shader @@ -198,7 +202,8 @@ /** * */ -WebGLSpriteBatch.prototype.begin = function () { +WebGLSpriteBatch.prototype.begin = function () +{ // this.shader = this.renderer.shaderManager.defaultShader; this.start(); @@ -206,19 +211,22 @@ /** */ -WebGLSpriteBatch.prototype.end = function () { +WebGLSpriteBatch.prototype.end = function () +{ this.flush(); }; /** * @param sprite {Sprite} the sprite to render when using this spritebatch */ -WebGLSpriteBatch.prototype.render = function (sprite) { +WebGLSpriteBatch.prototype.render = function (sprite) +{ var texture = sprite.texture; //TODO set blend modes.. // check texture.. - if (this.currentBatchSize >= this.size) { + if (this.currentBatchSize >= this.size) + { this.flush(); this.currentBaseTexture = texture.baseTexture; } @@ -227,7 +235,8 @@ var uvs = texture._uvs; // if the uvs have not updated then no point rendering just yet! - if (!uvs) { + if (!uvs) + { return; } @@ -237,7 +246,8 @@ var w0, w1, h0, h1; - if (texture.trim) { + 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; @@ -248,7 +258,8 @@ h0 = h1 + texture.crop.height; } - else { + else + { w0 = (texture.frame.width ) * (1-aX); w1 = (texture.frame.width ) * -aX; @@ -272,7 +283,8 @@ var colors = this.colors; var positions = this.positions; - if (this.renderer.roundPixels) { + if (this.renderer.roundPixels) + { // xy positions[index] = a * w1 + c * h1 + tx | 0; positions[index+1] = d * h1 + b * w1 + ty | 0; @@ -289,7 +301,8 @@ positions[index+15] = a * w1 + c * h0 + tx | 0; positions[index+16] = d * h0 + b * w1 + ty | 0; } - else { + else + { // xy positions[index] = a * w1 + c * h1 + tx; positions[index+1] = d * h1 + b * w1 + ty; @@ -338,11 +351,13 @@ * * @param sprite {TilingSprite} the tilingSprite to render */ -WebGLSpriteBatch.prototype.renderTilingSprite = function (tilingSprite) { +WebGLSpriteBatch.prototype.renderTilingSprite = function (tilingSprite) +{ var texture = tilingSprite.tilingTexture; // check texture.. - if (this.currentBatchSize >= this.size) { + if (this.currentBatchSize >= this.size) + { //return; this.flush(); this.currentBaseTexture = texture.baseTexture; @@ -351,7 +366,8 @@ // set the textures uvs temporarily // TODO create a separate texture so that we can tile part of a texture - if (!tilingSprite._uvs) { + if (!tilingSprite._uvs) + { tilingSprite._uvs = new TextureUvs(); } @@ -454,16 +470,19 @@ * Renders the content and empties the current batch. * */ -WebGLSpriteBatch.prototype.flush = function () { +WebGLSpriteBatch.prototype.flush = function () +{ // If the batch is length 0 then return as there is nothing to draw - if (this.currentBatchSize === 0) { + if (this.currentBatchSize === 0) + { return; } var gl = this.renderer.gl; var shader; - if (this.dirty) { + if (this.dirty) + { this.dirty = false; // bind the main texture gl.activeTexture(gl.TEXTURE0); @@ -482,10 +501,12 @@ } // upload the verts to the buffer - if (this.currentBatchSize > ( this.size * 0.5 ) ) { + if (this.currentBatchSize > ( this.size * 0.5 ) ) + { gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); } - else { + else + { var view = this.positions.subarray(0, this.currentBatchSize * this.vertByteSize); gl.bufferSubData(gl.ARRAY_BUFFER, 0, view); } @@ -502,7 +523,8 @@ var shaderSwap = false; var sprite; - for (var i = 0, j = this.currentBatchSize; i < j; i++) { + for (var i = 0, j = this.currentBatchSize; i < j; i++) + { sprite = this.sprites[i]; @@ -513,24 +535,28 @@ blendSwap = currentBlendMode !== nextBlendMode; shaderSwap = currentShader !== nextShader; // should I use uuidS??? - if (currentBaseTexture !== nextTexture || blendSwap || shaderSwap) { + if (currentBaseTexture !== nextTexture || blendSwap || shaderSwap) + { this.renderBatch(currentBaseTexture, batchSize, start); start = i; batchSize = 0; currentBaseTexture = nextTexture; - if (blendSwap) { + if (blendSwap) + { currentBlendMode = nextBlendMode; this.renderer.blendModeManager.setBlendMode( currentBlendMode ); } - if (shaderSwap) { + if (shaderSwap) + { currentShader = nextShader; shader = currentShader.shaders ? currentShader.shaders[gl.id] : currentShader; - if (!shader) { + if (!shader) + { shader = new Shader(gl, null, currentShader.fragmentSrc, currentShader.uniforms); currentShader.shaders[gl.id] = shader; } @@ -538,7 +564,8 @@ // set shader function??? this.renderer.shaderManager.setShader(shader); - if (shader.dirty) { + if (shader.dirty) + { shader.syncUniforms(); } @@ -569,17 +596,21 @@ * @param size {number} * @param startIndex {number} */ -WebGLSpriteBatch.prototype.renderBatch = function (texture, size, startIndex) { - if (size === 0) { +WebGLSpriteBatch.prototype.renderBatch = function (texture, size, startIndex) +{ + if (size === 0) + { return; } var gl = this.renderer.gl; - if (!texture._glTextures[gl.id]) { + if (!texture._glTextures[gl.id]) + { this.renderer.updateTexture(texture); } - else { + else + { // bind the current texture gl.bindTexture(gl.TEXTURE_2D, texture._glTextures[gl.id]); } @@ -594,7 +625,8 @@ /** * */ -WebGLSpriteBatch.prototype.stop = function () { +WebGLSpriteBatch.prototype.stop = function () +{ this.flush(); this.dirty = true; }; @@ -602,7 +634,8 @@ /** * */ -WebGLSpriteBatch.prototype.start = function () { +WebGLSpriteBatch.prototype.start = function () +{ this.dirty = true; }; @@ -610,7 +643,8 @@ * Destroys the SpriteBatch. * */ -WebGLSpriteBatch.prototype.destroy = function () { +WebGLSpriteBatch.prototype.destroy = function () +{ this.renderer.gl.deleteBuffer(this.vertexBuffer); this.renderer.gl.deleteBuffer(this.indexBuffer); diff --git a/src/core/textures/BaseTexture.js b/src/core/textures/BaseTexture.js index 2bf77d4..513d358 100644 --- a/src/core/textures/BaseTexture.js +++ b/src/core/textures/BaseTexture.js @@ -10,7 +10,8 @@ * @param source {Image|Canvas} the source object of the texture. * @param [scaleMode=scaleModes.DEFAULT] {number} See {@link scaleModes} for possible values */ -function BaseTexture(source, scaleMode) { +function BaseTexture(source, scaleMode) +{ this.uuid = utils.uuid(); /** @@ -123,7 +124,8 @@ this._needsUpdate = false; // if no source passed don't try to load - if (source) { + if (source) + { this.loadSource(source); } @@ -149,13 +151,16 @@ Object.defineProperties(BaseTexture.prototype, { needsUpdate: { - get: function () { + get: function () + { return this._needsUpdate; }, - set: function (val) { + set: function (val) + { this._needsUpdate = val; - if (val) { + if (val) + { this.emit('update', this); } } @@ -171,9 +176,11 @@ * * The logic state after calling `loadSource` directly or indirectly (eg. `fromImage`, `new BaseTexture`) is: * - * if (texture.hasLoaded) { + * if (texture.hasLoaded) + { * // texture ready for use - * } else if (texture.isLoading) { + * } else if (texture.isLoading) + { * // listen to 'loaded' and/or 'error' events on texture * } else { * // not loading, not going to load UNLESS the source is reloaded @@ -183,12 +190,14 @@ * @protected * @param source {Image|Canvas} the source object of the texture. */ -BaseTexture.prototype.loadSource = function (source) { +BaseTexture.prototype.loadSource = function (source) +{ var wasLoading = this.isLoading; this.hasLoaded = false; this.isLoading = false; - if (wasLoading && this.source) { + if (wasLoading && this.source) + { this.source.onload = null; this.source.onerror = null; } @@ -196,20 +205,24 @@ this.source = source; // Apply source if loaded. Otherwise setup appropriate loading monitors. - if ((this.source.complete || this.source.getContext) && this.source.width && this.source.height) { + if ((this.source.complete || this.source.getContext) && this.source.width && this.source.height) + { this._sourceLoaded(); } - else if(!source.getContext) { + else if(!source.getContext) + { // Image fail / not ready this.isLoading = true; var scope = this; - source.onload = function () { + source.onload = function () + { source.onload = null; source.onerror = null; - if(!scope.isLoading) { + if(!scope.isLoading) + { return; } @@ -219,11 +232,13 @@ scope.emit('loaded', scope); }; - source.onerror = function () { + source.onerror = function () + { source.onload = null; source.onerror = null; - if(!scope.isLoading) { + if(!scope.isLoading) + { return; } @@ -234,24 +249,29 @@ // Per http://www.w3.org/TR/html5/embedded-content-0.html#the-img-element // "The value of `complete` can thus change while a script is executing." // So complete needs to be re-checked after the callbacks have been added.. - if (source.complete) { + if (source.complete) + { this.isLoading = false; // ..and if we're complete now, no need for callbacks source.onload = null; source.onerror = null; - if (source.width && source.height) { + if (source.width && source.height) + { this._sourceLoaded(); // If any previous subscribers possible - if (wasLoading) { + if (wasLoading) + { this.emit('loaded', this); } } - else { + else + { // If any previous subscribers possible - if (wasLoading) { + if (wasLoading) + { this.emit('error', this); } } @@ -265,7 +285,8 @@ * * @private */ -BaseTexture.prototype._sourceLoaded = function () { +BaseTexture.prototype._sourceLoaded = function () +{ this.hasLoaded = true; this.width = this.source.naturalWidth || this.source.width; @@ -278,16 +299,20 @@ * Destroys this base texture * */ -BaseTexture.prototype.destroy = function () { - if (this.imageUrl) { +BaseTexture.prototype.destroy = function () +{ + if (this.imageUrl) + { delete utils.BaseTextureCache[this.imageUrl]; delete utils.TextureCache[this.imageUrl]; this.imageUrl = null; - if (!navigator.isCocoonJS) { + if (!navigator.isCocoonJS) + { this.source.src = ''; } } - else if (this.source && this.source._pixiId) { + else if (this.source && this.source._pixiId) + { delete utils.BaseTextureCache[this.source._pixiId]; } this.source = null; @@ -301,7 +326,8 @@ * memory again. * */ -BaseTexture.prototype.dispose = function () { +BaseTexture.prototype.dispose = function () +{ this.emit('dispose', this); }; @@ -311,7 +337,8 @@ * * @param newSrc {string} the path of the image */ -BaseTexture.prototype.updateSourceImage = function (newSrc) { +BaseTexture.prototype.updateSourceImage = function (newSrc) +{ this.source.src = newSrc; this.loadSource(this.source); }; @@ -326,18 +353,22 @@ * @param [scaleMode=scaleModes.DEFAULT] {number} See {@link scaleModes} for possible values * @return BaseTexture */ -BaseTexture.fromImage = function (imageUrl, crossorigin, scaleMode) { +BaseTexture.fromImage = function (imageUrl, crossorigin, scaleMode) +{ var baseTexture = utils.BaseTextureCache[imageUrl]; - if (crossorigin === undefined && imageUrl.indexOf('data:') !== 0) { + if (crossorigin === undefined && imageUrl.indexOf('data:') !== 0) + { crossorigin = true; } - if (!baseTexture) { + if (!baseTexture) + { // new Image() breaks tex loading in some versions of Chrome. // See https://code.google.com/p/chromium/issues/detail?id=238071 var image = new Image();//document.createElement('img'); - if (crossorigin) { + if (crossorigin) + { image.crossOrigin = ''; } @@ -347,7 +378,8 @@ utils.BaseTextureCache[imageUrl] = baseTexture; // if there is an @2x at the end of the url we are going to assume its a highres image - if ( imageUrl.indexOf(CONST.RETINA_PREFIX + '.') !== -1) { + if ( imageUrl.indexOf(CONST.RETINA_PREFIX + '.') !== -1) + { baseTexture.resolution = 2; } } @@ -363,14 +395,17 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return BaseTexture */ -BaseTexture.fromCanvas = function (canvas, scaleMode) { - if (!canvas._pixiId) { +BaseTexture.fromCanvas = function (canvas, scaleMode) +{ + if (!canvas._pixiId) + { canvas._pixiId = 'canvas_' + utils.uuid(); } var baseTexture = utils.BaseTextureCache[canvas._pixiId]; - if (!baseTexture) { + if (!baseTexture) + { baseTexture = new BaseTexture(canvas, scaleMode); utils.BaseTextureCache[canvas._pixiId] = baseTexture; } diff --git a/src/core/textures/RenderTexture.js b/src/core/textures/RenderTexture.js index 6dad20f..53ae796 100644 --- a/src/core/textures/RenderTexture.js +++ b/src/core/textures/RenderTexture.js @@ -46,8 +46,10 @@ * @param [scaleMode] {number} See {@link scaleModes} for possible values * @param [resolution=1] {number} The resolution of the texture being generated */ -function RenderTexture(renderer, width, height, scaleMode, resolution) { - if (!renderer) { +function RenderTexture(renderer, width, height, scaleMode, resolution) +{ + if (!renderer) + { throw new Error('Unable to create RenderTexture, you must pass a renderer into the constructor.'); } @@ -133,7 +135,8 @@ */ this.renderer = renderer; - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { var gl = this.renderer.gl; this.textureBuffer = new FilterTexture(gl, this.width * this.resolution, this.height * this.resolution, this.baseTexture.scaleMode); @@ -142,7 +145,8 @@ this.render = this.renderWebGL; this.projection = new math.Point(this.width*0.5, -this.height*0.5); } - else { + else + { this.render = this.renderCanvas; this.textureBuffer = new CanvasBuffer(this.width* this.resolution, this.height* this.resolution); this.baseTexture.source = this.textureBuffer.canvas; @@ -167,8 +171,10 @@ * @param height {number} The height to resize to. * @param updateBase {boolean} Should the baseTexture.width and height values be resized as well? */ -RenderTexture.prototype.resize = function (width, height, updateBase) { - if (width === this.width && height === this.height) { +RenderTexture.prototype.resize = function (width, height, updateBase) +{ + if (width === this.width && height === this.height) + { return; } @@ -177,17 +183,20 @@ this.width = this.frame.width = this.crop.width = width; this.height = this.frame.height = this.crop.height = height; - if (updateBase) { + if (updateBase) + { this.baseTexture.width = this.width; this.baseTexture.height = this.height; } - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { this.projection.x = this.width / 2; this.projection.y = -this.height / 2; } - if (!this.valid) { + if (!this.valid) + { return; } @@ -198,12 +207,15 @@ * Clears the RenderTexture. * */ -RenderTexture.prototype.clear = function () { - if (!this.valid) { +RenderTexture.prototype.clear = function () +{ + if (!this.valid) + { return; } - if (this.renderer.type === CONST.WEBGL_RENDERER) { + if (this.renderer.type === CONST.WEBGL_RENDERER) + { this.renderer.gl.bindFramebuffer(this.renderer.gl.FRAMEBUFFER, this.textureBuffer.frameBuffer); } @@ -220,19 +232,23 @@ * @param [restoreWorldTransform=true] {boolean} If true the displayObject's worldTransform/worldAlpha and all children * transformations will be restored. Not restoring this information will be a little faster. */ -RenderTexture.prototype.renderWebGL = function (displayObject, matrix, clear, restoreWorldTransform) { - if (!this.valid) { +RenderTexture.prototype.renderWebGL = function (displayObject, matrix, clear, restoreWorldTransform) +{ + if (!this.valid) + { return; } - if (typeof restoreWorldTransform === 'undefined') { + if (typeof restoreWorldTransform === 'undefined') + { restoreWorldTransform = true; } var tempAlpha, tempTransform; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { tempAlpha = displayObject.worldAlpha; tempTransform = displayObject.worldTransform.toArray(); } @@ -245,7 +261,8 @@ wt.identity(); wt.translate(0, this.projection.y * 2); - if (matrix) { + if (matrix) + { wt.append(matrix); } @@ -258,7 +275,8 @@ var children = displayObject.children; var i, j; - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } @@ -269,7 +287,8 @@ gl.bindFramebuffer(gl.FRAMEBUFFER, this.textureBuffer.frameBuffer ); - if (clear) { + if (clear) + { this.textureBuffer.clear(); } @@ -279,11 +298,13 @@ this.renderer.spriteBatch.dirty = true; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { displayObject.worldAlpha = tempAlpha; displayObject.worldTransform.fromArray(tempTransform); - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } } @@ -300,26 +321,31 @@ * @param [restoreWorldTransform=true] {boolean} If true the displayObject's worldTransform/worldAlpha and all children * transformations will be restored. Not restoring this information will be a little faster. */ -RenderTexture.prototype.renderCanvas = function (displayObject, matrix, clear, restoreWorldTransform) { - if (!this.valid) { +RenderTexture.prototype.renderCanvas = function (displayObject, matrix, clear, restoreWorldTransform) +{ + if (!this.valid) + { return; } - if (typeof restoreWorldTransform === 'undefined') { + if (typeof restoreWorldTransform === 'undefined') + { restoreWorldTransform = true; } var tempAlpha, tempTransform; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { tempAlpha = displayObject.worldAlpha; tempTransform = displayObject.worldTransform.toArray(); } var wt = displayObject.worldTransform; wt.identity(); - if (matrix) { + if (matrix) + { wt.append(matrix); } @@ -330,11 +356,13 @@ var children = displayObject.children; var i, j; - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } - if (clear) { + if (clear) + { this.textureBuffer.clear(); } @@ -348,11 +376,13 @@ this.renderer.resolution = realResolution; - if (restoreWorldTransform) { + if (restoreWorldTransform) + { displayObject.worldAlpha = tempAlpha; displayObject.worldTransform.fromArray(tempTransform); - for (i = 0, j = children.length; i < j; ++i) { + for (i = 0, j = children.length; i < j; ++i) + { children[i].updateTransform(); } } @@ -363,7 +393,8 @@ * * @return {Image} */ -RenderTexture.prototype.getImage = function () { +RenderTexture.prototype.getImage = function () +{ var image = new Image(); image.src = this.getBase64(); return image; @@ -374,7 +405,8 @@ * * @return {string} A base64 encoded string of the texture. */ -RenderTexture.prototype.getBase64 = function () { +RenderTexture.prototype.getBase64 = function () +{ return this.getCanvas().toDataURL(); }; @@ -383,8 +415,10 @@ * * @return {HTMLCanvasElement} A Canvas element with the texture rendered on. */ -RenderTexture.prototype.getCanvas = function () { - if (this.renderer.type === CONST.WEBGL_RENDERER) { +RenderTexture.prototype.getCanvas = function () +{ + if (this.renderer.type === CONST.WEBGL_RENDERER) + { var gl = this.renderer.gl; var width = this.textureBuffer.width; var height = this.textureBuffer.height; @@ -403,7 +437,8 @@ return tempCanvas.canvas; } - else { + else + { return this.textureBuffer.canvas; } }; diff --git a/src/core/textures/Texture.js b/src/core/textures/Texture.js index 3c65909..e97f0aa 100644 --- a/src/core/textures/Texture.js +++ b/src/core/textures/Texture.js @@ -17,7 +17,8 @@ * @param [crop] {Rectangle} The area of original texture * @param [trim] {Rectangle} Trimmed texture rectangle */ -function Texture(baseTexture, frame, crop, trim) { +function Texture(baseTexture, frame, crop, trim) +{ /** * Does this Texture have any frame data assigned to it? * @@ -25,12 +26,14 @@ */ this.noFrame = false; - if (!frame) { + if (!frame) + { this.noFrame = true; frame = new math.Rectangle(0, 0, 1, 1); } - if (baseTexture instanceof Texture) { + if (baseTexture instanceof Texture) + { baseTexture = baseTexture.baseTexture; } @@ -100,13 +103,16 @@ */ this.crop = crop || new math.Rectangle(0, 0, 1, 1); - if (baseTexture.hasLoaded) { - if (this.noFrame) { + if (baseTexture.hasLoaded) + { + if (this.noFrame) + { frame = new math.Rectangle(0, 0, baseTexture.width, baseTexture.height); } this.frame = frame; } - else { + else + { baseTexture.addEventListener('loaded', this.onBaseTextureLoaded.bind(this)); } } @@ -118,19 +124,23 @@ Object.defineProperties(Texture.prototype, { needsUpdate: { - get: function () { + get: function () + { return this.baseTexture.needsUpdate; }, - set: function (val) { + set: function (val) + { this.baseTexture.needsUpdate = val; } }, frame: { - get: function () { + get: function () + { return this._frame; }, - set: function (frame) { + set: function (frame) + { this._frame = frame; this.noFrame = false; @@ -143,20 +153,23 @@ 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 (!this.trim && (frame.x + frame.width > this.baseTexture.width || frame.y + frame.height > this.baseTexture.height)) + { throw new Error('Texture Error: frame does not fit inside the base Texture dimensions ' + this); } this.valid = frame && frame.width && frame.height && this.baseTexture.source && this.baseTexture.hasLoaded; - if (this.trim) { + 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) { + if (this.valid) + { this._updateUvs(); } } @@ -168,11 +181,13 @@ * * @private */ -Texture.prototype.onBaseTextureLoaded = function () { +Texture.prototype.onBaseTextureLoaded = function () +{ var baseTexture = this.baseTexture; baseTexture.removeEventListener('loaded', this.onLoaded); - if (this.noFrame) { + if (this.noFrame) + { this.frame = new math.Rectangle(0, 0, baseTexture.width, baseTexture.height); } @@ -184,8 +199,10 @@ * * @param destroyBase {boolean} Whether to destroy the base texture as well */ -Texture.prototype.destroy = function (destroyBase) { - if (destroyBase) { +Texture.prototype.destroy = function (destroyBase) +{ + if (destroyBase) + { this.baseTexture.destroy(); } @@ -197,8 +214,10 @@ * * @private */ -Texture.prototype._updateUvs = function () { - if (!this._uvs) { +Texture.prototype._updateUvs = function () +{ + if (!this._uvs) + { this._uvs = new TextureUvs(); } @@ -229,10 +248,12 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return Texture */ -Texture.fromImage = function (imageUrl, crossorigin, scaleMode) { +Texture.fromImage = function (imageUrl, crossorigin, scaleMode) +{ var texture = utils.TextureCache[imageUrl]; - if (!texture) { + if (!texture) + { texture = new Texture(BaseTexture.fromImage(imageUrl, crossorigin, scaleMode)); utils.TextureCache[imageUrl] = texture; } @@ -248,9 +269,11 @@ * @param frameId {string} The frame id of the texture * @return Texture */ -Texture.fromFrame = function (frameId) { +Texture.fromFrame = function (frameId) +{ var texture = utils.TextureCache[frameId]; - if (!texture) { + if (!texture) + { throw new Error('The frameId "' + frameId + '" does not exist in the texture cache '); } return texture; @@ -264,7 +287,8 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return {Texture} */ -Texture.fromCanvas = function (canvas, scaleMode) { +Texture.fromCanvas = function (canvas, scaleMode) +{ return new Texture(BaseTexture.fromCanvas(canvas, scaleMode)); }; @@ -276,7 +300,8 @@ * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return {Texture} A Texture */ -Texture.fromVideo = function (video, scaleMode) { +Texture.fromVideo = function (video, scaleMode) +{ return new Texture(VideoBaseTexture.baseTextureFromVideo(video, scaleMode)); }; @@ -287,7 +312,8 @@ * @param texture {Texture} The Texture to add to the cache. * @param id {string} The id that the texture will be stored against. */ -Texture.addTextureToCache = function (texture, id) { +Texture.addTextureToCache = function (texture, id) +{ utils.TextureCache[id] = texture; }; @@ -298,7 +324,8 @@ * @param id {string} The id of the texture to be removed * @return {Texture} The texture that was removed */ -Texture.removeTextureFromCache = function (id) { +Texture.removeTextureFromCache = function (id) +{ var texture = utils.TextureCache[id]; delete utils.TextureCache[id]; diff --git a/src/core/textures/TextureUvs.js b/src/core/textures/TextureUvs.js index b9bbb58..5424d52 100644 --- a/src/core/textures/TextureUvs.js +++ b/src/core/textures/TextureUvs.js @@ -1,4 +1,5 @@ -function TextureUvs() { +function TextureUvs() +{ this.x0 = 0; this.y0 = 0; diff --git a/src/core/textures/VideoBaseTexture.js b/src/core/textures/VideoBaseTexture.js index e3e0c5a..1a826a9 100644 --- a/src/core/textures/VideoBaseTexture.js +++ b/src/core/textures/VideoBaseTexture.js @@ -12,15 +12,18 @@ * @param source {HTMLVideoElement} * @param [scaleMode] {number} See {@link scaleModes} for possible values */ -function VideoBaseTexture(source, scaleMode) { - if (!source){ +function VideoBaseTexture(source, scaleMode) +{ + if (!source) + { throw new Error('No video source element specified.'); } // hook in here to check if video is already available. // BaseTexture looks for a source.complete boolean, plus width & height. - if ((source.readyState === source.HAVE_ENOUGH_DATA || source.readyState === source.HAVE_FUTURE_DATA) && source.width && source.height) { + if ((source.readyState === source.HAVE_ENOUGH_DATA || source.readyState === source.HAVE_FUTURE_DATA) && source.width && source.height) + { source.complete = true; } @@ -31,7 +34,8 @@ this._boundOnUpdate = this._onUpdate.bind(this); this._boundOnCanPlay = this._onCanPlay.bind(this); - if (!source.complete) { + if (!source.complete) + { source.addEventListener('canplay', this._boundOnCanPlay); source.addEventListener('canplaythrough', this._boundOnCanPlay); @@ -47,28 +51,35 @@ VideoBaseTexture.prototype.constructor = VideoBaseTexture; module.exports = VideoBaseTexture; -VideoBaseTexture.prototype._onUpdate = function () { - if (this.autoUpdate) { +VideoBaseTexture.prototype._onUpdate = function () +{ + if (this.autoUpdate) + { window.requestAnimationFrame(this._boundOnUpdate); this.needsUpdate = true; } }; -VideoBaseTexture.prototype._onPlayStart = function () { - if (!this.autoUpdate) { +VideoBaseTexture.prototype._onPlayStart = function () +{ + if (!this.autoUpdate) + { window.requestAnimationFrame(this._boundOnUpdate); this.autoUpdate = true; } }; -VideoBaseTexture.prototype._onPlayStop = function () { +VideoBaseTexture.prototype._onPlayStop = function () +{ this.autoUpdate = false; }; -VideoBaseTexture.prototype._onCanPlay = function () { +VideoBaseTexture.prototype._onCanPlay = function () +{ this.hasLoaded = true; - if (this.source) { + if (this.source) + { this.source.removeEventListener('canplay', this._boundOnCanPlay); this.source.removeEventListener('canplaythrough', this._boundOnCanPlay); @@ -78,15 +89,18 @@ this.source.play(); // prevent multiple loaded dispatches.. - if(!this.__loaded){ + if(!this.__loaded) + { this.__loaded = true; this.emit('loaded', this); } } }; -VideoBaseTexture.prototype.destroy = function () { - if (this.source && this.source._pixiId) { +VideoBaseTexture.prototype.destroy = function () +{ + if (this.source && this.source._pixiId) + { utils.BaseTextureCache[ this.source._pixiId ] = null; delete utils.BaseTextureCache[ this.source._pixiId ]; @@ -105,14 +119,17 @@ * @param scaleMode {number} See {@link scaleModes} for possible values * @return {VideoBaseTexture} */ -VideoBaseTexture.fromVideo = function (video, scaleMode) { - if (!video._pixiId) { +VideoBaseTexture.fromVideo = function (video, scaleMode) +{ + if (!video._pixiId) + { video._pixiId = 'video_' + utils.uuid(); } var baseTexture = utils.BaseTextureCache[video._pixiId]; - if (!baseTexture) { + if (!baseTexture) + { baseTexture = new VideoBaseTexture(video, scaleMode); utils.BaseTextureCache[ video._pixiId ] = baseTexture; } @@ -147,17 +164,21 @@ * @param scaleMode {number} See {@link scaleModes} for possible values * @return {VideoBaseTexture} */ -VideoBaseTexture.fromUrl = function (videoSrc, scaleMode) { +VideoBaseTexture.fromUrl = function (videoSrc, scaleMode) +{ var video = document.createElement('video'); // array of objects or strings - if (Array.isArray(videoSrc)) { - for (var i = 0; i < videoSrc.length; ++i) { + if (Array.isArray(videoSrc)) + { + for (var i = 0; i < videoSrc.length; ++i) + { video.appendChild(createSource(videoSrc.src || videoSrc, videoSrc.mime)); } } // single object or string - else { + else + { video.appendChild(createSource(videoSrc.src || videoSrc, videoSrc.mime)); } @@ -169,8 +190,10 @@ VideoBaseTexture.fromUrls = VideoBaseTexture.fromUrl; -function createSource(path, type) { - if (!type) { +function createSource(path, type) +{ + if (!type) + { type = 'video/' + path.substr(path.lastIndexOf('.') + 1); } diff --git a/src/core/utils/EventData.js b/src/core/utils/EventData.js index 5d55a22..8cdf701 100644 --- a/src/core/utils/EventData.js +++ b/src/core/utils/EventData.js @@ -7,7 +7,8 @@ * @param name {string} The string name of the event that was triggered * @param data {object} Arbitrary event data to pass along */ -function EventData(target, name, data) { +function EventData(target, name, data) +{ // for duck typing in the ".on()" function this.__isEventObject = true; @@ -71,7 +72,8 @@ * Stops the propagation of events up the scene graph (prevents bubbling). * */ -EventData.prototype.stopPropagation = function stopPropagation() { +EventData.prototype.stopPropagation = function stopPropagation() +{ this.stopped = true; }; @@ -79,6 +81,7 @@ * Stops the propagation of events to sibling listeners (no longer calls any listeners). * */ -EventData.prototype.stopImmediatePropagation = function stopImmediatePropagation() { +EventData.prototype.stopImmediatePropagation = function stopImmediatePropagation() +{ this.stoppedImmediate = true; }; diff --git a/src/core/utils/EventTarget.js b/src/core/utils/EventTarget.js index 7ae8820..671a151 100644 --- a/src/core/utils/EventTarget.js +++ b/src/core/utils/EventTarget.js @@ -13,14 +13,16 @@ * var em = new MyEmitter(); * em.emit('eventName', 'some data', 'some more data', {}, null, ...); */ -function eventTarget(obj) { +function eventTarget(obj) +{ /** * Return a list of assigned event listeners. * * @param eventName {string} The events that should be listed. * @return {Array} An array of listener functions */ - obj.listeners = function listeners(eventName) { + obj.listeners = function listeners(eventName) + { this._listeners = this._listeners || {}; return this._listeners[eventName] ? this._listeners[eventName].slice() : []; @@ -33,22 +35,26 @@ * @param eventName {string} The name of the event. * @return {boolean} Indication if we've emitted an event. */ - obj.emit = obj.dispatchEvent = function emit(eventName, data) { + obj.emit = obj.dispatchEvent = function emit(eventName, data) + { this._listeners = this._listeners || {}; // fast return when there are no listeners - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return; } //backwards compat with old method ".emit({ type: 'something' })" - if (typeof eventName === 'object') { + if (typeof eventName === 'object') + { data = eventName; eventName = eventName.type; } //ensure we are using a real pixi event - if (!data || data.__isEventObject !== true) { + if (!data || data.__isEventObject !== true) + { data = new EventData(this, eventName, data); } @@ -58,23 +64,27 @@ fn = listeners[0], i; - for (i = 0; i < length; fn = listeners[++i]) { + for (i = 0; i < length; fn = listeners[++i]) + { //call the event listener fn.call(this, data); //if "stopImmediatePropagation" is called, stop calling sibling events - if (data.stoppedImmediate) { + if (data.stoppedImmediate) + { return this; } } //if "stopPropagation" is called then don't bubble the event - if (data.stopped) { + if (data.stopped) + { return this; } //bubble this event up the scene graph - if (this.parent && this.parent.emit) { + if (this.parent && this.parent.emit) + { this.parent.emit.call(this.parent, eventName, data); } @@ -88,7 +98,8 @@ * @param eventName {string} Name of the event. * @param callback {Functon} fn Callback function. */ - obj.on = obj.addEventListener = function on(eventName, fn) { + obj.on = obj.addEventListener = function on(eventName, fn) + { this._listeners = this._listeners || {}; (this._listeners[eventName] = this._listeners[eventName] || []) @@ -103,11 +114,13 @@ * @param eventName {string} Name of the event. * @param callback {Function} Callback function. */ - obj.once = function once(eventName, fn) { + obj.once = function once(eventName, fn) + { this._listeners = this._listeners || {}; var self = this; - function onceHandlerWrapper() { + function onceHandlerWrapper() + { fn.apply(self.off(eventName, onceHandlerWrapper), arguments); } onceHandlerWrapper._originalHandler = fn; @@ -122,23 +135,28 @@ * @param eventName {string} The event we want to remove. * @param callback {Function} The listener that we need to find. */ - obj.off = obj.removeEventListener = function off(eventName, fn) { + obj.off = obj.removeEventListener = function off(eventName, fn) + { this._listeners = this._listeners || {}; - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return this; } var list = this._listeners[eventName], i = fn ? list.length : 0; - while(i-- > 0) { - if (list[i] === fn || list[i]._originalHandler === fn) { + while(i-- > 0) + { + if (list[i] === fn || list[i]._originalHandler === fn) + { list.splice(i, 1); } } - if (list.length === 0) { + if (list.length === 0) + { delete this._listeners[eventName]; } @@ -150,10 +168,12 @@ * * @param eventName {string} The event you want to remove all listeners for. */ - obj.removeAllListeners = function removeAllListeners(eventName) { + obj.removeAllListeners = function removeAllListeners(eventName) + { this._listeners = this._listeners || {}; - if (!this._listeners[eventName]) { + if (!this._listeners[eventName]) + { return this; } @@ -169,7 +189,8 @@ * * @param object {object} The obj to mix into */ - mixin: function mixin(obj) { + mixin: function mixin(obj) + { eventTarget(obj); } }; diff --git a/src/core/utils/PolyK.js b/src/core/utils/PolyK.js index 7325141..5e20c2b 100644 --- a/src/core/utils/PolyK.js +++ b/src/core/utils/PolyK.js @@ -47,7 +47,8 @@ * Triangulates shapes for webGL graphic fills. * */ -PolyK.Triangulate = function (p) { +PolyK.Triangulate = function (p) +{ var sign = true; var n = p.length >> 1; @@ -59,7 +60,8 @@ i = 0; var al = n; - while(al > 3) { + while(al > 3) + { var i0 = avl[(i+0)%al]; var i1 = avl[(i+1)%al]; var i2 = avl[(i+2)%al]; @@ -69,29 +71,35 @@ var cx = p[2*i2], cy = p[2*i2+1]; var earFound = false; - if (PolyK._convex(ax, ay, bx, by, cx, cy, sign)) { + if (PolyK._convex(ax, ay, bx, by, cx, cy, sign)) + { earFound = true; - for (var j = 0; j < al; j++) { + for (var j = 0; j < al; j++) + { var vi = avl[j]; if (vi === i0 || vi === i1 || vi === i2) continue; - if (PolyK._PointInTriangle(p[2*vi], p[2*vi+1], ax, ay, bx, by, cx, cy)) { + if (PolyK._PointInTriangle(p[2*vi], p[2*vi+1], ax, ay, bx, by, cx, cy)) + { earFound = false; break; } } } - if (earFound) { + if (earFound) + { tgs.push(i0, i1, i2); avl.splice((i+1)%al, 1); al--; i = 0; } - else if (i++ > 3*al) { + else if (i++ > 3*al) + { // need to flip flip reverse it! // reset! - if (sign) { + if (sign) + { tgs = []; avl = []; for (i = 0; i < n; i++) avl.push(i); @@ -101,7 +109,8 @@ sign = false; } - else { + else + { // window.console.log("PIXI Warning: shape too complex to fill"); return null; } @@ -126,7 +135,8 @@ * @private * @return {boolean} */ -PolyK._PointInTriangle = function (px, py, ax, ay, bx, by, cx, cy) { +PolyK._PointInTriangle = function (px, py, ax, ay, bx, by, cx, cy) +{ var v0x = cx-ax; var v0y = cy-ay; var v1x = bx-ax; @@ -154,6 +164,7 @@ * @private * @return {boolean} */ -PolyK._convex = function (ax, ay, bx, by, cx, cy, sign) { +PolyK._convex = function (ax, ay, bx, by, cx, cy, sign) +{ return ((ay-by)*(cx-bx) + (bx-ax)*(cy-by) >= 0) === sign; }; diff --git a/src/core/utils/index.js b/src/core/utils/index.js index ade9831..bfae7ae 100644 --- a/src/core/utils/index.js +++ b/src/core/utils/index.js @@ -16,7 +16,8 @@ * * @return {number} The next uuid to use. */ - uuid: function () { + uuid: function () + { return ++utils._uid; }, @@ -26,7 +27,8 @@ * @param hex {number} * @return {number[]} An array representing the [R, G, B] of the color. */ - hex2rgb: function (hex, out) { + hex2rgb: function (hex, out) + { out = out || []; out[0] = (hex >> 16 & 0xFF) / 255; @@ -42,7 +44,8 @@ * @param hex {number} * @return {string} The string color. */ - hex2string: function (hex) { + hex2string: function (hex) + { hex = hex.toString(16); hex = '000000'.substr(0, 6 - hex.length) + hex; @@ -55,7 +58,8 @@ * @param rgb {number[]} * @return {number} The color number */ - rgb2hex: function (rgb) { + rgb2hex: function (rgb) + { return ((rgb[0]*255 << 16) + (rgb[1]*255 << 8) + rgb[2]*255); }, @@ -64,8 +68,10 @@ * * @return {boolean} whether they are supported */ - canUseNewCanvasBlendModes: function () { - if (typeof document === 'undefined') { + canUseNewCanvasBlendModes: function () + { + if (typeof document === 'undefined') + { return false; } @@ -93,15 +99,19 @@ * @param number {number} * @return {number} the closest number that is a power of two */ - getNextPowerOfTwo: function (number) { + getNextPowerOfTwo: function (number) + { // see: http://en.wikipedia.org/wiki/Power_of_two#Fast_algorithm_to_check_if_a_positive_number_is_a_power_of_two - if (number > 0 && (number & (number - 1)) === 0) { + if (number > 0 && (number & (number - 1)) === 0) + { return number; } - else { + else + { var result = 1; - while (result < number) { + while (result < number) + { result <<= 1; } @@ -116,7 +126,8 @@ * @param height {number} * @return {boolean} */ - isPowerOfTwo: function (width, height) { + isPowerOfTwo: function (width, height) + { return (width > 0 && (width & (width - 1)) === 0 && height > 0 && (height & (height - 1)) === 0); }, @@ -130,12 +141,15 @@ * @constant * @static */ - sayHello: function (type) { - if (utils._saidHello) { + sayHello: function (type) + { + if (utils._saidHello) + { return; } - if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) { + if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) + { var args = [ '%c %c %c Pixi.js ' + CONST.VERSION + ' - ' + type + ' %c ' + ' %c ' + ' http://www.pixijs.com/ %c %c ♥%c♥%c♥ ', 'background: #ff66a5', @@ -151,7 +165,8 @@ console.log.apply(console, args); //jshint ignore:line } - else if (window.console) { + else if (window.console) + { console.log('Pixi.js ' + CONST.VERSION + ' - ' + type + ' - http://www.pixijs.com/'); //jshint ignore:line } @@ -166,15 +181,19 @@ * @class * @namespace PIXI */ - AjaxRequest: function () { + AjaxRequest: function () + { var activexmodes = ['Msxml2.XMLHTTP.6.0', 'Msxml2.XMLHTTP.3.0', 'Microsoft.XMLHTTP']; //activeX versions to check for in IE - if (window.ActiveXObject) { //Test for support for ActiveXObject in IE first (as XMLHttpRequest in IE7 is broken) - for (var i=0; i= this.textures.length) { + else if (round >= this.textures.length) + { this.gotoAndStop(this.textures.length - 1); - if (this.onComplete) { + if (this.onComplete) + { this.onComplete(); } } @@ -167,10 +182,12 @@ * @static * @param frames {string[]} the array of frames ids the movieclip will use as its texture frames */ -MovieClip.fromFrames = function (frames) { +MovieClip.fromFrames = function (frames) +{ var textures = []; - for (var i = 0; i < frames.length; ++i) { + for (var i = 0; i < frames.length; ++i) + { textures.push(new core.Texture.fromFrame(frames[i])); } @@ -183,10 +200,12 @@ * @static * @param images {string[]} the array of image urls the movieclip will use as its texture frames */ -MovieClip.fromImages = function (images) { +MovieClip.fromImages = function (images) +{ var textures = []; - for (var i = 0; i < images.length; ++i) { + for (var i = 0; i < images.length; ++i) + { textures.push(new core.Texture.fromImage(images[i])); } diff --git a/src/extras/Rope.js b/src/extras/Rope.js index c157ec4..9c87bc0 100644 --- a/src/extras/Rope.js +++ b/src/extras/Rope.js @@ -9,7 +9,8 @@ * @param {Array} points - An array of {Point}. * */ -function Rope(texture, points) { +function Rope(texture, points) +{ Strip.call(this, texture); this.points = points; @@ -31,10 +32,12 @@ * Refreshes * */ -Rope.prototype.refresh = function () { +Rope.prototype.refresh = function () +{ var points = this.points; - if (points.length < 1) { + if (points.length < 1) + { return; } @@ -59,20 +62,23 @@ var total = points.length, point, index, amount; - for (var i = 1; i < total; i++) { + for (var i = 1; i < total; i++) + { point = points[i]; index = i * 4; // time to do some smart drawing! amount = i / (total-1); - if (i%2) { + if (i%2) + { uvs[index] = amount; uvs[index+1] = 0; uvs[index+2] = amount; uvs[index+3] = 1; } - else { + else + { uvs[index] = amount; uvs[index+1] = 0; @@ -95,10 +101,12 @@ * * @private */ -Rope.prototype.updateTransform = function () { +Rope.prototype.updateTransform = function () +{ var points = this.points; - if (points.length < 1) { + if (points.length < 1) + { return; } @@ -113,14 +121,17 @@ var total = points.length, point, index, ratio, perpLength, num; - for (var i = 0; i < total; i++) { + for (var i = 0; i < total; i++) + { point = points[i]; index = i * 4; - if (i < points.length-1) { + if (i < points.length-1) + { nextPoint = points[i+1]; } - else { + else + { nextPoint = point; } @@ -129,7 +140,8 @@ ratio = (1 - (i / (total-1))) * 10; - if (ratio > 1) { + if (ratio > 1) + { ratio = 1; } @@ -157,7 +169,8 @@ * * @param texture {Texture} the texture that will be used */ -Rope.prototype.setTexture = function (texture) { +Rope.prototype.setTexture = function (texture) +{ // stop current texture this.texture = texture; //this.updateFrame = true; diff --git a/src/extras/Strip.js b/src/extras/Strip.js index c5e378f..57691b5 100644 --- a/src/extras/Strip.js +++ b/src/extras/Strip.js @@ -10,7 +10,8 @@ * @param height {number} the height * */ -function Strip(texture) { +function Strip(texture) +{ core.DisplayObjectContainer.call(this); /** @@ -70,9 +71,11 @@ * * @param renderer {WebGLRenderer} */ -Strip.prototype.renderWebGL = function (renderer) { +Strip.prototype.renderWebGL = function (renderer) +{ // if the sprite is not visible or the alpha is 0 then no need to render this element - if (!this.visible || this.alpha <= 0) { + if (!this.visible || this.alpha <= 0) + { return; } @@ -81,7 +84,8 @@ renderer.spriteBatch.stop(); // init! init! - if (!this._vertexBuffer) { + if (!this._vertexBuffer) + { this._initWebGL(renderer); } @@ -96,7 +100,8 @@ //TODO check culling }; -Strip.prototype._initWebGL = function (renderer) { +Strip.prototype._initWebGL = function (renderer) +{ // build the strip! var gl = renderer.gl; @@ -118,7 +123,8 @@ gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this.indices, gl.STATIC_DRAW); }; -Strip.prototype._renderStrip = function (renderer) { +Strip.prototype._renderStrip = function (renderer) +{ var gl = renderer.gl; var projection = renderer.projection, offset = renderer.offset, @@ -137,7 +143,8 @@ gl.uniform2f(shader.offsetVector, -offset.x, -offset.y); gl.uniform1f(shader.alpha, this.worldAlpha); - if (!this.dirty) { + if (!this.dirty) + { gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexBuffer); gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); @@ -150,10 +157,12 @@ gl.activeTexture(gl.TEXTURE0); // check if a texture is dirty.. - if (this.texture.baseTexture._dirty[gl.id]) { + if (this.texture.baseTexture._dirty[gl.id]) + { renderer.updateTexture(this.texture.baseTexture); } - else { + else + { // bind the current texture gl.bindTexture(gl.TEXTURE_2D, this.texture.baseTexture._glTextures[gl.id]); } @@ -163,7 +172,8 @@ } - else { + else + { this.dirty = false; gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexBuffer); @@ -178,10 +188,12 @@ gl.activeTexture(gl.TEXTURE0); // check if a texture is dirty.. - if (this.texture.baseTexture._dirty[gl.id]) { + if (this.texture.baseTexture._dirty[gl.id]) + { renderer.updateTexture(this.texture.baseTexture); } - else { + else + { gl.bindTexture(gl.TEXTURE_2D, this.texture.baseTexture._glTextures[gl.id]); } @@ -203,27 +215,33 @@ * * @param renderer {CanvasRenderer} */ -Strip.prototype.renderCanvas = function (renderer) { +Strip.prototype.renderCanvas = function (renderer) +{ var context = renderer.context; var transform = this.worldTransform; - if (renderer.roundPixels) { + if (renderer.roundPixels) + { context.setTransform(transform.a, transform.b, transform.c, transform.d, transform.tx | 0, transform.ty | 0); } - else { + else + { context.setTransform(transform.a, transform.b, transform.c, transform.d, transform.tx, transform.ty); } - if (this.drawMode === Strip.DrawModes.TRIANGLE_STRIP) { + if (this.drawMode === Strip.DrawModes.TRIANGLE_STRIP) + { this._renderCanvasTriangleStrip(context); } - else { + else + { this._renderCanvasTriangles(context); } }; -Strip.prototype._renderCanvasTriangleStrip = function (context) { +Strip.prototype._renderCanvasTriangleStrip = function (context) +{ // draw triangles!! var vertices = this.vertices; var uvs = this.uvs; @@ -231,14 +249,16 @@ var length = vertices.length / 2; // this.count++; - for (var i = 0; i < length - 2; i++) { + for (var i = 0; i < length - 2; i++) + { // draw some triangles! var index = i * 2; this._renderCanvasDrawTriangle(context, vertices, uvs, index, (index + 2), (index + 4)); } }; -Strip.prototype._renderCanvasTriangles = function (context) { +Strip.prototype._renderCanvasTriangles = function (context) +{ // draw triangles!! var vertices = this.vertices; var uvs = this.uvs; @@ -247,14 +267,16 @@ var length = indices.length; // this.count++; - for (var i = 0; i < length; i += 3) { + for (var i = 0; i < length; i += 3) + { // draw some triangles! var index0 = indices[i] * 2, index1 = indices[i + 1] * 2, index2 = indices[i + 2] * 2; this._renderCanvasDrawTriangle(context, vertices, uvs, index0, index1, index2); } }; -Strip.prototype._renderCanvasDrawTriangle = function (context, vertices, uvs, index0, index1, index2) { +Strip.prototype._renderCanvasDrawTriangle = function (context, vertices, uvs, index0, index1, index2) +{ var textureSource = this.texture.baseTexture.source; var textureWidth = this.texture.width; var textureHeight = this.texture.height; @@ -265,7 +287,8 @@ var u0 = uvs[index0] * textureWidth, u1 = uvs[index1] * textureWidth, u2 = uvs[index2] * textureWidth; var v0 = uvs[index0 + 1] * textureHeight, v1 = uvs[index1 + 1] * textureHeight, v2 = uvs[index2 + 1] * textureHeight; - if (this.canvasPadding > 0) { + if (this.canvasPadding > 0) + { var paddingX = this.canvasPadding / this.worldTransform.a; var paddingY = this.canvasPadding / this.worldTransform.d; var centerX = (x0 + x1 + x2) / 3; @@ -332,7 +355,8 @@ * @param strip {Strip} The Strip to render * @private */ -Strip.prototype.renderStripFlat = function (strip) { +Strip.prototype.renderStripFlat = function (strip) +{ var context = this.context; var vertices = strip.vertices; @@ -340,7 +364,8 @@ // this.count++; context.beginPath(); - for (var i=1; i < length-2; i++) { + for (var i=1; i < length-2; i++) + { // draw some triangles! var index = i*2; @@ -358,7 +383,8 @@ }; /* -Strip.prototype.setTexture = function (texture) { +Strip.prototype.setTexture = function (texture) +{ //TODO SET THE TEXTURES //TODO VISIBILITY @@ -377,7 +403,8 @@ * @private */ -Strip.prototype.onTextureUpdate = function () { +Strip.prototype.onTextureUpdate = function () +{ this.updateFrame = true; }; @@ -387,7 +414,8 @@ * @param matrix {Matrix} the transformation matrix of the sprite * @return {Rectangle} the framing rectangle */ -Strip.prototype.getBounds = function (matrix) { +Strip.prototype.getBounds = function (matrix) +{ var worldTransform = matrix || this.worldTransform; var a = worldTransform.a; @@ -404,7 +432,8 @@ var minY = Infinity; var vertices = this.vertices; - for (var i = 0, n = vertices.length; i < n; i += 2) { + for (var i = 0, n = vertices.length; i < n; i += 2) + { var rawX = vertices[i], rawY = vertices[i + 1]; var x = (a * rawX) + (c * rawY) + tx; var y = (d * rawY) + (b * rawX) + ty; @@ -416,7 +445,8 @@ maxY = y > maxY ? y : maxY; } - if (minX === -Infinity || maxY === Infinity) { + if (minX === -Infinity || maxY === Infinity) + { return core.math.Rectangle.EMPTY; } diff --git a/src/extras/TilingSprite.js b/src/extras/TilingSprite.js index 3ac22df..31da393 100644 --- a/src/extras/TilingSprite.js +++ b/src/extras/TilingSprite.js @@ -10,7 +10,8 @@ * @param width {number} the width of the tiling sprite * @param height {number} the height of the tiling sprite */ -function TilingSprite(texture, width, height) { +function TilingSprite(texture, width, height) +{ core.Sprite.call( this, texture); /** @@ -86,10 +87,12 @@ * @memberof TilingSprite# */ width: { - get: function () { + get: function () + { return this._width; }, - set: function (value) { + set: function (value) + { this._width = value; } }, @@ -101,20 +104,25 @@ * @memberof TilingSprite# */ height: { - get: function () { + get: function () + { return this._height; }, - set: function (value) { + set: function (value) + { this._height = value; } }, texture: { - get: function () { + get: function () + { return this._texture; }, - set: function (value) { - if (this._texture === value) { + set: function (value) + { + if (this._texture === value) + { return; } @@ -130,51 +138,61 @@ * * @param renderer {WebGLRenderer} */ -TilingSprite.prototype.renderWebGL = function (renderer) { - if (!this.visible || this.alpha <= 0) { +TilingSprite.prototype.renderWebGL = function (renderer) +{ + if (!this.visible || this.alpha <= 0) + { return; } var i, j; - if (this._mask) { + if (this._mask) + { renderer.spriteBatch.stop(); renderer.maskManager.pushMask(this.mask, renderer); renderer.spriteBatch.start(); } - if (this._filters) { + if (this._filters) + { renderer.spriteBatch.flush(); renderer.filterManager.pushFilter(this._filterBlock); } - if (!this.tilingTexture || this.refreshTexture) { + if (!this.tilingTexture || this.refreshTexture) + { this.generateTilingTexture(true); - if (this.tilingTexture && this.tilingTexture.needsUpdate) { + if (this.tilingTexture && this.tilingTexture.needsUpdate) + { //TODO - tweaking renderer.updateTexture(this.tilingTexture.baseTexture); this.tilingTexture.needsUpdate = false; // this.tilingTexture._uvs = null; } } - else { + else + { renderer.spriteBatch.renderTilingSprite(this); } // simple render children! - for (i=0,j=this.children.length; i= 0; i--) { + for (var i = length - 1; i >= 0; i--) + { var child = children[i]; // push all interactive bits - if (child._interactive) { + if (child._interactive) + { iParent.interactiveChildren = true; //child.__iParent = iParent; this.interactiveItems.push(child); - if (child.children.length > 0) { + if (child.children.length > 0) + { this.collectInteractiveSprite(child, child); } } - else { + else + { child.__iParent = null; - if (child.children.length > 0) { + if (child.children.length > 0) + { this.collectInteractiveSprite(child, iParent); } } @@ -189,7 +196,8 @@ * @param [resolution=1] {number} THe resolution of the new element (relative to the canvas). * @private */ -InteractionManager.prototype.setTargetElement = function (element, resolution) { +InteractionManager.prototype.setTargetElement = function (element, resolution) +{ this.removeEvents(); this.interactionDOMElement = element; @@ -203,12 +211,15 @@ * * @private */ -InteractionManager.prototype.addEvents = function () { - if (!this.interactionDOMElement) { +InteractionManager.prototype.addEvents = function () +{ + if (!this.interactionDOMElement) + { return; } - if (window.navigator.msPointerEnabled) { + if (window.navigator.msPointerEnabled) + { this.interactionDOMElement.style['-ms-content-zooming'] = 'none'; this.interactionDOMElement.style['-ms-touch-action'] = 'none'; } @@ -230,12 +241,15 @@ * * @private */ -InteractionManager.prototype.removeEvents = function () { - if (!this.interactionDOMElement) { +InteractionManager.prototype.removeEvents = function () +{ + if (!this.interactionDOMElement) + { return; } - if (window.navigator.msPointerEnabled) { + if (window.navigator.msPointerEnabled) + { this.interactionDOMElement.style['-ms-content-zooming'] = ''; this.interactionDOMElement.style['-ms-touch-action'] = ''; } @@ -260,8 +274,10 @@ * * @private */ -InteractionManager.prototype.update = function () { - if (!this.interactionDOMElement) { +InteractionManager.prototype.update = function () +{ + if (!this.interactionDOMElement) + { return; } @@ -269,7 +285,8 @@ var now = Date.now(); var diff = now - this.last; diff = (diff * INTERACTION_FREQUENCY ) / 1000; - if (diff < 1) { + if (diff < 1) + { return; } @@ -280,7 +297,8 @@ // ok.. so mouse events?? // yes for now :) // OPTIMISE - how often to check?? - if (this.dirty) { + if (this.dirty) + { this.rebuildInteractiveGraph(); } @@ -289,7 +307,8 @@ var cursor = 'inherit'; var over = false; - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { var item = this.interactiveItems[i]; // OPTIMISATION - only calculate every time if the mousemove function exists.. @@ -302,26 +321,34 @@ this.mouse.target = item; // ok so deal with interactions.. // looks like there was a hit! - if (item.__hit && !over) { - if (item.buttonMode) { + if (item.__hit && !over) + { + if (item.buttonMode) + { cursor = item.defaultCursor; } - if (!item.interactiveChildren) { + if (!item.interactiveChildren) + { over = true; } - if (!item.__isOver) { - if (item.mouseover) { + if (!item.__isOver) + { + if (item.mouseover) + { item.mouseover (this.mouse); } item.__isOver = true; } } - else { - if (item.__isOver) { + else + { + if (item.__isOver) + { // roll out! - if (item.mouseout) { + if (item.mouseout) + { item.mouseout (this.mouse); } item.__isOver = false; @@ -329,7 +356,8 @@ } } - if (this.currentCursorStyle !== cursor) { + if (this.currentCursorStyle !== cursor) + { this.currentCursorStyle = cursor; this.interactionDOMElement.style.cursor = cursor; } @@ -338,18 +366,21 @@ /** * @private */ -InteractionManager.prototype.rebuildInteractiveGraph = function () { +InteractionManager.prototype.rebuildInteractiveGraph = function () +{ this.dirty = false; var len = this.interactiveItems.length; - for (var i = 0; i < len; i++) { + for (var i = 0; i < len; i++) + { this.interactiveItems[i].interactiveChildren = false; } this.interactiveItems.length = 0; - if (this.stage.interactive) { + if (this.stage.interactive) + { this.interactiveItems.push(this.stage); } @@ -363,8 +394,10 @@ * @param event {Event} The DOM event of the mouse moving * @private */ -InteractionManager.prototype.onMouseMove = function (event) { - if (this.dirty) { +InteractionManager.prototype.onMouseMove = function (event) +{ + if (this.dirty) + { this.rebuildInteractiveGraph(); } @@ -378,11 +411,13 @@ var length = this.interactiveItems.length; - for (var i = 0; i < length; i++) { + for (var i = 0; i < length; i++) + { var item = this.interactiveItems[i]; // Call the function! - if (item.mousemove) { + if (item.mousemove) + { item.mousemove(this.mouse); } } @@ -394,14 +429,17 @@ * @param event {Event} The DOM event of a mouse button being pressed down * @private */ -InteractionManager.prototype.onMouseDown = function (event) { - if (this.dirty) { +InteractionManager.prototype.onMouseDown = function (event) +{ + if (this.dirty) + { this.rebuildInteractiveGraph(); } this.mouse.originalEvent = event; - if (AUTO_PREVENT_DEFAULT) { + if (AUTO_PREVENT_DEFAULT) + { this.mouse.originalEvent.preventDefault(); } @@ -420,22 +458,27 @@ // while // hit test - for (var i = 0; i < length; i++) { + for (var i = 0; i < length; i++) + { var item = this.interactiveItems[i]; - if (item[downFunction] || item[clickFunction]) { + if (item[downFunction] || item[clickFunction]) + { item[buttonIsDown] = true; item.__hit = this.hitTest(item, this.mouse); - if (item.__hit) { + if (item.__hit) + { //call the function! - if (item[downFunction]) { + if (item[downFunction]) + { item[downFunction](this.mouse); } item[isDown] = true; // just the one! - if (!item.interactiveChildren) { + if (!item.interactiveChildren) + { break; } } @@ -449,8 +492,10 @@ * @param event {Event} The DOM event of a mouse being moved out * @private */ -InteractionManager.prototype.onMouseOut = function (event) { - if (this.dirty) { +InteractionManager.prototype.onMouseOut = function (event) +{ + if (this.dirty) + { this.rebuildInteractiveGraph(); } @@ -460,11 +505,14 @@ this.interactionDOMElement.style.cursor = 'inherit'; - for (var i = 0; i < length; i++) { + for (var i = 0; i < length; i++) + { var item = this.interactiveItems[i]; - if (item.__isOver) { + if (item.__isOver) + { this.mouse.target = item; - if (item.mouseout) { + if (item.mouseout) + { item.mouseout(this.mouse); } item.__isOver = false; @@ -484,8 +532,10 @@ * @param event {Event} The DOM event of a mouse button being released * @private */ -InteractionManager.prototype.onMouseUp = function (event) { - if (this.dirty) { +InteractionManager.prototype.onMouseUp = function (event) +{ + if (this.dirty) + { this.rebuildInteractiveGraph(); } @@ -502,30 +552,40 @@ var upOutsideFunction = isRightButton ? 'rightupoutside' : 'mouseupoutside'; var isDown = isRightButton ? '__isRightDown' : '__isDown'; - for (var i = 0; i < length; i++) { + for (var i = 0; i < length; i++) + { var item = this.interactiveItems[i]; - if (item[clickFunction] || item[upFunction] || item[upOutsideFunction]) { + if (item[clickFunction] || item[upFunction] || item[upOutsideFunction]) + { item.__hit = this.hitTest(item, this.mouse); - if (item.__hit && !up) { + if (item.__hit && !up) + { //call the function! - if (item[upFunction]) { + if (item[upFunction]) + { item[upFunction](this.mouse); } - if (item[isDown]) { - if (item[clickFunction]) { + if (item[isDown]) + { + if (item[clickFunction]) + { item[clickFunction](this.mouse); } } - if (!item.interactiveChildren) { + if (!item.interactiveChildren) + { up = true; } } - else { - if (item[isDown]) { - if (item[upOutsideFunction]) { + else + { + if (item[isDown]) + { + if (item[upOutsideFunction]) + { item[upOutsideFunction](this.mouse); } } @@ -543,10 +603,12 @@ * @param interactionData {InteractionData} The interactionData object to update in the case there is a hit * @private */ -InteractionManager.prototype.hitTest = function (item, interactionData) { +InteractionManager.prototype.hitTest = function (item, interactionData) +{ var global = interactionData.global; - if (!item.worldVisible) { + if (!item.worldVisible) + { return false; } @@ -560,37 +622,46 @@ interactionData.target = item; //a sprite or display object with a hit area defined - if (item.hitArea && item.hitArea.contains) { + if (item.hitArea && item.hitArea.contains) + { return item.hitArea.contains(x, y); } // a sprite with no hitarea defined - else if (item instanceof core.Sprite) { + else if (item instanceof core.Sprite) + { var width = item.texture.frame.width; var height = item.texture.frame.height; var x1 = -width * item.anchor.x; var y1; - if (x > x1 && x < x1 + width) { + if (x > x1 && x < x1 + width) + { y1 = -height * item.anchor.y; - if (y > y1 && y < y1 + height) { + if (y > y1 && y < y1 + height) + { // set the target property if a hit is true! return true; } } } - else if (item instanceof core.Graphics) { + else if (item instanceof core.Graphics) + { var graphicsData = item.graphicsData; - for (i = 0; i < graphicsData.length; i++) { + for (i = 0; i < graphicsData.length; i++) + { var data = graphicsData[i]; - if (!data.fill) { + if (!data.fill) + { continue; } // only deal with fills.. - if (data.shape) { - if (data.shape.contains(x, y)) { + if (data.shape) + { + if (data.shape.contains(x, y)) + { //interactionData.target = item; return true; } @@ -600,10 +671,12 @@ var length = item.children.length; - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { var tempItem = item.children[i]; var hit = this.hitTest(tempItem, interactionData); - if (hit) { + if (hit) + { // hmm.. TODO SET CORRECT TARGET? interactionData.target = item; return true; @@ -618,8 +691,10 @@ * @param event {Event} The DOM event of a touch moving across the renderer view * @private */ -InteractionManager.prototype.onTouchMove = function (event) { - if (this.dirty) { +InteractionManager.prototype.onTouchMove = function (event) +{ + if (this.dirty) + { this.rebuildInteractiveGraph(); } @@ -628,7 +703,8 @@ var touchData; var i = 0; - for (i = 0; i < changedTouches.length; i++) { + for (i = 0; i < changedTouches.length; i++) + { var touchEvent = changedTouches[i]; touchData = this.touches[touchEvent.identifier]; touchData.originalEvent = event; @@ -636,15 +712,18 @@ // update the touch position touchData.global.x = ( (touchEvent.clientX - rect.left) * (this.interactionDOMElement.width / rect.width) ) / this.resolution; touchData.global.y = ( (touchEvent.clientY - rect.top) * (this.interactionDOMElement.height / rect.height) ) / this.resolution; - if (navigator.isCocoonJS && !rect.left && !rect.top && !event.target.style.width && !event.target.style.height) { + if (navigator.isCocoonJS && !rect.left && !rect.top && !event.target.style.width && !event.target.style.height) + { //Support for CocoonJS fullscreen scale modes touchData.global.x = touchEvent.clientX; touchData.global.y = touchEvent.clientY; } - for (var j = 0; j < this.interactiveItems.length; j++) { + for (var j = 0; j < this.interactiveItems.length; j++) + { var item = this.interactiveItems[j]; - if (item.touchmove && item.__touchData && item.__touchData[touchEvent.identifier]) { + if (item.touchmove && item.__touchData && item.__touchData[touchEvent.identifier]) + { item.touchmove(touchData); } } @@ -657,23 +736,28 @@ * @param event {Event} The DOM event of a touch starting on the renderer view * @private */ -InteractionManager.prototype.onTouchStart = function (event) { - if (this.dirty) { +InteractionManager.prototype.onTouchStart = function (event) +{ + if (this.dirty) + { this.rebuildInteractiveGraph(); } var rect = this.interactionDOMElement.getBoundingClientRect(); - if (AUTO_PREVENT_DEFAULT) { + if (AUTO_PREVENT_DEFAULT) + { event.preventDefault(); } var changedTouches = event.changedTouches; - for (var i=0; i < changedTouches.length; i++) { + for (var i=0; i < changedTouches.length; i++) + { var touchEvent = changedTouches[i]; var touchData = this.pool.pop(); - if (!touchData) { + if (!touchData) + { touchData = new InteractionData(); } @@ -682,7 +766,8 @@ this.touches[touchEvent.identifier] = touchData; touchData.global.x = ( (touchEvent.clientX - rect.left) * (this.interactionDOMElement.width / rect.width) ) / this.resolution; touchData.global.y = ( (touchEvent.clientY - rect.top) * (this.interactionDOMElement.height / rect.height) ) / this.resolution; - if (navigator.isCocoonJS && !rect.left && !rect.top && !event.target.style.width && !event.target.style.height) { + if (navigator.isCocoonJS && !rect.left && !rect.top && !event.target.style.width && !event.target.style.height) + { //Support for CocoonJS fullscreen scale modes touchData.global.x = touchEvent.clientX; touchData.global.y = touchEvent.clientY; @@ -690,15 +775,19 @@ var length = this.interactiveItems.length; - for (var j = 0; j < length; j++) { + for (var j = 0; j < length; j++) + { var item = this.interactiveItems[j]; - if (item.touchstart || item.tap) { + if (item.touchstart || item.tap) + { item.__hit = this.hitTest(item, touchData); - if (item.__hit) { + if (item.__hit) + { //call the function! - if (item.touchstart) { + if (item.touchstart) + { item.touchstart(touchData); } @@ -706,7 +795,8 @@ item.__touchData = item.__touchData || {}; item.__touchData[touchEvent.identifier] = touchData; - if (!item.interactiveChildren) { + if (!item.interactiveChildren) + { break; } } @@ -721,31 +811,37 @@ * @param event {Event} The DOM event of a touch ending on the renderer view * @private */ -InteractionManager.prototype.onTouchEnd = function (event) { - if (this.dirty) { +InteractionManager.prototype.onTouchEnd = function (event) +{ + if (this.dirty) + { this.rebuildInteractiveGraph(); } var rect = this.interactionDOMElement.getBoundingClientRect(); var changedTouches = event.changedTouches; - for (var i=0; i < changedTouches.length; i++) { + for (var i=0; i < changedTouches.length; i++) + { var touchEvent = changedTouches[i]; var touchData = this.touches[touchEvent.identifier]; var up = false; touchData.global.x = ( (touchEvent.clientX - rect.left) * (this.interactionDOMElement.width / rect.width) ) / this.resolution; touchData.global.y = ( (touchEvent.clientY - rect.top) * (this.interactionDOMElement.height / rect.height) ) / this.resolution; - if (navigator.isCocoonJS && !rect.left && !rect.top && !event.target.style.width && !event.target.style.height) { + if (navigator.isCocoonJS && !rect.left && !rect.top && !event.target.style.width && !event.target.style.height) + { //Support for CocoonJS fullscreen scale modes touchData.global.x = touchEvent.clientX; touchData.global.y = touchEvent.clientY; } var length = this.interactiveItems.length; - for (var j = 0; j < length; j++) { + for (var j = 0; j < length; j++) + { var item = this.interactiveItems[j]; - if (item.__touchData && item.__touchData[touchEvent.identifier]) { + if (item.__touchData && item.__touchData[touchEvent.identifier]) + { item.__hit = this.hitTest(item, item.__touchData[touchEvent.identifier]); @@ -753,20 +849,27 @@ touchData.originalEvent = event; // hitTest?? - if (item.touchend || item.tap) { - if (item.__hit && !up) { - if (item.touchend) { + if (item.touchend || item.tap) + { + if (item.__hit && !up) + { + if (item.touchend) + { item.touchend(touchData); } - if (item.__isDown && item.tap) { + if (item.__isDown && item.tap) + { item.tap(touchData); } - if (!item.interactiveChildren) { + if (!item.interactiveChildren) + { up = true; } } - else { - if (item.__isDown && item.touchendoutside) { + else + { + if (item.__isDown && item.touchendoutside) + { item.touchendoutside(touchData); } } diff --git a/src/loaders/AssetLoader.js b/src/loaders/AssetLoader.js index 20da0cf..c4dba1c 100644 --- a/src/loaders/AssetLoader.js +++ b/src/loaders/AssetLoader.js @@ -21,7 +21,8 @@ * data formats include 'xml' and 'fnt'. * @param crossorigin {boolean} Whether requests should be treated as crossorigin */ -function AssetLoader(assetURLs, crossorigin) { +function AssetLoader(assetURLs, crossorigin) +{ /** * The array of asset URLs that are going to be loaded * @@ -76,16 +77,19 @@ * * @param str {string} the name of the asset */ -AssetLoader.prototype._getDataType = function (str) { +AssetLoader.prototype._getDataType = function (str) +{ var test = 'data:'; var start = str.slice(0, test.length).toLowerCase(); - if (start === test) { + if (start === test) + { var data = str.slice(test.length); var sepIdx = data.indexOf(','); // check for malformed data URI scheme - if (sepIdx === -1) { + if (sepIdx === -1) + { return null; } @@ -94,7 +98,8 @@ //We might need to handle some special cases here... //standardize text/plain to 'txt' file extension - if (!info || info.toLowerCase() === 'text/plain') { + if (!info || info.toLowerCase() === 'text/plain') + { return 'txt'; } @@ -109,27 +114,32 @@ * Starts loading the assets sequentially * */ -AssetLoader.prototype.load = function () { +AssetLoader.prototype.load = function () +{ var scope = this; - function onLoad(evt) { + function onLoad(evt) + { scope.onAssetLoaded(evt.data.content); } this.loadCount = this.assetURLs.length; - for (var i=0; i < this.assetURLs.length; i++) { + for (var i=0; i < this.assetURLs.length; i++) + { var fileName = this.assetURLs[i]; //first see if we have a data URI scheme.. var fileType = this._getDataType(fileName); //if not, assume it's a file URI - if (!fileType) { + if (!fileType) + { fileType = fileName.split('?').shift().split('.').pop().toLowerCase(); } var Constructor = this.loadersByType[fileType]; - if (!Constructor) { + if (!Constructor) + { throw new Error(fileType + ' is an unsupported file type'); } @@ -145,18 +155,22 @@ * * @private */ -AssetLoader.prototype.onAssetLoaded = function (loader) { +AssetLoader.prototype.onAssetLoaded = function (loader) +{ this.loadCount--; this.emit('onProgress', { content: this, loader: loader }); - if (this.onProgress) { + if (this.onProgress) + { this.onProgress(loader); } - if (!this.loadCount) { + if (!this.loadCount) + { this.emit('onComplete', { content: this }); - if (this.onComplete) { + if (this.onComplete) + { this.onComplete(); } } diff --git a/src/loaders/AtlasLoader.js b/src/loaders/AtlasLoader.js index 5eda286..3aec9e2 100644 --- a/src/loaders/AtlasLoader.js +++ b/src/loaders/AtlasLoader.js @@ -15,7 +15,8 @@ * @param url {String} The url of the JSON file * @param crossorigin {boolean} Whether requests should be treated as crossorigin */ -function AtlasLoader(url, crossorigin) { +function AtlasLoader(url, crossorigin) +{ this.url = url; this.baseUrl = url.replace(/[^\/]*$/, ''); this.crossorigin = crossorigin; @@ -31,13 +32,15 @@ * Starts loading the JSON file * */ -AtlasLoader.prototype.load = function () { +AtlasLoader.prototype.load = function () +{ this.ajaxRequest = new core.utils.AjaxRequest(); this.ajaxRequest.onreadystatechange = this.onAtlasLoaded.bind(this); this.ajaxRequest.open('GET', this.url, true); - if (this.ajaxRequest.overrideMimeType) { + if (this.ajaxRequest.overrideMimeType) + { this.ajaxRequest.overrideMimeType('application/json'); } @@ -49,9 +52,12 @@ * * @private */ -AtlasLoader.prototype.onAtlasLoaded = function () { - if (this.ajaxRequest.readyState === 4) { - if (this.ajaxRequest.status === 200 || window.location.href.indexOf('http') === -1) { +AtlasLoader.prototype.onAtlasLoaded = function () +{ + if (this.ajaxRequest.readyState === 4) + { + if (this.ajaxRequest.status === 200 || window.location.href.indexOf('http') === -1) + { this.atlas = { meta : { image : [] @@ -70,34 +76,44 @@ selfOnLoaded = this.onLoaded.bind(this); // parser without rotation support yet! - for (i = 0; i < result.length; i++) { + for (i = 0; i < result.length; i++) + { result[i] = result[i].replace(/^\s+|\s+$/g, ''); - if (result[i] === '') { + if (result[i] === '') + { nameInNextLine = i+1; } - if (result[i].length > 0) { - if (nameInNextLine === i) { + if (result[i].length > 0) + { + if (nameInNextLine === i) + { this.atlas.meta.image.push(result[i]); currentImageId = this.atlas.meta.image.length - 1; this.atlas.frames.push({}); lineCount = -3; - } else if (lineCount > 0) { - if (lineCount % 7 === 1) { // frame name - if (currentFrame != null) { //jshint ignore:line + } else if (lineCount > 0) + { + if (lineCount % 7 === 1) + { // frame name + if (currentFrame != null) + { //jshint ignore:line this.atlas.frames[currentImageId][currentFrame.name] = currentFrame; } currentFrame = { name: result[i], frame : {} }; } else { var text = result[i].split(' '); - if (lineCount % 7 === 3) { // position + if (lineCount % 7 === 3) + { // position currentFrame.frame.x = Number(text[1].replace(',', '')); currentFrame.frame.y = Number(text[2]); - } else if (lineCount % 7 === 4) { // size + } else if (lineCount % 7 === 4) + { // size currentFrame.frame.w = Number(text[1].replace(',', '')); currentFrame.frame.h = Number(text[2]); - } else if (lineCount % 7 === 5) { // real size + } else if (lineCount % 7 === 5) + { // real size var realSize = { x : 0, y : 0, @@ -105,7 +121,8 @@ h : Number(text[2]) }; - if (realSize.w > currentFrame.frame.w || realSize.h > currentFrame.frame.h) { + if (realSize.w > currentFrame.frame.w || realSize.h > currentFrame.frame.h) + { currentFrame.trimmed = true; currentFrame.realSize = realSize; } else { @@ -118,28 +135,34 @@ } } - if (currentFrame != null) { //jshint ignore:line + if (currentFrame != null) + { //jshint ignore:line this.atlas.frames[currentImageId][currentFrame.name] = currentFrame; } - if (this.atlas.meta.image.length > 0) { + if (this.atlas.meta.image.length > 0) + { this.images = []; - for (j = 0; j < this.atlas.meta.image.length; j++) { + for (j = 0; j < this.atlas.meta.image.length; j++) + { // sprite sheet var textureUrl = this.baseUrl + this.atlas.meta.image[j]; var frameData = this.atlas.frames[j]; this.images.push(new ImageLoader(textureUrl, this.crossorigin)); - for (i in frameData) { + for (i in frameData) + { var rect = frameData[i].frame; - if (rect) { + if (rect) + { core.utils.TextureCache[i] = new core.Texture(this.images[j].texture.baseTexture, { x: rect.x, y: rect.y, width: rect.w, height: rect.h }); - if (frameData[i].trimmed) { + if (frameData[i].trimmed) + { core.utils.TextureCache[i].realSize = frameData[i].realSize; // trim in pixi not supported yet, todo update trim properties if it is done ... core.utils.TextureCache[i].trim.x = 0; @@ -150,7 +173,8 @@ } this.currentImageId = 0; - for (j = 0; j < this.images.length; j++) { + for (j = 0; j < this.images.length; j++) + { this.images[j].on('loaded', selfOnLoaded); } this.images[this.currentImageId].load(); @@ -170,8 +194,10 @@ * * @private */ -AtlasLoader.prototype.onLoaded = function () { - if (this.images.length - 1 > this.currentImageId) { +AtlasLoader.prototype.onLoaded = function () +{ + if (this.images.length - 1 > this.currentImageId) + { this.currentImageId++; this.images[this.currentImageId].load(); } else { @@ -185,6 +211,7 @@ * * @private */ -AtlasLoader.prototype.onError = function () { +AtlasLoader.prototype.onError = function () +{ this.emit('error', { content: this }); }; diff --git a/src/loaders/BitmapFontLoader.js b/src/loaders/BitmapFontLoader.js index 8641760..13e5c1b 100644 --- a/src/loaders/BitmapFontLoader.js +++ b/src/loaders/BitmapFontLoader.js @@ -13,7 +13,8 @@ * @param url {String} The url of the sprite sheet JSON file * @param crossorigin {boolean} Whether requests should be treated as crossorigin */ -function BitmapFontLoader(url, crossorigin) { +function BitmapFontLoader(url, crossorigin) +{ /** * The url of the bitmap font data * @@ -54,13 +55,15 @@ * Loads the XML font data * */ -BitmapFontLoader.prototype.load = function () { +BitmapFontLoader.prototype.load = function () +{ this.ajaxRequest = new core.utils.AjaxRequest(); this.ajaxRequest.onreadystatechange = this.onXMLLoaded.bind(this); this.ajaxRequest.open('GET', this.url, true); - if (this.ajaxRequest.overrideMimeType) { + if (this.ajaxRequest.overrideMimeType) + { this.ajaxRequest.overrideMimeType('application/xml'); } @@ -72,12 +75,17 @@ * * @private */ -BitmapFontLoader.prototype.onXMLLoaded = function () { - if (this.ajaxRequest.readyState === 4) { - if (this.ajaxRequest.status === 200 || window.location.protocol.indexOf('http') === -1) { +BitmapFontLoader.prototype.onXMLLoaded = function () +{ + if (this.ajaxRequest.readyState === 4) + { + if (this.ajaxRequest.status === 200 || window.location.protocol.indexOf('http') === -1) + { var responseXML = this.ajaxRequest.responseXML; - if (!responseXML || /MSIE 9/i.test(navigator.userAgent) || navigator.isCocoonJS) { - if (typeof(window.DOMParser) === 'function') { + if (!responseXML || /MSIE 9/i.test(navigator.userAgent) || navigator.isCocoonJS) + { + if (typeof(window.DOMParser) === 'function') + { var domparser = new DOMParser(); responseXML = domparser.parseFromString(this.ajaxRequest.responseText, 'text/xml'); } else { @@ -102,7 +110,8 @@ //parse letters var letters = responseXML.getElementsByTagName('char'); - for (var i = 0; i < letters.length; i++) { + for (var i = 0; i < letters.length; i++) + { var charCode = parseInt(letters[i].getAttribute('id'), 10); var textureRect = new core.math.Rectangle( @@ -124,7 +133,8 @@ //parse kernings var kernings = responseXML.getElementsByTagName('kerning'); - for (i = 0; i < kernings.length; i++) { + for (i = 0; i < kernings.length; i++) + { var first = parseInt(kernings[i].getAttribute('first'), 10); var second = parseInt(kernings[i].getAttribute('second'), 10); var amount = parseInt(kernings[i].getAttribute('amount'), 10); @@ -146,6 +156,7 @@ * * @private */ -BitmapFontLoader.prototype.onLoaded = function () { +BitmapFontLoader.prototype.onLoaded = function () +{ this.emit('loaded', { content: this }); }; diff --git a/src/loaders/ImageLoader.js b/src/loaders/ImageLoader.js index e3ff493..16ee7c8 100644 --- a/src/loaders/ImageLoader.js +++ b/src/loaders/ImageLoader.js @@ -11,7 +11,8 @@ * @param url {String} The url of the image * @param crossorigin {boolean} Whether requests should be treated as crossorigin */ -function ImageLoader(url, crossorigin) { +function ImageLoader(url, crossorigin) +{ /** * The texture being loaded * @@ -39,12 +40,15 @@ * Loads image or takes it from cache * */ -ImageLoader.prototype.load = function () { - if (!this.texture.baseTexture.hasLoaded) { +ImageLoader.prototype.load = function () +{ + if (!this.texture.baseTexture.hasLoaded) + { this.texture.baseTexture.on('loaded', this.onLoaded.bind(this)); this.texture.baseTexture.on('error', this.onError.bind(this)); } - else { + else + { this.onLoaded(); } }; @@ -54,7 +58,8 @@ * * @private */ -ImageLoader.prototype.onLoaded = function () { +ImageLoader.prototype.onLoaded = function () +{ this.emit('loaded', { content: this }); }; @@ -64,7 +69,8 @@ * @method onError * @private */ -ImageLoader.prototype.onError = function () { +ImageLoader.prototype.onError = function () +{ this.emit('error', { content: this }); }; @@ -75,15 +81,18 @@ * @param frameHeight {number} height of each frame * @param textureName {String} if given, the frames will be cached in - format */ -ImageLoader.prototype.loadFramedSpriteSheet = function (frameWidth, frameHeight, textureName) { +ImageLoader.prototype.loadFramedSpriteSheet = function (frameWidth, frameHeight, textureName) +{ this.frames = []; var cols = Math.floor(this.texture.width / frameWidth); var rows = Math.floor(this.texture.height / frameHeight); var i=0; - for (var y = 0; y < rows; ++y) { - for (var x = 0; x < cols; ++x, ++i) { + for (var y = 0; y < rows; ++y) + { + for (var x = 0; x < cols; ++x, ++i) + { var texture = new core.Texture( this.texture.baseTexture, new core.math.Rectangle( @@ -96,7 +105,8 @@ this.frames.push(texture); - if (textureName) { + if (textureName) + { core.utils.TextureCache[textureName + '-' + i] = texture; } } diff --git a/src/loaders/JsonLoader.js b/src/loaders/JsonLoader.js index 3279f40..7aabeb4 100644 --- a/src/loaders/JsonLoader.js +++ b/src/loaders/JsonLoader.js @@ -14,7 +14,8 @@ * @param url {String} The url of the JSON file * @param crossorigin {boolean} Whether requests should be treated as crossorigin */ -function JsonLoader(url, crossorigin) { +function JsonLoader(url, crossorigin) +{ /** * The url of the bitmap font data * @@ -56,8 +57,10 @@ * Loads the JSON data * */ -JsonLoader.prototype.load = function () { - if (window.XDomainRequest && this.crossorigin) { +JsonLoader.prototype.load = function () +{ + if (window.XDomainRequest && this.crossorigin) + { this.ajaxRequest = new window.XDomainRequest(); // XDomainRequest has a few quirks. Occasionally it will abort requests @@ -68,15 +71,19 @@ this.ajaxRequest.onerror = this.onError.bind(this); this.ajaxRequest.ontimeout = this.onError.bind(this); - this.ajaxRequest.onprogress = function () {}; + this.ajaxRequest.onprogress = function () + {}; this.ajaxRequest.onload = this.onJSONLoaded.bind(this); } - else { - if (window.XMLHttpRequest) { + else + { + if (window.XMLHttpRequest) + { this.ajaxRequest = new window.XMLHttpRequest(); } - else { + else + { this.ajaxRequest = new window.ActiveXObject('Microsoft.XMLHTTP'); } @@ -93,8 +100,10 @@ * * @private */ -JsonLoader.prototype.onReadyStateChanged = function () { - if (this.ajaxRequest.readyState === 4 && (this.ajaxRequest.status === 200 || window.location.href.indexOf('http') === -1)) { +JsonLoader.prototype.onReadyStateChanged = function () +{ + if (this.ajaxRequest.readyState === 4 && (this.ajaxRequest.status === 200 || window.location.href.indexOf('http') === -1)) + { this.onJSONLoaded(); } }; @@ -104,15 +113,18 @@ * * @private */ -JsonLoader.prototype.onJSONLoaded = function () { - if (!this.ajaxRequest.responseText) { +JsonLoader.prototype.onJSONLoaded = function () +{ + if (!this.ajaxRequest.responseText) + { this.onError(); return; } this.json = JSON.parse(this.ajaxRequest.responseText); - if (this.json.frames) { + if (this.json.frames) + { // sprite sheet var textureUrl = this.baseUrl + this.json.meta.image; var image = new ImageLoader(textureUrl, this.crossorigin); @@ -122,16 +134,19 @@ image.addEventListener('loaded', this.onLoaded.bind(this)); image.addEventListener('error', this.onError.bind(this)); - for (var i in frameData) { + for (var i in frameData) + { var rect = frameData[i].frame; - if (rect) { + if (rect) + { var textureSize = new core.math.Rectangle(rect.x, rect.y, rect.w, rect.h); var crop = textureSize.clone(); var trim = null; // Check to see if the sprite is trimmed - if (frameData[i].trimmed) { + if (frameData[i].trimmed) + { var actualSize = frameData[i].sourceSize; var realSize = frameData[i].spriteSourceSize; trim = new core.math.Rectangle(realSize.x, realSize.y, actualSize.w, actualSize.h); @@ -143,12 +158,15 @@ image.load(); } - else if (this.json.bones) { + else if (this.json.bones) + { // check if the json was loaded before - if (core.utils.AnimCache[this.url]) { + if (core.utils.AnimCache[this.url]) + { this.onLoaded(); } - else { + else + { /** * use a bit of hackery to load the atlas file, here we assume that the .json, .atlas and .png files * that correspond to the spine file are in the same base URL and that the .json and .atlas files @@ -159,9 +177,11 @@ // save a copy of the current object for future reference // var originalLoader = this; // before loading the file, replace the "onJSONLoaded" function for our own // - atlasLoader.onJSONLoaded = function () { + atlasLoader.onJSONLoaded = function () + { // at this point "this" points at the atlasLoader (JsonLoader) instance // - if (!this.ajaxRequest.responseText) { + if (!this.ajaxRequest.responseText) + { this.onError(); // FIXME: hmm, this is funny because we are not responding to errors yet return; } @@ -179,14 +199,18 @@ originalLoader.spineAtlas = spineAtlas; originalLoader.spineAtlasLoader = atlasLoader; // wait for textures to finish loading if needed - if (textureLoader.loadingCount > 0) { - textureLoader.addEventListener('loadedBaseTexture', function (evt){ - if (evt.content.content.loadingCount <= 0) { + if (textureLoader.loadingCount > 0) + { + textureLoader.addEventListener('loadedBaseTexture', function (evt) + { + if (evt.content.content.loadingCount <= 0) + { originalLoader.onLoaded(); } }); } - else { + else + { originalLoader.onLoaded(); } }; @@ -194,7 +218,8 @@ atlasLoader.load(); } } - else { + else + { this.onLoaded(); } }; @@ -204,7 +229,8 @@ * * @private */ -JsonLoader.prototype.onLoaded = function () { +JsonLoader.prototype.onLoaded = function () +{ this.loaded = true; this.dispatchEvent({ type: 'loaded', @@ -217,7 +243,8 @@ * * @private */ -JsonLoader.prototype.onError = function () { +JsonLoader.prototype.onError = function () +{ this.dispatchEvent({ type: 'error', diff --git a/src/loaders/SpineLoader.js b/src/loaders/SpineLoader.js index 51aaddb..69bae21 100644 --- a/src/loaders/SpineLoader.js +++ b/src/loaders/SpineLoader.js @@ -24,7 +24,8 @@ * @param url {String} The url of the JSON file * @param crossorigin {boolean} Whether requests should be treated as crossorigin */ -function SpineLoader(url, crossorigin) { +function SpineLoader(url, crossorigin) +{ /** * The url of the bitmap font data * @@ -57,11 +58,13 @@ * Loads the JSON data * */ -SpineLoader.prototype.load = function () { +SpineLoader.prototype.load = function () +{ var scope = this; var jsonLoader = new JsonLoader(this.url, this.crossorigin); - jsonLoader.on('loaded', function (event) { + jsonLoader.on('loaded', function (event) + { scope.json = event.data.content.json; scope.onLoaded(); }); @@ -74,7 +77,8 @@ * * @private */ -SpineLoader.prototype.onLoaded = function () { +SpineLoader.prototype.onLoaded = function () +{ this.loaded = true; this.emit('loaded', { content: this }); }; diff --git a/src/loaders/SpineTextureLoader.js b/src/loaders/SpineTextureLoader.js index 61c51c0..c09a548 100644 --- a/src/loaders/SpineTextureLoader.js +++ b/src/loaders/SpineTextureLoader.js @@ -9,7 +9,8 @@ * @param basePath {string} Tha base path where to look for the images to be loaded * @param crossorigin {boolean} Whether requests should be treated as crossorigin */ -function SpineTextureLoader(basePath, crossorigin) { +function SpineTextureLoader(basePath, crossorigin) +{ this.basePath = basePath; this.crossorigin = crossorigin; this.loadingCount = 0; @@ -26,12 +27,15 @@ * @param page {spine.AtlasPage} Atlas page to which texture belongs * @param file {string} The file to load, this is just the file path relative to the base path configured in the constructor */ -SpineTextureLoader.prototype.load = function (page, file) { +SpineTextureLoader.prototype.load = function (page, file) +{ page.rendererObject = core.BaseTexture.fromImage(this.basePath + '/' + file, this.crossorigin); - if (!page.rendererObject.hasLoaded) { + if (!page.rendererObject.hasLoaded) + { var scope = this; ++scope.loadingCount; - page.rendererObject.addEventListener('loaded', function (){ + page.rendererObject.addEventListener('loaded', function () + { --scope.loadingCount; scope.dispatchEvent({ type: 'loadedBaseTexture', @@ -46,6 +50,7 @@ * * @param texture {BaseTexture} Texture object to destroy */ -SpineTextureLoader.prototype.unload = function (texture) { +SpineTextureLoader.prototype.unload = function (texture) +{ texture.destroy(true); }; diff --git a/src/loaders/SpriteSheetLoader.js b/src/loaders/SpriteSheetLoader.js index 5ee79df..a554e9d 100644 --- a/src/loaders/SpriteSheetLoader.js +++ b/src/loaders/SpriteSheetLoader.js @@ -16,7 +16,8 @@ * @param url {String} The url of the sprite sheet JSON file * @param crossorigin {boolean} Whether requests should be treated as crossorigin */ -function SpriteSheetLoader(url, crossorigin) { +function SpriteSheetLoader(url, crossorigin) +{ /** * The url of the atlas data @@ -65,11 +66,13 @@ * This will begin loading the JSON file * */ -SpriteSheetLoader.prototype.load = function () { +SpriteSheetLoader.prototype.load = function () +{ var scope = this; var jsonLoader = new JsonLoader(this.url, this.crossorigin); - jsonLoader.on('loaded', function (event) { + jsonLoader.on('loaded', function (event) + { scope.json = event.data.content.json; scope.onLoaded(); }); @@ -82,7 +85,8 @@ * * @private */ -SpriteSheetLoader.prototype.onLoaded = function () { +SpriteSheetLoader.prototype.onLoaded = function () +{ this.emit('loaded', { content: this }); diff --git a/src/spine/Spine.js b/src/spine/Spine.js index be7ad18..ce425cc 100644 --- a/src/spine/Spine.js +++ b/src/spine/Spine.js @@ -15,12 +15,14 @@ * @namespace PIXI * @param url {string} The url of the spine anim file to be used */ -function Spine(url) { +function Spine(url) +{ core.DisplayObjectContainer.call(this); this.spineData = core.utils.AnimCache[url]; - if (!this.spineData) { + if (!this.spineData) + { throw new Error('Spine data must be preloaded using SpineLoader or AssetLoader: ' + url); } @@ -32,27 +34,31 @@ this.slotContainers = []; - for (var i = 0, n = this.skeleton.drawOrder.length; i < n; i++) { + for (var i = 0, n = this.skeleton.drawOrder.length; i < n; i++) + { var slot = this.skeleton.drawOrder[i]; var attachment = slot.attachment; var slotContainer = new core.DisplayObjectContainer(); this.slotContainers.push(slotContainer); this.addChild(slotContainer); - if (attachment instanceof spine.RegionAttachment) { + if (attachment instanceof spine.RegionAttachment) + { var spriteName = attachment.rendererObject.name; var sprite = this.createSprite(slot, attachment); slot.currentSprite = sprite; slot.currentSpriteName = spriteName; slotContainer.addChild(sprite); } - else if (attachment instanceof spine.MeshAttachment) { + else if (attachment instanceof spine.MeshAttachment) + { var mesh = this.createMesh(slot, attachment); slot.currentMesh = mesh; slot.currentMeshName = attachment.name; slotContainer.addChild(mesh); } - else { + else + { continue; } @@ -78,11 +84,13 @@ * @default true */ autoUpdate: { - get: function () { + get: function () + { return (this.updateTransform === Spine.prototype.autoUpdateTransform); }, - set: function (value) { + set: function (value) + { this.updateTransform = value ? Spine.prototype.autoUpdateTransform : core.DisplayObjectContainer.prototype.updateTransform; } } @@ -93,35 +101,44 @@ * * @param dt {number} Delta time. Time by which the animation should be updated */ -Spine.prototype.update = function (dt) { +Spine.prototype.update = function (dt) +{ this.state.update(dt); this.state.apply(this.skeleton); this.skeleton.updateWorldTransform(); var drawOrder = this.skeleton.drawOrder; - for (var i = 0, n = drawOrder.length; i < n; i++) { + for (var i = 0, n = drawOrder.length; i < n; i++) + { var slot = drawOrder[i]; var attachment = slot.attachment; var slotContainer = this.slotContainers[i]; - if (!attachment) { + if (!attachment) + { slotContainer.visible = false; continue; } var type = attachment.type; - if (type === spine.AttachmentType.region) { - if (attachment.rendererObject) { - if (!slot.currentSpriteName || slot.currentSpriteName !== attachment.rendererObject.name) { + if (type === spine.AttachmentType.region) + { + if (attachment.rendererObject) + { + if (!slot.currentSpriteName || slot.currentSpriteName !== attachment.rendererObject.name) + { var spriteName = attachment.rendererObject.name; - if (slot.currentSprite !== undefined) { + if (slot.currentSprite !== undefined) + { slot.currentSprite.visible = false; } slot.sprites = slot.sprites || {}; - if (slot.sprites[spriteName] !== undefined) { + if (slot.sprites[spriteName] !== undefined) + { slot.sprites[spriteName].visible = true; } - else { + else + { var sprite = this.createSprite(slot, attachment); slotContainer.addChild(sprite); } @@ -141,19 +158,24 @@ slot.currentSprite.tint = core.utils.rgb2hex([slot.r,slot.g,slot.b]); } - else if (type === spine.AttachmentType.skinnedmesh) { - if (!slot.currentMeshName || slot.currentMeshName !== attachment.name) { + else if (type === spine.AttachmentType.skinnedmesh) + { + if (!slot.currentMeshName || slot.currentMeshName !== attachment.name) + { var meshName = attachment.name; - if (slot.currentMesh !== undefined) { + if (slot.currentMesh !== undefined) + { slot.currentMesh.visible = false; } slot.meshes = slot.meshes || {}; - if (slot.meshes[meshName] !== undefined) { + if (slot.meshes[meshName] !== undefined) + { slot.meshes[meshName].visible = true; } - else { + else + { var mesh = this.createMesh(slot, attachment); slotContainer.addChild(mesh); } @@ -165,7 +187,8 @@ attachment.computeWorldVertices(slot.bone.skeleton.x, slot.bone.skeleton.y, slot, slot.currentMesh.vertices); } - else { + else + { slotContainer.visible = false; continue; } @@ -180,7 +203,8 @@ * * @private */ -Spine.prototype.autoUpdateTransform = function () { +Spine.prototype.autoUpdateTransform = function () +{ this.lastTime = this.lastTime || Date.now(); var timeDelta = (Date.now() - this.lastTime) * 0.001; this.lastTime = Date.now(); @@ -197,7 +221,8 @@ * @param attachment {spine.RegionAttachment} The attachment that the sprite will represent * @private */ -Spine.prototype.createSprite = function (slot, attachment) { +Spine.prototype.createSprite = function (slot, attachment) +{ var descriptor = attachment.rendererObject; var baseTexture = descriptor.page.rendererObject; var spriteRect = new core.math.Rectangle(descriptor.x, @@ -223,7 +248,8 @@ * @param attachment {spine.RegionAttachment} The attachment that the sprite will represent * @private */ -Spine.prototype.createMesh = function (slot, attachment) { +Spine.prototype.createMesh = function (slot, attachment) +{ var descriptor = attachment.rendererObject; var baseTexture = descriptor.page.rendererObject; var texture = new core.Texture(baseTexture); diff --git a/src/spine/SpineRuntime.js b/src/spine/SpineRuntime.js index 392a878..fadd1b5 100644 --- a/src/spine/SpineRuntime.js +++ b/src/spine/SpineRuntime.js @@ -36,7 +36,8 @@ Uint16Array: (typeof(Uint16Array) === 'undefined') ? Array : Uint16Array }; -spine.BoneData = function (name, parent) { +spine.BoneData = function (name, parent) +{ this.name = name; this.parent = parent; }; @@ -50,7 +51,8 @@ flipX: false, flipY: false }; -spine.SlotData = function (name, boneData) { +spine.SlotData = function (name, boneData) +{ this.name = name; this.boneData = boneData; }; @@ -60,7 +62,8 @@ additiveBlending: false }; -spine.IkConstraintData = function (name) { +spine.IkConstraintData = function (name) +{ this.name = name; this.bones = []; }; @@ -70,7 +73,8 @@ mix: 1 }; -spine.Bone = function (boneData, skeleton, parent) { +spine.Bone = function (boneData, skeleton, parent) +{ this.data = boneData; this.skeleton = skeleton; this.parent = parent; @@ -87,12 +91,15 @@ worldRotation: 0, worldScaleX: 1, worldScaleY: 1, worldFlipX: false, worldFlipY: false, - updateWorldTransform: function () { + updateWorldTransform: function () + { var parent = this.parent; - if (parent) { + if (parent) + { this.worldX = this.x * parent.m00 + this.y * parent.m01 + parent.worldX; this.worldY = this.x * parent.m10 + this.y * parent.m11 + parent.worldY; - if (this.data.inheritScale) { + if (this.data.inheritScale) + { this.worldScaleX = parent.worldScaleX * this.scaleX; this.worldScaleY = parent.worldScaleY * this.scaleY; } else { @@ -115,14 +122,16 @@ var radians = this.worldRotation * spine.degRad; var cos = Math.cos(radians); var sin = Math.sin(radians); - if (this.worldFlipX) { + if (this.worldFlipX) + { this.m00 = -cos * this.worldScaleX; this.m01 = sin * this.worldScaleY; } else { this.m00 = cos * this.worldScaleX; this.m01 = -sin * this.worldScaleY; } - if (this.worldFlipY != spine.Bone.yDown) { + if (this.worldFlipY != spine.Bone.yDown) + { this.m10 = -sin * this.worldScaleX; this.m11 = -cos * this.worldScaleY; } else { @@ -130,7 +139,8 @@ this.m11 = cos * this.worldScaleY; } }, - setToSetupPose: function () { + setToSetupPose: function () + { var data = this.data; this.x = data.x; this.y = data.y; @@ -141,10 +151,12 @@ this.flipX = data.flipX; this.flipY = data.flipY; }, - worldToLocal: function (world) { + worldToLocal: function (world) + { var dx = world[0] - this.worldX, dy = world[1] - this.worldY; var m00 = this.m00, m10 = this.m10, m01 = this.m01, m11 = this.m11; - if (this.worldFlipX != (this.worldFlipY != spine.Bone.yDown)) { + if (this.worldFlipX != (this.worldFlipY != spine.Bone.yDown)) + { m00 = -m00; m11 = -m11; } @@ -152,14 +164,16 @@ world[0] = dx * m00 * invDet - dy * m01 * invDet; world[1] = dy * m11 * invDet - dx * m10 * invDet; }, - localToWorld: function (local) { + localToWorld: function (local) + { var localX = local[0], localY = local[1]; local[0] = localX * this.m00 + localY * this.m01 + this.worldX; local[1] = localX * this.m10 + localY * this.m11 + this.worldY; } }; -spine.Slot = function (slotData, bone) { +spine.Slot = function (slotData, bone) +{ this.data = slotData; this.bone = bone; this.setToSetupPose(); @@ -169,18 +183,22 @@ _attachmentTime: 0, attachment: null, attachmentVertices: [], - setAttachment: function (attachment) { + setAttachment: function (attachment) + { this.attachment = attachment; this._attachmentTime = this.bone.skeleton.time; this.attachmentVertices.length = 0; }, - setAttachmentTime: function (time) { + setAttachmentTime: function (time) + { this._attachmentTime = this.bone.skeleton.time - time; }, - getAttachmentTime: function () { + getAttachmentTime: function () + { return this.bone.skeleton.time - this._attachmentTime; }, - setToSetupPose: function () { + setToSetupPose: function () + { var data = this.data; this.r = data.r; this.g = data.g; @@ -188,8 +206,10 @@ this.a = data.a; var slotDatas = this.bone.skeleton.data.slots; - for (var i = 0, n = slotDatas.length; i < n; i++) { - if (slotDatas[i] == data) { + for (var i = 0, n = slotDatas.length; i < n; i++) + { + if (slotDatas[i] == data) + { this.setAttachment(!data.attachmentName ? null : this.bone.skeleton.getAttachmentBySlotIndex(i, data.attachmentName)); break; } @@ -197,7 +217,8 @@ } }; -spine.IkConstraint = function (data, skeleton) { +spine.IkConstraint = function (data, skeleton) +{ this.data = data; this.mix = data.mix; this.bendDirection = data.bendDirection; @@ -208,10 +229,12 @@ this.target = skeleton.findBone(data.target.name); }; spine.IkConstraint.prototype = { - apply: function () { + apply: function () + { var target = this.target; var bones = this.bones; - switch (bones.length) { + switch (bones.length) + { case 1: spine.IkConstraint.apply1(bones[0], target.worldX, target.worldY, this.mix); break; @@ -223,7 +246,8 @@ }; /** Adjusts the bone rotation so the tip is as close to the target position as possible. The target is specified in the world * coordinate system. */ -spine.IkConstraint.apply1 = function (bone, targetX, targetY, alpha) { +spine.IkConstraint.apply1 = function (bone, targetX, targetY, alpha) +{ var parentRotation = (!bone.data.inheritRotation || !bone.parent) ? 0 : bone.parent.worldRotation; var rotation = bone.rotation; var rotationIK = Math.atan2(targetY - bone.worldY, targetX - bone.worldX) * spine.radDeg - parentRotation; @@ -232,16 +256,19 @@ /** Adjusts the parent and child bone rotations so the tip of the child is as close to the target position as possible. The * target is specified in the world coordinate system. * @param child Any descendant bone of the parent. */ -spine.IkConstraint.apply2 = function (parent, child, targetX, targetY, bendDirection, alpha) { +spine.IkConstraint.apply2 = function (parent, child, targetX, targetY, bendDirection, alpha) +{ var childRotation = child.rotation, parentRotation = parent.rotation; - if (!alpha) { + if (!alpha) + { child.rotationIK = childRotation; parent.rotationIK = parentRotation; return; } var positionX, positionY, tempPosition = spine.temp; var parentParent = parent.parent; - if (parentParent) { + if (parentParent) + { tempPosition[0] = targetX; tempPosition[1] = targetY; parentParent.worldToLocal(tempPosition); @@ -251,7 +278,8 @@ targetX -= parent.x; targetY -= parent.y; } - if (child.parent == parent) { + if (child.parent == parent) + { positionX = child.x; positionY = child.y; } else { @@ -267,7 +295,8 @@ var len1 = Math.sqrt(childX * childX + childY * childY), len2 = child.data.length * child.worldScaleX; // Based on code by Ryan Juckett with permission: Copyright (c) 2008-2009 Ryan Juckett, http://www.ryanjuckett.com/ var cosDenom = 2 * len1 * len2; - if (cosDenom < 0.0001) { + if (cosDenom < 0.0001) + { child.rotationIK = childRotation + (Math.atan2(targetY, targetX) * spine.radDeg - parentRotation - childRotation) * alpha; return; } @@ -293,24 +322,30 @@ child.rotationIK = childRotation + (rotation + parent.worldRotation - child.parent.worldRotation) * alpha; }; -spine.Skin = function (name) { +spine.Skin = function (name) +{ this.name = name; this.attachments = {}; }; spine.Skin.prototype = { - addAttachment: function (slotIndex, name, attachment) { + addAttachment: function (slotIndex, name, attachment) + { this.attachments[slotIndex + ":" + name] = attachment; }, - getAttachment: function (slotIndex, name) { + getAttachment: function (slotIndex, name) + { return this.attachments[slotIndex + ":" + name]; }, - _attachAll: function (skeleton, oldSkin) { - for (var key in oldSkin.attachments) { + _attachAll: function (skeleton, oldSkin) + { + for (var key in oldSkin.attachments) + { var colon = key.indexOf(":"); var slotIndex = parseInt(key.substring(0, colon)); var name = key.substring(colon + 1); var slot = skeleton.slots[slotIndex]; - if (slot.attachment && slot.attachment.name == name) { + if (slot.attachment && slot.attachment.name == name) + { var attachment = this.getAttachment(slotIndex, name); if (attachment) slot.setAttachment(attachment); } @@ -318,14 +353,17 @@ } }; -spine.Animation = function (name, timelines, duration) { +spine.Animation = function (name, timelines, duration) +{ this.name = name; this.timelines = timelines; this.duration = duration; }; spine.Animation.prototype = { - apply: function (skeleton, lastTime, time, loop, events) { - if (loop && this.duration != 0) { + apply: function (skeleton, lastTime, time, loop, events) + { + if (loop && this.duration != 0) + { time %= this.duration; lastTime %= this.duration; } @@ -333,8 +371,10 @@ for (var i = 0, n = timelines.length; i < n; i++) timelines[i].apply(skeleton, lastTime, time, events, 1); }, - mix: function (skeleton, lastTime, time, loop, events, alpha) { - if (loop && this.duration != 0) { + mix: function (skeleton, lastTime, time, loop, events, alpha) + { + if (loop && this.duration != 0) + { time %= this.duration; lastTime %= this.duration; } @@ -343,12 +383,14 @@ timelines[i].apply(skeleton, lastTime, time, events, alpha); } }; -spine.Animation.binarySearch = function (values, target, step) { +spine.Animation.binarySearch = function (values, target, step) +{ var low = 0; var high = Math.floor(values.length / step) - 2; if (!high) return step; var current = high >>> 1; - while (true) { + while (true) + { if (values[(current + 1) * step] <= target) low = current + 1; else @@ -357,12 +399,14 @@ current = (low + high) >>> 1; } }; -spine.Animation.binarySearch1 = function (values, target) { +spine.Animation.binarySearch1 = function (values, target) +{ var low = 0; var high = values.length - 2; if (!high) return 1; var current = high >>> 1; - while (true) { + while (true) + { if (values[current + 1] <= target) low = current + 1; else @@ -371,27 +415,32 @@ current = (low + high) >>> 1; } }; -spine.Animation.linearSearch = function (values, target, step) { +spine.Animation.linearSearch = function (values, target, step) +{ for (var i = 0, last = values.length - step; i <= last; i += step) if (values[i] > target) return i; return -1; }; -spine.Curves = function (frameCount) { +spine.Curves = function (frameCount) +{ this.curves = []; // type, x, y, ... //this.curves.length = (frameCount - 1) * 19/*BEZIER_SIZE*/; }; spine.Curves.prototype = { - setLinear: function (frameIndex) { + setLinear: function (frameIndex) + { this.curves[frameIndex * 19/*BEZIER_SIZE*/] = 0/*LINEAR*/; }, - setStepped: function (frameIndex) { + setStepped: function (frameIndex) + { this.curves[frameIndex * 19/*BEZIER_SIZE*/] = 1/*STEPPED*/; }, /** Sets the control handle positions for an interpolation bezier curve used to transition from this keyframe to the next. * cx1 and cx2 are from 0 to 1, representing the percent of time between the two keyframes. cy1 and cy2 are the percent of * the difference between the keyframe's values. */ - setCurve: function (frameIndex, cx1, cy1, cx2, cy2) { + setCurve: function (frameIndex, cx1, cy1, cx2, cy2) + { var subdiv1 = 1 / 10/*BEZIER_SEGMENTS*/, subdiv2 = subdiv1 * subdiv1, subdiv3 = subdiv2 * subdiv1; var pre1 = 3 * subdiv1, pre2 = 3 * subdiv2, pre4 = 6 * subdiv2, pre5 = 6 * subdiv3; var tmp1x = -cx1 * 2 + cx2, tmp1y = -cy1 * 2 + cy2, tmp2x = (cx1 - cx2) * 3 + 1, tmp2y = (cy1 - cy2) * 3 + 1; @@ -404,7 +453,8 @@ curves[i++] = 2/*BEZIER*/; var x = dfx, y = dfy; - for (var n = i + 19/*BEZIER_SIZE*/ - 1; i < n; i += 2) { + for (var n = i + 19/*BEZIER_SIZE*/ - 1; i < n; i += 2) + { curves[i] = x; curves[i + 1] = y; dfx += ddfx; @@ -415,7 +465,8 @@ y += dfy; } }, - getCurvePercent: function (frameIndex, percent) { + getCurvePercent: function (frameIndex, percent) + { percent = percent < 0 ? 0 : (percent > 1 ? 1 : percent); var curves = this.curves; var i = frameIndex * 19/*BEZIER_SIZE*/; @@ -424,11 +475,14 @@ if (type == 1/*STEPPED*/) return 0; i++; var x = 0; - for (var start = i, n = i + 19/*BEZIER_SIZE*/ - 1; i < n; i += 2) { + for (var start = i, n = i + 19/*BEZIER_SIZE*/ - 1; i < n; i += 2) + { x = curves[i]; - if (x >= percent) { + if (x >= percent) + { var prevX, prevY; - if (i == start) { + if (i == start) + { prevX = 0; prevY = 0; } else { @@ -443,28 +497,33 @@ } }; -spine.RotateTimeline = function (frameCount) { +spine.RotateTimeline = function (frameCount) +{ this.curves = new spine.Curves(frameCount); this.frames = []; // time, angle, ... this.frames.length = frameCount * 2; }; spine.RotateTimeline.prototype = { boneIndex: 0, - getFrameCount: function () { + getFrameCount: function () + { return this.frames.length / 2; }, - setFrame: function (frameIndex, time, angle) { + setFrame: function (frameIndex, time, angle) + { frameIndex *= 2; this.frames[frameIndex] = time; this.frames[frameIndex + 1] = angle; }, - apply: function (skeleton, lastTime, time, firedEvents, alpha) { + apply: function (skeleton, lastTime, time, firedEvents, alpha) + { var frames = this.frames; if (time < frames[0]) return; // Time is before first frame. var bone = skeleton.bones[this.boneIndex]; - if (time >= frames[frames.length - 2]) { // Time is after last frame. + if (time >= frames[frames.length - 2]) + { // Time is after last frame. var amount = bone.data.rotation + frames[frames.length - 1] - bone.rotation; while (amount > 180) amount -= 360; @@ -495,29 +554,34 @@ } }; -spine.TranslateTimeline = function (frameCount) { +spine.TranslateTimeline = function (frameCount) +{ this.curves = new spine.Curves(frameCount); this.frames = []; // time, x, y, ... this.frames.length = frameCount * 3; }; spine.TranslateTimeline.prototype = { boneIndex: 0, - getFrameCount: function () { + getFrameCount: function () + { return this.frames.length / 3; }, - setFrame: function (frameIndex, time, x, y) { + setFrame: function (frameIndex, time, x, y) + { frameIndex *= 3; this.frames[frameIndex] = time; this.frames[frameIndex + 1] = x; this.frames[frameIndex + 2] = y; }, - apply: function (skeleton, lastTime, time, firedEvents, alpha) { + apply: function (skeleton, lastTime, time, firedEvents, alpha) + { var frames = this.frames; if (time < frames[0]) return; // Time is before first frame. var bone = skeleton.bones[this.boneIndex]; - if (time >= frames[frames.length - 3]) { // Time is after last frame. + if (time >= frames[frames.length - 3]) + { // Time is after last frame. bone.x += (bone.data.x + frames[frames.length - 2] - bone.x) * alpha; bone.y += (bone.data.y + frames[frames.length - 1] - bone.y) * alpha; return; @@ -536,29 +600,34 @@ } }; -spine.ScaleTimeline = function (frameCount) { +spine.ScaleTimeline = function (frameCount) +{ this.curves = new spine.Curves(frameCount); this.frames = []; // time, x, y, ... this.frames.length = frameCount * 3; }; spine.ScaleTimeline.prototype = { boneIndex: 0, - getFrameCount: function () { + getFrameCount: function () + { return this.frames.length / 3; }, - setFrame: function (frameIndex, time, x, y) { + setFrame: function (frameIndex, time, x, y) + { frameIndex *= 3; this.frames[frameIndex] = time; this.frames[frameIndex + 1] = x; this.frames[frameIndex + 2] = y; }, - apply: function (skeleton, lastTime, time, firedEvents, alpha) { + apply: function (skeleton, lastTime, time, firedEvents, alpha) + { var frames = this.frames; if (time < frames[0]) return; // Time is before first frame. var bone = skeleton.bones[this.boneIndex]; - if (time >= frames[frames.length - 3]) { // Time is after last frame. + if (time >= frames[frames.length - 3]) + { // Time is after last frame. bone.scaleX += (bone.data.scaleX * frames[frames.length - 2] - bone.scaleX) * alpha; bone.scaleY += (bone.data.scaleY * frames[frames.length - 1] - bone.scaleY) * alpha; return; @@ -577,17 +646,20 @@ } }; -spine.ColorTimeline = function (frameCount) { +spine.ColorTimeline = function (frameCount) +{ this.curves = new spine.Curves(frameCount); this.frames = []; // time, r, g, b, a, ... this.frames.length = frameCount * 5; }; spine.ColorTimeline.prototype = { slotIndex: 0, - getFrameCount: function () { + getFrameCount: function () + { return this.frames.length / 5; }, - setFrame: function (frameIndex, time, r, g, b, a) { + setFrame: function (frameIndex, time, r, g, b, a) + { frameIndex *= 5; this.frames[frameIndex] = time; this.frames[frameIndex + 1] = r; @@ -595,12 +667,14 @@ this.frames[frameIndex + 3] = b; this.frames[frameIndex + 4] = a; }, - apply: function (skeleton, lastTime, time, firedEvents, alpha) { + apply: function (skeleton, lastTime, time, firedEvents, alpha) + { var frames = this.frames; if (time < frames[0]) return; // Time is before first frame. var r, g, b, a; - if (time >= frames[frames.length - 5]) { + if (time >= frames[frames.length - 5]) + { // Time is after last frame. var i = frames.length - 1; r = frames[i - 3]; @@ -624,7 +698,8 @@ a = prevFrameA + (frames[frameIndex + 4/*FRAME_A*/] - prevFrameA) * percent; } var slot = skeleton.slots[this.slotIndex]; - if (alpha < 1) { + if (alpha < 1) + { slot.r += (r - slot.r) * alpha; slot.g += (g - slot.g) * alpha; slot.b += (b - slot.b) * alpha; @@ -638,7 +713,8 @@ } }; -spine.AttachmentTimeline = function (frameCount) { +spine.AttachmentTimeline = function (frameCount) +{ this.curves = new spine.Curves(frameCount); this.frames = []; // time, ... this.frames.length = frameCount; @@ -647,16 +723,20 @@ }; spine.AttachmentTimeline.prototype = { slotIndex: 0, - getFrameCount: function () { + getFrameCount: function () + { return this.frames.length; }, - setFrame: function (frameIndex, time, attachmentName) { + setFrame: function (frameIndex, time, attachmentName) + { this.frames[frameIndex] = time; this.attachmentNames[frameIndex] = attachmentName; }, - apply: function (skeleton, lastTime, time, firedEvents, alpha) { + apply: function (skeleton, lastTime, time, firedEvents, alpha) + { var frames = this.frames; - if (time < frames[0]) { + if (time < frames[0]) + { if (lastTime > time) this.apply(skeleton, lastTime, Number.MAX_VALUE, null, 0); return; } else if (lastTime > time) // @@ -671,28 +751,33 @@ } }; -spine.EventTimeline = function (frameCount) { +spine.EventTimeline = function (frameCount) +{ this.frames = []; // time, ... this.frames.length = frameCount; this.events = []; this.events.length = frameCount; }; spine.EventTimeline.prototype = { - getFrameCount: function () { + getFrameCount: function () + { return this.frames.length; }, - setFrame: function (frameIndex, time, event) { + setFrame: function (frameIndex, time, event) + { this.frames[frameIndex] = time; this.events[frameIndex] = event; }, /** Fires events for frames > lastTime and <= time. */ - apply: function (skeleton, lastTime, time, firedEvents, alpha) { + apply: function (skeleton, lastTime, time, firedEvents, alpha) + { if (!firedEvents) return; var frames = this.frames; var frameCount = frames.length; - if (lastTime > time) { // Fire events after last time for looped animations. + if (lastTime > time) + { // Fire events after last time for looped animations. this.apply(skeleton, lastTime, Number.MAX_VALUE, firedEvents, alpha); lastTime = -1; } else if (lastTime >= frames[frameCount - 1]) // Last time is after last frame. @@ -702,10 +787,12 @@ var frameIndex; if (lastTime < frames[0]) frameIndex = 0; - else { + else + { frameIndex = spine.Animation.binarySearch1(frames, lastTime); var frame = frames[frameIndex]; - while (frameIndex > 0) { // Fire multiple events with the same frame. + while (frameIndex > 0) + { // Fire multiple events with the same frame. if (frames[frameIndex - 1] != frame) break; frameIndex--; } @@ -716,21 +803,25 @@ } }; -spine.DrawOrderTimeline = function (frameCount) { +spine.DrawOrderTimeline = function (frameCount) +{ this.frames = []; // time, ... this.frames.length = frameCount; this.drawOrders = []; this.drawOrders.length = frameCount; }; spine.DrawOrderTimeline.prototype = { - getFrameCount: function () { + getFrameCount: function () + { return this.frames.length; }, - setFrame: function (frameIndex, time, drawOrder) { + setFrame: function (frameIndex, time, drawOrder) + { this.frames[frameIndex] = time; this.drawOrders[frameIndex] = drawOrder; }, - apply: function (skeleton, lastTime, time, firedEvents, alpha) { + apply: function (skeleton, lastTime, time, firedEvents, alpha) + { var frames = this.frames; if (time < frames[0]) return; // Time is before first frame. @@ -743,7 +834,8 @@ var drawOrder = skeleton.drawOrder; var slots = skeleton.slots; var drawOrderToSetupIndex = this.drawOrders[frameIndex]; - if (!drawOrderToSetupIndex) { + if (!drawOrderToSetupIndex) + { for (var i = 0, n = slots.length; i < n; i++) drawOrder[i] = slots[i]; } else { @@ -754,7 +846,8 @@ } }; -spine.FfdTimeline = function (frameCount) { +spine.FfdTimeline = function (frameCount) +{ this.curves = new spine.Curves(frameCount); this.frames = []; this.frames.length = frameCount; @@ -764,14 +857,17 @@ spine.FfdTimeline.prototype = { slotIndex: 0, attachment: 0, - getFrameCount: function () { + getFrameCount: function () + { return this.frames.length; }, - setFrame: function (frameIndex, time, vertices) { + setFrame: function (frameIndex, time, vertices) + { this.frames[frameIndex] = time; this.frameVertices[frameIndex] = vertices; }, - apply: function (skeleton, lastTime, time, firedEvents, alpha) { + apply: function (skeleton, lastTime, time, firedEvents, alpha) + { var slot = skeleton.slots[this.slotIndex]; if (slot.attachment != this.attachment) return; @@ -785,9 +881,11 @@ if (vertices.length != vertexCount) alpha = 1; vertices.length = vertexCount; - if (time >= frames[frames.length - 1]) { // Time is after last frame. + if (time >= frames[frames.length - 1]) + { // Time is after last frame. var lastVertices = frameVertices[frames.length - 1]; - if (alpha < 1) { + if (alpha < 1) + { for (var i = 0; i < vertexCount; i++) vertices[i] += (lastVertices[i] - vertices[i]) * alpha; } else { @@ -806,13 +904,16 @@ var prevVertices = frameVertices[frameIndex - 1]; var nextVertices = frameVertices[frameIndex]; - if (alpha < 1) { - for (var i = 0; i < vertexCount; i++) { + if (alpha < 1) + { + for (var i = 0; i < vertexCount; i++) + { var prev = prevVertices[i]; vertices[i] += (prev + (nextVertices[i] - prev) * percent - vertices[i]) * alpha; } } else { - for (var i = 0; i < vertexCount; i++) { + for (var i = 0; i < vertexCount; i++) + { var prev = prevVertices[i]; vertices[i] = prev + (nextVertices[i] - prev) * percent; } @@ -820,29 +921,34 @@ } }; -spine.IkConstraintTimeline = function (frameCount) { +spine.IkConstraintTimeline = function (frameCount) +{ this.curves = new spine.Curves(frameCount); this.frames = []; // time, mix, bendDirection, ... this.frames.length = frameCount * 3; }; spine.IkConstraintTimeline.prototype = { ikConstraintIndex: 0, - getFrameCount: function () { + getFrameCount: function () + { return this.frames.length / 3; }, - setFrame: function (frameIndex, time, mix, bendDirection) { + setFrame: function (frameIndex, time, mix, bendDirection) + { frameIndex *= 3; this.frames[frameIndex] = time; this.frames[frameIndex + 1] = mix; this.frames[frameIndex + 2] = bendDirection; }, - apply: function (skeleton, lastTime, time, firedEvents, alpha) { + apply: function (skeleton, lastTime, time, firedEvents, alpha) + { var frames = this.frames; if (time < frames[0]) return; // Time is before first frame. var ikConstraint = skeleton.ikConstraints[this.ikConstraintIndex]; - if (time >= frames[frames.length - 3]) { // Time is after last frame. + if (time >= frames[frames.length - 3]) + { // Time is after last frame. ikConstraint.mix += (frames[frames.length - 2] - ikConstraint.mix) * alpha; ikConstraint.bendDirection = frames[frames.length - 1]; return; @@ -861,24 +967,29 @@ } }; -spine.FlipXTimeline = function (frameCount) { +spine.FlipXTimeline = function (frameCount) +{ this.curves = new spine.Curves(frameCount); this.frames = []; // time, flip, ... this.frames.length = frameCount * 2; }; spine.FlipXTimeline.prototype = { boneIndex: 0, - getFrameCount: function () { + getFrameCount: function () + { return this.frames.length / 2; }, - setFrame: function (frameIndex, time, flip) { + setFrame: function (frameIndex, time, flip) + { frameIndex *= 2; this.frames[frameIndex] = time; this.frames[frameIndex + 1] = flip ? 1 : 0; }, - apply: function (skeleton, lastTime, time, firedEvents, alpha) { + apply: function (skeleton, lastTime, time, firedEvents, alpha) + { var frames = this.frames; - if (time < frames[0]) { + if (time < frames[0]) + { if (lastTime > time) this.apply(skeleton, lastTime, Number.MAX_VALUE, null, 0); return; } else if (lastTime > time) // @@ -889,24 +1000,29 @@ } }; -spine.FlipYTimeline = function (frameCount) { +spine.FlipYTimeline = function (frameCount) +{ this.curves = new spine.Curves(frameCount); this.frames = []; // time, flip, ... this.frames.length = frameCount * 2; }; spine.FlipYTimeline.prototype = { boneIndex: 0, - getFrameCount: function () { + getFrameCount: function () + { return this.frames.length / 2; }, - setFrame: function (frameIndex, time, flip) { + setFrame: function (frameIndex, time, flip) + { frameIndex *= 2; this.frames[frameIndex] = time; this.frames[frameIndex + 1] = flip ? 1 : 0; }, - apply: function (skeleton, lastTime, time, firedEvents, alpha) { + apply: function (skeleton, lastTime, time, firedEvents, alpha) + { var frames = this.frames; - if (time < frames[0]) { + if (time < frames[0]) + { if (lastTime > time) this.apply(skeleton, lastTime, Number.MAX_VALUE, null, 0); return; } else if (lastTime > time) // @@ -917,7 +1033,8 @@ } }; -spine.SkeletonData = function () { +spine.SkeletonData = function () +{ this.bones = []; this.slots = []; this.skins = []; @@ -931,57 +1048,66 @@ width: 0, height: 0, version: null, hash: null, /** @return May be null. */ - findBone: function (boneName) { + findBone: function (boneName) + { var bones = this.bones; for (var i = 0, n = bones.length; i < n; i++) if (bones[i].name == boneName) return bones[i]; return null; }, /** @return -1 if the bone was not found. */ - findBoneIndex: function (boneName) { + findBoneIndex: function (boneName) + { var bones = this.bones; for (var i = 0, n = bones.length; i < n; i++) if (bones[i].name == boneName) return i; return -1; }, /** @return May be null. */ - findSlot: function (slotName) { + findSlot: function (slotName) + { var slots = this.slots; - for (var i = 0, n = slots.length; i < n; i++) { + for (var i = 0, n = slots.length; i < n; i++) + { if (slots[i].name == slotName) return slot[i]; } return null; }, /** @return -1 if the bone was not found. */ - findSlotIndex: function (slotName) { + findSlotIndex: function (slotName) + { var slots = this.slots; for (var i = 0, n = slots.length; i < n; i++) if (slots[i].name == slotName) return i; return -1; }, /** @return May be null. */ - findSkin: function (skinName) { + findSkin: function (skinName) + { var skins = this.skins; for (var i = 0, n = skins.length; i < n; i++) if (skins[i].name == skinName) return skins[i]; return null; }, /** @return May be null. */ - findEvent: function (eventName) { + findEvent: function (eventName) + { var events = this.events; for (var i = 0, n = events.length; i < n; i++) if (events[i].name == eventName) return events[i]; return null; }, /** @return May be null. */ - findAnimation: function (animationName) { + findAnimation: function (animationName) + { var animations = this.animations; for (var i = 0, n = animations.length; i < n; i++) if (animations[i].name == animationName) return animations[i]; return null; }, /** @return May be null. */ - findIkConstraint: function (ikConstraintName) { + findIkConstraint: function (ikConstraintName) + { var ikConstraints = this.ikConstraints; for (var i = 0, n = ikConstraints.length; i < n; i++) if (ikConstraints[i].name == ikConstraintName) return ikConstraints[i]; @@ -989,11 +1115,13 @@ } }; -spine.Skeleton = function (skeletonData) { +spine.Skeleton = function (skeletonData) +{ this.data = skeletonData; this.bones = []; - for (var i = 0, n = skeletonData.bones.length; i < n; i++) { + for (var i = 0, n = skeletonData.bones.length; i < n; i++) + { var boneData = skeletonData.bones[i]; var parent = !boneData.parent ? null : this.bones[skeletonData.bones.indexOf(boneData.parent)]; this.bones.push(new spine.Bone(boneData, this, parent)); @@ -1001,7 +1129,8 @@ this.slots = []; this.drawOrder = []; - for (var i = 0, n = skeletonData.slots.length; i < n; i++) { + for (var i = 0, n = skeletonData.slots.length; i < n; i++) + { var slotData = skeletonData.slots[i]; var bone = this.bones[skeletonData.bones.indexOf(slotData.boneData)]; var slot = new spine.Slot(slotData, bone); @@ -1023,7 +1152,8 @@ time: 0, flipX: false, flipY: false, /** Caches information about bones and IK constraints. Must be called if bones or IK constraints are added or removed. */ - updateCache: function () { + updateCache: function () + { var ikConstraints = this.ikConstraints; var ikConstraintsCount = ikConstraints.length; @@ -1039,16 +1169,20 @@ var bones = this.bones; outer: - for (var i = 0, n = bones.length; i < n; i++) { + for (var i = 0, n = bones.length; i < n; i++) + { var bone = bones[i]; var current = bone; do { - for (var ii = 0; ii < ikConstraintsCount; ii++) { + for (var ii = 0; ii < ikConstraintsCount; ii++) + { var ikConstraint = ikConstraints[ii]; var parent = ikConstraint.bones[0]; var child= ikConstraint.bones[ikConstraint.bones.length - 1]; - while (true) { - if (current == child) { + while (true) + { + if (current == child) + { boneCache[ii].push(bone); boneCache[ii + 1].push(bone); continue outer; @@ -1063,14 +1197,17 @@ } }, /** Updates the world transform for each bone. */ - updateWorldTransform: function () { + updateWorldTransform: function () + { var bones = this.bones; - for (var i = 0, n = bones.length; i < n; i++) { + for (var i = 0, n = bones.length; i < n; i++) + { var bone = bones[i]; bone.rotationIK = bone.rotation; } var i = 0, last = this.boneCache.length - 1; - while (true) { + while (true) + { var cacheBones = this.boneCache[i]; for (var ii = 0, nn = cacheBones.length; ii < nn; ii++) cacheBones[ii].updateWorldTransform(); @@ -1080,63 +1217,74 @@ } }, /** Sets the bones and slots to their setup pose values. */ - setToSetupPose: function () { + setToSetupPose: function () + { this.setBonesToSetupPose(); this.setSlotsToSetupPose(); }, - setBonesToSetupPose: function () { + setBonesToSetupPose: function () + { var bones = this.bones; for (var i = 0, n = bones.length; i < n; i++) bones[i].setToSetupPose(); var ikConstraints = this.ikConstraints; - for (var i = 0, n = ikConstraints.length; i < n; i++) { + for (var i = 0, n = ikConstraints.length; i < n; i++) + { var ikConstraint = ikConstraints[i]; ikConstraint.bendDirection = ikConstraint.data.bendDirection; ikConstraint.mix = ikConstraint.data.mix; } }, - setSlotsToSetupPose: function () { + setSlotsToSetupPose: function () + { var slots = this.slots; var drawOrder = this.drawOrder; - for (var i = 0, n = slots.length; i < n; i++) { + for (var i = 0, n = slots.length; i < n; i++) + { drawOrder[i] = slots[i]; slots[i].setToSetupPose(i); } }, /** @return May return null. */ - getRootBone: function () { + getRootBone: function () + { return this.bones.length ? this.bones[0] : null; }, /** @return May be null. */ - findBone: function (boneName) { + findBone: function (boneName) + { var bones = this.bones; for (var i = 0, n = bones.length; i < n; i++) if (bones[i].data.name == boneName) return bones[i]; return null; }, /** @return -1 if the bone was not found. */ - findBoneIndex: function (boneName) { + findBoneIndex: function (boneName) + { var bones = this.bones; for (var i = 0, n = bones.length; i < n; i++) if (bones[i].data.name == boneName) return i; return -1; }, /** @return May be null. */ - findSlot: function (slotName) { + findSlot: function (slotName) + { var slots = this.slots; for (var i = 0, n = slots.length; i < n; i++) if (slots[i].data.name == slotName) return slots[i]; return null; }, /** @return -1 if the bone was not found. */ - findSlotIndex: function (slotName) { + findSlotIndex: function (slotName) + { var slots = this.slots; for (var i = 0, n = slots.length; i < n; i++) if (slots[i].data.name == slotName) return i; return -1; }, - setSkinByName: function (skinName) { + setSkinByName: function (skinName) + { var skin = this.data.findSkin(skinName); if (!skin) throw "Skin not found: " + skinName; this.setSkin(skin); @@ -1145,16 +1293,21 @@ * Attachments from the new skin are attached if the corresponding attachment from the old skin was attached. If there was * no old skin, each slot's setup mode attachment is attached from the new skin. * @param newSkin May be null. */ - setSkin: function (newSkin) { - if (newSkin) { + setSkin: function (newSkin) + { + if (newSkin) + { if (this.skin) newSkin._attachAll(this, this.skin); - else { + else + { var slots = this.slots; - for (var i = 0, n = slots.length; i < n; i++) { + for (var i = 0, n = slots.length; i < n; i++) + { var slot = slots[i]; var name = slot.data.attachmentName; - if (name) { + if (name) + { var attachment = newSkin.getAttachment(i, name); if (attachment) slot.setAttachment(attachment); } @@ -1164,12 +1317,15 @@ this.skin = newSkin; }, /** @return May be null. */ - getAttachmentBySlotName: function (slotName, attachmentName) { + getAttachmentBySlotName: function (slotName, attachmentName) + { return this.getAttachmentBySlotIndex(this.data.findSlotIndex(slotName), attachmentName); }, /** @return May be null. */ - getAttachmentBySlotIndex: function (slotIndex, attachmentName) { - if (this.skin) { + getAttachmentBySlotIndex: function (slotIndex, attachmentName) + { + if (this.skin) + { var attachment = this.skin.getAttachment(slotIndex, attachmentName); if (attachment) return attachment; } @@ -1177,13 +1333,17 @@ return null; }, /** @param attachmentName May be null. */ - setAttachment: function (slotName, attachmentName) { + setAttachment: function (slotName, attachmentName) + { var slots = this.slots; - for (var i = 0, n = slots.length; i < n; i++) { + for (var i = 0, n = slots.length; i < n; i++) + { var slot = slots[i]; - if (slot.data.name == slotName) { + if (slot.data.name == slotName) + { var attachment = null; - if (attachmentName) { + if (attachmentName) + { attachment = this.getAttachmentBySlotIndex(i, attachmentName); if (!attachment) throw "Attachment not found: " + attachmentName + ", for slot: " + slotName; } @@ -1194,18 +1354,21 @@ throw "Slot not found: " + slotName; }, /** @return May be null. */ - findIkConstraint: function (ikConstraintName) { + findIkConstraint: function (ikConstraintName) + { var ikConstraints = this.ikConstraints; for (var i = 0, n = ikConstraints.length; i < n; i++) if (ikConstraints[i].data.name == ikConstraintName) return ikConstraints[i]; return null; }, - update: function (delta) { + update: function (delta) + { this.time += delta; } }; -spine.EventData = function (name) { +spine.EventData = function (name) +{ this.name = name; }; spine.EventData.prototype = { @@ -1214,7 +1377,8 @@ stringValue: null }; -spine.Event = function (data) { +spine.Event = function (data) +{ this.data = data; }; spine.Event.prototype = { @@ -1230,7 +1394,8 @@ skinnedmesh: 3 }; -spine.RegionAttachment = function (name) { +spine.RegionAttachment = function (name) +{ this.name = name; this.offset = []; this.offset.length = 8; @@ -1249,9 +1414,11 @@ regionOffsetX: 0, regionOffsetY: 0, regionWidth: 0, regionHeight: 0, regionOriginalWidth: 0, regionOriginalHeight: 0, - setUVs: function (u, v, u2, v2, rotate) { + setUVs: function (u, v, u2, v2, rotate) + { var uvs = this.uvs; - if (rotate) { + if (rotate) + { uvs[2/*X2*/] = u; uvs[3/*Y2*/] = v2; uvs[4/*X3*/] = u; @@ -1271,7 +1438,8 @@ uvs[7/*Y4*/] = v2; } }, - updateOffset: function () { + updateOffset: function () + { var regionScaleX = this.width / this.regionOriginalWidth * this.scaleX; var regionScaleY = this.height / this.regionOriginalHeight * this.scaleY; var localX = -this.width / 2 * this.scaleX + this.regionOffsetX * regionScaleX; @@ -1299,7 +1467,8 @@ offset[6/*X4*/] = localX2Cos - localYSin; offset[7/*Y4*/] = localYCos + localX2Sin; }, - computeVertices: function (x, y, bone, vertices) { + computeVertices: function (x, y, bone, vertices) + { x += bone.worldX; y += bone.worldY; var m00 = bone.m00, m01 = bone.m01, m10 = bone.m10, m11 = bone.m11; @@ -1315,7 +1484,8 @@ } }; -spine.MeshAttachment = function (name) { +spine.MeshAttachment = function (name) +{ this.name = name; }; spine.MeshAttachment.prototype = { @@ -1334,25 +1504,31 @@ regionOriginalWidth: 0, regionOriginalHeight: 0, edges: null, width: 0, height: 0, - updateUVs: function () { + updateUVs: function () + { var width = this.regionU2 - this.regionU, height = this.regionV2 - this.regionV; var n = this.regionUVs.length; - if (!this.uvs || this.uvs.length != n) { + if (!this.uvs || this.uvs.length != n) + { this.uvs = new spine.Float32Array(n); } - if (this.regionRotate) { - for (var i = 0; i < n; i += 2) { + if (this.regionRotate) + { + for (var i = 0; i < n; i += 2) + { this.uvs[i] = this.regionU + this.regionUVs[i + 1] * width; this.uvs[i + 1] = this.regionV + height - this.regionUVs[i] * height; } } else { - for (var i = 0; i < n; i += 2) { + for (var i = 0; i < n; i += 2) + { this.uvs[i] = this.regionU + this.regionUVs[i] * width; this.uvs[i + 1] = this.regionV + this.regionUVs[i + 1] * height; } } }, - computeWorldVertices: function (x, y, slot, worldVertices) { + computeWorldVertices: function (x, y, slot, worldVertices) + { var bone = slot.bone; x += bone.worldX; y += bone.worldY; @@ -1360,7 +1536,8 @@ var vertices = this.vertices; var verticesCount = vertices.length; if (slot.attachmentVertices.length == verticesCount) vertices = slot.attachmentVertices; - for (var i = 0; i < verticesCount; i += 2) { + for (var i = 0; i < verticesCount; i += 2) + { var vx = vertices[i]; var vy = vertices[i + 1]; worldVertices[i] = vx * m00 + vy * m01 + x; @@ -1369,7 +1546,8 @@ } }; -spine.SkinnedMeshAttachment = function (name) { +spine.SkinnedMeshAttachment = function (name) +{ this.name = name; }; spine.SkinnedMeshAttachment.prototype = { @@ -1389,37 +1567,46 @@ regionOriginalWidth: 0, regionOriginalHeight: 0, edges: null, width: 0, height: 0, - updateUVs: function (u, v, u2, v2, rotate) { + updateUVs: function (u, v, u2, v2, rotate) + { var width = this.regionU2 - this.regionU, height = this.regionV2 - this.regionV; var n = this.regionUVs.length; - if (!this.uvs || this.uvs.length != n) { + if (!this.uvs || this.uvs.length != n) + { this.uvs = new spine.Float32Array(n); } - if (this.regionRotate) { - for (var i = 0; i < n; i += 2) { + if (this.regionRotate) + { + for (var i = 0; i < n; i += 2) + { this.uvs[i] = this.regionU + this.regionUVs[i + 1] * width; this.uvs[i + 1] = this.regionV + height - this.regionUVs[i] * height; } } else { - for (var i = 0; i < n; i += 2) { + for (var i = 0; i < n; i += 2) + { this.uvs[i] = this.regionU + this.regionUVs[i] * width; this.uvs[i + 1] = this.regionV + this.regionUVs[i + 1] * height; } } }, - computeWorldVertices: function (x, y, slot, worldVertices) { + computeWorldVertices: function (x, y, slot, worldVertices) + { var skeletonBones = slot.bone.skeleton.bones; var weights = this.weights; var bones = this.bones; var w = 0, v = 0, b = 0, f = 0, n = bones.length, nn; var wx, wy, bone, vx, vy, weight; - if (!slot.attachmentVertices.length) { - for (; v < n; w += 2) { + if (!slot.attachmentVertices.length) + { + for (; v < n; w += 2) + { wx = 0; wy = 0; nn = bones[v++] + v; - for (; v < nn; v++, b += 3) { + for (; v < nn; v++, b += 3) + { bone = skeletonBones[bones[v]]; vx = weights[b]; vy = weights[b + 1]; @@ -1432,11 +1619,13 @@ } } else { var ffd = slot.attachmentVertices; - for (; v < n; w += 2) { + for (; v < n; w += 2) + { wx = 0; wy = 0; nn = bones[v++] + v; - for (; v < nn; v++, b += 3, f += 2) { + for (; v < nn; v++, b += 3, f += 2) + { bone = skeletonBones[bones[v]]; vx = weights[b] + ffd[f]; vy = weights[b + 1] + ffd[f + 1]; @@ -1451,18 +1640,21 @@ } }; -spine.BoundingBoxAttachment = function (name) { +spine.BoundingBoxAttachment = function (name) +{ this.name = name; this.vertices = []; }; spine.BoundingBoxAttachment.prototype = { type: spine.AttachmentType.boundingbox, - computeWorldVertices: function (x, y, bone, worldVertices) { + computeWorldVertices: function (x, y, bone, worldVertices) + { x += bone.worldX; y += bone.worldY; var m00 = bone.m00, m01 = bone.m01, m10 = bone.m10, m11 = bone.m11; var vertices = this.vertices; - for (var i = 0, n = vertices.length; i < n; i += 2) { + for (var i = 0, n = vertices.length; i < n; i += 2) + { var px = vertices[i]; var py = vertices[i + 1]; worldVertices[i] = px * m00 + py * m01 + x; @@ -1471,29 +1663,34 @@ } }; -spine.AnimationStateData = function (skeletonData) { +spine.AnimationStateData = function (skeletonData) +{ this.skeletonData = skeletonData; this.animationToMixTime = {}; }; spine.AnimationStateData.prototype = { defaultMix: 0, - setMixByName: function (fromName, toName, duration) { + setMixByName: function (fromName, toName, duration) + { var from = this.skeletonData.findAnimation(fromName); if (!from) throw "Animation not found: " + fromName; var to = this.skeletonData.findAnimation(toName); if (!to) throw "Animation not found: " + toName; this.setMix(from, to, duration); }, - setMix: function (from, to, duration) { + setMix: function (from, to, duration) + { this.animationToMixTime[from.name + ":" + to.name] = duration; }, - getMix: function (from, to) { + getMix: function (from, to) + { var key = from.name + ":" + to.name; return this.animationToMixTime.hasOwnProperty(key) ? this.animationToMixTime[key] : this.defaultMix; } }; -spine.TrackEntry = function () {}; +spine.TrackEntry = function () +{}; spine.TrackEntry.prototype = { next: null, previous: null, animation: null, @@ -1504,7 +1701,8 @@ onStart: null, onEnd: null, onComplete: null, onEvent: null }; -spine.AnimationState = function (stateData) { +spine.AnimationState = function (stateData) +{ this.data = stateData; this.tracks = []; this.events = []; @@ -1515,21 +1713,25 @@ onComplete: null, onEvent: null, timeScale: 1, - update: function (delta) { + update: function (delta) + { delta *= this.timeScale; - for (var i = 0; i < this.tracks.length; i++) { + for (var i = 0; i < this.tracks.length; i++) + { var current = this.tracks[i]; if (!current) continue; current.time += delta * current.timeScale; - if (current.previous) { + if (current.previous) + { var previousDelta = delta * current.previous.timeScale; current.previous.time += previousDelta; current.mixTime += previousDelta; } var next = current.next; - if (next) { + if (next) + { next.time = current.lastTime - next.delay; if (next.time >= 0) this.setCurrent(i, next); } else { @@ -1538,8 +1740,10 @@ } } }, - apply: function (skeleton) { - for (var i = 0; i < this.tracks.length; i++) { + apply: function (skeleton) + { + for (var i = 0; i < this.tracks.length; i++) + { var current = this.tracks[i]; if (!current) continue; @@ -1552,7 +1756,8 @@ if (!loop && time > endTime) time = endTime; var previous = current.previous; - if (!previous) { + if (!previous) + { if (current.mix == 1) current.animation.apply(skeleton, current.lastTime, time, loop, this.events); else @@ -1563,21 +1768,24 @@ previous.animation.apply(skeleton, previousTime, previousTime, previous.loop, null); var alpha = current.mixTime / current.mixDuration * current.mix; - if (alpha >= 1) { + if (alpha >= 1) + { alpha = 1; current.previous = null; } current.animation.mix(skeleton, current.lastTime, time, loop, this.events, alpha); } - for (var ii = 0, nn = this.events.length; ii < nn; ii++) { + for (var ii = 0, nn = this.events.length; ii < nn; ii++) + { var event = this.events[ii]; if (current.onEvent) current.onEvent(i, event); if (this.onEvent) this.onEvent(i, event); } // Check if completed the animation or a loop iteration. - if (loop ? (lastTime % endTime > time % endTime) : (lastTime < endTime && time >= endTime)) { + if (loop ? (lastTime % endTime > time % endTime) : (lastTime < endTime && time >= endTime)) + { var count = Math.floor(time / endTime); if (current.onComplete) current.onComplete(i, count); if (this.onComplete) this.onComplete(i, count); @@ -1586,12 +1794,14 @@ current.lastTime = current.time; } }, - clearTracks: function () { + clearTracks: function () + { for (var i = 0, n = this.tracks.length; i < n; i++) this.clearTrack(i); this.tracks.length = 0; }, - clearTrack: function (trackIndex) { + clearTrack: function (trackIndex) + { if (trackIndex >= this.tracks.length) return; var current = this.tracks[trackIndex]; if (!current) return; @@ -1601,15 +1811,18 @@ this.tracks[trackIndex] = null; }, - _expandToIndex: function (index) { + _expandToIndex: function (index) + { if (index < this.tracks.length) return this.tracks[index]; while (index >= this.tracks.length) this.tracks.push(null); return null; }, - setCurrent: function (index, entry) { + setCurrent: function (index, entry) + { var current = this._expandToIndex(index); - if (current) { + if (current) + { var previous = current.previous; current.previous = null; @@ -1617,7 +1830,8 @@ if (this.onEnd) this.onEnd(index); entry.mixDuration = this.data.getMix(current.animation, entry.animation); - if (entry.mixDuration > 0) { + if (entry.mixDuration > 0) + { entry.mixTime = 0; // If a mix is in progress, mix from the closest animation. if (previous && current.mixTime / current.mixDuration < 0.5) @@ -1632,13 +1846,15 @@ if (entry.onStart) entry.onStart(index); if (this.onStart) this.onStart(index); }, - setAnimationByName: function (trackIndex, animationName, loop) { + setAnimationByName: function (trackIndex, animationName, loop) + { var animation = this.data.skeletonData.findAnimation(animationName); if (!animation) throw "Animation not found: " + animationName; return this.setAnimation(trackIndex, animation, loop); }, /** Set the current animation. Any queued animations are cleared. */ - setAnimation: function (trackIndex, animation, loop) { + setAnimation: function (trackIndex, animation, loop) + { var entry = new spine.TrackEntry(); entry.animation = animation; entry.loop = loop; @@ -1646,28 +1862,32 @@ this.setCurrent(trackIndex, entry); return entry; }, - addAnimationByName: function (trackIndex, animationName, loop, delay) { + addAnimationByName: function (trackIndex, animationName, loop, delay) + { var animation = this.data.skeletonData.findAnimation(animationName); if (!animation) throw "Animation not found: " + animationName; return this.addAnimation(trackIndex, animation, loop, delay); }, /** Adds an animation to be played delay seconds after the current or last queued animation. * @param delay May be <= 0 to use duration of previous animation minus any mix duration plus the negative delay. */ - addAnimation: function (trackIndex, animation, loop, delay) { + addAnimation: function (trackIndex, animation, loop, delay) + { var entry = new spine.TrackEntry(); entry.animation = animation; entry.loop = loop; entry.endTime = animation.duration; var last = this._expandToIndex(trackIndex); - if (last) { + if (last) + { while (last.next) last = last.next; last.next = entry; } else this.tracks[trackIndex] = entry; - if (delay <= 0) { + if (delay <= 0) + { if (last) delay += last.endTime - this.data.getMix(last.animation, animation); else @@ -1678,24 +1898,28 @@ return entry; }, /** May be null. */ - getCurrent: function (trackIndex) { + getCurrent: function (trackIndex) + { if (trackIndex >= this.tracks.length) return null; return this.tracks[trackIndex]; } }; -spine.SkeletonJson = function (attachmentLoader) { +spine.SkeletonJson = function (attachmentLoader) +{ this.attachmentLoader = attachmentLoader; }; spine.SkeletonJson.prototype = { scale: 1, - readSkeletonData: function (root, name) { + readSkeletonData: function (root, name) + { var skeletonData = new spine.SkeletonData(); skeletonData.name = name; // Skeleton. var skeletonMap = root["skeleton"]; - if (skeletonMap) { + if (skeletonMap) + { skeletonData.hash = skeletonMap["hash"]; skeletonData.version = skeletonMap["spine"]; skeletonData.width = skeletonMap["width"] || 0; @@ -1704,10 +1928,12 @@ // Bones. var bones = root["bones"]; - for (var i = 0, n = bones.length; i < n; i++) { + for (var i = 0, n = bones.length; i < n; i++) + { var boneMap = bones[i]; var parent = null; - if (boneMap["parent"]) { + if (boneMap["parent"]) + { parent = skeletonData.findBone(boneMap["parent"]); if (!parent) throw "Parent bone not found: " + boneMap["parent"]; } @@ -1725,13 +1951,16 @@ // IK constraints. var ik = root["ik"]; - if (ik) { - for (var i = 0, n = ik.length; i < n; i++) { + if (ik) + { + for (var i = 0, n = ik.length; i < n; i++) + { var ikMap = ik[i]; var ikConstraintData = new spine.IkConstraintData(ikMap["name"]); var bones = ikMap["bones"]; - for (var ii = 0, nn = bones.length; ii < nn; ii++) { + for (var ii = 0, nn = bones.length; ii < nn; ii++) + { var bone = skeletonData.findBone(bones[ii]); if (!bone) throw "IK bone not found: " + bones[ii]; ikConstraintData.bones.push(bone); @@ -1749,14 +1978,16 @@ // Slots. var slots = root["slots"]; - for (var i = 0, n = slots.length; i < n; i++) { + for (var i = 0, n = slots.length; i < n; i++) + { var slotMap = slots[i]; var boneData = skeletonData.findBone(slotMap["bone"]); if (!boneData) throw "Slot bone not found: " + slotMap["bone"]; var slotData = new spine.SlotData(slotMap["name"], boneData); var color = slotMap["color"]; - if (color) { + if (color) + { slotData.r = this.toColor(color, 0); slotData.g = this.toColor(color, 1); slotData.b = this.toColor(color, 2); @@ -1771,15 +2002,18 @@ // Skins. var skins = root["skins"]; - for (var skinName in skins) { + for (var skinName in skins) + { if (!skins.hasOwnProperty(skinName)) continue; var skinMap = skins[skinName]; var skin = new spine.Skin(skinName); - for (var slotName in skinMap) { + for (var slotName in skinMap) + { if (!skinMap.hasOwnProperty(slotName)) continue; var slotIndex = skeletonData.findSlotIndex(slotName); var slotEntry = skinMap[slotName]; - for (var attachmentName in slotEntry) { + for (var attachmentName in slotEntry) + { if (!slotEntry.hasOwnProperty(attachmentName)) continue; var attachment = this.readAttachment(skin, attachmentName, slotEntry[attachmentName]); if (attachment) skin.addAttachment(slotIndex, attachmentName, attachment); @@ -1791,7 +2025,8 @@ // Events. var events = root["events"]; - for (var eventName in events) { + for (var eventName in events) + { if (!events.hasOwnProperty(eventName)) continue; var eventMap = events[eventName]; var eventData = new spine.EventData(eventName); @@ -1803,21 +2038,24 @@ // Animations. var animations = root["animations"]; - for (var animationName in animations) { + for (var animationName in animations) + { if (!animations.hasOwnProperty(animationName)) continue; this.readAnimation(animationName, animations[animationName], skeletonData); } return skeletonData; }, - readAttachment: function (skin, name, map) { + readAttachment: function (skin, name, map) + { name = map["name"] || name; var type = spine.AttachmentType[map["type"] || "region"]; var path = map["path"] || name; var scale = this.scale; - if (type == spine.AttachmentType.region) { + if (type == spine.AttachmentType.region) + { var region = this.attachmentLoader.newRegionAttachment(skin, name, path); if (!region) return null; region.path = path; @@ -1830,7 +2068,8 @@ region.height = (map["height"] || 0) * scale; var color = map["color"]; - if (color) { + if (color) + { region.r = this.toColor(color, 0); region.g = this.toColor(color, 1); region.b = this.toColor(color, 2); @@ -1839,7 +2078,8 @@ region.updateOffset(); return region; - } else if (type == spine.AttachmentType.mesh) { + } else if (type == spine.AttachmentType.mesh) + { var mesh = this.attachmentLoader.newMeshAttachment(skin, name, path); if (!mesh) return null; mesh.path = path; @@ -1849,7 +2089,8 @@ mesh.updateUVs(); color = map["color"]; - if (color) { + if (color) + { mesh.r = this.toColor(color, 0); mesh.g = this.toColor(color, 1); mesh.b = this.toColor(color, 2); @@ -1861,7 +2102,8 @@ mesh.width = (map["width"] || 0) * scale; mesh.height = (map["height"] || 0) * scale; return mesh; - } else if (type == spine.AttachmentType.skinnedmesh) { + } else if (type == spine.AttachmentType.skinnedmesh) + { var mesh = this.attachmentLoader.newSkinnedMeshAttachment(skin, name, path); if (!mesh) return null; mesh.path = path; @@ -1870,10 +2112,12 @@ var vertices = this.getFloatArray(map, "vertices", 1); var weights = []; var bones = []; - for (var i = 0, n = vertices.length; i < n; ) { + for (var i = 0, n = vertices.length; i < n; ) + { var boneCount = vertices[i++] | 0; bones[bones.length] = boneCount; - for (var nn = i + boneCount * 4; i < nn; ) { + for (var nn = i + boneCount * 4; i < nn; ) + { bones[bones.length] = vertices[i]; weights[weights.length] = vertices[i + 1] * scale; weights[weights.length] = vertices[i + 2] * scale; @@ -1888,7 +2132,8 @@ mesh.updateUVs(); color = map["color"]; - if (color) { + if (color) + { mesh.r = this.toColor(color, 0); mesh.g = this.toColor(color, 1); mesh.b = this.toColor(color, 2); @@ -1900,7 +2145,8 @@ mesh.width = (map["width"] || 0) * scale; mesh.height = (map["height"] || 0) * scale; return mesh; - } else if (type == spine.AttachmentType.boundingbox) { + } else if (type == spine.AttachmentType.boundingbox) + { var attachment = this.attachmentLoader.newBoundingBoxAttachment(skin, name); var vertices = map["vertices"]; for (var i = 0, n = vertices.length; i < n; i++) @@ -1909,25 +2155,30 @@ } throw "Unknown attachment type: " + type; }, - readAnimation: function (name, map, skeletonData) { + readAnimation: function (name, map, skeletonData) + { var timelines = []; var duration = 0; var slots = map["slots"]; - for (var slotName in slots) { + for (var slotName in slots) + { if (!slots.hasOwnProperty(slotName)) continue; var slotMap = slots[slotName]; var slotIndex = skeletonData.findSlotIndex(slotName); - for (var timelineName in slotMap) { + for (var timelineName in slotMap) + { if (!slotMap.hasOwnProperty(timelineName)) continue; var values = slotMap[timelineName]; - if (timelineName == "color") { + if (timelineName == "color") + { var timeline = new spine.ColorTimeline(values.length); timeline.slotIndex = slotIndex; var frameIndex = 0; - for (var i = 0, n = values.length; i < n; i++) { + for (var i = 0, n = values.length; i < n; i++) + { var valueMap = values[i]; var color = valueMap["color"]; var r = this.toColor(color, 0); @@ -1941,12 +2192,14 @@ timelines.push(timeline); duration = Math.max(duration, timeline.frames[timeline.getFrameCount() * 5 - 5]); - } else if (timelineName == "attachment") { + } else if (timelineName == "attachment") + { var timeline = new spine.AttachmentTimeline(values.length); timeline.slotIndex = slotIndex; var frameIndex = 0; - for (var i = 0, n = values.length; i < n; i++) { + for (var i = 0, n = values.length; i < n; i++) + { var valueMap = values[i]; timeline.setFrame(frameIndex++, valueMap["time"], valueMap["name"]); } @@ -1959,21 +2212,25 @@ } var bones = map["bones"]; - for (var boneName in bones) { + for (var boneName in bones) + { if (!bones.hasOwnProperty(boneName)) continue; var boneIndex = skeletonData.findBoneIndex(boneName); if (boneIndex == -1) throw "Bone not found: " + boneName; var boneMap = bones[boneName]; - for (var timelineName in boneMap) { + for (var timelineName in boneMap) + { if (!boneMap.hasOwnProperty(timelineName)) continue; var values = boneMap[timelineName]; - if (timelineName == "rotate") { + if (timelineName == "rotate") + { var timeline = new spine.RotateTimeline(values.length); timeline.boneIndex = boneIndex; var frameIndex = 0; - for (var i = 0, n = values.length; i < n; i++) { + for (var i = 0, n = values.length; i < n; i++) + { var valueMap = values[i]; timeline.setFrame(frameIndex, valueMap["time"], valueMap["angle"]); this.readCurve(timeline, frameIndex, valueMap); @@ -1982,19 +2239,22 @@ timelines.push(timeline); duration = Math.max(duration, timeline.frames[timeline.getFrameCount() * 2 - 2]); - } else if (timelineName == "translate" || timelineName == "scale") { + } else if (timelineName == "translate" || timelineName == "scale") + { var timeline; var timelineScale = 1; if (timelineName == "scale") timeline = new spine.ScaleTimeline(values.length); - else { + else + { timeline = new spine.TranslateTimeline(values.length); timelineScale = this.scale; } timeline.boneIndex = boneIndex; var frameIndex = 0; - for (var i = 0, n = values.length; i < n; i++) { + for (var i = 0, n = values.length; i < n; i++) + { var valueMap = values[i]; var x = (valueMap["x"] || 0) * timelineScale; var y = (valueMap["y"] || 0) * timelineScale; @@ -2005,14 +2265,16 @@ timelines.push(timeline); duration = Math.max(duration, timeline.frames[timeline.getFrameCount() * 3 - 3]); - } else if (timelineName == "flipX" || timelineName == "flipY") { + } else if (timelineName == "flipX" || timelineName == "flipY") + { var x = timelineName == "flipX"; var timeline = x ? new spine.FlipXTimeline(values.length) : new spine.FlipYTimeline(values.length); timeline.boneIndex = boneIndex; var field = x ? "x" : "y"; var frameIndex = 0; - for (var i = 0, n = values.length; i < n; i++) { + for (var i = 0, n = values.length; i < n; i++) + { var valueMap = values[i]; timeline.setFrame(frameIndex, valueMap["time"], valueMap[field] || false); frameIndex++; @@ -2025,14 +2287,16 @@ } var ikMap = map["ik"]; - for (var ikConstraintName in ikMap) { + for (var ikConstraintName in ikMap) + { if (!ikMap.hasOwnProperty(ikConstraintName)) continue; var ikConstraint = skeletonData.findIkConstraint(ikConstraintName); var values = ikMap[ikConstraintName]; var timeline = new spine.IkConstraintTimeline(values.length); timeline.ikConstraintIndex = skeletonData.ikConstraints.indexOf(ikConstraint); var frameIndex = 0; - for (var i = 0, n = values.length; i < n; i++) { + for (var i = 0, n = values.length; i < n; i++) + { var valueMap = values[i]; var mix = valueMap.hasOwnProperty("mix") ? valueMap["mix"] : 1; var bendDirection = (!valueMap.hasOwnProperty("bendPositive") || valueMap["bendPositive"]) ? 1 : -1; @@ -2045,13 +2309,16 @@ } var ffd = map["ffd"]; - for (var skinName in ffd) { + for (var skinName in ffd) + { var skin = skeletonData.findSkin(skinName); var slotMap = ffd[skinName]; - for (slotName in slotMap) { + for (slotName in slotMap) + { var slotIndex = skeletonData.findSlotIndex(slotName); var meshMap = slotMap[slotName]; - for (var meshName in meshMap) { + for (var meshName in meshMap) + { var values = meshMap[meshName]; var timeline = new spine.FfdTimeline(values.length); var attachment = skin.getAttachment(slotIndex, meshName); @@ -2067,13 +2334,16 @@ vertexCount = attachment.weights.length / 3 * 2; var frameIndex = 0; - for (var i = 0, n = values.length; i < n; i++) { + for (var i = 0, n = values.length; i < n; i++) + { var valueMap = values[i]; var vertices; - if (!valueMap["vertices"]) { + if (!valueMap["vertices"]) + { if (isMesh) vertices = attachment.vertices; - else { + else + { vertices = []; vertices.length = vertexCount; } @@ -2083,14 +2353,16 @@ vertices.length = vertexCount; var start = valueMap["offset"] || 0; var nn = verticesValue.length; - if (this.scale == 1) { + if (this.scale == 1) + { for (var ii = 0; ii < nn; ii++) vertices[ii + start] = verticesValue[ii]; } else { for (var ii = 0; ii < nn; ii++) vertices[ii + start] = verticesValue[ii] * this.scale; } - if (isMesh) { + if (isMesh) + { var meshVertices = attachment.vertices; for (var ii = 0, nn = vertices.length; ii < nn; ii++) vertices[ii] += meshVertices[ii]; @@ -2109,14 +2381,17 @@ var drawOrderValues = map["drawOrder"]; if (!drawOrderValues) drawOrderValues = map["draworder"]; - if (drawOrderValues) { + if (drawOrderValues) + { var timeline = new spine.DrawOrderTimeline(drawOrderValues.length); var slotCount = skeletonData.slots.length; var frameIndex = 0; - for (var i = 0, n = drawOrderValues.length; i < n; i++) { + for (var i = 0, n = drawOrderValues.length; i < n; i++) + { var drawOrderMap = drawOrderValues[i]; var drawOrder = null; - if (drawOrderMap["offsets"]) { + if (drawOrderMap["offsets"]) + { drawOrder = []; drawOrder.length = slotCount; for (var ii = slotCount - 1; ii >= 0; ii--) @@ -2125,7 +2400,8 @@ var unchanged = []; unchanged.length = slotCount - offsets.length; var originalIndex = 0, unchangedIndex = 0; - for (var ii = 0, nn = offsets.length; ii < nn; ii++) { + for (var ii = 0, nn = offsets.length; ii < nn; ii++) + { var offsetMap = offsets[ii]; var slotIndex = skeletonData.findSlotIndex(offsetMap["slot"]); if (slotIndex == -1) throw "Slot not found: " + offsetMap["slot"]; @@ -2149,10 +2425,12 @@ } var events = map["events"]; - if (events) { + if (events) + { var timeline = new spine.EventTimeline(events.length); var frameIndex = 0; - for (var i = 0, n = events.length; i < n; i++) { + for (var i = 0, n = events.length; i < n; i++) + { var eventMap = events[i]; var eventData = skeletonData.findEvent(eventMap["name"]); if (!eventData) throw "Event not found: " + eventMap["name"]; @@ -2168,7 +2446,8 @@ skeletonData.animations.push(new spine.Animation(name, timelines, duration)); }, - readCurve: function (timeline, frameIndex, valueMap) { + readCurve: function (timeline, frameIndex, valueMap) + { var curve = valueMap["curve"]; if (!curve) timeline.curves.setLinear(frameIndex); @@ -2177,15 +2456,18 @@ else if (curve instanceof Array) timeline.curves.setCurve(frameIndex, curve[0], curve[1], curve[2], curve[3]); }, - toColor: function (hexString, colorIndex) { + toColor: function (hexString, colorIndex) + { if (hexString.length != 8) throw "Color hexidecimal length must be 8, recieved: " + hexString; return parseInt(hexString.substring(colorIndex * 2, (colorIndex * 2) + 2), 16) / 255; }, - getFloatArray: function (map, name, scale) { + getFloatArray: function (map, name, scale) + { var list = map[name]; var values = new spine.Float32Array(list.length); var i = 0, n = list.length; - if (scale == 1) { + if (scale == 1) + { for (; i < n; i++) values[i] = list[i]; } else { @@ -2194,7 +2476,8 @@ } return values; }, - getIntArray: function (map, name) { + getIntArray: function (map, name) + { var list = map[name]; var values = new spine.Uint16Array(list.length); for (var i = 0, n = list.length; i < n; i++) @@ -2203,7 +2486,8 @@ } }; -spine.Atlas = function (atlasText, textureLoader) { +spine.Atlas = function (atlasText, textureLoader) +{ this.textureLoader = textureLoader; this.pages = []; this.regions = []; @@ -2212,17 +2496,20 @@ var tuple = []; tuple.length = 4; var page = null; - while (true) { + while (true) + { var line = reader.readLine(); if (line === null) break; line = reader.trim(line); if (!line.length) page = null; - else if (!page) { + else if (!page) + { page = new spine.AtlasPage(); page.name = line; - if (reader.readTuple(tuple) == 2) { // size is only optional for an atlas packed with an old TexturePacker. + if (reader.readTuple(tuple) == 2) + { // size is only optional for an atlas packed with an old TexturePacker. page.width = parseInt(tuple[0]); page.height = parseInt(tuple[1]); reader.readTuple(tuple); @@ -2264,7 +2551,8 @@ region.u = x / page.width; region.v = y / page.height; - if (region.rotate) { + if (region.rotate) + { region.u2 = (x + height) / page.width; region.v2 = (y + width) / page.height; } else { @@ -2276,10 +2564,12 @@ region.width = Math.abs(width); region.height = Math.abs(height); - if (reader.readTuple(tuple) == 4) { // split is optional + if (reader.readTuple(tuple) == 4) + { // split is optional region.splits = [parseInt(tuple[0]), parseInt(tuple[1]), parseInt(tuple[2]), parseInt(tuple[3])]; - if (reader.readTuple(tuple) == 4) { // pad is optional, but only present with splits + if (reader.readTuple(tuple) == 4) + { // pad is optional, but only present with splits region.pads = [parseInt(tuple[0]), parseInt(tuple[1]), parseInt(tuple[2]), parseInt(tuple[3])]; reader.readTuple(tuple); @@ -2300,25 +2590,30 @@ } }; spine.Atlas.prototype = { - findRegion: function (name) { + findRegion: function (name) + { var regions = this.regions; for (var i = 0, n = regions.length; i < n; i++) if (regions[i].name == name) return regions[i]; return null; }, - dispose: function () { + dispose: function () + { var pages = this.pages; for (var i = 0, n = pages.length; i < n; i++) this.textureLoader.unload(pages[i].rendererObject); }, - updateUVs: function (page) { + updateUVs: function (page) + { var regions = this.regions; - for (var i = 0, n = regions.length; i < n; i++) { + for (var i = 0, n = regions.length; i < n; i++) + { var region = regions[i]; if (region.page != page) continue; region.u = region.x / page.width; region.v = region.y / page.height; - if (region.rotate) { + if (region.rotate) + { region.u2 = (region.x + region.height) / page.width; region.v2 = (region.y + region.width) / page.height; } else { @@ -2355,7 +2650,8 @@ repeat: 2 }; -spine.AtlasPage = function () {}; +spine.AtlasPage = function () +{}; spine.AtlasPage.prototype = { name: null, format: null, @@ -2368,7 +2664,8 @@ height: 0 }; -spine.AtlasRegion = function () {}; +spine.AtlasRegion = function () +{}; spine.AtlasRegion.prototype = { page: null, name: null, @@ -2383,31 +2680,37 @@ pads: null }; -spine.AtlasReader = function (text) { +spine.AtlasReader = function (text) +{ this.lines = text.split(/\r\n|\r|\n/); }; spine.AtlasReader.prototype = { index: 0, - trim: function (value) { + trim: function (value) + { return value.replace(/^\s+|\s+$/g, ""); }, - readLine: function () { + readLine: function () + { if (this.index >= this.lines.length) return null; return this.lines[this.index++]; }, - readValue: function () { + readValue: function () + { var line = this.readLine(); var colon = line.indexOf(":"); if (colon == -1) throw "Invalid line: " + line; return this.trim(line.substring(colon + 1)); }, /** Returns the number of tuple values read (1, 2 or 4). */ - readTuple: function (tuple) { + readTuple: function (tuple) + { var line = this.readLine(); var colon = line.indexOf(":"); if (colon == -1) throw "Invalid line: " + line; var i = 0, lastMatch = colon + 1; - for (; i < 3; i++) { + for (; i < 3; i++) + { var comma = line.indexOf(",", lastMatch); if (comma == -1) break; tuple[i] = this.trim(line.substr(lastMatch, comma - lastMatch)); @@ -2418,11 +2721,13 @@ } }; -spine.AtlasAttachmentLoader = function (atlas) { +spine.AtlasAttachmentLoader = function (atlas) +{ this.atlas = atlas; }; spine.AtlasAttachmentLoader.prototype = { - newRegionAttachment: function (skin, name, path) { + newRegionAttachment: function (skin, name, path) + { var region = this.atlas.findRegion(path); if (!region) throw "Region not found in atlas: " + path + " (region attachment: " + name + ")"; var attachment = new spine.RegionAttachment(name); @@ -2436,7 +2741,8 @@ attachment.regionOriginalHeight = region.originalHeight; return attachment; }, - newMeshAttachment: function (skin, name, path) { + newMeshAttachment: function (skin, name, path) + { var region = this.atlas.findRegion(path); if (!region) throw "Region not found in atlas: " + path + " (mesh attachment: " + name + ")"; var attachment = new spine.MeshAttachment(name); @@ -2454,7 +2760,8 @@ attachment.regionOriginalHeight = region.originalHeight; return attachment; }, - newSkinnedMeshAttachment: function (skin, name, path) { + newSkinnedMeshAttachment: function (skin, name, path) + { var region = this.atlas.findRegion(path); if (!region) throw "Region not found in atlas: " + path + " (skinned mesh attachment: " + name + ")"; var attachment = new spine.SkinnedMeshAttachment(name); @@ -2472,19 +2779,22 @@ attachment.regionOriginalHeight = region.originalHeight; return attachment; }, - newBoundingBoxAttachment: function (skin, name) { + newBoundingBoxAttachment: function (skin, name) + { return new spine.BoundingBoxAttachment(name); } }; -spine.SkeletonBounds = function () { +spine.SkeletonBounds = function () +{ this.polygonPool = []; this.polygons = []; this.boundingBoxes = []; }; spine.SkeletonBounds.prototype = { minX: 0, minY: 0, maxX: 0, maxY: 0, - update: function (skeleton, updateAabb) { + update: function (skeleton, updateAabb) + { var slots = skeleton.slots; var slotCount = slots.length; var x = skeleton.x, y = skeleton.y; @@ -2497,14 +2807,16 @@ polygonPool.push(polygons[i]); polygons.length = 0; - for (var i = 0; i < slotCount; i++) { + for (var i = 0; i < slotCount; i++) + { var slot = slots[i]; var boundingBox = slot.attachment; if (boundingBox.type != spine.AttachmentType.boundingbox) continue; boundingBoxes.push(boundingBox); var poolCount = polygonPool.length, polygon; - if (poolCount > 0) { + if (poolCount > 0) + { polygon = polygonPool[poolCount - 1]; polygonPool.splice(poolCount - 1, 1); } else @@ -2517,12 +2829,15 @@ if (updateAabb) this.aabbCompute(); }, - aabbCompute: function () { + aabbCompute: function () + { var polygons = this.polygons; var minX = Number.MAX_VALUE, minY = Number.MAX_VALUE, maxX = Number.MIN_VALUE, maxY = Number.MIN_VALUE; - for (var i = 0, n = polygons.length; i < n; i++) { + for (var i = 0, n = polygons.length; i < n; i++) + { var vertices = polygons[i]; - for (var ii = 0, nn = vertices.length; ii < nn; ii += 2) { + for (var ii = 0, nn = vertices.length; ii < nn; ii += 2) + { var x = vertices[ii]; var y = vertices[ii + 1]; minX = Math.min(minX, x); @@ -2537,11 +2852,13 @@ this.maxY = maxY; }, /** Returns true if the axis aligned bounding box contains the point. */ - aabbContainsPoint: function (x, y) { + aabbContainsPoint: function (x, y) + { return x >= this.minX && x <= this.maxX && y >= this.minY && y <= this.maxY; }, /** Returns true if the axis aligned bounding box intersects the line segment. */ - aabbIntersectsSegment: function (x1, y1, x2, y2) { + aabbIntersectsSegment: function (x1, y1, x2, y2) + { var minX = this.minX, minY = this.minY, maxX = this.maxX, maxY = this.maxY; if ((x1 <= minX && x2 <= minX) || (y1 <= minY && y2 <= minY) || (x1 >= maxX && x2 >= maxX) || (y1 >= maxY && y2 >= maxY)) return false; @@ -2557,12 +2874,14 @@ return false; }, /** Returns true if the axis aligned bounding box intersects the axis aligned bounding box of the specified bounds. */ - aabbIntersectsSkeleton: function (bounds) { + aabbIntersectsSkeleton: function (bounds) + { return this.minX < bounds.maxX && this.maxX > bounds.minX && this.minY < bounds.maxY && this.maxY > bounds.minY; }, /** Returns the first bounding box attachment that contains the point, or null. When doing many checks, it is usually more * efficient to only call this method if {@link #aabbContainsPoint(float, float)} returns true. */ - containsPoint: function (x, y) { + containsPoint: function (x, y) + { var polygons = this.polygons; for (var i = 0, n = polygons.length; i < n; i++) if (this.polygonContainsPoint(polygons[i], x, y)) return this.boundingBoxes[i]; @@ -2570,21 +2889,25 @@ }, /** Returns the first bounding box attachment that contains the line segment, or null. When doing many checks, it is usually * more efficient to only call this method if {@link #aabbIntersectsSegment(float, float, float, float)} returns true. */ - intersectsSegment: function (x1, y1, x2, y2) { + intersectsSegment: function (x1, y1, x2, y2) + { var polygons = this.polygons; for (var i = 0, n = polygons.length; i < n; i++) if (polygons[i].intersectsSegment(x1, y1, x2, y2)) return this.boundingBoxes[i]; return null; }, /** Returns true if the polygon contains the point. */ - polygonContainsPoint: function (polygon, x, y) { + polygonContainsPoint: function (polygon, x, y) + { var nn = polygon.length; var prevIndex = nn - 2; var inside = false; - for (var ii = 0; ii < nn; ii += 2) { + for (var ii = 0; ii < nn; ii += 2) + { var vertexY = polygon[ii + 1]; var prevY = polygon[prevIndex + 1]; - if ((vertexY < y && prevY >= y) || (prevY < y && vertexY >= y)) { + if ((vertexY < y && prevY >= y) || (prevY < y && vertexY >= y)) + { var vertexX = polygon[ii]; if (vertexX + (y - vertexY) / (prevY - vertexY) * (polygon[prevIndex] - vertexX) < x) inside = !inside; } @@ -2593,18 +2916,21 @@ return inside; }, /** Returns true if the polygon contains the line segment. */ - polygonIntersectsSegment: function (polygon, x1, y1, x2, y2) { + polygonIntersectsSegment: function (polygon, x1, y1, x2, y2) + { var nn = polygon.length; var width12 = x1 - x2, height12 = y1 - y2; var det1 = x1 * y2 - y1 * x2; var x3 = polygon[nn - 2], y3 = polygon[nn - 1]; - for (var ii = 0; ii < nn; ii += 2) { + for (var ii = 0; ii < nn; ii += 2) + { var x4 = polygon[ii], y4 = polygon[ii + 1]; var det2 = x3 * y4 - y3 * x4; var width34 = x3 - x4, height34 = y3 - y4; var det3 = width12 * height34 - height12 * width34; var x = (det1 * width34 - width12 * det2) / det3; - if (((x >= x3 && x <= x4) || (x >= x4 && x <= x3)) && ((x >= x1 && x <= x2) || (x >= x2 && x <= x1))) { + if (((x >= x3 && x <= x4) || (x >= x4 && x <= x3)) && ((x >= x1 && x <= x2) || (x >= x2 && x <= x1))) + { var y = (det1 * height34 - height12 * det2) / det3; if (((y >= y3 && y <= y4) || (y >= y4 && y <= y3)) && ((y >= y1 && y <= y2) || (y >= y2 && y <= y1))) return true; } @@ -2613,14 +2939,17 @@ } return false; }, - getPolygon: function (attachment) { + getPolygon: function (attachment) + { var index = this.boundingBoxes.indexOf(attachment); return index == -1 ? null : this.polygons[index]; }, - getWidth: function () { + getWidth: function () + { return this.maxX - this.minX; }, - getHeight: function () { + getHeight: function () + { return this.maxY - this.minY; } }; diff --git a/src/text/BitmapText.js b/src/text/BitmapText.js index e973630..d25f2cb 100644 --- a/src/text/BitmapText.js +++ b/src/text/BitmapText.js @@ -15,7 +15,8 @@ * @param style.font {string} The size (optional) and bitmap font id (required) eq 'Arial' or '20px Arial' (must have loaded previously) * @param [style.align='left'] {string} Alignment for multiline text ('left', 'center' or 'right'), does not affect single line text */ -function BitmapText(text, style) { +function BitmapText(text, style) +{ core.DisplayObjectContainer.call(this); /** @@ -89,10 +90,12 @@ * @memberof BitmapText# */ tint: { - get: function () { + get: function () + { return this._style.tint; }, - set: function (value) { + set: function (value) + { this._style.tint = (typeof value === 'number' && value >= 0) ? value : 0xFFFFFF; this.dirty = true; @@ -107,10 +110,12 @@ * @memberof BitmapText# */ align: { - get: function () { + get: function () + { return this._style.align; }, - set: function (value) { + set: function (value) + { this._style.align = value; this.dirty = true; @@ -124,10 +129,12 @@ * @memberof BitmapText# */ font: { - get: function () { + get: function () + { return this._style.font; }, - set: function (value) { + set: function (value) + { value = value.split(' '); // TODO - This should be object-based not string based like it has been. @@ -145,10 +152,12 @@ * @memberof BitmapText# */ text: { - get: function () { + get: function () + { return this._text; }, - set: function (value) { + set: function (value) + { this._text = value; this.dirty = true; @@ -161,7 +170,8 @@ * * @private */ -BitmapText.prototype.updateText = function () { +BitmapText.prototype.updateText = function () +{ var data = BitmapText.fonts[this.fontName]; var pos = new core.math.Point(); var prevCharCode = null; @@ -171,10 +181,12 @@ var line = 0; var scale = this.fontSize / data.size; - for (var i = 0; i < this.text.length; i++) { + for (var i = 0; i < this.text.length; i++) + { var charCode = this.text.charCodeAt(i); - if (/(?:\r\n|\r|\n)/.test(this.text.charAt(i))) { + if (/(?:\r\n|\r|\n)/.test(this.text.charAt(i))) + { lineWidths.push(pos.x); maxLineWidth = Math.max(maxLineWidth, pos.x); line++; @@ -187,11 +199,13 @@ var charData = data.chars[charCode]; - if (!charData) { + if (!charData) + { continue; } - if (prevCharCode && charData.kerning[prevCharCode]) { + if (prevCharCode && charData.kerning[prevCharCode]) + { pos.x += charData.kerning[prevCharCode]; } @@ -206,13 +220,16 @@ var lineAlignOffsets = []; - for (i = 0; i <= line; i++) { + for (i = 0; i <= line; i++) + { var alignOffset = 0; - if (this.style.align === 'right') { + if (this.style.align === 'right') + { alignOffset = maxLineWidth - lineWidths[i]; } - else if (this.style.align === 'center') { + else if (this.style.align === 'center') + { alignOffset = (maxLineWidth - lineWidths[i]) / 2; } @@ -223,13 +240,16 @@ var lenChars = chars.length; var tint = this.tint; - for (i = 0; i < lenChars; i++) { + for (i = 0; i < lenChars; i++) + { var c = i < lenChildren ? this.children[i] : this._pool.pop(); // get old child if have. if not - take from pool. - if (c) { + if (c) + { c.setTexture(chars[i].texture); // check if got one before. } - else { + else + { c = new core.Sprite(chars[i].texture); // if no create new one. } @@ -238,14 +258,16 @@ c.scale.x = c.scale.y = scale; c.tint = tint; - if (!c.parent) { + if (!c.parent) + { this.addChild(c); } } // remove unnecessary children. // and put their into the pool. - while(this.children.length > lenChars) { + while(this.children.length > lenChars) + { var child = this.getChildAt(this.children.length - 1); this._pool.push(child); this.removeChild(child); @@ -260,8 +282,10 @@ * * @private */ -BitmapText.prototype.updateTransform = function () { - if (this.dirty) { +BitmapText.prototype.updateTransform = function () +{ + if (this.dirty) + { this.updateText(); this.dirty = false; } diff --git a/src/text/Text.js b/src/text/Text.js index e89728f..e48e3c7 100644 --- a/src/text/Text.js +++ b/src/text/Text.js @@ -21,7 +21,8 @@ * @param [style.dropShadowAngle=Math.PI/4] {number} Set a angle of the drop shadow * @param [style.dropShadowDistance=5] {number} Set a distance of the drop shadow */ -function Text(text, style) { +function Text(text, style) +{ /** * The canvas element that everything is drawn to * @@ -60,15 +61,18 @@ * @memberof Text# */ width: { - get: function () { - if (this.dirty) { + get: function () + { + if (this.dirty) + { this.updateText(); this.dirty = false; } return this.scale.x * this.texture.frame.width; }, - set: function (value) { + set: function (value) + { this.scale.x = value / this.texture.frame.width; this._width = value; } @@ -81,15 +85,18 @@ * @memberof Text# */ height: { - get: function () { - if (this.dirty) { + get: function () + { + if (this.dirty) + { this.updateText(); this.dirty = false; } return this.scale.y * this.texture.frame.height; }, - set: function (value) { + set: function (value) + { this.scale.y = value / this.texture.frame.height; this._height = value; } @@ -112,7 +119,8 @@ * @param [style.dropShadowAngle=Math.PI/4] {number} Set a angle of the drop shadow * @param [style.dropShadowDistance=5] {number} Set a distance of the drop shadow */ -Text.prototype.setStyle = function (style) { +Text.prototype.setStyle = function (style) +{ style = style || {}; style.font = style.font || 'bold 20pt Arial'; style.fill = style.fill || 'black'; @@ -136,7 +144,8 @@ * * @param text {string} The copy that you would like the text to display */ -Text.prototype.setText = function (text) { +Text.prototype.setText = function (text) +{ this.text = text.toString() || ' '; this.dirty = true; }; @@ -146,7 +155,8 @@ * * @private */ -Text.prototype.updateText = function () { +Text.prototype.updateText = function () +{ this.texture.baseTexture.resolution = this.resolution; this.context.font = this.style.font; @@ -155,7 +165,8 @@ // word wrap // preserve original text - if (this.style.wordWrap) { + if (this.style.wordWrap) + { outputText = this.wordWrap(this.text); } @@ -166,14 +177,16 @@ var lineWidths = []; var maxLineWidth = 0; var fontProperties = this.determineFontProperties(this.style.font); - for (var i = 0; i < lines.length; i++) { + for (var i = 0; i < lines.length; i++) + { var lineWidth = this.context.measureText(lines[i]).width; lineWidths[i] = lineWidth; maxLineWidth = Math.max(maxLineWidth, lineWidth); } var width = maxLineWidth + this.style.strokeThickness; - if (this.style.dropShadow) { + if (this.style.dropShadow) + { width += this.style.dropShadowDistance; } @@ -183,7 +196,8 @@ var lineHeight = fontProperties.fontSize + this.style.strokeThickness; var height = lineHeight * lines.length; - if (this.style.dropShadow) { + if (this.style.dropShadow) + { height += this.style.dropShadowDistance; } @@ -191,7 +205,8 @@ this.context.scale( this.resolution, this.resolution); - if (navigator.isCocoonJS) { + if (navigator.isCocoonJS) + { this.context.clearRect(0, 0, this.canvas.width, this.canvas.height); } @@ -208,24 +223,29 @@ var linePositionX; var linePositionY; - if (this.style.dropShadow) { + if (this.style.dropShadow) + { this.context.fillStyle = this.style.dropShadowColor; var xShadowOffset = Math.cos(this.style.dropShadowAngle) * this.style.dropShadowDistance; var yShadowOffset = Math.sin(this.style.dropShadowAngle) * this.style.dropShadowDistance; - for (i = 0; i < lines.length; i++) { + for (i = 0; i < lines.length; i++) + { linePositionX = this.style.strokeThickness / 2; linePositionY = (this.style.strokeThickness / 2 + i * lineHeight) + fontProperties.ascent; - if (this.style.align === 'right') { + if (this.style.align === 'right') + { linePositionX += maxLineWidth - lineWidths[i]; } - else if (this.style.align === 'center') { + else if (this.style.align === 'center') + { linePositionX += (maxLineWidth - lineWidths[i]) / 2; } - if (this.style.fill) { + if (this.style.fill) + { this.context.fillText(lines[i], linePositionX + xShadowOffset, linePositionY + yShadowOffset); } @@ -237,22 +257,27 @@ this.context.fillStyle = this.style.fill; //draw lines line by line - for (i = 0; i < lines.length; i++) { + for (i = 0; i < lines.length; i++) + { linePositionX = this.style.strokeThickness / 2; linePositionY = (this.style.strokeThickness / 2 + i * lineHeight) + fontProperties.ascent; - if (this.style.align === 'right') { + if (this.style.align === 'right') + { linePositionX += maxLineWidth - lineWidths[i]; } - else if (this.style.align === 'center') { + else if (this.style.align === 'center') + { linePositionX += (maxLineWidth - lineWidths[i]) / 2; } - if (this.style.stroke && this.style.strokeThickness) { + if (this.style.stroke && this.style.strokeThickness) + { this.context.strokeText(lines[i], linePositionX, linePositionY); } - if (this.style.fill) { + if (this.style.fill) + { this.context.fillText(lines[i], linePositionX, linePositionY); } @@ -267,7 +292,8 @@ * * @private */ -Text.prototype.updateTexture = function () { +Text.prototype.updateTexture = function () +{ this.texture.baseTexture.width = this.canvas.width; this.texture.baseTexture.height = this.canvas.height; this.texture.crop.width = this.texture.frame.width = this.canvas.width; @@ -285,8 +311,10 @@ * * @param renderer {WebGLRenderer} */ -Text.prototype.renderWebGL = function (renderer) { - if (this.dirty) { +Text.prototype.renderWebGL = function (renderer) +{ + if (this.dirty) + { this.resolution = renderer.resolution; this.updateText(); @@ -301,8 +329,10 @@ * * @param renderer {CanvasRenderer} */ -Text.prototype.renderCanvas = function (renderer) { - if (this.dirty) { +Text.prototype.renderCanvas = function (renderer) +{ + if (this.dirty) + { this.resolution = renderer.resolution; this.updateText(); @@ -318,10 +348,12 @@ * @param fontStyle {object} * @private */ -Text.prototype.determineFontProperties = function (fontStyle) { +Text.prototype.determineFontProperties = function (fontStyle) +{ var properties = Text.fontPropertiesCache[fontStyle]; - if (!properties) { + if (!properties) + { properties = {}; var canvas = Text.fontPropertiesCanvas; @@ -357,17 +389,22 @@ var stop = false; // ascent. scan from top to bottom until we find a non red pixel - for (i = 0; i < baseline; i++) { - for (j = 0; j < line; j += 4) { - if (imagedata[idx + j] !== 255) { + for (i = 0; i < baseline; i++) + { + for (j = 0; j < line; j += 4) + { + if (imagedata[idx + j] !== 255) + { stop = true; break; } } - if (!stop) { + if (!stop) + { idx += line; } - else { + else + { break; } } @@ -378,17 +415,22 @@ stop = false; // descent. scan from bottom to top until we find a non red pixel - for (i = height; i > baseline; i--) { - for (j = 0; j < line; j += 4) { - if (imagedata[idx + j] !== 255) { + for (i = height; i > baseline; i--) + { + for (j = 0; j < line; j += 4) + { + if (imagedata[idx + j] !== 255) + { stop = true; break; } } - if (!stop) { + if (!stop) + { idx -= line; } - else { + else + { break; } } @@ -411,33 +453,40 @@ * @param text {string} * @private */ -Text.prototype.wordWrap = function (text) { +Text.prototype.wordWrap = function (text) +{ // Greedy wrapping algorithm that will wrap words as the line grows longer // than its horizontal bounds. var result = ''; var lines = text.split('\n'); - for (var i = 0; i < lines.length; i++) { + for (var i = 0; i < lines.length; i++) + { var spaceLeft = this.style.wordWrapWidth; var words = lines[i].split(' '); - for (var j = 0; j < words.length; j++) { + for (var j = 0; j < words.length; j++) + { var wordWidth = this.context.measureText(words[j]).width; var wordWidthWithSpace = wordWidth + this.context.measureText(' ').width; - if (j === 0 || wordWidthWithSpace > spaceLeft) { + if (j === 0 || wordWidthWithSpace > spaceLeft) + { // Skip printing the newline if it's the first word of the line that is // greater than the word wrap width. - if (j > 0) { + if (j > 0) + { result += '\n'; } result += words[j]; spaceLeft = this.style.wordWrapWidth - wordWidth; } - else { + else + { spaceLeft -= wordWidthWithSpace; result += ' ' + words[j]; } } - if (i < lines.length-1) { + if (i < lines.length-1) + { result += '\n'; } } @@ -450,8 +499,10 @@ * @param matrix {Matrix} the transformation matrix of the Text * @return {Rectangle} the framing rectangle */ -Text.prototype.getBounds = function (matrix) { - if (this.dirty) { +Text.prototype.getBounds = function (matrix) +{ + if (this.dirty) + { this.updateText(); this.dirty = false; } @@ -464,7 +515,8 @@ * * @param destroyBaseTexture {boolean} whether to destroy the base texture as well */ -Text.prototype.destroy = function (destroyBaseTexture) { +Text.prototype.destroy = function (destroyBaseTexture) +{ // make sure to reset the the context and canvas.. dont want this hanging around in memory! this.context = null; this.canvas = null;